Metadata-Version: 2.4
Name: par-term-emu-core-rust
Version: 0.94.0
Classifier: License :: OSI Approved :: MIT License
Classifier: Environment :: Console
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Rust
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: MacOS
Classifier: Operating System :: Microsoft :: Windows :: Windows 10
Classifier: Operating System :: Microsoft :: Windows :: Windows 11
Classifier: Topic :: Terminals
Classifier: Topic :: Terminals :: Terminal Emulators/X Terminals
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Dist: pillow>=13.0.0 ; extra == 'image'
Provides-Extra: image
License-File: LICENSE
Summary: A comprehensive terminal emulator library in Rust with Python bindings - supports true color, alt screen, mouse reporting, bracketed paste, and full Unicode
Keywords: terminal,emulator,vt100,vt220,vt320,vt420,ansi,sixel,pty,rust,pyo3,terminal-emulator,unicode,true-color
Author-email: Paul Robello <probello@gmail.com>
Maintainer-email: Paul Robello <probello@gmail.com>
Requires-Python: >=3.12
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Discussions, https://github.com/paulrobello/par-term-emu-core-rust/discussions
Project-URL: Documentation, https://github.com/paulrobello/par-term-emu-core-rust/blob/main/README.md
Project-URL: Homepage, https://github.com/paulrobello/par-term-emu-core-rust
Project-URL: Issues, https://github.com/paulrobello/par-term-emu-core-rust/issues
Project-URL: Repository, https://github.com/paulrobello/par-term-emu-core-rust

# Par Term Emu Core Rust

[![CI](https://github.com/paulrobello/par-term-emu-core-rust/actions/workflows/ci.yml/badge.svg)](https://github.com/paulrobello/par-term-emu-core-rust/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/par_term_emu_core_rust)](https://pypi.org/project/par_term_emu_core_rust/)
[![Crates.io](https://img.shields.io/crates/v/par-term-emu-core-rust)](https://crates.io/crates/par-term-emu-core-rust)
[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/par_term_emu_core_rust.svg)](https://pypi.org/project/par_term_emu_core_rust/)
![Runs on Linux | MacOS | Windows](https://img.shields.io/badge/runs%20on-Linux%20%7C%20MacOS%20%7C%20Windows-blue)
![Arch x86-64 | ARM | AppleSilicon](https://img.shields.io/badge/arch-x86--64%20%7C%20ARM%20%7C%20AppleSilicon-blue)
![PyPI - Downloads](https://img.shields.io/pypi/dm/par_term_emu_core_rust)
![Crates.io Downloads](https://img.shields.io/crates/d/par-term-emu-core-rust)
![PyPI - License](https://img.shields.io/pypi/l/par_term_emu_core_rust)

A comprehensive terminal emulator library written in Rust with Python bindings for Python 3.12+. Provides VT100/VT220/VT320/VT420/VT520 compatibility with PTY support, matching iTerm2's feature set.

[!["Buy Me A Coffee"](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)](https://buymeacoffee.com/probello3)

## Quick Install

Checksum-verified standalone binaries from the [GitHub releases](https://github.com/paulrobello/par-term-emu-core-rust/releases). Installs both the `par-term-streamer` streaming server and the `par-mux` multiplexer into `~/.cargo/bin` (or `$HOME\.cargo\bin`).

macOS / Linux:

```bash
curl -fsSL https://raw.githubusercontent.com/paulrobello/par-term-emu-core-rust/main/install.sh | bash
```

Windows (PowerShell):

```powershell
irm https://raw.githubusercontent.com/paulrobello/par-term-emu-core-rust/main/install.ps1 | iex
```

Options: `--streamer` / `--streamer-mux` / `--mux` (PowerShell: `-Streamer` / `-StreamerMux` / `-Mux`) install a subset, `--version vX.Y.Z` / `-Version` pins a release, and `--bin-dir DIR` / `-BinDir` picks a different destination. The default (no selectors) installs the plain streamer and par-mux; `--mux` combines with either streamer variant, `--streamer` and `--streamer-mux` are mutually exclusive.

## What's New

Version 0.94.0 sharpens par-mux viewer attribution: `pane-info` now carries `tui_viewers=<n>`, the count of attach TUIs showing a pane (declared via `refresh-client -t <pane> -C WxH -T` once the daemon advertises the `tui` feature token), and a streaming mirror's size report no longer counts as viewing the window's active pane — it counts toward the one pane it named — so a supervisor can no longer be fooled into showing a pane nobody watches. It also fixes attach pane emulators going one row off the daemon grid after a reflow refit under `xterm-resize-reflow`. Version 0.93.0 introduced experimental [cell borders](docs/VT_TECHNICAL_REFERENCE.md#cell-borders-dcs-1--b). The draft protocol is off by default in the core library. When enabled, borders survive scrollback and replay and appear in screenshots. par-mux attach draws them on hosts that advertise support, and Python and C consumers can read border masks. The bundled web terminal does not advertise border support because its renderer cannot place strokes behind text. This release also fixed interleaved Kitty graphics transfers and an attach hang when stdin is redirected. See [CHANGELOG.md](CHANGELOG.md) for the full notes.

Version 0.92.0 is the audit-remediation and fail-closed authenticity release. **Breaking:** streaming clients are read-only by default (`default_read_only: true`, SEC-001) — the standalone streamer takes `--read-write` for PTY write; release signature verification is fail-closed everywhere (SEC-002): the self-updaters, the frontend download, and both first-run installers refuse a release that publishes no `.minisig` sidecar (or an unverifiable one), so every release from this cut on carries minisign sidecars signed in CI, and releases older than the first signed release are unreachable by design. OSC 7 / OSC 1337 CurrentDir cwd tracking is now opt-in (`accept_osc7` defaults off, SEC-005; par-mux panes opt in at spawn), the per-client input rate limit defaults to 1 MiB/s (SEC-003), every C FFI export is `catch_unwind`-contained (QA-001), a chunked Kitty transmission survives interleaved Kitty commands (probe/put no longer hijack the in-flight stream), and the mux `/clear` no longer blanks the roster's project name. Packaging gets leaner (pillow leaves the wheel runtime, crates.io ships no dev-tooling residue) and three new drift gates join `make checkall` (packaged contents, TerminalEvent size, web_term freshness). See [CHANGELOG.md](CHANGELOG.md) for the full notes.

Version 0.91.0 is a PTY throughput release. `PtySession::write` / `PtyInputHandle::write` stop taking the exclusive Terminal lock per chunk and stop blocking on the tty round trip under the writer mutex: writes enqueue onto a bounded per-session queue drained by a dedicated writer thread, input recording runs at enqueue time gated on a shared atomic recording flag, and a non-recording write no longer serializes against the reader thread or concurrent frame gathers — a 512 MiB paste measured 10x faster under par-term's paste-upload shape (3.9 → 38.5 MB/s). Error timing changed: a tty write failure now latches sticky and is reported by the next write call (the enqueue-time call returns `Ok`). `make install` now ships the mux-enabled streamer, and `make streamer-install-mux` proves the mux bridge actually compiled in (the plain and mux streamer builds print identical `--help`/`--version`). See [CHANGELOG.md](CHANGELOG.md) for the full notes.

Version 0.90.0 is a resource-bounds and resilience release. `Terminal::transfer_summaries()` gives Rust embedders payload-free file-transfer snapshots (SEC-010) — id, filename, direction, status and byte counts in one read-lock call, allocating byte-identically for a 50 MiB and a 1-byte transfer, so transfer polling no longer copies payload bytes. The par-mux control client bounds its notification queue by bytes and items (SEC-012): a stalled frontend can no longer grow memory with pane output — past the 8 MiB budget the reader closes the connection, riding the existing reconnect-and-requery heal. The streaming mux-mirror bridge consumes the daemon's `gen=` replay fence, so a daemon restart mid-stream cannot double-apply replay-covered chunks onto the mirror terminal (matching the attach pump's 0.89 fence), and agent restore now launches resumed agents with their full original arguments instead of the hook's minimal resume shape. The fleet gains `make fleet-par-mux-update` (minisign-verified release deploy + per-host-model restart across minimac and the lennys), the script audit hardened the gate checks for Windows (utf-8 text reads, posix table separators) and gated or removed the stale manual helpers, the three streaming test clients were rewritten as real protobuf clients, and the bench gate bootstraps a baseline that predates the bench feature. See [CHANGELOG.md](CHANGELOG.md) for the full notes.

Version 0.89.0 carries the post-0.88.0 remediation train. The mux_factory bridge's top churn×complexity hotspot is decomposed — `spawn_drain` becomes a dispatcher over eight named per-concern methods, with seven wire-behavior pins added before the edit — and the streaming server's 32-arm send filter is a declarative table compile-checked against the protocol enum (ARC-002). Idle daemon CPU drops ~2.7x (agent-kind probes batch into a single process walk, empty trees skip the scrape tick) and the passthrough attach mode fences replayed output by damage generation exactly like the TUI client, closing the same double-apply race fixed there in 0.88.0. `StreamingConfig` gains `allow_legacy_password_hashes` (default `false`): legacy `{SHA}`/`$apr1$` htpasswd hashes are now refused on the library path exactly as the standalone streamer already refused them — opt-in verifies with a loud deprecation warning and removal is targeted at 0.91.0 (**behavior change** for embedders relying on library acceptance). The scheduled Bench gate works again (criterion feature-gating had silently broken its build flags), the pyclass-migration watch is retired by owner decision — the flat Python surface is permanent (parsight decision 133) — and the docstring pass confirmed the stub's remaining undocumented defs are the gate's allow-listed set. See [CHANGELOG.md](CHANGELOG.md) for the full notes.

Version 0.88.0 is the audit-remediation and agent-integration release. `par-mux` gains first-class Antigravity CLI (`agy`) support: `--install-agent-hooks` registers session hooks in `~/.gemini/config/hooks.json` (identity, working, idle), a bundled scrape set reads agy's spinner line as `working` and enrolls fresh panes from the process tree, and agent resume relaunches with `agy --conversation <id>`. The attach TUI's divider drags now start from both border cells of a shared divider on both axes. Release authenticity lands (SEC-001): every update path — self-update, frontend download, install.sh/ps1 — verifies a detached minisign signature after the SHA-256 gate, with CI signing each release's artifacts in the approval-gated `release` GitHub environment; absent signatures warn until the next release, when refusal activates. The streamer drops `script-src 'unsafe-inline'` for per-response nonces (SEC-004), the frontend download follows HTTPS-only redirects (SEC-003), and Windows daemons take a real `LockFileEx` state-file lock (SEC-005). **Breaking for Rust embedders:** the deprecated `streaming::Broadcaster` (dead since 0.58.0) is removed. Also in: the tmux-control parser split with inline tests, write-path classification helpers (measured net-faster: ASCII −6.8%, wide-char −18.3%), 30 deterministic integration tests joining the fast gate, a DECSERA fuzz crash fixed before it shipped, and the dependency/action train current (Rust 1.100). See [CHANGELOG.md](CHANGELOG.md) for the full notes.

> **Note:** This section covers the releases from 0.63.0 through 0.91.0. The
> complete release history is in [CHANGELOG.md](CHANGELOG.md).

Version 0.87.0 improves the par-mux attach settings dialog's agent hook integrations page: each hook row now grades against a PATH probe of the agent binary, so a host with agents installed but no par-mux hooks reads as "detected — hook not installed" instead of "no agents," and pressing `i` installs the session hooks of every detected-but-uninstalled arm; the integrations list itself is selectable (arrow/j/k with a following window), so all 16 rows are reachable. `par-mux --cmd doctor` now reports the daemon's macOS responsible-process attribution with a healthy/tainted verdict that names the bare-fork taint shapes (the herdr#808 bug class). The streamer CSP's `connect-src` always permits `blob:` — the `--csp-allow-blob-connect` opt-in is removed (breaking for `StreamingConfig(allow_blob_connect_src=...)` callers, who should drop the argument). Also fixed: the mux explicit-target passthrough tests use platform-absolute socket paths so they pass on Windows. See [CHANGELOG.md](CHANGELOG.md) for the full notes.

Version 0.86.0 adds `par-mux --restart` on macOS: restarting a launchd-managed default-instance daemon now goes through its `com.paulrobello.par-mux` launchd job (clean stop, then `launchctl kickstart -k`), so the fresh daemon stays launchd-managed instead of being replaced by an adhoc-signature fork that loses TCC identity and Local Network grants — with a stamp-changed verification that turns a squatter's autostart noop into a loud error, and fallback to the bare-fork restart for named instances, unloaded jobs, or a failed kickstart. Also fixed: the `install.sh` exclusivity check referenced lowercase globals that were unbound under `set -u`, killing every invocation. See [CHANGELOG.md](CHANGELOG.md) for the full notes.

Version 0.85.0 is a mux durability and dependency-train release: pane terminal grids leave the state file for content-addressed per-pane snapshot files (format v4, reads v3 — the 221 MB single-file rewrite per mutating command is gone), pane and session environment moves out of the state file into `0600` sidecar files so live tokens no longer ride the one JSON every downstream reader parses, every install target Developer-ID-signs its installed artifacts so macOS Local Network grants survive reinstalls, an attach window switch-back replays the landed window's full panes (transient reconnect corruption fixed), and agent resumes re-enter the agent's own working directory (a claude session that `EnterWorktree`'d no longer restores fenced out of its worktree). `par-mux` now suggests the verb you meant on a typo'd command, and the dependency train moves to pyo3 0.30, syn 3, zbus 6, toml 1.0, and the current streaming stack. See [CHANGELOG.md](CHANGELOG.md) for the full notes.

Version 0.84.0 ships the opt-in `[daemon] xterm-resize-reflow` flag (ENH-045): a mux daemon running with it gives every pane terminal xterm.js's resize reflow — a resize rewraps grid and scrollback as one buffer, and the streamer's per-pane mirror and the `Connected.pane_resize_reflow` handshake field keep streaming viewers in lockstep. Fixes ride along: the claude hook/mod install no longer corrupts `settings.json` on windows (backslashes became invalid JSON escapes), `worktree-remove` finishes a removal git abandoned mid-teardown (git deletes the directory before the registration and continues after the deletion fails — the windows-latest "is not a working tree" failures), EL 0/ECH clear the row's wrapped flag like xterm (an exactly-full readline force-wrap row no longer merges with the row below in `content()`), and the mux test client's daemon auto-spawn finds its binary under cargo 1.100's new `build/<pkg>/<hash>/out/` test layout. See [CHANGELOG.md](CHANGELOG.md) for the full notes.

Version 0.83.0 lands the 2026-11 audit remediation train: the 13 doc-hidden pub raw fields leave the published surface in favor of accessors (**breaking for crates.io embedders reaching into them**, now enforced by a shrink-only gate), control clients perform a connect-time version handshake that stays compatible with legacy daemons, the streaming protocol module splits into per-direction files with a byte-identical wire format (proto goldens prove it), four v0.82-era opt-in APIs reach the C embedding surface as ABI v6 (`set_xterm_resize`, `set_max_scrollback`, `set_codepoint_widths`, `remove_graphic_everywhere`), failed streaming authentication logs the peer address, and a raced seed re-export no longer stalls every pane's fan-out behind a multi-megabyte export. Grid fixes: a VS16-widened emoji no longer vanishes under the next character, a REP pending across a programmatic alt-screen switch no longer fires on the other screen, and DECALN now raises the used-length marker it previously skipped (EL/ECH/region-scroll kept stale cells). mux-test's macOS leg runs on the repository's MiniMac self-hosted runner, and the kernel-cwd streaming tests probe the cross-process cwd read at runtime and skip loudly where the host denies it. See [CHANGELOG.md](CHANGELOG.md) for the full notes.

Version 0.82.0 merges a 13-PR contributor series for the terminal core, with every reviewed fix applied: REP (`CSI Ps b`), SGR 21/58 and colon-truecolor forms, OSC 8 URIs keeping semicolons, the kitty keyboard pop default, 1049's SGR-pen restore through the DECSC/DECRC slot, intermediate-safe ESC parsing plus a spec-correct DECALN, xterm wrap semantics for wide characters in the last column, half-wide overwrite/erase partner blanking extended to the rectangle operations, and kitty animation frames that edit in place per the protocol (root-gap honored, bad `c=` an error, `a=c` rejected instead of corrupting the image). Opt-in additions: xterm.js-style reflow resize (`Terminal::set_xterm_resize`), live scrollback resize (`Terminal::set_max_scrollback`), per-code-point emoji widths (`Terminal::set_codepoint_widths`), and compact scrollback storage. The scrolling/printing paths are reworked for throughput (4-5x on the project's interleaved bench gate). Two behavior changes to note: a wrap flag now travels with its line through partial scrolls, and kitty `a=f` no longer creates an image from nothing (transmit first). Graphics stay honest: scrollback images follow their lines through eviction and shrink, kitty deletion follows the protocol's real deleting grammar (lowercase placements-only, uppercase frees stored data) with per-matrix error replies and spec negative-z frame gaps, and scrollback animation copies keep the frame they showed when they scrolled off. mux and streaming ride the same train: a paste payload can no longer end its own bracketed paste (a web page could plant a command through a copy handler), a resize the child never agreed to no longer reflows the grid (PTY ioctl/SIGWINCH runs first, failure returns before reflow), the streamer's CSP `connect-src` takes opt-in HTTPS origins for custom web roots, `par-mux --keep-alive` keeps a headless-started daemon waiting for its first window, broadcast client eviction is byte-budgeted (8 MiB per client, 16 MiB aggregate) instead of line-counted, and one plain output chunk no longer erases the damage queued in the same broadcaster batch. See [CHANGELOG.md](CHANGELOG.md) for the full notes.

Version 0.81.0 makes **untrusted terminal output memory-bounded and the streaming protocol richer for remote pane management**: a unified output memory budget (default 320 MiB, ENH-062) aggregates everything untrusted PTY output can make the terminal retain — decoded graphics pixels, the in-flight iTerm2 multipart buffer, and file-transfer payloads — reporting refusals through the new `OutputBudgetExceeded` event, and the kitty RGB and RGBA decode branches now enforce `MAX_IMAGE_PIXELS` before any payload copy. Streaming clients of mux-backed sessions receive the pane's working directory (`Connected.cwd_hostname`/`cwd_is_local`, `CwdChanged.is_local`) and can create named panes (`PaneCreateRequest.name`, validated ≤ 64 bytes; the handshake advertises `pane_create_allowed`). Agent rosters stay honest across kills: `kill-window`/`kill-session` cascades emit `%agent-released` (as does `worktree-remove -f`), presence stamps refresh on a 60 s cadence between full roster fetches, and an agent's `report-state` claim and reason stream through roster deltas. mux attach polish: the keybinds panel lists the copy-mode key table, and the click-latency harness now splits paint from delivery. See [CHANGELOG.md](CHANGELOG.md) for complete release notes.

Version 0.80.0 ships **the select-layout multiplexer feature and hardens secret handling**: `par-mux select-layout [-t <target>] <preset>` rearranges a window into one of five presets (`even-horizontal`, `even-vertical`, `main-horizontal`, `main-vertical`, `tiled`) through the full layout-mutation path (unzoom, PTY re-fit, `%layout-change` broadcast, persistence), and attach clients apply the same presets with `prefix M-1`..`M-5` — rebindable through `[client]` `layout-*` chords in the settings dialog. The streamer gains `--api-key-file` / `PAR_TERM_API_KEY_FILE` (first line, trimmed, parse-time conflict with `--api-key`) so the API key stays out of `ps` output and shell history, plus startup refusals for unauthenticated/cleartext non-loopback binds without explicit `--allow-unauthenticated` / `--allow-cleartext-auth`. Security hardening closes an orphaned iTerm2 multipart memory-retention hole (restart fails the superseded transfer into the bounded ring; `active_transfers` caps at 8), percent-decodes query-param API keys before the constant-time compare, hardens DNS rebinding and auth backoff, and bounds frontend archive extraction. The mux tab strip keeps its configured width bounds across width changes (the long-standing tab-width reset bug). **Downstream (Rust embedders):** the crate is now a three-crate workspace — `par_term_emu_core_rust::mux::…` imports move to the standalone `par-mux` crate (root re-exports remain for this release), and `cargo install par-term-emu-core-rust --bin par-mux` is replaced by `cargo install par-mux --features mux-bin,attach`. See [CHANGELOG.md](CHANGELOG.md) for complete release notes.

Version 0.79.0 makes **mux diagnostics and the daemon lifecycle cleaner**: rejected and unparseable control-command log lines now name the peer on the other end (pid plus image path where the platform exposes peer pids, uid on macOS), a fresh default-instance daemon start hands off to the com.paulrobello.par-mux launchd job when it is loaded — no more adhoc-binary orphans losing TCC identity and LAN grants; `PAR_MUX_NO_LAUNCHD=1` opts out — and the attach TUI's window picker lists windows only, a session no longer a selectable row, with a window name two sessions share disambiguated as `session/name`. See [CHANGELOG.md](CHANGELOG.md) for complete release notes.

Version 0.78.1 fixes **the CI-only flake that blocked the 0.78.0 crates.io publish**: the scrape fallback tests' fixture spawned a live shell, whose OSC title on the ubuntu runner outranked the `idle_fallback` rule the tests pin; they now use quiet `sleep` panes, so the fallback is the only reachable rule. See [CHANGELOG.md](CHANGELOG.md) for complete release notes.

Version 0.78.0 gives **the attach TUI a full vi copy mode and makes agent rosters and restarts trustworthy**: prefix `[` now enters a complete copy mode on EVERY pane — the cursor roams scrollback plus a frozen snapshot of the screen at entry, `v`/`V`/Ctrl+V select character/line/block, `y` yanks per mode as an OSC 52 write and exits per the new `[client] copy-mode-auto-exit` setting, `/`/`?` search with `n`/`N`, `m{a-z}`/`'{a-z}` mark and jump, and the scrollback editor moves to its own chord, prefix `e`; the session/window/workspace pickers open in search mode with live filtering and Enter-activates. Idle codex panes now enroll on the agent roster (the codex hook captures the full lifecycle, a fresh pane reports idle at SessionStart, and the scrape tick detects fresh agent panes from their process tree). Daemon restarts stop resurrecting dead agents twice over: hook v5 stamps each claim with the reporting agent's pid so a dead session can't ride a same-label replacement, and generated resume wrappers are no longer persisted as pane spawn commands. Streaming: pane output is never silently dropped on the relay to viewers (three drop sites closed, lagged clients get an in-band screen resync), the damage pairing survives quiet links, and pane `BellRang` events forward to pane-subscribed sessions. See [CHANGELOG.md](CHANGELOG.md) for complete release notes.

Version 0.77.0 makes **the mux attach path faster and the streaming protocol richer for XR and web clients**: host input reaches the render TUI at a few-millisecond floor instead of riding out the pump's 16 ms poll tick, a roster click's landing is one daemon round trip instead of two serialized waits, and cross-workspace roster clicks land focused on the clicked agent's pane; the refresh-client seed reply is ordered against %output (a buffering consumer's seed discard is exact) and a failed seed replay retries once and fails loudly instead of leaving stale panes. Streaming gains optional per-chunk damage ranges on `output` (repaint changed rows instead of scanning the whole grid), normalized raw-SGR mouse `move` buttons, opt-in pane creation via the mux bridge (`--allow-pane-create`), and an opt-in CSP `connect-src blob:` variant for custom web roots; par-mux gains `prefer-default-workspace` for target-less multi-workspace attaches and a `window-add-replay` verb that rebuilds a session's windows from the live tree. **Web fix:** the bundled terminal now reacts to the server's real mouse mode names and encodes the wheel as SGR 64/65 — mouse support was inert before. See [CHANGELOG.md](CHANGELOG.md) for complete release notes.

Version 0.75.0 brings **env-gated OTLP metrics to the par-mux daemon and fixes how pane resizes move borders** — a new opt-in `otel` cargo feature (default builds carry no OpenTelemetry code) lets a daemon export live `sessions`/`panes`/`connected_clients` gauges plus `daemon_starts`/`client_connections`/`client_attaches` counters to par-obs, gated again at runtime by `--otel-enabled`/`PAR_MUX_OTEL_ENABLED` with the streamer's endpoint/transport/headers flags (see `docs/MUX.md`); the agent-state Claude Code mod now ships with the claude hook integration, reporting `question`/`working`/`idle` live so the roster icon no longer sticks after a question is answered; and a daemon restart restores each agent's exec-time environment, so resumes survive a launchd-restarted daemon. **Breaking:** `resize-pane -L/-U` now follow tmux's border semantics — every direction grows the pane (the daemon previously shrank) — so old shrink-callers use the opposite flag, and the attach drag grammar was re-aimed to match. See [CHANGELOG.md](CHANGELOG.md) for complete release notes.

Version 0.74.0 makes **par-mux's control surface harder to misuse and friendlier to discover**: `par-mux --cmd help` now lists every control verb (including `report-state`) straight from the parser registry without a daemon, and unknown control commands point at it instead of failing silently; `--cmd ""` and whitespace-only commands exit with a usage error instead of hanging; the attach TUI enables bracketed paste (DECSET 2004) on the host for the session's lifetime, so multi-line pastes reach pane apps like claude code framed instead of submitting line-by-line (hosts without 2004 keep sending pastes raw); and `new-workspace` auto-disambiguates its first session's name tmux-style (`main`, `main-2`, …), so a bare `new-workspace` works even when a session `main` already exists, with `--session-name` naming the first session explicitly. See [CHANGELOG.md](CHANGELOG.md) for complete release notes.

Version 0.73.0 adds **daemon-restart agent resume and roster presence in the streaming protocol** — a daemon restart now resumes agents with a continuation prompt (the `[daemon] agent-resume-prompt` setting, default ON with assess-first wording), so a restored `claude --resume <id>` starts working immediately instead of idling at its prompt, and a persisted park message composes in front; and the streamer's roster frame carries the v0.72 activity/presence stats — `last_activity_at`/`last_report_at`/`last_input_at`/`last_viewed_at`, `viewer_count`, `cpu_ms`, `stalled` — so a streamer client sees everything the mux CLI roster shows, wire-compatible with pre-0.72 bytes. Fixes: the Par-mux launcher signs with an audio-input entitlement so its status-only microphone probe works under hardened runtime. See [CHANGELOG.md](CHANGELOG.md) for complete release notes.

Version 0.72.0 adds **per-pane human-presence stats, agent self-reporting, and restore policies for par-mux** — `pane-info` and `list-agents` now carry `viewer_count`/`last_viewed_at`/`last_input_at`/`cpu_ms` so a supervisor can tell a human is driving; agents can park a pane's roster state themselves with `report-state`; per-agent `last_activity_at`/`last_report_at`/`stalled` and a replayable `events` ring give supervisors durable lifecycle events; `new-session --restore start-command` plus `set-workspace-restore-policy` (`start-command`/`agent-resume`/`none`) let a supervised pane re-run its original launch flags across restarts and give a workspace a hard no-restore opt-out; and a nested `claude -p` can no longer hijack its ancestor pane's agent claim (hook v4 + daemon guards + claim recovery). **Breaking:** the streamer now refuses legacy `{SHA}`/`$1$`/`$apr1$` htpasswd hashes at startup by default — regenerate with `htpasswd -nB`, or pass `--allow-legacy-hash`. Also: a view re-land deletes the previous view's kitty graphics from the host; PtySession exports and screenshots render from snapshots instead of holding the terminal lock; a multi-pane-tab roster click survives a lagging `%layout-change`; and `TerminalClipboard` ships as a Python-side feature-scoped facade. See [CHANGELOG.md](CHANGELOG.md) for complete release notes.

Version 0.71.1 fixes **the mirror streamer dying on a client text frame**: the tungstenite transport serving `par-term-streamer --mux-socket` treated any TEXT frame as a protocol error and tore down the session, so a probing client's control text frame (pardeck sends one on every connect) killed an otherwise healthy mirror; the path now logs and skips text frames, matching the axum `/ws` route. See [CHANGELOG.md](CHANGELOG.md) for complete release notes.



Version 0.69.0 makes **the mux mirror a first-class pane citizen and the gate fit the host**: a late joiner replays a pane's graphics even when they were placed before the streamer attached (`refresh-client -G` carries the placements in the seed, and the mirror tags every frame with its pane), every graphics frame on the wire — `inline_image` and `graphics_added` — carries its source pane for the coming multi-pane clients, the attach TUI's wheel scrolls menus, dialogs, and pickers with the arrows' scroll-into-view behavior while pane scrollback keeps the wheel, and each workspace gains an exit action (`remove`/`hold`/`shell`) set live via `set-exit-action` — `shell` respawns the user's shell when a pane child exits (crash-loop guarded, inherited by agent-append resumed panes). The gate itself now splits by load tolerance: 219 tests are labeled load-sensitive and leave the default gate (run exactly that set with `make test-rust-sensitive`; `checkall-ci` keeps full coverage), so a loaded host can still gate load-insensitive changes. The dependency train moved to current stable across Cargo, uv, bun, and CI action pins. See [CHANGELOG.md](CHANGELOG.md) for complete release notes.

Version 0.68.0 makes **files and images flow both ways across the mux, and the TUI points at what it means**: a phone (or any streaming client) can push a file into a pane with four new control verbs (`upload-begin`/`-chunk`/`-commit`/`-abort`) — staging is bounded (64 KiB chunks, 100 MiB per upload, 8 concurrent, idle/total timeouts) and commit bracket-pastes the materialized file's path into the pane rather than injecting bytes into its input. The connect handshake's inline-image replay is bounded for phone-cellular budgets (newest frames first, stopping at 8 MiB aggregate / 24 frames, skipped tail logged), replayed frames carry their exact cell positions, and a late joiner's `Connected` now includes the frames already on screen. In the attach TUI, `drag-cursor-shape` is renamed `change-cursor-shape` and defaults ON (an explicit `false` in an existing config still wins; the old key is ignored), the pointer takes the pointing hand over clickable tabs, and the tab context menu opens under the clicked tab instead of mid-screen, clamped on-screen for far-right tabs. The async attach cleanup completes: the seed's and re-seed's status snapshots ride the pump's `send_then` continuation (no snapshot round trip parks the view), a push handled mid-seed stays out of the transition baseline (identical rebroadcasts toast again), and a gone-window landing resolves from the cached roster first. See [CHANGELOG.md](CHANGELOG.md) for complete release notes.

Version 0.65.0 makes **the streamer and par-mux self-updating and one-line installable**: both binaries gain `--check-update`/`--self-update` plus an opt-in auto mode that checks at startup and on an hourly/daily/weekly cadence (default daily), driven by one checksum-verified release engine (`crates/par-term-emu-core/src/self_update.rs`), and `curl -fsSL .../install.sh | bash` (PowerShell `irm | iex` twin) installs them into `~/.cargo/bin` with streamer/mux/streamer-mux selectors. The release matrix now publishes a mux-enabled `par-term-streamer-mux-<os>-<arch>` artifact beside the plain streamer — each build self-updates only from its own artifact — and macOS release binaries are Developer ID signed and notarized, so the application firewall's allow rule survives update swaps. Mux-backed streaming viewers get `pane_size_status` (effective grid plus separate column/row constraint owners) and `viewer_presence` pushes, and a phone viewer's Fit resize no longer sticks after it disconnects: mux mirrors close on last-viewer disconnect, withdrawing the streamer's size claim so the remaining viewers re-fit the pane. See [CHANGELOG.md](CHANGELOG.md) for complete release notes.

Version 0.64.0 makes **par-mux's sidebar show workspace state at a glance**: every workspace row carries a herdr-style git badge (` main ↑2`, ahead/behind counts, hidden for non-repos, detached HEAD, or `[client] git-status = false`) resolved daemon-side from the pane's OSC 7-tracked cwd on a 2-second bound with a TTL cache keyed to the new `[client] git-poll-secs` setting (0 disables polling), and the marker column shows each workspace's most urgent agent status glyph — `question` is a first-class agent state end to end (scrape-tier dialog rules, sounds, notifications, prompt verbs), outranking `blocked`. A new `[daemon] split-start-dir` setting (`home-dir` | `previous-pane-dir` | `workspace-dir`) picks the folder a `split-window` pane starts in when no `-c` is given, and a new `[daemon.agent-append]` table carries per-agent resume words that `agent-start` appends when it launches one of the fourteen supported agents (`{name}` expands to the pane cwd's basename and every word is shell-quoted, so a configured value can never execute shell syntax). The streaming agent-roster entries gain `workspace`, `project`, and `pane_label` fields populated end to end (pane-title query, probe attribution), so ParDeck's phone roster can render them, and a restored daemon re-seeds its agents' last-known state so `list-agents` survives a restart. Seven fixes ride along: ED2/ED3 full-screen erases clear soft-wrap metadata so erased rows no longer stay joined in `content()` and par-mux `capture-pane`; kind-filtered event observers can subscribe to `pointer_shape_changed` again (the `TerminalEventKind::ALL` table had dropped it); the pane-stream seed's race check now samples its baseline before the export; bulk `--install-agent-hooks` covers all twelve hook arms (qwen, qodercli, devin, kimi, and mastracode were missing); the workspace status glyph sits next to the workspace name instead of displacing the marker column; a streaming session close no longer panics when the drain thread runs off the Tokio runtime; and `reload-config` re-reads the applied copy's stamped config path. See [CHANGELOG.md](CHANGELOG.md) for complete release notes.

Version 0.63.0 makes **par-mux self-updating and extensible**: `par-mux update [--channel stable|preview]` downloads the platform archive from GitHub releases, verifies the new binary's `--version` before replacing anything, keeps `par-mux.previous` beside it, and restarts the daemon through the stop-and-restore handoff; a checksum-verified curl|sh installer and a Homebrew tap template join it. The release also ships a trust-gated plugin system (manifests, event hooks), saved machines and an SSH thin client, persistence resilience (snapshot history, logind shutdown inhibitor), a macOS app-bundle wrapper for TCC permissions with launchd autostart, and a large attach batch — an interactive session picker, kitty graphics rendered in panes, popup command windows, theme presets with auto light/dark switching, IME/CJK input, drag-to-highlight copy, and jump-to-notification. Daemon side: git worktree workspaces, the `done` agent state, `agent-start`/`agent-prompt`/`agent-explain`/`wait-output`/`show-notification` control commands, raw pane streams for local clients, shell completions, and herdr's agent-integration ports. Breaking for configs that set `notify-states` explicitly: `[client] notify-states` now defaults to `["blocked", "done"]`, so add `"done"` to keep hearing about background finishes. See [CHANGELOG.md](CHANGELOG.md) for complete release notes.

Every other release is documented in [CHANGELOG.md](CHANGELOG.md).

## Features

### Core Terminal Emulation

- **VT100/VT220/VT320/VT420/VT520 Support** - Comprehensive terminal emulation matching iTerm2
- **Rich Color Support** - 16 ANSI colors, 256-color palette, 24-bit RGB (true color)
- **Text Attributes** - Bold, italic, underline (5 styles), strikethrough, blink, reverse, dim, hidden
- **Advanced Cursor Control** - Full VT cursor movement and positioning
- **Line/Character Editing** - VT220 insert/delete operations
- **Rectangle Operations** - VT420 fill/copy/erase/modify rectangular regions (DECFRA, DECCRA, etc.)
- **Scrolling Regions** - DECSTBM for restricted scrolling areas
- **Tab Stops** - Configurable tab stops (HTS, TBC, CHT, CBT)
- **Unicode Support** - Full Unicode including complex emoji sequences and grapheme clusters
  - Variation selectors (emoji vs text presentation)
  - Skin tone modifiers (Fitzpatrick scale U+1F3FB-U+1F3FF)
  - Zero Width Joiner (ZWJ) sequences for multi-emoji glyphs
  - Regional indicators for flag emoji
  - Combining characters and diacritical marks

### Modern Features

- **Alternate Screen Buffer** - Full support with automatic cleanup
- **Mouse Support** - Multiple tracking modes and encodings (X10, Normal, Button, Any, SGR, URXVT)
- **Bracketed Paste Mode** - Safe paste handling
- **Focus Tracking** - Focus in/out events
- **OSC 8 Hyperlinks** - Clickable URLs in terminal (full TUI support)
- **OSC 52 Clipboard** - Copy/paste over SSH without X11
- **OSC 9/777/99 Notifications** - Desktop-style alerts and notifications, including Kitty's OSC 99 protocol (chunked payloads, urgency levels, actions) via `take_notifications_detailed()`
- **Terminal Capability Queries** - XTGETTCAP (`DCS + q`) capability lookup and DECRQSS (`DCS $ q`) SGR/cursor-style/scroll-margin introspection
- **Expanded XTWINOPS Reporting** - `CSI 11/13/19 t` report window state, position, and screen size in characters
- **Shell Integration** - OSC 133 (iTerm2/VSCode compatible), OSC 1337 RemoteHost for remote host detection
- **Semantic Buffer Zones** - OSC 133 FinalTerm markers partition scrollback into prompt, command, and output zones
- **Command Output Capture** - Extract text from specific command execution blocks via `get_command_output()` and `get_command_outputs()`
- **Semantic Snapshot API** - Structured terminal state extraction via `get_semantic_snapshot()` for AI/LLM consumption, with configurable scope (visible, recent, full) and JSON output
- **Kitty Keyboard Protocol** - Progressive keyboard enhancement with auto-reset on alternate screen exit
- **Synchronized Updates (DEC 2026)** - Flicker-free rendering
- **Tmux Control Protocol** - Control mode integration support
- **Observer API** - Push-based event delivery with sync callbacks and async queues; convenience wrappers for common patterns (bell, title, CWD, command completion, zone changes)
- **General-purpose File Transfer** - OSC 1337 `File=` with `inline=0` for host-to-terminal downloads, `RequestUpload` for terminal-to-host uploads, with progress tracking and lifecycle events
- **Instant Replay** - Cell-level terminal snapshots with input-stream delta recording, size-based eviction, and timeline navigation via `SnapshotManager` and `ReplaySession`
- **C-Compatible FFI** - embedding API in `include/terminal_core.h` (`ptec_terminal_create`/`feed`/`dirty_ranges`/`read_row` render loop, key encoding, snapshots, observers; `SharedState`/`SharedCell`) for C/C++ and Swift apps — see the [FFI Guide](docs/FFI_GUIDE.md) and `make xcframework` for iOS

### Graphics Support

- **Sixel Graphics** - DEC VT340 compatible bitmap graphics with half-block rendering
- **iTerm2 Inline Images** - OSC 1337 protocol for PNG, JPEG, GIF images
- **Kitty Graphics Protocol** - APC G protocol with image reuse, animations, zlib compression (`o=z`), and advanced placement; the `t=f`/`t=t` file media is security-gated (`set_allow_file_media`, default allows only spec-named `*tty-graphics-protocol*` temp files, deleted only after decoding)
- **Unicode Placeholders** - Virtual placements insert U+10EEEE characters for inline image display
- **Unified Graphics Store** - Protocol-agnostic storage with scrollback support
- **Animation Support** - Frame-based animations with timing and composition control
- **Resource Management** - Configurable memory limits and graphics dropped tracking

### PTY Support

- **Interactive Shell Sessions** - Spawn and control shell processes
- **Bidirectional I/O** - Send input and receive output
- **Process Management** - Start, stop, and monitor child processes
- **Dynamic Resizing** - Resize with SIGWINCH signal
- **Environment Control** - Custom environment variables and working directory
- **Event Loop Integration** - Non-blocking update detection
- **Cross-Platform** - Linux, macOS, and Windows via portable-pty

### Terminal Streaming (WebSocket)

- **Standalone Server** - Pure Rust streaming server binary (no Python required)
- **Real-time Streaming** - Sub-100ms latency terminal streaming over WebSocket
- **Multiple Clients** - Support for concurrent viewers per session
- **Authentication** - Optional API key authentication (header or URL param)
- **Configurable Themes** - Multiple built-in color themes (iTerm2, Monokai, Dracula, Solarized)
- **Auto-resize** - Client-initiated terminal resizing with SIGWINCH support
- **Browser Compatible** - Works with any WebSocket client (xterm.js recommended)
- **Modern Web Frontend** - Next.js/React application with Tailwind CSS v4 and xterm.js

### Terminal Multiplexer (par-mux)

- **tmux Control Mode** - Sessions, windows, and split panes served over a local socket, attachable by tmux control-mode clients
- **Real-Time Push** - Pane output streams to clients as bytes arrive; no polling
- **Agent Awareness** - Panes report agent state over the same socket (JSON hook reports), with a scrape fallback for agents without hooks and an agent roster query
- **Session Resume** - Agent session identity persists across daemon restarts; agent panes respawn through their resume invocations
- **Attach Client** - `par-mux attach` renders sessions in your terminal (render mode, the default) or byte-pumps one pane (passthrough), with workspaces, a sidebar, and a config file; see [docs/MUX.md](docs/MUX.md#attaching-from-a-terminal)
- **Crash-Safe State** - Atomic saves with quarantine of unreadable state files; a clean SIGTERM never loses the last window

### Standalone Binary Updates

Both `par-term-streamer` and `par-mux` support `--check-update` (report only) and
`--self-update` (install and restart). Updates use this repository's GitHub releases,
require SHA-256 checksum sidecars, and retain a `.previous` binary beside the installation.
Automatic installation is **off by default**. Enable streamer `--auto-update` or
mux `[daemon] auto-update = true`, with an `hourly`, `daily` (default), or `weekly`
interval. See [streamer configuration](docs/STREAMING.md#binary-updates) and
[mux configuration](docs/MUX.md#binary-updates) for restart behavior and the app-bundle guard.

### Screenshots and Export

- **Multiple Formats** - PNG, JPEG, BMP, SVG (vector); HTML via `export_html()`
- **Embedded Font** - JetBrains Mono bundled - no installation required
- **Programming Ligatures** - =>, !=, >=, and other code ligatures
- **True Font Rendering** - High-quality antialiasing for raster formats
- **Color Emoji Support** - Full emoji rendering with automatic font fallback
- **Session Recording** - Record/replay sessions (asciicast v2, JSON)
- **Export Functions** - Plain text, ANSI styled, HTML export

### Macro Recording and Playback

- **YAML Format** - Human-readable macro storage format
- **Friendly Key Names** - Intuitive key combinations (`ctrl+shift+s`, `enter`, `f1`, etc.)
- **Keyboard Events** - Record and replay keyboard input with precise timing
- **Delays** - Control timing between events
- **Screenshot Triggers** - Trigger screenshots during playback
- **Playback Controls** - Play, pause, resume, stop, and speed control
- **Macro Library** - Store and manage multiple macros
- **Recording Conversion** - Convert terminal recording sessions to macros

### Utility Functions

- **Text Extraction** - Smart word/URL detection, selection boundaries, bracket matching
- **Content Search** - Find text with case-sensitive/insensitive matching
- **Buffer Statistics** - Memory usage, cell counts, graphics count and memory tracking
- **Color Utilities** - 18+ color manipulation functions (iTerm2-compatible)
  - NTSC brightness, contrast adjustment, WCAG accessibility checks
  - Color space conversions (RGB, HSL, Hex, ANSI 256)
  - Saturation/hue adjustment, color mixing

## Documentation

- **[Quick Start Guide](QUICKSTART.md)** - Get running in minutes
- **[API Reference](docs/API_REFERENCE.md)** - Complete Python API documentation
- **[VT Sequences](docs/VT_SEQUENCES.md)** - Comprehensive ANSI/VT sequence reference
- **[Advanced Features](docs/ADVANCED_FEATURES.md)** - Detailed feature guides
- **[Architecture](docs/ARCHITECTURE.md)** - Internal architecture details
- **[Security](docs/SECURITY.md)** - PTY security best practices
- **[Building](docs/BUILDING.md)** - Build instructions and requirements
- **[Troubleshooting](docs/TROUBLESHOOTING.md)** - Common build, test, streaming, and par-mux failures in one place
- **[Configuration Reference](docs/CONFIG_REFERENCE.md)** - Configuration options and the [environment variable reference](docs/CONFIG_REFERENCE.md#environment-variables)
- **[Cross-Platform Notes](docs/CROSS_PLATFORM.md)** - Platform-specific information
- **[VT Technical Reference](docs/VT_TECHNICAL_REFERENCE.md)** - Detailed VT compatibility and implementation
- **[Fonts](docs/FONTS.md)** - Font configuration and rendering
- **[Macros](docs/MACROS.md)** - Macro recording and playback system
- **[Streaming](docs/STREAMING.md)** - WebSocket terminal streaming
- **[Multiplexer](docs/MUX.md)** - par-mux terminal multiplexer daemon
- **[Manual Pass Checklist](docs/MANUAL-PASS.md)** - Human pass over the par-mux attach client in real terminal emulators (the attach ship gate)
- **[Rust Usage](docs/RUST_USAGE.md)** - Using the library in pure Rust projects
- **[Observers](docs/OBSERVERS.md)** - Push-based event delivery (callbacks and asyncio queues)
- **[Instant Replay](docs/INSTANT_REPLAY.md)** - Cell-level snapshots and timeline navigation
- **[FFI Guide](docs/FFI_GUIDE.md)** - C-compatible embedding API for Swift/JNI/C/C++
- **[Graphics Testing](docs/GRAPHICS_TESTING.md)** - Testing graphics protocol implementations
- **[Benchmarking](docs/BENCHMARKING.md)** - Criterion throughput benches and interleaved A/B comparison
- **[Testing Kitty Animations](docs/TESTING_KITTY_ANIMATIONS.md)** - Testing Kitty graphics animation support
- **[Regional Flag Limitation](docs/REGIONAL_FLAG_LIMITATION.md)** - Why regional-indicator flag emoji may not render as one glyph in some frontends
- **[Maturin Best Practices](docs/MATURIN_BEST_PRACTICES.md)** - Wheel build and packaging compliance review
- **[par-mux Design Pointer](docs/par-mux.md)** - Where the par-mux design plan lives
- **[par-mux Design Decisions](docs/MUX_DECISIONS.md)** - One-line summaries of the D-numbered decisions cited in code
- **[Documentation Style Guide](docs/DOCUMENTATION_STYLE_GUIDE.md)** - Standards for writing project documentation

## Installation

### From PyPI

```bash
uv add par-term-emu-core-rust
# or
pip install par-term-emu-core-rust
```

Wheels ship with the streaming server compiled in (`StreamingServer` works out of the box; check `par_term_emu_core_rust._native.HAS_STREAMING` to detect a build without it).

### From Source

Requires Rust 1.100+ and Python 3.12+:

```bash
# Install maturin (build tool)
uv tool install maturin

# Build and install
maturin develop --release
```

### Building a Wheel

```bash
# streaming is included: pyproject.toml [tool.maturin] features apply to every maturin build
maturin build --release
uv add --find-links target/wheels par-term-emu-core-rust
# or
pip install target/wheels/par_term_emu_core_rust-*.whl
```

### Using as a Rust Library

The library can be used in pure Rust projects without Python. Choose your feature combination:

| Use Case | Command | What's Included |
|----------|------------|-----------------|
| **Rust Only** | `cargo add par-term-emu-core-rust --no-default-features --features pty_session` | Terminal, PTY, Macros |
| **Rust + Streaming** | `cargo add par-term-emu-core-rust --no-default-features --features streaming,pty_session` | + WebSocket/HTTP server |
| **Python Only** | `cargo add par-term-emu-core-rust` | + Python bindings |
| **Everything** | `cargo add par-term-emu-core-rust --features full` | All features |

> **Note:** Since v0.46.0 the `pty_session` module (real PTY backend) is a separate feature. Omit it only for headless use without `PtySession`. See [docs/RUST_USAGE.md](docs/RUST_USAGE.md) for details.

**Download pre-built streaming server (recommended):**

Pre-built binaries and web frontend packages are available from [GitHub Releases](https://github.com/paulrobello/par-term-emu-core-rust/releases):

```bash
# Download binary (Linux example)
wget https://github.com/paulrobello/par-term-emu-core-rust/releases/latest/download/par-term-streamer-linux-x86_64
chmod +x par-term-streamer-linux-x86_64

# Download web frontend (asset named par-term-web-frontend-v<version>.tar.gz from
# https://github.com/paulrobello/par-term-emu-core-rust/releases/latest)
mkdir -p ./web_term
tar -xzf par-term-web-frontend-v*.tar.gz -C ./web_term

# Run
./par-term-streamer-linux-x86_64 --web-root ./web_term
```

Available binaries: Linux (x86_64, ARM64), macOS (Intel, Apple Silicon), Windows (x86_64)

**Pre-built `par-mux` daemon binaries** (standalone: no Python, no par-term
installation) are attached to the same [GitHub Releases](https://github.com/paulrobello/par-term-emu-core-rust/releases)
as `par-mux-v<version>-<target>.tar.gz` (Unix) / `.zip` (Windows) archives
with a `SHA256SUMS` file. Per-platform install steps:
[docs/MUX.md](docs/MUX.md#standalone-binaries-github-releases).

**Or install from crates.io:**
```bash
# Streaming server (no-default-features is required: the default python feature
# links libpython and fails at link time for a standalone binary)
cargo install par-term-emu-core-rust --no-default-features --features streaming-bin --bin par-term-streamer

# Terminal multiplexer daemon with the attach client (the standalone par-mux crate):
cargo install par-mux --features mux-bin,attach
```

Or build them from a source checkout (drop `,attach` for the daemon alone):

```bash
cargo install --path crates/par-mux --features mux-bin,attach --locked
```

**Or build from source:**
```bash
cargo build --bin par-term-streamer --no-default-features --features streaming-bin --release
./target/release/par-term-streamer --help
```

See [docs/RUST_USAGE.md](docs/RUST_USAGE.md) for detailed Rust API documentation and examples.

### Embedding in iOS Apps

The core ships a C API (`src/ffi.rs`, header `include/terminal_core.h`) for on-device embedding — the same emulator as par-term, packaged as a static xcframework for iOS device and simulator:

```bash
# Requires Xcode + rustup target add aarch64-apple-ios aarch64-apple-ios-sim
make xcframework
# → target/xcframework/TerminalCore.xcframework
```

`TerminalCore.xcframework` (device + simulator slices) is attached to GitHub releases from 0.56.0 on; build it locally with `make xcframework` for unreleased commits. Each slice carries a `Modules/module.modulemap`, so after adding the xcframework to an Xcode project a Swift file just does `import TerminalCore` (the C header is re-exported; no bridging header needed).

The C surface is a full embedding API, not just snapshots (contracts and examples in the [FFI Guide](docs/FFI_GUIDE.md)):

- **Version check**: `ptec_terminal_abi_version` — compare against the header's `TERM_CORE_ABI_VERSION` at startup
- **Lifecycle/input**: `ptec_terminal_create` / `ptec_terminal_free` / `ptec_terminal_feed` (VT bytes) / `ptec_terminal_resize`
- **Damage**: `ptec_terminal_dirty_ranges` returns coalesced inclusive dirty-row ranges and `ptec_terminal_mark_clean` consumes them; independent renderers use `ptec_terminal_damage_generation` + `ptec_terminal_dirty_ranges_since`, so one consumer never hides damage from another
- **Scroll-aware damage (ABI v5)**: `ptec_terminal_scroll_delta_since` + `ptec_terminal_content_dirty_ranges_since` report a region's net scroll plus only the content-changed rows, so a renderer blits on scroll and redraws just the new rows
- **Pinned readback**: `ptec_terminal_read_row` / `ptec_terminal_read_scrollback_row` / `ptec_terminal_scrollback_count` copy cells into caller-owned buffers — no allocation, no full-grid copy per frame — with palette-resolved colors and default-color bits (ABI v4); `ptec_terminal_read_cell_grapheme` returns a cell's full grapheme cluster; `ptec_terminal_scrollback_total_scrolled` pairs with the count to sync a mirrored scrollback window; `ptec_terminal_get_cursor` / `ptec_terminal_get_modes` carry per-frame state
- **Key encoding**: `ptec_terminal_encode_key` turns key events into PTY bytes (xterm legacy, kitty level-1 disambiguate, and modifyOtherKeys, honoring application cursor keys and the negotiated kitty flags); `ptec_terminal_encode_key_ex` adds per-side macOS Option-key modes through `TermKeyOptions`
- **Snapshots and observers**: `ptec_terminal_get_state` / `ptec_terminal_free_state`, `ptec_terminal_add_observer` / `ptec_terminal_remove_observer`; the `on_event_v2` slot delivers structured `TermEvent`s (a `TERM_EVENT_*` kind plus a JSON payload)

### Optional Components

#### Terminfo Installation

For optimal terminal compatibility, install the par-term terminfo definition:

```bash
# Install for current user
./terminfo/install.sh

# Or install system-wide
sudo ./terminfo/install.sh --system

# Then use
export TERM=par-term
export COLORTERM=truecolor
```

See [terminfo/README.md](terminfo/README.md) for details.

#### Shell Integration

Enhances terminal with semantic prompt markers, command status tracking, and smart selection:

```bash
cd shell_integration
./install.sh  # Auto-detects bash/zsh/fish
```

See [shell_integration/README.md](shell_integration/README.md) for details.

## Quick Start

### Basic Terminal Emulation

```python
from par_term_emu_core_rust import Terminal

# Create terminal
term = Terminal(80, 24)

# Process ANSI sequences
term.process_str("Hello, \x1b[31mWorld\x1b[0m!\n")
term.process_str("\x1b[1;32mBold green text\x1b[0m\n")

# Get content and cursor position
print(term.content())
col, row = term.cursor_position()
print(f"Cursor at: ({col}, {row})")
```

### PTY (Interactive Shell)

```python
from par_term_emu_core_rust import PtyTerminal

# Create PTY terminal and spawn shell
with PtyTerminal(80, 24) as term:
    term.spawn_shell()

    # Send commands
    term.write_str("echo 'Hello from shell!'\n")
    # Block until the output actually lands — no sleep guessing
    term.wait_for_text("Hello from shell!", timeout=3.0)

    # Get output
    print(term.content())

    # Resize terminal
    term.resize(100, 30)

    # Exit shell
    term.write_str("exit\n")
# Automatic cleanup
```

#### Environment Variables and Working Directory

Pass environment variables and working directory directly to `spawn_shell()` without modifying
the parent process environment. This is safe for multi-threaded applications (e.g., Tokio):

```python
from par_term_emu_core_rust import PtyTerminal

# Spawn with custom environment variables
with PtyTerminal(80, 24) as term:
    term.spawn_shell(env={"MY_VAR": "hello", "DEBUG": "1"})
    term.write_str("echo $MY_VAR\n")  # Outputs: hello

# Spawn with custom working directory
with PtyTerminal(80, 24) as term:
    term.spawn_shell(cwd="/tmp")
    term.write_str("pwd\n")  # Outputs: /tmp

# Combine both
with PtyTerminal(80, 24) as term:
    term.spawn_shell(env={"PROJECT": "myapp"}, cwd="/home/user/projects")
```

The `spawn()` method also accepts `env` and `cwd` parameters:

```python
term.spawn("/bin/bash", ["-c", "echo $MY_VAR"], env={"MY_VAR": "test"}, cwd="/tmp")
```

### Screenshots

```python
term = Terminal(80, 24)
term.process_str("\x1b[1;31mHello, World!\x1b[0m\n")

# Save screenshot
term.screenshot_to_file("output.png")
term.screenshot_to_file("output.svg", format="svg")  # Vector graphics!
open("output.html", "w").write(term.export_html(include_styles=True))  # Styled HTML

# Custom configuration
term.screenshot_to_file(
    "output.png",
    font_size=16.0,
    padding=20,
    include_scrollback=True,
    minimum_contrast=0.5,  # iTerm2-compatible contrast adjustment
)
```

### Color Utilities

```python
from par_term_emu_core_rust import (
    perceived_brightness_rgb,
    adjust_contrast_rgb,
    contrast_ratio,
    meets_wcag_aa,
    rgb_to_hex,
    hex_to_rgb,
    mix_colors,
)

# iTerm2-compatible contrast adjustment
adjusted = adjust_contrast_rgb((64, 64, 64), (0, 0, 0), 0.5)

# WCAG accessibility checks
ratio = contrast_ratio((0, 0, 0), (255, 255, 255))
print(f"Contrast ratio: {ratio:.1f}:1")
print(f"Meets WCAG AA: {meets_wcag_aa((0, 0, 0), (255, 255, 255))}")

# Color conversions
hex_color = rgb_to_hex((255, 128, 64))  # "#FF8040"
rgb = hex_to_rgb("#FF8040")  # (255, 128, 64)
mixed = mix_colors((255, 0, 0), (0, 0, 255), 0.5)  # Purple
```

### Macro Recording and Playback

```python
from par_term_emu_core_rust import Macro, PtyTerminal
import time

# Create a macro manually
macro = Macro("git_status")
macro.set_description("Check git status and show branch")
macro.add_key("g")
macro.add_key("i")
macro.add_key("t")
macro.add_key("space")
macro.add_key("s")
macro.add_key("t")
macro.add_key("a")
macro.add_key("t")
macro.add_key("u")
macro.add_key("s")
macro.add_key("enter")
macro.add_delay(500)  # Wait 500ms
macro.add_screenshot("git_status.png")  # Trigger screenshot

# Save to YAML
macro.save_yaml("git_status.yaml")

# Load and play back
term = PtyTerminal(80, 24)
term.spawn_shell()

# Load macro from file
loaded_macro = Macro.load_yaml("git_status.yaml")
term.load_macro("git_check", loaded_macro)

# Play the macro
term.play_macro("git_check", speed=1.0)  # Normal speed

# Tick to execute macro events
while term.is_macro_playing():
    if term.tick_macro():  # Returns True if event was processed
        time.sleep(0.01)  # Small delay for visual effect

    # Check for screenshot triggers
    triggers = term.get_macro_screenshot_triggers()
    for label in triggers:
        term.screenshot_to_file(label)

# Convert a recording to a macro
term.start_recording("test session")
term.write_str("ls -la\n")
time.sleep(0.5)
session = term.stop_recording()

# Convert and save
macro = term.recording_to_macro(session, "ls_command")
macro.save_yaml("ls_command.yaml")
```

## Examples

See the `examples/` directory for comprehensive examples:

### Basic Examples
- `basic_usage_improved.py` - Enhanced basic usage
- `colors_demo.py` - Color support
- `cursor_movement.py` - Cursor control
- `text_attributes.py` - Text styling
- `unicode_emoji.py` - Unicode/emoji support
- `scrollback_demo.py` - Scrollback buffer usage

### Advanced Features
- `alt_screen.py` - Alternate screen buffer
- `mouse_tracking.py` - Mouse events
- `bracketed_paste.py` - Bracketed paste
- `synchronized_updates.py` - Flicker-free rendering
- `shell_integration.py` - OSC 133 integration
- `test_osc52_clipboard.py` - SSH clipboard
- `test_kitty_keyboard.py` - Kitty keyboard protocol
- `hyperlink_demo.py` - Clickable URLs
- `notifications.py` - Desktop notifications
- `rectangle_operations.py` - VT420 rectangle ops

### Graphics and Export
- `display_image_sixel.py` - Sixel graphics
- `test_sixel_simple.py` - Simple sixel examples
- `test_sixel_display.py` - Advanced sixel display
- `screenshot_demo.py` - Screenshot features
- `feature_showcase.py` - Comprehensive TUI showcase

### PTY Examples
- `pty_basic.py` - Basic PTY usage
- `pty_shell.py` - Interactive shells
- `pty_resize.py` - Dynamic resizing
- `pty_event_loop.py` - Event loop integration
- `pty_mouse_events.py` - Mouse in PTY
- `pty_custom_env.py` - Custom environment variables
- `pty_multiple.py` - Multiple PTY sessions
- `pty_with_par_term.py` - Integration with par-term

### Terminal Streaming
- `streaming_demo.py` - Python WebSocket streaming server
- `streaming_client.html` - Browser-based terminal client

### Macros and Automation
- `demo.yaml` - Example macro definition

**Standalone Rust Server:**
```bash
# Build and run (default: ws://127.0.0.1:8099)
make streamer-run

# Run with authentication
make streamer-run-auth

# Or use cargo directly
cargo build --bin par-term-streamer --no-default-features --features streaming-bin --release
./target/release/par-term-streamer --port 8099 --theme dracula

# With authentication (prefer the env var: a CLI argument is readable in
# ps and shell history for the server's lifetime)
export PAR_TERM_API_KEY=my-secret
./target/release/par-term-streamer --theme monokai

# With system resource stats (CPU, memory, disk, network)
./target/release/par-term-streamer --enable-system-stats --system-stats-interval 5

# Install globally
make streamer-install
par-term-streamer --help
```

**Available Themes:** `iterm2-dark`, `monokai`, `dracula`, `solarized-dark`

### Diagnostics and Test Scripts
- `bce_scroll_test.py` - Background color erase (BCE) during scrolling
- `char_test.py` - Character-specific rendering test
- `gradient_test.py` - Minimal gradient test for terminal wrap behavior
- `rich_mimic_test.py` - Rich-style output rendering test
- `scroll_timing_test.py` - Scroll timing test
- `streaming_debug.py` - Streaming server debug tool
- `test_tui_clipboard.py` - TUI clipboard and selection features
- `test_underline_styles.py` - Underline styles (SGR 4:x)
- `render_utils.py` - Rendering helpers imported by the other examples (not run directly)

### Web Terminal Frontend

**Using Pre-built Package (Recommended):**

Download the pre-built static web frontend from [GitHub Releases](https://github.com/paulrobello/par-term-emu-core-rust/releases):

```bash
# Download and extract (asset named par-term-web-frontend-v<version>.tar.gz from
# https://github.com/paulrobello/par-term-emu-core-rust/releases/latest)
mkdir -p ./web_term
tar -xzf par-term-web-frontend-v*.tar.gz -C ./web_term

# Run streamer with web frontend
par-term-streamer --web-root ./web_term
# Open browser to http://localhost:8099
```

See [web-terminal-frontend/README.md](web-terminal-frontend/README.md) for detailed usage instructions.

**Building from Source:**

A modern Next.js-based web terminal frontend source is in `web-terminal-frontend/`:

```bash
# Install dependencies (bun)
make web-install

# Development server on http://localhost:3000
make web-dev

# Static build copied to web_term/ for par-term-streamer --web-root
make web-build-static
```

**Features:**
- Modern UI with Tailwind CSS v4
- xterm.js terminal emulator
- WebSocket connection to streaming server
- Theme selection and synchronization
- Responsive design
- Terminal resize support
- **Customizable UI theme** - Edit `theme.css` after build (no rebuild required)

See [web-terminal-frontend/README.md](web-terminal-frontend/README.md) for detailed setup and configuration.

## TUI Demo Application

A full-featured TUI (Text User Interface) application is available in the sister project [par-term-emu-tui-rust](https://github.com/paulrobello/par-term-emu-tui-rust).

![TUI Demo Application](https://raw.githubusercontent.com/paulrobello/par-term-emu-tui-rust/refs/heads/main/Screenshot.png)

**Installation:** `uv add par-term-emu-tui-rust` or `pip install par-term-emu-tui-rust`

**GitHub:** [https://github.com/paulrobello/par-term-emu-tui-rust](https://github.com/paulrobello/par-term-emu-tui-rust)

## Technology

- **Rust** (1.100+) - Core library implementation
- **Python** (3.12+) - Python bindings
- **PyO3** - Zero-cost Python/Rust bindings
- **VTE** - ANSI sequence parsing
- **portable-pty** - Cross-platform PTY support

## Running Tests

```bash
# All tests: Rust, Rust streaming, and Python (rebuilds the extension first)
make test

# Rust tests only (plain `cargo test` fails to link under the default `python` feature)
make test-rust

# Python tests only (runs `make dev` first)
make test-python
```

## Performance

- Zero-copy operations where possible
- Efficient grid representation
- Fast ANSI parsing with VTE crate
- Minimal Python/Rust boundary crossings

See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) for implementation details.

## Security

When using PTY functionality, follow security best practices to prevent command injection and other vulnerabilities.

See [docs/SECURITY.md](docs/SECURITY.md) for comprehensive security guidelines.

## Contributing

Contributions are welcome! Please submit issues or pull requests on GitHub.

### Development Setup

```bash
git clone https://github.com/paulrobello/par-term-emu-core-rust.git
cd par-term-emu-core-rust
make setup-venv  # Create virtual environment
make pre-commit-install  # Install pre-commit hooks (recommended)
make dev  # Build library
make checkall  # Run all quality checks
```

### Code Quality

All contributions must pass:
- Rust formatting (`cargo fmt`)
- Rust linting (`cargo clippy`)
- Python formatting (`make fmt-python`)
- Python linting (`make lint-python`)
- Type checking (`pyright`)
- Tests (`make test-python`)

**TIP:** Use `make pre-commit-install` to automate all checks on every commit!

### Load-Sensitive Tests

Timing-dependent Rust tests (the PTY and attach integration suites, and render tests pinned to timing) are labeled `#[ignore = "load-sensitive ..."]`. A plain `cargo test` and `make checkall` skip them, and `make test-rust` prints how many it deferred. Run them as follows:

- `make test-rust-sensitive` runs exactly the labeled set.
- `make checkall-ci` includes them (its nextest legs run ignored tests too), so it is the gate to pass before pushing a change that touches a labeled test.
- To run one suite by hand, pass `--include-ignored`, for example `cargo test -p par-mux --features mux-bin,attach --test mux_attach -- --include-ignored --test-threads=1`.

These tests measure wall-clock behavior, so run them on a quiet machine. Under heavy host load a failure is usually a timing flake rather than a regression, so re-run on an idle host before debugging.

See [CONTRIBUTING.md](CONTRIBUTING.md) for the contribution workflow, and [CLAUDE.md](CLAUDE.md) for detailed development instructions.

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## Author

Paul Robello - probello@gmail.com

## Links

- **PyPI:** [https://pypi.org/project/par-term-emu-core-rust/](https://pypi.org/project/par-term-emu-core-rust/)
- **Crates.io:** [https://crates.io/crates/par-term-emu-core-rust](https://crates.io/crates/par-term-emu-core-rust)
- **GitHub:** [https://github.com/paulrobello/par-term-emu-core-rust](https://github.com/paulrobello/par-term-emu-core-rust)
- **TUI Application:** [https://github.com/paulrobello/par-term-emu-tui-rust](https://github.com/paulrobello/par-term-emu-tui-rust)
- **Documentation:** See [docs/](docs/) directory
- **Examples:** See [examples/](examples/) directory

