mirror of
https://github.com/agentclientprotocol/claude-agent-acp.git
synced 2026-11-22 17:21:45 +00:00
fix: give a forked skill's child session its tool calls and text (#1677)
## Problem A forked skill (`context: fork`, such as `/code-review`) runs as a subagent that no Agent or Task call launched. The adapter ties a subagent's messages to its child session through that call, so a client with subagent sessions got an empty child: - **The user types `/code-review`:** the child was announced with its prompt, then went `idle`. On v2 the fork's tool calls landed on the root session; on v1 they were never sent. - **Claude calls the Skill tool:** no child was announced, and the fork's tool calls were never sent. What Claude Code 2.1.328 sends, captured from its output stream: | | Skill tool | Typed | | --- | --- | --- | | `task_started` names a tool call | yes, the Skill call | no | | `parent_tool_use_id` of the fork's messages | the Skill call's id | `forked-command-<skill>`, the same for every run | | `agent_id` of the fork's messages | the task id | the task id | | When the messages come | live | together, after the `task_notification` and before the turn's result | ## Change 1. **Route by `agent_id`.** A message whose `parent_tool_use_id` names no launch call goes to the child that its `agent_id` names. 2. **Announce a Skill-launched child** on the session that made the Skill call. The call stays a tool call, and the skill's prompt is a `session_message` in the child only. 3. **Hold the child's end until its messages came,** so its `idle` follows its tool calls and text. The end is reported at the first message of the main conversation after one of the child's, at the turn's result, at Claude Code's `idle`, or when the turn or the query ends. Both cores apply the same two rules, `endWaitsForMessages` and `endsMessageWait` in `src/native-subagents.ts`. AIR gets the change through the v1 runtime; I could not check it against an AIR client. ## Workarounds for Claude Code's behavior - **The hold is a heuristic.** No task event marks a typed fork. The adapter holds the end of every foreground subagent that no tool call launched, and reports it when the turn ends at the latest. - **`messageCame` returns a promise only when it reports an end.** The v1 loop calls it for every message, and an `await` on each one let a cancel run between a message and its handling. ## What a client gets - **Typed:** the child stays `running` until the command ends, then gets its tool calls and text together, then `idle`. Claude Code writes the fork's messages only then, so the transcript is not live. - **Skill tool:** the child's work is live. The Skill call carries the RFD's `session` reference on an update with content, such as a failed result. - **A subagent that a typed skill launches** gets no session: Claude Code reports the end of its task before the Agent call that launched it. That call is a tool call of the skill's child. - **`session/cancel` of the root:** a typed skill's messages are the output of stopped work, which the adapter drops. The child reports `idle` with `cancelled`. - **`session/cancel` of the child:** its messages still go to it, before its `idle` with `cancelled`. - **Replay:** no child for a forked skill. The Skill call stays a tool call. `docs/subagent-sessions.md` and the AIR section of `docs/air-extensions.md` describe this. ## Testing - Against the real CLI (2.1.328, Haiku), on v2 and on v1 with `clientCapabilities.subagents`: a typed skill, a typed skill that launches a subagent, a Skill call, a cancel of the root, and a cancel of the child. - New unit tests for the v2 core, the v1 agent and the shared runtime, built from the captured frames. They fail without the change. - A new integration case (`v2-integration.test.ts`) runs a typed forked skill against the real CLI. It fails without the `agent_id` routing. - `npm run build`, `npm run check`, and the whole suite against the real CLI (`RUN_INTEGRATION_TESTS=true`): 4440 passed, 9 skipped. An earlier run had one failure, a temp-directory cleanup race (`ENOTEMPTY`) in `acp-agent-settings.test.ts`, which passed on three reruns.
This commit is contained in:
@@ -1313,6 +1313,10 @@ This section covers only the AIR bridge.
|
||||
The source is the `task_started` prompt, else the Agent or Task input `prompt`.
|
||||
A resumed generation gets the SendMessage `message` text.
|
||||
The field is absent when the adapter has no prompt. The adapter does not truncate it.
|
||||
- A forked skill (`context: fork`, such as `/code-review`) is a child session too, without an Agent or Task call.
|
||||
The parent of one that Claude runs with the Skill tool is the session that made the Skill call, which stays a tool call.
|
||||
The parent of one that the user types is the root session.
|
||||
Claude Code sends the output of a typed one only when the command ends: its `subagent_state_update` follows that output.
|
||||
- Without either signal, Agent and Task stay ordinary tool calls. AIR gets `_meta.jetbrains.air.subagent: true` on them.
|
||||
Child interactions stay on the root session.
|
||||
- A client that uses the older `_meta["subagent-transcript"]` capability or the `forwardSubagentText` session option keeps the flat child transcript.
|
||||
|
||||
@@ -32,6 +32,25 @@ Task subagent as its own child session, following the [subagents RFD](https://gi
|
||||
message to the parent instead, in both transcripts and linked the same way.
|
||||
- A launch whose child is never exposed is shown as a tool call after all, with its final
|
||||
status.
|
||||
- A forked skill (a skill with `context: fork`, such as `/code-review`) is a child session too.
|
||||
Claude Code runs it as a subagent that no Agent or Task call launched:
|
||||
- When Claude runs it with the Skill tool, the child is announced on the session that made the
|
||||
Skill call, once Claude Code reports its task. The Skill call stays a tool call of that session,
|
||||
with the skill's result. The skill's prompt is a `session_message` in the child's transcript
|
||||
only, with the Skill call's tool use id.
|
||||
- When the user types it, there is no call: the child is announced on the root session, and the
|
||||
command's output is the root's message. Claude Code (2.1.328) sends such a child's messages
|
||||
only when the command ends, after it reports the task's end. The adapter keeps the child
|
||||
`running` until they came, so its `idle` follows its tool calls and text. They all arrive at
|
||||
once: the child's transcript is not live.
|
||||
- A subagent that a typed skill launches gets no session: Claude Code reports the end of its
|
||||
task before the Agent call that launched it. That call is a tool call of the skill's child,
|
||||
with its final status.
|
||||
- After a `session/cancel` of the root session, a typed skill's messages are the output of
|
||||
stopped work, which the adapter drops: the child reports `idle` with `cancelled` and no more.
|
||||
After a `session/cancel` of the child itself, they still go to the child, before its `idle`
|
||||
with `cancelled`.
|
||||
- A replay shows no child for a forked skill. The Skill call stays a tool call.
|
||||
- On v1, the parent's prompt turn ends at its result, also while a background child that it
|
||||
launched or resumed still runs. The child's updates and requests follow the prompt response: the
|
||||
RFD has a client keep receiving child events after it. The parent's summary when the child ends
|
||||
@@ -48,10 +67,11 @@ Task subagent as its own child session, following the [subagents RFD](https://gi
|
||||
carries the RFD's `session` content, `{ "type": "session", "sessionId": "<child>" }`, after its
|
||||
other content: a TaskStop call whose `task_id`, or a SendMessage call whose `to`, is the child's
|
||||
agent id; a SendMessage call that resumed the child and stays shown because a permission request
|
||||
showed it first; and, on v1, an Agent or Task call that stays shown for the same reason. A
|
||||
`tool_call_update` without content carries none, since it would replace the content the client
|
||||
holds. A call that names the child by its name gets no reference: Claude Code resolves the
|
||||
name, and the adapter cannot tell which agent it picked.
|
||||
showed it first; on v1, an Agent or Task call that stays shown for the same reason; and the
|
||||
Skill call that launched a forked skill's child. A `tool_call_update` without content carries
|
||||
none, since it would replace the content the client holds. A call that names the child by its
|
||||
name gets no reference: Claude Code resolves the name, and the adapter cannot tell which agent it
|
||||
picked.
|
||||
- `session/cancel` on the parent interrupts Claude Code, which stops the foreground children that
|
||||
the turn waits on. Background children keep running, as the RFD prefers; a client stops one with
|
||||
its own `cancel`. Each stopped child reports `idle` with `cancelled` from Claude Code's own
|
||||
|
||||
@@ -58,6 +58,14 @@ export type NativeSubagent = {
|
||||
endedRuns?: Set<string>;
|
||||
/** The RFD form: the calls that delegated to the child, whose runs handed back a report. */
|
||||
handedBack?: Set<string>;
|
||||
/** Whether a message of it came (see `NativeSubagentRuntime.messageCame`). */
|
||||
heard?: boolean;
|
||||
/**
|
||||
* The RFD form: the call that launched it is no Agent or Task call, such as
|
||||
* the Skill call of a forked skill. The client is shown that call, so the
|
||||
* prompt does not replace it.
|
||||
*/
|
||||
launchShown?: boolean;
|
||||
announced?: boolean;
|
||||
/**
|
||||
* The RFD form: the `cwd` that the client holds for the child. Undefined or
|
||||
@@ -126,6 +134,8 @@ export type TaskEnd = {
|
||||
* conversation was reset, and the runtime forgets its children.
|
||||
*/
|
||||
unobservable?: boolean;
|
||||
/** Whether the task ran in the foreground of its parent's work when it ended. */
|
||||
foreground?: boolean;
|
||||
};
|
||||
|
||||
type TaskStarted = {
|
||||
@@ -134,8 +144,52 @@ type TaskStarted = {
|
||||
subagentType?: unknown;
|
||||
description?: unknown;
|
||||
prompt?: unknown;
|
||||
/** The name of the tool of the call `toolUseId`, when the session has that call. */
|
||||
launchTool?: string;
|
||||
/** The task of the subagent that started this one. None means the root session. */
|
||||
parentTaskId?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether the end of a subagent's run waits for its messages. Claude Code
|
||||
* (2.1.328) holds the messages of a forked skill that the user typed, such as
|
||||
* `/code-review`, and writes them after its next `init` or before its next
|
||||
* result: most or all of them come after the task's end. Nothing but that
|
||||
* order tells such a subagent apart: no tool call launched it, and it ran in
|
||||
* the foreground.
|
||||
*/
|
||||
export function endWaitsForMessages(run: { launched: boolean; foreground: boolean }): boolean {
|
||||
return !run.launched && run.foreground;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `message` ends the wait of an agent's end (see
|
||||
* {@link endWaitsForMessages}):
|
||||
*
|
||||
* - the turn's result, which Claude Code writes after the agent's messages;
|
||||
* - Claude Code's `idle`, for a turn that ends without a result;
|
||||
* - once a message of the agent came (`heard`), the first message of the main
|
||||
* conversation (`parent_tool_use_id: null`). Another subagent's message
|
||||
* ends no wait: Claude Code holds the messages of the subagents that the
|
||||
* agent launched along with the agent's own.
|
||||
*
|
||||
* Without a message, no more come: the turn or the query ended, or the
|
||||
* conversation was reset.
|
||||
*/
|
||||
export function endsMessageWait(
|
||||
message:
|
||||
{ type: string; subtype?: unknown; state?: unknown; parent_tool_use_id?: unknown } | undefined,
|
||||
heard: boolean,
|
||||
): boolean {
|
||||
if (message === undefined || message.type === "result") return true;
|
||||
if (message.type === "system") {
|
||||
return message.subtype === "session_state_changed" && message.state === "idle";
|
||||
}
|
||||
const conversation =
|
||||
message.type === "assistant" || message.type === "user" || message.type === "stream_event";
|
||||
return conversation && heard && message.parent_tool_use_id === null;
|
||||
}
|
||||
|
||||
export type SubagentIdentity = {
|
||||
name?: string;
|
||||
description?: string;
|
||||
@@ -204,6 +258,8 @@ export class NativeSubagentRuntime {
|
||||
*/
|
||||
private readonly childByToolCall = new Map<string, NativeSubagent>();
|
||||
private readonly taskFinishPromises = new Map<string, Promise<void>>();
|
||||
/** The ends that wait for their tasks' messages (see {@link finishTask}), by task id. */
|
||||
private readonly heldEnds = new Map<string, { status: unknown; end?: TaskEnd }>();
|
||||
/** The session that made each SendMessage call. */
|
||||
private readonly senderByToolUse = new Map<string, string>();
|
||||
/**
|
||||
@@ -629,6 +685,87 @@ export class NativeSubagentRuntime {
|
||||
return notification;
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes a message of the query, before its updates are routed.
|
||||
*
|
||||
* A subagent's message names it by `agent_id`. A child that no tool call
|
||||
* launched has no id that its updates could go by: a forked skill that the
|
||||
* user typed sends `forked-command-<skill>` as `parent_tool_use_id`, for
|
||||
* every run of the skill. From this message on, the updates under that id
|
||||
* are the child's, and no longer those of an earlier run's child.
|
||||
*
|
||||
* It also ends the runs whose ends waited for their messages (see
|
||||
* {@link finishTask} and {@link endsMessageWait}). Only then does it return
|
||||
* a promise, for the caller to await: a caller that awaited every message
|
||||
* would let a cancel run between a message and its handling.
|
||||
*/
|
||||
messageCame(
|
||||
message: {
|
||||
type: string;
|
||||
subtype?: unknown;
|
||||
state?: unknown;
|
||||
parent_tool_use_id?: unknown;
|
||||
agent_id?: unknown;
|
||||
},
|
||||
deliver: Publish,
|
||||
): Promise<void> | undefined {
|
||||
if (!this.enabled) return undefined;
|
||||
const { parent_tool_use_id: launchId, agent_id: agentId } = message;
|
||||
const child = typeof agentId === "string" ? this.children.get(agentId) : undefined;
|
||||
if (child && typeof agentId === "string" && typeof launchId === "string") {
|
||||
child.heard = true;
|
||||
if (
|
||||
child.parentToolUseId === undefined &&
|
||||
this.childByParentToolUse.get(launchId) !== child
|
||||
) {
|
||||
this.taskByToolUse.set(launchId, agentId);
|
||||
this.childByParentToolUse.set(launchId, child);
|
||||
}
|
||||
}
|
||||
return this.releaseHeldEnds(deliver, message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ends the runs whose wait `message` ends; without a message, all of them.
|
||||
* Undefined when it ends none.
|
||||
*/
|
||||
private releaseHeldEnds(
|
||||
deliver: Publish,
|
||||
message?: Parameters<typeof endsMessageWait>[0],
|
||||
): Promise<void> | undefined {
|
||||
if (this.heldEnds.size === 0) return undefined;
|
||||
const ended = [...this.heldEnds].filter(([taskId]) =>
|
||||
endsMessageWait(message, this.children.get(taskId)?.heard === true),
|
||||
);
|
||||
if (ended.length === 0) return undefined;
|
||||
return (async () => {
|
||||
for (const [taskId, held] of ended) {
|
||||
this.heldEnds.delete(taskId);
|
||||
await this.finishTask(taskId, held.status, deliver, undefined, held.end);
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
/**
|
||||
* The session of the call that launched `task`, when the session has that
|
||||
* call and it is no Agent, Task or SendMessage call, such as the Skill call
|
||||
* of a forked skill: the session of the subagent that made it, once that
|
||||
* one is announced, or the root session.
|
||||
*/
|
||||
private shownLaunchParent(task: TaskStarted): string | undefined {
|
||||
if (
|
||||
!task.toolUseId ||
|
||||
task.launchTool === undefined ||
|
||||
task.launchTool === "SendMessage" ||
|
||||
isNativeSubagentControlTool(task.launchTool)
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
if (task.parentTaskId === undefined) return this.rootSessionId;
|
||||
const parent = this.children.get(task.parentTaskId);
|
||||
return parent?.announced ? parent.sessionId : undefined;
|
||||
}
|
||||
|
||||
async taskStarted(task: TaskStarted, deliver: Publish): Promise<void> {
|
||||
if (!this.enabled) return;
|
||||
const known =
|
||||
@@ -678,9 +815,11 @@ export class NativeSubagentRuntime {
|
||||
|
||||
// A SendMessage resume reuses the finished generation's tool id, whose
|
||||
// control state is already cleaned up.
|
||||
const shownLaunchParent = this.shownLaunchParent(task);
|
||||
const knownParentSessionId =
|
||||
(task.toolUseId ? this.parentByToolUse.get(task.toolUseId) : undefined) ??
|
||||
(previous && this.resumedParentSessionId(previous));
|
||||
(previous && this.resumedParentSessionId(previous)) ??
|
||||
shownLaunchParent;
|
||||
const identity = task.toolUseId ? this.identityByToolUse.get(task.toolUseId) : undefined;
|
||||
// A nested child must wait for the spawning Agent/Task frame to establish
|
||||
// its immediate parent. Root children without a tool id can be announced.
|
||||
@@ -706,6 +845,7 @@ export class NativeSubagentRuntime {
|
||||
identity?.subagentType ?? task.subagentType,
|
||||
identity?.description ?? task.description,
|
||||
),
|
||||
...(shownLaunchParent !== undefined ? { launchShown: true } : {}),
|
||||
},
|
||||
!!knownParentSessionId || !task.toolUseId,
|
||||
deliver,
|
||||
@@ -804,6 +944,8 @@ export class NativeSubagentRuntime {
|
||||
/**
|
||||
* Reports that the SDK ended the task's work. `end` has what the SDK says
|
||||
* about it: its text for a failure, and its reason for an unusual end.
|
||||
* The end of a child whose messages Claude Code holds until after it (see
|
||||
* {@link endWaitsForMessages}) is reported once they came.
|
||||
*/
|
||||
async finishTask(
|
||||
taskId: string,
|
||||
@@ -834,6 +976,23 @@ export class NativeSubagentRuntime {
|
||||
if (this.form === "rfd") await this.supplyError(child, state, end?.error);
|
||||
return;
|
||||
}
|
||||
const held = this.heldEnds.get(taskId);
|
||||
if (held) {
|
||||
// A second report of an end that waits can give the text of its failure.
|
||||
if (end?.error && !held.end?.error) held.end = { ...held.end, error: end.error };
|
||||
return;
|
||||
}
|
||||
if (
|
||||
child.announced &&
|
||||
endWaitsForMessages({
|
||||
launched: child.parentToolUseId !== undefined,
|
||||
foreground: end?.foreground === true,
|
||||
})
|
||||
) {
|
||||
// The run ends once its messages came (see `messageCame`).
|
||||
this.heldEnds.set(taskId, { status, end: { ...end, foreground: false } });
|
||||
return;
|
||||
}
|
||||
|
||||
const finish = Promise.resolve().then(async () => {
|
||||
try {
|
||||
@@ -896,6 +1055,12 @@ export class NativeSubagentRuntime {
|
||||
: mayStillRun
|
||||
? { unobservable: true }
|
||||
: { unexplained: true };
|
||||
try {
|
||||
// An end that waited for its task's messages is that task's end.
|
||||
await this.releaseHeldEnds(deliver);
|
||||
} catch (error) {
|
||||
errors.push(error);
|
||||
}
|
||||
try {
|
||||
for (const taskId of [...this.children.keys()].reverse()) {
|
||||
try {
|
||||
@@ -1519,7 +1684,9 @@ export class NativeSubagentRuntime {
|
||||
* - a SendMessage call that resumed the child, and stays shown because a
|
||||
* permission request showed it;
|
||||
* - an Agent/Task call that launched the child, and stays shown for the
|
||||
* same reason.
|
||||
* same reason;
|
||||
* - the call that launched a child and is no Agent/Task call, such as the
|
||||
* Skill call of a forked skill, which always stays shown.
|
||||
*
|
||||
* The RFD requires the announcement before the reference, so a call whose
|
||||
* child is not announced yet gets none.
|
||||
@@ -1599,6 +1766,7 @@ export class NativeSubagentRuntime {
|
||||
this.cwdBySession.clear();
|
||||
this.childByParentToolUse.clear();
|
||||
this.taskFinishPromises.clear();
|
||||
this.heldEnds.clear();
|
||||
this.senderByToolUse.clear();
|
||||
this.hiddenLaunches.clear();
|
||||
this.hiddenSendMessages.clear();
|
||||
@@ -1698,6 +1866,7 @@ export class NativeSubagentRuntime {
|
||||
| "title"
|
||||
| "role"
|
||||
| "description"
|
||||
| "launchShown"
|
||||
>,
|
||||
announce: boolean,
|
||||
deliver: Publish,
|
||||
@@ -1824,7 +1993,8 @@ export async function announceNativeSubagent(
|
||||
});
|
||||
if (cwd) child.reportedCwd = cwd;
|
||||
child.announced = true;
|
||||
// The immediate parent made the Agent/Task call that launched the child.
|
||||
// The immediate parent made the call that launched the child. The
|
||||
// prompt replaces an Agent/Task call, and not a call that stays shown.
|
||||
if (child.prompt) {
|
||||
await publishPrompt(
|
||||
child,
|
||||
@@ -1832,7 +2002,7 @@ export async function announceNativeSubagent(
|
||||
child.parentToolUseId,
|
||||
child.parentSessionId,
|
||||
publish,
|
||||
{ replacesCall: true },
|
||||
{ replacesCall: !child.launchShown },
|
||||
);
|
||||
}
|
||||
return;
|
||||
|
||||
@@ -1949,6 +1949,267 @@ describe("NativeSubagentRuntime in the RFD form", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("a forked skill", () => {
|
||||
/** The `parent_tool_use_id` of every message of a typed `/code-review`. */
|
||||
const FORKED = "forked-command-code-review";
|
||||
/** The `task_started` of a typed `/code-review`: no tool call launched it. */
|
||||
const typed = {
|
||||
taskId: "fork-1",
|
||||
subagentType: "general-purpose",
|
||||
description: "/code-review",
|
||||
prompt: "Review the diff",
|
||||
};
|
||||
const forkMessage = (agentId: string) => ({
|
||||
type: "assistant",
|
||||
parent_tool_use_id: FORKED,
|
||||
agent_id: agentId,
|
||||
});
|
||||
const rootMessage = { type: "assistant", parent_tool_use_id: null };
|
||||
const skillCall = (toolCallId: string, parentToolUseId?: string): AcpSessionNotification =>
|
||||
({
|
||||
sessionId: "root",
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId,
|
||||
title: "Load skill: code-review",
|
||||
status: "pending",
|
||||
rawInput: { skill: "code-review" },
|
||||
_meta: {
|
||||
claudeCode: { toolName: "Skill", ...(parentToolUseId ? { parentToolUseId } : {}) },
|
||||
},
|
||||
},
|
||||
}) as AcpSessionNotification;
|
||||
|
||||
/** A runtime, the updates it sends in order, and the deliver function of
|
||||
* the agent, which sends what the runtime routes (as `sendUpdate` does). */
|
||||
function setup(form: "rfd" | "air" = "rfd") {
|
||||
const sent: AcpSessionNotification[] = [];
|
||||
const runtime: NativeSubagentRuntime = new NativeSubagentRuntime(
|
||||
form,
|
||||
"root",
|
||||
{},
|
||||
async (notification) => {
|
||||
sent.push(notification);
|
||||
},
|
||||
{ log: () => {} },
|
||||
);
|
||||
const deliver = async (notification: AcpSessionNotification): Promise<void> => {
|
||||
const routed = await runtime.route(notification, deliver);
|
||||
if (routed) sent.push(routed);
|
||||
};
|
||||
return { runtime, sent, deliver };
|
||||
}
|
||||
/** The child's text and its ends, in order, as "<session> <what>". */
|
||||
const story = (sent: AcpSessionNotification[]) =>
|
||||
sent.flatMap(({ sessionId, update }) =>
|
||||
update.sessionUpdate === "agent_message_chunk"
|
||||
? [`${sessionId} text`]
|
||||
: update.sessionUpdate === "subagent_state_update"
|
||||
? [`${update.subagentSessionId} ${update.state}`]
|
||||
: update.sessionUpdate === "subagent_update" && update.state?.state === "idle"
|
||||
? [`${update.sessionId} idle ${update.state.stopReason}`]
|
||||
: [],
|
||||
);
|
||||
const announcements = (sent: AcpSessionNotification[]) =>
|
||||
sent.flatMap(({ sessionId, update }) =>
|
||||
update.sessionUpdate === "subagent_update" && update.title !== undefined
|
||||
? [[sessionId, update.sessionId]]
|
||||
: [],
|
||||
);
|
||||
|
||||
it("that the user typed gets the updates of its messages by their agent id, for each run", async () => {
|
||||
const { runtime, sent, deliver } = setup();
|
||||
for (const taskId of ["fork-1", "fork-2"]) {
|
||||
await runtime.taskStarted({ ...typed, taskId }, deliver);
|
||||
await runtime.messageCame(forkMessage(taskId), deliver);
|
||||
await deliver(output(FORKED));
|
||||
}
|
||||
|
||||
expect(story(sent)).toEqual(["fork-1 text", "fork-2 text"]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["rfd", "fork-1 idle end_turn"],
|
||||
["air", "fork-1 completed"],
|
||||
] as const)(
|
||||
"that the user typed ends after its messages, which come after its task's end (%s)",
|
||||
async (form, end) => {
|
||||
const { runtime, sent, deliver } = setup(form);
|
||||
await runtime.taskStarted(typed, deliver);
|
||||
await runtime.finishTask("fork-1", "completed", deliver, undefined, { foreground: true });
|
||||
// A second report of the end, and the turn's `init`, end no wait.
|
||||
await runtime.finishTask("fork-1", "completed", deliver);
|
||||
await runtime.messageCame({ type: "system", subtype: "init" }, deliver);
|
||||
// Neither does a message of the root before the child's.
|
||||
await runtime.messageCame(rootMessage, deliver);
|
||||
expect(story(sent)).toEqual([]);
|
||||
|
||||
await runtime.messageCame(forkMessage("fork-1"), deliver);
|
||||
await deliver(output(FORKED));
|
||||
// Nor a message of a subagent that the skill launched, which Claude
|
||||
// Code holds along with the skill's own.
|
||||
await runtime.messageCame(
|
||||
{ type: "assistant", parent_tool_use_id: "toolu_nested", agent_id: "nested-1" },
|
||||
deliver,
|
||||
);
|
||||
await runtime.messageCame(forkMessage("fork-1"), deliver);
|
||||
await deliver(output(FORKED));
|
||||
expect(story(sent)).toEqual(["fork-1 text", "fork-1 text"]);
|
||||
|
||||
await runtime.messageCame(rootMessage, deliver);
|
||||
expect(story(sent)).toEqual(["fork-1 text", "fork-1 text", end]);
|
||||
},
|
||||
);
|
||||
|
||||
it("that the user typed also waits when some of its messages came before its task's end", async () => {
|
||||
const { runtime, sent, deliver } = setup();
|
||||
await runtime.taskStarted(typed, deliver);
|
||||
// Claude Code wrote an `init` while the command ran: the messages so far came.
|
||||
await runtime.messageCame(forkMessage("fork-1"), deliver);
|
||||
await deliver(output(FORKED));
|
||||
await runtime.finishTask("fork-1", "completed", deliver, undefined, { foreground: true });
|
||||
await runtime.messageCame(forkMessage("fork-1"), deliver);
|
||||
await deliver(output(FORKED));
|
||||
expect(story(sent)).toEqual(["fork-1 text", "fork-1 text"]);
|
||||
|
||||
await runtime.messageCame(rootMessage, deliver);
|
||||
expect(story(sent)).toEqual(["fork-1 text", "fork-1 text", "fork-1 idle end_turn"]);
|
||||
});
|
||||
|
||||
it("reports a failure's text that only a second report of the waiting end gives", async () => {
|
||||
const { runtime, sent, deliver } = setup();
|
||||
await runtime.taskStarted(typed, deliver);
|
||||
await runtime.finishTask("fork-1", "failed", deliver, undefined, { foreground: true });
|
||||
await runtime.finishTask("fork-1", "failed", deliver, undefined, { error: "boom" });
|
||||
await runtime.messageCame({ type: "result" }, deliver);
|
||||
|
||||
expect(sent.at(-1)?.update).toMatchObject({
|
||||
sessionUpdate: "subagent_update",
|
||||
state: { state: "idle", stopReason: "error", error: { message: "boom" } },
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"at the turn's result",
|
||||
(runtime: NativeSubagentRuntime) => runtime.messageCame({ type: "result" }, async () => {}),
|
||||
],
|
||||
[
|
||||
"at Claude Code's idle",
|
||||
(runtime: NativeSubagentRuntime) =>
|
||||
runtime.messageCame(
|
||||
{ type: "system", subtype: "session_state_changed", state: "idle" },
|
||||
async () => {},
|
||||
),
|
||||
],
|
||||
[
|
||||
"with the stream",
|
||||
(runtime: NativeSubagentRuntime) => runtime.finishAll("completed", async () => {}),
|
||||
],
|
||||
])(
|
||||
"that the user typed ends %s, as its task ended, when no message of it comes",
|
||||
async (_, end) => {
|
||||
const { runtime, sent, deliver } = setup();
|
||||
await runtime.taskStarted(typed, deliver);
|
||||
await runtime.finishTask("fork-1", "stopped", deliver, undefined, { foreground: true });
|
||||
expect(story(sent)).toEqual([]);
|
||||
|
||||
await end(runtime);
|
||||
|
||||
expect(story(sent)).toEqual(["fork-1 idle cancelled"]);
|
||||
},
|
||||
);
|
||||
|
||||
it("ends with its task when it runs in the background", async () => {
|
||||
const { runtime, sent, deliver } = setup();
|
||||
await runtime.taskStarted(typed, deliver);
|
||||
|
||||
await runtime.finishTask("fork-1", "completed", deliver, undefined, { foreground: false });
|
||||
|
||||
expect(story(sent)).toEqual(["fork-1 idle end_turn"]);
|
||||
});
|
||||
|
||||
it("that Claude called is announced on the root, with the Skill call shown and the prompt as its message only", async () => {
|
||||
const { runtime, sent, deliver } = setup();
|
||||
await deliver(skillCall("skill-1"));
|
||||
await runtime.taskStarted({ ...typed, toolUseId: "skill-1", launchTool: "Skill" }, deliver);
|
||||
await deliver(output("skill-1"));
|
||||
|
||||
expect(sent.map(({ sessionId, update }) => [sessionId, update.sessionUpdate])).toEqual([
|
||||
["root", "tool_call"],
|
||||
["root", "subagent_update"],
|
||||
["fork-1", "session_message"],
|
||||
["fork-1", "agent_message_chunk"],
|
||||
]);
|
||||
expect(sent[2]?.update).toEqual({
|
||||
sessionUpdate: "session_message",
|
||||
messageId: "skill-1",
|
||||
senderSessionId: "root",
|
||||
recipientSessionId: "fork-1",
|
||||
content: [{ type: "text", text: "Review the diff" }],
|
||||
});
|
||||
});
|
||||
|
||||
it("references the child from the Skill call that launched it", async () => {
|
||||
const { runtime, sent, deliver } = setup();
|
||||
await deliver(skillCall("skill-1"));
|
||||
await runtime.taskStarted({ ...typed, toolUseId: "skill-1", launchTool: "Skill" }, deliver);
|
||||
const failure = [{ type: "content", content: { type: "text", text: "The skill failed" } }];
|
||||
await deliver({
|
||||
sessionId: "root",
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: "skill-1",
|
||||
status: "failed",
|
||||
content: failure,
|
||||
_meta: { claudeCode: { toolName: "Skill" } },
|
||||
},
|
||||
} as AcpSessionNotification);
|
||||
|
||||
expect(sent.at(-1)).toMatchObject({
|
||||
sessionId: "root",
|
||||
update: { content: [...failure, { type: "session", sessionId: "fork-1" }] },
|
||||
});
|
||||
});
|
||||
|
||||
it("that a subagent called is announced on that subagent's session, once it is announced", async () => {
|
||||
const { runtime, sent, deliver } = setup();
|
||||
const nested = { ...typed, launchTool: "Skill", parentTaskId: "worker-1" };
|
||||
// worker-1 is known, but its launch frame has not come: not announced.
|
||||
await runtime.taskStarted(
|
||||
{ taskId: "worker-1", toolUseId: "launch-1", subagentType: "Explore" },
|
||||
deliver,
|
||||
);
|
||||
await runtime.taskStarted({ ...nested, taskId: "fork-0", toolUseId: "skill-0" }, deliver);
|
||||
expect(announcements(sent)).toEqual([]);
|
||||
|
||||
await deliver(launch("launch-1", { description: "Fix the build" }));
|
||||
await deliver(skillCall("skill-1", "launch-1"));
|
||||
await runtime.taskStarted({ ...nested, toolUseId: "skill-1" }, deliver);
|
||||
|
||||
expect(announcements(sent)).toEqual([
|
||||
["root", "worker-1"],
|
||||
["worker-1", "fork-1"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps an agent that a SendMessage call resumed and the history cannot place unexposed", async () => {
|
||||
const { runtime, sent, deliver } = setup();
|
||||
// The call's update did not come: the subagent that made it is not announced.
|
||||
await runtime.taskStarted(
|
||||
{
|
||||
taskId: "old-1",
|
||||
toolUseId: "send-1",
|
||||
subagentType: "Explore",
|
||||
launchTool: "SendMessage",
|
||||
},
|
||||
deliver,
|
||||
);
|
||||
|
||||
expect(announcements(sent)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
it("titles the child by the name a late frame gives it, and keeps its role", async () => {
|
||||
const published: AcpSessionNotification[] = [];
|
||||
const runtime = new NativeSubagentRuntime(
|
||||
|
||||
@@ -4233,6 +4233,35 @@ describe("subagent transcript replay", () => {
|
||||
}
|
||||
}
|
||||
|
||||
it("replays a forked skill as its Skill call, without a child", async () => {
|
||||
const trace = await replayRfd(
|
||||
[
|
||||
user("u1", "Review it"),
|
||||
assistant("a1", [toolUse("toolu_skill", "Skill", { skill: "code-review" })]),
|
||||
user("u2", [
|
||||
toolResult("toolu_skill", 'Skill "code-review" completed (forked execution).'),
|
||||
]),
|
||||
],
|
||||
{
|
||||
// Claude Code 2.1.328 names no call in the metadata of a forked skill's agent.
|
||||
fork9: {
|
||||
meta: {
|
||||
agentType: "general-purpose",
|
||||
isBuiltIn: true,
|
||||
spawnDepth: 1,
|
||||
requestShape: "foreground",
|
||||
},
|
||||
records: [
|
||||
user("f1", "Review the diff"),
|
||||
assistant("f2", [{ type: "text", text: "Off by one." }]),
|
||||
],
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
expect(trace).toEqual(["root user_message_chunk Review it", "root tool_call toolu_skill"]);
|
||||
});
|
||||
|
||||
it("announces a worktree child with its recorded cwd, and clears it when the worktree is gone", async () => {
|
||||
const worktree = "/tmp/proj/.claude/worktrees/agent-wt1";
|
||||
const trace = await replayRfd(
|
||||
@@ -8176,6 +8205,251 @@ describe("subagent permission attribution (issue #851)", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("a forked skill", () => {
|
||||
/**
|
||||
* The frames of the forked skill `agentId`, as Claude Code 2.1.328 sends
|
||||
* them for `/code-review`. Its messages carry `launchId`: the id of the
|
||||
* Skill call that Claude made, or `forked-command-code-review` for a
|
||||
* skill that the user typed, which no call launched.
|
||||
*/
|
||||
const fork = (agentId: string, launchId: string) => {
|
||||
const system = (subtype: string, more: Record<string, unknown>) => ({
|
||||
type: "system",
|
||||
subtype,
|
||||
task_id: agentId,
|
||||
skip_transcript: true,
|
||||
ambient: true,
|
||||
uuid: randomUUID(),
|
||||
session_id: "test-session",
|
||||
...more,
|
||||
});
|
||||
return {
|
||||
started: (more: Record<string, unknown> = {}) =>
|
||||
system("task_started", {
|
||||
description: "/code-review",
|
||||
subagent_type: "general-purpose",
|
||||
is_backgrounded: false,
|
||||
spawn_depth: 1,
|
||||
task_type: "local_agent",
|
||||
prompt: "Review the diff",
|
||||
...more,
|
||||
}),
|
||||
ended: (more: Record<string, unknown> = {}) =>
|
||||
system("task_notification", {
|
||||
status: "completed",
|
||||
output_file: "",
|
||||
summary: "/code-review",
|
||||
...more,
|
||||
}),
|
||||
/** Its call `toolUseId` of the Bash tool. */
|
||||
runs: (toolUseId: string) => ({
|
||||
...rootToolUse(toolUseId, "Bash", { command: "git diff HEAD" }),
|
||||
parent_tool_use_id: launchId,
|
||||
agent_id: agentId,
|
||||
subagent_type: "general-purpose",
|
||||
}),
|
||||
/** The result of its call `toolUseId`. */
|
||||
ran: (toolUseId: string) => ({
|
||||
type: "user",
|
||||
parent_tool_use_id: launchId,
|
||||
agent_id: agentId,
|
||||
subagent_type: "general-purpose",
|
||||
uuid: randomUUID(),
|
||||
session_id: "test-session",
|
||||
message: {
|
||||
role: "user",
|
||||
content: [{ type: "tool_result", tool_use_id: toolUseId, content: "done" }],
|
||||
},
|
||||
}),
|
||||
};
|
||||
};
|
||||
/** The output of a typed command, as the root's message. */
|
||||
const commandOutput = (text: string) => ({
|
||||
type: "assistant",
|
||||
parent_tool_use_id: null,
|
||||
uuid: randomUUID(),
|
||||
session_id: "test-session",
|
||||
message: {
|
||||
id: randomUUID(),
|
||||
model: "<synthetic>",
|
||||
role: "assistant",
|
||||
type: "message",
|
||||
stop_reason: "end_turn",
|
||||
content: [{ type: "text", text }],
|
||||
},
|
||||
});
|
||||
/** Where each Bash call and text went, and each announcement and end of a child, in order. */
|
||||
const story = (updates: AcpSessionNotification[]) =>
|
||||
updates.flatMap(({ sessionId, update }) =>
|
||||
update.sessionUpdate === "agent_message_chunk"
|
||||
? [`${sessionId}: ${(update.content as { text: string }).text}`]
|
||||
: update.sessionUpdate === "tool_call" && update.toolCallId.startsWith("toolu_diff")
|
||||
? [`${sessionId}: ${update.toolCallId}`]
|
||||
: update.sessionUpdate === "subagent_update" && update.state
|
||||
? [
|
||||
`${sessionId}: ${update.sessionId} ${update.state.state}` +
|
||||
("stopReason" in update.state ? ` ${update.state.stopReason}` : ""),
|
||||
]
|
||||
: [],
|
||||
);
|
||||
|
||||
it.each([
|
||||
["task_notification", (typed: ReturnType<typeof fork>) => [typed.ended()], "end_turn"],
|
||||
[
|
||||
"terminal task_updated patch",
|
||||
() => [{ ...taskUpdated({ status: "completed" }), task_id: "a995b1" }],
|
||||
"end_turn",
|
||||
],
|
||||
[
|
||||
// As seen live, when the client cancels the child session.
|
||||
"task's stop, which Claude Code reports twice",
|
||||
(typed: ReturnType<typeof fork>) => [
|
||||
{ ...taskUpdated({ status: "killed" }), task_id: "a995b1" },
|
||||
typed.ended({ status: "stopped" }),
|
||||
],
|
||||
"cancelled",
|
||||
],
|
||||
])(
|
||||
"that the user typed gets its messages, which come after its %s, before its idle",
|
||||
async (_, ended, stopReason) => {
|
||||
const typed = fork("a995b1", "forked-command-code-review");
|
||||
const updates = await run([
|
||||
typed.started(),
|
||||
...ended(typed),
|
||||
typed.runs("toolu_diff"),
|
||||
commandOutput("Off by one."),
|
||||
]);
|
||||
|
||||
expect(story(updates)).toEqual([
|
||||
"test-session: a995b1 running",
|
||||
"a995b1: toolu_diff",
|
||||
`test-session: a995b1 idle ${stopReason}`,
|
||||
"test-session: Off by one.",
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
it("that the user typed and launched a subagent stays running through that subagent's messages", async () => {
|
||||
const typed = fork("a71bcc", "forked-command-code-review");
|
||||
const nested = fork("ac5905", "toolu_agent");
|
||||
const updates = await run([
|
||||
typed.started(),
|
||||
// Claude Code reports the subagent's task as it runs, and holds its
|
||||
// messages along with the skill's own.
|
||||
nested.started({ tool_use_id: "toolu_agent", parent_task_id: "a71bcc" }),
|
||||
nested.ended({ tool_use_id: "toolu_agent" }),
|
||||
typed.ended(),
|
||||
{
|
||||
...rootToolUse("toolu_agent", "Agent", { description: "Echo", prompt: "Echo nested" }),
|
||||
parent_tool_use_id: "forked-command-code-review",
|
||||
agent_id: "a71bcc",
|
||||
},
|
||||
nested.runs("toolu_diff_nested"),
|
||||
nested.ran("toolu_diff_nested"),
|
||||
typed.ran("toolu_agent"),
|
||||
typed.runs("toolu_diff"),
|
||||
commandOutput("DONE"),
|
||||
]);
|
||||
|
||||
// The subagent's task ended before its Agent call came: it gets no session.
|
||||
expect(story(updates)).toEqual([
|
||||
"test-session: a71bcc running",
|
||||
"a71bcc: toolu_diff",
|
||||
"test-session: a71bcc idle end_turn",
|
||||
"test-session: DONE",
|
||||
]);
|
||||
});
|
||||
|
||||
it("that the user typed and a cancel of the root stopped shows none of its messages, and ends cancelled", async () => {
|
||||
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: { subagents: {} } as ClientCapabilities,
|
||||
});
|
||||
const typed = fork("a41595", "forked-command-code-review");
|
||||
const cancelled = Promise.withResolvers<void>();
|
||||
injectGeneratorSession(agent, async function* (input: Pushable<any>) {
|
||||
const { value } = await input[Symbol.asyncIterator]().next();
|
||||
yield typed.started();
|
||||
await cancelled.promise;
|
||||
// As seen live: the task's end, what Claude Code held, the prompt's
|
||||
// echo, and a result of no turn.
|
||||
yield typed.ended({ status: "stopped" });
|
||||
yield typed.runs("toolu_diff");
|
||||
yield typed.ran("toolu_diff");
|
||||
yield userEcho(value);
|
||||
yield { ...successResult(), num_turns: 0 };
|
||||
yield { type: "system", subtype: "session_state_changed", state: "idle" };
|
||||
} as never);
|
||||
const prompt = agent.prompt({
|
||||
sessionId: "test-session",
|
||||
prompt: [{ type: "text", text: "/code-review" }],
|
||||
});
|
||||
await vi.waitFor(() => expect(story(updates)).toEqual(["test-session: a41595 running"]));
|
||||
|
||||
await agent.cancel({ sessionId: "test-session" });
|
||||
cancelled.resolve();
|
||||
|
||||
await expect(prompt).resolves.toMatchObject({ stopReason: "cancelled" });
|
||||
await vi.waitFor(() =>
|
||||
expect(story(updates)).toEqual([
|
||||
"test-session: a41595 running",
|
||||
"test-session: a41595 idle cancelled",
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["Claude", [], null, "test-session"],
|
||||
[
|
||||
"a subagent",
|
||||
[{ ...taskStarted("agent-42", "toolu_parent"), subagent_type: "Explore" }],
|
||||
"toolu_parent",
|
||||
"agent-42",
|
||||
],
|
||||
])(
|
||||
"that %s called with the Skill tool is announced on the caller's session",
|
||||
async (_, before, callerLaunch, caller) => {
|
||||
const called = fork("a66033", "toolu_skill");
|
||||
const updates = await run([
|
||||
...before,
|
||||
{
|
||||
...rootToolUse("toolu_skill", "Skill", { skill: "code-review" }),
|
||||
parent_tool_use_id: callerLaunch,
|
||||
...(callerLaunch ? { agent_id: "agent-42" } : {}),
|
||||
},
|
||||
called.started({
|
||||
tool_use_id: "toolu_skill",
|
||||
...(callerLaunch ? { parent_task_id: "agent-42" } : {}),
|
||||
}),
|
||||
called.runs("toolu_diff"),
|
||||
called.ended({ tool_use_id: "toolu_skill" }),
|
||||
]);
|
||||
|
||||
expect(story(updates).filter((line) => line.includes("a66033"))).toEqual([
|
||||
`${caller}: a66033 running`,
|
||||
"a66033: toolu_diff",
|
||||
`${caller}: a66033 idle end_turn`,
|
||||
]);
|
||||
// The Skill call stays a tool call of the session that made it.
|
||||
expect(
|
||||
updates.find(
|
||||
({ update }) =>
|
||||
update.sessionUpdate === "tool_call" && update.toolCallId === "toolu_skill",
|
||||
)?.sessionId,
|
||||
).toBe(caller);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("session/cancel on a child session", () => {
|
||||
/**
|
||||
* Runs a turn whose child agent-42 runs until `stopped`, then ends as
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { spawn, spawnSync, type ChildProcess } from "node:child_process";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import * as os from "node:os";
|
||||
import * as path from "node:path";
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||
@@ -330,6 +330,55 @@ describe.skipIf(!process.env.RUN_INTEGRATION_TESTS)("v2 core with Claude Code",
|
||||
});
|
||||
}, 240_000);
|
||||
|
||||
// A forked skill that the user types runs as a subagent that no tool call
|
||||
// launched. Its child session rests on what the SDK's types do not promise:
|
||||
// a `task_started` without a tool call, messages that name the subagent by
|
||||
// `agent_id` only, and their order (Claude Code writes them after the
|
||||
// task's end and before the turn's result).
|
||||
it("gives the child of a typed forked skill its tool call and text, before its idle", async () => {
|
||||
const skill = path.join(cwd, ".claude", "skills", "forked");
|
||||
await mkdir(skill, { recursive: true });
|
||||
await writeFile(
|
||||
path.join(skill, "SKILL.md"),
|
||||
[
|
||||
"---",
|
||||
"name: forked",
|
||||
"description: Runs one command in a forked context",
|
||||
"context: fork",
|
||||
"---",
|
||||
"",
|
||||
"Run exactly this Bash command, with no other tool call: echo forked",
|
||||
"Then reply with just: done",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
const sessionId = await newSession("bypassPermissions");
|
||||
await prompt(sessionId, "/forked");
|
||||
await until(() => states(sessionId).some((update) => update.state === "idle"));
|
||||
|
||||
const announcement = updates.find(
|
||||
({ sessionId: id, update }) => id === sessionId && update.sessionUpdate === "subagent_update",
|
||||
);
|
||||
const childId = (announcement?.update as { sessionId?: string } | undefined)?.sessionId;
|
||||
expect(childId).toBeDefined();
|
||||
const child = updates.flatMap(({ sessionId: id, update }) => {
|
||||
if (id !== childId) return [];
|
||||
if (update.sessionUpdate === "state_update") return [update.state];
|
||||
if (update.sessionUpdate === "agent_message_chunk") return ["text"];
|
||||
const ended =
|
||||
update.sessionUpdate === "tool_call_update" &&
|
||||
(update as { status?: string }).status === "completed";
|
||||
return ended ? ["tool call"] : [];
|
||||
});
|
||||
expect(child).toEqual(["running", "tool call", "text", "idle"]);
|
||||
// The root has the command's output, and none of the child's tool calls.
|
||||
const root = updates.flatMap(({ sessionId: id, update }) =>
|
||||
id === sessionId ? [update.sessionUpdate] : [],
|
||||
);
|
||||
expect(root).toContain("agent_message_chunk");
|
||||
expect(root).not.toContain("tool_call_update");
|
||||
}, 180_000);
|
||||
|
||||
it("fails a queued prompt with -32800 at a cancel and goes idle with cancelled", async () => {
|
||||
const sessionId = await newSession("bypassPermissions");
|
||||
await prompt(
|
||||
|
||||
@@ -495,6 +495,65 @@ function subagent(agentId: string, launch: string, fields: Record<string, unknow
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A forked skill (`context: fork`), as Claude Code 2.1.328 runs
|
||||
* `/code-review`: a subagent that no Agent call launched. `call` is the Skill
|
||||
* call that Claude made for it. A skill that the user typed has no call: its
|
||||
* `task_started` names none, and its messages carry
|
||||
* `forked-command-code-review` for every run.
|
||||
*/
|
||||
function forkedSkill(agentId: string, call?: string) {
|
||||
const from = {
|
||||
parent_tool_use_id: call ?? "forked-command-code-review",
|
||||
agent_id: agentId,
|
||||
subagent_type: "general-purpose",
|
||||
task_description: "Review the current diff",
|
||||
};
|
||||
const system = (subtype: string, more: Record<string, unknown>) => ({
|
||||
type: "system",
|
||||
subtype,
|
||||
task_id: agentId,
|
||||
...(call !== undefined ? { tool_use_id: call } : {}),
|
||||
run_id: `run-${agentId}`,
|
||||
skip_transcript: true,
|
||||
ambient: true,
|
||||
uuid: randomUUID(),
|
||||
...more,
|
||||
});
|
||||
const user = (content: unknown[]) => ({
|
||||
type: "user",
|
||||
message: { role: "user", content },
|
||||
...from,
|
||||
uuid: randomUUID(),
|
||||
});
|
||||
return {
|
||||
started: () =>
|
||||
system("task_started", {
|
||||
description: "/code-review",
|
||||
subagent_type: "general-purpose",
|
||||
is_backgrounded: false,
|
||||
spawn_depth: 1,
|
||||
task_type: "local_agent",
|
||||
prompt: "Review the diff",
|
||||
}),
|
||||
ended: (status = "completed") =>
|
||||
system("task_notification", { status, output_file: "", summary: "/code-review" }),
|
||||
prompt: () => user([{ type: "text", text: "Review the diff" }]),
|
||||
runs: (toolUseId: string) => ({
|
||||
...assistant(`msg_${toolUseId}`, [
|
||||
{ type: "tool_use", id: toolUseId, name: "Bash", input: { command: "git diff HEAD" } },
|
||||
]),
|
||||
...from,
|
||||
}),
|
||||
ran: (toolUseId: string) =>
|
||||
user([{ type: "tool_result", tool_use_id: toolUseId, content: "diff --git a/sum.js" }]),
|
||||
says: (text: string, id = `msg_${agentId}`) => ({
|
||||
...assistant(id, [{ type: "text", text }]),
|
||||
...from,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/** The updates of the session `sessionId` that the client received, in order. */
|
||||
function updatesOf(
|
||||
notifications: v2.UpdateSessionNotification[],
|
||||
@@ -3718,6 +3777,461 @@ describe("ACP v2 core", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("a forked skill", () => {
|
||||
/** The kinds of the child's updates that show its work, with its states. */
|
||||
const transcript = (client: ReturnType<typeof v2Client>, agentId: string) =>
|
||||
updatesOf(client.notifications, agentId).flatMap((update) =>
|
||||
update.sessionUpdate === "state_update"
|
||||
? [update.state]
|
||||
: update.sessionUpdate === "agent_message_chunk"
|
||||
? [(update.content as { text: string }).text]
|
||||
: update.sessionUpdate === "tool_call_update" && update.status === "completed"
|
||||
? [update.toolCallId]
|
||||
: [],
|
||||
);
|
||||
|
||||
it("that the user typed gets its messages, which come after its end, before its idle", async () => {
|
||||
const client = v2Client();
|
||||
const sessionId = await client.connect(async (agent) => {
|
||||
const { response, claude } = await openSession(agent);
|
||||
// Both runs send `forked-command-code-review`: each goes by its `agent_id`.
|
||||
for (const [agentId, finding] of [
|
||||
["a995b1", "Off by one."],
|
||||
["a205ff", "No findings."],
|
||||
]) {
|
||||
const fork = forkedSkill(agentId);
|
||||
claude.send(fork.started());
|
||||
claude.send(fork.ended());
|
||||
// Claude Code writes the held messages after the turn's `init`.
|
||||
claude.send({ type: "system", subtype: "init", uuid: randomUUID() });
|
||||
claude.send(fork.prompt());
|
||||
claude.send(fork.runs(`toolu_${agentId}`));
|
||||
claude.send(fork.ran(`toolu_${agentId}`));
|
||||
claude.send(fork.says(finding));
|
||||
// The command's output, as the root's message.
|
||||
claude.send(assistant(`msg_root_${agentId}`, [{ type: "text", text: finding }]));
|
||||
claude.send(result({ num_turns: 0, result: finding }));
|
||||
}
|
||||
await vi.waitFor(() =>
|
||||
expect(client.states()).toEqual(["running", "idle", "running", "idle"]),
|
||||
);
|
||||
return response.sessionId;
|
||||
});
|
||||
|
||||
expect(transcript(client, "a995b1")).toEqual([
|
||||
"running",
|
||||
"toolu_a995b1",
|
||||
"Off by one.",
|
||||
"idle",
|
||||
]);
|
||||
expect(transcript(client, "a205ff")).toEqual([
|
||||
"running",
|
||||
"toolu_a205ff",
|
||||
"No findings.",
|
||||
"idle",
|
||||
]);
|
||||
// The root has the command's output only, after each child's idle.
|
||||
expect(transcript(client, sessionId)).toEqual([
|
||||
"running",
|
||||
"Off by one.",
|
||||
"idle",
|
||||
"running",
|
||||
"No findings.",
|
||||
"idle",
|
||||
]);
|
||||
const idle = client.notifications.findIndex(
|
||||
(n) => n.sessionId === "a995b1" && (n.update as { state?: unknown }).state === "idle",
|
||||
);
|
||||
const output = client.notifications.findIndex(
|
||||
(n) => n.sessionId === sessionId && n.update.sessionUpdate === "agent_message_chunk",
|
||||
);
|
||||
expect(idle).toBeLessThan(output);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["at the turn's result", (claude: FakeClaudeCode) => claude.send(result({ num_turns: 0 }))],
|
||||
["when the query ends", (claude: FakeClaudeCode) => claude.end()],
|
||||
["at Claude Code's idle", (claude: FakeClaudeCode) => claude.send(sessionState("idle"))],
|
||||
[
|
||||
"when the conversation is reset",
|
||||
(claude: FakeClaudeCode) =>
|
||||
claude.send({
|
||||
type: "conversation_reset",
|
||||
new_conversation_id: randomUUID(),
|
||||
uuid: randomUUID(),
|
||||
trigger: "clear",
|
||||
timestamp: new Date().toISOString(),
|
||||
session_id: "session",
|
||||
}),
|
||||
],
|
||||
])("that the user typed ends %s when no message of it comes", async (_, end) => {
|
||||
const client = v2Client();
|
||||
await client.connect(async (agent) => {
|
||||
const { claude } = await openSession(agent);
|
||||
const fork = forkedSkill("a41595");
|
||||
claude.send(fork.started());
|
||||
claude.send(fork.ended("stopped"));
|
||||
// A second report of the end, and another `system` message, end no wait.
|
||||
claude.send({
|
||||
type: "system",
|
||||
subtype: "task_updated",
|
||||
task_id: "a41595",
|
||||
patch: { status: "killed" },
|
||||
uuid: randomUUID(),
|
||||
});
|
||||
claude.send({ type: "system", subtype: "init", uuid: randomUUID() });
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
expect(transcript(client, "a41595")).toEqual(["running"]);
|
||||
end(claude);
|
||||
await vi.waitFor(() => expect(transcript(client, "a41595")).toEqual(["running", "idle"]));
|
||||
});
|
||||
expect(updatesOf(client.notifications, "a41595").at(-1)).toMatchObject({
|
||||
state: "idle",
|
||||
stopReason: "cancelled",
|
||||
});
|
||||
});
|
||||
|
||||
it("that the user typed also waits when some of its messages came before its task's end", async () => {
|
||||
const client = v2Client();
|
||||
await client.connect(async (agent) => {
|
||||
const { claude } = await openSession(agent);
|
||||
const fork = forkedSkill("a7c2d0");
|
||||
claude.send(fork.started());
|
||||
// Claude Code wrote an `init` while the command ran: the messages so far came.
|
||||
claude.send(fork.says("First half.", "msg_first"));
|
||||
claude.send(fork.ended());
|
||||
claude.send(fork.says("Second half.", "msg_second"));
|
||||
await vi.waitFor(() =>
|
||||
expect(transcript(client, "a7c2d0")).toEqual([
|
||||
"running",
|
||||
"First half.",
|
||||
"Second half.",
|
||||
]),
|
||||
);
|
||||
claude.send(assistant("msg_root", [{ type: "text", text: "Second half." }]));
|
||||
await vi.waitFor(() => expect(transcript(client, "a7c2d0").at(-1)).toBe("idle"));
|
||||
});
|
||||
});
|
||||
|
||||
it("that the user typed and launched a subagent stays running through that subagent's messages", async () => {
|
||||
const client = v2Client();
|
||||
await client.connect(async (agent) => {
|
||||
const { claude } = await openSession(agent);
|
||||
const fork = forkedSkill("a71bcc");
|
||||
const nested = subagent("ac5905", "toolu_agent", { parent_task_id: "a71bcc" });
|
||||
claude.send(fork.started());
|
||||
// Claude Code reports the subagent's task as it runs, and holds its
|
||||
// messages along with the skill's own.
|
||||
claude.send(nested.started());
|
||||
claude.send(nested.ended());
|
||||
claude.send(fork.ended());
|
||||
claude.send({ type: "system", subtype: "init", uuid: randomUUID() });
|
||||
claude.send(fork.prompt());
|
||||
claude.send({ ...nested.launch("forked-command-code-review"), agent_id: "a71bcc" });
|
||||
claude.send({ ...nested.says("nested"), agent_id: "ac5905" });
|
||||
claude.send(fork.ran("toolu_agent"));
|
||||
claude.send(fork.says("DONE"));
|
||||
claude.send(assistant("msg_root", [{ type: "text", text: "DONE" }]));
|
||||
claude.send(result({ num_turns: 0 }));
|
||||
await vi.waitFor(() => expect(client.states()).toEqual(["running", "idle"]));
|
||||
});
|
||||
|
||||
// The subagent's task ended before its Agent call came: it stays that
|
||||
// call of the skill's child, and gets no session.
|
||||
expect(transcript(client, "a71bcc")).toEqual(["running", "toolu_agent", "DONE", "idle"]);
|
||||
expect(updatesOf(client.notifications, "ac5905")).toEqual([]);
|
||||
});
|
||||
|
||||
it("that the user typed ends before the root's idle when its turn closes without a result", async () => {
|
||||
const client = v2Client();
|
||||
const sessionId = await client.connect(async (agent) => {
|
||||
const { response, claude } = await openSession(agent);
|
||||
const prompted = agent.request(v2.methods.agent.session.prompt, {
|
||||
sessionId: response.sessionId,
|
||||
prompt: PROMPT,
|
||||
});
|
||||
const prompt = await claude.prompt(0);
|
||||
claude.send(lifecycle(prompt, "started"));
|
||||
await prompted;
|
||||
const fork = forkedSkill("a41595");
|
||||
claude.send(fork.started());
|
||||
claude.send(fork.ended("stopped"));
|
||||
claude.send(lifecycle(prompt, "cancelled"));
|
||||
await vi.waitFor(() => expect(client.states()).toEqual(["running", "idle"]));
|
||||
return response.sessionId;
|
||||
});
|
||||
|
||||
expect(
|
||||
client.notifications.flatMap(({ sessionId: id, update }) =>
|
||||
update.sessionUpdate === "state_update" && update.state === "idle" ? [id] : [],
|
||||
),
|
||||
).toEqual(["a41595", sessionId]);
|
||||
});
|
||||
|
||||
it("that the user typed reports a failure's text that only a second report of its end gives", async () => {
|
||||
const client = v2Client();
|
||||
await client.connect(async (agent) => {
|
||||
const { claude } = await openSession(agent);
|
||||
const fork = forkedSkill("a41595");
|
||||
claude.send(fork.started());
|
||||
claude.send(fork.ended("failed"));
|
||||
claude.send({
|
||||
type: "system",
|
||||
subtype: "task_updated",
|
||||
task_id: "a41595",
|
||||
patch: { status: "failed", error: "boom" },
|
||||
uuid: randomUUID(),
|
||||
});
|
||||
claude.send(result({ num_turns: 0 }));
|
||||
await vi.waitFor(() => expect(transcript(client, "a41595")).toEqual(["running", "idle"]));
|
||||
});
|
||||
|
||||
expect(updatesOf(client.notifications, "a41595").at(-1)).toMatchObject({
|
||||
state: "idle",
|
||||
stopReason: "error",
|
||||
error: { message: "boom" },
|
||||
});
|
||||
});
|
||||
|
||||
it("that the user typed and its own cancel stopped shows its messages, then ends cancelled", async () => {
|
||||
const client = v2Client();
|
||||
await client.connect(async (agent) => {
|
||||
const { claude } = await openSession(agent);
|
||||
const fork = forkedSkill("a41595");
|
||||
claude.send(cycleStart());
|
||||
claude.send(fork.started());
|
||||
await vi.waitFor(() => expect(transcript(client, "a41595")).toEqual(["running"]));
|
||||
await agent.notify(v2.methods.agent.session.cancel, { sessionId: "a41595" });
|
||||
await vi.waitFor(() => expect(claude.stopTask).toHaveBeenCalledWith("a41595"));
|
||||
// Claude Code reports the stop twice, then writes what it held.
|
||||
claude.send({
|
||||
type: "system",
|
||||
subtype: "task_updated",
|
||||
task_id: "a41595",
|
||||
patch: { status: "killed" },
|
||||
uuid: randomUUID(),
|
||||
});
|
||||
claude.send(fork.ended("stopped"));
|
||||
claude.send({ type: "system", subtype: "init", uuid: randomUUID() });
|
||||
claude.send(fork.prompt());
|
||||
claude.send(fork.runs("toolu_diff"));
|
||||
claude.send(fork.ran("toolu_diff"));
|
||||
claude.send(result({ num_turns: 0 }));
|
||||
await vi.waitFor(() => expect(client.states()).toEqual(["running", "idle"]));
|
||||
});
|
||||
|
||||
expect(transcript(client, "a41595")).toEqual(["running", "toolu_diff", "idle"]);
|
||||
expect(updatesOf(client.notifications, "a41595").at(-1)).toMatchObject({
|
||||
state: "idle",
|
||||
stopReason: "cancelled",
|
||||
});
|
||||
});
|
||||
|
||||
it("that the user typed and a cancel of the root stopped shows none of its messages, and ends cancelled", async () => {
|
||||
const client = v2Client();
|
||||
await client.connect(async (agent) => {
|
||||
const { response, claude } = await openSession(agent);
|
||||
const fork = forkedSkill("a41595");
|
||||
claude.send(cycleStart());
|
||||
claude.send(fork.started());
|
||||
await vi.waitFor(() => expect(transcript(client, "a41595")).toEqual(["running"]));
|
||||
await agent.notify(v2.methods.agent.session.cancel, { sessionId: response.sessionId });
|
||||
await vi.waitFor(() => expect(claude.interrupt).toHaveBeenCalled());
|
||||
claude.send(fork.ended("stopped"));
|
||||
claude.send({ type: "system", subtype: "init", uuid: randomUUID() });
|
||||
claude.send(fork.prompt());
|
||||
claude.send(fork.runs("toolu_diff"));
|
||||
claude.send(fork.says("Half a review"));
|
||||
claude.send(result({ num_turns: 0 }));
|
||||
claude.send(sessionState("idle"));
|
||||
await vi.waitFor(() => expect(client.states()).toEqual(["running", "idle"]));
|
||||
});
|
||||
|
||||
expect(
|
||||
updatesOf(client.notifications, "a41595").map((update) => update.sessionUpdate),
|
||||
).toEqual(["state_update", "session_message", "state_update"]);
|
||||
expect(updatesOf(client.notifications, "a41595").at(-1)).toMatchObject({
|
||||
state: "idle",
|
||||
stopReason: "cancelled",
|
||||
});
|
||||
});
|
||||
|
||||
it("that Claude called is referenced from its Skill call, on an update with content", async () => {
|
||||
const client = v2Client();
|
||||
const sessionId = await client.connect(async (agent) => {
|
||||
const { response, claude } = await openSession(agent);
|
||||
const fork = forkedSkill("a66033", "toolu_skill");
|
||||
claude.send(cycleStart());
|
||||
claude.send(
|
||||
assistant("msg_skill", [
|
||||
{
|
||||
type: "tool_use",
|
||||
id: "toolu_skill",
|
||||
name: "Skill",
|
||||
input: { skill: "code-review" },
|
||||
},
|
||||
]),
|
||||
);
|
||||
claude.send(fork.started());
|
||||
claude.send(fork.ended("failed"));
|
||||
claude.send({
|
||||
type: "user",
|
||||
message: {
|
||||
role: "user",
|
||||
content: [
|
||||
{
|
||||
type: "tool_result",
|
||||
tool_use_id: "toolu_skill",
|
||||
is_error: true,
|
||||
content: "The skill failed",
|
||||
},
|
||||
],
|
||||
},
|
||||
parent_tool_use_id: null,
|
||||
uuid: randomUUID(),
|
||||
});
|
||||
claude.send(result());
|
||||
await vi.waitFor(() => expect(client.states()).toEqual(["running", "idle"]));
|
||||
return response.sessionId;
|
||||
});
|
||||
|
||||
const failed = updatesOf(client.notifications, sessionId).find(
|
||||
(update) => update.sessionUpdate === "tool_call_update" && update.status === "failed",
|
||||
);
|
||||
expect((failed as { content?: unknown[] }).content?.at(-1)).toEqual({
|
||||
type: "session",
|
||||
sessionId: "a66033",
|
||||
});
|
||||
});
|
||||
|
||||
it("that Claude called replays as its Skill call, without a child", async () => {
|
||||
// Claude Code 2.1.328 names no call in the metadata of a forked skill's
|
||||
// agent. A replay shows no child even for metadata that names the Skill call.
|
||||
sdk.subagents = new Map([
|
||||
["toolu_skill", { agentId: "a66033", background: false, agentType: "general-purpose" }],
|
||||
]);
|
||||
const client = v2Client();
|
||||
await client.connect(async (agent) => {
|
||||
const { response } = await openSession(agent);
|
||||
const sessionId = response.sessionId;
|
||||
const row = { session_id: sessionId, parent_tool_use_id: null, parent_agent_id: null };
|
||||
vi.mocked(getSessionMessages).mockResolvedValueOnce([
|
||||
{
|
||||
...row,
|
||||
type: "assistant",
|
||||
uuid: "a1",
|
||||
message: assistant("msg_skill", [
|
||||
{
|
||||
type: "tool_use",
|
||||
id: "toolu_skill",
|
||||
name: "Skill",
|
||||
input: { skill: "code-review" },
|
||||
},
|
||||
]).message,
|
||||
},
|
||||
{
|
||||
...row,
|
||||
type: "user",
|
||||
uuid: "u1",
|
||||
message: {
|
||||
role: "user",
|
||||
content: [
|
||||
{
|
||||
type: "tool_result",
|
||||
tool_use_id: "toolu_skill",
|
||||
content: 'Skill "code-review" completed (forked execution).',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
]);
|
||||
await agent.request(v2.methods.agent.session.resume, {
|
||||
sessionId,
|
||||
cwd,
|
||||
replayFrom: { type: "start" },
|
||||
});
|
||||
});
|
||||
|
||||
expect(client.sessionUpdates.map((update) => update.sessionUpdate)).not.toContain(
|
||||
"subagent_update",
|
||||
);
|
||||
expect(
|
||||
client.sessionUpdates.flatMap((update) =>
|
||||
update.sessionUpdate === "tool_call_update" ? [update.status] : [],
|
||||
),
|
||||
).toEqual(["pending", "completed"]);
|
||||
});
|
||||
|
||||
it("that Claude called is announced on the session of its Skill call, which stays shown", async () => {
|
||||
const client = v2Client();
|
||||
const agentId = "a66033";
|
||||
const sessionId = await client.connect(async (agent) => {
|
||||
const { response, claude } = await openSession(agent);
|
||||
const fork = forkedSkill(agentId, "toolu_skill");
|
||||
claude.send(cycleStart());
|
||||
claude.send(
|
||||
assistant("msg_skill", [
|
||||
{
|
||||
type: "tool_use",
|
||||
id: "toolu_skill",
|
||||
name: "Skill",
|
||||
input: { skill: "code-review", args: "low" },
|
||||
},
|
||||
]),
|
||||
);
|
||||
claude.send(fork.started());
|
||||
claude.send(fork.prompt());
|
||||
claude.send(fork.says("Off by one."));
|
||||
claude.send(fork.ended());
|
||||
claude.send({
|
||||
type: "user",
|
||||
message: {
|
||||
role: "user",
|
||||
content: [
|
||||
{
|
||||
type: "tool_result",
|
||||
tool_use_id: "toolu_skill",
|
||||
content: 'Skill "code-review" completed (forked execution).',
|
||||
},
|
||||
],
|
||||
},
|
||||
parent_tool_use_id: null,
|
||||
uuid: randomUUID(),
|
||||
});
|
||||
claude.send(result());
|
||||
await vi.waitFor(() => expect(client.states()).toEqual(["running", "idle"]));
|
||||
return response.sessionId;
|
||||
});
|
||||
|
||||
// The call, then the child, and no message of the parent in place of the call.
|
||||
const parent = updatesOf(client.notifications, sessionId).flatMap((update) =>
|
||||
update.sessionUpdate === "tool_call_update"
|
||||
? [`${update.toolCallId} ${update.status}`]
|
||||
: update.sessionUpdate === "subagent_update" ||
|
||||
update.sessionUpdate === "session_message"
|
||||
? [update.sessionUpdate]
|
||||
: [],
|
||||
);
|
||||
expect(parent).toEqual([
|
||||
"toolu_skill pending",
|
||||
"subagent_update",
|
||||
"subagent_update",
|
||||
"toolu_skill completed",
|
||||
]);
|
||||
expect(updatesOf(client.notifications, agentId).slice(0, 2)).toEqual([
|
||||
{ sessionUpdate: "state_update", state: "running", background: [] },
|
||||
{
|
||||
sessionUpdate: "session_message",
|
||||
messageId: "toolu_skill",
|
||||
senderSessionId: sessionId,
|
||||
recipientSessionId: agentId,
|
||||
content: [{ type: "text", text: "Review the diff" }],
|
||||
},
|
||||
]);
|
||||
expect(transcript(client, agentId)).toEqual(["running", "Off by one.", "idle"]);
|
||||
});
|
||||
});
|
||||
|
||||
it("asks a subagent's permission on its session, and blocks the work that waits on it", async () => {
|
||||
let answer = (_: v2.RequestPermissionResponse) => {};
|
||||
const client = v2Client({
|
||||
|
||||
@@ -4744,6 +4744,14 @@ export class ClaudeAcpAgent {
|
||||
await asyncTasks.autonomousTurnStarted();
|
||||
}
|
||||
|
||||
// Before the message's updates are routed: a subagent's message names
|
||||
// its child session, and an end that waited for such messages is
|
||||
// reported (see `NativeSubagentRuntime.messageCame`). Awaited only
|
||||
// when an end is reported, so that no cancel runs between any other
|
||||
// message and its handling.
|
||||
const reported = subagents.messageCame(message, sendUpdate);
|
||||
if (reported) await reported;
|
||||
|
||||
switch (message.type) {
|
||||
case "system":
|
||||
switch (message.subtype) {
|
||||
@@ -5309,6 +5317,10 @@ export class ClaudeAcpAgent {
|
||||
subagentType: message.subagent_type,
|
||||
description: message.description,
|
||||
prompt: message.prompt,
|
||||
launchTool: message.tool_use_id
|
||||
? session.toolUseCache[message.tool_use_id]?.name
|
||||
: undefined,
|
||||
parentTaskId: message.parent_task_id,
|
||||
},
|
||||
sendUpdate,
|
||||
);
|
||||
@@ -5348,7 +5360,11 @@ export class ClaudeAcpAgent {
|
||||
message.status,
|
||||
sendUpdate,
|
||||
message.tool_use_id,
|
||||
{ reason: message.reason },
|
||||
{
|
||||
reason: message.reason,
|
||||
foreground:
|
||||
session.liveBackgroundTasks.get(message.task_id)?.backgrounded === false,
|
||||
},
|
||||
);
|
||||
await asyncTasks.taskNotification({
|
||||
task_id: message.task_id,
|
||||
@@ -5399,7 +5415,11 @@ export class ClaudeAcpAgent {
|
||||
message.patch.status,
|
||||
sendUpdate,
|
||||
undefined,
|
||||
{ error: message.patch.status === "failed" ? message.patch.error : undefined },
|
||||
{
|
||||
error: message.patch.status === "failed" ? message.patch.error : undefined,
|
||||
foreground:
|
||||
session.liveBackgroundTasks.get(message.task_id)?.backgrounded === false,
|
||||
},
|
||||
);
|
||||
const parentToolUseId = session.liveBackgroundTasks.get(
|
||||
message.task_id,
|
||||
|
||||
@@ -1447,6 +1447,8 @@ export class V2Session implements RequestTarget {
|
||||
*/
|
||||
private closeTurn(): void {
|
||||
if (!this.foreground || this.clearContext.holdsTurn()) return;
|
||||
// A subagent's end that still waited for its messages, before the turn's idle.
|
||||
this.tasks.turnClosed();
|
||||
// v2 asks for a final status of the turn's tool calls before its idle. A
|
||||
// tool call whose task goes on in the background is not part of the work.
|
||||
const cancelled = idleOutcome(this.lastEnd, this.cancelledWork).stopReason === "cancelled";
|
||||
|
||||
126
src/v2/tasks.ts
126
src/v2/tasks.ts
@@ -18,6 +18,14 @@
|
||||
* wait for it. A child that ends before it is announced stays unexposed.
|
||||
* Each run of it is the child's foreground work: `running` from its start
|
||||
* to its end, on its stream and mirrored on the parent's `subagent_update`.
|
||||
* - A forked skill (`context: fork`, such as `/code-review`) runs as a
|
||||
* subagent that no Agent or Task call launched. One that Claude called
|
||||
* with the Skill tool is announced on the session that made the call, which
|
||||
* stays shown. One that the user typed has no call: it is announced on the
|
||||
* root, and its messages name it by `agent_id` only, under an id that no
|
||||
* call has (`forked-command-code-review`). Claude Code (2.1.328) holds
|
||||
* those until after the task's end, so the child's end waits for them (see
|
||||
* {@link SessionTasks.taskEnded}).
|
||||
* - The parent is not shown the Agent call of an announced child: the call's
|
||||
* prompt is the parent's outgoing `session_message` and the child's
|
||||
* incoming one, and a foreground child's answer is its reply to the parent.
|
||||
@@ -66,6 +74,8 @@ import {
|
||||
} from "../background-output.js";
|
||||
import {
|
||||
childModelOption,
|
||||
endsMessageWait,
|
||||
endWaitsForMessages,
|
||||
HANDBACK_TOOL,
|
||||
handbackMessage,
|
||||
isNativeSubagentControlTool,
|
||||
@@ -193,6 +203,8 @@ type Child = {
|
||||
awaitedParent: string | undefined;
|
||||
/** Its messages that came before its announcement. */
|
||||
pending: SDKMessage[];
|
||||
/** Whether a message of it came. */
|
||||
heard: boolean;
|
||||
title: string | undefined;
|
||||
description: string | undefined;
|
||||
/** Whether a run of it is going on: its foreground work. */
|
||||
@@ -264,6 +276,11 @@ export class SessionTasks {
|
||||
private readonly pendingByLaunch = new Map<string, SDKMessage[]>();
|
||||
/** The live subagent tasks, by agent id, announced or not. */
|
||||
private readonly agents = new Map<string, AgentTask>();
|
||||
/**
|
||||
* The ends of the runs that wait for their messages (see {@link taskEnded}),
|
||||
* by agent id.
|
||||
*/
|
||||
private readonly heldEnds = new Map<string, IdleOutcome>();
|
||||
/** The open permission requests of each subagent, by agent id. */
|
||||
private readonly agentRequests = new Map<string, Set<AbortController>>();
|
||||
/** The subagents whose runs a cancel stops, by agent id, until their runs end. */
|
||||
@@ -378,6 +395,7 @@ export class SessionTasks {
|
||||
* was a child's, which then goes to the child's stream only.
|
||||
*/
|
||||
handle(message: SDKMessage): boolean {
|
||||
this.releaseHeldEnds(message);
|
||||
switch (message.type) {
|
||||
case "system":
|
||||
switch (message.subtype) {
|
||||
@@ -870,6 +888,15 @@ export class SessionTasks {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The root's turn ends: a run whose end still waited for its messages ends
|
||||
* before the root's idle, since the turn waited on it. Such a turn ended
|
||||
* without a result, as one that a cancel stopped can.
|
||||
*/
|
||||
turnClosed(): void {
|
||||
this.releaseHeldEnds();
|
||||
}
|
||||
|
||||
/**
|
||||
* Claude Code's query ended: its tasks ended with its process. Terminals
|
||||
* exit and background tool calls are cancelled; a child that worked ends
|
||||
@@ -877,6 +904,7 @@ export class SessionTasks {
|
||||
*/
|
||||
queryEnded(error: { code: number; message: string } | undefined): void {
|
||||
this.stopForeground();
|
||||
this.releaseHeldEnds();
|
||||
for (const [taskId, terminal] of this.terminals) {
|
||||
terminal.tail?.stop();
|
||||
if (error) this.exitTerminal(taskId);
|
||||
@@ -904,6 +932,7 @@ export class SessionTasks {
|
||||
* its state.
|
||||
*/
|
||||
conversationReset(): void {
|
||||
this.releaseHeldEnds();
|
||||
for (const child of [...this.parentsFirst()].reverse()) {
|
||||
if (!child.working) continue;
|
||||
child.working = false;
|
||||
@@ -1007,9 +1036,11 @@ export class SessionTasks {
|
||||
if (toolUseId !== undefined) {
|
||||
this.pendingByLaunch.delete(toolUseId);
|
||||
this.childByToolUse.set(toolUseId, child);
|
||||
// The launch call names the parent. Without one, it is the parent task.
|
||||
const launch = this.launches.get(toolUseId);
|
||||
if (launch) this.announce(child, launch.output.sessionId);
|
||||
// The call that launched it names the parent: an Agent or Task call,
|
||||
// else a call that a session's stream mapped, such as the Skill call
|
||||
// of a forked skill. Without a call, it is the parent task.
|
||||
const parent = this.launches.get(toolUseId)?.output.sessionId ?? this.callerOf(toolUseId);
|
||||
if (parent !== undefined) this.announce(child, parent);
|
||||
} else {
|
||||
// No session update may carry a session id before its announcement.
|
||||
const parent = message.parent_task_id ?? this.host.sessionId;
|
||||
@@ -1118,12 +1149,12 @@ export class SessionTasks {
|
||||
error?: string,
|
||||
): void {
|
||||
const child = this.children.get(taskId);
|
||||
const foreground = this.agents.get(taskId)?.background === false;
|
||||
if (this.agents.delete(taskId)) this.host.foregroundRequestsChanged();
|
||||
if (child && !child.announced) {
|
||||
this.withdrawChild(child);
|
||||
} else if (child) {
|
||||
this.endRun(
|
||||
child,
|
||||
const outcome: IdleOutcome =
|
||||
status === "completed"
|
||||
? { stopReason: "end_turn" }
|
||||
: status === "stopped"
|
||||
@@ -1133,8 +1164,28 @@ export class SessionTasks {
|
||||
...(error
|
||||
? { error: { code: RequestError.internalError().code, message: error } }
|
||||
: {}),
|
||||
},
|
||||
);
|
||||
};
|
||||
const held = this.heldEnds.get(taskId);
|
||||
if (held) {
|
||||
// A second report of an end that waits can give the text of its failure.
|
||||
if (
|
||||
held.stopReason === "error" &&
|
||||
!held.error &&
|
||||
outcome.stopReason === "error" &&
|
||||
outcome.error
|
||||
) {
|
||||
this.heldEnds.set(taskId, outcome);
|
||||
}
|
||||
} else if (
|
||||
child.working &&
|
||||
endWaitsForMessages({ launched: child.launchToolUseId !== undefined, foreground })
|
||||
) {
|
||||
// The run of a child whose messages Claude Code holds until after
|
||||
// its end ends once they came (see `releaseHeldEnds`).
|
||||
this.heldEnds.set(taskId, outcome);
|
||||
} else {
|
||||
this.endRun(child, outcome);
|
||||
}
|
||||
}
|
||||
// A foreground command's output is read no more: a tool call that gets no
|
||||
// result, such as one of a reply that Claude Code took back, would
|
||||
@@ -1198,6 +1249,8 @@ export class SessionTasks {
|
||||
launchToolUseId: string | undefined,
|
||||
task: Child["task"],
|
||||
): Child {
|
||||
const pending =
|
||||
launchToolUseId !== undefined ? (this.pendingByLaunch.get(launchToolUseId) ?? []) : [];
|
||||
const child: Child = {
|
||||
sessionId,
|
||||
parentSessionId: this.host.sessionId,
|
||||
@@ -1205,8 +1258,8 @@ export class SessionTasks {
|
||||
task,
|
||||
announced: false,
|
||||
awaitedParent: undefined,
|
||||
pending:
|
||||
launchToolUseId !== undefined ? (this.pendingByLaunch.get(launchToolUseId) ?? []) : [],
|
||||
pending,
|
||||
heard: pending.length > 0,
|
||||
title: undefined,
|
||||
description: undefined,
|
||||
working: true,
|
||||
@@ -1287,15 +1340,49 @@ export class SessionTasks {
|
||||
this.host.foregroundRequestsChanged();
|
||||
}
|
||||
|
||||
/** The session whose stream mapped the tool call `toolCallId`, if one did. */
|
||||
private callerOf(toolCallId: string): string | undefined {
|
||||
if (this.rootOutput.holds(toolCallId)) return this.host.sessionId;
|
||||
for (const child of this.children.values()) {
|
||||
if (child.output?.holds(toolCallId)) return child.sessionId;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ends the runs whose ends waited for their messages (see {@link taskEnded}),
|
||||
* when `message` ends their wait (see `endsMessageWait`). Without a
|
||||
* message, all of them: the root's turn or the query ended, or the
|
||||
* conversation was reset.
|
||||
*/
|
||||
private releaseHeldEnds(message?: SDKMessage): void {
|
||||
if (this.heldEnds.size === 0) return;
|
||||
for (const [agentId, outcome] of [...this.heldEnds]) {
|
||||
const child = this.children.get(agentId);
|
||||
if (!endsMessageWait(message, child?.heard === true)) continue;
|
||||
this.heldEnds.delete(agentId);
|
||||
if (child) this.endRun(child, outcome);
|
||||
this.publish();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A message of a subagent, by its `parent_tool_use_id`: it goes to the
|
||||
* child's stream, or waits for the child's announcement. A message of an
|
||||
* agent that no known call launched is the root's.
|
||||
* child's stream, or waits for the child's announcement. One whose
|
||||
* `parent_tool_use_id` is no Agent or Task call goes by its `agent_id`: a
|
||||
* forked skill that the user typed sends `forked-command-<skill>` for every
|
||||
* run of the skill. A message of an agent that neither names is the root's.
|
||||
*/
|
||||
private childMessage(message: SDKMessage & { parent_tool_use_id: string | null }): boolean {
|
||||
const launchId = message.parent_tool_use_id;
|
||||
if (launchId === null) return false;
|
||||
const child = this.childByToolUse.get(launchId);
|
||||
const agentId = (message as { agent_id?: unknown }).agent_id;
|
||||
const child =
|
||||
this.childByToolUse.get(launchId) ??
|
||||
(typeof agentId === "string" && !this.launches.has(launchId)
|
||||
? this.children.get(agentId)
|
||||
: undefined);
|
||||
if (child) child.heard = true;
|
||||
if (child?.announced) {
|
||||
this.deliver(child, message);
|
||||
return true;
|
||||
@@ -1358,7 +1445,14 @@ export class SessionTasks {
|
||||
update: { sessionUpdate: "state_update", ...state } as v2.SessionUpdate,
|
||||
});
|
||||
const prompt = child.task.prompt ?? identity?.prompt;
|
||||
if (prompt) this.sendPrompt(child, prompt, child.launchToolUseId, parentSessionId, true);
|
||||
// The prompt replaces an Agent or Task call in the parent's transcript.
|
||||
// Another call that launched the child, such as a Skill call, stays
|
||||
// shown there, so the prompt is the child's incoming message only.
|
||||
const replacesCall =
|
||||
child.launchToolUseId !== undefined && this.launches.has(child.launchToolUseId);
|
||||
if (prompt) {
|
||||
this.sendPrompt(child, prompt, child.launchToolUseId, parentSessionId, replacesCall);
|
||||
}
|
||||
// What its hooks reported before, after the prompt.
|
||||
this.publishConfiguration(child, undefined);
|
||||
const pending = child.pending;
|
||||
@@ -1464,9 +1558,11 @@ export class SessionTasks {
|
||||
/**
|
||||
* `notification`, an update that the client is shown on the session
|
||||
* `shownOn`, with a `session` reference when it is of a TaskStop or
|
||||
* SendMessage call that names an announced child by its agent id, or of a
|
||||
* SendMessage call that names an announced child by its agent id, of a
|
||||
* SendMessage call that resumed one and stays shown (see
|
||||
* {@link requestShows}), as on v1 (`NativeSubagentRuntime.withTarget`).
|
||||
* {@link requestShows}), or of the call that launched one and is no Agent
|
||||
* or Task call, such as the Skill call of a forked skill, as on v1
|
||||
* (`NativeSubagentRuntime.withTarget`).
|
||||
*/
|
||||
private withTarget(
|
||||
notification: AcpSessionNotification,
|
||||
|
||||
Reference in New Issue
Block a user