@agentclientprotocol/claude-agent-acp 0.113.1-preview.9 → 0.114.1-preview.1

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.
Files changed (61) hide show
  1. package/README.md +2 -0
  2. package/dist/query-settings.d.ts +42 -0
  3. package/dist/query-settings.d.ts.map +1 -0
  4. package/dist/query-settings.js +43 -0
  5. package/dist/resumed-session.d.ts +9 -2
  6. package/dist/resumed-session.d.ts.map +1 -1
  7. package/dist/resumed-session.js +51 -7
  8. package/dist/sdk-to-acp.js +4 -2
  9. package/dist/session-cursors.d.ts +1 -1
  10. package/dist/session-cursors.d.ts.map +1 -1
  11. package/dist/session-cursors.js +8 -2
  12. package/dist/session-index/transcript-scan.d.ts +11 -3
  13. package/dist/session-index/transcript-scan.d.ts.map +1 -1
  14. package/dist/session-index/transcript-scan.js +21 -5
  15. package/dist/session-mode.d.ts +31 -2
  16. package/dist/session-mode.d.ts.map +1 -1
  17. package/dist/session-mode.js +35 -5
  18. package/dist/session-model.d.ts +4 -1
  19. package/dist/session-model.d.ts.map +1 -1
  20. package/dist/session-model.js +26 -4
  21. package/dist/session-read.d.ts +59 -0
  22. package/dist/session-read.d.ts.map +1 -0
  23. package/dist/session-read.js +407 -0
  24. package/dist/session-rewind.d.ts +6 -2
  25. package/dist/session-rewind.d.ts.map +1 -1
  26. package/dist/session-rewind.js +13 -4
  27. package/dist/session-ultracode.d.ts +4 -1
  28. package/dist/session-ultracode.d.ts.map +1 -1
  29. package/dist/session-ultracode.js +14 -25
  30. package/dist/settings.d.ts +34 -0
  31. package/dist/settings.d.ts.map +1 -1
  32. package/dist/settings.js +55 -4
  33. package/dist/subagent-history.d.ts +9 -1
  34. package/dist/subagent-history.d.ts.map +1 -1
  35. package/dist/subagent-history.js +55 -13
  36. package/dist/v1/acp-agent.d.ts +6 -0
  37. package/dist/v1/acp-agent.d.ts.map +1 -1
  38. package/dist/v1/acp-agent.js +146 -72
  39. package/dist/v1/session-read.d.ts +31 -0
  40. package/dist/v1/session-read.d.ts.map +1 -0
  41. package/dist/v1/session-read.js +63 -0
  42. package/dist/v2/agent.d.ts.map +1 -1
  43. package/dist/v2/agent.js +62 -27
  44. package/dist/v2/config.d.ts +6 -5
  45. package/dist/v2/config.d.ts.map +1 -1
  46. package/dist/v2/config.js +4 -1
  47. package/dist/v2/session-read.d.ts +16 -0
  48. package/dist/v2/session-read.d.ts.map +1 -0
  49. package/dist/v2/session-read.js +28 -0
  50. package/dist/v2/setup.d.ts +4 -1
  51. package/dist/v2/setup.d.ts.map +1 -1
  52. package/dist/v2/setup.js +4 -2
  53. package/dist/v2/stream.d.ts +9 -13
  54. package/dist/v2/stream.d.ts.map +1 -1
  55. package/dist/v2/stream.js +10 -9
  56. package/dist/v2/subagent-replay.d.ts +16 -4
  57. package/dist/v2/subagent-replay.d.ts.map +1 -1
  58. package/dist/v2/subagent-replay.js +22 -10
  59. package/dist/v2/tasks.d.ts.map +1 -1
  60. package/dist/v2/tasks.js +5 -3
  61. package/package.json +1 -1
@@ -602,7 +602,9 @@ export function withCurrentModelInfo(allowedModels, sdkModels, currentModelId) {
602
602
  function isPreModelSwitchHookBlock(error) {
603
603
  return error instanceof Error && error.message.includes("blocked by a PreModelSwitch hook");
604
604
  }
605
- export async function getAvailableModels(query, models, sdkModels, settingsManager, logger, isResumedSession, sessionId, resumedModelHint, narrowedByGateway = false) {
605
+ export async function getAvailableModels(query, models, sdkModels, settingsManager, logger, isResumedSession, sessionId, resumedModelHint, narrowedByGateway = false,
606
+ /** Claude Code's `get_settings` answer for this query, read after `initialize`. */
607
+ cliSettings) {
606
608
  // A gateway that lists none of the SDK's models leaves none to offer
607
609
  // (`narrowToGatewayModels`). The session stays on the model the SDK runs,
608
610
  // and the gateway refuses its requests.
@@ -612,7 +614,13 @@ export async function getAvailableModels(query, models, sdkModels, settingsManag
612
614
  currentModelId: (isResumedSession && resumedModelHint) || sdkModels[0]?.value || "default",
613
615
  };
614
616
  }
615
- const settings = settingsManager.getSettings();
617
+ // The `model` setting as the running CLI resolved it, which also counts the
618
+ // tiers that `settingsManager` does not read (the `settings` option of the
619
+ // query). Without the CLI's answer, the settings of this process.
620
+ const settings = cliSettings?.effective ?? settingsManager.getSettings();
621
+ const appliedModel = typeof cliSettings?.applied?.model === "string" && cliSettings.applied.model.trim()
622
+ ? cliSettings.applied.model
623
+ : undefined;
616
624
  let currentModel = models[0];
617
625
  let resolvedFromInput;
618
626
  // Model priority (highest to lowest):
@@ -644,7 +652,7 @@ export async function getAvailableModels(query, models, sdkModels, settingsManag
644
652
  currentModel = resumedModelHint ? matchResumedModel(models, resumedModelHint) : currentModel;
645
653
  }
646
654
  // Skip the setModel round-trip when we can prove the SDK has already landed
647
- // on the same model. Two cases qualify:
655
+ // on the same model. Three cases qualify:
648
656
  // (a) No override applied — currentModel is the SDK's own default (or, on
649
657
  // resume, the live model read back from the SDK above); nothing to sync.
650
658
  // (b) The resolver returned the user's input verbatim AND that value exists
@@ -654,6 +662,8 @@ export async function getAvailableModels(query, models, sdkModels, settingsManag
654
662
  // This only holds for fresh sessions: a resumed session lands on the
655
663
  // transcript's model regardless of env/settings, so the override must
656
664
  // be re-asserted to keep the reported model truthful.
665
+ // (c) The CLI reports that it runs the model that `currentModel` resolves
666
+ // to (`cliRunsSelectedModel` below), on a fresh or a resumed session.
657
667
  // Anything else (fuzzy match, allowlist-synthesized value, alias) gets a
658
668
  // setModel call so we don't drift from the user's intended pin.
659
669
  // Case (a) does not hold when `narrowToGatewayModels` left the SDK on a
@@ -680,7 +690,19 @@ export async function getAvailableModels(query, models, sdkModels, settingsManag
680
690
  }
681
691
  // When the switch fails, the SDK stays on the model it ran before it.
682
692
  const modelBeforeSwitch = () => switchToListed && sdkDefault !== undefined ? sdkDefault : models[0];
683
- const skipSetModel = (resolvedFromInput === undefined && !switchToListed) ||
693
+ // `applied.model` is the model that the CLI runs: `claude-sonnet-5-5` for a
694
+ // `claude-sonnet-5-5[1m]` pin (it drops the hint of a model whose only
695
+ // window is 1M), `claude-sonnet-4-6[1m]` for the 1M lane of a model that
696
+ // also has a 200k one. The ids are compared with their hints, so a session
697
+ // on the 200k lane still gets a `[1m]` row set. On a resumed session the
698
+ // CLI has restored the transcript's model before it answers `get_settings`
699
+ // (seen on 2.1.333); nothing here enforces that order.
700
+ const cliRunsSelectedModel = appliedModel !== undefined &&
701
+ sdkSawSameValue &&
702
+ canonicalizeModelId(currentModel.resolvedModel ?? currentModel.value) ===
703
+ canonicalizeModelId(appliedModel);
704
+ const skipSetModel = cliRunsSelectedModel ||
705
+ (resolvedFromInput === undefined && !switchToListed) ||
684
706
  (!isResumedSession && currentModel.value === resolvedFromInput && sdkSawSameValue);
685
707
  if (!skipSetModel) {
686
708
  const setModelStartedAt = performance.now();
@@ -0,0 +1,59 @@
1
+ export declare const SESSION_READ_METHOD = "_session/read";
2
+ export declare const SESSION_READ_CAPABILITY: {
3
+ readonly supported: true;
4
+ };
5
+ export type SessionReadFrame = {
6
+ sessionId: string;
7
+ update: {
8
+ sessionUpdate: string;
9
+ [key: string]: unknown;
10
+ };
11
+ [key: string]: unknown;
12
+ };
13
+ type ReadOptions = {
14
+ protocol: 1 | 2;
15
+ capabilities: unknown;
16
+ cursors: boolean;
17
+ signal?: AbortSignal;
18
+ isOpen(sessionId: string): boolean;
19
+ assertRoot?(sessionId: string): void;
20
+ replay(sessionId: string, cwd: string | undefined, observeStorage: boolean): Promise<{
21
+ frames: SessionReadFrame[];
22
+ cwd: string;
23
+ historyEnd?: number;
24
+ title?: string;
25
+ storage?: SessionReadStorage;
26
+ }>;
27
+ send(frame: SessionReadFrame): Promise<void> | void;
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
+ };
35
+ /** The SDK follows parent links in these records, including the branch selected by rewind.json. */
36
+ export declare function readSessionTranscript(sessionId: string, cwd?: string, observeStorage?: boolean): Promise<{
37
+ messages: import("@anthropic-ai/claude-agent-sdk").SessionMessage[];
38
+ cwd: string;
39
+ transcript: string;
40
+ title: string | undefined;
41
+ storage: {
42
+ transcript: string;
43
+ version: string;
44
+ sidecarTitle: string | null | undefined;
45
+ } | undefined;
46
+ }>;
47
+ /** A read owns only a replay on this connection. Closing it invalidates the pending delivery. */
48
+ export declare class SessionReads {
49
+ private readonly active;
50
+ private readonly transitions;
51
+ private readonly checkpoints;
52
+ /** Reserve a session before load, resume, close or delete can yield. */
53
+ transition<T>(sessionId: string | undefined, kind: "open" | "close", run: () => Promise<T>): Promise<T>;
54
+ read(params: unknown, options: ReadOptions): Promise<{
55
+ cursorId?: string;
56
+ }>;
57
+ }
58
+ export {};
59
+ //# sourceMappingURL=session-read.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-read.d.ts","sourceRoot":"","sources":["../src/session-read.ts"],"names":[],"mappings":"AAwBA,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,UAAU,CAAC,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACrC,MAAM,CACJ,SAAS,EAAE,MAAM,EACjB,GAAG,EAAE,MAAM,GAAG,SAAS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-agent-sdk";
3
+ import { createHash } from "node:crypto";
4
+ import { lstat, open } from "node:fs/promises";
5
+ import path from "node:path";
6
+ import { z } from "zod";
7
+ import packageJson from "../package.json" with { type: "json" };
8
+ import { claudeConfigDir, isSessionId } from "./paths.js";
9
+ import { findTranscript, readHistoryAcrossCompactions, readTranscriptEntriesOf, } from "./resumed-session.js";
10
+ import { LastReportedEntity } from "./session-cursors.js";
11
+ import { readHeadTailOf, readRecentCustomTitle, readSidecarTitle, } from "./session-index/transcript-scan.js";
12
+ import { sanitizeTitle } from "./session-titles.js";
13
+ import { activeSessionMessages, readRewindPoint } from "./session-rewind.js";
14
+ export const SESSION_READ_METHOD = "_session/read";
15
+ export const SESSION_READ_CAPABILITY = { supported: true };
16
+ const request = z.object({
17
+ sessionId: z.string().trim().min(1),
18
+ _meta: z.record(z.string(), z.unknown()).nullish(),
19
+ cwd: z.string().refine(path.isAbsolute, "cwd must be an absolute path").nullish(),
20
+ replayFrom: z
21
+ .discriminatedUnion("type", [
22
+ z.object({ type: z.literal("start") }),
23
+ z.object({ type: z.literal("cursor"), cursorId: z.unknown().optional() }),
24
+ ])
25
+ .nullish(),
26
+ });
27
+ function fileVersion(stats) {
28
+ const { dev, ino, mode, size, mtimeNs, ctimeNs } = stats;
29
+ return [dev, ino, mode, size, mtimeNs, ctimeNs].join(":");
30
+ }
31
+ /** Checks the transcript's metadata and the sidecar inputs read by the replay. */
32
+ async function storageUnchanged(sessionId, storage) {
33
+ try {
34
+ // A move or a different matching project must go through the ordinary lookup.
35
+ const transcript = await findTranscript(sessionId, { strict: true });
36
+ if (transcript !== storage.transcript)
37
+ return false;
38
+ const matchesTranscript = async () => {
39
+ const root = await lstat(transcript, { bigint: true });
40
+ return root.isFile() && fileVersion(root) === storage.version;
41
+ };
42
+ if (!(await matchesTranscript()))
43
+ return false;
44
+ if (storage.sidecarTitle !== undefined) {
45
+ const title = await readSidecarTitle(transcript, { strict: true });
46
+ if ((title ?? null) !== storage.sidecarTitle)
47
+ return false;
48
+ }
49
+ if (await readRewindPoint(sessionId, undefined, { transcript }))
50
+ return false;
51
+ return await matchesTranscript();
52
+ }
53
+ catch {
54
+ // An uncertain probe leaves validation and errors to the ordinary replay.
55
+ return false;
56
+ }
57
+ }
58
+ /** These tools render their stored input and result, with no child or workspace reads. */
59
+ const ROOT_ONLY_TOOLS = new Set(["Bash", "PowerShell", "Read", "Write", "Edit", "Glob", "Grep"]);
60
+ function hasIndependentHistory(content) {
61
+ return (Array.isArray(content) &&
62
+ content.some((block) => ["tool_use", "server_tool_use", "mcp_tool_use"].includes(block?.type) &&
63
+ !ROOT_ONLY_TOOLS.has(block.name)));
64
+ }
65
+ function currentDirectory() {
66
+ try {
67
+ return process.cwd();
68
+ }
69
+ catch {
70
+ // The working directory could be gone; a replay with a stored cwd may still work.
71
+ return undefined;
72
+ }
73
+ }
74
+ /** The SDK follows parent links in these records, including the branch selected by rewind.json. */
75
+ export async function readSessionTranscript(sessionId, cwd, observeStorage = false) {
76
+ if (!isSessionId(sessionId)) {
77
+ throw RequestError.invalidParams({ sessionId }, "Read the root Claude session by its UUID.");
78
+ }
79
+ const transcript = await findTranscript(sessionId, { strict: true });
80
+ if (!transcript)
81
+ throw RequestError.sessionNotFound(sessionId);
82
+ const handle = await open(transcript, "r");
83
+ let headTail;
84
+ let records;
85
+ let version;
86
+ try {
87
+ const stat = await handle.stat({ bigint: true });
88
+ if (observeStorage)
89
+ version = fileVersion(stat);
90
+ const size = Number(stat.size);
91
+ headTail = await readHeadTailOf(handle, size);
92
+ records = await readTranscriptEntriesOf(transcript, handle, size);
93
+ }
94
+ finally {
95
+ await handle.close();
96
+ }
97
+ let sidecarTitle;
98
+ const readTitle = async (file) => {
99
+ const title = await readSidecarTitle(file, { strict: true });
100
+ sidecarTitle = title ?? null;
101
+ return title;
102
+ };
103
+ const title = records[0]?.isSidechain === true
104
+ ? undefined
105
+ : ((await readRecentCustomTitle(transcript, headTail, readTitle)) ??
106
+ lastRecordedTitle(records, "custom-title", "customTitle") ??
107
+ lastRecordedTitle(records, "ai-title", "aiTitle"));
108
+ const dir = cwd ?? records.find((r) => typeof r.cwd === "string" && path.isAbsolute(r.cwd))?.cwd;
109
+ const effectiveCwd = typeof dir === "string" ? dir : process.cwd();
110
+ const options = {
111
+ dir: effectiveCwd,
112
+ sessionStore: { append: async () => { }, load: async () => records },
113
+ };
114
+ const chain = await getSessionMessages(sessionId, options);
115
+ const rewind = await readRewindPoint(sessionId, undefined, { transcript });
116
+ const retained = activeSessionMessages(chain, rewind);
117
+ const messages = await readHistoryAcrossCompactions(sessionId, retained, undefined, effectiveCwd, records);
118
+ return {
119
+ messages,
120
+ cwd: effectiveCwd,
121
+ transcript,
122
+ title: title && sanitizeTitle(title),
123
+ storage: version &&
124
+ !rewind &&
125
+ !messages.some((message) => hasIndependentHistory(message.message?.content))
126
+ ? { transcript, version, sidecarTitle }
127
+ : undefined,
128
+ };
129
+ }
130
+ /**
131
+ * The `field` of the last `type` record of the snapshot, undefined when it is
132
+ * empty. The SDK reads the head and tail 64 KB windows instead, so a large
133
+ * tool result appended after the last `ai-title` would hide it from the read
134
+ * and change the title of an unchanged session.
135
+ */
136
+ function lastRecordedTitle(records, type, field) {
137
+ for (let i = records.length - 1; i >= 0; i--) {
138
+ const record = records[i];
139
+ const value = record.type === type ? record[field] : undefined;
140
+ if (typeof value === "string")
141
+ return value || undefined;
142
+ }
143
+ return undefined;
144
+ }
145
+ function invalidCursor() {
146
+ return RequestError.invalidParams({ reason: "invalid_cursor" }, "This cursor cannot continue the replay. Read from start.");
147
+ }
148
+ function alreadyOpen(sessionId) {
149
+ return RequestError.invalidRequest({ reason: "session_already_open", sessionId }, "The session is open or changing on this connection. Retry after it closes.");
150
+ }
151
+ function json(value) {
152
+ return JSON.stringify(value, (_key, member) => member && typeof member === "object" && !Array.isArray(member)
153
+ ? Object.fromEntries(Object.keys(member)
154
+ .sort()
155
+ .map((key) => [key, member[key]]))
156
+ : member);
157
+ }
158
+ function digest(value) {
159
+ return createHash("sha256").update(value).digest("base64url");
160
+ }
161
+ // A cursor carries the number of delivered updates per session. Its digest binds
162
+ // those counts to the rendering options, exact history prefixes and post-replay metadata.
163
+ const lengths = z.record(z.string(), z.int().nonnegative());
164
+ function decodeLengths(id) {
165
+ const match = /^read:v1:[\w-]{43}\.([\w-]+)$/.exec(id);
166
+ if (match) {
167
+ try {
168
+ return new Map(Object.entries(lengths.parse(JSON.parse(Buffer.from(match[1], "base64url").toString("utf8")))));
169
+ }
170
+ catch {
171
+ /* Invalid and expired cursors have the same recovery. */
172
+ }
173
+ }
174
+ throw invalidCursor();
175
+ }
176
+ function snapshot(frames, root, protocol, scope, previous, historyEnd = frames.length) {
177
+ const saved = previous ? decodeLengths(previous) : new Map();
178
+ const streams = new Map();
179
+ const entities = new LastReportedEntity();
180
+ const outgoing = [];
181
+ for (const [index, frame] of frames.entries()) {
182
+ const { sessionId, update } = frame;
183
+ // The renderer emits each child's final state on its parent after all messages.
184
+ // A later parent message precedes that same state in the next full replay.
185
+ const boundary = update.sessionUpdate === "replay_complete";
186
+ const key = index < historyEnd || boundary
187
+ ? sessionId
188
+ : json([sessionId, update.sessionUpdate, update.sessionId ?? update.subagentSessionId]);
189
+ let stream = streams.get(key);
190
+ if (!stream) {
191
+ stream = {
192
+ count: 0,
193
+ history: createHash("sha256"),
194
+ prefix: digest(""),
195
+ };
196
+ streams.set(key, stream);
197
+ }
198
+ const before = saved.get(key);
199
+ if (boundary) {
200
+ if (before === undefined || sessionId === root || stream.count > before)
201
+ outgoing.push(frame);
202
+ }
203
+ else {
204
+ stream.history.update(json(frame) + "\n");
205
+ stream.count++;
206
+ if (stream.count === before)
207
+ stream.prefix = stream.history.copy().digest("base64url");
208
+ if (before === undefined || stream.count > before)
209
+ outgoing.push(frame);
210
+ entities.sending(frame, protocol);
211
+ }
212
+ }
213
+ function cursor(prefix) {
214
+ const counts = new Map();
215
+ const hashes = new Map();
216
+ for (const [id, stream] of streams) {
217
+ const count = prefix ? saved.get(id) : stream.count;
218
+ if (count === undefined)
219
+ continue;
220
+ if (count > stream.count)
221
+ throw invalidCursor();
222
+ counts.set(id, count);
223
+ hashes.set(id, prefix ? stream.prefix : stream.history.copy().digest("base64url"));
224
+ }
225
+ const encoded = Buffer.from(json(Object.fromEntries(counts))).toString("base64url");
226
+ return "read:v1:" + digest(json([scope, encoded, Object.fromEntries(hashes)])) + "." + encoded;
227
+ }
228
+ if (previous && cursor(true) !== previous)
229
+ throw invalidCursor();
230
+ const anchor = entities.after(root);
231
+ if (previous && !anchor)
232
+ throw invalidCursor();
233
+ return { outgoing, anchor, cursorId: anchor ? cursor(false) : undefined };
234
+ }
235
+ /** A read owns only a replay on this connection. Closing it invalidates the pending delivery. */
236
+ export class SessionReads {
237
+ active = new Map();
238
+ transitions = new Map();
239
+ checkpoints = new Map();
240
+ /** Reserve a session before load, resume, close or delete can yield. */
241
+ async transition(sessionId, kind, run) {
242
+ if (sessionId === undefined)
243
+ return run();
244
+ const read = this.active.get(sessionId);
245
+ if (read) {
246
+ if (kind === "open")
247
+ throw alreadyOpen(sessionId);
248
+ read.invalidated = true;
249
+ }
250
+ this.checkpoints.delete(sessionId);
251
+ this.transitions.set(sessionId, (this.transitions.get(sessionId) ?? 0) + 1);
252
+ try {
253
+ return await run();
254
+ }
255
+ finally {
256
+ const remaining = this.transitions.get(sessionId) - 1;
257
+ if (remaining === 0)
258
+ this.transitions.delete(sessionId);
259
+ else
260
+ this.transitions.set(sessionId, remaining);
261
+ }
262
+ }
263
+ async read(params, options) {
264
+ const parsed = request.safeParse(params);
265
+ if (!parsed.success)
266
+ throw RequestError.invalidParams(undefined, parsed.error.issues[0]?.message);
267
+ const { sessionId, replayFrom } = parsed.data;
268
+ const cwd = parsed.data.cwd ?? undefined;
269
+ const previous = replayFrom?.type === "cursor" ? replayFrom.cursorId : undefined;
270
+ if (replayFrom?.type === "cursor" &&
271
+ (typeof previous !== "string" || !previous || !options.cursors))
272
+ throw invalidCursor();
273
+ const cursor = typeof previous === "string" ? previous : undefined;
274
+ if (this.active.has(sessionId))
275
+ throw alreadyOpen(sessionId);
276
+ const read = { invalidated: false };
277
+ const check = () => {
278
+ if (options.signal?.aborted)
279
+ throw RequestError.requestCancelled();
280
+ if (read.invalidated || this.transitions.has(sessionId) || options.isOpen(sessionId))
281
+ throw alreadyOpen(sessionId);
282
+ };
283
+ check();
284
+ options.assertRoot?.(sessionId);
285
+ this.active.set(sessionId, read);
286
+ const useCursor = options.cursors && replayFrom != null;
287
+ const processCwd = useCursor ? currentDirectory() : undefined;
288
+ const scopeFor = (effectiveCwd) => json([
289
+ sessionId,
290
+ effectiveCwd,
291
+ claudeConfigDir(),
292
+ options.protocol,
293
+ options.capabilities,
294
+ packageJson.version,
295
+ ]);
296
+ const replay = async () => {
297
+ try {
298
+ const view = await options.replay(sessionId, cwd, useCursor);
299
+ if (options.protocol === 1 && view.title)
300
+ view.frames.push({
301
+ sessionId,
302
+ update: { sessionUpdate: "session_info_update", title: view.title },
303
+ });
304
+ return view;
305
+ }
306
+ catch (error) {
307
+ check();
308
+ if (error instanceof RequestError)
309
+ throw error;
310
+ const file = error?.path;
311
+ throw RequestError.internalError({
312
+ sessionId,
313
+ reason: "history_read_failed",
314
+ retryable: true,
315
+ ...(file && { paths: [file] }),
316
+ }, `Could not read the history of ${sessionId}. Retry the read. ${String(error)}`);
317
+ }
318
+ };
319
+ const deliver = async (outgoing, cursorId, title) => {
320
+ for (const frame of outgoing) {
321
+ check();
322
+ await options.send(frame);
323
+ }
324
+ // On v2 the title is current session info, outside the replay cursor.
325
+ if (options.protocol === 2 && (title || useCursor)) {
326
+ check();
327
+ await options.send({
328
+ sessionId,
329
+ update: { sessionUpdate: "session_info_update", title: title || null },
330
+ });
331
+ }
332
+ check();
333
+ return cursorId ? { cursorId } : {};
334
+ };
335
+ try {
336
+ const cached = cursor ? this.checkpoints.get(sessionId) : undefined;
337
+ if (cached &&
338
+ cached.cursorId === cursor &&
339
+ (cached.requestedCwd === cwd || cached.cwd === cwd) &&
340
+ cached.processCwd === processCwd &&
341
+ cached.scope === scopeFor(cached.cwd) &&
342
+ (await storageUnchanged(sessionId, cached.storage)) &&
343
+ cached.processCwd === currentDirectory()) {
344
+ return await deliver(cached.boundaries, cached.cursorId, cached.title);
345
+ }
346
+ check();
347
+ if (useCursor)
348
+ this.checkpoints.delete(sessionId);
349
+ const { frames, cwd: effectiveCwd, historyEnd, title, storage } = await replay();
350
+ check();
351
+ if (!useCursor)
352
+ return await deliver(frames, undefined, title);
353
+ const scope = scopeFor(effectiveCwd);
354
+ const { outgoing, cursorId, anchor } = snapshot(frames, sessionId, options.protocol, scope, cursor, historyEnd);
355
+ let verifiedStorage = storage;
356
+ const isRootBoundary = (frame) => frame.sessionId === sessionId && frame.update.sessionUpdate === "replay_complete";
357
+ if (cursorId && cursorId !== cursor) {
358
+ // A terminal can append or rewind between the reads of the root and a child.
359
+ const again = await replay();
360
+ check();
361
+ if (again.cwd !== effectiveCwd ||
362
+ again.historyEnd !== historyEnd ||
363
+ frames.length !== again.frames.length ||
364
+ frames.some((frame, i) => json(frame) !== json(again.frames[i]))) {
365
+ throw RequestError.internalError({ sessionId, retryable: true }, "History changed during the read. Retry with the last successful cursor.");
366
+ }
367
+ if (again.storage?.transcript !== storage?.transcript ||
368
+ again.storage?.version !== storage?.version ||
369
+ again.storage?.sidecarTitle !== storage?.sidecarTitle) {
370
+ verifiedStorage = undefined;
371
+ }
372
+ const end = outgoing.findIndex(isRootBoundary);
373
+ outgoing.splice(end < 0 ? outgoing.length : end, 0, {
374
+ sessionId,
375
+ update: {
376
+ sessionUpdate: "cursor_update",
377
+ cursorId,
378
+ anchor,
379
+ capabilities: { read: {} },
380
+ },
381
+ });
382
+ }
383
+ // Pair the cursor only with the inputs read by its render, never a later append.
384
+ const result = await deliver(outgoing, cursorId, title);
385
+ check();
386
+ if (cursorId && verifiedStorage && processCwd && processCwd === currentDirectory()) {
387
+ this.checkpoints.set(sessionId, {
388
+ cursorId,
389
+ scope,
390
+ requestedCwd: cwd,
391
+ cwd: effectiveCwd,
392
+ processCwd,
393
+ storage: verifiedStorage,
394
+ boundaries: frames.filter(isRootBoundary),
395
+ title,
396
+ });
397
+ if (this.checkpoints.size > 32) {
398
+ this.checkpoints.delete(this.checkpoints.keys().next().value);
399
+ }
400
+ }
401
+ return result;
402
+ }
403
+ finally {
404
+ this.active.delete(sessionId);
405
+ }
406
+ }
407
+ }
@@ -97,7 +97,9 @@ export declare function loadRewindableHistory(sessionId: string, logger?: Logger
97
97
  */
98
98
  export declare function cutAtRewindPoint<M extends {
99
99
  uuid?: string | null;
100
- }>(sessionId: string, stored: readonly M[], logger?: Logger): Promise<M[]>;
100
+ }>(sessionId: string, stored: readonly M[], logger?: Logger, options?: {
101
+ transcript: string;
102
+ }): Promise<M[]>;
101
103
  /**
102
104
  * The entry that a fork of the whole of `sessionId` ends at while a rewind is
103
105
  * pending, or undefined when there is none: the newest leaf then still lies in
@@ -136,7 +138,9 @@ export declare function writeRewindPoint(sessionId: string, point: RewindPoint):
136
138
  * parsed fails with an internal error: reading it as "no rewind" would show or
137
139
  * resume the dropped turns. The file stays, so the client can retry.
138
140
  */
139
- export declare function readRewindPoint(sessionId: string, logger?: Logger): Promise<RewindPoint | undefined>;
141
+ export declare function readRewindPoint(sessionId: string, logger?: Logger, options?: {
142
+ transcript: string;
143
+ }): Promise<RewindPoint | undefined>;
140
144
  /** Removes the record of the last rewind. */
141
145
  export declare function clearRewindPoint(sessionId: string): Promise<void>;
142
146
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"session-rewind.d.ts","sourceRoot":"","sources":["../src/session-rewind.ts"],"names":[],"mappings":"AAsBA,OAAO,EAEL,KAAK,cAAc,EACnB,KAAK,iBAAiB,EACvB,MAAM,gCAAgC,CAAC;AAaxC,eAAO,MAAM,qBAAqB,oBAAoB,CAAC;AAEvD,MAAM,MAAM,oBAAoB,GAAG;IACjC,SAAS,EAAE,MAAM,CAAC;IAClB,4EAA4E;IAC5E,QAAQ,EAAE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;AAC5C,wBAAsB,gBAAgB,CAAC,SAAS,EAAE,MAAM,EAAE,KAAK,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAY3F;AAED;;;;;GAKG;AACH,wBAAsB,eAAe,CACnC,SAAS,EAAE,MAAM,EACjB,MAAM,CAAC,EAAE,MAAM,EACf,OAAO,CAAC,EAAE;IAAE,UAAU,EAAE,MAAM,CAAA;CAAE,GAC/B,OAAO,CAAC,WAAW,GAAG,SAAS,CAAC,CA+BlC;AAED,6CAA6C;AAC7C,wBAAsB,gBAAgB,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAGvE;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAsB,oBAAoB,CACxC,SAAS,EAAE,MAAM,EACjB,MAAM,CAAC,EAAE,MAAM,GACd,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAuB7B"}
@@ -194,8 +194,8 @@ export async function loadRewindableHistory(sessionId, logger) {
194
194
  * that a pending rewind dropped. Cut before reading across compactions: the
195
195
  * newest leaf is the last retained message.
196
196
  */
197
- export async function cutAtRewindPoint(sessionId, stored, logger) {
198
- return activeSessionMessages(stored, await readRewindPoint(sessionId, logger));
197
+ export async function cutAtRewindPoint(sessionId, stored, logger, options) {
198
+ return activeSessionMessages(stored, await readRewindPoint(sessionId, logger, options));
199
199
  }
200
200
  /**
201
201
  * The entry that a fork of the whole of `sessionId` ends at while a rewind is
@@ -272,9 +272,11 @@ export async function writeRewindPoint(sessionId, point) {
272
272
  * parsed fails with an internal error: reading it as "no rewind" would show or
273
273
  * resume the dropped turns. The file stays, so the client can retry.
274
274
  */
275
- export async function readRewindPoint(sessionId, logger) {
275
+ export async function readRewindPoint(sessionId, logger, options) {
276
276
  try {
277
- const file = await rewindPointFile(sessionId);
277
+ const file = options
278
+ ? path.join(path.dirname(options.transcript), sessionId, "rewind.json")
279
+ : await rewindPointFile(sessionId);
278
280
  if (!file)
279
281
  return undefined;
280
282
  let point;
@@ -293,6 +295,13 @@ export async function readRewindPoint(sessionId, logger) {
293
295
  return { resumeSessionAt, droppedPromptUuid };
294
296
  }
295
297
  catch (error) {
298
+ if (options) {
299
+ if (typeof error?.path === "string")
300
+ throw error;
301
+ throw Object.assign(new Error("Failed to read the rewind point", { cause: error }), {
302
+ path: path.join(path.dirname(options.transcript), sessionId, "rewind.json"),
303
+ });
304
+ }
296
305
  logger?.error(`Failed to read the rewind point of session ${sessionId}:`, error);
297
306
  throw RequestError.internalError(undefined, `Session ${sessionId} was rewound, but its rewind point cannot be read (${error instanceof Error ? error.message : String(error)}). Try again.`);
298
307
  }
@@ -25,7 +25,10 @@ export type SettingsReport = {
25
25
  settingsErrors: SDKSettingsParseError[];
26
26
  };
27
27
  /** Ask the CLI whether ultracode is available and requested for the session,
28
- * and which settings files it skipped. */
28
+ * and which settings files it skipped. Its own request, after the session's
29
+ * model is settled: `applied.ultracodeAvailable` is for the model that the
30
+ * CLI runs at the request, and `getAvailableModels` can have set another one
31
+ * since the start's first `get_settings` answer (`followQueryPolicy`). */
29
32
  export declare function readSettingsReport(query: Query): Promise<SettingsReport>;
30
33
  /** The CLI supports ultracode on exactly the models that support `xhigh`
31
34
  * effort (both use the same capability check), and `supportedEffortLevels`
@@ -1 +1 @@
1
- {"version":3,"file":"session-ultracode.d.ts","sourceRoot":"","sources":["../src/session-ultracode.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,mBAAmB,EACnB,6BAA6B,EAC9B,MAAM,mCAAmC,CAAC;AAC3C,OAAO,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE,qBAAqB,EAAE,MAAM,gCAAgC,CAAC;AAG9F,OAAO,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAE9D,yEAAyE;AACzE,eAAO,MAAM,YAAY,OAAO,CAAC;AACjC,eAAO,MAAM,aAAa,QAAQ,CAAC;AAGnC;;iDAEiD;AACjD,MAAM,MAAM,uBAAuB,GAAG;IACpC,sEAAsE;IACtE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