diff --git a/docs/session-read.md b/docs/session-read.md index 0f15f9f3..89102921 100644 --- a/docs/session-read.md +++ b/docs/session-read.md @@ -38,7 +38,7 @@ Send `filters.subagents: "status"` with a root read: The read renders the root history as a default read does, with the announcement of each child on its parent's stream: `subagent_spawned` for AIR clients on v1, `subagent_update` with `running` on the RFD form and on v2. It sends none of the end states that a default read sends after the history (`subagent_state_update` on v1 AIR, `subagent_update` with an end otherwise). The status update below holds the current state of each child. A child's stream gets at most the prompt of its launch, the lifecycle updates of its own children and, on v2, its `replay_complete`. No message or tool call of a child's own history is sent. -The read parses no child transcript. Of each child it reads the metadata file and the end of the transcript: the last 64 KB, or twice as many bytes each time while they do not hold a whole record with the model and the end of the last turn, up to 4 MB. A child whose metadata names a working directory, such as a worktree child, also has its transcript read up to the first line with a `cwd`. The transcript of a child that launched children is searched as bytes for the lines that name those launches, and only those lines are parsed. The adapter keeps the places of those lines for each file, so a later read searches only the bytes appended since. A rewritten or replaced file is searched again from the start. A v1 connection without native subagent sessions ignores `filters.subagents` and sends a default read. +The read parses no child transcript. Of each child it reads the metadata file and the end of the transcript: the last 64 KB, or twice as many bytes each time while they do not hold a whole record with the model and the end of the last turn, up to 4 MB. A child whose metadata names a working directory, such as a worktree child, also has its transcript read up to the first line with a `cwd`. The transcript of a child that launched children is searched as bytes for the lines that name an Agent or Task launch: the launch calls, their results and the task notifications. Only those lines are parsed. The adapter keeps the places of those lines for each file, so a later read searches only the bytes appended since, also when they hold a new launch. A replaced or shortened file is searched again from the start, and so is a file whose found lines no longer start and end where they did. A file is also searched again from the start, once, when the metadata names a launch that the search did not find. Other rewrites in place, which keep every line in its place, are not noticed: Claude Code only appends to these transcripts. A v1 connection without native subagent sessions ignores `filters.subagents` and sends a default read. After the replay and its cursor update, and before the title, each status read sends one update with the current status of every announced child. It is outside the cursor: it comes on every poll, also when the cursor stays the same, and replaces the previous one. The title follows it outside the cursor on v1 too, as on v2 in step 2 above: a null title clears the previous one. diff --git a/src/subagent-status.ts b/src/subagent-status.ts index 294424c9..e2fdba8e 100644 --- a/src/subagent-status.ts +++ b/src/subagent-status.ts @@ -24,6 +24,7 @@ import type { SubagentState } from "./acp-subagents.js"; import { HANDBACK_TOOL, type WorkState } from "./native-subagents.js"; import { isMissing, + subagentLaunchIds, subagentTranscript, withPath, type SubagentHistory, @@ -424,14 +425,17 @@ function handbackResults(content: { type?: unknown }[]): Set | undefined } /** - * The lines of one transcript that name launches, from earlier status reads. - * Only their places are kept, so a later read scans only the appended bytes. + * The lines of one transcript that name Agent or Task launches, from earlier + * status reads. Only their places are kept, so a later read scans only the + * appended bytes, also when they hold a new launch. */ type LaunchScan = { /** The device and inode of the file. */ identity: string; - /** The launches that the scan looks for. */ - launches: string; + /** The ids of the launch calls found. */ + launchIds: Set; + /** Launches named by metadata that a scan from the start of this file did not find. */ + missing: Set; /** The bytes scanned: up to the end of the last whole line. */ scanned: number; /** The start and the end (the newline) of each line that names a launch, in file order. */ @@ -448,9 +452,13 @@ export const launchScanStats = { bytes: 0 }; /** * The launch calls `launchIds`, their results and their task notifications * in the transcript `file` (see {@link NestedLaunches}). The file is searched - * as bytes; only the lines that name a launch are parsed. A scan of an - * earlier read is continued from where it ended, while the file has the same - * identity and did not shrink. + * as bytes for the lines that name any Agent or Task launch (see + * `scanLaunches`); only those lines are parsed. A scan of an earlier read is + * continued from where it ended, also when the appended bytes hold a new + * launch, while the file has the same identity, did not shrink, and still has + * line ends where the scan found them. Otherwise it is scanned from the start. + * It is also scanned from the start, once, when the metadata names a launch + * that the scan did not find. */ async function readLaunches( file: string, @@ -516,19 +524,34 @@ async function readLaunches( }; } -/** The lines of the open transcript `file` that name the launches `launchIds`, in file order. */ +/** + * The lines of the open transcript `file` that name an Agent or Task launch, + * in file order: the launch calls, the results of those calls, and the task + * notifications. The search for results relies on each result coming after + * its call in the file, as Claude Code writes them. + */ async function scanLaunches( handle: FileHandle, file: string, - launchIds: string[], + /** The launches that the metadata names. */ + named: string[], ): Promise { const stats = await handle.stat({ bigint: true }); const identity = `${stats.dev}:${stats.ino}`; const size = Number(stats.size); - const launches = [...launchIds].sort().join(","); let scan = launchScans.get(file); - if (!scan || scan.identity !== identity || scan.launches !== launches || scan.scanned > size) { - scan = { identity, launches, scanned: 0, lines: [] }; + if (!scan || scan.identity !== identity || scan.scanned > size) { + scan = { identity, launchIds: new Set(), missing: new Set(), scanned: 0, lines: [] }; + } + const rescan = () => { + launchScans.delete(file); + return scanLaunches(handle, file, named); + }; + // The scanned bytes still end a line, else the file was rewritten. + if (scan.scanned > 0) { + const last = Buffer.alloc(1); + const { bytesRead } = await handle.read(last, 0, 1, scan.scanned - 1); + if (bytesRead !== 1 || last[0] !== 10) return rescan(); } // The lines found before, each still a whole line, else the file was rewritten. const known: string[] = []; @@ -541,8 +564,7 @@ async function scanLaunches( buffer[bytesRead - 1] !== 10 || (start > 0 && buffer[0] !== 10) ) { - launchScans.delete(file); - return scanLaunches(handle, file, launchIds); + return rescan(); } known.push(buffer.toString("utf8", start - from, bytesRead - 1)); } @@ -561,15 +583,30 @@ async function scanLaunches( at = buffer.indexOf(needle, end); } }; - for (const id of launchIds) { - collect(`"id":"${id}"`); - collect(`"tool_use_id":"${id}"`); + // The launch calls first, so that the results of the new launches are found too. + const launchIds = new Set(scan.launchIds); + for (const name of ["Agent", "Task"]) collect(`"name":"${name}"`); + for (const [start, end] of lines) { + const record = parse(buffer.toString("utf8", start, end)) as { + type?: unknown; + message?: { content?: unknown }; + } | null; + if (record?.type !== "assistant") continue; + for (const id of subagentLaunchIds(record.message?.content)) launchIds.add(id); } + for (const id of launchIds) collect(`"tool_use_id":"${id}"`); collect(``); + // A launch of the metadata that no scan found. Its call may not be written + // yet, or a rewrite in place that kept every line end may have added it: + // scan from the start, once for each such launch. + const missing = named.filter((id) => !launchIds.has(id) && !scan.missing.has(id)); + if (missing.length > 0 && scan.scanned > 0) return rescan(); const added = [...lines].sort(([a], [b]) => a - b); launchScans.delete(file); launchScans.set(file, { - ...scan, + identity, + launchIds, + missing: new Set([...scan.missing, ...missing]), scanned: scan.scanned + buffer.length, lines: [ ...scan.lines, diff --git a/src/tests/session-read-subagents.test.ts b/src/tests/session-read-subagents.test.ts index 500c6bef..495ef43a 100644 --- a/src/tests/session-read-subagents.test.ts +++ b/src/tests/session-read-subagents.test.ts @@ -1060,6 +1060,74 @@ describe.each(["air", "rfd", "v2"] as const)("status _session/read (%s)", (form) } }); + it("scans only the appended bytes of a parent for a new nested launch, and a rewritten parent again", 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; + }; + const outer = path.join(session.directory, `agent-${session.agentIdOf("outer")}.jsonl`); + // Sizes come from the read bytes, not `stat`, so the file is never checked and then used. + const sizeOf = async () => (await readFile(outer)).length; + const before = await sizeOf(); + await session.agent("nestedlate", "outer", { finish: false }); + const appended = (await sizeOf()) - before; + let scanned = launchScanStats.bytes; + const launched = await poll(); + expect(launchScanStats.bytes - scanned).toBe(appended); + expect(statusOf(launched.frames).find((e) => e.sessionId === idOf("nestedlate"))).toEqual( + expect.objectContaining({ parentSessionId: idOf("outer"), state: stateOf("running") }), + ); + + // A rewrite in place keeps the file identity but moves the lines: the scan starts again. + const text = await readFile(outer, "utf8"); + await writeFile(outer, text.replace('"content":"Do outer"', '"content":"Do outer now"')); + scanned = launchScanStats.bytes; + const rewritten = await poll(); + expect(launchScanStats.bytes - scanned).toBe(await sizeOf()); + expect(statesOf(rewritten.frames)).toEqual(statesOf(launched.frames)); + + // A rewrite of the same size that turns a Bash call into a launch keeps every line end. + // The metadata names a launch that the scan did not find, so the scan starts again. + const before2 = await readFile(outer, "utf8"); + const call = /"id":"(toolu_bash\d+)","name":"Bash","input":\{"command":"date"\}/.exec( + before2, + )!; + const launchId = call[1]!; + const after = before2.replace( + call[0], + `"id":"${launchId}","name":"Agent","input":{"prompt":"date"}`, + ); + expect(after.length).toBe(before2.length); + await writeFile(outer, after); + const agentId = "ainplace000000000"; + session.agents.set("inplace", { agentId, launch: launchId }); + await writeFile( + path.join(session.directory, `agent-${agentId}.meta.json`), + JSON.stringify({ + agentType: "Explore", + toolUseId: launchId, + parentAgentId: session.agentIdOf("outer"), + }), + ); + // The new launch is before others on the stream of `outer`, so the cursor cannot continue. + await expect(poll()).rejects.toMatchObject(invalidCursor); + const inPlace = await r.read({ sessionId, replayFrom: start, ...status }); + expect(statusOf(inPlace.frames).find((e) => e.sessionId === idOf("inplace"))).toEqual( + expect.objectContaining({ parentSessionId: idOf("outer") }), + ); + } 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 });