Files
claude-agent-acp/src/v2/agent.ts
Ben Brandt 1801c037b8 feat: add an experimental native ACP v2 core
Serves ACP v2 straight from the Claude Agent SDK query, without the
v1 core, behind CLAUDE_AGENT_ACP_V2_CORE=native. Foreground work is
each Claude Code turn, subagents are child sessions (subagents RFD),
and every state carries its background list. See
docs/v2-native-core.md.
2026-11-09 09:58:58 +01:00

423 lines
17 KiB
TypeScript

/**
* The experimental draft ACP v2 surface of the adapter.
*
* `ClaudeAcpAgent` speaks ACP v1 types. This surface translates each v2
* request into the v1 request that the agent serves, and each v1 message that
* the agent sends into its v2 form, so v1 and v2 share one implementation.
* Where the versions differ, it maps the agent's own types instead: a prompt
* is served through the agent's turn events (see `prompt.ts`).
*/
import type {
CompleteElicitationNotification,
CreateElicitationRequest,
CreateElicitationResponse,
McpServer,
RequestPermissionResponse,
} from "@agentclientprotocol/sdk/unstable";
import * as v2 from "@agentclientprotocol/sdk/experimental/v2/unstable";
import { ClaudeAcpAgent, type AcpClient, type Logger } from "../acp-agent.js";
import type { AcpSessionNotification } from "../acp-subagents.js";
import type { AcpPermissionRequest } from "../permissions/presentation.js";
import { stateUpdate, V2Background } from "./background.js";
import { v1InitializeRequest, v2InitializeResponse } from "./initialize.js";
import { v1PermissionResponse, v2PermissionRequest } from "./permission.js";
import { v2Foreground, v2Prompt } from "./prompt.js";
import {
v1ForkSessionRequest,
v1NewSessionRequest,
v1RestoreSessionRequest,
v1SetSessionConfigOptionRequest,
v2AvailableCommands,
v2ConfigOptions,
v2NewSessionResponse,
v2ResumeSessionResponse,
} from "./session.js";
import { v2ChildStateUpdate } from "./session-update.js";
import { replayClear, V2UpdateTranslator } from "./update-translator.js";
/**
* The ACP v2 surface, for one connection.
*
* As in `v1AgentApp`, the agent of the connection is created when the
* connection opens, before the connection processes any inbound message.
* `onAgent` receives it for the owner of the process (shutdown).
*
* The provider methods pass through: their types are the same in v1 and v2.
*/
export function v2AgentApp(
logger: Logger | undefined,
onAgent: (agent: ClaudeAcpAgent) => void,
): v2.AgentApp {
let agent!: ClaudeAcpAgent;
let client!: V2ClientConnection;
return v2
.agent({ name: "claude-code-acp" })
.onConnect((connection) => {
client = new V2ClientConnection(connection.client, logger ?? console);
agent = new ClaudeAcpAgent(client, logger, {
v2: true,
foreground: (sessionId) =>
v2Foreground((update) => {
void client.send({ sessionId, update });
}),
background: {
changed: (report) => {
for (const notification of client.background.changed(report)) {
void client.send(notification);
}
},
forget: (sessionId) => client.background.forget(sessionId),
},
});
onAgent(agent);
})
.onRequest(v2.methods.agent.initialize, async ({ params }) =>
v2InitializeResponse(await agent.initialize(v1InitializeRequest(params))),
)
.onRequest(v2.methods.agent.auth.login, ({ params }) => agent.authenticate(params))
.onRequest(v2.methods.agent.auth.logout, ({ params }) => agent.logout(params))
.onRequest(v2.methods.agent.providers.list, ({ params }) =>
agent.unstable_listProviders(params),
)
.onRequest(v2.methods.agent.providers.set, ({ params }) => agent.unstable_setProvider(params))
.onRequest(v2.methods.agent.providers.disable, ({ params }) =>
agent.unstable_disableProvider(params),
)
.onRequest(v2.methods.agent.session.new, async ({ params }) => {
const request = v1NewSessionRequest(params);
const response = await agent.newSession(request);
const commands = await setupCommands(agent, response.sessionId, logger);
afterSetupResponse(agent, response.sessionId, request.mcpServers, commands, logger);
return { ...v2NewSessionResponse(response), ...commands };
})
.onRequest(v2.methods.agent.session.list, ({ params }) => agent.listSessions(params))
.onRequest(v2.methods.agent.session.resume, async ({ params }) => {
const restore = v1RestoreSessionRequest(params);
const response =
restore.method === "resume"
? await agent.resumeSession(restore.request)
: await client.replaying(params.sessionId, () => agent.loadSession(restore.request));
// v2 asks for the current title and `updatedAt` after the replay and
// before the response, also without a replay, as the client may hold
// none or stale ones.
await agent.publishCurrentSessionInfo(params.sessionId);
// v2 requires a snapshot of the foreground state after the replay and
// before the response, also without a replay: a resumed live session can
// be running a turn, or waiting on a permission request. The current
// state of each subagent, terminal and tool call it lists comes first,
// as v2 requires. The subagents' go again after the response (see below).
await agent.publishLiveSubagents(
params.sessionId,
client.background.listedSubagents(params.sessionId),
);
await agent.publishBackgroundToolCalls(
params.sessionId,
client.background.listedToolCalls(params.sessionId),
);
for (const notification of client.background.currentItems(params.sessionId)) {
void client.send(notification);
}
void client.send({
sessionId: params.sessionId,
update: stateUpdate(agent.foregroundState(params.sessionId)),
});
const commands = await setupCommands(agent, params.sessionId, logger);
// The response ends a replay. The subagents RFD treats the replayed
// subagent states before it as history, so their current states follow it.
afterSetupResponse(
agent,
params.sessionId,
restore.request.mcpServers ?? [],
commands,
logger,
() => void agent.publishCurrentSubagentStates(params.sessionId),
);
return { ...v2ResumeSessionResponse(response), ...commands };
})
.onRequest(v2.methods.agent.session.fork, ({ params }) =>
agent.forking(params.sessionId, async () => {
// The agent starts the forked session, so the client can prompt it.
const request = v1ForkSessionRequest(params);
const response = await agent.unstable_forkSession(request);
const commands = await setupCommands(agent, response.sessionId, logger);
afterSetupResponse(agent, response.sessionId, request.mcpServers ?? [], commands, logger);
return {
sessionId: response.sessionId,
...v2ResumeSessionResponse(response),
...commands,
};
}),
)
.onRequest(v2.methods.agent.session.close, async ({ params }) => {
const response = await agent.closeSession(params);
client.translator.forget(params.sessionId);
return response;
})
.onRequest(v2.methods.agent.session.delete, ({ params }) => agent.deleteSession(params))
.onRequest(v2.methods.agent.session.setConfigOption, async ({ params }) => {
const { configOptions, ...response } = await agent.setSessionConfigOption(
v1SetSessionConfigOptionRequest(params),
);
// v2 asks for a `config_option_update` on every config change, also one
// that a client requested, so other attached clients see it. It goes
// before the response, as v2 asks of this duplicate. The agent sends v1
// clients none: they read the change from the response only.
const options = v2ConfigOptions(configOptions);
void client.send({
sessionId: params.sessionId,
update: { sessionUpdate: "config_option_update", configOptions: options },
});
return { ...response, configOptions: options };
})
.onRequest(v2.methods.agent.session.prompt, ({ params }) =>
v2Prompt(agent, params, (update) => {
void client.send({ sessionId: params.sessionId, update });
}),
)
.onRequest(v2.methods.agent.terminal.cancel, async ({ params }) => {
await agent.cancelBackgroundTerminal(params);
return {};
})
.onRequest(v2.methods.agent.toolCall.cancel, async ({ params }) => {
await agent.cancelBackgroundToolCall(params);
return {};
})
.onNotification(v2.methods.agent.session.cancel, ({ params }) => agent.cancel(params));
}
/**
* The `availableCommands` of a setup response, which v2 requires when the
* session has commands. The agent sends a v1 client the same list as an
* `available_commands_update` after the response, and a v2 client none
* (`ClaudeAcpAgent.afterSetupResponse`). Later changes still arrive as
* updates. An empty list is left out, as the draft asks. A failure to read
* the commands does not fail the setup: the result is `undefined`, and
* {@link afterSetupResponse} sends the commands in an update instead.
*/
async function setupCommands(
agent: ClaudeAcpAgent,
sessionId: string,
logger: Logger | undefined,
): Promise<{ availableCommands?: v2.AvailableCommand[] } | undefined> {
try {
const commands = await agent.availableCommands(sessionId);
return commands.length > 0 ? { availableCommands: v2AvailableCommands(commands) } : {};
} catch (error) {
(logger ?? console).error(`Session ${sessionId}: failed to read the session's commands`, error);
return undefined;
}
}
/**
* The work that follows a v2 setup response, run once the response is sent
* (`ClaudeAcpAgent.afterSetupResponse` does it on v1):
*
* - When `commands` is `undefined` (reading them for the response failed),
* an `available_commands_update` with the commands, read again.
* - `then`, such as sending the current states of replayed subagents.
* - OAuth for the MCP servers that need it. Its URL elicitation must not
* reach the client before the response, which v2 asks against.
*/
function afterSetupResponse(
agent: ClaudeAcpAgent,
sessionId: string,
mcpServers: McpServer[],
commands: { availableCommands?: v2.AvailableCommand[] } | undefined,
logger: Logger | undefined,
then?: () => void,
): void {
setTimeout(() => {
if (!commands) {
agent.sendAvailableCommandsUpdate(sessionId).catch((error) => {
(logger ?? console).error(
`Session ${sessionId}: failed to send the session's commands`,
error,
);
});
}
then?.();
agent.authenticateMcpServers(sessionId, mcpServers);
}, 0);
}
/**
* The {@link AcpClient} of an ACP v2 connection: it sends the v1 messages of
* the agent as v2 messages.
*/
class V2ClientConnection implements AcpClient {
/**
* The sessions whose history replays, each with the messages that the
* replay has cleared so far. A subagent that a replay announces replays
* with it.
*/
private readonly replays = new Map<string, Set<string>>();
/** The session whose replay announced each replaying subagent. */
private readonly replayRoots = new Map<string, string>();
/**
* The last work state that a replay reported for each subagent, as the
* `state_update` of the child's own stream. It goes out once the replay
* ends: v2 forbids replaying a child's past `running` and `idle` as current
* activity.
*/
private readonly replayedChildStates = new Map<string, v2.UpdateSessionNotification>();
/** 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.translator.terminals);
constructor(
private readonly ctx: v2.AgentContext,
private readonly logger: Logger,
) {}
/**
* Runs `restore`, which replays the history of `sessionId`.
*
* The agent replays messages as chunks. A v2 client may still hold a
* replayed message, and chunks append, so before the first replayed chunk of
* each message the client gets the message with no content, which clears it,
* as v2 requires of a message replayed as chunks.
*
* Each replayed subagent gets one `state_update` on its own stream, with its
* last state, after the replay.
*/
async replaying<T>(sessionId: string, restore: () => Promise<T>): Promise<T> {
this.replays.set(sessionId, new Set());
const children = () =>
[...this.replayRoots].filter(([, root]) => root === sessionId).map(([child]) => child);
try {
const result = await restore();
for (const child of children()) {
const state = this.replayedChildStates.get(child);
if (state) void this.send(state);
}
return result;
} finally {
this.replays.delete(sessionId);
for (const child of children()) {
this.replays.delete(child);
this.replayRoots.delete(child);
this.replayedChildStates.delete(child);
}
}
}
/**
* Sends a v2 session update, and logs rather than rejects when that fails.
* It and {@link sessionUpdate} hand updates to the connection synchronously,
* so they go out in the order of the calls. The agent's consumer awaits each
* of its updates before it reports the next turn event, so a turn's state
* follows the output that came before it. (An update the consumer is still
* routing can be overtaken by an event from elsewhere, such as a permission
* request opening.)
*/
send(notification: v2.UpdateSessionNotification): Promise<void> {
return this.ctx
.notify(v2.methods.client.session.update, this.background.stamp(notification))
.catch((error) => {
this.logger.error(`Failed to send a ${notification.update.sessionUpdate} update:`, error);
});
}
extNotification(method: string, params: Record<string, unknown>): Promise<void> {
if (!isExtensionMethod(method)) {
return Promise.reject(new Error(`${method} is not an ACP extension method`));
}
return this.ctx.notify(method, params);
}
async sessionUpdate({ update, ...notification }: AcpSessionNotification): Promise<void> {
// A subagent that a replay announces replays too, so its messages are
// cleared before their first replayed chunk, as the parent's are.
if (
update.sessionUpdate === "subagent_update" &&
this.replays.has(notification.sessionId) &&
!this.replays.has(update.sessionId)
) {
this.replays.set(update.sessionId, new Set());
this.replayRoots.set(
update.sessionId,
this.replayRoots.get(notification.sessionId) ?? notification.sessionId,
);
}
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`).
let childState = v2ChildStateUpdate(update);
if (childState && this.replays.has(notification.sessionId)) {
this.replayedChildStates.set(childState.sessionId, childState);
childState = undefined;
}
// Every update goes to the connection before any is awaited, so an update
// that another call sends meanwhile cannot come between them. The parent's
// copy is stamped first: a child's announcement starts its list.
const stamped = [
...updates.map((v2Update) => this.background.stamp({ ...notification, update: v2Update })),
...(childState ? [this.background.stamp(childState)] : []),
];
await Promise.all(
stamped.map((v2Notification) =>
this.ctx.notify(v2.methods.client.session.update, v2Notification),
),
);
}
async requestPermission(
params: AcpPermissionRequest,
signal?: AbortSignal,
): Promise<RequestPermissionResponse> {
// The subject is an update of the tool call, with its stored `_meta`.
const toolCall = this.translator.toolCallMeta.subject(params.sessionId, params.toolCall);
const response = await this.ctx.request(
v2.methods.client.session.requestPermission,
v2PermissionRequest({ ...params, toolCall }),
{ cancellationSignal: signal, stopWaitingOnCancel: true },
);
return v1PermissionResponse(response);
}
// Elicitation is the same in v1 and v2.
createElicitation(
params: CreateElicitationRequest,
signal?: AbortSignal,
): Promise<CreateElicitationResponse> {
return this.ctx.request(
v2.methods.client.elicitation.create,
// The v1 types accept a property schema with any tag; the v2 types accept
// one only in a received value. As on v1, an MCP server's schema is
// relayed here unchanged, so this cast does not check it.
params as v2.CreateElicitationRequest,
{ cancellationSignal: signal, stopWaitingOnCancel: true },
);
}
completeElicitation(params: CompleteElicitationNotification): Promise<void> {
return this.ctx.notify(v2.methods.client.elicitation.complete, params);
}
// v2 has no client file system. The agent never calls these on v2, because
// `v1InitializeRequest` reports no `fs` capability.
readTextFile(): Promise<never> {
return Promise.reject(new Error("ACP v2 has no client file system"));
}
writeTextFile(): Promise<never> {
return Promise.reject(new Error("ACP v2 has no client file system"));
}
}
function isExtensionMethod(method: string): method is v2.ExtensionMethod {
return method.startsWith("_");
}