From e13c48837679919318f5eaeaf522b3844eab220b Mon Sep 17 00:00:00 2001 From: Ben Brandt Date: Wed, 18 Nov 2026 16:39:57 +0100 Subject: [PATCH] fix: align v2 cancel dispatch and session setup with ACP --- src/examples/dual-version-agent.test.ts | 28 ++++++++++ src/examples/dual-version-agent.ts | 14 +++++ src/v2/acp.test.ts | 6 +- src/v2/bindings.ts | 69 ++++------------------- src/v2/stable/bindings.ts | 74 ++++--------------------- 5 files changed, 69 insertions(+), 122 deletions(-) diff --git a/src/examples/dual-version-agent.test.ts b/src/examples/dual-version-agent.test.ts index d7ffdafd..036d97c7 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); } +it("rejects unsupported v2 system prompts without creating or resuming a session", async () => { + await withExampleAgent(async ({ agent, sessionId, updates, send }) => { + const systemPrompt = { + mode: "append", + content: [{ type: "text", text: "Example instructions" }], + } satisfies v2.SystemPrompt; + + await expect( + agent.request(v2.methods.agent.session.new, { cwd, systemPrompt }), + ).rejects.toMatchObject({ code: -32602 }); + const { sessions } = await agent.request(v2.methods.agent.session.list, {}); + expect(sessions.map((session) => session.sessionId)).toEqual([sessionId]); + + await agent.request(v2.methods.agent.session.close, { sessionId }); + const before = updates.length; + await expect( + agent.request(v2.methods.agent.session.resume, { + sessionId, + cwd, + replayFrom: { type: "start" }, + systemPrompt, + }), + ).rejects.toMatchObject({ code: -32602 }); + await expect(send("still-closed")).rejects.toMatchObject({ code: -32002 }); + expect(updates.slice(before)).toEqual([]); + }); +}); + 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..ac5cb2ca 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); + rejectUnsupportedSystemPrompt(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); + rejectUnsupportedSystemPrompt(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. @@ -292,6 +294,18 @@ function requireSession(sessions: Set, sessionId: string): void { } } +/** The example does not advertise or apply client-supplied instructions. */ +function rejectUnsupportedSystemPrompt( + prompt: v2.SystemPrompt | null | undefined, +): void { + if (prompt != null) { + throw v2.RequestError.invalidParams( + undefined, + "systemPrompt is not supported", + ); + } +} + /** * This agent advertises no prompt capabilities (`capabilities.session.prompt` * is absent), so it accepts only the baseline `text` and `resource_link` diff --git a/src/v2/acp.test.ts b/src/v2/acp.test.ts index 9db77441..465ddc42 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 }); }); }); diff --git a/src/v2/bindings.ts b/src/v2/bindings.ts index a01a6785..610694f9 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) { @@ -2443,6 +2399,10 @@ 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. + * If the new session is not idle, send its `state_update` after the + * response. Clients may drop updates for a session they do not know yet. + * If the Agent cannot apply a supplied `systemPrompt` because of its + * value, reject with `-32602` without creating the session. */ [schema.AGENT_METHODS.session_new]: AgentRequestHandler< schema.NewSessionRequest, @@ -2598,6 +2558,8 @@ 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. + * If the Agent cannot apply a supplied `systemPrompt` because of its + * value, reject with `-32602` without resuming the session. */ [schema.AGENT_METHODS.session_resume]: AgentRequestHandler< schema.ResumeSessionRequest, @@ -2624,9 +2586,9 @@ export type AgentRequestHandlersByMethod = { * `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 has since reached a final status. If the session is unknown + * or inactive, throw `-32002` with `data.sessionId`. Without this handler + * or a `"*"` request fallback the app answers with `-32601`. */ [schema.AGENT_METHODS.tool_call_cancel]: AgentRequestHandler< schema.CancelToolCallRequest, @@ -2640,8 +2602,9 @@ export type AgentRequestHandlersByMethod = { * 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`. + * If the session is unknown or inactive, throw `-32002` with + * `data.sessionId`. Without this handler or a `"*"` request fallback the + * app answers with `-32601`. */ [schema.AGENT_METHODS.terminal_cancel]: AgentRequestHandler< schema.CancelTerminalRequest, @@ -3052,17 +3015,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 +3156,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/bindings.ts b/src/v2/stable/bindings.ts index 865dd2a9..e4d59f75 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) { @@ -2179,6 +2130,10 @@ 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. + * If the new session is not idle, send its `state_update` after the + * response. Clients may drop updates for a session they do not know yet. + * If the Agent cannot apply a supplied `systemPrompt` because of its + * value, reject with `-32602` without creating the session. */ [schema.AGENT_METHODS.session_new]: AgentRequestHandler< schema.NewSessionRequest, @@ -2270,6 +2225,8 @@ 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. + * If the Agent cannot apply a supplied `systemPrompt` because of its + * value, reject with `-32602` without resuming the session. */ [schema.AGENT_METHODS.session_resume]: AgentRequestHandler< schema.ResumeSessionRequest, @@ -2296,9 +2253,9 @@ export type AgentRequestHandlersByMethod = { * `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 has since reached a final status. If the session is unknown + * or inactive, throw `-32002` with `data.sessionId`. Without this handler + * or a `"*"` request fallback the app answers with `-32601`. */ [schema.AGENT_METHODS.tool_call_cancel]: AgentRequestHandler< schema.CancelToolCallRequest, @@ -2312,8 +2269,9 @@ export type AgentRequestHandlersByMethod = { * 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`. + * If the session is unknown or inactive, throw `-32002` with + * `data.sessionId`. Without this handler or a `"*"` request fallback the + * app answers with `-32601`. */ [schema.AGENT_METHODS.terminal_cancel]: AgentRequestHandler< schema.CancelTerminalRequest, @@ -2681,16 +2639,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 +2771,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,