import { execFileSync } from "node:child_process"; import { randomUUID } from "node:crypto"; import { addAbortListener } from "node:events"; import { statSync } from "node:fs"; import { createConnection } from "node:net"; import { setTimeout as delay } from "node:timers/promises"; import { isCmuxId, isMuxSocketPath, MUX_CAPABILITIES, shellEscape, UnconfirmedPaneAllocationError, validateMuxLaunchContext, type CapturePaneOptions, type CapturePaneResult, type Multiplexer, type MuxLaunchContext, type MuxTarget, type PaneActivity, type PaneLiveness, type PaneRef, } from "./multiplexer-contracts"; import { parseJsonRecord } from "./json-input"; const SOCKET_TIMEOUT_MS = 5_000; const CREATED_SURFACE_TIMEOUT_MS = 250; const CREATED_SURFACE_RETRY_MS = 20; export const CMUX_DISCOVERY_TIMEOUT_MS = 1_500; const RESPONSE_MAX_BYTES = 1024 * 1024; const REQUIRED_METHODS = [ "system.capabilities", "system.identify", "surface.create", "surface.split", "surface.list", "surface.close", "surface.focus", "terminal.paste", "surface.send_key", ]; const SOCKET_CLIENT = ` const net = require("node:net"); const chunks = []; process.stdin.on("data", (chunk) => chunks.push(chunk)); process.stdin.on("end", () => { let bytes = 0; const response = []; const socket = net.createConnection({ path: process.argv[1] }); socket.on("connect", () => socket.write(Buffer.concat(chunks))); socket.on("data", (chunk) => { const end = chunk.indexOf(10); const part = end < 0 ? chunk : chunk.subarray(0, end); bytes += part.length; if (bytes > ${RESPONSE_MAX_BYTES}) { socket.destroy(new Error("response too large")); return; } response.push(part); if (end >= 0) { process.stdout.write(Buffer.concat(response)); socket.destroy(); } }); socket.on("error", (error) => { process.stderr.write(error.message); process.exitCode = 1; }); }); `; function record(value: unknown): value is Record { return value !== null && typeof value === "object" && !Array.isArray(value); } function cmuxSocketPath(path: unknown): string { if ( !isMuxSocketPath(path) || !statSync(path, { throwIfNoEntry: false })?.isSocket() ) { throw new Error("cmux local socket is unavailable"); } return path; } /** One request per local Unix-socket connection; no cmux CLI fallback. */ function cmuxRequest( path: string, method: string, params: Record = {}, timeout = SOCKET_TIMEOUT_MS, ): Record { const id = randomUUID(); const input = `${JSON.stringify({ id, method, params })}\n`; const output = execFileSync(process.execPath, ["-e", SOCKET_CLIENT, path], { encoding: "utf8", timeout, maxBuffer: RESPONSE_MAX_BYTES, input, stdio: ["pipe", "pipe", "pipe"], }); return parseResponse(output, id, method); } async function cmuxRequestAsync( path: string, method: string, params: Record = {}, timeout = SOCKET_TIMEOUT_MS, signal?: AbortSignal, ): Promise> { signal?.throwIfAborted(); const id = randomUUID(); const input = `${JSON.stringify({ id, method, params })}\n`; const output = await new Promise((resolve, reject) => { const socket = createConnection({ path }); const subscription = signal ? addAbortListener(signal, () => socket.destroy()) : undefined; const deadline = setTimeout( () => socket.destroy(new Error("cmux socket request timed out")), timeout, ); const chunks: Buffer[] = []; let size = 0; socket.once("connect", () => socket.write(input)); socket.once("error", reject); socket.once("close", () => { clearTimeout(deadline); subscription?.[Symbol.dispose](); reject(new Error("cmux socket closed without a complete response")); }); socket.on("data", (chunk: Buffer) => { const end = chunk.indexOf(10); const part = end < 0 ? chunk : chunk.subarray(0, end); size += part.length; if (size > RESPONSE_MAX_BYTES) { socket.destroy(new Error("cmux socket response too large")); return; } chunks.push(part); if (end >= 0) { resolve(Buffer.concat(chunks).toString("utf8")); socket.destroy(); } }); }); return parseResponse(output, id, method); } function parseResponse( output: string, id: string, method: string, ): Record { const response = parseJsonRecord(output); if (response?.id !== id || response.ok !== true || !record(response.result)) { const message = record(response?.error) && typeof response.error.message === "string" ? response.error.message : "malformed response"; throw new Error(`cmux ${method} failed: ${message}`); } return response.result; } function requireCapabilities(result: Record): void { const methods = result.methods; if ( result.protocol !== "cmux-socket" || result.version !== 2 || !Array.isArray(methods) || !REQUIRED_METHODS.every((method) => methods.includes(method)) ) { throw new Error("cmux socket API v2 lacks required sub-agent capabilities"); } } function controllingTTY(): string | undefined { try { const tty = execFileSync( "/bin/ps", ["-p", String(process.pid), "-o", "tty="], { encoding: "utf8", timeout: 1_500, maxBuffer: 4096, stdio: ["ignore", "pipe", "pipe"], }, ).trim(); return tty; } catch { // No reliable local terminal observation. return undefined; } } export type CmuxTarget = Extract; export function cmuxCandidate(env: NodeJS.ProcessEnv): CmuxTarget | undefined { const { CMUX_SOCKET_PATH: server, CMUX_WORKSPACE_ID: session, CMUX_SURFACE_ID: paneId, } = env; if (isMuxSocketPath(server) && isCmuxId(session) && isCmuxId(paneId)) { return { mux: "cmux", server, session, paneId }; } } function identifyParams(tty: string | undefined): { caller_tty: string } { if (!tty || !/^(?:\/dev\/)?(?:tty[A-Za-z0-9]+|pts\/\d+)$/.test(tty)) { throw new Error( "cmux could not verify this process belongs to its marked surface", ); } // cmux resolves caller_tty independently of its env-attributed process tree. return { caller_tty: tty }; } function requireCaller(caller: unknown, target: CmuxTarget): void { if ( !record(caller) || !sameUUID(caller.surface_id, target.paneId) || !sameUUID(caller.workspace_id, target.session) || caller.surface_type !== "terminal" || !isCmuxId(caller.pane_id) ) { throw new Error( "cmux could not verify this process belongs to its marked surface", ); } } /** Markers nominate a surface; the caller's OS TTY proves local ownership. */ export function verifyCmuxTarget( target: CmuxTarget, tty: string | undefined, timeout = SOCKET_TIMEOUT_MS, ): void { const params = identifyParams(tty); const server = cmuxSocketPath(target.server); requireCapabilities(cmuxRequest(server, "system.capabilities", {}, timeout)); requireCaller( cmuxRequest(server, "system.identify", params, timeout).caller, target, ); } export async function verifyCmuxTargetAsync( target: CmuxTarget, tty: string | undefined, signal?: AbortSignal, ): Promise { const params = identifyParams(tty); const server = target.server; const timeout = CMUX_DISCOVERY_TIMEOUT_MS; requireCapabilities( await cmuxRequestAsync(server, "system.capabilities", {}, timeout, signal), ); requireCaller( (await cmuxRequestAsync(server, "system.identify", params, timeout, signal)) .caller, target, ); } export function cmuxLaunchContext( env: NodeJS.ProcessEnv = process.env, ): MuxLaunchContext { const target = cmuxCandidate(env); if (!target) throw new Error("cmux did not provide a complete surface context"); verifyCmuxTarget(target, controllingTTY()); return { ...target, kind: "attached" }; } function sameUUID(value: unknown, id: string): boolean { return isCmuxId(value) && value.toLowerCase() === id.toLowerCase(); } function listedSurfaces( result: Record, workspaceId: string, ): Record[] { const surfaces: unknown = result.surfaces; if ( !sameUUID(result.workspace_id, workspaceId) || !Array.isArray(surfaces) || !surfaces.every( (row) => record(row) && isCmuxId(row.id) && typeof row.type === "string", ) ) { throw new Error("cmux returned an invalid workspace surface list"); } return surfaces; } function listSurfaces(path: string, workspaceId: string) { return listedSurfaces( cmuxRequest(path, "surface.list", { workspace_id: workspaceId }), workspaceId, ); } function terminalSurface(surfaces: Record[], paneId: string) { return surfaces.find( (surface) => sameUUID(surface.id, paneId) && surface.type === "terminal", ); } async function verifyCreatedSurface( server: string, workspaceId: string, surfaceId: string, ): Promise { const deadline = performance.now() + CREATED_SURFACE_TIMEOUT_MS; const params = { workspace_id: workspaceId }; for (;;) { const remaining = Math.floor(deadline - performance.now()); if (remaining <= 0) break; const result = await cmuxRequestAsync( server, "surface.list", params, remaining, ); const matches = listedSurfaces(result, workspaceId).filter((row) => sameUUID(row.id, surfaceId), ); if (matches.length > 0) { if (matches.length !== 1 || matches[0]?.type !== "terminal") { throw new Error("cmux returned an invalid created child surface"); } if (performance.now() < deadline) return; break; } // A valid list can briefly omit a newly allocated terminal. const wait = Math.min( CREATED_SURFACE_RETRY_MS, Math.floor(deadline - performance.now()), ); if (wait <= 0) break; await delay(wait); } throw new Error("cmux did not verify the created child surface"); } export class CmuxMultiplexer implements Multiplexer { readonly name = "cmux" as const; readonly capabilities = MUX_CAPABILITIES[this.name]; readonly confirmsPaneStop = true; isAvailable(): boolean { try { return cmuxLaunchContext().kind === "attached"; } catch { return false; } } async createPane( opts: Parameters[0], ): Promise { const { context, cwd, background } = opts; validateMuxLaunchContext(this.name, context); if (context?.kind !== "attached" || context.mux !== this.name) { throw new Error( "Start Pi inside a verified cmux terminal to use this backend", ); } const { server } = context; cmuxLaunchContext({ CMUX_SOCKET_PATH: server, CMUX_WORKSPACE_ID: context.session, CMUX_SURFACE_ID: context.paneId, }); const existing = listSurfaces(server, context.session); const parent = terminalSurface(existing, context.paneId); if (!parent || !isCmuxId(parent.pane_id)) { throw new Error("cmux did not confirm the caller surface's pane"); } const method = background ? "surface.create" : "surface.split"; const params = background ? { workspace_id: context.session, pane_id: parent.pane_id, type: "terminal", focus: false, working_directory: cwd, } : { workspace_id: context.session, surface_id: context.paneId, direction: "right", focus: true, working_directory: cwd, }; try { const created = cmuxRequest(server, method, params); const childId = created.surface_id; if ( !isCmuxId(childId) || !sameUUID(created.workspace_id, context.session) || existing.some((surface) => sameUUID(surface.id, childId)) ) { throw new Error( "cmux did not return a new surface in the requested workspace", ); } await verifyCreatedSurface(server, context.session, childId); return { paneId: childId, session: context.session, server }; } catch (error) { throw new UnconfirmedPaneAllocationError( error instanceof Error ? error.message : String(error), { cause: error }, ); } } getPaneLiveness( paneId: string, session?: string, server?: string, ): PaneLiveness { if (!isCmuxId(paneId) || !isCmuxId(session)) return "unknown"; try { const surfaces = listSurfaces(cmuxSocketPath(server), session); return terminalSurface(surfaces, paneId) ? "alive" : "dead"; } catch { return "unknown"; } } async getPaneLivenessAsync( paneId: string, session?: string, server?: string, ): Promise { if (!isCmuxId(paneId) || !isCmuxId(session) || !isMuxSocketPath(server)) { return "unknown"; } try { const result = await cmuxRequestAsync(server, "surface.list", { workspace_id: session, }); return terminalSurface(listedSurfaces(result, session), paneId) ? "alive" : "dead"; } catch { return "unknown"; } } async getPaneActivityAsync(): Promise { return "unknown"; } sendKeys( paneId: string, text: string, session?: string, server?: string, ): void { this.requireListedSurface(paneId, session, server); if (text.length === 0) return; cmuxRequest(cmuxSocketPath(server), "terminal.paste", { workspace_id: session, surface_id: paneId, text, submit_key: "none", }); } sendEnter(paneId: string, session?: string, server?: string): void { this.requireListedSurface(paneId, session, server); cmuxRequest(cmuxSocketPath(server), "surface.send_key", { workspace_id: session, surface_id: paneId, key: "enter", }); } killPane(paneId: string, session?: string, server?: string): void { if (!isCmuxId(paneId) || !isCmuxId(session)) { throw new Error("Invalid cmux surface identity"); } const path = cmuxSocketPath(server); if (!terminalSurface(listSurfaces(path, session), paneId)) return; try { const result = cmuxRequest(path, "surface.close", { workspace_id: session, surface_id: paneId, force: true, }); if ( !sameUUID(result.surface_id, paneId) || !sameUUID(result.workspace_id, session) ) { throw new Error("cmux did not confirm the closed child surface"); } } catch (error) { // Tolerate races with an independently closed surface, not a close // rejection that leaves the target live (or its status unproven). if (this.getPaneLiveness(paneId, session, server) !== "dead") throw error; } } async focusPane(ref: PaneRef): Promise { this.requireListedSurface(ref.paneId, ref.session, ref.server); cmuxRequest(cmuxSocketPath(ref.server), "surface.focus", { workspace_id: ref.session, surface_id: ref.paneId, }); } async capturePane( _ref: PaneRef, _opts: CapturePaneOptions, ): Promise { throw new Error( "cmux does not advertise a verified bounded terminal capture operation", ); } async showNativeViewer(): Promise { return false; } buildAttachCommands({ paneId, session, server, }: { paneId: string; session?: string; server?: string; }) { if (!isCmuxId(paneId) || !isCmuxId(session) || !isMuxSocketPath(server)) { throw new Error("Invalid cmux surface identity"); } const command = `cmux --socket ${shellEscape(server)} focus-panel --workspace ${shellEscape(session)} --panel ${shellEscape(paneId)}`; return { attachCommand: command, focusCommand: command }; } private requireListedSurface( paneId: string, session?: string, server?: string, ): void { if ( !isCmuxId(paneId) || !isCmuxId(session) || !terminalSurface(listSurfaces(cmuxSocketPath(server), session), paneId) ) { throw new Error( "cmux child surface is unavailable or could not be verified", ); } } }