@agentclientprotocol/claude-agent-acp 0.102.1-preview.3 → 0.102.1-preview.5

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