diff --git a/README.md b/README.md index 0c44487e..96fc0163 100644 --- a/README.md +++ b/README.md @@ -144,6 +144,10 @@ with replay, `session/close`, `session/prompt`, `session/cancel`), `session/dele compaction, display terminals for commands, permission requests, elicitation, providers, auth, and [subagents](#subagent-sessions). Steering and the AIR extensions are v1 only for now. +`CLAUDE_AGENT_ACP_V2_CORE=native` serves v2 with an experimental core that runs straight on +Claude Code instead of translating to v1. It serves less of the list above for now; see +[the native v2 core](docs/v2-native-core.md). + ## Contribution Policy This project does not require a Contributor License Agreement (CLA). Instead, contributions are accepted under the following terms: diff --git a/docs/v2-native-core.md b/docs/v2-native-core.md new file mode 100644 index 00000000..2dc56e69 --- /dev/null +++ b/docs/v2-native-core.md @@ -0,0 +1,224 @@ +# The native ACP v2 core + +Status: experimental, opt-in with `CLAUDE_AGENT_ACP_V2_CORE=native`. The default v2 core is +still the bridge. + +## Why + +The adapter serves ACP v2 through a bridge today: `src/v2/` converts each v2 request to v1, runs +it through `ClaudeAcpAgent`, and converts what comes back. So every v2 session runs the v1 core, +including the machinery that exists only because of v1: + +- **Held prompts.** A v1 `session/prompt` answers when the turn ends, so the core keeps a turn + queue and settles each turn itself. That needs echo matching, a per-uuid orphan account for + prompts a cancel settled after they were pushed, owed-trailing-idle debt (turns settle at the + `result`, and Claude Code's `idle` lags behind it), the steer lane, `cancelledThrough`, and the + hold for background subagents (`deferredSettle`). +- **AIR branches.** The JetBrains AIR extensions are gated on `air.client` throughout the core. + +The v1-only part is about 2,000 lines inline in `acp-agent.ts`, and it all runs on v2 too. For +example, `deferredSettle` holds a v2 turn open and `v2/prompt.ts` ignores the result. + +ACP v2 describes a session the way Claude Code already does. A prompt is inserted into a queue +and answered at insertion, and the session reports whether it is working. Claude Code reports +both, so a v2 core can follow Claude Code's own events instead of rebuilding a turn model. + +## How it maps + +| ACP v2 | Claude Code | +| ---------------------------------- | --------------------------------------------------------------------------------- | +| `session/prompt` answers | `command_lifecycle` `started` for the prompt's uuid, or the prompt's echo | +| `session/prompt` fails | `command_lifecycle` `cancelled` (-32800), `discarded` or `refused` (-32603) | +| `state_update` `running` | a turn starts: a prompt's `started`, or the turn's `system/init` | +| `state_update` `idle` | the turn's `result`, with its stop reason, usage and error | +| `state_update` `requires_action` | a turn is open and a permission request of the session is open | +| `session/cancel` | `interrupt({ cancelQueued: true })`, which also ends the queued prompts | +| `session/resume` with `replayFrom` | `getSessionMessages`, mapped like live output | +| output updates | the shared SDK mapping (`toAcpNotifications`), translated by `V2UpdateTranslator` | + +The session keeps little of its own: a map of prompts that are not inserted yet, whether a turn +is open, and its count of open permission requests (`src/v2-native/session.ts`). + +Claude Code's `session_state_changed` is not the foreground state. It stays `running` while +background subagents work: across the turn's `result`, the next prompts' turns, and the turn +that Claude Code starts on its own when a subagent ends. The bundled CLI shows it (a background +subagent that sleeps 20 seconds): + +```text + 0.4 session_state_changed running · command_lifecycle started (P1) · system init + 9.3 result "launched" · command_lifecycle completed (P1) +12.1 command_lifecycle started (P2) · system init +15.3 result "second" · command_lifecycle completed (P2) +33.3 task_notification completed · background_tasks_changed [] +33.4 system init +35.9 result · session_state_changed idle +``` + +So each turn is foreground work from its start to its `result`, as v2 asks ("When foreground +work ends, the Agent MUST report `idle`, even if background activity continues"). An `idle` +without a result, or the `completed` or `cancelled` frame of the turn's prompt, also ends a turn, +such as one that an interrupt stopped before it ran. + +## Subagents and background work + +`tasks.ts` is written for v2 only, rather than reusing `native-subagents.ts`, which also serves +AIR's draft and restores subagents from history. It follows the subagents RFD, from Claude +Code's task events (with `forwardSubagentText` and `perTaskStopAffordance`): + +| ACP v2 | Claude Code | +| ------------------------------------------------------ | ---------------------------------------------------------------------------------- | +| child session id | the agent id (`task_id`), the same for every delegation to it | +| `subagent_update` announcement, on the parent's stream | `task_started` of a `local_agent`; the parent is `parent_task_id`, or the root | +| the child's traffic | messages whose `parent_tool_use_id` is the Agent call that launched it | +| incoming `session_message` in the child | the first user text of each run: the delegation | +| `cwd` of the child | the `SubagentStart` hook's `cwd`, when it is not the parent's (such as a worktree) | +| child `running` / `idle`, mirrored on the parent | `task_started` (or a `running` patch) to `task_notification` | +| child `requires_action` | a permission request whose `agentID` is the child | +| `session/cancel` of a child | `stopTask(agentId)` | +| `background` of a session | its background subagents, commands (terminals), task tool calls and other tasks | +| `terminal/cancel`, `tool_call/cancel` | `stopTask` of the listed item's task | + +A child that its parent waits on (`is_backgrounded: false`) is part of the parent's foreground +work: its requests block the parent too (`requires_action`), and cancelling the parent stops +it. A background child is listed in its parent's `background` while it works, and cancelling +the parent leaves it running. The client can only watch a child and cancel its run: prompt, +close, resume, delete and config changes on it fail with -32602. + +## Layout + +- `src/v2-native/agent.ts`: the request handlers, session setup, and the SDK `query` options. +- `src/v2-native/session.ts`: one session: its prompts, its state, and the routing of the + query's messages. +- `src/v2-native/stream.ts`: the SDK output, and replayed history, as v2 updates. +- `src/v2-native/tasks.ts`: Claude Code's tasks: subagents as child sessions, and the + `background` list of each session (see below). +- `src/v2-native/permissions.ts`: `canUseTool` as v2 permission requests, on the session of the + agent that asks. +- `src/v2-native/config.ts`: the mode and model config options. + +About 2,600 lines in total. The native core shares these with v1 and the bridge: + +- the SDK message mapping and tool call rendering (`toAcpNotifications`, + `streamEventToAcpNotifications`, `tool-calls/*`) +- permission presentation, options and decoding (`permissions/*`) +- the mode catalog (`buildAvailableModes`) +- `promptToClaude` +- the v2 converters (`v2/session.ts`, `v2/permission.ts`, `v2/prompt.ts`) +- the `background` stamping and the `cancel` advertisement of listed items (`V2Background`) +- the background command helpers: `backgroundBashTaskFromToolResult`, `withRunningTerminal`, + `withRunningToolCall`, `BackgroundOutputTail` + +This change extracted three pieces so that both cores use the same code: + +- `V2UpdateTranslator` and `replayClear` (`v2/update-translator.ts`), taken from the bridge's + client connection +- `terminalAuthMethods` (`auth-methods.ts`), taken from `ClaudeAcpAgent.initialize` +- `sdkMcpServers` (`mcp-servers.ts`), taken from `ClaudeAcpAgent.createSession` + +## How it is checked + +- `src/tests/v2-native.test.ts` drives the core with a Claude Code double, message by message: + insertion, folding, lifecycle failures, cancel, permission states, config, local commands, + a crashed query, and replay. +- `src/tests/acp-scenarios-v2-native.test.ts` runs every scenario of the shared suite on the + native core. All 40 send only schema-valid v2. 39 pass. `ask-user-question` stops, because + the native core sends no form elicitations. `SAME_AS_BRIDGE` lists the scenarios whose session + updates equal the bridge's golden file, which today is only `session-setup`. The differences + are listed below. +- The scenario double now sends `session_state_changed` when the query asks for it, as the real + CLI does. The bridge and v1 scenario golden files did not change. +- A manual run against the bundled Claude Code CLI checked the following: + - a prompt answers at insertion + - Bash runs as display terminals + - a permission request goes `running` → `requires_action` → `running` + - `session/cancel` fails a queued prompt with -32800 and goes `idle` with `cancelled` + - the next prompt runs normally + +## Intended differences from the bridge + +- The turn's `running` comes before the prompt's `user_message`. v2 allows this. +- Output that comes after `session/cancel`, until the turn's `result`, is still sent: the work is + still stopping. The bridge drops the output of stopped work. +- A text block that an interrupt cut short does not get its tail from the consolidated message. + +## Not served yet + +- Session methods: + - `session/fork` (not advertised) + - `providers/*` + - gateway auth and `_auth/status_update` + - `auth/login` (only terminal logins are advertised) +- Elicitation (and so `requires_action` for a question): + - AskUserQuestion (the tool is disallowed) + - MCP elicitation (the SDK declines) + - the refusal-fallback dialog + - MCP OAuth +- Subagents: + - the child's configuration (`config_option_update` from the `SubagentStart` hook) + - the incoming view of a SendMessage, which the child's transcript does not show + - replaying children's history on resume (`getSubagentMessages`) + - a subagent whose parent Claude Code no longer tracks, such as after a restart, stays + unexposed: its traffic is the root's +- Reports: + - `usage_update` (context window, cost) + - quota `_meta` + - `session_info_update` (titles) + - notices (API retries, rate limits, model fallback) + - compaction updates + - prompt suggestions + - task-hook plans (TaskCreate) +- An Edit's patch before it runs (the bridge's PreToolUse preview). The permission request does + show it. +- Session options: + - `_meta.claudeCode.options` + - effort, fast mode, ultracode and agent options + - the thinking and model env (`MAX_THINKING_TOKENS`, `CLAUDE_MODEL_CONFIG`) + - the `availableModels` allowlist + - model preference from settings (the model starts at `default`) +- Resume: + - the mode and model of the transcript's last turn + - replaying compactions + - `replayFrom` other than `start` +- ExitPlanMode's "clear context" option. +- The v1-only features: AIR extensions, steering, Remote Control, idle compaction, the Claude + subscription guard, MCP startup failure notices, and file change reports. + +## Replacing the bridge + +1. Move the SDK mapping out of `acp-agent.ts`: `toAcpNotifications`, + `streamEventToAcpNotifications`, `promptToClaude`, `messageIdForGrouping`, and the helpers + they use. The native core imports them from `acp-agent.ts` today, which is its only tie to + the v1 core's module. +2. Port the gaps one feature at a time, each in a module that the native core owns. Start with + what clients use most: `usage_update` and titles. Several of + these are protocol-neutral modules already (`context-compaction.ts`, `session-titles.ts`). + Others are typed for v1 (`native-subagents.ts`, `background-work.ts`). +3. Ratchet `NATIVE_STOPS` and `SAME_AS_BRIDGE`, and make `native` the default once it serves + what v2 clients need. +4. Delete the bridge: `v2/agent.ts`, `v2/prompt.ts`, `v2/background.ts`, the v1 request + conversions, and the v2 paths of `ClaudeAcpAgent`. Those paths are the `v2` option, the + `foreground` and `background` hooks, `ForegroundEvents`, `foregroundWork`, and the + `this.v2` branches. The v1 core then serves v1 and AIR only. `ClientCapabilities.v2` stays: + the shared renderer uses it. + +## Spec checks + +Beyond the scenarios, `v2-native.test.ts` covers these requirements of the draft spec: + +- A cancel covers only the prompts received before it. A later prompt waits for the interrupt, + whose `cancelQueued` would end it otherwise. A prompt not pushed yet fails at once. +- A cancel that ended only queued prompts leaves the next turn's stop reason alone. +- `session/close` sends the cancelled work's final updates and `idle(cancelled)` before its + response, and nothing after. It waits up to 5 seconds for Claude Code to end the work. +- Closing or deleting a session that does not exist succeeds. +- Stopped work gives its unfinished tool calls a final status before its idle: `cancelled` + after a cancel, `failed` after an error. +- A session whose query ended is no longer active (-32002 with `data.sessionId`), and a resume + starts it again from its transcript. +- Resuming the active session checks the request as a new one, keeps its work, and replaces its + MCP servers. A different `cwd` or other additional directories are rejected. +- Config values must have the `id` type, additional directories must be absolute, and terminal + logins are advertised only with `auth.terminal`. + +`requires_action` comes from the session's own open requests, not Claude Code's: it covers +exactly this session's permission requests, and will cover its elicitations. diff --git a/src/acp-agent.ts b/src/acp-agent.ts index 264b201c..c85754b0 100644 --- a/src/acp-agent.ts +++ b/src/acp-agent.ts @@ -67,7 +67,6 @@ import { getSessionMessages, HookCallback, listSessions, - McpServerConfig, McpServerStatus, ModelInfo, ModelUsage, @@ -184,7 +183,8 @@ import { notLoggedInAuthStatus, sameAuthStatus, } from "./auth-status.js"; -import { agentCommand } from "./agent-command.js"; +import { terminalAuthMethods as authMethodsForTerminal } from "./auth-methods.js"; +import { sdkMcpServers } from "./mcp-servers.js"; import { claudeCliPath } from "./claude-cli.js"; import { ContentBlockParam } from "@anthropic-ai/sdk/resources"; import { BetaContentBlock, BetaRawContentBlockDelta } from "@anthropic-ai/sdk/resources/beta.mjs"; @@ -2968,87 +2968,11 @@ export class ClaudeAcpAgent { const supportsTerminalAuth = request.clientCapabilities?.auth?.terminal === true; const supportsMetaTerminalAuth = request.clientCapabilities?._meta?.["terminal-auth"] === true; - // Detect remote environments where the OAuth browser redirect to localhost - // won't work. This matches the SDK's internal isRemote check. In these cases, - // the `auth login` subcommand would fall back to a device-code-like manual - // flow, which doesn't work well over ACP, so we offer the TUI login instead. - const isRemote = !!( - process.env.NO_BROWSER || - process.env.SSH_CONNECTION || - process.env.SSH_CLIENT || - process.env.SSH_TTY || - process.env.CLAUDE_CODE_REMOTE - ); - const terminalAuthMethods: AuthMethod[] = []; + const terminalAuthMethods = authMethodsForTerminal({ + terminal: supportsTerminalAuth, + metaTerminal: supportsMetaTerminalAuth, + }); - if (isRemote) { - const remoteLoginMethod: AuthMethod = { - description: "Run `claude /login` in the terminal", - name: "Log in with Claude", - id: "claude-login", - type: "terminal", - args: ["--cli"], - }; - - if (supportsMetaTerminalAuth) { - const agent = agentCommand(); - remoteLoginMethod._meta = { - "terminal-auth": { - command: agent.command, - args: [...agent.args, "--cli"], - label: "Claude Login", - }, - }; - } - - if (!shouldHideClaudeAuth() && (supportsTerminalAuth || supportsMetaTerminalAuth)) { - terminalAuthMethods.push(remoteLoginMethod); - } - } else { - const claudeLoginMethod: AuthMethod = { - description: "Use Claude subscription ", - name: "Claude Subscription", - id: "claude-ai-login", - type: "terminal", - args: ["--cli", "auth", "login", "--claudeai"], - }; - - const consoleLoginMethod: AuthMethod = { - description: "Use Anthropic Console (API usage billing)", - name: "Anthropic Console", - id: "console-login", - type: "terminal", - args: ["--cli", "auth", "login", "--console"], - }; - - if (supportsMetaTerminalAuth) { - const agent = agentCommand(); - claudeLoginMethod._meta = { - "terminal-auth": { - command: agent.command, - args: [...agent.args, "--cli", "auth", "login", "--claudeai"], - label: "Claude Login", - }, - }; - consoleLoginMethod._meta = { - "terminal-auth": { - command: agent.command, - args: [...agent.args, "--cli", "auth", "login", "--console"], - label: "Anthropic Console Login", - }, - }; - } - - if (!shouldHideClaudeAuth() && (supportsTerminalAuth || supportsMetaTerminalAuth)) { - terminalAuthMethods.push(claudeLoginMethod); - } - if (supportsTerminalAuth || supportsMetaTerminalAuth) { - terminalAuthMethods.push(consoleLoginMethod); - } - } - - // The subagents RFD has only the client capability. AIR's draft also had - // this agent capability, which AIR gets (`docs/air-extensions.md`). const sessionCapabilities: SubagentAwareSessionCapabilities = { additionalDirectories: {}, close: {}, @@ -12037,31 +11961,7 @@ export class ClaudeAcpAgent { await settingsManager.initialize(); timing.phase("settings"); - const mcpServers: Record = {}; - if (Array.isArray(params.mcpServers)) { - for (const server of params.mcpServers) { - if ("type" in server && (server.type === "http" || server.type === "sse")) { - // HTTP or SSE type MCP server - mcpServers[server.name] = { - type: server.type, - url: server.url, - headers: server.headers - ? Object.fromEntries(server.headers.map((e) => [e.name, e.value])) - : undefined, - }; - } else if (!("type" in server)) { - // Stdio type MCP server (with or without explicit type field) - mcpServers[server.name] = { - type: "stdio", - command: server.command, - args: server.args, - env: server.env - ? Object.fromEntries(server.env.map((e) => [e.name, e.value])) - : undefined, - }; - } - } - } + const mcpServers = sdkMcpServers(params.mcpServers); const customInstructions = airCustomInstructions(params._meta); let systemPrompt: Options["systemPrompt"] = diff --git a/src/auth-methods.ts b/src/auth-methods.ts new file mode 100644 index 00000000..8ff81756 --- /dev/null +++ b/src/auth-methods.ts @@ -0,0 +1,88 @@ +import type { AuthMethod } from "@agentclientprotocol/sdk/unstable"; +import { agentCommand } from "./agent-command.js"; +import { shouldHideClaudeAuth } from "./hide-claude-auth.js"; + +/** + * The terminal login methods the agent advertises, in v1 form. + * + * - `terminal`: the client runs `args` against the agent's own command + * (`auth.terminal` in v1, an `auth.terminal` object in v2). + * - `metaTerminal`: the client reads `_meta["terminal-auth"]`, which names + * the command too. + * + * Without either, the client cannot run a login, and the list is empty. On a + * remote machine (SSH, `NO_BROWSER`, `CLAUDE_CODE_REMOTE`, as the SDK's own + * isRemote check) the OAuth redirect to localhost cannot reach a browser, and + * `claude auth login` falls back to a manual flow that does not work over ACP, + * so the one method runs the TUI's `claude /login` instead. The Claude + * subscription method is left out when `shouldHideClaudeAuth()` says so. + */ +export function terminalAuthMethods({ + terminal, + metaTerminal, +}: { + terminal: boolean; + metaTerminal: boolean; +}): AuthMethod[] { + if (!terminal && !metaTerminal) return []; + const withMeta = (method: AuthMethod & { args: string[] }, label: string): AuthMethod => { + if (!metaTerminal) return method; + const agent = agentCommand(); + return { + ...method, + _meta: { + "terminal-auth": { command: agent.command, args: [...agent.args, ...method.args], label }, + }, + }; + }; + const isRemote = !!( + process.env.NO_BROWSER || + process.env.SSH_CONNECTION || + process.env.SSH_CLIENT || + process.env.SSH_TTY || + process.env.CLAUDE_CODE_REMOTE + ); + if (isRemote) { + if (shouldHideClaudeAuth()) return []; + return [ + withMeta( + { + description: "Run `claude /login` in the terminal", + name: "Log in with Claude", + id: "claude-login", + type: "terminal", + args: ["--cli"], + }, + "Claude Login", + ), + ]; + } + const methods: AuthMethod[] = []; + if (!shouldHideClaudeAuth()) { + methods.push( + withMeta( + { + description: "Use Claude subscription ", + name: "Claude Subscription", + id: "claude-ai-login", + type: "terminal", + args: ["--cli", "auth", "login", "--claudeai"], + }, + "Claude Login", + ), + ); + } + methods.push( + withMeta( + { + description: "Use Anthropic Console (API usage billing)", + name: "Anthropic Console", + id: "console-login", + type: "terminal", + args: ["--cli", "auth", "login", "--console"], + }, + "Anthropic Console Login", + ), + ); + return methods; +} diff --git a/src/index.ts b/src/index.ts index 1cc9e06a..09775c2c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2,7 +2,7 @@ import { claudeCliPath } from "./claude-cli.js"; import { applyManagedPolicyEnv } from "./managed-policy.js"; -import { acpProtocolsFromEnv, serveAcp } from "./serve.js"; +import { acpProtocolsFromEnv, serveAcp, v2CoreFromEnv } from "./serve.js"; import packageJson from "../package.json" with { type: "json" }; import { appendFileSync, mkdirSync } from "node:fs"; import { join } from "node:path"; @@ -85,6 +85,7 @@ if (process.argv.includes("--cli")) { const acp = serveAcp(logger, { protocols: acpProtocolsFromEnv(process.env.CLAUDE_AGENT_ACP_PROTOCOL), + v2Core: v2CoreFromEnv(process.env.CLAUDE_AGENT_ACP_V2_CORE), }); async function shutdown() { diff --git a/src/mcp-servers.ts b/src/mcp-servers.ts new file mode 100644 index 00000000..e691de58 --- /dev/null +++ b/src/mcp-servers.ts @@ -0,0 +1,33 @@ +import type { McpServer } from "@agentclientprotocol/sdk/unstable"; +import type { McpServerConfig } from "@anthropic-ai/claude-agent-sdk"; + +/** + * The SDK configs of a session's ACP MCP servers, by name. HTTP and SSE + * servers keep their URL and headers; a server without `type` is stdio. A + * server of any other transport is left out: the session's `initialize` + * advertises none. + */ +export function sdkMcpServers( + servers: readonly McpServer[] | null | undefined, +): Record { + const configs: Record = {}; + for (const server of servers ?? []) { + if ("type" in server && (server.type === "http" || server.type === "sse")) { + configs[server.name] = { + type: server.type, + url: server.url, + headers: server.headers + ? Object.fromEntries(server.headers.map((e) => [e.name, e.value])) + : undefined, + }; + } else if (!("type" in server)) { + configs[server.name] = { + type: "stdio", + command: server.command, + args: server.args, + env: server.env ? Object.fromEntries(server.env.map((e) => [e.name, e.value])) : undefined, + }; + } + } + return configs; +} diff --git a/src/serve.ts b/src/serve.ts index 3f11699d..19c71bd6 100644 --- a/src/serve.ts +++ b/src/serve.ts @@ -2,6 +2,7 @@ import * as v2 from "@agentclientprotocol/sdk/experimental/v2"; import { v1AgentApp, type ClaudeAcpAgent, type Logger } from "./acp-agent.js"; import { nodeToWebReadable, nodeToWebWritable } from "./utils.js"; import { v2AgentApp } from "./v2/agent.js"; +import { nativeV2AgentApp, type AgentHandle } from "./v2-native/agent.js"; /** * The ACP versions that the adapter serves: `v1` or `v2` alone, or both with @@ -23,22 +24,45 @@ export function acpProtocolsFromEnv(value: string | undefined): AcpProtocols { ); } +/** + * The implementation that serves ACP v2: + * + * - `bridge` (the default): `src/v2/`, which converts each v2 request to v1 + * and serves it with `ClaudeAcpAgent`. + * - `native`: `src/v2-native/`, which serves v2 straight from Claude Code. + * Experimental: see `docs/v2-native-core.md` for what it does not serve. + */ +export type V2Core = "bridge" | "native"; + +/** + * Reads `CLAUDE_AGENT_ACP_V2_CORE`: unset or empty is `bridge`. Throws on any + * value other than `bridge` and `native`. + */ +export function v2CoreFromEnv(value: string | undefined): V2Core { + if (value === undefined || value === "") return "bridge"; + if (value === "bridge" || value === "native") return value; + throw new Error( + `CLAUDE_AGENT_ACP_V2_CORE must be "bridge" or "native", not ${JSON.stringify(value)}`, + ); +} + /** Serves ACP on stdio through {@link acpProtocolRouter}. */ export function serveAcp( logger: Logger | undefined, - options: { protocols: AcpProtocols }, + options: { protocols: AcpProtocols; v2Core?: V2Core }, ): { closed: Promise; dispose(): Promise } { const output = nodeToWebWritable(process.stdout); const input = nodeToWebReadable(process.stdin); // The router opens the connection of the negotiated version only when it // reads `initialize`, so a client that leaves before then leaves no agent. - let agent: ClaudeAcpAgent | undefined; - const onAgent = (created: ClaudeAcpAgent) => { + let agent: AgentHandle | undefined; + const onAgent = (created: AgentHandle) => { agent = created; }; - const { closed } = acpProtocolRouter(logger, onAgent, options.protocols).connect( - v2.ndJsonStream(output, input), - ); + const { closed } = acpProtocolRouter(logger, onAgent, options.protocols, { + v2Core: options.v2Core, + onNativeAgent: onAgent, + }).connect(v2.ndJsonStream(output, input)); return { closed, dispose: async () => { @@ -53,15 +77,25 @@ export function serveAcp( * the draft ACP v2, and every other client gets ACP v1. With `v1`, a v2 * client is negotiated down to v1. With `v2`, the router rejects the * `initialize` of a v1 client as an unsupported protocol version. `onAgent` - * receives the agent of the connection once the router has opened it. + * receives the agent of the connection once the router has opened it, and + * `onNativeAgent` the agent of a v2 connection that the native core serves + * (`v2Core: "native"`). */ export function acpProtocolRouter( logger: Logger | undefined, onAgent: (agent: ClaudeAcpAgent) => void, protocols: AcpProtocols = "auto", + { + v2Core = "bridge", + onNativeAgent = () => {}, + }: { v2Core?: V2Core; onNativeAgent?: (agent: AgentHandle) => void } = {}, ): v2.AgentProtocolRouter { const router = v2.agentProtocolRouter(); if (protocols !== "v2") router.withV1(v1AgentApp(logger, onAgent)); - if (protocols !== "v1") router.withV2(v2AgentApp(logger, onAgent)); + if (protocols !== "v1") { + router.withV2( + v2Core === "native" ? nativeV2AgentApp(logger, onNativeAgent) : v2AgentApp(logger, onAgent), + ); + } return router; } diff --git a/src/session-mode.ts b/src/session-mode.ts index 2004e97e..2eabaf35 100644 --- a/src/session-mode.ts +++ b/src/session-mode.ts @@ -405,7 +405,7 @@ export class SessionModeManager { } } -function buildAvailableModes( +export function buildAvailableModes( { allowBypass, allowAuto }: ModeAvailability, air = false, ): SessionModeState["availableModes"] { diff --git a/src/tests/acp-scenarios-v2-native.test.ts b/src/tests/acp-scenarios-v2-native.test.ts new file mode 100644 index 00000000..5bc82a6f --- /dev/null +++ b/src/tests/acp-scenarios-v2-native.test.ts @@ -0,0 +1,165 @@ +/** + * Every scenario of `acp-scenarios/scenarios.ts` on the native ACP v2 core + * (`CLAUDE_AGENT_ACP_V2_CORE=native`), as `acp-scenarios-v2.test.ts` runs them + * on the bridge. + * + * - Status: each scenario passes, or stops as {@link NATIVE_STOPS} says. + * - Schema: every message the native core sends is valid against the draft + * v2 schema, also in a scenario that stops. + * - Parity: the scenarios whose session updates equal the bridge's golden + * file are listed in {@link SAME_AS_BRIDGE}, so a change in parity, either + * way, shows up as a diff of that list. `docs/v2-native-core.md` says why + * the others differ. + */ +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; +import { fileURLToPath } from "node:url"; +import type { AgentHandle } from "../v2-native/agent.js"; +import { + resetIds, + runScenarioV2, + type ScenarioRunV2, + type WireRecorded, +} from "./acp-scenarios/harness.js"; +import { SCENARIOS } from "./acp-scenarios/scenarios.js"; +import { canonical } from "./acp-scenarios/compare.js"; +import { validateV2Message } from "./acp-scenarios/schema.js"; + +vi.mock("@anthropic-ai/claude-agent-sdk", async (importOriginal) => { + const actual = await importOriginal(); + const harness = await import("./acp-scenarios/harness.js"); + return { + ...actual, + query: harness.mockedQuery, + getSessionMessages: harness.mockedSessionMessages, + getSessionInfo: harness.mockedSessionInfo, + }; +}); + +vi.mock("node:crypto", async (importOriginal) => { + const actual = await importOriginal(); + const harness = await import("./acp-scenarios/harness.js"); + return { + ...actual, + randomUUID: (...args: Parameters) => { + const id = actual.randomUUID(...args); + harness.noteGeneratedId(id); + return id; + }, + }; +}); + +const here = path.dirname(fileURLToPath(import.meta.url)); + +const PASSES = "passes"; + +/** + * The scenarios that stop on the native core, each with the reason, as the + * native core reports it. + */ +const NATIVE_STOPS: Record = { + // AskUserQuestion needs a form elicitation, which the native core does not + // send: it disallows the tool, and the scenario's script, which calls it + // anyway, then ends the stream. + "ask-user-question": "Internal error: Claude Code stopped. Resume the session to continue.", +}; + +/** + * The scenarios whose session updates equal the bridge's v2 golden file. + * The others differ in what the native core does not report yet + * (`usage_update`, the `background` list and quota `_meta` of a state, an + * Edit's patch before it runs, ...), and in that Claude Code's `running` + * comes before the prompt's `user_message`. + */ +const SAME_AS_BRIDGE: string[] = ["session-setup"]; + +const runs = new Map(); +let configDir: string; + +beforeAll(async () => { + for (const name of ["SSH_CONNECTION", "SSH_CLIENT", "SSH_TTY", "NO_BROWSER"]) { + vi.stubEnv(name, ""); + } + vi.stubEnv("CLAUDE_CODE_REMOTE", ""); + vi.stubEnv("ANTHROPIC_MODEL", ""); + vi.stubEnv("IS_SANDBOX", "1"); + vi.stubEnv("CLAUDE_CODE_EXECUTABLE", "/usr/bin/false"); + configDir = fs.mkdtempSync(path.join(os.tmpdir(), "acp-scenario-config-")); + vi.stubEnv("CLAUDE_CONFIG_DIR", configDir); + const { acpProtocolRouter } = await import("../serve.js"); + for (const scenario of SCENARIOS) { + resetIds(); + const agents: AgentHandle[] = []; + const quiet = { log: () => {}, error: () => {} }; + runs.set( + scenario.name, + await runScenarioV2( + (stream) => + acpProtocolRouter(quiet, () => {}, "auto", { + v2Core: "native", + onNativeAgent: (agent) => agents.push(agent), + }).connect(stream), + scenario, + ), + ); + await Promise.all(agents.map((agent) => agent.dispose())); + } +}, 120_000); + +afterAll(() => { + vi.unstubAllEnvs(); + fs.rmSync(configDir, { recursive: true, force: true }); +}); + +function run(scenario: string): ScenarioRunV2 { + const recorded = runs.get(scenario); + if (!recorded) throw new Error(`no native run of ${scenario}`); + return recorded; +} + +/** The session updates of a run, as lines of its golden file. */ +function sessionUpdateLines(recorded: WireRecorded[]): string[] { + return recorded + .filter((record) => record.kind === "notification" && record.method === "session/update") + .map((record) => canonical(record)); +} + +function bridgeSessionUpdateLines(scenario: string): string[] | undefined { + const file = path.join(here, "acp-scenarios", "__snapshots__", "v2", `${scenario}.jsonl`); + if (!fs.existsSync(file)) return undefined; + return fs + .readFileSync(file, "utf8") + .split("\n") + .filter( + (line) => line.includes('"method":"session/update"') && line.includes('"notification"'), + ); +} + +describe("ACP v2 scenarios on the native core", () => { + it("pass, or stop as the table says", () => { + const table = (status: (scenario: string) => string) => + Object.fromEntries(SCENARIOS.map((scenario) => [scenario.name, status(scenario.name)])); + expect(table((scenario) => run(scenario).status)).toEqual( + table((scenario) => NATIVE_STOPS[scenario] ?? PASSES), + ); + }); + + describe("schema check", () => { + it.each(SCENARIOS.map((scenario) => scenario.name))("%s", (scenario) => { + expect(run(scenario).raw.flatMap((message) => validateV2Message(message))).toEqual([]); + }); + }); + + it("send the bridge's session updates in the scenarios the parity list names", () => { + const same = SCENARIOS.map((scenario) => scenario.name).filter((scenario) => { + const bridge = bridgeSessionUpdateLines(scenario); + return ( + bridge !== undefined && + JSON.stringify(sessionUpdateLines(run(scenario).normalized)) === JSON.stringify(bridge) + ); + }); + expect(same).toEqual(SAME_AS_BRIDGE); + }); +}); diff --git a/src/tests/acp-scenarios/harness.ts b/src/tests/acp-scenarios/harness.ts index 74ab42ba..813e8463 100644 --- a/src/tests/acp-scenarios/harness.ts +++ b/src/tests/acp-scenarios/harness.ts @@ -94,6 +94,7 @@ export const PROFILES: Record = { type QueryOptions = { sessionId?: string; resume?: string; + env?: Record; canUseTool?: ( toolName: string, input: Record, @@ -234,6 +235,16 @@ export function mockedQuery(args: { prompt: AsyncIterable; options: QueryOp ); }, }; + // With `CLAUDE_CODE_EMIT_SESSION_STATE_EVENTS`, Claude Code reports that it + // works once it takes a prompt in, and that it is idle after the result. + const stateEvents = options.env?.CLAUDE_CODE_EMIT_SESSION_STATE_EVENTS === "1"; + const state = (value: "running" | "idle") => ({ + type: "system", + subtype: "session_state_changed", + state: value, + uuid: `state-${value}`, + session_id: sessionId, + }); async function* run() { const iterator = args.prompt[Symbol.asyncIterator](); for (const turn of script.scenario.turns) { @@ -241,6 +252,7 @@ export function mockedQuery(args: { prompt: AsyncIterable; options: QueryOp if (next.done) return; const user = next.value; ctx.promptUuid = user.uuid; + if (stateEvents) yield state("running"); yield { type: "user", message: user.message, @@ -250,6 +262,7 @@ export function mockedQuery(args: { prompt: AsyncIterable; options: QueryOp isReplay: true, }; yield* turn(ctx); + if (stateEvents) yield state("idle"); } // Stay open like a live Claude Code process. await iterator.next(); diff --git a/src/tests/v2-native.test.ts b/src/tests/v2-native.test.ts new file mode 100644 index 00000000..987c04c9 --- /dev/null +++ b/src/tests/v2-native.test.ts @@ -0,0 +1,1092 @@ +/** + * The native ACP v2 core (`src/v2-native/`), driven through the protocol + * router with the SDK's v2 client app, which validates every response and + * session update against the v2 schema. + * + * Claude Code is a double that the test drives message by message (see + * {@link FakeClaudeCode}), shaped like what the bundled CLI sends: prompt + * echoes with `isReplay`, `command_lifecycle` frames, and + * `session_state_changed`. + */ +import { randomUUID } from "node:crypto"; +import { mkdtemp, rm } from "node:fs/promises"; +import * as os from "node:os"; +import * as path from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import * as v2 from "@agentclientprotocol/sdk/experimental/v2/unstable"; +import { + getSessionMessages, + type Options, + type SDKUserMessage, +} from "@anthropic-ai/claude-agent-sdk"; +import { acpProtocolRouter, v2CoreFromEnv } from "../serve.js"; +import type { AgentHandle } from "../v2-native/agent.js"; + +/** One Claude Code process: the prompts it reads and the messages it sends. */ +type FakeClaudeCode = { + options: Options; + /** The prompts the session pushed, in order. */ + prompts: SDKUserMessage[]; + /** Resolves with the `index`th prompt once the session pushed it. */ + prompt(index: number): Promise; + /** Sends a message to the session. */ + send(message: Record): void; + /** Ends the stream, with `error` as a crash. */ + end(error?: Error): void; + interrupt: ReturnType; + setPermissionMode: ReturnType; + setModel: ReturnType; + stopTask: ReturnType; + close: ReturnType; +}; + +const sdk = vi.hoisted(() => ({ + processes: [] as FakeClaudeCode[], + models: [ + { value: "default", displayName: "Default", description: "Recommended" }, + { value: "opus", displayName: "Opus", description: "Most capable" }, + ], +})); + +vi.mock("@anthropic-ai/claude-agent-sdk", async () => { + const actual = await vi.importActual( + "@anthropic-ai/claude-agent-sdk", + ); + return { + ...actual, + query: ({ prompt, options }: { prompt: AsyncIterable; options: Options }) => { + const queue: Array> | Error> = []; + let wake = () => {}; + const prompts: SDKUserMessage[] = []; + let promptArrived = () => {}; + void (async () => { + for await (const message of prompt) { + prompts.push(message); + promptArrived(); + } + })(); + const push = (item: IteratorResult> | Error) => { + queue.push(item); + wake(); + }; + const fake: FakeClaudeCode = { + options, + prompts, + prompt: async (index) => { + while (prompts.length <= index) { + await new Promise((resolve) => (promptArrived = resolve)); + } + return prompts[index]; + }, + send: (message) => push({ value: message, done: false }), + end: (error) => push(error ?? { value: undefined, done: true }), + interrupt: vi.fn(async () => undefined), + setPermissionMode: vi.fn(async () => {}), + setModel: vi.fn(async () => {}), + stopTask: vi.fn(async () => {}), + close: vi.fn(() => push({ value: undefined, done: true })), + }; + sdk.processes.push(fake); + const messages: AsyncGenerator> = { + async next() { + while (queue.length === 0) await new Promise((resolve) => (wake = resolve)); + const item = queue.shift()!; + if (item instanceof Error) throw item; + return item; + }, + async return() { + return { value: undefined, done: true }; + }, + async throw(error) { + throw error; + }, + [Symbol.asyncIterator]() { + return this; + }, + async [Symbol.asyncDispose]() {}, + }; + return Object.assign(messages, { + initializationResult: async () => ({ models: sdk.models }), + supportedCommands: async () => [ + { name: "review", description: "Review a change", argumentHint: "" }, + ], + interrupt: fake.interrupt, + setPermissionMode: fake.setPermissionMode, + setModel: fake.setModel, + stopTask: fake.stopTask, + close: fake.close, + }); + }, + getSessionMessages: vi.fn(async () => []), + }; +}); + +vi.mock("../tools.js", async () => ({ + ...(await vi.importActual("../tools.js")), + registerHookCallback: vi.fn(), +})); + +const agents: AgentHandle[] = []; +let tempDir: string; +let cwd: string; + +beforeEach(async () => { + tempDir = await mkdtemp(path.join(os.tmpdir(), "acp-v2-native-")); + cwd = await mkdtemp(path.join(tempDir, "project-")); + vi.stubEnv("CLAUDE_CONFIG_DIR", path.join(tempDir, "claude")); + sdk.processes = []; +}); + +afterEach(async () => { + await Promise.all(agents.splice(0).map((agent) => agent.dispose())); + vi.unstubAllEnvs(); + await rm(tempDir, { recursive: true, force: true, maxRetries: 10 }); +}); + +/** A v2 client of the native core that records the session updates it receives. */ +function nativeClient({ + answerPermission = () => ({ outcome: { outcome: "cancelled" } }), +}: { + answerPermission?: ( + request: v2.RequestPermissionRequest, + ) => v2.RequestPermissionResponse | Promise; +} = {}) { + const sessionUpdates: v2.SessionUpdate[] = []; + const notifications: v2.UpdateSessionNotification[] = []; + const permissionRequests: v2.RequestPermissionRequest[] = []; + const app = v2 + .client({ name: "native-test-client" }) + .onNotification(v2.methods.client.session.update, ({ params }) => { + notifications.push(params); + sessionUpdates.push(params.update); + }) + .onRequest(v2.methods.client.session.requestPermission, ({ params }) => { + permissionRequests.push(params); + return answerPermission(params); + }); + const toAgent = new TransformStream(); + const toClient = new TransformStream(); + acpProtocolRouter(undefined, () => {}, "v2", { + v2Core: "native", + onNativeAgent: (agent) => agents.push(agent), + }).connect({ readable: toAgent.readable, writable: toClient.writable }); + /** The `state_update`s of root sessions, not subagents', as their states. */ + const states = () => { + const children = new Set( + notifications.flatMap(({ update }) => + update.sessionUpdate === "subagent_update" ? [update.sessionId] : [], + ), + ); + return notifications.flatMap(({ sessionId, update }) => + update.sessionUpdate === "state_update" && !children.has(sessionId) ? [update.state] : [], + ); + }; + return { + sessionUpdates, + notifications, + permissionRequests, + states, + connect: (run: (agent: v2.ClientContext) => Promise) => + app.connectWith({ readable: toClient.readable, writable: toAgent.writable }, run), + }; +} + +async function openSession(agent: v2.ClientContext, capabilities: v2.ClientCapabilities = {}) { + await agent.request(v2.methods.agent.initialize, { + protocolVersion: v2.PROTOCOL_VERSION, + info: { name: "native-test-client", version: "1.0.0" }, + capabilities, + }); + const response = await agent.request(v2.methods.agent.session.new, { cwd }); + return { response, claude: sdk.processes.at(-1)! }; +} + +function lifecycle(prompt: SDKUserMessage, state: string) { + return { type: "command_lifecycle", command_uuid: prompt.uuid, state, uuid: randomUUID() }; +} + +function echo(prompt: SDKUserMessage) { + return { + type: "user", + message: prompt.message, + parent_tool_use_id: null, + uuid: prompt.uuid, + session_id: "session", + isReplay: true, + }; +} + +function sessionState(state: "idle" | "running" | "requires_action") { + return { type: "system", subtype: "session_state_changed", state, uuid: randomUUID() }; +} + +/** The `system/init` that starts each turn, also one that no prompt started. */ +function turnInit() { + return { type: "system", subtype: "init", uuid: randomUUID() }; +} + +function textDelta(id: string, text: string) { + return [ + { + type: "stream_event", + event: { type: "message_start", message: { id, content: [] } }, + parent_tool_use_id: null, + uuid: randomUUID(), + }, + { + type: "stream_event", + event: { type: "content_block_delta", index: 0, delta: { type: "text_delta", text } }, + parent_tool_use_id: null, + uuid: randomUUID(), + }, + ]; +} + +function assistant(id: string, content: unknown[]) { + return { + type: "assistant", + message: { id, type: "message", role: "assistant", content, usage: {} }, + parent_tool_use_id: null, + uuid: randomUUID(), + }; +} + +function result(overrides: Record = {}) { + return { + type: "result", + subtype: "success", + stop_reason: "end_turn", + is_error: false, + result: "", + errors: [], + usage: { + input_tokens: 3, + output_tokens: 2, + cache_read_input_tokens: 1, + cache_creation_input_tokens: 0, + }, + uuid: randomUUID(), + ...overrides, + }; +} + +const PROMPT = [{ type: "text" as const, text: "Hi" }]; + +/** + * A subagent's task events and messages, shaped like the bundled CLI's: its + * messages carry the id of the Agent call that launched it. + */ +function subagent(agentId: string, launch: string, fields: Record = {}) { + const system = (subtype: string, more: Record) => ({ + type: "system", + subtype, + task_id: agentId, + uuid: randomUUID(), + ...more, + }); + return { + started: (more: Record = {}) => + system("task_started", { + tool_use_id: launch, + task_type: "local_agent", + subagent_type: "general-purpose", + description: "Investigate the test", + is_backgrounded: false, + ...fields, + ...more, + }), + ended: (status = "completed") => + system("task_notification", { tool_use_id: launch, status, output_file: "", summary: "" }), + prompt: (text: string) => ({ + type: "user", + message: { role: "user", content: [{ type: "text", text }] }, + parent_tool_use_id: launch, + uuid: randomUUID(), + }), + says: (text: string) => ({ + ...assistant(`msg_${agentId}`, [{ type: "text", text }]), + parent_tool_use_id: launch, + }), + }; +} + +/** The updates of the session `sessionId` that the client received, in order. */ +function updatesOf( + notifications: v2.UpdateSessionNotification[], + sessionId: string, +): v2.SessionUpdate[] { + return notifications.flatMap((n) => (n.sessionId === sessionId ? [n.update] : [])); +} + +describe("native ACP v2 core", () => { + it("advertises the v2 session baseline without fork, and terminal logins", async () => { + const client = nativeClient(); + const response = await client.connect((agent) => + agent.request(v2.methods.agent.initialize, { + protocolVersion: v2.PROTOCOL_VERSION, + info: { name: "native-test-client", version: "1.0.0" }, + capabilities: { auth: { terminal: {} } }, + }), + ); + + expect(response.protocolVersion).toBe(2); + expect(response.capabilities?.session?.fork).toBeUndefined(); + expect(response.capabilities?.session?.prompt).toEqual({ image: {}, embeddedContext: {} }); + expect((response.authMethods ?? []).map((method) => method.methodId)).toContain( + "console-login", + ); + }); + + it("answers session/new with the mode and model options and the commands", async () => { + const client = nativeClient(); + const { response, claude } = await client.connect((agent) => openSession(agent)); + + expect(response.configOptions?.map((option) => option.configId)).toEqual(["mode", "model"]); + expect(response.availableCommands).toEqual([ + { + type: "command", + name: "review", + description: "Review a change", + input: { type: "text", hint: "" }, + }, + ]); + // Each prompt is echoed, and the session's state is reported. + expect(claude.options.extraArgs).toMatchObject({ "replay-user-messages": "" }); + expect(claude.options.env?.CLAUDE_CODE_EMIT_SESSION_STATE_EVENTS).toBe("1"); + }); + + it("answers a prompt when Claude Code starts it, and reports the work until the turn's result", async () => { + const client = nativeClient(); + await client.connect(async (agent) => { + const { response, claude } = await openSession(agent); + const answer = agent.request(v2.methods.agent.session.prompt, { + sessionId: response.sessionId, + prompt: PROMPT, + }); + const prompt = await claude.prompt(0); + claude.send(sessionState("running")); + claude.send(lifecycle(prompt, "started")); + expect(await answer).toEqual({ messageId: prompt.uuid }); + // The echo of a prompt that already started inserts nothing more. + claude.send(echo(prompt)); + for (const event of textDelta("msg_1", "Hello")) claude.send(event); + claude.send(assistant("msg_1", [{ type: "text", text: "Hello" }])); + claude.send(result({ result: "Hello" })); + claude.send(sessionState("idle")); + await vi.waitFor(() => expect(client.states()).toEqual(["running", "idle"])); + }); + + const kinds = client.sessionUpdates + .map((update) => update.sessionUpdate) + .filter((kind) => kind !== "available_commands_update"); + expect(kinds).toEqual(["state_update", "user_message", "agent_message_chunk", "state_update"]); + expect(client.sessionUpdates.at(-1)).toEqual({ + sessionUpdate: "state_update", + state: "idle", + stopReason: "end_turn", + // The session reports its background work, on every state. + background: [], + usage: { + inputTokens: 3, + outputTokens: 2, + cachedReadTokens: 1, + cachedWriteTokens: 0, + totalTokens: 6, + }, + }); + }); + + it("inserts a prompt that Claude Code folds into the running work at its echo", async () => { + const client = nativeClient(); + await client.connect(async (agent) => { + const { response, claude } = await openSession(agent); + const answer = agent.request(v2.methods.agent.session.prompt, { + sessionId: response.sessionId, + prompt: PROMPT, + }); + const prompt = await claude.prompt(0); + claude.send(echo(prompt)); + expect(await answer).toEqual({ messageId: prompt.uuid }); + }); + + expect(client.sessionUpdates).toContainEqual({ + sessionUpdate: "user_message", + messageId: expect.any(String), + content: PROMPT, + }); + }); + + it.each([ + ["discarded", -32603], + ["refused", -32603], + ])("fails a prompt that Claude Code %s", async (state, code) => { + const client = nativeClient(); + const error = await client.connect(async (agent) => { + const { response, claude } = await openSession(agent); + const answer = agent.request(v2.methods.agent.session.prompt, { + sessionId: response.sessionId, + prompt: PROMPT, + }); + claude.send(lifecycle(await claude.prompt(0), state)); + return answer.catch((error: unknown) => error); + }); + + expect(error).toMatchObject({ code }); + }); + + it("cancels the work and the prompts not inserted yet with one interrupt", async () => { + const client = nativeClient(); + await client.connect(async (agent) => { + const { response, claude } = await openSession(agent); + const sessionId = response.sessionId; + const first = agent.request(v2.methods.agent.session.prompt, { sessionId, prompt: PROMPT }); + const running = await claude.prompt(0); + claude.send(sessionState("running")); + claude.send(lifecycle(running, "started")); + await first; + const queued = agent.request(v2.methods.agent.session.prompt, { sessionId, prompt: PROMPT }); + const waiting = await claude.prompt(1); + + await agent.notify(v2.methods.agent.session.cancel, { sessionId }); + await vi.waitFor(() => expect(claude.interrupt).toHaveBeenCalledWith({ cancelQueued: true })); + // Claude Code ends the queued prompt, then the interrupted work. + claude.send(lifecycle(waiting, "cancelled")); + await expect(queued).rejects.toMatchObject({ code: -32800 }); + claude.send(result({ subtype: "error_during_execution", is_error: true })); + claude.send(sessionState("idle")); + await vi.waitFor(() => expect(client.states()).toEqual(["running", "idle"])); + }); + + expect(client.sessionUpdates.at(-1)).toMatchObject({ state: "idle", stopReason: "cancelled" }); + }); + + it("reports requires_action while a permission request is open, and running once answered", async () => { + const client = nativeClient({ + answerPermission: (request) => ({ + outcome: { outcome: "selected", optionId: request.options[0].optionId }, + }), + }); + const decision = await client.connect(async (agent) => { + const { claude } = await openSession(agent); + claude.send(turnInit()); + await vi.waitFor(() => expect(client.states()).toEqual(["running"])); + return claude.options.canUseTool!( + "Bash", + { command: "ls" }, + { + signal: new AbortController().signal, + toolUseID: "toolu_1", + requestId: "r1", + suggestions: [], + }, + ); + }); + + expect(decision?.behavior).toBe("allow"); + expect(client.states()).toEqual(["running", "requires_action", "running"]); + expect(client.permissionRequests[0].subject).toMatchObject({ + type: "tool_call", + toolCall: { toolCallId: "toolu_1" }, + }); + }); + + it("reads a dismissed permission request as the user refusing the tool", async () => { + const client = nativeClient(); + const decision = await client.connect(async (agent) => { + const { claude } = await openSession(agent); + return claude.options.canUseTool!( + "Bash", + { command: "rm -rf build" }, + { + signal: new AbortController().signal, + toolUseID: "toolu_1", + requestId: "r1", + suggestions: [], + }, + ); + }); + + expect(decision).toMatchObject({ behavior: "deny", decisionClassification: "user_reject" }); + }); + + it("sets a config option on the query and sends it as an update too", async () => { + const client = nativeClient(); + const { claude, configOptions } = await client.connect(async (agent) => { + const { response, claude } = await openSession(agent); + const { configOptions } = await agent.request(v2.methods.agent.session.setConfigOption, { + sessionId: response.sessionId, + configId: "mode", + type: "id", + value: "plan", + } as v2.SetSessionConfigOptionRequest); + return { claude, configOptions }; + }); + + expect(claude.setPermissionMode).toHaveBeenCalledWith("plan"); + const mode = configOptions.find((option) => option.configId === "mode"); + expect(mode).toMatchObject({ currentValue: "plan" }); + expect(client.sessionUpdates).toContainEqual({ + sessionUpdate: "config_option_update", + configOptions, + }); + }); + + it("forwards the result of a local command, which streamed no text", async () => { + const client = nativeClient(); + await client.connect(async (agent) => { + const { response, claude } = await openSession(agent); + const answer = agent.request(v2.methods.agent.session.prompt, { + sessionId: response.sessionId, + prompt: [{ type: "text", text: "/context" }], + }); + const prompt = await claude.prompt(0); + claude.send(sessionState("running")); + claude.send(lifecycle(prompt, "started")); + await answer; + claude.send(result({ result: "Context: 12k tokens" })); + claude.send(sessionState("idle")); + await vi.waitFor(() => expect(client.states()).toEqual(["running", "idle"])); + }); + + expect(client.sessionUpdates).toContainEqual( + expect.objectContaining({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Context: 12k tokens" }, + }), + ); + }); + + it("fails the pending prompts and ends the work when Claude Code exits", async () => { + const client = nativeClient(); + const error = await client.connect(async (agent) => { + const { response, claude } = await openSession(agent); + claude.send(turnInit()); + claude.send( + assistant("msg_1", [ + { type: "tool_use", id: "toolu_1", name: "Bash", input: { command: "make" } }, + ]), + ); + const answer = agent.request(v2.methods.agent.session.prompt, { + sessionId: response.sessionId, + prompt: PROMPT, + }); + await claude.prompt(0); + claude.end(new Error("Claude Code process exited with code 1")); + const error = await answer.catch((error: unknown) => error); + await vi.waitFor(() => expect(client.states()).toEqual(["running", "idle"])); + return error; + }); + + expect(error).toMatchObject({ code: -32603 }); + // The unfinished tool call fails before the idle. + expect(client.sessionUpdates.slice(-2)).toMatchObject([ + { sessionUpdate: "tool_call_update", toolCallId: "toolu_1", status: "failed" }, + { state: "idle", stopReason: "error" }, + ]); + }); + + it("starts a session whose query ended again on resume", async () => { + const client = nativeClient(); + await client.connect(async (agent) => { + const { response, claude } = await openSession(agent); + claude.end(new Error("Claude Code process exited with code 1")); + await expect( + agent.request(v2.methods.agent.session.prompt, { + sessionId: response.sessionId, + prompt: PROMPT, + }), + ).rejects.toMatchObject({ code: -32002, data: { sessionId: response.sessionId } }); + await agent.request(v2.methods.agent.session.resume, { sessionId: response.sessionId, cwd }); + }); + + expect(sdk.processes).toHaveLength(2); + expect(sdk.processes[1].options.resume).toBe(sdk.processes[0].options.sessionId); + }); + + it("ends the work at the turn's result while background subagents keep Claude Code running", async () => { + const client = nativeClient(); + await client.connect(async (agent) => { + const { response, claude } = await openSession(agent); + const answer = agent.request(v2.methods.agent.session.prompt, { + sessionId: response.sessionId, + prompt: PROMPT, + }); + const prompt = await claude.prompt(0); + // As the bundled CLI sends it: `running` stays until the background + // subagent ends and the turn that Claude Code starts on its own ends. + claude.send(sessionState("running")); + claude.send(lifecycle(prompt, "started")); + claude.send(turnInit()); + await answer; + claude.send(result({ result: "launched" })); + claude.send(lifecycle(prompt, "completed")); + await vi.waitFor(() => expect(client.states()).toEqual(["running", "idle"])); + claude.send(turnInit()); + claude.send(result({ result: "The subagent finished." })); + claude.send(sessionState("idle")); + await vi.waitFor(() => + expect(client.states()).toEqual(["running", "idle", "running", "idle"]), + ); + }); + }); + + it("does not report a later turn as cancelled after a cancel that only ended queued prompts", async () => { + const client = nativeClient(); + await client.connect(async (agent) => { + const { response, claude } = await openSession(agent); + const sessionId = response.sessionId; + const first = agent.request(v2.methods.agent.session.prompt, { sessionId, prompt: PROMPT }); + const queued = await claude.prompt(0); + await agent.notify(v2.methods.agent.session.cancel, { sessionId }); + await vi.waitFor(() => expect(claude.interrupt).toHaveBeenCalled()); + claude.send(lifecycle(queued, "cancelled")); + await expect(first).rejects.toMatchObject({ code: -32800 }); + + const second = agent.request(v2.methods.agent.session.prompt, { sessionId, prompt: PROMPT }); + const prompt = await claude.prompt(1); + claude.send(lifecycle(prompt, "started")); + await second; + claude.send(result()); + await vi.waitFor(() => expect(client.states()).toEqual(["running", "idle"])); + }); + + expect(client.sessionUpdates.at(-1)).toMatchObject({ state: "idle", stopReason: "end_turn" }); + }); + + it("pushes a prompt sent after session/cancel only once the interrupt is done", async () => { + const client = nativeClient(); + await client.connect(async (agent) => { + const { response, claude } = await openSession(agent); + const sessionId = response.sessionId; + let finishInterrupt = () => {}; + claude.interrupt.mockImplementationOnce( + () => new Promise((resolve) => (finishInterrupt = resolve)), + ); + claude.send(turnInit()); + await vi.waitFor(() => expect(client.states()).toEqual(["running"])); + await agent.notify(v2.methods.agent.session.cancel, { sessionId }); + await vi.waitFor(() => expect(claude.interrupt).toHaveBeenCalled()); + // Never answered: the test ends before Claude Code starts it. + agent.request(v2.methods.agent.session.prompt, { sessionId, prompt: PROMPT }).catch(() => {}); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(claude.prompts).toHaveLength(0); + finishInterrupt(); + await claude.prompt(0); + }); + }); + + it("closes active work with its cancelled idle before the response, and nothing after", async () => { + const client = nativeClient(); + let updatesAtResponse = 0; + await client.connect(async (agent) => { + const { response, claude } = await openSession(agent); + const sessionId = response.sessionId; + claude.send(turnInit()); + await vi.waitFor(() => expect(client.states()).toEqual(["running"])); + claude.interrupt.mockImplementationOnce(async () => { + claude.send(result({ subtype: "error_during_execution", is_error: true })); + }); + await agent.request(v2.methods.agent.session.close, { sessionId }); + updatesAtResponse = client.sessionUpdates.length; + claude.send(assistant("msg_late", [{ type: "text", text: "late" }])); + await new Promise((resolve) => setTimeout(resolve, 20)); + }); + + expect(client.sessionUpdates.at(-1)).toMatchObject({ state: "idle", stopReason: "cancelled" }); + expect(client.sessionUpdates).toHaveLength(updatesAtResponse); + }); + + it.each([ + ["session/close", v2.methods.agent.session.close], + ["session/delete", v2.methods.agent.session.delete], + ])("answers %s of a session that does not exist with an empty result", async (_, method) => { + const client = nativeClient(); + const response = await client.connect(async (agent) => { + await openSession(agent); + return agent.request(method, { sessionId: randomUUID() }); + }); + + expect(response).toEqual({}); + }); + + it("rejects a config value whose type does not match the option", async () => { + const client = nativeClient(); + const error = await client.connect(async (agent) => { + const { response } = await openSession(agent); + return agent + .request(v2.methods.agent.session.setConfigOption, { + sessionId: response.sessionId, + configId: "mode", + type: "boolean", + value: true, + } as v2.SetSessionConfigOptionRequest) + .catch((error: unknown) => error); + }); + + expect(error).toMatchObject({ code: -32602 }); + }); + + it("rejects additional directories that are not absolute", async () => { + const client = nativeClient(); + const error = await client.connect(async (agent) => { + await openSession(agent); + return agent + .request(v2.methods.agent.session.new, { cwd, additionalDirectories: ["src"] }) + .catch((error: unknown) => error); + }); + + expect(error).toMatchObject({ code: -32602 }); + }); + + it("replays the stored history, then sends the state, before the resume response", async () => { + vi.mocked(getSessionMessages).mockResolvedValueOnce([ + { + type: "user", + uuid: "u1", + session_id: "s", + parent_tool_use_id: null, + parent_agent_id: null, + message: { role: "user", content: "Fix the build" }, + }, + { + type: "assistant", + uuid: "a1", + session_id: "s", + parent_tool_use_id: null, + parent_agent_id: null, + message: { id: "msg_a", role: "assistant", content: [{ type: "text", text: "Done" }] }, + }, + ]); + const client = nativeClient(); + const sessionId = randomUUID(); + await client.connect(async (agent) => { + await agent.request(v2.methods.agent.initialize, { + protocolVersion: v2.PROTOCOL_VERSION, + info: { name: "native-test-client", version: "1.0.0" }, + capabilities: {}, + }); + await agent.request(v2.methods.agent.session.resume, { + sessionId, + cwd, + replayFrom: { type: "start" }, + }); + }); + + expect(sdk.processes[0].options.resume).toBe(sessionId); + expect(client.sessionUpdates).toEqual([ + { sessionUpdate: "user_message", messageId: "u1", content: [] }, + { + sessionUpdate: "user_message_chunk", + messageId: "u1", + content: { type: "text", text: "Fix the build" }, + }, + { sessionUpdate: "agent_message", messageId: "msg_a", content: [] }, + { + sessionUpdate: "agent_message_chunk", + messageId: "msg_a", + content: { type: "text", text: "Done" }, + }, + { sessionUpdate: "state_update", state: "idle", stopReason: "end_turn", background: [] }, + ]); + }); + + describe("subagents and background work", () => { + it("announces a subagent before its traffic, and reports its runs on its own stream", async () => { + const client = nativeClient(); + const agentId = "a7f0c1"; + const sessionId = await client.connect(async (agent) => { + const { response, claude } = await openSession(agent); + const child = subagent(agentId, "toolu_launch"); + claude.send(turnInit()); + claude.send(child.started()); + claude.send(child.prompt("Find why the test fails")); + claude.send(child.says("It is a race.")); + claude.send(child.ended()); + await vi.waitFor(() => + expect(updatesOf(client.notifications, agentId).at(-1)).toMatchObject({ + sessionUpdate: "state_update", + state: "idle", + }), + ); + return response.sessionId; + }); + + const parent = updatesOf(client.notifications, sessionId).filter( + (update) => update.sessionUpdate === "subagent_update", + ); + expect(parent).toEqual([ + { + sessionUpdate: "subagent_update", + sessionId: agentId, + title: "Investigate the test", + description: "general-purpose", + capabilities: { cancel: {} }, + }, + { + sessionUpdate: "subagent_update", + sessionId: agentId, + state: { state: "running", background: [] }, + }, + { + sessionUpdate: "subagent_update", + sessionId: agentId, + state: { state: "idle", stopReason: "end_turn", background: [] }, + }, + ]); + // The announcement comes before the child's first update. + const announced = client.notifications.findIndex( + (n) => n.update.sessionUpdate === "subagent_update", + ); + const firstChild = client.notifications.findIndex((n) => n.sessionId === agentId); + expect(announced).toBeLessThan(firstChild); + expect( + updatesOf(client.notifications, agentId).map((update) => update.sessionUpdate), + ).toEqual(["state_update", "session_message", "agent_message_chunk", "state_update"]); + expect(updatesOf(client.notifications, agentId)[1]).toMatchObject({ + senderSessionId: sessionId, + recipientSessionId: agentId, + content: [{ type: "text", text: "Find why the test fails" }], + }); + }); + + it("lists a background subagent while it works, after the turn's idle", async () => { + const client = nativeClient(); + const agentId = "a5966d"; + const sessionId = await client.connect(async (agent) => { + const { response, claude } = await openSession(agent); + const child = subagent(agentId, "toolu_bg_agent", { is_backgrounded: true }); + claude.send(turnInit()); + claude.send({ + type: "system", + subtype: "background_tasks_changed", + tasks: [{ task_id: agentId, task_type: "local_agent", description: "sleeper" }], + uuid: randomUUID(), + }); + claude.send(child.started()); + claude.send(result({ result: "launched" })); + // The list changes while the turn runs: the state goes out again with it. + await vi.waitFor(() => expect(client.states()).toEqual(["running", "running", "idle"])); + claude.send(child.ended()); + await vi.waitFor(() => + expect(client.states()).toEqual(["running", "running", "idle", "idle"]), + ); + return response.sessionId; + }); + + const states = updatesOf(client.notifications, sessionId).filter( + (update) => update.sessionUpdate === "state_update", + ); + // The turn ends at its result, with the subagent still working. + expect(states[2]).toMatchObject({ + state: "idle", + stopReason: "end_turn", + background: [{ type: "subagent", sessionId: agentId }], + }); + // Its end drops it: a repeated idle without a stop reason, after the child's own idle. + expect(states[3]).toEqual({ sessionUpdate: "state_update", state: "idle", background: [] }); + const childIdle = client.notifications.findIndex( + (n) => + n.sessionId === agentId && + n.update.sessionUpdate === "state_update" && + n.update.state === "idle", + ); + expect(childIdle).toBeLessThan( + client.notifications.lastIndexOf(client.notifications.find((n) => n.update === states[3])!), + ); + }); + + it("announces a nested subagent on its parent subagent's stream", async () => { + const client = nativeClient(); + await client.connect(async (agent) => { + const { claude } = await openSession(agent); + claude.send(turnInit()); + claude.send(subagent("outer", "toolu_outer").started()); + claude.send(subagent("inner", "toolu_inner", { parent_task_id: "outer" }).started()); + await vi.waitFor(() => + expect(updatesOf(client.notifications, "outer")).toContainEqual( + expect.objectContaining({ sessionUpdate: "subagent_update", sessionId: "inner" }), + ), + ); + }); + }); + + it("asks a subagent's permission on its session, and blocks the work that waits on it", async () => { + let answer = (_: v2.RequestPermissionResponse) => {}; + const client = nativeClient({ + answerPermission: () => new Promise((resolve) => (answer = resolve)), + }); + await client.connect(async (agent) => { + const { claude } = await openSession(agent); + claude.send(turnInit()); + claude.send(subagent("child", "toolu_launch").started()); + await vi.waitFor(() => expect(client.states()).toEqual(["running"])); + const decision = claude.options.canUseTool!( + "Bash", + { command: "rm -rf build" }, + { + signal: new AbortController().signal, + toolUseID: "toolu_rm", + requestId: "r1", + suggestions: [], + agentID: "child", + }, + ); + await vi.waitFor(() => expect(client.permissionRequests).toHaveLength(1)); + expect(client.permissionRequests[0].sessionId).toBe("child"); + // The parent's turn waits on the foreground subagent, which waits on the user. + await vi.waitFor(() => expect(client.states()).toEqual(["running", "requires_action"])); + expect(updatesOf(client.notifications, "child").at(-1)).toMatchObject({ + state: "requires_action", + }); + answer({ + outcome: { + outcome: "selected", + optionId: client.permissionRequests[0].options[0].optionId, + }, + }); + await decision; + await vi.waitFor(() => + expect(client.states()).toEqual(["running", "requires_action", "running"]), + ); + }); + }); + + it("stops a subagent's run on session/cancel of its session, and leaves the parent's work alone", async () => { + const client = nativeClient(); + await client.connect(async (agent) => { + const { claude } = await openSession(agent); + claude.send(turnInit()); + claude.send(subagent("child", "toolu_launch", { is_backgrounded: true }).started()); + await vi.waitFor(() => + expect(updatesOf(client.notifications, "child")).toContainEqual( + expect.objectContaining({ state: "running" }), + ), + ); + await agent.notify(v2.methods.agent.session.cancel, { sessionId: "child" }); + await vi.waitFor(() => expect(claude.stopTask).toHaveBeenCalledWith("child")); + expect(claude.interrupt).not.toHaveBeenCalled(); + claude.send(subagent("child", "toolu_launch").ended("stopped")); + await vi.waitFor(() => + expect(updatesOf(client.notifications, "child").at(-1)).toMatchObject({ + state: "idle", + stopReason: "cancelled", + }), + ); + }); + }); + + it.each([ + ["session/prompt", v2.methods.agent.session.prompt, { prompt: PROMPT }], + ["session/close", v2.methods.agent.session.close, {}], + ])("rejects %s on a subagent's session", async (_, method, params) => { + const client = nativeClient(); + const error = await client.connect(async (agent) => { + const { claude } = await openSession(agent); + claude.send(turnInit()); + claude.send(subagent("child", "toolu_launch").started()); + await vi.waitFor(() => + expect(client.notifications.some((n) => n.sessionId === "child")).toBe(true), + ); + return agent + .request( + method as typeof v2.methods.agent.session.close, + { + sessionId: "child", + ...params, + } as v2.CloseSessionRequest, + ) + .catch((error: unknown) => error); + }); + + expect(error).toMatchObject({ code: -32602 }); + }); + + it("keeps a background command's terminal running and listed until its task ends", async () => { + const client = nativeClient(); + const sessionId = await client.connect(async (agent) => { + const { response, claude } = await openSession(agent); + claude.send(turnInit()); + claude.send( + assistant("msg_bash", [ + { + type: "tool_use", + id: "toolu_bg", + name: "Bash", + input: { command: "make test", run_in_background: true }, + }, + ]), + ); + claude.send({ + type: "system", + subtype: "task_started", + task_id: "bg1", + task_type: "local_bash", + description: "make test", + tool_use_id: "toolu_bg", + is_backgrounded: true, + uuid: randomUUID(), + }); + claude.send({ + type: "system", + subtype: "background_tasks_changed", + tasks: [{ task_id: "bg1", task_type: "local_bash", description: "make test" }], + uuid: randomUUID(), + }); + claude.send({ + type: "user", + message: { + role: "user", + content: [ + { + type: "tool_result", + tool_use_id: "toolu_bg", + content: "Command running in background with ID: bg1.", + }, + ], + }, + tool_use_result: { stdout: "", stderr: "", interrupted: false, backgroundTaskId: "bg1" }, + parent_tool_use_id: null, + uuid: randomUUID(), + }); + claude.send(result()); + await vi.waitFor(() => expect(client.states()).toEqual(["running", "running", "idle"])); + claude.send({ + type: "system", + subtype: "task_notification", + task_id: "bg1", + tool_use_id: "toolu_bg", + status: "completed", + output_file: "", + summary: "", + uuid: randomUUID(), + }); + await vi.waitFor(() => + expect(client.states()).toEqual(["running", "running", "idle", "idle"]), + ); + return response.sessionId; + }); + + const trace = updatesOf(client.notifications, sessionId).flatMap((update) => + update.sessionUpdate === "terminal_update" + ? [update.exitStatus ? "exit" : "terminal"] + : update.sessionUpdate === "state_update" + ? [`${update.state} ${JSON.stringify(update.background)}`] + : [], + ); + expect(trace.filter((entry) => entry !== "terminal")).toEqual([ + "running []", + 'running [{"terminalId":"toolu_bg","type":"terminal"}]', + 'idle [{"terminalId":"toolu_bg","type":"terminal"}]', + "exit", + "idle []", + ]); + }); + }); + + it("reads which v2 core to serve from CLAUDE_AGENT_ACP_V2_CORE", () => { + expect(v2CoreFromEnv(undefined)).toBe("bridge"); + expect(v2CoreFromEnv("")).toBe("bridge"); + expect(v2CoreFromEnv("native")).toBe("native"); + expect(() => v2CoreFromEnv("v2")).toThrow(/CLAUDE_AGENT_ACP_V2_CORE/); + }); +}); diff --git a/src/v2-native/agent.ts b/src/v2-native/agent.ts new file mode 100644 index 00000000..3fa8f93f --- /dev/null +++ b/src/v2-native/agent.ts @@ -0,0 +1,507 @@ +/** + * The native ACP v2 core: serves ACP v2 straight from Claude Code, without + * `ClaudeAcpAgent`. + * + * The bridge in `src/v2/` serves v2 by converting each request to v1 and + * running it through the v1 core, which holds turns open, matches echoes, + * and keeps the v1 and AIR extensions. This core serves only v2, so it keeps + * none of that: each session mirrors its Claude Code query (see + * `session.ts`). It shares the protocol-neutral pieces with v1: the SDK + * message mapping, tool call rendering, permission options, and the mode + * catalog. What it does not serve yet is listed in `docs/v2-native-core.md`. + * + * Opt in with `CLAUDE_AGENT_ACP_V2_CORE=native` (see `serve.ts`). + */ +import { execFile } from "node:child_process"; +import { randomUUID } from "node:crypto"; +import * as fs from "node:fs/promises"; +import * as path from "node:path"; +import { promisify } from "node:util"; +import { RequestError } from "@agentclientprotocol/sdk/unstable"; +import * as v2 from "@agentclientprotocol/sdk/experimental/v2/unstable"; +import { + deleteSession, + getSessionMessages, + listSessions, + query, + type Options, + type SDKUserMessage, +} from "@anthropic-ai/claude-agent-sdk"; +import packageJson from "../../package.json" with { type: "json" }; +import type { Logger } from "../acp-agent.js"; +import { terminalAuthMethods } from "../auth-methods.js"; +import { claudeCliPath } from "../claude-cli.js"; +import { clientSystemPrompt, sdkSystemPrompt } from "../client-system-prompt.js"; +import { sdkMcpServers } from "../mcp-servers.js"; +import { ALLOW_BYPASS, autoModeDisabled } from "../permissions/modes.js"; +import { buildAvailableModes, resolveInitialPermissionMode } from "../session-mode.js"; +import { sanitizeTitle } from "../session-titles.js"; +import { SettingsManager } from "../settings.js"; +import { STARTUP_FAILURE_RESULTS_ENV, startupFailureError } from "../startup-failure.js"; +import { createPostToolUseHook } from "../tools.js"; +import { Pushable } from "../utils.js"; +import { v2AuthMethod, V2_SESSION_CAPABILITIES } from "../v2/initialize.js"; +import { v1NewSessionRequest, v2AvailableCommands } from "../v2/session.js"; +import { V2UpdateTranslator } from "../v2/update-translator.js"; +import { SessionConfig } from "./config.js"; +import { canUseTool } from "./permissions.js"; +import { NativeSession, type SessionConnection } from "./session.js"; +import { restrictedChild } from "./tasks.js"; + +const execFileAsync = promisify(execFile); + +/** The sessions per `session/list` page. */ +const SESSION_LIST_PAGE_SIZE = 1000; + +/** What the owner of the process holds of the agent: its shutdown. */ +export interface AgentHandle { + dispose(): Promise; +} + +/** The native ACP v2 surface, for one connection. */ +export function nativeV2AgentApp( + logger: Logger | undefined, + onAgent: (agent: AgentHandle) => void, +): v2.AgentApp { + let agent!: NativeV2Agent; + return ( + v2 + .agent({ name: "claude-code-acp" }) + .onConnect((connection) => { + agent = new NativeV2Agent(connection.client, logger ?? console); + onAgent(agent); + }) + .onRequest(v2.methods.agent.initialize, ({ params }) => agent.initialize(params)) + .onRequest(v2.methods.agent.auth.login, ({ params }) => { + // Every method this core advertises is a terminal login, which the client runs. + throw RequestError.invalidParams( + { methodId: params.methodId }, + `${params.methodId} is a terminal login: run it in a terminal, then retry the request`, + ); + }) + .onRequest(v2.methods.agent.auth.logout, () => agent.logout()) + .onRequest(v2.methods.agent.session.new, ({ params }) => agent.newSession(params)) + .onRequest(v2.methods.agent.session.resume, ({ params }) => agent.resumeSession(params)) + .onRequest(v2.methods.agent.session.list, ({ params }) => agent.listSessions(params)) + .onRequest(v2.methods.agent.session.close, ({ params }) => agent.closeSession(params)) + .onRequest(v2.methods.agent.session.delete, ({ params }) => agent.deleteSession(params)) + .onRequest(v2.methods.agent.session.setConfigOption, ({ params }) => + agent.setConfigOption(params), + ) + .onRequest(v2.methods.agent.session.prompt, ({ params }) => + agent.session(params.sessionId, "prompt").prompt(params), + ) + .onRequest(v2.methods.agent.terminal.cancel, ({ params }) => + agent.cancelItem(params.sessionId, { terminalId: params.terminalId }), + ) + .onRequest(v2.methods.agent.toolCall.cancel, ({ params }) => + agent.cancelItem(params.sessionId, { toolCallId: params.toolCallId }), + ) + // `session/cancel` of a session that is not active is ignored. A + // subagent's session advertises `cancel`: it stops the subagent's run. + .onNotification(v2.methods.agent.session.cancel, ({ params }) => + agent.cancel(params.sessionId), + ) + ); +} + +/** The capabilities of the native core: the bridge's, without fork. */ +const NATIVE_SESSION_CAPABILITIES: v2.SessionCapabilities = Object.fromEntries( + Object.entries(V2_SESSION_CAPABILITIES).filter(([capability]) => capability !== "fork"), +); + +class NativeV2Agent implements AgentHandle, SessionConnection { + readonly sessions = new Map(); + readonly translator = new V2UpdateTranslator(); + + constructor( + private readonly ctx: v2.AgentContext, + readonly logger: Logger, + ) {} + + // --- SessionConnection --------------------------------------------------- + + send(notification: v2.UpdateSessionNotification): void { + this.ctx.notify(v2.methods.client.session.update, notification).catch((error) => { + this.logger.error(`Failed to send a ${notification.update.sessionUpdate} update:`, error); + }); + } + + requestPermission( + request: v2.RequestPermissionRequest, + signal: AbortSignal, + ): Promise { + // Aborting `signal` sends `$/cancel_request`, and stops waiting for the answer. + return this.ctx.request(v2.methods.client.session.requestPermission, request, { + cancellationSignal: signal, + stopWaitingOnCancel: true, + }); + } + + ended(sessionId: string): void { + // A later `session/resume` starts the session again from its transcript. + this.sessions.delete(sessionId); + this.translator.forget(sessionId); + } + + // --- Requests -------------------------------------------------------------- + + initialize(request: v2.InitializeRequest): v2.InitializeResponse { + const capabilities = request.capabilities; + return { + protocolVersion: v2.PROTOCOL_VERSION, + info: { name: packageJson.name, title: "Claude Agent", version: packageJson.version }, + capabilities: { session: NATIVE_SESSION_CAPABILITIES }, + // v2 advertises terminal logins only to a client with `auth.terminal`. + authMethods: + capabilities?.auth?.terminal != null + ? terminalAuthMethods({ terminal: true, metaTerminal: false }).map(v2AuthMethod) + : [], + }; + } + + async logout(): Promise { + // The credentials live in the CLI's store, which only the CLI can clear. + try { + await execFileAsync(await claudeCliPath(), ["auth", "logout"]); + } catch (error) { + throw RequestError.internalError( + undefined, + `claude auth logout failed: ${error instanceof Error ? error.message : String(error)}`, + ); + } + return {}; + } + + async newSession(params: v2.NewSessionRequest): Promise { + const sessionId = randomUUID(); + const session = await this.startSession(sessionId, params, undefined); + return { sessionId, ...(await this.setupFields(session)) }; + } + + /** + * Resumes a stored session, or attaches to a live one. With `replayFrom: + * { type: "start" }` the stored history replays first. Either way, the + * state snapshot goes out after any replay and before the response. + */ + async resumeSession(params: v2.ResumeSessionRequest): Promise { + const { sessionId, replayFrom } = params; + if (replayFrom != null && replayFrom.type !== "start") { + throw RequestError.invalidParams( + { replayFrom }, + `Replaying from a ${replayFrom.type} cursor is not supported`, + ); + } + if (this.ownerOfChild(sessionId)) throw restrictedChild(sessionId, "resume"); + let session = this.sessions.get(sessionId); + if (session) { + // Resuming the active session synchronizes it again. Its work goes on, + // and the request's MCP servers replace the session's. + const request = await validatedSetup(params); + if (request.cwd !== session.cwd) { + throw RequestError.invalidParams( + { cwd: request.cwd }, + `Session ${sessionId} works in ${session.cwd}: resume it with that \`cwd\``, + ); + } + if (!sameDirectories(request.additionalDirectories ?? [], session.additionalDirectories)) { + throw RequestError.invalidParams( + { additionalDirectories: request.additionalDirectories }, + `Session ${sessionId} is active with other additional directories: close it, then resume it with these`, + ); + } + await session.setMcpServers(sdkMcpServers(request.mcpServers)); + } else { + session = await this.startSession(sessionId, params, sessionId); + } + if (replayFrom != null) { + session.output.replay(await getSessionMessages(sessionId, { dir: session.cwd })); + } + for (const notification of session.resumeSnapshot()) this.send(notification); + return this.setupFields(session); + } + + async listSessions(params: v2.ListSessionsRequest): Promise { + if (params.cwd != null && !path.isAbsolute(params.cwd)) { + throw RequestError.invalidParams({ cwd: params.cwd }, "`cwd` must be an absolute path"); + } + const offset = listOffset(params.cursor); + // One more than a page tells whether a next page exists. + const stored = await listSessions({ + dir: params.cwd ?? undefined, + includeWorktrees: false, + limit: SESSION_LIST_PAGE_SIZE + 1, + offset, + }); + const sessions = stored.slice(0, SESSION_LIST_PAGE_SIZE).flatMap((session) => + session.cwd + ? [ + { + sessionId: session.sessionId, + cwd: session.cwd, + title: sanitizeTitle(session.summary), + updatedAt: new Date(session.lastModified).toISOString(), + }, + ] + : [], + ); + return stored.length > SESSION_LIST_PAGE_SIZE + ? { sessions, nextCursor: `offset:${offset + SESSION_LIST_PAGE_SIZE}` } + : { sessions }; + } + + /** Closing is idempotent: a session that is not active closes at once. */ + async closeSession({ sessionId }: v2.CloseSessionRequest): Promise { + if (this.ownerOfChild(sessionId)) throw restrictedChild(sessionId, "close"); + const session = this.sessions.get(sessionId); + if (!session) return {}; + await session.close(); + if (this.sessions.get(sessionId) === session) this.sessions.delete(sessionId); + this.translator.forget(sessionId); + return {}; + } + + /** Deleting a session that does not exist succeeds, as v2 asks. */ + async deleteSession({ sessionId }: v2.DeleteSessionRequest): Promise { + if (this.ownerOfChild(sessionId)) throw restrictedChild(sessionId, "delete"); + const live = this.sessions.get(sessionId); + if (live) await this.closeSession({ sessionId }); + try { + await deleteSession(sessionId, live ? { dir: live.cwd } : undefined); + } catch (error) { + // A session without a transcript, such as one never prompted, has nothing to delete. + if (error instanceof Error && /not found/i.test(error.message)) return {}; + throw error; + } + return {}; + } + + async setConfigOption( + params: v2.SetSessionConfigOptionRequest, + ): Promise { + const configOptions = await this.session(params.sessionId, "configure").setConfigOption( + params.configId, + (params as { type?: string }).type, + params.value, + ); + return { configOptions }; + } + + /** + * The active session `sessionId`, for a request that `method` names. A + * subagent's session takes no such request: the client can only watch it + * and cancel its run. + */ + session(sessionId: string, method: string): NativeSession { + const session = this.sessions.get(sessionId); + if (session) return session; + if (this.ownerOfChild(sessionId)) throw restrictedChild(sessionId, method); + throw RequestError.sessionNotFound(sessionId); + } + + async cancel(sessionId: string): Promise { + const session = this.sessions.get(sessionId); + if (session) return session.cancel(); + await this.ownerOfChild(sessionId)?.tasks.cancelChild(sessionId); + } + + /** `terminal/cancel` and `tool_call/cancel`: stops a listed item of a session or a child. */ + async cancelItem( + sessionId: string, + target: { terminalId: string } | { toolCallId: string }, + ): Promise> { + const root = this.sessions.get(sessionId) ?? this.ownerOfChild(sessionId); + if (!root) throw RequestError.sessionNotFound(sessionId); + if (!(await root.tasks.cancelItem(sessionId, target))) { + throw "terminalId" in target + ? RequestError.invalidParams( + { sessionId, terminalId: target.terminalId }, + `Terminal ${target.terminalId} is not a command running in the background, so it cannot be cancelled.`, + ) + : RequestError.invalidParams( + { sessionId, toolCallId: target.toolCallId }, + `Tool call ${target.toolCallId} is not running in the background, so it cannot be cancelled.`, + ); + } + return {}; + } + + /** The root session that `sessionId` is a subagent session of. */ + private ownerOfChild(sessionId: string): NativeSession | undefined { + return [...this.sessions.values()].find((session) => session.tasks.hasChild(sessionId)); + } + + async dispose(): Promise { + const sessions = [...this.sessions.values()]; + this.sessions.clear(); + await Promise.all(sessions.map((session) => session.close())); + } + + // --- Session setup ----------------------------------------------------------- + + /** The config options and commands of a setup response. */ + private async setupFields(session: NativeSession): Promise<{ + configOptions: v2.SessionConfigOption[]; + availableCommands?: v2.AvailableCommand[]; + }> { + const commands = await session.commands().catch((error) => { + // The session works without its command list; the response goes without it. + this.logger.error(`Session ${session.sessionId}: failed to read its commands`, error); + return []; + }); + return { + configOptions: session.config.options(), + ...(commands.length > 0 ? { availableCommands: v2AvailableCommands(commands) } : {}), + }; + } + + /** Starts the query of a session: a new one, or `resume` of a stored one. */ + private async startSession( + sessionId: string, + params: v2.NewSessionRequest | v2.ResumeSessionRequest, + resume: string | undefined, + ): Promise { + const request = await validatedSetup(params); + const settings = new SettingsManager(request.cwd, { logger: this.logger }); + await settings.initialize(); + const allowBypass = + ALLOW_BYPASS && + settings.getSettings().permissions?.disableBypassPermissionsMode !== "disable"; + const allowAuto = !autoModeDisabled(settings.getSettings()); + const { mode } = resolveInitialPermissionMode( + { defaultMode: settings.getSettings().permissions?.defaultMode }, + this.logger, + { allowBypass, allowAuto }, + ); + settings.dispose(); + + const clientPrompt = clientSystemPrompt(request.systemPrompt); + const input = new Pushable(); + const session = new NativeSession( + sessionId, + request.cwd, + request.additionalDirectories ?? [], + this, + input, + ); + const options: Options = { + systemPrompt: clientPrompt + ? sdkSystemPrompt(clientPrompt, undefined) + : { type: "preset", preset: "claude_code" }, + settingSources: ["user", "project", "local"], + cwd: request.cwd, + additionalDirectories: request.additionalDirectories ?? [], + includePartialMessages: true, + // A subagent's text, for its own session's stream (see `tasks.ts`). + forwardSubagentText: true, + // Claude Code's interrupt then spares background tasks, which the + // client stops one at a time: `session/cancel` must leave listed work + // running. + perTaskStopAffordance: true, + mcpServers: sdkMcpServers(request.mcpServers), + permissionMode: mode, + allowDangerouslySkipPermissions: allowBypass, + canUseTool: canUseTool(session), + pathToClaudeCodeExecutable: await claudeCliPath(), + // Echoes each prompt that Claude Code takes in (see `NativeSession`). + extraArgs: { "replay-user-messages": "" }, + // AskUserQuestion needs a form elicitation, which this core does not send. + disallowedTools: ["AskUserQuestion"], + tools: { type: "preset", preset: "claude_code" }, + hooks: { + SubagentStart: [ + { + hooks: [ + async (input) => { + // Its `cwd` is the subagent's, such as its worktree. + if (input.hook_event_name === "SubagentStart") { + session.tasks.subagentStarted(input.agent_id, input.cwd, input.agent_type); + } + return { continue: true }; + }, + ], + }, + ], + PostToolUse: [ + { + hooks: [ + createPostToolUseHook({ onEnterPlanMode: async () => session.modeChanged("plan") }), + ], + }, + ], + }, + env: { + ...process.env, + // `session_state_changed`, which is the session's state. + CLAUDE_CODE_EMIT_SESSION_STATE_EVENTS: "1", + ...STARTUP_FAILURE_RESULTS_ENV, + }, + ...(resume !== undefined ? { resume } : { sessionId }), + }; + const q = query({ prompt: input, options }); + let initialization; + try { + initialization = await q.initializationResult(); + } catch (error) { + q.close(); + if ( + resume !== undefined && + error instanceof Error && + error.message.includes("No conversation found with session ID") + ) { + throw RequestError.sessionNotFound(sessionId); + } + throw startupFailureError(error) ?? error; + } + const models = initialization.models; + const currentModel = + models.find((model) => model.value === "default")?.value ?? models[0]?.value ?? "default"; + const availableModes = buildAvailableModes({ allowBypass, allowAuto }); + session.start( + q, + new SessionConfig(q, { currentModeId: mode, availableModes }, models, currentModel), + ); + this.sessions.set(sessionId, session); + return session; + } +} + +/** + * The setup request in v1 form, once it is valid: the MCP transports and the + * system prompt as the bridge checks them, an absolute `cwd` that is a + * directory, and absolute additional directories. + */ +async function validatedSetup(params: v2.NewSessionRequest | v2.ResumeSessionRequest) { + const request = v1NewSessionRequest({ ...params, mcpServers: params.mcpServers ?? [] }); + const { cwd } = request; + if (!path.isAbsolute(cwd)) { + throw RequestError.invalidParams({ cwd }, `\`cwd\` must be an absolute path, not ${cwd}`); + } + const stat = await fs.stat(cwd).catch(() => undefined); + if (!stat?.isDirectory()) { + throw RequestError.invalidParams({ cwd }, `\`cwd\` is not a directory: ${cwd}`); + } + for (const directory of request.additionalDirectories ?? []) { + if (!path.isAbsolute(directory)) { + throw RequestError.invalidParams( + { additionalDirectories: request.additionalDirectories }, + `Additional directories must be absolute paths, not ${directory}`, + ); + } + } + return request; +} + +function sameDirectories(left: readonly string[], right: readonly string[]): boolean { + const normalize = (directories: readonly string[]) => + [...new Set(directories.map((directory) => path.resolve(directory)))].sort().join("\n"); + return normalize(left) === normalize(right); +} + +function listOffset(cursor: string | null | undefined): number { + if (cursor == null) return 0; + const match = /^offset:(\d+)$/.exec(cursor); + if (!match) + throw RequestError.invalidParams({ cursor }, `Unknown session/list cursor: ${cursor}`); + return Number(match[1]); +} diff --git a/src/v2-native/config.ts b/src/v2-native/config.ts new file mode 100644 index 00000000..172b6095 --- /dev/null +++ b/src/v2-native/config.ts @@ -0,0 +1,87 @@ +/** + * The config options of a native v2 session: its permission mode and its + * model. Claude Code owns both. The session sets each on the query when the + * client picks a value, and follows the changes it learns of (an approved + * plan's mode). + */ +import { RequestError, type SessionModeState } from "@agentclientprotocol/sdk/unstable"; +import type * as v2 from "@agentclientprotocol/sdk/experimental/v2/unstable"; +import type { ModelInfo, PermissionMode, Query } from "@anthropic-ai/claude-agent-sdk"; +import { MODEL_CONFIG_ID } from "../session-model.js"; +import { MODE_CONFIG_ID, SessionModeManager } from "../session-mode.js"; +import { v2ConfigOptions } from "../v2/session.js"; + +export class SessionConfig { + constructor( + private readonly query: Pick, + private modes: SessionModeState, + private readonly models: ModelInfo[], + private currentModel: string, + ) {} + + options(): v2.SessionConfigOption[] { + return v2ConfigOptions([ + SessionModeManager.configOption(this.modes), + ...(this.models.length > 0 + ? [ + { + id: MODEL_CONFIG_ID, + name: "Model", + category: "model" as const, + type: "select" as const, + currentValue: this.currentModel, + options: this.models.map((model) => ({ + value: model.value, + name: model.displayName, + ...(model.description ? { description: model.description } : {}), + })), + }, + ] + : []), + ]); + } + + availableModeIds(): string[] { + return this.modes.availableModes.map((mode) => mode.id); + } + + /** + * Sets `value` on the query, and records it once Claude Code took it. Both + * options are selects, which take an `id` value. + */ + async set(configId: string, type: string | undefined, value: unknown): Promise { + if (type !== "id" || typeof value !== "string") { + throw RequestError.invalidParams( + { configId, type }, + `${configId} is a select option: set it with an \`id\` value`, + ); + } + switch (configId) { + case MODE_CONFIG_ID: { + if (!this.availableModeIds().includes(value)) { + throw RequestError.invalidParams({ value }, `Unknown mode: ${value}`); + } + await this.query.setPermissionMode(value as PermissionMode); + this.modes = { ...this.modes, currentModeId: value }; + return; + } + case MODEL_CONFIG_ID: { + if (!this.models.some((model) => model.value === value)) { + throw RequestError.invalidParams({ value }, `Unknown model: ${value}`); + } + await this.query.setModel(value); + this.currentModel = value; + return; + } + default: + throw RequestError.invalidParams({ configId }, `Unknown config option: ${configId}`); + } + } + + /** Claude Code switched the mode itself. Returns whether the option changed. */ + modeChanged(mode: PermissionMode): boolean { + if (this.modes.currentModeId === mode || !this.availableModeIds().includes(mode)) return false; + this.modes = { ...this.modes, currentModeId: mode }; + return true; + } +} diff --git a/src/v2-native/permissions.ts b/src/v2-native/permissions.ts new file mode 100644 index 00000000..e83474ee --- /dev/null +++ b/src/v2-native/permissions.ts @@ -0,0 +1,123 @@ +/** + * Claude Code's permission checks (`canUseTool`), asked as ACP v2 permission + * requests. + * + * The request is built and its answer read by the same helpers as on v1 + * (`permissions/*`), so a v2 client gets the same options and the same + * effects of each. + */ +import type { CanUseTool, PermissionMode } from "@anthropic-ai/claude-agent-sdk"; +import { previewPatchContent } from "../diff.js"; +import { normalizeDurablePermissionChangeSet } from "../permissions/normalization.js"; +import { buildClaudePermissionOptions } from "../permissions/options.js"; +import { buildClaudePermissionPresentation } from "../permissions/presentation.js"; +import { decodeClaudePermissionResponse } from "../permissions/response.js"; +import { ClientCapabilities } from "../tool-calls/client-capabilities.js"; +import { v1PermissionResponse, v2PermissionRequest } from "../v2/permission.js"; +import type { RequestTarget } from "./tasks.js"; + +const V2_CAPABILITIES = ClientCapabilities.from(undefined, { v2: true }); + +/** What a permission check needs of its root session. */ +export interface PermissionHost { + /** The ids of the modes that the session offers. */ + availableModes(): string[]; + /** + * The session that the request goes to: the root, or the child session of + * the subagent `agentId`. It counts the request as open while it is + * (`requires_action`). + */ + target(agentId: string | undefined): Promise; + /** The user picked a mode in the answer, such as ExitPlanMode's "auto-accept edits". */ + modeChanged(mode: PermissionMode): void; +} + +export function canUseTool(host: PermissionHost): CanUseTool { + return async ( + toolName, + toolInput, + { + signal, + suggestions, + toolUseID, + matchedAskRule, + blockedPath, + decisionReason, + title, + displayName, + description, + defaultToNo, + suppressAlwaysAllowRule, + agentID, + }, + ) => { + const target = await host.target(agentID); + // No persistent "always allow" when the user's own ask rule forced the + // prompt, or when Claude Code says the rule it would write grants more + // than this ask. + const noPersistentRule = matchedAskRule !== undefined || suppressAlwaysAllowRule === true; + const durableChangeSet = normalizeDurablePermissionChangeSet(suggestions, noPersistentRule); + // A v2 diff cannot hold an Edit's snippet: the request shows the exact patch. + const previewContent = await previewPatchContent(toolName, toolInput, target.cwd, "v2"); + const presentation = buildClaudePermissionPresentation({ + toolName, + input: toolInput, + toolUseID, + cwd: target.cwd, + capabilities: V2_CAPABILITIES, + previewContent, + blockedPath, + title, + displayName, + description, + decisionReason, + defaultToNo, + }); + const options = buildClaudePermissionOptions({ + toolName, + displayName, + input: toolInput, + cwd: target.cwd, + durableChangeSet, + allowPersistentOptions: !noPersistentRule, + defaultToNo, + availableModes: host.availableModes(), + // Clearing the context after a plan needs a turn to continue in, which + // this core does not start on its own. + allowContextReset: false, + }); + const response = v1PermissionResponse( + await target.requestPermission( + v2PermissionRequest({ ...presentation, options, sessionId: target.sessionId }), + signal, + ), + ); + if (signal.aborted) throw new Error("Tool use aborted"); + // In v2, `cancelled` is also the user dismissing the prompt. Without a + // `session/cancel`, that is a refusal, and the turn goes on. + if (response.outcome.outcome === "cancelled") { + if (target.cancelling()) throw new Error("Tool use aborted"); + return { + behavior: "deny", + message: "User refused permission to run tool", + toolUseID, + decisionClassification: "user_reject", + }; + } + const { permissionResult } = decodeClaudePermissionResponse( + response, + toolName, + toolInput, + toolUseID, + options, + durableChangeSet, + ); + if (permissionResult.behavior === "allow") { + const modeUpdate = permissionResult.updatedPermissions?.find( + (update) => update.type === "setMode" && update.destination === "session", + ); + if (modeUpdate?.type === "setMode") host.modeChanged(modeUpdate.mode); + } + return permissionResult; + }; +} diff --git a/src/v2-native/session.ts b/src/v2-native/session.ts new file mode 100644 index 00000000..62624c05 --- /dev/null +++ b/src/v2-native/session.ts @@ -0,0 +1,676 @@ +/** + * One ACP v2 session, served straight from its Claude Code query. + * + * ACP v2 and Claude Code describe a session the same way: prompts go into a + * queue, Claude Code works through them, and the session reports whether it + * is working. So this session keeps little of its own: + * + * - A prompt is pushed to Claude Code at once, with a uuid. Its response is + * the prompt's insertion: the `command_lifecycle` frame `started` for that + * uuid, or the prompt's echo, whichever comes first. `cancelled`, + * `discarded` or `refused` fails the prompt. + * - The foreground work is Claude Code's turn: it starts with a prompt's + * `started` frame or the turn's `system/init` (a turn that Claude Code + * starts on its own, such as after a background task ends), and ends with + * the turn's `result`, whose stop reason and usage the idle carries. + * Claude Code's own `session_state_changed` stays `running` while + * background subagents work, which v2 lists as background work instead + * (`background`), so it only ends a turn that ended without a result. + * - `requires_action` is this session's own: a turn is open, and a + * permission request of this session is open, or of a subagent that the + * turn waits on. + * - Subagents are child sessions, and background work is listed on every + * state (see {@link SessionTasks}). + * - `session/cancel` is Claude Code's interrupt with `cancelQueued`, which + * also ends the prompts that are not inserted yet, as v2 asks: each gets a + * `cancelled` lifecycle frame. With `perTaskStopAffordance`, the interrupt + * spares background tasks. + * + * Output goes out as it comes, whatever prompt it belongs to (see + * {@link SessionOutput}). + */ +import { randomUUID } from "node:crypto"; +import { + RequestError, + type AvailableCommand, + type PromptRequest, +} from "@agentclientprotocol/sdk/unstable"; +import type * as v2 from "@agentclientprotocol/sdk/experimental/v2/unstable"; +import type { + PermissionMode, + Query, + SDKMessage, + SDKResultMessage, + SDKUserMessage, +} from "@anthropic-ai/claude-agent-sdk"; +import { isLoginRequiredText, promptToClaude, type Logger } from "../acp-agent.js"; +import { Pushable } from "../utils.js"; +import { v1PromptRequest } from "../v2/prompt.js"; +import { V2Background } from "../v2/background.js"; +import type { V2UpdateTranslator } from "../v2/update-translator.js"; +import type { SessionConfig } from "./config.js"; +import { SessionOutput } from "./stream.js"; +import { SessionTasks, type RequestTarget } from "./tasks.js"; + +/** What a session needs of its connection. */ +export interface SessionConnection { + readonly logger: Logger; + readonly translator: V2UpdateTranslator; + /** Sends an update of the session. Updates go out in the order of the calls. */ + send(notification: v2.UpdateSessionNotification): void; + requestPermission( + request: v2.RequestPermissionRequest, + signal: AbortSignal, + ): Promise; + /** The session's query ended on its own: the session is no longer active. */ + ended(sessionId: string): void; +} + +type PendingPrompt = { + prompt: v2.ContentBlock[]; + /** Whether the prompt went to Claude Code (see {@link NativeSession.prompt}). */ + pushed: boolean; + resolve: (response: v2.PromptResponse) => void; + reject: (error: unknown) => void; +}; + +type ForegroundState = "idle" | "running" | "requires_action"; + +/** The `command_lifecycle` frame of a uuid-stamped prompt. It is not part of the SDK's types. */ +type CommandLifecycleFrame = { type: "command_lifecycle"; command_uuid: string; state: string }; + +/** How long `session/close` waits for the cancelled work to end before it ends the query. */ +const CLOSE_TIMEOUT_MS = 5000; + +export class NativeSession implements RequestTarget { + /** The prompts not inserted yet, by uuid. */ + private readonly pending = new Map(); + /** Whether a turn of Claude Code is open: the session's foreground work. */ + private foreground = false; + /** The prompt whose `started` frame came last in the open turn. */ + private turnCommand: string | undefined; + /** The state the client was told last. */ + private reportedState: ForegroundState = "idle"; + private openRequests = 0; + /** The open permission requests, aborted by `session/cancel`. */ + private readonly requestAborts = new Set(); + /** Whether `session/cancel` stops the open turn: its idle reports `cancelled`. */ + private cancelledWork = false; + /** + * The pushed prompts that a `session/cancel` covered, which Claude Code had + * not reported on yet. Its interrupt ends them, or the turn they start. + */ + private readonly cancelCovered = new Set(); + /** The interrupt of the last `session/cancel`, while it runs. */ + private interrupting: Promise | undefined; + /** Pushes prompts in the order they came (see {@link prompt}). */ + private pushes: Promise = Promise.resolve(); + /** The result of the open turn. */ + private lastResult: SDKResultMessage | undefined; + /** Set by `session/close`, or when the query ends: nothing more goes out. */ + private closed = false; + private closing: Promise | undefined; + /** Called when the cancelled work and the covered prompts have ended. */ + private settledWaiters: Array<() => void> = []; + private query: Query | undefined; + readonly output: SessionOutput; + /** The `background` lists of the session and its children, stamped on each state. */ + private readonly background: V2Background; + readonly tasks: SessionTasks; + config!: SessionConfig; + + constructor( + readonly sessionId: string, + readonly cwd: string, + /** The session's additional directories, as its query got them. */ + readonly additionalDirectories: readonly string[], + private readonly connection: SessionConnection, + private readonly input: Pushable, + ) { + this.output = new SessionOutput( + sessionId, + cwd, + connection.translator, + (update) => this.send(update), + connection.logger, + ); + this.background = new V2Background(connection.translator.terminals); + this.tasks = new SessionTasks( + { + sessionId, + cwd, + logger: connection.logger, + translator: connection.translator, + background: this.background, + send: (notification) => this.sendNotification(notification), + rootState: () => this.foregroundState(), + foregroundRequestsChanged: () => this.reportState(), + stopTask: async (taskId) => { + await this.query?.stopTask(taskId); + }, + }, + this.output, + ); + this.tasks.hostRequest = (request, signal) => connection.requestPermission(request, signal); + // The session reports its background work: every state carries a list. + this.background.changed({ sessionId, items: [], state: undefined }); + } + + /** Starts reading the query. Called once, after its initialization. */ + start(query: Query, config: SessionConfig): void { + this.query = query; + this.config = config; + void this.consume(query); + } + + /** The session's commands, from Claude Code, in v1 form. */ + async commands(): Promise { + if (!this.query) return []; + const commands = await this.query.supportedCommands(); + return commands.map((command) => ({ + name: command.name, + description: command.description, + ...(command.argumentHint ? { input: { hint: command.argumentHint } } : {}), + })); + } + + /** + * What `session/resume` sends before its response: the children with their + * current states, the current update of each listed item, then the + * session's state, with its list. + */ + resumeSnapshot(): v2.UpdateSessionNotification[] { + return [ + ...this.tasks.currentState(), + this.background.stamp({ + sessionId: this.sessionId, + update: this.stateUpdate(this.foregroundState()), + }), + ]; + } + + /** Replaces the session's MCP servers, as a resume of the active session asks. */ + async setMcpServers(servers: Parameters[0]): Promise { + await this.query?.setMcpServers(servers); + } + + // --- Requests --------------------------------------------------------- + + /** + * Pushes the prompt to Claude Code. Answers once Claude Code inserted it + * (see the module doc), right after the prompt's `user_message`. + * + * A prompt waits for the interrupt of an earlier `session/cancel` before it + * goes to Claude Code: the interrupt's `cancelQueued` must not end a prompt + * that came after the cancel. + */ + prompt(params: v2.PromptRequest): Promise { + if (this.closed) { + return Promise.reject(RequestError.sessionNotFound(this.sessionId)); + } + // Throws invalid params for content that Claude cannot take. + const request: PromptRequest = v1PromptRequest(params); + const uuid = randomUUID(); + const message = { ...promptToClaude(request), uuid }; + return new Promise((resolve, reject) => { + const pending: PendingPrompt = { prompt: params.prompt, pushed: false, resolve, reject }; + this.pending.set(uuid, pending); + this.pushes = this.pushes + .then(() => this.interrupting) + .then(() => { + // A cancel or close answered it before it went out. + if (this.pending.get(uuid) !== pending || this.closed) return; + pending.pushed = true; + this.input.push(message); + }); + }); + } + + /** + * Stops the foreground work, and the prompts not inserted yet. The work's + * idle reports `cancelled`. Open permission requests are withdrawn with + * `$/cancel_request`. Background work goes on. + */ + async cancel(): Promise { + if (this.closed || !this.query) return; + // Not pushed yet: no one but this session knows of them. + for (const [uuid, prompt] of [...this.pending]) { + if (!prompt.pushed) this.failPrompt(uuid, RequestError.requestCancelled()); + } + const covered = [...this.pending.keys()]; + if (!this.foreground && covered.length === 0) return; + if (this.foreground) this.cancelledWork = true; + for (const uuid of covered) this.cancelCovered.add(uuid); + for (const abort of this.requestAborts) abort.abort(); + // The subagents that the work waits on stop with it. Background ones go on. + this.tasks.cancelForeground(); + // `cancelQueued` is untyped in the SDK (`Query.interrupt` takes it since + // the CLI's `interrupt_cancel_queued_v1`): Claude Code then ends each + // queued prompt with a `cancelled` lifecycle frame, which fails it here. + const interrupt = this.query.interrupt as (options: { + cancelQueued: boolean; + }) => Promise; + const done = interrupt.call(this.query, { cancelQueued: true }).then( + () => undefined, + (error: unknown) => { + // `session/cancel` is a notification: no one can be answered. Nothing + // stopped, so the work's idle reports how it really ends. + this.connection.logger.error(`Session ${this.sessionId}: the interrupt failed`, error); + this.cancelledWork = false; + this.cancelCovered.clear(); + }, + ); + this.interrupting = done; + await done; + if (this.interrupting === done) this.interrupting = undefined; + } + + async setConfigOption( + configId: string, + type: string | undefined, + value: unknown, + ): Promise { + await this.config.set(configId, type, value); + const options = this.config.options(); + // v2 sends every config change as an update too, for the session's other clients. + this.send({ sessionUpdate: "config_option_update", configOptions: options }); + return options; + } + + /** + * Cancels as `session/cancel` does, waits for the cancelled work's idle and + * for the covered prompts' answers, then ends the query, which stops the + * background work too. Nothing of the session goes out after it resolves. + */ + close(): Promise { + this.closing ??= (async () => { + await this.cancel(); + // v2 asks to withdraw every request of the session before the close + // response, also its background subagents'. + this.tasks.withdrawAll(); + await this.settled(CLOSE_TIMEOUT_MS); + // Claude Code did not end the work in time: it ends with the query. + if (this.foreground) { + this.cancelledWork = true; + this.closeTurn(); + } + this.failPending(RequestError.requestCancelled()); + this.closed = true; + this.input.end(); + this.query?.close(); + })(); + return this.closing; + } + + // --- Permission requests ----------------------------------------------- + + availableModes(): string[] { + return this.config.availableModeIds(); + } + + cancelling(): boolean { + return this.cancelledWork; + } + + /** The session of a permission request: this one, or a subagent's (see `canUseTool`). */ + target(agentId: string | undefined): Promise { + return this.tasks.target(agentId, this); + } + + async requestPermission( + request: v2.RequestPermissionRequest, + toolSignal: AbortSignal, + ): Promise { + const abort = new AbortController(); + const signal = AbortSignal.any([toolSignal, abort.signal]); + this.requestAborts.add(abort); + this.openRequests++; + this.reportState(); + try { + // The subject is an upsert of the tool call: the client may see the + // request before the tool use streams. + return await this.connection.requestPermission(request, signal); + } catch (error) { + if (signal.aborted) return { outcome: { outcome: "cancelled" } }; + throw error; + } finally { + this.requestAborts.delete(abort); + this.openRequests--; + this.reportState(); + } + } + + modeChanged(mode: PermissionMode): void { + if (this.config.modeChanged(mode)) { + this.send({ sessionUpdate: "config_option_update", configOptions: this.config.options() }); + } + } + + // --- The query's messages ---------------------------------------------- + + private async consume(query: Query): Promise { + try { + for await (const message of query) { + if (this.closed) break; + try { + this.handle(message); + } catch (error) { + this.connection.logger.error( + `Session ${this.sessionId}: failed to handle a ${message.type} message`, + error, + ); + } + this.checkSettled(); + } + this.ended(undefined); + } catch (error) { + this.ended(error); + } + } + + private handle(message: SDKMessage): void { + if ((message as { type: string }).type === "command_lifecycle") { + this.lifecycle(message as unknown as CommandLifecycleFrame); + return; + } + // Task events, and a subagent's messages, which go to its session. + if (this.tasks.handle(message)) return; + switch (message.type) { + case "stream_event": + if (message.parent_tool_use_id === null) this.openTurn(undefined); + this.output.streamEvent(message); + return; + case "assistant": + if (message.parent_tool_use_id === null) this.openTurn(undefined); + this.output.assistant(message); + return; + case "user": + // With `replay-user-messages`, Claude Code echoes each prompt it takes + // in. A prompt Claude Code reported `started` for is inserted already. + if ("isReplay" in message && message.isReplay) { + if (message.uuid && message.parent_tool_use_id === null) { + this.openTurn(message.uuid); + this.inserted(message.uuid); + } + return; + } + this.tasks.toolResults(this.output, message); + return; + case "result": + this.result(message); + return; + case "system": + switch (message.subtype) { + case "init": + // Each turn starts with one, also a turn that no prompt started. + this.openTurn(undefined); + return; + case "session_state_changed": + // The turn's `result` ends it. An idle without one ends it too, + // such as a turn that an interrupt stopped before it ran. + if (message.state === "idle") this.closeTurn(); + return; + default: + return; + } + default: + // Not reported yet: tool progress, background tasks, compaction, + // rate limits, notices and the rest (see docs/v2-native-core.md). + return; + } + } + + private lifecycle(frame: CommandLifecycleFrame): void { + const uuid = frame.command_uuid; + switch (frame.state) { + case "started": + this.openTurn(uuid); + this.inserted(uuid); + return; + case "cancelled": + this.cancelCovered.delete(uuid); + if (this.failPrompt(uuid, RequestError.requestCancelled())) return; + // The prompt had started: the interrupt stopped its turn. + if (uuid === this.turnCommand) this.closeTurn(); + return; + case "discarded": + case "refused": + this.cancelCovered.delete(uuid); + this.failPrompt( + uuid, + RequestError.internalError( + { lifecycle: frame.state }, + `Claude Code ${frame.state} the prompt before it ran`, + ), + ); + return; + case "completed": + // Comes after the turn's result. A turn that ended without one ends here. + if (uuid === this.turnCommand) this.closeTurn(); + return; + default: + // `queued`: the prompt waits in Claude Code's queue. + return; + } + } + + private inserted(uuid: string): void { + const prompt = this.pending.get(uuid); + if (!prompt) return; + this.pending.delete(uuid); + this.send({ sessionUpdate: "user_message", messageId: uuid, content: prompt.prompt }); + prompt.resolve({ messageId: uuid }); + } + + private result(message: SDKResultMessage): void { + // A result with no open turn: a turn that sent nothing before it. + this.openTurn(undefined); + this.lastResult = message; + // A local command (such as `/context`) answers with its result alone: no + // model text streamed for it. + if ( + message.subtype === "success" && + !message.is_error && + message.result && + !this.output.hasAgentText() + ) { + this.output.agentMessage(message.result, message.uuid); + } + this.closeTurn(); + } + + /** The query ended, with `error` when it failed. The session cannot go on. */ + private ended(error: unknown): void { + if (this.closing || this.closed) { + this.tasks.queryEnded(undefined); + this.failPending(RequestError.requestCancelled()); + this.closed = true; + return; + } + const failure = RequestError.internalError( + error instanceof Error ? { cause: error.message } : undefined, + "Claude Code stopped. Resume the session to continue.", + ); + this.failPending(failure); + this.connection.logger.error(`Session ${this.sessionId}: the query ended`, error); + this.tasks.queryEnded({ code: failure.code, message: failure.message }); + if (this.foreground) { + // Cancelled work that ended with the query was still cancelled. + this.output.finishUnfinished(this.cancelledWork ? "cancelled" : "failed"); + this.foreground = false; + this.reportedState = "idle"; + this.send({ + sessionUpdate: "state_update", + state: "idle", + ...(this.cancelledWork + ? { stopReason: "cancelled" as const } + : { + stopReason: "error" as const, + error: { code: failure.code, message: failure.message }, + }), + }); + } + this.closed = true; + this.connection.ended(this.sessionId); + } + + // --- State --------------------------------------------------------------- + + /** + * Opens a turn, if none is open. `command` is the prompt that started it, + * if one did. A prompt that a cancel covered starts work that the cancel's + * interrupt stops. + */ + private openTurn(command: string | undefined): void { + if (command !== undefined) { + this.turnCommand = command; + if (this.cancelCovered.delete(command)) this.cancelledWork = true; + } + if (this.foreground) return; + this.foreground = true; + this.lastResult = undefined; + this.output.resetAgentText(); + this.reportState(); + } + + /** Ends the open turn: its idle goes out with the turn's outcome. */ + private closeTurn(): void { + if (!this.foreground) return; + // v2 asks for a final status of the tool calls of stopped work before its idle. + const outcome = idleOutcome(this.lastResult, this.cancelledWork).stopReason; + if (outcome === "cancelled" || outcome === "error") { + this.output.finishUnfinished(outcome === "cancelled" ? "cancelled" : "failed"); + } + this.foreground = false; + this.reportState(); + this.cancelledWork = false; + this.lastResult = undefined; + this.turnCommand = undefined; + } + + private foregroundState(): ForegroundState { + if (!this.foreground) return "idle"; + return this.openRequests > 0 || this.tasks.foregroundBlocked() ? "requires_action" : "running"; + } + + /** Reports the foreground state when it changed. */ + private reportState(): void { + if (this.closed) return; + const state = this.foregroundState(); + if (state === this.reportedState) return; + // A cancel withdrew the open requests: the work is stopping, and its idle follows. + if (this.reportedState === "requires_action" && state === "running" && this.cancelledWork) { + return; + } + this.reportedState = state; + this.send(this.stateUpdate(state)); + } + + private stateUpdate(state: ForegroundState): v2.SessionUpdate { + switch (state) { + case "running": + return { sessionUpdate: "state_update", state }; + case "requires_action": + return { sessionUpdate: "state_update", state }; + default: + return { + sessionUpdate: "state_update", + state, + ...idleOutcome(this.lastResult, this.cancelledWork), + }; + } + } + + private send(update: v2.SessionUpdate): void { + this.sendNotification({ sessionId: this.sessionId, update }); + } + + /** Sends an update of the session or of a child, with its `background` list. */ + private sendNotification(notification: v2.UpdateSessionNotification): void { + if (this.closed) return; + this.connection.send(this.background.stamp(notification)); + } + + /** Resolves once no turn is open and every prompt is answered, or after `timeoutMs`. */ + private settled(timeoutMs: number): Promise { + if (!this.foreground && this.pending.size === 0) return Promise.resolve(); + return new Promise((resolve) => { + const timer = setTimeout(done, timeoutMs); + function done() { + clearTimeout(timer); + resolve(); + } + this.settledWaiters.push(done); + }); + } + + private checkSettled(): void { + if (this.foreground || this.pending.size > 0) return; + const waiters = this.settledWaiters; + this.settledWaiters = []; + for (const waiter of waiters) waiter(); + } + + /** Fails the prompt `uuid` if it is not answered yet. Returns whether it was pending. */ + private failPrompt(uuid: string, error: unknown): boolean { + const prompt = this.pending.get(uuid); + if (!prompt) return false; + this.pending.delete(uuid); + prompt.reject(error); + return true; + } + + private failPending(error: unknown): void { + for (const uuid of [...this.pending.keys()]) this.failPrompt(uuid, error); + } +} + +/** + * The idle members this core reports. Typed as those members, so the checker + * matches each stop reason to its own, which it cannot against the whole + * union with its custom and unknown members. + */ +type IdleOutcome = Extract< + v2.IdleStateUpdate, + { + stopReason: "end_turn" | "max_tokens" | "max_turn_requests" | "refusal" | "cancelled" | "error"; + } +>; + +/** The stop reason, usage and error of an idle, from the turn's result. */ +function idleOutcome(result: SDKResultMessage | undefined, cancelled: boolean): IdleOutcome { + const usage = usageOf(result); + if (cancelled) return { stopReason: "cancelled", ...usage }; + if (!result) return { stopReason: "end_turn" }; + if (result.subtype === "error_max_turns") return { stopReason: "max_turn_requests", ...usage }; + if (result.stop_reason === "max_tokens") return { stopReason: "max_tokens", ...usage }; + if (result.stop_reason === "refusal") return { stopReason: "refusal", ...usage }; + if (result.subtype !== "success" || result.is_error) { + const text = result.subtype === "success" ? result.result : result.errors.join("\n"); + const error = + result.subtype === "success" && isLoginRequiredText(text) + ? RequestError.authRequired() + : RequestError.internalError(undefined, text || `Claude Code ended with ${result.subtype}`); + return { stopReason: "error", error: { code: error.code, message: error.message }, ...usage }; + } + return { stopReason: "end_turn", ...usage }; +} + +function usageOf(result: SDKResultMessage | undefined): { usage?: v2.Usage } { + if (!result) return {}; + const { input_tokens, output_tokens, cache_read_input_tokens, cache_creation_input_tokens } = + result.usage; + const inputTokens = input_tokens ?? 0; + const outputTokens = output_tokens ?? 0; + const cachedReadTokens = cache_read_input_tokens ?? 0; + const cachedWriteTokens = cache_creation_input_tokens ?? 0; + return { + usage: { + inputTokens, + outputTokens, + cachedReadTokens, + cachedWriteTokens, + totalTokens: inputTokens + outputTokens + cachedReadTokens + cachedWriteTokens, + }, + }; +} diff --git a/src/v2-native/stream.ts b/src/v2-native/stream.ts new file mode 100644 index 00000000..329b0543 --- /dev/null +++ b/src/v2-native/stream.ts @@ -0,0 +1,278 @@ +/** + * The output of one Claude Code session, as ACP session updates. + * + * {@link SessionOutput} maps the SDK's content messages (stream events, + * consolidated assistant messages, tool results) through the shared mapping + * of `acp-agent.ts` (`toAcpNotifications`), whose v1 updates the connection's + * {@link V2UpdateTranslator} turns into v2 updates. It knows nothing about + * prompts or turns: the session decides what the output belongs to. + */ +import type * as v2 from "@agentclientprotocol/sdk/experimental/v2/unstable"; +import type { + SDKAssistantMessage, + SDKPartialAssistantMessage, + SDKUserMessage, + SessionMessage, +} from "@anthropic-ai/claude-agent-sdk"; +import { + isReplayHiddenMetaMessage, + messageIdForGrouping, + stripLocalCommandMetadata, + streamEventToAcpNotifications, + toAcpNotifications, + type AcpClient, + type Logger, + type StreamedToolInputCache, + type ToolUseCache, +} from "../acp-agent.js"; +import type { AcpSessionNotification } from "../acp-subagents.js"; +import { ClientCapabilities } from "../tool-calls/client-capabilities.js"; +import { ToolCallFieldTracker } from "../tool-calls/field-tracker.js"; +import { replayClear, type V2UpdateTranslator } from "../v2/update-translator.js"; + +/** Every v2 client gets the same tool call reports: v2 diffs and display terminals. */ +const V2_TOOL_CALL_CAPABILITIES = ClientCapabilities.from(undefined, { v2: true }); + +type AssistantContent = SDKAssistantMessage["message"]["content"]; +type UserContent = SDKUserMessage["message"]["content"]; + +export class SessionOutput { + private readonly toolUseCache: ToolUseCache = {}; + private readonly emittedToolCalls = new Set(); + /** What the client holds of each open tool call: an update carries only what changed. */ + private readonly toolCallFields = new ToolCallFieldTracker(); + private readonly streamedToolInputs: StreamedToolInputCache = new Map(); + /** The API ids of the assistant messages whose text streamed as deltas. */ + private readonly streamedMessages = new Set(); + /** The id of the assistant message that is streaming. */ + private streamingMessageId: string | undefined; + /** Whether any agent text went out since {@link resetAgentText}. */ + private agentText = false; + /** During {@link replay}, the messages that it has cleared so far. */ + private replayCleared: Set | undefined; + + constructor( + readonly sessionId: string, + private readonly cwd: string, + private readonly translator: V2UpdateTranslator, + private readonly send: (update: v2.SessionUpdate) => void, + private readonly logger: Logger, + ) {} + + /** Tool updates that a hook callback sends outside the stream (an Edit's diff). */ + private readonly hookClient = { + sessionUpdate: async (notification: AcpSessionNotification) => this.emit([notification]), + } as unknown as AcpClient; + + /** A partial assistant message: one event of the streaming API response. */ + streamEvent(message: SDKPartialAssistantMessage): void { + // A subagent's text streams only with `forwardSubagentText`, which this + // core leaves off: its tool calls come with its consolidated messages. + if (message.parent_tool_use_id !== null) return; + if (message.event.type === "message_start") { + this.streamingMessageId = message.event.message.id; + this.streamedMessages.add(message.event.message.id); + } + this.emit( + streamEventToAcpNotifications( + message, + this.sessionId, + this.toolUseCache, + this.hookClient, + this.logger, + { + toolCallCapabilities: V2_TOOL_CALL_CAPABILITIES, + cwd: this.cwd, + emittedToolCalls: this.emittedToolCalls, + toolCallFields: this.toolCallFields, + messageId: this.streamingMessageId, + streamedToolInputs: this.streamedToolInputs, + }, + ), + ); + } + + /** + * A consolidated assistant message. Its text and thinking streamed already + * when the message's stream started (`message_start` with the same id), + * so only its other blocks go out: a tool use then gets its complete input. + * A message that never streamed (a gateway without streaming, a subagent) + * goes out whole, a subagent's without its text, as it streamed none. + * + * A stream that an interrupt cut short leaves its tail out. The v1 core + * diffs the text against the deltas to send that tail + * (`unstreamedRemainder`); this core does not. + */ + assistant(message: SDKAssistantMessage): void { + const messageId = messageIdForGrouping(message); + const streamed = + message.message.id !== undefined && this.streamedMessages.delete(message.message.id); + const dropText = streamed || message.parent_tool_use_id !== null; + const content = dropText + ? message.message.content.filter( + (block) => block.type !== "text" && block.type !== "thinking", + ) + : message.message.content; + this.content(content, "assistant", message.parent_tool_use_id, { messageId }); + } + + /** + * A user message that Claude Code adds: the results of tool uses. Its other + * blocks (command output, reminders, a prompt's echo) are not output. + * `transform` rewrites each update before it goes out, such as a background + * command's result, whose terminal keeps running. + */ + toolResults( + message: SDKUserMessage, + transform: (notification: AcpSessionNotification) => AcpSessionNotification = (n) => n, + ): void { + if (!Array.isArray(message.message.content)) return; + const results = message.message.content.filter((block) => block.type === "tool_result"); + if (results.length === 0) return; + this.content( + results, + "user", + message.parent_tool_use_id, + { + toolUseResult: message.tool_use_result, + toolResultMeta: (message as { tool_result_meta?: unknown }).tool_result_meta, + }, + transform, + ); + } + + /** The tool uses of the session's tool calls, by id. */ + toolUses(): Readonly { + return this.toolUseCache; + } + + /** Sends v1-shaped updates of the session, as the shared mapping makes them. */ + emitV1(notifications: AcpSessionNotification[]): void { + this.emit(notifications); + } + + /** Sets the status of a tool call, such as a background task's when it ends. */ + toolCallStatus(toolCallId: string, status: "in_progress" | "paused" | ToolCallFinalStatus): void { + if (FINAL_STATUSES.has(status)) this.unfinished.delete(toolCallId); + this.send({ sessionUpdate: "tool_call_update", toolCallId, status } as v2.SessionUpdate); + } + + /** + * Replays the stored history of the session: its prompts, Claude's + * messages and its tool calls, as the live session sent them. Subagent + * transcripts are left out, as live. The client may hold the replayed + * messages already, so each message is cleared before its first chunk. + */ + replay(messages: SessionMessage[]): void { + this.replayCleared = new Set(); + try { + for (const message of messages) { + if (message.parent_tool_use_id !== null || isReplayHiddenMetaMessage(message)) continue; + const inner = message.message as { id?: string; content?: unknown }; + if (message.type === "assistant" && Array.isArray(inner.content)) { + this.content(inner.content as AssistantContent, "assistant", null, { + messageId: inner.id ?? message.uuid, + replay: true, + }); + } else if (message.type === "user" && inner.content !== undefined) { + // `null`: the message was command metadata alone. + const content = stripLocalCommandMetadata(inner.content); + if (content === null) continue; + this.content(content as UserContent, "user", null, { + messageId: message.uuid, + replay: true, + }); + } + } + } finally { + this.replayCleared = undefined; + } + } + + /** Agent text that is not a model message, such as a local command's result. */ + agentMessage(text: string, messageId: string): void { + this.content(text, "assistant", null, { messageId }); + } + + /** Whether agent text went out since the last {@link resetAgentText}. */ + hasAgentText(): boolean { + return this.agentText; + } + + resetAgentText(): void { + this.agentText = false; + } + + private content( + content: Parameters[0], + role: "assistant" | "user", + parentToolUseId: string | null, + options: { + messageId?: string; + toolUseResult?: unknown; + toolResultMeta?: unknown; + replay?: boolean; + }, + transform: (notification: AcpSessionNotification) => AcpSessionNotification = (n) => n, + ): void { + this.emit( + toAcpNotifications( + content, + role, + this.sessionId, + this.toolUseCache, + this.hookClient, + this.logger, + { + toolCallCapabilities: V2_TOOL_CALL_CAPABILITIES, + cwd: this.cwd, + emittedToolCalls: this.emittedToolCalls, + toolCallFields: this.toolCallFields, + parentToolUseId, + // A replayed tool use runs no hook that could report its result. + registerHooks: !options.replay, + ...options, + }, + ).map(transform), + ); + } + + /** + * Gives each tool call that has no final status yet the final `status`, + * except those in `keep` (background work, which goes on). For the end of + * stopped work: v2 asks for a final status of its tool calls before the idle. + */ + finishUnfinished(status: "failed" | "cancelled", keep: ReadonlySet = new Set()): void { + for (const toolCallId of [...this.unfinished]) { + if (keep.has(toolCallId)) continue; + this.unfinished.delete(toolCallId); + this.send({ sessionUpdate: "tool_call_update", toolCallId, status }); + } + } + + /** The tool calls that the client holds without a final status. */ + private readonly unfinished = new Set(); + + private emit(notifications: AcpSessionNotification[]): void { + for (const { update } of notifications) { + if (update.sessionUpdate === "agent_message_chunk") this.agentText = true; + const replaying = this.replayCleared !== undefined; + for (const v2Update of this.translator.updates(this.sessionId, update, replaying)) { + const clear = this.replayCleared && replayClear(this.replayCleared, v2Update); + if (clear) this.send(clear); + if (v2Update.sessionUpdate === "tool_call_update" && !replaying) { + const { toolCallId, status } = v2Update as { toolCallId: string; status?: string | null }; + if (status != null) { + if (FINAL_STATUSES.has(status)) this.unfinished.delete(toolCallId); + else this.unfinished.add(toolCallId); + } + } + this.send(v2Update); + } + } + } +} + +type ToolCallFinalStatus = "completed" | "failed" | "cancelled"; + +const FINAL_STATUSES = new Set(["completed", "failed", "cancelled"]); diff --git a/src/v2-native/tasks.ts b/src/v2-native/tasks.ts new file mode 100644 index 00000000..00d93531 --- /dev/null +++ b/src/v2-native/tasks.ts @@ -0,0 +1,935 @@ +/** + * Claude Code's tasks of one root session, as ACP v2 reports them: its + * subagents as child sessions (the subagents RFD), and the work that runs in + * the background as the `background` list of each session's states. + * + * Claude Code reports each task with `task_started`, then `task_updated` + * patches, and its end with `task_notification` (or a terminal `task_updated` + * patch, the only one it promises per transition). `background_tasks_changed` + * is its live set of background tasks. From those: + * + * - A subagent (`local_agent`) is a child session whose id is its agent id, + * the same session for every delegation to it (a SendMessage resume starts + * it again under the same `task_id`). It is announced on its parent's + * stream (`parent_task_id`, or the root) with `subagent_update`, before + * any of its traffic. Its messages carry the `parent_tool_use_id` of the + * Agent call that launched it, also after a resume, and go to its stream. + * Each run of it is the child's foreground work: `running` from its start + * to its end, on its stream and mirrored on the parent's `subagent_update`. + * The parent's turn waits on a child that is not `is_backgrounded`; one in + * the background is listed in its parent's `background` while it works. + * - A command that went to the background is its display terminal, kept + * running from its Bash result until its task ends, with its output read + * from the file Claude Code writes it to. + * - A task that a tool call started, such as a `Monitor` or `Workflow` call, + * is that tool call, kept `in_progress` (or `paused`) until the task ends. + * - Any other background task is a `_claude/task` item. + * + * Claude Code's interrupt spares background tasks (`perTaskStopAffordance`), + * so `session/cancel` leaves listed work running, as v2 asks. + */ +import * as fs from "node:fs"; +import * as path from "node:path"; +import { RequestError } from "@agentclientprotocol/sdk/unstable"; +import type * as v2 from "@agentclientprotocol/sdk/experimental/v2/unstable"; +import type { + SDKAssistantMessage, + SDKMessage, + SDKUserMessage, +} from "@anthropic-ai/claude-agent-sdk"; +import type { Logger } from "../acp-agent.js"; +import type { AcpSessionNotification } from "../acp-subagents.js"; +import { backgroundBashTaskFromToolResult } from "../async-tasks.js"; +import { BackgroundOutputTail, type BackgroundOutput } from "../background-output.js"; +import type { BackgroundItem, WorkStateName } from "../background-work.js"; +import { withRunningTerminal, withRunningToolCall } from "../tool-calls/background.js"; +import type { V2Background } from "../v2/background.js"; +import type { V2UpdateTranslator } from "../v2/update-translator.js"; +import { SessionOutput } from "./stream.js"; + +/** What the tasks need of their root session. */ +export interface TaskHost { + readonly sessionId: string; + readonly cwd: string; + readonly logger: Logger; + readonly translator: V2UpdateTranslator; + readonly background: V2Background; + /** Sends an update of the root session or one of its children. */ + send(notification: v2.UpdateSessionNotification): void; + /** The root session's foreground state now. */ + rootState(): WorkStateName; + /** A child's open requests changed, which can block the root's foreground work. */ + foregroundRequestsChanged(): void; + stopTask(taskId: string): Promise; +} + +/** Where a permission request goes: the root session or a child. */ +export interface RequestTarget { + readonly sessionId: string; + readonly cwd: string; + /** Whether a cancel stops the work that the request belongs to. */ + cancelling(): boolean; + requestPermission( + request: v2.RequestPermissionRequest, + signal: AbortSignal, + ): Promise; +} + +type ChildState = "idle" | "running" | "requires_action"; + +type IdleOutcome = + | { stopReason: "end_turn" } + | { stopReason: "cancelled" } + | { stopReason: "error"; error: { code: number; message: string } }; + +type Child = { + /** The child's session id: its agent id. */ + sessionId: string; + parentSessionId: string; + /** The Agent call that launched it, whose id its messages carry. */ + launchToolUseId: string | undefined; + title: string; + description: string | undefined; + /** Whether its parent's work waits on its run (`is_backgrounded: false`). */ + foreground: boolean; + /** Whether a run of it is going on: its foreground work. */ + working: boolean; + /** The state its stream was told last. */ + reportedState: ChildState | undefined; + /** How its last run ended. */ + outcome: IdleOutcome | undefined; + /** Whether a cancel of it, or of the work waiting on it, stops its run. */ + cancelled: boolean; + /** Whether its run's delegation went out as an incoming `session_message`. */ + delegationReported: boolean; + openRequests: number; + readonly requestAborts: Set; + /** The working directory it was announced with, when not its parent's. */ + cwd: string | undefined; + output: SessionOutput; +}; + +type ToolResultBlock = { type: "tool_result"; tool_use_id: string; is_error?: boolean }; + +/** A task of `background_tasks_changed`. */ +type LevelTask = { ambient: boolean; taskType: string; description: string; parentTaskId?: string }; + +/** What `task_started` said of a task that is not a subagent. */ +type StartedTask = { toolUseId?: string; parentTaskId?: string; taskType?: string }; + +/** How long a subagent's permission request waits for the subagent's `task_started`. */ +const ANNOUNCE_WAIT_MS = 2000; + +/** The tools whose structured result names the task that the call started. */ +const TASK_TOOLS = new Set(["Monitor", "Workflow"]); + +export class SessionTasks { + /** The subagents, by agent id. */ + private readonly children = new Map(); + /** The child of each Agent call that launched or resumed one. */ + private readonly childByToolUse = new Map(); + /** The other tasks that `task_started` reported, until they end. */ + private readonly started = new Map(); + /** Claude Code's live background tasks, from its last `background_tasks_changed`. */ + private level = new Map(); + /** The terminals of the commands that went to the background, by task id. */ + private readonly terminals = new Map< + string, + { toolCallId: string; output: SessionOutput; tail?: BackgroundOutputTail; ending?: boolean } + >(); + /** The tool calls whose tasks go on in the background, by task id. */ + private readonly toolCalls = new Map< + string, + { toolCallId: string; output: SessionOutput; paused: boolean } + >(); + /** The tool calls that returned: their tasks no longer hold their work. */ + private readonly returned = new Set(); + /** What a `SubagentStart` hook reported before the child was announced, by agent id. */ + private readonly startedHooks = new Map(); + /** Permission requests waiting for their subagent's announcement, by agent id. */ + private readonly announceWaiters = new Map void>>(); + + constructor( + private readonly host: TaskHost, + /** The root session's output, which owns its tool calls. */ + private readonly rootOutput: SessionOutput, + ) {} + + // --- Claude Code's messages --------------------------------------------- + + /** + * Takes a message of the query that concerns the tasks. Returns whether it + * was a child's, which then goes to the child's stream only. + */ + handle(message: SDKMessage): boolean { + switch (message.type) { + case "system": + switch (message.subtype) { + case "task_started": + this.taskStarted(message); + return true; + case "task_updated": + this.taskUpdated(message); + return true; + case "task_notification": + this.taskEnded(message.task_id, message.status); + return true; + case "background_tasks_changed": + this.levelChanged(message.tasks); + return true; + default: + return false; + } + case "stream_event": { + // A child's text comes whole, in its consolidated messages. + return message.parent_tool_use_id !== null && this.childOf(message) !== undefined; + } + case "assistant": { + const child = this.childOf(message); + if (!child) return false; + child.output.assistant({ ...message, parent_tool_use_id: null } as SDKAssistantMessage); + return true; + } + case "user": { + const child = this.childOf(message); + if (!child) return false; + this.childUserMessage(child, message); + return true; + } + default: + return false; + } + } + + /** + * The tool results of the root session, or of a child (`output`): a + * background command's terminal and a background task's tool call keep + * running past them. + */ + toolResults(output: SessionOutput, message: SDKUserMessage): void { + const content = message.message.content; + if (!Array.isArray(content)) return; + const results = content.filter( + (block) => block.type === "tool_result", + ) as unknown as ToolResultBlock[]; + for (const { tool_use_id } of results) this.returned.add(tool_use_id); + const toolUses = output.toolUses(); + + const command = backgroundBashTaskFromToolResult( + content, + message.tool_use_result, + toolUses, + (toolUseId) => + [...this.started].find( + ([, task]) => task.toolUseId === toolUseId && task.taskType === "local_bash", + )?.[0], + ); + // A fast command can end before its result: then its terminal exits with it. + const runningTerminal = + command && this.started.has(command.taskId) ? command.toolCallId : undefined; + if (command && runningTerminal) { + this.terminals.set(command.taskId, { toolCallId: command.toolCallId, output }); + } + + const runningToolCalls = new Set(); + const succeeded = results.filter((block) => block.is_error !== true); + const structuredTaskId = + succeeded.length === 1 && + typeof message.tool_use_result === "object" && + message.tool_use_result !== null && + typeof (message.tool_use_result as { taskId?: unknown }).taskId === "string" + ? (message.tool_use_result as { taskId: string }).taskId + : undefined; + for (const { tool_use_id: toolCallId } of succeeded) { + const toolUse = toolUses[toolCallId]; + if (!toolUse || toolUse.name === "Bash" || toolUse.name === "Agent") continue; + const taskId = + (TASK_TOOLS.has(toolUse.name) ? structuredTaskId : undefined) ?? + [...this.started].find(([, task]) => task.toolUseId === toolCallId)?.[0]; + const task = taskId === undefined ? undefined : this.level.get(taskId); + if (!task || task.taskType === "local_bash" || task.taskType === "local_agent") continue; + this.toolCalls.set(taskId!, { toolCallId, output, paused: false }); + runningToolCalls.add(toolCallId); + } + + // The helpers are typed for the SDK's notification; they only rewrite a tool call update. + type Notification = Parameters[0]; + output.toolResults( + message, + (notification) => + withRunningToolCall( + withRunningTerminal(notification as Notification, runningTerminal), + runningToolCalls, + ) as AcpSessionNotification, + ); + // After the result's own updates: the output replaces their placeholder. + if (command && runningTerminal) { + this.followOutput( + command.taskId, + typeof command.outputFilePath === "string" ? command.outputFilePath : undefined, + ); + } + this.publish(); + } + + // --- Subagent sessions ---------------------------------------------------- + + /** Whether `sessionId` is a child session of this root. */ + hasChild(sessionId: string): boolean { + return this.childSession(sessionId) !== undefined; + } + + /** + * The session that a permission request of the agent `agentId` goes to: + * its child session, once announced, else the root. A request can come + * before its subagent's `task_started`, so it waits for it a little. + */ + async target(agentId: string | undefined, root: RequestTarget): Promise { + if (agentId === undefined) return root; + if (!this.children.has(agentId)) { + await new Promise((resolve) => { + const timer = setTimeout(resolve, ANNOUNCE_WAIT_MS); + const waiters = this.announceWaiters.get(agentId) ?? []; + waiters.push(() => { + clearTimeout(timer); + resolve(); + }); + this.announceWaiters.set(agentId, waiters); + }); + } + const child = this.children.get(agentId); + // Not announced: its request stays the root's, as its other traffic does. + if (!child) return root; + return { + sessionId: child.sessionId, + cwd: child.cwd ?? this.host.cwd, + cancelling: () => child.cancelled, + requestPermission: (request, signal) => this.childRequest(child, request, signal), + }; + } + + /** + * Whether the root's foreground work waits on a child that waits on the + * user: a child it does not run in the background, or one of that child's. + */ + foregroundBlocked(): boolean { + return this.foregroundChildren(this.host.sessionId).some((child) => child.openRequests > 0); + } + + /** + * The root's foreground work is cancelled: so is the work of the children + * that it waits on. Their open requests are withdrawn. Claude Code's + * interrupt stops their runs, which then end `cancelled`. + */ + cancelForeground(): void { + for (const child of this.foregroundChildren(this.host.sessionId)) this.withdraw(child); + } + + /** The root session closes: every child's open request is withdrawn. */ + withdrawAll(): void { + for (const child of this.children.values()) this.withdraw(child); + } + + /** + * `session/cancel` of a child: stops its run, and the work of the children + * that it waits on. Its idle reports `cancelled` once Claude Code reports + * the task stopped. A child that does not work has nothing to stop. + */ + async cancelChild(sessionId: string): Promise { + const child = this.childSession(sessionId); + if (!child?.working) return; + this.withdraw(child); + for (const waited of this.foregroundChildren(child.sessionId)) this.withdraw(waited); + try { + await this.host.stopTask(child.sessionId); + } catch (error) { + // The run ended meanwhile, or Claude Code refused: it reports how it ends. + child.cancelled = false; + this.host.logger.error(`Subagent ${sessionId}: stopping it failed`, error); + } + } + + /** A `SubagentStart` hook: the child's working directory and type. */ + subagentStarted(agentId: string, cwd: string, agentType: string): void { + const child = this.children.get(agentId); + if (!child) { + this.startedHooks.set(agentId, { cwd, agentType }); + return; + } + this.reportCwd(child, cwd); + } + + // --- Background work ---------------------------------------------------------- + + /** + * Stops the listed terminal or tool call of `sessionId` (`terminal/cancel` + * and `tool_call/cancel`). It ends when Claude Code reports its task stopped. + */ + async cancelItem( + sessionId: string, + target: { terminalId: string } | { toolCallId: string }, + ): Promise { + const listed = this.lists().get(sessionId) ?? []; + const taskId = + "terminalId" in target + ? listed.some((item) => item.type === "terminal" && item.terminalId === target.terminalId) + ? [...this.terminals].find(([, t]) => t.toolCallId === target.terminalId)?.[0] + : undefined + : listed.some((item) => item.type === "tool_call" && item.toolCallId === target.toolCallId) + ? [...this.toolCalls].find(([, t]) => t.toolCallId === target.toolCallId)?.[0] + : undefined; + if (taskId === undefined) return false; + await this.host.stopTask(taskId); + return true; + } + + /** + * The current state of the children and of the listed work, for a resume + * of the active session: each child's announcement, parent before child, + * with its current state, and each listed item's current update. + */ + currentState(): v2.UpdateSessionNotification[] { + const updates: v2.UpdateSessionNotification[] = []; + for (const child of this.parentsFirst()) { + updates.push({ + sessionId: child.parentSessionId, + update: { + ...this.announcement(child), + state: stateObject(this.childState(child), child.outcome), + }, + }); + } + for (const sessionId of [this.host.sessionId, ...this.parentsFirst().map((c) => c.sessionId)]) { + updates.push(...this.host.background.currentItems(sessionId)); + } + return updates; + } + + /** + * Claude Code's query ended: its tasks ended with its process. Terminals + * exit and background tool calls are cancelled; a child that worked ends + * `error`, as the root's work does. + */ + queryEnded(error: { code: number; message: string } | undefined): void { + for (const [taskId, terminal] of this.terminals) { + terminal.tail?.stop(); + if (error) this.exitTerminal(taskId); + } + if (!error) return; + for (const [taskId] of this.toolCalls) this.endToolCall(taskId, "stopped"); + for (const child of this.children.values()) { + if (child.working) this.endRun(child, { stopReason: "error", error }); + } + this.level = new Map(); + this.publish(); + } + + /** + * Publishes the `background` list of each session that changed, deeper + * sessions first, so a child's own list is current before its parent's + * list names or drops it. + */ + publish(): void { + const lists = this.lists(); + for (const child of [...this.parentsFirst()].reverse()) { + this.sendAll( + this.host.background.changed({ + sessionId: child.sessionId, + items: lists.get(child.sessionId) ?? [], + state: this.childState(child), + parentSessionId: child.parentSessionId, + }), + ); + } + this.sendAll( + this.host.background.changed({ + sessionId: this.host.sessionId, + items: lists.get(this.host.sessionId) ?? [], + state: this.host.rootState(), + }), + ); + } + + // --- Task events ---------------------------------------------------------------- + + private taskStarted(message: Extract): void { + const isAgent = message.task_type === "local_agent" || message.subagent_type !== undefined; + if (!isAgent) { + this.started.set(message.task_id, { + ...(message.tool_use_id !== undefined ? { toolUseId: message.tool_use_id } : {}), + ...(message.parent_task_id !== undefined ? { parentTaskId: message.parent_task_id } : {}), + ...(message.task_type !== undefined ? { taskType: message.task_type } : {}), + }); + return; + } + let child = this.children.get(message.task_id); + if (!child) { + // A child's parent is the subagent that launched it. One Claude Code + // no longer tracks, such as one from before a restart, cannot be + // placed: the child stays unexposed, its traffic the root's. + const parent = + message.parent_task_id !== undefined + ? this.children.get(message.parent_task_id) + : undefined; + if (message.parent_task_id !== undefined && !parent) return; + const hook = this.startedHooks.get(message.task_id); + this.startedHooks.delete(message.task_id); + const parentCwd = parent ? (parent.cwd ?? this.host.cwd) : this.host.cwd; + const cwd = hook && !sameDirectory(hook.cwd, parentCwd) ? hook.cwd : undefined; + child = { + sessionId: message.task_id, + parentSessionId: parent?.sessionId ?? this.host.sessionId, + launchToolUseId: message.tool_use_id, + title: message.description, + description: message.subagent_type ?? hook?.agentType, + foreground: message.is_backgrounded === false, + working: false, + reportedState: undefined, + outcome: undefined, + cancelled: false, + delegationReported: false, + openRequests: 0, + requestAborts: new Set(), + cwd, + output: new SessionOutput( + message.task_id, + cwd ?? parentCwd, + this.host.translator, + (update) => this.host.send({ sessionId: message.task_id, update }), + this.host.logger, + ), + }; + this.children.set(child.sessionId, child); + this.host.send({ sessionId: child.parentSessionId, update: this.announcement(child) }); + for (const waiter of this.announceWaiters.get(child.sessionId) ?? []) waiter(); + this.announceWaiters.delete(child.sessionId); + } else { + // A resume: the same child, again. A resumed subagent runs in the background. + child.foreground = message.is_backgrounded === false; + } + if (message.tool_use_id !== undefined) this.childByToolUse.set(message.tool_use_id, child); + this.startRun(child); + } + + private taskUpdated(message: Extract): void { + const { task_id: taskId, patch } = message; + const child = this.children.get(taskId); + if (patch.is_backgrounded !== undefined && child) { + child.foreground = !patch.is_backgrounded; + this.host.foregroundRequestsChanged(); + this.publish(); + } + switch (patch.status) { + case "completed": + case "failed": + this.taskEnded(taskId, patch.status, patch.error); + return; + case "killed": + this.taskEnded(taskId, "stopped"); + return; + case "paused": + case "running": + case "pending": { + const paused = patch.status === "paused"; + const toolCall = this.toolCalls.get(taskId); + if (toolCall && toolCall.paused !== paused) { + toolCall.paused = paused; + toolCall.output.toolCallStatus(toolCall.toolCallId, paused ? "paused" : "in_progress"); + } + // Claude Code can resume a subagent that ended without a new `task_started`. + if (patch.status === "running" && child && !child.working) this.startRun(child); + return; + } + default: + return; + } + } + + /** + * The task `taskId` ended. Claude Code can report one end twice (a + * terminal `task_updated` and a `task_notification`), so a second is a + * no-op. + */ + private taskEnded( + taskId: string, + status: "completed" | "failed" | "stopped", + error?: string, + ): void { + const child = this.children.get(taskId); + if (child) { + this.endRun( + child, + status === "completed" + ? { stopReason: "end_turn" } + : status === "stopped" + ? { stopReason: "cancelled" } + : { + stopReason: "error", + error: { code: -32603, message: error ?? "The subagent failed" }, + }, + ); + } + this.started.delete(taskId); + const terminal = this.terminals.get(taskId); + if (terminal && !terminal.ending) { + terminal.ending = true; + // The rest of the output goes out before the exit, and the list drops + // the terminal only after its exit. + void (terminal.tail?.finish() ?? Promise.resolve()).then(() => { + this.exitTerminal(taskId); + this.publish(); + }); + } + if (this.toolCalls.has(taskId)) this.endToolCall(taskId, status); + this.publish(); + } + + /** + * Claude Code's live background task set changed. Terminals and tool calls + * whose tasks it no longer holds ended, without saying how. + */ + private levelChanged( + tasks: Array<{ + task_id: string; + task_type: string; + description: string; + parent_task_id?: string; + ambient?: boolean; + }>, + ): void { + this.level = new Map( + tasks.map((task) => [ + task.task_id, + { + ambient: task.ambient === true, + taskType: task.task_type, + description: task.description, + ...(task.parent_task_id !== undefined ? { parentTaskId: task.parent_task_id } : {}), + }, + ]), + ); + for (const taskId of [...this.terminals.keys(), ...this.toolCalls.keys()]) { + if (!this.level.has(taskId)) this.taskEnded(taskId, "completed"); + } + this.publish(); + } + + // --- Children --------------------------------------------------------------------- + + private childOf(message: { parent_tool_use_id: string | null }): Child | undefined { + return message.parent_tool_use_id !== null + ? this.childByToolUse.get(message.parent_tool_use_id) + : undefined; + } + + private childSession(sessionId: string): Child | undefined { + return this.children.get(sessionId); + } + + /** + * A user message of a child's transcript: its tool results, or, first in + * a run, the delegation that its parent sent it, which goes out as an + * incoming `session_message`. + */ + private childUserMessage(child: Child, message: SDKUserMessage): void { + const content = message.message.content; + const blocks = + typeof content === "string" ? [{ type: "text" as const, text: content }] : content; + if (blocks.some((block) => block.type === "tool_result")) { + this.toolResults(child.output, { ...message, parent_tool_use_id: null }); + return; + } + if (child.delegationReported) return; + const text = blocks.flatMap((block) => + block.type === "text" ? [{ type: "text" as const, text: block.text }] : [], + ); + if (text.length === 0) return; + child.delegationReported = true; + this.host.send({ + sessionId: child.sessionId, + update: { + sessionUpdate: "session_message", + messageId: message.uuid ?? `${child.sessionId}:delegation`, + senderSessionId: child.parentSessionId, + recipientSessionId: child.sessionId, + content: text, + } as v2.SessionUpdate, + }); + } + + private startRun(child: Child): void { + if (child.working) return; + child.working = true; + child.cancelled = false; + child.delegationReported = false; + child.outcome = undefined; + this.reportChild(child); + this.publish(); + } + + /** A run of `child` ended: its unfinished tool calls end with it, then its idle. */ + private endRun(child: Child, outcome: IdleOutcome): void { + if (!child.working) return; + if (outcome.stopReason !== "end_turn") { + child.output.finishUnfinished(outcome.stopReason === "cancelled" ? "cancelled" : "failed"); + } + child.working = false; + child.outcome = outcome; + child.cancelled = false; + this.withdraw(child); + this.reportChild(child); + this.host.foregroundRequestsChanged(); + } + + private childState(child: Child): ChildState { + if (!child.working) return "idle"; + return child.openRequests > 0 ? "requires_action" : "running"; + } + + /** Sends the child's state on its stream and in its parent's mirror, when it changed. */ + private reportChild(child: Child): void { + const state = this.childState(child); + if (state === child.reportedState) return; + // A cancel withdrew the open requests: the run is stopping, and its idle follows. + if (child.reportedState === "requires_action" && state === "running" && child.cancelled) { + return; + } + child.reportedState = state; + const snapshot = stateObject(state, child.outcome); + this.host.send({ + sessionId: child.parentSessionId, + update: { sessionUpdate: "subagent_update", sessionId: child.sessionId, state: snapshot }, + }); + this.host.send({ + sessionId: child.sessionId, + update: { sessionUpdate: "state_update", ...snapshot } as v2.SessionUpdate, + }); + } + + private async childRequest( + child: Child, + request: v2.RequestPermissionRequest, + toolSignal: AbortSignal, + ): Promise { + const abort = new AbortController(); + const signal = AbortSignal.any([toolSignal, abort.signal]); + child.requestAborts.add(abort); + child.openRequests++; + this.reportChild(child); + this.host.foregroundRequestsChanged(); + try { + return await this.hostRequest(request, signal); + } catch (error) { + if (signal.aborted) return { outcome: { outcome: "cancelled" } }; + throw error; + } finally { + child.requestAborts.delete(abort); + child.openRequests--; + this.reportChild(child); + this.host.foregroundRequestsChanged(); + } + } + + /** Set by the session: sends a permission request to the client. */ + hostRequest!: ( + request: v2.RequestPermissionRequest, + signal: AbortSignal, + ) => Promise; + + /** Withdraws the open requests of a child whose run stops. */ + private withdraw(child: Child): void { + if (child.working) child.cancelled = true; + for (const abort of child.requestAborts) abort.abort(); + } + + /** The children whose runs the work of `sessionId` waits on, transitively. */ + private foregroundChildren(sessionId: string): Child[] { + const direct = [...this.children.values()].filter( + (child) => child.parentSessionId === sessionId && child.working && child.foreground, + ); + return direct.flatMap((child) => [child, ...this.foregroundChildren(child.sessionId)]); + } + + private reportCwd(child: Child, cwd: string): void { + const parent = this.children.get(child.parentSessionId); + const parentCwd = parent ? (parent.cwd ?? this.host.cwd) : this.host.cwd; + const next = sameDirectory(cwd, parentCwd) ? undefined : cwd; + if (next === child.cwd) return; + child.cwd = next; + this.host.send({ + sessionId: child.parentSessionId, + update: { sessionUpdate: "subagent_update", sessionId: child.sessionId, cwd: next ?? null }, + }); + } + + private announcement( + child: Child, + ): Extract { + return { + sessionUpdate: "subagent_update", + sessionId: child.sessionId, + title: child.title, + ...(child.description !== undefined ? { description: child.description } : {}), + ...(child.cwd !== undefined ? { cwd: child.cwd } : {}), + // `session/cancel` of the child stops its run (`stopTask`). + capabilities: { cancel: {} }, + }; + } + + /** The announced children, each after its parent. */ + private parentsFirst(): Child[] { + const ordered: Child[] = []; + const visit = (sessionId: string) => { + for (const child of this.children.values()) { + if (child.parentSessionId !== sessionId) continue; + ordered.push(child); + visit(child.sessionId); + } + }; + visit(this.host.sessionId); + return ordered; + } + + // --- Lists ------------------------------------------------------------------------ + + /** + * The `background` list of each session: its background terminals, tool + * calls and other tasks, and its children that work in the background or + * have background work of their own. A task that a tool call started is + * part of that call until the call returns, and is not listed. + */ + private lists(): Map { + const lists = new Map([[this.host.sessionId, []]]); + for (const child of this.children.values()) lists.set(child.sessionId, []); + const sessionOfTask = (taskId: string | undefined) => + (taskId !== undefined ? this.children.get(taskId)?.sessionId : undefined) ?? + this.host.sessionId; + // Listed until they end: a terminal's exit, or a tool call's final + // status, goes out before the list that drops it. + for (const terminal of this.terminals.values()) { + lists.get(terminal.output.sessionId)?.push({ + type: "terminal", + terminalId: terminal.toolCallId, + }); + } + for (const toolCall of this.toolCalls.values()) { + lists.get(toolCall.output.sessionId)?.push({ + type: "tool_call", + toolCallId: toolCall.toolCallId, + }); + } + for (const [taskId, task] of this.level) { + if (this.terminals.has(taskId) || this.toolCalls.has(taskId)) continue; + if (task.ambient || task.taskType === "local_bash" || task.taskType === "local_agent") { + continue; + } + const started = this.started.get(taskId); + if (!started || (started.toolUseId && !this.returned.has(started.toolUseId))) continue; + lists + .get(sessionOfTask(task.parentTaskId)) + ?.push({ type: "_claude/task", taskId, description: task.description }); + } + // Deeper children first: a child's own list is whole before its parent's reads it. + for (const child of [...this.parentsFirst()].reverse()) { + const inBackground = child.working && !child.foreground; + if (inBackground || (lists.get(child.sessionId)?.length ?? 0) > 0) { + lists.get(child.parentSessionId)?.push({ type: "subagent", sessionId: child.sessionId }); + } + } + return lists; + } + + private followOutput(taskId: string, outputFilePath: string | undefined): void { + const terminal = this.terminals.get(taskId); + if (!terminal || !outputFilePath) return; + terminal.tail = new BackgroundOutputTail(outputFilePath, async (output) => + terminal.output.emitV1([ + terminalOutput(terminal.output.sessionId, terminal.toolCallId, output), + ]), + ); + } + + private exitTerminal(taskId: string): void { + const terminal = this.terminals.get(taskId); + if (!terminal) return; + this.terminals.delete(taskId); + terminal.output.emitV1([ + { + sessionId: terminal.output.sessionId, + update: { + sessionUpdate: "tool_call_update", + toolCallId: terminal.toolCallId, + _meta: { + terminal_exit: { terminal_id: terminal.toolCallId, exit_code: null, signal: null }, + }, + }, + }, + ]); + } + + private endToolCall(taskId: string, status: "completed" | "failed" | "stopped"): void { + const toolCall = this.toolCalls.get(taskId); + if (!toolCall) return; + this.toolCalls.delete(taskId); + toolCall.output.toolCallStatus( + toolCall.toolCallId, + status === "stopped" ? "cancelled" : status, + ); + } + + private sendAll(notifications: v2.UpdateSessionNotification[]): void { + for (const notification of notifications) this.host.send(notification); + } +} + +/** + * Whether two paths name one directory, also through a symlink: a hook's + * `cwd` is the real path, such as `/private/tmp/project` for `/tmp/project`. + */ +function sameDirectory(left: string, right: string): boolean { + const real = (directory: string) => { + try { + return fs.realpathSync.native(directory); + } catch { + return path.resolve(directory); + } + }; + return path.resolve(left) === path.resolve(right) || real(left) === real(right); +} + +/** A child's state as a `StateUpdate`: an idle with how its last run ended. */ +function stateObject(state: ChildState, outcome: IdleOutcome | undefined): v2.StateUpdate { + switch (state) { + case "running": + return { state: "running" }; + case "requires_action": + return { state: "requires_action" }; + default: + return { state: "idle", ...(outcome ?? {}) } as v2.StateUpdate; + } +} + +/** The v1 update that gives a background command's terminal its output. */ +function terminalOutput( + sessionId: string, + terminalId: string, + output: BackgroundOutput, +): AcpSessionNotification { + const data = { terminal_id: terminalId, data: output.text }; + return { + sessionId, + update: { + sessionUpdate: "tool_call_update", + toolCallId: terminalId, + _meta: output.replaces ? { terminal_output: data } : { terminal_output_delta: data }, + }, + }; +} + +/** The error of a request on a child session: the client can only watch a child. */ +export function restrictedChild(sessionId: string, method: string): RequestError { + return RequestError.invalidParams( + { sessionId }, + `${sessionId} is a subagent session: the client cannot ${method} it. Its parent session runs it.`, + ); +} diff --git a/src/v2/agent.ts b/src/v2/agent.ts index 91ab61e8..17735f69 100644 --- a/src/v2/agent.ts +++ b/src/v2/agent.ts @@ -32,10 +32,8 @@ import { v2NewSessionResponse, v2ResumeSessionResponse, } from "./session.js"; -import { v2ChildStateUpdate, v2SessionUpdate } from "./session-update.js"; -import { V2Terminals } from "./terminal.js"; -import { V2ToolCallMeta } from "./tool-call-meta.js"; -import { v2RestartedToolCall } from "./tool-call.js"; +import { v2ChildStateUpdate } from "./session-update.js"; +import { replayClear, V2UpdateTranslator } from "./update-translator.js"; /** * The ACP v2 surface, for one connection. @@ -152,8 +150,7 @@ export function v2AgentApp( ) .onRequest(v2.methods.agent.session.close, async ({ params }) => { const response = await agent.closeSession(params); - client.terminals.forget(params.sessionId); - client.toolCallMeta.forget(params.sessionId); + client.translator.forget(params.sessionId); return response; }) .onRequest(v2.methods.agent.session.delete, ({ params }) => agent.deleteSession(params)) @@ -266,14 +263,11 @@ class V2ClientConnection implements AcpClient { */ private readonly replayedChildStates = new Map(); - /** The display terminals of the commands that the agent runs. */ - readonly terminals = new V2Terminals(); - - /** The `_meta` that the client stores for each tool call. */ - readonly toolCallMeta = new V2ToolCallMeta(); + /** Turns the agent's v1 updates into v2 updates (terminals, tool call `_meta`). */ + readonly translator = new V2UpdateTranslator(); /** The `background` list of each session's `state_update`s. */ - readonly background = new V2Background(this.terminals); + readonly background = new V2Background(this.translator.terminals); constructor( private readonly ctx: v2.AgentContext, @@ -350,10 +344,13 @@ class V2ClientConnection implements AcpClient { this.replayRoots.get(notification.sessionId) ?? notification.sessionId, ); } - const updates = this.v2Updates(notification.sessionId, update).flatMap((v2Update) => { - const clear = this.replayClear(notification.sessionId, v2Update); - return clear ? [clear, v2Update] : [v2Update]; - }); + const updates = this.translator + .updates(notification.sessionId, update, this.replays.has(notification.sessionId)) + .flatMap((v2Update) => { + const cleared = this.replays.get(notification.sessionId); + const clear = cleared && replayClear(cleared, v2Update); + return clear ? [clear, v2Update] : [v2Update]; + }); // A subagent's work state also goes to the child's own stream, after the // parent's copy. During a replay, only its last state goes, after the // replay (see `replayedChildStates`). @@ -376,64 +373,12 @@ class V2ClientConnection implements AcpClient { ); } - /** - * The v2 updates of a v1 update: for a tool call report, the updates of its - * terminal first (see {@link V2Terminals}), then the report itself, with the - * `_meta` keys that it changes (see {@link V2ToolCallMeta}), and during a - * replay the `_meta` of a tool call that the report cleared. - */ - private v2Updates( - sessionId: string, - update: AcpSessionNotification["update"], - ): v2.SessionUpdate[] { - if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") { - const v2Update = v2SessionUpdate(update); - return v2Update ? [v2Update] : []; - } - const { terminal, report } = this.terminals.split(sessionId, update); - if (!report) return terminal; - const starts = report.sessionUpdate === "tool_call"; - const replaying = this.replays.has(sessionId); - // A v1 `tool_call` starts the tool call afresh, but v2 only has updates, - // which keep each field they leave out. The client may already hold this - // id: from an earlier report on this connection, or, during a replay, from - // before it (a client that resumes a session it showed before). - const restarts = - starts && (replaying || this.toolCallMeta.reported(sessionId, report.toolCallId)); - const [reported, metaPatch] = this.toolCallMeta.apply(sessionId, report, starts, replaying); - const reportUpdate = restarts ? v2RestartedToolCall(reported) : v2SessionUpdate(reported); - const metaUpdate = metaPatch - ? v2SessionUpdate({ sessionUpdate: "tool_call_update", ...metaPatch }) - : undefined; - return [ - ...terminal, - ...(reportUpdate ? [reportUpdate] : []), - ...(metaUpdate ? [metaUpdate] : []), - ]; - } - - /** - * The update that clears the message of a replayed chunk, when it is the - * first replayed chunk of that message (see {@link replaying}). - */ - private replayClear(sessionId: string, update: v2.SessionUpdate): v2.SessionUpdate | undefined { - const cleared = this.replays.get(sessionId); - if (!cleared) return undefined; - const kind = MESSAGE_OF_CHUNK.get(update.sessionUpdate); - if (!kind) return undefined; - const { messageId } = update as { messageId: string }; - const key = `${kind} ${messageId}`; - if (cleared.has(key)) return undefined; - cleared.add(key); - return emptyMessage(kind, messageId); - } - async requestPermission( params: AcpPermissionRequest, signal?: AbortSignal, ): Promise { // The subject is an update of the tool call, with its stored `_meta`. - const toolCall = this.toolCallMeta.subject(params.sessionId, params.toolCall); + const toolCall = this.translator.toolCallMeta.subject(params.sessionId, params.toolCall); const response = await this.ctx.request( v2.methods.client.session.requestPermission, v2PermissionRequest({ ...params, toolCall }), @@ -472,28 +417,6 @@ class V2ClientConnection implements AcpClient { } } -/** The message update of each message chunk. */ -const MESSAGE_OF_CHUNK = new Map([ - ["user_message_chunk", "user_message"], - ["agent_message_chunk", "agent_message"], - ["agent_thought_chunk", "agent_thought"], -]); - -function emptyMessage( - kind: "user_message" | "agent_message" | "agent_thought", - messageId: string, -): v2.SessionUpdate { - const message = { messageId, content: [] }; - switch (kind) { - case "user_message": - return { ...message, sessionUpdate: kind }; - case "agent_message": - return { ...message, sessionUpdate: kind }; - default: - return { ...message, sessionUpdate: kind }; - } -} - function isExtensionMethod(method: string): method is v2.ExtensionMethod { return method.startsWith("_"); } diff --git a/src/v2/initialize.ts b/src/v2/initialize.ts index 076c7786..0b3d768b 100644 --- a/src/v2/initialize.ts +++ b/src/v2/initialize.ts @@ -145,7 +145,7 @@ export const V2_SESSION_CAPABILITIES: v2.SessionCapabilities = { }; /** v2 names the id of a method `methodId`, requires `type`, and lists `env` as name and value pairs. */ -function v2AuthMethod(method: AuthMethod): v2.AuthMethod { +export function v2AuthMethod(method: AuthMethod): v2.AuthMethod { if ("type" in method && method.type === "terminal") { const { id, env, ...terminal } = method; return { diff --git a/src/v2/update-translator.ts b/src/v2/update-translator.ts new file mode 100644 index 00000000..54d33382 --- /dev/null +++ b/src/v2/update-translator.ts @@ -0,0 +1,107 @@ +/** + * Turns the v1 session updates that the shared SDK-to-ACP mapping produces + * (`toAcpNotifications`) into the v2 updates of one connection. + * + * Both v2 cores use it: the bridge (`agent.ts`), which translates every update + * of `ClaudeAcpAgent`, and the native core (`src/v2-native/`), which maps the + * SDK stream itself. It holds the per-connection state that the translation + * needs: the display terminals of commands and the `_meta` the client stores + * for each tool call. + */ +import type * as v2 from "@agentclientprotocol/sdk/experimental/v2/unstable"; +import type { AcpSessionNotification } from "../acp-subagents.js"; +import { v2SessionUpdate } from "./session-update.js"; +import { V2Terminals } from "./terminal.js"; +import { V2ToolCallMeta } from "./tool-call-meta.js"; +import { v2RestartedToolCall } from "./tool-call.js"; + +export class V2UpdateTranslator { + /** The display terminals of the commands that the agent runs. */ + readonly terminals = new V2Terminals(); + + /** The `_meta` that the client stores for each tool call. */ + readonly toolCallMeta = new V2ToolCallMeta(); + + /** + * The v2 updates of a v1 update: for a tool call report, the updates of its + * terminal first (see {@link V2Terminals}), then the report itself, with the + * `_meta` keys that it changes (see {@link V2ToolCallMeta}), and during a + * replay the `_meta` of a tool call that the report cleared. + */ + updates( + sessionId: string, + update: AcpSessionNotification["update"], + replaying = false, + ): v2.SessionUpdate[] { + if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") { + const v2Update = v2SessionUpdate(update); + return v2Update ? [v2Update] : []; + } + const { terminal, report } = this.terminals.split(sessionId, update); + if (!report) return terminal; + const starts = report.sessionUpdate === "tool_call"; + // A v1 `tool_call` starts the tool call afresh, but v2 only has updates, + // which keep each field they leave out. The client may already hold this + // id: from an earlier report on this connection, or, during a replay, from + // before it (a client that resumes a session it showed before). + const restarts = + starts && (replaying || this.toolCallMeta.reported(sessionId, report.toolCallId)); + const [reported, metaPatch] = this.toolCallMeta.apply(sessionId, report, starts, replaying); + const reportUpdate = restarts ? v2RestartedToolCall(reported) : v2SessionUpdate(reported); + const metaUpdate = metaPatch + ? v2SessionUpdate({ sessionUpdate: "tool_call_update", ...metaPatch }) + : undefined; + return [ + ...terminal, + ...(reportUpdate ? [reportUpdate] : []), + ...(metaUpdate ? [metaUpdate] : []), + ]; + } + + /** Forgets the terminals and tool calls of a session, when it closes. */ + forget(sessionId: string): void { + this.terminals.forget(sessionId); + this.toolCallMeta.forget(sessionId); + } +} + +/** + * The update that clears the message of a replayed chunk, when it is the + * first replayed chunk of that message: a v2 client may still hold a message + * that a replay sends again, and chunks append to it. `cleared` holds the + * messages that the replay has cleared so far, and gains this one. + */ +export function replayClear( + cleared: Set, + update: v2.SessionUpdate, +): v2.SessionUpdate | undefined { + const kind = MESSAGE_OF_CHUNK.get(update.sessionUpdate); + if (!kind) return undefined; + const { messageId } = update as { messageId: string }; + const key = `${kind} ${messageId}`; + if (cleared.has(key)) return undefined; + cleared.add(key); + return emptyMessage(kind, messageId); +} + +/** The message update of each message chunk. */ +const MESSAGE_OF_CHUNK = new Map([ + ["user_message_chunk", "user_message"], + ["agent_message_chunk", "agent_message"], + ["agent_thought_chunk", "agent_thought"], +]); + +function emptyMessage( + kind: "user_message" | "agent_message" | "agent_thought", + messageId: string, +): v2.SessionUpdate { + const message = { messageId, content: [] }; + switch (kind) { + case "user_message": + return { ...message, sessionUpdate: kind }; + case "agent_message": + return { ...message, sessionUpdate: kind }; + default: + return { ...message, sessionUpdate: kind }; + } +}