@agentclientprotocol/claude-agent-acp 0.114.0 → 0.114.1-preview.2

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 +1 @@
1
- {"version":3,"file":"resumed-session.d.ts","sourceRoot":"","sources":["../src/resumed-session.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,cAAc,EAEnB,KAAK,iBAAiB,EACvB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAyB,KAAK,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAU1E,KAAK,YAAY,GAAG;IAClB,GAAG,EAAE,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,IAAI,CAAC;IAClC,KAAK,EAAE,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,IAAI,CAAC;CACrC,CAAC;AAEF,MAAM,MAAM,sBAAsB,GAAG;IACnC,QAAQ,CAAC,EAAE,cAAc,EAAE,CAAC;IAC5B,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF;;;iDAGiD;AACjD,wBAAgB,0BAA0B,CAAC,QAAQ,EAAE,cAAc,EAAE,GAAG,MAAM,GAAG,SAAS,CAgBzF;AASD;uEACuE;AACvE,wBAAsB,kBAAkB,CACtC,SAAS,EAAE,MAAM,EACjB,MAAM,CAAC,EAAE,YAAY,GACpB,OAAO,CAAC,sBAAsB,CAAC,CAejC;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAsB,4BAA4B,CAChD,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,cAAc,EAAE,EAC1B,MAAM,CAAC,EAAE,YAAY,EACrB,GAAG,CAAC,EAAE,MAAM,EACZ,QAAQ,CAAC,EAAE,iBAAiB,EAAE,GAC7B,OAAO,CAAC,cAAc,EAAE,CAAC,CA4B3B;AAED;;2DAE2D;AAC3D,wBAAsB,sBAAsB,CAC1C,SAAS,EAAE,MAAM,EACjB,GAAG,CAA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C,iBAAiB,EAAE,CAAC,CAOtF;AAED,wBAAsB,uBAAuB,CAC3C,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,UAAU,EAClB,IAAI,EAAE,MAAM,GACX,OAAO,CAAC,iBAAiB,EAAE,CAAC,CAgB9B"}
@@ -5,6 +5,7 @@ import { isCompactSummaryMessage } from "./context-compaction.js";
5
5
  import { projectsRoot } from "./paths.js";
6
6
  import { errorCode } from "./session-index/project-dirs.js";
7
7
  import { SessionTiming } from "./session-timing.js";
8
+ import { withReplyBranches } from "./transcript-branches.js";
8
9
  /** The size of one backward read of a transcript. */
9
10
  const TAIL_CHUNK_BYTES = 64 * 1024;
10
11
  /** Return the concrete model recorded by the last real assistant response.
@@ -82,10 +83,15 @@ export async function readHistoryAcrossCompactions(sessionId, messages, logger,
82
83
  return messages;
83
84
  try {
84
85
  const entries = (snapshot ?? (await loadFullSessionHistory(sessionId, dir))).map(linkCompactBoundary);
85
- const history = await getSessionMessages(sessionId, {
86
+ const read = (records) => getSessionMessages(sessionId, {
86
87
  dir,
87
- sessionStore: { append: async () => { }, load: async () => entries },
88
+ sessionStore: { append: async () => { }, load: async () => records },
88
89
  });
90
+ // `_session/read` gives `messages` with the branches of each model reply,
91
+ // and passes its records: the history before it gets them too.
92
+ const history = snapshot
93
+ ? await withReplyBranches(entries, await read(entries), read)
94
+ : await read(entries);
89
95
  const leaf = messages.at(-1)?.uuid;
90
96
  const end = history.findIndex((message) => message.uuid === leaf);
91
97
  if (end < 0) {
@@ -136,10 +136,8 @@ export declare function isSidechainTranscript(head: string): boolean;
136
136
  /** `<projectDir>/<sessionId>/custom-title.json` of a transcript. */
137
137
  export declare function customTitleSidecarPath(transcriptPath: string): string;
138
138
  /** The custom title that the SDK reads first: the tail's, else the CLI's
139
- * sidecar's. A strict read throws when the sidecar cannot be read. */
140
- export declare function readRecentCustomTitle(transcriptPath: string, headTail: HeadTail, options?: {
141
- strict: boolean;
142
- }): Promise<string | undefined>;
139
+ * sidecar's, read by `readSidecar`. */
140
+ export declare function readRecentCustomTitle(transcriptPath: string, headTail: HeadTail, readSidecar?: (transcriptPath: string) => Promise<string | undefined>): Promise<string | undefined>;
143
141
  /** The title of the CLI's sidecar, if it has a readable title. A strict read
144
142
  * throws when the sidecar exists but cannot be read. */
145
143
  export declare function readSidecarTitle(transcriptPath: string, options?: {
@@ -1 +1 @@
1
- {"version":3,"file":"transcript-scan.d.ts","sourceRoot":"","sources":["../../src/session-index/transcript-scan.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EAAE,MAAM,kBAAkB,CAAC;AAEvC,OAAO,EAAqB,KAAK,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAehF,MAAM,MAAM,SAAS,GAAG,UAAU,GAAG,YAAY,CAAC;AAElD,MAAM,MAAM,eAAe,GAAG;IAC5B,wEAAwE;IACxE,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB;0BACsB;IACtB,SAAS,CAAC,EAAE,SAAS,CAAC;IACtB,gDAAgD;IAChD,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB;8EAC0E;IAC1E,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,mCAAmC;IACnC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,kCAAkC;IAClC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;qDACiD;IACjD,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;kEAC8D;IAC9D,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,2DAA2D;IAC3D,KAAK,CAAC,EAAE,MAAM,CAAC;IACf;6DACyD;IACzD,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;+EAG2E;IAC3E,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB;yEACqE;IACrE,eAAe,CAAC,EAAE,eAAe,CAAC;IAClC;0DACsD;IACtD,WAAW,EAAE,OAAO,CAAC;CACtB,CAAC;AAEF,MAAM,MAAM,QAAQ,GAAG;IACrB,IAAI,E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2BnE"}
@@ -543,9 +543,9 @@ export function customTitleSidecarPath(transcriptPath) {
543
543
  return path.join(path.dirname(transcriptPath), sessionId, "custom-title.json");
544
544
  }
545
545
  /** The custom title that the SDK reads first: the tail's, else the CLI's
546
- * sidecar's. A strict read throws when the sidecar cannot be read. */
547
- export async function readRecentCustomTitle(transcriptPath, headTail, options) {
548
- return tailCustomTitle(headTail) ?? (await readSidecarTitle(transcriptPath, options));
546
+ * sidecar's, read by `readSidecar`. */
547
+ export async function readRecentCustomTitle(transcriptPath, headTail, readSidecar = readSidecarTitle) {
548
+ return tailCustomTitle(headTail) ?? (await readSidecar(transcriptPath));
549
549
  }
550
550
  /** The title of the CLI's sidecar, if it has a readable title. A strict read
551
551
  * throws when the sidecar exists but cannot be read. */
@@ -16,25 +16,39 @@ type ReadOptions = {
16
16
  cursors: boolean;
17
17
  signal?: AbortSignal;
18
18
  isOpen(sessionId: string): boolean;
19
- replay(sessionId: string, cwd: string | undefined): Promise<{
19
+ assertRoot?(sessionId: string): void;
20
+ replay(sessionId: string, cwd: string | undefined, observeStorage: boolean): Promise<{
20
21
  frames: SessionReadFrame[];
21
22
  cwd: string;
22
23
  historyEnd?: number;
23
24
  title?: string;
25
+ storage?: SessionReadStorage;
24
26
  }>;
25
27
  send(frame: SessionReadFrame): Promise<void> | void;
26
28
  };
29
+ export type SessionReadStorage = {
30
+ transcript: string;
31
+ version: string;
32
+ /** Undefined when replay skipped the sidecar, null when it had no title. */
33
+ sidecarTitle?: string | null;
34
+ };
27
35
  /** The SDK follows parent links in these records, including the branch selected by rewind.json. */
28
- export declare function readSessionTranscript(sessionId: string, cwd?: string): Promise<{
36
+ export declare function readSessionTranscript(sessionId: string, cwd?: string, observeStorage?: boolean): Promise<{
29
37
  messages: import("@anthropic-ai/claude-agent-sdk").SessionMessage[];
30
38
  cwd: string;
31
39
  transcript: string;
32
40
  title: string | undefined;
41
+ storage: {
42
+ transcript: string;
43
+ version: string;
44
+ sidecarTitle: string | null | undefined;
45
+ } | undefined;
33
46
  }>;
34
47
  /** A read owns only a replay on this connection. Closing it invalidates the pending delivery. */
35
48
  export declare class SessionReads {
36
49
  private readonly active;
37
50
  private readonly transitions;
51
+ private readonly checkpoints;
38
52
  /** Reserve a session before load, resume, close or delete can yield. */
39
53
  transition<T>(sessionId: string | undefined, kind: "open" | "close", run: () => Promise<T>): Promise<T>;
40
54
  read(params: unknown, options: ReadOptions): Promise<{
@@ -1 +1 @@
1
- {"version":3,"file":"session-read.d.ts","sourceRoot":"","sources":["../src/session-read.ts"],"names":[],"mappings":"AAsBA,eAAO,MAAM,mBAAmB,kBAAkB,CAAC;AACnD,eAAO,MAAM,uBAAuB;;CAA+B,CAAC;AAEpE,MAAM,MAAM,gBAAgB,GAAG;IAC7B,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE;QAAE,aAAa,EAAE,MAAM,CAAC;QAAC,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;KAAE,CAAC;IAC1D,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB,CAAC;AAcF,KAAK,WAAW,GAAG;IACjB,QAAQ,EAAE,CAAC,GAAG,CAAC,CAAC;IAChB,YAAY,EAAE,OAAO,CAAC;IACtB,OAAO,EAAE,OAAO,CAAC;IACjB,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,MAAM,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC;IACnC,MAAM,CACJ,SAAS,EAAE,MAAM,EACjB,GAAG,EAAE,MAAM,GAAG,SAAS,GACtB,OAAO,CAAC;QAAE,MAAM,EAAE,gBAAgB,EAAE,CAAC;QAAC,GAAG,EAAE,MAAM,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAC7F,IAAI,CAAC,KAAK,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;CACrD,CAAC;A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{ RequestError } from "@agentclientprotocol/sdk/unstable";
2
2
  import { getSessionMessages } from "@anthropic-ai/claude-agent-sdk";
3
3
  import { createHash } from "node:crypto";
4
- import { open } from "node:fs/promises";
4
+ import { lstat, open } 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" };
8
8
  import { claudeConfigDir, isSessionId } from "./paths.js";
9
9
  import { findTranscript, readHistoryAcrossCompactions, readTranscriptEntriesOf, } from "./resumed-session.js";
10
10
  import { LastReportedEntity } from "./session-cursors.js";
11
- import { readHeadTailOf, readRecentCustomTitle, } from "./session-index/transcript-scan.js";
11
+ import { readHeadTailOf, readRecentCustomTitle, readSidecarTitle, } from "./session-index/transcript-scan.js";
12
12
  import { sanitizeTitle } from "./session-titles.js";
13
- import { cutAtRewindPoint } from "./session-rewind.js";
13
+ import { activeSessionMessages, readRewindPoint } from "./session-rewind.js";
14
+ import { withReplyBranches } from "./transcript-branches.js";
14
15
  export const SESSION_READ_METHOD = "_session/read";
15
16
  export const SESSION_READ_CAPABILITY = { supported: true };
16
17
  const request = z.object({
@@ -24,8 +25,55 @@ const request = z.object({
24
25
  ])
25
26
  .nullish(),
26
27
  });
28
+ function fileVersion(stats) {
29
+ const { dev, ino, mode, size, mtimeNs, ctimeNs } = stats;
30
+ return [dev, ino, mode, size, mtimeNs, ctimeNs].join(":");
31
+ }
32
+ /** Checks the transcript's metadata and the sidecar inputs read by the replay. */
33
+ async function storageUnchanged(sessionId, storage) {
34
+ try {
35
+ // A move or a different matching project must go through the ordinary lookup.
36
+ const transcript = await findTranscript(sessionId, { strict: true });
37
+ 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;
42
+ };
43
+ if (!(await matchesTranscript()))
44
+ return false;
45
+ if (storage.sidecarTitle !== undefined) {
46
+ const title = await readSidecarTitle(transcript, { strict: true });
47
+ if ((title ?? null) !== storage.sidecarTitle)
48
+ return false;
49
+ }
50
+ if (await readRewindPoint(sessionId, undefined, { transcript }))
51
+ return false;
52
+ return await matchesTranscript();
53
+ }
54
+ catch {
55
+ // An uncertain probe leaves validation and errors to the ordinary replay.
56
+ return false;
57
+ }
58
+ }
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) {
62
+ 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)));
65
+ }
66
+ function currentDirectory() {
67
+ try {
68
+ return process.cwd();
69
+ }
70
+ catch {
71
+ // The working directory could be gone; a replay with a stored cwd may still work.
72
+ return undefined;
73
+ }
74
+ }
27
75
  /** The SDK follows parent links in these records, including the branch selected by rewind.json. */
28
- export async function readSessionTranscript(sessionId, cwd) {
76
+ export async function readSessionTranscript(sessionId, cwd, observeStorage = false) {
29
77
  if (!isSessionId(sessionId)) {
30
78
  throw RequestError.invalidParams({ sessionId }, "Read the root Claude session by its UUID.");
31
79
  }
@@ -35,33 +83,50 @@ export async function readSessionTranscript(sessionId, cwd) {
35
83
  const handle = await open(transcript, "r");
36
84
  let headTail;
37
85
  let records;
86
+ let version;
38
87
  try {
39
- const { size } = await handle.stat();
88
+ const stat = await handle.stat({ bigint: true });
89
+ if (observeStorage)
90
+ version = fileVersion(stat);
91
+ const size = Number(stat.size);
40
92
  headTail = await readHeadTailOf(handle, size);
41
93
  records = await readTranscriptEntriesOf(transcript, handle, size);
42
94
  }
43
95
  finally {
44
96
  await handle.close();
45
97
  }
98
+ let sidecarTitle;
99
+ const readTitle = async (file) => {
100
+ const title = await readSidecarTitle(file, { strict: true });
101
+ sidecarTitle = title ?? null;
102
+ return title;
103
+ };
46
104
  const title = records[0]?.isSidechain === true
47
105
  ? undefined
48
- : ((await readRecentCustomTitle(transcript, headTail, { strict: true })) ??
106
+ : ((await readRecentCustomTitle(transcript, headTail, readTitle)) ??
49
107
  lastRecordedTitle(records, "custom-title", "customTitle") ??
50
108
  lastRecordedTitle(records, "ai-title", "aiTitle"));
51
109
  const dir = cwd ?? records.find((r) => typeof r.cwd === "string" && path.isAbsolute(r.cwd))?.cwd;
52
110
  const effectiveCwd = typeof dir === "string" ? dir : process.cwd();
53
- const options = {
111
+ const read = (entries) => getSessionMessages(sessionId, {
54
112
  dir: effectiveCwd,
55
- sessionStore: { append: async () => { }, load: async () => records },
56
- };
57
- const chain = await getSessionMessages(sessionId, options);
58
- const retained = await cutAtRewindPoint(sessionId, chain, undefined, { transcript });
113
+ sessionStore: { append: async () => { }, load: async () => entries },
114
+ });
115
+ // A poll must see the earlier history as a prefix (see `withReplyBranches`).
116
+ const chain = await withReplyBranches(records, await read(records), read);
117
+ const rewind = await readRewindPoint(sessionId, undefined, { transcript });
118
+ const retained = activeSessionMessages(chain, rewind);
59
119
  const messages = await readHistoryAcrossCompactions(sessionId, retained, undefined, effectiveCwd, records);
60
120
  return {
61
121
  messages,
62
122
  cwd: effectiveCwd,
63
123
  transcript,
64
124
  title: title && sanitizeTitle(title),
125
+ storage: version &&
126
+ !rewind &&
127
+ !messages.some((message) => hasIndependentHistory(message.message?.content))
128
+ ? { transcript, version, sidecarTitle }
129
+ : undefined,
65
130
  };
66
131
  }
67
132
  /**
@@ -173,6 +238,7 @@ function snapshot(frames, root, protocol, scope, previous, historyEnd = frames.l
173
238
  export class SessionReads {
174
239
  active = new Map();
175
240
  transitions = new Map();
241
+ checkpoints = new Map();
176
242
  /** Reserve a session before load, resume, close or delete can yield. */
177
243
  async transition(sessionId, kind, run) {
178
244
  if (sessionId === undefined)
@@ -183,6 +249,7 @@ export class SessionReads {
183
249
  throw alreadyOpen(sessionId);
184
250
  read.invalidated = true;
185
251
  }
252
+ this.checkpoints.delete(sessionId);
186
253
  this.transitions.set(sessionId, (this.transitions.get(sessionId) ?? 0) + 1);
187
254
  try {
188
255
  return await run();
@@ -199,7 +266,8 @@ export class SessionReads {
199
266
  const parsed = request.safeParse(params);
200
267
  if (!parsed.success)
201
268
  throw RequestError.invalidParams(undefined, parsed.error.issues[0]?.message);
202
- const { sessionId, cwd, replayFrom } = parsed.data;
269
+ const { sessionId, replayFrom } = parsed.data;
270
+ const cwd = parsed.data.cwd ?? undefined;
203
271
  const previous = replayFrom?.type === "cursor" ? replayFrom.cursorId : undefined;
204
272
  if (replayFrom?.type === "cursor" &&
205
273
  (typeof previous !== "string" || !previous || !options.cursors))
@@ -215,10 +283,21 @@ export class SessionReads {
215
283
  throw alreadyOpen(sessionId);
216
284
  };
217
285
  check();
286
+ options.assertRoot?.(sessionId);
218
287
  this.active.set(sessionId, read);
288
+ const useCursor = options.cursors && replayFrom != null;
289
+ const processCwd = useCursor ? currentDirectory() : undefined;
290
+ const scopeFor = (effectiveCwd) => json([
291
+ sessionId,
292
+ effectiveCwd,
293
+ claudeConfigDir(),
294
+ options.protocol,
295
+ options.capabilities,
296
+ packageJson.version,
297
+ ]);
219
298
  const replay = async () => {
220
299
  try {
221
- const view = await options.replay(sessionId, cwd ?? undefined);
300
+ const view = await options.replay(sessionId, cwd, useCursor);
222
301
  if (options.protocol === 1 && view.title)
223
302
  view.frames.push({
224
303
  sessionId,
@@ -239,59 +318,89 @@ export class SessionReads {
239
318
  }, `Could not read the history of ${sessionId}. Retry the read. ${String(error)}`);
240
319
  }
241
320
  };
242
- try {
243
- const { frames, cwd: effectiveCwd, historyEnd, title } = await replay();
244
- check();
245
- let outgoing = frames;
246
- let cursorId;
247
- const useCursor = options.cursors && replayFrom != null;
248
- if (useCursor) {
249
- const scope = json([
250
- sessionId,
251
- effectiveCwd,
252
- claudeConfigDir(),
253
- options.protocol,
254
- options.capabilities,
255
- packageJson.version,
256
- ]);
257
- const next = snapshot(frames, sessionId, options.protocol, scope, cursor, historyEnd);
258
- outgoing = next.outgoing;
259
- cursorId = next.cursorId;
260
- if (cursorId && cursorId !== cursor) {
261
- // A terminal can append or rewind between the reads of the root and a child.
262
- const again = await replay();
263
- check();
264
- if (again.cwd !== effectiveCwd ||
265
- again.historyEnd !== historyEnd ||
266
- frames.length !== again.frames.length ||
267
- frames.some((frame, i) => json(frame) !== json(again.frames[i]))) {
268
- throw RequestError.internalError({ sessionId, retryable: true }, "History changed during the read. Retry with the last successful cursor.");
269
- }
270
- const end = outgoing.findIndex((frame) => frame.sessionId === sessionId && frame.update.sessionUpdate === "replay_complete");
271
- outgoing.splice(end < 0 ? outgoing.length : end, 0, {
272
- sessionId,
273
- update: {
274
- sessionUpdate: "cursor_update",
275
- cursorId,
276
- anchor: next.anchor,
277
- capabilities: { read: {} },
278
- },
279
- });
280
- }
321
+ const deliver = async (outgoing, cursorId, title) => {
322
+ for (const frame of outgoing) {
323
+ check();
324
+ await options.send(frame);
281
325
  }
282
326
  // On v2 the title is current session info, outside the replay cursor.
283
327
  if (options.protocol === 2 && (title || useCursor)) {
284
- outgoing.push({
328
+ check();
329
+ await options.send({
285
330
  sessionId,
286
331
  update: { sessionUpdate: "session_info_update", title: title || null },
287
332
  });
288
333
  }
289
- for (const frame of outgoing) {
334
+ check();
335
+ return cursorId ? { cursorId } : {};
336
+ };
337
+ try {
338
+ const cached = cursor ? this.checkpoints.get(sessionId) : undefined;
339
+ if (cached &&
340
+ cached.cursorId === cursor &&
341
+ (cached.requestedCwd === cwd || cached.cwd === cwd) &&
342
+ 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);
347
+ }
348
+ check();
349
+ if (useCursor)
350
+ this.checkpoints.delete(sessionId);
351
+ const { frames, cwd: effectiveCwd, historyEnd, title, storage } = await replay();
352
+ check();
353
+ 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);
357
+ let verifiedStorage = storage;
358
+ const isRootBoundary = (frame) => frame.sessionId === sessionId && frame.update.sessionUpdate === "replay_complete";
359
+ if (cursorId && cursorId !== cursor) {
360
+ // A terminal can append or rewind between the reads of the root and a child.
361
+ const again = await replay();
290
362
  check();
291
- await options.send(frame);
363
+ if (again.cwd !== effectiveCwd ||
364
+ again.historyEnd !== historyEnd ||
365
+ frames.length !== again.frames.length ||
366
+ frames.some((frame, i) => json(frame) !== json(again.frames[i]))) {
367
+ throw RequestError.internalError({ sessionId, retryable: true }, "History changed during the read. Retry with the last successful cursor.");
368
+ }
369
+ if (again.storage?.transcript !== storage?.transcript ||
370
+ again.storage?.version !== storage?.version ||
371
+ again.storage?.sidecarTitle !== storage?.sidecarTitle) {
372
+ verifiedStorage = undefined;
373
+ }
374
+ const end = outgoing.findIndex(isRootBoundary);
375
+ outgoing.splice(end < 0 ? outgoing.length : end, 0, {
376
+ sessionId,
377
+ update: {
378
+ sessionUpdate: "cursor_update",
379
+ cursorId,
380
+ anchor,
381
+ capabilities: { read: {} },
382
+ },
383
+ });
292
384
  }
385
+ // Pair the cursor only with the inputs read by its render, never a later append.
386
+ const result = await deliver(outgoing, cursorId, title);
293
387
  check();
294
- return cursorId ? { cursorId } : {};
388
+ if (cursorId && verifiedStorage && processCwd && processCwd === currentDirectory()) {
389
+ this.checkpoints.set(sessionId, {
390
+ cursorId,
391
+ scope,
392
+ requestedCwd: cwd,
393
+ cwd: effectiveCwd,
394
+ processCwd,
395
+ storage: verifiedStorage,
396
+ boundaries: frames.filter(isRootBoundary),
397
+ title,
398
+ });
399
+ if (this.checkpoints.size > 32) {
400
+ this.checkpoints.delete(this.checkpoints.keys().next().value);
401
+ }
402
+ }
403
+ return result;
295
404
  }
296
405
  finally {
297
406
  this.active.delete(sessionId);
@@ -1 +1 @@
1
- {"version":3,"file":"subagent-history.d.ts","sourceR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D,sFAAsF;AACtF,wBAAsB,0BAA0B,CAC9C,SAAS,EAAE,MAAM,EACjB,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,eAAe,EACxB,QAAQ,EAAE,MAAM,GACf,OAAO,CAAC,cAAc,EAAE,CAAC,CAmB3B;AAyBD;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,cAAc,EAAE,GAAG,cAAc,EAAE,CAkB5E"}
@@ -5,6 +5,7 @@ import path from "node:path";
5
5
  import readline from "node:readline";
6
6
  import { isNativeSubagentControlTool } from "./native-subagents.js";
7
7
  import { findTranscript, readTranscriptEntries } from "./resumed-session.js";
8
+ import { withReplyBranches } from "./transcript-branches.js";
8
9
  /**
9
10
  * Finds the subagent transcripts of a session.
10
11
  *
@@ -248,16 +249,53 @@ export async function readSubagentMessages(sessionId, agentId, history, logger)
248
249
  try {
249
250
  if (history.dir) {
250
251
  const messages = await getSubagentMessages(sessionId, agentId, { dir: history.dir });
251
- if (messages.length > 0)
252
- return stripForkPrefix(messages);
252
+ if (messages.length > 0) {
253
+ return stripForkPrefix(await withSubagentBranches(sessionId, agentId, history, messages));
254
+ }
253
255
  }
254
- return stripForkPrefix(await getSubagentMessages(sessionId, agentId));
256
+ const messages = await getSubagentMessages(sessionId, agentId);
257
+ return stripForkPrefix(await withSubagentBranches(sessionId, agentId, history, messages));
255
258
  }
256
259
  catch (error) {
257
260
  logger.error(`Failed to read the history of subagent ${agentId}:`, error);
258
261
  return [];
259
262
  }
260
263
  }
264
+ /**
265
+ * The chain of the subagent `agentId` in its transcript records `entries`,
266
+ * with the branches of its model replies (see {@link withReplyBranches}).
267
+ */
268
+ async function readSubagentChain(sessionId, agentId, entries) {
269
+ const read = (records) => getSubagentMessages(sessionId, agentId, {
270
+ sessionStore: { append: async () => { }, load: async () => records },
271
+ });
272
+ return withReplyBranches(entries, await read(entries), read);
273
+ }
274
+ /**
275
+ * `messages`, the chain that the SDK read from the files of the subagent
276
+ * `agentId`, with the branches of its model replies. It is `messages` when
277
+ * the transcript in `history.directory` cannot be read.
278
+ */
279
+ async function withSubagentBranches(sessionId, agentId, history, messages) {
280
+ if (messages.length === 0 || !history.directory)
281
+ return messages;
282
+ let entries;
283
+ try {
284
+ entries = await readTranscriptEntries(path.join(history.directory, `agent-${agentId}.jsonl`));
285
+ }
286
+ catch {
287
+ return messages;
288
+ }
289
+ const read = async (records) => (await getSubagentMessages(sessionId, agentId, {
290
+ sessionStore: { append: async () => { }, load: async () => records },
291
+ })).map((message) => ({
292
+ ...message,
293
+ // The SDK reads these fields from agent-*.meta.json only with its filesystem store.
294
+ parent_tool_use_id: messages[0].parent_tool_use_id,
295
+ parent_agent_id: messages[0].parent_agent_id,
296
+ }));
297
+ return withReplyBranches(entries, messages, read);
298
+ }
261
299
  /** Whether a filesystem error means a file does not exist. */
262
300
  function isMissing(error) {
263
301
  return error?.code === "ENOENT";
@@ -276,8 +314,7 @@ export async function readSubagentMessagesOrFail(sessionId, agentId, history, la
276
314
  const file = path.join(history.directory, `agent-${agentId}.jsonl`);
277
315
  try {
278
316
  const entries = await readTranscriptEntries(file);
279
- const sessionStore = { append: async () => { }, load: async () => entries };
280
- const messages = await getSubagentMessages(sessionId, agentId, { sessionStore });
317
+ const messages = await readSubagentChain(sessionId, agentId, entries);
281
318
  // The SDK reads these fields from agent-*.meta.json only with its filesystem store.
282
319
  const parent = history.agents.get(launchId)?.parentAgentId ?? null;
283
320
  return stripForkPrefix(messages.map((message) => ({
@@ -0,0 +1,44 @@
1
+ import type { SessionMessage, SessionStoreEntry } from "@anthropic-ai/claude-agent-sdk";
2
+ /**
3
+ * The history of a transcript with each record of a model reply's branches,
4
+ * in file order. `chain` is what the SDK read from `entries`, and `read`
5
+ * reads the history from other entries in the same way.
6
+ *
7
+ * Claude Code writes each tool_use block of one model reply as its own
8
+ * record, and parents the result of each call on the record of that call. A
9
+ * record that comes with a result, such as the text of a Skill, has that
10
+ * result as parent. So parallel calls make one branch per call. The SDK reads
11
+ * one chain, from the last record back by `parentUuid`, and adds some of the
12
+ * other records of the reply after the last chain record of the reply. So a
13
+ * new record can move a record of the reply or drop it from the history:
14
+ *
15
+ * - a third tool_use of the reply, with the second result as parent, moves
16
+ * the first result after it;
17
+ * - the second result drops a record whose parent is the first result.
18
+ *
19
+ * The earlier history is then no prefix of the later one, and a record that
20
+ * a client got is gone. Here each reply of the chain keeps every record that
21
+ * grows from its records, up to the next reply, in file order, as Claude
22
+ * Code appended them. A record whose branch leads to another reply is an
23
+ * other history, such as the prompt before a rewind, and stays out. A
24
+ * record that Claude Code wrote after the next record of the chain, or after
25
+ * the last record of the chain, stays out too: it would go before a record
26
+ * that a client already got. A later read adds a record of the second kind
27
+ * when a record after it comes.
28
+ *
29
+ * The SDK still converts and selects the records: they go back to `read`
30
+ * with the `parentUuid` of each record of a changed reply set to the record
31
+ * before it in file order. The result is `chain` when no reply changes, or
32
+ * when `read` drops a message of `chain` or gives another order.
33
+ */
34
+ export declare function withReplyBranches(entries: readonly SessionStoreEntry[], chain: SessionMessage[], read: (entries: SessionStoreEntry[]) => Promise<SessionMessage[]>): Promise<SessionMessage[]>;
35
+ /**
36
+ * The record order of {@link withReplyBranches} for the SDK chain `chain`
37
+ * (its uuids), and the entries to read it from. Undefined when the chain
38
+ * already has that order.
39
+ */
40
+ export declare function replyBranchOrder(entries: readonly SessionStoreEntry[], chain: readonly string[]): {
41
+ order: string[];
42
+ entries: SessionStoreEntry[];
43
+ } | undefined;
44
+ //# sourceMappingURL=transcript-branches.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transcript-branches.d.ts","sourceRoot":"","sources":["../src/transcript-branches.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAC;AAWxF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,wBAAsB,iBAAiB,CACrC,OAAO,EAAE,SAAS,iBAAiB,EAAE,EACrC,KAAK,EAAE,cAAc,EAAE,EACvB,IAAI,EAAE,CAAC,OAAO,EAAE,iBAAiB,EAAE,KAAK,OAAO,CAAC,cAAc,EAAE,CAAC,GAChE,OAAO,CAAC,cAAc,EAAE,CAAC,CAkB3B;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAC9B,OAAO,EAAE,SAAS,iBAAiB,EAAE,EACrC,KAAK,EAAE,SAAS,MAAM,EAAE,GACvB;IAAE,KAAK,EAAE,MAAM,EAAE,CAAC;IAAC,OAAO,EAAE,iBAAiB,EAAE,CAAA;CAAE,GAAG,SAAS,CAuI/D"}
@@ -0,0 +1,228 @@
1
+ /**
2
+ * The history of a transcript with each record of a model reply's branches,
3
+ * in file order. `chain` is what the SDK read from `entries`, and `read`
4
+ * reads the history from other entries in the same way.
5
+ *
6
+ * Claude Code writes each tool_use block of one model reply as its own
7
+ * record, and parents the result of each call on the record of that call. A
8
+ * record that comes with a result, such as the text of a Skill, has that
9
+ * result as parent. So parallel calls make one branch per call. The SDK reads
10
+ * one chain, from the last record back by `parentUuid`, and adds some of the
11
+ * other records of the reply after the last chain record of the reply. So a
12
+ * new record can move a record of the reply or drop it from the history:
13
+ *
14
+ * - a third tool_use of the reply, with the second result as parent, moves
15
+ * the first result after it;
16
+ * - the second result drops a record whose parent is the first result.
17
+ *
18
+ * The earlier history is then no prefix of the later one, and a record that
19
+ * a client got is gone. Here each reply of the chain keeps every record that
20
+ * grows from its records, up to the next reply, in file order, as Claude
21
+ * Code appended them. A record whose branch leads to another reply is an
22
+ * other history, such as the prompt before a rewind, and stays out. A
23
+ * record that Claude Code wrote after the next record of the chain, or after
24
+ * the last record of the chain, stays out too: it would go before a record
25
+ * that a client already got. A later read adds a record of the second kind
26
+ * when a record after it comes.
27
+ *
28
+ * The SDK still converts and selects the records: they go back to `read`
29
+ * with the `parentUuid` of each record of a changed reply set to the record
30
+ * before it in file order. The result is `chain` when no reply changes, or
31
+ * when `read` drops a message of `chain` or gives another order.
32
+ */
33
+ export async function withReplyBranches(entries, chain, read) {
34
+ const plan = replyBranchOrder(entries, chain.map((message) => message.uuid));
35
+ if (!plan)
36
+ return chain;
37
+ const history = await read(plan.entries);
38
+ // The SDK leaves out some records, such as a meta prompt of the main thread.
39
+ // The result must keep each message of `chain`, in the planned order.
40
+ const kept = new Set(history.map((message) => message.uuid));
41
+ if (chain.some((message) => !kept.has(message.uuid)))
42
+ return chain;
43
+ let at = 0;
44
+ for (const message of history) {
45
+ while (at < plan.order.length && plan.order[at] !== message.uuid)
46
+ at++;
47
+ if (at === plan.order.length)
48
+ return chain;
49
+ at++;
50
+ }
51
+ return history;
52
+ }
53
+ /**
54
+ * The record order of {@link withReplyBranches} for the SDK chain `chain`
55
+ * (its uuids), and the entries to read it from. Undefined when the chain
56
+ * already has that order.
57
+ */
58
+ export function replyBranchOrder(entries, chain) {
59
+ const records = entries;
60
+ const byUuid = new Map();
61
+ const position = new Map();
62
+ const children = new Map();
63
+ const replies = new Map();
64
+ records.forEach((record, index) => {
65
+ if (typeof record.uuid !== "string")
66
+ return;
67
+ if (!byUuid.has(record.uuid) && typeof record.parentUuid === "string") {
68
+ const siblings = children.get(record.parentUuid);
69
+ if (siblings)
70
+ siblings.push(record.uuid);
71
+ else
72
+ children.set(record.parentUuid, [record.uuid]);
73
+ }
74
+ if (!byUuid.has(record.uuid)) {
75
+ const id = replyId(record);
76
+ if (id !== undefined) {
77
+ const members = replies.get(id);
78
+ if (members)
79
+ members.push(record.uuid);
80
+ else
81
+ replies.set(id, [record.uuid]);
82
+ }
83
+ }
84
+ byUuid.set(record.uuid, record);
85
+ if (!position.has(record.uuid))
86
+ position.set(record.uuid, index);
87
+ });
88
+ const inChain = new Set(chain);
89
+ const order = [];
90
+ /** The records of each changed reply, of every type, in file order. */
91
+ const relinked = [];
92
+ const done = new Set();
93
+ for (let at = 0; at < chain.length;) {
94
+ const record = byUuid.get(chain[at]);
95
+ const id = record && replyId(record);
96
+ if (!record || id === undefined || done.has(id)) {
97
+ order.push(chain[at]);
98
+ at++;
99
+ continue;
100
+ }
101
+ done.add(id);
102
+ const region = growth(record, id);
103
+ let end = at;
104
+ while (end < chain.length && region.has(chain[end]))
105
+ end++;
106
+ const run = chain.slice(at, end);
107
+ // A record that Claude Code wrote after the next record of the chain would
108
+ // go before a record that a client already got, so it stays out. So does a
109
+ // record after the last one of the chain: the SDK ends the history at the
110
+ // record that it chose, and a later read adds the record after it.
111
+ // The SDK can move an earlier record of the run to its end, so the newest
112
+ // record of the run sets the limit, not the last one.
113
+ const limit = end < chain.length
114
+ ? position.get(chain[end])
115
+ : Math.max(...run.map((uuid) => position.get(uuid))) + 1;
116
+ const sorted = [...region]
117
+ .filter((uuid) => inChain.has(uuid) || position.get(uuid) < limit)
118
+ .sort((a, b) => position.get(a) - position.get(b));
119
+ const messages = sorted.filter((uuid) => isMessage(byUuid.get(uuid)));
120
+ // A record of the reply that the chain has at another place: keep the SDK order.
121
+ const inRun = new Set(run);
122
+ const inMessages = new Set(messages);
123
+ if (messages.some((uuid) => inChain.has(uuid) && !inRun.has(uuid)))
124
+ return undefined;
125
+ if (run.some((uuid) => !inMessages.has(uuid)))
126
+ return undefined;
127
+ order.push(...messages);
128
+ if (messages.length !== run.length || messages.some((uuid, index) => uuid !== run[index])) {
129
+ relinked.push({ region: sorted, next: chain[end] });
130
+ }
131
+ at = end;
132
+ }
133
+ if (relinked.length === 0)
134
+ return undefined;
135
+ const replaced = new Map();
136
+ const relink = (uuid, parentUuid) => {
137
+ const record = byUuid.get(uuid);
138
+ replaced.set(record, { ...(replaced.get(record) ?? record), parentUuid });
139
+ };
140
+ for (const { region, next } of relinked) {
141
+ for (let index = 1; index < region.length; index++)
142
+ relink(region[index], region[index - 1]);
143
+ if (next !== undefined)
144
+ relink(next, region.at(-1));
145
+ }
146
+ return {
147
+ order,
148
+ entries: records.map((record) => replaced.get(record) ?? record),
149
+ };
150
+ /**
151
+ * The records of the reply `id` of `first`, and each record of the same
152
+ * agent that grows from them up to the next reply. A record outside the
153
+ * chain whose branch reaches another reply is left out, with its branch.
154
+ */
155
+ function growth(first, id) {
156
+ const region = new Set(replies.get(id).filter((uuid) => sameAgent(byUuid.get(uuid), first)));
157
+ const queue = [...region];
158
+ /** Whether the branch of each visited record reaches a record of another reply. */
159
+ const leads = new Map();
160
+ const leadsElsewhere = (start) => {
161
+ // A walk with a stack: a branch can be thousands of records long.
162
+ const stack = [[start, false]];
163
+ const entered = new Set();
164
+ while (stack.length > 0) {
165
+ const [uuid, expanded] = stack.pop();
166
+ if (expanded) {
167
+ leads.set(uuid, (children.get(uuid) ?? []).some((child) => leads.get(child) === true));
168
+ continue;
169
+ }
170
+ // A record seen before, or a cycle of `parentUuid` links.
171
+ if (leads.has(uuid) || entered.has(uuid))
172
+ continue;
173
+ entered.add(uuid);
174
+ const other = replyId(byUuid.get(uuid));
175
+ if (other !== undefined && other !== id) {
176
+ leads.set(uuid, true);
177
+ continue;
178
+ }
179
+ stack.push([uuid, true]);
180
+ for (const child of children.get(uuid) ?? [])
181
+ stack.push([child, false]);
182
+ }
183
+ return leads.get(start) === true;
184
+ };
185
+ while (queue.length > 0) {
186
+ for (const child of children.get(queue.shift()) ?? []) {
187
+ if (region.has(child))
188
+ continue;
189
+ const record = byUuid.get(child);
190
+ const other = replyId(record);
191
+ if (other !== undefined && other !== id)
192
+ continue;
193
+ if (!sameAgent(record, first))
194
+ continue;
195
+ // A prompt outside the chain is a prompt that the user left, such as
196
+ // the prompt before an edit or a rewind.
197
+ if (!inChain.has(child) && (isPrompt(record) || leadsElsewhere(child)))
198
+ continue;
199
+ region.add(child);
200
+ queue.push(child);
201
+ }
202
+ }
203
+ return region;
204
+ }
205
+ }
206
+ /** The `message.id` of the model reply of an assistant record, or undefined. */
207
+ function replyId(record) {
208
+ if (record.type !== "assistant")
209
+ return undefined;
210
+ const id = record.message?.id;
211
+ return typeof id === "string" ? id : undefined;
212
+ }
213
+ /** Whether `record` is a prompt: a user record with no tool result that is not a meta record. */
214
+ function isPrompt(record) {
215
+ if (record.type !== "user" || record.isMeta === true)
216
+ return false;
217
+ const content = record.message?.content;
218
+ return !(Array.isArray(content) &&
219
+ content.some((block) => block?.type === "tool_result"));
220
+ }
221
+ /** Whether the SDK gives `record` as a message of the history. */
222
+ function isMessage(record) {
223
+ return record.type === "user" || record.type === "assistant";
224
+ }
225
+ /** Whether two records belong to one thread: the main thread or one subagent. */
226
+ function sameAgent(a, b) {
227
+ return (a.isSidechain === true) === (b.isSidechain === true) && a.agentId === b.agentId;
228
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"session-read.d.ts","sourceRoot":"","sources":["../../src/v1/session-read.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAuB,MAAM,mCAAmC,CAAC;AACjG,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAKlD,0EAA0E;AAC1E,MAAM,MAAM,cAAc,GAAG;IAC3B,QAAQ,EAAE,cAAc,EAAE,CAAC;IAC3B,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,SAAS,CAAC,eAAe,CAAC,CAAC;IACpC,UAAU,EAAE,MAAM,IAAI,CAAC;IACvB,MAAM,EAAE,WAAW,CAAC;CACrB,CAAC;AAEF,qBAAa,cAAc;IAIb,OAAO,CAAC,QAAQ,CAAC,MAAM;IAHnC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAsB;IAC5C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAyB;gBAEnB,MAAM,EAAE,IAAI,CAAC,SAAS,EAAE,eAAe,CAAC;IAErE,OAAO,IAAI,IAAI;IAIf,QAAQ,CAAC,UAAU,kGAA0C;IAE7D,IAAI,CACF,MAAM,EAAE,OAAO,EACf,OAAO,EAAE;QACP,YAAY,EAAE,kBAAkB,GAAG,SAAS,CAAC;QAC7C,SAAS,EAAE,OAAO,CAAC;QACnB,MAAM,CAAC,EA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AkB,GAAG,SAAS,CAAC;QAC7C,SAAS,EAAE,OAAO,CAAC;QACnB,MAAM,CAAC,EAAE,WAAW,CAAC;QACrB,MAAM,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,OAAO,CAAC;QACvC,UAAU,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,IAAI,CAAC;QACxC,WAAW,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,MAAM,CAAC;QACvC,MAAM,EAAE,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,cAAc,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;KACnF,GACA,OAAO,CAAC;QAAE,QAAQ,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;CAkDlC"}
@@ -20,10 +20,10 @@ export class V1SessionReads {
20
20
  capabilities: options.capabilities,
21
21
  cursors: options.capabilities?.session?.cursors != null,
22
22
  isOpen: options.isOpen,
23
+ assertRoot: options.assertRoot,
23
24
  signal,
24
- replay: async (sessionId, cwd) => {
25
- options.assertRoot(sessionId);
26
- const transcript = await readSessionTranscript(sessionId, cwd);
25
+ replay: async (sessionId, cwd, observeStorage) => {
26
+ const transcript = await readSessionTranscript(sessionId, cwd, observeStorage);
27
27
  signal.throwIfAborted();
28
28
  const frames = [];
29
29
  let historyEnd;
@@ -52,6 +52,7 @@ export class V1SessionReads {
52
52
  return {
53
53
  frames,
54
54
  cwd: transcript.cwd,
55
+ storage: transcript.storage,
55
56
  historyEnd,
56
57
  title: transcript.title === undefined ? undefined : options.clientTitle(transcript.title),
57
58
  };
package/dist/v2/agent.js CHANGED
@@ -312,7 +312,7 @@ class V2Agent {
312
312
  cursors: true,
313
313
  signal,
314
314
  isOpen: (sessionId) => this.sessions.has(sessionId) || this.stopped.has(sessionId) || this.starting.has(sessionId),
315
- replay: (sessionId, cwd) => renderSessionRead(sessionId, cwd, this.logger, capabilities),
315
+ replay: (sessionId, cwd, observeStorage) => renderSessionRead(sessionId, cwd, this.logger, capabilities, observeStorage),
316
316
  send: (frame) => this.ctx.notify(v2.methods.client.session.update, frame),
317
317
  });
318
318
  }
@@ -2,10 +2,15 @@ import type * as v2 from "@agentclientprotocol/sdk/experimental/v2/unstable";
2
2
  import type { Logger } from "../logger.js";
3
3
  import { type SessionReadFrame } from "../session-read.js";
4
4
  /** Renders a stored history without the connection's live tool calls or child sessions. */
5
- export declare function renderSessionRead(sessionId: string, dir: string | undefined, logger: Logger, capabilities: v2.ClientCapabilities | null | undefined): Promise<{
5
+ export declare function renderSessionRead(sessionId: string, dir: string | undefined, logger: Logger, capabilities: v2.ClientCapabilities | null | undefined, observeStorage: boolean): Promise<{
6
6
  frames: SessionReadFrame[];
7
7
  cwd: string;
8
8
  historyEnd: number;
9
- title?: string;
9
+ title: string | undefined;
10
+ storage: {
11
+ transcript: string;
12
+ version: string;
13
+ sidecarTitle: string | null | undefined;
14
+ } | undefined;
10
15
  }>;
11
16
  //# sourceMappingURL=session-read.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"session-read.d.ts","sourceRoot":"","sources":["../../src/v2/session-read.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,EAAE,MAAM,mDAAmD,CAAC;AAC7E,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAyB,KAAK,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAMlF,2FAA2F;AAC3F,wBAAsB,iBAAiB,CACrC,SAAS,EAAE,MAAM,EACjB,GAAG,EAAE,MAAM,GAAG,SAAS,EACvB,MAAM,EAAE,MAAM,EACd,YAAY,EAAE,EAAE,CAAC,kBAAkB,GAAG,IAAI,GAAG,SAAS,GACrD,OAAO,CAAC;IAAE,MAAM,EAAE,gBAAgB,EAAE,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,CA+B1F"}
1
+ {"version":3,"file":"session-read.d.ts","sourceRoot":"","sources":["../../src/v2/session-read.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,EAAE,MAAM,mDAAmD,CAAC;AAC7E,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAyB,KAAK,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAMlF,2FAA2F;AAC3F,wBAAsB,iBAAiB,CACrC,SAAS,EAAE,MAAM,EACjB,GAAG,EAAE,MAAM,GAAG,SAAS,EACvB,MAAM,EAAE,MAAM,EACd,YAAY,EAAE,EAAE,CAAC,kBAAkB,GAAG,IAAI,GAAG,SAAS,EACtD,cAAc,EAAE,OAAO;;;;;;;;;;GAoCxB"}
@@ -4,8 +4,8 @@ import { SessionOutput } from "./stream.js";
4
4
  import { replaySessionHistory, SubagentReplay } from "./subagent-replay.js";
5
5
  import { V2UpdateTranslator } from "./update-translator.js";
6
6
  /** Renders a stored history without the connection's live tool calls or child sessions. */
7
- export async function renderSessionRead(sessionId, dir, logger, capabilities) {
8
- const { messages, cwd, transcript, title } = await readSessionTranscript(sessionId, dir);
7
+ export async function renderSessionRead(sessionId, dir, logger, capabilities, observeStorage) {
8
+ const { messages, cwd, transcript, title, storage } = await readSessionTranscript(sessionId, dir, observeStorage);
9
9
  const frames = [];
10
10
  const translator = new V2UpdateTranslator();
11
11
  const send = (notification) => {
@@ -24,5 +24,5 @@ export async function renderSessionRead(sessionId, dir, logger, capabilities) {
24
24
  if (end)
25
25
  send({ sessionId, update: end });
26
26
  subagents?.reportMissingHistory();
27
- return { frames, cwd, historyEnd, title };
27
+ return { frames, cwd, historyEnd, title, storage };
28
28
  }
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "0.114.0",
6
+ "version": "0.114.1-preview.2",
7
7
  "description": "An ACP-compatible coding agent powered by the Claude Agent SDK (TypeScript)",
8
8
  "main": "dist/lib.js",
9
9
  "types": "dist/lib.d.ts",