# libvt.aio Source: https://libvt.git-pull.com/api/aio/ # `libvt.aio` ```{eval-rst} .. automodule:: libvt.aio :members: ``` --- # libvt.codec Source: https://libvt.git-pull.com/api/codec/ # `libvt.codec` ```{eval-rst} .. automodule:: libvt.codec :members: ``` --- # libvt.config Source: https://libvt.git-pull.com/api/config/ # `libvt.config` ```{eval-rst} .. automodule:: libvt.config :members: ``` --- # libvt.events Source: https://libvt.git-pull.com/api/events/ # `libvt.events` ```{eval-rst} .. automodule:: libvt.events :members: ``` --- # libvt.exc Source: https://libvt.git-pull.com/api/exc/ # `libvt.exc` ```{eval-rst} .. automodule:: libvt.exc :members: ``` --- # libvt.graphics Source: https://libvt.git-pull.com/api/graphics/ # `libvt.graphics` ```{eval-rst} .. automodule:: libvt.graphics :members: ``` --- # API Reference Source: https://libvt.git-pull.com/api/ (api)= (reference)= # API Reference Public modules and types shipped by `libvt`. ::::{grid} 1 1 2 2 :gutter: 2 2 3 3 :::{grid-item-card} `libvt` :link: libvt :link-type: doc Top-level re-exports, progressive-disclosure helpers, and package metadata. ::: :::{grid-item-card} `libvt.terminal` :link: terminal :link-type: doc `Terminal`, `Snapshot`, `Formatter`, `FlightRecorder`, `render`, and `strip`. ::: :::{grid-item-card} `libvt.screen` :link: screen :link-type: doc `Screen`, `ScreenSet`, `Cell`, `RowView`, `RowRun`, `RegionView`, and `Cursor`. ::: :::{grid-item-card} `libvt.parser` :link: parser :link-type: doc Streaming VT500 `Parser`, `CsiParams`, `Action` records, and `parse_sgr`. ::: :::{grid-item-card} `libvt.style` & `libvt.modes` :link: style :link-type: doc `Style`, `AnsiColor`, `IndexedColor`, `RgbColor`, `Hyperlink`, and DEC/ANSI `Mode`s. ::: :::{grid-item-card} `libvt.config`, `events`, & `status` :link: config :link-type: doc `Profile`, `Policy`, `Limits`, closed `Event` union, and `OSC 7501` `ProgramStatus`. ::: :::{grid-item-card} `libvt.input` & `libvt.codec` :link: input :link-type: doc Mode-aware `KeyEvent`, `MouseEvent`, `PasteEvent`, and VT sequence `explain`. ::: :::{grid-item-card} `libvt.aio`, `testing`, & `pytest_plugin` :link: aio :link-type: doc `AsyncTerminalStream`, POSIX `open_pty`, `assert_screen`, and `vt_*` fixtures. ::: :::{grid-item-card} `libvt.graphics` :link: graphics :link-type: doc Zero-dependency `SIXEL` and Kitty `APC G` `ImageMeta` and `ImagePlacement`. ::: :::{grid-item-card} `libvt.tmux` :link: tmux :link-type: doc `decode_tmux_capture`, `TmuxPaneMetadata`, and `-CC` `%output` unescaping. ::: :::: ## Policy and Guarantees ::::{grid} 1 2 3 3 :gutter: 2 :::{grid-item-card} Public API :link: ../project/public-api :link-type: doc What is and is not part of the public API. ::: :::{grid-item-card} Compatibility :link: ../project/compatibility :link-type: doc Supported Python versions and platforms. ::: :::{grid-item-card} Deprecations :link: ../project/deprecations :link-type: doc Active deprecations and migration guidance. ::: :::: ```{toctree} :hidden: :maxdepth: 1 libvt terminal screen parser style modes config events status input codec graphics tmux aio testing pytest_plugin exc ``` --- # libvt.input Source: https://libvt.git-pull.com/api/input/ # `libvt.input` ```{eval-rst} .. automodule:: libvt.input :members: ``` --- # libvt Source: https://libvt.git-pull.com/api/libvt/ # `libvt` ```{eval-rst} .. automodule:: libvt :members: :no-index: ``` --- # libvt.modes Source: https://libvt.git-pull.com/api/modes/ # `libvt.modes` ```{eval-rst} .. automodule:: libvt.modes :members: ``` --- # libvt.parser Source: https://libvt.git-pull.com/api/parser/ # `libvt.parser` ```{eval-rst} .. automodule:: libvt.parser :members: ``` --- # libvt.pytest_plugin Source: https://libvt.git-pull.com/api/pytest_plugin/ # `libvt.pytest_plugin` ```{eval-rst} .. automodule:: libvt.pytest_plugin :members: ``` --- # libvt.screen Source: https://libvt.git-pull.com/api/screen/ # `libvt.screen` ```{eval-rst} .. automodule:: libvt.screen :members: ``` --- # libvt.status Source: https://libvt.git-pull.com/api/status/ # `libvt.status` ```{eval-rst} .. automodule:: libvt.status :members: ``` --- # libvt.style Source: https://libvt.git-pull.com/api/style/ # `libvt.style` ```{eval-rst} .. automodule:: libvt.style :members: ``` --- # libvt.terminal Source: https://libvt.git-pull.com/api/terminal/ # `libvt.terminal` ```{eval-rst} .. automodule:: libvt.terminal :members: ``` --- # libvt.testing Source: https://libvt.git-pull.com/api/testing/ # `libvt.testing` ```{eval-rst} .. automodule:: libvt.testing :members: ``` --- # libvt.tmux Source: https://libvt.git-pull.com/api/tmux/ # `libvt.tmux` ```{eval-rst} .. automodule:: libvt.tmux :members: ``` --- # Changelog Source: https://libvt.git-pull.com/history/ (changes)= (changelog)= (history)= ```{currentmodule} libvt ``` ```{include} ../CHANGES ``` --- # libvt Source: https://libvt.git-pull.com/ (index)= # libvt Pure-Python, zero-dependency, typed virtual terminal emulator and streaming VT parser (`py3-none-any.whl` — no C shared library required). ::::{grid} 1 1 2 2 :gutter: 2 2 3 3 :::{grid-item-card} Quickstart :link: quickstart :link-type: doc Render VT streams, inspect cells, and write boxed screen assertions. ::: :::{grid-item-card} Topics :link: topics/index :link-type: doc Sans-I/O layering, RLE scrollback, `?2026` stepping, `OSC 7501`, and input encoding. ::: :::{grid-item-card} API Reference :link: api/index :link-type: doc Public modules, dataclasses, protocols, and `vt_*` pytest fixtures. ::: :::{grid-item-card} Project & ADRs :link: project/index :link-type: doc Contributing, code style, releases, and Architecture Decision Records `0001`–`0010`. ::: :::: ## Install ```console $ uv add libvt ``` ```console $ pip install libvt ``` `libvt` is pre-1.0; pin a minor range (`libvt>=0.1,<0.2`). ## At a glance ```python >>> import libvt >>> term = libvt.Terminal(rows=4, cols=20) >>> term.feed(b"\x1b[1;31mhello\x1b[0m \xe6\x97\xa5\xe6\x9c\xac") >>> term.text 'hello 日本' >>> term[0, 0].style.fg >>> term.cursor.row, term.cursor.col (0, 10) ``` ```{toctree} :hidden: quickstart topics/index api/index project/index history migration GitHub ``` --- # Migration notes Source: https://libvt.git-pull.com/migration/ (migration)= ```{currentmodule} libvt ``` ```{include} ../MIGRATION ``` --- # ADR 0001: Clean-room MIT provenance, PyPI namespace, and Python 3.12+ floor Source: https://libvt.git-pull.com/project/adr/0001-clean-room-provenance-and-license-firewall/ (adr-clean-room-provenance)= # ADR 0001: Clean-room MIT provenance, PyPI namespace, and Python 3.12+ floor ## Status Accepted. 2026-11-21. ## Context `libtmux` (`>= 3.11`), `tmuxp` (`>= 3.11`), and Python terminal test suites need an in-memory virtual terminal emulator and streaming VT parser without copyleft license obligations (`tmux-python/libtmux#886`). Existing pure-Python and GTK terminal libraries carry copyleft terms (`pyte` under `LGPL-3.0`, `libvte` under `LGPL-3.0`, and `asciinema`'s virtual terminal engine under `GPL-3.0-or-later`) and omit contemporary terminal extensions used by `tmux` and modern TUIs: DEC mode `?2026` synchronized output, DEC mode `?2027` Unicode grapheme clustering, ITU T.416 colon-delimited `SGR` subparameters (`4:3`, `38:2::R:G:B`, `58:2::R:G:B`), `OSC 8` hyperlinks, `OSC 133` semantic shell prompts, `OSC 7501` program status, Kitty keyboard stacks (`CSI u`), and `SIXEL` / Kitty graphics placement and erase tracking. Three packaging and runtime constraints govern the package boundary: 1. **Distribution and import name availability**: Candidate package names `pyvt` (`https://pypi.org/project/pyvt/`) and `vt` (`https://pypi.org/project/vt/`, also used as `import vt` by `vt-py`) are already registered on PyPI, whereas `libvt` is available and matches the `libtmux` / `libvcs` naming family. 2. **Python interpreter floor**: Raising `requires-python` to `>= 3.14` (to use stdlib `compression.zstd` or PEP 649 runtime semantics) would block adoption in `libtmux`, `tmuxp`, and downstream CI matrices running Python 3.12 and 3.13. 3. **Pure-Python wheel portability**: Shipping a mandatory C, Zig, or Rust extension complicates universal wheels, free-threaded CPython builds (`PYTHON_GIL=0`), PyPy, WebAssembly sandboxes, and offline CI runners. ## Decision `libvt` ships as a standalone, MIT-licensed, pure-Python (`py3-none-any.whl`) distribution under the `libvt` package and import name with `dependencies = []` and `requires-python = ">=3.12,<4.0"`: - **Clean-room license firewall**: Every parser transition, escape parameter rule, character-width table, and test vector is derived strictly from public standards (ECMA-48, DEC STD 070, ITU T.416, Paul Flo Williams' VT500 parser state diagram, Unicode UAX #11 and UAX #29) and permissively licensed (`MIT`, `ISC`, `Apache-2.0`, `BSD`) specifications and implementations (`tmux`, `ghostty` / `libghostty-vt`, `alacritty_terminal`, `wezterm` VT crates, `zellij`, `ratatui`, and the Rex `OSC 7501` specification). - **Copyleft quarantine**: Source code under `LGPL`, `GPL`, `AGPL`, or `MPL` (including `pyte`, `libvte`, `asciinema`, `fish-shell`, and `helix`) MUST never be read, translated, or copied when developing or testing `libvt`. - **Acyclic ecosystem dependency graph**: `stdlib -> libvt -> libtmux -> tmuxp`. `libvt` never imports `libtmux`. - **Zero-GIL thread safety**: Mutable parser and SGR memoization tables live on `Parser` / `Terminal` instances rather than unlocked module-global dictionaries so concurrent `Terminal` instances run without data races on free-threaded CPython (`3.13t` / `3.14t`). ## Alternatives considered | Candidate | License | PyPI name | Wheel | Python floor | Disqualifier or trade-off | |---|---|---|---|---|---| | `libvt` standalone pure-Python (chosen) | MIT | available | `py3-none-any.whl` | `>= 3.12` | Pure-Python CPU ceiling (~10-35 MiB/s vs SIMD native) | | `pyvt` / `vt` standalone naming | MIT | occupied | `py3-none-any.whl` | `>= 3.12` | Name collision on PyPI and `import vt` conflict | | Python `>= 3.14`-only pure-Python engine | MIT | occupied (`vt`) | `py3-none-any.whl` | `>= 3.14` | Excludes Python 3.12 and 3.13 consumers (`libtmux`, `tmuxp`) | | Inline helper inside `libtmux.test.vt` | MIT | n/a | `py3-none-any.whl` | `>= 3.11` | Unusable without installing `libtmux` | | Mandatory `libghostty-vt` C ABI FFI wheel | MIT | available | platform wheels | `>= 3.12` | Requires Zig build matrix; omits `SIXEL` | | Retain `pyte` | LGPL-3.0 | occupied | `py3-none-any.whl` | `>= 3.8` | Copyleft license; lacks `?2026`, `?1049`, colon SGR, `OSC 8/133/7501` | ## Consequences ### Positive - Downstream MIT, BSD, Apache-2.0, and proprietary consumers depend on `libvt` without copyleft review or native C/Zig/Rust toolchains. - Python 3.12, 3.13, 3.14, 3.15, and PyPy share a single `py3-none-any.whl` artifact. - Instance-local caches allow parallel test workers and free-threaded Python threads to drive separate `Terminal` instances concurrently. ### Tradeoffs - Pure-Python byte ingestion (`~10-35 MiB/s` on ASCII/ANSI streams) is slower than SIMD-accelerated native engines (`>100 MiB/s`), while still processing typical `80x24` TUI frames in well under a millisecond. ### Risks - Contributors consulting copyleft terminal emulators during bug fixes. Mitigation: state the quarantine in `AGENTS.md`, `.github/CONTRIBUTING.md`, and this ADR, and cite ECMA-48, DEC, `tmux`, or `ghostty` references in tests and commit messages. --- # ADR 0002: Sans-I/O layering, Profile/Policy/Limits separation, and closed Events Source: https://libvt.git-pull.com/project/adr/0002-sans-io-layers-profiles-and-closed-events/ (adr-sans-io-layers)= # 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: 1. **One-line script and CLI callers** that want rendered plain text or ANSI-stripped text from a `bytes` capture (`libvt.render(raw)` / `libvt.strip(raw)`) without instantiating classes. 2. **Deterministic unit tests** (`term = Terminal(rows=24, cols=80); term.feed(raw)`) that inspect `term.text`, `term[row, col]`, and `term.cursor` with zero file descriptors, sockets, clocks, or threads. 3. **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. 4. **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]` or `Update` from every `feed()` call**: Allocates wrapper lists/objects on 100% of chunks even when callers only inspect grid state at quiescence, and encourages callers to treat arbitrary `os.read()` chunk cuts as semantic transaction boundaries. - **Mixing security policy booleans and event callbacks on a single `Effects` bag**, or exposing `ActionSink` methods (`on_print`, `on_csi`, `on_osc`) publicly on `Terminal`: 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 boxed `Token` -> `Command` dataclasses**: 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`): 1. **Progressive-disclosure entry points (`libvt`)**: - Level 0 pure helpers: `render(data, *, rows=24, cols=80) -> str`, `strip(data) -> str`, and `explain(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`, and `assert_screen`. 2. **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 presets `DEFAULT_PROFILE`, `XTERM_PROFILE`, and `TMUX_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`) plus `TMUX_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`). 3. **Zero-allocation hot path with private `_TerminalSink`**: - `Terminal.feed(data, /) -> None` mutates terminal state in place through an internal `_TerminalSink` passed to `Parser.feed_to()`. Public `Terminal` attributes contain no `on_print` / `on_csi` plumbing methods. - Outbound wire replies accumulate in a `Limits.max_reply_bytes`-bounded `bytearray` drained via `term.drain_replies() -> bytes` (or forwarded via `on_pty_write` when attached). 4. **Closed algebraic `Event` union (`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 set `record_events: bool = True` and call `term.drain_events() -> tuple[Event, ...]` (pull). When neither is enabled, `feed()` allocates zero `Event` objects. ## Alternatives considered - **`feed(data) -> list[Effect]` or `feed(data) -> Update`**: Rejected because allocating return containers on every `os.read()` chunk penalizes the 95% case where callers inspect `term.text` or `term.committed` after feeding. - **Two-object `Screen` + `Stream(screen)` split**: Rejected because sans-I/O reply generation (`DA1`, `DSR`, `DECRQM`), dual-screen mode reconciliation, and `?2026` held snapshots span parser dispatch and screen state together. - **40+ file per-sequence subpackage hierarchy**: Rejected per `AGENTS.md` file-boundary rules; keeping ~15 cohesive modules preserves fast imports and direct dispatch. ## Consequences ### Positive - Callers match `Event` exhaustively (`case _: t.assert_never(ev)`) under `ty`, `mypy`, and `pyright`. - `Policy`, `Profile`, and `Limits` separate security review from capability emulation and DoS budgets. - `Terminal` keeps a small, discoverable method surface without leaking parser sink callbacks. ### Tradeoffs - Callers wanting pull-based event inspection pass `record_events=True` (or an `on_event` callback) instead of receiving events implicitly from `feed()`. ### Risks - Event queue growth when `record_events=True` and `drain_events()` is never called. Mitigation: store buffered events in a `collections.deque` bounded by `Limits.max_events`. --- # ADR 0003: Two-tier lazy packed viewport rows and RLE FrozenRow scrollback Source: https://libvt.git-pull.com/project/adr/0003-two-tier-packed-viewport-and-rle-scrollback/ (adr-two-tier-storage)= # ADR 0003: Two-tier lazy packed viewport rows and RLE FrozenRow scrollback ## Status Accepted. 2026-11-21. ## Context Grid and scrollback storage in pure Python faces three simultaneous traps: 1. **Object-per-cell heap blowup**: Representing a `10,000 x 80` scrollback buffer as `list[list[Cell]]` (800,000 frozen slotted dataclasses) consumes `56.46 MiB` of traced CPython 3.15 heap (`>130 MiB` without `__slots__`) and amplifies garbage-collection pause times. 2. **Pooled `StyleId` RGB leaks and `u16` overflows**: Designs that intern `Style` objects into a `StylePool` indexed by `array("I")` (`u32`) or `array("H")` (`u16`) break on 24-bit RGB (`SGR 38;2;r;g;b`) streams (`btop`, `chafa`, `timg`, smooth fades, or hostile PTYs). Without eviction, 16.7 million RGB combinations leak gigabytes of `Style` objects across `RIS`; with `array("H")` (`u16`), style `#65,536` (reached in `<50 ms` of `240x80` truecolor frames) raises `OverflowError` or requires expensive stop-the-world reference counting across active and historical cells. 3. **Unwritten-blank vs space vs wide-spacer ambiguity**: Using `""` for unwritten blank cells causes cursor jumps (`CSI 1;10 H` + `"OK"`) to collapse interior columns when joining cell text (`"OK"` instead of `" OK"`) and collides with `""` on wide-character `SPACER_TAIL` cells. Conversely, scanning backward across `" "` cells during `EL 0` (`CSI K`) must never erase explicit `" "` characters printed to the left of the erase start column. ## Decision Adopt a two-tier memory architecture that uses **inline 64-bit bit-packed attribute words** (zero `StylePool`) across both hot mutable viewport rows and cold run-length-encoded (`RLE`) scrollback lines: 1. **Hot viewport `_Row` (`libvt._grid`)**: - `chars: list[str]` of length `cols`: `" "` for narrow blank or erased cells, single-codepoint or multi-codepoint grapheme strings for printed cells, and `""` reserved strictly for `WidthRole.SPACER_TAIL` and `WidthRole.SPACER_HEAD`. - `used: int`: High-water column index (`0..cols`) of explicitly written or non-default `BCE`-erased content. `clear_range(lo, cols, bce_word=0)` clamps `used = min(used, lo)` without scanning left past `lo`, preserving explicit spaces printed left of `lo`. - **Lazy 64-bit `attrs`**: Starts as `attrs: array.array[int] | None = None` with scalar `uniform_attr: int = 0` and `has_wide: bool = False`. Plain default-styled ASCII writes slice-assign `chars[col:end] = list(seg)` with zero `array("Q")` allocation. On the first non-uniform style, wide glyph, protected attribute, or `HAS_EXT` cell, `_Row` promotes `attrs = array.array("Q", [uniform_attr]) * cols`. - **64-bit inline bit layout (`0` == blank default narrow unprotected cell)**: - bits `0..24` (`25`b): foreground color (`0` = default, `1..16` = `AnsiColor`, `256..511` = `IndexedColor(0..255)` keeping `0..15` distinct from `AnsiColor`, `(1 << 24) | 0xRRGGBB` = `RgbColor`). - bits `25..49` (`25`b): background color (same encoding). - bits `50..56` (`7`b): `bold`, `dim`, `italic`, `blink`, `reverse`, `hidden`, `strikethrough`. - bits `57..59` (`3`b): `UnderlineStyle` (`0..5`). - bits `60..61` (`2`b): `WidthRole` (`NARROW=0`, `WIDE=1`, `SPACER_TAIL=2`, `SPACER_HEAD=3`). - bit `62` (`1`b): `overline`. - bit `63` (`1`b): `HAS_EXT`, gating lazy `ext: dict[int, _CellExt] | None` holding `underline_color: Color`, `hyperlink: Hyperlink | None`, and `protected: bool` (`DECSCA`). 2. **Cold scrollback `FrozenRow` (`libvt._grid`) and `_Row` recycling**: - When `Screen.scroll_up` evicts a full-width top row into `history`, it seals the row into an immutable `FrozenRow(text: str, cols: int, runs: tuple[tuple[int, int], ...], exts: tuple[tuple[int, _CellExt], ...], wrapped: bool)` where `runs` stores `(end_col, attr_u64)` RLE spans (sharing a singleton `()` tuple when completely default-styled) and recycles the cleared `_Row` instance to the bottom of the viewport. - Measured on CPython 3.15.1 (`10,000 x 80` styled CLI log rows), `FrozenRow` RLE scrollback consumes `~2.66 MiB` vs `22.59 MiB` for cloned mutable `_Row`s (`8.5x` reduction) and `56.46 MiB` for `Cell` grids (`21.2x` reduction) — with zero `zstd` dependency and zero `StylePool` leak. 3. **Unified public `RowView`, `RowRun`, and `Cell` views (`libvt.screen`)**: - `RowView` wraps either a live `_Row` or a `FrozenRow`, exposing `.text`, `.wrapped`, `row[col] -> Cell` (returning `BLANK_CELL` when default), and `.runs -> tuple[RowRun, ...]` for `O(runs)` styled span rendering. - Primary scrollback stores `FrozenRow` records in `256`-row copy-on-write tuple blocks (`_FrozenHistory` / `_HistoryView`), so `Screen.history`, `Terminal.history`, and `Snapshot.history` satisfy `collections.abc.Sequence[RowView]` with `O(1)` snapshot capture and `O(1)` random row indexing without leaking mutable storage. ## Alternatives considered | Storage model | `10,000 x 80` heap (Py 3.15) | 24-bit RGB safety | Multi-codepoint graphemes | Verdict | |---|---|---|---|---| | Lazy 64-bit `_Row` + RLE `FrozenRow` (chosen) | `~2.66 MiB` | inline 64b (leak-free) | native `str` per cell | Adopted | | Uncompressed cloned `_Row` scrollback | `22.59 MiB` | inline 64b (leak-free) | native `str` per cell | `8.5x` heavier scrollback | | `array("I")` codepoint + `u32` `StylePool` | `11.04 MiB` + pool | leaks unbounded RGB styles | side-dict per cluster | OOM on RGB streams | | `CompactRow` `array("H")` `u16` `StyleId` | `~1.7-3.0 MiB` + pool | `OverflowError` at 65,536 styles | native `str` per cell | Crashes/corrupts on truecolor | | `list[list[Cell]]` grid | `56.46 MiB` | per-cell objects | native `str` per cell | High RAM and GC pressure | ## Consequences ### Positive - Truecolor animations (`16.7M` colors) allocate zero persistent style-table entries and never overflow 16-bit IDs. - Unstyled ASCII logs skip `array("Q")` allocation on active rows and compress to one `str` + shared empty tuple in scrollback, recycling `_Row` buffers on every scroll. - `IndexedColor(0..15)` (`SGR 38;5;0..15`) round-trips distinctly from `AnsiColor(0..15)` (`SGR 30..37`, `90..97`). ### Tradeoffs - Random cell indexing into `FrozenRow` (`history[i][col]`) performs a short tuple scan (`bisect` / linear over typically 1-6 RLE spans) rather than `O(1)` array indexing. ### Risks - Wide-character `WIDE` / `SPACER_TAIL` pairing corruption during `ICH` (`CSI @`) or `DCH` (`CSI P`). Mitigation: heal split wide pairs *after* or at the exact cut boundaries (`col` when `col` is `SPACER_TAIL`, and `right` when a shifted `WIDE` head loses its tail at the right margin), verified by 400+ randomized fuzz trials. --- # ADR 0004: Zero-based (row, col) coordinates, resize reflow, and ?2026 stepping Source: https://libvt.git-pull.com/project/adr/0004-zero-based-row-col-coordinates-and-sync-stepping/ (adr-coordinates-and-sync-stepping)= # ADR 0004: Zero-based (row, col) coordinates, resize reflow, and ?2026 stepping ## Status Accepted. 2026-11-21. ## Context Three coordinate and frame-lifecycle problems recur across terminal APIs: 1. **Axis inversion**: Legacy Python libraries pass `(cols, rows)` to constructors and `(x, y)` on cursors while indexing `screen[row][col]`, inverting horizontal and vertical axes between construction and indexing. 2. **Cursor allocation churn and `pending_wrap` edge cases**: Storing `Screen`'s live cursor as a frozen dataclass re-allocated on every character, `CR`, and `LF` consumed `28%` of total CPU in `cProfile` runs (`90,000+` allocations per `30,000` lines). In addition, `xterm`/`Ghostty` and `tmux` (`s->cx == sx` in `screen-write.c`) differ subtly when `CUB` (`CSI D`) or `BS` (`0x08`) arrives during `pending_wrap` at the right margin. 3. **Torn `?2026` frames, timer races, and resize reflow**: Eagerly cloning all 24 rows on every `CSI ? 2026 h` wastes work when `CSI ? 2026 l` arrives in the same `feed()` buffer, while untagged async timeouts clearing a held snapshot can clobber a *subsequent* `?2026` batch. On `resize()`, cropping rows without rejoining soft-wrapped (`wrapped=True`) primary lines breaks shell prompts and wrapped CLI output compared to `tmux` and `Ghostty`. ## Decision 1. **Universal 0-based `(row, col)` order**: - Every constructor, helper, and `resize()` method accepts keyword-only `(*, rows: int = 24, cols: int = 80)`. Zero `(col, row)` types exist in `libvt`; `Terminal.from_size(os.terminal_size)` converts `os.terminal_size` (`columns`, `lines`) explicitly. - `Screen` stores `_cur_row: int`, `_cur_col: int`, `_pending_wrap: bool`, `_cur_visible: bool`, `_cur_shape: CursorShape`, and `_cur_blinking: bool` as scalars on the hot path, materializing a frozen `Cursor` dataclass on demand in `@property def cursor`. - Indexing uses NumPy-style 2D syntax on `Terminal`, `Screen`, and `Snapshot`: `term[row] -> RowView`, `term[row, col] -> Cell`, and `term[r1:r2, c1:c2] -> RegionView` (supporting negative indices such as `term[-1]` for status lines). - `Profile.pending_wrap_phantom_col` + `Mode.REVERSE_WRAP` (`?45`) model both `xterm`/`Ghostty` (`DEFAULT_PROFILE`) and `tmux` (`TMUX_PROFILE`, where `pending_wrap` acts as phantom column `cols` on `CUB`/`BS` and `BS` at column `0` reverse-wraps across `wrapped` lines). 2. **Copy-on-write `?2026` render hold and generation-tagged expiry**: - On `CSI ? 2026 h`, `Terminal` increments `_sync_generation: int` and marks `_sync_hold_pending = True` without cloning rows immediately; only if `term.committed` is read while `?2026` remains active (or before the first post-hold mutation when a waiter is attached) is the pre-batch `Snapshot` materialized, and `CSI ? 2026 l` in the same chunk skips cloning altogether. - `term.expire_synchronized_output(sync_generation: int | None = None) -> bool` releases a stalled `?2026` hold, clears `Mode.SYNCHRONIZED_OUTPUT`, and emits `RenderHoldChanged(active=False, expired=True)` only when `sync_generation` matches `_sync_generation`, preventing stale async timers from releasing a newer frame. - `term.feed_until(data, *, offset=0, stop=...)` bulk-scans `GROUND` and control-string interiors (`OSC`/`DCS`/`APC`) to `\x07`/`\x1b` boundaries and checks `not parser.utf8_pending` before reporting `StopOn.GROUND`. 3. **Primary-screen soft-wrap resize reflow (`resize(*, rows, cols, reflow=True)`)**: - Resizing `primary` when `cols` changes and `reflow=True` rejoins `wrapped=True` logical lines across `history + viewport` (eliding `WidthRole.SPACER_HEAD` wrap-padding cells), re-wraps them to the new column width while tracking cursor `(row, col)`, and pushes excess top rows into `FrozenRow` scrollback rather than truncating bottom lines. - Resizing `alternate` (`?1049`) crops/pads in place without reflow, matching full-screen TUI `SIGWINCH` redraw expectations; when `Mode.IN_BAND_RESIZE` (`?2048`) is enabled, `resize()` also queues `CSI 48 ; rows ; cols ; 0 ; 0 t` and emits `InBandResize`. ## Alternatives considered - **Positional `Terminal(80, 24)` or `Terminal(columns=80, rows=24)`**: Rejected because mixing `(X, Y)` construction with `[row, col]` indexing invites silent axis transposition. - **Exposing four `CoordSpace` enums and `StaleGridRefError` cell handles**: Rejected because immutable `Cell` values, `Snapshot`, and `term.history` provide safe inspection without runtime borrow-checker exceptions in Python. ## Consequences ### Positive - Eliminating per-character `Cursor` allocation and `feed_until` 1-byte slicing removes the primary pure-Python CPU bottlenecks. - Primary-screen `resize()` matches `tmux` and `Ghostty` soft-wrap reflow. - Generation-tagged `?2026` expiry eliminates async timer races. ### Tradeoffs - `reflow=True` unpacks wrapped lines during `cols` changes (`O(history + rows)`), which callers can bypass with `reflow=False` when batch-resizing. ### Risks - Wide characters landing on `cols - 1` during reflow. Mitigation: emit `SPACER_HEAD` at `cols - 1` and wrap the 2-column glyph cleanly to column `0` of the next reflowed row. --- # ADR 0005: UTF-8/C1 isolation, grapheme caps, and Unicode 17 two-stage table Source: https://libvt.git-pull.com/project/adr/0005-utf8-c1-isolation-and-unicode-17-grapheme-width/ (adr-utf8-and-unicode-17)= # ADR 0005: UTF-8/C1 isolation, grapheme caps, and Unicode 17 two-stage table ## Status Accepted. 2026-11-21. ## Context Adversarial testing and differential fuzzing uncovered four Unicode and byte framing hazards in terminal emulators: 1. **UTF-8 continuation `0x9C` vs 8-bit `C1` `ST` escape-injection breakout**: In UTF-8, valid multi-byte characters including `“` (`U+201C` = `\xe2\x80\x9c`), `本` (`U+672C` = `\xe6\x9c\xac`), `Ü` (`\xc3\x9c`), and `😜` (`\xf0\x9f\x98\x9c`) contain byte `0x9C`. Treating raw `0x9C` as 8-bit String Terminator (`ST`) inside `OSC`, `DCS`, or `APC` strings truncates non-ASCII titles/hyperlinks mid-codepoint and executes the remaining payload directly in `GROUND` state — enabling escape-sequence injection past callers that filter `\x07` and `\x1b`. 2. **Incomplete UTF-8 ordering before C0 controls and combining-mark teleportation**: Flushing incomplete UTF-8 lead bytes only on `ESC` (and not C0 controls like `\n` or `\r`) emits `U+FFFD` on the wrong line, while retaining `_last_printed_pos` across cursor movements (`CUP`, `CUB`, `LF`), erases, scrolls, or `?1049` switches causes subsequent combining marks to mutate a stale cell elsewhere on screen. 3. **Single-cell combining-mark DoS ("grapheme bomb")**: Appending combining marks without a per-cell codepoint cap or scanning the growing cluster string on every mark causes quadratic CPU freeze (`10+ s` on 200 KB of `U+0301`) and multi-megabyte single-cell strings. 4. **Unicode version drift across Python 3.12-3.15 and missing UAX #29 rules**: Python's `unicodedata` module bundles Unicode 15.0 in 3.12, 15.1 in 3.13, 16.0 in 3.14, and 17.0 in 3.15, and lacks `Extended_Pictographic`, `Regional_Indicator` pair clustering (`🇯🇵`, `🇺🇸`), and UAX #29 `GB9c` Indic `InCB` (`Linker` / `Consonant` / `Extend`) properties needed for DEC mode `?2027`. ## Decision 1. **`STRING_ESC` 7-bit string termination and separated wire modes (`libvt.parser`)**: - `Parser(encoding="utf-8")` ignores raw `0x80..0x9F` 8-bit `C1` bytes and UTF-8-encoded `U+0080..U+009F` (`0xC2 0x80..0x9F`) as control introducers; `Parser(encoding="latin-1")` provides complete 8-bit DEC `C1` `anywhere` transitions for legacy Latin-1 byte streams. - `OSC`, `DCS`, and `APC`/`SOS`/`PM` transition on `0x1B` into a dedicated `ParserState.STRING_ESC` substate: `\` (`0x5C`) dispatches with `DCS` header intermediates intact, `0x1B` inside a latched `DCS tmux;` envelope collapses `ESC ESC` into one payload `ESC` byte, and any other byte aborts and discards the unclosed payload per DEC STD 070 §5.1.2.3 before re-evaluating that byte in `ESCAPE`. - Incomplete UTF-8 sequences flush `U+FFFD` *before* executing any C0 control (`< 0x20`), `ESC`, `CAN` (`0x18`), or `SUB` (`0x1A`). 2. **Strict `_last_printed_pos` invalidation and `O(1)` combining cap**: - Any cursor motion, C0 execution, erase, scroll, resize, reset, or screen switch clears `_last_printed_pos = None`. - `Terminal` tracks `_cluster_codepoints: int` and enforces `Limits.max_grapheme_codepoints` (default `32`), dropping excess zero-width extenders in `O(1)` time without re-scanning the cluster string. - When `VS16` (`\ufe0f`) widens a 1-column base glyph at `col == right` (right margin), `Terminal` replaces `col` with `SPACER_HEAD` (`""`), soft-wraps to the next line, and writes the widened 2-column cluster at `left` (`col 0`). `VS15` (`\ufe0e`) narrows default-wide emoji to `1` column under `?2027`. 3. **SHA-256-pinned Unicode 17.0.0 two-stage block table (`libvt._ucd`)**: - `scripts/generate_ucd.py` compiles official SHA-256-verified Unicode 17.0.0 UCD and Emoji data (`GraphemeBreakProperty.txt`, `DerivedCoreProperties.txt`, `EastAsianWidth.txt`, `DerivedGeneralCategory.txt`, `emoji-data.txt`, and `emoji-variation-sequences.txt`) into a zlib-compressed base85 2-stage 256-codepoint `u16` block table in `libvt._ucd` (`~70.5 KiB` unpacked, zero runtime dependencies), validated in `pytest` against all official `GraphemeBreakTest.txt` vectors. - Python 3.12, 3.13, 3.14, and 3.15 therefore compute identical cell widths and UAX #29 `?2027` cluster boundaries (`GB9`, `GB9a`, `GB9c` Indic conjuncts, `GB11` ZWJ pictographics, and `GB12`/`GB13` Regional Indicator pairs). ## Alternatives considered - **Calling stdlib `unicodedata` directly at runtime**: Rejected because emoji and Indic conjunct properties (`Extended_Pictographic`, `InCB`) are absent from `unicodedata` in Python 3.12-3.14, and Unicode table versions drift across interpreter versions. - **Runtime `wcwidth` / `grapheme` PyPI dependency**: Violates ADR 0001's `dependencies = []` invariant. ## Consequences ### Positive - UTF-8 titles, hyperlinks, and status messages containing `0x9C` continuation bytes never break out of `OSC`/`DCS`/`APC` framing. - Hostile combining-mark floods stay bounded at `<= 32` codepoints per cell in `O(1)` time per byte. - Flag emoji (`🇯🇵`), ZWJ sequences (`🧑‍🌾`), variation selectors (`❤️`), and Devanagari conjuncts cluster identically on Python 3.12 through 3.15. ### Tradeoffs - `src/libvt/_ucd.py` embeds `~14 KiB` of compressed base85 lookup data, regenerated via `scripts/generate_ucd.py` when upgrading Unicode versions. ### Risks - BiDi override characters (`U+202A..U+202E`, `U+2066..U+2069`) spoofing visual test diagnostics. Mitigation: `libvt._ucd.sanitize_terminal_text()` escapes C0, C1, and BiDi override codepoints in diagnostic views and rejects them in `OSC 7501` status fields. --- # ADR 0006: G0-G3 charsets, selective erase, and single-truth mode reconciliation Source: https://libvt.git-pull.com/project/adr/0006-charset-designations-and-single-truth-mode-reconciliation/ (adr-charsets-and-mode-truth)= # ADR 0006: G0-G3 charsets, selective erase, and single-truth mode reconciliation ## Status Accepted. 2026-11-21. ## Context Differential testing against `tmux` and `ncurses` applications exposed three classic VT100/VT420 gaps that break real-world terminal UIs even when modern sequences work: 1. **DEC Special Graphics (`ESC ( 0` / `SO` / `SI`)**: `tmux` (`tty-acs.c`), `ncurses`, `dialog`, `make menuconfig`, and `htop` designate `G0` or `G1` as DEC Special Graphics (`0`) and print `l q k x m j w u t v n` to draw `┌ ─ ┐ │ └ ┘ ┬ ┤ ├ ┴ ┼`. Dropping charset designations renders literal `lqqqk` ASCII letters instead of box-drawing glyphs. 2. **Tabulation and selective erase**: `CBT` (`CSI Ps Z` backward tab) and `CHT` (`CSI Ps I` forward tab) are standard horizontal cursor primitives, and VT220/VT420 applications use `DECSCA` (`CSI Ps " q`) with `DECSED` (`CSI ? Ps J`) and `DECSEL` (`CSI ? Ps K`) to clear unprotected fields while preserving protected form labels. Kitty-compatible shells also emit `CSI 22 J` to push the visible screen into scrollback before clearing. 3. **Alternate-screen `DECRQM` desynchronization (`?47` / `?1047` / `?1049`)**: Tracking `ALT_SCREEN_47`, `ALT_SCREEN_1047`, and `ALT_SCREEN` (`?1049`) as independent booleans in `ModeState` causes `CSI ? 47 h` followed by `CSI ? 1049 l` (or `?1049h` followed by `?47l`) to return to the primary screen while `CSI ? 47 $ p` falsely replies `1` (`SET`) instead of `2` (`RESET`), and `Formatter(OutputFormat.VT)` re-emits `\x1b[?47h`! ## Decision 1. **Per-screen `G0`-`G3` charset slots and shifts (`libvt.terminal`)**: - Track four charset slots (`G0`, `G1`, `G2`, `G3`, each `'B'` US-ASCII, `'0'` DEC Special Graphics, or `'A'` UK), active locking-shift slot `gl: int` (`0` via `SI` `0x0F`, `1` via `SO` `0x0E`, `2` via `LS2` `ESC n`, `3` via `LS3` `ESC o`), and one-shot single shift `single_shift: int | None` (`2` via `SS2` `ESC N`, `3` via `SS3` `ESC O`). - Designate slots via `ESC ( F` (`G0`), `ESC ) F` (`G1`), `ESC * F` (`G2`), and `ESC + F` (`G3`). When the active slot for the next printed character is `'0'`, map `0x5F..0x7E` through the 32-entry DEC Special Graphics table (`┌`, `─`, `┐`, `│`, `└`, `┘`, `┼`, `◆`, `▒`, `°`, `±`, `≤`, `≥`, `π`, `≠`, `£`, `·`, etc.) before writing to `_Row`. - Save and restore `(g_sets, gl)` inside `_SavedCursor` (`DECSC` / `DECRC` / `?1049`) and reset to `('B', 'B', 'B', 'B'), gl=0` on `DECSTR` and `RIS`. 2. **Tab navigation, selective erase, and scroll-clear**: - Implement `CHT` (`CSI Ps I`: advance `Ps` tabstops clamped to right margin) and `CBT` (`CSI Ps Z`: retreat `Ps` tabstops clamped to left margin, clearing `pending_wrap`). Keep sorted tabstops cached on `Screen`. - Implement `DECSCA` (`CSI 0 " q` / `CSI 2 " q` unprotected, `CSI 1 " q` protected) stored on `_CellExt.protected`, respected by `DECSED` (`CSI ? Ps J`) and `DECSEL` (`CSI ? Ps K`) while `ED` / `EL` erase unconditionally. - Support `CSI 22 J` (push non-blank primary viewport lines into `FrozenRow` scrollback before clearing the viewport). 3. **Single-truth alternate-screen reconciliation (`libvt.modes`)**: - `ScreenSet.active_is_alt` is the sole source of truth for whether the alternate buffer is active. Exiting via *any* of `?47l`, `?1047l`, or `?1049l` clears all three alt-screen mode bits in `ModeState`, and `ModeState.decrpm()` reconciles `?47`, `?1047`, and `?1049` against `active_is_alt` so `DECRQM` and `Formatter(OutputFormat.VT)` never report stale alt-screen state. ## Alternatives considered - **Ignoring `ESC ( 0` in UTF-8 mode**: Rejected because `ncurses`, `dialog`, and `tmux` still emit `ESC ( 0` whenever `acsc` terminfo capabilities are active. - **Reporting `SET` for `?47` whenever `?1049` is active**: Keep `?1049` as the canonical bit set when entering via `?1049h` (and `?47` when entering via `?47h`), while clearing *all* three bits whenever *any* exit sequence returns `active_is_alt` to `False`. ## Consequences ### Positive - `ncurses` and `tmux` ACS box-drawing borders render as real Unicode box characters (`┌───┐`) in `term.text` and `assert_screen()`. - `?47` / `?1047` / `?1049` transitions never leave ghost mode flags in `DECRQM` replies or `VT` snapshot exports. ### Tradeoffs - `on_print`'s ASCII slice fast path runs unhindered when the active charset is `'B'` (99%+ of traffic) and translates via `str.translate` when `'0'` or `'A'` is active. ### Risks - Applications leaving `SO` (`0x0E` -> `G1 = '0'`) latched after crashing. Mitigation: `DECSTR` (`CSI ! p`), `RIS` (`ESC c`), and `sgr0` (`ESC ( B` emitted by `tput sgr0`) restore `G0` US-ASCII. --- # ADR 0007: Rex OSC 7501 program status, semantic prompts, and host queries Source: https://libvt.git-pull.com/project/adr/0007-rex-osc-7501-program-status-and-semantic-prompts/ (adr-osc-7501-and-prompts)= # ADR 0007: Rex OSC 7501 program status, semantic prompts, and host queries ## Status Accepted. 2026-11-21. ## Context Modern CLI tools, build runners, and AI coding agents report structured task progress via the Program Status protocol (`OSC 7501`), supported in `tmux` ([`input.c` at `cce5f10`](https://github.com/tmux/tmux/blob/cce5f10/input.c)) and `Ghostty` / `libghostty-vt` ([`terminal.zig` at `5b0690d`](https://github.com/ghostty-org/ghostty/blob/5b0690d/src/terminal/c/terminal.zig)), alongside FinalTerm / shell-integration prompt markers (`OSC 133`), ConEmu/OSC `9;4` progress bars, `OSC 7` working-directory notifications, `OSC 52` clipboard writes, and startup capability queries (`XTVERSION`, `DECRQSS`, `XTGETTCAP`, `OSC 10/11;?`, `?2031` / `CSI ? 996 n`). Upstream sources exhibit a concrete behavioral divergence on the `OSC 7501 ; ?` capability query: - `tmux` (`cce5f10`) replies unconditionally with bare `"\033]7501;?\033\\"`. - Full Rex `OSC 7501` registries advertise supported states and kinds: `"\033]7501;?:states=idle,working,done,blocked,error:kinds=permission,question,auth\033\\"`. - `libghostty-vt` (`5b0690d`) suppresses the `OSC 7501 ; ?` reply unless a `program_status` effect consumer is attached, so applications avoid sending status updates nobody observes. ## Decision 1. **Spec-compliant `ProgramStatusStore` (`libvt.status`)**: - Enforce wire payload ceiling `<= 4,096` bytes before parsing. - Parse colon-delimited `[a-z]{1,16}=value` pairs: - `state`: `idle | working | done | blocked | error | clear` (required on non-query payloads). - `id`: optional slash-delimited hierarchical task identifier (`<= 128` bytes, `<= 8` `/` segments, `[A-Za-z0-9_.-]` segments; `""` = root). - `kind`: optional `permission | question | auth` (valid with `state=blocked`). - `progress`: optional integer `0..100`. - `app`: optional `[A-Za-z0-9_.+-]{1,32}`, inheriting `effective_app` from nearest ancestor `id` prefix when omitted on child tasks. - `title`: optional base64-encoded UTF-8 (`<= 256` encoded / `<= 192` decoded bytes); `msg`: optional base64-encoded UTF-8 (`<= 2,732` encoded / `<= 2,048` decoded bytes). Reject malformed base64, invalid UTF-8, C0 controls (`< 0x20` except `\t` in `msg`), `DEL`/C1 (`0x7F..0x9F`), and Unicode BiDi overrides. - `state=clear` removes `id` and all `id/*` descendants (when `id == ""`, clears the entire store). Total active records stay bounded by `Limits.max_status_records` (`256`). - Expose `term.program_status` (most urgent active `ProgramStatus` ordered `blocked > error > working > done > idle`, or root record) and `term.program_statuses -> dict[str, ProgramStatus]`. - **Profile- and policy-gated `OSC 7501 ; ?` reply**: Reply whenever `Policy.allow_program_status_query` is `True` (default `True`) and `Profile.osc_7501_capabilities` is non-empty (independent of `on_event` and `record_events` so pull-mode `term.program_status` inspection never changes wire negotiation), formatting the capability payload from `Profile.osc_7501_capabilities` (full `states=...:kinds=...` on `DEFAULT_PROFILE`, bare `?` on `TMUX_PROFILE`, empty on `XTERM_PROFILE`) and mirroring the incoming `BEL` (`\x07`) vs `ST` (`\x1b\\`) terminator. - **Lifecycle and `OSC 9;4` fallback**: Map `OSC 9;4;st;prog` into synthetic root status until the first native `OSC 7501` arrives (re-enabled on `RIS`). On `OSC 133;A` prompt start (ignoring `k=s` secondary continuation prompts) or `term.notify_process_exit()`, prune transient `working`, `blocked`, and `idle` entries while retaining `done` and `error`; survive `DECSTR` soft reset and clear all records on `RIS`. 2. **Monotonic `OSC 133` prompt zones and host queries (`libvt.terminal`)**: - Store `PromptZone(kind: PromptKind, abs_row: int, col: int, exit_code: int | None)` in a `collections.deque` bounded by `Limits.max_prompt_zones` (`1,024`), resolving rows on demand via `Snapshot.at_abs(abs_row)` and `Snapshot.viewport_row(abs_row)` so scrolling never invalidates stored prompt coordinates. - Support `OSC 7` and `OSC 9;9` (`term.cwd_uri` for any URI, `term.cwd` filtered by `Policy.osc7_hosts` without host syscalls, plus `WorkingDirectoryChanged`), `OSC 52` write (`ClipboardWrite` when `Policy.allow_clipboard_write`; `OSC 52 ; c ; ?` denied unless `Policy.allow_clipboard_read`), `XTVERSION` (`CSI > q` -> `DCS > | ... ST`), `DECRQSS` (`DCS $ q ... ST` for `m` SGR, `r` `DECSTBM`, `s` `DECSLRM`, ` q` `DECSCUSR`, `"q` `DECSCA`), `XTGETTCAP` (`DCS + q ST` for `TN`/`Co`/`RGB`/`Smulx`), `OSC 10;?` / `OSC 11;?` foreground/background queries, `?2031` + `CSI ? 996 n` color-scheme DSR, and `DCS tmux; ESC ESC ... ST` passthrough envelopes (emitting `Passthrough` and re-feeding inner bytes only when `Policy.allow_passthrough=True`). ## Alternatives considered - **Simplified `OSC 7501;value;progress` string split**: Rejected because it is wire-incompatible with `tmux`, `Ghostty`, and Rex CLI emitters. - **Coupling `OSC 7501 ; ?` replies to `record_events` / `on_event`**: Rejected because attaching an observer must not alter wire capabilities seen by the child process, and pull-mode `term.program_status` callers rely on the built-in `ProgramStatusStore`. ## Consequences ### Positive - `libvt` interoperates out of the box with `tmux` 3.6+/3.8+, `Ghostty`, and CLI tools emitting Rex `OSC 7501`, `OSC 9;4`, and `OSC 133`. - Startup capability handshakes (`tmux attach`, Neovim, Fish, Helix) complete immediately via `drain_replies()` without 1-2 second query timeouts. ### Tradeoffs - `ProgramStatusStore` validates base64 and UTF-8 bounds eagerly on `OSC 7501` frames (`<= 4 KiB`), dropping non-conformant fields safely. ### Risks - Untrusted PTY output flooding `OSC 133;A` or `OSC 7501` unique IDs. Mitigation: `Limits.max_prompt_zones = 1_024` (`deque` FIFO) and `Limits.max_status_records = 256`. --- # ADR 0008: Mode-aware input encoding, Kitty keyboard stacks, and paste safety Source: https://libvt.git-pull.com/project/adr/0008-mode-aware-input-encoding-and-paste-safety/ (adr-input-encoding)= # ADR 0008: Mode-aware input encoding, Kitty keyboard stacks, and paste safety ## Status Accepted. 2026-11-21. ## Context Driving interactive PTY sessions (`tmux`, shells, editors, modal TUIs) requires the outbound half of the terminal contract: encoding structured key, mouse, focus, and paste events into the exact byte sequences negotiated by the child application's active modes (`DECCKM` `?1`, mouse `?1000`/`?1002`/`?1003`/`?1006` /`?1016`, focus `?1004`, bracketed paste `?2004`, and the Kitty Keyboard Protocol `CSI u`). Two defects commonly break terminal input encoders: 1. **Shared primary/alternate Kitty keyboard state**: Full-screen TUIs push Kitty keyboard flags (`CSI > 1 u`) on the `?1049` alternate screen and crash without popping (`CSI < u`); sharing one stack corrupts primary-shell key encoding after `?1049l`. Furthermore, unprefixed `CSI u` is `SCORC` (restore cursor) and MUST NOT be confused with `CSI ? u` / `CSI > u` / `CSI < u` / `CSI = u`. 2. **Single-pass `.replace("\x1b[201~", "")` bracketed-paste RCE bypass**: Sanitizing pasted text with `text.replace("\x1b[201~", "")` stitches `"\x1b[20\x1b[201~1~; id\r"` directly back into `"\x1b[201~; id\r"`, breaking out of bracketed paste and executing arbitrary shell commands! It also misses 8-bit `CSI` (`\x9b201~`) and raw `\r`/`\n` command execution when `?2004` bracketed paste is disabled. ## Decision Provide a pure, zero-dependency `libvt.input` module integrated with `Terminal.encode(event: InputEvent) -> bytes`: 1. **Typed input events (`libvt.input`)**: - `KeyEvent(key: str, modifiers: KeyMod = KeyMod.NONE, action: KeyAction = KeyAction.PRESS, text: str = "")` with `KeyEvent.parse("ctrl+shift+p")` shorthand. - `MouseEvent(button: MouseButton, action: MouseAction, row: int, col: int, modifiers: KeyMod = KeyMod.NONE, pixel_x: int = 0, pixel_y: int = 0)` using 0-based `(row, col)` matching `Terminal`. - `FocusEvent(focused: bool)` (`\x1b[I` / `\x1b[O` when `?1004` is set, else `b""`). - `PasteEvent(text: str)`. 2. **Independent Primary and Alternate Kitty keyboard stacks**: - `ScreenSet` maintains separate 8-entry (`Limits.max_keyboard_stack`) `KittyKeyboardStack` instances on `primary` and `alternate`. - `CSI > flags u` pushes `flags`, `CSI < count u` pops `count` entries, `CSI = flags ; mode u` sets/ORs/clears `flags` (`mode` `1`=`set`, `2`=`or`, `3`=`not`), and `CSI ? u` queues `b"\x1b[?" + str(flags) + b"u"` into `drain_replies()`. Unprefixed `CSI u` remains `SCORC`. - `DECSTR` and `RIS` clear the active (or both) keyboard stacks. - When active `KittyKeyboardFlags` is non-zero, `encode_input` encodes disambiguated `CSI codepoint ; modifiers [: event_type] u` sequences; otherwise it encodes legacy xterm / `DECCKM` (`\x1bOA` vs `\x1b[A`) bytes. 3. **Fail-closed `encode_paste()` (`UnsafePasteError`)**: - By default (`sanitize=False`), `encode_paste(text, *, bracketed: bool)` raises `UnsafePasteError(LibVtError)` if `text` contains `ESC` (`\x1b`), 8-bit `C1` (`\x80..\x9f`, including `\x9b`), `NUL` (`\x00`), `DEL` (`\x7f`), or C0 controls other than `\t` and (when `bracketed=True`) `\n` / `\r`. When `bracketed=False`, `\r` and `\n` also raise `UnsafePasteError` so multi-line paste never executes unbracketed shell lines silently. - When callers explicitly opt into `sanitize=True`, all C0/C1/`ESC`/`DEL` codepoints are stripped character-by-character in a single pass over codepoints (never substring `.replace`), which cannot re-stitch `\x1b[201~`. ## Alternatives considered - **Silent `.replace("\x1b[201~", "")` sanitization**: Rejected due to the nested-substring stitching exploit (`"\x1b[20\x1b[201~1~"` -> `"\x1b[201~"`). - **Encoding mouse events with 1-based `(x, y)` coordinates**: Rejected by ADR 0004; `MouseEvent(row=0, col=0)` stays 0-based `(row, col)` in Python and adds `+ 1` on the wire (`\x1b[ `Registry` -> `Command` objects degrades throughput by `4-8x`. ## Decision Keep hot-path emulation and cold-path sequence disassembly cleanly separated: 1. **Cold-path `libvt.codec` (`explain` and `format_explain`)**: - `explain(data: Buffer | str) -> tuple[ExplainedSpan, ...]` drives `Parser` with a cold-path `_ExplainSink` and maps each action (`Print`, `Execute`, `EscDispatch`, `CsiDispatch`, `OscDispatch`, `DcsDispatch`, `ApcDispatch`) through compact lookup tables to produce frozen `ExplainedSpan(kind, mnemonic, summary, raw)` records (e.g. `CSI`, `"DECSET"`, `"?2026 (SYNCHRONIZED_OUTPUT) = set"`). - `format_explain(data: Buffer | str) -> str` formats one human-readable line per span for terminal debugging and pytest failure reports. 2. **Zero-dependency CLI (`src/libvt/__main__.py`)**: - `python -m libvt explain` reads stdin (or a file path) and prints `format_explain` output. - `python -m libvt render [--rows 24] [--cols 80]` renders final plain-text screen state. - `python -m libvt strip` strips VT escape sequences from stdin/file. 3. **Hot path untouched**: - `Terminal.feed()` never imports `libvt.codec` and never instantiates `ExplainedSpan` objects. ## Alternatives considered - **Unified hot/cold `@csi` `Command` registry**: Rejected because allocating a `Command` dataclass per `SGR` or `CUP` sequence penalizes every `Terminal.feed` call for metadata only humans read during debugging. - **Registering a global `vt` console-script binary in `[project.scripts]`**: Omitted to avoid colliding with external `vt` binaries on user `PATH`; `python -m libvt` is zero-collision and always matches the active virtualenv. ## Consequences ### Positive - Developers and pytest failure hooks (`FlightRecorder`) disassemble arbitrary VT traces with `libvt.explain()` or `python -m libvt explain` with zero impact on `Terminal.feed()` speed. ### Tradeoffs - Sequence mnemonics in `libvt.codec` are maintained alongside `Terminal`'s dispatch handlers, tested for parity in `tests/test_codec.py`. ### Risks - Raw untrusted bytes inside `format_explain` emitting live escape sequences to the developer's own terminal. Mitigation: `format_explain` escapes all C0, C1, `ESC`, and BiDi override characters in both `raw` and `summary` columns. --- # ADR 0010: Transport-only asyncio/PTY adapters and diagnostic pytest plugin Source: https://libvt.git-pull.com/project/adr/0010-transport-only-asyncio-and-diagnostic-pytest-plugin/ (adr-asyncio-and-pytest-plugin)= # ADR 0010: Transport-only asyncio/PTY adapters and diagnostic pytest plugin ## Status Accepted. 2026-11-21. ## Context `libvt` ships an `asyncio` / POSIX PTY transport layer (`libvt.aio`), visual assertion helpers (`libvt.testing`), and a `pytest11` plugin (`libvt.pytest_plugin`). Four concrete failure modes emerged during review and empirical testing: 1. **Import pollution**: Importing `asyncio`, `pty`, or `pytest` inside `libvt/__init__.py` slows every `import libtmux` call. 2. **Fixture namespace collisions**: Auto-discovered `pytest11` plugins that register unprefixed fixture names (`terminal`, `spawn`, `shell`) collide with fixtures in `pytest-shell-utilities`, `pexpect`, and downstream test suites, whereas splitting a separate `pytest-vt` PyPI package creates cross-package version skew relative to `libtmux.pytest_plugin`. 3. **Wide-glyph box misalignment and terminal-escape injection in failure diffs**: Padding `format_screen_box` rows with `str.ljust(w)` counts Python codepoints instead of terminal display columns, pushing right `│` borders out of alignment on every 2-column CJK/emoji character (`"日本"`), while unescaped C0/C1/BiDi characters in failure messages can corrupt the test runner's terminal. 4. **POSIX vs Windows PTY scope**: Both `libtmux` and `tmuxp` declare `Operating System :: POSIX` and `Operating System :: MacOS :: MacOS X` classifiers only (`tmux` itself is POSIX-only). Adding a `pywinpty` C/Rust ConPTY dependency for Windows subprocess PTYs would break ADR 0001's pure `py3-none-any.whl` zero-dependency guarantee. ## Decision 1. **Strict import isolation (`libvt/__init__.py`)**: - `import libvt` never loads `asyncio`, `pty`, `termios`, or `pytest` (enforced by a clean-interpreter subprocess test in `tests/test_libvt.py`). 2. **`AsyncTerminalStream` and POSIX `open_pty()` (`libvt.aio`)**: - `AsyncTerminalStream` drives `Terminal` from `(StreamReader, StreamWriter)` pairs, flushing `drain_replies()` automatically and enforcing `sync_timeout` via `Terminal.expire_synchronized_output(sync_gen)` in both background-task (`async with`) and on-demand `wait_for()` modes. - `open_pty(argv, *, rows=24, cols=80, env=None, cwd=None, tty_mode="cooked", python_executable=None)` spawns a child process attached to a stdlib `pty.openpty()` master/slave pair via an isolated `-I -S` child trampoline (`start_new_session=True`, strict `TIOCSCTTY` controlling terminal acquisition, `SIGPIPE`/`SIGXFSZ` reset to `SIG_DFL`, and a pre-exec marker + bounded stage/errno packet on a `CLOEXEC` `err_fd` pipe without `preexec_fn`), configures `TIOCSWINSZ` and optional `"cbreak"` / `"raw"` termios modes, augments unset `Policy.osc7_hosts` with the local hostname, and reaps owned process groups on `aclose()` via `os.killpg` (`SIGHUP` -> `SIGTERM` -> `SIGKILL`) after draining final PTY bytes. On Windows (`sys.platform == "win32"`), `open_pty()` raises `NotImplementedError` cleanly while the entire Sans-I/O core works unchanged. 3. **Strictly `vt_`-prefixed, `Protocol`-typed `pytest11` plugin (`libvt.pytest_plugin`)**: - Register `vt_terminal`, `vt_factory` (typed via `TerminalFactory` `t.Protocol` so static type checkers verify keyword arguments), `vt_parser`, `vt_recorder` (`FlightRecorder`), and `vt_pty` (calling `pytest.skip("POSIX pty required")` on `win32`), with lazy imports inside fixture bodies. 4. **Literal `assert_screen`, column-exact `assert_screen_box`, and `FlightRecorder` (`libvt.testing`)**: - `assert_screen` compares literal screen text without stripping `┌──┐` borders rendered by applications, while `format_screen_box` and `assert_screen_box` measure cells by terminal display width (`WidthRole` / `display_width`), sanitize C0/C1 and BiDi overrides, validate outer `│W` soft-wrap markers, and append `FlightRecorder` diagnostics (cursor, active modes, `OSC 7501` status, `Parser.state`, and disassembled recent raw bytes via `format_explain`) when a `FlightRecorder` is attached to `Terminal`. - `Snapshot.to_dict()` returns a deterministic JSON-compatible dictionary for snapshot testing (`inline-snapshot` / `syrupy`). ## Alternatives considered - **Unprefixed `terminal`, `spawn`, `shell` fixtures**: Rejected due to global `pytest11` namespace collisions. - **Separate `pytest-vt` PyPI package**: Rejected to match `libtmux.pytest_plugin` single-package ergonomics. - **Optional `pywinpty` dependency**: Deferred; `libtmux` and `tmuxp` target POSIX/macOS exclusively, and keeping `dependencies = []` preserves universal pure-Python wheels. ## Consequences ### Positive - `assert_screen` aligns CJK, emoji, and combining marks to exact terminal columns and never leaks raw escape or BiDi spoofing sequences into pytest logs. - Failed async or PTY tests include the exact disassembled tail of VT bytes that produced the mismatch. ### Tradeoffs - Live subprocess `vt_pty` tests run on Linux/macOS/BSD and skip on native Windows, whereas all in-memory `vt_terminal` / `AsyncTerminalStream` tests run on every OS. ### Risks - Leaked PTY file descriptors or child processes if a test fails mid-wait. Mitigation: `PtySession.__aexit__` closes the master fd, terminates/reaps the child process, and cancels the pump task inside `try / finally`. --- # Architecture Decision Records Source: https://libvt.git-pull.com/project/adr/ (adr)= # Architecture Decision Records Design decisions, protocol contracts, storage layouts, and security boundaries for `libvt`. Copy `_template.md` to `NNNN-short-slug.md` and add the new document to the table of contents below when recording a decision. ```{toctree} :maxdepth: 1 0001-clean-room-provenance-and-license-firewall 0002-sans-io-layers-profiles-and-closed-events 0003-two-tier-packed-viewport-and-rle-scrollback 0004-zero-based-row-col-coordinates-and-sync-stepping 0005-utf8-c1-isolation-and-unicode-17-grapheme-width 0006-charset-designations-and-single-truth-mode-reconciliation 0007-rex-osc-7501-program-status-and-semantic-prompts 0008-mode-aware-input-encoding-and-paste-safety 0009-declarative-sequence-codec-and-stream-explainer 0010-transport-only-asyncio-and-diagnostic-pytest-plugin ``` --- # Benchmarking Source: https://libvt.git-pull.com/project/benchmark/ (benchmark)= # Benchmarking `libvt` ships two developer-only benchmark runners under `scripts/`: - `scripts/bench_vt.py`: in-process throughput and percentile suite for parser, screen, and import workloads (`just bench`). - `scripts/benchmark.py`: cross-commit runner (`hyperfine` with a pure-Python fallback) driven by `scripts/benchmark.toml`. Neither script is packaged in the published wheel. ## In-process microbenchmarks Run the default suite: ```console $ just bench ``` Emit machine-readable JSON: ```console $ uv run python scripts/bench_vt.py --warmup 2 --runs 10 --format json ``` ## Cross-commit harness Compare `HEAD` against `master`: ```console $ uv run python scripts/benchmark.py run --head-vs-trunk ``` Inspect resolved configuration and commit selectors without running benchmarks: ```console $ uv run python scripts/benchmark.py list-commands $ uv run python scripts/benchmark.py list-commits --lookback 5 ``` Override sample counts or add machine-local commands by copying `scripts/benchmark.local.toml.example` to `scripts/benchmark.local.toml` (gitignored). --- # Code Style Source: https://libvt.git-pull.com/project/code-style/ # Code Style Formatting, linting, typing, and import conventions are documented in {doc}`Contributing `. Docstring conventions are in [`.github/WRITING.md`](https://github.com/tmux-python/libvt/blob/master/.github/WRITING.md#docstrings). --- # Compatibility Source: https://libvt.git-pull.com/project/compatibility/ # Compatibility ## Python - **Minimum**: Python 3.12 - **Tested**: Python 3.12, 3.13, 3.14, 3.15 - **Maximum**: Python < 4.0 - **Runtimes**: CPython and PyPy (`py3-none-any.whl`, zero C extensions) ## Platforms | Platform | Status | |----------|--------| | Linux | Supported | | macOS | Supported | | WSL / WSL2 | Supported | | Windows | Supported (sans-I/O core and `asyncio` stream adapter) | --- # Contributing Source: https://libvt.git-pull.com/project/contributing/ (development)= # Contributing The contributor guide — environment setup, the gates, tests, documentation builds, releases, and the pull request process — lives in [.github/CONTRIBUTING.md](https://github.com/tmux-python/libvt/blob/master/.github/CONTRIBUTING.md). Prose conventions — README, `CHANGES`, commit messages, docstrings, and source comments — are in [.github/WRITING.md](https://github.com/tmux-python/libvt/blob/master/.github/WRITING.md). --- # Deprecations Source: https://libvt.git-pull.com/project/deprecations/ # Deprecations Active deprecations with timeline and migration paths. ## Active Deprecations No active deprecations at this time. See [history](../history.md) for past changes and the [migration guide](../migration.md) for upgrading between versions. ## Deprecation Policy See [Public API -- Deprecation Process](public-api.md#deprecation-process). --- # Project Source: https://libvt.git-pull.com/project/ (project)= # Project Project guides, compatibility information, and API governance. ::::{grid} 1 1 3 3 :gutter: 2 2 3 3 :::{grid-item-card} Contributing :link: contributing :link-type: doc Development setup, running tests, and submitting pull requests. ::: :::{grid-item-card} Code Style :link: code-style :link-type: doc [Ruff], [ty], [NumPy] docstrings, and import conventions. ::: :::{grid-item-card} Releasing :link: releasing :link-type: doc Release checklist and version policy. ::: :::{grid-item-card} Benchmarking :link: benchmark :link-type: doc In-process VT microbenchmarks and cross-commit timing harness. ::: :::{grid-item-card} Architecture Decisions :link: adr/index :link-type: doc Architecture decision records and proposal template. ::: :::: ## API Governance ::::{grid} 1 2 3 3 :gutter: 2 2 3 3 :::{grid-item-card} Public API :link: public-api :link-type: doc Public boundaries, stability policy, and deprecation process. ::: :::{grid-item-card} Compatibility :link: compatibility :link-type: doc Python runtime and platform support. ::: :::{grid-item-card} Deprecations :link: deprecations :link-type: doc Active deprecations and migration guidance. ::: :::: ```{toctree} :hidden: contributing code-style releasing benchmark adr/index public-api compatibility deprecations ``` [Ruff]: https://docs.astral.sh/ruff/ [ty]: https://docs.astral.sh/ty/ [NumPy]: https://numpydoc.readthedocs.io/en/latest/format.html --- # Public API Source: https://libvt.git-pull.com/project/public-api/ # Public API ## What Is Public Every module documented under [API Reference](../api/index.md) is public API. ## What Is Internal Modules prefixed with `_` (such as `libvt._grid` or `libvt._width`) are not public. They may change or be removed without notice between any release. ## Pre-1.0 Stability Policy `libvt` is pre-1.0: - **Minor versions** (`0.x` -> `0.y`) may include breaking API changes. - **Patch versions** (`0.x.y` -> `0.x.z`) contain bug fixes only. - **Pin your dependency**: use `libvt>=0.1,<0.2` or `libvt~=0.1.0`. Breaking changes are recorded in [changelog](../history.md) and [migration](../migration.md). ## Deprecation Process Before removing or changing public API: 1. Emit a `DeprecationWarning` for at least one minor release. 2. Document the replacement in [deprecations](deprecations.md) and [migration](../migration.md). 3. Remove the deprecated symbol in a subsequent minor release. --- # Releasing Source: https://libvt.git-pull.com/project/releasing/ # Releasing ## Version Policy `libvt` is pre-1.0. Minor version bumps may include breaking API changes. Downstream users should pin to `>=0.x,<0.y`. ## Release Process Releases are triggered by git tags and published to [PyPI] via OIDC trusted publishing. 1. Update `CHANGES` with the release notes. 2. Bump version in `pyproject.toml` and `src/libvt/__about__.py`. 3. Commit: ```console $ git commit -m "libvt " ``` 4. Tag: ```console $ git tag v ``` 5. Push: ```console $ git push && git push --tags ``` 6. CI builds and publishes to [PyPI] via trusted publishing. [PyPI]: https://pypi.org/project/libvt/ --- # Quickstart Source: https://libvt.git-pull.com/quickstart/ (quickstart)= # Quickstart ## Requirements - Python >= 3.12 (CPython and PyPy) - Zero runtime dependencies ## Installation ```console $ uv add libvt ``` ```console $ pip install libvt ``` ## One-liner helpers {func}`libvt.render`, {func}`libvt.strip`, and {func}`libvt.explain` cover one-shot rendering, control-sequence stripping, and byte-stream disassembly: ```python >>> import libvt >>> libvt.render(b"\x1b[32mok\x1b[0m\r\nnext", rows=3, cols=10) 'ok\nnext' >>> libvt.strip(b"\x1b[1mbold\x1b[0m plain") 'bold plain' >>> [s.mnemonic for s in libvt.explain(b"\x1b[1;31mhi\x1b[0m")] ['SGR', 'TEXT', 'SGR'] ``` ## Stateful emulation {class}`libvt.Terminal` uses keyword-only `(rows, cols)` dimensions and zero-based `(row, col)` indexing across cells, rows, and 2D slices: ```python >>> term = libvt.Terminal(rows=4, cols=20) >>> term.feed(b"\x1b(0lqqqk\x1b(B\r\n\x1b[4:3mwave\x1b[0m") >>> term.lines[:2] ('┌───┐', 'wave') >>> term[1, 0].style.underline ``` ## Mode-aware input and paste safety {meth}`libvt.Terminal.encode` serializes keys, mouse events, focus changes, and bracketed pastes according to active terminal modes: ```python >>> term = libvt.Terminal(rows=4, cols=20) >>> term.feed(b"\x1b[>1u\x1b[?2004h") >>> term.encode(libvt.KeyEvent.parse("ctrl+k")) b'\x1b[107;5u' >>> term.encode(libvt.PasteEvent("line 1\nline 2")) b'\x1b[200~line 1\nline 2\x1b[201~' ``` ## Pytest assertions {func}`libvt.testing.assert_screen` compares literal visible text (including box-drawing borders) and optional cursor coordinates, while {func}`libvt.testing.assert_screen_box` validates column-aligned `┌──┐` diagrams and soft-wrap markers: ```python >>> from libvt.testing import assert_screen, assert_screen_box >>> term = libvt.Terminal(rows=2, cols=8) >>> term.feed("日本!\r\nok".encode()) >>> assert_screen(term, "日本!\nok", cursor=(1, 2)) >>> assert_screen_box( ... term, ... """ ... ┌────────┐ ... │日本! │ ... │ok │ ... └────────┘ ... """, ... cursor=(1, 2), ... ) ``` --- # Architecture & Grid Storage Source: https://libvt.git-pull.com/topics/architecture/ (topics-architecture)= # Architecture & Grid Storage `libvt` separates terminal emulation into four acyclic layers so callers import only the machinery they need: 1. **Streaming parser** ({mod}`libvt.parser`): VT500 byte state machine with colon-subparameter `CSI` bitmasks, incremental UTF-8 decoding, `STRING_ESC` 7-bit string termination, optional Latin-1 8-bit `C1` wire parsing, and `DCS tmux;` `ESC ESC` collapsing. 2. **Grid and screen model** ({mod}`libvt.screen`): Zero-based `(row, col)` viewport with lazy 64-bit `array('Q')` attribute words, wide-spacer boundary healing, run-length-encoded scrollback rows, and primary-screen soft-wrap resize reflow. 3. **Sans-I/O terminal facade** ({mod}`libvt.terminal`, {mod}`libvt.status`, {mod}`libvt.input`, {mod}`libvt.codec`): Coordinates dual primary/alternate screens, `Profile` / `Policy` / `Limits`, `OSC 7501` status records, outbound replies, and input encoding with zero system calls. 4. **Transport and test edges** ({mod}`libvt.aio`, {mod}`libvt.testing`, {mod}`libvt.pytest_plugin`): Optional `asyncio` stream/PTY runners and pytest diagnostics. ## Configuration split {class}`~libvt.config.Profile`, {class}`~libvt.config.Policy`, and {class}`~libvt.config.Limits` separate compatibility identity from security gates and resource caps: ```python >>> import libvt >>> term = libvt.Terminal( ... rows=3, ... cols=5, ... profile=libvt.TMUX_PROFILE, ... policy=libvt.Policy(strict=False), ... limits=libvt.Limits(max_osc_bytes=8192), ... ) >>> term.feed(b"12345\x1b[1DX") >>> term[0].text '1234X' ``` ## Two-tier viewport and RLE scrollback Active viewport rows keep plain ASCII lines at a single uniform 64-bit word and promote to `array('Q')` only when styled or wide cells appear. Evicted scrollback lines freeze into immutable run-length-encoded rows exposed through {attr}`~libvt.terminal.Terminal.history`: ```python >>> term = libvt.Terminal(rows=2, cols=12, scrollback=10) >>> term.feed(b"\x1b[32mline-0\x1b[0m\r\nline-1\r\nline-2") >>> [r.text for r in term.history] ['line-0'] >>> term.history[0].runs[0].style.fg ``` For rationale and memory measurements, see {doc}`../project/adr/index`. --- # Topics Source: https://libvt.git-pull.com/topics/ (topics)= # Topics Conceptual guides covering `libvt`'s sans-I/O architecture, synchronize stepping, terminal protocols, and migration patterns. ::::{grid} 1 1 2 2 :gutter: 2 2 3 3 :::{grid-item-card} Architecture & Grid Storage :link: architecture :link-type: doc Sans-I/O layering, lazy 64-bit viewport rows, RLE scrollback, and Unicode 17 clustering. ::: :::{grid-item-card} Synchronized Output & `asyncio` :link: sync-and-asyncio :link-type: doc DEC `?2026` copy-on-write holds, `feed_until`, `AsyncTerminalStream`, and `open_pty`. ::: :::{grid-item-card} Protocols & Input Encoding :link: protocols-and-input :link-type: doc Rex `OSC 7501` Program Status, `OSC 133`, host queries, Kitty `CSI u`, and paste safety. ::: :::{grid-item-card} Migrating from `pyte` :link: migrating-from-pyte :link-type: doc Translating screen setup, coordinates, alternate screens, and replies to `libvt`. ::: :::: ```{toctree} :hidden: :maxdepth: 2 architecture sync-and-asyncio protocols-and-input migrating-from-pyte ``` --- # Migrating from pyte Source: https://libvt.git-pull.com/topics/migrating-from-pyte/ (topics-migrating-from-pyte)= # Migrating from `pyte` `libvt` provides an MIT-licensed, zero-dependency replacement for legacy Python terminal emulators with native support for `?1049` alternate screens, colon SGR subparameters, bidirectional query replies, and Unicode 17 grapheme clustering. ## Dimension order and coordinates `libvt` uses keyword-only `(rows, cols)` dimensions and zero-based `(row, col)` indexing everywhere: ```python >>> import libvt >>> term = libvt.Terminal(rows=24, cols=80) >>> term.feed(b"\x1b[2;5Hhello") >>> term.cursor.row, term.cursor.col (1, 9) >>> term[1, 4].text 'h' ``` ## Single byte-stream entry point Instead of pairing a separate `ByteStream` with a `Screen` or `HistoryScreen`, feed `bytes`, `bytearray`, or `memoryview` directly to {meth}`libvt.Terminal.feed` (or UTF-8 strings via {meth}`libvt.Terminal.feed_str`): ```python >>> term = libvt.Terminal(rows=4, cols=20, scrollback=500) >>> term.feed(b"first\r\n\x1b[?1049hfullscreen\x1b[?1049l") >>> term.text 'first' ``` ## Bidirectional replies and side-effect events Terminal queries (`CSI 6 n`, `CSI c`, `DECRQM`, `DECRQSS`, `XTVERSION`, `XTGETTCAP`, `OSC 10/11 ; ?`) accumulate in {meth}`libvt.Terminal.drain_replies` rather than being dropped, and structured notifications (`OSC 0/2`, `OSC 7`, `OSC 52`, `OSC 133`, `OSC 7501`, `?2026`) flow through `on_event` or {meth}`libvt.Terminal.drain_events`. --- # Protocols & Input Encoding Source: https://libvt.git-pull.com/topics/protocols-and-input/ (topics-protocols-and-input)= # Protocols & Input Encoding ## Rex `OSC 7501` Program Status `libvt` implements the Rex `OSC 7501` Program Status grammar (`:`-joined `key=value` pairs, hierarchical `/` task identifiers, ancestor `app` inheritance, base64 `title` and `msg`, and `OSC 9;4` ConEmu progress fallback): ```python >>> import base64, libvt >>> term = libvt.Terminal(rows=4, cols=30, record_events=True) >>> title_b64 = base64.b64encode(b"Running pytest").decode("ascii") >>> term.feed( ... f"\x1b]7501;state=working:id=ci:app=pytest:progress=75:title={title_b64}\x1b\\".encode() ... ) >>> term.feed(b"\x1b]7501;state=blocked:id=ci/approve:kind=permission\x1b\\") >>> term.program_status.id, term.program_status.effective_app ('ci/approve', 'pytest') ``` `OSC 7501 ; ?` capability queries answer whenever `Policy.allow_program_status_query` is `True` (the default) and `Profile.osc_7501_capabilities` is non-empty, independent of whether `on_event` or `record_events=True` is attached. ## Semantic prompts (`OSC 133`) and queries `OSC 133` prompt markers record monotonic `abs_row` indices across scrollback eviction so stored prompt zones remain valid as output scrolls: ```python >>> term = libvt.Terminal(rows=2, cols=20, scrollback=10) >>> term.feed(b"\x1b]133;A\x07$ \x1b]133;B\x07ls\r\nfile.py\r\n\x1b]133;D;0\x07") >>> [(z.kind.value, z.exit_code) for z in term.prompt_zones] [('A', None), ('B', None), ('D', 0)] ``` ## Outbound input encoding and paste safety {func}`~libvt.input.encode_input` and {meth}`~libvt.terminal.Terminal.encode` consult `DECCKM`, mouse modes (`?9`, `?1000`, `?1002`, `?1003`, `?1006`, `?1016`), focus reporting (`?1004`), bracketed paste (`?2004`), and the active screen's Kitty `CSI u` keyboard stack: ```python >>> term = libvt.Terminal(rows=4, cols=20) >>> term.feed(b"\x1b[?1h") >>> term.encode(libvt.KeyEvent.parse("up")) b'\x1bOA' ``` {func}`~libvt.input.encode_paste` fails closed with {exc}`~libvt.exc.UnsafePasteError` whenever pasted text contains `ESC`, 8-bit `C1` bytes, `NUL`, `DEL`, or unbracketed newlines rather than relying on single-pass substring replacement. --- # Synchronized Output & asyncio Source: https://libvt.git-pull.com/topics/sync-and-asyncio/ (topics-sync-and-asyncio)= # Synchronized Output & `asyncio` Modern TUI applications wrap screen redraws in DEC private mode `?2026` (`CSI ? 2026 h` … `CSI ? 2026 l`) so observers never inspect half-drawn frames. ## Copy-on-write `?2026` holds and `feed_until` While `term.synchronized` is `True`, {attr}`~libvt.terminal.Terminal.committed` returns the pre-batch {class}`~libvt.terminal.Snapshot` while {meth}`~libvt.terminal.Terminal.snapshot` reflects live in-progress mutations: ```python >>> import libvt >>> term = libvt.Terminal(rows=2, cols=16) >>> term.feed(b"stable") >>> term.feed(b"\x1b[?2026h\x1b[2J\x1b[Hredrawing") >>> term.committed.text 'stable' >>> term.snapshot().text 'redrawing' >>> term.feed(b"\x1b[?2026l") >>> term.committed.text 'redrawing' ``` {meth}`~libvt.terminal.Terminal.feed_until` steps through concatenated captures and stops cleanly at `?2026l` (`StopOn.SYNC_END`), `OSC 133` prompt boundaries, or `OSC 7501` status transitions: ```python >>> batch = b"\x1b[?2026h\x1b[Hf1\x1b[?2026l\x1b[?2026h\x1b[Hf2\x1b[?2026l" >>> t = libvt.Terminal(rows=2, cols=8) >>> step = t.feed_until(batch, stop=libvt.StopOn.SYNC_END) >>> t.text, step.stopped_on ('f1', ) ``` If an application crashes mid-frame without closing `?2026l`, {meth}`~libvt.terminal.Terminal.expire_synchronized_output` releases the hold only when `sync_generation` still matches the stalled batch. ## `AsyncTerminalStream` and `open_pty` {mod}`libvt.aio` wraps sans-I/O terminals for `asyncio` readers/writers and POSIX pseudo-terminals without adding background threads to the core: - {class}`~libvt.aio.AsyncTerminalStream` pumps an `asyncio.StreamReader`, flushes {meth}`~libvt.terminal.Terminal.drain_replies` to an optional writer, and coalesces `wait_for(...)` wakeups across `?2026` batches up to `sync_timeout`. - {func}`~libvt.aio.open_pty` spawns a child process attached to a controlling `pty.openpty()` terminal (`TIOCSCTTY`, `TIOCSWINSZ`, default `SIGPIPE`, and selectable `tty_mode`), forwards terminal query replies, and calls {meth}`~libvt.terminal.Terminal.notify_process_exit` on teardown. ---