Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions src/examples/dual-version-agent.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,34 @@ async function finishTurn(harness: Harness, permission: number): Promise<void> {
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) => {
Expand Down
14 changes: 14 additions & 0 deletions src/examples/dual-version-agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -292,6 +294,18 @@ function requireSession(sessions: Set<string>, 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`
Expand Down
6 changes: 3 additions & 3 deletions src/v2/acp.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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 });
});
});

Expand Down
69 changes: 12 additions & 57 deletions src/v2/bindings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import {
Connection,
Handled,
HandlerRegistration,
isRecord,
isV2RequestId,
RequestError,
respondWithNullId,
Expand Down Expand Up @@ -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<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) {
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -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<string>();
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);
}
Expand Down Expand Up @@ -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<unknown, unknown, unknown>,
handlerOrParams as AgentRequestHandler<unknown, unknown>,
Expand Down
74 changes: 12 additions & 62 deletions src/v2/stable/bindings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import {
Connection,
Handled,
HandlerRegistration,
isRecord,
isV2RequestId,
RequestError,
respondWithNullId,
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -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<string>();
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);
}
Expand Down Expand Up @@ -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<unknown, unknown, unknown>,
handlerOrParams as AgentRequestHandler<unknown, unknown>,
Expand Down
Loading