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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (206) hide show
  1. package/README.md +5 -1
  2. package/dist/acp-agent.d.ts +119 -439
  3. package/dist/acp-agent.d.ts.map +1 -1
  4. package/dist/acp-agent.js +380 -2412
  5. package/dist/acp-subagents.d.ts +1 -2
  6. package/dist/acp-subagents.d.ts.map +1 -1
  7. package/dist/auth-methods.d.ts +21 -0
  8. package/dist/auth-methods.d.ts.map +1 -0
  9. package/dist/auth-methods.js +68 -0
  10. package/dist/auth-status-reporter.d.ts +112 -0
  11. package/dist/auth-status-reporter.d.ts.map +1 -0
  12. package/dist/auth-status-reporter.js +253 -0
  13. package/dist/background-work.d.ts +12 -265
  14. package/dist/background-work.d.ts.map +1 -1
  15. package/dist/background-work.js +8 -558
  16. package/dist/client-system-prompt.d.ts +7 -0
  17. package/dist/client-system-prompt.d.ts.map +1 -1
  18. package/dist/client-system-prompt.js +24 -0
  19. package/dist/context-compaction.d.ts +20 -0
  20. package/dist/context-compaction.d.ts.map +1 -1
  21. package/dist/context-compaction.js +26 -0
  22. package/dist/context-window.d.ts +70 -0
  23. package/dist/context-window.d.ts.map +1 -0
  24. package/dist/context-window.js +132 -0
  25. package/dist/diff.d.ts +1 -1
  26. package/dist/diff.js +1 -1
  27. package/dist/elicitation.d.ts +66 -1
  28. package/dist/elicitation.d.ts.map +1 -1
  29. package/dist/elicitation.js +109 -0
  30. package/dist/file-change-audit.d.ts +4 -3
  31. package/dist/file-change-audit.d.ts.map +1 -1
  32. package/dist/file-change-audit.js +3 -2
  33. package/dist/mcp-oauth.d.ts +44 -0
  34. package/dist/mcp-oauth.d.ts.map +1 -0
  35. package/dist/mcp-oauth.js +142 -0
  36. package/dist/mcp-servers.d.ts +10 -0
  37. package/dist/mcp-servers.d.ts.map +1 -0
  38. package/dist/mcp-servers.js +29 -0
  39. package/dist/native-subagents.d.ts +18 -8
  40. package/dist/native-subagents.d.ts.map +1 -1
  41. package/dist/native-subagents.js +7 -35
  42. package/dist/permissions/presentation.d.ts +29 -0
  43. package/dist/permissions/presentation.d.ts.map +1 -1
  44. package/dist/permissions/presentation.js +38 -11
  45. package/dist/plans.d.ts +36 -6
  46. package/dist/plans.d.ts.map +1 -1
  47. package/dist/plans.js +49 -11
  48. package/dist/prompt-suggestions.d.ts +29 -0
  49. package/dist/prompt-suggestions.d.ts.map +1 -1
  50. package/dist/prompt-suggestions.js +45 -0
  51. package/dist/providers.d.ts +139 -0
  52. package/dist/providers.d.ts.map +1 -0
  53. package/dist/providers.js +286 -0
  54. package/dist/remote-control.d.ts +62 -0
  55. package/dist/remote-control.d.ts.map +1 -0
  56. package/dist/remote-control.js +78 -0
  57. package/dist/result-end.d.ts +39 -0
  58. package/dist/result-end.d.ts.map +1 -0
  59. package/dist/result-end.js +50 -0
  60. package/dist/serve.d.ts +7 -2
  61. package/dist/serve.d.ts.map +1 -1
  62. package/dist/serve.js +10 -5
  63. package/dist/session-config-ids.d.ts +1 -0
  64. package/dist/session-config-ids.d.ts.map +1 -1
  65. package/dist/session-config-ids.js +1 -0
  66. package/dist/session-config-options.d.ts +64 -0
  67. package/dist/session-config-options.d.ts.map +1 -0
  68. package/dist/session-config-options.js +162 -0
  69. package/dist/session-effort.d.ts +67 -0
  70. package/dist/session-effort.d.ts.map +1 -1
  71. package/dist/session-effort.js +98 -0
  72. package/dist/session-env.d.ts +22 -0
  73. package/dist/session-env.d.ts.map +1 -0
  74. package/dist/session-env.js +66 -0
  75. package/dist/session-fast-mode.d.ts +83 -0
  76. package/dist/session-fast-mode.d.ts.map +1 -0
  77. package/dist/session-fast-mode.js +142 -0
  78. package/dist/session-index/connection.d.ts +2 -5
  79. package/dist/session-index/connection.d.ts.map +1 -1
  80. package/dist/session-index/connection.js +3 -5
  81. package/dist/session-mode.d.ts +1 -0
  82. package/dist/session-mode.d.ts.map +1 -1
  83. package/dist/session-mode.js +1 -1
  84. package/dist/session-model.d.ts +41 -0
  85. package/dist/session-model.d.ts.map +1 -1
  86. package/dist/session-model.js +110 -45
  87. package/dist/session-notices.d.ts +44 -0
  88. package/dist/session-notices.d.ts.map +1 -1
  89. package/dist/session-notices.js +68 -0
  90. package/dist/session-titles.d.ts +34 -12
  91. package/dist/session-titles.d.ts.map +1 -1
  92. package/dist/session-titles.js +7 -6
  93. package/dist/session-usage.d.ts +125 -0
  94. package/dist/session-usage.d.ts.map +1 -0
  95. package/dist/session-usage.js +196 -0
  96. package/dist/streamed-text.d.ts +33 -0
  97. package/dist/streamed-text.d.ts.map +1 -0
  98. package/dist/streamed-text.js +71 -0
  99. package/dist/subagent-configuration.d.ts +32 -0
  100. package/dist/subagent-configuration.d.ts.map +1 -0
  101. package/dist/subagent-configuration.js +70 -0
  102. package/dist/subagent-replay.d.ts +18 -0
  103. package/dist/subagent-replay.d.ts.map +1 -1
  104. package/dist/subagent-replay.js +25 -15
  105. package/dist/tool-calls/client-capabilities.d.ts +8 -8
  106. package/dist/tool-calls/client-capabilities.js +4 -4
  107. package/dist/tool-calls/renderer.d.ts +4 -5
  108. package/dist/tool-calls/renderer.d.ts.map +1 -1
  109. package/dist/tool-calls/renderer.js +4 -5
  110. package/dist/turn-events.d.ts +6 -46
  111. package/dist/turn-events.d.ts.map +1 -1
  112. package/dist/v2/agent.d.ts +7 -11
  113. package/dist/v2/agent.d.ts.map +1 -1
  114. package/dist/v2/agent.js +751 -331
  115. package/dist/v2/air.d.ts +33 -0
  116. package/dist/v2/air.d.ts.map +1 -0
  117. package/dist/v2/air.js +29 -0
  118. package/dist/v2/auth.d.ts +97 -0
  119. package/dist/v2/auth.d.ts.map +1 -0
  120. package/dist/v2/auth.js +216 -0
  121. package/dist/v2/background.d.ts +27 -16
  122. package/dist/v2/background.d.ts.map +1 -1
  123. package/dist/v2/background.js +4 -32
  124. package/dist/v2/child-config.d.ts +55 -0
  125. package/dist/v2/child-config.d.ts.map +1 -0
  126. package/dist/v2/child-config.js +92 -0
  127. package/dist/v2/clear-context.d.ts +94 -0
  128. package/dist/v2/clear-context.d.ts.map +1 -0
  129. package/dist/v2/clear-context.js +176 -0
  130. package/dist/v2/commands.d.ts +46 -0
  131. package/dist/v2/commands.d.ts.map +1 -0
  132. package/dist/v2/commands.js +54 -0
  133. package/dist/v2/config.d.ts +187 -0
  134. package/dist/v2/config.d.ts.map +1 -0
  135. package/dist/v2/config.js +494 -0
  136. package/dist/v2/elicitation.d.ts +93 -0
  137. package/dist/v2/elicitation.d.ts.map +1 -0
  138. package/dist/v2/elicitation.js +160 -0
  139. package/dist/v2/file-changes.d.ts +61 -0
  140. package/dist/v2/file-changes.d.ts.map +1 -0
  141. package/dist/v2/file-changes.js +108 -0
  142. package/dist/v2/file-preview.d.ts +18 -0
  143. package/dist/v2/file-preview.d.ts.map +1 -0
  144. package/dist/v2/file-preview.js +29 -0
  145. package/dist/v2/initialize.d.ts +10 -24
  146. package/dist/v2/initialize.d.ts.map +1 -1
  147. package/dist/v2/initialize.js +4 -111
  148. package/dist/v2/outcome.d.ts +81 -0
  149. package/dist/v2/outcome.d.ts.map +1 -0
  150. package/dist/v2/outcome.js +165 -0
  151. package/dist/v2/permissions.d.ts +92 -0
  152. package/dist/v2/permissions.d.ts.map +1 -0
  153. package/dist/v2/permissions.js +162 -0
  154. package/dist/v2/prompt.d.ts +2 -42
  155. package/dist/v2/prompt.d.ts.map +1 -1
  156. package/dist/v2/prompt.js +2 -119
  157. package/dist/v2/remote-control.d.ts +41 -0
  158. package/dist/v2/remote-control.d.ts.map +1 -0
  159. package/dist/v2/remote-control.js +63 -0
  160. package/dist/v2/reports.d.ts +198 -0
  161. package/dist/v2/reports.d.ts.map +1 -0
  162. package/dist/v2/reports.js +487 -0
  163. package/dist/v2/restarts.d.ts +128 -0
  164. package/dist/v2/restarts.d.ts.map +1 -0
  165. package/dist/v2/restarts.js +348 -0
  166. package/dist/v2/session-requests.d.ts +20 -0
  167. package/dist/v2/session-requests.d.ts.map +1 -0
  168. package/dist/v2/session-requests.js +108 -0
  169. package/dist/v2/session-update.d.ts +2 -13
  170. package/dist/v2/session-update.d.ts.map +1 -1
  171. package/dist/v2/session-update.js +2 -22
  172. package/dist/v2/session.d.ts +340 -41
  173. package/dist/v2/session.d.ts.map +1 -1
  174. package/dist/v2/session.js +1223 -141
  175. package/dist/v2/setup.d.ts +49 -0
  176. package/dist/v2/setup.d.ts.map +1 -0
  177. package/dist/v2/setup.js +62 -0
  178. package/dist/v2/stopped-work.d.ts +123 -0
  179. package/dist/v2/stopped-work.d.ts.map +1 -0
  180. package/dist/v2/stopped-work.js +210 -0
  181. package/dist/v2/stream.d.ts +228 -0
  182. package/dist/v2/stream.d.ts.map +1 -0
  183. package/dist/v2/stream.js +506 -0
  184. package/dist/v2/subagent-replay.d.ts +115 -0
  185. package/dist/v2/subagent-replay.d.ts.map +1 -0
  186. package/dist/v2/subagent-replay.js +479 -0
  187. package/dist/v2/subscription-guard.d.ts +60 -0
  188. package/dist/v2/subscription-guard.d.ts.map +1 -0
  189. package/dist/v2/subscription-guard.js +84 -0
  190. package/dist/v2/tasks.d.ts +492 -0
  191. package/dist/v2/tasks.d.ts.map +1 -0
  192. package/dist/v2/tasks.js +1728 -0
  193. package/dist/v2/terminal.d.ts.map +1 -1
  194. package/dist/v2/terminal.js +6 -1
  195. package/dist/v2/tool-call.d.ts +3 -2
  196. package/dist/v2/tool-call.d.ts.map +1 -1
  197. package/dist/v2/update-translator.d.ts +36 -0
  198. package/dist/v2/update-translator.d.ts.map +1 -0
  199. package/dist/v2/update-translator.js +80 -0
  200. package/dist/workflow-progress.d.ts +23 -0
  201. package/dist/workflow-progress.d.ts.map +1 -1
  202. package/dist/workflow-progress.js +31 -8
  203. package/package.json +1 -1
  204. package/dist/v2/permission.d.ts +0 -28
  205. package/dist/v2/permission.d.ts.map +0 -1
  206. package/dist/v2/permission.js +0 -41
package/dist/acp-agent.js CHANGED
@@ -1,29 +1,29 @@
1
1
  import { agent as acpAgent, methods, ndJsonStream, RequestError, } from "@agentclientprotocol/sdk/unstable";
2
- import { filterEscalatingDefaultMode, getSessionMessages, listSessions, query, resolveSettings, } from "@anthropic-ai/claude-agent-sdk";
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
4
  import { blobResourceToClaude } from "./blob-resources.js";
5
- import { checklistPlanUpdate, resetPlanUpdates } from "./plans.js";
6
- import { promptSuggestionsMeta, promptSuggestionText } from "./prompt-suggestions.js";
5
+ import { checklistPlanUpdate, resetPlanUpdates, todoWritePlanUpdate, } from "./plans.js";
6
+ import { PromptSuggestions } from "./prompt-suggestions.js";
7
7
  import { sanitizeTitle, SessionTitles } from "./session-titles.js";
8
8
  import { AIR_NATIVE_SUBAGENT_SESSIONS_CAPABILITY, asSdkSessionNotification, clientSupportsSubagents, subagentForm, } from "./acp-subagents.js";
9
9
  import { childModelOption, isNativeSubagentControlTool, isNativeSubagentControlUpdate, NativeSubagentRuntime, nativeSubagentState, responseModelEntry, resumedNativeSubagentId, sameModelEntry, sendMessageResume, sendMessageResumePrompt, } from "./native-subagents.js";
10
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";
11
11
  import * as sessionIndex from "./session-index/connection.js";
12
- import { AsyncTaskRuntime, backgroundBashTaskFromToolResult, backgroundedBashToolCallIds, clientSupportsAsyncTasks, taskProgressFields, } from "./async-tasks.js";
13
- import { workflowSnapshot } from "./workflow-progress.js";
14
- import { BackgroundWorkReporter, cancelBackgroundWork, SessionBackgroundWork, } from "./background-work.js";
15
- import { AUTH_STATUS_PROBE_TIMEOUT_MS, AUTH_STATUS_UPDATE_METHOD, authStatusCapability, fromAccountInfo, fromCliStatus, gatewayAuthStatus, mergeAuthStatus, notLoggedInAuthStatus, sameAuthStatus, } from "./auth-status.js";
16
- import { agentCommand } from "./agent-command.js";
12
+ import { AsyncTaskRuntime, backgroundBashTaskFromToolResult, backgroundedBashToolCallIds, clientSupportsAsyncTasks, } from "./async-tasks.js";
13
+ import { SessionBackgroundWork } from "./background-work.js";
14
+ import { AUTH_STATUS_UPDATE_METHOD, authStatusCapability, fromAccountInfo, gatewayAuthStatus, notLoggedInAuthStatus, } from "./auth-status.js";
15
+ import { AuthStatusReporter, cliLogout } from "./auth-status-reporter.js";
16
+ import { terminalAuthMethods as authMethodsForTerminal } from "./auth-methods.js";
17
+ import { sdkMcpServers } from "./mcp-servers.js";
17
18
  import { claudeCliPath } from "./claude-cli.js";
18
- import { execFile } from "node:child_process";
19
19
  import { randomUUID } from "node:crypto";
20
20
  import * as fs from "node:fs/promises";
21
21
  import * as path from "node:path";
22
- import { promisify } from "node:util";
23
22
  import packageJson from "../package.json" with { type: "json" };
24
- import { applyAskElicitationResponse, askUserQuestionsToCreateRequest, createElicitationResponseToElicitResult, extractAskUserQuestions, extractRefusalFallbackPrompt, mcpElicitationToCreateRequest, REFUSAL_FALLBACK_DIALOG_KIND, refusalFallbackResultFromResponse, refusalFallbackToCreateRequest, } from "./elicitation.js";
23
+ import { answerAskUserQuestion, answerMcpElicitation, answerUserDialog, elicitUnlessWithdrawn, REFUSAL_FALLBACK_DIALOG_KIND, } from "./elicitation.js";
24
+ import { startMcpServerAuthentication as startSharedMcpServerAuthentication, supportsMcpOAuth, } from "./mcp-oauth.js";
25
25
  import { forkSession } from "./fork-session.js";
26
- import { clientSystemPrompt, sdkSystemPrompt, SYSTEM_PROMPT_CAPABILITY, } from "./client-system-prompt.js";
26
+ import { clientSystemPrompt, sessionSystemPrompt, SYSTEM_PROMPT_CAPABILITY, } from "./client-system-prompt.js";
27
27
  import { readSubagentMessages, subagentHistory, subagentLaunchIds, subagentLaunchedBy, subagentLineage, } from "./subagent-history.js";
28
28
  import { RfdSubagentReplay, firstResponseModel, replaySubagentTerminalState, } from "./subagent-replay.js";
29
29
  import { readResumedSession, readResumedTail, } from "./resumed-session.js";
@@ -31,18 +31,20 @@ import { SessionTiming } from "./session-timing.js";
31
31
  import { ALLOW_BYPASS, autoModeDisabled } from "./permissions/modes.js";
32
32
  import { normalizeDurablePermissionChangeSet } from "./permissions/normalization.js";
33
33
  import { buildClaudePermissionOptions } from "./permissions/options.js";
34
- import { buildClaudePermissionPresentation, } from "./permissions/presentation.js";
34
+ import { buildClaudePermissionPresentation, permissionToolCallMeta, } from "./permissions/presentation.js";
35
35
  import { decodeClaudePermissionResponse } from "./permissions/response.js";
36
36
  import { SettingsManager } from "./settings.js";
37
37
  import { activeUsageLimitMessage, airSessionFailureCapabilityMeta, assistantMessageText, createSessionFailureState, isSyntheticUsageLimitMessage, providerFailureCategory, SessionFailureController, sessionFailureMeta, supportsAirSessionFailures, } from "./session-failure-extension.js";
38
38
  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";
39
40
  import { AGENT_FILE_CHANGE_REPORT_CAPABILITY, agentFileChangeReportMeta, createNativeFileChangeReporter, recordSubagentFileEdits, supportsAgentFileChangeReport, } from "./file-change-audit.js";
40
- import { ContextCompactionLifecycle, clientSupportsCompactionUpdates, contextCompactionMetadataFromBoundary, isCompactSummaryMessage, } from "./context-compaction.js";
41
+ import { ContextCompactionLifecycle, clientSupportsCompactionUpdates, contextCompactionMetadataFromBoundary, replayCompactSummary, } from "./context-compaction.js";
41
42
  import { IdleCompaction } from "./idle-compaction.js";
42
- import { clientSupportsNotices, collapseHookSpeaker, MAX_NOTICE_TITLE_LENGTH, normalizeNoticeText, noticeOrTranscriptUpdate, sentenceCase, splitNoticeText, } from "./session-notices.js";
43
+ import { clientSupportsNotices, collapseHookSpeaker, informationalNotice, MAX_NOTICE_TITLE_LENGTH, mcpServerStartupNotice, modelRefusalFallback, normalizeNoticeText, noticeOrTranscriptUpdate, sentenceCase, } from "./session-notices.js";
43
44
  import { applyTaskCreate, applyTaskList, applyTaskUpdate, clearHookCallbacks, completeHookCallback, createPostToolUseHook, hasHookCallback, createTaskHook, parseTaskCreateOutput, parseTaskListOutput, parseTaskUpdateOutput, planEntries, registerHookCallback, changedTaskPlanEntries, forgetPublishedTaskPlan, unregisterHookCallback, } from "./tools.js";
45
+ import { addModelUsage, DEFAULT_CONTEXT_WINDOW, getMatchingModelUsage, inferContextWindowFromModel, modelUsageIncrement, normalizeModelUsage, quotaMeta, resumedFirstResultModelUsage, snapshotFromUsage, tallyTotal, totalTokens, ZERO_USAGE, } from "./session-usage.js";
44
46
  import { previewPatchContent } from "./diff.js";
45
- import { backgroundedBashToolCall, withRunningTerminal, withRunningToolCall, } from "./tool-calls/background.js";
47
+ import { backgroundedBashToolCall, withRunningTerminal } from "./tool-calls/background.js";
46
48
  import { ChangedMetaFilter } from "./tool-calls/changed-meta-filter.js";
47
49
  import { ToolCallFieldTracker } from "./tool-calls/field-tracker.js";
48
50
  import { ClientCapabilities as ToolCallClientCapabilities } from "./tool-calls/client-capabilities.js";
@@ -50,21 +52,31 @@ import { AcpToolCallRenderer, isFinalToolCallStatus, } from "./tool-calls/render
50
52
  import { resolveSkillPath } from "./tool-calls/reporters/interaction.js";
51
53
  import { messageLoopYielder, nodeToWebReadable, nodeToWebWritable, Pushable, raceTimeoutAndAbort, unreachable, } from "./utils.js";
52
54
  import { acceptedPlanToolResult, approvedPlan, ExitPlanCoordinator, isExitPlanInterruptionResult, observeExitPlanToolResults, planModeUpdate, } from "./exit-plan.js";
53
- import { DEFAULT_AGENT_ID } from "./session-config-ids.js";
55
+ import { AGENT_CONFIG_ID, DEFAULT_AGENT_ID } from "./session-config-ids.js";
54
56
  import { parseToolResultMeta } from "./tool-result-meta.js";
55
57
  import { markerTagText, TASK_NOTIFICATION_TAG, taskNotificationsOf, } from "./task-notifications.js";
56
58
  import { formatUsageResponse, isUsageCommandText, parseUsageResponse } from "./usage-markdown.js";
57
59
  export { DEFAULT_AGENT_ID } from "./session-config-ids.js";
58
60
  import { MCP_AVAILABLE_COMMAND, parseMcpCommand, runMcpCommand } from "./mcp-command.js";
61
+ import { configuredSettings, resolveThinkingConfig } from "./session-env.js";
59
62
  import { MODE_CONFIG_ID, resolveInitialPermissionMode, SessionModeManager, } from "./session-mode.js";
60
- import { aliasResumedModelRow, applyAvailableModelsAllowlist, buildModelConfigOption, getAvailableModels, MODEL_CONFIG_ID, modelDisplayName, modelEntryFor, narrowToGatewayModels, resolveModelPreference, } from "./session-model.js";
61
- import { GatewayListingError, listBedrockModels, listGatewayModels, PROVIDER_AUTH_TOKEN_PLACEHOLDER, selectBedrockRegion, } from "./gateway-models.js";
62
- import { buildEffortConfigOption, EFFORT_CONFIG_ID, effortFlagSettings, effortLevelName, mergeEffortSettings, settingsEffortForModel, } from "./session-effort.js";
63
- import { createUltracodeConfigOption, readUltracodeSettings, resolveUltracodeEnabled, ULTRACODE_CONFIG_ID, ultracodeSupported, ultracodeWorkflowsEnabled, } from "./session-ultracode.js";
63
+ import { aliasResumedModelRow, applyAvailableModelsAllowlist, getAvailableModels, MODEL_CONFIG_ID, modelDisplayName, modelEntryFor, narrowToGatewayModels, resolveModelPreference, withCurrentModelInfo, } from "./session-model.js";
64
+ import { createEnvForProvider, defaultProviderConfig, gatewayRequestToProviderConfig, isGatewayAuthMethod, listProvidersResponse, loggableBaseUrl, PROVIDER_ID, providerConfigFromSetRequest, validatedGatewayAuthRequest, withListedModels, } from "./providers.js";
65
+ import { EFFORT_CONFIG_ID, effortFlagSettings, effortForModelSwitch, mergeEffortSettings, settleEffortAfterModelSwitch, settingsEffortForModel, withoutEffort, } from "./session-effort.js";
66
+ import { createUltracodeConfigOption, readUltracodeSettings, ULTRACODE_CONFIG_ID, ultracodeSupported, ultracodeWorkflowsEnabled, } from "./session-ultracode.js";
67
+ import { buildConfigOptions, clientSupportsBooleanConfigOptions, clientSupportsRecommendedConfigValue, configOptionValue, discoverCustomAgents, } from "./session-config-options.js";
68
+ import { createFastModeConfigOption, FAST_MODE_CONFIG_ID, fastModeStateChange, fastModeStateEnabled, normalizeFastModeDisabledReason, } from "./session-fast-mode.js";
69
+ import { cacheResultContextWindow, clearContextWindowCache, immediateContextWindow, providerCacheKeyFor, readContextWindow, } from "./context-window.js";
70
+ import { isLoginRequiredText, resultEnd } from "./result-end.js";
64
71
  import { STARTUP_FAILURE_RESULTS_ENV, startupFailureError } from "./startup-failure.js";
72
+ import { recordStreamedDelta, unstreamedRemainder } from "./streamed-text.js";
73
+ import { subagentHookOptions } from "./subagent-configuration.js";
74
+ export { AGENT_CONFIG_ID, BUILTIN_AGENT_NAMES, buildConfigOptions, clientSupportsBooleanConfigOptions, clientSupportsRecommendedConfigValue, discoverCustomAgents, MODE_CONFIG_ID, } from "./session-config-options.js";
75
+ export { createFastModeConfigOption, FAST_MODE_CONFIG_ID, FAST_MODE_OFF, FAST_MODE_ON, fastModeStateEnabled, normalizeFastModeDisabledReason, resolveFastModeEnabled, } from "./session-fast-mode.js";
65
76
  export { EFFORT_CONFIG_ID, settingsEffortForModel } from "./session-effort.js";
66
77
  export { applyAvailableModelsAllowlist, matchResumedModel, MODEL_CONFIG_ID, resolveModelPreference, } from "./session-model.js";
67
- const execFileAsync = promisify(execFile);
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";
68
80
  /** Claude CLI emits this synthetic result when an interrupted cycle ends on
69
81
  * queued user input before producing any assistant content. It is a hand-off
70
82
  * marker, not the outcome of the replacement prompt that may already be
@@ -78,13 +90,6 @@ function isEmptyUserInterruptionDiagnostic(message) {
78
90
  /(?:^|\s)last_content_type=n\/a(?:\s|$)/.test(diagnostic) &&
79
91
  /(?:^|\s)stop_reason=null(?:\s|$)/.test(diagnostic));
80
92
  }
81
- const ZERO_USAGE = Object.freeze({
82
- input_tokens: 0,
83
- output_tokens: 0,
84
- cache_read_input_tokens: 0,
85
- cache_creation_input_tokens: 0,
86
- });
87
- const DEFAULT_CONTEXT_WINDOW = 200000;
88
93
  /** Floor after `session/cancel` before the adapter forces the active prompt
89
94
  * loop to return "cancelled". `query.interrupt()` normally makes the SDK
90
95
  * yield a trailing idle within milliseconds, and the loop returns through its
@@ -182,68 +187,6 @@ async function structuredUsageMarkdown(query, signal, logger) {
182
187
  return null;
183
188
  }
184
189
  }
185
- /** Claude Code keeps the OAuth callback listener open in the background after
186
- * `mcpAuthenticate` returns the authorization URL. The SDK does not expose
187
- * that listener's completion promise, so watch the server status while the
188
- * ACP client has the URL elicitation open. */
189
- const MCP_OAUTH_STATUS_POLL_MS = 1_000;
190
- const MCP_OAUTH_TIMEOUT_MS = 10 * 60_000;
191
- function supportsMcpOAuth(query) {
192
- return typeof query.mcpAuthenticate === "function";
193
- }
194
- function supportsRemoteControl(query) {
195
- return typeof query.enableRemoteControl === "function";
196
- }
197
- const REMOTE_CONTROL_COMMAND_NAME = "remote-control";
198
- /** Parses `/remote-control [name]` and `/remote-control off` from a single-text
199
- * prompt. Connecting is idempotent, so the command never needs to know whether
200
- * Remote Control is already on. */
201
- function parseRemoteControlCommand(prompt) {
202
- const [first] = prompt;
203
- if (prompt.length !== 1 || first?.type !== "text")
204
- return null;
205
- const match = /^\/remote-control(?:\s+([\s\S]*))?$/.exec(first.text.trim());
206
- if (!match)
207
- return null;
208
- const argument = match[1]?.trim();
209
- if (argument?.toLowerCase() === "off")
210
- return { action: "disconnect" };
211
- return argument ? { action: "connect", name: argument } : { action: "connect" };
212
- }
213
- /** A top-level message a person typed in another client of the session, such
214
- * as claude.ai or the Claude mobile app over Remote Control. Tool results and
215
- * the CLI's own synthetic messages are user-role too, but carry no human
216
- * origin. */
217
- function isRemoteHumanMessage(message) {
218
- return (message.type === "user" &&
219
- message.origin?.kind === "human" &&
220
- message.parent_tool_use_id === null &&
221
- !message.isSynthetic);
222
- }
223
- /** Whether Claude Code offers a slash command of this name to an ACP client.
224
- * This is the rule `getAvailableSlashCommands` applies when it lists the
225
- * commands, so the adapter stands in for the command exactly when the client
226
- * sees the adapter's entry: Claude Code's terminal-bound commands are not
227
- * offered, and a user's own command or skill of the name is never shadowed. */
228
- function claudeCodeOffersCommand(commands, terminalCommands, name) {
229
- return commands.some((command) => command.name === name && !terminalCommands?.includes(command.name));
230
- }
231
- /** Wait for a polling interval, resolving false when the session is aborted. */
232
- function waitUnlessAborted(milliseconds, signal) {
233
- if (signal.aborted)
234
- return Promise.resolve(false);
235
- return new Promise((resolve) => {
236
- const timer = setTimeout(() => {
237
- signal.removeEventListener("abort", onAbort);
238
- resolve(true);
239
- }, milliseconds);
240
- const onAbort = () => {
241
- clearTimeout(timer);
242
- resolve(false);
243
- };
244
- signal.addEventListener("abort", onAbort, { once: true });
245
- });
246
- }
247
190
  /** Error surfaced when the SDK declares a turn over (`session_state_changed:
248
191
  * idle`, its authoritative turn-over signal) without ever emitting the turn's
249
192
  * `result` — a model stream that dropped mid-turn, or an async agent that
@@ -329,26 +272,19 @@ function parseSteerRequest(params) {
329
272
  * Exception: a result from one of these origins that names a pending prompt
330
273
  * in `user_message_uuids` consumed that folded prompt and takes the user
331
274
  * lane (see the result handler). */
332
- const AUTONOMOUS_RESULT_ORIGINS = new Set([
275
+ export const AUTONOMOUS_RESULT_ORIGINS = new Set([
333
276
  "task-notification",
334
277
  "peer",
335
278
  "coordinator",
336
279
  "observer",
337
280
  "observer-activity",
338
281
  ]);
339
- /** The foreground work of a session (see ForegroundEvents): a prompt's turn,
340
- * or a model cycle that Claude Code started on its own. At most one cycle
341
- * runs at a time, so a constant names it. */
342
- const AUTONOMOUS_CYCLE = "autonomous-cycle";
343
- /** The events of a connection that reports no foreground work: v1, whose
344
- * client has no session state. The agent still tracks the work, which
282
+ /** The foreground work of a session: a prompt's turn, from its insertion
283
+ * until its result, or a model cycle that Claude Code started on its own
284
+ * (see `startAutonomousCycle`). At most one cycle runs at a time, so a
285
+ * constant names it. The client is told nothing of the work itself, but it
345
286
  * decides what the window after a cancel drops (see `workEndReported`). */
346
- const UNREPORTED_FOREGROUND = {
347
- running: () => { },
348
- awaitingUser: () => { },
349
- ended: () => { },
350
- failed: () => { },
351
- };
287
+ const AUTONOMOUS_CYCLE = "autonomous-cycle";
352
288
  /** Whether this turn's terminal result arrived but its settlement is being
353
289
  * held for background subagents it spawned (see Turn.deferredSettle). The
354
290
  * single spelling of the hold predicate, shared by the consumer's settle
@@ -519,66 +455,9 @@ export function computeSessionFingerprint(params) {
519
455
  options,
520
456
  }));
521
457
  }
522
- /** `params` without `_meta.claudeCode.options.effort`. */
523
- function withoutEffort(params) {
524
- const meta = params._meta;
525
- if (meta?.claudeCode?.options?.effort === undefined) {
526
- return params;
527
- }
528
- const options = { ...meta.claudeCode.options };
529
- delete options.effort;
530
- return { ...params, _meta: { ...meta, claudeCode: { ...meta.claudeCode, options } } };
531
- }
532
458
  /** The JSON-RPC code ACP assigns to `authRequired`. Read from the SDK so it
533
459
  * cannot drift from the errors this agent throws. */
534
460
  const AUTH_REQUIRED_CODE = RequestError.authRequired().code;
535
- const SUPPORTED_PROTOCOLS = ["anthropic", "bedrock", "vertex"];
536
- const PROVIDER_ID = "main";
537
- const DEFAULT_ANTHROPIC_BASE_URL = "https://api.anthropic.com";
538
- const DEFAULT_VERTEX_BASE_URL = "https://aiplatform.googleapis.com";
539
- /**
540
- * The blocks of a consolidated assistant message without the text that
541
- * already streamed as deltas.
542
- *
543
- * Each assembled text/thinking block is diffed against the streamed blocks in
544
- * document order: nothing is left if it streamed in full (the common case),
545
- * the whole block if it never streamed (a non-streaming gateway), and just the
546
- * tail if the stream was cut short mid-block. Matching on content rather than
547
- * the message id keeps the dedupe robust for gateways without a stable id.
548
- * Tool-use and other blocks pass through untouched.
549
- */
550
- function unstreamedRemainder(blocks, streamedBlocks) {
551
- const kept = [];
552
- let streamPos = 0;
553
- for (const item of blocks) {
554
- if (item.type !== "text" && item.type !== "thinking") {
555
- kept.push(item);
556
- continue;
557
- }
558
- const block = item;
559
- const full = (item.type === "text" ? block.text : block.thinking) ?? "";
560
- // Empty assembled blocks carry nothing: drop them.
561
- if (full.length === 0)
562
- continue;
563
- // A streamed block of the same type whose text is a prefix of this one
564
- // was already delivered, at least partly. A non-empty streamed text is
565
- // required so an empty or aborted streamed block does not swallow it.
566
- const streamed = streamedBlocks[streamPos];
567
- if (streamed &&
568
- streamed.type === item.type &&
569
- streamed.text.length > 0 &&
570
- full.startsWith(streamed.text)) {
571
- streamPos++;
572
- const remainder = full.slice(streamed.text.length);
573
- if (remainder.length === 0)
574
- continue;
575
- kept.push({ ...item, [item.type === "text" ? "text" : "thinking"]: remainder });
576
- continue;
577
- }
578
- kept.push(item);
579
- }
580
- return kept;
581
- }
582
461
  /** Attributes a report to the Agent/Task tool call of the subagent that made it. */
583
462
  function stampParentToolUseId(update, parentToolUseId) {
584
463
  update._meta = {
@@ -828,16 +707,12 @@ function isTaskNotificationRecord(message) {
828
707
  const origin = message.origin;
829
708
  return origin?.kind === "task-notification" && origin.subkind === undefined;
830
709
  }
831
- /**
832
- * True when CLI error text tells the user to sign in with `/login`. The CLI
833
- * words this several ways — "Not logged in · Please run /login", "Not logged
834
- * in · Run /login", "Login expired · Run /login to sign in again, or
835
- * re-authenticate your Anthropic profile" — so match the "run /login"
836
- * instruction rather than one sentence.
837
- */
838
- export function isLoginRequiredText(text) {
839
- return /\brun \/login\b/i.test(text);
840
- }
710
+ /** The session failure of an error result at one of Claude Code's limits. */
711
+ const LIMIT_FAILURE_CATEGORY = {
712
+ error_max_budget_usd: "budget_exhausted",
713
+ error_max_turns: "context_exhausted",
714
+ error_max_structured_output_retries: "provider_error",
715
+ };
841
716
  /**
842
717
  * True for the synthetic assistant message the CLI injects into the transcript
843
718
  * when a turn fails authentication (e.g. "Not logged in · Please run /login",
@@ -1001,9 +876,6 @@ function raceWithAbort(operation, signal) {
1001
876
  });
1002
877
  });
1003
878
  }
1004
- /** Background OAuth work is implementation state, not part of the public
1005
- * `Session` shape exposed through `ClaudeAcpAgent.sessions`. */
1006
- const mcpAuthentications = new WeakMap();
1007
879
  /** Start OAuth for ACP-provided MCP servers that Claude reported as needing
1008
880
  * authentication. This runs after session creation has returned so an
1009
881
  * interactive browser flow never delays `session/new`. */
@@ -1013,117 +885,23 @@ function startMcpAuthentication(host, sessionId, mcpServers) {
1013
885
  startMcpServerAuthentication(host, sessionId, new Set(mcpServers.map((server) => server.name)));
1014
886
  }
1015
887
  /** Start OAuth in the background for the servers in `requestedServers` that
1016
- * Claude reports as needing authentication. Startup and `/mcp` use it. It
1017
- * does nothing while another OAuth run of the session is in progress. */
888
+ * Claude reports as needing authentication (see `mcp-oauth.ts`). Startup and
889
+ * `/mcp` use it. */
1018
890
  function startMcpServerAuthentication(host, sessionId, requestedServers) {
1019
- if (!host.clientCapabilities?.elicitation?.url)
1020
- return;
1021
- const session = host.sessions[sessionId];
1022
- if (!session || mcpAuthentications.has(session))
1023
- return;
1024
- const authentication = authenticateMcpServers(host, sessionId, session.query, requestedServers)
1025
- .catch((error) => {
1026
- if (!session.abortController.signal.aborted) {
1027
- host.logger.error(`Failed to inspect MCP servers for OAuth: ${error}`);
1028
- }
1029
- })
1030
- .finally(() => {
1031
- if (mcpAuthentications.get(session) === authentication) {
1032
- mcpAuthentications.delete(session);
1033
- }
1034
- });
1035
- mcpAuthentications.set(session, authentication);
1036
- }
1037
- async function authenticateMcpServers(host, sessionId, query, requestedServers) {
1038
- if (!supportsMcpOAuth(query)) {
1039
- host.logger.error("The Claude Agent SDK does not expose MCP OAuth authentication.");
1040
- return;
1041
- }
1042
- const statuses = await query.mcpServerStatus();
1043
- for (const status of statuses) {
1044
- if (status.status !== "needs-auth" || !requestedServers.has(status.name))
1045
- continue;
1046
- try {
1047
- await authenticateMcpServer(host, sessionId, query, status.name);
1048
- }
1049
- catch (error) {
1050
- const session = host.sessions[sessionId];
1051
- if (session && !session.abortController.signal.aborted) {
1052
- host.logger.error(`Failed to authenticate MCP server ${status.name}: ${error}`);
1053
- }
1054
- }
1055
- }
1056
- }
1057
- /** Bridge Claude Code's startup MCP OAuth control to ACP URL elicitation.
1058
- * Claude opens and owns the localhost callback listener; the ACP client only
1059
- * needs to present the returned authorization URL. */
1060
- async function authenticateMcpServer(host, sessionId, query, serverName) {
1061
891
  const session = host.sessions[sessionId];
1062
892
  if (!session)
1063
893
  return;
1064
- const login = await query.mcpAuthenticate(serverName);
1065
- if (!login.requiresUserAction)
1066
- return;
1067
- if (!login.authUrl) {
1068
- throw new Error("Claude Code requested user action without returning an authorization URL");
1069
- }
1070
- const elicitationId = `mcp-oauth-${randomUUID()}`;
1071
- const flowAbort = new AbortController();
1072
- const abortFlow = () => flowAbort.abort(session.abortController.signal.reason);
1073
- session.abortController.signal.addEventListener("abort", abortFlow, { once: true });
1074
- if (session.abortController.signal.aborted)
1075
- abortFlow();
1076
- try {
1077
- const completed = waitForMcpAuthentication(host.sessions, sessionId, query, serverName, flowAbort.signal);
1078
- const elicitation = host.client.createElicitation({
1079
- mode: "url",
1080
- sessionId,
1081
- message: `Authenticate with MCP server ${serverName}`,
1082
- url: login.authUrl,
1083
- elicitationId,
1084
- }, flowAbort.signal);
1085
- const first = await Promise.race([
1086
- completed.then((authenticated) => ({ type: "completed", authenticated })),
1087
- elicitation.then((response) => ({ type: "elicitation", response })),
1088
- ]);
1089
- // A url-mode accept carries no content to check. The guard
1090
- // `CreateElicitationResponse.isAccept` would also reject an accept whose
1091
- // `content` holds a v2-only value, such as an object.
1092
- if (first.type === "elicitation" && first.response.action !== "accept") {
1093
- return;
1094
- }
1095
- if (first.type === "elicitation") {
1096
- await completed;
1097
- }
1098
- try {
1099
- await host.client.completeElicitation({ elicitationId });
1100
- }
1101
- catch (error) {
1102
- if (!flowAbort.signal.aborted) {
1103
- host.logger.error(`Failed to complete MCP OAuth elicitation: ${error}`);
1104
- }
1105
- }
1106
- }
1107
- finally {
1108
- flowAbort.abort();
1109
- session.abortController.signal.removeEventListener("abort", abortFlow);
1110
- }
1111
- }
1112
- async function waitForMcpAuthentication(sessions, sessionId, query, serverName, signal) {
1113
- const deadline = Date.now() + MCP_OAUTH_TIMEOUT_MS;
1114
- while (!signal.aborted && Date.now() < deadline) {
1115
- const session = sessions[sessionId];
1116
- if (!session || session.query !== query)
1117
- return false;
1118
- const status = (await query.mcpServerStatus()).find((server) => server.name === serverName);
1119
- if (!status || status.status === "failed" || status.status === "disabled")
1120
- return false;
1121
- if (status.status === "connected")
1122
- return true;
1123
- if (!(await waitUnlessAborted(MCP_OAUTH_STATUS_POLL_MS, signal)))
1124
- return false;
1125
- }
1126
- return false;
894
+ startSharedMcpServerAuthentication({
895
+ urlElicitation: !!host.clientCapabilities?.elicitation?.url,
896
+ createElicitation: (params, signal) => host.client.createElicitation(params, signal),
897
+ completeElicitation: (params) => host.client.completeElicitation(params),
898
+ logger: host.logger,
899
+ }, {
900
+ key: session,
901
+ sessionId,
902
+ currentQuery: () => host.sessions[sessionId]?.query,
903
+ closed: session.abortController.signal,
904
+ }, requestedServers);
1127
905
  }
1128
906
  export class ClaudeAcpAgent {
1129
907
  sessions;
@@ -1141,27 +919,22 @@ export class ClaudeAcpAgent {
1141
919
  /** Per session: queue that runs mode/config changes and query restarts one at a time. */
1142
920
  configurationChanges = new Map();
1143
921
  exitPlan;
1144
- /** Last auth identity reported to the client, connection-scoped like
1145
- * `authenticate`/`logout`. Undefined means "not determined yet". */
1146
- currentAuthStatus;
1147
- authStatusSettings;
1148
- authStatusHelper;
1149
- /** In-flight `claude auth status --json` probe, shared by every caller so
1150
- * a concurrent `initialize` and start-of-prompt read never spawn two CLI
1151
- * processes. */
1152
- cliAuthProbe = null;
1153
- /** Counts auth-affecting events (`authenticate`, `logout`) on this
1154
- * connection. A probe records it at start and publishes only if it has not
1155
- * moved, so a slow read can never overwrite a newer login or logout. */
1156
- authEpoch = 0;
1157
- /** Keeps the "session account told us nothing" note to one line per process
1158
- * instead of one per session. */
1159
- loggedUninformativeAccount = false;
1160
- /** Same, for the "client provider override active" note. */
1161
- loggedOverriddenAccount = false;
1162
- /** Same, for the "the CLI probe timed out" warning: a wedged CLI stays wedged
1163
- * and would otherwise warn once per probe, i.e. once per user prompt. */
1164
- loggedProbeTimeout = false;
922
+ /** The connection's `authStatus` state and pushes, connection-scoped like
923
+ * `authenticate`/`logout`. */
924
+ authStatus = new AuthStatusReporter({
925
+ push: (authStatus) => this.client.extNotification(AUTH_STATUS_UPDATE_METHOD, { authStatus }),
926
+ logger: {
927
+ log: (...args) => this.logger.log(...args),
928
+ error: (...args) => this.logger.error(...args),
929
+ },
930
+ gatewayLogin: () => this.gatewayAuthRequest !== undefined,
931
+ providerOverride: () => this.providerConfig !== undefined,
932
+ onProbe: (kind) => this.markSessionsWhoseAccountKindChanged(kind),
933
+ });
934
+ /** Last auth identity reported to the client. Undefined means "not determined yet". */
935
+ get currentAuthStatus() {
936
+ return this.authStatus.current;
937
+ }
1165
938
  /** Grace period before a `session/cancel` forces a wedged prompt loop to
1166
939
  * return "cancelled". See {@link DEFAULT_FORCE_CANCEL_GRACE_MS}. Mutable so
1167
940
  * tests can shrink it. */
@@ -1169,12 +942,6 @@ export class ClaudeAcpAgent {
1169
942
  /** How long `canUseTool` or a hook waits for the consumer to reach a tool
1170
943
  * use (see `isStoppedWorkToolUse`). Mutable so tests can shrink it. */
1171
944
  toolUseWaitMs = TOOL_USE_WAIT_MS;
1172
- /**
1173
- * The connection serves ACP v2 (`src/v2/`). The agent still speaks v1
1174
- * types, except for the tool call content that v2 needs and v1 cannot
1175
- * express: see {@link ToolCallClientCapabilities.v2}.
1176
- */
1177
- v2;
1178
945
  /**
1179
946
  * The subagent replay of each session's last load, until
1180
947
  * {@link publishCurrentSubagentStates} sends its children's current states.
@@ -1186,10 +953,6 @@ export class ClaudeAcpAgent {
1186
953
  * {@link publishReplayedChildModels}.
1187
954
  */
1188
955
  replayedChildModels = new Map();
1189
- /** See the `foreground` constructor option. */
1190
- foregroundEvents;
1191
- /** See the `background` constructor option. */
1192
- backgroundWork;
1193
956
  /** Counts the prompts `startTurn()` has received, across sessions. */
1194
957
  promptsReceived = 0;
1195
958
  /** Per session, the `promptsReceived` count when its last cancel started.
@@ -1197,11 +960,11 @@ export class ClaudeAcpAgent {
1197
960
  * yet ends as cancelled instead of being queued. */
1198
961
  cancelledThrough = new Map();
1199
962
  /**
1200
- * The foreground work of each session while it runs, by the session id that
1201
- * the client knows, on every connection: only the `foreground` option
1202
- * reports it. A clear-context restart replaces the Claude Code session
1203
- * behind that id and moves the running turn to it, so the work belongs to the
1204
- * id, not to a {@link Session}.
963
+ * The owner of the foreground work of each session while it runs (see
964
+ * {@link ForegroundOwner}), by the session id that the client knows. A
965
+ * clear-context restart replaces the Claude Code session behind that id and
966
+ * moves the running turn to it, so the work belongs to the id, not to a
967
+ * {@link Session}.
1205
968
  */
1206
969
  foregroundWork = new Map();
1207
970
  /** The session index (docs/air-extensions.md, "Session index"). */
@@ -1213,18 +976,14 @@ export class ClaudeAcpAgent {
1213
976
  });
1214
977
  /**
1215
978
  * Whether a turn ends at its result while background subagents that it
1216
- * spawned or resumed still run. Only an ACP v1 AIR client that declares
979
+ * spawned or resumed still run. Only an AIR client that declares
1217
980
  * `backgroundSubagents` gets this. Every other client keeps the hold of
1218
981
  * `Turn.deferredSettle`.
1219
982
  */
1220
983
  endsTurnsWithLiveSubagents() {
1221
- return (!this.v2 &&
1222
- clientSupportsAirCapability(this.clientCapabilities, AIR_BACKGROUND_SUBAGENTS_CAPABILITY));
984
+ return clientSupportsAirCapability(this.clientCapabilities, AIR_BACKGROUND_SUBAGENTS_CAPABILITY);
1223
985
  }
1224
- constructor(client, logger, options = {}) {
1225
- this.v2 = options.v2 ?? false;
1226
- this.foregroundEvents = options.foreground;
1227
- this.backgroundWork = new BackgroundWorkReporter(options.background);
986
+ constructor(client, logger) {
1228
987
  this.sessions = {};
1229
988
  this.client = new ChangedMetaClient(client, () => this.toolCallCapabilities.air.client);
1230
989
  this.logger = logger ?? console;
@@ -1285,16 +1044,14 @@ export class ClaudeAcpAgent {
1285
1044
  }
1286
1045
  async initialize(request) {
1287
1046
  this.clientCapabilities = request.clientCapabilities;
1288
- this.toolCallCapabilities = ToolCallClientCapabilities.from(request.clientCapabilities, {
1289
- v2: this.v2,
1290
- });
1291
- this.sessionIndex.negotiate(request, { v2: this.v2 });
1047
+ this.toolCallCapabilities = ToolCallClientCapabilities.from(request.clientCapabilities);
1048
+ this.sessionIndex.negotiate(request);
1292
1049
  // Learn the auth identity in the background: `initialize` never waits on
1293
1050
  // the CLI probe, and no snapshot rides in its response. When the probe
1294
1051
  // lands it calls `setAuthStatus`, which pushes `_auth/status_update` — the
1295
1052
  // connection's first push, and unconditional, because nothing was reported
1296
1053
  // before it. It is therefore sent after this response, never before it.
1297
- void this.probeCliAuthStatus();
1054
+ void this.authStatus.probe();
1298
1055
  // Bypasses standard auth by routing requests through a custom Anthropic-protocol gateway.
1299
1056
  // Only offered when the client advertises `auth._meta.gateway` capability.
1300
1057
  const supportsGatewayAuth = request.clientCapabilities?.auth?._meta?.gateway === true;
@@ -1320,79 +1077,10 @@ export class ClaudeAcpAgent {
1320
1077
  };
1321
1078
  const supportsTerminalAuth = request.clientCapabilities?.auth?.terminal === true;
1322
1079
  const supportsMetaTerminalAuth = request.clientCapabilities?._meta?.["terminal-auth"] === true;
1323
- // Detect remote environments where the OAuth browser redirect to localhost
1324
- // won't work. This matches the SDK's internal isRemote check. In these cases,
1325
- // the `auth login` subcommand would fall back to a device-code-like manual
1326
- // flow, which doesn't work well over ACP, so we offer the TUI login instead.
1327
- const isRemote = !!(process.env.NO_BROWSER ||
1328
- process.env.SSH_CONNECTION ||
1329
- process.env.SSH_CLIENT ||
1330
- process.env.SSH_TTY ||
1331
- process.env.CLAUDE_CODE_REMOTE);
1332
- const terminalAuthMethods = [];
1333
- if (isRemote) {
1334
- const remoteLoginMethod = {
1335
- description: "Run `claude /login` in the terminal",
1336
- name: "Log in with Claude",
1337
- id: "claude-login",
1338
- type: "terminal",
1339
- args: ["--cli"],
1340
- };
1341
- if (supportsMetaTerminalAuth) {
1342
- const agent = agentCommand();
1343
- remoteLoginMethod._meta = {
1344
- "terminal-auth": {
1345
- command: agent.command,
1346
- args: [...agent.args, "--cli"],
1347
- label: "Claude Login",
1348
- },
1349
- };
1350
- }
1351
- if (!shouldHideClaudeAuth() && (supportsTerminalAuth || supportsMetaTerminalAuth)) {
1352
- terminalAuthMethods.push(remoteLoginMethod);
1353
- }
1354
- }
1355
- else {
1356
- const claudeLoginMethod = {
1357
- description: "Use Claude subscription ",
1358
- name: "Claude Subscription",
1359
- id: "claude-ai-login",
1360
- type: "terminal",
1361
- args: ["--cli", "auth", "login", "--claudeai"],
1362
- };
1363
- const consoleLoginMethod = {
1364
- description: "Use Anthropic Console (API usage billing)",
1365
- name: "Anthropic Console",
1366
- id: "console-login",
1367
- type: "terminal",
1368
- args: ["--cli", "auth", "login", "--console"],
1369
- };
1370
- if (supportsMetaTerminalAuth) {
1371
- const agent = agentCommand();
1372
- claudeLoginMethod._meta = {
1373
- "terminal-auth": {
1374
- command: agent.command,
1375
- args: [...agent.args, "--cli", "auth", "login", "--claudeai"],
1376
- label: "Claude Login",
1377
- },
1378
- };
1379
- consoleLoginMethod._meta = {
1380
- "terminal-auth": {
1381
- command: agent.command,
1382
- args: [...agent.args, "--cli", "auth", "login", "--console"],
1383
- label: "Anthropic Console Login",
1384
- },
1385
- };
1386
- }
1387
- if (!shouldHideClaudeAuth() && (supportsTerminalAuth || supportsMetaTerminalAuth)) {
1388
- terminalAuthMethods.push(claudeLoginMethod);
1389
- }
1390
- if (supportsTerminalAuth || supportsMetaTerminalAuth) {
1391
- terminalAuthMethods.push(consoleLoginMethod);
1392
- }
1393
- }
1394
- // The subagents RFD has only the client capability. AIR's draft also had
1395
- // this agent capability, which AIR gets (`docs/air-extensions.md`).
1080
+ const terminalAuthMethods = authMethodsForTerminal({
1081
+ terminal: supportsTerminalAuth,
1082
+ metaTerminal: supportsMetaTerminalAuth,
1083
+ });
1396
1084
  const sessionCapabilities = {
1397
1085
  additionalDirectories: {},
1398
1086
  close: {},
@@ -1450,9 +1138,7 @@ export class ClaudeAcpAgent {
1450
1138
  // `jetbrains.air`.
1451
1139
  _meta: {
1452
1140
  ...(this.toolCallCapabilities.air.client
1453
- ? withAirMeta(airSessionFailureCapabilityMeta(AGENT_FILE_CHANGE_REPORT_CAPABILITY, AIR_NATIVE_SUBAGENT_SESSIONS_CAPABILITY, AIR_ASYNC_TASKS_CAPABILITY, AIR_CUSTOM_INSTRUCTIONS_CAPABILITY, AIR_RECOMMENDED_CONFIG_VALUE_CAPABILITY, AIR_DIFF_PATCH_CAPABILITY, AIR_PLAN_FILE_CAPABILITY,
1454
- // ACP v2 keeps the hold (see `src/v2/prompt.ts`).
1455
- ...(this.v2 ? [] : [AIR_BACKGROUND_SUBAGENTS_CAPABILITY]), ...this.sessionIndex.capabilities()), AIR_GOAL_KEY, {
1141
+ ? withAirMeta(airSessionFailureCapabilityMeta(AGENT_FILE_CHANGE_REPORT_CAPABILITY, AIR_NATIVE_SUBAGENT_SESSIONS_CAPABILITY, AIR_ASYNC_TASKS_CAPABILITY, AIR_CUSTOM_INSTRUCTIONS_CAPABILITY, AIR_RECOMMENDED_CONFIG_VALUE_CAPABILITY, AIR_DIFF_PATCH_CAPABILITY, AIR_PLAN_FILE_CAPABILITY, AIR_BACKGROUND_SUBAGENTS_CAPABILITY, ...this.sessionIndex.capabilities()), AIR_GOAL_KEY, {
1456
1142
  version: GOAL_EXTENSION_VERSION,
1457
1143
  controlMethod: GOAL_CONTROL_METHOD,
1458
1144
  actions: [...GOAL_ACTIONS],
@@ -1487,6 +1173,7 @@ export class ClaudeAcpAgent {
1487
1173
  state: {
1488
1174
  cwd: params.cwd,
1489
1175
  taskState: new Map(),
1176
+ subagentChecklists: new Set(),
1490
1177
  forwardSubagentText: this.forwardsSubagentText(params._meta),
1491
1178
  messageIdToUuid: new Map(),
1492
1179
  sessionFailureState: createSessionFailureState(),
@@ -1658,221 +1345,24 @@ export class ClaudeAcpAgent {
1658
1345
  }
1659
1346
  /**
1660
1347
  * `authenticate` — the legacy gateway methods store a provider override that
1661
- * every later session reads. Validate the payload here, with the same base
1662
- * URL rule as `providers/set`. An unchecked payload either throws a
1663
- * `TypeError` deep in session creation, or installs an empty base URL that
1664
- * silently turns the `--hide-claude-auth` subscription guard off.
1665
- *
1666
- * A call that carries no gateway payload at all keeps its historical
1667
- * meaning: it installs no override and succeeds. That has always been a
1668
- * no-op here, and a client that probes the method this way must keep
1669
- * working. Only a payload that IS present has to be usable.
1348
+ * every later session reads, once {@link validatedGatewayAuthRequest} accepts
1349
+ * its payload.
1670
1350
  */
1671
1351
  async authenticate(_params) {
1672
- if (_params.methodId === "gateway" || _params.methodId === "gateway-bedrock") {
1673
- const gateway = _params._meta?.gateway;
1674
- if (gateway !== undefined && gateway !== null) {
1675
- if (typeof gateway !== "object" || !isValidBaseUrl(gateway.baseUrl)) {
1676
- throw RequestError.invalidParams({ baseUrl: gateway.baseUrl }, "`_meta.gateway.baseUrl` must be a non-empty absolute http(s) URL.");
1677
- }
1678
- if (gateway.headers !== undefined && typeof gateway.headers !== "object") {
1679
- throw RequestError.invalidParams(undefined, "`_meta.gateway.headers` must be an object of header names to values.");
1680
- }
1681
- }
1682
- this.gatewayAuthRequest = _params;
1352
+ if (isGatewayAuthMethod(_params.methodId)) {
1353
+ this.gatewayAuthRequest = validatedGatewayAuthRequest(_params);
1683
1354
  // The gateway holds the credentials from here on, so it replaces
1684
1355
  // whatever the CLI store reported. Bumping the epoch discards any probe
1685
1356
  // that started before this login: its answer is now stale.
1686
- this.authEpoch += 1;
1687
- this.setAuthStatus(gatewayAuthStatus(gatewayRequestToProviderConfig(this.gatewayAuthRequest)?.baseUrl));
1357
+ this.authStatus.changed();
1358
+ this.authStatus.set(gatewayAuthStatus(gatewayRequestToProviderConfig(this.gatewayAuthRequest)?.baseUrl));
1688
1359
  return;
1689
1360
  }
1690
1361
  throw RequestError.invalidParams({ methodId: _params.methodId }, `Unsupported authentication method: ${_params.methodId}`);
1691
1362
  }
1692
- /**
1693
- * Stores `next` and pushes it to the client.
1694
- *
1695
- * A push goes out only when the payload changed. The identity is read on many
1696
- * occasions — each session create, each guarded turn, the start of each user
1697
- * prompt — and almost all of them see the same login. Clients replace their
1698
- * whole state on each update and tolerate duplicates, so a repeat is
1699
- * harmless, but it is also pure noise; {@link sameAuthStatus} drops it.
1700
- *
1701
- * What the agent owes is truth — a stale or uninformative source must not
1702
- * reach here at all (see the epoch check in the probe and the guards at
1703
- * session create).
1704
- */
1363
+ /** Stores `next` and pushes it to the client when it changed (see {@link AuthStatusReporter.set}). */
1705
1364
  setAuthStatus(next) {
1706
- if (!next) {
1707
- return;
1708
- }
1709
- if (sameAuthStatus(this.currentAuthStatus, next)) {
1710
- return;
1711
- }
1712
- this.currentAuthStatus = next;
1713
- // ACP notifications get no reply, and clients that do not know the method
1714
- // drop it silently — send unconditionally and never fail a caller on it.
1715
- void Promise.resolve()
1716
- .then(() => this.client.extNotification(AUTH_STATUS_UPDATE_METHOD, { authStatus: next }))
1717
- .catch((error) => {
1718
- this.logger.error("Failed to send _auth/status_update:", error);
1719
- });
1720
- }
1721
- /**
1722
- * Report the identity behind a session's `AccountInfo`.
1723
- *
1724
- * `AccountInfo` is richer than the CLI probe (it is what the live query
1725
- * actually authenticates with). Called before the `--hide-claude-auth` guard
1726
- * may refuse the session or the turn: that flag blocks the *use* of a
1727
- * subscription, it does not make the state secret, and a refusal is when the
1728
- * client most needs to know the account it was refused for.
1729
- *
1730
- * Two cases skip it:
1731
- *
1732
- * - ACP gateway *authentication* (`gatewayAuthRequest`): the gateway, not
1733
- * this account, is the agent-owned identity — already reported as
1734
- * `kind: "gateway"` by `authenticate`.
1735
- * - A client-driven provider override (`providers/set`): the session then
1736
- * routes through the client's endpoint and `AccountInfo` describes that
1737
- * route (e.g. `apiProvider: "gateway"`), which is NOT agent-owned state.
1738
- * `authStatus` reports the agent's own login only, so the CLI probe —
1739
- * which reads the credential store the override never touches — stays
1740
- * authoritative.
1741
- *
1742
- * An account with no identity signal (e.g. `{apiProvider: "firstParty"}`
1743
- * under an apiKeyHelper) means "nothing to add", not "logged out" — keep
1744
- * what the CLI probe already established instead of overwriting it.
1745
- */
1746
- useAuthStatusSettings(manager, settingsOverride, launchEnv) {
1747
- const helper = manager.getApiKeyHelper(settingsOverride);
1748
- const changed = manager.getCwd() !== (this.authStatusSettings?.manager.getCwd() ?? process.cwd()) ||
1749
- helper !== this.authStatusHelper ||
1750
- JSON.stringify(launchEnv) !== JSON.stringify(this.authStatusSettings?.env);
1751
- this.authStatusSettings = { manager, override: settingsOverride, env: launchEnv };
1752
- this.authStatusHelper = helper;
1753
- if (changed) {
1754
- // The epoch bump discards any probe that read the old context, and the
1755
- // session account may carry no identity signal (an apiKeyHelper), so
1756
- // only a probe in the new context can classify it.
1757
- this.authEpoch += 1;
1758
- void this.probeCliAuthStatus({ fresh: true });
1759
- }
1760
- }
1761
- publishSessionAccountIdentity(account, apiKeyHelper) {
1762
- if (this.providerConfig) {
1763
- if (!this.loggedOverriddenAccount) {
1764
- this.loggedOverriddenAccount = true;
1765
- this.logger.log("[authStatus] client provider override active; keeping agent-owned probe state");
1766
- }
1767
- return;
1768
- }
1769
- if (this.gatewayAuthRequest) {
1770
- return;
1771
- }
1772
- const fromSession = fromAccountInfo(account, apiKeyHelper);
1773
- if (fromSession) {
1774
- this.setAuthStatus(fromSession);
1775
- }
1776
- else if (!this.loggedUninformativeAccount) {
1777
- this.loggedUninformativeAccount = true;
1778
- this.logger.log("[authStatus] session account carries no identity signal; keeping probe");
1779
- }
1780
- }
1781
- /** Shares one in-flight `claude auth status --json` run between callers. The
1782
- * promise is released once settled so a later call re-probes instead of
1783
- * replaying a stale verdict. `fresh` forces a new run even when one is in
1784
- * flight — `logout` needs a read that started after the credentials were
1785
- * cleared. */
1786
- probeCliAuthStatus(options) {
1787
- if (!options?.fresh && this.cliAuthProbe) {
1788
- return this.cliAuthProbe;
1789
- }
1790
- const probe = this.runCliAuthProbe();
1791
- this.cliAuthProbe = probe;
1792
- void probe.finally(() => {
1793
- if (this.cliAuthProbe === probe) {
1794
- this.cliAuthProbe = null;
1795
- }
1796
- });
1797
- return probe;
1798
- }
1799
- /** Never rejects: an unavailable CLI means "not reported", not an error. */
1800
- async runCliAuthProbe() {
1801
- // Monotonicity: a read that started before the connection's latest
1802
- // auth-affecting event describes a world that no longer exists. Remember
1803
- // which one this read belongs to and drop the answer if it moved on.
1804
- const epoch = this.authEpoch;
1805
- const context = this.authStatusSettings;
1806
- const apiKeyHelper = context?.manager.getApiKeyHelper(context.override);
1807
- // ACP gateway auth bypasses the CLI credential store entirely, so the
1808
- // probe would report an identity that is not the one being used. A mere
1809
- // client provider override (`providers/set`) does NOT skip the probe: it
1810
- // reroutes traffic without touching the credential store, and the store is
1811
- // exactly the agent-owned login `authStatus` reports.
1812
- if (this.gatewayAuthRequest) {
1813
- return this.currentAuthStatus;
1814
- }
1815
- let stdout;
1816
- try {
1817
- const cliPath = await claudeCliPath();
1818
- const args = ["auth", "status", "--json"];
1819
- // `--settings` is a global CLI option: after the `auth status` subcommand the CLI rejects
1820
- // it with "unknown option '--settings'", so it has to come first.
1821
- if (context?.override)
1822
- args.unshift("--settings", JSON.stringify(context.override));
1823
- ({ stdout } = await execFileAsync(cliPath, args, {
1824
- timeout: AUTH_STATUS_PROBE_TIMEOUT_MS,
1825
- cwd: context?.manager.getCwd() ?? process.cwd(),
1826
- env: context?.env ? { ...process.env, ...context.env } : process.env,
1827
- }));
1828
- }
1829
- catch (error) {
1830
- const failed = error;
1831
- // Node killed the child on the timeout. Whatever it printed so far is a
1832
- // truncated fragment, never valid JSON: report nothing and keep the last
1833
- // known state, so nothing regresses and no push goes out.
1834
- if (failed?.killed === true && failed.signal) {
1835
- if (!this.loggedProbeTimeout) {
1836
- this.loggedProbeTimeout = true;
1837
- this.logger.error("claude auth status did not answer within 5 s; the identity is not refreshed");
1838
- }
1839
- return this.currentAuthStatus;
1840
- }
1841
- // The logged-out case exits 1 while still printing valid JSON, so the
1842
- // stdout of a failed exec is parsed just like a successful one.
1843
- if (typeof failed?.stdout !== "string" || failed.stdout.trim().length === 0) {
1844
- this.logger.error("claude auth status failed:", error instanceof Error ? error.message : String(error));
1845
- return undefined;
1846
- }
1847
- stdout = failed.stdout;
1848
- }
1849
- let status = fromCliStatus(stdout, apiKeyHelper);
1850
- if (!context && status?.kind === "api_key" && status.detail === "API key helper") {
1851
- try {
1852
- const resolved = await resolveSettings({ cwd: process.cwd() });
1853
- status = fromCliStatus(stdout, filterEscalatingDefaultMode(resolved).apiKeyHelper);
1854
- }
1855
- catch {
1856
- this.logger.error("Could not resolve auth source settings");
1857
- }
1858
- }
1859
- if (!status) {
1860
- this.logger.error("claude auth status returned unparseable output");
1861
- return undefined;
1862
- }
1863
- if (epoch !== this.authEpoch) {
1864
- // An `authenticate` or `logout` landed while this probe was running; the
1865
- // newer state wins and this answer is discarded, never published.
1866
- this.logger.log("[authStatus] discarding a probe that predates the latest auth change");
1867
- return this.currentAuthStatus;
1868
- }
1869
- // The CLI probe can be poorer than the session `AccountInfo` for the very
1870
- // same login (no organization, say). Keep those extra fields rather than
1871
- // regressing the payload; a different identity replaces it wholesale.
1872
- const merged = mergeAuthStatus(this.currentAuthStatus, status);
1873
- this.setAuthStatus(merged);
1874
- this.markSessionsWhoseAccountKindChanged(status.kind);
1875
- return merged;
1365
+ this.authStatus.set(next);
1876
1366
  }
1877
1367
  /**
1878
1368
  * Feed the completed probe to the `--hide-claude-auth` guard.
@@ -1909,51 +1399,18 @@ export class ClaudeAcpAgent {
1909
1399
  }
1910
1400
  }
1911
1401
  async unstable_listProviders(_params) {
1912
- const config = this.providerConfig ?? this.defaultProviderConfig();
1913
- this.logger.log(`[providers/list] apiType=${config.apiType} baseUrl=${config.baseUrl} overridden=${this.providerConfig !== undefined}`);
1914
- const provider = {
1915
- providerId: PROVIDER_ID,
1916
- supported: SUPPORTED_PROTOCOLS,
1917
- required: false,
1918
- current: { apiType: config.apiType, baseUrl: config.baseUrl },
1919
- };
1920
- return { providers: [provider] };
1402
+ const config = this.providerConfig ?? defaultProviderConfig(this.gatewayAuthRequest);
1403
+ this.logger.log(`[providers/list] apiType=${config.apiType} baseUrl=${loggableBaseUrl(config.baseUrl)} overridden=${this.providerConfig !== undefined}`);
1404
+ return listProvidersResponse(config);
1921
1405
  }
1922
1406
  /**
1923
- * `providers/set` — replace the full configuration for the `main` provider.
1924
- * Rejects unknown IDs, unsupported protocols, and empty/invalid base URLs with
1925
- * `invalid_params`. Config is process-scoped and applies to sessions created or
1926
- * loaded after this call.
1407
+ * `providers/set` — replace the full configuration for the `main` provider
1408
+ * (validated by {@link providerConfigFromSetRequest}). Config is
1409
+ * process-scoped and applies to sessions created or loaded after this call.
1927
1410
  */
1928
1411
  async unstable_setProvider(params) {
1929
- if (params.providerId !== PROVIDER_ID) {
1930
- throw RequestError.invalidParams({ providerId: params.providerId }, `Unknown provider ID "${params.providerId}"; expected "${PROVIDER_ID}".`);
1931
- }
1932
- if (!SUPPORTED_PROTOCOLS.includes(params.apiType)) {
1933
- throw RequestError.invalidParams({ apiType: params.apiType, supported: SUPPORTED_PROTOCOLS }, `Unsupported apiType "${params.apiType}" for provider "${PROVIDER_ID}".`);
1934
- }
1935
- if (!isValidBaseUrl(params.baseUrl)) {
1936
- throw RequestError.invalidParams({ baseUrl: params.baseUrl }, "baseUrl must be a non-empty absolute http(s) URL.");
1937
- }
1938
- const config = {
1939
- apiType: params.apiType,
1940
- baseUrl: params.baseUrl,
1941
- headers: params.headers ?? {},
1942
- };
1943
- // Vertex requires project + region, which the standard payload cannot
1944
- // carry, so they arrive via `_meta.claudeCode.vertex`.
1945
- if (params.apiType === "vertex") {
1946
- const vertex = params._meta?.claudeCode?.vertex;
1947
- if (!vertex ||
1948
- typeof vertex.projectId !== "string" ||
1949
- vertex.projectId.trim() === "" ||
1950
- typeof vertex.region !== "string" ||
1951
- vertex.region.trim() === "") {
1952
- throw RequestError.invalidParams(undefined, "vertex apiType requires non-empty `_meta.claudeCode.vertex.projectId` and `_meta.claudeCode.vertex.region`.");
1953
- }
1954
- config.vertex = { projectId: vertex.projectId, region: vertex.region };
1955
- }
1956
- this.logger.log(`[providers/set] apiType=${config.apiType} baseUrl=${config.baseUrl} sessions=${Object.keys(this.sessions).length}`);
1412
+ const config = providerConfigFromSetRequest(params);
1413
+ this.logger.log(`[providers/set] apiType=${config.apiType} baseUrl=${loggableBaseUrl(config.baseUrl)} sessions=${Object.keys(this.sessions).length}`);
1957
1414
  await this.enqueueProviderUpdate(config);
1958
1415
  return {};
1959
1416
  }
@@ -1969,70 +1426,9 @@ export class ClaudeAcpAgent {
1969
1426
  // Unknown provider: idempotent success.
1970
1427
  return {};
1971
1428
  }
1972
- /**
1973
- * The model ids the gateway in `config` lists, read before `providers/set`
1974
- * returns so the sessions it recreates already offer only those, and for
1975
- * `bedrock` the region prefix picked from them. Setting the same gateway
1976
- * again reuses the previous listing. `vertex` gateways are not listed.
1977
- * Throws a {@link GatewayListingError} when the listing fails.
1978
- */
1979
- async listProviderModels(config) {
1980
- // Reuse needs the very same headers, so a rotated token lists again, and a
1981
- // failed listing then fails that `providers/set`. Deliberate: AIR keeps its
1982
- // proxy key for the IDE's lifetime and does not rotate it.
1983
- const current = this.providerConfig;
1984
- if (current?.listedModels &&
1985
- current.apiType === config.apiType &&
1986
- current.baseUrl === config.baseUrl &&
1987
- sameHeaders(current.headers, config.headers)) {
1988
- return {
1989
- listedModels: current.listedModels,
1990
- bedrockRegionPrefix: current.bedrockRegionPrefix,
1991
- };
1992
- }
1993
- if (config.apiType === "anthropic") {
1994
- return { listedModels: await listGatewayModels(config.baseUrl, config.headers, this.logger) };
1995
- }
1996
- if (config.apiType === "bedrock") {
1997
- const modelIds = await listBedrockModels(config.baseUrl, config.headers, this.logger);
1998
- if (!modelIds)
1999
- return {};
2000
- const region = selectBedrockRegion(modelIds);
2001
- if (region.modelIds.length < modelIds.length) {
2002
- this.logger.log(`[providers/set] Bedrock models span several region prefixes; using ${region.regionPrefix} and dropping ${modelIds.length - region.modelIds.length} id(s) of other prefixes`);
2003
- }
2004
- return { listedModels: region.modelIds, bedrockRegionPrefix: region.regionPrefix };
2005
- }
2006
- return {};
2007
- }
2008
1429
  resolveProviderConfig() {
2009
1430
  return this.providerConfig ?? gatewayRequestToProviderConfig(this.gatewayAuthRequest);
2010
1431
  }
2011
- defaultProviderConfig() {
2012
- const gatewayConfig = gatewayRequestToProviderConfig(this.gatewayAuthRequest);
2013
- if (gatewayConfig) {
2014
- return gatewayConfig;
2015
- }
2016
- if (process.env.CLAUDE_CODE_USE_BEDROCK) {
2017
- return {
2018
- apiType: "bedrock",
2019
- baseUrl: process.env.ANTHROPIC_BEDROCK_BASE_URL ?? "https://bedrock-runtime.amazonaws.com",
2020
- headers: {},
2021
- };
2022
- }
2023
- if (process.env.CLAUDE_CODE_USE_VERTEX) {
2024
- return {
2025
- apiType: "vertex",
2026
- baseUrl: process.env.ANTHROPIC_VERTEX_BASE_URL ?? DEFAULT_VERTEX_BASE_URL,
2027
- headers: {},
2028
- };
2029
- }
2030
- return {
2031
- apiType: "anthropic",
2032
- baseUrl: process.env.ANTHROPIC_BASE_URL ?? DEFAULT_ANTHROPIC_BASE_URL,
2033
- headers: {},
2034
- };
2035
- }
2036
1432
  async logout(_params) {
2037
1433
  // Clear in-memory gateway credentials supplied via `authenticate` and any
2038
1434
  // provider routing set via `providers/set`. Neither touches the on-disk
@@ -2045,25 +1441,16 @@ export class ClaudeAcpAgent {
2045
1441
  this.providerConfig = undefined;
2046
1442
  // Any probe already running read the pre-logout world; the bump makes its
2047
1443
  // answer unpublishable so it cannot resurrect the identity being cleared.
2048
- this.authEpoch += 1;
1444
+ this.authStatus.changed();
2049
1445
  // Learned context windows are per-account state too: 1M-context
2050
1446
  // entitlement is gated per org/tier, and an OAuth re-login is invisible to
2051
1447
  // the env-derived provider cache key, so windows learned under the old
2052
1448
  // login must not seed sessions under the next. Worst case of clearing is
2053
1449
  // re-learning on each model's next turn.
2054
- contextWindowCache.clear();
2055
- // For the Claude/Console login methods the credentials live in the native
2056
- // CLI's store (keychain or config dir), which only the binary can clear.
2057
- // `claude auth logout` is non-interactive and idempotent.
1450
+ clearContextWindowCache();
1451
+ // The Claude and Console logins live in the CLI's store.
2058
1452
  try {
2059
- const cliPath = await claudeCliPath();
2060
- await execFileAsync(cliPath, ["auth", "logout"]);
2061
- }
2062
- catch (error) {
2063
- const stderr = typeof error === "object" && error && "stderr" in error
2064
- ? String(error.stderr).trim()
2065
- : undefined;
2066
- throw RequestError.internalError({ stderr: stderr || undefined }, `claude auth logout failed: ${error instanceof Error ? error.message : String(error)}`);
1453
+ await cliLogout();
2067
1454
  }
2068
1455
  finally {
2069
1456
  // The cleared provider or gateway routing is baked into the env of every
@@ -2081,8 +1468,8 @@ export class ClaudeAcpAgent {
2081
1468
  // credentials were cleared, so it never joins a probe that is already in
2082
1469
  // flight. If it can't be read, the logout still happened — drop the
2083
1470
  // now-stale identity instead of reporting it further.
2084
- if (!(await this.probeCliAuthStatus({ fresh: true }))) {
2085
- this.setAuthStatus(notLoggedInAuthStatus());
1471
+ if (!(await this.authStatus.probe({ fresh: true }))) {
1472
+ this.authStatus.set(notLoggedInAuthStatus());
2086
1473
  }
2087
1474
  }
2088
1475
  /** The structured replacement for a prompt that is exactly `/usage` or a
@@ -2132,8 +1519,7 @@ export class ClaudeAcpAgent {
2132
1519
  *
2133
1520
  * A content block that the agent does not advertise, such as `audio`, fails
2134
1521
  * the request with invalid params (-32602) before anything is queued:
2135
- * `promptToClaude` would drop it. v2 prompts reach `startTurn` through
2136
- * `v1PromptRequest`, which rejects these blocks itself.
1522
+ * `promptToClaude` would drop it.
2137
1523
  */
2138
1524
  async prompt(params, origin = "client") {
2139
1525
  for (const block of params.prompt) {
@@ -2175,8 +1561,8 @@ export class ClaudeAcpAgent {
2175
1561
  // that finds the new credential must not be the one the refusal skipped.
2176
1562
  // The guard itself consumes the result only at the next turn boundary (see
2177
1563
  // `markSessionsWhoseAccountKindChanged`).
2178
- this.useAuthStatusSettings(session.settingsManager, session.effortSettingsOverride, session.creationParams?._meta?.claudeCode?.options?.env);
2179
- void this.probeCliAuthStatus();
1564
+ this.authStatus.useSettings(session.settingsManager, session.effortSettingsOverride, session.creationParams?._meta?.claudeCode?.options?.env);
1565
+ void this.authStatus.probe();
2180
1566
  const signOutRespawn = this.respawnSignedOutSession(params.sessionId, session);
2181
1567
  if (signOutRespawn) {
2182
1568
  await signOutRespawn;
@@ -2194,13 +1580,15 @@ export class ClaudeAcpAgent {
2194
1580
  if (session.queryClosed) {
2195
1581
  throw RequestError.internalError(undefined, SESSION_ENDED_MESSAGE);
2196
1582
  }
2197
- const remoteControlCommand = parseRemoteControlCommand(params.prompt);
2198
- if (remoteControlCommand &&
2199
- supportsRemoteControl(session.query) &&
2200
- !claudeCodeOffersCommand(await session.query.supportedCommands(), session.terminalSlashCommands, REMOTE_CONTROL_COMMAND_NAME)) {
1583
+ // Only a prompt that is the command awaits here: an await on every prompt
1584
+ // would let other work run between its checks and its turn's enqueue.
1585
+ const remoteControl = parseRemoteControlCommand(params.prompt)
1586
+ ? await adapterRemoteControlCommand(params.prompt, session.query, session.terminalSlashCommands)
1587
+ : null;
1588
+ if (remoteControl) {
2201
1589
  // The reply bypasses the turn queue, so it would land inside the output of
2202
- // a turn that is still running, and v2 would report no `running` state
2203
- // around it. Refuse instead of interleaving. `foregroundWork` also covers
1590
+ // a turn that is still running. Refuse instead of interleaving.
1591
+ // `foregroundWork` also covers
2204
1592
  // a cycle that Claude Code started on its own, such as its follow-up
2205
1593
  // after a background subagent finished, which is not in `turnQueue`.
2206
1594
  if (this.claudeIsWorking(params.sessionId, session)) {
@@ -2214,13 +1602,12 @@ export class ClaudeAcpAgent {
2214
1602
  // those to reach this client, and a command that answers without a turn
2215
1603
  // would otherwise leave the stream unread until the next prompt.
2216
1604
  this.ensureConsumer(session, params.sessionId);
2217
- // Answered by the adapter without a model turn; v2 clients treat an
2218
- // `ended` without a prior `inserted` as a refused prompt.
1605
+ // Answered by the adapter without a model turn.
2219
1606
  events.inserted(randomUUID());
2220
1607
  // The request goes over the network. Until it and its reply are done,
2221
1608
  // `remoteControlCommand` holds back the prompts that follow, which would
2222
1609
  // otherwise start a turn that the reply lands in.
2223
- const command = this.runRemoteControlCommand(params.sessionId, session.query, remoteControlCommand);
1610
+ const command = this.runRemoteControlCommand(params.sessionId, remoteControl);
2224
1611
  session.remoteControlCommand = command;
2225
1612
  try {
2226
1613
  await command;
@@ -2260,12 +1647,9 @@ export class ClaudeAcpAgent {
2260
1647
  // the usage limit) from leaving the stale prediction in the composer. A
2261
1648
  // session that holds no prediction needs no clear, and the prompt path
2262
1649
  // then keeps the ordering it has without this feature.
2263
- if (session.lastPublishedPromptSuggestion != null) {
2264
- await this.publishPromptSuggestion(params.sessionId, null);
2265
- }
2266
- else {
2267
- session.promptSuggestionExpected = false;
2268
- }
1650
+ const cleared = session.promptSuggestions?.clear();
1651
+ if (cleared)
1652
+ await this.publishPromptSuggestion(params.sessionId, cleared);
2269
1653
  }
2270
1654
  // A `/remote-control` command still in flight answers into the session's
2271
1655
  // output; wait for its reply before this prompt's turn can begin. Nothing
@@ -2274,8 +1658,8 @@ export class ClaudeAcpAgent {
2274
1658
  if (session.remoteControlCommand)
2275
1659
  await session.remoteControlCommand.catch(() => { });
2276
1660
  // A `session/close` during the awaits above tore the session down, and
2277
- // its consumer is gone, so the prompt would never be inserted. End it as
2278
- // the close ends a queued turn: `cancelled` on v1, -32800 on v2. A stream
1661
+ // its consumer is gone, so the prompt would never be inserted. End it
1662
+ // `cancelled`, as the close ends a queued turn. A stream
2279
1663
  // that ended meanwhile fails the prompt as the check above does.
2280
1664
  // A `session/cancel` that arrived after this prompt, during the awaits
2281
1665
  // above, ends it the same way.
@@ -2305,12 +1689,12 @@ export class ClaudeAcpAgent {
2305
1689
  completeTurn = resolve;
2306
1690
  }),
2307
1691
  resolve: (outcome) => {
2308
- this.endForeground(params.sessionId, turn, { outcome });
1692
+ this.endForeground(params.sessionId, turn);
2309
1693
  events.ended(outcome);
2310
1694
  completeTurn();
2311
1695
  },
2312
1696
  reject: (error) => {
2313
- this.endForeground(params.sessionId, turn, { error });
1697
+ this.endForeground(params.sessionId, turn);
2314
1698
  events.failed(error);
2315
1699
  completeTurn();
2316
1700
  },
@@ -2326,31 +1710,9 @@ export class ClaudeAcpAgent {
2326
1710
  // the goal it sets; the turn's events report the outcome.
2327
1711
  await this.publishGoalFromPrompt(params.sessionId, firstText, promptUuid).catch((error) => this.logger.error(`Session ${params.sessionId}: failed to publish the prompt's goal:`, error));
2328
1712
  }
2329
- /** Connects Remote Control (again, if it is already on) or disconnects it. */
2330
- async runRemoteControlCommand(sessionId, query, command) {
2331
- let text;
2332
- if (command.action === "disconnect") {
2333
- try {
2334
- await query.enableRemoteControl(false);
2335
- text = "Remote Control is off. Run /remote-control to reconnect.";
2336
- }
2337
- catch (error) {
2338
- this.logger.error(`Failed to disable Remote Control: ${error}`);
2339
- text = `Could not stop Remote Control: ${error instanceof Error ? error.message : error}`;
2340
- }
2341
- }
2342
- else {
2343
- try {
2344
- const result = await query.enableRemoteControl(true, command.name);
2345
- text = result.session_url
2346
- ? `Remote Control is active. Continue this session from claude.ai/code or the Claude mobile app:\n\n${result.session_url}\n\nRun /remote-control off to disconnect.`
2347
- : "Remote Control is active, but Claude Code did not return a session URL.";
2348
- }
2349
- catch (error) {
2350
- this.logger.error(`Failed to enable Remote Control: ${error}`);
2351
- text = `Could not start Remote Control: ${error instanceof Error ? error.message : error}`;
2352
- }
2353
- }
1713
+ /** Runs the command, and sends its reply (see `runRemoteControlCommand`). */
1714
+ async runRemoteControlCommand(sessionId, { query, command }) {
1715
+ const text = await runRemoteControlCommand(query, command, (message) => this.logger.error(message));
2354
1716
  await this.client.sessionUpdate({
2355
1717
  sessionId,
2356
1718
  update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } },
@@ -2459,24 +1821,9 @@ export class ClaudeAcpAgent {
2459
1821
  if (!clientServers.has(server.name) || session.reportedMcpServers?.has(server.name)) {
2460
1822
  continue;
2461
1823
  }
2462
- let notice;
2463
- if (server.status === "failed") {
2464
- notice = {
2465
- severity: "warning",
2466
- title: `MCP server "${server.name}" failed to start`,
2467
- description: "Its tools are unavailable in this session. Run /mcp for the error.",
2468
- };
2469
- }
2470
- else if (server.status === "needs-auth" && !oauthAvailable) {
2471
- notice = {
2472
- severity: "info",
2473
- title: `MCP server "${server.name}" needs authentication`,
2474
- description: "Its tools are unavailable until the server is authenticated.",
2475
- };
2476
- }
2477
- else {
1824
+ const notice = mcpServerStartupNotice(server, oauthAvailable);
1825
+ if (!notice)
2478
1826
  continue;
2479
- }
2480
1827
  (session.reportedMcpServers ??= new Set()).add(server.name);
2481
1828
  await sendUpdate({
2482
1829
  sessionId,
@@ -2556,7 +1903,7 @@ export class ClaudeAcpAgent {
2556
1903
  logger: this.logger,
2557
1904
  // The guard reads the account anyway; reuse that read to keep the
2558
1905
  // reported identity current, refusal or not.
2559
- onAccount: (account) => this.publishSessionAccountIdentity(account, session.settingsManager.getApiKeyHelper(session.effortSettingsOverride)),
1906
+ onAccount: (account) => this.authStatus.publishSessionAccount(account, session.settingsManager.getApiKeyHelper(session.effortSettingsOverride)),
2560
1907
  });
2561
1908
  }
2562
1909
  async goal(params) {
@@ -2589,31 +1936,15 @@ export class ClaudeAcpAgent {
2589
1936
  });
2590
1937
  }
2591
1938
  /**
2592
- * Publishes the follow-up prompt the CLI predicted for the next turn, or
2593
- * `null` to clear the one the client holds. Only AIR renders it, so only AIR
2594
- * gets the key; see `docs/air-extensions.md`.
1939
+ * Sends the `_meta` of a session's {@link PromptSuggestions}: the follow-up
1940
+ * prompt the CLI predicted for the next turn, or the clear of the one the
1941
+ * client holds. Only AIR renders it, so only an AIR session has the state;
1942
+ * see `docs/air-extensions.md`.
2595
1943
  */
2596
- async publishPromptSuggestion(sessionId, text) {
2597
- const session = this.sessions[sessionId];
2598
- if (!session)
2599
- return;
2600
- // A clear ends the window the turn's result opened: whatever prediction is
2601
- // still in flight answers a turn the user has already moved past.
2602
- if (text === null)
2603
- session.promptSuggestionExpected = false;
2604
- // A session that never published one holds nothing, so a clear before the
2605
- // first prediction is already true on the client and goes nowhere.
2606
- if ((session.lastPublishedPromptSuggestion ?? null) === text)
2607
- return;
2608
- if (!this.toolCallCapabilities.air.client)
2609
- return;
2610
- session.lastPublishedPromptSuggestion = text;
1944
+ async publishPromptSuggestion(sessionId, meta) {
2611
1945
  await this.client.sessionUpdate({
2612
1946
  sessionId,
2613
- update: {
2614
- sessionUpdate: "session_info_update",
2615
- _meta: promptSuggestionsMeta(text),
2616
- },
1947
+ update: { sessionUpdate: "session_info_update", _meta: meta },
2617
1948
  });
2618
1949
  }
2619
1950
  async publishTaskPlan(sessionId, taskState) {
@@ -3152,9 +2483,6 @@ export class ClaudeAcpAgent {
3152
2483
  // handler), activation is the first sign that Claude Code took the
3153
2484
  // prompt in: its echo, or for an echo-less command, its result.
3154
2485
  reportInserted(turn);
3155
- // A request can already be open: Claude Code asks for a queued prompt
3156
- // before the consumer reaches its echo.
3157
- this.syncAwaitingUser(params.sessionId, session);
3158
2486
  };
3159
2487
  /** Report that Claude Code took the turn's prompt in, once. A turn can be
3160
2488
  * settled by now: an echo hand-off awaits settling the previous turn, and
@@ -3419,16 +2747,13 @@ export class ClaudeAcpAgent {
3419
2747
  if (isSubagent && session.activeTurn && !session.activeTurn.settled) {
3420
2748
  (session.activeTurn.spawnedTaskIds ??= new Set()).add(taskId);
3421
2749
  }
3422
- this.syncAwaitingUser(params.sessionId, session);
3423
2750
  };
3424
- /** Ends the terminal and the tool call of a task that ran in the
3425
- * background, once the task ends (see `Session.background`). */
3426
- const endBackgroundTask = (taskId, end) => session.background.taskEnded(taskId, end, sendUpdate);
3427
- /** Settles a task. Its request may still be open, and an agent without a
3428
- * record no longer blocks the foreground work, so that is checked again. */
2751
+ /** Ends the terminal of a command that ran in the background, once its
2752
+ * task ends (see `Session.background`). */
2753
+ const endBackgroundTask = (taskId) => session.background.taskEnded(taskId, sendUpdate);
2754
+ /** Settles a task. */
3429
2755
  const settleLiveTask = (taskId) => {
3430
2756
  settleLiveBackgroundTask(session, taskId);
3431
- this.syncAwaitingUser(params.sessionId, session);
3432
2757
  };
3433
2758
  /** Registers a settled subagent again when the SDK resumes it without a
3434
2759
  * new `task_started`. The active turn is the one that resumed it, so it
@@ -3499,7 +2824,7 @@ export class ClaudeAcpAgent {
3499
2824
  turnAwaitingSubagents(session.activeTurn)) {
3500
2825
  session.activeTurn.deferredSettle = outcome;
3501
2826
  // The hold delays v1's answer; the turn's work ended at its result.
3502
- this.endForeground(params.sessionId, session.activeTurn, { outcome });
2827
+ this.endForeground(params.sessionId, session.activeTurn);
3503
2828
  }
3504
2829
  else {
3505
2830
  await settleActive(outcome);
@@ -3624,6 +2949,7 @@ export class ClaudeAcpAgent {
3624
2949
  parentToolUseId: message.parent_tool_use_id,
3625
2950
  cwd: session.cwd,
3626
2951
  taskState: session.taskState,
2952
+ subagentChecklists: session.subagentChecklists,
3627
2953
  emittedToolCalls: session.emittedToolCalls,
3628
2954
  toolCallFields: toolCallFieldsOf(session),
3629
2955
  messageId: messageIdForGrouping(message),
@@ -3735,8 +3061,7 @@ export class ClaudeAcpAgent {
3735
3061
  }
3736
3062
  }
3737
3063
  // The client is told that the work a cancel stopped ended (the prompt
3738
- // response on v1, `idle` on v2) only after every tool call that work
3739
- // opened has ended.
3064
+ // response) only after every tool call that work opened has ended.
3740
3065
  if (result.stopReason === "cancelled" && session.cancelled) {
3741
3066
  await closeCancelledToolCalls(turn);
3742
3067
  // `cancelTurns` can settle the turn while the reports are in flight.
@@ -3850,7 +3175,7 @@ export class ClaudeAcpAgent {
3850
3175
  * error is the cancel's, not the work's. */
3851
3176
  const failAllTurns = (error) => {
3852
3177
  disarmForceCancel(session);
3853
- this.endAutonomousCycle(params.sessionId, session.cancelled ? { outcome: { stopReason: "cancelled" } } : { error });
3178
+ this.endAutonomousCycle(params.sessionId);
3854
3179
  const active = session.activeTurn;
3855
3180
  const turns = active
3856
3181
  ? [active, ...(session.turnQueue ?? []).filter((t) => t !== active)]
@@ -3902,12 +3227,6 @@ export class ClaudeAcpAgent {
3902
3227
  const pause = messageLoopYielder.maybeYield();
3903
3228
  if (pause)
3904
3229
  await pause;
3905
- // The last message may have changed the background work, and its
3906
- // updates are sent, so the list follows them. A task that needs a
3907
- // tool call of its own gets it first, so the list can name it.
3908
- for (const call of session.background.adoptTasks(session))
3909
- await sendUpdate(call);
3910
- this.backgroundWork.sync(params.sessionId, session, this.foregroundState(params.sessionId));
3911
3230
  pendingNext ??= session.query
3912
3231
  .next()
3913
3232
  .then((result) => ({ kind: "message", result }));
@@ -4029,9 +3348,7 @@ export class ClaudeAcpAgent {
4029
3348
  // it), but the stored one is the authoritative source.
4030
3349
  const inFlight = session.activeTurn;
4031
3350
  await finishLifecycle(session.cancelled ? "cancelled" : "failed", session.cancelled ? "stopped" : "failed", "at end of stream");
4032
- this.endAutonomousCycle(params.sessionId, session.cancelled
4033
- ? { outcome: { stopReason: "cancelled" } }
4034
- : { error: RequestError.internalError(undefined, SESSION_ENDED_MESSAGE) });
3351
+ this.endAutonomousCycle(params.sessionId);
4035
3352
  await settleActive(session.cancelled
4036
3353
  ? cancelledOutcome(session, inFlight)
4037
3354
  : (inFlight?.deferredSettle ?? turnOutcome(session, stopReason)));
@@ -4393,9 +3710,7 @@ export class ClaudeAcpAgent {
4393
3710
  await asyncTasks.autonomousTurnEnded("completed");
4394
3711
  }
4395
3712
  await closeCycleToolCalls();
4396
- this.endAutonomousCycle(params.sessionId, {
4397
- outcome: { stopReason: session.cancelled ? "cancelled" : "end_turn" },
4398
- });
3713
+ this.endAutonomousCycle(params.sessionId);
4399
3714
  }
4400
3715
  // A non-cancelled turn normally settled at its terminal
4401
3716
  // `result` already (issue #773), and that result recorded an
@@ -4479,7 +3794,7 @@ export class ClaudeAcpAgent {
4479
3794
  const steered = session.activeTurn;
4480
3795
  steered.deferredSettle = outcome;
4481
3796
  // A hold delays v1's answer; the turn's work ends here.
4482
- this.endForeground(params.sessionId, steered, { outcome });
3797
+ this.endForeground(params.sessionId, steered);
4483
3798
  leaveSteerLane(steered);
4484
3799
  await settleDeferredIfDrained();
4485
3800
  }
@@ -4647,19 +3962,13 @@ export class ClaudeAcpAgent {
4647
3962
  noticedToolUses.add(message.tool_use_id);
4648
3963
  }
4649
3964
  }
4650
- const severity = message.level === "warning" ? "warning" : "info";
4651
3965
  const transcriptContent = collapseHookSpeaker(message.content);
4652
3966
  const transcriptText = message.level === "info"
4653
3967
  ? transcriptContent
4654
3968
  : `**${sentenceCase(message.level)}:** ${transcriptContent}`;
4655
3969
  await sendUpdate({
4656
3970
  sessionId: params.sessionId,
4657
- update: noticeOrTranscriptUpdate({
4658
- severity,
4659
- ...splitNoticeText(message.content, severity === "warning"
4660
- ? "Claude reported a warning"
4661
- : "Claude reported a notice"),
4662
- }, supportsNotices, transcriptText, { claudeCode: { kind: "informational", level: message.level } }),
3971
+ update: noticeOrTranscriptUpdate(informationalNotice(message), supportsNotices, transcriptText, { claudeCode: { kind: "informational", level: message.level } }),
4663
3972
  });
4664
3973
  const noticedTurn = session.activeTurn ?? session.turnQueue?.[0];
4665
3974
  if (supportsNotices && noticedTurn) {
@@ -4672,19 +3981,11 @@ export class ClaudeAcpAgent {
4672
3981
  case "hook_response":
4673
3982
  case "files_persisted":
4674
3983
  break;
4675
- case "task_progress": {
3984
+ case "task_progress":
4676
3985
  if (isLateTaskRun(session, message.task_id, message.run_id)) {
4677
3986
  this.logger.log(`Ignoring task_progress for task ${message.task_id} from earlier run ${message.run_id}`);
4678
3987
  break;
4679
3988
  }
4680
- // The SDK does not type `workflow_progress`; see workflow-progress.ts.
4681
- const workflow = workflowSnapshot(message.workflow_progress);
4682
- const progress = session.background.taskProgress(message.task_id, {
4683
- ...taskProgressFields(message),
4684
- ...(workflow ? { workflow } : {}),
4685
- });
4686
- if (progress)
4687
- await sendUpdate(progress);
4688
3989
  await asyncTasks.taskProgress({
4689
3990
  task_id: message.task_id,
4690
3991
  description: message.description,
@@ -4694,7 +3995,6 @@ export class ClaudeAcpAgent {
4694
3995
  tool_use_id: message.tool_use_id,
4695
3996
  });
4696
3997
  break;
4697
- }
4698
3998
  case "task_started":
4699
3999
  if (isLateTaskRun(session, message.task_id, message.run_id)) {
4700
4000
  this.logger.log(`Ignoring task_started for task ${message.task_id} from earlier run ${message.run_id}`);
@@ -4767,7 +4067,7 @@ export class ClaudeAcpAgent {
4767
4067
  streamedBlocksByParent.delete(message.tool_use_id);
4768
4068
  droppedStreams.delete(message.tool_use_id);
4769
4069
  }
4770
- await endBackgroundTask(message.task_id, message.status);
4070
+ await endBackgroundTask(message.task_id);
4771
4071
  if (message.status === "stopped") {
4772
4072
  await closeStoppedSubagentToolCalls(message.tool_use_id);
4773
4073
  }
@@ -4780,12 +4080,11 @@ export class ClaudeAcpAgent {
4780
4080
  }
4781
4081
  await asyncTasks.taskUpdated(message.task_id, message.patch);
4782
4082
  // A task moved to the background no longer blocks the tool
4783
- // call that spawned it, nor its requests the foreground work.
4083
+ // call that spawned it.
4784
4084
  if (message.patch.is_backgrounded !== undefined) {
4785
4085
  const task = session.liveBackgroundTasks.get(message.task_id);
4786
4086
  if (task)
4787
4087
  task.backgrounded = message.patch.is_backgrounded;
4788
- this.syncAwaitingUser(params.sessionId, session);
4789
4088
  }
4790
4089
  // terminal-status task_updated patch and a (deduplicated)
4791
4090
  // task_notification when a task settles, but only the patch is
@@ -4801,22 +4100,14 @@ export class ClaudeAcpAgent {
4801
4100
  streamedBlocksByParent.delete(parentToolUseId);
4802
4101
  droppedStreams.delete(parentToolUseId);
4803
4102
  }
4804
- await endBackgroundTask(message.task_id, message.patch.status === "killed" ? "stopped" : message.patch.status);
4103
+ await endBackgroundTask(message.task_id);
4805
4104
  if (message.patch.status === "killed") {
4806
4105
  await closeStoppedSubagentToolCalls(parentToolUseId);
4807
4106
  }
4808
4107
  settleLiveTask(message.task_id);
4809
4108
  }
4810
- else if (message.patch.status === "paused") {
4811
- const pause = session.background.taskPaused(message.task_id, true);
4812
- if (pause)
4813
- await sendUpdate(pause);
4814
- }
4815
4109
  else if (message.patch.status === "running" ||
4816
4110
  message.patch.status === "pending") {
4817
- const resume = session.background.taskPaused(message.task_id, false);
4818
- if (resume)
4819
- await sendUpdate(resume);
4820
4111
  // The SDK can resume a finished subagent under the same
4821
4112
  // agent id without a new task_started.
4822
4113
  resumeLiveTask(message.task_id);
@@ -4880,41 +4171,13 @@ export class ClaudeAcpAgent {
4880
4171
  break;
4881
4172
  }
4882
4173
  case "model_refusal_fallback": {
4883
- // The SDK retried a refused turn on the fallback model and made
4884
- // the swap persistent for the session. Without a notice the
4885
- // user just sees regenerated output; without the state sync the
4886
- // client's model picker (and the model-dependent options
4887
- // rebuilt from it) keeps advertising a model the session is no
4888
- // longer running.
4889
- //
4890
- // Current CLIs only emit direction "retry" (persistent swap).
4891
- // "revert"/"sticky" are retained in the SDK enum for older
4892
- // CLIs, where "revert" marked a turn-only fallback — for that
4893
- // direction the session stays on the original model, so skip
4894
- // the persistent-swap claim and the state sync.
4895
- //
4896
- // `scope` (CLI 2.1.232+) marks WHERE the fallback happened:
4897
- // "local" means a subagent / side-question / background fork
4898
- // response fell back and the session model is unchanged, so
4899
- // syncing the picker would advertise a model the session
4900
- // isn't running. Absent scope means an older CLI, where every
4901
- // retry was a session-level swap — treat as "session".
4902
- const local = message.scope === "local";
4903
- const persistent = message.direction !== "revert" && !local;
4904
- const category = message.api_refusal_category
4905
- ? ` (${message.api_refusal_category})`
4906
- : "";
4907
- const outcome = persistent
4908
- ? `The session will continue on ${message.fallback_model}.`
4909
- : local
4910
- ? `Only that response came from ${message.fallback_model}; the session stays on ${message.original_model}.`
4911
- : `The session stays on ${message.original_model}.`;
4912
- const fallbackSummary = `${message.original_model} declined this request${category}; ` +
4913
- `retried with ${message.fallback_model}. ${outcome}`;
4914
- const explanation = message.api_refusal_explanation || undefined;
4915
- const fallbackNotice = explanation
4916
- ? `${fallbackSummary}\n\n${explanation}`
4917
- : fallbackSummary;
4174
+ // The SDK retried a refused turn on the fallback model. Without
4175
+ // a notice the user just sees regenerated output; without the
4176
+ // state sync the client's model picker (and the model-dependent
4177
+ // options rebuilt from it) keeps advertising a model the
4178
+ // session is no longer running (see `modelRefusalFallback`).
4179
+ const fallback = modelRefusalFallback(message);
4180
+ const { summary: fallbackSummary, explanation } = fallback;
4918
4181
  // A silent model swap is a session-level advisory, not something the model said.
4919
4182
  // Clients on the ACP notice contract get it as a `notice`; clients that negotiated
4920
4183
  // AIR typed records get it as one of those; the rest keep the bold-label transcript
@@ -4923,26 +4186,21 @@ export class ClaudeAcpAgent {
4923
4186
  const useDetails = explanation !== undefined &&
4924
4187
  fallbackSummary.length + 2 + explanation.length > MAX_NOTICE_TITLE_LENGTH;
4925
4188
  await publishSessionFailure("advisory", {
4926
- title: useDetails ? fallbackSummary : fallbackNotice,
4189
+ title: useDetails
4190
+ ? fallbackSummary
4191
+ : explanation
4192
+ ? `${fallbackSummary}\n\n${explanation}`
4193
+ : fallbackSummary,
4927
4194
  ...(useDetails ? { details: explanation } : {}),
4928
4195
  });
4929
4196
  }
4930
4197
  else {
4931
- // A title must stand alone: the one-line summary when it is
4932
- // short enough, else a generic title with everything in the
4933
- // description (the same cap the AIR lane applies above).
4934
- const notice = fallbackSummary.length > MAX_NOTICE_TITLE_LENGTH
4935
- ? { title: "Model fallback", description: fallbackNotice }
4936
- : {
4937
- title: fallbackSummary,
4938
- ...(explanation ? { description: explanation } : {}),
4939
- };
4940
4198
  await sendUpdate({
4941
4199
  sessionId: params.sessionId,
4942
- update: noticeOrTranscriptUpdate({ severity: "warning", ...notice }, supportsNotices, `**Model fallback:** ${fallbackNotice}`),
4200
+ update: noticeOrTranscriptUpdate(fallback.notice, supportsNotices, fallback.transcript),
4943
4201
  });
4944
4202
  }
4945
- if (persistent) {
4203
+ if (fallback.persistent) {
4946
4204
  await this.syncModelAfterExternalSwitch(params.sessionId, session, message.fallback_model);
4947
4205
  }
4948
4206
  break;
@@ -4972,7 +4230,6 @@ export class ClaudeAcpAgent {
4972
4230
  break;
4973
4231
  case "background_tasks_changed": {
4974
4232
  await asyncTasks.backgroundTasksChanged(message.tasks);
4975
- await session.background.levelChanged(message.tasks, sendUpdate);
4976
4233
  // A level signal: the full live background-task set on every
4977
4234
  // membership change, with REPLACE semantics. Used only to
4978
4235
  // reconcile `liveBackgroundTasks` — dropping (or, for
@@ -5027,7 +4284,7 @@ export class ClaudeAcpAgent {
5027
4284
  session.modelRequestSinceResult = false;
5028
4285
  // The CLI predicts the next prompt right after this result, so a
5029
4286
  // `prompt_suggestion` from here on belongs to the turn just ended.
5030
- session.promptSuggestionExpected = true;
4287
+ session.promptSuggestions?.resultArrived();
5031
4288
  // The result ends the model turn. A background task that still
5032
4289
  // waits for its tool call id gets its spawn now, without the id.
5033
4290
  await asyncTasks.releaseHeld();
@@ -5204,23 +4461,9 @@ export class ClaudeAcpAgent {
5204
4461
  matchingModelUsage.usage.contextWindow > 0) {
5205
4462
  session.contextWindowSize = matchingModelUsage.usage.contextWindow;
5206
4463
  session.contextWindowAuthoritative = true;
5207
- // Authoritative: fold it into the cross-session cache keyed on
5208
- // (this session's provider, the resolved model id —
5209
- // matchingModelUsage.key, e.g. "claude-sonnet-5[1m]") so a later
5210
- // session/new or switch on the same provider that resolves to
5211
- // this model seeds the correct window synchronously, with no
5212
- // getContextUsage IPC.
5213
- cacheContextWindow(contextWindowCacheKey(session.providerCacheKey, matchingModelUsage.key), matchingModelUsage.usage.contextWindow);
5214
- // Also cache under the assistant message's own (bare) spelling.
5215
- // Seed-time reads fall back to a picker value / verbatim live id
5216
- // when a row carries no resolvedModel (the synthesized
5217
- // out-of-allowlist resume row sets it undefined on purpose), and
5218
- // those spellings match `.model` from the assistant message, not
5219
- // the decorated modelUsage key — without this entry such rows
5220
- // could never hit the cache.
5221
- if (lastAssistantModel && lastAssistantModel !== matchingModelUsage.key) {
5222
- cacheContextWindow(contextWindowCacheKey(session.providerCacheKey, lastAssistantModel), matchingModelUsage.usage.contextWindow);
5223
- }
4464
+ // Authoritative: fold it into the cross-session cache (see
4465
+ // `cacheResultContextWindow`).
4466
+ cacheResultContextWindow(session.providerCacheKey, matchingModelUsage.key, lastAssistantModel, matchingModelUsage.usage.contextWindow);
5224
4467
  }
5225
4468
  session.lastTotalCostUsd = message.total_cost_usd;
5226
4469
  this.sessionIndex.onOwnSessionChanged(params.sessionId);
@@ -5261,7 +4504,7 @@ export class ClaudeAcpAgent {
5261
4504
  pendingExitPlanModeInterruption?.toolUseId;
5262
4505
  if (!continuesPlan && !(isAutonomousResult && message.num_turns === 0)) {
5263
4506
  await closeCycleToolCalls();
5264
- this.endAutonomousCycle(params.sessionId, autonomousCycleEnd(message, resultModelUsage, session.cancelled || exitPlanInterruption || isAbortedResult(message)));
4507
+ this.endAutonomousCycle(params.sessionId);
5265
4508
  }
5266
4509
  if (session.cancelled) {
5267
4510
  session.pendingExitPlanModeInterruption = undefined;
@@ -5509,18 +4752,21 @@ export class ClaudeAcpAgent {
5509
4752
  failure.recoveryPolicy === "auth_status" ||
5510
4753
  (failure.severity === "warning" && failure.turnId === activeTurnId));
5511
4754
  }
4755
+ // The stop reason or the error, by the rules both cores share.
4756
+ const ended = resultEnd(message);
5512
4757
  switch (message.subtype) {
5513
4758
  case "success": {
5514
- if (message.is_error && isLoginRequiredText(message.result)) {
5515
- await failActiveWithSessionFailure("auth_required", RequestError.authRequired(), message.result);
5516
- break;
5517
- }
5518
- if (message.stop_reason === "max_tokens") {
5519
- stopReason = "max_tokens";
4759
+ if ("error" in ended) {
4760
+ if (ended.loginRequired) {
4761
+ await failActiveWithSessionFailure("auth_required", RequestError.authRequired(), ended.error);
4762
+ break;
4763
+ }
4764
+ await failActiveWithSessionFailure(providerFailureCategory(lastAssistantError, lastAssistantWasUsageLimit), internalErrorForClient(errorKindData(lastAssistantError), ended.error), lastAssistantFailureTitle ?? ended.error);
5520
4765
  break;
5521
4766
  }
5522
- if (message.is_error) {
5523
- await failActiveWithSessionFailure(providerFailureCategory(lastAssistantError, lastAssistantWasUsageLimit), internalErrorForClient(errorKindData(lastAssistantError), message.result), lastAssistantFailureTitle ?? message.result);
4767
+ // `end_turn` keeps the stop reason as it was.
4768
+ if (ended.stopReason !== "end_turn") {
4769
+ stopReason = ended.stopReason;
5524
4770
  break;
5525
4771
  }
5526
4772
  // The result text is forwarded in two cases. Local-only
@@ -5560,38 +4806,21 @@ export class ClaudeAcpAgent {
5560
4806
  }
5561
4807
  break;
5562
4808
  }
5563
- case "error_during_execution": {
5564
- if (message.stop_reason === "max_tokens") {
5565
- stopReason = "max_tokens";
5566
- break;
5567
- }
5568
- if (message.is_error) {
5569
- await failActiveWithSessionFailure(providerFailureCategory(lastAssistantError, lastAssistantWasUsageLimit), internalErrorForClient(errorKindData(lastAssistantError), message.errors.join(", ") || message.subtype), lastAssistantFailureTitle ?? (message.errors.join(", ") || message.subtype));
4809
+ case "error_during_execution":
4810
+ if ("error" in ended) {
4811
+ await failActiveWithSessionFailure(providerFailureCategory(lastAssistantError, lastAssistantWasUsageLimit), internalErrorForClient(errorKindData(lastAssistantError), ended.error), lastAssistantFailureTitle ?? ended.error);
5570
4812
  break;
5571
4813
  }
5572
- stopReason = "end_turn";
4814
+ stopReason = ended.stopReason;
5573
4815
  break;
5574
- }
5575
4816
  case "error_max_budget_usd":
5576
- if (message.is_error) {
5577
- await failActiveWithSessionFailure("budget_exhausted", internalErrorForClient(errorKindData(lastAssistantError), message.errors.join(", ") || message.subtype), message.errors.join(", ") || message.subtype);
5578
- break;
5579
- }
5580
- stopReason = "max_turn_requests";
5581
- break;
5582
4817
  case "error_max_turns":
5583
- if (message.is_error) {
5584
- await failActiveWithSessionFailure("context_exhausted", internalErrorForClient(errorKindData(lastAssistantError), message.errors.join(", ") || message.subtype), message.errors.join(", ") || message.subtype);
5585
- break;
5586
- }
5587
- stopReason = "max_turn_requests";
5588
- break;
5589
4818
  case "error_max_structured_output_retries":
5590
- if (message.is_error) {
5591
- await failActiveWithSessionFailure("provider_error", internalErrorForClient(errorKindData(lastAssistantError), message.errors.join(", ") || message.subtype), message.errors.join(", ") || message.subtype);
4819
+ if ("error" in ended) {
4820
+ await failActiveWithSessionFailure(LIMIT_FAILURE_CATEGORY[message.subtype], internalErrorForClient(errorKindData(lastAssistantError), ended.error), ended.error);
5592
4821
  break;
5593
4822
  }
5594
- stopReason = "max_turn_requests";
4823
+ stopReason = ended.stopReason;
5595
4824
  break;
5596
4825
  default:
5597
4826
  unreachable(message, this.logger);
@@ -5788,32 +5017,7 @@ export class ClaudeAcpAgent {
5788
5017
  // already reached the client as chunks and forward only the
5789
5018
  // remainder. Each stream (top level or one subagent) keeps its own
5790
5019
  // record, so a subagent cannot attribute content to another stream.
5791
- // Contiguous deltas of the same block (same index and type) extend
5792
- // the current entry; anything else opens a new one.
5793
- if (message.event.type === "content_block_delta") {
5794
- const delta = message.event.delta;
5795
- const chunk = delta.type === "text_delta"
5796
- ? { type: "text", text: delta.text }
5797
- : delta.type === "thinking_delta"
5798
- ? { type: "thinking", text: delta.thinking }
5799
- : undefined;
5800
- // Skip empty deltas (some gateways emit empty thinking chunks —
5801
- // #793): appending "" is a no-op, but pushing a "" entry would
5802
- // create a block the consolidated handler's `text.length > 0`
5803
- // guard can never consume, stalling the diff cursor and
5804
- // re-emitting the next block as a duplicate.
5805
- if (chunk?.text) {
5806
- const index = message.event.index;
5807
- const streamedBlocks = streamedBlocksOf(message.parent_tool_use_id);
5808
- const last = streamedBlocks[streamedBlocks.length - 1];
5809
- if (last && last.index === index && last.type === chunk.type) {
5810
- last.text += chunk.text;
5811
- }
5812
- else {
5813
- streamedBlocks.push({ index, type: chunk.type, text: chunk.text });
5814
- }
5815
- }
5816
- }
5020
+ recordStreamedDelta(streamedBlocksOf(message.parent_tool_use_id), message.event);
5817
5021
  // The stream sees a tool_use first, so the tool's PostToolUse hook
5818
5022
  // is registered here, and publishes through this client: a
5819
5023
  // subagent's hook update must reach the child session too.
@@ -5822,6 +5026,7 @@ export class ClaudeAcpAgent {
5822
5026
  toolCallCapabilities: this.toolCallCapabilities,
5823
5027
  cwd: session.cwd,
5824
5028
  taskState: session.taskState,
5029
+ subagentChecklists: session.subagentChecklists,
5825
5030
  emittedToolCalls: session.emittedToolCalls,
5826
5031
  toolCallFields: toolCallFieldsOf(session),
5827
5032
  messageId: currentStreamMessageId,
@@ -6084,6 +5289,7 @@ export class ClaudeAcpAgent {
6084
5289
  parentToolUseId: message.parent_tool_use_id,
6085
5290
  cwd: session.cwd,
6086
5291
  taskState: session.taskState,
5292
+ subagentChecklists: session.subagentChecklists,
6087
5293
  messageId: messageIdForGrouping(message),
6088
5294
  })) {
6089
5295
  await sendUpdate(notification);
@@ -6163,8 +5369,6 @@ export class ClaudeAcpAgent {
6163
5369
  const acceptedPlanToolUseId = observeExitPlanToolResults(message, content, session);
6164
5370
  let backgroundedToolCalls = new Set();
6165
5371
  let runningTerminal;
6166
- let runningTerminalTask;
6167
- let runningToolCalls = new Set();
6168
5372
  if (message.type === "user") {
6169
5373
  rememberResolvedToolNames(session, content);
6170
5374
  recordSubagentFileEdits(session.activeTurn, message.parent_tool_use_id, content, session.toolUseCache);
@@ -6194,13 +5398,8 @@ export class ClaudeAcpAgent {
6194
5398
  ...(message.parent_tool_use_id
6195
5399
  ? { parentToolUseId: message.parent_tool_use_id }
6196
5400
  : {}),
6197
- ...(typeof backgroundBashTask.outputFilePath === "string"
6198
- ? { outputFilePath: backgroundBashTask.outputFilePath }
6199
- : {}),
6200
5401
  });
6201
- runningTerminalTask = backgroundBashTask.taskId;
6202
5402
  }
6203
- runningToolCalls = session.background.toolResults(session, content, toolUseResult, session.toolUseCache, message.parent_tool_use_id);
6204
5403
  await asyncTasks.toolResults(content);
6205
5404
  backgroundedToolCalls = backgroundedBashToolCallIds(content, session.toolUseCache, asyncTasks, backgroundBashTask);
6206
5405
  const resumedAgentId = resumedNativeSubagentId(toolUseResult);
@@ -6222,6 +5421,7 @@ export class ClaudeAcpAgent {
6222
5421
  parentToolUseId: message.parent_tool_use_id,
6223
5422
  cwd: session.cwd,
6224
5423
  taskState: session.taskState,
5424
+ subagentChecklists: session.subagentChecklists,
6225
5425
  emittedToolCalls: session.emittedToolCalls,
6226
5426
  toolCallFields: toolCallFieldsOf(session),
6227
5427
  messageId: messageIdForGrouping(message),
@@ -6236,17 +5436,7 @@ export class ClaudeAcpAgent {
6236
5436
  // filtered out of `content` above; blocks that do pass through
6237
5437
  // (e.g. a subagent image) carry the stamped parentToolUseId
6238
5438
  // meta and are excluded there.
6239
- await sendUpdate(withRunningToolCall(withRunningTerminal(backgroundedBashToolCall(acceptedPlanToolResult(notification, acceptedPlanToolUseId), backgroundedToolCalls, asyncTasks.enabled), runningTerminal), runningToolCalls));
6240
- }
6241
- for (const progress of session.background.toolCallProgress(runningToolCalls)) {
6242
- await sendUpdate(progress);
6243
- }
6244
- // After the result's own updates: the command's output replaces
6245
- // the placeholder that they gave its terminal.
6246
- if (runningTerminalTask) {
6247
- session.background.followOutput(runningTerminalTask, (notification) => sendUpdate(notification).catch((error) => {
6248
- this.logger.error(`Session ${params.sessionId}: failed to send background command output:`, error);
6249
- }));
5439
+ await sendUpdate(withRunningTerminal(backgroundedBashToolCall(acceptedPlanToolResult(notification, acceptedPlanToolUseId), backgroundedToolCalls, asyncTasks.enabled), runningTerminal));
6250
5440
  }
6251
5441
  break;
6252
5442
  }
@@ -6332,7 +5522,7 @@ export class ClaudeAcpAgent {
6332
5522
  clearHookCallbacks(params.sessionId);
6333
5523
  session.taskState.clear();
6334
5524
  forgetPublishedTaskPlan(session.taskState);
6335
- for (const update of resetPlanUpdates(this.clientCapabilities?.plan != null, this.toolCallCapabilities.air.client)) {
5525
+ for (const update of resetPlanUpdates(this.clientCapabilities?.plan != null, this.toolCallCapabilities.air.client, session.subagentChecklists)) {
6336
5526
  await this.client.sessionUpdate({ sessionId: params.sessionId, update });
6337
5527
  }
6338
5528
  // A reset mounts a fresh transcript (`new_conversation_id`), so our
@@ -6341,7 +5531,9 @@ export class ClaudeAcpAgent {
6341
5531
  session.titles.reset();
6342
5532
  // The follow-up prompt was predicted from the transcript the reset
6343
5533
  // dropped, so it no longer follows from anything.
6344
- await this.publishPromptSuggestion(params.sessionId, null);
5534
+ const cleared = session.promptSuggestions?.clear();
5535
+ if (cleared)
5536
+ await this.publishPromptSuggestion(params.sessionId, cleared);
6345
5537
  // The recorded request and TTL describe the dropped conversation.
6346
5538
  session.idleCompaction?.reset();
6347
5539
  break;
@@ -6352,10 +5544,9 @@ export class ClaudeAcpAgent {
6352
5544
  // The CLI predicts the next prompt after the turn's `result`. AIR
6353
5545
  // shows it as gray text in an empty composer; Tab fills the
6354
5546
  // composer, and nothing is sent until the user sends it.
6355
- if (!session.promptSuggestionExpected)
6356
- break;
6357
- session.promptSuggestionExpected = false;
6358
- await this.publishPromptSuggestion(params.sessionId, promptSuggestionText(message.suggestion));
5547
+ const suggested = session.promptSuggestions?.suggested(message.suggestion);
5548
+ if (suggested)
5549
+ await this.publishPromptSuggestion(params.sessionId, suggested);
6359
5550
  break;
6360
5551
  }
6361
5552
  case "auth_status":
@@ -6551,10 +5742,6 @@ export class ClaudeAcpAgent {
6551
5742
  // cancelled by it).
6552
5743
  const cancelledThrough = this.promptsReceived;
6553
5744
  this.cancelledThrough.set(params.sessionId, cancelledThrough);
6554
- // The interrupt below makes Claude Code withdraw the requests that are open
6555
- // now (see `withPendingUserInput`).
6556
- for (const input of session.openUserInputs ?? [])
6557
- input.cancelled = true;
6558
5745
  // Before anything awaits, so a model request that the consumer reads in
6559
5746
  // the meantime is already judged against these prompts.
6560
5747
  session.cancelledPrompts ??= new Set();
@@ -6911,13 +6098,6 @@ export class ClaudeAcpAgent {
6911
6098
  continue;
6912
6099
  // Its list row now shows what the registry and the transcript tell.
6913
6100
  this.sessionIndex.onOwnSessionChanged(sessionId);
6914
- // Its background tasks end with the query's process.
6915
- for (const exit of session.background.queryClosed()) {
6916
- this.client.sessionUpdate(exit).catch((error) => {
6917
- this.logger.error(`Session ${sessionId}: failed to end a background terminal:`, error);
6918
- });
6919
- }
6920
- this.backgroundWork.sync(sessionId, session, this.foregroundState(sessionId));
6921
6101
  }
6922
6102
  session.consumer = undefined;
6923
6103
  session.contextCompaction = undefined;
@@ -6928,10 +6108,8 @@ export class ClaudeAcpAgent {
6928
6108
  }
6929
6109
  /** Cleanly tear down a session: cancel in-flight work, release stream
6930
6110
  * resources, and remove it from the session map. Returns once the turns it
6931
- * cancels have ended, so their end (a v1 `session/prompt` response, a v2
6932
- * `idle` state) goes out before the caller answers: ACP v2's
6933
- * `session/close` cancels "as if `session/cancel` had been called", then
6934
- * frees the session. A wedged consumer holds it at most
6111
+ * cancels have ended, so their `session/prompt` responses go out before
6112
+ * the caller answers. A wedged consumer holds it at most
6935
6113
  * {@link TEARDOWN_TURN_END_TIMEOUT_MS}. */
6936
6114
  async teardownSession(sessionId) {
6937
6115
  const session = this.sessions[sessionId];
@@ -6949,7 +6127,7 @@ export class ClaudeAcpAgent {
6949
6127
  }
6950
6128
  // The turns end before this returns; so does a model cycle that Claude
6951
6129
  // Code started on its own, which no turn waits for.
6952
- this.endAutonomousCycle(sessionId, { outcome: { stopReason: "cancelled" } });
6130
+ this.endAutonomousCycle(sessionId);
6953
6131
  // cancel() arms the force-cancel floor and interrupts gracefully, but a
6954
6132
  // wedged consumer only wakes when `cancelController` aborts — closeQueryStream
6955
6133
  // below doesn't touch it. Since we're tearing the session down anyway, wake
@@ -6972,15 +6150,13 @@ export class ClaudeAcpAgent {
6972
6150
  session.asyncTaskRuntime?.clear();
6973
6151
  this.replayedChildModels.delete(sessionId);
6974
6152
  this.cancelledThrough.delete(sessionId);
6975
- this.backgroundWork.forget(sessionId);
6976
6153
  delete this.sessions[sessionId];
6977
6154
  this.sessionIndex.onTeardown(sessionId);
6978
6155
  const ended = await raceTimeoutAndAbort(turnsEnded, TEARDOWN_TURN_END_TIMEOUT_MS, new AbortController().signal);
6979
6156
  if (ended.type === "timeout") {
6980
6157
  this.logger.error(`Session ${sessionId}: its cancelled turns did not end within ${TEARDOWN_TURN_END_TIMEOUT_MS}ms of the teardown`);
6981
- // Settle them here, so the close still answers after each turn's end: a
6982
- // v1 prompt gets `cancelled`, a v2 prompt not yet inserted gets -32800,
6983
- // and an inserted one ends in an `idle` with `cancelled`.
6158
+ // Settle them here, so the close still answers after each turn's end:
6159
+ // its prompt gets `cancelled`.
6984
6160
  for (const turn of turns) {
6985
6161
  if (turn.settled)
6986
6162
  continue;
@@ -6992,10 +6168,9 @@ export class ClaudeAcpAgent {
6992
6168
  session.activeTurn = null;
6993
6169
  // Foreground work that no turn owns, such as a cycle that Claude Code
6994
6170
  // started after the endAutonomousCycle call above.
6995
- const work = this.foregroundWork.get(sessionId);
6996
- if (work) {
6997
- this.endForeground(sessionId, work.owner, { outcome: { stopReason: "cancelled" } });
6998
- }
6171
+ const owner = this.foregroundWork.get(sessionId);
6172
+ if (owner)
6173
+ this.endForeground(sessionId, owner);
6999
6174
  }
7000
6175
  }
7001
6176
  /** Tear down all active sessions. Called when the ACP connection closes. */
@@ -7011,63 +6186,12 @@ export class ClaudeAcpAgent {
7011
6186
  await this.teardownSession(params.sessionId);
7012
6187
  return {};
7013
6188
  }
7014
- /** Stops a command running in the background (v2 `terminal/cancel`, see
7015
- * {@link cancelBackgroundWork}). */
7016
- cancelBackgroundTerminal(params) {
7017
- return cancelBackgroundWork(Object.values(this.sessions), params.sessionId, {
7018
- terminalId: params.terminalId,
7019
- });
6189
+ /** Per client: see {@link sessionIndex.SessionIndexConnection.deleteSession}. */
6190
+ async deleteSession(params) {
6191
+ return this.sessionIndex.deleteSession(params);
7020
6192
  }
7021
- /** Stops the task of a tool call running in the background (v2
7022
- * `tool_call/cancel`, see {@link cancelBackgroundWork}). */
7023
- cancelBackgroundToolCall(params) {
7024
- return cancelBackgroundWork(Object.values(this.sessions), params.sessionId, {
7025
- toolCallId: params.toolCallId,
7026
- });
7027
- }
7028
- /** Sends the current state of each tool call in `toolCallIds` that the root
7029
- * session `sessionId` runs in the background: the call as its tool use
7030
- * shows it, with its status now. v2 requires it for each tool call that a
7031
- * `session/resume` snapshot lists. A failure is logged, as for
7032
- * {@link publishLiveSubagents}. */
7033
- async publishBackgroundToolCalls(sessionId, toolCallIds) {
7034
- const session = this.sessions[sessionId];
7035
- if (!session)
7036
- return;
7037
- const renderer = new AcpToolCallRenderer(this.toolCallCapabilities);
7038
- try {
7039
- for (const update of session.background.toolCallStates(toolCallIds, renderer, session.cwd)) {
7040
- await this.client.sessionUpdate(update);
7041
- }
7042
- }
7043
- catch (error) {
7044
- this.logger.error(`Session ${sessionId}: failed to send background tool calls:`, error);
7045
- }
7046
- }
7047
- /** Sends the current `subagent_update` of each live subagent session in
7048
- * `children`, of the session `sessionId` (see
7049
- * {@link NativeSubagentRuntime.currentUpdate}). v2 requires it for each
7050
- * child that a `session/resume` snapshot lists. A failure is logged, as
7051
- * for {@link publishCurrentSubagentStates}. */
7052
- async publishLiveSubagents(sessionId, children) {
7053
- const runtime = this.sessions[sessionId]?.nativeSubagentRuntime;
7054
- try {
7055
- for (const child of children) {
7056
- const update = runtime?.currentUpdate(child);
7057
- if (update)
7058
- await this.client.sessionUpdate(asSdkSessionNotification(update));
7059
- }
7060
- }
7061
- catch (error) {
7062
- this.logger.error(`Session ${sessionId}: failed to send current subagent states:`, error);
7063
- }
7064
- }
7065
- /** Per client: see {@link sessionIndex.SessionIndexConnection.deleteSession}. */
7066
- async deleteSession(params) {
7067
- return this.sessionIndex.deleteSession(params);
7068
- }
7069
- setSessionMode(params) {
7070
- return this.serializeConfigurationChange(params.sessionId, () => this.sessionModes.setSessionMode(params));
6193
+ setSessionMode(params) {
6194
+ return this.serializeConfigurationChange(params.sessionId, () => this.sessionModes.setSessionMode(params));
7071
6195
  }
7072
6196
  setSessionConfigOption(params) {
7073
6197
  return this.serializeConfigurationChange(params.sessionId, () => this.selectSessionConfigOption(params));
@@ -7088,60 +6212,17 @@ export class ClaudeAcpAgent {
7088
6212
  if (!option) {
7089
6213
  throw RequestError.invalidParams(undefined, `Unknown config option: ${params.configId}`);
7090
6214
  }
7091
- // The value must match the type the option was advertised with: a
7092
- // `type: "boolean"` option takes `true`/`false`, not "on"/"off", and a
7093
- // `type: "select"` option takes a string.
7094
- const expectedType = option.type === "boolean" ? "boolean" : "string";
7095
- if (typeof params.value !== expectedType) {
7096
- throw RequestError.invalidParams({ configId: params.configId, value: params.value }, `Config option ${params.configId} takes a ${expectedType} value, but received: ${JSON.stringify(params.value)}`);
7097
- }
7098
- // Fast mode and ultracode carry a boolean value (for Clients that opted
7099
- // into boolean config options) or the "on"/"off" select fallback, so they
7100
- // bypass the
7101
- // string-only validation the select-style options below rely on.
7102
- if (params.configId === FAST_MODE_CONFIG_ID) {
7103
- await this.applyFastMode(session, resolveFastModeEnabled(params));
7104
- return { configOptions: session.configOptions };
7105
- }
7106
- if (params.configId === ULTRACODE_CONFIG_ID) {
7107
- await this.applyUltracode(session, resolveUltracodeEnabled(params));
7108
- return { configOptions: session.configOptions };
7109
- }
7110
- if (typeof params.value !== "string") {
7111
- throw RequestError.invalidParams(undefined, `Invalid value for config option ${params.configId}: ${params.value}`);
7112
- }
7113
- const allValues = "options" in option && Array.isArray(option.options)
7114
- ? option.options.flatMap((o) => ("options" in o ? o.options : [o]))
7115
- : [];
7116
- let validValue = allValues.find((o) => o.value === params.value);
7117
- // For model options, fall back to resolveModelPreference when the exact
7118
- // value doesn't match. This lets callers use human-friendly aliases like
7119
- // "opus" or "sonnet" instead of full model IDs like "claude-opus-4-6".
7120
- // Resolve against session.modelInfos first: those entries carry
7121
- // `resolvedModel`, so a full model id (in either hint spelling) lands on
7122
- // the right row via the exact tier instead of a fuzzier one picking a
7123
- // same-family sibling from a different context lane. The options-derived
7124
- // list (which never carries `resolvedModel`) remains as a fallback for
7125
- // resolutions that don't map back onto a selectable option (e.g. a fuzzy
7126
- // hit on an out-of-picker verbatim entry).
7127
- if (!validValue && params.configId === MODEL_CONFIG_ID) {
7128
- const toOptionValue = (resolved) => resolved ? allValues.find((o) => o.value === resolved.value) : undefined;
7129
- validValue = toOptionValue(resolveModelPreference(session.modelInfos, params.value));
7130
- if (!validValue) {
7131
- const optionInfos = allValues.map((o) => ({
7132
- value: o.value,
7133
- displayName: o.name,
7134
- description: o.description ?? "",
7135
- }));
7136
- validValue = toOptionValue(resolveModelPreference(optionInfos, params.value));
6215
+ const selected = configOptionValue(option, params, session.modelInfos);
6216
+ if ("enabled" in selected) {
6217
+ if (params.configId === FAST_MODE_CONFIG_ID) {
6218
+ await this.applyFastMode(session, selected.enabled);
7137
6219
  }
6220
+ else {
6221
+ await this.applyUltracode(session, selected.enabled);
6222
+ }
6223
+ return { configOptions: session.configOptions };
7138
6224
  }
7139
- if (!validValue) {
7140
- throw RequestError.invalidParams(undefined, `Invalid value for config option ${params.configId}: ${params.value}`);
7141
- }
7142
- // Use the canonical option value so downstream code always receives the
7143
- // model ID rather than the caller-supplied alias.
7144
- const resolvedValue = validValue.value;
6225
+ const resolvedValue = selected.value;
7145
6226
  let effectiveValue = resolvedValue;
7146
6227
  if (params.configId === MODE_CONFIG_ID) {
7147
6228
  effectiveValue = await this.sessionModes.selectMode(params.sessionId, resolvedValue);
@@ -7480,28 +6561,11 @@ export class ClaudeAcpAgent {
7480
6561
  // Claude persists the retained summary as a user message framed with
7481
6562
  // continuation instructions for the model. Clients on the compaction
7482
6563
  // contract get it materialized as the completed compaction entity at
7483
- // this transcript position (the boundary's own system record comes back
7484
- // from getSessionMessages without its metadata, so the summary message
7485
- // is the one durable marker); other clients keep the transcript text.
7486
- // The entity is keyed by the summary message's uuid, which differs from
7487
- // the live id (the `compacting` status uuid) — replay is terminal-first
7488
- // by the RFD, and no client merges a replay into a live entity store.
7489
- // A subagent's own compaction summary is not the root session's. A summary
7490
- // whose framing is unrecognized is still this compaction, without summary
7491
- // text: isCompactSummary says what it is, and the framing is Claude Code's
7492
- // to change.
6564
+ // this transcript position; other clients keep the transcript text.
6565
+ // A subagent's own compaction summary is not the root session's.
7493
6566
  if (replayCompactionUpdates &&
7494
- isCompactSummaryMessage(message) &&
7495
6567
  parentToolUseId === null &&
7496
- typeof message.uuid === "string" &&
7497
- message.uuid.length > 0) {
7498
- const replayCompaction = new ContextCompactionLifecycle((notification) => this.client.sessionUpdate(notification), {
7499
- sessionId,
7500
- presentation: "compaction_update",
7501
- airClient: this.toolCallCapabilities.air.client,
7502
- });
7503
- replayCompaction.recordSummary(assistantMessageText(message.message));
7504
- await replayCompaction.finish(message.uuid, "completed");
6568
+ (await replayCompactSummary(message, (notification) => this.client.sessionUpdate(notification), { sessionId, airClient: this.toolCallCapabilities.air.client }))) {
7505
6569
  return;
7506
6570
  }
7507
6571
  for (const notification of toAcpNotifications(
@@ -7515,6 +6579,7 @@ export class ClaudeAcpAgent {
7515
6579
  toolCallCapabilities: this.toolCallCapabilities,
7516
6580
  cwd: replayState()?.cwd,
7517
6581
  taskState: replayState()?.taskState,
6582
+ subagentChecklists: replayState()?.subagentChecklists,
7518
6583
  messageId: replayMessageId,
7519
6584
  parentToolUseId,
7520
6585
  })) {
@@ -7638,119 +6703,41 @@ export class ClaudeAcpAgent {
7638
6703
  * conversation) as awaiting user input for exactly the lifetime of its
7639
6704
  * promise (see `Session.openUserInputs`). Steering consults the open
7640
6705
  * requests synchronously, so a message arriving while any permission or
7641
- * elicitation card is open uses non-interrupting SDK delivery.
7642
- *
7643
- * `signal` aborts when Claude Code withdraws the request, which is not an
7644
- * answer. Example: the user cancels while a permission request is open.
7645
- * Claude Code's interrupt withdraws it as it stops the work, and the work
7646
- * ends `idle cancelled` right after. The end of the request then reports
7647
- * no `running`: the client would see `requires_action`, `running`, `idle
7648
- * cancelled`. A withdrawal without a cancel means that something else
7649
- * answered the request in the user's place, such as a `PermissionRequest`
7650
- * hook, and the work goes on, so the end reports `running`. */
7651
- async withPendingUserInput(sessionId, signal, request, agentID) {
6706
+ * elicitation card is open uses non-interrupting SDK delivery. */
6707
+ async withPendingUserInput(sessionId, request, agentID) {
7652
6708
  const session = this.sessions[sessionId];
7653
6709
  if (!session)
7654
6710
  return request();
7655
6711
  const input = agentID !== undefined ? { agentID } : {};
7656
6712
  (session.openUserInputs ??= new Set()).add(input);
7657
- this.syncAwaitingUser(sessionId, session);
7658
6713
  try {
7659
6714
  return await request();
7660
6715
  }
7661
6716
  finally {
7662
6717
  session.openUserInputs.delete(input);
7663
- const withdrawnByCancel = signal.aborted && input.cancelled === true;
7664
- this.syncAwaitingUser(sessionId, session, withdrawnByCancel);
7665
6718
  }
7666
6719
  }
7667
- /** Report whether the session's foreground work awaits the user: exactly
7668
- * while a permission request or question that blocks it is open (see
7669
- * {@link blocksForeground}). A request does not say which prompt it is for,
7670
- * and Claude Code can ask for a queued prompt before the consumer activates
7671
- * it, so a request is not tied to the work that was running when it
7672
- * opened. Called when a request opens or closes, when a turn activates, and
7673
- * when a task registers or moves to the background.
7674
- *
7675
- * When the last request ends, the work reports `running` again, unless a
7676
- * cancel withdrew that request (`withdrawnByCancel`, see
7677
- * {@link withPendingUserInput}): the work is being stopped, and reports its
7678
- * end next. */
7679
- syncAwaitingUser(sessionId, session, withdrawnByCancel = false) {
7680
- const work = this.foregroundWork.get(sessionId);
7681
- if (!work)
7682
- return;
7683
- const waiting = [...(session.openUserInputs ?? [])].some((input) => blocksForeground(session, input.agentID));
7684
- if (waiting === work.awaitingUser)
7685
- return;
7686
- work.awaitingUser = waiting;
7687
- if (waiting)
7688
- work.events.awaitingUser();
7689
- else if (!withdrawnByCancel)
7690
- work.events.running();
7691
- }
7692
6720
  /** Whether Claude is working in the session `sessionId`: an unsettled turn in
7693
6721
  * its queue, or foreground work that no turn owns, such as a cycle that
7694
6722
  * Claude Code started on its own. */
7695
6723
  claudeIsWorking(sessionId, session) {
7696
6724
  return (this.foregroundWork.has(sessionId) || (session.turnQueue ?? []).some((turn) => !turn.settled));
7697
6725
  }
7698
- /** Sends the current title and `updatedAt` of the session `sessionId` as a
7699
- * `session_info_update` (see {@link SessionTitles.publishCurrent}). A
7700
- * failure is logged: the info is optional, so it does not fail a resume. */
7701
- async publishCurrentSessionInfo(sessionId) {
7702
- const session = this.sessions[sessionId];
7703
- if (!session)
7704
- return;
7705
- try {
7706
- await session.titles.publishCurrent(session);
7707
- }
7708
- catch (error) {
7709
- this.logger.error(`Session ${sessionId}: failed to send the session info:`, error);
7710
- }
7711
- }
7712
- /** The foreground state of the session `sessionId` now, as v2's
7713
- * `state_update` names it: `idle` while no work runs, `requires_action`
7714
- * while the work awaits the user (see {@link syncAwaitingUser}), and
7715
- * `running` otherwise. */
7716
- foregroundState(sessionId) {
7717
- const work = this.foregroundWork.get(sessionId);
7718
- if (!work)
7719
- return "idle";
7720
- return work.awaitingUser ? "requires_action" : "running";
7721
- }
7722
6726
  /** Make `owner` the foreground work of the session `sessionId` (see
7723
- * {@link ForegroundEvents}): it reports `running`, then waits at once if a
7724
- * request is open. If work already runs, it goes on under `owner` and
7725
- * reports nothing new: a turn takes over a cycle that Claude Code started on
7726
- * its own, and only the owner's end ends the work. */
6727
+ * {@link ForegroundOwner}). If work already runs, it goes on under
6728
+ * `owner`: a turn takes over a cycle that Claude Code started on its own,
6729
+ * and only the owner's end ends the work. */
7727
6730
  startForeground(sessionId, owner) {
7728
- const current = this.foregroundWork.get(sessionId);
7729
- if (current) {
7730
- current.owner = owner;
7731
- return;
7732
- }
7733
- const events = this.foregroundEvents?.(sessionId) ?? UNREPORTED_FOREGROUND;
7734
- this.foregroundWork.set(sessionId, { owner, events, awaitingUser: false });
7735
- events.running();
7736
- const session = this.sessions[sessionId];
7737
- if (session)
7738
- this.syncAwaitingUser(sessionId, session);
7739
- }
7740
- /** End the foreground work of the session `sessionId` with `outcome`, or as
7741
- * failed with `error`, if `owner` is that work. */
7742
- endForeground(sessionId, owner, end) {
7743
- const work = this.foregroundWork.get(sessionId);
7744
- if (work?.owner !== owner)
7745
- return;
7746
- this.foregroundWork.delete(sessionId);
7747
- if ("outcome" in end)
7748
- work.events.ended(end.outcome);
7749
- else
7750
- work.events.failed(end.error);
6731
+ this.foregroundWork.set(sessionId, owner);
6732
+ }
6733
+ /** End the foreground work of the session `sessionId`, if `owner` is that
6734
+ * work. */
6735
+ endForeground(sessionId, owner) {
6736
+ if (this.foregroundWork.get(sessionId) === owner)
6737
+ this.foregroundWork.delete(sessionId);
7751
6738
  }
7752
6739
  /** Start a model cycle that Claude Code started on its own as the foreground
7753
- * work (see {@link ForegroundEvents}) when `message` is its first output:
6740
+ * work (see {@link ForegroundOwner}) when `message` is its first output:
7754
6741
  * model output of the main conversation (not a subagent's) while no work
7755
6742
  * runs. That includes a turn that v1 holds for its background subagents,
7756
6743
  * whose work ended at its result, so its follow-up is a cycle. Output of
@@ -7771,16 +6758,13 @@ export class ClaudeAcpAgent {
7771
6758
  return;
7772
6759
  this.startForeground(sessionId, AUTONOMOUS_CYCLE);
7773
6760
  }
7774
- /** Whether the client has been told that the session's work ended: on v2 by
7775
- * an idle state, so no foreground work is open, including a cycle that
7776
- * Claude Code started on its own; on v1 by the response to the turn's
7777
- * prompt, so no turn is active. v1 reports nothing for a cycle, so its end
7778
- * is its result or idle: until then, Claude Code's results for the cycle's
7779
- * tool calls still reach the client after a cancel. */
6761
+ /** Whether the client has been told that the session's work ended: by the
6762
+ * response to the turn's prompt, so no turn is active. The client is told
6763
+ * nothing of a cycle, so its end is its result or idle: until then, Claude
6764
+ * Code's results for the cycle's tool calls still reach the client after a
6765
+ * cancel. */
7780
6766
  workEndReported(sessionId, session) {
7781
- return this.foregroundEvents
7782
- ? !this.foregroundWork.has(sessionId)
7783
- : !session.activeTurn && !this.runsAutonomousCycle(sessionId);
6767
+ return !session.activeTurn && !this.runsAutonomousCycle(sessionId);
7784
6768
  }
7785
6769
  /** Whether the consumer drops what it reaches now as output of the work a
7786
6770
  * cancel stopped: the client has been told that the work ended, and the
@@ -7839,13 +6823,13 @@ export class ClaudeAcpAgent {
7839
6823
  }
7840
6824
  /** End the session's model cycle that Claude Code started on its own, if one
7841
6825
  * runs. */
7842
- endAutonomousCycle(sessionId, end) {
7843
- this.endForeground(sessionId, AUTONOMOUS_CYCLE, end);
6826
+ endAutonomousCycle(sessionId) {
6827
+ this.endForeground(sessionId, AUTONOMOUS_CYCLE);
7844
6828
  }
7845
6829
  /** Whether a model cycle that Claude Code started on its own is the session's
7846
6830
  * foreground work. A turn that took a cycle over owns the work from then on. */
7847
6831
  runsAutonomousCycle(sessionId) {
7848
- return this.foregroundWork.get(sessionId)?.owner === AUTONOMOUS_CYCLE;
6832
+ return this.foregroundWork.get(sessionId) === AUTONOMOUS_CYCLE;
7849
6833
  }
7850
6834
  /** The ACP turn that owns a root request of the session now, if any. A
7851
6835
  * model cycle that Claude Code started on its own owns no turn. A turn that
@@ -7884,7 +6868,7 @@ export class ClaudeAcpAgent {
7884
6868
  // The request goes to a subagent's child session for a tool call of that
7885
6869
  // subagent, but it blocks the turn of the owner session.
7886
6870
  try {
7887
- return await this.withChildAwaitingUser(ownerSessionId, params.sessionId, signal, () => this.withPendingUserInput(ownerSessionId, signal, () => this.client.requestPermission(params, signal), agentID));
6871
+ return await this.withChildAwaitingUser(ownerSessionId, params.sessionId, signal, () => this.withPendingUserInput(ownerSessionId, () => this.client.requestPermission(params, signal), agentID));
7888
6872
  }
7889
6873
  catch (error) {
7890
6874
  if (signal.aborted) {
@@ -7905,9 +6889,9 @@ export class ClaudeAcpAgent {
7905
6889
  /** `signal`, also aborted when `teardownSession` aborts the
7906
6890
  * `abortController` of session `sessionId`. Claude Code aborts a callback's
7907
6891
  * own signal when its query closes, but not necessarily before
7908
- * `session/close` responds, and v2 requires every pending permission
7909
- * request and elicitation of the session to be cancelled with
7910
- * `$/cancel_request` before that response. */
6892
+ * `session/close` responds, and every pending permission request and
6893
+ * elicitation of the session is cancelled with `$/cancel_request` before
6894
+ * that response. */
7911
6895
  untilSessionClosed(sessionId, signal) {
7912
6896
  const sessionSignal = this.sessions[sessionId]?.abortController?.signal;
7913
6897
  return sessionSignal ? AbortSignal.any([signal, sessionSignal]) : signal;
@@ -8050,111 +7034,17 @@ export class ClaudeAcpAgent {
8050
7034
  await session.nativeSubagentRuntime
8051
7035
  ?.reportCwd(input.agent_id, input.cwd)
8052
7036
  .catch((error) => this.logger.error(`Session ${sessionId}: failed to report subagent cwd: ${error}`));
8053
- const options = [];
8054
- if (input.permission_mode) {
8055
- const mode = session.modes.availableModes.find((mode) => mode.id === input.permission_mode);
8056
- options.push(SessionModeManager.configOption({
8057
- currentModeId: input.permission_mode,
8058
- availableModes: [mode ?? { id: input.permission_mode, name: input.permission_mode }],
8059
- }));
8060
- }
8061
- const switchedModel = input.hook_event_name === "PostModelSwitch"
8062
- ? responseModelEntry(input.to_model, this.subagentModels(sessionId))
8063
- : undefined;
8064
- // The entry of the root session's `model` option, as for a child response.
8065
- if (switchedModel)
8066
- options.push(childModelOption(switchedModel));
8067
- if (input.effort?.level) {
8068
- options.push({
8069
- id: EFFORT_CONFIG_ID,
8070
- name: "Effort",
8071
- description: "Current reasoning effort",
8072
- category: "thought_level",
8073
- type: "select",
8074
- currentValue: input.effort.level,
8075
- options: [{ value: input.effort.level, name: effortLevelName(input.effort.level) }],
8076
- });
8077
- }
8078
- if (input.agent_type) {
8079
- const agent = session.agents.find((agent) => agent.name === input.agent_type);
8080
- options.push({
8081
- id: AGENT_CONFIG_ID,
8082
- name: "Agent",
8083
- description: "Subagent type",
8084
- type: "select",
8085
- currentValue: input.agent_type,
8086
- options: [
8087
- {
8088
- value: input.agent_type,
8089
- name: input.agent_type,
8090
- ...(agent?.description ? { description: agent.description } : {}),
8091
- },
8092
- ],
8093
- });
8094
- }
7037
+ const options = subagentHookOptions(input, {
7038
+ availableModes: session.modes.availableModes,
7039
+ models: this.subagentModels(sessionId),
7040
+ agents: session.agents,
7041
+ });
8095
7042
  await session.nativeSubagentRuntime
8096
7043
  ?.reportConfiguration(input.agent_id, options)
8097
7044
  .catch((error) => this.logger.error(`Session ${sessionId}: failed to report subagent configuration: ${error}`));
8098
7045
  return { continue: true };
8099
7046
  };
8100
7047
  }
8101
- /**
8102
- * Captures pre-execution patches for v2 Edit and Write tool calls.
8103
- *
8104
- * A v2 diff cannot hold the input's snippet, so the patch needs the file as
8105
- * it was before the tool runs. Claude Code waits for the hook before running
8106
- * the tool. If its streamed tool use has not arrived, the patch waits for
8107
- * the tool call's first publication. The hook makes no permission decision,
8108
- * and a failure only leaves the preview out.
8109
- */
8110
- fileChangePreviewHook(sessionId) {
8111
- return async (input, toolUseID, { signal }) => {
8112
- if (input.hook_event_name === "PreToolUse" && toolUseID) {
8113
- await this.previewFileChange(sessionId, input, toolUseID, signal).catch((error) => this.logger.error(`Session ${sessionId}: failed to preview ${toolUseID}: ${error}`));
8114
- }
8115
- return { continue: true };
8116
- };
8117
- }
8118
- async previewFileChange(sessionId, input, toolUseID, signal) {
8119
- const session = this.sessions[sessionId];
8120
- if (!session)
8121
- return;
8122
- // As in `canUseTool`: the work a cancel stopped shows nothing.
8123
- const stopped = this.isStoppedWorkToolUse(session, toolUseID, signal);
8124
- if (stopped instanceof Promise ? await stopped : stopped)
8125
- return;
8126
- const toolInput = (input.tool_input ?? {});
8127
- const content = await previewPatchContent(input.tool_name, toolInput, session.cwd, "v2");
8128
- if (!content)
8129
- return;
8130
- const fields = toolCallFieldsOf(session);
8131
- // Workflow tools can run hooks without streaming their use or result.
8132
- // Keep the patch until the stream or a permission request publishes the
8133
- // tool call, instead of creating a pending call with no completion path.
8134
- if (!session.emittedToolCalls.has(toolUseID)) {
8135
- fields.stagePreview(toolUseID, content);
8136
- return;
8137
- }
8138
- const { parentToolUseId, toolCallSessionId } = this.toolUseOwner(session, sessionId, input.agent_id);
8139
- const update = {
8140
- sessionUpdate: "tool_call_update",
8141
- toolCallId: toolUseID,
8142
- content,
8143
- };
8144
- if (parentToolUseId)
8145
- stampParentToolUseId(update, parentToolUseId);
8146
- if (!fields.apply(update))
8147
- return;
8148
- // The streamed input must not replace the patch, as for an approval patch.
8149
- fields.pinContent(toolUseID, content);
8150
- // The stream's router sends it to the session that holds the tool call.
8151
- if (session.nativeSubagentDeliver) {
8152
- await session.nativeSubagentDeliver({ sessionId, update });
8153
- }
8154
- else {
8155
- await this.client.sessionUpdate({ sessionId: toolCallSessionId, update });
8156
- }
8157
- }
8158
7048
  canUseTool(sessionId) {
8159
7049
  return async (toolName, toolInput, { signal, suggestions, toolUseID, agentID, matchedAskRule, blockedPath, decisionReason, title, displayName, description, defaultToNo, suppressAlwaysAllowRule, mcpServer, }) => {
8160
7050
  const session = this.sessions[sessionId];
@@ -8207,8 +7097,8 @@ export class ClaudeAcpAgent {
8207
7097
  const noPersistentRule = matchedAskRule !== undefined || suppressAlwaysAllowRule === true;
8208
7098
  const durableChangeSet = normalizeDurablePermissionChangeSet(suggestions, noPersistentRule);
8209
7099
  const capabilities = this.toolCallCapabilities;
8210
- const previewContent = capabilities.diffPatch || capabilities.v2
8211
- ? await previewPatchContent(toolName, toolInput, session.cwd, capabilities.v2 ? "v2" : "air")
7100
+ const previewContent = capabilities.diffPatch
7101
+ ? await previewPatchContent(toolName, toolInput, session.cwd, "air")
8212
7102
  : undefined;
8213
7103
  const presentation = buildClaudePermissionPresentation({
8214
7104
  toolName,
@@ -8224,24 +7114,16 @@ export class ClaudeAcpAgent {
8224
7114
  decisionReason,
8225
7115
  defaultToNo,
8226
7116
  });
8227
- // `mcpServer` (SDK 0.3.274+): which MCP server serves an `mcp__*` tool
8228
- // and where its definition came from. Forwarded verbatim so a client
8229
- // can key trust on `source` (`sdk` = a host-registered in-process
8230
- // server; anything else is configuration) instead of parsing the
8231
- // tool-name prefix. The name is the config key as authored — untrusted
8232
- // text, so it rides `_meta` rather than the title.
8233
7117
  // AIR already holds the tool name and the parent tool call. Every
8234
7118
  // other client gets them again, like upstream.
8235
- const airClient = capabilities.air.client;
8236
- if (mcpServer || (parentToolUseId && !airClient)) {
8237
- presentation.toolCall._meta = {
8238
- claudeCode: {
8239
- ...(airClient ? {} : { toolName }),
8240
- ...(parentToolUseId && !airClient ? { parentToolUseId } : {}),
8241
- ...(mcpServer ? { mcpServer: { name: mcpServer.name, source: mcpServer.source } } : {}),
8242
- },
8243
- };
8244
- }
7119
+ const toolCallMeta = permissionToolCallMeta({
7120
+ toolName,
7121
+ parentToolUseId,
7122
+ mcpServer,
7123
+ airClient: capabilities.air.client,
7124
+ });
7125
+ if (toolCallMeta)
7126
+ presentation.toolCall._meta = toolCallMeta;
8245
7127
  const permissionOptions = buildClaudePermissionOptions({
8246
7128
  toolName,
8247
7129
  displayName,
@@ -8273,13 +7155,9 @@ export class ClaudeAcpAgent {
8273
7155
  // cancel does not stop. Answer such a request with a denial so the
8274
7156
  // subagent reads "the user refused" and goes on. Throwing instead makes
8275
7157
  // Claude Code deny it as "Tool permission request failed".
8276
- // On ACP v2, `cancelled` also answers a prompt that the user dismissed
8277
- // or that the client declined by policy. Without a `session/cancel`
8278
- // (`session.cancelled` unset), that is the user refusing the tool, so it
8279
- // gets the same denial and the turn goes on.
8280
7158
  if (response.outcome?.outcome === "cancelled" &&
8281
7159
  this.sessions[sessionId] === session &&
8282
- (!blocksForeground(session, agentID) || (this.v2 && !session.cancelled))) {
7160
+ !blocksForeground(session, agentID)) {
8283
7161
  return {
8284
7162
  behavior: "deny",
8285
7163
  message: "User refused permission to run tool",
@@ -8337,118 +7215,50 @@ export class ClaudeAcpAgent {
8337
7215
  }
8338
7216
  /**
8339
7217
  * Handle elicitation requests that originate from MCP servers by forwarding
8340
- * them to the client over ACP. Only the user's own decline reaches the MCP
8341
- * server as `decline`. A request the user never saw, because the client did
8342
- * not advertise its mode, we can't represent it, or the client answered with
8343
- * an error, is a `cancel`.
7218
+ * them to the client over ACP (see {@link answerMcpElicitation}).
8344
7219
  */
8345
7220
  handleMcpElicitation(sessionId, support) {
8346
7221
  return async (request, { signal: callbackSignal }) => {
8347
7222
  const signal = this.untilSessionClosed(sessionId, callbackSignal);
8348
- const isUrl = request.mode === "url";
8349
- if ((isUrl && !support.url) || (!isUrl && !support.form)) {
8350
- return { action: "cancel" };
8351
- }
8352
- const createRequest = mcpElicitationToCreateRequest(request, sessionId);
8353
- if (!createRequest) {
8354
- return { action: "cancel" };
8355
- }
8356
- try {
8357
- const response = await this.withPendingUserInput(sessionId, signal, () => this.elicitFromClient(createRequest, signal));
8358
- if (signal.aborted) {
8359
- return { action: "cancel" };
8360
- }
8361
- return createElicitationResponseToElicitResult(response);
8362
- }
8363
- catch (error) {
8364
- // A cancellation we requested (signal aborted) settles as a cancel, not
8365
- // a hard decline — the elicitation was abandoned, not refused.
8366
- if (signal.aborted) {
8367
- return { action: "cancel" };
8368
- }
8369
- // The client answered with an error, e.g. -32602 for a form it cannot
8370
- // render, so the user never saw the request. MCP's `decline` means the
8371
- // user refused; `cancel` means they made no explicit choice.
8372
- this.logger.error(`Failed to forward MCP elicitation: ${error}`);
8373
- return { action: "cancel" };
8374
- }
7223
+ return answerMcpElicitation(request, {
7224
+ sessionId,
7225
+ support,
7226
+ logger: this.logger,
7227
+ elicit: (createRequest) => elicitUnlessWithdrawn(signal, (signal) => this.withPendingUserInput(sessionId, () => this.elicitFromClient(createRequest, signal))),
7228
+ });
8375
7229
  };
8376
7230
  }
8377
7231
  /**
8378
7232
  * Present the built-in AskUserQuestion tool's questions as an ACP form
8379
- * elicitation and return the answers as the tool's `updatedInput`. Called from
8380
- * `canUseTool` since that is where the SDK routes the tool's permission check.
8381
- * The elicitation goes to `requestSessionId`, a subagent's child session for
8382
- * a question it asks, and blocks the turn of `sessionId`.
7233
+ * elicitation and return the answers as the tool's `updatedInput` (see
7234
+ * {@link answerAskUserQuestion}). Called from `canUseTool` since that is
7235
+ * where the SDK routes the tool's permission check. The elicitation goes to
7236
+ * `requestSessionId`, a subagent's child session for a question it asks,
7237
+ * and blocks the turn of `sessionId`.
8383
7238
  */
8384
7239
  async handleAskUserQuestion(sessionId, requestSessionId, toolInput, toolUseID, toolSignal, agentID) {
8385
7240
  const signal = this.untilSessionClosed(sessionId, toolSignal);
8386
- const questions = extractAskUserQuestions(toolInput);
8387
- if (!questions) {
8388
- return { behavior: "deny", message: "AskUserQuestion called with no valid questions." };
8389
- }
8390
- const createRequest = askUserQuestionsToCreateRequest(questions, requestSessionId, toolUseID, this.toolCallCapabilities.air.client);
8391
- let response;
8392
- try {
8393
- response = await this.withChildAwaitingUser(sessionId, requestSessionId, signal, () => this.withPendingUserInput(sessionId, signal, () => this.elicitFromClient(createRequest, signal), agentID));
8394
- }
8395
- catch (error) {
8396
- // A cancellation we requested (signal aborted) settles as an aborted tool
8397
- // use, matching the post-response check below.
8398
- if (signal.aborted) {
8399
- throw new Error("Tool use aborted", { cause: error });
8400
- }
8401
- this.logger.error(`Failed to present AskUserQuestion elicitation: ${error}`);
8402
- return { behavior: "deny", message: "Could not present the question to the user." };
8403
- }
8404
- if (signal.aborted) {
8405
- throw new Error("Tool use aborted");
8406
- }
8407
- const outcome = applyAskElicitationResponse(response, toolInput, questions, {
8408
- reportUnanswered: this.sessions[sessionId]?.askUserQuestionUnansweredV1 === true,
7241
+ return answerAskUserQuestion(toolInput, {
7242
+ sessionId: requestSessionId,
7243
+ toolUseID,
7244
+ airClient: this.toolCallCapabilities.air.client,
7245
+ reportUnanswered: () => this.sessions[sessionId]?.askUserQuestionUnansweredV1 === true,
7246
+ logger: this.logger,
7247
+ elicit: (createRequest) => elicitUnlessWithdrawn(signal, (signal) => this.withChildAwaitingUser(sessionId, requestSessionId, signal, () => this.withPendingUserInput(sessionId, () => this.elicitFromClient(createRequest, signal), agentID))),
8409
7248
  });
8410
- if (outcome.action === "cancel") {
8411
- throw new Error("Tool use aborted");
8412
- }
8413
- return { behavior: "allow", updatedInput: outcome.updatedInput };
8414
7249
  }
8415
7250
  /**
8416
7251
  * Handle `request_user_dialog` control requests — blocking dialogs the CLI
8417
- * asks the host to render. Only kinds declared in `supportedDialogKinds`
8418
- * are ever emitted; everything unexpected is answered `cancelled` (the
8419
- * required answer for unrecognized kinds), which applies the dialog's
8420
- * default behavior CLI-side. Today the only declared kind is the
8421
- * refusal-fallback consent prompt, rendered as an ACP form elicitation.
7252
+ * asks the host to render (see {@link answerUserDialog}).
8422
7253
  */
8423
7254
  handleUserDialog(sessionId) {
8424
7255
  return async (request, { signal: callbackSignal }) => {
8425
7256
  const signal = this.untilSessionClosed(sessionId, callbackSignal);
8426
- if (request.dialogKind !== REFUSAL_FALLBACK_DIALOG_KIND) {
8427
- return { behavior: "cancelled" };
8428
- }
8429
- const prompt = extractRefusalFallbackPrompt(request.payload);
8430
- if (!prompt) {
8431
- this.logger.error(`refusal_fallback_prompt payload had an unexpected shape; cancelling the dialog: ${JSON.stringify(request.payload)}`);
8432
- return { behavior: "cancelled" };
8433
- }
8434
- let response;
8435
- try {
8436
- response = await this.withPendingUserInput(sessionId, signal, () => this.elicitFromClient(refusalFallbackToCreateRequest(prompt, sessionId), signal));
8437
- }
8438
- catch (error) {
8439
- // A cancellation we requested (signal aborted) is expected teardown;
8440
- // anything else is a client failure. Either way the safe answer is
8441
- // `cancelled` — the CLI applies the dialog's default (keep the
8442
- // refusal) rather than switching models without consent.
8443
- if (!signal.aborted) {
8444
- this.logger.error(`Failed to present refusal fallback elicitation: ${error}`);
8445
- }
8446
- return { behavior: "cancelled" };
8447
- }
8448
- if (signal.aborted) {
8449
- return { behavior: "cancelled" };
8450
- }
8451
- return { behavior: "completed", result: refusalFallbackResultFromResponse(response) };
7257
+ return answerUserDialog(request, {
7258
+ sessionId,
7259
+ logger: this.logger,
7260
+ elicit: (createRequest) => elicitUnlessWithdrawn(signal, (signal) => this.withPendingUserInput(sessionId, () => this.elicitFromClient(createRequest, signal))),
7261
+ });
8452
7262
  };
8453
7263
  }
8454
7264
  /**
@@ -8526,27 +7336,15 @@ export class ClaudeAcpAgent {
8526
7336
  /**
8527
7337
  * The work that follows a session setup response: the session's commands,
8528
7338
  * the current states of the subagents a load replayed, and MCP server
8529
- * authentication. On v2 the setup handlers of `src/v2/agent.ts` do this
8530
- * work once they have sent their response, so it does nothing here.
7339
+ * authentication.
8531
7340
  */
8532
7341
  afterSetupResponse(sessionId, mcpServers) {
8533
- if (this.v2)
8534
- return;
8535
7342
  setTimeout(() => {
8536
7343
  this.sendAvailableCommandsUpdate(sessionId);
8537
7344
  void this.publishCurrentSubagentStates(sessionId);
8538
7345
  startMcpAuthentication(this, sessionId, mcpServers);
8539
7346
  }, 0);
8540
7347
  }
8541
- /**
8542
- * Starts OAuth in the background for the servers of `mcpServers` that
8543
- * Claude Code reports as needing it, which sends the client a URL
8544
- * elicitation. The v2 surface calls it after the setup response, since v2
8545
- * asks for no elicitation before the `session/new` response.
8546
- */
8547
- authenticateMcpServers(sessionId, mcpServers) {
8548
- startMcpAuthentication(this, sessionId, mcpServers);
8549
- }
8550
7348
  /**
8551
7349
  * Sends the current state of each subagent that the last load of
8552
7350
  * `sessionId` replayed (see {@link RfdSubagentReplay.currentStates}). Run it
@@ -8615,21 +7413,12 @@ export class ClaudeAcpAgent {
8615
7413
  });
8616
7414
  }
8617
7415
  /**
8618
- * Refine a heuristic context window with `getContextUsage().rawMaxTokens`,
8619
- * without blocking the caller. The text heuristic misses natively-1M models
8620
- * whose picker rows carry no "1m" token (e.g. `sonnet`, and since CLI
8621
- * 2.1.283 `opus`/`default`), so those would otherwise show 200k until the
8622
- * first result's modelUsage arrives.
8623
- *
8624
- * Never awaited: SDK control requests are serialized, so awaiting here
8625
- * would delay session/new or a model switch (~15s on older CLIs, issues
8626
- * #886/#880; ~0.5s on 2.1.283). Requests the `summary` detail instead of
8627
- * the default `full` breakdown, which issues one `messages/count_tokens`
8628
- * call per category (~18 for a bare session) and hit rate limits on every
8629
- * model switch; `summary` answers locally with the same `rawMaxTokens`.
8630
- *
8631
- * Does not write `contextWindowCache` (that stays keyed to the
8632
- * `result.modelUsage` spellings) — a later result still overwrites this.
7416
+ * Refine a heuristic context window with `getContextUsage().rawMaxTokens`
7417
+ * (`readContextWindow`), without blocking the caller. The text heuristic
7418
+ * misses natively-1M models whose picker rows carry no "1m" token (e.g.
7419
+ * `sonnet`, and since CLI 2.1.283 `opus`/`default`), so those would
7420
+ * otherwise show 200k until the first result's modelUsage arrives. A later
7421
+ * result still overwrites this.
8633
7422
  */
8634
7423
  refreshContextWindowInBackground(sessionId, session) {
8635
7424
  if (session.contextWindowAuthoritative)
@@ -8641,13 +7430,13 @@ export class ClaudeAcpAgent {
8641
7430
  session.models.currentModelId === modelId;
8642
7431
  // A synchronous throw must not fail the caller either.
8643
7432
  Promise.resolve()
8644
- .then(() => query.getContextUsage({ detail: "summary" }))
8645
- .then((usage) => {
7433
+ .then(() => readContextWindow(query))
7434
+ .then((window) => {
8646
7435
  if (!stillCurrent() || session.contextWindowAuthoritative)
8647
7436
  return;
8648
- if (!(usage.rawMaxTokens > 0))
7437
+ if (window === undefined)
8649
7438
  return;
8650
- session.contextWindowSize = usage.rawMaxTokens;
7439
+ session.contextWindowSize = window;
8651
7440
  session.contextWindowAuthoritative = true;
8652
7441
  }, (error) => {
8653
7442
  if (stillCurrent())
@@ -8689,30 +7478,18 @@ export class ClaudeAcpAgent {
8689
7478
  session.fastModeDisabledReason = undefined;
8690
7479
  }
8691
7480
  // Rebuild config options since effort levels depend on the selected
8692
- // model. The effort seed depends on who owns the choice: a user pin
8693
- // made through the ACP picker this session lives at the SDK's flag
8694
- // layer and follows the session across switches, so carry it forward.
8695
- // Otherwise the CLI resolves effort itself from the persisted settings
8696
- // — the NEW model's `modelSettings` entry first (the CLI persists
8697
- // /effort per model), then the legacy top-level value — so display
8698
- // what it will actually run instead of dragging the old model's value
8699
- // along.
7481
+ // model (see `effortForModelSwitch`).
8700
7482
  const effortOpt = session.configOptions.find((o) => o.id === EFFORT_CONFIG_ID);
8701
- const currentEffort = typeof effortOpt?.currentValue === "string" ? effortOpt.currentValue : undefined;
8702
7483
  const useRecommendedValue = clientSupportsRecommendedConfigValue(this.clientCapabilities);
8703
- const pinnedEffort = session.effortPinnedLevel;
8704
- const effortWasPinned = pinnedEffort !== undefined;
8705
- const appliedEffortBeforeSwitch = session.appliedEffortLevel ??
8706
- (useRecommendedValue && typeof currentEffort === "string" && currentEffort !== "default"
8707
- ? currentEffort
8708
- : pinnedEffort);
8709
- const effortPinnedForNewModel = effortWasPinned &&
8710
- newModelInfo?.supportsEffort === true &&
8711
- newModelInfo.supportedEffortLevels?.some((level) => level === pinnedEffort) === true;
8712
- const seedEffort = effortPinnedForNewModel
8713
- ? pinnedEffort
8714
- : settingsEffortForModel(mergeEffortSettings(session.settingsManager.getSettings(), session.effortSettingsOverride), newModelInfo, value);
8715
- session.configOptions = buildConfigOptions(session.modes, session.models, session.modelInfos, seedEffort, session.agents, session.currentAgent, {
7484
+ const effortSwitch = effortForModelSwitch({
7485
+ state: { pinned: session.effortPinnedLevel, applied: session.appliedEffortLevel },
7486
+ displayed: typeof effortOpt?.currentValue === "string" ? effortOpt.currentValue : undefined,
7487
+ newModelInfo,
7488
+ modelId: value,
7489
+ settings: mergeEffortSettings(session.settingsManager.getSettings(), session.effortSettingsOverride),
7490
+ useRecommendedValue,
7491
+ });
7492
+ session.configOptions = buildConfigOptions(session.modes, session.models, session.modelInfos, effortSwitch.seed, session.agents, session.currentAgent, {
8716
7493
  // The toggle follows the newly selected model: it disappears when the
8717
7494
  // model lacks fast support and reappears (with the retained user
8718
7495
  // intent) when a supporting model is selected again.
@@ -8729,60 +7506,16 @@ export class ClaudeAcpAgent {
8729
7506
  enabled: session.ultracodeEnabled,
8730
7507
  useBooleanOption: clientSupportsBooleanConfigOptions(this.clientCapabilities),
8731
7508
  });
8732
- // Opted-in clients apply the concrete displayed effort on every switch,
8733
- // including settings-derived values, so a previous automatic flag cannot
8734
- // shadow the new model's settings. This does not create a user pin.
8735
- // For legacy clients, sync only when a user pin changed across the
8736
- // switch — i.e. the new model clamped it away (buildConfigOptions
8737
- // validated the seed against the new model's levels), where the flag
8738
- // must be cleared too or the SDK would keep running the old pin
8739
- // invisibly. Settings-derived seeds are display-only: the CLI resolves
8740
- // persisted effort itself, and pinning it at the flag layer would
8741
- // shadow the per-model values on every later switch.
8742
- const shouldSyncEffort = useRecommendedValue || (effortWasPinned && !effortPinnedForNewModel);
8743
- if (shouldSyncEffort) {
8744
- const newEffortOpt = session.configOptions.find((o) => o.id === EFFORT_CONFIG_ID);
8745
- const newEffort = typeof newEffortOpt?.currentValue === "string" ? newEffortOpt.currentValue : undefined;
8746
- try {
8747
- await session.query.applyFlagSettings(
8748
- // A legacy client's unpinned effort is display-only: the CLI
8749
- // resolves the persisted value for the new model. When an old
8750
- // user pin is no longer supported, clear the flag layer instead
8751
- // of replacing it with that displayed value. Opted-in clients
8752
- // deliberately apply their concrete displayed effort.
8753
- effortFlagSettings(useRecommendedValue ? newEffort : undefined, session.ultracodeEnabled));
8754
- session.effortPinnedLevel = effortPinnedForNewModel ? pinnedEffort : undefined;
8755
- session.appliedEffortLevel =
8756
- useRecommendedValue && newEffort !== "default" ? newEffort : undefined;
8757
- }
8758
- catch (error) {
8759
- // setModel has already succeeded. Effort synchronization is a
8760
- // secondary, best-effort operation: propagating this error would
8761
- // make the RPC report failure (or suppress an external-switch
8762
- // notification) even though the SDK is already on the new model.
8763
- // Preserve the old SDK/pin bookkeeping and never advertise the
8764
- // unapplied value: restore the last applied value when the new model
8765
- // can select it, otherwise omit the effort option until a later
8766
- // successful switch rebuilds it.
8767
- session.effortPinnedLevel = pinnedEffort;
8768
- session.appliedEffortLevel = appliedEffortBeforeSwitch;
8769
- const appliedValueStillSelectable = appliedEffortBeforeSwitch !== undefined &&
8770
- newEffortOpt?.type === "select" &&
8771
- newEffortOpt.options.some((option) => "value" in option
8772
- ? option.value === appliedEffortBeforeSwitch
8773
- : option.options.some((nested) => nested.value === appliedEffortBeforeSwitch));
8774
- if (newEffortOpt?.type === "select" && appliedValueStillSelectable) {
8775
- newEffortOpt.currentValue = appliedEffortBeforeSwitch;
8776
- }
8777
- else {
8778
- session.configOptions = session.configOptions.filter((option) => option.id !== EFFORT_CONFIG_ID);
8779
- }
8780
- this.logger.error(`Failed to synchronize effort after model switch to "${value}":`, error);
8781
- }
8782
- }
8783
- else if (effortPinnedForNewModel) {
8784
- session.effortPinnedLevel = pinnedEffort;
8785
- session.appliedEffortLevel = pinnedEffort;
7509
+ // setModel has already succeeded, so a failed effort sync is logged:
7510
+ // propagating it would make the RPC report failure (or suppress an
7511
+ // external-switch notification) even though the SDK is already on the
7512
+ // new model.
7513
+ const effort = await settleEffortAfterModelSwitch(effortSwitch, session.configOptions.find((o) => o.id === EFFORT_CONFIG_ID), session.ultracodeEnabled, useRecommendedValue, (settings) => session.query.applyFlagSettings(settings));
7514
+ session.effortPinnedLevel = effort.state.pinned;
7515
+ session.appliedEffortLevel = effort.state.applied;
7516
+ session.configOptions = session.configOptions.flatMap((option) => option.id !== EFFORT_CONFIG_ID ? [option] : effort.option ? [effort.option] : []);
7517
+ if ("error" in effort) {
7518
+ this.logger.error(`Failed to synchronize effort after model switch to "${value}":`, effort.error);
8786
7519
  }
8787
7520
  // Emit current_mode_update only after session.modes AND
8788
7521
  // session.configOptions have been fully reconciled. This way, a failure
@@ -8890,58 +7623,28 @@ export class ClaudeAcpAgent {
8890
7623
  * `fast_mode_state` (delivered on `system`/init and on user-turn `result`s).
8891
7624
  * The SDK can flip fast mode independently of the user — e.g. back to `on`
8892
7625
  * once a rate-limit `cooldown` clears — so we mirror definitive on/off
8893
- * changes into the config option and notify the client.
8894
- *
8895
- * Guards, in order:
8896
- * - absent state: nothing to reconcile.
8897
- * - no Fast mode option: the current model doesn't support fast mode, so the
8898
- * reported state reflects capability, not the user's intent. Leave the
8899
- * retained setting untouched so it's correct when a supporting model is
8900
- * reselected (the source of the earlier intent-clobber bug was mutating it
8901
- * here).
8902
- * - `cooldown`: a transient suspension of an already-enabled fast mode.
8903
- * Leave the toggle as-is rather than flapping it — and never let a stray
8904
- * cooldown spuriously enable a toggle the user has off.
7626
+ * changes into the config option and notify the client (see
7627
+ * {@link fastModeStateChange}).
8905
7628
  *
8906
- * `reason` is the SDK's `fast_mode_disabled_reason`, reported alongside the
8907
- * state. Only explainable reasons are retained (see
8908
- * {@link normalizeFastModeDisabledReason}), so the comparison below tracks
8909
- * exactly what the user can see: a routine `sdk_opt_in_required` report on
8910
- * every turn's result can't churn the option, while a real blocker updates
8911
- * the description even when the toggle's own value is unchanged. */
7629
+ * Without a Fast mode option the current model doesn't support fast mode,
7630
+ * so the reported state reflects capability, not the user's intent. The
7631
+ * retained setting stays untouched so it's correct when a supporting model
7632
+ * is reselected (the source of the earlier intent-clobber bug was mutating
7633
+ * it here). */
8912
7634
  async syncFastModeState(sessionId, session, state, reason) {
8913
- if (state === undefined) {
8914
- return;
8915
- }
8916
7635
  if (!session.configOptions.some((o) => o.id === FAST_MODE_CONFIG_ID)) {
8917
7636
  return;
8918
7637
  }
8919
- if (state === "cooldown") {
8920
- return;
8921
- }
8922
- const enabled = state === "on";
8923
- // A reason only describes an off state; drop any that rides an `on` report
8924
- // so it can't decorate the option the next time fast mode goes off.
8925
- const nextReason = enabled ? undefined : normalizeFastModeDisabledReason(reason);
8926
- if (enabled === session.fastModeEnabled && nextReason === session.fastModeDisabledReason) {
7638
+ const change = fastModeStateChange({ enabled: session.fastModeEnabled, disabledReason: session.fastModeDisabledReason }, state, reason);
7639
+ if (!change)
8927
7640
  return;
8928
- }
8929
- // The user asked for Fast mode and the SDK is telling us it can't serve it.
8930
- // The description carries the same explanation, but a toggle silently
8931
- // snapping back is the case worth saying out loud once, at the flip.
8932
- const explanation = nextReason !== undefined ? FAST_MODE_UNAVAILABLE_EXPLANATIONS[nextReason] : undefined;
8933
- const explain = session.fastModeEnabled && !enabled && explanation !== undefined;
8934
- session.fastModeEnabled = enabled;
8935
- session.fastModeDisabledReason = nextReason;
8936
- this.refreshFastModeOption(session, enabled);
8937
- if (explain) {
7641
+ session.fastModeEnabled = change.enabled;
7642
+ session.fastModeDisabledReason = change.disabledReason;
7643
+ this.refreshFastModeOption(session, change.enabled);
7644
+ if (change.notice) {
8938
7645
  await this.client.sessionUpdate({
8939
7646
  sessionId,
8940
- update: noticeOrTranscriptUpdate({
8941
- severity: "warning",
8942
- title: "Fast mode turned off",
8943
- description: `${sentenceCase(explanation)}.`,
8944
- }, clientSupportsNotices(this.clientCapabilities), `**Fast mode turned off:** ${explanation}.`),
7647
+ update: noticeOrTranscriptUpdate(change.notice.notice, clientSupportsNotices(this.clientCapabilities), change.notice.transcript),
8945
7648
  });
8946
7649
  }
8947
7650
  await this.client.sessionUpdate({
@@ -9087,57 +7790,9 @@ export class ClaudeAcpAgent {
9087
7790
  });
9088
7791
  await settingsManager.initialize();
9089
7792
  timing.phase("settings");
9090
- const mcpServers = {};
9091
- if (Array.isArray(params.mcpServers)) {
9092
- for (const server of params.mcpServers) {
9093
- if ("type" in server && (server.type === "http" || server.type === "sse")) {
9094
- // HTTP or SSE type MCP server
9095
- mcpServers[server.name] = {
9096
- type: server.type,
9097
- url: server.url,
9098
- headers: server.headers
9099
- ? Object.fromEntries(server.headers.map((e) => [e.name, e.value]))
9100
- : undefined,
9101
- };
9102
- }
9103
- else if (!("type" in server)) {
9104
- // Stdio type MCP server (with or without explicit type field)
9105
- mcpServers[server.name] = {
9106
- type: "stdio",
9107
- command: server.command,
9108
- args: server.args,
9109
- env: server.env
9110
- ? Object.fromEntries(server.env.map((e) => [e.name, e.value]))
9111
- : undefined,
9112
- };
9113
- }
9114
- }
9115
- }
7793
+ const mcpServers = sdkMcpServers(params.mcpServers);
9116
7794
  const customInstructions = airCustomInstructions(params._meta);
9117
- let systemPrompt = customInstructions === undefined
9118
- ? { type: "preset", preset: "claude_code" }
9119
- : { type: "preset", preset: "claude_code", append: customInstructions };
9120
- if (params._meta?.systemPrompt) {
9121
- const customPrompt = params._meta.systemPrompt;
9122
- if (typeof customPrompt === "string") {
9123
- systemPrompt = customPrompt;
9124
- }
9125
- else if (typeof customPrompt === "object" &&
9126
- customPrompt !== null &&
9127
- !Array.isArray(customPrompt)) {
9128
- // Forward all preset options (append, excludeDynamicSections, and
9129
- // anything the SDK adds later) while locking type/preset.
9130
- systemPrompt = {
9131
- ...customPrompt,
9132
- type: "preset",
9133
- preset: "claude_code",
9134
- };
9135
- }
9136
- }
9137
- // The spec's `systemPrompt` takes precedence over the `_meta.systemPrompt`
9138
- // extension above.
9139
- if (clientPrompt)
9140
- systemPrompt = sdkSystemPrompt(clientPrompt, customInstructions);
7795
+ const systemPrompt = sessionSystemPrompt(clientPrompt, params._meta?.systemPrompt, customInstructions);
9141
7796
  // Extract options from _meta if provided
9142
7797
  const sessionMeta = params._meta;
9143
7798
  // Bypass is off for root outside a sandbox, when settings disable it (the
@@ -9157,8 +7812,6 @@ export class ClaudeAcpAgent {
9157
7812
  const forwardSubagentText = this.forwardsSubagentText(params._meta);
9158
7813
  // Configure thinking behavior from environment variables
9159
7814
  const thinking = resolveThinkingConfig(process.env.MAX_THINKING_TOKENS, process.env.CLAUDE_CODE_THINKING_DISPLAY, this.logger);
9160
- // Parse model configuration from environment (e.g. Bedrock model overrides)
9161
- const modelConfig = parseModelConfig(process.env.CLAUDE_MODEL_CONFIG);
9162
7815
  // Elicitation modes the connected client advertised. We only forward
9163
7816
  // elicitations (and only re-enable AskUserQuestion) for modes the client
9164
7817
  // can actually render.
@@ -9213,13 +7866,8 @@ export class ClaudeAcpAgent {
9213
7866
  // into the query.
9214
7867
  const resolvedProvider = this.resolveProviderConfig();
9215
7868
  const providerEnv = createEnvForProvider(resolvedProvider);
9216
- const providedSettings = userProvidedOptions?.settings;
9217
- const providedSettingsObject = typeof providedSettings === "string"
9218
- ? JSON.parse(await fs.readFile(path.resolve(params.cwd, providedSettings), "utf8"))
9219
- : providedSettings;
9220
- const configuredSettingsObject = modelConfig
9221
- ? { ...modelConfig, ...providedSettingsObject }
9222
- : providedSettingsObject;
7869
+ // With the model configuration of the environment (e.g. Bedrock model overrides).
7870
+ const configuredSettingsObject = await configuredSettings(userProvidedOptions?.settings, params.cwd);
9223
7871
  // Claude Code applies env from settings.json after the subprocess env. Put
9224
7872
  // an active ACP route in the programmatic settings tier too so user/project
9225
7873
  // settings cannot silently restore a different ANTHROPIC_BASE_URL.
@@ -9246,7 +7894,7 @@ export class ClaudeAcpAgent {
9246
7894
  // SDK, so per-session `_meta` env routing and ambient process-env routing
9247
7895
  // are distinguished exactly as the CLI will see them.
9248
7896
  const providerCacheKey = providerCacheKeyFor(env);
9249
- this.logger.log(`[session/query] sessionId=${sessionId} resume=${creationOpts?.resume ?? "none"} apiType=${resolvedProvider?.apiType ?? "native"} baseUrl=${resolvedProvider?.baseUrl ?? "native"}`);
7897
+ this.logger.log(`[session/query] sessionId=${sessionId} resume=${creationOpts?.resume ?? "none"} apiType=${resolvedProvider?.apiType ?? "native"} baseUrl=${loggableBaseUrl(resolvedProvider?.baseUrl)}`);
9250
7898
  // Both forms of native subagent sessions report the configuration of a child.
9251
7899
  const subagentConfigHook = subagentForm(this.clientCapabilities)
9252
7900
  ? this.subagentConfigurationHook(sessionId)
@@ -9335,17 +7983,11 @@ export class ClaudeAcpAgent {
9335
7983
  ],
9336
7984
  }
9337
7985
  : {}),
9338
- // v2 needs the patch captured before an Edit or Write runs, also
9339
- // without a permission request (`fileChangePreviewHook`): a v2 diff
9340
- // cannot hold the input's snippet.
9341
- ...(this.v2 || subagentConfigHook
7986
+ ...(subagentConfigHook
9342
7987
  ? {
9343
7988
  PreToolUse: [
9344
7989
  ...(userProvidedOptions?.hooks?.PreToolUse || []),
9345
- ...(subagentConfigHook ? [{ hooks: [subagentConfigHook] }] : []),
9346
- ...(this.v2
9347
- ? [{ matcher: "Edit|Write", hooks: [this.fileChangePreviewHook(sessionId)] }]
9348
- : []),
7990
+ { hooks: [subagentConfigHook] },
9349
7991
  ],
9350
7992
  }
9351
7993
  : {}),
@@ -9466,8 +8108,8 @@ export class ClaudeAcpAgent {
9466
8108
  prompt: input,
9467
8109
  options,
9468
8110
  });
9469
- this.useAuthStatusSettings(settingsManager, configuredSettingsObject, userProvidedOptions?.env);
9470
- const authSettingsEpoch = this.authEpoch;
8111
+ this.authStatus.useSettings(settingsManager, configuredSettingsObject, userProvidedOptions?.env);
8112
+ const authSettingsEpoch = this.authStatus.epoch;
9471
8113
  timing.phase("prepare-query");
9472
8114
  // `query()` spawns the CLI at once. Any throw between here and the
9473
8115
  // registration in `this.sessions` would leave that child process running
@@ -9490,8 +8132,8 @@ export class ClaudeAcpAgent {
9490
8132
  // Publish the identity BEFORE the guard can refuse this session. A
9491
8133
  // refusal is exactly when the client most needs to know which account it
9492
8134
  // was refused for.
9493
- if (authSettingsEpoch === this.authEpoch) {
9494
- this.publishSessionAccountIdentity(initializationResult.account, settingsManager.getApiKeyHelper(configuredSettingsObject));
8135
+ if (authSettingsEpoch === this.authStatus.epoch) {
8136
+ this.authStatus.publishSessionAccount(initializationResult.account, settingsManager.getApiKeyHelper(configuredSettingsObject));
9495
8137
  }
9496
8138
  // Shared with the per-turn guard, so "warn once" spans the whole session.
9497
8139
  const claudeSubscriptionGuard = {};
@@ -9539,41 +8181,9 @@ export class ClaudeAcpAgent {
9539
8181
  const models = await getAvailableModels(q, allowedModels, initializationResult.models, settingsManager, this.logger, creationOpts.resume !== undefined, sessionId, resumedModel, resolvedProvider?.listedModels !== undefined);
9540
8182
  timing.phase("models");
9541
8183
  // Resolve the current model's capabilities separately from the stable
9542
- // permission-mode catalog advertised to ACP clients.
9543
- // A resumed session can be running a model outside the `availableModels`
9544
- // allowlist (currentModelId is then the verbatim live id, see
9545
- // `matchResumedModel`); its capabilities are still known to the SDK's
9546
- // unfiltered list, so fall back to that before treating the model as
9547
- // unknown — otherwise auto mode would be spuriously clamped and the
9548
- // Fast-mode/Effort options hidden for a model that supports them.
9549
- const allowlistedModelInfo = allowedModels.find((m) => m.value === models.currentModelId);
9550
- const fallbackModelInfo = allowlistedModelInfo
9551
- ? undefined
9552
- : (resolveModelPreference(sdkModels, models.currentModelId) ?? undefined);
9553
- const currentModelInfo = allowlistedModelInfo ?? fallbackModelInfo;
9554
- // Register the fallback-resolved capabilities under the verbatim live id
9555
- // so every modelInfos consumer (buildConfigOptions' effort lookup, later
9556
- // rebuilds via session.modelInfos) agrees with the gating below.
9557
- // `buildModelConfigOption` lists this model as its own entry while it is
9558
- // current and drops it once the user switches to a listed model; it is
9559
- // never added to `models.availableModels`. The spread keeps every capability flag
9560
- // (current and future); the identity fields are overridden because the
9561
- // fuzzy-matched sibling's resolvedModel/displayName/description can
9562
- // describe a different context lane and would poison later resolvedModel
9563
- // matching (syncModelAfterExternalSwitch) and context-window inference
9564
- // (applyConfigOptionValue) if they traveled under this id.
9565
- const modelInfos = fallbackModelInfo
9566
- ? [
9567
- ...allowedModels,
9568
- {
9569
- ...fallbackModelInfo,
9570
- value: models.currentModelId,
9571
- displayName: models.currentModelId,
9572
- description: "",
9573
- resolvedModel: undefined,
9574
- },
9575
- ]
9576
- : allowedModels;
8184
+ // permission-mode catalog advertised to ACP clients (see
8185
+ // `withCurrentModelInfo`).
8186
+ const { allowlistedModelInfo, currentModelInfo, modelInfos } = withCurrentModelInfo(allowedModels, sdkModels, models.currentModelId);
9577
8187
  const { modes, autoModeFallbackWarningPending } = await this.sessionModes.initialize({
9578
8188
  query: q,
9579
8189
  requestedMode: initialPermissionMode,
@@ -9710,13 +8320,13 @@ export class ClaudeAcpAgent {
9710
8320
  contextWindowAuthoritative: seededWindow.authoritative,
9711
8321
  providerCacheKey,
9712
8322
  taskState,
8323
+ subagentChecklists: creationOpts.replayState?.subagentChecklists ?? new Set(),
9713
8324
  toolUseCache: {},
9714
8325
  emittedToolCalls: new Set(),
9715
8326
  eagerToolCallSessions: new Map(),
9716
8327
  liveBackgroundTasks: new Map(),
9717
- background: new SessionBackgroundWork(sessionId, this.backgroundWork.enabled && options.perTaskStopAffordance === true),
8328
+ background: new SessionBackgroundWork(sessionId),
9718
8329
  stopsWorkflowsOnCancel: options.perTaskStopAffordance === true &&
9719
- !this.backgroundWork.enabled &&
9720
8330
  !clientSupportsAsyncTasks(this.clientCapabilities),
9721
8331
  nativeSubagentsByTaskId: new Map(),
9722
8332
  nativeSubagentTaskIdByToolUseId: new Map(),
@@ -9728,6 +8338,9 @@ export class ClaudeAcpAgent {
9728
8338
  claudeSubscriptionGuard,
9729
8339
  accountKind: fromAccountInfo(initializationResult.account, settingsManager.getApiKeyHelper(configuredSettingsObject))?.kind,
9730
8340
  fileChangeReporter,
8341
+ ...(this.toolCallCapabilities.air.client
8342
+ ? { promptSuggestions: new PromptSuggestions() }
8343
+ : {}),
9731
8344
  };
9732
8345
  const registered = this.sessions[sessionId];
9733
8346
  registered.idleCompaction = new IdleCompaction({
@@ -9744,7 +8357,6 @@ export class ClaudeAcpAgent {
9744
8357
  // The CLI's own environment: process env, the client's and the provider's.
9745
8358
  { env });
9746
8359
  timing.phase("register");
9747
- this.backgroundWork.sync(sessionId, this.sessions[sessionId], this.foregroundState(sessionId));
9748
8360
  this.refreshContextWindowInBackground(sessionId, this.sessions[sessionId]);
9749
8361
  return {
9750
8362
  sessionId,
@@ -9769,16 +8381,7 @@ export class ClaudeAcpAgent {
9769
8381
  // and logout apply in the order they arrived. A failed listing fails this
9770
8382
  // `providers/set` before the provider replaces the current one.
9771
8383
  if (config) {
9772
- try {
9773
- Object.assign(config, await this.listProviderModels(config));
9774
- }
9775
- catch (error) {
9776
- if (error instanceof GatewayListingError) {
9777
- throw RequestError.internalError({ providerId: PROVIDER_ID, apiType: config.apiType, baseUrl: config.baseUrl }, `Model discovery for provider "${PROVIDER_ID}" failed: ${error.message}`);
9778
- }
9779
- throw error;
9780
- }
9781
- this.logger.log(`[providers/set] listedModels=${config.listedModels?.length ?? "none"} bedrockRegionPrefix=${config.bedrockRegionPrefix ?? "none"}`);
8384
+ await withListedModels(config, this.providerConfig, this.logger);
9782
8385
  }
9783
8386
  const sessions = Object.entries(this.sessions);
9784
8387
  const activeTurns = sessions.flatMap(([, session]) => (session.turnQueue ?? []).flatMap((turn) => (turn.completion ? [turn.completion] : [])));
@@ -10052,19 +8655,6 @@ function servesCancelledWork(session, status) {
10052
8655
  function turnQuotaMeta(session) {
10053
8656
  return quotaMeta(session.accumulatedUsage, session.accumulatedModelUsage);
10054
8657
  }
10055
- /** `_meta.quota` for work that spent `usage` in its main agent loop and
10056
- * `modelUsage` by model (see {@link turnQuotaMeta}). */
10057
- function quotaMeta(usage, modelUsage) {
10058
- return {
10059
- quota: {
10060
- token_count: quotaTokenCount(usage),
10061
- model_usage: Object.entries(modelUsage ?? {}).map(([model, usage]) => ({
10062
- model,
10063
- token_count: quotaTokenCount(usage),
10064
- })),
10065
- },
10066
- };
10067
- }
10068
8658
  /** Whether a request that awaits the user for the subagent `agentID` (absent
10069
8659
  * for the main conversation) blocks the session's foreground work. The main
10070
8660
  * conversation's requests do. So do those of a subagent that runs in the
@@ -10093,158 +8683,9 @@ function blocksForeground(session, agentID) {
10093
8683
  }
10094
8684
  /** Whether Claude Code ended the work of `result` because an interrupt
10095
8685
  * stopped it, while the model streamed or while a tool ran. */
10096
- function isAbortedResult(result) {
8686
+ export function isAbortedResult(result) {
10097
8687
  return (result.terminal_reason === "aborted_streaming" || result.terminal_reason === "aborted_tools");
10098
8688
  }
10099
- /** How a model cycle that Claude Code started on its own ended, read from its
10100
- * result as a turn's is: a refusal, the token limit, and the turn and budget
10101
- * limits are their stop reasons, an error result fails the cycle, and a
10102
- * cancel ends it `cancelled`. The usage and `_meta.quota` are the result's
10103
- * own, `modelUsage` its increment by model, since autonomous results stay out
10104
- * of the turn tally. */
10105
- function autonomousCycleEnd(result, modelUsage, cancelled) {
10106
- // Typed non-null, but third-party backends have been observed omitting
10107
- // usage token fields (see snapshotFromUsage).
10108
- const tally = {
10109
- inputTokens: result.usage.input_tokens ?? 0,
10110
- outputTokens: result.usage.output_tokens ?? 0,
10111
- cachedReadTokens: result.usage.cache_read_input_tokens ?? 0,
10112
- cachedWriteTokens: result.usage.cache_creation_input_tokens ?? 0,
10113
- };
10114
- const ended = (stopReason) => ({
10115
- outcome: {
10116
- stopReason,
10117
- usage: { ...tally, totalTokens: tallyTotal(tally) },
10118
- _meta: quotaMeta(tally, modelUsage),
10119
- },
10120
- });
10121
- if (cancelled)
10122
- return ended("cancelled");
10123
- if (result.stop_reason === "refusal")
10124
- return ended("refusal");
10125
- if (result.stop_reason === "max_tokens")
10126
- return ended("max_tokens");
10127
- if (result.is_error) {
10128
- const text = result.subtype === "success" ? result.result : result.errors.join(", ") || result.subtype;
10129
- return { error: RequestError.internalError(undefined, text) };
10130
- }
10131
- return ended(result.subtype === "success" || result.subtype === "error_during_execution"
10132
- ? "end_turn"
10133
- : "max_turn_requests");
10134
- }
10135
- /** One `token_count` object. `cachedInputTokens` is cache reads, matching
10136
- * codex's field; Claude also reports cache writes, which codex has no slot
10137
- * for, so those ride along in an extra sibling (the same name the ACP `usage`
10138
- * field already uses) and are counted in `totalTokens`. `reasoningOutputTokens`
10139
- * is always 0: Claude bills thinking inside its output tokens and never breaks
10140
- * it out — the key is kept so the shape stays uniform across agents. */
10141
- function quotaTokenCount(usage) {
10142
- return {
10143
- totalTokens: tallyTotal(usage),
10144
- inputTokens: usage.inputTokens,
10145
- cachedInputTokens: usage.cachedReadTokens,
10146
- cachedWriteTokens: usage.cachedWriteTokens,
10147
- outputTokens: usage.outputTokens,
10148
- reasoningOutputTokens: 0,
10149
- };
10150
- }
10151
- /** Sum a tally's four counters. Per the Anthropic API `inputTokens` excludes
10152
- * the cache counters, so this is not double-counting (see `totalTokens`). */
10153
- function tallyTotal(usage) {
10154
- return usage.inputTokens + usage.outputTokens + usage.cachedReadTokens + usage.cachedWriteTokens;
10155
- }
10156
- /** Project `result.modelUsage` into our tally shape. Counters are coerced the
10157
- * way `snapshotFromUsage` coerces the stream's: third-party backends have been
10158
- * observed omitting fields, and a missing or NaN counter must not reach the
10159
- * wire as NaN (which `JSON.stringify` writes as `null`). */
10160
- function normalizeModelUsage(modelUsage) {
10161
- const tally = {};
10162
- for (const [model, usage] of Object.entries(modelUsage ?? {})) {
10163
- tally[model] = {
10164
- inputTokens: finiteCount(usage?.inputTokens),
10165
- outputTokens: finiteCount(usage?.outputTokens),
10166
- cachedReadTokens: finiteCount(usage?.cacheReadInputTokens),
10167
- cachedWriteTokens: finiteCount(usage?.cacheCreationInputTokens),
10168
- };
10169
- }
10170
- return tally;
10171
- }
10172
- function finiteCount(value) {
10173
- return typeof value === "number" && Number.isFinite(value) ? value : 0;
10174
- }
10175
- /** `current - previous` per model, dropping models with nothing to report so a
10176
- * turn only lists the models it actually ran on. A reading that fell BELOW the
10177
- * previous one means the running total restarted under us (a mid-session
10178
- * /clear, a zeroed crash result): there is no usable reference left to
10179
- * subtract, so the reading itself is the increment. */
10180
- function modelUsageIncrement(current, previous) {
10181
- const increment = {};
10182
- for (const [model, usage] of Object.entries(current)) {
10183
- const base = previous[model];
10184
- const subtracted = base
10185
- ? {
10186
- inputTokens: usage.inputTokens - base.inputTokens,
10187
- outputTokens: usage.outputTokens - base.outputTokens,
10188
- cachedReadTokens: usage.cachedReadTokens - base.cachedReadTokens,
10189
- cachedWriteTokens: usage.cachedWriteTokens - base.cachedWriteTokens,
10190
- }
10191
- : usage;
10192
- const rewound = Object.values(subtracted).some((count) => count < 0);
10193
- const resolved = rewound ? usage : subtracted;
10194
- if (tallyTotal(resolved) > 0) {
10195
- increment[model] = resolved;
10196
- }
10197
- }
10198
- return increment;
10199
- }
10200
- /** The per-model rows for the first result of a resumed session. Its
10201
- * `modelUsage` reading continues from the totals the transcript saved (SDK
10202
- * 0.3.277+; older transcripts may hold none), so there is no earlier reading
10203
- * to subtract from, and taking the reading itself would charge the whole
10204
- * pre-resume history to this one turn. The result's own `usage` is per-turn
10205
- * (main agent loop only, like the response's `usage`), so it stands in under
10206
- * the turn's top-level model — `key` is that model's `modelUsage` spelling
10207
- * when the reading has one, else the assistant message's own. Any subagent
10208
- * spend on this one turn goes unlisted rather than over-listed. */
10209
- function resumedFirstResultModelUsage(usage, key) {
10210
- if (key === null) {
10211
- return {};
10212
- }
10213
- const row = {
10214
- inputTokens: finiteCount(usage.input_tokens),
10215
- outputTokens: finiteCount(usage.output_tokens),
10216
- cachedReadTokens: finiteCount(usage.cache_read_input_tokens),
10217
- cachedWriteTokens: finiteCount(usage.cache_creation_input_tokens),
10218
- };
10219
- return tallyTotal(row) > 0 ? { [key]: row } : {};
10220
- }
10221
- /** Fold `increment` into `base` per model — the per-model counterpart of the
10222
- * `+=` the turn's flat accumulator uses. */
10223
- function addModelUsage(base, increment) {
10224
- const merged = { ...base };
10225
- for (const [model, usage] of Object.entries(increment)) {
10226
- const existing = merged[model];
10227
- merged[model] = existing
10228
- ? {
10229
- inputTokens: existing.inputTokens + usage.inputTokens,
10230
- outputTokens: existing.outputTokens + usage.outputTokens,
10231
- cachedReadTokens: existing.cachedReadTokens + usage.cachedReadTokens,
10232
- cachedWriteTokens: existing.cachedWriteTokens + usage.cachedWriteTokens,
10233
- }
10234
- : usage;
10235
- }
10236
- return merged;
10237
- }
10238
- /** Sum all four fields as a proxy for post-turn context occupancy: the current
10239
- * turn's output becomes next turn's input. Per the Anthropic API, input_tokens
10240
- * excludes cache tokens — cache_read and cache_creation are reported
10241
- * separately — so summing all four is not double-counting. */
10242
- function totalTokens(usage) {
10243
- return (usage.input_tokens +
10244
- usage.output_tokens +
10245
- usage.cache_read_input_tokens +
10246
- usage.cache_creation_input_tokens);
10247
- }
10248
8689
  /**
10249
8690
  * Build the `data` payload attached to a `RequestError.internalError` when we
10250
8691
  * have a categorical error — from the Claude SDK, or one of the adapter's own
@@ -10258,309 +8699,7 @@ function totalTokens(usage) {
10258
8699
  function errorKindData(errorKind) {
10259
8700
  return errorKind ? { errorKind } : undefined;
10260
8701
  }
10261
- /** Project a nullable API usage object into our non-null snapshot shape.
10262
- * Both SDK message_start and assistant message `usage` have `number | null`
10263
- * cache fields; we coerce absent values to 0 so `totalTokens` never hits
10264
- * NaN. `input_tokens`/`output_tokens` are typed `number` by the SDK but
10265
- * synthetic or third-party-backend stream events have been observed emitting
10266
- * them as null/undefined — coerce those too so a malformed upstream event
10267
- * can't leak NaN into the wire `used` field. Delta events have different
10268
- * semantics (cumulative + prev fallback) and are handled inline. */
10269
- function snapshotFromUsage(usage) {
10270
- return {
10271
- input_tokens: usage.input_tokens ?? 0,
10272
- output_tokens: usage.output_tokens ?? 0,
10273
- cache_read_input_tokens: usage.cache_read_input_tokens ?? 0,
10274
- cache_creation_input_tokens: usage.cache_creation_input_tokens ?? 0,
10275
- };
10276
- }
10277
- /**
10278
- * Adapt a legacy gateway `authenticate` request into the shared
10279
- * {@link ProviderConfig} shape. Returns `null` when no gateway request is
10280
- * present. `methodId` selects the protocol: `gateway-bedrock` → bedrock,
10281
- * otherwise anthropic.
10282
- */
10283
- function gatewayRequestToProviderConfig(request) {
10284
- // `authenticate` validates the payload before it stores one, so a stored
10285
- // request always carries a usable gateway. Re-check the shape here anyway:
10286
- // this function decides whether a provider override is active, and the
10287
- // `--hide-claude-auth` guard is off while one is.
10288
- const gateway = request?._meta?.gateway;
10289
- if (!gateway || !isValidBaseUrl(gateway.baseUrl)) {
10290
- return null;
10291
- }
10292
- return {
10293
- apiType: request?.methodId === "gateway-bedrock" ? "bedrock" : "anthropic",
10294
- baseUrl: gateway.baseUrl,
10295
- headers: gateway.headers ?? {},
10296
- };
10297
- }
10298
- /**
10299
- * Map a resolved provider config into the Claude Code env vars that redirect API
10300
- * traffic and inject headers. Returns an empty object when routing is
10301
- * unconfigured. The token/bypass placeholders (`" "`) are required so the CLI
10302
- * skips its normal login/credential checks when a gateway is in use.
10303
- */
10304
- function createEnvForProvider(config) {
10305
- if (!config) {
10306
- return {};
10307
- }
10308
- const resetRouting = {
10309
- ANTHROPIC_BASE_URL: "",
10310
- ANTHROPIC_BEDROCK_BASE_URL: "",
10311
- ANTHROPIC_VERTEX_BASE_URL: "",
10312
- CLAUDE_CODE_USE_BEDROCK: "0",
10313
- CLAUDE_CODE_USE_VERTEX: "0",
10314
- ANTHROPIC_VERTEX_PROJECT_ID: "",
10315
- CLOUD_ML_REGION: "",
10316
- AWS_REGION: "",
10317
- ANTHROPIC_API_KEY: "",
10318
- ANTHROPIC_AUTH_TOKEN: "",
10319
- CLAUDE_CODE_OAUTH_TOKEN: "",
10320
- };
10321
- const customHeaders = Object.entries(config.headers)
10322
- .map(([key, value]) => `${key}: ${value}`)
10323
- .join("\n");
10324
- if (config.apiType === "bedrock") {
10325
- return {
10326
- ...resetRouting,
10327
- CLAUDE_CODE_USE_BEDROCK: "1",
10328
- AWS_BEARER_TOKEN_BEDROCK: PROVIDER_AUTH_TOKEN_PLACEHOLDER, // Bypass local AWS credential checks
10329
- ANTHROPIC_BEDROCK_BASE_URL: config.baseUrl,
10330
- ANTHROPIC_CUSTOM_HEADERS: customHeaders,
10331
- ...(config.bedrockRegionPrefix
10332
- ? { ANTHROPIC_BEDROCK_REGION_PREFIX: config.bedrockRegionPrefix }
10333
- : {}),
10334
- };
10335
- }
10336
- if (config.apiType === "vertex") {
10337
- // `config.vertex` is guaranteed present for vertex by `unstable_setProvider`
10338
- // validation; fall back to empty strings defensively.
10339
- // Leaving ANTHROPIC_VERTEX_BASE_URL empty for the default endpoint lets
10340
- // Claude Code use its native Vertex endpoint/model resolution. Supplying
10341
- // even the default host marks the session as a custom Vertex deployment and
10342
- // can hide otherwise-valid models.
10343
- return {
10344
- ...resetRouting,
10345
- CLAUDE_CODE_USE_VERTEX: "1",
10346
- ...(config.baseUrl !== DEFAULT_VERTEX_BASE_URL
10347
- ? { ANTHROPIC_VERTEX_BASE_URL: config.baseUrl }
10348
- : {}),
10349
- ANTHROPIC_VERTEX_PROJECT_ID: config.vertex?.projectId ?? "",
10350
- CLOUD_ML_REGION: config.vertex?.region ?? "",
10351
- ANTHROPIC_CUSTOM_HEADERS: customHeaders,
10352
- };
10353
- }
10354
- return {
10355
- ...resetRouting,
10356
- ANTHROPIC_BASE_URL: config.baseUrl,
10357
- ANTHROPIC_CUSTOM_HEADERS: customHeaders,
10358
- ANTHROPIC_AUTH_TOKEN: PROVIDER_AUTH_TOKEN_PLACEHOLDER, // Bypass local Claude login checks
10359
- };
10360
- }
10361
- function sameHeaders(a, b) {
10362
- const aKeys = Object.keys(a);
10363
- return aKeys.length === Object.keys(b).length && aKeys.every((key) => b[key] === a[key]);
10364
- }
10365
- /**
10366
- * Validate a provider base URL: must be a non-empty absolute http(s) URL.
10367
- */
10368
- function isValidBaseUrl(baseUrl) {
10369
- if (typeof baseUrl !== "string" || baseUrl.trim() === "") {
10370
- return false;
10371
- }
10372
- let parsed;
10373
- try {
10374
- parsed = new URL(baseUrl);
10375
- }
10376
- catch {
10377
- return false;
10378
- }
10379
- return parsed.protocol === "http:" || parsed.protocol === "https:";
10380
- }
10381
- // `supportedAgents()` always returns Claude Code's built-in subagents — the
10382
- // ones used for Task-tool delegation (Explore, Plan, etc.) — even when the user
10383
- // has configured none of their own. Those aren't meaningful *main-thread*
10384
- // personas, so we filter them out and only surface the Agent picker when the
10385
- // user (or a plugin/project) has configured custom agents. Update this set if
10386
- // the SDK's built-in roster changes.
10387
- export const BUILTIN_AGENT_NAMES = new Set([
10388
- "claude",
10389
- "general-purpose",
10390
- "Explore",
10391
- "Plan",
10392
- "statusline-setup",
10393
- ]);
10394
- // Value of the synthetic "Default" entry in the agent picker, which maps to the
10395
- // standard Claude Code agent (`applyFlagSettings({ agent: null })`). It is a
10396
- // reserved sentinel: a custom agent named exactly this would collide with it
10397
- // (two options sharing the value, selection silently routing to `null`), so we
10398
- // exclude that name from discovery.
10399
- /** Discover user/plugin/project-configured main-thread agents, excluding the
10400
- * built-in subagents and the reserved "default" sentinel. Returns an empty
10401
- * list if discovery fails so a flaky control request never blocks session
10402
- * creation. */
10403
- export async function discoverCustomAgents(q) {
10404
- try {
10405
- const agents = await q.supportedAgents();
10406
- return agents.filter((a) => !BUILTIN_AGENT_NAMES.has(a.name) && a.name !== DEFAULT_AGENT_ID);
10407
- }
10408
- catch {
10409
- return [];
10410
- }
10411
- }
10412
- /** Stable ids for the session config options surfaced via `configOptions`.
10413
- * Centralized so the option declarations in `buildConfigOptions` and the
10414
- * handlers in `setSessionConfigOption`/`applyConfigOptionValue` reference the
10415
- * same identifiers and can't drift apart. */
10416
- export { MODE_CONFIG_ID };
10417
- export const AGENT_CONFIG_ID = "agent";
10418
- export const FAST_MODE_CONFIG_ID = "fast";
10419
- /** Select-fallback values used when the client has not opted into boolean
10420
- * config options (see {@link createFastModeConfigOption}). */
10421
- export const FAST_MODE_ON = "on";
10422
- export const FAST_MODE_OFF = "off";
10423
- const FAST_MODE_DESCRIPTION = "Faster responses on supported models";
10424
- /** Map the SDK's tri-state `fast_mode_state` onto the boolean config toggle.
10425
- * `cooldown` (fast mode temporarily suspended after a rate limit, per the SDK
10426
- * docs) keeps the toggle on so it reflects the user's intent — only an
10427
- * explicit `off` clears it. */
10428
- export function fastModeStateEnabled(state) {
10429
- return state !== "off";
10430
- }
10431
- /** User-facing explanations for the SDK's `fast_mode_disabled_reason` values
10432
- * that a user can act on (or at least wants to know about). Deliberately
10433
- * partial — the omitted reasons are not worth surfacing:
10434
- * - `sdk_opt_in_required`: every SDK session starts here (the toggle IS the
10435
- * opt-in), so it describes the default, not a problem.
10436
- * - `preference`: the user turned Fast mode off themselves.
10437
- * - `pending`: eligibility is still resolving; the next report supersedes it.
10438
- * - `unknown`: nothing meaningful to say.
10439
- * Unknown future reasons fall through the same way (open set — the SDK's docs
10440
- * say to ignore values you don't handle). */
10441
- const FAST_MODE_UNAVAILABLE_EXPLANATIONS = {
10442
- free: "not available on the free plan",
10443
- extra_usage_disabled: "requires extra usage to be enabled for this account",
10444
- model_not_allowed: "not available for the selected model",
10445
- not_first_party: "not available on this API provider",
10446
- disabled_by_env: "disabled by environment configuration",
10447
- network_error: "eligibility could not be verified (network error)",
10448
- };
10449
- /** Normalize an SDK-reported `fast_mode_disabled_reason` to the one we retain:
10450
- * a reason we have an explanation for, else `undefined`. Keeping only
10451
- * explainable reasons means state comparisons (see `syncFastModeState`) track
10452
- * exactly what the user can see, so routine reports like
10453
- * `sdk_opt_in_required` never churn the config option. */
10454
- export function normalizeFastModeDisabledReason(reason) {
10455
- return reason && FAST_MODE_UNAVAILABLE_EXPLANATIONS[reason] ? reason : undefined;
10456
- }
10457
- /** Whether the Client advertised support for boolean session config options
10458
- * (`session.configOptions.boolean`). Agents MUST only send `type: "boolean"`
10459
- * config options to Clients that opt in; otherwise we fall back to a `select`.
10460
- * See https://agentclientprotocol.com/rfds/boolean-config-option. */
10461
- export function clientSupportsBooleanConfigOptions(clientCapabilities) {
10462
- return clientCapabilities?.session?.configOptions?.boolean != null;
10463
- }
10464
- /** Whether the Client advertised the AIR `recommendedValue` capability for
10465
- * select-style model and effort options. Missing or malformed AIR metadata
10466
- * retains the legacy `default` entries. */
10467
- export function clientSupportsRecommendedConfigValue(clientCapabilities) {
10468
- return clientSupportsAirCapability(clientCapabilities, AIR_RECOMMENDED_CONFIG_VALUE_CAPABILITY);
10469
- }
10470
- /** Build the Fast mode config option. When the Client supports boolean config
10471
- * options we expose a native `type: "boolean"` toggle; otherwise we degrade to
10472
- * a two-value `select` ("on"/"off") so older Clients still get a usable
10473
- * control.
10474
- *
10475
- * `disabledReason` (the SDK's `fast_mode_disabled_reason`) is folded into the
10476
- * description while the toggle reads off, so a user whose account or provider
10477
- * can't serve Fast mode sees why instead of a switch that silently refuses to
10478
- * stay on. Ignored while enabled: a reason reported alongside an `on`/`cooldown`
10479
- * state isn't blocking anything right now. */
10480
- export function createFastModeConfigOption(enabled, useBooleanOption, disabledReason) {
10481
- const explanation = enabled
10482
- ? undefined
10483
- : disabledReason && FAST_MODE_UNAVAILABLE_EXPLANATIONS[disabledReason];
10484
- const base = {
10485
- id: FAST_MODE_CONFIG_ID,
10486
- name: "Fast mode",
10487
- description: explanation ? `${FAST_MODE_DESCRIPTION} — ${explanation}` : FAST_MODE_DESCRIPTION,
10488
- category: "model_config",
10489
- };
10490
- if (useBooleanOption) {
10491
- return { ...base, type: "boolean", currentValue: enabled };
10492
- }
10493
- return {
10494
- ...base,
10495
- type: "select",
10496
- currentValue: enabled ? FAST_MODE_ON : FAST_MODE_OFF,
10497
- options: [
10498
- { value: FAST_MODE_ON, name: "On" },
10499
- { value: FAST_MODE_OFF, name: "Off" },
10500
- ],
10501
- };
10502
- }
10503
- /** Resolve the requested Fast mode value from a `session/set_config_option`
10504
- * request. Accepts a native boolean (boolean-capable Clients) or the
10505
- * "on"/"off" select-fallback strings. */
10506
- export function resolveFastModeEnabled(params) {
10507
- const value = params.value;
10508
- if (typeof value === "boolean") {
10509
- return value;
10510
- }
10511
- if (value === FAST_MODE_ON) {
10512
- return true;
10513
- }
10514
- if (value === FAST_MODE_OFF) {
10515
- return false;
10516
- }
10517
- throw RequestError.invalidParams(undefined, `Invalid value for config option ${FAST_MODE_CONFIG_ID}: ${value}`);
10518
- }
10519
- export function buildConfigOptions(modes, models, modelInfos, currentEffortLevel, agents = [], currentAgent = DEFAULT_AGENT_ID, fastMode, presentation, ultracode) {
10520
- const options = [SessionModeManager.configOption(modes)];
10521
- // A gateway that lists none of the SDK's models leaves no model to offer, so
10522
- // there is no model option at all.
10523
- if (models.availableModels.length > 0) {
10524
- options.push(buildModelConfigOption(models, modelInfos, presentation?.useRecommendedValue === true));
10525
- }
10526
- const effort = buildEffortConfigOption(modelInfos, models.currentModelId, currentEffortLevel, presentation?.useRecommendedValue === true);
10527
- if (effort)
10528
- options.push(effort);
10529
- // Surface the Fast mode toggle only when the current model supports it. The
10530
- // option renders as a native boolean toggle for Clients that opted in, and a
10531
- // two-value select otherwise.
10532
- if (fastMode?.supported) {
10533
- options.push(createFastModeConfigOption(fastMode.enabled, fastMode.useBooleanOption, fastMode.disabledReason));
10534
- }
10535
- // Surface the ultracode toggle only while the CLI can run it: dynamic
10536
- // workflows are enabled and the current model supports it.
10537
- if (ultracode?.supported) {
10538
- options.push(createUltracodeConfigOption(ultracode.enabled, ultracode.useBooleanOption));
10539
- }
10540
- // Only surface the Agent picker when there's a real choice — i.e. the user
10541
- // has configured at least one custom agent (built-ins are filtered out in
10542
- // discoverCustomAgents). With none configured, "Default" would be the only
10543
- // entry, so we omit the option entirely.
10544
- if (agents.length > 0) {
10545
- options.push({
10546
- id: AGENT_CONFIG_ID,
10547
- name: "Agent",
10548
- description: "Main-thread agent persona",
10549
- type: "select",
10550
- currentValue: currentAgent,
10551
- options: [
10552
- { value: DEFAULT_AGENT_ID, name: "Default", description: "Standard Claude Code agent" },
10553
- ...agents.map((a) => ({
10554
- value: a.name,
10555
- name: a.name,
10556
- description: a.description || undefined,
10557
- })),
10558
- ],
10559
- });
10560
- }
10561
- return options;
10562
- }
10563
- function getAvailableSlashCommands(commands,
8702
+ export function getAvailableSlashCommands(commands,
10564
8703
  // Names the CLI tagged terminal-bound on `system`/init (their UX lives in
10565
8704
  // the CLI's own terminal, which ACP clients aren't) — filtered alongside
10566
8705
  // the static list. Raw CLI names, matched before the MCP rename.
@@ -11026,7 +9165,14 @@ export function toAcpNotifications(content, role, sessionId, toolUseCache, clien
11026
9165
  if (chunk.name === "TodoWrite") {
11027
9166
  // @ts-expect-error - sometimes input is empty object or undefined
11028
9167
  if (Array.isArray(chunk.input?.todos)) {
11029
- update = checklistPlanUpdate(planEntries(chunk.input), options?.clientCapabilities?.plan != null);
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
+ });
11030
9176
  }
11031
9177
  }
11032
9178
  else if (isTaskTool(chunk.name)) {
@@ -11315,6 +9461,7 @@ export function streamEventToAcpNotifications(message, sessionId, toolUseCache,
11315
9461
  parentToolUseId: message.parent_tool_use_id,
11316
9462
  cwd: options?.cwd,
11317
9463
  taskState: options?.taskState,
9464
+ subagentChecklists: options?.subagentChecklists,
11318
9465
  emittedToolCalls: options?.emittedToolCalls,
11319
9466
  toolCallFields: options?.toolCallFields,
11320
9467
  messageId: options?.messageId,
@@ -11487,185 +9634,6 @@ export function runAcp(logger) {
11487
9634
  const connection = v1AgentApp(logger, (created) => (agent = created)).connect(stream);
11488
9635
  return { connection, agent };
11489
9636
  }
11490
- function commonPrefixLength(a, b) {
11491
- let i = 0;
11492
- while (i < a.length && i < b.length && a[i] === b[i]) {
11493
- i++;
11494
- }
11495
- return i;
11496
- }
11497
- /** Best-effort first guess of a model's context window, used to seed the
11498
- * window synchronously (via `immediateContextWindow`) until a `result` message
11499
- * arrives with the authoritative `modelUsage` value.
11500
- *
11501
- * Anthropic 1M-context variants encode "1m" as a distinct token in the SDK
11502
- * model ID (e.g., "claude-opus-4-6-1m"), which `\b1m\b` catches without also
11503
- * matching things like "10m" or embedded substrings. Semantic aliases like
11504
- * `default` carry no such token in the ID, but their `resolvedModel` and the
11505
- * SDK's human-facing `displayName`/`description` can (e.g.
11506
- * "claude-opus-4-8[1m]", "Opus 4.7 (1M context)"), so callers pass those too.
11507
- * This text scan can't catch every model — some resolve to extended-context
11508
- * models with no "1m" anywhere (e.g. `sonnet` → claude-sonnet-5, natively
11509
- * ~1M). Such a miss falls back to the default window, is refined by the
11510
- * background `getContextUsage` (`refreshContextWindowInBackground`), and is
11511
- * corrected by `result.modelUsage` (and cached) within one turn. */
11512
- function inferContextWindowFromModel(...texts) {
11513
- if (texts.some((text) => text != null && /\b1m\b/i.test(text)))
11514
- return 1_000_000;
11515
- return null;
11516
- }
11517
- /** Cross-session cache of authoritative context windows, keyed by
11518
- * `${providerCacheKey}\0${modelId}` (see {@link contextWindowCacheKey}).
11519
- * The window is a property of (model id, backend): the same resolved model id
11520
- * (e.g. "claude-sonnet-5[1m]", the spelling of the `result.modelUsage` keys)
11521
- * can name different context lanes behind different base URLs, routing
11522
- * headers, or credentials, so the key carries both. Caching it module-level
11523
- * lets a later session/new or switch that resolves to the same (backend,
11524
- * model) — in this session or any other, within the adapter's lifetime — seed
11525
- * the correct window synchronously with no IPC. Keying on the resolved id
11526
- * (rather than the picker value) means aliases that resolve to the same
11527
- * concrete model share one entry; the result handler additionally writes the
11528
- * bare assistant-message spelling so seed-time reads that fall back to a
11529
- * verbatim live id (rows without `resolvedModel`) can hit too.
11530
- *
11531
- * Populated authoritatively by each `result.modelUsage` a turn confirms (see
11532
- * the consumer's result handler). We deliberately never populate it from
11533
- * `getContextUsage`: its `model` spelling and `rawMaxTokens` can differ from
11534
- * the `result.modelUsage` key and window (e.g. 967000 vs 1000000 for sonnet),
11535
- * so it only refines the live session (`refreshContextWindowInBackground`).
11536
- * Cleared on `logout`: 1M-context entitlement can differ per account/tier, so
11537
- * windows learned under one login must not seed sessions under the next. */
11538
- const contextWindowCache = new Map();
11539
- /** The env vars that determine which LLM backend — and which context lane on
11540
- * it — a query's API traffic reaches: endpoint selection (base URLs and the
11541
- * Bedrock/Vertex switches with their project/region), routing/beta headers
11542
- * (an `anthropic-beta: context-1m-…` header flips the same model id at the
11543
- * same endpoint between context lanes), and credential identity (extended
11544
- * context is entitlement-gated per account). Used to derive the
11545
- * provider-cache key from the exact env a query is created with, so
11546
- * `providers/set` config, per-session `_meta` env overrides, and ambient
11547
- * process env are all distinguished exactly as the CLI will see them. */
11548
- const PROVIDER_ROUTING_ENV_VARS = [
11549
- "ANTHROPIC_BASE_URL",
11550
- "ANTHROPIC_BEDROCK_BASE_URL",
11551
- "ANTHROPIC_VERTEX_BASE_URL",
11552
- "CLAUDE_CODE_USE_BEDROCK",
11553
- "CLAUDE_CODE_USE_VERTEX",
11554
- "ANTHROPIC_VERTEX_PROJECT_ID",
11555
- "CLOUD_ML_REGION",
11556
- "AWS_REGION",
11557
- "ANTHROPIC_CUSTOM_HEADERS",
11558
- "ANTHROPIC_API_KEY",
11559
- "ANTHROPIC_AUTH_TOKEN",
11560
- "CLAUDE_CODE_OAUTH_TOKEN",
11561
- ];
11562
- /** Stable identifier for the LLM backend a session's query is created against,
11563
- * used to scope {@link contextWindowCache} per backend. Positional `\0`-join
11564
- * of {@link PROVIDER_ROUTING_ENV_VARS} values, so no segment can masquerade
11565
- * as another and unset vars everywhere yield one stable "default" bucket.
11566
- * Header/credential values can be secrets; the key only ever lives as an
11567
- * in-memory Map key and is never logged or surfaced. Over-keying is the safe
11568
- * side: a var change that didn't really change the backend costs one cache
11569
- * miss (heuristic seed until the next result), while under-keying would serve
11570
- * one backend's window for another's. */
11571
- function providerCacheKeyFor(env) {
11572
- return PROVIDER_ROUTING_ENV_VARS.map((name) => env[name] ?? "").join("\0");
11573
- }
11574
- /** Compose the `contextWindowCache` key from a session's provider key and a
11575
- * model id. `\0`-joined so the model segment can't collide with a provider
11576
- * segment. */
11577
- function contextWindowCacheKey(providerCacheKey, modelId) {
11578
- return `${providerCacheKey}\0${modelId}`;
11579
- }
11580
- function cacheContextWindow(modelKey, window) {
11581
- if (window > 0) {
11582
- contextWindowCache.set(modelKey, window);
11583
- }
11584
- }
11585
- /** The context window to report *right now* for a model, with NO IPC on the
11586
- * critical path: the cached authoritative value if we've learned it (from a
11587
- * prior turn's `result.modelUsage`, this or any session on the same backend),
11588
- * else the text heuristic over the model row's identity strings, else the
11589
- * default. Derives the cache key itself — `modelInfo?.resolvedModel ?? modelId`,
11590
- * the same rule at every seed site — so read keys can't drift from the write
11591
- * site's spelling. `authoritative` reports whether the value came from the
11592
- * cache: an authoritative window can legitimately equal
11593
- * DEFAULT_CONTEXT_WINDOW, so the value alone can't tell the caller. */
11594
- function immediateContextWindow(providerCacheKey, modelId, modelInfo) {
11595
- const cached = contextWindowCache.get(contextWindowCacheKey(providerCacheKey, modelInfo?.resolvedModel ?? modelId));
11596
- if (cached !== undefined)
11597
- return { size: cached, authoritative: true };
11598
- return {
11599
- size: inferContextWindowFromModel(modelId, modelInfo?.resolvedModel, modelInfo?.displayName, modelInfo?.description) ?? DEFAULT_CONTEXT_WINDOW,
11600
- authoritative: false,
11601
- };
11602
- }
11603
- /** Translate the legacy `MAX_THINKING_TOKENS` env var, plus the optional
11604
- * `CLAUDE_CODE_THINKING_DISPLAY` env var, into the SDK's `thinking` option.
11605
- * The `maxThinkingTokens` option it used to feed is deprecated and reduced
11606
- * to on/off on current models, so map the value to explicit thinking config
11607
- * instead: unset → `undefined` (SDK default, adaptive on models that support
11608
- * it) unless a display mode is requested, in which case it becomes explicit
11609
- * `adaptive`; `0` → disabled; a positive integer → a fixed token budget.
11610
- * Anything else is ignored with a warning. `CLAUDE_CODE_THINKING_DISPLAY`
11611
- * must be `summarized` or `omitted`; it has no effect when thinking is
11612
- * disabled. */
11613
- function resolveThinkingConfig(rawTokens, rawDisplay, logger) {
11614
- let display;
11615
- if (rawDisplay !== undefined) {
11616
- if (rawDisplay === "summarized" || rawDisplay === "omitted") {
11617
- display = rawDisplay;
11618
- }
11619
- else {
11620
- logger.error(`Ignoring CLAUDE_CODE_THINKING_DISPLAY: expected 'summarized' or 'omitted', got '${rawDisplay}'.`);
11621
- }
11622
- }
11623
- if (rawTokens === undefined) {
11624
- return display ? { type: "adaptive", display } : undefined;
11625
- }
11626
- const parsed = Number.parseInt(rawTokens, 10);
11627
- if (Number.isNaN(parsed) || parsed < 0) {
11628
- logger.error(`Ignoring MAX_THINKING_TOKENS: expected a non-negative integer, got '${rawTokens}'.`);
11629
- return display ? { type: "adaptive", display } : undefined;
11630
- }
11631
- return parsed === 0
11632
- ? { type: "disabled" }
11633
- : { type: "enabled", budgetTokens: parsed, ...(display && { display }) };
11634
- }
11635
- function parseModelConfig(raw) {
11636
- if (!raw)
11637
- return undefined;
11638
- const parsed = JSON.parse(raw);
11639
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
11640
- throw new Error("CLAUDE_MODEL_CONFIG must be a JSON object");
11641
- }
11642
- const result = {};
11643
- if (parsed.modelOverrides !== undefined)
11644
- result.modelOverrides = parsed.modelOverrides;
11645
- if (parsed.availableModels !== undefined)
11646
- result.availableModels = parsed.availableModels;
11647
- return Object.keys(result).length > 0 ? result : undefined;
11648
- }
11649
- function getMatchingModelUsage(modelUsage, currentModel) {
11650
- let bestKey = null;
11651
- let bestLen = 0;
11652
- for (const key of Object.keys(modelUsage)) {
11653
- const len = commonPrefixLength(key, currentModel);
11654
- if (len > bestLen) {
11655
- bestLen = len;
11656
- bestKey = key;
11657
- }
11658
- }
11659
- if (bestKey) {
11660
- // `bestKey` is the SDK's resolved model id (e.g. "claude-sonnet-5[1m]"),
11661
- // the same spelling as ModelInfo.resolvedModel — the primary key the
11662
- // window is cached under. `currentModel` (the assistant message's
11663
- // `.model`) can be the bare form (e.g. "claude-sonnet-5"); the result
11664
- // handler caches under that spelling too, for seed-time reads that fall
11665
- // back to a bare id (rows without `resolvedModel`).
11666
- return { key: bestKey, usage: modelUsage[bestKey] };
11667
- }
11668
- }
11669
9637
  /**
11670
9638
  * What a `command_lifecycle` "started" frame says started the command: a
11671
9639
  * ScheduleWakeup (dynamic `/loop`) wakeup, with the time it was set for in