Files
claude-agent-acp/src/v2/session.ts
Ben Brandt d2ef490a31 fix: validate session, prompt, config, and auth requests per the latest ACP spec (#1495)
Request validation from the ACP schema v1.28.0 / v2.0.0-alpha.11 review.
Each change has a test.

**Paths**
- `session/list` rejects a relative `cwd` with -32602. Without a session
index it passes `includeWorktrees: false`, so the filter matches only
sessions of exactly that directory, not other git worktrees of the same
repo.
- Resume, load and fork check `cwd` and `additionalDirectories` before
anything else. Before, a resume with a bad `cwd` tore down the live
session and then failed, and a fork copied the transcript first.
- Relative `additionalDirectories` entries are rejected with -32602.

**Session setup (v2)**
- Uses the SDK's `assertSupportedMcpServers`, which also rejects
duplicate MCP server names with -32602.
- Rejects an empty `prompt` with -32602.
- The v2 initialize response no longer advertises the AIR `asyncTasks`
capability or the `goal` entry, since the v2 app has no handlers for
`_session/async_task/stop` or `_session/goal`. v1 AIR is unchanged.

**Errors**
- `session/fork` of an unknown session returns -32002 with
`data.sessionId` instead of -32603. This matches the Claude SDK's
"Session … not found" and "Invalid sessionId" messages.
- `authenticate` with an unknown `methodId` returns -32602 instead of
-32603.
- `set_config_option` rejects a value whose type doesn't match the
advertised option type. A `type: "boolean"` option takes `true`/`false`,
and a select option takes a string. Model aliases such as `"opus"` are
still accepted.
- An AIR `session/delete` of a session that has no transcript now
succeeds instead of failing with a generic error.

**Prompts and commands**
- v1 `session/prompt` rejects `audio` and unknown content blocks with
-32602 before queueing them. Before, they were silently dropped.
- Advertised command names that contain whitespace are dropped, and of
duplicate names only the first is kept.
- The `/mcp:server:prompt` rewrite now accepts arguments that span
lines, and applies only to the first text block.
2026-10-30 16:03:58 +01:00

195 lines
7.1 KiB
TypeScript

/**
* The ACP v2 session lifecycle, expressed through the v1 session methods of
* `ClaudeAcpAgent`: v2 requests become the v1 requests that the agent serves,
* and its v1 responses become v2 responses.
*/
import {
RequestError,
type AvailableCommand,
type ForkSessionRequest,
type LoadSessionRequest,
type McpServer,
type NewSessionRequest,
type NewSessionResponse,
type ResumeSessionRequest,
type ResumeSessionResponse,
type SessionConfigOption,
type SessionConfigSelectGroup,
type SessionConfigSelectOptions,
type SetSessionConfigOptionRequest,
type SystemPrompt,
} from "@agentclientprotocol/sdk/unstable";
import * as v2 from "@agentclientprotocol/sdk/experimental/v2/unstable";
import { V2_SESSION_CAPABILITIES } from "./initialize.js";
import { v1ContentBlock } from "./prompt.js";
export function v1NewSessionRequest(params: v2.NewSessionRequest): NewSessionRequest {
const { mcpServers, systemPrompt, ...request } = params;
// v1 requires the list; v2 treats an omitted list as an empty one.
return {
...request,
mcpServers: v1McpServers(mcpServers) ?? [],
...v1SystemPromptField(systemPrompt),
};
}
/**
* The v1 request that a v2 `session/resume` means.
*
* v2 restores a session with `session/resume` and replays its history only
* when `replayFrom` asks for it. v1 has two methods: `session/resume`, which
* never replays, and `session/load`, which replays the whole history before it
* responds. `replayFrom: { type: "start" }` is the second; a cursor that
* starts elsewhere is rejected.
*/
export function v1RestoreSessionRequest(
params: v2.ResumeSessionRequest,
):
| { method: "resume"; request: ResumeSessionRequest }
| { method: "load"; request: LoadSessionRequest } {
const { replayFrom, mcpServers, systemPrompt, ...rest } = params;
const request = { ...rest, ...v1SystemPromptField(systemPrompt) };
if (replayFrom == null) {
return {
method: "resume",
request: { ...request, ...(mcpServers ? { mcpServers: v1McpServers(mcpServers) } : {}) },
};
}
const servers = v1McpServers(mcpServers);
if (replayFrom.type !== "start") {
throw RequestError.invalidParams(
{ replayFrom },
`Replaying from a ${replayFrom.type} cursor is not supported`,
);
}
return {
method: "load",
request: { ...request, mcpServers: servers ?? [] },
};
}
/**
* The v1 request of a v2 `session/fork`. In both versions the agent's fork
* returns a session that the client can prompt, with its config options.
*/
export function v1ForkSessionRequest(params: v2.ForkSessionRequest): ForkSessionRequest {
const { mcpServers, systemPrompt, ...request } = params;
return {
...request,
...(mcpServers ? { mcpServers: v1McpServers(mcpServers) } : {}),
...v1SystemPromptField(systemPrompt),
};
}
/**
* The v1 `systemPrompt`. Its content converts like prompt content: a v2
* annotation audience can be any string, and v1 takes only `user` or `assistant`.
*/
function v1SystemPromptField(systemPrompt: v2.SystemPrompt | null | undefined): {
systemPrompt?: SystemPrompt;
} {
if (systemPrompt == null) return {};
return { systemPrompt: { ...systemPrompt, content: systemPrompt.content.map(v1ContentBlock) } };
}
/** v2 drops `modes`: the session mode is the `mode` config option, which the agent always lists. */
export function v2NewSessionResponse(response: NewSessionResponse): v2.NewSessionResponse {
return { sessionId: response.sessionId, ...v2ResumeSessionResponse(response) };
}
export function v2ResumeSessionResponse(response: ResumeSessionResponse): v2.ResumeSessionResponse {
return {
...v2ConfigOptionsField(response.configOptions),
...(response._meta != null ? { _meta: response._meta } : {}),
};
}
/** v2 tags a select value with `type: "id"`; v1 leaves it untagged. */
export function v1SetSessionConfigOptionRequest(
params: v2.SetSessionConfigOptionRequest,
): SetSessionConfigOptionRequest {
const request = {
sessionId: params.sessionId,
configId: params.configId,
...(params._meta != null ? { _meta: params._meta } : {}),
};
if (v2.SetSessionConfigOptionRequest.isId(params)) {
return { ...request, value: params.value };
}
if (v2.SetSessionConfigOptionRequest.isBoolean(params)) {
return { ...request, type: "boolean", value: params.value };
}
throw RequestError.invalidParams(
{ type: params.type },
`Config option values of type ${params.type} are not supported`,
);
}
/** v2 names the id of an option `configId` and the id of a select group `groupId`. */
export function v2ConfigOptions(options: SessionConfigOption[]): v2.SessionConfigOption[] {
return options.map((option) => {
const { id, ...rest } = option;
if (rest.type === "select") {
return { ...rest, configId: id, options: v2SelectOptions(rest.options) };
}
return { ...rest, configId: id };
});
}
function v2SelectOptions(options: SessionConfigSelectOptions): v2.SessionConfigSelectOptions {
if (!isGrouped(options)) return options;
return options.map(({ group, ...selectGroup }) => ({ ...selectGroup, groupId: group }));
}
function isGrouped(options: SessionConfigSelectOptions): options is SessionConfigSelectGroup[] {
return options.some((entry) => "group" in entry);
}
/**
* v2 tags each command with `type: "command"` and its free-text input with
* `type: "text"`. A receiver drops a command without the `type` tag.
*/
export function v2AvailableCommands(commands: AvailableCommand[]): v2.AvailableCommand[] {
return commands.map(({ input, ...command }) => ({
type: "command",
...command,
...(input != null ? { input: { type: "text", ...input } } : {}),
}));
}
/** v1 responses may send `null`; v2 omits the field instead. */
function v2ConfigOptionsField(options: SessionConfigOption[] | null | undefined): {
configOptions?: v2.SessionConfigOption[];
} {
return options != null ? { configOptions: v2ConfigOptions(options) } : {};
}
/**
* The v1 list of the MCP servers of a v2 setup request, or undefined for no
* list. A request with two servers of the same `name`, or with a transport
* that the agent does not advertise in `session.mcp` (such as `acp` or a
* custom `_` type), fails with invalid params (-32602): the v1 session setup
* would otherwise drop the server without telling the client.
*/
function v1McpServers(servers: v2.McpServer[] | null | undefined): McpServer[] | undefined {
if (servers == null) return undefined;
v2.assertSupportedMcpServers(servers, V2_SESSION_CAPABILITIES.mcp);
return servers.map(v1McpServer);
}
/**
* v2 requires a `type` on every transport and makes the empty lists optional.
* The agent recognizes a v1 stdio server by its missing `type`, so the v2 tag
* is dropped. {@link v1McpServers} has already rejected every other transport.
*/
function v1McpServer(server: v2.McpServer): McpServer {
if (v2.McpServer.isStdio(server)) {
const { name, command, args, env, _meta } = server;
return { name, command, args: args ?? [], env: env ?? [], ...(_meta != null ? { _meta } : {}) };
}
if (v2.McpServer.isHttp(server)) {
return { ...server, headers: server.headers ?? [] };
}
throw new Error(`Unreachable: MCP server of type ${server.type} passed the transport check`);
}