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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (203) hide show
  1. package/README.md +5 -1
  2. package/dist/acp-agent.d.ts +113 -439
  3. package/dist/acp-agent.d.ts.map +1 -1
  4. package/dist/acp-agent.js +362 -2409
  5. package/dist/acp-subagents.d.ts +1 -2
  6. package/dist/acp-subagents.d.ts.map +1 -1
  7. package/dist/auth-methods.d.ts +21 -0
  8. package/dist/auth-methods.d.ts.map +1 -0
  9. package/dist/auth-methods.js +68 -0
  10. package/dist/auth-status-reporter.d.ts +112 -0
  11. package/dist/auth-status-reporter.d.ts.map +1 -0
  12. package/dist/auth-status-reporter.js +253 -0
  13. package/dist/background-work.d.ts +12 -265
  14. package/dist/background-work.d.ts.map +1 -1
  15. package/dist/background-work.js +8 -558
  16. package/dist/client-system-prompt.d.ts +7 -0
  17. package/dist/client-system-prompt.d.ts.map +1 -1
  18. package/dist/client-system-prompt.js +24 -0
  19. package/dist/context-compaction.d.ts +20 -0
  20. package/dist/context-compaction.d.ts.map +1 -1
  21. package/dist/context-compaction.js +26 -0
  22. package/dist/context-window.d.ts +70 -0
  23. package/dist/context-window.d.ts.map +1 -0
  24. package/dist/context-window.js +132 -0
  25. package/dist/diff.d.ts +1 -1
  26. package/dist/diff.js +1 -1
  27. package/dist/elicitation.d.ts +66 -1
  28. package/dist/elicitation.d.ts.map +1 -1
  29. package/dist/elicitation.js +109 -0
  30. package/dist/file-change-audit.d.ts +4 -3
  31. package/dist/file-change-audit.d.ts.map +1 -1
  32. package/dist/file-change-audit.js +3 -2
  33. package/dist/mcp-oauth.d.ts +44 -0
  34. package/dist/mcp-oauth.d.ts.map +1 -0
  35. package/dist/mcp-oauth.js +142 -0
  36. package/dist/mcp-servers.d.ts +10 -0
  37. package/dist/mcp-servers.d.ts.map +1 -0
  38. package/dist/mcp-servers.js +29 -0
  39. package/dist/native-subagents.d.ts +18 -8
  40. package/dist/native-subagents.d.ts.map +1 -1
  41. package/dist/native-subagents.js +7 -35
  42. package/dist/permissions/presentation.d.ts +29 -0
  43. package/dist/permissions/presentation.d.ts.map +1 -1
  44. package/dist/permissions/presentation.js +38 -11
  45. package/dist/prompt-suggestions.d.ts +29 -0
  46. package/dist/prompt-suggestions.d.ts.map +1 -1
  47. package/dist/prompt-suggestions.js +45 -0
  48. package/dist/providers.d.ts +139 -0
  49. package/dist/providers.d.ts.map +1 -0
  50. package/dist/providers.js +286 -0
  51. package/dist/remote-control.d.ts +62 -0
  52. package/dist/remote-control.d.ts.map +1 -0
  53. package/dist/remote-control.js +78 -0
  54. package/dist/result-end.d.ts +39 -0
  55. package/dist/result-end.d.ts.map +1 -0
  56. package/dist/result-end.js +50 -0
  57. package/dist/serve.d.ts +7 -2
  58. package/dist/serve.d.ts.map +1 -1
  59. package/dist/serve.js +10 -5
  60. package/dist/session-config-ids.d.ts +1 -0
  61. package/dist/session-config-ids.d.ts.map +1 -1
  62. package/dist/session-config-ids.js +1 -0
  63. package/dist/session-config-options.d.ts +64 -0
  64. package/dist/session-config-options.d.ts.map +1 -0
  65. package/dist/session-config-options.js +162 -0
  66. package/dist/session-effort.d.ts +67 -0
  67. package/dist/session-effort.d.ts.map +1 -1
  68. package/dist/session-effort.js +98 -0
  69. package/dist/session-env.d.ts +22 -0
  70. package/dist/session-env.d.ts.map +1 -0
  71. package/dist/session-env.js +66 -0
  72. package/dist/session-fast-mode.d.ts +83 -0
  73. package/dist/session-fast-mode.d.ts.map +1 -0
  74. package/dist/session-fast-mode.js +142 -0
  75. package/dist/session-index/connection.d.ts +2 -5
  76. package/dist/session-index/connection.d.ts.map +1 -1
  77. package/dist/session-index/connection.js +3 -5
  78. package/dist/session-mode.d.ts +1 -0
  79. package/dist/session-mode.d.ts.map +1 -1
  80. package/dist/session-mode.js +1 -1
  81. package/dist/session-model.d.ts +41 -0
  82. package/dist/session-model.d.ts.map +1 -1
  83. package/dist/session-model.js +110 -45
  84. package/dist/session-notices.d.ts +44 -0
  85. package/dist/session-notices.d.ts.map +1 -1
  86. package/dist/session-notices.js +68 -0
  87. package/dist/session-titles.d.ts +34 -12
  88. package/dist/session-titles.d.ts.map +1 -1
  89. package/dist/session-titles.js +7 -6
  90. package/dist/session-usage.d.ts +125 -0
  91. package/dist/session-usage.d.ts.map +1 -0
  92. package/dist/session-usage.js +196 -0
  93. package/dist/streamed-text.d.ts +33 -0
  94. package/dist/streamed-text.d.ts.map +1 -0
  95. package/dist/streamed-text.js +71 -0
  96. package/dist/subagent-configuration.d.ts +32 -0
  97. package/dist/subagent-configuration.d.ts.map +1 -0
  98. package/dist/subagent-configuration.js +70 -0
  99. package/dist/subagent-replay.d.ts +18 -0
  100. package/dist/subagent-replay.d.ts.map +1 -1
  101. package/dist/subagent-replay.js +25 -15
  102. package/dist/tool-calls/client-capabilities.d.ts +8 -8
  103. package/dist/tool-calls/client-capabilities.js +4 -4
  104. package/dist/tool-calls/renderer.d.ts +4 -5
  105. package/dist/tool-calls/renderer.d.ts.map +1 -1
  106. package/dist/tool-calls/renderer.js +4 -5
  107. package/dist/turn-events.d.ts +6 -46
  108. package/dist/turn-events.d.ts.map +1 -1
  109. package/dist/v2/agent.d.ts +7 -11
  110. package/dist/v2/agent.d.ts.map +1 -1
  111. package/dist/v2/agent.js +751 -331
  112. package/dist/v2/air.d.ts +33 -0
  113. package/dist/v2/air.d.ts.map +1 -0
  114. package/dist/v2/air.js +29 -0
  115. package/dist/v2/auth.d.ts +97 -0
  116. package/dist/v2/auth.d.ts.map +1 -0
  117. package/dist/v2/auth.js +216 -0
  118. package/dist/v2/background.d.ts +27 -16
  119. package/dist/v2/background.d.ts.map +1 -1
  120. package/dist/v2/background.js +4 -32
  121. package/dist/v2/child-config.d.ts +55 -0
  122. package/dist/v2/child-config.d.ts.map +1 -0
  123. package/dist/v2/child-config.js +92 -0
  124. package/dist/v2/clear-context.d.ts +94 -0
  125. package/dist/v2/clear-context.d.ts.map +1 -0
  126. package/dist/v2/clear-context.js +176 -0
  127. package/dist/v2/commands.d.ts +46 -0
  128. package/dist/v2/commands.d.ts.map +1 -0
  129. package/dist/v2/commands.js +54 -0
  130. package/dist/v2/config.d.ts +187 -0
  131. package/dist/v2/config.d.ts.map +1 -0
  132. package/dist/v2/config.js +494 -0
  133. package/dist/v2/elicitation.d.ts +93 -0
  134. package/dist/v2/elicitation.d.ts.map +1 -0
  135. package/dist/v2/elicitation.js +160 -0
  136. package/dist/v2/file-changes.d.ts +61 -0
  137. package/dist/v2/file-changes.d.ts.map +1 -0
  138. package/dist/v2/file-changes.js +108 -0
  139. package/dist/v2/file-preview.d.ts +18 -0
  140. package/dist/v2/file-preview.d.ts.map +1 -0
  141. package/dist/v2/file-preview.js +29 -0
  142. package/dist/v2/initialize.d.ts +10 -24
  143. package/dist/v2/initialize.d.ts.map +1 -1
  144. package/dist/v2/initialize.js +4 -111
  145. package/dist/v2/outcome.d.ts +81 -0
  146. package/dist/v2/outcome.d.ts.map +1 -0
  147. package/dist/v2/outcome.js +165 -0
  148. package/dist/v2/permissions.d.ts +92 -0
  149. package/dist/v2/permissions.d.ts.map +1 -0
  150. package/dist/v2/permissions.js +162 -0
  151. package/dist/v2/prompt.d.ts +2 -42
  152. package/dist/v2/prompt.d.ts.map +1 -1
  153. package/dist/v2/prompt.js +2 -119
  154. package/dist/v2/remote-control.d.ts +41 -0
  155. package/dist/v2/remote-control.d.ts.map +1 -0
  156. package/dist/v2/remote-control.js +63 -0
  157. package/dist/v2/reports.d.ts +198 -0
  158. package/dist/v2/reports.d.ts.map +1 -0
  159. package/dist/v2/reports.js +487 -0
  160. package/dist/v2/restarts.d.ts +128 -0
  161. package/dist/v2/restarts.d.ts.map +1 -0
  162. package/dist/v2/restarts.js +348 -0
  163. package/dist/v2/session-requests.d.ts +20 -0
  164. package/dist/v2/session-requests.d.ts.map +1 -0
  165. package/dist/v2/session-requests.js +108 -0
  166. package/dist/v2/session-update.d.ts +2 -13
  167. package/dist/v2/session-update.d.ts.map +1 -1
  168. package/dist/v2/session-update.js +2 -22
  169. package/dist/v2/session.d.ts +340 -41
  170. package/dist/v2/session.d.ts.map +1 -1
  171. package/dist/v2/session.js +1223 -141
  172. package/dist/v2/setup.d.ts +49 -0
  173. package/dist/v2/setup.d.ts.map +1 -0
  174. package/dist/v2/setup.js +62 -0
  175. package/dist/v2/stopped-work.d.ts +123 -0
  176. package/dist/v2/stopped-work.d.ts.map +1 -0
  177. package/dist/v2/stopped-work.js +210 -0
  178. package/dist/v2/stream.d.ts +228 -0
  179. package/dist/v2/stream.d.ts.map +1 -0
  180. package/dist/v2/stream.js +506 -0
  181. package/dist/v2/subagent-replay.d.ts +115 -0
  182. package/dist/v2/subagent-replay.d.ts.map +1 -0
  183. package/dist/v2/subagent-replay.js +479 -0
  184. package/dist/v2/subscription-guard.d.ts +60 -0
  185. package/dist/v2/subscription-guard.d.ts.map +1 -0
  186. package/dist/v2/subscription-guard.js +84 -0
  187. package/dist/v2/tasks.d.ts +492 -0
  188. package/dist/v2/tasks.d.ts.map +1 -0
  189. package/dist/v2/tasks.js +1728 -0
  190. package/dist/v2/terminal.d.ts.map +1 -1
  191. package/dist/v2/terminal.js +6 -1
  192. package/dist/v2/tool-call.d.ts +3 -2
  193. package/dist/v2/tool-call.d.ts.map +1 -1
  194. package/dist/v2/update-translator.d.ts +36 -0
  195. package/dist/v2/update-translator.d.ts.map +1 -0
  196. package/dist/v2/update-translator.js +80 -0
  197. package/dist/workflow-progress.d.ts +23 -0
  198. package/dist/workflow-progress.d.ts.map +1 -1
  199. package/dist/workflow-progress.js +31 -8
  200. package/package.json +1 -1
  201. package/dist/v2/permission.d.ts +0 -28
  202. package/dist/v2/permission.d.ts.map +0 -1
  203. package/dist/v2/permission.js +0 -41
@@ -0,0 +1,487 @@
1
+ import { ContextCompactionLifecycle, contextCompactionMetadataFromBoundary, } from "../context-compaction.js";
2
+ import { cacheResultContextWindow, immediateContextWindow, providerCacheKeyFor, readContextWindow, } from "../context-window.js";
3
+ import { IdleCompaction } from "../idle-compaction.js";
4
+ import { PromptSuggestions } from "../prompt-suggestions.js";
5
+ import { informationalNotice, mcpServerStartupNotice, normalizeNoticeText, noticeUpdate, } from "../session-notices.js";
6
+ import { DEFAULT_CONTEXT_WINDOW, getMatchingModelUsage, inferContextWindowFromModel, snapshotFromUsage, totalTokens, ZERO_USAGE, } from "../session-usage.js";
7
+ import { SessionTitles } from "../session-titles.js";
8
+ import { createTaskHook } from "../tools.js";
9
+ export class SessionReports {
10
+ host;
11
+ titles;
12
+ compaction;
13
+ idleCompaction;
14
+ settings;
15
+ clientMcpServers = new Set();
16
+ mcpOAuth = false;
17
+ reportedMcpServers = new Set();
18
+ /** The tool uses whose `informational` progress went out as a notice. */
19
+ noticedToolUses = new Set();
20
+ // The open turn's figures, reset when a turn starts.
21
+ lastUsage = null;
22
+ lastTotal = null;
23
+ lastModel = null;
24
+ /** A `rate_limit_event` that came before the turn had usage to report it with. */
25
+ pendingRateLimit = null;
26
+ /** The normalized texts of the turn's notices (see {@link repeats}). */
27
+ noticeTexts = [];
28
+ /** The context window of the session's model (see `context-window.ts`). */
29
+ contextWindow = DEFAULT_CONTEXT_WINDOW;
30
+ /** Whether {@link contextWindow} came from Claude Code, not from a guess. */
31
+ contextWindowAuthoritative = false;
32
+ /** The model that {@link contextWindow} is of. */
33
+ modelId;
34
+ /** Scopes the cross-session window cache to the query's backend. */
35
+ providerCacheKey = "";
36
+ query;
37
+ disposed = false;
38
+ /** The context used after the last main-thread request. */
39
+ contextUsed;
40
+ /** The follow-up prompt the client holds, for an AIR client only. */
41
+ suggestions;
42
+ constructor(host) {
43
+ this.host = host;
44
+ this.suggestions = host.airClient ? new PromptSuggestions() : undefined;
45
+ this.titles = new SessionTitles({
46
+ client: { sessionUpdate: async (notification) => host.emit([notification]) },
47
+ logger: host.logger,
48
+ get sessions() {
49
+ const session = host.titledSession();
50
+ return session ? { [host.sessionId]: session } : {};
51
+ },
52
+ }, host.sessionId);
53
+ // Every v2 client takes compaction updates.
54
+ this.compaction = new ContextCompactionLifecycle(async (notification) => host.emit([notification]), {
55
+ sessionId: host.sessionId,
56
+ presentation: "compaction_update",
57
+ logError: (message, error) => host.logger.error(message, error),
58
+ });
59
+ }
60
+ /** Called once, before the query's first message. */
61
+ configure(setup) {
62
+ this.clientMcpServers = new Set(setup.mcpServers);
63
+ this.mcpOAuth = setup.mcpOAuth;
64
+ this.settings = setup.settings;
65
+ this.query = setup.query;
66
+ // From the same env the query got.
67
+ this.providerCacheKey = providerCacheKeyFor(setup.env);
68
+ this.seedContextWindow(setup.model.id, setup.model.info);
69
+ this.idleCompaction = new IdleCompaction({
70
+ isBusy: () => this.host.isBusy(),
71
+ contextTokens: () => this.contextUsed,
72
+ settings: () => setup.settings.getSettings(),
73
+ compact: () => this.host.compact(),
74
+ // The logger has no debug level.
75
+ log: (message) => this.host.logger.log(message),
76
+ }, { env: setup.env });
77
+ }
78
+ /**
79
+ * The session's query restarted with the same MCP servers (see
80
+ * `restarts.ts`): a server already reported is not reported again, and the
81
+ * prediction the client holds is still cleared at the next prompt.
82
+ */
83
+ restartedFrom(previous) {
84
+ for (const server of previous.reportedMcpServers)
85
+ this.reportedMcpServers.add(server);
86
+ this.suggestions = previous.suggestions;
87
+ }
88
+ /** The session's MCP servers changed, as a resume of the active session asks. */
89
+ mcpServersChanged(names) {
90
+ this.clientMcpServers = new Set(names);
91
+ }
92
+ // --- Turns ---------------------------------------------------------------
93
+ turnStarted() {
94
+ this.lastUsage = null;
95
+ this.lastTotal = null;
96
+ this.lastModel = null;
97
+ this.noticeTexts = [];
98
+ }
99
+ /**
100
+ * The turn ends: a compaction that Claude Code left open ends `cancelled`.
101
+ * Called before the turn's idle.
102
+ */
103
+ turnEnded() {
104
+ void this.compaction.reset();
105
+ }
106
+ /**
107
+ * Whether the text of a result that streamed no model text was shown
108
+ * already: as a compaction, or as one of the turn's notices (a hook-blocked
109
+ * turn's result repeats the block reason).
110
+ */
111
+ repeats(resultText) {
112
+ return (this.compaction.hasDeliveredOutput ||
113
+ this.noticeTexts.includes(normalizeNoticeText(resultText)));
114
+ }
115
+ /**
116
+ * Claude Code's session state went `idle`: the idle compaction may arm, and
117
+ * the title may have landed (see {@link SessionTitles.onTurnEnd}).
118
+ */
119
+ idle() {
120
+ this.idleCompaction?.onIdle();
121
+ const session = this.host.titledSession();
122
+ if (session) {
123
+ this.titles.onTurnEnd(session).catch((error) => {
124
+ this.host.logger.error(`Session ${this.host.sessionId}: failed to update the title`, error);
125
+ });
126
+ }
127
+ }
128
+ // --- Titles ----------------------------------------------------------------
129
+ /**
130
+ * A client prompt came: it drops the armed idle compaction, and its text is
131
+ * for the title. The adapter's `/compact` is no client prompt.
132
+ */
133
+ promptSent(prompt) {
134
+ this.idleCompaction?.disarm("prompt");
135
+ this.titles.onPrompt(prompt);
136
+ // The prediction is spent: the user sent it or something else. A turn
137
+ // that predicts nothing (plan mode, an API error, the usage limit) then
138
+ // leaves no stale prediction in the composer.
139
+ this.sendSuggestion(this.suggestions?.clear());
140
+ }
141
+ /** The client prompt went to Claude Code, which may title the session from it. */
142
+ promptQueued(prompt) {
143
+ const session = this.host.titledSession();
144
+ if (session)
145
+ this.titles.onPromptQueued(session, prompt);
146
+ }
147
+ /** A live agent text chunk of the root session, for the title. */
148
+ agentText(content) {
149
+ this.titles.onAssistantText(content);
150
+ }
151
+ /** Sends the session's current title and `updatedAt`, as `session/resume` asks. */
152
+ async publishTitle() {
153
+ const session = this.host.titledSession();
154
+ if (!session)
155
+ return;
156
+ try {
157
+ await this.titles.publishCurrent(session);
158
+ }
159
+ catch (error) {
160
+ this.host.logger.error(`Session ${this.host.sessionId}: failed to send the session info`, error);
161
+ }
162
+ }
163
+ /** Drops the armed idle compaction: a prompt or a cancel came. */
164
+ disarmIdleCompaction(reason) {
165
+ this.idleCompaction?.disarm(reason);
166
+ }
167
+ /**
168
+ * The session's model is `id` now: the idle compaction's request describes
169
+ * the old one, and the context window is seeded for the new one, as on v1
170
+ * (`applyConfigOptionValue`). Nothing changes for the same model.
171
+ */
172
+ modelChanged(id, info) {
173
+ if (id === this.modelId)
174
+ return;
175
+ this.idleCompaction?.disarm("model change");
176
+ this.seedContextWindow(id, info);
177
+ }
178
+ /**
179
+ * A `conversation_reset`: Claude Code mounted a fresh transcript. A
180
+ * compaction still open ends `cancelled`, the title is evaluated again at
181
+ * the next idle, and the idle compaction's request and TTL describe the
182
+ * dropped conversation.
183
+ */
184
+ conversationReset() {
185
+ void this.compaction.reset();
186
+ // The fresh conversation's context is empty.
187
+ this.lastUsage = null;
188
+ this.lastTotal = null;
189
+ this.contextUsed = 0;
190
+ this.titles.reset();
191
+ this.idleCompaction?.reset();
192
+ // The prediction came from the transcript that the reset dropped.
193
+ this.sendSuggestion(this.suggestions?.clear());
194
+ }
195
+ /** Sends the usage of an empty context, as a fresh context for an approved plan starts. */
196
+ emptyContext() {
197
+ this.host.emit([
198
+ {
199
+ sessionId: this.host.sessionId,
200
+ update: { sessionUpdate: "usage_update", used: 0, size: this.contextWindow },
201
+ },
202
+ ]);
203
+ }
204
+ /** The share of the context window in use, in percent, once a request reported it. */
205
+ contextUsedPercent() {
206
+ if (this.contextUsed === undefined || this.contextWindow <= 0)
207
+ return undefined;
208
+ return Math.max(0, Math.min(100, Math.round((this.contextUsed / this.contextWindow) * 100)));
209
+ }
210
+ dispose() {
211
+ this.disposed = true;
212
+ this.idleCompaction?.dispose();
213
+ this.settings?.dispose();
214
+ }
215
+ /** The PostCompact hook's summary of the root conversation's compaction. */
216
+ compactSummary(summary) {
217
+ this.compaction.recordSummary(summary);
218
+ }
219
+ // --- The query's messages ----------------------------------------------
220
+ /** A root stream event: its usage, and the streamed summary of a compaction. */
221
+ streamEvent(message) {
222
+ const { event } = message;
223
+ const compactionBlock = event.type === "content_block_start" && event.content_block.type === "compaction"
224
+ ? event.content_block
225
+ : event.type === "content_block_delta" && event.delta.type === "compaction_delta"
226
+ ? event.delta
227
+ : undefined;
228
+ // `content` is null on the opening block and on a failed compaction.
229
+ if (compactionBlock) {
230
+ void this.compaction.heartbeat(message.uuid, compactionBlock.content ?? undefined);
231
+ }
232
+ if (event.type === "message_start") {
233
+ this.lastUsage = snapshotFromUsage(event.message.usage);
234
+ const model = event.message.model;
235
+ if (model && model !== "<synthetic>") {
236
+ this.lastModel = model;
237
+ this.idleCompaction?.noteRequest(event.message.usage, event.message.id || undefined);
238
+ if (!this.contextWindowAuthoritative && this.contextWindow === DEFAULT_CONTEXT_WINDOW) {
239
+ this.contextWindow = inferContextWindowFromModel(model) ?? this.contextWindow;
240
+ }
241
+ }
242
+ }
243
+ else if (event.type === "message_delta") {
244
+ const usage = event.usage;
245
+ const prev = this.lastUsage ?? ZERO_USAGE;
246
+ // The delta's counters are cumulative; the nullable ones keep the
247
+ // previous value when the delta leaves them out.
248
+ this.lastUsage = {
249
+ input_tokens: usage.input_tokens ?? prev.input_tokens,
250
+ output_tokens: usage.output_tokens,
251
+ cache_read_input_tokens: usage.cache_read_input_tokens ?? prev.cache_read_input_tokens,
252
+ cache_creation_input_tokens: usage.cache_creation_input_tokens ?? prev.cache_creation_input_tokens,
253
+ };
254
+ }
255
+ else {
256
+ return;
257
+ }
258
+ const used = totalTokens(this.lastUsage);
259
+ if (used === this.lastTotal)
260
+ return;
261
+ this.lastTotal = used;
262
+ this.contextUsed = used;
263
+ this.sendUsage({ sessionUpdate: "usage_update", used, size: this.contextWindow });
264
+ }
265
+ /**
266
+ * A root assistant message: the turn's latest usage and model. A synthetic
267
+ * message (a CLI banner with an all-zero usage) is not a model response.
268
+ */
269
+ assistant(message) {
270
+ if (message.message.model === "<synthetic>")
271
+ return;
272
+ this.lastUsage = snapshotFromUsage(message.message.usage);
273
+ this.lastTotal = totalTokens(this.lastUsage);
274
+ this.contextUsed = this.lastTotal;
275
+ this.idleCompaction?.noteRequest(message.message.usage, message.message.id || undefined);
276
+ if (message.message.model)
277
+ this.lastModel = message.message.model;
278
+ }
279
+ /**
280
+ * A result: its cost, and the model's context window. The idle's quota is
281
+ * `outcome.ts`'s. The CLI predicts the next prompt right after it.
282
+ */
283
+ result(message) {
284
+ this.suggestions?.resultArrived();
285
+ const matching = this.lastModel
286
+ ? getMatchingModelUsage(message.modelUsage, this.lastModel)
287
+ : undefined;
288
+ const window = matching?.usage?.contextWindow;
289
+ if (matching && typeof window === "number" && window > 0) {
290
+ this.contextWindow = window;
291
+ this.contextWindowAuthoritative = true;
292
+ cacheResultContextWindow(this.providerCacheKey, matching.key, this.lastModel, window);
293
+ }
294
+ if (this.lastTotal === null)
295
+ return;
296
+ this.sendUsage({
297
+ sessionUpdate: "usage_update",
298
+ used: this.lastTotal,
299
+ size: this.contextWindow,
300
+ cost: { amount: message.total_cost_usd, currency: "USD" },
301
+ ...(message.origin ? { _meta: { "_claude/origin": message.origin } } : {}),
302
+ });
303
+ }
304
+ /**
305
+ * The messages that only report: Claude Code's notices, compaction states,
306
+ * rate limits and predicted prompts. Returns whether `message` was one.
307
+ */
308
+ handle(message) {
309
+ switch (message.type) {
310
+ case "prompt_suggestion":
311
+ // AIR shows it as gray text in an empty composer, which Tab fills.
312
+ this.sendSuggestion(this.suggestions?.suggested(message.suggestion));
313
+ return true;
314
+ case "rate_limit_event":
315
+ this.idleCompaction?.noteRateLimit(message.rate_limit_info);
316
+ // Sent before the turn's first usage: it goes out with that usage.
317
+ if (this.lastTotal === null) {
318
+ this.pendingRateLimit = message.rate_limit_info;
319
+ }
320
+ else {
321
+ this.sendUsage({
322
+ sessionUpdate: "usage_update",
323
+ used: this.lastTotal,
324
+ size: this.contextWindow,
325
+ _meta: { "_claude/rateLimit": message.rate_limit_info },
326
+ });
327
+ }
328
+ return true;
329
+ case "system":
330
+ break;
331
+ default:
332
+ return false;
333
+ }
334
+ switch (message.subtype) {
335
+ case "init":
336
+ this.mcpStartupFailures(message.mcp_servers);
337
+ // The turn goes on: the session opens it.
338
+ return false;
339
+ case "status":
340
+ if (message.status === "compacting") {
341
+ void this.compaction.start(message.uuid);
342
+ }
343
+ else if (message.compact_result === "success") {
344
+ void this.compaction.finish(message.uuid, "completed");
345
+ }
346
+ else if (message.compact_result === "failed") {
347
+ this.idleCompaction?.noteCompactionFailed(message.compact_error);
348
+ void this.compaction.finish(message.uuid, "failed", {
349
+ ...(message.compact_error ? { error: message.compact_error } : {}),
350
+ });
351
+ }
352
+ return true;
353
+ case "compact_boundary": {
354
+ const metadata = message.compact_metadata;
355
+ void this.compaction.finish(message.uuid, "completed", metadata
356
+ ? contextCompactionMetadataFromBoundary(metadata, {
357
+ idleCompaction: this.idleCompaction?.isCompacting,
358
+ })
359
+ : {}, true);
360
+ // The boundary carries the context that the compaction kept. The
361
+ // window stays: compaction frees context, it does not change the model.
362
+ const used = metadata?.post_tokens ?? 0;
363
+ this.lastUsage = null;
364
+ this.lastTotal = used;
365
+ this.contextUsed = used;
366
+ this.sendUsage({ sessionUpdate: "usage_update", used, size: this.contextWindow });
367
+ return true;
368
+ }
369
+ case "informational": {
370
+ // 'info' shows only in Claude Code's transcript mode: not worth a notice.
371
+ if (message.level === "info")
372
+ return true;
373
+ if (message.tool_use_id) {
374
+ if (this.noticedToolUses.has(message.tool_use_id))
375
+ return true;
376
+ this.noticedToolUses.add(message.tool_use_id);
377
+ }
378
+ this.host.emit([
379
+ { sessionId: this.host.sessionId, update: noticeUpdate(informationalNotice(message)) },
380
+ ]);
381
+ this.noticeTexts.push(normalizeNoticeText(message.content));
382
+ return true;
383
+ }
384
+ default:
385
+ return false;
386
+ }
387
+ }
388
+ /**
389
+ * The window of model `id` without IPC: one learned from a result of this
390
+ * or another session on the same backend, else a guess from the model's
391
+ * names. A guess is then read from Claude Code in the background
392
+ * (`readContextWindow`), until a result reports the window.
393
+ */
394
+ seedContextWindow(id, info) {
395
+ this.modelId = id;
396
+ const seeded = immediateContextWindow(this.providerCacheKey, id, info);
397
+ this.contextWindow = seeded.size;
398
+ this.contextWindowAuthoritative = seeded.authoritative;
399
+ const query = this.query;
400
+ if (seeded.authoritative || !query)
401
+ return;
402
+ const current = () => !this.disposed && this.modelId === id;
403
+ // A synchronous throw must not fail the caller either.
404
+ Promise.resolve()
405
+ .then(() => readContextWindow(query))
406
+ .then((window) => {
407
+ if (!current() || this.contextWindowAuthoritative || window === undefined)
408
+ return;
409
+ this.contextWindow = window;
410
+ this.contextWindowAuthoritative = true;
411
+ }, (error) => {
412
+ if (current()) {
413
+ this.host.logger.error(`Session ${this.host.sessionId}: failed to read the context window`, error);
414
+ }
415
+ });
416
+ }
417
+ /** A notice for each client MCP server that did not start, once per server. */
418
+ mcpStartupFailures(servers) {
419
+ for (const server of servers ?? []) {
420
+ if (!this.clientMcpServers.has(server.name) || this.reportedMcpServers.has(server.name)) {
421
+ continue;
422
+ }
423
+ const notice = mcpServerStartupNotice(server, this.mcpOAuth);
424
+ if (!notice)
425
+ continue;
426
+ this.reportedMcpServers.add(server.name);
427
+ this.host.emit([{ sessionId: this.host.sessionId, update: noticeUpdate(notice) }]);
428
+ }
429
+ }
430
+ /** Sends the `_meta` of {@link PromptSuggestions}, when it has one. */
431
+ sendSuggestion(meta) {
432
+ if (!meta)
433
+ return;
434
+ this.host.emit([
435
+ {
436
+ sessionId: this.host.sessionId,
437
+ update: { sessionUpdate: "session_info_update", _meta: meta },
438
+ },
439
+ ]);
440
+ }
441
+ /**
442
+ * Sends a `usage_update` with the model the usage belongs to and any
443
+ * pending rate limit in `_meta`, as ACP's usage_update has no field for them.
444
+ */
445
+ sendUsage(update) {
446
+ let meta = { ...(update._meta ?? {}) };
447
+ if (this.pendingRateLimit !== null) {
448
+ meta = { "_claude/rateLimit": this.pendingRateLimit, ...meta };
449
+ this.pendingRateLimit = null;
450
+ }
451
+ if (this.lastModel)
452
+ meta["_claude/model"] = this.lastModel;
453
+ this.host.emit([
454
+ {
455
+ sessionId: this.host.sessionId,
456
+ update: { ...update, ...(Object.keys(meta).length > 0 ? { _meta: meta } : {}) },
457
+ },
458
+ ]);
459
+ }
460
+ }
461
+ /**
462
+ * The hooks that feed the reports: the PostCompact summary of the root
463
+ * conversation's compaction (a subagent's own is not the session's), and
464
+ * the TaskCreated and TaskCompleted changes of the session's Task* plan.
465
+ */
466
+ export function reportHooks(session) {
467
+ const taskHook = createTaskHook({
468
+ taskState: session.output.taskState,
469
+ onChange: async () => session.output.taskPlanChanged(),
470
+ });
471
+ return {
472
+ PostCompact: [
473
+ {
474
+ hooks: [
475
+ async (input) => {
476
+ if (input.hook_event_name === "PostCompact" && !input.agent_id) {
477
+ session.reports.compactSummary(input.compact_summary);
478
+ }
479
+ return { continue: true };
480
+ },
481
+ ],
482
+ },
483
+ ],
484
+ TaskCreated: [{ hooks: [taskHook] }],
485
+ TaskCompleted: [{ hooks: [taskHook] }],
486
+ };
487
+ }
@@ -0,0 +1,128 @@
1
+ import type * as v2 from "@agentclientprotocol/sdk/experimental/v2/unstable";
2
+ import type { Logger } from "../acp-agent.js";
3
+ import type { V2Session } from "./session.js";
4
+ /** The request that set the session up, whose options a restart starts with again. */
5
+ export type SetupParams = v2.NewSessionRequest | v2.ResumeSessionRequest | v2.ForkSessionRequest;
6
+ /** What the restarts need of the agent. */
7
+ export interface RestartHost {
8
+ readonly logger: Logger;
9
+ /** The active session `sessionId`. */
10
+ active(sessionId: string): V2Session | undefined;
11
+ /**
12
+ * Starts a new query that resumes `sessionId`, with the options of `params`
13
+ * and the current route. The new session is active once it resolves.
14
+ */
15
+ start(sessionId: string, params: SetupParams): Promise<V2Session>;
16
+ /** `previous` could not start again: the session stops. */
17
+ lost(sessionId: string, previous: V2Session): Promise<void>;
18
+ send(notification: v2.UpdateSessionNotification): void;
19
+ }
20
+ export declare class SessionRestarts {
21
+ private readonly host;
22
+ /** The setup request of each live session. */
23
+ private readonly setups;
24
+ /** The sessions whose account may have changed: their next prompt at a turn boundary restarts them. */
25
+ private readonly accountChanged;
26
+ /** The route restarts that wait for the session's turn boundary. Prompts do not wait for them. */
27
+ private readonly reroutes;
28
+ /** The restarts that run: from the new query's start to the old one's end. */
29
+ private readonly swaps;
30
+ /** The session that each running restart replaces. */
31
+ private readonly retiring;
32
+ /** The sessions that `session/close` closes: a restart that runs does not track them again. */
33
+ private readonly closingSessions;
34
+ /**
35
+ * The sessions whose start read the route before a change that
36
+ * {@link reroute} did not find them live for: they restart once their
37
+ * setup answered ({@link setupAnswered}).
38
+ */
39
+ private readonly staleRoutes;
40
+ /** The prompts that wait for a restart, each with what rejects it. */
41
+ private readonly held;
42
+ constructor(host: RestartHost);
43
+ /**
44
+ * The session started from `params`, or a resume of the active session
45
+ * brought new ones. `staleRoute`: the start read the route before a route
46
+ * change came.
47
+ */
48
+ track(sessionId: string, params: SetupParams, { staleRoute }?: {
49
+ staleRoute?: boolean | undefined;
50
+ }): void;
51
+ /**
52
+ * The setup response of `sessionId` goes out: a route restart that its
53
+ * start missed runs from then, as for a live session (see {@link reroute}).
54
+ * Not before: the restart's updates must not precede the response.
55
+ */
56
+ setupAnswered(sessionId: string): void;
57
+ /**
58
+ * A resume of the active session brought other additional directories:
59
+ * the session restarts with `params`, as for a new route (see the module
60
+ * doc). Does not wait for it.
61
+ */
62
+ rootsChanged(sessionId: string, params: SetupParams): void;
63
+ /**
64
+ * The session is no longer active, such as when its query ended. A route
65
+ * restart that is due does not run.
66
+ */
67
+ forget(sessionId: string): void;
68
+ /**
69
+ * The route changed: restarts every live session at its next turn
70
+ * boundary. Resolves once each session that is at one now restarted, or
71
+ * was closed or lost. Their restarts start in this call, so a prompt that
72
+ * comes after it waits for them (`beforePrompt`). The busy sessions'
73
+ * restarts are only due: a failure of one stops its session later
74
+ * (`RestartHost.lost`).
75
+ */
76
+ reroute(): Promise<void>;
77
+ /** The session's account may have changed: its next prompt at a turn boundary restarts it. */
78
+ accountMayHaveChanged(sessionId: string): void;
79
+ /**
80
+ * What a prompt of `sessionId` waits for before it goes to the session: a
81
+ * restart that runs, or an account restart that is due. `undefined` when
82
+ * none is: the prompt goes on in the same call, so prompts keep their
83
+ * order. A route restart that waits for a turn boundary does not hold it:
84
+ * the prompt goes to the current query.
85
+ */
86
+ beforePrompt(sessionId: string): Promise<void> | undefined;
87
+ /**
88
+ * Whether a restart runs: its new query starts MCP OAuth once it took
89
+ * over, so the setup response of the session it replaces need not.
90
+ */
91
+ restarting(sessionId: string): boolean;
92
+ /** What a request other than a prompt waits for: a restart that runs. */
93
+ settled(sessionId: string): Promise<void> | undefined;
94
+ /**
95
+ * `session/cancel`: the prompts that wait for a restart fail with -32800,
96
+ * and work that runs on the query that a restart replaces stops too (the
97
+ * restart waits for it).
98
+ */
99
+ cancelled(sessionId: string): void;
100
+ /**
101
+ * `session/close`: the prompts that wait fail with -32800, and a route
102
+ * restart that waits for a turn boundary is dropped (the closed session
103
+ * reaches none). Resolves once a restart that runs is done, so the close
104
+ * ends the session that it started.
105
+ */
106
+ closing(sessionId: string): Promise<void>;
107
+ /** `session/close` closed the session. */
108
+ closed(sessionId: string): void;
109
+ /** Waits for the restarts that run, so no new query starts after the agent's sessions closed. */
110
+ dispose(): Promise<void>;
111
+ /**
112
+ * Restarts the session for a new route. At a turn boundary, with no restart
113
+ * that runs, the restart starts in this call, and the result resolves once
114
+ * it is done. Otherwise it is due at the next turn boundary, and the result
115
+ * resolves at once.
116
+ */
117
+ private rerouteSession;
118
+ /**
119
+ * Starts the new query, then ends the old one and sets the client's choices
120
+ * on the new one. With `keepOnFailure`, a failed start rejects and leaves
121
+ * `previous` active. Otherwise the session is lost.
122
+ */
123
+ private swap;
124
+ /** Waits for `work`, unless a cancel or close of the session comes first. */
125
+ private hold;
126
+ private release;
127
+ }
128
+ //# sourceMappingURL=restarts.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"restarts.d.ts","sourceRoot":"","sources":["../../src/v2/restarts.ts"],"names":[],"mappings":"AAqDA,OAAO,KAAK,KAAK,EAAE,MAAM,mDAAmD,CAAC;AAC7E,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAE9C,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,cAAc,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