mirror of
https://github.com/agentclientprotocol/claude-agent-acp.git
synced 2026-11-17 23:01:26 +00:00
Compare commits
1 Commits
v0.108.1-p
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3205f0bf02 |
98
src/tests/server-tool-calls.test.ts
Normal file
98
src/tests/server-tool-calls.test.ts
Normal file
@@ -0,0 +1,98 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { UnansweredServerToolCalls } from "../tool-calls/server-tool-calls.js";
|
||||
|
||||
const text = { type: "text", text: "Next." };
|
||||
const advisorCall = (id: string) => ({ type: "server_tool_use", id, name: "advisor", input: {} });
|
||||
const advisorResult = (id: string) => ({
|
||||
type: "advisor_tool_result",
|
||||
tool_use_id: id,
|
||||
content: { type: "advisor_result", text: "Check the edge case." },
|
||||
});
|
||||
const bashCall = (id: string) => ({ type: "tool_use", id, name: "Bash", input: {} });
|
||||
|
||||
describe("UnansweredServerToolCalls", () => {
|
||||
it("never ends a call that its own reply answers", () => {
|
||||
const calls = new UnansweredServerToolCalls();
|
||||
calls.replyStarted(null, "msg_1");
|
||||
expect(calls.observe(null, advisorCall("srvtoolu_1"))).toEqual([]);
|
||||
expect(calls.observe(null, advisorResult("srvtoolu_1"))).toEqual([]);
|
||||
expect(calls.observe(null, text)).toEqual([]);
|
||||
calls.replyStarted(null, "msg_2");
|
||||
expect(calls.observe(null, text)).toEqual([]);
|
||||
});
|
||||
|
||||
it("waits for the next reply to start with the result of a call its reply left pending", () => {
|
||||
const calls = new UnansweredServerToolCalls();
|
||||
calls.replyStarted(null, "msg_1");
|
||||
calls.observe(null, bashCall("toolu_1"));
|
||||
calls.observe(null, advisorCall("srvtoolu_1"));
|
||||
calls.replyStarted(null, "msg_2");
|
||||
expect(calls.observe(null, advisorResult("srvtoolu_1"))).toEqual([]);
|
||||
expect(calls.observe(null, text)).toEqual([]);
|
||||
});
|
||||
|
||||
it("ends a call still waiting once a later reply starts any other block, and only once", () => {
|
||||
const calls = new UnansweredServerToolCalls();
|
||||
calls.replyStarted(null, "msg_cut_off");
|
||||
calls.observe(null, advisorCall("srvtoolu_1"));
|
||||
calls.replyStarted(null, "msg_asked_again");
|
||||
expect(calls.observe(null, { type: "thinking", thinking: "" })).toEqual(["srvtoolu_1"]);
|
||||
expect(calls.observe(null, text)).toEqual([]);
|
||||
});
|
||||
|
||||
it("ends the earlier call at a later reply's own server tool use, which then waits in turn", () => {
|
||||
const calls = new UnansweredServerToolCalls();
|
||||
calls.replyStarted(null, "msg_cut_off");
|
||||
calls.observe(null, advisorCall("srvtoolu_1"));
|
||||
calls.replyStarted(null, "msg_asked_again");
|
||||
expect(calls.observe(null, advisorCall("srvtoolu_2"))).toEqual(["srvtoolu_1"]);
|
||||
expect(calls.observe(null, text)).toEqual([]);
|
||||
calls.replyStarted(null, "msg_3");
|
||||
expect(calls.observe(null, text)).toEqual(["srvtoolu_2"]);
|
||||
});
|
||||
|
||||
it("takes a consolidated message's blocks as its own reply's, by the id it carries", () => {
|
||||
const calls = new UnansweredServerToolCalls();
|
||||
calls.replyStarted(null, "msg_1");
|
||||
calls.observe(null, advisorCall("srvtoolu_1"));
|
||||
expect(calls.observe(null, advisorCall("srvtoolu_1"), "msg_1")).toEqual([]);
|
||||
expect(calls.observe(null, text, "msg_1")).toEqual([]);
|
||||
expect(calls.observe(null, text, "msg_2")).toEqual(["srvtoolu_1"]);
|
||||
});
|
||||
|
||||
it("follows calls of a reply that was not streamed, by its consolidated messages", () => {
|
||||
const calls = new UnansweredServerToolCalls();
|
||||
expect(calls.observe(null, advisorCall("srvtoolu_1"), "msg_1")).toEqual([]);
|
||||
expect(calls.observe(null, text, "msg_2")).toEqual(["srvtoolu_1"]);
|
||||
});
|
||||
|
||||
it("keeps each conversation's calls to that conversation", () => {
|
||||
const calls = new UnansweredServerToolCalls();
|
||||
calls.replyStarted(null, "msg_main");
|
||||
calls.observe(null, advisorCall("srvtoolu_main"));
|
||||
calls.replyStarted("toolu_agent", "msg_sub_1");
|
||||
calls.observe("toolu_agent", advisorCall("srvtoolu_sub"));
|
||||
calls.replyStarted("toolu_agent", "msg_sub_2");
|
||||
expect(calls.observe("toolu_agent", text)).toEqual(["srvtoolu_sub"]);
|
||||
calls.replyStarted(null, "msg_main_2");
|
||||
expect(calls.observe(null, text)).toEqual(["srvtoolu_main"]);
|
||||
});
|
||||
|
||||
it("does not follow the calls of a reply of unknown id", () => {
|
||||
const calls = new UnansweredServerToolCalls();
|
||||
calls.replyStarted(null, undefined);
|
||||
calls.observe(null, advisorCall("srvtoolu_1"));
|
||||
expect(calls.observe(null, text)).toEqual([]);
|
||||
calls.replyStarted(null, "msg_2");
|
||||
expect(calls.observe(null, text)).toEqual([]);
|
||||
});
|
||||
|
||||
it("forgets the calls of a subagent that ended", () => {
|
||||
const calls = new UnansweredServerToolCalls();
|
||||
calls.replyStarted("toolu_agent", "msg_sub_1");
|
||||
calls.observe("toolu_agent", advisorCall("srvtoolu_sub"));
|
||||
calls.forget("toolu_agent");
|
||||
calls.replyStarted("toolu_agent", "msg_sub_2");
|
||||
expect(calls.observe("toolu_agent", text)).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -254,6 +254,135 @@ describe("incomplete foreground tools", () => {
|
||||
expect(agent.sessions[sessionId].dispatchedToolCalls?.has(advisorId)).toBe(false);
|
||||
});
|
||||
|
||||
it("closes an advisor call whose reply Claude Code gave up on once the next reply's first block has reached the client, and ends the turn as usual", async () => {
|
||||
const advisorId = "srvtoolu_cut_off";
|
||||
const nextToolId = "toolu_next";
|
||||
const { prompt, updates, logError, agent } = createTestSession(async function* (input) {
|
||||
yield* echoNextPrompt(input);
|
||||
yield messageStart("msg_cut_off");
|
||||
yield advisorStart(advisorId);
|
||||
yield advisorToolUse(advisorId, "msg_cut_off");
|
||||
// No result: Claude Code gives up on the reply and asks again.
|
||||
yield messageStart("msg_asked_again");
|
||||
yield toolStart(nextToolId);
|
||||
yield blockStart({ type: "text", text: "" }, 1);
|
||||
yield {
|
||||
...blockStart({}),
|
||||
event: {
|
||||
type: "content_block_delta",
|
||||
index: 1,
|
||||
delta: { type: "text_delta", text: "Next." },
|
||||
},
|
||||
};
|
||||
yield successfulResultMessage();
|
||||
});
|
||||
|
||||
await expect(prompt()).resolves.toMatchObject({ stopReason: "end_turn" });
|
||||
const ends = updates.filter(
|
||||
(update) =>
|
||||
update.toolCallId === advisorId && ["completed", "failed"].includes(update.status),
|
||||
);
|
||||
expect(ends).toHaveLength(1);
|
||||
expect(ends[0]).toMatchObject({ status: "failed" });
|
||||
expect(ends[0].content[0].content.text).toBe(
|
||||
"Claude Code replaced the response that made this tool call, and stopped the call. If it had started, some of its effects may have happened.",
|
||||
);
|
||||
const advisorEnds = updates.indexOf(ends[0]);
|
||||
const nextToolStarts = updates.findIndex(
|
||||
(update) => update.sessionUpdate === "tool_call" && update.toolCallId === nextToolId,
|
||||
);
|
||||
const nextText = updates.findIndex(
|
||||
(update) => update.sessionUpdate === "agent_message_chunk" && update.content.text === "Next.",
|
||||
);
|
||||
expect(nextToolStarts).toBeGreaterThanOrEqual(0);
|
||||
expect(advisorEnds).toBeGreaterThan(nextToolStarts);
|
||||
expect(advisorEnds).toBeLessThan(nextText);
|
||||
expect(agent.sessions[sessionId].emittedToolCalls.has(advisorId)).toBe(false);
|
||||
expect(logError).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("closes an advisor call whose reply Claude Code gave up on when the next reply does not stream, by its message id", async () => {
|
||||
const advisorId = "srvtoolu_cut_off";
|
||||
const retryToolId = "toolu_retry";
|
||||
const retry = toolUse(retryToolId);
|
||||
const { prompt, updates, logError } = createTestSession(async function* (input) {
|
||||
yield* echoNextPrompt(input);
|
||||
yield messageStart("msg_cut_off");
|
||||
yield advisorStart(advisorId);
|
||||
yield advisorToolUse(advisorId, "msg_cut_off");
|
||||
// Claude Code asks again without streaming, as its fallback after a
|
||||
// streaming error does: only the consolidated message comes.
|
||||
yield { ...retry, message: { ...retry.message, id: "msg_retry" } };
|
||||
yield toolResult(retryToolId);
|
||||
yield successfulResultMessage();
|
||||
});
|
||||
|
||||
await expect(prompt()).resolves.toMatchObject({ stopReason: "end_turn" });
|
||||
const ends = updates.filter(
|
||||
(update) =>
|
||||
update.toolCallId === advisorId && ["completed", "failed"].includes(update.status),
|
||||
);
|
||||
expect(ends).toHaveLength(1);
|
||||
expect(ends[0]).toMatchObject({ status: "failed" });
|
||||
expect(ends[0].content[0].content.text).toBe(
|
||||
"Claude Code replaced the response that made this tool call, and stopped the call. If it had started, some of its effects may have happened.",
|
||||
);
|
||||
expect(updates).toContainEqual(
|
||||
expect.objectContaining({ toolCallId: retryToolId, status: "completed" }),
|
||||
);
|
||||
expect(logError).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("names the subagent on the close of its advisor call whose reply Claude Code gave up on", async () => {
|
||||
const advisorId = "srvtoolu_subagent_cut_off";
|
||||
const subagent = { parent_tool_use_id: "toolu_agent" };
|
||||
const { prompt, updates } = createTestSession(async function* (input) {
|
||||
yield* echoNextPrompt(input);
|
||||
yield { ...messageStart("msg_subagent_cut_off"), ...subagent };
|
||||
yield { ...advisorStart(advisorId), ...subagent };
|
||||
yield { ...messageStart("msg_subagent_asked_again"), ...subagent };
|
||||
yield { ...blockStart({ type: "text", text: "" }), ...subagent };
|
||||
yield assistantText("Done.");
|
||||
yield successfulResultMessage();
|
||||
});
|
||||
|
||||
await expect(prompt()).resolves.toMatchObject({ stopReason: "end_turn" });
|
||||
const ends = updates.filter(
|
||||
(update) =>
|
||||
update.toolCallId === advisorId && ["completed", "failed"].includes(update.status),
|
||||
);
|
||||
expect(ends).toMatchObject([
|
||||
{ status: "failed", _meta: { claudeCode: { parentToolUseId: "toolu_agent" } } },
|
||||
]);
|
||||
const mainText = updates.findIndex(
|
||||
(update) => update.sessionUpdate === "agent_message_chunk" && update.content.text === "Done.",
|
||||
);
|
||||
expect(updates.indexOf(ends[0])).toBeLessThan(mainText);
|
||||
});
|
||||
|
||||
it("leaves an advisor call that its reply left pending for the result that starts the next reply", async () => {
|
||||
const advisorId = "srvtoolu_pending";
|
||||
const result = { type: "advisor_result", text: "Check the edge case." };
|
||||
const { prompt, updates, logError } = createTestSession(async function* (input) {
|
||||
yield* echoNextPrompt(input);
|
||||
yield messageStart("msg_paused");
|
||||
yield advisorStart(advisorId);
|
||||
yield advisorToolUse(advisorId, "msg_paused");
|
||||
yield messageStart("msg_continued");
|
||||
yield advisorResult(advisorId, result, "msg_continued");
|
||||
yield blockStart({ type: "text", text: "" }, 1);
|
||||
yield successfulResultMessage();
|
||||
});
|
||||
|
||||
await expect(prompt()).resolves.toMatchObject({ stopReason: "end_turn" });
|
||||
const ends = updates.filter(
|
||||
(update) =>
|
||||
update.toolCallId === advisorId && ["completed", "failed"].includes(update.status),
|
||||
);
|
||||
expect(ends.map((update) => update.status)).toEqual(["completed"]);
|
||||
expect(logError).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("allows a tool explicitly handed off to a background task", async () => {
|
||||
const { prompt, updates } = createTestSession(backgroundToolMessages);
|
||||
|
||||
@@ -1288,6 +1417,31 @@ describe("a tool use whose input Claude Code rejects", () => {
|
||||
});
|
||||
});
|
||||
|
||||
/** The stream event that starts an API reply, which carries its message id. */
|
||||
function messageStart(id: string) {
|
||||
return {
|
||||
type: "stream_event",
|
||||
session_id: sessionId,
|
||||
uuid: `stream-${id}`,
|
||||
parent_tool_use_id: null,
|
||||
event: {
|
||||
type: "message_start",
|
||||
message: { id, model: "claude-test", usage: successfulResultMessage().usage },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** The stream event that starts a block of the reply streaming: `block` at `index`. */
|
||||
function blockStart(block: Record<string, unknown>, index = 0) {
|
||||
return {
|
||||
type: "stream_event",
|
||||
session_id: sessionId,
|
||||
uuid: "stream-message",
|
||||
parent_tool_use_id: null,
|
||||
event: { type: "content_block_start", index, content_block: block },
|
||||
};
|
||||
}
|
||||
|
||||
function toolStart(id = toolCallId, parent: string | null = null, name = "Bash") {
|
||||
return {
|
||||
type: "stream_event",
|
||||
@@ -1333,12 +1487,13 @@ function advisorStart(id: string) {
|
||||
}
|
||||
|
||||
/** The complete assistant message that dispatches the advisor server tool. */
|
||||
function advisorToolUse(id: string) {
|
||||
function advisorToolUse(id: string, messageId?: string) {
|
||||
return {
|
||||
type: "assistant",
|
||||
session_id: sessionId,
|
||||
parent_tool_use_id: null,
|
||||
message: {
|
||||
...(messageId && { id: messageId }),
|
||||
role: "assistant",
|
||||
usage: successfulResultMessage().usage,
|
||||
content: [{ type: "server_tool_use", id, name: "advisor", input: {} }],
|
||||
@@ -1346,12 +1501,13 @@ function advisorToolUse(id: string) {
|
||||
};
|
||||
}
|
||||
|
||||
function advisorResult(id: string, content: unknown) {
|
||||
function advisorResult(id: string, content: unknown, messageId?: string) {
|
||||
return {
|
||||
type: "assistant",
|
||||
session_id: sessionId,
|
||||
parent_tool_use_id: null,
|
||||
message: {
|
||||
...(messageId && { id: messageId }),
|
||||
role: "assistant",
|
||||
usage: successfulResultMessage().usage,
|
||||
content: [{ type: "advisor_tool_result", tool_use_id: id, content }],
|
||||
|
||||
@@ -4197,6 +4197,83 @@ describe("ACP v2 prompts", () => {
|
||||
expect(reports.at(-1)).toMatchObject({ status: "failed" });
|
||||
});
|
||||
|
||||
/**
|
||||
* Scenario:
|
||||
* 1. Claude's reply calls the advisor, and its stream goes silent.
|
||||
* 2. Claude Code gives up on the reply, for example after its stream idle
|
||||
* timeout, and asks again. The call never gets its result.
|
||||
* Expected:
|
||||
* - The advisor call ends `cancelled` once the next reply starts, before
|
||||
* its text, rather than at the idle.
|
||||
*/
|
||||
it.each<[string, boolean]>([
|
||||
["streams", true],
|
||||
["does not stream", false],
|
||||
])(
|
||||
"ends an advisor call whose reply Claude Code gave up on once the next reply starts, which %s",
|
||||
async (_name, streams) => {
|
||||
const advisorCall = {
|
||||
type: "server_tool_use",
|
||||
id: "srvtoolu_cut_off",
|
||||
name: "advisor",
|
||||
input: {},
|
||||
};
|
||||
scriptTurns(async function* (options) {
|
||||
yield stream(options, {
|
||||
type: "message_start",
|
||||
message: { id: "msg_cut_off", role: "assistant", content: [], usage: {} },
|
||||
});
|
||||
yield stream(options, {
|
||||
type: "content_block_start",
|
||||
index: 0,
|
||||
content_block: advisorCall,
|
||||
});
|
||||
const cutOff = assistantText(options, "", "msg_cut_off");
|
||||
yield { ...cutOff, message: { ...cutOff.message, content: [advisorCall] } };
|
||||
if (streams) {
|
||||
yield stream(options, {
|
||||
type: "message_start",
|
||||
message: { id: "msg_asked_again", role: "assistant", content: [], usage: {} },
|
||||
});
|
||||
yield stream(options, {
|
||||
type: "content_block_start",
|
||||
index: 0,
|
||||
content_block: { type: "text", text: "" },
|
||||
});
|
||||
yield stream(options, {
|
||||
type: "content_block_delta",
|
||||
index: 0,
|
||||
delta: { type: "text_delta", text: "Next." },
|
||||
});
|
||||
}
|
||||
yield assistantText(options, "Next.", "msg_asked_again");
|
||||
yield result(options);
|
||||
});
|
||||
const client = v2Client();
|
||||
await client.app.connectWith(connectRouter(), async (agent) => {
|
||||
await initializeV2(agent);
|
||||
const { sessionId } = await agent.request(v2.methods.agent.session.new, { cwd });
|
||||
await agent.request(v2.methods.agent.session.prompt, { sessionId, prompt: text("hi") });
|
||||
await vi.waitFor(() => expect(turnTrace(client.sessionUpdates)).toContain("idle end_turn"));
|
||||
await client.authUpdate(1);
|
||||
});
|
||||
|
||||
const updates = client.sessionUpdates.map(({ update }) => update);
|
||||
const closed = updates.findIndex(
|
||||
(update) =>
|
||||
update.sessionUpdate === "tool_call_update" &&
|
||||
update.toolCallId === advisorCall.id &&
|
||||
update.status === "cancelled",
|
||||
);
|
||||
expect(JSON.stringify(updates[closed])).toContain(
|
||||
"Claude Code replaced the response that made this tool call, and stopped the call. If it had started, some of its effects may have happened.",
|
||||
);
|
||||
expect(closed).toBeLessThan(
|
||||
updates.findIndex((update) => update.sessionUpdate === "agent_message_chunk"),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("reports a turn that fails after it was taken in as idle with the error stop reason", async () => {
|
||||
scriptTurns(async function* (options) {
|
||||
yield result(options, { is_error: true, result: "API Error: 529 Overloaded" });
|
||||
|
||||
79
src/tool-calls/server-tool-calls.ts
Normal file
79
src/tool-calls/server-tool-calls.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
/** One content block of a reply. Only these fields are read. */
|
||||
type Block = { type?: unknown; id?: unknown; tool_use_id?: unknown };
|
||||
|
||||
/** The state of one conversation: the main one, or a subagent's. */
|
||||
type Stream = {
|
||||
/** The id of the reply streaming now, from its `message_start`. */
|
||||
replyId?: string;
|
||||
/** Server tool calls without a result yet: call id -> id of the reply that made the call. */
|
||||
unanswered: Map<string, string>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Finds server tool calls, such as the advisor's, that will never get a
|
||||
* result, so the caller can close them.
|
||||
*
|
||||
* The API runs a server tool itself and puts the result in Claude's reply:
|
||||
* right after the call or, if the reply ended first, at the start of the next
|
||||
* reply. So once a later reply starts with anything other than that result,
|
||||
* the call will never get one. This happens when Claude Code gives up on a
|
||||
* reply, for example after its stream idle timeout, and asks again.
|
||||
*
|
||||
* Example: reply msg_1 makes call srvtoolu_1 and goes silent. Reply msg_2
|
||||
* starts with a text block, so `observe` returns ["srvtoolu_1"].
|
||||
*
|
||||
* Each conversation is tracked on its own: the main one, and each subagent's.
|
||||
*/
|
||||
export class UnansweredServerToolCalls {
|
||||
private readonly streams = new Map<string, Stream>();
|
||||
|
||||
/** Records that the reply `replyId` started streaming in the conversation
|
||||
* of `parentToolUseId` (null for the main one). */
|
||||
replyStarted(parentToolUseId: string | null, replyId: string | undefined): void {
|
||||
this.streamOf(parentToolUseId).replyId = replyId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Records one block of a reply and returns the server tool calls it shows
|
||||
* will never get a result:
|
||||
* - a result block marks its call answered;
|
||||
* - any other block ends the calls made in earlier replies, which are
|
||||
* returned and forgotten;
|
||||
* - a `server_tool_use` block starts tracking its call.
|
||||
*
|
||||
* `replyId` is the block's message id. Without it, the block belongs to the
|
||||
* reply that `replyStarted` last reported. If neither is known, only a
|
||||
* result block has an effect.
|
||||
*/
|
||||
observe(parentToolUseId: string | null, block: unknown, replyId?: string): string[] {
|
||||
const stream = this.streamOf(parentToolUseId);
|
||||
const reply = replyId ?? stream.replyId;
|
||||
const { type, id, tool_use_id } = (block ?? {}) as Block;
|
||||
if (typeof type !== "string") return [];
|
||||
if (typeof tool_use_id === "string" && type.endsWith("tool_result")) {
|
||||
stream.unanswered.delete(tool_use_id);
|
||||
return [];
|
||||
}
|
||||
const ended =
|
||||
reply === undefined
|
||||
? []
|
||||
: [...stream.unanswered].filter(([, madeIn]) => madeIn !== reply).map(([call]) => call);
|
||||
for (const call of ended) stream.unanswered.delete(call);
|
||||
if (type === "server_tool_use" && typeof id === "string" && reply !== undefined) {
|
||||
if (!stream.unanswered.has(id)) stream.unanswered.set(id, reply);
|
||||
}
|
||||
return ended;
|
||||
}
|
||||
|
||||
/** Forgets the conversation of a subagent that ended. */
|
||||
forget(parentToolUseId: string): void {
|
||||
this.streams.delete(parentToolUseId);
|
||||
}
|
||||
|
||||
private streamOf(parentToolUseId: string | null): Stream {
|
||||
const key = parentToolUseId ?? "";
|
||||
let stream = this.streams.get(key);
|
||||
if (!stream) this.streams.set(key, (stream = { unanswered: new Map() }));
|
||||
return stream;
|
||||
}
|
||||
}
|
||||
@@ -343,6 +343,7 @@ import {
|
||||
type ToolCallUpdate,
|
||||
} from "../tool-calls/renderer.js";
|
||||
import { messageLoopYielder, Pushable, raceTimeoutAndAbort, unreachable } from "../utils.js";
|
||||
import { UnansweredServerToolCalls } from "../tool-calls/server-tool-calls.js";
|
||||
import {
|
||||
acceptedPlanToolResult,
|
||||
ExitPlanCoordinator,
|
||||
@@ -3163,6 +3164,9 @@ export class ClaudeAcpAgent {
|
||||
if (!blocks) streamedBlocksByParent.set(key, (blocks = []));
|
||||
return blocks;
|
||||
};
|
||||
// The server tool calls of each conversation that still wait for their
|
||||
// result, which a later reply can show will get none (see UnansweredServerToolCalls).
|
||||
const serverToolCalls = new UnansweredServerToolCalls();
|
||||
// The streams, keyed like streamedBlocksByParent, that dropped a delta
|
||||
// after a cancel since their record last reset, so the record no longer
|
||||
// matches what the client got (see the stream_event case).
|
||||
@@ -3964,6 +3968,20 @@ export class ClaudeAcpAgent {
|
||||
await sendUpdate({ sessionId: params.sessionId, update: report });
|
||||
};
|
||||
|
||||
/** Records `block`, of a reply in the conversation of `parentToolUseId`,
|
||||
* and closes the server tool calls that it shows will never get a result
|
||||
* (see `UnansweredServerToolCalls.observe`): Claude Code gave up on the
|
||||
* reply that made them and asked again, so they end as `retracted`. */
|
||||
const closeUnansweredServerToolCalls = async (
|
||||
parentToolUseId: string | null,
|
||||
block: unknown,
|
||||
replyId?: string,
|
||||
): Promise<void> => {
|
||||
const ended = new Set(serverToolCalls.observe(parentToolUseId, block, replyId));
|
||||
if (ended.size === 0) return;
|
||||
await closeOpenToolCalls((_parent, toolCallId) => ended.has(toolCallId), "retracted");
|
||||
};
|
||||
|
||||
/** Whether the subagent that the Agent call `agentToolUseId` started runs in
|
||||
* the background and has not ended. */
|
||||
const runsInBackground = (agentToolUseId: string): boolean =>
|
||||
@@ -5327,6 +5345,7 @@ export class ClaudeAcpAgent {
|
||||
// The subagent streams no more text under this parent.
|
||||
streamedBlocksByParent.delete(message.tool_use_id);
|
||||
droppedStreams.delete(message.tool_use_id);
|
||||
serverToolCalls.forget(message.tool_use_id);
|
||||
}
|
||||
await endBackgroundTask(message.task_id);
|
||||
if (message.status === "stopped") {
|
||||
@@ -5371,6 +5390,7 @@ export class ClaudeAcpAgent {
|
||||
if (parentToolUseId) {
|
||||
streamedBlocksByParent.delete(parentToolUseId);
|
||||
droppedStreams.delete(parentToolUseId);
|
||||
serverToolCalls.forget(parentToolUseId);
|
||||
}
|
||||
await endBackgroundTask(message.task_id);
|
||||
if (message.patch.status === "killed") {
|
||||
@@ -6327,6 +6347,7 @@ export class ClaudeAcpAgent {
|
||||
// it) can all be tagged with the same, replay-stable id.
|
||||
if (message.event.type === "message_start") {
|
||||
currentStreamMessageId = message.event.message.id || undefined;
|
||||
serverToolCalls.replyStarted(message.parent_tool_use_id, currentStreamMessageId);
|
||||
await subagents.reportModel(
|
||||
message.parent_tool_use_id,
|
||||
message.event.message.model,
|
||||
@@ -6479,6 +6500,14 @@ export class ClaudeAcpAgent {
|
||||
// the stamped parentToolUseId meta and are excluded there.
|
||||
await sendUpdate(notification);
|
||||
}
|
||||
// After the block that shows them, so a client sees the next step
|
||||
// start before the calls it leaves behind end.
|
||||
if (message.event.type === "content_block_start") {
|
||||
await closeUnansweredServerToolCalls(
|
||||
message.parent_tool_use_id,
|
||||
message.event.content_block,
|
||||
);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "user":
|
||||
@@ -6497,6 +6526,12 @@ export class ClaudeAcpAgent {
|
||||
recordReachedToolUse(session, block.id, stoppedWorkOutput);
|
||||
}
|
||||
}
|
||||
if (!stoppedWorkOutput) {
|
||||
const replyId = message.message.id || undefined;
|
||||
for (const block of Array.isArray(content) ? content : []) {
|
||||
await closeUnansweredServerToolCalls(message.parent_tool_use_id, block, replyId);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Record the ACP messageId -> SDK uuid mapping for this message
|
||||
// (including replays). The consolidated message carries both ids, so
|
||||
|
||||
@@ -42,6 +42,7 @@ import { isCompactSummaryMessage, replayCompactSummary } from "../context-compac
|
||||
import { ClientCapabilities } from "../tool-calls/client-capabilities.js";
|
||||
import { ToolCallFieldTracker } from "../tool-calls/field-tracker.js";
|
||||
import { RetractedToolCalls } from "../tool-calls/retracted.js";
|
||||
import { UnansweredServerToolCalls } from "../tool-calls/server-tool-calls.js";
|
||||
import { AcpToolCallRenderer, progressToolCallId, V2_CANCELLED } from "../tool-calls/renderer.js";
|
||||
import { changedTaskPlanEntries, unregisterHookCallback, type TaskState } from "../tools.js";
|
||||
import { recordStreamedDelta, unstreamedRemainder, type StreamedBlock } from "../streamed-text.js";
|
||||
@@ -104,6 +105,8 @@ export class SessionOutput {
|
||||
private readonly dispatched = new Set<string>();
|
||||
/** The tool uses of the assistant messages, for {@link closeRetracted}. */
|
||||
private readonly retracted = new RetractedToolCalls();
|
||||
/** The server tool calls that still wait for their result, for {@link closeUnanswered}. */
|
||||
private readonly serverToolCalls = new UnansweredServerToolCalls();
|
||||
/**
|
||||
* Whether the output comes from work that a `session/cancel` stopped, until
|
||||
* its idle. The session's streamed deltas still go out,
|
||||
@@ -155,6 +158,10 @@ export class SessionOutput {
|
||||
if (message.parent_tool_use_id !== null && !this.subagent) return;
|
||||
if (message.event.type === "message_start") {
|
||||
this.streamingMessageId = message.event.message.id;
|
||||
this.serverToolCalls.replyStarted(
|
||||
message.parent_tool_use_id,
|
||||
this.streamingMessageId || undefined,
|
||||
);
|
||||
// A message that never reached its consolidated message, such as one an
|
||||
// interrupt cut short, leaves its record behind.
|
||||
this.streamedBlocks.length = 0;
|
||||
@@ -177,6 +184,11 @@ export class SessionOutput {
|
||||
},
|
||||
),
|
||||
);
|
||||
// After the block that shows them, so a client sees the next step start
|
||||
// before the calls it leaves behind end.
|
||||
if (message.event.type === "content_block_start") {
|
||||
this.closeUnanswered(message.parent_tool_use_id, message.event.content_block);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -203,6 +215,9 @@ export class SessionOutput {
|
||||
);
|
||||
if (ownText) this.streamedBlocks.length = 0;
|
||||
if (this.stoppedWork(message)) return;
|
||||
for (const block of message.message.content) {
|
||||
this.closeUnanswered(message.parent_tool_use_id, block, message.message.id || undefined);
|
||||
}
|
||||
this.content(content, "assistant", message.parent_tool_use_id, { messageId });
|
||||
}
|
||||
|
||||
@@ -591,6 +606,21 @@ export class SessionOutput {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Records `block`, of a reply in the conversation of `parentToolUseId`, and
|
||||
* ends the open server tool calls that it shows will never get a result
|
||||
* (see `UnansweredServerToolCalls.observe`), `cancelled`: Claude Code gave
|
||||
* up on the reply that made them and asked again, so they end as
|
||||
* `retracted`, as in {@link closeRetracted}.
|
||||
*/
|
||||
private closeUnanswered(parentToolUseId: string | null, block: unknown, replyId?: string): void {
|
||||
for (const toolCallId of this.serverToolCalls.observe(parentToolUseId, block, replyId)) {
|
||||
if (this.unfinished.has(toolCallId)) {
|
||||
this.close({ toolCallId, ran: this.dispatched.has(toolCallId), retracted: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ends the open tool call of `call` without its result, with the report of
|
||||
* `AcpToolCallRenderer.unfinished`. A command's report also ends its
|
||||
|
||||
Reference in New Issue
Block a user