fix: reject requests that name a replayed subagent session with -32602 (#1686)

A child session that a `session/load` or `session/resume` replay
announced was known only to the replay. A request that named it was
answered as one of an unknown session: `session/close` and
`session/delete` reported success, and the rest failed with `-32002`. A
live child was forgotten the same way after `/clear` and after a restart
of its root's query.

Found while reviewing the protocol changes since ACP SDK 2.8.0
(agentclientprotocol/agent-client-protocol#2952).

## The rules

- Errors page, v1 and v2: "A child session that the Agent announced with
`subagent_update` is not an unknown session… Agents **SHOULD** reject
any other request that names a child with `-32602`."
- v2 session setup: "Agents **SHOULD** reject a `session/close` that
names one with `-32602`." The delete page says the same for
`session/delete`.
- Subagents, restricted methods: the Client can name a child from the
child's announcement until the child's root session stops being active.

## Before

- v2: `V2Agent.ownerOfChild` asked `SessionTasks.hasChild`, which reads
only the children of the current conversation.
- v1: `assertNoChildSession` asked `NativeSubagentRuntime.hasChild`,
which reads only live children.

## After

Each connection keeps one record of the child sessions it announced,
`AnnouncedChildren` in `src/acp-subagents.ts`. It takes the child of
every `subagent_update` at the point where updates go out
(`V2Agent.send` on v2, `ChangedMetaClient` on v1), and forgets a root's
children when the client ends that root.

A request that names such a child now fails with `-32602` through the
existing `restrictedChild`, on v1 and v2. `session/cancel` of a child
that does not run still does nothing. On v2, `tool_call/cancel` and
`terminal/cancel` answer `-32602` for it, also after its root's query
ended (it was `-32002`).

The record is per connection and not per session because per-session
state does not last long enough. On v1 a load's replay runs before the
session record and its runtime exist. On both versions a query restart
creates a new session object, and `/clear` drops the live children,
while the client still holds every child it was told about.

Other changes that follow from it:

- v1: a new `endSession` (teardown plus forgetting the children) serves
`session/close`, `session/delete` and archive. A load or resume that
replaces the query still only tears down, and keeps the children.
- v2: a replayed child's own updates are now held while a second replay
of its root is in flight, like the parent's `subagent_update` for it.
Before, the child's state could overtake its announcement.
- `NativeSubagentRuntime.hasChild` had no caller left and is removed.
`SessionTasks.hasChild` is private and documented as live-only.
- AIR's draft announces with `subagent_spawned` and keeps its own rules,
so its children are never in the record, as before.

`docs/subagent-sessions.md` says which children are covered and for how
long.

## Tests

- `src/tests/acp-subagents.test.ts` covers the record.
- v1: the existing `it.each` over the methods now announces through the
agent's client. New cases: a child from a live run, a child from a load
replay with no session record (forgotten after close), and a child kept
when a resume recreates the session.
- v2: the `it.each` gains a row after a conversation reset. New cases: a
replay-only child (close, cancel as a no-op, item cancel while the root
runs and after its query ended, `-32002` after the root closes), and a
child across a provider restart.

`npm run build`, `npm run check` and `npm run test:run` pass. The whole
suite also passes against the real Claude Code CLI on this branch merged
with the SDK 2.9.0 bump and the other replay fix (4,459 passed, 9
skipped).

## Not verified

- v1 delete and archive forgetting is covered only through
`closeSession`. They share `endSession`.
- Three paths leave an entry until the connection ends: a root whose
process died without a close, a v2 resume that fails after its replay
announced children, and a `subagent_update` sent after a close. The only
effect is `-32602` instead of not-found for an id that is invalid either
way.
This commit is contained in:
Ben Brandt
2026-11-21 14:58:30 +01:00
committed by GitHub
parent 6a760cbca6
commit 3304ca724c
12 changed files with 443 additions and 133 deletions

View File

@@ -109,9 +109,11 @@ Task subagent as its own child session, following ACP's [subagents](https://agen
parent's: Claude Code also stops the foreground children it waits on, and the parent's turn goes
on. Each stopped child reports `idle` with `cancelled` from Claude Code's own events, and its
requests that the stop withdraws report no `running` first. A replayed child, which no longer
runs, gets no capabilities. A client cannot prompt or otherwise change a child: any other request
that names an announced child of a running session fails with `-32602` (Invalid params),
`session/close` and `session/delete` too.
runs, gets no capabilities, and a `session/cancel` of it does nothing. A client cannot prompt or
otherwise change a child: any other request that names a child fails with `-32602` (Invalid
params), `session/close` and `session/delete` too. That holds for every child that a
`subagent_update` announced, while it ran or in a replay, until the client closes the child's
root session: also after `/clear` and after a restart of the root's Claude Code process.
An [ACP v2](../README.md#acp-v2-preview) client gets the same without declaring anything, since subagents
are part of v2's baseline. Each child also reports its work state as its own `state_update`, right

View File

@@ -37,6 +37,59 @@ export function restrictedChild(sessionId: string, method: string): RequestError
);
}
/**
* The child sessions that the sessions of one connection announced with
* `subagent_update`, while they run or in the replay of a `session/load` or
* `session/resume`. The client knows such a session, so a request that names
* it fails as {@link restrictedChild} says, and not as a request of an unknown
* session.
*
* A child is known from its announcement until the client ends its root
* session ({@link rootClosed}): with `session/close`, or a request that closes
* the session too, such as `session/delete`. Nothing else removes it: after a
* conversation reset (`/clear`), a restart of the root's query or the end of
* the root's Claude Code process, the client still holds the child.
*
* AIR's draft announces a child with `subagent_spawned` and keeps its own
* rules, so its children are never known here.
*/
export class AnnouncedChildren {
/** The root session of each announced child session, by the child's id. */
private readonly rootByChild = new Map<string, string>();
/**
* Takes a session update that goes to the client. A `subagent_update`
* announces the child session it names, or reports on one that is known
* already. The update's own session is the child's parent, which can be a
* child itself: its root is the child's too.
*/
sending(notification: {
sessionId: string;
update: { sessionUpdate: string; sessionId?: unknown };
}): void {
const { sessionId: parent, update } = notification;
if (update.sessionUpdate !== "subagent_update" || typeof update.sessionId !== "string") return;
this.rootByChild.set(update.sessionId, this.rootByChild.get(parent) ?? parent);
}
/** Whether `sessionId` is a child session that the client knows. */
has(sessionId: string): boolean {
return this.rootByChild.has(sessionId);
}
/** The root session of the child session `sessionId`, when the client knows it. */
rootOf(sessionId: string): string | undefined {
return this.rootByChild.get(sessionId);
}
/** The client ended the session `rootSessionId`, and can no longer name its children. */
rootClosed(rootSessionId: string): void {
for (const [child, root] of this.rootByChild) {
if (root === rootSessionId) this.rootByChild.delete(child);
}
}
}
/** The form of native subagent sessions that the client gets, or none. */
export function subagentForm(capabilities?: ClientCapabilities | null): SubagentForm | undefined {
if (!clientSupportsSubagents(capabilities)) return undefined;

View File

@@ -1118,15 +1118,6 @@ export class NativeSubagentRuntime {
return true;
}
/**
* The RFD form: whether `sessionId` is a child session that this runtime
* announced. The client can cancel such a session and nothing else (see
* `restrictedChild`). False in AIR's draft, which keeps its own rules.
*/
hasChild(sessionId: string): boolean {
return this.announcedChild(sessionId) !== undefined;
}
/** The RFD form: the announced child session `sessionId`, with its task id. */
private announcedChild(sessionId: string): [string, NativeSubagent] | undefined {
if (this.form !== "rfd") return undefined;

View File

@@ -0,0 +1,59 @@
import { describe, expect, it } from "vitest";
import { AnnouncedChildren, type AcpSessionNotification } from "../acp-subagents.js";
describe("AnnouncedChildren", () => {
const announce = (children: AnnouncedChildren, parent: string, child: string) =>
children.sending({
sessionId: parent,
update: { sessionUpdate: "subagent_update", sessionId: child },
});
it("knows a child from its subagent_update, under the root of its parent", () => {
const children = new AnnouncedChildren();
announce(children, "root", "coordinator");
announce(children, "coordinator", "worker");
expect(["root", "coordinator", "worker"].map((id) => children.rootOf(id))).toEqual([
undefined,
"root",
"root",
]);
expect(["root", "coordinator", "worker"].map((id) => children.has(id))).toEqual([
false,
true,
true,
]);
});
it("takes no child from the subagent_spawned of AIR's draft", () => {
const children = new AnnouncedChildren();
const spawned: AcpSessionNotification = {
sessionId: "root",
update: {
sessionUpdate: "subagent_spawned",
subagentSessionId: "spawned",
name: "Explore",
task: "Look around",
capabilities: {},
},
};
children.sending(spawned);
expect(children.has("spawned")).toBe(false);
});
it("forgets the children of a closed root, also the nested ones, and no other root's", () => {
const children = new AnnouncedChildren();
announce(children, "root", "coordinator");
announce(children, "coordinator", "worker");
announce(children, "other-root", "other-child");
children.rootClosed("root");
expect(["coordinator", "worker", "other-child"].map((id) => children.has(id))).toEqual([
false,
false,
true,
]);
});
});

View File

@@ -2476,7 +2476,6 @@ describe("NativeSubagentRuntime in the RFD form", () => {
const { runtime, published } = await runningWorker();
const stop = vi.fn(async (_taskId: string) => {});
expect(runtime.hasChild("worker-1")).toBe(true);
await expect(runtime.cancelChild("worker-1", stop)).resolves.toBe(true);
expect(stop).toHaveBeenCalledExactlyOnceWith("worker-1");
@@ -2503,9 +2502,6 @@ describe("NativeSubagentRuntime in the RFD form", () => {
await expect(runtime.cancelChild("other-1", stop)).resolves.toBe(false);
await expect(air.cancelChild("child-1", stop)).resolves.toBe(false);
expect(stop).not.toHaveBeenCalled();
// AIR's draft keeps its own rules for a request that names a child.
expect(["root", "other-1"].map((id) => runtime.hasChild(id))).toEqual([false, false]);
expect(air.hasChild("child-1")).toBe(false);
});
});

View File

@@ -4112,10 +4112,13 @@ describe("subagent transcript replay", () => {
{
traceModels = false,
load = false,
replayed,
}: {
traceModels?: boolean;
/** Replay as a load does, while the CLI starts: without the session record. */
load?: boolean;
/** Runs after the replay, with the agent that replayed. */
replayed?: (agent: ClaudeAcpAgent) => Promise<void>;
} = {},
): Promise<string[]> {
const configDir = await mkdtemp(path.join(os.tmpdir(), "claude-acp-rfd-replay-"));
@@ -4169,6 +4172,7 @@ describe("subagent transcript replay", () => {
): Promise<void>;
}
).replaySessionHistory(sessionId, undefined, pending);
await replayed?.(agent);
const responseAt = updates.length;
if (afterResponse) {
// Stands in for the live session's runtime, which knows its running children.
@@ -4776,6 +4780,47 @@ describe("subagent transcript replay", () => {
]);
});
it("refuses a request that names a child that the replay announced, until the session closes", async () => {
const refusals: unknown[] = [];
const refusal = (agent: ClaudeAcpAgent) => {
try {
agent.assertNoChildSession("aaa111", "prompt");
return undefined;
} catch (error) {
return error;
}
};
await replayRfd(
[
user("u1", "Go"),
assistant("a1", [toolUse("toolu_agent", "Agent", { prompt: "Run" })]),
user("u2", [toolResult("toolu_agent", "Done.")]),
],
{
aaa111: {
meta: { toolUseId: "toolu_agent", requestShape: "foreground" },
records: [user("c1", "Run")],
},
},
undefined,
undefined,
{
// No session record and no subagent runtime exist yet.
load: true,
replayed: async (agent) => {
refusals.push(refusal(agent));
await agent.closeSession({ sessionId });
refusals.push(refusal(agent));
},
},
);
expect(refusals).toEqual([
expect.objectContaining({ code: -32602, data: { sessionId: "aaa111" } }),
undefined,
]);
});
it("ends a child that the user stopped as cancelled, and one without a known end as idle", async () => {
const trace = await replayRfd(
[
@@ -8483,70 +8528,70 @@ describe("subagent permission attribution (issue #851)", () => {
);
});
describe("session/cancel on a child session", () => {
/**
* Runs a turn whose child agent-42 runs until `stopped`, then ends as
* Claude Code ends a child that `stopTask` stopped, for a client with
* `capabilities`. Returns the agent, its updates, and the prompt.
*/
async function childRuns(capabilities: ClientCapabilities = { subagents: {} }) {
const updates: AcpSessionNotification[] = [];
const agent = new ClaudeAcpAgent(
{
sessionUpdate: async (update: AcpSessionNotification) => {
updates.push(update);
},
} as unknown as AcpClient,
{ log: () => {}, error: () => {} },
);
await agent.initialize({ protocolVersion: 1, clientCapabilities: capabilities });
const stopped = Promise.withResolvers<void>();
injectGeneratorSession(agent, async function* (input: Pushable<any>) {
const { value } = await input[Symbol.asyncIterator]().next();
yield userEcho(value);
yield rootToolUse("toolu_parent", "Agent");
yield {
...taskStarted("agent-42", "toolu_parent"),
subagent_type: "Explore",
prompt: "Go",
};
await stopped.promise;
// As seen live: the child's end, then the Agent call's interrupted
// result, and the parent's turn goes on.
yield taskUpdated({ status: "killed" });
yield taskNotification("toolu_parent", "stopped");
yield {
type: "user",
parent_tool_use_id: null,
uuid: randomUUID(),
session_id: "test-session",
message: {
role: "user",
content: [
{
type: "tool_result",
tool_use_id: "toolu_parent",
is_error: true,
content: "[Request interrupted by user for tool use]",
},
],
},
};
yield successResult();
yield { type: "system", subtype: "session_state_changed", state: "idle" };
} as never);
const prompt = agent.prompt({
sessionId: "test-session",
prompt: [{ type: "text", text: "go" }],
});
await vi.waitFor(() =>
expect(
agent.sessions["test-session"]?.nativeSubagentsByTaskId?.get("agent-42")?.announced,
).toBe(true),
);
return { agent, updates, prompt, stop: () => stopped.resolve() };
}
/**
* Runs a turn whose child agent-42 runs until `stopped`, then ends as
* Claude Code ends a child that `stopTask` stopped, for a client with
* `capabilities`. Returns the agent, its updates, and the prompt.
*/
async function childRuns(capabilities: ClientCapabilities = { subagents: {} }) {
const updates: AcpSessionNotification[] = [];
const agent = new ClaudeAcpAgent(
{
sessionUpdate: async (update: AcpSessionNotification) => {
updates.push(update);
},
} as unknown as AcpClient,
{ log: () => {}, error: () => {} },
);
await agent.initialize({ protocolVersion: 1, clientCapabilities: capabilities });
const stopped = Promise.withResolvers<void>();
injectGeneratorSession(agent, async function* (input: Pushable<any>) {
const { value } = await input[Symbol.asyncIterator]().next();
yield userEcho(value);
yield rootToolUse("toolu_parent", "Agent");
yield {
...taskStarted("agent-42", "toolu_parent"),
subagent_type: "Explore",
prompt: "Go",
};
await stopped.promise;
// As seen live: the child's end, then the Agent call's interrupted
// result, and the parent's turn goes on.
yield taskUpdated({ status: "killed" });
yield taskNotification("toolu_parent", "stopped");
yield {
type: "user",
parent_tool_use_id: null,
uuid: randomUUID(),
session_id: "test-session",
message: {
role: "user",
content: [
{
type: "tool_result",
tool_use_id: "toolu_parent",
is_error: true,
content: "[Request interrupted by user for tool use]",
},
],
},
};
yield successResult();
yield { type: "system", subtype: "session_state_changed", state: "idle" };
} as never);
const prompt = agent.prompt({
sessionId: "test-session",
prompt: [{ type: "text", text: "go" }],
});
await vi.waitFor(() =>
expect(
agent.sessions["test-session"]?.nativeSubagentsByTaskId?.get("agent-42")?.announced,
).toBe(true),
);
return { agent, updates, prompt, stop: () => stopped.resolve() };
}
describe("session/cancel on a child session", () => {
it("stops the child's task, and not its parent's work, then reports the child idle cancelled", async () => {
const { agent, updates, prompt, stop } = await childRuns();
@@ -8645,27 +8690,11 @@ describe("subagent permission attribution (issue #851)", () => {
protocolVersion: 1,
clientCapabilities: { subagents: {} },
});
injectGeneratorSession(agent, async function* () {} as never);
const session = agent.sessions["test-session"]!;
session.nativeSubagentsByTaskId = new Map([
[
sessionId,
{
sessionId,
parentSessionId: "test-session",
name: "Explore",
task: "Go",
announced: true,
},
],
]);
session.nativeSubagentRuntime = new NativeSubagentRuntime(
"rfd",
"test-session",
session,
async () => {},
logger,
);
// The session test-session announces its child.
await agent.client.sessionUpdate({
sessionId: "test-session",
update: { sessionUpdate: "subagent_update", sessionId },
});
await expect(client.request(method as never, params as never)).rejects.toMatchObject({
code: -32602,
@@ -8675,6 +8704,16 @@ describe("subagent permission attribution (issue #851)", () => {
},
);
});
it("knows a child from the announcement of its run", async () => {
const { agent, prompt, stop } = await childRuns();
expect(() => agent.assertNoChildSession(sessionId, "prompt")).toThrow(
"agent-42 is a subagent session",
);
stop();
await prompt;
});
});
describe("session/cancel on the parent session", () => {

View File

@@ -1096,6 +1096,24 @@ describe("createSession options merging", () => {
});
});
it("keeps a live session's subagent sessions known to the client when a resume recreates it", async () => {
const { sessionId } = await agent.newSession({ cwd: process.cwd(), mcpServers: [] });
await agent.client.sessionUpdate({
sessionId,
update: { sessionUpdate: "subagent_update", sessionId: "agent-42" },
});
await agent.resumeSession({
sessionId,
cwd: process.cwd(),
systemPrompt: { mode: "append", content: [text("New instructions.")] },
});
expect(() => agent.assertNoChildSession("agent-42", "prompt")).toThrow(
"agent-42 is a subagent session",
);
});
it("rejects an unsupported systemPrompt on resume of a live session", async () => {
const { sessionId } = await agent.newSession({ cwd: process.cwd(), mcpServers: [] });

View File

@@ -755,6 +755,30 @@ describe("ACP v2 core", () => {
});
});
it("rejects a request on a subagent's session across the restart of its root's query", async () => {
const client = v2Client();
await client.connect(async (agent) => {
const { response, claude } = await openSession(agent);
void agent.request(v2.methods.agent.session.prompt, {
sessionId: response.sessionId,
prompt: PROMPT,
});
claude.send(lifecycle(await claude.prompt(0), "started"));
const helper = subagent("agent-1", "toolu_agent");
claude.send(helper.launch());
claude.send(helper.started());
claude.send(helper.ended());
claude.send(result());
await vi.waitFor(() => expect(client.states().at(-1)).toBe("idle"));
await setProvider(agent);
expect(sdk.processes).toHaveLength(2);
await expect(
agent.request(v2.methods.agent.session.close, { sessionId: "agent-1" }),
).rejects.toMatchObject({ code: -32602 });
});
});
it("sends a prompt of an idle session right after the response to the new query", async () => {
const client = v2Client();
await client.connect(async (agent) => {
@@ -4800,9 +4824,11 @@ describe("ACP v2 core", () => {
});
it.each([
["session/prompt", v2.methods.agent.session.prompt, { prompt: PROMPT }],
["session/close", v2.methods.agent.session.close, {}],
])("rejects %s on a subagent's session", async (_, method, params) => {
["session/prompt", v2.methods.agent.session.prompt, { prompt: PROMPT }, false],
["session/close", v2.methods.agent.session.close, {}, false],
// The adapter no longer follows the child, and the client still holds it.
["session/close after a conversation reset", v2.methods.agent.session.close, {}, true],
])("rejects %s on a subagent's session", async (_, method, params, reset) => {
const client = v2Client();
const error = await client.connect(async (agent) => {
const { claude } = await openSession(agent);
@@ -4812,6 +4838,22 @@ describe("ACP v2 core", () => {
await vi.waitFor(() =>
expect(client.notifications.some((n) => n.sessionId === "child")).toBe(true),
);
if (reset) {
claude.send({
type: "conversation_reset",
new_conversation_id: randomUUID(),
uuid: randomUUID(),
trigger: "clear",
timestamp: new Date().toISOString(),
session_id: "session",
});
await vi.waitFor(() =>
expect(updatesOf(client.notifications, "child").at(-1)).toMatchObject({
sessionUpdate: "state_update",
state: "unknown",
}),
);
}
return agent
.request(
method as typeof v2.methods.agent.session.close,
@@ -4826,6 +4868,74 @@ describe("ACP v2 core", () => {
expect(error).toMatchObject({ code: -32602 });
});
it("rejects a request on a subagent's session that only a replay announced, until its root closes", async () => {
sdk.subagents = new Map([
[
"toolu_launch",
{
agentId: "child",
background: false,
stoppedByUser: false,
agentType: "general-purpose",
},
],
]);
const client = v2Client();
const errors = await client.connect(async (agent) => {
const { response, claude } = await openSession(agent);
const sessionId = response.sessionId;
vi.mocked(getSessionMessages).mockResolvedValueOnce([
{
type: "assistant",
uuid: "a1",
session_id: sessionId,
parent_tool_use_id: null,
parent_agent_id: null,
message: subagent("child", "toolu_launch").launch().message,
},
] as never);
await agent.request(v2.methods.agent.session.resume, {
sessionId,
cwd,
replayFrom: { type: "start" },
});
// The child does not run, so a cancel of it has nothing to stop.
await agent.notify(v2.methods.agent.session.cancel, { sessionId: "child" });
const refusal = (request: Promise<unknown>) => request.catch((error: unknown) => error);
const close = await refusal(
agent.request(v2.methods.agent.session.close, { sessionId: "child" }),
);
// The child lists no tool call: it does not run.
const cancelItem = () =>
refusal(
agent.request(v2.methods.agent.toolCall.cancel, {
sessionId: "child",
toolCallId: "toolu_read",
}),
);
const whileRootRuns = await cancelItem();
expect(claude.stopTask).not.toHaveBeenCalled();
expect(claude.interrupt).not.toHaveBeenCalled();
// The root's query ends: the root is still active, and the child still known.
claude.end();
const afterQueryEnd = await cancelItem();
await agent.request(v2.methods.agent.session.close, { sessionId });
const afterClose = await refusal(
agent.request(v2.methods.agent.session.prompt, { sessionId: "child", prompt: PROMPT }),
);
return [close, whileRootRuns, afterQueryEnd, afterClose];
});
const notListed = { code: -32602, data: { sessionId: "child", toolCallId: "toolu_read" } };
expect(errors).toMatchObject([
{ code: -32602, message: expect.stringContaining("child is a subagent session") },
notListed,
notListed,
// The client closed the child's root, so it can no longer name the child.
{ code: -32002 },
]);
});
it("keeps a background command's terminal running and listed until its task ends", async () => {
const client = v2Client();
const sessionId = await client.connect(async (agent) => {

View File

@@ -113,6 +113,7 @@ import { sanitizeTitle, SessionTitles } from "../session-titles.js";
import {
AIR_NATIVE_SUBAGENT_SESSIONS_CAPABILITY,
AcpSessionNotification,
AnnouncedChildren,
asSdkSessionNotification,
clientSupportsSubagents,
restrictedChild,
@@ -1679,6 +1680,12 @@ export class ClaudeAcpAgent {
* and configurations.
*/
private readonly replayedSubagents = new Map<string, RfdSubagentReplay>();
/**
* The subagents RFD form: the child sessions that the sessions announced,
* from each one's `subagent_update` until the client ends its root session
* (see {@link endSession}) or the connection ends (see `AnnouncedChildren`).
*/
private readonly announcedChildren = new AnnouncedChildren();
/**
* AIR's draft: the model that the last load of each session replayed to each
* child session, as the model id and the entry that went out. See
@@ -1707,7 +1714,7 @@ export class ClaudeAcpAgent {
agent: this,
isAirClient: () => this.toolCallCapabilities.air.client,
interruptSession: (sessionId) => this.cancelTurns({ sessionId }, { awaitInterrupt: false }),
teardownSession: (sessionId) => this.teardownSession(sessionId),
teardownSession: (sessionId) => this.endSession(sessionId),
});
/**
@@ -1727,7 +1734,12 @@ export class ClaudeAcpAgent {
constructor(client: AcpClient, logger?: Logger) {
this.sessions = {};
this.client = new ChangedMetaClient(client, () => this.toolCallCapabilities.air.client);
this.client = new ChangedMetaClient(
client,
() => this.toolCallCapabilities.air.client,
// Before the client can name the child that a `subagent_update` announces.
(update) => this.announcedChildren.sending(update),
);
this.logger = logger ?? console;
this.exitPlan = new ExitPlanCoordinator<Session, Turn>({
currentSession: (id) => this.sessions[id],
@@ -7344,16 +7356,13 @@ export class ClaudeAcpAgent {
/**
* Throws invalid params (-32602) when `sessionId` is a child session that a
* session of this connection announced on the subagents RFD form (see
* `NativeSubagentRuntime.hasChild`): the client can cancel a child, and
* nothing else. `method` completes "the client cannot … it".
* session of this connection announced on the subagents RFD form, while it
* ran or in a load's replay, and that session is not closed (see
* `AnnouncedChildren`): the client can cancel a child, and nothing else.
* `method` completes "the client cannot … it".
*/
assertNoChildSession(sessionId: string, method: string): void {
for (const session of Object.values(this.sessions)) {
if (session.nativeSubagentRuntime?.hasChild(sessionId)) {
throw restrictedChild(sessionId, method);
}
}
if (this.announcedChildren.has(sessionId)) throw restrictedChild(sessionId, method);
}
/**
@@ -7892,12 +7901,21 @@ export class ClaudeAcpAgent {
await Promise.all(Object.keys(this.sessions).map((id) => this.teardownSession(id)));
}
/**
* {@link teardownSession}, for a session that the client ends: with
* `session/close`, `session/delete`, or an archive. The client can no
* longer name the session's children then (see `AnnouncedChildren`). A load
* or resume that replaces the session's query keeps them.
*/
private async endSession(sessionId: string): Promise<void> {
await this.teardownSession(sessionId);
// After the teardown's last updates, which name the children.
this.announcedChildren.rootClosed(sessionId);
}
/** Idempotent: a session that is not loaded here is already closed. */
async closeSession(params: CloseSessionRequest): Promise<CloseSessionResponse> {
if (!this.sessions[params.sessionId]) {
return {};
}
await this.teardownSession(params.sessionId);
await this.endSession(params.sessionId);
return {};
}

View File

@@ -83,7 +83,8 @@ export class ClientConnection implements AcpClient {
}
/**
* The client that the agent talks to. For an AIR client, every session update
* The client that the agent talks to. `sending` takes every session update
* first, before it goes to the client. For an AIR client, every session update
* passes the {@link ChangedMetaFilter} last, after the native subagent routing,
* so a `tool_call_update` carries only the `_meta` keys that changed. ACP
* merges only the top-level tool call fields, not the `_meta` keys. So another
@@ -95,9 +96,11 @@ export class ChangedMetaClient implements AcpClient {
constructor(
private readonly inner: AcpClient,
private readonly airClient: () => boolean,
private readonly sending: (update: AcpSessionNotification) => void = () => {},
) {}
async sessionUpdate(params: AcpSessionNotification): Promise<void> {
this.sending(params);
if (!this.airClient()) return this.inner.sessionUpdate(params);
const update = this.filter.apply(params.update as SessionNotification["update"]);
if (update) await this.inner.sessionUpdate({ ...params, update } as AcpSessionNotification);

View File

@@ -34,7 +34,7 @@ import packageJson from "../../package.json" with { type: "json" };
import { messageIdForGrouping } from "../sdk-to-acp.js";
import type { Logger } from "../logger.js";
import { customAgents } from "../session-config-options.js";
import { restrictedChild } from "../acp-subagents.js";
import { AnnouncedChildren, restrictedChild } from "../acp-subagents.js";
import { claudeCliPath, cliDelivery } from "../claude-cli.js";
import { clientSystemPrompt, sessionSystemPrompt } from "../client-system-prompt.js";
import type { ElicitationSupport } from "../elicitation.js";
@@ -187,6 +187,12 @@ class V2Agent implements AgentHandle, SessionConnection {
* session whose query ended, keep the record.
*/
private readonly promptKeys = new Map<string, PromptKeys>();
/**
* The subagent sessions that the sessions announced, from each one's
* `subagent_update` to the `session/close` of its root or the end of the
* connection (see `AnnouncedChildren`).
*/
private readonly children = new AnnouncedChildren();
readonly translator = new V2UpdateTranslator();
readonly auth: V2Auth;
/** The `--hide-claude-auth` subscription guard (see `subscription-guard.ts`). */
@@ -244,6 +250,8 @@ class V2Agent implements AgentHandle, SessionConnection {
/** Sends the update, after the `replay_complete` of a replay that holds it (see {@link heldBy}). */
send(notification: v2.UpdateSessionNotification): void {
// Before the client can name the child that a `subagent_update` announces.
this.children.sending(notification);
const send = () => {
this.ctx.notify(v2.methods.client.session.update, notification).catch((error) => {
this.logger.error(`Failed to send a ${notification.update.sessionUpdate} update:`, error);
@@ -418,7 +426,7 @@ class V2Agent implements AgentHandle, SessionConnection {
* with.
*/
async forkSession(params: v2.ForkSessionRequest): Promise<v2.ForkSessionResponse> {
if (this.ownerOfChild(params.sessionId)) throw restrictedChild(params.sessionId, "fork");
if (this.children.has(params.sessionId)) throw restrictedChild(params.sessionId, "fork");
// Rejects bad `configOptions`, a bad `cwd` or MCP server before the transcript is copied.
const initial = initialConfigRequests(params.sessionId, params.configOptions);
await validatedSetup(params);
@@ -471,7 +479,7 @@ class V2Agent implements AgentHandle, SessionConnection {
`Replaying from a ${replayFrom.type} cursor is not supported`,
);
}
if (this.ownerOfChild(sessionId)) throw restrictedChild(sessionId, "resume");
if (this.children.has(sessionId)) throw restrictedChild(sessionId, "resume");
const initial = initialConfigRequests(sessionId, params.configOptions);
// No await before it: nothing of the session goes out between the request and the hold.
const release = replayFrom != null ? this.replays.begin(sessionId) : undefined;
@@ -639,7 +647,7 @@ class V2Agent implements AgentHandle, SessionConnection {
async sessionStatus({ sessionId }: v2.SessionStatusRequest): Promise<v2.SessionStatusResponse> {
const session = this.sessions.get(sessionId);
if (session) return { status: "open", state: session.statusState() };
if (this.ownerOfChild(sessionId)) throw restrictedChild(sessionId, "ask the status of");
if (this.children.has(sessionId)) throw restrictedChild(sessionId, "ask the status of");
return savedSessionStatus(sessionId);
}
@@ -668,7 +676,7 @@ class V2Agent implements AgentHandle, SessionConnection {
};
let session: V2Session | undefined;
if (sessionId != null) {
if (this.ownerOfChild(sessionId)) throw restrictedChild(sessionId, "read the options of");
if (this.children.has(sessionId)) throw restrictedChild(sessionId, "read the options of");
// A restart or a resume that runs makes the session active.
await this.restarts.settled(sessionId);
await this.startSettled(sessionId);
@@ -705,7 +713,7 @@ class V2Agent implements AgentHandle, SessionConnection {
/** Closing is idempotent: a session that is not active closes at once. */
async closeSession({ sessionId }: v2.CloseSessionRequest): Promise<v2.CloseSessionResponse> {
if (this.ownerOfChild(sessionId)) throw restrictedChild(sessionId, "close");
if (this.children.has(sessionId)) throw restrictedChild(sessionId, "close");
// A restart that runs ends first, so the close ends the session it started.
await this.restarts.closing(sessionId);
// A resume that runs answers first: the close ends what it started, and
@@ -723,12 +731,14 @@ class V2Agent implements AgentHandle, SessionConnection {
this.guard.sessionEnded(sessionId);
}
this.restarts.closed(sessionId);
// After the close's last updates, which name the session's children.
this.children.rootClosed(sessionId);
return {};
}
/** Deleting a session that does not exist succeeds, as v2 asks. */
async deleteSession({ sessionId }: v2.DeleteSessionRequest): Promise<v2.DeleteSessionResponse> {
if (this.ownerOfChild(sessionId)) throw restrictedChild(sessionId, "delete");
if (this.children.has(sessionId)) throw restrictedChild(sessionId, "delete");
// A resume that runs, or its start, may make the session live.
await this.setupSettled(sessionId);
const live = this.sessions.get(sessionId);
@@ -753,7 +763,7 @@ class V2Agent implements AgentHandle, SessionConnection {
async setTitle(params: v2.SetSessionTitleRequest): Promise<v2.SetSessionTitleResponse> {
const request = parseRenameSessionRequest(params);
const { sessionId } = request;
if (this.ownerOfChild(sessionId)) throw restrictedChild(sessionId, "retitle");
if (this.children.has(sessionId)) throw restrictedChild(sessionId, "retitle");
// Renamed through the query that runs once a restart or resume settled.
await this.restarts.settled(sessionId);
await this.setupSettled(sessionId);
@@ -786,7 +796,7 @@ class V2Agent implements AgentHandle, SessionConnection {
session(sessionId: string, method: string): V2Session {
const session = this.sessions.get(sessionId);
if (session) return session;
if (this.ownerOfChild(sessionId)) throw restrictedChild(sessionId, method);
if (this.children.has(sessionId)) throw restrictedChild(sessionId, method);
throw this.inactive(sessionId);
}
@@ -812,8 +822,10 @@ class V2Agent implements AgentHandle, SessionConnection {
target: { terminalId: string } | { toolCallId: string },
): Promise<Record<string, never>> {
const root = this.sessions.get(sessionId) ?? this.ownerOfChild(sessionId);
if (!root) throw this.inactive(sessionId);
if (!(await root.tasks.cancelItem(sessionId, target))) {
// A subagent's session is known to the client also when its root's query
// ended: it lists nothing then.
if (!root && !this.children.has(sessionId)) throw this.inactive(sessionId);
if (!root || !(await root.tasks.cancelItem(sessionId, target))) {
throw "terminalId" in target
? RequestError.invalidParams(
{ sessionId, terminalId: target.terminalId },
@@ -827,9 +839,13 @@ class V2Agent implements AgentHandle, SessionConnection {
return {};
}
/** The root session that `sessionId` is a subagent session of. */
/**
* The active root session that `sessionId` is a subagent session of.
* Undefined also for a child whose root's query ended.
*/
private ownerOfChild(sessionId: string): V2Session | undefined {
return [...this.sessions.values()].find((session) => session.tasks.hasChild(sessionId));
const root = this.children.rootOf(sessionId);
return root === undefined ? undefined : this.sessions.get(root);
}
async dispose(): Promise<void> {

View File

@@ -593,8 +593,13 @@ export class SessionTasks {
return this.agents.size > 0;
}
/** Whether `sessionId` is an announced child session of this root. */
hasChild(sessionId: string): boolean {
/**
* Whether `sessionId` is a child session that this root announced in its
* current conversation. A child that only a replay announced, or one from
* before a conversation reset, is not: the client still knows those (see
* `AnnouncedChildren`).
*/
private hasChild(sessionId: string): boolean {
return this.children.get(sessionId)?.announced === true;
}