mirror of
https://github.com/agentclientprotocol/claude-agent-acp.git
synced 2026-12-04 23:22:01 +00:00
Compare commits
4 Commits
main
...
air/sessio
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bede1dfd0b | ||
|
|
04aa04c084 | ||
|
|
3c74fa65a7 | ||
|
|
34801673a5 |
@@ -10,11 +10,11 @@ Check `_meta.sessionRead.supported` in the initialize response. On v1 declare `c
|
||||
|
||||
Omitting `replayFrom` or setting it to `null` requests a full replay and returns `{}`. A v1 client without cursor support gets the same result from `start`. The optional absolute `cwd` overrides the working directory recorded in the root transcript for replay.
|
||||
|
||||
A missing transcript returns `-32002`. A session already open, opening, closing or being read on the same connection returns `-32600` with reason `session_already_open`. An unreadable history file returns `-32603` with reason `history_read_failed`. A read can also return a retryable error if the writer changes the history between the root and child scans.
|
||||
A missing transcript returns `-32002`. A session already open, opening, closing or being read on the same connection returns `-32600` with reason `session_already_open`. An unreadable history file returns `-32603` with reason `history_read_failed`. A read can also return a retryable error if the writer changes the history in each of four renders of one read.
|
||||
|
||||
## Polling cost and scope
|
||||
|
||||
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. Most tools, MCP tools included, render from their stored input and result, so their sessions keep this quiet path. Agent and Task calls render from the subagent transcripts, and ExitPlanMode from whether its plan file still exists, so a default read of a session with one of them takes the full replay path. A [status read](#status-read) checks the subagent files instead. For a Skill call, an AIR client gets a link to its `SKILL.md`, so for such a client the reader also checks that file in the working directory and the home folder. 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.
|
||||
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. Most tools, MCP tools included, render from their stored input and result, so their sessions keep this quiet path. Agent and Task calls render from the subagent transcripts, and ExitPlanMode from whether its plan file still exists, so a default read of a session with one of them takes the full replay path. A [status read](#status-read) checks the subagent files instead. For a Skill call, an AIR client gets a link to its `SKILL.md`, so for such a client the reader also checks that file in the working directory and the home folder. 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 before delivery. When the read inputs did not change after the render, the render is delivered. When the root only grew past the bytes that the render read, and those bytes are unchanged, the render is delivered too, and the next read renders the rest. Otherwise a second render must equal the first. When it does not, the read checks the second render in the same way, up to four renders. 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 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.
|
||||
|
||||
@@ -93,7 +93,7 @@ V1 has no custom update variants, so on v1 the update is a `session_info_update`
|
||||
- `state` uses the vocabulary of the lifecycle updates. On v1 AIR clients it is a string: `running`, `idle`, `completed`, `failed`, `cancelled` or `disconnected`. Otherwise it is a `subagent_update` state: `{"state":"running"}`, `{"state":"idle"}`, or `{"state":"idle","stopReason":"end_turn" | "cancelled" | "error"}`. The end comes from the last task notification of the child, then from a stop by the user, then from the result of a foreground launch. A background launch's result is no end. A launch whose parent cannot be restored, or a launch with neither a metadata file nor an end, is `disconnected` on v1 AIR clients. Without an end, a child is `idle` when the last user or assistant record of its transcript ends the turn, else `running`. An answer ends the turn with any stop reason except `tool_use` and `pause_turn`, such as `end_turn`, `max_tokens` or `refusal`. So do a record that no model wrote (model `<synthetic>`, such as an API error) and the successful result of a `SubagentHandback` call. `model` is the model of the last record that a model wrote. On the RFD form and v2 a full read reports such a child `idle` too. Past 4 MB without a whole record, a child is `running` with no `model` or `updatedAt`.
|
||||
- `background`, `agentType` and `cwd` come from the metadata file. `model`, `updatedAt` (the `timestamp` of the last record) and `size` (bytes) come from the transcript. A child without a transcript yet has no `size`.
|
||||
|
||||
A child that continues after its end, such as one resumed by `SendMessage`, keeps its end in `state`, and its `size` and `updatedAt` grow. Compare `size` with the previous status to see new work. Because the cursor covers no end state and no title, a child that ends, a stop by the user and a title change keep the cursor valid. The next cursor read returns only new records and the current status. A cached status cursor also covers sessions with Agent and Task calls: it checks the metadata of every child and the file version of each child transcript. When only the transcripts of children that launched no children changed, the read does not render the history again: it reads the ends of those transcripts and sends the same cursor with the new status. A change to the transcript of a child that launched children renders the history again, because the launches in it are on that child's stream. A child transcript that is not a regular file, such as a symbolic link, gives no cached cursor.
|
||||
A child that continues after its end, such as one resumed by `SendMessage`, keeps its end in `state`, and its `size` and `updatedAt` grow. Compare `size` with the previous status to see new work. Because the cursor covers no end state and no title, a child that ends, a stop by the user and a title change keep the cursor valid. The next cursor read returns only new records and the current status. A cached status cursor also covers sessions with Agent and Task calls: it checks the metadata of every child and the file version of each child transcript. When only the transcripts of children that launched no children changed, the read does not render the history again: it reads the ends of those transcripts and sends the same cursor with the new status. The same holds for the transcript of a child that launched children while the lines that name its launches do not change: the launch calls, their results and the task notifications. When they change, the read renders the history again, because the launches are on that child's stream. A child transcript that is not a regular file, such as a symbolic link, gives no cached cursor.
|
||||
|
||||
Limits:
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import { RequestError } from "@agentclientprotocol/sdk/unstable";
|
||||
import { getSessionMessages, type SessionStoreEntry } from "@anthropic-ai/claude-agent-sdk";
|
||||
import { createHash } from "node:crypto";
|
||||
import type { BigIntStats } from "node:fs";
|
||||
import { lstat, open, readFile } from "node:fs/promises";
|
||||
import { type FileHandle, lstat, open, readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { z } from "zod";
|
||||
import packageJson from "../package.json" with { type: "json" };
|
||||
@@ -23,7 +23,7 @@ import { sanitizeTitle } from "./session-titles.js";
|
||||
import { activeSessionMessages, readRewindPoint } from "./session-rewind.js";
|
||||
import { withReplyBranches } from "./transcript-branches.js";
|
||||
import { isNativeSubagentControlTool } from "./native-subagents.js";
|
||||
import { resolveSkillPath } from "./tool-calls/reporters/interaction.js";
|
||||
import { resolveSkillPath, type SkillScanCache } from "./tool-calls/reporters/interaction.js";
|
||||
import {
|
||||
isMissing,
|
||||
subagentHistory,
|
||||
@@ -114,8 +114,56 @@ export type SessionReadStorage = {
|
||||
sidecarTitle?: string | null;
|
||||
/** The SKILL.md of each skill of the root's Skill calls (see {@link skillPaths}). */
|
||||
skills?: { cwd: string; paths: [name: string, path: string | null][] };
|
||||
/** The bytes of the root that the replay read: their count and {@link prefixDigest}. */
|
||||
read?: { size: number; digest: string };
|
||||
};
|
||||
|
||||
/** The bytes that {@link prefixDigest} reads at a time. */
|
||||
const DIGEST_CHUNK = 4 * 1024 * 1024;
|
||||
|
||||
/** The digest of the first `size` bytes of the open file. */
|
||||
async function prefixDigest(handle: FileHandle, size: number): Promise<string> {
|
||||
const hash = createHash("sha256");
|
||||
const buffer = Buffer.alloc(Math.min(size, DIGEST_CHUNK));
|
||||
let position = 0;
|
||||
while (position < size) {
|
||||
const length = Math.min(buffer.length, size - position);
|
||||
const { bytesRead } = await handle.read(buffer, 0, length, position);
|
||||
if (bytesRead === 0) break;
|
||||
hash.update(buffer.subarray(0, bytesRead));
|
||||
position += bytesRead;
|
||||
}
|
||||
return hash.digest("base64url");
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the root `transcript` is still the file of `version` and only grew:
|
||||
* it has more bytes than `read` names, and the first of them are unchanged.
|
||||
* A writer that appends to the root does this. Any other change of the file,
|
||||
* in place too, fails the check.
|
||||
*/
|
||||
async function rootGrew(
|
||||
transcript: string,
|
||||
version: string,
|
||||
read: SessionReadStorage["read"],
|
||||
): Promise<boolean> {
|
||||
if (!read) return false;
|
||||
const handle = await open(transcript, "r");
|
||||
try {
|
||||
const stats = await handle.stat({ bigint: true });
|
||||
const [dev, ino] = version.split(":");
|
||||
return (
|
||||
stats.isFile() &&
|
||||
String(stats.dev) === dev &&
|
||||
String(stats.ino) === ino &&
|
||||
Number(stats.size) > read.size &&
|
||||
(await prefixDigest(handle, read.size)) === read.digest
|
||||
);
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
}
|
||||
|
||||
function fileVersion(stats: BigIntStats): string {
|
||||
const { dev, ino, mode, size, mtimeNs, ctimeNs } = stats;
|
||||
return [dev, ino, mode, size, mtimeNs, ctimeNs].join(":");
|
||||
@@ -158,24 +206,41 @@ function subagentRecords(history: SubagentHistory): string {
|
||||
return json([...history.agents].sort(([a], [b]) => a.localeCompare(b)));
|
||||
}
|
||||
|
||||
/** What changed of the inputs that a replay read (see {@link storageChanges}). */
|
||||
type StorageChanges = {
|
||||
/** The subagent transcripts of `files` that changed, with their current versions. */
|
||||
files: [path: string, version: string | null][];
|
||||
/** Whether the root only grew past the bytes that the replay read. */
|
||||
grew: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Checks the transcript's metadata and the sidecar inputs read by the
|
||||
* replay. Returns the subagent transcripts in `storage.files` that changed,
|
||||
* with their current versions: empty when nothing changed, undefined when
|
||||
* another input changed or a file is not a regular file.
|
||||
* replay. Undefined when an input other than the subagent transcripts of
|
||||
* `files` changed, or a file is not a regular file. With `growth`, a root
|
||||
* that only grew past the bytes that the replay read is no such change.
|
||||
*/
|
||||
async function storageChanges(
|
||||
sessionId: string,
|
||||
storage: SessionReadStorage,
|
||||
): Promise<[path: string, version: string | null][] | undefined> {
|
||||
growth = false,
|
||||
): Promise<StorageChanges | undefined> {
|
||||
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 undefined;
|
||||
const transcriptChanges = async () => {
|
||||
let grew = false;
|
||||
const transcriptChanges = async (last: boolean) => {
|
||||
if (storage.version !== undefined) {
|
||||
const root = await lstat(transcript, { bigint: true });
|
||||
if (!root.isFile() || fileVersion(root) !== storage.version) return undefined;
|
||||
if (!root.isFile()) return undefined;
|
||||
if (fileVersion(root) !== storage.version) {
|
||||
// The digest of the read bytes only in the last check, which decides.
|
||||
if (!growth || !storage.read || Number(root.size) <= storage.read.size) return undefined;
|
||||
if (last && !(await rootGrew(transcript, storage.version, storage.read)))
|
||||
return undefined;
|
||||
grew = true;
|
||||
}
|
||||
}
|
||||
const changed: [string, string | null][] = [];
|
||||
for (const [file, version] of storage.files ?? []) {
|
||||
@@ -185,7 +250,7 @@ async function storageChanges(
|
||||
}
|
||||
return changed;
|
||||
};
|
||||
if (!(await transcriptChanges())) return undefined;
|
||||
if (!(await transcriptChanges(false))) return undefined;
|
||||
if (
|
||||
storage.subagents !== undefined &&
|
||||
subagentRecords(await subagentHistory(sessionId, { strict: true, transcript })) !==
|
||||
@@ -208,7 +273,9 @@ async function storageChanges(
|
||||
)
|
||||
return undefined;
|
||||
// The versions of this second check: the caller reads the changed files after them.
|
||||
return await transcriptChanges();
|
||||
grew = false;
|
||||
const files = await transcriptChanges(true);
|
||||
return files && { files, grew };
|
||||
} catch {
|
||||
// An uncertain probe leaves validation and errors to the ordinary replay.
|
||||
return undefined;
|
||||
@@ -280,7 +347,9 @@ function skillNames(messages: readonly { message?: unknown }[]): string[] {
|
||||
* resolves it again.
|
||||
*/
|
||||
function skillPaths(names: string[], cwd: string): [string, string | null][] {
|
||||
return names.map((name) => [name, resolveSkillPath(name, cwd) ?? null]);
|
||||
// One listing of each skill folder for all names of this pass.
|
||||
const scans: SkillScanCache = new Map();
|
||||
return names.map((name) => [name, resolveSkillPath(name, cwd, scans) ?? null]);
|
||||
}
|
||||
|
||||
function contentOf(message: { message?: unknown }): unknown {
|
||||
@@ -426,11 +495,14 @@ export async function readSessionTranscript(
|
||||
let headTail: HeadTail;
|
||||
let records: SessionStoreEntry[];
|
||||
let version: string | undefined;
|
||||
let bytes: SessionReadStorage["read"];
|
||||
try {
|
||||
const stat = await handle.stat({ bigint: true });
|
||||
if (observeStorage) version = fileVersion(stat);
|
||||
const size = Number(stat.size);
|
||||
headTail = await readHeadTailOf(handle, size);
|
||||
// Before the entries: their read closes the handle.
|
||||
if (observeStorage) bytes = { size, digest: await prefixDigest(handle, size) };
|
||||
records = await readTranscriptEntriesOf(transcript, handle, size);
|
||||
} finally {
|
||||
await handle.close();
|
||||
@@ -507,6 +579,7 @@ export async function readSessionTranscript(
|
||||
? {
|
||||
transcript,
|
||||
version,
|
||||
read: bytes,
|
||||
sidecarTitle,
|
||||
...(files && history ? { files, subagents: subagentRecords(history) } : {}),
|
||||
...(skills.length > 0
|
||||
@@ -700,6 +773,14 @@ type Checkpoint = {
|
||||
stream?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The checks of a new cursor in one read. A check that renders again and
|
||||
* differs starts the next check with that render. So a read renders at most
|
||||
* once more than this, and a writer that changes the history in each render
|
||||
* fails it.
|
||||
*/
|
||||
const READ_ATTEMPTS = 3;
|
||||
|
||||
/** A read owns only a replay on this connection. Closing it invalidates the pending delivery. */
|
||||
export class SessionReads {
|
||||
/** Reads by root session, or by root, child and mode for the other scopes. */
|
||||
@@ -899,15 +980,15 @@ export class SessionReads {
|
||||
? await storageChanges(sessionId, cached.storage)
|
||||
: undefined;
|
||||
if (cached && changes && cached.processCwd === currentDirectory()) {
|
||||
if (changes.length === 0) {
|
||||
if (changes.files.length === 0) {
|
||||
return await deliver(cached.boundaries, cached.cursorId, cached.title, cached.status);
|
||||
}
|
||||
// Only child transcripts changed. When the render does not depend on
|
||||
// them, only the status changes, and it is outside the cursor.
|
||||
const status = await cached.status?.afterAppend(changes.map(([file]) => file));
|
||||
const status = await cached.status?.afterAppend(changes.files.map(([file]) => file));
|
||||
if (status) {
|
||||
const result = await deliver(cached.boundaries, cached.cursorId, cached.title, status);
|
||||
const versions = new Map(changes);
|
||||
const versions = new Map(changes.files);
|
||||
this.checkpoints.set(key, {
|
||||
...cached,
|
||||
storage: {
|
||||
@@ -924,79 +1005,94 @@ export class SessionReads {
|
||||
}
|
||||
check();
|
||||
if (useCursor) this.checkpoints.delete(key);
|
||||
const view = await replay();
|
||||
const { frames, cwd: effectiveCwd, historyEnd, title, storage, stream } = view;
|
||||
let current = view.status;
|
||||
const streamId = stream ?? sessionId;
|
||||
check();
|
||||
if (!useCursor) return await deliver(frames, undefined, title, current);
|
||||
const scope = scopeFor(effectiveCwd, stream);
|
||||
const { outgoing, cursorId, anchor } = snapshot(
|
||||
frames,
|
||||
streamId,
|
||||
options.protocol,
|
||||
scope,
|
||||
tag,
|
||||
cursor,
|
||||
historyEnd,
|
||||
stream !== undefined,
|
||||
);
|
||||
let verifiedStorage = storage;
|
||||
const isStreamBoundary = (frame: SessionReadFrame) =>
|
||||
frame.sessionId === streamId && 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();
|
||||
let view = await replay();
|
||||
for (let attempt = 1; ; attempt++) {
|
||||
const { frames, cwd: effectiveCwd, historyEnd, title, storage, stream } = view;
|
||||
let current = view.status;
|
||||
const streamId = stream ?? sessionId;
|
||||
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.",
|
||||
);
|
||||
}
|
||||
// The later status, which a child's append can change without changing the frames.
|
||||
current = again.status;
|
||||
if (json(again.storage ?? null) !== json(storage ?? null)) {
|
||||
verifiedStorage = undefined;
|
||||
}
|
||||
const end = outgoing.findIndex(isStreamBoundary);
|
||||
outgoing.splice(end < 0 ? outgoing.length : end, 0, {
|
||||
sessionId: streamId,
|
||||
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, current);
|
||||
check();
|
||||
if (cursorId && verifiedStorage && processCwd && processCwd === currentDirectory()) {
|
||||
this.checkpoints.set(key, {
|
||||
root: sessionId,
|
||||
...(stream !== undefined ? { stream } : {}),
|
||||
cursorId,
|
||||
if (!useCursor) return await deliver(frames, undefined, title, current);
|
||||
const scope = scopeFor(effectiveCwd, stream);
|
||||
const { outgoing, cursorId, anchor } = snapshot(
|
||||
frames,
|
||||
streamId,
|
||||
options.protocol,
|
||||
scope,
|
||||
requestedCwd: cwd,
|
||||
cwd: effectiveCwd,
|
||||
processCwd,
|
||||
storage: verifiedStorage,
|
||||
boundaries: frames.filter(isStreamBoundary),
|
||||
title,
|
||||
...(current ? { status: current } : {}),
|
||||
});
|
||||
if (this.checkpoints.size > 32) {
|
||||
this.checkpoints.delete(this.checkpoints.keys().next().value!);
|
||||
tag,
|
||||
cursor,
|
||||
historyEnd,
|
||||
stream !== undefined,
|
||||
);
|
||||
let verifiedStorage = storage;
|
||||
const isStreamBoundary = (frame: SessionReadFrame) =>
|
||||
frame.sessionId === streamId && frame.update.sessionUpdate === "replay_complete";
|
||||
if (cursorId && cursorId !== cursor) {
|
||||
// A terminal can append or rewind between the reads of the root and a child.
|
||||
// Inputs that did not change after the render read them give the same render again.
|
||||
const changes = storage ? await storageChanges(sessionId, storage, true) : undefined;
|
||||
check();
|
||||
if (changes?.files.length === 0 && changes.grew) {
|
||||
// The render holds the bytes of the root that it read. The next read renders the rest.
|
||||
verifiedStorage = undefined;
|
||||
} else if (changes?.files.length !== 0) {
|
||||
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]))
|
||||
) {
|
||||
// The later render is the first one of the next attempt.
|
||||
if (attempt < READ_ATTEMPTS) {
|
||||
view = again;
|
||||
continue;
|
||||
}
|
||||
throw RequestError.internalError(
|
||||
{ sessionId, retryable: true },
|
||||
"History changed during the read. Retry with the last successful cursor.",
|
||||
);
|
||||
}
|
||||
// The later status, which a child's append can change without changing the frames.
|
||||
current = again.status;
|
||||
if (json(again.storage ?? null) !== json(storage ?? null)) {
|
||||
verifiedStorage = undefined;
|
||||
}
|
||||
}
|
||||
const end = outgoing.findIndex(isStreamBoundary);
|
||||
outgoing.splice(end < 0 ? outgoing.length : end, 0, {
|
||||
sessionId: streamId,
|
||||
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, current);
|
||||
check();
|
||||
if (cursorId && verifiedStorage && processCwd && processCwd === currentDirectory()) {
|
||||
this.checkpoints.set(key, {
|
||||
root: sessionId,
|
||||
...(stream !== undefined ? { stream } : {}),
|
||||
cursorId,
|
||||
scope,
|
||||
requestedCwd: cwd,
|
||||
cwd: effectiveCwd,
|
||||
processCwd,
|
||||
storage: verifiedStorage,
|
||||
boundaries: frames.filter(isStreamBoundary),
|
||||
title,
|
||||
...(current ? { status: current } : {}),
|
||||
});
|
||||
if (this.checkpoints.size > 32) {
|
||||
this.checkpoints.delete(this.checkpoints.keys().next().value!);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
return result;
|
||||
} finally {
|
||||
this.active.delete(key);
|
||||
}
|
||||
|
||||
@@ -92,33 +92,29 @@ export class SubagentStatus {
|
||||
private readonly nested = new Map<string, NestedLaunches>();
|
||||
private reported: SubagentStatusEntry[] = [];
|
||||
private readonly sources = new WeakMap<SubagentStatusEntry, EntrySource>();
|
||||
/** The agent ids that a metadata file names as `parentAgentId`. */
|
||||
private readonly launchers: Set<string>;
|
||||
/** The launches of each agent id that a metadata file names as `parentAgentId`. */
|
||||
private readonly launchers = new Map<string, string[]>();
|
||||
|
||||
private constructor(readonly history: SubagentHistory) {
|
||||
this.launchers = new Set(
|
||||
[...history.agents.values()].flatMap((record) => record.parentAgentId ?? []),
|
||||
);
|
||||
for (const [launchId, record] of history.agents) {
|
||||
if (!record.parentAgentId) continue;
|
||||
this.launchers.set(record.parentAgentId, [
|
||||
...(this.launchers.get(record.parentAgentId) ?? []),
|
||||
launchId,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/** Reads the transcript ends of the children of `history`, and the launches of nested children. */
|
||||
static async read(history: SubagentHistory): Promise<SubagentStatus> {
|
||||
const status = new SubagentStatus(history);
|
||||
const launchers = new Map<string, string[]>();
|
||||
for (const [launchId, record] of history.agents) {
|
||||
if (!record.parentAgentId) continue;
|
||||
launchers.set(record.parentAgentId, [
|
||||
...(launchers.get(record.parentAgentId) ?? []),
|
||||
launchId,
|
||||
]);
|
||||
}
|
||||
await Promise.all([
|
||||
...[...history.agents.values()].map(async ({ agentId }) => {
|
||||
const file = status.file(agentId);
|
||||
const tail = file ? await readTail(file) : undefined;
|
||||
if (tail) status.tails.set(agentId, tail);
|
||||
}),
|
||||
...[...launchers].map(async ([agentId, launchIds]) => {
|
||||
...[...status.launchers].map(async ([agentId, launchIds]) => {
|
||||
const file = status.file(agentId);
|
||||
if (file) status.nested.set(agentId, await readLaunches(file, launchIds, history));
|
||||
}),
|
||||
@@ -198,12 +194,12 @@ export class SubagentStatus {
|
||||
* The status after appends to the child transcripts `files`, which it
|
||||
* reads the ends of again, with the entries of the same replay. Undefined
|
||||
* when one of them is not the transcript of a child of `history`, or is
|
||||
* the transcript of a child that launched children: the replay renders
|
||||
* the launches in it, so it must render again.
|
||||
* the transcript of a child that launched children whose launches changed
|
||||
* (see {@link launches}): the replay renders them, so it must render again.
|
||||
*
|
||||
* The replay depends on the other inputs only: the root transcript, the
|
||||
* metadata files and the transcripts of the children that launched
|
||||
* children. The caller checks that they are unchanged. The entries then
|
||||
* metadata files and the launches of the children that launched children.
|
||||
* The caller checks that the first two are unchanged. The entries then
|
||||
* equal those of a new replay.
|
||||
*/
|
||||
async afterAppend(files: string[]): Promise<SubagentStatus | undefined> {
|
||||
@@ -216,13 +212,21 @@ export class SubagentStatus {
|
||||
const changed = files.map((file) => agents.get(file));
|
||||
const sources = this.reported.map((entry) => this.sources.get(entry));
|
||||
if (
|
||||
changed.some((agentId) => agentId === undefined || this.launchers.has(agentId)) ||
|
||||
changed.some((agentId) => agentId === undefined) ||
|
||||
sources.some((source) => source === undefined)
|
||||
)
|
||||
return undefined;
|
||||
const status = new SubagentStatus(this.history);
|
||||
for (const [agentId, tail] of this.tails) status.tails.set(agentId, tail);
|
||||
for (const [agentId, launches] of this.nested) status.nested.set(agentId, launches);
|
||||
// The scan continues from the bytes that the replay's scan read (see `readLaunches`).
|
||||
for (const agentId of changed as string[]) {
|
||||
const launchIds = this.launchers.get(agentId);
|
||||
if (!launchIds) continue;
|
||||
const launches = await readLaunches(this.file(agentId)!, launchIds, this.history);
|
||||
if (JSON.stringify(launches) !== JSON.stringify(this.nested.get(agentId) ?? NO_LAUNCHES))
|
||||
return undefined;
|
||||
}
|
||||
await Promise.all(
|
||||
(changed as string[]).map(async (agentId) => {
|
||||
const tail = await readTail(this.file(agentId)!);
|
||||
|
||||
@@ -559,10 +559,15 @@ class StatusSession {
|
||||
});
|
||||
}
|
||||
|
||||
answer(agentId: string, text = "Report") {
|
||||
answer(agentId: string | undefined, text = "Report") {
|
||||
return this.assistant(agentId, [{ type: "text", text }], "end_turn");
|
||||
}
|
||||
|
||||
/** The transcript of the child `agentId`, or of the root when undefined. */
|
||||
transcript(agentId?: string): string {
|
||||
return this.fileOf(agentId);
|
||||
}
|
||||
|
||||
/** Launches the child `name` from `owner` (the root when undefined): metadata, prompt, work. */
|
||||
async agent(
|
||||
name: string,
|
||||
@@ -1017,6 +1022,47 @@ describe.each(["air", "rfd", "v2"] as const)("status _session/read (%s)", (form)
|
||||
}
|
||||
});
|
||||
|
||||
it("rebuilds only the status after an append to a child that launched children, while its launches stay", async () => {
|
||||
const r = await reader(form);
|
||||
try {
|
||||
const first = await r.read({ sessionId, replayFrom: start, ...status });
|
||||
const cursorId = first.response.cursorId!;
|
||||
const owner = session.agentIdOf("outer")!;
|
||||
const sizeOf = (frames: SessionReadFrame[]) =>
|
||||
statusOf(frames).find((entry) => entry.sessionId === idOf("outer"))!.size as number;
|
||||
const poll = () => r.read({ sessionId, replayFrom: { type: "cursor", cursorId }, ...status });
|
||||
// Work of the parent that holds no launch, no launch result and no task notification.
|
||||
await session.bash(owner);
|
||||
vi.mocked(getSessionMessages).mockClear();
|
||||
const next = await poll();
|
||||
expect(getSessionMessages).not.toHaveBeenCalled();
|
||||
expect(next.response).toEqual({ cursorId });
|
||||
expect(sizeOf(next.frames)).toBeGreaterThan(sizeOf(first.frames));
|
||||
const fresh = await r.read({ sessionId, replayFrom: start, ...status });
|
||||
expect(statusOf(next.frames)).toEqual(statusOf(fresh.frames));
|
||||
expect(fresh.response).toEqual({ cursorId });
|
||||
// A nested child ends in its parent's transcript: the root render shows the launch result.
|
||||
await session.answer(session.agentIdOf("nestedrun")!);
|
||||
await session.result(owner, session.launchOf("nestedrun"), "Report");
|
||||
vi.mocked(getSessionMessages).mockClear();
|
||||
const answer = (read: Read) =>
|
||||
read({ sessionId, replayFrom: { type: "cursor", cursorId }, ...status }).catch(
|
||||
(error: { data?: { reason?: string } }) => error.data?.reason,
|
||||
);
|
||||
const ended = await answer(r.read);
|
||||
expect(getSessionMessages).toHaveBeenCalled();
|
||||
// The answer of a reader without a checkpoint.
|
||||
const other = await reader(form);
|
||||
try {
|
||||
expect(ended).toEqual(await answer(other.read));
|
||||
} finally {
|
||||
await other.dispose();
|
||||
}
|
||||
} finally {
|
||||
await r.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("renders again after an append to a child that launched children, and finds its new launch", async () => {
|
||||
const r = await reader(form);
|
||||
try {
|
||||
@@ -1128,6 +1174,108 @@ describe.each(["air", "rfd", "v2"] as const)("status _session/read (%s)", (form)
|
||||
}
|
||||
});
|
||||
|
||||
/** Runs `during` once, in the next read of the root transcript, after the read. */
|
||||
function duringRootRead(during: () => Promise<void>) {
|
||||
const read = resumedSession.readTranscriptEntriesOf;
|
||||
return vi
|
||||
.spyOn(resumedSession, "readTranscriptEntriesOf")
|
||||
.mockImplementationOnce(async (...args) => {
|
||||
const records = await read(...args);
|
||||
await during();
|
||||
return records;
|
||||
});
|
||||
}
|
||||
|
||||
it("sends the history that it read when the root grows during the read", async () => {
|
||||
const r = await reader(form);
|
||||
try {
|
||||
const first = await r.read({ sessionId, replayFrom: start, ...status });
|
||||
await session.bash(undefined);
|
||||
// The terminal appends while the reader reads the root.
|
||||
const entries = duringRootRead(() => session.answer(undefined, "Written during the read"));
|
||||
const during = await r.read({
|
||||
sessionId,
|
||||
replayFrom: { type: "cursor", cursorId: first.response.cursorId },
|
||||
...status,
|
||||
});
|
||||
// One render: the root only grew after it.
|
||||
expect(entries).toHaveBeenCalledTimes(1);
|
||||
entries.mockRestore();
|
||||
const texts = (frames: SessionReadFrame[]) => JSON.stringify(frames);
|
||||
expect(during.response.cursorId).not.toBe(first.response.cursorId);
|
||||
expect(texts(during.frames)).toContain("toolu_bash");
|
||||
expect(texts(during.frames)).not.toContain("Written during the read");
|
||||
// The next poll sends the rest.
|
||||
const next = await r.read({
|
||||
sessionId,
|
||||
replayFrom: { type: "cursor", cursorId: during.response.cursorId },
|
||||
...status,
|
||||
});
|
||||
expect(texts(next.frames)).toContain("Written during the read");
|
||||
expect(texts(next.frames)).not.toContain("toolu_bash");
|
||||
} finally {
|
||||
await r.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("renders again when the history changes between the renders of a read", async () => {
|
||||
// ExitPlanMode keeps no storage, so the read checks its render with a second one.
|
||||
await session.assistant(undefined, [
|
||||
{ type: "tool_use", id: "toolu_plan", name: "ExitPlanMode", input: { plan: "Plan" } },
|
||||
]);
|
||||
const r = await reader(form);
|
||||
try {
|
||||
const first = await r.read({ sessionId, replayFrom: start, ...status });
|
||||
await session.bash(undefined);
|
||||
const entries = duringRootRead(() => session.answer(undefined, "Written during the read"));
|
||||
const params = {
|
||||
sessionId,
|
||||
replayFrom: { type: "cursor", cursorId: first.response.cursorId },
|
||||
...status,
|
||||
};
|
||||
const during = await r.read(params);
|
||||
// The first render, the second one that differs, and the third one that checks it.
|
||||
expect(entries).toHaveBeenCalledTimes(3);
|
||||
entries.mockRestore();
|
||||
expect(JSON.stringify(during.frames)).toContain("Written during the read");
|
||||
const fresh = await reader(form);
|
||||
try {
|
||||
expect(during).toEqual(await fresh.read(params));
|
||||
} finally {
|
||||
await fresh.dispose();
|
||||
}
|
||||
} finally {
|
||||
await r.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("does not take a root that changed in place and grew during the read as an append", async () => {
|
||||
await session.answer(undefined, "Original answer");
|
||||
const r = await reader(form);
|
||||
try {
|
||||
const first = await r.read({ sessionId, replayFrom: start, ...status });
|
||||
await session.bash(undefined);
|
||||
// A rewrite in place keeps the file and grows it, but changes the delivered history.
|
||||
const file = session.transcript();
|
||||
const entries = duringRootRead(async () => {
|
||||
const text = await readFile(file, "utf8");
|
||||
await writeFile(file, text.replace("Original answer", "Changed answer"));
|
||||
await session.answer(undefined, "Written during the read");
|
||||
});
|
||||
// The second render differs, and the retry with it finds the change of the delivered history.
|
||||
await expect(
|
||||
r.read({
|
||||
sessionId,
|
||||
replayFrom: { type: "cursor", cursorId: first.response.cursorId },
|
||||
...status,
|
||||
}),
|
||||
).rejects.toMatchObject(invalidCursor);
|
||||
expect(entries).toHaveBeenCalledTimes(2);
|
||||
} finally {
|
||||
await r.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("reports a child that handed back its report as the full read does, past long records", async () => {
|
||||
// A hand-back whose call is longer than the 64 KB window, and a child whose last record is.
|
||||
await session.agent("handback", undefined, { background: true, finish: false });
|
||||
|
||||
@@ -100,8 +100,19 @@ describe("session read cursors", () => {
|
||||
const reads = new SessionReads();
|
||||
const { cursorId } = await reads.read(start, options);
|
||||
options.send.mockClear();
|
||||
options.replay.mockResolvedValueOnce({ cwd: "/project", frames: [message("1"), message("2")] });
|
||||
// Each render differs from the one before, so each check of a render fails.
|
||||
const renders = (count: number) =>
|
||||
Array.from({ length: count }, (_, i) => message(String(i + 1)));
|
||||
for (const count of [2, 3, 4, 5]) {
|
||||
options.replay.mockResolvedValueOnce({ cwd: "/project", frames: renders(count) });
|
||||
}
|
||||
options.replay.mockClear();
|
||||
await expect(reads.read(poll(cursorId), options)).rejects.toMatchObject({ code: -32603 });
|
||||
expect(options.replay).toHaveBeenCalledTimes(4);
|
||||
// A check that differs is retried with the later render.
|
||||
options.replay.mockResolvedValueOnce({ cwd: "/project", frames: renders(2) });
|
||||
expect(await reads.read(poll(cursorId), options)).toEqual({ cursorId });
|
||||
expect(options.send).not.toHaveBeenCalled();
|
||||
options.replay.mockRejectedValueOnce(
|
||||
Object.assign(new Error("unreadable child"), { path: "/child" }),
|
||||
);
|
||||
|
||||
@@ -216,18 +216,30 @@ describe("_session/read on v1", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("finds an append that arrives after the confirmation transcript was read", async () => {
|
||||
it("renders a new cursor once when its inputs do not change after the render", async () => {
|
||||
await store(history);
|
||||
const { agent } = captureUpdates();
|
||||
try {
|
||||
await initializeClient(agent, { session: { cursors: {} } });
|
||||
vi.mocked(getSessionMessages).mockClear();
|
||||
const { cursorId } = await agent.readSession({ sessionId, replayFrom: start });
|
||||
expect(cursorId).toBeDefined();
|
||||
expect(vi.mocked(getSessionMessages)).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
await agent.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("finds an append that arrives after the 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;
|
||||
});
|
||||
vi.mocked(getSessionMessages).mockImplementationOnce(async (...args) => {
|
||||
const messages = await actual.getSessionMessages(...args);
|
||||
await store([...history, transcriptUser("u2", "Second question")]);
|
||||
return messages;
|
||||
});
|
||||
|
||||
const { agent, updates } = captureUpdates();
|
||||
try {
|
||||
|
||||
Reference in New Issue
Block a user