@agentclientprotocol/claude-agent-acp 0.102.0 → 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 (206) hide show
  1. package/README.md +5 -1
  2. package/dist/acp-agent.d.ts +119 -439
  3. package/dist/acp-agent.d.ts.map +1 -1
  4. package/dist/acp-agent.js +380 -2412
  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/plans.d.ts +36 -6
  46. package/dist/plans.d.ts.map +1 -1
  47. package/dist/plans.js +49 -11
  48. package/dist/prompt-suggestions.d.ts +29 -0
  49. package/dist/prompt-suggestions.d.ts.map +1 -1
  50. package/dist/prompt-suggestions.js +45 -0
  51. package/dist/providers.d.ts +139 -0
  52. package/dist/providers.d.ts.map +1 -0
  53. package/dist/providers.js +286 -0
  54. package/dist/remote-control.d.ts +62 -0
  55. package/dist/remote-control.d.ts.map +1 -0
  56. package/dist/remote-control.js +78 -0
  57. package/dist/result-end.d.ts +39 -0
  58. package/dist/result-end.d.ts.map +1 -0
  59. package/dist/result-end.js +50 -0
  60. package/dist/serve.d.ts +7 -2
  61. package/dist/serve.d.ts.map +1 -1
  62. package/dist/serve.js +10 -5
  63. package/dist/session-config-ids.d.ts +1 -0
  64. package/dist/session-config-ids.d.ts.map +1 -1
  65. package/dist/session-config-ids.js +1 -0
  66. package/dist/session-config-options.d.ts +64 -0
  67. package/dist/session-config-options.d.ts.map +1 -0
  68. package/dist/session-config-options.js +162 -0
  69. package/dist/session-effort.d.ts +67 -0
  70. package/dist/session-effort.d.ts.map +1 -1
  71. package/dist/session-effort.js +98 -0
  72. package/dist/session-env.d.ts +22 -0
  73. package/dist/session-env.d.ts.map +1 -0
  74. package/dist/session-env.js +66 -0
  75. package/dist/session-fast-mode.d.ts +83 -0
  76. package/dist/session-fast-mode.d.ts.map +1 -0
  77. package/dist/session-fast-mode.js +142 -0
  78. package/dist/session-index/connection.d.ts +2 -5
  79. package/dist/session-index/connection.d.ts.map +1 -1
  80. package/dist/session-index/connection.js +3 -5
  81. package/dist/session-mode.d.ts +1 -0
  82. package/dist/session-mode.d.ts.map +1 -1
  83. package/dist/session-mode.js +1 -1
  84. package/dist/session-model.d.ts +41 -0
  85. package/dist/session-model.d.ts.map +1 -1
  86. package/dist/session-model.js +110 -45
  87. package/dist/session-notices.d.ts +44 -0
  88. package/dist/session-notices.d.ts.map +1 -1
  89. package/dist/session-notices.js +68 -0
  90. package/dist/session-titles.d.ts +34 -12
  91. package/dist/session-titles.d.ts.map +1 -1
  92. package/dist/session-titles.js +7 -6
  93. package/dist/session-usage.d.ts +125 -0
  94. package/dist/session-usage.d.ts.map +1 -0
  95. package/dist/session-usage.js +196 -0
  96. package/dist/streamed-text.d.ts +33 -0
  97. package/dist/streamed-text.d.ts.map +1 -0
  98. package/dist/streamed-text.js +71 -0
  99. package/dist/subagent-configuration.d.ts +32 -0
  100. package/dist/subagent-configuration.d.ts.map +1 -0
  101. package/dist/subagent-configuration.js +70 -0
  102. package/dist/subagent-replay.d.ts +18 -0
  103. package/dist/subagent-replay.d.ts.map +1 -1
  104. package/dist/subagent-replay.js +25 -15
  105. package/dist/tool-calls/client-capabilities.d.ts +8 -8
  106. package/dist/tool-calls/client-capabilities.js +4 -4
  107. package/dist/tool-calls/renderer.d.ts +4 -5
  108. package/dist/tool-calls/renderer.d.ts.map +1 -1
  109. package/dist/tool-calls/renderer.js +4 -5
  110. package/dist/turn-events.d.ts +6 -46
  111. package/dist/turn-events.d.ts.map +1 -1
  112. package/dist/v2/agent.d.ts +7 -11
  113. package/dist/v2/agent.d.ts.map +1 -1
  114. package/dist/v2/agent.js +751 -331
  115. package/dist/v2/air.d.ts +33 -0
  116. package/dist/v2/air.d.ts.map +1 -0
  117. package/dist/v2/air.js +29 -0
  118. package/dist/v2/auth.d.ts +97 -0
  119. package/dist/v2/auth.d.ts.map +1 -0
  120. package/dist/v2/auth.js +216 -0
  121. package/dist/v2/background.d.ts +27 -16
  122. package/dist/v2/background.d.ts.map +1 -1
  123. package/dist/v2/background.js +4 -32
  124. package/dist/v2/child-config.d.ts +55 -0
  125. package/dist/v2/child-config.d.ts.map +1 -0
  126. package/dist/v2/child-config.js +92 -0
  127. package/dist/v2/clear-context.d.ts +94 -0
  128. package/dist/v2/clear-context.d.ts.map +1 -0
  129. package/dist/v2/clear-context.js +176 -0
  130. package/dist/v2/commands.d.ts +46 -0
  131. package/dist/v2/commands.d.ts.map +1 -0
  132. package/dist/v2/commands.js +54 -0
  133. package/dist/v2/config.d.ts +187 -0
  134. package/dist/v2/config.d.ts.map +1 -0
  135. package/dist/v2/config.js +494 -0
  136. package/dist/v2/elicitation.d.ts +93 -0
  137. package/dist/v2/elicitation.d.ts.map +1 -0
  138. package/dist/v2/elicitation.js +160 -0
  139. package/dist/v2/file-changes.d.ts +61 -0
  140. package/dist/v2/file-changes.d.ts.map +1 -0
  141. package/dist/v2/file-changes.js +108 -0
  142. package/dist/v2/file-preview.d.ts +18 -0
  143. package/dist/v2/file-preview.d.ts.map +1 -0
  144. package/dist/v2/file-preview.js +29 -0
  145. package/dist/v2/initialize.d.ts +10 -24
  146. package/dist/v2/initialize.d.ts.map +1 -1
  147. package/dist/v2/initialize.js +4 -111
  148. package/dist/v2/outcome.d.ts +81 -0
  149. package/dist/v2/outcome.d.ts.map +1 -0
  150. package/dist/v2/outcome.js +165 -0
  151. package/dist/v2/permissions.d.ts +92 -0
  152. package/dist/v2/permissions.d.ts.map +1 -0
  153. package/dist/v2/permissions.js +162 -0
  154. package/dist/v2/prompt.d.ts +2 -42
  155. package/dist/v2/prompt.d.ts.map +1 -1
  156. package/dist/v2/prompt.js +2 -119
  157. package/dist/v2/remote-control.d.ts +41 -0
  158. package/dist/v2/remote-control.d.ts.map +1 -0
  159. package/dist/v2/remote-control.js +63 -0
  160. package/dist/v2/reports.d.ts +198 -0
  161. package/dist/v2/reports.d.ts.map +1 -0
  162. package/dist/v2/reports.js +487 -0
  163. package/dist/v2/restarts.d.ts +128 -0
  164. package/dist/v2/restarts.d.ts.map +1 -0
  165. package/dist/v2/restarts.js +348 -0
  166. package/dist/v2/session-requests.d.ts +20 -0
  167. package/dist/v2/session-requests.d.ts.map +1 -0
  168. package/dist/v2/session-requests.js +108 -0
  169. package/dist/v2/session-update.d.ts +2 -13
  170. package/dist/v2/session-update.d.ts.map +1 -1
  171. package/dist/v2/session-update.js +2 -22
  172. package/dist/v2/session.d.ts +340 -41
  173. package/dist/v2/session.d.ts.map +1 -1
  174. package/dist/v2/session.js +1223 -141
  175. package/dist/v2/setup.d.ts +49 -0
  176. package/dist/v2/setup.d.ts.map +1 -0
  177. package/dist/v2/setup.js +62 -0
  178. package/dist/v2/stopped-work.d.ts +123 -0
  179. package/dist/v2/stopped-work.d.ts.map +1 -0
  180. package/dist/v2/stopped-work.js +210 -0
  181. package/dist/v2/stream.d.ts +228 -0
  182. package/dist/v2/stream.d.ts.map +1 -0
  183. package/dist/v2/stream.js +506 -0
  184. package/dist/v2/subagent-replay.d.ts +115 -0
  185. package/dist/v2/subagent-replay.d.ts.map +1 -0
  186. package/dist/v2/subagent-replay.js +479 -0
  187. package/dist/v2/subscription-guard.d.ts +60 -0
  188. package/dist/v2/subscription-guard.d.ts.map +1 -0
  189. package/dist/v2/subscription-guard.js +84 -0
  190. package/dist/v2/tasks.d.ts +492 -0
  191. package/dist/v2/tasks.d.ts.map +1 -0
  192. package/dist/v2/tasks.js +1728 -0
  193. package/dist/v2/terminal.d.ts.map +1 -1
  194. package/dist/v2/terminal.js +6 -1
  195. package/dist/v2/tool-call.d.ts +3 -2
  196. package/dist/v2/tool-call.d.ts.map +1 -1
  197. package/dist/v2/update-translator.d.ts +36 -0
  198. package/dist/v2/update-translator.d.ts.map +1 -0
  199. package/dist/v2/update-translator.js +80 -0
  200. package/dist/workflow-progress.d.ts +23 -0
  201. package/dist/workflow-progress.d.ts.map +1 -1
  202. package/dist/workflow-progress.js +31 -8
  203. package/package.json +1 -1
  204. package/dist/v2/permission.d.ts +0 -28
  205. package/dist/v2/permission.d.ts.map +0 -1
  206. package/dist/v2/permission.js +0 -41
@@ -0,0 +1,479 @@
1
+ /**
2
+ * The replay of a session's subagents, for `session/resume` with
3
+ * `replayFrom`, as the v1 core replays them (`RfdSubagentReplay`).
4
+ *
5
+ * Claude Code keeps each subagent's history in its own transcript, and its
6
+ * metadata file names the Agent or Task call that launched it (see
7
+ * `subagentHistory`). The replay announces each child right after that call,
8
+ * under its live session id (the agent id), with no capabilities: it cannot
9
+ * run again in this process. Then it sends the child's `model` (of its first
10
+ * response) and its history to the child session; a later response with
11
+ * another model sends it again. As live, the parent is not shown the launch
12
+ * call: its prompt is the parent's outgoing message, and a foreground child's
13
+ * answer its reply. A child's successful SubagentHandback call is its message
14
+ * to the parent instead. Unlike live, the replay does not tell runs apart, so
15
+ * a child that handed back any report gets no reply from its launch's result.
16
+ *
17
+ * A SendMessage call whose message the replay delivered to a child before it
18
+ * reached the call is that message too: the sender's outgoing view, at the
19
+ * call, and the child's incoming one, in the child's history. A child's
20
+ * history follows its launch, so a call to a child from its parent is always
21
+ * delivered first. Any other SendMessage call stays a tool call.
22
+ *
23
+ * Every child's end goes out on its parent at the end of the replay, and once
24
+ * on the child's own stream: v2 forbids replaying a child's past `running` as
25
+ * current activity. These states are history to the client, so each child's
26
+ * current state goes out again after the response ({@link afterResponse}).
27
+ * A child that the live session still tracks, on a resume of the active
28
+ * session, gets its current state from the resume snapshot instead
29
+ * (`SessionTasks.currentState`). After the response, a child whose
30
+ * configuration is not the `model` that the replay sent, such as a live child
31
+ * whose hooks reported its mode, gets it again.
32
+ *
33
+ * A launch without metadata has no known id, so it is not announced: the RFD
34
+ * forbids inventing one. Its Agent call stays an ordinary tool call of the
35
+ * parent, and a notice at the end says that subagent history is missing, as
36
+ * it does for a child whose transcript cannot be read.
37
+ */
38
+ import * as fs from "node:fs";
39
+ import { childModelOption, HANDBACK_TOOL, handbackMessage, isNativeSubagentControlTool, launchReply, linkedSessionMessages, nativeSubagentState, responseModelEntry, rfdEndState, rfdLabels, } from "../native-subagents.js";
40
+ import { readSubagentMessages, subagentHistory, subagentLaunchIds, } from "../subagent-history.js";
41
+ import { deliveredCall, firstResponseModel, isDelivery, missingHistoryNotice, replaySubagentTerminalState, } from "../subagent-replay.js";
42
+ import { taskNotificationsOf } from "../task-notifications.js";
43
+ import { SessionOutput } from "./stream.js";
44
+ import { sameDirectory } from "./tasks.js";
45
+ const NO_LIVE_CHILDREN = { tracks: () => false, configuration: () => undefined };
46
+ export class SubagentReplay {
47
+ host;
48
+ history;
49
+ transcripts;
50
+ live;
51
+ /** The children, by the id of the call that launched each. */
52
+ children = new Map();
53
+ sendMessages = [];
54
+ /** The SubagentHandback calls, with their report and whether their result failed. */
55
+ handbacks = new Map();
56
+ /** Launches without metadata, which the replay leaves out. */
57
+ omitted = new Set();
58
+ /** Children whose transcript could not be read: only their association is replayed. */
59
+ withoutHistory = 0;
60
+ rootOutput;
61
+ constructor(host, history,
62
+ /** The transcript of each child, by agent id. */
63
+ transcripts, live) {
64
+ this.host = host;
65
+ this.history = history;
66
+ this.transcripts = transcripts;
67
+ this.live = live;
68
+ }
69
+ /**
70
+ * Reads the subagent history that `messages`, the session's transcript,
71
+ * launched, with every child's transcript. Undefined when it launched none.
72
+ */
73
+ static async load(host, messages, live = NO_LIVE_CHILDREN) {
74
+ if (!messages.some((message) => launchIdsOf(message).length > 0))
75
+ return undefined;
76
+ const history = await subagentHistory(host.sessionId);
77
+ const transcripts = new Map();
78
+ const queue = messages.flatMap(launchIdsOf);
79
+ while (queue.length > 0) {
80
+ const record = history.agents.get(queue.shift());
81
+ if (!record || transcripts.has(record.agentId))
82
+ continue;
83
+ const transcript = (await readSubagentMessages(host.sessionId, record.agentId, history, host.logger)).map((message) => ({ ...message, parent_tool_use_id: null }));
84
+ transcripts.set(record.agentId, transcript);
85
+ queue.push(...transcript.flatMap(launchIdsOf));
86
+ }
87
+ return new SubagentReplay(host, history, transcripts, live);
88
+ }
89
+ /** The hooks of the replay of the root session's history (`messages`). */
90
+ hooks(output, messages) {
91
+ this.rootOutput = output;
92
+ this.scan(messages, output.sessionId);
93
+ return this.ownerHooks(output, undefined);
94
+ }
95
+ /**
96
+ * Ends the replay: every child's end, on its parent, then once on its own
97
+ * stream, and the notice when subagent history is missing.
98
+ */
99
+ finish() {
100
+ const announced = [...this.children.values()].filter((child) => child.announced);
101
+ for (const child of [...announced].reverse()) {
102
+ this.host.send({
103
+ sessionId: child.parentSessionId,
104
+ update: {
105
+ sessionUpdate: "subagent_update",
106
+ sessionId: child.sessionId,
107
+ state: endState(child),
108
+ },
109
+ });
110
+ }
111
+ for (const child of announced) {
112
+ this.host.send({
113
+ sessionId: child.sessionId,
114
+ update: { sessionUpdate: "state_update", ...endState(child) },
115
+ });
116
+ }
117
+ const missing = this.omitted.size + this.withoutHistory;
118
+ if (missing > 0) {
119
+ this.rootOutput?.emitV1([
120
+ { sessionId: this.host.sessionId, update: missingHistoryNotice(missing) },
121
+ ]);
122
+ }
123
+ }
124
+ /**
125
+ * After the response, as the v1 core sends them (`currentStates`): the
126
+ * current state of each replayed child that the live session does not
127
+ * track, since its process is gone, so its replayed end. A `cwd` that is
128
+ * gone, such as a worktree that Claude Code removed, is cleared. Then each
129
+ * replayed child's configuration, when it is not the `model` that the
130
+ * replay sent: the live child's, else the model of its latest response, by
131
+ * the session's model list.
132
+ */
133
+ afterResponse() {
134
+ for (const child of this.children.values()) {
135
+ if (!child.announced)
136
+ continue;
137
+ if (!this.live.tracks(child.sessionId))
138
+ this.sendEndState(child);
139
+ this.sendConfiguration(child);
140
+ }
141
+ }
142
+ sendConfiguration(child) {
143
+ const entry = responseModelEntry(child.responseModel, this.host.models());
144
+ const current = this.live.configuration(child.sessionId) ?? (entry ? [childModelOption(entry)] : undefined);
145
+ const replayed = child.model ? JSON.stringify([childModelOption(child.model)]) : undefined;
146
+ if (!current || JSON.stringify(current) === replayed)
147
+ return;
148
+ child.output.emitV1([
149
+ {
150
+ sessionId: child.sessionId,
151
+ update: { sessionUpdate: "config_option_update", configOptions: current },
152
+ },
153
+ ]);
154
+ }
155
+ sendEndState(child) {
156
+ const state = endState(child);
157
+ this.host.send({
158
+ sessionId: child.parentSessionId,
159
+ update: {
160
+ sessionUpdate: "subagent_update",
161
+ sessionId: child.sessionId,
162
+ ...(child.cwd && !isDirectory(child.cwd) ? { cwd: null } : {}),
163
+ state: state,
164
+ },
165
+ });
166
+ this.host.send({
167
+ sessionId: child.sessionId,
168
+ update: { sessionUpdate: "state_update", ...state },
169
+ });
170
+ }
171
+ ownerHooks(output, owner) {
172
+ return {
173
+ route: (notification) => this.route(notification, output, owner),
174
+ replaying: (message) => this.replaying(message, owner),
175
+ replayed: (message) => this.replayed(message, output),
176
+ ...(owner
177
+ ? { userContent: (message, content) => this.childContent(owner, message, content) }
178
+ : {}),
179
+ };
180
+ }
181
+ /**
182
+ * Registers the launches, the launch results, the SendMessage calls and the
183
+ * SubagentHandback calls in `messages`, of the session `ownerSessionId`.
184
+ */
185
+ scan(messages, ownerSessionId) {
186
+ for (const message of messages) {
187
+ for (const block of contentBlocks(message)) {
188
+ if (block.type === "tool_use" && typeof block.id === "string") {
189
+ if (isNativeSubagentControlTool(block.name)) {
190
+ this.registerLaunch(block.id, inputOf(block), ownerSessionId);
191
+ }
192
+ else if (block.name === HANDBACK_TOOL) {
193
+ const report = handbackMessage(block.input);
194
+ if (report)
195
+ this.handbacks.set(block.id, { message: report, failed: false, sent: false });
196
+ }
197
+ else if (block.name === "SendMessage") {
198
+ const input = inputOf(block);
199
+ if (typeof input.to === "string" && typeof input.message === "string") {
200
+ this.sendMessages.push({
201
+ toolUseId: block.id,
202
+ to: input.to,
203
+ message: input.message,
204
+ senderSessionId: ownerSessionId,
205
+ shownAsToolCall: false,
206
+ outgoingSent: false,
207
+ });
208
+ }
209
+ }
210
+ }
211
+ else if (block.type === "tool_result" && typeof block.tool_use_id === "string") {
212
+ const handback = this.handbacks.get(block.tool_use_id);
213
+ if (handback && block.is_error === true)
214
+ handback.failed = true;
215
+ const child = this.children.get(block.tool_use_id);
216
+ // A background launch answers at once; its result is not the end.
217
+ if (child && !child.record.background)
218
+ child.launchEnd = replaySubagentTerminalState(block);
219
+ }
220
+ }
221
+ }
222
+ }
223
+ registerLaunch(launchId, input, parentSessionId) {
224
+ if (this.children.has(launchId))
225
+ return;
226
+ const record = this.history.agents.get(launchId);
227
+ if (!record) {
228
+ this.omitted.add(launchId);
229
+ return;
230
+ }
231
+ this.children.set(launchId, {
232
+ launchId,
233
+ sessionId: record.agentId,
234
+ record,
235
+ parentSessionId,
236
+ input,
237
+ announced: false,
238
+ promptSent: false,
239
+ });
240
+ }
241
+ /**
242
+ * A replayed update of a tool call of `output`, the session of `owner`
243
+ * when it is a child's. The client is not shown the launch of a replayed
244
+ * child, a SendMessage call whose message the replay delivered, or a
245
+ * successful SubagentHandback call: a foreground launch's completed result
246
+ * goes out as the child's reply, a delivered SendMessage as the sender's
247
+ * outgoing message, and a hand-back as the child's message to its parent.
248
+ */
249
+ route(notification, output, owner) {
250
+ const { update } = notification;
251
+ if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") {
252
+ return [notification];
253
+ }
254
+ const sendMessage = this.sendMessages.find((call) => call.toolUseId === update.toolCallId);
255
+ if (sendMessage) {
256
+ if (sendMessage.recipientSessionId === undefined) {
257
+ sendMessage.shownAsToolCall = true;
258
+ return [notification];
259
+ }
260
+ if (sendMessage.outgoingSent)
261
+ return [];
262
+ sendMessage.outgoingSent = true;
263
+ const [outgoing] = linkedSessionMessages(sendMessage.toolUseId, sendMessage.senderSessionId, sendMessage.recipientSessionId, sendMessage.message);
264
+ return [outgoing];
265
+ }
266
+ const handback = owner ? this.handbacks.get(update.toolCallId) : undefined;
267
+ if (owner && handback && !handback.failed) {
268
+ if (handback.sent)
269
+ return [];
270
+ handback.sent = true;
271
+ owner.handedBack = true;
272
+ const [outgoing, incoming] = linkedSessionMessages(update.toolCallId, owner.sessionId, owner.parentSessionId, handback.message);
273
+ // Sent here, in order: an output routes each update once the ones before it went out.
274
+ output.emitV1([outgoing]);
275
+ this.outputOf(owner.parentSessionId)?.emitV1([incoming]);
276
+ return [];
277
+ }
278
+ const child = this.children.get(update.toolCallId);
279
+ if (!child)
280
+ return [notification];
281
+ if (update.status === "completed" &&
282
+ child.announced &&
283
+ !child.record.background &&
284
+ !child.handedBack) {
285
+ const reply = launchReply(child.launchId, child.sessionId, child.parentSessionId, update);
286
+ if (reply)
287
+ return [reply];
288
+ }
289
+ return [];
290
+ }
291
+ /**
292
+ * Before a message of `owner`'s history (the root's when undefined): a
293
+ * child's response with another model sends its `model` again, and a
294
+ * persisted task notification of a child is the state its work ended in.
295
+ */
296
+ replaying(message, owner) {
297
+ const inner = message.message;
298
+ if (message.type === "assistant") {
299
+ if (owner)
300
+ this.sendModel(owner, typeof inner?.model === "string" ? inner.model : undefined);
301
+ return;
302
+ }
303
+ for (const notification of taskNotificationsOf(inner?.content)) {
304
+ const child = [...this.children.values()].find((c) => c.sessionId === notification.task_id);
305
+ if (child)
306
+ child.notified = nativeSubagentState(notification.status) ?? child.notified;
307
+ }
308
+ }
309
+ /** After a message that launched children: each is announced, and its history replays. */
310
+ replayed(message, parent) {
311
+ if (message.type !== "assistant")
312
+ return;
313
+ for (const launchId of launchIdsOf(message)) {
314
+ const child = this.children.get(launchId);
315
+ if (!child || child.announced)
316
+ continue;
317
+ const messages = this.transcripts.get(child.sessionId) ?? [];
318
+ if (messages.length === 0)
319
+ this.withoutHistory++;
320
+ this.announce(child);
321
+ this.sendModel(child, firstResponseModel(messages));
322
+ this.scan(messages, child.sessionId);
323
+ child.output.replay(messages, this.ownerHooks(child.output, child));
324
+ if (!child.promptSent && typeof child.input.prompt === "string") {
325
+ this.sendPrompt(child, parent, child.input.prompt);
326
+ }
327
+ }
328
+ }
329
+ announce(child) {
330
+ const labels = rfdLabels(child.record.name ?? child.input.name, child.record.agentType ?? child.input.subagent_type, child.record.description ?? child.input.description);
331
+ const parentCwd = this.cwdOf(child.parentSessionId);
332
+ child.cwd =
333
+ child.record.cwd && !sameDirectory(child.record.cwd, parentCwd)
334
+ ? child.record.cwd
335
+ : undefined;
336
+ child.announced = true;
337
+ this.host.send({
338
+ sessionId: child.parentSessionId,
339
+ update: {
340
+ sessionUpdate: "subagent_update",
341
+ sessionId: child.sessionId,
342
+ ...(labels.title ? { title: labels.title } : {}),
343
+ ...(labels.description ? { description: labels.description } : {}),
344
+ ...(child.cwd ? { cwd: child.cwd } : {}),
345
+ state: { state: "running" },
346
+ },
347
+ });
348
+ child.output = new SessionOutput(child.sessionId, child.cwd ?? parentCwd, this.host.translator, (update) => this.host.send({ sessionId: child.sessionId, update }), this.host.logger, true);
349
+ }
350
+ /** The `model` of a response of `child`, when it is not the one the client holds. */
351
+ sendModel(child, model) {
352
+ const entry = responseModelEntry(model, this.host.models());
353
+ if (!entry || !child.output)
354
+ return;
355
+ child.responseModel = model;
356
+ if (child.model?.value === entry.value && child.model.name === entry.name)
357
+ return;
358
+ child.model = entry;
359
+ child.output.emitV1([
360
+ {
361
+ sessionId: child.sessionId,
362
+ update: { sessionUpdate: "config_option_update", configOptions: [childModelOption(entry)] },
363
+ },
364
+ ]);
365
+ }
366
+ /**
367
+ * The rest of a child's user message to replay, or `null` when nothing is
368
+ * left, after its text went out as the child's incoming `session_message`.
369
+ * The first text is the prompt of the launch. A message that a SendMessage
370
+ * call delivered (`origin.kind: "coordinator"`) is another incoming
371
+ * message. Any other text is Claude Code's, such as "[Request interrupted
372
+ * by user]", which the live child session does not show. Tool results stay.
373
+ */
374
+ childContent(child, message, content) {
375
+ const text = textOf(content);
376
+ if (text.trim()) {
377
+ if (isDelivery(message))
378
+ this.sendDelivery(child, message, text);
379
+ else if (!child.promptSent) {
380
+ const parent = this.outputOf(child.parentSessionId);
381
+ if (parent)
382
+ this.sendPrompt(child, parent, text);
383
+ }
384
+ }
385
+ if (!Array.isArray(content))
386
+ return null;
387
+ const rest = content.filter((block) => !(typeof block === "object" && block !== null && block.type === "text"));
388
+ return rest.length > 0 ? rest : null;
389
+ }
390
+ /**
391
+ * A message that a SendMessage call delivered to `child` (see
392
+ * `deliveredCall`). With the call, the message has the call's id and text
393
+ * and its sender, as live, and, unless the replay already showed the call
394
+ * as a tool call, it replaces the call: the sender's view goes out at the
395
+ * call (see {@link route}). Without the call, it has its transcript id and
396
+ * the delivered text.
397
+ */
398
+ sendDelivery(child, message, text) {
399
+ const call = deliveredCall(this.sendMessages, [child.sessionId, child.record.name, child.input.name], text);
400
+ if (call)
401
+ call.recipientSessionId = child.sessionId;
402
+ const messageId = call?.toolUseId ?? message.uuid;
403
+ const linked = call !== undefined && !call.shownAsToolCall;
404
+ child.output.emitV1([
405
+ {
406
+ sessionId: child.sessionId,
407
+ update: {
408
+ sessionUpdate: "session_message",
409
+ messageId,
410
+ ...(call ? { senderSessionId: call.senderSessionId } : {}),
411
+ recipientSessionId: child.sessionId,
412
+ ...(linked ? { senderMessageId: messageId } : {}),
413
+ content: [{ type: "text", text: call?.message ?? text }],
414
+ },
415
+ },
416
+ ]);
417
+ }
418
+ sendPrompt(child, parent, text) {
419
+ child.promptSent = true;
420
+ const [outgoing, incoming] = linkedSessionMessages(child.launchId, child.parentSessionId, child.sessionId, text);
421
+ parent.emitV1([outgoing]);
422
+ child.output.emitV1([incoming]);
423
+ }
424
+ outputOf(sessionId) {
425
+ if (sessionId === this.host.sessionId)
426
+ return this.rootOutput;
427
+ return [...this.children.values()].find((child) => child.sessionId === sessionId)?.output;
428
+ }
429
+ cwdOf(sessionId) {
430
+ const child = [...this.children.values()].find((c) => c.sessionId === sessionId);
431
+ if (!child)
432
+ return this.host.cwd;
433
+ return child.cwd ?? this.cwdOf(child.parentSessionId);
434
+ }
435
+ }
436
+ /**
437
+ * How a replayed child's work ended: the state of its last task
438
+ * notification, else a stop by the user, else its foreground launch's result.
439
+ */
440
+ function endState(child) {
441
+ const end = child.notified ??
442
+ nativeSubagentState(child.record.stoppedByUser ? "cancelled" : child.launchEnd);
443
+ return end ? rfdEndState(end, undefined) : { state: "idle" };
444
+ }
445
+ function launchIdsOf(message) {
446
+ if (message.type !== "assistant")
447
+ return [];
448
+ return subagentLaunchIds(message.message?.content);
449
+ }
450
+ function contentBlocks(message) {
451
+ const content = message.message?.content;
452
+ return Array.isArray(content)
453
+ ? content.filter((block) => typeof block === "object" && block !== null)
454
+ : [];
455
+ }
456
+ function inputOf(block) {
457
+ return typeof block.input === "object" && block.input !== null
458
+ ? block.input
459
+ : {};
460
+ }
461
+ /** The text of user message content: a string, or its text blocks. */
462
+ function textOf(content) {
463
+ if (typeof content === "string")
464
+ return content;
465
+ if (!Array.isArray(content))
466
+ return "";
467
+ return content
468
+ .flatMap((block) => typeof block === "object" && block !== null && block.type === "text" ? [block.text] : [])
469
+ .filter((text) => typeof text === "string")
470
+ .join("\n");
471
+ }
472
+ function isDirectory(dir) {
473
+ try {
474
+ return fs.statSync(dir).isDirectory();
475
+ }
476
+ catch {
477
+ return false;
478
+ }
479
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * The `--hide-claude-auth` subscription guard on the v2 core: this
3
+ * integration never bills a claude.ai subscription. The policy is the v1
4
+ * core's (`hide-claude-auth.ts`):
5
+ *
6
+ * - It holds while the flag is on and no provider or gateway login routes
7
+ * the traffic away from the CLI's own login.
8
+ * - A session does not start on an account that a subscription would pay
9
+ * for (`authRequired` with the `claude_subscription_not_supported`
10
+ * reason), or that holds no credential this integration accepts
11
+ * (`authRequired`).
12
+ * - Each prompt reads the account that the query cached at its start, and is
13
+ * refused, before it is inserted, on the same terms.
14
+ * - The cached account goes stale when the user signs out or logs in
15
+ * elsewhere. A turn that fails for a missing login, or an auth status
16
+ * probe that finds another kind of identity than the session started on,
17
+ * restarts the query at the next prompt that finds the session idle (see
18
+ * `restarts.ts`), so its start judges the current account.
19
+ *
20
+ * The `/remote-control` command that the adapter runs is not guarded.
21
+ */
22
+ import type { AccountInfo, Query } from "@anthropic-ai/claude-agent-sdk";
23
+ import type { Logger } from "../acp-agent.js";
24
+ import { type AuthStatusKind } from "../auth-status.js";
25
+ /** What the guard needs of the connection's auth state (`V2Auth`). */
26
+ export interface GuardAuth {
27
+ /** Whether a provider or a gateway login routes the traffic. */
28
+ overridesRoute(): boolean;
29
+ /** Reports the account a session's query cached, as the identity. */
30
+ publishAccount(sessionId: string, account: AccountInfo): void;
31
+ }
32
+ export declare class SubscriptionGuard {
33
+ private readonly auth;
34
+ private readonly logger;
35
+ /** The session's account may have changed: restart it at its next prompt. */
36
+ private readonly accountMayHaveChanged;
37
+ private readonly sessions;
38
+ constructor(auth: GuardAuth, logger: Logger,
39
+ /** The session's account may have changed: restart it at its next prompt. */
40
+ accountMayHaveChanged: (sessionId: string) => void);
41
+ /** Whether the guard holds now (see the module doc). */
42
+ active(): boolean;
43
+ /**
44
+ * A session's query started on `account`. Throws the refusal when the
45
+ * guard holds and the account is one it refuses.
46
+ */
47
+ sessionStarted(sessionId: string, account: AccountInfo | undefined, apiKeyHelper?: string): void;
48
+ /**
49
+ * A prompt of `sessionId` is about to go to `query`: rejects with the
50
+ * refusal when the guard holds and refuses the cached account. `undefined`
51
+ * while the guard is off, so the prompt goes on in the same call.
52
+ */
53
+ beforePrompt(sessionId: string, query: Pick<Query, "accountInfo">): Promise<void> | undefined;
54
+ /** A turn of `sessionId` failed for a missing login: the user signed out. */
55
+ signedOut(sessionId: string): void;
56
+ /** An auth status probe read `kind`: a session started on another kind restarts. */
57
+ probed(kind: AuthStatusKind): void;
58
+ sessionEnded(sessionId: string): void;
59
+ }
60
+ //# sourceMappingURL=subscription-guard.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subscription-guard.d.ts","sourceRoot":"","sources":["../../src/v2/subscription-guard.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,KAAK,EAAE,MAAM,gCAAgC,CAAC;AACzE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,EAAE,KAAK,cAAc,EAAmB,MAAM,mBAAmB,CAAC;AAYzE,sEAAsE;AACtE,MAAM,WAAW,SAAS;IACxB,gEAAgE;IAChE,cAAc,IAAI,OAAO,CAAC;IAC1B,qEAAqE;IACrE,cAAc,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,GAAG,IAAI,CAAC;CAC/D;AAQD,qBAAa,iBAAiB;IAI1B,OAAO,CAAC,QAAQ,CAAC,IAAI;IACrB,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,6EAA6E;IAC7E,OAAO,CAAC,QAAQ,CAAC,qBAAqB;IANxC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAqC;gBAG3C,IAAI,EAAE,SAAS,EACf,MAAM,EAAE,MAAM;IAC/B,6EAA6E;IAC5D,qBAAqB,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,IAAI;IAGrE,wDAAwD;IACxD,MAAM,IAAI,OAAO;IAIjB;;;OAGG;IACH,cAAc,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,GAAG,SAAS,EAAE,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI;IAsBhG;;;;OAIG;IACH,YAAY,CAAC,SAAS,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,aAAa,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,GAAG,SAAS;IAc7F,6EAA6E;IAC7E,SAAS,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI;IAIlC,oFAAoF;IACpF,MAAM,CAAC,IAAI,EAAE,cAAc,GAAG,IAAI;IAQlC,YAAY,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI;CAGtC"}
@@ -0,0 +1,84 @@
1
+ import { fromAccountInfo } from "../auth-status.js";
2
+ import { billsClaudeSubscription, claudeLoginRequiredError, claudeSubscriptionNotSupportedError, holdsNonSubscriptionCredential, refuseClaudeSubscriptionTurn, shouldHideClaudeAuth, warnClaudeSubscriptionGuardDegraded, } from "../hide-claude-auth.js";
3
+ export class SubscriptionGuard {
4
+ auth;
5
+ logger;
6
+ accountMayHaveChanged;
7
+ sessions = new Map();
8
+ constructor(auth, logger,
9
+ /** The session's account may have changed: restart it at its next prompt. */
10
+ accountMayHaveChanged) {
11
+ this.auth = auth;
12
+ this.logger = logger;
13
+ this.accountMayHaveChanged = accountMayHaveChanged;
14
+ }
15
+ /** Whether the guard holds now (see the module doc). */
16
+ active() {
17
+ return shouldHideClaudeAuth() && !this.auth.overridesRoute();
18
+ }
19
+ /**
20
+ * A session's query started on `account`. Throws the refusal when the
21
+ * guard holds and the account is one it refuses.
22
+ */
23
+ sessionStarted(sessionId, account, apiKeyHelper) {
24
+ const session = {
25
+ state: {},
26
+ kind: fromAccountInfo(account, apiKeyHelper)?.kind,
27
+ };
28
+ if (this.active()) {
29
+ if (!account) {
30
+ warnClaudeSubscriptionGuardDegraded({
31
+ sessionId,
32
+ guardState: session.state,
33
+ logger: this.logger,
34
+ cause: "the CLI reported no account at initialize",
35
+ });
36
+ }
37
+ else if (billsClaudeSubscription(account)) {
38
+ throw claudeSubscriptionNotSupportedError();
39
+ }
40
+ else if (!holdsNonSubscriptionCredential(account)) {
41
+ throw claudeLoginRequiredError();
42
+ }
43
+ }
44
+ this.sessions.set(sessionId, session);
45
+ }
46
+ /**
47
+ * A prompt of `sessionId` is about to go to `query`: rejects with the
48
+ * refusal when the guard holds and refuses the cached account. `undefined`
49
+ * while the guard is off, so the prompt goes on in the same call.
50
+ */
51
+ beforePrompt(sessionId, query) {
52
+ if (!this.active())
53
+ return undefined;
54
+ let session = this.sessions.get(sessionId);
55
+ if (!session)
56
+ this.sessions.set(sessionId, (session = { state: {}, kind: undefined }));
57
+ return refuseClaudeSubscriptionTurn({
58
+ sessionId,
59
+ query,
60
+ guardState: session.state,
61
+ logger: this.logger,
62
+ // The guard reads the account anyway: it keeps the identity current.
63
+ onAccount: (account) => this.auth.publishAccount(sessionId, account),
64
+ });
65
+ }
66
+ /** A turn of `sessionId` failed for a missing login: the user signed out. */
67
+ signedOut(sessionId) {
68
+ if (shouldHideClaudeAuth())
69
+ this.accountMayHaveChanged(sessionId);
70
+ }
71
+ /** An auth status probe read `kind`: a session started on another kind restarts. */
72
+ probed(kind) {
73
+ if (!this.active())
74
+ return;
75
+ for (const [sessionId, session] of this.sessions) {
76
+ // No kind: the account said nothing that this read could contradict.
77
+ if (session.kind && session.kind !== kind)
78
+ this.accountMayHaveChanged(sessionId);
79
+ }
80
+ }
81
+ sessionEnded(sessionId) {
82
+ this.sessions.delete(sessionId);
83
+ }
84
+ }