fascicle 0.18.1 → 0.19.0

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.
Files changed (51) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/README.md +27 -1
  3. package/dist/AGENTS.md +11 -10
  4. package/dist/a2a.d.ts +358 -0
  5. package/dist/a2a.js +2234 -0
  6. package/dist/a2a.js.map +1 -0
  7. package/dist/acp.d.ts +120 -9
  8. package/dist/acp.js +927 -154
  9. package/dist/acp.js.map +1 -1
  10. package/dist/adapters-DYFauXE1.js +1147 -0
  11. package/dist/adapters-DYFauXE1.js.map +1 -0
  12. package/dist/adapters.d.ts +124 -36
  13. package/dist/adapters.js +1 -1
  14. package/dist/agents.d.ts +2 -2
  15. package/dist/agents.js +1 -1
  16. package/dist/{core-BH7sWpEG.js → core-xTtRZqdb.js} +217 -99
  17. package/dist/core-xTtRZqdb.js.map +1 -0
  18. package/dist/diagram_bin.js +1 -1
  19. package/dist/durable-CgU0kO2H.d.ts +144 -0
  20. package/dist/{engine-fOjYHcv6.js → engine-B_Yl7acj.js} +128 -42
  21. package/dist/engine-B_Yl7acj.js.map +1 -0
  22. package/dist/index.d.ts +9 -136
  23. package/dist/index.js +6 -5
  24. package/dist/index.js.map +1 -1
  25. package/dist/{invoke-7iu8db6V.js → invoke-Bbk0RuVL.js} +3 -3
  26. package/dist/{invoke-7iu8db6V.js.map → invoke-Bbk0RuVL.js.map} +1 -1
  27. package/dist/{leading_system-BeQUSAim.js → leading_system-m-x7HzbQ.js} +16 -4
  28. package/dist/leading_system-m-x7HzbQ.js.map +1 -0
  29. package/dist/mcp-D1hN5ywq.js +662 -0
  30. package/dist/mcp-D1hN5ywq.js.map +1 -0
  31. package/dist/mcp.d.ts +115 -5
  32. package/dist/mcp.js +2 -2
  33. package/dist/otel.d.ts +1 -1
  34. package/dist/stdio.d.ts +1 -1
  35. package/dist/stdio.js +2 -2
  36. package/dist/testing.d.ts +7 -5
  37. package/dist/testing.js +618 -318
  38. package/dist/testing.js.map +1 -1
  39. package/dist/{types-BUXt_zgJ.d.ts → types-BtRpSctv.d.ts} +38 -5
  40. package/dist/{types-Dk9tLpUq.d.ts → types-CDTW7XWB.d.ts} +2 -2
  41. package/dist/ui.d.ts +2 -2
  42. package/dist/viewer.js +2 -2
  43. package/dist/web.d.ts +1 -1
  44. package/package.json +17 -5
  45. package/dist/adapters-CpKpDk7r.js +0 -461
  46. package/dist/adapters-CpKpDk7r.js.map +0 -1
  47. package/dist/core-BH7sWpEG.js.map +0 -1
  48. package/dist/engine-fOjYHcv6.js.map +0 -1
  49. package/dist/leading_system-BeQUSAim.js.map +0 -1
  50. package/dist/mcp-CHJ88HiG.js +0 -262
  51. package/dist/mcp-CHJ88HiG.js.map +0 -1
package/dist/acp.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"acp.js","names":["asked","is_record","is_record"],"sources":["../src/acp/modes.ts","../src/acp/mcp_servers.ts","../src/acp/tools/previews.ts","../src/acp/tools/write_file.ts","../src/acp/tools/edit_file.ts","../src/acp/tools/run_command.ts","../src/acp/workspace_tools.ts","../src/acp/presentation.ts","../src/acp/approve.ts","../src/acp/models.ts","../src/acp/to_session_updates.ts","../src/acp/usage.ts","../src/acp/prompt_turn.ts","../src/acp/errors.ts","../src/acp/sdk_loader.ts","../src/acp/acp_agent.ts","../src/acp/serve_streams.ts","../src/acp/serve_acp.ts","../src/acp/session_store.ts"],"sourcesContent":["/**\n * modes: the three ways a coding session runs, and when each asks the\n * client before a workspace tool acts.\n *\n * Reads and searches never ask. Manual asks before every edit and every\n * command, Accept edits only before a command, and Auto never asks. That is\n * the contract Claude Agent set and Zed's mode picker presents. Auto runs\n * commands with nobody watching, so it belongs in a container or a\n * throwaway worktree, and an agent that runs anywhere else leaves it out\n * with `ServeAcpConfig.modes`.\n *\n * ACP reports a session's mode two ways, as `modes` and as a config option\n * in the `mode` category, and a client reads one or the other. Both come\n * from the one table here and the one `ModeOffer` an agent builds from its\n * config, and every change sends both updates, so the two can't disagree in\n * front of the user.\n */\n\nimport type { SessionConfigOption, SessionModeState, SessionUpdate } from '@agentclientprotocol/sdk'\nimport type { AcpMode } from './types.js'\n\n/** The id of the config option that carries the mode. */\nexport const MODE_CONFIG_ID = 'mode'\n\n/** What a workspace tool does that a mode may want to ask about first. */\nexport type GatedAction = 'edit' | 'command'\n\ntype ModeEntry = {\n readonly name: string\n readonly description: string\n readonly asks: Readonly<Record<GatedAction, boolean>>\n}\n\n/** Every mode, in the order a client lists them. */\nconst MODES: Readonly<Record<AcpMode, ModeEntry>> = {\n manual: {\n name: 'Manual',\n description: 'Ask before every edit and every command',\n asks: { edit: true, command: true },\n },\n accept_edits: {\n name: 'Accept edits',\n description: 'Edit files without asking, and ask before every command',\n asks: { edit: false, command: true },\n },\n auto: {\n name: 'Auto',\n description: 'Edit files and run commands without asking, for a container or a throwaway worktree',\n asks: { edit: false, command: false },\n },\n}\n\n/**\n * Whether `id` names one of the modes. An own-key check, so an id such as\n * `toString` that every object answers to isn't taken for one.\n */\nexport function is_acp_mode(id: unknown): id is AcpMode {\n return typeof id === 'string' && Object.hasOwn(MODES, id)\n}\n\n/**\n * The modes an agent offers, in the table's order and each once, and the\n * mode each of its sessions starts in. `acp_agent` builds one from its\n * config, and every list, check, and start mode reads it.\n */\nexport type ModeOffer = {\n readonly modes: ReadonlyArray<AcpMode>\n readonly default_mode: AcpMode\n}\n\n/** Every mode's id, as the refusals list them. */\nconst MODE_NAMES = Object.keys(MODES).join(', ')\n\n/**\n * The modes an agent offers and where its sessions start, from the config's\n * `modes` (default: all three) and `default_mode` (default: the first mode\n * offered). Throws an `Error` that names the problem for an empty `modes`,\n * an entry that isn't a mode, or a `default_mode` the agent doesn't offer,\n * so `acp_agent` fails as it's built rather than at every `session/new`.\n */\nexport function mode_offer(config: {\n readonly modes?: ReadonlyArray<AcpMode> | undefined\n readonly default_mode?: AcpMode | undefined\n}): ModeOffer {\n // A caller with no types can pass anything, so each entry is checked as unknown.\n const listed: ReadonlyArray<unknown> = config.modes ?? Object.keys(MODES)\n if (listed.length === 0) {\n throw new Error(\n `acp_agent: modes is empty; list at least one of ${MODE_NAMES}, or leave modes out to offer all three`,\n )\n }\n for (const entry of listed) {\n if (!is_acp_mode(entry)) {\n throw new Error(`acp_agent: modes lists ${JSON.stringify(entry)}, which isn't a mode; use one of ${MODE_NAMES}`)\n }\n }\n const modes = Object.keys(MODES).filter((id): id is AcpMode => listed.includes(id))\n const wanted = config.default_mode ?? modes[0]\n const default_mode = modes.find((mode) => mode === wanted)\n if (default_mode === undefined) {\n throw new Error(\n `acp_agent: default_mode ${JSON.stringify(config.default_mode)} isn't one of the modes this agent offers (${modes.join(', ')}); add it to modes or leave default_mode out`,\n )\n }\n return { modes, default_mode }\n}\n\n/**\n * The refusal for a mode id the agent doesn't offer, naming the ones it does.\n */\nexport function unknown_mode_message(id: unknown, offer: ModeOffer): string {\n return `unknown mode ${JSON.stringify(id)}; choose one of ${offer.modes.join(', ')}`\n}\n\n/**\n * Whether a session in `mode` asks the client before a tool does `action`.\n */\nexport function asks_before(mode: AcpMode, action: GatedAction): boolean {\n return MODES[mode].asks[action]\n}\n\n/** A mode as ACP lists one: its id, its name, and what it asks. */\ntype ListedMode = { readonly id: AcpMode; readonly name: string; readonly description: string }\n\n/**\n * Every mode the agent offers as ACP lists one, in the table's order.\n */\nfunction available_modes(offer: ModeOffer): ListedMode[] {\n return offer.modes.map((id) => ({ id, name: MODES[id].name, description: MODES[id].description }))\n}\n\n/**\n * The session's modes as `session/new` reports them in `modes`.\n */\nexport function mode_state(offer: ModeOffer, mode: AcpMode): SessionModeState {\n return { currentModeId: mode, availableModes: available_modes(offer) }\n}\n\n/**\n * The session's mode as a config option, a select over every mode the agent\n * offers, which leads the options `session/new` and\n * `session/set_config_option` report.\n */\nexport function config_options(offer: ModeOffer, mode: AcpMode): SessionConfigOption[] {\n return [\n {\n id: MODE_CONFIG_ID,\n name: 'Mode',\n description: 'When the agent asks before it edits a file or runs a command',\n category: 'mode',\n type: 'select',\n currentValue: mode,\n options: available_modes(offer).map(({ id, name, description }) => ({ value: id, name, description })),\n },\n ]\n}\n\n/**\n * A session's mode as the agent holds it: what it is now, whether the agent\n * offers a mode, and the one way to change it, which tells the client both\n * ways it may be reading it.\n */\nexport type SessionModes = {\n readonly current: () => AcpMode\n readonly offers: (mode: unknown) => mode is AcpMode\n readonly switch_to: (mode: AcpMode) => Promise<void>\n}\n\n/**\n * Hold a session's mode, starting at `start` when the agent offers it and\n * at the offer's `default_mode` otherwise, so a stored session whose mode the\n * agent has since stopped offering starts where a new one would. A switch\n * takes effect before the client hears of it, so a tool call that asks after\n * the switch reads the new mode, and the two updates go out in order through\n * `send`. A config option update carries every option the session has, so\n * `others` gives the ones after the mode, such as the model.\n */\nexport function session_modes(\n offer: ModeOffer,\n send: (update: SessionUpdate) => Promise<void>,\n start?: AcpMode,\n others: () => SessionConfigOption[] = () => [],\n): SessionModes {\n const offered: ReadonlyArray<unknown> = offer.modes\n let mode = offer.modes.find((entry) => entry === start) ?? offer.default_mode\n return {\n current: () => mode,\n offers: (candidate): candidate is AcpMode => offered.includes(candidate),\n switch_to: async (next) => {\n mode = next\n await send({ sessionUpdate: 'current_mode_update', currentModeId: next })\n await send({ sessionUpdate: 'config_option_update', configOptions: [...config_options(offer, next), ...others()] })\n },\n }\n}\n","/**\n * mcp_servers: the MCP servers a client sends with a session, connected\n * for the session's flow.\n *\n * Zed sends the MCP servers its user configured with every session. An\n * agent whose config sets `mcp_servers` connects to each one through\n * `mcp_client` from fascicle/mcp and hands their tools to the flow builder.\n * A server that can't be reached is left out with a warning on stderr\n * rather than failing the session, so one broken entry in the editor's\n * settings can't stop every thread. Each tool is named\n * `mcp__<server>__<tool>`, the form Claude Code uses, so two servers' tools\n * don't collide and none takes a workspace tool's name. A name that two\n * servers still share after that goes to the first.\n *\n * An MCP tool can do anything its server can, so each one asks before it\n * runs whenever the session's mode asks before a command. The approval\n * knows these calls the way it knows the workspace tools', by the input\n * their `needs_approval` was asked about, so a flow's own tool that copies\n * one's name doesn't pass for it.\n *\n * The connections last as long as the session, and close when the client\n * closes the session or the connection.\n */\n\nimport type { McpServer } from '@agentclientprotocol/sdk'\nimport type { Tool } from '#engine'\nimport { mcp_client } from '#mcp'\nimport type { McpClientConfig, McpClientHandle } from '#mcp'\nimport { is_record } from '#schema'\nimport { asks_before } from './modes.js'\nimport type { AcpSession } from './types.js'\n\n/**\n * The MCP transports the agent tells a client it speaks beside stdio, which\n * every agent takes.\n */\nexport const MCP_CAPABILITIES = { http: true } as const\n\n/** A session's MCP servers, connected: every tool they offer, and the way to close them all. */\nexport type McpConnections = {\n readonly tools: ReadonlyArray<Tool>\n readonly close: () => Promise<void>\n}\n\n/** The connections of a session with no MCP servers. */\nexport const NO_MCP: McpConnections = { tools: [], close: async () => {} }\n\n/** Who the agent says it is to each server. */\ntype McpIdentity = { readonly name: string; readonly version: string }\n\n/** The validated inputs each session's MCP tools were asked about. */\nconst asked = new WeakMap<AcpSession, WeakSet<object>>()\n\n/**\n * Say on stderr what went wrong with a session's MCP servers, since the\n * session carries on without what failed.\n */\nfunction warn(message: string): void {\n process.stderr.write(`fascicle/acp: ${message}\\n`)\n}\n\n/**\n * A list of names and values as the record a transport takes.\n */\nfunction record_of(entries: ReadonlyArray<{ readonly name: string; readonly value: string }>): Record<string, string> {\n return Object.fromEntries(entries.map(({ name, value }) => [name, value]))\n}\n\n/**\n * How `mcp_client` reaches a server the client sent, or undefined for a\n * transport it doesn't speak. A stdio server starts in the session's cwd\n * with the variables the client gave it on top of the MCP SDK's own short\n * list, so it doesn't inherit the agent's provider keys.\n */\nfunction client_config(server: McpServer, cwd: string): McpClientConfig | undefined {\n if ('command' in server) {\n return { transport: 'stdio', command: server.command, args: [...server.args], env: record_of(server.env), cwd }\n }\n if (server.type === 'http') return { transport: 'http', url: server.url, headers: record_of(server.headers) }\n return undefined\n}\n\n/**\n * Connect to one server, or warn and return undefined when it can't be\n * reached, so the session starts without it.\n */\nasync function connect_server(\n server: McpServer,\n cwd: string,\n identity: McpIdentity,\n): Promise<McpClientHandle | undefined> {\n const config = client_config(server, cwd)\n if (config === undefined) {\n warn(`MCP server ${server.name} uses a transport this agent doesn't speak, so its tools are left out of the session`)\n return undefined\n }\n const name_prefix = `mcp__${server.name.replaceAll(/[^\\w-]/g, '_')}__`\n try {\n return await mcp_client(config, { client_info: identity, name_prefix })\n } catch (err: unknown) {\n const reason = err instanceof Error ? err.message : String(err)\n warn(`couldn't connect to MCP server ${server.name} (${reason}), so its tools are left out of the session`)\n return undefined\n }\n}\n\n/**\n * Close every connection, warning about any that fails to close rather\n * than leaving the others open.\n */\nasync function close_all(handles: ReadonlyArray<McpClientHandle>): Promise<void> {\n const results = await Promise.allSettled(handles.map((handle) => handle.close()))\n for (const result of results) {\n if (result.status === 'rejected') {\n const reason: unknown = result.reason\n warn(`couldn't close an MCP server (${reason instanceof Error ? reason.message : String(reason)})`)\n }\n }\n}\n\n/**\n * Connect to every server the client sent for a session, all at once, and\n * gather their tools, keeping the first tool to take each name.\n */\nexport async function connect_mcp_servers(\n servers: ReadonlyArray<McpServer>,\n cwd: string,\n identity: McpIdentity,\n): Promise<McpConnections> {\n if (servers.length === 0) return NO_MCP\n const connected = await Promise.all(servers.map((server) => connect_server(server, cwd, identity)))\n const handles = connected.filter((handle) => handle !== undefined)\n const tools = new Map<string, Tool>()\n for (const tool of handles.flatMap((handle) => handle.tools)) {\n if (tools.has(tool.name)) warn(`two MCP servers offer a tool named ${tool.name}, so the second one's is left out`)\n else tools.set(tool.name, tool)\n }\n return { tools: [...tools.values()], close: () => close_all(handles) }\n}\n\n/**\n * Whether one of the session's MCP tools was asked about this very input,\n * which makes the call one of theirs rather than a call to a tool that only\n * shares a name with one.\n */\nexport function is_mcp_call(session: AcpSession, input: unknown): boolean {\n return is_record(input) && asked.get(session)?.has(input) === true\n}\n\n/**\n * The session's MCP tools, each asking before it runs whenever the\n * session's mode asks before a command, and marking the input it was asked\n * about as one of the session's own MCP calls. The tools are made as the\n * session is, so they reach it through `session` at each call.\n */\nexport function gated_mcp_tools(tools: ReadonlyArray<Tool>, session: () => AcpSession): ReadonlyArray<Tool> {\n return tools.map((tool) => ({\n ...tool,\n needs_approval: (input: unknown) => {\n const current = session()\n const inputs = asked.get(current) ?? new WeakSet<object>()\n asked.set(current, inputs)\n if (is_record(input)) inputs.add(input)\n return asks_before(current.mode(), 'command')\n },\n }))\n}\n","/**\n * The preview store: what each workspace tool call changed or ran, kept for\n * the client's card that shows it.\n *\n * A write's card shows its diff and a command's shows its output and exit\n * code, but the model reads back a single line, so the call's result can't\n * carry them. Each tool leaves its call's preview here once the call\n * succeeds, under the engine's raw call id, and `to_session_updates` takes\n * it when that call's result arrives. The file reads behind a diff happen\n * in the tool, before it writes, so the mapper itself stays free of I/O.\n *\n * Raw ids repeat across model calls (Ollama numbers its calls afresh on\n * each one), and the turn's consumer can fall behind the engine, so each id\n * holds a queue, taken oldest first. The engine runs a turn's calls one\n * after another, which keeps each queue in the order its results arrive.\n * Only a call that succeeded leaves a preview, and only a successful result\n * takes one, so a call refused before it ran can't take a later call's.\n *\n * The store belongs to the session and is keyed by the session object, so\n * `AcpSession` carries nothing for it. Each turn starts it empty, so what a\n * cancelled turn left behind never reaches the next.\n */\n\nimport type { AcpSession } from '../types.js'\n\n/**\n * A file change that landed: the path in the client's terms, the text\n * before (`null` for a new file) and after, and for an edit, the line where\n * its first match starts, counting from 1 (a write has none).\n */\nexport type ChangePreview = {\n readonly kind: 'change'\n readonly path: string\n readonly old_text: string | null\n readonly new_text: string\n readonly line: number | undefined\n}\n\n/**\n * A command that ran to its end: what it printed, and its exit code or the\n * signal that ended it.\n */\nexport type CommandPreview = {\n readonly kind: 'command'\n readonly output: string\n readonly exit_code: number | null\n readonly signal: string | null\n}\n\nexport type ToolPreview = ChangePreview | CommandPreview\n\nconst stores = new WeakMap<AcpSession, Map<string, ToolPreview[]>>()\n\n/**\n * The session's store, made empty the first time it's asked for.\n */\nfunction store_of(session: AcpSession): Map<string, ToolPreview[]> {\n const store = stores.get(session) ?? new Map<string, ToolPreview[]>()\n stores.set(session, store)\n return store\n}\n\n/**\n * Empty the session's store as a turn starts.\n */\nexport function reset_previews(session: AcpSession): void {\n stores.set(session, new Map())\n}\n\n/**\n * Leave a call's preview at the back of its raw id's queue.\n */\nexport function record_preview(session: AcpSession, tool_call_id: string, preview: ToolPreview): void {\n const store = store_of(session)\n store.set(tool_call_id, [...(store.get(tool_call_id) ?? []), preview])\n}\n\n/**\n * Take the oldest preview waiting under a raw id, or `undefined` when none\n * is.\n */\nexport function take_preview(session: AcpSession, tool_call_id: string): ToolPreview | undefined {\n return store_of(session).get(tool_call_id)?.shift()\n}\n","/**\n * write_file: create a text file in the workspace, or replace everything one\n * holds.\n *\n * Every write is worked out before it happens, as the file's whole text\n * before and after, so the client can be shown the change as a diff before\n * anything reaches the disk. `edit_file` builds its change from the same\n * pieces, so the two tools agree on what they refuse and how they write.\n *\n * A write lands at the path's real location, which `contain` placed inside a\n * root, and creates the directories it needs there, so a model writing\n * `src/new/thing.ts` doesn't need a command to make `src/new` first.\n */\n\nimport { isUtf8 } from 'node:buffer'\nimport { mkdir, open, stat, writeFile } from 'node:fs/promises'\nimport { dirname } from 'node:path'\nimport type { Tool } from '#engine'\nimport { as_record, json_schema_to_standard } from '#schema'\nimport type { AcpSession } from '../types.js'\nimport { contain_writable, error_code, shown_path } from './containment.js'\nimport type { ContainedPath } from './containment.js'\nimport { record_preview } from './previews.js'\nimport { is_binary } from './read_file.js'\n\n/**\n * A write worked out before anything is written: the file both ways\n * `contain` names it, and its whole text before and after. `old_text` is\n * `null` only when the write creates the file.\n */\nexport type FileChange = ContainedPath & {\n readonly old_text: string | null\n readonly new_text: string\n}\n\n/** A file change as a card or a permission request shows it, with the line an edit lands on. */\nexport type ShownChange = FileChange & { readonly line?: number }\n\n/**\n * The largest file a change reads, in bytes. A change is shown as a diff,\n * which carries the file's whole text twice, as its text before and after,\n * and the closing card update carries it again.\n */\nconst CHANGE_LIMIT_BYTES = 1_000_000\n\n/** One write as the model asked for it. */\ntype WriteRequest = {\n readonly path: string\n readonly content: string\n}\n\n/**\n * Read the call's path and content out of its input.\n */\nfunction write_request(input: unknown): WriteRequest {\n const fields: Record<string, unknown> = as_record(input) ?? {}\n const { path, content } = fields\n if (typeof path !== 'string' || typeof content !== 'string') {\n throw new Error('write_file needs a path and the content to write, as strings')\n }\n return { path, content }\n}\n\n/**\n * The text a write would replace, or `null` when no file is there yet.\n * Anything but a regular UTF-8 text file is refused, because the change is\n * shown as a diff of text, and rewriting a file in another encoding would\n * change bytes outside the edit. A file with other hard links is refused too:\n * a write changes the file under every name it has, and real paths can't say\n * where the other names lie. A file over CHANGE_LIMIT_BYTES is refused from\n * its size, before it's opened. `shown` is the path as the model gave it,\n * and `tool` names the tool asking, for the refusals.\n */\nexport async function current_text(real: string, shown: string, tool: string): Promise<string | null> {\n const info = await stat(real).catch((err: unknown) => {\n if (error_code(err) === 'ENOENT') return undefined\n throw err\n })\n if (info === undefined) return null\n if (info.isDirectory()) throw new Error(`${shown} is a directory; ${tool} changes a file, so name one inside it`)\n if (!info.isFile()) throw new Error(`${shown} isn't a regular file, so ${tool} can't change it`)\n if (info.nlink > 1) {\n throw new Error(\n `${shown} is one of ${info.nlink} hard links to the same file, and the rest may lie outside the workspace, so ${tool} won't change it`,\n )\n }\n if (info.size > CHANGE_LIMIT_BYTES) {\n throw new Error(\n `${shown} is ${info.size} bytes, over the ${CHANGE_LIMIT_BYTES} that write_file and edit_file read to show a change as a diff; change it with run_command instead`,\n )\n }\n const handle = await open(real)\n try {\n if (await is_binary(handle)) {\n throw new Error(`${shown} is a binary file (it has a NUL byte in its first 8 KB), so ${tool} won't change it`)\n }\n // The binary check reads at an explicit position, which leaves the\n // handle's own position at the top, where readFile starts.\n const bytes = await handle.readFile()\n if (!isUtf8(bytes)) throw new Error(`${shown} isn't UTF-8 text, so ${tool} won't change it`)\n return bytes.toString('utf8')\n } finally {\n await handle.close()\n }\n}\n\n/**\n * Write a change's new text where it lands, creating the directories it\n * needs first. A turn cancelled while the change was worked out stops here,\n * before anything is written. A new file is created exclusively, so a file or\n * a symlink that appeared at its path since then stops the write instead of\n * taking it.\n */\nexport async function apply_change(change: FileChange, abort: AbortSignal): Promise<void> {\n abort.throwIfAborted()\n await mkdir(dirname(change.real), { recursive: true })\n await writeFile(change.real, change.new_text, change.old_text === null ? { flag: 'wx' } : {})\n}\n\n/**\n * Leave a change that landed in the session's preview store, for the card\n * of the call that made it to show as a diff.\n */\nexport function record_change(\n session: AcpSession,\n tool_call_id: string,\n change: ShownChange,\n): void {\n record_preview(session, tool_call_id, {\n kind: 'change',\n path: change.path,\n old_text: change.old_text,\n new_text: change.new_text,\n line: change.line,\n })\n}\n\n/**\n * The change a `write_file` call would make, worked out without writing: its\n * path checked against the session's roots and kept out of `.git` and\n * `node_modules`, the text it would replace, and the content that replaces\n * it.\n */\nexport async function write_file_change(session: AcpSession, input: unknown): Promise<FileChange> {\n const request = write_request(input)\n const target = await contain_writable(session, request.path, 'write_file')\n const old_text = await current_text(target.real, request.path, 'write_file')\n return { ...target, old_text, new_text: request.content }\n}\n\n/**\n * The `write_file` tool for one session: a file inside its workspace,\n * created or replaced whole. The model reads back a line saying which, since\n * it already has the text it sent.\n */\nexport function write_file_tool(session: AcpSession): Tool {\n return {\n name: 'write_file',\n description:\n 'Write a text file in the workspace: create it, along with any directories it needs, or replace everything it holds. ' +\n \"content is the file's whole text; to change part of a file, use edit_file. \" +\n 'The path is absolute or relative to the workspace root.',\n input_schema: json_schema_to_standard({\n type: 'object',\n properties: {\n path: { type: 'string', description: 'The file to write, absolute or relative to the workspace root' },\n content: { type: 'string', description: \"The file's whole text\" },\n },\n required: ['path', 'content'],\n additionalProperties: false,\n }),\n execute: async (input, ctx) => {\n const change = await write_file_change(session, input)\n await apply_change(change, ctx.abort)\n record_change(session, ctx.tool_call_id, change)\n return `${change.old_text === null ? 'created' : 'overwrote'} ${shown_path(session, change.path)}`\n },\n }\n}\n","/**\n * edit_file: replace an exact match in a text file in the workspace.\n *\n * The match has to be exact and, unless the call sets `replace_all`, the only\n * one, so the model names enough of the file to say which place it means. A\n * looser match could change a place it never looked at. The change is worked\n * out first, the way `write_file`'s is, as the whole file before and after,\n * with the line where the first match starts for the client to point at.\n */\n\nimport type { Tool } from '#engine'\nimport { as_record, json_schema_to_standard } from '#schema'\nimport type { AcpSession } from '../types.js'\nimport { contain_writable, shown_path } from './containment.js'\nimport { apply_change, current_text, record_change } from './write_file.js'\nimport type { FileChange } from './write_file.js'\n\n/**\n * A change `edit_file` would make. The file exists, so `old_text` is always\n * its text. `line` is where the first match starts, counting from 1, and\n * `matches` is how many places the edit replaces.\n */\nexport type EditChange = FileChange & {\n readonly old_text: string\n readonly line: number\n readonly matches: number\n}\n\n/** One edit as the model asked for it. */\ntype EditRequest = {\n readonly path: string\n readonly old_text: string\n readonly new_text: string\n readonly replace_all: boolean\n}\n\n/**\n * Read the call's path, texts, and `replace_all` out of its input, refusing\n * an `old_text` that's empty, which matches everywhere, or the same as\n * `new_text`, which changes nothing.\n */\nfunction edit_request(input: unknown): EditRequest {\n const fields: Record<string, unknown> = as_record(input) ?? {}\n const { path, old_text, new_text, replace_all = false } = fields\n if (\n typeof path !== 'string' ||\n typeof old_text !== 'string' ||\n typeof new_text !== 'string' ||\n typeof replace_all !== 'boolean'\n ) {\n throw new Error('edit_file needs path, old_text, and new_text as strings, and takes replace_all as true or false')\n }\n if (old_text === '') throw new Error(\"old_text is empty, so there's nothing to find; write_file writes a whole file\")\n if (old_text === new_text) throw new Error('old_text and new_text are the same, so the edit would change nothing')\n return { path, old_text, new_text, replace_all }\n}\n\n/**\n * The change an `edit_file` call would make, worked out without writing: the\n * file's whole text before, and after `old_text` is replaced. It fails on a\n * path that `contain_writable` refuses, when `old_text` isn't there, or when\n * it's there more than once and the call doesn't set `replace_all`.\n */\nexport async function edit_file_change(session: AcpSession, input: unknown): Promise<EditChange> {\n const request = edit_request(input)\n const target = await contain_writable(session, request.path, 'edit_file')\n const text = await current_text(target.real, request.path, 'edit_file')\n if (text === null) throw new Error(`${request.path} doesn't exist; write_file creates a file`)\n // Splitting on the match, where String.replace would read its replacement\n // as a pattern, keeps a `$&` or `$$` in new_text as the model wrote it.\n const pieces = text.split(request.old_text)\n const matches = pieces.length - 1\n if (matches === 0) {\n throw new Error(\n `old_text doesn't appear in ${request.path}; it has to match the file exactly, whitespace included, so read the lines again and copy them without their numbers`,\n )\n }\n if (matches > 1 && !request.replace_all) {\n throw new Error(\n `old_text appears ${matches} times in ${request.path}; include more of the lines around it so it matches once, or set replace_all to replace every one`,\n )\n }\n const before = text.slice(0, text.indexOf(request.old_text))\n return {\n ...target,\n old_text: text,\n new_text: pieces.join(request.new_text),\n line: before.split('\\n').length,\n matches,\n }\n}\n\n/**\n * The `edit_file` tool for one session: an exact match replaced in a file\n * inside its workspace. The model reads back where the edit landed rather\n * than the file again.\n */\nexport function edit_file_tool(session: AcpSession): Tool {\n return {\n name: 'edit_file',\n description:\n 'Edit a text file in the workspace by replacing old_text with new_text. ' +\n 'old_text has to match the file exactly, whitespace and line breaks included, ' +\n 'and appear in it once, unless replace_all is set to replace every match. ' +\n 'Copy it from read_file without the line number and tab that read_file puts before each line. ' +\n 'The path is absolute or relative to the workspace root.',\n input_schema: json_schema_to_standard({\n type: 'object',\n properties: {\n path: { type: 'string', description: 'The file to edit, absolute or relative to the workspace root' },\n old_text: { type: 'string', minLength: 1, description: 'The exact text to replace' },\n new_text: { type: 'string', description: 'The text to put in its place' },\n replace_all: {\n type: 'boolean',\n description: 'Replace every match of old_text, rather than exactly one; default: false',\n },\n },\n required: ['path', 'old_text', 'new_text'],\n additionalProperties: false,\n }),\n execute: async (input, ctx) => {\n const change = await edit_file_change(session, input)\n await apply_change(change, ctx.abort)\n record_change(session, ctx.tool_call_id, change)\n const shown = shown_path(session, change.path)\n return change.matches === 1\n ? `edited ${shown} at line ${change.line}`\n : `edited ${shown} in ${change.matches} places, the first at line ${change.line}`\n },\n }\n}\n","/**\n * run_command: run a shell command in the workspace and hand back what it\n * printed and how it ended.\n *\n * The command is a string the model wrote in POSIX shell, so it runs as\n * `/bin/sh -c`, which behaves the same on every host and needs no read of\n * the user's `$SHELL`. Windows has neither that shell nor POSIX process\n * groups, so there the tool refuses and the file tools carry on.\n *\n * Each command leads a process group of its own, so the whole tree it starts\n * dies together: when the turn is cancelled, when it runs past its timeout,\n * and when the shell exits, which stops whatever it left running in the\n * background. Without that last kill, a job left behind would outlive the\n * call, and then the agent, since nothing would ever abort it. A command\n * that moves work into a group of its own (`set -m` in an interactive\n * shell, or a daemon that starts its own session) takes that work out of\n * reach, as it would from a terminal's Ctrl-C.\n *\n * The file tools' containment doesn't bind a command: the shell reaches\n * anything the user can.\n *\n * This is the one file in `src/acp/` that may import `node:child_process`\n * (rules/no-child-process-outside-run-command.yml).\n */\n\nimport { spawn } from 'node:child_process'\nimport type { ChildProcess } from 'node:child_process'\nimport { StringDecoder } from 'node:string_decoder'\nimport type { Tool } from '#engine'\nimport { as_record, json_schema_to_standard } from '#schema'\nimport type { AcpSession } from '../types.js'\nimport { record_preview } from './previews.js'\nimport type { CommandPreview } from './previews.js'\n\n/** The shell every command runs in. */\nconst SHELL = '/bin/sh'\n\n/**\n * The longest delay a Node timer keeps. A longer one fires after 1 ms\n * instead, so a longer timeout is held to this, about 24.8 days.\n */\nconst MAX_TIMER_MS = 2_147_483_647\n\n/**\n * How long the output may stay open once the shell has exited and its group\n * has been killed. The group's processes are gone by then, so only\n * something moved out of the group can be holding it, and that could hold\n * it for good.\n */\nconst OUTPUT_GRACE_MS = 1000\n\n/** How `run_command` runs one session's commands, from `workspace_tools`' options. */\nexport type CommandSettings = {\n /** How long a call may run, unless it sets its own `timeout_ms`. */\n readonly timeout_ms: number\n /** The most output a call returns, in bytes. */\n readonly output_limit_bytes: number\n /** The whole environment commands run with, or `undefined` to inherit the agent's. */\n readonly env: Readonly<Record<string, string>> | undefined\n}\n\n/** One command as the model asked for it. */\ntype CommandRequest = {\n readonly command: string\n readonly timeout_ms: number | undefined\n}\n\n/**\n * What a command printed, stdout and stderr together in the order they\n * arrived, up to `limit` bytes: the parts kept, the bytes they account\n * for, and every byte the command printed.\n */\ntype Capture = {\n readonly limit: number\n readonly parts: string[]\n kept: number\n total: number\n}\n\n/**\n * Whether a value counts milliseconds: a whole number of at least 1.\n */\nfunction is_millis(value: unknown): value is number {\n return Number.isInteger(value) && Number(value) >= 1\n}\n\n/**\n * Read the call's command and timeout out of its input. The tool loop has\n * already checked the types against the schema, but a flow that wraps the\n * tool can call `execute` directly, and the schema's `minimum` is advice to\n * the model rather than something the loop enforces.\n */\nfunction command_request(input: unknown): CommandRequest {\n const fields: Record<string, unknown> = as_record(input) ?? {}\n const { command, timeout_ms } = fields\n if (typeof command !== 'string') throw new Error('run_command needs a command, as a string')\n if (timeout_ms !== undefined && !is_millis(timeout_ms)) {\n throw new Error('run_command counts timeout_ms in milliseconds, so it has to be a whole number of at least 1')\n }\n return { command, timeout_ms }\n}\n\n/**\n * Keep a chunk of output while the capture has room, cutting the chunk that\n * crosses the limit, and count every byte either way. The output goes on\n * being read past the limit, since a command blocked on a full pipe would\n * never finish.\n */\nfunction take(capture: Capture, chunk: string): void {\n const size = Buffer.byteLength(chunk)\n const room = capture.limit - capture.kept\n capture.total += size\n // Stryker disable next-line ConditionalExpression,EqualityOperator: with no room left the cut below keeps an empty string and counts no bytes, so going on reads the same; the return only spares a copy of every chunk past the cap.\n if (room <= 0) return\n // A chunk that fits comes through whole. One cut at the limit can end\n // inside a character, whose partial bytes the decoder holds back.\n capture.parts.push(new StringDecoder().write(Buffer.from(chunk).subarray(0, room)))\n capture.kept += Math.min(size, room)\n}\n\n/**\n * What a command printed as the model reads it, without its trailing\n * whitespace, with a marker when it was cut, and a line saying so when it\n * printed nothing at all.\n */\nfunction printed(capture: Capture): string[] {\n if (capture.total === 0) return ['[no output]']\n const lines = [capture.parts.join('').trimEnd()]\n if (capture.total > capture.kept) {\n lines.push(\n `[output cut at ${capture.limit} bytes of ${capture.total}; pipe the command through tail, head, or grep to see the part you need]`,\n )\n }\n return lines.filter((line) => line !== '')\n}\n\n/**\n * How a finished command ended, as its report's last line: its exit code,\n * or the signal that ended it. Node sets exactly one of the two.\n */\nfunction ending(child: ChildProcess): string {\n return child.exitCode === null ? `[ended by ${String(child.signalCode)}]` : `[exit code ${child.exitCode}]`\n}\n\n/**\n * A command that ran to its end: what it printed, its process, and whether\n * something it moved out of its group held its output open.\n */\ntype Finished = {\n readonly capture: Capture\n readonly child: ChildProcess\n readonly held: boolean\n}\n\n/**\n * A finished command's report: what it printed, then how it ended, and a\n * note when something it moved out of its group held its output open and\n * was left running.\n */\nfunction report({ capture, child, held }: Finished): string {\n const lines = [...printed(capture), ending(child)]\n if (held) {\n lines.push(\n '[the command exited, but something it moved out of its process group held its output open, so run_command stopped reading and left that running]',\n )\n }\n return lines.join('\\n')\n}\n\n/**\n * A finished command as its card shows it: what it printed, with nothing in\n * place of an empty output, and its exit code or the signal that ended it.\n */\nfunction command_preview({ capture, child }: Finished): CommandPreview {\n return {\n kind: 'command',\n output: capture.total === 0 ? '' : printed(capture).join('\\n'),\n exit_code: child.exitCode,\n signal: child.signalCode,\n }\n}\n\n/**\n * The error a call that ran past its timeout fails with, carrying what the\n * command printed before it was killed.\n */\nfunction timeout_error(capture: Capture, timeout_ms: number): Error {\n return new Error(\n `the command didn't finish within ${timeout_ms / 1000} s, so run_command killed it and everything it started; ` +\n 'pass a larger timeout_ms if it needs longer, but a server or a watch mode never finishes, so run it in a way that does. ' +\n `What it printed before then:\\n${printed(capture).join('\\n')}`,\n )\n}\n\n/**\n * Kill a command's whole process group with SIGKILL, the one signal no\n * command can ignore. The turn's abort can be the agent's last act before\n * `serve_acp` exits, which leaves no later moment to follow a gentler\n * signal with this one.\n */\nfunction kill_group(child: ChildProcess): void {\n // Stryker disable next-line ConditionalExpression: without a pid, process.kill throws on the NaN it's handed, and the catch below takes that the same way.\n if (child.pid === undefined) return\n try {\n process.kill(-child.pid, 'SIGKILL')\n } catch {\n // The group is gone: every process in it has exited.\n }\n}\n\n/**\n * Run one command to its end in its own process group. A command that ends\n * on its own is a result, whatever its exit code; a timeout and a shell that\n * won't start are errors, and the turn's abort rejects with its reason. The\n * timeout and the abort kill the group, and the shell's exit kills whatever\n * it left behind. Each reads on to the end of the output, so what the\n * command printed last isn't lost, until the grace after the shell's exit\n * runs out. However the call ends, its timers and the abort listener go\n * with it.\n */\nasync function run_shell(\n request: CommandRequest,\n cwd: string,\n settings: CommandSettings,\n abort: AbortSignal,\n): Promise<Finished> {\n abort.throwIfAborted()\n const timeout_ms = request.timeout_ms ?? settings.timeout_ms\n const capture: Capture = { limit: settings.output_limit_bytes, parts: [], kept: 0, total: 0 }\n const child = spawn(SHELL, ['-c', request.command], {\n cwd,\n env: settings.env === undefined ? undefined : { ...settings.env },\n detached: true,\n stdio: ['ignore', 'pipe', 'pipe'],\n })\n const { promise, resolve, reject } = Promise.withResolvers<Finished>()\n let timed_out = false\n let held = false\n let settled = false\n let grace: NodeJS.Timeout | undefined\n const on_abort = (): void => {\n kill_group(child)\n reject(abort.reason)\n }\n for (const stream of [child.stdout, child.stderr]) {\n // Stryker disable next-line StringLiteral: Node reads an empty encoding name as UTF-8.\n stream.setEncoding('utf8')\n stream.on('data', (chunk: string) => {\n take(capture, chunk)\n })\n }\n const timer = setTimeout(() => {\n timed_out = true\n kill_group(child)\n }, Math.min(timeout_ms, MAX_TIMER_MS))\n child.once('error', (err) => {\n reject(\n new Error(`run_command couldn't start ${SHELL} in ${cwd} (${err.message}); the workspace may have been moved or deleted`, {\n cause: err,\n }),\n )\n })\n const stop_reading = (): void => {\n child.stdout.destroy()\n child.stderr.destroy()\n }\n child.once('exit', () => {\n clearTimeout(timer)\n kill_group(child)\n // A call the abort has already settled reads nothing more, so its output\n // closes at once, rather than on a grace timer that would outlive it.\n if (settled) {\n stop_reading()\n return\n }\n // Stopping the reads closes the call even while something still holds\n // the other end of the output open.\n grace = setTimeout(() => {\n held = true\n stop_reading()\n }, OUTPUT_GRACE_MS)\n })\n child.once('close', () => {\n if (timed_out) reject(timeout_error(capture, timeout_ms))\n else resolve({ capture, child, held })\n })\n abort.addEventListener('abort', on_abort)\n try {\n return await promise\n } finally {\n settled = true\n clearTimeout(timer)\n clearTimeout(grace)\n abort.removeEventListener('abort', on_abort)\n }\n}\n\n/**\n * The `run_command` tool for one session: a command run through the shell\n * in its `cwd`, with a timeout, an output cap, and the environment the\n * settings give it, its whole process tree killed when the turn is\n * cancelled. POSIX only: on Windows every call is refused.\n */\nexport function run_command_tool(session: AcpSession, settings: CommandSettings): Tool {\n return {\n name: 'run_command',\n description: [\n `Run a shell command with ${SHELL} -c in the workspace root, and return what it printed (stdout and stderr together) and its exit code.`,\n 'Each call starts a fresh shell there, so a cd lasts for its own command only.',\n `The command is stopped after ${settings.timeout_ms / 1000} s unless timeout_ms says otherwise,`,\n `and output past ${settings.output_limit_bytes} bytes is cut, with a note that says so; run it again through tail, head, or grep for the part you need.`,\n 'Give the command plainly, without 2>&1 or a pipe to trim output that may well fit:',\n 'the user can allow a plain command for the rest of the session, but never one that holds a pipe, a redirect, &&, or ;.',\n \"It gets no input, and anything it starts is stopped once it exits, so it can't leave a server or a watcher running.\",\n ].join(' '),\n input_schema: json_schema_to_standard({\n type: 'object',\n properties: {\n command: { type: 'string', description: 'The command line, as you would type it in a POSIX shell' },\n timeout_ms: {\n type: 'integer',\n minimum: 1,\n description: `How long the command may run, in milliseconds; default: ${settings.timeout_ms}`,\n },\n },\n required: ['command'],\n additionalProperties: false,\n }),\n execute: async (input, ctx) => {\n if (process.platform === 'win32') {\n throw new Error(\n `run_command runs commands through ${SHELL} in a process group of their own, which Windows doesn't have, ` +\n 'so it can only refuse here; read_file, list_files, search, write_file, and edit_file still work',\n )\n }\n const finished = await run_shell(command_request(input), session.cwd, settings, ctx.abort)\n record_preview(session, ctx.tool_call_id, command_preview(finished))\n return report(finished)\n },\n }\n}\n","/**\n * workspace_tools: the tools a coding agent served over ACP needs, confined\n * to its session's workspace.\n *\n * They run in-process against the files on disk and in a shell of their\n * own, never through the client's `fs/*` or `terminal/*` methods, which\n * Claude Agent stopped using and the ACP v2 draft drops. They're plain\n * `Tool` values, so a flow can filter them (a read-only critic takes the\n * reads), set its own beside them, or wrap them. Each file tool checks every\n * path it's handed against the session's roots; a command starts in `cwd`\n * and reaches whatever the user can.\n *\n * The writes and `run_command` ask for approval when the session's mode\n * says to, and the reads never do.\n *\n * A flow or an MCP server can hand a model a tool of its own under one of\n * these names, and a name is all the engine tells the approval and the\n * cards. So each session keeps what it built: the names, which pick the\n * cards it draws, and every validated input that its gated tools were\n * asked about, which is how the approval knows its own calls. The engine\n * hands `needs_approval` and the approval handler the same input object,\n * so a same-named tool's call never passes for one of these.\n */\n\nimport type { Tool } from '#engine'\nimport { is_record } from '#schema'\nimport { asks_before } from './modes.js'\nimport type { GatedAction } from './modes.js'\nimport { edit_file_tool } from './tools/edit_file.js'\nimport { list_files_tool } from './tools/list_files.js'\nimport { read_file_tool } from './tools/read_file.js'\nimport { run_command_tool } from './tools/run_command.js'\nimport { search_tool } from './tools/search.js'\nimport { write_file_tool } from './tools/write_file.js'\nimport type { AcpSession, WorkspaceToolsOptions } from './types.js'\n\n/** The most lines one `read_file` call returns unless the options say otherwise. */\nconst READ_LIMIT_LINES = 2000\n\n/** The most paths one `list_files` call returns, so a very large repository's listing can't fill the context. */\nconst LIST_LIMIT = 1000\n\n/** The names `list_files` and `search` skip unless the options say otherwise. */\nconst IGNORE: ReadonlyArray<string> = ['.git', 'node_modules']\n\n/** How long one `search` may run unless the options say otherwise. */\nconst SEARCH_TIMEOUT_MS = 30_000\n\n/** How long one `run_command` call may run unless the options or the call say otherwise. */\nconst COMMAND_TIMEOUT_MS = 120_000\n\n/** The most output one `run_command` call returns unless the options say otherwise. */\nconst OUTPUT_LIMIT_BYTES = 32_000\n\n/**\n * The names each session's `workspace_tools` built. The set takes\n * `undefined` too, so a card whose opening the mapper never saw simply\n * finds nothing.\n */\nconst built = new WeakMap<AcpSession, ReadonlySet<string | undefined>>()\n\n/** The validated inputs each session's gated workspace tools were asked about. */\nconst asked = new WeakMap<AcpSession, WeakSet<object>>()\n\n/**\n * The inputs the session's gated workspace tools were asked about, made\n * empty the first time it's asked for.\n */\nfunction asked_of(session: AcpSession): WeakSet<object> {\n const inputs = asked.get(session) ?? new WeakSet<object>()\n asked.set(session, inputs)\n return inputs\n}\n\n/**\n * Whether the session's `workspace_tools` built a tool named `name`, so its\n * calls take the card that tool's presentation gives it.\n */\nexport function is_workspace_tool(session: AcpSession, name: string | undefined): boolean {\n return built.get(session)?.has(name) === true\n}\n\n/**\n * Whether one of the session's gated workspace tools was asked about this\n * very input, which makes the call one of theirs rather than a call to a\n * tool that only shares a name with one.\n */\nexport function is_workspace_call(session: AcpSession, input: unknown): boolean {\n return is_record(input) && asked.get(session)?.has(input) === true\n}\n\n/**\n * `tool`, asking for approval before each call when the session's mode asks\n * before `action`, and marking the input it was asked about as one of the\n * session's own. The mode is read at each call, not once, so a switch the\n * client makes mid-turn holds from the next call on.\n */\nfunction gated(tool: Tool, session: AcpSession, action: GatedAction): Tool {\n return {\n ...tool,\n needs_approval: (input) => {\n if (is_record(input)) asked_of(session).add(input)\n return asks_before(session.mode(), action)\n },\n }\n}\n\n/**\n * The workspace tools for one session: the reads (`read_file`, `list_files`,\n * and `search`), then the writes (`write_file` and `edit_file`), each\n * confined to the session's `cwd` and additional directories, then\n * `run_command`. The writes and the command ask before they run as the\n * session's mode says. From the first call on, the six names are the\n * workspace tools' within the session.\n */\nexport function workspace_tools(session: AcpSession, options: WorkspaceToolsOptions = {}): ReadonlyArray<Tool> {\n const ignore = options.ignore ?? IGNORE\n const tools = [\n read_file_tool(session, options.read_limit_lines ?? READ_LIMIT_LINES),\n list_files_tool(session, ignore, LIST_LIMIT),\n search_tool(session, ignore, options.search_timeout_ms ?? SEARCH_TIMEOUT_MS),\n gated(write_file_tool(session), session, 'edit'),\n gated(edit_file_tool(session), session, 'edit'),\n gated(\n run_command_tool(session, {\n timeout_ms: options.command_timeout_ms ?? COMMAND_TIMEOUT_MS,\n output_limit_bytes: options.output_limit_bytes ?? OUTPUT_LIMIT_BYTES,\n env: options.command_env,\n }),\n session,\n 'command',\n ),\n ]\n built.set(session, new Set(tools.map((tool) => tool.name)))\n return tools\n}\n","/**\n * presentation: how a workspace tool's call looks in the client, matching\n * what Zed's Claude Agent sends for its own tools.\n *\n * Each card gets the kind that picks its icon, a title that reads like the\n * call (`Read src/a.ts (1 - 40)`, `grep \"todo\" src`, the command line) with\n * its paths relative to `cwd`, and the places it touches as locations, whose\n * lines count from 1 as Claude Agent's do. A write's or an edit's card shows\n * its diff once the call lands, a read's, a listing's, or a search's shows\n * the text the model read in a code block, and a command's shows what it\n * printed: in a terminal when the client advertises Zed's terminal extension\n * (`_meta.terminal_output`), and as a `console` code block otherwise.\n *\n * It's keyed by tool name, since nothing ACP-specific may reach the engine's\n * `Tool` type and a card opens with nothing but the name the model called.\n * Only the names the session's `workspace_tools` built count, so in a\n * session that never built them, a tool of the flow's own that shares a\n * name gets the plain card. It does no I/O: the file reads behind a diff\n * happen in the tools, which leave each call's preview in the session's\n * store for its card to take when the call's result arrives.\n */\n\nimport { resolve } from 'node:path'\nimport type { SessionUpdate, ToolCall, ToolCallContent, ToolCallLocation, ToolKind } from '@agentclientprotocol/sdk'\nimport type { StreamChunk } from '#engine'\nimport { as_record } from '#schema'\nimport { shown_path } from './tools/containment.js'\nimport { take_preview } from './tools/previews.js'\nimport type { ChangePreview, CommandPreview, ToolPreview } from './tools/previews.js'\nimport type { AcpSession } from './types.js'\nimport { is_workspace_tool } from './workspace_tools.js'\n\ntype ToolResultChunk = Extract<StreamChunk, { kind: 'tool_result' }>\n\n/** An update to a card the client already shows. */\nexport type CardUpdate = Extract<SessionUpdate, { sessionUpdate: 'tool_call_update' }>\n\n/** What a call's input says about its card: its title, and the places it touches. */\ntype Described = {\n readonly title: string\n readonly locations?: ToolCallLocation[]\n}\n\n/** How a command ended, as its terminal shows it. */\ntype Ran = Pick<CommandPreview, 'output' | 'exit_code' | 'signal'>\n\n/**\n * How one workspace tool's cards look: the kind that picks the icon, what a\n * call's input says about it, and what its card shows once the call\n * succeeds: the change it made, what the command printed, or the text the\n * model read.\n */\ntype Presenter = {\n readonly kind: ToolKind\n readonly describe: (fields: Record<string, unknown>, session: AcpSession) => Described | undefined\n readonly shows?: 'change' | 'command' | 'text'\n}\n\n/**\n * A path the call names, made absolute under the client's `cwd`, which is\n * how a location and a diff carry it.\n */\nfunction absolute(session: AcpSession, path: string): string {\n return resolve(session.cwd, path)\n}\n\n/**\n * A path as a title shows it: relative to `cwd` when it's under it, and\n * absolute otherwise, the way the tools show paths to the model.\n */\nfunction shown(session: AcpSession, path: string): string {\n return shown_path(session, absolute(session, path))\n}\n\n/**\n * The lines a read covers, as its title says them: a range when the call\n * sets a limit, where it starts when it sets only an offset, and nothing\n * when it reads from the top.\n */\nfunction read_range(first: number, offset: unknown, limit: unknown): string {\n if (typeof limit === 'number') return ` (${first} - ${first + limit - 1})`\n if (typeof offset === 'number') return ` (from line ${offset})`\n return ''\n}\n\n/**\n * A `read_file` card: `Read <path>` with the lines it covers, pointing at\n * the line the read starts on.\n */\nfunction describe_read({ path, offset, limit }: Record<string, unknown>, session: AcpSession): Described | undefined {\n if (typeof path !== 'string') return undefined\n const first = typeof offset === 'number' ? offset : 1\n return {\n title: `Read ${shown(session, path)}${read_range(first, offset, limit)}`,\n locations: [{ path: absolute(session, path), line: first }],\n }\n}\n\n/**\n * A `write_file` or `edit_file` card: the verb and the path, pointing at\n * the file. The line an edit lands on comes with its preview, once the\n * edit has found it.\n */\nfunction describe_change(verb: string): Presenter['describe'] {\n return ({ path }, session) =>\n typeof path === 'string'\n ? { title: `${verb} ${shown(session, path)}`, locations: [{ path: absolute(session, path) }] }\n : undefined\n}\n\n/**\n * A `list_files` card: `Find` with the directory and the pattern in code\n * spans, each when the call names it.\n */\nfunction describe_find({ pattern, path }: Record<string, unknown>, session: AcpSession): Described {\n const parts = ['Find']\n if (typeof path === 'string') parts.push(`\\`${shown(session, path)}\\``)\n if (typeof pattern === 'string') parts.push(`\\`${pattern}\\``)\n return { title: parts.join(' ') }\n}\n\n/**\n * A `search` card, titled the way the grep command line that does the same\n * search reads.\n */\nfunction describe_grep({ pattern, path, glob }: Record<string, unknown>, session: AcpSession): Described {\n const parts = ['grep']\n if (typeof glob === 'string') parts.push(`--include=\"${glob}\"`)\n if (typeof pattern === 'string') parts.push(`\"${pattern}\"`)\n if (typeof path === 'string') parts.push(shown(session, path))\n return { title: parts.join(' ') }\n}\n\n/**\n * A `run_command` card, titled with the command line itself.\n */\nfunction describe_command({ command }: Record<string, unknown>): Described | undefined {\n return typeof command === 'string' ? { title: command } : undefined\n}\n\n/**\n * The workspace tools by name. The key takes `undefined` too, so a card\n * whose opening the mapper never saw simply finds nothing.\n */\nconst PRESENTERS = new Map<string | undefined, Presenter>([\n ['read_file', { kind: 'read', describe: describe_read, shows: 'text' }],\n ['list_files', { kind: 'search', describe: describe_find, shows: 'text' }],\n ['search', { kind: 'search', describe: describe_grep, shows: 'text' }],\n ['write_file', { kind: 'edit', describe: describe_change('Write'), shows: 'change' }],\n ['edit_file', { kind: 'edit', describe: describe_change('Edit'), shows: 'change' }],\n ['run_command', { kind: 'execute', describe: describe_command, shows: 'command' }],\n])\n\n/**\n * How the cards of the tool `name` look in `session`, when the session's\n * `workspace_tools` built a tool of that name. Any other tool gets the\n * plain card.\n */\nfunction presenter_of(session: AcpSession, name: string | undefined): Presenter | undefined {\n return is_workspace_tool(session, name) ? PRESENTERS.get(name) : undefined\n}\n\n/**\n * Whether the client draws a command's output in a terminal from Zed's\n * `_meta` extension, which it says in `initialize`.\n */\nfunction renders_terminals(session: AcpSession): boolean {\n const { _meta: meta } = session.client_capabilities\n return meta?.['terminal_output'] === true\n}\n\n/**\n * The terminal a card shows, under the card's own id, as Claude Agent names\n * its terminals.\n */\nfunction terminal(card: string): ToolCallContent {\n return { type: 'terminal', terminalId: card }\n}\n\n/**\n * What a workspace tool's card opens with: its kind, and for a command in a\n * client that draws terminals, the terminal its output will land in.\n */\nexport function opening_fields(session: AcpSession | undefined, name: string, card: string): Partial<ToolCall> {\n // Stryker disable next-line ConditionalExpression: a missing session built no workspace tools, so presenter_of finds nothing for it either way; the check narrows the type.\n if (session === undefined) return {}\n const presenter = presenter_of(session, name)\n if (presenter === undefined) return {}\n if (presenter.shows !== 'command' || !renders_terminals(session)) return { kind: presenter.kind }\n return { kind: presenter.kind, content: [terminal(card)], _meta: { terminal_info: { terminal_id: card } } }\n}\n\n/**\n * What a workspace tool call's complete input adds to its card: its title\n * and locations. An input that lacks what they need leaves the card as it\n * opened.\n */\nexport function input_fields(session: AcpSession | undefined, name: string | undefined, input: unknown): Partial<CardUpdate> {\n // Stryker disable next-line ConditionalExpression: a missing session built no workspace tools, so presenter_of finds nothing for it either way; the check narrows the type.\n if (session === undefined) return {}\n const presenter = presenter_of(session, name)\n if (presenter === undefined) return {}\n return presenter.describe(as_record(input) ?? {}, session) ?? {}\n}\n\n/**\n * A file change as a diff, which a client shows as the file's hunks.\n */\nfunction diff_of(change: ChangePreview): ToolCallContent {\n return { type: 'diff', path: change.path, oldText: change.old_text, newText: change.new_text }\n}\n\n/**\n * Close a write's or an edit's card with the change it made, and for an\n * edit, the line its first match starts on. The closing update replaces the\n * card's content, so it carries the diff again rather than dropping one the\n * card already shows. A call that failed, or left no change behind, closes\n * as it stands.\n */\nfunction close_change(closing: CardUpdate, preview: ToolPreview | undefined): CardUpdate {\n if (preview?.kind !== 'change') return closing\n return {\n ...closing,\n content: [diff_of(preview)],\n ...(preview.line === undefined ? {} : { locations: [{ path: preview.path, line: preview.line }] }),\n }\n}\n\n/**\n * Text in a code block under the `info` string, its fence longer than any\n * run of backticks that opens one of its lines, so nothing in the text can\n * close the block early.\n */\nfunction code_block(text: string, info: string): ToolCallContent {\n const longest = Math.max(2, ...Array.from(text.matchAll(/^`+/gm), ([run]) => run.length))\n const fence = '`'.repeat(longest + 1)\n return { type: 'content', content: { type: 'text', text: `${fence}${info}\\n${text}\\n${fence}` } }\n}\n\n/**\n * Close a read's, a listing's, or a search's card with the text the model\n * read. A listing or a search result goes in a code block too, since a\n * matching line can hold markdown that the client would otherwise render.\n * A failed call keeps its error text.\n */\nfunction close_text(closing: CardUpdate, chunk: ToolResultChunk): CardUpdate {\n if (chunk.error !== undefined) return closing\n return { ...closing, content: [code_block(String(chunk.output), '')] }\n}\n\n/**\n * How a command's terminal ends: what it printed and how it exited, or, for\n * a call that failed or left nothing behind, the error text and no exit\n * code.\n */\nfunction ran(chunk: ToolResultChunk, preview: ToolPreview | undefined): Ran {\n if (preview?.kind === 'command') return preview\n return { output: chunk.error?.message ?? '', exit_code: null, signal: null }\n}\n\n/**\n * Close a command's card. A client that draws terminals gets the output on\n * the terminal the card opened with, then the exit and the status, as\n * Claude Agent sends them. Any other client gets what the model read, its\n * exit code included, in a `console` block; a failed call keeps its error\n * text.\n */\nfunction close_command(\n session: AcpSession,\n card: string,\n chunk: ToolResultChunk,\n closing: CardUpdate,\n preview: ToolPreview | undefined,\n): SessionUpdate[] {\n if (!renders_terminals(session)) {\n if (chunk.error !== undefined) return [closing]\n return [{ ...closing, content: [code_block(String(chunk.output), 'console')] }]\n }\n const { output, exit_code, signal } = ran(chunk, preview)\n return [\n {\n sessionUpdate: 'tool_call_update',\n toolCallId: card,\n _meta: { terminal_output: { terminal_id: card, data: output } },\n },\n {\n ...closing,\n content: [terminal(card)],\n _meta: { terminal_exit: { terminal_id: card, exit_code, signal } },\n },\n ]\n}\n\n/**\n * The updates that close a tool call's card, starting from the plain\n * `closing` update. A read, a listing, or a search leaves no preview, so its\n * card takes nothing from the session's store. A successful call of a tool\n * that leaves a preview takes it from the store whatever the card then does\n * with it, which keeps each raw id's queue in step with its results.\n */\nexport function closing_updates(\n session: AcpSession | undefined,\n name: string | undefined,\n card: string,\n chunk: ToolResultChunk,\n closing: CardUpdate,\n): SessionUpdate[] {\n // Stryker disable next-line ConditionalExpression: a missing session built no workspace tools, so presenter_of finds nothing for it either way; the check narrows the type.\n if (session === undefined) return [closing]\n const shows = presenter_of(session, name)?.shows\n if (shows === undefined) return [closing]\n if (shows === 'text') return [close_text(closing, chunk)]\n const preview = chunk.error === undefined ? take_preview(session, chunk.id) : undefined\n if (shows === 'change') return [close_change(closing, preview)]\n return close_command(session, card, chunk, closing, preview)\n}\n","/**\n * approve: ask the client before a workspace tool edits a file or runs a\n * command, through `session/request_permission`.\n *\n * The request shows the card the client already draws for the call, and\n * for an edit, the change worked out on disk first, so the user approves\n * the diff itself. It offers Allow, Reject, and an \"always\" that lives in\n * memory for the session. For an edit, \"always\" switches the session to\n * Accept edits, as Claude Agent's does, and tells the client both ways so\n * its mode picker follows. An edit is offered one only when the agent\n * offers Accept edits, since that's the mode it switches to. For a\n * command, it covers that exact command line and nothing else, since one\n * flag can turn a listing into a delete (`find . -name '*.ts'` and\n * `find . -delete`). A command with shell control syntax is never covered\n * and never offered one, since anything can follow a `;` or a `|`.\n *\n * Only the session's own workspace tools get the diff and the \"always\",\n * known by the input their `needs_approval` marked rather than by name. The\n * tools of the MCP servers the client sent ask as a command does, and their\n * \"always\" covers that one tool for the session. A tool of a flow's own\n * that shares a name with either gets the plain request, and no grant\n * covers it.\n *\n * A permission check that fails open isn't a check, so anything short of\n * an allow denies the call: a rejection, a `cancelled` outcome, an option\n * the request never offered, and a request that fails for any reason.\n *\n * The engine asks with its raw call id, which can repeat inside a turn,\n * and the turn's consumer can still be sending earlier updates when it\n * asks. So the request waits until the consumer has sent everything the\n * run had recorded by then, the card's opening included, and points at the\n * latest card the client was sent for that raw id. The consumer never\n * waits on an approval, so the wait can't deadlock, and the turn's abort\n * ends it.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type {\n PermissionOption,\n RequestPermissionOutcome,\n RequestPermissionRequest,\n RequestPermissionResponse,\n SessionUpdate,\n ToolCallUpdate,\n} from '@agentclientprotocol/sdk'\nimport type { TrajectoryEvent, TrajectoryLogger } from '#core'\nimport type { ToolApprovalRequest } from '#engine'\nimport { as_record } from '#schema'\nimport { asks_before } from './modes.js'\nimport type { SessionModes } from './modes.js'\nimport { is_mcp_call } from './mcp_servers.js'\nimport { input_fields, opening_fields } from './presentation.js'\nimport { edit_file_change } from './tools/edit_file.js'\nimport { write_file_change } from './tools/write_file.js'\nimport type { ShownChange } from './tools/write_file.js'\nimport type { AcpSession } from './types.js'\nimport { is_workspace_call } from './workspace_tools.js'\n\n/**\n * What a session's turn tells its approvals: how far the turn's consumer\n * has got, and which card each raw call id opened last.\n *\n * A run that outran the client so far that it dropped events never lets\n * the consumer catch up, so an approval it asks for waits until the turn\n * is cancelled. Only a client that has stopped reading gets that far\n * behind, and it wouldn't answer the request either.\n */\nexport type CardSync = {\n /**\n * Start a turn, forgetting the last one. Returns the logger the turn's\n * run records through, which counts every event `run.stream` queues and\n * passes each one on to `inner`.\n */\n readonly start: (inner: TrajectoryLogger | undefined) => TrajectoryLogger\n /** Note that the consumer has sent every update one event maps to. */\n readonly sent: (event: TrajectoryEvent, updates: ReadonlyArray<SessionUpdate>) => void\n /** Settle once the consumer has sent every event the run had recorded by now. */\n readonly caught_up: () => Promise<void>\n /** The id of the latest card the client was sent for a raw call id. */\n readonly card_for: (raw_id: string) => string | undefined\n}\n\n/** One turn's count of the events its run recorded and its consumer sent. */\ntype TurnProgress = {\n recorded: number\n sent: number\n /** Settles at the consumer's next event, then gives way to a fresh one. */\n moved: PromiseWithResolvers<void>\n readonly cards: Map<string, string>\n}\n\n/**\n * Asks the client to approve one tool call, and withdraws the request\n * when `cancel` fires.\n */\nexport type PermissionAsker = (\n request: RequestPermissionRequest,\n cancel: AbortSignal,\n) => Promise<RequestPermissionResponse>\n\n/** What a session's approvals need beside the session itself. */\nexport type ApproverDeps = {\n readonly modes: SessionModes\n readonly cards: CardSync\n readonly ask: PermissionAsker\n}\n\n/** Answers the engine's approval requests for the calls in one session. */\nexport type SessionApprover = (session: AcpSession, request: ToolApprovalRequest) => Promise<boolean>\n\n/** What an \"always\" for one call covers, under the name the request offers it by. */\ntype Grant = { readonly key: string; readonly name: string }\n\n/**\n * How a call that asks is shown and what may cover it: for a write or an\n * edit, how to work out its change without making it, which also makes it\n * an edit that Accept edits covers, and for a command or an MCP call, what\n * a grant for the session covers. A workspace tool's gate goes by name, but\n * only a call the session's own workspace tool marked ever reaches one.\n */\ntype Gate = {\n readonly change?: (session: AcpSession, input: unknown) => Promise<ShownChange>\n readonly grant?: (request: ToolApprovalRequest) => Grant | undefined\n}\n\nconst GATES: ReadonlyMap<string, Gate> = new Map<string, Gate>([\n ['write_file', { change: write_file_change }],\n ['edit_file', { change: edit_file_change }],\n [\n 'run_command',\n {\n grant: (request) => {\n const line = command_key(request.input)\n return line === undefined ? undefined : { key: `command ${line}`, name: `Always allow \\`${line}\\` this session` }\n },\n },\n ],\n])\n\n/** The gate every MCP tool's call goes through: it asks as a command does, and the grant covers the tool. */\nconst MCP_GATE: Gate = {\n grant: (request) => ({ key: `tool ${request.tool_name}`, name: `Always allow ${request.tool_name} this session` }),\n}\n\n/**\n * The gate a call goes through: its workspace tool's, the MCP tools' for a\n * call one of the session's MCP tools marked, and none for any other call.\n */\nfunction gate_for(session: AcpSession, request: ToolApprovalRequest): Gate | undefined {\n if (is_workspace_call(session, request.input)) return GATES.get(request.tool_name)\n return is_mcp_call(session, request.input) ? MCP_GATE : undefined\n}\n\n/**\n * Shell syntax that runs, chains, or redirects something past the\n * command's own program: `;`, `&`, `|`, `>`, `<`, a backtick, `$(`, and a\n * newline.\n */\nconst CONTROL_SYNTAX = /[;&|<>`\\n]|\\$\\(/\n\n/** The \"always\" an approval offers, and what choosing it grants. */\ntype Always = {\n readonly name: string\n readonly grant: () => Promise<void>\n}\n\nconst ALLOW_ONCE: PermissionOption = { optionId: 'allow_once', name: 'Allow', kind: 'allow_once' }\nconst REJECT_ONCE: PermissionOption = { optionId: 'reject_once', name: 'Reject', kind: 'reject_once' }\n\n/**\n * A fresh count for a turn that has recorded and sent nothing yet.\n */\nfunction fresh_progress(): TurnProgress {\n return { recorded: 0, sent: 0, moved: Promise.withResolvers(), cards: new Map() }\n}\n\n/**\n * `inner`, or nothing, with `count` called after each call that queues an\n * event. Without an inner logger, a span gets an id of its own, as the\n * runner's default logger gives one.\n */\nfunction counting_logger(inner: TrajectoryLogger | undefined, count: () => void): TrajectoryLogger {\n return {\n record: (event) => {\n inner?.record(event)\n count()\n },\n start_span: (name, meta) => {\n const id = inner?.start_span(name, meta) ?? `${name}:${randomUUID()}`\n count()\n return id\n },\n end_span: (id, meta) => {\n inner?.end_span(id, meta)\n count()\n },\n }\n}\n\n/**\n * The raw id of the call a `tool_call_start` chunk opens, or `undefined`\n * for any other event.\n */\nfunction started_call(event: TrajectoryEvent): string | undefined {\n if (event.kind !== 'model_chunk') return undefined\n const chunk = as_record(event['chunk'])\n // Stryker disable next-line ConditionalExpression: a non-string id would land under a key no string lookup finds, so the check only narrows the type.\n return chunk?.['kind'] === 'tool_call_start' && typeof chunk['id'] === 'string' ? chunk['id'] : undefined\n}\n\n/**\n * Whether an update opens a card.\n */\nfunction opens_card(update: SessionUpdate): update is Extract<SessionUpdate, { sessionUpdate: 'tool_call' }> {\n return update.sessionUpdate === 'tool_call'\n}\n\n/**\n * Create the sync between a session's turns and its approvals. Turns in a\n * session never overlap, so one sync serves them all, a turn at a time.\n */\nexport function create_card_sync(): CardSync {\n let turn = fresh_progress()\n return {\n start: (inner) => {\n const started = fresh_progress()\n turn = started\n return counting_logger(inner, () => {\n started.recorded += 1\n })\n },\n sent: (event, updates) => {\n const raw_id = started_call(event)\n const card = updates.find(opens_card)\n // Stryker disable next-line ConditionalExpression: a card noted under no raw id sits where no lookup asks, so the check only narrows the type.\n if (raw_id !== undefined && card !== undefined) turn.cards.set(raw_id, card.toolCallId)\n turn.sent += 1\n turn.moved.resolve()\n turn.moved = Promise.withResolvers()\n },\n caught_up: async () => {\n const waiting = turn\n const target = waiting.recorded\n while (waiting.sent < target) await waiting.moved.promise\n },\n card_for: (raw_id) => turn.cards.get(raw_id),\n }\n}\n\n/**\n * What an \"always\" grant for a command covers: the command line itself,\n * with the whitespace at its ends trimmed and everything between compared\n * exactly, because `rm \"a b\"` and `rm \"a b\"` name different files. A\n * command with shell control syntax has none, so no grant ever covers it,\n * and neither does one that isn't a string or is only whitespace.\n */\nexport function command_key(input: unknown): string | undefined {\n const command = as_record(input)?.['command']\n if (typeof command !== 'string' || CONTROL_SYNTAX.test(command)) return undefined\n const key = command.trim()\n return key === '' ? undefined : key\n}\n\n/**\n * The message a failure carries, whatever was thrown.\n */\nexport function message_of(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\n/**\n * Start `work` and settle with it, or reject with the abort's reason as\n * soon as `abort` fires, so a turn's cancel never waits on the client. A\n * turn already cancelled starts nothing, so no request goes out for it.\n */\nasync function unless_aborted<T>(abort: AbortSignal, work: () => Promise<T>): Promise<T> {\n abort.throwIfAborted()\n const { promise: aborted, reject } = Promise.withResolvers<never>()\n const on_abort = (): void => {\n reject(abort.reason)\n }\n abort.addEventListener('abort', on_abort)\n try {\n return await Promise.race([work(), aborted])\n } finally {\n // The turn's signal outlives every approval it asks for.\n abort.removeEventListener('abort', on_abort)\n }\n}\n\n/**\n * What a change adds to the request's card: its diff, and for an edit,\n * the line its first match starts on. A change that can't be worked out\n * shows why instead, which is what the call will fail with if it's\n * allowed, so the user isn't asked to approve a change they can't see.\n */\nasync function change_fields(\n change: NonNullable<Gate['change']>,\n session: AcpSession,\n input: unknown,\n): Promise<Partial<ToolCallUpdate>> {\n try {\n const { path, old_text, new_text, line } = await change(session, input)\n return {\n content: [{ type: 'diff', path, oldText: old_text, newText: new_text }],\n ...(line === undefined ? {} : { locations: [{ path, line }] }),\n }\n } catch (err: unknown) {\n return { content: [{ type: 'content', content: { type: 'text', text: message_of(err) } }] }\n }\n}\n\n/**\n * The card a request shows: the one the client already draws for the call\n * under `card`, as its tool's presentation describes it, with the change\n * for a write or an edit.\n *\n * A tool with no presenter names no kind. The client applies a request's\n * fields to the card it already drew, so a kind sent here would replace the\n * one the card's own opening gave it, and an absent kind leaves it as it was.\n */\nasync function permission_card(\n session: AcpSession,\n request: ToolApprovalRequest,\n card: string,\n gate: Gate | undefined,\n): Promise<ToolCallUpdate> {\n const { tool_name: name, input } = request\n const { kind } = opening_fields(session, name, card)\n const fields: ToolCallUpdate = {\n toolCallId: card,\n title: name,\n ...(kind === undefined ? {} : { kind }),\n rawInput: input,\n ...input_fields(session, name, input),\n }\n if (gate?.change === undefined) return fields\n return { ...fields, ...(await change_fields(gate.change, session, input)) }\n}\n\n/**\n * Whether the user's answer allows the call, granting the \"always\" first\n * when that's what they chose. Only an option the request offered counts.\n */\nasync function allowed(outcome: RequestPermissionOutcome, always: Always | undefined): Promise<boolean> {\n if (outcome.outcome !== 'selected') return false\n if (outcome.optionId === ALLOW_ONCE.optionId) return true\n if (outcome.optionId !== 'allow_always' || always === undefined) return false\n await always.grant()\n return true\n}\n\n/**\n * Say on stderr that a permission request failed, since the call was\n * refused without the user ever seeing it.\n */\nfunction warn_failed(tool_name: string, err: unknown): void {\n process.stderr.write(\n `fascicle/acp: asking the client to approve ${tool_name} failed (${message_of(err)}), so the call was refused; check that the client answers session/request_permission\\n`,\n )\n}\n\n/**\n * The \"always\" a call is offered: Accept edits for an edit, when the agent\n * offers that mode, and the grant its gate makes for a command line or an\n * MCP tool. Any other call gets none. Choosing Accept edits leaves a session\n * that has moved past Manual since the call asked where it is.\n */\nfunction always_for(\n gate: Gate | undefined,\n grant: Grant | undefined,\n modes: SessionModes,\n granted: Set<string>,\n): Always | undefined {\n if (gate?.change !== undefined) {\n if (!modes.offers('accept_edits')) return undefined\n return {\n name: 'Allow all edits this session',\n grant: async () => {\n if (asks_before(modes.current(), 'edit')) await modes.switch_to('accept_edits')\n },\n }\n }\n if (grant === undefined) return undefined\n return {\n name: grant.name,\n grant: async () => {\n granted.add(grant.key)\n },\n }\n}\n\n/**\n * The options a request offers. Allow is always among them, since some\n * hosts answer every request on their own by choosing `allow_once`.\n */\nfunction options_for(always: Always | undefined): PermissionOption[] {\n if (always === undefined) return [ALLOW_ONCE, REJECT_ONCE]\n return [ALLOW_ONCE, { optionId: 'allow_always', name: always.name, kind: 'allow_always' }, REJECT_ONCE]\n}\n\n/**\n * Create the approvals for one session's calls, holding its commands'\n * \"always\" grants for the life of the session.\n */\nexport function session_approver({ modes, cards, ask }: ApproverDeps): SessionApprover {\n const granted = new Set<string>()\n return async (session, request) => {\n const gate = gate_for(session, request)\n const grant = gate?.grant?.(request)\n // Stryker disable next-line ConditionalExpression: only grants' keys are ever granted, so has() answers false without one either way; the check narrows the type.\n if (grant !== undefined && granted.has(grant.key)) return true\n const always = always_for(gate, grant, modes, granted)\n const options = options_for(always)\n try {\n await unless_aborted(request.abort, cards.caught_up)\n const card = cards.card_for(request.tool_call_id) ?? randomUUID()\n const toolCall = await permission_card(session, request, card, gate)\n const answer = await unless_aborted(request.abort, () =>\n ask({ sessionId: session.id, toolCall, options }, request.abort),\n )\n return await allowed(answer.outcome, always)\n } catch (err: unknown) {\n if (!request.abort.aborted) warn_failed(request.tool_name, err)\n return false\n }\n }\n}\n","/**\n * models: the models a session can run on, offered to the client as a\n * config option in the `model` category, which Zed draws as its model\n * picker.\n *\n * ACP v1 has no model field of its own, so the config option is how the\n * protocol carries one. Each model's id is the agent's, and the flow builder\n * reads it from `session.model()`. A model call takes its model as it's\n * built, so the agent builds the session's flow again whenever the user\n * picks another model, and the pick holds from the next turn on. A model may\n * name its own context window, which the context ring is drawn against while\n * the session runs on it.\n */\n\nimport type { SessionConfigOption } from '@agentclientprotocol/sdk'\nimport type { AcpModel } from './types.js'\n\n/** The id of the config option that carries the model. */\nexport const MODEL_CONFIG_ID = 'model'\n\n/** The models an agent offers and the one each of its sessions starts on. */\nexport type ModelOffer = {\n readonly models: ReadonlyArray<AcpModel>\n readonly default_model: string\n}\n\n/**\n * The models an agent offers, from the config's `models` and\n * `default_model`, or undefined for an agent that offers none. Throws an\n * `Error` that names the problem for a `models` that's empty or lists an id\n * twice, a `default_model` it doesn't list, a `default_model` without\n * `models`, and a flow built once, which can't change its model, so\n * `acp_agent` fails as it's built.\n */\nexport function model_offer(config: {\n readonly models?: ReadonlyArray<AcpModel> | undefined\n readonly default_model?: string | undefined\n readonly flow: unknown\n}): ModelOffer | undefined {\n const { models, default_model } = config\n if (models === undefined) {\n if (default_model === undefined) return undefined\n throw new Error('acp_agent: default_model is set without models; list the models a session can run on, or leave default_model out')\n }\n if (typeof config.flow !== 'function') {\n throw new Error(\n \"acp_agent: models needs flow to be a function of the session, since a flow built once can't change its model; build the flow with session.model()\",\n )\n }\n const ids = models.map((model) => model.id)\n const [first] = ids\n if (first === undefined) throw new Error('acp_agent: models is empty; list at least one model, or leave models out')\n const repeated = ids.find((id, index) => ids.indexOf(id) !== index)\n if (repeated !== undefined) {\n throw new Error(`acp_agent: models lists ${JSON.stringify(repeated)} twice; give each model its own id`)\n }\n const start = default_model ?? first\n if (!ids.includes(start)) {\n throw new Error(\n `acp_agent: default_model ${JSON.stringify(start)} isn't one of the models (${ids.join(', ')}); add it to models or leave default_model out`,\n )\n }\n return { models, default_model: start }\n}\n\n/**\n * Whether the agent offers a model with the id `id`.\n */\nexport function offers_model(offer: ModelOffer, id: unknown): id is string {\n return offer.models.some((model) => model.id === id)\n}\n\n/**\n * The model a session starts on: the one it was stored with when the agent\n * still offers it, and the offer's `default_model` otherwise, or undefined\n * for an agent that offers none.\n */\nexport function start_model(offer: ModelOffer | undefined, stored: string | undefined): string | undefined {\n if (offer === undefined) return undefined\n return offers_model(offer, stored) ? stored : offer.default_model\n}\n\n/**\n * The refusal for a model id the agent doesn't offer, naming the ones it does.\n */\nexport function unknown_model_message(id: unknown, offer: ModelOffer): string {\n return `unknown model ${JSON.stringify(id)}; choose one of ${offer.models.map((model) => model.id).join(', ')}`\n}\n\n/**\n * The session's model as a config option, a select over every model the\n * agent offers, or none for an agent that offers no models.\n */\nexport function model_options(offer: ModelOffer | undefined, model: string | undefined): SessionConfigOption[] {\n if (offer === undefined || model === undefined) return []\n return [\n {\n id: MODEL_CONFIG_ID,\n name: 'Model',\n description: 'The model that answers the next turn',\n category: 'model',\n type: 'select',\n currentValue: model,\n options: offer.models.map(({ id, name, description }) => ({\n value: id,\n name: name ?? id,\n ...(description === undefined ? {} : { description }),\n })),\n },\n ]\n}\n\n/**\n * The context window a session's context ring is drawn against: the\n * window its model names, and the config's `context_window` otherwise.\n */\nexport function context_window_of(\n config: { readonly models?: ReadonlyArray<AcpModel> | undefined; readonly context_window?: number | undefined },\n model: string | undefined,\n): number | undefined {\n return config.models?.find((entry) => entry.id === model)?.context_window ?? config.context_window\n}\n","/**\n * Maps a run's events onto ACP `session/update` payloads.\n *\n * Under `run.stream`, each `model_call` records `model_chunk` events carrying\n * the engine's `StreamChunk`, the same source fascicle/ui reads. This half of\n * a prompt turn does no I/O and holds no SDK value, so a flow author can wrap\n * `to_session_updates` in their own `to_updates` and add to what it returns,\n * as long as every event still reaches it: each `span_start` advances the\n * state's count of how many times a step has run, and a workspace tool's\n * result takes its call's preview from the session's store. Spans, `cost`,\n * and `emit` events map to nothing; an `emit` never becomes chat output\n * implicitly, because output that changes with a value's shape is a trap.\n *\n * Every tool gets a plain card here. Given the turn's session, the workspace\n * tools' cards also take the look `presentation.ts` gives them.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type { ContentBlock, SessionUpdate } from '@agentclientprotocol/sdk'\nimport type { TrajectoryEvent } from '#core'\nimport type { StreamChunk } from '#engine'\nimport { closing_updates, input_fields, opening_fields } from './presentation.js'\nimport type { CardUpdate } from './presentation.js'\nimport type { AcpMapperOptions, AcpMapperState, AcpStreamRoute } from './types.js'\n\ntype ToolResultChunk = Extract<StreamChunk, { kind: 'tool_result' }>\n\n/**\n * Create the state for one prompt turn's events, routing every model call's\n * text to the reply unless `stream` says otherwise.\n */\nexport function create_acp_mapper_state(options: AcpMapperOptions = {}): AcpMapperState {\n return {\n turn_id: options.turn_id ?? randomUUID(),\n stream: options.stream ?? (() => 'message'),\n runs: new Map(),\n session: options.session,\n tools: new Map(),\n }\n}\n\n/**\n * Build the session-unique ACP id for an engine tool call id.\n *\n * Raw ids repeat across model calls, turns, and runs of one model call\n * (Ollama has none on the wire, so the engine numbers them\n * `ollama_call_<step>_<n>` afresh on every generate call), and a repeated id\n * would make the client update an old card instead of opening a new one.\n */\nfunction acp_tool_call_id(state: AcpMapperState, step_id: string, raw_id: string): string {\n return `${state.turn_id}:${step_id}:${state.runs.get(step_id) ?? 0}:${raw_id}`\n}\n\n/**\n * Count one more run of the step a `span_start` opens, by the `id` its span\n * carries. Counting starts rather than finishes covers a retry whose first\n * attempt failed before it finished.\n */\nfunction count_run(event: TrajectoryEvent, state: AcpMapperState): void {\n const id = event['id']\n if (typeof id === 'string') state.runs.set(id, (state.runs.get(id) ?? 0) + 1)\n}\n\n/**\n * Wrap streamed text as the update its route names, or nothing for `'none'`.\n */\nfunction text_updates(route: AcpStreamRoute, text: string): SessionUpdate[] {\n const content: ContentBlock = { type: 'text', text }\n if (route === 'message') return [{ sessionUpdate: 'agent_message_chunk', content }]\n if (route === 'thought') return [{ sessionUpdate: 'agent_thought_chunk', content }]\n return []\n}\n\n/**\n * Close a tool card: `completed` with the raw output, or `failed` with the\n * error text as the card's content, since that text is what the user needs\n * to see.\n */\nfunction tool_result_update(tool_call_id: string, chunk: ToolResultChunk): CardUpdate {\n if (chunk.error !== undefined) {\n return {\n sessionUpdate: 'tool_call_update',\n toolCallId: tool_call_id,\n status: 'failed',\n content: [{ type: 'content', content: { type: 'text', text: chunk.error.message } }],\n }\n }\n return {\n sessionUpdate: 'tool_call_update',\n toolCallId: tool_call_id,\n status: 'completed',\n rawOutput: chunk.output,\n }\n}\n\n/**\n * Map one engine `StreamChunk` from the model call `step_id` to the session\n * updates it produces.\n */\nfunction map_chunk(chunk: StreamChunk, step_id: string, state: AcpMapperState): SessionUpdate[] {\n switch (chunk.kind) {\n case 'text':\n return text_updates(state.stream(step_id), chunk.text)\n case 'reasoning':\n return text_updates('thought', chunk.text)\n case 'tool_call_start': {\n const card = acp_tool_call_id(state, step_id, chunk.id)\n state.tools.set(card, chunk.name)\n return [\n {\n sessionUpdate: 'tool_call',\n toolCallId: card,\n title: chunk.name,\n kind: 'other',\n status: 'pending',\n ...opening_fields(state.session, chunk.name, card),\n },\n ]\n }\n case 'tool_call_end': {\n const card = acp_tool_call_id(state, step_id, chunk.id)\n return [\n {\n sessionUpdate: 'tool_call_update',\n toolCallId: card,\n status: 'in_progress',\n rawInput: chunk.input,\n ...input_fields(state.session, state.tools.get(card), chunk.input),\n },\n ]\n }\n case 'tool_result': {\n const card = acp_tool_call_id(state, step_id, chunk.id)\n return closing_updates(state.session, state.tools.get(card), card, chunk, tool_result_update(card, chunk))\n }\n default:\n // The input arrives whole at tool_call_end, so its deltas add nothing,\n // and step_finish and finish carry no content for the client.\n return []\n }\n}\n\n/**\n * Narrow the loose `chunk` field of a `model_chunk` event. model_call records\n * only real StreamChunks there, and map_chunk maps a kind it doesn't know to\n * nothing, so ruling out a missing or null value is enough.\n */\nexport function is_stream_chunk(value: unknown): value is StreamChunk {\n return typeof value === 'object' && value !== null\n}\n\n/**\n * Map one run event to zero or more ACP session updates. Only `model_chunk`\n * events produce any. A `span_start` advances the state's run count, a\n * card's opening records its tool, and a workspace tool's result takes its\n * preview; the function does no I/O.\n */\nexport function to_session_updates(event: TrajectoryEvent, state: AcpMapperState): SessionUpdate[] {\n if (event.kind === 'span_start') {\n count_run(event, state)\n return []\n }\n if (event.kind !== 'model_chunk') return []\n const step_id = event['step_id']\n const chunk = event['chunk']\n if (typeof step_id !== 'string' || !is_stream_chunk(chunk)) return []\n return map_chunk(chunk, step_id, state)\n}\n","/**\n * usage: what a session has spent and how full its context is, read off the\n * run events of its turns, and the stop reason a turn's model calls earn.\n *\n * The engine's tool loop records a `response_received` event for each model\n * turn and a `cost` event for each turn it prices, and a model call records\n * a `finish` chunk once its loop ends. A provider that runs its own loop,\n * such as `claude_cli`, reports each turn as a `step_finish` chunk instead,\n * and some providers send both. The context a session holds is the last\n * model turn's input and output, since the next turn sends all of it again,\n * and its cost is the sum of every priced turn. The client draws both as a\n * context ring, which needs the model's context window, so the agent sends\n * them only when its config names one.\n */\n\nimport type { SessionUpdate, StopReason } from '@agentclientprotocol/sdk'\nimport type { TrajectoryEvent } from '#core'\nimport type { FinishReason, StreamChunk } from '#engine'\nimport { is_stream_chunk } from './to_session_updates.js'\n\n/** What a session has spent so far, kept across its turns. */\nexport type SessionUsage = {\n /** The last model turn's input and output tokens, which the next turn sends again. */\n context_tokens: number\n /** Every priced model turn's cost, in US dollars. */\n cost_usd: number\n /** Whether any model turn was priced; the client hears no cost until one is. */\n priced: boolean\n}\n\n/**\n * A session's usage before its first turn.\n */\nexport function create_session_usage(): SessionUsage {\n return { context_tokens: 0, cost_usd: 0, priced: false }\n}\n\n/**\n * The stream chunk a `model_chunk` event carries, or undefined for any other\n * event.\n */\nfunction chunk_of(event: TrajectoryEvent): StreamChunk | undefined {\n if (event.kind !== 'model_chunk') return undefined\n const chunk = event['chunk']\n return is_stream_chunk(chunk) ? chunk : undefined\n}\n\n/**\n * The tokens a model turn left in the context, from either way a turn is\n * reported, or undefined for any other event.\n */\nfunction context_of(event: TrajectoryEvent): number | undefined {\n if (event.kind === 'response_received') {\n const input = event['input_tokens']\n const output = event['output_tokens']\n return typeof input === 'number' && typeof output === 'number' ? input + output : undefined\n }\n const chunk = chunk_of(event)\n return chunk?.kind === 'step_finish' ? chunk.usage.input_tokens + chunk.usage.output_tokens : undefined\n}\n\n/**\n * Fold one run event into the session's usage, and say whether it changed,\n * so a turn that a provider reports twice tells the client once.\n */\nexport function note_usage(usage: SessionUsage, event: TrajectoryEvent): boolean {\n if (event.kind === 'cost') {\n const total = event['total_usd']\n if (typeof total !== 'number') return false\n usage.cost_usd += total\n usage.priced = true\n return true\n }\n const context = context_of(event)\n if (context === undefined || context === usage.context_tokens) return false\n usage.context_tokens = context\n return true\n}\n\n/**\n * The session's usage as the update a client draws its context ring from,\n * against a context window of `size` tokens.\n */\nexport function usage_update(usage: SessionUsage, size: number): SessionUpdate {\n return {\n sessionUpdate: 'usage_update',\n used: usage.context_tokens,\n size,\n ...(usage.priced ? { cost: { amount: usage.cost_usd, currency: 'USD' } } : {}),\n }\n}\n\n/**\n * The finish reason a model call's `finish` chunk carries, or undefined for\n * any other event.\n */\nexport function finish_reason_of(event: TrajectoryEvent): FinishReason | undefined {\n const chunk = chunk_of(event)\n return chunk?.kind === 'finish' ? chunk.finish_reason : undefined\n}\n\n/**\n * The stop reason for a turn that wasn't cancelled, from the finish reason of\n * the last model call that finished in it, which is the one whose reply the\n * user reads. A call that ran out of tool turns, ran out of output tokens, or\n * was stopped by the provider's filter says so, rather than reading as a turn\n * that finished.\n */\nexport function stop_reason_for(finish: FinishReason | undefined): StopReason {\n if (finish === 'max_steps') return 'max_turn_requests'\n if (finish === 'length') return 'max_tokens'\n if (finish === 'content_filter') return 'refusal'\n return 'end_turn'\n}\n","/**\n * One ACP prompt turn: run the session's flow through `run.stream` and send\n * what it produces to the client as session updates.\n *\n * The turn holds three rules the protocol leaves to the agent. A cancel\n * (`session/cancel`, the request's own `$/cancel_request`, a disconnect, or\n * the config's `abort`) stops the sending at once, then waits for the run to\n * settle and answers `cancelled`, even when the flow ignored the abort and\n * finished. A turn that sent no message text sends `to_text(output)` as its\n * reply. And the history records what the client was actually sent, a\n * cancelled turn included, so it matches the thread the user sees.\n */\n\nimport type { ContentBlock, PromptResponse, SessionUpdate } from '@agentclientprotocol/sdk'\nimport { aborted_error, run } from '#core'\nimport type { Step, TrajectoryEvent } from '#core'\nimport type { FinishReason } from '#engine'\nimport type { CardSync } from './approve.js'\nimport { context_window_of } from './models.js'\nimport { create_acp_mapper_state, to_session_updates } from './to_session_updates.js'\nimport { reset_previews } from './tools/previews.js'\nimport { finish_reason_of, note_usage, stop_reason_for, usage_update } from './usage.js'\nimport type { SessionUsage } from './usage.js'\nimport type { AcpHistoryEntry, AcpSession, AcpTurn, ServeAcpConfig } from './types.js'\n\n/**\n * A session's latest turn, finished or not. Cancelling a finished turn does\n * nothing and waiting on it returns at once, so the record never needs\n * clearing.\n */\ntype TurnHandle = {\n readonly cancel: AbortController\n readonly settled: Promise<void>\n}\n\n/**\n * A session between turns: its flow, its history, its latest turn, the sync\n * that lets its approvals wait for the client to catch up, what it has spent,\n * and its title, which stays null until its first turn names it.\n */\nexport type SessionRecord<i, o> = {\n readonly session: AcpSession\n /** Built again when the user picks another model, so a turn reads it as it starts. */\n flow: Step<i, o>\n readonly history: AcpHistoryEntry[]\n readonly cards: CardSync\n readonly usage: SessionUsage\n last_turn: TurnHandle | null\n title: string | null\n}\n\nexport type SendUpdate = (update: SessionUpdate) => Promise<void>\n\ntype Reply = { sent: boolean; text: string; card_since_text: boolean }\n\ntype Settled<o> = { readonly ok: true; readonly output: o } | { readonly ok: false; readonly error: unknown }\n\n/**\n * Join a prompt's blocks into the text a flow reads. Text blocks join as the\n * client split them, and a resource link or an embedded resource reads as\n * its URI where it sat. Each embedded resource's text follows the prompt in\n * a `<context>` block naming that URI, the form Claude Agent uses, so a file\n * the user @-mentioned reaches the model without splitting the sentence that\n * mentions it. Image and audio blocks stay in `turn.prompt` only, since the\n * agent advertises neither.\n */\nfunction turn_text(prompt: ReadonlyArray<ContentBlock>): string {\n const inline: string[] = []\n const context: string[] = []\n for (const block of prompt) {\n if (block.type === 'text') inline.push(block.text)\n else if (block.type === 'resource_link') inline.push(block.uri)\n else if (block.type === 'resource') {\n inline.push(block.resource.uri)\n if ('text' in block.resource) {\n context.push(`<context ref=\"${block.resource.uri}\">\\n${block.resource.text}\\n</context>`)\n }\n }\n }\n return [inline.join(''), ...context].join('\\n\\n')\n}\n\n/**\n * The flow's input for a turn: the config's `to_input`, or the turn's text,\n * which `ServeAcpConfig` allows only when the flow takes a string.\n */\nfunction turn_input<i, o>(config: ServeAcpConfig<i, o>, turn: AcpTurn): i {\n if (config.to_input !== undefined) return config.to_input(turn)\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return turn.text as i\n}\n\n/** The most characters a default title keeps. */\nconst TITLE_LIMIT = 60\n\n/**\n * The default `to_title`: the first line of the turn's text with its\n * whitespace collapsed, cut to `TITLE_LIMIT` characters.\n */\nfunction default_title(turn: AcpTurn): string {\n const line = turn.text.split('\\n').find((text) => text.trim() !== '') ?? ''\n const words = line.trim().replaceAll(/\\s+/g, ' ')\n return words.length <= TITLE_LIMIT ? words : `${words.slice(0, TITLE_LIMIT - 1).trimEnd()}…`\n}\n\n/**\n * Name the session from its first turn, and tell the client, which shows it\n * on the thread. A session already named keeps its title, and an empty one\n * leaves the thread untitled.\n */\nasync function name_session<i, o>(\n config: ServeAcpConfig<i, o>,\n record: SessionRecord<i, o>,\n turn: AcpTurn,\n send: SendUpdate,\n): Promise<void> {\n if (record.title !== null) return\n record.title = (config.to_title ?? default_title)(turn)\n if (record.title !== '') await send({ sessionUpdate: 'session_info_update', title: record.title })\n}\n\n/**\n * The default `to_text`: a string as-is, anything else as JSON, and nothing\n * at all for a flow that returns nothing.\n */\nfunction default_to_text(output: unknown): string {\n return typeof output === 'string' ? output : (JSON.stringify(output) ?? '')\n}\n\n/**\n * Wrap a turn's final text as the message update that carries it.\n */\nfunction agent_message(text: string): SessionUpdate {\n return { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text } }\n}\n\n/**\n * Count a message update the client was sent toward the turn's reply. Only\n * text joins the reply's text, but any message counts as a reply, so a flow\n * that sent an image doesn't get a `to_text` message after it. A tool card\n * that opened after some reply text splits the reply in two on the client,\n * so the recorded text starts the next run on a blank line instead of\n * running the two together.\n */\nfunction note_reply(reply: Reply, update: SessionUpdate): void {\n if (update.sessionUpdate === 'tool_call' && reply.text !== '') reply.card_since_text = true\n if (update.sessionUpdate !== 'agent_message_chunk') return\n reply.sent = true\n if (update.content.type !== 'text' || update.content.text === '') return\n reply.text += reply.card_since_text ? `\\n\\n${update.content.text}` : update.content.text\n reply.card_since_text = false\n}\n\n/**\n * Append a turn to the session's history: the user's text, then the reply\n * text the client was sent, when there was any. A cancelled turn marks\n * whichever of the two came last.\n */\nfunction record_exchange(history: AcpHistoryEntry[], user_text: string, reply_text: string, cancelled: boolean): void {\n const stop = cancelled ? { cancelled: true as const } : {}\n if (reply_text === '') history.push({ role: 'user', text: user_text, ...stop })\n else history.push({ role: 'user', text: user_text }, { role: 'agent', text: reply_text, ...stop })\n}\n\n/**\n * Settle a run's result into a value, so a run that fails while the turn is\n * still sending never surfaces as an unhandled rejection.\n */\nfunction settle<o>(result: Promise<o>): Promise<Settled<o>> {\n return result.then(\n (output): Settled<o> => ({ ok: true, output }),\n (error: unknown): Settled<o> => ({ ok: false, error }),\n )\n}\n\n/**\n * Say on stderr that the run outran the client and dropped events, since the\n * reply the client shows is missing text from that point on.\n */\nfunction warn_dropped(event: TrajectoryEvent): void {\n process.stderr.write(\n `fascicle/acp: the client read updates slower than the run produced them, so ${String(event['count'])} run events were dropped and the reply is missing text from that point; send the prompt again for the whole reply\\n`,\n )\n}\n\n/**\n * Send `updates` in order until the turn is cancelled, and say whether all\n * of them went out.\n */\nasync function send_all(updates: ReadonlyArray<SessionUpdate>, cancelled: AbortSignal, send: SendUpdate): Promise<boolean> {\n for (const update of updates) {\n if (cancelled.aborted) return false\n await send(update)\n }\n return true\n}\n\n/**\n * Fold a run event into the session's usage, and return the `usage_update`\n * that a change sends, when the config names the context window.\n */\nfunction usage_updates<i, o>(config: ServeAcpConfig<i, o>, record: SessionRecord<i, o>, event: TrajectoryEvent): SessionUpdate[] {\n const changed = note_usage(record.usage, event)\n const window = context_window_of(config, record.session.model())\n return changed && window !== undefined ? [usage_update(record.usage, window)] : []\n}\n\n/**\n * Send each run event's updates in order, and tell the session's card sync\n * once all of an event's updates have gone out. Each event also folds into\n * the session's usage, and a change goes out as a `usage_update` when the\n * config names the context window. Once the turn is cancelled nothing more\n * is sent, and leaving the loop closes the run's event stream. Resolves with\n * the finish reason of the last model call that finished.\n */\nasync function forward<i, o>(\n events: AsyncIterable<TrajectoryEvent>,\n config: ServeAcpConfig<i, o>,\n record: SessionRecord<i, o>,\n cancelled: AbortSignal,\n send: SendUpdate,\n): Promise<FinishReason | undefined> {\n const state = create_acp_mapper_state({ stream: config.stream, session: record.session })\n const to_updates = config.to_updates ?? to_session_updates\n let finish: FinishReason | undefined\n for await (const event of events) {\n if (event.kind === 'events_dropped') warn_dropped(event)\n finish = finish_reason_of(event) ?? finish\n const updates = to_updates(event, state)\n if (!(await send_all(updates, cancelled, send))) return finish\n record.cards.sent(event, updates)\n if (!(await send_all(usage_updates(config, record, event), cancelled, send))) return finish\n }\n return finish\n}\n\n/**\n * Run the flow for one turn, forward its updates, and record the exchange.\n * The run has always settled by the time this returns or throws, so a turn\n * never leaves a run behind. A turn that ends in a refusal stays out of the\n * history, since the protocol has the client leave it out of the next prompt\n * too.\n */\nasync function run_turn<i, o>(\n config: ServeAcpConfig<i, o>,\n record: SessionRecord<i, o>,\n prompt: ReadonlyArray<ContentBlock>,\n cancelled: AbortSignal,\n send: SendUpdate,\n): Promise<PromptResponse> {\n const turn: AcpTurn = {\n session_id: record.session.id,\n cwd: record.session.cwd,\n text: turn_text(prompt),\n prompt,\n history: [...record.history],\n }\n const reply: Reply = { sent: false, text: '', card_since_text: false }\n const send_update: SendUpdate = async (update) => {\n await send(update)\n note_reply(reply, update)\n }\n const stop = new AbortController()\n // A turn cancelled before its consumer caught up leaves previews nobody\n // took, and raw ids repeat from turn to turn.\n reset_previews(record.session)\n const handle = run.stream(record.flow, turn_input(config, turn), {\n abort: AbortSignal.any([cancelled, stop.signal]),\n install_signal_handlers: false,\n // Every event the run queues for the consumer passes through here first,\n // which is how an approval knows what the client hasn't been sent yet.\n trajectory: record.cards.start(config.trajectory),\n })\n const outcome = settle(handle.result)\n let finish: FinishReason | undefined\n try {\n // The run starts first, so a client slow to take the title holds up only\n // the updates queued behind it.\n await name_session(config, record, turn, send_update)\n finish = await forward(handle.events, config, record, cancelled, send_update)\n const result = await outcome\n if (!cancelled.aborted) {\n if (!result.ok) throw result.error\n const final_text = (config.to_text ?? default_to_text)(result.output)\n if (!reply.sent && final_text !== '') await send_update(agent_message(final_text))\n }\n } catch (err: unknown) {\n stop.abort(new aborted_error('the prompt turn failed before its run finished'))\n await outcome\n if (!cancelled.aborted) throw err\n }\n const stop_reason = cancelled.aborted ? 'cancelled' : stop_reason_for(finish)\n if (stop_reason !== 'refusal') record_exchange(record.history, turn.text, reply.text, cancelled.aborted)\n return { stopReason: stop_reason }\n}\n\n/**\n * Run one prompt turn and answer with its stop reason. A new prompt cancels\n * the session's turn in flight and waits for it to settle first, so it sees\n * that turn in its history and never runs beside it.\n */\nexport async function prompt_turn<i, o>(\n config: ServeAcpConfig<i, o>,\n record: SessionRecord<i, o>,\n prompt: ReadonlyArray<ContentBlock>,\n request_signal: AbortSignal,\n send: SendUpdate,\n): Promise<PromptResponse> {\n const previous = record.last_turn\n const cancel = new AbortController()\n const { promise: settled, resolve: settle_turn } = Promise.withResolvers<void>()\n record.last_turn = { cancel, settled }\n try {\n if (previous !== null) {\n previous.cancel.abort(new aborted_error('a new prompt replaced the turn'))\n await previous.settled\n }\n const signals = [cancel.signal, request_signal, ...(config.abort === undefined ? [] : [config.abort])]\n return await run_turn(config, record, prompt, AbortSignal.any(signals), send)\n } finally {\n settle_turn()\n }\n}\n\n/**\n * Cancel the session's latest turn on the client's `session/cancel`.\n */\nexport function cancel_turn<i, o>(record: SessionRecord<i, o>): void {\n record.last_turn?.cancel.abort(new aborted_error('the ACP client cancelled the turn'))\n}\n","/**\n * Typed errors for the ACP adapter.\n *\n * Listed alongside src/mcp/errors.ts in the `no-class` rule ignores:\n * `instanceof` branching is how callers tell a missing optional peer apart\n * from a failure inside a prompt turn.\n */\n\nexport class acp_sdk_missing_error extends Error {\n readonly kind = 'acp_sdk_missing_error' as const;\n constructor(\n message = '@agentclientprotocol/sdk is required for fascicle/acp; install it with its zod peer: pnpm add @agentclientprotocol/sdk zod',\n ) {\n super(message)\n this.name = 'acp_sdk_missing_error'\n }\n}\n","/**\n * Lazy loader for the optional `@agentclientprotocol/sdk` peer.\n *\n * The adapter needs SDK values (the `agent()` builder, `ndJsonStream`,\n * `RequestError`), so it imports the SDK dynamically rather than statically:\n * a consumer can import `fascicle/acp` without the SDK installed and only pays\n * for it when they serve a flow. A missing peer surfaces as a typed\n * `acp_sdk_missing_error` with install guidance, mirroring\n * src/mcp/sdk_loader.ts.\n *\n * The package root is the SDK's stable protocol v1 entry; v2 sits under its\n * `experimental/` subpaths, which fascicle never imports. The SDK imports\n * `zod/v4` at runtime as its own peer, so a missing zod fails here too, and\n * the error names both installs.\n */\n\nimport { acp_sdk_missing_error } from './errors.js'\n\n/**\n * Dynamically imports the `@agentclientprotocol/sdk` v1 entry, throwing a\n * typed `acp_sdk_missing_error` when the optional peer (or its zod peer) is\n * not installed.\n */\nexport async function load_acp_sdk() {\n try {\n return await import('@agentclientprotocol/sdk')\n } catch (err: unknown) {\n const detail = err instanceof Error ? err.message : String(err)\n throw new acp_sdk_missing_error(\n `@agentclientprotocol/sdk is required for fascicle/acp; install it with its zod peer: pnpm add @agentclientprotocol/sdk zod (cause: ${detail})`,\n )\n }\n}\n","/**\n * acp_agent: the ACP agent app that answers each prompt turn by running a\n * flow.\n *\n * It registers the protocol v1 handlers and holds the sessions, and connects\n * to anything the SDK can: `serve_acp`'s stdio streams, or an in-process\n * `client()` in a test. It doesn't own the process, so it leaves the console\n * and the engine alone; `serve_acp` handles both.\n *\n * Given a session store, it saves each session after every turn and every\n * mode or model switch, and answers `session/list`, `session/load`, and\n * `session/resume` from it. A loaded session gets a fresh flow from the\n * config, and the history it carries is what its next turn starts from.\n *\n * A session holds what the client gave it until the client closes it with\n * `session/close` or drops the connection: its MCP servers, for an agent\n * that connects to them, are closed then, and a closed session leaves\n * memory, though not the store.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type {\n AgentApp,\n AgentContext,\n ClientCapabilities,\n ListSessionsResponse,\n McpServer,\n SessionConfigOption,\n SessionInfo,\n SessionUpdate,\n} from '@agentclientprotocol/sdk'\nimport { create_card_sync, message_of, session_approver } from './approve.js'\nimport type { PermissionAsker } from './approve.js'\nimport { connect_mcp_servers, gated_mcp_tools, MCP_CAPABILITIES, NO_MCP } from './mcp_servers.js'\nimport type { McpConnections } from './mcp_servers.js'\nimport {\n context_window_of,\n MODEL_CONFIG_ID,\n model_offer,\n model_options,\n offers_model,\n start_model,\n unknown_model_message,\n} from './models.js'\nimport type { ModelOffer } from './models.js'\nimport { config_options, MODE_CONFIG_ID, mode_offer, mode_state, session_modes, unknown_mode_message } from './modes.js'\nimport type { ModeOffer, SessionModes } from './modes.js'\nimport { cancel_turn, prompt_turn } from './prompt_turn.js'\nimport type { SessionRecord } from './prompt_turn.js'\nimport { load_acp_sdk } from './sdk_loader.js'\nimport { resolve_roots } from './tools/containment.js'\nimport type { AcpHistoryEntry, AcpMode, AcpSession, AcpSessionSummary, AcpStoredSession, ServeAcpConfig } from './types.js'\nimport { create_session_usage, usage_update } from './usage.js'\nimport type { SessionUsage } from './usage.js'\n\ntype AcpSdk = Awaited<ReturnType<typeof load_acp_sdk>>\n\n/**\n * A session as the agent holds it: what a turn needs, its mode, its model,\n * its MCP servers, and the latest save, which the next save waits on so two\n * never write at once.\n */\ntype AgentSession<i, o> = SessionRecord<i, o> & {\n readonly modes: SessionModes\n readonly model: { id: string | undefined }\n readonly mcp: McpConnections\n saving: Promise<void>\n}\n\n/**\n * What a session starts from: its workspace, the MCP servers the client\n * sent for it, and for a stored one, where it left off.\n */\ntype SessionStart = {\n readonly id: string\n readonly cwd: string\n readonly additional_directories: ReadonlyArray<string>\n readonly mcp_servers: ReadonlyArray<McpServer>\n readonly stored?: AcpStoredSession | undefined\n}\n\n/** Every config option id a session can have, as a refusal lists them. */\nconst CONFIG_IDS = `${MODE_CONFIG_ID} and ${MODEL_CONFIG_ID}`\n\nconst ONE_CONNECTION =\n 'acp_agent: this app already serves a connection; build an app for each connection, as serve_acp does'\n\n/**\n * Turn a failure inside a handler into a JSON-RPC error that carries its\n * message. The SDK reports a plain thrown `Error` as a bare \"Internal error\",\n * which tells the user in the client nothing about what went wrong.\n */\nfunction internal_error(sdk: AcpSdk, err: unknown): Error {\n return sdk.RequestError.internalError(undefined, message_of(err))\n}\n\n/**\n * A function that sends one update to the client for one session.\n */\nfunction sender(sdk: AcpSdk, client: AgentContext, sessionId: string): (update: SessionUpdate) => Promise<void> {\n return (update) => client.notify(sdk.methods.client.session.update, { sessionId, update })\n}\n\n/**\n * A function that asks the client to approve one tool call. The SDK\n * withdraws the request with `$/cancel_request` once `cancel` fires, which\n * is the turn's abort, so a cancelled turn takes its prompt down with it.\n */\nfunction permission_asker(sdk: AcpSdk, client: AgentContext): PermissionAsker {\n return (request, cancel) =>\n client.request(sdk.methods.client.session.requestPermission, request, { cancellationSignal: cancel })\n}\n\n/**\n * The model a client asked for, or an invalid-params error naming the\n * models the agent offers.\n */\nfunction requested_model(sdk: AcpSdk, offer: ModelOffer, id: unknown): string {\n if (offers_model(offer, id)) return id\n throw sdk.RequestError.invalidParams({ value: id }, unknown_model_message(id, offer))\n}\n\n/**\n * The mode a client asked for, or an invalid-params error naming the modes\n * the agent offers, for a mode it doesn't know and one it leaves out alike.\n * `field` is the param the id arrived in, for the error's data.\n */\nfunction requested_mode(\n sdk: AcpSdk,\n offer: ModeOffer,\n modes: SessionModes,\n id: unknown,\n field: 'modeId' | 'value',\n): AcpMode {\n if (modes.offers(id)) return id\n throw sdk.RequestError.invalidParams({ [field]: id }, unknown_mode_message(id, offer))\n}\n\n/**\n * The additional directories a client sent with a session request, or, from\n * an agent whose config sets `additional_directories: false`, an\n * invalid-params error refusing them. Every session request that carries\n * `additionalDirectories` goes through this check before its roots resolve,\n * so each one refuses them the same way. The protocol reads an empty list as\n * none, so an empty list passes.\n */\nfunction requested_directories(\n sdk: AcpSdk,\n config: { readonly additional_directories?: boolean | undefined },\n method: string,\n directories: ReadonlyArray<string> = [],\n): ReadonlyArray<string> {\n if (config.additional_directories !== false || directories.length === 0) return directories\n throw sdk.RequestError.invalidParams(\n { additionalDirectories: directories },\n `this agent works in cwd alone and takes no additional directories; send ${method} without additionalDirectories`,\n )\n}\n\n/**\n * A session's state as the store keeps it, copied, so a turn that runs while\n * the save is writing can't change what it writes.\n */\nfunction stored_session<i, o>(record: AgentSession<i, o>): AcpStoredSession {\n return {\n id: record.session.id,\n cwd: record.session.cwd,\n additional_directories: [...record.session.additional_directories],\n mode: record.modes.current(),\n model: record.model.id,\n title: record.title,\n updated_at: new Date().toISOString(),\n history: structuredClone(record.history),\n usage: { ...record.usage },\n }\n}\n\n/**\n * Save a session after the save before it. A session with no history yet\n * isn't saved, so a thread the user never wrote in doesn't fill the list. A\n * failed save is reported on stderr rather than failing the turn the user\n * already watched finish, and it leaves the session as it was in the store.\n */\nfunction save_session<i, o>(config: ServeAcpConfig<i, o>, record: AgentSession<i, o>): Promise<void> {\n const store = config.session_store\n if (store === undefined || record.history.length === 0) return Promise.resolve()\n const snapshot = stored_session(record)\n record.saving = record.saving\n .then(() => store.save(snapshot))\n .catch((err: unknown) => {\n process.stderr.write(`fascicle/acp: couldn't save session ${snapshot.id}: ${message_of(err)}\\n`)\n })\n return record.saving\n}\n\n/**\n * A history entry as the update that shows it again in a loaded thread.\n */\nfunction replayed(entry: AcpHistoryEntry): SessionUpdate {\n const content = { type: 'text' as const, text: entry.text }\n return entry.role === 'user'\n ? { sessionUpdate: 'user_message_chunk', content }\n : { sessionUpdate: 'agent_message_chunk', content }\n}\n\n/**\n * A stored session as `session/list` reports one.\n */\nfunction session_info(summary: AcpSessionSummary): SessionInfo {\n return {\n sessionId: summary.id,\n cwd: summary.cwd,\n updatedAt: summary.updated_at,\n ...(summary.additional_directories.length > 0 ? { additionalDirectories: [...summary.additional_directories] } : {}),\n ...(summary.title !== null && summary.title !== '' ? { title: summary.title } : {}),\n }\n}\n\n/**\n * Build the ACP agent app that answers each prompt turn by running the\n * config's flow, with its handlers registered and not yet connected.\n *\n * An app serves one connection for its life, since its sessions and the\n * client's capabilities aren't scoped to a connection. A second `connect`\n * throws, and so, for a server that routes a second client to the same app\n * and runs `initialize` before any connect hook, does a second `initialize`,\n * before it can overwrite the first client's capabilities.\n */\nexport async function acp_agent<i, o>(config: ServeAcpConfig<i, o>): Promise<AgentApp> {\n // A bad config fails here, before the SDK loads, so the error names it.\n const offer = mode_offer(config)\n const models = model_offer(config)\n const sdk = await load_acp_sdk()\n const sessions = new Map<string, AgentSession<i, o>>()\n const store = config.session_store\n const identity = { name: config.name, version: config.version ?? '0.0.0' }\n let client_capabilities: ClientCapabilities = {}\n let connected = false\n let initialized = false\n const session_of = (sessionId: string): AgentSession<i, o> => {\n const record = sessions.get(sessionId)\n if (record !== undefined) return record\n throw sdk.RequestError.invalidParams({ sessionId }, `unknown session ${sessionId}; start one with session/new first`)\n }\n // Every option a session has, the mode first, as each answer and each\n // config option update reports them.\n const options_of = (record: AgentSession<i, o>): SessionConfigOption[] => [\n ...config_options(offer, record.modes.current()),\n ...model_options(models, record.model.id),\n ]\n const build_flow = (session: AcpSession) => (typeof config.flow === 'function' ? config.flow(session) : config.flow)\n // The roots resolve once, here, so every containment check compares\n // against the same real paths for the life of the session. The MCP\n // servers connect before the flow is built, since the builder hands their\n // tools to the model, and close again when the builder throws.\n const open_session = async (client: AgentContext, start: SessionStart): Promise<AgentSession<i, o>> => {\n const { id, cwd, additional_directories, stored } = start\n const roots = await resolve_roots([cwd, ...additional_directories]).catch((err: unknown) => {\n throw sdk.RequestError.invalidParams({ cwd, additionalDirectories: additional_directories }, message_of(err))\n })\n const model = { id: start_model(models, stored?.model) }\n const modes = session_modes(offer, sender(sdk, client, id), stored?.mode, () => model_options(models, model.id))\n const cards = create_card_sync()\n const approver = session_approver({ modes, cards, ask: permission_asker(sdk, client) })\n const mcp = config.mcp_servers === true ? await connect_mcp_servers(start.mcp_servers, cwd, identity) : NO_MCP\n const session: AcpSession = {\n id,\n cwd,\n additional_directories,\n roots,\n client_capabilities,\n mode: modes.current,\n model: () => model.id,\n mcp_tools: gated_mcp_tools(mcp.tools, () => session),\n approve: (request) => approver(session, request),\n }\n const usage: SessionUsage = stored === undefined ? create_session_usage() : { ...stored.usage }\n try {\n const record: AgentSession<i, o> = {\n session,\n flow: build_flow(session),\n history: structuredClone([...(stored?.history ?? [])]),\n cards,\n usage,\n last_turn: null,\n title: stored?.title ?? null,\n modes,\n model,\n mcp,\n saving: Promise.resolve(),\n }\n sessions.set(id, record)\n return record\n } catch (err: unknown) {\n await mcp.close()\n throw internal_error(sdk, err)\n }\n }\n // A session this connection already holds is picked up as it is, and a\n // stored one is opened from the store. Either way the client must send the\n // cwd the session started in, which the protocol lets the roots beside it\n // change.\n const reopen = async (\n client: AgentContext,\n method: 'session/load' | 'session/resume',\n params: {\n sessionId: string\n cwd: string\n additionalDirectories?: ReadonlyArray<string> | undefined\n mcpServers?: ReadonlyArray<McpServer> | undefined\n },\n ): Promise<AgentSession<i, o>> => {\n if (store === undefined) throw sdk.RequestError.methodNotFound(method)\n const { sessionId, cwd } = params\n const additional_directories = requested_directories(sdk, config, method, params.additionalDirectories)\n const live = sessions.get(sessionId)\n const stored = live === undefined ? await store.load(sessionId).catch((err: unknown) => {\n throw internal_error(sdk, err)\n }) : undefined\n const started_in = live?.session.cwd ?? stored?.cwd\n if (started_in === undefined) {\n throw sdk.RequestError.invalidParams({ sessionId }, `unknown session ${sessionId}; list the stored ones with session/list`)\n }\n if (started_in !== cwd) {\n throw sdk.RequestError.invalidParams(\n { sessionId, cwd },\n `session ${sessionId} started in ${started_in}; send that cwd with ${method}`,\n )\n }\n return (\n live ?? open_session(client, { id: sessionId, cwd, additional_directories, mcp_servers: params.mcpServers ?? [], stored })\n )\n }\n // A reopened thread shows its title and its usage again, which the client\n // can't keep for an agent that restarted, and the answer carries its mode\n // and its model.\n const reopened = async (client: AgentContext, record: AgentSession<i, o>) => {\n const send = sender(sdk, client, record.session.id)\n if (record.title !== null && record.title !== '') await send({ sessionUpdate: 'session_info_update', title: record.title })\n const window = context_window_of(config, record.model.id)\n if (window !== undefined && (record.usage.context_tokens > 0 || record.usage.priced)) {\n await send(usage_update(record.usage, window))\n }\n return { modes: mode_state(offer, record.modes.current()), configOptions: options_of(record) }\n }\n // The flow is built again for the new model before the pick takes, so a\n // builder that throws leaves the session on the model it had. A turn in\n // flight keeps the flow it started with.\n const switch_model = (record: AgentSession<i, o>, next: string): void => {\n const previous = record.model.id\n record.model.id = next\n try {\n record.flow = build_flow(record.session)\n } catch (err: unknown) {\n record.model.id = previous\n throw internal_error(sdk, err)\n }\n }\n // Closing cancels the session's turn as session/cancel does, and waits for\n // its run to settle before the MCP servers close, so no tool call is left\n // talking to one. The session leaves memory, and the store keeps it.\n const close_session = async (record: AgentSession<i, o>): Promise<void> => {\n sessions.delete(record.session.id)\n cancel_turn(record)\n await record.last_turn?.settled\n await record.mcp.close()\n }\n return sdk\n .agent()\n .onConnect((connection) => {\n if (connected) throw new Error(ONE_CONNECTION)\n connected = true\n // The SDK aborts every request in flight as the connection closes,\n // which ends each turn, and then every session closes, so a stdio MCP\n // server doesn't outlive the editor that sent it.\n void connection.closed.then(() => Promise.all([...sessions.values()].map(close_session)))\n })\n .onRequest('initialize', (ctx) => {\n if (initialized) throw sdk.RequestError.invalidRequest(undefined, ONE_CONNECTION)\n initialized = true\n client_capabilities = ctx.params.clientCapabilities ?? {}\n return {\n protocolVersion: sdk.PROTOCOL_VERSION,\n agentInfo: identity,\n // Embedded context lets a file the user @-mentions arrive with its\n // text, rather than as a bare URI the flow has no way to read. The\n // agent advertises additional directories, which let a client widen\n // the workspace past `cwd`, unless the config sets\n // `additional_directories: false`.\n agentCapabilities: {\n loadSession: store !== undefined,\n promptCapabilities: { embeddedContext: true },\n ...(config.mcp_servers === true ? { mcpCapabilities: MCP_CAPABILITIES } : {}),\n sessionCapabilities: {\n close: {},\n ...(config.additional_directories === false ? {} : { additionalDirectories: {} }),\n ...(store === undefined ? {} : { list: {}, resume: {} }),\n },\n },\n // Providers authenticate with what the launched process can see;\n // ACP v1 gives the client no way to hand the agent credentials.\n authMethods: [],\n }\n })\n .onRequest(\n 'authenticate',\n // Stryker disable next-line ArrowFunction: the SDK answers an authenticate handler's undefined with {}, so both read the same on the wire.\n () => ({}),\n )\n .onRequest('session/new', async (ctx) => {\n // `mcpServers` is ignored unless the config sets `mcp_servers`.\n const { cwd, mcpServers } = ctx.params\n const additional_directories = requested_directories(sdk, config, 'session/new', ctx.params.additionalDirectories)\n const record = await open_session(ctx.client, { id: randomUUID(), cwd, additional_directories, mcp_servers: mcpServers })\n return {\n sessionId: record.session.id,\n modes: mode_state(offer, record.modes.current()),\n configOptions: options_of(record),\n }\n })\n .onRequest('session/load', async (ctx) => {\n const record = await reopen(ctx.client, 'session/load', ctx.params)\n const send = sender(sdk, ctx.client, record.session.id)\n for (const entry of record.history) await send(replayed(entry))\n return reopened(ctx.client, record)\n })\n .onRequest('session/resume', async (ctx) => reopened(ctx.client, await reopen(ctx.client, 'session/resume', ctx.params)))\n .onRequest('session/list', async (ctx): Promise<ListSessionsResponse> => {\n if (store === undefined) throw sdk.RequestError.methodNotFound('session/list')\n const { cwd } = ctx.params\n const summaries = await store.list().catch((err: unknown) => {\n throw internal_error(sdk, err)\n })\n const listed = summaries\n .filter((summary) => cwd === undefined || cwd === null || summary.cwd === cwd)\n .toSorted((a, b) => b.updated_at.localeCompare(a.updated_at))\n return { sessions: listed.map(session_info) }\n })\n .onRequest('session/close', async (ctx) => {\n await close_session(session_of(ctx.params.sessionId))\n return {}\n })\n .onRequest('session/prompt', async (ctx) => {\n const { sessionId, prompt } = ctx.params\n const record = session_of(sessionId)\n try {\n return await prompt_turn(config, record, prompt, ctx.signal, sender(sdk, ctx.client, sessionId))\n } catch (err: unknown) {\n throw internal_error(sdk, err)\n } finally {\n await save_session(config, record)\n }\n })\n .onRequest('session/set_mode', async (ctx) => {\n const { sessionId, modeId } = ctx.params\n const record = session_of(sessionId)\n await record.modes.switch_to(requested_mode(sdk, offer, record.modes, modeId, 'modeId'))\n await save_session(config, record)\n return {}\n })\n .onRequest('session/set_config_option', async (ctx) => {\n const { sessionId, configId, value } = ctx.params\n const record = session_of(sessionId)\n if (configId === MODE_CONFIG_ID) {\n await record.modes.switch_to(requested_mode(sdk, offer, record.modes, value, 'value'))\n } else if (configId === MODEL_CONFIG_ID && models !== undefined) {\n switch_model(record, requested_model(sdk, models, value))\n } else {\n const known = models === undefined ? `the only one is ${MODE_CONFIG_ID}` : `the options are ${CONFIG_IDS}`\n throw sdk.RequestError.invalidParams({ configId }, `unknown config option ${configId}; ${known}`)\n }\n await save_session(config, record)\n return { configOptions: options_of(record) }\n })\n .onNotification('session/cancel', (ctx) => {\n const record = sessions.get(ctx.params.sessionId)\n if (record !== undefined) cancel_turn(record)\n })\n}\n","/**\n * The ACP agent's serving loop, minus the process.\n *\n * `serve_streams` is everything `serve_acp` does once the console and the\n * signals are handled: connect `acp_agent` to a pair of ndjson byte streams,\n * hold the connection until the client hangs up or `shutdown` fires, then\n * dispose the engine. It takes its streams as arguments, mirroring\n * `execute_stdio` under `run_stdio`, so the disconnect path is unit-tested\n * here and the thin glue in `serve_acp.ts` owns the real stdin and stdout.\n *\n * Closing the connection is what aborts the runs: the SDK aborts every\n * in-flight request's signal as it closes, and each prompt turn's run\n * listens on its request's signal. So by the time `closed` resolves, every\n * active run has seen its abort, and only then is the engine disposed.\n */\n\nimport { acp_agent } from './acp_agent.js'\nimport { load_acp_sdk } from './sdk_loader.js'\nimport type { ServeAcpConfig } from './types.js'\n\ntype AcpServeIo = {\n /** What the client sends, as ndjson bytes; stdin under `serve_acp`. */\n readonly input: ReadableStream<Uint8Array>\n /** Where the protocol goes, as ndjson bytes; stdout under `serve_acp`. */\n readonly output: WritableStream<Uint8Array>\n /** Ends the connection from the agent's side, aborting every active run with its reason. */\n readonly shutdown?: AbortSignal | undefined\n}\n\n/**\n * Serve the config's flow as an ACP agent over `io` until the client\n * disconnects or `io.shutdown` fires, then dispose the engine once every\n * active run has been aborted.\n */\nexport async function serve_streams<i, o>(config: ServeAcpConfig<i, o>, io: AcpServeIo): Promise<void> {\n const sdk = await load_acp_sdk()\n const app = await acp_agent(config)\n const connection = app.connect(sdk.ndJsonStream(io.output, io.input))\n const { shutdown } = io\n if (shutdown !== undefined) {\n // A signal can land while the SDK loads, before there is a listener to hear it.\n if (shutdown.aborted) connection.close(shutdown.reason)\n else shutdown.addEventListener('abort', () => connection.close(shutdown.reason))\n }\n await connection.closed\n await config.engine?.dispose()\n}\n","/**\n * Process glue for serving a flow as an ACP agent over stdio.\n *\n * Binds `serve_streams` to the real process: ndjson in on stdin, the\n * protocol out on stdout, and nothing else on stdout ever. A stray log line\n * from a flow or a dependency would corrupt the protocol stream, so\n * `console.log`, `console.info`, `console.debug`, `console.dir`, and\n * `console.dirxml` go to stderr for the life of the process.\n *\n * SIGTERM and SIGINT abort every active run, dispose the engine, and exit.\n * A host that ends the agent with a signal instead of closing stdin would\n * otherwise leave a run's work going after the editor has closed, since each\n * turn runs with the runner's own signal handlers off. The handlers are\n * one-shot, so a second Ctrl-C falls through to Node's default and kills the\n * process outright when a shutdown hangs.\n *\n * Excluded from mutation testing as process glue (see stryker.config.mjs);\n * the spawn tests in `__tests__/e2e/` exercise it for real.\n */\n\nimport { constants } from 'node:os'\nimport { Readable, Writable } from 'node:stream'\nimport { aborted_error } from '#core'\nimport { route_console_to_stderr } from '#process'\nimport { serve_streams } from './serve_streams.js'\nimport type { ServeAcpConfig } from './types.js'\n\n/**\n * Serve a flow as an ACP agent over stdin and stdout until the client\n * disconnects, disposing the engine once every active run has been aborted.\n * A SIGTERM or SIGINT does the same, then exits with the signal's code.\n */\nexport async function serve_acp<i, o>(config: ServeAcpConfig<i, o>): Promise<void> {\n // Leave stdout to the protocol alone.\n route_console_to_stderr(console, process.stderr)\n const shutdown = new AbortController()\n let received: NodeJS.Signals | null = null\n const on_signal = (signal: NodeJS.Signals): void => {\n received = signal\n shutdown.abort(new aborted_error(`received ${signal}`, { reason: { signal } }))\n }\n process.once('SIGTERM', on_signal)\n process.once('SIGINT', on_signal)\n try {\n await serve_streams(config, {\n input: Readable.toWeb(process.stdin),\n output: Writable.toWeb(process.stdout),\n shutdown: shutdown.signal,\n })\n } finally {\n process.off('SIGTERM', on_signal)\n process.off('SIGINT', on_signal)\n }\n // Exiting here rather than draining tells the host a signal ended the\n // agent, and leaves no wait on a flow that ignored its abort.\n if (received !== null) process.exit(128 + constants.signals[received])\n}\n","/**\n * session_store: a filesystem store for ACP sessions, one JSON file each.\n *\n * A session is saved as `<id>.json` under the root directory. A save writes a\n * temporary sibling first and renames it into place, so a crash mid-write\n * leaves the earlier copy whole. A session holds the whole conversation,\n * which can carry code or a key the user pasted, so the directory the store\n * makes is readable by its owner alone, and so is every file it writes. A session id comes from the client on\n * `session/load` and `session/resume`, so only an id made of letters, digits,\n * `-`, and `_` names a file, and any other id reads as a session the store\n * doesn't hold rather than as a path. A file that isn't a stored session\n * fails its load with a message naming it, and `list` skips it with a\n * warning on stderr, so one bad file can't hide every other thread.\n *\n * Paths are accepted at construction; the store never reads `process.env`.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport { mkdir, readdir, readFile, rename, writeFile } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { is_acp_mode } from './modes.js'\nimport { error_code } from './tools/containment.js'\nimport type { AcpHistoryEntry, AcpSessionStore, AcpSessionSummary, AcpSessionUsage, AcpStoredSession } from './types.js'\n\nexport type FilesystemSessionStoreConfig = {\n /** The directory the session files go in, made on the first save. */\n readonly root_dir: string\n}\n\n/** The ids that can name a file, which every id the agent makes matches. */\nconst SAFE_ID = /^[\\w-]+$/\n\n/**\n * Whether `value` is a plain object, read as a record of unknown fields.\n */\nfunction is_record(value: unknown): value is Readonly<Record<string, unknown>> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/**\n * Whether `value` is a list of strings.\n */\nfunction is_strings(value: unknown): value is ReadonlyArray<string> {\n return Array.isArray(value) && value.every((entry) => typeof entry === 'string')\n}\n\n/**\n * Whether `value` is one history entry, with a role, its text, and, on the\n * entry where a cancelled turn stopped, the mark that says so.\n */\nfunction is_history_entry(value: unknown): value is AcpHistoryEntry {\n if (!is_record(value)) return false\n const { role, text, cancelled } = value\n return (role === 'user' || role === 'agent') && typeof text === 'string' && (cancelled === undefined || cancelled === true)\n}\n\n/**\n * Whether `value` is a session's usage.\n */\nfunction is_usage(value: unknown): value is AcpSessionUsage {\n if (!is_record(value)) return false\n const { context_tokens, cost_usd, priced } = value\n return typeof context_tokens === 'number' && typeof cost_usd === 'number' && typeof priced === 'boolean'\n}\n\n/**\n * Whether `value` is a stored session, checked field by field, since the\n * file is anything a person or another program left there.\n */\nfunction is_stored_session(value: unknown): value is AcpStoredSession {\n if (!is_record(value)) return false\n const { id, cwd, additional_directories, mode, model, title, updated_at, history, usage } = value\n return (\n typeof id === 'string' &&\n typeof cwd === 'string' &&\n is_strings(additional_directories) &&\n is_acp_mode(mode) &&\n (model === undefined || typeof model === 'string') &&\n (title === null || typeof title === 'string') &&\n typeof updated_at === 'string' &&\n Array.isArray(history) &&\n history.every(is_history_entry) &&\n is_usage(usage)\n )\n}\n\n/**\n * Read the session file at `path`, or undefined when there is none. Throws\n * an `Error` naming the file when it holds anything but a stored session.\n */\nasync function read_session(path: string): Promise<AcpStoredSession | undefined> {\n let text: string\n try {\n text = await readFile(path, 'utf8')\n } catch (err: unknown) {\n if (error_code(err) === 'ENOENT') return undefined\n throw err\n }\n let value: unknown\n try {\n value = JSON.parse(text)\n } catch {\n value = undefined\n }\n if (is_stored_session(value)) return value\n throw new Error(`${path} isn't a stored ACP session; fix or delete the file to load the others`)\n}\n\n/**\n * Build a session store that keeps one JSON file for each session under\n * `root_dir`.\n */\nexport function filesystem_session_store(config: FilesystemSessionStoreConfig): AcpSessionStore {\n const path_of = (id: string): string => join(config.root_dir, `${id}.json`)\n return {\n save: async (session) => {\n if (!SAFE_ID.test(session.id)) {\n throw new Error(`can't save session ${JSON.stringify(session.id)}: an id names a file, so use letters, digits, - and _`)\n }\n await mkdir(config.root_dir, { recursive: true, mode: 0o700 })\n const temporary = join(config.root_dir, `.${session.id}.${randomUUID()}.tmp`)\n await writeFile(temporary, JSON.stringify(session), { encoding: 'utf8', mode: 0o600 })\n await rename(temporary, path_of(session.id))\n },\n load: async (id) => (SAFE_ID.test(id) ? read_session(path_of(id)) : undefined),\n list: async () => {\n let names: string[]\n try {\n names = await readdir(config.root_dir)\n } catch (err: unknown) {\n if (error_code(err) === 'ENOENT') return []\n throw err\n }\n const files = names.filter((name) => name.endsWith('.json') && !name.startsWith('.'))\n const sessions = await Promise.all(\n files.map((name) =>\n read_session(join(config.root_dir, name)).catch((err: unknown) => {\n process.stderr.write(`fascicle/acp: ${err instanceof Error ? err.message : String(err)}\\n`)\n return undefined\n }),\n ),\n )\n return sessions\n .filter((session) => session !== undefined)\n .map(({ id, cwd, additional_directories, title, updated_at }): AcpSessionSummary => ({\n id,\n cwd,\n additional_directories,\n title,\n updated_at,\n }))\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAsBA,MAAa,iBAAiB;;AAY9B,MAAM,QAA8C;CAClD,QAAQ;EACN,MAAM;EACN,aAAa;EACb,MAAM;GAAE,MAAM;GAAM,SAAS;EAAK;CACpC;CACA,cAAc;EACZ,MAAM;EACN,aAAa;EACb,MAAM;GAAE,MAAM;GAAO,SAAS;EAAK;CACrC;CACA,MAAM;EACJ,MAAM;EACN,aAAa;EACb,MAAM;GAAE,MAAM;GAAO,SAAS;EAAM;CACtC;AACF;;;;;AAMA,SAAgB,YAAY,IAA4B;CACtD,OAAO,OAAO,OAAO,YAAY,OAAO,OAAO,OAAO,EAAE;AAC1D;;AAaA,MAAM,aAAa,OAAO,KAAK,KAAK,CAAC,CAAC,KAAK,IAAI;;;;;;;;AAS/C,SAAgB,WAAW,QAGb;CAEZ,MAAM,SAAiC,O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AAM,MAAM,OAAO,UAAU;IAAE,WAAW;IAAM,MAAM;GAAM,CAAC;GAC7D,MAAM,YAAY,KAAK,OAAO,UAAU,IAAI,QAAQ,GAAG,GAAG,WAAW,EAAE,KAAK;GAC5E,MAAM,UAAU,WAAW,KAAK,UAAU,OAAO,GAAG;IAAE,UAAU;IAAQ,MAAM;GAAM,CAAC;GACrF,MAAM,OAAO,WAAW,QAAQ,QAAQ,EAAE,CAAC;EAC7C;EACA,MAAM,OAAO,OAAQ,QAAQ,KAAK,EAAE,IAAI,aAAa,QAAQ,EAAE,CAAC,IAAI,KAAA;EACpE,MAAM,YAAY;GAChB,IAAI;GACJ,IAAI;IACF,QAAQ,MAAM,QAAQ,OAAO,QAAQ;GACvC,SAAS,KAAc;IACrB,IAAI,WAAW,GAAG,MAAM,UAAU,OAAO,CAAC;IAC1C,MAAM;GACR;GACA,MAAM,QAAQ,MAAM,QAAQ,SAAS,KAAK,SAAS,OAAO,KAAK,CAAC,KAAK,WAAW,GAAG,CAAC;GASpF,QAAO,MARgB,QAAQ,IAC7B,MAAM,KAAK,SACT,aAAa,KAAK,OAAO,UAAU,IAAI,CAAC,CAAC,CAAC,OAAO,QAAiB;IAChE,QAAQ,OAAO,MAAM,iBAAiB,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,EAAE,GAAG;GAE5F,CAAC,CACH,CACF,EAAA,CAEG,QAAQ,YAAY,YAAY,KAAA,CAAS,CAAC,CAC1C,KAAK,EAAE,IAAI,KAAK,wBAAwB,OAAO,kBAAqC;IACnF;IACA;IACA;IACA;IACA;GACF,EAAE;EACN;CACF;AACF"}
1
+ {"version":3,"file":"acp.js","names":["asked","is_record","is_record","is_record","is_record","is_record","constants"],"sources":["../src/acp/modes.ts","../src/acp/mcp_servers.ts","../src/acp/tools/previews.ts","../src/acp/tools/write_file.ts","../src/acp/tools/edit_file.ts","../src/acp/tools/run_command.ts","../src/acp/workspace_tools.ts","../src/acp/presentation.ts","../src/acp/approve.ts","../src/acp/models.ts","../src/acp/to_session_updates.ts","../src/acp/transcript.ts","../src/acp/usage.ts","../src/acp/prompt_turn.ts","../src/acp/errors.ts","../src/acp/sdk_loader.ts","../src/acp/session_list.ts","../src/acp/acp_agent.ts","../src/acp/api_key_login.ts","../src/acp/session_store.ts","../src/acp/checkpoint_session_store.ts","../src/acp/serve_streams.ts","../src/acp/serve_acp.ts"],"sourcesContent":["/**\n * modes: the three ways a coding session runs, and when each asks the\n * client before a workspace tool acts.\n *\n * Reads and searches never ask. Manual asks before every edit and every\n * command, Accept edits only before a command, and Auto never asks. That is\n * the contract Claude Agent set and Zed's mode picker presents. Auto runs\n * commands with nobody watching, so it belongs in a container or a\n * throwaway worktree, and an agent that runs anywhere else leaves it out\n * with `ServeAcpConfig.modes`.\n *\n * ACP reports a session's mode two ways, as `modes` and as a config option\n * in the `mode` category, and a client reads one or the other. Both come\n * from the one table here and the one `ModeOffer` an agent builds from its\n * config, and every change sends both updates, so the two can't disagree in\n * front of the user.\n */\n\nimport type { SessionConfigOption, SessionModeState, SessionUpdate } from '@agentclientprotocol/sdk'\nimport type { AcpMode } from './types.js'\n\n/** The id of the config option that carries the mode. */\nexport const MODE_CONFIG_ID = 'mode'\n\n/** What a workspace tool does that a mode may want to ask about first. */\nexport type GatedAction = 'edit' | 'command'\n\ntype ModeEntry = {\n readonly name: string\n readonly description: string\n readonly asks: Readonly<Record<GatedAction, boolean>>\n}\n\n/** Every mode, in the order a client lists them. */\nconst MODES: Readonly<Record<AcpMode, ModeEntry>> = {\n manual: {\n name: 'Manual',\n description: 'Ask before every edit and every command',\n asks: { edit: true, command: true },\n },\n accept_edits: {\n name: 'Accept edits',\n description: 'Edit files without asking, and ask before every command',\n asks: { edit: false, command: true },\n },\n auto: {\n name: 'Auto',\n description: 'Edit files and run commands without asking, for a container or a throwaway worktree',\n asks: { edit: false, command: false },\n },\n}\n\n/**\n * Whether `id` names one of the modes. An own-key check, so an id such as\n * `toString` that every object answers to isn't taken for one.\n */\nexport function is_acp_mode(id: unknown): id is AcpMode {\n return typeof id === 'string' && Object.hasOwn(MODES, id)\n}\n\n/**\n * The modes an agent offers, in the table's order and each once, and the\n * mode each of its sessions starts in. `acp_agent` builds one from its\n * config, and every list, check, and start mode reads it.\n */\nexport type ModeOffer = {\n readonly modes: ReadonlyArray<AcpMode>\n readonly default_mode: AcpMode\n}\n\n/** Every mode's id, as the refusals list them. */\nconst MODE_NAMES = Object.keys(MODES).join(', ')\n\n/**\n * The modes an agent offers and where its sessions start, from the config's\n * `modes` (default: all three) and `default_mode` (default: the first mode\n * offered). Throws an `Error` that names the problem for an empty `modes`,\n * an entry that isn't a mode, or a `default_mode` the agent doesn't offer,\n * so `acp_agent` fails as it's built rather than at every `session/new`.\n */\nexport function mode_offer(config: {\n readonly modes?: ReadonlyArray<AcpMode> | undefined\n readonly default_mode?: AcpMode | undefined\n}): ModeOffer {\n // A caller with no types can pass anything, so each entry is checked as unknown.\n const listed: ReadonlyArray<unknown> = config.modes ?? Object.keys(MODES)\n if (listed.length === 0) {\n throw new Error(\n `acp_agent: modes is empty; list at least one of ${MODE_NAMES}, or leave modes out to offer all three`,\n )\n }\n for (const entry of listed) {\n if (!is_acp_mode(entry)) {\n throw new Error(`acp_agent: modes lists ${JSON.stringify(entry)}, which isn't a mode; use one of ${MODE_NAMES}`)\n }\n }\n const modes = Object.keys(MODES).filter((id): id is AcpMode => listed.includes(id))\n const wanted = config.default_mode ?? modes[0]\n const default_mode = modes.find((mode) => mode === wanted)\n if (default_mode === undefined) {\n throw new Error(\n `acp_agent: default_mode ${JSON.stringify(config.default_mode)} isn't one of the modes this agent offers (${modes.join(', ')}); add it to modes or leave default_mode out`,\n )\n }\n return { modes, default_mode }\n}\n\n/**\n * The refusal for a mode id the agent doesn't offer, naming the ones it does.\n */\nexport function unknown_mode_message(id: unknown, offer: ModeOffer): string {\n return `unknown mode ${JSON.stringify(id)}; choose one of ${offer.modes.join(', ')}`\n}\n\n/**\n * Whether a session in `mode` asks the client before a tool does `action`.\n */\nexport function asks_before(mode: AcpMode, action: GatedAction): boolean {\n return MODES[mode].asks[action]\n}\n\n/** A mode as ACP lists one: its id, its name, and what it asks. */\ntype ListedMode = { readonly id: AcpMode; readonly name: string; readonly description: string }\n\n/**\n * Every mode the agent offers as ACP lists one, in the table's order.\n */\nfunction available_modes(offer: ModeOffer): ListedMode[] {\n return offer.modes.map((id) => ({ id, name: MODES[id].name, description: MODES[id].description }))\n}\n\n/**\n * The session's modes as `session/new` reports them in `modes`.\n */\nexport function mode_state(offer: ModeOffer, mode: AcpMode): SessionModeState {\n return { currentModeId: mode, availableModes: available_modes(offer) }\n}\n\n/**\n * The session's mode as a config option, a select over every mode the agent\n * offers, which leads the options `session/new` and\n * `session/set_config_option` report.\n */\nexport function config_options(offer: ModeOffer, mode: AcpMode): SessionConfigOption[] {\n return [\n {\n id: MODE_CONFIG_ID,\n name: 'Mode',\n description: 'When the agent asks before it edits a file or runs a command',\n category: 'mode',\n type: 'select',\n currentValue: mode,\n options: available_modes(offer).map(({ id, name, description }) => ({ value: id, name, description })),\n },\n ]\n}\n\n/**\n * A session's mode as the agent holds it: what it is now, whether the agent\n * offers a mode, and the one way to change it, which tells the client both\n * ways it may be reading it.\n */\nexport type SessionModes = {\n readonly current: () => AcpMode\n readonly offers: (mode: unknown) => mode is AcpMode\n readonly switch_to: (mode: AcpMode) => Promise<void>\n}\n\n/**\n * Hold a session's mode, starting at `start` when the agent offers it and\n * at the offer's `default_mode` otherwise, so a stored session whose mode the\n * agent has since stopped offering starts where a new one would. A switch\n * takes effect before the client hears of it, so a tool call that asks after\n * the switch reads the new mode, and the two updates go out in order through\n * `send`. A config option update carries every option the session has, so\n * `others` gives the ones after the mode, such as the model.\n */\nexport function session_modes(\n offer: ModeOffer,\n send: (update: SessionUpdate) => Promise<void>,\n start?: AcpMode,\n others: () => SessionConfigOption[] = () => [],\n): SessionModes {\n const offered: ReadonlyArray<unknown> = offer.modes\n let mode = offer.modes.find((entry) => entry === start) ?? offer.default_mode\n return {\n current: () => mode,\n offers: (candidate): candidate is AcpMode => offered.includes(candidate),\n switch_to: async (next) => {\n mode = next\n await send({ sessionUpdate: 'current_mode_update', currentModeId: next })\n await send({ sessionUpdate: 'config_option_update', configOptions: [...config_options(offer, next), ...others()] })\n },\n }\n}\n","/**\n * mcp_servers: the MCP servers a client sends with a session, connected\n * for the session's flow.\n *\n * Zed sends the MCP servers its user configured with every session. An\n * agent whose config sets `mcp_servers` connects to each one through\n * `mcp_client` from fascicle/mcp and hands their tools to the flow builder.\n * A server that can't be reached is left out with a warning on stderr\n * rather than failing the session, so one broken entry in the editor's\n * settings can't stop every thread, and the warning is kept for a client\n * that shows notices. A server's `env` and `headers` values are\n * credentials, so a warning carries the server's name and its error with\n * those values cut out, and nothing else of the server. The one value that\n * stays is a value under three characters, which is too short to tell from\n * the message's own words and numbers.\n *\n * Each tool is named `mcp__<server>__<tool>`, the form Claude Code uses, so\n * two servers' tools don't collide and none takes a workspace tool's name.\n * A provider takes a tool name of 64 characters at most, and the engine\n * refuses two tools under one name, so a name that runs longer, or that\n * another tool already took once the server's name was cleaned up, is cut\n * and ends in a hash of its server and tool. The tool still calls its\n * server under the name the server gave it.\n *\n * An MCP tool can do anything its server can, so each one asks before it\n * runs whenever the session's mode asks before a command. The approval\n * knows these calls the way it knows the workspace tools', by the input\n * their `needs_approval` was asked about, so a flow's own tool that copies\n * one's name doesn't pass for it.\n *\n * The connections last as long as the session, and close when the client\n * closes the session or the connection.\n */\n\nimport { createHash } from 'node:crypto'\nimport type { McpServer } from '@agentclientprotocol/sdk'\nimport type { Tool } from '#engine'\nimport { mcp_client } from '#mcp'\nimport type { McpClientConfig, McpClientHandle } from '#mcp'\nimport { is_record } from '#schema'\nimport { asks_before } from './modes.js'\nimport type { AcpSession } from './types.js'\n\n/**\n * The MCP transports the agent tells a client it speaks beside stdio, which\n * every agent takes.\n */\nexport const MCP_CAPABILITIES = { http: true } as const\n\n/** What went wrong with one MCP server, in the words a client shows the user. */\nexport type McpWarning = {\n readonly title: string\n readonly description: string\n}\n\n/**\n * A session's MCP servers, connected: every tool they offer, the way to\n * close them all, and a warning for each server that was left out.\n */\nexport type McpConnections = {\n readonly tools: ReadonlyArray<Tool>\n readonly close: () => Promise<void>\n readonly warnings: ReadonlyArray<McpWarning>\n}\n\n/** The connections of a session with no MCP servers. */\nexport const NO_MCP: McpConnections = { tools: [], close: async () => {}, warnings: [] }\n\n/** The longest tool name a provider takes. */\nconst NAME_LIMIT = 64\n\n/**\n * The shortest `env` or `headers` value that's cut out of a warning\n * wherever it appears. A shorter one, such as `true` or `8080`, is cut only\n * where it stands whole, since cutting it out of the middle of every word\n * and number would shred the message it happens to appear in.\n */\nconst SECRET_LENGTH = 8\n\n/**\n * The shortest `env` or `headers` value that's cut out of a warning at\n * all. A value of one or two characters, such as `1` or `no`, stands whole\n * in ordinary error text (the `1` of `exit 1`, the last octet of\n * `127.0.0.1`), so cutting it hides the error and protects nothing worth\n * calling a secret.\n */\nconst SHORTEST_CUT = 3\n\n/** How many characters of a hash end a shortened name. */\nconst HASH_LENGTH = 8\n\n/** Who the agent says it is to each server. */\ntype McpIdentity = { readonly name: string; readonly version: string }\n\n/** The validated inputs each session's MCP tools were asked about. */\nconst asked = new WeakMap<AcpSession, WeakSet<object>>()\n\n/**\n * Say on stderr what went wrong with a session's MCP servers, since the\n * session carries on without what failed.\n */\nfunction warn(message: string): void {\n process.stderr.write(`fascicle/acp: ${message}\\n`)\n}\n\n/**\n * A list of names and values as the record a transport takes.\n */\nfunction record_of(entries: ReadonlyArray<{ readonly name: string; readonly value: string }>): Record<string, string> {\n return Object.fromEntries(entries.map(({ name, value }) => [name, value]))\n}\n\n/**\n * How `mcp_client` reaches a server the client sent, or undefined for a\n * transport it doesn't speak. A stdio server starts in the session's cwd\n * with the variables the client gave it on top of the MCP SDK's own short\n * list, so it doesn't inherit the agent's provider keys.\n */\nfunction client_config(server: McpServer, cwd: string): McpClientConfig | undefined {\n if ('command' in server) {\n return { transport: 'stdio', command: server.command, args: [...server.args], env: record_of(server.env), cwd }\n }\n if (server.type === 'http') return { transport: 'http', url: server.url, headers: record_of(server.headers) }\n return undefined\n}\n\n/**\n * `text` with one `env` or `headers` value cut out. A short value is cut\n * where no letter, digit, or underscore adjoins it, and a value under\n * three characters is left where it is.\n */\nfunction without_value(text: string, value: string): string {\n if (value.length < SHORTEST_CUT) return text\n if (value.length >= SECRET_LENGTH) return text.replaceAll(value, '[redacted]')\n const literal = value.replaceAll(/[.*+?^${}()|[\\]\\\\]/g, String.raw`\\$&`)\n return text.replaceAll(new RegExp(String.raw`(?<!\\w)${literal}(?!\\w)`, 'g'), '[redacted]')\n}\n\n/**\n * `text` with the `env` and `headers` values of `server` cut out, the\n * longest first, since an error that quotes one would carry it to stderr\n * and to the client.\n */\nfunction without_secrets(server: McpServer, text: string): string {\n const pairs = 'command' in server ? server.env : 'headers' in server ? server.headers : []\n const values = pairs.map(({ value }) => value)\n return values.toSorted((a, b) => b.length - a.length).reduce(without_value, text)\n}\n\nconst NEEDS_AUTHORIZATION =\n \"it answered 401, which means that its entry in your editor's MCP settings sends no token it accepts (fix the entry's headers)\"\n\n/**\n * The warning for a server left out of the session, also written to\n * stderr, for a client that shows no notices. `error` is the server's own\n * failure, which is the part that can quote one of its values.\n */\nfunction left_out(server: McpServer, reason: string, error?: string): McpWarning {\n const detail = error === undefined ? '' : ` (${without_secrets(server, error)})`\n const description = `${reason}${detail}, so its tools are left out of the session`\n warn(`MCP server ${server.name}: ${description}`)\n return { title: `MCP server ${server.name} isn't connected`, description }\n}\n\n/**\n * Connect to one server, or return the warning that says why it was left\n * out, so the session starts without it. A missing MCP SDK isn't one\n * server's failure, so that error is thrown on.\n */\nasync function connect_server(\n server: McpServer,\n cwd: string,\n identity: McpIdentity,\n): Promise<McpClientHandle | McpWarning> {\n const config = client_config(server, cwd)\n if (config === undefined) return left_out(server, \"it uses a transport this agent doesn't speak\")\n const name_prefix = `mcp__${server.name.replaceAll(/[^\\w-]/g, '_')}__`\n try {\n return await mcp_client(config, { client_info: identity, name_prefix })\n } catch (err: unknown) {\n if (err instanceof Error && err.name === 'mcp_sdk_missing_error') throw err\n // The error's own advice is for the app that called `mcp_client`. Here\n // the entry came from the editor, so the fix is in the editor's settings.\n if (err instanceof Error && err.name === 'mcp_auth_required_error') return left_out(server, NEEDS_AUTHORIZATION)\n return left_out(server, \"it couldn't be reached\", err instanceof Error ? err.message : String(err))\n }\n}\n\n/**\n * Close every connection, warning about any that fails to close rather\n * than leaving the others open.\n */\nasync function close_all(handles: ReadonlyArray<McpClientHandle>): Promise<void> {\n const results = await Promise.allSettled(handles.map((handle) => handle.close()))\n for (const result of results) {\n if (result.status === 'rejected') {\n const reason: unknown = result.reason\n warn(`couldn't close an MCP server (${reason instanceof Error ? reason.message : String(reason)})`)\n }\n }\n}\n\n/**\n * A tool's name cut to the limit, ending in a hash of the server it came\n * from (by its place in the list and its name as the client sent it) and\n * the name `mcp_client` gave the tool, so two tools that would share a name\n * each get one of their own.\n */\nfunction shortened(name: string, server: McpServer, index: number): string {\n const hash = createHash('sha256').update(`${index}\\0${server.name}\\0${name}`).digest('hex').slice(0, HASH_LENGTH)\n return `${name.slice(0, NAME_LIMIT - HASH_LENGTH - 1)}_${hash}`\n}\n\n/**\n * Whether `value` is a connection instead of the warning that stands in\n * for one.\n */\nfunction is_handle(value: McpClientHandle | McpWarning): value is McpClientHandle {\n return 'tools' in value\n}\n\n/**\n * Connect to every server the client sent for a session, all at once, and\n * gather their tools under names no two of them share and no provider\n * refuses.\n */\nexport async function connect_mcp_servers(\n servers: ReadonlyArray<McpServer>,\n cwd: string,\n identity: McpIdentity,\n): Promise<McpConnections> {\n if (servers.length === 0) return NO_MCP\n const settled = await Promise.allSettled(\n servers.map(async (server) => ({ server, entry: await connect_server(server, cwd, identity) })),\n )\n const reached = settled.flatMap((result) => (result.status === 'fulfilled' ? [result.value] : []))\n const handles = reached.map(({ entry }) => entry).filter(is_handle)\n const failed = settled.find((result) => result.status === 'rejected')\n if (failed !== undefined) {\n await close_all(handles)\n throw failed.reason\n }\n const tools = new Map<string, Tool>()\n const warnings: McpWarning[] = []\n // Every server was reached or left out by here, so each one's place in\n // `reached` is its place in the list the client sent.\n reached.forEach(({ server, entry }, index) => {\n if (!is_handle(entry)) {\n warnings.push(entry)\n return\n }\n for (const tool of entry.tools) {\n const name = tool.name.length > NAME_LIMIT || tools.has(tool.name) ? shortened(tool.name, server, index) : tool.name\n if (tools.has(name)) warn(`MCP server ${server.name} offers a tool named ${tool.name} twice, so the second one is left out`)\n else tools.set(name, name === tool.name ? tool : { ...tool, name })\n }\n })\n return { tools: [...tools.values()], close: () => close_all(handles), warnings }\n}\n\n/**\n * Whether one of the session's MCP tools was asked about this very input,\n * which makes the call one of theirs rather than a call to a tool that only\n * shares a name with one.\n */\nexport function is_mcp_call(session: AcpSession, input: unknown): boolean {\n return is_record(input) && asked.get(session)?.has(input) === true\n}\n\n/**\n * The session's MCP tools, each asking before it runs whenever the\n * session's mode asks before a command, and marking the input it was asked\n * about as one of the session's own MCP calls. The tools are made as the\n * session is, so they reach it through `session` at each call.\n */\nexport function gated_mcp_tools(tools: ReadonlyArray<Tool>, session: () => AcpSession): ReadonlyArray<Tool> {\n return tools.map((tool) => ({\n ...tool,\n needs_approval: (input: unknown) => {\n const current = session()\n const inputs = asked.get(current) ?? new WeakSet<object>()\n asked.set(current, inputs)\n if (is_record(input)) inputs.add(input)\n return asks_before(current.mode(), 'command')\n },\n }))\n}\n","/**\n * The preview store: what each workspace tool call changed or ran, kept for\n * the client's card that shows it.\n *\n * A write's card shows its diff and a command's shows its output and exit\n * code, but the model reads back a single line, so the call's result can't\n * carry them. Each tool leaves its call's preview here once the call\n * succeeds, under the engine's raw call id, and `to_session_updates` takes\n * it when that call's result arrives. The file reads behind a diff happen\n * in the tool, before it writes, so the mapper itself stays free of I/O.\n *\n * Raw ids repeat across model calls (Ollama numbers its calls afresh on\n * each one), and the turn's consumer can fall behind the engine, so each id\n * holds a queue, taken oldest first. The engine runs a turn's calls one\n * after another, which keeps each queue in the order its results arrive.\n * Only a call that succeeded leaves a preview, and only a successful result\n * takes one, so a call refused before it ran can't take a later call's.\n *\n * The store belongs to the session and is keyed by the session object, so\n * `AcpSession` carries nothing for it. Each turn starts it empty, so what a\n * cancelled turn left behind never reaches the next.\n */\n\nimport type { AcpSession } from '../types.js'\n\n/**\n * A file change that landed: the path in the client's terms, the text\n * before (`null` for a new file) and after, and for an edit, the line where\n * its first match starts, counting from 1 (a write has none).\n */\nexport type ChangePreview = {\n readonly kind: 'change'\n readonly path: string\n readonly old_text: string | null\n readonly new_text: string\n readonly line: number | undefined\n}\n\n/**\n * A command that ran to its end: what it printed, and its exit code or the\n * signal that ended it.\n */\nexport type CommandPreview = {\n readonly kind: 'command'\n readonly output: string\n readonly exit_code: number | null\n readonly signal: string | null\n}\n\nexport type ToolPreview = ChangePreview | CommandPreview\n\nconst stores = new WeakMap<AcpSession, Map<string, ToolPreview[]>>()\n\n/**\n * The session's store, made empty the first time it's asked for.\n */\nfunction store_of(session: AcpSession): Map<string, ToolPreview[]> {\n const store = stores.get(session) ?? new Map<string, ToolPreview[]>()\n stores.set(session, store)\n return store\n}\n\n/**\n * Empty the session's store as a turn starts.\n */\nexport function reset_previews(session: AcpSession): void {\n stores.set(session, new Map())\n}\n\n/**\n * Leave a call's preview at the back of its raw id's queue.\n */\nexport function record_preview(session: AcpSession, tool_call_id: string, preview: ToolPreview): void {\n const store = store_of(session)\n store.set(tool_call_id, [...(store.get(tool_call_id) ?? []), preview])\n}\n\n/**\n * Take the oldest preview waiting under a raw id, or `undefined` when none\n * is.\n */\nexport function take_preview(session: AcpSession, tool_call_id: string): ToolPreview | undefined {\n return store_of(session).get(tool_call_id)?.shift()\n}\n","/**\n * write_file: create a text file in the workspace, or replace everything one\n * holds.\n *\n * Every write is worked out before it happens, as the file's whole text\n * before and after, so the client can be shown the change as a diff before\n * anything reaches the disk. `edit_file` builds its change from the same\n * pieces, so the two tools agree on what they refuse and how they write.\n *\n * A write lands at the path's real location, which `contain` placed inside a\n * root, and creates the directories it needs there, so a model writing\n * `src/new/thing.ts` doesn't need a command to make `src/new` first.\n */\n\nimport { isUtf8 } from 'node:buffer'\nimport { mkdir, open, stat, writeFile } from 'node:fs/promises'\nimport { dirname } from 'node:path'\nimport type { Tool } from '#engine'\nimport { as_record, json_schema_to_standard } from '#schema'\nimport type { AcpSession } from '../types.js'\nimport { contain_writable, error_code, shown_path } from './containment.js'\nimport type { ContainedPath } from './containment.js'\nimport { record_preview } from './previews.js'\nimport { is_binary } from './read_file.js'\n\n/**\n * A write worked out before anything is written: the file both ways\n * `contain` names it, and its whole text before and after. `old_text` is\n * `null` only when the write creates the file.\n */\nexport type FileChange = ContainedPath & {\n readonly old_text: string | null\n readonly new_text: string\n}\n\n/** A file change as a card or a permission request shows it, with the line an edit lands on. */\nexport type ShownChange = FileChange & { readonly line?: number }\n\n/**\n * The largest file a change reads, in bytes. A change is shown as a diff,\n * which carries the file's whole text twice, as its text before and after,\n * and the closing card update carries it again.\n */\nconst CHANGE_LIMIT_BYTES = 1_000_000\n\n/** One write as the model asked for it. */\ntype WriteRequest = {\n readonly path: string\n readonly content: string\n}\n\n/**\n * Read the call's path and content out of its input.\n */\nfunction write_request(input: unknown): WriteRequest {\n const fields: Record<string, unknown> = as_record(input) ?? {}\n const { path, content } = fields\n if (typeof path !== 'string' || typeof content !== 'string') {\n throw new Error('write_file needs a path and the content to write, as strings')\n }\n return { path, content }\n}\n\n/**\n * The text a write would replace, or `null` when no file is there yet.\n * Anything but a regular UTF-8 text file is refused, because the change is\n * shown as a diff of text, and rewriting a file in another encoding would\n * change bytes outside the edit. A file with other hard links is refused too:\n * a write changes the file under every name it has, and real paths can't say\n * where the other names lie. A file over CHANGE_LIMIT_BYTES is refused from\n * its size, before it's opened. `shown` is the path as the model gave it,\n * and `tool` names the tool asking, for the refusals.\n */\nexport async function current_text(real: string, shown: string, tool: string): Promise<string | null> {\n const info = await stat(real).catch((err: unknown) => {\n if (error_code(err) === 'ENOENT') return undefined\n throw err\n })\n if (info === undefined) return null\n if (info.isDirectory()) throw new Error(`${shown} is a directory; ${tool} changes a file, so name one inside it`)\n if (!info.isFile()) throw new Error(`${shown} isn't a regular file, so ${tool} can't change it`)\n if (info.nlink > 1) {\n throw new Error(\n `${shown} is one of ${info.nlink} hard links to the same file, and the rest may lie outside the workspace, so ${tool} won't change it`,\n )\n }\n if (info.size > CHANGE_LIMIT_BYTES) {\n throw new Error(\n `${shown} is ${info.size} bytes, over the ${CHANGE_LIMIT_BYTES} that write_file and edit_file read to show a change as a diff; change it with run_command instead`,\n )\n }\n const handle = await open(real)\n try {\n if (await is_binary(handle)) {\n throw new Error(`${shown} is a binary file (it has a NUL byte in its first 8 KB), so ${tool} won't change it`)\n }\n // The binary check reads at an explicit position, which leaves the\n // handle's own position at the top, where readFile starts.\n const bytes = await handle.readFile()\n if (!isUtf8(bytes)) throw new Error(`${shown} isn't UTF-8 text, so ${tool} won't change it`)\n return bytes.toString('utf8')\n } finally {\n await handle.close()\n }\n}\n\n/**\n * Write a change's new text where it lands, creating the directories it\n * needs first. A turn cancelled while the change was worked out stops here,\n * before anything is written. A new file is created exclusively, so a file or\n * a symlink that appeared at its path since then stops the write instead of\n * taking it.\n */\nexport async function apply_change(change: FileChange, abort: AbortSignal): Promise<void> {\n abort.throwIfAborted()\n await mkdir(dirname(change.real), { recursive: true })\n await writeFile(change.real, change.new_text, change.old_text === null ? { flag: 'wx' } : {})\n}\n\n/**\n * Leave a change that landed in the session's preview store, for the card\n * of the call that made it to show as a diff.\n */\nexport function record_change(\n session: AcpSession,\n tool_call_id: string,\n change: ShownChange,\n): void {\n record_preview(session, tool_call_id, {\n kind: 'change',\n path: change.path,\n old_text: change.old_text,\n new_text: change.new_text,\n line: change.line,\n })\n}\n\n/**\n * The change a `write_file` call would make, worked out without writing: its\n * path checked against the session's roots and kept out of `.git` and\n * `node_modules`, the text it would replace, and the content that replaces\n * it.\n */\nexport async function write_file_change(session: AcpSession, input: unknown): Promise<FileChange> {\n const request = write_request(input)\n const target = await contain_writable(session, request.path, 'write_file')\n const old_text = await current_text(target.real, request.path, 'write_file')\n return { ...target, old_text, new_text: request.content }\n}\n\n/**\n * The `write_file` tool for one session: a file inside its workspace,\n * created or replaced whole. The model reads back a line saying which, since\n * it already has the text it sent.\n */\nexport function write_file_tool(session: AcpSession): Tool {\n return {\n name: 'write_file',\n description:\n 'Write a text file in the workspace: create it, along with any directories it needs, or replace everything it holds. ' +\n \"content is the file's whole text; to change part of a file, use edit_file. \" +\n 'The path is absolute or relative to the workspace root.',\n input_schema: json_schema_to_standard({\n type: 'object',\n properties: {\n path: { type: 'string', description: 'The file to write, absolute or relative to the workspace root' },\n content: { type: 'string', description: \"The file's whole text\" },\n },\n required: ['path', 'content'],\n additionalProperties: false,\n }),\n execute: async (input, ctx) => {\n const change = await write_file_change(session, input)\n await apply_change(change, ctx.abort)\n record_change(session, ctx.tool_call_id, change)\n return `${change.old_text === null ? 'created' : 'overwrote'} ${shown_path(session, change.path)}`\n },\n }\n}\n","/**\n * edit_file: replace an exact match in a text file in the workspace.\n *\n * The match has to be exact and, unless the call sets `replace_all`, the only\n * one, so the model names enough of the file to say which place it means. A\n * looser match could change a place it never looked at. The change is worked\n * out first, the way `write_file`'s is, as the whole file before and after,\n * with the line where the first match starts for the client to point at.\n */\n\nimport type { Tool } from '#engine'\nimport { as_record, json_schema_to_standard } from '#schema'\nimport type { AcpSession } from '../types.js'\nimport { contain_writable, shown_path } from './containment.js'\nimport { apply_change, current_text, record_change } from './write_file.js'\nimport type { FileChange } from './write_file.js'\n\n/**\n * A change `edit_file` would make. The file exists, so `old_text` is always\n * its text. `line` is where the first match starts, counting from 1, and\n * `matches` is how many places the edit replaces.\n */\nexport type EditChange = FileChange & {\n readonly old_text: string\n readonly line: number\n readonly matches: number\n}\n\n/** One edit as the model asked for it. */\ntype EditRequest = {\n readonly path: string\n readonly old_text: string\n readonly new_text: string\n readonly replace_all: boolean\n}\n\n/**\n * Read the call's path, texts, and `replace_all` out of its input, refusing\n * an `old_text` that's empty, which matches everywhere, or the same as\n * `new_text`, which changes nothing.\n */\nfunction edit_request(input: unknown): EditRequest {\n const fields: Record<string, unknown> = as_record(input) ?? {}\n const { path, old_text, new_text, replace_all = false } = fields\n if (\n typeof path !== 'string' ||\n typeof old_text !== 'string' ||\n typeof new_text !== 'string' ||\n typeof replace_all !== 'boolean'\n ) {\n throw new Error('edit_file needs path, old_text, and new_text as strings, and takes replace_all as true or false')\n }\n if (old_text === '') throw new Error(\"old_text is empty, so there's nothing to find; write_file writes a whole file\")\n if (old_text === new_text) throw new Error('old_text and new_text are the same, so the edit would change nothing')\n return { path, old_text, new_text, replace_all }\n}\n\n/**\n * The change an `edit_file` call would make, worked out without writing: the\n * file's whole text before, and after `old_text` is replaced. It fails on a\n * path that `contain_writable` refuses, when `old_text` isn't there, or when\n * it's there more than once and the call doesn't set `replace_all`.\n */\nexport async function edit_file_change(session: AcpSession, input: unknown): Promise<EditChange> {\n const request = edit_request(input)\n const target = await contain_writable(session, request.path, 'edit_file')\n const text = await current_text(target.real, request.path, 'edit_file')\n if (text === null) throw new Error(`${request.path} doesn't exist; write_file creates a file`)\n // Splitting on the match, where String.replace would read its replacement\n // as a pattern, keeps a `$&` or `$$` in new_text as the model wrote it.\n const pieces = text.split(request.old_text)\n const matches = pieces.length - 1\n if (matches === 0) {\n throw new Error(\n `old_text doesn't appear in ${request.path}; it has to match the file exactly, whitespace included, so read the lines again and copy them without their numbers`,\n )\n }\n if (matches > 1 && !request.replace_all) {\n throw new Error(\n `old_text appears ${matches} times in ${request.path}; include more of the lines around it so it matches once, or set replace_all to replace every one`,\n )\n }\n const before = text.slice(0, text.indexOf(request.old_text))\n return {\n ...target,\n old_text: text,\n new_text: pieces.join(request.new_text),\n line: before.split('\\n').length,\n matches,\n }\n}\n\n/**\n * The `edit_file` tool for one session: an exact match replaced in a file\n * inside its workspace. The model reads back where the edit landed rather\n * than the file again.\n */\nexport function edit_file_tool(session: AcpSession): Tool {\n return {\n name: 'edit_file',\n description:\n 'Edit a text file in the workspace by replacing old_text with new_text. ' +\n 'old_text has to match the file exactly, whitespace and line breaks included, ' +\n 'and appear in it once, unless replace_all is set to replace every match. ' +\n 'Copy it from read_file without the line number and tab that read_file puts before each line. ' +\n 'The path is absolute or relative to the workspace root.',\n input_schema: json_schema_to_standard({\n type: 'object',\n properties: {\n path: { type: 'string', description: 'The file to edit, absolute or relative to the workspace root' },\n old_text: { type: 'string', minLength: 1, description: 'The exact text to replace' },\n new_text: { type: 'string', description: 'The text to put in its place' },\n replace_all: {\n type: 'boolean',\n description: 'Replace every match of old_text, rather than exactly one; default: false',\n },\n },\n required: ['path', 'old_text', 'new_text'],\n additionalProperties: false,\n }),\n execute: async (input, ctx) => {\n const change = await edit_file_change(session, input)\n await apply_change(change, ctx.abort)\n record_change(session, ctx.tool_call_id, change)\n const shown = shown_path(session, change.path)\n return change.matches === 1\n ? `edited ${shown} at line ${change.line}`\n : `edited ${shown} in ${change.matches} places, the first at line ${change.line}`\n },\n }\n}\n","/**\n * run_command: run a shell command in the workspace and hand back what it\n * printed and how it ended.\n *\n * The command is a string the model wrote in POSIX shell, so it runs as\n * `/bin/sh -c`, which behaves the same on every host and needs no read of\n * the user's `$SHELL`. Windows has neither that shell nor POSIX process\n * groups, so there the tool refuses and the file tools carry on.\n *\n * Each command leads a process group of its own, so the whole tree it starts\n * dies together: when the turn is cancelled, when it runs past its timeout,\n * and when the shell exits, which stops whatever it left running in the\n * background. Without that last kill, a job left behind would outlive the\n * call, and then the agent, since nothing would ever abort it. A command\n * that moves work into a group of its own (`set -m` in an interactive\n * shell, or a daemon that starts its own session) takes that work out of\n * reach, as it would from a terminal's Ctrl-C.\n *\n * The file tools' containment doesn't bind a command: the shell reaches\n * anything the user can.\n *\n * This is the one file in `src/acp/` that may import `node:child_process`\n * (rules/no-child-process-outside-run-command.yml).\n */\n\nimport { spawn } from 'node:child_process'\nimport type { ChildProcess } from 'node:child_process'\nimport { StringDecoder } from 'node:string_decoder'\nimport type { Tool } from '#engine'\nimport { as_record, json_schema_to_standard } from '#schema'\nimport type { AcpSession } from '../types.js'\nimport { record_preview } from './previews.js'\nimport type { CommandPreview } from './previews.js'\n\n/** The shell every command runs in. */\nconst SHELL = '/bin/sh'\n\n/**\n * The longest delay a Node timer keeps. A longer one fires after 1 ms\n * instead, so a longer timeout is held to this, about 24.8 days.\n */\nconst MAX_TIMER_MS = 2_147_483_647\n\n/**\n * How long the output may stay open once the shell has exited and its group\n * has been killed. The group's processes are gone by then, so only\n * something moved out of the group can be holding it, and that could hold\n * it for good.\n */\nconst OUTPUT_GRACE_MS = 1000\n\n/** How `run_command` runs one session's commands, from `workspace_tools`' options. */\nexport type CommandSettings = {\n /** How long a call may run, unless it sets its own `timeout_ms`. */\n readonly timeout_ms: number\n /** The most output a call returns, in bytes. */\n readonly output_limit_bytes: number\n /** The whole environment commands run with, or `undefined` to inherit the agent's. */\n readonly env: Readonly<Record<string, string>> | undefined\n}\n\n/** One command as the model asked for it. */\ntype CommandRequest = {\n readonly command: string\n readonly timeout_ms: number | undefined\n}\n\n/**\n * What a command printed, stdout and stderr together in the order they\n * arrived, up to `limit` bytes: the parts kept, the bytes they account\n * for, and every byte the command printed.\n */\ntype Capture = {\n readonly limit: number\n readonly parts: string[]\n kept: number\n total: number\n}\n\n/**\n * Whether a value counts milliseconds: a whole number of at least 1.\n */\nfunction is_millis(value: unknown): value is number {\n return Number.isInteger(value) && Number(value) >= 1\n}\n\n/**\n * Read the call's command and timeout out of its input. The tool loop has\n * already checked the types against the schema, but a flow that wraps the\n * tool can call `execute` directly, and the schema's `minimum` is advice to\n * the model rather than something the loop enforces.\n */\nfunction command_request(input: unknown): CommandRequest {\n const fields: Record<string, unknown> = as_record(input) ?? {}\n const { command, timeout_ms } = fields\n if (typeof command !== 'string') throw new Error('run_command needs a command, as a string')\n if (timeout_ms !== undefined && !is_millis(timeout_ms)) {\n throw new Error('run_command counts timeout_ms in milliseconds, so it has to be a whole number of at least 1')\n }\n return { command, timeout_ms }\n}\n\n/**\n * Keep a chunk of output while the capture has room, cutting the chunk that\n * crosses the limit, and count every byte either way. The output goes on\n * being read past the limit, since a command blocked on a full pipe would\n * never finish.\n */\nfunction take(capture: Capture, chunk: string): void {\n const size = Buffer.byteLength(chunk)\n const room = capture.limit - capture.kept\n capture.total += size\n // Stryker disable next-line ConditionalExpression,EqualityOperator: with no room left the cut below keeps an empty string and counts no bytes, so going on reads the same; the return only spares a copy of every chunk past the cap.\n if (room <= 0) return\n // A chunk that fits comes through whole. One cut at the limit can end\n // inside a character, whose partial bytes the decoder holds back.\n capture.parts.push(new StringDecoder().write(Buffer.from(chunk).subarray(0, room)))\n capture.kept += Math.min(size, room)\n}\n\n/**\n * What a command printed as the model reads it, without its trailing\n * whitespace, with a marker when it was cut, and a line saying so when it\n * printed nothing at all.\n */\nfunction printed(capture: Capture): string[] {\n if (capture.total === 0) return ['[no output]']\n const lines = [capture.parts.join('').trimEnd()]\n if (capture.total > capture.kept) {\n lines.push(\n `[output cut at ${capture.limit} bytes of ${capture.total}; pipe the command through tail, head, or grep to see the part you need]`,\n )\n }\n return lines.filter((line) => line !== '')\n}\n\n/**\n * How a finished command ended, as its report's last line: its exit code,\n * or the signal that ended it. Node sets exactly one of the two.\n */\nfunction ending(child: ChildProcess): string {\n return child.exitCode === null ? `[ended by ${String(child.signalCode)}]` : `[exit code ${child.exitCode}]`\n}\n\n/**\n * A command that ran to its end: what it printed, its process, and whether\n * something it moved out of its group held its output open.\n */\ntype Finished = {\n readonly capture: Capture\n readonly child: ChildProcess\n readonly held: boolean\n}\n\n/**\n * A finished command's report: what it printed, then how it ended, and a\n * note when something it moved out of its group held its output open and\n * was left running.\n */\nfunction report({ capture, child, held }: Finished): string {\n const lines = [...printed(capture), ending(child)]\n if (held) {\n lines.push(\n '[the command exited, but something it moved out of its process group held its output open, so run_command stopped reading and left that running]',\n )\n }\n return lines.join('\\n')\n}\n\n/**\n * A finished command as its card shows it: what it printed, with nothing in\n * place of an empty output, and its exit code or the signal that ended it.\n */\nfunction command_preview({ capture, child }: Finished): CommandPreview {\n return {\n kind: 'command',\n output: capture.total === 0 ? '' : printed(capture).join('\\n'),\n exit_code: child.exitCode,\n signal: child.signalCode,\n }\n}\n\n/**\n * The error a call that ran past its timeout fails with, carrying what the\n * command printed before it was killed.\n */\nfunction timeout_error(capture: Capture, timeout_ms: number): Error {\n return new Error(\n `the command didn't finish within ${timeout_ms / 1000} s, so run_command killed it and everything it started; ` +\n 'pass a larger timeout_ms if it needs longer, but a server or a watch mode never finishes, so run it in a way that does. ' +\n `What it printed before then:\\n${printed(capture).join('\\n')}`,\n )\n}\n\n/**\n * Kill a command's whole process group with SIGKILL, the one signal no\n * command can ignore. The turn's abort can be the agent's last act before\n * `serve_acp` exits, which leaves no later moment to follow a gentler\n * signal with this one.\n */\nfunction kill_group(child: ChildProcess): void {\n // Stryker disable next-line ConditionalExpression: without a pid, process.kill throws on the NaN it's handed, and the catch below takes that the same way.\n if (child.pid === undefined) return\n try {\n process.kill(-child.pid, 'SIGKILL')\n } catch {\n // The group is gone: every process in it has exited.\n }\n}\n\n/**\n * Run one command to its end in its own process group. A command that ends\n * on its own is a result, whatever its exit code; a timeout and a shell that\n * won't start are errors, and the turn's abort rejects with its reason. The\n * timeout and the abort kill the group, and the shell's exit kills whatever\n * it left behind. Each reads on to the end of the output, so what the\n * command printed last isn't lost, until the grace after the shell's exit\n * runs out. However the call ends, its timers and the abort listener go\n * with it.\n */\nasync function run_shell(\n request: CommandRequest,\n cwd: string,\n settings: CommandSettings,\n abort: AbortSignal,\n): Promise<Finished> {\n abort.throwIfAborted()\n const timeout_ms = request.timeout_ms ?? settings.timeout_ms\n const capture: Capture = { limit: settings.output_limit_bytes, parts: [], kept: 0, total: 0 }\n const child = spawn(SHELL, ['-c', request.command], {\n cwd,\n env: settings.env === undefined ? undefined : { ...settings.env },\n detached: true,\n stdio: ['ignore', 'pipe', 'pipe'],\n })\n const { promise, resolve, reject } = Promise.withResolvers<Finished>()\n let timed_out = false\n let held = false\n let settled = false\n let grace: NodeJS.Timeout | undefined\n const on_abort = (): void => {\n kill_group(child)\n reject(abort.reason)\n }\n for (const stream of [child.stdout, child.stderr]) {\n // Stryker disable next-line StringLiteral: Node reads an empty encoding name as UTF-8.\n stream.setEncoding('utf8')\n stream.on('data', (chunk: string) => {\n take(capture, chunk)\n })\n }\n const timer = setTimeout(() => {\n timed_out = true\n kill_group(child)\n }, Math.min(timeout_ms, MAX_TIMER_MS))\n child.once('error', (err) => {\n reject(\n new Error(`run_command couldn't start ${SHELL} in ${cwd} (${err.message}); the workspace may have been moved or deleted`, {\n cause: err,\n }),\n )\n })\n const stop_reading = (): void => {\n child.stdout.destroy()\n child.stderr.destroy()\n }\n child.once('exit', () => {\n clearTimeout(timer)\n kill_group(child)\n // A call the abort has already settled reads nothing more, so its output\n // closes at once, rather than on a grace timer that would outlive it.\n if (settled) {\n stop_reading()\n return\n }\n // Stopping the reads closes the call even while something still holds\n // the other end of the output open.\n grace = setTimeout(() => {\n held = true\n stop_reading()\n }, OUTPUT_GRACE_MS)\n })\n child.once('close', () => {\n if (timed_out) reject(timeout_error(capture, timeout_ms))\n else resolve({ capture, child, held })\n })\n abort.addEventListener('abort', on_abort)\n try {\n return await promise\n } finally {\n settled = true\n clearTimeout(timer)\n clearTimeout(grace)\n abort.removeEventListener('abort', on_abort)\n }\n}\n\n/**\n * The `run_command` tool for one session: a command run through the shell\n * in its `cwd`, with a timeout, an output cap, and the environment the\n * settings give it, its whole process tree killed when the turn is\n * cancelled. POSIX only: on Windows every call is refused.\n */\nexport function run_command_tool(session: AcpSession, settings: CommandSettings): Tool {\n return {\n name: 'run_command',\n description: [\n `Run a shell command with ${SHELL} -c in the workspace root, and return what it printed (stdout and stderr together) and its exit code.`,\n 'Each call starts a fresh shell there, so a cd lasts for its own command only.',\n `The command is stopped after ${settings.timeout_ms / 1000} s unless timeout_ms says otherwise,`,\n `and output past ${settings.output_limit_bytes} bytes is cut, with a note that says so; run it again through tail, head, or grep for the part you need.`,\n 'Give the command plainly, without 2>&1 or a pipe to trim output that may well fit:',\n 'the user can allow a plain command for the rest of the session, but never one that holds a pipe, a redirect, &&, or ;.',\n \"It gets no input, and anything it starts is stopped once it exits, so it can't leave a server or a watcher running.\",\n ].join(' '),\n input_schema: json_schema_to_standard({\n type: 'object',\n properties: {\n command: { type: 'string', description: 'The command line, as you would type it in a POSIX shell' },\n timeout_ms: {\n type: 'integer',\n minimum: 1,\n description: `How long the command may run, in milliseconds; default: ${settings.timeout_ms}`,\n },\n },\n required: ['command'],\n additionalProperties: false,\n }),\n execute: async (input, ctx) => {\n if (process.platform === 'win32') {\n throw new Error(\n `run_command runs commands through ${SHELL} in a process group of their own, which Windows doesn't have, ` +\n 'so it can only refuse here; read_file, list_files, search, write_file, and edit_file still work',\n )\n }\n const finished = await run_shell(command_request(input), session.cwd, settings, ctx.abort)\n record_preview(session, ctx.tool_call_id, command_preview(finished))\n return report(finished)\n },\n }\n}\n","/**\n * workspace_tools: the tools a coding agent served over ACP needs, confined\n * to its session's workspace.\n *\n * They run in-process against the files on disk and in a shell of their\n * own, never through the client's `fs/*` or `terminal/*` methods, which\n * Claude Agent stopped using and the ACP v2 draft drops. They're plain\n * `Tool` values, so a flow can filter them (a read-only critic takes the\n * reads), set its own beside them, or wrap them. Each file tool checks every\n * path it's handed against the session's roots; a command starts in `cwd`\n * and reaches whatever the user can.\n *\n * The writes and `run_command` ask for approval when the session's mode\n * says to, and the reads never do.\n *\n * A flow or an MCP server can hand a model a tool of its own under one of\n * these names, and a name is all the engine tells the approval and the\n * cards. So each session keeps what it built: the names, which pick the\n * cards it draws, and every validated input that its gated tools were\n * asked about, which is how the approval knows its own calls. The engine\n * hands `needs_approval` and the approval handler the same input object,\n * so a same-named tool's call never passes for one of these.\n */\n\nimport type { Tool } from '#engine'\nimport { is_record } from '#schema'\nimport { asks_before } from './modes.js'\nimport type { GatedAction } from './modes.js'\nimport { edit_file_tool } from './tools/edit_file.js'\nimport { list_files_tool } from './tools/list_files.js'\nimport { read_file_tool } from './tools/read_file.js'\nimport { run_command_tool } from './tools/run_command.js'\nimport { search_tool } from './tools/search.js'\nimport { write_file_tool } from './tools/write_file.js'\nimport type { AcpSession, WorkspaceToolsOptions } from './types.js'\n\n/** The most lines one `read_file` call returns unless the options say otherwise. */\nconst READ_LIMIT_LINES = 2000\n\n/** The most paths one `list_files` call returns, so a very large repository's listing can't fill the context. */\nconst LIST_LIMIT = 1000\n\n/** The names `list_files` and `search` skip unless the options say otherwise. */\nconst IGNORE: ReadonlyArray<string> = ['.git', 'node_modules']\n\n/** How long one `search` may run unless the options say otherwise. */\nconst SEARCH_TIMEOUT_MS = 30_000\n\n/** How long one `run_command` call may run unless the options or the call say otherwise. */\nconst COMMAND_TIMEOUT_MS = 120_000\n\n/** The most output one `run_command` call returns unless the options say otherwise. */\nconst OUTPUT_LIMIT_BYTES = 32_000\n\n/**\n * The names each session's `workspace_tools` built. The set takes\n * `undefined` too, so a card whose opening the mapper never saw simply\n * finds nothing.\n */\nconst built = new WeakMap<AcpSession, ReadonlySet<string | undefined>>()\n\n/** The validated inputs each session's gated workspace tools were asked about. */\nconst asked = new WeakMap<AcpSession, WeakSet<object>>()\n\n/**\n * The inputs the session's gated workspace tools were asked about, made\n * empty the first time it's asked for.\n */\nfunction asked_of(session: AcpSession): WeakSet<object> {\n const inputs = asked.get(session) ?? new WeakSet<object>()\n asked.set(session, inputs)\n return inputs\n}\n\n/**\n * Whether the session's `workspace_tools` built a tool named `name`, so its\n * calls take the card that tool's presentation gives it.\n */\nexport function is_workspace_tool(session: AcpSession, name: string | undefined): boolean {\n return built.get(session)?.has(name) === true\n}\n\n/**\n * Whether one of the session's gated workspace tools was asked about this\n * very input, which makes the call one of theirs rather than a call to a\n * tool that only shares a name with one.\n */\nexport function is_workspace_call(session: AcpSession, input: unknown): boolean {\n return is_record(input) && asked.get(session)?.has(input) === true\n}\n\n/**\n * `tool`, asking for approval before each call when the session's mode asks\n * before `action`, and marking the input it was asked about as one of the\n * session's own. The mode is read at each call, not once, so a switch the\n * client makes mid-turn holds from the next call on.\n */\nfunction gated(tool: Tool, session: AcpSession, action: GatedAction): Tool {\n return {\n ...tool,\n needs_approval: (input) => {\n if (is_record(input)) asked_of(session).add(input)\n return asks_before(session.mode(), action)\n },\n }\n}\n\n/**\n * The workspace tools for one session: the reads (`read_file`, `list_files`,\n * and `search`), then the writes (`write_file` and `edit_file`), each\n * confined to the session's `cwd` and additional directories, then\n * `run_command`. The writes and the command ask before they run as the\n * session's mode says. From the first call on, the six names are the\n * workspace tools' within the session.\n */\nexport function workspace_tools(session: AcpSession, options: WorkspaceToolsOptions = {}): ReadonlyArray<Tool> {\n const ignore = options.ignore ?? IGNORE\n const tools = [\n read_file_tool(session, options.read_limit_lines ?? READ_LIMIT_LINES),\n list_files_tool(session, ignore, LIST_LIMIT),\n search_tool(session, ignore, options.search_timeout_ms ?? SEARCH_TIMEOUT_MS),\n gated(write_file_tool(session), session, 'edit'),\n gated(edit_file_tool(session), session, 'edit'),\n gated(\n run_command_tool(session, {\n timeout_ms: options.command_timeout_ms ?? COMMAND_TIMEOUT_MS,\n output_limit_bytes: options.output_limit_bytes ?? OUTPUT_LIMIT_BYTES,\n env: options.command_env,\n }),\n session,\n 'command',\n ),\n ]\n built.set(session, new Set(tools.map((tool) => tool.name)))\n return tools\n}\n","/**\n * presentation: how a workspace tool's call looks in the client, matching\n * what Zed's Claude Agent sends for its own tools.\n *\n * Each card gets the kind that picks its icon, a title that reads like the\n * call (`Read src/a.ts (1 - 40)`, `grep \"todo\" src`, the command line) with\n * its paths relative to `cwd`, and the places it touches as locations, whose\n * lines count from 1 as Claude Agent's do. A write's or an edit's card shows\n * its diff once the call lands, a read's, a listing's, or a search's shows\n * the text the model read in a code block, and a command's shows what it\n * printed: in a terminal when the client advertises Zed's terminal extension\n * (`_meta.terminal_output`), and as a `console` code block otherwise.\n *\n * It's keyed by tool name, since nothing ACP-specific may reach the engine's\n * `Tool` type and a card opens with nothing but the name the model called.\n * Only the names the session's `workspace_tools` built count, so in a\n * session that never built them, a tool of the flow's own that shares a\n * name gets the plain card. It does no I/O: the file reads behind a diff\n * happen in the tools, which leave each call's preview in the session's\n * store for its card to take when the call's result arrives.\n */\n\nimport { resolve } from 'node:path'\nimport type { SessionUpdate, ToolCall, ToolCallContent, ToolCallLocation, ToolKind } from '@agentclientprotocol/sdk'\nimport type { StreamChunk } from '#engine'\nimport { as_record } from '#schema'\nimport { shown_path } from './tools/containment.js'\nimport { take_preview } from './tools/previews.js'\nimport type { ChangePreview, CommandPreview, ToolPreview } from './tools/previews.js'\nimport type { AcpSession } from './types.js'\nimport { is_workspace_tool } from './workspace_tools.js'\n\ntype ToolResultChunk = Extract<StreamChunk, { kind: 'tool_result' }>\n\n/** An update to a card the client already shows. */\nexport type CardUpdate = Extract<SessionUpdate, { sessionUpdate: 'tool_call_update' }>\n\n/** What a call's input says about its card: its title, and the places it touches. */\ntype Described = {\n readonly title: string\n readonly locations?: ToolCallLocation[]\n}\n\n/** How a command ended, as its terminal shows it. */\ntype Ran = Pick<CommandPreview, 'output' | 'exit_code' | 'signal'>\n\n/**\n * How one workspace tool's cards look: the kind that picks the icon, what a\n * call's input says about it, and what its card shows once the call\n * succeeds: the change it made, what the command printed, or the text the\n * model read.\n */\ntype Presenter = {\n readonly kind: ToolKind\n readonly describe: (fields: Record<string, unknown>, session: AcpSession) => Described | undefined\n readonly shows?: 'change' | 'command' | 'text'\n}\n\n/**\n * A path the call names, made absolute under the client's `cwd`, which is\n * how a location and a diff carry it.\n */\nfunction absolute(session: AcpSession, path: string): string {\n return resolve(session.cwd, path)\n}\n\n/**\n * A path as a title shows it: relative to `cwd` when it's under it, and\n * absolute otherwise, the way the tools show paths to the model.\n */\nfunction shown(session: AcpSession, path: string): string {\n return shown_path(session, absolute(session, path))\n}\n\n/**\n * The lines a read covers, as its title says them: a range when the call\n * sets a limit, where it starts when it sets only an offset, and nothing\n * when it reads from the top.\n */\nfunction read_range(first: number, offset: unknown, limit: unknown): string {\n if (typeof limit === 'number') return ` (${first} - ${first + limit - 1})`\n if (typeof offset === 'number') return ` (from line ${offset})`\n return ''\n}\n\n/**\n * A `read_file` card: `Read <path>` with the lines it covers, pointing at\n * the line the read starts on.\n */\nfunction describe_read({ path, offset, limit }: Record<string, unknown>, session: AcpSession): Described | undefined {\n if (typeof path !== 'string') return undefined\n const first = typeof offset === 'number' ? offset : 1\n return {\n title: `Read ${shown(session, path)}${read_range(first, offset, limit)}`,\n locations: [{ path: absolute(session, path), line: first }],\n }\n}\n\n/**\n * A `write_file` or `edit_file` card: the verb and the path, pointing at\n * the file. The line an edit lands on comes with its preview, once the\n * edit has found it.\n */\nfunction describe_change(verb: string): Presenter['describe'] {\n return ({ path }, session) =>\n typeof path === 'string'\n ? { title: `${verb} ${shown(session, path)}`, locations: [{ path: absolute(session, path) }] }\n : undefined\n}\n\n/**\n * A `list_files` card: `Find` with the directory and the pattern in code\n * spans, each when the call names it.\n */\nfunction describe_find({ pattern, path }: Record<string, unknown>, session: AcpSession): Described {\n const parts = ['Find']\n if (typeof path === 'string') parts.push(`\\`${shown(session, path)}\\``)\n if (typeof pattern === 'string') parts.push(`\\`${pattern}\\``)\n return { title: parts.join(' ') }\n}\n\n/**\n * A `search` card, titled the way the grep command line that does the same\n * search reads.\n */\nfunction describe_grep({ pattern, path, glob }: Record<string, unknown>, session: AcpSession): Described {\n const parts = ['grep']\n if (typeof glob === 'string') parts.push(`--include=\"${glob}\"`)\n if (typeof pattern === 'string') parts.push(`\"${pattern}\"`)\n if (typeof path === 'string') parts.push(shown(session, path))\n return { title: parts.join(' ') }\n}\n\n/**\n * A `run_command` card, titled with the command line itself.\n */\nfunction describe_command({ command }: Record<string, unknown>): Described | undefined {\n return typeof command === 'string' ? { title: command } : undefined\n}\n\n/**\n * The workspace tools by name. The key takes `undefined` too, so a card\n * whose opening the mapper never saw simply finds nothing.\n */\nconst PRESENTERS = new Map<string | undefined, Presenter>([\n ['read_file', { kind: 'read', describe: describe_read, shows: 'text' }],\n ['list_files', { kind: 'search', describe: describe_find, shows: 'text' }],\n ['search', { kind: 'search', describe: describe_grep, shows: 'text' }],\n ['write_file', { kind: 'edit', describe: describe_change('Write'), shows: 'change' }],\n ['edit_file', { kind: 'edit', describe: describe_change('Edit'), shows: 'change' }],\n ['run_command', { kind: 'execute', describe: describe_command, shows: 'command' }],\n])\n\n/**\n * How the cards of the tool `name` look in `session`, when the session's\n * `workspace_tools` built a tool of that name. Any other tool gets the\n * plain card.\n */\nfunction presenter_of(session: AcpSession, name: string | undefined): Presenter | undefined {\n return is_workspace_tool(session, name) ? PRESENTERS.get(name) : undefined\n}\n\n/**\n * Whether the client draws a command's output in a terminal from Zed's\n * `_meta` extension, which it says in `initialize`.\n */\nfunction renders_terminals(session: AcpSession): boolean {\n const { _meta: meta } = session.client_capabilities\n return meta?.['terminal_output'] === true\n}\n\n/**\n * The terminal a card shows, under the card's own id, as Claude Agent names\n * its terminals.\n */\nfunction terminal(card: string): ToolCallContent {\n return { type: 'terminal', terminalId: card }\n}\n\n/**\n * What a workspace tool's card opens with: its kind, and for a command in a\n * client that draws terminals, the terminal its output will land in.\n */\nexport function opening_fields(session: AcpSession | undefined, name: string, card: string): Partial<ToolCall> {\n // Stryker disable next-line ConditionalExpression: a missing session built no workspace tools, so presenter_of finds nothing for it either way; the check narrows the type.\n if (session === undefined) return {}\n const presenter = presenter_of(session, name)\n if (presenter === undefined) return {}\n if (presenter.shows !== 'command' || !renders_terminals(session)) return { kind: presenter.kind }\n return { kind: presenter.kind, content: [terminal(card)], _meta: { terminal_info: { terminal_id: card } } }\n}\n\n/**\n * What a workspace tool call's complete input adds to its card: its title\n * and locations. An input that lacks what they need leaves the card as it\n * opened.\n */\nexport function input_fields(session: AcpSession | undefined, name: string | undefined, input: unknown): Partial<CardUpdate> {\n // Stryker disable next-line ConditionalExpression: a missing session built no workspace tools, so presenter_of finds nothing for it either way; the check narrows the type.\n if (session === undefined) return {}\n const presenter = presenter_of(session, name)\n if (presenter === undefined) return {}\n return presenter.describe(as_record(input) ?? {}, session) ?? {}\n}\n\n/**\n * A file change as a diff, which a client shows as the file's hunks.\n */\nfunction diff_of(change: ChangePreview): ToolCallContent {\n return { type: 'diff', path: change.path, oldText: change.old_text, newText: change.new_text }\n}\n\n/**\n * Close a write's or an edit's card with the change it made, and for an\n * edit, the line its first match starts on. The closing update replaces the\n * card's content, so it carries the diff again rather than dropping one the\n * card already shows. A call that failed, or left no change behind, closes\n * as it stands.\n */\nfunction close_change(closing: CardUpdate, preview: ToolPreview | undefined): CardUpdate {\n if (preview?.kind !== 'change') return closing\n return {\n ...closing,\n content: [diff_of(preview)],\n ...(preview.line === undefined ? {} : { locations: [{ path: preview.path, line: preview.line }] }),\n }\n}\n\n/**\n * Text in a code block under the `info` string, its fence longer than any\n * run of backticks that opens one of its lines, so nothing in the text can\n * close the block early.\n */\nfunction code_block(text: string, info: string): ToolCallContent {\n const longest = Math.max(2, ...Array.from(text.matchAll(/^`+/gm), ([run]) => run.length))\n const fence = '`'.repeat(longest + 1)\n return { type: 'content', content: { type: 'text', text: `${fence}${info}\\n${text}\\n${fence}` } }\n}\n\n/**\n * Close a read's, a listing's, or a search's card with the text the model\n * read. A listing or a search result goes in a code block too, since a\n * matching line can hold markdown that the client would otherwise render.\n * A failed call keeps its error text.\n */\nfunction close_text(closing: CardUpdate, chunk: ToolResultChunk): CardUpdate {\n if (chunk.error !== undefined) return closing\n return { ...closing, content: [code_block(String(chunk.output), '')] }\n}\n\n/**\n * How a command's terminal ends: what it printed and how it exited, or, for\n * a call that failed or left nothing behind, the error text and no exit\n * code.\n */\nfunction ran(chunk: ToolResultChunk, preview: ToolPreview | undefined): Ran {\n if (preview?.kind === 'command') return preview\n return { output: chunk.error?.message ?? '', exit_code: null, signal: null }\n}\n\n/**\n * Close a command's card. A client that draws terminals gets the output on\n * the terminal the card opened with, then the exit and the status, as\n * Claude Agent sends them. Any other client gets what the model read, its\n * exit code included, in a `console` block; a failed call keeps its error\n * text.\n */\nfunction close_command(\n session: AcpSession,\n card: string,\n chunk: ToolResultChunk,\n closing: CardUpdate,\n preview: ToolPreview | undefined,\n): SessionUpdate[] {\n if (!renders_terminals(session)) {\n if (chunk.error !== undefined) return [closing]\n return [{ ...closing, content: [code_block(String(chunk.output), 'console')] }]\n }\n const { output, exit_code, signal } = ran(chunk, preview)\n return [\n {\n sessionUpdate: 'tool_call_update',\n toolCallId: card,\n _meta: { terminal_output: { terminal_id: card, data: output } },\n },\n {\n ...closing,\n content: [terminal(card)],\n _meta: { terminal_exit: { terminal_id: card, exit_code, signal } },\n },\n ]\n}\n\n/**\n * The updates that close a tool call's card, starting from the plain\n * `closing` update. A read, a listing, or a search leaves no preview, so its\n * card takes nothing from the session's store. A successful call of a tool\n * that leaves a preview takes it from the store whatever the card then does\n * with it, which keeps each raw id's queue in step with its results.\n */\nexport function closing_updates(\n session: AcpSession | undefined,\n name: string | undefined,\n card: string,\n chunk: ToolResultChunk,\n closing: CardUpdate,\n): SessionUpdate[] {\n // Stryker disable next-line ConditionalExpression: a missing session built no workspace tools, so presenter_of finds nothing for it either way; the check narrows the type.\n if (session === undefined) return [closing]\n const shows = presenter_of(session, name)?.shows\n if (shows === undefined) return [closing]\n if (shows === 'text') return [close_text(closing, chunk)]\n const preview = chunk.error === undefined ? take_preview(session, chunk.id) : undefined\n if (shows === 'change') return [close_change(closing, preview)]\n return close_command(session, card, chunk, closing, preview)\n}\n","/**\n * approve: ask the client before a workspace tool edits a file or runs a\n * command, through `session/request_permission`.\n *\n * The request shows the card the client already draws for the call, and\n * for an edit, the change worked out on disk first, so the user approves\n * the diff itself. It offers Allow, Reject, and an \"always\" that lives in\n * memory for the session. For an edit, \"always\" switches the session to\n * Accept edits, as Claude Agent's does, and tells the client both ways so\n * its mode picker follows. An edit is offered one only when the agent\n * offers Accept edits, since that's the mode it switches to. For a\n * command, it covers that exact command line and nothing else, since one\n * flag can turn a listing into a delete (`find . -name '*.ts'` and\n * `find . -delete`). A command with shell control syntax is never covered\n * and never offered one, since anything can follow a `;` or a `|`.\n *\n * Only the session's own workspace tools get the diff and the \"always\",\n * known by the input their `needs_approval` marked rather than by name. The\n * tools of the MCP servers the client sent ask as a command does, and their\n * \"always\" covers that one tool for the session. A tool of a flow's own\n * that shares a name with either gets the plain request, and no grant\n * covers it.\n *\n * A permission check that fails open isn't a check, so anything short of\n * an allow denies the call: a rejection, a `cancelled` outcome, an option\n * the request never offered, and a request that fails for any reason.\n *\n * The engine asks with its raw call id, which can repeat inside a turn,\n * and the turn's consumer can still be sending earlier updates when it\n * asks. So the request waits until the consumer has sent everything the\n * run had recorded by then, the card's opening included, and points at the\n * latest card the client was sent for that raw id. The consumer never\n * waits on an approval, so the wait can't deadlock, and the turn's abort\n * ends it.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type {\n PermissionOption,\n RequestPermissionOutcome,\n RequestPermissionRequest,\n RequestPermissionResponse,\n SessionUpdate,\n ToolCallUpdate,\n} from '@agentclientprotocol/sdk'\nimport type { TrajectoryEvent, TrajectoryLogger } from '#core'\nimport type { ToolApprovalRequest } from '#engine'\nimport { as_record } from '#schema'\nimport { asks_before } from './modes.js'\nimport type { SessionModes } from './modes.js'\nimport { is_mcp_call } from './mcp_servers.js'\nimport { input_fields, opening_fields } from './presentation.js'\nimport { edit_file_change } from './tools/edit_file.js'\nimport { write_file_change } from './tools/write_file.js'\nimport type { ShownChange } from './tools/write_file.js'\nimport type { AcpSession } from './types.js'\nimport { is_workspace_call } from './workspace_tools.js'\n\n/**\n * What a session's turn tells its approvals: how far the turn's consumer\n * has got, and which card each raw call id opened last.\n *\n * A run that outran the client so far that it dropped events never lets\n * the consumer catch up, so an approval it asks for waits until the turn\n * is cancelled. Only a client that has stopped reading gets that far\n * behind, and it wouldn't answer the request either.\n */\nexport type CardSync = {\n /**\n * Start a turn, forgetting the last one. Returns the logger the turn's\n * run records through, which counts every event `run.stream` queues and\n * passes each one on to `inner`.\n */\n readonly start: (inner: TrajectoryLogger | undefined) => TrajectoryLogger\n /** Note that the consumer has sent every update one event maps to. */\n readonly sent: (event: TrajectoryEvent, updates: ReadonlyArray<SessionUpdate>) => void\n /** Settle once the consumer has sent every event the run had recorded by now. */\n readonly caught_up: () => Promise<void>\n /** The id of the latest card the client was sent for a raw call id. */\n readonly card_for: (raw_id: string) => string | undefined\n}\n\n/** One turn's count of the events its run recorded and its consumer sent. */\ntype TurnProgress = {\n recorded: number\n sent: number\n /** Settles at the consumer's next event, then gives way to a fresh one. */\n moved: PromiseWithResolvers<void>\n readonly cards: Map<string, string>\n}\n\n/**\n * Asks the client to approve one tool call, and withdraws the request\n * when `cancel` fires.\n */\nexport type PermissionAsker = (\n request: RequestPermissionRequest,\n cancel: AbortSignal,\n) => Promise<RequestPermissionResponse>\n\n/** What a session's approvals need beside the session itself. */\nexport type ApproverDeps = {\n readonly modes: SessionModes\n readonly cards: CardSync\n readonly ask: PermissionAsker\n}\n\n/** Answers the engine's approval requests for the calls in one session. */\nexport type SessionApprover = (session: AcpSession, request: ToolApprovalRequest) => Promise<boolean>\n\n/** What an \"always\" for one call covers, under the name the request offers it by. */\ntype Grant = { readonly key: string; readonly name: string }\n\n/**\n * How a call that asks is shown and what may cover it: for a write or an\n * edit, how to work out its change without making it, which also makes it\n * an edit that Accept edits covers, and for a command or an MCP call, what\n * a grant for the session covers. A workspace tool's gate goes by name, but\n * only a call the session's own workspace tool marked ever reaches one.\n */\ntype Gate = {\n readonly change?: (session: AcpSession, input: unknown) => Promise<ShownChange>\n readonly grant?: (request: ToolApprovalRequest) => Grant | undefined\n}\n\nconst GATES: ReadonlyMap<string, Gate> = new Map<string, Gate>([\n ['write_file', { change: write_file_change }],\n ['edit_file', { change: edit_file_change }],\n [\n 'run_command',\n {\n grant: (request) => {\n const line = command_key(request.input)\n return line === undefined ? undefined : { key: `command ${line}`, name: `Always allow \\`${line}\\` this session` }\n },\n },\n ],\n])\n\n/** The gate every MCP tool's call goes through: it asks as a command does, and the grant covers the tool. */\nconst MCP_GATE: Gate = {\n grant: (request) => ({ key: `tool ${request.tool_name}`, name: `Always allow ${request.tool_name} this session` }),\n}\n\n/**\n * The gate a call goes through: its workspace tool's, the MCP tools' for a\n * call one of the session's MCP tools marked, and none for any other call.\n */\nfunction gate_for(session: AcpSession, request: ToolApprovalRequest): Gate | undefined {\n if (is_workspace_call(session, request.input)) return GATES.get(request.tool_name)\n return is_mcp_call(session, request.input) ? MCP_GATE : undefined\n}\n\n/**\n * Shell syntax that runs, chains, or redirects something past the\n * command's own program: `;`, `&`, `|`, `>`, `<`, a backtick, `$(`, and a\n * newline.\n */\nconst CONTROL_SYNTAX = /[;&|<>`\\n]|\\$\\(/\n\n/** The \"always\" an approval offers, and what choosing it grants. */\ntype Always = {\n readonly name: string\n readonly grant: () => Promise<void>\n}\n\nconst ALLOW_ONCE: PermissionOption = { optionId: 'allow_once', name: 'Allow', kind: 'allow_once' }\nconst REJECT_ONCE: PermissionOption = { optionId: 'reject_once', name: 'Reject', kind: 'reject_once' }\n\n/**\n * A fresh count for a turn that has recorded and sent nothing yet.\n */\nfunction fresh_progress(): TurnProgress {\n return { recorded: 0, sent: 0, moved: Promise.withResolvers(), cards: new Map() }\n}\n\n/**\n * `inner`, or nothing, with `count` called after each call that queues an\n * event. Without an inner logger, a span gets an id of its own, as the\n * runner's default logger gives one.\n */\nfunction counting_logger(inner: TrajectoryLogger | undefined, count: () => void): TrajectoryLogger {\n return {\n record: (event) => {\n inner?.record(event)\n count()\n },\n start_span: (name, meta) => {\n const id = inner?.start_span(name, meta) ?? `${name}:${randomUUID()}`\n count()\n return id\n },\n end_span: (id, meta) => {\n inner?.end_span(id, meta)\n count()\n },\n }\n}\n\n/**\n * The raw id of the call a `tool_call_start` chunk opens, or `undefined`\n * for any other event.\n */\nfunction started_call(event: TrajectoryEvent): string | undefined {\n if (event.kind !== 'model_chunk') return undefined\n const chunk = as_record(event['chunk'])\n // Stryker disable next-line ConditionalExpression: a non-string id would land under a key no string lookup finds, so the check only narrows the type.\n return chunk?.['kind'] === 'tool_call_start' && typeof chunk['id'] === 'string' ? chunk['id'] : undefined\n}\n\n/**\n * Whether an update opens a card.\n */\nfunction opens_card(update: SessionUpdate): update is Extract<SessionUpdate, { sessionUpdate: 'tool_call' }> {\n return update.sessionUpdate === 'tool_call'\n}\n\n/**\n * Create the sync between a session's turns and its approvals. Turns in a\n * session never overlap, so one sync serves them all, a turn at a time.\n */\nexport function create_card_sync(): CardSync {\n let turn = fresh_progress()\n return {\n start: (inner) => {\n const started = fresh_progress()\n turn = started\n return counting_logger(inner, () => {\n started.recorded += 1\n })\n },\n sent: (event, updates) => {\n const raw_id = started_call(event)\n const card = updates.find(opens_card)\n // Stryker disable next-line ConditionalExpression: a card noted under no raw id sits where no lookup asks, so the check only narrows the type.\n if (raw_id !== undefined && card !== undefined) turn.cards.set(raw_id, card.toolCallId)\n turn.sent += 1\n turn.moved.resolve()\n turn.moved = Promise.withResolvers()\n },\n caught_up: async () => {\n const waiting = turn\n const target = waiting.recorded\n while (waiting.sent < target) await waiting.moved.promise\n },\n card_for: (raw_id) => turn.cards.get(raw_id),\n }\n}\n\n/**\n * What an \"always\" grant for a command covers: the command line itself,\n * with the whitespace at its ends trimmed and everything between compared\n * exactly, because `rm \"a b\"` and `rm \"a b\"` name different files. A\n * command with shell control syntax has none, so no grant ever covers it,\n * and neither does one that isn't a string or is only whitespace.\n */\nexport function command_key(input: unknown): string | undefined {\n const command = as_record(input)?.['command']\n if (typeof command !== 'string' || CONTROL_SYNTAX.test(command)) return undefined\n const key = command.trim()\n return key === '' ? undefined : key\n}\n\n/**\n * The message a failure carries, whatever was thrown.\n */\nexport function message_of(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\n/**\n * Start `work` and settle with it, or reject with the abort's reason as\n * soon as `abort` fires, so a turn's cancel never waits on the client. A\n * turn already cancelled starts nothing, so no request goes out for it.\n */\nasync function unless_aborted<T>(abort: AbortSignal, work: () => Promise<T>): Promise<T> {\n abort.throwIfAborted()\n const { promise: aborted, reject } = Promise.withResolvers<never>()\n const on_abort = (): void => {\n reject(abort.reason)\n }\n abort.addEventListener('abort', on_abort)\n try {\n return await Promise.race([work(), aborted])\n } finally {\n // The turn's signal outlives every approval it asks for.\n abort.removeEventListener('abort', on_abort)\n }\n}\n\n/**\n * What a change adds to the request's card: its diff, and for an edit,\n * the line its first match starts on. A change that can't be worked out\n * shows why instead, which is what the call will fail with if it's\n * allowed, so the user isn't asked to approve a change they can't see.\n */\nasync function change_fields(\n change: NonNullable<Gate['change']>,\n session: AcpSession,\n input: unknown,\n): Promise<Partial<ToolCallUpdate>> {\n try {\n const { path, old_text, new_text, line } = await change(session, input)\n return {\n content: [{ type: 'diff', path, oldText: old_text, newText: new_text }],\n ...(line === undefined ? {} : { locations: [{ path, line }] }),\n }\n } catch (err: unknown) {\n return { content: [{ type: 'content', content: { type: 'text', text: message_of(err) } }] }\n }\n}\n\n/**\n * The card a request shows: the one the client already draws for the call\n * under `card`, as its tool's presentation describes it, with the change\n * for a write or an edit.\n *\n * A tool with no presenter names no kind. The client applies a request's\n * fields to the card it already drew, so a kind sent here would replace the\n * one the card's own opening gave it, and an absent kind leaves it as it was.\n */\nasync function permission_card(\n session: AcpSession,\n request: ToolApprovalRequest,\n card: string,\n gate: Gate | undefined,\n): Promise<ToolCallUpdate> {\n const { tool_name: name, input } = request\n const { kind } = opening_fields(session, name, card)\n const fields: ToolCallUpdate = {\n toolCallId: card,\n title: name,\n ...(kind === undefined ? {} : { kind }),\n rawInput: input,\n ...input_fields(session, name, input),\n }\n if (gate?.change === undefined) return fields\n return { ...fields, ...(await change_fields(gate.change, session, input)) }\n}\n\n/**\n * Whether the user's answer allows the call, granting the \"always\" first\n * when that's what they chose. Only an option the request offered counts.\n */\nasync function allowed(outcome: RequestPermissionOutcome, always: Always | undefined): Promise<boolean> {\n if (outcome.outcome !== 'selected') return false\n if (outcome.optionId === ALLOW_ONCE.optionId) return true\n if (outcome.optionId !== 'allow_always' || always === undefined) return false\n await always.grant()\n return true\n}\n\n/**\n * Say on stderr that a permission request failed, since the call was\n * refused without the user ever seeing it.\n */\nfunction warn_failed(tool_name: string, err: unknown): void {\n process.stderr.write(\n `fascicle/acp: asking the client to approve ${tool_name} failed (${message_of(err)}), so the call was refused; check that the client answers session/request_permission\\n`,\n )\n}\n\n/**\n * The \"always\" a call is offered: Accept edits for an edit, when the agent\n * offers that mode, and the grant its gate makes for a command line or an\n * MCP tool. Any other call gets none. Choosing Accept edits leaves a session\n * that has moved past Manual since the call asked where it is.\n */\nfunction always_for(\n gate: Gate | undefined,\n grant: Grant | undefined,\n modes: SessionModes,\n granted: Set<string>,\n): Always | undefined {\n if (gate?.change !== undefined) {\n if (!modes.offers('accept_edits')) return undefined\n return {\n name: 'Allow all edits this session',\n grant: async () => {\n if (asks_before(modes.current(), 'edit')) await modes.switch_to('accept_edits')\n },\n }\n }\n if (grant === undefined) return undefined\n return {\n name: grant.name,\n grant: async () => {\n granted.add(grant.key)\n },\n }\n}\n\n/**\n * The options a request offers. Allow is always among them, since some\n * hosts answer every request on their own by choosing `allow_once`.\n */\nfunction options_for(always: Always | undefined): PermissionOption[] {\n if (always === undefined) return [ALLOW_ONCE, REJECT_ONCE]\n return [ALLOW_ONCE, { optionId: 'allow_always', name: always.name, kind: 'allow_always' }, REJECT_ONCE]\n}\n\n/**\n * Create the approvals for one session's calls, holding its commands'\n * \"always\" grants for the life of the session.\n */\nexport function session_approver({ modes, cards, ask }: ApproverDeps): SessionApprover {\n const granted = new Set<string>()\n return async (session, request) => {\n const gate = gate_for(session, request)\n const grant = gate?.grant?.(request)\n // Stryker disable next-line ConditionalExpression: only grants' keys are ever granted, so has() answers false without one either way; the check narrows the type.\n if (grant !== undefined && granted.has(grant.key)) return true\n const always = always_for(gate, grant, modes, granted)\n const options = options_for(always)\n try {\n await unless_aborted(request.abort, cards.caught_up)\n const card = cards.card_for(request.tool_call_id) ?? randomUUID()\n const toolCall = await permission_card(session, request, card, gate)\n const answer = await unless_aborted(request.abort, () =>\n ask({ sessionId: session.id, toolCall, options }, request.abort),\n )\n return await allowed(answer.outcome, always)\n } catch (err: unknown) {\n if (!request.abort.aborted) warn_failed(request.tool_name, err)\n return false\n }\n }\n}\n","/**\n * models: the models a session can run on, offered to the client as a\n * config option in the `model` category, which Zed draws as its model\n * picker.\n *\n * ACP v1 has no model field of its own, so the config option is how the\n * protocol carries one. Each model's id is the agent's, and the flow builder\n * reads it from `session.model()`. A model call takes its model as it's\n * built, so the agent builds the session's flow again whenever the user\n * picks another model, and the pick holds from the next turn on. A model may\n * name its own context window, which the context ring is drawn against while\n * the session runs on it.\n */\n\nimport type { SessionConfigOption } from '@agentclientprotocol/sdk'\nimport type { AcpModel } from './types.js'\n\n/** The id of the config option that carries the model. */\nexport const MODEL_CONFIG_ID = 'model'\n\n/** The models an agent offers and the one each of its sessions starts on. */\nexport type ModelOffer = {\n readonly models: ReadonlyArray<AcpModel>\n readonly default_model: string\n}\n\n/**\n * The models an agent offers, from the config's `models` and\n * `default_model`, or undefined for an agent that offers none. Throws an\n * `Error` that names the problem for a `models` that's empty or lists an id\n * twice, a `default_model` it doesn't list, a `default_model` without\n * `models`, and a flow built once, which can't change its model, so\n * `acp_agent` fails as it's built.\n */\nexport function model_offer(config: {\n readonly models?: ReadonlyArray<AcpModel> | undefined\n readonly default_model?: string | undefined\n readonly flow: unknown\n}): ModelOffer | undefined {\n const { models, default_model } = config\n if (models === undefined) {\n if (default_model === undefined) return undefined\n throw new Error('acp_agent: default_model is set without models; list the models a session can run on, or leave default_model out')\n }\n if (typeof config.flow !== 'function') {\n throw new Error(\n \"acp_agent: models needs flow to be a function of the session, since a flow built once can't change its model; build the flow with session.model()\",\n )\n }\n const ids = models.map((model) => model.id)\n const [first] = ids\n if (first === undefined) throw new Error('acp_agent: models is empty; list at least one model, or leave models out')\n const repeated = ids.find((id, index) => ids.indexOf(id) !== index)\n if (repeated !== undefined) {\n throw new Error(`acp_agent: models lists ${JSON.stringify(repeated)} twice; give each model its own id`)\n }\n const start = default_model ?? first\n if (!ids.includes(start)) {\n throw new Error(\n `acp_agent: default_model ${JSON.stringify(start)} isn't one of the models (${ids.join(', ')}); add it to models or leave default_model out`,\n )\n }\n return { models, default_model: start }\n}\n\n/**\n * Whether the agent offers a model with the id `id`.\n */\nexport function offers_model(offer: ModelOffer, id: unknown): id is string {\n return offer.models.some((model) => model.id === id)\n}\n\n/**\n * The model a session starts on: the one it was stored with when the agent\n * still offers it, and the offer's `default_model` otherwise, or undefined\n * for an agent that offers none.\n */\nexport function start_model(offer: ModelOffer | undefined, stored: string | undefined): string | undefined {\n if (offer === undefined) return undefined\n return offers_model(offer, stored) ? stored : offer.default_model\n}\n\n/**\n * The refusal for a model id the agent doesn't offer, naming the ones it does.\n */\nexport function unknown_model_message(id: unknown, offer: ModelOffer): string {\n return `unknown model ${JSON.stringify(id)}; choose one of ${offer.models.map((model) => model.id).join(', ')}`\n}\n\n/**\n * The session's model as a config option, a select over every model the\n * agent offers, or none for an agent that offers no models.\n */\nexport function model_options(offer: ModelOffer | undefined, model: string | undefined): SessionConfigOption[] {\n if (offer === undefined || model === undefined) return []\n return [\n {\n id: MODEL_CONFIG_ID,\n name: 'Model',\n description: 'The model that answers the next turn',\n category: 'model',\n type: 'select',\n currentValue: model,\n options: offer.models.map(({ id, name, description }) => ({\n value: id,\n name: name ?? id,\n ...(description === undefined ? {} : { description }),\n })),\n },\n ]\n}\n\n/**\n * The context window a session's context ring is drawn against: the\n * window its model names, and the config's `context_window` otherwise.\n */\nexport function context_window_of(\n config: { readonly models?: ReadonlyArray<AcpModel> | undefined; readonly context_window?: number | undefined },\n model: string | undefined,\n): number | undefined {\n return config.models?.find((entry) => entry.id === model)?.context_window ?? config.context_window\n}\n","/**\n * Maps a run's events onto ACP `session/update` payloads.\n *\n * Under `run.stream`, each `model_call` records `model_chunk` events carrying\n * the engine's `StreamChunk`, the same source fascicle/ui reads. This half of\n * a prompt turn does no I/O and holds no SDK value, so a flow author can wrap\n * `to_session_updates` in their own `to_updates` and add to what it returns,\n * as long as every event still reaches it: each `span_start` advances the\n * state's count of how many times a step has run, and a workspace tool's\n * result takes its call's preview from the session's store. Spans, `cost`,\n * and `emit` events map to nothing; an `emit` never becomes chat output\n * implicitly, because output that changes with a value's shape is a trap.\n *\n * Every tool gets a plain card here. Given the turn's session, the workspace\n * tools' cards also take the look `presentation.ts` gives them.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type { ContentBlock, SessionUpdate } from '@agentclientprotocol/sdk'\nimport type { TrajectoryEvent } from '#core'\nimport type { StreamChunk } from '#engine'\nimport { closing_updates, input_fields, opening_fields } from './presentation.js'\nimport type { CardUpdate } from './presentation.js'\nimport type { AcpMapperOptions, AcpMapperState, AcpStreamRoute } from './types.js'\n\ntype ToolResultChunk = Extract<StreamChunk, { kind: 'tool_result' }>\n\n/**\n * Create the state for one prompt turn's events, routing every model call's\n * text to the reply unless `stream` says otherwise.\n */\nexport function create_acp_mapper_state(options: AcpMapperOptions = {}): AcpMapperState {\n return {\n turn_id: options.turn_id ?? randomUUID(),\n stream: options.stream ?? (() => 'message'),\n runs: new Map(),\n session: options.session,\n tools: new Map(),\n }\n}\n\n/**\n * Build the session-unique ACP id for an engine tool call id.\n *\n * Raw ids repeat across model calls, turns, and runs of one model call\n * (Ollama has none on the wire, so the engine numbers them\n * `ollama_call_<step>_<n>` afresh on every generate call), and a repeated id\n * would make the client update an old card instead of opening a new one.\n */\nfunction acp_tool_call_id(state: AcpMapperState, step_id: string, raw_id: string): string {\n return `${state.turn_id}:${step_id}:${state.runs.get(step_id) ?? 0}:${raw_id}`\n}\n\n/**\n * Count one more run of the step a `span_start` opens, by the `id` its span\n * carries. Counting starts rather than finishes covers a retry whose first\n * attempt failed before it finished.\n */\nfunction count_run(event: TrajectoryEvent, state: AcpMapperState): void {\n const id = event['id']\n if (typeof id === 'string') state.runs.set(id, (state.runs.get(id) ?? 0) + 1)\n}\n\n/**\n * Wrap streamed text as the update its route names, or nothing for `'none'`.\n */\nfunction text_updates(route: AcpStreamRoute, text: string): SessionUpdate[] {\n const content: ContentBlock = { type: 'text', text }\n if (route === 'message') return [{ sessionUpdate: 'agent_message_chunk', content }]\n if (route === 'thought') return [{ sessionUpdate: 'agent_thought_chunk', content }]\n return []\n}\n\n/**\n * Close a tool card: `completed` with the raw output, or `failed` with the\n * error text as the card's content, since that text is what the user needs\n * to see.\n */\nfunction tool_result_update(tool_call_id: string, chunk: ToolResultChunk): CardUpdate {\n if (chunk.error !== undefined) {\n return {\n sessionUpdate: 'tool_call_update',\n toolCallId: tool_call_id,\n status: 'failed',\n content: [{ type: 'content', content: { type: 'text', text: chunk.error.message } }],\n }\n }\n return {\n sessionUpdate: 'tool_call_update',\n toolCallId: tool_call_id,\n status: 'completed',\n rawOutput: chunk.output,\n }\n}\n\n/**\n * Map one engine `StreamChunk` from the model call `step_id` to the session\n * updates it produces.\n */\nfunction map_chunk(chunk: StreamChunk, step_id: string, state: AcpMapperState): SessionUpdate[] {\n switch (chunk.kind) {\n case 'text':\n return text_updates(state.stream(step_id), chunk.text)\n case 'reasoning':\n return text_updates('thought', chunk.text)\n case 'tool_call_start': {\n const card = acp_tool_call_id(state, step_id, chunk.id)\n state.tools.set(card, chunk.name)\n return [\n {\n sessionUpdate: 'tool_call',\n toolCallId: card,\n title: chunk.name,\n kind: 'other',\n status: 'pending',\n ...opening_fields(state.session, chunk.name, card),\n },\n ]\n }\n case 'tool_call_end': {\n const card = acp_tool_call_id(state, step_id, chunk.id)\n return [\n {\n sessionUpdate: 'tool_call_update',\n toolCallId: card,\n status: 'in_progress',\n rawInput: chunk.input,\n ...input_fields(state.session, state.tools.get(card), chunk.input),\n },\n ]\n }\n case 'tool_result': {\n const card = acp_tool_call_id(state, step_id, chunk.id)\n return closing_updates(state.session, state.tools.get(card), card, chunk, tool_result_update(card, chunk))\n }\n default:\n // The input arrives whole at tool_call_end, so its deltas add nothing,\n // and step_finish and finish carry no content for the client.\n return []\n }\n}\n\n/**\n * Narrow the loose `chunk` field of a `model_chunk` event. model_call records\n * only real StreamChunks there, and map_chunk maps a kind it doesn't know to\n * nothing, so ruling out a missing or null value is enough.\n */\nexport function is_stream_chunk(value: unknown): value is StreamChunk {\n return typeof value === 'object' && value !== null\n}\n\n/**\n * Map one run event to zero or more ACP session updates. Only `model_chunk`\n * events produce any. A `span_start` advances the state's run count, a\n * card's opening records its tool, and a workspace tool's result takes its\n * preview; the function does no I/O.\n */\nexport function to_session_updates(event: TrajectoryEvent, state: AcpMapperState): SessionUpdate[] {\n if (event.kind === 'span_start') {\n count_run(event, state)\n return []\n }\n if (event.kind !== 'model_chunk') return []\n const step_id = event['step_id']\n const chunk = event['chunk']\n if (typeof step_id !== 'string' || !is_stream_chunk(chunk)) return []\n return map_chunk(chunk, step_id, state)\n}\n","/**\n * transcript: one turn as the client saw it, kept so `session/load` can show\n * the thread again.\n *\n * A turn's record is its prompt as `user_message_chunk` updates, then every\n * update the turn sent. A reply streams as one chunk per token, so adjacent\n * text chunks of one kind are joined into one, which keeps a turn's record\n * to a few entries for each message. Tool calls and their updates stay as\n * they were sent, so an edit's diff and a command's output replay as they\n * appeared. What tells the client about the session instead of adding to the\n * thread (its title, its usage, a notice) stays out, since a load sends the\n * title and the usage as they stand now.\n */\n\nimport type { ContentBlock, SessionUpdate } from '@agentclientprotocol/sdk'\n\n/** A turn's record as it builds up. */\nexport type Transcript = {\n /** Adds an update the client was sent. */\n readonly note: (update: SessionUpdate) => void\n /** The record so far. */\n readonly updates: () => SessionUpdate[]\n}\n\ntype TextChunk = Extract<SessionUpdate, { sessionUpdate: 'user_message_chunk' | 'agent_message_chunk' | 'agent_thought_chunk' }>\n\n/** The updates about the session, which a turn's record leaves out. */\nconst ABOUT_THE_SESSION: ReadonlySet<string> = new Set(['session_info_update', 'usage_update', 'notice'])\n\n/**\n * Whether `update` carries a run of text, which is what gets joined.\n */\nfunction is_text_chunk(update: SessionUpdate): update is TextChunk {\n const kind = update.sessionUpdate\n if (kind !== 'user_message_chunk' && kind !== 'agent_message_chunk' && kind !== 'agent_thought_chunk') return false\n return update.content.type === 'text'\n}\n\n/**\n * Everything about a text chunk but its text, as one string. Two chunks join\n * only when this matches, so a chunk that belongs to another message stays\n * its own.\n */\nfunction rest_of(chunk: TextChunk): string {\n return JSON.stringify({ ...chunk, content: { ...chunk.content, text: '' } })\n}\n\n/**\n * `first` with the text of `second` after its own.\n */\nfunction joined(first: TextChunk, second: TextChunk): SessionUpdate {\n if (first.content.type !== 'text' || second.content.type !== 'text') return first\n return { ...first, content: { ...first.content, text: first.content.text + second.content.text } }\n}\n\n/**\n * Add `update` to `updates`, joined onto the last one when both are text\n * chunks that differ only in their text.\n */\nfunction append(updates: SessionUpdate[], update: SessionUpdate): void {\n const last = updates.at(-1)\n if (last !== undefined && is_text_chunk(last) && is_text_chunk(update) && rest_of(last) === rest_of(update)) {\n updates[updates.length - 1] = joined(last, update)\n return\n }\n updates.push(structuredClone(update))\n}\n\n/**\n * Start a turn's record with the prompt the client sent, one\n * `user_message_chunk` for each block, with adjacent text joined.\n */\nexport function create_transcript(prompt: ReadonlyArray<ContentBlock>): Transcript {\n const updates: SessionUpdate[] = []\n for (const content of prompt) append(updates, { sessionUpdate: 'user_message_chunk', content })\n return {\n note: (update) => {\n if (!ABOUT_THE_SESSION.has(update.sessionUpdate)) append(updates, update)\n },\n updates: () => updates,\n }\n}\n","/**\n * usage: what a session has spent and how full its context is, read off the\n * run events of its turns, and the stop reason a turn's model calls earn.\n *\n * The engine's tool loop records a `response_received` event for each model\n * turn and a `cost` event for each turn it prices, and a model call records\n * a `finish` chunk once its loop ends. A provider that runs its own loop,\n * such as `claude_cli`, reports each turn as a `step_finish` chunk instead,\n * and some providers send both. The context a session holds is the last\n * model turn's input and output, since the next turn sends all of it again,\n * and its cost is the sum of every priced turn. The client draws both as a\n * context ring, which needs the model's context window, so the agent sends\n * them only when its config names one.\n */\n\nimport type { SessionUpdate, StopReason } from '@agentclientprotocol/sdk'\nimport type { TrajectoryEvent } from '#core'\nimport type { FinishReason, StreamChunk } from '#engine'\nimport { is_stream_chunk } from './to_session_updates.js'\n\n/** What a session has spent so far, kept across its turns. */\nexport type SessionUsage = {\n /** The last model turn's input and output tokens, which the next turn sends again. */\n context_tokens: number\n /** Every priced model turn's cost, in US dollars. */\n cost_usd: number\n /** Whether any model turn was priced; the client hears no cost until one is. */\n priced: boolean\n}\n\n/**\n * A session's usage before its first turn.\n */\nexport function create_session_usage(): SessionUsage {\n return { context_tokens: 0, cost_usd: 0, priced: false }\n}\n\n/**\n * The stream chunk a `model_chunk` event carries, or undefined for any other\n * event.\n */\nfunction chunk_of(event: TrajectoryEvent): StreamChunk | undefined {\n if (event.kind !== 'model_chunk') return undefined\n const chunk = event['chunk']\n return is_stream_chunk(chunk) ? chunk : undefined\n}\n\n/**\n * The tokens a model turn left in the context, from either way a turn is\n * reported, or undefined for any other event.\n */\nfunction context_of(event: TrajectoryEvent): number | undefined {\n if (event.kind === 'response_received') {\n const input = event['input_tokens']\n const output = event['output_tokens']\n return typeof input === 'number' && typeof output === 'number' ? input + output : undefined\n }\n const chunk = chunk_of(event)\n return chunk?.kind === 'step_finish' ? chunk.usage.input_tokens + chunk.usage.output_tokens : undefined\n}\n\n/**\n * Fold one run event into the session's usage, and say whether it changed,\n * so a turn that a provider reports twice tells the client once.\n */\nexport function note_usage(usage: SessionUsage, event: TrajectoryEvent): boolean {\n if (event.kind === 'cost') {\n const total = event['total_usd']\n if (typeof total !== 'number') return false\n usage.cost_usd += total\n usage.priced = true\n return true\n }\n const context = context_of(event)\n if (context === undefined || context === usage.context_tokens) return false\n usage.context_tokens = context\n return true\n}\n\n/**\n * The session's usage as the update a client draws its context ring from,\n * against a context window of `size` tokens.\n */\nexport function usage_update(usage: SessionUsage, size: number): SessionUpdate {\n return {\n sessionUpdate: 'usage_update',\n used: usage.context_tokens,\n size,\n ...(usage.priced ? { cost: { amount: usage.cost_usd, currency: 'USD' } } : {}),\n }\n}\n\n/**\n * The finish reason a model call's `finish` chunk carries, or undefined for\n * any other event.\n */\nexport function finish_reason_of(event: TrajectoryEvent): FinishReason | undefined {\n const chunk = chunk_of(event)\n return chunk?.kind === 'finish' ? chunk.finish_reason : undefined\n}\n\n/**\n * The stop reason for a turn that wasn't cancelled, from the finish reason of\n * the last model call that finished in it, which is the one whose reply the\n * user reads. A call that ran out of tool turns, ran out of output tokens, or\n * was stopped by the provider's filter says so, rather than reading as a turn\n * that finished.\n */\nexport function stop_reason_for(finish: FinishReason | undefined): StopReason {\n if (finish === 'max_steps') return 'max_turn_requests'\n if (finish === 'length') return 'max_tokens'\n if (finish === 'content_filter') return 'refusal'\n return 'end_turn'\n}\n","/**\n * One ACP prompt turn: run the session's flow through `run.stream` and send\n * what it produces to the client as session updates.\n *\n * The turn holds three rules the protocol leaves to the agent. A cancel\n * (`session/cancel`, the request's own `$/cancel_request`, a disconnect, or\n * the config's `abort`) stops the sending at once, then waits for the run to\n * settle and answers `cancelled`, even when the flow ignored the abort and\n * finished. A turn that sent no message text sends `to_text(output)` as its\n * reply. And the history records what the client was actually sent, a\n * cancelled turn included, so it matches the thread the user sees.\n *\n * A turn that the history keeps also leaves its transcript, the prompt and\n * every update the client was sent, for the agent to hand its session\n * store, which is what a loaded thread is shown again from.\n */\n\nimport type { ContentBlock, PromptResponse, SessionUpdate } from '@agentclientprotocol/sdk'\nimport { aborted_error, run } from '#core'\nimport type { Step, TrajectoryEvent } from '#core'\nimport type { FinishReason } from '#engine'\nimport { is_record } from '#schema'\nimport type { CardSync } from './approve.js'\nimport { context_window_of } from './models.js'\nimport { create_acp_mapper_state, to_session_updates } from './to_session_updates.js'\nimport { create_transcript } from './transcript.js'\nimport { reset_previews } from './tools/previews.js'\nimport { finish_reason_of, note_usage, stop_reason_for, usage_update } from './usage.js'\nimport type { SessionUsage } from './usage.js'\nimport type { AcpHistoryEntry, AcpSession, AcpTurn, ServeAcpConfig } from './types.js'\n\n/**\n * A session's latest turn, finished or not. Cancelling a finished turn does\n * nothing and waiting on it returns at once, so the record never needs\n * clearing.\n */\ntype TurnHandle = {\n readonly cancel: AbortController\n readonly settled: Promise<void>\n}\n\n/**\n * A session between turns: its flow, its history, its latest turn, the sync\n * that lets its approvals wait for the client to catch up, what it has spent,\n * its title, which stays null until its first turn names it, and the\n * transcripts of the turns the agent hasn't handed its store yet.\n */\nexport type SessionRecord<i, o> = {\n readonly session: AcpSession\n /** Built again when the user picks another model, so a turn reads it as it starts. */\n flow: Step<i, o>\n readonly history: AcpHistoryEntry[]\n readonly cards: CardSync\n readonly usage: SessionUsage\n last_turn: TurnHandle | null\n title: string | null\n readonly unsaved_turns: SessionUpdate[][]\n}\n\nexport type SendUpdate = (update: SessionUpdate) => Promise<void>\n\ntype Reply = { sent: boolean; text: string; card_since_text: boolean }\n\ntype Settled<o> = { readonly ok: true; readonly output: o } | { readonly ok: false; readonly error: unknown }\n\n/**\n * Join a prompt's blocks into the text a flow reads. Text blocks join as the\n * client split them, and a resource link or an embedded resource reads as\n * its URI where it sat. Each embedded resource's text follows the prompt in\n * a `<context>` block naming that URI, the form Claude Agent uses, so a file\n * the user @-mentioned reaches the model without splitting the sentence that\n * mentions it. Image and audio blocks stay in `turn.prompt` only, since the\n * agent advertises neither.\n */\nfunction turn_text(prompt: ReadonlyArray<ContentBlock>): string {\n const inline: string[] = []\n const context: string[] = []\n for (const block of prompt) {\n if (block.type === 'text') inline.push(block.text)\n else if (block.type === 'resource_link') inline.push(block.uri)\n else if (block.type === 'resource') {\n inline.push(block.resource.uri)\n if ('text' in block.resource) {\n context.push(`<context ref=\"${block.resource.uri}\">\\n${block.resource.text}\\n</context>`)\n }\n }\n }\n return [inline.join(''), ...context].join('\\n\\n')\n}\n\n/**\n * The flow's input for a turn: the config's `to_input`, or the turn's text,\n * which `ServeAcpConfig` allows only when the flow takes a string.\n */\nfunction turn_input<i, o>(config: ServeAcpConfig<i, o>, turn: AcpTurn): i {\n if (config.to_input !== undefined) return config.to_input(turn)\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return turn.text as i\n}\n\n/** The most characters a default title keeps. */\nconst TITLE_LIMIT = 60\n\n/**\n * The default `to_title`: the first line of the turn's text with its\n * whitespace collapsed, cut to `TITLE_LIMIT` characters.\n */\nfunction default_title(turn: AcpTurn): string {\n const line = turn.text.split('\\n').find((text) => text.trim() !== '') ?? ''\n const words = line.trim().replaceAll(/\\s+/g, ' ')\n return words.length <= TITLE_LIMIT ? words : `${words.slice(0, TITLE_LIMIT - 1).trimEnd()}…`\n}\n\n/**\n * Name the session from its first turn, and tell the client, which shows it\n * on the thread. A session already named keeps its title, and an empty one\n * leaves the thread untitled.\n */\nasync function name_session<i, o>(\n config: ServeAcpConfig<i, o>,\n record: SessionRecord<i, o>,\n turn: AcpTurn,\n send: SendUpdate,\n): Promise<void> {\n if (record.title !== null) return\n record.title = (config.to_title ?? default_title)(turn)\n if (record.title !== '') await send({ sessionUpdate: 'session_info_update', title: record.title })\n}\n\n/**\n * The default `to_text`: a string as-is, anything else as JSON, and nothing\n * at all for a flow that returns nothing.\n */\nfunction default_to_text(output: unknown): string {\n return typeof output === 'string' ? output : (JSON.stringify(output) ?? '')\n}\n\n/**\n * Wrap a turn's final text as the message update that carries it.\n */\nfunction agent_message(text: string): SessionUpdate {\n return { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text } }\n}\n\n/**\n * Count a message update the client was sent toward the turn's reply. Only\n * text joins the reply's text, but any message counts as a reply, so a flow\n * that sent an image doesn't get a `to_text` message after it. A tool card\n * that opened after some reply text splits the reply in two on the client,\n * so the recorded text starts the next run on a blank line instead of\n * running the two together.\n */\nfunction note_reply(reply: Reply, update: SessionUpdate): void {\n if (update.sessionUpdate === 'tool_call' && reply.text !== '') reply.card_since_text = true\n if (update.sessionUpdate !== 'agent_message_chunk') return\n reply.sent = true\n if (update.content.type !== 'text' || update.content.text === '') return\n reply.text += reply.card_since_text ? `\\n\\n${update.content.text}` : update.content.text\n reply.card_since_text = false\n}\n\n/**\n * Append a turn to the session's history: the user's text, then the reply\n * text the client was sent, when there was any. A cancelled turn marks\n * whichever of the two came last.\n */\nfunction record_exchange(history: AcpHistoryEntry[], user_text: string, reply_text: string, cancelled: boolean): void {\n const stop = cancelled ? { cancelled: true as const } : {}\n if (reply_text === '') history.push({ role: 'user', text: user_text, ...stop })\n else history.push({ role: 'user', text: user_text }, { role: 'agent', text: reply_text, ...stop })\n}\n\n/**\n * Settle a run's result into a value, so a run that fails while the turn is\n * still sending never surfaces as an unhandled rejection.\n */\nfunction settle<o>(result: Promise<o>): Promise<Settled<o>> {\n return result.then(\n (output): Settled<o> => ({ ok: true, output }),\n (error: unknown): Settled<o> => ({ ok: false, error }),\n )\n}\n\n/**\n * Say on stderr that the run outran the client and dropped events, since the\n * reply the client shows is missing text from that point on.\n */\nfunction warn_dropped(event: TrajectoryEvent): void {\n process.stderr.write(\n `fascicle/acp: the client read updates slower than the run produced them, so ${String(event['count'])} run events were dropped and the reply is missing text from that point; send the prompt again for the whole reply\\n`,\n )\n}\n\n/**\n * Send `updates` in order until the turn is cancelled, and say whether all\n * of them went out.\n */\nasync function send_all(updates: ReadonlyArray<SessionUpdate>, cancelled: AbortSignal, send: SendUpdate): Promise<boolean> {\n for (const update of updates) {\n if (cancelled.aborted) return false\n await send(update)\n }\n return true\n}\n\n/**\n * Fold a run event into the session's usage, and return the `usage_update`\n * that a change sends, when the config names the context window.\n */\nfunction usage_updates<i, o>(config: ServeAcpConfig<i, o>, record: SessionRecord<i, o>, event: TrajectoryEvent): SessionUpdate[] {\n const changed = note_usage(record.usage, event)\n const window = context_window_of(config, record.session.model())\n return changed && window !== undefined ? [usage_update(record.usage, window)] : []\n}\n\n/**\n * Send each run event's updates in order, and tell the session's card sync\n * once all of an event's updates have gone out. Each event also folds into\n * the session's usage, and a change goes out as a `usage_update` when the\n * config names the context window. Once the turn is cancelled nothing more\n * is sent, and leaving the loop closes the run's event stream. Resolves with\n * the finish reason of the last model call that finished.\n */\nasync function forward<i, o>(\n events: AsyncIterable<TrajectoryEvent>,\n config: ServeAcpConfig<i, o>,\n record: SessionRecord<i, o>,\n cancelled: AbortSignal,\n send: SendUpdate,\n): Promise<FinishReason | undefined> {\n const state = create_acp_mapper_state({ stream: config.stream, session: record.session })\n const to_updates = config.to_updates ?? to_session_updates\n let finish: FinishReason | undefined\n for await (const event of events) {\n if (event.kind === 'events_dropped') warn_dropped(event)\n finish = finish_reason_of(event) ?? finish\n const updates = to_updates(event, state)\n if (!(await send_all(updates, cancelled, send))) return finish\n record.cards.sent(event, updates)\n if (!(await send_all(usage_updates(config, record, event), cancelled, send))) return finish\n }\n return finish\n}\n\n/**\n * The finish reason of a model call that threw because it ended before its\n * schema validated, or undefined for any other failure. The engine throws\n * `incomplete_generation_error` for that, known here by its `kind`, since\n * the turn answers with a stop reason where the client can say what\n * happened in its own words.\n */\nfunction incomplete_finish(error: unknown): FinishReason | undefined {\n if (!is_record(error) || error['kind'] !== 'incomplete_generation_error') return undefined\n const finish = error['finish_reason']\n return finish === 'length' || finish === 'max_steps' || finish === 'content_filter' ? finish : undefined\n}\n\n/**\n * End a turn whose run has settled and wasn't cancelled. A run that\n * finished sends `to_text(output)` as the reply when the turn sent none. A\n * run that threw because a schema call ended early resolves with that\n * call's finish reason, which decides the turn's stop reason, and any other\n * failure is thrown on.\n */\nasync function end_run<i, o>(\n config: ServeAcpConfig<i, o>,\n result: Settled<o>,\n reply: Reply,\n send: SendUpdate,\n): Promise<FinishReason | undefined> {\n if (result.ok) {\n const final_text = (config.to_text ?? default_to_text)(result.output)\n if (!reply.sent && final_text !== '') await send(agent_message(final_text))\n return undefined\n }\n const finish = incomplete_finish(result.error)\n if (finish === undefined) throw result.error\n return finish\n}\n\n/**\n * Run the flow for one turn, forward its updates, and record the exchange.\n * The run has always settled by the time this returns or throws, so a turn\n * never leaves a run behind. A turn that ends in a refusal stays out of the\n * history and leaves no transcript, since the protocol has the client leave\n * it out of the next prompt too. A flow that throws because a schema call\n * ran out of tokens or steps, or was filtered, ends the turn with that stop\n * reason instead of failing the request.\n */\nasync function run_turn<i, o>(\n config: ServeAcpConfig<i, o>,\n record: SessionRecord<i, o>,\n prompt: ReadonlyArray<ContentBlock>,\n cancelled: AbortSignal,\n send: SendUpdate,\n): Promise<PromptResponse> {\n const turn: AcpTurn = {\n session_id: record.session.id,\n cwd: record.session.cwd,\n text: turn_text(prompt),\n prompt,\n history: [...record.history],\n }\n const reply: Reply = { sent: false, text: '', card_since_text: false }\n const transcript = create_transcript(prompt)\n const send_update: SendUpdate = async (update) => {\n await send(update)\n note_reply(reply, update)\n transcript.note(update)\n }\n const stop = new AbortController()\n // A turn cancelled before its consumer caught up leaves previews nobody\n // took, and raw ids repeat from turn to turn.\n reset_previews(record.session)\n const handle = run.stream(record.flow, turn_input(config, turn), {\n abort: AbortSignal.any([cancelled, stop.signal]),\n install_signal_handlers: false,\n // Every event the run queues for the consumer passes through here first,\n // which is how an approval knows what the client hasn't been sent yet.\n trajectory: record.cards.start(config.trajectory),\n })\n const outcome = settle(handle.result)\n let finish: FinishReason | undefined\n try {\n // The run starts first, so a client slow to take the title holds up only\n // the updates queued behind it.\n await name_session(config, record, turn, send_update)\n finish = await forward(handle.events, config, record, cancelled, send_update)\n const result = await outcome\n if (!cancelled.aborted) finish = (await end_run(config, result, reply, send_update)) ?? finish\n } catch (err: unknown) {\n stop.abort(new aborted_error('the prompt turn failed before its run finished'))\n await outcome\n if (!cancelled.aborted) throw err\n }\n const stop_reason = cancelled.aborted ? 'cancelled' : stop_reason_for(finish)\n if (stop_reason !== 'refusal') {\n record_exchange(record.history, turn.text, reply.text, cancelled.aborted)\n record.unsaved_turns.push(transcript.updates())\n }\n return { stopReason: stop_reason }\n}\n\n/**\n * Run one prompt turn and answer with its stop reason. A new prompt cancels\n * the session's turn in flight and waits for it to settle first, so it sees\n * that turn in its history and never runs beside it.\n */\nexport async function prompt_turn<i, o>(\n config: ServeAcpConfig<i, o>,\n record: SessionRecord<i, o>,\n prompt: ReadonlyArray<ContentBlock>,\n request_signal: AbortSignal,\n send: SendUpdate,\n): Promise<PromptResponse> {\n const previous = record.last_turn\n const cancel = new AbortController()\n const { promise: settled, resolve: settle_turn } = Promise.withResolvers<void>()\n record.last_turn = { cancel, settled }\n try {\n if (previous !== null) {\n previous.cancel.abort(new aborted_error('a new prompt replaced the turn'))\n await previous.settled\n }\n const signals = [cancel.signal, request_signal, ...(config.abort === undefined ? [] : [config.abort])]\n return await run_turn(config, record, prompt, AbortSignal.any(signals), send)\n } finally {\n settle_turn()\n }\n}\n\n/**\n * Cancel the session's latest turn on the client's `session/cancel`.\n */\nexport function cancel_turn<i, o>(record: SessionRecord<i, o>): void {\n record.last_turn?.cancel.abort(new aborted_error('the ACP client cancelled the turn'))\n}\n","/**\n * Typed errors for the ACP adapter.\n *\n * Listed alongside src/mcp/errors.ts in the `no-class` rule ignores:\n * `instanceof` branching is how callers tell a missing optional peer apart\n * from a failure inside a prompt turn.\n */\n\nexport class acp_sdk_missing_error extends Error {\n readonly kind = 'acp_sdk_missing_error' as const;\n constructor(\n message = '@agentclientprotocol/sdk is required for fascicle/acp; install it with its zod peer: pnpm add @agentclientprotocol/sdk zod',\n ) {\n super(message)\n this.name = 'acp_sdk_missing_error'\n }\n}\n","/**\n * Lazy loader for the optional `@agentclientprotocol/sdk` peer.\n *\n * The adapter needs SDK values (the `agent()` builder, `ndJsonStream`,\n * `RequestError`), so it imports the SDK dynamically rather than statically:\n * a consumer can import `fascicle/acp` without the SDK installed and only pays\n * for it when they serve a flow. A missing peer surfaces as a typed\n * `acp_sdk_missing_error` with install guidance, mirroring\n * src/mcp/sdk_loader.ts.\n *\n * The package root is the SDK's stable protocol v1 entry; v2 sits under its\n * `experimental/` subpaths, which fascicle never imports. The SDK imports\n * `zod/v4` at runtime as its own peer, so a missing zod fails here too, and\n * the error names both installs.\n */\n\nimport { acp_sdk_missing_error } from './errors.js'\n\n/**\n * Dynamically imports the `@agentclientprotocol/sdk` v1 entry, throwing a\n * typed `acp_sdk_missing_error` when the optional peer (or its zod peer) is\n * not installed.\n */\nexport async function load_acp_sdk() {\n try {\n return await import('@agentclientprotocol/sdk')\n } catch (err: unknown) {\n const detail = err instanceof Error ? err.message : String(err)\n throw new acp_sdk_missing_error(\n `@agentclientprotocol/sdk is required for fascicle/acp; install it with its zod peer: pnpm add @agentclientprotocol/sdk zod (cause: ${detail})`,\n )\n }\n}\n","/**\n * session_list: the page of stored sessions one `session/list` answers with.\n *\n * Sessions list newest first, 50 to a page. A cursor names the last session\n * of the page before it, by when it changed and its id, so a session saved\n * between two pages moves to the front without pushing one the client has\n * seen onto the next page. The protocol leaves a cursor opaque to the\n * client, and has an agent refuse one that isn't valid.\n */\n\nimport type { AcpSessionSummary } from './types.js'\n\n/** The most sessions one `session/list` answers with. */\nexport const PAGE_SIZE = 50\n\n/** One page of sessions, and the cursor for the page after it when more remain. */\nexport type SessionPage = {\n readonly sessions: ReadonlyArray<AcpSessionSummary>\n readonly next_cursor?: string | undefined\n}\n\ntype Position = Pick<AcpSessionSummary, 'updated_at' | 'id'>\n\n/**\n * Order two sessions newest first, and by id where two changed in the same\n * millisecond, so the order is the same every time it's asked for.\n */\nfunction newest_first(a: Position, b: Position): number {\n return b.updated_at.localeCompare(a.updated_at) || a.id.localeCompare(b.id)\n}\n\n/**\n * The cursor that names `last` as the end of a page.\n */\nfunction cursor_after(last: Position): string {\n return Buffer.from(JSON.stringify([last.updated_at, last.id]), 'utf8').toString('base64url')\n}\n\n/**\n * The session a cursor names, or undefined for a string that isn't one of\n * this agent's cursors.\n */\nfunction cursor_position(cursor: string): Position | undefined {\n let value: unknown\n try {\n value = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'))\n } catch {\n return undefined\n }\n if (!Array.isArray(value) || value.length !== 2) return undefined\n const [updated_at, id]: unknown[] = value\n return typeof updated_at === 'string' && typeof id === 'string' ? { updated_at, id } : undefined\n}\n\n/**\n * The page of `summaries` that follows `cursor`, or the first page without\n * one, keeping only the sessions that started in `cwd` when it's given.\n * Returns undefined for a cursor that isn't valid.\n */\nexport function session_page(\n summaries: ReadonlyArray<AcpSessionSummary>,\n cwd: string | null | undefined,\n cursor: string | null | undefined,\n): SessionPage | undefined {\n const listed = summaries.filter((summary) => cwd === undefined || cwd === null || summary.cwd === cwd).toSorted(newest_first)\n let rest = listed\n if (cursor !== undefined && cursor !== null) {\n const position = cursor_position(cursor)\n if (position === undefined) return undefined\n rest = listed.filter((summary) => newest_first(position, summary) < 0)\n }\n const sessions = rest.slice(0, PAGE_SIZE)\n const last = sessions.at(-1)\n return rest.length > PAGE_SIZE && last !== undefined ? { sessions, next_cursor: cursor_after(last) } : { sessions }\n}\n","/**\n * acp_agent: the ACP agent app that answers each prompt turn by running a\n * flow.\n *\n * It registers the protocol v1 handlers and holds the sessions, and connects\n * to anything the SDK can: `serve_acp`'s stdio streams, or an in-process\n * `client()` in a test. It doesn't own the process, so it leaves the console\n * and the engine alone; `serve_acp` handles both.\n *\n * Given a session store, it saves each session after every turn and every\n * mode or model switch, and answers `session/list`, `session/load`,\n * `session/resume`, and `session/delete` from it. A loaded session gets a\n * fresh flow from the config, and the history it carries is what its next\n * turn starts from.\n *\n * A session holds what the client gave it until the client closes it with\n * `session/close` or drops the connection: its MCP servers, for an agent\n * that connects to them, are closed then, and a closed session leaves\n * memory, though not the store.\n *\n * A request that names a session the agent doesn't hold fails with -32002\n * and the id as `data.sessionId`, which is how the protocol has an agent\n * say that a session is gone, and what a host reads before it offers to\n * start the thread over. Given an `auth`, the agent offers a login and\n * refuses to start, load, or resume a session until the login is ready.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type {\n AgentApp,\n AgentContext,\n AuthMethod,\n ClientCapabilities,\n ListSessionsResponse,\n McpServer,\n SessionConfigOption,\n SessionInfo,\n SessionUpdate,\n} from '@agentclientprotocol/sdk'\nimport { create_card_sync, message_of, session_approver } from './approve.js'\nimport type { PermissionAsker } from './approve.js'\nimport { connect_mcp_servers, gated_mcp_tools, MCP_CAPABILITIES, NO_MCP } from './mcp_servers.js'\nimport type { McpConnections, McpWarning } from './mcp_servers.js'\nimport {\n context_window_of,\n MODEL_CONFIG_ID,\n model_offer,\n model_options,\n offers_model,\n start_model,\n unknown_model_message,\n} from './models.js'\nimport type { ModelOffer } from './models.js'\nimport { config_options, MODE_CONFIG_ID, mode_offer, mode_state, session_modes, unknown_mode_message } from './modes.js'\nimport type { ModeOffer, SessionModes } from './modes.js'\nimport { cancel_turn, prompt_turn } from './prompt_turn.js'\nimport type { SessionRecord } from './prompt_turn.js'\nimport { load_acp_sdk } from './sdk_loader.js'\nimport { session_page } from './session_list.js'\nimport { resolve_roots } from './tools/containment.js'\nimport type {\n AcpAuth,\n AcpHistoryEntry,\n AcpMode,\n AcpSession,\n AcpSessionStore,\n AcpSessionSummary,\n AcpStoredSession,\n ServeAcpConfig,\n} from './types.js'\nimport { create_session_usage, usage_update } from './usage.js'\nimport type { SessionUsage } from './usage.js'\n\ntype AcpSdk = Awaited<ReturnType<typeof load_acp_sdk>>\n\n/**\n * A session as the agent holds it: what a turn needs, its mode, its model,\n * its MCP servers as the client sent them and as connected, the warnings\n * about them the client hasn't been shown, how many of its turns the store\n * keeps (null for a session whose turns aren't kept), the latest save,\n * which the next save waits on so two never write at once, and the prompts\n * that haven't answered yet, each done once its turn is saved. A deleted\n * session saves nothing more.\n */\ntype AgentSession<i, o> = SessionRecord<i, o> & {\n readonly modes: SessionModes\n readonly model: { id: string | undefined }\n mcp: McpConnections\n mcp_servers: ReadonlyArray<McpServer>\n /** Hands the session's flow builder another set of connections' tools. */\n readonly use_mcp: (connections: McpConnections) => void\n readonly notices: McpWarning[]\n turns: number | null\n saving: Promise<void>\n readonly prompts: Set<Promise<void>>\n deleted: boolean\n}\n\n/**\n * What a session starts from: its workspace, the MCP servers the client\n * sent for it, and for a stored one, where it left off.\n */\ntype SessionStart = {\n readonly id: string\n readonly cwd: string\n readonly additional_directories: ReadonlyArray<string>\n readonly mcp_servers: ReadonlyArray<McpServer>\n readonly stored?: AcpStoredSession | undefined\n}\n\n/** What a load or a resume asks for, once its directories are checked. */\ntype ReopenRequest = {\n readonly sessionId: string\n readonly cwd: string\n readonly additional_directories: ReadonlyArray<string>\n readonly mcp_servers: ReadonlyArray<McpServer> | undefined\n}\n\n/** Every config option id a session can have, as a refusal lists them. */\nconst CONFIG_IDS = `${MODE_CONFIG_ID} and ${MODEL_CONFIG_ID}`\n\n/** The id of the login every client is offered, which `authenticate` takes. */\nconst LOGIN_METHOD = 'login'\n\n/** The id of the login a client runs in a terminal. */\nconst TERMINAL_LOGIN_METHOD = 'terminal-login'\n\nconst ONE_CONNECTION =\n 'acp_agent: this app already serves a connection; build an app for each connection, as serve_acp does'\n\n/**\n * Turn a failure inside a handler into a JSON-RPC error that carries its\n * message. The SDK reports a plain thrown `Error` as a bare \"Internal error\",\n * which tells the user in the client nothing about what went wrong.\n */\nfunction internal_error(sdk: AcpSdk, err: unknown): Error {\n return sdk.RequestError.internalError(undefined, message_of(err))\n}\n\n/**\n * The error for a request that names a session the agent doesn't hold:\n * -32002 with the id as `data.sessionId`, as the protocol asks. It's built\n * here because the SDK's own helper for it is newer than the oldest SDK the\n * peer range takes.\n */\nfunction unknown_session(sdk: AcpSdk, sessionId: string): Error {\n return new sdk.RequestError(-32002, 'Resource not found', { sessionId })\n}\n\n/**\n * The error that tells a client the user has to log in first, which it\n * answers by offering the agent's login methods.\n */\nfunction login_required(sdk: AcpSdk, auth: AcpAuth): Error {\n return new sdk.RequestError(-32000, `Authentication required: ${auth.instructions}`)\n}\n\n/**\n * The error for a load or a resume that names a session with another cwd\n * than the one it started in, which the protocol has the client send.\n */\nfunction other_cwd(sdk: AcpSdk, method: string, sessionId: string, started_in: string, cwd: string): Error {\n return sdk.RequestError.invalidParams(\n { sessionId, cwd },\n `session ${sessionId} started in ${started_in}; send that cwd with ${method}`,\n )\n}\n\n/**\n * The login methods an agent offers a client. Every client gets the one\n * the agent checks by itself, which is what the ACP registry looks for,\n * and a client that can run a terminal login also gets that one.\n */\nfunction auth_methods(auth: AcpAuth | undefined, capabilities: ClientCapabilities): AuthMethod[] {\n if (auth === undefined) return []\n const shown = { name: auth.name, ...(auth.description === undefined ? {} : { description: auth.description }) }\n const agent_login: AuthMethod = { id: LOGIN_METHOD, ...shown }\n if (auth.terminal_args === undefined || capabilities.auth?.terminal !== true) return [agent_login]\n return [agent_login, { type: 'terminal', id: TERMINAL_LOGIN_METHOD, ...shown, args: [...auth.terminal_args] }]\n}\n\n/**\n * Whether two lists of MCP servers are the same list, entry for entry.\n */\nfunction same_servers(a: ReadonlyArray<McpServer>, b: ReadonlyArray<McpServer>): boolean {\n return JSON.stringify(a) === JSON.stringify(b)\n}\n\n/**\n * A function that sends one update to the client for one session.\n */\nfunction sender(sdk: AcpSdk, client: AgentContext, sessionId: string): (update: SessionUpdate) => Promise<void> {\n return (update) => client.notify(sdk.methods.client.session.update, { sessionId, update })\n}\n\n/**\n * A function that asks the client to approve one tool call. The SDK\n * withdraws the request with `$/cancel_request` once `cancel` fires, which\n * is the turn's abort, so a cancelled turn takes its prompt down with it.\n */\nfunction permission_asker(sdk: AcpSdk, client: AgentContext): PermissionAsker {\n return (request, cancel) =>\n client.request(sdk.methods.client.session.requestPermission, request, { cancellationSignal: cancel })\n}\n\n/**\n * The model a client asked for, or an invalid-params error naming the\n * models the agent offers.\n */\nfunction requested_model(sdk: AcpSdk, offer: ModelOffer, id: unknown): string {\n if (offers_model(offer, id)) return id\n throw sdk.RequestError.invalidParams({ value: id }, unknown_model_message(id, offer))\n}\n\n/**\n * The mode a client asked for, or an invalid-params error naming the modes\n * the agent offers, for a mode it doesn't know and one it leaves out alike.\n * `field` is the param the id arrived in, for the error's data.\n */\nfunction requested_mode(\n sdk: AcpSdk,\n offer: ModeOffer,\n modes: SessionModes,\n id: unknown,\n field: 'modeId' | 'value',\n): AcpMode {\n if (modes.offers(id)) return id\n throw sdk.RequestError.invalidParams({ [field]: id }, unknown_mode_message(id, offer))\n}\n\n/**\n * The additional directories a client sent with a session request, or, from\n * an agent whose config sets `additional_directories: false`, an\n * invalid-params error refusing them. Every session request that carries\n * `additionalDirectories` goes through this check before its roots resolve,\n * so each one refuses them the same way. The protocol reads an empty list as\n * none, so an empty list passes.\n */\nfunction requested_directories(\n sdk: AcpSdk,\n config: { readonly additional_directories?: boolean | undefined },\n method: string,\n directories: ReadonlyArray<string> = [],\n): ReadonlyArray<string> {\n if (config.additional_directories !== false || directories.length === 0) return directories\n throw sdk.RequestError.invalidParams(\n { additionalDirectories: directories },\n `this agent works in cwd alone and takes no additional directories; send ${method} without additionalDirectories`,\n )\n}\n\n/**\n * A session's state as the store keeps it, copied, so a turn that runs while\n * the save is writing can't change what it writes. Its count of turns isn't\n * here, since the save adds it once it has written them.\n */\nfunction stored_session<i, o>(record: AgentSession<i, o>): AcpStoredSession {\n return {\n id: record.session.id,\n cwd: record.session.cwd,\n additional_directories: [...record.session.additional_directories],\n mode: record.modes.current(),\n model: record.model.id,\n title: record.title,\n updated_at: new Date().toISOString(),\n history: structuredClone(record.history),\n usage: { ...record.usage },\n }\n}\n\n/**\n * Save a session after the save before it: first each turn the store hasn't\n * been handed, for a store that keeps turns, then the session, whose count\n * of turns then reaches them. A turn leaves `unsaved_turns` and joins the\n * count only once it's written, so a turn whose write failed goes with the\n * next save instead of leaving a hole in the thread. A session with no\n * history yet isn't saved, so a thread the user never wrote in doesn't fill\n * the list, and neither is a deleted one. A failed save is reported on\n * stderr rather than failing the turn the user already watched finish, and\n * it leaves the session as it was in the store.\n */\nfunction save_session<i, o>(config: ServeAcpConfig<i, o>, record: AgentSession<i, o>): Promise<void> {\n const store = config.session_store\n if (store === undefined || record.deleted || record.history.length === 0) {\n record.unsaved_turns.length = 0\n return Promise.resolve()\n }\n const { save_turn } = store\n const snapshot = stored_session(record)\n const report = (err: unknown): void => {\n process.stderr.write(`fascicle/acp: couldn't save session ${snapshot.id}: ${message_of(err)}\\n`)\n }\n if (record.turns === null || save_turn === undefined) {\n record.unsaved_turns.length = 0\n record.saving = record.saving.then(() => store.save(snapshot)).catch(report)\n return record.saving\n }\n // The history is copied now and names the turns that go with it, by the\n // number the last of them will have, so a turn that ends while this save\n // waits its place isn't written by it.\n const through = record.turns + record.unsaved_turns.length\n record.saving = record.saving\n .then(async () => {\n // The saves ahead of this one have written their turns by now, and\n // the count says how many of this one's turns they took with them.\n const first = record.turns ?? 0\n const unsaved = record.unsaved_turns.slice(0, through - first)\n await Promise.all(unsaved.map((updates, offset) => save_turn(snapshot.id, first + offset, updates)))\n record.unsaved_turns.splice(0, unsaved.length)\n record.turns = first + unsaved.length\n return store.save({ ...snapshot, turns: record.turns })\n })\n .catch(report)\n return record.saving\n}\n\n/**\n * A history entry as the update that shows it again in a loaded thread.\n */\nfunction replayed(entry: AcpHistoryEntry): SessionUpdate {\n const content = { type: 'text' as const, text: entry.text }\n return entry.role === 'user'\n ? { sessionUpdate: 'user_message_chunk', content }\n : { sessionUpdate: 'agent_message_chunk', content }\n}\n\n/**\n * A stored session as `session/list` reports one.\n */\nfunction session_info(summary: AcpSessionSummary): SessionInfo {\n return {\n sessionId: summary.id,\n cwd: summary.cwd,\n updatedAt: summary.updated_at,\n ...(summary.additional_directories.length > 0 ? { additionalDirectories: [...summary.additional_directories] } : {}),\n ...(summary.title !== null && summary.title !== '' ? { title: summary.title } : {}),\n }\n}\n\n/**\n * Build the ACP agent app that answers each prompt turn by running the\n * config's flow, with its handlers registered and not yet connected.\n *\n * An app serves one connection for its life, since its sessions and the\n * client's capabilities aren't scoped to a connection. A second `connect`\n * throws, and so, for a server that routes a second client to the same app\n * and runs `initialize` before any connect hook, does a second `initialize`,\n * before it can overwrite the first client's capabilities.\n */\nexport async function acp_agent<i, o>(config: ServeAcpConfig<i, o>): Promise<AgentApp> {\n // A bad config fails here, before the SDK loads, so the error names it.\n const offer = mode_offer(config)\n const models = model_offer(config)\n const sdk = await load_acp_sdk()\n const sessions = new Map<string, AgentSession<i, o>>()\n // The stored sessions being opened, so a second request for one waits\n // for the first instead of opening it again.\n const opening = new Map<string, Promise<AgentSession<i, o>>>()\n const store = config.session_store\n const identity = { name: config.name, version: config.version ?? '0.0.0' }\n let client_capabilities: ClientCapabilities = {}\n let connected = false\n let initialized = false\n const { auth } = config\n const session_of = (sessionId: string): AgentSession<i, o> => {\n const record = sessions.get(sessionId)\n if (record !== undefined) return record\n throw unknown_session(sdk, sessionId)\n }\n // A session that can't run shouldn't look started or restored, so each\n // request that opens one asks the login first.\n const require_login = async (): Promise<void> => {\n if (auth === undefined) return\n const ready = await Promise.resolve()\n .then(() => auth.ready())\n .catch((err: unknown) => {\n throw internal_error(sdk, err)\n })\n if (!ready) throw login_required(sdk, auth)\n }\n const connect = (servers: ReadonlyArray<McpServer>, cwd: string): Promise<McpConnections> =>\n config.mcp_servers === true\n ? connect_mcp_servers(servers, cwd, identity).catch((err: unknown) => {\n throw internal_error(sdk, err)\n })\n : Promise.resolve(NO_MCP)\n // A notice is a live message that only a client that asked for notices\n // may be sent. The warnings already went to stderr for every other one.\n const send_notices = async (client: AgentContext, record: AgentSession<i, o>): Promise<void> => {\n const warnings = record.notices.splice(0)\n if (client_capabilities.session?.notices === undefined || client_capabilities.session.notices === null) return\n const send = sender(sdk, client, record.session.id)\n // A notice is fire-and-forget, so one that can't be sent is dropped\n // instead of failing the request it rode in on.\n await Promise.all(\n warnings.map(({ title, description }) =>\n send({ sessionUpdate: 'notice', severity: 'warning', title, description }).catch(() => {}),\n ),\n )\n }\n // Every option a session has, the mode first, as each answer and each\n // config option update reports them.\n const options_of = (record: AgentSession<i, o>): SessionConfigOption[] => [\n ...config_options(offer, record.modes.current()),\n ...model_options(models, record.model.id),\n ]\n const build_flow = async (session: AcpSession) => (typeof config.flow === 'function' ? config.flow(session) : config.flow)\n // The roots resolve once, here, so every containment check compares\n // against the same real paths for the life of the session. The MCP\n // servers connect before the flow is built, since the builder hands their\n // tools to the model, and close again when the builder throws.\n const open_session = async (client: AgentContext, start: SessionStart): Promise<AgentSession<i, o>> => {\n const { id, cwd, additional_directories, stored } = start\n const roots = await resolve_roots([cwd, ...additional_directories]).catch((err: unknown) => {\n throw sdk.RequestError.invalidParams({ cwd, additionalDirectories: additional_directories }, message_of(err))\n })\n const model = { id: start_model(models, stored?.model) }\n const modes = session_modes(offer, sender(sdk, client, id), stored?.mode, () => model_options(models, model.id))\n const cards = create_card_sync()\n const approver = session_approver({ modes, cards, ask: permission_asker(sdk, client) })\n const mcp = await connect(start.mcp_servers, cwd)\n // The flow builder reads the tools off the session each time it runs, so\n // a session handed another list of servers builds its next flow on them.\n const tools = { gated: gated_mcp_tools(mcp.tools, () => session) }\n const session: AcpSession = {\n id,\n cwd,\n additional_directories,\n roots,\n client_capabilities,\n mode: modes.current,\n model: () => model.id,\n get mcp_tools() {\n return tools.gated\n },\n approve: (request) => approver(session, request),\n }\n const usage: SessionUsage = stored === undefined ? create_session_usage() : { ...stored.usage }\n // Turns are kept from a session's first one or not at all, so a session\n // stored without them goes on replaying its history's text.\n const keeps_turns = store?.save_turn !== undefined && store.load_turns !== undefined\n try {\n const record: AgentSession<i, o> = {\n session,\n flow: await build_flow(session),\n history: structuredClone([...(stored?.history ?? [])]),\n cards,\n usage,\n last_turn: null,\n title: stored?.title ?? null,\n unsaved_turns: [],\n modes,\n model,\n mcp,\n mcp_servers: start.mcp_servers,\n use_mcp: (connections) => {\n tools.gated = gated_mcp_tools(connections.tools, () => session)\n },\n notices: [...mcp.warnings],\n turns: keeps_turns ? (stored === undefined ? 0 : (stored.turns ?? null)) : null,\n saving: Promise.resolve(),\n prompts: new Set(),\n deleted: false,\n }\n sessions.set(id, record)\n return record\n } catch (err: unknown) {\n await mcp.close()\n throw internal_error(sdk, err)\n }\n }\n // A live session handed another list of MCP servers connects to the new\n // list and builds its flow again, as a model switch does, so its next turn\n // has the new tools. The old connections close once the turn in flight has\n // settled, since its flow still calls them. A builder that throws leaves\n // the session on the servers it had.\n const switch_servers = async (record: AgentSession<i, o>, servers: ReadonlyArray<McpServer>): Promise<void> => {\n if (config.mcp_servers !== true || same_servers(record.mcp_servers, servers)) return\n const previous = record.mcp\n const next = await connect(servers, record.session.cwd)\n record.use_mcp(next)\n try {\n record.flow = await build_flow(record.session)\n } catch (err: unknown) {\n record.use_mcp(previous)\n await next.close()\n throw internal_error(sdk, err)\n }\n record.mcp = next\n record.mcp_servers = servers\n record.notices.push(...next.warnings)\n void Promise.resolve(record.last_turn?.settled).then(() => previous.close())\n }\n // A stored session is opened from the store with the cwd it started in,\n // which the client must send. The directories the request sends replace\n // the stored ones, and a request that sends none keeps them, unless the\n // agent works in cwd alone.\n const restore = async (\n client: AgentContext,\n method: 'session/load' | 'session/resume',\n request: ReopenRequest,\n session_store: AcpSessionStore,\n ): Promise<AgentSession<i, o>> => {\n const { sessionId, cwd } = request\n const stored = await session_store.load(sessionId).catch((err: unknown) => {\n throw internal_error(sdk, err)\n })\n if (stored === undefined) throw unknown_session(sdk, sessionId)\n if (stored.cwd !== cwd) throw other_cwd(sdk, method, sessionId, stored.cwd, cwd)\n const kept = config.additional_directories === false ? [] : stored.additional_directories\n return open_session(client, {\n id: sessionId,\n cwd,\n additional_directories: request.additional_directories.length > 0 ? request.additional_directories : kept,\n mcp_servers: request.mcp_servers ?? [],\n stored,\n })\n }\n // A session this connection already holds is picked up as it is, and a\n // stored one is opened from the store, once: a second request for it that\n // arrives meanwhile waits and picks up the session the first one opened.\n const reopen = async (\n client: AgentContext,\n method: 'session/load' | 'session/resume',\n params: {\n sessionId: string\n cwd: string\n additionalDirectories?: ReadonlyArray<string> | undefined\n mcpServers?: ReadonlyArray<McpServer> | undefined\n },\n ): Promise<AgentSession<i, o>> => {\n if (store === undefined) throw sdk.RequestError.methodNotFound(method)\n await require_login()\n const { sessionId, cwd } = params\n const additional_directories = requested_directories(sdk, config, method, params.additionalDirectories)\n for (let pending = opening.get(sessionId); pending !== undefined; pending = opening.get(sessionId)) {\n await pending.catch(() => {})\n }\n const live = sessions.get(sessionId)\n if (live === undefined) {\n const request = { sessionId, cwd, additional_directories, mcp_servers: params.mcpServers }\n const opened = restore(client, method, request, store).finally(() => opening.delete(sessionId))\n opening.set(sessionId, opened)\n return opened\n }\n if (live.session.cwd !== cwd) throw other_cwd(sdk, method, sessionId, live.session.cwd, cwd)\n if (params.mcpServers !== undefined) await switch_servers(live, params.mcpServers)\n return live\n }\n // A loaded thread is shown again from the turns the store kept, each as\n // the client saw it. A session whose turns weren't kept shows its\n // history's text, without its tool cards.\n const replay = async (client: AgentContext, record: AgentSession<i, o>): Promise<void> => {\n await record.saving\n const kept =\n record.turns !== null && record.turns > 0 && store?.load_turns !== undefined\n ? await store.load_turns(record.session.id, record.turns).catch((err: unknown) => {\n throw internal_error(sdk, err)\n })\n : undefined\n const send = sender(sdk, client, record.session.id)\n // A store that kept none of the turns it was handed still has the\n // history, so the thread shows its text instead of nothing.\n const turns = kept === undefined || kept.length === 0 ? record.history.map(replayed) : kept.flat()\n for (const update of turns) await send(update)\n }\n // A reopened thread shows its title and its usage again, which the client\n // can't keep for an agent that restarted, and the answer carries its mode\n // and its model. A host that keeps a running cost takes the usage sent\n // here as where the session stood, so its next turn isn't charged with\n // the whole total.\n const reopened = async (client: AgentContext, record: AgentSession<i, o>) => {\n await send_notices(client, record)\n const send = sender(sdk, client, record.session.id)\n if (record.title !== null && record.title !== '') await send({ sessionUpdate: 'session_info_update', title: record.title })\n const window = context_window_of(config, record.model.id)\n if (window !== undefined && (record.usage.context_tokens > 0 || record.usage.priced)) {\n await send(usage_update(record.usage, window))\n }\n return { modes: mode_state(offer, record.modes.current()), configOptions: options_of(record) }\n }\n // The flow is built again for the new model before the pick takes, so a\n // builder that throws leaves the session on the model it had. A turn in\n // flight keeps the flow it started with.\n const switch_model = async (record: AgentSession<i, o>, next: string): Promise<void> => {\n const previous = record.model.id\n record.model.id = next\n try {\n record.flow = await build_flow(record.session)\n } catch (err: unknown) {\n record.model.id = previous\n throw internal_error(sdk, err)\n }\n }\n // Closing cancels the session's turn as session/cancel does, and waits for\n // its run to settle before the MCP servers close, so no tool call is left\n // talking to one. It waits for the cancelled turn's save too, so a load\n // sent as soon as the close answers finds that turn in the store. The\n // session leaves memory, and the store keeps it.\n const close_session = async (record: AgentSession<i, o>): Promise<void> => {\n sessions.delete(record.session.id)\n cancel_turn(record)\n await record.last_turn?.settled\n await Promise.all(record.prompts)\n await record.saving\n await record.mcp.close()\n }\n return sdk\n .agent()\n .onConnect((connection) => {\n if (connected) throw new Error(ONE_CONNECTION)\n connected = true\n // The SDK aborts every request in flight as the connection closes,\n // which ends each turn, and then every session closes, so a stdio MCP\n // server doesn't outlive the editor that sent it.\n void connection.closed.then(() => Promise.all([...sessions.values()].map(close_session)))\n })\n .onRequest('initialize', (ctx) => {\n if (initialized) throw sdk.RequestError.invalidRequest(undefined, ONE_CONNECTION)\n initialized = true\n client_capabilities = ctx.params.clientCapabilities ?? {}\n return {\n protocolVersion: sdk.PROTOCOL_VERSION,\n agentInfo: identity,\n // Embedded context lets a file the user @-mentions arrive with its\n // text, rather than as a bare URI the flow has no way to read. The\n // agent advertises additional directories, which let a client widen\n // the workspace past `cwd`, unless the config sets\n // `additional_directories: false`.\n agentCapabilities: {\n loadSession: store !== undefined,\n promptCapabilities: { embeddedContext: true },\n ...(config.mcp_servers === true ? { mcpCapabilities: MCP_CAPABILITIES } : {}),\n sessionCapabilities: {\n close: {},\n ...(config.additional_directories === false ? {} : { additionalDirectories: {} }),\n ...(store === undefined ? {} : { list: {}, resume: {} }),\n ...(store?.delete === undefined ? {} : { delete: {} }),\n },\n ...(auth?.logout === undefined ? {} : { auth: { logout: {} } }),\n },\n // Without an `auth`, providers authenticate with what the launched\n // process can see, and the agent offers no method, since a client\n // can't act on a login the agent has no way to check.\n authMethods: auth_methods(auth, client_capabilities),\n }\n })\n .onRequest('authenticate', async (ctx) => {\n if (auth === undefined) return {}\n const { methodId } = ctx.params\n if (methodId !== LOGIN_METHOD) {\n throw sdk.RequestError.invalidParams({ methodId }, `unknown login method ${JSON.stringify(methodId)}; the method is ${LOGIN_METHOD}`)\n }\n await require_login()\n return {}\n })\n .onRequest('logout', async () => {\n if (auth?.logout === undefined) throw sdk.RequestError.methodNotFound('logout')\n await auth.logout().catch((err: unknown) => {\n throw internal_error(sdk, err)\n })\n return {}\n })\n .onRequest('session/new', async (ctx) => {\n await require_login()\n // `mcpServers` is ignored unless the config sets `mcp_servers`.\n const { cwd, mcpServers } = ctx.params\n const additional_directories = requested_directories(sdk, config, 'session/new', ctx.params.additionalDirectories)\n const record = await open_session(ctx.client, { id: randomUUID(), cwd, additional_directories, mcp_servers: mcpServers })\n return {\n sessionId: record.session.id,\n modes: mode_state(offer, record.modes.current()),\n configOptions: options_of(record),\n }\n })\n .onRequest('session/load', async (ctx) => {\n const record = await reopen(ctx.client, 'session/load', ctx.params)\n await replay(ctx.client, record)\n return reopened(ctx.client, record)\n })\n .onRequest('session/resume', async (ctx) => reopened(ctx.client, await reopen(ctx.client, 'session/resume', ctx.params)))\n .onRequest('session/list', async (ctx): Promise<ListSessionsResponse> => {\n if (store === undefined) throw sdk.RequestError.methodNotFound('session/list')\n const { cwd, cursor } = ctx.params\n const summaries = await store.list().catch((err: unknown) => {\n throw internal_error(sdk, err)\n })\n const page = session_page(summaries, cwd, cursor)\n if (page === undefined) {\n throw sdk.RequestError.invalidParams({ cursor }, \"that cursor isn't one this agent gave out; send session/list without a cursor to start over\")\n }\n return {\n sessions: page.sessions.map(session_info),\n ...(page.next_cursor === undefined ? {} : { nextCursor: page.next_cursor }),\n }\n })\n .onRequest('session/delete', async (ctx) => {\n if (store?.delete === undefined) throw sdk.RequestError.methodNotFound('session/delete')\n const { sessionId } = ctx.params\n const live = sessions.get(sessionId)\n if (live !== undefined) {\n // A turn that ends while the session is being deleted would save it\n // back, so the session stops saving before it closes.\n live.deleted = true\n await close_session(live)\n await live.saving\n }\n await store.delete(sessionId).catch((err: unknown) => {\n throw internal_error(sdk, err)\n })\n return {}\n })\n .onRequest('session/close', async (ctx) => {\n await close_session(session_of(ctx.params.sessionId))\n return {}\n })\n .onRequest('session/prompt', async (ctx) => {\n const { sessionId, prompt } = ctx.params\n const record = session_of(sessionId)\n // A warning about a server left out of a new session waits for the\n // first prompt, since the client didn't know the session's id while\n // the session was being made.\n await send_notices(ctx.client, record)\n const saved = Promise.withResolvers<void>()\n record.prompts.add(saved.promise)\n try {\n return await prompt_turn(config, record, prompt, ctx.signal, sender(sdk, ctx.client, sessionId))\n } catch (err: unknown) {\n throw internal_error(sdk, err)\n } finally {\n await save_session(config, record)\n record.prompts.delete(saved.promise)\n saved.resolve()\n }\n })\n .onRequest('session/set_mode', async (ctx) => {\n const { sessionId, modeId } = ctx.params\n const record = session_of(sessionId)\n await record.modes.switch_to(requested_mode(sdk, offer, record.modes, modeId, 'modeId'))\n await save_session(config, record)\n return {}\n })\n .onRequest('session/set_config_option', async (ctx) => {\n const { sessionId, configId, value } = ctx.params\n const record = session_of(sessionId)\n if (configId === MODE_CONFIG_ID) {\n await record.modes.switch_to(requested_mode(sdk, offer, record.modes, value, 'value'))\n } else if (configId === MODEL_CONFIG_ID && models !== undefined) {\n await switch_model(record, requested_model(sdk, models, value))\n } else {\n const known = models === undefined ? `the only one is ${MODE_CONFIG_ID}` : `the options are ${CONFIG_IDS}`\n throw sdk.RequestError.invalidParams({ configId }, `unknown config option ${configId}; ${known}`)\n }\n await save_session(config, record)\n return { configOptions: options_of(record) }\n })\n .onNotification('session/cancel', (ctx) => {\n const record = sessions.get(ctx.params.sessionId)\n if (record !== undefined) cancel_turn(record)\n })\n}\n","/**\n * api_key_login: a login that keeps one API key in a file only the user can\n * read.\n *\n * Every agent that runs on a provider's API key needs the same login, so\n * this is it. The key comes from an environment variable first, so a key in\n * the client's agent server entry keeps working, and then from the file. A\n * client that can run a terminal login runs the agent's own command with\n * `--login`, where `run` asks for the key without echoing it and writes the\n * file. The agent's entry point calls `run` before it serves, so\n * `serve_acp` never reads a terminal.\n *\n * The file holds the key in plain text, as `~/.aws/credentials` does, in a\n * directory made for its owner alone (mode 0700) and readable by its owner\n * alone (mode 0600). The key never reaches a log, stdout, or the protocol:\n * the prompt and every message go to the terminal's own output, and none of\n * them carries it.\n *\n * The environment and the path are accepted at construction; this module\n * never reads `process.env`.\n */\n\nimport { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'\nimport { dirname } from 'node:path'\nimport { is_record } from '#schema'\nimport type { AcpAuth } from './types.js'\n\nexport type ApiKeyLoginConfig = {\n /** What the client shows for the login, such as `'OpenRouter API key'`. */\n readonly name: string\n /** The environment variable read first, such as `'OPENROUTER_API_KEY'`. */\n readonly variable: string\n /** Where a key entered at the terminal is kept. */\n readonly file: string\n /** The environment `variable` is read from, which an entry point passes as `process.env`. */\n readonly env: Readonly<Record<string, string | undefined>>\n}\n\n/**\n * The terminal a login reads the key from. `process.stdin` and\n * `process.stderr` fit it, and stderr is the output to use, since stdout\n * belongs to whoever launched the command.\n */\nexport type LoginTerminal = {\n readonly input: {\n readonly isTTY?: boolean | undefined\n readonly setRawMode?: ((raw: boolean) => unknown) | undefined\n readonly on: (event: 'data', listener: (chunk: Buffer | string) => void) => unknown\n readonly off: (event: 'data', listener: (chunk: Buffer | string) => void) => unknown\n readonly resume?: (() => unknown) | undefined\n readonly pause?: (() => unknown) | undefined\n }\n readonly output: { readonly write: (text: string) => unknown }\n}\n\nexport type ApiKeyLogin = {\n /** The key now: the variable when it's set, and the file otherwise. */\n readonly key: () => string | undefined\n /** The login for `serve_acp`'s `auth`, with a terminal login under `--login`. */\n readonly auth: AcpAuth\n /**\n * Reads a key at the terminal without echoing it, writes the file, and\n * resolves with the process's exit code: 0 once the key is kept, and 1\n * when the input isn't a terminal or no key was entered.\n */\n readonly run: (terminal: LoginTerminal) => Promise<number>\n}\n\n/** The argument an agent's entry point runs the terminal login under. */\nconst LOGIN_ARGUMENT = '--login'\n\n/**\n * The key a credentials file holds, or undefined when the file is missing\n * or holds anything else.\n */\nfunction stored_key(file: string): string | undefined {\n try {\n const value: unknown = JSON.parse(readFileSync(file, 'utf8'))\n const key = is_record(value) ? value['api_key'] : undefined\n return typeof key === 'string' && key !== '' ? key : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * Write the key to `file`, readable by its owner alone, in a directory made\n * for its owner alone. The key goes to a temporary sibling first and is\n * renamed into place, so a crash mid-write leaves the earlier file whole.\n */\nfunction store_key(file: string, key: string): void {\n mkdirSync(dirname(file), { recursive: true, mode: 0o700 })\n const temporary = `${file}.${process.pid}.tmp`\n writeFileSync(temporary, `${JSON.stringify({ api_key: key })}\\n`, { encoding: 'utf8', mode: 0o600 })\n renameSync(temporary, file)\n}\n\n/**\n * Read one line from a terminal in raw mode, so nothing typed is echoed.\n * Resolves with the line at Enter, and with undefined at Ctrl-C or Ctrl-D.\n * Backspace removes the last character.\n */\nfunction read_secret(terminal: LoginTerminal): Promise<string | undefined> {\n const { input } = terminal\n const { promise, resolve } = Promise.withResolvers<string | undefined>()\n let typed = ''\n const on_data = (chunk: Buffer | string): void => {\n for (const character of chunk.toString()) {\n if (character === '\\r' || character === '\\n') return resolve(typed)\n if (character === '\\u0003' || character === '\\u0004') return resolve(undefined)\n if (character === '\\u007F' || character === '\\b') typed = typed.slice(0, -1)\n else typed += character\n }\n }\n input.setRawMode?.(true)\n input.on('data', on_data)\n input.resume?.()\n return promise.finally(() => {\n input.off('data', on_data)\n input.setRawMode?.(false)\n input.pause?.()\n })\n}\n\n/**\n * Build a login that keeps one API key: `key` reads it, `auth` goes to\n * `serve_acp`, and `run` is the terminal login the agent's entry point runs\n * under `--login`.\n */\nexport function api_key_login(config: ApiKeyLoginConfig): ApiKeyLogin {\n const { name, variable, file, env } = config\n const key = (): string | undefined => {\n const from_env = env[variable]\n return from_env !== undefined && from_env !== '' ? from_env : stored_key(file)\n }\n return {\n key,\n auth: {\n name,\n description: `Reads ${variable}, or a key kept in ${file}`,\n ready: () => key() !== undefined,\n instructions: `set ${variable} in the agent server's env, or run the agent with ${LOGIN_ARGUMENT} in a terminal to enter a key`,\n terminal_args: [LOGIN_ARGUMENT],\n logout: async () => {\n rmSync(file, { force: true })\n },\n },\n run: async (terminal) => {\n const say = (text: string): void => {\n terminal.output.write(text)\n }\n if (terminal.input.isTTY !== true) {\n say(`${name}: this login needs a terminal to read the key from; run it in one, or set ${variable} instead\\n`)\n return 1\n }\n say(`${name} (what you type isn't shown): `)\n const entered = (await read_secret(terminal))?.trim()\n say('\\n')\n if (entered === undefined || entered === '') {\n say(`${name}: no key was entered, so nothing was saved; run the login again to enter one\\n`)\n return 1\n }\n store_key(file, entered)\n say(`${name}: saved to ${file}\\n`)\n return 0\n },\n }\n}\n","/**\n * session_store: a filesystem store for ACP sessions, one JSON file each.\n *\n * A session is saved as `<id>.json` under the root directory. A save writes a\n * temporary sibling first and renames it into place, so a crash mid-write\n * leaves the earlier copy whole. A session holds the whole conversation,\n * which can carry code or a key the user pasted, so the directory the store\n * makes is readable by its owner alone, and so is every file it writes. A session id comes from the client on\n * `session/load` and `session/resume`, so only an id made of letters, digits,\n * `-`, and `_` names a file, and any other id reads as a session the store\n * doesn't hold rather than as a path. A file that isn't a stored session\n * fails its load with a message naming it, and `list` skips it with a\n * warning on stderr, so one bad file can't hide every other thread.\n *\n * Each turn as the client saw it goes in a file of its own,\n * `<id>.turns/<n>.json`, so a long session costs one small write for each\n * turn instead of a rewrite of everything it has shown. Deleting a session\n * removes its file and that directory.\n *\n * Paths are accepted at construction; the store never reads `process.env`.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport { mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport type { SessionUpdate } from '@agentclientprotocol/sdk'\nimport { is_acp_mode } from './modes.js'\nimport { error_code } from './tools/containment.js'\nimport type { AcpFullSessionStore, AcpHistoryEntry, AcpSessionSummary, AcpSessionUsage, AcpStoredSession } from './types.js'\n\nexport type FilesystemSessionStoreConfig = {\n /** The directory the session files go in, made on the first save. */\n readonly root_dir: string\n}\n\n/** The ids that can name a file, which every id the agent makes matches. */\nconst SAFE_ID = /^[\\w-]+$/\n\n/**\n * Whether `value` is a plain object, read as a record of unknown fields.\n */\nfunction is_record(value: unknown): value is Readonly<Record<string, unknown>> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/**\n * Whether `value` is a list of strings.\n */\nfunction is_strings(value: unknown): value is ReadonlyArray<string> {\n return Array.isArray(value) && value.every((entry) => typeof entry === 'string')\n}\n\n/**\n * Whether `value` is one history entry, with a role, its text, and, on the\n * entry where a cancelled turn stopped, the mark that says so.\n */\nfunction is_history_entry(value: unknown): value is AcpHistoryEntry {\n if (!is_record(value)) return false\n const { role, text, cancelled } = value\n return (role === 'user' || role === 'agent') && typeof text === 'string' && (cancelled === undefined || cancelled === true)\n}\n\n/**\n * Whether `value` is a session's usage.\n */\nfunction is_usage(value: unknown): value is AcpSessionUsage {\n if (!is_record(value)) return false\n const { context_tokens, cost_usd, priced } = value\n return typeof context_tokens === 'number' && typeof cost_usd === 'number' && typeof priced === 'boolean'\n}\n\n/**\n * Whether `value` is a stored session, checked field by field, since the\n * file is anything a person or another program left there.\n */\nexport function is_stored_session(value: unknown): value is AcpStoredSession {\n if (!is_record(value)) return false\n const { id, cwd, additional_directories, mode, model, title, updated_at, history, usage, turns } = value\n return (\n typeof id === 'string' &&\n typeof cwd === 'string' &&\n is_strings(additional_directories) &&\n is_acp_mode(mode) &&\n (model === undefined || typeof model === 'string') &&\n (title === null || typeof title === 'string') &&\n typeof updated_at === 'string' &&\n Array.isArray(history) &&\n history.every(is_history_entry) &&\n is_usage(usage) &&\n (turns === undefined || typeof turns === 'number')\n )\n}\n\n/**\n * Whether `value` is one turn as a store keeps it: a list of session\n * updates, each checked only for the field that names its kind, since the\n * client checks the rest as it takes them.\n */\nexport function is_stored_turn(value: unknown): value is SessionUpdate[] {\n return Array.isArray(value) && value.every((update) => is_record(update) && typeof update['sessionUpdate'] === 'string')\n}\n\n/**\n * What `session/list` reports of a stored session.\n */\nexport function summary_of(session: AcpStoredSession): AcpSessionSummary {\n const { id, cwd, additional_directories, title, updated_at } = session\n return { id, cwd, additional_directories, title, updated_at }\n}\n\n/**\n * Write `value` as JSON to `path` through a temporary sibling and a rename,\n * readable by its owner alone.\n */\nasync function write_private(path: string, value: unknown): Promise<void> {\n const temporary = `${path}.${randomUUID()}.tmp`\n await writeFile(temporary, JSON.stringify(value), { encoding: 'utf8', mode: 0o600 })\n await rename(temporary, path)\n}\n\n/**\n * Read one stored turn, or undefined when its file is missing or holds\n * anything else, so a load replays the turns that can be read.\n */\nasync function read_turn(path: string): Promise<SessionUpdate[] | undefined> {\n try {\n const value: unknown = JSON.parse(await readFile(path, 'utf8'))\n return is_stored_turn(value) ? value : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * Read the session file at `path`, or undefined when there is none. Throws\n * an `Error` naming the file when it holds anything but a stored session.\n */\nasync function read_session(path: string): Promise<AcpStoredSession | undefined> {\n let text: string\n try {\n text = await readFile(path, 'utf8')\n } catch (err: unknown) {\n if (error_code(err) === 'ENOENT') return undefined\n throw err\n }\n let value: unknown\n try {\n value = JSON.parse(text)\n } catch {\n value = undefined\n }\n if (is_stored_session(value)) return value\n throw new Error(`${path} isn't a stored ACP session; fix or delete the file to load the others`)\n}\n\n/**\n * `id` when it can name a file, and otherwise an error that says which ids\n * can.\n */\nfunction checked(id: string): string {\n if (SAFE_ID.test(id)) return id\n throw new Error(`can't save session ${JSON.stringify(id)}: an id names a file, so use letters, digits, - and _`)\n}\n\n/**\n * Build a session store that keeps one JSON file for each session under\n * `root_dir`.\n */\nexport function filesystem_session_store(config: FilesystemSessionStoreConfig): AcpFullSessionStore {\n const path_of = (id: string): string => join(config.root_dir, `${id}.json`)\n const turns_dir = (id: string): string => join(config.root_dir, `${id}.turns`)\n const turn_path = (id: string, index: number): string => join(turns_dir(id), `${index}.json`)\n return {\n save: async (session) => {\n const id = checked(session.id)\n await mkdir(config.root_dir, { recursive: true, mode: 0o700 })\n await write_private(path_of(id), session)\n },\n load: async (id) => (SAFE_ID.test(id) ? read_session(path_of(id)) : undefined),\n delete: async (id) => {\n if (!SAFE_ID.test(id)) return\n await rm(path_of(id), { force: true })\n await rm(turns_dir(id), { recursive: true, force: true })\n },\n save_turn: async (id, index, updates) => {\n await mkdir(turns_dir(checked(id)), { recursive: true, mode: 0o700 })\n await write_private(turn_path(id, index), updates)\n },\n load_turns: async (id, count) => {\n if (!SAFE_ID.test(id)) return []\n const turns = await Promise.all(Array.from({ length: count }, (_, index) => read_turn(turn_path(id, index))))\n return turns.filter((turn) => turn !== undefined)\n },\n list: async () => {\n let names: string[]\n try {\n names = await readdir(config.root_dir)\n } catch (err: unknown) {\n if (error_code(err) === 'ENOENT') return []\n throw err\n }\n const files = names.filter((name) => name.endsWith('.json') && !name.startsWith('.'))\n const sessions = await Promise.all(\n files.map((name) =>\n read_session(join(config.root_dir, name)).catch((err: unknown) => {\n process.stderr.write(`fascicle/acp: ${err instanceof Error ? err.message : String(err)}\\n`)\n return undefined\n }),\n ),\n )\n return sessions.filter((session) => session !== undefined).map(summary_of)\n },\n }\n}\n","/**\n * checkpoint_session_store: ACP sessions kept in any `CheckpointStore`.\n *\n * An app that already has a checkpoint store for its durable runs, or one\n * of its own that passes the store conformance suite, keeps its sessions\n * there too, under three kinds of key. `acp/session/<id>` holds the session,\n * `acp/session/<id>/turn/<n>` holds turn `n` as the client saw it, and\n * `acp/sessions` holds the index that `session/list` reads, since a\n * `CheckpointStore` can't list its keys.\n *\n * Updating the index is a read, a change, and a write. On a store with\n * `get_versioned` and `set_if`, the write goes through only while the index\n * is still as it was read, and a writer that lost reads it again, so two\n * agent processes sharing a store never drop each other's entries. A store\n * without them is safe for one agent process at a time, which makes its\n * updates one after another, so two of its sessions that save together\n * both land in the index.\n *\n * A stored session holds the conversation, which can carry code or a key\n * the user pasted, so who can read it is up to the store underneath.\n */\n\nimport type { CheckpointStore } from '#core'\nimport { is_record } from '#schema'\nimport { is_stored_session, is_stored_turn, summary_of } from './session_store.js'\nimport type { AcpFullSessionStore, AcpSessionSummary } from './types.js'\n\n/** The key of the index that `session/list` reads. */\nconst INDEX_KEY = 'acp/sessions'\n\n/** How many times an index update reads again after losing its write to another writer. */\nconst INDEX_ATTEMPTS = 50\n\n/**\n * The latest index update on each store that can't compare and set, which\n * the next one waits on, so two updates in one process never read the same\n * index and write over each other. It's keyed by the store, since two\n * session stores can share one.\n */\nconst index_updates = new WeakMap<CheckpointStore, Promise<void>>()\n\n/**\n * The key a session is kept under.\n */\nfunction session_key(id: string): string {\n return `acp/session/${id}`\n}\n\n/**\n * The key one turn of a session is kept under.\n */\nfunction turn_key(id: string, index: number): string {\n return `${session_key(id)}/turn/${index}`\n}\n\n/**\n * Whether `value` is one entry of the index.\n */\nfunction is_summary(value: unknown): value is AcpSessionSummary {\n if (!is_record(value)) return false\n const { id, cwd, additional_directories, title, updated_at } = value\n return (\n typeof id === 'string' &&\n typeof cwd === 'string' &&\n Array.isArray(additional_directories) &&\n additional_directories.every((entry) => typeof entry === 'string') &&\n (title === null || typeof title === 'string') &&\n typeof updated_at === 'string'\n )\n}\n\n/**\n * The index a store holds, read from whatever is under its key. Anything\n * that isn't an entry is left out, so one bad entry can't hide the rest.\n */\nfunction index_of(value: unknown): AcpSessionSummary[] {\n return Array.isArray(value) ? value.filter(is_summary) : []\n}\n\n/**\n * Replace the index with `change` applied to it. On a store that can\n * compare and set, a write that lost to another writer reads the index\n * again and applies the change to what it finds. On any other store, the\n * update waits for every one this process already started there, whether\n * or not that one failed, since nothing else keeps two of them apart.\n */\nasync function update_index(\n store: CheckpointStore,\n change: (index: AcpSessionSummary[]) => AcpSessionSummary[],\n): Promise<void> {\n const { get_versioned, set_if } = store\n if (get_versioned === undefined || set_if === undefined) {\n const update = (index_updates.get(store) ?? Promise.resolve()).then(async () =>\n store.set(INDEX_KEY, change(index_of(await store.get(INDEX_KEY)))),\n )\n index_updates.set(\n store,\n update.catch(() => {}),\n )\n return update\n }\n for (let attempt = 0; attempt < INDEX_ATTEMPTS; attempt += 1) {\n const read = await get_versioned(INDEX_KEY)\n if (await set_if(INDEX_KEY, change(index_of(read?.value)), read?.version ?? null)) return\n }\n throw new Error(\n `couldn't update the session index at ${INDEX_KEY}: ${INDEX_ATTEMPTS} writes in a row lost to another writer; save the session again`,\n )\n}\n\n/**\n * Build a session store that keeps its sessions in `store`, with their\n * turns, and can delete them.\n */\nexport function checkpoint_session_store(store: CheckpointStore): AcpFullSessionStore {\n return {\n save: async (session) => {\n await store.set(session_key(session.id), session)\n const summary = summary_of(session)\n await update_index(store, (index) => [summary, ...index.filter((entry) => entry.id !== session.id)])\n },\n load: async (id) => {\n const value = await store.get(session_key(id))\n if (value === undefined || value === null) return undefined\n if (is_stored_session(value)) return value\n throw new Error(`the value at ${session_key(id)} isn't a stored ACP session; delete the session to list the others`)\n },\n list: async () => index_of(await store.get(INDEX_KEY)),\n delete: async (id) => {\n const value = await store.get(session_key(id))\n const turns = is_stored_session(value) ? (value.turns ?? 0) : 0\n await Promise.all(Array.from({ length: turns }, (_, index) => store.delete(turn_key(id, index))))\n await store.delete(session_key(id))\n await update_index(store, (index) => index.filter((entry) => entry.id !== id))\n },\n save_turn: (id, index, updates) => store.set(turn_key(id, index), updates),\n load_turns: async (id, count) => {\n const turns = await Promise.all(Array.from({ length: count }, (_, index) => store.get(turn_key(id, index))))\n return turns.filter(is_stored_turn)\n },\n }\n}\n","/**\n * The ACP agent's serving loop, minus the process.\n *\n * `serve_streams` is everything `serve_acp` does once the console and the\n * signals are handled: connect `acp_agent` to a pair of ndjson byte streams,\n * hold the connection until the client hangs up or `shutdown` fires, then\n * dispose the engine. It takes its streams as arguments, mirroring\n * `execute_stdio` under `run_stdio`, so the disconnect path is unit-tested\n * here and the thin glue in `serve_acp.ts` owns the real stdin and stdout.\n *\n * Closing the connection is what aborts the runs: the SDK aborts every\n * in-flight request's signal as it closes, and each prompt turn's run\n * listens on its request's signal. So by the time `closed` resolves, every\n * active run has seen its abort, and only then is the engine disposed.\n */\n\nimport { acp_agent } from './acp_agent.js'\nimport { load_acp_sdk } from './sdk_loader.js'\nimport type { ServeAcpConfig } from './types.js'\n\ntype AcpServeIo = {\n /** What the client sends, as ndjson bytes; stdin under `serve_acp`. */\n readonly input: ReadableStream<Uint8Array>\n /** Where the protocol goes, as ndjson bytes; stdout under `serve_acp`. */\n readonly output: WritableStream<Uint8Array>\n /** Ends the connection from the agent's side, aborting every active run with its reason. */\n readonly shutdown?: AbortSignal | undefined\n}\n\n/**\n * Serve the config's flow as an ACP agent over `io` until the client\n * disconnects or `io.shutdown` fires, then dispose the engine once every\n * active run has been aborted.\n */\nexport async function serve_streams<i, o>(config: ServeAcpConfig<i, o>, io: AcpServeIo): Promise<void> {\n const sdk = await load_acp_sdk()\n const app = await acp_agent(config)\n const connection = app.connect(sdk.ndJsonStream(io.output, io.input))\n const { shutdown } = io\n if (shutdown !== undefined) {\n // A signal can land while the SDK loads, before there is a listener to hear it.\n if (shutdown.aborted) connection.close(shutdown.reason)\n else shutdown.addEventListener('abort', () => connection.close(shutdown.reason))\n }\n await connection.closed\n await config.engine?.dispose()\n}\n","/**\n * Process glue for serving a flow as an ACP agent over stdio.\n *\n * Binds `serve_streams` to the real process: ndjson in on stdin, the\n * protocol out on stdout, and nothing else on stdout ever. A stray log line\n * from a flow or a dependency would corrupt the protocol stream, so\n * `console.log`, `console.info`, `console.debug`, `console.dir`, and\n * `console.dirxml` go to stderr for the life of the process.\n *\n * SIGTERM and SIGINT abort every active run, dispose the engine, and exit.\n * A host that ends the agent with a signal instead of closing stdin would\n * otherwise leave a run's work going after the editor has closed, since each\n * turn runs with the runner's own signal handlers off. The handlers are\n * one-shot, so a second Ctrl-C falls through to Node's default and kills the\n * process outright when a shutdown hangs.\n *\n * Excluded from mutation testing as process glue (see stryker.config.mjs);\n * the spawn tests in `__tests__/e2e/` exercise it for real.\n */\n\nimport { constants } from 'node:os'\nimport { Readable, Writable } from 'node:stream'\nimport { aborted_error } from '#core'\nimport { route_console_to_stderr } from '#process'\nimport { serve_streams } from './serve_streams.js'\nimport type { ServeAcpConfig } from './types.js'\n\n/**\n * Serve a flow as an ACP agent over stdin and stdout until the client\n * disconnects, disposing the engine once every active run has been aborted.\n * A SIGTERM or SIGINT does the same, then exits with the signal's code.\n */\nexport async function serve_acp<i, o>(config: ServeAcpConfig<i, o>): Promise<void> {\n // Leave stdout to the protocol alone.\n route_console_to_stderr(console, process.stderr)\n const shutdown = new AbortController()\n let received: NodeJS.Signals | null = null\n const on_signal = (signal: NodeJS.Signals): void => {\n received = signal\n shutdown.abort(new aborted_error(`received ${signal}`, { reason: { signal } }))\n }\n process.once('SIGTERM', on_signal)\n process.once('SIGINT', on_signal)\n try {\n await serve_streams(config, {\n input: Readable.toWeb(process.stdin),\n output: Writable.toWeb(process.stdout),\n shutdown: shutdown.signal,\n })\n } finally {\n process.off('SIGTERM', on_signal)\n process.off('SIGINT', on_signal)\n }\n // Exiting here rather than draining tells the host a signal ended the\n // agent, and leaves no wait on a flow that ignored its abort.\n if (received !== null) process.exit(128 + constants.signals[received])\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAsBA,MAAa,iBAAiB;;AAY9B,MAAM,QAA8C;CAClD,QAAQ;EACN,MAAM;EACN,aAAa;EACb,MAAM;GAAE,MAAM;GAAM,SAAS;EAAK;CACpC;CACA,cAAc;EACZ,MAAM;EACN,aAAa;EACb,MAAM;GAAE,MAAM;GAAO,SAAS;EAAK;CACrC;CACA,MAAM;EACJ,MAAM;EACN,aAAa;EACb,MAAM;GAAE,MAAM;GAAO,SAAS;EAAM;CACtC;AACF;;;;;AAMA,SAAgB,YAAY,IAA4B;CACtD,OAAO,OAAO,OAAO,YAAY,OAAO,OAAO,OAAO,EAAE;AAC1D;;AAaA,MAAM,aAAa,OAAO,KAAK,KAAK,CAAC,CAAC,KAAK,IAAI;;;;;;;;AAS/C,SAAgB,WAAW,QAGb;CAEZ,MAAM,SAAiC,OAAO,SAAS,OAAO,KAAK,KAAK;CACxE,IAAI,OAAO,WAAW,GACpB,MAAM,IAAI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