@lucascouts/claude-agent-acp-plus 0.37.1 → 0.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/acp-agent.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { agent as acpAgent, methods, ndJsonStream, RequestError, } from "@agentclientprotocol/sdk/unstable";
2
- import { deleteSession, getSessionMessages, getSubagentMessages, listSessions, query, } from "@anthropic-ai/claude-agent-sdk";
2
+ import { deleteSession, getSessionMessages, forkSession as sdkForkSession, getSubagentMessages, listSessions, query, } from "@anthropic-ai/claude-agent-sdk";
3
3
  import { GOAL_ACTIONS, GOAL_CONTROL_METHOD, GOAL_EXTENSION_VERSION, goalUpdateFromPrompt, parseGoalRequest, toGoalSnapshot, } from "./goal-extension.js";
4
4
  import { sanitizeTitle, SessionTitles } from "./session-titles.js";
5
5
  import { readResumedPermissionMode, readResumedSession, } from "./resumed-session.js";
@@ -14,6 +14,7 @@ import { promisify } from "node:util";
14
14
  import packageJson from "../package.json" with { type: "json" };
15
15
  import { applyAskElicitationResponse, askUserQuestionsToCreateRequest, createElicitationResponseToElicitResult, extractAskUserQuestions, extractRefusalFallbackPrompt, mcpElicitationToCreateRequest, REFUSAL_FALLBACK_DIALOG_KIND, refusalFallbackResultFromResponse, refusalFallbackToCreateRequest, } from "./elicitation.js";
16
16
  import { agentName } from "./agent-name.js";
17
+ import { withQuestionRouting } from "./question-routing.js";
17
18
  import { filterDeprecatedModels } from "./model-deprecation.js";
18
19
  import { filterSupersededModels } from "./model-recency.js";
19
20
  import { SettingsManager } from "./settings.js";
@@ -24,6 +25,10 @@ import { deleteSessionIfStored } from "./session-delete.js";
24
25
  import { applyPlanUpdatesToOptions, createPlanUpdatesConfigOption, resolvePlanUpdatesAtSpawn, resolvePlanUpdatesRequested, TODO_TOOLS_ENV, } from "./plan-updates.js";
25
26
  import { planRemovedUpdate, planSessionUpdate, supportsPlanOperations } from "./keyed-plan.js";
26
27
  import { handleRewindCommand, parseRewindInvocation } from "./rewind-command.js";
28
+ import { askSideQuestion, BTW_CAPABILITY_KEY, BTW_CAPABILITY_VERSION, BTW_METHOD, BTW_USAGE_TEXT, formatSideAnswer, parseBtwInvocation, parseSideQuestionRequest, } from "./side-question.js";
29
+ import { FORK_AT_META_KEY, parseRewindRequest, planFork, REWIND_CAPABILITY_KEY, REWIND_CAPABILITY_VERSION, REWIND_METHOD, rewindSession, } from "./session-rewind.js";
30
+ import { parseCutAt } from "./turn-cut.js";
31
+ import { CONTEXT_USAGE_CAPABILITY_KEY, CONTEXT_USAGE_CAPABILITY_VERSION, CONTEXT_USAGE_METHOD, fetchContextReport, parseContextUsageRequest, } from "./context-usage.js";
27
32
  import { resolvePermissionMode, sessionAllowsBypass } from "./permissions/modes.js";
28
33
  import { normalizeDurablePermissionChangeSet } from "./permissions/normalization.js";
29
34
  import { buildClaudePermissionOptions } from "./permissions/options.js";
@@ -42,6 +47,8 @@ import { ChildSessionRouter, childStopReasonOf } from "./child-sessions.js";
42
47
  import { readSubagentLaunches } from "./child-session-history.js";
43
48
  import { findTranscript } from "./transcript-path.js";
44
49
  import { parseToolResultMeta } from "./tool-result-meta.js";
50
+ import { progressToolCallId } from "./tool-progress-target.js";
51
+ import { RETRACTED_TOOL_CALL_TEXT, RetractedToolCalls } from "./retracted-tool-calls.js";
45
52
  import { AccountUsageTracker } from "./account-usage.js";
46
53
  import { readFreshLimits, sharedSampleMaxAgeMs, writeLimits } from "./quota-cache.js";
47
54
  import { ACCOUNT_CONFIG_ID, accountForValue, accountInForce, createAccountConfigOption, envForAccount, readDeclaredAccounts, } from "./accounts.js";
@@ -60,7 +67,14 @@ const ZERO_USAGE = Object.freeze({
60
67
  cache_read_input_tokens: 0,
61
68
  cache_creation_input_tokens: 0,
62
69
  });
63
- const DEFAULT_CONTEXT_WINDOW = 200000;
70
+ /** The window reported before Claude Code has said what it is: the background
71
+ * `getContextUsage` read at session creation and at every model switch, then
72
+ * each result's `modelUsage`. 1M since Claude Code 2.1.323, which assumes 1M
73
+ * for an id it does not know and reports 1M for its `opus`/`sonnet`/`haiku`
74
+ * aliases (upstream #1613, measured with `getContextUsage` and no prompt): 200K
75
+ * became the less likely guess, and a 200K default drew a 1M session's context
76
+ * ring at five times its fill until the read landed. */
77
+ const DEFAULT_CONTEXT_WINDOW = 1_000_000;
64
78
  /** Floor after `session/cancel` before the adapter forces the active prompt
65
79
  * loop to return "cancelled". `query.interrupt()` normally makes the SDK
66
80
  * yield a trailing idle within milliseconds, and the loop returns through its
@@ -361,6 +375,23 @@ function isHeldOpen(turn) {
361
375
  function isSteering(turn) {
362
376
  return turn != null && turn.steeredEchoes !== undefined && !turn.settled;
363
377
  }
378
+ /** Whether a steered turn's recorded outcome is its steered work's own: every
379
+ * steered message has been picked up and a result arrived after the last one
380
+ * (see Turn.steeredAwaitingResult), so the next idle can settle it. */
381
+ function isSteeredSettleReady(turn) {
382
+ return (isSteering(turn) &&
383
+ turn.steeredEchoes.size === 0 &&
384
+ turn.steeredSettle !== undefined &&
385
+ !turn.steeredAwaitingResult);
386
+ }
387
+ /** Take a turn out of the steer lane so its settlement follows the ordinary
388
+ * result/idle rules again. */
389
+ function leaveSteerLane(turn) {
390
+ turn.steeredEchoes = undefined;
391
+ turn.steeredUuids = undefined;
392
+ turn.steeredAwaitingResult = undefined;
393
+ turn.steeredSettle = undefined;
394
+ }
364
395
  /** Disarm the force-cancel backstop (see Session.forceCancelTimer). Every
365
396
  * path that settles the active turn must run this so a timer can never fire
366
397
  * on an already-settled turn — and must leave the field undefined, or the
@@ -1082,6 +1113,9 @@ export class ClaudeAcpAgent {
1082
1113
  version: this.childSessions ? TASKS_RFD_CONTRACT_VERSION : TASKS_CAPABILITY_VERSION,
1083
1114
  },
1084
1115
  [USAGE_CAPABILITY_KEY]: { version: USAGE_CAPABILITY_VERSION },
1116
+ [BTW_CAPABILITY_KEY]: { version: BTW_CAPABILITY_VERSION },
1117
+ [REWIND_CAPABILITY_KEY]: { version: REWIND_CAPABILITY_VERSION },
1118
+ [CONTEXT_USAGE_CAPABILITY_KEY]: { version: CONTEXT_USAGE_CAPABILITY_VERSION },
1085
1119
  },
1086
1120
  promptCapabilities: {
1087
1121
  image: true,
@@ -1149,15 +1183,16 @@ export class ClaudeAcpAgent {
1149
1183
  async unstable_forkSession(params) {
1150
1184
  if (this.providerUpdate)
1151
1185
  await this.providerUpdate;
1186
+ // A cut point under `_meta["_claude/forkAt"]` forks from that turn (§6.33);
1187
+ // without one the fork copies the whole session, as before.
1188
+ const rawCut = params._meta?.[FORK_AT_META_KEY];
1189
+ const plan = await planFork(this.sessionCutDeps(params.sessionId), params.sessionId, rawCut === undefined ? undefined : parseCutAt(rawCut, `session/fork ${FORK_AT_META_KEY}`));
1152
1190
  const response = await this.createSession({
1153
1191
  cwd: params.cwd,
1154
1192
  mcpServers: params.mcpServers ?? [],
1155
1193
  additionalDirectories: params.additionalDirectories,
1156
1194
  _meta: params._meta,
1157
- }, {
1158
- resume: params.sessionId,
1159
- forkSession: true,
1160
- });
1195
+ }, plan);
1161
1196
  // Needs to happen after we return the session
1162
1197
  setTimeout(() => {
1163
1198
  this.sendAvailableCommandsUpdate(response.sessionId);
@@ -1349,6 +1384,23 @@ export class ClaudeAcpAgent {
1349
1384
  // emits every user-facing update before it resolves, so returning end_turn
1350
1385
  // here leaves Zed with a complete turn rather than an empty/hung one.
1351
1386
  const commandText = params.prompt[0]?.type === "text" ? params.prompt[0].text : "";
1387
+ // `/btw` typed into a composer (§6.8): a side question answered as an
1388
+ // aside, never enqueued and never added to the model's history, so it may
1389
+ // run while a turn is in flight. Zeo uses `_claude/btw` instead.
1390
+ const btwInvocation = parseBtwInvocation(commandText);
1391
+ if (btwInvocation) {
1392
+ const text = btwInvocation.kind === "usage"
1393
+ ? BTW_USAGE_TEXT
1394
+ : formatSideAnswer(await this.sideQuestion({
1395
+ sessionId: params.sessionId,
1396
+ question: btwInvocation.question,
1397
+ }));
1398
+ await this.client.sessionUpdate({
1399
+ sessionId: params.sessionId,
1400
+ update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } },
1401
+ });
1402
+ return { stopReason: "end_turn" };
1403
+ }
1352
1404
  const rewindInvocation = parseRewindInvocation(commandText);
1353
1405
  if (rewindInvocation) {
1354
1406
  // A lazy Thinking recreate may be swapping the session's query right
@@ -1687,6 +1739,106 @@ export class ClaudeAcpAgent {
1687
1739
  timer.unref?.();
1688
1740
  session.accountUsageTimer = timer;
1689
1741
  }
1742
+ /**
1743
+ * `_claude/context/usage`: what fills this session's context window (see
1744
+ * context-usage.ts), asked on a click, never per turn. On an idle session it
1745
+ * asks for the full breakdown; while a turn is active or queued only for the
1746
+ * local estimate, because the full one makes token-count calls and SDK
1747
+ * control requests are serialized — an interrupt queued behind it would
1748
+ * delay the Stop button (the same reason `_claude/usage/refresh` skips
1749
+ * mid-turn). The answer says which it got.
1750
+ */
1751
+ async contextUsage(params) {
1752
+ const { sessionId } = params;
1753
+ const log = (outcome) => this.logger.log(`[context/usage] method=${CONTEXT_USAGE_METHOD} sessionId=${logValue(sessionId)} outcome=${outcome}`);
1754
+ const session = Object.hasOwn(this.sessions, sessionId) ? this.sessions[sessionId] : undefined;
1755
+ if (!session) {
1756
+ log("error_unknown_session");
1757
+ throw RequestError.invalidParams(undefined, `unknown session ${sessionId}`);
1758
+ }
1759
+ if (session.queryClosed) {
1760
+ log("unavailable_session_ended");
1761
+ return { status: "unavailable", message: SESSION_ENDED_MESSAGE };
1762
+ }
1763
+ if (session.queryRecreateInFlight) {
1764
+ await session.queryRecreateInFlight;
1765
+ }
1766
+ const busy = Boolean(session.turnQueue?.length || session.activeTurn);
1767
+ const report = await fetchContextReport(session.query, busy ? "summary" : "full");
1768
+ log(report.status === "ok" ? `ok_${report.detail}` : report.status);
1769
+ return report;
1770
+ }
1771
+ /** Transcript reads and copies for a cut at a turn (fork and rewind). */
1772
+ sessionCutDeps(sessionId) {
1773
+ return {
1774
+ readTranscript: async () => (await getSessionMessages(sessionId)),
1775
+ messageIdToUuid: this.sessions[sessionId]?.messageIdToUuid ?? new Map(),
1776
+ forkTranscript: async (upToUuid) => (await sdkForkSession(sessionId, { upToMessageId: upToUuid })).sessionId,
1777
+ };
1778
+ }
1779
+ /**
1780
+ * `_claude/rewind`: take the session back to the end of a turn, files
1781
+ * optionally included (see session-rewind.ts). Refused as `busy` while a turn
1782
+ * is active or queued, or another rewind runs — the same idleness rule as
1783
+ * `/rewind`, for the same reason: never restore files under a running edit.
1784
+ * The answer names a NEW session holding the kept turns; this session is
1785
+ * left as it is for the client to replace.
1786
+ */
1787
+ async rewind(params) {
1788
+ const { sessionId } = params;
1789
+ const log = (outcome) => this.logger.log(`[rewind] method=${REWIND_METHOD} sessionId=${logValue(sessionId)} restoreFiles=${params.restoreFiles} outcome=${outcome}`);
1790
+ const session = Object.hasOwn(this.sessions, sessionId) ? this.sessions[sessionId] : undefined;
1791
+ if (!session) {
1792
+ log("error_unknown_session");
1793
+ throw RequestError.invalidParams(undefined, `unknown session ${sessionId}`);
1794
+ }
1795
+ if (session.queryRecreateInFlight) {
1796
+ await session.queryRecreateInFlight;
1797
+ }
1798
+ if (session.turnQueue?.length || session.activeTurn || session.rewindInFlight) {
1799
+ log("busy");
1800
+ return { status: "busy" };
1801
+ }
1802
+ session.rewindInFlight = true;
1803
+ try {
1804
+ const result = await rewindSession({
1805
+ ...this.sessionCutDeps(sessionId),
1806
+ rewindFiles: (uuid) => session.query.rewindFiles(uuid),
1807
+ }, params);
1808
+ log(result.status === "failed" ? `failed_${result.stage}` : result.status);
1809
+ return result;
1810
+ }
1811
+ finally {
1812
+ session.rewindInFlight = false;
1813
+ }
1814
+ }
1815
+ /**
1816
+ * `_claude/btw`: answer a side question without touching the conversation
1817
+ * (see side-question.ts). Allowed while a turn runs — that is the point —
1818
+ * and never enqueued: the CLI's `side_question` control request answers
1819
+ * beside the turn. Only an unknown session is an error; every other outcome,
1820
+ * an ended session included, is a result the client can show.
1821
+ */
1822
+ async sideQuestion(params, signal) {
1823
+ const { sessionId, question } = params;
1824
+ const log = (outcome) => this.logger.log(`[btw] method=${BTW_METHOD} sessionId=${logValue(sessionId)} questionChars=${question.length} outcome=${outcome}`);
1825
+ const session = Object.hasOwn(this.sessions, sessionId) ? this.sessions[sessionId] : undefined;
1826
+ if (!session) {
1827
+ log("error_unknown_session");
1828
+ throw RequestError.invalidParams(undefined, `unknown session ${sessionId}`);
1829
+ }
1830
+ if (session.queryClosed) {
1831
+ log("failed_session_ended");
1832
+ return { status: "failed", message: SESSION_ENDED_MESSAGE };
1833
+ }
1834
+ // A Thinking recreate may be swapping the query; ask the live one.
1835
+ if (session.queryRecreateInFlight) {
1836
+ await session.queryRecreateInFlight;
1837
+ }
1838
+ const result = await askSideQuestion(session.query, question, signal);
1839
+ log(result.status);
1840
+ return result;
1841
+ }
1690
1842
  /**
1691
1843
  * `_claude/usage/refresh`: publish this session's quota windows now, on
1692
1844
  * demand, and answer whether any were published.
@@ -1839,10 +1991,9 @@ export class ClaudeAcpAgent {
1839
1991
  *
1840
1992
  * Before 0.3.286 delivering `now` ABORTED the cycle, which emitted a `result`
1841
1993
  * of its own before the steered message ran as a second one; since then it
1842
- * joins the turn. The turn is marked (`Turn.steeredEchoes`) to settle at the
1843
- * SDK's `idle` instead of at a result in both cases, so either CLI behaviour
1844
- * settles once, after the steered work. Zeo sends no ACP steering, so none
1845
- * of this is reachable from it.
1994
+ * joins the turn. The turn is marked (`Turn.steeredEchoes`) to settle only
1995
+ * once a result answers the steer, or at the SDK's `idle` after one, so
1996
+ * either CLI behaviour settles once, after the steered work.
1846
1997
  *
1847
1998
  * When the session is idle, the opt-in path returns `promptRequired` WITHOUT
1848
1999
  * calling `prompt()`, pushing SDK input, or mutating `turnQueue`: the content
@@ -2016,6 +2167,7 @@ export class ClaudeAcpAgent {
2016
2167
  // time the consumer next runs, and an unmarked result would settle the turn
2017
2168
  // (see Turn.steeredEchoes).
2018
2169
  (turnInFlight.steeredEchoes ??= new Set()).add(steeredUuid);
2170
+ (turnInFlight.steeredUuids ??= new Set()).add(steeredUuid);
2019
2171
  // A turn already held for background subagents has a recorded outcome the
2020
2172
  // steer supersedes: move it into the steer lane so one lane owns settlement.
2021
2173
  // The idle handler re-applies the hold through the subagent gate.
@@ -2082,6 +2234,9 @@ export class ClaudeAcpAgent {
2082
2234
  // send it with (upstream #1534): with partial messages on, the SDK sends it
2083
2235
  // ahead of the first assistant frame. It rides the turn's next usage_update.
2084
2236
  let pendingRateLimit = null;
2237
+ // The turn's latest rate_limit_event info, for the data of its failure
2238
+ // (upstream #1610, see `errorKindData`).
2239
+ let turnRateLimit;
2085
2240
  // When the Claude SDK classifies a turn as failed (e.g. rate limit, auth
2086
2241
  // problem, billing), it sets a categorical `error` field on the
2087
2242
  // `SDKAssistantMessage` that precedes the final `result` message. We capture
@@ -2256,6 +2411,7 @@ export class ClaudeAcpAgent {
2256
2411
  // usage_update to ride must not be attributed to the next turn. The
2257
2412
  // tracker already remembers its status (R1.6).
2258
2413
  pendingRateLimit = null;
2414
+ turnRateLimit = undefined;
2259
2415
  lastAssistantError = undefined;
2260
2416
  lastAssistantWasUsageLimit = false;
2261
2417
  lastAssistantFailureTitle = undefined;
@@ -2506,6 +2662,8 @@ export class ClaudeAcpAgent {
2506
2662
  * marked as a background result, but it lists the uuids of the prompts it
2507
2663
  * answered.
2508
2664
  *
2665
+ * A steer belongs to the live active turn even though it has no queued
2666
+ * Turn of its own. Its stamped result can answer that turn too.
2509
2667
  * A turn held open for its background subagents already has its result,
2510
2668
  * so a result that names it does not answer it. */
2511
2669
  const answersPendingPrompt = (message) => {
@@ -2518,8 +2676,13 @@ export class ClaudeAcpAgent {
2518
2676
  else if (typeof message.user_message_uuid === "string") {
2519
2677
  answeredPromptUuids = [message.user_message_uuid];
2520
2678
  }
2679
+ const activeTurn = session.activeTurn;
2680
+ const liveActiveTurn = activeTurn && !activeTurn.settled && !isHeldOpen(activeTurn) ? activeTurn : undefined;
2521
2681
  for (const promptUuid of answeredPromptUuids) {
2522
- const turn = findUnsettledTurn(promptUuid);
2682
+ // Keep queued prompt matching, including folded sends with no echo.
2683
+ // Steers qualify only through their live active owner.
2684
+ const turn = findUnsettledTurn(promptUuid) ??
2685
+ (liveActiveTurn?.steeredUuids?.has(promptUuid) ? liveActiveTurn : undefined);
2523
2686
  if (turn === undefined) {
2524
2687
  // Not a prompt of this session, or it was answered already.
2525
2688
  continue;
@@ -2630,6 +2793,29 @@ export class ClaudeAcpAgent {
2630
2793
  },
2631
2794
  });
2632
2795
  };
2796
+ /** Upstream #1616: fails the open tool calls of the messages that `message`
2797
+ * says Claude Code took back. No result comes for them, so they would
2798
+ * spin in the client. A call whose result came is not open any more. */
2799
+ const closeRetractedToolCalls = async (message) => {
2800
+ const retracted = (session.retractedToolCalls ??= new RetractedToolCalls()).retractedBy(message);
2801
+ for (const { toolCallId, parentToolUseId } of retracted) {
2802
+ if (!session.emittedToolCalls.delete(toolCallId))
2803
+ continue;
2804
+ this.logger.log(`[tool-call/retracted] sessionId=${params.sessionId} toolCallId=${toolCallId}`);
2805
+ await sendUpdate({
2806
+ sessionId: params.sessionId,
2807
+ update: {
2808
+ sessionUpdate: "tool_call_update",
2809
+ toolCallId,
2810
+ status: "failed",
2811
+ content: [
2812
+ { type: "content", content: { type: "text", text: RETRACTED_TOOL_CALL_TEXT } },
2813
+ ],
2814
+ ...(parentToolUseId ? { _meta: { claudeCode: { parentToolUseId } } } : {}),
2815
+ },
2816
+ });
2817
+ }
2818
+ };
2633
2819
  const turnAwaitingSubagents = (turn) => {
2634
2820
  if (!turn.spawnedTaskIds?.size) {
2635
2821
  return false;
@@ -2697,6 +2883,7 @@ export class ClaudeAcpAgent {
2697
2883
  // so the last result and its usage win.
2698
2884
  if (isSteering(session.activeTurn)) {
2699
2885
  session.activeTurn.steeredSettle = outcome;
2886
+ session.activeTurn.steeredAwaitingResult = false;
2700
2887
  return;
2701
2888
  }
2702
2889
  if (session.activeTurn &&
@@ -3274,9 +3461,9 @@ export class ClaudeAcpAgent {
3274
3461
  // why this sweep is safe to carry on both cadences.
3275
3462
  //
3276
3463
  // Left in place, each unit would absorb a later un-owed idle
3277
- // -- masking an issue-#825 detection -- or swallow the idle a
3278
- // steered turn settles on (the owed-idle branch runs before
3279
- // the steer lane), hanging that prompt.
3464
+ // -- masking an issue-#825 detection. (The ready steer lane
3465
+ // below runs ahead of the debt and leaves it standing when it
3466
+ // settles, so the sweep is what retires that debt.)
3280
3467
  this.logger.log(`[turn/idle-debt] swept=${session.owedTrailingIdles} session=${params.sessionId} at=running-transition`);
3281
3468
  session.owedTrailingIdles = 0;
3282
3469
  }
@@ -3348,38 +3535,44 @@ export class ClaudeAcpAgent {
3348
3535
  }
3349
3536
  settleDeferredIfDrained();
3350
3537
  }
3538
+ else if (isSteeredSettleReady(session.activeTurn)) {
3539
+ // A steered turn whose steered work has produced its result
3540
+ // (see Turn.steeredEchoes) settles at the next idle — the
3541
+ // only signal spanning the interrupted and steered cycles
3542
+ // when results aren't stamped. AHEAD of owed-idle debt:
3543
+ // the outcome is final, so whichever idle this is settles
3544
+ // the turn correctly, while debt absorption could swallow
3545
+ // the only idle it gets — e.g. a steer that aborted an
3546
+ // autonomous followup, whose counted trailer collapses into
3547
+ // this one idle. The debt is left standing: a genuinely
3548
+ // separate trailer still absorbs the idle it belongs to,
3549
+ // and one that never comes is swept at the next `running`
3550
+ // transition.
3551
+ //
3552
+ // Via the subagent gate, not settleActive: a steered turn
3553
+ // can also have spawned background subagents, which own it
3554
+ // from here (settles now if none is live, holds otherwise).
3555
+ const steered = session.activeTurn;
3556
+ steered.deferredSettle = steered.steeredSettle;
3557
+ leaveSteerLane(steered);
3558
+ settleDeferredIfDrained();
3559
+ }
3351
3560
  else if (session.owedTrailingIdles > 0) {
3352
3561
  // Absorb a settled turn's trailing idle. Also covers a
3353
3562
  // cancel that landed between a turn's counted result and
3354
3563
  // this lagged idle (no active turn to settle): the idle
3355
3564
  // still belongs to that settled turn, and skipping the
3356
3565
  // decrement would leak the debt permanently.
3357
- // Deliberately BEFORE the steer lane below: an owed idle
3358
- // belongs to an earlier turn, and reading it as the steered
3359
- // sequence's turn-over signal would settle a turn whose
3360
- // steered cycle is still running. Steered results owe none.
3566
+ // Deliberately BEFORE the not-ready steer lane below: an
3567
+ // owed idle belongs to an earlier turn, and it must not be
3568
+ // left to reach the #825 fail. Steered results owe none.
3361
3569
  session.owedTrailingIdles--;
3362
3570
  }
3363
3571
  else if (isSteering(session.activeTurn)) {
3364
- // A steered turn settles here, not at a result: this idle is
3365
- // the only signal spanning the interrupted and steered cycles
3366
- // (see Turn.steeredEchoes). An idle before the steered echo,
3367
- // or before any result was recorded, means the answer is
3368
- // still ahead — swallow it, and never let it reach the #825
3369
- // fail below, which would reject a prompt about to answer.
3370
- //
3371
- // Plain Turn so the fields can be cleared below; isSteering
3372
- // narrows steeredEchoes to non-optional.
3373
- const steered = session.activeTurn;
3374
- if (steered.steeredEchoes?.size === 0 && steered.steeredSettle !== undefined) {
3375
- // Via the subagent gate, not settleActive: a steered turn
3376
- // can also have spawned background subagents, which own it
3377
- // from here (settles now if none is live, holds otherwise).
3378
- steered.deferredSettle = steered.steeredSettle;
3379
- steered.steeredEchoes = undefined;
3380
- steered.steeredSettle = undefined;
3381
- settleDeferredIfDrained();
3382
- }
3572
+ // A steered turn whose answer is still ahead: an idle before
3573
+ // the steered echo, or before a result since it. Swallow it,
3574
+ // and never let it reach the #825 fail below, which would
3575
+ // reject a prompt about to answer.
3383
3576
  }
3384
3577
  else if (!session.cancelled &&
3385
3578
  session.activeTurn &&
@@ -3647,6 +3840,7 @@ export class ClaudeAcpAgent {
3647
3840
  ? { backgrounded: message.is_backgrounded }
3648
3841
  : {}),
3649
3842
  ...(message.parent_task_id ? { parentTaskId: message.parent_task_id } : {}),
3843
+ ...(message.task_type ? { taskType: message.task_type } : {}),
3650
3844
  });
3651
3845
  if (message.subagent_type && session.activeTurn && !session.activeTurn.settled) {
3652
3846
  (session.activeTurn.spawnedTaskIds ??= new Set()).add(message.task_id);
@@ -3780,6 +3974,7 @@ export class ClaudeAcpAgent {
3780
3974
  break;
3781
3975
  }
3782
3976
  case "model_refusal_fallback": {
3977
+ await closeRetractedToolCalls(message);
3783
3978
  // The SDK retried a refused turn on the fallback model and made
3784
3979
  // the swap persistent for the session. Without a notice the
3785
3980
  // user just sees regenerated output; without the state sync the
@@ -3959,6 +4154,29 @@ export class ClaudeAcpAgent {
3959
4154
  if (!isAutonomousResult) {
3960
4155
  recordResultForOrphanCommands();
3961
4156
  ensureActiveTurn(message.user_message_uuid);
4157
+ // A result that names a steer consumed it (see
4158
+ // Turn.steeredEchoes), so the steered work is done: retire
4159
+ // its echo — the CLI may never have replayed it — and, with
4160
+ // no other steer outstanding, leave the steer lane so this
4161
+ // result settles the turn through the ordinary lanes below
4162
+ // and owes its trailing idle like any other. The interrupted
4163
+ // cycle's result names only the send it was answering, so it
4164
+ // stays on the steer lane. A cancelled turn's steers are
4165
+ // cancel()'s to account for.
4166
+ const steeredTurn = session.activeTurn;
4167
+ if (!session.cancelled && isSteering(steeredTurn)) {
4168
+ const consumed = message.user_message_uuids ??
4169
+ (message.user_message_uuid !== undefined ? [message.user_message_uuid] : []);
4170
+ let answersSteer = false;
4171
+ for (const uuid of consumed) {
4172
+ steeredTurn.steeredEchoes.delete(uuid);
4173
+ if (steeredTurn.steeredUuids?.has(uuid))
4174
+ answersSteer = true;
4175
+ }
4176
+ if (answersSteer && steeredTurn.steeredEchoes.size === 0) {
4177
+ leaveSteerLane(steeredTurn);
4178
+ }
4179
+ }
3962
4180
  // Once the submitted goal command has produced its own result,
3963
4181
  // no older runtime update can still precede it in the ordered
3964
4182
  // SDK stream. Stop suppressing updates even when this runtime
@@ -4040,7 +4258,9 @@ export class ClaudeAcpAgent {
4040
4258
  // Turn.steeredEchoes). One idle covers the whole interrupted +
4041
4259
  // steered sequence and that idle settles the turn, so counting
4042
4260
  // either result would leave a debt that swallows it. Autonomous
4043
- // results inside a steered turn keep their own trailers.
4261
+ // results inside a steered turn keep their own trailers, and so
4262
+ // does a result that named the steer: it took the turn out of the
4263
+ // steer lane above and settles at the result, not the idle.
4044
4264
  const owesTrailingIdle = isAutonomousResult || !isSteering(session.activeTurn);
4045
4265
  if (owesTrailingIdle &&
4046
4266
  (isAutonomousResult || !session.cancelled || !session.activeTurn)) {
@@ -4260,7 +4480,7 @@ export class ClaudeAcpAgent {
4260
4480
  break;
4261
4481
  }
4262
4482
  if (message.is_error) {
4263
- await failActiveWithSessionFailure(providerFailureCategory(lastAssistantError, lastAssistantWasUsageLimit), internalErrorForClient(errorKindData(lastAssistantError), message.result), lastAssistantFailureTitle ?? message.result);
4483
+ await failActiveWithSessionFailure(providerFailureCategory(lastAssistantError, lastAssistantWasUsageLimit), internalErrorForClient(errorKindData(lastAssistantError, turnRateLimit), message.result), lastAssistantFailureTitle ?? message.result);
4264
4484
  break;
4265
4485
  }
4266
4486
  // The result text is forwarded in two cases. Local-only
@@ -4307,7 +4527,7 @@ export class ClaudeAcpAgent {
4307
4527
  break;
4308
4528
  }
4309
4529
  if (message.is_error) {
4310
- await failActiveWithSessionFailure(providerFailureCategory(lastAssistantError, lastAssistantWasUsageLimit), internalErrorForClient(errorKindData(lastAssistantError), message.errors.join(", ") || message.subtype), lastAssistantFailureTitle ?? (message.errors.join(", ") || message.subtype));
4530
+ await failActiveWithSessionFailure(providerFailureCategory(lastAssistantError, lastAssistantWasUsageLimit), internalErrorForClient(errorKindData(lastAssistantError, turnRateLimit), message.errors.join(", ") || message.subtype), lastAssistantFailureTitle ?? (message.errors.join(", ") || message.subtype));
4311
4531
  break;
4312
4532
  }
4313
4533
  stopReason = "end_turn";
@@ -4315,21 +4535,21 @@ export class ClaudeAcpAgent {
4315
4535
  }
4316
4536
  case "error_max_budget_usd":
4317
4537
  if (message.is_error) {
4318
- await failActiveWithSessionFailure("budget_exhausted", internalErrorForClient(errorKindData(lastAssistantError), message.errors.join(", ") || message.subtype), message.errors.join(", ") || message.subtype);
4538
+ await failActiveWithSessionFailure("budget_exhausted", internalErrorForClient(errorKindData(lastAssistantError, turnRateLimit), message.errors.join(", ") || message.subtype), message.errors.join(", ") || message.subtype);
4319
4539
  break;
4320
4540
  }
4321
4541
  stopReason = "max_turn_requests";
4322
4542
  break;
4323
4543
  case "error_max_turns":
4324
4544
  if (message.is_error) {
4325
- await failActiveWithSessionFailure("context_exhausted", internalErrorForClient(errorKindData(lastAssistantError), message.errors.join(", ") || message.subtype), message.errors.join(", ") || message.subtype);
4545
+ await failActiveWithSessionFailure("context_exhausted", internalErrorForClient(errorKindData(lastAssistantError, turnRateLimit), message.errors.join(", ") || message.subtype), message.errors.join(", ") || message.subtype);
4326
4546
  break;
4327
4547
  }
4328
4548
  stopReason = "max_turn_requests";
4329
4549
  break;
4330
4550
  case "error_max_structured_output_retries":
4331
4551
  if (message.is_error) {
4332
- await failActiveWithSessionFailure("provider_error", internalErrorForClient(errorKindData(lastAssistantError), message.errors.join(", ") || message.subtype), message.errors.join(", ") || message.subtype);
4552
+ await failActiveWithSessionFailure("provider_error", internalErrorForClient(errorKindData(lastAssistantError, turnRateLimit), message.errors.join(", ") || message.subtype), message.errors.join(", ") || message.subtype);
4333
4553
  break;
4334
4554
  }
4335
4555
  stopReason = "max_turn_requests";
@@ -4477,21 +4697,6 @@ export class ClaudeAcpAgent {
4477
4697
  const model = message.event.message.model;
4478
4698
  if (model && model !== "<synthetic>") {
4479
4699
  lastAssistantModel = model;
4480
- // Only upgrade from the heuristic default — once we have an
4481
- // authoritative window (cache-seeded at session creation or
4482
- // on a model switch, read from the resumed session on
4483
- // session/load, confirmed by each `result`), trust it over
4484
- // the heuristic. The flag, not the value, is the sentinel: an
4485
- // authoritative window can legitimately equal
4486
- // DEFAULT_CONTEXT_WINDOW (e.g. a backend serving a 200k lane
4487
- // under a "[1m]"-spelled id) and must not be clobbered.
4488
- if (!session.contextWindowAuthoritative &&
4489
- session.contextWindowSize === DEFAULT_CONTEXT_WINDOW) {
4490
- const inferred = inferContextWindowFromModel(model);
4491
- if (inferred !== null) {
4492
- session.contextWindowSize = inferred;
4493
- }
4494
- }
4495
4700
  }
4496
4701
  }
4497
4702
  else {
@@ -4631,8 +4836,11 @@ export class ClaudeAcpAgent {
4631
4836
  // none), but it marks the steered cycle as running — how the idle
4632
4837
  // lane tells "the answer is still ahead" from "the turn is over"
4633
4838
  // (see Turn.steeredEchoes).
4634
- if (isSteering(session.activeTurn)) {
4635
- session.activeTurn.steeredEchoes.delete(message.uuid);
4839
+ // The outcome recorded so far predates the steered cycle, so the
4840
+ // idle lane waits for that cycle's own result.
4841
+ if (isSteering(session.activeTurn) &&
4842
+ session.activeTurn.steeredEchoes.delete(message.uuid)) {
4843
+ session.activeTurn.steeredAwaitingResult = true;
4636
4844
  }
4637
4845
  // Unrelated replay (e.g. the echo of an already-settled turn).
4638
4846
  break;
@@ -4645,6 +4853,13 @@ export class ClaudeAcpAgent {
4645
4853
  !this.childSessions?.childFor(params.sessionId, parentToolUseIdOf(message))) {
4646
4854
  break;
4647
4855
  }
4856
+ // Upstream #1616: the first message of a retry names the response it
4857
+ // replaces (`supersedes`); every assistant message is recorded so a
4858
+ // later retraction can find its tool calls.
4859
+ if (message.type === "assistant") {
4860
+ await closeRetractedToolCalls(message);
4861
+ (session.retractedToolCalls ??= new RetractedToolCalls()).sent(message);
4862
+ }
4648
4863
  // Synthetic assistant frames carry the CLI's local-command output.
4649
4864
  // On resume the SDK can replay a stale frame from an earlier compact
4650
4865
  // attempt after a later compaction completed. Scope the suppression
@@ -4931,25 +5146,11 @@ export class ClaudeAcpAgent {
4931
5146
  break;
4932
5147
  }
4933
5148
  case "tool_progress": {
4934
- // Not every beat reports under the id of a tool call the client has
4935
- // seen: heartbeats derive `<tool_use_id>-heartbeat-<n>`, and the
4936
- // `agent_api_retry` beats behind `subagentRetry` report under
4937
- // `agent_<assistant_message_id>`. Forwarding those verbatim leaves the
4938
- // client resolving an id it has never been told about (the same trap
4939
- // `ensureToolCallEmitted` documents for #851). The SDK stamps
4940
- // `parent_tool_use_id` with the executing tool's real id whenever the
4941
- // beat doesn't carry one of its own, so fall back to it rather than
4942
- // pattern-matching each synthetic id shape. Beats that do report a real
4943
- // id (a subagent's `bash_progress`, whose parent is the spawning Agent
4944
- // call) keep resolving to that id.
4945
- const toolCallId = session.emittedToolCalls.has(message.tool_use_id)
4946
- ? message.tool_use_id
4947
- : message.parent_tool_use_id;
4948
- // Ids leave `emittedToolCalls` at `tool_result`, so this also stops a
4949
- // beat that races past completion from reopening a finished call.
4950
- if (toolCallId === null || !session.emittedToolCalls.has(toolCallId)) {
5149
+ // Which call a beat lands on, and which beats are dropped (a hook's
5150
+ // heartbeat among them), is `progressToolCallId`'s rule.
5151
+ const toolCallId = progressToolCallId(message, session.emittedToolCalls);
5152
+ if (toolCallId === undefined)
4951
5153
  break;
4952
- }
4953
5154
  await sendUpdate({
4954
5155
  sessionId: params.sessionId,
4955
5156
  update: {
@@ -4994,6 +5195,7 @@ export class ClaudeAcpAgent {
4994
5195
  // the same notification shape (R1.8); when the turn has no context
4995
5196
  // total yet, it waits for the turn's next usage_update (#1534).
4996
5197
  this.accountUsageTracker(session).recordMeasured(message.rate_limit_info);
5198
+ turnRateLimit = message.rate_limit_info;
4997
5199
  if (lastAssistantTotalUsage === null) {
4998
5200
  pendingRateLimit = message.rate_limit_info;
4999
5201
  }
@@ -6409,11 +6611,11 @@ export class ClaudeAcpAgent {
6409
6611
  });
6410
6612
  }
6411
6613
  /**
6412
- * Replace a heuristic context window with `getContextUsage().rawMaxTokens`
6413
- * without blocking the caller. The text heuristic misses natively-1M models
6414
- * whose picker rows carry no "1m" token (`sonnet`, and since CLI 2.1.283
6415
- * `opus`/`default`), which would otherwise report 200k until the first
6416
- * result's modelUsage. Never awaited: SDK control requests are serialized,
6614
+ * Replace the default context window with `getContextUsage().rawMaxTokens`
6615
+ * without blocking the caller. Without it, a model with a 200K window
6616
+ * (`claude-sonnet-4-5`, or any model under `CLAUDE_CODE_DISABLE_1M_CONTEXT=1`)
6617
+ * would report the 1M default until the first result's modelUsage
6618
+ * (upstream #1613). Never awaited: SDK control requests are serialized,
6417
6619
  * so an awaited call would delay session/new or a model switch (before the
6418
6620
  * first turn it took ~15s on older CLIs, issues #886/#880; ~0.5s on 2.1.283).
6419
6621
  * Not written to `contextWindowCache` — that stays keyed to the
@@ -6472,11 +6674,11 @@ export class ClaudeAcpAgent {
6472
6674
  if (modelChanged) {
6473
6675
  // Seed the new model's context window WITHOUT awaited IPC on the
6474
6676
  // switch path: cached authoritative value if we've already learned it
6475
- // (from a prior turn's `result.modelUsage`), else the text heuristic,
6476
- // else the default. SDK control requests are serialized over one
6477
- // channel, so an awaited `getContextUsage` here would delay the rest
6478
- // of the switch (issues #886/#880); a guessed seed is instead refined
6479
- // in the background once the switch is done
6677
+ // (from a prior turn's `result.modelUsage`), else the default. SDK
6678
+ // control requests are serialized over one channel, so an awaited
6679
+ // `getContextUsage` here would delay the rest of the switch (issues
6680
+ // #886/#880); the default is instead replaced in the background once
6681
+ // the switch is done
6480
6682
  // (`refreshContextWindowInBackground`).
6481
6683
  const seeded = immediateContextWindow(session.providerCacheKey, value, newModelInfo);
6482
6684
  session.contextWindowSize = seeded.size;
@@ -7038,7 +7240,7 @@ export class ClaudeAcpAgent {
7038
7240
  // The user asked for Fast mode and the SDK is telling us it can't serve it.
7039
7241
  // The description carries the same explanation, but a toggle silently
7040
7242
  // snapping back is the case worth saying out loud once, at the flip.
7041
- const explanation = nextReason !== undefined ? FAST_MODE_UNAVAILABLE_EXPLANATIONS[nextReason] : undefined;
7243
+ const explanation = explainFastModeDisabledReason(nextReason);
7042
7244
  const explain = session.fastModeEnabled && !enabled && explanation !== undefined;
7043
7245
  session.fastModeEnabled = enabled;
7044
7246
  session.fastModeDisabledReason = nextReason;
@@ -7235,6 +7437,14 @@ export class ClaudeAcpAgent {
7235
7437
  // we render as a form elicitation. Without form-elicitation support there
7236
7438
  // is no way to present it over ACP, so keep it disabled in that case.
7237
7439
  const disallowedTools = elicitationSupport.form ? [] : ["AskUserQuestion"];
7440
+ // §6.43: steer open questions into AskUserQuestion's card when the client
7441
+ // can render it and has not opted out.
7442
+ systemPrompt = withQuestionRouting(systemPrompt, {
7443
+ formElicitation: elicitationSupport.form,
7444
+ meta: params._meta,
7445
+ userTools: userProvidedOptions?.tools,
7446
+ userDisallowedTools: userProvidedOptions?.disallowedTools,
7447
+ });
7238
7448
  // Resolve which built-in tools to expose.
7239
7449
  // Explicit tools array from _meta.claudeCode.options takes precedence.
7240
7450
  // disableBuiltInTools is a legacy shorthand for tools: [] — kept for
@@ -7734,29 +7944,21 @@ export class ClaudeAcpAgent {
7734
7944
  // authoritative and wins. That one response also carries how much of the
7735
7945
  // window is already occupied, seeded onto `contextUsedTokens` below.
7736
7946
  // Otherwise: the cached authoritative window if a prior turn has learned
7737
- // it for this model (`result.modelUsage`, cross-session), else the text
7738
- // heuristic, else the default. We deliberately do NOT issue a
7739
- // getContextUsage call here: on a fresh session that control request is
7947
+ // it for this model (`result.modelUsage`, cross-session), else the
7948
+ // default. We deliberately do NOT await a getContextUsage call here: on a fresh session that control request is
7740
7949
  // not serviced until the first prompt turn runs, so awaiting it — as
7741
7950
  // 0.59.0 did — made session/new take ~15s (issues #886/#880). The
7742
7951
  // authoritative window arrives on the first `result.modelUsage` and is
7743
7952
  // cached from there.
7744
7953
  //
7745
- // Text inference alone misses aliases that resolve to extended-context
7746
- // models with no "1m" token anywhere in their id or description (e.g.
7747
- // `sonnet` → claude-sonnet-5, natively ~1M): those stream
7748
- // `usage_update.size: 200000` until the first result's modelUsage corrects
7749
- // it — but the cache means only the FIRST session to ever run a turn on such
7750
- // a model eats that window, not every fresh session after a process
7751
- // restart (issue #596; a post-restart session/load is covered by the
7752
- // resumed report above).
7954
+ // A miss seeds the default, which `refreshContextWindowInBackground`
7955
+ // replaces once the session is registered (issue #596; upstream #1613).
7753
7956
  //
7754
- // The inference fallback is deliberately keyed to the catalog entry (the
7755
- // fork's unfiltered lookup, see `catalogModelInfo` above): a
7756
- // fallback-resolved sibling's resolvedModel/displayName/description can
7757
- // describe a different context lane than the verbatim live id (e.g. an
7758
- // "opus[1m]" row matched for a bare 200k id), so on the fallback path only
7759
- // the id itself is a trustworthy window signal.
7957
+ // The cache lookup is deliberately keyed to the catalog entry (the fork's
7958
+ // unfiltered lookup, see `catalogModelInfo` above): a fallback-resolved
7959
+ // sibling's resolvedModel can name a different context lane than the
7960
+ // verbatim live id (e.g. an "opus[1m]" row matched for a bare 200k id), so
7961
+ // on the fallback path the lookup uses the id itself.
7760
7962
  const seededWindow = resumedContextWindow !== null
7761
7963
  ? { size: resumedContextWindow, authoritative: true }
7762
7964
  : immediateContextWindow(providerCacheKey, models.currentModelId, catalogModelInfo);
@@ -7838,7 +8040,7 @@ export class ClaudeAcpAgent {
7838
8040
  // land whenever the response does. `publishAccountUsage` never rejects, so
7839
8041
  // this cannot become an unhandled rejection.
7840
8042
  void this.publishAccountUsage(sessionId, this.sessions[sessionId]);
7841
- // A guessed window seed (text heuristic / default) is refined the same way,
8043
+ // A default window seed is replaced the same way,
7842
8044
  // unawaited; a resumed session's authoritative seed makes it a no-op.
7843
8045
  this.refreshContextWindowInBackground(sessionId, this.sessions[sessionId]);
7844
8046
  this.refreshUltracodeInBackground(sessionId, this.sessions[sessionId], true);
@@ -7929,9 +8131,16 @@ function totalTokens(usage) {
7929
8131
  * The `errorKind` field is a convention for ACP clients to dispatch on
7930
8132
  * without having to pattern-match the human-readable message text. Clients
7931
8133
  * that don't understand it fall back to the existing message-based rendering.
8134
+ *
8135
+ * For a `rate_limit` failure the turn's latest `rate_limit_event` info rides
8136
+ * along as `rateLimit` (upstream #1610): its `resetsAt` says when the account
8137
+ * can run again, and a message refused at the limit fails before its first
8138
+ * usage, so no `usage_update` carries that info.
7932
8139
  */
7933
- function errorKindData(errorKind) {
7934
- return errorKind ? { errorKind } : undefined;
8140
+ function errorKindData(errorKind, rateLimit) {
8141
+ if (!errorKind)
8142
+ return undefined;
8143
+ return errorKind === "rate_limit" && rateLimit ? { errorKind, rateLimit } : { errorKind };
7935
8144
  }
7936
8145
  /** Project a nullable API usage object into our non-null snapshot shape.
7937
8146
  * Both SDK message_start and assistant message `usage` have `number | null`
@@ -8088,16 +8297,15 @@ const FAST_MODE_DESCRIPTION = "Faster responses on supported models";
8088
8297
  export function fastModeStateEnabled(state) {
8089
8298
  return state !== "off";
8090
8299
  }
8091
- /** User-facing explanations for the SDK's `fast_mode_disabled_reason` values
8092
- * that a user can act on (or at least wants to know about). Deliberately
8093
- * partial — the omitted reasons are not worth surfacing:
8094
- * - `sdk_opt_in_required`: every SDK session starts here (the toggle IS the
8095
- * opt-in), so it describes the default, not a problem.
8096
- * - `preference`: the user turned Fast mode off themselves.
8097
- * - `pending`: eligibility is still resolving; the next report supersedes it.
8098
- * - `unknown`: nothing meaningful to say.
8099
- * Unknown future reasons fall through the same way (open set — the SDK's docs
8100
- * say to ignore values you don't handle). */
8300
+ /** User-facing explanations for the SDK's `fast_mode_disabled_reason` values.
8301
+ * Every reason is explained except the two in
8302
+ * {@link FAST_MODE_UNEXPLAINED_REASONS}; a code missing here gets the generic
8303
+ * text from {@link explainFastModeDisabledReason}.
8304
+ *
8305
+ * `preference` and `unknown` were left out until upstream #1602: behind an API
8306
+ * gateway that authenticates with `ANTHROPIC_AUTH_TOKEN` only, Claude Code
8307
+ * reports `preference` on every turn without asking the server, so the toggle
8308
+ * snapped off with no reason. */
8101
8309
  const FAST_MODE_UNAVAILABLE_EXPLANATIONS = {
8102
8310
  free: "not available on the free plan",
8103
8311
  extra_usage_disabled: "requires extra usage to be enabled for this account",
@@ -8105,14 +8313,32 @@ const FAST_MODE_UNAVAILABLE_EXPLANATIONS = {
8105
8313
  not_first_party: "not available on this API provider",
8106
8314
  disabled_by_env: "disabled by environment configuration",
8107
8315
  network_error: "eligibility could not be verified (network error)",
8316
+ preference: "not enabled for your organization or API gateway",
8317
+ unknown: "currently unavailable",
8108
8318
  };
8319
+ /** Reasons that are never explained:
8320
+ * - `sdk_opt_in_required`: every SDK session starts here (the toggle IS the
8321
+ * opt-in), so it describes the default, not a problem.
8322
+ * - `pending`: eligibility is still resolving; the next report supersedes it. */
8323
+ const FAST_MODE_UNEXPLAINED_REASONS = new Set([
8324
+ "sdk_opt_in_required",
8325
+ "pending",
8326
+ ]);
8327
+ /** The user-facing explanation of a `fast_mode_disabled_reason`: `undefined`
8328
+ * for no reason, `sdk_opt_in_required` or `pending`; the table text when there
8329
+ * is one; else a generic text naming the code (a reason a newer SDK added). */
8330
+ export function explainFastModeDisabledReason(reason) {
8331
+ if (reason === undefined || FAST_MODE_UNEXPLAINED_REASONS.has(reason))
8332
+ return undefined;
8333
+ return FAST_MODE_UNAVAILABLE_EXPLANATIONS[reason] ?? `not available (${reason})`;
8334
+ }
8109
8335
  /** Normalize an SDK-reported `fast_mode_disabled_reason` to the one we retain:
8110
- * a reason we have an explanation for, else `undefined`. Keeping only
8111
- * explainable reasons means state comparisons (see `syncFastModeState`) track
8112
- * exactly what the user can see, so routine reports like
8113
- * `sdk_opt_in_required` never churn the config option. */
8336
+ * a reason {@link explainFastModeDisabledReason} explains (including codes a
8337
+ * newer SDK adds), else `undefined`. State comparisons (see
8338
+ * `syncFastModeState`) then track exactly what the user can see, so
8339
+ * `sdk_opt_in_required` and `pending` never churn the config option. */
8114
8340
  export function normalizeFastModeDisabledReason(reason) {
8115
- return reason && FAST_MODE_UNAVAILABLE_EXPLANATIONS[reason] ? reason : undefined;
8341
+ return explainFastModeDisabledReason(reason) !== undefined ? reason : undefined;
8116
8342
  }
8117
8343
  /** Whether the Client advertised support for boolean session config options
8118
8344
  * (`session.configOptions.boolean`). Agents MUST only send `type: "boolean"`
@@ -8132,9 +8358,7 @@ export function clientSupportsBooleanConfigOptions(clientCapabilities) {
8132
8358
  * stay on. Ignored while enabled: a reason reported alongside an `on`/`cooldown`
8133
8359
  * state isn't blocking anything right now. */
8134
8360
  export function createFastModeConfigOption(enabled, useBooleanOption, disabledReason) {
8135
- const explanation = enabled
8136
- ? undefined
8137
- : disabledReason && FAST_MODE_UNAVAILABLE_EXPLANATIONS[disabledReason];
8361
+ const explanation = enabled ? undefined : explainFastModeDisabledReason(disabledReason);
8138
8362
  const base = {
8139
8363
  id: FAST_MODE_CONFIG_ID,
8140
8364
  name: "Fast mode",
@@ -8660,8 +8884,8 @@ export function applyAvailableModelsAllowlist(sdkModels, allowlist, settingsMode
8660
8884
  * any turn runs in the new process — unlike fresh sessions, where it stalls
8661
8885
  * until the first prompt turn (issues #886/#880) — so the same response that
8662
8886
  * restores the live model (issue #845) also seeds the window for free,
8663
- * covering post-restart reloads of models the text heuristic misses (issue
8664
- * #596), and the occupancy with it: a thread reloaded carrying 150k of
8887
+ * covering post-restart reloads whose window the default would misstate
8888
+ * (issue #596), and the occupancy with it: a thread reloaded carrying 150k of
8665
8889
  * context otherwise reports `used: 0` until its first turn ends, and the
8666
8890
  * client assigns that number to the ring unconditionally. All three come out
8667
8891
  * of ONE response — nothing here adds a control request.
@@ -8917,6 +9141,14 @@ terminalCommands) {
8917
9141
  input: { hint: "checkpoint number (omit to list)" },
8918
9142
  });
8919
9143
  }
9144
+ // `/btw` is answered by the adapter too (§6.8); the SDK lists no such command.
9145
+ if (!advertised.some((command) => command.name === "btw")) {
9146
+ advertised.push({
9147
+ name: "btw",
9148
+ description: "Ask a side question. The answer is not added to the conversation.",
9149
+ input: { hint: "question" },
9150
+ });
9151
+ }
8920
9152
  return advertised;
8921
9153
  }
8922
9154
  function formatUriAsLink(uri) {
@@ -9790,6 +10022,9 @@ export function runAcp(logger) {
9790
10022
  .onRequest(TASKS_OUTPUT_METHOD, { parse: parseTasksOutputRequest }, (ctx) => agent.taskOutput(ctx.params))
9791
10023
  .onRequest(TASKS_BACKGROUND_METHOD, { parse: parseTasksBackgroundRequest }, (ctx) => agent.backgroundTask(ctx.params))
9792
10024
  .onRequest(USAGE_REFRESH_METHOD, { parse: parseUsageRefreshRequest }, (ctx) => agent.refreshUsage(ctx.params))
10025
+ .onRequest(CONTEXT_USAGE_METHOD, { parse: parseContextUsageRequest }, (ctx) => agent.contextUsage(ctx.params))
10026
+ .onRequest(REWIND_METHOD, { parse: parseRewindRequest }, (ctx) => agent.rewind(ctx.params))
10027
+ .onRequest(BTW_METHOD, { parse: parseSideQuestionRequest }, (ctx) => agent.sideQuestion(ctx.params, ctx.signal))
9793
10028
  .onRequest(GOAL_CONTROL_METHOD, { parse: parseGoalRequest }, (ctx) => agent.goal(ctx.params))
9794
10029
  .connect(stream);
9795
10030
  agent = new ClaudeAcpAgent(new ClientConnection(connection.client), logger);
@@ -9802,29 +10037,6 @@ function commonPrefixLength(a, b) {
9802
10037
  }
9803
10038
  return i;
9804
10039
  }
9805
- /** Best-effort first guess of a model's context window, used to seed the
9806
- * window synchronously (via `immediateContextWindow`) until a `result` message
9807
- * arrives with the authoritative `modelUsage` value.
9808
- *
9809
- * Anthropic 1M-context variants encode "1m" as a distinct token in the SDK
9810
- * model ID (e.g., "claude-opus-4-6-1m"), which `\b1m\b` catches without also
9811
- * matching things like "10m" or embedded substrings. Semantic aliases like
9812
- * `default` carry no such token in the ID, but their `resolvedModel` and the
9813
- * SDK's human-facing `displayName`/`description` can (e.g.
9814
- * "claude-opus-4-8[1m]", "Opus 4.7 (1M context)"), so callers pass those too.
9815
- * This text scan can't catch every model — some resolve to extended-context
9816
- * models with no "1m" anywhere (e.g. `sonnet` → claude-sonnet-5, natively
9817
- * ~1M). Such a miss falls back to the default window and is corrected by
9818
- * `result.modelUsage` (and cached) within one turn. We do NOT consult the
9819
- * SDK's `getContextUsage` to close that gap: on a fresh session it is not
9820
- * serviced before the first prompt turn (issues #886/#880, see
9821
- * `contextWindowCache`; resumed sessions do get it, via
9822
- * `readResumedLiveModel`). */
9823
- function inferContextWindowFromModel(...texts) {
9824
- if (texts.some((text) => text != null && /\b1m\b/i.test(text)))
9825
- return 1_000_000;
9826
- return null;
9827
- }
9828
10040
  /** Fetch the SDK's authoritative context-window occupancy via the
9829
10041
  * `getContextUsage` control request. Unlike the per-message API usage numbers
9830
10042
  * (which only count message tokens), this `totalTokens` includes the system
@@ -9896,7 +10108,7 @@ const PROVIDER_ROUTING_ENV_VARS = [
9896
10108
  * Header/credential values can be secrets; the key only ever lives as an
9897
10109
  * in-memory Map key and is never logged or surfaced. Over-keying is the safe
9898
10110
  * side: a var change that didn't really change the backend costs one cache
9899
- * miss (heuristic seed until the next result), while under-keying would serve
10111
+ * miss (default seed until the background read or the next result), while under-keying would serve
9900
10112
  * one backend's window for another's. */
9901
10113
  function providerCacheKeyFor(env) {
9902
10114
  return PROVIDER_ROUTING_ENV_VARS.map((name) => env[name] ?? "").join("\0");
@@ -9915,20 +10127,22 @@ function cacheContextWindow(modelKey, window) {
9915
10127
  /** The context window to report *right now* for a model, with NO IPC on the
9916
10128
  * critical path: the cached authoritative value if we've learned it (from a
9917
10129
  * prior turn's `result.modelUsage`, this or any session on the same backend),
9918
- * else the text heuristic over the model row's identity strings, else the
9919
- * default. Derives the cache key itself — `modelInfo?.resolvedModel ?? modelId`,
9920
- * the same rule at every seed site — so read keys can't drift from the write
9921
- * site's spelling. `authoritative` reports whether the value came from the
9922
- * cache: an authoritative window can legitimately equal
9923
- * DEFAULT_CONTEXT_WINDOW, so the value alone can't tell the caller. */
10130
+ * else the default. Derives the cache key itself —
10131
+ * `modelInfo?.resolvedModel ?? modelId`, the same rule at every seed site — so
10132
+ * read keys can't drift from the write site's spelling. `authoritative` reports
10133
+ * whether the value came from the cache: an authoritative window can
10134
+ * legitimately equal DEFAULT_CONTEXT_WINDOW, so the value alone can't tell the
10135
+ * caller.
10136
+ *
10137
+ * There is no text heuristic any more (upstream #1613): it only turned the old
10138
+ * 200K default into 1M for a "1m" token in the model's id or description, and
10139
+ * a model's names do not give its window — `sonnet` is 1M, or 200K under
10140
+ * `CLAUDE_CODE_DISABLE_1M_CONTEXT=1`. */
9924
10141
  function immediateContextWindow(providerCacheKey, modelId, modelInfo) {
9925
10142
  const cached = contextWindowCache.get(contextWindowCacheKey(providerCacheKey, modelInfo?.resolvedModel ?? modelId));
9926
10143
  if (cached !== undefined)
9927
10144
  return { size: cached, authoritative: true };
9928
- return {
9929
- size: inferContextWindowFromModel(modelId, modelInfo?.resolvedModel, modelInfo?.displayName, modelInfo?.description) ?? DEFAULT_CONTEXT_WINDOW,
9930
- authoritative: false,
9931
- };
10145
+ return { size: DEFAULT_CONTEXT_WINDOW, authoritative: false };
9932
10146
  }
9933
10147
  function parseModelConfig(raw) {
9934
10148
  if (!raw)
@@ -9966,26 +10180,39 @@ function getMatchingModelUsage(modelUsage, currentModel) {
9966
10180
  }
9967
10181
  /**
9968
10182
  * Parity item 92: the Bash tool call and task of a command this result sent to
9969
- * the background — the structured `BashOutput` carries `backgroundTaskId`, and
9970
- * the message holds exactly one tool_result, of a Bash call.
10183
+ * the background. The message holds exactly one tool_result, of a Bash call,
10184
+ * and the task is the structured `BashOutput`'s `backgroundTaskId`.
10185
+ *
10186
+ * Upstream #1540: Claude Code sends no `tool_use_result` with a subagent's tool
10187
+ * results (none of 35 across CLI 2.1.293–2.1.318, per upstream). Without one,
10188
+ * the task is the live backgrounded `local_bash` task whose `task_started`
10189
+ * named this Bash call, which comes before the result. A failed result never
10190
+ * names one: the command did not start.
9971
10191
  */
9972
10192
  function backgroundBashTerminal(message, content, session) {
9973
10193
  if (message.type !== "user" || !Array.isArray(content))
9974
10194
  return undefined;
9975
- const result = message.tool_use_result;
9976
- if (typeof result !== "object" || result === null || !("backgroundTaskId" in result)) {
9977
- return undefined;
9978
- }
9979
- const taskId = result.backgroundTaskId;
9980
- if (typeof taskId !== "string" || taskId === "")
9981
- return undefined;
9982
10195
  const blocks = content.filter((c) => typeof c === "object" && c !== null && c.type === "tool_result");
9983
10196
  if (blocks.length !== 1)
9984
10197
  return undefined;
9985
10198
  const toolCallId = blocks[0].tool_use_id;
9986
10199
  if (session.toolUseCache[toolCallId]?.name !== "Bash")
9987
10200
  return undefined;
9988
- return { taskId, toolCallId };
10201
+ const result = message.tool_use_result;
10202
+ if (typeof result === "object" && result !== null && "backgroundTaskId" in result) {
10203
+ const taskId = result.backgroundTaskId;
10204
+ return typeof taskId === "string" && taskId !== "" ? { taskId, toolCallId } : undefined;
10205
+ }
10206
+ if (result !== undefined || blocks[0].is_error === true)
10207
+ return undefined;
10208
+ for (const [taskId, task] of session.liveBackgroundTasks) {
10209
+ if (task.parentToolUseId === toolCallId &&
10210
+ task.taskType === "local_bash" &&
10211
+ task.backgrounded) {
10212
+ return { taskId, toolCallId };
10213
+ }
10214
+ }
10215
+ return undefined;
9989
10216
  }
9990
10217
  /**
9991
10218
  * Drops `terminal_exit` from the tool result update of `toolCallId`: the Bash