The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat(cli): stream agent terminals through tmux
0xken1581d1923bfb8d
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.tsindex 63a984967..79f9dd201 100644--- a/cli/src/backendSocket.spec.ts+++ b/cli/src/backendSocket.spec.ts@@ -120,6 +120,26 @@ describe('BackendSocket outbound queue', () => {await socket.stop()})+ it('routes e2e control frames to the handshake manager instead of the RPC fallback', async () => {+ const socket = new BackendSocket('token')+ const handle = vi.spyOn(socket.e2ee, 'handleFrame').mockReturnValue(true)+ socket.connect()+ const ws = wsMock.instances[0]+ ws.open()++ const frame = {+ type: 'e2e_setup_claim',+ payload: { requestId: 'setup-1', token: 'signed-setup-token' },+ }+ ws.message({ t: 'down', connId: 'web-1', frame })++ await vi.waitFor(() => expect(handle).toHaveBeenCalledWith('web-1', frame))+ expect(parseSent(ws).some((item) =>+ (item.frame as { type?: string } | undefined)?.type === 'e2e_setup_claim_result',+ )).toBe(false)+ await socket.stop()+ })+it('serves the opaque runtime catalog through the existing models_list RPC', async () => {const socket = new BackendSocket('token')socket.runtimeModelsProvider = async () => [@@ -239,7 +259,7 @@ describe('BackendSocket outbound queue', () => {clients(0)clients(0)clients(1)- expect(changes).toEqual([true, false, true])+ await vi.waitFor(() => expect(changes).toEqual([true, false, true]))await socket.stop()expect(changes).toEqual([true, false, true, false])@@ -260,7 +280,7 @@ describe('BackendSocket outbound queue', () => {expect(drop).not.toHaveBeenCalled()ws.message({ t: 'down', connId: '', frame: { type: '__clients', payload: { commander: 0 } } })- expect(drop).toHaveBeenCalledWith('device')+ await vi.waitFor(() => expect(drop).toHaveBeenCalledWith('device'))await socket.stop()})diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 9181a75f5..62865a849 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -44,6 +44,7 @@ import { readDevinMessages } from './engines/devin/reader.js'import { readOpencodeMessages } from './engines/opencode/reader.js'import { readKiloMessages } from './engines/kilo/reader.js'import { E2eeManager, type PairResult } from './lib/e2ee/manager.js'+import type { TerminalStreamManager } from './lib/terminalStreamManager.js'import { ENCRYPTED_RPC_RESULT_TYPES, isEncryptedDownType, isWrapped } from './lib/e2ee/core.js'import { DEVICE_RECENT_SAFE_FRAME_BYTES, fitRecentReplyPayloadForDevice } from './lib/deviceRecentTrim.js'import { shouldReplayCommander } from './lib/commanderReplay.js'@@ -247,6 +248,8 @@ export class BackendSocket {private droppedSinceLog = 0private heartbeat: NodeJS.Timeout | null = nullprivate appPing: NodeJS.Timeout | null = null+ private readonly downChains = new Map<string, Promise<void>>()+ private terminalStreams: TerminalStreamManager | null = nullprivate isAlive = trueprivate onStatus: (connected: boolean) => void/** Cross-instance commander (device) client count, from backend `__clients` frames. */@@ -356,6 +359,10 @@ export class BackendSocket {})}+ setTerminalStreamManager(manager: TerminalStreamManager): void {+ this.terminalStreams = manager+ }+/** Run CPace pairing for a code entered via `harness pair <code>` (delegated to the manager). */pair(code: string): Promise<PairResult> {return this.e2ee.onPair(code)@@ -412,8 +419,7 @@ export class BackendSocket {// A malformed/hostile down-frame (bad __e2e envelope, bad ephemeral key) can throw in the// pre-`try` part of dispatchDown; without this .catch that becomes an unhandledRejection and the// daemon exits. Contain it: log, drop the frame, keep the socket alive.- void this.dispatchDown(env_.frame, env_.connId ?? '').catch((err) =>- console.error('[backend] down-frame dispatch failed:', err instanceof Error ? err.message : err))+ this.enqueueDown(env_.frame, env_.connId ?? '')}})@@ -428,6 +434,7 @@ export class BackendSocket {// completing during the gap burns a `claude -p` recap that goes nowhere. attachAdapter always// re-pushes the true count via recomputeAndSendClients on reconnect (and 0→N re-fires the replay).this.setCommanderCount(0, null) // active count is unknown until the next __clients snapshot+ void this.terminalStreams?.closeAll('backend disconnected')this.replayCommanderOnNextSnapshot = truethis.onStatus(false)if (this.closed) return@@ -460,6 +467,7 @@ export class BackendSocket {this.closed = trueif (this.heartbeat) clearInterval(this.heartbeat)if (this.appPing) clearInterval(this.appPing)+ await this.terminalStreams?.stop()try { this.ws?.close() } catch { /* ignore */ }this.ws = null}@@ -476,6 +484,19 @@ export class BackendSocket {this.enqueue({ t: 'up', targetConnId: connId, frame })}+ /** Pairwise terminal output is never queued across reconnect: the stream/lease is closed on link loss. */+ sendTerminalTo(connId: string, type: string, payload: Record<string, unknown>): boolean {+ const frame = this.e2ee.wrapTarget(connId, type, payload)+ if (!frame) return false+ return this.sendBestEffort({+ t: 'up',+ targetConnId: connId,+ webEligible: true,+ commanderEligible: false,+ frame,+ })+ }+/** Send a user-level notification to every logged-in browser that owns this machine. */sendUser(frame: Frame): void {this.enqueue({ t: 'up', userEligible: true, webEligible: false, frame })@@ -500,11 +521,27 @@ export class BackendSocket {this.drainQueue()}- private sendBestEffort(msg: OutboundEnvelope): void {+ private sendBestEffort(msg: OutboundEnvelope): boolean {const data = JSON.stringify(msg)if (this.ws && this.ws.readyState === WebSocket.OPEN) {- try { this.ws.send(data) } catch { /* ignore */ }+ try { this.ws.send(data); return true } catch { /* ignore */ }}+ return false+ }++ private enqueueDown(frame: Frame, connId: string): void {+ const key = connId || '__backend__'+ const previous = this.downChains.get(key) ?? Promise.resolve()+ const next = previous+ .catch(() => { /* prior failure is already logged */ })+ .then(() => this.dispatchDown(frame, connId))+ .catch((err) => {+ console.error('[backend] down-frame dispatch failed:', err instanceof Error ? err.message : err)+ })+ .finally(() => {+ if (this.downChains.get(key) === next) this.downChains.delete(key)+ })+ this.downChains.set(key, next)}private drainQueue(): void {@@ -610,7 +647,11 @@ export class BackendSocket {}// Logged AFTER the unwrap above, so a down-frame reads as what the client actually asked for rather// than as an opaque __e2e envelope.- if (env.LOG_FRAMES) logFrame('←', connId ? `conn:${sid(connId)}` : 'backend', frame)+ // Terminal frames contain raw keystrokes, paste text and screen bytes after+ // unwrap. Never pass them to the frame logger, even in diagnostic mode.+ if (env.LOG_FRAMES && !type.startsWith('terminal_')) {+ logFrame('←', connId ? `conn:${sid(connId)}` : 'backend', frame)+ }const reply = (t: string, rid: unknown, p: Record<string, unknown>): void => this.emitReply(connId, t, rid, p)// Cross-instance client snapshot. Generation detects leave/join cycles that coalesce to the same// count; count rise remains the compatibility fallback for older backends.@@ -653,6 +694,11 @@ export class BackendSocket {const payload = (frame.payload ?? {}) as Record<string, unknown>const requestId = payload.requestId+ if (type.startsWith('terminal_')) {+ if (this.terminalStreams) await this.terminalStreams.handleFrame(connId, type, payload)+ return+ }+try {switch (type) {case 'device_e2ee_pair':diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex eee5f86df..3119f7fe2 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -42,6 +42,7 @@ import {} from './lib/herdrSessions.js'import { ALL_TERMINAL_BACKENDS } from './config/terminalConfig.js'import { TerminalBackendCoordinator } from './lib/terminalBackendCoordinator.js'+import { TerminalStreamManager } from './lib/terminalStreamManager.js'import { terminalRouteKey, terminalRuntimeLabel } from './lib/terminalRuntime.js'import { TerminalAgentReconciler } from './lib/terminalAgentReconciler.js'import { processRows, type DiscoveredTerminalAgent } from './lib/terminalAgentDiscovery.js'@@ -766,6 +767,13 @@ async function runForeground(token: string): Promise<void> {})}, computerId())backendRef = backend+ const terminalStreams = new TerminalStreamManager({+ terminals,+ resolveAgent: (agentId) => registry.resolve(agentId),+ sendTarget: (connId, type, payload) => backend.sendTerminalTo(connId, type, payload),+ streamingAvailable: tmuxBackend != null,+ })+ backend.setTerminalStreamManager(terminalStreams)// Per-session web turn-lifecycle state; the device mirror keeps its own state + recap.const turnStates = new Map<string, TurnState>()diff --git a/cli/src/lib/e2ee/core.test.ts b/cli/src/lib/e2ee/core.test.tsindex 61e358b9d..6c817d5bb 100644--- a/cli/src/lib/e2ee/core.test.ts+++ b/cli/src/lib/e2ee/core.test.ts@@ -137,6 +137,7 @@ describe('e2ee core — codes + fingerprint + classification', () => {expect(C.ENCRYPTED_RPC_RESULT_TYPES.has('agent_update_result')).toBe(true)expect(C.isEncryptedDownType('models_list')).toBe(true)expect(C.ENCRYPTED_RPC_RESULT_TYPES.has('models_list_result')).toBe(true)+ expect(C.isEncryptedDownType('terminal_input')).toBe(true)})it('gates question_response, which the device encrypts', () => {@@ -186,6 +187,6 @@ describe('e2ee core — interop keystone', () => {it('core.ts still hashes to the pinned value shared with the other implementations', () => {const here = dirname(fileURLToPath(import.meta.url))const actual = createHash('sha256').update(readFileSync(join(here, 'core.ts'))).digest('hex')- expect(actual).toBe('ef9c3f25f41bc4ccece8d082aa9c366037399de9b462d5106c165ce25d0f9bb0')+ expect(actual).toBe('e08eafcdd0a820992fee2ba5e598b94db9877d4e16c8bea8cba49a2690071db7')})})diff --git a/cli/src/lib/e2ee/core.ts b/cli/src/lib/e2ee/core.tsindex dc5c2f587..cfa52f2ed 100644--- a/cli/src/lib/e2ee/core.ts+++ b/cli/src/lib/e2ee/core.ts@@ -363,6 +363,10 @@ export const ENCRYPTED_DOWN_TYPES = new Set<string>(['agent_create', 'agent_delete', 'agent_recent', 'agent_update', 'agent_files', 'agent_read_file','device_e2ee_pair', 'e2ee_pairings_list', 'e2ee_pairing_unpair','e2ee_pairings_unpair_all', 'e2ee_browser_link_create',+ // Remote terminal control is always pairwise E2EE. The relay may route by outer type/connId but must+ // never see agent ids, terminal bytes, dimensions, sequence numbers, or capability metadata.+ 'terminal_capabilities', 'terminal_open', 'terminal_alive', 'terminal_ack', 'terminal_input',+ 'terminal_resize', 'terminal_resync', 'terminal_close',])export function isEncryptedUpType(t: string): boolean { return ENCRYPTED_UP_TYPES.has(t) }export function isEncryptedRpcResultType(t: string): boolean { return ENCRYPTED_RPC_RESULT_TYPES.has(t) }diff --git a/cli/src/lib/e2ee/manager.ts b/cli/src/lib/e2ee/manager.tsindex fbc6f2b82..067a6665c 100644--- a/cli/src/lib/e2ee/manager.ts+++ b/cli/src/lib/e2ee/manager.ts@@ -249,7 +249,8 @@ export class E2eeManager {return Buffer.byteLength(JSON.stringify({ type: resultType, payload: wrapped }), 'utf8')}- private wrapTarget(connId: string, type: string, payload: Record<string, unknown>): Frame | null {+ /** Pairwise-encrypt a connection-targeted non-RPC frame (terminal ready/output/keyframe/error). */+ wrapTarget(connId: string, type: string, payload: Record<string, unknown>): Frame | null {const s = this.sessions.get(connId)if (!s) return nullconst wrapped = C.wrapPayload(s.s2c, 'p', s.s2cCounter++, type, undefined, payload)diff --git a/cli/src/lib/engineBin.ts b/cli/src/lib/engineBin.tsindex 43d79bb68..519a166f9 100644--- a/cli/src/lib/engineBin.ts+++ b/cli/src/lib/engineBin.ts@@ -8,13 +8,11 @@import { accessSync, constants, realpathSync, statSync } from 'node:fs'import { delimiter, isAbsolute, join, normalize, sep } from 'node:path'import { env } from '../config/env.js'-import type { AgentEngine } from '../engines/types.js'+import { ENGINES, type AgentEngine } from '../engines/types.js'-/** Every engine the adapter can discover and drive. */-export const ENGINES: readonly AgentEngine[] = [- 'claude', 'codex', 'cursor', 'opencode', 'pi', 'hermes', 'commandcode', 'devin', 'muse', 'amp', 'kilo', 'grok',- 'agy', 'copilot',-] as const+// Keep this historical import surface for callers, but never duplicate the+// catalog here. `engines/types.ts` is the one iterable source of truth.+export { ENGINES }/** Public vendor command shown to users and matched by the real-binary smoke matrix. */export const ENGINE_CLI_COMMANDS: Readonly<Record<AgentEngine, string>> = {diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.tsindex d0203d3b1..2f607c9af 100644--- a/cli/src/lib/registry.ts+++ b/cli/src/lib/registry.ts@@ -35,7 +35,7 @@ import { join, basename, dirname, relative } from 'path'import { uptime } from 'os'import { env } from '../config/env.js'import { readCodexRolloutMeta, resolveCodexRollout } from '../engines/codex/rollout.js'-import type { AgentEngine } from '../engines/types.js'+import { ENGINES, type AgentEngine } from '../engines/types.js'import { commandcodeTranscriptPath } from '../engines/commandcode/transcript.js'import { agyTranscriptPath } from '../engines/agy/session.js'import { copilotTranscriptPath } from '../engines/copilot/session.js'@@ -144,10 +144,13 @@ const NAME_OVERRIDES = new Map<string, string>()const PANE_RE = /^%\d+$/const GROK_SESSION_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i-const AGENT_ENGINES = new Set<AgentEngine>([- 'claude', 'codex', 'cursor', 'opencode', 'pi', 'hermes', 'commandcode', 'devin', 'muse', 'amp', 'kilo', 'grok',- 'agy', 'copilot',-])+const AGENT_ENGINES: ReadonlySet<string> = new Set(ENGINES)++function normalizedAgentEngine(value: unknown): AgentEngine {+ return typeof value === 'string' && AGENT_ENGINES.has(value)+ ? value as AgentEngine+ : 'claude'+}const LOCK_WAIT_MS = 20const LOCK_ATTEMPTS = 100@@ -632,7 +635,7 @@ class Registry {}let changed = falsefor (const raw of Array.isArray(arr) ? arr : []) {- const engine: AgentEngine = raw?.engine === 'codex' || raw?.engine === 'cursor' || raw?.engine === 'opencode' || raw?.engine === 'pi' || raw?.engine === 'hermes' || raw?.engine === 'commandcode' || raw?.engine === 'devin' || raw?.engine === 'muse' || raw?.engine === 'amp' || raw?.engine === 'kilo' || raw?.engine === 'grok' || raw?.engine === 'agy' || raw?.engine === 'copilot' ? raw.engine : 'claude'+ const engine = normalizedAgentEngine(raw?.engine)const runtimes = normalizedRuntimes(raw?.runtimes, raw?.tmuxPane)const pane = tmuxProjection(runtimes)let transcriptPath =@@ -867,8 +870,7 @@ class Registry {const transcriptPath = input.transcriptPathconst sessionId =input.sessionId || (transcriptPath ? basename(transcriptPath).replace(/\.jsonl$/, '') : '')- const engine: AgentEngine =- input.engine === 'codex' || input.engine === 'cursor' || input.engine === 'opencode' || input.engine === 'pi' || input.engine === 'hermes' || input.engine === 'commandcode' || input.engine === 'devin' || input.engine === 'muse' || input.engine === 'amp' || input.engine === 'kilo' || input.engine === 'grok' || input.engine === 'agy' || input.engine === 'copilot' ? input.engine : 'claude'+ const engine = normalizedAgentEngine(input.engine)const pane = input.tmuxPane// Hooks carry process metadata, not ownership. The already-discovered pane+engine process chooses the// agent; an optional legacy launcherId is intentionally ignored.diff --git a/cli/src/lib/terminalBackend.ts b/cli/src/lib/terminalBackend.tsindex e8d2dc342..169363330 100644--- a/cli/src/lib/terminalBackend.ts+++ b/cli/src/lib/terminalBackend.ts@@ -9,6 +9,9 @@ import type {TerminalProcessExpectation,TerminalReadResult,TerminalRuntimeRef,+ TerminalStreamHandle,+ TerminalStreamSink,+ TerminalStreamSize,RuntimeValidation,} from './terminalTypes.js'@@ -29,4 +32,12 @@ export interface TerminalBackend<Ref extends TerminalRuntimeRef = TerminalRuntimsendKey(runtime: Ref, key: TerminalLogicalKey): Promise<TerminalActionResult>setTitle(runtime: Ref, title: string): Promise<TerminalActionResult>notify(runtime: Ref, title: string, body: string): Promise<TerminalActionResult>++ /** Byte streaming is optional per backend. MVP is implemented by tmux; Herdr remains capture-only. */+ openStream?(+ runtime: Ref,+ expected: TerminalProcessExpectation,+ size: TerminalStreamSize,+ sink: TerminalStreamSink,+ ): Promise<TerminalReadResult<TerminalStreamHandle<Ref>>>}diff --git a/cli/src/lib/terminalBackendCoordinator.ts b/cli/src/lib/terminalBackendCoordinator.tsindex 676755c20..a52299ed8 100644--- a/cli/src/lib/terminalBackendCoordinator.ts+++ b/cli/src/lib/terminalBackendCoordinator.ts@@ -9,6 +9,9 @@ import {type TerminalLogicalKey,type TerminalReadResult,type TerminalRuntimeRef,+ type TerminalStreamHandle,+ type TerminalStreamSink,+ type TerminalStreamSize,} from './terminalTypes.js'export interface TerminalControlLease {@@ -181,6 +184,27 @@ export class TerminalBackendCoordinator {return backend ? backend.capture(lease.runtime, options) : { state: 'failed', reason: 'leased terminal backend is disabled' }}+ /** Open a byte stream on the first validated streaming-capable runtime. MVP deliberately skips Herdr. */+ async openStream(+ session: RegisteredSession,+ size: TerminalStreamSize,+ sink: TerminalStreamSink,+ ): Promise<TerminalReadResult<TerminalStreamHandle>> {+ if (!session.active) return { state: 'failed', reason: 'terminal agent is dormant' }+ let reason = 'TERMINAL_RUNTIME_UNAVAILABLE'+ for (const runtime of this.orderedRuntimes(session)) {+ const backend = this.backendFor(runtime)+ if (!backend?.openStream) continue+ const result = await backend.openStream(runtime, {+ engine: session.engine,+ processIdentity: session.processIdentity ?? undefined,+ }, size, sink)+ if (result.state === 'succeeded') return result as TerminalReadResult<TerminalStreamHandle>+ reason = result.reason+ }+ return { state: 'failed', reason }+ }+typeLiteralLease(lease: TerminalControlLease, text: string): Promise<TerminalActionResult> {const backend = this.backendFor(lease.runtime)return backenddiff --git a/cli/src/lib/terminalStreamManager.spec.ts b/cli/src/lib/terminalStreamManager.spec.tsnew file mode 100644index 000000000..9b0d712e7--- /dev/null+++ b/cli/src/lib/terminalStreamManager.spec.ts@@ -0,0 +1,218 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { ENGINES } from '../engines/types.js'+import type { RegisteredSession } from './registry.js'+import { TerminalStreamManager, terminalEngineCapabilities } from './terminalStreamManager.js'+import { TERMINAL_ACTION_SUCCEEDED, type TerminalStreamHandle, type TerminalStreamSink } from './terminalTypes.js'+import type { TerminalBackendCoordinator } from './terminalBackendCoordinator.js'++class FakeStream implements TerminalStreamHandle {+ readonly runtime = { backend: 'tmux' as const, paneId: '%1' }+ writes: Uint8Array[] = []+ sizes: Array<{ cols: number; rows: number }> = []+ closed = false+ snapshots = 0+ snapshotHistory: number[] = []+ snapshotBytes = Buffer.from('\u001bcfixture')++ async snapshot(historyLines: number): Promise<{ state: 'succeeded'; value: { bytes: Uint8Array; cols: number; rows: number } }> {+ this.snapshots+++ this.snapshotHistory.push(historyLines)+ return { state: 'succeeded', value: { bytes: this.snapshotBytes, cols: 120, rows: 40 } }+ }+ async writeRaw(bytes: Uint8Array) { this.writes.push(bytes); return TERMINAL_ACTION_SUCCEEDED }+ async resize(size: { cols: number; rows: number }) { this.sizes.push(size); return TERMINAL_ACTION_SUCCEEDED }+ async close(): Promise<void> { this.closed = true }+}++function session(engine: string = 'codex', agentId = 'agent-1'): RegisteredSession {+ return {+ agentId, sessionId: `session-${agentId}`, engine, active: true,+ registeredAt: Date.now(), updatedAt: Date.now(), runtimes: [{ backend: 'tmux', paneId: '%1' }],+ primaryRuntimeKey: 'tmux:default:%1',+ } as unknown as RegisteredSession+}++describe('TerminalStreamManager', () => {+ let sink: TerminalStreamSink | null+ let stream: FakeStream+ let sent: Array<{ connId: string; type: string; payload: Record<string, unknown> }>+ let manager: TerminalStreamManager+ let agents: Map<string, RegisteredSession>++ beforeEach(() => {+ vi.useFakeTimers()+ sink = null+ stream = new FakeStream()+ sent = []+ agents = new Map([['agent-1', session()]])+ const terminals = {+ openStream: async (_session: RegisteredSession, _size: unknown, nextSink: TerminalStreamSink) => {+ sink = nextSink+ return { state: 'succeeded' as const, value: stream }+ },+ } as unknown as TerminalBackendCoordinator+ manager = new TerminalStreamManager({+ terminals,+ resolveAgent: (id) => agents.get(id),+ sendTarget: (connId, type, payload) => { sent.push({ connId, type, payload }); return true },+ streamingAvailable: true,+ now: () => Date.now(),+ })+ })++ afterEach(async () => {+ await manager.stop()+ vi.useRealTimers()+ })++ it('publishes the complete engine catalog without a client whitelist', async () => {+ await manager.handleFrame('web-1', 'terminal_capabilities', { requestId: 'r1' })+ const result = sent.at(-1)!+ expect(result.type).toBe('terminal_capabilities_result')+ expect((result.payload.engines as Array<{ id: string }>).map((row) => row.id)).toEqual([...ENGINES])+ })++ it('uses the same generic path for every current engine', async () => {+ for (const [index, engine] of ENGINES.entries()) {+ const agentId = `agent-generic-${index}`+ agents.set(agentId, session(engine, agentId))+ await manager.handleFrame('web-1', 'terminal_open', {+ requestId: `open-${index}`, protocolVersion: 1, agentId, cols: 100, rows: 30,+ })+ const ready = sent.findLast((frame) => frame.type === 'terminal_ready')+ expect(ready?.payload.agentId).toBe(agentId)+ expect(ready?.payload.engineId).toBe(engine)+ }+ })++ it('automatically publishes a future engine once the source catalog contains it', () => {+ const futureCatalog = [...ENGINES, 'future-engine-added-later']+ expect(terminalEngineCapabilities(true, futureCatalog).map((row) => row.id)).toEqual(futureCatalog)+ })++ it('fails closed for an engine that is not in the current source catalog', async () => {+ const unsafe = session('claude') as unknown as { engine: string }+ unsafe.engine = 'hostile-unregistered-engine'+ agents.set('agent-1', unsafe as unknown as RegisteredSession)+ await manager.handleFrame('web-1', 'terminal_open', {+ requestId: 'unsupported', protocolVersion: 1, agentId: 'agent-1', cols: 100, rows: 30,+ })+ expect(sent.at(-1)?.payload.code).toBe('TERMINAL_ENGINE_UNSUPPORTED')+ })++ it('rejects an unknown agent without opening a stream', async () => {+ await manager.handleFrame('web-1', 'terminal_open', {+ requestId: 'missing', protocolVersion: 1, agentId: 'does-not-exist', cols: 100, rows: 30,+ })+ expect(sent.at(-1)?.payload.code).toBe('TERMINAL_AGENT_NOT_FOUND')+ })++ it('opens with a keyframe, streams coalesced output, and writes ordered raw input', async () => {+ await manager.handleFrame('web-1', 'terminal_open', {+ requestId: 'open-1', protocolVersion: 1, agentId: 'agent-1', cols: 120, rows: 40, compression: ['zlib'],+ })+ expect(sent.map((frame) => frame.type)).toEqual(['terminal_ready', 'terminal_keyframe'])+ const streamId = sent[0].payload.streamId as string++ sink!.onData(Buffer.from('hello'))+ await vi.advanceTimersByTimeAsync(8)+ expect(sent.at(-1)?.type).toBe('terminal_output')+ expect(sent.at(-1)?.payload.seq).toBe(1)++ await manager.handleFrame('web-1', 'terminal_input', {+ streamId, inputSeq: 0, data: Buffer.from('abc').toString('base64'),+ })+ expect(Buffer.from(stream.writes[0]).toString()).toBe('abc')+ await manager.handleFrame('web-1', 'terminal_input', {+ streamId, inputSeq: 2, data: Buffer.from('out-of-order').toString('base64'),+ })+ expect(stream.writes).toHaveLength(1)+ expect(sent.at(-1)?.payload.code).toBe('TERMINAL_INPUT_INVALID')++ const mouse = Buffer.from('\u001b[<0;12;8M')+ await manager.handleFrame('web-1', 'terminal_input', {+ streamId, inputSeq: 1, data: mouse.toString('base64'),+ })+ expect(Buffer.from(stream.writes.at(-1)!).equals(mouse)).toBe(true)++ await manager.handleFrame('web-1', 'terminal_resize', {+ streamId, resizeSeq: 0, cols: 140, rows: 50,+ })+ expect(stream.sizes.at(-1)).toEqual({ cols: 140, rows: 50 })+ })++ it('rejects a second controller and expires the first lease after heartbeat timeout', async () => {+ await manager.handleFrame('web-1', 'terminal_open', {+ requestId: 'open-1', protocolVersion: 1, agentId: 'agent-1', cols: 100, rows: 30,+ })+ await manager.handleFrame('web-2', 'terminal_open', {+ requestId: 'open-2', protocolVersion: 1, agentId: 'agent-1', cols: 100, rows: 30,+ })+ expect(sent.at(-1)?.payload.code).toBe('CONTROL_LEASE_HELD')++ await vi.advanceTimersByTimeAsync(30_000)+ expect(stream.closed).toBe(true)+ expect(sent.some((frame) => frame.type === 'terminal_closed' && frame.payload.reason === 'heartbeat timeout')).toBe(true)+ })++ it('rejects a second agent alias that resolves to the same tmux pane', async () => {+ agents.set('agent-alias', session('claude', 'agent-alias'))+ await manager.handleFrame('web-1', 'terminal_open', {+ requestId: 'open-1', protocolVersion: 1, agentId: 'agent-1', cols: 100, rows: 30,+ })+ await manager.handleFrame('web-2', 'terminal_open', {+ requestId: 'open-2', protocolVersion: 1, agentId: 'agent-alias', cols: 100, rows: 30,+ })+ expect(sent.at(-1)?.payload.code).toBe('CONTROL_LEASE_HELD')+ })++ it('uses frequent ACKs rather than the five-second heartbeat for output backpressure', async () => {+ await manager.handleFrame('web-1', 'terminal_open', {+ requestId: 'open-1', protocolVersion: 1, agentId: 'agent-1', cols: 100, rows: 30,+ })+ const streamId = sent[0].payload.streamId as string+ for (let i = 0; i < 40; i++) {+ sink!.onData(Buffer.alloc(32 * 1024, i))+ const output = sent.at(-1)!+ expect(output.type).toBe('terminal_output')+ await manager.handleFrame('web-1', 'terminal_ack', { streamId, lastSeq: output.payload.seq })+ }+ expect(sent.filter((frame) => frame.type === 'terminal_keyframe')).toHaveLength(1)+ })++ it('bounds unacked output by replacing the backlog with a keyframe', async () => {+ await manager.handleFrame('web-1', 'terminal_open', {+ requestId: 'open-1', protocolVersion: 1, agentId: 'agent-1', cols: 100, rows: 30,+ })+ for (let i = 0; i < 33; i++) sink!.onData(Buffer.alloc(32 * 1024, i))+ await vi.advanceTimersByTimeAsync(1)+ expect(stream.snapshots).toBeGreaterThanOrEqual(2)+ expect(sent.filter((frame) => frame.type === 'terminal_keyframe').length).toBeGreaterThanOrEqual(2)+ })++ it('fails closed instead of emitting an oversized doubly-base64 keyframe', async () => {+ stream.snapshotBytes = Buffer.alloc(241 * 1024, 0x61)+ await manager.handleFrame('web-1', 'terminal_open', {+ requestId: 'oversized', protocolVersion: 1, agentId: 'agent-1', cols: 100, rows: 30,+ })+ expect(stream.snapshotHistory).toEqual([1_000, 500, 250, 100, 0])+ expect(sent.some((frame) => frame.type === 'terminal_keyframe')).toBe(false)+ expect(sent.findLast((frame) => frame.type === 'terminal_error')?.payload.code)+ .toBe('TERMINAL_SNAPSHOT_TOO_LARGE')+ expect(stream.closed).toBe(true)+ })++ it('disconnect cleanup closes the stream and releases the controller', async () => {+ await manager.handleFrame('web-1', 'terminal_open', {+ requestId: 'open-1', protocolVersion: 1, agentId: 'agent-1', cols: 100, rows: 30,+ })+ await manager.closeConnection('web-1')+ expect(stream.closed).toBe(true)+ const replacement = new FakeStream()+ stream = replacement+ await manager.handleFrame('web-2', 'terminal_open', {+ requestId: 'open-2', protocolVersion: 1, agentId: 'agent-1', cols: 100, rows: 30,+ })+ expect(sent.at(-2)?.type).toBe('terminal_ready')+ })+})diff --git a/cli/src/lib/terminalStreamManager.ts b/cli/src/lib/terminalStreamManager.tsnew file mode 100644index 000000000..61b44c1f1--- /dev/null+++ b/cli/src/lib/terminalStreamManager.ts@@ -0,0 +1,483 @@+import { randomUUID } from 'node:crypto'+import { deflateSync } from 'node:zlib'+import { ENGINES } from '../engines/types.js'+import type { RegisteredSession } from './registry.js'+import type { TerminalBackendCoordinator } from './terminalBackendCoordinator.js'+import { terminalPlacementKey, terminalRouteKey } from './terminalRuntime.js'+import type { TerminalStreamHandle, TerminalStreamSize } from './terminalTypes.js'++type FramePayload = Record<string, unknown>++const PROTOCOL_VERSION = 1+const HEARTBEAT_TIMEOUT_MS = 30_000+const OUTPUT_FLUSH_MS = 8+const OUTPUT_CHUNK_BYTES = 32 * 1024+const INPUT_MAX_BYTES = 64 * 1024+const MAX_UNACKED_FRAMES = 256+const MAX_UNACKED_BYTES = 1024 * 1024+// Terminal data is base64 inside the clear payload, then the entire E2EE+// ciphertext is base64 again. Keep enough headroom below Backend's 512 KiB+// outer-envelope limit for both JSON layers, AEAD tag and routing fields.+const KEYFRAME_MAX_BYTES = 240 * 1024+const KEYFRAME_HISTORY_ATTEMPTS = [1_000, 500, 250, 100, 0] as const+const TERMINAL_ENGINES: ReadonlySet<string> = new Set(ENGINES)++interface PendingOutput {+ seq: number+ bytes: number+}++interface ActiveStream {+ connId: string+ streamId: string+ agentId: string+ engineId: string+ placementKey: string+ handle: TerminalStreamHandle+ compression: 'none' | 'zlib'+ expiresAt: number+ nextSeq: number+ lastInputSeq: number+ lastResizeSeq: number+ pending: PendingOutput[]+ pendingBytes: number+ output: Buffer[]+ outputBytes: number+ flushTimer: ReturnType<typeof setTimeout> | null+ snapshotting: boolean+ resyncing: boolean+ closing: boolean+}++export interface TerminalStreamManagerDeps {+ terminals: TerminalBackendCoordinator+ resolveAgent: (agentId: string) => RegisteredSession | undefined+ sendTarget: (connId: string, type: string, payload: FramePayload) => boolean+ streamingAvailable: boolean+ now?: () => number+}++function sizeFrom(payload: FramePayload): TerminalStreamSize | null {+ const cols = Number(payload.cols)+ const rows = Number(payload.rows)+ if (!Number.isSafeInteger(cols) || !Number.isSafeInteger(rows) || cols < 40 || cols > 300 || rows < 12 || rows > 120) return null+ return { cols, rows }+}++function strictBase64(raw: unknown): Buffer | null {+ if (typeof raw !== 'string' || raw.length === 0 || raw.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(raw)) return null+ const bytes = Buffer.from(raw, 'base64')+ return bytes.toString('base64') === raw ? bytes : null+}++function encoded(bytes: Uint8Array, compression: 'none' | 'zlib'): { encoding: 'none' | 'zlib'; data: string; plainBytes: number } {+ const raw = Buffer.from(bytes)+ if (compression === 'zlib' && raw.length > 1024) {+ const compressed = deflateSync(raw, { level: 1 })+ if (compressed.length < raw.length) return { encoding: 'zlib', data: compressed.toString('base64'), plainBytes: raw.length }+ }+ return { encoding: 'none', data: raw.toString('base64'), plainBytes: raw.length }+}++export function terminalEngineCapabilities(+ streamingAvailable: boolean,+ engines: readonly string[] = ENGINES,+): Array<{ id: string; terminalStreaming: boolean; unavailableReason?: string }> {+ return engines.map((id) => ({+ id,+ terminalStreaming: streamingAvailable,+ ...(!streamingAvailable ? { unavailableReason: 'tmux streaming backend unavailable' } : {}),+ }))+}++export class TerminalStreamManager {+ private readonly streams = new Map<string, ActiveStream>()+ private readonly controllerByAgent = new Map<string, string>()+ private readonly controllerByPlacement = new Map<string, string>()+ private readonly now: () => number+ private readonly expiryTimer: ReturnType<typeof setInterval>++ constructor(private readonly deps: TerminalStreamManagerDeps) {+ this.now = deps.now ?? (() => Date.now())+ this.expiryTimer = setInterval(() => this.expireLeases(), 5_000)+ this.expiryTimer.unref?.()+ }++ async handleFrame(connId: string, type: string, payload: FramePayload): Promise<boolean> {+ switch (type) {+ case 'terminal_capabilities':+ this.capabilities(connId, payload.requestId)+ return true+ case 'terminal_open':+ await this.open(connId, payload)+ return true+ case 'terminal_alive':+ this.alive(connId, payload)+ return true+ case 'terminal_ack':+ this.ack(connId, payload)+ return true+ case 'terminal_input':+ await this.input(connId, payload)+ return true+ case 'terminal_resize':+ await this.resize(connId, payload)+ return true+ case 'terminal_resync':+ await this.resyncRequested(connId, payload)+ return true+ case 'terminal_close':+ await this.closeRequested(connId, payload)+ return true+ default:+ return false+ }+ }++ private capabilities(connId: string, requestId: unknown): void {+ this.deps.sendTarget(connId, 'terminal_capabilities_result', {+ requestId,+ protocolVersion: PROTOCOL_VERSION,+ backend: 'tmux',+ available: this.deps.streamingAvailable,+ features: {+ rawInput: true,+ resize: true,+ mouse: true,+ keyframe: true,+ compression: ['none', 'zlib'],+ },+ engines: terminalEngineCapabilities(this.deps.streamingAvailable),+ })+ }++ private sendError(connId: string, code: string, options: { streamId?: string; requestId?: unknown; message?: string } = {}): void {+ this.deps.sendTarget(connId, 'terminal_error', {+ protocolVersion: PROTOCOL_VERSION,+ code,+ ...options,+ })+ }++ private async open(connId: string, payload: FramePayload): Promise<void> {+ const requestId = payload.requestId+ if (payload.protocolVersion !== PROTOCOL_VERSION) {+ this.sendError(connId, 'TERMINAL_PROTOCOL_UNSUPPORTED', { requestId })+ return+ }+ const agentId = typeof payload.agentId === 'string' ? payload.agentId : ''+ const size = sizeFrom(payload)+ if (!agentId || !size) {+ this.sendError(connId, 'TERMINAL_OPEN_INVALID', { requestId })+ return+ }+ if (!this.deps.streamingAvailable) {+ this.sendError(connId, 'TERMINAL_RUNTIME_UNAVAILABLE', { requestId })+ return+ }+ const session = this.deps.resolveAgent(agentId)+ if (!session) {+ this.sendError(connId, 'TERMINAL_AGENT_NOT_FOUND', { requestId })+ return+ }+ if (!TERMINAL_ENGINES.has(session.engine)) {+ this.sendError(connId, 'TERMINAL_ENGINE_UNSUPPORTED', { requestId })+ return+ }+ const controller = this.controllerByAgent.get(session.agentId)+ if (controller && controller !== connId) {+ this.sendError(connId, 'CONTROL_LEASE_HELD', { requestId })+ return+ }+ const streamRuntime = session.runtimes.find((runtime) => runtime.backend === 'tmux'+ && terminalRouteKey(runtime) === session.primaryRuntimeKey)+ ?? session.runtimes.find((runtime) => runtime.backend === 'tmux')+ if (!streamRuntime) {+ this.sendError(connId, 'TERMINAL_RUNTIME_UNAVAILABLE', { requestId })+ return+ }+ const reservedPlacement = terminalPlacementKey(streamRuntime)+ const placementController = this.controllerByPlacement.get(reservedPlacement)+ if (placementController && placementController !== connId) {+ this.sendError(connId, 'CONTROL_LEASE_HELD', { requestId })+ return+ }++ await this.closeConnection(connId, 'replaced', false)+ this.controllerByAgent.set(session.agentId, connId)+ this.controllerByPlacement.set(reservedPlacement, connId)+ const streamId = randomUUID()+ const buffered: Buffer[] = []+ let state: ActiveStream | null = null+ let opened: Awaited<ReturnType<TerminalBackendCoordinator['openStream']>>+ try {+ opened = await this.deps.terminals.openStream(session, size, {+ onData: (bytes) => {+ if (state) this.onOutput(state, bytes)+ else buffered.push(Buffer.from(bytes))+ },+ onClose: (reason) => {+ if (state) void this.closeStream(state, reason, true)+ },+ })+ } catch {+ if (this.controllerByAgent.get(session.agentId) === connId) this.controllerByAgent.delete(session.agentId)+ if (this.controllerByPlacement.get(reservedPlacement) === connId) this.controllerByPlacement.delete(reservedPlacement)+ this.sendError(connId, 'TERMINAL_OPEN_FAILED', { requestId })+ return+ }+ if (opened.state !== 'succeeded') {+ if (this.controllerByAgent.get(session.agentId) === connId) this.controllerByAgent.delete(session.agentId)+ if (this.controllerByPlacement.get(reservedPlacement) === connId) this.controllerByPlacement.delete(reservedPlacement)+ this.sendError(connId, opened.reason, { requestId })+ return+ }++ const placementKey = terminalPlacementKey(opened.value.runtime)+ const actualController = this.controllerByPlacement.get(placementKey)+ if (actualController && actualController !== connId) {+ if (this.controllerByAgent.get(session.agentId) === connId) this.controllerByAgent.delete(session.agentId)+ if (this.controllerByPlacement.get(reservedPlacement) === connId) this.controllerByPlacement.delete(reservedPlacement)+ await opened.value.close().catch(() => { /* best effort */ })+ this.sendError(connId, 'CONTROL_LEASE_HELD', { requestId })+ return+ }+ if (reservedPlacement !== placementKey && this.controllerByPlacement.get(reservedPlacement) === connId) {+ this.controllerByPlacement.delete(reservedPlacement)+ }+ this.controllerByPlacement.set(placementKey, connId)++ const requestedCompression = Array.isArray(payload.compression) ? payload.compression : []+ state = {+ connId,+ streamId,+ agentId: session.agentId,+ engineId: session.engine,+ placementKey,+ handle: opened.value,+ compression: requestedCompression.includes('zlib') ? 'zlib' : 'none',+ expiresAt: this.now() + HEARTBEAT_TIMEOUT_MS,+ nextSeq: 0,+ lastInputSeq: -1,+ lastResizeSeq: -1,+ pending: [],+ pendingBytes: 0,+ output: buffered,+ outputBytes: buffered.reduce((sum, chunk) => sum + chunk.length, 0),+ flushTimer: null,+ snapshotting: false,+ resyncing: false,+ closing: false,+ }+ this.streams.set(streamId, state)+ if (!this.deps.sendTarget(connId, 'terminal_ready', {+ requestId,+ protocolVersion: PROTOCOL_VERSION,+ streamId,+ agentId: session.agentId,+ engineId: session.engine,+ backend: 'tmux',+ })) {+ await this.closeStream(state, 'backend disconnected', false)+ return+ }+ await this.sendKeyframe(state)+ }++ private streamFor(connId: string, payload: FramePayload): ActiveStream | null {+ const streamId = typeof payload.streamId === 'string' ? payload.streamId : ''+ const state = this.streams.get(streamId)+ return state?.connId === connId && !state.closing ? state : null+ }++ private alive(connId: string, payload: FramePayload): void {+ const state = this.streamFor(connId, payload)+ if (!state) return+ state.expiresAt = this.now() + HEARTBEAT_TIMEOUT_MS+ }++ private ack(connId: string, payload: FramePayload): void {+ const state = this.streamFor(connId, payload)+ if (!state) return+ const lastSeq = Number(payload.lastSeq)+ if (!Number.isSafeInteger(lastSeq) || lastSeq < -1 || lastSeq >= state.nextSeq) return+ while (state.pending.length && state.pending[0].seq <= lastSeq) {+ state.pendingBytes -= state.pending.shift()!.bytes+ }+ }++ private async input(connId: string, payload: FramePayload): Promise<void> {+ const state = this.streamFor(connId, payload)+ if (!state) return+ const inputSeq = Number(payload.inputSeq)+ const bytes = strictBase64(payload.data)+ if (!Number.isSafeInteger(inputSeq) || inputSeq !== state.lastInputSeq + 1 || !bytes || bytes.length > INPUT_MAX_BYTES) {+ this.sendError(connId, 'TERMINAL_INPUT_INVALID', { streamId: state.streamId })+ return+ }+ state.lastInputSeq = inputSeq+ state.expiresAt = this.now() + HEARTBEAT_TIMEOUT_MS+ const result = await state.handle.writeRaw(bytes)+ if (result.state !== 'succeeded') {+ this.sendError(connId, 'TERMINAL_INPUT_FAILED', { streamId: state.streamId, message: result.reason })+ if (result.dispatch === 'possibly_executed') await this.sendKeyframe(state)+ }+ }++ private async resize(connId: string, payload: FramePayload): Promise<void> {+ const state = this.streamFor(connId, payload)+ if (!state) return+ const resizeSeq = Number(payload.resizeSeq)+ const size = sizeFrom(payload)+ if (!Number.isSafeInteger(resizeSeq) || resizeSeq <= state.lastResizeSeq || !size) return+ state.lastResizeSeq = resizeSeq+ state.expiresAt = this.now() + HEARTBEAT_TIMEOUT_MS+ const result = await state.handle.resize(size)+ if (result.state !== 'succeeded') {+ this.sendError(connId, 'TERMINAL_RESIZE_FAILED', { streamId: state.streamId, message: result.reason })+ return+ }+ await this.sendKeyframe(state)+ }++ private async resyncRequested(connId: string, payload: FramePayload): Promise<void> {+ const state = this.streamFor(connId, payload)+ if (state) await this.sendKeyframe(state)+ }++ private async closeRequested(connId: string, payload: FramePayload): Promise<void> {+ const state = this.streamFor(connId, payload)+ if (state) await this.closeStream(state, 'client closed', true)+ }++ private onOutput(state: ActiveStream, bytes: Uint8Array): void {+ if (state.closing || bytes.length === 0) return+ state.output.push(Buffer.from(bytes))+ state.outputBytes += bytes.length+ if (state.snapshotting) return+ if (state.outputBytes >= OUTPUT_CHUNK_BYTES) {+ this.flushOutput(state)+ return+ }+ state.flushTimer ??= setTimeout(() => this.flushOutput(state), OUTPUT_FLUSH_MS)+ }++ private flushOutput(state: ActiveStream): void {+ if (state.flushTimer) { clearTimeout(state.flushTimer); state.flushTimer = null }+ if (state.closing || state.snapshotting || state.outputBytes === 0) return+ const all = Buffer.concat(state.output, state.outputBytes)+ state.output = []+ state.outputBytes = 0+ for (let offset = 0; offset < all.length; offset += OUTPUT_CHUNK_BYTES) {+ const chunk = all.subarray(offset, offset + OUTPUT_CHUNK_BYTES)+ const seq = state.nextSeq+++ const body = encoded(chunk, state.compression)+ if (!this.deps.sendTarget(state.connId, 'terminal_output', {+ protocolVersion: PROTOCOL_VERSION,+ streamId: state.streamId,+ seq,+ encoding: body.encoding,+ data: body.data,+ })) {+ void this.closeStream(state, 'backend disconnected', false)+ return+ }+ state.pending.push({ seq, bytes: body.plainBytes })+ state.pendingBytes += body.plainBytes+ }+ if ((state.pending.length > MAX_UNACKED_FRAMES || state.pendingBytes > MAX_UNACKED_BYTES) && !state.resyncing) {+ void this.sendKeyframe(state)+ }+ }++ private async sendKeyframe(state: ActiveStream): Promise<void> {+ if (state.closing || state.resyncing) return+ state.resyncing = true+ state.snapshotting = true+ if (state.flushTimer) { clearTimeout(state.flushTimer); state.flushTimer = null }+ let snapshot: Awaited<ReturnType<TerminalStreamHandle['snapshot']>> = {+ state: 'failed',+ reason: 'tmux snapshot did not run',+ }+ for (const historyLines of KEYFRAME_HISTORY_ATTEMPTS) {+ snapshot = await state.handle.snapshot(historyLines)+ if (snapshot.state !== 'succeeded' || snapshot.value.bytes.length <= KEYFRAME_MAX_BYTES) break+ }+ if (snapshot.state !== 'succeeded') {+ state.snapshotting = false+ state.resyncing = false+ this.sendError(state.connId, 'TERMINAL_SNAPSHOT_FAILED', { streamId: state.streamId, message: snapshot.reason })+ await this.closeStream(state, snapshot.reason, false)+ return+ }+ if (snapshot.value.bytes.length > KEYFRAME_MAX_BYTES) {+ state.snapshotting = false+ state.resyncing = false+ this.sendError(state.connId, 'TERMINAL_SNAPSHOT_TOO_LARGE', { streamId: state.streamId })+ await this.closeStream(state, 'terminal snapshot exceeds safe envelope size', false)+ return+ }+ const bytes = Buffer.from(snapshot.value.bytes)+ state.pending = []+ state.pendingBytes = 0+ const seq = state.nextSeq+++ const body = encoded(bytes, state.compression)+ const sent = this.deps.sendTarget(state.connId, 'terminal_keyframe', {+ protocolVersion: PROTOCOL_VERSION,+ streamId: state.streamId,+ seq,+ cols: snapshot.value.cols,+ rows: snapshot.value.rows,+ encoding: body.encoding,+ data: body.data,+ })+ if (!sent) {+ state.snapshotting = false+ state.resyncing = false+ await this.closeStream(state, 'backend disconnected', false)+ return+ }+ state.pending.push({ seq, bytes: body.plainBytes })+ state.pendingBytes = body.plainBytes+ state.snapshotting = false+ state.resyncing = false+ this.flushOutput(state)+ }++ private expireLeases(): void {+ const now = this.now()+ for (const state of [...this.streams.values()]) {+ if (!state.closing && state.expiresAt <= now) void this.closeStream(state, 'heartbeat timeout', true)+ }+ }++ private async closeStream(state: ActiveStream, reason: string, notify: boolean): Promise<void> {+ if (state.closing) return+ state.closing = true+ if (state.flushTimer) clearTimeout(state.flushTimer)+ state.flushTimer = null+ this.streams.delete(state.streamId)+ if (this.controllerByAgent.get(state.agentId) === state.connId) this.controllerByAgent.delete(state.agentId)+ if (this.controllerByPlacement.get(state.placementKey) === state.connId) this.controllerByPlacement.delete(state.placementKey)+ await state.handle.close().catch(() => { /* best effort */ })+ if (notify) this.deps.sendTarget(state.connId, 'terminal_closed', {+ protocolVersion: PROTOCOL_VERSION,+ streamId: state.streamId,+ reason,+ })+ }++ async closeConnection(connId: string, reason = 'connection closed', notify = false): Promise<void> {+ const states = [...this.streams.values()].filter((state) => state.connId === connId)+ await Promise.all(states.map((state) => this.closeStream(state, reason, notify)))+ }++ async closeAll(reason = 'backend disconnected'): Promise<void> {+ await Promise.all([...this.streams.values()].map((state) => this.closeStream(state, reason, false)))+ }++ async stop(): Promise<void> {+ clearInterval(this.expiryTimer)+ await this.closeAll('terminal manager stopped')+ }+}diff --git a/cli/src/lib/terminalTypes.ts b/cli/src/lib/terminalTypes.tsindex dc7fc9d63..bcd8aefd3 100644--- a/cli/src/lib/terminalTypes.ts+++ b/cli/src/lib/terminalTypes.ts@@ -117,6 +117,31 @@ export interface TerminalProcessExpectation {processIdentity?: ProcessIdentity}+export interface TerminalStreamSize {+ cols: number+ rows: number+}++export interface TerminalStreamSnapshot {+ bytes: Uint8Array+ cols: number+ rows: number+}++export interface TerminalStreamSink {+ onData: (bytes: Uint8Array) => void+ onClose: (reason: string) => void+}++/** A live byte-oriented terminal stream. Implementations must preserve input/output order. */+export interface TerminalStreamHandle<Ref extends TerminalRuntimeRef = TerminalRuntimeRef> {+ readonly runtime: Ref+ snapshot(historyLines: number): Promise<TerminalReadResult<TerminalStreamSnapshot>>+ writeRaw(bytes: Uint8Array): Promise<TerminalActionResult>+ resize(size: TerminalStreamSize): Promise<TerminalActionResult>+ close(): Promise<void>+}+export const TERMINAL_ACTION_SUCCEEDED: TerminalActionResult = {state: 'succeeded',dispatch: 'executed',diff --git a/cli/src/lib/tmuxBackend.ts b/cli/src/lib/tmuxBackend.tsindex 6a89ee7e6..2388427a9 100644--- a/cli/src/lib/tmuxBackend.ts+++ b/cli/src/lib/tmuxBackend.ts@@ -12,9 +12,13 @@ import {type TerminalLogicalKey,type TerminalProcessExpectation,type TerminalReadResult,+ type TerminalStreamHandle,+ type TerminalStreamSink,+ type TerminalStreamSize,type TmuxRuntimeRef,type RuntimeValidation,} from './terminalTypes.js'+import { TmuxControlStream } from './tmuxStream.js'import {captureTmuxPane,listPaneTitles,@@ -178,4 +182,18 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {})return legacyActionResult(ok, 'tmux notification')}++ async openStream(+ runtime: TmuxRuntimeRef,+ expected: TerminalProcessExpectation,+ size: TerminalStreamSize,+ sink: TerminalStreamSink,+ ): Promise<TerminalReadResult<TerminalStreamHandle<TmuxRuntimeRef>>> {+ const validation = await this.validate(runtime, expected)+ if (validation.state !== 'alive') return {+ state: 'failed',+ reason: validation.state === 'gone' ? validation.reason : 'tmux runtime validation failed',+ }+ return TmuxControlStream.open(runtime.paneId, size, sink)+ }}diff --git a/cli/src/lib/tmuxStream.real.spec.ts b/cli/src/lib/tmuxStream.real.spec.tsnew file mode 100644index 000000000..b7105f267--- /dev/null+++ b/cli/src/lib/tmuxStream.real.spec.ts@@ -0,0 +1,56 @@+import { execFile } from 'node:child_process'+import { randomUUID } from 'node:crypto'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { TmuxControlStream } from './tmuxStream.js'++const run = process.env.RUN_REAL_TMUX_STREAM === '1' ? describe : describe.skip++function tmux(args: string[]): Promise<string> {+ return new Promise((resolve, reject) => {+ execFile('tmux', args, { timeout: 3_000 }, (error, stdout) => error ? reject(error) : resolve(stdout.trim()))+ })+}++run('TmuxControlStream real tmux', () => {+ const session = `harness-stream-${randomUUID().slice(0, 8)}`+ let paneId = ''++ beforeAll(async () => {+ paneId = await tmux(['new-session', '-d', '-P', '-F', '#{pane_id}', '-s', session, 'bash', '--noprofile', '--norc'])+ })++ afterAll(async () => {+ await tmux(['kill-session', '-t', session]).catch(() => { /* exact disposable session only */ })+ })++ it('captures, streams raw output, accepts input, and resizes one-pane windows', async () => {+ const chunks: Buffer[] = []+ let closedReason = ''+ const opened = await TmuxControlStream.open(paneId, { cols: 96, rows: 28 }, {+ onData: (bytes) => chunks.push(Buffer.from(bytes)),+ onClose: (reason) => { closedReason = reason },+ })+ expect(opened.state).toBe('succeeded')+ if (opened.state !== 'succeeded') return++ const snapshot = await opened.value.snapshot(100)+ expect(snapshot.state).toBe('succeeded')+ if (snapshot.state === 'succeeded') {+ expect(snapshot.value.cols).toBe(96)+ expect(snapshot.value.rows).toBe(28)+ expect(Buffer.from(snapshot.value.bytes).includes(Buffer.from('\u001bc'))).toBe(true)+ }++ await opened.value.writeRaw(Buffer.from("printf 'HARNESS_STREAM_OK\\n'\r"))+ const deadline = Date.now() + 3_000+ while (!Buffer.concat(chunks).includes(Buffer.from('HARNESS_STREAM_OK')) && Date.now() < deadline) {+ await new Promise((resolve) => setTimeout(resolve, 20))+ }+ expect(Buffer.concat(chunks).includes(Buffer.from('HARNESS_STREAM_OK'))).toBe(true)++ expect((await opened.value.resize({ cols: 110, rows: 35 })).state).toBe('succeeded')+ expect(await tmux(['display-message', '-p', '-t', paneId, '#{pane_width}x#{pane_height}'])).toBe('110x35')+ await opened.value.close()+ expect(closedReason === '' || closedReason === 'closed').toBe(true)+ })+})diff --git a/cli/src/lib/tmuxStream.spec.ts b/cli/src/lib/tmuxStream.spec.tsnew file mode 100644index 000000000..206455586--- /dev/null+++ b/cli/src/lib/tmuxStream.spec.ts@@ -0,0 +1,13 @@+import { describe, expect, it } from 'vitest'+import { decodeTmuxControlData } from './tmuxStream.js'++describe('tmux control-mode output decoding', () => {+ it('decodes octal bytes without corrupting adjacent UTF-8', () => {+ const decoded = decodeTmuxControlData('hello\\040世界\\015\\012\\033[31m')+ expect(Buffer.from(decoded)).toEqual(Buffer.from('hello 世界\r\n\u001b[31m'))+ })++ it('preserves ordinary backslashes that are not octal escapes', () => {+ expect(Buffer.from(decodeTmuxControlData('C:\\Users\\name')).toString()).toBe('C:\\Users\\name')+ })+})diff --git a/cli/src/lib/tmuxStream.ts b/cli/src/lib/tmuxStream.tsnew file mode 100644index 000000000..1b324ced6--- /dev/null+++ b/cli/src/lib/tmuxStream.ts@@ -0,0 +1,287 @@+import { execFile, spawn, type ChildProcessWithoutNullStreams } from 'node:child_process'+import { randomUUID } from 'node:crypto'+import { StringDecoder } from 'node:string_decoder'+import {+ TERMINAL_ACTION_SUCCEEDED,+ terminalActionNotStarted,+ terminalActionPossiblyExecuted,+ type TerminalActionResult,+ type TerminalReadResult,+ type TerminalStreamHandle,+ type TerminalStreamSink,+ type TerminalStreamSize,+ type TerminalStreamSnapshot,+ type TmuxRuntimeRef,+} from './terminalTypes.js'++const MIN_COLS = 40+const MAX_COLS = 300+const MIN_ROWS = 12+const MAX_ROWS = 120+const SMALL_INPUT_BYTES = 4 * 1024++interface PaneMeta {+ sessionId: string+ windowId: string+ windowPanes: number+ windowWidth: number+ windowHeight: number+ paneWidth: number+ paneHeight: number+ alternateOn: boolean+ cursorX: number+ cursorY: number+ mouseStandard: boolean+ mouseButton: boolean+ mouseAll: boolean+ mouseUtf8: boolean+ mouseSgr: boolean+}++function boundedSize(size: TerminalStreamSize): TerminalStreamSize {+ return {+ cols: Math.max(MIN_COLS, Math.min(MAX_COLS, Math.floor(size.cols))),+ rows: Math.max(MIN_ROWS, Math.min(MAX_ROWS, Math.floor(size.rows))),+ }+}++function execTmux(args: string[], timeout = 2_000): Promise<{ ok: boolean; stdout: Buffer }> {+ return new Promise((resolve) => {+ execFile('tmux', args, { timeout, encoding: 'buffer', maxBuffer: 8 * 1024 * 1024 }, (error, stdout) => {+ resolve({ ok: !error, stdout: Buffer.isBuffer(stdout) ? stdout : Buffer.from(stdout ?? '') })+ })+ })+}++async function paneMeta(paneId: string): Promise<PaneMeta | null> {+ const format = [+ '#{session_id}', '#{window_id}', '#{window_panes}', '#{window_width}', '#{window_height}',+ '#{pane_width}', '#{pane_height}', '#{alternate_on}', '#{cursor_x}', '#{cursor_y}',+ '#{mouse_standard_flag}', '#{mouse_button_flag}', '#{mouse_all_flag}', '#{mouse_utf8_flag}', '#{mouse_sgr_flag}',+ ].join('|')+ const result = await execTmux(['display-message', '-p', '-t', paneId, format])+ if (!result.ok) return null+ const fields = result.stdout.toString('utf8').trim().split('|')+ if (fields.length !== 15 || !/^\$\d+$/.test(fields[0]) || !/^@\d+$/.test(fields[1])) return null+ const nums = fields.slice(2).map(Number)+ if (nums.some((value) => !Number.isFinite(value))) return null+ return {+ sessionId: fields[0],+ windowId: fields[1],+ windowPanes: nums[0],+ windowWidth: nums[1],+ windowHeight: nums[2],+ paneWidth: nums[3],+ paneHeight: nums[4],+ alternateOn: nums[5] === 1,+ cursorX: nums[6],+ cursorY: nums[7],+ mouseStandard: nums[8] === 1,+ mouseButton: nums[9] === 1,+ mouseAll: nums[10] === 1,+ mouseUtf8: nums[11] === 1,+ mouseSgr: nums[12] === 1,+ }+}++/** Decode the octal escaping used by tmux control-mode `%output` notifications. */+export function decodeTmuxControlData(encoded: string): Uint8Array {+ const chunks: Buffer[] = []+ let plainStart = 0+ for (let i = 0; i < encoded.length; i++) {+ if (encoded[i] !== '\\' || !/^[0-7]{3}$/.test(encoded.slice(i + 1, i + 4))) continue+ if (i > plainStart) chunks.push(Buffer.from(encoded.slice(plainStart, i), 'utf8'))+ chunks.push(Buffer.from([Number.parseInt(encoded.slice(i + 1, i + 4), 8)]))+ i += 3+ plainStart = i + 1+ }+ if (plainStart < encoded.length) chunks.push(Buffer.from(encoded.slice(plainStart), 'utf8'))+ return Buffer.concat(chunks)+}++function mouseModes(meta: PaneMeta): string {+ let out = ''+ if (meta.mouseAll) out += '\u001b[?1003h'+ else if (meta.mouseButton) out += '\u001b[?1002h'+ else if (meta.mouseStandard) out += '\u001b[?1000h'+ if (meta.mouseUtf8) out += '\u001b[?1005h'+ if (meta.mouseSgr) out += '\u001b[?1006h'+ return out+}++export function synthesizeTmuxSnapshot(capture: Uint8Array, meta: PaneMeta): Uint8Array {+ const cursorRow = Math.max(1, Math.min(meta.paneHeight, meta.cursorY + 1))+ const cursorCol = Math.max(1, Math.min(meta.paneWidth, meta.cursorX + 1))+ const prefix = Buffer.from(`\u001bc\u001b[?25l\u001b[H\u001b[2J\u001b[3J${mouseModes(meta)}`, 'utf8')+ const suffix = Buffer.from(`\u001b[${cursorRow};${cursorCol}H\u001b[?25h`, 'utf8')+ return Buffer.concat([prefix, Buffer.from(capture), suffix])+}++async function loadAndPaste(paneId: string, bytes: Uint8Array): Promise<TerminalActionResult> {+ const bufferName = `harness-terminal-${randomUUID()}`+ const loaded = await new Promise<boolean>((resolve) => {+ const child = spawn('tmux', ['load-buffer', '-b', bufferName, '-'], { stdio: ['pipe', 'ignore', 'ignore'] })+ child.once('error', () => resolve(false))+ child.once('close', (code) => resolve(code === 0))+ child.stdin.end(Buffer.from(bytes))+ })+ if (!loaded) return terminalActionNotStarted('tmux input buffer could not be loaded')+ const pasted = await execTmux(['paste-buffer', '-d', '-b', bufferName, '-t', paneId])+ if (!pasted.ok) {+ void execTmux(['delete-buffer', '-b', bufferName])+ return terminalActionPossiblyExecuted('tmux raw paste did not complete')+ }+ return TERMINAL_ACTION_SUCCEEDED+}++async function sendHexBytes(paneId: string, bytes: Uint8Array): Promise<TerminalActionResult> {+ for (let offset = 0; offset < bytes.length; offset += 256) {+ const hex = [...bytes.slice(offset, offset + 256)].map((byte) => byte.toString(16).padStart(2, '0'))+ const result = await execTmux(['send-keys', '-t', paneId, '-H', ...hex])+ if (!result.ok) return offset === 0+ ? terminalActionNotStarted('tmux raw input could not be sent')+ : terminalActionPossiblyExecuted('tmux raw input stopped after a partial write')+ }+ return TERMINAL_ACTION_SUCCEEDED+}++export class TmuxControlStream implements TerminalStreamHandle<TmuxRuntimeRef> {+ readonly runtime: TmuxRuntimeRef+ private readonly child: ChildProcessWithoutNullStreams+ private readonly decoder = new StringDecoder('utf8')+ private lineBuffer = ''+ private closed = false+ private closeNotified = false+ private original: PaneMeta+ private lastApplied: TerminalStreamSize | null = null++ private constructor(+ paneId: string,+ original: PaneMeta,+ child: ChildProcessWithoutNullStreams,+ private readonly sink: TerminalStreamSink,+ ) {+ this.runtime = { backend: 'tmux', paneId }+ this.original = original+ this.child = child+ child.stdout.on('data', (chunk: Buffer) => this.onStdout(chunk))+ child.once('error', (error) => this.notifyClose(`tmux control client error: ${error.message}`))+ child.once('close', (code) => this.notifyClose(this.closed ? 'closed' : `tmux control client exited (${code ?? 'signal'})`))+ }++ static async open(paneId: string, size: TerminalStreamSize, sink: TerminalStreamSink): Promise<TerminalReadResult<TmuxControlStream>> {+ const original = await paneMeta(paneId)+ if (!original) return { state: 'failed', reason: 'tmux pane metadata is unavailable' }+ if (original.windowPanes !== 1) return { state: 'failed', reason: 'TERMINAL_MULTI_PANE_UNSUPPORTED' }+ const child = spawn('tmux', ['-C', 'attach-session', '-f', 'ignore-size', '-t', paneId], {+ stdio: ['pipe', 'pipe', 'pipe'],+ })+ const spawned = await new Promise<boolean>((resolve) => {+ let settled = false+ child.once('spawn', () => { if (!settled) { settled = true; resolve(true) } })+ child.once('error', () => { if (!settled) { settled = true; resolve(false) } })+ })+ if (!spawned) return { state: 'failed', reason: 'tmux control client could not start' }+ const stream = new TmuxControlStream(paneId, original, child, sink)+ const resized = await stream.resize(size)+ if (resized.state !== 'succeeded') {+ await stream.close()+ return { state: 'failed', reason: resized.reason }+ }+ return { state: 'succeeded', value: stream }+ }++ private onStdout(chunk: Buffer): void {+ this.lineBuffer += this.decoder.write(chunk)+ while (true) {+ const newline = this.lineBuffer.indexOf('\n')+ if (newline < 0) break+ const line = this.lineBuffer.slice(0, newline).replace(/\r$/, '')+ this.lineBuffer = this.lineBuffer.slice(newline + 1)+ this.onControlLine(line)+ }+ }++ private onControlLine(line: string): void {+ const output = /^%output\s+(%\d+)\s(.*)$/.exec(line)+ if (output) {+ if (output[1] === this.runtime.paneId) this.sink.onData(decodeTmuxControlData(output[2]))+ return+ }+ const extended = /^%extended-output\s+(%\d+)\s+\d+\s+:?\s?(.*)$/.exec(line)+ if (extended) {+ if (extended[1] === this.runtime.paneId) this.sink.onData(decodeTmuxControlData(extended[2]))+ return+ }+ const paused = /^%pause\s+(%\d+)$/.exec(line)+ if (paused?.[1] === this.runtime.paneId && !this.closed) {+ this.child.stdin.write(`refresh-client -A ${this.runtime.paneId}:continue\n`)+ return+ }+ if (line.startsWith('%exit')) this.notifyClose(this.closed ? 'closed' : 'tmux pane/control client closed')+ }++ private notifyClose(reason: string): void {+ if (this.closeNotified) return+ this.closeNotified = true+ this.sink.onClose(reason)+ }++ async snapshot(historyLines: number): Promise<TerminalReadResult<TerminalStreamSnapshot>> {+ const meta = await paneMeta(this.runtime.paneId)+ if (!meta) return { state: 'failed', reason: 'tmux pane disappeared' }+ const boundedHistory = Math.max(0, Math.min(1_000, Math.floor(historyLines)))+ const args = ['capture-pane', '-p', '-e', '-t', this.runtime.paneId]+ if (!meta.alternateOn && boundedHistory > 0) args.push('-S', `-${boundedHistory}`)+ const capture = await execTmux(args, 3_000)+ if (!capture.ok) return { state: 'failed', reason: 'tmux snapshot failed' }+ return {+ state: 'succeeded',+ value: {+ bytes: synthesizeTmuxSnapshot(capture.stdout, meta),+ cols: meta.paneWidth,+ rows: meta.paneHeight,+ },+ }+ }++ async writeRaw(bytes: Uint8Array): Promise<TerminalActionResult> {+ if (this.closed) return terminalActionNotStarted('terminal stream is closed')+ if (bytes.length === 0) return TERMINAL_ACTION_SUCCEEDED+ return bytes.length <= SMALL_INPUT_BYTES+ ? sendHexBytes(this.runtime.paneId, bytes)+ : loadAndPaste(this.runtime.paneId, bytes)+ }++ async resize(requested: TerminalStreamSize): Promise<TerminalActionResult> {+ if (this.closed) return terminalActionNotStarted('terminal stream is closed')+ const meta = await paneMeta(this.runtime.paneId)+ if (!meta) return terminalActionNotStarted('tmux pane disappeared')+ if (meta.windowPanes !== 1) return terminalActionNotStarted('TERMINAL_MULTI_PANE_UNSUPPORTED')+ const size = boundedSize(requested)+ const result = await execTmux(['resize-window', '-t', meta.windowId, '-x', String(size.cols), '-y', String(size.rows)])+ if (!result.ok) return terminalActionPossiblyExecuted('tmux resize did not complete')+ this.lastApplied = size+ return TERMINAL_ACTION_SUCCEEDED+ }++ async close(): Promise<void> {+ if (this.closed) return+ this.closed = true+ const current = await paneMeta(this.runtime.paneId)+ if (current && current.windowPanes === 1 && this.lastApplied+ && current.windowWidth === this.lastApplied.cols && current.windowHeight === this.lastApplied.rows) {+ await execTmux([+ 'resize-window', '-t', current.windowId,+ '-x', String(this.original.windowWidth), '-y', String(this.original.windowHeight),+ ])+ }+ try { this.child.stdin.write('detach-client\n') } catch { /* ignore */ }+ const exited = await new Promise<boolean>((resolve) => {+ if (this.child.exitCode != null || this.child.signalCode != null) { resolve(true); return }+ const timer = setTimeout(() => resolve(false), 500)+ this.child.once('close', () => { clearTimeout(timer); resolve(true) })+ })+ if (!exited) this.child.kill('SIGTERM')+ }+}