mirror of
https://github.com/agentclientprotocol/claude-agent-acp.git
synced 2026-12-02 22:23:18 +00:00
Compare commits
3 Commits
v0.114.0
...
air/sessio
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
12e8b795dc | ||
|
|
fc095a7d76 | ||
|
|
5fb2db36eb |
@@ -14,8 +14,10 @@ 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.
|
||||
On the full replay path, each connection keeps the parsed records of the root and child transcripts that it read. A poll parses only the lines appended since the last read. It reuses the messages of each transcript that did not change. A transcript that got a new identity, got shorter, or changed its first or last 4 KB is parsed again in full. A connection keeps at most 1,024 files and 256 MB of transcript lines. At the limit, this costs about 200 to 340 MB of heap. To keep a new file, it drops only files that no read used in the last minute. So a session bigger than the limit keeps the same part from poll to poll, and the rest is parsed on each poll. A file that no read used for 5 minutes is dropped. A load, resume, close or delete drops the files of the session.
|
||||
|
||||
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.
|
||||
|
||||
@@ -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 { TranscriptCache, type TranscriptSnapshot } from "./transcript-cache.js";
|
||||
|
||||
export const SESSION_READ_METHOD = "_session/read";
|
||||
export const SESSION_READ_CAPABILITY = { supported: true } as const;
|
||||
@@ -47,15 +50,93 @@ 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,
|
||||
cache: TranscriptCache,
|
||||
): Promise<{
|
||||
frames: SessionReadFrame[];
|
||||
cwd: string;
|
||||
historyEnd?: number;
|
||||
title?: string;
|
||||
storage?: SessionReadStorage;
|
||||
}>;
|
||||
send(frame: SessionReadFrame): Promise<void> | void;
|
||||
};
|
||||
|
||||
/** The SDK follows parent links in these records, including the branch selected by rewind.json. */
|
||||
export async function readSessionTranscript(sessionId: string, cwd?: string) {
|
||||
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.
|
||||
*
|
||||
* With `cache`, the records come from the kept parse of the transcript, and
|
||||
* the messages of an unchanged transcript come from the last read (see
|
||||
* {@link TranscriptCache}). The result is the same as without it.
|
||||
*/
|
||||
export async function readSessionTranscript(
|
||||
sessionId: string,
|
||||
cwd?: string,
|
||||
observeStorage = false,
|
||||
cache?: TranscriptCache,
|
||||
) {
|
||||
if (!isSessionId(sessionId)) {
|
||||
throw RequestError.invalidParams({ sessionId }, "Read the root Claude session by its UUID.");
|
||||
}
|
||||
@@ -64,17 +145,32 @@ export async function readSessionTranscript(sessionId: string, cwd?: string) {
|
||||
const handle = await open(transcript, "r");
|
||||
let headTail: HeadTail;
|
||||
let records: SessionStoreEntry[];
|
||||
let version: string | undefined;
|
||||
let snapshot: TranscriptSnapshot | 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);
|
||||
if (cache) {
|
||||
snapshot = await cache.read(transcript, { handle, size });
|
||||
records = snapshot.entries;
|
||||
} else {
|
||||
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;
|
||||
@@ -83,20 +179,35 @@ export async function readSessionTranscript(sessionId: string, cwd?: string) {
|
||||
dir: effectiveCwd,
|
||||
sessionStore: { append: async () => {}, load: async () => records },
|
||||
};
|
||||
const chain = await getSessionMessages(sessionId, options);
|
||||
const retained = await cutAtRewindPoint(sessionId, chain, undefined, { transcript });
|
||||
const messages = await readHistoryAcrossCompactions(
|
||||
sessionId,
|
||||
retained,
|
||||
undefined,
|
||||
effectiveCwd,
|
||||
records,
|
||||
);
|
||||
const rewind = await readRewindPoint(sessionId, undefined, { transcript });
|
||||
const history = async () => {
|
||||
const chain = await getSessionMessages(sessionId, options);
|
||||
const retained = activeSessionMessages(chain, rewind);
|
||||
return readHistoryAcrossCompactions(sessionId, retained, undefined, effectiveCwd, records);
|
||||
};
|
||||
// The messages depend only on the records, the directory and the rewind point.
|
||||
const messages =
|
||||
cache && snapshot
|
||||
? await cache.memo(
|
||||
transcript,
|
||||
snapshot.version,
|
||||
json(["root", effectiveCwd, rewind ?? null]),
|
||||
history,
|
||||
)
|
||||
: await history();
|
||||
return {
|
||||
messages,
|
||||
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 +348,46 @@ function snapshot(
|
||||
return { outgoing, anchor, cursorId: anchor ? cursor(false) : undefined };
|
||||
}
|
||||
|
||||
/** How many transcript files a connection keeps parsed: the root and the subagent transcripts. */
|
||||
const KEPT_TRANSCRIPTS = 1024;
|
||||
|
||||
/** How many bytes of transcript lines a connection keeps parsed, all files together. */
|
||||
const KEPT_TRANSCRIPT_BYTES = 256 * 1024 * 1024;
|
||||
|
||||
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>();
|
||||
|
||||
/**
|
||||
* The parsed transcripts of the reads on this connection. A poll parses
|
||||
* only the lines that Claude Code appended since the last read, and reuses
|
||||
* the messages of each transcript that did not change.
|
||||
*/
|
||||
private readonly cache = new TranscriptCache({
|
||||
files: KEPT_TRANSCRIPTS,
|
||||
bytes: KEPT_TRANSCRIPT_BYTES,
|
||||
});
|
||||
|
||||
/** Drops the parsed transcripts of the connection. */
|
||||
dispose(): void {
|
||||
this.cache.clear();
|
||||
}
|
||||
|
||||
/** Reserve a session before load, resume, close or delete can yield. */
|
||||
async transition<T>(
|
||||
sessionId: string | undefined,
|
||||
@@ -255,6 +400,9 @@ export class SessionReads {
|
||||
if (kind === "open") throw alreadyOpen(sessionId);
|
||||
read.invalidated = true;
|
||||
}
|
||||
this.checkpoints.delete(sessionId);
|
||||
// An open session refuses reads, and a closed one changes its files.
|
||||
this.cache.forgetSession(sessionId);
|
||||
this.transitions.set(sessionId, (this.transitions.get(sessionId) ?? 0) + 1);
|
||||
try {
|
||||
return await run();
|
||||
@@ -269,7 +417,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 +434,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, this.cache);
|
||||
if (options.protocol === 1 && view.title)
|
||||
view.frames.push({
|
||||
sessionId,
|
||||
@@ -310,67 +471,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,13 +2,16 @@ 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";
|
||||
import path from "node:path";
|
||||
import readline from "node:readline";
|
||||
import { isDeepStrictEqual } from "node:util";
|
||||
import { isNativeSubagentControlTool, type HistoricalSubagent } from "./native-subagents.js";
|
||||
import { findTranscript, readTranscriptEntries } from "./resumed-session.js";
|
||||
import type { TranscriptCache } from "./transcript-cache.js";
|
||||
|
||||
/** What the metadata file of a subagent says about it. */
|
||||
export interface SubagentRecord {
|
||||
@@ -329,21 +332,27 @@ function withPath(error: unknown, file: string): Error & { path: string } {
|
||||
return Object.assign(new Error(`Failed to read ${file}`, { cause: error }), { path: file });
|
||||
}
|
||||
|
||||
/** Read a child from the resolved project without silently omitting read failures. */
|
||||
/**
|
||||
* Read a child from the resolved project without silently omitting read failures.
|
||||
*
|
||||
* With `cache`, the records come from the kept parse of the transcript, and
|
||||
* the messages of an unchanged transcript come from the last read (see
|
||||
* {@link TranscriptCache}). The result is the same as without it.
|
||||
*/
|
||||
export async function readSubagentMessagesOrFail(
|
||||
sessionId: string,
|
||||
agentId: string,
|
||||
history: SubagentHistory,
|
||||
launchId: string,
|
||||
cache?: TranscriptCache,
|
||||
): Promise<SessionMessage[]> {
|
||||
if (!history.directory) throw new Error("Subagent directory was not resolved");
|
||||
const file = path.join(history.directory, `agent-${agentId}.jsonl`);
|
||||
try {
|
||||
const entries = await readTranscriptEntries(file);
|
||||
// The SDK reads these fields from agent-*.meta.json only with its filesystem store.
|
||||
const parent = history.agents.get(launchId)?.parentAgentId ?? null;
|
||||
const messagesOf = async (entries: SessionStoreEntry[]) => {
|
||||
const sessionStore = { append: async () => {}, load: async () => entries };
|
||||
const messages = await getSubagentMessages(sessionId, agentId, { sessionStore });
|
||||
// The SDK reads these fields from agent-*.meta.json only with its filesystem store.
|
||||
const parent = history.agents.get(launchId)?.parentAgentId ?? null;
|
||||
return stripForkPrefix(
|
||||
messages.map((message) => ({
|
||||
...message,
|
||||
@@ -351,12 +360,43 @@ export async function readSubagentMessagesOrFail(
|
||||
parent_agent_id: parent,
|
||||
})),
|
||||
);
|
||||
};
|
||||
try {
|
||||
if (!cache) return await messagesOf(await readTranscriptEntries(file));
|
||||
const { entries, version } = await cache.read(file);
|
||||
return await cache.memo(
|
||||
file,
|
||||
version,
|
||||
JSON.stringify([sessionId, launchId, parent]),
|
||||
async () => shareRecords(await messagesOf(entries), entries),
|
||||
);
|
||||
} catch (error) {
|
||||
if (isMissing(error)) return [];
|
||||
throw withPath(error, file);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `messages` with the `message` of the record of `entries` that each one
|
||||
* equals. The SDK copies the `message` of each subagent record, so a kept
|
||||
* list of messages would hold the transcript a second time.
|
||||
*/
|
||||
function shareRecords(messages: SessionMessage[], entries: SessionStoreEntry[]): SessionMessage[] {
|
||||
const records = new Map<unknown, SessionStoreEntry>();
|
||||
for (const entry of entries) records.set(entry.uuid, entry);
|
||||
for (const message of messages) {
|
||||
const record = records.get(message.uuid);
|
||||
if (
|
||||
record &&
|
||||
record.message !== message.message &&
|
||||
isDeepStrictEqual(record.message, message.message)
|
||||
) {
|
||||
message.message = record.message;
|
||||
}
|
||||
}
|
||||
return messages;
|
||||
}
|
||||
|
||||
/** How Claude Code opens the directive message of a `subagent_type: "fork"` child. */
|
||||
const FORK_BOILERPLATE_OPEN = "<fork-boilerplate>";
|
||||
/** What follows the boilerplate, right before the prompt of the Agent call. */
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { appendFile, mkdir, mkdtemp, rename, rm, writeFile } 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 { readSubagentMessagesOrFail, subagentHistory } from "../subagent-history.js";
|
||||
import { TranscriptCache } from "../transcript-cache.js";
|
||||
import { transcriptAssistant, transcriptUser, writeTranscript } from "./helpers.js";
|
||||
|
||||
describe("session read cursors", () => {
|
||||
const message = (messageId: string): SessionReadFrame => ({
|
||||
@@ -74,4 +84,183 @@ 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 });
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("transcript cache of session reads", () => {
|
||||
it.each(["open", "close"] as const)(
|
||||
"drops the parsed transcripts of a session on %s, and all of them on dispose",
|
||||
async (kind) => {
|
||||
const forget = vi.spyOn(TranscriptCache.prototype, "forgetSession");
|
||||
const clear = vi.spyOn(TranscriptCache.prototype, "clear");
|
||||
try {
|
||||
const reads = new SessionReads();
|
||||
expect(await reads.transition("session-1", kind, async () => "done")).toBe("done");
|
||||
expect(forget).toHaveBeenCalledWith("session-1");
|
||||
reads.dispose();
|
||||
expect(clear).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
forget.mockRestore();
|
||||
clear.mockRestore();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("reads what a read without the cache reads after each change of the files", async () => {
|
||||
const sessionId = randomUUID();
|
||||
const dir = await mkdtemp(path.join(tmpdir(), "claude-acp-read-cache-"));
|
||||
const project = path.join(dir, "projects", "-project");
|
||||
const children = path.join(project, sessionId, "subagents");
|
||||
const child = path.join(children, "agent-child.jsonl");
|
||||
vi.stubEnv("CLAUDE_CONFIG_DIR", dir);
|
||||
try {
|
||||
const root: Record<string, unknown>[] = [
|
||||
{ cwd: dir, ...transcriptUser("u1", "Explore it") },
|
||||
{
|
||||
cwd: dir,
|
||||
type: "assistant",
|
||||
uuid: "launch",
|
||||
message: {
|
||||
id: "msg_launch",
|
||||
role: "assistant",
|
||||
model: "claude-opus-5",
|
||||
content: [
|
||||
{
|
||||
type: "tool_use",
|
||||
id: "toolu_agent",
|
||||
name: "Agent",
|
||||
input: { prompt: "Look around", description: "Explore" },
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
];
|
||||
const childLine = (uuid: string, parentUuid: string | null, text: string) =>
|
||||
JSON.stringify({
|
||||
...(parentUuid === null ? transcriptUser(uuid, text) : transcriptAssistant(uuid, text)),
|
||||
parentUuid,
|
||||
sessionId,
|
||||
cwd: dir,
|
||||
isSidechain: true,
|
||||
agentId: "child",
|
||||
timestamp: "2026-10-11T00:00:00.000Z",
|
||||
}) + "\n";
|
||||
await mkdir(children, { recursive: true });
|
||||
await writeFile(
|
||||
path.join(children, "agent-child.meta.json"),
|
||||
JSON.stringify({ agentType: "Explore", toolUseId: "toolu_agent" }),
|
||||
);
|
||||
await writeTranscript(project, sessionId, root);
|
||||
await writeFile(child, childLine("c1", null, "Look around"));
|
||||
const transcript = path.join(project, `${sessionId}.jsonl`);
|
||||
|
||||
const cache = new TranscriptCache({ files: 8, bytes: 1024 * 1024 });
|
||||
const compare = async () => {
|
||||
expect(await readSessionTranscript(sessionId, undefined, true, cache)).toEqual(
|
||||
await readSessionTranscript(sessionId, undefined, true),
|
||||
);
|
||||
const history = await subagentHistory(sessionId, { strict: true, transcript });
|
||||
const cached = await readSubagentMessagesOrFail(
|
||||
sessionId,
|
||||
"child",
|
||||
history,
|
||||
"toolu_agent",
|
||||
cache,
|
||||
);
|
||||
expect(cached).toEqual(
|
||||
await readSubagentMessagesOrFail(sessionId, "child", history, "toolu_agent"),
|
||||
);
|
||||
expect(cached.length).toBeGreaterThan(0);
|
||||
};
|
||||
const changes: (() => Promise<unknown>)[] = [
|
||||
async () => {},
|
||||
// Appends to the root and to the subagent.
|
||||
() => writeTranscript(project, sessionId, [...root, transcriptUser("u2", "Go on")]),
|
||||
() => appendFile(child, childLine("c2", "c1", "Found one")),
|
||||
// A line that the writer has not ended yet, then its end.
|
||||
() => appendFile(child, childLine("c3", "c2", "Found two").slice(0, 40)),
|
||||
() => appendFile(child, childLine("c3", "c2", "Found two").slice(40)),
|
||||
// A new file with other records, as after a rewrite of the transcript.
|
||||
() => writeTranscript(project, sessionId, [...root, transcriptUser("u3", "Other")]),
|
||||
async () => {
|
||||
await writeFile(
|
||||
`${child}.new`,
|
||||
childLine("c1", null, "Look around") + childLine("d2", "c1", "Again"),
|
||||
);
|
||||
await rename(`${child}.new`, child);
|
||||
},
|
||||
// A shorter file.
|
||||
() => writeTranscript(project, sessionId, root),
|
||||
() => writeRewindPoint(sessionId, { resumeSessionAt: "u1", droppedPromptUuid: "u2" }),
|
||||
];
|
||||
for (const change of changes) {
|
||||
await change();
|
||||
await compare();
|
||||
// A second read of the same files.
|
||||
await compare();
|
||||
}
|
||||
} finally {
|
||||
vi.unstubAllEnvs();
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
199
src/tests/transcript-cache.test.ts
Normal file
199
src/tests/transcript-cache.test.ts
Normal file
@@ -0,0 +1,199 @@
|
||||
import { appendFile, mkdir, mkdtemp, open, rename, rm, writeFile } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { readTranscriptEntries } from "../resumed-session.js";
|
||||
import { TranscriptCache } from "../transcript-cache.js";
|
||||
|
||||
describe("TranscriptCache", () => {
|
||||
let directory: string;
|
||||
let file: string;
|
||||
const line = (uuid: string) => JSON.stringify({ type: "user", uuid }) + "\n";
|
||||
|
||||
beforeEach(async () => {
|
||||
directory = await mkdtemp(path.join(os.tmpdir(), "claude-acp-transcript-cache-"));
|
||||
file = path.join(directory, "session.jsonl");
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
vi.restoreAllMocks();
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const entries = () => new TranscriptCache({ files: 4, bytes: 1024 * 1024 });
|
||||
|
||||
it("gives the records of readTranscriptEntries, and reads a last line again until it ends", async () => {
|
||||
await writeFile(
|
||||
file,
|
||||
line("a") +
|
||||
"\n" +
|
||||
"not json\n" +
|
||||
JSON.stringify({ uuid: "no type" }) +
|
||||
"\n" +
|
||||
"null\n" +
|
||||
// `readline` also ends a line at a carriage return and at U+2028 and U+2029.
|
||||
'{"type":"user","uuid":"split","text":"one\u2028two"}\n' +
|
||||
'{"type":"user","uuid":"r1"}\r{"type":"user","uuid":"r2"}\r\n',
|
||||
);
|
||||
await appendFile(file, '{"type":"user","uuid":"b"');
|
||||
const cache = entries();
|
||||
expect((await cache.read(file)).entries).toEqual(await readTranscriptEntries(file));
|
||||
expect((await cache.read(file)).entries.map((entry) => entry.uuid)).toEqual(["a", "r1", "r2"]);
|
||||
await appendFile(file, "}\n");
|
||||
expect((await cache.read(file)).entries).toEqual(await readTranscriptEntries(file));
|
||||
|
||||
const handle = await open(file, "a+");
|
||||
try {
|
||||
const { size } = await handle.stat();
|
||||
await handle.appendFile(line("c"));
|
||||
// The read ends at the size of the open handle, as `readTranscriptEntriesOf` does.
|
||||
expect((await cache.read(file, { handle, size })).entries.map((e) => e.uuid)).toEqual([
|
||||
"a",
|
||||
"r1",
|
||||
"r2",
|
||||
"b",
|
||||
]);
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("parses only the appended lines of a grown file and keeps its version line", async () => {
|
||||
await writeFile(file, line("a") + line("b"));
|
||||
const cache = entries();
|
||||
const first = await cache.read(file);
|
||||
await appendFile(file, line("c"));
|
||||
const parse = vi.spyOn(JSON, "parse");
|
||||
const grown = await cache.read(file);
|
||||
expect(parse).toHaveBeenCalledTimes(1);
|
||||
parse.mockRestore();
|
||||
expect(grown.entries).toEqual(await readTranscriptEntries(file));
|
||||
expect(first.entries.map((e) => e.uuid)).toEqual(["a", "b"]);
|
||||
expect(grown.version).not.toBe(first.version);
|
||||
expect((await cache.read(file)).version).toBe(grown.version);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["is shorter", () => writeFile(file, line("a"))],
|
||||
["has other first bytes", () => writeFile(file, line("x") + line("b") + line("c"))],
|
||||
["has other bytes at the end of the read part", () => writeFile(file, line("a") + line("x"))],
|
||||
[
|
||||
"is another file",
|
||||
async () => {
|
||||
await writeFile(path.join(directory, "new.jsonl"), line("a") + line("b") + line("c"));
|
||||
await rename(path.join(directory, "new.jsonl"), file);
|
||||
},
|
||||
],
|
||||
])("parses the whole file again when it %s", async (_name, change) => {
|
||||
await writeFile(file, line("a") + line("b"));
|
||||
const cache = entries();
|
||||
const first = await cache.read(file);
|
||||
await change();
|
||||
const parse = vi.spyOn(JSON, "parse");
|
||||
const next = await cache.read(file);
|
||||
expect(parse.mock.calls.length).toBe(next.entries.length);
|
||||
expect(next.entries).toEqual(await readTranscriptEntries(file));
|
||||
expect(next.version.split(":")[0]).not.toBe(first.version.split(":")[0]);
|
||||
});
|
||||
|
||||
it("keeps a computed value for one version of the records", async () => {
|
||||
await writeFile(file, line("a"));
|
||||
const cache = entries();
|
||||
const compute = vi.fn(async () => "value");
|
||||
const { version } = await cache.read(file);
|
||||
await expect(
|
||||
cache.memo(file, version, "key", () => Promise.reject(new Error("no"))),
|
||||
).rejects.toThrow("no");
|
||||
expect(await cache.memo(file, version, "key", compute)).toBe("value");
|
||||
expect(await cache.memo(file, version, "key", compute)).toBe("value");
|
||||
expect(compute).toHaveBeenCalledTimes(1);
|
||||
await appendFile(file, line("b"));
|
||||
const grown = await cache.read(file);
|
||||
expect(await cache.memo(file, grown.version, "key", compute)).toBe("value");
|
||||
expect(compute).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("keeps the files of a recent read when a new file does not fit", async () => {
|
||||
const files = ["a", "b", "c"].map((name) => path.join(directory, `${name}.jsonl`));
|
||||
for (const each of files) await writeFile(each, line("x"));
|
||||
const now = vi.spyOn(Date, "now").mockReturnValue(0);
|
||||
const cache = new TranscriptCache({ files: 2, bytes: 1024 * 1024 });
|
||||
for (const each of files) await cache.read(each);
|
||||
const parse = vi.spyOn(JSON, "parse");
|
||||
for (const each of files) await cache.read(each);
|
||||
// `a` and `b` stay kept; `c` does not fit and is parsed again.
|
||||
expect(parse).toHaveBeenCalledTimes(1);
|
||||
now.mockReturnValue(120_000);
|
||||
parse.mockClear();
|
||||
await cache.read(files[2]!);
|
||||
await cache.read(files[2]!);
|
||||
// After a minute, `c` takes the place of `a`, read least recently.
|
||||
expect(parse).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("forgets the transcript and the subagent transcripts of a session", async () => {
|
||||
const sessionId = "11111111-1111-4111-8111-111111111111";
|
||||
const root = path.join(directory, `${sessionId}.jsonl`);
|
||||
const children = path.join(directory, sessionId, "subagents");
|
||||
const child = path.join(children, "agent-a1.jsonl");
|
||||
await mkdir(children, { recursive: true });
|
||||
await writeFile(root, line("a"));
|
||||
await writeFile(child, line("b"));
|
||||
await writeFile(file, line("c"));
|
||||
const cache = entries();
|
||||
for (const each of [root, child, file]) await cache.read(each);
|
||||
cache.forgetSession(sessionId);
|
||||
const parse = vi.spyOn(JSON, "parse");
|
||||
for (const each of [root, child, file]) await cache.read(each);
|
||||
// The two files of the session are parsed again; the other file is not.
|
||||
expect(parse).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("keeps nothing of a read that was in progress when the session was forgotten", async () => {
|
||||
const sessionId = "11111111-1111-4111-8111-111111111111";
|
||||
const root = path.join(directory, `${sessionId}.jsonl`);
|
||||
await writeFile(root, line("a"));
|
||||
const cache = entries();
|
||||
const read = cache.read(root);
|
||||
cache.forgetSession(sessionId);
|
||||
expect((await read).entries).toEqual([{ type: "user", uuid: "a" }]);
|
||||
const parse = vi.spyOn(JSON, "parse");
|
||||
await cache.read(root);
|
||||
expect(parse).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("drops a file that no read used for five minutes", async () => {
|
||||
vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] });
|
||||
try {
|
||||
await writeFile(file, line("a") + line("b"));
|
||||
const cache = entries();
|
||||
const kept = () => (Reflect.get(cache, "kept") as Map<string, unknown>).size;
|
||||
await cache.read(file);
|
||||
vi.advanceTimersByTime(4 * 60_000);
|
||||
const parse = vi.spyOn(JSON, "parse");
|
||||
await cache.read(file);
|
||||
expect(parse).not.toHaveBeenCalled();
|
||||
expect(kept()).toBe(1);
|
||||
vi.advanceTimersByTime(5 * 60_000);
|
||||
expect(kept()).toBe(0);
|
||||
await cache.read(file);
|
||||
expect(parse).toHaveBeenCalledTimes(2);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("gives the version of the bytes that it read", async () => {
|
||||
await writeFile(file, line("a"));
|
||||
const cache = entries();
|
||||
const handle = await open(file, "r");
|
||||
try {
|
||||
// The size of a stat before the file was cut.
|
||||
const read = await cache.read(file, { handle, size: 1024 });
|
||||
expect(read.entries).toEqual([{ type: "user", uuid: "a" }]);
|
||||
expect((await cache.read(file)).version).toBe(read.version);
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,9 @@
|
||||
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";
|
||||
import { getSessionMessages, query } from "@anthropic-ai/claude-agent-sdk";
|
||||
import { getSessionMessages, getSubagentMessages, query } from "@anthropic-ai/claude-agent-sdk";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
AIR_ASYNC_TASKS_CAPABILITY,
|
||||
@@ -15,6 +15,7 @@ import type { AcpClient } from "../../acp-client.js";
|
||||
import { AuthStatusReporter } from "../../auth-status-reporter.js";
|
||||
import { writeCustomTitleSidecar } from "../../session-index/service.js";
|
||||
import { writeRewindPoint } from "../../session-rewind.js";
|
||||
import { TranscriptCache } from "../../transcript-cache.js";
|
||||
import { ClaudeAcpAgent, v1AgentApp } from "../../v1/acp-agent.js";
|
||||
import {
|
||||
initializeClient,
|
||||
@@ -25,7 +26,12 @@ import {
|
||||
|
||||
vi.mock("@anthropic-ai/claude-agent-sdk", async (load) => {
|
||||
const sdk = await load<typeof import("@anthropic-ai/claude-agent-sdk")>();
|
||||
return { ...sdk, query: vi.fn(), getSessionMessages: vi.fn(sdk.getSessionMessages) };
|
||||
return {
|
||||
...sdk,
|
||||
query: vi.fn(),
|
||||
getSessionMessages: vi.fn(sdk.getSessionMessages),
|
||||
getSubagentMessages: vi.fn(sdk.getSubagentMessages),
|
||||
};
|
||||
});
|
||||
|
||||
const logger = { log() {}, error() {} };
|
||||
@@ -132,6 +138,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 +178,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 +204,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 +221,101 @@ describe("_session/read on v1", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("finds an append that arrives after the confirmation transcript was read", async () => {
|
||||
await store(history);
|
||||
const read = TranscriptCache.prototype.read;
|
||||
vi.spyOn(TranscriptCache.prototype, "read")
|
||||
.mockImplementationOnce(read)
|
||||
.mockImplementationOnce(async function (this: TranscriptCache, ...args) {
|
||||
const snapshot = await read.apply(this, args);
|
||||
await store([...history, transcriptUser("u2", "Second question")]);
|
||||
return snapshot;
|
||||
});
|
||||
|
||||
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;
|
||||
const transcriptReads = vi.spyOn(TranscriptCache.prototype, "read");
|
||||
expect(
|
||||
await agent.readSession({ sessionId, replayFrom: { type: "cursor", cursorId } }),
|
||||
).toEqual({ cursorId });
|
||||
expect(updates).toEqual([]);
|
||||
expect(transcriptReads).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 +526,120 @@ describe("_session/read on v1", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it("reuses the parse of each unchanged transcript and reads what a new connection reads", async () => {
|
||||
const children = ["a1111111111111111", "a2222222222222222"];
|
||||
const launch = (index: number) => ({
|
||||
...transcriptAssistant(`launch${index}`, ""),
|
||||
message: {
|
||||
role: "assistant",
|
||||
model: "claude-opus-5",
|
||||
id: `msg_launch${index}`,
|
||||
content: [
|
||||
{
|
||||
type: "tool_use",
|
||||
id: `toolu_launch${index}`,
|
||||
name: "Agent",
|
||||
input: { prompt: `Check part ${index}`, description: `Part ${index}` },
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
const root = [...history, launch(0), launch(1)];
|
||||
await store(root);
|
||||
const directory = path.join(project, sessionId, "subagents");
|
||||
await mkdir(directory, { recursive: true });
|
||||
const childRecords = children.map((childId, index) => [
|
||||
transcriptUser(`c${index}u1`, `Check part ${index}`),
|
||||
transcriptAssistant(`c${index}a1`, `Part ${index} is fine`),
|
||||
]);
|
||||
const writeChild = async (index: number) => {
|
||||
const childId = children[index]!;
|
||||
await writeFile(
|
||||
path.join(directory, `agent-${childId}.meta.json`),
|
||||
JSON.stringify({ toolUseId: `toolu_launch${index}`, description: `Part ${index}` }),
|
||||
);
|
||||
await writeTranscript(
|
||||
directory,
|
||||
`agent-${childId}`,
|
||||
childRecords[index]!.map((record) => ({
|
||||
sessionId,
|
||||
cwd,
|
||||
agentId: childId,
|
||||
isSidechain: true,
|
||||
...record,
|
||||
})),
|
||||
);
|
||||
};
|
||||
await writeChild(0);
|
||||
await writeChild(1);
|
||||
const capabilities = {
|
||||
session: { cursors: {} },
|
||||
_meta: {
|
||||
jetbrains: { air: { version: 1, capabilities: [AIR_NATIVE_SUBAGENT_SESSIONS_CAPABILITY] } },
|
||||
},
|
||||
};
|
||||
const childReads = () =>
|
||||
vi.mocked(getSubagentMessages).mock.calls.map(([, agentId]) => agentId);
|
||||
const poll = async (cursorId: string | undefined) => {
|
||||
vi.mocked(getSessionMessages).mockClear();
|
||||
vi.mocked(getSubagentMessages).mockClear();
|
||||
updates.length = 0;
|
||||
return (await agent.readSession({ sessionId, replayFrom: { type: "cursor", cursorId } }))
|
||||
.cursorId;
|
||||
};
|
||||
const { agent, updates } = captureUpdates();
|
||||
try {
|
||||
await initializeClient(agent, capabilities);
|
||||
let cursorId = (await agent.readSession({ sessionId, replayFrom: start })).cursorId;
|
||||
expect(childReads().sort()).toEqual(children);
|
||||
|
||||
// The Agent calls rule out the saved checkpoint, so the poll replays the kept messages.
|
||||
expect(await poll(cursorId)).toBe(cursorId);
|
||||
expect(updates).toEqual([]);
|
||||
expect(getSessionMessages).not.toHaveBeenCalled();
|
||||
expect(childReads()).toEqual([]);
|
||||
|
||||
await store([...root, transcriptUser("u2", "Keep going")]);
|
||||
cursorId = await poll(cursorId);
|
||||
expect(updates).toContainEqual(
|
||||
expect.objectContaining({
|
||||
sessionId,
|
||||
update: expect.objectContaining({ content: { type: "text", text: "Keep going" } }),
|
||||
}),
|
||||
);
|
||||
// The check replay of the new cursor reads the same bytes: one SDK read.
|
||||
expect(getSessionMessages).toHaveBeenCalledTimes(1);
|
||||
expect(childReads()).toEqual([]);
|
||||
|
||||
childRecords[1]!.push(transcriptAssistant("c1a2", "Part 1 has one more note"));
|
||||
await writeChild(1);
|
||||
cursorId = await poll(cursorId);
|
||||
expect(updates).toContainEqual(
|
||||
expect.objectContaining({
|
||||
update: expect.objectContaining({
|
||||
content: { type: "text", text: "Part 1 has one more note" },
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(getSessionMessages).not.toHaveBeenCalled();
|
||||
expect(childReads()).toEqual([children[1]]);
|
||||
|
||||
updates.length = 0;
|
||||
const warm = await agent.readSession({ sessionId, replayFrom: start });
|
||||
const warmUpdates = [...updates];
|
||||
const cold = captureUpdates();
|
||||
try {
|
||||
await initializeClient(cold.agent, capabilities);
|
||||
expect(await cold.agent.readSession({ sessionId, replayFrom: start })).toEqual(warm);
|
||||
expect(cold.updates).toEqual(warmUpdates);
|
||||
} finally {
|
||||
await cold.agent.dispose();
|
||||
}
|
||||
} 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")>(
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
forkSession,
|
||||
getSessionInfo,
|
||||
getSessionMessages,
|
||||
getSubagentMessages,
|
||||
type McpHttpServerConfig,
|
||||
type Options,
|
||||
type SDKUserMessage,
|
||||
@@ -191,6 +192,7 @@ vi.mock("@anthropic-ai/claude-agent-sdk", async () => {
|
||||
},
|
||||
]),
|
||||
getSessionMessages: vi.fn(async () => []),
|
||||
getSubagentMessages: vi.fn(actual.getSubagentMessages),
|
||||
getSessionInfo: vi.fn(async () => undefined),
|
||||
forkSession: vi.fn(async () => ({ sessionId: "99999999-8888-4777-8666-555555555555" })),
|
||||
deleteSession: vi.fn(async () => {}),
|
||||
@@ -1261,6 +1263,88 @@ describe("ACP v2 sessions", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("reads again only the transcripts that changed since the last read", async () => {
|
||||
const sessionId = randomUUID();
|
||||
const childId = "abc123";
|
||||
const prompt = randomUUID();
|
||||
const launch = randomUUID();
|
||||
const childPrompt = randomUUID();
|
||||
const root = [
|
||||
transcriptRecord(sessionId, prompt, null, { role: "user", content: "Explore it" }),
|
||||
transcriptRecord(sessionId, launch, prompt, {
|
||||
id: "msg_launch",
|
||||
role: "assistant",
|
||||
content: [
|
||||
{
|
||||
type: "tool_use",
|
||||
id: "toolu_agent",
|
||||
name: "Agent",
|
||||
input: { prompt: "Look around", description: "Explore" },
|
||||
},
|
||||
],
|
||||
}),
|
||||
];
|
||||
const child = [
|
||||
transcriptRecord(sessionId, childPrompt, null, { role: "user", content: "Look around" }),
|
||||
];
|
||||
const meta = { agentType: "Explore", toolUseId: "toolu_agent" };
|
||||
await writeSubagentHistory(sessionId, root, childId, meta, child);
|
||||
const client = v2Client();
|
||||
await client.app.connectWith(connectRouter(), async (agent) => {
|
||||
await initializeV2(agent);
|
||||
const poll = async (cursorId: string) => {
|
||||
vi.mocked(getSessionMessages).mockClear();
|
||||
vi.mocked(getSubagentMessages).mockClear();
|
||||
client.sessionUpdates.length = 0;
|
||||
return (await read(agent, sessionId, { type: "cursor", cursorId })).cursorId!;
|
||||
};
|
||||
let cursorId = (await read(agent, sessionId, { type: "start" })).cursorId!;
|
||||
|
||||
expect(await poll(cursorId)).toBe(cursorId);
|
||||
expect(getSessionMessages).not.toHaveBeenCalled();
|
||||
expect(getSubagentMessages).not.toHaveBeenCalled();
|
||||
|
||||
root.push(
|
||||
transcriptRecord(sessionId, randomUUID(), launch, { role: "user", content: "Go on" }),
|
||||
);
|
||||
await writeSubagentHistory(sessionId, root, childId, meta, child);
|
||||
cursorId = await poll(cursorId);
|
||||
expect(getSessionMessages).toHaveBeenCalledTimes(1);
|
||||
expect(getSubagentMessages).not.toHaveBeenCalled();
|
||||
|
||||
child.push(
|
||||
transcriptRecord(sessionId, randomUUID(), childPrompt, {
|
||||
id: "msg_child",
|
||||
role: "assistant",
|
||||
content: text("Found it"),
|
||||
}),
|
||||
);
|
||||
await writeSubagentHistory(sessionId, root, childId, meta, child);
|
||||
await poll(cursorId);
|
||||
expect(client.sessionUpdates).toContainEqual({
|
||||
sessionId: childId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
messageId: "msg_child",
|
||||
content: text("Found it")[0],
|
||||
},
|
||||
});
|
||||
expect(getSessionMessages).not.toHaveBeenCalled();
|
||||
expect(getSubagentMessages).toHaveBeenCalledTimes(1);
|
||||
|
||||
// A read from the start equals the read of a new connection.
|
||||
client.sessionUpdates.length = 0;
|
||||
const warm = await read(agent, sessionId, { type: "start" });
|
||||
const warmUpdates = [...client.sessionUpdates];
|
||||
const cold = v2Client();
|
||||
await cold.app.connectWith(connectRouter(), async (coldAgent) => {
|
||||
await initializeV2(coldAgent);
|
||||
expect(await read(coldAgent, sessionId, { type: "start" })).toEqual(warm);
|
||||
expect(cold.sessionUpdates).toEqual(warmUpdates);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
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 +1375,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();
|
||||
|
||||
327
src/transcript-cache.ts
Normal file
327
src/transcript-cache.ts
Normal file
@@ -0,0 +1,327 @@
|
||||
import type { SessionStoreEntry } from "@anthropic-ai/claude-agent-sdk";
|
||||
import { open, type FileHandle } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
|
||||
/** The length of each of the two windows that tell whether the read part of a file is still the same. */
|
||||
const WINDOW_BYTES = 4096;
|
||||
|
||||
/** How long after its last read a kept file is safe from a drop for a new file. */
|
||||
const RECENT_MS = 60_000;
|
||||
|
||||
/** How long after its last read a kept file stays kept. */
|
||||
const IDLE_MS = 5 * 60_000;
|
||||
|
||||
/** The size of one read of the new bytes of a file. */
|
||||
const READ_CHUNK_BYTES = 8 * 1024 * 1024;
|
||||
|
||||
/** The records of a transcript up to a captured size, and a version of these records. */
|
||||
export type TranscriptSnapshot = {
|
||||
entries: SessionStoreEntry[];
|
||||
/**
|
||||
* Equal for two reads of one file only when both read the same bytes: the
|
||||
* same number of bytes, and no whole parse of the file between them.
|
||||
*/
|
||||
version: string;
|
||||
};
|
||||
|
||||
/** The parsed lines of one transcript file, up to the end of its last full line. */
|
||||
type KeptFile = {
|
||||
dev: bigint;
|
||||
ino: bigint;
|
||||
/** The byte after the last line feed that the parse read. */
|
||||
offset: number;
|
||||
/** The first bytes of the file, up to {@link WINDOW_BYTES}. */
|
||||
head: Buffer;
|
||||
/** The bytes before `offset`, up to {@link WINDOW_BYTES}. */
|
||||
tail: Buffer;
|
||||
/** Each record of the file before `offset`, in file order. */
|
||||
entries: SessionStoreEntry[];
|
||||
/** The number of the whole parse that these entries continue. */
|
||||
generation: number;
|
||||
/** The values that {@link TranscriptCache.memo} computed from one version of the records. */
|
||||
derived: Map<string, { version: string; value: unknown }>;
|
||||
/** The time of the last read, in epoch ms. */
|
||||
readAt: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* The records of transcript files, parsed one time and kept: a next read of
|
||||
* a grown file parses only the bytes after the last full line that it read.
|
||||
*
|
||||
* A read gives the records that `readTranscriptEntriesOf` gives for the same
|
||||
* bytes: each line that parses as JSON and has a string `type`, in file
|
||||
* order, with the line ends of `readline`. A last line with no line feed (a
|
||||
* writer is in the middle of it) is in the result only when it parses, and
|
||||
* the next read reads it again.
|
||||
*
|
||||
* A read parses the whole file again when the file has another device or
|
||||
* inode, is shorter than the read part, or has other bytes in the first or
|
||||
* the last {@link WINDOW_BYTES} of the read part. A change of other bytes
|
||||
* inside the read part that keeps the length, the start and the end of the
|
||||
* read part is not seen: Claude Code appends to a transcript or writes it
|
||||
* again whole.
|
||||
*
|
||||
* It keeps `files` files and `bytes` bytes of lines at most. To keep a new
|
||||
* file, it drops the files read least recently first, but only the files
|
||||
* that no read used in the last {@link RECENT_MS}. When the new file still
|
||||
* does not fit, it is not kept, and the next read parses it whole. So a
|
||||
* client that polls a session bigger than the limit keeps the same part of
|
||||
* it from poll to poll. A file that no read used in the last
|
||||
* {@link IDLE_MS} is dropped.
|
||||
*/
|
||||
export class TranscriptCache {
|
||||
private readonly kept = new Map<string, KeptFile>();
|
||||
/** The read in progress of each file, so that two reads of one file do not parse into one list. */
|
||||
private readonly reads = new Map<string, { done: Promise<unknown> }>();
|
||||
/**
|
||||
* For each file with a read in progress, how many times {@link forgetSession}
|
||||
* dropped it. A read keeps its result only when the count did not change.
|
||||
*/
|
||||
private readonly forgets = new Map<string, number>();
|
||||
private parses = 0;
|
||||
private sweep: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
constructor(private readonly limits: { files: number; bytes: number }) {}
|
||||
|
||||
/**
|
||||
* The records of `file`, up to the size of `opened` when it is given, else
|
||||
* up to the size of the file at the read. Throws when the file cannot be
|
||||
* read; the error has the `path` of the file.
|
||||
*/
|
||||
async read(
|
||||
file: string,
|
||||
opened?: { handle: FileHandle; size: number },
|
||||
): Promise<TranscriptSnapshot> {
|
||||
const before = this.reads.get(file);
|
||||
const forgets = this.forgets.get(file) ?? 0;
|
||||
const read = (async () => {
|
||||
await before?.done.catch(() => {});
|
||||
return opened
|
||||
? this.refresh(file, opened.handle, opened.size, forgets)
|
||||
: this.openAndRefresh(file, forgets);
|
||||
})();
|
||||
// The entry, not the promise, tells whether a later read replaced this one.
|
||||
const entry = { done: read };
|
||||
this.reads.set(file, entry);
|
||||
try {
|
||||
return await read;
|
||||
} catch (error) {
|
||||
const code = (error as { code?: unknown } | null)?.code;
|
||||
throw Object.assign(new Error(`Could not read ${file}`, { cause: error }), {
|
||||
path: file,
|
||||
...(code !== undefined && { code }),
|
||||
});
|
||||
} finally {
|
||||
if (this.reads.get(file) === entry) {
|
||||
this.reads.delete(file);
|
||||
this.forgets.delete(file);
|
||||
}
|
||||
this.scheduleSweep();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The value of `compute` for the records of `file` at `version`. It keeps
|
||||
* one value per `key` while the file is kept, and computes it again when
|
||||
* the version changed. A failed `compute` keeps nothing.
|
||||
*/
|
||||
async memo<T>(file: string, version: string, key: string, compute: () => Promise<T>): Promise<T> {
|
||||
const saved = this.kept.get(file)?.derived.get(key);
|
||||
if (saved?.version === version) return saved.value as T;
|
||||
const value = await compute();
|
||||
this.kept.get(file)?.derived.set(key, { version, value });
|
||||
return value;
|
||||
}
|
||||
|
||||
/** Drops the kept records of the session `sessionId`: its transcript and its subagent transcripts. */
|
||||
forgetSession(sessionId: string): void {
|
||||
const children = `${path.sep}${sessionId}${path.sep}subagents${path.sep}`;
|
||||
const ofSession = (file: string) =>
|
||||
path.basename(file) === `${sessionId}.jsonl` || file.includes(children);
|
||||
for (const file of [...this.kept.keys()]) {
|
||||
if (ofSession(file)) this.kept.delete(file);
|
||||
}
|
||||
for (const file of this.reads.keys()) {
|
||||
if (ofSession(file)) this.forgets.set(file, (this.forgets.get(file) ?? 0) + 1);
|
||||
}
|
||||
}
|
||||
|
||||
/** Drops every kept file. */
|
||||
clear(): void {
|
||||
this.kept.clear();
|
||||
clearTimeout(this.sweep);
|
||||
this.sweep = undefined;
|
||||
}
|
||||
|
||||
/** Drops the files that no read used in the last {@link IDLE_MS}. */
|
||||
private dropIdle(): void {
|
||||
const now = Date.now();
|
||||
// The map is in read order.
|
||||
for (const [file, kept] of this.kept) {
|
||||
if (now - kept.readAt < IDLE_MS) break;
|
||||
this.kept.delete(file);
|
||||
}
|
||||
}
|
||||
|
||||
/** Drops the idle files after {@link IDLE_MS}, also when no read comes. */
|
||||
private scheduleSweep(): void {
|
||||
clearTimeout(this.sweep);
|
||||
if (this.kept.size === 0) return;
|
||||
// The timer holds the cache weakly, so a closed connection frees its files.
|
||||
const cache = new WeakRef(this);
|
||||
this.sweep = setTimeout(() => cache.deref()?.sweepNow(), IDLE_MS);
|
||||
this.sweep.unref();
|
||||
}
|
||||
|
||||
private sweepNow(): void {
|
||||
this.sweep = undefined;
|
||||
this.dropIdle();
|
||||
this.scheduleSweep();
|
||||
}
|
||||
|
||||
private async openAndRefresh(file: string, forgets: number): Promise<TranscriptSnapshot> {
|
||||
const handle = await open(file, "r");
|
||||
try {
|
||||
return await this.refresh(file, handle, (await handle.stat()).size, forgets);
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
}
|
||||
|
||||
private async refresh(
|
||||
file: string,
|
||||
handle: FileHandle,
|
||||
size: number,
|
||||
forgets: number,
|
||||
): Promise<TranscriptSnapshot> {
|
||||
this.dropIdle();
|
||||
const { dev, ino } = await handle.stat({ bigint: true });
|
||||
let kept = this.kept.get(file);
|
||||
this.kept.delete(file);
|
||||
if (kept && !(await continues(handle, kept, dev, ino, size))) kept = undefined;
|
||||
const generation = kept?.generation ?? ++this.parses;
|
||||
const entries = kept?.entries ?? [];
|
||||
const parsed = await parseFrom(handle, kept?.offset ?? 0, size, entries);
|
||||
const result = {
|
||||
// A copy: the next read of the file appends to the kept list.
|
||||
entries: parsed.last === undefined ? entries.slice() : [...entries, ...parsed.last],
|
||||
version: `${generation}:${parsed.end}`,
|
||||
};
|
||||
// A forgetSession during this read dropped the file: keep nothing.
|
||||
if ((this.forgets.get(file) ?? 0) !== forgets) return result;
|
||||
this.keep(file, {
|
||||
dev,
|
||||
ino,
|
||||
offset: parsed.offset,
|
||||
head: await bytesAt(handle, 0, Math.min(parsed.offset, WINDOW_BYTES)),
|
||||
tail: await bytesAt(
|
||||
handle,
|
||||
Math.max(0, parsed.offset - WINDOW_BYTES),
|
||||
Math.min(parsed.offset, WINDOW_BYTES),
|
||||
),
|
||||
entries,
|
||||
generation,
|
||||
derived: kept?.derived ?? new Map(),
|
||||
readAt: Date.now(),
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
private keep(file: string, next: KeptFile): void {
|
||||
if (next.offset > this.limits.bytes) return;
|
||||
let bytes = next.offset;
|
||||
for (const value of this.kept.values()) bytes += value.offset;
|
||||
const fits = () => this.kept.size < this.limits.files && bytes <= this.limits.bytes;
|
||||
// The map is in read order. A read of a session reads all its files, so
|
||||
// dropping the files of a recent read would drop the files that the next
|
||||
// poll reads first, and no file would stay kept.
|
||||
for (const [oldFile, old] of this.kept) {
|
||||
if (fits() || next.readAt - old.readAt < RECENT_MS) break;
|
||||
this.kept.delete(oldFile);
|
||||
bytes -= old.offset;
|
||||
}
|
||||
if (fits()) this.kept.set(file, next);
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the file of `handle` is the file of `kept` with bytes appended or none. */
|
||||
async function continues(
|
||||
handle: FileHandle,
|
||||
kept: KeptFile,
|
||||
dev: bigint,
|
||||
ino: bigint,
|
||||
size: number,
|
||||
): Promise<boolean> {
|
||||
if (dev !== kept.dev || ino !== kept.ino || size < kept.offset) return false;
|
||||
const head = await bytesAt(handle, 0, kept.head.length);
|
||||
if (!head.equals(kept.head)) return false;
|
||||
const tail = await bytesAt(handle, kept.offset - kept.tail.length, kept.tail.length);
|
||||
return tail.equals(kept.tail);
|
||||
}
|
||||
|
||||
async function bytesAt(handle: FileHandle, position: number, length: number): Promise<Buffer> {
|
||||
const buffer = Buffer.alloc(length);
|
||||
let read = 0;
|
||||
while (read < length) {
|
||||
const { bytesRead } = await handle.read(buffer, read, length - read, position + read);
|
||||
if (bytesRead === 0) break;
|
||||
read += bytesRead;
|
||||
}
|
||||
return read === length ? buffer : buffer.subarray(0, read);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the lines of the file from `start` to `size` into `entries`. Gives
|
||||
* the byte after the last line feed, the byte after the last byte read, and
|
||||
* the parsed last line when it has no line feed.
|
||||
*/
|
||||
async function parseFrom(
|
||||
handle: FileHandle,
|
||||
start: number,
|
||||
size: number,
|
||||
entries: SessionStoreEntry[],
|
||||
): Promise<{ offset: number; end: number; last?: SessionStoreEntry[] }> {
|
||||
let offset = start;
|
||||
let carry: Buffer | undefined;
|
||||
let position = start;
|
||||
while (position < size) {
|
||||
const chunk = await bytesAt(handle, position, Math.min(READ_CHUNK_BYTES, size - position));
|
||||
if (chunk.length === 0) break;
|
||||
position += chunk.length;
|
||||
const bytes = carry ? Buffer.concat([carry, chunk]) : chunk;
|
||||
let lineStart = 0;
|
||||
for (let end = bytes.indexOf(0x0a); end >= 0; end = bytes.indexOf(0x0a, lineStart)) {
|
||||
parseLines(bytes, lineStart, end, entries);
|
||||
lineStart = end + 1;
|
||||
}
|
||||
offset += lineStart;
|
||||
carry = lineStart < bytes.length ? bytes.subarray(lineStart) : undefined;
|
||||
}
|
||||
const last: SessionStoreEntry[] = [];
|
||||
if (carry) parseLines(carry, 0, carry.length, last);
|
||||
return { offset, end: position, ...(last.length > 0 ? { last } : {}) };
|
||||
}
|
||||
|
||||
/**
|
||||
* The line ends of `readline`, other than a line feed. `readTranscriptEntriesOf`
|
||||
* reads with `readline`, so a record with one of these characters in a string
|
||||
* is split there and does not parse.
|
||||
*/
|
||||
const OTHER_LINE_ENDS = /\r|\u2028|\u2029/;
|
||||
|
||||
/**
|
||||
* Adds to `entries` each record of the bytes from `start` to `end`, which
|
||||
* have no line feed: each part between the other line ends that parses as
|
||||
* JSON and has a string `type`.
|
||||
*/
|
||||
function parseLines(bytes: Buffer, start: number, end: number, entries: SessionStoreEntry[]): void {
|
||||
const text = bytes.toString("utf8", start, end);
|
||||
for (const line of OTHER_LINE_ENDS.test(text) ? text.split(OTHER_LINE_ENDS) : [text]) {
|
||||
try {
|
||||
const record = JSON.parse(line);
|
||||
if (record && typeof record.type === "string") entries.push(record);
|
||||
} catch {
|
||||
// Claude's transcript reader skips lines that do not parse.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8599,7 +8599,7 @@ export class ClaudeAcpAgent {
|
||||
: subagentHistory(sessionId);
|
||||
const readChildMessages = (agentId: string, history: SubagentHistory, launchId: string) =>
|
||||
detached
|
||||
? readSubagentMessagesOrFail(sessionId, agentId, history, launchId)
|
||||
? readSubagentMessagesOrFail(sessionId, agentId, history, launchId, detached.cache)
|
||||
: readSubagentMessages(sessionId, agentId, history, this.logger);
|
||||
|
||||
// Registers the Agent and Task launches of `list`, and the terminal state
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { SessionMessage } from "@anthropic-ai/claude-agent-sdk";
|
||||
import type { AcpClient } from "../acp-client.js";
|
||||
import type { AcpSessionNotification } from "../acp-subagents.js";
|
||||
import { readSessionTranscript, SessionReads, type SessionReadFrame } from "../session-read.js";
|
||||
import type { TranscriptCache } from "../transcript-cache.js";
|
||||
import { ChangedMetaFilter } from "./tool-calls/changed-meta-filter.js";
|
||||
|
||||
/** A render whose updates are held until the read cursor is validated. */
|
||||
@@ -12,6 +13,8 @@ export type DetachedReplay = {
|
||||
publish: AcpClient["sessionUpdate"];
|
||||
endHistory: () => void;
|
||||
signal: AbortSignal;
|
||||
/** The parsed transcripts of the connection's reads (see `SessionReads`). */
|
||||
cache?: TranscriptCache;
|
||||
};
|
||||
|
||||
export class V1SessionReads {
|
||||
@@ -22,6 +25,7 @@ export class V1SessionReads {
|
||||
|
||||
dispose(): void {
|
||||
this.closed.abort();
|
||||
this.reads.dispose();
|
||||
}
|
||||
|
||||
readonly transition = this.reads.transition.bind(this.reads);
|
||||
@@ -46,16 +50,17 @@ 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, cache) => {
|
||||
const transcript = await readSessionTranscript(sessionId, cwd, observeStorage, cache);
|
||||
signal.throwIfAborted();
|
||||
const frames: SessionReadFrame[] = [];
|
||||
let historyEnd: number | undefined;
|
||||
const filter = options.airClient ? new ChangedMetaFilter() : undefined;
|
||||
await options.render(sessionId, transcript.cwd, {
|
||||
...transcript,
|
||||
cache,
|
||||
signal,
|
||||
endHistory: () => {
|
||||
historyEnd = frames.length;
|
||||
@@ -79,6 +84,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, cache) =>
|
||||
renderSessionRead(sessionId, cwd, this.logger, capabilities, observeStorage, cache),
|
||||
send: (frame) =>
|
||||
this.ctx.notify(v2.methods.client.session.update, frame as v2.UpdateSessionNotification),
|
||||
});
|
||||
@@ -957,6 +958,7 @@ class V2Agent implements AgentHandle, SessionConnection {
|
||||
this.stopped.clear();
|
||||
this.promptKeys.clear();
|
||||
await Promise.all(sessions.map((session) => session.close()));
|
||||
this.sessionReads.dispose();
|
||||
}
|
||||
|
||||
// --- Session setup -----------------------------------------------------------
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type * as v2 from "@agentclientprotocol/sdk/experimental/v2/unstable";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { readSessionTranscript, type SessionReadFrame } from "../session-read.js";
|
||||
import type { TranscriptCache } from "../transcript-cache.js";
|
||||
import { replayEndUpdate } from "./setup.js";
|
||||
import { SessionOutput } from "./stream.js";
|
||||
import { replaySessionHistory, SubagentReplay } from "./subagent-replay.js";
|
||||
@@ -12,8 +13,15 @@ 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,
|
||||
cache?: TranscriptCache,
|
||||
) {
|
||||
const { messages, cwd, transcript, title, storage } = await readSessionTranscript(
|
||||
sessionId,
|
||||
dir,
|
||||
observeStorage,
|
||||
cache,
|
||||
);
|
||||
const frames: SessionReadFrame[] = [];
|
||||
const translator = new V2UpdateTranslator();
|
||||
const send = (notification: v2.UpdateSessionNotification): void => {
|
||||
@@ -30,7 +38,7 @@ export async function renderSessionRead(
|
||||
const subagents = await SubagentReplay.load(
|
||||
{ sessionId, cwd, logger, translator, send },
|
||||
messages,
|
||||
{ transcript },
|
||||
{ transcript, cache },
|
||||
);
|
||||
let historyEnd = 0;
|
||||
replaySessionHistory(send, output, messages, subagents, {
|
||||
@@ -42,5 +50,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 };
|
||||
}
|
||||
|
||||
@@ -75,6 +75,7 @@ import {
|
||||
type ReplayChild as SharedReplayChild,
|
||||
} from "../subagent-replay.js";
|
||||
import { taskNotificationsOf } from "../task-notifications.js";
|
||||
import type { TranscriptCache } from "../transcript-cache.js";
|
||||
import type { V2UpdateTranslator } from "./update-translator.js";
|
||||
import { REPLAY_COMPLETE } from "./setup.js";
|
||||
import { SessionOutput, type ReplayHooks } from "./stream.js";
|
||||
@@ -150,7 +151,8 @@ export class SubagentReplay {
|
||||
{
|
||||
live = NO_LIVE_CHILDREN,
|
||||
transcript: transcriptPath,
|
||||
}: { live?: LiveChildren; transcript?: string } = {},
|
||||
cache,
|
||||
}: { live?: LiveChildren; transcript?: string; cache?: TranscriptCache } = {},
|
||||
): Promise<SubagentReplay | undefined> {
|
||||
if (!messages.some((message) => launchIdsOf(message).length > 0)) return undefined;
|
||||
const history = await subagentHistory(
|
||||
@@ -166,7 +168,7 @@ export class SubagentReplay {
|
||||
const transcript = (
|
||||
await (transcriptPath === undefined
|
||||
? readSubagentMessages(host.sessionId, record.agentId, history, host.logger)
|
||||
: readSubagentMessagesOrFail(host.sessionId, record.agentId, history, launchId))
|
||||
: readSubagentMessagesOrFail(host.sessionId, record.agentId, history, launchId, cache))
|
||||
).map((message) => ({ ...message, parent_tool_use_id: null }));
|
||||
transcripts.set(record.agentId, transcript);
|
||||
queue.push(...transcript.flatMap(launchIdsOf));
|
||||
|
||||
Reference in New Issue
Block a user