mirror of
https://github.com/agentclientprotocol/claude-agent-acp.git
synced 2026-12-02 22:23:18 +00:00
Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
75376d11d6 | ||
|
|
5fb2db36eb |
@@ -14,8 +14,8 @@ A missing transcript returns `-32002`. A session already open, opening, closing
|
||||
|
||||
## Polling cost and scope
|
||||
|
||||
Each poll renders the retained history locally and sends only the additions to the client. A changed cursor is checked against a second render before delivery. Recorded children share the root request and can append independently. The unit of delivery is the whole suffix, including updates from recorded children. Clients can virtualize that history for display.
|
||||
A reader with a cached cursor for a root transcript checks the root file identity, size and timestamps, the rewind file, and the stored title when needed. When they match, it skips rendering history. This also covers sessions using Bash, PowerShell, Read, Write, Edit, Glob or Grep. Other tools can depend on child transcripts or workspace files, so their sessions take the full replay path. A reader restart, a pending rewind, or a change to the transcript or its title file also triggers full validation. A new or changed cursor is checked against a second render before delivery. Recorded children share the root request and can append independently. The unit of delivery is the whole suffix, including updates from recorded children. Clients can virtualize that history for display.
|
||||
|
||||
The title is the custom title from the transcript tail or `custom-title.json`, as in Claude’s session index. Otherwise it is the last `custom-title` record, or else the last `ai-title` record, of the whole captured transcript. The index reads only the first and last 64 KB of the file, so a large tool result would otherwise hide an unchanged title. The cursor describes the rendered transcript. For current session activity, AIR clients can use the [session index](air-extensions.md#session-index). For clients also talking to older adapters, a successful cursor request that returns `{}` means a full replay. Replace the saved view and clear the cursor.
|
||||
The title is the custom title from the transcript tail or `custom-title.json`, as in Claude’s session index. Otherwise it is the last `custom-title` record, or else the last `ai-title` record, of the whole captured transcript. The index reads only the first and last 64 KB of the file, so a large tool result would otherwise hide an unchanged title. The quiet check assumes the local filesystem updates file identity or timestamps on rewrites. The cursor describes the rendered transcript. For current session activity, AIR clients can use the [session index](air-extensions.md#session-index). For clients also talking to older adapters, a successful cursor request that returns `{}` means a full replay. Replace the saved view and clear the cursor.
|
||||
|
||||
A client switching from a live load to polling closes the session on its own connection and starts a fresh read.
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -623,13 +623,13 @@ export function customTitleSidecarPath(transcriptPath: string): string {
|
||||
}
|
||||
|
||||
/** The custom title that the SDK reads first: the tail's, else the CLI's
|
||||
* sidecar's. A strict read throws when the sidecar cannot be read. */
|
||||
* sidecar's, read by `readSidecar`. */
|
||||
export async function readRecentCustomTitle(
|
||||
transcriptPath: string,
|
||||
headTail: HeadTail,
|
||||
options?: { strict: boolean },
|
||||
readSidecar: (transcriptPath: string) => Promise<string | undefined> = readSidecarTitle,
|
||||
): Promise<string | undefined> {
|
||||
return tailCustomTitle(headTail) ?? (await readSidecarTitle(transcriptPath, options));
|
||||
return tailCustomTitle(headTail) ?? (await readSidecar(transcriptPath));
|
||||
}
|
||||
|
||||
/** The title of the CLI's sidecar, if it has a readable title. A strict read
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { RequestError } from "@agentclientprotocol/sdk/unstable";
|
||||
import { getSessionMessages, type SessionStoreEntry } from "@anthropic-ai/claude-agent-sdk";
|
||||
import { createHash } from "node:crypto";
|
||||
import { open } from "node:fs/promises";
|
||||
import type { BigIntStats } from "node:fs";
|
||||
import { lstat, open } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { z } from "zod";
|
||||
import packageJson from "../package.json" with { type: "json" };
|
||||
@@ -15,10 +16,12 @@ import { LastReportedEntity } from "./session-cursors.js";
|
||||
import {
|
||||
readHeadTailOf,
|
||||
readRecentCustomTitle,
|
||||
readSidecarTitle,
|
||||
type HeadTail,
|
||||
} from "./session-index/transcript-scan.js";
|
||||
import { sanitizeTitle } from "./session-titles.js";
|
||||
import { cutAtRewindPoint } from "./session-rewind.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;
|
||||
@@ -47,15 +50,85 @@ type ReadOptions = {
|
||||
cursors: boolean;
|
||||
signal?: AbortSignal;
|
||||
isOpen(sessionId: string): boolean;
|
||||
assertRoot?(sessionId: string): void;
|
||||
replay(
|
||||
sessionId: string,
|
||||
cwd: string | undefined,
|
||||
): Promise<{ frames: SessionReadFrame[]; cwd: string; historyEnd?: number; title?: string }>;
|
||||
observeStorage: boolean,
|
||||
): Promise<{
|
||||
frames: SessionReadFrame[];
|
||||
cwd: string;
|
||||
historyEnd?: number;
|
||||
title?: string;
|
||||
storage?: SessionReadStorage;
|
||||
}>;
|
||||
send(frame: SessionReadFrame): Promise<void> | void;
|
||||
};
|
||||
|
||||
export type SessionReadStorage = {
|
||||
transcript: string;
|
||||
version: string;
|
||||
/** Undefined when replay skipped the sidecar, null when it had no title. */
|
||||
sidecarTitle?: string | null;
|
||||
};
|
||||
|
||||
function fileVersion(stats: BigIntStats): string {
|
||||
const { dev, ino, mode, size, mtimeNs, ctimeNs } = stats;
|
||||
return [dev, ino, mode, size, mtimeNs, ctimeNs].join(":");
|
||||
}
|
||||
|
||||
/** Checks the transcript's metadata and the sidecar inputs read by the replay. */
|
||||
async function storageUnchanged(sessionId: string, storage: SessionReadStorage): Promise<boolean> {
|
||||
try {
|
||||
// A move or a different matching project must go through the ordinary lookup.
|
||||
const transcript = await findTranscript(sessionId, { strict: true });
|
||||
if (transcript !== storage.transcript) return false;
|
||||
const matchesTranscript = async () => {
|
||||
const root = await lstat(transcript, { bigint: true });
|
||||
return root.isFile() && fileVersion(root) === storage.version;
|
||||
};
|
||||
if (!(await matchesTranscript())) return false;
|
||||
if (storage.sidecarTitle !== undefined) {
|
||||
const title = await readSidecarTitle(transcript, { strict: true });
|
||||
if ((title ?? null) !== storage.sidecarTitle) return false;
|
||||
}
|
||||
if (await readRewindPoint(sessionId, undefined, { transcript })) return false;
|
||||
return await matchesTranscript();
|
||||
} catch {
|
||||
// An uncertain probe leaves validation and errors to the ordinary replay.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** These tools render their stored input and result, with no child or workspace reads. */
|
||||
const ROOT_ONLY_TOOLS = new Set(["Bash", "PowerShell", "Read", "Write", "Edit", "Glob", "Grep"]);
|
||||
|
||||
function hasIndependentHistory(content: unknown): boolean {
|
||||
return (
|
||||
Array.isArray(content) &&
|
||||
content.some(
|
||||
(block) =>
|
||||
["tool_use", "server_tool_use", "mcp_tool_use"].includes(block?.type) &&
|
||||
!ROOT_ONLY_TOOLS.has(block.name),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function currentDirectory(): string | undefined {
|
||||
try {
|
||||
return process.cwd();
|
||||
} catch {
|
||||
// The working directory could be gone; a replay with a stored cwd may still work.
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** The SDK follows parent links in these records, including the branch selected by rewind.json. */
|
||||
export async function readSessionTranscript(sessionId: string, cwd?: string) {
|
||||
export async function readSessionTranscript(
|
||||
sessionId: string,
|
||||
cwd?: string,
|
||||
observeStorage = false,
|
||||
) {
|
||||
if (!isSessionId(sessionId)) {
|
||||
throw RequestError.invalidParams({ sessionId }, "Read the root Claude session by its UUID.");
|
||||
}
|
||||
@@ -64,27 +137,39 @@ export async function readSessionTranscript(sessionId: string, cwd?: string) {
|
||||
const handle = await open(transcript, "r");
|
||||
let headTail: HeadTail;
|
||||
let records: SessionStoreEntry[];
|
||||
let version: string | undefined;
|
||||
try {
|
||||
const { size } = await handle.stat();
|
||||
const stat = await handle.stat({ bigint: true });
|
||||
if (observeStorage) version = fileVersion(stat);
|
||||
const size = Number(stat.size);
|
||||
headTail = await readHeadTailOf(handle, size);
|
||||
records = await readTranscriptEntriesOf(transcript, handle, size);
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
let sidecarTitle: string | null | undefined;
|
||||
const readTitle = async (file: string) => {
|
||||
const title = await readSidecarTitle(file, { strict: true });
|
||||
sidecarTitle = title ?? null;
|
||||
return title;
|
||||
};
|
||||
const title =
|
||||
records[0]?.isSidechain === true
|
||||
? undefined
|
||||
: ((await readRecentCustomTitle(transcript, headTail, { strict: true })) ??
|
||||
: ((await readRecentCustomTitle(transcript, headTail, readTitle)) ??
|
||||
lastRecordedTitle(records, "custom-title", "customTitle") ??
|
||||
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 retained = await cutAtRewindPoint(sessionId, chain, undefined, { transcript });
|
||||
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(
|
||||
sessionId,
|
||||
retained,
|
||||
@@ -97,6 +182,14 @@ export async function readSessionTranscript(sessionId: string, cwd?: string) {
|
||||
cwd: effectiveCwd,
|
||||
transcript,
|
||||
title: title && sanitizeTitle(title),
|
||||
storage:
|
||||
version &&
|
||||
!rewind &&
|
||||
!messages.some((message) =>
|
||||
hasIndependentHistory((message.message as { content?: unknown } | null)?.content),
|
||||
)
|
||||
? { transcript, version, sidecarTitle }
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -237,12 +330,25 @@ function snapshot(
|
||||
return { outgoing, anchor, cursorId: anchor ? cursor(false) : undefined };
|
||||
}
|
||||
|
||||
type Checkpoint = {
|
||||
cursorId: string;
|
||||
scope: string;
|
||||
requestedCwd: string | undefined;
|
||||
cwd: string;
|
||||
processCwd: string;
|
||||
storage: SessionReadStorage;
|
||||
boundaries: SessionReadFrame[];
|
||||
title?: string;
|
||||
};
|
||||
|
||||
/** A read owns only a replay on this connection. Closing it invalidates the pending delivery. */
|
||||
export class SessionReads {
|
||||
private readonly active = new Map<string, { invalidated: boolean }>();
|
||||
|
||||
private readonly transitions = new Map<string, number>();
|
||||
|
||||
private readonly checkpoints = new Map<string, Checkpoint>();
|
||||
|
||||
/** Reserve a session before load, resume, close or delete can yield. */
|
||||
async transition<T>(
|
||||
sessionId: string | undefined,
|
||||
@@ -255,6 +361,7 @@ export class SessionReads {
|
||||
if (kind === "open") throw alreadyOpen(sessionId);
|
||||
read.invalidated = true;
|
||||
}
|
||||
this.checkpoints.delete(sessionId);
|
||||
this.transitions.set(sessionId, (this.transitions.get(sessionId) ?? 0) + 1);
|
||||
try {
|
||||
return await run();
|
||||
@@ -269,7 +376,8 @@ export class SessionReads {
|
||||
const parsed = request.safeParse(params);
|
||||
if (!parsed.success)
|
||||
throw RequestError.invalidParams(undefined, parsed.error.issues[0]?.message);
|
||||
const { sessionId, cwd, replayFrom } = parsed.data;
|
||||
const { sessionId, replayFrom } = parsed.data;
|
||||
const cwd = parsed.data.cwd ?? undefined;
|
||||
const previous = replayFrom?.type === "cursor" ? replayFrom.cursorId : undefined;
|
||||
if (
|
||||
replayFrom?.type === "cursor" &&
|
||||
@@ -285,10 +393,22 @@ export class SessionReads {
|
||||
throw alreadyOpen(sessionId);
|
||||
};
|
||||
check();
|
||||
options.assertRoot?.(sessionId);
|
||||
this.active.set(sessionId, read);
|
||||
const useCursor = options.cursors && replayFrom != null;
|
||||
const processCwd = useCursor ? currentDirectory() : undefined;
|
||||
const scopeFor = (effectiveCwd: string) =>
|
||||
json([
|
||||
sessionId,
|
||||
effectiveCwd,
|
||||
claudeConfigDir(),
|
||||
options.protocol,
|
||||
options.capabilities,
|
||||
packageJson.version,
|
||||
]);
|
||||
const replay = async () => {
|
||||
try {
|
||||
const view = await options.replay(sessionId, cwd ?? undefined);
|
||||
const view = await options.replay(sessionId, cwd, useCursor);
|
||||
if (options.protocol === 1 && view.title)
|
||||
view.frames.push({
|
||||
sessionId,
|
||||
@@ -310,67 +430,108 @@ export class SessionReads {
|
||||
);
|
||||
}
|
||||
};
|
||||
try {
|
||||
const { frames, cwd: effectiveCwd, historyEnd, title } = await replay();
|
||||
check();
|
||||
let outgoing = frames;
|
||||
let cursorId: string | undefined;
|
||||
const useCursor = options.cursors && replayFrom != null;
|
||||
if (useCursor) {
|
||||
const scope = json([
|
||||
sessionId,
|
||||
effectiveCwd,
|
||||
claudeConfigDir(),
|
||||
options.protocol,
|
||||
options.capabilities,
|
||||
packageJson.version,
|
||||
]);
|
||||
const next = snapshot(frames, sessionId, options.protocol, scope, cursor, historyEnd);
|
||||
outgoing = next.outgoing;
|
||||
cursorId = next.cursorId;
|
||||
if (cursorId && cursorId !== cursor) {
|
||||
// A terminal can append or rewind between the reads of the root and a child.
|
||||
const again = await replay();
|
||||
check();
|
||||
if (
|
||||
again.cwd !== effectiveCwd ||
|
||||
again.historyEnd !== historyEnd ||
|
||||
frames.length !== again.frames.length ||
|
||||
frames.some((frame, i) => json(frame) !== json(again.frames[i]))
|
||||
) {
|
||||
throw RequestError.internalError(
|
||||
{ sessionId, retryable: true },
|
||||
"History changed during the read. Retry with the last successful cursor.",
|
||||
);
|
||||
}
|
||||
const end = outgoing.findIndex(
|
||||
(frame) =>
|
||||
frame.sessionId === sessionId && frame.update.sessionUpdate === "replay_complete",
|
||||
);
|
||||
outgoing.splice(end < 0 ? outgoing.length : end, 0, {
|
||||
sessionId,
|
||||
update: {
|
||||
sessionUpdate: "cursor_update",
|
||||
cursorId,
|
||||
anchor: next.anchor,
|
||||
capabilities: { read: {} },
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
// On v2 the title is current session info, outside the replay cursor.
|
||||
if (options.protocol === 2 && (title || useCursor)) {
|
||||
outgoing.push({
|
||||
sessionId,
|
||||
update: { sessionUpdate: "session_info_update", title: title || null },
|
||||
});
|
||||
}
|
||||
const deliver = async (
|
||||
outgoing: SessionReadFrame[],
|
||||
cursorId: string | undefined,
|
||||
title: string | undefined,
|
||||
) => {
|
||||
for (const frame of outgoing) {
|
||||
check();
|
||||
await options.send(frame);
|
||||
}
|
||||
// On v2 the title is current session info, outside the replay cursor.
|
||||
if (options.protocol === 2 && (title || useCursor)) {
|
||||
check();
|
||||
await options.send({
|
||||
sessionId,
|
||||
update: { sessionUpdate: "session_info_update", title: title || null },
|
||||
});
|
||||
}
|
||||
check();
|
||||
return cursorId ? { cursorId } : {};
|
||||
};
|
||||
try {
|
||||
const cached = cursor ? this.checkpoints.get(sessionId) : undefined;
|
||||
if (
|
||||
cached &&
|
||||
cached.cursorId === cursor &&
|
||||
(cached.requestedCwd === cwd || cached.cwd === cwd) &&
|
||||
cached.processCwd === processCwd &&
|
||||
cached.scope === scopeFor(cached.cwd) &&
|
||||
(await storageUnchanged(sessionId, cached.storage)) &&
|
||||
cached.processCwd === currentDirectory()
|
||||
) {
|
||||
return await deliver(cached.boundaries, cached.cursorId, cached.title);
|
||||
}
|
||||
check();
|
||||
if (useCursor) this.checkpoints.delete(sessionId);
|
||||
const { frames, cwd: effectiveCwd, historyEnd, title, storage } = await replay();
|
||||
check();
|
||||
if (!useCursor) return await deliver(frames, undefined, title);
|
||||
const scope = scopeFor(effectiveCwd);
|
||||
const { outgoing, cursorId, anchor } = snapshot(
|
||||
frames,
|
||||
sessionId,
|
||||
options.protocol,
|
||||
scope,
|
||||
cursor,
|
||||
historyEnd,
|
||||
);
|
||||
let verifiedStorage = storage;
|
||||
const isRootBoundary = (frame: SessionReadFrame) =>
|
||||
frame.sessionId === sessionId && frame.update.sessionUpdate === "replay_complete";
|
||||
if (cursorId && cursorId !== cursor) {
|
||||
// A terminal can append or rewind between the reads of the root and a child.
|
||||
const again = await replay();
|
||||
check();
|
||||
if (
|
||||
again.cwd !== effectiveCwd ||
|
||||
again.historyEnd !== historyEnd ||
|
||||
frames.length !== again.frames.length ||
|
||||
frames.some((frame, i) => json(frame) !== json(again.frames[i]))
|
||||
) {
|
||||
throw RequestError.internalError(
|
||||
{ sessionId, retryable: true },
|
||||
"History changed during the read. Retry with the last successful cursor.",
|
||||
);
|
||||
}
|
||||
if (
|
||||
again.storage?.transcript !== storage?.transcript ||
|
||||
again.storage?.version !== storage?.version ||
|
||||
again.storage?.sidecarTitle !== storage?.sidecarTitle
|
||||
) {
|
||||
verifiedStorage = undefined;
|
||||
}
|
||||
const end = outgoing.findIndex(isRootBoundary);
|
||||
outgoing.splice(end < 0 ? outgoing.length : end, 0, {
|
||||
sessionId,
|
||||
update: {
|
||||
sessionUpdate: "cursor_update",
|
||||
cursorId,
|
||||
anchor,
|
||||
capabilities: { read: {} },
|
||||
},
|
||||
});
|
||||
}
|
||||
// Pair the cursor only with the inputs read by its render, never a later append.
|
||||
const result = await deliver(outgoing, cursorId, title);
|
||||
check();
|
||||
if (cursorId && verifiedStorage && processCwd && processCwd === currentDirectory()) {
|
||||
this.checkpoints.set(sessionId, {
|
||||
cursorId,
|
||||
scope,
|
||||
requestedCwd: cwd,
|
||||
cwd: effectiveCwd,
|
||||
processCwd,
|
||||
storage: verifiedStorage,
|
||||
boundaries: frames.filter(isRootBoundary),
|
||||
title,
|
||||
});
|
||||
if (this.checkpoints.size > 32) {
|
||||
this.checkpoints.delete(this.checkpoints.keys().next().value!);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
} finally {
|
||||
this.active.delete(sessionId);
|
||||
}
|
||||
|
||||
@@ -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`. */
|
||||
|
||||
@@ -1,5 +1,18 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { SessionReads, type SessionReadFrame } from "../session-read.js";
|
||||
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 {
|
||||
parallelToolCallRecords,
|
||||
transcriptAssistant,
|
||||
transcriptUser,
|
||||
writeTranscript,
|
||||
} from "./helpers.js";
|
||||
|
||||
describe("session read cursors", () => {
|
||||
const message = (messageId: string): SessionReadFrame => ({
|
||||
@@ -74,4 +87,122 @@ describe("session read cursors", () => {
|
||||
"cursor_update",
|
||||
]);
|
||||
});
|
||||
|
||||
it.each(["title", "rewind"] as const)(
|
||||
"validates the %s observed while a sidecar briefly exists during each render",
|
||||
async (kind) => {
|
||||
const sessionId = randomUUID();
|
||||
const dir = await mkdtemp(path.join(tmpdir(), "claude-acp-read-race-"));
|
||||
const project = path.join(dir, "projects", "-project");
|
||||
const transcript = path.join(project, `${sessionId}.jsonl`);
|
||||
const sidecar =
|
||||
kind === "title"
|
||||
? transcriptScan.customTitleSidecarPath(transcript)
|
||||
: path.join(project, sessionId, "rewind.json");
|
||||
vi.stubEnv("CLAUDE_CONFIG_DIR", dir);
|
||||
const readHeadTail = transcriptScan.readHeadTailOf;
|
||||
const race = vi
|
||||
.spyOn(transcriptScan, "readHeadTailOf")
|
||||
.mockImplementation(async (...args) => {
|
||||
if (kind === "title") await writeCustomTitleSidecar(transcript, "Temporary title");
|
||||
else
|
||||
await writeRewindPoint(sessionId, { resumeSessionAt: "u1", droppedPromptUuid: "a1" });
|
||||
return readHeadTail(...args);
|
||||
});
|
||||
try {
|
||||
await writeTranscript(project, sessionId, [
|
||||
transcriptUser("u1", "Prompt", { cwd: dir }),
|
||||
transcriptAssistant("a1", "Answer"),
|
||||
]);
|
||||
const reads = new SessionReads();
|
||||
const options = {
|
||||
...reader([]),
|
||||
protocol: 2 as const,
|
||||
replay: async (id: string, cwd: string | undefined, observeStorage: boolean) => {
|
||||
const view = await readSessionTranscript(id, cwd, observeStorage);
|
||||
await rm(sidecar, { force: true });
|
||||
return {
|
||||
...view,
|
||||
frames: view.messages.map(({ uuid }) => ({ ...message(uuid), sessionId })),
|
||||
};
|
||||
},
|
||||
};
|
||||
const { cursorId } = await reads.read({ ...start, sessionId }, options);
|
||||
expect(cursorId).toBeTruthy();
|
||||
expect(race).toHaveBeenCalledTimes(2);
|
||||
race.mockRestore();
|
||||
options.send.mockClear();
|
||||
|
||||
const next = await reads.read({ ...poll(cursorId), sessionId }, options);
|
||||
if (kind === "title") expect(next.cursorId).toBe(cursorId);
|
||||
else expect(next.cursorId).not.toBe(cursorId);
|
||||
expect(options.send.mock.calls.at(-1)?.[0]).toEqual({
|
||||
sessionId,
|
||||
update: { sessionUpdate: "session_info_update", title: null },
|
||||
});
|
||||
} finally {
|
||||
race.mockRestore();
|
||||
vi.unstubAllEnvs();
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { mkdir, mkdtemp, readFile, rm, utimes, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { client, methods, type InitializeResponse } from "@agentclientprotocol/sdk/unstable";
|
||||
@@ -18,6 +18,7 @@ import { writeRewindPoint } from "../../session-rewind.js";
|
||||
import { ClaudeAcpAgent, v1AgentApp } from "../../v1/acp-agent.js";
|
||||
import {
|
||||
initializeClient,
|
||||
parallelToolCallRecords,
|
||||
transcriptAssistant,
|
||||
transcriptUser,
|
||||
writeTranscript,
|
||||
@@ -132,6 +133,9 @@ describe("_session/read on v1", () => {
|
||||
transcriptAssistant("a2", "Second answer"),
|
||||
];
|
||||
await store(first);
|
||||
const transcript = path.join(project, `${sessionId}.jsonl`);
|
||||
const mtime = new Date("2026-10-11T00:00:00Z");
|
||||
await utimes(transcript, mtime, mtime);
|
||||
const { connection, agent, updates } = connect();
|
||||
try {
|
||||
const init = (await connection.agent.request("initialize", {
|
||||
@@ -169,10 +173,14 @@ describe("_session/read on v1", () => {
|
||||
});
|
||||
const poll = (cursorId: string, dir?: string) => read({ type: "cursor", cursorId }, dir);
|
||||
updates.length = 0;
|
||||
vi.mocked(getSessionMessages).mockClear();
|
||||
expect(await poll(initial.cursorId, cwd)).toEqual(initial);
|
||||
expect(updates).toEqual([]);
|
||||
expect(getSessionMessages).not.toHaveBeenCalled();
|
||||
|
||||
// Rewriting the same number of bytes and restoring mtime still changes ctime.
|
||||
await store([...history, first[2]!, transcriptAssistant("a2", "Edited answer")]);
|
||||
await utimes(transcript, mtime, mtime);
|
||||
await expect(poll(initial.cursorId)).rejects.toMatchObject(invalidCursor);
|
||||
expect(updates).toEqual([]);
|
||||
|
||||
@@ -191,7 +199,6 @@ describe("_session/read on v1", () => {
|
||||
},
|
||||
]);
|
||||
|
||||
const transcript = path.join(project, `${sessionId}.jsonl`);
|
||||
const previousContents = await readFile(transcript, "utf8");
|
||||
await writeRewindPoint(sessionId, { resumeSessionAt: "a1", droppedPromptUuid: "u2" });
|
||||
updates.length = 0;
|
||||
@@ -209,6 +216,103 @@ describe("_session/read on v1", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("finds an append that arrives after the confirmation transcript was read", async () => {
|
||||
await store(history);
|
||||
const actual = await vi.importActual<typeof import("@anthropic-ai/claude-agent-sdk")>(
|
||||
"@anthropic-ai/claude-agent-sdk",
|
||||
);
|
||||
vi.mocked(getSessionMessages)
|
||||
.mockImplementationOnce(actual.getSessionMessages)
|
||||
.mockImplementationOnce(async (...args) => {
|
||||
const messages = await actual.getSessionMessages(...args);
|
||||
await store([...history, transcriptUser("u2", "Second question")]);
|
||||
return messages;
|
||||
});
|
||||
|
||||
const { agent, updates } = captureUpdates();
|
||||
try {
|
||||
await initializeClient(agent, { session: { cursors: {} } });
|
||||
const { cursorId } = await agent.readSession({ sessionId, replayFrom: start });
|
||||
expect(
|
||||
updates.flatMap(({ update }) => ("content" in update ? [update.content] : [])),
|
||||
).toEqual([
|
||||
{ type: "text", text: "First question" },
|
||||
{ type: "text", text: "First answer" },
|
||||
]);
|
||||
|
||||
updates.length = 0;
|
||||
const next = await agent.readSession({
|
||||
sessionId,
|
||||
replayFrom: { type: "cursor", cursorId },
|
||||
});
|
||||
expect(next.cursorId).not.toBe(cursorId);
|
||||
expect(
|
||||
updates.flatMap(({ update }) => ("content" in update ? [update.content] : [])),
|
||||
).toEqual([{ type: "text", text: "Second question" }]);
|
||||
|
||||
await rm(path.join(project, `${sessionId}.jsonl`));
|
||||
updates.length = 0;
|
||||
await expect(
|
||||
agent.readSession({ sessionId, replayFrom: { type: "cursor", cursorId: next.cursorId } }),
|
||||
).rejects.toMatchObject({ code: -32002 });
|
||||
expect(updates).toEqual([]);
|
||||
} finally {
|
||||
await agent.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
["Read", false],
|
||||
["Skill", true],
|
||||
])("checks whether %s replay needs a full scan", async (name, needsReplay) => {
|
||||
const toolId = "toolu_saved";
|
||||
await store([
|
||||
history[0]!,
|
||||
{
|
||||
...transcriptAssistant("use", ""),
|
||||
message: {
|
||||
role: "assistant",
|
||||
id: "msg_use",
|
||||
content: [
|
||||
{
|
||||
type: "tool_use",
|
||||
id: toolId,
|
||||
name,
|
||||
input:
|
||||
name === "Read" ? { file_path: path.join(cwd, "saved.txt") } : { skill: "example" },
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
]);
|
||||
const { agent, updates } = captureUpdates();
|
||||
try {
|
||||
await initializeClient(agent, { session: { cursors: {} } });
|
||||
const { cursorId } = await agent.readSession({ sessionId, replayFrom: start });
|
||||
expect(updates.some(({ update }) => update.sessionUpdate === "tool_call")).toBe(true);
|
||||
|
||||
updates.length = 0;
|
||||
vi.mocked(getSessionMessages).mockClear();
|
||||
expect(
|
||||
await agent.readSession({ sessionId, replayFrom: { type: "cursor", cursorId } }),
|
||||
).toEqual({ cursorId });
|
||||
expect(updates).toEqual([]);
|
||||
expect(getSessionMessages).toHaveBeenCalledTimes(needsReplay ? 1 : 0);
|
||||
if (!needsReplay) {
|
||||
await expect(
|
||||
agent.readSession({
|
||||
sessionId,
|
||||
cwd: path.join(cwd, "other"),
|
||||
replayFrom: { type: "cursor", cursorId },
|
||||
}),
|
||||
).rejects.toMatchObject(invalidCursor);
|
||||
expect(updates).toEqual([]);
|
||||
}
|
||||
} finally {
|
||||
await agent.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("invalidates a saved cursor after a sidecar title in the replay changes", async () => {
|
||||
await store(history);
|
||||
const transcript = path.join(project, `${sessionId}.jsonl`);
|
||||
@@ -419,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");
|
||||
@@ -1291,12 +1339,17 @@ describe("ACP v2 sessions", () => {
|
||||
expect(cursorId).toEqual(expect.any(String));
|
||||
expect(client.sessionUpdates.slice(-2)).toEqual(titleUpdates("Original"));
|
||||
saved = { type: "cursor", cursorId: cursorId! };
|
||||
for (const title of ["Renamed", "Renamed", null]) {
|
||||
if (title === null) await rm(customTitleSidecarPath(transcript));
|
||||
const expectTitle = async (title: string | null) => {
|
||||
client.sessionUpdates.length = 0;
|
||||
expect(await read(agent, sessionId, saved)).toEqual({ cursorId });
|
||||
expect(client.sessionUpdates).toEqual(titleUpdates(title));
|
||||
}
|
||||
};
|
||||
await expectTitle("Renamed");
|
||||
vi.mocked(getSessionMessages).mockClear();
|
||||
await expectTitle("Renamed");
|
||||
expect(getSessionMessages).not.toHaveBeenCalled();
|
||||
await rm(customTitleSidecarPath(transcript));
|
||||
await expectTitle(null);
|
||||
});
|
||||
|
||||
const reconnect = v2Client();
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -46,10 +46,10 @@ export class V1SessionReads {
|
||||
capabilities: options.capabilities,
|
||||
cursors: options.capabilities?.session?.cursors != null,
|
||||
isOpen: options.isOpen,
|
||||
assertRoot: options.assertRoot,
|
||||
signal,
|
||||
replay: async (sessionId, cwd) => {
|
||||
options.assertRoot(sessionId);
|
||||
const transcript = await readSessionTranscript(sessionId, cwd);
|
||||
replay: async (sessionId, cwd, observeStorage) => {
|
||||
const transcript = await readSessionTranscript(sessionId, cwd, observeStorage);
|
||||
signal.throwIfAborted();
|
||||
const frames: SessionReadFrame[] = [];
|
||||
let historyEnd: number | undefined;
|
||||
@@ -79,6 +79,7 @@ export class V1SessionReads {
|
||||
return {
|
||||
frames,
|
||||
cwd: transcript.cwd,
|
||||
storage: transcript.storage,
|
||||
historyEnd,
|
||||
title: transcript.title === undefined ? undefined : options.clientTitle(transcript.title),
|
||||
};
|
||||
|
||||
@@ -420,7 +420,8 @@ class V2Agent implements AgentHandle, SessionConnection {
|
||||
signal,
|
||||
isOpen: (sessionId) =>
|
||||
this.sessions.has(sessionId) || this.stopped.has(sessionId) || this.starting.has(sessionId),
|
||||
replay: (sessionId, cwd) => renderSessionRead(sessionId, cwd, this.logger, capabilities),
|
||||
replay: (sessionId, cwd, observeStorage) =>
|
||||
renderSessionRead(sessionId, cwd, this.logger, capabilities, observeStorage),
|
||||
send: (frame) =>
|
||||
this.ctx.notify(v2.methods.client.session.update, frame as v2.UpdateSessionNotification),
|
||||
});
|
||||
|
||||
@@ -12,8 +12,13 @@ export async function renderSessionRead(
|
||||
dir: string | undefined,
|
||||
logger: Logger,
|
||||
capabilities: v2.ClientCapabilities | null | undefined,
|
||||
): Promise<{ frames: SessionReadFrame[]; cwd: string; historyEnd: number; title?: string }> {
|
||||
const { messages, cwd, transcript, title } = await readSessionTranscript(sessionId, dir);
|
||||
observeStorage: boolean,
|
||||
) {
|
||||
const { messages, cwd, transcript, title, storage } = await readSessionTranscript(
|
||||
sessionId,
|
||||
dir,
|
||||
observeStorage,
|
||||
);
|
||||
const frames: SessionReadFrame[] = [];
|
||||
const translator = new V2UpdateTranslator();
|
||||
const send = (notification: v2.UpdateSessionNotification): void => {
|
||||
@@ -42,5 +47,5 @@ export async function renderSessionRead(
|
||||
const end = replayEndUpdate(capabilities);
|
||||
if (end) send({ sessionId, update: end });
|
||||
subagents?.reportMissingHistory();
|
||||
return { frames, cwd, historyEnd, title };
|
||||
return { frames, cwd, historyEnd, title, storage };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user