SugarInput
Terminal escape sequence decoder
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, chunk-invariant, and fuzz-friendly, 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.
EscapeDecoder
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
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
ReleaseA (isRelease()), repeats as isRepeatKeyModifier
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.
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 (releasedaarrives asReleaseA); the flags query/reply uses theCSI ?…ushape 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
- Source on GitHub
- Full README
- Test suite
- examples/decode.php — labeled frames decoded to events, in the terminal
- Native PHP — decoding semantics follow charmbracelet/bubbletea's input handling.
API
| Class | Method | Description |
|---|---|---|
| EscapeDecoder | __construct(?EscapeDecoderOptions $options = null) | Choose which protocol families decode |
| EscapeDecoder | decode(string $bytes): list<Event> | Decode byte buffer, buffer partials |
| EscapeDecoder | remainder(): string | Get unconsumed bytes |
| EscapeDecoder | flushDeferredEscape(): list<Event> | Settle a deferred lone ESC on input idle |
| EscapeDecoder | drainedReplyCount(): int | Terminal replies drained as events |
| EscapeDecoder | droppedUnknownCount(): int | Frames refused (unknown or disabled family) |
| EscapeDecoder | discardedPasteBytes(): int | Bytes discarded after a paste overflow |
| EscapeDecoder | reset(): void | Clear partial, paste and string state |
| StreamInputDriver | read(): ?Event | Next event from stream, or null (idle/EOF) |
| StreamInputDriver | isEof(): bool / hasPending(): bool | Distinguish ended-and-drained from idle |
| StreamInputDriver | escapeDecoder(): EscapeDecoder | Seam to the owned decoder (reset/counters/flush) |
| ReactInputDriver | on('data'): events | Emits decoded Events as they complete (event emitter, not a pull driver) |
| ReactInputDriver | isReadable() / pause() / resume() / close() | ReadableStreamInterface surface; pause buffers, resume flushes |
| ReactInputDriver | pipe(WritableStreamInterface): WritableStreamInterface | Forwards raw bytes of the wrapped stream |
| ReactInputDriver | escapeDecoder(): EscapeDecoder | Seam to the owned decoder |
| SignalResizeDriver | arm(): bool | Install the SIGWINCH handler; false without ext-pcntl (constructor is side-effect free) |
| SignalResizeDriver | disarm(): bool | Hand the process disposition back (previous handler, or SIG_DFL) |
| SignalResizeDriver | read(): Event|ResizeEvent|null | InputDriver surface: returns a fresh ResizeEvent when a SIGWINCH landed since the last read, else null |
| KeyEvent | key: string | Symbolic key name (releases: Release + capitalised name) |
| KeyEvent | modifiers: KeyModifier | Modifier bitmask |
| KeyEvent | raw: string | Raw bytes that produced this event |
| KeyEvent | isRelease(): bool | True for Kitty key-release events |
| KeyEvent | isRepeat: bool | True for Kitty autorepeat frames (decode as press) |
| MouseEvent | x, y: int | Column 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) |
| MouseEvent | button: int | Button 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) |
| MouseEvent | action: string | press | release | drag | scroll (constructor refuses anything else) |
| FocusEvent | gained: bool | True if focus gained, false if lost |
| FocusEvent | raw: ?string | Escape sequence that produced the event |
| PasteEvent | content: string | Pasted content (max 1 MiB) |
| PasteEvent | truncated: bool | True when content was clipped to the cap |
| PasteEvent | truncationNotice(): ?string | Localized one-liner explaining the clip, or null |
| TerminalReplyEvent | family: string | One of the eight reply families (see FAMILIES) |
| TerminalReplyEvent | params / paramsDropped / raw / body / truncated | Parsed 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 |
| TerminalReplyEvent | is(string $family): bool | Family check |
| ResizeEvent | cols, rows: int | New terminal dimensions |
| KeyModifier | none() / shift() / alt() / ctrl() / altShift() / ctrlShift() / altCtrl() / all() | Named factories (memoized) |
| KeyModifier | fromKittyInt() / fromSgrMouse() / fromXtermParam() | Wire decoders for each protocol's modifier encoding |
| KeyModifier | includes(int $flag): bool | Check if flag (e.g. KeyModifier::SHIFT) is set |
| KeyModifier | equals(KeyModifier $other): bool | Bitmask equality |
| KeyModifier | value(): int | Raw bitmask value |
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. 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.