mirror of
https://github.com/agentclientprotocol/claude-agent-acp.git
synced 2026-12-02 22:23:18 +00:00
Compare commits
1 Commits
air/sessio
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
75376d11d6 |
@@ -11,6 +11,7 @@ import { isCompactSummaryMessage } from "./context-compaction.js";
|
||||
import { projectsRoot } from "./paths.js";
|
||||
import { errorCode } from "./session-index/project-dirs.js";
|
||||
import { SessionTiming } from "./session-timing.js";
|
||||
import { withReplyBranches } from "./transcript-branches.js";
|
||||
|
||||
/** The size of one backward read of a transcript. */
|
||||
const TAIL_CHUNK_BYTES = 64 * 1024;
|
||||
@@ -112,10 +113,16 @@ export async function readHistoryAcrossCompactions(
|
||||
const entries = (snapshot ?? (await loadFullSessionHistory(sessionId, dir))).map(
|
||||
linkCompactBoundary,
|
||||
);
|
||||
const history = await getSessionMessages(sessionId, {
|
||||
dir,
|
||||
sessionStore: { append: async () => {}, load: async () => entries },
|
||||
});
|
||||
const read = (records: SessionStoreEntry[]) =>
|
||||
getSessionMessages(sessionId, {
|
||||
dir,
|
||||
sessionStore: { append: async () => {}, load: async () => records },
|
||||
});
|
||||
// `_session/read` gives `messages` with the branches of each model reply,
|
||||
// and passes its records: the history before it gets them too.
|
||||
const history = snapshot
|
||||
? await withReplyBranches(entries, await read(entries), read)
|
||||
: await read(entries);
|
||||
const leaf = messages.at(-1)?.uuid;
|
||||
const end = history.findIndex((message) => message.uuid === leaf);
|
||||
if (end < 0) {
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
} from "./session-index/transcript-scan.js";
|
||||
import { sanitizeTitle } from "./session-titles.js";
|
||||
import { activeSessionMessages, readRewindPoint } from "./session-rewind.js";
|
||||
import { withReplyBranches } from "./transcript-branches.js";
|
||||
|
||||
export const SESSION_READ_METHOD = "_session/read";
|
||||
export const SESSION_READ_CAPABILITY = { supported: true } as const;
|
||||
@@ -160,11 +161,13 @@ export async function readSessionTranscript(
|
||||
lastRecordedTitle(records, "ai-title", "aiTitle"));
|
||||
const dir = cwd ?? records.find((r) => typeof r.cwd === "string" && path.isAbsolute(r.cwd))?.cwd;
|
||||
const effectiveCwd = typeof dir === "string" ? dir : process.cwd();
|
||||
const options = {
|
||||
dir: effectiveCwd,
|
||||
sessionStore: { append: async () => {}, load: async () => records },
|
||||
};
|
||||
const chain = await getSessionMessages(sessionId, options);
|
||||
const read = (entries: SessionStoreEntry[]) =>
|
||||
getSessionMessages(sessionId, {
|
||||
dir: effectiveCwd,
|
||||
sessionStore: { append: async () => {}, load: async () => entries },
|
||||
});
|
||||
// A poll must see the earlier history as a prefix (see `withReplyBranches`).
|
||||
const chain = await withReplyBranches(records, await read(records), read);
|
||||
const rewind = await readRewindPoint(sessionId, undefined, { transcript });
|
||||
const retained = activeSessionMessages(chain, rewind);
|
||||
const messages = await readHistoryAcrossCompactions(
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
getSessionInfo,
|
||||
getSubagentMessages,
|
||||
type SessionMessage,
|
||||
type SessionStoreEntry,
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
import { createReadStream } from "node:fs";
|
||||
import { readdir, readFile } from "node:fs/promises";
|
||||
@@ -9,6 +10,7 @@ import path from "node:path";
|
||||
import readline from "node:readline";
|
||||
import { isNativeSubagentControlTool, type HistoricalSubagent } from "./native-subagents.js";
|
||||
import { findTranscript, readTranscriptEntries } from "./resumed-session.js";
|
||||
import { withReplyBranches } from "./transcript-branches.js";
|
||||
|
||||
/** What the metadata file of a subagent says about it. */
|
||||
export interface SubagentRecord {
|
||||
@@ -307,15 +309,66 @@ export async function readSubagentMessages(
|
||||
try {
|
||||
if (history.dir) {
|
||||
const messages = await getSubagentMessages(sessionId, agentId, { dir: history.dir });
|
||||
if (messages.length > 0) return stripForkPrefix(messages);
|
||||
if (messages.length > 0) {
|
||||
return stripForkPrefix(await withSubagentBranches(sessionId, agentId, history, messages));
|
||||
}
|
||||
}
|
||||
return stripForkPrefix(await getSubagentMessages(sessionId, agentId));
|
||||
const messages = await getSubagentMessages(sessionId, agentId);
|
||||
return stripForkPrefix(await withSubagentBranches(sessionId, agentId, history, messages));
|
||||
} catch (error) {
|
||||
logger.error(`Failed to read the history of subagent ${agentId}:`, error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The chain of the subagent `agentId` in its transcript records `entries`,
|
||||
* with the branches of its model replies (see {@link withReplyBranches}).
|
||||
*/
|
||||
async function readSubagentChain(
|
||||
sessionId: string,
|
||||
agentId: string,
|
||||
entries: SessionStoreEntry[],
|
||||
): Promise<SessionMessage[]> {
|
||||
const read = (records: SessionStoreEntry[]) =>
|
||||
getSubagentMessages(sessionId, agentId, {
|
||||
sessionStore: { append: async () => {}, load: async () => records },
|
||||
});
|
||||
return withReplyBranches(entries, await read(entries), read);
|
||||
}
|
||||
|
||||
/**
|
||||
* `messages`, the chain that the SDK read from the files of the subagent
|
||||
* `agentId`, with the branches of its model replies. It is `messages` when
|
||||
* the transcript in `history.directory` cannot be read.
|
||||
*/
|
||||
async function withSubagentBranches(
|
||||
sessionId: string,
|
||||
agentId: string,
|
||||
history: SubagentHistory,
|
||||
messages: SessionMessage[],
|
||||
): Promise<SessionMessage[]> {
|
||||
if (messages.length === 0 || !history.directory) return messages;
|
||||
let entries: SessionStoreEntry[];
|
||||
try {
|
||||
entries = await readTranscriptEntries(path.join(history.directory, `agent-${agentId}.jsonl`));
|
||||
} catch {
|
||||
return messages;
|
||||
}
|
||||
const read = async (records: SessionStoreEntry[]) =>
|
||||
(
|
||||
await getSubagentMessages(sessionId, agentId, {
|
||||
sessionStore: { append: async () => {}, load: async () => records },
|
||||
})
|
||||
).map((message) => ({
|
||||
...message,
|
||||
// The SDK reads these fields from agent-*.meta.json only with its filesystem store.
|
||||
parent_tool_use_id: messages[0]!.parent_tool_use_id,
|
||||
parent_agent_id: messages[0]!.parent_agent_id,
|
||||
}));
|
||||
return withReplyBranches(entries, messages, read);
|
||||
}
|
||||
|
||||
/** Whether a filesystem error means a file does not exist. */
|
||||
function isMissing(error: unknown): boolean {
|
||||
return (error as { code?: unknown } | null)?.code === "ENOENT";
|
||||
@@ -340,8 +393,7 @@ export async function readSubagentMessagesOrFail(
|
||||
const file = path.join(history.directory, `agent-${agentId}.jsonl`);
|
||||
try {
|
||||
const entries = await readTranscriptEntries(file);
|
||||
const sessionStore = { append: async () => {}, load: async () => entries };
|
||||
const messages = await getSubagentMessages(sessionId, agentId, { sessionStore });
|
||||
const messages = await readSubagentChain(sessionId, agentId, entries);
|
||||
// The SDK reads these fields from agent-*.meta.json only with its filesystem store.
|
||||
const parent = history.agents.get(launchId)?.parentAgentId ?? null;
|
||||
return stripForkPrefix(
|
||||
|
||||
@@ -203,6 +203,94 @@ export function transcriptCompactSummary(
|
||||
return transcriptUser(uuid, content, { isCompactSummary: true });
|
||||
}
|
||||
|
||||
/**
|
||||
* A prompt and one model reply with parallel Read calls, in the record order
|
||||
* of Claude Code 2.1.332. Each tool_use block is a record of its own whose
|
||||
* parent is the record before it, and each result has the record of its call
|
||||
* as parent:
|
||||
*
|
||||
* - `results`: two calls, then the result of each call;
|
||||
* - `third call`: a third call of the same reply, whose parent is the second result;
|
||||
* - `streamed call`: the first result comes while the reply streams a third
|
||||
* call, which then has that result as parent.
|
||||
*
|
||||
* Each record has its `parentUuid`, for {@link writeTranscript}.
|
||||
*/
|
||||
export function parallelToolCallRecords(
|
||||
variant: "results" | "third call" | "streamed call" | "skill text",
|
||||
): Record<string, unknown>[] {
|
||||
let clock = 0;
|
||||
const at = () => new Date(Date.UTC(2026, 9, 11, 0, 0, clock++)).toISOString();
|
||||
const call = (uuid: string, parentUuid: string, id: string) => ({
|
||||
type: "assistant",
|
||||
uuid,
|
||||
parentUuid,
|
||||
timestamp: at(),
|
||||
message: {
|
||||
id: "msg_parallel",
|
||||
role: "assistant",
|
||||
model: "claude-opus-5",
|
||||
content: [{ type: "tool_use", id, name: "Read", input: { file_path: `/work/${id}.txt` } }],
|
||||
},
|
||||
});
|
||||
const result = (uuid: string, parentUuid: string, id: string) => ({
|
||||
type: "user",
|
||||
uuid,
|
||||
parentUuid,
|
||||
sourceToolAssistantUUID: parentUuid,
|
||||
timestamp: at(),
|
||||
message: {
|
||||
role: "user",
|
||||
content: [{ type: "tool_result", tool_use_id: id, content: `Text of ${id}` }],
|
||||
},
|
||||
});
|
||||
const prompt = { ...transcriptUser("p132", "Read the files"), parentUuid: null, timestamp: at() };
|
||||
if (variant === "skill text") {
|
||||
// Three calls; the third result has a Skill text; a fourth call streams in.
|
||||
return [
|
||||
prompt,
|
||||
call("p133", "p132", "toolu_1"),
|
||||
call("p134", "p133", "toolu_2"),
|
||||
call("p135", "p134", "toolu_3"),
|
||||
result("p136", "p135", "toolu_3"),
|
||||
{
|
||||
type: "user",
|
||||
uuid: "p137",
|
||||
parentUuid: "p136",
|
||||
isMeta: true,
|
||||
timestamp: at(),
|
||||
message: { role: "user", content: [{ type: "text", text: "Text of the Skill" }] },
|
||||
},
|
||||
result("p138", "p134", "toolu_2"),
|
||||
call("p139", "p138", "toolu_4"),
|
||||
result("p140", "p133", "toolu_1"),
|
||||
result("p141", "p139", "toolu_4"),
|
||||
];
|
||||
}
|
||||
const records: Record<string, unknown>[] = [
|
||||
prompt,
|
||||
call("p133", "p132", "toolu_1"),
|
||||
call("p134", "p133", "toolu_2"),
|
||||
result("p135", "p133", "toolu_1"),
|
||||
];
|
||||
if (variant === "results") records.push(result("p136", "p134", "toolu_2"));
|
||||
if (variant === "third call") {
|
||||
records.push(
|
||||
result("p136", "p134", "toolu_2"),
|
||||
call("p137", "p136", "toolu_3"),
|
||||
result("p138", "p137", "toolu_3"),
|
||||
);
|
||||
}
|
||||
if (variant === "streamed call") {
|
||||
records.push(
|
||||
call("p136", "p135", "toolu_3"),
|
||||
result("p137", "p134", "toolu_2"),
|
||||
result("p138", "p136", "toolu_3"),
|
||||
);
|
||||
}
|
||||
return records;
|
||||
}
|
||||
|
||||
/** Writes `<directory>/<sessionId>.jsonl` as Claude Code does: each record
|
||||
* links to the record before it, except a record that sets its own
|
||||
* `parentUuid`. */
|
||||
|
||||
@@ -7,7 +7,12 @@ import { writeCustomTitleSidecar } from "../session-index/service.js";
|
||||
import * as transcriptScan from "../session-index/transcript-scan.js";
|
||||
import { readSessionTranscript, SessionReads, type SessionReadFrame } from "../session-read.js";
|
||||
import { writeRewindPoint } from "../session-rewind.js";
|
||||
import { transcriptAssistant, transcriptUser, writeTranscript } from "./helpers.js";
|
||||
import {
|
||||
parallelToolCallRecords,
|
||||
transcriptAssistant,
|
||||
transcriptUser,
|
||||
writeTranscript,
|
||||
} from "./helpers.js";
|
||||
|
||||
describe("session read cursors", () => {
|
||||
const message = (messageId: string): SessionReadFrame => ({
|
||||
@@ -142,4 +147,62 @@ describe("session read cursors", () => {
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.each([false, true])(
|
||||
"leaves out a prompt that the user left for another prompt (rewind point: %s)",
|
||||
async (rewind) => {
|
||||
const sessionId = randomUUID();
|
||||
const dir = await mkdtemp(path.join(tmpdir(), "claude-acp-read-left-prompt-"));
|
||||
const project = path.join(dir, "projects", "-project");
|
||||
vi.stubEnv("CLAUDE_CONFIG_DIR", dir);
|
||||
try {
|
||||
await writeTranscript(project, sessionId, [
|
||||
{ cwd: dir, ...transcriptUser("u1", "One") },
|
||||
{ cwd: dir, ...transcriptAssistant("a1", "Answer one") },
|
||||
{ cwd: dir, ...transcriptUser("uA", "A prompt with a typo") },
|
||||
{ cwd: dir, ...transcriptUser("uB", "The same prompt"), parentUuid: "a1" },
|
||||
{ cwd: dir, ...transcriptAssistant("a2", "Answer two") },
|
||||
]);
|
||||
if (rewind) {
|
||||
await writeRewindPoint(sessionId, { resumeSessionAt: "a1", droppedPromptUuid: "uA" });
|
||||
}
|
||||
const { messages } = await readSessionTranscript(sessionId);
|
||||
expect(messages.map((message) => message.uuid)).toEqual(["u1", "a1", "uB", "a2"]);
|
||||
} finally {
|
||||
vi.unstubAllEnvs();
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["results", "third call", "streamed call", "skill text"] as const)(
|
||||
"reads each record of parallel tool calls of the root in file order: %s",
|
||||
async (variant) => {
|
||||
const sessionId = randomUUID();
|
||||
const dir = await mkdtemp(path.join(tmpdir(), "claude-acp-read-parallel-"));
|
||||
const project = path.join(dir, "projects", "-project");
|
||||
vi.stubEnv("CLAUDE_CONFIG_DIR", dir);
|
||||
try {
|
||||
const records = parallelToolCallRecords(variant).map((record): Record<string, unknown> => ({
|
||||
cwd: dir,
|
||||
...record,
|
||||
}));
|
||||
let previous: string[] = [];
|
||||
for (let count = 1; count <= records.length; count++) {
|
||||
await writeTranscript(project, sessionId, records.slice(0, count));
|
||||
const { messages } = await readSessionTranscript(sessionId);
|
||||
const uuids = messages.map((message) => message.uuid);
|
||||
expect(uuids.slice(0, previous.length)).toEqual(previous);
|
||||
previous = uuids;
|
||||
}
|
||||
// The SDK leaves out a meta record of the main thread, such as a Skill text.
|
||||
expect(previous).toEqual(
|
||||
records.filter((record) => record.isMeta !== true).map((record) => record.uuid),
|
||||
);
|
||||
} finally {
|
||||
vi.unstubAllEnvs();
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { parallelToolCallRecords } from "./helpers.js";
|
||||
import type { SessionMessage } from "@anthropic-ai/claude-agent-sdk";
|
||||
import {
|
||||
stripForkPrefix,
|
||||
subagentLineage,
|
||||
subagentHistory,
|
||||
readSubagentMessages,
|
||||
readSubagentMessagesOrFail,
|
||||
} from "../subagent-history.js";
|
||||
|
||||
@@ -374,6 +376,36 @@ describe("strict subagent history", () => {
|
||||
expect(messages.map((message) => message.uuid)).toEqual(["child-1", "child-2"]);
|
||||
});
|
||||
|
||||
it.each(["results", "third call", "streamed call", "skill text"] as const)(
|
||||
"keeps each record of parallel tool calls in file order: %s",
|
||||
async (variant) => {
|
||||
const file = path.join(dir, "agent-child.jsonl");
|
||||
const records = parallelToolCallRecords(variant).map((record): Record<string, unknown> => ({
|
||||
...base,
|
||||
...record,
|
||||
isSidechain: true,
|
||||
agentId: "child",
|
||||
}));
|
||||
const history = { agents: new Map(), directory: dir };
|
||||
let previous: string[] = [];
|
||||
for (let count = 1; count <= records.length; count++) {
|
||||
await writeFile(
|
||||
file,
|
||||
records
|
||||
.slice(0, count)
|
||||
.map((record) => JSON.stringify(record) + "\n")
|
||||
.join(""),
|
||||
);
|
||||
const uuids = (await readSubagentMessagesOrFail(sessionId, "child", history, "launch")).map(
|
||||
(message) => message.uuid,
|
||||
);
|
||||
expect(uuids.slice(0, previous.length)).toEqual(previous);
|
||||
previous = uuids;
|
||||
}
|
||||
expect(previous).toEqual(records.map((record) => record.uuid));
|
||||
},
|
||||
);
|
||||
|
||||
it("fails rather than silently accepting an unreadable child transcript", async () => {
|
||||
const file = path.join(dir, "agent-bad.jsonl");
|
||||
await mkdir(file);
|
||||
@@ -382,3 +414,67 @@ describe("strict subagent history", () => {
|
||||
).rejects.toMatchObject({ path: file });
|
||||
});
|
||||
});
|
||||
|
||||
describe("subagent load replay", () => {
|
||||
let config: string;
|
||||
beforeEach(async () => {
|
||||
config = await mkdtemp(path.join(os.tmpdir(), "claude-acp-subagent-load-"));
|
||||
vi.stubEnv("CLAUDE_CONFIG_DIR", config);
|
||||
});
|
||||
afterEach(async () => {
|
||||
vi.unstubAllEnvs();
|
||||
await rm(config, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it.each(["results", "third call", "streamed call", "skill text"] as const)(
|
||||
"loads each record of parallel tool calls in file order: %s",
|
||||
async (variant) => {
|
||||
const cwd = path.join(config, "work");
|
||||
await mkdir(cwd);
|
||||
const project = path.join(config, "projects", cwd.replace(/[^a-zA-Z0-9]/g, "-"));
|
||||
const children = path.join(project, sessionId, "subagents");
|
||||
await mkdir(children, { recursive: true });
|
||||
await writeFile(
|
||||
path.join(project, `${sessionId}.jsonl`),
|
||||
[
|
||||
{ ...user("u1", "Go"), parentUuid: null, cwd },
|
||||
{ ...launch("a1", "toolu_agent"), parentUuid: "u1", cwd },
|
||||
]
|
||||
.map((record) => JSON.stringify(record) + "\n")
|
||||
.join(""),
|
||||
);
|
||||
await writeFile(
|
||||
path.join(children, "agent-child.meta.json"),
|
||||
JSON.stringify({ agentType: "Explore", toolUseId: "toolu_agent", description: "Work" }),
|
||||
);
|
||||
const records = parallelToolCallRecords(variant).map((record): Record<string, unknown> => ({
|
||||
...base,
|
||||
cwd,
|
||||
...record,
|
||||
isSidechain: true,
|
||||
agentId: "child",
|
||||
}));
|
||||
const logger = { error: vi.fn() };
|
||||
let previous: string[] = [];
|
||||
for (let count = 1; count <= records.length; count++) {
|
||||
await writeFile(
|
||||
path.join(children, "agent-child.jsonl"),
|
||||
records
|
||||
.slice(0, count)
|
||||
.map((record) => JSON.stringify(record) + "\n")
|
||||
.join(""),
|
||||
);
|
||||
const history = await subagentHistory(sessionId);
|
||||
const messages = await readSubagentMessages(sessionId, "child", history, logger);
|
||||
expect(messages.every((message) => message.parent_tool_use_id === "toolu_agent")).toBe(
|
||||
true,
|
||||
);
|
||||
const uuids = messages.map((message) => message.uuid);
|
||||
expect(uuids.slice(0, previous.length)).toEqual(previous);
|
||||
previous = uuids;
|
||||
}
|
||||
expect(previous).toEqual(records.map((record) => record.uuid));
|
||||
expect(logger.error).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
72
src/tests/transcript-branches.test.ts
Normal file
72
src/tests/transcript-branches.test.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
import type { SessionMessage, SessionStoreEntry } from "@anthropic-ai/claude-agent-sdk";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { replyBranchOrder, withReplyBranches } from "../transcript-branches.js";
|
||||
import { parallelToolCallRecords } from "./helpers.js";
|
||||
|
||||
/** The records of the `results` fixture, with the records of `extra` after them. */
|
||||
function records(...extra: Record<string, unknown>[]): SessionStoreEntry[] {
|
||||
return [...parallelToolCallRecords("results"), ...extra] as SessionStoreEntry[];
|
||||
}
|
||||
|
||||
/** The records of the `results` fixture, with a Skill text on the first result before the second result. */
|
||||
function withSkillText(): SessionStoreEntry[] {
|
||||
const fixture = records();
|
||||
return [
|
||||
...fixture.slice(0, 4),
|
||||
text("skill", "p135", { isMeta: true }),
|
||||
...fixture.slice(4),
|
||||
] as SessionStoreEntry[];
|
||||
}
|
||||
|
||||
const text = (uuid: string, parentUuid: string, fields: Record<string, unknown> = {}) => ({
|
||||
type: "user",
|
||||
uuid,
|
||||
parentUuid,
|
||||
message: { role: "user", content: [{ type: "text", text: uuid }] },
|
||||
...fields,
|
||||
});
|
||||
const reply = (uuid: string, parentUuid: string) => ({
|
||||
type: "assistant",
|
||||
uuid,
|
||||
parentUuid,
|
||||
message: { id: `msg_${uuid}`, role: "assistant", content: [{ type: "text", text: uuid }] },
|
||||
});
|
||||
const messages = (uuids: string[]) => uuids.map((uuid) => ({ uuid }) as SessionMessage);
|
||||
|
||||
describe("replyBranchOrder", () => {
|
||||
it("adds a record that grows from a result of another branch, such as the text of a Skill", () => {
|
||||
const entries = withSkillText();
|
||||
// The SDK chain follows the second result and drops the text on the first one.
|
||||
const plan = replyBranchOrder(entries, ["p132", "p133", "p134", "p135", "p136"]);
|
||||
expect(plan?.order).toEqual(["p132", "p133", "p134", "p135", "skill", "p136"]);
|
||||
});
|
||||
|
||||
it("leaves out a branch that leads to another reply, such as the prompt before a rewind", () => {
|
||||
const entries = records(text("old prompt", "p135"), reply("old answer", "old prompt"));
|
||||
expect(replyBranchOrder(entries, ["p132", "p133", "p134", "p135", "p136"])).toBeUndefined();
|
||||
});
|
||||
|
||||
it("leaves out a record that comes after the next record of the chain", () => {
|
||||
const entries = records(reply("next", "p136"), text("late", "p135", { isMeta: true }));
|
||||
expect(
|
||||
replyBranchOrder(entries, ["p132", "p133", "p134", "p135", "p136", "next"]),
|
||||
).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("withReplyBranches", () => {
|
||||
const entries = withSkillText();
|
||||
const chain = messages(["p132", "p133", "p134", "p135", "p136"]);
|
||||
|
||||
it.each([
|
||||
["drops a message of the chain", ["p132", "p133", "p134", "skill", "p136"]],
|
||||
["gives another order", ["p132", "p133", "p134", "skill", "p135", "p136"]],
|
||||
])("keeps the SDK chain when the read %s", async (_name, read) => {
|
||||
expect(await withReplyBranches(entries, chain, async () => messages(read))).toBe(chain);
|
||||
});
|
||||
|
||||
it("gives a read that leaves out a planned record, such as a meta prompt that the SDK hides", async () => {
|
||||
const read = messages(["p132", "p133", "p134", "p135", "p136"]);
|
||||
expect(await withReplyBranches(entries, chain, async () => read)).toBe(read);
|
||||
});
|
||||
});
|
||||
@@ -18,6 +18,7 @@ import { writeRewindPoint } from "../../session-rewind.js";
|
||||
import { ClaudeAcpAgent, v1AgentApp } from "../../v1/acp-agent.js";
|
||||
import {
|
||||
initializeClient,
|
||||
parallelToolCallRecords,
|
||||
transcriptAssistant,
|
||||
transcriptUser,
|
||||
writeTranscript,
|
||||
@@ -522,6 +523,75 @@ describe("_session/read on v1", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["results", "third call", "streamed call"] as const)(
|
||||
"keeps a cursor valid while the results of parallel tool calls of a child arrive: %s",
|
||||
async (variant) => {
|
||||
const childId = "a1122334455667788";
|
||||
const launchId = "toolu_review";
|
||||
const launched = {
|
||||
...transcriptAssistant("launch", ""),
|
||||
message: {
|
||||
role: "assistant",
|
||||
model: "claude-opus-5",
|
||||
id: "msg_launch",
|
||||
content: [
|
||||
{
|
||||
type: "tool_use",
|
||||
id: launchId,
|
||||
name: "Agent",
|
||||
input: { prompt: "Read the files", description: "Read files" },
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
await store([...history, launched]);
|
||||
const directory = path.join(project, sessionId, "subagents");
|
||||
await mkdir(directory, { recursive: true });
|
||||
await writeFile(
|
||||
path.join(directory, `agent-${childId}.meta.json`),
|
||||
JSON.stringify({ toolUseId: launchId, description: "Read files" }),
|
||||
);
|
||||
const records = parallelToolCallRecords(variant).map((record) => ({
|
||||
sessionId,
|
||||
cwd,
|
||||
agentId: childId,
|
||||
isSidechain: true,
|
||||
...record,
|
||||
}));
|
||||
const writeChild = (count: number) =>
|
||||
writeTranscript(directory, `agent-${childId}`, records.slice(0, count));
|
||||
// The prompt and the two tool_use records: the cursor comes after `p134`.
|
||||
await writeChild(3);
|
||||
const { agent, updates } = captureUpdates();
|
||||
try {
|
||||
await initializeClient(agent, {
|
||||
session: { cursors: {} },
|
||||
_meta: {
|
||||
jetbrains: {
|
||||
air: { version: 1, capabilities: [AIR_NATIVE_SUBAGENT_SESSIONS_CAPABILITY] },
|
||||
},
|
||||
},
|
||||
});
|
||||
let { cursorId } = await agent.readSession({ sessionId, replayFrom: start });
|
||||
for (let count = 4; count <= records.length; count++) {
|
||||
await writeChild(count);
|
||||
({ cursorId } = await agent.readSession({
|
||||
sessionId,
|
||||
replayFrom: { type: "cursor", cursorId },
|
||||
}));
|
||||
}
|
||||
const completed = updates.flatMap(({ update }) =>
|
||||
update.sessionUpdate === "tool_call_update" && update.status === "completed"
|
||||
? [update.toolCallId]
|
||||
: [],
|
||||
);
|
||||
expect(completed).toEqual(expect.arrayContaining(["toolu_1", "toolu_2"]));
|
||||
} finally {
|
||||
await agent.dispose();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["close", "cancel"] as const)("releases a fenced read after %s", async (action) => {
|
||||
await store(history);
|
||||
const actual = await vi.importActual<typeof import("@anthropic-ai/claude-agent-sdk")>(
|
||||
|
||||
@@ -46,6 +46,7 @@ import { customTitleSidecarPath } from "../../session-index/transcript-scan.js";
|
||||
import {
|
||||
claudeCodeMcpRequest,
|
||||
cliSettingsReport,
|
||||
parallelToolCallRecords,
|
||||
runMcpToolHooks,
|
||||
setModelRefusal,
|
||||
startupFailure,
|
||||
@@ -1261,6 +1262,53 @@ describe("ACP v2 sessions", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["results", "third call", "streamed call"] as const)(
|
||||
"keeps a cursor valid while the results of parallel tool calls of a child arrive: %s",
|
||||
async (variant) => {
|
||||
const sessionId = randomUUID();
|
||||
const childId = "abc123";
|
||||
const prompt = randomUUID();
|
||||
const root = [
|
||||
transcriptRecord(sessionId, prompt, null, { role: "user", content: "Explore it" }),
|
||||
transcriptRecord(sessionId, randomUUID(), prompt, {
|
||||
id: "msg_launch",
|
||||
role: "assistant",
|
||||
content: [
|
||||
{
|
||||
type: "tool_use",
|
||||
id: "toolu_agent",
|
||||
name: "Agent",
|
||||
input: { prompt: "Read the files", description: "Explore" },
|
||||
},
|
||||
],
|
||||
}),
|
||||
];
|
||||
const records = parallelToolCallRecords(variant).map((record) => ({
|
||||
sessionId,
|
||||
cwd,
|
||||
...record,
|
||||
}));
|
||||
const meta = { agentType: "Explore", toolUseId: "toolu_agent" };
|
||||
// The prompt and the two tool_use records: the cursor comes after `p134`.
|
||||
await writeSubagentHistory(sessionId, root, childId, meta, records.slice(0, 3));
|
||||
const client = v2Client();
|
||||
await client.app.connectWith(connectRouter(), async (agent) => {
|
||||
await initializeV2(agent);
|
||||
let { cursorId } = await read(agent, sessionId, { type: "start" });
|
||||
for (let count = 4; count <= records.length; count++) {
|
||||
await writeSubagentHistory(sessionId, root, childId, meta, records.slice(0, count));
|
||||
({ cursorId } = await read(agent, sessionId, { type: "cursor", cursorId: cursorId! }));
|
||||
}
|
||||
const completed = client.sessionUpdates.flatMap(({ update }) =>
|
||||
update.sessionUpdate === "tool_call_update" && update.status === "completed"
|
||||
? [update.toolCallId]
|
||||
: [],
|
||||
);
|
||||
expect(completed).toEqual(expect.arrayContaining(["toolu_1", "toolu_2"]));
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("delivers the current title after replay without changing the saved cursor", async () => {
|
||||
const sessionId = randomUUID();
|
||||
const project = path.join(tempDir, "claude", "projects", "-project");
|
||||
|
||||
238
src/transcript-branches.ts
Normal file
238
src/transcript-branches.ts
Normal file
@@ -0,0 +1,238 @@
|
||||
import type { SessionMessage, SessionStoreEntry } from "@anthropic-ai/claude-agent-sdk";
|
||||
|
||||
/** One record of a transcript file, with the fields that the branch order reads. */
|
||||
type TranscriptRecord = SessionStoreEntry & {
|
||||
uuid?: unknown;
|
||||
parentUuid?: unknown;
|
||||
isSidechain?: unknown;
|
||||
agentId?: unknown;
|
||||
message?: unknown;
|
||||
};
|
||||
|
||||
/**
|
||||
* The history of a transcript with each record of a model reply's branches,
|
||||
* in file order. `chain` is what the SDK read from `entries`, and `read`
|
||||
* reads the history from other entries in the same way.
|
||||
*
|
||||
* Claude Code writes each tool_use block of one model reply as its own
|
||||
* record, and parents the result of each call on the record of that call. A
|
||||
* record that comes with a result, such as the text of a Skill, has that
|
||||
* result as parent. So parallel calls make one branch per call. The SDK reads
|
||||
* one chain, from the last record back by `parentUuid`, and adds some of the
|
||||
* other records of the reply after the last chain record of the reply. So a
|
||||
* new record can move a record of the reply or drop it from the history:
|
||||
*
|
||||
* - a third tool_use of the reply, with the second result as parent, moves
|
||||
* the first result after it;
|
||||
* - the second result drops a record whose parent is the first result.
|
||||
*
|
||||
* The earlier history is then no prefix of the later one, and a record that
|
||||
* a client got is gone. Here each reply of the chain keeps every record that
|
||||
* grows from its records, up to the next reply, in file order, as Claude
|
||||
* Code appended them. A record whose branch leads to another reply is an
|
||||
* other history, such as the prompt before a rewind, and stays out. A
|
||||
* record that Claude Code wrote after the next record of the chain, or after
|
||||
* the last record of the chain, stays out too: it would go before a record
|
||||
* that a client already got. A later read adds a record of the second kind
|
||||
* when a record after it comes.
|
||||
*
|
||||
* The SDK still converts and selects the records: they go back to `read`
|
||||
* with the `parentUuid` of each record of a changed reply set to the record
|
||||
* before it in file order. The result is `chain` when no reply changes, or
|
||||
* when `read` drops a message of `chain` or gives another order.
|
||||
*/
|
||||
export async function withReplyBranches(
|
||||
entries: readonly SessionStoreEntry[],
|
||||
chain: SessionMessage[],
|
||||
read: (entries: SessionStoreEntry[]) => Promise<SessionMessage[]>,
|
||||
): Promise<SessionMessage[]> {
|
||||
const plan = replyBranchOrder(
|
||||
entries,
|
||||
chain.map((message) => message.uuid),
|
||||
);
|
||||
if (!plan) return chain;
|
||||
const history = await read(plan.entries);
|
||||
// The SDK leaves out some records, such as a meta prompt of the main thread.
|
||||
// The result must keep each message of `chain`, in the planned order.
|
||||
const kept = new Set(history.map((message) => message.uuid));
|
||||
if (chain.some((message) => !kept.has(message.uuid))) return chain;
|
||||
let at = 0;
|
||||
for (const message of history) {
|
||||
while (at < plan.order.length && plan.order[at] !== message.uuid) at++;
|
||||
if (at === plan.order.length) return chain;
|
||||
at++;
|
||||
}
|
||||
return history;
|
||||
}
|
||||
|
||||
/**
|
||||
* The record order of {@link withReplyBranches} for the SDK chain `chain`
|
||||
* (its uuids), and the entries to read it from. Undefined when the chain
|
||||
* already has that order.
|
||||
*/
|
||||
export function replyBranchOrder(
|
||||
entries: readonly SessionStoreEntry[],
|
||||
chain: readonly string[],
|
||||
): { order: string[]; entries: SessionStoreEntry[] } | undefined {
|
||||
const records = entries as readonly TranscriptRecord[];
|
||||
const byUuid = new Map<string, TranscriptRecord>();
|
||||
const position = new Map<string, number>();
|
||||
const children = new Map<string, string[]>();
|
||||
const replies = new Map<string, string[]>();
|
||||
records.forEach((record, index) => {
|
||||
if (typeof record.uuid !== "string") return;
|
||||
if (!byUuid.has(record.uuid) && typeof record.parentUuid === "string") {
|
||||
const siblings = children.get(record.parentUuid);
|
||||
if (siblings) siblings.push(record.uuid);
|
||||
else children.set(record.parentUuid, [record.uuid]);
|
||||
}
|
||||
if (!byUuid.has(record.uuid)) {
|
||||
const id = replyId(record);
|
||||
if (id !== undefined) {
|
||||
const members = replies.get(id);
|
||||
if (members) members.push(record.uuid);
|
||||
else replies.set(id, [record.uuid]);
|
||||
}
|
||||
}
|
||||
byUuid.set(record.uuid, record);
|
||||
if (!position.has(record.uuid)) position.set(record.uuid, index);
|
||||
});
|
||||
const inChain = new Set(chain);
|
||||
const order: string[] = [];
|
||||
/** The records of each changed reply, of every type, in file order. */
|
||||
const relinked: { region: string[]; next?: string }[] = [];
|
||||
const done = new Set<string>();
|
||||
for (let at = 0; at < chain.length;) {
|
||||
const record = byUuid.get(chain[at]!);
|
||||
const id = record && replyId(record);
|
||||
if (!record || id === undefined || done.has(id)) {
|
||||
order.push(chain[at]!);
|
||||
at++;
|
||||
continue;
|
||||
}
|
||||
done.add(id);
|
||||
const region = growth(record, id);
|
||||
let end = at;
|
||||
while (end < chain.length && region.has(chain[end]!)) end++;
|
||||
const run = chain.slice(at, end);
|
||||
// A record that Claude Code wrote after the next record of the chain would
|
||||
// go before a record that a client already got, so it stays out. So does a
|
||||
// record after the last one of the chain: the SDK ends the history at the
|
||||
// record that it chose, and a later read adds the record after it.
|
||||
// The SDK can move an earlier record of the run to its end, so the newest
|
||||
// record of the run sets the limit, not the last one.
|
||||
const limit =
|
||||
end < chain.length
|
||||
? position.get(chain[end]!)!
|
||||
: Math.max(...run.map((uuid) => position.get(uuid)!)) + 1;
|
||||
const sorted = [...region]
|
||||
.filter((uuid) => inChain.has(uuid) || position.get(uuid)! < limit)
|
||||
.sort((a, b) => position.get(a)! - position.get(b)!);
|
||||
const messages = sorted.filter((uuid) => isMessage(byUuid.get(uuid)!));
|
||||
// A record of the reply that the chain has at another place: keep the SDK order.
|
||||
const inRun = new Set(run);
|
||||
const inMessages = new Set(messages);
|
||||
if (messages.some((uuid) => inChain.has(uuid) && !inRun.has(uuid))) return undefined;
|
||||
if (run.some((uuid) => !inMessages.has(uuid))) return undefined;
|
||||
order.push(...messages);
|
||||
if (messages.length !== run.length || messages.some((uuid, index) => uuid !== run[index])) {
|
||||
relinked.push({ region: sorted, next: chain[end] });
|
||||
}
|
||||
at = end;
|
||||
}
|
||||
if (relinked.length === 0) return undefined;
|
||||
|
||||
const replaced = new Map<TranscriptRecord, TranscriptRecord>();
|
||||
const relink = (uuid: string, parentUuid: string) => {
|
||||
const record = byUuid.get(uuid)!;
|
||||
replaced.set(record, { ...(replaced.get(record) ?? record), parentUuid });
|
||||
};
|
||||
for (const { region, next } of relinked) {
|
||||
for (let index = 1; index < region.length; index++) relink(region[index]!, region[index - 1]!);
|
||||
if (next !== undefined) relink(next, region.at(-1)!);
|
||||
}
|
||||
return {
|
||||
order,
|
||||
entries: records.map((record) => replaced.get(record) ?? record),
|
||||
};
|
||||
|
||||
/**
|
||||
* The records of the reply `id` of `first`, and each record of the same
|
||||
* agent that grows from them up to the next reply. A record outside the
|
||||
* chain whose branch reaches another reply is left out, with its branch.
|
||||
*/
|
||||
function growth(first: TranscriptRecord, id: string): Set<string> {
|
||||
const region = new Set(replies.get(id)!.filter((uuid) => sameAgent(byUuid.get(uuid)!, first)));
|
||||
const queue = [...region];
|
||||
/** Whether the branch of each visited record reaches a record of another reply. */
|
||||
const leads = new Map<string, boolean>();
|
||||
const leadsElsewhere = (start: string): boolean => {
|
||||
// A walk with a stack: a branch can be thousands of records long.
|
||||
const stack: [string, boolean][] = [[start, false]];
|
||||
const entered = new Set<string>();
|
||||
while (stack.length > 0) {
|
||||
const [uuid, expanded] = stack.pop()!;
|
||||
if (expanded) {
|
||||
leads.set(
|
||||
uuid,
|
||||
(children.get(uuid) ?? []).some((child) => leads.get(child) === true),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
// A record seen before, or a cycle of `parentUuid` links.
|
||||
if (leads.has(uuid) || entered.has(uuid)) continue;
|
||||
entered.add(uuid);
|
||||
const other = replyId(byUuid.get(uuid)!);
|
||||
if (other !== undefined && other !== id) {
|
||||
leads.set(uuid, true);
|
||||
continue;
|
||||
}
|
||||
stack.push([uuid, true]);
|
||||
for (const child of children.get(uuid) ?? []) stack.push([child, false]);
|
||||
}
|
||||
return leads.get(start) === true;
|
||||
};
|
||||
while (queue.length > 0) {
|
||||
for (const child of children.get(queue.shift()!) ?? []) {
|
||||
if (region.has(child)) continue;
|
||||
const record = byUuid.get(child)!;
|
||||
const other = replyId(record);
|
||||
if (other !== undefined && other !== id) continue;
|
||||
if (!sameAgent(record, first)) continue;
|
||||
// A prompt outside the chain is a prompt that the user left, such as
|
||||
// the prompt before an edit or a rewind.
|
||||
if (!inChain.has(child) && (isPrompt(record) || leadsElsewhere(child))) continue;
|
||||
region.add(child);
|
||||
queue.push(child);
|
||||
}
|
||||
}
|
||||
return region;
|
||||
}
|
||||
}
|
||||
|
||||
/** The `message.id` of the model reply of an assistant record, or undefined. */
|
||||
function replyId(record: TranscriptRecord): string | undefined {
|
||||
if (record.type !== "assistant") return undefined;
|
||||
const id = (record.message as { id?: unknown } | null | undefined)?.id;
|
||||
return typeof id === "string" ? id : undefined;
|
||||
}
|
||||
|
||||
/** Whether `record` is a prompt: a user record with no tool result that is not a meta record. */
|
||||
function isPrompt(record: TranscriptRecord): boolean {
|
||||
if (record.type !== "user" || (record as { isMeta?: unknown }).isMeta === true) return false;
|
||||
const content = (record.message as { content?: unknown } | null | undefined)?.content;
|
||||
return !(
|
||||
Array.isArray(content) &&
|
||||
content.some((block) => (block as { type?: unknown } | null)?.type === "tool_result")
|
||||
);
|
||||
}
|
||||
|
||||
/** Whether the SDK gives `record` as a message of the history. */
|
||||
function isMessage(record: TranscriptRecord): boolean {
|
||||
return record.type === "user" || record.type === "assistant";
|
||||
}
|
||||
|
||||
/** Whether two records belong to one thread: the main thread or one subagent. */
|
||||
function sameAgent(a: TranscriptRecord, b: TranscriptRecord): boolean {
|
||||
return (a.isSidechain === true) === (b.isSidechain === true) && a.agentId === b.agentId;
|
||||
}
|
||||
Reference in New Issue
Block a user