@agentclientprotocol/claude-agent-acp 0.102.1-preview.1 → 0.102.1-preview.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -1
- package/dist/acp-agent.d.ts +113 -439
- package/dist/acp-agent.d.ts.map +1 -1
- package/dist/acp-agent.js +362 -2409
- package/dist/acp-subagents.d.ts +1 -2
- package/dist/acp-subagents.d.ts.map +1 -1
- package/dist/auth-methods.d.ts +21 -0
- package/dist/auth-methods.d.ts.map +1 -0
- package/dist/auth-methods.js +68 -0
- package/dist/auth-status-reporter.d.ts +112 -0
- package/dist/auth-status-reporter.d.ts.map +1 -0
- package/dist/auth-status-reporter.js +253 -0
- package/dist/background-work.d.ts +12 -265
- package/dist/background-work.d.ts.map +1 -1
- package/dist/background-work.js +8 -558
- package/dist/client-system-prompt.d.ts +7 -0
- package/dist/client-system-prompt.d.ts.map +1 -1
- package/dist/client-system-prompt.js +24 -0
- package/dist/context-compaction.d.ts +20 -0
- package/dist/context-compaction.d.ts.map +1 -1
- package/dist/context-compaction.js +26 -0
- package/dist/context-window.d.ts +70 -0
- package/dist/context-window.d.ts.map +1 -0
- package/dist/context-window.js +132 -0
- package/dist/diff.d.ts +1 -1
- package/dist/diff.js +1 -1
- package/dist/elicitation.d.ts +66 -1
- package/dist/elicitation.d.ts.map +1 -1
- package/dist/elicitation.js +109 -0
- package/dist/file-change-audit.d.ts +4 -3
- package/dist/file-change-audit.d.ts.map +1 -1
- package/dist/file-change-audit.js +3 -2
- package/dist/mcp-oauth.d.ts +44 -0
- package/dist/mcp-oauth.d.ts.map +1 -0
- package/dist/mcp-oauth.js +142 -0
- package/dist/mcp-servers.d.ts +10 -0
- package/dist/mcp-servers.d.ts.map +1 -0
- package/dist/mcp-servers.js +29 -0
- package/dist/native-subagents.d.ts +18 -8
- package/dist/native-subagents.d.ts.map +1 -1
- package/dist/native-subagents.js +7 -35
- package/dist/permissions/presentation.d.ts +29 -0
- package/dist/permissions/presentation.d.ts.map +1 -1
- package/dist/permissions/presentation.js +38 -11
- package/dist/prompt-suggestions.d.ts +29 -0
- package/dist/prompt-suggestions.d.ts.map +1 -1
- package/dist/prompt-suggestions.js +45 -0
- package/dist/providers.d.ts +139 -0
- package/dist/providers.d.ts.map +1 -0
- package/dist/providers.js +286 -0
- package/dist/remote-control.d.ts +62 -0
- package/dist/remote-control.d.ts.map +1 -0
- package/dist/remote-control.js +78 -0
- package/dist/result-end.d.ts +39 -0
- package/dist/result-end.d.ts.map +1 -0
- package/dist/result-end.js +50 -0
- package/dist/serve.d.ts +7 -2
- package/dist/serve.d.ts.map +1 -1
- package/dist/serve.js +10 -5
- package/dist/session-config-ids.d.ts +1 -0
- package/dist/session-config-ids.d.ts.map +1 -1
- package/dist/session-config-ids.js +1 -0
- package/dist/session-config-options.d.ts +64 -0
- package/dist/session-config-options.d.ts.map +1 -0
- package/dist/session-config-options.js +162 -0
- package/dist/session-effort.d.ts +67 -0
- package/dist/session-effort.d.ts.map +1 -1
- package/dist/session-effort.js +98 -0
- package/dist/session-env.d.ts +22 -0
- package/dist/session-env.d.ts.map +1 -0
- package/dist/session-env.js +66 -0
- package/dist/session-fast-mode.d.ts +83 -0
- package/dist/session-fast-mode.d.ts.map +1 -0
- package/dist/session-fast-mode.js +142 -0
- package/dist/session-index/connection.d.ts +2 -5
- package/dist/session-index/connection.d.ts.map +1 -1
- package/dist/session-index/connection.js +3 -5
- package/dist/session-mode.d.ts +1 -0
- package/dist/session-mode.d.ts.map +1 -1
- package/dist/session-mode.js +1 -1
- package/dist/session-model.d.ts +41 -0
- package/dist/session-model.d.ts.map +1 -1
- package/dist/session-model.js +110 -45
- package/dist/session-notices.d.ts +44 -0
- package/dist/session-notices.d.ts.map +1 -1
- package/dist/session-notices.js +68 -0
- package/dist/session-titles.d.ts +34 -12
- package/dist/session-titles.d.ts.map +1 -1
- package/dist/session-titles.js +7 -6
- package/dist/session-usage.d.ts +125 -0
- package/dist/session-usage.d.ts.map +1 -0
- package/dist/session-usage.js +196 -0
- package/dist/streamed-text.d.ts +33 -0
- package/dist/streamed-text.d.ts.map +1 -0
- package/dist/streamed-text.js +71 -0
- package/dist/subagent-configuration.d.ts +32 -0
- package/dist/subagent-configuration.d.ts.map +1 -0
- package/dist/subagent-configuration.js +70 -0
- package/dist/subagent-replay.d.ts +18 -0
- package/dist/subagent-replay.d.ts.map +1 -1
- package/dist/subagent-replay.js +25 -15
- package/dist/tool-calls/client-capabilities.d.ts +8 -8
- package/dist/tool-calls/client-capabilities.js +4 -4
- package/dist/tool-calls/renderer.d.ts +4 -5
- package/dist/tool-calls/renderer.d.ts.map +1 -1
- package/dist/tool-calls/renderer.js +4 -5
- package/dist/turn-events.d.ts +6 -46
- package/dist/turn-events.d.ts.map +1 -1
- package/dist/v2/agent.d.ts +7 -11
- package/dist/v2/agent.d.ts.map +1 -1
- package/dist/v2/agent.js +751 -331
- package/dist/v2/air.d.ts +33 -0
- package/dist/v2/air.d.ts.map +1 -0
- package/dist/v2/air.js +29 -0
- package/dist/v2/auth.d.ts +97 -0
- package/dist/v2/auth.d.ts.map +1 -0
- package/dist/v2/auth.js +216 -0
- package/dist/v2/background.d.ts +27 -16
- package/dist/v2/background.d.ts.map +1 -1
- package/dist/v2/background.js +4 -32
- package/dist/v2/child-config.d.ts +55 -0
- package/dist/v2/child-config.d.ts.map +1 -0
- package/dist/v2/child-config.js +92 -0
- package/dist/v2/clear-context.d.ts +94 -0
- package/dist/v2/clear-context.d.ts.map +1 -0
- package/dist/v2/clear-context.js +176 -0
- package/dist/v2/commands.d.ts +46 -0
- package/dist/v2/commands.d.ts.map +1 -0
- package/dist/v2/commands.js +54 -0
- package/dist/v2/config.d.ts +187 -0
- package/dist/v2/config.d.ts.map +1 -0
- package/dist/v2/config.js +494 -0
- package/dist/v2/elicitation.d.ts +93 -0
- package/dist/v2/elicitation.d.ts.map +1 -0
- package/dist/v2/elicitation.js +160 -0
- package/dist/v2/file-changes.d.ts +61 -0
- package/dist/v2/file-changes.d.ts.map +1 -0
- package/dist/v2/file-changes.js +108 -0
- package/dist/v2/file-preview.d.ts +18 -0
- package/dist/v2/file-preview.d.ts.map +1 -0
- package/dist/v2/file-preview.js +29 -0
- package/dist/v2/initialize.d.ts +10 -24
- package/dist/v2/initialize.d.ts.map +1 -1
- package/dist/v2/initialize.js +4 -111
- package/dist/v2/outcome.d.ts +81 -0
- package/dist/v2/outcome.d.ts.map +1 -0
- package/dist/v2/outcome.js +165 -0
- package/dist/v2/permissions.d.ts +92 -0
- package/dist/v2/permissions.d.ts.map +1 -0
- package/dist/v2/permissions.js +162 -0
- package/dist/v2/prompt.d.ts +2 -42
- package/dist/v2/prompt.d.ts.map +1 -1
- package/dist/v2/prompt.js +2 -119
- package/dist/v2/remote-control.d.ts +41 -0
- package/dist/v2/remote-control.d.ts.map +1 -0
- package/dist/v2/remote-control.js +63 -0
- package/dist/v2/reports.d.ts +198 -0
- package/dist/v2/reports.d.ts.map +1 -0
- package/dist/v2/reports.js +487 -0
- package/dist/v2/restarts.d.ts +128 -0
- package/dist/v2/restarts.d.ts.map +1 -0
- package/dist/v2/restarts.js +348 -0
- package/dist/v2/session-requests.d.ts +20 -0
- package/dist/v2/session-requests.d.ts.map +1 -0
- package/dist/v2/session-requests.js +108 -0
- package/dist/v2/session-update.d.ts +2 -13
- package/dist/v2/session-update.d.ts.map +1 -1
- package/dist/v2/session-update.js +2 -22
- package/dist/v2/session.d.ts +340 -41
- package/dist/v2/session.d.ts.map +1 -1
- package/dist/v2/session.js +1223 -141
- package/dist/v2/setup.d.ts +49 -0
- package/dist/v2/setup.d.ts.map +1 -0
- package/dist/v2/setup.js +62 -0
- package/dist/v2/stopped-work.d.ts +123 -0
- package/dist/v2/stopped-work.d.ts.map +1 -0
- package/dist/v2/stopped-work.js +210 -0
- package/dist/v2/stream.d.ts +228 -0
- package/dist/v2/stream.d.ts.map +1 -0
- package/dist/v2/stream.js +506 -0
- package/dist/v2/subagent-replay.d.ts +115 -0
- package/dist/v2/subagent-replay.d.ts.map +1 -0
- package/dist/v2/subagent-replay.js +479 -0
- package/dist/v2/subscription-guard.d.ts +60 -0
- package/dist/v2/subscription-guard.d.ts.map +1 -0
- package/dist/v2/subscription-guard.js +84 -0
- package/dist/v2/tasks.d.ts +492 -0
- package/dist/v2/tasks.d.ts.map +1 -0
- package/dist/v2/tasks.js +1728 -0
- package/dist/v2/terminal.d.ts.map +1 -1
- package/dist/v2/terminal.js +6 -1
- package/dist/v2/tool-call.d.ts +3 -2
- package/dist/v2/tool-call.d.ts.map +1 -1
- package/dist/v2/update-translator.d.ts +36 -0
- package/dist/v2/update-translator.d.ts.map +1 -0
- package/dist/v2/update-translator.js +80 -0
- package/dist/workflow-progress.d.ts +23 -0
- package/dist/workflow-progress.d.ts.map +1 -1
- package/dist/workflow-progress.js +31 -8
- package/package.json +1 -1
- package/dist/v2/permission.d.ts +0 -28
- package/dist/v2/permission.d.ts.map +0 -1
- 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 {
|
|
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
5
|
import { checklistPlanUpdate, resetPlanUpdates, todoWritePlanUpdate, } from "./plans.js";
|
|
6
|
-
import {
|
|
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,
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
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 {
|
|
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,
|
|
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,
|
|
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,
|
|
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
|
|
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,
|
|
61
|
-
import {
|
|
62
|
-
import {
|
|
63
|
-
import { createUltracodeConfigOption, readUltracodeSettings,
|
|
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
|
-
|
|
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
|
|
340
|
-
* or a model cycle that Claude Code started on its own
|
|
341
|
-
* runs at a time, so a
|
|
342
|
-
|
|
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
|
|
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
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
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
|
|
1017
|
-
*
|
|
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
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
}
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
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
|
-
/**
|
|
1145
|
-
* `authenticate`/`logout`.
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
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
|
|
1201
|
-
*
|
|
1202
|
-
*
|
|
1203
|
-
*
|
|
1204
|
-
*
|
|
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
|
|
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 (
|
|
1222
|
-
clientSupportsAirCapability(this.clientCapabilities, AIR_BACKGROUND_SUBAGENTS_CAPABILITY));
|
|
984
|
+
return clientSupportsAirCapability(this.clientCapabilities, AIR_BACKGROUND_SUBAGENTS_CAPABILITY);
|
|
1223
985
|
}
|
|
1224
|
-
constructor(client, logger
|
|
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
|
-
|
|
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.
|
|
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
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
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],
|
|
@@ -1659,221 +1345,24 @@ export class ClaudeAcpAgent {
|
|
|
1659
1345
|
}
|
|
1660
1346
|
/**
|
|
1661
1347
|
* `authenticate` — the legacy gateway methods store a provider override that
|
|
1662
|
-
* every later session reads
|
|
1663
|
-
*
|
|
1664
|
-
* `TypeError` deep in session creation, or installs an empty base URL that
|
|
1665
|
-
* silently turns the `--hide-claude-auth` subscription guard off.
|
|
1666
|
-
*
|
|
1667
|
-
* A call that carries no gateway payload at all keeps its historical
|
|
1668
|
-
* meaning: it installs no override and succeeds. That has always been a
|
|
1669
|
-
* no-op here, and a client that probes the method this way must keep
|
|
1670
|
-
* working. Only a payload that IS present has to be usable.
|
|
1348
|
+
* every later session reads, once {@link validatedGatewayAuthRequest} accepts
|
|
1349
|
+
* its payload.
|
|
1671
1350
|
*/
|
|
1672
1351
|
async authenticate(_params) {
|
|
1673
|
-
if (_params.methodId
|
|
1674
|
-
|
|
1675
|
-
if (gateway !== undefined && gateway !== null) {
|
|
1676
|
-
if (typeof gateway !== "object" || !isValidBaseUrl(gateway.baseUrl)) {
|
|
1677
|
-
throw RequestError.invalidParams({ baseUrl: gateway.baseUrl }, "`_meta.gateway.baseUrl` must be a non-empty absolute http(s) URL.");
|
|
1678
|
-
}
|
|
1679
|
-
if (gateway.headers !== undefined && typeof gateway.headers !== "object") {
|
|
1680
|
-
throw RequestError.invalidParams(undefined, "`_meta.gateway.headers` must be an object of header names to values.");
|
|
1681
|
-
}
|
|
1682
|
-
}
|
|
1683
|
-
this.gatewayAuthRequest = _params;
|
|
1352
|
+
if (isGatewayAuthMethod(_params.methodId)) {
|
|
1353
|
+
this.gatewayAuthRequest = validatedGatewayAuthRequest(_params);
|
|
1684
1354
|
// The gateway holds the credentials from here on, so it replaces
|
|
1685
1355
|
// whatever the CLI store reported. Bumping the epoch discards any probe
|
|
1686
1356
|
// that started before this login: its answer is now stale.
|
|
1687
|
-
this.
|
|
1688
|
-
this.
|
|
1357
|
+
this.authStatus.changed();
|
|
1358
|
+
this.authStatus.set(gatewayAuthStatus(gatewayRequestToProviderConfig(this.gatewayAuthRequest)?.baseUrl));
|
|
1689
1359
|
return;
|
|
1690
1360
|
}
|
|
1691
1361
|
throw RequestError.invalidParams({ methodId: _params.methodId }, `Unsupported authentication method: ${_params.methodId}`);
|
|
1692
1362
|
}
|
|
1693
|
-
/**
|
|
1694
|
-
* Stores `next` and pushes it to the client.
|
|
1695
|
-
*
|
|
1696
|
-
* A push goes out only when the payload changed. The identity is read on many
|
|
1697
|
-
* occasions — each session create, each guarded turn, the start of each user
|
|
1698
|
-
* prompt — and almost all of them see the same login. Clients replace their
|
|
1699
|
-
* whole state on each update and tolerate duplicates, so a repeat is
|
|
1700
|
-
* harmless, but it is also pure noise; {@link sameAuthStatus} drops it.
|
|
1701
|
-
*
|
|
1702
|
-
* What the agent owes is truth — a stale or uninformative source must not
|
|
1703
|
-
* reach here at all (see the epoch check in the probe and the guards at
|
|
1704
|
-
* session create).
|
|
1705
|
-
*/
|
|
1363
|
+
/** Stores `next` and pushes it to the client when it changed (see {@link AuthStatusReporter.set}). */
|
|
1706
1364
|
setAuthStatus(next) {
|
|
1707
|
-
|
|
1708
|
-
return;
|
|
1709
|
-
}
|
|
1710
|
-
if (sameAuthStatus(this.currentAuthStatus, next)) {
|
|
1711
|
-
return;
|
|
1712
|
-
}
|
|
1713
|
-
this.currentAuthStatus = next;
|
|
1714
|
-
// ACP notifications get no reply, and clients that do not know the method
|
|
1715
|
-
// drop it silently — send unconditionally and never fail a caller on it.
|
|
1716
|
-
void Promise.resolve()
|
|
1717
|
-
.then(() => this.client.extNotification(AUTH_STATUS_UPDATE_METHOD, { authStatus: next }))
|
|
1718
|
-
.catch((error) => {
|
|
1719
|
-
this.logger.error("Failed to send _auth/status_update:", error);
|
|
1720
|
-
});
|
|
1721
|
-
}
|
|
1722
|
-
/**
|
|
1723
|
-
* Report the identity behind a session's `AccountInfo`.
|
|
1724
|
-
*
|
|
1725
|
-
* `AccountInfo` is richer than the CLI probe (it is what the live query
|
|
1726
|
-
* actually authenticates with). Called before the `--hide-claude-auth` guard
|
|
1727
|
-
* may refuse the session or the turn: that flag blocks the *use* of a
|
|
1728
|
-
* subscription, it does not make the state secret, and a refusal is when the
|
|
1729
|
-
* client most needs to know the account it was refused for.
|
|
1730
|
-
*
|
|
1731
|
-
* Two cases skip it:
|
|
1732
|
-
*
|
|
1733
|
-
* - ACP gateway *authentication* (`gatewayAuthRequest`): the gateway, not
|
|
1734
|
-
* this account, is the agent-owned identity — already reported as
|
|
1735
|
-
* `kind: "gateway"` by `authenticate`.
|
|
1736
|
-
* - A client-driven provider override (`providers/set`): the session then
|
|
1737
|
-
* routes through the client's endpoint and `AccountInfo` describes that
|
|
1738
|
-
* route (e.g. `apiProvider: "gateway"`), which is NOT agent-owned state.
|
|
1739
|
-
* `authStatus` reports the agent's own login only, so the CLI probe —
|
|
1740
|
-
* which reads the credential store the override never touches — stays
|
|
1741
|
-
* authoritative.
|
|
1742
|
-
*
|
|
1743
|
-
* An account with no identity signal (e.g. `{apiProvider: "firstParty"}`
|
|
1744
|
-
* under an apiKeyHelper) means "nothing to add", not "logged out" — keep
|
|
1745
|
-
* what the CLI probe already established instead of overwriting it.
|
|
1746
|
-
*/
|
|
1747
|
-
useAuthStatusSettings(manager, settingsOverride, launchEnv) {
|
|
1748
|
-
const helper = manager.getApiKeyHelper(settingsOverride);
|
|
1749
|
-
const changed = manager.getCwd() !== (this.authStatusSettings?.manager.getCwd() ?? process.cwd()) ||
|
|
1750
|
-
helper !== this.authStatusHelper ||
|
|
1751
|
-
JSON.stringify(launchEnv) !== JSON.stringify(this.authStatusSettings?.env);
|
|
1752
|
-
this.authStatusSettings = { manager, override: settingsOverride, env: launchEnv };
|
|
1753
|
-
this.authStatusHelper = helper;
|
|
1754
|
-
if (changed) {
|
|
1755
|
-
// The epoch bump discards any probe that read the old context, and the
|
|
1756
|
-
// session account may carry no identity signal (an apiKeyHelper), so
|
|
1757
|
-
// only a probe in the new context can classify it.
|
|
1758
|
-
this.authEpoch += 1;
|
|
1759
|
-
void this.probeCliAuthStatus({ fresh: true });
|
|
1760
|
-
}
|
|
1761
|
-
}
|
|
1762
|
-
publishSessionAccountIdentity(account, apiKeyHelper) {
|
|
1763
|
-
if (this.providerConfig) {
|
|
1764
|
-
if (!this.loggedOverriddenAccount) {
|
|
1765
|
-
this.loggedOverriddenAccount = true;
|
|
1766
|
-
this.logger.log("[authStatus] client provider override active; keeping agent-owned probe state");
|
|
1767
|
-
}
|
|
1768
|
-
return;
|
|
1769
|
-
}
|
|
1770
|
-
if (this.gatewayAuthRequest) {
|
|
1771
|
-
return;
|
|
1772
|
-
}
|
|
1773
|
-
const fromSession = fromAccountInfo(account, apiKeyHelper);
|
|
1774
|
-
if (fromSession) {
|
|
1775
|
-
this.setAuthStatus(fromSession);
|
|
1776
|
-
}
|
|
1777
|
-
else if (!this.loggedUninformativeAccount) {
|
|
1778
|
-
this.loggedUninformativeAccount = true;
|
|
1779
|
-
this.logger.log("[authStatus] session account carries no identity signal; keeping probe");
|
|
1780
|
-
}
|
|
1781
|
-
}
|
|
1782
|
-
/** Shares one in-flight `claude auth status --json` run between callers. The
|
|
1783
|
-
* promise is released once settled so a later call re-probes instead of
|
|
1784
|
-
* replaying a stale verdict. `fresh` forces a new run even when one is in
|
|
1785
|
-
* flight — `logout` needs a read that started after the credentials were
|
|
1786
|
-
* cleared. */
|
|
1787
|
-
probeCliAuthStatus(options) {
|
|
1788
|
-
if (!options?.fresh && this.cliAuthProbe) {
|
|
1789
|
-
return this.cliAuthProbe;
|
|
1790
|
-
}
|
|
1791
|
-
const probe = this.runCliAuthProbe();
|
|
1792
|
-
this.cliAuthProbe = probe;
|
|
1793
|
-
void probe.finally(() => {
|
|
1794
|
-
if (this.cliAuthProbe === probe) {
|
|
1795
|
-
this.cliAuthProbe = null;
|
|
1796
|
-
}
|
|
1797
|
-
});
|
|
1798
|
-
return probe;
|
|
1799
|
-
}
|
|
1800
|
-
/** Never rejects: an unavailable CLI means "not reported", not an error. */
|
|
1801
|
-
async runCliAuthProbe() {
|
|
1802
|
-
// Monotonicity: a read that started before the connection's latest
|
|
1803
|
-
// auth-affecting event describes a world that no longer exists. Remember
|
|
1804
|
-
// which one this read belongs to and drop the answer if it moved on.
|
|
1805
|
-
const epoch = this.authEpoch;
|
|
1806
|
-
const context = this.authStatusSettings;
|
|
1807
|
-
const apiKeyHelper = context?.manager.getApiKeyHelper(context.override);
|
|
1808
|
-
// ACP gateway auth bypasses the CLI credential store entirely, so the
|
|
1809
|
-
// probe would report an identity that is not the one being used. A mere
|
|
1810
|
-
// client provider override (`providers/set`) does NOT skip the probe: it
|
|
1811
|
-
// reroutes traffic without touching the credential store, and the store is
|
|
1812
|
-
// exactly the agent-owned login `authStatus` reports.
|
|
1813
|
-
if (this.gatewayAuthRequest) {
|
|
1814
|
-
return this.currentAuthStatus;
|
|
1815
|
-
}
|
|
1816
|
-
let stdout;
|
|
1817
|
-
try {
|
|
1818
|
-
const cliPath = await claudeCliPath();
|
|
1819
|
-
const args = ["auth", "status", "--json"];
|
|
1820
|
-
// `--settings` is a global CLI option: after the `auth status` subcommand the CLI rejects
|
|
1821
|
-
// it with "unknown option '--settings'", so it has to come first.
|
|
1822
|
-
if (context?.override)
|
|
1823
|
-
args.unshift("--settings", JSON.stringify(context.override));
|
|
1824
|
-
({ stdout } = await execFileAsync(cliPath, args, {
|
|
1825
|
-
timeout: AUTH_STATUS_PROBE_TIMEOUT_MS,
|
|
1826
|
-
cwd: context?.manager.getCwd() ?? process.cwd(),
|
|
1827
|
-
env: context?.env ? { ...process.env, ...context.env } : process.env,
|
|
1828
|
-
}));
|
|
1829
|
-
}
|
|
1830
|
-
catch (error) {
|
|
1831
|
-
const failed = error;
|
|
1832
|
-
// Node killed the child on the timeout. Whatever it printed so far is a
|
|
1833
|
-
// truncated fragment, never valid JSON: report nothing and keep the last
|
|
1834
|
-
// known state, so nothing regresses and no push goes out.
|
|
1835
|
-
if (failed?.killed === true && failed.signal) {
|
|
1836
|
-
if (!this.loggedProbeTimeout) {
|
|
1837
|
-
this.loggedProbeTimeout = true;
|
|
1838
|
-
this.logger.error("claude auth status did not answer within 5 s; the identity is not refreshed");
|
|
1839
|
-
}
|
|
1840
|
-
return this.currentAuthStatus;
|
|
1841
|
-
}
|
|
1842
|
-
// The logged-out case exits 1 while still printing valid JSON, so the
|
|
1843
|
-
// stdout of a failed exec is parsed just like a successful one.
|
|
1844
|
-
if (typeof failed?.stdout !== "string" || failed.stdout.trim().length === 0) {
|
|
1845
|
-
this.logger.error("claude auth status failed:", error instanceof Error ? error.message : String(error));
|
|
1846
|
-
return undefined;
|
|
1847
|
-
}
|
|
1848
|
-
stdout = failed.stdout;
|
|
1849
|
-
}
|
|
1850
|
-
let status = fromCliStatus(stdout, apiKeyHelper);
|
|
1851
|
-
if (!context && status?.kind === "api_key" && status.detail === "API key helper") {
|
|
1852
|
-
try {
|
|
1853
|
-
const resolved = await resolveSettings({ cwd: process.cwd() });
|
|
1854
|
-
status = fromCliStatus(stdout, filterEscalatingDefaultMode(resolved).apiKeyHelper);
|
|
1855
|
-
}
|
|
1856
|
-
catch {
|
|
1857
|
-
this.logger.error("Could not resolve auth source settings");
|
|
1858
|
-
}
|
|
1859
|
-
}
|
|
1860
|
-
if (!status) {
|
|
1861
|
-
this.logger.error("claude auth status returned unparseable output");
|
|
1862
|
-
return undefined;
|
|
1863
|
-
}
|
|
1864
|
-
if (epoch !== this.authEpoch) {
|
|
1865
|
-
// An `authenticate` or `logout` landed while this probe was running; the
|
|
1866
|
-
// newer state wins and this answer is discarded, never published.
|
|
1867
|
-
this.logger.log("[authStatus] discarding a probe that predates the latest auth change");
|
|
1868
|
-
return this.currentAuthStatus;
|
|
1869
|
-
}
|
|
1870
|
-
// The CLI probe can be poorer than the session `AccountInfo` for the very
|
|
1871
|
-
// same login (no organization, say). Keep those extra fields rather than
|
|
1872
|
-
// regressing the payload; a different identity replaces it wholesale.
|
|
1873
|
-
const merged = mergeAuthStatus(this.currentAuthStatus, status);
|
|
1874
|
-
this.setAuthStatus(merged);
|
|
1875
|
-
this.markSessionsWhoseAccountKindChanged(status.kind);
|
|
1876
|
-
return merged;
|
|
1365
|
+
this.authStatus.set(next);
|
|
1877
1366
|
}
|
|
1878
1367
|
/**
|
|
1879
1368
|
* Feed the completed probe to the `--hide-claude-auth` guard.
|
|
@@ -1910,51 +1399,18 @@ export class ClaudeAcpAgent {
|
|
|
1910
1399
|
}
|
|
1911
1400
|
}
|
|
1912
1401
|
async unstable_listProviders(_params) {
|
|
1913
|
-
const config = this.providerConfig ?? this.
|
|
1914
|
-
this.logger.log(`[providers/list] apiType=${config.apiType} baseUrl=${config.baseUrl} overridden=${this.providerConfig !== undefined}`);
|
|
1915
|
-
|
|
1916
|
-
providerId: PROVIDER_ID,
|
|
1917
|
-
supported: SUPPORTED_PROTOCOLS,
|
|
1918
|
-
required: false,
|
|
1919
|
-
current: { apiType: config.apiType, baseUrl: config.baseUrl },
|
|
1920
|
-
};
|
|
1921
|
-
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);
|
|
1922
1405
|
}
|
|
1923
1406
|
/**
|
|
1924
|
-
* `providers/set` — replace the full configuration for the `main` provider
|
|
1925
|
-
*
|
|
1926
|
-
*
|
|
1927
|
-
* 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.
|
|
1928
1410
|
*/
|
|
1929
1411
|
async unstable_setProvider(params) {
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
}
|
|
1933
|
-
if (!SUPPORTED_PROTOCOLS.includes(params.apiType)) {
|
|
1934
|
-
throw RequestError.invalidParams({ apiType: params.apiType, supported: SUPPORTED_PROTOCOLS }, `Unsupported apiType "${params.apiType}" for provider "${PROVIDER_ID}".`);
|
|
1935
|
-
}
|
|
1936
|
-
if (!isValidBaseUrl(params.baseUrl)) {
|
|
1937
|
-
throw RequestError.invalidParams({ baseUrl: params.baseUrl }, "baseUrl must be a non-empty absolute http(s) URL.");
|
|
1938
|
-
}
|
|
1939
|
-
const config = {
|
|
1940
|
-
apiType: params.apiType,
|
|
1941
|
-
baseUrl: params.baseUrl,
|
|
1942
|
-
headers: params.headers ?? {},
|
|
1943
|
-
};
|
|
1944
|
-
// Vertex requires project + region, which the standard payload cannot
|
|
1945
|
-
// carry, so they arrive via `_meta.claudeCode.vertex`.
|
|
1946
|
-
if (params.apiType === "vertex") {
|
|
1947
|
-
const vertex = params._meta?.claudeCode?.vertex;
|
|
1948
|
-
if (!vertex ||
|
|
1949
|
-
typeof vertex.projectId !== "string" ||
|
|
1950
|
-
vertex.projectId.trim() === "" ||
|
|
1951
|
-
typeof vertex.region !== "string" ||
|
|
1952
|
-
vertex.region.trim() === "") {
|
|
1953
|
-
throw RequestError.invalidParams(undefined, "vertex apiType requires non-empty `_meta.claudeCode.vertex.projectId` and `_meta.claudeCode.vertex.region`.");
|
|
1954
|
-
}
|
|
1955
|
-
config.vertex = { projectId: vertex.projectId, region: vertex.region };
|
|
1956
|
-
}
|
|
1957
|
-
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}`);
|
|
1958
1414
|
await this.enqueueProviderUpdate(config);
|
|
1959
1415
|
return {};
|
|
1960
1416
|
}
|
|
@@ -1970,70 +1426,9 @@ export class ClaudeAcpAgent {
|
|
|
1970
1426
|
// Unknown provider: idempotent success.
|
|
1971
1427
|
return {};
|
|
1972
1428
|
}
|
|
1973
|
-
/**
|
|
1974
|
-
* The model ids the gateway in `config` lists, read before `providers/set`
|
|
1975
|
-
* returns so the sessions it recreates already offer only those, and for
|
|
1976
|
-
* `bedrock` the region prefix picked from them. Setting the same gateway
|
|
1977
|
-
* again reuses the previous listing. `vertex` gateways are not listed.
|
|
1978
|
-
* Throws a {@link GatewayListingError} when the listing fails.
|
|
1979
|
-
*/
|
|
1980
|
-
async listProviderModels(config) {
|
|
1981
|
-
// Reuse needs the very same headers, so a rotated token lists again, and a
|
|
1982
|
-
// failed listing then fails that `providers/set`. Deliberate: AIR keeps its
|
|
1983
|
-
// proxy key for the IDE's lifetime and does not rotate it.
|
|
1984
|
-
const current = this.providerConfig;
|
|
1985
|
-
if (current?.listedModels &&
|
|
1986
|
-
current.apiType === config.apiType &&
|
|
1987
|
-
current.baseUrl === config.baseUrl &&
|
|
1988
|
-
sameHeaders(current.headers, config.headers)) {
|
|
1989
|
-
return {
|
|
1990
|
-
listedModels: current.listedModels,
|
|
1991
|
-
bedrockRegionPrefix: current.bedrockRegionPrefix,
|
|
1992
|
-
};
|
|
1993
|
-
}
|
|
1994
|
-
if (config.apiType === "anthropic") {
|
|
1995
|
-
return { listedModels: await listGatewayModels(config.baseUrl, config.headers, this.logger) };
|
|
1996
|
-
}
|
|
1997
|
-
if (config.apiType === "bedrock") {
|
|
1998
|
-
const modelIds = await listBedrockModels(config.baseUrl, config.headers, this.logger);
|
|
1999
|
-
if (!modelIds)
|
|
2000
|
-
return {};
|
|
2001
|
-
const region = selectBedrockRegion(modelIds);
|
|
2002
|
-
if (region.modelIds.length < modelIds.length) {
|
|
2003
|
-
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`);
|
|
2004
|
-
}
|
|
2005
|
-
return { listedModels: region.modelIds, bedrockRegionPrefix: region.regionPrefix };
|
|
2006
|
-
}
|
|
2007
|
-
return {};
|
|
2008
|
-
}
|
|
2009
1429
|
resolveProviderConfig() {
|
|
2010
1430
|
return this.providerConfig ?? gatewayRequestToProviderConfig(this.gatewayAuthRequest);
|
|
2011
1431
|
}
|
|
2012
|
-
defaultProviderConfig() {
|
|
2013
|
-
const gatewayConfig = gatewayRequestToProviderConfig(this.gatewayAuthRequest);
|
|
2014
|
-
if (gatewayConfig) {
|
|
2015
|
-
return gatewayConfig;
|
|
2016
|
-
}
|
|
2017
|
-
if (process.env.CLAUDE_CODE_USE_BEDROCK) {
|
|
2018
|
-
return {
|
|
2019
|
-
apiType: "bedrock",
|
|
2020
|
-
baseUrl: process.env.ANTHROPIC_BEDROCK_BASE_URL ?? "https://bedrock-runtime.amazonaws.com",
|
|
2021
|
-
headers: {},
|
|
2022
|
-
};
|
|
2023
|
-
}
|
|
2024
|
-
if (process.env.CLAUDE_CODE_USE_VERTEX) {
|
|
2025
|
-
return {
|
|
2026
|
-
apiType: "vertex",
|
|
2027
|
-
baseUrl: process.env.ANTHROPIC_VERTEX_BASE_URL ?? DEFAULT_VERTEX_BASE_URL,
|
|
2028
|
-
headers: {},
|
|
2029
|
-
};
|
|
2030
|
-
}
|
|
2031
|
-
return {
|
|
2032
|
-
apiType: "anthropic",
|
|
2033
|
-
baseUrl: process.env.ANTHROPIC_BASE_URL ?? DEFAULT_ANTHROPIC_BASE_URL,
|
|
2034
|
-
headers: {},
|
|
2035
|
-
};
|
|
2036
|
-
}
|
|
2037
1432
|
async logout(_params) {
|
|
2038
1433
|
// Clear in-memory gateway credentials supplied via `authenticate` and any
|
|
2039
1434
|
// provider routing set via `providers/set`. Neither touches the on-disk
|
|
@@ -2046,25 +1441,16 @@ export class ClaudeAcpAgent {
|
|
|
2046
1441
|
this.providerConfig = undefined;
|
|
2047
1442
|
// Any probe already running read the pre-logout world; the bump makes its
|
|
2048
1443
|
// answer unpublishable so it cannot resurrect the identity being cleared.
|
|
2049
|
-
this.
|
|
1444
|
+
this.authStatus.changed();
|
|
2050
1445
|
// Learned context windows are per-account state too: 1M-context
|
|
2051
1446
|
// entitlement is gated per org/tier, and an OAuth re-login is invisible to
|
|
2052
1447
|
// the env-derived provider cache key, so windows learned under the old
|
|
2053
1448
|
// login must not seed sessions under the next. Worst case of clearing is
|
|
2054
1449
|
// re-learning on each model's next turn.
|
|
2055
|
-
|
|
2056
|
-
//
|
|
2057
|
-
// CLI's store (keychain or config dir), which only the binary can clear.
|
|
2058
|
-
// `claude auth logout` is non-interactive and idempotent.
|
|
1450
|
+
clearContextWindowCache();
|
|
1451
|
+
// The Claude and Console logins live in the CLI's store.
|
|
2059
1452
|
try {
|
|
2060
|
-
|
|
2061
|
-
await execFileAsync(cliPath, ["auth", "logout"]);
|
|
2062
|
-
}
|
|
2063
|
-
catch (error) {
|
|
2064
|
-
const stderr = typeof error === "object" && error && "stderr" in error
|
|
2065
|
-
? String(error.stderr).trim()
|
|
2066
|
-
: undefined;
|
|
2067
|
-
throw RequestError.internalError({ stderr: stderr || undefined }, `claude auth logout failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
1453
|
+
await cliLogout();
|
|
2068
1454
|
}
|
|
2069
1455
|
finally {
|
|
2070
1456
|
// The cleared provider or gateway routing is baked into the env of every
|
|
@@ -2082,8 +1468,8 @@ export class ClaudeAcpAgent {
|
|
|
2082
1468
|
// credentials were cleared, so it never joins a probe that is already in
|
|
2083
1469
|
// flight. If it can't be read, the logout still happened — drop the
|
|
2084
1470
|
// now-stale identity instead of reporting it further.
|
|
2085
|
-
if (!(await this.
|
|
2086
|
-
this.
|
|
1471
|
+
if (!(await this.authStatus.probe({ fresh: true }))) {
|
|
1472
|
+
this.authStatus.set(notLoggedInAuthStatus());
|
|
2087
1473
|
}
|
|
2088
1474
|
}
|
|
2089
1475
|
/** The structured replacement for a prompt that is exactly `/usage` or a
|
|
@@ -2133,8 +1519,7 @@ export class ClaudeAcpAgent {
|
|
|
2133
1519
|
*
|
|
2134
1520
|
* A content block that the agent does not advertise, such as `audio`, fails
|
|
2135
1521
|
* the request with invalid params (-32602) before anything is queued:
|
|
2136
|
-
* `promptToClaude` would drop it.
|
|
2137
|
-
* `v1PromptRequest`, which rejects these blocks itself.
|
|
1522
|
+
* `promptToClaude` would drop it.
|
|
2138
1523
|
*/
|
|
2139
1524
|
async prompt(params, origin = "client") {
|
|
2140
1525
|
for (const block of params.prompt) {
|
|
@@ -2176,8 +1561,8 @@ export class ClaudeAcpAgent {
|
|
|
2176
1561
|
// that finds the new credential must not be the one the refusal skipped.
|
|
2177
1562
|
// The guard itself consumes the result only at the next turn boundary (see
|
|
2178
1563
|
// `markSessionsWhoseAccountKindChanged`).
|
|
2179
|
-
this.
|
|
2180
|
-
void this.
|
|
1564
|
+
this.authStatus.useSettings(session.settingsManager, session.effortSettingsOverride, session.creationParams?._meta?.claudeCode?.options?.env);
|
|
1565
|
+
void this.authStatus.probe();
|
|
2181
1566
|
const signOutRespawn = this.respawnSignedOutSession(params.sessionId, session);
|
|
2182
1567
|
if (signOutRespawn) {
|
|
2183
1568
|
await signOutRespawn;
|
|
@@ -2195,13 +1580,15 @@ export class ClaudeAcpAgent {
|
|
|
2195
1580
|
if (session.queryClosed) {
|
|
2196
1581
|
throw RequestError.internalError(undefined, SESSION_ENDED_MESSAGE);
|
|
2197
1582
|
}
|
|
2198
|
-
|
|
2199
|
-
|
|
2200
|
-
|
|
2201
|
-
|
|
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) {
|
|
2202
1589
|
// The reply bypasses the turn queue, so it would land inside the output of
|
|
2203
|
-
// a turn that is still running
|
|
2204
|
-
//
|
|
1590
|
+
// a turn that is still running. Refuse instead of interleaving.
|
|
1591
|
+
// `foregroundWork` also covers
|
|
2205
1592
|
// a cycle that Claude Code started on its own, such as its follow-up
|
|
2206
1593
|
// after a background subagent finished, which is not in `turnQueue`.
|
|
2207
1594
|
if (this.claudeIsWorking(params.sessionId, session)) {
|
|
@@ -2215,13 +1602,12 @@ export class ClaudeAcpAgent {
|
|
|
2215
1602
|
// those to reach this client, and a command that answers without a turn
|
|
2216
1603
|
// would otherwise leave the stream unread until the next prompt.
|
|
2217
1604
|
this.ensureConsumer(session, params.sessionId);
|
|
2218
|
-
// Answered by the adapter without a model turn
|
|
2219
|
-
// `ended` without a prior `inserted` as a refused prompt.
|
|
1605
|
+
// Answered by the adapter without a model turn.
|
|
2220
1606
|
events.inserted(randomUUID());
|
|
2221
1607
|
// The request goes over the network. Until it and its reply are done,
|
|
2222
1608
|
// `remoteControlCommand` holds back the prompts that follow, which would
|
|
2223
1609
|
// otherwise start a turn that the reply lands in.
|
|
2224
|
-
const command = this.runRemoteControlCommand(params.sessionId,
|
|
1610
|
+
const command = this.runRemoteControlCommand(params.sessionId, remoteControl);
|
|
2225
1611
|
session.remoteControlCommand = command;
|
|
2226
1612
|
try {
|
|
2227
1613
|
await command;
|
|
@@ -2261,12 +1647,9 @@ export class ClaudeAcpAgent {
|
|
|
2261
1647
|
// the usage limit) from leaving the stale prediction in the composer. A
|
|
2262
1648
|
// session that holds no prediction needs no clear, and the prompt path
|
|
2263
1649
|
// then keeps the ordering it has without this feature.
|
|
2264
|
-
|
|
2265
|
-
|
|
2266
|
-
|
|
2267
|
-
else {
|
|
2268
|
-
session.promptSuggestionExpected = false;
|
|
2269
|
-
}
|
|
1650
|
+
const cleared = session.promptSuggestions?.clear();
|
|
1651
|
+
if (cleared)
|
|
1652
|
+
await this.publishPromptSuggestion(params.sessionId, cleared);
|
|
2270
1653
|
}
|
|
2271
1654
|
// A `/remote-control` command still in flight answers into the session's
|
|
2272
1655
|
// output; wait for its reply before this prompt's turn can begin. Nothing
|
|
@@ -2275,8 +1658,8 @@ export class ClaudeAcpAgent {
|
|
|
2275
1658
|
if (session.remoteControlCommand)
|
|
2276
1659
|
await session.remoteControlCommand.catch(() => { });
|
|
2277
1660
|
// A `session/close` during the awaits above tore the session down, and
|
|
2278
|
-
// its consumer is gone, so the prompt would never be inserted. End it
|
|
2279
|
-
// the close ends a queued turn
|
|
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
|
|
2280
1663
|
// that ended meanwhile fails the prompt as the check above does.
|
|
2281
1664
|
// A `session/cancel` that arrived after this prompt, during the awaits
|
|
2282
1665
|
// above, ends it the same way.
|
|
@@ -2306,12 +1689,12 @@ export class ClaudeAcpAgent {
|
|
|
2306
1689
|
completeTurn = resolve;
|
|
2307
1690
|
}),
|
|
2308
1691
|
resolve: (outcome) => {
|
|
2309
|
-
this.endForeground(params.sessionId, turn
|
|
1692
|
+
this.endForeground(params.sessionId, turn);
|
|
2310
1693
|
events.ended(outcome);
|
|
2311
1694
|
completeTurn();
|
|
2312
1695
|
},
|
|
2313
1696
|
reject: (error) => {
|
|
2314
|
-
this.endForeground(params.sessionId, turn
|
|
1697
|
+
this.endForeground(params.sessionId, turn);
|
|
2315
1698
|
events.failed(error);
|
|
2316
1699
|
completeTurn();
|
|
2317
1700
|
},
|
|
@@ -2327,31 +1710,9 @@ export class ClaudeAcpAgent {
|
|
|
2327
1710
|
// the goal it sets; the turn's events report the outcome.
|
|
2328
1711
|
await this.publishGoalFromPrompt(params.sessionId, firstText, promptUuid).catch((error) => this.logger.error(`Session ${params.sessionId}: failed to publish the prompt's goal:`, error));
|
|
2329
1712
|
}
|
|
2330
|
-
/**
|
|
2331
|
-
async runRemoteControlCommand(sessionId, query, command) {
|
|
2332
|
-
|
|
2333
|
-
if (command.action === "disconnect") {
|
|
2334
|
-
try {
|
|
2335
|
-
await query.enableRemoteControl(false);
|
|
2336
|
-
text = "Remote Control is off. Run /remote-control to reconnect.";
|
|
2337
|
-
}
|
|
2338
|
-
catch (error) {
|
|
2339
|
-
this.logger.error(`Failed to disable Remote Control: ${error}`);
|
|
2340
|
-
text = `Could not stop Remote Control: ${error instanceof Error ? error.message : error}`;
|
|
2341
|
-
}
|
|
2342
|
-
}
|
|
2343
|
-
else {
|
|
2344
|
-
try {
|
|
2345
|
-
const result = await query.enableRemoteControl(true, command.name);
|
|
2346
|
-
text = result.session_url
|
|
2347
|
-
? `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.`
|
|
2348
|
-
: "Remote Control is active, but Claude Code did not return a session URL.";
|
|
2349
|
-
}
|
|
2350
|
-
catch (error) {
|
|
2351
|
-
this.logger.error(`Failed to enable Remote Control: ${error}`);
|
|
2352
|
-
text = `Could not start Remote Control: ${error instanceof Error ? error.message : error}`;
|
|
2353
|
-
}
|
|
2354
|
-
}
|
|
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));
|
|
2355
1716
|
await this.client.sessionUpdate({
|
|
2356
1717
|
sessionId,
|
|
2357
1718
|
update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } },
|
|
@@ -2460,24 +1821,9 @@ export class ClaudeAcpAgent {
|
|
|
2460
1821
|
if (!clientServers.has(server.name) || session.reportedMcpServers?.has(server.name)) {
|
|
2461
1822
|
continue;
|
|
2462
1823
|
}
|
|
2463
|
-
|
|
2464
|
-
if (
|
|
2465
|
-
notice = {
|
|
2466
|
-
severity: "warning",
|
|
2467
|
-
title: `MCP server "${server.name}" failed to start`,
|
|
2468
|
-
description: "Its tools are unavailable in this session. Run /mcp for the error.",
|
|
2469
|
-
};
|
|
2470
|
-
}
|
|
2471
|
-
else if (server.status === "needs-auth" && !oauthAvailable) {
|
|
2472
|
-
notice = {
|
|
2473
|
-
severity: "info",
|
|
2474
|
-
title: `MCP server "${server.name}" needs authentication`,
|
|
2475
|
-
description: "Its tools are unavailable until the server is authenticated.",
|
|
2476
|
-
};
|
|
2477
|
-
}
|
|
2478
|
-
else {
|
|
1824
|
+
const notice = mcpServerStartupNotice(server, oauthAvailable);
|
|
1825
|
+
if (!notice)
|
|
2479
1826
|
continue;
|
|
2480
|
-
}
|
|
2481
1827
|
(session.reportedMcpServers ??= new Set()).add(server.name);
|
|
2482
1828
|
await sendUpdate({
|
|
2483
1829
|
sessionId,
|
|
@@ -2557,7 +1903,7 @@ export class ClaudeAcpAgent {
|
|
|
2557
1903
|
logger: this.logger,
|
|
2558
1904
|
// The guard reads the account anyway; reuse that read to keep the
|
|
2559
1905
|
// reported identity current, refusal or not.
|
|
2560
|
-
onAccount: (account) => this.
|
|
1906
|
+
onAccount: (account) => this.authStatus.publishSessionAccount(account, session.settingsManager.getApiKeyHelper(session.effortSettingsOverride)),
|
|
2561
1907
|
});
|
|
2562
1908
|
}
|
|
2563
1909
|
async goal(params) {
|
|
@@ -2590,31 +1936,15 @@ export class ClaudeAcpAgent {
|
|
|
2590
1936
|
});
|
|
2591
1937
|
}
|
|
2592
1938
|
/**
|
|
2593
|
-
*
|
|
2594
|
-
*
|
|
2595
|
-
*
|
|
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`.
|
|
2596
1943
|
*/
|
|
2597
|
-
async publishPromptSuggestion(sessionId,
|
|
2598
|
-
const session = this.sessions[sessionId];
|
|
2599
|
-
if (!session)
|
|
2600
|
-
return;
|
|
2601
|
-
// A clear ends the window the turn's result opened: whatever prediction is
|
|
2602
|
-
// still in flight answers a turn the user has already moved past.
|
|
2603
|
-
if (text === null)
|
|
2604
|
-
session.promptSuggestionExpected = false;
|
|
2605
|
-
// A session that never published one holds nothing, so a clear before the
|
|
2606
|
-
// first prediction is already true on the client and goes nowhere.
|
|
2607
|
-
if ((session.lastPublishedPromptSuggestion ?? null) === text)
|
|
2608
|
-
return;
|
|
2609
|
-
if (!this.toolCallCapabilities.air.client)
|
|
2610
|
-
return;
|
|
2611
|
-
session.lastPublishedPromptSuggestion = text;
|
|
1944
|
+
async publishPromptSuggestion(sessionId, meta) {
|
|
2612
1945
|
await this.client.sessionUpdate({
|
|
2613
1946
|
sessionId,
|
|
2614
|
-
update: {
|
|
2615
|
-
sessionUpdate: "session_info_update",
|
|
2616
|
-
_meta: promptSuggestionsMeta(text),
|
|
2617
|
-
},
|
|
1947
|
+
update: { sessionUpdate: "session_info_update", _meta: meta },
|
|
2618
1948
|
});
|
|
2619
1949
|
}
|
|
2620
1950
|
async publishTaskPlan(sessionId, taskState) {
|
|
@@ -3153,9 +2483,6 @@ export class ClaudeAcpAgent {
|
|
|
3153
2483
|
// handler), activation is the first sign that Claude Code took the
|
|
3154
2484
|
// prompt in: its echo, or for an echo-less command, its result.
|
|
3155
2485
|
reportInserted(turn);
|
|
3156
|
-
// A request can already be open: Claude Code asks for a queued prompt
|
|
3157
|
-
// before the consumer reaches its echo.
|
|
3158
|
-
this.syncAwaitingUser(params.sessionId, session);
|
|
3159
2486
|
};
|
|
3160
2487
|
/** Report that Claude Code took the turn's prompt in, once. A turn can be
|
|
3161
2488
|
* settled by now: an echo hand-off awaits settling the previous turn, and
|
|
@@ -3420,16 +2747,13 @@ export class ClaudeAcpAgent {
|
|
|
3420
2747
|
if (isSubagent && session.activeTurn && !session.activeTurn.settled) {
|
|
3421
2748
|
(session.activeTurn.spawnedTaskIds ??= new Set()).add(taskId);
|
|
3422
2749
|
}
|
|
3423
|
-
this.syncAwaitingUser(params.sessionId, session);
|
|
3424
2750
|
};
|
|
3425
|
-
/** Ends the terminal
|
|
3426
|
-
*
|
|
3427
|
-
const endBackgroundTask = (taskId
|
|
3428
|
-
/** Settles a task.
|
|
3429
|
-
* 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. */
|
|
3430
2755
|
const settleLiveTask = (taskId) => {
|
|
3431
2756
|
settleLiveBackgroundTask(session, taskId);
|
|
3432
|
-
this.syncAwaitingUser(params.sessionId, session);
|
|
3433
2757
|
};
|
|
3434
2758
|
/** Registers a settled subagent again when the SDK resumes it without a
|
|
3435
2759
|
* new `task_started`. The active turn is the one that resumed it, so it
|
|
@@ -3500,7 +2824,7 @@ export class ClaudeAcpAgent {
|
|
|
3500
2824
|
turnAwaitingSubagents(session.activeTurn)) {
|
|
3501
2825
|
session.activeTurn.deferredSettle = outcome;
|
|
3502
2826
|
// The hold delays v1's answer; the turn's work ended at its result.
|
|
3503
|
-
this.endForeground(params.sessionId, session.activeTurn
|
|
2827
|
+
this.endForeground(params.sessionId, session.activeTurn);
|
|
3504
2828
|
}
|
|
3505
2829
|
else {
|
|
3506
2830
|
await settleActive(outcome);
|
|
@@ -3737,8 +3061,7 @@ export class ClaudeAcpAgent {
|
|
|
3737
3061
|
}
|
|
3738
3062
|
}
|
|
3739
3063
|
// The client is told that the work a cancel stopped ended (the prompt
|
|
3740
|
-
// response
|
|
3741
|
-
// opened has ended.
|
|
3064
|
+
// response) only after every tool call that work opened has ended.
|
|
3742
3065
|
if (result.stopReason === "cancelled" && session.cancelled) {
|
|
3743
3066
|
await closeCancelledToolCalls(turn);
|
|
3744
3067
|
// `cancelTurns` can settle the turn while the reports are in flight.
|
|
@@ -3852,7 +3175,7 @@ export class ClaudeAcpAgent {
|
|
|
3852
3175
|
* error is the cancel's, not the work's. */
|
|
3853
3176
|
const failAllTurns = (error) => {
|
|
3854
3177
|
disarmForceCancel(session);
|
|
3855
|
-
this.endAutonomousCycle(params.sessionId
|
|
3178
|
+
this.endAutonomousCycle(params.sessionId);
|
|
3856
3179
|
const active = session.activeTurn;
|
|
3857
3180
|
const turns = active
|
|
3858
3181
|
? [active, ...(session.turnQueue ?? []).filter((t) => t !== active)]
|
|
@@ -3904,12 +3227,6 @@ export class ClaudeAcpAgent {
|
|
|
3904
3227
|
const pause = messageLoopYielder.maybeYield();
|
|
3905
3228
|
if (pause)
|
|
3906
3229
|
await pause;
|
|
3907
|
-
// The last message may have changed the background work, and its
|
|
3908
|
-
// updates are sent, so the list follows them. A task that needs a
|
|
3909
|
-
// tool call of its own gets it first, so the list can name it.
|
|
3910
|
-
for (const call of session.background.adoptTasks(session))
|
|
3911
|
-
await sendUpdate(call);
|
|
3912
|
-
this.backgroundWork.sync(params.sessionId, session, this.foregroundState(params.sessionId));
|
|
3913
3230
|
pendingNext ??= session.query
|
|
3914
3231
|
.next()
|
|
3915
3232
|
.then((result) => ({ kind: "message", result }));
|
|
@@ -4031,9 +3348,7 @@ export class ClaudeAcpAgent {
|
|
|
4031
3348
|
// it), but the stored one is the authoritative source.
|
|
4032
3349
|
const inFlight = session.activeTurn;
|
|
4033
3350
|
await finishLifecycle(session.cancelled ? "cancelled" : "failed", session.cancelled ? "stopped" : "failed", "at end of stream");
|
|
4034
|
-
this.endAutonomousCycle(params.sessionId
|
|
4035
|
-
? { outcome: { stopReason: "cancelled" } }
|
|
4036
|
-
: { error: RequestError.internalError(undefined, SESSION_ENDED_MESSAGE) });
|
|
3351
|
+
this.endAutonomousCycle(params.sessionId);
|
|
4037
3352
|
await settleActive(session.cancelled
|
|
4038
3353
|
? cancelledOutcome(session, inFlight)
|
|
4039
3354
|
: (inFlight?.deferredSettle ?? turnOutcome(session, stopReason)));
|
|
@@ -4395,9 +3710,7 @@ export class ClaudeAcpAgent {
|
|
|
4395
3710
|
await asyncTasks.autonomousTurnEnded("completed");
|
|
4396
3711
|
}
|
|
4397
3712
|
await closeCycleToolCalls();
|
|
4398
|
-
this.endAutonomousCycle(params.sessionId
|
|
4399
|
-
outcome: { stopReason: session.cancelled ? "cancelled" : "end_turn" },
|
|
4400
|
-
});
|
|
3713
|
+
this.endAutonomousCycle(params.sessionId);
|
|
4401
3714
|
}
|
|
4402
3715
|
// A non-cancelled turn normally settled at its terminal
|
|
4403
3716
|
// `result` already (issue #773), and that result recorded an
|
|
@@ -4481,7 +3794,7 @@ export class ClaudeAcpAgent {
|
|
|
4481
3794
|
const steered = session.activeTurn;
|
|
4482
3795
|
steered.deferredSettle = outcome;
|
|
4483
3796
|
// A hold delays v1's answer; the turn's work ends here.
|
|
4484
|
-
this.endForeground(params.sessionId, steered
|
|
3797
|
+
this.endForeground(params.sessionId, steered);
|
|
4485
3798
|
leaveSteerLane(steered);
|
|
4486
3799
|
await settleDeferredIfDrained();
|
|
4487
3800
|
}
|
|
@@ -4649,19 +3962,13 @@ export class ClaudeAcpAgent {
|
|
|
4649
3962
|
noticedToolUses.add(message.tool_use_id);
|
|
4650
3963
|
}
|
|
4651
3964
|
}
|
|
4652
|
-
const severity = message.level === "warning" ? "warning" : "info";
|
|
4653
3965
|
const transcriptContent = collapseHookSpeaker(message.content);
|
|
4654
3966
|
const transcriptText = message.level === "info"
|
|
4655
3967
|
? transcriptContent
|
|
4656
3968
|
: `**${sentenceCase(message.level)}:** ${transcriptContent}`;
|
|
4657
3969
|
await sendUpdate({
|
|
4658
3970
|
sessionId: params.sessionId,
|
|
4659
|
-
update: noticeOrTranscriptUpdate({
|
|
4660
|
-
severity,
|
|
4661
|
-
...splitNoticeText(message.content, severity === "warning"
|
|
4662
|
-
? "Claude reported a warning"
|
|
4663
|
-
: "Claude reported a notice"),
|
|
4664
|
-
}, supportsNotices, transcriptText, { claudeCode: { kind: "informational", level: message.level } }),
|
|
3971
|
+
update: noticeOrTranscriptUpdate(informationalNotice(message), supportsNotices, transcriptText, { claudeCode: { kind: "informational", level: message.level } }),
|
|
4665
3972
|
});
|
|
4666
3973
|
const noticedTurn = session.activeTurn ?? session.turnQueue?.[0];
|
|
4667
3974
|
if (supportsNotices && noticedTurn) {
|
|
@@ -4674,19 +3981,11 @@ export class ClaudeAcpAgent {
|
|
|
4674
3981
|
case "hook_response":
|
|
4675
3982
|
case "files_persisted":
|
|
4676
3983
|
break;
|
|
4677
|
-
case "task_progress":
|
|
3984
|
+
case "task_progress":
|
|
4678
3985
|
if (isLateTaskRun(session, message.task_id, message.run_id)) {
|
|
4679
3986
|
this.logger.log(`Ignoring task_progress for task ${message.task_id} from earlier run ${message.run_id}`);
|
|
4680
3987
|
break;
|
|
4681
3988
|
}
|
|
4682
|
-
// The SDK does not type `workflow_progress`; see workflow-progress.ts.
|
|
4683
|
-
const workflow = workflowSnapshot(message.workflow_progress);
|
|
4684
|
-
const progress = session.background.taskProgress(message.task_id, {
|
|
4685
|
-
...taskProgressFields(message),
|
|
4686
|
-
...(workflow ? { workflow } : {}),
|
|
4687
|
-
});
|
|
4688
|
-
if (progress)
|
|
4689
|
-
await sendUpdate(progress);
|
|
4690
3989
|
await asyncTasks.taskProgress({
|
|
4691
3990
|
task_id: message.task_id,
|
|
4692
3991
|
description: message.description,
|
|
@@ -4696,7 +3995,6 @@ export class ClaudeAcpAgent {
|
|
|
4696
3995
|
tool_use_id: message.tool_use_id,
|
|
4697
3996
|
});
|
|
4698
3997
|
break;
|
|
4699
|
-
}
|
|
4700
3998
|
case "task_started":
|
|
4701
3999
|
if (isLateTaskRun(session, message.task_id, message.run_id)) {
|
|
4702
4000
|
this.logger.log(`Ignoring task_started for task ${message.task_id} from earlier run ${message.run_id}`);
|
|
@@ -4769,7 +4067,7 @@ export class ClaudeAcpAgent {
|
|
|
4769
4067
|
streamedBlocksByParent.delete(message.tool_use_id);
|
|
4770
4068
|
droppedStreams.delete(message.tool_use_id);
|
|
4771
4069
|
}
|
|
4772
|
-
await endBackgroundTask(message.task_id
|
|
4070
|
+
await endBackgroundTask(message.task_id);
|
|
4773
4071
|
if (message.status === "stopped") {
|
|
4774
4072
|
await closeStoppedSubagentToolCalls(message.tool_use_id);
|
|
4775
4073
|
}
|
|
@@ -4782,12 +4080,11 @@ export class ClaudeAcpAgent {
|
|
|
4782
4080
|
}
|
|
4783
4081
|
await asyncTasks.taskUpdated(message.task_id, message.patch);
|
|
4784
4082
|
// A task moved to the background no longer blocks the tool
|
|
4785
|
-
// call that spawned it
|
|
4083
|
+
// call that spawned it.
|
|
4786
4084
|
if (message.patch.is_backgrounded !== undefined) {
|
|
4787
4085
|
const task = session.liveBackgroundTasks.get(message.task_id);
|
|
4788
4086
|
if (task)
|
|
4789
4087
|
task.backgrounded = message.patch.is_backgrounded;
|
|
4790
|
-
this.syncAwaitingUser(params.sessionId, session);
|
|
4791
4088
|
}
|
|
4792
4089
|
// terminal-status task_updated patch and a (deduplicated)
|
|
4793
4090
|
// task_notification when a task settles, but only the patch is
|
|
@@ -4803,22 +4100,14 @@ export class ClaudeAcpAgent {
|
|
|
4803
4100
|
streamedBlocksByParent.delete(parentToolUseId);
|
|
4804
4101
|
droppedStreams.delete(parentToolUseId);
|
|
4805
4102
|
}
|
|
4806
|
-
await endBackgroundTask(message.task_id
|
|
4103
|
+
await endBackgroundTask(message.task_id);
|
|
4807
4104
|
if (message.patch.status === "killed") {
|
|
4808
4105
|
await closeStoppedSubagentToolCalls(parentToolUseId);
|
|
4809
4106
|
}
|
|
4810
4107
|
settleLiveTask(message.task_id);
|
|
4811
4108
|
}
|
|
4812
|
-
else if (message.patch.status === "paused") {
|
|
4813
|
-
const pause = session.background.taskPaused(message.task_id, true);
|
|
4814
|
-
if (pause)
|
|
4815
|
-
await sendUpdate(pause);
|
|
4816
|
-
}
|
|
4817
4109
|
else if (message.patch.status === "running" ||
|
|
4818
4110
|
message.patch.status === "pending") {
|
|
4819
|
-
const resume = session.background.taskPaused(message.task_id, false);
|
|
4820
|
-
if (resume)
|
|
4821
|
-
await sendUpdate(resume);
|
|
4822
4111
|
// The SDK can resume a finished subagent under the same
|
|
4823
4112
|
// agent id without a new task_started.
|
|
4824
4113
|
resumeLiveTask(message.task_id);
|
|
@@ -4882,41 +4171,13 @@ export class ClaudeAcpAgent {
|
|
|
4882
4171
|
break;
|
|
4883
4172
|
}
|
|
4884
4173
|
case "model_refusal_fallback": {
|
|
4885
|
-
// The SDK retried a refused turn on the fallback model
|
|
4886
|
-
//
|
|
4887
|
-
//
|
|
4888
|
-
//
|
|
4889
|
-
//
|
|
4890
|
-
|
|
4891
|
-
|
|
4892
|
-
// Current CLIs only emit direction "retry" (persistent swap).
|
|
4893
|
-
// "revert"/"sticky" are retained in the SDK enum for older
|
|
4894
|
-
// CLIs, where "revert" marked a turn-only fallback — for that
|
|
4895
|
-
// direction the session stays on the original model, so skip
|
|
4896
|
-
// the persistent-swap claim and the state sync.
|
|
4897
|
-
//
|
|
4898
|
-
// `scope` (CLI 2.1.232+) marks WHERE the fallback happened:
|
|
4899
|
-
// "local" means a subagent / side-question / background fork
|
|
4900
|
-
// response fell back and the session model is unchanged, so
|
|
4901
|
-
// syncing the picker would advertise a model the session
|
|
4902
|
-
// isn't running. Absent scope means an older CLI, where every
|
|
4903
|
-
// retry was a session-level swap — treat as "session".
|
|
4904
|
-
const local = message.scope === "local";
|
|
4905
|
-
const persistent = message.direction !== "revert" && !local;
|
|
4906
|
-
const category = message.api_refusal_category
|
|
4907
|
-
? ` (${message.api_refusal_category})`
|
|
4908
|
-
: "";
|
|
4909
|
-
const outcome = persistent
|
|
4910
|
-
? `The session will continue on ${message.fallback_model}.`
|
|
4911
|
-
: local
|
|
4912
|
-
? `Only that response came from ${message.fallback_model}; the session stays on ${message.original_model}.`
|
|
4913
|
-
: `The session stays on ${message.original_model}.`;
|
|
4914
|
-
const fallbackSummary = `${message.original_model} declined this request${category}; ` +
|
|
4915
|
-
`retried with ${message.fallback_model}. ${outcome}`;
|
|
4916
|
-
const explanation = message.api_refusal_explanation || undefined;
|
|
4917
|
-
const fallbackNotice = explanation
|
|
4918
|
-
? `${fallbackSummary}\n\n${explanation}`
|
|
4919
|
-
: 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;
|
|
4920
4181
|
// A silent model swap is a session-level advisory, not something the model said.
|
|
4921
4182
|
// Clients on the ACP notice contract get it as a `notice`; clients that negotiated
|
|
4922
4183
|
// AIR typed records get it as one of those; the rest keep the bold-label transcript
|
|
@@ -4925,26 +4186,21 @@ export class ClaudeAcpAgent {
|
|
|
4925
4186
|
const useDetails = explanation !== undefined &&
|
|
4926
4187
|
fallbackSummary.length + 2 + explanation.length > MAX_NOTICE_TITLE_LENGTH;
|
|
4927
4188
|
await publishSessionFailure("advisory", {
|
|
4928
|
-
title: useDetails
|
|
4189
|
+
title: useDetails
|
|
4190
|
+
? fallbackSummary
|
|
4191
|
+
: explanation
|
|
4192
|
+
? `${fallbackSummary}\n\n${explanation}`
|
|
4193
|
+
: fallbackSummary,
|
|
4929
4194
|
...(useDetails ? { details: explanation } : {}),
|
|
4930
4195
|
});
|
|
4931
4196
|
}
|
|
4932
4197
|
else {
|
|
4933
|
-
// A title must stand alone: the one-line summary when it is
|
|
4934
|
-
// short enough, else a generic title with everything in the
|
|
4935
|
-
// description (the same cap the AIR lane applies above).
|
|
4936
|
-
const notice = fallbackSummary.length > MAX_NOTICE_TITLE_LENGTH
|
|
4937
|
-
? { title: "Model fallback", description: fallbackNotice }
|
|
4938
|
-
: {
|
|
4939
|
-
title: fallbackSummary,
|
|
4940
|
-
...(explanation ? { description: explanation } : {}),
|
|
4941
|
-
};
|
|
4942
4198
|
await sendUpdate({
|
|
4943
4199
|
sessionId: params.sessionId,
|
|
4944
|
-
update: noticeOrTranscriptUpdate(
|
|
4200
|
+
update: noticeOrTranscriptUpdate(fallback.notice, supportsNotices, fallback.transcript),
|
|
4945
4201
|
});
|
|
4946
4202
|
}
|
|
4947
|
-
if (persistent) {
|
|
4203
|
+
if (fallback.persistent) {
|
|
4948
4204
|
await this.syncModelAfterExternalSwitch(params.sessionId, session, message.fallback_model);
|
|
4949
4205
|
}
|
|
4950
4206
|
break;
|
|
@@ -4974,7 +4230,6 @@ export class ClaudeAcpAgent {
|
|
|
4974
4230
|
break;
|
|
4975
4231
|
case "background_tasks_changed": {
|
|
4976
4232
|
await asyncTasks.backgroundTasksChanged(message.tasks);
|
|
4977
|
-
await session.background.levelChanged(message.tasks, sendUpdate);
|
|
4978
4233
|
// A level signal: the full live background-task set on every
|
|
4979
4234
|
// membership change, with REPLACE semantics. Used only to
|
|
4980
4235
|
// reconcile `liveBackgroundTasks` — dropping (or, for
|
|
@@ -5029,7 +4284,7 @@ export class ClaudeAcpAgent {
|
|
|
5029
4284
|
session.modelRequestSinceResult = false;
|
|
5030
4285
|
// The CLI predicts the next prompt right after this result, so a
|
|
5031
4286
|
// `prompt_suggestion` from here on belongs to the turn just ended.
|
|
5032
|
-
session.
|
|
4287
|
+
session.promptSuggestions?.resultArrived();
|
|
5033
4288
|
// The result ends the model turn. A background task that still
|
|
5034
4289
|
// waits for its tool call id gets its spawn now, without the id.
|
|
5035
4290
|
await asyncTasks.releaseHeld();
|
|
@@ -5206,23 +4461,9 @@ export class ClaudeAcpAgent {
|
|
|
5206
4461
|
matchingModelUsage.usage.contextWindow > 0) {
|
|
5207
4462
|
session.contextWindowSize = matchingModelUsage.usage.contextWindow;
|
|
5208
4463
|
session.contextWindowAuthoritative = true;
|
|
5209
|
-
// Authoritative: fold it into the cross-session cache
|
|
5210
|
-
//
|
|
5211
|
-
|
|
5212
|
-
// session/new or switch on the same provider that resolves to
|
|
5213
|
-
// this model seeds the correct window synchronously, with no
|
|
5214
|
-
// getContextUsage IPC.
|
|
5215
|
-
cacheContextWindow(contextWindowCacheKey(session.providerCacheKey, matchingModelUsage.key), matchingModelUsage.usage.contextWindow);
|
|
5216
|
-
// Also cache under the assistant message's own (bare) spelling.
|
|
5217
|
-
// Seed-time reads fall back to a picker value / verbatim live id
|
|
5218
|
-
// when a row carries no resolvedModel (the synthesized
|
|
5219
|
-
// out-of-allowlist resume row sets it undefined on purpose), and
|
|
5220
|
-
// those spellings match `.model` from the assistant message, not
|
|
5221
|
-
// the decorated modelUsage key — without this entry such rows
|
|
5222
|
-
// could never hit the cache.
|
|
5223
|
-
if (lastAssistantModel && lastAssistantModel !== matchingModelUsage.key) {
|
|
5224
|
-
cacheContextWindow(contextWindowCacheKey(session.providerCacheKey, lastAssistantModel), matchingModelUsage.usage.contextWindow);
|
|
5225
|
-
}
|
|
4464
|
+
// Authoritative: fold it into the cross-session cache (see
|
|
4465
|
+
// `cacheResultContextWindow`).
|
|
4466
|
+
cacheResultContextWindow(session.providerCacheKey, matchingModelUsage.key, lastAssistantModel, matchingModelUsage.usage.contextWindow);
|
|
5226
4467
|
}
|
|
5227
4468
|
session.lastTotalCostUsd = message.total_cost_usd;
|
|
5228
4469
|
this.sessionIndex.onOwnSessionChanged(params.sessionId);
|
|
@@ -5263,7 +4504,7 @@ export class ClaudeAcpAgent {
|
|
|
5263
4504
|
pendingExitPlanModeInterruption?.toolUseId;
|
|
5264
4505
|
if (!continuesPlan && !(isAutonomousResult && message.num_turns === 0)) {
|
|
5265
4506
|
await closeCycleToolCalls();
|
|
5266
|
-
this.endAutonomousCycle(params.sessionId
|
|
4507
|
+
this.endAutonomousCycle(params.sessionId);
|
|
5267
4508
|
}
|
|
5268
4509
|
if (session.cancelled) {
|
|
5269
4510
|
session.pendingExitPlanModeInterruption = undefined;
|
|
@@ -5511,18 +4752,21 @@ export class ClaudeAcpAgent {
|
|
|
5511
4752
|
failure.recoveryPolicy === "auth_status" ||
|
|
5512
4753
|
(failure.severity === "warning" && failure.turnId === activeTurnId));
|
|
5513
4754
|
}
|
|
4755
|
+
// The stop reason or the error, by the rules both cores share.
|
|
4756
|
+
const ended = resultEnd(message);
|
|
5514
4757
|
switch (message.subtype) {
|
|
5515
4758
|
case "success": {
|
|
5516
|
-
if (
|
|
5517
|
-
|
|
5518
|
-
|
|
5519
|
-
|
|
5520
|
-
|
|
5521
|
-
|
|
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);
|
|
5522
4765
|
break;
|
|
5523
4766
|
}
|
|
5524
|
-
|
|
5525
|
-
|
|
4767
|
+
// `end_turn` keeps the stop reason as it was.
|
|
4768
|
+
if (ended.stopReason !== "end_turn") {
|
|
4769
|
+
stopReason = ended.stopReason;
|
|
5526
4770
|
break;
|
|
5527
4771
|
}
|
|
5528
4772
|
// The result text is forwarded in two cases. Local-only
|
|
@@ -5562,38 +4806,21 @@ export class ClaudeAcpAgent {
|
|
|
5562
4806
|
}
|
|
5563
4807
|
break;
|
|
5564
4808
|
}
|
|
5565
|
-
case "error_during_execution":
|
|
5566
|
-
if (
|
|
5567
|
-
|
|
5568
|
-
break;
|
|
5569
|
-
}
|
|
5570
|
-
if (message.is_error) {
|
|
5571
|
-
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);
|
|
5572
4812
|
break;
|
|
5573
4813
|
}
|
|
5574
|
-
stopReason =
|
|
4814
|
+
stopReason = ended.stopReason;
|
|
5575
4815
|
break;
|
|
5576
|
-
}
|
|
5577
4816
|
case "error_max_budget_usd":
|
|
5578
|
-
if (message.is_error) {
|
|
5579
|
-
await failActiveWithSessionFailure("budget_exhausted", internalErrorForClient(errorKindData(lastAssistantError), message.errors.join(", ") || message.subtype), message.errors.join(", ") || message.subtype);
|
|
5580
|
-
break;
|
|
5581
|
-
}
|
|
5582
|
-
stopReason = "max_turn_requests";
|
|
5583
|
-
break;
|
|
5584
4817
|
case "error_max_turns":
|
|
5585
|
-
if (message.is_error) {
|
|
5586
|
-
await failActiveWithSessionFailure("context_exhausted", internalErrorForClient(errorKindData(lastAssistantError), message.errors.join(", ") || message.subtype), message.errors.join(", ") || message.subtype);
|
|
5587
|
-
break;
|
|
5588
|
-
}
|
|
5589
|
-
stopReason = "max_turn_requests";
|
|
5590
|
-
break;
|
|
5591
4818
|
case "error_max_structured_output_retries":
|
|
5592
|
-
if (
|
|
5593
|
-
await failActiveWithSessionFailure(
|
|
4819
|
+
if ("error" in ended) {
|
|
4820
|
+
await failActiveWithSessionFailure(LIMIT_FAILURE_CATEGORY[message.subtype], internalErrorForClient(errorKindData(lastAssistantError), ended.error), ended.error);
|
|
5594
4821
|
break;
|
|
5595
4822
|
}
|
|
5596
|
-
stopReason =
|
|
4823
|
+
stopReason = ended.stopReason;
|
|
5597
4824
|
break;
|
|
5598
4825
|
default:
|
|
5599
4826
|
unreachable(message, this.logger);
|
|
@@ -5790,32 +5017,7 @@ export class ClaudeAcpAgent {
|
|
|
5790
5017
|
// already reached the client as chunks and forward only the
|
|
5791
5018
|
// remainder. Each stream (top level or one subagent) keeps its own
|
|
5792
5019
|
// record, so a subagent cannot attribute content to another stream.
|
|
5793
|
-
|
|
5794
|
-
// the current entry; anything else opens a new one.
|
|
5795
|
-
if (message.event.type === "content_block_delta") {
|
|
5796
|
-
const delta = message.event.delta;
|
|
5797
|
-
const chunk = delta.type === "text_delta"
|
|
5798
|
-
? { type: "text", text: delta.text }
|
|
5799
|
-
: delta.type === "thinking_delta"
|
|
5800
|
-
? { type: "thinking", text: delta.thinking }
|
|
5801
|
-
: undefined;
|
|
5802
|
-
// Skip empty deltas (some gateways emit empty thinking chunks —
|
|
5803
|
-
// #793): appending "" is a no-op, but pushing a "" entry would
|
|
5804
|
-
// create a block the consolidated handler's `text.length > 0`
|
|
5805
|
-
// guard can never consume, stalling the diff cursor and
|
|
5806
|
-
// re-emitting the next block as a duplicate.
|
|
5807
|
-
if (chunk?.text) {
|
|
5808
|
-
const index = message.event.index;
|
|
5809
|
-
const streamedBlocks = streamedBlocksOf(message.parent_tool_use_id);
|
|
5810
|
-
const last = streamedBlocks[streamedBlocks.length - 1];
|
|
5811
|
-
if (last && last.index === index && last.type === chunk.type) {
|
|
5812
|
-
last.text += chunk.text;
|
|
5813
|
-
}
|
|
5814
|
-
else {
|
|
5815
|
-
streamedBlocks.push({ index, type: chunk.type, text: chunk.text });
|
|
5816
|
-
}
|
|
5817
|
-
}
|
|
5818
|
-
}
|
|
5020
|
+
recordStreamedDelta(streamedBlocksOf(message.parent_tool_use_id), message.event);
|
|
5819
5021
|
// The stream sees a tool_use first, so the tool's PostToolUse hook
|
|
5820
5022
|
// is registered here, and publishes through this client: a
|
|
5821
5023
|
// subagent's hook update must reach the child session too.
|
|
@@ -6167,8 +5369,6 @@ export class ClaudeAcpAgent {
|
|
|
6167
5369
|
const acceptedPlanToolUseId = observeExitPlanToolResults(message, content, session);
|
|
6168
5370
|
let backgroundedToolCalls = new Set();
|
|
6169
5371
|
let runningTerminal;
|
|
6170
|
-
let runningTerminalTask;
|
|
6171
|
-
let runningToolCalls = new Set();
|
|
6172
5372
|
if (message.type === "user") {
|
|
6173
5373
|
rememberResolvedToolNames(session, content);
|
|
6174
5374
|
recordSubagentFileEdits(session.activeTurn, message.parent_tool_use_id, content, session.toolUseCache);
|
|
@@ -6198,13 +5398,8 @@ export class ClaudeAcpAgent {
|
|
|
6198
5398
|
...(message.parent_tool_use_id
|
|
6199
5399
|
? { parentToolUseId: message.parent_tool_use_id }
|
|
6200
5400
|
: {}),
|
|
6201
|
-
...(typeof backgroundBashTask.outputFilePath === "string"
|
|
6202
|
-
? { outputFilePath: backgroundBashTask.outputFilePath }
|
|
6203
|
-
: {}),
|
|
6204
5401
|
});
|
|
6205
|
-
runningTerminalTask = backgroundBashTask.taskId;
|
|
6206
5402
|
}
|
|
6207
|
-
runningToolCalls = session.background.toolResults(session, content, toolUseResult, session.toolUseCache, message.parent_tool_use_id);
|
|
6208
5403
|
await asyncTasks.toolResults(content);
|
|
6209
5404
|
backgroundedToolCalls = backgroundedBashToolCallIds(content, session.toolUseCache, asyncTasks, backgroundBashTask);
|
|
6210
5405
|
const resumedAgentId = resumedNativeSubagentId(toolUseResult);
|
|
@@ -6241,17 +5436,7 @@ export class ClaudeAcpAgent {
|
|
|
6241
5436
|
// filtered out of `content` above; blocks that do pass through
|
|
6242
5437
|
// (e.g. a subagent image) carry the stamped parentToolUseId
|
|
6243
5438
|
// meta and are excluded there.
|
|
6244
|
-
await sendUpdate(
|
|
6245
|
-
}
|
|
6246
|
-
for (const progress of session.background.toolCallProgress(runningToolCalls)) {
|
|
6247
|
-
await sendUpdate(progress);
|
|
6248
|
-
}
|
|
6249
|
-
// After the result's own updates: the command's output replaces
|
|
6250
|
-
// the placeholder that they gave its terminal.
|
|
6251
|
-
if (runningTerminalTask) {
|
|
6252
|
-
session.background.followOutput(runningTerminalTask, (notification) => sendUpdate(notification).catch((error) => {
|
|
6253
|
-
this.logger.error(`Session ${params.sessionId}: failed to send background command output:`, error);
|
|
6254
|
-
}));
|
|
5439
|
+
await sendUpdate(withRunningTerminal(backgroundedBashToolCall(acceptedPlanToolResult(notification, acceptedPlanToolUseId), backgroundedToolCalls, asyncTasks.enabled), runningTerminal));
|
|
6255
5440
|
}
|
|
6256
5441
|
break;
|
|
6257
5442
|
}
|
|
@@ -6346,7 +5531,9 @@ export class ClaudeAcpAgent {
|
|
|
6346
5531
|
session.titles.reset();
|
|
6347
5532
|
// The follow-up prompt was predicted from the transcript the reset
|
|
6348
5533
|
// dropped, so it no longer follows from anything.
|
|
6349
|
-
|
|
5534
|
+
const cleared = session.promptSuggestions?.clear();
|
|
5535
|
+
if (cleared)
|
|
5536
|
+
await this.publishPromptSuggestion(params.sessionId, cleared);
|
|
6350
5537
|
// The recorded request and TTL describe the dropped conversation.
|
|
6351
5538
|
session.idleCompaction?.reset();
|
|
6352
5539
|
break;
|
|
@@ -6357,10 +5544,9 @@ export class ClaudeAcpAgent {
|
|
|
6357
5544
|
// The CLI predicts the next prompt after the turn's `result`. AIR
|
|
6358
5545
|
// shows it as gray text in an empty composer; Tab fills the
|
|
6359
5546
|
// composer, and nothing is sent until the user sends it.
|
|
6360
|
-
|
|
6361
|
-
|
|
6362
|
-
|
|
6363
|
-
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);
|
|
6364
5550
|
break;
|
|
6365
5551
|
}
|
|
6366
5552
|
case "auth_status":
|
|
@@ -6556,10 +5742,6 @@ export class ClaudeAcpAgent {
|
|
|
6556
5742
|
// cancelled by it).
|
|
6557
5743
|
const cancelledThrough = this.promptsReceived;
|
|
6558
5744
|
this.cancelledThrough.set(params.sessionId, cancelledThrough);
|
|
6559
|
-
// The interrupt below makes Claude Code withdraw the requests that are open
|
|
6560
|
-
// now (see `withPendingUserInput`).
|
|
6561
|
-
for (const input of session.openUserInputs ?? [])
|
|
6562
|
-
input.cancelled = true;
|
|
6563
5745
|
// Before anything awaits, so a model request that the consumer reads in
|
|
6564
5746
|
// the meantime is already judged against these prompts.
|
|
6565
5747
|
session.cancelledPrompts ??= new Set();
|
|
@@ -6916,13 +6098,6 @@ export class ClaudeAcpAgent {
|
|
|
6916
6098
|
continue;
|
|
6917
6099
|
// Its list row now shows what the registry and the transcript tell.
|
|
6918
6100
|
this.sessionIndex.onOwnSessionChanged(sessionId);
|
|
6919
|
-
// Its background tasks end with the query's process.
|
|
6920
|
-
for (const exit of session.background.queryClosed()) {
|
|
6921
|
-
this.client.sessionUpdate(exit).catch((error) => {
|
|
6922
|
-
this.logger.error(`Session ${sessionId}: failed to end a background terminal:`, error);
|
|
6923
|
-
});
|
|
6924
|
-
}
|
|
6925
|
-
this.backgroundWork.sync(sessionId, session, this.foregroundState(sessionId));
|
|
6926
6101
|
}
|
|
6927
6102
|
session.consumer = undefined;
|
|
6928
6103
|
session.contextCompaction = undefined;
|
|
@@ -6933,10 +6108,8 @@ export class ClaudeAcpAgent {
|
|
|
6933
6108
|
}
|
|
6934
6109
|
/** Cleanly tear down a session: cancel in-flight work, release stream
|
|
6935
6110
|
* resources, and remove it from the session map. Returns once the turns it
|
|
6936
|
-
* cancels have ended, so their
|
|
6937
|
-
*
|
|
6938
|
-
* `session/close` cancels "as if `session/cancel` had been called", then
|
|
6939
|
-
* 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
|
|
6940
6113
|
* {@link TEARDOWN_TURN_END_TIMEOUT_MS}. */
|
|
6941
6114
|
async teardownSession(sessionId) {
|
|
6942
6115
|
const session = this.sessions[sessionId];
|
|
@@ -6954,7 +6127,7 @@ export class ClaudeAcpAgent {
|
|
|
6954
6127
|
}
|
|
6955
6128
|
// The turns end before this returns; so does a model cycle that Claude
|
|
6956
6129
|
// Code started on its own, which no turn waits for.
|
|
6957
|
-
this.endAutonomousCycle(sessionId
|
|
6130
|
+
this.endAutonomousCycle(sessionId);
|
|
6958
6131
|
// cancel() arms the force-cancel floor and interrupts gracefully, but a
|
|
6959
6132
|
// wedged consumer only wakes when `cancelController` aborts — closeQueryStream
|
|
6960
6133
|
// below doesn't touch it. Since we're tearing the session down anyway, wake
|
|
@@ -6977,15 +6150,13 @@ export class ClaudeAcpAgent {
|
|
|
6977
6150
|
session.asyncTaskRuntime?.clear();
|
|
6978
6151
|
this.replayedChildModels.delete(sessionId);
|
|
6979
6152
|
this.cancelledThrough.delete(sessionId);
|
|
6980
|
-
this.backgroundWork.forget(sessionId);
|
|
6981
6153
|
delete this.sessions[sessionId];
|
|
6982
6154
|
this.sessionIndex.onTeardown(sessionId);
|
|
6983
6155
|
const ended = await raceTimeoutAndAbort(turnsEnded, TEARDOWN_TURN_END_TIMEOUT_MS, new AbortController().signal);
|
|
6984
6156
|
if (ended.type === "timeout") {
|
|
6985
6157
|
this.logger.error(`Session ${sessionId}: its cancelled turns did not end within ${TEARDOWN_TURN_END_TIMEOUT_MS}ms of the teardown`);
|
|
6986
|
-
// Settle them here, so the close still answers after each turn's end:
|
|
6987
|
-
//
|
|
6988
|
-
// 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`.
|
|
6989
6160
|
for (const turn of turns) {
|
|
6990
6161
|
if (turn.settled)
|
|
6991
6162
|
continue;
|
|
@@ -6997,10 +6168,9 @@ export class ClaudeAcpAgent {
|
|
|
6997
6168
|
session.activeTurn = null;
|
|
6998
6169
|
// Foreground work that no turn owns, such as a cycle that Claude Code
|
|
6999
6170
|
// started after the endAutonomousCycle call above.
|
|
7000
|
-
const
|
|
7001
|
-
if (
|
|
7002
|
-
this.endForeground(sessionId,
|
|
7003
|
-
}
|
|
6171
|
+
const owner = this.foregroundWork.get(sessionId);
|
|
6172
|
+
if (owner)
|
|
6173
|
+
this.endForeground(sessionId, owner);
|
|
7004
6174
|
}
|
|
7005
6175
|
}
|
|
7006
6176
|
/** Tear down all active sessions. Called when the ACP connection closes. */
|
|
@@ -7016,63 +6186,12 @@ export class ClaudeAcpAgent {
|
|
|
7016
6186
|
await this.teardownSession(params.sessionId);
|
|
7017
6187
|
return {};
|
|
7018
6188
|
}
|
|
7019
|
-
/**
|
|
7020
|
-
|
|
7021
|
-
|
|
7022
|
-
return cancelBackgroundWork(Object.values(this.sessions), params.sessionId, {
|
|
7023
|
-
terminalId: params.terminalId,
|
|
7024
|
-
});
|
|
6189
|
+
/** Per client: see {@link sessionIndex.SessionIndexConnection.deleteSession}. */
|
|
6190
|
+
async deleteSession(params) {
|
|
6191
|
+
return this.sessionIndex.deleteSession(params);
|
|
7025
6192
|
}
|
|
7026
|
-
|
|
7027
|
-
|
|
7028
|
-
cancelBackgroundToolCall(params) {
|
|
7029
|
-
return cancelBackgroundWork(Object.values(this.sessions), params.sessionId, {
|
|
7030
|
-
toolCallId: params.toolCallId,
|
|
7031
|
-
});
|
|
7032
|
-
}
|
|
7033
|
-
/** Sends the current state of each tool call in `toolCallIds` that the root
|
|
7034
|
-
* session `sessionId` runs in the background: the call as its tool use
|
|
7035
|
-
* shows it, with its status now. v2 requires it for each tool call that a
|
|
7036
|
-
* `session/resume` snapshot lists. A failure is logged, as for
|
|
7037
|
-
* {@link publishLiveSubagents}. */
|
|
7038
|
-
async publishBackgroundToolCalls(sessionId, toolCallIds) {
|
|
7039
|
-
const session = this.sessions[sessionId];
|
|
7040
|
-
if (!session)
|
|
7041
|
-
return;
|
|
7042
|
-
const renderer = new AcpToolCallRenderer(this.toolCallCapabilities);
|
|
7043
|
-
try {
|
|
7044
|
-
for (const update of session.background.toolCallStates(toolCallIds, renderer, session.cwd)) {
|
|
7045
|
-
await this.client.sessionUpdate(update);
|
|
7046
|
-
}
|
|
7047
|
-
}
|
|
7048
|
-
catch (error) {
|
|
7049
|
-
this.logger.error(`Session ${sessionId}: failed to send background tool calls:`, error);
|
|
7050
|
-
}
|
|
7051
|
-
}
|
|
7052
|
-
/** Sends the current `subagent_update` of each live subagent session in
|
|
7053
|
-
* `children`, of the session `sessionId` (see
|
|
7054
|
-
* {@link NativeSubagentRuntime.currentUpdate}). v2 requires it for each
|
|
7055
|
-
* child that a `session/resume` snapshot lists. A failure is logged, as
|
|
7056
|
-
* for {@link publishCurrentSubagentStates}. */
|
|
7057
|
-
async publishLiveSubagents(sessionId, children) {
|
|
7058
|
-
const runtime = this.sessions[sessionId]?.nativeSubagentRuntime;
|
|
7059
|
-
try {
|
|
7060
|
-
for (const child of children) {
|
|
7061
|
-
const update = runtime?.currentUpdate(child);
|
|
7062
|
-
if (update)
|
|
7063
|
-
await this.client.sessionUpdate(asSdkSessionNotification(update));
|
|
7064
|
-
}
|
|
7065
|
-
}
|
|
7066
|
-
catch (error) {
|
|
7067
|
-
this.logger.error(`Session ${sessionId}: failed to send current subagent states:`, error);
|
|
7068
|
-
}
|
|
7069
|
-
}
|
|
7070
|
-
/** Per client: see {@link sessionIndex.SessionIndexConnection.deleteSession}. */
|
|
7071
|
-
async deleteSession(params) {
|
|
7072
|
-
return this.sessionIndex.deleteSession(params);
|
|
7073
|
-
}
|
|
7074
|
-
setSessionMode(params) {
|
|
7075
|
-
return this.serializeConfigurationChange(params.sessionId, () => this.sessionModes.setSessionMode(params));
|
|
6193
|
+
setSessionMode(params) {
|
|
6194
|
+
return this.serializeConfigurationChange(params.sessionId, () => this.sessionModes.setSessionMode(params));
|
|
7076
6195
|
}
|
|
7077
6196
|
setSessionConfigOption(params) {
|
|
7078
6197
|
return this.serializeConfigurationChange(params.sessionId, () => this.selectSessionConfigOption(params));
|
|
@@ -7093,60 +6212,17 @@ export class ClaudeAcpAgent {
|
|
|
7093
6212
|
if (!option) {
|
|
7094
6213
|
throw RequestError.invalidParams(undefined, `Unknown config option: ${params.configId}`);
|
|
7095
6214
|
}
|
|
7096
|
-
|
|
7097
|
-
|
|
7098
|
-
|
|
7099
|
-
|
|
7100
|
-
if (typeof params.value !== expectedType) {
|
|
7101
|
-
throw RequestError.invalidParams({ configId: params.configId, value: params.value }, `Config option ${params.configId} takes a ${expectedType} value, but received: ${JSON.stringify(params.value)}`);
|
|
7102
|
-
}
|
|
7103
|
-
// Fast mode and ultracode carry a boolean value (for Clients that opted
|
|
7104
|
-
// into boolean config options) or the "on"/"off" select fallback, so they
|
|
7105
|
-
// bypass the
|
|
7106
|
-
// string-only validation the select-style options below rely on.
|
|
7107
|
-
if (params.configId === FAST_MODE_CONFIG_ID) {
|
|
7108
|
-
await this.applyFastMode(session, resolveFastModeEnabled(params));
|
|
7109
|
-
return { configOptions: session.configOptions };
|
|
7110
|
-
}
|
|
7111
|
-
if (params.configId === ULTRACODE_CONFIG_ID) {
|
|
7112
|
-
await this.applyUltracode(session, resolveUltracodeEnabled(params));
|
|
7113
|
-
return { configOptions: session.configOptions };
|
|
7114
|
-
}
|
|
7115
|
-
if (typeof params.value !== "string") {
|
|
7116
|
-
throw RequestError.invalidParams(undefined, `Invalid value for config option ${params.configId}: ${params.value}`);
|
|
7117
|
-
}
|
|
7118
|
-
const allValues = "options" in option && Array.isArray(option.options)
|
|
7119
|
-
? option.options.flatMap((o) => ("options" in o ? o.options : [o]))
|
|
7120
|
-
: [];
|
|
7121
|
-
let validValue = allValues.find((o) => o.value === params.value);
|
|
7122
|
-
// For model options, fall back to resolveModelPreference when the exact
|
|
7123
|
-
// value doesn't match. This lets callers use human-friendly aliases like
|
|
7124
|
-
// "opus" or "sonnet" instead of full model IDs like "claude-opus-4-6".
|
|
7125
|
-
// Resolve against session.modelInfos first: those entries carry
|
|
7126
|
-
// `resolvedModel`, so a full model id (in either hint spelling) lands on
|
|
7127
|
-
// the right row via the exact tier instead of a fuzzier one picking a
|
|
7128
|
-
// same-family sibling from a different context lane. The options-derived
|
|
7129
|
-
// list (which never carries `resolvedModel`) remains as a fallback for
|
|
7130
|
-
// resolutions that don't map back onto a selectable option (e.g. a fuzzy
|
|
7131
|
-
// hit on an out-of-picker verbatim entry).
|
|
7132
|
-
if (!validValue && params.configId === MODEL_CONFIG_ID) {
|
|
7133
|
-
const toOptionValue = (resolved) => resolved ? allValues.find((o) => o.value === resolved.value) : undefined;
|
|
7134
|
-
validValue = toOptionValue(resolveModelPreference(session.modelInfos, params.value));
|
|
7135
|
-
if (!validValue) {
|
|
7136
|
-
const optionInfos = allValues.map((o) => ({
|
|
7137
|
-
value: o.value,
|
|
7138
|
-
displayName: o.name,
|
|
7139
|
-
description: o.description ?? "",
|
|
7140
|
-
}));
|
|
7141
|
-
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);
|
|
7142
6219
|
}
|
|
6220
|
+
else {
|
|
6221
|
+
await this.applyUltracode(session, selected.enabled);
|
|
6222
|
+
}
|
|
6223
|
+
return { configOptions: session.configOptions };
|
|
7143
6224
|
}
|
|
7144
|
-
|
|
7145
|
-
throw RequestError.invalidParams(undefined, `Invalid value for config option ${params.configId}: ${params.value}`);
|
|
7146
|
-
}
|
|
7147
|
-
// Use the canonical option value so downstream code always receives the
|
|
7148
|
-
// model ID rather than the caller-supplied alias.
|
|
7149
|
-
const resolvedValue = validValue.value;
|
|
6225
|
+
const resolvedValue = selected.value;
|
|
7150
6226
|
let effectiveValue = resolvedValue;
|
|
7151
6227
|
if (params.configId === MODE_CONFIG_ID) {
|
|
7152
6228
|
effectiveValue = await this.sessionModes.selectMode(params.sessionId, resolvedValue);
|
|
@@ -7485,28 +6561,11 @@ export class ClaudeAcpAgent {
|
|
|
7485
6561
|
// Claude persists the retained summary as a user message framed with
|
|
7486
6562
|
// continuation instructions for the model. Clients on the compaction
|
|
7487
6563
|
// contract get it materialized as the completed compaction entity at
|
|
7488
|
-
// this transcript position
|
|
7489
|
-
//
|
|
7490
|
-
// is the one durable marker); other clients keep the transcript text.
|
|
7491
|
-
// The entity is keyed by the summary message's uuid, which differs from
|
|
7492
|
-
// the live id (the `compacting` status uuid) — replay is terminal-first
|
|
7493
|
-
// by the RFD, and no client merges a replay into a live entity store.
|
|
7494
|
-
// A subagent's own compaction summary is not the root session's. A summary
|
|
7495
|
-
// whose framing is unrecognized is still this compaction, without summary
|
|
7496
|
-
// text: isCompactSummary says what it is, and the framing is Claude Code's
|
|
7497
|
-
// 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.
|
|
7498
6566
|
if (replayCompactionUpdates &&
|
|
7499
|
-
isCompactSummaryMessage(message) &&
|
|
7500
6567
|
parentToolUseId === null &&
|
|
7501
|
-
|
|
7502
|
-
message.uuid.length > 0) {
|
|
7503
|
-
const replayCompaction = new ContextCompactionLifecycle((notification) => this.client.sessionUpdate(notification), {
|
|
7504
|
-
sessionId,
|
|
7505
|
-
presentation: "compaction_update",
|
|
7506
|
-
airClient: this.toolCallCapabilities.air.client,
|
|
7507
|
-
});
|
|
7508
|
-
replayCompaction.recordSummary(assistantMessageText(message.message));
|
|
7509
|
-
await replayCompaction.finish(message.uuid, "completed");
|
|
6568
|
+
(await replayCompactSummary(message, (notification) => this.client.sessionUpdate(notification), { sessionId, airClient: this.toolCallCapabilities.air.client }))) {
|
|
7510
6569
|
return;
|
|
7511
6570
|
}
|
|
7512
6571
|
for (const notification of toAcpNotifications(
|
|
@@ -7644,119 +6703,41 @@ export class ClaudeAcpAgent {
|
|
|
7644
6703
|
* conversation) as awaiting user input for exactly the lifetime of its
|
|
7645
6704
|
* promise (see `Session.openUserInputs`). Steering consults the open
|
|
7646
6705
|
* requests synchronously, so a message arriving while any permission or
|
|
7647
|
-
* elicitation card is open uses non-interrupting SDK delivery.
|
|
7648
|
-
|
|
7649
|
-
* `signal` aborts when Claude Code withdraws the request, which is not an
|
|
7650
|
-
* answer. Example: the user cancels while a permission request is open.
|
|
7651
|
-
* Claude Code's interrupt withdraws it as it stops the work, and the work
|
|
7652
|
-
* ends `idle cancelled` right after. The end of the request then reports
|
|
7653
|
-
* no `running`: the client would see `requires_action`, `running`, `idle
|
|
7654
|
-
* cancelled`. A withdrawal without a cancel means that something else
|
|
7655
|
-
* answered the request in the user's place, such as a `PermissionRequest`
|
|
7656
|
-
* hook, and the work goes on, so the end reports `running`. */
|
|
7657
|
-
async withPendingUserInput(sessionId, signal, request, agentID) {
|
|
6706
|
+
* elicitation card is open uses non-interrupting SDK delivery. */
|
|
6707
|
+
async withPendingUserInput(sessionId, request, agentID) {
|
|
7658
6708
|
const session = this.sessions[sessionId];
|
|
7659
6709
|
if (!session)
|
|
7660
6710
|
return request();
|
|
7661
6711
|
const input = agentID !== undefined ? { agentID } : {};
|
|
7662
6712
|
(session.openUserInputs ??= new Set()).add(input);
|
|
7663
|
-
this.syncAwaitingUser(sessionId, session);
|
|
7664
6713
|
try {
|
|
7665
6714
|
return await request();
|
|
7666
6715
|
}
|
|
7667
6716
|
finally {
|
|
7668
6717
|
session.openUserInputs.delete(input);
|
|
7669
|
-
const withdrawnByCancel = signal.aborted && input.cancelled === true;
|
|
7670
|
-
this.syncAwaitingUser(sessionId, session, withdrawnByCancel);
|
|
7671
6718
|
}
|
|
7672
6719
|
}
|
|
7673
|
-
/** Report whether the session's foreground work awaits the user: exactly
|
|
7674
|
-
* while a permission request or question that blocks it is open (see
|
|
7675
|
-
* {@link blocksForeground}). A request does not say which prompt it is for,
|
|
7676
|
-
* and Claude Code can ask for a queued prompt before the consumer activates
|
|
7677
|
-
* it, so a request is not tied to the work that was running when it
|
|
7678
|
-
* opened. Called when a request opens or closes, when a turn activates, and
|
|
7679
|
-
* when a task registers or moves to the background.
|
|
7680
|
-
*
|
|
7681
|
-
* When the last request ends, the work reports `running` again, unless a
|
|
7682
|
-
* cancel withdrew that request (`withdrawnByCancel`, see
|
|
7683
|
-
* {@link withPendingUserInput}): the work is being stopped, and reports its
|
|
7684
|
-
* end next. */
|
|
7685
|
-
syncAwaitingUser(sessionId, session, withdrawnByCancel = false) {
|
|
7686
|
-
const work = this.foregroundWork.get(sessionId);
|
|
7687
|
-
if (!work)
|
|
7688
|
-
return;
|
|
7689
|
-
const waiting = [...(session.openUserInputs ?? [])].some((input) => blocksForeground(session, input.agentID));
|
|
7690
|
-
if (waiting === work.awaitingUser)
|
|
7691
|
-
return;
|
|
7692
|
-
work.awaitingUser = waiting;
|
|
7693
|
-
if (waiting)
|
|
7694
|
-
work.events.awaitingUser();
|
|
7695
|
-
else if (!withdrawnByCancel)
|
|
7696
|
-
work.events.running();
|
|
7697
|
-
}
|
|
7698
6720
|
/** Whether Claude is working in the session `sessionId`: an unsettled turn in
|
|
7699
6721
|
* its queue, or foreground work that no turn owns, such as a cycle that
|
|
7700
6722
|
* Claude Code started on its own. */
|
|
7701
6723
|
claudeIsWorking(sessionId, session) {
|
|
7702
6724
|
return (this.foregroundWork.has(sessionId) || (session.turnQueue ?? []).some((turn) => !turn.settled));
|
|
7703
6725
|
}
|
|
7704
|
-
/** Sends the current title and `updatedAt` of the session `sessionId` as a
|
|
7705
|
-
* `session_info_update` (see {@link SessionTitles.publishCurrent}). A
|
|
7706
|
-
* failure is logged: the info is optional, so it does not fail a resume. */
|
|
7707
|
-
async publishCurrentSessionInfo(sessionId) {
|
|
7708
|
-
const session = this.sessions[sessionId];
|
|
7709
|
-
if (!session)
|
|
7710
|
-
return;
|
|
7711
|
-
try {
|
|
7712
|
-
await session.titles.publishCurrent(session);
|
|
7713
|
-
}
|
|
7714
|
-
catch (error) {
|
|
7715
|
-
this.logger.error(`Session ${sessionId}: failed to send the session info:`, error);
|
|
7716
|
-
}
|
|
7717
|
-
}
|
|
7718
|
-
/** The foreground state of the session `sessionId` now, as v2's
|
|
7719
|
-
* `state_update` names it: `idle` while no work runs, `requires_action`
|
|
7720
|
-
* while the work awaits the user (see {@link syncAwaitingUser}), and
|
|
7721
|
-
* `running` otherwise. */
|
|
7722
|
-
foregroundState(sessionId) {
|
|
7723
|
-
const work = this.foregroundWork.get(sessionId);
|
|
7724
|
-
if (!work)
|
|
7725
|
-
return "idle";
|
|
7726
|
-
return work.awaitingUser ? "requires_action" : "running";
|
|
7727
|
-
}
|
|
7728
6726
|
/** Make `owner` the foreground work of the session `sessionId` (see
|
|
7729
|
-
* {@link
|
|
7730
|
-
*
|
|
7731
|
-
*
|
|
7732
|
-
* 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. */
|
|
7733
6730
|
startForeground(sessionId, owner) {
|
|
7734
|
-
|
|
7735
|
-
|
|
7736
|
-
|
|
7737
|
-
|
|
7738
|
-
|
|
7739
|
-
|
|
7740
|
-
|
|
7741
|
-
events.running();
|
|
7742
|
-
const session = this.sessions[sessionId];
|
|
7743
|
-
if (session)
|
|
7744
|
-
this.syncAwaitingUser(sessionId, session);
|
|
7745
|
-
}
|
|
7746
|
-
/** End the foreground work of the session `sessionId` with `outcome`, or as
|
|
7747
|
-
* failed with `error`, if `owner` is that work. */
|
|
7748
|
-
endForeground(sessionId, owner, end) {
|
|
7749
|
-
const work = this.foregroundWork.get(sessionId);
|
|
7750
|
-
if (work?.owner !== owner)
|
|
7751
|
-
return;
|
|
7752
|
-
this.foregroundWork.delete(sessionId);
|
|
7753
|
-
if ("outcome" in end)
|
|
7754
|
-
work.events.ended(end.outcome);
|
|
7755
|
-
else
|
|
7756
|
-
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);
|
|
7757
6738
|
}
|
|
7758
6739
|
/** Start a model cycle that Claude Code started on its own as the foreground
|
|
7759
|
-
* work (see {@link
|
|
6740
|
+
* work (see {@link ForegroundOwner}) when `message` is its first output:
|
|
7760
6741
|
* model output of the main conversation (not a subagent's) while no work
|
|
7761
6742
|
* runs. That includes a turn that v1 holds for its background subagents,
|
|
7762
6743
|
* whose work ended at its result, so its follow-up is a cycle. Output of
|
|
@@ -7777,16 +6758,13 @@ export class ClaudeAcpAgent {
|
|
|
7777
6758
|
return;
|
|
7778
6759
|
this.startForeground(sessionId, AUTONOMOUS_CYCLE);
|
|
7779
6760
|
}
|
|
7780
|
-
/** Whether the client has been told that the session's work ended:
|
|
7781
|
-
*
|
|
7782
|
-
*
|
|
7783
|
-
*
|
|
7784
|
-
*
|
|
7785
|
-
* 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. */
|
|
7786
6766
|
workEndReported(sessionId, session) {
|
|
7787
|
-
return this.
|
|
7788
|
-
? !this.foregroundWork.has(sessionId)
|
|
7789
|
-
: !session.activeTurn && !this.runsAutonomousCycle(sessionId);
|
|
6767
|
+
return !session.activeTurn && !this.runsAutonomousCycle(sessionId);
|
|
7790
6768
|
}
|
|
7791
6769
|
/** Whether the consumer drops what it reaches now as output of the work a
|
|
7792
6770
|
* cancel stopped: the client has been told that the work ended, and the
|
|
@@ -7845,13 +6823,13 @@ export class ClaudeAcpAgent {
|
|
|
7845
6823
|
}
|
|
7846
6824
|
/** End the session's model cycle that Claude Code started on its own, if one
|
|
7847
6825
|
* runs. */
|
|
7848
|
-
endAutonomousCycle(sessionId
|
|
7849
|
-
this.endForeground(sessionId, AUTONOMOUS_CYCLE
|
|
6826
|
+
endAutonomousCycle(sessionId) {
|
|
6827
|
+
this.endForeground(sessionId, AUTONOMOUS_CYCLE);
|
|
7850
6828
|
}
|
|
7851
6829
|
/** Whether a model cycle that Claude Code started on its own is the session's
|
|
7852
6830
|
* foreground work. A turn that took a cycle over owns the work from then on. */
|
|
7853
6831
|
runsAutonomousCycle(sessionId) {
|
|
7854
|
-
return this.foregroundWork.get(sessionId)
|
|
6832
|
+
return this.foregroundWork.get(sessionId) === AUTONOMOUS_CYCLE;
|
|
7855
6833
|
}
|
|
7856
6834
|
/** The ACP turn that owns a root request of the session now, if any. A
|
|
7857
6835
|
* model cycle that Claude Code started on its own owns no turn. A turn that
|
|
@@ -7890,7 +6868,7 @@ export class ClaudeAcpAgent {
|
|
|
7890
6868
|
// The request goes to a subagent's child session for a tool call of that
|
|
7891
6869
|
// subagent, but it blocks the turn of the owner session.
|
|
7892
6870
|
try {
|
|
7893
|
-
return await this.withChildAwaitingUser(ownerSessionId, params.sessionId, signal, () => this.withPendingUserInput(ownerSessionId,
|
|
6871
|
+
return await this.withChildAwaitingUser(ownerSessionId, params.sessionId, signal, () => this.withPendingUserInput(ownerSessionId, () => this.client.requestPermission(params, signal), agentID));
|
|
7894
6872
|
}
|
|
7895
6873
|
catch (error) {
|
|
7896
6874
|
if (signal.aborted) {
|
|
@@ -7911,9 +6889,9 @@ export class ClaudeAcpAgent {
|
|
|
7911
6889
|
/** `signal`, also aborted when `teardownSession` aborts the
|
|
7912
6890
|
* `abortController` of session `sessionId`. Claude Code aborts a callback's
|
|
7913
6891
|
* own signal when its query closes, but not necessarily before
|
|
7914
|
-
* `session/close` responds, and
|
|
7915
|
-
*
|
|
7916
|
-
*
|
|
6892
|
+
* `session/close` responds, and every pending permission request and
|
|
6893
|
+
* elicitation of the session is cancelled with `$/cancel_request` before
|
|
6894
|
+
* that response. */
|
|
7917
6895
|
untilSessionClosed(sessionId, signal) {
|
|
7918
6896
|
const sessionSignal = this.sessions[sessionId]?.abortController?.signal;
|
|
7919
6897
|
return sessionSignal ? AbortSignal.any([signal, sessionSignal]) : signal;
|
|
@@ -8056,111 +7034,17 @@ export class ClaudeAcpAgent {
|
|
|
8056
7034
|
await session.nativeSubagentRuntime
|
|
8057
7035
|
?.reportCwd(input.agent_id, input.cwd)
|
|
8058
7036
|
.catch((error) => this.logger.error(`Session ${sessionId}: failed to report subagent cwd: ${error}`));
|
|
8059
|
-
const options =
|
|
8060
|
-
|
|
8061
|
-
|
|
8062
|
-
|
|
8063
|
-
|
|
8064
|
-
availableModes: [mode ?? { id: input.permission_mode, name: input.permission_mode }],
|
|
8065
|
-
}));
|
|
8066
|
-
}
|
|
8067
|
-
const switchedModel = input.hook_event_name === "PostModelSwitch"
|
|
8068
|
-
? responseModelEntry(input.to_model, this.subagentModels(sessionId))
|
|
8069
|
-
: undefined;
|
|
8070
|
-
// The entry of the root session's `model` option, as for a child response.
|
|
8071
|
-
if (switchedModel)
|
|
8072
|
-
options.push(childModelOption(switchedModel));
|
|
8073
|
-
if (input.effort?.level) {
|
|
8074
|
-
options.push({
|
|
8075
|
-
id: EFFORT_CONFIG_ID,
|
|
8076
|
-
name: "Effort",
|
|
8077
|
-
description: "Current reasoning effort",
|
|
8078
|
-
category: "thought_level",
|
|
8079
|
-
type: "select",
|
|
8080
|
-
currentValue: input.effort.level,
|
|
8081
|
-
options: [{ value: input.effort.level, name: effortLevelName(input.effort.level) }],
|
|
8082
|
-
});
|
|
8083
|
-
}
|
|
8084
|
-
if (input.agent_type) {
|
|
8085
|
-
const agent = session.agents.find((agent) => agent.name === input.agent_type);
|
|
8086
|
-
options.push({
|
|
8087
|
-
id: AGENT_CONFIG_ID,
|
|
8088
|
-
name: "Agent",
|
|
8089
|
-
description: "Subagent type",
|
|
8090
|
-
type: "select",
|
|
8091
|
-
currentValue: input.agent_type,
|
|
8092
|
-
options: [
|
|
8093
|
-
{
|
|
8094
|
-
value: input.agent_type,
|
|
8095
|
-
name: input.agent_type,
|
|
8096
|
-
...(agent?.description ? { description: agent.description } : {}),
|
|
8097
|
-
},
|
|
8098
|
-
],
|
|
8099
|
-
});
|
|
8100
|
-
}
|
|
7037
|
+
const options = subagentHookOptions(input, {
|
|
7038
|
+
availableModes: session.modes.availableModes,
|
|
7039
|
+
models: this.subagentModels(sessionId),
|
|
7040
|
+
agents: session.agents,
|
|
7041
|
+
});
|
|
8101
7042
|
await session.nativeSubagentRuntime
|
|
8102
7043
|
?.reportConfiguration(input.agent_id, options)
|
|
8103
7044
|
.catch((error) => this.logger.error(`Session ${sessionId}: failed to report subagent configuration: ${error}`));
|
|
8104
7045
|
return { continue: true };
|
|
8105
7046
|
};
|
|
8106
7047
|
}
|
|
8107
|
-
/**
|
|
8108
|
-
* Captures pre-execution patches for v2 Edit and Write tool calls.
|
|
8109
|
-
*
|
|
8110
|
-
* A v2 diff cannot hold the input's snippet, so the patch needs the file as
|
|
8111
|
-
* it was before the tool runs. Claude Code waits for the hook before running
|
|
8112
|
-
* the tool. If its streamed tool use has not arrived, the patch waits for
|
|
8113
|
-
* the tool call's first publication. The hook makes no permission decision,
|
|
8114
|
-
* and a failure only leaves the preview out.
|
|
8115
|
-
*/
|
|
8116
|
-
fileChangePreviewHook(sessionId) {
|
|
8117
|
-
return async (input, toolUseID, { signal }) => {
|
|
8118
|
-
if (input.hook_event_name === "PreToolUse" && toolUseID) {
|
|
8119
|
-
await this.previewFileChange(sessionId, input, toolUseID, signal).catch((error) => this.logger.error(`Session ${sessionId}: failed to preview ${toolUseID}: ${error}`));
|
|
8120
|
-
}
|
|
8121
|
-
return { continue: true };
|
|
8122
|
-
};
|
|
8123
|
-
}
|
|
8124
|
-
async previewFileChange(sessionId, input, toolUseID, signal) {
|
|
8125
|
-
const session = this.sessions[sessionId];
|
|
8126
|
-
if (!session)
|
|
8127
|
-
return;
|
|
8128
|
-
// As in `canUseTool`: the work a cancel stopped shows nothing.
|
|
8129
|
-
const stopped = this.isStoppedWorkToolUse(session, toolUseID, signal);
|
|
8130
|
-
if (stopped instanceof Promise ? await stopped : stopped)
|
|
8131
|
-
return;
|
|
8132
|
-
const toolInput = (input.tool_input ?? {});
|
|
8133
|
-
const content = await previewPatchContent(input.tool_name, toolInput, session.cwd, "v2");
|
|
8134
|
-
if (!content)
|
|
8135
|
-
return;
|
|
8136
|
-
const fields = toolCallFieldsOf(session);
|
|
8137
|
-
// Workflow tools can run hooks without streaming their use or result.
|
|
8138
|
-
// Keep the patch until the stream or a permission request publishes the
|
|
8139
|
-
// tool call, instead of creating a pending call with no completion path.
|
|
8140
|
-
if (!session.emittedToolCalls.has(toolUseID)) {
|
|
8141
|
-
fields.stagePreview(toolUseID, content);
|
|
8142
|
-
return;
|
|
8143
|
-
}
|
|
8144
|
-
const { parentToolUseId, toolCallSessionId } = this.toolUseOwner(session, sessionId, input.agent_id);
|
|
8145
|
-
const update = {
|
|
8146
|
-
sessionUpdate: "tool_call_update",
|
|
8147
|
-
toolCallId: toolUseID,
|
|
8148
|
-
content,
|
|
8149
|
-
};
|
|
8150
|
-
if (parentToolUseId)
|
|
8151
|
-
stampParentToolUseId(update, parentToolUseId);
|
|
8152
|
-
if (!fields.apply(update))
|
|
8153
|
-
return;
|
|
8154
|
-
// The streamed input must not replace the patch, as for an approval patch.
|
|
8155
|
-
fields.pinContent(toolUseID, content);
|
|
8156
|
-
// The stream's router sends it to the session that holds the tool call.
|
|
8157
|
-
if (session.nativeSubagentDeliver) {
|
|
8158
|
-
await session.nativeSubagentDeliver({ sessionId, update });
|
|
8159
|
-
}
|
|
8160
|
-
else {
|
|
8161
|
-
await this.client.sessionUpdate({ sessionId: toolCallSessionId, update });
|
|
8162
|
-
}
|
|
8163
|
-
}
|
|
8164
7048
|
canUseTool(sessionId) {
|
|
8165
7049
|
return async (toolName, toolInput, { signal, suggestions, toolUseID, agentID, matchedAskRule, blockedPath, decisionReason, title, displayName, description, defaultToNo, suppressAlwaysAllowRule, mcpServer, }) => {
|
|
8166
7050
|
const session = this.sessions[sessionId];
|
|
@@ -8213,8 +7097,8 @@ export class ClaudeAcpAgent {
|
|
|
8213
7097
|
const noPersistentRule = matchedAskRule !== undefined || suppressAlwaysAllowRule === true;
|
|
8214
7098
|
const durableChangeSet = normalizeDurablePermissionChangeSet(suggestions, noPersistentRule);
|
|
8215
7099
|
const capabilities = this.toolCallCapabilities;
|
|
8216
|
-
const previewContent = capabilities.diffPatch
|
|
8217
|
-
? await previewPatchContent(toolName, toolInput, session.cwd,
|
|
7100
|
+
const previewContent = capabilities.diffPatch
|
|
7101
|
+
? await previewPatchContent(toolName, toolInput, session.cwd, "air")
|
|
8218
7102
|
: undefined;
|
|
8219
7103
|
const presentation = buildClaudePermissionPresentation({
|
|
8220
7104
|
toolName,
|
|
@@ -8230,24 +7114,16 @@ export class ClaudeAcpAgent {
|
|
|
8230
7114
|
decisionReason,
|
|
8231
7115
|
defaultToNo,
|
|
8232
7116
|
});
|
|
8233
|
-
// `mcpServer` (SDK 0.3.274+): which MCP server serves an `mcp__*` tool
|
|
8234
|
-
// and where its definition came from. Forwarded verbatim so a client
|
|
8235
|
-
// can key trust on `source` (`sdk` = a host-registered in-process
|
|
8236
|
-
// server; anything else is configuration) instead of parsing the
|
|
8237
|
-
// tool-name prefix. The name is the config key as authored — untrusted
|
|
8238
|
-
// text, so it rides `_meta` rather than the title.
|
|
8239
7117
|
// AIR already holds the tool name and the parent tool call. Every
|
|
8240
7118
|
// other client gets them again, like upstream.
|
|
8241
|
-
const
|
|
8242
|
-
|
|
8243
|
-
|
|
8244
|
-
|
|
8245
|
-
|
|
8246
|
-
|
|
8247
|
-
|
|
8248
|
-
|
|
8249
|
-
};
|
|
8250
|
-
}
|
|
7119
|
+
const toolCallMeta = permissionToolCallMeta({
|
|
7120
|
+
toolName,
|
|
7121
|
+
parentToolUseId,
|
|
7122
|
+
mcpServer,
|
|
7123
|
+
airClient: capabilities.air.client,
|
|
7124
|
+
});
|
|
7125
|
+
if (toolCallMeta)
|
|
7126
|
+
presentation.toolCall._meta = toolCallMeta;
|
|
8251
7127
|
const permissionOptions = buildClaudePermissionOptions({
|
|
8252
7128
|
toolName,
|
|
8253
7129
|
displayName,
|
|
@@ -8279,13 +7155,9 @@ export class ClaudeAcpAgent {
|
|
|
8279
7155
|
// cancel does not stop. Answer such a request with a denial so the
|
|
8280
7156
|
// subagent reads "the user refused" and goes on. Throwing instead makes
|
|
8281
7157
|
// Claude Code deny it as "Tool permission request failed".
|
|
8282
|
-
// On ACP v2, `cancelled` also answers a prompt that the user dismissed
|
|
8283
|
-
// or that the client declined by policy. Without a `session/cancel`
|
|
8284
|
-
// (`session.cancelled` unset), that is the user refusing the tool, so it
|
|
8285
|
-
// gets the same denial and the turn goes on.
|
|
8286
7158
|
if (response.outcome?.outcome === "cancelled" &&
|
|
8287
7159
|
this.sessions[sessionId] === session &&
|
|
8288
|
-
|
|
7160
|
+
!blocksForeground(session, agentID)) {
|
|
8289
7161
|
return {
|
|
8290
7162
|
behavior: "deny",
|
|
8291
7163
|
message: "User refused permission to run tool",
|
|
@@ -8343,118 +7215,50 @@ export class ClaudeAcpAgent {
|
|
|
8343
7215
|
}
|
|
8344
7216
|
/**
|
|
8345
7217
|
* Handle elicitation requests that originate from MCP servers by forwarding
|
|
8346
|
-
* them to the client over ACP
|
|
8347
|
-
* server as `decline`. A request the user never saw, because the client did
|
|
8348
|
-
* not advertise its mode, we can't represent it, or the client answered with
|
|
8349
|
-
* an error, is a `cancel`.
|
|
7218
|
+
* them to the client over ACP (see {@link answerMcpElicitation}).
|
|
8350
7219
|
*/
|
|
8351
7220
|
handleMcpElicitation(sessionId, support) {
|
|
8352
7221
|
return async (request, { signal: callbackSignal }) => {
|
|
8353
7222
|
const signal = this.untilSessionClosed(sessionId, callbackSignal);
|
|
8354
|
-
|
|
8355
|
-
|
|
8356
|
-
|
|
8357
|
-
|
|
8358
|
-
|
|
8359
|
-
|
|
8360
|
-
return { action: "cancel" };
|
|
8361
|
-
}
|
|
8362
|
-
try {
|
|
8363
|
-
const response = await this.withPendingUserInput(sessionId, signal, () => this.elicitFromClient(createRequest, signal));
|
|
8364
|
-
if (signal.aborted) {
|
|
8365
|
-
return { action: "cancel" };
|
|
8366
|
-
}
|
|
8367
|
-
return createElicitationResponseToElicitResult(response);
|
|
8368
|
-
}
|
|
8369
|
-
catch (error) {
|
|
8370
|
-
// A cancellation we requested (signal aborted) settles as a cancel, not
|
|
8371
|
-
// a hard decline — the elicitation was abandoned, not refused.
|
|
8372
|
-
if (signal.aborted) {
|
|
8373
|
-
return { action: "cancel" };
|
|
8374
|
-
}
|
|
8375
|
-
// The client answered with an error, e.g. -32602 for a form it cannot
|
|
8376
|
-
// render, so the user never saw the request. MCP's `decline` means the
|
|
8377
|
-
// user refused; `cancel` means they made no explicit choice.
|
|
8378
|
-
this.logger.error(`Failed to forward MCP elicitation: ${error}`);
|
|
8379
|
-
return { action: "cancel" };
|
|
8380
|
-
}
|
|
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
|
+
});
|
|
8381
7229
|
};
|
|
8382
7230
|
}
|
|
8383
7231
|
/**
|
|
8384
7232
|
* Present the built-in AskUserQuestion tool's questions as an ACP form
|
|
8385
|
-
* elicitation and return the answers as the tool's `updatedInput
|
|
8386
|
-
* `canUseTool` since that is
|
|
8387
|
-
*
|
|
8388
|
-
* a
|
|
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`.
|
|
8389
7238
|
*/
|
|
8390
7239
|
async handleAskUserQuestion(sessionId, requestSessionId, toolInput, toolUseID, toolSignal, agentID) {
|
|
8391
7240
|
const signal = this.untilSessionClosed(sessionId, toolSignal);
|
|
8392
|
-
|
|
8393
|
-
|
|
8394
|
-
|
|
8395
|
-
|
|
8396
|
-
|
|
8397
|
-
|
|
8398
|
-
|
|
8399
|
-
response = await this.withChildAwaitingUser(sessionId, requestSessionId, signal, () => this.withPendingUserInput(sessionId, signal, () => this.elicitFromClient(createRequest, signal), agentID));
|
|
8400
|
-
}
|
|
8401
|
-
catch (error) {
|
|
8402
|
-
// A cancellation we requested (signal aborted) settles as an aborted tool
|
|
8403
|
-
// use, matching the post-response check below.
|
|
8404
|
-
if (signal.aborted) {
|
|
8405
|
-
throw new Error("Tool use aborted", { cause: error });
|
|
8406
|
-
}
|
|
8407
|
-
this.logger.error(`Failed to present AskUserQuestion elicitation: ${error}`);
|
|
8408
|
-
return { behavior: "deny", message: "Could not present the question to the user." };
|
|
8409
|
-
}
|
|
8410
|
-
if (signal.aborted) {
|
|
8411
|
-
throw new Error("Tool use aborted");
|
|
8412
|
-
}
|
|
8413
|
-
const outcome = applyAskElicitationResponse(response, toolInput, questions, {
|
|
8414
|
-
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))),
|
|
8415
7248
|
});
|
|
8416
|
-
if (outcome.action === "cancel") {
|
|
8417
|
-
throw new Error("Tool use aborted");
|
|
8418
|
-
}
|
|
8419
|
-
return { behavior: "allow", updatedInput: outcome.updatedInput };
|
|
8420
7249
|
}
|
|
8421
7250
|
/**
|
|
8422
7251
|
* Handle `request_user_dialog` control requests — blocking dialogs the CLI
|
|
8423
|
-
* asks the host to render
|
|
8424
|
-
* are ever emitted; everything unexpected is answered `cancelled` (the
|
|
8425
|
-
* required answer for unrecognized kinds), which applies the dialog's
|
|
8426
|
-
* default behavior CLI-side. Today the only declared kind is the
|
|
8427
|
-
* refusal-fallback consent prompt, rendered as an ACP form elicitation.
|
|
7252
|
+
* asks the host to render (see {@link answerUserDialog}).
|
|
8428
7253
|
*/
|
|
8429
7254
|
handleUserDialog(sessionId) {
|
|
8430
7255
|
return async (request, { signal: callbackSignal }) => {
|
|
8431
7256
|
const signal = this.untilSessionClosed(sessionId, callbackSignal);
|
|
8432
|
-
|
|
8433
|
-
|
|
8434
|
-
|
|
8435
|
-
|
|
8436
|
-
|
|
8437
|
-
this.logger.error(`refusal_fallback_prompt payload had an unexpected shape; cancelling the dialog: ${JSON.stringify(request.payload)}`);
|
|
8438
|
-
return { behavior: "cancelled" };
|
|
8439
|
-
}
|
|
8440
|
-
let response;
|
|
8441
|
-
try {
|
|
8442
|
-
response = await this.withPendingUserInput(sessionId, signal, () => this.elicitFromClient(refusalFallbackToCreateRequest(prompt, sessionId), signal));
|
|
8443
|
-
}
|
|
8444
|
-
catch (error) {
|
|
8445
|
-
// A cancellation we requested (signal aborted) is expected teardown;
|
|
8446
|
-
// anything else is a client failure. Either way the safe answer is
|
|
8447
|
-
// `cancelled` — the CLI applies the dialog's default (keep the
|
|
8448
|
-
// refusal) rather than switching models without consent.
|
|
8449
|
-
if (!signal.aborted) {
|
|
8450
|
-
this.logger.error(`Failed to present refusal fallback elicitation: ${error}`);
|
|
8451
|
-
}
|
|
8452
|
-
return { behavior: "cancelled" };
|
|
8453
|
-
}
|
|
8454
|
-
if (signal.aborted) {
|
|
8455
|
-
return { behavior: "cancelled" };
|
|
8456
|
-
}
|
|
8457
|
-
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
|
+
});
|
|
8458
7262
|
};
|
|
8459
7263
|
}
|
|
8460
7264
|
/**
|
|
@@ -8532,27 +7336,15 @@ export class ClaudeAcpAgent {
|
|
|
8532
7336
|
/**
|
|
8533
7337
|
* The work that follows a session setup response: the session's commands,
|
|
8534
7338
|
* the current states of the subagents a load replayed, and MCP server
|
|
8535
|
-
* authentication.
|
|
8536
|
-
* work once they have sent their response, so it does nothing here.
|
|
7339
|
+
* authentication.
|
|
8537
7340
|
*/
|
|
8538
7341
|
afterSetupResponse(sessionId, mcpServers) {
|
|
8539
|
-
if (this.v2)
|
|
8540
|
-
return;
|
|
8541
7342
|
setTimeout(() => {
|
|
8542
7343
|
this.sendAvailableCommandsUpdate(sessionId);
|
|
8543
7344
|
void this.publishCurrentSubagentStates(sessionId);
|
|
8544
7345
|
startMcpAuthentication(this, sessionId, mcpServers);
|
|
8545
7346
|
}, 0);
|
|
8546
7347
|
}
|
|
8547
|
-
/**
|
|
8548
|
-
* Starts OAuth in the background for the servers of `mcpServers` that
|
|
8549
|
-
* Claude Code reports as needing it, which sends the client a URL
|
|
8550
|
-
* elicitation. The v2 surface calls it after the setup response, since v2
|
|
8551
|
-
* asks for no elicitation before the `session/new` response.
|
|
8552
|
-
*/
|
|
8553
|
-
authenticateMcpServers(sessionId, mcpServers) {
|
|
8554
|
-
startMcpAuthentication(this, sessionId, mcpServers);
|
|
8555
|
-
}
|
|
8556
7348
|
/**
|
|
8557
7349
|
* Sends the current state of each subagent that the last load of
|
|
8558
7350
|
* `sessionId` replayed (see {@link RfdSubagentReplay.currentStates}). Run it
|
|
@@ -8621,21 +7413,12 @@ export class ClaudeAcpAgent {
|
|
|
8621
7413
|
});
|
|
8622
7414
|
}
|
|
8623
7415
|
/**
|
|
8624
|
-
* Refine a heuristic context window with `getContextUsage().rawMaxTokens
|
|
8625
|
-
* without blocking the caller. The text heuristic
|
|
8626
|
-
* whose picker rows carry no "1m" token (e.g.
|
|
8627
|
-
* 2.1.283 `opus`/`default`), so those would
|
|
8628
|
-
* first result's modelUsage arrives.
|
|
8629
|
-
*
|
|
8630
|
-
* Never awaited: SDK control requests are serialized, so awaiting here
|
|
8631
|
-
* would delay session/new or a model switch (~15s on older CLIs, issues
|
|
8632
|
-
* #886/#880; ~0.5s on 2.1.283). Requests the `summary` detail instead of
|
|
8633
|
-
* the default `full` breakdown, which issues one `messages/count_tokens`
|
|
8634
|
-
* call per category (~18 for a bare session) and hit rate limits on every
|
|
8635
|
-
* model switch; `summary` answers locally with the same `rawMaxTokens`.
|
|
8636
|
-
*
|
|
8637
|
-
* Does not write `contextWindowCache` (that stays keyed to the
|
|
8638
|
-
* `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.
|
|
8639
7422
|
*/
|
|
8640
7423
|
refreshContextWindowInBackground(sessionId, session) {
|
|
8641
7424
|
if (session.contextWindowAuthoritative)
|
|
@@ -8647,13 +7430,13 @@ export class ClaudeAcpAgent {
|
|
|
8647
7430
|
session.models.currentModelId === modelId;
|
|
8648
7431
|
// A synchronous throw must not fail the caller either.
|
|
8649
7432
|
Promise.resolve()
|
|
8650
|
-
.then(() => query
|
|
8651
|
-
.then((
|
|
7433
|
+
.then(() => readContextWindow(query))
|
|
7434
|
+
.then((window) => {
|
|
8652
7435
|
if (!stillCurrent() || session.contextWindowAuthoritative)
|
|
8653
7436
|
return;
|
|
8654
|
-
if (
|
|
7437
|
+
if (window === undefined)
|
|
8655
7438
|
return;
|
|
8656
|
-
session.contextWindowSize =
|
|
7439
|
+
session.contextWindowSize = window;
|
|
8657
7440
|
session.contextWindowAuthoritative = true;
|
|
8658
7441
|
}, (error) => {
|
|
8659
7442
|
if (stillCurrent())
|
|
@@ -8695,30 +7478,18 @@ export class ClaudeAcpAgent {
|
|
|
8695
7478
|
session.fastModeDisabledReason = undefined;
|
|
8696
7479
|
}
|
|
8697
7480
|
// Rebuild config options since effort levels depend on the selected
|
|
8698
|
-
// model
|
|
8699
|
-
// made through the ACP picker this session lives at the SDK's flag
|
|
8700
|
-
// layer and follows the session across switches, so carry it forward.
|
|
8701
|
-
// Otherwise the CLI resolves effort itself from the persisted settings
|
|
8702
|
-
// — the NEW model's `modelSettings` entry first (the CLI persists
|
|
8703
|
-
// /effort per model), then the legacy top-level value — so display
|
|
8704
|
-
// what it will actually run instead of dragging the old model's value
|
|
8705
|
-
// along.
|
|
7481
|
+
// model (see `effortForModelSwitch`).
|
|
8706
7482
|
const effortOpt = session.configOptions.find((o) => o.id === EFFORT_CONFIG_ID);
|
|
8707
|
-
const currentEffort = typeof effortOpt?.currentValue === "string" ? effortOpt.currentValue : undefined;
|
|
8708
7483
|
const useRecommendedValue = clientSupportsRecommendedConfigValue(this.clientCapabilities);
|
|
8709
|
-
const
|
|
8710
|
-
|
|
8711
|
-
|
|
8712
|
-
|
|
8713
|
-
|
|
8714
|
-
|
|
8715
|
-
|
|
8716
|
-
|
|
8717
|
-
|
|
8718
|
-
const seedEffort = effortPinnedForNewModel
|
|
8719
|
-
? pinnedEffort
|
|
8720
|
-
: settingsEffortForModel(mergeEffortSettings(session.settingsManager.getSettings(), session.effortSettingsOverride), newModelInfo, value);
|
|
8721
|
-
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, {
|
|
8722
7493
|
// The toggle follows the newly selected model: it disappears when the
|
|
8723
7494
|
// model lacks fast support and reappears (with the retained user
|
|
8724
7495
|
// intent) when a supporting model is selected again.
|
|
@@ -8735,60 +7506,16 @@ export class ClaudeAcpAgent {
|
|
|
8735
7506
|
enabled: session.ultracodeEnabled,
|
|
8736
7507
|
useBooleanOption: clientSupportsBooleanConfigOptions(this.clientCapabilities),
|
|
8737
7508
|
});
|
|
8738
|
-
//
|
|
8739
|
-
//
|
|
8740
|
-
//
|
|
8741
|
-
//
|
|
8742
|
-
|
|
8743
|
-
|
|
8744
|
-
|
|
8745
|
-
|
|
8746
|
-
|
|
8747
|
-
|
|
8748
|
-
const shouldSyncEffort = useRecommendedValue || (effortWasPinned && !effortPinnedForNewModel);
|
|
8749
|
-
if (shouldSyncEffort) {
|
|
8750
|
-
const newEffortOpt = session.configOptions.find((o) => o.id === EFFORT_CONFIG_ID);
|
|
8751
|
-
const newEffort = typeof newEffortOpt?.currentValue === "string" ? newEffortOpt.currentValue : undefined;
|
|
8752
|
-
try {
|
|
8753
|
-
await session.query.applyFlagSettings(
|
|
8754
|
-
// A legacy client's unpinned effort is display-only: the CLI
|
|
8755
|
-
// resolves the persisted value for the new model. When an old
|
|
8756
|
-
// user pin is no longer supported, clear the flag layer instead
|
|
8757
|
-
// of replacing it with that displayed value. Opted-in clients
|
|
8758
|
-
// deliberately apply their concrete displayed effort.
|
|
8759
|
-
effortFlagSettings(useRecommendedValue ? newEffort : undefined, session.ultracodeEnabled));
|
|
8760
|
-
session.effortPinnedLevel = effortPinnedForNewModel ? pinnedEffort : undefined;
|
|
8761
|
-
session.appliedEffortLevel =
|
|
8762
|
-
useRecommendedValue && newEffort !== "default" ? newEffort : undefined;
|
|
8763
|
-
}
|
|
8764
|
-
catch (error) {
|
|
8765
|
-
// setModel has already succeeded. Effort synchronization is a
|
|
8766
|
-
// secondary, best-effort operation: propagating this error would
|
|
8767
|
-
// make the RPC report failure (or suppress an external-switch
|
|
8768
|
-
// notification) even though the SDK is already on the new model.
|
|
8769
|
-
// Preserve the old SDK/pin bookkeeping and never advertise the
|
|
8770
|
-
// unapplied value: restore the last applied value when the new model
|
|
8771
|
-
// can select it, otherwise omit the effort option until a later
|
|
8772
|
-
// successful switch rebuilds it.
|
|
8773
|
-
session.effortPinnedLevel = pinnedEffort;
|
|
8774
|
-
session.appliedEffortLevel = appliedEffortBeforeSwitch;
|
|
8775
|
-
const appliedValueStillSelectable = appliedEffortBeforeSwitch !== undefined &&
|
|
8776
|
-
newEffortOpt?.type === "select" &&
|
|
8777
|
-
newEffortOpt.options.some((option) => "value" in option
|
|
8778
|
-
? option.value === appliedEffortBeforeSwitch
|
|
8779
|
-
: option.options.some((nested) => nested.value === appliedEffortBeforeSwitch));
|
|
8780
|
-
if (newEffortOpt?.type === "select" && appliedValueStillSelectable) {
|
|
8781
|
-
newEffortOpt.currentValue = appliedEffortBeforeSwitch;
|
|
8782
|
-
}
|
|
8783
|
-
else {
|
|
8784
|
-
session.configOptions = session.configOptions.filter((option) => option.id !== EFFORT_CONFIG_ID);
|
|
8785
|
-
}
|
|
8786
|
-
this.logger.error(`Failed to synchronize effort after model switch to "${value}":`, error);
|
|
8787
|
-
}
|
|
8788
|
-
}
|
|
8789
|
-
else if (effortPinnedForNewModel) {
|
|
8790
|
-
session.effortPinnedLevel = pinnedEffort;
|
|
8791
|
-
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);
|
|
8792
7519
|
}
|
|
8793
7520
|
// Emit current_mode_update only after session.modes AND
|
|
8794
7521
|
// session.configOptions have been fully reconciled. This way, a failure
|
|
@@ -8896,58 +7623,28 @@ export class ClaudeAcpAgent {
|
|
|
8896
7623
|
* `fast_mode_state` (delivered on `system`/init and on user-turn `result`s).
|
|
8897
7624
|
* The SDK can flip fast mode independently of the user — e.g. back to `on`
|
|
8898
7625
|
* once a rate-limit `cooldown` clears — so we mirror definitive on/off
|
|
8899
|
-
* changes into the config option and notify the client
|
|
7626
|
+
* changes into the config option and notify the client (see
|
|
7627
|
+
* {@link fastModeStateChange}).
|
|
8900
7628
|
*
|
|
8901
|
-
*
|
|
8902
|
-
*
|
|
8903
|
-
*
|
|
8904
|
-
*
|
|
8905
|
-
*
|
|
8906
|
-
* reselected (the source of the earlier intent-clobber bug was mutating it
|
|
8907
|
-
* here).
|
|
8908
|
-
* - `cooldown`: a transient suspension of an already-enabled fast mode.
|
|
8909
|
-
* Leave the toggle as-is rather than flapping it — and never let a stray
|
|
8910
|
-
* cooldown spuriously enable a toggle the user has off.
|
|
8911
|
-
*
|
|
8912
|
-
* `reason` is the SDK's `fast_mode_disabled_reason`, reported alongside the
|
|
8913
|
-
* state. Only explainable reasons are retained (see
|
|
8914
|
-
* {@link normalizeFastModeDisabledReason}), so the comparison below tracks
|
|
8915
|
-
* exactly what the user can see: a routine `sdk_opt_in_required` report on
|
|
8916
|
-
* every turn's result can't churn the option, while a real blocker updates
|
|
8917
|
-
* 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). */
|
|
8918
7634
|
async syncFastModeState(sessionId, session, state, reason) {
|
|
8919
|
-
if (state === undefined) {
|
|
8920
|
-
return;
|
|
8921
|
-
}
|
|
8922
7635
|
if (!session.configOptions.some((o) => o.id === FAST_MODE_CONFIG_ID)) {
|
|
8923
7636
|
return;
|
|
8924
7637
|
}
|
|
8925
|
-
|
|
8926
|
-
|
|
8927
|
-
}
|
|
8928
|
-
const enabled = state === "on";
|
|
8929
|
-
// A reason only describes an off state; drop any that rides an `on` report
|
|
8930
|
-
// so it can't decorate the option the next time fast mode goes off.
|
|
8931
|
-
const nextReason = enabled ? undefined : normalizeFastModeDisabledReason(reason);
|
|
8932
|
-
if (enabled === session.fastModeEnabled && nextReason === session.fastModeDisabledReason) {
|
|
7638
|
+
const change = fastModeStateChange({ enabled: session.fastModeEnabled, disabledReason: session.fastModeDisabledReason }, state, reason);
|
|
7639
|
+
if (!change)
|
|
8933
7640
|
return;
|
|
8934
|
-
|
|
8935
|
-
|
|
8936
|
-
|
|
8937
|
-
|
|
8938
|
-
const explanation = nextReason !== undefined ? FAST_MODE_UNAVAILABLE_EXPLANATIONS[nextReason] : undefined;
|
|
8939
|
-
const explain = session.fastModeEnabled && !enabled && explanation !== undefined;
|
|
8940
|
-
session.fastModeEnabled = enabled;
|
|
8941
|
-
session.fastModeDisabledReason = nextReason;
|
|
8942
|
-
this.refreshFastModeOption(session, enabled);
|
|
8943
|
-
if (explain) {
|
|
7641
|
+
session.fastModeEnabled = change.enabled;
|
|
7642
|
+
session.fastModeDisabledReason = change.disabledReason;
|
|
7643
|
+
this.refreshFastModeOption(session, change.enabled);
|
|
7644
|
+
if (change.notice) {
|
|
8944
7645
|
await this.client.sessionUpdate({
|
|
8945
7646
|
sessionId,
|
|
8946
|
-
update: noticeOrTranscriptUpdate(
|
|
8947
|
-
severity: "warning",
|
|
8948
|
-
title: "Fast mode turned off",
|
|
8949
|
-
description: `${sentenceCase(explanation)}.`,
|
|
8950
|
-
}, clientSupportsNotices(this.clientCapabilities), `**Fast mode turned off:** ${explanation}.`),
|
|
7647
|
+
update: noticeOrTranscriptUpdate(change.notice.notice, clientSupportsNotices(this.clientCapabilities), change.notice.transcript),
|
|
8951
7648
|
});
|
|
8952
7649
|
}
|
|
8953
7650
|
await this.client.sessionUpdate({
|
|
@@ -9093,57 +7790,9 @@ export class ClaudeAcpAgent {
|
|
|
9093
7790
|
});
|
|
9094
7791
|
await settingsManager.initialize();
|
|
9095
7792
|
timing.phase("settings");
|
|
9096
|
-
const mcpServers =
|
|
9097
|
-
if (Array.isArray(params.mcpServers)) {
|
|
9098
|
-
for (const server of params.mcpServers) {
|
|
9099
|
-
if ("type" in server && (server.type === "http" || server.type === "sse")) {
|
|
9100
|
-
// HTTP or SSE type MCP server
|
|
9101
|
-
mcpServers[server.name] = {
|
|
9102
|
-
type: server.type,
|
|
9103
|
-
url: server.url,
|
|
9104
|
-
headers: server.headers
|
|
9105
|
-
? Object.fromEntries(server.headers.map((e) => [e.name, e.value]))
|
|
9106
|
-
: undefined,
|
|
9107
|
-
};
|
|
9108
|
-
}
|
|
9109
|
-
else if (!("type" in server)) {
|
|
9110
|
-
// Stdio type MCP server (with or without explicit type field)
|
|
9111
|
-
mcpServers[server.name] = {
|
|
9112
|
-
type: "stdio",
|
|
9113
|
-
command: server.command,
|
|
9114
|
-
args: server.args,
|
|
9115
|
-
env: server.env
|
|
9116
|
-
? Object.fromEntries(server.env.map((e) => [e.name, e.value]))
|
|
9117
|
-
: undefined,
|
|
9118
|
-
};
|
|
9119
|
-
}
|
|
9120
|
-
}
|
|
9121
|
-
}
|
|
7793
|
+
const mcpServers = sdkMcpServers(params.mcpServers);
|
|
9122
7794
|
const customInstructions = airCustomInstructions(params._meta);
|
|
9123
|
-
|
|
9124
|
-
? { type: "preset", preset: "claude_code" }
|
|
9125
|
-
: { type: "preset", preset: "claude_code", append: customInstructions };
|
|
9126
|
-
if (params._meta?.systemPrompt) {
|
|
9127
|
-
const customPrompt = params._meta.systemPrompt;
|
|
9128
|
-
if (typeof customPrompt === "string") {
|
|
9129
|
-
systemPrompt = customPrompt;
|
|
9130
|
-
}
|
|
9131
|
-
else if (typeof customPrompt === "object" &&
|
|
9132
|
-
customPrompt !== null &&
|
|
9133
|
-
!Array.isArray(customPrompt)) {
|
|
9134
|
-
// Forward all preset options (append, excludeDynamicSections, and
|
|
9135
|
-
// anything the SDK adds later) while locking type/preset.
|
|
9136
|
-
systemPrompt = {
|
|
9137
|
-
...customPrompt,
|
|
9138
|
-
type: "preset",
|
|
9139
|
-
preset: "claude_code",
|
|
9140
|
-
};
|
|
9141
|
-
}
|
|
9142
|
-
}
|
|
9143
|
-
// The spec's `systemPrompt` takes precedence over the `_meta.systemPrompt`
|
|
9144
|
-
// extension above.
|
|
9145
|
-
if (clientPrompt)
|
|
9146
|
-
systemPrompt = sdkSystemPrompt(clientPrompt, customInstructions);
|
|
7795
|
+
const systemPrompt = sessionSystemPrompt(clientPrompt, params._meta?.systemPrompt, customInstructions);
|
|
9147
7796
|
// Extract options from _meta if provided
|
|
9148
7797
|
const sessionMeta = params._meta;
|
|
9149
7798
|
// Bypass is off for root outside a sandbox, when settings disable it (the
|
|
@@ -9163,8 +7812,6 @@ export class ClaudeAcpAgent {
|
|
|
9163
7812
|
const forwardSubagentText = this.forwardsSubagentText(params._meta);
|
|
9164
7813
|
// Configure thinking behavior from environment variables
|
|
9165
7814
|
const thinking = resolveThinkingConfig(process.env.MAX_THINKING_TOKENS, process.env.CLAUDE_CODE_THINKING_DISPLAY, this.logger);
|
|
9166
|
-
// Parse model configuration from environment (e.g. Bedrock model overrides)
|
|
9167
|
-
const modelConfig = parseModelConfig(process.env.CLAUDE_MODEL_CONFIG);
|
|
9168
7815
|
// Elicitation modes the connected client advertised. We only forward
|
|
9169
7816
|
// elicitations (and only re-enable AskUserQuestion) for modes the client
|
|
9170
7817
|
// can actually render.
|
|
@@ -9219,13 +7866,8 @@ export class ClaudeAcpAgent {
|
|
|
9219
7866
|
// into the query.
|
|
9220
7867
|
const resolvedProvider = this.resolveProviderConfig();
|
|
9221
7868
|
const providerEnv = createEnvForProvider(resolvedProvider);
|
|
9222
|
-
|
|
9223
|
-
const
|
|
9224
|
-
? JSON.parse(await fs.readFile(path.resolve(params.cwd, providedSettings), "utf8"))
|
|
9225
|
-
: providedSettings;
|
|
9226
|
-
const configuredSettingsObject = modelConfig
|
|
9227
|
-
? { ...modelConfig, ...providedSettingsObject }
|
|
9228
|
-
: providedSettingsObject;
|
|
7869
|
+
// With the model configuration of the environment (e.g. Bedrock model overrides).
|
|
7870
|
+
const configuredSettingsObject = await configuredSettings(userProvidedOptions?.settings, params.cwd);
|
|
9229
7871
|
// Claude Code applies env from settings.json after the subprocess env. Put
|
|
9230
7872
|
// an active ACP route in the programmatic settings tier too so user/project
|
|
9231
7873
|
// settings cannot silently restore a different ANTHROPIC_BASE_URL.
|
|
@@ -9252,7 +7894,7 @@ export class ClaudeAcpAgent {
|
|
|
9252
7894
|
// SDK, so per-session `_meta` env routing and ambient process-env routing
|
|
9253
7895
|
// are distinguished exactly as the CLI will see them.
|
|
9254
7896
|
const providerCacheKey = providerCacheKeyFor(env);
|
|
9255
|
-
this.logger.log(`[session/query] sessionId=${sessionId} resume=${creationOpts?.resume ?? "none"} apiType=${resolvedProvider?.apiType ?? "native"} baseUrl=${resolvedProvider?.baseUrl
|
|
7897
|
+
this.logger.log(`[session/query] sessionId=${sessionId} resume=${creationOpts?.resume ?? "none"} apiType=${resolvedProvider?.apiType ?? "native"} baseUrl=${loggableBaseUrl(resolvedProvider?.baseUrl)}`);
|
|
9256
7898
|
// Both forms of native subagent sessions report the configuration of a child.
|
|
9257
7899
|
const subagentConfigHook = subagentForm(this.clientCapabilities)
|
|
9258
7900
|
? this.subagentConfigurationHook(sessionId)
|
|
@@ -9341,17 +7983,11 @@ export class ClaudeAcpAgent {
|
|
|
9341
7983
|
],
|
|
9342
7984
|
}
|
|
9343
7985
|
: {}),
|
|
9344
|
-
|
|
9345
|
-
// without a permission request (`fileChangePreviewHook`): a v2 diff
|
|
9346
|
-
// cannot hold the input's snippet.
|
|
9347
|
-
...(this.v2 || subagentConfigHook
|
|
7986
|
+
...(subagentConfigHook
|
|
9348
7987
|
? {
|
|
9349
7988
|
PreToolUse: [
|
|
9350
7989
|
...(userProvidedOptions?.hooks?.PreToolUse || []),
|
|
9351
|
-
|
|
9352
|
-
...(this.v2
|
|
9353
|
-
? [{ matcher: "Edit|Write", hooks: [this.fileChangePreviewHook(sessionId)] }]
|
|
9354
|
-
: []),
|
|
7990
|
+
{ hooks: [subagentConfigHook] },
|
|
9355
7991
|
],
|
|
9356
7992
|
}
|
|
9357
7993
|
: {}),
|
|
@@ -9472,8 +8108,8 @@ export class ClaudeAcpAgent {
|
|
|
9472
8108
|
prompt: input,
|
|
9473
8109
|
options,
|
|
9474
8110
|
});
|
|
9475
|
-
this.
|
|
9476
|
-
const authSettingsEpoch = this.
|
|
8111
|
+
this.authStatus.useSettings(settingsManager, configuredSettingsObject, userProvidedOptions?.env);
|
|
8112
|
+
const authSettingsEpoch = this.authStatus.epoch;
|
|
9477
8113
|
timing.phase("prepare-query");
|
|
9478
8114
|
// `query()` spawns the CLI at once. Any throw between here and the
|
|
9479
8115
|
// registration in `this.sessions` would leave that child process running
|
|
@@ -9496,8 +8132,8 @@ export class ClaudeAcpAgent {
|
|
|
9496
8132
|
// Publish the identity BEFORE the guard can refuse this session. A
|
|
9497
8133
|
// refusal is exactly when the client most needs to know which account it
|
|
9498
8134
|
// was refused for.
|
|
9499
|
-
if (authSettingsEpoch === this.
|
|
9500
|
-
this.
|
|
8135
|
+
if (authSettingsEpoch === this.authStatus.epoch) {
|
|
8136
|
+
this.authStatus.publishSessionAccount(initializationResult.account, settingsManager.getApiKeyHelper(configuredSettingsObject));
|
|
9501
8137
|
}
|
|
9502
8138
|
// Shared with the per-turn guard, so "warn once" spans the whole session.
|
|
9503
8139
|
const claudeSubscriptionGuard = {};
|
|
@@ -9545,41 +8181,9 @@ export class ClaudeAcpAgent {
|
|
|
9545
8181
|
const models = await getAvailableModels(q, allowedModels, initializationResult.models, settingsManager, this.logger, creationOpts.resume !== undefined, sessionId, resumedModel, resolvedProvider?.listedModels !== undefined);
|
|
9546
8182
|
timing.phase("models");
|
|
9547
8183
|
// Resolve the current model's capabilities separately from the stable
|
|
9548
|
-
// permission-mode catalog advertised to ACP clients
|
|
9549
|
-
//
|
|
9550
|
-
|
|
9551
|
-
// `matchResumedModel`); its capabilities are still known to the SDK's
|
|
9552
|
-
// unfiltered list, so fall back to that before treating the model as
|
|
9553
|
-
// unknown — otherwise auto mode would be spuriously clamped and the
|
|
9554
|
-
// Fast-mode/Effort options hidden for a model that supports them.
|
|
9555
|
-
const allowlistedModelInfo = allowedModels.find((m) => m.value === models.currentModelId);
|
|
9556
|
-
const fallbackModelInfo = allowlistedModelInfo
|
|
9557
|
-
? undefined
|
|
9558
|
-
: (resolveModelPreference(sdkModels, models.currentModelId) ?? undefined);
|
|
9559
|
-
const currentModelInfo = allowlistedModelInfo ?? fallbackModelInfo;
|
|
9560
|
-
// Register the fallback-resolved capabilities under the verbatim live id
|
|
9561
|
-
// so every modelInfos consumer (buildConfigOptions' effort lookup, later
|
|
9562
|
-
// rebuilds via session.modelInfos) agrees with the gating below.
|
|
9563
|
-
// `buildModelConfigOption` lists this model as its own entry while it is
|
|
9564
|
-
// current and drops it once the user switches to a listed model; it is
|
|
9565
|
-
// never added to `models.availableModels`. The spread keeps every capability flag
|
|
9566
|
-
// (current and future); the identity fields are overridden because the
|
|
9567
|
-
// fuzzy-matched sibling's resolvedModel/displayName/description can
|
|
9568
|
-
// describe a different context lane and would poison later resolvedModel
|
|
9569
|
-
// matching (syncModelAfterExternalSwitch) and context-window inference
|
|
9570
|
-
// (applyConfigOptionValue) if they traveled under this id.
|
|
9571
|
-
const modelInfos = fallbackModelInfo
|
|
9572
|
-
? [
|
|
9573
|
-
...allowedModels,
|
|
9574
|
-
{
|
|
9575
|
-
...fallbackModelInfo,
|
|
9576
|
-
value: models.currentModelId,
|
|
9577
|
-
displayName: models.currentModelId,
|
|
9578
|
-
description: "",
|
|
9579
|
-
resolvedModel: undefined,
|
|
9580
|
-
},
|
|
9581
|
-
]
|
|
9582
|
-
: allowedModels;
|
|
8184
|
+
// permission-mode catalog advertised to ACP clients (see
|
|
8185
|
+
// `withCurrentModelInfo`).
|
|
8186
|
+
const { allowlistedModelInfo, currentModelInfo, modelInfos } = withCurrentModelInfo(allowedModels, sdkModels, models.currentModelId);
|
|
9583
8187
|
const { modes, autoModeFallbackWarningPending } = await this.sessionModes.initialize({
|
|
9584
8188
|
query: q,
|
|
9585
8189
|
requestedMode: initialPermissionMode,
|
|
@@ -9721,9 +8325,8 @@ export class ClaudeAcpAgent {
|
|
|
9721
8325
|
emittedToolCalls: new Set(),
|
|
9722
8326
|
eagerToolCallSessions: new Map(),
|
|
9723
8327
|
liveBackgroundTasks: new Map(),
|
|
9724
|
-
background: new SessionBackgroundWork(sessionId
|
|
8328
|
+
background: new SessionBackgroundWork(sessionId),
|
|
9725
8329
|
stopsWorkflowsOnCancel: options.perTaskStopAffordance === true &&
|
|
9726
|
-
!this.backgroundWork.enabled &&
|
|
9727
8330
|
!clientSupportsAsyncTasks(this.clientCapabilities),
|
|
9728
8331
|
nativeSubagentsByTaskId: new Map(),
|
|
9729
8332
|
nativeSubagentTaskIdByToolUseId: new Map(),
|
|
@@ -9735,6 +8338,9 @@ export class ClaudeAcpAgent {
|
|
|
9735
8338
|
claudeSubscriptionGuard,
|
|
9736
8339
|
accountKind: fromAccountInfo(initializationResult.account, settingsManager.getApiKeyHelper(configuredSettingsObject))?.kind,
|
|
9737
8340
|
fileChangeReporter,
|
|
8341
|
+
...(this.toolCallCapabilities.air.client
|
|
8342
|
+
? { promptSuggestions: new PromptSuggestions() }
|
|
8343
|
+
: {}),
|
|
9738
8344
|
};
|
|
9739
8345
|
const registered = this.sessions[sessionId];
|
|
9740
8346
|
registered.idleCompaction = new IdleCompaction({
|
|
@@ -9751,7 +8357,6 @@ export class ClaudeAcpAgent {
|
|
|
9751
8357
|
// The CLI's own environment: process env, the client's and the provider's.
|
|
9752
8358
|
{ env });
|
|
9753
8359
|
timing.phase("register");
|
|
9754
|
-
this.backgroundWork.sync(sessionId, this.sessions[sessionId], this.foregroundState(sessionId));
|
|
9755
8360
|
this.refreshContextWindowInBackground(sessionId, this.sessions[sessionId]);
|
|
9756
8361
|
return {
|
|
9757
8362
|
sessionId,
|
|
@@ -9776,16 +8381,7 @@ export class ClaudeAcpAgent {
|
|
|
9776
8381
|
// and logout apply in the order they arrived. A failed listing fails this
|
|
9777
8382
|
// `providers/set` before the provider replaces the current one.
|
|
9778
8383
|
if (config) {
|
|
9779
|
-
|
|
9780
|
-
Object.assign(config, await this.listProviderModels(config));
|
|
9781
|
-
}
|
|
9782
|
-
catch (error) {
|
|
9783
|
-
if (error instanceof GatewayListingError) {
|
|
9784
|
-
throw RequestError.internalError({ providerId: PROVIDER_ID, apiType: config.apiType, baseUrl: config.baseUrl }, `Model discovery for provider "${PROVIDER_ID}" failed: ${error.message}`);
|
|
9785
|
-
}
|
|
9786
|
-
throw error;
|
|
9787
|
-
}
|
|
9788
|
-
this.logger.log(`[providers/set] listedModels=${config.listedModels?.length ?? "none"} bedrockRegionPrefix=${config.bedrockRegionPrefix ?? "none"}`);
|
|
8384
|
+
await withListedModels(config, this.providerConfig, this.logger);
|
|
9789
8385
|
}
|
|
9790
8386
|
const sessions = Object.entries(this.sessions);
|
|
9791
8387
|
const activeTurns = sessions.flatMap(([, session]) => (session.turnQueue ?? []).flatMap((turn) => (turn.completion ? [turn.completion] : [])));
|
|
@@ -10059,19 +8655,6 @@ function servesCancelledWork(session, status) {
|
|
|
10059
8655
|
function turnQuotaMeta(session) {
|
|
10060
8656
|
return quotaMeta(session.accumulatedUsage, session.accumulatedModelUsage);
|
|
10061
8657
|
}
|
|
10062
|
-
/** `_meta.quota` for work that spent `usage` in its main agent loop and
|
|
10063
|
-
* `modelUsage` by model (see {@link turnQuotaMeta}). */
|
|
10064
|
-
function quotaMeta(usage, modelUsage) {
|
|
10065
|
-
return {
|
|
10066
|
-
quota: {
|
|
10067
|
-
token_count: quotaTokenCount(usage),
|
|
10068
|
-
model_usage: Object.entries(modelUsage ?? {}).map(([model, usage]) => ({
|
|
10069
|
-
model,
|
|
10070
|
-
token_count: quotaTokenCount(usage),
|
|
10071
|
-
})),
|
|
10072
|
-
},
|
|
10073
|
-
};
|
|
10074
|
-
}
|
|
10075
8658
|
/** Whether a request that awaits the user for the subagent `agentID` (absent
|
|
10076
8659
|
* for the main conversation) blocks the session's foreground work. The main
|
|
10077
8660
|
* conversation's requests do. So do those of a subagent that runs in the
|
|
@@ -10100,158 +8683,9 @@ function blocksForeground(session, agentID) {
|
|
|
10100
8683
|
}
|
|
10101
8684
|
/** Whether Claude Code ended the work of `result` because an interrupt
|
|
10102
8685
|
* stopped it, while the model streamed or while a tool ran. */
|
|
10103
|
-
function isAbortedResult(result) {
|
|
8686
|
+
export function isAbortedResult(result) {
|
|
10104
8687
|
return (result.terminal_reason === "aborted_streaming" || result.terminal_reason === "aborted_tools");
|
|
10105
8688
|
}
|
|
10106
|
-
/** How a model cycle that Claude Code started on its own ended, read from its
|
|
10107
|
-
* result as a turn's is: a refusal, the token limit, and the turn and budget
|
|
10108
|
-
* limits are their stop reasons, an error result fails the cycle, and a
|
|
10109
|
-
* cancel ends it `cancelled`. The usage and `_meta.quota` are the result's
|
|
10110
|
-
* own, `modelUsage` its increment by model, since autonomous results stay out
|
|
10111
|
-
* of the turn tally. */
|
|
10112
|
-
function autonomousCycleEnd(result, modelUsage, cancelled) {
|
|
10113
|
-
// Typed non-null, but third-party backends have been observed omitting
|
|
10114
|
-
// usage token fields (see snapshotFromUsage).
|
|
10115
|
-
const tally = {
|
|
10116
|
-
inputTokens: result.usage.input_tokens ?? 0,
|
|
10117
|
-
outputTokens: result.usage.output_tokens ?? 0,
|
|
10118
|
-
cachedReadTokens: result.usage.cache_read_input_tokens ?? 0,
|
|
10119
|
-
cachedWriteTokens: result.usage.cache_creation_input_tokens ?? 0,
|
|
10120
|
-
};
|
|
10121
|
-
const ended = (stopReason) => ({
|
|
10122
|
-
outcome: {
|
|
10123
|
-
stopReason,
|
|
10124
|
-
usage: { ...tally, totalTokens: tallyTotal(tally) },
|
|
10125
|
-
_meta: quotaMeta(tally, modelUsage),
|
|
10126
|
-
},
|
|
10127
|
-
});
|
|
10128
|
-
if (cancelled)
|
|
10129
|
-
return ended("cancelled");
|
|
10130
|
-
if (result.stop_reason === "refusal")
|
|
10131
|
-
return ended("refusal");
|
|
10132
|
-
if (result.stop_reason === "max_tokens")
|
|
10133
|
-
return ended("max_tokens");
|
|
10134
|
-
if (result.is_error) {
|
|
10135
|
-
const text = result.subtype === "success" ? result.result : result.errors.join(", ") || result.subtype;
|
|
10136
|
-
return { error: RequestError.internalError(undefined, text) };
|
|
10137
|
-
}
|
|
10138
|
-
return ended(result.subtype === "success" || result.subtype === "error_during_execution"
|
|
10139
|
-
? "end_turn"
|
|
10140
|
-
: "max_turn_requests");
|
|
10141
|
-
}
|
|
10142
|
-
/** One `token_count` object. `cachedInputTokens` is cache reads, matching
|
|
10143
|
-
* codex's field; Claude also reports cache writes, which codex has no slot
|
|
10144
|
-
* for, so those ride along in an extra sibling (the same name the ACP `usage`
|
|
10145
|
-
* field already uses) and are counted in `totalTokens`. `reasoningOutputTokens`
|
|
10146
|
-
* is always 0: Claude bills thinking inside its output tokens and never breaks
|
|
10147
|
-
* it out — the key is kept so the shape stays uniform across agents. */
|
|
10148
|
-
function quotaTokenCount(usage) {
|
|
10149
|
-
return {
|
|
10150
|
-
totalTokens: tallyTotal(usage),
|
|
10151
|
-
inputTokens: usage.inputTokens,
|
|
10152
|
-
cachedInputTokens: usage.cachedReadTokens,
|
|
10153
|
-
cachedWriteTokens: usage.cachedWriteTokens,
|
|
10154
|
-
outputTokens: usage.outputTokens,
|
|
10155
|
-
reasoningOutputTokens: 0,
|
|
10156
|
-
};
|
|
10157
|
-
}
|
|
10158
|
-
/** Sum a tally's four counters. Per the Anthropic API `inputTokens` excludes
|
|
10159
|
-
* the cache counters, so this is not double-counting (see `totalTokens`). */
|
|
10160
|
-
function tallyTotal(usage) {
|
|
10161
|
-
return usage.inputTokens + usage.outputTokens + usage.cachedReadTokens + usage.cachedWriteTokens;
|
|
10162
|
-
}
|
|
10163
|
-
/** Project `result.modelUsage` into our tally shape. Counters are coerced the
|
|
10164
|
-
* way `snapshotFromUsage` coerces the stream's: third-party backends have been
|
|
10165
|
-
* observed omitting fields, and a missing or NaN counter must not reach the
|
|
10166
|
-
* wire as NaN (which `JSON.stringify` writes as `null`). */
|
|
10167
|
-
function normalizeModelUsage(modelUsage) {
|
|
10168
|
-
const tally = {};
|
|
10169
|
-
for (const [model, usage] of Object.entries(modelUsage ?? {})) {
|
|
10170
|
-
tally[model] = {
|
|
10171
|
-
inputTokens: finiteCount(usage?.inputTokens),
|
|
10172
|
-
outputTokens: finiteCount(usage?.outputTokens),
|
|
10173
|
-
cachedReadTokens: finiteCount(usage?.cacheReadInputTokens),
|
|
10174
|
-
cachedWriteTokens: finiteCount(usage?.cacheCreationInputTokens),
|
|
10175
|
-
};
|
|
10176
|
-
}
|
|
10177
|
-
return tally;
|
|
10178
|
-
}
|
|
10179
|
-
function finiteCount(value) {
|
|
10180
|
-
return typeof value === "number" && Number.isFinite(value) ? value : 0;
|
|
10181
|
-
}
|
|
10182
|
-
/** `current - previous` per model, dropping models with nothing to report so a
|
|
10183
|
-
* turn only lists the models it actually ran on. A reading that fell BELOW the
|
|
10184
|
-
* previous one means the running total restarted under us (a mid-session
|
|
10185
|
-
* /clear, a zeroed crash result): there is no usable reference left to
|
|
10186
|
-
* subtract, so the reading itself is the increment. */
|
|
10187
|
-
function modelUsageIncrement(current, previous) {
|
|
10188
|
-
const increment = {};
|
|
10189
|
-
for (const [model, usage] of Object.entries(current)) {
|
|
10190
|
-
const base = previous[model];
|
|
10191
|
-
const subtracted = base
|
|
10192
|
-
? {
|
|
10193
|
-
inputTokens: usage.inputTokens - base.inputTokens,
|
|
10194
|
-
outputTokens: usage.outputTokens - base.outputTokens,
|
|
10195
|
-
cachedReadTokens: usage.cachedReadTokens - base.cachedReadTokens,
|
|
10196
|
-
cachedWriteTokens: usage.cachedWriteTokens - base.cachedWriteTokens,
|
|
10197
|
-
}
|
|
10198
|
-
: usage;
|
|
10199
|
-
const rewound = Object.values(subtracted).some((count) => count < 0);
|
|
10200
|
-
const resolved = rewound ? usage : subtracted;
|
|
10201
|
-
if (tallyTotal(resolved) > 0) {
|
|
10202
|
-
increment[model] = resolved;
|
|
10203
|
-
}
|
|
10204
|
-
}
|
|
10205
|
-
return increment;
|
|
10206
|
-
}
|
|
10207
|
-
/** The per-model rows for the first result of a resumed session. Its
|
|
10208
|
-
* `modelUsage` reading continues from the totals the transcript saved (SDK
|
|
10209
|
-
* 0.3.277+; older transcripts may hold none), so there is no earlier reading
|
|
10210
|
-
* to subtract from, and taking the reading itself would charge the whole
|
|
10211
|
-
* pre-resume history to this one turn. The result's own `usage` is per-turn
|
|
10212
|
-
* (main agent loop only, like the response's `usage`), so it stands in under
|
|
10213
|
-
* the turn's top-level model — `key` is that model's `modelUsage` spelling
|
|
10214
|
-
* when the reading has one, else the assistant message's own. Any subagent
|
|
10215
|
-
* spend on this one turn goes unlisted rather than over-listed. */
|
|
10216
|
-
function resumedFirstResultModelUsage(usage, key) {
|
|
10217
|
-
if (key === null) {
|
|
10218
|
-
return {};
|
|
10219
|
-
}
|
|
10220
|
-
const row = {
|
|
10221
|
-
inputTokens: finiteCount(usage.input_tokens),
|
|
10222
|
-
outputTokens: finiteCount(usage.output_tokens),
|
|
10223
|
-
cachedReadTokens: finiteCount(usage.cache_read_input_tokens),
|
|
10224
|
-
cachedWriteTokens: finiteCount(usage.cache_creation_input_tokens),
|
|
10225
|
-
};
|
|
10226
|
-
return tallyTotal(row) > 0 ? { [key]: row } : {};
|
|
10227
|
-
}
|
|
10228
|
-
/** Fold `increment` into `base` per model — the per-model counterpart of the
|
|
10229
|
-
* `+=` the turn's flat accumulator uses. */
|
|
10230
|
-
function addModelUsage(base, increment) {
|
|
10231
|
-
const merged = { ...base };
|
|
10232
|
-
for (const [model, usage] of Object.entries(increment)) {
|
|
10233
|
-
const existing = merged[model];
|
|
10234
|
-
merged[model] = existing
|
|
10235
|
-
? {
|
|
10236
|
-
inputTokens: existing.inputTokens + usage.inputTokens,
|
|
10237
|
-
outputTokens: existing.outputTokens + usage.outputTokens,
|
|
10238
|
-
cachedReadTokens: existing.cachedReadTokens + usage.cachedReadTokens,
|
|
10239
|
-
cachedWriteTokens: existing.cachedWriteTokens + usage.cachedWriteTokens,
|
|
10240
|
-
}
|
|
10241
|
-
: usage;
|
|
10242
|
-
}
|
|
10243
|
-
return merged;
|
|
10244
|
-
}
|
|
10245
|
-
/** Sum all four fields as a proxy for post-turn context occupancy: the current
|
|
10246
|
-
* turn's output becomes next turn's input. Per the Anthropic API, input_tokens
|
|
10247
|
-
* excludes cache tokens — cache_read and cache_creation are reported
|
|
10248
|
-
* separately — so summing all four is not double-counting. */
|
|
10249
|
-
function totalTokens(usage) {
|
|
10250
|
-
return (usage.input_tokens +
|
|
10251
|
-
usage.output_tokens +
|
|
10252
|
-
usage.cache_read_input_tokens +
|
|
10253
|
-
usage.cache_creation_input_tokens);
|
|
10254
|
-
}
|
|
10255
8689
|
/**
|
|
10256
8690
|
* Build the `data` payload attached to a `RequestError.internalError` when we
|
|
10257
8691
|
* have a categorical error — from the Claude SDK, or one of the adapter's own
|
|
@@ -10265,309 +8699,7 @@ function totalTokens(usage) {
|
|
|
10265
8699
|
function errorKindData(errorKind) {
|
|
10266
8700
|
return errorKind ? { errorKind } : undefined;
|
|
10267
8701
|
}
|
|
10268
|
-
|
|
10269
|
-
* Both SDK message_start and assistant message `usage` have `number | null`
|
|
10270
|
-
* cache fields; we coerce absent values to 0 so `totalTokens` never hits
|
|
10271
|
-
* NaN. `input_tokens`/`output_tokens` are typed `number` by the SDK but
|
|
10272
|
-
* synthetic or third-party-backend stream events have been observed emitting
|
|
10273
|
-
* them as null/undefined — coerce those too so a malformed upstream event
|
|
10274
|
-
* can't leak NaN into the wire `used` field. Delta events have different
|
|
10275
|
-
* semantics (cumulative + prev fallback) and are handled inline. */
|
|
10276
|
-
function snapshotFromUsage(usage) {
|
|
10277
|
-
return {
|
|
10278
|
-
input_tokens: usage.input_tokens ?? 0,
|
|
10279
|
-
output_tokens: usage.output_tokens ?? 0,
|
|
10280
|
-
cache_read_input_tokens: usage.cache_read_input_tokens ?? 0,
|
|
10281
|
-
cache_creation_input_tokens: usage.cache_creation_input_tokens ?? 0,
|
|
10282
|
-
};
|
|
10283
|
-
}
|
|
10284
|
-
/**
|
|
10285
|
-
* Adapt a legacy gateway `authenticate` request into the shared
|
|
10286
|
-
* {@link ProviderConfig} shape. Returns `null` when no gateway request is
|
|
10287
|
-
* present. `methodId` selects the protocol: `gateway-bedrock` → bedrock,
|
|
10288
|
-
* otherwise anthropic.
|
|
10289
|
-
*/
|
|
10290
|
-
function gatewayRequestToProviderConfig(request) {
|
|
10291
|
-
// `authenticate` validates the payload before it stores one, so a stored
|
|
10292
|
-
// request always carries a usable gateway. Re-check the shape here anyway:
|
|
10293
|
-
// this function decides whether a provider override is active, and the
|
|
10294
|
-
// `--hide-claude-auth` guard is off while one is.
|
|
10295
|
-
const gateway = request?._meta?.gateway;
|
|
10296
|
-
if (!gateway || !isValidBaseUrl(gateway.baseUrl)) {
|
|
10297
|
-
return null;
|
|
10298
|
-
}
|
|
10299
|
-
return {
|
|
10300
|
-
apiType: request?.methodId === "gateway-bedrock" ? "bedrock" : "anthropic",
|
|
10301
|
-
baseUrl: gateway.baseUrl,
|
|
10302
|
-
headers: gateway.headers ?? {},
|
|
10303
|
-
};
|
|
10304
|
-
}
|
|
10305
|
-
/**
|
|
10306
|
-
* Map a resolved provider config into the Claude Code env vars that redirect API
|
|
10307
|
-
* traffic and inject headers. Returns an empty object when routing is
|
|
10308
|
-
* unconfigured. The token/bypass placeholders (`" "`) are required so the CLI
|
|
10309
|
-
* skips its normal login/credential checks when a gateway is in use.
|
|
10310
|
-
*/
|
|
10311
|
-
function createEnvForProvider(config) {
|
|
10312
|
-
if (!config) {
|
|
10313
|
-
return {};
|
|
10314
|
-
}
|
|
10315
|
-
const resetRouting = {
|
|
10316
|
-
ANTHROPIC_BASE_URL: "",
|
|
10317
|
-
ANTHROPIC_BEDROCK_BASE_URL: "",
|
|
10318
|
-
ANTHROPIC_VERTEX_BASE_URL: "",
|
|
10319
|
-
CLAUDE_CODE_USE_BEDROCK: "0",
|
|
10320
|
-
CLAUDE_CODE_USE_VERTEX: "0",
|
|
10321
|
-
ANTHROPIC_VERTEX_PROJECT_ID: "",
|
|
10322
|
-
CLOUD_ML_REGION: "",
|
|
10323
|
-
AWS_REGION: "",
|
|
10324
|
-
ANTHROPIC_API_KEY: "",
|
|
10325
|
-
ANTHROPIC_AUTH_TOKEN: "",
|
|
10326
|
-
CLAUDE_CODE_OAUTH_TOKEN: "",
|
|
10327
|
-
};
|
|
10328
|
-
const customHeaders = Object.entries(config.headers)
|
|
10329
|
-
.map(([key, value]) => `${key}: ${value}`)
|
|
10330
|
-
.join("\n");
|
|
10331
|
-
if (config.apiType === "bedrock") {
|
|
10332
|
-
return {
|
|
10333
|
-
...resetRouting,
|
|
10334
|
-
CLAUDE_CODE_USE_BEDROCK: "1",
|
|
10335
|
-
AWS_BEARER_TOKEN_BEDROCK: PROVIDER_AUTH_TOKEN_PLACEHOLDER, // Bypass local AWS credential checks
|
|
10336
|
-
ANTHROPIC_BEDROCK_BASE_URL: config.baseUrl,
|
|
10337
|
-
ANTHROPIC_CUSTOM_HEADERS: customHeaders,
|
|
10338
|
-
...(config.bedrockRegionPrefix
|
|
10339
|
-
? { ANTHROPIC_BEDROCK_REGION_PREFIX: config.bedrockRegionPrefix }
|
|
10340
|
-
: {}),
|
|
10341
|
-
};
|
|
10342
|
-
}
|
|
10343
|
-
if (config.apiType === "vertex") {
|
|
10344
|
-
// `config.vertex` is guaranteed present for vertex by `unstable_setProvider`
|
|
10345
|
-
// validation; fall back to empty strings defensively.
|
|
10346
|
-
// Leaving ANTHROPIC_VERTEX_BASE_URL empty for the default endpoint lets
|
|
10347
|
-
// Claude Code use its native Vertex endpoint/model resolution. Supplying
|
|
10348
|
-
// even the default host marks the session as a custom Vertex deployment and
|
|
10349
|
-
// can hide otherwise-valid models.
|
|
10350
|
-
return {
|
|
10351
|
-
...resetRouting,
|
|
10352
|
-
CLAUDE_CODE_USE_VERTEX: "1",
|
|
10353
|
-
...(config.baseUrl !== DEFAULT_VERTEX_BASE_URL
|
|
10354
|
-
? { ANTHROPIC_VERTEX_BASE_URL: config.baseUrl }
|
|
10355
|
-
: {}),
|
|
10356
|
-
ANTHROPIC_VERTEX_PROJECT_ID: config.vertex?.projectId ?? "",
|
|
10357
|
-
CLOUD_ML_REGION: config.vertex?.region ?? "",
|
|
10358
|
-
ANTHROPIC_CUSTOM_HEADERS: customHeaders,
|
|
10359
|
-
};
|
|
10360
|
-
}
|
|
10361
|
-
return {
|
|
10362
|
-
...resetRouting,
|
|
10363
|
-
ANTHROPIC_BASE_URL: config.baseUrl,
|
|
10364
|
-
ANTHROPIC_CUSTOM_HEADERS: customHeaders,
|
|
10365
|
-
ANTHROPIC_AUTH_TOKEN: PROVIDER_AUTH_TOKEN_PLACEHOLDER, // Bypass local Claude login checks
|
|
10366
|
-
};
|
|
10367
|
-
}
|
|
10368
|
-
function sameHeaders(a, b) {
|
|
10369
|
-
const aKeys = Object.keys(a);
|
|
10370
|
-
return aKeys.length === Object.keys(b).length && aKeys.every((key) => b[key] === a[key]);
|
|
10371
|
-
}
|
|
10372
|
-
/**
|
|
10373
|
-
* Validate a provider base URL: must be a non-empty absolute http(s) URL.
|
|
10374
|
-
*/
|
|
10375
|
-
function isValidBaseUrl(baseUrl) {
|
|
10376
|
-
if (typeof baseUrl !== "string" || baseUrl.trim() === "") {
|
|
10377
|
-
return false;
|
|
10378
|
-
}
|
|
10379
|
-
let parsed;
|
|
10380
|
-
try {
|
|
10381
|
-
parsed = new URL(baseUrl);
|
|
10382
|
-
}
|
|
10383
|
-
catch {
|
|
10384
|
-
return false;
|
|
10385
|
-
}
|
|
10386
|
-
return parsed.protocol === "http:" || parsed.protocol === "https:";
|
|
10387
|
-
}
|
|
10388
|
-
// `supportedAgents()` always returns Claude Code's built-in subagents — the
|
|
10389
|
-
// ones used for Task-tool delegation (Explore, Plan, etc.) — even when the user
|
|
10390
|
-
// has configured none of their own. Those aren't meaningful *main-thread*
|
|
10391
|
-
// personas, so we filter them out and only surface the Agent picker when the
|
|
10392
|
-
// user (or a plugin/project) has configured custom agents. Update this set if
|
|
10393
|
-
// the SDK's built-in roster changes.
|
|
10394
|
-
export const BUILTIN_AGENT_NAMES = new Set([
|
|
10395
|
-
"claude",
|
|
10396
|
-
"general-purpose",
|
|
10397
|
-
"Explore",
|
|
10398
|
-
"Plan",
|
|
10399
|
-
"statusline-setup",
|
|
10400
|
-
]);
|
|
10401
|
-
// Value of the synthetic "Default" entry in the agent picker, which maps to the
|
|
10402
|
-
// standard Claude Code agent (`applyFlagSettings({ agent: null })`). It is a
|
|
10403
|
-
// reserved sentinel: a custom agent named exactly this would collide with it
|
|
10404
|
-
// (two options sharing the value, selection silently routing to `null`), so we
|
|
10405
|
-
// exclude that name from discovery.
|
|
10406
|
-
/** Discover user/plugin/project-configured main-thread agents, excluding the
|
|
10407
|
-
* built-in subagents and the reserved "default" sentinel. Returns an empty
|
|
10408
|
-
* list if discovery fails so a flaky control request never blocks session
|
|
10409
|
-
* creation. */
|
|
10410
|
-
export async function discoverCustomAgents(q) {
|
|
10411
|
-
try {
|
|
10412
|
-
const agents = await q.supportedAgents();
|
|
10413
|
-
return agents.filter((a) => !BUILTIN_AGENT_NAMES.has(a.name) && a.name !== DEFAULT_AGENT_ID);
|
|
10414
|
-
}
|
|
10415
|
-
catch {
|
|
10416
|
-
return [];
|
|
10417
|
-
}
|
|
10418
|
-
}
|
|
10419
|
-
/** Stable ids for the session config options surfaced via `configOptions`.
|
|
10420
|
-
* Centralized so the option declarations in `buildConfigOptions` and the
|
|
10421
|
-
* handlers in `setSessionConfigOption`/`applyConfigOptionValue` reference the
|
|
10422
|
-
* same identifiers and can't drift apart. */
|
|
10423
|
-
export { MODE_CONFIG_ID };
|
|
10424
|
-
export const AGENT_CONFIG_ID = "agent";
|
|
10425
|
-
export const FAST_MODE_CONFIG_ID = "fast";
|
|
10426
|
-
/** Select-fallback values used when the client has not opted into boolean
|
|
10427
|
-
* config options (see {@link createFastModeConfigOption}). */
|
|
10428
|
-
export const FAST_MODE_ON = "on";
|
|
10429
|
-
export const FAST_MODE_OFF = "off";
|
|
10430
|
-
const FAST_MODE_DESCRIPTION = "Faster responses on supported models";
|
|
10431
|
-
/** Map the SDK's tri-state `fast_mode_state` onto the boolean config toggle.
|
|
10432
|
-
* `cooldown` (fast mode temporarily suspended after a rate limit, per the SDK
|
|
10433
|
-
* docs) keeps the toggle on so it reflects the user's intent — only an
|
|
10434
|
-
* explicit `off` clears it. */
|
|
10435
|
-
export function fastModeStateEnabled(state) {
|
|
10436
|
-
return state !== "off";
|
|
10437
|
-
}
|
|
10438
|
-
/** User-facing explanations for the SDK's `fast_mode_disabled_reason` values
|
|
10439
|
-
* that a user can act on (or at least wants to know about). Deliberately
|
|
10440
|
-
* partial — the omitted reasons are not worth surfacing:
|
|
10441
|
-
* - `sdk_opt_in_required`: every SDK session starts here (the toggle IS the
|
|
10442
|
-
* opt-in), so it describes the default, not a problem.
|
|
10443
|
-
* - `preference`: the user turned Fast mode off themselves.
|
|
10444
|
-
* - `pending`: eligibility is still resolving; the next report supersedes it.
|
|
10445
|
-
* - `unknown`: nothing meaningful to say.
|
|
10446
|
-
* Unknown future reasons fall through the same way (open set — the SDK's docs
|
|
10447
|
-
* say to ignore values you don't handle). */
|
|
10448
|
-
const FAST_MODE_UNAVAILABLE_EXPLANATIONS = {
|
|
10449
|
-
free: "not available on the free plan",
|
|
10450
|
-
extra_usage_disabled: "requires extra usage to be enabled for this account",
|
|
10451
|
-
model_not_allowed: "not available for the selected model",
|
|
10452
|
-
not_first_party: "not available on this API provider",
|
|
10453
|
-
disabled_by_env: "disabled by environment configuration",
|
|
10454
|
-
network_error: "eligibility could not be verified (network error)",
|
|
10455
|
-
};
|
|
10456
|
-
/** Normalize an SDK-reported `fast_mode_disabled_reason` to the one we retain:
|
|
10457
|
-
* a reason we have an explanation for, else `undefined`. Keeping only
|
|
10458
|
-
* explainable reasons means state comparisons (see `syncFastModeState`) track
|
|
10459
|
-
* exactly what the user can see, so routine reports like
|
|
10460
|
-
* `sdk_opt_in_required` never churn the config option. */
|
|
10461
|
-
export function normalizeFastModeDisabledReason(reason) {
|
|
10462
|
-
return reason && FAST_MODE_UNAVAILABLE_EXPLANATIONS[reason] ? reason : undefined;
|
|
10463
|
-
}
|
|
10464
|
-
/** Whether the Client advertised support for boolean session config options
|
|
10465
|
-
* (`session.configOptions.boolean`). Agents MUST only send `type: "boolean"`
|
|
10466
|
-
* config options to Clients that opt in; otherwise we fall back to a `select`.
|
|
10467
|
-
* See https://agentclientprotocol.com/rfds/boolean-config-option. */
|
|
10468
|
-
export function clientSupportsBooleanConfigOptions(clientCapabilities) {
|
|
10469
|
-
return clientCapabilities?.session?.configOptions?.boolean != null;
|
|
10470
|
-
}
|
|
10471
|
-
/** Whether the Client advertised the AIR `recommendedValue` capability for
|
|
10472
|
-
* select-style model and effort options. Missing or malformed AIR metadata
|
|
10473
|
-
* retains the legacy `default` entries. */
|
|
10474
|
-
export function clientSupportsRecommendedConfigValue(clientCapabilities) {
|
|
10475
|
-
return clientSupportsAirCapability(clientCapabilities, AIR_RECOMMENDED_CONFIG_VALUE_CAPABILITY);
|
|
10476
|
-
}
|
|
10477
|
-
/** Build the Fast mode config option. When the Client supports boolean config
|
|
10478
|
-
* options we expose a native `type: "boolean"` toggle; otherwise we degrade to
|
|
10479
|
-
* a two-value `select` ("on"/"off") so older Clients still get a usable
|
|
10480
|
-
* control.
|
|
10481
|
-
*
|
|
10482
|
-
* `disabledReason` (the SDK's `fast_mode_disabled_reason`) is folded into the
|
|
10483
|
-
* description while the toggle reads off, so a user whose account or provider
|
|
10484
|
-
* can't serve Fast mode sees why instead of a switch that silently refuses to
|
|
10485
|
-
* stay on. Ignored while enabled: a reason reported alongside an `on`/`cooldown`
|
|
10486
|
-
* state isn't blocking anything right now. */
|
|
10487
|
-
export function createFastModeConfigOption(enabled, useBooleanOption, disabledReason) {
|
|
10488
|
-
const explanation = enabled
|
|
10489
|
-
? undefined
|
|
10490
|
-
: disabledReason && FAST_MODE_UNAVAILABLE_EXPLANATIONS[disabledReason];
|
|
10491
|
-
const base = {
|
|
10492
|
-
id: FAST_MODE_CONFIG_ID,
|
|
10493
|
-
name: "Fast mode",
|
|
10494
|
-
description: explanation ? `${FAST_MODE_DESCRIPTION} — ${explanation}` : FAST_MODE_DESCRIPTION,
|
|
10495
|
-
category: "model_config",
|
|
10496
|
-
};
|
|
10497
|
-
if (useBooleanOption) {
|
|
10498
|
-
return { ...base, type: "boolean", currentValue: enabled };
|
|
10499
|
-
}
|
|
10500
|
-
return {
|
|
10501
|
-
...base,
|
|
10502
|
-
type: "select",
|
|
10503
|
-
currentValue: enabled ? FAST_MODE_ON : FAST_MODE_OFF,
|
|
10504
|
-
options: [
|
|
10505
|
-
{ value: FAST_MODE_ON, name: "On" },
|
|
10506
|
-
{ value: FAST_MODE_OFF, name: "Off" },
|
|
10507
|
-
],
|
|
10508
|
-
};
|
|
10509
|
-
}
|
|
10510
|
-
/** Resolve the requested Fast mode value from a `session/set_config_option`
|
|
10511
|
-
* request. Accepts a native boolean (boolean-capable Clients) or the
|
|
10512
|
-
* "on"/"off" select-fallback strings. */
|
|
10513
|
-
export function resolveFastModeEnabled(params) {
|
|
10514
|
-
const value = params.value;
|
|
10515
|
-
if (typeof value === "boolean") {
|
|
10516
|
-
return value;
|
|
10517
|
-
}
|
|
10518
|
-
if (value === FAST_MODE_ON) {
|
|
10519
|
-
return true;
|
|
10520
|
-
}
|
|
10521
|
-
if (value === FAST_MODE_OFF) {
|
|
10522
|
-
return false;
|
|
10523
|
-
}
|
|
10524
|
-
throw RequestError.invalidParams(undefined, `Invalid value for config option ${FAST_MODE_CONFIG_ID}: ${value}`);
|
|
10525
|
-
}
|
|
10526
|
-
export function buildConfigOptions(modes, models, modelInfos, currentEffortLevel, agents = [], currentAgent = DEFAULT_AGENT_ID, fastMode, presentation, ultracode) {
|
|
10527
|
-
const options = [SessionModeManager.configOption(modes)];
|
|
10528
|
-
// A gateway that lists none of the SDK's models leaves no model to offer, so
|
|
10529
|
-
// there is no model option at all.
|
|
10530
|
-
if (models.availableModels.length > 0) {
|
|
10531
|
-
options.push(buildModelConfigOption(models, modelInfos, presentation?.useRecommendedValue === true));
|
|
10532
|
-
}
|
|
10533
|
-
const effort = buildEffortConfigOption(modelInfos, models.currentModelId, currentEffortLevel, presentation?.useRecommendedValue === true);
|
|
10534
|
-
if (effort)
|
|
10535
|
-
options.push(effort);
|
|
10536
|
-
// Surface the Fast mode toggle only when the current model supports it. The
|
|
10537
|
-
// option renders as a native boolean toggle for Clients that opted in, and a
|
|
10538
|
-
// two-value select otherwise.
|
|
10539
|
-
if (fastMode?.supported) {
|
|
10540
|
-
options.push(createFastModeConfigOption(fastMode.enabled, fastMode.useBooleanOption, fastMode.disabledReason));
|
|
10541
|
-
}
|
|
10542
|
-
// Surface the ultracode toggle only while the CLI can run it: dynamic
|
|
10543
|
-
// workflows are enabled and the current model supports it.
|
|
10544
|
-
if (ultracode?.supported) {
|
|
10545
|
-
options.push(createUltracodeConfigOption(ultracode.enabled, ultracode.useBooleanOption));
|
|
10546
|
-
}
|
|
10547
|
-
// Only surface the Agent picker when there's a real choice — i.e. the user
|
|
10548
|
-
// has configured at least one custom agent (built-ins are filtered out in
|
|
10549
|
-
// discoverCustomAgents). With none configured, "Default" would be the only
|
|
10550
|
-
// entry, so we omit the option entirely.
|
|
10551
|
-
if (agents.length > 0) {
|
|
10552
|
-
options.push({
|
|
10553
|
-
id: AGENT_CONFIG_ID,
|
|
10554
|
-
name: "Agent",
|
|
10555
|
-
description: "Main-thread agent persona",
|
|
10556
|
-
type: "select",
|
|
10557
|
-
currentValue: currentAgent,
|
|
10558
|
-
options: [
|
|
10559
|
-
{ value: DEFAULT_AGENT_ID, name: "Default", description: "Standard Claude Code agent" },
|
|
10560
|
-
...agents.map((a) => ({
|
|
10561
|
-
value: a.name,
|
|
10562
|
-
name: a.name,
|
|
10563
|
-
description: a.description || undefined,
|
|
10564
|
-
})),
|
|
10565
|
-
],
|
|
10566
|
-
});
|
|
10567
|
-
}
|
|
10568
|
-
return options;
|
|
10569
|
-
}
|
|
10570
|
-
function getAvailableSlashCommands(commands,
|
|
8702
|
+
export function getAvailableSlashCommands(commands,
|
|
10571
8703
|
// Names the CLI tagged terminal-bound on `system`/init (their UX lives in
|
|
10572
8704
|
// the CLI's own terminal, which ACP clients aren't) — filtered alongside
|
|
10573
8705
|
// the static list. Raw CLI names, matched before the MCP rename.
|
|
@@ -11502,185 +9634,6 @@ export function runAcp(logger) {
|
|
|
11502
9634
|
const connection = v1AgentApp(logger, (created) => (agent = created)).connect(stream);
|
|
11503
9635
|
return { connection, agent };
|
|
11504
9636
|
}
|
|
11505
|
-
function commonPrefixLength(a, b) {
|
|
11506
|
-
let i = 0;
|
|
11507
|
-
while (i < a.length && i < b.length && a[i] === b[i]) {
|
|
11508
|
-
i++;
|
|
11509
|
-
}
|
|
11510
|
-
return i;
|
|
11511
|
-
}
|
|
11512
|
-
/** Best-effort first guess of a model's context window, used to seed the
|
|
11513
|
-
* window synchronously (via `immediateContextWindow`) until a `result` message
|
|
11514
|
-
* arrives with the authoritative `modelUsage` value.
|
|
11515
|
-
*
|
|
11516
|
-
* Anthropic 1M-context variants encode "1m" as a distinct token in the SDK
|
|
11517
|
-
* model ID (e.g., "claude-opus-4-6-1m"), which `\b1m\b` catches without also
|
|
11518
|
-
* matching things like "10m" or embedded substrings. Semantic aliases like
|
|
11519
|
-
* `default` carry no such token in the ID, but their `resolvedModel` and the
|
|
11520
|
-
* SDK's human-facing `displayName`/`description` can (e.g.
|
|
11521
|
-
* "claude-opus-4-8[1m]", "Opus 4.7 (1M context)"), so callers pass those too.
|
|
11522
|
-
* This text scan can't catch every model — some resolve to extended-context
|
|
11523
|
-
* models with no "1m" anywhere (e.g. `sonnet` → claude-sonnet-5, natively
|
|
11524
|
-
* ~1M). Such a miss falls back to the default window, is refined by the
|
|
11525
|
-
* background `getContextUsage` (`refreshContextWindowInBackground`), and is
|
|
11526
|
-
* corrected by `result.modelUsage` (and cached) within one turn. */
|
|
11527
|
-
function inferContextWindowFromModel(...texts) {
|
|
11528
|
-
if (texts.some((text) => text != null && /\b1m\b/i.test(text)))
|
|
11529
|
-
return 1_000_000;
|
|
11530
|
-
return null;
|
|
11531
|
-
}
|
|
11532
|
-
/** Cross-session cache of authoritative context windows, keyed by
|
|
11533
|
-
* `${providerCacheKey}\0${modelId}` (see {@link contextWindowCacheKey}).
|
|
11534
|
-
* The window is a property of (model id, backend): the same resolved model id
|
|
11535
|
-
* (e.g. "claude-sonnet-5[1m]", the spelling of the `result.modelUsage` keys)
|
|
11536
|
-
* can name different context lanes behind different base URLs, routing
|
|
11537
|
-
* headers, or credentials, so the key carries both. Caching it module-level
|
|
11538
|
-
* lets a later session/new or switch that resolves to the same (backend,
|
|
11539
|
-
* model) — in this session or any other, within the adapter's lifetime — seed
|
|
11540
|
-
* the correct window synchronously with no IPC. Keying on the resolved id
|
|
11541
|
-
* (rather than the picker value) means aliases that resolve to the same
|
|
11542
|
-
* concrete model share one entry; the result handler additionally writes the
|
|
11543
|
-
* bare assistant-message spelling so seed-time reads that fall back to a
|
|
11544
|
-
* verbatim live id (rows without `resolvedModel`) can hit too.
|
|
11545
|
-
*
|
|
11546
|
-
* Populated authoritatively by each `result.modelUsage` a turn confirms (see
|
|
11547
|
-
* the consumer's result handler). We deliberately never populate it from
|
|
11548
|
-
* `getContextUsage`: its `model` spelling and `rawMaxTokens` can differ from
|
|
11549
|
-
* the `result.modelUsage` key and window (e.g. 967000 vs 1000000 for sonnet),
|
|
11550
|
-
* so it only refines the live session (`refreshContextWindowInBackground`).
|
|
11551
|
-
* Cleared on `logout`: 1M-context entitlement can differ per account/tier, so
|
|
11552
|
-
* windows learned under one login must not seed sessions under the next. */
|
|
11553
|
-
const contextWindowCache = new Map();
|
|
11554
|
-
/** The env vars that determine which LLM backend — and which context lane on
|
|
11555
|
-
* it — a query's API traffic reaches: endpoint selection (base URLs and the
|
|
11556
|
-
* Bedrock/Vertex switches with their project/region), routing/beta headers
|
|
11557
|
-
* (an `anthropic-beta: context-1m-…` header flips the same model id at the
|
|
11558
|
-
* same endpoint between context lanes), and credential identity (extended
|
|
11559
|
-
* context is entitlement-gated per account). Used to derive the
|
|
11560
|
-
* provider-cache key from the exact env a query is created with, so
|
|
11561
|
-
* `providers/set` config, per-session `_meta` env overrides, and ambient
|
|
11562
|
-
* process env are all distinguished exactly as the CLI will see them. */
|
|
11563
|
-
const PROVIDER_ROUTING_ENV_VARS = [
|
|
11564
|
-
"ANTHROPIC_BASE_URL",
|
|
11565
|
-
"ANTHROPIC_BEDROCK_BASE_URL",
|
|
11566
|
-
"ANTHROPIC_VERTEX_BASE_URL",
|
|
11567
|
-
"CLAUDE_CODE_USE_BEDROCK",
|
|
11568
|
-
"CLAUDE_CODE_USE_VERTEX",
|
|
11569
|
-
"ANTHROPIC_VERTEX_PROJECT_ID",
|
|
11570
|
-
"CLOUD_ML_REGION",
|
|
11571
|
-
"AWS_REGION",
|
|
11572
|
-
"ANTHROPIC_CUSTOM_HEADERS",
|
|
11573
|
-
"ANTHROPIC_API_KEY",
|
|
11574
|
-
"ANTHROPIC_AUTH_TOKEN",
|
|
11575
|
-
"CLAUDE_CODE_OAUTH_TOKEN",
|
|
11576
|
-
];
|
|
11577
|
-
/** Stable identifier for the LLM backend a session's query is created against,
|
|
11578
|
-
* used to scope {@link contextWindowCache} per backend. Positional `\0`-join
|
|
11579
|
-
* of {@link PROVIDER_ROUTING_ENV_VARS} values, so no segment can masquerade
|
|
11580
|
-
* as another and unset vars everywhere yield one stable "default" bucket.
|
|
11581
|
-
* Header/credential values can be secrets; the key only ever lives as an
|
|
11582
|
-
* in-memory Map key and is never logged or surfaced. Over-keying is the safe
|
|
11583
|
-
* side: a var change that didn't really change the backend costs one cache
|
|
11584
|
-
* miss (heuristic seed until the next result), while under-keying would serve
|
|
11585
|
-
* one backend's window for another's. */
|
|
11586
|
-
function providerCacheKeyFor(env) {
|
|
11587
|
-
return PROVIDER_ROUTING_ENV_VARS.map((name) => env[name] ?? "").join("\0");
|
|
11588
|
-
}
|
|
11589
|
-
/** Compose the `contextWindowCache` key from a session's provider key and a
|
|
11590
|
-
* model id. `\0`-joined so the model segment can't collide with a provider
|
|
11591
|
-
* segment. */
|
|
11592
|
-
function contextWindowCacheKey(providerCacheKey, modelId) {
|
|
11593
|
-
return `${providerCacheKey}\0${modelId}`;
|
|
11594
|
-
}
|
|
11595
|
-
function cacheContextWindow(modelKey, window) {
|
|
11596
|
-
if (window > 0) {
|
|
11597
|
-
contextWindowCache.set(modelKey, window);
|
|
11598
|
-
}
|
|
11599
|
-
}
|
|
11600
|
-
/** The context window to report *right now* for a model, with NO IPC on the
|
|
11601
|
-
* critical path: the cached authoritative value if we've learned it (from a
|
|
11602
|
-
* prior turn's `result.modelUsage`, this or any session on the same backend),
|
|
11603
|
-
* else the text heuristic over the model row's identity strings, else the
|
|
11604
|
-
* default. Derives the cache key itself — `modelInfo?.resolvedModel ?? modelId`,
|
|
11605
|
-
* the same rule at every seed site — so read keys can't drift from the write
|
|
11606
|
-
* site's spelling. `authoritative` reports whether the value came from the
|
|
11607
|
-
* cache: an authoritative window can legitimately equal
|
|
11608
|
-
* DEFAULT_CONTEXT_WINDOW, so the value alone can't tell the caller. */
|
|
11609
|
-
function immediateContextWindow(providerCacheKey, modelId, modelInfo) {
|
|
11610
|
-
const cached = contextWindowCache.get(contextWindowCacheKey(providerCacheKey, modelInfo?.resolvedModel ?? modelId));
|
|
11611
|
-
if (cached !== undefined)
|
|
11612
|
-
return { size: cached, authoritative: true };
|
|
11613
|
-
return {
|
|
11614
|
-
size: inferContextWindowFromModel(modelId, modelInfo?.resolvedModel, modelInfo?.displayName, modelInfo?.description) ?? DEFAULT_CONTEXT_WINDOW,
|
|
11615
|
-
authoritative: false,
|
|
11616
|
-
};
|
|
11617
|
-
}
|
|
11618
|
-
/** Translate the legacy `MAX_THINKING_TOKENS` env var, plus the optional
|
|
11619
|
-
* `CLAUDE_CODE_THINKING_DISPLAY` env var, into the SDK's `thinking` option.
|
|
11620
|
-
* The `maxThinkingTokens` option it used to feed is deprecated and reduced
|
|
11621
|
-
* to on/off on current models, so map the value to explicit thinking config
|
|
11622
|
-
* instead: unset → `undefined` (SDK default, adaptive on models that support
|
|
11623
|
-
* it) unless a display mode is requested, in which case it becomes explicit
|
|
11624
|
-
* `adaptive`; `0` → disabled; a positive integer → a fixed token budget.
|
|
11625
|
-
* Anything else is ignored with a warning. `CLAUDE_CODE_THINKING_DISPLAY`
|
|
11626
|
-
* must be `summarized` or `omitted`; it has no effect when thinking is
|
|
11627
|
-
* disabled. */
|
|
11628
|
-
function resolveThinkingConfig(rawTokens, rawDisplay, logger) {
|
|
11629
|
-
let display;
|
|
11630
|
-
if (rawDisplay !== undefined) {
|
|
11631
|
-
if (rawDisplay === "summarized" || rawDisplay === "omitted") {
|
|
11632
|
-
display = rawDisplay;
|
|
11633
|
-
}
|
|
11634
|
-
else {
|
|
11635
|
-
logger.error(`Ignoring CLAUDE_CODE_THINKING_DISPLAY: expected 'summarized' or 'omitted', got '${rawDisplay}'.`);
|
|
11636
|
-
}
|
|
11637
|
-
}
|
|
11638
|
-
if (rawTokens === undefined) {
|
|
11639
|
-
return display ? { type: "adaptive", display } : undefined;
|
|
11640
|
-
}
|
|
11641
|
-
const parsed = Number.parseInt(rawTokens, 10);
|
|
11642
|
-
if (Number.isNaN(parsed) || parsed < 0) {
|
|
11643
|
-
logger.error(`Ignoring MAX_THINKING_TOKENS: expected a non-negative integer, got '${rawTokens}'.`);
|
|
11644
|
-
return display ? { type: "adaptive", display } : undefined;
|
|
11645
|
-
}
|
|
11646
|
-
return parsed === 0
|
|
11647
|
-
? { type: "disabled" }
|
|
11648
|
-
: { type: "enabled", budgetTokens: parsed, ...(display && { display }) };
|
|
11649
|
-
}
|
|
11650
|
-
function parseModelConfig(raw) {
|
|
11651
|
-
if (!raw)
|
|
11652
|
-
return undefined;
|
|
11653
|
-
const parsed = JSON.parse(raw);
|
|
11654
|
-
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
11655
|
-
throw new Error("CLAUDE_MODEL_CONFIG must be a JSON object");
|
|
11656
|
-
}
|
|
11657
|
-
const result = {};
|
|
11658
|
-
if (parsed.modelOverrides !== undefined)
|
|
11659
|
-
result.modelOverrides = parsed.modelOverrides;
|
|
11660
|
-
if (parsed.availableModels !== undefined)
|
|
11661
|
-
result.availableModels = parsed.availableModels;
|
|
11662
|
-
return Object.keys(result).length > 0 ? result : undefined;
|
|
11663
|
-
}
|
|
11664
|
-
function getMatchingModelUsage(modelUsage, currentModel) {
|
|
11665
|
-
let bestKey = null;
|
|
11666
|
-
let bestLen = 0;
|
|
11667
|
-
for (const key of Object.keys(modelUsage)) {
|
|
11668
|
-
const len = commonPrefixLength(key, currentModel);
|
|
11669
|
-
if (len > bestLen) {
|
|
11670
|
-
bestLen = len;
|
|
11671
|
-
bestKey = key;
|
|
11672
|
-
}
|
|
11673
|
-
}
|
|
11674
|
-
if (bestKey) {
|
|
11675
|
-
// `bestKey` is the SDK's resolved model id (e.g. "claude-sonnet-5[1m]"),
|
|
11676
|
-
// the same spelling as ModelInfo.resolvedModel — the primary key the
|
|
11677
|
-
// window is cached under. `currentModel` (the assistant message's
|
|
11678
|
-
// `.model`) can be the bare form (e.g. "claude-sonnet-5"); the result
|
|
11679
|
-
// handler caches under that spelling too, for seed-time reads that fall
|
|
11680
|
-
// back to a bare id (rows without `resolvedModel`).
|
|
11681
|
-
return { key: bestKey, usage: modelUsage[bestKey] };
|
|
11682
|
-
}
|
|
11683
|
-
}
|
|
11684
9637
|
/**
|
|
11685
9638
|
* What a `command_lifecycle` "started" frame says started the command: a
|
|
11686
9639
|
* ScheduleWakeup (dynamic `/loop`) wakeup, with the time it was set for in
|