@agentclientprotocol/claude-agent-acp 0.113.1-preview.8 → 0.114.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.
Files changed (69) hide show
  1. package/README.md +5 -3
  2. package/dist/claude-cli.d.ts +22 -16
  3. package/dist/claude-cli.d.ts.map +1 -1
  4. package/dist/claude-cli.js +40 -18
  5. package/dist/query-settings.d.ts +42 -0
  6. package/dist/query-settings.d.ts.map +1 -0
  7. package/dist/query-settings.js +43 -0
  8. package/dist/resumed-session.d.ts +9 -2
  9. package/dist/resumed-session.d.ts.map +1 -1
  10. package/dist/resumed-session.js +51 -7
  11. package/dist/sdk-to-acp.js +4 -2
  12. package/dist/session-cursors.d.ts +1 -1
  13. package/dist/session-cursors.d.ts.map +1 -1
  14. package/dist/session-cursors.js +8 -2
  15. package/dist/session-index/transcript-scan.d.ts +13 -3
  16. package/dist/session-index/transcript-scan.d.ts.map +1 -1
  17. package/dist/session-index/transcript-scan.js +21 -5
  18. package/dist/session-mode.d.ts +69 -3
  19. package/dist/session-mode.d.ts.map +1 -1
  20. package/dist/session-mode.js +103 -15
  21. package/dist/session-model.d.ts +4 -1
  22. package/dist/session-model.d.ts.map +1 -1
  23. package/dist/session-model.js +26 -4
  24. package/dist/session-read.d.ts +45 -0
  25. package/dist/session-read.d.ts.map +1 -0
  26. package/dist/session-read.js +300 -0
  27. package/dist/session-rewind.d.ts +6 -2
  28. package/dist/session-rewind.d.ts.map +1 -1
  29. package/dist/session-rewind.js +13 -4
  30. package/dist/session-ultracode.d.ts +4 -1
  31. package/dist/session-ultracode.d.ts.map +1 -1
  32. package/dist/session-ultracode.js +14 -25
  33. package/dist/settings.d.ts +34 -0
  34. package/dist/settings.d.ts.map +1 -1
  35. package/dist/settings.js +55 -4
  36. package/dist/startup-failure.d.ts +3 -1
  37. package/dist/startup-failure.d.ts.map +1 -1
  38. package/dist/startup-failure.js +7 -1
  39. package/dist/subagent-history.d.ts +9 -1
  40. package/dist/subagent-history.d.ts.map +1 -1
  41. package/dist/subagent-history.js +55 -13
  42. package/dist/v1/acp-agent.d.ts +6 -0
  43. package/dist/v1/acp-agent.d.ts.map +1 -1
  44. package/dist/v1/acp-agent.js +162 -76
  45. package/dist/v1/session-read.d.ts +31 -0
  46. package/dist/v1/session-read.d.ts.map +1 -0
  47. package/dist/v1/session-read.js +62 -0
  48. package/dist/v2/agent.d.ts.map +1 -1
  49. package/dist/v2/agent.js +62 -27
  50. package/dist/v2/config.d.ts +9 -8
  51. package/dist/v2/config.d.ts.map +1 -1
  52. package/dist/v2/config.js +11 -8
  53. package/dist/v2/session-read.d.ts +11 -0
  54. package/dist/v2/session-read.d.ts.map +1 -0
  55. package/dist/v2/session-read.js +28 -0
  56. package/dist/v2/session.d.ts.map +1 -1
  57. package/dist/v2/session.js +6 -0
  58. package/dist/v2/setup.d.ts +4 -1
  59. package/dist/v2/setup.d.ts.map +1 -1
  60. package/dist/v2/setup.js +4 -2
  61. package/dist/v2/stream.d.ts +9 -13
  62. package/dist/v2/stream.d.ts.map +1 -1
  63. package/dist/v2/stream.js +10 -9
  64. package/dist/v2/subagent-replay.d.ts +16 -4
  65. package/dist/v2/subagent-replay.d.ts.map +1 -1
  66. package/dist/v2/subagent-replay.js +22 -10
  67. package/dist/v2/tasks.d.ts.map +1 -1
  68. package/dist/v2/tasks.js +5 -3
  69. package/package.json +4 -4
package/README.md CHANGED
@@ -48,9 +48,9 @@ Claude CLI (`claude`) it runs. Keep them in the same directory; a symlink to
48
48
  instead, set `CLAUDE_CODE_EXECUTABLE`. On Alpine, install `libgcc` and
49
49
  `libstdc++` first.
50
50
 
51
- A CLI named with `CLAUDE_CODE_EXECUTABLE` gets a session's MCP servers on its
52
- command line, where other users of the machine can read their `env` and
53
- `headers`. The CLI that comes with the adapter gets them over stdin.
51
+ A CLI named with `CLAUDE_CODE_EXECUTABLE` must be Claude Code 2.1.328 or newer:
52
+ the adapter sends a session's MCP servers and settings to Claude Code over
53
+ stdin. With an older one, a session that has either does not start.
54
54
 
55
55
  To build one for your machine (needs [Bun](https://bun.sh)) and check it:
56
56
 
@@ -85,6 +85,8 @@ is inserted once, and the retry gets the first `messageId`. The key is known for
85
85
  Code stores the message, also after a restart. A prompt that Claude Code does not store, such as a
86
86
  local command, keeps its key until `session/close` or the end of the connection.
87
87
 
88
+ A client can [read and follow a stored session](docs/session-read.md) through `_session/read` while a terminal continues writing it.
89
+
88
90
  The adapter announces a session cursor (`cursor_update`) before each user message that follows
89
91
  another entry of the conversation, live and in a replay. `session/fork` with its `cursorId` copies
90
92
  the history before that message, and fails with `-32602` for any other `cursorId`. A v1 client gets
@@ -1,3 +1,4 @@
1
+ import { RequestError } from "@agentclientprotocol/sdk/unstable";
1
2
  import type { Options } from "@anthropic-ai/claude-agent-sdk";
2
3
  /**
3
4
  * Called by the executable's entry (`src/binary-entry.ts`) before the agent
@@ -20,31 +21,36 @@ export declare function isRemoteSession(clientExtraArgs: Options["extraArgs"]):
20
21
  * The SDK options that say how a session's MCP servers and its `settings`
21
22
  * reach the CLI of {@link claudeCliPath}. A client's own options replace them.
22
23
  *
23
- * - `'initialize'` for the CLI that the adapter ships: over stdin, in the
24
- * SDK's initialize request.
25
- * - `'argv'` for a CLI that `CLAUDE_CODE_EXECUTABLE` names: in the
26
- * `--mcp-config` and `--settings` flags, as before SDK 0.3.326. Its version
27
- * is not known, and a CLI that cannot take them over stdin fails the session
28
- * at startup (2.1.323: "too old to read MCP servers from the initialize
29
- * request", "unknown option '--initialize-fields=settings'").
30
- * - `settings` stay `'argv'` when the client's `extraArgs` hold `settings`:
31
- * Claude Code refuses to start with both ("--initialize-fields=settings
32
- * cannot be used with --settings"), and in the flag the `settings` option
33
- * replaces that argument. They also stay `'argv'` with `sdk-url` in the
34
- * `extraArgs`: such a session cannot read the request at launch, and the SDK
35
- * sends its MCP servers in the flag for the same reason.
24
+ * - `'initialize'`: over stdin, in the SDK's initialize request. That needs
25
+ * Claude Code 2.1.326 for the MCP servers and 2.1.328 for the settings. The
26
+ * CLI that the adapter ships is newer. An older CLI that
27
+ * `CLAUDE_CODE_EXECUTABLE` names fails the session at startup, with the
28
+ * error of {@link outdatedCliError}.
29
+ * - `settings` are `'argv'`, in the `--settings` flag, when the client's
30
+ * `extraArgs` hold `settings`: Claude Code refuses to start with both
31
+ * ("--initialize-fields=settings cannot be used with --settings"), and in
32
+ * the flag the `settings` option replaces that argument. They are `'argv'`
33
+ * too with `sdk-url` in the `extraArgs`: such a session cannot read the
34
+ * request at launch, and the SDK sends its MCP servers in the flag for the
35
+ * same reason.
36
36
  *
37
37
  * The SDK reads `settingsDelivery` (0.3.328) but does not declare it in
38
38
  * `sdk.d.ts`, so nothing fails to compile if a later SDK drops it. The v2
39
39
  * integration tests check the delivery against the real CLI.
40
40
  *
41
- * `mcpServersDelivery` is always set. The adapter names the CLI to start
42
- * (`pathToClaudeCodeExecutable`), and for such an app the SDK prints a
43
- * `DeprecationWarning` when a session has MCP servers and the option is unset.
41
+ * `mcpServersDelivery` is set although `'initialize'` is the SDK's default
42
+ * since 0.3.333: the delivery then does not change with the SDK's default.
44
43
  */
45
44
  export declare function cliDelivery(clientExtraArgs: Options["extraArgs"]): {
46
45
  mcpServersDelivery: Delivery;
47
46
  settingsDelivery: Delivery;
48
47
  };
48
+ /**
49
+ * The error for a session that did not start because the CLI that
50
+ * `CLAUDE_CODE_EXECUTABLE` names is too old (see {@link cliDelivery}), with
51
+ * the failure's own text in `data.details`. Undefined for any other failure,
52
+ * and without `CLAUDE_CODE_EXECUTABLE`.
53
+ */
54
+ export declare function outdatedCliError(error: unknown): RequestError | undefined;
49
55
  export {};
50
56
  //# sourceMappingURL=claude-cli.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"claude-cli.d.ts","sourceRoot":"","sources":["../src/claude-cli.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gCAAgC,CAAC;AAM9D;;;;;;GAMG;AACH,wBAAgB,mBAAm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B,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,YAAY,GAAG,SAAS,CAOzE"}
@@ -1,5 +1,6 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { join } from "node:path";
3
+ import { RequestError } from "@agentclientprotocol/sdk/unstable";
3
4
  const CLI_FILE_NAME = process.platform === "win32" ? "claude.exe" : "claude";
4
5
  let bundledCliDirectory;
5
6
  /**
@@ -33,32 +34,53 @@ export function isRemoteSession(clientExtraArgs) {
33
34
  * The SDK options that say how a session's MCP servers and its `settings`
34
35
  * reach the CLI of {@link claudeCliPath}. A client's own options replace them.
35
36
  *
36
- * - `'initialize'` for the CLI that the adapter ships: over stdin, in the
37
- * SDK's initialize request.
38
- * - `'argv'` for a CLI that `CLAUDE_CODE_EXECUTABLE` names: in the
39
- * `--mcp-config` and `--settings` flags, as before SDK 0.3.326. Its version
40
- * is not known, and a CLI that cannot take them over stdin fails the session
41
- * at startup (2.1.323: "too old to read MCP servers from the initialize
42
- * request", "unknown option '--initialize-fields=settings'").
43
- * - `settings` stay `'argv'` when the client's `extraArgs` hold `settings`:
44
- * Claude Code refuses to start with both ("--initialize-fields=settings
45
- * cannot be used with --settings"), and in the flag the `settings` option
46
- * replaces that argument. They also stay `'argv'` with `sdk-url` in the
47
- * `extraArgs`: such a session cannot read the request at launch, and the SDK
48
- * sends its MCP servers in the flag for the same reason.
37
+ * - `'initialize'`: over stdin, in the SDK's initialize request. That needs
38
+ * Claude Code 2.1.326 for the MCP servers and 2.1.328 for the settings. The
39
+ * CLI that the adapter ships is newer. An older CLI that
40
+ * `CLAUDE_CODE_EXECUTABLE` names fails the session at startup, with the
41
+ * error of {@link outdatedCliError}.
42
+ * - `settings` are `'argv'`, in the `--settings` flag, when the client's
43
+ * `extraArgs` hold `settings`: Claude Code refuses to start with both
44
+ * ("--initialize-fields=settings cannot be used with --settings"), and in
45
+ * the flag the `settings` option replaces that argument. They are `'argv'`
46
+ * too with `sdk-url` in the `extraArgs`: such a session cannot read the
47
+ * request at launch, and the SDK sends its MCP servers in the flag for the
48
+ * same reason.
49
49
  *
50
50
  * The SDK reads `settingsDelivery` (0.3.328) but does not declare it in
51
51
  * `sdk.d.ts`, so nothing fails to compile if a later SDK drops it. The v2
52
52
  * integration tests check the delivery against the real CLI.
53
53
  *
54
- * `mcpServersDelivery` is always set. The adapter names the CLI to start
55
- * (`pathToClaudeCodeExecutable`), and for such an app the SDK prints a
56
- * `DeprecationWarning` when a session has MCP servers and the option is unset.
54
+ * `mcpServersDelivery` is set although `'initialize'` is the SDK's default
55
+ * since 0.3.333: the delivery then does not change with the SDK's default.
57
56
  */
58
57
  export function cliDelivery(clientExtraArgs) {
59
- const delivery = process.env.CLAUDE_CODE_EXECUTABLE ? "argv" : "initialize";
60
58
  const settingsInFlag = "settings" in (clientExtraArgs ?? {}) || isRemoteSession(clientExtraArgs);
61
- return { mcpServersDelivery: delivery, settingsDelivery: settingsInFlag ? "argv" : delivery };
59
+ return {
60
+ mcpServersDelivery: "initialize",
61
+ settingsDelivery: settingsInFlag ? "argv" : "initialize",
62
+ };
63
+ }
64
+ /**
65
+ * How the start of a Claude Code that cannot take a session's MCP servers or
66
+ * settings over stdin fails:
67
+ * - before 2.1.326, with MCP servers: the SDK ends the session, "This Claude
68
+ * Code (version 2.1.323) is too old to read MCP servers over stdin, …";
69
+ * - before 2.1.328, with settings: the CLI exits, "error: unknown option
70
+ * '--initialize-fields=settings'".
71
+ */
72
+ const OUTDATED_CLI = /is too old to read MCP servers|unknown option '--initialize-fields/;
73
+ /**
74
+ * The error for a session that did not start because the CLI that
75
+ * `CLAUDE_CODE_EXECUTABLE` names is too old (see {@link cliDelivery}), with
76
+ * the failure's own text in `data.details`. Undefined for any other failure,
77
+ * and without `CLAUDE_CODE_EXECUTABLE`.
78
+ */
79
+ export function outdatedCliError(error) {
80
+ const named = process.env.CLAUDE_CODE_EXECUTABLE;
81
+ if (!named || !(error instanceof Error) || !OUTDATED_CLI.test(error.message))
82
+ return undefined;
83
+ return RequestError.internalError({ details: error.message }, `The Claude Code that CLAUDE_CODE_EXECUTABLE names (${named}) is too old: it cannot take a session's MCP servers and settings over stdin. Update it to 2.1.328 or newer, or unset CLAUDE_CODE_EXECUTABLE to use the Claude Code that comes with the adapter.`);
62
84
  }
63
85
  function bundledClaudeCliPath(directory) {
64
86
  const path = join(directory, CLI_FILE_NAME);
@@ -0,0 +1,42 @@
1
+ import type { Query, SDKSettingsParseError, Settings } from "@anthropic-ai/claude-agent-sdk";
2
+ import type { SettingsManager } from "./settings.js";
3
+ /** The fields used from Claude Code's `get_settings` control response. */
4
+ export type QuerySettings = {
5
+ effective?: Settings;
6
+ sources?: Array<{
7
+ source?: unknown;
8
+ settings?: Settings;
9
+ }>;
10
+ applied?: {
11
+ model?: unknown;
12
+ ultracodeAvailable?: unknown;
13
+ ultracodeRequested?: unknown;
14
+ };
15
+ errors?: SDKSettingsParseError[];
16
+ };
17
+ /**
18
+ * Claude Code's answer to `get_settings`. Undefined when the SDK has no
19
+ * `getSettings` or the request fails; a failure is logged when a `logger` is
20
+ * given.
21
+ */
22
+ export declare function readQuerySettings(query: Query, logger?: {
23
+ error: (...args: unknown[]) => void;
24
+ }): Promise<QuerySettings | undefined>;
25
+ /**
26
+ * The policy tier the running CLI applies: its managed settings, remote ones
27
+ * included. Undefined when the CLI reports none.
28
+ */
29
+ export declare function cliPolicySettings(report: QuerySettings | undefined): Settings | undefined;
30
+ /**
31
+ * Reads the settings that the query's Claude Code applies, once it has
32
+ * answered `initialize`, and has `settings` follow its policy tier from then
33
+ * on (see `SettingsManager.followCliPolicy`). Call it before the first reader
34
+ * of a value that a policy can set, such as the `apiKeyHelper` of the
35
+ * session's identity. Returns the answer that it read, for the start's other
36
+ * readers (`getAvailableModels`), or undefined without one: the settings then
37
+ * stay those of this process, and the failure is logged.
38
+ */
39
+ export declare function followQueryPolicy(query: Query, settings: Pick<SettingsManager, "followCliPolicy">, logger: {
40
+ error: (...args: unknown[]) => void;
41
+ }): Promise<QuerySettings | und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AO,CAAC,aAAa,GAAG,SAAS,CAAC,CAQpC"}
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Claude Code's answer to `get_settings`. Undefined when the SDK has no
3
+ * `getSettings` or the request fails; a failure is logged when a `logger` is
4
+ * given.
5
+ */
6
+ export async function readQuerySettings(query, logger) {
7
+ const getSettings = query.getSettings;
8
+ if (typeof getSettings !== "function")
9
+ return undefined;
10
+ try {
11
+ return await getSettings.call(query);
12
+ }
13
+ catch (error) {
14
+ logger?.error("Failed to read the settings that Claude Code applies:", error);
15
+ return undefined;
16
+ }
17
+ }
18
+ /**
19
+ * The policy tier the running CLI applies: its managed settings, remote ones
20
+ * included. Undefined when the CLI reports none.
21
+ */
22
+ export function cliPolicySettings(report) {
23
+ const sources = Array.isArray(report?.sources) ? report.sources : [];
24
+ const policy = sources.find((entry) => entry?.source === "policySettings")?.settings;
25
+ if (!policy || typeof policy !== "object" || Object.keys(policy).length === 0)
26
+ return undefined;
27
+ return policy;
28
+ }
29
+ /**
30
+ * Reads the settings that the query's Claude Code applies, once it has
31
+ * answered `initialize`, and has `settings` follow its policy tier from then
32
+ * on (see `SettingsManager.followCliPolicy`). Call it before the first reader
33
+ * of a value that a policy can set, such as the `apiKeyHelper` of the
34
+ * session's identity. Returns the answer that it read, for the start's other
35
+ * readers (`getAvailableModels`), or undefined without one: the settings then
36
+ * stay those of this process, and the failure is logged.
37
+ */
38
+ export async function followQueryPolicy(query, settings, logger) {
39
+ const read = () => readQuerySettings(query, logger);
40
+ const report = await read();
41
+ await settings.followCliPolicy(async () => cliPolicySettings(await read()), cliPolicySettings(report));
42
+ return report;
43
+ }
@@ -1,4 +1,5 @@
1
1
  import { type SessionMessage, type SessionStoreEntry } from "@anthropic-ai/claude-agent-sdk";
2
+ import { type FileHandle } from "node:fs/promises";
2
3
  type ResumeLogger = {
3
4
  log: (...args: unknown[]) => void;
4
5
  error: (...args: unknown[]) => void;
@@ -39,7 +40,7 @@ export declare function readResumedSession(sessionId: string, logger?: ResumeLog
39
40
  * the chain loops and ends there. Without it, the kept messages stay where
40
41
  * they were said, before the boundary.
41
42
  */
42
- export declare function readHistoryAcrossCompactions(sessionId: string, messages: SessionMessage[], logger?: ResumeLogger, dir?: string): Promise<SessionMessage[]>;
43
+ export declare function readHistoryAcrossCompactions(sessionId: string, messages: SessionMessage[], logger?: ResumeLogger, dir?: string, snapshot?: SessionStoreEntry[]): Promise<SessionMessage[]>;
43
44
  /** Every record of a session's transcript, including the inactive branches
44
45
  * and the history before a compaction that `getSessionMessages` leaves out.
45
46
  * Without `dir`, all project directories are searched. */
@@ -64,6 +65,12 @@ export type ResumedTail = {
64
65
  */
65
66
  export declare function readResumedTail(sessionId: string, logger?: ResumeLogger, withModel?: boolean): Promise<ResumedTail>;
66
67
  /** The local transcript of a session in any project directory, as the SDK looks it up. */
67
- export declare function findTranscript(sessionId: string): Promise<string | undefined>;
68
+ export declare function findTranscript(sessionId: string, options?: {
69
+ strict: boolean;
70
+ }): Promise<string | undefined>;
71
+ /** Read the records once so the SDK projects the active branch and its compactions
72
+ * from the same bytes. An unfinished JSON line can be completed by the next poll. */
73
+ export declare function readTranscriptEntries(file: string): Promise<SessionStoreEntry[]>;
74
+ export declare function readTranscriptEntriesOf(file: string, handle: FileHandle, size: number): Promise<SessionStoreEntry[]>;
68
75
  export {};
69
76
  //# sourceMappingURL=resumed-session.d.ts.map
@@ -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;AAUxC,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;IAC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,EAAE,YAAY,EACrB,SAAS,UAAO,GACf,OAAO,CAAC,WAAW,CAAC,CAiBtB;AAED,0FAA0F;AAC1F,wBAAsB,cAAc,CAClC,SAAS,EAAE,MAAM,EACjB,OAAO,CAAC,EAAE;IAAE,MAAM,EAAE,OAAO,CAAA;CAAE,GAC5B,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAuB7B;AAED;qFACqF;AACrF,wBAAsB,qBAAqB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,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"}
@@ -2,7 +2,8 @@ import { getSessionMessages, importSessionToStore, } from "@anthropic-ai/claude-
2
2
  import { access, open, readdir } from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { isCompactSummaryMessage } from "./context-compaction.js";
5
- import { claudeConfigDir } from "./paths.js";
5
+ import { projectsRoot } from "./paths.js";
6
+ import { errorCode } from "./session-index/project-dirs.js";
6
7
  import { SessionTiming } from "./session-timing.js";
7
8
  /** The size of one backward read of a transcript. */
8
9
  const TAIL_CHUNK_BYTES = 64 * 1024;
@@ -76,11 +77,11 @@ export async function readResumedSession(sessionId, logger) {
76
77
  * the chain loops and ends there. Without it, the kept messages stay where
77
78
  * they were said, before the boundary.
78
79
  */
79
- export async function readHistoryAcrossCompactions(sessionId, messages, logger, dir) {
80
+ export async function readHistoryAcrossCompactions(sessionId, messages, logger, dir, snapshot) {
80
81
  if (!isCompactSummaryMessage(messages[0]))
81
82
  return messages;
82
83
  try {
83
- const entries = (await loadFullSessionHistory(sessionId, dir)).map(linkCompactBoundary);
84
+ const entries = (snapshot ?? (await loadFullSessionHistory(sessionId, dir))).map(linkCompactBoundary);
84
85
  const history = await getSessionMessages(sessionId, {
85
86
  dir,
86
87
  sessionStore: { append: async () => { }, load: async () => entries },
@@ -88,12 +89,16 @@ export async function readHistoryAcrossCompactions(sessionId, messages, logger,
88
89
  const leaf = messages.at(-1)?.uuid;
89
90
  const end = history.findIndex((message) => message.uuid === leaf);
90
91
  if (end < 0) {
92
+ if (snapshot)
93
+ throw new Error("Compacted history does not reach the active branch");
91
94
  logger?.error(`The history before the last compaction of session ${sessionId} does not reach message ${leaf}: replaying the messages after it`);
92
95
  return messages;
93
96
  }
94
97
  return history.slice(0, end + 1);
95
98
  }
96
99
  catch (error) {
100
+ if (snapshot)
101
+ throw error;
97
102
  logger?.error(`Failed to read the history before the last compaction of session ${sessionId}:`, error);
98
103
  return messages;
99
104
  }
@@ -155,27 +160,66 @@ export async function readResumedTail(sessionId, logger, withModel = true) {
155
160
  return withModel ? { model: (await readResumedSession(sessionId, logger)).model } : {};
156
161
  }
157
162
  /** The local transcript of a session in any project directory, as the SDK looks it up. */
158
- export async function findTranscript(sessionId) {
159
- const projects = path.join(claudeConfigDir(), "projects");
163
+ export async function findTranscript(sessionId, options) {
164
+ const projects = projectsRoot();
160
165
  let directories;
161
166
  try {
162
167
  directories = await readdir(projects);
163
168
  }
164
- catch {
169
+ catch (error) {
170
+ if (options?.strict && errorCode(error) !== "ENOENT")
171
+ throw error;
165
172
  return undefined;
166
173
  }
174
+ let lookupError;
167
175
  for (const directory of directories) {
168
176
  const candidate = path.join(projects, directory, `${sessionId}.jsonl`);
169
177
  try {
170
178
  await access(candidate);
171
179
  return candidate;
172
180
  }
173
- catch {
181
+ catch (error) {
182
+ if (options?.strict && errorCode(error) !== "ENOENT" && errorCode(error) !== "ENOTDIR")
183
+ lookupError ??= error;
174
184
  // Not in this project directory.
175
185
  }
176
186
  }
187
+ if (lookupError)
188
+ throw lookupError;
177
189
  return undefined;
178
190
  }
191
+ /** Read the records once so the SDK projects the active branch and its compactions
192
+ * from the same bytes. An unfinished JSON line can be completed by the next poll. */
193
+ export async function readTranscriptEntries(file) {
194
+ const handle = await open(file, "r");
195
+ try {
196
+ return await readTranscriptEntriesOf(file, handle, (await handle.stat()).size);
197
+ }
198
+ finally {
199
+ await handle.close();
200
+ }
201
+ }
202
+ export async function readTranscriptEntriesOf(file, handle, size) {
203
+ if (size === 0)
204
+ return [];
205
+ try {
206
+ const records = [];
207
+ for await (const line of handle.readLines({ start: 0, end: size - 1 })) {
208
+ try {
209
+ const record = JSON.parse(line);
210
+ if (record && typeof record.type === "string")
211
+ records.push(record);
212
+ }
213
+ catch {
214
+ // Claude's transcript reader skips lines that do not parse.
215
+ }
216
+ }
217
+ return records;
218
+ }
219
+ catch (error) {
220
+ throw Object.assign(new Error(`Could not read ${file}`, { cause: error }), { path: file });
221
+ }
222
+ }
179
223
  /** The model of the last real assistant record and the last permission mode
180
224
  * of the main thread in a JSONL transcript. */
181
225
  async function lastTailRecords(filePath, withModel) {
@@ -324,7 +324,8 @@ export function toAcpNotifications(content, role, sessionId, toolUseCache, clien
324
324
  // Resolve the server tool through the normal result path without rendering
325
325
  // opaque ciphertext. Server tools have no later PostToolUse hook to await.
326
326
  const result = chunk.content;
327
- unregisterHookCallback(chunk.tool_use_id);
327
+ if (registerHooks)
328
+ unregisterHookCallback(chunk.tool_use_id);
328
329
  output.push(...toAcpNotifications([
329
330
  {
330
331
  type: "tool_result",
@@ -349,7 +350,8 @@ export function toAcpNotifications(content, role, sessionId, toolUseCache, clien
349
350
  case "mcp_tool_result": {
350
351
  const wasEmitted = options?.emittedToolCalls?.has(chunk.tool_use_id) === true;
351
352
  options?.emittedToolCalls?.delete(chunk.tool_use_id);
352
- completeHookCallback(chunk.tool_use_id);
353
+ if (registerHooks)
354
+ completeHookCallback(chunk.tool_use_id);
353
355
  finishedToolCallId = chunk.tool_use_id;
354
356
  // Why this is_error result carries harness prose instead of tool
355
357
  // output (user-rejected / interrupted / …), when the SDK said so.
@@ -95,7 +95,7 @@ export declare class LastReportedEntity {
95
95
  sessionUpdate: string;
96
96
  _meta?: unknown;
97
97
  } & Record<string, unknown>;
98
- }): void;
98
+ }, protocol?: 1 | 2): void;
99
99
  /** The position after the last entity of the session, if the client holds one. */
100
100
  after(sessionId: string): CursorAnchor | undefined;
101
101
  /** The last entity of the session that the client holds, if any. */
@@ -1 +1 @@
1
- {"version":3,"file":"session-cursors.d.ts","sourceRoot":"","sources":["../src/session-cursors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AAOrE,+CAA+C;AAC/C,MAAM,MAAM,YAAY,GACpB;IAAE,IAAI,EAAE,cAAc,GAAG,eAAe,GAAG,eAAe,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,GAC/E;IAAE,IAAI,EAAE,WAAW,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,GACzC;IAAE,IAAI,EAAE,YAAY,CAAC;IAAC,YAAY,EAAE,MAAM,CAAA;CAAE,CAAC;AAEjD,kEAAkE;AAClE,MAAM,MAAM,YAAY,GAAG,YAAY,GAAG;IAAE,QAAQ,EAAE,QAAQ,GAAG,OAAO,CAAA;CAAE,CAAC;AAE3E,6EAA6E;AAC7E,wBAAgB,gBAAgB,CAAC,SAAS,EAAE,MAAM;;;;;;;;;;;EAKjD;AAED;;;;GAIG;AACH,wBAAgB,wBAAwB,CAAC,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,YAAY;;;;;;;EAE/E;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,CAAC,SAAS;IAAE,YAAY,EAAE;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,CAAA;CAAE,EAC/E,MAAM,EAAE,CAAC,GACR,CAAC,GAAG;IAAE,YAAY,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAA;CAAE,CAExD;AAED,0GAA0G;AAC1G,wBAAgB,eAAe,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CA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C,YAAY,CAA4D;IAEzF,OAAO,CACL,YAAY,EAAE;QACZ,SAAS,EAAE,MAAM,CAAC;QAClB,MAAM,EAAE;YAAE,aAAa,EAAE,MAAM,CAAC;YAAC,KAAK,CAAC,EAAE,OAAO,CAAA;SAAE,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;KAC9E,EACD,QAAQ,GAAE,CAAC,GAAG,CAAK,GAClB,IAAI;IAqCP,kFAAkF;IAClF,KAAK,CAAC,SAAS,EAAE,MAAM,GAAG,YAAY,GAAG,SAAS;IAKlD,oEAAoE;IACpE,IAAI,CAAC,SAAS,EAAE,MAAM,GAAG,YAAY,GAAG,SAAS;IAIjD,+FAA+F;IAC/F,YAAY,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,YAAY,GAAG,SAAS,GAAG,IAAI;IAMzF;;;;;OAKG;IACH,MAAM,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI;IAajD,+FAA+F;IAC/F,MAAM,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI;CAOhC;AAED;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,aAAa,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,OAAO,CAAA;CAAE,CAAC,GAAG,OAAO,CAGjG;AAED;;;;;;GAMG;AACH,wBAAgB,aAAa,CAAC,QAAQ,EAAE,SAAS,cAAc,EAAE,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAIzF;AAmBD;;;;GAIG;AACH,wBAAgB,WAAW,CACzB,QAAQ,EAAE,MAAM,EAChB,QAAQ,EAAE,SAAS,cAAc,EAAE,GAClC,MAAM,GAAG,SAAS,CAKpB"}
@@ -52,27 +52,33 @@ export class LastReportedEntity {
52
52
  bySession = new Map();
53
53
  /** Per session, in announcement order: the entity before each announced cursor. */
54
54
  beforeCursor = new Map();
55
- sending(notification) {
55
+ sending(notification, protocol = 1) {
56
56
  const { sessionId, update } = notification;
57
57
  const meta = update._meta;
58
58
  if (meta?.claudeCode?.parentToolUseId)
59
59
  return;
60
60
  const messageId = typeof update.messageId === "string" ? update.messageId : undefined;
61
61
  switch (update.sessionUpdate) {
62
+ case "user_message":
62
63
  case "user_message_chunk":
63
64
  if (messageId)
64
65
  this.bySession.set(sessionId, { type: "user_message", messageId });
65
66
  break;
67
+ case "agent_message":
66
68
  case "agent_message_chunk":
67
69
  if (messageId)
68
70
  this.bySession.set(sessionId, { type: "agent_message", messageId });
69
71
  break;
72
+ case "agent_thought":
70
73
  case "agent_thought_chunk":
71
74
  if (messageId)
72
75
  this.bySession.set(sessionId, { type: "agent_thought", messageId });
73
76
  break;
74
77
  case "tool_call":
75
- if (typeof update.toolCallId === "string") {
78
+ case "tool_call_update":
79
+ if ((update.sessionUpdate === "tool_call" ||
80
+ (protocol === 2 && typeof update.name === "string")) &&
81
+ typeof update.toolCallId === "string") {
76
82
  this.bySession.set(sessionId, { type: "tool_call", toolCallId: update.toolCallId });
77
83
  }
78
84
  break;
@@ -135,8 +135,16 @@ export declare function scanTranscript({ head, tail }: HeadTail, options?: {
135
135
  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
- /** The title of the CLI's sidecar, if it has a readable title. */
139
- export declare function readSidecarTitle(transcriptPath: string): Promise<string | undefined>;
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>;
143
+ /** The title of the CLI's sidecar, if it has a readable title. A strict read
144
+ * throws when the sidecar exists but cannot be read. */
145
+ export declare function readSidecarTitle(transcriptPath: string, options?: {
146
+ strict: boolean;
147
+ }): Promise<string | undefined>;
140
148
  /** The last agent name of a transcript, as AIR's native Claude provider
141
149
  * reads it: the top-level `agentName` of any record, from the tail, else
142
150
  * from the head. */
@@ -157,7 +165,9 @@ export type SdkTitles = {
157
165
  */
158
166
  export declare function sdkTitles(headTail: HeadTail, sidecarTitle?: string): SdkTitles;
159
167
  /** Reads the titles of this transcript copy without another SDK project lookup. */
160
- export declare function readTranscriptTitles(transcriptPath: string, headTail: HeadTail): Promise<SdkTitles>;
168
+ export declare function readTranscriptTitles(transcriptPath: string, headTail: HeadTail, options?: {
169
+ strict: boolean;
170
+ }): Promise<SdkTitles>;
161
171
  /** The title of a transcript without a custom title, in the SDK's order: AI
162
172
  * title, last prompt, summary, first prompt. The last prompt and the summary
163
173
  * are the field of a record of any type. */
@@ -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;AAchF,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,MAA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asksOf } from "./background-tasks.js";
17
17
  import { firstPrompt, isUserPrompt, mediaPrompt, promptOf } from "./first-prompt.js";
18
+ import { errorCode } from "./project-dirs.js";
18
19
  const CHUNK_SIZE = 64 * 1024;
19
20
  /** The largest tail window read to find the last message. */
20
21
  const MAX_TAIL_SIZE = 4 * 1024 * 1024;
@@ -541,10 +542,25 @@ export function customTitleSidecarPath(transcriptPath) {
541
542
  const sessionId = path.basename(transcriptPath, ".jsonl");
542
543
  return path.join(path.dirname(transcriptPath), sessionId, "custom-title.json");
543
544
  }
544
- /** The title of the CLI's sidecar, if it has a readable title. */
545
- export async function readSidecarTitle(transcriptPath) {
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));
549
+ }
550
+ /** The title of the CLI's sidecar, if it has a readable title. A strict read
551
+ * throws when the sidecar exists but cannot be read. */
552
+ export async function readSidecarTitle(transcriptPath, options) {
553
+ const file = customTitleSidecarPath(transcriptPath);
554
+ let text;
555
+ try {
556
+ text = await fs.readFile(file, "utf8");
557
+ }
558
+ catch (error) {
559
+ if (options?.strict && errorCode(error) !== "ENOENT")
560
+ throw error;
561
+ return undefined;
562
+ }
546
563
  try {
547
- const text = await fs.readFile(customTitleSidecarPath(transcriptPath), "utf8");
548
564
  const title = JSON.parse(text).customTitle;
549
565
  return typeof title === "string" && title.trim() ? title : undefined;
550
566
  }
@@ -592,11 +608,11 @@ export function sdkTitles(headTail, sidecarTitle) {
592
608
  return { customTitle, summary: customTitle ?? generatedTitle({ head, tail }) };
593
609
  }
594
610
  /** Reads the titles of this transcript copy without another SDK project lookup. */
595
- export async function readTranscriptTitles(transcriptPath, headTail) {
611
+ export async function readTranscriptTitles(transcriptPath, headTail, options) {
596
612
  const customTitle = tailCustomTitle(headTail);
597
613
  if (customTitle !== undefined)
598
614
  return { customTitle, summary: customTitle };
599
- return sdkTitles(headTail, await readSidecarTitle(transcriptPath));
615
+ return sdkTitles(headTail, await readSidecarTitle(transcriptPath, options));
600
616
  }
601
617
  /** The title of a transcript without a custom title, in the SDK's order: AI
602
618
  * title, last prompt, summary, first prompt. The last prompt and the summary