All 48 libraries

SugarInput

Terminal escape sequence decoder

native PHP — semantics follow bubbletea input input foundation-package

SugarInput code coverage

The missing input layer for PHP TUI. EscapeDecoder consumes raw TTY bytes and emits typed Event objects — plain and legacy keys (including modified xterm forms), Kitty keyboard protocol, SGR 1006/1016 + urxvt 1015 + X10 mouse, focus events, bracketed paste, and a typed drain for terminal replies (DA, DSR/CPR, mode reports, Kitty flags). Reentrant and fuzz-friendly, chunk-invariant in the events it emits once deferTrailingEscape holds a lone ESC, with counters that make dropped or discarded input observable.

Install

composer require sugarcraft/sugar-input

Quickstart

use SugarCraft\Input\Driver\StreamInputDriver;
use SugarCraft\Input\Event\FocusEvent;
use SugarCraft\Input\Event\KeyEvent;
use SugarCraft\Input\Event\MouseEvent;
use SugarCraft\Input\Event\PasteEvent;
use SugarCraft\Input\Event\TerminalReplyEvent;

$driver = new StreamInputDriver(STDIN);

while (!$driver->isEof()) {
    $event = $driver->read();
    if ($event === null) {
        if (!$driver->hasPending()) {
            usleep(2_000); // nothing buffered — back off before polling again
        }
        continue;
    }

    match (true) {
        $event instanceof KeyEvent        => handleKey($event),
        $event instanceof MouseEvent      => handleMouse($event),
        $event instanceof PasteEvent      => handlePaste($event),
        $event instanceof FocusEvent      => handleFocus($event),
        $event instanceof TerminalReplyEvent => handleReply($event),
        default                           => handleOther($event),
    };
}

One termination caveat: isEof() means "ended and drained", not "ended". A stream that stops mid-sequence leaves the decoder holding a partial, so isEof() stays false and read() answers null forever — call escapeDecoder()->reset() (or bound the loop with a grace period) when shutdown must win over an unfinished frame.

Concepts

The lib is a byte decoder. It never reads the terminal and never writes to it. The host puts the terminal into raw mode and negotiates the mouse, paste, focus and Kitty modes, then hands the decoder the bytes the terminal sends. EscapeDecoder::decode() turns each complete sequence into one typed Event, and it buffers a partial sequence until the rest arrives, so the output does not depend on how the bytes were chunked when deferTrailingEscape is on. By default a read that ends on a lone ESC settles it as an Escape key at once, so a split right after a 0x1b byte can decode differently from a single call.

Each sequence belongs to one protocol family: legacy keys, Kitty keyboard, mouse, focus, bracketed paste, or a terminal reply. EscapeDecoderOptions switches families on and off. A frame from a disabled or unknown family is counted in droppedUnknownCount(), never decoded as a different key. Terminal replies, such as a cursor position report, are drained as TerminalReplyEvent values instead of being dropped.

Tasks

  • Read keys from a non-blocking stream. Build a StreamInputDriver over STDIN, call read() in a loop, and sleep briefly when it returns null with hasPending() false.
  • Put the terminal in the right shape first. Disable canonical mode and echo before decoding, for example with stty -icanon -echo or sugar-pty. Then enable the modes you need: ?1006 for mouse, ?2004 for bracketed paste, ?1004 for focus. The decoder never writes these itself.
  • Handle a Kitty key release. Check KeyEvent::isRelease(). Release events arrive with a Release prefix on the key name, and autorepeat frames set isRepeat and decode as presses.
  • Hold a trailing ESC until input goes idle. The default settles a lone ESC at once, as an immediate Escape key. Set deferTrailingEscape to hold it, then call flushDeferredEscape() on an input-idle timer.
  • Recover from an unterminated paste or partial frame. Call reset() on the decoder, or bound the loop with a grace period, so shutdown wins over an unfinished frame.
  • Resize without polling. Create a SignalResizeDriver, call arm() to install the SIGWINCH handler, and read ResizeEvent values from it. arm() returns false without ext-pcntl.

EscapeDecoder

EscapeDecoder::__construct(?EscapeDecoderOptions $options = null)Protocol toggles at construction; null uses the defaults.
EscapeDecoder::decode(string $bytes): list<Event>Decode a byte buffer — emits 0+ Events; buffers partial sequences.
EscapeDecoder::remainder(): stringGet unconsumed bytes that couldn't yet form a complete sequence.
EscapeDecoder::flushDeferredEscape(): list<Event>Settle a lone trailing ESC on an input-idle timer (with deferTrailingEscape).
EscapeDecoder::drainedReplyCount() / EscapeDecoder::droppedUnknownCount() / EscapeDecoder::discardedPasteBytes(): intCounters for terminal replies drained, frames refused, and bytes discarded after a paste overflow.
EscapeDecoder::reset(): voidClear every buffer — partials, paste state, string state. The recovery lever after an unterminated forged paste.

EscapeDecoderOptions

Five readonly booleans — enableMouse, enableKitty, enableFocus, enablePaste (all true by default) and deferTrailingEscape (false by default) — decide which protocol families the decoder interprets. A disabled family's frames are counted drops, never mis-decoded keys.

InputDriver

InputDriver::read(): ?EventReturn the next Event, or null when the non-blocking stream is idle or at EOF.

StreamInputDriver additionally answers isEof() and hasPending() — the null alone does not distinguish idle from ended — and both the stream and React drivers expose their owned decoder via escapeDecoder() for reset(), the flush helper, and the counters.

Event types

KeyEventkey, modifiers, raw, isRelease(), isRepeat — plain keys, F1-F24 legacy and up to F35 via Kitty, arrows, Home/End/PageUp/PageDown, Insert, Delete, Backspace, Tab, Enter, Escape, Ctrl+letter; Kitty releases arrive as ReleaseA (isRelease()), repeats as isRepeat
MouseEventx, y, button, action, modifiers — SGR 1006/1016, urxvt 1015 and X10: press, release, drag, scroll (buttons 96/97 up/down, 98/99 horizontal wheel); the constructor refuses any other action
FocusEventgained, raw — terminal window focus gained/lost (DECSET 1004)
PasteEventcontent, truncated, truncationNotice(): ?string — bracketed paste (CSI 200~ … CSI 201~); above the 1 MiB cap the announcement fires once and the overflow is discarded until the real terminator, never re-decoded as keys
TerminalReplyEventfamily, params, raw, body, truncated, is() — typed drain for device attributes, cursor position, DSR status, window reports, Kitty flags, mode reports, private CSI and string replies
ResizeEventcols, rows — produced by SignalResizeDriver after SIGWINCH (arm() opt-in)

KeyModifier

Modifiers arrive on events and are read with includes() / value(). The constants SHIFT, ALT, CTRL, META, SUPER, HYPER, CAPS_LOCK, NUM_LOCK document the wire bit layout the decoder maps from — Kitty lock-state bits arrive on the explicit-event-type form — and the constructor is private, so masks are not built by hand.

Configuration and options

OptionTypeDefaultEffect
enableMousebooltrueDecodes X10, urxvt 1015 and SGR 1006/1016 mouse frames. Disabled frames count as drops.
enableKittybooltrueDecodes Kitty keyboard protocol frames, including releases and repeats.
enableFocusbooltrueDecodes focus gained and lost reports (DECSET 1004).
enablePastebooltrueDecodes bracketed paste into PasteEvent, capped at 1 MiB.
deferTrailingEscapeboolfalseHolds a lone trailing ESC until flushDeferredEscape() settles it on input idle.

The options are readonly values passed to the EscapeDecoder constructor. A null argument uses the defaults. The options change parsing only. They do not turn modes on or off on the terminal, and the host still sends those sequences.

Keys and key names

Key events carry a symbolic key name, a KeyModifier bitmask and the raw bytes. Names cover literal characters, the arrows, Home, End, PageUp, PageDown, Insert, Delete, Backspace, Tab, Enter, Escape, and Ctrl plus a letter. Legacy function keys run from F1 to F24, and the Kitty protocol reaches F35. Modifiers are read with includes() and value(), and KeyModifier::none(), shift(), ctrl() and their combinations are the named constructors.

Mouse events carry x, y, button and action. X10 release frames report button 3, so match releases on action, not on the button index.

Theme and styling

Not applicable. This lib decodes input and draws nothing, so it has no theme, color or style surface. Rendering belongs to the host or to the output libraries, and the decoded events are plain PHP values.

Examples

examples/decode.php is an EscapeDecoder micro-demo. It feeds labeled byte frames through the decoder and prints each event: literal keys, legacy arrows, Kitty arrows and releases, modifyOtherKeys, SGR mouse, drained replies, focus, and a bracketed paste. The forged mouse frame is refused, so it prints a label and no event line. Every frame is written with explicit hex escapes, so the file survives editor and terminal mangling of control bytes. Run it with php examples/decode.php.

Testing

Run the suite from the lib root:

composer install && vendor/bin/phpunit

The suites cover the decoder and its options, each driver, the event classes, the modifier bitmask, the terminal-reply drain, and a key table parity check. Feed the decoder split byte streams in your own tests and compare the events. With deferTrailingEscape set, the emitted events should match a single-call decode, because the decoder is then chunk-invariant in its events. The paste overshoot counter is not: discardedPasteBytes() can differ by chunking, so do not assert counter parity across different splits. Under the default options, a split right after a 0x1b byte can emit an Escape key before the rest of the sequence arrives, so compare those boundaries with the option on.

Troubleshooting and FAQ

  • Arrow keys do not reach the decoder, or echo back as escape text. The terminal is still in canonical mode with echo on, so the bytes wait in the line buffer or echo to the screen. Disable ICANON and ECHO before decoding.
  • The loop never ends after the stream closes. isEof() means ended and drained. A stream that stops mid-sequence leaves a partial in the decoder, so call escapeDecoder()->reset() or bound the loop with a grace period.
  • A key from a Kitty-capable terminal is missing. Check droppedUnknownCount(). A frame from a disabled family, or an unknown one, is refused and counted, and the decoder never guesses at it.
  • Paste text is truncated. Paste above 1 MiB is clipped, and PasteEvent::truncated is true. The overflow is discarded and the announcement fires once. The overshoot past the cap in the read that crosses it is counted in discardedPasteBytes() at once, and bytes arriving after that are counted as they arrive; only a paste that crosses the cap and ends in the same read is truncated without any overshoot count.
  • Parameterized focus reports such as CSI 1;3I are ignored. This is intentional. Those forms are dropped, as xterm never sends them. 8-bit C1 controls are also not treated as sequence starts.
  • arm() returns false on Windows or without pcntl. SIGWINCH detection is POSIX-only and needs ext-pcntl. Without it, the resize driver is inert and the host must detect resizes some other way.

Upstream mapping

The decoding semantics follow the input handling in charmbracelet/bubbletea. The port is native PHP. The README and body describe the typed terminal-reply draining and the 1 MiB paste cap as additions beyond the upstream surface.

Concern (bubbletea input)SugarInput
Key message from raw bytesEscapeDecoder::decode() returning KeyEvent
Mouse messageMouseEvent (X10, 1006, 1015)
Paste messagePasteEvent, capped at 1 MiB
Focus messageFocusEvent
Terminal repliesTerminalReplyEvent, drained instead of dropped

Architecture

EscapeDecoder is the core. It holds the partial-sequence buffer, the paste state and the counters, and it applies the EscapeDecoderOptions family switches. The stream and React drivers wrap a source and call the decoder. StreamInputDriver reads a non-blocking stream. ReactInputDriver emits events from a ReactPHP readable stream. SignalResizeDriver turns SIGWINCH into ResizeEvent. StreamInputDriver and ReactInputDriver expose their owned decoder through escapeDecoder(), which is the seam for reset(), the flush helper and the counters. SignalResizeDriver holds no decoder, so it has no escapeDecoder(). Events are value classes in the Event namespace.

Two decoders exist in the fleet. sugar-input is the byte-level decoder used by sugar-readline, sugar-pty and the input-facing apps. sugar-core's InputReader runs on every sugar-core Program. A program should use one of them for its whole input path, not both.

Changelog and versioning

The package ships no CHANGELOG file. The commit history of sugar-input/ in the monorepo is the record of changes. The install line takes the monorepo's current release line.

Use it for

  • Real-TTY input — decode raw bytes instead of symbolic key names, on plain streams or ReactPHP loops.
  • Interactive TUI programs — keyboard and mouse input without depending on a specific runtime.
  • Kitty keyboard protocol — event frames CSI code;mods u, including key release events (released a arrives as ReleaseA); the flags query/reply uses the CSI ?…u shape and drains as a reply.
  • Safe paste handling — bracketed paste with a 1 MiB cap whose overflow is discarded, not replayed, so hostile input cannot forge keystrokes.
  • Foundation for any input-consuming lib — pure byte decoding with no event-loop requirement; drivers add stream/ReactPHP/pcntl plumbing.

Source & demos

Try the quickstart →

API

ClassMethodDescription
EscapeDecoder__construct(?EscapeDecoderOptions $options = null)Choose which protocol families decode
EscapeDecoderdecode(string $bytes): list<Event>Decode byte buffer, buffer partials
EscapeDecoderremainder(): stringGet unconsumed bytes
EscapeDecoderflushDeferredEscape(): list<Event>Settle a deferred lone ESC on input idle
EscapeDecoderdrainedReplyCount(): intTerminal replies drained as events
EscapeDecoderdroppedUnknownCount(): intFrames refused (unknown or disabled family), an incomplete sequence whose buffered tail passes the 128-byte cap, or an unterminated OSC/DCS string abandoned past its 64 KiB budget
EscapeDecoderdiscardedPasteBytes(): intPaste bytes discarded after a paste overflow (paste only, never sequences)
EscapeDecoderreset(): voidClear partial, paste and string state
StreamInputDriverread(): ?EventNext event from stream, or null (idle/EOF)
StreamInputDriverisEof(): bool / hasPending(): boolDistinguish ended-and-drained from idle
StreamInputDriverescapeDecoder(): EscapeDecoderSeam to the owned decoder (reset/counters/flush)
ReactInputDriveron('data'): eventsEmits decoded Events as they complete (event emitter, not a pull driver)
ReactInputDriverisReadable() / pause() / resume() / close()ReadableStreamInterface surface; pause buffers, resume flushes
ReactInputDriverpipe(WritableStreamInterface): WritableStreamInterfaceForwards raw bytes of the wrapped stream
ReactInputDriverescapeDecoder(): EscapeDecoderSeam to the owned decoder
SignalResizeDriverarm(): boolInstall the SIGWINCH handler; false without ext-pcntl (constructor is side-effect free)
SignalResizeDriverdisarm(): boolHand the process disposition back (previous handler, or SIG_DFL)
SignalResizeDriverread(): Event|ResizeEvent|nullInputDriver surface: returns a fresh ResizeEvent when a SIGWINCH landed since the last read, else null
KeyEventkey: stringSymbolic key name (releases: Release + capitalised name)
KeyEventmodifiers: KeyModifierModifier bitmask
KeyEventraw: stringRaw bytes that produced this event
KeyEventisRelease(): boolTrue for Kitty key-release events
KeyEventisRepeat: boolTrue for Kitty autorepeat frames (decode as press)
MouseEventx, y: intColumn and row (1-based; cells under 1000/1006, pixels under 1016 — the decoder keeps each field's first integer verbatim, units belong to the reporting mode)
MouseEventbutton: intButton index (0=left, 1=middle, 2=right; scroll 96=up, 97=down, 98=wheel-left, 99=wheel-right; X10 releases report 3 — match releases on action, not the button index)
MouseEventaction: stringpress | release | drag | scroll (constructor refuses anything else)
FocusEventgained: boolTrue if focus gained, false if lost
FocusEventraw: ?stringEscape sequence that produced the event
PasteEventcontent: stringPasted content (max 1 MiB)
PasteEventtruncated: boolTrue when content was clipped to the cap
PasteEventtruncationNotice(): ?stringLocalized one-liner explaining the clip, or null
TerminalReplyEventfamily: stringOne of the eight reply families (see FAMILIES)
TerminalReplyEventparams / paramsDropped / raw / body / truncatedParsed reply parameters (first MAX_PARAMS = 32 ride the event; the count the wire carried beyond the cap rides paramsDropped) and the bytes that carried them
TerminalReplyEventis(string $family): boolFamily check
ResizeEventcols, rows: intNew terminal dimensions
KeyModifiernone() / shift() / alt() / ctrl() / altShift() / ctrlShift() / altCtrl() / all()Named factories (memoized)
KeyModifierfromKittyInt() / fromSgrMouse() / fromXtermParam()Wire decoders for each protocol's modifier encoding
KeyModifierincludes(int $flag): boolCheck if flag (e.g. KeyModifier::SHIFT) is set
KeyModifierequals(KeyModifier $other): boolBitmask equality
KeyModifiervalue(): intRaw bitmask value

Only methods declared in sugar-input/src, or inherited from a parent declared there, are listed. A type that extends a class outside that tree, such as \RuntimeException, does not show the methods of that class.

SugarCraft\Input

EscapeDecoder final class

Terminal escape sequence decoder.

MethodSummary
__construct(?EscapeDecoderOptions $options = null)
decode(string $bytes): arrayDecode a byte buffer into zero or more Events.
remainder(): stringGet bytes that couldn't be consumed as part of a complete sequence.
drainedReplyCount(): intCount of unsolicited terminal replies drained into TerminalReplyEvent since the last reset() — the counters measure one decoder epoch, not a process lifetime. Distinguishes "recognized and drained" from the silent drops counted by droppedUnknownCount().
droppedUnknownCount(): intCount of complete-but-unrecognized sequences consumed with no event (unknown CSI finals, malformed runs, unknown Kitty key codes) since the last reset(); reset() clears it along with the state.
discardedPasteBytes(): intBytes of paste body swallowed past the 1 MiB cap while waiting for the paste's real 201~ terminator (the truncated PasteEvent announce fires once, at the cap). A forged paste that never sends the terminator keeps discarding — this counter grows monotonically and is the visible proof the tail became nothing rather than keys. reset() clears it along with the state.
flushDeferredEscape(): arrayResolve a lone trailing ESC deferred by the deferTrailingEscape option into the Escape key it (probably) was. Call from an application timer once no more input arrives within the escape-timeout window; if the buffered tail is exactly one ESC byte, clear it and return that KeyEvent. A held lone ESC P (no > followed) resolves the same way, to Alt+P.
reset(): voidClear the partial-sequence buffer, paste/string state, overflow-discard states, and reply counters. This is the host's recovery lever for a forged paste whose 201~ terminator never arrives (the decoder otherwise keeps discarding, by design, so no attacker byte can become a key).

EscapeDecoderOptions final class

Configuration options for EscapeDecoder protocol filtering.

Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.

MethodSummary
__construct(public readonly bool $enableMouse = true, public readonly bool $enableKitty = true, public readonly bool $enableFocus = true, public readonly bool $enablePaste = true, public readonly bool $deferTrailingEscape = false)
withMouse(bool $enabled = true): self
withKitty(bool $enabled = true): self
withFocus(bool $enabled = true): self
withPaste(bool $enabled = true): self
withTrailingEscapeDeferral(bool $deferred = true): self

Event interface

Marker interface for all input events produced by EscapeDecoder.

InputDriver interface

Contract for a pull-based source of decoded terminal events.

MethodSummary
read(): Event|nullRead and return the next input event, or null when none is available (EOF on a stream driver, no pending signal on the resize driver — each implementation documents which).

KeyModifier final class

Modifier key flags for keyboard and mouse events.

MethodSummary
static none(): selfNo modifiers held.
static alt(): selfAlt modifier.
static ctrl(): selfCtrl modifier.
static shift(): selfShift modifier.
static altShift(): selfAlt+Shift modifiers.
static ctrlShift(): selfCtrl+Shift modifiers.
static altCtrl(): selfAlt+Ctrl modifiers.
static shiftAltCtrl(): selfShift+Alt+Ctrl — the bits the legacy CSI wire forms can express.
static all(): self
static fromMask(int $mask): selfRebuild an instance from a stored mask value (the IPC/bridge seam for hosts that persisted value()). Refuses anything outside the defined bit union — a phantom bit fails fast at the boundary instead of travelling silently through the event stream.
static fromKittyInt(int $raw): selfBuild a modifier mask from a raw Kitty modifier bitmask (bits already de-based by the caller: the wire field is 1 + mask). Bit layout per the Kitty keyboard protocol: bit 0=Shift, bit 1=Alt, bit 2=Control, bit 3=Super, bit 4=Hyper, bit 5=Meta, bit 6=CapsLock, bit 7=NumLock.
static fromSgrMouse(int $raw): selfBuild a modifier mask from an SGR mouse modifier field. SGR uses: bit 0=Shift, bit 1=Alt, bit 2=Ctrl.
static fromXtermParam(int $xtermParam): selfBuild a modifier mask from an xterm modified-key parameter.
includes(int $flag): boolCheck if a specific modifier flag is set.
value(): intGet the raw bitmask value.
equals(self $other): bool

Lang final class

Per-library translation facade for sugar-input.

SugarCraft\Input\Driver

ReactInputDriver final class

ReactPHP-compatible input driver that wraps a ReadableStreamInterface.

Not listed: the methods of Evenement\EventEmitterTrait, a trait declared outside src/.

MethodSummary
__construct(private readonly ReadableStreamInterface $stream, ?EscapeDecoderOptions $options = null)
escapeDecoder(): EscapeDecoderThe decoder instance behind this driver — the seam for reset() after a forged unterminated paste and for the drop/drain counters.
isReadable(): boolChecks whether this stream is in a readable state.
pause(): voidPauses receiving data events.
resume(): voidResumes receiving data events.
pipe(\React\Stream\WritableStreamInterface $dest, array $options = []): \React\Stream\WritableStreamInterfacePipes the underlying byte stream into the given writable destination.
close(): voidCloses the stream and emits a 'close' event.

SignalResizeDriver final class

InputDriver that detects terminal resize events via SIGWINCH signals.

MethodSummary
__construct(?callable $commandRunner = null, ?callable $ttyProbe = null)
arm(): boolOpt in to the driver's process-global side effects.
disarm(): boolUndo arm() for this instance (m3: arming used to be a one-way door).
read(): Event|ResizeEvent|nullRead the next resize event, or null if no resize has been detected.

StreamInputDriver final class

InputDriver backed by a PHP stream resource (e.g. STDIN).

MethodSummary
__construct(private readonly mixed $stream, ?EscapeDecoderOptions $options = null)
__destruct()
escapeDecoder(): EscapeDecoderThe decoder instance behind this driver — the seam for hosts that need reset() after a forged unterminated paste, flushDeferredEscape() on an input-idle timer (with deferTrailingEscape), or the drop/drain counters.
isEof(): boolTrue once the stream has reached end-of-file AND every buffered and remainder event has been handed out.
hasPending(): boolTrue when more events are already decoded and waiting (driver buffer or decoder remainder) — distinguishes "keep pulling" from a true idle.
read(): Event|nullRead the next Event from the stream, or null when the non-blocking read found no data (also returned forever after EOF once buffers are drained).

SugarCraft\Input\Event

FocusEvent final readonly class

Focus event — terminal window gained or lost focus.

MethodSummary
__construct(public bool $gained, public ?string $raw = null)

KeyEvent final readonly class

A keyboard event — plain key or escape sequence decoded key.

MethodSummary
__construct(public string $key, public KeyModifier $modifiers, public string $raw, public bool $isRepeat = false)
isRelease(): boolTrue when this is a key RELEASE event: the name is the "Release" prefix followed by the press name with its first letter capitalised ("ReleaseA", "ReleaseArrowUp"). Only the Kitty protocol can report releases, so this is false for every other source.
static plain(string $char, ?KeyModifier $modifiers = null): selfA bare printable key: the character IS the event, so $raw defaults to $char and a null $modifiers means "no modifiers held" (KeyModifier::none() — PHP cannot default a parameter to a method call, hence the nullable).
static esc(string $key, ?KeyModifier $modifiers = null, string $raw = ''): selfA named key (ArrowUp, Enter, F5, ...). Null $modifiers means none held; empty $raw falls back to the bare ESC byte, which is honest only for Escape itself — callers with real wire bytes should pass them.

MouseEvent final readonly class

A mouse event (SGR 1006/1016, urxvt 1015, X10 1000).

MethodSummary
__construct(public int $x, public int $y, public int $button, public string $action, public KeyModifier $modifiers)
isScroll(): bool
static scrollUp(int $x, int $y, ?KeyModifier $modifiers = null): selfScroll up — wire button code 64 (SGR/X10), normalized to stored code 96.
static scrollDown(int $x, int $y, ?KeyModifier $modifiers = null): selfScroll down — wire button code 65 (SGR/X10), normalized to stored code 97.
static scrollLeft(int $x, int $y, ?KeyModifier $modifiers = null): selfHorizontal wheel left — wire button code 66 (SGR/X10), stored as 98.
static scrollRight(int $x, int $y, ?KeyModifier $modifiers = null): selfHorizontal wheel right — wire button code 67 (SGR/X10), stored as 99.

PasteEvent final readonly class

A bracketed paste event — content being pasted from the clipboard.

MethodSummary
__construct(string $content, bool $truncated = false)
static truncate(string $content): selfClip a paste to MAX_SIZE. Since the cap binds in the constructor this is a plain construction; the factory is kept for its name at call sites.
truncationNotice(): ?stringTranslated notice describing the cap, or null when the paste is intact.

ResizeEvent final readonly class

A terminal resize event (SIGWINCH).

MethodSummary
__construct(public int $cols, public int $rows)

TerminalReplyEvent final readonly class

A terminal REPLY that arrived unsolicited on the input stream.

MethodSummary
__construct(public string $family, array $params = [], public string $raw = '', public string $body = '', public bool $truncated = false)
is(string $family): bool

Security: decoded content is untrusted

Everything the decoder emits is attacker-writable input — any process that can write the pts slave, an injected tmux send-keys session, or whatever the clipboard held feeds the stream. Treat key names, PasteEvent::content, TerminalReplyEvent::body/params, and every raw field as hostile bytes: never echo decoded content straight back to the terminal (a crafted paste or reply body can carry OSC-8 hyperlinks and other introducers that command your renderer — sugar-core's Sanitize is the fleet's shared tool for the sweep), and never interpolate it into shell commands, paths, or logs without your own quoting and redaction discipline.

Two structural laws to design against. Bracketed paste fences are forgeable: CSI 200~/CSI 201~ are just bytes — use framing for convenience (bulk text without keymap side effects), never as an authenticity boundary between typed and pasted. Caps never reinterpret: a sequence that overflows its cap is refused with one counted drop (droppedUnknownCount()); paste bytes past the cap are discarded and counted by discardedPasteBytes() — the paste-only counter — as they arrive, and the overshoot of the cap-crossing read is included too, except when that same read carries the 201~ terminator: such a paste is truncated and its overshoot is not counted. Neither is ever pushed back into the stream for a second parse. The fleet's private-use-area arena (zone sentinels U+E000/U+E001, image markers from U+E002) passes through decoding byte-identical — the consumer that renders owns the sweep, with Sanitize::untrustedForMarkedFrames(); sugar-core's InputReader is a consumer that strips. The decoder's own caps contain parser resource use; they do not make the content trustworthy. The fleet-wide contract lives in docs/TRUST-BOUNDARY.md.

  • SugarReadline: line-editing and selection prompts for terminal UIs, one layer above raw key events.
  • SugarPty: pseudo-terminal primitives for hosting a program under a PTY.