ADR 0002: Sans-I/O layering, Profile/Policy/Limits separation, and closed Events¶
Status¶
Accepted. 2026-11-21.
Context¶
A virtual terminal package serves four audiences with competing ergonomic and performance requirements:
One-line script and CLI callers that want rendered plain text or ANSI-stripped text from a
bytescapture (libvt.render(raw)/libvt.strip(raw)) without instantiating classes.Deterministic unit tests (
term = Terminal(rows=24, cols=80); term.feed(raw)) that inspectterm.text,term[row, col], andterm.cursorwith zero file descriptors, sockets, clocks, or threads.Interactive PTY harnesses (
tmux attach-session, shells, full-screen TUIs) that must flush bidirectional capability replies (DA1,DA2,XTVERSION,DSR,DECRQM,DECRQSS,XTGETTCAP,OSC 7501 ; ?,CSI ? u) back to the child PTY while blocking untrusted sequences from exfiltrating clipboard data or window titles.Protocol tools and host integrators that subscribe to structured side effects (
Bell,TitleChanged,WorkingDirectoryChanged,ClipboardWrite,PromptMark,ProgramStatusChanged,SixelGraphic,KittyGraphic,ScreenErased) with exhaustive static type narrowing.
Three anti-patterns surfaced when evaluating candidate designs:
Returning
list[Effect]orUpdatefrom everyfeed()call: Allocates wrapper lists/objects on 100% of chunks even when callers only inspect grid state at quiescence, and encourages callers to treat arbitraryos.read()chunk cuts as semantic transaction boundaries.Mixing security policy booleans and event callbacks on a single
Effectsbag, or exposingActionSinkmethods (on_print,on_csi,on_osc) publicly onTerminal: Confuses IDE autocompletion between internal parser dispatch methods and host event hooks.Splitting every CSI/OSC sequence into ~40 micro-modules and dispatching hot-path
feed()via boxedToken->Commanddataclasses: Inflates import time and object allocation on SGR/cursor-heavy streams.
Decision¶
Organize libvt as a flat ~15-module Sans-I/O package with progressive
disclosure and explicit separation between terminal identity (Profile),
security gates (Policy), resource bounds (Limits), outbound wire replies
(drain_replies()), and semantic host events (Event):
Progressive-disclosure entry points (
libvt):Level 0 pure helpers:
render(data, *, rows=24, cols=80) -> str,strip(data) -> str, andexplain(data) -> tuple[ExplainedSpan, ...].Level 1 stateful facade:
Terminal(*, rows=24, cols=80, ...).Level 2 standalone building blocks:
Parser,parse_sgr,encode_input,Formatter,AsyncTerminalStream,open_pty, andassert_screen.
Three immutable configuration objects (
libvt.config):Profile: Terminal identity and compatibility behavior (name,da1,da2,xtversion,osc_7501_capabilities,color_scheme,fg_rgb,bg_rgb,pending_wrap_phantom_col,vs15_narrows_wide_emoji,vs16_always_wide,tmux_window_rename), with presetsDEFAULT_PROFILE,XTERM_PROFILE, andTMUX_PROFILE.Policy: Default-deny host security gates (allow_title_report=False,allow_checksum_report=False,allow_clipboard_read=False,allow_clipboard_write=True,allow_color_queries=True,allow_program_status_query=True,allow_unsafe_uris=False,allow_passthrough=False,abort_dispatch_osc=False,osc7_hosts=None,strict=False) plusTMUX_CAPTURE_POLICY.Limits: Hard memory and CPU bounds (max_grapheme_codepoints=32,max_csi_params=32,max_osc_bytes=131_072,max_dcs_bytes=8_388_608,max_apc_bytes=4_194_304,max_reply_bytes=65_536,max_rep_count=4_096,max_prompt_zones=1_024,max_status_records=256,max_events=4_096,max_event_bytes=16_777_216,max_keyboard_stack=8).
Zero-allocation hot path with private
_TerminalSink:Terminal.feed(data, /) -> Nonemutates terminal state in place through an internal_TerminalSinkpassed toParser.feed_to(). PublicTerminalattributes contain noon_print/on_csiplumbing methods.Outbound wire replies accumulate in a
Limits.max_reply_bytes-boundedbytearraydrained viaterm.drain_replies() -> bytes(or forwarded viaon_pty_writewhen attached).
Closed algebraic
Eventunion (libvt.events):type Event = Bell | TitleChanged | WindowRenamed | WorkingDirectoryChanged | ClipboardWrite | PromptMark | ProgramStatusChanged | RenderHoldChanged | ColorSchemeQueried | InBandResize | SixelGraphic | KittyGraphic | ScreenErased | Passthrough | UnhandledSequence.Callers either pass
on_event: Callable[[Event], None](push) or setrecord_events: bool = Trueand callterm.drain_events() -> tuple[Event, ...](pull). When neither is enabled,feed()allocates zeroEventobjects.
Alternatives considered¶
feed(data) -> list[Effect]orfeed(data) -> Update: Rejected because allocating return containers on everyos.read()chunk penalizes the 95% case where callers inspectterm.textorterm.committedafter feeding.Two-object
Screen+Stream(screen)split: Rejected because sans-I/O reply generation (DA1,DSR,DECRQM), dual-screen mode reconciliation, and?2026held snapshots span parser dispatch and screen state together.40+ file per-sequence subpackage hierarchy: Rejected per
AGENTS.mdfile-boundary rules; keeping ~15 cohesive modules preserves fast imports and direct dispatch.
Consequences¶
Positive¶
Callers match
Eventexhaustively (case _: t.assert_never(ev)) underty,mypy, andpyright.Policy,Profile, andLimitsseparate security review from capability emulation and DoS budgets.Terminalkeeps a small, discoverable method surface without leaking parser sink callbacks.
Tradeoffs¶
Callers wanting pull-based event inspection pass
record_events=True(or anon_eventcallback) instead of receiving events implicitly fromfeed().
Risks¶
Event queue growth when
record_events=Trueanddrain_events()is never called. Mitigation: store buffered events in acollections.dequebounded byLimits.max_events.