From 0a46daa3382f82b8562cc9c9d901ea59ac7b9a83 Mon Sep 17 00:00:00 2001 From: Ben Brandt Date: Wed, 18 Nov 2026 16:45:20 +0100 Subject: [PATCH] fix: answer -32601 for tool_call/cancel and terminal/cancel without a handler Follows the v2 protocol docs that landed after schema v2.0.0-alpha.17. A v2 agent app without a handler for `tool_call/cancel` or `terminal/cancel` answered every such request with `-32602`. The protocol now says that `-32602` is the answer of an Agent that implements the method, and that such a request for an unknown session gets `-32002`, which the default could not know. An app without the handler does not implement the method, so it now answers `-32601`, as for any other method. An Agent that advertises `capabilities.cancel` on a tool call or terminal registers the handler. - `ActiveSession.isForBackgroundWork` compares a request's subject with the listed tool calls and terminals only for a request of its own session, because those IDs are scoped to the session that reports them. A request of a child session is for listed work when the child is a listed `subagent`. - The dual-version example agent rejects a `systemPrompt` with `-32602` and creates or resumes no session. It advertises no `session.systemPrompt`, and it used to ignore the field. - Handler docs: the error codes of the two cancel requests, `-32602` for a `systemPrompt` the Agent cannot apply, a new session's non-idle state after the `session/new` response, the `replay_complete` of each replayed child session, the child session rules of `session/cancel`, how long an `idempotencyKey` is recognized, and that a fork does not share its source's keys. --- src/examples/dual-version-agent.test.ts | 28 ++++ src/examples/dual-version-agent.ts | 18 +++ src/v2/acp.test.ts | 21 ++- src/v2/acp.ts | 8 +- src/v2/bindings.ts | 164 ++++++++++++----------- src/v2/stable/acp.ts | 8 +- src/v2/stable/bindings.ts | 166 ++++++++++++------------ 7 files changed, 252 insertions(+), 161 deletions(-) diff --git a/src/examples/dual-version-agent.test.ts b/src/examples/dual-version-agent.test.ts index d7ffdafd..17338f41 100644 --- a/src/examples/dual-version-agent.test.ts +++ b/src/examples/dual-version-agent.test.ts @@ -123,6 +123,34 @@ async function finishTurn(harness: Harness, permission: number): Promise { await until(() => idleStopReasons(harness.updates).length > idles, 10_000); } +describe("dual-version example agent: v2 session setup", () => { + it("rejects a systemPrompt with -32602 and creates no session", async () => { + await withExampleAgent(async ({ agent, sessionId }) => { + const systemPrompt: v2.SystemPrompt = { + mode: "append", + content: [{ type: "text", text: "Answer in French." }], + }; + + await expect( + agent.request(v2.methods.agent.session.new, { cwd, systemPrompt }), + ).rejects.toMatchObject({ code: -32602 }); + await expect( + agent.request(v2.methods.agent.session.resume, { + sessionId, + cwd, + systemPrompt, + }), + ).rejects.toMatchObject({ code: -32602 }); + + const { sessions } = await agent.request( + v2.methods.agent.session.list, + {}, + ); + expect(sessions.map((session) => session.sessionId)).toEqual([sessionId]); + }); + }); +}); + describe("dual-version example agent: v2 idempotency keys", () => { it("answers a retry with the original messageId and inserts one user message", async () => { await withExampleAgent(async (harness) => { diff --git a/src/examples/dual-version-agent.ts b/src/examples/dual-version-agent.ts index 94ada34d..dde74d49 100644 --- a/src/examples/dual-version-agent.ts +++ b/src/examples/dual-version-agent.ts @@ -97,6 +97,7 @@ const v2Agent = v2 .onRequest(v2.methods.agent.auth.logout, () => {}) .onRequest(v2.methods.agent.session.new, ({ params }) => { requireAbsoluteCwd(params.cwd); + rejectSystemPrompt(params.systemPrompt); v2.assertSupportedMcpServers( params.mcpServers, V2_CAPABILITIES.session?.mcp, @@ -130,6 +131,7 @@ const v2Agent = v2 }) .onRequest(v2.methods.agent.session.resume, async ({ params, client }) => { requireAbsoluteCwd(params.cwd); + rejectSystemPrompt(params.systemPrompt); const session = requireV2Session(params.sessionId); // `mcpServers` is the complete set for the resumed session; this agent // advertises no MCP transports, so any server is rejected. @@ -320,6 +322,22 @@ function requireAbsoluteCwd(cwd: string): void { } } +/** + * This agent advertises no `session.systemPrompt`, so it can apply none. A + * `systemPrompt` that the Agent cannot apply gets `-32602`, and the session is + * not created or resumed. + */ +function rejectSystemPrompt( + systemPrompt: v2.SystemPrompt | null | undefined, +): void { + if (systemPrompt != null) { + throw v2.RequestError.invalidParams( + { systemPrompt: { mode: systemPrompt.mode } }, + "systemPrompt is not supported: the agent does not advertise session.systemPrompt", + ); + } +} + /** * Inserts a prompt's user message and starts its turn. When the turn ends, * the next held prompt is inserted. diff --git a/src/v2/acp.test.ts b/src/v2/acp.test.ts index 9db77441..a46fe802 100644 --- a/src/v2/acp.test.ts +++ b/src/v2/acp.test.ts @@ -3024,7 +3024,7 @@ describe("v2 background work", () => { expect(stableSdk.BackgroundWork.isTerminal(terminal)).toBe(true); }); - it("answers tool_call/cancel and terminal/cancel with -32602 when the agent has no handler", async () => { + it("answers tool_call/cancel and terminal/cancel with -32601 when the agent has no handler", async () => { await client().connectWith(testAgent(), async (agentContext) => { await agentContext.request(methods.agent.initialize, { protocolVersion: PROTOCOL_VERSION, @@ -3035,13 +3035,13 @@ describe("v2 background work", () => { sessionId: "s", toolCallId: "c", }), - ).rejects.toMatchObject({ code: -32602, data: { toolCallId: "c" } }); + ).rejects.toMatchObject({ code: -32601 }); await expect( agentContext.request(methods.agent.terminal.cancel, { sessionId: "s", terminalId: "t", }), - ).rejects.toMatchObject({ code: -32602, data: { terminalId: "t" } }); + ).rejects.toMatchObject({ code: -32601 }); }); }); @@ -3183,6 +3183,7 @@ describe("v2 background work", () => { command: "npm run dev", capabilities: { cancel: {} }, }); + await send({ sessionUpdate: "subagent_update", sessionId: "child" }); await send({ sessionUpdate: "state_update", state: "idle", @@ -3190,16 +3191,30 @@ describe("v2 background work", () => { background: [ { type: "tool_call", toolCallId: "watch" }, { type: "terminal", terminalId: "dev" }, + { type: "subagent", sessionId: "child" }, ], }); expect(session.background).toEqual([ { type: "tool_call", toolCallId: "watch" }, { type: "terminal", terminalId: "dev" }, + { type: "subagent", sessionId: "child" }, ]); expect(session.isForBackgroundWork(forListedToolCall)).toBe(true); expect(session.isForBackgroundWork(forListedTerminal)).toBe(true); expect(session.isForBackgroundWork(forForeground)).toBe(false); expect(session.isForBackgroundWork(withoutSubject)).toBe(false); + // A request of a listed child is for listed work, whatever its + // subject. IDs are scoped to their session, so a request of another + // session with a listed ID of this one is not. + expect( + session.isForBackgroundWork({ ...forForeground, sessionId: "child" }), + ).toBe(true); + expect( + session.isForBackgroundWork({ + ...forListedToolCall, + sessionId: "grandchild", + }), + ).toBe(false); // Omitting `capabilities` leaves them unchanged. await send({ diff --git a/src/v2/acp.ts b/src/v2/acp.ts index 5cad3c0c..5fb93509 100644 --- a/src/v2/acp.ts +++ b/src/v2/acp.ts @@ -26,6 +26,10 @@ * without a successful response is truncated. Agents do not send it when * `replayFrom` is omitted or `null`. Do not send a second `session/resume` * with a `replayFrom` cursor for a session while the first one is pending. + * A replay can include child sessions. Each child that it announces gets its + * own `replay_complete` on its own `sessionId`, and the rule applies to each + * session separately: a parent's `replay_complete` says nothing about its + * children. * * A `session/resume` without `replayFrom` synchronizes the session's state, * not its conversation. The agent sends the current `state_update` and a @@ -40,7 +44,9 @@ * The `session/new` and `session/resume` responses carry the session's * `configOptions` and `availableCommands`. Each response replaces the lists * you hold, including lists from updates that arrived before it. An omitted - * list means none. + * list means none. A new session is `idle` until a `state_update` reports + * otherwise, and an agent whose new session is not `idle` sends that state + * after the `session/new` response. * * An agent announces a child session with `subagent_update` on its parent * and then sends the child's updates and requests with the child's diff --git a/src/v2/bindings.ts b/src/v2/bindings.ts index a01a6785..8a1450b2 100644 --- a/src/v2/bindings.ts +++ b/src/v2/bindings.ts @@ -12,7 +12,6 @@ import { Connection, Handled, HandlerRegistration, - isRecord, isV2RequestId, RequestError, respondWithNullId, @@ -472,49 +471,6 @@ async function waitUntilInitializedIncoming( return blockUninitializedIncoming(message); } -/** - * Answers `tool_call/cancel` and `terminal/cancel` with `-32602` when the app - * has no handler for them. Neither method has an initialize-time capability: - * an Agent that never advertises `capabilities.cancel` on a tool call or - * terminal has nothing to cancel, and the spec answers a request for an - * unknown or non-cancellable entity with `-32602`, not `-32601`. - */ -function defaultEntityCancelHandler( - handles: (method: string) => boolean, -): JsonRpcHandler { - const entities: Record = { - [schema.AGENT_METHODS.tool_call_cancel]: { - key: "toolCallId", - label: "tool call", - }, - [schema.AGENT_METHODS.terminal_cancel]: { - key: "terminalId", - label: "terminal", - }, - }; - return { - async handleMessage(message) { - const entity = Object.hasOwn(entities, message.method) - ? entities[message.method] - : undefined; - if (message.kind !== "request" || !entity || handles(message.method)) { - return Handled.no(message); - } - const id = isRecord(message.params) - ? message.params[entity.key] - : undefined; - return rejectIncoming( - message, - RequestError.invalidParams( - typeof id === "string" ? { [entity.key]: id } : undefined, - `the ${entity.label} is unknown or not cancellable`, - ), - ); - }, - describe: () => "default-entity-cancel", - }; -} - function agentInitializationGuard(): JsonRpcHandler { return { async handleMessage(message, cx) { @@ -1624,10 +1580,13 @@ export class ActiveSession { } /** - * Whether `request`'s `subject` references work in the latest `background` - * list: a listed tool call (by the subject's `toolCall.toolCallId`, or a - * command subject's `toolCallId`) or a listed terminal (by a command - * subject's `terminalId`). + * Whether `request` is for work in the latest `background` list of this + * session. For a request of this session, that is a listed tool call (by + * the subject's `toolCall.toolCallId`, or a command subject's `toolCallId`) + * or a listed terminal (by a command subject's `terminalId`). A request of + * another session is for listed work when that session is a listed + * `subagent`: tool call and terminal IDs are scoped to the session that + * reports them, so its subject is not compared with this session's items. * * `session/cancel` does not cover listed work, so permission requests for * it stay open. For the cancelled foreground work, the Agent stops waiting @@ -1637,8 +1596,10 @@ export class ActiveSession { * right after sending `session/cancel`, without waiting for * `$/cancel_request`, but only when it knows the request belongs to the * cancelled work. A `false` result alone does not establish that: it is - * also returned for requests without a `subject`, custom subjects, and any - * request while `background` is not reported. On `session/close`, the Agent + * also returned for requests without a `subject`, custom subjects, a + * request of a child session that is not listed, such as a listed child's + * own child, and any request while `background` is not reported. On + * `session/close`, the Agent * cancels every pending permission request in the session with * `$/cancel_request`. When an Agent sends a permission request with * `cancellationSignal` and `stopWaitingOnCancel: true`, aborting the signal @@ -1646,8 +1607,18 @@ export class ActiveSession { */ isForBackgroundWork(request: schema.RequestPermissionRequest): boolean { const background = this.latestBackground; + if (!background) { + return false; + } + if (request.sessionId !== this.sessionId) { + return background.some( + (work) => + guards.BackgroundWork.isSubagent(work) && + work.sessionId === request.sessionId, + ); + } const subject = request.subject; - if (!background || !subject) { + if (!subject) { return false; } let toolCallId: schema.ToolCallId | null | undefined; @@ -2443,6 +2414,18 @@ export type AgentRequestHandlersByMethod = { * `availableCommands` in the response when it has any. The response * replaces the lists the Client holds, including lists from updates that * arrived before it, and an omitted list means none. + * + * A new session is `idle` until a `state_update` reports otherwise. If the + * session is not `idle`, for example because it started work when it was + * created, send its `state_update` after the response. The app sends the + * response once this handler's promise settles, so a notification sent + * inside the handler goes out before it. + * + * Throw an error, and do not create the session, for a `systemPrompt` the + * Agent cannot apply. When the cause is the value, such as a mode the Agent + * does not advertise in `session.systemPrompt`, an unsupported content + * block type, or content over the Agent's limits, the error is `-32602`. + * The app passes such a value to this handler unchanged. */ [schema.AGENT_METHODS.session_new]: AgentRequestHandler< schema.NewSessionRequest, @@ -2481,9 +2464,12 @@ export type AgentRequestHandlersByMethod = { * pending request with the key, withdraw the prompt when it is not * inserted yet and answer every pending request for the key with `-32800`. * - * Recognize a key for as long as the message it belongs to is retained, on - * any connection where the session is active. Do not echo keys in session - * updates, `session/list` results, or replayed history. + * A key lasts as long as its message. For a message that is retained, + * recognize the key for as long as the message is, across connections and + * Agent restarts. For a message that is not retained, such as a locally + * handled command, recognize the key while the session stays active on a + * connection. Do not echo keys in session updates, `session/list` results, + * or replayed history. */ [schema.AGENT_METHODS.session_prompt]: AgentRequestHandler< schema.PromptRequest, @@ -2509,7 +2495,8 @@ export type AgentRequestHandlersByMethod = { * Agent did not announce on the source session, no longer accepts, or * whose `capabilities` do not include `fork`. Do not fork the whole session * in that case. The new session does not inherit the source session's - * cursors. + * cursors, or the `idempotencyKey`s of its prompts: the same key in the + * new session names an unrelated submission. */ [schema.AGENT_METHODS.session_fork]: AgentRequestHandler< schema.ForkSessionRequest, @@ -2577,6 +2564,14 @@ export type AgentRequestHandlersByMethod = { * replay cannot be finished. Throw `-32602` for an unsupported cursor, * without replaying anything. * + * A replay can include the history of child sessions. Each child that the + * replay announces with `subagent_update` gets its own `replay_complete` + * exactly once, on its own `sessionId`, after its announcement and its + * last replayed update, also when it has no replayed history. The same + * rules then apply to each session separately, and no session waits for + * another. A `subagent_update` is an update of the parent session, so the + * parent's `replay_complete` separates a replayed one from a current one. + * * To replay an entity from its beginning as chunks, first send that * entity's update with the same ID and the chunked field emptied: * `content: []` on `user_message`, `agent_message`, `agent_thought`, @@ -2598,6 +2593,11 @@ export type AgentRequestHandlersByMethod = { * Return the session's `configOptions` and `availableCommands` in the * response when it has any. The response replaces the lists the Client * holds. + * + * A `systemPrompt` the Agent cannot apply fails the request as on + * `session/new`, with `-32602` when the cause is the value, and the session + * is not resumed. Throw `-32602` for a child session's `sessionId`: the + * Client resumes a child through the session it created or resumed. */ [schema.AGENT_METHODS.session_resume]: AgentRequestHandler< schema.ResumeSessionRequest, @@ -2618,30 +2618,43 @@ export type AgentRequestHandlersByMethod = { schema.CloseSessionResponse | void >; /** - * Handles `tool_call/cancel`. + * Handles `tool_call/cancel`. An Agent that advertises `capabilities.cancel` + * on a tool call needs this handler. Without it (and without a `"*"` + * request fallback), the app answers `-32601`, as for any method it does + * not implement. * * Respond once the cancellation is accepted, then confirm it with a - * `tool_call_update` to a final status. Throw `-32602` for a tool call - * that is unknown, already final, or not cancellable. This includes a - * request the Client sends again after the first one was accepted and the - * tool call has since reached a final status. Without this handler (and - * without a `"*"` request fallback), the app answers every - * `tool_call/cancel` with `-32602`. + * `tool_call_update` to a final status. Throw `-32602`, not `-32601`, for a + * tool call that is unknown, already final, or does not advertise `cancel`. + * This includes a request the Client sends again after the first one was + * accepted and the tool call has since reached a final status. + * + * Throw `-32002` with `data.sessionId` (`RequestError.sessionNotFound`) for + * a session that does not exist or is not active on the connection. A child + * session that the Agent announced with `subagent_update` is not unknown: + * `sessionId` names the child for a tool call that the child reports. */ [schema.AGENT_METHODS.tool_call_cancel]: AgentRequestHandler< schema.CancelToolCallRequest, schema.CancelToolCallResponse | void >; /** - * Handles `terminal/cancel`. + * Handles `terminal/cancel`. An Agent that advertises `capabilities.cancel` + * on a terminal needs this handler. Without it (and without a `"*"` request + * fallback), the app answers `-32601`, as for any method it does not + * implement. * * Respond once the cancellation is accepted, then confirm it with a * `terminal_update` that sets `exitStatus`. Cancelling does not release the - * terminal. Throw `-32602` for a terminal that is unknown, has already - * exited, or is not cancellable. This includes a request the Client sends - * again after the first one was accepted and the process has since exited. - * Without this handler (and without a `"*"` request fallback), the app - * answers every `terminal/cancel` with `-32602`. + * terminal. Throw `-32602`, not `-32601`, for a terminal that is unknown, + * has already exited, or does not advertise `cancel`. This includes a + * request the Client sends again after the first one was accepted and the + * process has since exited. + * + * Throw `-32002` with `data.sessionId` (`RequestError.sessionNotFound`) for + * a session that does not exist or is not active on the connection. A child + * session that the Agent announced with `subagent_update` is not unknown: + * `sessionId` names the child for a terminal that the child reports. */ [schema.AGENT_METHODS.terminal_cancel]: AgentRequestHandler< schema.CancelTerminalRequest, @@ -2687,6 +2700,13 @@ export type AgentNotificationHandlersByMethod = { * `$/cancel_request` and rejects the request promise with `-32800` without * waiting for the Client's answer. Work in the latest `background` list * keeps running. + * + * `sessionId` can name a child session. Cancel the child's foreground + * work only while the child advertises `capabilities.cancel`, and ignore + * the notification otherwise. Cancelling a session, parent or child, also + * cancels the descendant work that the cancelled work is waiting on, and + * the pending requests of the descendants it stops are cancelled with + * `$/cancel_request` too. A child that keeps running keeps its requests. */ [schema.AGENT_METHODS .session_cancel]: AgentNotificationHandler; @@ -3052,17 +3072,10 @@ export class AgentApp { private readonly builder = Connection.builder(); private readonly connectHandlers: AgentConnectHandler[] = []; private readonly fallbackKinds = new Set<"request" | "notification">(); - private readonly requestMethods = new Set(); private hasInitializeHandler = false; constructor(options: AppOptions = {}) { this.builder.withHandler(agentInitializationGuard()); - this.builder.withHandler( - defaultEntityCancelHandler( - (method) => - this.requestMethods.has(method) || this.fallbackKinds.has("request"), - ), - ); if (options.name) { this.builder.name(options.name); } @@ -3200,7 +3213,6 @@ export class AgentApp { if (method === schema.AGENT_METHODS.initialize) { this.hasInitializeHandler = true; } - this.requestMethods.add(method); return this.request( spec as AcpRequestSpec, handlerOrParams as AgentRequestHandler, diff --git a/src/v2/stable/acp.ts b/src/v2/stable/acp.ts index 1986d130..b393aaef 100644 --- a/src/v2/stable/acp.ts +++ b/src/v2/stable/acp.ts @@ -27,6 +27,10 @@ * without a successful response is truncated. Agents do not send it when * `replayFrom` is omitted or `null`. Do not send a second `session/resume` * with a `replayFrom` cursor for a session while the first one is pending. + * A replay can include child sessions. Each child that it announces gets its + * own `replay_complete` on its own `sessionId`, and the rule applies to each + * session separately: a parent's `replay_complete` says nothing about its + * children. * * A `session/resume` without `replayFrom` synchronizes the session's state, * not its conversation. The agent sends the current `state_update` and a @@ -41,7 +45,9 @@ * The `session/new` and `session/resume` responses carry the session's * `configOptions` and `availableCommands`. Each response replaces the lists * you hold, including lists from updates that arrived before it. An omitted - * list means none. + * list means none. A new session is `idle` until a `state_update` reports + * otherwise, and an agent whose new session is not `idle` sends that state + * after the `session/new` response. * * An agent announces a child session with `subagent_update` on its parent * and then sends the child's updates and requests with the child's diff --git a/src/v2/stable/bindings.ts b/src/v2/stable/bindings.ts index 865dd2a9..fb382bc1 100644 --- a/src/v2/stable/bindings.ts +++ b/src/v2/stable/bindings.ts @@ -13,7 +13,6 @@ import { Connection, Handled, HandlerRegistration, - isRecord, isV2RequestId, RequestError, respondWithNullId, @@ -434,54 +433,6 @@ async function waitUntilInitializedIncoming( } return blockUninitializedIncoming(message); } -/** - * Answers `tool_call/cancel` and `terminal/cancel` with `-32602` when the app - * has no handler for them. Neither method has an initialize-time capability: - * an Agent that never advertises `capabilities.cancel` on a tool call or - * terminal has nothing to cancel, and the spec answers a request for an - * unknown or non-cancellable entity with `-32602`, not `-32601`. - */ -function defaultEntityCancelHandler( - handles: (method: string) => boolean, -): JsonRpcHandler { - const entities: Record< - string, - { - key: string; - label: string; - } - > = { - [schema.AGENT_METHODS.tool_call_cancel]: { - key: "toolCallId", - label: "tool call", - }, - [schema.AGENT_METHODS.terminal_cancel]: { - key: "terminalId", - label: "terminal", - }, - }; - return { - async handleMessage(message) { - const entity = Object.hasOwn(entities, message.method) - ? entities[message.method] - : undefined; - if (message.kind !== "request" || !entity || handles(message.method)) { - return Handled.no(message); - } - const id = isRecord(message.params) - ? message.params[entity.key] - : undefined; - return rejectIncoming( - message, - RequestError.invalidParams( - typeof id === "string" ? { [entity.key]: id } : undefined, - `the ${entity.label} is unknown or not cancellable`, - ), - ); - }, - describe: () => "default-entity-cancel", - }; -} function agentInitializationGuard(): JsonRpcHandler { return { async handleMessage(message, cx) { @@ -1512,10 +1463,13 @@ export class ActiveSession { return this.latestBackground; } /** - * Whether `request`'s `subject` references work in the latest `background` - * list: a listed tool call (by the subject's `toolCall.toolCallId`, or a - * command subject's `toolCallId`) or a listed terminal (by a command - * subject's `terminalId`). + * Whether `request` is for work in the latest `background` list of this + * session. For a request of this session, that is a listed tool call (by + * the subject's `toolCall.toolCallId`, or a command subject's `toolCallId`) + * or a listed terminal (by a command subject's `terminalId`). A request of + * another session is for listed work when that session is a listed + * `subagent`: tool call and terminal IDs are scoped to the session that + * reports them, so its subject is not compared with this session's items. * * `session/cancel` does not cover listed work, so permission requests for * it stay open. For the cancelled foreground work, the Agent stops waiting @@ -1525,8 +1479,10 @@ export class ActiveSession { * right after sending `session/cancel`, without waiting for * `$/cancel_request`, but only when it knows the request belongs to the * cancelled work. A `false` result alone does not establish that: it is - * also returned for requests without a `subject`, custom subjects, and any - * request while `background` is not reported. On `session/close`, the Agent + * also returned for requests without a `subject`, custom subjects, a + * request of a child session that is not listed, such as a listed child's + * own child, and any request while `background` is not reported. On + * `session/close`, the Agent * cancels every pending permission request in the session with * `$/cancel_request`. When an Agent sends a permission request with * `cancellationSignal` and `stopWaitingOnCancel: true`, aborting the signal @@ -1534,8 +1490,18 @@ export class ActiveSession { */ isForBackgroundWork(request: schema.RequestPermissionRequest): boolean { const background = this.latestBackground; + if (!background) { + return false; + } + if (request.sessionId !== this.sessionId) { + return background.some( + (work) => + guards.BackgroundWork.isSubagent(work) && + work.sessionId === request.sessionId, + ); + } const subject = request.subject; - if (!background || !subject) { + if (!subject) { return false; } let toolCallId: schema.ToolCallId | null | undefined; @@ -2179,6 +2145,18 @@ export type AgentRequestHandlersByMethod = { * `availableCommands` in the response when it has any. The response * replaces the lists the Client holds, including lists from updates that * arrived before it, and an omitted list means none. + * + * A new session is `idle` until a `state_update` reports otherwise. If the + * session is not `idle`, for example because it started work when it was + * created, send its `state_update` after the response. The app sends the + * response once this handler's promise settles, so a notification sent + * inside the handler goes out before it. + * + * Throw an error, and do not create the session, for a `systemPrompt` the + * Agent cannot apply. When the cause is the value, such as a mode the Agent + * does not advertise in `session.systemPrompt`, an unsupported content + * block type, or content over the Agent's limits, the error is `-32602`. + * The app passes such a value to this handler unchanged. */ [schema.AGENT_METHODS.session_new]: AgentRequestHandler< schema.NewSessionRequest, @@ -2217,9 +2195,12 @@ export type AgentRequestHandlersByMethod = { * pending request with the key, withdraw the prompt when it is not * inserted yet and answer every pending request for the key with `-32800`. * - * Recognize a key for as long as the message it belongs to is retained, on - * any connection where the session is active. Do not echo keys in session - * updates, `session/list` results, or replayed history. + * A key lasts as long as its message. For a message that is retained, + * recognize the key for as long as the message is, across connections and + * Agent restarts. For a message that is not retained, such as a locally + * handled command, recognize the key while the session stays active on a + * connection. Do not echo keys in session updates, `session/list` results, + * or replayed history. */ [schema.AGENT_METHODS.session_prompt]: AgentRequestHandler< schema.PromptRequest, @@ -2249,6 +2230,14 @@ export type AgentRequestHandlersByMethod = { * replay cannot be finished. Throw `-32602` for an unsupported cursor, * without replaying anything. * + * A replay can include the history of child sessions. Each child that the + * replay announces with `subagent_update` gets its own `replay_complete` + * exactly once, on its own `sessionId`, after its announcement and its + * last replayed update, also when it has no replayed history. The same + * rules then apply to each session separately, and no session waits for + * another. A `subagent_update` is an update of the parent session, so the + * parent's `replay_complete` separates a replayed one from a current one. + * * To replay an entity from its beginning as chunks, first send that * entity's update with the same ID and the chunked field emptied: * `content: []` on `user_message`, `agent_message`, `agent_thought`, @@ -2270,6 +2259,11 @@ export type AgentRequestHandlersByMethod = { * Return the session's `configOptions` and `availableCommands` in the * response when it has any. The response replaces the lists the Client * holds. + * + * A `systemPrompt` the Agent cannot apply fails the request as on + * `session/new`, with `-32602` when the cause is the value, and the session + * is not resumed. Throw `-32602` for a child session's `sessionId`: the + * Client resumes a child through the session it created or resumed. */ [schema.AGENT_METHODS.session_resume]: AgentRequestHandler< schema.ResumeSessionRequest, @@ -2290,30 +2284,43 @@ export type AgentRequestHandlersByMethod = { schema.CloseSessionResponse | void >; /** - * Handles `tool_call/cancel`. + * Handles `tool_call/cancel`. An Agent that advertises `capabilities.cancel` + * on a tool call needs this handler. Without it (and without a `"*"` + * request fallback), the app answers `-32601`, as for any method it does + * not implement. * * Respond once the cancellation is accepted, then confirm it with a - * `tool_call_update` to a final status. Throw `-32602` for a tool call - * that is unknown, already final, or not cancellable. This includes a - * request the Client sends again after the first one was accepted and the - * tool call has since reached a final status. Without this handler (and - * without a `"*"` request fallback), the app answers every - * `tool_call/cancel` with `-32602`. + * `tool_call_update` to a final status. Throw `-32602`, not `-32601`, for a + * tool call that is unknown, already final, or does not advertise `cancel`. + * This includes a request the Client sends again after the first one was + * accepted and the tool call has since reached a final status. + * + * Throw `-32002` with `data.sessionId` (`RequestError.sessionNotFound`) for + * a session that does not exist or is not active on the connection. A child + * session that the Agent announced with `subagent_update` is not unknown: + * `sessionId` names the child for a tool call that the child reports. */ [schema.AGENT_METHODS.tool_call_cancel]: AgentRequestHandler< schema.CancelToolCallRequest, schema.CancelToolCallResponse | void >; /** - * Handles `terminal/cancel`. + * Handles `terminal/cancel`. An Agent that advertises `capabilities.cancel` + * on a terminal needs this handler. Without it (and without a `"*"` request + * fallback), the app answers `-32601`, as for any method it does not + * implement. * * Respond once the cancellation is accepted, then confirm it with a * `terminal_update` that sets `exitStatus`. Cancelling does not release the - * terminal. Throw `-32602` for a terminal that is unknown, has already - * exited, or is not cancellable. This includes a request the Client sends - * again after the first one was accepted and the process has since exited. - * Without this handler (and without a `"*"` request fallback), the app - * answers every `terminal/cancel` with `-32602`. + * terminal. Throw `-32602`, not `-32601`, for a terminal that is unknown, + * has already exited, or does not advertise `cancel`. This includes a + * request the Client sends again after the first one was accepted and the + * process has since exited. + * + * Throw `-32002` with `data.sessionId` (`RequestError.sessionNotFound`) for + * a session that does not exist or is not active on the connection. A child + * session that the Agent announced with `subagent_update` is not unknown: + * `sessionId` names the child for a terminal that the child reports. */ [schema.AGENT_METHODS.terminal_cancel]: AgentRequestHandler< schema.CancelTerminalRequest, @@ -2349,6 +2356,13 @@ export type AgentNotificationHandlersByMethod = { * `$/cancel_request` and rejects the request promise with `-32800` without * waiting for the Client's answer. Work in the latest `background` list * keeps running. + * + * `sessionId` can name a child session. Cancel the child's foreground + * work only while the child advertises `capabilities.cancel`, and ignore + * the notification otherwise. Cancelling a session, parent or child, also + * cancels the descendant work that the cancelled work is waiting on, and + * the pending requests of the descendants it stops are cancelled with + * `$/cancel_request` too. A child that keeps running keeps its requests. */ [schema.AGENT_METHODS .session_cancel]: AgentNotificationHandler; @@ -2681,16 +2695,9 @@ export class AgentApp { private readonly builder = Connection.builder(); private readonly connectHandlers: AgentConnectHandler[] = []; private readonly fallbackKinds = new Set<"request" | "notification">(); - private readonly requestMethods = new Set(); private hasInitializeHandler = false; constructor(options: AppOptions = {}) { this.builder.withHandler(agentInitializationGuard()); - this.builder.withHandler( - defaultEntityCancelHandler( - (method) => - this.requestMethods.has(method) || this.fallbackKinds.has("request"), - ), - ); if (options.name) { this.builder.name(options.name); } @@ -2820,7 +2827,6 @@ export class AgentApp { if (method === schema.AGENT_METHODS.initialize) { this.hasInitializeHandler = true; } - this.requestMethods.add(method); return this.request( spec as AcpRequestSpec, handlerOrParams as AgentRequestHandler,