@wrongstack/acp 0.289.0 → 0.291.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/sdk.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/sdk.ts", "../src/agent/stdio-transport.ts", "../src/win32-cmd.ts", "../src/client/websocket-transport.ts", "../src/types/acp-v1.ts", "../src/client/file-server.ts", "../src/client/permission.ts", "../src/client/terminal-server.ts", "../src/client/acp-session.ts", "../src/agent/protocol-handler.ts", "../src/agent/wrongstack-acp-agent.ts", "../src/agent/server-agent-turn.ts", "../src/agent/session-store.ts", "../src/registry/agents.catalog.ts", "../src/integration/run-one-acp-task.ts", "../src/integration/acp-subagent-runner.ts"],
4
- "sourcesContent": ["/**\n * Official ACP TypeScript SDK integration for WrongStack.\n *\n * This module re-exports types and utilities from @agentclientprotocol/sdk\n * alongside WrongStack's own ACP implementation, providing 100% ACP v1\n * type coverage.\n *\n * Import from here when you need the full ACP type surface:\n * import { ACPSession, AcpServer, schema, ... } from '@wrongstack/acp/sdk';\n */\n\n// Re-export the SDK's method constants (never conflict)\nexport {\n AGENT_METHODS,\n CLIENT_METHODS,\n PROTOCOL_METHODS,\n PROTOCOL_VERSION,\n} from '@agentclientprotocol/sdk';\n\n// Re-export the SDK's high-level API\nexport {\n AgentApp,\n ClientApp,\n ActiveSession,\n SessionBuilder,\n methods,\n} from '@agentclientprotocol/sdk';\nexport type {\n AgentContext,\n AgentConnection,\n ClientContext,\n ClientConnection,\n AcpConnection,\n} from '@agentclientprotocol/sdk';\n\n// Re-export server and transports\nexport {\n AcpServer,\n} from '@agentclientprotocol/sdk/experimental/server';\n\nexport {\n createWebSocketStream,\n} from '@agentclientprotocol/sdk/experimental/ws-client';\n\nexport type {\n WebSocketStreamOptions,\n} from '@agentclientprotocol/sdk/experimental/ws-client';\n\nexport {\n createNodeHttpHandler,\n createNodeWebSocketUpgradeHandler,\n} from '@agentclientprotocol/sdk/experimental/node';\n\n// The official ACP JSON schema \u2014 import as JSON for type validation\n// eslint-disable-next-line @typescript-eslint/consistent-type-imports\nimport type schema from '@agentclientprotocol/sdk/schema/schema.json';\nexport type { schema };\n\n// Re-export WrongStack's ACP implementation\nexport {\n ACPSession,\n ACPSessionError,\n textContent,\n imageContent,\n audioContent,\n} from './client/acp-session.js';\nexport type {\n ACPSessionOptions,\n ACPSessionRunResult,\n ACPSessionErrorKind,\n ACPProgressEvent,\n ACPProgressHandler,\n ACPCapturedToolCall,\n ACPCapturedDiff,\n} from './client/acp-session.js';\n\nexport { WebSocketClientTransport } from './client/websocket-transport.js';\nexport type { WebSocketClientTransportOptions } from './client/websocket-transport.js';\nexport type { ACPClientTransport } from './agent/stdio-transport.js';\n\nexport {\n ACPProtocolHandler,\n WRONGSTACK_VERSION,\n} from './agent/protocol-handler.js';\nexport type {\n RunTurn,\n RunTurnResult,\n RunTurnInput,\n SessionState,\n SessionMode,\n SessionConfigOption,\n ProtocolHandlerOptions,\n} from './agent/protocol-handler.js';\n\nexport {\n WrongStackACPServer,\n} from './agent/wrongstack-acp-agent.js';\nexport type {\n WrongStackACPServerOptions,\n} from './agent/wrongstack-acp-agent.js';\n\nexport {\n makeACPServerAgentTurn,\n disposeACPServerAgentTurn,\n} from './agent/server-agent-turn.js';\nexport type {\n ACPServerAgentTurnOptions,\n} from './agent/server-agent-turn.js';\n\nexport {\n ACPSessionStore,\n} from './agent/session-store.js';\nexport type {\n SessionStoreOptions,\n} from './agent/session-store.js';\n\nexport {\n FileServer,\n FsError,\n} from './client/file-server.js';\nexport type {\n FileServerOptions,\n ReadFileParams,\n WriteFileParams,\n FsErrorCode,\n} from './client/file-server.js';\n\nexport {\n TerminalServer,\n} from './client/terminal-server.js';\nexport type {\n TerminalServerOptions,\n} from './client/terminal-server.js';\n\nexport {\n defaultPermissionPolicy,\n readOnlyPermissionPolicy,\n makePermissionPolicy,\n} from './client/permission.js';\nexport type {\n PermissionPolicy,\n PermissionRequest,\n} from './client/permission.js';\n\nexport {\n makeACPSubagentRunner,\n makeACPSubagentRunnerWithStop,\n ACP_AGENT_COMMANDS,\n resolveAcpAgentCommand,\n runOneAcpTask,\n probeAcpAgent,\n} from './integration/acp-subagent-runner.js';\nexport type {\n ACPSubagentRunnerOptions,\n AcpAgentCommandOverrides,\n RunOneAcpTaskOptions,\n RunOneAcpTaskResult,\n AcpProbeResult,\n} from './integration/acp-subagent-runner.js';\n", "/**\n * StdioTransport \u2014 bidirectional stdin/stdout communication for ACP.\n *\n * ACP uses newline-delimited JSON-RPC 2.0 messages over stdio:\n * client \u2192 agent: JSON-RPC request/notification on stdin\n * agent \u2192 client: JSON-RPC response/notification on stdout\n *\n * Legacy startup marker support remains for older internal harnesses, but\n * standard ACP agents must not write non-JSON data to stdout.\n */\nimport { expectDefined, writeErr } from '@wrongstack/core';\nimport type { ACPMessage } from '../types/acp-messages.js';\nimport { buildWin32CmdShimInvocation } from '../win32-cmd.js';\nexport interface AgentServerTransport {\n send(msg: ACPMessage): Promise<void>;\n sendRaw(chunk: string): void;\n read(): Promise<ACPMessage | null>;\n close(): void;\n onMessage(handler: (msg: ACPMessage) => void): () => void;\n}\n\n/**\n * Minimal client-side transport contract `ACPSession` drives. `ClientTransport`\n * (stdio subprocess) and `WebSocketClientTransport` (remote) both implement it,\n * so the session is agnostic to how bytes reach the agent.\n */\nexport interface ACPClientTransport {\n start(): Promise<void>;\n send(msg: ACPMessage): Promise<void>;\n onMessage(handler: (msg: ACPMessage) => void): () => void;\n stop(): void;\n}\n\nexport class StdioTransport implements AgentServerTransport {\n private readonly stdin = process.stdin;\n private readonly stdout = process.stdout;\n private readonly stderr = process.stderr;\n\n private buffer = '';\n private readonly handlers = new Set<(msg: ACPMessage) => void>();\n private closed = false;\n private resolveRead: ((msg: ACPMessage | null) => void) | null = null;\n private messageQueue: ACPMessage[] = [];\n\n constructor() {\n this.stdin.resume();\n this.stdin.setEncoding('utf8');\n this.stdin.on('data', (chunk: string) => this.onData(chunk));\n this.stdin.on('end', () => this.handleClose());\n this.stdin.on('error', (err: Error) => this.failAll(err));\n }\n\n sendStartupMarker(): void {\n this.stdout.write('[wstack-acp]\\n', 'utf8');\n }\n\n send(msg: ACPMessage): Promise<void> {\n if (this.closed) return Promise.resolve();\n return new Promise((resolve) => {\n const line = JSON.stringify(msg) + '\\n';\n this.stdout.write(line, 'utf8', () => resolve());\n });\n }\n\n sendRaw(chunk: string): void {\n this.stdout.write(chunk, 'utf8');\n }\n\n read(): Promise<ACPMessage | null> {\n if (this.messageQueue.length > 0) return Promise.resolve(expectDefined(this.messageQueue.shift()));\n if (this.closed) return Promise.resolve(null);\n return new Promise((resolve) => {\n this.resolveRead = resolve;\n });\n }\n\n onMessage(handler: (msg: ACPMessage) => void): () => void {\n this.handlers.add(handler);\n return () => this.handlers.delete(handler);\n }\n\n close(): void {\n this.closed = true;\n this.stdin.pause();\n this.resolveRead?.(null);\n this.resolveRead = null;\n }\n\n private onData(chunk: string): void {\n this.buffer += chunk;\n const lines = this.buffer.split('\\n');\n /* v8 ignore next -- split() always yields \u22651 element, so pop() is never undefined; the ?? '' is defensive. */\n this.buffer = lines.pop() ?? '';\n\n for (const raw of lines) {\n if (!raw.trim()) continue;\n try {\n this.dispatch(JSON.parse(raw) as ACPMessage);\n } catch (err) {\n this.stderr.write(`[wstack-acp parse error] ${err}\\n`, 'utf8');\n }\n }\n }\n\n private dispatch(msg: ACPMessage): void {\n if (this.resolveRead) {\n const resolve = this.resolveRead;\n this.resolveRead = null;\n resolve(msg);\n } else {\n this.messageQueue.push(msg);\n }\n for (const handler of this.handlers) {\n try {\n handler(msg);\n } catch (err) {\n this.stderr.write(`[wstack-acp handler error] ${err}\\n`, 'utf8');\n }\n }\n }\n\n private handleClose(): void {\n this.closed = true;\n this.resolveRead?.(null);\n this.resolveRead = null;\n }\n\n private failAll(err: Error): void {\n this.stderr.write(`[wstack-acp stdin error] ${err.message}\\n`, 'utf8');\n this.close();\n }\n}\n\n// ---------------------------------------------------------------------------\n// ClientTransport \u2014 spawns a child ACP agent process (DIR-1)\n// ---------------------------------------------------------------------------\n\nimport type { EventEmitter } from 'node:events';\n\nexport interface ClientTransportOptions {\n command: string;\n args?: string[] | undefined;\n env?: Record<string, string>;\n cwd?: string | undefined;\n handshakeTimeoutMs?: number | undefined;\n /**\n * Set to true when the child is an external ACP agent (Claude Code,\n * Gemini CLI, Codex CLI, \u2026) that does NOT emit a `[wstack-acp]\\n`\n * marker on startup. The v1 client (`ACPSession`) sets this; the\n * server-side transport (the default) keeps the marker check.\n */\n skipHandshakeMarker?: boolean | undefined;\n}\n\nexport interface ACPChildProcess extends EventEmitter {\n stdout: NodeJS.ReadableStream;\n stdin: NodeJS.WritableStream;\n stderr: NodeJS.ReadableStream;\n pid: number | undefined;\n kill(): void;\n}\n\nexport class ClientTransport implements ACPClientTransport {\n private child: ACPChildProcess | null = null;\n private buffer = '';\n private readonly handlers = new Set<(msg: ACPMessage) => void>();\n private closed = false;\n private resolveRead: ((msg: ACPMessage | null) => void) | null = null;\n private messageQueue: ACPMessage[] = [];\n private readonly opts: Required<Pick<ClientTransportOptions, 'handshakeTimeoutMs'>> &\n ClientTransportOptions;\n\n constructor(options: ClientTransportOptions) {\n this.opts = {\n handshakeTimeoutMs: 30_000,\n ...options,\n };\n }\n\n async start(): Promise<void> {\n if (this.child) return;\n const [{ spawn }, { buildChildEnv }, os] = await Promise.all([\n import('node:child_process'),\n import('@wrongstack/core'),\n import('node:os'),\n ]);\n return new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n reject(\n new Error(`ACP child process failed to start within ${this.opts.handshakeTimeoutMs}ms`),\n );\n }, this.opts.handshakeTimeoutMs);\n\n // `npx`/`uvx` resolve+install the package using the npm/pip config of\n // the spawn cwd. Inside a repo with dependency `overrides` (WrongStack\n // pins undici/jsdom), that install fails with EOVERRIDE and the adapter\n // never starts \u2192 handshake timeout. Spawn package launchers from a\n // NEUTRAL dir (home) so they install cleanly; the agent still learns the\n // project directory via the ACP `session/new` `cwd` param, not this cwd.\n const isPkgLauncher = this.opts.command === 'npx' || this.opts.command === 'uvx';\n const spawnCwd = isPkgLauncher ? os.homedir() : this.opts.cwd;\n\n try {\n const childArgs = this.opts.args ?? [];\n const shim = process.platform === 'win32'\n ? buildWin32CmdShimInvocation(this.opts.command, childArgs)\n : null;\n this.child = spawn(shim?.command ?? this.opts.command, shim?.args ?? childArgs, {\n env: { ...buildChildEnv(), ...this.opts.env },\n cwd: spawnCwd,\n stdio: ['pipe', 'pipe', 'pipe'],\n windowsHide: true,\n ...(shim ? { windowsVerbatimArguments: shim.windowsVerbatimArguments } : {}),\n }) as never as ACPChildProcess;\n /* v8 ignore start -- spawn() throwing synchronously is a defensive guard (e.g. argv0 type errors); the realistic async failure path is the child 'error' event, covered by tests. */\n } catch (err) {\n clearTimeout(timeout);\n reject(err);\n return;\n }\n /* v8 ignore stop */\n\n const child = this.child;\n\n child.stdout.setEncoding('utf8');\n\n let settled = false;\n // Register failure handlers IMMEDIATELY, before either readiness path,\n // so a spawn failure (ENOENT / EACCES) rejects start() instead of\n // emitting an unhandled 'error' event that crashes the host process.\n // This is critical for the skip-marker path (external ACP agents),\n // which previously returned before any 'error' listener was attached.\n const onSpawnFailure = (err: Error): void => {\n if (settled) {\n // Post-ready error: just tear the connection down.\n this.closed = true;\n return;\n }\n settled = true;\n clearTimeout(timeout);\n reject(err);\n };\n child.on('error', onSpawnFailure);\n child.stdout.on('error', onSpawnFailure);\n\n if (this.opts.skipHandshakeMarker) {\n // External ACP agents don't emit a startup marker. Attach the data\n // pump right away so no early output is dropped, then resolve once\n // the OS confirms the process actually spawned (the 'spawn' event).\n // If the binary is missing, 'error' fires instead and rejects above.\n child.stdout.on('data', (c: string) => this.onChildData(c));\n child.stderr.on('data', (c: string) => this.onChildError(c));\n child.on('close', (code: number | null) => this.onChildClose(code));\n child.once('spawn', () => {\n if (settled) return;\n settled = true;\n clearTimeout(timeout);\n resolve();\n });\n return;\n }\n\n const onReady = (): void => {\n if (settled) return;\n settled = true;\n child.stdout.on('data', (c: string) => this.onChildData(c));\n child.stderr.on('data', (c: string) => this.onChildError(c));\n child.on('close', (code: number | null) => this.onChildClose(code));\n clearTimeout(timeout);\n resolve();\n };\n\n const waitForMarker = (chunk: string) => {\n this.buffer += chunk;\n const idx = this.buffer.indexOf('[wstack-acp]\\n');\n if (idx !== -1) {\n this.buffer = this.buffer.slice(idx + '[wstack-acp]\\n'.length);\n child.stdout.removeListener('data', waitForMarker);\n onReady();\n }\n };\n\n child.stdout.on('data', waitForMarker);\n });\n }\n\n send(msg: ACPMessage): Promise<void> {\n if (!this.child) return Promise.reject(new Error('ClientTransport not started'));\n return new Promise((resolve, reject) => {\n const line = JSON.stringify(msg) + '\\n';\n this.child?.stdin.write(line, 'utf8', (err) => {\n if (err) reject(err);\n else resolve();\n });\n });\n }\n\n read(): Promise<ACPMessage | null> {\n if (this.messageQueue.length > 0) return Promise.resolve(expectDefined(this.messageQueue.shift()));\n if (this.closed) return Promise.resolve(null);\n return new Promise((resolve) => {\n this.resolveRead = resolve;\n });\n }\n\n onMessage(handler: (msg: ACPMessage) => void): () => void {\n this.handlers.add(handler);\n return () => this.handlers.delete(handler);\n }\n\n stop(): void {\n if (!this.child) return;\n this.closed = true;\n try {\n this.child.kill();\n } catch {\n // already dead\n }\n this.child = null;\n }\n\n private onChildData(chunk: string): void {\n this.buffer += chunk;\n const lines = this.buffer.split('\\n');\n /* v8 ignore next -- split() always yields \u22651 element, so pop() is never undefined; the ?? '' is defensive. */\n this.buffer = lines.pop() ?? '';\n\n for (const raw of lines) {\n if (!raw.trim()) continue;\n try {\n this.dispatch(JSON.parse(raw) as ACPMessage);\n } catch {\n // skip malformed\n }\n }\n }\n\n private onChildError(chunk: string): void {\n writeErr(`[acp-child stderr] ${chunk}`);\n }\n\n private onChildClose(code: number | null): void {\n this.closed = true;\n this.resolveRead?.(null);\n this.resolveRead = null;\n if (code !== 0 && code !== null) {\n writeErr(`[acp-child exited with code ${code}]\\n`);\n }\n }\n\n private dispatch(msg: ACPMessage): void {\n if (this.resolveRead) {\n const resolve = this.resolveRead;\n this.resolveRead = null;\n resolve(msg);\n } else {\n this.messageQueue.push(msg);\n }\n for (const handler of this.handlers) {\n try {\n handler(msg);\n } catch {\n // non-fatal\n }\n }\n }\n}\n", "const WIN32_CMD_META = /[&|<>\"\\r\\n\\0]/;\n\nexport interface Win32CmdShimInvocation {\n command: string;\n args: string[];\n windowsVerbatimArguments: true;\n}\n\nexport function buildWin32CmdShimInvocation(\n command: string,\n args: readonly string[] = [],\n): Win32CmdShimInvocation {\n assertSafeWin32CmdArgs([command, ...args]);\n const line = ['call', quoteWin32CmdArg(command), ...args.map(quoteWin32CmdArg)].join(' ');\n return {\n command: process.env['COMSPEC'] ?? 'cmd.exe',\n args: ['/d', '/c', line],\n windowsVerbatimArguments: true,\n };\n}\n\nfunction assertSafeWin32CmdArgs(args: readonly unknown[]): void {\n for (const arg of args) {\n if (typeof arg === 'string' && WIN32_CMD_META.test(arg)) {\n throw new Error(\n 'win32 cmd shim spawn: argument contains a shell metacharacter ' +\n '(one of & | < > \", or a newline) that could enable command injection ' +\n 'through the .cmd/.bat wrapper - refusing to run. Offending argument: ' +\n JSON.stringify(arg),\n );\n }\n }\n}\n\nfunction quoteWin32CmdArg(arg: string): string {\n return `\"${arg}\"`;\n}\n", "/**\n * WebSocketClientTransport \u2014 remote ACP transport for `ACPSession`.\n *\n * Connects to a remote ACP agent over a WebSocket (cloud-hosted agents,\n * separate-process agents reachable over the network). Each WebSocket\n * message carries exactly one JSON-RPC 2.0 object \u2014 message boundaries\n * are preserved by the WS framing, so (unlike stdio) no newline delimiter\n * is needed.\n *\n * Uses the Node \u2265 22 built-in global `WebSocket` (undici), so there is no\n * runtime dependency. Per-connection auth headers are not supported by the\n * WHATWG WebSocket client; authenticate over the protocol instead\n * (`ACPSession.authenticate`) or embed a token in the URL query string.\n *\n * Spec: https://agentclientprotocol.com/protocol/v1/overview (remote transport)\n */\n\nimport type { ACPClientTransport } from '../agent/stdio-transport.js';\nimport type { ACPMessage } from '../types/acp-messages.js';\n\nexport interface WebSocketClientTransportOptions {\n /** ws:// or wss:// URL of the remote ACP agent. */\n url: string;\n /** Optional WebSocket subprotocols. */\n protocols?: string | string[] | undefined;\n /** How long to wait for the socket to open. Default 30s. */\n handshakeTimeoutMs?: number | undefined;\n}\n\n/** Narrow view of the global WebSocket we rely on (avoids lib.dom typings). */\ninterface WSLike {\n send(data: string): void;\n close(): void;\n addEventListener(type: 'open', cb: () => void): void;\n addEventListener(type: 'error', cb: (ev: unknown) => void): void;\n addEventListener(type: 'close', cb: () => void): void;\n addEventListener(type: 'message', cb: (ev: { data: unknown }) => void): void;\n}\n\ntype WSConstructor = new (url: string, protocols?: string | string[]) => WSLike;\n\nexport class WebSocketClientTransport implements ACPClientTransport {\n private ws: WSLike | null = null;\n private readonly handlers = new Set<(msg: ACPMessage) => void>();\n private closed = false;\n private readonly opts: WebSocketClientTransportOptions;\n\n constructor(opts: WebSocketClientTransportOptions) {\n this.opts = opts;\n }\n\n start(): Promise<void> {\n const WS = (globalThis as { WebSocket?: WSConstructor }).WebSocket;\n if (!WS) {\n return Promise.reject(\n new Error(\n 'global WebSocket is not available \u2014 Node \u2265 22 is required for the remote ACP transport',\n ),\n );\n }\n const timeoutMs = this.opts.handshakeTimeoutMs ?? 30_000;\n return new Promise<void>((resolve, reject) => {\n let settled = false;\n const ws = new WS(this.opts.url, this.opts.protocols);\n this.ws = ws;\n const timer = setTimeout(() => {\n if (settled) return;\n settled = true;\n try {\n ws.close();\n } catch {\n // ignore\n }\n reject(new Error(`WebSocket failed to open within ${timeoutMs}ms`));\n }, timeoutMs);\n\n ws.addEventListener('open', () => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n resolve();\n });\n ws.addEventListener('error', (ev: unknown) => {\n if (settled) {\n // Post-open errors just tear the connection down.\n this.closed = true;\n return;\n }\n settled = true;\n clearTimeout(timer);\n const message =\n ev && typeof ev === 'object' && 'message' in ev\n ? String((ev as { message: unknown }).message)\n : 'WebSocket error';\n reject(new Error(message));\n });\n ws.addEventListener('close', () => {\n this.closed = true;\n });\n ws.addEventListener('message', (ev: { data: unknown }) => {\n this.onData(ev.data);\n });\n });\n }\n\n send(msg: ACPMessage): Promise<void> {\n if (this.closed || !this.ws) {\n return Promise.reject(new Error('WebSocket transport is not open'));\n }\n try {\n this.ws.send(JSON.stringify(msg));\n return Promise.resolve();\n } catch (err) {\n return Promise.reject(err instanceof Error ? err : new Error(String(err)));\n }\n }\n\n onMessage(handler: (msg: ACPMessage) => void): () => void {\n this.handlers.add(handler);\n return () => this.handlers.delete(handler);\n }\n\n stop(): void {\n this.closed = true;\n if (this.ws) {\n try {\n this.ws.close();\n } catch {\n // already closed\n }\n this.ws = null;\n }\n }\n\n private onData(data: unknown): void {\n const text =\n typeof data === 'string'\n ? data\n : data instanceof ArrayBuffer\n ? Buffer.from(data).toString('utf8')\n : Buffer.isBuffer(data)\n ? data.toString('utf8')\n : String(data);\n if (!text.trim()) return;\n let msg: ACPMessage;\n try {\n msg = JSON.parse(text) as ACPMessage;\n } catch {\n // A remote agent that frames multiple JSON objects per message is\n // non-conformant; try newline-splitting as a fallback before dropping.\n for (const line of text.split('\\n')) {\n if (!line.trim()) continue;\n try {\n this.dispatch(JSON.parse(line) as ACPMessage);\n } catch {\n // skip malformed fragment\n }\n }\n return;\n }\n this.dispatch(msg);\n }\n\n private dispatch(msg: ACPMessage): void {\n for (const handler of [...this.handlers]) {\n try {\n handler(msg);\n } catch {\n // a faulty consumer must not break the socket pump\n }\n }\n }\n}\n", "/**\n * ACP v1 type definitions \u2014 Agent Client Protocol, stable v1 spec.\n *\n * Scope: discriminated union for the `session/update` notification payload\n * (the `update` field of a `session/update` JSON-RPC notification), plus the\n * subset of supporting types it depends on.\n *\n * Spec: https://agentclientprotocol.com/protocol/v1/overview\n *\n * Design notes\n * \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n * \u2022 The stable v1 spec defines 11 `sessionUpdate` discriminator values. We\n * type exactly those 11, plus an `_unstable_*` escape hatch for v2-RFD\n * kinds (e.g. `next_edit_suggestions`, `elicitation`) that real agents\n * may emit before the spec stabilises them, and an `unknown` fallback for\n * everything else. We do NOT synthesise 32 fake variants to match a\n * number cited in passing \u2014 the union is honest about the surface.\n *\n * \u2022 Per the spec's conventions, discriminator values use snake_case. The\n * property keys inside each variant are camelCase (the JSON-RPC envelope\n * is JSON-RPC 2.0, everything else is camelCase unless the spec says\n * otherwise).\n *\n * \u2022 Optional fields that the spec marks optional are marked `?:`. Required\n * fields have no `?`. We do not include spec fields the spec marks\n * \"SHOULD NOT\" or \"reserved\".\n *\n * \u2022 The existing `acp-messages.ts` types describe an older draft of the\n * protocol (string `protocolVersion: '2024-11'`, fake `tools/call`\n * method, etc.). Do NOT import from it here \u2014 `acp-v1.ts` is\n * self-contained so the new code path can be reviewed in isolation and\n * deleted wholesale if the rewrite is ever reverted.\n */\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Shared building blocks\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Stable protocol version (integer per the spec, not a date-string). */\nexport const ACP_PROTOCOL_VERSION = 1 as const;\nexport type ACPProtocolVersion = typeof ACP_PROTOCOL_VERSION;\n\n/** Per the spec: opaque, unique id. We type as branded string. */\nexport type SessionId = string & { readonly __acpSessionId: unique symbol };\nexport type ToolCallId = string & { readonly __acpToolCallId: unique symbol };\nexport type MessageId = string & { readonly __acpMessageId: unique symbol };\nexport type TerminalId = string & { readonly __acpTerminalId: unique symbol };\nexport type PlanEntryId = string & { readonly __acpPlanEntryId: unique symbol };\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Implementation metadata\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface Implementation {\n /** Programmatic/logical name \u2014 also a display-name fallback if title is absent. */\n name: string;\n /** Human-readable display name for UI contexts. */\n title?: string | undefined;\n /** Version string (display/debug/metrics). */\n version: string;\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Client capabilities \u2014 sent in the initialize request\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface ClientCapabilities {\n fs?: {\n readTextFile?: boolean | undefined;\n writeTextFile?: boolean | undefined;\n } | undefined;\n terminal?: boolean | undefined;\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Agent capabilities \u2014 received in the initialize response\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface PromptCapabilities {\n image?: boolean | undefined;\n audio?: boolean | undefined;\n embeddedContext?: boolean | undefined;\n}\n\nexport interface McpCapabilities {\n http?: boolean | undefined;\n sse?: boolean | undefined;\n}\n\nexport interface SessionCapabilities {\n close?: Record<string, unknown> | undefined;\n list?: Record<string, unknown> | undefined;\n delete?: Record<string, unknown> | undefined;\n resume?: Record<string, unknown> | undefined;\n additionalDirectories?: Record<string, unknown> | undefined;\n}\n\nexport interface AuthCapabilities {\n logout?: Record<string, unknown> | undefined;\n}\n\nexport interface AgentCapabilities {\n loadSession?: boolean | undefined;\n promptCapabilities?: PromptCapabilities | undefined;\n mcpCapabilities?: McpCapabilities | undefined;\n sessionCapabilities?: SessionCapabilities | undefined;\n auth?: AuthCapabilities | undefined;\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Authentication\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface AuthMethod {\n id: string;\n name: string;\n description?: string | undefined;\n type?: 'agent' | 'oauth' | 'http' | undefined;\n}\n\nexport interface AuthenticateRequest {\n methodId: string;\n}\n\nexport type AuthenticateResponse = {}\n\nexport type LogoutRequest = {}\n\nexport type LogoutResponse = {}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// MCP server configuration \u2014 sent in session lifecycle requests\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface StdioMcpServer {\n name: string;\n command: string;\n args?: string[] | undefined;\n env?: { name: string; value: string }[] | undefined;\n}\n\nexport interface HttpMcpServer {\n type: 'http';\n name: string;\n url: string;\n headers?: { name: string; value: string }[] | undefined;\n}\n\nexport interface SseMcpServer {\n type: 'sse';\n name: string;\n url: string;\n headers?: { name: string; value: string }[] | undefined;\n}\n\nexport type McpServer = StdioMcpServer | HttpMcpServer | SseMcpServer;\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Session lifecycle \u2014 request/response types\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface NewSessionRequest {\n cwd: string;\n mcpServers: McpServer[];\n additionalDirectories?: string[] | undefined;\n}\n\nexport interface NewSessionResponse {\n sessionId: SessionId;\n initialMode?: SessionModeState | null | undefined;\n configOptions?: SessionConfigOption[] | null | undefined;\n}\n\nexport interface LoadSessionRequest {\n sessionId: SessionId;\n cwd: string;\n mcpServers: McpServer[];\n additionalDirectories?: string[] | undefined;\n}\n\nexport interface LoadSessionResponse {\n initialMode?: SessionModeState | null | undefined;\n configOptions?: SessionConfigOption[] | null | undefined;\n}\n\nexport interface ResumeSessionRequest {\n sessionId: SessionId;\n cwd: string;\n mcpServers: McpServer[];\n additionalDirectories?: string[] | undefined;\n}\n\nexport interface ResumeSessionResponse {\n initialMode?: SessionModeState | null | undefined;\n configOptions?: SessionConfigOption[] | null | undefined;\n}\n\nexport interface CloseSessionRequest {\n sessionId: SessionId;\n}\n\nexport type CloseSessionResponse = {}\n\nexport interface ListSessionsRequest {\n cursor?: string | undefined;\n cwd?: string | undefined;\n}\n\nexport interface ListSessionsResponse {\n sessions: SessionInfo[];\n nextCursor?: string | undefined;\n}\n\nexport interface DeleteSessionRequest {\n sessionId: SessionId;\n}\n\nexport type DeleteSessionResponse = {}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Session config options\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface SessionConfigOption {\n id: string;\n name: string;\n description?: string | undefined;\n category?: ConfigOptionCategory | undefined;\n type: ConfigOptionType;\n defaultValue?: string | undefined;\n currentValue: string;\n options: ConfigOptionValue[];\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Content blocks \u2014 reused from MCP per the spec\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Annotations attached to a content block. Optional, agent-supplied hint\n * about audience/priority. Spec leaves shape open; we mirror the fields\n * the spec shows in its examples.\n */\nexport interface ContentAnnotations {\n audience?: ('user' | 'assistant')[] | undefined;\n priority?: number | undefined;\n [key: string]: unknown;\n}\n\nexport interface TextContent {\n type: 'text';\n text: string;\n annotations?: ContentAnnotations | undefined;\n}\n\nexport interface ImageContent {\n type: 'image';\n mimeType: string;\n /** Base64-encoded image data. */\n data: string;\n uri?: string | undefined;\n annotations?: ContentAnnotations | undefined;\n}\n\nexport interface AudioContent {\n type: 'audio';\n mimeType: string;\n /** Base64-encoded audio data. */\n data: string;\n annotations?: ContentAnnotations | undefined;\n}\n\nexport interface TextResourceContents {\n uri: string;\n mimeType?: string | undefined;\n text: string;\n}\n\nexport interface BlobResourceContents {\n uri: string;\n mimeType?: string | undefined;\n /** Base64-encoded binary. */\n blob: string;\n}\n\nexport type EmbeddedResourceContents = TextResourceContents | BlobResourceContents;\n\nexport interface EmbeddedResourceContent {\n type: 'resource';\n resource: EmbeddedResourceContents;\n annotations?: ContentAnnotations | undefined;\n}\n\nexport interface ResourceLinkContent {\n type: 'resource_link';\n uri: string;\n name: string;\n mimeType?: string | undefined;\n title?: string | undefined;\n description?: string | undefined;\n size?: number | undefined;\n annotations?: ContentAnnotations | undefined;\n}\n\nexport type ContentBlock =\n | TextContent\n | ImageContent\n | AudioContent\n | EmbeddedResourceContent\n | ResourceLinkContent;\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Tool calls\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport type ToolKind =\n | 'read'\n | 'edit'\n | 'delete'\n | 'move'\n | 'search'\n | 'execute'\n | 'think'\n | 'fetch'\n | 'switch_mode'\n | 'other';\n\nexport type ToolCallStatus = 'pending' | 'in_progress' | 'completed' | 'failed';\n\n/** A single concrete content payload attached to a tool call. */\nexport type ToolCallContent =\n | { type: 'content'; content: ContentBlock }\n | {\n type: 'diff';\n path: string;\n oldText: string | null;\n newText: string;\n }\n | { type: 'terminal'; terminalId: TerminalId };\n\nexport interface ToolCallLocation {\n path: string;\n /** 1-based per the spec's argument requirements. */\n line?: number | undefined;\n}\n\nexport interface ToolCall {\n toolCallId: ToolCallId;\n title: string;\n kind?: ToolKind | undefined;\n status?: ToolCallStatus | undefined;\n content?: ToolCallContent[] | undefined;\n locations?: ToolCallLocation[] | undefined;\n rawInput?: Record<string, unknown> | undefined;\n rawOutput?: Record<string, unknown> | undefined;\n}\n\n/**\n * Partial update of a previously-emitted tool call. All fields except\n * `toolCallId` are optional \u2014 only the changed fields are included.\n * Declared standalone (not `extends ToolCall`) because `title` is required\n * on `ToolCall` but optional here; the structural variance is the point.\n */\nexport interface ToolCallUpdateFields {\n toolCallId: ToolCallId;\n status?: ToolCallStatus | undefined;\n content?: ToolCallContent[] | undefined;\n title?: string | undefined;\n kind?: ToolKind | undefined;\n locations?: ToolCallLocation[] | undefined;\n rawInput?: Record<string, unknown> | undefined;\n rawOutput?: Record<string, unknown> | undefined;\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Plan\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport type PlanEntryPriority = 'high' | 'medium' | 'low';\nexport type PlanEntryStatus = 'pending' | 'in_progress' | 'completed';\n\nexport interface PlanEntry {\n /** Required by the spec for the array shape, but per-entry id is optional. */\n content: string;\n priority: PlanEntryPriority;\n status: PlanEntryStatus;\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Slash commands\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface AvailableCommandInput {\n hint: string;\n}\n\nexport interface AvailableCommand {\n name: string;\n description: string;\n input?: AvailableCommandInput | undefined;\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Session modes\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport type SessionModeId = string & { readonly __acpModeId: unique symbol };\n\nexport interface SessionMode {\n id: SessionModeId;\n name: string;\n description?: string | undefined;\n}\n\nexport interface SessionModeState {\n currentModeId: SessionModeId;\n availableModes: SessionMode[];\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Config options\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Reserved spec categories. Underscore-prefixed names are free for custom use. */\nexport type ConfigOptionCategory =\n | 'mode'\n | 'model'\n | 'thought_level'\n | `_${string}`;\n\nexport type ConfigOptionType = 'select' | string;\n\nexport interface ConfigOptionValue {\n value: string;\n name: string;\n description?: string | undefined;\n}\n\nexport interface ConfigOption {\n id: string;\n name: string;\n description?: string | undefined;\n category?: ConfigOptionCategory | undefined;\n type: ConfigOptionType;\n currentValue: string;\n options: ConfigOptionValue[];\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Session info\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface SessionInfo {\n sessionId: SessionId;\n cwd: string;\n title?: string | undefined;\n updatedAt?: string | undefined;\n /** Agent-supplied extension metadata; opaque to clients. */\n _meta?: Record<string, unknown> | undefined;\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Usage (token / cost) updates\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface UsageCost {\n amount: number;\n /** ISO 4217 currency code, e.g. \"USD\". */\n currency: string;\n}\n\nexport interface UsageUpdate {\n /** Tokens used in the current session context. Required, non-null. */\n used: number;\n /** Total context window size in tokens. Required, non-null. */\n size: number;\n cost?: UsageCost | undefined;\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Permission requests\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport type PermissionOptionKind =\n | 'allow_once'\n | 'allow_always'\n | 'reject_once'\n | 'reject_always';\n\nexport interface PermissionOption {\n optionId: string;\n name: string;\n kind: PermissionOptionKind;\n}\n\nexport type RequestPermissionOutcome =\n | { outcome: 'cancelled' }\n | { outcome: 'selected'; optionId: string };\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Stop reasons\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport type StopReason =\n | 'end_turn'\n | 'max_tokens'\n | 'max_turn_requests'\n | 'refusal'\n | 'cancelled'\n | string;\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// SessionUpdate \u2014 the discriminated union\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Stable v1 variants. The spec currently defines exactly 11. */\nexport type SessionUpdate =\n | UserMessageChunkUpdate\n | AgentMessageChunkUpdate\n | ThoughtChunkUpdate\n | ToolCallUpdateUpdate\n | ToolCallUpdateNotification\n | PlanUpdate\n | AvailableCommandsUpdate\n | CurrentModeUpdate\n | ConfigOptionUpdate\n | SessionInfoUpdate\n | UsageUpdateUpdate;\n\n// --- Streaming message chunks -----------------------------------------------\n\nexport interface UserMessageChunkUpdate {\n sessionUpdate: 'user_message_chunk';\n messageId?: MessageId | undefined;\n content: ContentBlock;\n}\n\nexport interface AgentMessageChunkUpdate {\n sessionUpdate: 'agent_message_chunk';\n messageId?: MessageId | undefined;\n content: ContentBlock;\n}\n\nexport interface ThoughtChunkUpdate {\n sessionUpdate: 'thought_chunk';\n messageId?: MessageId | undefined;\n content: ContentBlock;\n}\n\n// --- Tool calls ------------------------------------------------------------\n\n/** First notification for a new tool call. */\nexport interface ToolCallUpdateUpdate {\n sessionUpdate: 'tool_call';\n toolCallId: ToolCallId;\n title: string;\n kind?: ToolKind | undefined;\n status?: ToolCallStatus | undefined;\n content?: ToolCallContent[] | undefined;\n locations?: ToolCallLocation[] | undefined;\n rawInput?: Record<string, unknown> | undefined;\n}\n\n/** Subsequent updates to a previously-emitted tool call. */\nexport interface ToolCallUpdateNotification {\n sessionUpdate: 'tool_call_update';\n toolCallId: ToolCallId;\n status?: ToolCallStatus | undefined;\n content?: ToolCallContent[] | undefined;\n title?: string | undefined;\n kind?: ToolKind | undefined;\n locations?: ToolCallLocation[] | undefined;\n rawInput?: Record<string, unknown> | undefined;\n rawOutput?: Record<string, unknown> | undefined;\n}\n\n// --- Plan ------------------------------------------------------------------\n\nexport interface PlanUpdate {\n sessionUpdate: 'plan';\n entries: PlanEntry[];\n}\n\n// --- Commands / modes / config ---------------------------------------------\n\nexport interface AvailableCommandsUpdate {\n sessionUpdate: 'available_commands_update';\n availableCommands: AvailableCommand[];\n}\n\nexport interface CurrentModeUpdate {\n sessionUpdate: 'current_mode_update';\n modeId: SessionModeId;\n}\n\nexport interface ConfigOptionUpdate {\n sessionUpdate: 'config_option_update';\n configOptions: ConfigOption[];\n}\n\n// --- Session metadata ------------------------------------------------------\n\nexport interface SessionInfoUpdate {\n sessionUpdate: 'session_info_update';\n title?: string | null | undefined;\n updatedAt?: string | null | undefined;\n _meta?: Record<string, unknown> | undefined;\n}\n\n// --- Usage -----------------------------------------------------------------\n\nexport interface UsageUpdateUpdate {\n sessionUpdate: 'usage_update';\n used: number;\n size: number;\n cost?: UsageCost | undefined;\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Escape hatches: unknown / unstable\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Escape hatch for v2-RFD `sessionUpdate` kinds that have been published\n * but are not yet stabilised in the v1 spec. Examples seen in the wild:\n * `next_edit_suggestions`, `elicitation`, `proxy_extension`. We surface\n * the raw payload so forward-compat code can switch on\n * `kind === 'next_edit_suggestions'` etc. without losing the data.\n */\nexport interface UnstableSessionUpdate {\n sessionUpdate: `_unstable_${string}`;\n [key: string]: unknown;\n}\n\n/**\n * Last-resort variant: the agent sent a discriminator string we don't\n * recognise at all. The full payload is preserved as a record so consumers\n * can still log/inspect it. Prefer matching the known variants first.\n */\nexport interface UnknownSessionUpdate {\n sessionUpdate: string;\n [key: string]: unknown;\n}\n\n/** The full union, including escape hatches. */\nexport type AnySessionUpdate = SessionUpdate | UnstableSessionUpdate | UnknownSessionUpdate;\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Top-level notification envelope\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface SessionUpdateNotification {\n jsonrpc?: '2.0' | undefined;\n method: 'session/update';\n params: {\n sessionId: SessionId;\n update: AnySessionUpdate;\n };\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Type guards\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Exhaustiveness helper. Call from the `default:` branch of a switch on\n * `sessionUpdate` to get a compile-time error when a new variant is added\n * without updating the consumer.\n */\nexport function assertNeverSessionUpdate(x: never): never {\n throw new Error(\n `Unhandled sessionUpdate: ${JSON.stringify(x)}`,\n );\n}\n", "/**\n * FileServer \u2014 answers `fs/read_text_file` and `fs/write_text_file`\n * from an ACP agent, scoped to a single project root.\n *\n * Per the spec, all file paths in ACP MUST be absolute. We additionally\n * require them to resolve under `projectRoot` after normalisation AND after\n * resolving symlinks (`fs.realpath`). A path that passes a lexical prefix\n * check but points outside the root via an in-project symlink/junction is\n * rejected. This closes the CWE-22/CWE-59 symlink-escape vector that a\n * purely textual containment check leaves open.\n *\n * The server itself is transport-agnostic: the caller (ACPSession)\n * routes incoming fs/* requests to `readTextFile`/`writeTextFile` and\n * sends the result back. Keeping the routing out of this class lets the\n * file logic be unit-tested in isolation.\n */\nimport { randomBytes } from 'node:crypto';\nimport { realpathSync } from 'node:fs';\nimport * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\n\nexport interface FileServerOptions {\n /** Absolute path; only files under this root are accessible. */\n projectRoot: string;\n /** Per-call timeout, default 30s. */\n timeoutMs?: number;\n /**\n * Hard cap on the number of bytes that may be read in a single\n * `readTextFile` call. Protects against a malicious agent requesting a\n * gigantic file to exhaust host memory. Default 5 MiB.\n */\n maxReadBytes?: number;\n /**\n * Hard cap on the number of bytes that may be written in a single\n * `writeTextFile` call. Default 5 MiB.\n */\n maxWriteBytes?: number;\n}\n\nexport interface ReadFileParams {\n sessionId: string;\n path: string;\n}\n\nexport interface WriteFileParams {\n sessionId: string;\n path: string;\n content: string;\n}\n\nexport type FsErrorCode =\n | 'ENOENT'\n | 'EACCES'\n | 'OUTSIDE_ROOT'\n | 'TIMEOUT'\n | 'INVALID_PATH'\n | 'TOO_LARGE';\n\nconst DEFAULT_MAX_READ_BYTES = 5 * 1024 * 1024;\nconst DEFAULT_MAX_WRITE_BYTES = 5 * 1024 * 1024;\n\n/**\n * Thrown for protocol-level rejections (path outside root, etc.).\n * The session converts these into JSON-RPC error responses.\n */\nexport class FsError extends Error {\n readonly code: FsErrorCode;\n readonly path: string;\n constructor(code: FsErrorCode, path: string, message: string) {\n super(message);\n this.name = 'FsError';\n this.code = code;\n this.path = path;\n }\n}\n\nexport class FileServer {\n private readonly root: string;\n private readonly realRoot: string;\n private readonly timeoutMs: number;\n private readonly maxReadBytes: number;\n private readonly maxWriteBytes: number;\n\n constructor(opts: FileServerOptions) {\n this.root = path.resolve(opts.projectRoot);\n // Resolve the root itself once \u2014 it may be a symlink (macOS /var \u2192\n // /private/var, Windows 8.3 short names, etc.). All realpaths are\n // compared against this canonical root for a like-for-like check.\n // Synchronous in constructor: the root must exist for an ACP session\n // and this keeps the per-call path simple.\n this.realRoot = safeRealpathSync(this.root);\n this.timeoutMs = opts.timeoutMs ?? 30_000;\n this.maxReadBytes = opts.maxReadBytes ?? DEFAULT_MAX_READ_BYTES;\n this.maxWriteBytes = opts.maxWriteBytes ?? DEFAULT_MAX_WRITE_BYTES;\n }\n\n /** Read a text file. Returns the content as a string. */\n async readTextFile(params: ReadFileParams): Promise<{ content: string }> {\n const safe = await this.resolveInside(params.path);\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n try {\n // Size check before reading to prevent loading a huge file.\n const stat = await fsp.stat(safe).catch((err) => {\n throw mapFsError(err, safe);\n });\n if (stat.size > this.maxReadBytes) {\n throw new FsError(\n 'TOO_LARGE',\n safe,\n `file is ${stat.size} bytes, max read is ${this.maxReadBytes} bytes`,\n );\n }\n const content = await fsp.readFile(safe, {\n encoding: 'utf8',\n signal: controller.signal,\n });\n return { content };\n } catch (err) {\n if (err instanceof FsError) throw err;\n if (controller.signal.aborted) {\n throw new FsError('TIMEOUT', safe, `readTextFile timed out after ${this.timeoutMs}ms`);\n }\n throw mapFsError(err, safe);\n } finally {\n clearTimeout(timer);\n }\n }\n\n /** Write a text file. Atomic via write-then-rename. */\n async writeTextFile(params: WriteFileParams): Promise<void> {\n const byteLength = Buffer.byteLength(params.content, 'utf8');\n if (byteLength > this.maxWriteBytes) {\n throw new FsError(\n 'TOO_LARGE',\n params.path,\n `content is ${byteLength} bytes, max write is ${this.maxWriteBytes} bytes`,\n );\n }\n\n const safe = await this.resolveInside(params.path);\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n const tmp = `${safe}.${randomBytes(6).toString('hex')}.tmp`;\n try {\n await fsp.writeFile(tmp, params.content, {\n encoding: 'utf8',\n signal: controller.signal,\n });\n // Re-verify both tmp and the rename destination's parent dir before\n // rename. This closes the TOCTOU window where an attacker could plant a\n // symlink at the destination's parent between resolveInside and rename.\n await this.assertRealInside(tmp);\n await this.assertRealInside(path.dirname(safe));\n await fsp.rename(tmp, safe);\n } catch (err) {\n if (err instanceof FsError) {\n // Best-effort cleanup of the tmp file\n await fsp.unlink(tmp).catch(() => undefined);\n throw err;\n }\n // Best-effort cleanup of the tmp file\n try {\n await fsp.unlink(tmp);\n } catch {\n // tmp didn't exist; ignore\n }\n if (controller.signal.aborted) {\n throw new FsError('TIMEOUT', safe, `writeTextFile timed out after ${this.timeoutMs}ms`);\n }\n throw mapFsError(err, safe);\n } finally {\n clearTimeout(timer);\n }\n }\n\n /**\n * Resolve a path and verify it is inside the project root by realpath.\n * Rejects with `FsError` if the textual path, the resolved path, or the\n * real (symlink-resolved) path escapes the project root.\n *\n * For files that don't exist yet (e.g. a write to a new file), the\n * nearest existing ancestor directory is realpath-checked instead.\n */\n private async resolveInside(p: string): Promise<string> {\n if (typeof p !== 'string' || p.length === 0) {\n throw new FsError('INVALID_PATH', p, 'path is empty or not a string');\n }\n if (!path.isAbsolute(p)) {\n throw new FsError('INVALID_PATH', p, 'path must be absolute (ACP requirement)');\n }\n const resolved = path.resolve(p);\n // +path.sep prevents \"/project-evil\" matching \"/project\" as a prefix.\n const rootWithSep = this.root.endsWith(path.sep) ? this.root : this.root + path.sep;\n if (resolved !== this.root && !resolved.startsWith(rootWithSep)) {\n throw new FsError('OUTSIDE_ROOT', resolved, 'path is outside the project root');\n }\n\n // Now resolve symlinks and compare against the canonical root.\n await this.assertRealInside(resolved);\n return resolved;\n }\n\n /**\n * Resolve `resolvedPath` through `fs.realpath` and verify the result is\n * inside `realRoot`. For non-existent paths (new files), walk up to the\n * nearest existing ancestor and check that instead.\n */\n private async assertRealInside(resolvedPath: string): Promise<void> {\n let probe = resolvedPath;\n for (;;) {\n let real: string;\n try {\n real = await fsp.realpath(probe);\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === 'ENOENT') {\n const parent = path.dirname(probe);\n if (parent === probe) return; // reached fs root without escaping\n probe = parent;\n continue;\n }\n throw mapFsError(err, resolvedPath);\n }\n if (real === this.realRoot || real.startsWith(this.realRoot + path.sep)) return;\n throw new FsError(\n 'OUTSIDE_ROOT',\n resolvedPath,\n 'path resolves through a symlink outside the project root',\n );\n }\n }\n}\n\nfunction mapFsError(err: unknown, p: string): FsError {\n const code = (err as NodeJS.ErrnoException | undefined)?.code;\n if (code === 'ENOENT') return new FsError('ENOENT', p, `no such file: ${p}`);\n if (code === 'EACCES' || code === 'EPERM') {\n return new FsError('EACCES', p, `permission denied: ${p}`);\n }\n const msg = err instanceof Error ? err.message : String(err);\n return new FsError('INVALID_PATH', p, msg);\n}\n\n/**\n * Synchronous realpath that falls back to the input on failure (root may be\n * a fresh directory that hasn't been statted yet). The constructor needs the\n * canonical root before any async call so per-request resolveInside has a\n * stable comparison target.\n */\nfunction safeRealpathSync(p: string): string {\n try {\n return realpathSync(p);\n } catch {\n return p;\n }\n}\n", "/**\n * Permission policy for ACP v1 client sessions.\n *\n * ACP agents can call `session/request_permission` to ask the user\n * before executing a tool call. The client is expected to surface\n * the question, get a decision, and respond. This module is the seam\n * where WrongStack-specific permission UI can plug in; for v1 we ship\n * a minimal default that auto-approves the first `allow_once` option\n * (or `allow_always` if present) and rejects on abort.\n */\nimport type {\n PermissionOption,\n RequestPermissionOutcome,\n ToolCallUpdateNotification,\n} from '../types/acp-v1.js';\n\n/** A single permission decision request. */\nexport interface PermissionRequest {\n toolCall: ToolCallUpdateNotification;\n options: readonly PermissionOption[];\n signal: AbortSignal;\n}\n\n/** A permission policy decides how to respond to a request. */\nexport type PermissionPolicy = (\n req: PermissionRequest,\n) => Promise<RequestPermissionOutcome>;\n\n/**\n * Default policy: pick the safest-looking allow option if the signal\n * is not aborted, otherwise report cancelled. Order of preference:\n *\n * 1. `allow_always`\n * 2. `allow_once`\n * 3. anything else with `optionId` (last resort)\n *\n * Real WrongStack permission UIs replace this; the contract is the\n * `PermissionPolicy` function type, not the implementation.\n */\nfunction pickAllow(\n options: readonly PermissionOption[],\n): RequestPermissionOutcome {\n const ranked = [...options].sort((a, b) => {\n const score = (k: PermissionOption['kind']): number => {\n if (k === 'allow_once') return 0; // prefer once over always \u2014 least standing grant\n if (k === 'allow_always') return 1;\n if (k === 'reject_once') return 2;\n return 3;\n };\n return score(a.kind) - score(b.kind);\n });\n const chosen = ranked[0];\n if (!chosen || chosen.kind === 'reject_once' || chosen.kind === 'reject_always') {\n return { outcome: 'cancelled' };\n }\n return { outcome: 'selected', optionId: chosen.optionId };\n}\n\nfunction pickReject(\n options: readonly PermissionOption[],\n): RequestPermissionOutcome {\n const reject = options.find(\n (o) => o.kind === 'reject_once' || o.kind === 'reject_always',\n );\n return reject ? { outcome: 'selected', optionId: reject.optionId } : { outcome: 'cancelled' };\n}\n\n/**\n * Tool kinds considered side-effect-free (safe to auto-approve even in a\n * non-interactive run). Everything else (edit/delete/move/execute) mutates\n * the workspace or runs commands and should be gated by a real policy.\n */\nconst READ_ONLY_KINDS = new Set(['read', 'search', 'fetch', 'think']);\n\n/**\n * Default policy: auto-approve the least-standing allow option.\n *\n * \u26A0\uFE0F This auto-approves EVERY tool call, including file writes and shell\n * commands. It exists so non-interactive contexts (CLI `acp spawn`,\n * the Director fan-out) work without a human in the loop. Interactive\n * surfaces (TUI/WebUI) MUST inject a policy that surfaces the request to\n * the user \u2014 pass `permissionPolicy` to `ACPSession` / the subagent runner.\n * For untrusted agents prefer {@link readOnlyPermissionPolicy}.\n */\nexport const defaultPermissionPolicy: PermissionPolicy = async (req) => {\n if (req.signal.aborted) return { outcome: 'cancelled' };\n return pickAllow(req.options);\n};\n\n/**\n * Safe-by-default policy: auto-approve only side-effect-free tool calls\n * (read/search/fetch/think); reject anything that would write files or\n * run commands. Use this when driving an untrusted external agent and no\n * interactive surface is available to ask the user.\n */\nexport const readOnlyPermissionPolicy: PermissionPolicy = async (req) => {\n if (req.signal.aborted) return { outcome: 'cancelled' };\n const kind = req.toolCall.kind;\n if (kind && READ_ONLY_KINDS.has(kind)) {\n return pickAllow(req.options);\n }\n return pickReject(req.options);\n};\n\n/**\n * Build a policy from a yes/no decision function. The decider receives the\n * tool call (title + kind + rawInput) and returns whether to allow it.\n * This is the seam an interactive host (TUI/WebUI confirm prompt, trust\n * store, exec-allowlist) plugs into.\n */\nexport function makePermissionPolicy(\n decide: (req: PermissionRequest) => boolean | Promise<boolean>,\n): PermissionPolicy {\n return async (req) => {\n if (req.signal.aborted) return { outcome: 'cancelled' };\n const allow = await decide(req);\n return allow ? pickAllow(req.options) : pickReject(req.options);\n };\n}\n", "/**\n * TerminalServer \u2014 answers `terminal/*` methods from an ACP agent.\n *\n * The spec lets agents spawn shell commands inside the client's\n * environment and observe their output. We honour the protocol, but\n * every command runs under a per-process timeout and a byte limit on\n * retained output, both to keep runaway agents from filling memory\n * and to give the runner a clean signal when something is stuck.\n *\n * Scoping: commands run with `cwd` set to the agent's requested cwd\n * if its canonical path is inside `projectRoot`, else `projectRoot`.\n * Agent env entries are overlaid on a credential-scrubbed base, except\n * for variables that enable preload injection or path hijacking.\n */\nimport { spawn } from 'node:child_process';\nimport { realpathSync } from 'node:fs';\nimport * as path from 'node:path';\nimport { buildChildEnv } from '@wrongstack/core/utils';\n\nexport interface TerminalServerOptions {\n projectRoot: string;\n /** Hard cap on per-command wall-clock. Default 5 minutes. */\n commandTimeoutMs?: number;\n /** Bytes of output to retain per terminal. Default 1 MiB. */\n outputByteLimit?: number;\n /**\n * Hard maximum cap on the per-call `outputByteLimit`. The agent can request\n * a lower limit per terminal/create, but it can never raise it above this\n * host-configured ceiling. Protects against memory exhaustion from a\n * malicious agent requesting `outputByteLimit: Infinity`. Default 16 MiB.\n */\n maxOutputByteLimit?: number;\n /** Optional abort signal that kills ALL active terminals. */\n signal?: AbortSignal;\n}\n\ninterface TerminalState {\n proc: ReturnType<typeof spawn>;\n cwd: string;\n command: string;\n args: string[];\n /** Output buffer as a string; appended as bytes arrive. */\n output: string;\n /** Bytes currently retained (post-truncation). */\n retainedBytes: number;\n /** True once we've dropped output to fit under the per-call byte limit. */\n truncated: boolean;\n exitStatus?: { exitCode: number | null; signal: string | null } | undefined;\n /** Resolves when the process exits. */\n exitPromise: Promise<{ exitCode: number | null; signal: string | null }>;\n /** Per-terminal timeout handle. */\n timeoutHandle: ReturnType<typeof setTimeout> | null;\n}\n\nexport class TerminalServer {\n private readonly terminals = new Map<string, TerminalState>();\n private readonly projectRoot: string;\n private readonly commandTimeoutMs: number;\n private readonly outputByteLimit: number;\n private readonly maxOutputByteLimit: number;\n private nextId = 1;\n\n constructor(opts: TerminalServerOptions) {\n this.projectRoot = path.resolve(opts.projectRoot);\n this.commandTimeoutMs = opts.commandTimeoutMs ?? 5 * 60_000;\n this.outputByteLimit = opts.outputByteLimit ?? 1024 * 1024;\n this.maxOutputByteLimit = opts.maxOutputByteLimit ?? 16 * 1024 * 1024;\n if (opts.signal) {\n opts.signal.addEventListener('abort', () => this.releaseAll());\n }\n }\n\n /** Spawn a new terminal. Returns the agent-facing id. */\n create(params: {\n sessionId: string;\n command: string;\n args?: string[];\n env?: { name: string; value: string }[];\n cwd?: string;\n outputByteLimit?: number;\n }): { terminalId: string } {\n const id = `term_${this.nextId++}`;\n const cwd = this.resolveCwd(params.cwd);\n const proc = spawn(params.command, params.args ?? [], {\n cwd,\n env: this.buildEnv(params.env),\n stdio: ['ignore', 'pipe', 'pipe'],\n windowsHide: true,\n // shell: false on purpose. The terminal server is invoked with\n // the agent's explicit argv; turning on shell-mode would make\n // the command a single shell-parsed string, which breaks\n // Windows cmd quoting for the common case of running node with\n // `-e \"<script>\"`. If a future feature needs shell features\n // (pipes, redirects), it should be opt-in per-call, not the\n // default.\n });\n\n const state: TerminalState = {\n proc,\n cwd,\n command: params.command,\n args: params.args ?? [],\n output: '',\n retainedBytes: 0,\n truncated: false,\n exitStatus: undefined,\n timeoutHandle: null,\n exitPromise: new Promise((resolve) => {\n proc.on('close', (code, signalName) => {\n if (state.timeoutHandle) {\n clearTimeout(state.timeoutHandle);\n state.timeoutHandle = null;\n }\n const exitStatus = {\n exitCode: typeof code === 'number' ? code : null,\n signal: typeof signalName === 'string' ? signalName : null,\n };\n state.exitStatus = exitStatus;\n resolve(exitStatus);\n });\n proc.on('error', (err) => {\n // Spawn-time errors (ENOENT etc.) \u2014 surface as a special\n // exit status with exitCode 127 (command not found).\n if (state.timeoutHandle) {\n clearTimeout(state.timeoutHandle);\n state.timeoutHandle = null;\n }\n const exitStatus = { exitCode: 127, signal: null };\n state.exitStatus = exitStatus;\n state.output += `[spawn error] ${err.message}\\n`;\n state.retainedBytes = Buffer.byteLength(state.output, 'utf8');\n resolve(exitStatus);\n });\n }),\n };\n\n const perCallByteLimit = Math.min(\n Math.max(1, this.clampFiniteInt(params.outputByteLimit, this.outputByteLimit)),\n this.maxOutputByteLimit,\n );\n proc.stdout?.setEncoding('utf8');\n proc.stderr?.setEncoding('utf8');\n const onData = (chunk: string): void => {\n state.output += chunk;\n state.retainedBytes = Buffer.byteLength(state.output, 'utf8');\n // Truncate from the start if we exceed the limit. Per spec, the\n // truncation MUST happen at a character boundary. UTF-8 slicing\n // a string can land mid-codepoint; we trim back to the last\n // complete code point to honour that.\n while (state.retainedBytes > perCallByteLimit) {\n const trimmed = state.output.slice(1);\n // Cheap boundary check: if dropping the first char doesn't\n // shrink us by at least one byte, we're slicing inside a\n // multi-byte sequence; keep dropping.\n state.output = trimmed;\n const newBytes = Buffer.byteLength(state.output, 'utf8');\n if (newBytes >= state.retainedBytes) {\n // give up \u2014 would loop forever\n break;\n }\n state.retainedBytes = newBytes;\n state.truncated = true;\n }\n };\n proc.stdout?.on('data', onData);\n proc.stderr?.on('data', onData);\n\n state.timeoutHandle = setTimeout(() => {\n // Best-effort kill; we don't have an exact \"TIMEOUT\" stop reason\n // so we just exit with -1.\n try {\n proc.kill('SIGTERM');\n } catch {\n // already dead\n }\n }, this.commandTimeoutMs);\n\n this.terminals.set(id, state);\n return { terminalId: id };\n }\n\n /** Return captured output and (if available) the exit status. */\n output(terminalId: string): { output: string; truncated: boolean; exitStatus?: { exitCode: number | null; signal: string | null } } {\n const state = this.terminals.get(terminalId);\n if (!state) throw new Error(`unknown terminal: ${terminalId}`);\n return {\n output: state.output,\n truncated: state.truncated,\n ...(state.exitStatus ? { exitStatus: state.exitStatus } : {}),\n };\n }\n\n /** Block until the process exits. Resolves with the exit status. */\n async waitForExit(terminalId: string): Promise<{ exitCode: number | null; signal: string | null }> {\n const state = this.terminals.get(terminalId);\n if (!state) throw new Error(`unknown terminal: ${terminalId}`);\n return state.exitPromise;\n }\n\n /** Kill the process but keep the terminal record (agent can still read output). */\n kill(terminalId: string): void {\n const state = this.terminals.get(terminalId);\n if (!state) throw new Error(`unknown terminal: ${terminalId}`);\n try {\n state.proc.kill('SIGTERM');\n } catch {\n // already dead\n }\n }\n\n /** Kill the process if alive and remove the record. */\n release(terminalId: string): void {\n const state = this.terminals.get(terminalId);\n if (!state) return;\n if (state.timeoutHandle) {\n clearTimeout(state.timeoutHandle);\n state.timeoutHandle = null;\n }\n try {\n state.proc.kill('SIGKILL');\n } catch {\n // already dead\n }\n this.terminals.delete(terminalId);\n }\n\n /** Kill all active terminals. Used on session close. */\n releaseAll(): void {\n for (const id of [...this.terminals.keys()]) {\n this.release(id);\n }\n }\n\n private resolveCwd(cwd: string | undefined): string {\n if (!cwd) return this.projectRoot;\n const resolved = path.resolve(cwd);\n const rootWithSep = this.projectRoot.endsWith(path.sep)\n ? this.projectRoot\n : this.projectRoot + path.sep;\n if (resolved !== this.projectRoot && !resolved.startsWith(rootWithSep)) {\n return this.projectRoot;\n }\n try {\n const realRoot = realpathSync(this.projectRoot);\n const realCwd = realpathSync(resolved);\n const realRootWithSep = realRoot.endsWith(path.sep) ? realRoot : realRoot + path.sep;\n if (realCwd !== realRoot && !realCwd.startsWith(realRootWithSep)) {\n return realRoot;\n }\n return realCwd;\n } catch {\n // A process cannot start in a missing/unresolvable cwd. Fall back to the\n // configured root rather than allowing spawn to fail or follow a bad link.\n return this.projectRoot;\n }\n }\n\n private buildEnv(\n agentEnv?: { name: string; value: string }[],\n ): NodeJS.ProcessEnv {\n // Use the sanitized child env from @wrongstack/core instead of raw\n // process.env. This strips API keys, tokens, and other credentials from\n // the host environment so a compromised ACP agent cannot exfiltrate them\n // via `terminal/create`. buildChildEnv preserves system/tooling variables\n // (PATH, HOME, LANG, ...) and handles the Windows Path/PATH aliasing.\n const env: NodeJS.ProcessEnv = buildChildEnv();\n if (agentEnv) {\n for (const { name, value } of agentEnv) {\n // Deny agent overrides of environment variables that could re-introduce\n // code injection (NODE_OPTIONS --require/--import/--loader), shared-library\n // preloading (LD_PRELOAD, DYLD_*), or path hijacking (PATH). buildChildEnv\n // already stripped these from the host env; the agent must not be able to\n // add them back.\n const upper = name.toUpperCase();\n if (DENIED_AGENT_ENV_KEYS.has(upper)) continue;\n env[name] = value;\n }\n }\n return env;\n }\n\n /**\n * Clamp an agent-supplied numeric to a finite positive safe integer, falling\n * back to `defaultValue` for undefined/NaN/non-finite values. Prevents\n * negative, NaN, or Infinity values from disabling output caps or causing\n * unbounded memory growth.\n */\n private clampFiniteInt(\n value: number | undefined,\n defaultValue: number,\n ): number {\n if (value === undefined || !Number.isFinite(value) || value < 1) {\n return defaultValue;\n }\n return Math.trunc(value);\n }\n}\n\n/**\n * Environment variables an ACP agent must NOT be allowed to set, because they\n * can re-introduce code injection or path hijacking after `buildChildEnv`\n * already stripped them from the host env. Checked case-insensitively.\n */\nconst DENIED_AGENT_ENV_KEYS: ReadonlySet<string> = new Set([\n 'NODE_OPTIONS',\n 'LD_PRELOAD',\n 'LD_LIBRARY_PATH',\n 'DYLD_INSERT_LIBRARIES',\n 'DYLD_LIBRARY_PATH',\n 'DYLD_FALLBACK_LIBRARY_PATH',\n 'PATH',\n 'PYTHONPATH',\n 'PYTHONSTARTUP',\n 'PERL5OPT',\n 'PERLLIB',\n 'RUBYOPT',\n 'RUBYLIB',\n]);\n", "/**\n * ACPSession \u2014 v1-correct ACP client.\n *\n * Owns one child process running an ACP-supporting agent (Claude Code,\n * Gemini CLI, Codex CLI, etc.) and translates the wire protocol into\n * a `SubagentRunner`-shaped surface for the rest of WrongStack.\n *\n * Spec: https://agentclientprotocol.com/protocol/v1/overview\n * Design: see ./acp-session.design.md in this directory.\n */\nimport { ClientTransport, type ACPClientTransport } from '../agent/stdio-transport.js';\nimport type { ACPMessage } from '../types/acp-messages.js';\nimport {\n WebSocketClientTransport,\n type WebSocketClientTransportOptions,\n} from './websocket-transport.js';\nimport {\n ACP_PROTOCOL_VERSION,\n type AgentCapabilities,\n type AnySessionUpdate,\n type AuthMethod,\n type ContentBlock,\n type McpServer,\n type PlanEntry,\n type SessionId,\n type SessionInfo,\n type StopReason,\n type ToolCallContent,\n type ToolCallStatus,\n type ToolCallUpdateNotification,\n type ToolKind,\n type UsageCost,\n} from '../types/acp-v1.js';\nimport { FileServer, FsError } from './file-server.js';\nimport {\n defaultPermissionPolicy,\n type PermissionPolicy,\n} from './permission.js';\nimport { TerminalServer } from './terminal-server.js';\n\nexport interface ACPSessionOptions {\n command: string;\n args?: readonly string[] | undefined;\n env?: Record<string, string> | undefined;\n cwd?: string | undefined;\n role?: string | undefined;\n /** Sandbox root for fs/* and terminal/* methods. */\n projectRoot: string;\n /** Hard timeout for one prompt turn. Default 5 minutes. */\n timeoutMs?: number | undefined;\n /** Override the permission policy. */\n permissionPolicy?: PermissionPolicy | undefined;\n /** Per-fs-call timeout, default 30s. */\n fsTimeoutMs?: number | undefined;\n /** Per-terminal command timeout, default 5 minutes. */\n terminalTimeoutMs?: number | undefined;\n /** Per-terminal output byte cap, default 1 MiB. */\n terminalOutputByteLimit?: number | undefined;\n /**\n * MCP server configs to include in session/new, session/load, and\n * session/resume. The agent will connect to these servers to provide\n * additional tools.\n *\n * Stdio servers are always sent. HTTP/SSE servers are only sent if\n * the agent advertises the corresponding mcpCapabilities.\n */\n mcpServers?: McpServer[] | undefined;\n}\n\n/**\n * A captured file diff emitted by the agent during a turn (via a tool\n * call's `diff` content). `oldText: null` means the file was created.\n */\nexport interface ACPCapturedDiff {\n path: string;\n oldText: string | null;\n newText: string;\n}\n\n/**\n * A captured tool call the agent ran during a turn. We collapse the\n * `tool_call` + subsequent `tool_call_update` notifications for the same\n * `toolCallId` into one record carrying its latest status.\n */\nexport interface ACPCapturedToolCall {\n toolCallId: string;\n title: string;\n kind?: ToolKind | undefined;\n status: ToolCallStatus;\n /** Terminal/command output or text content surfaced by the tool, if any. */\n rawOutput?: Record<string, unknown> | undefined;\n rawInput?: Record<string, unknown> | undefined;\n}\n\nexport interface ACPSessionRunResult {\n text: string;\n stopReason: StopReason;\n hasText: boolean;\n usage?: { used: number; size: number; cost?: UsageCost | undefined } | undefined;\n plan?: PlanEntry[] | undefined;\n /** Tool calls the agent ran this turn (deduped by toolCallId). */\n toolCalls: ACPCapturedToolCall[];\n /** File diffs the agent produced this turn. */\n diffs: ACPCapturedDiff[];\n /** Agent \"thinking\" text emitted via thought_chunk, concatenated. */\n thoughts: string;\n}\n\n/**\n * Live progress callback. Invoked for every `session/update` notification\n * the agent streams during a `prompt()` turn, in arrival order, BEFORE the\n * turn resolves. Lets the host render tool activity / text deltas / diffs\n * as they happen instead of waiting for the buffered final result.\n *\n * The raw `update` (the discriminated `session/update` payload) is passed\n * through verbatim so callers can switch on `update.sessionUpdate`.\n */\nexport type ACPProgressHandler = (event: ACPProgressEvent) => void;\n\nexport type ACPProgressEvent =\n | { type: 'message'; text: string }\n | { type: 'thought'; text: string }\n | { type: 'tool_call'; toolCall: ACPCapturedToolCall }\n | { type: 'tool_call_update'; toolCall: ACPCapturedToolCall }\n | { type: 'diff'; diff: ACPCapturedDiff }\n | { type: 'plan'; entries: PlanEntry[] }\n | { type: 'usage'; usage: { used: number; size: number; cost?: UsageCost | undefined } }\n | { type: 'raw'; update: AnySessionUpdate };\n\nexport type ACPSessionErrorKind =\n | 'spawn_failed'\n | 'init_failed'\n | 'protocol_error'\n | 'session_create_failed'\n | 'prompt_failed'\n | 'auth_failed'\n | 'logout_failed'\n | 'aborted'\n | 'closed'\n | 'agent_died'\n | 'unsupported_capability';\n\nexport class ACPSessionError extends Error {\n readonly kind: ACPSessionErrorKind;\n override readonly cause: unknown;\n constructor(kind: ACPSessionErrorKind, message: string, cause?: unknown) {\n super(message);\n this.name = 'ACPSessionError';\n this.kind = kind;\n this.cause = cause;\n }\n}\n\ninterface PendingRequest {\n method: string;\n resolve: (v: unknown) => void;\n reject: (e: Error) => void;\n timeoutMs: number;\n timeoutHandle: ReturnType<typeof setTimeout>;\n}\n\ntype State = 'init' | 'ready' | 'authenticated' | 'sessioning' | 'prompting' | 'done' | 'closed';\n\ninterface JsonRpcError {\n code: number;\n message: string;\n data?: unknown;\n}\n\nfunction isJsonRpcError(v: unknown): v is JsonRpcError {\n return (\n typeof v === 'object' &&\n v !== null &&\n typeof (v as { code?: unknown }).code === 'number' &&\n typeof (v as { message?: unknown }).message === 'string'\n );\n}\n\nexport class ACPSession {\n private readonly transport: ACPClientTransport;\n private readonly fileServer: FileServer;\n private readonly terminalServer: TerminalServer;\n private readonly permissionPolicy: PermissionPolicy;\n private readonly timeoutMs: number;\n private readonly opts: ACPSessionOptions;\n\n private state: State = 'init';\n private sessionId: SessionId | null = null;\n /** Pending outbound requests (initialize, session/new, session/prompt, etc). */\n private readonly pending = new Map<string | number, PendingRequest>();\n private nextId = 1;\n /** True after close() has been called. */\n private closed = false;\n\n // Agent-provided info from the initialize handshake\n private agentCapabilities: AgentCapabilities = {};\n private agentInfo: { name: string; title?: string | undefined; version: string } | null = null;\n private authMethods: AuthMethod[] = [];\n /** Protocol version negotiated with the agent during initialize. */\n private negotiatedVersion: number = ACP_PROTOCOL_VERSION;\n\n private constructor(opts: ACPSessionOptions, transport: ACPClientTransport) {\n this.opts = opts;\n this.transport = transport;\n this.timeoutMs = opts.timeoutMs ?? 5 * 60_000;\n const fsOpts: ConstructorParameters<typeof FileServer>[0] = {\n projectRoot: opts.projectRoot,\n };\n if (opts.fsTimeoutMs !== undefined) fsOpts.timeoutMs = opts.fsTimeoutMs;\n this.fileServer = new FileServer(fsOpts);\n const termOpts: ConstructorParameters<typeof TerminalServer>[0] = {\n projectRoot: opts.projectRoot,\n };\n if (opts.terminalTimeoutMs !== undefined) {\n termOpts.commandTimeoutMs = opts.terminalTimeoutMs;\n }\n if (opts.terminalOutputByteLimit !== undefined) {\n termOpts.outputByteLimit = opts.terminalOutputByteLimit;\n }\n this.terminalServer = new TerminalServer(termOpts);\n this.permissionPolicy = opts.permissionPolicy ?? defaultPermissionPolicy;\n }\n\n // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Public accessors\n // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Agent capabilities advertised during initialize. */\n getCapabilities(): AgentCapabilities {\n return { ...this.agentCapabilities };\n }\n\n /** Authentication methods advertised by the agent. */\n getAuthMethods(): AuthMethod[] {\n return [...this.authMethods];\n }\n\n /** Agent info (name, title, version) from initialize. */\n getAgentInfo(): { name: string; title?: string | undefined; version: string } | null {\n return this.agentInfo;\n }\n\n /** Whether the agent requires authentication (has auth methods). */\n requiresAuth(): boolean {\n return this.authMethods.length > 0;\n }\n\n /** Current session id, if one exists. */\n getSessionId(): SessionId | null {\n return this.sessionId;\n }\n\n /** Protocol version negotiated during initialize. */\n getNegotiatedVersion(): number {\n return this.negotiatedVersion;\n }\n\n // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Lifecycle \u2014 start\n // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Spawn the child, run the initialize handshake, install the\n * message dispatch, and return a ready session.\n */\n static async start(opts: ACPSessionOptions): Promise<ACPSession> {\n const transportOpts: ConstructorParameters<typeof ClientTransport>[0] = {\n command: opts.command,\n args: opts.args ? [...opts.args] : [],\n handshakeTimeoutMs: 30_000,\n skipHandshakeMarker: true,\n };\n if (opts.env !== undefined) transportOpts.env = opts.env;\n if (opts.cwd !== undefined) transportOpts.cwd = opts.cwd;\n const transport = new ClientTransport(transportOpts);\n return ACPSession.attach(opts, transport, `failed to spawn ${opts.command}`);\n }\n\n /**\n * Connect to a REMOTE ACP agent over a WebSocket instead of spawning a\n * local subprocess. `opts.command` is ignored for the wire (a label is\n * still useful for `role`); everything else (projectRoot sandbox for\n * fs/terminal, timeouts, permission policy, MCP servers) applies the same.\n */\n static async connectWebSocket(\n wsOpts: WebSocketClientTransportOptions,\n opts: ACPSessionOptions,\n ): Promise<ACPSession> {\n const transport = new WebSocketClientTransport(wsOpts);\n return ACPSession.attach(opts, transport, `failed to connect to ${wsOpts.url}`);\n }\n\n /**\n * Connect using a caller-supplied transport. Lets advanced callers plug\n * in their own wire (SDK streams, in-process pipes, test doubles).\n */\n static async connect(\n transport: ACPClientTransport,\n opts: ACPSessionOptions,\n ): Promise<ACPSession> {\n return ACPSession.attach(opts, transport, 'failed to connect transport');\n }\n\n /** Shared connect path: start the transport, install dispatch, handshake. */\n private static async attach(\n opts: ACPSessionOptions,\n transport: ACPClientTransport,\n spawnErrLabel: string,\n ): Promise<ACPSession> {\n try {\n await transport.start();\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n throw new ACPSessionError('spawn_failed', `${spawnErrLabel}: ${msg}`, err);\n }\n\n const session = new ACPSession(opts, transport);\n transport.onMessage((msg) => session.handleMessage(msg));\n\n try {\n await session.initialize();\n } catch (err) {\n try {\n transport.stop();\n } catch {\n // best effort\n }\n throw err;\n }\n return session;\n }\n\n // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Initialization\n // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private async initialize(): Promise<void> {\n const id = this.allocId();\n const result = await this.sendRequest(id, 'initialize', {\n protocolVersion: ACP_PROTOCOL_VERSION,\n clientCapabilities: {\n fs: { readTextFile: true, writeTextFile: true },\n terminal: true,\n },\n clientInfo: { name: 'wrongstack', title: 'WrongStack', version: '0.287.0' },\n });\n if (isJsonRpcError(result)) {\n throw new ACPSessionError('init_failed', `initialize failed: ${result.message}`, result);\n }\n if (\n typeof result !== 'object' ||\n result === null ||\n typeof (result as { protocolVersion?: unknown }).protocolVersion !== 'number'\n ) {\n throw new ACPSessionError('protocol_error', 'initialize returned no protocolVersion');\n }\n const r = result as {\n protocolVersion: number;\n agentCapabilities?: AgentCapabilities;\n agentInfo?: { name: string; title?: string | undefined; version: string };\n authMethods?: AuthMethod[];\n };\n // Negotiation per spec: the client advertises its latest supported\n // version; the agent replies with the version both will use \u2014 the\n // client's if the agent supports it, otherwise the agent's own latest.\n // We therefore accept any version <= ours (we can speak it) and only\n // reject a version HIGHER than we support (the agent demands a protocol\n // we don't implement). Equal is the common path.\n if (r.protocolVersion > ACP_PROTOCOL_VERSION) {\n throw new ACPSessionError(\n 'unsupported_capability',\n `agent requires protocolVersion=${r.protocolVersion}, client supports up to ${ACP_PROTOCOL_VERSION}`,\n );\n }\n this.negotiatedVersion = r.protocolVersion;\n // Store agent metadata\n this.agentCapabilities = r.agentCapabilities ?? {};\n this.agentInfo = r.agentInfo ?? null;\n this.authMethods = r.authMethods ?? [];\n this.state = 'ready';\n }\n\n // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Authentication\n // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Authenticate with the agent using one of the advertised auth methods.\n * Call this AFTER start() and BEFORE any session/new call.\n *\n * Throws ACPSessionError('auth_failed') if the agent rejects the\n * authentication or if the methodId is not in the advertised list.\n */\n async authenticate(methodId: string): Promise<void> {\n if (this.state === 'closed') {\n throw new ACPSessionError('closed', 'session is closed');\n }\n if (this.state !== 'ready') {\n throw new ACPSessionError(\n 'protocol_error',\n `authenticate called in state=${this.state} (expected 'ready')`,\n );\n }\n if (!this.authMethods.some((m) => m.id === methodId)) {\n throw new ACPSessionError(\n 'auth_failed',\n `auth method \"${methodId}\" not in advertised methods: ${this.authMethods.map((m) => m.id).join(', ')}`,\n );\n }\n\n const id = this.allocId();\n const result = await this.sendRequest(id, 'authenticate', { methodId });\n if (isJsonRpcError(result)) {\n throw new ACPSessionError('auth_failed', `authenticate failed: ${result.message}`, result);\n }\n this.state = 'authenticated';\n }\n\n /**\n * Log out from the current authenticated session.\n * Only callable if the agent advertises `auth.logout` capability.\n */\n async logout(): Promise<void> {\n if (this.state === 'closed') {\n throw new ACPSessionError('closed', 'session is closed');\n }\n if (!this.agentCapabilities.auth?.logout) {\n throw new ACPSessionError(\n 'unsupported_capability',\n 'agent does not support logout (auth.logout capability not advertised)',\n );\n }\n\n const id = this.allocId();\n const result = await this.sendRequest(id, 'logout', {});\n if (isJsonRpcError(result)) {\n throw new ACPSessionError('logout_failed', `logout failed: ${result.message}`, result);\n }\n this.state = 'ready';\n }\n\n // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Session management\n // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Load an existing session. The agent replays the conversation history\n * via session/update notifications before responding.\n *\n * Only works if the agent advertises `loadSession` capability.\n *\n * @param sessionId - The session to load\n * @param mcpServers - Optional MCP servers (defaults to options.mcpServers)\n * @param cwd - Optional working directory (defaults to options.cwd or projectRoot)\n */\n async loadSession(\n sessionId: SessionId,\n mcpServers?: McpServer[],\n cwd?: string,\n ): Promise<void> {\n if (this.closed) {\n throw new ACPSessionError('closed', 'session is closed');\n }\n if (!this.agentCapabilities.loadSession) {\n throw new ACPSessionError(\n 'unsupported_capability',\n 'agent does not support session/load (loadSession capability not advertised)',\n );\n }\n if (this.sessionId) {\n // Close current session first\n await this.closeSession();\n }\n\n this.resetScratch();\n const servers = this.filterMcpServers(mcpServers ?? this.opts.mcpServers);\n const id = this.allocId();\n const result = await this.sendRequest(id, 'session/load', {\n sessionId,\n cwd: cwd ?? this.opts.cwd ?? this.opts.projectRoot,\n mcpServers: servers,\n });\n if (isJsonRpcError(result)) {\n throw new ACPSessionError('prompt_failed', `session/load failed: ${result.message}`, result);\n }\n this.sessionId = sessionId;\n }\n\n /**\n * Resume an existing session without replaying history.\n *\n * Only works if the agent advertises `sessionCapabilities.resume`.\n *\n * @param sessionId - The session to resume\n * @param mcpServers - Optional MCP servers (defaults to options.mcpServers)\n * @param cwd - Optional working directory (defaults to options.cwd or projectRoot)\n */\n async resumeSession(\n sessionId: SessionId,\n mcpServers?: McpServer[],\n cwd?: string,\n ): Promise<void> {\n if (this.closed) {\n throw new ACPSessionError('closed', 'session is closed');\n }\n if (!this.agentCapabilities.sessionCapabilities?.resume) {\n throw new ACPSessionError(\n 'unsupported_capability',\n 'agent does not support session/resume (sessionCapabilities.resume not advertised)',\n );\n }\n if (this.sessionId) {\n await this.closeSession();\n }\n\n const servers = this.filterMcpServers(mcpServers ?? this.opts.mcpServers);\n const id = this.allocId();\n const result = await this.sendRequest(id, 'session/resume', {\n sessionId,\n cwd: cwd ?? this.opts.cwd ?? this.opts.projectRoot,\n mcpServers: servers,\n });\n if (isJsonRpcError(result)) {\n throw new ACPSessionError('prompt_failed', `session/resume failed: ${result.message}`, result);\n }\n this.sessionId = sessionId;\n }\n\n /**\n * List existing sessions known to the agent.\n *\n * Only works if the agent advertises `sessionCapabilities.list`.\n */\n async listSessions(cursor?: string, cwd?: string): Promise<{ sessions: SessionInfo[]; nextCursor?: string | undefined }> {\n if (this.closed) {\n throw new ACPSessionError('closed', 'session is closed');\n }\n if (!this.agentCapabilities.sessionCapabilities?.list) {\n throw new ACPSessionError(\n 'unsupported_capability',\n 'agent does not support session/list (sessionCapabilities.list not advertised)',\n );\n }\n\n const id = this.allocId();\n const params: Record<string, unknown> = {};\n if (cursor !== undefined) params.cursor = cursor;\n if (cwd !== undefined) params.cwd = cwd;\n const result = await this.sendRequest(id, 'session/list', params);\n if (isJsonRpcError(result)) {\n throw new ACPSessionError('prompt_failed', `session/list failed: ${result.message}`, result);\n }\n const r = result as { sessions?: SessionInfo[]; nextCursor?: string };\n return {\n sessions: r.sessions ?? [],\n nextCursor: r.nextCursor,\n };\n }\n\n /**\n * Delete a session from the agent's session list.\n *\n * Only works if the agent advertises `sessionCapabilities.delete`.\n */\n async deleteSession(sessionId: SessionId): Promise<void> {\n if (this.closed) {\n throw new ACPSessionError('closed', 'session is closed');\n }\n if (!this.agentCapabilities.sessionCapabilities?.delete) {\n throw new ACPSessionError(\n 'unsupported_capability',\n 'agent does not support session/delete (sessionCapabilities.delete not advertised)',\n );\n }\n\n const id = this.allocId();\n const result = await this.sendRequest(id, 'session/delete', { sessionId });\n if (isJsonRpcError(result)) {\n throw new ACPSessionError('prompt_failed', `session/delete failed: ${result.message}`, result);\n }\n\n if (this.sessionId === sessionId) {\n this.sessionId = null;\n }\n }\n\n /**\n * Fork a session \u2014 create a new session from an existing one.\n */\n async forkSession(\n sourceSessionId: SessionId,\n cwd?: string,\n mcpServers?: McpServer[],\n ): Promise<SessionId> {\n if (this.closed) throw new ACPSessionError('closed', 'session is closed');\n\n const servers = this.filterMcpServers(mcpServers ?? this.opts.mcpServers);\n const id = this.allocId();\n const result = await this.sendRequest(id, 'session/fork', {\n sessionId: sourceSessionId,\n cwd: cwd ?? this.opts.cwd ?? this.opts.projectRoot,\n ...(servers.length > 0 ? { mcpServers: servers } : {}),\n });\n if (isJsonRpcError(result)) {\n throw new ACPSessionError('prompt_failed', `session/fork failed: ${result.message}`, result);\n }\n const newId = (result as { sessionId?: unknown }).sessionId;\n if (typeof newId !== 'string' || !newId) {\n throw new ACPSessionError('protocol_error', 'session/fork returned no sessionId', result);\n }\n return newId as SessionId;\n }\n\n /**\n * Set the active mode for a session.\n */\n async setMode(sessionId: SessionId, modeId: string): Promise<void> {\n if (this.closed) throw new ACPSessionError('closed', 'session is closed');\n const id = this.allocId();\n const result = await this.sendRequest(id, 'session/set_mode', { sessionId, modeId });\n if (isJsonRpcError(result)) {\n throw new ACPSessionError('prompt_failed', `session/set_mode failed: ${result.message}`, result);\n }\n }\n\n /**\n * Set a configuration option for a session.\n */\n async setConfigOption(sessionId: SessionId, configId: string, value: string): Promise<void> {\n if (this.closed) throw new ACPSessionError('closed', 'session is closed');\n const id = this.allocId();\n const result = await this.sendRequest(id, 'session/set_config_option', {\n sessionId, configId, value,\n });\n if (isJsonRpcError(result)) {\n throw new ACPSessionError('prompt_failed', `session/set_config_option failed: ${result.message}`, result);\n }\n }\n\n /**\n * List available providers and the current provider.\n */\n async listProviders(): Promise<{ providers: unknown[]; currentProviderId: string | null }> {\n if (this.closed) throw new ACPSessionError('closed', 'session is closed');\n const id = this.allocId();\n const result = await this.sendRequest(id, 'providers/list', {});\n if (isJsonRpcError(result)) {\n throw new ACPSessionError('prompt_failed', `providers/list failed: ${result.message}`, result);\n }\n const r = result as { providers?: unknown[]; currentProviderId?: string | null };\n return { providers: r.providers ?? [], currentProviderId: r.currentProviderId ?? null };\n }\n\n /**\n * Send an MCP message to the agent for routing.\n */\n async mcpMessage(connectionId: string, message: Record<string, unknown>): Promise<unknown> {\n if (this.closed) throw new ACPSessionError('closed', 'session is closed');\n const id = this.allocId();\n const result = await this.sendRequest(id, 'mcp/message', { connectionId, message });\n if (isJsonRpcError(result)) {\n throw new ACPSessionError('prompt_failed', `mcp/message failed: ${result.message}`, result);\n }\n return result;\n }\n\n /**\n * Set the active provider for the agent.\n */\n async setProvider(providerId: string, config?: Record<string, unknown>): Promise<void> {\n if (this.closed) throw new ACPSessionError('closed', 'session is closed');\n const id = this.allocId();\n const result = await this.sendRequest(id, 'providers/set', { providerId, ...(config ?? {}) });\n if (isJsonRpcError(result)) {\n throw new ACPSessionError('prompt_failed', `providers/set failed: ${result.message}`, result);\n }\n }\n\n /**\n * Disable the current provider.\n */\n async disableProvider(): Promise<void> {\n if (this.closed) throw new ACPSessionError('closed', 'session is closed');\n const id = this.allocId();\n const result = await this.sendRequest(id, 'providers/disable', {});\n if (isJsonRpcError(result)) {\n throw new ACPSessionError('prompt_failed', `providers/disable failed: ${result.message}`, result);\n }\n }\n\n // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Prompt\n // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Run one prompt turn. Creates a session if needed, sends the\n * prompt, streams session/update notifications, and resolves with\n * the agent's response.\n *\n * @param blocks - Content blocks to send. Use `textContent()` for plain\n * text, or include ImageContent/AudioContent if the agent's\n * `promptCapabilities` allow it.\n * @param signal - AbortSignal for cancellation.\n *\n * Cancellation: if `signal` aborts mid-prompt, we send\n * `session/cancel` (a notification per spec) and keep accepting\n * updates until the agent returns with `stopReason: 'cancelled'`.\n * The result is the same shape as a normal turn, with\n * `stopReason === 'cancelled'`.\n */\n async prompt(\n blocks: ContentBlock[],\n signal: AbortSignal,\n onProgress?: ACPProgressHandler,\n ): Promise<ACPSessionRunResult> {\n if (this.closed) {\n throw new ACPSessionError('closed', 'session is closed');\n }\n if (this.state !== 'ready' && this.state !== 'authenticated' && this.state !== 'done') {\n throw new ACPSessionError('protocol_error', `prompt called in state=${this.state}`);\n }\n\n // Pre-aborted signals short-circuit BEFORE we create a session\n // and before any wire activity.\n if (signal.aborted) {\n return emptyRunResult('cancelled');\n }\n\n if (!this.sessionId) {\n await this.createSession();\n }\n\n this.resetScratch();\n this.progressHandler = onProgress ?? null;\n\n const promptId = this.allocId();\n const turnPromise = this.sendRequest(\n promptId,\n 'session/prompt',\n {\n sessionId: this.sessionId,\n prompt: blocks,\n },\n this.timeoutMs,\n );\n\n let cancelled = false;\n const onAbort = (): void => {\n cancelled = true;\n this.transport\n .send({\n jsonrpc: '2.0',\n method: 'session/cancel',\n params: { sessionId: this.sessionId },\n } as never as ACPMessage)\n .catch(() => {\n // transport may already be torn down \u2014 ignore\n });\n };\n signal.addEventListener('abort', onAbort, { once: true });\n\n this.state = 'prompting';\n let response: unknown;\n try {\n response = await turnPromise;\n } catch (err) {\n this.state = 'done';\n signal.removeEventListener('abort', onAbort);\n if (cancelled || signal.aborted) {\n throw new ACPSessionError('aborted', 'prompt was aborted by the parent');\n }\n const msg = err instanceof Error ? err.message : String(err);\n throw new ACPSessionError('prompt_failed', `session/prompt failed: ${msg}`, err);\n } finally {\n signal.removeEventListener('abort', onAbort);\n this.progressHandler = null;\n }\n\n this.state = 'done';\n if (isJsonRpcError(response)) {\n throw new ACPSessionError('prompt_failed', `agent error: ${response.message}`, response);\n }\n const stopReason = (response as { stopReason?: StopReason }).stopReason ?? 'end_turn';\n const finalText = this.scratch.text;\n return {\n text: finalText,\n stopReason,\n hasText: finalText.length > 0,\n usage: this.scratch.usage,\n plan: this.scratch.plan,\n toolCalls: [...this.scratch.toolCalls.values()],\n diffs: this.scratch.diffs,\n thoughts: this.scratch.thoughts,\n };\n }\n\n private async createSession(): Promise<void> {\n const servers = this.filterMcpServers(this.opts.mcpServers);\n const id = this.allocId();\n const result = await this.sendRequest(id, 'session/new', {\n cwd: this.opts.cwd ?? this.opts.projectRoot,\n mcpServers: servers,\n });\n if (isJsonRpcError(result)) {\n throw new ACPSessionError(\n 'session_create_failed',\n `session/new failed: ${result.message}`,\n result,\n );\n }\n const sessionId = (result as { sessionId?: unknown }).sessionId;\n if (typeof sessionId !== 'string' || sessionId.length === 0) {\n throw new ACPSessionError(\n 'protocol_error',\n 'session/new returned no sessionId',\n result,\n );\n }\n this.sessionId = sessionId as SessionId;\n }\n\n /**\n * Close the current session gracefully (if the agent supports it).\n *\n * Sends `session/close` JSON-RPC request, then clears the local\n * session id. Best-effort \u2014 errors are swallowed so the caller can\n * always proceed to transport teardown.\n */\n private async closeSession(): Promise<void> {\n if (!this.sessionId) return;\n const sid = this.sessionId;\n this.sessionId = null;\n\n if (this.agentCapabilities.sessionCapabilities?.close) {\n const id = this.allocId();\n try {\n await this.sendRequest(id, 'session/close', { sessionId: sid }, 10_000);\n } catch {\n // Best-effort: if close fails, we still proceed with transport stop.\n }\n }\n }\n\n // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Lifecycle \u2014 close\n // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Tear down the session and kill the child process. */\n async close(): Promise<void> {\n if (this.closed) return;\n this.closed = true;\n this.state = 'closed';\n this.terminalServer.releaseAll();\n\n // Graceful session close (if session is active and agent supports it)\n if (this.sessionId && this.agentCapabilities.sessionCapabilities?.close) {\n try {\n await this.closeSession();\n } catch {\n // best-effort\n }\n }\n\n // Reject any pending outbound requests so their awaits return.\n for (const [, p] of this.pending) {\n clearTimeout(p.timeoutHandle);\n p.reject(new ACPSessionError('closed', 'session was closed'));\n }\n this.pending.clear();\n try {\n this.transport.stop();\n } catch {\n // best effort\n }\n }\n\n // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Helpers\n // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Filter MCP servers according to agent capabilities.\n * - Stdio servers are always included.\n * - HTTP servers are only included if agent supports mcpCapabilities.http.\n * - SSE servers are only included if agent supports mcpCapabilities.sse.\n */\n private filterMcpServers(servers?: McpServer[]): McpServer[] {\n if (!servers || servers.length === 0) return [];\n const mcpCaps = this.agentCapabilities.mcpCapabilities ?? {};\n return servers.filter((s) => {\n if ('type' in s && s.type === 'http') return mcpCaps.http === true;\n if ('type' in s && s.type === 'sse') return mcpCaps.sse === true;\n return true; // stdio \u2014 always supported per spec\n });\n }\n\n // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Wire layer\n // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private allocId(): number {\n return this.nextId++;\n }\n\n private async sendRequest(\n id: number,\n method: string,\n params: unknown,\n timeoutMs?: number,\n ): Promise<unknown> {\n return new Promise<unknown>((resolve, reject) => {\n const effectiveTimeout = timeoutMs ?? this.timeoutMs;\n const handle = setTimeout(() => {\n this.pending.delete(id);\n reject(\n new ACPSessionError(\n 'protocol_error',\n `${method} timed out after ${effectiveTimeout}ms`,\n ),\n );\n }, effectiveTimeout);\n this.pending.set(id, {\n method,\n resolve: resolve as (v: unknown) => void,\n reject,\n timeoutMs: effectiveTimeout,\n timeoutHandle: handle,\n });\n this.transport\n .send({ jsonrpc: '2.0', id, method, params } as never as ACPMessage)\n .catch((err) => {\n clearTimeout(handle);\n this.pending.delete(id);\n const msg = err instanceof Error ? err.message : String(err);\n reject(new ACPSessionError('protocol_error', `send ${method} failed: ${msg}`, err));\n });\n });\n }\n\n /**\n * Send a JSON-RPC 2.0 success response to an agent-initiated request.\n *\n * Per JSON-RPC 2.0 (and the official ACP SDK's message router) a Response\n * object MUST carry `jsonrpc: \"2.0\"` and MUST NOT carry a `method` field \u2014\n * the SDK classifies any object with a `method` key as a Request and drops\n * it as a response, so an agent's `fs/*`, `terminal/*`, or\n * `session/request_permission` callback would hang forever. The legacy\n * `ACPMessage` type predates v1 (requires `method`, lacks `jsonrpc`), so we\n * build the correct wire object and cast at the boundary.\n */\n private sendResult(id: string | number, result: unknown): Promise<void> {\n return this.transport.send({ jsonrpc: '2.0', id, result } as never as ACPMessage);\n }\n\n /** Send a JSON-RPC 2.0 error response (no `method` field, per spec). */\n private sendErrorResponse(\n id: string | number,\n code: number,\n message: string,\n ): Promise<void> {\n return this.transport.send({\n jsonrpc: '2.0',\n id,\n error: { code, message },\n } as never as ACPMessage);\n }\n\n private handleMessage(msg: ACPMessage): void {\n // Response to an outbound request (has id and either result or error)\n if (msg.id !== undefined && (msg.result !== undefined || msg.error !== undefined)) {\n const pending = this.pending.get(msg.id);\n if (!pending) return;\n clearTimeout(pending.timeoutHandle);\n this.pending.delete(msg.id);\n if (msg.error !== undefined) {\n pending.reject(new Error(msg.error.message ?? 'unknown JSON-RPC error'));\n } else {\n pending.resolve(msg.result);\n }\n return;\n }\n\n // session/update notification (no id)\n if (msg.method === 'session/update') {\n this.handleUpdate(msg);\n return;\n }\n\n // session/request_permission (has id, expected response: outcome)\n if (msg.method === 'session/request_permission') {\n void this.handlePermissionRequest(msg);\n return;\n }\n\n // fs/* requests\n if (msg.method === 'fs/read_text_file' || msg.method === 'fs/write_text_file') {\n void this.handleFsRequest(msg);\n return;\n }\n\n // terminal/* requests\n if (msg.method?.startsWith('terminal/')) {\n void this.handleTerminalRequest(msg);\n return;\n }\n\n // mcp/* requests from the agent\n if (msg.method === 'mcp/connect' || msg.method === 'mcp/message' || msg.method === 'mcp/disconnect') {\n // MCP channel management \u2014 best-effort acknowledge.\n if (msg.id !== undefined) {\n this.sendResult(msg.id, {}).catch(() => {});\n }\n return;\n }\n\n // elicitation/* requests from the agent\n if (msg.method === 'elicitation/create' || msg.method === 'elicitation/complete') {\n // Elicitation is a UI feedback mechanism \u2014 acknowledge and ignore.\n if (msg.id !== undefined) {\n this.sendResult(msg.id, {}).catch(() => {});\n }\n return;\n }\n\n // $/cancel_request protocol notification \u2014 no response expected.\n if (msg.method === '$/cancel_request') {\n return;\n }\n\n // Anything else: log to stderr and ignore. Don't crash.\n if (msg.method) {\n // eslint-disable-next-line no-console\n console.warn(\n JSON.stringify({\n level: 'warn',\n event: 'acp_session.unhandled_method',\n method: msg.method,\n timestamp: new Date().toISOString(),\n }),\n );\n }\n }\n\n private handleUpdate(msg: ACPMessage): void {\n const update = (msg as { params?: { update?: unknown } }).params?.update;\n if (typeof update !== 'object' || update === null) return;\n const u = update as { sessionUpdate?: string; [k: string]: unknown };\n // Always surface the raw update so callers that want full fidelity\n // (forwarding to an event bus, etc.) never lose a notification.\n this.emitProgress({ type: 'raw', update: u as AnySessionUpdate });\n switch (u.sessionUpdate) {\n case 'agent_message_chunk': {\n const text = extractText(u.content);\n if (text) {\n this.scratch.text += text;\n this.emitProgress({ type: 'message', text });\n }\n return;\n }\n case 'thought_chunk': {\n const text = extractText(u.content);\n if (text) {\n this.scratch.thoughts += text;\n this.emitProgress({ type: 'thought', text });\n }\n return;\n }\n case 'tool_call':\n case 'tool_call_update': {\n this.captureToolCall(u, u.sessionUpdate === 'tool_call');\n return;\n }\n case 'plan':\n if (Array.isArray(u.entries)) {\n this.scratch.plan = u.entries as PlanEntry[];\n this.emitProgress({ type: 'plan', entries: u.entries as PlanEntry[] });\n }\n return;\n case 'usage_update':\n if (typeof u.used === 'number' && typeof u.size === 'number') {\n const usage = {\n used: u.used,\n size: u.size,\n ...(typeof u.cost === 'object' && u.cost !== null\n ? { cost: u.cost as UsageCost }\n : {}),\n };\n this.scratch.usage = usage;\n this.emitProgress({ type: 'usage', usage });\n }\n return;\n case 'available_commands_update':\n case 'current_mode_update':\n case 'config_option_update':\n case 'session_info_update':\n case 'user_message_chunk':\n case 'next_edit_suggestions':\n case 'elicitation':\n return;\n default:\n return;\n }\n }\n\n /**\n * Fold a `tool_call` / `tool_call_update` notification into the scratch\n * tool-call map (deduped by toolCallId), extract any `diff` content into\n * the diffs list, and emit live progress.\n */\n private captureToolCall(\n u: { [k: string]: unknown },\n isNew: boolean,\n ): void {\n const toolCallId = typeof u.toolCallId === 'string' ? u.toolCallId : '';\n if (!toolCallId) return;\n const prev = this.scratch.toolCalls.get(toolCallId);\n const record: ACPCapturedToolCall = {\n toolCallId,\n title:\n typeof u.title === 'string'\n ? u.title\n : (prev?.title ?? toolCallId),\n kind: (typeof u.kind === 'string' ? (u.kind as ToolKind) : prev?.kind),\n status:\n typeof u.status === 'string'\n ? (u.status as ToolCallStatus)\n : (prev?.status ?? (isNew ? 'pending' : 'in_progress')),\n rawInput:\n isRecord(u.rawInput) ? u.rawInput : prev?.rawInput,\n rawOutput:\n isRecord(u.rawOutput) ? u.rawOutput : prev?.rawOutput,\n };\n this.scratch.toolCalls.set(toolCallId, record);\n\n // Pull any diff content out of the tool call so the host can show\n // what changed. The agent sends diffs as ToolCallContent of type 'diff'.\n if (Array.isArray(u.content)) {\n for (const c of u.content as ToolCallContent[]) {\n if (c && typeof c === 'object' && c.type === 'diff') {\n const diff: ACPCapturedDiff = {\n path: c.path,\n oldText: c.oldText,\n newText: c.newText,\n };\n this.scratch.diffs.push(diff);\n this.emitProgress({ type: 'diff', diff });\n }\n }\n }\n\n this.emitProgress({\n type: isNew ? 'tool_call' : 'tool_call_update',\n toolCall: record,\n });\n }\n\n private emitProgress(event: ACPProgressEvent): void {\n if (!this.progressHandler) return;\n try {\n this.progressHandler(event);\n } catch {\n // A faulty host handler must never break the wire pump.\n }\n }\n\n /** Live progress handler installed for the duration of a `prompt()` turn. */\n private progressHandler: ACPProgressHandler | null = null;\n\n // Per-prompt scratch state\n private scratch: {\n text: string;\n thoughts: string;\n plan?: PlanEntry[];\n usage?: { used: number; size: number; cost?: UsageCost | undefined };\n toolCalls: Map<string, ACPCapturedToolCall>;\n diffs: ACPCapturedDiff[];\n } = { text: '', thoughts: '', toolCalls: new Map(), diffs: [] };\n\n private resetScratch(): void {\n this.scratch = { text: '', thoughts: '', toolCalls: new Map(), diffs: [] };\n }\n\n private async handlePermissionRequest(msg: ACPMessage): Promise<void> {\n const id = msg.id;\n if (id === undefined) return;\n const params = (msg as { params?: { toolCall?: unknown; options?: unknown } }).params;\n const toolCall = params?.toolCall as ToolCallUpdateNotification | undefined;\n const options = Array.isArray(params?.options)\n ? (params.options as never as Parameters<PermissionPolicy>[0]['options'])\n : [];\n if (!toolCall) {\n await this.sendErrorResponse(id, -32602, 'toolCall is required');\n return;\n }\n const policyAbort = new AbortController();\n try {\n const outcome = await this.permissionPolicy({\n toolCall,\n options,\n signal: policyAbort.signal,\n });\n await this.sendResult(id, { outcome });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n await this.sendErrorResponse(id, -32603, `permission policy failed: ${message}`);\n }\n }\n\n /**\n * Enforce authorization at privileged callback sinks (fs/write,\n * terminal/create). Unlike `handlePermissionRequest` which responds to\n * agent-initiated `session/request_permission` messages, this method is\n * called by the handler BEFORE dispatching to FileServer/TerminalServer,\n * closing the gap where the agent simply skips the voluntary permission\n * request and sends the privileged callback directly.\n *\n * Uses the session's permission policy. The default policy\n * (`defaultPermissionPolicy`) auto-approves everything \u2014 this is correct\n * for trusted local agents (CLI `acp spawn`, Director fan-out). For\n * untrusted/remote agents, the host should inject\n * `readOnlyPermissionPolicy` or an interactive policy.\n *\n * Returns true if the callback is authorized, false if denied.\n */\n private async authorizeCallback(partial: {\n toolCallId: string;\n title: string;\n kind: import('../types/acp-v1.js').ToolKind;\n }): Promise<boolean> {\n try {\n const outcome = await this.permissionPolicy({\n toolCall: {\n sessionUpdate: 'tool_call_update',\n toolCallId: partial.toolCallId as import('../types/acp-v1.js').ToolCallId,\n title: partial.title,\n kind: partial.kind,\n status: 'pending',\n },\n options: [\n { optionId: 'allow', name: 'Allow', kind: 'allow_once' },\n { optionId: 'reject', name: 'Reject', kind: 'reject_once' },\n ],\n signal: new AbortController().signal,\n });\n return outcome.outcome === 'selected' &&\n outcome.optionId !== 'reject' &&\n outcome.optionId !== 'reject_once' &&\n outcome.optionId !== 'reject_always';\n } catch {\n // If the policy throws, deny rather than crash.\n return false;\n }\n }\n\n private async handleFsRequest(msg: ACPMessage): Promise<void> {\n const id = msg.id;\n if (id === undefined) return;\n const params = (msg as { params?: { sessionId?: string; path?: string; content?: string } }).params;\n if (!params?.path) {\n await this.sendErrorResponse(id, -32602, 'path is required');\n return;\n }\n // Authorization gate: the ACP spec makes session/request_permission\n // voluntary \u2014 the agent is NOT required to ask before sending fs/*.\n // Enforce authorization at the sink: synthesize a permission request\n // for write operations (reads are auto-approved), and reject if the\n // policy denies.\n if (msg.method === 'fs/write_text_file') {\n const allowed = await this.authorizeCallback({\n toolCallId: `acp-fs-write-${id}`,\n title: `Write file: ${params.path}`,\n kind: 'edit',\n });\n if (!allowed) {\n await this.sendErrorResponse(id, -32602, 'filesystem write denied by permission policy');\n return;\n }\n }\n try {\n if (msg.method === 'fs/read_text_file') {\n const result = await this.fileServer.readTextFile({\n sessionId: params.sessionId ?? '',\n path: params.path,\n });\n await this.sendResult(id, result);\n } else {\n await this.fileServer.writeTextFile({\n sessionId: params.sessionId ?? '',\n path: params.path,\n content: params.content ?? '',\n });\n await this.sendResult(id, {});\n }\n } catch (err) {\n const code = err instanceof FsError ? -32602 : -32603;\n const message = err instanceof Error ? err.message : String(err);\n await this.sendErrorResponse(id, code, message);\n }\n }\n\n private async handleTerminalRequest(msg: ACPMessage): Promise<void> {\n const id = msg.id;\n if (id === undefined) return;\n const params = (msg as { params?: Record<string, unknown> }).params ?? {};\n try {\n switch (msg.method) {\n case 'terminal/create': {\n // Authorization gate: terminal/create spawns a process with the\n // agent's chosen command/args. Require explicit policy approval\n // before allowing it, since this is arbitrary code execution.\n const allowed = await this.authorizeCallback({\n toolCallId: `acp-terminal-create-${id}`,\n title: `Run command: ${String(params.command ?? '')} ${(Array.isArray(params.args) ? params.args : []).join(' ')}`.trim(),\n kind: 'execute',\n });\n if (!allowed) {\n await this.sendErrorResponse(id, -32602, 'terminal create denied by permission policy');\n return;\n }\n const createOpts: Parameters<TerminalServer['create']>[0] = {\n sessionId: String(params.sessionId ?? ''),\n command: String(params.command ?? ''),\n args: Array.isArray(params.args) ? (params.args as string[]) : [],\n };\n if (Array.isArray(params.env)) {\n createOpts.env = params.env as { name: string; value: string }[];\n }\n if (typeof params.cwd === 'string') {\n createOpts.cwd = params.cwd;\n }\n if (typeof params.outputByteLimit === 'number') {\n createOpts.outputByteLimit = params.outputByteLimit;\n }\n const result = this.terminalServer.create(createOpts);\n await this.sendResult(id, result);\n return;\n }\n case 'terminal/output': {\n const terminalId = String(params.terminalId ?? '');\n const out = this.terminalServer.output(terminalId);\n await this.sendResult(id, out);\n return;\n }\n case 'terminal/wait_for_exit': {\n const terminalId = String(params.terminalId ?? '');\n const exit = await this.terminalServer.waitForExit(terminalId);\n await this.sendResult(id, exit);\n return;\n }\n case 'terminal/kill': {\n const terminalId = String(params.terminalId ?? '');\n this.terminalServer.kill(terminalId);\n await this.sendResult(id, {});\n return;\n }\n case 'terminal/release': {\n const terminalId = String(params.terminalId ?? '');\n this.terminalServer.release(terminalId);\n await this.sendResult(id, {});\n return;\n }\n default:\n await this.sendErrorResponse(id, -32601, `unknown method: ${msg.method}`);\n }\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n await this.sendErrorResponse(id, -32603, message);\n }\n }\n}\n\n/**\n * Create a text ContentBlock. Convenience helper for callers of\n * `session.prompt()`.\n */\nexport function textContent(text: string): ContentBlock {\n return { type: 'text', text };\n}\n\n/**\n * Create an image ContentBlock. Only send this if the agent's\n * `promptCapabilities.image` is `true` (check via\n * `session.getCapabilities().promptCapabilities?.image`).\n */\nexport function imageContent(mimeType: string, data: string): ContentBlock {\n return { type: 'image', mimeType, data };\n}\n\n/**\n * Create an audio ContentBlock. Only send this if the agent's\n * `promptCapabilities.audio` is `true` (check via\n * `session.getCapabilities().promptCapabilities?.audio`).\n */\nexport function audioContent(mimeType: string, data: string): ContentBlock {\n return { type: 'audio', mimeType, data };\n}\n\nfunction extractText(block: unknown): string {\n if (typeof block !== 'object' || block === null) return '';\n const b = block as {\n type?: string;\n text?: unknown;\n resource?: { text?: unknown };\n };\n if (b.type === 'text' && typeof b.text === 'string') return b.text;\n // Embedded text resources carry their content under `resource.text`.\n if (\n b.type === 'resource' &&\n b.resource &&\n typeof b.resource === 'object' &&\n typeof b.resource.text === 'string'\n ) {\n return b.resource.text;\n }\n return '';\n}\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\n/** A fully-populated empty run result (used for pre-aborted short-circuits). */\nfunction emptyRunResult(stopReason: StopReason): ACPSessionRunResult {\n return {\n text: '',\n stopReason,\n hasText: false,\n toolCalls: [],\n diffs: [],\n thoughts: '',\n };\n}\n", "/**\n * ACP v1 server-side protocol handler.\n *\n * Receives JSON-RPC requests from an external ACP client (Zed, JetBrains\n * Junie, VS Code ACP extension, etc.) over stdio and answers them per the\n * v1 spec. See https://agentclientprotocol.com/protocol/v1/overview.\n *\n * Supported methods\n * \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n * - initialize \u2014 handshake\n * - authenticate \u2014 optional, no-op when auth isn't required\n * - session/new \u2014 create a session\n * - session/load \u2014 restore a session by id\n * - session/prompt \u2014 run one turn, stream session/update\n * notifications, return stopReason\n * - session/cancel \u2014 notification (no response); cancels the\n * in-flight turn on the target session\n * - session/set_mode \u2014 change the active mode for a session\n * - session/set_config_option \u2014 change a config option value\n * - session/list \u2014 list known sessions\n *\n * Method execution\n * \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n * The handler is transport-agnostic; it sends responses via the\n * `AgentServerTransport` injected at construction. The actual\n * agent-loop work for a `session/prompt` turn is delegated to the\n * caller-provided `runTurn` callback, which receives the prompt\n * blocks and the per-turn AbortSignal and resolves with the final\n * stopReason. Updates are streamed via the `emit` callback passed\n * to `runTurn`; the handler wraps each as a `session/update`\n * notification.\n *\n * This separation keeps the handler unit-testable: tests can supply\n * a fake `runTurn` that yields a canned sequence of updates, and\n * assert on the JSON-RPC traffic the handler produces. A real\n * production caller wires `runTurn` to a core `Agent` instance.\n *\n * Concurrency\n * \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n * Each session is single-threaded (one active turn at a time). The\n * handler keeps a per-session AbortController so a `session/cancel`\n * notification can stop the running turn mid-stream without tearing\n * down the session. Multiple sessions can be active concurrently.\n */\nimport {\n ACP_PROTOCOL_VERSION,\n type StopReason,\n type ContentBlock,\n type PermissionOption,\n type PlanEntry,\n type RequestPermissionOutcome,\n type ToolKind,\n type UsageCost,\n} from '../types/acp-v1.js';\nimport type { AgentServerTransport } from './stdio-transport.js';\nimport type { ACPMessage } from '../types/acp-messages.js';\n\n// Transport's `send` is typed `ACPMessage` which predates v1 and\n// doesn't carry a `jsonrpc` field. The runtime is fine \u2014 the\n// transport just `JSON.stringify`s the message \u2014 so cast at the\n// boundary.\ntype WireMessage = { jsonrpc?: '2.0'; id?: string | number; method?: string; params?: unknown; result?: unknown; error?: unknown };\nfunction toWire(msg: WireMessage): ACPMessage {\n return msg as never as ACPMessage;\n}\n\nexport const WRONGSTACK_VERSION = '0.274.1';\nconst WRONGSTACK_AUTH_METHODS = [\n {\n id: 'wrongstack-auth',\n name: 'Run wstack auth',\n description: 'Configure a WrongStack model provider in an interactive terminal.',\n type: 'terminal',\n args: ['auth'],\n },\n];\n\n/** What kinds of content the agent accepts in a prompt. */\nexport interface PromptCapabilities {\n image: boolean;\n audio: boolean;\n embeddedContext: boolean;\n}\n\nexport interface AgentCapabilities {\n loadSession: boolean;\n promptCapabilities: PromptCapabilities;\n}\n\nexport interface RunTurnInput {\n sessionId: string;\n /** Content blocks the client sent. */\n prompt: readonly ContentBlock[];\n /** Cancelled when the client sends `session/cancel` for this session. */\n signal: AbortSignal;\n}\n\nexport interface RunTurnResult {\n stopReason: StopReason;\n /** Optional summary text the agent produced. */\n text?: string;\n plan?: PlanEntry[];\n usage?: { used: number; size: number; cost?: UsageCost | undefined };\n}\n\n/**\n * A tool-call permission request the agent surfaces to the client.\n */\nexport interface RunTurnPermissionRequest {\n toolCall: { toolCallId: string; title: string; kind?: ToolKind | undefined };\n options: PermissionOption[];\n}\n\n/** Client filesystem/terminal capabilities advertised at initialize. */\nexport interface ClientCapabilities {\n fs?: { readTextFile?: boolean | undefined; writeTextFile?: boolean | undefined } | undefined;\n terminal?: boolean | undefined;\n}\n\n/**\n * Client-callback API handed to `runTurn`. Lets the agent's tools call back\n * into the connected ACP client \u2014 ask for permission, and (when the client\n * advertises the capability) use the client's filesystem and terminal so the\n * editor's view (including unsaved buffers) is the source of truth.\n */\nexport interface RunTurnApi {\n /**\n * Ask the connected ACP client to approve/reject a tool call via the\n * `session/request_permission` method. Resolves with the client's\n * outcome. Rejects if no client channel is available or the request\n * times out \u2014 the caller decides the fallback.\n */\n requestPermission(req: RunTurnPermissionRequest): Promise<RequestPermissionOutcome>;\n /** Capabilities the client advertised at initialize \u2014 gate tool wiring on these. */\n clientCapabilities: ClientCapabilities;\n /** Read a text file from the client's filesystem (`fs/read_text_file`). */\n readTextFile(params: { path: string; line?: number; limit?: number }): Promise<string>;\n /** Write a text file in the client's filesystem (`fs/write_text_file`). */\n writeTextFile(params: { path: string; content: string }): Promise<void>;\n /**\n * Run a command in the client's terminal (`terminal/create` \u2192\n * `wait_for_exit` \u2192 `output` \u2192 `release`) and resolve with the combined\n * output and exit code.\n */\n runTerminal(params: {\n command: string;\n args?: string[] | undefined;\n cwd?: string | undefined;\n }): Promise<{ output: string; exitCode: number | null }>;\n}\n\n/**\n * The agent's per-turn work. Streams `SessionUpdate` notifications to\n * `emit` and resolves with the final stopReason. Errors thrown from\n * this iterable are converted to a `prompt_failed` JSON-RPC error.\n *\n * `api` is an optional client-callback surface (permission requests).\n * Older runTurn implementations that ignore it keep working unchanged.\n */\nexport type RunTurn = (\n input: RunTurnInput,\n emit: (update: unknown) => void,\n api?: RunTurnApi,\n) => Promise<RunTurnResult>;\n\nexport interface SessionState {\n id: string;\n cwd: string;\n /** Per-turn abort signal \u2014 aborted when the session is cancelled or closed. */\n abort: AbortController;\n /** Active mode, advertised to the client in current_mode_update. */\n modeId: string;\n /** Created at, for session/list ordering. */\n createdAt: string;\n /** Last activity timestamp, for session/info_update. */\n updatedAt: string;\n /** Optional human title. */\n title?: string;\n}\n\n/** MCP-style session mode advertised in current_mode_update. */\nexport interface SessionMode {\n id: string;\n name: string;\n description?: string | undefined;\n}\n\nexport interface SessionConfigOption {\n id: string;\n name: string;\n type: 'select' | string;\n currentValue: string;\n options: { value: string; name: string; description?: string | undefined }[];\n}\n\nexport interface ProtocolHandlerOptions {\n transport: AgentServerTransport;\n /** Where the server is running; used for new sessions' default cwd. */\n defaultCwd: string;\n /** Agent's per-turn implementation. */\n runTurn: RunTurn;\n /**\n * Optional callbacks for the lifecycle events the server should\n * surface to the client. All default to no-ops.\n */\n onSessionNew?: ((state: SessionState) => void) | undefined;\n /** Static list of available modes (advertised to clients). */\n modes?: readonly SessionMode[] | undefined;\n /** Static list of config options. */\n configOptions?: readonly SessionConfigOption[] | undefined;\n /** Agent name advertised in initialize. */\n agentName?: string | undefined;\n /**\n * Optional source of replayable conversation history for `session/load`.\n * Returns the `session/update` payloads (user/agent message chunks) to\n * stream back to the client before the load response. Wired from\n * `makeACPServerAgentTurn(...).replay`.\n */\n replayFor?: ((sessionId: string) => Array<{ sessionUpdate: string; content: unknown }>) | undefined;\n /**\n * Optional hook to prime the turn engine's session history on cold\n * `session/load` (server restart). Wired from `makeACPServerAgentTurn(...).seed`\n * \u2014 it re-feeds the persisted conversation into the next-created Agent so\n * the model resumes, not just the client UI.\n */\n seedFor?: ((sessionId: string, history: Array<{ sessionUpdate: string; content: unknown }>) => void) | undefined;\n /**\n * Optional durable session store. When set, sessions + their recorded\n * history are persisted on create/prompt and restored on `session/load`,\n * so a reconnecting client can resume after a server restart.\n * (Structural type \u2014 `ACPSessionStore` satisfies it without a value import.)\n */\n store?: SessionPersistence | undefined;\n}\n\n/** Minimal durable-store contract the handler uses (ACPSessionStore satisfies it). */\nexport interface SessionPersistence {\n save(\n state: SessionState,\n history?: Array<{ sessionUpdate: string; content: unknown }>,\n ): Promise<unknown>;\n load(\n sessionId: string,\n ): Promise<\n | (Partial<SessionState> & { history?: Array<{ sessionUpdate: string; content: unknown }> | undefined })\n | null\n >;\n}\n\n/** Single global mode id, sufficient for v1. */\nconst DEFAULT_MODE_ID = 'code';\n\nconst DEFAULT_MODES: readonly SessionMode[] = [\n {\n id: DEFAULT_MODE_ID,\n name: 'Code',\n description: 'Default agent mode for code-generation tasks.',\n },\n];\n\nexport class ACPProtocolHandler {\n private readonly transport: AgentServerTransport;\n private readonly defaultCwd: string;\n private readonly runTurn: RunTurn;\n private readonly onSessionNew: (state: SessionState) => void;\n private readonly modes: readonly SessionMode[];\n private readonly configOptions: readonly SessionConfigOption[];\n private readonly agentName: string;\n private readonly replayFor:\n | ((sessionId: string) => Array<{ sessionUpdate: string; content: unknown }>)\n | undefined;\n private readonly seedFor:\n | ((sessionId: string, history: Array<{ sessionUpdate: string; content: unknown }>) => void)\n | undefined;\n private readonly store: SessionPersistence | undefined;\n\n private initialized = false;\n private clientCapabilities: ClientCapabilities = {};\n private readonly sessions = new Map<string, SessionState>();\n private nextId = 1;\n\n // Outbound request correlation (server \u2192 client requests, e.g.\n // session/request_permission). Keyed by our own `srv_N` ids.\n private readonly pendingOut = new Map<\n string,\n { resolve: (v: unknown) => void; reject: (e: Error) => void; timer: ReturnType<typeof setTimeout> }\n >();\n private nextOutId = 1;\n\n constructor(opts: ProtocolHandlerOptions) {\n this.transport = opts.transport;\n this.defaultCwd = opts.defaultCwd;\n this.runTurn = opts.runTurn;\n this.onSessionNew = opts.onSessionNew ?? (() => {});\n this.modes = opts.modes ?? DEFAULT_MODES;\n this.configOptions = opts.configOptions ?? [];\n this.agentName = opts.agentName ?? 'wrongstack';\n this.replayFor = opts.replayFor;\n this.seedFor = opts.seedFor;\n this.store = opts.store;\n // Route inbound JSON-RPC responses (to our outbound requests)\n // independently of the server's read loop. StdioTransport fires\n // onMessage on the stdin 'data' event, so a pending request resolves\n // even while a session/prompt handler is parked awaiting it.\n // Guarded: minimal transports (and some test fakes) may omit onMessage;\n // without it, server\u2192client requests simply aren't supported.\n if (typeof this.transport.onMessage === 'function') {\n this.transport.onMessage((m) => this.maybeResolvePending(m));\n }\n }\n\n /**\n * Send a request to the client and await its response. Used for\n * server-initiated calls like `session/request_permission`. Rejects on\n * timeout or transport error so the caller can pick a safe fallback.\n */\n private request(method: string, params: unknown, timeoutMs = 60_000): Promise<unknown> {\n const id = `srv_${this.nextOutId++}`;\n return new Promise<unknown>((resolve, reject) => {\n const timer = setTimeout(() => {\n this.pendingOut.delete(id);\n reject(new Error(`${method} timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n this.pendingOut.set(id, { resolve, reject, timer });\n this.transport\n .send(toWire({ jsonrpc: '2.0', id, method, params }))\n .catch((e: unknown) => {\n clearTimeout(timer);\n this.pendingOut.delete(id);\n reject(e instanceof Error ? e : new Error(String(e)));\n });\n });\n }\n\n private maybeResolvePending(m: ACPMessage): void {\n const id = (m as { id?: unknown }).id;\n if (typeof id !== 'string') return;\n const pending = this.pendingOut.get(id);\n if (!pending) return;\n this.pendingOut.delete(id);\n clearTimeout(pending.timer);\n const err = (m as { error?: { message?: string } }).error;\n if (err) pending.reject(new Error(err.message ?? 'client request failed'));\n else pending.resolve((m as { result?: unknown }).result);\n }\n\n /**\n * Process one inbound message. Returns true if this was a terminal\n * message (rare; reserved for future use by the server's own\n * shutdown signal).\n */\n async handleMessage(msg: unknown): Promise<boolean> {\n if (typeof msg !== 'object' || msg === null) return false;\n const m = msg as { id?: unknown; method?: unknown; params?: unknown; result?: unknown; error?: unknown };\n\n // Response (we never initiate requests, but be defensive).\n if (m.id !== undefined && (m.result !== undefined || m.error !== undefined)) {\n return false;\n }\n\n // Request (has id, has method, no result/error)\n if (m.id !== undefined && typeof m.method === 'string') {\n return this.handleRequest(m.id as string | number, m.method, m.params);\n }\n\n // Notification (no id, has method)\n if (typeof m.method === 'string') {\n return this.handleNotification(m.method, m.params);\n }\n\n return false;\n }\n\n /** Abort all active turns and drop session state. */\n close(): void {\n for (const [, session] of this.sessions) {\n session.abort.abort();\n }\n this.sessions.clear();\n for (const [, p] of this.pendingOut) {\n clearTimeout(p.timer);\n p.reject(new Error('protocol handler closed'));\n }\n this.pendingOut.clear();\n }\n\n // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Requests\n // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private async handleRequest(\n id: string | number,\n method: string,\n params: unknown,\n ): Promise<boolean> {\n // The only method allowed before initialize is `initialize` itself.\n if (method !== 'initialize' && !this.initialized) {\n await this.sendError(id, -32000, 'Not initialized');\n return false;\n }\n\n try {\n switch (method) {\n case 'initialize':\n return await this.handleInitialize(id, params);\n case 'authenticate':\n return await this.handleAuthenticate(id, params);\n case 'logout':\n return await this.handleLogout(id, params);\n case 'session/new':\n return await this.handleSessionNew(id, params);\n case 'session/load':\n return await this.handleSessionLoad(id, params);\n case 'session/resume':\n return await this.handleSessionResume(id, params);\n case 'session/close':\n return await this.handleSessionClose(id, params);\n case 'session/delete':\n return await this.handleSessionDelete(id, params);\n case 'session/prompt':\n return await this.handleSessionPrompt(id, params);\n case 'session/set_mode':\n return await this.handleSetMode(id, params);\n case 'session/set_config_option':\n return await this.handleSetConfigOption(id, params);\n case 'session/list':\n return await this.handleSessionList(id);\n case 'session/fork':\n return await this.handleSessionFork(id, params);\n case 'providers/list':\n return await this.handleProvidersList(id, params);\n case 'providers/set':\n return await this.handleProvidersSet(id, params);\n case 'providers/disable':\n return await this.handleProvidersDisable(id, params);\n case 'mcp/message':\n return await this.handleMcpMessage(id, params);\n default:\n // Everything reaching handleRequest carries an id, so it's a\n // JSON-RPC *request* and MUST get a response \u2014 otherwise a\n // conformant client blocks forever awaiting it. Unimplemented\n // IDE features (document/*, nes/*, elicitation/*) and any other\n // unknown method get a standard method-not-found error.\n await this.sendError(id, -32601, `Unknown method: ${method}`);\n return false;\n }\n } catch (err) {\n const { code, message, data } = errorToJsonRpc(err);\n await this.sendError(id, code, message, data);\n return false;\n }\n }\n\n private async handleInitialize(id: string | number, params: unknown): Promise<boolean> {\n const p = (params ?? {}) as { protocolVersion?: unknown; clientCapabilities?: ClientCapabilities };\n if (p.clientCapabilities && typeof p.clientCapabilities === 'object') {\n this.clientCapabilities = p.clientCapabilities;\n }\n // Version negotiation per spec: the client advertises its latest\n // supported version; the agent replies with the version it will use \u2014\n // the client's if supported, otherwise the agent's own latest. We must\n // NOT error on a mismatch (that breaks a forward-compatible client that\n // requested a newer protocol): we simply respond with the version we\n // speak and let the client decide whether to proceed. The client side\n // (`ACPSession.initialize`) already mirrors this lenient negotiation.\n this.initialized = true;\n await this.transport.send(toWire({\n jsonrpc: '2.0',\n id,\n result: {\n protocolVersion: ACP_PROTOCOL_VERSION,\n agentCapabilities: {\n loadSession: true,\n promptCapabilities: {\n // We route ACP image blocks into the core agent's multimodal\n // input (server-agent-turn.promptToAgentInput); whether the\n // model can see them is the configured provider's concern.\n image: true,\n audio: false,\n embeddedContext: true,\n },\n mcpCapabilities: {\n http: false,\n sse: false,\n },\n sessionCapabilities: {\n close: {},\n list: {},\n delete: {},\n resume: {},\n fork: {},\n },\n auth: {\n logout: {},\n },\n },\n agentInfo: {\n name: this.agentName,\n title: 'WrongStack',\n version: WRONGSTACK_VERSION,\n },\n authMethods: WRONGSTACK_AUTH_METHODS,\n modes: this.modes,\n configOptions: this.configOptions,\n },\n }));\n return false;\n }\n\n private async handleAuthenticate(id: string | number, _params: unknown): Promise<boolean> {\n // WrongStack doesn't currently require auth.\n await this.transport.send(toWire({\n jsonrpc: '2.0',\n id,\n result: { outcome: 'unauthenticated' },\n }));\n return false;\n }\n\n private async handleLogout(id: string | number, _params: unknown): Promise<boolean> {\n // WrongStack doesn't have persistent auth state, so logout is a no-op.\n await this.transport.send(toWire({\n jsonrpc: '2.0',\n id,\n result: {},\n }));\n return false;\n }\n\n private async handleSessionNew(id: string | number, params: unknown): Promise<boolean> {\n const p = (params ?? {}) as { cwd?: unknown; mcpServers?: unknown };\n const cwd = typeof p.cwd === 'string' ? p.cwd : this.defaultCwd;\n const sessionId = `sess_${this.allocId()}`;\n const now = new Date().toISOString();\n const state: SessionState = {\n id: sessionId,\n cwd,\n abort: new AbortController(),\n modeId: DEFAULT_MODE_ID,\n createdAt: now,\n updatedAt: now,\n };\n this.sessions.set(sessionId, state);\n this.onSessionNew(state);\n await this.persist(state);\n\n // Per spec, the server MAY emit current_mode_update /\n // config_option_update / available_commands_update notifications\n // immediately after session/new to populate the client UI. We do.\n await this.sendNotification({\n sessionId,\n update: {\n sessionUpdate: 'current_mode_update',\n modeId: this.modes[0]?.id ?? DEFAULT_MODE_ID,\n },\n });\n if (this.configOptions.length > 0) {\n await this.sendNotification({\n sessionId,\n update: {\n sessionUpdate: 'config_option_update',\n configOptions: [...this.configOptions],\n },\n });\n }\n\n await this.transport.send(toWire({\n jsonrpc: '2.0',\n id,\n result: {\n sessionId,\n modes: this.modes,\n configOptions: this.configOptions,\n },\n }));\n return false;\n }\n\n private async handleSessionLoad(id: string | number, params: unknown): Promise<boolean> {\n const p = (params ?? {}) as { sessionId?: unknown; cwd?: unknown; mcpServers?: unknown };\n const sessionId = typeof p.sessionId === 'string' ? p.sessionId : null;\n const loadCwd = typeof p.cwd === 'string' ? p.cwd : undefined;\n const existing = sessionId ? this.sessions.get(sessionId) : undefined;\n\n // Cold path: not in memory but persisted (server restarted). Restore the\n // session state + replay its stored history. The agent's own model\n // context starts fresh \u2014 the client UI is made whole via replay.\n if (!existing && sessionId && this.store) {\n const persisted = await this.store.load(sessionId);\n if (persisted) {\n const restored: SessionState = {\n id: sessionId,\n cwd: persisted.cwd ?? loadCwd ?? this.defaultCwd,\n abort: new AbortController(),\n modeId: persisted.modeId ?? DEFAULT_MODE_ID,\n createdAt: persisted.createdAt ?? new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n ...(persisted.title !== undefined ? { title: persisted.title } : {}),\n };\n this.sessions.set(sessionId, restored);\n // Prime the turn engine so the next prompt's Agent resumes the\n // model's context, not just the client UI.\n this.seedFor?.(sessionId, persisted.history ?? []);\n for (const update of persisted.history ?? []) {\n await this.sendNotification({ sessionId, update });\n }\n await this.sendNotification({\n sessionId,\n update: { sessionUpdate: 'current_mode_update', modeId: restored.modeId },\n });\n await this.transport.send(toWire({\n jsonrpc: '2.0',\n id,\n result: {\n initialMode: { currentModeId: restored.modeId, availableModes: this.modes },\n },\n }));\n return false;\n }\n }\n\n if (existing) {\n // Session exists in memory \u2014 restore it.\n existing.updatedAt = new Date().toISOString();\n // Replay the recorded conversation history (user/agent message\n // chunks) so the reconnecting client sees the prior turns.\n const replay = sessionId ? this.replayFor?.(sessionId) : undefined;\n if (replay) {\n for (const update of replay) {\n await this.sendNotification({ sessionId, update });\n }\n }\n await this.sendNotification({\n sessionId,\n update: {\n sessionUpdate: 'session_info_update',\n updatedAt: existing.updatedAt,\n },\n });\n await this.sendNotification({\n sessionId,\n update: {\n sessionUpdate: 'current_mode_update',\n modeId: existing.modeId,\n },\n });\n await this.transport.send(toWire({\n jsonrpc: '2.0',\n id,\n result: {\n initialMode: {\n currentModeId: existing.modeId,\n availableModes: this.modes,\n },\n },\n }));\n return false;\n }\n\n // Session not found \u2014 spec says to return an error.\n await this.sendError(id, -32000, `session not found: ${sessionId}`);\n return false;\n }\n\n private async handleSessionResume(id: string | number, params: unknown): Promise<boolean> {\n const p = (params ?? {}) as { sessionId?: unknown; cwd?: unknown; mcpServers?: unknown };\n const sessionId = typeof p.sessionId === 'string' ? p.sessionId : null;\n const existing = sessionId ? this.sessions.get(sessionId) : undefined;\n\n if (existing) {\n existing.updatedAt = new Date().toISOString();\n await this.transport.send(toWire({\n jsonrpc: '2.0',\n id,\n result: {\n initialMode: {\n currentModeId: existing.modeId,\n availableModes: this.modes,\n },\n },\n }));\n return false;\n }\n\n await this.sendError(id, -32000, `session not found: ${sessionId}`);\n return false;\n }\n\n private async handleSessionClose(id: string | number, params: unknown): Promise<boolean> {\n const p = (params ?? {}) as { sessionId?: unknown };\n const sessionId = typeof p.sessionId === 'string' ? p.sessionId : null;\n const session = sessionId ? this.sessions.get(sessionId) : undefined;\n\n if (!session) {\n await this.sendError(id, -32000, `session not found: ${sessionId}`);\n return false;\n }\n\n // Abort any in-flight turn and remove the session.\n session.abort.abort();\n if (sessionId) this.sessions.delete(sessionId);\n\n await this.transport.send(toWire({\n jsonrpc: '2.0',\n id,\n result: {},\n }));\n return false;\n }\n\n private async handleSessionDelete(id: string | number, params: unknown): Promise<boolean> {\n const p = (params ?? {}) as { sessionId?: unknown };\n const sessionId = typeof p.sessionId === 'string' ? p.sessionId : null;\n\n if (!sessionId) {\n await this.sendError(id, -32000, `session not found: ${sessionId}`);\n return false;\n }\n\n if (!this.sessions.has(sessionId)) {\n await this.transport.send(toWire({ jsonrpc: '2.0', id, result: { configOptions: [...this.configOptions] } }));\n return false;\n }\n const session = this.sessions.get(sessionId)!;\n session.abort.abort();\n this.sessions.delete(sessionId);\n\n await this.transport.send(toWire({\n jsonrpc: '2.0',\n id,\n result: {},\n }));\n return false;\n }\n\n private async handleSessionFork(id: string | number, params: unknown): Promise<boolean> {\n const p = (params ?? {}) as { sessionId?: unknown; cwd?: unknown; mcpServers?: unknown };\n const sourceId = typeof p.sessionId === 'string' ? p.sessionId : null;\n const source = sourceId ? this.sessions.get(sourceId) : undefined;\n if (!sourceId || !source) {\n await this.sendError(id, -32000, `session not found: ${sourceId}`);\n return false;\n }\n\n const now = new Date().toISOString();\n const sessionId = `sess_${this.allocId()}`;\n const forked: SessionState = {\n id: sessionId,\n cwd: typeof p.cwd === 'string' ? p.cwd : source.cwd,\n abort: new AbortController(),\n modeId: source.modeId,\n createdAt: now,\n updatedAt: now,\n ...(source.title !== undefined ? { title: source.title } : {}),\n };\n const history = (this.replayFor?.(sourceId) ?? []).map((update) => ({\n sessionUpdate: update.sessionUpdate,\n content: structuredClone(update.content),\n }));\n this.sessions.set(sessionId, forked);\n this.seedFor?.(sessionId, history);\n this.onSessionNew(forked);\n await this.persist(forked, history);\n\n await this.sendNotification({\n sessionId,\n update: { sessionUpdate: 'current_mode_update', modeId: forked.modeId },\n });\n await this.transport.send(toWire({\n jsonrpc: '2.0',\n id,\n result: {\n sessionId,\n modes: this.modes,\n configOptions: this.configOptions,\n },\n }));\n return false;\n }\n\n private async handleProvidersList(id: string | number, _params: unknown): Promise<boolean> {\n // Return the current provider configuration.\n await this.transport.send(toWire({\n jsonrpc: '2.0',\n id,\n result: {\n providers: [],\n currentProviderId: null,\n },\n }));\n return false;\n }\n\n private async handleProvidersSet(id: string | number, _params: unknown): Promise<boolean> {\n await this.sendError(id, -32000, 'provider configuration not available through ACP; use wstack auth');\n return false;\n }\n\n private async handleProvidersDisable(id: string | number, _params: unknown): Promise<boolean> {\n await this.transport.send(toWire({\n jsonrpc: '2.0',\n id,\n result: {},\n }));\n return false;\n }\n\n private async handleMcpMessage(id: string | number, _params: unknown): Promise<boolean> {\n await this.sendError(id, -32000, 'MCP message routing not available through ACP');\n return false;\n }\n\n private async handleSessionPrompt(id: string | number, params: unknown): Promise<boolean> {\n const p = (params ?? {}) as { sessionId?: unknown; prompt?: unknown };\n const sessionId = typeof p.sessionId === 'string' ? p.sessionId : null;\n if (!sessionId || !this.sessions.has(sessionId)) {\n await this.sendError(id, -32000, 'unknown or missing sessionId');\n return false;\n }\n if (!Array.isArray(p.prompt)) {\n await this.sendError(id, -32602, 'prompt must be an array of content blocks');\n return false;\n }\n const session = this.sessions.get(sessionId)!;\n\n // If the previous turn was cancelled, recreate the AbortController\n // so a stale signal doesn't cancel the new turn.\n if (session.abort.signal.aborted) {\n session.abort = new AbortController();\n }\n\n const turnSignal = new AbortController();\n // Forward session/cancel notifications to the turn's signal.\n const onCancel = (): void => turnSignal.abort();\n session.abort.signal.addEventListener('abort', onCancel, { once: true });\n\n // Client-callback surface for this turn: lets the agent's tools ask\n // the connected client for permission, and use the client's filesystem\n // and terminal (when advertised) instead of the local ones.\n const api: RunTurnApi = {\n clientCapabilities: this.clientCapabilities,\n requestPermission: async (req) => {\n const res = await this.request('session/request_permission', {\n sessionId,\n toolCall: req.toolCall,\n options: req.options,\n });\n const outcome = (res as { outcome?: RequestPermissionOutcome } | undefined)?.outcome;\n return outcome ?? { outcome: 'cancelled' };\n },\n readTextFile: async (params) => {\n const res = await this.request('fs/read_text_file', { sessionId, ...params });\n return String((res as { content?: unknown })?.content ?? '');\n },\n writeTextFile: async (params) => {\n await this.request('fs/write_text_file', { sessionId, ...params });\n },\n runTerminal: async ({ command, args, cwd }) => {\n const created = (await this.request('terminal/create', {\n sessionId,\n command,\n ...(args ? { args } : {}),\n ...(cwd ? { cwd } : {}),\n })) as { terminalId?: string };\n const terminalId = created?.terminalId;\n if (!terminalId) return { output: '', exitCode: null };\n try {\n const exit = (await this.request('terminal/wait_for_exit', { sessionId, terminalId })) as {\n exitCode?: number | null;\n };\n const out = (await this.request('terminal/output', { sessionId, terminalId })) as {\n output?: unknown;\n };\n return {\n output: String(out?.output ?? ''),\n exitCode: typeof exit?.exitCode === 'number' ? exit.exitCode : null,\n };\n } finally {\n try {\n await this.request('terminal/release', { sessionId, terminalId });\n } catch {\n // best-effort release\n }\n }\n },\n };\n\n let result: RunTurnResult;\n try {\n result = await this.runTurn(\n { sessionId, prompt: p.prompt as ContentBlock[], signal: turnSignal.signal },\n (update) => this.sendNotification({ sessionId, update }),\n api,\n );\n } catch (err) {\n session.abort.signal.removeEventListener('abort', onCancel);\n const { code, message, data } = errorToJsonRpc(err);\n await this.sendError(id, code, message, data);\n return false;\n }\n session.abort.signal.removeEventListener('abort', onCancel);\n session.updatedAt = new Date().toISOString();\n await this.persist(session);\n\n await this.transport.send(toWire({\n jsonrpc: '2.0',\n id,\n result: { stopReason: result.stopReason },\n }));\n return false;\n }\n\n private async handleSetMode(id: string | number, params: unknown): Promise<boolean> {\n const p = (params ?? {}) as { sessionId?: unknown; modeId?: unknown };\n const sessionId = typeof p.sessionId === 'string' ? p.sessionId : null;\n const modeId = typeof p.modeId === 'string' ? p.modeId : null;\n const session = sessionId ? this.sessions.get(sessionId) : undefined;\n if (!session || !modeId || !this.modes.some((m) => m.id === modeId)) {\n await this.sendError(id, -32602, 'invalid sessionId or modeId');\n return false;\n }\n session.modeId = modeId;\n session.updatedAt = new Date().toISOString();\n await this.sendNotification({\n sessionId,\n update: { sessionUpdate: 'current_mode_update', modeId },\n });\n await this.transport.send(toWire({ jsonrpc: '2.0', id, result: {} }));\n return false;\n }\n\n private async handleSetConfigOption(id: string | number, params: unknown): Promise<boolean> {\n const p = (params ?? {}) as { sessionId?: unknown; configId?: unknown; value?: unknown };\n const sessionId = typeof p.sessionId === 'string' ? p.sessionId : null;\n const optionId = typeof p.configId === 'string' ? p.configId : null;\n const value = typeof p.value === 'string' ? p.value : null;\n const session = sessionId ? this.sessions.get(sessionId) : undefined;\n const option = optionId ? this.configOptions.find((o) => o.id === optionId) : undefined;\n if (!session || !option || value === null || !option.options.some((o) => o.value === value)) {\n await this.sendError(id, -32602, 'invalid sessionId, configId, or value');\n return false;\n }\n option.currentValue = value;\n session.updatedAt = new Date().toISOString();\n await this.sendNotification({\n sessionId,\n update: {\n sessionUpdate: 'config_option_update',\n configOptions: [...this.configOptions],\n },\n });\n await this.transport.send(toWire({ jsonrpc: '2.0', id, result: { configOptions: [...this.configOptions] } }));\n return false;\n }\n\n private async handleSessionList(id: string | number): Promise<boolean> {\n const sessions = Array.from(this.sessions.values()).map((s) => {\n const out: { sessionId: string; cwd: string; updatedAt: string; title?: string } = {\n sessionId: s.id,\n cwd: s.cwd,\n updatedAt: s.updatedAt,\n };\n if (s.title !== undefined) out.title = s.title;\n return out;\n });\n await this.transport.send(toWire({\n jsonrpc: '2.0',\n id,\n result: { sessions },\n }));\n return false;\n }\n\n // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Notifications\n // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private async handleNotification(method: string, params: unknown): Promise<boolean> {\n switch (method) {\n case 'session/cancel': {\n const p = (params ?? {}) as { sessionId?: unknown };\n const sessionId = typeof p.sessionId === 'string' ? p.sessionId : null;\n const session = sessionId ? this.sessions.get(sessionId) : undefined;\n if (session) {\n session.abort.abort();\n }\n return false;\n }\n case '$/cancel_request': {\n // Protocol-level request cancellation \u2014 no-op for now.\n return false;\n }\n case 'exit':\n // Client is shutting down. Best-effort: abort all sessions.\n this.close();\n return true;\n default:\n // Unknown notification \u2014 log and ignore.\n return false;\n }\n }\n\n // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Wire helpers\n // \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private async sendNotification(params: unknown): Promise<void> {\n await this.transport.send(toWire({ jsonrpc: '2.0', method: 'session/update', params }));\n }\n\n /** Best-effort durable persistence of a session + its recorded history. */\n private async persist(\n state: SessionState,\n history: Array<{ sessionUpdate: string; content: unknown }> | undefined = undefined,\n ): Promise<void> {\n if (!this.store) return;\n try {\n await this.store.save(state, history ?? this.replayFor?.(state.id));\n } catch {\n // persistence is best-effort \u2014 never fail a request because the disk hiccuped\n }\n }\n\n private async sendError(\n id: string | number,\n code: number,\n message: string,\n data?: unknown,\n ): Promise<void> {\n const error: { code: number; message: string; data?: unknown } = { code, message };\n if (data !== undefined) error.data = data;\n await this.transport.send(toWire({ jsonrpc: '2.0', id, error }));\n }\n\n private allocId(): number {\n return this.nextId++;\n }\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Error mapping\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction errorToJsonRpc(err: unknown): { code: number; message: string; data?: unknown } {\n if (err && typeof err === 'object') {\n const e = err as { code?: unknown; message?: unknown; data?: unknown };\n if (typeof e.code === 'number' && typeof e.message === 'string') {\n const result: { code: number; message: string; data?: unknown } = {\n code: e.code,\n message: e.message,\n };\n if (e.data !== undefined) result.data = e.data;\n return result;\n }\n }\n const message = err instanceof Error ? err.message : String(err);\n return { code: -32603, message };\n}\n", "/**\n * WrongStackACPServer \u2014 ACP v1 server-side entry point.\n *\n * Exposes WrongStack as an ACP-compatible agent. ACP clients (Zed, JetBrains\n * Junie, VS Code ACP extension) spawn this as a subprocess, send JSON-RPC\n * messages over stdio, and receive v1-protocol responses.\n *\n * Usage:\n * node dist/agent/wrongstack-acp-agent.js\n *\n * Or via the CLI:\n * wstack acp-server\n *\n * Wiring a real agent: this class is the surface; the bootstrap\n * binary uses a no-op echo by default so the binary is a useful\n * connectivity smoke test. For a real server, instantiate\n * `WrongStackACPServer` programmatically and pass a `runTurn`\n * produced by `makeACPServerAgentTurn({ agentFor: ... })` from\n * `./server-agent-turn.js`. The factory is responsible for building\n * a real core `Agent` (with the right provider, model, system prompt,\n * etc.) per session.\n *\n * Startup: stdout is JSON-RPC only by default. The legacy `[wstack-acp]\\n`\n * marker can be enabled for older internal harnesses with\n * `legacyStartupMarker`, but ACP clients should rely on v1 initialize.\n */\nimport { fileURLToPath } from 'node:url';\nimport { createServer, type Server } from 'node:http';\nimport { writeErr } from '@wrongstack/core';\nimport type { ACPMessage } from '../types/acp-messages.js';\nimport {\n ACPProtocolHandler,\n type RunTurn,\n type RunTurnResult,\n type SessionPersistence,\n} from './protocol-handler.js';\nimport { StdioTransport } from './stdio-transport.js';\n\nexport interface WrongStackACPServerOptions {\n runTurn?: RunTurn | undefined;\n defaultCwd?: string | undefined;\n agentName?: string | undefined;\n /**\n * Transport mode. 'stdio' (default) communicates over stdin/stdout.\n * When a number is provided, the server listens as an HTTP server on\n * that port, accepting Streamable HTTP (JSON-RPC over HTTP POST).\n */\n transport?: 'stdio' | number | undefined;\n /** Host for HTTP transport. Defaults to '127.0.0.1'. */\n host?: string | undefined;\n /**\n * Bearer token required for HTTP transport authentication. When set,\n * every HTTP request must include `Authorization: Bearer <token>` or\n * `?token=<token>` in the query string. When unset, the server is\n * unauthenticated (acceptable for loopback-only development).\n */\n authToken?: string | undefined;\n /** Emit the pre-v1 startup marker on stdio. Defaults to false. */\n legacyStartupMarker?: boolean | undefined;\n /**\n * Conversation-history source for `session/load` replay. Pass\n * `makeACPServerAgentTurn(...).replay` here so a reconnecting client\n * gets prior turns streamed back.\n */\n replayFor?: ((sessionId: string) => Array<{ sessionUpdate: string; content: unknown }>) | undefined;\n /**\n * Cold-load seed hook. Pass `makeACPServerAgentTurn(...).seed` so a\n * restored session's Agent resumes the model context, not just the UI.\n */\n seedFor?: ((sessionId: string, history: Array<{ sessionUpdate: string; content: unknown }>) => void) | undefined;\n /**\n * Durable session store. When set, sessions + history are persisted and\n * restored across restarts for `session/load`. Pass an `ACPSessionStore`.\n */\n store?: SessionPersistence | undefined;\n}\n\nexport class WrongStackACPServer {\n private readonly transport: StdioTransport;\n private readonly handler: ACPProtocolHandler;\n private readonly options: WrongStackACPServerOptions;\n /** HTTP server when transport mode is HTTP. */\n private httpServer: Server | null = null;\n private running = false;\n\n constructor(opts: WrongStackACPServerOptions = {}) {\n this.options = opts;\n this.transport = new StdioTransport();\n const runTurn: RunTurn = opts.runTurn ?? defaultEchoRunTurn;\n this.handler = new ACPProtocolHandler({\n transport: this.transport,\n defaultCwd: opts.defaultCwd ?? process.cwd(),\n runTurn,\n agentName: opts.agentName,\n ...(opts.replayFor ? { replayFor: opts.replayFor } : {}),\n ...(opts.seedFor ? { seedFor: opts.seedFor } : {}),\n ...(opts.store ? { store: opts.store } : {}),\n });\n }\n\n /**\n * Start the server. Mode depends on `options.transport`:\n * - 'stdio' (default): reads JSON-RPC from stdin, writes to stdout.\n * - number: listens as HTTP on the given port.\n */\n async start(): Promise<void> {\n const transportMode = this.options.transport;\n if (typeof transportMode === 'number') {\n await this.startHttp(transportMode);\n } else {\n await this.startStdio();\n }\n }\n\n private async startStdio(): Promise<void> {\n if (this.options.legacyStartupMarker) {\n this.transport.sendStartupMarker();\n }\n this.running = true;\n while (this.running) {\n const msg = await this.transport.read();\n if (!msg) break;\n const terminal = await this.handler.handleMessage(msg);\n if (terminal) break;\n }\n this.transport.close();\n }\n\n private async startHttp(port: number): Promise<void> {\n const host = this.options.host ?? '127.0.0.1';\n const handler = this.handler;\n const authToken = this.options.authToken;\n\n // Serialize HTTP requests to prevent concurrent transport.send races.\n // The ACPProtocolHandler stores a single transport reference; without\n // serialization, concurrent requests would overwrite each other's\n // monkey-patched send capture, causing cross-talk or lost responses.\n let httpChain: Promise<void> = Promise.resolve();\n\n this.httpServer = createServer(async (req, res) => {\n // \u2500\u2500 Authentication \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // When an authToken is configured, require it on every request.\n // Accept `Authorization: Bearer <token>` header or `?token=<token>`\n // query parameter (the latter for browser clients).\n if (authToken) {\n const url = new URL(req.url ?? '/', `http://${host}:${port}`);\n const queryToken = url.searchParams.get('token');\n const authHeader = req.headers['authorization'];\n const bearerToken = Array.isArray(authHeader)\n ? authHeader[0]?.replace(/^Bearer\\s+/i, '')\n : authHeader?.replace(/^Bearer\\s+/i, '');\n const supplied = queryToken ?? bearerToken ?? '';\n if (supplied !== authToken) {\n res.writeHead(401, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({ error: { code: -32001, message: 'Unauthorized' } }));\n return;\n }\n }\n\n // Origin guard. Real ACP/MCP clients (Zed, JetBrains, curl, the MCP SDK)\n // are non-browser and send no `Origin` header, so they are unaffected. A\n // browser making a cross-origin request DOES send `Origin`; reject it so a\n // malicious web page the user visits cannot reach this agent and\n // drive it (a real `runTurn` executes tools/commands \u2014 i.e. RCE).\n const selfOrigin = `http://${host}:${port}`;\n const reqOrigin = Array.isArray(req.headers.origin)\n ? req.headers.origin[0]\n : req.headers.origin;\n if (reqOrigin && reqOrigin !== selfOrigin) {\n res.writeHead(403);\n res.end(JSON.stringify({ error: 'cross-origin request forbidden' }));\n return;\n }\n if (reqOrigin) res.setHeader('Access-Control-Allow-Origin', reqOrigin);\n res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');\n res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Mcp-Session-Id, Authorization');\n\n if (req.method === 'OPTIONS') {\n res.writeHead(204);\n res.end();\n return;\n }\n\n if (req.method !== 'POST') {\n res.writeHead(405);\n res.end(JSON.stringify({ error: 'method not allowed' }));\n return;\n }\n\n // Reject oversized request bodies (CWE-400).\n const MAX_HTTP_BODY = 10 * 1024 * 1024;\n let body = '';\n let bodyBytes = 0;\n let tooLarge = false;\n for await (const chunk of req) {\n bodyBytes += chunk.length;\n if (bodyBytes > MAX_HTTP_BODY) {\n tooLarge = true;\n break;\n }\n body += chunk;\n }\n if (tooLarge) {\n res.writeHead(413, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({ error: { code: -32700, message: 'Request body too large' } }));\n return;\n }\n\n let msg: unknown;\n try {\n msg = JSON.parse(body);\n } catch {\n res.writeHead(400);\n res.end(JSON.stringify({ error: { code: -32700, message: 'Parse error' } }));\n return;\n }\n\n // Notifications (no `id`) \u2014 e.g. `session/cancel` \u2014 must NOT queue behind\n // the request chain. A `session/prompt` awaits its whole turn while\n // holding the chain, so a cancel routed through the chain would only be\n // delivered after the very turn it is trying to stop already finished.\n // Cancel/exit produce no outbound sends, so they need neither the\n // send-capture swap nor the chain; deliver them immediately as an ack.\n const isNotification =\n typeof msg === 'object' &&\n msg !== null &&\n (msg as { id?: unknown }).id === undefined &&\n typeof (msg as { method?: unknown }).method === 'string';\n if (isNotification) {\n try {\n await handler.handleMessage(msg);\n } catch {\n /* best-effort: a cancel/exit that throws must not 500 the client */\n }\n res.writeHead(200, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({ notifications: [] }));\n return;\n }\n\n // Serialize this request's processing through a chain so concurrent\n // HTTP requests can't race on the shared transport.send capture.\n const requestPromise = httpChain.then(async () => {\n const notifications: unknown[] = [];\n let response: ACPMessage | null = null;\n const originalSend = this.transport.send.bind(this.transport);\n this.transport.send = async (m: ACPMessage) => {\n if (m.id !== undefined && (m.result !== undefined || m.error !== undefined)) {\n response = m;\n } else if (m.method === 'session/update') {\n notifications.push(m.params);\n } else {\n notifications.push(m);\n }\n };\n\n try {\n await handler.handleMessage(msg);\n } finally {\n this.transport.send = originalSend;\n }\n\n res.writeHead(200, { 'Content-Type': 'application/json' });\n const responseBody =\n response !== null\n ? { ...(response as ACPMessage), notifications }\n : { notifications };\n res.end(JSON.stringify(responseBody));\n });\n\n // Chain the next request after this one completes (success or failure).\n httpChain = requestPromise.catch(() => undefined);\n\n // Await the chained promise so the response is sent before the\n // function returns. Errors are caught by the chain wrapper.\n try {\n await requestPromise;\n } catch {\n // Response already ended or an error occurred after res.end.\n // The chain's catch ensures httpChain doesn't stay rejected.\n }\n });\n\n return new Promise<void>((resolve) => {\n this.httpServer!.listen(port, host, () => {\n writeErr(`[wstack-acp] HTTP server listening on http://${host}:${port}\\n`);\n this.running = true;\n resolve();\n });\n });\n }\n\n /** Stop the server. */\n stop(): void {\n this.running = false;\n this.transport.close();\n if (this.httpServer) {\n this.httpServer.close();\n this.httpServer = null;\n }\n }\n}\n\n/**\n * Default per-turn implementation: a no-op that echoes nothing useful\n * and returns `end_turn`. Lets the server boot end-to-end without\n * needing the core Agent factory (which would couple this entrypoint\n * to a long-lived model provider). The real implementation is\n * `ACPServerAgentTurn` (follow-up PR) that wires a core `Agent`.\n */\nconst defaultEchoRunTurn: RunTurn = async (_input, _emit): Promise<RunTurnResult> => {\n return { stopReason: 'end_turn' };\n};\n\n/**\n * Bootstrap function for `node dist/agent/wrongstack-acp-agent.js`.\n * Instantiates the server with the default (no-op) runTurn so the\n * binary is useful as a connectivity smoke test.\n *\n * In practice the CLI will instantiate and run `WrongStackACPServer`\n * directly, passing a real `runTurn` wired to a core `Agent`.\n */\n/* v8 ignore start -- process entrypoint: bootstrap + auto-start only run when launched as `node wrongstack-acp-agent.js`, never on import (which the CLI does to reuse the class). */\nasync function main(): Promise<void> {\n const server = new WrongStackACPServer();\n await server.start();\n}\n\nconst isEntrypoint =\n process.argv[1] !== undefined && fileURLToPath(import.meta.url) === process.argv[1];\nif (isEntrypoint) {\n main().catch((err) => {\n writeErr(`[wstack-acp fatal] ${err}\\n`);\n process.exit(1);\n });\n}\n/* v8 ignore stop */\n", "/**\n * ACPServerAgentTurn \u2014 `RunTurn` adapter for the v1 server side.\n *\n * Wires the ACP v1 server (`ACPProtocolHandler`) to a core `Agent`.\n * Each session gets its own `Agent` instance (per spec: sessions are\n * isolated; sharing agents across sessions would defeat isolation).\n * The agent is created lazily on the first `session/prompt` and\n * torn down when the server is closed or the session is removed.\n *\n * The adapter:\n * - converts the ACP `ContentBlock[]` prompt into a single string\n * (concatenating text blocks; non-text blocks are recorded as a\n * note in the prompt \u2014 future work can route images / audio to\n * the appropriate provider)\n * - calls `agent.run(prompt, {signal})` to drive the core loop\n * - captures the agent's text result and emits it as one or more\n * `agent_message_chunk` notifications\n * - maps the agent's stop semantics to a v1 `StopReason`\n *\n * Streaming: the core `Agent` API is not currently token-streamed\n * through this surface (its `run()` returns a final `RunResult`).\n * v1 clients expect text deltas, but most implementations batch\n * them \u2014 a single chunk per turn is acceptable. A future\n * enhancement can use the Agent's `Renderer` interface to capture\n * deltas as they're written, then forward them as multiple chunks.\n *\n * Scope: the adapter is deliberately minimal. It does NOT:\n * - model the full conversation history across turns (the v1 spec\n * leaves this to the agent; on the next prompt we re-feed the\n * latest user message and the agent handles its own history)\n * - use the agent's tool registry, permission policy, or\n * extensions (this adapter is the lowest-fidelity integration;\n * a future PR can wire a richer session-aware agent)\n * - stream deltas token-by-token (see \"Streaming\" above)\n *\n * Cancellation: the parent `AbortSignal` propagates through\n * `agent.run({signal})` and the underlying provider call observes\n * it. On abort, the adapter maps the resulting `AbortError` to\n * `{stopReason: 'cancelled'}`.\n */\nimport type { Agent, AgentInput } from '@wrongstack/core';\nimport type {\n ContentBlock,\n PlanEntry,\n StopReason,\n ToolKind,\n UsageCost,\n} from '../types/acp-v1.js';\nimport type {\n RunTurn,\n RunTurnApi,\n RunTurnResult,\n} from './protocol-handler.js';\n\nexport interface ACPServerAgentTurnOptions {\n /**\n * Factory that creates a fresh `Agent` for a given session.\n * Called once per session on the first `session/prompt` turn.\n * The factory must isolate each agent \u2014 sharing one agent\n * across sessions would defeat v1's session-isolation model.\n *\n * `api` (when provided) is the client-callback surface: ask the client\n * for permission, and use the client's filesystem/terminal when it\n * advertises those capabilities. A factory that wires it builds a\n * client-backed permission policy and ACP-backed fs/terminal tools\n * instead of silently auto-approving against the local disk.\n */\n agentFor: (\n sessionId: string,\n cwd: string,\n api?: RunTurnApi,\n ) => Promise<Agent> | Agent;\n /**\n * Hard wall-clock cap for one turn. The agent's own provider\n * timeout is layered under this; this cap is a safety belt.\n * Default 5 minutes.\n */\n timeoutMs?: number | undefined;\n}\n\n/** A recorded conversation turn, replayable on `session/load`. */\nexport interface SessionReplayUpdate {\n sessionUpdate: 'user_message_chunk' | 'agent_message_chunk';\n content: { type: 'text'; text: string };\n}\n\n/**\n * A `RunTurn` that also exposes the recorded per-session history so the\n * server can replay it on `session/load`.\n */\nexport interface ACPServerAgentTurn {\n (input: Parameters<RunTurn>[0], emit: Parameters<RunTurn>[1], api?: Parameters<RunTurn>[2]): Promise<RunTurnResult>;\n /** Recorded user/agent text turns for a session, in order. */\n replay(sessionId: string): SessionReplayUpdate[];\n /**\n * Seed a session's history (from a durable store on cold `session/load`)\n * so `replay()` returns it AND the next-created `Agent` for the session is\n * primed with the prior conversation as model context \u2014 not just the\n * client UI. Call before the first post-load `session/prompt`.\n */\n seed(sessionId: string, history: ReadonlyArray<{ sessionUpdate: string; content: unknown }>): void;\n}\n\n/**\n * Build a `RunTurn` that owns per-session `Agent` instances and\n * delegates each turn to the appropriate agent. The returned\n * function is reusable across sessions \u2014 the agents are kept in a\n * Map keyed by `sessionId`. It also records each turn's user/agent\n * text so the server can replay history on `session/load` (see\n * `.replay(sessionId)`).\n */\nexport function makeACPServerAgentTurn(\n opts: ACPServerAgentTurnOptions,\n): ACPServerAgentTurn {\n const agents = new Map<string, Agent>();\n const timeouts = new Map<string, ReturnType<typeof setTimeout>>();\n const history = new Map<string, SessionReplayUpdate[]>();\n // Sessions restored from a durable store whose freshly-created Agent must\n // be primed with the prior conversation before its first turn runs.\n const pendingSeed = new Set<string>();\n const timeoutMs = opts.timeoutMs ?? 5 * 60_000;\n\n const turn = async (\n input: Parameters<RunTurn>[0],\n emit: Parameters<RunTurn>[1],\n api?: Parameters<RunTurn>[2],\n ): Promise<RunTurnResult> => {\n // Lazily create an agent for this session on the first turn.\n let agent = agents.get(input.sessionId);\n if (!agent) {\n agent = await opts.agentFor(input.sessionId, process.cwd(), api);\n agents.set(input.sessionId, agent);\n // Cold-load priming: re-feed the restored conversation into the new\n // agent's context so the MODEL resumes (not just the client UI).\n if (pendingSeed.has(input.sessionId)) {\n pendingSeed.delete(input.sessionId);\n seedAgentContext(agent, history.get(input.sessionId) ?? []);\n }\n }\n\n // Per-turn safety belt: a hard wall-clock cap that actually aborts the\n // run. We drive `agent.run` with a derived signal that fires when EITHER\n // the parent signal (client `session/cancel`) aborts OR the timer\n // elapses. Without this, a provider call that ignores the parent signal\n // would hang forever despite the documented `timeoutMs` cap.\n const turnAbort = new AbortController();\n const abortForTimeout = (): void => turnAbort.abort();\n const onParentAbort = (): void => turnAbort.abort();\n if (input.signal.aborted) {\n turnAbort.abort();\n } else {\n input.signal.addEventListener('abort', onParentAbort, { once: true });\n }\n const timer = setTimeout(() => {\n timeouts.delete(input.sessionId);\n abortForTimeout();\n }, timeoutMs);\n timeouts.set(input.sessionId, timer);\n\n // Stream the core agent's tool activity to the ACP client as\n // tool_call / tool_call_update notifications so editors (Zed,\n // JetBrains, \u2026) render live tool cards + statuses instead of seeing\n // a silent gap until the final text. We subscribe for the duration\n // of this turn and detach in the finally block.\n const unsub: Array<() => void> = [];\n // Real `Agent` always exposes `.events`; guard for Agent-like fakes.\n const bus = (agent as { events?: { on?: typeof agent.events.on } }).events;\n if (bus?.on) {\n unsub.push(\n bus.on('tool.started', (e) => {\n emit({\n sessionUpdate: 'tool_call',\n toolCallId: e.id,\n title: toolTitle(e.name, e.input),\n kind: toolNameToKind(e.name),\n status: 'in_progress',\n ...(isRecord(e.input) ? { rawInput: e.input } : {}),\n });\n }),\n bus.on('tool.executed', (e) => {\n emit({\n sessionUpdate: 'tool_call_update',\n toolCallId: e.id ?? e.name,\n status: e.ok ? 'completed' : 'failed',\n ...(e.output !== undefined\n ? {\n content: [\n { type: 'content', content: { type: 'text', text: e.output } },\n ],\n }\n : {}),\n });\n }),\n );\n }\n\n try {\n const userInput = promptToAgentInput(input.prompt);\n const result = await agent.run(userInput, { signal: turnAbort.signal });\n\n // Stream the agent's final text back\n const text = extractText(result);\n if (text) {\n emit({\n sessionUpdate: 'agent_message_chunk',\n content: { type: 'text', text },\n });\n }\n\n // Record the turn so `session/load` can replay the conversation.\n const userText = promptToText(input.prompt);\n const hist = history.get(input.sessionId) ?? [];\n if (userText) {\n hist.push({ sessionUpdate: 'user_message_chunk', content: { type: 'text', text: userText } });\n }\n if (text) {\n hist.push({ sessionUpdate: 'agent_message_chunk', content: { type: 'text', text } });\n }\n if (hist.length > 0) history.set(input.sessionId, hist);\n\n // Emit plan if the agent provided one\n const plan = extractPlan(result);\n if (plan.length > 0) {\n emit({\n sessionUpdate: 'plan',\n entries: plan,\n });\n }\n\n // Emit usage if the agent provided one\n const usage = extractUsage(result);\n if (usage) {\n emit({\n sessionUpdate: 'usage_update',\n used: usage.used,\n size: usage.size,\n ...(usage.cost ? { cost: usage.cost } : {}),\n });\n }\n\n const result_out: RunTurnResult = {\n // `turnAbort.signal` covers both client cancellation and the\n // wall-clock timeout, so either maps to stopReason 'cancelled'.\n stopReason: pickStopReason(result, turnAbort.signal),\n };\n if (text) result_out.text = text;\n const runTurnPlan = extractPlan(result);\n if (runTurnPlan.length > 0) result_out.plan = runTurnPlan;\n if (usage) result_out.usage = usage;\n return result_out;\n } finally {\n clearTimeout(timer);\n timeouts.delete(input.sessionId);\n input.signal.removeEventListener('abort', onParentAbort);\n for (const u of unsub) u();\n }\n };\n\n const replay = (sessionId: string): SessionReplayUpdate[] =>\n history.get(sessionId) ?? [];\n\n const seed = (\n sessionId: string,\n incoming: ReadonlyArray<{ sessionUpdate: string; content: unknown }>,\n ): void => {\n if (incoming.length === 0) return;\n history.set(sessionId, [...incoming] as SessionReplayUpdate[]);\n pendingSeed.add(sessionId);\n };\n\n return Object.assign(turn, { replay, seed });\n}\n\n/**\n * Prime a freshly-created agent's conversation state with restored history.\n * Each recorded user/agent chunk becomes a `user`/`assistant` message so the\n * model continues the prior conversation instead of starting blank.\n */\nfunction seedAgentContext(\n agent: Agent,\n history: ReadonlyArray<{ sessionUpdate: string; content: unknown }>,\n): void {\n const state = (agent as { ctx?: { state?: { appendMessage?: (m: unknown) => void } } }).ctx?.state;\n if (!state?.appendMessage) return;\n for (const u of history) {\n const text = (u.content as { text?: unknown } | undefined)?.text;\n if (typeof text !== 'string' || text.length === 0) continue;\n const role = u.sessionUpdate === 'user_message_chunk' ? 'user' : 'assistant';\n state.appendMessage({ role, content: text });\n }\n}\n\n/** Map a WrongStack tool name to the closest ACP ToolKind for UI grouping. */\nfunction toolNameToKind(name: string): ToolKind {\n const n = name.toLowerCase();\n if (n.includes('read') || n.includes('cat')) return 'read';\n if (n.includes('write') || n.includes('edit') || n.includes('apply') || n.includes('patch')) return 'edit';\n if (n.includes('delete') || n.includes('rm')) return 'delete';\n if (n.includes('move') || n.includes('rename') || n.includes('mv')) return 'move';\n if (n.includes('grep') || n.includes('glob') || n.includes('search') || n.includes('find')) return 'search';\n if (n.includes('bash') || n.includes('shell') || n.includes('exec') || n.includes('run') || n.includes('terminal')) return 'execute';\n if (n.includes('fetch') || n.includes('http') || n.includes('web') || n.includes('url')) return 'fetch';\n if (n.includes('think') || n.includes('plan')) return 'think';\n return 'other';\n}\n\n/** A short, human-readable title for a tool call card. */\nfunction toolTitle(name: string, input: unknown): string {\n if (isRecord(input)) {\n const path = input.path ?? input.file ?? input.filePath ?? input.pattern ?? input.command;\n if (typeof path === 'string' && path.length > 0) {\n return `${name}: ${path.length > 80 ? `${path.slice(0, 77)}\u2026` : path}`;\n }\n }\n return name;\n}\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\n/**\n * Convert an ACP `ContentBlock[]` prompt into a core `AgentInput`.\n *\n * When the prompt is all text we return a plain string (the common,\n * cheapest path). When it carries images we build a multimodal\n * `ContentBlock[]` the provider can pass to a vision-capable model.\n * Audio and resource blocks have no core representation yet, so they're\n * recorded as bracketed text placeholders alongside the other content.\n */\nfunction promptToAgentInput(blocks: readonly ContentBlock[]): AgentInput {\n const hasImage = blocks.some((b) => b.type === 'image');\n if (!hasImage) {\n return promptToText(blocks);\n }\n const out: AgentInput = [];\n for (const b of blocks) {\n if (b.type === 'text') {\n out.push({ type: 'text', text: b.text });\n } else if (b.type === 'image') {\n out.push({\n type: 'image',\n source: { type: 'base64', media_type: b.mimeType, data: b.data },\n });\n } else if (b.type === 'audio') {\n out.push({ type: 'text', text: `[audio: ${b.mimeType}]` });\n } else if (b.type === 'resource') {\n const text =\n 'text' in b.resource && typeof b.resource.text === 'string'\n ? b.resource.text\n : `[embedded resource: ${b.resource.uri}]`;\n out.push({ type: 'text', text });\n } else if (b.type === 'resource_link') {\n out.push({ type: 'text', text: `[resource link: ${b.uri}]` });\n }\n }\n return out;\n}\n\n/**\n * Tear down the agents and timers held by a turn factory. The\n * server's `close()` should call this so child connections don't\n * outlive the server.\n */\nexport function disposeACPServerAgentTurn(\n opts: { agents: Map<string, Agent> },\n): Promise<void> {\n return Promise.allSettled(\n Array.from(opts.agents.values()).map((agent) => agent.teardown()),\n ).then(() => undefined);\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Helpers\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Convert an ACP `ContentBlock[]` prompt to a single user-message\n * string. Text blocks are concatenated; image / audio / resource\n * blocks are recorded as a bracketed placeholder (full multimodal\n * support is a future PR \u2014 the adapter is v1-text only for now).\n */\nfunction promptToText(blocks: readonly ContentBlock[]): string {\n const parts: string[] = [];\n for (const b of blocks) {\n if (b.type === 'text') {\n parts.push(b.text);\n } else if (b.type === 'image') {\n parts.push(`[image: ${b.mimeType}]`);\n } else if (b.type === 'audio') {\n parts.push(`[audio: ${b.mimeType}]`);\n } else if (b.type === 'resource') {\n parts.push(`[embedded resource: ${b.resource.uri}]`);\n } else if (b.type === 'resource_link') {\n parts.push(`[resource link: ${b.uri}]`);\n }\n }\n return parts.join('\\n').trim();\n}\n\n/**\n * Extract the agent's final text from a `RunResult`. The shape\n * varies across core versions, so we read the most common fields\n * defensively and concatenate whatever text we find.\n */\nfunction extractText(result: unknown): string {\n if (typeof result !== 'object' || result === null) return '';\n const r = result as Record<string, unknown>;\n // v1: result.text is the agent's final text (string).\n if (typeof r.text === 'string') return r.text;\n // Legacy: result.content is an array of blocks.\n if (Array.isArray(r.content)) {\n const parts: string[] = [];\n for (const c of r.content) {\n if (typeof c === 'object' && c !== null) {\n const cb = c as { type?: string; text?: unknown };\n if (cb.type === 'text' && typeof cb.text === 'string') parts.push(cb.text);\n }\n }\n return parts.join('');\n }\n return '';\n}\n\n/**\n * Map a `RunResult` (and the parent signal) to a v1 `StopReason`.\n *\n * If the parent signal was aborted, return `'cancelled'`. Otherwise\n * the agent completed normally \u2014 we treat any non-error result\n * as `'end_turn'`. The core `RunResult` doesn't currently surface\n * a per-turn stop reason, so v1's `'max_tokens'`, `'max_turn_requests'`,\n * and `'refusal'` discriminators can't be emitted precisely; we\n * log a warning if the result carries an error and return the\n * generic end_turn.\n */\nfunction pickStopReason(result: unknown, signal: AbortSignal): StopReason {\n if (signal.aborted) return 'cancelled';\n if (typeof result !== 'object' || result === null) return 'end_turn';\n const r = result as { error?: unknown; stopReason?: unknown };\n if (r.error) {\n return 'end_turn';\n }\n if (typeof r.stopReason === 'string' && r.stopReason) {\n return r.stopReason as StopReason;\n }\n return 'end_turn';\n}\n\n/**\n * Extract a plan from the agent's RunResult, if available.\n * The plan is an array of PlanEntry objects.\n */\nfunction extractPlan(result: unknown): PlanEntry[] {\n if (typeof result !== 'object' || result === null) return [];\n const r = result as Record<string, unknown>;\n if (Array.isArray(r.plan)) {\n // Agent provided a plan array\n return r.plan.filter(\n (e: unknown) =>\n typeof e === 'object' && e !== null && typeof (e as { content?: unknown }).content === 'string',\n ) as PlanEntry[];\n }\n return [];\n}\n\n/**\n * Extract usage/token info from the agent's RunResult, if available.\n */\nfunction extractUsage(\n result: unknown,\n): { used: number; size: number; cost?: UsageCost | undefined } | null {\n if (typeof result !== 'object' || result === null) return null;\n const r = result as Record<string, unknown>;\n if (typeof r.usage === 'object' && r.usage !== null) {\n const u = r.usage as { used?: unknown; size?: unknown; cost?: unknown };\n if (typeof u.used === 'number' && typeof u.size === 'number') {\n return {\n used: u.used,\n size: u.size,\n ...(typeof u.cost === 'object' && u.cost !== null ? { cost: u.cost as UsageCost } : {}),\n };\n }\n }\n return null;\n}\n", "/**\n * ACPSessionStore \u2014 persistent session storage for the ACP server.\n *\n * Sessions are saved as JSON files in a configurable directory.\n * This enables session/load to work across server restarts.\n *\n * Format: one JSON file per session, named `<sessionId>.json`.\n */\nimport * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport type { SessionState } from './protocol-handler.js';\n\n/** A persisted conversation turn (user/agent message chunk) for replay. */\nexport interface PersistedHistoryUpdate {\n sessionUpdate: string;\n content: unknown;\n}\n\n/** A persisted session: metadata + replayable conversation history. */\nexport interface PersistedSession extends Partial<SessionState> {\n history?: PersistedHistoryUpdate[] | undefined;\n}\n\nexport interface SessionStoreOptions {\n /** Directory to store session files. Defaults to a temp dir. */\n dir?: string | undefined;\n}\n\nexport class ACPSessionStore {\n private readonly dir: string;\n /**\n * Memoized result of the first successful `init()`. Saved sessions\n * are the hot path \u2014 calling `mkdir(..., {recursive:true})` on every\n * turn adds an avoidable syscall to the per-prompt persistence flow.\n * Cleared automatically if the directory disappears between calls.\n */\n private initialized = false;\n\n constructor(opts: SessionStoreOptions = {}) {\n this.dir = opts.dir ?? path.join(process.cwd(), '.acp-sessions');\n }\n\n /** Ensure the store directory exists. Memoized \u2014 only mkdirs once. */\n async init(): Promise<void> {\n if (this.initialized) return;\n await fsp.mkdir(this.dir, { recursive: true });\n this.initialized = true;\n }\n\n /**\n * Persist a session state (and optionally its conversation history) to\n * disk. Returns the session id. `history` enables cross-restart\n * `session/load` replay.\n */\n async save(state: SessionState, history?: PersistedHistoryUpdate[]): Promise<string> {\n await this.init();\n await fsp.writeFile(\n path.join(this.dir, `${state.id}.json`),\n JSON.stringify({\n id: state.id,\n cwd: state.cwd,\n modeId: state.modeId,\n createdAt: state.createdAt,\n updatedAt: state.updatedAt,\n title: state.title,\n ...(history && history.length > 0 ? { history } : {}),\n }),\n 'utf8',\n );\n await this.updateIndex(state.id, state.updatedAt);\n return state.id;\n }\n\n /** Load a persisted session (metadata + history) from disk, or null. */\n async load(sessionId: string): Promise<PersistedSession | null> {\n try {\n const data = await fsp.readFile(path.join(this.dir, `${sessionId}.json`), 'utf8');\n return JSON.parse(data) as PersistedSession;\n } catch {\n return null;\n }\n }\n\n /** List all persisted sessions. */\n async list(): Promise<Array<{ id: string; updatedAt: string }>> {\n // Fast path: read the small sidecar index instead of every session\n // file. Rebuilds on first call if the index is missing or stale.\n const indexEntries = await this.readIndex();\n if (indexEntries !== null) {\n return indexEntries.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));\n }\n // Slow path fallback: scan the directory, parse each file, then\n // rebuild the index for next time. Same external contract as before.\n const files: string[] = [];\n try {\n const entries = await fsp.readdir(this.dir);\n for (const entry of entries) {\n if (entry.endsWith('.json') && entry !== 'index.json') {\n files.push(entry);\n }\n }\n } catch {\n return [];\n }\n\n const sessions: Array<{ id: string; updatedAt: string }> = [];\n for (const file of files) {\n try {\n const data = await fsp.readFile(path.join(this.dir, file), 'utf8');\n const parsed = JSON.parse(data) as { id?: string; updatedAt?: string };\n if (parsed.id) {\n sessions.push({ id: parsed.id, updatedAt: parsed.updatedAt ?? '' });\n }\n } catch {\n // Corrupted file \u2014 skip\n }\n }\n sessions.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));\n // Best-effort rebuild; failure to write the index does not affect\n // the returned list.\n void this.writeIndex(sessions).catch(() => undefined);\n return sessions;\n }\n\n /** Sidecar path that stores `{id, updatedAt}` for every saved session. */\n private indexPath(): string {\n return path.join(this.dir, 'index.json');\n }\n\n /** Read the sidecar index. Returns `null` when missing or unreadable. */\n private async readIndex(): Promise<Array<{ id: string; updatedAt: string }> | null> {\n try {\n const data = await fsp.readFile(this.indexPath(), 'utf8');\n const parsed = JSON.parse(data);\n if (!Array.isArray(parsed)) return null;\n const out: Array<{ id: string; updatedAt: string }> = [];\n for (const e of parsed) {\n if (\n e &&\n typeof (e as { id?: unknown }).id === 'string' &&\n typeof (e as { updatedAt?: unknown }).updatedAt === 'string'\n ) {\n out.push({\n id: (e as { id: string }).id,\n updatedAt: (e as { updatedAt: string }).updatedAt,\n });\n }\n }\n return out;\n } catch {\n return null;\n }\n }\n\n /** Atomically replace the sidecar index with the supplied entries. */\n private async writeIndex(entries: Array<{ id: string; updatedAt: string }>): Promise<void> {\n const target = this.indexPath();\n const tmp = `${target}.${process.pid}.${Date.now()}.tmp`;\n await fsp.writeFile(tmp, JSON.stringify(entries), 'utf8');\n await fsp.rename(tmp, target);\n }\n\n /** Update one entry in the index, adding it if missing. Best-effort. */\n private async updateIndex(id: string, updatedAt: string): Promise<void> {\n const entries = await this.readIndex();\n if (entries === null) {\n // No index yet \u2014 fall back to a full scan to populate it.\n await this.list();\n return;\n }\n const i = entries.findIndex((e) => e.id === id);\n if (i >= 0) entries[i] = { id, updatedAt };\n else entries.push({ id, updatedAt });\n try {\n await this.writeIndex(entries);\n } catch {\n // Index is best-effort; per-session file is the source of truth.\n }\n }\n\n /** Delete a session file. */\n async delete(sessionId: string): Promise<void> {\n try {\n await fsp.unlink(path.join(this.dir, `${sessionId}.json`));\n } catch {\n // File may not exist \u2014 ignore\n }\n // Best-effort: drop the entry from the sidecar index so future\n // `list()` calls don't return a stale row.\n const entries = await this.readIndex();\n if (entries === null) return;\n const next = entries.filter((e) => e.id !== sessionId);\n if (next.length !== entries.length) {\n try {\n await this.writeIndex(next);\n } catch {\n // Index is best-effort; next list() rebuild will fix it.\n }\n }\n }\n\n /** Get the store directory path. */\n getDirectory(): string {\n return this.dir;\n }\n}\n", "/**\n * Static catalog of ACP-supporting agents known to WrongStack.\n *\n * Scope: CLI-spawnable agents only (i.e. agents that can be run as a\n * subprocess with stdio JSON-RPC, per the ACP v1 spec's local-transport\n * model). IDE-only or SaaS-only entries from\n * https://agentclientprotocol.com/get-started/agents are deliberately\n * omitted \u2014 they can't be driven by a SubagentRunner.\n *\n * Maintenance\n * \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n * This is the OFFLINE FALLBACK catalog. The official, hourly-updated registry\n * now lives at https://github.com/agentclientprotocol/registry (CDN snapshot\n * in `acp-registry-fetch.ts`). `wstack acp sync` / `/acp sync` fetch it into a\n * local cache that supersedes this file at resolution time \u2014 so this catalog\n * only needs to carry the most-used agents with invocations that work without\n * a network round-trip. Entries here are kept aligned to the registry's\n * authoritative ACP-entry commands; run `/acp probe` to confirm on a host.\n *\n * Each entry tags its `integration` mechanism:\n * - `native` \u2014 the agent ships with a documented ACP entry flag.\n * - `adapter` \u2014 runs through Zed's SDK adapter or similar wrapper.\n * - `community` \u2014 community-maintained wrapper (e.g. `@agentify/cline`,\n * `bub-acp-server`, `pi-acp`).\n * - `experimental` \u2014 listed by ACP but no public ACP entry yet;\n * entry may not work.\n *\n * When the maintainer verifies an entry works, flip `integration` from\n * `experimental` to `native`/`adapter`/`community` and remove the warning.\n *\n * Detection\n * \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n * The `EnsembleRegistry` (sibling module) probes each entry's `probe`\n * argv in parallel via `Promise.allSettled`. A probe that exits 0 with\n * a non-empty stdout line is considered installed. Probes that time out\n * or print nothing are treated as not-installed.\n */\nimport type { ACPAgentDescriptor } from './ensemble-registry.js';\n\n/**\n * The catalog. Order is significant for the TUI render \u2014 most-requested\n * agents go first. Edit by re-ordering, not by alphabetising.\n */\nexport const AGENTS_CATALOG: readonly ACPAgentDescriptor[] = [\n // \u2500\u2500 Anthropic \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n id: 'claude-code',\n displayName: 'Claude Code',\n vendor: 'anthropic',\n probe: { command: 'claude', args: ['--version'] },\n // Claude Code does not speak stdio ACP from the bare `claude` binary \u2014\n // it drops into its interactive TUI. The official ACP adapter\n // (`@agentclientprotocol/claude-agent-acp`, registry id `claude-acp`)\n // wraps the logged-in Claude Code CLI and translates ACP \u2194 Claude Code.\n // Verify with `/acp probe claude-code`; override via `config.acp.agents`.\n acp: { command: 'npx', args: ['-y', '@agentclientprotocol/claude-agent-acp'] },\n supports: {\n loadSession: true,\n promptImages: true,\n terminal: true,\n fs: true,\n },\n integration: 'adapter',\n docs: 'https://docs.anthropic.com/en/docs/claude-code',\n },\n\n // \u2500\u2500 Google \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n id: 'gemini-cli',\n displayName: 'Gemini CLI',\n vendor: 'google',\n probe: { command: 'gemini', args: ['--version'] },\n // Gemini CLI (the @google/gemini-cli package, registry id `gemini`)\n // speaks ACP behind `--acp`. We invoke the locally-installed binary so it\n // uses the user's existing login. Confirm with `/acp probe gemini-cli`.\n acp: { command: 'gemini', args: ['--acp'] },\n supports: {\n loadSession: true,\n promptImages: true,\n terminal: true,\n fs: true,\n },\n integration: 'native',\n docs: 'https://github.com/google-gemini/gemini-cli',\n },\n\n // \u2500\u2500 OpenAI \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n id: 'codex-cli',\n displayName: 'Codex CLI',\n vendor: 'openai',\n probe: { command: 'codex', args: ['--version'] },\n // Bare `codex` has no stdio-ACP entry; the official adapter\n // (`@agentclientprotocol/codex-acp`, registry id `codex-acp`) wraps the\n // logged-in Codex CLI. Confirm with `/acp probe codex-cli`.\n acp: { command: 'npx', args: ['-y', '@agentclientprotocol/codex-acp'] },\n supports: {\n loadSession: false,\n promptImages: false,\n terminal: true,\n fs: true,\n },\n integration: 'adapter',\n docs: 'https://github.com/openai/codex',\n },\n\n // \u2500\u2500 GitHub \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n id: 'copilot',\n displayName: 'GitHub Copilot CLI',\n vendor: 'github',\n probe: { command: 'gh', args: ['copilot', '--help'] },\n // ACP is in the standalone @github/copilot CLI (registry id\n // `github-copilot-cli`), not the `gh copilot` extension. Use the package.\n acp: { command: 'npx', args: ['-y', '@github/copilot', '--acp'] },\n supports: {\n loadSession: false,\n promptImages: false,\n terminal: true,\n fs: false,\n },\n integration: 'experimental',\n docs: 'https://github.com/features/copilot/cli',\n },\n\n // \u2500\u2500 Community / wrappers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n id: 'cline',\n displayName: 'Cline',\n vendor: 'community',\n probe: { command: 'npx', args: ['--version'] },\n // Registry id `cline`: the `cline` npm package speaks ACP behind `--acp`.\n acp: {\n command: 'npx',\n args: ['-y', 'cline', '--acp'],\n },\n supports: {\n loadSession: true,\n promptImages: true,\n terminal: true,\n fs: true,\n },\n integration: 'community',\n docs: 'https://github.com/cline/cline',\n },\n {\n id: 'goose',\n displayName: 'Goose',\n vendor: 'community',\n probe: { command: 'goose', args: ['--version'] },\n acp: { command: 'goose', args: ['acp'] },\n supports: {\n loadSession: true,\n promptImages: true,\n terminal: true,\n fs: true,\n },\n integration: 'experimental',\n docs: 'https://github.com/block/goose',\n },\n {\n id: 'openhands',\n displayName: 'OpenHands',\n vendor: 'community',\n probe: { command: 'openhands', args: ['--version'] },\n acp: { command: 'openhands', args: [] },\n supports: {\n loadSession: false,\n promptImages: true,\n terminal: true,\n fs: true,\n },\n integration: 'experimental',\n // Canonical repo URL \u2014 the org renamed; All-Hands-AI/OpenHands 301-redirects here.\n docs: 'https://github.com/OpenHands/OpenHands',\n },\n\n // \u2500\u2500 Vendor CLIs (native binaries) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n id: 'qwen-code',\n displayName: 'Qwen Code',\n vendor: 'community',\n probe: { command: 'qwen', args: ['--version'] },\n // Qwen Code (the @qwen-code/qwen-code package) speaks ACP behind `--acp`.\n acp: { command: 'qwen', args: ['--acp'] },\n supports: {\n loadSession: false,\n promptImages: false,\n terminal: true,\n fs: false,\n },\n integration: 'experimental',\n docs: 'https://github.com/QwenLM/Qwen3-Coder',\n },\n {\n id: 'kiro-cli',\n displayName: 'Kiro CLI',\n vendor: 'community',\n probe: { command: 'kiro', args: ['--version'] },\n acp: { command: 'kiro', args: [] },\n supports: {\n loadSession: false,\n promptImages: false,\n terminal: true,\n fs: true,\n },\n integration: 'experimental',\n docs: 'https://kiro.dev',\n },\n {\n id: 'opencode',\n displayName: 'OpenCode',\n vendor: 'community',\n probe: { command: 'opencode', args: ['--version'] },\n // OpenCode speaks ACP via its `acp` subcommand (registry id `opencode`).\n acp: { command: 'opencode', args: ['acp'] },\n supports: {\n loadSession: true,\n promptImages: true,\n terminal: true,\n fs: true,\n },\n integration: 'native',\n docs: 'https://github.com/sst/opencode',\n },\n {\n id: 'mistral-vibe',\n displayName: 'Mistral Vibe',\n vendor: 'community',\n probe: { command: 'vibe', args: ['--version'] },\n acp: { command: 'vibe', args: [] },\n supports: {\n loadSession: false,\n promptImages: false,\n terminal: true,\n fs: false,\n },\n integration: 'experimental',\n docs: 'https://github.com/mistralai/mistral-vibe',\n },\n {\n id: 'cursor',\n displayName: 'Cursor',\n vendor: 'community',\n probe: { command: 'cursor', args: ['--version'] },\n // Cursor's ACP entry is the `cursor-agent acp` binary (registry id `cursor`).\n acp: { command: 'cursor-agent', args: ['acp'] },\n supports: {\n loadSession: true,\n promptImages: true,\n terminal: true,\n fs: true,\n },\n integration: 'experimental',\n docs: 'https://cursor.com',\n },\n // \u2500\u2500 Moonshot AI (Kimi) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n {\n id: 'kimi',\n displayName: 'Kimi Code CLI',\n vendor: 'moonshot',\n probe: { command: 'kimi', args: ['--version'] },\n // Kimi Code CLI speaks ACP behind `kimi acp`. The user must complete\n // terminal login (`kimi` \u2192 `/login`) before launching `kimi acp`;\n // otherwise session creation fails with `Authentication required`.\n // The adapter reuses the CLI's existing auth state \u2014 WrongStack does\n // NOT capture or replay the Kimi OAuth tokens.\n // Docs: https://www.kimi.com/code/docs/en/kimi-code-cli/reference/kimi-acp.html\n acp: { command: 'kimi', args: ['acp'] },\n supports: {\n loadSession: true,\n promptImages: true,\n terminal: true,\n fs: true,\n },\n integration: 'native',\n docs: 'https://www.kimi.com/code/docs/en/kimi-code-cli/guides/ides.html',\n },\n] as const;\n\n/** O(1) lookup by id. Returns `undefined` for unknown ids. */\nexport function findAgentDescriptor(\n id: string,\n): ACPAgentDescriptor | undefined {\n return AGENTS_CATALOG.find((a) => a.id === id);\n}\n", "/**\n * One-shot ACP task runner, split out of acp-subagent-runner.ts so the\n * `client` entry (which only needs `makeACPSubagentRunner`) doesn't bundle\n * the SubagentBudget machinery. This is the shared engine behind\n * `wstack acp spawn` and `/acp <id> <task>`.\n */\nimport type { SubagentRunContext } from '@wrongstack/core';\nimport { SubagentBudget } from '@wrongstack/core/coordination';\nimport type { ACPProgressHandler } from '../client/acp-session.js';\nimport type { PermissionPolicy } from '../client/permission.js';\nimport { makeACPSubagentRunnerWithStop } from './acp-subagent-runner.js';\n\nexport interface RunOneAcpTaskOptions {\n command: string;\n args?: string[] | undefined;\n env?: Record<string, string> | undefined;\n /** Agent id / role label, surfaced in errors + the synthetic task id. */\n role?: string | undefined;\n /** The task description forwarded verbatim to the agent. */\n task: string;\n cwd?: string | undefined;\n projectRoot?: string | undefined;\n timeoutMs?: number | undefined;\n signal?: AbortSignal | undefined;\n onProgress?: ACPProgressHandler | undefined;\n permissionPolicy?: PermissionPolicy | undefined;\n}\n\nexport interface RunOneAcpTaskResult {\n result: string;\n iterations: number;\n toolCalls: number;\n}\n\n/**\n * Run a single task on one ACP agent and return its result. Spawns a fresh\n * process, runs one prompt turn, and tears everything down. Throws a\n * structured `SubagentError` on failure (spawn/init/prompt).\n */\nexport async function runOneAcpTask(\n opts: RunOneAcpTaskOptions,\n): Promise<RunOneAcpTaskResult> {\n const role = opts.role ?? 'acp';\n const timeoutMs = opts.timeoutMs ?? 5 * 60_000;\n const { runner, stop } = await makeACPSubagentRunnerWithStop({\n command: opts.command,\n ...(opts.args !== undefined ? { args: opts.args } : {}),\n ...(opts.env !== undefined ? { env: opts.env } : {}),\n ...(opts.cwd !== undefined ? { cwd: opts.cwd } : {}),\n ...(opts.projectRoot !== undefined ? { projectRoot: opts.projectRoot } : {}),\n role,\n timeoutMs,\n ...(opts.onProgress !== undefined ? { onProgress: opts.onProgress } : {}),\n ...(opts.permissionPolicy !== undefined ? { permissionPolicy: opts.permissionPolicy } : {}),\n });\n try {\n const budget = new SubagentBudget({\n timeoutMs,\n maxIterations: 2000,\n maxToolCalls: 5000,\n });\n budget.start();\n const ctx: SubagentRunContext = {\n subagentId: role,\n config: { id: role, name: role, role, provider: 'acp', prompt: '' },\n budget,\n signal: opts.signal ?? new AbortController().signal,\n bridge: null,\n };\n const result = await runner({ id: `acp-${role}`, description: opts.task }, ctx);\n return {\n result: result.result == null ? '' : String(result.result),\n iterations: result.iterations,\n toolCalls: result.toolCalls,\n };\n } finally {\n try {\n await stop();\n } catch {\n // best-effort teardown\n }\n }\n}\n", "/**\n * ACPSubagentRunner \u2014 `SubagentRunner` implementation for DIR-1.\n *\n * Wraps an external ACP-supporting agent (Claude Code, Gemini CLI, Codex\n * CLI, Cline, Goose, OpenHands, etc.) as a WrongStack subagent. The\n * external agent runs its own agent loop; we send it a task via the ACP\n * v1 protocol and return the result.\n *\n * v1 spec: https://agentclientprotocol.com/protocol/v1/overview\n *\n * Connected to the Director / MultiAgentCoordinator via the\n * `SubagentRunner` interface (same shape as `AgentSubagentRunner`).\n */\nimport type {\n SubagentError,\n SubagentErrorKind,\n SubagentRunContext,\n SubagentRunOutcome,\n SubagentRunner,\n TaskSpec,\n} from '@wrongstack/core';\nimport {\n ACPSession,\n ACPSessionError,\n textContent,\n type ACPProgressEvent,\n type ACPProgressHandler,\n} from '../client/acp-session.js';\nimport type { ACPSessionErrorKind } from '../client/acp-session.js';\nimport type { PermissionPolicy } from '../client/permission.js';\nimport { findAgentDescriptor } from '../registry/agents.catalog.js';\nimport type { McpServer } from '../types/acp-v1.js';\n\nexport interface ACPSubagentRunnerOptions {\n /** How to spawn the external agent. */\n command: string;\n args?: string[] | undefined;\n env?: Record<string, string> | undefined;\n cwd?: string | undefined;\n /** Subagent role label \u2014 surfaced in errors and used for logging. */\n role?: string | undefined;\n /**\n * Hard wall-clock cap for one prompt turn. Defaults to 5 minutes.\n * Overrides `SubagentRunContext.budget.limits.timeoutMs` if both are set.\n */\n timeoutMs?: number | undefined;\n /**\n * Filesystem sandbox root. Defaults to `options.cwd` (when set) or\n * the process's current working directory. All `fs/read_text_file` /\n * `fs/write_text_file` calls are bounded to this root.\n */\n projectRoot?: string | undefined;\n /**\n * Live progress callback. Forwarded to `ACPSession.prompt` so the host\n * can render the external agent's tool calls / diffs / text as they\n * stream, instead of waiting for the buffered final result.\n */\n onProgress?: ACPProgressHandler | undefined;\n /**\n * Permission policy for the external agent's `session/request_permission`\n * calls. Defaults to the session's own default. Inject the host's\n * confirm/trust UI here so an external agent's file writes / commands\n * are surfaced to a human instead of silently auto-approved.\n */\n permissionPolicy?: PermissionPolicy | undefined;\n /**\n * MCP servers to expose to the external agent (passed through\n * `session/new` / `session/load`). Stdio servers are always sent;\n * HTTP/SSE are filtered by the agent's advertised capabilities.\n */\n mcpServers?: McpServer[] | undefined;\n /**\n * When true, the underlying `ACPSession` is kept open across multiple\n * runner invocations (multi-turn conversation \u2014 the external agent\n * keeps its context). The caller MUST call `stop()` to tear it down.\n * Defaults to false (one process per task).\n */\n persistent?: boolean | undefined;\n}\n\n/**\n * Static catalog of agent ids \u2192 spawn options.\n *\n * The CLI and the host's `buildACPRunner` look up entries by id. The\n * canonical, multi-source catalog is `packages/acp/src/registry/agents.catalog.ts`\n * (the 12-entry static catalog introduced in commit 4ad287b4). This\n * map stays for backward compatibility with existing call sites that\n * import it directly; new code should prefer the registry.\n */\nexport const ACP_AGENT_COMMANDS: Record<string, ACPSubagentRunnerOptions> = {\n cline: {\n command: 'npx',\n args: ['-y', '@agentify/cline'],\n role: 'cline',\n },\n 'gemini-cli': {\n command: 'gemini',\n role: 'gemini-cli',\n },\n copilot: {\n command: 'gh',\n args: ['copilot', 'agent'],\n role: 'copilot',\n },\n openhands: {\n command: 'openhands',\n role: 'openhands',\n },\n goose: {\n command: 'goose',\n role: 'goose',\n },\n};\n\n/**\n * Build a one-shot `SubagentRunner` for a single agent invocation. Each\n * call to the returned function spawns a fresh child process, runs one\n * prompt turn, and tears everything down. The cost is ~1 second of\n * process-startup per call; for long-lived sessions (multi-turn\n * conversations), use `makeACPSubagentRunnerWithStop` and call `stop()`\n * explicitly.\n */\nexport async function makeACPSubagentRunner(\n options: ACPSubagentRunnerOptions,\n): Promise<SubagentRunner> {\n const { runner, stop } = await makeACPSubagentRunnerWithStop(options);\n // Wrap so we always tear down after the turn, even if the caller\n // forgot to call `stop()`. stop() is idempotent, so a double-call is\n // safe.\n const wrappedRunner: SubagentRunner = async (task, ctx) => {\n try {\n return await runner(task, ctx);\n } finally {\n stop();\n }\n };\n return wrappedRunner;\n}\n\n/**\n * Build a long-lived `SubagentRunner` plus an explicit `stop()` for\n * teardown. The caller is responsible for calling `stop()` when done\n * (or when the host's signal fires). Useful for the `wstack acp spawn`\n * CLI command, which holds the child open for the duration of a user\n * task and tears down on SIGINT.\n */\nexport async function makeACPSubagentRunnerWithStop(\n options: ACPSubagentRunnerOptions,\n): Promise<{ runner: SubagentRunner; stop: () => void | Promise<void> }> {\n const projectRoot = options.projectRoot ?? options.cwd ?? process.cwd();\n const timeoutMs = options.timeoutMs ?? 5 * 60_000;\n const persistent = options.persistent === true;\n\n // In persistent mode we keep a single session alive across runner calls\n // so the external agent retains its conversation context (multi-turn).\n let shared: ACPSession | null = null;\n\n const startSession = async (): Promise<ACPSession> => {\n return ACPSession.start({\n command: options.command,\n ...(options.args !== undefined ? { args: options.args } : {}),\n ...(options.env !== undefined ? { env: options.env } : {}),\n ...(options.cwd !== undefined ? { cwd: options.cwd } : {}),\n projectRoot,\n timeoutMs,\n role: options.role,\n ...(options.permissionPolicy !== undefined\n ? { permissionPolicy: options.permissionPolicy }\n : {}),\n ...(options.mcpServers !== undefined ? { mcpServers: options.mcpServers } : {}),\n });\n };\n\n const runner: SubagentRunner = async (\n task: TaskSpec,\n ctx: SubagentRunContext,\n ): Promise<SubagentRunOutcome> => {\n let session: ACPSession;\n const reuse = persistent && shared !== null;\n try {\n session = reuse ? (shared as ACPSession) : await startSession();\n if (persistent) shared = session;\n } catch (err) {\n // init / spawn failure. Throw a structured error so the host can\n // classify it (SubagentErrorKind).\n throw acpErrorToSubagentError(err, options.role ?? 'acp-subagent');\n }\n\n // Count real tool calls from the captured stream, and keep the\n // budget's idle clock fresh on every update so a long-but-working\n // external agent is never reaped by the watchdog as \"stalled\".\n const onProgress: ACPProgressHandler = (event: ACPProgressEvent) => {\n try {\n ctx.budget.markActivity();\n } catch {\n // markActivity never throws today; guard defensively anyway.\n }\n options.onProgress?.(event);\n };\n\n try {\n const result = await session.prompt(\n [textContent(task.description)],\n ctx.signal,\n onProgress,\n );\n // Surface the real tool-call count captured from the stream. A\n // text-less turn is a soft signal (an ACP agent may legitimately\n // end with no message), not an error.\n return {\n result: result.text,\n iterations: 1,\n toolCalls: result.toolCalls.length,\n };\n } catch (err) {\n throw acpErrorToSubagentError(err, options.role ?? 'acp-subagent');\n } finally {\n // One-shot mode closes after each turn. Persistent mode keeps the\n // session open; the caller tears it down via stop().\n if (!persistent) {\n try {\n await session.close();\n } catch {\n // best-effort cleanup\n }\n }\n }\n };\n\n // In persistent mode stop() closes the long-lived session; in one-shot\n // mode it's a no-op (each session is closed in the runner's finally).\n const stop = async (): Promise<void> => {\n if (shared) {\n const s = shared;\n shared = null;\n try {\n await s.close();\n } catch {\n // best-effort\n }\n }\n };\n\n return { runner, stop };\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Error mapping\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Map an ACPSessionError (or arbitrary Error from the session layer)\n * to a structured `SubagentError` that the existing coordinator can\n * classify and act on. Unknown error shapes get `kind: 'unknown'` \u2014\n * they shouldn't crash the parent.\n */\nfunction acpErrorToSubagentError(\n err: unknown,\n subagentId: string,\n): SubagentError {\n if (err instanceof ACPSessionError) {\n const kind = mapACPKind(err.kind);\n return {\n kind,\n message: `${subagentId}: ${err.message}`,\n retryable: isRetryable(kind),\n cause: {\n name: err.name,\n message: err.message,\n ...(err.stack !== undefined ? { stack: err.stack } : {}),\n },\n };\n }\n const message = err instanceof Error ? err.message : String(err);\n return {\n kind: 'bridge_failed',\n message: `${subagentId}: ${message}`,\n retryable: false,\n cause: {\n name: err instanceof Error ? err.name : 'Error',\n message,\n ...(err instanceof Error && err.stack !== undefined ? { stack: err.stack } : {}),\n },\n };\n}\n\nfunction mapACPKind(acpKind: ACPSessionErrorKind): SubagentErrorKind {\n switch (acpKind) {\n case 'spawn_failed':\n case 'init_failed':\n case 'session_create_failed':\n case 'agent_died':\n case 'protocol_error':\n return 'bridge_failed';\n case 'prompt_failed':\n return 'tool_failed';\n case 'auth_failed':\n case 'logout_failed':\n return 'bridge_failed';\n case 'aborted':\n return 'aborted_by_parent';\n case 'closed':\n case 'unsupported_capability':\n return 'unknown';\n }\n}\n\nfunction isRetryable(kind: SubagentErrorKind): boolean {\n // Conservative: spawn / init / protocol / agent-died are NOT\n // retryable as-is (they need config or a re-install). Timeouts and\n // prompt failures might be \u2014 the parent's classifier will branch on\n // `kind` and decide.\n switch (kind) {\n case 'provider_5xx':\n case 'provider_rate_limit':\n case 'provider_timeout':\n case 'tool_threw':\n case 'budget_timeout':\n return true;\n default:\n return false;\n }\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Unused but exported for future use\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Re-export so the CLI handler can import the session type. */\nexport type { ACPSession };\n\n/** Exposed for the `wstack acp list` renderer. */\nexport function describeAgent(id: string): {\n command: string;\n args: readonly string[];\n role: string;\n} | null {\n const entry = ACP_AGENT_COMMANDS[id];\n if (!entry) return null;\n return {\n command: entry.command,\n args: entry.args ?? [],\n role: entry.role ?? id,\n };\n}\n\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Shared command resolution + single-task run + handshake probe\n//\n// These are the building blocks both the `wstack acp` CLI handler and the\n// `/acp` slash command consume, so the two surfaces stay in lock-step.\n// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Per-agent ACP invocation overrides, sourced from the user's\n * `~/.wrongstack/config.json` (`config.acp.agents`). Lets a user point an\n * agent id at the correct ACP entry \u2014 e.g. the Zed Claude-Code adapter \u2014\n * without a code change. NEVER honoured from in-project config (it is an\n * arbitrary-command exec surface); see `config-loader.ts`.\n */\nexport type AcpAgentCommandOverrides = Record<\n string,\n { command: string; args?: string[]; env?: Record<string, string> }\n>;\n\n/** A synced-registry catalog keyed by registry id (from `fetchAcpRegistry`). */\nexport type AcpLiveCatalog = Record<\n string,\n { command: string; args?: readonly string[]; env?: Record<string, string> }\n>;\n\n/**\n * Map our stable, human-friendly catalog ids to the official registry's ids,\n * so a live-synced registry (keyed by registry id) still resolves when the\n * user types our id. Our id is preferred in the UI; the alias is the bridge.\n */\nexport const REGISTRY_ID_ALIASES: Readonly<Record<string, string>> = {\n 'claude-code': 'claude-acp',\n 'gemini-cli': 'gemini',\n 'codex-cli': 'codex-acp',\n copilot: 'github-copilot-cli',\n // Kimi's live registry id is `kimi` \u2014 same as our catalog id, so the\n // alias is identity. Listed explicitly so `resolveAcpAgentCommand`\n // finds the live entry when the registry is synced.\n kimi: 'kimi',\n};\n\n/**\n * Resolve an agent id to its spawn command. Precedence:\n * 1. user override (`config.acp.agents[id]`)\n * 2. the bundled static `AGENTS_CATALOG` (curated LOCAL-binary invocations)\n * 3. live synced registry (`fetchAcpRegistry` \u2192 cache), by id or alias\n * 4. legacy `ACP_AGENT_COMMANDS` map (last resort, kept for back-compat)\n * Returns `null` for an id present in none of them.\n *\n * Why catalog BEFORE the live registry: our goal is to drive the user's\n * already-installed, logged-in CLI. The catalog hand-curates the LOCAL-binary\n * ACP entry for each popular agent (`gemini --acp`, `opencode acp`, \u2026), which\n * preserves the agent's own login and starts instantly. The official registry,\n * by contrast, encodes \"run a fresh copy\" invocations \u2014 pinned `npx <pkg>@ver`\n * downloads (no local login, slow first run) and platform binaries like\n * `opencode.exe` that may not match a shim on PATH. So the registry is the\n * source for the long tail of agents the catalog doesn't cover, NOT an\n * override of the curated 12. Users force a specific command via the override.\n */\nexport function resolveAcpAgentCommand(\n id: string,\n overrides?: AcpAgentCommandOverrides,\n live?: AcpLiveCatalog,\n): ACPSubagentRunnerOptions | null {\n const ov = overrides?.[id];\n if (ov && typeof ov.command === 'string' && ov.command.length > 0) {\n const out: ACPSubagentRunnerOptions = {\n command: ov.command,\n args: [...(ov.args ?? [])],\n role: id,\n };\n if (ov.env) out.env = ov.env;\n return out;\n }\n const desc = findAgentDescriptor(id);\n if (desc) {\n const out: ACPSubagentRunnerOptions = {\n command: desc.acp.command,\n args: [...(desc.acp.args ?? [])],\n role: id,\n };\n if (desc.acp.env) out.env = desc.acp.env;\n return out;\n }\n const liveEntry = live?.[id] ?? live?.[REGISTRY_ID_ALIASES[id] ?? ''];\n if (liveEntry && typeof liveEntry.command === 'string' && liveEntry.command.length > 0) {\n const out: ACPSubagentRunnerOptions = {\n command: liveEntry.command,\n args: [...(liveEntry.args ?? [])],\n role: id,\n };\n if (liveEntry.env) out.env = liveEntry.env;\n return out;\n }\n const fromMap = ACP_AGENT_COMMANDS[id];\n if (fromMap) return fromMap;\n return null;\n}\n\n// runOneAcpTask lives in run-one-acp-task.ts so the `client` entry (which\n// only re-exports makeACPSubagentRunner from this module) doesn't bundle the\n// SubagentBudget machinery. Re-exported for API compatibility.\nexport {\n runOneAcpTask,\n type RunOneAcpTaskOptions,\n type RunOneAcpTaskResult,\n} from './run-one-acp-task.js';\n\nexport interface AcpProbeResult {\n id: string;\n ok: boolean;\n ms: number;\n agentInfo?: { name: string; title?: string | undefined; version: string } | undefined;\n error?: string | undefined;\n}\n\n/**\n * Empirically test whether an agent actually speaks ACP on this machine:\n * spawn it, run the `initialize` handshake, and close. `ok: true` means the\n * agent answered `initialize` within `timeoutMs` (default 8s) \u2014 the truth,\n * regardless of what the static catalog guesses. A bare CLI that drops into\n * an interactive prompt fails here (init times out) instead of hanging a\n * real turn.\n */\nexport async function probeAcpAgent(\n idOrCmd: string | ACPSubagentRunnerOptions,\n opts?: {\n timeoutMs?: number | undefined;\n projectRoot?: string | undefined;\n overrides?: AcpAgentCommandOverrides | undefined;\n live?: AcpLiveCatalog | undefined;\n },\n): Promise<AcpProbeResult> {\n const id =\n typeof idOrCmd === 'string' ? idOrCmd : (idOrCmd.role ?? idOrCmd.command);\n const cmd =\n typeof idOrCmd === 'string'\n ? resolveAcpAgentCommand(idOrCmd, opts?.overrides, opts?.live)\n : idOrCmd;\n if (!cmd) return { id, ok: false, ms: 0, error: 'unknown agent' };\n\n const timeoutMs = opts?.timeoutMs ?? 8_000;\n const startedAt = Date.now();\n let session: ACPSession | null = null;\n try {\n session = await ACPSession.start({\n command: cmd.command,\n ...(cmd.args !== undefined ? { args: cmd.args } : {}),\n ...(cmd.env !== undefined ? { env: cmd.env } : {}),\n projectRoot: opts?.projectRoot ?? process.cwd(),\n // Bounds the `initialize` request: a CLI that spawns but never answers\n // the handshake fails after this instead of blocking.\n timeoutMs,\n });\n const info = session.getAgentInfo();\n return {\n id,\n ok: true,\n ms: Date.now() - startedAt,\n ...(info ? { agentInfo: info } : {}),\n };\n } catch (err) {\n return {\n id,\n ok: false,\n ms: Date.now() - startedAt,\n error: err instanceof Error ? err.message : String(err),\n };\n } finally {\n if (session) {\n try {\n await session.close();\n } catch {\n // best-effort\n }\n }\n }\n}\n\nexport interface ProbeAcpAgentsOptions {\n agentIds: string[];\n resolveCmd: (id: string) => ACPSubagentRunnerOptions | null;\n projectRoot?: string | undefined;\n /** Max agents probed at once. Default 4. Keeps concurrent first-run `npx`\n * downloads from starving local agents' stdout past their timeout. */\n concurrency?: number | undefined;\n /** Per-agent handshake timeout for LOCAL binary commands. Default 20s. */\n timeoutMs?: number | undefined;\n /** Per-agent timeout for `npx`/`uvx` commands (first run downloads the\n * package, which is slow). Default 90s. */\n packageTimeoutMs?: number | undefined;\n signal?: AbortSignal | undefined;\n onProgress?: ((id: string, result: AcpProbeResult) => void) | undefined;\n}\n\n/**\n * Probe many agents with BOUNDED concurrency. Unbounded `Promise.all` over the\n * full set spawns every agent at once \u2014 and a few concurrent `npx` downloads\n * peg the machine hard enough that even already-installed local agents miss\n * their handshake window. Bounding the fan-out (and giving npx/uvx a longer\n * timeout) is what makes a mixed install probe reliably.\n */\nexport async function probeAcpAgents(\n opts: ProbeAcpAgentsOptions,\n): Promise<AcpProbeResult[]> {\n const localTimeout = opts.timeoutMs ?? 20_000;\n const pkgTimeout = opts.packageTimeoutMs ?? 90_000;\n const ids = opts.agentIds;\n const byId = new Map<string, AcpProbeResult>();\n\n // Partition: local binaries vs npx/uvx package launchers. A first-run `npx`\n // download is heavy enough to starve a LOCAL agent sharing the same batch\n // (its stdout 'data' misses the handshake window \u2192 false timeout). So probe\n // all locals first (clean resources, fast), THEN the package ones \u2014 which\n // are inherently slow on first run \u2014 at low concurrency.\n const local: string[] = [];\n const pkg: string[] = [];\n const cmds = new Map<string, ACPSubagentRunnerOptions | null>();\n for (const id of ids) {\n const cmd = opts.resolveCmd(id);\n cmds.set(id, cmd);\n if (!cmd) continue;\n if (cmd.command === 'npx' || cmd.command === 'uvx') pkg.push(id);\n else local.push(id);\n }\n\n const runPhase = async (phaseIds: string[], concurrency: number, timeoutMs: number): Promise<void> => {\n let next = 0;\n const workerCount = Math.min(Math.max(1, concurrency), Math.max(1, phaseIds.length));\n const workers: Promise<void>[] = [];\n for (let w = 0; w < workerCount; w++) {\n workers.push(\n (async () => {\n while (true) {\n const current = next++;\n if (current >= phaseIds.length) return;\n const id = phaseIds[current]!;\n if (opts.signal?.aborted) {\n byId.set(id, { id, ok: false, ms: 0, error: 'aborted' });\n continue;\n }\n const cmd = cmds.get(id)!;\n const r = await probeAcpAgent(cmd!, {\n timeoutMs,\n ...(opts.projectRoot !== undefined ? { projectRoot: opts.projectRoot } : {}),\n });\n r.id = id; // probeAcpAgent derives id from cmd.role; pin to our id.\n byId.set(id, r);\n opts.onProgress?.(id, r);\n }\n })(),\n );\n }\n await Promise.all(workers);\n };\n\n // Unknown ids resolve to null \u2014 record immediately.\n for (const id of ids) {\n if (cmds.get(id) === null) {\n const r: AcpProbeResult = { id, ok: false, ms: 0, error: 'unknown agent' };\n byId.set(id, r);\n opts.onProgress?.(id, r);\n }\n }\n\n await runPhase(local, opts.concurrency ?? 4, localTimeout);\n // Package launchers run AFTER locals (so npm downloads never starve a local\n // agent's handshake), at low concurrency with a long timeout \u2014 first-run\n // `npx`/`uvx` fetches are inherently slow.\n await runPhase(pkg, 2, pkgTimeout);\n\n // Preserve the caller's input order.\n return ids.map((id) => byId.get(id) ?? { id, ok: false, ms: 0, error: 'not probed' });\n}\n"],
5
- "mappings": ";AAYA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAUP;AAAA,EACE;AAAA,OACK;AAEP;AAAA,EACE;AAAA,OACK;AAMP;AAAA,EACE;AAAA,EACA;AAAA,OACK;;;ACzCP,SAAS,eAAe,gBAAgB;;;ACVxC,IAAM,iBAAiB;AAQhB,SAAS,4BACd,SACA,OAA0B,CAAC,GACH;AACxB,yBAAuB,CAAC,SAAS,GAAG,IAAI,CAAC;AACzC,QAAM,OAAO,CAAC,QAAQ,iBAAiB,OAAO,GAAG,GAAG,KAAK,IAAI,gBAAgB,CAAC,EAAE,KAAK,GAAG;AACxF,SAAO;AAAA,IACL,SAAS,QAAQ,IAAI,SAAS,KAAK;AAAA,IACnC,MAAM,CAAC,MAAM,MAAM,IAAI;AAAA,IACvB,0BAA0B;AAAA,EAC5B;AACF;AAEA,SAAS,uBAAuB,MAAgC;AAC9D,aAAW,OAAO,MAAM;AACtB,QAAI,OAAO,QAAQ,YAAY,eAAe,KAAK,GAAG,GAAG;AACvD,YAAM,IAAI;AAAA,QACR,6MAGE,KAAK,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AAM,IAAI,IAC3D;AACN,MAAI,CAAC,IAAK,QAAO,EAAE,IAAI,IAAI,OAAO,IAAI,GAAG,OAAO,gBAAgB;AAEhE,QAAM,YAAY,MAAM,aAAa;AACrC,QAAM,YAAY,KAAK,IAAI;AAC3B,MAAI,UAA6B;AACjC,MAAI;AACF,cAAU,MAAM,WAAW,MAAM;AAAA,MAC/B,SAAS,IAAI;AAAA,MACb,GAAI,IAAI,SAAS,SAAY,EAAE,MAAM,IAAI,KAAK,IAAI,CAAC;AAAA,MACnD,GAAI,IAAI,QAAQ,SAAY,EAAE,KAAK,IAAI,IAAI,IAAI,CAAC;AAAA,MAChD,aAAa,MAAM,eAAe,QAAQ,IAAI;AAAA;AAAA;AAAA,MAG9C;AAAA,IACF,CAAC;AACD,UAAM,OAAO,QAAQ,aAAa;AAClC,WAAO;AAAA,MACL;AAAA,MACA,IAAI;AAAA,MACJ,IAAI,KAAK,IAAI,IAAI;AAAA,MACjB,GAAI,OAAO,EAAE,WAAW,KAAK,IAAI,CAAC;AAAA,IACpC;AAAA,EACF,SAAS,KAAK;AACZ,WAAO;AAAA,MACL;AAAA,MACA,IAAI;AAAA,MACJ,IAAI,KAAK,IAAI,IAAI;AAAA,MACjB,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAAA,IACxD;AAAA,EACF,UAAE;AACA,QAAI,SAAS;AACX,UAAI;AACF,cAAM,QAAQ,MAAM;AAAA,MACtB,QAAQ;AAAA,MAER;AAAA,IACF;AAAA,EACF;AACF;",
6
- "names": ["resolve", "spawn", "buildChildEnv", "resolve", "path", "stat", "realpathSync", "path", "resolve", "resolve", "resolve", "params", "writeErr", "resolve", "writeErr", "isRecord", "extractText", "path", "fsp", "path"]
3
+ "sources": [],
4
+ "sourcesContent": [],
5
+ "mappings": "",
6
+ "names": []
7
7
  }