@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
@@ -0,0 +1,507 @@
1
+ import { isReplayHiddenMetaMessage, isSyntheticLoginMessage, stripLocalCommandMetadata, } from "../message-filters.js";
2
+ import { messageIdForGrouping, streamEventToAcpNotifications, toAcpNotifications, } from "../sdk-to-acp.js";
3
+ import { isCompactSummaryMessage, replayCompactSummary } from "../context-compaction.js";
4
+ import { ClientCapabilities } from "../tool-calls/client-capabilities.js";
5
+ import { ToolCallFieldTracker } from "../tool-calls/field-tracker.js";
6
+ import { AcpToolCallRenderer, V2_CANCELLED } from "../tool-calls/renderer.js";
7
+ import { changedTaskPlanEntries, unregisterHookCallback } from "../tools.js";
8
+ import { recordStreamedDelta, unstreamedRemainder } from "../streamed-text.js";
9
+ import { replayClear } from "./update-translator.js";
10
+ /** Every v2 client gets the same tool call reports: v2 diffs and display terminals. */
11
+ const V2_TOOL_CALL_CAPABILITIES = ClientCapabilities.from(undefined, { v2: true });
12
+ /**
13
+ * The v1 capabilities the shared mapping reads. Every v2 client takes
14
+ * `plan_update` with a markdown plan, so an approved ExitPlanMode's plan
15
+ * goes out as one. Every v2 client also gets a session per subagent
16
+ * (`tasks.ts`), so a subagent's TodoWrite checklist is that session's `plan`
17
+ * rather than `plan:<parentToolUseId>` in its parent's session.
18
+ */
19
+ const V2_CLIENT_CAPABILITIES = { plan: {}, subagents: {} };
20
+ export class SessionOutput {
21
+ sessionId;
22
+ cwd;
23
+ translator;
24
+ send;
25
+ logger;
26
+ subagent;
27
+ toolUseCache = {};
28
+ emittedToolCalls = new Set();
29
+ /** What the client holds of each open tool call: an update carries only what changed. */
30
+ toolCallFields = new ToolCallFieldTracker();
31
+ streamedToolInputs = new Map();
32
+ /** The session's Task* list (TaskCreate, TaskUpdate, TaskList), sent as plan updates. */
33
+ taskState = new Map();
34
+ /** The text and thinking that streamed as deltas since the last message started or ended. */
35
+ streamedBlocks = [];
36
+ /** The id of the assistant message that is streaming. */
37
+ streamingMessageId;
38
+ /** Whether any agent text went out since {@link resetAgentText}. */
39
+ agentText = false;
40
+ /** During {@link replay}, the messages that it has cleared so far. */
41
+ replayCleared;
42
+ /** The open tool calls whose tool use reached a complete assistant message: Claude Code runs them. */
43
+ dispatched = new Set();
44
+ /**
45
+ * Whether the output comes from work that a `session/cancel` stopped, until
46
+ * its idle. The session's streamed deltas still go out,
47
+ * and of its consolidated messages only the tool results of the calls that
48
+ * the client holds, where an error result ends a run that the cancel
49
+ * aborted (`cancelled`). On the root, this covers the main conversation's
50
+ * messages. A foreground subagent's session sets it at the root's cancel,
51
+ * until its run ends (see `SessionTasks.cancelForeground`).
52
+ */
53
+ cancelled = false;
54
+ /** Whether `message` is of the work that a cancel stopped (see {@link cancelled}). */
55
+ stoppedWork(message) {
56
+ return this.cancelled && (this.subagent || message.parent_tool_use_id === null);
57
+ }
58
+ /** During {@link replay}, the replayed tool uses, apart from the live ones. */
59
+ replayToolUses;
60
+ /** During {@link replay}, what the session's subagents ask of it. */
61
+ replayHooks;
62
+ /** During {@link replay}, the replayed tool calls without a final status. */
63
+ replayUnfinished;
64
+ /** Set by the session's tasks: rewrites the live updates (see {@link OutputRoute}). */
65
+ route;
66
+ /** Set by the session around one message: rewrites its updates before {@link route}. */
67
+ rewrite;
68
+ constructor(sessionId, cwd, translator, send, logger,
69
+ /**
70
+ * Whether this is a subagent's session. Its messages keep the
71
+ * `parent_tool_use_id` of the Agent call that launched it, and its text
72
+ * streams (`forwardSubagentText`).
73
+ */
74
+ subagent = false) {
75
+ this.sessionId = sessionId;
76
+ this.cwd = cwd;
77
+ this.translator = translator;
78
+ this.send = send;
79
+ this.logger = logger;
80
+ this.subagent = subagent;
81
+ }
82
+ /** Tool updates that a hook callback sends outside the stream (an Edit's diff). */
83
+ hookClient = {
84
+ sessionUpdate: async (notification) => this.emit([notification]),
85
+ };
86
+ /** A partial assistant message: one event of the streaming API response. */
87
+ streamEvent(message) {
88
+ // A subagent's stream goes to its own session (see `tasks.ts`).
89
+ if (message.parent_tool_use_id !== null && !this.subagent)
90
+ return;
91
+ if (message.event.type === "message_start") {
92
+ this.streamingMessageId = message.event.message.id;
93
+ // A message that never reached its consolidated message, such as one an
94
+ // interrupt cut short, leaves its record behind.
95
+ this.streamedBlocks.length = 0;
96
+ }
97
+ recordStreamedDelta(this.streamedBlocks, message.event);
98
+ this.emit(streamEventToAcpNotifications(message, this.sessionId, this.toolUseCache, this.hookClient, this.logger, {
99
+ toolCallCapabilities: V2_TOOL_CALL_CAPABILITIES,
100
+ cwd: this.cwd,
101
+ emittedToolCalls: this.emittedToolCalls,
102
+ toolCallFields: this.toolCallFields,
103
+ messageId: this.streamingMessageId,
104
+ streamedToolInputs: this.streamedToolInputs,
105
+ }));
106
+ }
107
+ /**
108
+ * A consolidated assistant message. Of its text and thinking, only what did
109
+ * not stream as deltas goes out (`unstreamedRemainder`):
110
+ * the tail of a block whose stream was cut short, or the whole message when
111
+ * it never streamed (a gateway without streaming). Its tool uses then get
112
+ * their complete input. A subagent's message on the root session goes
113
+ * without its text, which belongs to the subagent's own session. After a
114
+ * cancel, the stopped work's message is dropped (see {@link cancelled}).
115
+ */
116
+ assistant(message) {
117
+ const messageId = messageIdForGrouping(message);
118
+ for (const block of message.message.content) {
119
+ if (block.type === "tool_use")
120
+ this.dispatched.add(block.id);
121
+ }
122
+ const ownText = message.parent_tool_use_id === null || this.subagent;
123
+ const content = ownText
124
+ ? unstreamedRemainder(message.message.content, this.streamedBlocks)
125
+ : message.message.content.filter((block) => block.type !== "text" && block.type !== "thinking");
126
+ if (ownText)
127
+ this.streamedBlocks.length = 0;
128
+ if (this.stoppedWork(message))
129
+ return;
130
+ this.content(content, "assistant", message.parent_tool_use_id, { messageId });
131
+ }
132
+ /**
133
+ * A user message that Claude Code adds: the results of tool uses. Its other
134
+ * blocks (command output, reminders, a prompt's echo) are not output.
135
+ * `transform` rewrites each update before it goes out, such as a background
136
+ * command's result, whose terminal keeps running.
137
+ */
138
+ toolResults(message, transform = (n) => n) {
139
+ if (!Array.isArray(message.message.content))
140
+ return;
141
+ const all = message.message.content.filter((block) => block.type === "tool_result");
142
+ // After a cancel, only the results of the calls that the client holds (see {@link cancelled}).
143
+ const results = this.stoppedWork(message)
144
+ ? all.filter((block) => this.emittedToolCalls.has(block.tool_use_id))
145
+ : all;
146
+ if (results.length === 0)
147
+ return;
148
+ this.content(results, "user", message.parent_tool_use_id, {
149
+ // `tool_use_result` describes the one result of its message.
150
+ toolUseResult: results.length === all.length ? message.tool_use_result : undefined,
151
+ toolResultMeta: message.tool_result_meta,
152
+ cancelled: this.cancelled,
153
+ }, transform);
154
+ }
155
+ /**
156
+ * Shows `content`, the exact patch of an Edit or Write, on its tool call
157
+ * before the tool runs (see `file-preview.ts`). The streamed input's diff
158
+ * does not replace the patch. A hook can come before the streamed tool_use,
159
+ * and a workflow's tools run hooks without ever streaming their use or
160
+ * result: the patch then waits for the tool call's first publication (by the
161
+ * stream or a permission request), instead of showing a tool call that would
162
+ * never end.
163
+ */
164
+ preview(toolCallId, content) {
165
+ if (!this.emittedToolCalls.has(toolCallId)) {
166
+ this.toolCallFields.stagePreview(toolCallId, content);
167
+ return;
168
+ }
169
+ const update = { sessionUpdate: "tool_call_update", toolCallId, content };
170
+ if (!this.toolCallFields.apply(update))
171
+ return;
172
+ this.toolCallFields.pinContent(toolCallId, content);
173
+ this.emit([{ sessionId: this.sessionId, update }]);
174
+ }
175
+ /** Whether the stream mapped the tool call `toolCallId`, shown or routed away. */
176
+ holds(toolCallId) {
177
+ return this.emittedToolCalls.has(toolCallId);
178
+ }
179
+ /** The tool uses of the session's tool calls, by id. */
180
+ toolUses() {
181
+ return this.toolUseCache;
182
+ }
183
+ /** Sends v1-shaped updates of the session, as the shared mapping makes them. */
184
+ emitV1(notifications) {
185
+ this.emit(notifications);
186
+ }
187
+ /**
188
+ * A tool's progress beat, on its tool call: the beat's own `tool_use_id`
189
+ * when the client holds that call, else the call it runs in
190
+ * (`parent_tool_use_id`), such as the Agent call of a subagent's tool or
191
+ * a heartbeat's derived id. A beat for a call that returned is dropped.
192
+ */
193
+ toolProgress(message) {
194
+ const toolCallId = this.emittedToolCalls.has(message.tool_use_id)
195
+ ? message.tool_use_id
196
+ : message.parent_tool_use_id;
197
+ if (toolCallId === null || !this.emittedToolCalls.has(toolCallId))
198
+ return;
199
+ // A subagent's beat, on its own session, names the Agent call that runs
200
+ // it. A tool call is never its own parent.
201
+ const parentToolUseId = this.subagent && message.parent_tool_use_id !== toolCallId
202
+ ? (message.parent_tool_use_id ?? undefined)
203
+ : undefined;
204
+ const beat = new AcpToolCallRenderer(V2_TOOL_CALL_CAPABILITIES).progress({
205
+ toolCallId,
206
+ toolName: message.tool_name,
207
+ parentToolUseId,
208
+ elapsedTimeSeconds: message.elapsed_time_seconds,
209
+ subagentType: message.subagent_type,
210
+ subagentRetry: message.subagent_retry,
211
+ });
212
+ if (this.toolCallFields.apply(beat))
213
+ this.emit([{ sessionId: this.sessionId, update: beat }]);
214
+ }
215
+ /** Claude Code recalled memories: a completed read tool call. */
216
+ memoryRecall(message) {
217
+ this.emit([
218
+ {
219
+ sessionId: this.sessionId,
220
+ update: new AcpToolCallRenderer(V2_TOOL_CALL_CAPABILITIES).memoryRecall(message),
221
+ },
222
+ ]);
223
+ }
224
+ /** The Task* list changed outside a tool result (the TaskCreated and TaskCompleted hooks). */
225
+ taskPlanChanged() {
226
+ const entries = changedTaskPlanEntries(this.taskState, false);
227
+ if (entries)
228
+ this.emit([{ sessionId: this.sessionId, update: { sessionUpdate: "plan", entries } }]);
229
+ }
230
+ /**
231
+ * The tool call of a permission request that the stream never shows, such
232
+ * as SandboxNetworkAccess's, before the request: the client holds it, and
233
+ * {@link toolCallStatus} ends it once the request is answered, as on v1
234
+ * (`ensureToolCallEmitted`).
235
+ */
236
+ permissionToolCall(toolName, toolCallId, input) {
237
+ if (this.emittedToolCalls.has(toolCallId))
238
+ return;
239
+ this.emittedToolCalls.add(toolCallId);
240
+ const update = new AcpToolCallRenderer(V2_TOOL_CALL_CAPABILITIES).toolCall({ id: toolCallId, name: toolName, input }, { cwd: this.cwd });
241
+ this.toolCallFields.apply(update);
242
+ this.emit([{ sessionId: this.sessionId, update }]);
243
+ }
244
+ /**
245
+ * The tool call that the adapter starts for a background task that no tool
246
+ * call stands for (see `SessionTasks.adoptTasks`). It ends with the task.
247
+ */
248
+ taskToolCall(update) {
249
+ this.emittedToolCalls.add(update.toolCallId);
250
+ this.toolCallFields.apply(update);
251
+ this.emit([{ sessionId: this.sessionId, update }]);
252
+ }
253
+ /** A workflow's latest progress on its tool call, as its title and body (`workflowCard`). */
254
+ taskToolCallProgress(toolCallId, card) {
255
+ this.emit([
256
+ {
257
+ sessionId: this.sessionId,
258
+ update: { sessionUpdate: "tool_call_update", toolCallId, ...card },
259
+ },
260
+ ]);
261
+ }
262
+ /**
263
+ * Claude Code denied a tool use without asking (a rule, the classifier or
264
+ * the mode): its tool call fails with the reason. A tool
265
+ * call that the client does not hold, such as dropped work's, is left out.
266
+ */
267
+ permissionDenied(message, parentToolUseId) {
268
+ // Its PostToolUse hook never runs.
269
+ unregisterHookCallback(message.tool_use_id);
270
+ if (!this.emittedToolCalls.has(message.tool_use_id))
271
+ return;
272
+ const denied = new AcpToolCallRenderer(V2_TOOL_CALL_CAPABILITIES).permissionDenied({
273
+ toolCallId: message.tool_use_id,
274
+ toolName: message.tool_name,
275
+ ...(parentToolUseId !== undefined ? { parentToolUseId } : {}),
276
+ decisionReasonType: message.decision_reason_type,
277
+ decisionReason: message.decision_reason,
278
+ message: message.message,
279
+ });
280
+ // A denial is final, so it replaces a pinned approval patch.
281
+ if (this.toolCallFields.apply(denied, { replacePinnedContent: true })) {
282
+ this.emit([{ sessionId: this.sessionId, update: denied }]);
283
+ }
284
+ }
285
+ /** Sets the status of a tool call, such as a background task's when it ends. */
286
+ toolCallStatus(toolCallId, status) {
287
+ if (FINAL_STATUSES.has(status))
288
+ this.unfinished.delete(toolCallId);
289
+ this.send({ sessionUpdate: "tool_call_update", toolCallId, status });
290
+ }
291
+ /**
292
+ * Replays the stored history of the session: its prompts, Claude's
293
+ * messages and its tool calls, as the live session sent them. Subagent
294
+ * transcripts are left out, as live. The client may hold the replayed
295
+ * messages already, so each message is cleared before its first chunk.
296
+ * `hooks` replays the subagents' own histories to their sessions.
297
+ *
298
+ * A replayed tool call that the history gives no result, such as one that
299
+ * ran when Claude Code was killed, ends `failed` after the replay, as v2
300
+ * asks of replayed work that no longer runs. The calls that the live
301
+ * session holds open, and those in `live` (its background work), go on.
302
+ * `running` rewrites the replayed results of that background work as live,
303
+ * so that they do not end it (see `SessionTasks.replayedBackground`).
304
+ */
305
+ replay(messages, hooks, live = new Set(), running) {
306
+ this.replayCleared = new Set();
307
+ this.replayHooks = hooks;
308
+ const unfinished = (this.replayUnfinished = new Set());
309
+ try {
310
+ for (const message of messages) {
311
+ if (message.parent_tool_use_id !== null || isReplayHiddenMetaMessage(message))
312
+ continue;
313
+ // Claude Code's sign-in message, which the live session did not show either.
314
+ if (message.type === "assistant" && isSyntheticLoginMessage(message.message))
315
+ continue;
316
+ // A compaction's summary message replays as the completed compaction.
317
+ // `emit` sends at once, before the call returns, so the update keeps
318
+ // its place among the replayed messages.
319
+ if (isCompactSummaryMessage(message) && message.uuid) {
320
+ void replayCompactSummary(message, async (n) => this.emit([n]), {
321
+ sessionId: this.sessionId,
322
+ });
323
+ continue;
324
+ }
325
+ hooks?.replaying?.(message);
326
+ const inner = message.message;
327
+ if (message.type === "assistant" && Array.isArray(inner.content)) {
328
+ this.content(inner.content, "assistant", null, {
329
+ messageId: inner.id ?? message.uuid,
330
+ replay: true,
331
+ });
332
+ }
333
+ else if (message.type === "user" && inner.content !== undefined) {
334
+ // `null`: the message was command metadata alone.
335
+ let content = stripLocalCommandMetadata(inner.content);
336
+ if (content !== null && hooks?.userContent)
337
+ content = hooks.userContent(message, content);
338
+ if (content === null)
339
+ continue;
340
+ this.content(content, "user", null, { messageId: message.uuid, replay: true }, running);
341
+ }
342
+ hooks?.replayed(message);
343
+ }
344
+ }
345
+ finally {
346
+ this.replayCleared = undefined;
347
+ this.replayToolUses = undefined;
348
+ this.replayHooks = undefined;
349
+ this.replayUnfinished = undefined;
350
+ }
351
+ for (const toolCallId of unfinished) {
352
+ if (this.unfinished.has(toolCallId) || live.has(toolCallId))
353
+ continue;
354
+ this.send({ sessionUpdate: "tool_call_update", toolCallId, status: "failed" });
355
+ }
356
+ }
357
+ /** Agent text that is not a model message, such as a local command's result. */
358
+ agentMessage(text, messageId) {
359
+ this.content(text, "assistant", null, { messageId });
360
+ }
361
+ /**
362
+ * A user message that this session did not send, such as one typed in
363
+ * another client over Remote Control: rendered as a replayed one is,
364
+ * without its command metadata.
365
+ */
366
+ userMessage(content, messageId) {
367
+ const shown = stripLocalCommandMetadata(content);
368
+ if (shown !== null)
369
+ this.content(shown, "user", null, { messageId });
370
+ }
371
+ /** Whether agent text went out since the last {@link resetAgentText}. */
372
+ hasAgentText() {
373
+ return this.agentText;
374
+ }
375
+ resetAgentText() {
376
+ this.agentText = false;
377
+ }
378
+ content(content, role, parentToolUseId, options, transform = (n) => n) {
379
+ // A replay renders the history on its own: each
380
+ // replayed tool call goes out whole, whatever the live session sent.
381
+ const live = !options.replay;
382
+ this.emit(toAcpNotifications(content, role, this.sessionId, live ? this.toolUseCache : (this.replayToolUses ??= {}), this.hookClient, this.logger, {
383
+ clientCapabilities: V2_CLIENT_CAPABILITIES,
384
+ toolCallCapabilities: V2_TOOL_CALL_CAPABILITIES,
385
+ cwd: this.cwd,
386
+ ...(live
387
+ ? { emittedToolCalls: this.emittedToolCalls, toolCallFields: this.toolCallFields }
388
+ : {}),
389
+ taskState: this.taskState,
390
+ parentToolUseId,
391
+ // A replayed tool use runs no hook that could report its result.
392
+ registerHooks: !options.replay,
393
+ ...options,
394
+ }).map(transform));
395
+ }
396
+ /**
397
+ * Gives each tool call that has no final status yet the final `status`,
398
+ * except those in `keep` (background work, which goes on). For the end of
399
+ * stopped work: v2 asks for a final status of its tool calls before the idle.
400
+ * With `exitTerminals`, a command's terminal exits with its call, with no
401
+ * exit code. Returns the ids of the calls it ended.
402
+ */
403
+ finishUnfinished(status, keep = new Set(), { exitTerminals = false } = {}) {
404
+ const finished = [];
405
+ for (const toolCallId of [...this.unfinished]) {
406
+ if (keep.has(toolCallId))
407
+ continue;
408
+ this.unfinished.delete(toolCallId);
409
+ finished.push(toolCallId);
410
+ if (!exitTerminals) {
411
+ this.send({ sessionUpdate: "tool_call_update", toolCallId, status });
412
+ continue;
413
+ }
414
+ // The translator ignores `terminal_exit` for a call without a terminal.
415
+ this.emit([
416
+ {
417
+ sessionId: this.sessionId,
418
+ update: {
419
+ sessionUpdate: "tool_call_update",
420
+ toolCallId,
421
+ status: status === "cancelled" ? V2_CANCELLED : status,
422
+ _meta: { terminal_exit: { terminal_id: toolCallId, exit_code: null, signal: null } },
423
+ },
424
+ },
425
+ ]);
426
+ }
427
+ return finished;
428
+ }
429
+ /**
430
+ * Ends the open tool calls that will get no result, for the end of the work
431
+ * (see `AcpToolCallRenderer.unfinished`), before its idle. After a cancel
432
+ * (`stopped`), every open call ends `cancelled`. Otherwise only the calls
433
+ * that Claude dropped before they ran end, `cancelled` too: a streamed
434
+ * tool_use that no complete message holds. A call that runs, such as one in
435
+ * the background, gets Claude Code's result. A command's report also ends
436
+ * its terminal. The call is forgotten, so a late result changes nothing.
437
+ * The calls in `keep` stay open, such as one whose task runs in the background.
438
+ */
439
+ closeUnfinished(stopped, keep = new Set()) {
440
+ const renderer = new AcpToolCallRenderer(V2_TOOL_CALL_CAPABILITIES);
441
+ for (const toolCallId of [...this.unfinished]) {
442
+ if (keep.has(toolCallId))
443
+ continue;
444
+ const ran = this.dispatched.has(toolCallId);
445
+ if (ran && !stopped)
446
+ continue;
447
+ const report = renderer.unfinished({ toolCallId, ran, cancelled: stopped });
448
+ const toolUse = this.toolUseCache[toolCallId];
449
+ const terminalExit = toolUse && renderer.terminalExit(toolUse);
450
+ if (terminalExit)
451
+ report._meta = { ...report._meta, ...terminalExit };
452
+ this.emittedToolCalls.delete(toolCallId);
453
+ delete this.toolUseCache[toolCallId];
454
+ this.toolCallFields.delete(toolCallId);
455
+ this.emit([{ sessionId: this.sessionId, update: report }]);
456
+ }
457
+ }
458
+ /** The tool calls that the client holds without a final status. */
459
+ unfinished = new Set();
460
+ /** Called with each live agent text chunk, for the session's title. */
461
+ onAgentText;
462
+ emit(notifications) {
463
+ // A replay routes only what its hooks ask: the live routing tracks live calls.
464
+ const route = this.replayCleared !== undefined ? this.replayHooks?.route : this.route;
465
+ // Each update is routed once the ones before it went out: a route can
466
+ // send updates of its own, such as a child's announcement or a
467
+ // hand-back's two messages, which then keep their place.
468
+ for (const original of notifications) {
469
+ const notification = this.rewrite ? this.rewrite(original) : original;
470
+ for (const { update } of route ? route(notification) : [notification])
471
+ this.sendOne(update);
472
+ }
473
+ }
474
+ sendOne(update) {
475
+ const replaying = this.replayCleared !== undefined;
476
+ if (update.sessionUpdate === "agent_message_chunk") {
477
+ this.agentText = true;
478
+ if (!replaying)
479
+ this.onAgentText?.(update.content);
480
+ }
481
+ for (const v2Update of this.translator.updates(this.sessionId, update, replaying)) {
482
+ const clear = this.replayCleared && replayClear(this.replayCleared, v2Update);
483
+ if (clear)
484
+ this.send(clear);
485
+ if (v2Update.sessionUpdate === "tool_call_update") {
486
+ const { toolCallId, status } = v2Update;
487
+ if (status != null && replaying) {
488
+ if (FINAL_STATUSES.has(status))
489
+ this.replayUnfinished?.delete(toolCallId);
490
+ else
491
+ this.replayUnfinished?.add(toolCallId);
492
+ }
493
+ else if (status != null) {
494
+ if (FINAL_STATUSES.has(status)) {
495
+ this.unfinished.delete(toolCallId);
496
+ this.dispatched.delete(toolCallId);
497
+ }
498
+ else {
499
+ this.unfinished.add(toolCallId);
500
+ }
501
+ }
502
+ }
503
+ this.send(v2Update);
504
+ }
505
+ }
506
+ }
507
+ const FINAL_STATUSES = new Set(["completed", "failed", "cancelled"]);
@@ -0,0 +1,115 @@
1
+ import type * as v2 from "@agentclientprotocol/sdk/experimental/v2/unstable";
2
+ import type { SessionConfigOption } from "@agentclientprotocol/sdk/unstable";
3
+ import type { SessionMessage } from "@anthropic-ai/claude-agent-sdk";
4
+ import type { Logger } from "../logger.js";
5
+ import { type SubagentModels } from "../native-subagents.js";
6
+ import type { V2UpdateTranslator } from "./update-translator.js";
7
+ import { SessionOutput, type ReplayHooks } from "./stream.js";
8
+ /** What the replay needs of its root session. */
9
+ export interface ReplayHost {
10
+ readonly sessionId: string;
11
+ readonly cwd: string;
12
+ readonly logger: Logger;
13
+ readonly translator: V2UpdateTranslator;
14
+ /** Sends an update of the root session or one of its children. */
15
+ send(notification: v2.UpdateSessionNotification): void;
16
+ models(): SubagentModels;
17
+ }
18
+ /** What the live session knows of the replayed children. */
19
+ export interface LiveChildren {
20
+ /** Whether the live session tracks the child session `sessionId`. */
21
+ tracks(sessionId: string): boolean;
22
+ /** The configuration that the client last got for the live child `sessionId`, if any. */
23
+ configuration(sessionId: string): SessionConfigOption[] | undefined;
24
+ }
25
+ export declare class SubagentReplay {
26
+ private readonly host;
27
+ private readonly history;
28
+ /** The transcript of each child, by agent id. */
29
+ private readonly transcripts;
30
+ private readonly live;
31
+ /** The children, by the id of the call that launched each. */
32
+ private readonly children;
33
+ private readonly sendMessages;
34
+ /** The SubagentHandback calls, with their report and whether their result failed. */
35
+ private readonly handbacks;
36
+ /** Launches without metadata, which the replay leaves out. */
37
+ private readonly omitted;
38
+ /** Children whose transcript could not be read: only their association is replayed. */
39
+ private withoutHistory;
40
+ private rootOutput;
41
+ private constructor();
42
+ /**
43
+ * Reads the subagent history that `messages`, the session's transcript,
44
+ * launched, with every child's transcript. Undefined when it launched none.
45
+ */
46
+ static load(host: ReplayHost, messages: SessionMessage[], live?: LiveChildren): Promise<SubagentReplay | undefined>;
47
+ /** The hooks of the replay of the root session's history (`messages`). */
48
+ hooks(output: SessionOutput, messages: SessionMessage[]): ReplayHooks;
49
+ /**
50
+ * Ends the replay: every child's end, on its parent, then once on its own
51
+ * stream, and the notice when subagent history is missing.
52
+ */
53
+ finish(): void;
54
+ /**
55
+ * After the response, as the v1 core sends them (`currentStates`): the
56
+ * current state of each replayed child that the live session does not
57
+ * track, since its process is gone, so its replayed end. A `cwd` that is
58
+ * gone, such as a worktree that Claude Code removed, is cleared. Then each
59
+ * replayed child's configuration, when it is not the `model` that the
60
+ * replay sent: the live child's, else the model of its latest response, by
61
+ * the session's model list.
62
+ */
63
+ afterResponse(): void;
64
+ private sendConfiguration;
65
+ private sendEndState;
66
+ private ownerHooks;
67
+ /**
68
+ * Registers the launches, the launch results, the SendMessage calls and the
69
+ * SubagentHandback calls in `messages`, of the session `ownerSessionId`.
70
+ */
71
+ private scan;
72
+ private registerLaunch;
73
+ /**
74
+ * A replayed update of a tool call of `output`, the session of `owner`
75
+ * when it is a child's. The client is not shown the launch of a replayed
76
+ * child, a SendMessage call whose message the replay delivered, or a
77
+ * successful SubagentHandback call: a foreground launch's completed result
78
+ * goes out as the child's reply, a delivered SendMessage as the sender's
79
+ * outgoing message, and a hand-back as the child's message to its parent.
80
+ */
81
+ private route;
82
+ /**
83
+ * Before a message of `owner`'s history (the root's when undefined): a
84
+ * child's response with another model sends its `model` again, and a
85
+ * persisted task notification of a child is the state its work ended in.
86
+ */
87
+ private replaying;
88
+ /** After a message that launched children: each is announced, and its history replays. */
89
+ private replayed;
90
+ private announce;
91
+ /** The `model` of a response of `child`, when it is not the one the client holds. */
92
+ private sendModel;
93
+ /**
94
+ * The rest of a child's user message to replay, or `null` when nothing is
95
+ * left, after its text went out as the child's incoming `session_message`.
96
+ * The first text is the prompt of the launch. A message that a SendMessage
97
+ * call delivered (`origin.kind: "coordinator"`) is another incoming
98
+ * message. Any other text is Claude Code's, such as "[Request interrupted
99
+ * by user]", which the live child session does not show. Tool results stay.
100
+ */
101
+ private childContent;
102
+ /**
103
+ * A message that a SendMessage call delivered to `child` (see
104
+ * `deliveredCall`). With the call, the message has the call's id and text
105
+ * and its sender, as live, and, unless the replay already showed the call
106
+ * as a tool call, it replaces the call: the sender's view goes out at the
107
+ * call (see {@link route}). Without the call, it has its transcript id and
108
+ * the delivered text.
109
+ */
110
+ private sendDelivery;
111
+ private sendPrompt;
112
+ private outputOf;
113
+ private cwdOf;
114
+ }
115
+ //# sourceMappingURL=subagent-replay.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subagent-replay.d.ts","sourceRoot":"","sources":["../../src/v2/subagent-replay.ts"],"names":[],"mappings":"AAsCA,OAAO,KAAK,KAAK,EAAE,MAAM,mDAAmD,CAAC;AAC7E,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,mCAAmC,CAAC;AAC7E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAE3C,OAAO,EAYL,KAAK,cAAc,EAEpB,MAAM,wBAAwB,CAAC;AAgBhC,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,EAAE,aAAa,EAAE,KAAK,WAAW,EAAE,MAAM,aAAa,CAAC;AAG9D,iDAAiD;AACjD,MAAM,WAAW,UAAU;IACzB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,UAAU,EAAE,kBAAkB,CAAC;IACxC,kEAAkE;IAClE,IAAI,CAAC,YAAY,EAAE,EAAE,CAAC,yBAAyB,GAAG,IAAI,CAAC;IACvD,MAAM,IAAI,cAAc,CAAC;CAC1B;AAED,4DAA4D;AAC5D,MAAM,WAAW,YAAY;IAC3B,qEAAqE;IACrE,MAAM,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC;IACnC,yFAAyF;IACzF,aAAa,CAAC,SAAS,EAAE,MAAM,GAAG,mBAAmB,EAAE,GAAG,SAAS,CAAC;CACrE;AAwCD,qBAAa,cAAc;IAgBvB,OAAO,CAAC,QAAQ,CAAC,IAAI;IACrB,OAAO,CAAC,QAAQ,CAAC,OAAO;IACxB,iDAAiD;IACjD,OAAO,CAAC,QAAQ,CAAC,WAAW;IAC5B,OAAO,CAAC,QAAQ,CAAC,IAAI;IAnBvB,8DAA8D;IAC9D,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAkC;IAC3D,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAyB;IACtD,qFAAqF;IACrF,OAAO,CAAC,QAAQ,CAAC,SAAS,CAGtB;IACJ,8DAA8D;IAC9D,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAqB;IAC7C,uFAAuF;IACvF,OAAO,CAAC,cAAc,CAAK;IAC3B,OAAO,CAAC,UAAU,CAA4B;IAE9C,OAAO;IAQP;;;OAGG;WACU,IAAI,CACf,IAAI,EAAE,UAAU,EAChB,QAAQ,EAAE,cAAc,EAAE,EAC1B,IAAI,GAAE,YAA+B,GACpC,OAAO,CAAC,cAAc,GAAG,SAAS,CAAC;IAiBtC,0EAA0E;IAC1E,KAAK,CAAC,MAAM,EAAE,aAAa,EAAE,QAAQ,EAAE,cAAc,EAAE,GAAG,WAAW;IAMrE;;;OAGG;IACH,MAAM,IAAI,IAAI;IA0Bd;;;;;;;;OAQG;IACH,aAAa,IAAI,IAAI;IAQrB,OAAO,CAAC,iBAAiB;IAczB,OAAO,CAAC,YAAY;IAiBpB,OAAO,CAAC,UAAU;IAWlB;;;OAGG;IACH,OAAO,CAAC,IAAI;IAmCZ,OAAO,CAAC,cAAc;IAsBtB;;;;;;;OAOG;IACH,OAAO,CAAC,KAAK;IAuDb;;;;OAIG;IACH,OAAO,CAAC,SAAS;IAYjB,0FAA0F;IAC1F,OAAO,CAAC,QAAQ;IAiBhB,OAAO,CAAC,QAAQ;IAiChB,qFAAqF;IACrF,OAAO,CAAC,SAAS;IAcjB;;;;;;;OAOG;IACH,OAAO,CAAC,YAAY;IAgBpB;;;;;;;OAOG;IACH,OAAO,CAAC,YAAY;IAwBpB,OAAO,CAAC,UAAU;IAYlB,OAAO,CAAC,QAAQ;IAKhB,OAAO,CAAC,KAAK;CAKd"}