@agentclientprotocol/claude-agent-acp 0.102.1-preview.2 → 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 (72) hide show
  1. package/dist/acp-agent.d.ts +14 -217
  2. package/dist/acp-agent.d.ts.map +1 -1
  3. package/dist/acp-agent.js +18 -1076
  4. package/dist/acp-client.d.ts +28 -0
  5. package/dist/acp-client.d.ts.map +1 -0
  6. package/dist/acp-client.js +1 -0
  7. package/dist/lib.d.ts +5 -1
  8. package/dist/lib.d.ts.map +1 -1
  9. package/dist/lib.js +3 -1
  10. package/dist/logger.d.ts +10 -0
  11. package/dist/logger.d.ts.map +1 -0
  12. package/dist/logger.js +1 -0
  13. package/dist/message-filters.d.ts +43 -0
  14. package/dist/message-filters.d.ts.map +1 -0
  15. package/dist/message-filters.js +197 -0
  16. package/dist/new-session-meta.d.ts +40 -0
  17. package/dist/new-session-meta.d.ts.map +1 -0
  18. package/dist/new-session-meta.js +1 -0
  19. package/dist/prompt-to-claude.d.ts +10 -0
  20. package/dist/prompt-to-claude.d.ts.map +1 -0
  21. package/dist/prompt-to-claude.js +120 -0
  22. package/dist/result-end.d.ts +33 -4
  23. package/dist/result-end.d.ts.map +1 -1
  24. package/dist/result-end.js +34 -0
  25. package/dist/sdk-to-acp.d.ts +93 -0
  26. package/dist/sdk-to-acp.d.ts.map +1 -0
  27. package/dist/sdk-to-acp.js +635 -0
  28. package/dist/serve.d.ts +2 -1
  29. package/dist/serve.d.ts.map +1 -1
  30. package/dist/session-index/connection.d.ts +3 -1
  31. package/dist/session-index/connection.d.ts.map +1 -1
  32. package/dist/slash-commands.d.ts +10 -0
  33. package/dist/slash-commands.d.ts.map +1 -0
  34. package/dist/slash-commands.js +99 -0
  35. package/dist/utils.d.ts +1 -1
  36. package/dist/utils.d.ts.map +1 -1
  37. package/dist/v2/agent.d.ts +1 -1
  38. package/dist/v2/agent.d.ts.map +1 -1
  39. package/dist/v2/agent.js +1 -1
  40. package/dist/v2/auth.d.ts +1 -1
  41. package/dist/v2/auth.d.ts.map +1 -1
  42. package/dist/v2/commands.js +1 -1
  43. package/dist/v2/config.d.ts +1 -1
  44. package/dist/v2/config.d.ts.map +1 -1
  45. package/dist/v2/elicitation.d.ts +1 -1
  46. package/dist/v2/elicitation.d.ts.map +1 -1
  47. package/dist/v2/file-preview.d.ts +1 -1
  48. package/dist/v2/file-preview.d.ts.map +1 -1
  49. package/dist/v2/outcome.d.ts.map +1 -1
  50. package/dist/v2/outcome.js +2 -1
  51. package/dist/v2/remote-control.d.ts +1 -1
  52. package/dist/v2/remote-control.d.ts.map +1 -1
  53. package/dist/v2/reports.d.ts +1 -1
  54. package/dist/v2/reports.d.ts.map +1 -1
  55. package/dist/v2/restarts.d.ts +1 -1
  56. package/dist/v2/restarts.d.ts.map +1 -1
  57. package/dist/v2/session.d.ts +1 -1
  58. package/dist/v2/session.d.ts.map +1 -1
  59. package/dist/v2/session.js +2 -1
  60. package/dist/v2/setup.d.ts +1 -1
  61. package/dist/v2/setup.d.ts.map +1 -1
  62. package/dist/v2/stopped-work.js +1 -1
  63. package/dist/v2/stream.d.ts +3 -2
  64. package/dist/v2/stream.d.ts.map +1 -1
  65. package/dist/v2/stream.js +2 -1
  66. package/dist/v2/subagent-replay.d.ts +1 -1
  67. package/dist/v2/subagent-replay.d.ts.map +1 -1
  68. package/dist/v2/subscription-guard.d.ts +1 -1
  69. package/dist/v2/subscription-guard.d.ts.map +1 -1
  70. package/dist/v2/tasks.d.ts +1 -1
  71. package/dist/v2/tasks.d.ts.map +1 -1
  72. package/package.json +1 -1
@@ -0,0 +1,635 @@
1
+ import { clientSupportsSubagents } from "./acp-subagents.js";
2
+ import { approvedPlan, planModeUpdate } from "./exit-plan.js";
3
+ import { checklistPlanUpdate, todoWritePlanUpdate } from "./plans.js";
4
+ import { AcpToolCallRenderer } from "./tool-calls/renderer.js";
5
+ import { parseToolResultMeta } from "./tool-result-meta.js";
6
+ import { applyTaskCreate, applyTaskList, applyTaskUpdate, changedTaskPlanEntries, completeHookCallback, hasHookCallback, parseTaskCreateOutput, parseTaskListOutput, parseTaskUpdateOutput, planEntries, registerHookCallback, unregisterHookCallback, } from "./tools.js";
7
+ import { unreachable } from "./utils.js";
8
+ /** Attributes a report to the Agent/Task tool call of the subagent that made it. */
9
+ export function stampParentToolUseId(update, parentToolUseId) {
10
+ update._meta = {
11
+ ...update._meta,
12
+ claudeCode: {
13
+ ...(update._meta?.claudeCode ?? {}),
14
+ parentToolUseId,
15
+ },
16
+ };
17
+ }
18
+ /**
19
+ * Advance the lexer state across the fragment appended since the last delta:
20
+ * just enough JSON awareness (string/escape, nesting depth) to spot commas
21
+ * that sit at the top level of the input object — everything before such a
22
+ * comma is a set of complete fields. Returns true once the input object's
23
+ * closing brace arrives.
24
+ *
25
+ * The lexer reads the fragment itself, never `partialJson` by index. V8 keeps a
26
+ * string built with `+=` as a chain of parts, and the first index access
27
+ * copies the whole chain into one flat string. An index scan of `partialJson`
28
+ * would copy the whole input on each delta, so a large Write would cost
29
+ * quadratic time. A test in `acp-agent.test.ts` checks this.
30
+ */
31
+ function scanStreamedToolInput(state, fragment) {
32
+ const offset = state.partialJson.length;
33
+ state.partialJson += fragment;
34
+ let complete = false;
35
+ for (let index = 0; index < fragment.length; index++) {
36
+ const character = fragment[index];
37
+ if (state.inString) {
38
+ if (state.escaped) {
39
+ state.escaped = false;
40
+ }
41
+ else if (character === "\\") {
42
+ state.escaped = true;
43
+ }
44
+ else if (character === '"') {
45
+ state.inString = false;
46
+ }
47
+ continue;
48
+ }
49
+ if (character === '"') {
50
+ state.inString = true;
51
+ }
52
+ else if (character === "{") {
53
+ state.objectDepth++;
54
+ }
55
+ else if (character === "}") {
56
+ state.objectDepth--;
57
+ if (state.objectDepth === 0) {
58
+ complete = true;
59
+ }
60
+ }
61
+ else if (character === "[") {
62
+ state.arrayDepth++;
63
+ }
64
+ else if (character === "]") {
65
+ state.arrayDepth--;
66
+ }
67
+ else if (character === "," && state.objectDepth === 1 && state.arrayDepth === 0) {
68
+ state.lastTopLevelComma = offset + index;
69
+ }
70
+ }
71
+ return complete;
72
+ }
73
+ /** Parse the complete top-level fields before a top-level comma by closing the
74
+ * object at that boundary. */
75
+ function recoveredToolInput(prefix) {
76
+ try {
77
+ const value = JSON.parse(prefix + "}");
78
+ return value !== null && typeof value === "object" && !Array.isArray(value)
79
+ ? value
80
+ : undefined;
81
+ }
82
+ catch {
83
+ return undefined;
84
+ }
85
+ }
86
+ /**
87
+ * Resolves the ACP `messageId` for a Claude SDK message (live) or a persisted
88
+ * transcript message (replay) so chunk grouping is identical in both views.
89
+ *
90
+ * Assistant turns are keyed by the Anthropic API message id (`message.id`),
91
+ * which is identical at `message_start`, on the consolidated assistant message,
92
+ * and in the persisted transcript — unlike the per-`stream_event` uuid, which is
93
+ * unique per event and never persisted. User messages have no API id, but they
94
+ * are never streamed, so their (stable) SDK uuid is used instead. ACP message
95
+ * ids are opaque strings, so no particular format is required.
96
+ */
97
+ export function messageIdForGrouping(message) {
98
+ if (message.type === "assistant") {
99
+ const inner = message.message;
100
+ const apiId = inner && typeof inner === "object" && "id" in inner
101
+ ? inner.id
102
+ : undefined;
103
+ if (typeof apiId === "string" && apiId.length > 0) {
104
+ return apiId;
105
+ }
106
+ }
107
+ return typeof message.uuid === "string" && message.uuid.length > 0 ? message.uuid : undefined;
108
+ }
109
+ /**
110
+ * Stamps an ACP `messageId` onto a session update, but only on the message/
111
+ * thought chunk variants that carry one — tool_call/plan/etc. updates never do.
112
+ * No-op when `messageId` is falsy, so callers can pass it through unconditionally.
113
+ */
114
+ function applyMessageId(update, messageId) {
115
+ if (messageId &&
116
+ (update.sessionUpdate === "agent_message_chunk" ||
117
+ update.sessionUpdate === "user_message_chunk" ||
118
+ update.sessionUpdate === "agent_thought_chunk")) {
119
+ update.messageId = messageId;
120
+ }
121
+ }
122
+ /** Built-in tools that drive the task list (headless/SDK sessions use these
123
+ * instead of TodoWrite). Their tool_use/tool_result are surfaced as `plan`
124
+ * snapshots rather than as tool_calls. */
125
+ function isTaskTool(toolName) {
126
+ return (toolName === "TaskCreate" ||
127
+ toolName === "TaskUpdate" ||
128
+ toolName === "TaskList" ||
129
+ toolName === "TaskGet");
130
+ }
131
+ /** Whether the streamed tool_use path surfaces this tool as a standalone
132
+ * `tool_call`. TodoWrite is rendered as a `plan` and Task* tools are
133
+ * suppressed (their plan snapshot is emitted at tool_result time), so neither
134
+ * produces a streamed tool_call/tool_call_update — which means a
135
+ * permission-surfaced tool_call for them (see `ensureToolCallEmitted`) must be
136
+ * resolved explicitly at tool_result time. */
137
+ function shouldEmitToolCall(toolName) {
138
+ return toolName !== "TodoWrite" && !isTaskTool(toolName);
139
+ }
140
+ /**
141
+ * The renderer of the notification functions: the agent's tool call
142
+ * capabilities when they are passed, else those of the ACP capabilities.
143
+ */
144
+ function toolCallRenderer(options) {
145
+ return options?.toolCallCapabilities
146
+ ? new AcpToolCallRenderer(options.toolCallCapabilities, options.replay)
147
+ : AcpToolCallRenderer.for(options?.clientCapabilities, options?.replay);
148
+ }
149
+ /**
150
+ * Convert an SDKAssistantMessage (Claude) to a SessionNotification (ACP).
151
+ * Only handles text, image, and thinking chunks for now.
152
+ */
153
+ export function toAcpNotifications(content, role, sessionId, toolUseCache, client, logger, options) {
154
+ const taskState = options?.taskState ?? new Map();
155
+ const registerHooks = options?.registerHooks !== false;
156
+ const renderer = toolCallRenderer(options);
157
+ if (typeof content === "string") {
158
+ if (content.length === 0) {
159
+ return [];
160
+ }
161
+ const update = {
162
+ sessionUpdate: role === "assistant" ? "agent_message_chunk" : "user_message_chunk",
163
+ content: {
164
+ type: "text",
165
+ text: content,
166
+ },
167
+ };
168
+ applyMessageId(update, options?.messageId);
169
+ if (options?.parentToolUseId)
170
+ stampParentToolUseId(update, options.parentToolUseId);
171
+ return [{ sessionId, update }];
172
+ }
173
+ // `tool_use_result` is message-level and carries no tool_use_id of its own:
174
+ // it describes "the" tool_result block of the message it rode in on. If
175
+ // several tool_result blocks were ever batched into one message it couldn't
176
+ // be attributed, so it is only honored when the message carries exactly one.
177
+ const toolUseResult = options?.toolUseResult !== undefined &&
178
+ content.filter((c) => typeof c === "object" && c !== null && c.type === "tool_result")
179
+ .length === 1
180
+ ? options.toolUseResult
181
+ : undefined;
182
+ // Unlike `tool_use_result`, entries carry their own tool_use_id, so batched
183
+ // messages need no single-block guard.
184
+ const toolResultMeta = parseToolResultMeta(options?.toolResultMeta);
185
+ const output = [];
186
+ // Only handle the first chunk for streaming; extend as needed for batching
187
+ for (const chunk of content) {
188
+ let update = null;
189
+ // The tool call that this chunk finishes, if it is a tool result.
190
+ let finishedToolCallId;
191
+ // The plan that this chunk approves, if it is an ExitPlanMode result.
192
+ let approvedPlanUpdate;
193
+ switch (chunk.type) {
194
+ case "text":
195
+ case "text_delta": {
196
+ if (chunk.text) {
197
+ update = {
198
+ sessionUpdate: role === "assistant" ? "agent_message_chunk" : "user_message_chunk",
199
+ content: {
200
+ type: "text",
201
+ text: chunk.text,
202
+ },
203
+ };
204
+ }
205
+ break;
206
+ }
207
+ case "image":
208
+ update = {
209
+ sessionUpdate: role === "assistant" ? "agent_message_chunk" : "user_message_chunk",
210
+ content: {
211
+ type: "image",
212
+ data: chunk.source.type === "base64" ? chunk.source.data : "",
213
+ mimeType: chunk.source.type === "base64" ? chunk.source.media_type : "",
214
+ uri: chunk.source.type === "url" ? chunk.source.url : undefined,
215
+ },
216
+ };
217
+ break;
218
+ case "thinking":
219
+ case "thinking_delta": {
220
+ // Recent models default `thinking.display` to "omitted", which streams
221
+ // signature-only thinking blocks whose text is empty.
222
+ if (chunk.thinking) {
223
+ update = {
224
+ sessionUpdate: "agent_thought_chunk",
225
+ content: {
226
+ type: "text",
227
+ text: chunk.thinking,
228
+ },
229
+ };
230
+ }
231
+ break;
232
+ }
233
+ case "tool_use":
234
+ case "server_tool_use":
235
+ case "mcp_tool_use": {
236
+ const alreadyCached = chunk.id in toolUseCache;
237
+ toolUseCache[chunk.id] = chunk;
238
+ if (chunk.name === "TodoWrite") {
239
+ // @ts-expect-error - sometimes input is empty object or undefined
240
+ if (Array.isArray(chunk.input?.todos)) {
241
+ update = todoWritePlanUpdate(planEntries(chunk.input), {
242
+ planOperations: options?.clientCapabilities?.plan != null,
243
+ parentToolUseId: options?.parentToolUseId,
244
+ // With native subagent sessions, an update of a subagent goes
245
+ // to the subagent's session (see NativeSubagentRuntime).
246
+ childSessions: clientSupportsSubagents(options?.clientCapabilities),
247
+ shown: options?.subagentChecklists,
248
+ });
249
+ }
250
+ }
251
+ else if (isTaskTool(chunk.name)) {
252
+ // Task* tool_use is suppressed; the plan update is emitted at
253
+ // tool_result time once we have the task ID (for TaskCreate) and
254
+ // confirmation that the change took effect.
255
+ }
256
+ else {
257
+ // Only register hooks on first encounter to avoid double-firing
258
+ if (registerHooks && !alreadyCached) {
259
+ // Capture the tool name in the closure rather than re-reading the
260
+ // cache when the hook fires. The cache entry is pruned at
261
+ // tool_result time, and a PostToolUse hook can fire after that, so
262
+ // closing over the name keeps the diff working without depending on
263
+ // (or pinning) the cache entry's lifetime.
264
+ const toolName = chunk.name;
265
+ const hookToolCallId = chunk.id;
266
+ registerHookCallback(chunk.id, {
267
+ onPostToolUseHook: async (toolUseId, _toolInput, toolResponse) => {
268
+ // The final diff of an Edit or a Write replaces the
269
+ // optimistic content built from the input. Only the marker
270
+ // fields of the tool_response travel: the rest repeats
271
+ // output that the content already carries.
272
+ const update = await renderer.hookResult({ id: toolUseId, name: toolName }, toolResponse, options?.cwd);
273
+ if (!update)
274
+ return;
275
+ if (options?.parentToolUseId) {
276
+ stampParentToolUseId(update, options.parentToolUseId);
277
+ }
278
+ // The final result may replace a pinned approval patch.
279
+ if (options?.toolCallFields &&
280
+ !options.toolCallFields.apply(update, { replacePinnedContent: true })) {
281
+ return;
282
+ }
283
+ await client.sessionUpdate({ sessionId, update });
284
+ },
285
+ onRelease: () => options?.toolCallFields?.finishHook(hookToolCallId),
286
+ }, sessionId);
287
+ }
288
+ let rawInput;
289
+ try {
290
+ rawInput = JSON.parse(JSON.stringify(chunk.input));
291
+ }
292
+ catch {
293
+ // ignore if we can't turn it to JSON
294
+ }
295
+ const toolUse = { id: chunk.id, name: chunk.name, input: rawInput };
296
+ // Emit a `tool_call` only the first time this id surfaces to the
297
+ // client; afterwards refine it with a `tool_call_update`. The first
298
+ // surface may be this stream chunk OR an earlier permission request
299
+ // (see `ensureToolCallEmitted`), so emission is tracked separately
300
+ // from `toolUseCache`. Without an `emittedToolCalls` set we fall back
301
+ // to cache presence — the historical streaming-only behavior.
302
+ const emittedToolCalls = options?.emittedToolCalls;
303
+ const alreadyEmitted = emittedToolCalls ? emittedToolCalls.has(chunk.id) : alreadyCached;
304
+ emittedToolCalls?.add(chunk.id);
305
+ // A permission request surfaced the tool call with its complete
306
+ // input. The empty input at the stream start has nothing to add.
307
+ if (alreadyEmitted && options?.inputComplete === false)
308
+ break;
309
+ update = alreadyEmitted
310
+ ? // Already surfaced (full assistant message after streaming, or a
311
+ // permission request emitted it first): refine it with the
312
+ // complete input.
313
+ renderer.refinement(toolUse, options?.cwd)
314
+ : // First surface (streaming content_block_start or replay).
315
+ renderer.toolCall(toolUse, {
316
+ cwd: options?.cwd,
317
+ inputComplete: options?.inputComplete,
318
+ });
319
+ }
320
+ break;
321
+ }
322
+ case "advisor_tool_result": {
323
+ // Advisor results arrive in assistant content, including encrypted advice.
324
+ // Resolve the server tool through the normal result path without rendering
325
+ // opaque ciphertext. Server tools have no later PostToolUse hook to await.
326
+ const result = chunk.content;
327
+ unregisterHookCallback(chunk.tool_use_id);
328
+ output.push(...toAcpNotifications([
329
+ {
330
+ type: "tool_result",
331
+ tool_use_id: chunk.tool_use_id,
332
+ is_error: result.type === "advisor_tool_result_error",
333
+ content: result.type === "advisor_result"
334
+ ? result.text
335
+ : result.type === "advisor_redacted_result"
336
+ ? "Advisor guidance applied server-side."
337
+ : `Advisor error: ${result.error_code}`,
338
+ },
339
+ ], role, sessionId, toolUseCache, client, logger, options));
340
+ break;
341
+ }
342
+ case "tool_result":
343
+ case "tool_search_tool_result":
344
+ case "web_fetch_tool_result":
345
+ case "web_search_tool_result":
346
+ case "code_execution_tool_result":
347
+ case "bash_code_execution_tool_result":
348
+ case "text_editor_code_execution_tool_result":
349
+ case "mcp_tool_result": {
350
+ const wasEmitted = options?.emittedToolCalls?.has(chunk.tool_use_id) === true;
351
+ options?.emittedToolCalls?.delete(chunk.tool_use_id);
352
+ completeHookCallback(chunk.tool_use_id);
353
+ finishedToolCallId = chunk.tool_use_id;
354
+ // Why this is_error result carries harness prose instead of tool
355
+ // output (user-rejected / interrupted / …), when the SDK said so.
356
+ // Spread into the claudeCode meta of every update emitted below; the
357
+ // untracked-tool fallback can't carry it (claudeCode metas always
358
+ // carry `toolName`, which is unknown there).
359
+ const nonExecution = toolResultMeta?.get(chunk.tool_use_id);
360
+ const toolUse = toolUseCache[chunk.tool_use_id];
361
+ if (!toolUse) {
362
+ // The permission flow may have surfaced this tool_call even though
363
+ // its tool_use never reached the cache (e.g. the assistant message
364
+ // carrying it was dropped by the cancelled-turn guard and a straggler
365
+ // result landed later). Resolve the surfaced call anyway so it can't
366
+ // stay pending in the client forever; without the cache entry the
367
+ // tool name is unknown, so no claudeCode meta is attached.
368
+ if (wasEmitted) {
369
+ output.push({
370
+ sessionId,
371
+ update: {
372
+ toolCallId: chunk.tool_use_id,
373
+ sessionUpdate: "tool_call_update",
374
+ status: renderer.resultStatus("is_error" in chunk && chunk.is_error === true, nonExecution, { cancelled: options?.cancelled }),
375
+ rawOutput: chunk.content,
376
+ },
377
+ });
378
+ }
379
+ logger.error(`[claude-agent-acp] Got a tool result for tool use that wasn't tracked: ${chunk.tool_use_id}`);
380
+ break;
381
+ }
382
+ // A permission request may have surfaced a plan-rendered (TodoWrite) or
383
+ // suppressed (Task*) tool as a real tool_call so the request referenced
384
+ // a tool call the client knows about (see `ensureToolCallEmitted`,
385
+ // issue #851). The branches below never emit a tool_call_update for
386
+ // those tools, which would leave the surfaced call pending in the
387
+ // client forever — resolve it here. `wasEmitted` is only ever true for
388
+ // these tools via the permission flow: the streamed plan/suppressed
389
+ // branches don't record emissions.
390
+ if (wasEmitted && !shouldEmitToolCall(toolUse.name)) {
391
+ output.push({
392
+ sessionId,
393
+ update: {
394
+ _meta: {
395
+ claudeCode: {
396
+ toolName: toolUse.name,
397
+ ...(nonExecution ?? {}),
398
+ ...(options?.parentToolUseId ? { parentToolUseId: options.parentToolUseId } : {}),
399
+ },
400
+ },
401
+ toolCallId: chunk.tool_use_id,
402
+ sessionUpdate: "tool_call_update",
403
+ status: renderer.resultStatus("is_error" in chunk && chunk.is_error === true, nonExecution, { cancelled: options?.cancelled }),
404
+ rawOutput: chunk.content,
405
+ },
406
+ });
407
+ }
408
+ if (isTaskTool(toolUse.name)) {
409
+ // Headless/SDK sessions emit Task* tools instead of TodoWrite.
410
+ // TaskCreate / TaskUpdate mutate the accumulated task list. TaskList
411
+ // reconciles it from the SDK's authoritative snapshot, which repairs
412
+ // resumed or compacted sessions whose creating calls are no longer in
413
+ // replay history. TaskGet is read-only and remains suppressed. Plan
414
+ // updates always carry the full accumulated snapshot, mirroring the
415
+ // legacy TodoWrite behavior.
416
+ const isError = "is_error" in chunk && chunk.is_error;
417
+ let shouldEmitTaskPlan = false;
418
+ if (!isError) {
419
+ if (toolUse.name === "TaskCreate") {
420
+ applyTaskCreate(taskState, toolUse.input, parseTaskCreateOutput(toolUseResult) ?? parseTaskCreateOutput(chunk.content));
421
+ shouldEmitTaskPlan = true;
422
+ }
423
+ else if (toolUse.name === "TaskUpdate") {
424
+ const input = toolUse.input;
425
+ const output = parseTaskUpdateOutput(toolUseResult, input?.taskId) ??
426
+ parseTaskUpdateOutput(chunk.content, input?.taskId);
427
+ // Older CLI transcripts have no structured output, so retain the
428
+ // input-based fallback. When an output is available, only apply a
429
+ // confirmed update for the same task.
430
+ if (!output || (output.success && output.taskId === input?.taskId)) {
431
+ applyTaskUpdate(taskState, input);
432
+ shouldEmitTaskPlan = true;
433
+ }
434
+ }
435
+ else if (toolUse.name === "TaskList") {
436
+ const output = parseTaskListOutput(toolUseResult) ?? parseTaskListOutput(chunk.content);
437
+ if (output) {
438
+ applyTaskList(taskState, output);
439
+ shouldEmitTaskPlan = true;
440
+ }
441
+ }
442
+ }
443
+ const entries = shouldEmitTaskPlan
444
+ ? changedTaskPlanEntries(taskState, renderer.capabilities.air.client)
445
+ : undefined;
446
+ if (entries) {
447
+ update = checklistPlanUpdate(entries, options?.clientCapabilities?.plan != null);
448
+ }
449
+ }
450
+ else if (toolUse.name !== "TodoWrite") {
451
+ // A command sends its output first, then the exit and the status.
452
+ const [finalUpdate, ...rest] = renderer
453
+ .result(toolUse, chunk, {
454
+ structured: toolUseResult,
455
+ nonExecution,
456
+ cancelled: options?.cancelled,
457
+ })
458
+ .reverse();
459
+ for (const outputUpdate of rest.reverse()) {
460
+ if (options?.parentToolUseId) {
461
+ stampParentToolUseId(outputUpdate, options.parentToolUseId);
462
+ }
463
+ output.push({ sessionId, update: outputUpdate });
464
+ }
465
+ // An approved plan of the main conversation becomes the session's
466
+ // markdown plan, after the tool call's result. An approval that
467
+ // clears the context ends the tool with an error result instead, and
468
+ // the restart into the fresh context publishes that plan (see
469
+ // ExitPlanCoordinator.restart).
470
+ if (toolUse.name === "ExitPlanMode" &&
471
+ options?.clientCapabilities?.plan &&
472
+ !options.parentToolUseId &&
473
+ !("is_error" in chunk && chunk.is_error)) {
474
+ const plan = approvedPlan(toolUse.input, toolUseResult);
475
+ if (plan) {
476
+ approvedPlanUpdate = planModeUpdate(plan, renderer.capabilities.air.client ? toolUse.id : undefined);
477
+ }
478
+ }
479
+ update = finalUpdate;
480
+ }
481
+ // The tool_use is fully resolved now — drop it so a long session doesn't
482
+ // retain every tool call. The PostToolUse hook (Edit/Write diffs) closes
483
+ // over the tool name and no longer reads the cache, so pruning here is
484
+ // safe regardless of hook/result ordering.
485
+ delete toolUseCache[chunk.tool_use_id];
486
+ break;
487
+ }
488
+ case "document":
489
+ case "search_result":
490
+ case "redacted_thinking":
491
+ case "input_json_delta":
492
+ case "citations_delta":
493
+ case "signature_delta":
494
+ case "container_upload":
495
+ case "compaction":
496
+ case "compaction_delta":
497
+ case "fallback":
498
+ case "mcp_tool_listing":
499
+ break;
500
+ default:
501
+ unreachable(chunk, logger);
502
+ break;
503
+ }
504
+ if (update) {
505
+ if (options?.parentToolUseId)
506
+ stampParentToolUseId(update, options.parentToolUseId);
507
+ applyMessageId(update, options?.messageId);
508
+ // A tool result is final, so it may replace a pinned approval patch,
509
+ // for example with the error text of a rejected Edit.
510
+ if (!options?.toolCallFields ||
511
+ options.toolCallFields.apply(update, {
512
+ replacePinnedContent: finishedToolCallId !== undefined,
513
+ })) {
514
+ output.push({ sessionId, update });
515
+ }
516
+ }
517
+ if (approvedPlanUpdate)
518
+ output.push({ sessionId, update: approvedPlanUpdate });
519
+ if (finishedToolCallId !== undefined) {
520
+ // The PostToolUse hook can still send the final diff, so the fields
521
+ // stay tracked until its callback leaves the registry.
522
+ options?.toolCallFields?.finishResult(finishedToolCallId, hasHookCallback(finishedToolCallId));
523
+ }
524
+ }
525
+ return output;
526
+ }
527
+ export function streamEventToAcpNotifications(message, sessionId, toolUseCache, client, logger, options) {
528
+ const event = message.event;
529
+ const streamKey = message.parent_tool_use_id ?? "";
530
+ const streamedToolInputs = options?.streamedToolInputs;
531
+ const forwardedOptions = {
532
+ clientCapabilities: options?.clientCapabilities,
533
+ toolCallCapabilities: options?.toolCallCapabilities,
534
+ parentToolUseId: message.parent_tool_use_id,
535
+ cwd: options?.cwd,
536
+ taskState: options?.taskState,
537
+ subagentChecklists: options?.subagentChecklists,
538
+ emittedToolCalls: options?.emittedToolCalls,
539
+ toolCallFields: options?.toolCallFields,
540
+ messageId: options?.messageId,
541
+ };
542
+ switch (event.type) {
543
+ case "content_block_start": {
544
+ const block = event.content_block;
545
+ if (streamedToolInputs &&
546
+ (block.type === "tool_use" ||
547
+ block.type === "server_tool_use" ||
548
+ block.type === "mcp_tool_use")) {
549
+ let inputsForMessage = streamedToolInputs.get(streamKey);
550
+ if (!inputsForMessage) {
551
+ inputsForMessage = new Map();
552
+ streamedToolInputs.set(streamKey, inputsForMessage);
553
+ }
554
+ inputsForMessage.set(event.index, {
555
+ id: block.id,
556
+ name: block.name,
557
+ partialJson: "",
558
+ inString: false,
559
+ escaped: false,
560
+ objectDepth: 0,
561
+ arrayDepth: 0,
562
+ lastTopLevelComma: -1,
563
+ emittedThroughComma: -1,
564
+ });
565
+ }
566
+ // The input of a streamed tool_use starts empty and streams after this
567
+ // event, so the tool_call waits for the complete input.
568
+ return toAcpNotifications([block], "assistant", sessionId, toolUseCache, client, logger, {
569
+ ...forwardedOptions,
570
+ inputComplete: false,
571
+ });
572
+ }
573
+ case "content_block_delta": {
574
+ if (event.delta.type === "input_json_delta") {
575
+ const streamedInput = streamedToolInputs?.get(streamKey)?.get(event.index);
576
+ if (!streamedInput)
577
+ return [];
578
+ if (scanStreamedToolInput(streamedInput, event.delta.partial_json)) {
579
+ // Input complete: the consolidated assistant message replays the
580
+ // block with its full input and refines the call there; emitting
581
+ // here too would send a duplicate identical update.
582
+ const inputsForMessage = streamedToolInputs?.get(streamKey);
583
+ inputsForMessage?.delete(event.index);
584
+ if (inputsForMessage?.size === 0)
585
+ streamedToolInputs?.delete(streamKey);
586
+ return [];
587
+ }
588
+ if (streamedInput.lastTopLevelComma <= streamedInput.emittedThroughComma) {
589
+ return [];
590
+ }
591
+ streamedInput.emittedThroughComma = streamedInput.lastTopLevelComma;
592
+ const input = recoveredToolInput(streamedInput.partialJson.slice(0, streamedInput.lastTopLevelComma));
593
+ if (!input)
594
+ return [];
595
+ // TodoWrite and the Task* tools never surfaced a tool_call to refine.
596
+ if (!shouldEmitToolCall(streamedInput.name))
597
+ return [];
598
+ const update = toolCallRenderer(options).partialRefinement(streamedInput, input, options?.cwd);
599
+ if (message.parent_tool_use_id)
600
+ stampParentToolUseId(update, message.parent_tool_use_id);
601
+ applyMessageId(update, options?.messageId);
602
+ // A refinement resends only what changed: rawInput grows with every
603
+ // field, and title, kind, and locations usually stay the same.
604
+ if (options?.toolCallFields && !options.toolCallFields.apply(update))
605
+ return [];
606
+ return [{ sessionId, update }];
607
+ }
608
+ return toAcpNotifications([event.delta], "assistant", sessionId, toolUseCache, client, logger, forwardedOptions);
609
+ }
610
+ // No content. `ping` is a Messages-API keep-alive event that the SDK's
611
+ // `BetaRawMessageStreamEvent` union doesn't include even though the
612
+ // wire format emits it; the `as never` cast lets us no-op it here
613
+ // instead of letting it fall through to `unreachable`.
614
+ case "ping":
615
+ case "message_delta":
616
+ return [];
617
+ // A message boundary ends every input stream on this lane: message_stop is
618
+ // the normal end, and a message_start clears anything a prior message on
619
+ // the lane left behind (e.g. a stream cut short mid-block).
620
+ case "message_start":
621
+ case "message_stop":
622
+ streamedToolInputs?.delete(streamKey);
623
+ return [];
624
+ case "content_block_stop": {
625
+ const inputsForMessage = streamedToolInputs?.get(streamKey);
626
+ inputsForMessage?.delete(event.index);
627
+ if (inputsForMessage?.size === 0)
628
+ streamedToolInputs?.delete(streamKey);
629
+ return [];
630
+ }
631
+ default:
632
+ unreachable(event, logger);
633
+ return [];
634
+ }
635
+ }
package/dist/serve.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import * as v2 from "@agentclientprotocol/sdk/experimental/v2";
2
- import { type ClaudeAcpAgent, type Logger } from "./acp-agent.js";
2
+ import { type ClaudeAcpAgent } from "./acp-agent.js";
3
+ import type { Logger } from "./logger.js";
3
4
  import { type AgentHandle } from "./v2/agent.js";
4
5
  /**
5
6
  * The ACP versions that the adapter serves: `v1` or `v2` alone, or both with
@@ -1 +1 @@
1
- {"version":3,"file":"serve.d.ts","sourceRoot":"","sources":["../src/serve.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,0CAA0C,CAAC;AAC/D,OAAO,EAAc,KAAK,cAAc,EAAE,KAAK,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAE9E,OAAO,EAAc,KAAK,WAAW,EAAE,MAAM,eAAe,CAAC;AAE7D;;;GAGG;AACH,MAAM,MAAM,YAAY,GAAG,MAAM,GAAG,IAAI,GAAG,IAAI,CAAC;AAEhD;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,YAAY,CAM3E;AAED,6DAA6D;AAC7D,wBAAgB,QAAQ,CACtB,MAAM,EAAE,MAAM,GAAG,SAAS,EAC1B,OAAO,EAAE;IAAE,SAAS,EAAE,YAAY,CAAA;CAAE,GACnC;IAAE,MAAM,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;IAAC,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAA;CAAE,CAkBrD;AAED;;;;;;;;;GASG;AACH,wBAAgB,iBAAiB,CAC/B,MAAM,EAAE,MAAM,GAAG,SAAS,EAC1B,OAAO,EAAE,CAAC,KAAK,EAAE,cAAc,KAAK,IAAI,EACxC,SAAS,GAAE,YAAqB,EAChC,EAAE,SAAoB,EAAE,GAAE;IAAE,SAAS,CAAC,EAAE,CAAC,KAAK,EAAE,WAAW,KAAK,IAAI,CAAA;CAAO,GAC1E,EAAE,CAAC,mBAAmB,CAOxB"}
1
+ {"version":3,"file":"serve.d.ts","sourceRoot":"","sources":["../src/serve.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,0CAA0C,CAAC;AAC/D,OAAO,EAAc,KAAK,cAAc,EAAE,MAAM,gBAAgB,CAAC;AACjE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAE1C,OAAO,EAAc,KAAK,WAAW,EAAE,MAAM,eAAe,CAAC;AAE7D;;;GAGG;AACH,MAAM,MAAM,YAAY,GAAG,MAAM,GAAG,IAAI,GAAG,IAAI,CAAC;AAEhD;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,YAAY,CAM3E;AAED,6DAA6D;AAC7D,wBAAgB,QAAQ,CACtB,MAAM,EAAE,MAAM,GAAG,SAAS,EAC1B,OAAO,EAAE;IAAE,SAAS,EAAE,YAAY,CAAA;CAAE,GACnC;IAAE,MAAM,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;IAAC,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAA;CAAE,CAkBrD;AAED;;;;;;;;;GASG;AACH,wBAAgB,iBAAiB,CAC/B,MAAM,EAAE,MAAM,GAAG,SAAS,EAC1B,OAAO,EAAE,CAAC,KAAK,EAAE,cAAc,KAAK,IAAI,EACxC,SAAS,GAAE,YAAqB,EAChC,EAAE,SAAoB,EAAE,GAAE;IAAE,SAAS,CAAC,EAAE,CAAC,KAAK,EAAE,WAAW,KAAK,IAAI,CAAA;CAAO,GAC1E,EAAE,CAAC,mBAAmB,CAOxB"}
@@ -7,7 +7,9 @@
7
7
  * Wire contract: docs/air-extensions.md, "Session index".
8
8
  */
9
9
  import { type AgentApp, type DeleteSessionRequest, type DeleteSessionResponse, type InitializeRequest, type ListSessionsRequest, type ListSessionsResponse } from "@agentclientprotocol/sdk/unstable";
10
- import type { AcpClient, Logger, Session } from "../acp-agent.js";
10
+ import type { Session } from "../acp-agent.js";
11
+ import type { AcpClient } from "../acp-client.js";
12
+ import type { Logger } from "../logger.js";
11
13
  import { type ListSubscribeRequest, type ListSubscribeResponse, type ListUnsubscribeRequest } from "./list-subscriptions.js";
12
14
  import { SessionIndexService, type RenameSessionRequest, type SessionIdRequest, type BatchGetSessionsRequest, type BatchGetSessionsResponse } from "./service.js";
13
15
  /** What the session index keeps on each `Session`. */