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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/dist/acp-agent.d.ts +1 -1812
  2. package/dist/acp-agent.d.ts.map +1 -1
  3. package/dist/acp-agent.js +3 -9657
  4. package/dist/acp-client.d.ts +28 -0
  5. package/dist/acp-client.d.ts.map +1 -0
  6. package/dist/hide-claude-auth.d.ts +3 -3
  7. package/dist/hide-claude-auth.js +3 -3
  8. package/dist/idle-compaction.d.ts +1 -1
  9. package/dist/idle-compaction.js +1 -1
  10. package/dist/lib.d.ts +5 -1
  11. package/dist/lib.d.ts.map +1 -1
  12. package/dist/lib.js +3 -1
  13. package/dist/logger.d.ts +10 -0
  14. package/dist/logger.d.ts.map +1 -0
  15. package/dist/logger.js +1 -0
  16. package/dist/message-filters.d.ts +43 -0
  17. package/dist/message-filters.d.ts.map +1 -0
  18. package/dist/message-filters.js +197 -0
  19. package/dist/new-session-meta.d.ts +40 -0
  20. package/dist/new-session-meta.d.ts.map +1 -0
  21. package/dist/new-session-meta.js +1 -0
  22. package/dist/prompt-to-claude.d.ts +10 -0
  23. package/dist/prompt-to-claude.d.ts.map +1 -0
  24. package/dist/prompt-to-claude.js +120 -0
  25. package/dist/result-end.d.ts +33 -4
  26. package/dist/result-end.d.ts.map +1 -1
  27. package/dist/result-end.js +34 -0
  28. package/dist/sdk-to-acp.d.ts +93 -0
  29. package/dist/sdk-to-acp.d.ts.map +1 -0
  30. package/dist/sdk-to-acp.js +635 -0
  31. package/dist/serve.d.ts +2 -1
  32. package/dist/serve.d.ts.map +1 -1
  33. package/dist/serve.js +1 -1
  34. package/dist/session-titles.d.ts +1 -1
  35. package/dist/session-titles.js +1 -1
  36. package/dist/session-usage.d.ts +1 -1
  37. package/dist/session-usage.d.ts.map +1 -1
  38. package/dist/session-usage.js +1 -1
  39. package/dist/slash-commands.d.ts +10 -0
  40. package/dist/slash-commands.d.ts.map +1 -0
  41. package/dist/slash-commands.js +99 -0
  42. package/dist/task-notifications.d.ts +2 -2
  43. package/dist/task-notifications.js +2 -2
  44. package/dist/utils.d.ts +1 -1
  45. package/dist/utils.d.ts.map +1 -1
  46. package/dist/v1/acp-agent.d.ts +1610 -0
  47. package/dist/v1/acp-agent.d.ts.map +1 -0
  48. package/dist/v1/acp-agent.js +8600 -0
  49. package/dist/{background-work.d.ts → v1/background-work.d.ts} +1 -1
  50. package/dist/v1/background-work.d.ts.map +1 -0
  51. package/dist/v1/goal-extension.d.ts.map +1 -0
  52. package/dist/v1/session-index/activity.d.ts.map +1 -0
  53. package/dist/v1/session-index/archive-title.d.ts.map +1 -0
  54. package/dist/v1/session-index/background-tasks.d.ts.map +1 -0
  55. package/dist/{session-index → v1/session-index}/background-tasks.js +1 -1
  56. package/dist/{session-index → v1/session-index}/connection.d.ts +3 -1
  57. package/dist/v1/session-index/connection.d.ts.map +1 -0
  58. package/dist/{session-index → v1/session-index}/connection.js +1 -1
  59. package/dist/v1/session-index/dir-listing.d.ts.map +1 -0
  60. package/dist/v1/session-index/first-prompt.d.ts.map +1 -0
  61. package/dist/v1/session-index/list-subscriptions.d.ts.map +1 -0
  62. package/dist/v1/session-index/live-registry.d.ts.map +1 -0
  63. package/dist/{session-index → v1/session-index}/live-registry.js +1 -1
  64. package/dist/v1/session-index/project-dirs.d.ts.map +1 -0
  65. package/dist/{session-index → v1/session-index}/project-dirs.js +1 -1
  66. package/dist/v1/session-index/service.d.ts.map +1 -0
  67. package/dist/{session-index → v1/session-index}/service.js +2 -2
  68. package/dist/v1/session-index/session-index.d.ts.map +1 -0
  69. package/dist/{session-index → v1/session-index}/session-index.js +1 -1
  70. package/dist/v1/session-index/session-info.d.ts.map +1 -0
  71. package/dist/{session-index → v1/session-index}/session-info.js +1 -1
  72. package/dist/v1/session-index/transcript-scan.d.ts.map +1 -0
  73. package/dist/v1/session-index/worktrees.d.ts.map +1 -0
  74. package/dist/v1/tool-calls/changed-meta-filter.d.ts.map +1 -0
  75. package/dist/v1/turn-events.d.ts.map +1 -0
  76. package/dist/v1/turn-events.js +1 -0
  77. package/dist/v2/agent.d.ts +1 -1
  78. package/dist/v2/agent.d.ts.map +1 -1
  79. package/dist/v2/agent.js +1 -1
  80. package/dist/v2/auth.d.ts +1 -1
  81. package/dist/v2/auth.d.ts.map +1 -1
  82. package/dist/v2/commands.js +1 -1
  83. package/dist/v2/config.d.ts +1 -1
  84. package/dist/v2/config.d.ts.map +1 -1
  85. package/dist/v2/elicitation.d.ts +1 -1
  86. package/dist/v2/elicitation.d.ts.map +1 -1
  87. package/dist/v2/file-preview.d.ts +1 -1
  88. package/dist/v2/file-preview.d.ts.map +1 -1
  89. package/dist/v2/outcome.d.ts.map +1 -1
  90. package/dist/v2/outcome.js +2 -1
  91. package/dist/v2/remote-control.d.ts +1 -1
  92. package/dist/v2/remote-control.d.ts.map +1 -1
  93. package/dist/v2/reports.d.ts +1 -1
  94. package/dist/v2/reports.d.ts.map +1 -1
  95. package/dist/v2/restarts.d.ts +1 -1
  96. package/dist/v2/restarts.d.ts.map +1 -1
  97. package/dist/v2/session.d.ts +1 -1
  98. package/dist/v2/session.d.ts.map +1 -1
  99. package/dist/v2/session.js +2 -1
  100. package/dist/v2/setup.d.ts +1 -1
  101. package/dist/v2/setup.d.ts.map +1 -1
  102. package/dist/v2/stopped-work.js +1 -1
  103. package/dist/v2/stream.d.ts +3 -2
  104. package/dist/v2/stream.d.ts.map +1 -1
  105. package/dist/v2/stream.js +2 -1
  106. package/dist/v2/subagent-replay.d.ts +1 -1
  107. package/dist/v2/subagent-replay.d.ts.map +1 -1
  108. package/dist/v2/subscription-guard.d.ts +1 -1
  109. package/dist/v2/subscription-guard.d.ts.map +1 -1
  110. package/dist/v2/tasks.d.ts +1 -1
  111. package/dist/v2/tasks.d.ts.map +1 -1
  112. package/package.json +1 -1
  113. package/dist/background-work.d.ts.map +0 -1
  114. package/dist/goal-extension.d.ts.map +0 -1
  115. package/dist/session-index/activity.d.ts.map +0 -1
  116. package/dist/session-index/archive-title.d.ts.map +0 -1
  117. package/dist/session-index/background-tasks.d.ts.map +0 -1
  118. package/dist/session-index/connection.d.ts.map +0 -1
  119. package/dist/session-index/dir-listing.d.ts.map +0 -1
  120. package/dist/session-index/first-prompt.d.ts.map +0 -1
  121. package/dist/session-index/list-subscriptions.d.ts.map +0 -1
  122. package/dist/session-index/live-registry.d.ts.map +0 -1
  123. package/dist/session-index/project-dirs.d.ts.map +0 -1
  124. package/dist/session-index/service.d.ts.map +0 -1
  125. package/dist/session-index/session-index.d.ts.map +0 -1
  126. package/dist/session-index/session-info.d.ts.map +0 -1
  127. package/dist/session-index/transcript-scan.d.ts.map +0 -1
  128. package/dist/session-index/worktrees.d.ts.map +0 -1
  129. package/dist/tool-calls/changed-meta-filter.d.ts.map +0 -1
  130. package/dist/turn-events.d.ts.map +0 -1
  131. /package/dist/{turn-events.js → acp-client.js} +0 -0
  132. /package/dist/{background-work.js → v1/background-work.js} +0 -0
  133. /package/dist/{goal-extension.d.ts → v1/goal-extension.d.ts} +0 -0
  134. /package/dist/{goal-extension.js → v1/goal-extension.js} +0 -0
  135. /package/dist/{session-index → v1/session-index}/activity.d.ts +0 -0
  136. /package/dist/{session-index → v1/session-index}/activity.js +0 -0
  137. /package/dist/{session-index → v1/session-index}/archive-title.d.ts +0 -0
  138. /package/dist/{session-index → v1/session-index}/archive-title.js +0 -0
  139. /package/dist/{session-index → v1/session-index}/background-tasks.d.ts +0 -0
  140. /package/dist/{session-index → v1/session-index}/dir-listing.d.ts +0 -0
  141. /package/dist/{session-index → v1/session-index}/dir-listing.js +0 -0
  142. /package/dist/{session-index → v1/session-index}/first-prompt.d.ts +0 -0
  143. /package/dist/{session-index → v1/session-index}/first-prompt.js +0 -0
  144. /package/dist/{session-index → v1/session-index}/list-subscriptions.d.ts +0 -0
  145. /package/dist/{session-index → v1/session-index}/list-subscriptions.js +0 -0
  146. /package/dist/{session-index → v1/session-index}/live-registry.d.ts +0 -0
  147. /package/dist/{session-index → v1/session-index}/project-dirs.d.ts +0 -0
  148. /package/dist/{session-index → v1/session-index}/service.d.ts +0 -0
  149. /package/dist/{session-index → v1/session-index}/session-index.d.ts +0 -0
  150. /package/dist/{session-index → v1/session-index}/session-info.d.ts +0 -0
  151. /package/dist/{session-index → v1/session-index}/transcript-scan.d.ts +0 -0
  152. /package/dist/{session-index → v1/session-index}/transcript-scan.js +0 -0
  153. /package/dist/{session-index → v1/session-index}/worktrees.d.ts +0 -0
  154. /package/dist/{session-index → v1/session-index}/worktrees.js +0 -0
  155. /package/dist/{tool-calls → v1/tool-calls}/changed-meta-filter.d.ts +0 -0
  156. /package/dist/{tool-calls → v1/tool-calls}/changed-meta-filter.js +0 -0
  157. /package/dist/{turn-events.d.ts → v1/turn-events.d.ts} +0 -0
@@ -1,1813 +1,2 @@
1
- import { AgentApp, AuthenticateRequest, AvailableCommand, CancelNotification, ClientCapabilities, CompleteElicitationNotification, CreateElicitationRequest, CreateElicitationResponse, DisableProviderRequest, DisableProviderResponse, ForkSessionRequest, ForkSessionResponse, InitializeRequest, InitializeResponse, ListProvidersRequest, ListProvidersResponse, ListSessionsRequest, ListSessionsResponse, LoadSessionRequest, LoadSessionResponse, LogoutRequest, NewSessionRequest, NewSessionResponse, PromptRequest, PromptResponse, ReadTextFileRequest, ReadTextFileResponse, SetProviderRequest, SetProviderResponse, RequestPermissionResponse, ResumeSessionRequest, ResumeSessionResponse, SessionConfigOption, SessionModeState, SessionNotification, SetSessionConfigOptionRequest, SetSessionConfigOptionResponse, SetSessionModeRequest, SetSessionModeResponse, CloseSessionRequest, CloseSessionResponse, DeleteSessionRequest, DeleteSessionResponse, WriteTextFileRequest, WriteTextFileResponse } from "@agentclientprotocol/sdk/unstable";
2
- import type { TurnEvents, TurnOutcome } from "./turn-events.js";
3
- import { AgentInfo, CanUseTool, FastModeDisabledReason, ModelInfo, Options, PermissionMode, Query, SDKMessage, SDKMessageOrigin, SDKPartialAssistantMessage, SDKUserMessage, Settings, SlashCommand } from "@anthropic-ai/claude-agent-sdk";
4
- import { GoalRequest, GoalControlResponse, GoalSnapshot } from "./goal-extension.js";
5
- import { type SubagentChecklists } from "./plans.js";
6
- import { PromptSuggestions } from "./prompt-suggestions.js";
7
- import { SessionTitles } from "./session-titles.js";
8
- import { AcpSessionNotification } from "./acp-subagents.js";
9
- import { NativeSubagent, NativeSubagentRuntime } from "./native-subagents.js";
10
- import * as sessionIndex from "./session-index/connection.js";
11
- import type { BatchGetSessionsRequest, RenameSessionRequest, SessionIdRequest } from "./session-index/service.js";
12
- import type { ListSubscribeRequest, ListUnsubscribeRequest } from "./session-index/list-subscriptions.js";
13
- import { AsyncTaskRuntime } from "./async-tasks.js";
14
- import { SessionBackgroundWork } from "./background-work.js";
15
- import { type AuthStatus, type AuthStatusKind } from "./auth-status.js";
16
- import { ContentBlockParam } from "@anthropic-ai/sdk/resources";
17
- import { BetaContentBlock, BetaRawContentBlockDelta } from "@anthropic-ai/sdk/resources/beta.mjs";
18
- import { type AcpPermissionRequest } from "./permissions/presentation.js";
19
- import { SettingsManager } from "./settings.js";
20
- import { type SessionFailureState } from "./session-failure-extension.js";
21
- import { type ClaudeSubscriptionGuardState } from "./hide-claude-auth.js";
22
- import { type FileChangeReportTurnState, type NativeFileChangeReporter } from "./file-change-audit.js";
23
- import { ContextCompactionLifecycle } from "./context-compaction.js";
24
- import { IdleCompaction } from "./idle-compaction.js";
25
- import { TaskState } from "./tools.js";
26
- import { type AccumulatedUsage, type ModelTokenTally } from "./session-usage.js";
27
- import { ToolCallFieldTracker } from "./tool-calls/field-tracker.js";
28
- import { ClientCapabilities as ToolCallClientCapabilities } from "./tool-calls/client-capabilities.js";
29
- import { Pushable } from "./utils.js";
30
- export { DEFAULT_AGENT_ID } from "./session-config-ids.js";
31
- import { type SessionModelState } from "./session-model.js";
32
- import { type GatewayAuthRequest, type ProviderConfig } from "./providers.js";
33
- export { AGENT_CONFIG_ID, BUILTIN_AGENT_NAMES, buildConfigOptions, clientSupportsBooleanConfigOptions, clientSupportsRecommendedConfigValue, type ConfigOptionPresentation, discoverCustomAgents, MODE_CONFIG_ID, } from "./session-config-options.js";
34
- export { createFastModeConfigOption, FAST_MODE_CONFIG_ID, FAST_MODE_OFF, FAST_MODE_ON, fastModeStateEnabled, type FastModeOptionState, normalizeFastModeDisabledReason, resolveFastModeEnabled, } from "./session-fast-mode.js";
35
- export { EFFORT_CONFIG_ID, settingsEffortForModel } from "./session-effort.js";
36
- export { applyAvailableModelsAllowlist, matchResumedModel, MODEL_CONFIG_ID, resolveModelPreference, } from "./session-model.js";
37
- export { isLoginRequiredText } from "./result-end.js";
38
- /**
39
- * Logger interface for customizing logging output
40
- */
41
- export interface Logger {
42
- log: (...args: any[]) => void;
43
- error: (...args: any[]) => void;
44
- /** Optional: a caller that supplies no `warn` gets its warnings on `error`. */
45
- warn?: (...args: any[]) => void;
46
- }
47
- /** The structured replacement for the text of a local command that Claude
48
- * Code runs itself, such as `/usage` or `/mcp`. */
49
- type LocalCommandMarkdown = {
50
- /** True when `produce` starts at turn activation. Otherwise it starts when
51
- * the command output arrives, so Claude Code has finished the command. */
52
- startsAtActivation: boolean;
53
- /** The replacement, or null to keep the original text of Claude Code.
54
- * `originalOutput` is that text. It is empty when `produce` starts at
55
- * turn activation. */
56
- produce(query: Query, signal: AbortSignal, originalOutput: string): Promise<string | null>;
57
- /** Runs once when the turn ends after it delivered the replacement. */
58
- afterDelivery?(): void;
59
- };
60
- type AsyncTaskStopRequest = {
61
- sessionId: string;
62
- asyncTaskId: string;
63
- };
64
- type AsyncTaskStopResponse = {
65
- stopped: boolean;
66
- };
67
- /** Request-level steering options. `promptRequired` is opt-in so existing Hosts
68
- * keep the established idle fallback behavior. */
69
- type SteerMeta = {
70
- [key: string]: unknown;
71
- steering?: {
72
- idleBehavior?: "promptRequired";
73
- };
74
- };
75
- /** Params of a {@link STEER_METHOD} request. Shaped like the relevant subset of
76
- * a `PromptRequest` so the same `promptToClaude` conversion applies. Delivery
77
- * priority is deliberately NOT exposed here — it's an internal detail the agent
78
- * chooses (see {@link STEER_PRIORITY}). */
79
- export type SteerRequest = {
80
- sessionId: string;
81
- prompt: PromptRequest["prompt"];
82
- _meta?: SteerMeta | null;
83
- };
84
- /** Result of a {@link STEER_METHOD} request. The legacy `startedNewTurn` result
85
- * remains the default idle behavior; `promptRequired` is returned only when the
86
- * Host explicitly opts into the host-owned fallback in request `_meta`. */
87
- export type SteerResponse = {
88
- outcome: "injected";
89
- } | {
90
- outcome: "startedNewTurn";
91
- } | {
92
- outcome: "promptRequired";
93
- reason: "noRunningTurn";
94
- };
95
- /** Who started a turn. `idleCompaction` is the adapter's own `/compact` (see
96
- * `IdleCompaction`): it is not a user prompt, so it neither disarms idle
97
- * compaction, asks for a title from its prompt, nor clears the published prompt suggestion. */
98
- type TurnOrigin = "client" | "idleCompaction";
99
- /** One in-flight turn, started by `startTurn()`. A persistent per-session
100
- * consumer (see `runConsumer`) drains the SDK query stream for the whole
101
- * session and settles each Turn when that turn's outcome is known, so
102
- * `startTurn()` itself holds no loop. Turns are processed FIFO: the SDK echoes
103
- * queued user messages back in submission order, so `turnQueue[0]` is the turn
104
- * currently running. */
105
- type Turn = {
106
- /** The `ClaudeAcpAgent.promptsReceived` count when `startTurn()` received
107
- * this prompt. `cancelTurns` cancels only turns received before the cancel. */
108
- received: number;
109
- /** uuid stamped on the pushed `SDKUserMessage`; the SDK echoes it back so the
110
- * consumer can match the replayed user message to this turn. It is also the
111
- * id of the user message the turn reports as inserted. */
112
- promptUuid: string;
113
- /** Where the turn reports how its prompt is answered (see {@link TurnEvents}). */
114
- events: TurnEvents;
115
- /** Set once `events.inserted` has been reported. A clear-context restart
116
- * activates the same turn again in the fresh session, which must not report
117
- * it twice. */
118
- insertedReported?: boolean;
119
- /** Tools surfaced during this turn, awaiting completion or an explicit
120
- * background handoff. Intersect with emittedToolCalls at settlement so
121
- * tool_result counts even when a presentation hook is still pending. */
122
- foregroundToolCallIds?: Set<string>;
123
- /** Closes the tool calls this turn left open when a cancel ended it. Both
124
- * the consumer and `cancelTurns` can settle a cancelled turn; they share
125
- * this one closing, so each call gets one report and both wait for all of
126
- * them before reporting the cancel. */
127
- closingCancelledToolCalls?: Promise<void>;
128
- /** Local-only slash commands (e.g. `/clear`) return a result without an echo,
129
- * so the consumer can't promote them via the replay; it falls back to
130
- * promoting the queue head when the result arrives. */
131
- isLocalOnlyCommand: boolean;
132
- /** Whitespace-normalized text this turn delivered as live `notice` updates
133
- * (SDK `informational` frames on the notice lane). A hook-blocked turn's
134
- * result repeats the block reason verbatim with zero output tokens; the
135
- * issue-#453 result-text fallback skips a result that only repeats one of
136
- * these, without the notice counting as the turn's answer. Recorded on the
137
- * queue head, not `activeTurn`: a UserPromptSubmit block arrives before
138
- * any echo, so the turn is only promoted when its result lands. */
139
- noticeTexts?: string[];
140
- /** Structured presentation for an exact /usage or /mcp command. The command
141
- * still runs through the normal SDK turn so ordering, cancellation,
142
- * persistence, and replay remain unchanged. A null result means the request
143
- * failed and every output path must preserve Claude Code's original text. */
144
- localCommand?: LocalCommandMarkdown;
145
- localCommandMarkdown?: Promise<string | null>;
146
- localCommandAbort?: AbortController;
147
- /** The SDK can expose a local command through more than one message shape;
148
- * publish the structured replacement at most once. */
149
- localCommandDelivered?: boolean;
150
- localCommandOriginalOutput?: string;
151
- /** Optional native checkpoint preview requested by the ACP client for this
152
- * turn. The state is turn-owned so a late control response can never be
153
- * rebound to a newer prompt. */
154
- fileChangeReport?: FileChangeReportTurnState;
155
- /** Files that subagents of this turn edited with a file tool, collected only
156
- * when a report was requested (see {@link recordSubagentFileEdits}). */
157
- editedPaths?: Set<string>;
158
- /** Set once the deferred has been resolved/rejected, so the consumer never
159
- * settles a turn twice (idle + handoff + stream-end can all race). */
160
- settled: boolean;
161
- /** Set while the terminal checkpoint preview is in flight. The consumer can
162
- * observe another terminal signal during that bounded await; only the first
163
- * one may continue into settlement. */
164
- settling?: boolean;
165
- /** Outcome captured before the checkpoint preview await, so cancel() can
166
- * preserve its usage and metadata while atomically winning that race. */
167
- settlingOutcome?: TurnOutcome;
168
- /** Set when a `command_lifecycle` "started" frame arrives for this turn's
169
- * uuid (msg_lifecycle_v1 CLIs): the SDK dispatched the command into a turn.
170
- * Read by cancel() to seed the orphan's state — a started orphan's turn may
171
- * still emit a result, an undispatched one may be dropped without one. */
172
- commandStarted?: boolean;
173
- /** Set when a terminal `command_lifecycle` frame arrives for this turn's
174
- * uuid while the turn is still queued (msg_lifecycle_v1 CLIs). The command
175
- * is already finished SDK-side, so a later cancel() must not seed an
176
- * orphan entry for it — no terminal frame will ever come to drain it.
177
- * "completed"/"discarded"/"refused" leave nothing outstanding; "cancelled"
178
- * after a dispatch means the dead turn's result may still arrive (seeded
179
- * as a zombie) unless it already passed (`commandResultSeen`), and without
180
- * a dispatch means dropped (nothing coming). */
181
- commandFinished?: "completed" | "discarded" | "cancelled" | "refused";
182
- /** Set when a user-turn result arrives while this command is known
183
- * dispatched (`commandStarted`) with no terminal frame yet. Turns run
184
- * sequentially and frames arrive in stream order, so the turn this command
185
- * was dispatched into IS the turn that emitted that result — including
186
- * when the command was FOLDED into another turn (their shared result).
187
- * Read by cancel() and the force-cancel wedge path so neither seeds an
188
- * orphan entry for a result that has already passed: such an entry could
189
- * never be drained by its result and would swallow an unrelated later
190
- * echo-less one instead. */
191
- commandResultSeen?: boolean;
192
- /** Task ids of the background subagents launched while this turn was the
193
- * active one — including during its held-open drain window, so an agent
194
- * chain (a followup that launches another subagent) extends the hold.
195
- * A settled subagent that the SDK resumes while this turn is active (for
196
- * example through SendMessage) counts as a spawn of this turn.
197
- * A turn only waits on its OWN spawned subagents: a long-running agent
198
- * from an earlier turn must not stall every later prompt's settlement.
199
- * Known residual: task_started names no turn (its `parent_task_id`
200
- * names only a launching subagent), so a spawn made by a
201
- * PREVIOUS turn's followup chain while a later turn happens to be held
202
- * is attributed to the holder — extending that hold behind a foreign
203
- * chain. Bounded: the hold still ends at drain, hand-off, or cancel.
204
- * The set is also kept for a client with `backgroundSubagents`, but no
205
- * hold reads it there (see `deferredSettle`). */
206
- spawnedTaskIds?: Set<string>;
207
- /** Set instead of settling when the turn's terminal result arrives while
208
- * subagents it spawned are still live (`spawnedTaskIds` ∩
209
- * `session.liveBackgroundTasks`). The turn is held open — its
210
- * `session/prompt` stays pending — so the subagents' streamed output,
211
- * their permission requests (which would otherwise block on an RPC a
212
- * client that stops consuming at the prompt response never answers —
213
- * issue #866), and the model's task-notification followup summary all
214
- * land inside the turn.
215
- *
216
- * An ACP v1 AIR client that declares `backgroundSubagents` gets no hold:
217
- * this field stays unset, and the turn settles at its result. AIR keeps
218
- * listening after the prompt response, so the subagent updates, their
219
- * permission requests and elicitations, and the followup summary go out
220
- * after it, with the same routing. A held turn hides the end of the
221
- * answer, and the next user message would steer into it. Consequences:
222
- * a followup result is an out-of-turn autonomous result; a steer with no
223
- * turn in flight starts a new turn; the file-change report of the turn
224
- * leaves out subagent edits after the result. Every other client keeps
225
- * the hold, so issue #866 stays fixed for it.
226
- *
227
- * Idle cadence depends on the CLI. Through 2.1.269 the trailing idle is
228
- * NOT held for background agents (observed on 2.1.206: `idle` follows
229
- * the result immediately while the subagent still runs), so the hold
230
- * spans multiple idle cycles: user result → idle → (subagent works) →
231
- * task_notification → followup turn → idle. From 2.1.270 the CLI stays
232
- * `running` while background agents live (observed live: user result →
233
- * task_notification → followup turn → ONE idle), so the user result's
234
- * idle debt goes unpaid — swept at the next `running` transition.
235
- * The stored outcome (the result's stop reason and usage snapshot) is
236
- * what the turn settles with once its spawned subagents have settled —
237
- * at the followup's terminal result (the summary has streamed by then),
238
- * or at an idle with none of its subagents left (no followup came). A
239
- * cancel or the next turn's echo hand-off settles it earlier, so a
240
- * long-running subagent never holds the prompt hostage.
241
- *
242
- * Accepted residuals. (1) A subagent that ends WITHOUT waking the model —
243
- * its task_notification lost or skipped (only the terminal task_updated
244
- * patch is guaranteed per transition) — leaves no followup result and no
245
- * further idle, so the held turn parks until `session/cancel` or the next
246
- * prompt (either settles it: the echo hand-off or ensureActiveTurn's
247
- * held-turn hand-off). Settling at the prune sites instead would preempt
248
- * the followup summary in the normal ordering (prunes precede the
249
- * notification), and a grace timer was judged not worth the machinery —
250
- * the same rescue contract as the adapter's other wedge classes (issue
251
- * #825's out-of-scope notes). (2) Drained-ness is judged by live-task
252
- * membership only: with parallel subagents, a notification that prunes
253
- * the last task during an earlier task's still-streaming followup lets
254
- * that followup's result settle the turn before the LAST task's summary
255
- * streams — degrading to post-turn delivery for it, never worse than the
256
- * pre-hold behavior (pending wakes are not countable: notifications can
257
- * batch into one followup). */
258
- deferredSettle?: TurnOutcome;
259
- /** Uuids of `steer()`-injected messages the SDK has not replayed back yet.
260
- *
261
- * A steer is normally delivered at priority `now`. When it lands during
262
- * generation the CLI ABORTS the running cycle: it emits its own human-origin
263
- * `result` — indistinguishable from a turn's terminal one — and the steered
264
- * message runs as a SECOND cycle. When it lands during a foreground tool call
265
- * (CLI 2.1.286) the CLI moves the tool to the background instead and either
266
- * joins the steer into the running cycle (ONE result stamped with both
267
- * uuids) or still ends that cycle early and runs the steer as a second one.
268
- * Settling at an interrupted cycle's result would answer `session/prompt`
269
- * mid-work, so a steered turn's results only RECORD their outcome
270
- * (`steeredSettle`) until one provably answers the steer.
271
- *
272
- * Two signals prove it. Exact: a result whose `user_message_uuids` names
273
- * one of `steeredUuids` consumed the steered message, so once no echo is
274
- * outstanding it is the turn's terminal result and the turn leaves the steer
275
- * lane to settle there like any other (this also retires an echo the CLI
276
- * never replayed). Fallback, for producers that don't stamp results: the
277
- * SDK's `idle` after a result recorded since the last echo (see
278
- * `steeredAwaitingResult`), the only signal spanning both cycles
279
- * (CLI 2.1.220).
280
- *
281
- * A non-empty set at an idle means the steered cycle hasn't started — the CLI
282
- * replays a message only when it picks it up, always after the interrupted
283
- * cycle's result — so that idle is swallowed. Drained by the replay handler
284
- * and by stamped results.
285
- *
286
- * Residual: a message the CLI drops unreplayed, with no stamped result naming
287
- * it, parks the turn until `session/cancel` or the next prompt (both settle
288
- * it). */
289
- steeredEchoes?: Set<string>;
290
- /** Every steer this turn has taken, echoed or not: a stamped result naming one
291
- * answers the steer even after its echo drained `steeredEchoes`. */
292
- steeredUuids?: Set<string>;
293
- /** Set when a steered echo drains and cleared when a result records
294
- * `steeredSettle`. `steeredSettle` can already hold the interrupted cycle's
295
- * outcome (or a held turn's, moved over by `steer()`) when the echo lands, so
296
- * while this is set the recorded outcome predates the steered work and an
297
- * idle must not settle on it. */
298
- steeredAwaitingResult?: boolean;
299
- /** What a steered turn settles with once its steered work has run: the outcome
300
- * of its latest result, so its usage covers every cycle the turn ran. */
301
- steeredSettle?: TurnOutcome;
302
- carriedUsage?: AccumulatedUsage;
303
- /** `carriedUsage`'s per-model counterpart, so a turn that survives a
304
- * clear-context restart keeps the `_meta.quota` rows it earned pre-restart. */
305
- carriedModelUsage?: ModelTokenTally;
306
- resolve: (outcome: TurnOutcome) => void;
307
- reject: (error: unknown) => void;
308
- /** Settles once the turn has ended or failed. */
309
- completion?: Promise<void>;
310
- };
311
- /** A permission or elicitation request that awaits user input. */
312
- type OpenUserInput = {
313
- /** The subagent that asked: absent for the main conversation and for a
314
- * request that names no agent. */
315
- agentID?: string;
316
- };
317
- export type Session = {
318
- query: Query;
319
- input: Pushable<SDKUserMessage>;
320
- /** Set by a cancel. While it is set, the consumer treats what arrives as the
321
- * work the cancel stopped: it drops main-thread `assistant` and `user`
322
- * messages (streamed text still goes out), skips results, and starts no
323
- * model cycle. Two things still go out: a tool result for a tool call that
324
- * the client holds open, until the client is told that the work ended, and,
325
- * as the turn settles, a report that closes each tool call left without a
326
- * result. Cleared when the next prompt's turn activates,
327
- * or when Claude Code starts a model request that serves none of
328
- * {@link Session.cancelledPrompts} (see the `status` case of the
329
- * consumer), such as its follow-up after a background command finished. */
330
- cancelled: boolean;
331
- /** The prompts whose work the cancel stopped: the turns it settled as
332
- * cancelled, and their steers. Recorded when the cancel arrives, before the
333
- * orphan accounting, which can undercount a prompt that Claude Code had
334
- * already taken off its queue. */
335
- cancelledPrompts?: Set<string>;
336
- /** FIFO of in-flight prompts. The head is the turn the SDK is currently
337
- * processing; later entries are queued and will be echoed in order. */
338
- turnQueue?: Turn[];
339
- /** The turn whose messages the consumer is currently attributing output to
340
- * (the head of `turnQueue` once its user message has been echoed). */
341
- activeTurn?: Turn | null;
342
- /** Session-owned native checkpoint reporter. Turn state stays on each Turn. */
343
- fileChangeReporter?: NativeFileChangeReporter;
344
- /** Optimistic goal state published for a submitted `/goal` command whose
345
- * matching runtime update has not arrived yet. Runtime updates for the old
346
- * goal are suppressed until this command is echoed or completes, otherwise
347
- * a late old-goal update can overwrite a replacement that the runtime never
348
- * announces (the compatibility case the optimistic update exists for). */
349
- pendingGoalUpdate?: {
350
- commandUuid: string;
351
- expected: GoalSnapshot | null;
352
- previous: GoalSnapshot | null | undefined;
353
- started: boolean;
354
- };
355
- /** Last goal snapshot sent to the ACP client, used to roll back an
356
- * optimistic `/goal` update when the command itself fails. */
357
- lastPublishedGoal?: GoalSnapshot | null;
358
- /** The follow-up prompt the client holds, for an AIR client only. */
359
- promptSuggestions?: PromptSuggestions;
360
- /** Count of result messages the consumer should treat as orphans and skip
361
- * (not promote/attribute to the current head). When cancel() settles+removes
362
- * a queued turn, that turn's user message was already pushed to the SDK, so
363
- * the SDK still runs it and emits a result with no uuid we can match. Because
364
- * the SDK processes input FIFO, those orphan results arrive (in submission
365
- * order) before the next live turn's, so skipping exactly this many leaves
366
- * the genuine head untouched. On CLIs with the interrupt receipt, orphans
367
- * the interrupt dropped (absent from `still_queued`) are uncounted as soon
368
- * as the receipt arrives (see cancel()). Reset to 0 on every activation as
369
- * a backstop against a dropped queued input this can't see (older CLIs, a
370
- * receipt lost to a failed control round-trip). Only used when the CLI does
371
- * NOT emit lifecycle frames (see `orphanCommands` for the msg_lifecycle_v1
372
- * lane); a count can't express command coalescing — N queued commands can
373
- * fold into ONE turn emitting one result, leaving a stale skip of N-1. */
374
- pendingOrphanResults?: number;
375
- /** UUIDs of cancelled-before-echo commands that can still emit Claude's
376
- * empty user-interruption diagnostic. Interrupt receipts and command
377
- * lifecycle frames remove commands that were dropped before dispatch; the
378
- * next ordinary result clears any stale survivors. */
379
- pendingEmptyInterruptionDiagnosticCommands?: Set<string>;
380
- /** msg_lifecycle_v1 lane of the orphan accounting (see
381
- * `pendingOrphanResults` for the count lane): the uuids of cancelled queued
382
- * turns whose SDK-side command may still produce an unaccounted result,
383
- * keyed to what we know of its fate. "pending" = not seen dispatched; if
384
- * the SDK drops it (interrupt, `cancelled` before "started") no result
385
- * ever comes. "started" = dispatched into a turn whose result is still
386
- * coming; exactly one terminal lifecycle frame will follow. "zombie" = its
387
- * turn was aborted/failed after dispatch with no result seen since
388
- * (`cancelled` after "started"); no more lifecycle frames come, but the
389
- * dead turn's error result may still arrive. Entries are removed the
390
- * moment their result is covered: EVERY user-turn result covers ALL
391
- * started and zombie entries at once (turns run sequentially and frames
392
- * arrive in stream order, so at any result the started entries were
393
- * dispatched into — possibly folded into — the emitting turn, and any
394
- * zombie's late result has already passed or never existed), whether that
395
- * result was attributed to the active turn or skipped echo-less (see
396
- * recordResultForOrphanCommands / ensureActiveTurn). A command's own
397
- * terminal frame also drains its entry ("completed" is emitted after any
398
- * result its turn produced; a bare `cancelled` deletes a pending entry —
399
- * dropped without running — and zombifies a started one). An echo-less
400
- * result is an orphan's iff this map is non-empty (FIFO: orphan turns run
401
- * before any live turn's). Cleared on every activation, same self-heal as
402
- * the count (covers a lost frame, which can leak an entry — each state
403
- * bounds the damage to one wrong skip). */
404
- orphanCommands?: Map<string, "pending" | "started" | "zombie">;
405
- /** True once a `system`/init advertised the msg_lifecycle_v1 capability, so
406
- * cancel() routes orphan accounting to `orphanCommands` (exact, per-uuid)
407
- * instead of `pendingOrphanResults` (count, coalescing-blind). */
408
- msgLifecycleV1?: boolean;
409
- /** True once a `system`/init advertised the request_marker_lists_v1
410
- * capability: each `status: requesting` frame, which starts a model
411
- * request, then lists the prompts the request serves in
412
- * `user_message_uuids`, and leaves the field out for a request that serves
413
- * none, such as a cycle that Claude Code started on its own. */
414
- requestMarkerListsV1?: boolean;
415
- /** True once a `system`/init advertised the ask_user_question_unanswered_v1
416
- * capability, so an AskUserQuestion answer may set
417
- * `annotations[question].unanswered`. An older CLI can refuse the whole
418
- * answer when that field is present. */
419
- askUserQuestionUnansweredV1?: boolean;
420
- /** A main-thread model request started (`status: requesting`) since the
421
- * last result, so a model cycle runs. Read only with
422
- * {@link Session.requestMarkerListsV1}. */
423
- modelRequestSinceResult?: boolean;
424
- /** Latched from `system`/init `terminal_slash_commands` (CLI 2.1.232+):
425
- * names of advertised slash commands whose UX is bound to the CLI's own
426
- * terminal (e.g. /doctor, /color). ACP clients aren't that terminal, so
427
- * these are filtered out of `available_commands_update` payloads. */
428
- terminalSlashCommands?: string[];
429
- /** The uuids of the user messages this adapter pushed whose echo has not come
430
- * back yet. Claude Code stamps the echo with the same human origin as a
431
- * message typed in another client, so the uuid is what tells the two apart. */
432
- sentUserUuids?: Set<string>;
433
- /** The `/remote-control` command that is running, from its request to its
434
- * reply. Prompts wait for it, and a second command is refused meanwhile. */
435
- remoteControlCommand?: Promise<void>;
436
- /** The resolved SKILL.md paths of the skill commands, keyed by the cwd and
437
- * the command name. A `commands_changed` clears it, because the skill
438
- * files can have changed then. */
439
- skillPaths?: Map<string, string | undefined>;
440
- /** The skill files Claude Code reports in `getContextUsage().skills.skillFrontmatter`,
441
- * keyed by the skill name as the slash command is named (`plug:pskill`).
442
- * `path` is the SKILL.md file, absent for a skill bundled with the CLI and
443
- * on remote connections. Filled by
444
- * {@link ClaudeAcpAgent.refreshSkillFiles}; undefined until the first read. */
445
- skillFiles?: Map<string, {
446
- path?: string;
447
- }>;
448
- /** True once the first `system`/init has started the first skill file read,
449
- * so the per-turn init re-emit does not start another. */
450
- skillFilesRequested?: boolean;
451
- /** A skill file read is running; a trigger meanwhile sets `skillFilesRerun`. */
452
- skillFilesRefreshing?: boolean;
453
- /** A trigger came in during a running read, which may have read the state
454
- * from before it, so one more read follows. */
455
- skillFilesRerun?: boolean;
456
- /** Serialized `system`/init `plugin_errors` last logged, so the per-turn
457
- * init re-emit logs a plugin load failure once, not every turn. */
458
- loggedPluginErrors?: string;
459
- /** Names of client-provided MCP servers already reported as failed or
460
- * needing authentication. `system`/init re-emits on every turn with the
461
- * same statuses, and each server is reported once per session. */
462
- reportedMcpServers?: Set<string>;
463
- /** The long-lived consumer task. Lazily started on the first `prompt()` and
464
- * kept alive for the session so between-turn/background messages are still
465
- * drained and forwarded. */
466
- consumer?: Promise<void>;
467
- /** Set once the SDK query stream has terminated (it ran to `done` or threw a
468
- * non-process error). The query iterator is not reusable afterward, so a
469
- * later `prompt()` rejects instead of enqueueing onto a dead stream and
470
- * hanging (or silently restarting a consumer that resolves `end_turn`
471
- * without ever reaching the model). */
472
- queryClosed?: boolean;
473
- /** Set when `teardownSession` starts (a `session/close` or the connection
474
- * closing), so a prompt that was still starting ends cancelled. */
475
- tornDown?: boolean;
476
- cwd: string;
477
- /** Serialized snapshot of session-defining params (cwd, mcpServers, skills)
478
- * used to detect when loadSession/resumeSession is called with changed values. */
479
- sessionFingerprint: string;
480
- /** Original ACP parameters used to recreate this query with a new provider. */
481
- creationParams?: NewSessionRequest;
482
- settingsManager: SettingsManager;
483
- /** Higher-priority programmatic settings passed to query(). Retained so
484
- * model switches resolve effort from the same effective settings as the SDK. */
485
- effortSettingsOverride?: Settings;
486
- /** This session's title state and the turn-end logic that maintains it. */
487
- titles: SessionTitles;
488
- accumulatedUsage: AccumulatedUsage;
489
- /** The active turn's spend broken out per model — the breakdown behind
490
- * `accumulatedUsage`, reported as `_meta.quota.model_usage` on the prompt
491
- * response. Accumulated and reset in lockstep with it. */
492
- accumulatedModelUsage?: ModelTokenTally;
493
- /** The last per-model reading seen on this query, autonomous cycles included.
494
- * `result.modelUsage` is a running total for the whole query() call rather
495
- * than a per-result figure, so consecutive readings are what a result's own
496
- * spend is derived from — this is not itself a turn tally. `undefined` on a
497
- * resumed session until its first result: the CLI continues the running
498
- * total from the totals the transcript saved (SDK 0.3.277+), so that first
499
- * reading is the baseline for later increments, not the first turn's spend
500
- * (see resumedFirstResultModelUsage). */
501
- lastModelUsageReading?: ModelTokenTally;
502
- modes: SessionModeState;
503
- /** The mode the session left when it entered plan mode, if it is in plan. */
504
- prePlanMode?: string;
505
- models: SessionModelState;
506
- modelInfos: ModelInfo[];
507
- /** Prevents the model-specific Auto fallback from spamming the transcript. */
508
- autoModeFallbackWarningShown?: boolean;
509
- /** Initial mode fallback is reported after session/new, on the first prompt. */
510
- autoModeFallbackWarningPending?: boolean;
511
- configOptions: SessionConfigOption[];
512
- /** Custom main-thread agent personas the user (or a plugin/project) has
513
- * configured, discovered via `supportedAgents()` with Claude Code's built-in
514
- * subagents filtered out. Empty when none are configured, in which case the
515
- * "agent" config option is omitted entirely. */
516
- agents: AgentInfo[];
517
- /** The currently selected main-thread agent name, or "default" for the
518
- * standard Claude Code agent (no `agent` flag applied). */
519
- currentAgent: string;
520
- /** Whether the client explicitly selected an agent, including Default. */
521
- agentSelected?: boolean;
522
- /** Whether Fast mode is currently enabled for this session. Tracked as the
523
- * user's intent so it persists across model switches; the Fast mode config
524
- * option is only surfaced while the selected model supports it. */
525
- fastModeEnabled: boolean;
526
- /** Whether ultracode is turned on for this session. Tracked as the user's
527
- * intent, like `fastModeEnabled`: the CLI keeps the request across model
528
- * switches and applies it whenever the model supports ultracode, while the
529
- * config option is only surfaced on supporting models. */
530
- ultracodeEnabled: boolean;
531
- /** Whether dynamic workflows are enabled, learned from the CLI's
532
- * `get_settings` at session start; undefined when unknown. Combined with
533
- * the model's support to decide whether to show the ultracode option. */
534
- ultracodeWorkflowsEnabled?: boolean;
535
- /** The non-default effort the user picked through the ACP picker this
536
- * session. A pin lives at the SDK's flag layer, which overrides the CLI's
537
- * persisted effort (including the per-model `modelSettings` entries), so it
538
- * follows the session across model switches. Without a pin, opted-in clients
539
- * apply the settings-derived effort or concrete recommendation on each switch;
540
- * legacy clients leave resolution to the CLI. Cleared when the
541
- * user picks "Default" (the flag layer is cleared with it) or when a model
542
- * switch clamps the pin away. */
543
- effortPinnedLevel?: string;
544
- /** Last concrete effort successfully written to the SDK flag layer. This is
545
- * independent of user ownership: opted-in clients also apply automatic
546
- * recommendations and settings-derived values. */
547
- appliedEffortLevel?: string;
548
- /** Why the SDK currently can't serve Fast mode, when the reason is one worth
549
- * telling the user about (see {@link FAST_MODE_UNAVAILABLE_EXPLANATIONS} —
550
- * routine states like the SDK's own opt-in requirement normalize to
551
- * `undefined`). Refreshed from every `fast_mode_disabled_reason` the SDK
552
- * reports on `system`/init and user-turn `result`s; surfaced in the Fast mode
553
- * option's description so a toggle that snaps back off explains itself. */
554
- fastModeDisabledReason?: FastModeDisabledReason;
555
- abortController: AbortController;
556
- /** Signal the consumer races `query.next()` against. Aborted by cancel()
557
- * (after a grace period) to force the active turn to settle "cancelled" when
558
- * the SDK is wedged and `query.next()` never yields again (issue #680).
559
- * Distinct from `abortController`: this only wakes the consumer; it does NOT
560
- * touch the SDK query/subprocess. The consumer re-arms it after each fire.
561
- * Undefined until the consumer is started by the first prompt. */
562
- cancelController?: AbortController;
563
- /** Pending grace-period timer that aborts `cancelController`. Cleared when the
564
- * active turn settles normally so the backstop never fires after a clean
565
- * cancel. */
566
- forceCancelTimer?: ReturnType<typeof setTimeout>;
567
- emitRawSDKMessages: boolean | SDKMessageFilter[];
568
- /** Whether nested subagent text/thinking is forwarded to the ACP client.
569
- * Enabled by either the ACP capability or the pre-existing SDK option. */
570
- forwardSubagentText: boolean;
571
- /** The ACP permission and elicitation requests that await user input.
572
- * Parallel subagents can ask concurrently. Steering stays non-interrupting
573
- * while any request is open, and the idle compaction waits until none is. */
574
- openUserInputs?: Set<OpenUserInput>;
575
- /** Context window size of the session's current model, carried across
576
- * prompts so mid-stream usage_update notifications report a correct `size`
577
- * before the turn's first result message arrives. Seeded synchronously at
578
- * session creation and on model switches from the per-model cache or the
579
- * text heuristic (DEFAULT_CONTEXT_WINDOW when both miss), refined by a
580
- * background `getContextUsage` when that seed was a guess (see
581
- * `refreshContextWindowInBackground`), then confirmed — and the cache
582
- * populated — by each result's modelUsage. No awaited IPC is on these
583
- * paths (see the seeding call sites and `contextWindowCache`). */
584
- contextWindowSize: number;
585
- contextUsedTokens?: number;
586
- /** Whether `contextWindowSize` came from an authoritative source (the
587
- * cross-session cache, a `result.modelUsage`, or the background
588
- * `getContextUsage`) rather than the text heuristic / default. Guards the
589
- * mid-stream `message_start` heuristic upgrade: an authoritative window that
590
- * happens to equal DEFAULT_CONTEXT_WINDOW must not be mistaken for "unseeded"
591
- * and clobbered by a "1m" text match. */
592
- contextWindowAuthoritative: boolean;
593
- /** Stable identifier of the LLM backend this session's query was created
594
- * against, derived from the routing-relevant vars of the exact `env` handed
595
- * to the SDK at query creation (see {@link providerCacheKeyFor}). The context
596
- * window is a property of (model id, backend) — the same resolved model id
597
- * can name different windows behind different base URLs, routing headers, or
598
- * credentials — so this scopes the module-global `contextWindowCache` per
599
- * backend. Captured from the query's own env (not re-resolved later) because
600
- * the process-wide provider config can change while a session is being
601
- * created, while the query stays baked to the env it was created with. */
602
- providerCacheKey: string;
603
- /** Accumulated task list for the session, keyed by task ID. Task IDs are
604
- * per-session, so this state must not be shared across sessions. */
605
- taskState: TaskState;
606
- /** The subagent TodoWrite checklists that the client holds in this session,
607
- * which a conversation reset removes. */
608
- subagentChecklists: SubagentChecklists;
609
- /** Caches `tool_use` blocks by id so the matching `tool_result` can recover
610
- * the tool name/input when mapping it to a `tool_call_update`. Per-session
611
- * (tool_use ids are only unique within a session) and pruned at
612
- * `tool_result` time so a long-running session doesn't accumulate every
613
- * tool call for its whole lifetime. */
614
- toolUseCache: ToolUseCache;
615
- /** Tracks which tool_use ids we've already emitted a `tool_call` for, so the
616
- * second source to encounter a tool call sends a `tool_call_update` instead
617
- * of a duplicate `tool_call`. The SDK can invoke `canUseTool` (→ a permission
618
- * request, which emits the tool_call eagerly so the client has it before
619
- * being asked to approve it) either before or after the assistant message's
620
- * tool_use block streams; this set makes the two paths converge regardless of
621
- * order. Pruned at `tool_result` time alongside `toolUseCache`. */
622
- emittedToolCalls: Set<string>;
623
- /** The tool names of the tool uses whose result arrived, after
624
- * {@link toolUseCache} dropped them. An async task can name its tool call
625
- * after the result, and the async task runtime needs the tool name. The
626
- * oldest entries are dropped. */
627
- resolvedToolNames?: Map<string, string>;
628
- /** The open tool calls that Claude Code sent to the tool runner: a complete
629
- * assistant message holds their `tool_use`, or a permission request asked
630
- * for them. A streamed tool_use that never reached a complete message is
631
- * not here: Claude abandoned it before it ran. Pruned when the call ends;
632
- * the oldest entries are dropped. */
633
- dispatchedToolCalls?: Set<string>;
634
- /** The tool uses that the consumer reached in the stream, each with whether
635
- * it dropped it as output of the work a cancel stopped (`true`, see
636
- * `dropsStoppedWorkOutput`). The first sight of a tool use decides: its
637
- * streamed start, or its complete message. `canUseTool` reads it (see
638
- * `isStoppedWorkToolUse`). The oldest entries are
639
- * dropped. */
640
- reachedToolUses?: Map<string, boolean>;
641
- /** What waits for the consumer to reach each tool use (see
642
- * `isStoppedWorkToolUse`). */
643
- toolUseWaiters?: Map<string, Set<() => void>>;
644
- /** For each open tool call that a subagent made: the Agent/Task call that
645
- * started that subagent. When a cancel ends such a call, the report names
646
- * that parent as the call's other updates do, so that every client form
647
- * routes it with them. It also tells the calls of a background subagent,
648
- * which a cancel leaves open while the subagent keeps running. Pruned when
649
- * the call ends; the oldest entries are dropped. */
650
- toolCallParents?: Map<string, string>;
651
- /** The fields that the client holds for each open tool call, so that a
652
- * `tool_call_update` resends only the fields that changed. Created lazily
653
- * by {@link toolCallFieldsOf}. */
654
- toolCallFields?: ToolCallFieldTracker;
655
- /** ACP session affinity for calls emitted eagerly by permission handling. */
656
- eagerToolCallSessions?: Map<string, string>;
657
- /** ExitPlanMode denial that intentionally interrupts the current Claude
658
- * cycle. Correlated by tool-use id until the terminal result arrives. */
659
- pendingExitPlanModeInterruption?: {
660
- toolUseId: string;
661
- toolResultSeen: boolean;
662
- };
663
- pendingExitPlanContextReset?: {
664
- toolUseId: string;
665
- plan: string;
666
- mode: PermissionMode;
667
- };
668
- /** Registry of live background tasks, keyed by task id: populated at
669
- * `task_started`, pruned when the task settles (a `task_notification` or
670
- * a terminal `task_updated` patch), and reconciled against
671
- * `background_tasks_changed`'s replace-semantics payload so a lost
672
- * bookend can't leak an entry. One structure for both of its concerns so
673
- * a future terminal path can't prune one and not the other:
674
- *
675
- * `parentToolUseId` — the tool_use id of the Agent/Task call that spawned
676
- * the task. For subagent tasks the SDK keys its registry by agent id, so
677
- * `task_started.task_id` IS the `agentID` that `canUseTool` later
678
- * receives. Lets the permission flow attribute a subagent's
679
- * eagerly-emitted `tool_call` (and the permission request itself) to its
680
- * parent tool call via `_meta.claudeCode.parentToolUseId`, matching the
681
- * streamed subagent path. Best-effort: a `canUseTool` that races ahead of
682
- * the consumer processing `task_started` omits the attribution from the
683
- * eager tool_call, and the streamed tool_use chunk's refining
684
- * `tool_call_update` — which carries the message-level
685
- * `parent_tool_use_id` — restores it for merging clients; that recovery
686
- * is what makes best-effort acceptable here.
687
- *
688
- * `isSubagent` — whether the task is a Task/Agent-tool subagent
689
- * (`task_started` carried a `subagent_type`). Read by
690
- * `turnAwaitingSubagents` (with `spawnedTaskIds`) to decide whether a
691
- * turn's settlement is deferred (see `Turn.deferredSettle`), so the
692
- * subagents' post-result output and permission requests stay inside the
693
- * turn (issues #864/#866). A client with `backgroundSubagents` gets no
694
- * such hold. Its subagent requests keep this attribution after the
695
- * prompt response. Deliberately false for non-subagent background
696
- * tasks (e.g. a `run_in_background` dev server): those can outlive every
697
- * turn, and the model's contract with them is a wake-on-exit
698
- * notification, not a turn-scoped drain — a hold must NEVER wait on a
699
- * shell.
700
- *
701
- * `endedPerLevel` — a `background_tasks_changed` payload did not include
702
- * this subagent entry. The level's universe is BACKGROUND tasks only, so
703
- * a live sync (foreground) subagent is legitimately absent — its entry is
704
- * kept for permission attribution — but a hold must stop waiting on the
705
- * id: an absent id can equally be a leaked async entry whose settle
706
- * bookends were lost, and waiting on it would park the hold forever.
707
- * Non-subagent entries are simply deleted instead (shells are always in
708
- * the level's universe). */
709
- liveBackgroundTasks: Map<string, {
710
- parentToolUseId?: string;
711
- isSubagent: boolean;
712
- /** The task's kind (`task_started.task_type`), such as `local_bash` or
713
- * `local_workflow`. Absent when Claude Code did not say. */
714
- taskType?: string;
715
- /** Whether the task runs in the background, so that the tool call that
716
- * spawned it does not wait on it (`task_started.is_backgrounded`, or a
717
- * later `task_updated` patch). Absent when Claude Code did not say. */
718
- backgrounded?: boolean;
719
- /** The subagent task whose agent launched this task
720
- * (`task_started.parent_task_id`), absent for one the main conversation
721
- * launched. */
722
- parentTaskId?: string;
723
- /** Absent-from-level lifecycle, one field so the illegal
724
- * armed-but-not-ended state is unrepresentable: undefined = live per
725
- * the level signal; "ended" = a level omitted the task (holds stop
726
- * waiting on it; attribution is kept); "sweep-armed" = a turn
727
- * activation saw it ended — the NEXT activation deletes it. The
728
- * one-activation grace exists for the absent-mark race (a level
729
- * payload built before a live async agent's registration): a
730
- * corrective inclusive level resets the field to undefined — one
731
- * assignment, disarming any in-flight sweep — if it arrives within a
732
- * full turn, keeping the agent's attribution; eager deletion would
733
- * be irreversible, since levels never ADD entries. A re-mark
734
- * preserves an in-flight arm (`??=`), keeping a continuously absent
735
- * entry on its two-activation clock. */
736
- endedPerLevel?: "ended" | "sweep-armed";
737
- }>;
738
- /** Whether `session/cancel` also stops the session's background workflows
739
- * (see `stopBackgroundWorkflows`). Claude Code's interrupt kills background
740
- * subagents and workflows, unless the query declares
741
- * `perTaskStopAffordance`: then it spares both, and the client is expected
742
- * to stop each one itself. A client that can cancel one subagent gets the
743
- * declaration, but it has no control for a workflow unless it is AIR with
744
- * `asyncTasks` (`_session/async_task/stop`). So for any other such client the
745
- * adapter stops the workflows after the interrupt, as the interrupt did
746
- * before. */
747
- stopsWorkflowsOnCancel?: boolean;
748
- /** The terminals of the commands that Claude Code runs in the background
749
- * for the session, kept for a client that renders terminals and is not
750
- * AIR (AIR shows a command through its async tasks). Per CLI process, as
751
- * is a session. */
752
- background: SessionBackgroundWork;
753
- /** The parent tool call of each subagent that a settle bookend removed from
754
- * `liveBackgroundTasks`. The SDK can resume such a subagent under the same
755
- * agent id without a new `task_started` (a running `task_updated` patch or
756
- * a SendMessage `resumedAgentId`). The resume signal puts the subagent back
757
- * into `liveBackgroundTasks` from this record, so the resuming turn holds
758
- * and its permission requests keep their attribution. With
759
- * `backgroundSubagents` the resuming turn does not hold, and the
760
- * attribution stays the same. Bounded by
761
- * `MAX_RESUMABLE_SUBAGENTS`, oldest first. */
762
- resumableSubagents?: Map<string, {
763
- parentToolUseId?: string;
764
- }>;
765
- /** The latest `run_id` seen on each task's events, so a late frame of an
766
- * earlier run is dropped (see `isLateTaskRun`). Run ids are per CLI
767
- * process, as is a session. Bounded by `MAX_TASK_RUN_IDS`, oldest first. */
768
- taskRunIds?: Map<string, string>;
769
- /** Native ACP subagent sessions negotiated through PR #1992. Records are
770
- * retained for the parent session lifetime so late child output cannot be
771
- * rebound to another task after the SDK prunes its live-task registry. */
772
- nativeSubagentsByTaskId?: Map<string, NativeSubagent>;
773
- /** Resolves the spawning Agent/Task tool use carried by child messages to
774
- * the corresponding native ACP child session. */
775
- nativeSubagentTaskIdByToolUseId?: Map<string, string>;
776
- /** Captures the ACP session in which an Agent/Task tool call was made. This
777
- * supplies the immediate parent for nested `task_started` notifications.
778
- * Their `parent_task_id` (SDK 0.3.292+) names the launching subagent too;
779
- * only {@link blocksForeground} reads it so far. */
780
- nativeSubagentParentByToolUseId?: Map<string, string>;
781
- /** Session-owned lifecycle controller shared by the consumer, cancel, reset,
782
- * and teardown paths. */
783
- nativeSubagentRuntime?: NativeSubagentRuntime;
784
- /** Child-aware delivery closure paired with {@link nativeSubagentRuntime}. */
785
- nativeSubagentDeliver?: (notification: AcpSessionNotification) => Promise<void>;
786
- /** The consumer's `closeCancelledToolCalls`, for `cancelTurns`, which settles
787
- * a held or settling turn itself. */
788
- closeCancelledToolCalls?: (turn: Turn) => Promise<void>;
789
- /** Session-owned async task controller. Prompt cancellation intentionally
790
- * does not finish it because background work may outlive a prompt. */
791
- asyncTaskRuntime?: AsyncTaskRuntime;
792
- /** The consumer's compaction lifecycle, exposed so the PostCompact hook can
793
- * hand it the retained summary. */
794
- contextCompaction?: ContextCompactionLifecycle;
795
- /** Compacts the session shortly before its one-hour prompt cache expires. */
796
- idleCompaction?: IdleCompaction;
797
- /** Whether any top-level assistant text reached the client since the last
798
- * stretch boundary. Set as a side effect of sending in the consumer's
799
- * `sendUpdate`, never at an emission site; read at the terminal `result`
800
- * to tell a turn whose answer was already delivered from one that only
801
- * ever carried it on `result` (issue #453). Session-level (not
802
- * consumer-scoped) so cancel()'s inline settle can clear it.
803
- *
804
- * The CURRENT boundary set — a new clear site must be added here: the
805
- * result case's `finally` (user-turn results), settleActive's wasHeld
806
- * clear (every held-turn settle lane: drain settle, both hand-offs,
807
- * stream-done), failActive, the force-cancel backstop, the idle
808
- * cancelled-settle, the autonomous-result close (only with no turn
809
- * active OR queued — see its queued-turn guard), and cancel()'s inline
810
- * mirror.
811
- *
812
- * Deliberately NOT reset on turn activation: activation can fire
813
- * mid-message (see the echo hand-off), so a flag cleared there would
814
- * forget text that already streamed and the result text would be emitted
815
- * a second time. Neither the consolidated `assistant` message nor a
816
- * `stream_event` carries `origin`, so an autonomous cycle's prose is
817
- * indistinguishable from a user turn's here and sets the flag too; the
818
- * autonomous-result close normally ends that stretch so a replayed
819
- * prompt behind it still delivers, and only in the racing window (a
820
- * turn already active or queued when the autonomous result lands) does
821
- * the replayed turn stay silent rather than risk a duplicate. */
822
- emittedAssistantText: boolean;
823
- /** The most recent `session_state_changed` state the consumer processed.
824
- * Read by cancel() to decide whether the interrupt will produce a
825
- * trailing idle worth pre-counting: interrupting a RUNNING cycle yields
826
- * one; interrupting an already-idle session (the common held-turn shape)
827
- * yields none, and a pre-counted debt that never drains would mask one
828
- * future issue-#825 detection. */
829
- lastSessionState?: "idle" | "running" | "requires_action";
830
- /** How many trailing `session_state_changed: idle` messages are already
831
- * accounted for: every result is followed by one (user-turn results that
832
- * terminate a turn — settle, reject, or orphan skip — and autonomous
833
- * cycles alike), as is a cancelled turn settled by the next turn's echo
834
- * hand-off or by cancel()'s inline settle of a held turn whose interrupt
835
- * pre-empts a running cycle — the reason this lives on the Session:
836
- * cancel() must be able to record the debt. The idle handler absorbs
837
- * owed idles; an idle that arrives when NONE is owed while the active
838
- * turn is still unsettled means the SDK ended the turn without ever
839
- * emitting its result, so the turn will never settle on its own (issue
840
- * #825). Stream-level debt, deliberately NOT reset per turn: a lagged
841
- * idle can arrive after the next turn has already activated (issue
842
- * #773), and the debt is what attributes it to the turn that owed it.
843
- * Over-counting (an idle the SDK never emits) is benign: the counter
844
- * just absorbs one future idle, and detection degrades to the status quo
845
- * rather than misfiring. */
846
- owedTrailingIdles: number;
847
- /** Maps the ACP `messageId` we expose to clients (see `messageIdForGrouping`)
848
- * to the SDK message uuid that the Agent SDK's rewind/resume APIs key on
849
- * (`Query.rewindFiles` takes a user-message uuid; `resumeSessionAt` takes an
850
- * `SDKAssistantMessage.uuid`). For assistant turns the two differ — the ACP
851
- * id is the Anthropic API message id (`msg_…`), available at `message_start`
852
- * so streamed chunks can carry it, while the uuid only arrives on the
853
- * consolidated message — so a client can only ask to rewind/fork by the id it
854
- * was given, and we need this table to translate it back.
855
- *
856
- * Populated as a byproduct of the message loop (the consolidated message
857
- * carries both ids) and of `replaySessionHistory` on load, so no extra
858
- * `getSessionMessages` read is needed at rewind time. Last-write-wins
859
- * naturally yields the turn-boundary uuid when one `msg_…` spans several
860
- * content-block messages.
861
- *
862
- * `unstable_forkSession` reads it to find the fork point without a read of
863
- * the transcript. The map lives until the session closes. */
864
- messageIdToUuid: Map<string, string>;
865
- /** Durable-for-this-consumer failure state shared with session/load replay.
866
- * Keeping it on the Session lets replay seed a failure that the persistent
867
- * consumer can later clear with the same id and a higher revision. */
868
- sessionFailureState: SessionFailureState;
869
- /** State of the `--hide-claude-auth` subscription guard for this session.
870
- * Built on the first guarded turn; most sessions never need it. */
871
- claudeSubscriptionGuard?: ClaudeSubscriptionGuardState;
872
- /** Identity kind of the account this session was created on. The CLI probe
873
- * compares its own read against it to notice that the credential behind the
874
- * cached account was swapped. Undefined when the account carried no
875
- * identity signal, which is "nothing to compare", not a match. */
876
- accountKind?: AuthStatusKind;
877
- /** Set under `--hide-claude-auth` when the CLI reported a sign-out during
878
- * this session. The query is closed and the account it cached at
879
- * `initialize` now describes a credential that no longer works, so the next
880
- * turn recreates the query before it runs. */
881
- needsSignOutRespawn?: boolean;
882
- /** The in-flight recreation, so turns that arrive together share one. */
883
- signOutRespawn?: Promise<void>;
884
- } & sessionIndex.SessionIndexFields;
885
- /** Result-message origin kinds that mark an AUTONOMOUS cycle — work the
886
- * model did on its own (a task-notification followup, a peer/coordinator/
887
- * observer message it handled) rather than the user's prompt. Absent,
888
- * `human`, and `channel` origins are the user's own turn (this adapter's
889
- * prompts arrive as the ACP channel on some CLI configurations — ALL
890
- * channel servers are treated as user, so a foreign channel integration's
891
- * autonomously-handled result is misclassified as the user's; accepted,
892
- * see below), and `auto-continuation` continues the user's turn, so its
893
- * result is the turn's real terminal.
894
- *
895
- * Deliberately fail-OPEN: an unknown future kind defaults to the user
896
- * lane — including `unclassified` (SDK 0.3.232+), the CLI's own "couldn't
897
- * attribute this" marker, which gets the same safe default. Misrouting a
898
- * USER result into the autonomous lane hangs the prompt un-detectably
899
- * (the result is skipped, its trailing idle absorbed as owed, so the
900
- * #825 detector can't fire); misrouting an autonomous result into the
901
- * user lane is the bounded misattribution class this set exists to
902
- * reduce.
903
- *
904
- * Exception: a result from one of these origins that names a pending prompt
905
- * in `user_message_uuids` consumed that folded prompt and takes the user
906
- * lane (see the result handler). */
907
- export declare const AUTONOMOUS_RESULT_ORIGINS: ReadonlySet<SDKMessageOrigin["kind"]>;
908
- /** Compute a stable fingerprint of the session-defining params so we can
909
- * detect when a loadSession/resumeSession call requires tearing down and
910
- * recreating the underlying Query process. Every option classified in
911
- * {@link OPTION_REBUILDS_SESSION} is covered, so a warm resume never silently
912
- * keeps stale values. MCP servers are sorted by name, and skills are
913
- * normalized as a set, so ordering differences don't trigger unnecessary
914
- * recreations. */
915
- export declare function computeSessionFingerprint(params: {
916
- cwd: string;
917
- mcpServers?: NewSessionRequest["mcpServers"];
918
- additionalDirectories?: NewSessionRequest["additionalDirectories"];
919
- systemPrompt?: NewSessionRequest["systemPrompt"];
920
- _meta?: NewSessionRequest["_meta"];
921
- }): string;
922
- export type SDKMessageFilter = {
923
- type: string;
924
- subtype?: string;
925
- origin?: SDKMessageOrigin["kind"];
926
- };
927
- /**
928
- * Extra metadata that can be given when creating a new session.
929
- */
930
- export type NewSessionMeta = {
931
- claudeCode?: {
932
- /**
933
- * Options forwarded to Claude Code when starting a new session.
934
- * Those parameters will be ignored and managed by ACP:
935
- * - cwd
936
- * - includePartialMessages
937
- * - permissionMode
938
- * - canUseTool
939
- * - executable
940
- * Those parameters will be used and updated to work with ACP:
941
- * - hooks (merged with ACP's hooks)
942
- * - mcpServers (merged with ACP's mcpServers)
943
- * - disallowedTools (merged with ACP's disallowedTools)
944
- * - tools (passed through; defaults to claude_code preset if not provided)
945
- * - allowDangerouslySkipPermissions (set to `false` to remove bypassPermissions
946
- * from this session; repeat it on session/load. `true` cannot override root)
947
- */
948
- options?: Options;
949
- /**
950
- * When set, raw SDK messages are emitted as extNotification("_claude/sdkMessage", message)
951
- * in addition to normal processing.
952
- * - true: emit all messages
953
- * - false/undefined: emit nothing (default)
954
- * - SDKMessageFilter[]: emit only messages matching at least one filter
955
- */
956
- emitRawSDKMessages?: boolean | SDKMessageFilter[];
957
- };
958
- additionalRoots?: string[];
959
- };
960
- export type { ToolUpdateMeta } from "./tool-calls/renderer.js";
961
- export type ToolUseCache = {
962
- [key: string]: {
963
- type: "tool_use" | "server_tool_use" | "mcp_tool_use";
964
- id: string;
965
- name: string;
966
- input: unknown;
967
- };
968
- };
969
- type StreamedToolInput = {
970
- id: string;
971
- name: string;
972
- partialJson: string;
973
- inString: boolean;
974
- escaped: boolean;
975
- objectDepth: number;
976
- arrayDepth: number;
977
- /** Offset of the most recent comma at the top level of the input object
978
- * (-1 before the first). Everything before it is a complete field. */
979
- lastTopLevelComma: number;
980
- /** The comma offset the last emitted refinement was sliced at (-1 before the
981
- * first), so a field boundary only triggers one recovery attempt. */
982
- emittedThroughComma: number;
983
- };
984
- export type StreamedToolInputCache = Map<string, Map<number, StreamedToolInput>>;
985
- /**
986
- * Return user-message content with local-command and injected-context marker
987
- * tags removed, or `null` if nothing meaningful remains (caller should skip
988
- * the message). Preserves real prose that's mixed in alongside the markers —
989
- * e.g. a message like `<command-name>…</command-name>hi` becomes `hi`, and
990
- * `hi<system-reminder>…</system-reminder>` becomes `hi`.
991
- */
992
- export declare function stripLocalCommandMetadata(content: unknown): unknown | null;
993
- export declare function isLocalCommandMetadata(content: unknown): boolean;
994
- /**
995
- * True for the synthetic assistant message the CLI injects into the transcript
996
- * when a turn fails authentication (e.g. "Not logged in · Please run /login",
997
- * "Session expired. Please run /login to sign in again."). The `/login`
998
- * instruction is Claude Code TUI-specific and meaningless to ACP clients
999
- * (issue #863). The live prompt loop suppresses the text and fails the turn
1000
- * with `authRequired` so the client can run its own auth flow; replay must
1001
- * skip it too — both for parity with what the client saw live and because the
1002
- * message stays in the transcript forever, so it would resurface on every
1003
- * session/load even after the user has logged back in.
1004
- *
1005
- * Takes the API message (`message.message`), which replay only knows as
1006
- * `unknown`. The persisted record's structured `error` marker is stripped by
1007
- * `getSessionMessages`, and the CLI does not always set it to
1008
- * `authentication_failed` anyway: an expired login with no refresh token
1009
- * ("Login expired · Run /login to sign in again, …") arrives as
1010
- * `invalid_request`. So the synthetic model + text is what both paths match on.
1011
- * Usage-limit banners are excluded because some of them also mention `/login`
1012
- * (to switch accounts) and have their own handling.
1013
- */
1014
- export declare function isSyntheticLoginMessage(apiMessage: unknown): boolean;
1015
- /**
1016
- * True for a transcript message delivered to the model from another agent,
1017
- * session or channel. Since SDK 0.3.284 `getSessionMessages` returns these as
1018
- * `is_meta` user messages whose content is the full harness framing (envelope
1019
- * XML plus the "not typed by your user" preamble). The live prompt loop never
1020
- * renders them, so replay skips them too rather than presenting them as text
1021
- * the user typed. Other `is_meta` messages (compact summaries) are kept.
1022
- *
1023
- * `is_meta` and `origin` are runtime fields not declared on `SessionMessage`.
1024
- */
1025
- export declare function isReplayHiddenMetaMessage(message: unknown): boolean;
1026
- /**
1027
- * Client-facing surface the agent calls back into. This is the subset of ACP
1028
- * client methods the agent actually uses, expressed as a narrow interface so
1029
- * tests can supply lightweight mocks. In production it is backed by
1030
- * {@link ClientConnection} over the SDK's typed `AgentContext`.
1031
- */
1032
- export interface AcpClient {
1033
- sessionUpdate(params: AcpSessionNotification): Promise<void>;
1034
- /** `signal`, when aborted, sends `$/cancel_request` for the in-flight
1035
- * permission request so the client can dismiss its prompt, and rejects the
1036
- * call at once: a client that ignores the cancel never answers. */
1037
- requestPermission(params: AcpPermissionRequest, signal?: AbortSignal): Promise<RequestPermissionResponse>;
1038
- readTextFile(params: ReadTextFileRequest): Promise<ReadTextFileResponse>;
1039
- writeTextFile(params: WriteTextFileRequest): Promise<WriteTextFileResponse>;
1040
- /** `signal`, when aborted, sends `$/cancel_request` for the in-flight
1041
- * elicitation so the client can dismiss its prompt, and rejects the call
1042
- * at once, as {@link requestPermission} does. */
1043
- createElicitation(params: CreateElicitationRequest, signal?: AbortSignal): Promise<CreateElicitationResponse>;
1044
- completeElicitation(params: CompleteElicitationNotification): Promise<void>;
1045
- /** Send a custom (extension) notification, e.g. `_claude/sdkMessage`. */
1046
- extNotification(method: string, params: Record<string, unknown>): Promise<void>;
1047
- }
1048
- export declare class ClaudeAcpAgent {
1049
- sessions: {
1050
- [key: string]: Session;
1051
- };
1052
- client: AcpClient;
1053
- clientCapabilities?: ClientCapabilities;
1054
- /** The tool call report choices, read once from {@link clientCapabilities} in `initialize`. */
1055
- private toolCallCapabilities;
1056
- logger: Logger;
1057
- private readonly sessionModes;
1058
- gatewayAuthRequest?: GatewayAuthRequest;
1059
- /** Set while ACP overrides the agent's native provider configuration. */
1060
- providerConfig?: ProviderConfig;
1061
- /** Serializes provider changes while every open query is recreated between turns. */
1062
- private providerUpdate;
1063
- /** Per session: queue that runs mode/config changes and query restarts one at a time. */
1064
- private readonly configurationChanges;
1065
- private readonly exitPlan;
1066
- /** The connection's `authStatus` state and pushes, connection-scoped like
1067
- * `authenticate`/`logout`. */
1068
- private readonly authStatus;
1069
- /** Last auth identity reported to the client. Undefined means "not determined yet". */
1070
- get currentAuthStatus(): AuthStatus | undefined;
1071
- /** Grace period before a `session/cancel` forces a wedged prompt loop to
1072
- * return "cancelled". See {@link DEFAULT_FORCE_CANCEL_GRACE_MS}. Mutable so
1073
- * tests can shrink it. */
1074
- forceCancelGraceMs: number;
1075
- /** How long `canUseTool` or a hook waits for the consumer to reach a tool
1076
- * use (see `isStoppedWorkToolUse`). Mutable so tests can shrink it. */
1077
- toolUseWaitMs: number;
1078
- /**
1079
- * The subagent replay of each session's last load, until
1080
- * {@link publishCurrentSubagentStates} sends its children's current states.
1081
- */
1082
- private readonly replayedSubagents;
1083
- /**
1084
- * AIR's draft: the model that the last load of each session replayed to each
1085
- * child session, as the model id and the entry that went out. See
1086
- * {@link publishReplayedChildModels}.
1087
- */
1088
- private readonly replayedChildModels;
1089
- /** Counts the prompts `startTurn()` has received, across sessions. */
1090
- private promptsReceived;
1091
- /** Per session, the `promptsReceived` count when its last cancel started.
1092
- * A prompt received before that cancel that `startTurn()` had not queued
1093
- * yet ends as cancelled instead of being queued. */
1094
- private readonly cancelledThrough;
1095
- /**
1096
- * The owner of the foreground work of each session while it runs (see
1097
- * {@link ForegroundOwner}), by the session id that the client knows. A
1098
- * clear-context restart replaces the Claude Code session behind that id and
1099
- * moves the running turn to it, so the work belongs to the id, not to a
1100
- * {@link Session}.
1101
- */
1102
- private readonly foregroundWork;
1103
- /** The session index (docs/air-extensions.md, "Session index"). */
1104
- private readonly sessionIndex;
1105
- /**
1106
- * Whether a turn ends at its result while background subagents that it
1107
- * spawned or resumed still run. Only an AIR client that declares
1108
- * `backgroundSubagents` gets this. Every other client keeps the hold of
1109
- * `Turn.deferredSettle`.
1110
- */
1111
- private endsTurnsWithLiveSubagents;
1112
- constructor(client: AcpClient, logger?: Logger);
1113
- initialize(request: InitializeRequest): Promise<InitializeResponse>;
1114
- newSession(params: NewSessionRequest): Promise<NewSessionResponse>;
1115
- /**
1116
- * Start the CLI of a loaded session, and replay the history while the CLI
1117
- * starts. The CLI start takes most of the load time, and the replay needs
1118
- * only the transcript and the {@link ReplayState}. An invalid `cwd` fails
1119
- * before the first update. A failed CLI start stops the replay.
1120
- */
1121
- private createSessionWhileReplaying;
1122
- /**
1123
- * Copies the session's transcript into a new session, then starts that
1124
- * session, so the client can prompt it as soon as the response arrives, as
1125
- * the schema requires of a fork. It starts like a resumed session: from the
1126
- * copied transcript, with the model and the permission mode it records. A
1127
- * later load or resume with the same settings reuses it.
1128
- */
1129
- unstable_forkSession(params: ForkSessionRequest): Promise<ForkSessionResponse>;
1130
- /** Runs `fork`, the handler of a `session/fork` request of `sourceId`,
1131
- * with its forks held back from the session list (see
1132
- * {@link sessionIndex.SessionIndexConnection.forking}). */
1133
- forking<T>(sourceId: string, fork: () => Promise<T>): Promise<T>;
1134
- resumeSession(params: ResumeSessionRequest): Promise<ResumeSessionResponse>;
1135
- loadSession(params: LoadSessionRequest): Promise<LoadSessionResponse>;
1136
- /**
1137
- * One page of the sessions, newest first. The cursor is the offset of the
1138
- * page. The SDK then orders the transcripts by their modification time and
1139
- * reads the start and the end only of the transcripts of the page.
1140
- */
1141
- listSessions(params: ListSessionsRequest): Promise<ListSessionsResponse>;
1142
- /** A stored session title as this client shows it (see
1143
- * {@link sessionIndex.SessionIndexConnection.clientTitle}). */
1144
- clientTitle(title: string): string;
1145
- /** `_session/batch_get`, `_session/list/subscribe`, `_session/list/unsubscribe`, `_session/rename`,
1146
- * `_session/archive`, `_session/unarchive`. */
1147
- subscribeSessionList(params: ListSubscribeRequest): Promise<import("./session-index/list-subscriptions.js").ListSubscribeResponse>;
1148
- unsubscribeSessionList(params: ListUnsubscribeRequest): Promise<{
1149
- [x: string]: never;
1150
- }>;
1151
- batchGetSessions(params: BatchGetSessionsRequest): Promise<import("./session-index/service.js").BatchGetSessionsResponse>;
1152
- renameSessionTitle(params: RenameSessionRequest): Promise<{
1153
- [x: string]: never;
1154
- }>;
1155
- archiveSession(params: SessionIdRequest): Promise<{
1156
- [x: string]: never;
1157
- }>;
1158
- unarchiveSession(params: SessionIdRequest): Promise<{
1159
- [x: string]: never;
1160
- }>;
1161
- /**
1162
- * `authenticate` — the legacy gateway methods store a provider override that
1163
- * every later session reads, once {@link validatedGatewayAuthRequest} accepts
1164
- * its payload.
1165
- */
1166
- authenticate(_params: AuthenticateRequest): Promise<void>;
1167
- /** Stores `next` and pushes it to the client when it changed (see {@link AuthStatusReporter.set}). */
1168
- setAuthStatus(next: AuthStatus | undefined): void;
1169
- /**
1170
- * Feed the completed probe to the `--hide-claude-auth` guard.
1171
- *
1172
- * The account cached at `initialize` is the guard's fact, and the CLI can
1173
- * swap the credential behind it between two turns (a Console key removed and
1174
- * a claude.ai login put in its place) without any turn failing. A read that
1175
- * reports a different kind of identity than the session was created on
1176
- * proves that fact stale.
1177
- *
1178
- * The probe decides nothing, and it interrupts nothing. Since the read is
1179
- * fired at the start of every user prompt, it usually lands in the middle of
1180
- * the turn it belongs to; all it may do there is set a flag. The turn runs to
1181
- * its end on the query it started on, the NEXT prompt consumes the flag and
1182
- * recreates the query, the new `initialize` reports the real account, and the
1183
- * creation guard judges it. So a probe can never refuse or abort a turn, and
1184
- * a wrong read costs one query recreation, not a false refusal.
1185
- */
1186
- private markSessionsWhoseAccountKindChanged;
1187
- unstable_listProviders(_params: ListProvidersRequest): Promise<ListProvidersResponse>;
1188
- /**
1189
- * `providers/set` — replace the full configuration for the `main` provider
1190
- * (validated by {@link providerConfigFromSetRequest}). Config is
1191
- * process-scoped and applies to sessions created or loaded after this call.
1192
- */
1193
- unstable_setProvider(params: SetProviderRequest): Promise<SetProviderResponse>;
1194
- /**
1195
- * `providers/disable` ends ACP ownership of the single mutually exclusive
1196
- * backend slot and restores the agent's native routing state.
1197
- */
1198
- unstable_disableProvider(params: DisableProviderRequest): Promise<DisableProviderResponse>;
1199
- resolveProviderConfig(): ProviderConfig | null;
1200
- logout(_params: LogoutRequest): Promise<void>;
1201
- /** The structured replacement for a prompt that is exactly `/usage` or a
1202
- * `/mcp` command. Claude Code runs the command, and the replacement takes
1203
- * the place of its text. Claude Code refuses a `/mcp` reconnect, enable,
1204
- * or disable in SDK mode. The `/mcp` producer runs them through the SDK
1205
- * control API when the text arrives, so the action stays in the turn. */
1206
- private localCommandMarkdown;
1207
- /**
1208
- * Serves an ACP v1 `session/prompt`, which answers when the turn ends. The
1209
- * outcome of a turn is field for field a v1 prompt response.
1210
- *
1211
- * A content block that the agent does not advertise, such as `audio`, fails
1212
- * the request with invalid params (-32602) before anything is queued:
1213
- * `promptToClaude` would drop it.
1214
- */
1215
- prompt(params: PromptRequest, origin?: TurnOrigin): Promise<PromptResponse>;
1216
- /**
1217
- * Starts a turn for a prompt. Resolves once the prompt is queued for Claude
1218
- * Code, and rejects only when the prompt is refused before that. From then
1219
- * on, `events` reports how the turn goes (see {@link TurnEvents}), possibly
1220
- * before this resolves.
1221
- */
1222
- startTurn(params: PromptRequest, events: TurnEvents, origin?: TurnOrigin): Promise<void>;
1223
- /** Runs the command, and sends its reply (see `runRemoteControlCommand`). */
1224
- private runRemoteControlCommand;
1225
- /** `--hide-claude-auth` applies only to the CLI's own login. A provider
1226
- * override (`providers/set` or gateway `authenticate`) routes traffic away
1227
- * from it, so the subscription guard is off while one is active. */
1228
- private claudeSubscriptionGuardActive;
1229
- /** Record that the account cached at `initialize` is wrong, and — unless the
1230
- * caller defers it — end the query.
1231
- *
1232
- * Only under `--hide-claude-auth`. That cached account is this
1233
- * integration's source of truth, and two things prove it wrong: a sign-out
1234
- * during the session, and a CLI probe that finds a different identity. In
1235
- * both cases the credential behind the cached account is gone, and whatever
1236
- * replaces it is invisible until a new `initialize` runs. The flag makes
1237
- * the next prompt recreate the query, so the creation guard decides on the
1238
- * real account.
1239
- *
1240
- * `endQuery` says whether the query dies now. A sign-out has already killed
1241
- * the turn, so its stream is closed at once. A probe has killed nothing: it
1242
- * runs beside a turn that is still producing output, and closing there would
1243
- * abort a turn the user is watching. It therefore leaves the stream alone
1244
- * and lets the recreation at the next prompt close it (`recreateSignedOutQuery`
1245
- * closes it too, and both are idempotent).
1246
- *
1247
- * Idempotent: one sign-out reaches this twice (the synthetic login message
1248
- * and the turn's error-shaped result), and the second call must not close
1249
- * a stream the first one already closed. Closing settles the queued turns
1250
- * through the consumer's end-of-stream path, which rejects each one. */
1251
- private markSessionForSignOutRespawn;
1252
- /** Recreate the query of a signed-out session, keeping the ACP session id and
1253
- * resuming the Claude session so the history survives. Returns the session
1254
- * the caller must go on with: the new one, or the argument when no
1255
- * recreation is due.
1256
- *
1257
- * When the CLI never persisted that conversation — the first turn was the
1258
- * one that signed out — the resume cannot succeed, so a fresh query starts
1259
- * under the same id. The session then keeps working, with an empty history.
1260
- *
1261
- * The recreation runs the full creation guard, so a subscription account is
1262
- * refused with the subscription reason, a still-signed-out account with the
1263
- * plain sign-out error, and an accepted credential proceeds. A refusal keeps
1264
- * the old husk in the session map, so the client can sign in and retry on
1265
- * the same session instead of meeting "Session not found".
1266
- *
1267
- * Returns `undefined`, not a resolved promise, when no recreation is due:
1268
- * the callers enqueue their turn in one synchronous section, and an extra
1269
- * microtask there would let the caller observe a half-built turn.
1270
- *
1271
- * A live turn also postpones it. A probe marks the session without ending
1272
- * the query, so a turn can still be running when the mark is read — by a
1273
- * `steer` injecting into it, say. Recreating there would close the stream
1274
- * under the turn and kill output the user is watching, so the flag waits for
1275
- * the next turn boundary. A sign-out is not affected: it closed the stream
1276
- * when it marked the session, and a closed stream recreates immediately. */
1277
- private respawnSignedOutSession;
1278
- private awaitSignOutRespawn;
1279
- /** Tells the user about client-provided MCP servers that `system`/init
1280
- * reports as `failed` or `needs-auth`, once per server per session. Servers
1281
- * from the user's Claude Code settings are left to `/mcp`: they are the same
1282
- * in every session, so a broken one would be reported in every session. A
1283
- * `needs-auth` server is reported only when the OAuth flow can't run (no
1284
- * URL elicitation on the client, or no `mcpAuthenticate` on the query);
1285
- * otherwise `startMcpAuthentication` asks the user to sign in. */
1286
- private reportMcpServerStartupFailures;
1287
- /** Queued per session, so a choice sent during the respawn lands on the new query. */
1288
- private recreateSignedOutQuery;
1289
- /**
1290
- * Starts a new query for the session `sessionId`, which ran on this
1291
- * connection and whose query is gone: it resumes the stored conversation.
1292
- * `resume` names the Claude session, which shares the ACP session id, so the
1293
- * new query continues the same conversation under the same id. Claude Code
1294
- * writes the conversation at the first prompt, so resuming a session that was
1295
- * never prompted fails with `sessionNotFound`, and keeps failing. Such a
1296
- * session starts a fresh query under the same id instead: it has no history
1297
- * to lose, and the client keeps a session it can use.
1298
- */
1299
- private recreateLiveSession;
1300
- /** Run the `--hide-claude-auth` guard before a turn starts. The returned
1301
- * promise rejects with the `authRequired` error when a claude.ai
1302
- * subscription would pay, or when the account holds no credential this
1303
- * integration accepts. Every entry point that starts a turn must await it,
1304
- * so the refusal reaches the client instead of a detached promise.
1305
- *
1306
- * Returns `undefined`, not a resolved promise, while the guard is off: the
1307
- * callers run in the same synchronous section as the turn they enqueue, and
1308
- * an extra microtask there would let the caller observe a half-built turn. */
1309
- private runClaudeSubscriptionGuard;
1310
- goal(params: GoalRequest): Promise<GoalControlResponse>;
1311
- private publishGoal;
1312
- /**
1313
- * Sends the `_meta` of a session's {@link PromptSuggestions}: the follow-up
1314
- * prompt the CLI predicted for the next turn, or the clear of the one the
1315
- * client holds. Only AIR renders it, so only an AIR session has the state;
1316
- * see `docs/air-extensions.md`.
1317
- */
1318
- private publishPromptSuggestion;
1319
- private publishTaskPlan;
1320
- private publishGoalFromPrompt;
1321
- private publishRuntimeGoal;
1322
- /** Steer the session per the ACP steering wire protocol: inject a follow-up
1323
- * message into the turn that is currently running. If that turn already
1324
- * settled, the established default starts a new detached turn; Hosts may opt
1325
- * into the host-owned `promptRequired` fallback through request `_meta`.
1326
- *
1327
- * When a turn is in flight this injects (returns `injected`): unlike
1328
- * `prompt()`, it does NOT create a Turn or enqueue on `turnQueue`; it pushes
1329
- * an `SDKUserMessage` onto the same streaming input, which the SDK routes
1330
- * into the in-flight turn. The injected message's echo carries a uuid that
1331
- * matches no queued turn, so the consumer drops it as an unrelated replay
1332
- * without promoting/settling anything. It is normally delivered at priority
1333
- * `now` so it pre-empts the current generation (interrupting a single-shot
1334
- * response, or slotting in between a multi-step turn's tool calls). While a
1335
- * permission or elicitation is awaiting user input it uses `later`, because
1336
- * interrupting that SDK callback cancels the ACP request and can strand the
1337
- * prompt (IJAI-1191). The steered message's own output streams via
1338
- * `session/update`, not this response.
1339
- *
1340
- * Pre-empting generation means ABORTING: the interrupted cycle emits a
1341
- * `result` of its own and the steered message runs as a second one. A steer
1342
- * during a foreground tool call moves that tool (Bash, Agent, MCP) to the
1343
- * background instead, and may join the running cycle (CLI 2.1.286). Either
1344
- * way the turn is marked (`Turn.steeredEchoes`) to settle only once a result
1345
- * answers the steer.
1346
- *
1347
- * When the session is idle, the opt-in path returns `promptRequired` WITHOUT
1348
- * calling `prompt()`, pushing SDK input, or mutating `turnQueue`: the content
1349
- * stays Host-owned so the Host can submit it through a standard
1350
- * `session/prompt`. Without the opt-in, the existing detached `prompt()` and
1351
- * `startedNewTurn` result are preserved for compatibility. */
1352
- steer(params: SteerRequest): Promise<SteerResponse>;
1353
- stopAsyncTask(params: AsyncTaskStopRequest): Promise<AsyncTaskStopResponse>;
1354
- /** Lazily start the per-session consumer that drains the SDK query stream for
1355
- * the session's whole life. Idempotent: only the first `prompt()` starts it. */
1356
- private ensureConsumer;
1357
- /** The single, long-lived consumer of the SDK query stream for a session. It
1358
- * forwards every message as ACP `sessionUpdate`s (so background/between-turn
1359
- * output streams live, not just while a prompt is awaiting) and settles each
1360
- * Turn's deferred when that turn ends. Replaces the per-prompt message loop;
1361
- * `params` only carries the (session-invariant) `sessionId`. */
1362
- private runConsumer;
1363
- /** Route one orphaned command into the session's orphan-accounting lane:
1364
- * the per-uuid map on msg_lifecycle_v1 CLIs (drained by the command's own
1365
- * terminal lifecycle frame and the echo-less-result skip), the plain count
1366
- * elsewhere (the count lane can't express per-command states, so `state`
1367
- * only matters on the map lane). Both orphan-producing paths — cancel()'s
1368
- * queued-turn sweep and the consumer's force-cancel wedge path — must seed
1369
- * through here so the lane split stays a single mechanism.
1370
- *
1371
- * Known window: `msgLifecycleV1` is only learnable from the stream's first
1372
- * `system`/init (the control-channel initialize carries no capabilities),
1373
- * so a cancel that beats that drain seeds the COUNT lane on a
1374
- * lifecycle-capable CLI — where command coalescing can leave the count
1375
- * stale by N-1 (the pre-map bug, confined to this sub-second window and
1376
- * still healed by the next activation's reset). Structural until the SDK
1377
- * exposes capabilities before the stream starts. */
1378
- private trackOrphanCommand;
1379
- /** Ask Claude Code to drop user messages it still has queued, so that a
1380
- * prompt a cancel settled is not run after all. Claude Code keeps queued
1381
- * messages through an interrupt and runs them next (the receipt's
1382
- * `still_queued`), unless they are cancelled first with
1383
- * `cancel_async_message`: a no-op for a message it already dequeued, which
1384
- * then still runs, as an orphan (see `orphanCommands`).
1385
- *
1386
- * Not awaited: the SDK writes control requests in call order, so the drops
1387
- * reach Claude Code before a request sent after them, and a wedged CLI must
1388
- * not hold up the cancel. The orphan accounting needs no update here: a
1389
- * dropped message gets a `cancelled` lifecycle frame and is missing from the
1390
- * interrupt receipt's `still_queued`, which both already account for. The
1391
- * SDK implements the request as `Query.cancelAsyncMessage` without typing
1392
- * it, so it is looked up, and a CLI that lacks it rejects the request. */
1393
- private dropQueuedMessages;
1394
- cancel(params: CancelNotification): Promise<void>;
1395
- /**
1396
- * Cancels the current work of the subagent child session `sessionId`, which
1397
- * its `cancel` capability permits on the subagents RFD form, without
1398
- * cancelling its parent (see `NativeSubagentRuntime.cancelChild`). Returns
1399
- * false when no session has such a child.
1400
- */
1401
- private cancelChildSession;
1402
- /**
1403
- * Stops each background workflow of the session that still runs, after the
1404
- * interrupt of a `session/cancel` spared it (see
1405
- * `Session.stopsWorkflowsOnCancel`). Claude Code reports each one
1406
- * `stopped`, along with the commands inside it, and starts no model cycle
1407
- * for it, as when the interrupt killed it. Every background workflow is
1408
- * stopped, whoever launched it, because the interrupt killed them all.
1409
- */
1410
- private stopBackgroundWorkflows;
1411
- /** Cancel the session's turns and interrupt the SDK query. With
1412
- * `awaitInterrupt: false` the interrupt is sent, but its reply is not
1413
- * awaited. `teardownSession` uses that: it closes the query right after, and
1414
- * the reply can queue behind a slow control request, such as the background
1415
- * `getContextUsage` of a fresh session. */
1416
- private cancelTurns;
1417
- /** Release a query that was spawned but never registered as a session. */
1418
- private discardUnregisteredQuery;
1419
- /** Mark a session's SDK query stream as permanently ended and release the
1420
- * resources tied to it: drop the consumer handle, dispose the settings
1421
- * watchers, end the input stream, and close the query (which terminates the
1422
- * subprocess). The query iterator is not revivable, so `prompt()`/`cancel()`
1423
- * consult `queryClosed` and fail/short-circuit instead of acting on a dead
1424
- * stream. Idempotent (guarded by `queryClosed`), so the consumer's done/error
1425
- * paths and a later `teardownSession` can all call it without double-releasing.
1426
- *
1427
- * Deliberately does NOT abort `session.abortController`: that controller may be
1428
- * CLIENT-supplied (`_meta.claudeCode.options.abortController`) and reused, so
1429
- * aborting it on a spontaneous stream end would cancel the client's own work
1430
- * or make a sibling session born aborted. `query.close()` already terminates
1431
- * the subprocess; aborting the signal belongs in `teardownSession` (explicit
1432
- * destroy), not here. Also does NOT remove the session from the map — that is
1433
- * `teardownSession`'s job — so prompt() can still answer with a clear "session
1434
- * ended" error after an unexpected stream close. The leftover session object
1435
- * is a lightweight husk (its heavy resources are released here) and is evicted
1436
- * on the next closeSession/deleteSession or when the connection's `dispose()`
1437
- * runs. */
1438
- private closeQueryStream;
1439
- /** Cleanly tear down a session: cancel in-flight work, release stream
1440
- * resources, and remove it from the session map. Returns once the turns it
1441
- * cancels have ended, so their `session/prompt` responses go out before
1442
- * the caller answers. A wedged consumer holds it at most
1443
- * {@link TEARDOWN_TURN_END_TIMEOUT_MS}. */
1444
- private teardownSession;
1445
- /** Tear down all active sessions. Called when the ACP connection closes. */
1446
- dispose(): Promise<void>;
1447
- /** Idempotent: a session that is not loaded here is already closed. */
1448
- closeSession(params: CloseSessionRequest): Promise<CloseSessionResponse>;
1449
- /** Per client: see {@link sessionIndex.SessionIndexConnection.deleteSession}. */
1450
- deleteSession(params: DeleteSessionRequest): Promise<DeleteSessionResponse>;
1451
- setSessionMode(params: SetSessionModeRequest): Promise<SetSessionModeResponse>;
1452
- setSessionConfigOption(params: SetSessionConfigOptionRequest): Promise<SetSessionConfigOptionResponse>;
1453
- private selectSessionConfigOption;
1454
- private replaySessionHistory;
1455
- readTextFile(params: ReadTextFileRequest): Promise<ReadTextFileResponse>;
1456
- writeTextFile(params: WriteTextFileRequest): Promise<WriteTextFileResponse>;
1457
- /** Runs `request`, a request that `requestSessionId` sends for the session
1458
- * `ownerSessionId`. When that is a subagent's child session, the child
1459
- * reports that it awaits the user while the request is open (the RFD form,
1460
- * see `NativeSubagentRuntime.awaitingUser`). `signal` aborts when Claude
1461
- * Code withdraws the request. */
1462
- private withChildAwaitingUser;
1463
- /** Mark a client request of the subagent `agentID` (absent for the main
1464
- * conversation) as awaiting user input for exactly the lifetime of its
1465
- * promise (see `Session.openUserInputs`). Steering consults the open
1466
- * requests synchronously, so a message arriving while any permission or
1467
- * elicitation card is open uses non-interrupting SDK delivery. */
1468
- private withPendingUserInput;
1469
- /** Whether Claude is working in the session `sessionId`: an unsettled turn in
1470
- * its queue, or foreground work that no turn owns, such as a cycle that
1471
- * Claude Code started on its own. */
1472
- private claudeIsWorking;
1473
- /** Make `owner` the foreground work of the session `sessionId` (see
1474
- * {@link ForegroundOwner}). If work already runs, it goes on under
1475
- * `owner`: a turn takes over a cycle that Claude Code started on its own,
1476
- * and only the owner's end ends the work. */
1477
- private startForeground;
1478
- /** End the foreground work of the session `sessionId`, if `owner` is that
1479
- * work. */
1480
- private endForeground;
1481
- /** Start a model cycle that Claude Code started on its own as the foreground
1482
- * work (see {@link ForegroundOwner}) when `message` is its first output:
1483
- * model output of the main conversation (not a subagent's) while no work
1484
- * runs. That includes a turn that v1 holds for its background subagents,
1485
- * whose work ended at its result, so its follow-up is a cycle. Output of
1486
- * the work a cancel stopped starts nothing (see Session.cancelled). */
1487
- private startAutonomousCycle;
1488
- /** Whether the client has been told that the session's work ended: by the
1489
- * response to the turn's prompt, so no turn is active. The client is told
1490
- * nothing of a cycle, so its end is its result or idle: until then, Claude
1491
- * Code's results for the cycle's tool calls still reach the client after a
1492
- * cancel. */
1493
- private workEndReported;
1494
- /** Whether the consumer drops what it reaches now as output of the work a
1495
- * cancel stopped: the client has been told that the work ended, and the
1496
- * window after the cancel is still open (see Session.cancelled). */
1497
- private dropsStoppedWorkOutput;
1498
- /**
1499
- * Whether the tool use `toolUseId`, which reaches `canUseTool` or a hook, is
1500
- * output of the work a cancel stopped that the consumer dropped (see
1501
- * `dropsStoppedWorkOutput`). Example: Claude Code runs a prompt that the
1502
- * cancel abandoned, and it asks to run a command. The consumer drops the
1503
- * tool use and its result, so a tool call shown for it would never end, and
1504
- * the client would keep it open (issue #1061).
1505
- *
1506
- * Claude Code calls `canUseTool` and hooks on its control channel, after it
1507
- * streamed the tool use, and the consumer can lag behind. So the session can
1508
- * still look cancelled while the consumer has the next prompt's echo, which
1509
- * ends the window, still ahead of the tool use. While a cancel's window may
1510
- * be open, this waits until the consumer reaches the tool use, for at most
1511
- * {@link toolUseWaitMs} or until `signal` aborts: the stream never shows
1512
- * some tool uses, such as SandboxNetworkAccess's. Without a cancel nothing
1513
- * is dropped, so it answers at once. It returns a promise only when it
1514
- * waits, so a permission request without a cancel goes out as soon as
1515
- * before.
1516
- */
1517
- private isStoppedWorkToolUse;
1518
- /** Waits until the consumer reaches the tool use `toolUseId` (see
1519
- * `isStoppedWorkToolUse`), then says whether it dropped it. */
1520
- private reachedInStream;
1521
- /** End the session's model cycle that Claude Code started on its own, if one
1522
- * runs. */
1523
- private endAutonomousCycle;
1524
- /** Whether a model cycle that Claude Code started on its own is the session's
1525
- * foreground work. A turn that took a cycle over owns the work from then on. */
1526
- private runsAutonomousCycle;
1527
- /** The ACP turn that owns a root request of the session now, if any. A
1528
- * model cycle that Claude Code started on its own owns no turn. A turn that
1529
- * took a cycle over owns it. A queued turn owns the request too, because
1530
- * Claude Code can ask for a queued prompt before the consumer reaches its
1531
- * echo (see `recordForegroundToolCall`). The ExitPlanMode request and the
1532
- * result of its interruption use this one rule, so an offered
1533
- * clear-context option always has a turn to continue. */
1534
- private requestOwnerTurn;
1535
- /** Forward a permission request to the client, wiring the tool call's
1536
- * `signal` through as a `cancellationSignal`. When the turn is cancelled
1537
- * while the client's prompt is still open the signal aborts, the SDK sends
1538
- * `$/cancel_request` and stops waiting for the client's answer. The
1539
- * rejection surfaces as the "Tool use aborted" that the callers expect.
1540
- * `canUseTool` decides what a `cancelled` outcome means. */
1541
- private requestPermissionFromClient;
1542
- /** Send the client an elicitation for a callback of Claude Code. When the
1543
- * callback's `signal` aborts, the SDK sends `$/cancel_request` and the call
1544
- * rejects at once, without waiting for a reply that a client ignoring the
1545
- * cancel never sends. Left open, the request would stay in
1546
- * `openUserInputs` (see {@link withPendingUserInput}), which keeps steering
1547
- * non-interrupting, and a child's `openRequests` would not drop. */
1548
- private elicitFromClient;
1549
- /** `signal`, also aborted when `teardownSession` aborts the
1550
- * `abortController` of session `sessionId`. Claude Code aborts a callback's
1551
- * own signal when its query closes, but not necessarily before
1552
- * `session/close` responds, and every pending permission request and
1553
- * elicitation of the session is cancelled with `$/cancel_request` before
1554
- * that response. */
1555
- private untilSessionClosed;
1556
- /** Settle the tool call `ensureToolCallEmitted` emitted for a
1557
- * SandboxNetworkAccess request once the request is answered. The callback
1558
- * asks for permission and runs nothing, so the SDK never sends a
1559
- * `tool_result` for its synthetic id, and the call would otherwise stay
1560
- * pending in the client. */
1561
- private settleSandboxNetworkCall;
1562
- /** Emit the `tool_call` a permission request references if it hasn't been sent
1563
- * yet, so the client has the tool call before being asked to approve it. The
1564
- * matching streamed tool_use chunk later refines it with a `tool_call_update`
1565
- * instead of emitting a duplicate (see `emittedToolCalls`). Built via the same
1566
- * `toolCallNotification` helper as the streamed path so the two are identical.
1567
- * Tools the stream renders as a plan (TodoWrite) or suppresses (Task*) are
1568
- * emitted too: a permission request referencing a tool call the client has
1569
- * never seen can trip strict clients (issue #851), so the reference must
1570
- * always resolve. Since the streamed path never completes those calls, they
1571
- * are resolved at tool_result time instead (see `toAcpNotifications`).
1572
- * `parentToolUseId` attributes a subagent's tool call to the Agent/Task call
1573
- * that spawned it, matching the streamed path's `_meta`. */
1574
- private ensureToolCallEmitted;
1575
- /**
1576
- * The owner of a tool use that Claude Code reports outside the stream, in
1577
- * `canUseTool` or a hook, for the subagent `agentID` or the root session.
1578
- * `parentToolUseId` is the Agent/Task tool call that spawned the subagent,
1579
- * as the streamed subagent path stamps it in `_meta.claudeCode` (see
1580
- * `liveBackgroundTasks`). `toolCallSessionId` is the session of an eagerly
1581
- * emitted tool call and of its requests: the subagent's child session once
1582
- * it is announced, else the root session. In the rare SDK ordering where
1583
- * the callback beats the spawning Agent/Task frame, the root keeps it; the
1584
- * later frame announces the child with its correct nested lineage.
1585
- */
1586
- private toolUseOwner;
1587
- /**
1588
- * The models of the session `sessionId`, for the `model` option of its
1589
- * subagents: the entries of the session's own `model` option.
1590
- */
1591
- private subagentModels;
1592
- private subagentConfigurationHook;
1593
- canUseTool(sessionId: string): CanUseTool;
1594
- /**
1595
- * Handle elicitation requests that originate from MCP servers by forwarding
1596
- * them to the client over ACP (see {@link answerMcpElicitation}).
1597
- */
1598
- private handleMcpElicitation;
1599
- /**
1600
- * Present the built-in AskUserQuestion tool's questions as an ACP form
1601
- * elicitation and return the answers as the tool's `updatedInput` (see
1602
- * {@link answerAskUserQuestion}). Called from `canUseTool` since that is
1603
- * where the SDK routes the tool's permission check. The elicitation goes to
1604
- * `requestSessionId`, a subagent's child session for a question it asks,
1605
- * and blocks the turn of `sessionId`.
1606
- */
1607
- private handleAskUserQuestion;
1608
- /**
1609
- * Handle `request_user_dialog` control requests — blocking dialogs the CLI
1610
- * asks the host to render (see {@link answerUserDialog}).
1611
- */
1612
- private handleUserDialog;
1613
- /**
1614
- * The slash commands of the session `sessionId`, as `available_commands_update`
1615
- * lists them. The SDK reads them from Claude Code's initialization, which
1616
- * session setup already awaited. Empty when the session does not exist.
1617
- */
1618
- availableCommands(sessionId: string): Promise<AvailableCommand[]>;
1619
- /**
1620
- * Reads the skill files from Claude Code's own skill list
1621
- * (`getContextUsage().skills.skillFrontmatter`) and, when they differ from
1622
- * the last read, re-publishes the slash commands with the skill paths. Only
1623
- * for AIR clients, the only ones that use the paths.
1624
- *
1625
- * Callers do not await it: the control request takes about 1 s on the first
1626
- * call, and it must not delay the turn or the first command list. A trigger
1627
- * during a running read does not start a parallel request; one more read
1628
- * runs after it. Errors are logged, never thrown. Older CLIs lack the method.
1629
- */
1630
- private refreshSkillFiles;
1631
- sendAvailableCommandsUpdate(sessionId: string): Promise<void>;
1632
- /**
1633
- * The work that follows a session setup response: the session's commands,
1634
- * the current states of the subagents a load replayed, and MCP server
1635
- * authentication.
1636
- */
1637
- private afterSetupResponse;
1638
- /**
1639
- * Sends the current state of each subagent that the last load of
1640
- * `sessionId` replayed (see {@link RfdSubagentReplay.currentStates}). Run it
1641
- * only after the load response: before it, the client treats subagent states
1642
- * as history.
1643
- */
1644
- publishCurrentSubagentStates(sessionId: string): Promise<void>;
1645
- /**
1646
- * AIR's draft: a load replays while the CLI starts, so the replay can lack
1647
- * the session's model list and send a child's model as its id. After the
1648
- * load response the list is known, and each replayed child whose model the
1649
- * list maps to another entry gets that entry. The replay already ended the
1650
- * child, and AIR's draft allows no other update after a child's end, but it
1651
- * takes this more exact snapshot of the same configuration.
1652
- */
1653
- private publishReplayedChildModels;
1654
- private updateConfigOption;
1655
- /**
1656
- * Refine a heuristic context window with `getContextUsage().rawMaxTokens`
1657
- * (`readContextWindow`), without blocking the caller. The text heuristic
1658
- * misses natively-1M models whose picker rows carry no "1m" token (e.g.
1659
- * `sonnet`, and since CLI 2.1.283 `opus`/`default`), so those would
1660
- * otherwise show 200k until the first result's modelUsage arrives. A later
1661
- * result still overwrites this.
1662
- */
1663
- private refreshContextWindowInBackground;
1664
- private applyConfigOptionValue;
1665
- /** Reconcile adapter model state after the SDK switched the session's
1666
- * model out from under us — a refusal fallback, or any switch reported by
1667
- * the PostModelSwitch hook that the adapter didn't drive (e.g. a `/model`
1668
- * command typed as a prompt). The SDK already made the switch, so this
1669
- * must NOT call `query.setModel` — it only updates our bookkeeping
1670
- * (currentModelId, context window, mode clamping, effort/Fast-mode
1671
- * options) via the same `applyConfigOptionValue` path a user-driven model
1672
- * change takes, then notifies the client. */
1673
- private syncModelAfterExternalSwitch;
1674
- /** Replace the Fast mode option in `session.configOptions` so it reflects
1675
- * `enabled` (and the client's current boolean-capability). A no-op when the
1676
- * option isn't present, so callers must confirm the current model surfaces
1677
- * it first. */
1678
- private refreshFastModeOption;
1679
- /** Toggle Fast mode for a session: push the SDK flag, record the user's
1680
- * intent, and refresh the Fast mode config option in place. Only reached
1681
- * once the option exists (i.e. the current model supports fast mode), so the
1682
- * option is guaranteed to be present in `configOptions`. */
1683
- private applyFastMode;
1684
- /** Turn ultracode on or off for a session. Sends an explicit boolean, which
1685
- * leaves the effort level alone (`null` would reset the flag layer instead).
1686
- * The SDK flag is applied first so a rejected request leaves the session
1687
- * state and option untouched. */
1688
- private applyUltracode;
1689
- /** Reconcile the session's Fast mode toggle with an SDK-reported
1690
- * `fast_mode_state` (delivered on `system`/init and on user-turn `result`s).
1691
- * The SDK can flip fast mode independently of the user — e.g. back to `on`
1692
- * once a rate-limit `cooldown` clears — so we mirror definitive on/off
1693
- * changes into the config option and notify the client (see
1694
- * {@link fastModeStateChange}).
1695
- *
1696
- * Without a Fast mode option the current model doesn't support fast mode,
1697
- * so the reported state reflects capability, not the user's intent. The
1698
- * retained setting stays untouched so it's correct when a supporting model
1699
- * is reselected (the source of the earlier intent-clobber bug was mutating
1700
- * it here). */
1701
- private syncFastModeState;
1702
- private getOrCreateSession;
1703
- /**
1704
- * Ensures the requested `cwd` is an absolute path that points at an existing
1705
- * directory before we create a session. Throws an `invalidParams` error with
1706
- * an actionable message so clients (e.g. Zed) can surface it to the user
1707
- * instead of failing later with an opaque SDK error.
1708
- *
1709
- * Each `additionalDirectories` entry must be absolute too. Only the lexical
1710
- * rule is checked there: a missing extra root does not fail a session.
1711
- */
1712
- private validateCwd;
1713
- /** Whether the session forwards the text and the thinking of a subagent. */
1714
- private forwardsSubagentText;
1715
- private createSession;
1716
- /**
1717
- * Provider routing is baked into the environment of each SDK Query. Wait for
1718
- * all submitted turns to settle, close every query, then resume each Claude
1719
- * session with the same ID so subsequent turns inherit the new environment.
1720
- */
1721
- private enqueueProviderUpdate;
1722
- /** Starts a new query for the session under the new provider and restores its choices. */
1723
- private restartSessionForProvider;
1724
- /** Recreates the session's query and restores its choices and reported MCP servers, unless it was closed meanwhile. */
1725
- private replaceSessionQuery;
1726
- /** Re-applies the choices of `previous` to the session that replaced it; a choice the new query rejects is logged. */
1727
- private restoreSessionChoices;
1728
- private serializeConfigurationChange;
1729
- /** Tell a capable client when a non-auth error ends a session during a provider switch. */
1730
- private reportSessionLostOnProviderUpdate;
1731
- }
1732
- /** Whether Claude Code ended the work of `result` because an interrupt
1733
- * stopped it, while the model streamed or while a tool ran. */
1734
- export declare function isAbortedResult(result: Extract<SDKMessage, {
1735
- type: "result";
1736
- }>): boolean;
1737
- export declare function getAvailableSlashCommands(commands: SlashCommand[], terminalCommands?: readonly string[], airSkillCwd?: string, skillPaths?: Map<string, string | undefined>, query?: Query, skillFiles?: ReadonlyMap<string, {
1738
- path?: string;
1739
- }>): AvailableCommand[];
1740
- export declare function promptToClaude(prompt: PromptRequest): SDKUserMessage;
1741
- /**
1742
- * Resolves the ACP `messageId` for a Claude SDK message (live) or a persisted
1743
- * transcript message (replay) so chunk grouping is identical in both views.
1744
- *
1745
- * Assistant turns are keyed by the Anthropic API message id (`message.id`),
1746
- * which is identical at `message_start`, on the consolidated assistant message,
1747
- * and in the persisted transcript — unlike the per-`stream_event` uuid, which is
1748
- * unique per event and never persisted. User messages have no API id, but they
1749
- * are never streamed, so their (stable) SDK uuid is used instead. ACP message
1750
- * ids are opaque strings, so no particular format is required.
1751
- */
1752
- export declare function messageIdForGrouping(message: {
1753
- type?: string;
1754
- uuid?: string | null;
1755
- message?: unknown;
1756
- }): string | undefined;
1757
- export declare function toAcpNotifications(content: string | ContentBlockParam[] | BetaContentBlock[] | BetaRawContentBlockDelta[], role: "assistant" | "user", sessionId: string, toolUseCache: ToolUseCache, client: AcpClient, logger: Logger, options?: {
1758
- registerHooks?: boolean;
1759
- clientCapabilities?: ClientCapabilities;
1760
- toolCallCapabilities?: ToolCallClientCapabilities;
1761
- parentToolUseId?: string | null;
1762
- cwd?: string;
1763
- taskState?: TaskState;
1764
- subagentChecklists?: SubagentChecklists;
1765
- emittedToolCalls?: Set<string>;
1766
- inputComplete?: boolean;
1767
- toolCallFields?: ToolCallFieldTracker;
1768
- messageId?: string;
1769
- toolUseResult?: unknown;
1770
- toolResultMeta?: unknown;
1771
- cancelled?: boolean;
1772
- replay?: boolean;
1773
- }): SessionNotification[];
1774
- export declare function streamEventToAcpNotifications(message: SDKPartialAssistantMessage, sessionId: string, toolUseCache: ToolUseCache, client: AcpClient, logger: Logger, options?: {
1775
- clientCapabilities?: ClientCapabilities;
1776
- toolCallCapabilities?: ToolCallClientCapabilities;
1777
- cwd?: string;
1778
- taskState?: TaskState;
1779
- subagentChecklists?: SubagentChecklists;
1780
- emittedToolCalls?: Set<string>;
1781
- toolCallFields?: ToolCallFieldTracker;
1782
- messageId?: string;
1783
- streamedToolInputs?: StreamedToolInputCache;
1784
- }): SessionNotification[];
1785
- /** Run a `session/prompt` while honoring `$/cancel_request` for it. ACP clients
1786
- * normally stop a turn with the `session/cancel` notification, but `signal`
1787
- * (the prompt request's abort signal) also fires when the client sends the
1788
- * generic `$/cancel_request` for this prompt — the protocol's complementary
1789
- * cancellation fallback. Route that to the same `agent.cancel` path so a client
1790
- * using only the generic mechanism still stops the turn (and the prompt
1791
- * resolves "cancelled" instead of running to completion).
1792
- *
1793
- * The listener is scoped to this call: once the prompt settles it is removed,
1794
- * so a later teardown-time abort of the (per-request) signal can't cancel a
1795
- * subsequent turn. `signal` also aborts on connection close, in which case
1796
- * cancelling the in-flight turn is the desired behavior anyway. */
1797
- export declare function runPromptWithCancellation(agent: Pick<ClaudeAcpAgent, "prompt" | "cancel" | "logger">, params: PromptRequest, signal: AbortSignal): Promise<PromptResponse>;
1798
- /**
1799
- * The ACP v1 surface of the adapter, for one connection.
1800
- *
1801
- * The agent of the connection is created when the connection opens, from the
1802
- * connection-scoped peer handle (`connection.client`), which stays valid for
1803
- * the whole connection. Connect handlers run before the connection processes
1804
- * any inbound message, so every handler below sees the agent. `onAgent`
1805
- * receives it for the owner of the process (shutdown).
1806
- */
1807
- export declare function v1AgentApp(logger: Logger | undefined, onAgent: (agent: ClaudeAcpAgent) => void): AgentApp;
1808
- /** Serves ACP v1 on stdio. */
1809
- export declare function runAcp(logger?: Logger): {
1810
- connection: import("@agentclientprotocol/sdk/unstable").AgentConnection;
1811
- agent: ClaudeAcpAgent;
1812
- };
1
+ export * from "./v1/acp-agent.js";
1813
2
  //# sourceMappingURL=acp-agent.d.ts.map