@volter/supercode-terminal
v0.3.18
Published
Optional leak-safe terminal and tmux host adapter for Volter Harness frontends
Readme
@volter/supercode-terminal
Native Claude rollover evidence
NativeTerminalSessionHost (also used by SupercodeTerminalController) follows
Claude /clear transcript successors while the process keeps its original argv
session ID. iTerm and Terminal observations share one ownership batch. Ambiguous
co-located predecessors and successors claimed by another pane are not adopted;
later predecessor activity or a missing successor revokes the mapping.
The rollover store defaults to CLAUDE_CONFIG_DIR, then ~/.claude. An explicit
nativeHost.home isolates discovery to that home's .claude; an explicit
nativeHost.claudeConfigDir takes precedence. Both rollover evidence and the
existing PID-only Claude fallback use this same native store.
Embedders can gather the same evidence with createSessionRollTracker from the
existing ./substrate/session-lifecycle.js export and supply its map as
ObserveIo.sessionRolls (or pass the tracker to gatherLifecycleObservation).
Evidence is asynchronous: 16 KiB transcript head/tail reads, a 50-entry head inspection bound, 500-entry edge caches, and a 15-second successor-scan cadence. Directory enumeration still scales with the native project inventory. No new watcher, timer, subprocess, transcript copy, or persistent state is introduced. Closed-pane chains are pruned; over-capacity evidence fails closed. These are conservative append-oriented observations, not proof of arbitrary interior transcript rewrites. Native routing tests use isolated command fixtures, not live user terminals.
Overview
Optional terminal/tmux hosting for Volter Harness frontends. It complements Volter Harness's semantic transcript and runtime APIs with the familiar live terminal screen; it does not turn terminal bytes into canonical conversation history.
This package owns the shared terminal substrate. src/substrate/ is its source;
substrate/ contains the compiled runtime and declarations. The existing host,
controller, and browser client consume these modules directly, without a
the fleet tool package dependency. Advanced hosts and legacy adapters may import
/substrate/attach.js, /substrate/client.js, /substrate/local-terminal.js,
/substrate/native-host.js, /substrate/session-lifecycle.js,
/substrate/tmux-stream.js, and /substrate/tmux.js; the two internal helper
subpaths are exported only for compatibility. Prefer the controller/client APIs
above this layer for new applications.
TmuxTerminalHost, PtyTerminalHost and PaneServerHost expose
hasLiveContext(contextKey) for decisions that require a complete presence
reading. Tmux reads all session IDs and context values in one command, without
the ordinary option reader's best-effort fallback. Failed, incomplete or
malformed identity reads reject; only an explicit no-server answer establishes
emptiness after a failed command. Other connection errors remain unknown. The
PTY host reads its own live catalog; an older pane server refuses this operation.
This is a host observation, not a physical window/tab reading or an existence
lock against a subsequent launch.
hasLiveContexts(keys) returns a Map from every requested opaque key to its
native presence in one reading. Tmux uses the same strict complete context door;
the pane-server host reads all existing generations once through their listings.
A legacy unbound row leaves missing contexts null, and a failed reading rejects.
No protocol upgrade or replacement of existing pane servers is required.
PaneServerHost retains existing panes on the original pipe and creates new
panes only on its -v2 protocol pipe. Creation checks protocol 2 and the advertised terminal
operations on the same connection that creates the pane. Main removed input
locking; the current server advertises inputOwnership:false. A legacy creation
request with requireInputOwnership:true refuses before any program starts. Discovery,
presence, capture and servers() connect only to existing servers. Unadvertised
server PID, version, protocol and operations remain null. Protocol 2 runtime
copies use a separate protocol-v2 directory beneath runtimeDir.
A Windows pane's foreground command (activeCommand) comes from one process
table, read at most every 3 s through supercode's kept process reader
(@volter/supercode-interchange/process-observation-reader, an optional peer that
needs Node 26.8.1's FFI); never a PowerShell or WMI process per reading. Where the
reader is absent, the command is unknown. The runtime copy carries the reader's
package without its npm dependencies, and the generation digest counts the
modules a pane server loads from it by content, so a release that changes none
of them keeps the running server. Process identities (sweep roots, root
identity) are creation FILETIMEs, the reader's Windows birth; the one-shot sweep
the watchdog runs once its host is gone still reads WMI itself.
Old pane operations and viewer grants route to their original server. A
retained server is never started or stopped by this client; when it has no
panes, the client disconnects for its own idle lifecycle. A server without
hasLiveContext refuses presence confirmation. Historical generation readings
do not qualify this generation router or Windows/native first-message delivery.
The substrate was moved from a retired package without behavioral changes.
Its existing home paths, environment variables, and tmux ownership markers stay
compatible. Those files retain Apache-2.0 licensing; see NOTICE-SUBSTRATE and
LICENSE-SUBSTRATE.
The server-side TmuxTerminalHost can discover existing tmux sessions, create a
session from a structured command, capture its display, submit input to a
session it owns, prepare a local tmux
attach-session launch, open that launch through the trusted local-terminal
adapter, and issue a one-use embedded attachment grant. Existing
sessions are read-only by default. Control and close are allowed only for
sessions bearing this host's ownership mark unless the embedding host explicitly
opts into unowned control.
Fast p_* programs can complete before attachment. The host retains a native
creation receipt and the same incarnation's actual exit, and may return a dead
session with ended rather than a missing-session error. Tmux records its
session/server identity and server birth; ConPTY records the entry's own
onExit. Destroying a live pane is not a recorded program exit. An opaque
incarnation survives a catalog refresh so a reused context cannot substitute a
different native pane. sessionCompletion(id) returns a positive observed exit
or null; Tmux keeps 256 creation cursors and ConPTY 256 completed entries.
Tmux completion cursors and log reads are asynchronous. The reader admits only
regular files, opens without waiting for a FIFO writer, and checks the opened
file against the named leaf before and after its bounded 64 KiB tail read.
Only complete lines for the recorded server/session incarnation count. An
unconfirmed handle close retains that handle and refuses later completion
reads with completion_cleanup_unconfirmed.
Missing or replaced evidence remains unknown. A retained older pane server
without this operation stays running and returns unknown.
Windows PaneServerHost creates new panes on its protocol-2 pipe and keeps
existing panes on the unversioned pipe until they finish. The current server
advertises its actual PID, version and supported operations. Exact completion
and presence are required for new creation; missing input ownership remains
unsupported. A retained server is never restarted to gain a capability.
A failed p_* ConPTY pane leaves the listing once its end and last screen are
kept in its server's pane-exit log (pane-exits.log, pane-exits/<pane>.screen),
as tmux panes do; PaneServerHost closes such dead panes on a retained server
of an earlier release that still lists them. A failed pane whose screen could
not be kept stays listed, marked dead, until it is closed.
Completion lookup remembers at most256 exact terminal-to-peer associations,
so a refreshed pane listing cannot redirect a closed incarnation's exit.
teams panes servers reports both serving roles without changing them.
teams panes requests lists the daemon's unanswered requests to each server
(op, pane or terminal, age; sent or waiting for a place), read from the daemon
alone, so it answers while every place is taken. A request ends with its
answer or with its connection; a frame either side cannot parse ends the
connection, so no lost answer leaves a request holding its place.
Servers advertising memory also report their process memory, main-isolate heap,
owned ConPTY output-worker count (including workers still draining), pending
parser units and pane count. Windows reports native private committed bytes,
resident bytes, handles and threads separately. Older servers' memory is null.
teams panes retire-server <pipe> <observed-pid> retires only an empty compatible
server; a changed PID, a retained pane or pending operation refuses the request.
It never ends a pane. Existing older servers leave through their normal idle
lifecycle after their panes finish and clients disconnect.
ConPTY output pauses at 256 Ki UTF-16 code units awaiting xterm and resumes at 64 Ki. The 5,000-line scrollback is unchanged. Pipe frames and queued writes are bounded to 8 MiB, with at most 64 pending requests/viewers per connection. The daemon's client sends at most 64 requests at once and holds up to 1,024 more in order, sending each as an answer frees a place, so one caller's burst delays another's request rather than refusing it. A slow viewer detaches at 4 MiB of queued output and can reattach for the current screen. Closing a pipe or viewer leaves its panes running. Pane cleanup releases its owned output worker even when the program is quiet or native cleanup has already run. Memory lifetime decision.
Windows panes use node-pty 0.15.0, whose native ownership lock fixes concurrent close/exit access to its process-global PTY records. Startup waits for the actual pipe connection and positive process PID, holding initial output until its readers are attached; a quiet program need not print to become usable. Native close investigation and qualification boundary retain the historical heap-corruption evidence and its unmeasured allocation.
Windows input waits for the pipe's write callback, and a bounded queue keeps
each paste and its Enter together with viewer input. Each started write
waits at most five seconds, shortened by its caller deadline; an unanswered
completion is unknown delivery and refuses later writes without ending the
program. A late callback never changes that retained result. An asynchronous
failure
returns pane_input_delivery_unknown with delivery: "unknown"; accepted
bytes cannot be inferred and the input must never be replayed automatically.
The same unknown result covers a completed paste followed by a refused Enter.
A later call refused before writing to an already failed input pipe instead
returns pane_input_unavailable with inputSent: false; it inherits no delivery
claim from the earlier call.
An input-only failure retains the program and output until native exit or
explicit close. The host journal records counts, timing and socket state,
without input text. Transport decision.
ConPTY retains an actual native exit callback even after explicit close removes
its pane; a close request alone creates no completion. Optional hostRuntime
metadata names the serving host instance/PID, entrypoint/module, package-file
version, module-file hash and exit-log destination. These self-reported
diagnostics provide neither kernel birth nor executable attestation. Existing
panes.list carries them only for permitted rows; older hosts remain unknown.
Source correction and historical Windows limits
separate this from proof that a real session's exact tab disappeared.
listWindows({ home, processIds, viewerPanes }) observes Windows Terminal
top-level windows and their UI Automation tabs, including HWND, process birth,
runtime identities, titles and selected state. Named process IDs and exact
fleet.mjs attach pane arguments select process/viewer metadata. A title is a
locator, never a pane ownership receipt. The snapshot has separate start/end
timestamps; it is not an atomic system snapshot. Provider errors or finite
enumeration limits set complete: false and keep their diagnostic records.
The machine exposes the same read as operator-only windows.list and
teams windows list --pids 123,456 --panes p_one,p_two. It compiles the packaged
read-only C# client with Windows' .NET Framework compiler into the owning
product home, records source/binary hashes, then runs it with bounded output
and a deadline. Missing compiler/assemblies or denied execution refuse with
windows_snapshot_unavailable or windows_snapshot_incomplete. No shell or
PowerShell interpreter, ExecutionPolicy change, input, activation or close is
used. Non-Windows hosts refuse as unsupported.
Source and partial product evidence record compilation, one ordinary owned Node version launch and its cleanup failure. Full machine-launch, daemon-restart and Windows qualification remain open. New launch receipts keep connection principal and resolved caller separate; no unknown historical starter is relabeled as a person or session.
Most Volter Harness frontends should use SupercodeTerminalController, which composes that low-level
host with the loopback bridge, persistent context recovery, native Claude Code/Codex handoff, and
harness-aware initial-input delivery. The embedding product supplies allowed browser origins and
optional display-path formatting; it should not create a second terminal registry or scrape agent
prompts itself. TmuxTerminalHost remains public for applications that deliberately need only the
lower-level primitive.
Claude Code and Codex launches with initialInput require the controller option
prepareInitialInputReceipt. A missing provider refuses before creating a terminal.
The host receives the launched terminalSession, harness, full text and cancellation
signal. Through its admitted native-session door it resolves that process's
conversation and checkpoints the native message count before any input is pasted.
It returns a NativeTerminalInputWatch naming harness, sessionId, fromMessage
and a cancellable read({ signal }) method. The reader returns a matching native
user-message observation (messageOffset, role, full text, harness and session
ID), or null while none is visible. Old history, discovery previews and screen
state cannot supply this observation. The host must retain the actual native
conversation binding and honor cancellation; the callback creates no grant or
writer attestation.
Preparation shares the existing five-minute startup/readiness deadline. After
one submission attempt, receipt observation lasts at most ten seconds, with each
read bounded to two seconds. The controller verifies the conversation, checkpoint,
user role and complete text, including Claude's native pasted_content envelope.
An unmatched, unavailable or late receipt leaves an explicit unconfirmed-delivery
error in snapshot().error; no input is repeated. A transport acknowledgement
failure also proceeds to native observation and never restores the composer. The host must decide how to handle an unconfirmed submission.
deliverComposerInput now reports submitted: true after Enter, or
submissionAttempted: true when its acknowledgement fails; delivered remains
false until a caller observes a native receipt. This changes the old Claude result
that inferred delivery from an empty composer. Teams' retained mailbox receipt
queue remains separate. Source checks and qualification limits
record this controller contract; no real native first-input delivery is qualified.
An embedding host may pass an opaque contextKey when it creates a session.
The host stores that association in a namespaced tmux user option and returns it
with future catalog reads, so a semantic conversation can recover its terminal
after the browser or native bridge restarts. The value is application-defined;
native harness session ids, tmux targets, sockets, and process handles should
never be used as context keys.
For a brand-new interactive launch, the native session does not exist when tmux is created.
conversationDiscovery records the pre-launch opaque catalog keys and first user prompt;
reconcileConversationBindings later binds the terminal only when exactly one new descriptor has
the same harness, workspace, and user prompt. Ambiguous matches remain unbound. This recovery
state is bounded, expires after ten minutes, and never exposes a tmux target to the product.
Browser and extension hosts can pair it with TerminalWebSocketBridge, which binds an ephemeral
loopback port, requires an exact configured origin on every WebSocket upgrade, and accepts only
one-use attachment grants. The embedding product supplies its allowed origin and never handles a
tmux socket or target. normalizeTerminalUiState performs the matching untrusted-wire projection
before state reaches the reusable terminal components.
Browser code imports @volter/supercode-terminal/client. It contains only
the terminal WebSocket client and protocol types; it never imports tmux,
node-pty, filesystem, or process APIs.
Frontends that want the default terminal experience can import the optional
Preact components from @volter/supercode-terminal/ui and its tokenized
stylesheet from @volter/supercode-terminal/ui/styles.css. TerminalWorkspace
is the terminal-app surface: retained live tabs, one-click session attachment,
keyboard tab switching, direct terminal focus, connection state, and separate detach/open/stop
actions. TerminalPanel, TerminalViewer, and TerminalPath remain independently reusable for
constrained hosts. The surfaces take
callbacks rather than a transport implementation, so a host can map its own
validated intents without exposing native handles. The heavy xterm runtime is a
dynamic import and is loaded only when a viewer is actually opened.
The workspace deliberately leaves browser-owned Command/Ctrl shortcuts alone. While it has focus,
its default namespace is Option/Alt+Shift: T opens the session menu, D detaches the active tab,
digits 1–9 select tabs, and brackets rotate between tabs.
Hosts with both a fixed simulated viewport and a responsive viewport can pass viewportMode and
onViewportModeChange. The workspace then exposes one compact scale/fit control for writable
attachments; read-only mirrors never offer a control that could reflow the source pane. The full,
evidence-scoped parity boundary is recorded in CAPABILITIES.md.
The terminal canvas and internal layout layers are transparent over one
--sctui-terminal-background backing layer (the Volter brand's terminal.background by default). Embedders
can set that token to any valid transparent or opaque CSS color without forking the component; the
color is intentionally applied once so nested alpha does not compound back into an opaque card.
Colours and fonts default to the Volter brand's roles, read as
var(--volter-<role>, <brand value>): a host that sets --volter-* (the brand's tokens.css)
governs them, and --sctui-* or --scui-* overrides the one it sets. The terminal looks like
Apple's Terminal.app with its Basic profile (the brand's terminal.* roles, font.terminal and
fontSize.terminal: SF Mono 11 where the platform has it, Terminal.app's palette, a steady block
cursor), and like Terminal.app it follows the system's appearance whatever the page's scheme.
styles.css is generated from src/styles.css, which
names each role as brand(<role>); npm run build resolves them.
Safety properties:
- browser actions use opaque catalog ids rather than tmux targets;
- embedded attachment grants are random, short-lived, and consumed once;
- the tmux socket and session target never appear in an embedded grant;
- detaching disposes the ephemeral PTY/WebSocket resources but cannot stop the durable tmux session;
- closing is a separate explicit operation and checks the ownership mark;
- structured commands and argument arrays are passed without shell-string construction.
Use the xterm UI with a browser runtime
The optional /stream and /react/stream entries export TerminalStreamViewer.
They use the same search, links, paste controls, download, status, and keyboard
behavior as TerminalViewer, with a caller-supplied connector instead of a
WebSocket. Import /ui/styles.css and @xterm/xterm/css/xterm.css; install the
xterm, fit, search, and web-links peer packages for this surface.
<TerminalStreamViewer
attachment={{ id: 'workspace-shell', sessionId: 'workspace', baseUrl: '', mode: 'control' }}
connect={(attachment, events, { cols, rows }) => {
// Subscribe to process output, report readiness with events.onOpen(),
// forward output through events.onOutput(data), and report exit/close.
return { write, resize, close: unsubscribe };
}}
convertEol={true}
onReady={({ focus }) => { /* retain focus for the host's terminal tab */ }}
/>connect returns synchronously and must keep its function identity stable for
one attachment. Unmount closes the attachment; the host retains ownership of
process termination. Use convertEol for streams without PTY newline processing;
the default preserves terminal bytes. Theme foreground, cursor and selection through
--sctui-terminal-foreground, --sctui-terminal-cursor and --sctui-terminal-selection-background,
the face and size through --sctui-terminal-font and --sctui-terminal-font-size, and the ANSI palette through
--sctui-terminal-black, -red, -green, -yellow, -blue, -magenta, -cyan, -white and
their -bright-* forms (defaults: the brand's terminal.* roles). xterm reads the resolved colours
when the viewer mounts. /stream does not
load the tmux or WebSocket implementation. Existing TerminalViewer consumers
keep the default WebSocket connector, also exported as /client's
connectTerminal.
Shells over a Docker exec wire
/docker-exec exports dockerExecTerminal, a controller for an environment that
offers Docker's Engine API and no session service: a container, a Conduit
docker/engine-api binding, or a browser tab's container. Each New terminal is
an exec of sh with a TTY. The controller holds the exec's stream and a bounded
buffer of its output, so a view that detaches leaves its shell running and one
that attaches replays the newest output. stop ends a shell or dismisses one
that exited. Nothing outlives the page: Docker offers no way back into an exec's
stream once its socket closes, so say so where the shells are listed.
import { dockerExecTerminal } from '@volter/supercode-terminal/docker-exec';
const shells = dockerExecTerminal({
base: 'https://agent.example/v1.51', containerId,
headers: { authorization: `Bearer ${token}` },
// in a tab, the page's own socket onto the exec's stream
socket: (url) => daemon.socket(url),
});
// shells.getState() and shells.subscribe() feed TerminalWorkspace;
// shells.connector is the viewer's `connect`.
const id = await shells.create();It loads neither xterm nor a UI framework.
