mirror of
https://github.com/agentclientprotocol/claude-agent-acp.git
synced 2026-12-04 15:11:51 +00:00
Compare commits
2 Commits
session-re
...
session-re
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8a97739cc4 | ||
|
|
13f2aa9fd6 |
@@ -14,7 +14,7 @@ A missing transcript returns `-32002`. A session already open, opening, closing
|
||||
|
||||
## 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. 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.
|
||||
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.
|
||||
|
||||
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. 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. 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.
|
||||
|
||||
Limits:
|
||||
|
||||
@@ -118,7 +118,7 @@ Send the root session and one child session id that the client got:
|
||||
|
||||
The response and the updates are those of a root read, restricted to the child's stream: every update has the child's session id, including the `cursor_update` and, on v2, the `replay_complete`. They are the updates of that stream in a default read. A child read sends no title. The child id can be the agent id, the agent id with a `:generation:<n>` suffix of a live child, or AIR's `<root>:replay-subagent:<launch id>`. All ids of one child share its stream and cursor.
|
||||
|
||||
The cursor belongs to that child: its scope includes the stream, so a root cursor, or another child's, returns `invalid_cursor`. A root cursor is refused before the render, another child's only after it, because the read must find the child's stream first. A rewritten child transcript, such as after a compaction, invalidates it too. The read renders only the transcripts of the child and its ancestors, and of the children it launched. A child that sends or gets a `SendMessage` renders every transcript, because the messages link both streams. A cached child cursor checks the child's transcript, the subagent metadata and the root's rewind file. It skips the render when they are unchanged, unless the child used a tool other than Bash, PowerShell, Read, Write, Edit, Glob, Grep or SubagentHandback.
|
||||
The cursor belongs to that child: its scope includes the stream, so a root cursor, or another child's, returns `invalid_cursor`. A root cursor is refused before the render, another child's only after it, because the read must find the child's stream first. A rewritten child transcript, such as after a compaction, invalidates it too. The read renders only the transcripts of the child and its ancestors, and of the children it launched. A child that sends or gets a `SendMessage` renders every transcript, because the messages link both streams. A cached child cursor checks the child's transcript, the subagent metadata and the root's rewind file. It skips the render when they are unchanged, unless the child made an Agent, Task, ExitPlanMode, SendMessage or Skill call.
|
||||
|
||||
A child that was just launched and has no transcript yet has no records on its stream: its read returns no cursor until the first record is written. Poll it from the start until then. Cached cursors of child reads and of root reads share one limit of 32 per connection; the oldest is dropped first, and its next read renders again.
|
||||
|
||||
|
||||
@@ -23,6 +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 {
|
||||
isMissing,
|
||||
subagentHistory,
|
||||
@@ -93,8 +94,8 @@ type ReadOptions = {
|
||||
historyEnd?: number;
|
||||
title?: string;
|
||||
storage?: SessionReadStorage;
|
||||
/** For a status read: the status update, which goes out outside the cursor. */
|
||||
status?: SessionReadFrame;
|
||||
/** For a status read: the status, whose update goes out outside the cursor. */
|
||||
status?: SubagentStatus;
|
||||
/** For a child read: the session id of the child's stream in `frames`. */
|
||||
stream?: string;
|
||||
}>;
|
||||
@@ -111,6 +112,8 @@ export type SessionReadStorage = {
|
||||
subagents?: string;
|
||||
/** Undefined when replay skipped the sidecar, null when it had no title. */
|
||||
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][] };
|
||||
};
|
||||
|
||||
function fileVersion(stats: BigIntStats): string {
|
||||
@@ -155,69 +158,131 @@ function subagentRecords(history: SubagentHistory): string {
|
||||
return json([...history.agents].sort(([a], [b]) => a.localeCompare(b)));
|
||||
}
|
||||
|
||||
/** Checks the transcript's metadata and the sidecar inputs read by the replay. */
|
||||
async function storageUnchanged(sessionId: string, storage: SessionReadStorage): Promise<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.
|
||||
*/
|
||||
async function storageChanges(
|
||||
sessionId: string,
|
||||
storage: SessionReadStorage,
|
||||
): Promise<[path: string, version: string | null][] | 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 false;
|
||||
const matchesTranscript = async () => {
|
||||
if (transcript !== storage.transcript) return undefined;
|
||||
const transcriptChanges = async () => {
|
||||
if (storage.version !== undefined) {
|
||||
const root = await lstat(transcript, { bigint: true });
|
||||
if (!root.isFile() || fileVersion(root) !== storage.version) return false;
|
||||
if (!root.isFile() || fileVersion(root) !== storage.version) return undefined;
|
||||
}
|
||||
const changed: [string, string | null][] = [];
|
||||
for (const [file, version] of storage.files ?? []) {
|
||||
const current = await fileVersionAt(file);
|
||||
if (current === undefined || current !== version) return false;
|
||||
if (current === undefined) return undefined;
|
||||
if (current !== version) changed.push([file, current]);
|
||||
}
|
||||
return true;
|
||||
return changed;
|
||||
};
|
||||
if (!(await matchesTranscript())) return false;
|
||||
if (!(await transcriptChanges())) return undefined;
|
||||
if (
|
||||
storage.subagents !== undefined &&
|
||||
subagentRecords(await subagentHistory(sessionId, { strict: true, transcript })) !==
|
||||
storage.subagents
|
||||
)
|
||||
return false;
|
||||
return undefined;
|
||||
if (storage.sidecarTitle !== undefined) {
|
||||
const title = await readSidecarTitle(transcript, { strict: true });
|
||||
if ((title ?? null) !== storage.sidecarTitle) return false;
|
||||
if ((title ?? null) !== storage.sidecarTitle) return undefined;
|
||||
}
|
||||
if (await readRewindPoint(sessionId, undefined, { transcript })) return false;
|
||||
return await matchesTranscript();
|
||||
if (await readRewindPoint(sessionId, undefined, { transcript })) return undefined;
|
||||
if (
|
||||
storage.skills &&
|
||||
json(
|
||||
skillPaths(
|
||||
storage.skills.paths.map(([name]) => name),
|
||||
storage.skills.cwd,
|
||||
),
|
||||
) !== json(storage.skills.paths)
|
||||
)
|
||||
return undefined;
|
||||
// The versions of this second check: the caller reads the changed files after them.
|
||||
return await transcriptChanges();
|
||||
} catch {
|
||||
// An uncertain probe leaves validation and errors to the ordinary replay.
|
||||
return false;
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** 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"]);
|
||||
|
||||
/** A child's hand-back renders from its own input and result too. */
|
||||
const CHILD_ONLY_TOOLS = new Set([...ROOT_ONLY_TOOLS, "SubagentHandback"]);
|
||||
/**
|
||||
* The tools whose render reads files besides the transcript and the inputs
|
||||
* that a checkpoint compares. Every other tool, MCP and unknown tools
|
||||
* included, renders from its stored input and result. A renderer that starts
|
||||
* to read a file for a tool must add the tool here.
|
||||
*
|
||||
* - Agent and Task: the subagent metadata and transcripts. A status read
|
||||
* compares them, so there they are no such tools.
|
||||
* - ExitPlanMode: whether the plan file exists, for AIR clients with `planFile`.
|
||||
*
|
||||
* Skill is not here: AIR's link to its SKILL.md depends on files in the
|
||||
* working directory and the home folder, and a root checkpoint of an AIR
|
||||
* client compares that link (see {@link skillPaths}). Other clients get no link.
|
||||
*/
|
||||
const ROOT_FILE_TOOLS = new Set(["Agent", "Task", "ExitPlanMode"]);
|
||||
|
||||
/**
|
||||
* Whether `content` has a tool call that renders from files that a
|
||||
* checkpoint does not observe. A status read observes the subagent files, so
|
||||
* an Agent or Task call is no such call there.
|
||||
* A child checkpoint compares only the child's own transcript. A SendMessage
|
||||
* makes the read render every transcript (see {@link findChild}), and the
|
||||
* child's SKILL.md links are not compared.
|
||||
*/
|
||||
function hasIndependentHistory(
|
||||
content: unknown,
|
||||
tools = ROOT_ONLY_TOOLS,
|
||||
launches = false,
|
||||
): boolean {
|
||||
const CHILD_FILE_TOOLS = new Set([...ROOT_FILE_TOOLS, "SendMessage", "Skill"]);
|
||||
|
||||
const TOOL_USES = ["tool_use", "server_tool_use", "mcp_tool_use"];
|
||||
|
||||
/**
|
||||
* Whether `content` has a tool call of `tools`, which renders from files that
|
||||
* a checkpoint does not compare. With `launches`, the subagent files are
|
||||
* compared, so an Agent or Task call is no such call.
|
||||
*/
|
||||
function readsOtherFiles(content: unknown, tools: Set<string>, launches = false): boolean {
|
||||
return (
|
||||
Array.isArray(content) &&
|
||||
content.some(
|
||||
(block) =>
|
||||
["tool_use", "server_tool_use", "mcp_tool_use"].includes(block?.type) &&
|
||||
!tools.has(block.name) &&
|
||||
TOOL_USES.includes(block?.type) &&
|
||||
tools.has(block.name) &&
|
||||
!(launches && isNativeSubagentControlTool(block.name)),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/** The skill names of the Skill calls in `messages`, sorted, each once. */
|
||||
function skillNames(messages: readonly { message?: unknown }[]): string[] {
|
||||
const names = new Set<string>();
|
||||
for (const message of messages) {
|
||||
const content = contentOf(message);
|
||||
if (!Array.isArray(content)) continue;
|
||||
for (const block of content) {
|
||||
if (TOOL_USES.includes(block?.type) && block.name === "Skill") {
|
||||
const skill = (block.input as { skill?: unknown } | null)?.skill;
|
||||
if (typeof skill === "string") names.add(skill);
|
||||
}
|
||||
}
|
||||
}
|
||||
return [...names].sort();
|
||||
}
|
||||
|
||||
/**
|
||||
* The SKILL.md that AIR's `_meta` of a Skill call links for each skill in
|
||||
* `names`, null for none, as the renderer resolves it in `cwd`. It depends
|
||||
* on the skill folders of `cwd` and of the home folder, so a checkpoint
|
||||
* resolves it again.
|
||||
*/
|
||||
function skillPaths(names: string[], cwd: string): [string, string | null][] {
|
||||
return names.map((name) => [name, resolveSkillPath(name, cwd) ?? null]);
|
||||
}
|
||||
|
||||
function contentOf(message: { message?: unknown }): unknown {
|
||||
return (message.message as { content?: unknown } | null)?.content;
|
||||
}
|
||||
@@ -268,9 +333,7 @@ export class SessionReadChild {
|
||||
/** The storage of a checkpoint, when the child's stream renders from its own files alone. */
|
||||
storage(transcript: string, rewound: boolean): SessionReadStorage | undefined {
|
||||
if (!this.files || rewound || !this.messages) return undefined;
|
||||
if (
|
||||
this.messages.some((message) => hasIndependentHistory(contentOf(message), CHILD_ONLY_TOOLS))
|
||||
)
|
||||
if (this.messages.some((message) => readsOtherFiles(contentOf(message), CHILD_FILE_TOOLS)))
|
||||
return undefined;
|
||||
return { transcript, files: this.files, subagents: subagentRecords(this.history) };
|
||||
}
|
||||
@@ -351,6 +414,8 @@ export async function readSessionTranscript(
|
||||
cwd?: string,
|
||||
observeStorage = false,
|
||||
scope: SessionReadScope = {},
|
||||
/** Whether the render links each Skill call to its SKILL.md, as for AIR clients (see `toolUseMeta`). */
|
||||
skillLinks = false,
|
||||
) {
|
||||
if (!isSessionId(sessionId)) {
|
||||
throw RequestError.invalidParams({ sessionId }, "Read the root Claude session by its UUID.");
|
||||
@@ -421,11 +486,11 @@ export async function readSessionTranscript(
|
||||
const quiet =
|
||||
version &&
|
||||
!rewind &&
|
||||
!messages.some((message) =>
|
||||
hasIndependentHistory(contentOf(message), ROOT_ONLY_TOOLS, statusRead),
|
||||
);
|
||||
!messages.some((message) => readsOtherFiles(contentOf(message), ROOT_FILE_TOOLS, statusRead));
|
||||
// Before the transcript ends, so that a checkpoint never pairs them with a later append.
|
||||
const files = quiet && history ? await fileVersions(subagentFiles(history)) : undefined;
|
||||
// Before the render, so that a checkpoint never pairs the links with a later change.
|
||||
const skills = quiet && skillLinks ? skillNames(messages) : [];
|
||||
return {
|
||||
messages,
|
||||
cwd: effectiveCwd,
|
||||
@@ -444,6 +509,9 @@ export async function readSessionTranscript(
|
||||
version,
|
||||
sidecarTitle,
|
||||
...(files && history ? { files, subagents: subagentRecords(history) } : {}),
|
||||
...(skills.length > 0
|
||||
? { skills: { cwd: effectiveCwd, paths: skillPaths(skills, effectiveCwd) } }
|
||||
: {}),
|
||||
}
|
||||
: undefined,
|
||||
};
|
||||
@@ -625,7 +693,7 @@ type Checkpoint = {
|
||||
storage: SessionReadStorage;
|
||||
boundaries: SessionReadFrame[];
|
||||
title?: string;
|
||||
status?: SessionReadFrame;
|
||||
status?: SubagentStatus;
|
||||
/** The root session, for a child read too. */
|
||||
root: string;
|
||||
/** The child's stream, for a child read. */
|
||||
@@ -792,7 +860,7 @@ export class SessionReads {
|
||||
outgoing: SessionReadFrame[],
|
||||
cursorId: string | undefined,
|
||||
title: string | undefined,
|
||||
current: SessionReadFrame | undefined,
|
||||
current: SubagentStatus | undefined,
|
||||
) => {
|
||||
for (const frame of outgoing) {
|
||||
check();
|
||||
@@ -801,7 +869,7 @@ export class SessionReads {
|
||||
// The subagent status is current, outside the replay cursor.
|
||||
if (current) {
|
||||
check();
|
||||
await options.send(current);
|
||||
await options.send(current.frame(sessionId, options.protocol));
|
||||
}
|
||||
// On v2, and in a v1 status read, the title is current session info, outside the replay cursor.
|
||||
if (
|
||||
@@ -822,16 +890,37 @@ export class SessionReads {
|
||||
// Before the render, which can take seconds on a large session.
|
||||
if (cursor !== undefined && tagOf(cursor) !== tag) throw invalidCursor();
|
||||
const cached = cursor ? this.checkpoints.get(key) : undefined;
|
||||
if (
|
||||
const changes =
|
||||
cached &&
|
||||
cached.cursorId === cursor &&
|
||||
(cached.requestedCwd === cwd || cached.cwd === cwd) &&
|
||||
cached.processCwd === processCwd &&
|
||||
cached.scope === scopeFor(cached.cwd, cached.stream) &&
|
||||
(await storageUnchanged(sessionId, cached.storage)) &&
|
||||
cached.processCwd === currentDirectory()
|
||||
) {
|
||||
return await deliver(cached.boundaries, cached.cursorId, cached.title, cached.status);
|
||||
cached.scope === scopeFor(cached.cwd, cached.stream)
|
||||
? await storageChanges(sessionId, cached.storage)
|
||||
: undefined;
|
||||
if (cached && changes && cached.processCwd === currentDirectory()) {
|
||||
if (changes.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));
|
||||
if (status) {
|
||||
const result = await deliver(cached.boundaries, cached.cursorId, cached.title, status);
|
||||
const versions = new Map(changes);
|
||||
this.checkpoints.set(key, {
|
||||
...cached,
|
||||
storage: {
|
||||
...cached.storage,
|
||||
files: cached.storage.files!.map(([file, version]) => [
|
||||
file,
|
||||
versions.has(file) ? versions.get(file)! : version,
|
||||
]),
|
||||
},
|
||||
status,
|
||||
});
|
||||
return result;
|
||||
}
|
||||
}
|
||||
check();
|
||||
if (useCursor) this.checkpoints.delete(key);
|
||||
|
||||
@@ -14,7 +14,9 @@
|
||||
* bytes appended since (see `readLaunches`).
|
||||
*
|
||||
* The read reports each announced child once more, in one update outside the
|
||||
* cursor (see {@link SubagentStatus.frame}).
|
||||
* cursor (see {@link SubagentStatus.frame}). An append to a child that
|
||||
* launched no children changes only that update (see
|
||||
* {@link SubagentStatus.afterAppend}).
|
||||
*/
|
||||
import type { SessionMessage } from "@anthropic-ai/claude-agent-sdk";
|
||||
import { open, type FileHandle } from "node:fs/promises";
|
||||
@@ -74,13 +76,29 @@ export type NestedLaunches = {
|
||||
|
||||
const NO_LAUNCHES: NestedLaunches = { messages: [], notifications: [] };
|
||||
|
||||
/** What a {@link SubagentStatusEntry} comes from, to build it again with new transcript ends. */
|
||||
type EntrySource = {
|
||||
sessionId: string;
|
||||
parentSessionId: string | undefined;
|
||||
record: SubagentRecord | undefined;
|
||||
/** The state, from the child's transcript end when it has no end of its own (see `activity`). */
|
||||
state(status: SubagentStatus): SubagentStatusEntry["state"];
|
||||
};
|
||||
|
||||
export class SubagentStatus {
|
||||
private readonly tails = new Map<string, ChildTail>();
|
||||
/** The launches of each child that launched children, by its agent id. */
|
||||
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>;
|
||||
|
||||
private constructor(readonly history: SubagentHistory) {}
|
||||
private constructor(readonly history: SubagentHistory) {
|
||||
this.launchers = new Set(
|
||||
[...history.agents.values()].flatMap((record) => record.parentAgentId ?? []),
|
||||
);
|
||||
}
|
||||
|
||||
/** Reads the transcript ends of the children of `history`, and the launches of nested children. */
|
||||
static async read(history: SubagentHistory): Promise<SubagentStatus> {
|
||||
@@ -145,7 +163,7 @@ export class SubagentStatus {
|
||||
child.sessionId,
|
||||
parentSessionId,
|
||||
record,
|
||||
end ?? (record ? this.activity(record) : "disconnected"),
|
||||
(status) => end ?? (record ? status.activity(record) : "disconnected"),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -160,11 +178,12 @@ export class SubagentStatus {
|
||||
.map((child) => {
|
||||
const ended =
|
||||
child.notified ?? (child.record.stoppedByUser ? "cancelled" : child.launchEnd);
|
||||
const end = ended ? replayEndState(child) : undefined;
|
||||
return this.entry(
|
||||
child.sessionId,
|
||||
child.parentSessionId === rootSessionId ? undefined : child.parentSessionId,
|
||||
child.record,
|
||||
ended ? replayEndState(child) : { state: this.activity(child.record) },
|
||||
(status) => end ?? { state: status.activity(child.record) },
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -174,6 +193,50 @@ export class SubagentStatus {
|
||||
this.reported = entries;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 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
|
||||
* equal those of a new replay.
|
||||
*/
|
||||
async afterAppend(files: string[]): Promise<SubagentStatus | undefined> {
|
||||
const agents = new Map(
|
||||
[...this.history.agents.values()].flatMap(({ agentId }) => {
|
||||
const file = this.file(agentId);
|
||||
return file ? [[file, agentId] as const] : [];
|
||||
}),
|
||||
);
|
||||
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)) ||
|
||||
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);
|
||||
await Promise.all(
|
||||
(changed as string[]).map(async (agentId) => {
|
||||
const tail = await readTail(this.file(agentId)!);
|
||||
if (tail) status.tails.set(agentId, tail);
|
||||
else status.tails.delete(agentId);
|
||||
}),
|
||||
);
|
||||
status.report(
|
||||
(sources as EntrySource[]).map((source) =>
|
||||
status.entry(source.sessionId, source.parentSessionId, source.record, source.state),
|
||||
),
|
||||
);
|
||||
return status;
|
||||
}
|
||||
|
||||
/**
|
||||
* The status update of the root session `sessionId`, with the {@link report}ed
|
||||
* entries: `_subagent_status` on v2, which accepts custom variants that start
|
||||
@@ -202,13 +265,13 @@ export class SubagentStatus {
|
||||
sessionId: string,
|
||||
parentSessionId: string | undefined,
|
||||
record: SubagentRecord | undefined,
|
||||
state: SubagentStatusEntry["state"],
|
||||
state: EntrySource["state"],
|
||||
): SubagentStatusEntry {
|
||||
const tail = record && this.tails.get(record.agentId);
|
||||
return {
|
||||
const entry: SubagentStatusEntry = {
|
||||
sessionId,
|
||||
...(parentSessionId ? { parentSessionId } : {}),
|
||||
state,
|
||||
state: state(this),
|
||||
...(record?.background ? { background: true } : {}),
|
||||
...(record?.agentType ? { agentType: record.agentType } : {}),
|
||||
...(record?.cwd ? { cwd: record.cwd } : {}),
|
||||
@@ -216,6 +279,8 @@ export class SubagentStatus {
|
||||
...(tail?.updatedAt ? { updatedAt: tail.updatedAt } : {}),
|
||||
...(tail ? { size: tail.size } : {}),
|
||||
};
|
||||
this.sources.set(entry, { sessionId, parentSessionId, record, state });
|
||||
return entry;
|
||||
}
|
||||
|
||||
private file(agentId: string): string | undefined {
|
||||
|
||||
@@ -315,6 +315,43 @@ describe.each(["rfd", "air", "v2"] as const)("child _session/read (%s)", (form)
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
["TodoWrite", { todos: [{ content: "Step", status: "pending", activeForm: "Step" }] }, false],
|
||||
["mcp__docs__search", { query: "cursor" }, false],
|
||||
["Skill", { skill: "example" }, true],
|
||||
["SendMessage", { to: "b2222222222222222", message: "Continue" }, true],
|
||||
] as const)(
|
||||
"renders a quiet child poll with a %s call only when it reads other files",
|
||||
async (name, input, renders) => {
|
||||
await writeTranscript(
|
||||
directory,
|
||||
`agent-${childA}`,
|
||||
[
|
||||
...childRecords("a", 1),
|
||||
{
|
||||
...transcriptAssistant("tool", ""),
|
||||
message: {
|
||||
role: "assistant",
|
||||
id: "msg_tool",
|
||||
content: [{ type: "tool_use", id: "toolu_tool", name, input }],
|
||||
},
|
||||
},
|
||||
].map((record) => ({ sessionId, cwd, agentId: childA, isSidechain: true, ...record })),
|
||||
);
|
||||
const r = await reader(form);
|
||||
try {
|
||||
const params = { sessionId, subagentSessionId: streamOf(childA, "toolu_a") };
|
||||
const { cursorId } = (await r.read({ ...params, replayFrom: start })).response;
|
||||
vi.mocked(getSessionMessages).mockClear();
|
||||
const quiet = await r.read({ ...params, replayFrom: { type: "cursor", cursorId } });
|
||||
expect(quiet.response).toEqual({ cursorId });
|
||||
expect(vi.mocked(getSessionMessages).mock.calls.length > 0).toBe(renders);
|
||||
} finally {
|
||||
await r.dispose();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("reads a nested child through its ancestors only, with the frames of a full read", async () => {
|
||||
const nested = "c3333333333333333";
|
||||
// A launches the nested child; its metadata names A as its parent.
|
||||
@@ -652,11 +689,12 @@ describe.each(["air", "rfd", "v2"] as const)("status _session/read (%s)", (form)
|
||||
let configDir: string;
|
||||
let session: StatusSession;
|
||||
let sessionId: string;
|
||||
let cwd: string;
|
||||
const status = { filters: { subagents: "status" } };
|
||||
|
||||
beforeEach(async () => {
|
||||
const folder = await configFolder();
|
||||
({ configDir, sessionId } = folder);
|
||||
({ configDir, sessionId, cwd } = folder);
|
||||
session = new StatusSession(sessionId, folder.project, folder.directory, folder.cwd);
|
||||
await session.create();
|
||||
});
|
||||
@@ -894,6 +932,134 @@ describe.each(["air", "rfd", "v2"] as const)("status _session/read (%s)", (form)
|
||||
}
|
||||
});
|
||||
|
||||
it("skips the render of a quiet poll with TodoWrite, MCP and Skill calls in the root", async () => {
|
||||
const calls = [
|
||||
["TodoWrite", { todos: [{ content: "Step", status: "pending", activeForm: "Step" }] }],
|
||||
["mcp__docs__search", { query: "cursor" }],
|
||||
["Skill", { skill: "example" }],
|
||||
] as const;
|
||||
for (const [name, input] of calls) {
|
||||
const id = `toolu_${name}`;
|
||||
await session.assistant(undefined, [{ type: "tool_use", id, name, input }], "tool_use");
|
||||
await session.user(undefined, [{ type: "tool_result", tool_use_id: id, content: "ok" }]);
|
||||
}
|
||||
const r = await reader(form);
|
||||
try {
|
||||
const first = await r.read({ sessionId, replayFrom: start, ...status });
|
||||
const cursorId = first.response.cursorId!;
|
||||
const poll = () => r.read({ sessionId, replayFrom: { type: "cursor", cursorId }, ...status });
|
||||
vi.mocked(getSessionMessages).mockClear();
|
||||
expect((await poll()).response).toEqual({ cursorId });
|
||||
expect(getSessionMessages).not.toHaveBeenCalled();
|
||||
|
||||
// A child's append is in the status of the next poll.
|
||||
const sizeOf = (frames: SessionReadFrame[]) =>
|
||||
statusOf(frames).find((entry) => entry.sessionId === idOf("bgrun"))!.size as number;
|
||||
await session.bash(session.agentIdOf("bgrun"));
|
||||
expect(sizeOf((await poll()).frames)).toBeGreaterThan(sizeOf(first.frames));
|
||||
|
||||
// On AIR, the link of the Skill call names its SKILL.md: a new one renders
|
||||
// the history again, also together with a child's append.
|
||||
const skill = path.join(cwd, ".claude", "skills", "example", "SKILL.md");
|
||||
await mkdir(path.dirname(skill), { recursive: true });
|
||||
await writeFile(skill, "---\nname: example\n---\nExample skill\n");
|
||||
await session.bash(session.agentIdOf("bgrun"));
|
||||
vi.mocked(getSessionMessages).mockClear();
|
||||
if (form === "air") {
|
||||
await expect(poll()).rejects.toMatchObject(invalidCursor);
|
||||
expect(getSessionMessages).toHaveBeenCalled();
|
||||
} else {
|
||||
expect((await poll()).response).toEqual({ cursorId });
|
||||
expect(getSessionMessages).not.toHaveBeenCalled();
|
||||
}
|
||||
} finally {
|
||||
await r.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("rebuilds only the status after an append to a child that launched no children", async () => {
|
||||
const r = await reader(form);
|
||||
try {
|
||||
const first = await r.read({ sessionId, replayFrom: start, ...status });
|
||||
const cursorId = first.response.cursorId!;
|
||||
const sizeOf = (frames: SessionReadFrame[]) =>
|
||||
statusOf(frames).find((entry) => entry.sessionId === idOf("bgrun"))!.size as number;
|
||||
await session.bash(session.agentIdOf("bgrun"));
|
||||
await session.answer(session.agentIdOf("bgrun")!);
|
||||
vi.mocked(getSessionMessages).mockClear();
|
||||
const reads = vi.spyOn(resumedSession, "readTranscriptEntries");
|
||||
const next = await r.read({
|
||||
sessionId,
|
||||
replayFrom: { type: "cursor", cursorId },
|
||||
...status,
|
||||
});
|
||||
// No render: the root part is the same, the status is new.
|
||||
expect(getSessionMessages).not.toHaveBeenCalled();
|
||||
expect(reads).not.toHaveBeenCalled();
|
||||
expect(next.response).toEqual({ cursorId });
|
||||
expect(statesOf(next.frames)[idOf("bgrun")]).toEqual(stateOf("idle"));
|
||||
expect(sizeOf(next.frames)).toBeGreaterThan(sizeOf(first.frames));
|
||||
// The status of a full render, and the cursor of the read from the start.
|
||||
const fresh = await r.read({ sessionId, replayFrom: start, ...status });
|
||||
expect(statusOf(next.frames)).toEqual(statusOf(fresh.frames));
|
||||
expect(fresh.response).toEqual({ cursorId });
|
||||
// The checkpoint has the new versions: the next poll is quiet.
|
||||
vi.mocked(getSessionMessages).mockClear();
|
||||
const quiet = await r.read({
|
||||
sessionId,
|
||||
replayFrom: { type: "cursor", cursorId },
|
||||
...status,
|
||||
});
|
||||
expect(getSessionMessages).not.toHaveBeenCalled();
|
||||
expect(statusOf(quiet.frames)).toEqual(statusOf(fresh.frames));
|
||||
} 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 {
|
||||
let { cursorId } = (await r.read({ sessionId, replayFrom: start, ...status })).response;
|
||||
const poll = async () => {
|
||||
const next = await r.read({
|
||||
sessionId,
|
||||
replayFrom: { type: "cursor", cursorId },
|
||||
...status,
|
||||
});
|
||||
cursorId = next.response.cursorId ?? cursorId;
|
||||
return next;
|
||||
};
|
||||
// The metadata of a child of `bgrun` comes before its launch call in `bgrun`'s transcript.
|
||||
const owner = session.agentIdOf("bgrun")!;
|
||||
const agentId = "adeep000000000000";
|
||||
session.agents.set("deep", { agentId, launch: "toolu_deep" });
|
||||
await writeFile(
|
||||
path.join(session.directory, `agent-${agentId}.meta.json`),
|
||||
JSON.stringify({ agentType: "Explore", toolUseId: "toolu_deep", parentAgentId: owner }),
|
||||
);
|
||||
expect(statesOf((await poll()).frames)).not.toHaveProperty(idOf("deep"));
|
||||
const before = cursorId;
|
||||
await session.assistant(owner, [
|
||||
{
|
||||
type: "tool_use",
|
||||
id: "toolu_deep",
|
||||
name: "Agent",
|
||||
input: { description: "Task deep", prompt: "Do deep", subagent_type: "Explore" },
|
||||
},
|
||||
]);
|
||||
vi.mocked(getSessionMessages).mockClear();
|
||||
const launched = await poll();
|
||||
expect(getSessionMessages).toHaveBeenCalled();
|
||||
expect(cursorId).not.toBe(before);
|
||||
expect(statusOf(launched.frames).find((entry) => entry.sessionId === idOf("deep"))).toEqual(
|
||||
expect.objectContaining({ parentSessionId: idOf("bgrun"), state: stateOf("running") }),
|
||||
);
|
||||
} 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 });
|
||||
|
||||
@@ -261,35 +261,45 @@ describe("_session/read on v1", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
["Read", false],
|
||||
["Skill", true],
|
||||
])("checks whether %s replay needs a full scan", async (name, needsReplay) => {
|
||||
const toolId = "toolu_saved";
|
||||
await store([
|
||||
/** A root history with one call of `name` and its result. */
|
||||
function storeToolCall(name: string, input: Record<string, unknown>) {
|
||||
return 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" },
|
||||
},
|
||||
],
|
||||
content: [{ type: "tool_use", id: "toolu_saved", name, input }],
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "user",
|
||||
uuid: "result",
|
||||
message: {
|
||||
role: "user",
|
||||
content: [{ type: "tool_result", tool_use_id: "toolu_saved", content: "Done" }],
|
||||
},
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
it.each([
|
||||
["Read", { file_path: "saved.txt" }, false],
|
||||
["TodoWrite", { todos: [{ content: "Step", status: "pending", activeForm: "Step" }] }, false],
|
||||
["mcp__docs__search", { query: "cursor" }, false],
|
||||
["Skill", { skill: "example" }, false],
|
||||
["ToolSearch", { query: "select:WebFetch" }, false],
|
||||
["SendMessage", { to: "a1111111111111111", message: "Continue" }, false],
|
||||
["ExitPlanMode", { plan: "Plan", planFilePath: "/plans/plan.md" }, true],
|
||||
["Agent", { prompt: "Check", description: "Check" }, true],
|
||||
])("checks whether %s replay needs a full scan", async (name, input, needsReplay) => {
|
||||
await storeToolCall(name, input);
|
||||
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);
|
||||
expect(cursorId).toBeTruthy();
|
||||
|
||||
updates.length = 0;
|
||||
vi.mocked(getSessionMessages).mockClear();
|
||||
@@ -313,6 +323,93 @@ describe("_session/read on v1", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it.each([true, false])(
|
||||
"follows the SKILL.md that a Skill call links only for an AIR client (AIR: %s)",
|
||||
async (air) => {
|
||||
await storeToolCall("Skill", { skill: "example" });
|
||||
const { agent, updates } = captureUpdates();
|
||||
const skillOf = () =>
|
||||
updates
|
||||
.map(({ update }) => update._meta as { jetbrains?: { air?: Record<string, unknown> } })
|
||||
.find((meta) => meta?.jetbrains?.air?.skill)?.jetbrains?.air?.skill;
|
||||
try {
|
||||
await initializeClient(agent, {
|
||||
session: { cursors: {} },
|
||||
...(air ? { _meta: { jetbrains: { air: { version: 1, capabilities: [] } } } } : {}),
|
||||
} as never);
|
||||
const { cursorId } = await agent.readSession({ sessionId, replayFrom: start });
|
||||
expect(skillOf()).toEqual(air ? { name: "example" } : undefined);
|
||||
updates.length = 0;
|
||||
vi.mocked(getSessionMessages).mockClear();
|
||||
expect(
|
||||
await agent.readSession({ sessionId, replayFrom: { type: "cursor", cursorId } }),
|
||||
).toEqual({ cursorId });
|
||||
expect(getSessionMessages).not.toHaveBeenCalled();
|
||||
|
||||
const skill = path.join(cwd, ".claude", "skills", "example", "SKILL.md");
|
||||
await mkdir(path.dirname(skill), { recursive: true });
|
||||
await writeFile(skill, "---\nname: example\n---\nExample skill\n");
|
||||
updates.length = 0;
|
||||
if (!air) {
|
||||
// No link depends on the file, so the poll stays quiet.
|
||||
expect(
|
||||
await agent.readSession({ sessionId, replayFrom: { type: "cursor", cursorId } }),
|
||||
).toEqual({ cursorId });
|
||||
expect(getSessionMessages).not.toHaveBeenCalled();
|
||||
return;
|
||||
}
|
||||
// The link of an already sent call changed: the client reads from the start.
|
||||
await expect(
|
||||
agent.readSession({ sessionId, replayFrom: { type: "cursor", cursorId } }),
|
||||
).rejects.toMatchObject(invalidCursor);
|
||||
expect(getSessionMessages).toHaveBeenCalledTimes(1);
|
||||
await agent.readSession({ sessionId, replayFrom: start });
|
||||
expect(skillOf()).toEqual({ name: "example", path: skill });
|
||||
} finally {
|
||||
await agent.dispose();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("renders a quiet poll of a full read again after its child appends", async () => {
|
||||
const agentId = "a1111111111111111";
|
||||
await storeToolCall("Agent", { prompt: "Check", description: "Check" });
|
||||
const subagents = path.join(project, sessionId, "subagents");
|
||||
await mkdir(subagents, { recursive: true });
|
||||
await writeFile(
|
||||
path.join(subagents, `agent-${agentId}.meta.json`),
|
||||
JSON.stringify({ toolUseId: "toolu_saved", description: "Check" }),
|
||||
);
|
||||
const child = (records: Record<string, unknown>[]) =>
|
||||
writeTranscript(
|
||||
subagents,
|
||||
`agent-${agentId}`,
|
||||
records.map((record) => ({ cwd, sessionId, agentId, isSidechain: true, ...record })),
|
||||
);
|
||||
await child([transcriptUser("c1", "Check"), transcriptAssistant("c2", "First report")]);
|
||||
const { agent, updates } = captureUpdates();
|
||||
try {
|
||||
await initializeClient(agent, { session: { cursors: {} }, subagents: {} } as never);
|
||||
const { cursorId } = await agent.readSession({ sessionId, replayFrom: start });
|
||||
await child([
|
||||
transcriptUser("c1", "Check"),
|
||||
transcriptAssistant("c2", "First report"),
|
||||
transcriptAssistant("c3", "Second report"),
|
||||
]);
|
||||
updates.length = 0;
|
||||
const next = await agent.readSession({ sessionId, replayFrom: { type: "cursor", cursorId } });
|
||||
expect(next.cursorId).not.toBe(cursorId);
|
||||
expect(updates).toContainEqual(
|
||||
expect.objectContaining({
|
||||
sessionId: agentId,
|
||||
update: expect.objectContaining({ content: { type: "text", text: "Second report" } }),
|
||||
}),
|
||||
);
|
||||
} 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`);
|
||||
|
||||
@@ -62,7 +62,13 @@ export class V1SessionReads {
|
||||
assertRoot: options.assertRoot,
|
||||
signal,
|
||||
replay: async (sessionId, cwd, observeStorage, scope) => {
|
||||
const transcript = await readSessionTranscript(sessionId, cwd, observeStorage, scope);
|
||||
const transcript = await readSessionTranscript(
|
||||
sessionId,
|
||||
cwd,
|
||||
observeStorage,
|
||||
scope,
|
||||
options.airClient,
|
||||
);
|
||||
const { child, subagentStatus } = transcript;
|
||||
const form = options.subagentForm;
|
||||
// `SessionReads` refuses a child read without native subagent sessions.
|
||||
@@ -100,7 +106,7 @@ export class V1SessionReads {
|
||||
? child.storage(transcript.transcript, transcript.rewound)
|
||||
: transcript.storage,
|
||||
...(child && form ? { stream: child.streamId(form) } : {}),
|
||||
...(subagentStatus ? { status: subagentStatus.frame(sessionId, 1) } : {}),
|
||||
...(subagentStatus ? { status: subagentStatus } : {}),
|
||||
historyEnd,
|
||||
title: transcript.title === undefined ? undefined : options.clientTitle(transcript.title),
|
||||
};
|
||||
|
||||
@@ -60,7 +60,7 @@ export async function renderSessionRead(
|
||||
}
|
||||
if (subagentStatus) {
|
||||
subagentStatus.report(subagents?.statusEntries() ?? []);
|
||||
return { frames, cwd, historyEnd, title, storage, status: subagentStatus.frame(sessionId, 2) };
|
||||
return { frames, cwd, historyEnd, title, storage, status: subagentStatus };
|
||||
}
|
||||
return { frames, cwd, historyEnd, title, storage };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user