@agentclientprotocol/claude-agent-acp 0.102.1-preview.1 → 0.102.1-preview.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (203) hide show
  1. package/README.md +5 -1
  2. package/dist/acp-agent.d.ts +113 -439
  3. package/dist/acp-agent.d.ts.map +1 -1
  4. package/dist/acp-agent.js +362 -2409
  5. package/dist/acp-subagents.d.ts +1 -2
  6. package/dist/acp-subagents.d.ts.map +1 -1
  7. package/dist/auth-methods.d.ts +21 -0
  8. package/dist/auth-methods.d.ts.map +1 -0
  9. package/dist/auth-methods.js +68 -0
  10. package/dist/auth-status-reporter.d.ts +112 -0
  11. package/dist/auth-status-reporter.d.ts.map +1 -0
  12. package/dist/auth-status-reporter.js +253 -0
  13. package/dist/background-work.d.ts +12 -265
  14. package/dist/background-work.d.ts.map +1 -1
  15. package/dist/background-work.js +8 -558
  16. package/dist/client-system-prompt.d.ts +7 -0
  17. package/dist/client-system-prompt.d.ts.map +1 -1
  18. package/dist/client-system-prompt.js +24 -0
  19. package/dist/context-compaction.d.ts +20 -0
  20. package/dist/context-compaction.d.ts.map +1 -1
  21. package/dist/context-compaction.js +26 -0
  22. package/dist/context-window.d.ts +70 -0
  23. package/dist/context-window.d.ts.map +1 -0
  24. package/dist/context-window.js +132 -0
  25. package/dist/diff.d.ts +1 -1
  26. package/dist/diff.js +1 -1
  27. package/dist/elicitation.d.ts +66 -1
  28. package/dist/elicitation.d.ts.map +1 -1
  29. package/dist/elicitation.js +109 -0
  30. package/dist/file-change-audit.d.ts +4 -3
  31. package/dist/file-change-audit.d.ts.map +1 -1
  32. package/dist/file-change-audit.js +3 -2
  33. package/dist/mcp-oauth.d.ts +44 -0
  34. package/dist/mcp-oauth.d.ts.map +1 -0
  35. package/dist/mcp-oauth.js +142 -0
  36. package/dist/mcp-servers.d.ts +10 -0
  37. package/dist/mcp-servers.d.ts.map +1 -0
  38. package/dist/mcp-servers.js +29 -0
  39. package/dist/native-subagents.d.ts +18 -8
  40. package/dist/native-subagents.d.ts.map +1 -1
  41. package/dist/native-subagents.js +7 -35
  42. package/dist/permissions/presentation.d.ts +29 -0
  43. package/dist/permissions/presentation.d.ts.map +1 -1
  44. package/dist/permissions/presentation.js +38 -11
  45. package/dist/prompt-suggestions.d.ts +29 -0
  46. package/dist/prompt-suggestions.d.ts.map +1 -1
  47. package/dist/prompt-suggestions.js +45 -0
  48. package/dist/providers.d.ts +139 -0
  49. package/dist/providers.d.ts.map +1 -0
  50. package/dist/providers.js +286 -0
  51. package/dist/remote-control.d.ts +62 -0
  52. package/dist/remote-control.d.ts.map +1 -0
  53. package/dist/remote-control.js +78 -0
  54. package/dist/result-end.d.ts +39 -0
  55. package/dist/result-end.d.ts.map +1 -0
  56. package/dist/result-end.js +50 -0
  57. package/dist/serve.d.ts +7 -2
  58. package/dist/serve.d.ts.map +1 -1
  59. package/dist/serve.js +10 -5
  60. package/dist/session-config-ids.d.ts +1 -0
  61. package/dist/session-config-ids.d.ts.map +1 -1
  62. package/dist/session-config-ids.js +1 -0
  63. package/dist/session-config-options.d.ts +64 -0
  64. package/dist/session-config-options.d.ts.map +1 -0
  65. package/dist/session-config-options.js +162 -0
  66. package/dist/session-effort.d.ts +67 -0
  67. package/dist/session-effort.d.ts.map +1 -1
  68. package/dist/session-effort.js +98 -0
  69. package/dist/session-env.d.ts +22 -0
  70. package/dist/session-env.d.ts.map +1 -0
  71. package/dist/session-env.js +66 -0
  72. package/dist/session-fast-mode.d.ts +83 -0
  73. package/dist/session-fast-mode.d.ts.map +1 -0
  74. package/dist/session-fast-mode.js +142 -0
  75. package/dist/session-index/connection.d.ts +2 -5
  76. package/dist/session-index/connection.d.ts.map +1 -1
  77. package/dist/session-index/connection.js +3 -5
  78. package/dist/session-mode.d.ts +1 -0
  79. package/dist/session-mode.d.ts.map +1 -1
  80. package/dist/session-mode.js +1 -1
  81. package/dist/session-model.d.ts +41 -0
  82. package/dist/session-model.d.ts.map +1 -1
  83. package/dist/session-model.js +110 -45
  84. package/dist/session-notices.d.ts +44 -0
  85. package/dist/session-notices.d.ts.map +1 -1
  86. package/dist/session-notices.js +68 -0
  87. package/dist/session-titles.d.ts +34 -12
  88. package/dist/session-titles.d.ts.map +1 -1
  89. package/dist/session-titles.js +7 -6
  90. package/dist/session-usage.d.ts +125 -0
  91. package/dist/session-usage.d.ts.map +1 -0
  92. package/dist/session-usage.js +196 -0
  93. package/dist/streamed-text.d.ts +33 -0
  94. package/dist/streamed-text.d.ts.map +1 -0
  95. package/dist/streamed-text.js +71 -0
  96. package/dist/subagent-configuration.d.ts +32 -0
  97. package/dist/subagent-configuration.d.ts.map +1 -0
  98. package/dist/subagent-configuration.js +70 -0
  99. package/dist/subagent-replay.d.ts +18 -0
  100. package/dist/subagent-replay.d.ts.map +1 -1
  101. package/dist/subagent-replay.js +25 -15
  102. package/dist/tool-calls/client-capabilities.d.ts +8 -8
  103. package/dist/tool-calls/client-capabilities.js +4 -4
  104. package/dist/tool-calls/renderer.d.ts +4 -5
  105. package/dist/tool-calls/renderer.d.ts.map +1 -1
  106. package/dist/tool-calls/renderer.js +4 -5
  107. package/dist/turn-events.d.ts +6 -46
  108. package/dist/turn-events.d.ts.map +1 -1
  109. package/dist/v2/agent.d.ts +7 -11
  110. package/dist/v2/agent.d.ts.map +1 -1
  111. package/dist/v2/agent.js +751 -331
  112. package/dist/v2/air.d.ts +33 -0
  113. package/dist/v2/air.d.ts.map +1 -0
  114. package/dist/v2/air.js +29 -0
  115. package/dist/v2/auth.d.ts +97 -0
  116. package/dist/v2/auth.d.ts.map +1 -0
  117. package/dist/v2/auth.js +216 -0
  118. package/dist/v2/background.d.ts +27 -16
  119. package/dist/v2/background.d.ts.map +1 -1
  120. package/dist/v2/background.js +4 -32
  121. package/dist/v2/child-config.d.ts +55 -0
  122. package/dist/v2/child-config.d.ts.map +1 -0
  123. package/dist/v2/child-config.js +92 -0
  124. package/dist/v2/clear-context.d.ts +94 -0
  125. package/dist/v2/clear-context.d.ts.map +1 -0
  126. package/dist/v2/clear-context.js +176 -0
  127. package/dist/v2/commands.d.ts +46 -0
  128. package/dist/v2/commands.d.ts.map +1 -0
  129. package/dist/v2/commands.js +54 -0
  130. package/dist/v2/config.d.ts +187 -0
  131. package/dist/v2/config.d.ts.map +1 -0
  132. package/dist/v2/config.js +494 -0
  133. package/dist/v2/elicitation.d.ts +93 -0
  134. package/dist/v2/elicitation.d.ts.map +1 -0
  135. package/dist/v2/elicitation.js +160 -0
  136. package/dist/v2/file-changes.d.ts +61 -0
  137. package/dist/v2/file-changes.d.ts.map +1 -0
  138. package/dist/v2/file-changes.js +108 -0
  139. package/dist/v2/file-preview.d.ts +18 -0
  140. package/dist/v2/file-preview.d.ts.map +1 -0
  141. package/dist/v2/file-preview.js +29 -0
  142. package/dist/v2/initialize.d.ts +10 -24
  143. package/dist/v2/initialize.d.ts.map +1 -1
  144. package/dist/v2/initialize.js +4 -111
  145. package/dist/v2/outcome.d.ts +81 -0
  146. package/dist/v2/outcome.d.ts.map +1 -0
  147. package/dist/v2/outcome.js +165 -0
  148. package/dist/v2/permissions.d.ts +92 -0
  149. package/dist/v2/permissions.d.ts.map +1 -0
  150. package/dist/v2/permissions.js +162 -0
  151. package/dist/v2/prompt.d.ts +2 -42
  152. package/dist/v2/prompt.d.ts.map +1 -1
  153. package/dist/v2/prompt.js +2 -119
  154. package/dist/v2/remote-control.d.ts +41 -0
  155. package/dist/v2/remote-control.d.ts.map +1 -0
  156. package/dist/v2/remote-control.js +63 -0
  157. package/dist/v2/reports.d.ts +198 -0
  158. package/dist/v2/reports.d.ts.map +1 -0
  159. package/dist/v2/reports.js +487 -0
  160. package/dist/v2/restarts.d.ts +128 -0
  161. package/dist/v2/restarts.d.ts.map +1 -0
  162. package/dist/v2/restarts.js +348 -0
  163. package/dist/v2/session-requests.d.ts +20 -0
  164. package/dist/v2/session-requests.d.ts.map +1 -0
  165. package/dist/v2/session-requests.js +108 -0
  166. package/dist/v2/session-update.d.ts +2 -13
  167. package/dist/v2/session-update.d.ts.map +1 -1
  168. package/dist/v2/session-update.js +2 -22
  169. package/dist/v2/session.d.ts +340 -41
  170. package/dist/v2/session.d.ts.map +1 -1
  171. package/dist/v2/session.js +1223 -141
  172. package/dist/v2/setup.d.ts +49 -0
  173. package/dist/v2/setup.d.ts.map +1 -0
  174. package/dist/v2/setup.js +62 -0
  175. package/dist/v2/stopped-work.d.ts +123 -0
  176. package/dist/v2/stopped-work.d.ts.map +1 -0
  177. package/dist/v2/stopped-work.js +210 -0
  178. package/dist/v2/stream.d.ts +228 -0
  179. package/dist/v2/stream.d.ts.map +1 -0
  180. package/dist/v2/stream.js +506 -0
  181. package/dist/v2/subagent-replay.d.ts +115 -0
  182. package/dist/v2/subagent-replay.d.ts.map +1 -0
  183. package/dist/v2/subagent-replay.js +479 -0
  184. package/dist/v2/subscription-guard.d.ts +60 -0
  185. package/dist/v2/subscription-guard.d.ts.map +1 -0
  186. package/dist/v2/subscription-guard.js +84 -0
  187. package/dist/v2/tasks.d.ts +492 -0
  188. package/dist/v2/tasks.d.ts.map +1 -0
  189. package/dist/v2/tasks.js +1728 -0
  190. package/dist/v2/terminal.d.ts.map +1 -1
  191. package/dist/v2/terminal.js +6 -1
  192. package/dist/v2/tool-call.d.ts +3 -2
  193. package/dist/v2/tool-call.d.ts.map +1 -1
  194. package/dist/v2/update-translator.d.ts +36 -0
  195. package/dist/v2/update-translator.d.ts.map +1 -0
  196. package/dist/v2/update-translator.js +80 -0
  197. package/dist/workflow-progress.d.ts +23 -0
  198. package/dist/workflow-progress.d.ts.map +1 -1
  199. package/dist/workflow-progress.js +31 -8
  200. package/package.json +1 -1
  201. package/dist/v2/permission.d.ts +0 -28
  202. package/dist/v2/permission.d.ts.map +0 -1
  203. package/dist/v2/permission.js +0 -41
package/dist/v2/agent.js CHANGED
@@ -1,383 +1,803 @@
1
- import * as v2 from "@agentclientprotocol/sdk/experimental/v2/unstable";
2
- import { ClaudeAcpAgent } from "../acp-agent.js";
3
- import { stateUpdate, V2Background } from "./background.js";
4
- import { v1InitializeRequest, v2InitializeResponse } from "./initialize.js";
5
- import { v1PermissionResponse, v2PermissionRequest } from "./permission.js";
6
- import { v2Foreground, v2Prompt } from "./prompt.js";
7
- import { v1ForkSessionRequest, v1NewSessionRequest, v1RestoreSessionRequest, v1SetSessionConfigOptionRequest, v2AvailableCommands, v2ConfigOptions, v2NewSessionResponse, v2ResumeSessionResponse, } from "./session.js";
8
- import { v2ChildStateUpdate, v2SessionUpdate } from "./session-update.js";
9
- import { V2Terminals } from "./terminal.js";
10
- import { V2ToolCallMeta } from "./tool-call-meta.js";
11
- import { v2RestartedToolCall } from "./tool-call.js";
12
1
  /**
13
- * The ACP v2 surface, for one connection.
14
- *
15
- * As in `v1AgentApp`, the agent of the connection is created when the
16
- * connection opens, before the connection processes any inbound message.
17
- * `onAgent` receives it for the owner of the process (shutdown).
2
+ * The ACP v2 core: serves ACP v2 straight from Claude Code, without
3
+ * `ClaudeAcpAgent`.
18
4
  *
19
- * The provider methods pass through: their types are the same in v1 and v2.
5
+ * The adapter's ACP v2 implementation. Unlike the v1 core, it holds no turn
6
+ * open and matches no echoes: each session mirrors its Claude Code query (see
7
+ * `session.ts`). It shares the protocol-neutral pieces with v1: the SDK
8
+ * message mapping, tool call rendering, permission options, and the mode
9
+ * catalog. It serves a JetBrains AIR client the AIR extensions that v2 does
10
+ * not cover (see `air.ts`).
20
11
  */
12
+ import { randomUUID } from "node:crypto";
13
+ import * as fs from "node:fs/promises";
14
+ import * as path from "node:path";
15
+ import { RequestError, } from "@agentclientprotocol/sdk/unstable";
16
+ import * as v2 from "@agentclientprotocol/sdk/experimental/v2/unstable";
17
+ import { deleteSession, getSessionMessages, listSessions, query, } from "@anthropic-ai/claude-agent-sdk";
18
+ import packageJson from "../../package.json" with { type: "json" };
19
+ import { messageIdForGrouping } from "../acp-agent.js";
20
+ import { customAgents } from "../session-config-options.js";
21
+ import { claudeCliPath } from "../claude-cli.js";
22
+ import { clientSystemPrompt, sessionSystemPrompt } from "../client-system-prompt.js";
23
+ import { forkSession } from "../fork-session.js";
24
+ import { supportsMcpOAuth } from "../mcp-oauth.js";
25
+ import { sdkMcpServers } from "../mcp-servers.js";
26
+ import { ALLOW_BYPASS, autoModeDisabled } from "../permissions/modes.js";
27
+ import { readResumedTail, resumedModelFromTranscript } from "../resumed-session.js";
28
+ import { mergeEffortSettings } from "../session-effort.js";
29
+ import { configuredSettings, resolveThinkingConfig } from "../session-env.js";
30
+ import { resolveInitialPermissionMode } from "../session-mode.js";
31
+ import { sanitizeTitle } from "../session-titles.js";
32
+ import { SettingsManager } from "../settings.js";
33
+ import { STARTUP_FAILURE_RESULTS_ENV, startupFailureError } from "../startup-failure.js";
34
+ import { createPostToolUseHook } from "../tools.js";
35
+ import { Pushable } from "../utils.js";
36
+ import { V2_SESSION_CAPABILITIES } from "./initialize.js";
37
+ import { v1ForkSessionRequest, v1NewSessionRequest } from "./session-requests.js";
38
+ import { V2UpdateTranslator } from "./update-translator.js";
39
+ import { airInitializeMeta, airSupport, NO_AIR } from "./air.js";
40
+ import { V2Auth } from "./auth.js";
41
+ import { subagentHooks } from "./child-config.js";
42
+ import { modelSwitchHook, SessionConfig } from "./config.js";
43
+ import { fileChangePreviewHook } from "./file-preview.js";
44
+ import { canUseTool, denyingStoppedWork } from "./permissions.js";
45
+ import { reportHooks } from "./reports.js";
46
+ import { SessionRestarts } from "./restarts.js";
47
+ import { V2Session } from "./session.js";
48
+ import { afterSetupResponse, clientOptions, replayEndUpdate, sessionModels, withClientHooks, } from "./setup.js";
49
+ import { SubscriptionGuard } from "./subscription-guard.js";
50
+ import { restrictedChild } from "./tasks.js";
51
+ /** The sessions per `session/list` page. */
52
+ const SESSION_LIST_PAGE_SIZE = 1000;
53
+ /** The ACP v2 surface, for one connection. */
21
54
  export function v2AgentApp(logger, onAgent) {
22
55
  let agent;
23
- let client;
24
- return v2
56
+ return (v2
25
57
  .agent({ name: "claude-code-acp" })
26
58
  .onConnect((connection) => {
27
- client = new V2ClientConnection(connection.client, logger ?? console);
28
- agent = new ClaudeAcpAgent(client, logger, {
29
- v2: true,
30
- foreground: (sessionId) => v2Foreground((update) => {
31
- void client.send({ sessionId, update });
32
- }),
33
- background: {
34
- changed: (report) => {
35
- for (const notification of client.background.changed(report)) {
36
- void client.send(notification);
37
- }
38
- },
39
- forget: (sessionId) => client.background.forget(sessionId),
40
- },
41
- });
59
+ agent = new V2Agent(connection.client, logger ?? console);
42
60
  onAgent(agent);
43
61
  })
44
- .onRequest(v2.methods.agent.initialize, async ({ params }) => v2InitializeResponse(await agent.initialize(v1InitializeRequest(params))))
45
- .onRequest(v2.methods.agent.auth.login, ({ params }) => agent.authenticate(params))
46
- .onRequest(v2.methods.agent.auth.logout, ({ params }) => agent.logout(params))
47
- .onRequest(v2.methods.agent.providers.list, ({ params }) => agent.unstable_listProviders(params))
48
- .onRequest(v2.methods.agent.providers.set, ({ params }) => agent.unstable_setProvider(params))
49
- .onRequest(v2.methods.agent.providers.disable, ({ params }) => agent.unstable_disableProvider(params))
50
- .onRequest(v2.methods.agent.session.new, async ({ params }) => {
51
- const request = v1NewSessionRequest(params);
52
- const response = await agent.newSession(request);
53
- const commands = await setupCommands(agent, response.sessionId, logger);
54
- afterSetupResponse(agent, response.sessionId, request.mcpServers, commands, logger);
55
- return { ...v2NewSessionResponse(response), ...commands };
56
- })
62
+ .onRequest(v2.methods.agent.initialize, ({ params }) => agent.initialize(params))
63
+ .onRequest(v2.methods.agent.auth.login, ({ params }) => agent.auth.login(params))
64
+ .onRequest(v2.methods.agent.auth.logout, () => agent.auth.logout())
65
+ .onRequest(v2.methods.agent.providers.list, () => agent.auth.listProviders())
66
+ .onRequest(v2.methods.agent.providers.set, ({ params }) => agent.auth.setProvider(params))
67
+ .onRequest(v2.methods.agent.providers.disable, ({ params }) => agent.auth.disableProvider(params))
68
+ .onRequest(v2.methods.agent.session.new, ({ params }) => agent.newSession(params))
69
+ .onRequest(v2.methods.agent.session.resume, ({ params }) => agent.resumeSession(params))
70
+ .onRequest(v2.methods.agent.session.fork, ({ params }) => agent.forkSession(params))
57
71
  .onRequest(v2.methods.agent.session.list, ({ params }) => agent.listSessions(params))
58
- .onRequest(v2.methods.agent.session.resume, async ({ params }) => {
59
- const restore = v1RestoreSessionRequest(params);
60
- const response = restore.method === "resume"
61
- ? await agent.resumeSession(restore.request)
62
- : await client.replaying(params.sessionId, () => agent.loadSession(restore.request));
63
- // v2 asks for the current title and `updatedAt` after the replay and
64
- // before the response, also without a replay, as the client may hold
65
- // none or stale ones.
66
- await agent.publishCurrentSessionInfo(params.sessionId);
67
- // v2 requires a snapshot of the foreground state after the replay and
68
- // before the response, also without a replay: a resumed live session can
69
- // be running a turn, or waiting on a permission request. The current
70
- // state of each subagent, terminal and tool call it lists comes first,
71
- // as v2 requires. The subagents' go again after the response (see below).
72
- await agent.publishLiveSubagents(params.sessionId, client.background.listedSubagents(params.sessionId));
73
- await agent.publishBackgroundToolCalls(params.sessionId, client.background.listedToolCalls(params.sessionId));
74
- for (const notification of client.background.currentItems(params.sessionId)) {
75
- void client.send(notification);
76
- }
77
- void client.send({
78
- sessionId: params.sessionId,
79
- update: stateUpdate(agent.foregroundState(params.sessionId)),
80
- });
81
- const commands = await setupCommands(agent, params.sessionId, logger);
82
- // The response ends a replay. The subagents RFD treats the replayed
83
- // subagent states before it as history, so their current states follow it.
84
- afterSetupResponse(agent, params.sessionId, restore.request.mcpServers ?? [], commands, logger, () => void agent.publishCurrentSubagentStates(params.sessionId));
85
- return { ...v2ResumeSessionResponse(response), ...commands };
86
- })
87
- .onRequest(v2.methods.agent.session.fork, ({ params }) => agent.forking(params.sessionId, async () => {
88
- // The agent starts the forked session, so the client can prompt it.
89
- const request = v1ForkSessionRequest(params);
90
- const response = await agent.unstable_forkSession(request);
91
- const commands = await setupCommands(agent, response.sessionId, logger);
92
- afterSetupResponse(agent, response.sessionId, request.mcpServers ?? [], commands, logger);
93
- return {
94
- sessionId: response.sessionId,
95
- ...v2ResumeSessionResponse(response),
96
- ...commands,
97
- };
98
- }))
99
- .onRequest(v2.methods.agent.session.close, async ({ params }) => {
100
- const response = await agent.closeSession(params);
101
- client.terminals.forget(params.sessionId);
102
- client.toolCallMeta.forget(params.sessionId);
103
- return response;
104
- })
72
+ .onRequest(v2.methods.agent.session.close, ({ params }) => agent.closeSession(params))
105
73
  .onRequest(v2.methods.agent.session.delete, ({ params }) => agent.deleteSession(params))
106
- .onRequest(v2.methods.agent.session.setConfigOption, async ({ params }) => {
107
- const { configOptions, ...response } = await agent.setSessionConfigOption(v1SetSessionConfigOptionRequest(params));
108
- // v2 asks for a `config_option_update` on every config change, also one
109
- // that a client requested, so other attached clients see it. It goes
110
- // before the response, as v2 asks of this duplicate. The agent sends v1
111
- // clients none: they read the change from the response only.
112
- const options = v2ConfigOptions(configOptions);
113
- void client.send({
114
- sessionId: params.sessionId,
115
- update: { sessionUpdate: "config_option_update", configOptions: options },
116
- });
117
- return { ...response, configOptions: options };
118
- })
119
- .onRequest(v2.methods.agent.session.prompt, ({ params }) => v2Prompt(agent, params, (update) => {
120
- void client.send({ sessionId: params.sessionId, update });
121
- }))
122
- .onRequest(v2.methods.agent.terminal.cancel, async ({ params }) => {
123
- await agent.cancelBackgroundTerminal(params);
124
- return {};
125
- })
126
- .onRequest(v2.methods.agent.toolCall.cancel, async ({ params }) => {
127
- await agent.cancelBackgroundToolCall(params);
128
- return {};
129
- })
130
- .onNotification(v2.methods.agent.session.cancel, ({ params }) => agent.cancel(params));
131
- }
132
- /**
133
- * The `availableCommands` of a setup response, which v2 requires when the
134
- * session has commands. The agent sends a v1 client the same list as an
135
- * `available_commands_update` after the response, and a v2 client none
136
- * (`ClaudeAcpAgent.afterSetupResponse`). Later changes still arrive as
137
- * updates. An empty list is left out, as the draft asks. A failure to read
138
- * the commands does not fail the setup: the result is `undefined`, and
139
- * {@link afterSetupResponse} sends the commands in an update instead.
140
- */
141
- async function setupCommands(agent, sessionId, logger) {
142
- try {
143
- const commands = await agent.availableCommands(sessionId);
144
- return commands.length > 0 ? { availableCommands: v2AvailableCommands(commands) } : {};
145
- }
146
- catch (error) {
147
- (logger ?? console).error(`Session ${sessionId}: failed to read the session's commands`, error);
148
- return undefined;
149
- }
74
+ .onRequest(v2.methods.agent.session.setConfigOption, ({ params }) => agent.setConfigOption(params))
75
+ .onRequest(v2.methods.agent.session.prompt, ({ params }) => agent.prompt(params))
76
+ .onRequest(v2.methods.agent.terminal.cancel, ({ params }) => agent.cancelItem(params.sessionId, { terminalId: params.terminalId }))
77
+ .onRequest(v2.methods.agent.toolCall.cancel, ({ params }) => agent.cancelItem(params.sessionId, { toolCallId: params.toolCallId }))
78
+ // `session/cancel` of a session that is not active is ignored. A
79
+ // subagent's session advertises `cancel`: it stops the subagent's run.
80
+ .onNotification(v2.methods.agent.session.cancel, ({ params }) => agent.cancel(params.sessionId)));
150
81
  }
151
- /**
152
- * The work that follows a v2 setup response, run once the response is sent
153
- * (`ClaudeAcpAgent.afterSetupResponse` does it on v1):
154
- *
155
- * - When `commands` is `undefined` (reading them for the response failed),
156
- * an `available_commands_update` with the commands, read again.
157
- * - `then`, such as sending the current states of replayed subagents.
158
- * - OAuth for the MCP servers that need it. Its URL elicitation must not
159
- * reach the client before the response, which v2 asks against.
160
- */
161
- function afterSetupResponse(agent, sessionId, mcpServers, commands, logger, then) {
162
- setTimeout(() => {
163
- if (!commands) {
164
- agent.sendAvailableCommandsUpdate(sessionId).catch((error) => {
165
- (logger ?? console).error(`Session ${sessionId}: failed to send the session's commands`, error);
166
- });
167
- }
168
- then?.();
169
- agent.authenticateMcpServers(sessionId, mcpServers);
170
- }, 0);
171
- }
172
- /**
173
- * The {@link AcpClient} of an ACP v2 connection: it sends the v1 messages of
174
- * the agent as v2 messages.
175
- */
176
- class V2ClientConnection {
82
+ class V2Agent {
177
83
  ctx;
178
84
  logger;
85
+ sessions = new Map();
179
86
  /**
180
- * The sessions whose history replays, each with the messages that the
181
- * replay has cleared so far. A subagent that a replay announces replays
182
- * with it.
87
+ * The sessions whose query ended without `session/close`, with what to tell
88
+ * the client. v2 keeps a session active until it is closed or the
89
+ * connection ends, so its requests fail with what happened, not -32002,
90
+ * until a resume starts it again.
183
91
  */
184
- replays = new Map();
185
- /** The session whose replay announced each replaying subagent. */
186
- replayRoots = new Map();
92
+ stopped = new Map();
187
93
  /**
188
- * The last work state that a replay reported for each subagent, as the
189
- * `state_update` of the child's own stream. It goes out once the replay
190
- * ends: v2 forbids replaying a child's past `running` and `idle` as current
191
- * activity.
94
+ * The query starts that run, by session id, until each settles (see
95
+ * {@link startSession}). A resume, close or dispose of a session waits for
96
+ * its start, so a second start never replaces a running query.
192
97
  */
193
- replayedChildStates = new Map();
194
- /** The display terminals of the commands that the agent runs. */
195
- terminals = new V2Terminals();
196
- /** The `_meta` that the client stores for each tool call. */
197
- toolCallMeta = new V2ToolCallMeta();
198
- /** The `background` list of each session's `state_update`s. */
199
- background = new V2Background(this.terminals);
98
+ starting = new Map();
99
+ /**
100
+ * The `session/resume` handlers that run, by session id. A close waits for
101
+ * them, so a resume's replay, snapshot and response go out before the close
102
+ * response, and nothing of the session after it.
103
+ */
104
+ resuming = new Map();
105
+ translator = new V2UpdateTranslator();
106
+ auth;
107
+ /** The `--hide-claude-auth` subscription guard (see `subscription-guard.ts`). */
108
+ guard;
109
+ /** The restarts of the sessions' queries, for a new route or account (see `restarts.ts`). */
110
+ restarts;
111
+ /** What the client declared in `initialize`. */
112
+ clientCapabilities;
113
+ /** The elicitation modes that the client advertised in `initialize`. */
114
+ elicitation = { form: false, url: false };
115
+ /** The AIR extensions that the client takes (see `air.ts`). */
116
+ air = NO_AIR;
200
117
  constructor(ctx, logger) {
201
118
  this.ctx = ctx;
202
119
  this.logger = logger;
120
+ this.auth = new V2Auth(ctx, logger, {
121
+ routeChanged: () => this.restarts.reroute(),
122
+ probed: (kind) => this.guard.probed(kind),
123
+ });
124
+ this.guard = new SubscriptionGuard(this.auth, logger, (sessionId) => this.restarts.accountMayHaveChanged(sessionId));
125
+ this.restarts = new SessionRestarts({
126
+ logger,
127
+ active: (sessionId) => this.sessions.get(sessionId),
128
+ start: (sessionId, params) => this.restartSession(sessionId, params),
129
+ lost: async (sessionId, previous) => {
130
+ await previous.retire();
131
+ if (this.sessions.get(sessionId) === previous) {
132
+ this.stop(sessionId, "Claude Code could not start again. Resume the session to continue.");
133
+ }
134
+ },
135
+ send: (notification) => this.send(notification),
136
+ });
137
+ }
138
+ // --- SessionConnection ---------------------------------------------------
139
+ send(notification) {
140
+ this.ctx.notify(v2.methods.client.session.update, notification).catch((error) => {
141
+ this.logger.error(`Failed to send a ${notification.update.sessionUpdate} update:`, error);
142
+ });
203
143
  }
144
+ requestPermission(request, signal) {
145
+ // Aborting `signal` sends `$/cancel_request`, and stops waiting for the answer.
146
+ return this.ctx.request(v2.methods.client.session.requestPermission, request, {
147
+ cancellationSignal: signal,
148
+ stopWaitingOnCancel: true,
149
+ });
150
+ }
151
+ createElicitation(request, signal) {
152
+ // The v1 types accept a property schema with any tag; the v2 types accept
153
+ // one only in a received value. An MCP server's schema is relayed
154
+ // unchanged, as on v1, so this cast does not check it.
155
+ return this.ctx.request(v2.methods.client.elicitation.create, request, { cancellationSignal: signal, stopWaitingOnCancel: true });
156
+ }
157
+ completeElicitation(params) {
158
+ return this.ctx.notify(v2.methods.client.elicitation.complete, params);
159
+ }
160
+ ended(session) {
161
+ // The old query of a restart that replaced it already.
162
+ if (this.sessions.get(session.sessionId) !== session)
163
+ return;
164
+ this.stop(session.sessionId, "Claude Code stopped. Resume the session to continue.");
165
+ }
166
+ /** The session's query ended: a later `session/resume` starts it again from its transcript. */
167
+ stop(sessionId, message) {
168
+ this.sessions.delete(sessionId);
169
+ this.stopped.set(sessionId, message);
170
+ this.translator.forget(sessionId);
171
+ this.auth.sessionEnded(sessionId);
172
+ this.guard.sessionEnded(sessionId);
173
+ this.restarts.forget(sessionId);
174
+ }
175
+ signedOut(sessionId) {
176
+ this.guard.signedOut(sessionId);
177
+ }
178
+ // --- Requests --------------------------------------------------------------
204
179
  /**
205
- * Runs `restore`, which replays the history of `sessionId`.
206
- *
207
- * The agent replays messages as chunks. A v2 client may still hold a
208
- * replayed message, and chunks append, so before the first replayed chunk of
209
- * each message the client gets the message with no content, which clears it,
210
- * as v2 requires of a message replayed as chunks.
180
+ * The v2 handshake. An AIR client gets the AIR capabilities that this core
181
+ * serves in the response's `_meta` (see `air.ts`).
182
+ */
183
+ initialize(request) {
184
+ this.clientCapabilities = request.capabilities;
185
+ this.elicitation = {
186
+ form: request.capabilities?.elicitation?.form != null,
187
+ url: request.capabilities?.elicitation?.url != null,
188
+ };
189
+ this.air = airSupport(request.capabilities);
190
+ const { authMethods, _meta } = this.auth.initialize(request.capabilities);
191
+ const airMeta = airInitializeMeta(this.air);
192
+ return {
193
+ ...(airMeta ? { _meta: airMeta } : {}),
194
+ protocolVersion: v2.PROTOCOL_VERSION,
195
+ info: { name: packageJson.name, title: "Claude Agent", version: packageJson.version },
196
+ capabilities: {
197
+ session: V2_SESSION_CAPABILITIES,
198
+ // `providers/list`, `set`, and `disable`, served for every client.
199
+ providers: {},
200
+ // A prompt that comes while Claude works waits in Claude Code's queue.
201
+ _meta: { claudeCode: { promptQueueing: true }, ..._meta },
202
+ },
203
+ authMethods,
204
+ };
205
+ }
206
+ /**
207
+ * `session/prompt`. Each prompt reads the auth identity again, as on v1. A
208
+ * restart of the session's query that is due runs first (see
209
+ * `restarts.ts`), then the subscription guard judges the account, among
210
+ * the session's prompts (see `V2Session.prompt`). The restart's await
211
+ * happens only when one is due, so the prompts of a session keep their
212
+ * order.
211
213
  *
212
- * Each replayed subagent gets one `state_update` on its own stream, with its
213
- * last state, after the replay.
214
+ * Not `async`, and the session's promise is returned as is: the response
215
+ * then goes out before the turn's `running`, which the session sends right
216
+ * after it resolves the prompt. Nothing enforces this
217
+ * order but the number of promise hops (v2 allows either), and the golden
218
+ * files of the scenarios (`acp-scenarios-v2.test.ts`) hold it.
214
219
  */
215
- async replaying(sessionId, restore) {
216
- this.replays.set(sessionId, new Set());
217
- const children = () => [...this.replayRoots].filter(([, root]) => root === sessionId).map(([child]) => child);
220
+ prompt(params) {
221
+ const prompt = () => this.session(params.sessionId, "prompt").prompt(params, (query) => this.guard.beforePrompt(params.sessionId, query));
218
222
  try {
219
- const result = await restore();
220
- for (const child of children()) {
221
- const state = this.replayedChildStates.get(child);
222
- if (state)
223
- void this.send(state);
224
- }
225
- return result;
223
+ this.session(params.sessionId, "prompt");
224
+ this.auth.promptStarted(params.sessionId);
225
+ const restart = this.restarts.beforePrompt(params.sessionId);
226
+ return restart ? restart.then(prompt) : prompt();
226
227
  }
227
- finally {
228
- this.replays.delete(sessionId);
229
- for (const child of children()) {
230
- this.replays.delete(child);
231
- this.replayRoots.delete(child);
232
- this.replayedChildStates.delete(child);
233
- }
228
+ catch (error) {
229
+ return Promise.reject(error);
234
230
  }
235
231
  }
232
+ async newSession(params) {
233
+ const sessionId = randomUUID();
234
+ const session = await this.startSession(sessionId, params, undefined);
235
+ const response = { sessionId, ...(await this.setupFields(session)) };
236
+ this.afterSetup(session, params);
237
+ return response;
238
+ }
236
239
  /**
237
- * Sends a v2 session update, and logs rather than rejects when that fails.
238
- * It and {@link sessionUpdate} hand updates to the connection synchronously,
239
- * so they go out in the order of the calls. The agent's consumer awaits each
240
- * of its updates before it reports the next turn event, so a turn's state
241
- * follows the output that came before it. (An update the consumer is still
242
- * routing can be overtaken by an event from elsewhere, such as a permission
243
- * request opening.)
240
+ * Copies the session's transcript into a new session (`forkSession`), and
241
+ * starts it from the copy, so the client can prompt it at once.
244
242
  */
245
- send(notification) {
246
- return this.ctx
247
- .notify(v2.methods.client.session.update, this.background.stamp(notification))
248
- .catch((error) => {
249
- this.logger.error(`Failed to send a ${notification.update.sessionUpdate} update:`, error);
243
+ async forkSession(params) {
244
+ if (this.ownerOfChild(params.sessionId))
245
+ throw restrictedChild(params.sessionId, "fork");
246
+ // Rejects a bad `cwd` or MCP server before the transcript is copied.
247
+ await validatedSetup(params);
248
+ const { sessionId } = await forkSession(v1ForkSessionRequest(params), {
249
+ logger: this.logger,
250
+ messageIdForGrouping,
250
251
  });
252
+ const session = await this.startSession(sessionId, params, sessionId);
253
+ const response = { sessionId, ...(await this.setupFields(session)) };
254
+ this.afterSetup(session, params);
255
+ return response;
251
256
  }
252
- extNotification(method, params) {
253
- if (!isExtensionMethod(method)) {
254
- return Promise.reject(new Error(`${method} is not an ACP extension method`));
257
+ /**
258
+ * Resumes a stored session, or attaches to a live one. With `replayFrom:
259
+ * { type: "start" }` the stored history replays first. Either way, the
260
+ * state snapshot goes out after any replay and before the response.
261
+ */
262
+ resumeSession(params) {
263
+ const { sessionId } = params;
264
+ const run = this.resume(params);
265
+ let runs = this.resuming.get(sessionId);
266
+ if (!runs)
267
+ this.resuming.set(sessionId, (runs = new Set()));
268
+ runs.add(run);
269
+ const settled = () => {
270
+ runs.delete(run);
271
+ if (runs.size === 0 && this.resuming.get(sessionId) === runs)
272
+ this.resuming.delete(sessionId);
273
+ };
274
+ run.then(settled, settled);
275
+ return run;
276
+ }
277
+ /** The handler of {@link resumeSession}. */
278
+ async resume(params) {
279
+ const { sessionId, replayFrom } = params;
280
+ if (replayFrom != null && replayFrom.type !== "start") {
281
+ throw RequestError.invalidParams({ replayFrom }, `Replaying from a ${replayFrom.type} cursor is not supported`);
255
282
  }
256
- return this.ctx.notify(method, params);
257
- }
258
- async sessionUpdate({ update, ...notification }) {
259
- // A subagent that a replay announces replays too, so its messages are
260
- // cleared before their first replayed chunk, as the parent's are.
261
- if (update.sessionUpdate === "subagent_update" &&
262
- this.replays.has(notification.sessionId) &&
263
- !this.replays.has(update.sessionId)) {
264
- this.replays.set(update.sessionId, new Set());
265
- this.replayRoots.set(update.sessionId, this.replayRoots.get(notification.sessionId) ?? notification.sessionId);
283
+ if (this.ownerOfChild(sessionId))
284
+ throw restrictedChild(sessionId, "resume");
285
+ await this.restarts.settled(sessionId);
286
+ // A concurrent resume of this session started its query: this one then
287
+ // attaches to the session that it started.
288
+ await this.startSettled(sessionId);
289
+ let session = this.sessions.get(sessionId);
290
+ let history;
291
+ if (session) {
292
+ // Resuming the active session synchronizes it again. Its work goes on,
293
+ // and the request's MCP servers and additional directories replace the
294
+ // session's.
295
+ const request = await validatedSetup(params);
296
+ if (request.cwd !== session.cwd) {
297
+ throw RequestError.invalidParams({ cwd: request.cwd }, `Session ${sessionId} works in ${session.cwd}: resume it with that \`cwd\``);
298
+ }
299
+ await session.setMcpServers({
300
+ ...clientOptions(params._meta)?.mcpServers,
301
+ ...sdkMcpServers(request.mcpServers),
302
+ });
303
+ if (!sameDirectories(request.additionalDirectories ?? [], session.additionalDirectories)) {
304
+ // The SDK cannot change them on a running query: it restarts with
305
+ // them at its next turn boundary (see `restarts.ts`).
306
+ this.restarts.rootsChanged(sessionId, params);
307
+ }
308
+ else {
309
+ // A restart of its query starts with these servers.
310
+ this.restarts.track(sessionId, params);
311
+ }
312
+ }
313
+ else {
314
+ // One read of the transcript serves the replay and the resumed model.
315
+ history = replayFrom != null ? getSessionMessages(sessionId, { dir: params.cwd }) : undefined;
316
+ // A failed start leaves it unawaited.
317
+ history?.catch(() => { });
318
+ session = await this.startSession(sessionId, params, sessionId, history);
319
+ }
320
+ let subagents;
321
+ if (replayFrom != null) {
322
+ const messages = await (history ?? getSessionMessages(sessionId, { dir: session.cwd }));
323
+ subagents = await session.tasks.loadReplay(messages);
324
+ session.output.replay(messages, subagents?.hooks(session.output, messages), session.tasks.backgroundWork(sessionId), session.tasks.replayedBackground(sessionId));
325
+ subagents?.finish();
326
+ const end = replayEndUpdate(this.clientCapabilities);
327
+ if (end)
328
+ this.send({ sessionId, update: end });
329
+ }
330
+ // The current title, after the replay and before the state.
331
+ await session.reports.publishTitle();
332
+ for (const notification of session.resumeSnapshot())
333
+ this.send(notification);
334
+ const response = await this.setupFields(session);
335
+ this.afterSetup(session, params);
336
+ // The response ends the replay, and the replayed children's states before
337
+ // it are history: their current states follow it. Nothing enforces that
338
+ // the timer runs after the response goes out; it relies on the response
339
+ // being written when this handler returns, as the v1 core's
340
+ // `afterSetupResponse` does.
341
+ if (subagents)
342
+ setTimeout(() => subagents.afterResponse(), 0);
343
+ return response;
344
+ }
345
+ async listSessions(params) {
346
+ if (params.cwd != null && !path.isAbsolute(params.cwd)) {
347
+ throw RequestError.invalidParams({ cwd: params.cwd }, "`cwd` must be an absolute path");
266
348
  }
267
- const updates = this.v2Updates(notification.sessionId, update).flatMap((v2Update) => {
268
- const clear = this.replayClear(notification.sessionId, v2Update);
269
- return clear ? [clear, v2Update] : [v2Update];
349
+ const offset = listOffset(params.cursor);
350
+ // One more than a page tells whether a next page exists.
351
+ const stored = await listSessions({
352
+ dir: params.cwd ?? undefined,
353
+ includeWorktrees: false,
354
+ limit: SESSION_LIST_PAGE_SIZE + 1,
355
+ offset,
270
356
  });
271
- // A subagent's work state also goes to the child's own stream, after the
272
- // parent's copy. During a replay, only its last state goes, after the
273
- // replay (see `replayedChildStates`).
274
- let childState = v2ChildStateUpdate(update);
275
- if (childState && this.replays.has(notification.sessionId)) {
276
- this.replayedChildStates.set(childState.sessionId, childState);
277
- childState = undefined;
357
+ const sessions = stored.slice(0, SESSION_LIST_PAGE_SIZE).flatMap((session) => session.cwd
358
+ ? [
359
+ {
360
+ sessionId: session.sessionId,
361
+ cwd: session.cwd,
362
+ title: sanitizeTitle(session.summary),
363
+ updatedAt: new Date(session.lastModified).toISOString(),
364
+ },
365
+ ]
366
+ : []);
367
+ return stored.length > SESSION_LIST_PAGE_SIZE
368
+ ? { sessions, nextCursor: `offset:${offset + SESSION_LIST_PAGE_SIZE}` }
369
+ : { sessions };
370
+ }
371
+ /** Closing is idempotent: a session that is not active closes at once. */
372
+ async closeSession({ sessionId }) {
373
+ if (this.ownerOfChild(sessionId))
374
+ throw restrictedChild(sessionId, "close");
375
+ // A restart that runs ends first, so the close ends the session it started.
376
+ await this.restarts.closing(sessionId);
377
+ // A resume that runs answers first: the close ends what it started, and
378
+ // its updates go out before the close response.
379
+ await this.setupSettled(sessionId);
380
+ this.stopped.delete(sessionId);
381
+ const session = this.sessions.get(sessionId);
382
+ if (session) {
383
+ await session.close();
384
+ if (this.sessions.get(sessionId) === session)
385
+ this.sessions.delete(sessionId);
386
+ this.translator.forget(sessionId);
387
+ this.auth.sessionEnded(sessionId);
388
+ this.guard.sessionEnded(sessionId);
278
389
  }
279
- // Every update goes to the connection before any is awaited, so an update
280
- // that another call sends meanwhile cannot come between them. The parent's
281
- // copy is stamped first: a child's announcement starts its list.
282
- const stamped = [
283
- ...updates.map((v2Update) => this.background.stamp({ ...notification, update: v2Update })),
284
- ...(childState ? [this.background.stamp(childState)] : []),
285
- ];
286
- await Promise.all(stamped.map((v2Notification) => this.ctx.notify(v2.methods.client.session.update, v2Notification)));
390
+ this.restarts.closed(sessionId);
391
+ return {};
392
+ }
393
+ /** Deleting a session that does not exist succeeds, as v2 asks. */
394
+ async deleteSession({ sessionId }) {
395
+ if (this.ownerOfChild(sessionId))
396
+ throw restrictedChild(sessionId, "delete");
397
+ // A resume that runs, or its start, may make the session live.
398
+ await this.setupSettled(sessionId);
399
+ const live = this.sessions.get(sessionId);
400
+ if (live || this.stopped.has(sessionId))
401
+ await this.closeSession({ sessionId });
402
+ try {
403
+ await deleteSession(sessionId, live ? { dir: live.cwd } : undefined);
404
+ }
405
+ catch (error) {
406
+ // A session without a transcript, such as one never prompted, has nothing to delete.
407
+ if (error instanceof Error && /not found/i.test(error.message))
408
+ return {};
409
+ throw error;
410
+ }
411
+ return {};
412
+ }
413
+ async setConfigOption(params) {
414
+ // On the new query, when a restart runs.
415
+ await this.restarts.settled(params.sessionId);
416
+ const configOptions = await this.session(params.sessionId, "configure").setConfigOption(params);
417
+ return { configOptions };
287
418
  }
288
419
  /**
289
- * The v2 updates of a v1 update: for a tool call report, the updates of its
290
- * terminal first (see {@link V2Terminals}), then the report itself, with the
291
- * `_meta` keys that it changes (see {@link V2ToolCallMeta}), and during a
292
- * replay the `_meta` of a tool call that the report cleared.
420
+ * The active session `sessionId`, for a request that `method` names. A
421
+ * subagent's session takes no such request: the client can only watch it
422
+ * and cancel its run.
293
423
  */
294
- v2Updates(sessionId, update) {
295
- if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") {
296
- const v2Update = v2SessionUpdate(update);
297
- return v2Update ? [v2Update] : [];
424
+ session(sessionId, method) {
425
+ const session = this.sessions.get(sessionId);
426
+ if (session)
427
+ return session;
428
+ if (this.ownerOfChild(sessionId))
429
+ throw restrictedChild(sessionId, method);
430
+ throw this.inactive(sessionId);
431
+ }
432
+ /** The error of a request of `sessionId`, which is not running. */
433
+ inactive(sessionId) {
434
+ const stopped = this.stopped.get(sessionId);
435
+ return stopped !== undefined
436
+ ? RequestError.internalError({ sessionId }, stopped)
437
+ : RequestError.sessionNotFound(sessionId);
438
+ }
439
+ async cancel(sessionId) {
440
+ this.restarts.cancelled(sessionId);
441
+ const session = this.sessions.get(sessionId);
442
+ if (session)
443
+ return session.cancel();
444
+ await this.ownerOfChild(sessionId)?.tasks.cancelChild(sessionId);
445
+ }
446
+ /** `terminal/cancel` and `tool_call/cancel`: stops a listed item of a session or a child. */
447
+ async cancelItem(sessionId, target) {
448
+ const root = this.sessions.get(sessionId) ?? this.ownerOfChild(sessionId);
449
+ if (!root)
450
+ throw this.inactive(sessionId);
451
+ if (!(await root.tasks.cancelItem(sessionId, target))) {
452
+ throw "terminalId" in target
453
+ ? RequestError.invalidParams({ sessionId, terminalId: target.terminalId }, `Terminal ${target.terminalId} is not a command running in the background, so it cannot be cancelled.`)
454
+ : RequestError.invalidParams({ sessionId, toolCallId: target.toolCallId }, `Tool call ${target.toolCallId} is not running in the background, so it cannot be cancelled.`);
298
455
  }
299
- const { terminal, report } = this.terminals.split(sessionId, update);
300
- if (!report)
301
- return terminal;
302
- const starts = report.sessionUpdate === "tool_call";
303
- const replaying = this.replays.has(sessionId);
304
- // A v1 `tool_call` starts the tool call afresh, but v2 only has updates,
305
- // which keep each field they leave out. The client may already hold this
306
- // id: from an earlier report on this connection, or, during a replay, from
307
- // before it (a client that resumes a session it showed before).
308
- const restarts = starts && (replaying || this.toolCallMeta.reported(sessionId, report.toolCallId));
309
- const [reported, metaPatch] = this.toolCallMeta.apply(sessionId, report, starts, replaying);
310
- const reportUpdate = restarts ? v2RestartedToolCall(reported) : v2SessionUpdate(reported);
311
- const metaUpdate = metaPatch
312
- ? v2SessionUpdate({ sessionUpdate: "tool_call_update", ...metaPatch })
313
- : undefined;
314
- return [
315
- ...terminal,
316
- ...(reportUpdate ? [reportUpdate] : []),
317
- ...(metaUpdate ? [metaUpdate] : []),
318
- ];
456
+ return {};
457
+ }
458
+ /** The root session that `sessionId` is a subagent session of. */
459
+ ownerOfChild(sessionId) {
460
+ return [...this.sessions.values()].find((session) => session.tasks.hasChild(sessionId));
319
461
  }
462
+ async dispose() {
463
+ await this.restarts.dispose();
464
+ await Promise.all([...this.starting.keys()].map((sessionId) => this.startSettled(sessionId)));
465
+ const sessions = [...this.sessions.values()];
466
+ this.sessions.clear();
467
+ this.stopped.clear();
468
+ await Promise.all(sessions.map((session) => session.close()));
469
+ }
470
+ // --- Session setup -----------------------------------------------------------
320
471
  /**
321
- * The update that clears the message of a replayed chunk, when it is the
322
- * first replayed chunk of that message (see {@link replaying}).
472
+ * Starts the query of the live session `sessionId` again, resuming its
473
+ * conversation (see `restarts.ts`). Claude Code writes the conversation at
474
+ * the first prompt, so a session never prompted has none to resume: it
475
+ * starts afresh under the same id.
323
476
  */
324
- replayClear(sessionId, update) {
325
- const cleared = this.replays.get(sessionId);
326
- if (!cleared)
327
- return undefined;
328
- const kind = MESSAGE_OF_CHUNK.get(update.sessionUpdate);
329
- if (!kind)
330
- return undefined;
331
- const { messageId } = update;
332
- const key = `${kind} ${messageId}`;
333
- if (cleared.has(key))
334
- return undefined;
335
- cleared.add(key);
336
- return emptyMessage(kind, messageId);
337
- }
338
- async requestPermission(params, signal) {
339
- // The subject is an update of the tool call, with its stored `_meta`.
340
- const toolCall = this.toolCallMeta.subject(params.sessionId, params.toolCall);
341
- const response = await this.ctx.request(v2.methods.client.session.requestPermission, v2PermissionRequest({ ...params, toolCall }), { cancellationSignal: signal, stopWaitingOnCancel: true });
342
- return v1PermissionResponse(response);
343
- }
344
- // Elicitation is the same in v1 and v2.
345
- createElicitation(params, signal) {
346
- return this.ctx.request(v2.methods.client.elicitation.create,
347
- // The v1 types accept a property schema with any tag; the v2 types accept
348
- // one only in a received value. As on v1, an MCP server's schema is
349
- // relayed here unchanged, so this cast does not check it.
350
- params, { cancellationSignal: signal, stopWaitingOnCancel: true });
477
+ async restartSession(sessionId, params) {
478
+ try {
479
+ return await this.startSession(sessionId, params, sessionId);
480
+ }
481
+ catch (error) {
482
+ if (!(error instanceof RequestError && error.code === RequestError.sessionNotFound(sessionId).code)) {
483
+ throw error;
484
+ }
485
+ return this.startSession(sessionId, params, undefined);
486
+ }
351
487
  }
352
- completeElicitation(params) {
353
- return this.ctx.notify(v2.methods.client.elicitation.complete, params);
488
+ /**
489
+ * The config options and commands of a setup response. When reading the
490
+ * commands fails, the response goes without them, and an
491
+ * `available_commands_update` with the commands, read again, follows it.
492
+ */
493
+ async setupFields(session) {
494
+ const commands = await session.commands.list().catch((error) => {
495
+ this.logger.error(`Session ${session.sessionId}: failed to read its commands`, error);
496
+ // After the response, which the SDK sends once this handler returns.
497
+ setTimeout(() => {
498
+ session.sendCommands().catch((error) => {
499
+ this.logger.error(`Session ${session.sessionId}: failed to send its commands`, error);
500
+ });
501
+ }, 0);
502
+ return [];
503
+ });
504
+ return {
505
+ configOptions: session.config.options(),
506
+ // The draft leaves out an empty list.
507
+ ...(commands.length > 0 ? { availableCommands: commands } : {}),
508
+ };
509
+ }
510
+ /**
511
+ * Resolves once the resumes of `sessionId` that run now, and every start of
512
+ * it, settled, whether they succeeded or not. A resume that comes later is
513
+ * not waited for.
514
+ */
515
+ async setupSettled(sessionId) {
516
+ const resumes = [...(this.resuming.get(sessionId) ?? [])];
517
+ await Promise.all(resumes.map((resume) => resume.catch(() => { })));
518
+ await this.startSettled(sessionId);
354
519
  }
355
- // v2 has no client file system. The agent never calls these on v2, because
356
- // `v1InitializeRequest` reports no `fs` capability.
357
- readTextFile() {
358
- return Promise.reject(new Error("ACP v2 has no client file system"));
520
+ /**
521
+ * What follows a setup response: OAuth for its MCP servers, and a route
522
+ * restart that the session's start missed (`SessionRestarts.setupAnswered`).
523
+ * A restart that runs, such as for other additional directories, retires
524
+ * `session` and starts OAuth on the new query instead.
525
+ */
526
+ afterSetup(session, params) {
527
+ if (!this.restarts.restarting(session.sessionId))
528
+ afterSetupResponse(session, params);
529
+ this.restarts.setupAnswered(session.sessionId);
530
+ }
531
+ /** Resolves once no start of `sessionId` runs, whether the starts succeeded or not. */
532
+ async startSettled(sessionId) {
533
+ // Each wait can end with another start running, which began after it.
534
+ let start = this.starting.get(sessionId);
535
+ while (start) {
536
+ await start.catch(() => { });
537
+ start = this.starting.get(sessionId);
538
+ }
359
539
  }
360
- writeTextFile() {
361
- return Promise.reject(new Error("ACP v2 has no client file system"));
540
+ /**
541
+ * Starts the query of a session: a new one, or `resume` of a stored one
542
+ * (also a fork's copy), and tracks the start in {@link starting} until it
543
+ * settles. A resume checks that no start of `sessionId` runs right
544
+ * before, with no await in between. A restart's start is serialized by
545
+ * `restarts.ts`, which a resume and a close wait for first.
546
+ */
547
+ startSession(sessionId, params, resume, history) {
548
+ const start = this.launchSession(sessionId, params, resume, history);
549
+ this.starting.set(sessionId, start);
550
+ const settled = () => {
551
+ if (this.starting.get(sessionId) === start)
552
+ this.starting.delete(sessionId);
553
+ };
554
+ start.then(settled, settled);
555
+ return start;
556
+ }
557
+ /**
558
+ * The query start of {@link startSession}. Its options are the client's
559
+ * `_meta.claudeCode.options` under the ones this core controls.
560
+ */
561
+ async launchSession(sessionId, params, resume,
562
+ /** The resumed transcript, when the caller reads it anyway (a replay). */
563
+ history) {
564
+ const request = await validatedSetup(params);
565
+ const client = clientOptions(params._meta);
566
+ // After a provider change that is still listing its models.
567
+ await this.auth.routeSettled();
568
+ // The resumed transcript's last model and mode.
569
+ const resumed = resume === undefined
570
+ ? undefined
571
+ : history
572
+ ? {
573
+ ...(await readResumedTail(resume, this.logger, false)),
574
+ model: await history.then(resumedModelFromTranscript, () => undefined),
575
+ }
576
+ : await readResumedTail(resume, this.logger);
577
+ // Read before the settings watchers open: only a failed query start disposes them.
578
+ const configured = await configuredSettings(client?.settings, request.cwd);
579
+ const pathToClaudeCodeExecutable = await claudeCliPath();
580
+ const settings = new SettingsManager(request.cwd, { logger: this.logger });
581
+ await settings.initialize();
582
+ // A client can remove bypass from the session with `false`.
583
+ const allowBypass = ALLOW_BYPASS &&
584
+ settings.getSettings().permissions?.disableBypassPermissionsMode !== "disable" &&
585
+ client?.allowDangerouslySkipPermissions !== false;
586
+ const allowAuto = !autoModeDisabled(settings.getSettings());
587
+ const { mode, builtInDefault } = resolveInitialPermissionMode({
588
+ resumed: resumed?.permissionMode,
589
+ defaultMode: settings.getSettings().permissions?.defaultMode,
590
+ }, this.logger, { allowBypass, allowAuto });
591
+ // The settings stay live for the idle compaction (see `reports.ts`) until the session
592
+ // ends. They keep the values they read: their cwd and key helper.
593
+ const authStarted = this.auth.sessionStarting(settings);
594
+ const routeGeneration = this.auth.routeGeneration;
595
+ const routing = this.auth.routing();
596
+ const thinking = resolveThinkingConfig(process.env.MAX_THINKING_TOKENS, process.env.CLAUDE_CODE_THINKING_DISPLAY, this.logger);
597
+ const mcpServers = { ...client?.mcpServers, ...sdkMcpServers(request.mcpServers) };
598
+ const clientPrompt = clientSystemPrompt(request.systemPrompt);
599
+ const input = new Pushable();
600
+ // A client can turn the affordance off (`_meta.claudeCode.options`). Then
601
+ // Claude Code's interrupt stops background tasks, so `session/cancel`
602
+ // could not leave listed work running, and the session lists none.
603
+ const perTaskStopAffordance = client?.perTaskStopAffordance !== false;
604
+ const additionalDirectories = [
605
+ ...(client?.additionalDirectories ?? []),
606
+ ...(request.additionalDirectories ?? []),
607
+ ];
608
+ const session = new V2Session(sessionId, request.cwd, request.additionalDirectories ?? [], this, input, perTaskStopAffordance, additionalDirectories);
609
+ const elicitationOptions = session.elicitations.queryOptions();
610
+ const subagent = subagentHooks((input) => session.tasks.subagentHook(input));
611
+ const options = {
612
+ systemPrompt: sessionSystemPrompt(clientPrompt, params._meta?.systemPrompt),
613
+ settingSources: ["user", "project", "local"],
614
+ ...(thinking !== undefined && { thinking }),
615
+ // Claude Code's interrupt then spares background tasks, which the
616
+ // client stops one at a time: `session/cancel` must leave listed work
617
+ // running. Before the client's options.
618
+ perTaskStopAffordance: true,
619
+ // AIR's predicted follow-up prompt (see `reports.ts`), as on v1. Only
620
+ // AIR gets it, so no other client's session spends a request on it.
621
+ // Before the client's options: `promptSuggestions: false` turns it off.
622
+ ...(this.air.client ? { promptSuggestions: true } : {}),
623
+ ...client,
624
+ // The checkpoints that AIR's file-change reports read (see
625
+ // `file-changes.ts`), only for a client that declared them, as on v1.
626
+ ...(this.air.fileChangeReport ? { enableFileCheckpointing: true } : {}),
627
+ // Claude Code applies the env of settings.json after the process env:
628
+ // the route goes into the programmatic settings too.
629
+ ...(routing.settings
630
+ ? {
631
+ settings: {
632
+ ...configured,
633
+ ...routing.settings,
634
+ env: { ...configured?.env, ...routing.settings.env },
635
+ },
636
+ }
637
+ : configured && { settings: configured }),
638
+ cwd: request.cwd,
639
+ additionalDirectories,
640
+ includePartialMessages: true,
641
+ // A subagent's text, for its own session's stream (see `tasks.ts`).
642
+ forwardSubagentText: true,
643
+ mcpServers,
644
+ permissionMode: mode,
645
+ allowDangerouslySkipPermissions: allowBypass,
646
+ canUseTool: denyingStoppedWork(session, session.elicitations.canUseTool(canUseTool(session))),
647
+ // MCP elicitations and the refusal fallback, for the modes the client
648
+ // renders. Without forms, AskUserQuestion is disallowed (below).
649
+ ...elicitationOptions,
650
+ pathToClaudeCodeExecutable,
651
+ // Echoes each prompt that Claude Code takes in (see `V2Session`).
652
+ extraArgs: { ...client?.extraArgs, "replay-user-messages": "" },
653
+ disallowedTools: [
654
+ ...(client?.disallowedTools ?? []),
655
+ ...(elicitationOptions.disallowedTools ?? []),
656
+ ],
657
+ tools: client?.tools ??
658
+ (params._meta?.disableBuiltInTools === true
659
+ ? []
660
+ : { type: "preset", preset: "claude_code" }),
661
+ hooks: withClientHooks(client?.hooks, {
662
+ // A subagent's `cwd` (such as its worktree) and configuration, from its hooks.
663
+ SubagentStart: [subagent.SubagentStart],
664
+ SubagentStop: [subagent.SubagentStop],
665
+ PostToolUseFailure: [subagent.PostToolUseFailure],
666
+ // An Edit or Write shows its exact patch before it runs.
667
+ PreToolUse: [subagent.PreToolUse, fileChangePreviewHook(session, this.logger)],
668
+ PostToolUse: [
669
+ subagent.PostToolUse,
670
+ {
671
+ hooks: [
672
+ createPostToolUseHook({ onEnterPlanMode: async () => session.modeChanged("plan") }),
673
+ ],
674
+ },
675
+ ],
676
+ PostModelSwitch: [
677
+ subagent.PostModelSwitch,
678
+ modelSwitchHook((model) => session.modelSwitched(model)),
679
+ ],
680
+ ...reportHooks(session),
681
+ }),
682
+ env: {
683
+ ...process.env,
684
+ ...client?.env,
685
+ // The gateway login or the provider (see `auth.ts`).
686
+ ...routing.env,
687
+ // `session_state_changed`, which is the session's state.
688
+ CLAUDE_CODE_EMIT_SESSION_STATE_EVENTS: "1",
689
+ ...STARTUP_FAILURE_RESULTS_ENV,
690
+ },
691
+ ...(resume !== undefined ? { resume } : { sessionId }),
692
+ };
693
+ const q = query({ prompt: input, options });
694
+ let initialization;
695
+ try {
696
+ initialization = await q.initializationResult();
697
+ }
698
+ catch (error) {
699
+ q.close();
700
+ settings.dispose();
701
+ if (resume !== undefined &&
702
+ error instanceof Error &&
703
+ error.message.includes("No conversation found with session ID")) {
704
+ throw RequestError.sessionNotFound(sessionId);
705
+ }
706
+ throw startupFailureError(error) ?? error;
707
+ }
708
+ authStarted(sessionId, initialization.account);
709
+ try {
710
+ this.guard.sessionStarted(sessionId, initialization.account, settings.getApiKeyHelper());
711
+ }
712
+ catch (error) {
713
+ q.close();
714
+ settings.dispose();
715
+ throw error;
716
+ }
717
+ // For the description of a child's agent type in its configuration.
718
+ session.tasks.configs.configureAgents(customAgents(initialization.agents ?? []));
719
+ let models;
720
+ try {
721
+ models = await sessionModels(q, initialization.models, settings, routing.models, routing.narrowsModels, resumed, sessionId, this.logger);
722
+ }
723
+ catch (error) {
724
+ // Claude Code refused a fresh session's model pin.
725
+ q.close();
726
+ settings.dispose();
727
+ throw error;
728
+ }
729
+ // A failed sync of the mode is logged (`SessionModeManager.initialize`),
730
+ // and a failed read of the agents or of ultracode leaves them out. Only
731
+ // the effort that `recommendedValue` sets can fail the start.
732
+ let config;
733
+ try {
734
+ config = await SessionConfig.start(sessionId, q, { mode, builtInDefault, allowBypass, allowAuto }, models.models, models.modelInfos, models.currentModelInfo, {
735
+ fastMode: {
736
+ state: initialization.fast_mode_state,
737
+ disabledReason: initialization.fast_mode_disabled_reason,
738
+ },
739
+ client,
740
+ effortSettings: () => mergeEffortSettings(settings.getSettings(), configured),
741
+ recommendedValue: this.air.recommendedValue,
742
+ }, (notification) => session.output.emitV1([notification]), this.logger);
743
+ }
744
+ catch (error) {
745
+ q.close();
746
+ settings.dispose();
747
+ throw error;
748
+ }
749
+ session.reports.configure({
750
+ settings,
751
+ env: options.env ?? {},
752
+ mcpServers: request.mcpServers.map((server) => server.name),
753
+ mcpOAuth: this.elicitation.url && supportsMcpOAuth(q),
754
+ query: q,
755
+ model: { id: models.models.currentModelId, info: models.allowlistedModelInfo },
756
+ });
757
+ session.start(q, config, mcpServers, resume !== undefined);
758
+ this.sessions.set(sessionId, session);
759
+ this.stopped.delete(sessionId);
760
+ // A route change during the start did not find this session live.
761
+ this.restarts.track(sessionId, params, {
762
+ staleRoute: this.auth.routeGeneration !== routeGeneration,
763
+ });
764
+ return session;
362
765
  }
363
766
  }
364
- /** The message update of each message chunk. */
365
- const MESSAGE_OF_CHUNK = new Map([
366
- ["user_message_chunk", "user_message"],
367
- ["agent_message_chunk", "agent_message"],
368
- ["agent_thought_chunk", "agent_thought"],
369
- ]);
370
- function emptyMessage(kind, messageId) {
371
- const message = { messageId, content: [] };
372
- switch (kind) {
373
- case "user_message":
374
- return { ...message, sessionUpdate: kind };
375
- case "agent_message":
376
- return { ...message, sessionUpdate: kind };
377
- default:
378
- return { ...message, sessionUpdate: kind };
767
+ /**
768
+ * The setup request in v1 form, once it is valid: the MCP transports that
769
+ * `V2_SESSION_CAPABILITIES` lists, a `systemPrompt` that the session can apply
770
+ * (`clientSystemPrompt`), an absolute `cwd` that is a directory, and
771
+ * absolute additional directories. Every setup path calls it before it acts,
772
+ * so an invalid request creates, resumes or forks nothing.
773
+ */
774
+ async function validatedSetup(params) {
775
+ const request = v1NewSessionRequest({ ...params, mcpServers: params.mcpServers ?? [] });
776
+ clientSystemPrompt(request.systemPrompt);
777
+ const { cwd } = request;
778
+ if (!path.isAbsolute(cwd)) {
779
+ throw RequestError.invalidParams({ cwd }, `\`cwd\` must be an absolute path, not ${cwd}`);
379
780
  }
781
+ const stat = await fs.stat(cwd).catch(() => undefined);
782
+ if (!stat?.isDirectory()) {
783
+ throw RequestError.invalidParams({ cwd }, `\`cwd\` is not a directory: ${cwd}`);
784
+ }
785
+ for (const directory of request.additionalDirectories ?? []) {
786
+ if (!path.isAbsolute(directory)) {
787
+ throw RequestError.invalidParams({ additionalDirectories: request.additionalDirectories }, `Additional directories must be absolute paths, not ${directory}`);
788
+ }
789
+ }
790
+ return request;
791
+ }
792
+ function sameDirectories(left, right) {
793
+ const normalize = (directories) => [...new Set(directories.map((directory) => path.resolve(directory)))].sort().join("\n");
794
+ return normalize(left) === normalize(right);
380
795
  }
381
- function isExtensionMethod(method) {
382
- return method.startsWith("_");
796
+ function listOffset(cursor) {
797
+ if (cursor == null)
798
+ return 0;
799
+ const match = /^offset:(\d+)$/.exec(cursor);
800
+ if (!match)
801
+ throw RequestError.invalidParams({ cursor }, `Unknown session/list cursor: ${cursor}`);
802
+ return Number(match[1]);
383
803
  }