@agentclientprotocol/claude-agent-acp 0.114.1-preview.4 → 0.115.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  import { RequestError } from "@agentclientprotocol/sdk/unstable";
2
2
  import { getSessionMessages } from "@anthropic-ai/claude-agent-sdk";
3
3
  import { createHash } from "node:crypto";
4
- import { lstat, open } from "node:fs/promises";
4
+ import { lstat, open, readFile } from "node:fs/promises";
5
5
  import path from "node:path";
6
6
  import { z } from "zod";
7
7
  import packageJson from "../package.json" with { type: "json" };
@@ -12,10 +12,26 @@ import { readHeadTailOf, readRecentCustomTitle, readSidecarTitle, } from "./sess
12
12
  import { sanitizeTitle } from "./session-titles.js";
13
13
  import { activeSessionMessages, readRewindPoint } from "./session-rewind.js";
14
14
  import { withReplyBranches } from "./transcript-branches.js";
15
+ import { isNativeSubagentControlTool } from "./native-subagents.js";
16
+ import { resolveSkillPath } from "./tool-calls/reporters/interaction.js";
17
+ import { isMissing, subagentHistory, subagentLaunchIds, subagentTranscript, } from "./subagent-history.js";
18
+ import { SubagentStatus } from "./subagent-status.js";
15
19
  export const SESSION_READ_METHOD = "_session/read";
16
20
  export const SESSION_READ_CAPABILITY = { supported: true };
21
+ /** The capability of a connection that can read subagents lazily (see `docs/session-read.md`). */
22
+ export const SESSION_READ_SUBAGENTS_CAPABILITY = {
23
+ supported: true,
24
+ subagents: {},
25
+ filters: { subagents: {} },
26
+ };
27
+ /** The keys of `filters` this adapter applies. A read with another key is refused. */
28
+ const SUPPORTED_FILTERS = new Set(["subagents"]);
17
29
  const request = z.object({
18
30
  sessionId: z.string().trim().min(1),
31
+ /** A child session of `sessionId`, as the client got it: reads that child's stream only. */
32
+ subagentSessionId: z.string().trim().min(1).nullish(),
33
+ /** What the read sends: `subagents` is `"full"` (the default) or `"status"`. */
34
+ filters: z.record(z.string(), z.unknown()).nullish(),
19
35
  _meta: z.record(z.string(), z.unknown()).nullish(),
20
36
  cwd: z.string().refine(path.isAbsolute, "cwd must be an absolute path").nullish(),
21
37
  replayFrom: z
@@ -29,39 +45,154 @@ function fileVersion(stats) {
29
45
  const { dev, ino, mode, size, mtimeNs, ctimeNs } = stats;
30
46
  return [dev, ino, mode, size, mtimeNs, ctimeNs].join(":");
31
47
  }
32
- /** Checks the transcript's metadata and the sidecar inputs read by the replay. */
33
- async function storageUnchanged(sessionId, storage) {
48
+ /**
49
+ * The version of the file `name`, `null` when it is missing. Undefined when
50
+ * it is not a regular file, such as a symbolic link, whose version does not
51
+ * change when its target does: as for the root, no checkpoint can rely on it.
52
+ */
53
+ async function fileVersionAt(name) {
54
+ try {
55
+ const stats = await lstat(name, { bigint: true });
56
+ return stats.isFile() ? fileVersion(stats) : undefined;
57
+ }
58
+ catch (error) {
59
+ if (isMissing(error))
60
+ return null;
61
+ throw error;
62
+ }
63
+ }
64
+ /** The versions of `names`, read in parallel; undefined when one is not a regular file. */
65
+ async function fileVersions(names) {
66
+ const versions = await Promise.all(names.map(async (name) => [name, await fileVersionAt(name)]));
67
+ return versions.every(([, version]) => version !== undefined)
68
+ ? versions
69
+ : undefined;
70
+ }
71
+ /** The transcript of the child `agentId`. */
72
+ function childFile(history, agentId) {
73
+ return history.directory && subagentTranscript(history.directory, agentId);
74
+ }
75
+ /**
76
+ * The metadata of the subagents of `history`, to compare. A checkpoint
77
+ * compares the content, not file versions: the files are read before their
78
+ * versions could be.
79
+ */
80
+ function subagentRecords(history) {
81
+ return json([...history.agents].sort(([a], [b]) => a.localeCompare(b)));
82
+ }
83
+ /**
84
+ * Checks the transcript's metadata and the sidecar inputs read by the
85
+ * replay. Returns the subagent transcripts in `storage.files` that changed,
86
+ * with their current versions: empty when nothing changed, undefined when
87
+ * another input changed or a file is not a regular file.
88
+ */
89
+ async function storageChanges(sessionId, storage) {
34
90
  try {
35
91
  // A move or a different matching project must go through the ordinary lookup.
36
92
  const transcript = await findTranscript(sessionId, { strict: true });
37
93
  if (transcript !== storage.transcript)
38
- return false;
39
- const matchesTranscript = async () => {
40
- const root = await lstat(transcript, { bigint: true });
41
- return root.isFile() && fileVersion(root) === storage.version;
94
+ return undefined;
95
+ const transcriptChanges = async () => {
96
+ if (storage.version !== undefined) {
97
+ const root = await lstat(transcript, { bigint: true });
98
+ if (!root.isFile() || fileVersion(root) !== storage.version)
99
+ return undefined;
100
+ }
101
+ const changed = [];
102
+ for (const [file, version] of storage.files ?? []) {
103
+ const current = await fileVersionAt(file);
104
+ if (current === undefined)
105
+ return undefined;
106
+ if (current !== version)
107
+ changed.push([file, current]);
108
+ }
109
+ return changed;
42
110
  };
43
- if (!(await matchesTranscript()))
44
- return false;
111
+ if (!(await transcriptChanges()))
112
+ return undefined;
113
+ if (storage.subagents !== undefined &&
114
+ subagentRecords(await subagentHistory(sessionId, { strict: true, transcript })) !==
115
+ storage.subagents)
116
+ return undefined;
45
117
  if (storage.sidecarTitle !== undefined) {
46
118
  const title = await readSidecarTitle(transcript, { strict: true });
47
119
  if ((title ?? null) !== storage.sidecarTitle)
48
- return false;
120
+ return undefined;
49
121
  }
50
122
  if (await readRewindPoint(sessionId, undefined, { transcript }))
51
- return false;
52
- return await matchesTranscript();
123
+ return undefined;
124
+ if (storage.skills &&
125
+ json(skillPaths(storage.skills.paths.map(([name]) => name), storage.skills.cwd)) !== json(storage.skills.paths))
126
+ return undefined;
127
+ // The versions of this second check: the caller reads the changed files after them.
128
+ return await transcriptChanges();
53
129
  }
54
130
  catch {
55
131
  // An uncertain probe leaves validation and errors to the ordinary replay.
56
- return false;
132
+ return undefined;
57
133
  }
58
134
  }
59
- /** These tools render their stored input and result, with no child or workspace reads. */
60
- const ROOT_ONLY_TOOLS = new Set(["Bash", "PowerShell", "Read", "Write", "Edit", "Glob", "Grep"]);
61
- function hasIndependentHistory(content) {
135
+ /**
136
+ * The tools whose render reads files besides the transcript and the inputs
137
+ * that a checkpoint compares. Every other tool, MCP and unknown tools
138
+ * included, renders from its stored input and result. A renderer that starts
139
+ * to read a file for a tool must add the tool here.
140
+ *
141
+ * - Agent and Task: the subagent metadata and transcripts. A status read
142
+ * compares them, so there they are no such tools.
143
+ * - ExitPlanMode: whether the plan file exists, for AIR clients with `planFile`.
144
+ *
145
+ * Skill is not here: AIR's link to its SKILL.md depends on files in the
146
+ * working directory and the home folder, and a root checkpoint of an AIR
147
+ * client compares that link (see {@link skillPaths}). Other clients get no link.
148
+ */
149
+ const ROOT_FILE_TOOLS = new Set(["Agent", "Task", "ExitPlanMode"]);
150
+ /**
151
+ * A child checkpoint compares only the child's own transcript. A SendMessage
152
+ * makes the read render every transcript (see {@link findChild}), and the
153
+ * child's SKILL.md links are not compared.
154
+ */
155
+ const CHILD_FILE_TOOLS = new Set([...ROOT_FILE_TOOLS, "SendMessage", "Skill"]);
156
+ const TOOL_USES = ["tool_use", "server_tool_use", "mcp_tool_use"];
157
+ /**
158
+ * Whether `content` has a tool call of `tools`, which renders from files that
159
+ * a checkpoint does not compare. With `launches`, the subagent files are
160
+ * compared, so an Agent or Task call is no such call.
161
+ */
162
+ function readsOtherFiles(content, tools, launches = false) {
62
163
  return (Array.isArray(content) &&
63
- content.some((block) => ["tool_use", "server_tool_use", "mcp_tool_use"].includes(block?.type) &&
64
- !ROOT_ONLY_TOOLS.has(block.name)));
164
+ content.some((block) => TOOL_USES.includes(block?.type) &&
165
+ tools.has(block.name) &&
166
+ !(launches && isNativeSubagentControlTool(block.name))));
167
+ }
168
+ /** The skill names of the Skill calls in `messages`, sorted, each once. */
169
+ function skillNames(messages) {
170
+ const names = new Set();
171
+ for (const message of messages) {
172
+ const content = contentOf(message);
173
+ if (!Array.isArray(content))
174
+ continue;
175
+ for (const block of content) {
176
+ if (TOOL_USES.includes(block?.type) && block.name === "Skill") {
177
+ const skill = block.input?.skill;
178
+ if (typeof skill === "string")
179
+ names.add(skill);
180
+ }
181
+ }
182
+ }
183
+ return [...names].sort();
184
+ }
185
+ /**
186
+ * The SKILL.md that AIR's `_meta` of a Skill call links for each skill in
187
+ * `names`, null for none, as the renderer resolves it in `cwd`. It depends
188
+ * on the skill folders of `cwd` and of the home folder, so a checkpoint
189
+ * resolves it again.
190
+ */
191
+ function skillPaths(names, cwd) {
192
+ return names.map((name) => [name, resolveSkillPath(name, cwd) ?? null]);
193
+ }
194
+ function contentOf(message) {
195
+ return message.message?.content;
65
196
  }
66
197
  function currentDirectory() {
67
198
  try {
@@ -72,8 +203,116 @@ function currentDirectory() {
72
203
  return undefined;
73
204
  }
74
205
  }
206
+ /** The id that AIR's draft gives a replayed child (see `replaySessionHistory` in the v1 agent). */
207
+ const AIR_REPLAY_CHILD = ":replay-subagent:";
208
+ /** The child that a child read selects (see {@link findChild}). */
209
+ export class SessionReadChild {
210
+ agentId;
211
+ launchId;
212
+ history;
213
+ rootSessionId;
214
+ lineage;
215
+ files;
216
+ /** The messages of the child's transcript, once the replay read them. */
217
+ messages;
218
+ constructor(agentId, launchId, history, rootSessionId,
219
+ /** The agents whose transcripts the replay reads; undefined for every agent. */
220
+ lineage,
221
+ /** The version of the child's transcript, read before the replay. */
222
+ files) {
223
+ this.agentId = agentId;
224
+ this.launchId = launchId;
225
+ this.history = history;
226
+ this.rootSessionId = rootSessionId;
227
+ this.lineage = lineage;
228
+ this.files = files;
229
+ }
230
+ /** Whether the replay reads the transcript of the agent `agentId`. Others keep their association only. */
231
+ expand(agentId) {
232
+ return !this.lineage || this.lineage.has(agentId);
233
+ }
234
+ /** Takes each child transcript that the replay read. */
235
+ read(agentId, messages) {
236
+ if (agentId === this.agentId)
237
+ this.messages = messages;
238
+ }
239
+ /** The session id of the child's stream: AIR's replay id, or the agent id. */
240
+ streamId(form) {
241
+ return form === "air" ? this.rootSessionId + AIR_REPLAY_CHILD + this.launchId : this.agentId;
242
+ }
243
+ /** The storage of a checkpoint, when the child's stream renders from its own files alone. */
244
+ storage(transcript, rewound) {
245
+ if (!this.files || rewound || !this.messages)
246
+ return undefined;
247
+ if (this.messages.some((message) => readsOtherFiles(contentOf(message), CHILD_FILE_TOOLS)))
248
+ return undefined;
249
+ return { transcript, files: this.files, subagents: subagentRecords(this.history) };
250
+ }
251
+ }
252
+ /**
253
+ * Finds the child `subagent` of the session `sessionId`. It is a child
254
+ * session id that the client got: AIR's `<root>:replay-subagent:<launch>`,
255
+ * an agent id, or an agent id with a live generation suffix. Every
256
+ * generation of an agent shares its transcript, so they are one stream.
257
+ */
258
+ async function findChild(sessionId, transcript, subagent, rootLaunches, observeStorage) {
259
+ const history = await subagentHistory(sessionId, { strict: true, transcript });
260
+ const byAgent = new Map([...history.agents].map(([launchId, record]) => [record.agentId, { launchId, record }]));
261
+ const prefix = sessionId + AIR_REPLAY_CHILD;
262
+ const launchId = subagent.startsWith(prefix) ? subagent.slice(prefix.length) : undefined;
263
+ const target = launchId !== undefined
264
+ ? history.agents.has(launchId)
265
+ ? { launchId, record: history.agents.get(launchId) }
266
+ : undefined
267
+ : byAgent.get(subagent.replace(/:generation:\d+$/, ""));
268
+ if (!target) {
269
+ throw new RequestError(-32002, "The session has no recorded subagent with this id. Read its root again.", { reason: "subagent_not_found", sessionId, subagentSessionId: subagent });
270
+ }
271
+ const { agentId } = target.record;
272
+ // Read before the transcripts, so that a checkpoint never pairs them with a later append.
273
+ const file = childFile(history, agentId);
274
+ const files = observeStorage && file ? await fileVersions([file]) : undefined;
275
+ // The child and its ancestors, by the parent that each metadata file names.
276
+ // Without one, a launch outside the root history replays every child.
277
+ let lineage = new Set();
278
+ for (let current = target; current && lineage;) {
279
+ if (lineage.has(current.record.agentId))
280
+ break;
281
+ lineage.add(current.record.agentId);
282
+ const parent = current.record.parentAgentId;
283
+ if (parent) {
284
+ current = byAgent.get(parent);
285
+ if (!current)
286
+ lineage = undefined;
287
+ }
288
+ else {
289
+ if (!rootLaunches.has(current.launchId))
290
+ lineage = undefined;
291
+ current = undefined;
292
+ }
293
+ }
294
+ if (lineage && file) {
295
+ const text = await readFile(file, "utf8").catch(() => "");
296
+ // A SendMessage between agents links both streams, and the replay links
297
+ // them only with the other agent's transcript: such a child replays them all.
298
+ if (text.includes('"name":"SendMessage"') || text.includes('"kind":"coordinator"')) {
299
+ lineage = undefined;
300
+ }
301
+ else {
302
+ // A child's hand-back is a message on this stream, so its direct children replay too.
303
+ for (const [launch, record] of history.agents) {
304
+ if (record.parentAgentId === agentId || text.includes(`"${launch}"`)) {
305
+ lineage.add(record.agentId);
306
+ }
307
+ }
308
+ }
309
+ }
310
+ return new SessionReadChild(agentId, target.launchId, history, sessionId, lineage, files);
311
+ }
75
312
  /** The SDK follows parent links in these records, including the branch selected by rewind.json. */
76
- export async function readSessionTranscript(sessionId, cwd, observeStorage = false) {
313
+ export async function readSessionTranscript(sessionId, cwd, observeStorage = false, scope = {},
314
+ /** Whether the render links each Skill call to its SKILL.md, as for AIR clients (see `toolUseMeta`). */
315
+ skillLinks = false) {
77
316
  if (!isSessionId(sessionId)) {
78
317
  throw RequestError.invalidParams({ sessionId }, "Read the root Claude session by its UUID.");
79
318
  }
@@ -117,18 +356,51 @@ export async function readSessionTranscript(sessionId, cwd, observeStorage = fal
117
356
  const rewind = await readRewindPoint(sessionId, undefined, { transcript });
118
357
  const retained = activeSessionMessages(chain, rewind);
119
358
  const messages = await readHistoryAcrossCompactions(sessionId, retained, undefined, effectiveCwd, records);
359
+ const rootLaunches = new Set(messages.flatMap((message) => subagentLaunchIds(contentOf(message))));
360
+ const child = scope.subagentSessionId === undefined
361
+ ? undefined
362
+ : await findChild(sessionId, transcript, scope.subagentSessionId, rootLaunches, observeStorage);
363
+ const statusRead = scope.subagents === "status";
364
+ const history = statusRead && rootLaunches.size > 0
365
+ ? await subagentHistory(sessionId, { strict: true, transcript })
366
+ : undefined;
367
+ const quiet = version &&
368
+ !rewind &&
369
+ !messages.some((message) => readsOtherFiles(contentOf(message), ROOT_FILE_TOOLS, statusRead));
370
+ // Before the transcript ends, so that a checkpoint never pairs them with a later append.
371
+ const files = quiet && history ? await fileVersions(subagentFiles(history)) : undefined;
372
+ // Before the render, so that a checkpoint never pairs the links with a later change.
373
+ const skills = quiet && skillLinks ? skillNames(messages) : [];
120
374
  return {
121
375
  messages,
122
376
  cwd: effectiveCwd,
123
377
  transcript,
378
+ child,
379
+ rewound: rewind !== undefined && rewind !== null,
380
+ subagentStatus: statusRead
381
+ ? await SubagentStatus.read(history ?? { agents: new Map() })
382
+ : undefined,
124
383
  title: title && sanitizeTitle(title),
125
- storage: version &&
126
- !rewind &&
127
- !messages.some((message) => hasIndependentHistory(message.message?.content))
128
- ? { transcript, version, sidecarTitle }
384
+ // A status read depends on the children's files: without their versions it keeps no checkpoint.
385
+ storage: !child && quiet && (!history || files)
386
+ ? {
387
+ transcript,
388
+ version,
389
+ sidecarTitle,
390
+ ...(files && history ? { files, subagents: subagentRecords(history) } : {}),
391
+ ...(skills.length > 0
392
+ ? { skills: { cwd: effectiveCwd, paths: skillPaths(skills, effectiveCwd) } }
393
+ : {}),
394
+ }
129
395
  : undefined,
130
396
  };
131
397
  }
398
+ /** The child transcripts that a status read depends on, in a stable order: it reads their ends. */
399
+ function subagentFiles(history) {
400
+ return [...history.agents.values()]
401
+ .flatMap(({ agentId }) => childFile(history, agentId) ?? [])
402
+ .sort();
403
+ }
132
404
  /**
133
405
  * The `field` of the last `type` record of the snapshot, undefined when it is
134
406
  * empty. The SDK reads the head and tail 64 KB windows instead, so a large
@@ -162,12 +434,14 @@ function digest(value) {
162
434
  }
163
435
  // A cursor carries the number of delivered updates per session. Its digest binds
164
436
  // those counts to the rendering options, exact history prefixes and post-replay metadata.
437
+ // Its read tag names the read that returned it (see `readTag`).
165
438
  const lengths = z.record(z.string(), z.int().nonnegative());
439
+ const CURSOR = /^read:v1:[\w-]{43}\.([\w-]{16})\.([\w-]+)$/;
166
440
  function decodeLengths(id) {
167
- const match = /^read:v1:[\w-]{43}\.([\w-]+)$/.exec(id);
441
+ const match = CURSOR.exec(id);
168
442
  if (match) {
169
443
  try {
170
- return new Map(Object.entries(lengths.parse(JSON.parse(Buffer.from(match[1], "base64url").toString("utf8")))));
444
+ return new Map(Object.entries(lengths.parse(JSON.parse(Buffer.from(match[2], "base64url").toString("utf8")))));
171
445
  }
172
446
  catch {
173
447
  /* Invalid and expired cursors have the same recovery. */
@@ -175,7 +449,24 @@ function decodeLengths(id) {
175
449
  }
176
450
  throw invalidCursor();
177
451
  }
178
- function snapshot(frames, root, protocol, scope, previous, historyEnd = frames.length) {
452
+ /**
453
+ * The tag of the cursors of a read: the part of its scope that is known
454
+ * before the render. Its session, the config folder, the protocol, the
455
+ * client capabilities, the adapter version, its filters and whether it reads
456
+ * a child. A cursor with another tag cannot continue the read, so it is
457
+ * refused without a render. The rest of the scope (the working directory and
458
+ * a child's stream) is checked after the render.
459
+ */
460
+ function readTag(scope) {
461
+ return digest(json(scope)).slice(0, 16);
462
+ }
463
+ /** The read tag of `cursorId`, undefined when it is no cursor of this adapter. */
464
+ function tagOf(cursorId) {
465
+ return CURSOR.exec(cursorId)?.[1];
466
+ }
467
+ function snapshot(frames, root, protocol, scope, tag, previous, historyEnd = frames.length,
468
+ /** `root` is a child's stream, whose entities name their launch. */
469
+ child = false) {
179
470
  const saved = previous ? decodeLengths(previous) : new Map();
180
471
  const streams = new Map();
181
472
  const entities = new LastReportedEntity();
@@ -209,7 +500,7 @@ function snapshot(frames, root, protocol, scope, previous, historyEnd = frames.l
209
500
  stream.prefix = stream.history.copy().digest("base64url");
210
501
  if (before === undefined || stream.count > before)
211
502
  outgoing.push(frame);
212
- entities.sending(frame, protocol);
503
+ entities.sending(frame, protocol, child);
213
504
  }
214
505
  }
215
506
  function cursor(prefix) {
@@ -225,7 +516,8 @@ function snapshot(frames, root, protocol, scope, previous, historyEnd = frames.l
225
516
  hashes.set(id, prefix ? stream.prefix : stream.history.copy().digest("base64url"));
226
517
  }
227
518
  const encoded = Buffer.from(json(Object.fromEntries(counts))).toString("base64url");
228
- return "read:v1:" + digest(json([scope, encoded, Object.fromEntries(hashes)])) + "." + encoded;
519
+ const hash = digest(json([scope, encoded, Object.fromEntries(hashes)]));
520
+ return `read:v1:${hash}.${tag}.${encoded}`;
229
521
  }
230
522
  if (previous && cursor(true) !== previous)
231
523
  throw invalidCursor();
@@ -236,6 +528,7 @@ function snapshot(frames, root, protocol, scope, previous, historyEnd = frames.l
236
528
  }
237
529
  /** A read owns only a replay on this connection. Closing it invalidates the pending delivery. */
238
530
  export class SessionReads {
531
+ /** Reads by root session, or by root, child and mode for the other scopes. */
239
532
  active = new Map();
240
533
  transitions = new Map();
241
534
  checkpoints = new Map();
@@ -243,13 +536,17 @@ export class SessionReads {
243
536
  async transition(sessionId, kind, run) {
244
537
  if (sessionId === undefined)
245
538
  return run();
246
- const read = this.active.get(sessionId);
247
- if (read) {
539
+ const reads = [...this.active.values()].filter((read) => read.root === sessionId);
540
+ if (reads.length > 0) {
248
541
  if (kind === "open")
249
542
  throw alreadyOpen(sessionId);
250
- read.invalidated = true;
543
+ for (const read of reads)
544
+ read.invalidated = true;
545
+ }
546
+ for (const [key, checkpoint] of this.checkpoints) {
547
+ if (checkpoint.root === sessionId)
548
+ this.checkpoints.delete(key);
251
549
  }
252
- this.checkpoints.delete(sessionId);
253
550
  this.transitions.set(sessionId, (this.transitions.get(sessionId) ?? 0) + 1);
254
551
  try {
255
552
  return await run();
@@ -267,15 +564,40 @@ export class SessionReads {
267
564
  if (!parsed.success)
268
565
  throw RequestError.invalidParams(undefined, parsed.error.issues[0]?.message);
269
566
  const { sessionId, replayFrom } = parsed.data;
567
+ const subagent = parsed.data.subagentSessionId ?? undefined;
568
+ if (subagent !== undefined && !options.subagents) {
569
+ throw RequestError.invalidParams({ reason: "subagent_read_unsupported", subagentSessionId: subagent }, "Reading a subagent needs native subagent sessions. Read the root session instead.");
570
+ }
571
+ const filters = parsed.data.filters ?? {};
572
+ // An adapter that ignored an unknown filter would send more than the client asked for.
573
+ const unsupported = Object.keys(filters).filter((name) => !SUPPORTED_FILTERS.has(name));
574
+ if (unsupported.length > 0) {
575
+ throw RequestError.invalidParams({ reason: "unsupported_filter", filters: unsupported }, `This adapter does not support the read filters ${unsupported.join(", ")}. Check \`_meta.sessionRead.filters\` in the initialize response and remove them.`);
576
+ }
577
+ if (filters.subagents != null &&
578
+ filters.subagents !== "full" &&
579
+ filters.subagents !== "status") {
580
+ throw RequestError.invalidParams({ reason: "unsupported_filter", filters: ["subagents"] }, '`filters.subagents` is "full" or "status".');
581
+ }
582
+ // Without native subagent sessions there are no child transcripts to leave out.
583
+ const status = options.subagents === true && filters.subagents === "status";
584
+ if (subagent !== undefined && status) {
585
+ throw RequestError.invalidParams({ reason: "subagent_read_with_status", subagentSessionId: subagent }, 'A subagent read has no `filters.subagents: "status"`. Remove one of them.');
586
+ }
587
+ const readScope = {
588
+ ...(status ? { subagents: "status" } : {}),
589
+ ...(subagent !== undefined ? { subagentSessionId: subagent } : {}),
590
+ };
591
+ const key = subagent === undefined && !status ? sessionId : json([sessionId, readScope]);
270
592
  const cwd = parsed.data.cwd ?? undefined;
271
593
  const previous = replayFrom?.type === "cursor" ? replayFrom.cursorId : undefined;
272
594
  if (replayFrom?.type === "cursor" &&
273
595
  (typeof previous !== "string" || !previous || !options.cursors))
274
596
  throw invalidCursor();
275
597
  const cursor = typeof previous === "string" ? previous : undefined;
276
- if (this.active.has(sessionId))
598
+ if (this.active.has(key))
277
599
  throw alreadyOpen(sessionId);
278
- const read = { invalidated: false };
600
+ const read = { root: sessionId, invalidated: false };
279
601
  const check = () => {
280
602
  if (options.signal?.aborted)
281
603
  throw RequestError.requestCancelled();
@@ -284,21 +606,46 @@ export class SessionReads {
284
606
  };
285
607
  check();
286
608
  options.assertRoot?.(sessionId);
287
- this.active.set(sessionId, read);
609
+ this.active.set(key, read);
288
610
  const useCursor = options.cursors && replayFrom != null;
289
611
  const processCwd = useCursor ? currentDirectory() : undefined;
290
- const scopeFor = (effectiveCwd) => json([
612
+ // A child's scope names its resolved stream, so each id of it shares a cursor.
613
+ const scopeFor = (effectiveCwd, stream) => json([
291
614
  sessionId,
292
615
  effectiveCwd,
293
616
  claudeConfigDir(),
294
617
  options.protocol,
295
618
  options.capabilities,
296
619
  packageJson.version,
620
+ // The cursor belongs to the read's filters: a read with other filters refuses it.
621
+ ...(status ? [{ filters: { subagents: "status" } }] : []),
622
+ ...(stream === undefined ? [] : [stream]),
623
+ ]);
624
+ // Root, status and child reads, and reads with other filters, refuse each other's cursors.
625
+ const tag = readTag([
626
+ sessionId,
627
+ claudeConfigDir(),
628
+ options.protocol,
629
+ options.capabilities,
630
+ packageJson.version,
631
+ status ? "status" : subagent !== undefined ? "subagent" : "full",
297
632
  ]);
298
633
  const replay = async () => {
299
634
  try {
300
- const view = await options.replay(sessionId, cwd, useCursor);
301
- if (options.protocol === 1 && view.title)
635
+ const view = await options.replay(sessionId, cwd, useCursor, readScope);
636
+ if (view.stream !== undefined) {
637
+ // The child's stream only. Other streams belong to their own reads.
638
+ const end = view.historyEnd ?? view.frames.length;
639
+ const own = (frame) => frame.sessionId === view.stream;
640
+ return {
641
+ ...view,
642
+ frames: view.frames.filter(own),
643
+ historyEnd: view.frames.slice(0, end).filter(own).length,
644
+ title: undefined,
645
+ };
646
+ }
647
+ // A status read sends the title outside the cursor, as on v2 (see `deliver`).
648
+ if (options.protocol === 1 && view.title && view.status === undefined)
302
649
  view.frames.push({
303
650
  sessionId,
304
651
  update: { sessionUpdate: "session_info_update", title: view.title },
@@ -318,13 +665,20 @@ export class SessionReads {
318
665
  }, `Could not read the history of ${sessionId}. Retry the read. ${String(error)}`);
319
666
  }
320
667
  };
321
- const deliver = async (outgoing, cursorId, title) => {
668
+ const deliver = async (outgoing, cursorId, title, current) => {
322
669
  for (const frame of outgoing) {
323
670
  check();
324
671
  await options.send(frame);
325
672
  }
326
- // On v2 the title is current session info, outside the replay cursor.
327
- if (options.protocol === 2 && (title || useCursor)) {
673
+ // The subagent status is current, outside the replay cursor.
674
+ if (current) {
675
+ check();
676
+ await options.send(current.frame(sessionId, options.protocol));
677
+ }
678
+ // On v2, and in a v1 status read, the title is current session info, outside the replay cursor.
679
+ if ((options.protocol === 2 || current !== undefined) &&
680
+ subagent === undefined &&
681
+ (title || useCursor)) {
328
682
  check();
329
683
  await options.send({
330
684
  sessionId,
@@ -335,27 +689,55 @@ export class SessionReads {
335
689
  return cursorId ? { cursorId } : {};
336
690
  };
337
691
  try {
338
- const cached = cursor ? this.checkpoints.get(sessionId) : undefined;
339
- if (cached &&
692
+ // Before the render, which can take seconds on a large session.
693
+ if (cursor !== undefined && tagOf(cursor) !== tag)
694
+ throw invalidCursor();
695
+ const cached = cursor ? this.checkpoints.get(key) : undefined;
696
+ const changes = cached &&
340
697
  cached.cursorId === cursor &&
341
698
  (cached.requestedCwd === cwd || cached.cwd === cwd) &&
342
699
  cached.processCwd === processCwd &&
343
- cached.scope === scopeFor(cached.cwd) &&
344
- (await storageUnchanged(sessionId, cached.storage)) &&
345
- cached.processCwd === currentDirectory()) {
346
- return await deliver(cached.boundaries, cached.cursorId, cached.title);
700
+ cached.scope === scopeFor(cached.cwd, cached.stream)
701
+ ? await storageChanges(sessionId, cached.storage)
702
+ : undefined;
703
+ if (cached && changes && cached.processCwd === currentDirectory()) {
704
+ if (changes.length === 0) {
705
+ return await deliver(cached.boundaries, cached.cursorId, cached.title, cached.status);
706
+ }
707
+ // Only child transcripts changed. When the render does not depend on
708
+ // them, only the status changes, and it is outside the cursor.
709
+ const status = await cached.status?.afterAppend(changes.map(([file]) => file));
710
+ if (status) {
711
+ const result = await deliver(cached.boundaries, cached.cursorId, cached.title, status);
712
+ const versions = new Map(changes);
713
+ this.checkpoints.set(key, {
714
+ ...cached,
715
+ storage: {
716
+ ...cached.storage,
717
+ files: cached.storage.files.map(([file, version]) => [
718
+ file,
719
+ versions.has(file) ? versions.get(file) : version,
720
+ ]),
721
+ },
722
+ status,
723
+ });
724
+ return result;
725
+ }
347
726
  }
348
727
  check();
349
728
  if (useCursor)
350
- this.checkpoints.delete(sessionId);
351
- const { frames, cwd: effectiveCwd, historyEnd, title, storage } = await replay();
729
+ this.checkpoints.delete(key);
730
+ const view = await replay();
731
+ const { frames, cwd: effectiveCwd, historyEnd, title, storage, stream } = view;
732
+ let current = view.status;
733
+ const streamId = stream ?? sessionId;
352
734
  check();
353
735
  if (!useCursor)
354
- return await deliver(frames, undefined, title);
355
- const scope = scopeFor(effectiveCwd);
356
- const { outgoing, cursorId, anchor } = snapshot(frames, sessionId, options.protocol, scope, cursor, historyEnd);
736
+ return await deliver(frames, undefined, title, current);
737
+ const scope = scopeFor(effectiveCwd, stream);
738
+ const { outgoing, cursorId, anchor } = snapshot(frames, streamId, options.protocol, scope, tag, cursor, historyEnd, stream !== undefined);
357
739
  let verifiedStorage = storage;
358
- const isRootBoundary = (frame) => frame.sessionId === sessionId && frame.update.sessionUpdate === "replay_complete";
740
+ const isStreamBoundary = (frame) => frame.sessionId === streamId && frame.update.sessionUpdate === "replay_complete";
359
741
  if (cursorId && cursorId !== cursor) {
360
742
  // A terminal can append or rewind between the reads of the root and a child.
361
743
  const again = await replay();
@@ -366,14 +748,14 @@ export class SessionReads {
366
748
  frames.some((frame, i) => json(frame) !== json(again.frames[i]))) {
367
749
  throw RequestError.internalError({ sessionId, retryable: true }, "History changed during the read. Retry with the last successful cursor.");
368
750
  }
369
- if (again.storage?.transcript !== storage?.transcript ||
370
- again.storage?.version !== storage?.version ||
371
- again.storage?.sidecarTitle !== storage?.sidecarTitle) {
751
+ // The later status, which a child's append can change without changing the frames.
752
+ current = again.status;
753
+ if (json(again.storage ?? null) !== json(storage ?? null)) {
372
754
  verifiedStorage = undefined;
373
755
  }
374
- const end = outgoing.findIndex(isRootBoundary);
756
+ const end = outgoing.findIndex(isStreamBoundary);
375
757
  outgoing.splice(end < 0 ? outgoing.length : end, 0, {
376
- sessionId,
758
+ sessionId: streamId,
377
759
  update: {
378
760
  sessionUpdate: "cursor_update",
379
761
  cursorId,
@@ -383,18 +765,21 @@ export class SessionReads {
383
765
  });
384
766
  }
385
767
  // Pair the cursor only with the inputs read by its render, never a later append.
386
- const result = await deliver(outgoing, cursorId, title);
768
+ const result = await deliver(outgoing, cursorId, title, current);
387
769
  check();
388
770
  if (cursorId && verifiedStorage && processCwd && processCwd === currentDirectory()) {
389
- this.checkpoints.set(sessionId, {
771
+ this.checkpoints.set(key, {
772
+ root: sessionId,
773
+ ...(stream !== undefined ? { stream } : {}),
390
774
  cursorId,
391
775
  scope,
392
776
  requestedCwd: cwd,
393
777
  cwd: effectiveCwd,
394
778
  processCwd,
395
779
  storage: verifiedStorage,
396
- boundaries: frames.filter(isRootBoundary),
780
+ boundaries: frames.filter(isStreamBoundary),
397
781
  title,
782
+ ...(current ? { status: current } : {}),
398
783
  });
399
784
  if (this.checkpoints.size > 32) {
400
785
  this.checkpoints.delete(this.checkpoints.keys().next().value);
@@ -403,7 +788,7 @@ export class SessionReads {
403
788
  return result;
404
789
  }
405
790
  finally {
406
- this.active.delete(sessionId);
791
+ this.active.delete(key);
407
792
  }
408
793
  }
409
794
  }