diff --git a/docs/session-read.md b/docs/session-read.md index 02f36adf..0f28785c 100644 --- a/docs/session-read.md +++ b/docs/session-read.md @@ -26,7 +26,7 @@ By default each read renders the root and the whole transcript of every subagent ### Filters -The optional `filters` object of a read says what the read sends. Its only key is `subagents`: `"full"`, the default, or `"status"`. A read without `filters`, or with `filters.subagents: "full"`, is the default read and shares its cursor. The keys that an adapter supports are the keys of `_meta.sessionRead.filters` in its initialize response. A read with another key, or with another value of `subagents`, returns `-32602` with `data.reason: "unsupported_filter"` and the refused keys in `data.filters`, so that a client never gets more than it asked for. A cursor belongs to the filters of the read that returned it: a read with other filters refuses it as `invalid_cursor`. +The optional `filters` object of a read says what the read sends. Its only key is `subagents`: `"full"`, the default, or `"status"`. A read without `filters`, or with `filters.subagents: "full"`, is the default read and shares its cursor. The keys that an adapter supports are the keys of `_meta.sessionRead.filters` in its initialize response. A read with another key, or with another value of `subagents`, returns `-32602` with `data.reason: "unsupported_filter"` and the refused keys in `data.filters`, so that a client never gets more than it asked for. A cursor belongs to the filters of the read that returned it: a read with other filters refuses it as `invalid_cursor`. A read refuses a cursor of another session, of a read with other filters, or of a root read in a child read and the other way around, before it renders the history, so the refusal is fast also on a large session. ### Status read @@ -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 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 used a tool other than Bash, PowerShell, Read, Write, Edit, Glob, Grep or SubagentHandback. 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 2ffdc84e..5f7ef283 100644 --- a/src/session-read.ts +++ b/src/session-read.ts @@ -507,14 +507,16 @@ function digest(value: string) { // A cursor carries the number of delivered updates per session. Its digest binds // those counts to the rendering options, exact history prefixes and post-replay metadata. +// Its read tag names the read that returned it (see `readTag`). const lengths = z.record(z.string(), z.int().nonnegative()); +const CURSOR = /^read:v1:[\w-]{43}\.([\w-]{16})\.([\w-]+)$/; function decodeLengths(id: string): Map { - const match = /^read:v1:[\w-]{43}\.([\w-]+)$/.exec(id); + const match = CURSOR.exec(id); if (match) { try { return new Map( Object.entries( - lengths.parse(JSON.parse(Buffer.from(match[1]!, "base64url").toString("utf8"))), + lengths.parse(JSON.parse(Buffer.from(match[2]!, "base64url").toString("utf8"))), ), ); } catch { @@ -524,11 +526,29 @@ function decodeLengths(id: string): Map { throw invalidCursor(); } +/** + * The tag of the cursors of a read: the part of its scope that is known + * before the render. Its session, the config folder, the protocol, the + * client capabilities, the adapter version, its filters and whether it reads + * a child. A cursor with another tag cannot continue the read, so it is + * refused without a render. The rest of the scope (the working directory and + * a child's stream) is checked after the render. + */ +function readTag(scope: unknown[]): string { + return digest(json(scope)).slice(0, 16); +} + +/** The read tag of `cursorId`, undefined when it is no cursor of this adapter. */ +function tagOf(cursorId: string): string | undefined { + return CURSOR.exec(cursorId)?.[1]; +} + function snapshot( frames: SessionReadFrame[], root: string, protocol: 1 | 2, scope: string, + tag: string, previous?: string, historyEnd = frames.length, /** `root` is a child's stream, whose entities name their launch. */ @@ -586,7 +606,8 @@ function snapshot( hashes.set(id, prefix ? stream.prefix : stream.history.copy().digest("base64url")); } const encoded = Buffer.from(json(Object.fromEntries(counts))).toString("base64url"); - return "read:v1:" + digest(json([scope, encoded, Object.fromEntries(hashes)])) + "." + encoded; + const hash = digest(json([scope, encoded, Object.fromEntries(hashes)])); + return `read:v1:${hash}.${tag}.${encoded}`; } if (previous && cursor(true) !== previous) throw invalidCursor(); @@ -722,6 +743,15 @@ export class SessionReads { ...(status ? [{ filters: { subagents: "status" } }] : []), ...(stream === undefined ? [] : [stream]), ]); + // Root, status and child reads, and reads with other filters, refuse each other's cursors. + const tag = readTag([ + sessionId, + claudeConfigDir(), + options.protocol, + options.capabilities, + packageJson.version, + status ? "status" : subagent !== undefined ? "subagent" : "full", + ]); const replay = async () => { try { const view = await options.replay(sessionId, cwd, useCursor, readScope); @@ -789,6 +819,8 @@ export class SessionReads { return cursorId ? { cursorId } : {}; }; try { + // 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 ( cached && @@ -815,6 +847,7 @@ export class SessionReads { streamId, options.protocol, scope, + tag, cursor, historyEnd, stream !== undefined, diff --git a/src/tests/session-read.test.ts b/src/tests/session-read.test.ts index 0275467e..31e713cc 100644 --- a/src/tests/session-read.test.ts +++ b/src/tests/session-read.test.ts @@ -67,6 +67,34 @@ describe("session read cursors", () => { expect(options.send).not.toHaveBeenCalled(); }); + it.each([ + ["a status read in a full read", { filters: { subagents: "status" } }, {}], + ["a full read in a status read", {}, { filters: { subagents: "status" } }], + ["a full read in a child read", {}, { subagentSessionId: "child" }], + ["a child read in a full read", { subagentSessionId: "child" }, {}], + ["another session", {}, { sessionId: "other" }], + ] as const)("refuses a cursor from %s before it renders", async (_name, first, other) => { + const options = { + ...reader([message("1")]), + subagents: true, + replay: vi.fn(async (_id: string, cwd = "/project", _observe: boolean, scope: object) => ({ + frames: [message("1")], + cwd, + ...("subagentSessionId" in scope ? { stream: "root" } : {}), + })), + }; + const reads = new SessionReads(); + const { cursorId } = await reads.read({ ...start, ...first }, options); + expect(cursorId).toBeTruthy(); + options.replay.mockClear(); + options.send.mockClear(); + await expect(reads.read({ ...poll(cursorId), ...other }, options)).rejects.toMatchObject( + invalid, + ); + expect(options.replay).not.toHaveBeenCalled(); + expect(options.send).not.toHaveBeenCalled(); + }); + it("keeps the previous cursor usable when the confirmation replay changes or a file cannot be read", async () => { const options = reader([message("1")]); const reads = new SessionReads();