fascicle 0.13.1 → 0.15.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 (45) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +20 -1
  3. package/dist/acp.d.ts +233 -0
  4. package/dist/acp.js +1919 -0
  5. package/dist/acp.js.map +1 -0
  6. package/dist/adapters.js +1 -2
  7. package/dist/agents.d.ts +1 -1
  8. package/dist/agents.js +1 -1
  9. package/dist/{core-DK7g1Z40.js → core-CDrz0NM1.js} +1 -12
  10. package/dist/core-CDrz0NM1.js.map +1 -0
  11. package/dist/diagram_bin.js +1 -1
  12. package/dist/{engine-BOGuc0X2.js → engine-ha9xmgwE.js} +528 -783
  13. package/dist/engine-ha9xmgwE.js.map +1 -0
  14. package/dist/index.d.ts +468 -622
  15. package/dist/index.js +20 -12
  16. package/dist/index.js.map +1 -1
  17. package/dist/{invoke-Beef3R3X.js → invoke-px31fffH.js} +97 -26
  18. package/dist/invoke-px31fffH.js.map +1 -0
  19. package/dist/json_schema_to_standard-BTWD0J6p.js +270 -0
  20. package/dist/json_schema_to_standard-BTWD0J6p.js.map +1 -0
  21. package/dist/leading_system-DfJLqpGi.js +584 -0
  22. package/dist/leading_system-DfJLqpGi.js.map +1 -0
  23. package/dist/mcp.d.ts +20 -19
  24. package/dist/mcp.js +5 -268
  25. package/dist/mcp.js.map +1 -1
  26. package/dist/records-1HU7mWXf.js +22 -0
  27. package/dist/records-1HU7mWXf.js.map +1 -0
  28. package/dist/search-CA_OqFeW.js +579 -0
  29. package/dist/search-CA_OqFeW.js.map +1 -0
  30. package/dist/search_worker.d.ts +1 -0
  31. package/dist/search_worker.js +19 -0
  32. package/dist/search_worker.js.map +1 -0
  33. package/dist/stdio.js +1 -1
  34. package/dist/testing.d.ts +1 -1
  35. package/dist/testing.js +3 -2
  36. package/dist/testing.js.map +1 -1
  37. package/dist/{types-CZ83Q5nm.d.ts → types-De-TVQxS.d.ts} +49 -4
  38. package/dist/viewer-app/assets/index-Fnh5HKSU.js +2 -0
  39. package/dist/viewer-app/index.html +1 -1
  40. package/dist/viewer.js +1 -1
  41. package/package.json +30 -19
  42. package/dist/core-DK7g1Z40.js.map +0 -1
  43. package/dist/engine-BOGuc0X2.js.map +0 -1
  44. package/dist/invoke-Beef3R3X.js.map +0 -1
  45. package/dist/viewer-app/assets/index-DXsB0byD.js +0 -2
@@ -0,0 +1 @@
1
+ {"version":3,"file":"acp.js","names":["message_of"],"sources":["../src/acp/modes.ts","../src/acp/tools/previews.ts","../src/acp/presentation.ts","../src/acp/tools/write_file.ts","../src/acp/tools/edit_file.ts","../src/acp/approve.ts","../src/acp/to_session_updates.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/tools/run_command.ts","../src/acp/workspace_tools.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.\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 every change sends both updates, so the two\n * can't disagree in front of the user.\n */\n\nimport type { SessionConfigOption, SessionMode, SessionModeState, SessionUpdate } from '@agentclientprotocol/sdk'\nimport type { AcpMode } from './types.js'\n\n/** The mode a session starts in unless `ServeAcpConfig.default_mode` says otherwise. */\nexport const DEFAULT_MODE: AcpMode = 'manual'\n\n/** The id of the config option that carries the mode, the only option this agent has. */\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 refusal for a mode id the agent doesn't know, naming the ones it does.\n */\nexport function unknown_mode_message(id: unknown): string {\n return `unknown mode ${JSON.stringify(id)}; choose one of ${Object.keys(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/**\n * Every mode as ACP lists one: its id, its name, and what it asks.\n */\nfunction available_modes(): SessionMode[] {\n return Object.entries(MODES).map(([id, { name, description }]) => ({ id, name, description }))\n}\n\n/**\n * The session's modes as `session/new` reports them in `modes`.\n */\nexport function mode_state(mode: AcpMode): SessionModeState {\n return { currentModeId: mode, availableModes: available_modes() }\n}\n\n/**\n * The session's config options, the mode as a select being the only one, as\n * `session/new` and `session/set_config_option` report them.\n */\nexport function config_options(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: Object.entries(MODES).map(([value, { name, description }]) => ({ value, name, description })),\n },\n ]\n}\n\n/**\n * A session's mode as the agent holds it: what it is now, and the one way\n * to change it, which tells the client both ways it may be reading it.\n */\nexport type SessionModes = {\n readonly current: () => AcpMode\n readonly switch_to: (mode: AcpMode) => Promise<void>\n}\n\n/**\n * Hold a session's mode, starting at `initial`. A switch takes effect before\n * the client hears of it, so a tool call that asks after the switch reads\n * the new mode, and the two updates go out in order through `send`.\n */\nexport function session_modes(initial: AcpMode, send: (update: SessionUpdate) => Promise<void>): SessionModes {\n let mode = initial\n return {\n current: () => mode,\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(next) })\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 * 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 it does no I/O: the file reads behind a diff happen in\n * the tools, which leave each call's preview in the session's store for its\n * 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'\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 * 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 const presenter = PRESENTERS.get(name)\n if (session === undefined || 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 const presenter = PRESENTERS.get(name)\n if (session === undefined || 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 const shows = PRESENTERS.get(name)?.shows\n if (session === undefined || 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 * 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, 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/**\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: FileChange & { readonly line?: number },\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, the text it would replace, and\n * the content that replaces 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(session, request.path)\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, 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 when\n * `old_text` isn't there, or is there more than once and the call doesn't set\n * `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(session, request.path)\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 * 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. For a command, it covers the program and its\n * first argument that isn't a flag (`pnpm test`). A command with shell\n * control syntax is never covered and never offered one, since anything\n * can follow a `;` or a `|`.\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 { GatedAction, SessionModes } from './modes.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 { FileChange } from './tools/write_file.js'\nimport type { AcpSession } from './types.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/** A file change the request shows, with the line an edit lands on. */\ntype Change = FileChange & { readonly line?: number }\n\n/**\n * What a workspace tool that asks does, and for a write or an edit, how\n * to work out its change without making it.\n */\ntype Gate = {\n readonly action: GatedAction\n readonly change?: (session: AcpSession, input: unknown) => Promise<Change>\n}\n\nconst GATES: ReadonlyMap<string, Gate> = new Map<string, Gate>([\n ['write_file', { action: 'edit', change: write_file_change }],\n ['edit_file', { action: 'edit', change: edit_file_change }],\n ['run_command', { action: 'command' }],\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: its program and its first\n * argument that isn't a flag (`git status`, `pnpm test`; `ls -la` is\n * `ls`). A command with shell control syntax has none, so no grant ever\n * covers it, and neither does one that isn't a string or names no program.\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 [program, ...args] = command.trim().split(/\\s+/)\n if (program === '') return undefined\n const subject = args.find((arg) => !arg.startsWith('-'))\n return subject === undefined ? program : [program, subject].join(' ')\n}\n\n/**\n * The message a failure carries, whatever was thrown.\n */\nfunction 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 */\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 fields: ToolCallUpdate = {\n toolCallId: card,\n title: name,\n kind: opening_fields(session, name, card).kind ?? 'other',\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, and a grant of\n * its key for a command that has one. Any other call gets none. Choosing\n * Accept edits leaves a session that has moved past Manual since the call\n * asked where it is.\n */\nfunction always_for(\n gate: Gate | undefined,\n key: string | undefined,\n modes: SessionModes,\n granted: Set<string>,\n): Always | undefined {\n if (gate?.action === 'edit') {\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 (key === undefined) return undefined\n return {\n name: `Always allow \\`${key}\\` this session`,\n grant: async () => {\n granted.add(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 = GATES.get(request.tool_name)\n const key = gate?.action === 'command' ? command_key(request.input) : undefined\n // Stryker disable next-line ConditionalExpression: only keys are ever granted, so has() answers false for a missing key either way; the check narrows the type.\n if (key !== undefined && granted.has(key)) return true\n const always = always_for(gate, key, 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 * 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 */\nfunction 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 * 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 { CardSync } from './approve.js'\nimport { create_acp_mapper_state, to_session_updates } from './to_session_updates.js'\nimport { reset_previews } from './tools/previews.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, and the\n * sync that lets its approvals wait for the client to catch up.\n */\nexport type SessionRecord<i, o> = {\n readonly session: AcpSession\n readonly flow: Step<i, o>\n readonly history: AcpHistoryEntry[]\n readonly cards: CardSync\n last_turn: TurnHandle | 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/**\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 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. Once the turn is cancelled\n * nothing more is sent, and leaving the loop closes the run's event stream.\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<void> {\n const state = create_acp_mapper_state({ stream: config.stream, session: record.session })\n const to_updates = config.to_updates ?? to_session_updates\n for await (const event of events) {\n if (event.kind === 'events_dropped') warn_dropped(event)\n const updates = to_updates(event, state)\n for (const update of updates) {\n if (cancelled.aborted) return\n await send(update)\n }\n record.cards.sent(event, updates)\n }\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.\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 try {\n 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 record_exchange(record.history, turn.text, reply.text, cancelled.aborted)\n return { stopReason: cancelled.aborted ? 'cancelled' : 'end_turn' }\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 and stays out of this build. 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\nimport { randomUUID } from 'node:crypto'\nimport type { AgentApp, AgentContext, ClientCapabilities, SessionUpdate } from '@agentclientprotocol/sdk'\nimport { create_card_sync, session_approver } from './approve.js'\nimport type { PermissionAsker } from './approve.js'\nimport {\n config_options,\n DEFAULT_MODE,\n is_acp_mode,\n MODE_CONFIG_ID,\n mode_state,\n session_modes,\n unknown_mode_message,\n} from './modes.js'\nimport type { 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 { AcpMode, AcpSession, ServeAcpConfig } from './types.js'\n\ntype AcpSdk = Awaited<ReturnType<typeof load_acp_sdk>>\n\n/** A session as the agent holds it: what a turn needs, and its mode. */\ntype AgentSession<i, o> = SessionRecord<i, o> & { readonly modes: SessionModes }\n\n/**\n * The message a failure carries, whatever was thrown.\n */\nfunction message_of(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\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 mode a client asked for, or an invalid-params error naming the modes\n * there are. `field` is the param the id arrived in, for the error's data.\n */\nfunction requested_mode(sdk: AcpSdk, id: unknown, field: 'modeId' | 'value'): AcpMode {\n if (is_acp_mode(id)) return id\n throw sdk.RequestError.invalidParams({ [field]: id }, unknown_mode_message(id))\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 */\nexport async function acp_agent<i, o>(config: ServeAcpConfig<i, o>): Promise<AgentApp> {\n const sdk = await load_acp_sdk()\n const sessions = new Map<string, AgentSession<i, o>>()\n let client_capabilities: ClientCapabilities = {}\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 return sdk\n .agent()\n .onRequest('initialize', (ctx) => {\n client_capabilities = ctx.params.clientCapabilities ?? {}\n return {\n protocolVersion: sdk.PROTOCOL_VERSION,\n agentInfo: { name: config.name, version: config.version ?? '0.0.0' },\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.\n // Additional directories let a client widen the workspace past `cwd`.\n agentCapabilities: {\n loadSession: false,\n promptCapabilities: { embeddedContext: true },\n sessionCapabilities: { additionalDirectories: {} },\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 accepted and ignored until a flow can be handed them.\n const { cwd, additionalDirectories: additional_directories = [] } = ctx.params\n // The roots resolve once, here, so every containment check compares\n // against the same real paths for the life of the session.\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 id = randomUUID()\n const modes = session_modes(config.default_mode ?? DEFAULT_MODE, sender(sdk, ctx.client, id))\n const cards = create_card_sync()\n const approver = session_approver({ modes, cards, ask: permission_asker(sdk, ctx.client) })\n const session: AcpSession = {\n id,\n cwd,\n additional_directories,\n roots,\n client_capabilities,\n mode: modes.current,\n approve: (request) => approver(session, request),\n }\n try {\n const flow = typeof config.flow === 'function' ? config.flow(session) : config.flow\n sessions.set(id, { session, flow, history: [], cards, last_turn: null, modes })\n } catch (err: unknown) {\n throw internal_error(sdk, err)\n }\n return { sessionId: id, modes: mode_state(modes.current()), configOptions: config_options(modes.current()) }\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 }\n })\n .onRequest('session/set_mode', async (ctx) => {\n const { sessionId, modeId } = ctx.params\n const { modes } = session_of(sessionId)\n await modes.switch_to(requested_mode(sdk, modeId, 'modeId'))\n return {}\n })\n .onRequest('session/set_config_option', async (ctx) => {\n const { sessionId, configId, value } = ctx.params\n const { modes } = session_of(sessionId)\n if (configId !== MODE_CONFIG_ID) {\n throw sdk.RequestError.invalidParams(\n { configId },\n `unknown config option ${configId}; the only one is ${MODE_CONFIG_ID}`,\n )\n }\n await modes.switch_to(requested_mode(sdk, value, 'value'))\n return { configOptions: config_options(modes.current()) }\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`, and `console.debug` go to stderr for the life\n * 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 { serve_streams } from './serve_streams.js'\nimport type { ServeAcpConfig } from './types.js'\n\n/**\n * Route the console's stdout methods to stderr, leaving stdout to the\n * protocol alone.\n */\nfunction route_console_to_stderr(): void {\n // oxlint-disable-next-line no-console\n Object.assign(console, { log: console.error, info: console.error, debug: console.error })\n}\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 route_console_to_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 * 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 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 child.once('exit', () => {\n clearTimeout(timer)\n kill_group(child)\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 child.stdout.destroy()\n child.stderr.destroy()\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 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\nimport type { Tool } from '#engine'\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 * `tool`, asking for approval before each call when the session's mode asks\n * before `action`. 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 { ...tool, needs_approval: () => asks_before(session.mode(), action) }\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.\n */\nexport function workspace_tools(session: AcpSession, options: WorkspaceToolsOptions = {}): ReadonlyArray<Tool> {\n const ignore = options.ignore ?? IGNORE\n return [\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}\n"],"mappings":";;;;;;;;;;;;;AAuBA,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,IAA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S,QAAQ,QAAQ,qBAAqB,iBAAiB;EAC3E,MAAM,gBAAgB,OAAO,GAAG,SAAS,MAAM;EAC/C,MAAM,eAAe,OAAO,GAAG,SAAS,MAAM;EAC9C,MACE,iBAAiB,SAAS;GACxB,YAAY,QAAQ,sBAAsB;GAC1C,oBAAoB,QAAQ,sBAAsB;GAClD,KAAK,QAAQ;EACf,CAAC,GACD,SACA,SACF;CACF;AACF"}
package/dist/adapters.js CHANGED
@@ -1,2 +1 @@
1
- import { a as http_logger, i as noop_logger, n as tee_logger, o as filesystem_logger, r as stderr_logger, t as filesystem_store } from "./adapters-DNnzeLxr.js";
2
- export { filesystem_logger, filesystem_store, http_logger, noop_logger, stderr_logger, tee_logger };
1
+ export { o as filesystem_logger, t as filesystem_store, a as http_logger, i as noop_logger, r as stderr_logger, n as tee_logger } from "./adapters-DNnzeLxr.js";
package/dist/agents.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { c as Step } from "./types-CPqLZOEr.js";
2
2
  import { r as ToolSchema } from "./types-BK0UW28o.js";
3
- import { a as Engine, i as EffortLevel } from "./types-CZ83Q5nm.js";
3
+ import { a as Engine, i as EffortLevel } from "./types-De-TVQxS.js";
4
4
  //#region src/agents/define_agent.d.ts
5
5
  type AgentBuiltPrompt = string | {
6
6
  readonly user: string;
package/dist/agents.js CHANGED
@@ -1,4 +1,4 @@
1
- import { S as assert_valid_step_id, k as aborted_error, x as step } from "./core-DK7g1Z40.js";
1
+ import { S as assert_valid_step_id, k as aborted_error, x as step } from "./core-CDrz0NM1.js";
2
2
  import { readFileSync } from "node:fs";
3
3
  import { fileURLToPath } from "node:url";
4
4
  //#region src/agents/define_agent.ts
@@ -3518,17 +3518,6 @@ function chain(input_name) {
3518
3518
  }
3519
3519
  register_traced_kind("chain");
3520
3520
  //#endregion
3521
- //#region src/core/index.ts
3522
- /**
3523
- * Public surface for core.
3524
- *
3525
- * Side-effect imports ensure every composer registers itself with the runner
3526
- * at module load. Importing anything from `core` populates the
3527
- * dispatch table with the core primitives. Built-in composites
3528
- * (adversarial, ensemble, tournament, consensus) live in composites
3529
- * and surface through the umbrella package.
3530
- */
3531
- //#endregion
3532
3521
  export { describe_cycle_error as A, is_valid_step_id as C, describe as D, run as E, suspended_error as F, timeout_error as I, STEP_KINDS as L, flow_changed_error as M, resume_validation_error as N, is_step as O, run_not_found_error as P, is_step_kind as R, assert_valid_step_id as S, durable as T, map as _, suspend as a, sequence as b, checkpoint as c, timeout as d, fallback as f, pipe as g, wait_with_abort as h, use as i, error_path as j, aborted_error as k, compose as l, compute_backoff as m, scope as n, format_schema_issues as o, retry as p, stash as r, validate_schema as s, chain as t, loop as u, branch as v, suggest_step_id as w, step as x, parallel as y, resolve_display_name as z };
3533
3522
 
3534
- //# sourceMappingURL=core-DK7g1Z40.js.map
3523
+ //# sourceMappingURL=core-CDrz0NM1.js.map