diff --git a/docs/session-read.md b/docs/session-read.md index 0f28785c..64f9cf92 100644 --- a/docs/session-read.md +++ b/docs/session-read.md @@ -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. @@ -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:` suffix of a live child, or AIR's `:replay-subagent:`. 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. diff --git a/src/session-read.ts b/src/session-read.ts index 5f7ef283..804ce09b 100644 --- a/src/session-read.ts +++ b/src/session-read.ts @@ -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, @@ -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 { @@ -184,6 +187,16 @@ async function storageUnchanged(sessionId: string, storage: SessionReadStorage): if ((title ?? null) !== storage.sidecarTitle) return false; } if (await readRewindPoint(sessionId, undefined, { transcript })) return false; + if ( + storage.skills && + json( + skillPaths( + storage.skills.paths.map(([name]) => name), + storage.skills.cwd, + ), + ) !== json(storage.skills.paths) + ) + return false; return await matchesTranscript(); } catch { // An uncertain probe leaves validation and errors to the ordinary replay. @@ -191,33 +204,74 @@ async function storageUnchanged(sessionId: string, storage: SessionReadStorage): } } -/** 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, 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(); + 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 +322,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 +403,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 +475,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 +498,9 @@ export async function readSessionTranscript( version, sidecarTitle, ...(files && history ? { files, subagents: subagentRecords(history) } : {}), + ...(skills.length > 0 + ? { skills: { cwd: effectiveCwd, paths: skillPaths(skills, effectiveCwd) } } + : {}), } : undefined, }; diff --git a/src/tests/session-read-subagents.test.ts b/src/tests/session-read-subagents.test.ts index 58ac5a41..b97b931e 100644 --- a/src/tests/session-read-subagents.test.ts +++ b/src/tests/session-read-subagents.test.ts @@ -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. @@ -894,6 +931,38 @@ 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 changes a file that the checkpoint compares: the poll renders. + const sizeOf = (frames: SessionReadFrame[]) => + statusOf(frames).find((entry) => entry.sessionId === idOf("bgrun"))!.size as number; + await session.bash(session.agentIdOf("bgrun")); + const grown = await poll(); + expect(getSessionMessages).toHaveBeenCalled(); + expect(sizeOf(grown.frames)).toBeGreaterThan(sizeOf(first.frames)); + } 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 }); diff --git a/src/tests/v1/session-read.test.ts b/src/tests/v1/session-read.test.ts index 9625f1af..1b065295 100644 --- a/src/tests/v1/session-read.test.ts +++ b/src/tests/v1/session-read.test.ts @@ -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) { + 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 } }) + .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[]) => + 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`); diff --git a/src/v1/session-read.ts b/src/v1/session-read.ts index d11d3cc0..6fa6cb43 100644 --- a/src/v1/session-read.ts +++ b/src/v1/session-read.ts @@ -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.