@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
package/dist/acp-agent.js CHANGED
@@ -1,13 +1,12 @@
1
1
  import { agent as acpAgent, methods, ndJsonStream, RequestError, } from "@agentclientprotocol/sdk/unstable";
2
2
  import { getSessionMessages, listSessions, query, } from "@anthropic-ai/claude-agent-sdk";
3
3
  import { GOAL_ACTIONS, GOAL_CONTROL_METHOD, GOAL_EXTENSION_VERSION, goalUpdateFromPrompt, parseGoalRequest, toGoalSnapshot, } from "./goal-extension.js";
4
- import { blobResourceToClaude } from "./blob-resources.js";
5
- import { checklistPlanUpdate, resetPlanUpdates, todoWritePlanUpdate, } from "./plans.js";
4
+ import { checklistPlanUpdate, resetPlanUpdates } from "./plans.js";
6
5
  import { PromptSuggestions } from "./prompt-suggestions.js";
7
6
  import { sanitizeTitle, SessionTitles } from "./session-titles.js";
8
7
  import { AIR_NATIVE_SUBAGENT_SESSIONS_CAPABILITY, asSdkSessionNotification, clientSupportsSubagents, subagentForm, } from "./acp-subagents.js";
9
8
  import { childModelOption, isNativeSubagentControlTool, isNativeSubagentControlUpdate, NativeSubagentRuntime, nativeSubagentState, responseModelEntry, resumedNativeSubagentId, sameModelEntry, sendMessageResume, sendMessageResumePrompt, } from "./native-subagents.js";
10
- import { AIR_ASYNC_TASKS_CAPABILITY, AIR_BACKGROUND_SUBAGENTS_CAPABILITY, AIR_CUSTOM_INSTRUCTIONS_CAPABILITY, airCustomInstructions, AIR_DIFF_PATCH_CAPABILITY, AIR_PLAN_FILE_CAPABILITY, AIR_GOAL_KEY, AIR_KIND_KEY, AIR_LOAD_REPLAY_END_CAPABILITY, AIR_LOAD_REPLAY_END_KEY, AIR_RECOMMENDED_CONFIG_VALUE_CAPABILITY, AIR_SKILL_PATH_KEY, clientSupportsAirCapability, withAirMeta, } from "./air-extension.js";
9
+ import { AIR_ASYNC_TASKS_CAPABILITY, AIR_BACKGROUND_SUBAGENTS_CAPABILITY, AIR_CUSTOM_INSTRUCTIONS_CAPABILITY, airCustomInstructions, AIR_DIFF_PATCH_CAPABILITY, AIR_PLAN_FILE_CAPABILITY, AIR_GOAL_KEY, AIR_LOAD_REPLAY_END_CAPABILITY, AIR_LOAD_REPLAY_END_KEY, AIR_RECOMMENDED_CONFIG_VALUE_CAPABILITY, clientSupportsAirCapability, withAirMeta, } from "./air-extension.js";
11
10
  import * as sessionIndex from "./session-index/connection.js";
12
11
  import { AsyncTaskRuntime, backgroundBashTaskFromToolResult, backgroundedBashToolCallIds, clientSupportsAsyncTasks, } from "./async-tasks.js";
13
12
  import { SessionBackgroundWork } from "./background-work.js";
@@ -36,12 +35,12 @@ import { decodeClaudePermissionResponse } from "./permissions/response.js";
36
35
  import { SettingsManager } from "./settings.js";
37
36
  import { activeUsageLimitMessage, airSessionFailureCapabilityMeta, assistantMessageText, createSessionFailureState, isSyntheticUsageLimitMessage, providerFailureCategory, SessionFailureController, sessionFailureMeta, supportsAirSessionFailures, } from "./session-failure-extension.js";
38
37
  import { billsClaudeSubscription, claudeLoginRequiredError, claudeSubscriptionNotSupportedError, holdsNonSubscriptionCredential, refuseClaudeSubscriptionTurn, shouldHideClaudeAuth, warnClaudeSubscriptionGuardDegraded, } from "./hide-claude-auth.js";
39
- import { adapterRemoteControlCommand, claudeCodeOffersCommand, isRemoteHumanMessage, parseRemoteControlCommand, REMOTE_CONTROL_COMMAND_NAME, runRemoteControlCommand, supportsRemoteControl, } from "./remote-control.js";
38
+ import { adapterRemoteControlCommand, isRemoteHumanMessage, parseRemoteControlCommand, runRemoteControlCommand, } from "./remote-control.js";
40
39
  import { AGENT_FILE_CHANGE_REPORT_CAPABILITY, agentFileChangeReportMeta, createNativeFileChangeReporter, recordSubagentFileEdits, supportsAgentFileChangeReport, } from "./file-change-audit.js";
41
40
  import { ContextCompactionLifecycle, clientSupportsCompactionUpdates, contextCompactionMetadataFromBoundary, replayCompactSummary, } from "./context-compaction.js";
42
41
  import { IdleCompaction } from "./idle-compaction.js";
43
42
  import { clientSupportsNotices, collapseHookSpeaker, informationalNotice, MAX_NOTICE_TITLE_LENGTH, mcpServerStartupNotice, modelRefusalFallback, normalizeNoticeText, noticeOrTranscriptUpdate, sentenceCase, } from "./session-notices.js";
44
- import { applyTaskCreate, applyTaskList, applyTaskUpdate, clearHookCallbacks, completeHookCallback, createPostToolUseHook, hasHookCallback, createTaskHook, parseTaskCreateOutput, parseTaskListOutput, parseTaskUpdateOutput, planEntries, registerHookCallback, changedTaskPlanEntries, forgetPublishedTaskPlan, unregisterHookCallback, } from "./tools.js";
43
+ import { clearHookCallbacks, createPostToolUseHook, createTaskHook, changedTaskPlanEntries, forgetPublishedTaskPlan, unregisterHookCallback, } from "./tools.js";
45
44
  import { addModelUsage, DEFAULT_CONTEXT_WINDOW, getMatchingModelUsage, inferContextWindowFromModel, modelUsageIncrement, normalizeModelUsage, quotaMeta, resumedFirstResultModelUsage, snapshotFromUsage, tallyTotal, totalTokens, ZERO_USAGE, } from "./session-usage.js";
46
45
  import { previewPatchContent } from "./diff.js";
47
46
  import { backgroundedBashToolCall, withRunningTerminal } from "./tool-calls/background.js";
@@ -49,15 +48,13 @@ import { ChangedMetaFilter } from "./tool-calls/changed-meta-filter.js";
49
48
  import { ToolCallFieldTracker } from "./tool-calls/field-tracker.js";
50
49
  import { ClientCapabilities as ToolCallClientCapabilities } from "./tool-calls/client-capabilities.js";
51
50
  import { AcpToolCallRenderer, isFinalToolCallStatus, } from "./tool-calls/renderer.js";
52
- import { resolveSkillPath } from "./tool-calls/reporters/interaction.js";
53
51
  import { messageLoopYielder, nodeToWebReadable, nodeToWebWritable, Pushable, raceTimeoutAndAbort, unreachable, } from "./utils.js";
54
- import { acceptedPlanToolResult, approvedPlan, ExitPlanCoordinator, isExitPlanInterruptionResult, observeExitPlanToolResults, planModeUpdate, } from "./exit-plan.js";
52
+ import { acceptedPlanToolResult, ExitPlanCoordinator, isExitPlanInterruptionResult, observeExitPlanToolResults, } from "./exit-plan.js";
55
53
  import { AGENT_CONFIG_ID, DEFAULT_AGENT_ID } from "./session-config-ids.js";
56
- import { parseToolResultMeta } from "./tool-result-meta.js";
57
- import { markerTagText, TASK_NOTIFICATION_TAG, taskNotificationsOf, } from "./task-notifications.js";
54
+ import { taskNotificationsOf } from "./task-notifications.js";
58
55
  import { formatUsageResponse, isUsageCommandText, parseUsageResponse } from "./usage-markdown.js";
59
56
  export { DEFAULT_AGENT_ID } from "./session-config-ids.js";
60
- import { MCP_AVAILABLE_COMMAND, parseMcpCommand, runMcpCommand } from "./mcp-command.js";
57
+ import { parseMcpCommand, runMcpCommand } from "./mcp-command.js";
61
58
  import { configuredSettings, resolveThinkingConfig } from "./session-env.js";
62
59
  import { MODE_CONFIG_ID, resolveInitialPermissionMode, SessionModeManager, } from "./session-mode.js";
63
60
  import { aliasResumedModelRow, applyAvailableModelsAllowlist, getAvailableModels, MODEL_CONFIG_ID, modelDisplayName, modelEntryFor, narrowToGatewayModels, resolveModelPreference, withCurrentModelInfo, } from "./session-model.js";
@@ -75,8 +72,17 @@ export { AGENT_CONFIG_ID, BUILTIN_AGENT_NAMES, buildConfigOptions, clientSupport
75
72
  export { createFastModeConfigOption, FAST_MODE_CONFIG_ID, FAST_MODE_OFF, FAST_MODE_ON, fastModeStateEnabled, normalizeFastModeDisabledReason, resolveFastModeEnabled, } from "./session-fast-mode.js";
76
73
  export { EFFORT_CONFIG_ID, settingsEffortForModel } from "./session-effort.js";
77
74
  export { applyAvailableModelsAllowlist, matchResumedModel, MODEL_CONFIG_ID, resolveModelPreference, } from "./session-model.js";
78
- // Moved to result-end.ts; kept as an export for consumers that deep-import dist/acp-agent.js.
79
- export { isLoginRequiredText } from "./result-end.js";
75
+ import { isReplayHiddenMetaMessage, isSyntheticLoginMessage, LOCAL_ONLY_COMMANDS, stripLocalCommandMetadata, } from "./message-filters.js";
76
+ import { promptToClaude, SUPPORTED_PROMPT_CONTENT_TYPES } from "./prompt-to-claude.js";
77
+ import { AUTONOMOUS_RESULT_ORIGINS, isAbortedResult } from "./result-end.js";
78
+ import { messageIdForGrouping, stampParentToolUseId, streamEventToAcpNotifications, toAcpNotifications, } from "./sdk-to-acp.js";
79
+ import { getAvailableSlashCommands } from "./slash-commands.js";
80
+ // Moved to their own modules; kept as exports for consumers that deep-import dist/acp-agent.js.
81
+ export { AUTONOMOUS_RESULT_ORIGINS, isAbortedResult, isLoginRequiredText } from "./result-end.js";
82
+ export { isLocalCommandMetadata, isReplayHiddenMetaMessage, isSyntheticLoginMessage, stripLocalCommandMetadata, } from "./message-filters.js";
83
+ export { promptToClaude } from "./prompt-to-claude.js";
84
+ export { messageIdForGrouping, streamEventToAcpNotifications, toAcpNotifications, } from "./sdk-to-acp.js";
85
+ export { getAvailableSlashCommands } from "./slash-commands.js";
80
86
  /** Claude CLI emits this synthetic result when an interrupted cycle ends on
81
87
  * queued user input before producing any assistant content. It is a hand-off
82
88
  * marker, not the outcome of the replacement prompt that may already be
@@ -250,35 +256,6 @@ function parseSteerRequest(params) {
250
256
  _meta: _meta,
251
257
  };
252
258
  }
253
- /** Result-message origin kinds that mark an AUTONOMOUS cycle — work the
254
- * model did on its own (a task-notification followup, a peer/coordinator/
255
- * observer message it handled) rather than the user's prompt. Absent,
256
- * `human`, and `channel` origins are the user's own turn (this adapter's
257
- * prompts arrive as the ACP channel on some CLI configurations — ALL
258
- * channel servers are treated as user, so a foreign channel integration's
259
- * autonomously-handled result is misclassified as the user's; accepted,
260
- * see below), and `auto-continuation` continues the user's turn, so its
261
- * result is the turn's real terminal.
262
- *
263
- * Deliberately fail-OPEN: an unknown future kind defaults to the user
264
- * lane — including `unclassified` (SDK 0.3.232+), the CLI's own "couldn't
265
- * attribute this" marker, which gets the same safe default. Misrouting a
266
- * USER result into the autonomous lane hangs the prompt un-detectably
267
- * (the result is skipped, its trailing idle absorbed as owed, so the
268
- * #825 detector can't fire); misrouting an autonomous result into the
269
- * user lane is the bounded misattribution class this set exists to
270
- * reduce.
271
- *
272
- * Exception: a result from one of these origins that names a pending prompt
273
- * in `user_message_uuids` consumed that folded prompt and takes the user
274
- * lane (see the result handler). */
275
- export const AUTONOMOUS_RESULT_ORIGINS = new Set([
276
- "task-notification",
277
- "peer",
278
- "coordinator",
279
- "observer",
280
- "observer-activity",
281
- ]);
282
259
  /** The foreground work of a session: a prompt's turn, from its insertion
283
260
  * until its result, or a model cycle that Claude Code started on its own
284
261
  * (see `startAutonomousCycle`). At most one cycle runs at a time, so a
@@ -458,16 +435,6 @@ export function computeSessionFingerprint(params) {
458
435
  /** The JSON-RPC code ACP assigns to `authRequired`. Read from the SDK so it
459
436
  * cannot drift from the errors this agent throws. */
460
437
  const AUTH_REQUIRED_CODE = RequestError.authRequired().code;
461
- /** Attributes a report to the Agent/Task tool call of the subagent that made it. */
462
- function stampParentToolUseId(update, parentToolUseId) {
463
- update._meta = {
464
- ...update._meta,
465
- claudeCode: {
466
- ...(update._meta?.claudeCode ?? {}),
467
- parentToolUseId,
468
- },
469
- };
470
- }
471
438
  const SUBAGENT_TRANSCRIPT_CAPABILITY = "subagent-transcript";
472
439
  function supportsSubagentTranscript(capabilities) {
473
440
  return capabilities?._meta?.[SUBAGENT_TRANSCRIPT_CAPABILITY] === true;
@@ -500,203 +467,10 @@ function stripSubagentTextAndThinking(content) {
500
467
  !("type" in item) ||
501
468
  (item.type !== "text" && item.type !== "thinking"));
502
469
  }
503
- /**
504
- * Advance the lexer state across the fragment appended since the last delta:
505
- * just enough JSON awareness (string/escape, nesting depth) to spot commas
506
- * that sit at the top level of the input object — everything before such a
507
- * comma is a set of complete fields. Returns true once the input object's
508
- * closing brace arrives.
509
- *
510
- * The lexer reads the fragment itself, never `partialJson` by index. V8 keeps a
511
- * string built with `+=` as a chain of parts, and the first index access
512
- * copies the whole chain into one flat string. An index scan of `partialJson`
513
- * would copy the whole input on each delta, so a large Write would cost
514
- * quadratic time. A test in `acp-agent.test.ts` checks this.
515
- */
516
- function scanStreamedToolInput(state, fragment) {
517
- const offset = state.partialJson.length;
518
- state.partialJson += fragment;
519
- let complete = false;
520
- for (let index = 0; index < fragment.length; index++) {
521
- const character = fragment[index];
522
- if (state.inString) {
523
- if (state.escaped) {
524
- state.escaped = false;
525
- }
526
- else if (character === "\\") {
527
- state.escaped = true;
528
- }
529
- else if (character === '"') {
530
- state.inString = false;
531
- }
532
- continue;
533
- }
534
- if (character === '"') {
535
- state.inString = true;
536
- }
537
- else if (character === "{") {
538
- state.objectDepth++;
539
- }
540
- else if (character === "}") {
541
- state.objectDepth--;
542
- if (state.objectDepth === 0) {
543
- complete = true;
544
- }
545
- }
546
- else if (character === "[") {
547
- state.arrayDepth++;
548
- }
549
- else if (character === "]") {
550
- state.arrayDepth--;
551
- }
552
- else if (character === "," && state.objectDepth === 1 && state.arrayDepth === 0) {
553
- state.lastTopLevelComma = offset + index;
554
- }
555
- }
556
- return complete;
557
- }
558
- /** Parse the complete top-level fields before a top-level comma by closing the
559
- * object at that boundary. */
560
- function recoveredToolInput(prefix) {
561
- try {
562
- const value = JSON.parse(prefix + "}");
563
- return value !== null && typeof value === "object" && !Array.isArray(value)
564
- ? value
565
- : undefined;
566
- }
567
- catch {
568
- return undefined;
569
- }
570
- }
571
470
  /** Returned to clients when a prompt or cancel targets a session whose SDK
572
471
  * query stream has already ended (ran to `done` or died). The stream is not
573
472
  * revivable, so the only recovery is a fresh session. */
574
473
  const SESSION_ENDED_MESSAGE = "The Claude Agent session has ended. Please start a new session.";
575
- // Slash commands that the SDK handles locally without replaying the user
576
- // message and without invoking the model.
577
- const LOCAL_ONLY_COMMANDS = new Set(["/context", "/heapdump", "/extra-usage"]);
578
- // Commands whose marker-only transcript records are ACP/client-local UI noise,
579
- // not model-visible user prompts. Marker-only custom slash skills are not in
580
- // this list, so replay can reconstruct them from `<command-name>`/`<command-args>`.
581
- const REPLAY_HIDDEN_COMMANDS = new Set([
582
- ...LOCAL_ONLY_COMMANDS,
583
- "/compact",
584
- "/model",
585
- "/mcp",
586
- "/status",
587
- "/usage",
588
- ]);
589
- // The Claude SDK persists local slash command invocations (e.g. `/model`) and
590
- // their output as user messages in the session transcript, wrapping the
591
- // payload in these XML-like markers that the CLI uses for its own display.
592
- // The live prompt loop drops them; replay must strip them too or they leak
593
- // into the UI on session/load.
594
- const LOCAL_COMMAND_MARKERS = [
595
- "command-name",
596
- "command-message",
597
- "command-args",
598
- "local-command-stdout",
599
- "local-command-stderr",
600
- ].map((tag) => ({ open: `<${tag}>`, close: `</${tag}>` }));
601
- // Context the CLI injects into a user turn to steer the model, appended to
602
- // whatever the user typed. Nobody wrote it and no client sees it live — the
603
- // prompt loop's user-message skip covers the whole message — but it is
604
- // persisted alongside that prose, so replay would hand the client a prompt
605
- // with instructions in it the user never gave. A `task-notification` tells the
606
- // model that a background task stopped; live, the SDK `task_notification`
607
- // frame reports the same stop, so replay restores the task state from it (see
608
- // taskNotificationsOf) instead of showing it.
609
- const INJECTED_CONTEXT_MARKERS = ["system-reminder", TASK_NOTIFICATION_TAG].map((tag) => ({
610
- open: `<${tag}>`,
611
- close: `</${tag}>`,
612
- }));
613
- // Everything a replayed user message may be wrapped in that is not speech.
614
- const TRANSCRIPT_MARKERS = [...LOCAL_COMMAND_MARKERS, ...INJECTED_CONTEXT_MARKERS];
615
- // Single-pass scanner that removes each `<tag>…</tag>` marker (matching the
616
- // nearest closing tag of the same name, like a lazy regex would).
617
- function stripMarkerTags(text) {
618
- const dead = new Set();
619
- let result = "";
620
- let copiedUpTo = 0;
621
- let i = 0;
622
- while (i < text.length) {
623
- if (text[i] === "<") {
624
- const marker = TRANSCRIPT_MARKERS.find((m) => !dead.has(m.open) && text.startsWith(m.open, i));
625
- if (marker) {
626
- const end = text.indexOf(marker.close, i + marker.open.length);
627
- if (end !== -1) {
628
- result += text.slice(copiedUpTo, i);
629
- i = copiedUpTo = end + marker.close.length;
630
- continue;
631
- }
632
- // No closing marker remains anywhere ahead, and `indexOf` only ever
633
- // searches forward from here on, so stop treating this tag as an
634
- // opener — that avoids rescanning the tail for it on every match.
635
- dead.add(marker.open);
636
- }
637
- }
638
- i++;
639
- }
640
- return result + text.slice(copiedUpTo);
641
- }
642
- function hasMarkerTag(text, tag) {
643
- return markerTagText(text, tag) !== undefined;
644
- }
645
- function commandInvocationFromMarkerOnlyText(text) {
646
- if (hasMarkerTag(text, "local-command-stdout") || hasMarkerTag(text, "local-command-stderr")) {
647
- return null;
648
- }
649
- const commandName = markerTagText(text, "command-name")?.trim();
650
- if (!commandName?.startsWith("/"))
651
- return null;
652
- if (REPLAY_HIDDEN_COMMANDS.has(commandName.split(" ", 1)[0]))
653
- return null;
654
- const commandArgs = markerTagText(text, "command-args")?.trim();
655
- return commandArgs ? `${commandName} ${commandArgs}` : commandName;
656
- }
657
- function stripLocalCommandMetadataText(text) {
658
- const stripped = stripMarkerTags(text);
659
- if (stripped.trim() !== "")
660
- return stripped;
661
- return commandInvocationFromMarkerOnlyText(text);
662
- }
663
- /**
664
- * Return user-message content with local-command and injected-context marker
665
- * tags removed, or `null` if nothing meaningful remains (caller should skip
666
- * the message). Preserves real prose that's mixed in alongside the markers —
667
- * e.g. a message like `<command-name>…</command-name>hi` becomes `hi`, and
668
- * `hi<system-reminder>…</system-reminder>` becomes `hi`.
669
- */
670
- export function stripLocalCommandMetadata(content) {
671
- if (typeof content === "string") {
672
- return stripLocalCommandMetadataText(content);
673
- }
674
- if (!Array.isArray(content))
675
- return content;
676
- const kept = [];
677
- for (const block of content) {
678
- if (block &&
679
- typeof block === "object" &&
680
- "type" in block &&
681
- block.type === "text" &&
682
- "text" in block &&
683
- typeof block.text === "string") {
684
- const stripped = stripLocalCommandMetadataText(block.text);
685
- if (stripped === null)
686
- continue;
687
- kept.push({ ...block, text: stripped });
688
- }
689
- else {
690
- kept.push(block);
691
- }
692
- }
693
- if (kept.length === 0)
694
- return null;
695
- return kept;
696
- }
697
- export function isLocalCommandMetadata(content) {
698
- return stripLocalCommandMetadata(content) === null;
699
- }
700
474
  /**
701
475
  * True for a user record that the CLI wrote to tell the model that a
702
476
  * background task stopped. A `subkind` marks the delivery of a prompt, for
@@ -713,69 +487,6 @@ const LIMIT_FAILURE_CATEGORY = {
713
487
  error_max_turns: "context_exhausted",
714
488
  error_max_structured_output_retries: "provider_error",
715
489
  };
716
- /**
717
- * True for the synthetic assistant message the CLI injects into the transcript
718
- * when a turn fails authentication (e.g. "Not logged in · Please run /login",
719
- * "Session expired. Please run /login to sign in again."). The `/login`
720
- * instruction is Claude Code TUI-specific and meaningless to ACP clients
721
- * (issue #863). The live prompt loop suppresses the text and fails the turn
722
- * with `authRequired` so the client can run its own auth flow; replay must
723
- * skip it too — both for parity with what the client saw live and because the
724
- * message stays in the transcript forever, so it would resurface on every
725
- * session/load even after the user has logged back in.
726
- *
727
- * Takes the API message (`message.message`), which replay only knows as
728
- * `unknown`. The persisted record's structured `error` marker is stripped by
729
- * `getSessionMessages`, and the CLI does not always set it to
730
- * `authentication_failed` anyway: an expired login with no refresh token
731
- * ("Login expired · Run /login to sign in again, …") arrives as
732
- * `invalid_request`. So the synthetic model + text is what both paths match on.
733
- * Usage-limit banners are excluded because some of them also mention `/login`
734
- * (to switch accounts) and have their own handling.
735
- */
736
- export function isSyntheticLoginMessage(apiMessage) {
737
- if (!apiMessage || typeof apiMessage !== "object") {
738
- return false;
739
- }
740
- const { model, content } = apiMessage;
741
- if (model !== "<synthetic>" || !Array.isArray(content) || content.length !== 1) {
742
- return false;
743
- }
744
- const block = content[0];
745
- return (!!block &&
746
- block.type === "text" &&
747
- typeof block.text === "string" &&
748
- isLoginRequiredText(block.text) &&
749
- !isSyntheticUsageLimitMessage(apiMessage));
750
- }
751
- /** Origin kinds of the meta user messages `getSessionMessages` returns since
752
- * SDK 0.3.284 (messages from other agents, sessions and channels). */
753
- const REPLAY_HIDDEN_META_ORIGIN_KINDS = new Set([
754
- "peer",
755
- "channel",
756
- "observer",
757
- "observer-activity",
758
- "slack-ping",
759
- ]);
760
- /**
761
- * True for a transcript message delivered to the model from another agent,
762
- * session or channel. Since SDK 0.3.284 `getSessionMessages` returns these as
763
- * `is_meta` user messages whose content is the full harness framing (envelope
764
- * XML plus the "not typed by your user" preamble). The live prompt loop never
765
- * renders them, so replay skips them too rather than presenting them as text
766
- * the user typed. Other `is_meta` messages (compact summaries) are kept.
767
- *
768
- * `is_meta` and `origin` are runtime fields not declared on `SessionMessage`.
769
- */
770
- export function isReplayHiddenMetaMessage(message) {
771
- if (!message || typeof message !== "object")
772
- return false;
773
- const { type, is_meta, origin } = message;
774
- return (type === "user" &&
775
- is_meta === true &&
776
- typeof origin?.kind === "string" &&
777
- REPLAY_HIDDEN_META_ORIGIN_KINDS.has(origin.kind));
778
- }
779
490
  /**
780
491
  * Bridges {@link AcpClient} to the connection-scoped {@link AgentContext}
781
492
  * exposed by `AgentApp.connect(...)` as `connection.client`. The peer handle is
@@ -8681,11 +8392,6 @@ function blocksForeground(session, agentID) {
8681
8392
  }
8682
8393
  return true;
8683
8394
  }
8684
- /** Whether Claude Code ended the work of `result` because an interrupt
8685
- * stopped it, while the model streamed or while a tool ran. */
8686
- export function isAbortedResult(result) {
8687
- return (result.terminal_reason === "aborted_streaming" || result.terminal_reason === "aborted_tools");
8688
- }
8689
8395
  /**
8690
8396
  * Build the `data` payload attached to a `RequestError.internalError` when we
8691
8397
  * have a categorical error — from the Claude SDK, or one of the adapter's own
@@ -8699,274 +8405,6 @@ export function isAbortedResult(result) {
8699
8405
  function errorKindData(errorKind) {
8700
8406
  return errorKind ? { errorKind } : undefined;
8701
8407
  }
8702
- export function getAvailableSlashCommands(commands,
8703
- // Names the CLI tagged terminal-bound on `system`/init (their UX lives in
8704
- // the CLI's own terminal, which ACP clients aren't) — filtered alongside
8705
- // the static list. Raw CLI names, matched before the MCP rename.
8706
- terminalCommands,
8707
- // The session cwd of an AIR client, or undefined for every other client.
8708
- // AIR gets the kind and the SKILL.md path of each skill command.
8709
- airSkillCwd,
8710
- // The resolved SKILL.md paths of the session, keyed by the cwd and the name.
8711
- skillPaths, query,
8712
- // The skill files Claude Code reports (`getContextUsage().skills.skillFrontmatter`).
8713
- // A listed skill gets its path from here; one that is not listed, or has no
8714
- // path (remote connections), is looked up on disk.
8715
- skillFiles) {
8716
- // The container listings of this one pass, so a list of a hundred commands lists each container once.
8717
- const skillScans = new Map();
8718
- const skillPath = (name, cwd) => {
8719
- const key = `${cwd}\0${name}`;
8720
- if (skillPaths?.has(key))
8721
- return skillPaths.get(key);
8722
- const resolved = resolveSkillPath(name, cwd, skillScans);
8723
- skillPaths?.set(key, resolved);
8724
- return resolved;
8725
- };
8726
- const UNSUPPORTED_COMMANDS = [
8727
- "clear",
8728
- "cost",
8729
- "keybindings-help",
8730
- "login",
8731
- "logout",
8732
- "output-style:new",
8733
- "release-notes",
8734
- "todos",
8735
- ];
8736
- const remoteControlCommands = query && supportsRemoteControl(query)
8737
- ? [
8738
- {
8739
- name: REMOTE_CONTROL_COMMAND_NAME,
8740
- description: "Continue this session from claude.ai/code or the Claude mobile app; `off` disconnects",
8741
- input: { hint: "[session name | off]" },
8742
- },
8743
- ]
8744
- : [];
8745
- // The adapter replaces the terminal text of `/mcp` and runs its actions,
8746
- // even when Claude Code tags the command terminal-bound.
8747
- const advertised = commands
8748
- .filter((command) => command.name !== "mcp" && !terminalCommands?.includes(command.name))
8749
- .map((command) => {
8750
- const input = command.argumentHint
8751
- ? {
8752
- hint: Array.isArray(command.argumentHint)
8753
- ? command.argumentHint.join(" ")
8754
- : command.argumentHint,
8755
- }
8756
- : null;
8757
- let name = command.name;
8758
- const mcpPrompt = command.name.endsWith(" (MCP)");
8759
- if (mcpPrompt) {
8760
- name = `mcp:${name.replace(" (MCP)", "")}`;
8761
- }
8762
- const skillFile = airSkillCwd && !mcpPrompt ? skillFiles?.get(command.name) : undefined;
8763
- const skillMdPath = skillFile?.path ??
8764
- (airSkillCwd && !command.builtin && !mcpPrompt
8765
- ? skillPath(command.name, airSkillCwd)
8766
- : undefined);
8767
- return {
8768
- name,
8769
- description: command.description || "",
8770
- input,
8771
- ...(skillMdPath
8772
- ? {
8773
- _meta: withAirMeta(withAirMeta(undefined, AIR_KIND_KEY, "skill"), AIR_SKILL_PATH_KEY, skillMdPath),
8774
- }
8775
- : skillFile
8776
- ? // A skill without a file (bundled with the CLI, like `simplify`, or a remote connection): kind only.
8777
- { _meta: withAirMeta(undefined, AIR_KIND_KEY, "skill") }
8778
- : {}),
8779
- };
8780
- })
8781
- .filter((command) => !UNSUPPORTED_COMMANDS.includes(command.name));
8782
- // Command names must not contain whitespace and must be unique. A name
8783
- // like "my command" is dropped, and of two commands named "review" only the
8784
- // first is kept.
8785
- const names = new Set();
8786
- return [
8787
- ...advertised,
8788
- MCP_AVAILABLE_COMMAND,
8789
- ...remoteControlCommands.filter((command) => !claudeCodeOffersCommand(commands, terminalCommands, command.name)),
8790
- ].filter((command) => {
8791
- if (/\s/.test(command.name) || names.has(command.name))
8792
- return false;
8793
- names.add(command.name);
8794
- return true;
8795
- });
8796
- }
8797
- function formatUriAsLink(uri) {
8798
- try {
8799
- if (uri.startsWith("file://")) {
8800
- const path = uri.slice(7); // Remove "file://"
8801
- const name = path.split("/").pop() || path;
8802
- return `[@${name}](${uri})`;
8803
- }
8804
- else if (uri.startsWith("zed://")) {
8805
- const parts = uri.split("/");
8806
- const name = parts[parts.length - 1] || uri;
8807
- return `[@${name}](${uri})`;
8808
- }
8809
- return uri;
8810
- }
8811
- catch {
8812
- return uri;
8813
- }
8814
- }
8815
- /** The prompt content block types that `promptToClaude` converts. The agent
8816
- * advertises no `audio` prompt capability. */
8817
- const SUPPORTED_PROMPT_CONTENT_TYPES = [
8818
- "text",
8819
- "image",
8820
- "resource_link",
8821
- "resource",
8822
- ];
8823
- export function promptToClaude(prompt) {
8824
- const content = [];
8825
- const context = [];
8826
- const firstText = prompt.prompt.find((chunk) => chunk.type === "text");
8827
- for (const chunk of prompt.prompt) {
8828
- switch (chunk.type) {
8829
- case "text": {
8830
- let text = chunk.text;
8831
- // A slash command is the first text block. Change
8832
- // `/mcp:server:command args` to `/server:command (MCP) args`; the
8833
- // arguments can span lines.
8834
- const mcpMatch = chunk === firstText ? text.match(/^\/mcp:([^:\s]+):(\S+)(?:\s+([\s\S]*))?$/) : null;
8835
- if (mcpMatch) {
8836
- const [, server, command, args] = mcpMatch;
8837
- text = `/${server}:${command} (MCP)${args ? ` ${args}` : ""}`;
8838
- }
8839
- content.push({ type: "text", text });
8840
- break;
8841
- }
8842
- case "resource_link": {
8843
- const formattedUri = formatUriAsLink(chunk.uri);
8844
- content.push({
8845
- type: "text",
8846
- text: formattedUri,
8847
- });
8848
- break;
8849
- }
8850
- case "resource": {
8851
- const { uri } = chunk.resource;
8852
- // A blob resource becomes an image or document block, or its decoded
8853
- // text. A v1 prompt skips a blob of any other type, e.g.
8854
- // `application/zip`; a v2 prompt rejects it (see `v1PromptRequest`).
8855
- const blob = "blob" in chunk.resource ? blobResourceToClaude(chunk.resource) : undefined;
8856
- const text = "text" in chunk.resource
8857
- ? chunk.resource.text
8858
- : blob?.kind === "text"
8859
- ? blob.text
8860
- : undefined;
8861
- if (blob?.kind === "image" || blob?.kind === "document") {
8862
- content.push({ type: "text", text: formatUriAsLink(uri) }, blob.block);
8863
- }
8864
- else if (text !== undefined) {
8865
- content.push({ type: "text", text: formatUriAsLink(uri) });
8866
- context.push({
8867
- type: "text",
8868
- text: `\n<context ref="${uri}">\n${text}\n</context>`,
8869
- });
8870
- }
8871
- break;
8872
- }
8873
- case "image":
8874
- if (chunk.data) {
8875
- content.push({
8876
- type: "image",
8877
- source: {
8878
- type: "base64",
8879
- data: chunk.data,
8880
- media_type: chunk.mimeType,
8881
- },
8882
- });
8883
- }
8884
- else if (chunk.uri && chunk.uri.startsWith("http")) {
8885
- content.push({
8886
- type: "image",
8887
- source: {
8888
- type: "url",
8889
- url: chunk.uri,
8890
- },
8891
- });
8892
- }
8893
- break;
8894
- // Ignore audio and other unsupported types
8895
- default:
8896
- break;
8897
- }
8898
- }
8899
- content.push(...context);
8900
- return {
8901
- type: "user",
8902
- message: {
8903
- role: "user",
8904
- content: content,
8905
- },
8906
- session_id: prompt.sessionId,
8907
- parent_tool_use_id: null,
8908
- // ACP prompts are the user's own input relayed by the client. Stamp the
8909
- // provenance explicitly: per the SDK, a host wrapping keyboard input must
8910
- // send `{kind: "human"}` — an absent `origin` is treated as unattributed
8911
- // and fails closed at the CLI's strict isHuman() trust gates (e.g. the
8912
- // ultracode keyword opt-in honors only human-originated turns).
8913
- origin: { kind: "human" },
8914
- };
8915
- }
8916
- /**
8917
- * Resolves the ACP `messageId` for a Claude SDK message (live) or a persisted
8918
- * transcript message (replay) so chunk grouping is identical in both views.
8919
- *
8920
- * Assistant turns are keyed by the Anthropic API message id (`message.id`),
8921
- * which is identical at `message_start`, on the consolidated assistant message,
8922
- * and in the persisted transcript — unlike the per-`stream_event` uuid, which is
8923
- * unique per event and never persisted. User messages have no API id, but they
8924
- * are never streamed, so their (stable) SDK uuid is used instead. ACP message
8925
- * ids are opaque strings, so no particular format is required.
8926
- */
8927
- export function messageIdForGrouping(message) {
8928
- if (message.type === "assistant") {
8929
- const inner = message.message;
8930
- const apiId = inner && typeof inner === "object" && "id" in inner
8931
- ? inner.id
8932
- : undefined;
8933
- if (typeof apiId === "string" && apiId.length > 0) {
8934
- return apiId;
8935
- }
8936
- }
8937
- return typeof message.uuid === "string" && message.uuid.length > 0 ? message.uuid : undefined;
8938
- }
8939
- /**
8940
- * Stamps an ACP `messageId` onto a session update, but only on the message/
8941
- * thought chunk variants that carry one — tool_call/plan/etc. updates never do.
8942
- * No-op when `messageId` is falsy, so callers can pass it through unconditionally.
8943
- */
8944
- function applyMessageId(update, messageId) {
8945
- if (messageId &&
8946
- (update.sessionUpdate === "agent_message_chunk" ||
8947
- update.sessionUpdate === "user_message_chunk" ||
8948
- update.sessionUpdate === "agent_thought_chunk")) {
8949
- update.messageId = messageId;
8950
- }
8951
- }
8952
- /** Built-in tools that drive the task list (headless/SDK sessions use these
8953
- * instead of TodoWrite). Their tool_use/tool_result are surfaced as `plan`
8954
- * snapshots rather than as tool_calls. */
8955
- function isTaskTool(toolName) {
8956
- return (toolName === "TaskCreate" ||
8957
- toolName === "TaskUpdate" ||
8958
- toolName === "TaskList" ||
8959
- toolName === "TaskGet");
8960
- }
8961
- /** Whether the streamed tool_use path surfaces this tool as a standalone
8962
- * `tool_call`. TodoWrite is rendered as a `plan` and Task* tools are
8963
- * suppressed (their plan snapshot is emitted at tool_result time), so neither
8964
- * produces a streamed tool_call/tool_call_update — which means a
8965
- * permission-surfaced tool_call for them (see `ensureToolCallEmitted`) must be
8966
- * resolved explicitly at tool_result time. */
8967
- function shouldEmitToolCall(toolName) {
8968
- return toolName !== "TodoWrite" && !isTaskTool(toolName);
8969
- }
8970
8408
  const MAX_TOOL_CALL_PARENTS = 1000;
8971
8409
  /** Records the Agent/Task call that started the subagent making `toolCallId`. */
8972
8410
  function recordToolCallParent(session, toolCallId, parentToolUseId) {
@@ -9043,19 +8481,6 @@ function forgetForegroundToolCall(session, toolCallId) {
9043
8481
  function toolCallFieldsOf(session) {
9044
8482
  return (session.toolCallFields ??= new ToolCallFieldTracker());
9045
8483
  }
9046
- /**
9047
- * Convert an SDKAssistantMessage (Claude) to a SessionNotification (ACP).
9048
- * Only handles text, image, and thinking chunks for now.
9049
- */
9050
- /**
9051
- * The renderer of the notification functions: the agent's tool call
9052
- * capabilities when they are passed, else those of the ACP capabilities.
9053
- */
9054
- function toolCallRenderer(options) {
9055
- return options?.toolCallCapabilities
9056
- ? new AcpToolCallRenderer(options.toolCallCapabilities, options.replay)
9057
- : AcpToolCallRenderer.for(options?.clientCapabilities, options?.replay);
9058
- }
9059
8484
  const MAX_RESOLVED_TOOL_NAMES = 1000;
9060
8485
  /** Keeps the tool names of the tool results in `content` before the tool use cache drops them. */
9061
8486
  function rememberResolvedToolNames(session, content) {
@@ -9077,489 +8502,6 @@ function rememberResolvedToolNames(session, content) {
9077
8502
  }
9078
8503
  }
9079
8504
  }
9080
- export function toAcpNotifications(content, role, sessionId, toolUseCache, client, logger, options) {
9081
- const taskState = options?.taskState ?? new Map();
9082
- const registerHooks = options?.registerHooks !== false;
9083
- const renderer = toolCallRenderer(options);
9084
- if (typeof content === "string") {
9085
- if (content.length === 0) {
9086
- return [];
9087
- }
9088
- const update = {
9089
- sessionUpdate: role === "assistant" ? "agent_message_chunk" : "user_message_chunk",
9090
- content: {
9091
- type: "text",
9092
- text: content,
9093
- },
9094
- };
9095
- applyMessageId(update, options?.messageId);
9096
- if (options?.parentToolUseId)
9097
- stampParentToolUseId(update, options.parentToolUseId);
9098
- return [{ sessionId, update }];
9099
- }
9100
- // `tool_use_result` is message-level and carries no tool_use_id of its own:
9101
- // it describes "the" tool_result block of the message it rode in on. If
9102
- // several tool_result blocks were ever batched into one message it couldn't
9103
- // be attributed, so it is only honored when the message carries exactly one.
9104
- const toolUseResult = options?.toolUseResult !== undefined &&
9105
- content.filter((c) => typeof c === "object" && c !== null && c.type === "tool_result")
9106
- .length === 1
9107
- ? options.toolUseResult
9108
- : undefined;
9109
- // Unlike `tool_use_result`, entries carry their own tool_use_id, so batched
9110
- // messages need no single-block guard.
9111
- const toolResultMeta = parseToolResultMeta(options?.toolResultMeta);
9112
- const output = [];
9113
- // Only handle the first chunk for streaming; extend as needed for batching
9114
- for (const chunk of content) {
9115
- let update = null;
9116
- // The tool call that this chunk finishes, if it is a tool result.
9117
- let finishedToolCallId;
9118
- // The plan that this chunk approves, if it is an ExitPlanMode result.
9119
- let approvedPlanUpdate;
9120
- switch (chunk.type) {
9121
- case "text":
9122
- case "text_delta": {
9123
- if (chunk.text) {
9124
- update = {
9125
- sessionUpdate: role === "assistant" ? "agent_message_chunk" : "user_message_chunk",
9126
- content: {
9127
- type: "text",
9128
- text: chunk.text,
9129
- },
9130
- };
9131
- }
9132
- break;
9133
- }
9134
- case "image":
9135
- update = {
9136
- sessionUpdate: role === "assistant" ? "agent_message_chunk" : "user_message_chunk",
9137
- content: {
9138
- type: "image",
9139
- data: chunk.source.type === "base64" ? chunk.source.data : "",
9140
- mimeType: chunk.source.type === "base64" ? chunk.source.media_type : "",
9141
- uri: chunk.source.type === "url" ? chunk.source.url : undefined,
9142
- },
9143
- };
9144
- break;
9145
- case "thinking":
9146
- case "thinking_delta": {
9147
- // Recent models default `thinking.display` to "omitted", which streams
9148
- // signature-only thinking blocks whose text is empty.
9149
- if (chunk.thinking) {
9150
- update = {
9151
- sessionUpdate: "agent_thought_chunk",
9152
- content: {
9153
- type: "text",
9154
- text: chunk.thinking,
9155
- },
9156
- };
9157
- }
9158
- break;
9159
- }
9160
- case "tool_use":
9161
- case "server_tool_use":
9162
- case "mcp_tool_use": {
9163
- const alreadyCached = chunk.id in toolUseCache;
9164
- toolUseCache[chunk.id] = chunk;
9165
- if (chunk.name === "TodoWrite") {
9166
- // @ts-expect-error - sometimes input is empty object or undefined
9167
- if (Array.isArray(chunk.input?.todos)) {
9168
- update = todoWritePlanUpdate(planEntries(chunk.input), {
9169
- planOperations: options?.clientCapabilities?.plan != null,
9170
- parentToolUseId: options?.parentToolUseId,
9171
- // With native subagent sessions, an update of a subagent goes
9172
- // to the subagent's session (see NativeSubagentRuntime).
9173
- childSessions: clientSupportsSubagents(options?.clientCapabilities),
9174
- shown: options?.subagentChecklists,
9175
- });
9176
- }
9177
- }
9178
- else if (isTaskTool(chunk.name)) {
9179
- // Task* tool_use is suppressed; the plan update is emitted at
9180
- // tool_result time once we have the task ID (for TaskCreate) and
9181
- // confirmation that the change took effect.
9182
- }
9183
- else {
9184
- // Only register hooks on first encounter to avoid double-firing
9185
- if (registerHooks && !alreadyCached) {
9186
- // Capture the tool name in the closure rather than re-reading the
9187
- // cache when the hook fires. The cache entry is pruned at
9188
- // tool_result time, and a PostToolUse hook can fire after that, so
9189
- // closing over the name keeps the diff working without depending on
9190
- // (or pinning) the cache entry's lifetime.
9191
- const toolName = chunk.name;
9192
- const hookToolCallId = chunk.id;
9193
- registerHookCallback(chunk.id, {
9194
- onPostToolUseHook: async (toolUseId, _toolInput, toolResponse) => {
9195
- // The final diff of an Edit or a Write replaces the
9196
- // optimistic content built from the input. Only the marker
9197
- // fields of the tool_response travel: the rest repeats
9198
- // output that the content already carries.
9199
- const update = await renderer.hookResult({ id: toolUseId, name: toolName }, toolResponse, options?.cwd);
9200
- if (!update)
9201
- return;
9202
- if (options?.parentToolUseId) {
9203
- stampParentToolUseId(update, options.parentToolUseId);
9204
- }
9205
- // The final result may replace a pinned approval patch.
9206
- if (options?.toolCallFields &&
9207
- !options.toolCallFields.apply(update, { replacePinnedContent: true })) {
9208
- return;
9209
- }
9210
- await client.sessionUpdate({ sessionId, update });
9211
- },
9212
- onRelease: () => options?.toolCallFields?.finishHook(hookToolCallId),
9213
- }, sessionId);
9214
- }
9215
- let rawInput;
9216
- try {
9217
- rawInput = JSON.parse(JSON.stringify(chunk.input));
9218
- }
9219
- catch {
9220
- // ignore if we can't turn it to JSON
9221
- }
9222
- const toolUse = { id: chunk.id, name: chunk.name, input: rawInput };
9223
- // Emit a `tool_call` only the first time this id surfaces to the
9224
- // client; afterwards refine it with a `tool_call_update`. The first
9225
- // surface may be this stream chunk OR an earlier permission request
9226
- // (see `ensureToolCallEmitted`), so emission is tracked separately
9227
- // from `toolUseCache`. Without an `emittedToolCalls` set we fall back
9228
- // to cache presence — the historical streaming-only behavior.
9229
- const emittedToolCalls = options?.emittedToolCalls;
9230
- const alreadyEmitted = emittedToolCalls ? emittedToolCalls.has(chunk.id) : alreadyCached;
9231
- emittedToolCalls?.add(chunk.id);
9232
- // A permission request surfaced the tool call with its complete
9233
- // input. The empty input at the stream start has nothing to add.
9234
- if (alreadyEmitted && options?.inputComplete === false)
9235
- break;
9236
- update = alreadyEmitted
9237
- ? // Already surfaced (full assistant message after streaming, or a
9238
- // permission request emitted it first): refine it with the
9239
- // complete input.
9240
- renderer.refinement(toolUse, options?.cwd)
9241
- : // First surface (streaming content_block_start or replay).
9242
- renderer.toolCall(toolUse, {
9243
- cwd: options?.cwd,
9244
- inputComplete: options?.inputComplete,
9245
- });
9246
- }
9247
- break;
9248
- }
9249
- case "advisor_tool_result": {
9250
- // Advisor results arrive in assistant content, including encrypted advice.
9251
- // Resolve the server tool through the normal result path without rendering
9252
- // opaque ciphertext. Server tools have no later PostToolUse hook to await.
9253
- const result = chunk.content;
9254
- unregisterHookCallback(chunk.tool_use_id);
9255
- output.push(...toAcpNotifications([
9256
- {
9257
- type: "tool_result",
9258
- tool_use_id: chunk.tool_use_id,
9259
- is_error: result.type === "advisor_tool_result_error",
9260
- content: result.type === "advisor_result"
9261
- ? result.text
9262
- : result.type === "advisor_redacted_result"
9263
- ? "Advisor guidance applied server-side."
9264
- : `Advisor error: ${result.error_code}`,
9265
- },
9266
- ], role, sessionId, toolUseCache, client, logger, options));
9267
- break;
9268
- }
9269
- case "tool_result":
9270
- case "tool_search_tool_result":
9271
- case "web_fetch_tool_result":
9272
- case "web_search_tool_result":
9273
- case "code_execution_tool_result":
9274
- case "bash_code_execution_tool_result":
9275
- case "text_editor_code_execution_tool_result":
9276
- case "mcp_tool_result": {
9277
- const wasEmitted = options?.emittedToolCalls?.has(chunk.tool_use_id) === true;
9278
- options?.emittedToolCalls?.delete(chunk.tool_use_id);
9279
- completeHookCallback(chunk.tool_use_id);
9280
- finishedToolCallId = chunk.tool_use_id;
9281
- // Why this is_error result carries harness prose instead of tool
9282
- // output (user-rejected / interrupted / …), when the SDK said so.
9283
- // Spread into the claudeCode meta of every update emitted below; the
9284
- // untracked-tool fallback can't carry it (claudeCode metas always
9285
- // carry `toolName`, which is unknown there).
9286
- const nonExecution = toolResultMeta?.get(chunk.tool_use_id);
9287
- const toolUse = toolUseCache[chunk.tool_use_id];
9288
- if (!toolUse) {
9289
- // The permission flow may have surfaced this tool_call even though
9290
- // its tool_use never reached the cache (e.g. the assistant message
9291
- // carrying it was dropped by the cancelled-turn guard and a straggler
9292
- // result landed later). Resolve the surfaced call anyway so it can't
9293
- // stay pending in the client forever; without the cache entry the
9294
- // tool name is unknown, so no claudeCode meta is attached.
9295
- if (wasEmitted) {
9296
- output.push({
9297
- sessionId,
9298
- update: {
9299
- toolCallId: chunk.tool_use_id,
9300
- sessionUpdate: "tool_call_update",
9301
- status: renderer.resultStatus("is_error" in chunk && chunk.is_error === true, nonExecution, { cancelled: options?.cancelled }),
9302
- rawOutput: chunk.content,
9303
- },
9304
- });
9305
- }
9306
- logger.error(`[claude-agent-acp] Got a tool result for tool use that wasn't tracked: ${chunk.tool_use_id}`);
9307
- break;
9308
- }
9309
- // A permission request may have surfaced a plan-rendered (TodoWrite) or
9310
- // suppressed (Task*) tool as a real tool_call so the request referenced
9311
- // a tool call the client knows about (see `ensureToolCallEmitted`,
9312
- // issue #851). The branches below never emit a tool_call_update for
9313
- // those tools, which would leave the surfaced call pending in the
9314
- // client forever — resolve it here. `wasEmitted` is only ever true for
9315
- // these tools via the permission flow: the streamed plan/suppressed
9316
- // branches don't record emissions.
9317
- if (wasEmitted && !shouldEmitToolCall(toolUse.name)) {
9318
- output.push({
9319
- sessionId,
9320
- update: {
9321
- _meta: {
9322
- claudeCode: {
9323
- toolName: toolUse.name,
9324
- ...(nonExecution ?? {}),
9325
- ...(options?.parentToolUseId ? { parentToolUseId: options.parentToolUseId } : {}),
9326
- },
9327
- },
9328
- toolCallId: chunk.tool_use_id,
9329
- sessionUpdate: "tool_call_update",
9330
- status: renderer.resultStatus("is_error" in chunk && chunk.is_error === true, nonExecution, { cancelled: options?.cancelled }),
9331
- rawOutput: chunk.content,
9332
- },
9333
- });
9334
- }
9335
- if (isTaskTool(toolUse.name)) {
9336
- // Headless/SDK sessions emit Task* tools instead of TodoWrite.
9337
- // TaskCreate / TaskUpdate mutate the accumulated task list. TaskList
9338
- // reconciles it from the SDK's authoritative snapshot, which repairs
9339
- // resumed or compacted sessions whose creating calls are no longer in
9340
- // replay history. TaskGet is read-only and remains suppressed. Plan
9341
- // updates always carry the full accumulated snapshot, mirroring the
9342
- // legacy TodoWrite behavior.
9343
- const isError = "is_error" in chunk && chunk.is_error;
9344
- let shouldEmitTaskPlan = false;
9345
- if (!isError) {
9346
- if (toolUse.name === "TaskCreate") {
9347
- applyTaskCreate(taskState, toolUse.input, parseTaskCreateOutput(toolUseResult) ?? parseTaskCreateOutput(chunk.content));
9348
- shouldEmitTaskPlan = true;
9349
- }
9350
- else if (toolUse.name === "TaskUpdate") {
9351
- const input = toolUse.input;
9352
- const output = parseTaskUpdateOutput(toolUseResult, input?.taskId) ??
9353
- parseTaskUpdateOutput(chunk.content, input?.taskId);
9354
- // Older CLI transcripts have no structured output, so retain the
9355
- // input-based fallback. When an output is available, only apply a
9356
- // confirmed update for the same task.
9357
- if (!output || (output.success && output.taskId === input?.taskId)) {
9358
- applyTaskUpdate(taskState, input);
9359
- shouldEmitTaskPlan = true;
9360
- }
9361
- }
9362
- else if (toolUse.name === "TaskList") {
9363
- const output = parseTaskListOutput(toolUseResult) ?? parseTaskListOutput(chunk.content);
9364
- if (output) {
9365
- applyTaskList(taskState, output);
9366
- shouldEmitTaskPlan = true;
9367
- }
9368
- }
9369
- }
9370
- const entries = shouldEmitTaskPlan
9371
- ? changedTaskPlanEntries(taskState, renderer.capabilities.air.client)
9372
- : undefined;
9373
- if (entries) {
9374
- update = checklistPlanUpdate(entries, options?.clientCapabilities?.plan != null);
9375
- }
9376
- }
9377
- else if (toolUse.name !== "TodoWrite") {
9378
- // A command sends its output first, then the exit and the status.
9379
- const [finalUpdate, ...rest] = renderer
9380
- .result(toolUse, chunk, {
9381
- structured: toolUseResult,
9382
- nonExecution,
9383
- cancelled: options?.cancelled,
9384
- })
9385
- .reverse();
9386
- for (const outputUpdate of rest.reverse()) {
9387
- if (options?.parentToolUseId) {
9388
- stampParentToolUseId(outputUpdate, options.parentToolUseId);
9389
- }
9390
- output.push({ sessionId, update: outputUpdate });
9391
- }
9392
- // An approved plan of the main conversation becomes the session's
9393
- // markdown plan, after the tool call's result. An approval that
9394
- // clears the context ends the tool with an error result instead, and
9395
- // the restart into the fresh context publishes that plan (see
9396
- // ExitPlanCoordinator.restart).
9397
- if (toolUse.name === "ExitPlanMode" &&
9398
- options?.clientCapabilities?.plan &&
9399
- !options.parentToolUseId &&
9400
- !("is_error" in chunk && chunk.is_error)) {
9401
- const plan = approvedPlan(toolUse.input, toolUseResult);
9402
- if (plan) {
9403
- approvedPlanUpdate = planModeUpdate(plan, renderer.capabilities.air.client ? toolUse.id : undefined);
9404
- }
9405
- }
9406
- update = finalUpdate;
9407
- }
9408
- // The tool_use is fully resolved now — drop it so a long session doesn't
9409
- // retain every tool call. The PostToolUse hook (Edit/Write diffs) closes
9410
- // over the tool name and no longer reads the cache, so pruning here is
9411
- // safe regardless of hook/result ordering.
9412
- delete toolUseCache[chunk.tool_use_id];
9413
- break;
9414
- }
9415
- case "document":
9416
- case "search_result":
9417
- case "redacted_thinking":
9418
- case "input_json_delta":
9419
- case "citations_delta":
9420
- case "signature_delta":
9421
- case "container_upload":
9422
- case "compaction":
9423
- case "compaction_delta":
9424
- case "fallback":
9425
- case "mcp_tool_listing":
9426
- break;
9427
- default:
9428
- unreachable(chunk, logger);
9429
- break;
9430
- }
9431
- if (update) {
9432
- if (options?.parentToolUseId)
9433
- stampParentToolUseId(update, options.parentToolUseId);
9434
- applyMessageId(update, options?.messageId);
9435
- // A tool result is final, so it may replace a pinned approval patch,
9436
- // for example with the error text of a rejected Edit.
9437
- if (!options?.toolCallFields ||
9438
- options.toolCallFields.apply(update, {
9439
- replacePinnedContent: finishedToolCallId !== undefined,
9440
- })) {
9441
- output.push({ sessionId, update });
9442
- }
9443
- }
9444
- if (approvedPlanUpdate)
9445
- output.push({ sessionId, update: approvedPlanUpdate });
9446
- if (finishedToolCallId !== undefined) {
9447
- // The PostToolUse hook can still send the final diff, so the fields
9448
- // stay tracked until its callback leaves the registry.
9449
- options?.toolCallFields?.finishResult(finishedToolCallId, hasHookCallback(finishedToolCallId));
9450
- }
9451
- }
9452
- return output;
9453
- }
9454
- export function streamEventToAcpNotifications(message, sessionId, toolUseCache, client, logger, options) {
9455
- const event = message.event;
9456
- const streamKey = message.parent_tool_use_id ?? "";
9457
- const streamedToolInputs = options?.streamedToolInputs;
9458
- const forwardedOptions = {
9459
- clientCapabilities: options?.clientCapabilities,
9460
- toolCallCapabilities: options?.toolCallCapabilities,
9461
- parentToolUseId: message.parent_tool_use_id,
9462
- cwd: options?.cwd,
9463
- taskState: options?.taskState,
9464
- subagentChecklists: options?.subagentChecklists,
9465
- emittedToolCalls: options?.emittedToolCalls,
9466
- toolCallFields: options?.toolCallFields,
9467
- messageId: options?.messageId,
9468
- };
9469
- switch (event.type) {
9470
- case "content_block_start": {
9471
- const block = event.content_block;
9472
- if (streamedToolInputs &&
9473
- (block.type === "tool_use" ||
9474
- block.type === "server_tool_use" ||
9475
- block.type === "mcp_tool_use")) {
9476
- let inputsForMessage = streamedToolInputs.get(streamKey);
9477
- if (!inputsForMessage) {
9478
- inputsForMessage = new Map();
9479
- streamedToolInputs.set(streamKey, inputsForMessage);
9480
- }
9481
- inputsForMessage.set(event.index, {
9482
- id: block.id,
9483
- name: block.name,
9484
- partialJson: "",
9485
- inString: false,
9486
- escaped: false,
9487
- objectDepth: 0,
9488
- arrayDepth: 0,
9489
- lastTopLevelComma: -1,
9490
- emittedThroughComma: -1,
9491
- });
9492
- }
9493
- // The input of a streamed tool_use starts empty and streams after this
9494
- // event, so the tool_call waits for the complete input.
9495
- return toAcpNotifications([block], "assistant", sessionId, toolUseCache, client, logger, {
9496
- ...forwardedOptions,
9497
- inputComplete: false,
9498
- });
9499
- }
9500
- case "content_block_delta": {
9501
- if (event.delta.type === "input_json_delta") {
9502
- const streamedInput = streamedToolInputs?.get(streamKey)?.get(event.index);
9503
- if (!streamedInput)
9504
- return [];
9505
- if (scanStreamedToolInput(streamedInput, event.delta.partial_json)) {
9506
- // Input complete: the consolidated assistant message replays the
9507
- // block with its full input and refines the call there; emitting
9508
- // here too would send a duplicate identical update.
9509
- const inputsForMessage = streamedToolInputs?.get(streamKey);
9510
- inputsForMessage?.delete(event.index);
9511
- if (inputsForMessage?.size === 0)
9512
- streamedToolInputs?.delete(streamKey);
9513
- return [];
9514
- }
9515
- if (streamedInput.lastTopLevelComma <= streamedInput.emittedThroughComma) {
9516
- return [];
9517
- }
9518
- streamedInput.emittedThroughComma = streamedInput.lastTopLevelComma;
9519
- const input = recoveredToolInput(streamedInput.partialJson.slice(0, streamedInput.lastTopLevelComma));
9520
- if (!input)
9521
- return [];
9522
- // TodoWrite and the Task* tools never surfaced a tool_call to refine.
9523
- if (!shouldEmitToolCall(streamedInput.name))
9524
- return [];
9525
- const update = toolCallRenderer(options).partialRefinement(streamedInput, input, options?.cwd);
9526
- if (message.parent_tool_use_id)
9527
- stampParentToolUseId(update, message.parent_tool_use_id);
9528
- applyMessageId(update, options?.messageId);
9529
- // A refinement resends only what changed: rawInput grows with every
9530
- // field, and title, kind, and locations usually stay the same.
9531
- if (options?.toolCallFields && !options.toolCallFields.apply(update))
9532
- return [];
9533
- return [{ sessionId, update }];
9534
- }
9535
- return toAcpNotifications([event.delta], "assistant", sessionId, toolUseCache, client, logger, forwardedOptions);
9536
- }
9537
- // No content. `ping` is a Messages-API keep-alive event that the SDK's
9538
- // `BetaRawMessageStreamEvent` union doesn't include even though the
9539
- // wire format emits it; the `as never` cast lets us no-op it here
9540
- // instead of letting it fall through to `unreachable`.
9541
- case "ping":
9542
- case "message_delta":
9543
- return [];
9544
- // A message boundary ends every input stream on this lane: message_stop is
9545
- // the normal end, and a message_start clears anything a prior message on
9546
- // the lane left behind (e.g. a stream cut short mid-block).
9547
- case "message_start":
9548
- case "message_stop":
9549
- streamedToolInputs?.delete(streamKey);
9550
- return [];
9551
- case "content_block_stop": {
9552
- const inputsForMessage = streamedToolInputs?.get(streamKey);
9553
- inputsForMessage?.delete(event.index);
9554
- if (inputsForMessage?.size === 0)
9555
- streamedToolInputs?.delete(streamKey);
9556
- return [];
9557
- }
9558
- default:
9559
- unreachable(event, logger);
9560
- return [];
9561
- }
9562
- }
9563
8505
  /** Run a `session/prompt` while honoring `$/cancel_request` for it. ACP clients
9564
8506
  * normally stop a turn with the `session/cancel` notification, but `signal`
9565
8507
  * (the prompt request's abort signal) also fires when the client sends the