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

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 (229) hide show
  1. package/README.md +5 -1
  2. package/dist/acp-agent.d.ts +93 -622
  3. package/dist/acp-agent.d.ts.map +1 -1
  4. package/dist/acp-agent.js +369 -3474
  5. package/dist/acp-client.d.ts +28 -0
  6. package/dist/acp-client.d.ts.map +1 -0
  7. package/dist/acp-client.js +1 -0
  8. package/dist/acp-subagents.d.ts +1 -2
  9. package/dist/acp-subagents.d.ts.map +1 -1
  10. package/dist/auth-methods.d.ts +21 -0
  11. package/dist/auth-methods.d.ts.map +1 -0
  12. package/dist/auth-methods.js +68 -0
  13. package/dist/auth-status-reporter.d.ts +112 -0
  14. package/dist/auth-status-reporter.d.ts.map +1 -0
  15. package/dist/auth-status-reporter.js +253 -0
  16. package/dist/background-work.d.ts +12 -265
  17. package/dist/background-work.d.ts.map +1 -1
  18. package/dist/background-work.js +8 -558
  19. package/dist/client-system-prompt.d.ts +7 -0
  20. package/dist/client-system-prompt.d.ts.map +1 -1
  21. package/dist/client-system-prompt.js +24 -0
  22. package/dist/context-compaction.d.ts +20 -0
  23. package/dist/context-compaction.d.ts.map +1 -1
  24. package/dist/context-compaction.js +26 -0
  25. package/dist/context-window.d.ts +70 -0
  26. package/dist/context-window.d.ts.map +1 -0
  27. package/dist/context-window.js +132 -0
  28. package/dist/diff.d.ts +1 -1
  29. package/dist/diff.js +1 -1
  30. package/dist/elicitation.d.ts +66 -1
  31. package/dist/elicitation.d.ts.map +1 -1
  32. package/dist/elicitation.js +109 -0
  33. package/dist/file-change-audit.d.ts +4 -3
  34. package/dist/file-change-audit.d.ts.map +1 -1
  35. package/dist/file-change-audit.js +3 -2
  36. package/dist/lib.d.ts +5 -1
  37. package/dist/lib.d.ts.map +1 -1
  38. package/dist/lib.js +3 -1
  39. package/dist/logger.d.ts +10 -0
  40. package/dist/logger.d.ts.map +1 -0
  41. package/dist/logger.js +1 -0
  42. package/dist/mcp-oauth.d.ts +44 -0
  43. package/dist/mcp-oauth.d.ts.map +1 -0
  44. package/dist/mcp-oauth.js +142 -0
  45. package/dist/mcp-servers.d.ts +10 -0
  46. package/dist/mcp-servers.d.ts.map +1 -0
  47. package/dist/mcp-servers.js +29 -0
  48. package/dist/message-filters.d.ts +43 -0
  49. package/dist/message-filters.d.ts.map +1 -0
  50. package/dist/message-filters.js +197 -0
  51. package/dist/native-subagents.d.ts +18 -8
  52. package/dist/native-subagents.d.ts.map +1 -1
  53. package/dist/native-subagents.js +7 -35
  54. package/dist/new-session-meta.d.ts +40 -0
  55. package/dist/new-session-meta.d.ts.map +1 -0
  56. package/dist/new-session-meta.js +1 -0
  57. package/dist/permissions/presentation.d.ts +29 -0
  58. package/dist/permissions/presentation.d.ts.map +1 -1
  59. package/dist/permissions/presentation.js +38 -11
  60. package/dist/prompt-suggestions.d.ts +29 -0
  61. package/dist/prompt-suggestions.d.ts.map +1 -1
  62. package/dist/prompt-suggestions.js +45 -0
  63. package/dist/prompt-to-claude.d.ts +10 -0
  64. package/dist/prompt-to-claude.d.ts.map +1 -0
  65. package/dist/prompt-to-claude.js +120 -0
  66. package/dist/providers.d.ts +139 -0
  67. package/dist/providers.d.ts.map +1 -0
  68. package/dist/providers.js +286 -0
  69. package/dist/remote-control.d.ts +62 -0
  70. package/dist/remote-control.d.ts.map +1 -0
  71. package/dist/remote-control.js +78 -0
  72. package/dist/result-end.d.ts +68 -0
  73. package/dist/result-end.d.ts.map +1 -0
  74. package/dist/result-end.js +84 -0
  75. package/dist/sdk-to-acp.d.ts +93 -0
  76. package/dist/sdk-to-acp.d.ts.map +1 -0
  77. package/dist/sdk-to-acp.js +635 -0
  78. package/dist/serve.d.ts +9 -3
  79. package/dist/serve.d.ts.map +1 -1
  80. package/dist/serve.js +10 -5
  81. package/dist/session-config-ids.d.ts +1 -0
  82. package/dist/session-config-ids.d.ts.map +1 -1
  83. package/dist/session-config-ids.js +1 -0
  84. package/dist/session-config-options.d.ts +64 -0
  85. package/dist/session-config-options.d.ts.map +1 -0
  86. package/dist/session-config-options.js +162 -0
  87. package/dist/session-effort.d.ts +67 -0
  88. package/dist/session-effort.d.ts.map +1 -1
  89. package/dist/session-effort.js +98 -0
  90. package/dist/session-env.d.ts +22 -0
  91. package/dist/session-env.d.ts.map +1 -0
  92. package/dist/session-env.js +66 -0
  93. package/dist/session-fast-mode.d.ts +83 -0
  94. package/dist/session-fast-mode.d.ts.map +1 -0
  95. package/dist/session-fast-mode.js +142 -0
  96. package/dist/session-index/connection.d.ts +5 -6
  97. package/dist/session-index/connection.d.ts.map +1 -1
  98. package/dist/session-index/connection.js +3 -5
  99. package/dist/session-mode.d.ts +1 -0
  100. package/dist/session-mode.d.ts.map +1 -1
  101. package/dist/session-mode.js +1 -1
  102. package/dist/session-model.d.ts +41 -0
  103. package/dist/session-model.d.ts.map +1 -1
  104. package/dist/session-model.js +110 -45
  105. package/dist/session-notices.d.ts +44 -0
  106. package/dist/session-notices.d.ts.map +1 -1
  107. package/dist/session-notices.js +68 -0
  108. package/dist/session-titles.d.ts +34 -12
  109. package/dist/session-titles.d.ts.map +1 -1
  110. package/dist/session-titles.js +7 -6
  111. package/dist/session-usage.d.ts +125 -0
  112. package/dist/session-usage.d.ts.map +1 -0
  113. package/dist/session-usage.js +196 -0
  114. package/dist/slash-commands.d.ts +10 -0
  115. package/dist/slash-commands.d.ts.map +1 -0
  116. package/dist/slash-commands.js +99 -0
  117. package/dist/streamed-text.d.ts +33 -0
  118. package/dist/streamed-text.d.ts.map +1 -0
  119. package/dist/streamed-text.js +71 -0
  120. package/dist/subagent-configuration.d.ts +32 -0
  121. package/dist/subagent-configuration.d.ts.map +1 -0
  122. package/dist/subagent-configuration.js +70 -0
  123. package/dist/subagent-replay.d.ts +18 -0
  124. package/dist/subagent-replay.d.ts.map +1 -1
  125. package/dist/subagent-replay.js +25 -15
  126. package/dist/tool-calls/client-capabilities.d.ts +8 -8
  127. package/dist/tool-calls/client-capabilities.js +4 -4
  128. package/dist/tool-calls/renderer.d.ts +4 -5
  129. package/dist/tool-calls/renderer.d.ts.map +1 -1
  130. package/dist/tool-calls/renderer.js +4 -5
  131. package/dist/turn-events.d.ts +6 -46
  132. package/dist/turn-events.d.ts.map +1 -1
  133. package/dist/utils.d.ts +1 -1
  134. package/dist/utils.d.ts.map +1 -1
  135. package/dist/v2/agent.d.ts +7 -11
  136. package/dist/v2/agent.d.ts.map +1 -1
  137. package/dist/v2/agent.js +751 -331
  138. package/dist/v2/air.d.ts +33 -0
  139. package/dist/v2/air.d.ts.map +1 -0
  140. package/dist/v2/air.js +29 -0
  141. package/dist/v2/auth.d.ts +97 -0
  142. package/dist/v2/auth.d.ts.map +1 -0
  143. package/dist/v2/auth.js +216 -0
  144. package/dist/v2/background.d.ts +27 -16
  145. package/dist/v2/background.d.ts.map +1 -1
  146. package/dist/v2/background.js +4 -32
  147. package/dist/v2/child-config.d.ts +55 -0
  148. package/dist/v2/child-config.d.ts.map +1 -0
  149. package/dist/v2/child-config.js +92 -0
  150. package/dist/v2/clear-context.d.ts +94 -0
  151. package/dist/v2/clear-context.d.ts.map +1 -0
  152. package/dist/v2/clear-context.js +176 -0
  153. package/dist/v2/commands.d.ts +46 -0
  154. package/dist/v2/commands.d.ts.map +1 -0
  155. package/dist/v2/commands.js +54 -0
  156. package/dist/v2/config.d.ts +187 -0
  157. package/dist/v2/config.d.ts.map +1 -0
  158. package/dist/v2/config.js +494 -0
  159. package/dist/v2/elicitation.d.ts +93 -0
  160. package/dist/v2/elicitation.d.ts.map +1 -0
  161. package/dist/v2/elicitation.js +160 -0
  162. package/dist/v2/file-changes.d.ts +61 -0
  163. package/dist/v2/file-changes.d.ts.map +1 -0
  164. package/dist/v2/file-changes.js +108 -0
  165. package/dist/v2/file-preview.d.ts +18 -0
  166. package/dist/v2/file-preview.d.ts.map +1 -0
  167. package/dist/v2/file-preview.js +29 -0
  168. package/dist/v2/initialize.d.ts +10 -24
  169. package/dist/v2/initialize.d.ts.map +1 -1
  170. package/dist/v2/initialize.js +4 -111
  171. package/dist/v2/outcome.d.ts +81 -0
  172. package/dist/v2/outcome.d.ts.map +1 -0
  173. package/dist/v2/outcome.js +166 -0
  174. package/dist/v2/permissions.d.ts +92 -0
  175. package/dist/v2/permissions.d.ts.map +1 -0
  176. package/dist/v2/permissions.js +162 -0
  177. package/dist/v2/prompt.d.ts +2 -42
  178. package/dist/v2/prompt.d.ts.map +1 -1
  179. package/dist/v2/prompt.js +2 -119
  180. package/dist/v2/remote-control.d.ts +41 -0
  181. package/dist/v2/remote-control.d.ts.map +1 -0
  182. package/dist/v2/remote-control.js +63 -0
  183. package/dist/v2/reports.d.ts +198 -0
  184. package/dist/v2/reports.d.ts.map +1 -0
  185. package/dist/v2/reports.js +487 -0
  186. package/dist/v2/restarts.d.ts +128 -0
  187. package/dist/v2/restarts.d.ts.map +1 -0
  188. package/dist/v2/restarts.js +348 -0
  189. package/dist/v2/session-requests.d.ts +20 -0
  190. package/dist/v2/session-requests.d.ts.map +1 -0
  191. package/dist/v2/session-requests.js +108 -0
  192. package/dist/v2/session-update.d.ts +2 -13
  193. package/dist/v2/session-update.d.ts.map +1 -1
  194. package/dist/v2/session-update.js +2 -22
  195. package/dist/v2/session.d.ts +340 -41
  196. package/dist/v2/session.d.ts.map +1 -1
  197. package/dist/v2/session.js +1224 -141
  198. package/dist/v2/setup.d.ts +49 -0
  199. package/dist/v2/setup.d.ts.map +1 -0
  200. package/dist/v2/setup.js +62 -0
  201. package/dist/v2/stopped-work.d.ts +123 -0
  202. package/dist/v2/stopped-work.d.ts.map +1 -0
  203. package/dist/v2/stopped-work.js +210 -0
  204. package/dist/v2/stream.d.ts +229 -0
  205. package/dist/v2/stream.d.ts.map +1 -0
  206. package/dist/v2/stream.js +507 -0
  207. package/dist/v2/subagent-replay.d.ts +115 -0
  208. package/dist/v2/subagent-replay.d.ts.map +1 -0
  209. package/dist/v2/subagent-replay.js +479 -0
  210. package/dist/v2/subscription-guard.d.ts +60 -0
  211. package/dist/v2/subscription-guard.d.ts.map +1 -0
  212. package/dist/v2/subscription-guard.js +84 -0
  213. package/dist/v2/tasks.d.ts +492 -0
  214. package/dist/v2/tasks.d.ts.map +1 -0
  215. package/dist/v2/tasks.js +1728 -0
  216. package/dist/v2/terminal.d.ts.map +1 -1
  217. package/dist/v2/terminal.js +6 -1
  218. package/dist/v2/tool-call.d.ts +3 -2
  219. package/dist/v2/tool-call.d.ts.map +1 -1
  220. package/dist/v2/update-translator.d.ts +36 -0
  221. package/dist/v2/update-translator.d.ts.map +1 -0
  222. package/dist/v2/update-translator.js +80 -0
  223. package/dist/workflow-progress.d.ts +23 -0
  224. package/dist/workflow-progress.d.ts.map +1 -1
  225. package/dist/workflow-progress.js +31 -8
  226. package/package.json +1 -1
  227. package/dist/v2/permission.d.ts +0 -28
  228. package/dist/v2/permission.d.ts.map +0 -1
  229. package/dist/v2/permission.js +0 -41
@@ -1,152 +1,1235 @@
1
1
  /**
2
- * The ACP v2 session lifecycle, expressed through the v1 session methods of
3
- * `ClaudeAcpAgent`: v2 requests become the v1 requests that the agent serves,
4
- * and its v1 responses become v2 responses.
5
- */
6
- import { RequestError, } from "@agentclientprotocol/sdk/unstable";
7
- import * as v2 from "@agentclientprotocol/sdk/experimental/v2/unstable";
8
- import { V2_SESSION_CAPABILITIES } from "./initialize.js";
9
- import { v1ContentBlock } from "./prompt.js";
10
- export function v1NewSessionRequest(params) {
11
- const { mcpServers, systemPrompt, ...request } = params;
12
- // v1 requires the list; v2 treats an omitted list as an empty one.
13
- return {
14
- ...request,
15
- mcpServers: v1McpServers(mcpServers) ?? [],
16
- ...v1SystemPromptField(systemPrompt),
17
- };
18
- }
19
- /**
20
- * The v1 request that a v2 `session/resume` means.
2
+ * One ACP v2 session, served straight from its Claude Code query.
21
3
  *
22
- * v2 restores a session with `session/resume` and replays its history only
23
- * when `replayFrom` asks for it. v1 has two methods: `session/resume`, which
24
- * never replays, and `session/load`, which replays the whole history before it
25
- * responds. `replayFrom: { type: "start" }` is the second; a cursor that
26
- * starts elsewhere is rejected.
4
+ * ACP v2 and Claude Code describe a session the same way: prompts go into a
5
+ * queue, Claude Code works through them, and the session reports whether it
6
+ * is working. So this session keeps little of its own:
7
+ *
8
+ * - A prompt is pushed to Claude Code at once, with a uuid. Its response is
9
+ * the prompt's insertion: the `command_lifecycle` frame `started` for that
10
+ * uuid, or the prompt's echo, whichever comes first. `cancelled`,
11
+ * `discarded` or `refused` fails the prompt.
12
+ * - The foreground work is Claude Code's turn: it starts with a prompt's
13
+ * `started` frame or echo, or with the main conversation's output (a
14
+ * cycle that Claude Code starts on its own, such as after a background
15
+ * task ends), and ends with the turn's `result`, whose stop reason, usage
16
+ * and quota the idle carries (see `outcome.ts`). Claude Code's own
17
+ * `session_state_changed` stays `running` while background subagents work,
18
+ * which v2 lists as background work instead (`background`), so its `idle`
19
+ * only ends a turn that ended without a result.
20
+ * - `requires_action` is this session's own: a turn is open, and a
21
+ * permission request or elicitation of this session is open, or, while
22
+ * the turn waits on subagents, each of them waits on one.
23
+ * - Subagents are child sessions, and background work is listed on every
24
+ * state (see {@link SessionTasks}).
25
+ * - `session/cancel` answers the prompts that are not inserted yet with
26
+ * -32800, and sends Claude Code's interrupt with `cancelQueued`, which ends
27
+ * them in Claude Code too. A run of one that Claude Code had taken in
28
+ * already is dropped (see {@link StoppedWork}). With
29
+ * `perTaskStopAffordance`, the interrupt spares background tasks.
30
+ *
31
+ * Output goes out as it comes, whatever prompt it belongs to (see
32
+ * {@link SessionOutput}).
27
33
  */
28
- export function v1RestoreSessionRequest(params) {
29
- const { replayFrom, mcpServers, systemPrompt, ...rest } = params;
30
- const request = { ...rest, ...v1SystemPromptField(systemPrompt) };
31
- if (replayFrom == null) {
32
- return {
33
- method: "resume",
34
- request: { ...request, ...(mcpServers ? { mcpServers: v1McpServers(mcpServers) } : {}) },
34
+ import { randomUUID } from "node:crypto";
35
+ import { RequestError, } from "@agentclientprotocol/sdk/unstable";
36
+ import { AUTONOMOUS_RESULT_ORIGINS } from "../result-end.js";
37
+ import { promptToClaude } from "../prompt-to-claude.js";
38
+ import { v1PromptRequest } from "./prompt.js";
39
+ import { V2Background, stateUpdate as currentStateUpdate } from "./background.js";
40
+ import { MODEL_CONFIG_ID } from "../session-model.js";
41
+ import { modelRefusalFallback, noticeUpdate } from "../session-notices.js";
42
+ import { planModeUpdate } from "../exit-plan.js";
43
+ import { resetPlanUpdates } from "../plans.js";
44
+ import { agentFileChangeReportMeta } from "../file-change-audit.js";
45
+ import { ClearContext } from "./clear-context.js";
46
+ import { TurnFileChanges } from "./file-changes.js";
47
+ import { SessionCommands } from "./commands.js";
48
+ import { idleOutcome, isPlaceholderResult, ResultUsage, TurnReport, } from "./outcome.js";
49
+ import { StoppedWork } from "./stopped-work.js";
50
+ import { SessionReports } from "./reports.js";
51
+ import { SessionElicitations } from "./elicitation.js";
52
+ import { SessionOutput } from "./stream.js";
53
+ import { SessionRemoteControl } from "./remote-control.js";
54
+ import { SessionTasks } from "./tasks.js";
55
+ export class V2Session {
56
+ sessionId;
57
+ cwd;
58
+ additionalDirectories;
59
+ connection;
60
+ input;
61
+ /** The prompts not inserted yet, by uuid. */
62
+ pending = new Map();
63
+ /** Whether a turn of Claude Code is open: the session's foreground work. */
64
+ foreground = false;
65
+ /** The prompt whose `started` frame came last in the open turn. */
66
+ turnCommand;
67
+ /** The state the client was told last. */
68
+ reportedState = "idle";
69
+ /** The open permission requests and elicitations of the session. */
70
+ requests = new Set();
71
+ /** Whether `session/cancel` stops the open turn: its idle reports `cancelled`. */
72
+ cancelledWork = false;
73
+ /** What a cancel stopped before the client saw it, and the reach of its interrupt. */
74
+ stopped = new StoppedWork();
75
+ /** The interrupt of the last `session/cancel`, while it runs. */
76
+ interrupting;
77
+ /** Pushes prompts in the order they came (see {@link prompt}). */
78
+ pushes = Promise.resolve();
79
+ /** Pushes the adapter's own prompts of the open turn in order (see {@link pushOwnPrompt}). */
80
+ ownPushes = Promise.resolve();
81
+ /** The result that ended the open turn, with what the turn spent. */
82
+ lastEnd;
83
+ usage = new ResultUsage(false);
84
+ /**
85
+ * Whether Claude Code's `idle` for the last result is still to come. It can
86
+ * come after the next cycle's first output, and does not end that cycle.
87
+ */
88
+ idleOwed = false;
89
+ /** Whether Claude Code sends `command_lifecycle` frames (`msg_lifecycle_v1`). */
90
+ lifecycleFrames = false;
91
+ /** What the open turn's assistant messages reported about its end (see {@link TurnReport}). */
92
+ turnReport = new TurnReport();
93
+ /** Set by `session/close`, or when the query ends: nothing more goes out. */
94
+ closed = false;
95
+ closing;
96
+ /** Set by {@link start}. */
97
+ query;
98
+ output;
99
+ /** Usage, quota, notices, compactions and the title (see {@link SessionReports}). */
100
+ reports;
101
+ /** Resolves the adapter's own `/compact` once a turn ends (see {@link compact}). */
102
+ ownCommandDone;
103
+ /** The `background` lists of the session and its children, stamped on each state. */
104
+ background;
105
+ tasks;
106
+ elicitations;
107
+ /** AIR's file-change reports, when the client declared them (see `file-changes.ts`). */
108
+ fileChanges;
109
+ config;
110
+ commands;
111
+ /** ExitPlanMode's "clear context" option (see {@link ClearContext}). */
112
+ clearContext;
113
+ /** The `/mcp` prompts not inserted yet, by uuid, and the open turn's (see `SessionCommands`). */
114
+ localCommands = new Map();
115
+ turnLocalCommand;
116
+ /** The JSON of the query's MCP servers. */
117
+ mcpServers = "";
118
+ /** The adapter's `/remote-control`, and messages typed in other clients. */
119
+ remoteControl;
120
+ /** Who waits for {@link turnBoundary}, with whether it waits for a restart. */
121
+ boundaryWaiters = [];
122
+ constructor(sessionId, cwd,
123
+ /** The session's additional directories, as its query got them. */
124
+ additionalDirectories, connection, input,
125
+ /** Whether Claude Code's interrupt spares background tasks (see {@link SessionTasks}). */
126
+ reportsBackground = true,
127
+ /**
128
+ * The query's additional directories: the request's and those of the
129
+ * client's `_meta.claudeCode.options`. A file-change report lists paths
130
+ * in them and in `cwd`.
131
+ */
132
+ workspaceDirectories = additionalDirectories) {
133
+ this.sessionId = sessionId;
134
+ this.cwd = cwd;
135
+ this.additionalDirectories = additionalDirectories;
136
+ this.connection = connection;
137
+ this.input = input;
138
+ this.output = new SessionOutput(sessionId, cwd, connection.translator, (update) => this.send(update), connection.logger);
139
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
140
+ const session = this;
141
+ const titled = {
142
+ get query() {
143
+ return session.query;
144
+ },
145
+ get queryClosed() {
146
+ return session.closed;
147
+ },
148
+ get cancelled() {
149
+ return session.cancelledWork;
150
+ },
151
+ cwd,
35
152
  };
153
+ this.reports = new SessionReports({
154
+ sessionId,
155
+ logger: connection.logger,
156
+ airClient: connection.air.client,
157
+ emit: (notifications) => this.output.emitV1(notifications),
158
+ isBusy: () => this.foreground || this.pending.size > 0 || this.requests.size > 0,
159
+ compact: () => this.compact(),
160
+ titledSession: () => (this.query && !this.closed ? titled : undefined),
161
+ });
162
+ this.output.onAgentText = (content) => this.reports.agentText(content);
163
+ this.fileChanges = TurnFileChanges.create(connection.air.fileChangeReport, {
164
+ cwd,
165
+ additionalDirectories: [...workspaceDirectories],
166
+ publish: async (report) => this.send({
167
+ sessionUpdate: "session_info_update",
168
+ _meta: agentFileChangeReportMeta(report),
169
+ }),
170
+ logError: (message) => connection.logger.error(`Session ${sessionId}: ${message}`),
171
+ });
172
+ this.clearContext = new ClearContext({
173
+ push: (text, uuid) => this.pushOwnPrompt(text, uuid),
174
+ enterMode: (mode) => this.config.enterMode(mode),
175
+ publish: (plan) => {
176
+ this.send({
177
+ sessionUpdate: "config_option_update",
178
+ configOptions: this.config.options(),
179
+ });
180
+ // Otherwise the client shows the old context's usage until the fresh one reports its own.
181
+ this.reports.emptyContext();
182
+ // The approved plan becomes the session's plan. Its ExitPlanMode
183
+ // ended as a rejection, so the stream did not show it.
184
+ this.output.emitV1([{ sessionId, update: planModeUpdate(plan) }]);
185
+ },
186
+ logError: (message, error) => connection.logger.error(`Session ${sessionId}: ${message}`, error),
187
+ }, () => this.output.toolUses(), randomUUID);
188
+ this.background = new V2Background(connection.translator.terminals);
189
+ this.tasks = new SessionTasks({
190
+ sessionId,
191
+ cwd,
192
+ logger: connection.logger,
193
+ translator: connection.translator,
194
+ background: this.background,
195
+ reportsBackground,
196
+ send: (notification) => this.sendNotification(notification),
197
+ rootState: () => this.foregroundState(),
198
+ // A cancel withdraws the requests of the subagents that the work waits on.
199
+ foregroundRequestsChanged: () => this.reportState(this.cancelledWork),
200
+ models: () => this.config.subagentModels(),
201
+ modes: () => this.config.availableModes(),
202
+ stopTask: async (taskId) => {
203
+ await this.query?.stopTask(taskId);
204
+ },
205
+ }, this.output);
206
+ this.tasks.hostRequest = (request, signal) => unlessWithdrawn(signal, () => connection.requestPermission(request, signal));
207
+ this.elicitations = new SessionElicitations({
208
+ sessionId,
209
+ logger: connection.logger,
210
+ support: connection.elicitation,
211
+ airClient: connection.air.client,
212
+ createElicitation: (request, signal) => unlessWithdrawn(signal, () => connection.createElicitation(request, signal)),
213
+ completeElicitation: (params) => connection.completeElicitation(params),
214
+ target: (agentId) => this.target(agentId),
215
+ query: () => this.query,
216
+ });
217
+ this.remoteControl = new SessionRemoteControl({
218
+ logger: connection.logger,
219
+ query: () => this.query,
220
+ terminalCommands: () => this.commands.terminal(),
221
+ idle: () => this.turnBoundary(false),
222
+ begin: (uuid) => {
223
+ this.inserted(uuid);
224
+ this.openTurn(undefined);
225
+ },
226
+ end: (text, messageId) => {
227
+ this.output.agentMessage(text, messageId);
228
+ this.closeTurn();
229
+ },
230
+ });
36
231
  }
37
- const servers = v1McpServers(mcpServers);
38
- if (replayFrom.type !== "start") {
39
- throw RequestError.invalidParams({ replayFrom }, `Replaying from a ${replayFrom.type} cursor is not supported`);
232
+ /**
233
+ * Starts reading the query. Called once, after its initialization.
234
+ * `mcpServers` are the servers the query started with.
235
+ */
236
+ start(query, config, mcpServers, resumed = false) {
237
+ this.query = query;
238
+ this.config = config;
239
+ this.usage = new ResultUsage(resumed);
240
+ this.mcpServers = JSON.stringify(mcpServers);
241
+ this.commands = new SessionCommands(query);
242
+ void this.consume(query);
40
243
  }
41
- return {
42
- method: "load",
43
- request: { ...request, mcpServers: servers ?? [] },
44
- };
45
- }
46
- /**
47
- * The v1 request of a v2 `session/fork`. In both versions the agent's fork
48
- * returns a session that the client can prompt, with its config options.
49
- */
50
- export function v1ForkSessionRequest(params) {
51
- const { mcpServers, systemPrompt, ...request } = params;
52
- return {
53
- ...request,
54
- ...(mcpServers ? { mcpServers: v1McpServers(mcpServers) } : {}),
55
- ...v1SystemPromptField(systemPrompt),
56
- };
57
- }
58
- /**
59
- * The v1 `systemPrompt`. Its content converts like prompt content: a v2
60
- * annotation audience can be any string, and v1 takes only `user` or `assistant`.
61
- */
62
- function v1SystemPromptField(systemPrompt) {
63
- if (systemPrompt == null)
64
- return {};
65
- return { systemPrompt: { ...systemPrompt, content: systemPrompt.content.map(v1ContentBlock) } };
66
- }
67
- /** v2 drops `modes`: the session mode is the `mode` config option, which the agent always lists. */
68
- export function v2NewSessionResponse(response) {
69
- return { sessionId: response.sessionId, ...v2ResumeSessionResponse(response) };
70
- }
71
- export function v2ResumeSessionResponse(response) {
72
- return {
73
- ...v2ConfigOptionsField(response.configOptions),
74
- ...(response._meta != null ? { _meta: response._meta } : {}),
75
- };
76
- }
77
- /** v2 tags a select value with `type: "id"`; v1 leaves it untagged. */
78
- export function v1SetSessionConfigOptionRequest(params) {
79
- const request = {
80
- sessionId: params.sessionId,
81
- configId: params.configId,
82
- ...(params._meta != null ? { _meta: params._meta } : {}),
83
- };
84
- if (v2.SetSessionConfigOptionRequest.isId(params)) {
85
- return { ...request, value: params.value };
86
- }
87
- if (v2.SetSessionConfigOptionRequest.isBoolean(params)) {
88
- return { ...request, type: "boolean", value: params.value };
89
- }
90
- throw RequestError.invalidParams({ type: params.type }, `Config option values of type ${params.type} are not supported`);
91
- }
92
- /** v2 names the id of an option `configId` and the id of a select group `groupId`. */
93
- export function v2ConfigOptions(options) {
94
- return options.map((option) => {
95
- const { id, ...rest } = option;
96
- if (rest.type === "select") {
97
- return { ...rest, configId: id, options: v2SelectOptions(rest.options) };
98
- }
99
- return { ...rest, configId: id };
100
- });
101
- }
102
- function v2SelectOptions(options) {
103
- if (!isGrouped(options))
244
+ /** Sends the session's commands in an update, read again from Claude Code. */
245
+ async sendCommands() {
246
+ const availableCommands = await this.commands.list();
247
+ this.send({ sessionUpdate: "available_commands_update", availableCommands });
248
+ }
249
+ /**
250
+ * What `session/resume` sends before its response: the listed children
251
+ * with their current states, the current update of each listed item, then
252
+ * the session's state, with its list. A snapshot is no new completion, so
253
+ * its idle has no stop reason.
254
+ */
255
+ resumeSnapshot() {
256
+ return [
257
+ ...this.tasks.currentState(),
258
+ this.background.stamp({
259
+ sessionId: this.sessionId,
260
+ update: currentStateUpdate(this.foregroundState()),
261
+ }),
262
+ ];
263
+ }
264
+ /**
265
+ * Replaces the session's MCP servers, as a resume of the active session
266
+ * asks. The same servers stay as they are, connected.
267
+ */
268
+ async setMcpServers(servers) {
269
+ const key = JSON.stringify(servers);
270
+ if (key === this.mcpServers)
271
+ return;
272
+ await this.query?.setMcpServers(servers);
273
+ this.reports.mcpServersChanged(Object.keys(servers));
274
+ this.mcpServers = key;
275
+ }
276
+ // --- Requests ---------------------------------------------------------
277
+ /**
278
+ * Pushes the prompt to Claude Code. Answers once Claude Code inserted it
279
+ * (see the module doc), right after the prompt's `user_message`.
280
+ *
281
+ * A prompt waits for the interrupt of an earlier `session/cancel` before it
282
+ * goes to Claude Code: the interrupt's `cancelQueued` must not end a prompt
283
+ * that came after the cancel.
284
+ *
285
+ * `guard`, the subscription guard's check (see `subscription-guard.ts`),
286
+ * runs in the prompt's turn among the session's prompts, so they keep their
287
+ * order, and a cancel or close answers a prompt that waits for it with
288
+ * -32800 as any prompt not inserted yet. Its refusal answers the prompt.
289
+ * The adapter's `/remote-control` is not guarded.
290
+ */
291
+ prompt(params, guard) {
292
+ if (this.closed) {
293
+ return Promise.reject(RequestError.sessionNotFound(this.sessionId));
294
+ }
295
+ // Throws invalid params for content that Claude cannot take.
296
+ const request = v1PromptRequest(params);
297
+ const remoteControl = this.remoteControl.mayRun(request.prompt);
298
+ const guarded = guard && !remoteControl ? guard : undefined;
299
+ // A prompt that the guard refuses titles nothing and sends no notice.
300
+ const sent = () => {
301
+ this.reports.promptSent(request.prompt);
302
+ // The notice of a mode fallback at the session's start, which sends it at once.
303
+ void this.config.promptSent();
304
+ };
305
+ if (!guarded)
306
+ sent();
307
+ const uuid = randomUUID();
308
+ const message = { ...promptToClaude(request), uuid };
309
+ // Only a prompt that goes to Claude Code gets a file-change report, as on
310
+ // v1: the adapter's `/remote-control` registers it once it passes the
311
+ // prompt on (below).
312
+ if (!remoteControl)
313
+ this.fileChanges?.requested(uuid, params._meta);
314
+ const localCommand = this.commands.localCommand(request.prompt);
315
+ if (localCommand)
316
+ this.localCommands.set(uuid, localCommand);
317
+ return new Promise((resolve, reject) => {
318
+ const pending = { prompt: params.prompt, pushed: false, resolve, reject };
319
+ this.pending.set(uuid, pending);
320
+ // A cancel or close answered it before it went out.
321
+ const answered = () => this.pending.get(uuid) !== pending || this.closed;
322
+ this.pushes = this.pushes
323
+ .then(() => this.interrupting)
324
+ .then(async () => {
325
+ if (answered())
326
+ return;
327
+ if (guarded) {
328
+ try {
329
+ // Set by `start`, which runs before the agent lists the session.
330
+ await guarded(this.query);
331
+ }
332
+ catch (error) {
333
+ this.failPrompt(uuid, error);
334
+ return;
335
+ }
336
+ if (answered())
337
+ return;
338
+ sent();
339
+ }
340
+ // The prompts after the adapter's `/remote-control` wait for it.
341
+ if (remoteControl) {
342
+ try {
343
+ if (await this.remoteControl.run(request.prompt, uuid, () => !answered()))
344
+ return;
345
+ }
346
+ catch (error) {
347
+ this.failPrompt(uuid, error);
348
+ return;
349
+ }
350
+ if (answered())
351
+ return;
352
+ this.fileChanges?.requested(uuid, params._meta);
353
+ }
354
+ pending.pushed = true;
355
+ this.remoteControl.pushed(uuid);
356
+ this.input.push(message);
357
+ this.reports.promptQueued(request.prompt);
358
+ });
359
+ });
360
+ }
361
+ /**
362
+ * Whether no turn is open and no prompt waits in Claude Code's queue. With
363
+ * `restart`, for a restart of the query (see `restarts.ts`), also no
364
+ * prompt of the session waits to go to Claude Code, which the restart would
365
+ * answer with -32800, and no subagent runs. Without it, for the adapter's
366
+ * `/remote-control`, whose own prompt waits for the boundary.
367
+ */
368
+ atTurnBoundary(restart) {
369
+ return (!this.closed &&
370
+ !this.foreground &&
371
+ ![...this.pending.values()].some((prompt) => restart || prompt.pushed) &&
372
+ !(restart && this.tasks.hasLiveSubagents()));
373
+ }
374
+ /**
375
+ * Resolves `true` at the next turn boundary (see {@link atTurnBoundary}),
376
+ * at once if the session is at one, and `false` once the session closed.
377
+ */
378
+ turnBoundary(restart) {
379
+ if (this.closed)
380
+ return Promise.resolve(false);
381
+ if (this.atTurnBoundary(restart))
382
+ return Promise.resolve(true);
383
+ return new Promise((resolve) => this.boundaryWaiters.push({ restart, resolve }));
384
+ }
385
+ checkBoundary() {
386
+ for (const waiter of [...this.boundaryWaiters]) {
387
+ if (!this.closed && !this.atTurnBoundary(waiter.restart))
388
+ continue;
389
+ this.boundaryWaiters.splice(this.boundaryWaiters.indexOf(waiter), 1);
390
+ waiter.resolve(!this.closed);
391
+ }
392
+ }
393
+ /**
394
+ * The adapter's idle compaction: `/compact`, as Claude Code's own turn. It
395
+ * is no prompt of the client's, so it gets no `user_message`, and the client
396
+ * sees its turn as `running`, then `idle`. Resolves when a turn ends after
397
+ * it: the idle compaction runs it only while the session is idle, so the
398
+ * next turn to end is its own.
399
+ */
400
+ compact() {
401
+ return new Promise((resolve) => {
402
+ this.ownCommandDone?.();
403
+ this.ownCommandDone = resolve;
404
+ const message = {
405
+ ...promptToClaude({
406
+ sessionId: this.sessionId,
407
+ prompt: [{ type: "text", text: "/compact" }],
408
+ }),
409
+ uuid: randomUUID(),
410
+ };
411
+ this.pushes = this.pushes
412
+ .then(() => this.interrupting)
413
+ .then(() => {
414
+ if (this.closed) {
415
+ resolve();
416
+ return;
417
+ }
418
+ this.remoteControl.pushed(message.uuid);
419
+ this.input.push(message);
420
+ });
421
+ });
422
+ }
423
+ /**
424
+ * Sends Claude Code the adapter's own prompt `text`, after the interrupt of
425
+ * an earlier `session/cancel`, as {@link prompt} does. It is no prompt of
426
+ * the client's: it gets no `user_message`, also when its echo carries the
427
+ * human `origin` that `promptToClaude` stamps.
428
+ *
429
+ * These prompts continue the open turn (`clear-context.ts`), so they do not
430
+ * wait on {@link pushes}: a `/remote-control` there waits for the turn to
431
+ * end, which needs them. The client's prompts keep their order among
432
+ * themselves on `pushes`.
433
+ */
434
+ pushOwnPrompt(text, uuid) {
435
+ const message = {
436
+ ...promptToClaude({ sessionId: this.sessionId, prompt: [{ type: "text", text }] }),
437
+ uuid,
438
+ };
439
+ this.ownPushes = this.ownPushes
440
+ .then(() => this.interrupting)
441
+ .then(() => {
442
+ if (this.closed)
443
+ return;
444
+ this.remoteControl.pushed(uuid);
445
+ this.input.push(message);
446
+ });
447
+ }
448
+ /**
449
+ * Stops the foreground work, and answers the prompts not inserted yet with
450
+ * -32800. The work's idle reports `cancelled`. Background work goes on.
451
+ *
452
+ * The interrupt goes out also while the session is idle:
453
+ * Claude Code may run a cycle that this session has not read yet.
454
+ */
455
+ async cancel() {
456
+ if (this.closed || !this.query)
457
+ return;
458
+ this.reports.disarmIdleCompaction("cancel");
459
+ this.stopForeground();
460
+ // `cancelQueued` is untyped in the SDK (`Query.interrupt` takes it since
461
+ // the CLI's `interrupt_cancel_queued_v1`): Claude Code then drops the
462
+ // queued prompts, which this session answered already.
463
+ const interrupt = this.query.interrupt;
464
+ const done = interrupt.call(this.query, { cancelQueued: true }).then(() => undefined, (error) => {
465
+ // `session/cancel` is a notification: no one can be answered. Nothing
466
+ // stopped, so the work's idle reports how it really ends.
467
+ this.connection.logger.error(`Session ${this.sessionId}: the interrupt failed`, error);
468
+ this.cancelledWork = false;
469
+ this.output.cancelled = false;
470
+ this.stopped.interruptFailed();
471
+ this.tasks.foregroundCancelFailed();
472
+ // The withdrawn requests reported no `running`: the work goes on.
473
+ this.reportState();
474
+ });
475
+ this.interrupting = done;
476
+ await done;
477
+ if (this.interrupting === done)
478
+ this.interrupting = undefined;
479
+ }
480
+ /**
481
+ * What a cancel or close stops at once: the prompts not inserted yet, the
482
+ * open turn, and the work of the subagents that it waits on. The open
483
+ * permission requests stay open: Claude Code's interrupt withdraws them,
484
+ * and the end of the stopped work withdraws what is left (see
485
+ * {@link closeTurn}).
486
+ */
487
+ stopForeground() {
488
+ const pushed = [];
489
+ for (const [uuid, prompt] of [...this.pending]) {
490
+ if (prompt.pushed)
491
+ pushed.push(uuid);
492
+ this.failPrompt(uuid, RequestError.requestCancelled());
493
+ }
494
+ // A turn that waits for its plan's prompt in a fresh context: the
495
+ // adapter's prompts are stopped work too, and no frame of the turn's own
496
+ // prompt is left to end it.
497
+ const heldTurn = this.clearContext.holdsTurn();
498
+ pushed.push(...this.clearContext.stop());
499
+ this.stopped.cancelled(pushed, this.foreground);
500
+ if (this.foreground) {
501
+ this.cancelledWork = true;
502
+ this.output.cancelled = true;
503
+ }
504
+ for (const request of this.requests)
505
+ request.coveredByCancel = true;
506
+ this.turnLocalCommand?.abort.abort();
507
+ // The subagents that the work waits on stop with it. Background ones go on.
508
+ this.tasks.cancelForeground();
509
+ if (heldTurn)
510
+ this.closeTurn();
511
+ }
512
+ async setConfigOption(params) {
513
+ await this.config.set(params);
514
+ if (params.configId === MODEL_CONFIG_ID)
515
+ this.modelChangedReports();
516
+ const options = this.config.options();
517
+ // v2 sends every config change as an update too, for the session's other clients.
518
+ this.send({ sessionUpdate: "config_option_update", configOptions: options });
104
519
  return options;
105
- return options.map(({ group, ...selectGroup }) => ({ ...selectGroup, groupId: group }));
106
- }
107
- function isGrouped(options) {
108
- return options.some((entry) => "group" in entry);
109
- }
110
- /**
111
- * v2 tags each command with `type: "command"` and its free-text input with
112
- * `type: "text"`. A receiver drops a command without the `type` tag.
113
- */
114
- export function v2AvailableCommands(commands) {
115
- return commands.map(({ input, ...command }) => ({
116
- type: "command",
117
- ...command,
118
- ...(input != null ? { input: { type: "text", ...input } } : {}),
119
- }));
120
- }
121
- /** v1 responses may send `null`; v2 omits the field instead. */
122
- function v2ConfigOptionsField(options) {
123
- return options != null ? { configOptions: v2ConfigOptions(options) } : {};
124
- }
125
- /**
126
- * The v1 list of the MCP servers of a v2 setup request, or undefined for no
127
- * list. A request with two servers of the same `name`, or with a transport
128
- * that the agent does not advertise in `session.mcp` (such as `acp` or a
129
- * custom `_` type), fails with invalid params (-32602): the v1 session setup
130
- * would otherwise drop the server without telling the client.
131
- */
132
- function v1McpServers(servers) {
133
- if (servers == null)
134
- return undefined;
135
- v2.assertSupportedMcpServers(servers, V2_SESSION_CAPABILITIES.mcp);
136
- return servers.map(v1McpServer);
520
+ }
521
+ /**
522
+ * Cancels as `session/cancel` does, ends the open turn with its cancelled
523
+ * idle, then ends the query, which stops the background work too. Nothing
524
+ * of the session goes out after it resolves. It does not wait for Claude
525
+ * Code to end the work: the query's end stops it, and the
526
+ * tool calls that the work leaves open end `cancelled` before its idle.
527
+ */
528
+ close() {
529
+ this.closing ??= (async () => {
530
+ if (!this.closed)
531
+ this.stopForeground();
532
+ // v2 asks to withdraw every request of the session before the close
533
+ // response, also its background subagents' and the MCP OAuth runs'.
534
+ this.tasks.withdrawAll();
535
+ this.elicitations.close();
536
+ for (const request of this.requests) {
537
+ request.coveredByCancel = true;
538
+ request.abort.abort();
539
+ }
540
+ this.closeTurn();
541
+ this.failPending(RequestError.requestCancelled());
542
+ this.closed = true;
543
+ this.checkBoundary();
544
+ this.endReports();
545
+ this.input.end();
546
+ this.query?.close();
547
+ })();
548
+ return this.closing;
549
+ }
550
+ /**
551
+ * Ends the session's query, which a new one replaced (see `restarts.ts`).
552
+ * The session is idle then. Its background work ends with the query: its
553
+ * terminals exit and its listed tool calls end before the list drops them,
554
+ * as when a query ends. Then it closes as {@link close} does.
555
+ */
556
+ retire() {
557
+ if (!this.closed && !this.closing) {
558
+ this.tasks.queryEnded({
559
+ code: RequestError.internalError().code,
560
+ message: "The session's query restarted",
561
+ });
562
+ }
563
+ return this.close();
564
+ }
565
+ // --- Permission requests -----------------------------------------------
566
+ get airClient() {
567
+ return this.connection.air.client;
568
+ }
569
+ availableModes() {
570
+ return this.config.availableModeIds();
571
+ }
572
+ cancelling() {
573
+ return this.cancelledWork;
574
+ }
575
+ dropsToolUse(toolUseId, agentId, signal) {
576
+ return this.stopped.dropsToolUse(toolUseId, agentId, signal);
577
+ }
578
+ /** The session of a permission request: this one, or a subagent's (see `canUseTool`). */
579
+ target(agentId) {
580
+ return this.tasks.target(agentId, this);
581
+ }
582
+ requestPermission(request, toolSignal) {
583
+ return this.openRequest(toolSignal, async (signal) => {
584
+ try {
585
+ // The subject is an upsert of the tool call: the client may see the
586
+ // request before the tool use streams.
587
+ return await unlessWithdrawn(signal, () => this.connection.requestPermission(request, signal));
588
+ }
589
+ catch (error) {
590
+ if (signal.aborted)
591
+ return { outcome: { outcome: "cancelled" } };
592
+ throw error;
593
+ }
594
+ });
595
+ }
596
+ /** Runs `send` as an open request of this session (see {@link RequestTarget.openRequest}). */
597
+ async openRequest(toolSignal, send) {
598
+ const open = { abort: new AbortController(), coveredByCancel: false };
599
+ // After `session/close` nothing of the session goes out: the request is
600
+ // withdrawn before it is sent.
601
+ if (this.closed)
602
+ open.abort.abort();
603
+ const signal = AbortSignal.any([toolSignal, open.abort.signal]);
604
+ this.requests.add(open);
605
+ this.reportState();
606
+ try {
607
+ return await send(signal);
608
+ }
609
+ finally {
610
+ this.requests.delete(open);
611
+ // A request withdrawn after a cancel (Claude Code's interrupt aborts
612
+ // `toolSignal`) ends work that is stopping: its idle follows, so no
613
+ // `running` comes first. One that the user answers, or that Claude Code
614
+ // withdraws without a cancel (a hook answered it), lets the work go on.
615
+ this.reportState(open.coveredByCancel && signal.aborted);
616
+ }
617
+ }
618
+ modeChanged(mode) {
619
+ if (this.config.modeChanged(mode)) {
620
+ this.send({ sessionUpdate: "config_option_update", configOptions: this.config.options() });
621
+ }
622
+ }
623
+ prePlanMode() {
624
+ return this.config.prePlanMode();
625
+ }
626
+ /** A fresh context continues the open turn: only the root's plan in a turn offers it. */
627
+ contextReset(agentId) {
628
+ return {
629
+ offered: agentId === undefined && this.foreground,
630
+ usedPercent: this.reports.contextUsedPercent(),
631
+ };
632
+ }
633
+ exitPlanInterrupting(toolUseId, reset) {
634
+ // The fresh context starts in the mode that the answer's mode runs as on
635
+ // the model, such as `acceptEdits` for `auto` on a model without Auto,
636
+ // with no fallback notice.
637
+ this.clearContext.interrupting(toolUseId, reset && { ...reset, mode: this.config.effectiveMode(reset.mode) });
638
+ }
639
+ permissionAllowed(result) {
640
+ return this.config.permissionAllowed(result);
641
+ }
642
+ requestShows(target, toolName, toolCallId) {
643
+ this.tasks.requestShows(target.output, toolName, toolCallId);
644
+ }
645
+ toolCallSubject(sessionId, toolCall) {
646
+ return this.connection.translator.toolCallMeta.subject(sessionId, toolCall);
647
+ }
648
+ /**
649
+ * Claude Code switched the model without the adapter: a typed `/model`
650
+ * (see `modelSwitchHook`), or a refusal fallback.
651
+ */
652
+ modelSwitched(model) {
653
+ this.config.modelSwitched(model).then((changed) => {
654
+ if (!changed)
655
+ return;
656
+ this.modelChangedReports();
657
+ this.send({ sessionUpdate: "config_option_update", configOptions: this.config.options() });
658
+ }, (error) => {
659
+ this.connection.logger.error(`Session ${this.sessionId}: failed to follow a model switch`, error);
660
+ });
661
+ }
662
+ /** The reports follow the model: its context window, and the idle compaction. */
663
+ modelChangedReports() {
664
+ const { id, info } = this.config.currentModel();
665
+ this.reports.modelChanged(id, info);
666
+ }
667
+ /** Claude Code reported a Fast mode state, on `system`/init or a result. */
668
+ fastModeReported(message) {
669
+ if (this.config.fastModeReported(message.fast_mode_state, message.fast_mode_disabled_reason)) {
670
+ this.send({ sessionUpdate: "config_option_update", configOptions: this.config.options() });
671
+ }
672
+ }
673
+ /**
674
+ * Claude Code mounted a fresh conversation (such as for `/clear`), whose
675
+ * Task* ids and task store are independent of the previous transcript. The
676
+ * old conversation's plans are removed (`plan_removed` of the checklist and
677
+ * of the approved ExitPlanMode plan) before a follow-up prompt can
678
+ * republish stale tasks, and the title and the idle compaction start over.
679
+ * The fresh context of an approved plan removes no plan: that plan becomes
680
+ * the session's plan in it.
681
+ */
682
+ conversationReset() {
683
+ // First, the subagents of the dropped conversation end.
684
+ this.tasks.conversationReset();
685
+ this.output.taskState.clear();
686
+ if (!this.clearContext.holdsTurn()) {
687
+ // Every v2 client has plan operations. v2 publishes an approved plan
688
+ // under the plain `plan-mode` id, also to AIR (see `planModeUpdate`).
689
+ const updates = resetPlanUpdates(true, false);
690
+ this.output.emitV1(updates.map((update) => ({ sessionId: this.sessionId, update })));
691
+ }
692
+ this.reports.conversationReset();
693
+ // A fresh context for an approved plan: the plan goes out in it.
694
+ this.clearContext.conversationReset();
695
+ }
696
+ // --- The query's messages ----------------------------------------------
697
+ async consume(query) {
698
+ try {
699
+ for await (const message of query) {
700
+ if (this.closed)
701
+ break;
702
+ try {
703
+ await this.handle(message);
704
+ }
705
+ catch (error) {
706
+ this.connection.logger.error(`Session ${this.sessionId}: failed to handle a ${message.type} message`, error);
707
+ }
708
+ this.checkBoundary();
709
+ }
710
+ this.ended(undefined);
711
+ }
712
+ catch (error) {
713
+ this.ended(error);
714
+ }
715
+ }
716
+ /**
717
+ * Claude Code's tool results. A SendMessage result can restore the agent
718
+ * that it resumed from the history: the results go out after the restore
719
+ * (see `SessionTasks.restoreResumed`).
720
+ */
721
+ toolResultMessage(message) {
722
+ const restoring = this.tasks.restoreResumed(this.output, message);
723
+ if (restoring)
724
+ return restoring.then(() => this.toolResults(message));
725
+ this.toolResults(message);
726
+ }
727
+ toolResults(message) {
728
+ if (message.parent_tool_use_id !== null) {
729
+ this.tasks.toolResults(this.output, message);
730
+ return;
731
+ }
732
+ // The rewrite applies to the updates of this message only.
733
+ this.output.rewrite = this.clearContext.toolResults(message);
734
+ try {
735
+ this.tasks.toolResults(this.output, message);
736
+ }
737
+ finally {
738
+ this.output.rewrite = undefined;
739
+ }
740
+ }
741
+ /**
742
+ * Handles one message. Only a `/mcp` turn's result, a result whose turn
743
+ * reads file-change reports, and a subagent's restore from the history are
744
+ * awaited (see {@link result}, {@link endTurn} and `SessionTasks.restored`).
745
+ */
746
+ handle(message) {
747
+ if (message.type === "command_lifecycle") {
748
+ this.lifecycle(message);
749
+ return;
750
+ }
751
+ // Before the tasks take a subagent's messages: its file edits are the turn's.
752
+ this.fileChanges?.message(message);
753
+ // Task events, and a subagent's messages, which go to its session.
754
+ // A subagent that a task restores from the history is read before the next message.
755
+ if (this.tasks.handle(message))
756
+ return this.tasks.restored();
757
+ switch (message.type) {
758
+ case "conversation_reset":
759
+ this.conversationReset();
760
+ return;
761
+ case "stream_event":
762
+ if (this.stopped.drops(message))
763
+ return;
764
+ if (message.parent_tool_use_id === null) {
765
+ this.outputStarts();
766
+ this.reports.streamEvent(message);
767
+ }
768
+ this.output.streamEvent(message);
769
+ return;
770
+ case "assistant":
771
+ if (message.parent_tool_use_id === null)
772
+ this.usage.assistant(message.message.model);
773
+ if (this.stopped.drops(message))
774
+ return;
775
+ if (message.parent_tool_use_id === null) {
776
+ // Claude Code's sign-in message is not shown (see `TurnReport`).
777
+ if (this.turnReport.assistant(message))
778
+ return;
779
+ this.outputStarts();
780
+ this.reports.assistant(message);
781
+ }
782
+ this.output.assistant(message);
783
+ return;
784
+ case "user":
785
+ // With `replay-user-messages`, Claude Code echoes each prompt it takes
786
+ // in. A prompt Claude Code reported `started` for is inserted already.
787
+ if ("isReplay" in message && message.isReplay) {
788
+ if (message.uuid && message.parent_tool_use_id === null) {
789
+ // A message typed in another client of the session.
790
+ const remote = this.remoteControl.remoteMessage(message);
791
+ if (remote !== undefined)
792
+ this.output.userMessage(remote, message.uuid);
793
+ this.promptStarted(message.uuid);
794
+ }
795
+ return;
796
+ }
797
+ if (this.stopped.drops(message))
798
+ return;
799
+ return this.toolResultMessage(message);
800
+ case "result":
801
+ return this.result(message);
802
+ case "system":
803
+ switch (message.subtype) {
804
+ case "init":
805
+ if (message.capabilities?.includes("msg_lifecycle_v1"))
806
+ this.lifecycleFrames = true;
807
+ this.elicitations.init(message.capabilities);
808
+ // A fresh init (such as after a reinitialize) can carry another Fast mode state.
809
+ this.fastModeReported(message);
810
+ this.reports.handle(message);
811
+ // Its terminal-bound commands leave the list.
812
+ if (this.commands.init(message))
813
+ this.resendCommands();
814
+ return;
815
+ case "status":
816
+ // Each model request starts with one, which lists the prompts it serves.
817
+ if (message.status === "requesting") {
818
+ const prompts = message.user_message_uuids;
819
+ this.stopped.requesting(Array.isArray(prompts) ? prompts : []);
820
+ }
821
+ this.report(message);
822
+ return;
823
+ case "local_command_output":
824
+ // The output of a local command, such as `/cost`.
825
+ if (this.stopped.drops(message))
826
+ return;
827
+ this.output.agentMessage(message.content, message.uuid);
828
+ return;
829
+ case "commands_changed":
830
+ this.send(this.commands.changed(message.commands));
831
+ return;
832
+ case "elicitation_complete":
833
+ this.elicitations.completed(message.elicitation_id);
834
+ return;
835
+ case "model_refusal_fallback": {
836
+ // Claude Code retried a refused turn on the fallback model.
837
+ const fallback = modelRefusalFallback(message);
838
+ this.output.emitV1([
839
+ { sessionId: this.sessionId, update: noticeUpdate(fallback.notice) },
840
+ ]);
841
+ if (fallback.persistent)
842
+ this.modelSwitched(message.fallback_model);
843
+ return;
844
+ }
845
+ case "model_refusal_no_fallback":
846
+ this.turnReport.refusalWithoutFallback(message);
847
+ return;
848
+ case "permission_denied":
849
+ // A rule, the classifier or the mode denied a tool use before it ran.
850
+ this.tasks.permissionDenied(message);
851
+ return;
852
+ case "session_state_changed":
853
+ if (message.state === "idle") {
854
+ this.claudeCodeIdle();
855
+ this.reports.idle();
856
+ }
857
+ return;
858
+ default:
859
+ this.report(message);
860
+ return;
861
+ }
862
+ default:
863
+ this.report(message);
864
+ return;
865
+ }
866
+ }
867
+ /**
868
+ * The messages that report on the session rather than carry Claude's
869
+ * output (see {@link SessionReports}).
870
+ */
871
+ report(message) {
872
+ if (message.type === "tool_progress") {
873
+ this.output.toolProgress(message);
874
+ return;
875
+ }
876
+ if (message.type === "system" && message.subtype === "memory_recall") {
877
+ this.output.memoryRecall(message);
878
+ return;
879
+ }
880
+ // A compaction runs in a turn: it opens the turn if nothing reported it yet.
881
+ if (message.type === "system" &&
882
+ message.subtype === "status" &&
883
+ message.status === "compacting") {
884
+ this.openTurn(undefined);
885
+ }
886
+ this.reports.handle(message);
887
+ }
888
+ lifecycle(frame) {
889
+ this.lifecycleFrames = true;
890
+ const uuid = frame.command_uuid;
891
+ switch (frame.state) {
892
+ case "started":
893
+ this.promptStarted(uuid);
894
+ return;
895
+ case "cancelled":
896
+ if (this.failPrompt(uuid, RequestError.requestCancelled()))
897
+ return;
898
+ this.stopped.promptEnded(uuid, true);
899
+ // The prompt had started: the interrupt stopped its turn.
900
+ if (uuid === this.turnCommand)
901
+ this.closeTurn();
902
+ return;
903
+ case "discarded":
904
+ case "refused":
905
+ this.failPrompt(uuid, RequestError.internalError({ lifecycle: frame.state }, `Claude Code ${frame.state} the prompt before it ran`));
906
+ return;
907
+ case "completed":
908
+ // Comes after the turn's result. A turn that ended without one ends here.
909
+ this.stopped.promptEnded(uuid);
910
+ if (uuid === this.turnCommand)
911
+ this.closeTurn();
912
+ return;
913
+ default:
914
+ // `queued`: the prompt waits in Claude Code's queue.
915
+ return;
916
+ }
917
+ }
918
+ /**
919
+ * Claude Code took in the prompt `uuid`: its `started` frame or its echo.
920
+ * The prompt's `user_message` comes before the turn's `running`. v2 allows
921
+ * either order. A prompt that a cancel abandoned starts
922
+ * nothing (see {@link StoppedWork}).
923
+ */
924
+ promptStarted(uuid) {
925
+ if (this.stopped.promptStarted(uuid, this.foreground))
926
+ return;
927
+ // Claude Code takes its prompts in order: the work that a cancel stopped
928
+ // has ended, also when the cancel came while it ran nothing.
929
+ this.tasks.foregroundCancelEnded();
930
+ if (this.clearContext.promptStarted(uuid))
931
+ this.fileChanges?.contextCleared(uuid);
932
+ this.inserted(uuid);
933
+ this.openTurn(uuid);
934
+ }
935
+ inserted(uuid) {
936
+ const prompt = this.pending.get(uuid);
937
+ if (!prompt)
938
+ return;
939
+ this.pending.delete(uuid);
940
+ this.fileChanges?.promptStarted(uuid);
941
+ this.send({ sessionUpdate: "user_message", messageId: uuid, content: prompt.prompt });
942
+ prompt.resolve({ messageId: uuid });
943
+ }
944
+ /**
945
+ * Output of the main conversation while no turn is open starts a cycle
946
+ * that Claude Code started on its own. Without lifecycle frames, a pushed
947
+ * prompt's output can come before its echo, so output while one waits is
948
+ * that prompt's, and its echo opens the turn.
949
+ */
950
+ outputStarts() {
951
+ if (this.foreground)
952
+ return;
953
+ if (!this.lifecycleFrames && [...this.pending.values()].some((prompt) => prompt.pushed)) {
954
+ return;
955
+ }
956
+ this.openTurn(undefined);
957
+ }
958
+ result(message) {
959
+ // Every result moves the usage reading on, also one that ends nothing.
960
+ const end = this.usage.record(message);
961
+ if (isPlaceholderResult(message))
962
+ return;
963
+ this.idleOwed = true;
964
+ const { dropped, interrupted } = this.stopped.result(message);
965
+ // Also a dropped result: the cancel's interrupt reached no further.
966
+ this.tasks.foregroundCancelEnded();
967
+ if (dropped) {
968
+ this.turnReport.reset();
969
+ return;
970
+ }
971
+ // The interrupt stopped work that Claude Code had started before the cancel arrived.
972
+ if (interrupted)
973
+ this.cancelledWork = true;
974
+ // A result with no open turn: a turn that sent nothing before it.
975
+ this.openTurn(undefined);
976
+ // A cycle that Claude Code started on its own leaves its Fast mode state
977
+ // to the next result of a prompt.
978
+ if (!(message.origin && AUTONOMOUS_RESULT_ORIGINS.has(message.origin.kind))) {
979
+ this.fastModeReported(message);
980
+ }
981
+ this.reports.result(message);
982
+ // The turn goes on in a fresh context (see `ClearContext`).
983
+ if (this.clearContext.holdsResult(message, end)) {
984
+ this.turnReport.reset();
985
+ return;
986
+ }
987
+ this.lastEnd = this.clearContext.turnEnd(end);
988
+ const local = this.turnLocalCommand;
989
+ if (message.stop_reason === "refusal") {
990
+ // The refused message shows nothing: its explanation answers.
991
+ const explanation = this.turnReport.refusalExplanation;
992
+ if (explanation)
993
+ this.output.agentMessage(explanation, message.uuid);
994
+ }
995
+ else if (message.subtype === "success" &&
996
+ !message.is_error &&
997
+ message.result &&
998
+ !this.output.hasAgentText() &&
999
+ !this.reports.repeats(message.result)) {
1000
+ // A local command (such as `/context`) answers with its result alone:
1001
+ // no model text streamed for it. A result that only repeats a notice or
1002
+ // a compaction of the turn is not shown again.
1003
+ if (local && this.query) {
1004
+ // The adapter's `/mcp` text replaces Claude Code's. `consume` waits
1005
+ // for it, so it goes out before the turn's idle.
1006
+ return this.commands
1007
+ .replace(this.query, local.command, message.result, local.abort.signal, (error) => this.connection.logger.error(`Session ${this.sessionId}: ${error}`))
1008
+ .then((text) => {
1009
+ this.output.agentMessage(text, message.uuid);
1010
+ return this.endTurn();
1011
+ });
1012
+ }
1013
+ this.output.agentMessage(message.result, message.uuid);
1014
+ }
1015
+ return this.endTurn();
1016
+ }
1017
+ /**
1018
+ * Ends the open turn at its result. The file-change reports that its
1019
+ * prompts asked for go out first (see `file-changes.ts`). `consume` waits
1020
+ * for them, so the idle follows them.
1021
+ */
1022
+ endTurn() {
1023
+ if (!this.foreground || this.clearContext.holdsTurn())
1024
+ return;
1025
+ const { stopReason } = idleOutcome(this.lastEnd, this.cancelledWork, this.turnReport);
1026
+ const reporting = this.fileChanges?.turnEnding(stopReason, this.query);
1027
+ if (!reporting)
1028
+ return this.closeTurn();
1029
+ return reporting.then(() => this.closeTurn());
1030
+ }
1031
+ /**
1032
+ * Claude Code's `idle`. The one that follows a result is that result's, and
1033
+ * can come after the next cycle's first output. Any other ends the open
1034
+ * turn, such as one that an interrupt stopped before it ran.
1035
+ */
1036
+ claudeCodeIdle() {
1037
+ if (this.idleOwed) {
1038
+ this.idleOwed = false;
1039
+ return;
1040
+ }
1041
+ this.stopped.idle();
1042
+ this.tasks.foregroundCancelEnded();
1043
+ this.closeTurn();
1044
+ }
1045
+ /** Sends the commands again, without failing the message that changed them. */
1046
+ resendCommands() {
1047
+ this.sendCommands().catch((error) => {
1048
+ this.connection.logger.error(`Session ${this.sessionId}: failed to send its commands`, error);
1049
+ });
1050
+ }
1051
+ /** The query ended, with `error` when it failed. The session cannot go on. */
1052
+ ended(error) {
1053
+ this.endReports();
1054
+ if (this.closing || this.closed) {
1055
+ this.tasks.queryEnded(undefined);
1056
+ this.failPending(RequestError.requestCancelled());
1057
+ this.closed = true;
1058
+ return;
1059
+ }
1060
+ const failure = RequestError.internalError(error instanceof Error ? { cause: error.message } : undefined, "Claude Code stopped. Resume the session to continue.");
1061
+ this.failPending(failure);
1062
+ this.connection.logger.error(`Session ${this.sessionId}: the query ended`, error);
1063
+ this.tasks.queryEnded({ code: failure.code, message: failure.message });
1064
+ if (this.foreground) {
1065
+ // Cancelled work that ended with the query was still cancelled.
1066
+ if (this.cancelledWork)
1067
+ this.output.closeUnfinished(true);
1068
+ else
1069
+ this.output.finishUnfinished("failed");
1070
+ this.fileChanges?.turnClosed(this.cancelledWork);
1071
+ // As `closeTurn`: a compaction still `in_progress` ends before the idle.
1072
+ this.reports.turnEnded();
1073
+ this.foreground = false;
1074
+ this.reportedState = "idle";
1075
+ this.send({
1076
+ sessionUpdate: "state_update",
1077
+ state: "idle",
1078
+ ...(this.cancelledWork
1079
+ ? idleOutcome(undefined, true, undefined, this.turnCommand !== undefined)
1080
+ : {
1081
+ stopReason: "error",
1082
+ error: { code: failure.code, message: failure.message },
1083
+ }),
1084
+ });
1085
+ }
1086
+ this.closed = true;
1087
+ this.checkBoundary();
1088
+ this.connection.ended(this);
1089
+ }
1090
+ /** The session ends: its idle compaction is off, and its own `/compact` settles. */
1091
+ endReports() {
1092
+ this.reports.dispose();
1093
+ this.ownCommandDone?.();
1094
+ this.ownCommandDone = undefined;
1095
+ }
1096
+ // --- State ---------------------------------------------------------------
1097
+ /**
1098
+ * Opens a turn, if none is open. `command` is the prompt that started it,
1099
+ * if one did.
1100
+ */
1101
+ openTurn(command) {
1102
+ if (command !== undefined) {
1103
+ this.turnCommand = command;
1104
+ const local = this.localCommands.get(command);
1105
+ this.localCommands.delete(command);
1106
+ if (local)
1107
+ this.turnLocalCommand = { command: local, abort: new AbortController() };
1108
+ }
1109
+ if (this.foreground)
1110
+ return;
1111
+ this.foreground = true;
1112
+ this.lastEnd = undefined;
1113
+ this.output.resetAgentText();
1114
+ this.reports.turnStarted();
1115
+ this.reportState();
1116
+ }
1117
+ /**
1118
+ * Ends the open turn: its idle goes out with the turn's outcome. A turn
1119
+ * that waits for its plan's prompt in a fresh context goes on: its end is
1120
+ * that prompt's.
1121
+ */
1122
+ closeTurn() {
1123
+ if (!this.foreground || this.clearContext.holdsTurn())
1124
+ return;
1125
+ // v2 asks for a final status of the turn's tool calls before its idle. A
1126
+ // tool call whose task goes on in the background is not part of the work.
1127
+ const cancelled = idleOutcome(this.lastEnd, this.cancelledWork).stopReason === "cancelled";
1128
+ this.output.closeUnfinished(cancelled, this.tasks.backgroundCalls(this.sessionId));
1129
+ if (cancelled) {
1130
+ // v2 asks to stop waiting for the stopped work's requests. Claude Code's
1131
+ // interrupt withdraws them, and this withdraws what it left open.
1132
+ for (const request of this.requests) {
1133
+ if (request.coveredByCancel)
1134
+ request.abort.abort();
1135
+ }
1136
+ }
1137
+ this.reports.turnEnded();
1138
+ this.elicitations.turnEnded();
1139
+ this.fileChanges?.turnClosed(cancelled);
1140
+ this.foreground = false;
1141
+ this.reportState();
1142
+ this.cancelledWork = false;
1143
+ this.output.cancelled = false;
1144
+ this.lastEnd = undefined;
1145
+ this.turnCommand = undefined;
1146
+ this.turnReport.reset();
1147
+ const ownCommandDone = this.ownCommandDone;
1148
+ this.ownCommandDone = undefined;
1149
+ ownCommandDone?.();
1150
+ this.turnLocalCommand = undefined;
1151
+ this.checkBoundary();
1152
+ }
1153
+ /**
1154
+ * While the turn waits on subagents, it is blocked when each of them is
1155
+ * (see `SessionTasks.foregroundBlocked`). Otherwise by the session's own
1156
+ * open requests.
1157
+ */
1158
+ foregroundState() {
1159
+ if (!this.foreground)
1160
+ return "idle";
1161
+ const blocked = this.tasks.foregroundBlocked() ?? this.requests.size > 0;
1162
+ return blocked ? "requires_action" : "running";
1163
+ }
1164
+ /**
1165
+ * Reports the foreground state when it changed. `withdrawnByCancel`: the
1166
+ * change is the end of a request that a cancel withdrew, so the work is
1167
+ * stopping and its idle follows: no `running` goes out for it.
1168
+ */
1169
+ reportState(withdrawnByCancel = false) {
1170
+ if (this.closed)
1171
+ return;
1172
+ const state = this.foregroundState();
1173
+ if (state === this.reportedState)
1174
+ return;
1175
+ // The client keeps `requires_action`: the next report sends `running`
1176
+ // if the work goes on after all, such as when the interrupt fails.
1177
+ if (withdrawnByCancel && state === "running")
1178
+ return;
1179
+ this.reportedState = state;
1180
+ const update = this.stateUpdate(state);
1181
+ this.send(update);
1182
+ const error = update.error;
1183
+ if (state === "idle" && error?.code === RequestError.authRequired().code) {
1184
+ this.connection.signedOut(this.sessionId);
1185
+ }
1186
+ }
1187
+ stateUpdate(state) {
1188
+ switch (state) {
1189
+ case "running":
1190
+ return { sessionUpdate: "state_update", state };
1191
+ case "requires_action":
1192
+ return { sessionUpdate: "state_update", state };
1193
+ default:
1194
+ return {
1195
+ sessionUpdate: "state_update",
1196
+ state,
1197
+ ...idleOutcome(this.lastEnd, this.cancelledWork, this.turnReport, this.turnCommand !== undefined),
1198
+ };
1199
+ }
1200
+ }
1201
+ send(update) {
1202
+ this.sendNotification({ sessionId: this.sessionId, update });
1203
+ }
1204
+ /** Sends an update of the session or of a child, with its `background` list. */
1205
+ sendNotification(notification) {
1206
+ if (this.closed)
1207
+ return;
1208
+ this.connection.send(this.background.stamp(notification));
1209
+ }
1210
+ /** Fails the prompt `uuid` if it is not answered yet. Returns whether it was pending. */
1211
+ failPrompt(uuid, error) {
1212
+ const prompt = this.pending.get(uuid);
1213
+ if (!prompt)
1214
+ return false;
1215
+ this.pending.delete(uuid);
1216
+ this.localCommands.delete(uuid);
1217
+ this.fileChanges?.promptFailed(uuid, error);
1218
+ prompt.reject(error);
1219
+ this.checkBoundary();
1220
+ return true;
1221
+ }
1222
+ failPending(error) {
1223
+ for (const uuid of [...this.pending.keys()])
1224
+ this.failPrompt(uuid, error);
1225
+ }
137
1226
  }
138
1227
  /**
139
- * v2 requires a `type` on every transport and makes the empty lists optional.
140
- * The agent recognizes a v1 stdio server by its missing `type`, so the v2 tag
141
- * is dropped. {@link v1McpServers} has already rejected every other transport.
1228
+ * Sends a request to the client unless `signal` aborted already. The ACP SDK
1229
+ * would send it anyway, then withdraw it with `$/cancel_request`.
142
1230
  */
143
- function v1McpServer(server) {
144
- if (v2.McpServer.isStdio(server)) {
145
- const { name, command, args, env, _meta } = server;
146
- return { name, command, args: args ?? [], env: env ?? [], ...(_meta != null ? { _meta } : {}) };
147
- }
148
- if (v2.McpServer.isHttp(server)) {
149
- return { ...server, headers: server.headers ?? [] };
150
- }
151
- throw new Error(`Unreachable: MCP server of type ${server.type} passed the transport check`);
1231
+ function unlessWithdrawn(signal, send) {
1232
+ if (signal.aborted)
1233
+ return Promise.reject(new Error("The request was withdrawn"));
1234
+ return send();
152
1235
  }