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

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 (74) hide show
  1. package/README.md +5 -3
  2. package/dist/async-tasks.d.ts +27 -0
  3. package/dist/async-tasks.d.ts.map +1 -1
  4. package/dist/async-tasks.js +36 -0
  5. package/dist/claude-cli.d.ts +22 -16
  6. package/dist/claude-cli.d.ts.map +1 -1
  7. package/dist/claude-cli.js +40 -18
  8. package/dist/mcp-oauth.d.ts +3 -2
  9. package/dist/mcp-oauth.d.ts.map +1 -1
  10. package/dist/mcp-oauth.js +65 -27
  11. package/dist/resumed-session.d.ts +9 -2
  12. package/dist/resumed-session.d.ts.map +1 -1
  13. package/dist/resumed-session.js +51 -7
  14. package/dist/sdk-to-acp.js +4 -2
  15. package/dist/session-cursors.d.ts +1 -1
  16. package/dist/session-cursors.d.ts.map +1 -1
  17. package/dist/session-cursors.js +8 -2
  18. package/dist/session-index/service.d.ts.map +1 -1
  19. package/dist/session-index/service.js +9 -17
  20. package/dist/session-index/session-index.d.ts +1 -13
  21. package/dist/session-index/session-index.d.ts.map +1 -1
  22. package/dist/session-index/session-index.js +3 -29
  23. package/dist/session-index/transcript-scan.d.ts +17 -4
  24. package/dist/session-index/transcript-scan.d.ts.map +1 -1
  25. package/dist/session-index/transcript-scan.js +44 -3
  26. package/dist/session-mode.d.ts +38 -1
  27. package/dist/session-mode.d.ts.map +1 -1
  28. package/dist/session-mode.js +73 -15
  29. package/dist/session-read.d.ts +45 -0
  30. package/dist/session-read.d.ts.map +1 -0
  31. package/dist/session-read.js +300 -0
  32. package/dist/session-rewind.d.ts +6 -2
  33. package/dist/session-rewind.d.ts.map +1 -1
  34. package/dist/session-rewind.js +13 -4
  35. package/dist/session-ultracode.d.ts +14 -5
  36. package/dist/session-ultracode.d.ts.map +1 -1
  37. package/dist/session-ultracode.js +23 -11
  38. package/dist/startup-failure.d.ts +11 -1
  39. package/dist/startup-failure.d.ts.map +1 -1
  40. package/dist/startup-failure.js +33 -1
  41. package/dist/subagent-history.d.ts +9 -1
  42. package/dist/subagent-history.d.ts.map +1 -1
  43. package/dist/subagent-history.js +55 -13
  44. package/dist/v1/acp-agent.d.ts +8 -1
  45. package/dist/v1/acp-agent.d.ts.map +1 -1
  46. package/dist/v1/acp-agent.js +167 -87
  47. package/dist/v1/async-task-stop.d.ts +31 -0
  48. package/dist/v1/async-task-stop.d.ts.map +1 -1
  49. package/dist/v1/async-task-stop.js +41 -0
  50. package/dist/v1/session-read.d.ts +31 -0
  51. package/dist/v1/session-read.d.ts.map +1 -0
  52. package/dist/v1/session-read.js +62 -0
  53. package/dist/v2/agent.d.ts.map +1 -1
  54. package/dist/v2/agent.js +60 -25
  55. package/dist/v2/commands.d.ts +8 -3
  56. package/dist/v2/commands.d.ts.map +1 -1
  57. package/dist/v2/commands.js +4 -3
  58. package/dist/v2/config.d.ts +3 -3
  59. package/dist/v2/config.d.ts.map +1 -1
  60. package/dist/v2/config.js +11 -9
  61. package/dist/v2/session-read.d.ts +11 -0
  62. package/dist/v2/session-read.d.ts.map +1 -0
  63. package/dist/v2/session-read.js +28 -0
  64. package/dist/v2/session.d.ts.map +1 -1
  65. package/dist/v2/session.js +19 -2
  66. package/dist/v2/stream.d.ts +9 -13
  67. package/dist/v2/stream.d.ts.map +1 -1
  68. package/dist/v2/stream.js +10 -9
  69. package/dist/v2/subagent-replay.d.ts +16 -4
  70. package/dist/v2/subagent-replay.d.ts.map +1 -1
  71. package/dist/v2/subagent-replay.js +22 -10
  72. package/dist/v2/tasks.d.ts.map +1 -1
  73. package/dist/v2/tasks.js +5 -3
  74. package/package.json +8 -8
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 type { SDKMessage } from "@anthropic-ai/claude-agent-sdk";
1
2
  import type { ClientCapabilities } from "@agentclientprotocol/sdk/unstable";
2
3
  import type { AcpSessionNotification, AsyncTaskState } from "./acp-subagents.js";
3
4
  type Publish = (notification: AcpSessionNotification) => Promise<void>;
@@ -102,6 +103,12 @@ export declare class AsyncTaskRuntime {
102
103
  private readonly outputPathsByToolCall;
103
104
  /** The task of the autonomous turn that runs now. */
104
105
  private autonomousTurn?;
106
+ /**
107
+ * Whether a stop interrupted the autonomous turn and its aborted result has
108
+ * not come yet. Stopping ends the task, so this is the only trace that the
109
+ * result belongs to that turn, see {@link startedByClaudeCode}.
110
+ */
111
+ private interruptedTurnResultOwed;
105
112
  /** The summary of the last task notification, which usually starts the next autonomous turn. */
106
113
  private lastNotificationSummary?;
107
114
  constructor(enabled: boolean, sessionId: string, publish: Publish,
@@ -154,6 +161,26 @@ export declare class AsyncTaskRuntime {
154
161
  get autonomousTurnOpen(): boolean;
155
162
  /** Ends the task of the autonomous turn that runs now, if there is one. */
156
163
  autonomousTurnEnded(state: "completed" | "failed"): Promise<void>;
164
+ /** A stop is about to interrupt the autonomous turn: its aborted result is owed. */
165
+ autonomousTurnInterrupting(): void;
166
+ /** The interrupt failed, so the turn goes on and no aborted result is owed. */
167
+ autonomousTurnInterruptFailed(): void;
168
+ /**
169
+ * Whether Claude Code started the work that a result reports: the result has
170
+ * an autonomous origin, or it is the aborted result that a stop owes. Call it
171
+ * for every result: the first one after the stop ends the debt, even when
172
+ * the result has an autonomous origin. A turn that a scheduler fire started
173
+ * has results with no `origin`, so the origin cannot tell it from a waiting
174
+ * prompt's result. The first result is the turn's when it is aborted and
175
+ * names no waiting prompt (`answersPrompt`). A non-aborted result means the
176
+ * interrupted turn finished without an aborted result, and one that names a
177
+ * waiting prompt means the turn took the prompt in; neither is the turn's.
178
+ * This relies on the CLI emitting the interrupted turn's result before the
179
+ * next turn's, which nothing enforces here.
180
+ */
181
+ startedByClaudeCode(result: Extract<SDKMessage, {
182
+ type: "result";
183
+ }>, answersPrompt: boolean): boolean;
157
184
  /** Whether the task stands for an autonomous turn, which a stop interrupts. */
158
185
  isAutonomousTurn(taskId: string): boolean;
159
186
  /** Whether a task of the tool call went to the background, so the client gets it. */
@@ -1 +1 @@
1
- {"version":3,"file":"async-tasks.d.ts","sourceRoot":"","sources":["../src/async-tasks.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,mCAAmC,CAAC;AAC5E,OAAO,KAAK,EAAE,sBAAsB,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAIjF,KAAK,OAAO,GAAG,CAAC,YAAY,EAAE,sBAAsB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;AACvE,qEAAqE;AACrE,KAAK,KAAK,GAAG,CAAC,YAAY,EAAE,sBAAsB,KAAK,sBAAsB,GAAG,IAAI,CAAC;AA4CrF,KAAK,YAAY,GAAG;IAAE,MAAM,CAAC,EAAE,O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B,EACzB,cAAc,CAAC,EAAE,gBAAgB,GAChC,GAAG,CAAC,MAAM,CAAC,CAmBb"}
@@ -1,5 +1,6 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { AIR_ASYNC_TASKS_CAPABILITY, clientSupportsAirCapability } from "./air-extension.js";
3
+ import { AUTONOMOUS_RESULT_ORIGINS, isAbortedResult } from "./result-end.js";
3
4
  import { noticeOrTranscriptUpdate } from "./session-notices.js";
4
5
  const MAX_TOOL_RESULT_PATHS = 500;
5
6
  /** Reads the display fields supplied by a task progress report. */
@@ -39,6 +40,12 @@ export class AsyncTaskRuntime {
39
40
  outputPathsByToolCall = new Map();
40
41
  /** The task of the autonomous turn that runs now. */
41
42
  autonomousTurn;
43
+ /**
44
+ * Whether a stop interrupted the autonomous turn and its aborted result has
45
+ * not come yet. Stopping ends the task, so this is the only trace that the
46
+ * result belongs to that turn, see {@link startedByClaudeCode}.
47
+ */
48
+ interruptedTurnResultOwed = false;
42
49
  /** The summary of the last task notification, which usually starts the next autonomous turn. */
43
50
  lastNotificationSummary;
44
51
  constructor(enabled, sessionId, publish,
@@ -262,6 +269,7 @@ export class AsyncTaskRuntime {
262
269
  }
263
270
  async finishAll(state) {
264
271
  this.autonomousTurn = undefined;
272
+ this.interruptedTurnResultOwed = false;
265
273
  const errors = [];
266
274
  for (const task of this.tasks.values()) {
267
275
  if ((task.announced || task.held) && !task.ignored && !isTerminal(task.state)) {
@@ -366,6 +374,33 @@ export class AsyncTaskRuntime {
366
374
  this.autonomousTurn = undefined;
367
375
  await this.finish(task, state, undefined, "event");
368
376
  }
377
+ /** A stop is about to interrupt the autonomous turn: its aborted result is owed. */
378
+ autonomousTurnInterrupting() {
379
+ this.interruptedTurnResultOwed = true;
380
+ }
381
+ /** The interrupt failed, so the turn goes on and no aborted result is owed. */
382
+ autonomousTurnInterruptFailed() {
383
+ this.interruptedTurnResultOwed = false;
384
+ }
385
+ /**
386
+ * Whether Claude Code started the work that a result reports: the result has
387
+ * an autonomous origin, or it is the aborted result that a stop owes. Call it
388
+ * for every result: the first one after the stop ends the debt, even when
389
+ * the result has an autonomous origin. A turn that a scheduler fire started
390
+ * has results with no `origin`, so the origin cannot tell it from a waiting
391
+ * prompt's result. The first result is the turn's when it is aborted and
392
+ * names no waiting prompt (`answersPrompt`). A non-aborted result means the
393
+ * interrupted turn finished without an aborted result, and one that names a
394
+ * waiting prompt means the turn took the prompt in; neither is the turn's.
395
+ * This relies on the CLI emitting the interrupted turn's result before the
396
+ * next turn's, which nothing enforces here.
397
+ */
398
+ startedByClaudeCode(result, answersPrompt) {
399
+ const owed = this.interruptedTurnResultOwed;
400
+ this.interruptedTurnResultOwed = false;
401
+ return ((result.origin != null && AUTONOMOUS_RESULT_ORIGINS.has(result.origin.kind)) ||
402
+ (owed && isAbortedResult(result) && !answersPrompt));
403
+ }
369
404
  /** Whether the task stands for an autonomous turn, which a stop interrupts. */
370
405
  isAutonomousTurn(taskId) {
371
406
  return this.tasks.get(taskId)?.autonomousTurn === true;
@@ -425,6 +460,7 @@ export class AsyncTaskRuntime {
425
460
  this.tasks.clear();
426
461
  this.outputPathsByToolCall.clear();
427
462
  this.autonomousTurn = undefined;
463
+ this.interruptedTurnResultOwed = false;
428
464
  this.lastNotificationSummary = undefined;
429
465
  }
430
466
  /**
@@ -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,mBAAmB,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,CAE3D;AAED;;;GAGG;AACH,wBAAsB,aAAa,IAAI,OAAO,CAAC,MAAM,CAAC,CAQrD;AAED,sGAAsG;AACtG,KAAK,QAAQ,GAAG,WAAW,CAAC,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAAC;AAE3D,yEAAyE;AACzE,wBAAgB,eAAe,CAAC,eAAe,EAAE,OAAO,CAAC,WAAW,CAAC,GAAG,OAAO,CAI9E;AAED;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAgB,WAAW,CAAC,eAAe,EAAE,OAAO,CAAC,WAAW,CAAC,GAAG;IAClE,kBAAkB,EAAE,QAAQ,CAAC;IAC7B,gBAAgB,EAAE,QAAQ,CAAC;CAC5B,CAIA"}
1
+ {"version":3,"file":"claude-cli.d.ts","sourceRoot":"","sources":["../src/claude-cli.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,YAAY,EAAE,MAAM,mCAAmC,CAAC;AACjE,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gCAAgC,CAAC;AAM9D;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,CAE3D;AAED;;;GAGG;AACH,wBAAsB,aAAa,IAAI,OAAO,CAAC,MAAM,CAAC,CAQrD;AAED,sGAAsG;AACtG,KAAK,QAAQ,GAAG,WAAW,CAAC,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAAC;AAE3D,yEAAyE;AACzE,wBAAgB,eAAe,CAAC,eAAe,EAAE,OAAO,CAAC,WAAW,CAAC,GAAG,OAAO,CAI9E;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,WAAW,CAAC,eAAe,EAAE,OAAO,CAAC,WAAW,CAAC,GAAG;IAClE,kBAAkB,EAAE,QAAQ,CAAC;IAC7B,gBAAgB,EAAE,QAAQ,CAAC;CAC5B,CAMA;AAYD;;;;;GAKG;AACH,wBAAgB,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);
@@ -35,8 +35,9 @@ export type McpOAuthSession = {
35
35
  readonly closed: AbortSignal;
36
36
  };
37
37
  /** Start OAuth in the background for the servers in `requestedServers` that
38
- * Claude reports as needing authentication. It does nothing while another
39
- * OAuth run of the session is in progress. */
38
+ * Claude reports as needing authentication. While an OAuth run of the
39
+ * session is in progress, the servers join it: it checks them after the
40
+ * sign-in that it waits for now. */
40
41
  export declare function startMcpServerAuthentication(client: McpOAuthClient, session: McpOAuthSession, requestedServers: Set<string>): void;
41
42
  /** Wait for a polling interval, resolving false when the session is aborted. */
42
43
  export declare function waitUnlessAborted(milliseconds: number, signal: AbortSignal): Promise<boolean>;
@@ -1 +1 @@
1
- {"version":3,"file":"mcp-oauth.d.ts","sourceRoot":"","sources":["../src/mcp-oauth.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EACV,+BAA+B,EAC/B,wBAAwB,EACxB,yBAAyB,EAC1B,MAAM,mCAAmC,CAAC;AAC3C,OAAO,KAAK,EAAmB,KA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AC,MAAM,EAAE;QAAE,KAAK,EAAE,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,IAAI,CAAA;KAAE,CAAC;CAC1D,CAAC;AAEF,8CAA8C;AAC9C,MAAM,MAAM,eAAe,GAAG;IAC5B,2DAA2D;IAC3D,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,wEAAwE;IACxE,YAAY,IAAI,KAAK,GAAG,SAAS,CAAC;IAClC,sCAAsC;IACtC,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAC;CAC9B,CAAC;AAKF;;;qCAGqC;AACrC,wBAAgB,4BAA4B,CAC1C,MAAM,EAAE,cAAc,EACtB,OAAO,EAAE,eAAe,EACxB,gBAAgB,EAAE,GAAG,CAAC,MAAM,CAAC,GAC5B,IAAI,CAiBN;AA0ID,gFAAgF;AAChF,wBAAgB,iBAAiB,CAAC,YAAY,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,CAa7F"}
package/dist/mcp-oauth.js CHANGED
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * OAuth for the MCP servers that Claude Code reports as `needs-auth`, as an
3
- * ACP URL elicitation. Protocol-neutral: the v1 core and the v2 core
4
- * both start it once a session's setup response is sent.
3
+ * ACP URL elicitation. Protocol-neutral: the v1 core and the v2 core start it
4
+ * for the session's ACP servers once a session's setup response is sent, and
5
+ * for the servers that a `/mcp reconnect` tried once its output is sent.
5
6
  */
6
7
  import { randomUUID } from "node:crypto";
7
8
  /** Claude Code keeps the OAuth callback listener open in the background after
@@ -13,47 +14,84 @@ const MCP_OAUTH_TIMEOUT_MS = 10 * 60_000;
13
14
  export function supportsMcpOAuth(query) {
14
15
  return typeof query.mcpAuthenticate === "function";
15
16
  }
17
+ /** The servers that the session's OAuth run has yet to check, by session key. */
16
18
  const mcpAuthentications = new WeakMap();
17
19
  /** Start OAuth in the background for the servers in `requestedServers` that
18
- * Claude reports as needing authentication. It does nothing while another
19
- * OAuth run of the session is in progress. */
20
+ * Claude reports as needing authentication. While an OAuth run of the
21
+ * session is in progress, the servers join it: it checks them after the
22
+ * sign-in that it waits for now. */
20
23
  export function startMcpServerAuthentication(client, session, requestedServers) {
21
24
  if (!client.urlElicitation || requestedServers.size === 0)
22
25
  return;
23
26
  const query = session.currentQuery();
24
- if (!query || mcpAuthentications.has(session.key))
27
+ if (!query)
25
28
  return;
26
- const authentication = authenticateMcpServers(client, session, query, requestedServers)
27
- .catch((error) => {
29
+ const running = mcpAuthentications.get(session.key);
30
+ if (running) {
31
+ for (const name of requestedServers)
32
+ running.add(name);
33
+ return;
34
+ }
35
+ const wanted = new Set(requestedServers);
36
+ mcpAuthentications.set(session.key, wanted);
37
+ authenticateMcpServers(client, session, query, wanted).catch((error) => {
28
38
  if (!session.closed.aborted) {
29
39
  client.logger.error(`Failed to inspect MCP servers for OAuth: ${error}`);
30
40
  }
31
- })
32
- .finally(() => {
33
- if (mcpAuthentications.get(session.key) === authentication) {
34
- mcpAuthentications.delete(session.key);
35
- }
36
41
  });
37
- mcpAuthentications.set(session.key, authentication);
38
42
  }
39
- async function authenticateMcpServers(client, session, query, requestedServers) {
40
- if (!supportsMcpOAuth(query)) {
41
- client.logger.error("The Claude Agent SDK does not expose MCP OAuth authentication.");
42
- return;
43
- }
44
- const statuses = await query.mcpServerStatus();
45
- for (const status of statuses) {
46
- if (status.status !== "needs-auth" || !requestedServers.has(status.name))
47
- continue;
48
- try {
49
- await authenticateMcpServer(client, session, query, status.name);
43
+ /** Signs in to the servers of `wanted` that need it, until `wanted` is empty.
44
+ * A server that reads `pending` stays in `wanted`: Claude Code connects the
45
+ * servers in the background, so right after a warm `session/new` a server
46
+ * that needs OAuth still reads `pending`. The run stops waiting for it
47
+ * {@link MCP_OAUTH_TIMEOUT_MS} after the run started, or when the session
48
+ * closes or its query is replaced. The run leaves `mcpAuthentications` in the same synchronous step
49
+ * that finds `wanted` empty, so a server added later starts a new run. */
50
+ async function authenticateMcpServers(client, session, query, wanted) {
51
+ try {
52
+ if (!supportsMcpOAuth(query)) {
53
+ client.logger.error("The Claude Agent SDK does not expose MCP OAuth authentication.");
54
+ return;
50
55
  }
51
- catch (error) {
52
- if (session.currentQuery() && !session.closed.aborted) {
53
- client.logger.error(`Failed to authenticate MCP server ${status.name}: ${error}`);
56
+ const deadline = Date.now() + MCP_OAUTH_TIMEOUT_MS;
57
+ while (wanted.size > 0) {
58
+ if (session.currentQuery() !== query)
59
+ return;
60
+ // A server that joins during the read is checked by the next one.
61
+ const checked = [...wanted];
62
+ const statuses = new Map((await query.mcpServerStatus()).map((status) => [status.name, status.status]));
63
+ const settled = checked.filter((name) => statuses.get(name) !== "pending");
64
+ for (const name of settled)
65
+ wanted.delete(name);
66
+ for (const name of settled) {
67
+ if (statuses.get(name) !== "needs-auth")
68
+ continue;
69
+ if (session.currentQuery() !== query)
70
+ return;
71
+ try {
72
+ await authenticateMcpServer(client, session, query, name);
73
+ }
74
+ catch (error) {
75
+ if (session.currentQuery() && !session.closed.aborted) {
76
+ client.logger.error(`Failed to authenticate MCP server ${name}: ${error}`);
77
+ }
78
+ }
54
79
  }
80
+ // Wait only when every server left read `pending`; read again at once
81
+ // for one that joined meanwhile.
82
+ const onlyPending = [...wanted].every((name) => checked.includes(name) && !settled.includes(name));
83
+ if (wanted.size === 0 || !onlyPending)
84
+ continue;
85
+ if (Date.now() >= deadline)
86
+ return;
87
+ if (!(await waitUnlessAborted(MCP_OAUTH_STATUS_POLL_MS, session.closed)))
88
+ return;
55
89
  }
56
90
  }
91
+ finally {
92
+ if (mcpAuthentications.get(session.key) === wanted)
93
+ mcpAuthentications.delete(session.key);
94
+ }
57
95
  }
58
96
  /** Bridge Claude Code's startup MCP OAuth control to ACP URL elicitation.
59
97
  * Claude opens and owns the localhost callback listener; the ACP client only
@@ -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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AAM,CAAC;IACf,yEAAyE;IACzE,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,wBAAsB,eAAe,CACnC,SAAS,EAAE,MAAM,EACjB,MAAM,CAAC,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.