@lucascouts/claude-agent-acp-plus 0.37.0 → 0.38.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";
@@ -24,6 +24,10 @@ import { deleteSessionIfStored } from "./session-delete.js";
24
24
  import { applyPlanUpdatesToOptions, createPlanUpdatesConfigOption, resolvePlanUpdatesAtSpawn, resolvePlanUpdatesRequested, TODO_TOOLS_ENV, } from "./plan-updates.js";
25
25
  import { planRemovedUpdate, planSessionUpdate, supportsPlanOperations } from "./keyed-plan.js";
26
26
  import { handleRewindCommand, parseRewindInvocation } from "./rewind-command.js";
27
+ import { askSideQuestion, BTW_CAPABILITY_KEY, BTW_CAPABILITY_VERSION, BTW_METHOD, BTW_USAGE_TEXT, formatSideAnswer, parseBtwInvocation, parseSideQuestionRequest, } from "./side-question.js";
28
+ import { FORK_AT_META_KEY, parseRewindRequest, planFork, REWIND_CAPABILITY_KEY, REWIND_CAPABILITY_VERSION, REWIND_METHOD, rewindSession, } from "./session-rewind.js";
29
+ import { parseCutAt } from "./turn-cut.js";
30
+ import { CONTEXT_USAGE_CAPABILITY_KEY, CONTEXT_USAGE_CAPABILITY_VERSION, CONTEXT_USAGE_METHOD, fetchContextReport, parseContextUsageRequest, } from "./context-usage.js";
27
31
  import { resolvePermissionMode, sessionAllowsBypass } from "./permissions/modes.js";
28
32
  import { normalizeDurablePermissionChangeSet } from "./permissions/normalization.js";
29
33
  import { buildClaudePermissionOptions } from "./permissions/options.js";
@@ -42,6 +46,8 @@ import { ChildSessionRouter, childStopReasonOf } from "./child-sessions.js";
42
46
  import { readSubagentLaunches } from "./child-session-history.js";
43
47
  import { findTranscript } from "./transcript-path.js";
44
48
  import { parseToolResultMeta } from "./tool-result-meta.js";
49
+ import { progressToolCallId } from "./tool-progress-target.js";
50
+ import { RETRACTED_TOOL_CALL_TEXT, RetractedToolCalls } from "./retracted-tool-calls.js";
45
51
  import { AccountUsageTracker } from "./account-usage.js";
46
52
  import { readFreshLimits, sharedSampleMaxAgeMs, writeLimits } from "./quota-cache.js";
47
53
  import { ACCOUNT_CONFIG_ID, accountForValue, accountInForce, createAccountConfigOption, envForAccount, readDeclaredAccounts, } from "./accounts.js";
@@ -60,7 +66,14 @@ const ZERO_USAGE = Object.freeze({
60
66
  cache_read_input_tokens: 0,
61
67
  cache_creation_input_tokens: 0,
62
68
  });
63
- const DEFAULT_CONTEXT_WINDOW = 200000;
69
+ /** The window reported before Claude Code has said what it is: the background
70
+ * `getContextUsage` read at session creation and at every model switch, then
71
+ * each result's `modelUsage`. 1M since Claude Code 2.1.323, which assumes 1M
72
+ * for an id it does not know and reports 1M for its `opus`/`sonnet`/`haiku`
73
+ * aliases (upstream #1613, measured with `getContextUsage` and no prompt): 200K
74
+ * became the less likely guess, and a 200K default drew a 1M session's context
75
+ * ring at five times its fill until the read landed. */
76
+ const DEFAULT_CONTEXT_WINDOW = 1_000_000;
64
77
  /** Floor after `session/cancel` before the adapter forces the active prompt
65
78
  * loop to return "cancelled". `query.interrupt()` normally makes the SDK
66
79
  * yield a trailing idle within milliseconds, and the loop returns through its
@@ -361,6 +374,23 @@ function isHeldOpen(turn) {
361
374
  function isSteering(turn) {
362
375
  return turn != null && turn.steeredEchoes !== undefined && !turn.settled;
363
376
  }
377
+ /** Whether a steered turn's recorded outcome is its steered work's own: every
378
+ * steered message has been picked up and a result arrived after the last one
379
+ * (see Turn.steeredAwaitingResult), so the next idle can settle it. */
380
+ function isSteeredSettleReady(turn) {
381
+ return (isSteering(turn) &&
382
+ turn.steeredEchoes.size === 0 &&
383
+ turn.steeredSettle !== undefined &&
384
+ !turn.steeredAwaitingResult);
385
+ }
386
+ /** Take a turn out of the steer lane so its settlement follows the ordinary
387
+ * result/idle rules again. */
388
+ function leaveSteerLane(turn) {
389
+ turn.steeredEchoes = undefined;
390
+ turn.steeredUuids = undefined;
391
+ turn.steeredAwaitingResult = undefined;
392
+ turn.steeredSettle = undefined;
393
+ }
364
394
  /** Disarm the force-cancel backstop (see Session.forceCancelTimer). Every
365
395
  * path that settles the active turn must run this so a timer can never fire
366
396
  * on an already-settled turn — and must leave the field undefined, or the
@@ -1082,6 +1112,9 @@ export class ClaudeAcpAgent {
1082
1112
  version: this.childSessions ? TASKS_RFD_CONTRACT_VERSION : TASKS_CAPABILITY_VERSION,
1083
1113
  },
1084
1114
  [USAGE_CAPABILITY_KEY]: { version: USAGE_CAPABILITY_VERSION },
1115
+ [BTW_CAPABILITY_KEY]: { version: BTW_CAPABILITY_VERSION },
1116
+ [REWIND_CAPABILITY_KEY]: { version: REWIND_CAPABILITY_VERSION },
1117
+ [CONTEXT_USAGE_CAPABILITY_KEY]: { version: CONTEXT_USAGE_CAPABILITY_VERSION },
1085
1118
  },
1086
1119
  promptCapabilities: {
1087
1120
  image: true,
@@ -1149,15 +1182,16 @@ export class ClaudeAcpAgent {
1149
1182
  async unstable_forkSession(params) {
1150
1183
  if (this.providerUpdate)
1151
1184
  await this.providerUpdate;
1185
+ // A cut point under `_meta["_claude/forkAt"]` forks from that turn (§6.33);
1186
+ // without one the fork copies the whole session, as before.
1187
+ const rawCut = params._meta?.[FORK_AT_META_KEY];
1188
+ const plan = await planFork(this.sessionCutDeps(params.sessionId), params.sessionId, rawCut === undefined ? undefined : parseCutAt(rawCut, `session/fork ${FORK_AT_META_KEY}`));
1152
1189
  const response = await this.createSession({
1153
1190
  cwd: params.cwd,
1154
1191
  mcpServers: params.mcpServers ?? [],
1155
1192
  additionalDirectories: params.additionalDirectories,
1156
1193
  _meta: params._meta,
1157
- }, {
1158
- resume: params.sessionId,
1159
- forkSession: true,
1160
- });
1194
+ }, plan);
1161
1195
  // Needs to happen after we return the session
1162
1196
  setTimeout(() => {
1163
1197
  this.sendAvailableCommandsUpdate(response.sessionId);
@@ -1349,6 +1383,23 @@ export class ClaudeAcpAgent {
1349
1383
  // emits every user-facing update before it resolves, so returning end_turn
1350
1384
  // here leaves Zed with a complete turn rather than an empty/hung one.
1351
1385
  const commandText = params.prompt[0]?.type === "text" ? params.prompt[0].text : "";
1386
+ // `/btw` typed into a composer (§6.8): a side question answered as an
1387
+ // aside, never enqueued and never added to the model's history, so it may
1388
+ // run while a turn is in flight. Zeo uses `_claude/btw` instead.
1389
+ const btwInvocation = parseBtwInvocation(commandText);
1390
+ if (btwInvocation) {
1391
+ const text = btwInvocation.kind === "usage"
1392
+ ? BTW_USAGE_TEXT
1393
+ : formatSideAnswer(await this.sideQuestion({
1394
+ sessionId: params.sessionId,
1395
+ question: btwInvocation.question,
1396
+ }));
1397
+ await this.client.sessionUpdate({
1398
+ sessionId: params.sessionId,
1399
+ update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } },
1400
+ });
1401
+ return { stopReason: "end_turn" };
1402
+ }
1352
1403
  const rewindInvocation = parseRewindInvocation(commandText);
1353
1404
  if (rewindInvocation) {
1354
1405
  // A lazy Thinking recreate may be swapping the session's query right
@@ -1687,6 +1738,106 @@ export class ClaudeAcpAgent {
1687
1738
  timer.unref?.();
1688
1739
  session.accountUsageTimer = timer;
1689
1740
  }
1741
+ /**
1742
+ * `_claude/context/usage`: what fills this session's context window (see
1743
+ * context-usage.ts), asked on a click, never per turn. On an idle session it
1744
+ * asks for the full breakdown; while a turn is active or queued only for the
1745
+ * local estimate, because the full one makes token-count calls and SDK
1746
+ * control requests are serialized — an interrupt queued behind it would
1747
+ * delay the Stop button (the same reason `_claude/usage/refresh` skips
1748
+ * mid-turn). The answer says which it got.
1749
+ */
1750
+ async contextUsage(params) {
1751
+ const { sessionId } = params;
1752
+ const log = (outcome) => this.logger.log(`[context/usage] method=${CONTEXT_USAGE_METHOD} sessionId=${logValue(sessionId)} outcome=${outcome}`);
1753
+ const session = Object.hasOwn(this.sessions, sessionId) ? this.sessions[sessionId] : undefined;
1754
+ if (!session) {
1755
+ log("error_unknown_session");
1756
+ throw RequestError.invalidParams(undefined, `unknown session ${sessionId}`);
1757
+ }
1758
+ if (session.queryClosed) {
1759
+ log("unavailable_session_ended");
1760
+ return { status: "unavailable", message: SESSION_ENDED_MESSAGE };
1761
+ }
1762
+ if (session.queryRecreateInFlight) {
1763
+ await session.queryRecreateInFlight;
1764
+ }
1765
+ const busy = Boolean(session.turnQueue?.length || session.activeTurn);
1766
+ const report = await fetchContextReport(session.query, busy ? "summary" : "full");
1767
+ log(report.status === "ok" ? `ok_${report.detail}` : report.status);
1768
+ return report;
1769
+ }
1770
+ /** Transcript reads and copies for a cut at a turn (fork and rewind). */
1771
+ sessionCutDeps(sessionId) {
1772
+ return {
1773
+ readTranscript: async () => (await getSessionMessages(sessionId)),
1774
+ messageIdToUuid: this.sessions[sessionId]?.messageIdToUuid ?? new Map(),
1775
+ forkTranscript: async (upToUuid) => (await sdkForkSession(sessionId, { upToMessageId: upToUuid })).sessionId,
1776
+ };
1777
+ }
1778
+ /**
1779
+ * `_claude/rewind`: take the session back to the end of a turn, files
1780
+ * optionally included (see session-rewind.ts). Refused as `busy` while a turn
1781
+ * is active or queued, or another rewind runs — the same idleness rule as
1782
+ * `/rewind`, for the same reason: never restore files under a running edit.
1783
+ * The answer names a NEW session holding the kept turns; this session is
1784
+ * left as it is for the client to replace.
1785
+ */
1786
+ async rewind(params) {
1787
+ const { sessionId } = params;
1788
+ const log = (outcome) => this.logger.log(`[rewind] method=${REWIND_METHOD} sessionId=${logValue(sessionId)} restoreFiles=${params.restoreFiles} outcome=${outcome}`);
1789
+ const session = Object.hasOwn(this.sessions, sessionId) ? this.sessions[sessionId] : undefined;
1790
+ if (!session) {
1791
+ log("error_unknown_session");
1792
+ throw RequestError.invalidParams(undefined, `unknown session ${sessionId}`);
1793
+ }
1794
+ if (session.queryRecreateInFlight) {
1795
+ await session.queryRecreateInFlight;
1796
+ }
1797
+ if (session.turnQueue?.length || session.activeTurn || session.rewindInFlight) {
1798
+ log("busy");
1799
+ return { status: "busy" };
1800
+ }
1801
+ session.rewindInFlight = true;
1802
+ try {
1803
+ const result = await rewindSession({
1804
+ ...this.sessionCutDeps(sessionId),
1805
+ rewindFiles: (uuid) => session.query.rewindFiles(uuid),
1806
+ }, params);
1807
+ log(result.status === "failed" ? `failed_${result.stage}` : result.status);
1808
+ return result;
1809
+ }
1810
+ finally {
1811
+ session.rewindInFlight = false;
1812
+ }
1813
+ }
1814
+ /**
1815
+ * `_claude/btw`: answer a side question without touching the conversation
1816
+ * (see side-question.ts). Allowed while a turn runs — that is the point —
1817
+ * and never enqueued: the CLI's `side_question` control request answers
1818
+ * beside the turn. Only an unknown session is an error; every other outcome,
1819
+ * an ended session included, is a result the client can show.
1820
+ */
1821
+ async sideQuestion(params, signal) {
1822
+ const { sessionId, question } = params;
1823
+ const log = (outcome) => this.logger.log(`[btw] method=${BTW_METHOD} sessionId=${logValue(sessionId)} questionChars=${question.length} outcome=${outcome}`);
1824
+ const session = Object.hasOwn(this.sessions, sessionId) ? this.sessions[sessionId] : undefined;
1825
+ if (!session) {
1826
+ log("error_unknown_session");
1827
+ throw RequestError.invalidParams(undefined, `unknown session ${sessionId}`);
1828
+ }
1829
+ if (session.queryClosed) {
1830
+ log("failed_session_ended");
1831
+ return { status: "failed", message: SESSION_ENDED_MESSAGE };
1832
+ }
1833
+ // A Thinking recreate may be swapping the query; ask the live one.
1834
+ if (session.queryRecreateInFlight) {
1835
+ await session.queryRecreateInFlight;
1836
+ }
1837
+ const result = await askSideQuestion(session.query, question, signal);
1838
+ log(result.status);
1839
+ return result;
1840
+ }
1690
1841
  /**
1691
1842
  * `_claude/usage/refresh`: publish this session's quota windows now, on
1692
1843
  * demand, and answer whether any were published.
@@ -1839,10 +1990,9 @@ export class ClaudeAcpAgent {
1839
1990
  *
1840
1991
  * Before 0.3.286 delivering `now` ABORTED the cycle, which emitted a `result`
1841
1992
  * 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.
1993
+ * joins the turn. The turn is marked (`Turn.steeredEchoes`) to settle only
1994
+ * once a result answers the steer, or at the SDK's `idle` after one, so
1995
+ * either CLI behaviour settles once, after the steered work.
1846
1996
  *
1847
1997
  * When the session is idle, the opt-in path returns `promptRequired` WITHOUT
1848
1998
  * calling `prompt()`, pushing SDK input, or mutating `turnQueue`: the content
@@ -2016,6 +2166,7 @@ export class ClaudeAcpAgent {
2016
2166
  // time the consumer next runs, and an unmarked result would settle the turn
2017
2167
  // (see Turn.steeredEchoes).
2018
2168
  (turnInFlight.steeredEchoes ??= new Set()).add(steeredUuid);
2169
+ (turnInFlight.steeredUuids ??= new Set()).add(steeredUuid);
2019
2170
  // A turn already held for background subagents has a recorded outcome the
2020
2171
  // steer supersedes: move it into the steer lane so one lane owns settlement.
2021
2172
  // The idle handler re-applies the hold through the subagent gate.
@@ -2082,6 +2233,9 @@ export class ClaudeAcpAgent {
2082
2233
  // send it with (upstream #1534): with partial messages on, the SDK sends it
2083
2234
  // ahead of the first assistant frame. It rides the turn's next usage_update.
2084
2235
  let pendingRateLimit = null;
2236
+ // The turn's latest rate_limit_event info, for the data of its failure
2237
+ // (upstream #1610, see `errorKindData`).
2238
+ let turnRateLimit;
2085
2239
  // When the Claude SDK classifies a turn as failed (e.g. rate limit, auth
2086
2240
  // problem, billing), it sets a categorical `error` field on the
2087
2241
  // `SDKAssistantMessage` that precedes the final `result` message. We capture
@@ -2256,6 +2410,7 @@ export class ClaudeAcpAgent {
2256
2410
  // usage_update to ride must not be attributed to the next turn. The
2257
2411
  // tracker already remembers its status (R1.6).
2258
2412
  pendingRateLimit = null;
2413
+ turnRateLimit = undefined;
2259
2414
  lastAssistantError = undefined;
2260
2415
  lastAssistantWasUsageLimit = false;
2261
2416
  lastAssistantFailureTitle = undefined;
@@ -2506,6 +2661,8 @@ export class ClaudeAcpAgent {
2506
2661
  * marked as a background result, but it lists the uuids of the prompts it
2507
2662
  * answered.
2508
2663
  *
2664
+ * A steer belongs to the live active turn even though it has no queued
2665
+ * Turn of its own. Its stamped result can answer that turn too.
2509
2666
  * A turn held open for its background subagents already has its result,
2510
2667
  * so a result that names it does not answer it. */
2511
2668
  const answersPendingPrompt = (message) => {
@@ -2518,8 +2675,13 @@ export class ClaudeAcpAgent {
2518
2675
  else if (typeof message.user_message_uuid === "string") {
2519
2676
  answeredPromptUuids = [message.user_message_uuid];
2520
2677
  }
2678
+ const activeTurn = session.activeTurn;
2679
+ const liveActiveTurn = activeTurn && !activeTurn.settled && !isHeldOpen(activeTurn) ? activeTurn : undefined;
2521
2680
  for (const promptUuid of answeredPromptUuids) {
2522
- const turn = findUnsettledTurn(promptUuid);
2681
+ // Keep queued prompt matching, including folded sends with no echo.
2682
+ // Steers qualify only through their live active owner.
2683
+ const turn = findUnsettledTurn(promptUuid) ??
2684
+ (liveActiveTurn?.steeredUuids?.has(promptUuid) ? liveActiveTurn : undefined);
2523
2685
  if (turn === undefined) {
2524
2686
  // Not a prompt of this session, or it was answered already.
2525
2687
  continue;
@@ -2630,6 +2792,29 @@ export class ClaudeAcpAgent {
2630
2792
  },
2631
2793
  });
2632
2794
  };
2795
+ /** Upstream #1616: fails the open tool calls of the messages that `message`
2796
+ * says Claude Code took back. No result comes for them, so they would
2797
+ * spin in the client. A call whose result came is not open any more. */
2798
+ const closeRetractedToolCalls = async (message) => {
2799
+ const retracted = (session.retractedToolCalls ??= new RetractedToolCalls()).retractedBy(message);
2800
+ for (const { toolCallId, parentToolUseId } of retracted) {
2801
+ if (!session.emittedToolCalls.delete(toolCallId))
2802
+ continue;
2803
+ this.logger.log(`[tool-call/retracted] sessionId=${params.sessionId} toolCallId=${toolCallId}`);
2804
+ await sendUpdate({
2805
+ sessionId: params.sessionId,
2806
+ update: {
2807
+ sessionUpdate: "tool_call_update",
2808
+ toolCallId,
2809
+ status: "failed",
2810
+ content: [
2811
+ { type: "content", content: { type: "text", text: RETRACTED_TOOL_CALL_TEXT } },
2812
+ ],
2813
+ ...(parentToolUseId ? { _meta: { claudeCode: { parentToolUseId } } } : {}),
2814
+ },
2815
+ });
2816
+ }
2817
+ };
2633
2818
  const turnAwaitingSubagents = (turn) => {
2634
2819
  if (!turn.spawnedTaskIds?.size) {
2635
2820
  return false;
@@ -2697,6 +2882,7 @@ export class ClaudeAcpAgent {
2697
2882
  // so the last result and its usage win.
2698
2883
  if (isSteering(session.activeTurn)) {
2699
2884
  session.activeTurn.steeredSettle = outcome;
2885
+ session.activeTurn.steeredAwaitingResult = false;
2700
2886
  return;
2701
2887
  }
2702
2888
  if (session.activeTurn &&
@@ -3274,9 +3460,9 @@ export class ClaudeAcpAgent {
3274
3460
  // why this sweep is safe to carry on both cadences.
3275
3461
  //
3276
3462
  // 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.
3463
+ // -- masking an issue-#825 detection. (The ready steer lane
3464
+ // below runs ahead of the debt and leaves it standing when it
3465
+ // settles, so the sweep is what retires that debt.)
3280
3466
  this.logger.log(`[turn/idle-debt] swept=${session.owedTrailingIdles} session=${params.sessionId} at=running-transition`);
3281
3467
  session.owedTrailingIdles = 0;
3282
3468
  }
@@ -3348,38 +3534,44 @@ export class ClaudeAcpAgent {
3348
3534
  }
3349
3535
  settleDeferredIfDrained();
3350
3536
  }
3537
+ else if (isSteeredSettleReady(session.activeTurn)) {
3538
+ // A steered turn whose steered work has produced its result
3539
+ // (see Turn.steeredEchoes) settles at the next idle — the
3540
+ // only signal spanning the interrupted and steered cycles
3541
+ // when results aren't stamped. AHEAD of owed-idle debt:
3542
+ // the outcome is final, so whichever idle this is settles
3543
+ // the turn correctly, while debt absorption could swallow
3544
+ // the only idle it gets — e.g. a steer that aborted an
3545
+ // autonomous followup, whose counted trailer collapses into
3546
+ // this one idle. The debt is left standing: a genuinely
3547
+ // separate trailer still absorbs the idle it belongs to,
3548
+ // and one that never comes is swept at the next `running`
3549
+ // transition.
3550
+ //
3551
+ // Via the subagent gate, not settleActive: a steered turn
3552
+ // can also have spawned background subagents, which own it
3553
+ // from here (settles now if none is live, holds otherwise).
3554
+ const steered = session.activeTurn;
3555
+ steered.deferredSettle = steered.steeredSettle;
3556
+ leaveSteerLane(steered);
3557
+ settleDeferredIfDrained();
3558
+ }
3351
3559
  else if (session.owedTrailingIdles > 0) {
3352
3560
  // Absorb a settled turn's trailing idle. Also covers a
3353
3561
  // cancel that landed between a turn's counted result and
3354
3562
  // this lagged idle (no active turn to settle): the idle
3355
3563
  // still belongs to that settled turn, and skipping the
3356
3564
  // 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.
3565
+ // Deliberately BEFORE the not-ready steer lane below: an
3566
+ // owed idle belongs to an earlier turn, and it must not be
3567
+ // left to reach the #825 fail. Steered results owe none.
3361
3568
  session.owedTrailingIdles--;
3362
3569
  }
3363
3570
  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
- }
3571
+ // A steered turn whose answer is still ahead: an idle before
3572
+ // the steered echo, or before a result since it. Swallow it,
3573
+ // and never let it reach the #825 fail below, which would
3574
+ // reject a prompt about to answer.
3383
3575
  }
3384
3576
  else if (!session.cancelled &&
3385
3577
  session.activeTurn &&
@@ -3647,6 +3839,7 @@ export class ClaudeAcpAgent {
3647
3839
  ? { backgrounded: message.is_backgrounded }
3648
3840
  : {}),
3649
3841
  ...(message.parent_task_id ? { parentTaskId: message.parent_task_id } : {}),
3842
+ ...(message.task_type ? { taskType: message.task_type } : {}),
3650
3843
  });
3651
3844
  if (message.subagent_type && session.activeTurn && !session.activeTurn.settled) {
3652
3845
  (session.activeTurn.spawnedTaskIds ??= new Set()).add(message.task_id);
@@ -3780,6 +3973,7 @@ export class ClaudeAcpAgent {
3780
3973
  break;
3781
3974
  }
3782
3975
  case "model_refusal_fallback": {
3976
+ await closeRetractedToolCalls(message);
3783
3977
  // The SDK retried a refused turn on the fallback model and made
3784
3978
  // the swap persistent for the session. Without a notice the
3785
3979
  // user just sees regenerated output; without the state sync the
@@ -3959,6 +4153,29 @@ export class ClaudeAcpAgent {
3959
4153
  if (!isAutonomousResult) {
3960
4154
  recordResultForOrphanCommands();
3961
4155
  ensureActiveTurn(message.user_message_uuid);
4156
+ // A result that names a steer consumed it (see
4157
+ // Turn.steeredEchoes), so the steered work is done: retire
4158
+ // its echo — the CLI may never have replayed it — and, with
4159
+ // no other steer outstanding, leave the steer lane so this
4160
+ // result settles the turn through the ordinary lanes below
4161
+ // and owes its trailing idle like any other. The interrupted
4162
+ // cycle's result names only the send it was answering, so it
4163
+ // stays on the steer lane. A cancelled turn's steers are
4164
+ // cancel()'s to account for.
4165
+ const steeredTurn = session.activeTurn;
4166
+ if (!session.cancelled && isSteering(steeredTurn)) {
4167
+ const consumed = message.user_message_uuids ??
4168
+ (message.user_message_uuid !== undefined ? [message.user_message_uuid] : []);
4169
+ let answersSteer = false;
4170
+ for (const uuid of consumed) {
4171
+ steeredTurn.steeredEchoes.delete(uuid);
4172
+ if (steeredTurn.steeredUuids?.has(uuid))
4173
+ answersSteer = true;
4174
+ }
4175
+ if (answersSteer && steeredTurn.steeredEchoes.size === 0) {
4176
+ leaveSteerLane(steeredTurn);
4177
+ }
4178
+ }
3962
4179
  // Once the submitted goal command has produced its own result,
3963
4180
  // no older runtime update can still precede it in the ordered
3964
4181
  // SDK stream. Stop suppressing updates even when this runtime
@@ -4040,7 +4257,9 @@ export class ClaudeAcpAgent {
4040
4257
  // Turn.steeredEchoes). One idle covers the whole interrupted +
4041
4258
  // steered sequence and that idle settles the turn, so counting
4042
4259
  // either result would leave a debt that swallows it. Autonomous
4043
- // results inside a steered turn keep their own trailers.
4260
+ // results inside a steered turn keep their own trailers, and so
4261
+ // does a result that named the steer: it took the turn out of the
4262
+ // steer lane above and settles at the result, not the idle.
4044
4263
  const owesTrailingIdle = isAutonomousResult || !isSteering(session.activeTurn);
4045
4264
  if (owesTrailingIdle &&
4046
4265
  (isAutonomousResult || !session.cancelled || !session.activeTurn)) {
@@ -4260,7 +4479,7 @@ export class ClaudeAcpAgent {
4260
4479
  break;
4261
4480
  }
4262
4481
  if (message.is_error) {
4263
- await failActiveWithSessionFailure(providerFailureCategory(lastAssistantError, lastAssistantWasUsageLimit), internalErrorForClient(errorKindData(lastAssistantError), message.result), lastAssistantFailureTitle ?? message.result);
4482
+ await failActiveWithSessionFailure(providerFailureCategory(lastAssistantError, lastAssistantWasUsageLimit), internalErrorForClient(errorKindData(lastAssistantError, turnRateLimit), message.result), lastAssistantFailureTitle ?? message.result);
4264
4483
  break;
4265
4484
  }
4266
4485
  // The result text is forwarded in two cases. Local-only
@@ -4307,7 +4526,7 @@ export class ClaudeAcpAgent {
4307
4526
  break;
4308
4527
  }
4309
4528
  if (message.is_error) {
4310
- await failActiveWithSessionFailure(providerFailureCategory(lastAssistantError, lastAssistantWasUsageLimit), internalErrorForClient(errorKindData(lastAssistantError), message.errors.join(", ") || message.subtype), lastAssistantFailureTitle ?? (message.errors.join(", ") || message.subtype));
4529
+ await failActiveWithSessionFailure(providerFailureCategory(lastAssistantError, lastAssistantWasUsageLimit), internalErrorForClient(errorKindData(lastAssistantError, turnRateLimit), message.errors.join(", ") || message.subtype), lastAssistantFailureTitle ?? (message.errors.join(", ") || message.subtype));
4311
4530
  break;
4312
4531
  }
4313
4532
  stopReason = "end_turn";
@@ -4315,21 +4534,21 @@ export class ClaudeAcpAgent {
4315
4534
  }
4316
4535
  case "error_max_budget_usd":
4317
4536
  if (message.is_error) {
4318
- await failActiveWithSessionFailure("budget_exhausted", internalErrorForClient(errorKindData(lastAssistantError), message.errors.join(", ") || message.subtype), message.errors.join(", ") || message.subtype);
4537
+ await failActiveWithSessionFailure("budget_exhausted", internalErrorForClient(errorKindData(lastAssistantError, turnRateLimit), message.errors.join(", ") || message.subtype), message.errors.join(", ") || message.subtype);
4319
4538
  break;
4320
4539
  }
4321
4540
  stopReason = "max_turn_requests";
4322
4541
  break;
4323
4542
  case "error_max_turns":
4324
4543
  if (message.is_error) {
4325
- await failActiveWithSessionFailure("context_exhausted", internalErrorForClient(errorKindData(lastAssistantError), message.errors.join(", ") || message.subtype), message.errors.join(", ") || message.subtype);
4544
+ await failActiveWithSessionFailure("context_exhausted", internalErrorForClient(errorKindData(lastAssistantError, turnRateLimit), message.errors.join(", ") || message.subtype), message.errors.join(", ") || message.subtype);
4326
4545
  break;
4327
4546
  }
4328
4547
  stopReason = "max_turn_requests";
4329
4548
  break;
4330
4549
  case "error_max_structured_output_retries":
4331
4550
  if (message.is_error) {
4332
- await failActiveWithSessionFailure("provider_error", internalErrorForClient(errorKindData(lastAssistantError), message.errors.join(", ") || message.subtype), message.errors.join(", ") || message.subtype);
4551
+ await failActiveWithSessionFailure("provider_error", internalErrorForClient(errorKindData(lastAssistantError, turnRateLimit), message.errors.join(", ") || message.subtype), message.errors.join(", ") || message.subtype);
4333
4552
  break;
4334
4553
  }
4335
4554
  stopReason = "max_turn_requests";
@@ -4477,21 +4696,6 @@ export class ClaudeAcpAgent {
4477
4696
  const model = message.event.message.model;
4478
4697
  if (model && model !== "<synthetic>") {
4479
4698
  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
4699
  }
4496
4700
  }
4497
4701
  else {
@@ -4631,8 +4835,11 @@ export class ClaudeAcpAgent {
4631
4835
  // none), but it marks the steered cycle as running — how the idle
4632
4836
  // lane tells "the answer is still ahead" from "the turn is over"
4633
4837
  // (see Turn.steeredEchoes).
4634
- if (isSteering(session.activeTurn)) {
4635
- session.activeTurn.steeredEchoes.delete(message.uuid);
4838
+ // The outcome recorded so far predates the steered cycle, so the
4839
+ // idle lane waits for that cycle's own result.
4840
+ if (isSteering(session.activeTurn) &&
4841
+ session.activeTurn.steeredEchoes.delete(message.uuid)) {
4842
+ session.activeTurn.steeredAwaitingResult = true;
4636
4843
  }
4637
4844
  // Unrelated replay (e.g. the echo of an already-settled turn).
4638
4845
  break;
@@ -4645,6 +4852,13 @@ export class ClaudeAcpAgent {
4645
4852
  !this.childSessions?.childFor(params.sessionId, parentToolUseIdOf(message))) {
4646
4853
  break;
4647
4854
  }
4855
+ // Upstream #1616: the first message of a retry names the response it
4856
+ // replaces (`supersedes`); every assistant message is recorded so a
4857
+ // later retraction can find its tool calls.
4858
+ if (message.type === "assistant") {
4859
+ await closeRetractedToolCalls(message);
4860
+ (session.retractedToolCalls ??= new RetractedToolCalls()).sent(message);
4861
+ }
4648
4862
  // Synthetic assistant frames carry the CLI's local-command output.
4649
4863
  // On resume the SDK can replay a stale frame from an earlier compact
4650
4864
  // attempt after a later compaction completed. Scope the suppression
@@ -4931,25 +5145,11 @@ export class ClaudeAcpAgent {
4931
5145
  break;
4932
5146
  }
4933
5147
  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)) {
5148
+ // Which call a beat lands on, and which beats are dropped (a hook's
5149
+ // heartbeat among them), is `progressToolCallId`'s rule.
5150
+ const toolCallId = progressToolCallId(message, session.emittedToolCalls);
5151
+ if (toolCallId === undefined)
4951
5152
  break;
4952
- }
4953
5153
  await sendUpdate({
4954
5154
  sessionId: params.sessionId,
4955
5155
  update: {
@@ -4994,6 +5194,7 @@ export class ClaudeAcpAgent {
4994
5194
  // the same notification shape (R1.8); when the turn has no context
4995
5195
  // total yet, it waits for the turn's next usage_update (#1534).
4996
5196
  this.accountUsageTracker(session).recordMeasured(message.rate_limit_info);
5197
+ turnRateLimit = message.rate_limit_info;
4997
5198
  if (lastAssistantTotalUsage === null) {
4998
5199
  pendingRateLimit = message.rate_limit_info;
4999
5200
  }
@@ -6409,11 +6610,11 @@ export class ClaudeAcpAgent {
6409
6610
  });
6410
6611
  }
6411
6612
  /**
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,
6613
+ * Replace the default context window with `getContextUsage().rawMaxTokens`
6614
+ * without blocking the caller. Without it, a model with a 200K window
6615
+ * (`claude-sonnet-4-5`, or any model under `CLAUDE_CODE_DISABLE_1M_CONTEXT=1`)
6616
+ * would report the 1M default until the first result's modelUsage
6617
+ * (upstream #1613). Never awaited: SDK control requests are serialized,
6417
6618
  * so an awaited call would delay session/new or a model switch (before the
6418
6619
  * first turn it took ~15s on older CLIs, issues #886/#880; ~0.5s on 2.1.283).
6419
6620
  * Not written to `contextWindowCache` — that stays keyed to the
@@ -6472,11 +6673,11 @@ export class ClaudeAcpAgent {
6472
6673
  if (modelChanged) {
6473
6674
  // Seed the new model's context window WITHOUT awaited IPC on the
6474
6675
  // 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
6676
+ // (from a prior turn's `result.modelUsage`), else the default. SDK
6677
+ // control requests are serialized over one channel, so an awaited
6678
+ // `getContextUsage` here would delay the rest of the switch (issues
6679
+ // #886/#880); the default is instead replaced in the background once
6680
+ // the switch is done
6480
6681
  // (`refreshContextWindowInBackground`).
6481
6682
  const seeded = immediateContextWindow(session.providerCacheKey, value, newModelInfo);
6482
6683
  session.contextWindowSize = seeded.size;
@@ -7038,7 +7239,7 @@ export class ClaudeAcpAgent {
7038
7239
  // The user asked for Fast mode and the SDK is telling us it can't serve it.
7039
7240
  // The description carries the same explanation, but a toggle silently
7040
7241
  // snapping back is the case worth saying out loud once, at the flip.
7041
- const explanation = nextReason !== undefined ? FAST_MODE_UNAVAILABLE_EXPLANATIONS[nextReason] : undefined;
7242
+ const explanation = explainFastModeDisabledReason(nextReason);
7042
7243
  const explain = session.fastModeEnabled && !enabled && explanation !== undefined;
7043
7244
  session.fastModeEnabled = enabled;
7044
7245
  session.fastModeDisabledReason = nextReason;
@@ -7734,29 +7935,21 @@ export class ClaudeAcpAgent {
7734
7935
  // authoritative and wins. That one response also carries how much of the
7735
7936
  // window is already occupied, seeded onto `contextUsedTokens` below.
7736
7937
  // 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
7938
+ // it for this model (`result.modelUsage`, cross-session), else the
7939
+ // default. We deliberately do NOT await a getContextUsage call here: on a fresh session that control request is
7740
7940
  // not serviced until the first prompt turn runs, so awaiting it — as
7741
7941
  // 0.59.0 did — made session/new take ~15s (issues #886/#880). The
7742
7942
  // authoritative window arrives on the first `result.modelUsage` and is
7743
7943
  // cached from there.
7744
7944
  //
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).
7945
+ // A miss seeds the default, which `refreshContextWindowInBackground`
7946
+ // replaces once the session is registered (issue #596; upstream #1613).
7753
7947
  //
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.
7948
+ // The cache lookup is deliberately keyed to the catalog entry (the fork's
7949
+ // unfiltered lookup, see `catalogModelInfo` above): a fallback-resolved
7950
+ // sibling's resolvedModel can name a different context lane than the
7951
+ // verbatim live id (e.g. an "opus[1m]" row matched for a bare 200k id), so
7952
+ // on the fallback path the lookup uses the id itself.
7760
7953
  const seededWindow = resumedContextWindow !== null
7761
7954
  ? { size: resumedContextWindow, authoritative: true }
7762
7955
  : immediateContextWindow(providerCacheKey, models.currentModelId, catalogModelInfo);
@@ -7838,7 +8031,7 @@ export class ClaudeAcpAgent {
7838
8031
  // land whenever the response does. `publishAccountUsage` never rejects, so
7839
8032
  // this cannot become an unhandled rejection.
7840
8033
  void this.publishAccountUsage(sessionId, this.sessions[sessionId]);
7841
- // A guessed window seed (text heuristic / default) is refined the same way,
8034
+ // A default window seed is replaced the same way,
7842
8035
  // unawaited; a resumed session's authoritative seed makes it a no-op.
7843
8036
  this.refreshContextWindowInBackground(sessionId, this.sessions[sessionId]);
7844
8037
  this.refreshUltracodeInBackground(sessionId, this.sessions[sessionId], true);
@@ -7929,9 +8122,16 @@ function totalTokens(usage) {
7929
8122
  * The `errorKind` field is a convention for ACP clients to dispatch on
7930
8123
  * without having to pattern-match the human-readable message text. Clients
7931
8124
  * that don't understand it fall back to the existing message-based rendering.
8125
+ *
8126
+ * For a `rate_limit` failure the turn's latest `rate_limit_event` info rides
8127
+ * along as `rateLimit` (upstream #1610): its `resetsAt` says when the account
8128
+ * can run again, and a message refused at the limit fails before its first
8129
+ * usage, so no `usage_update` carries that info.
7932
8130
  */
7933
- function errorKindData(errorKind) {
7934
- return errorKind ? { errorKind } : undefined;
8131
+ function errorKindData(errorKind, rateLimit) {
8132
+ if (!errorKind)
8133
+ return undefined;
8134
+ return errorKind === "rate_limit" && rateLimit ? { errorKind, rateLimit } : { errorKind };
7935
8135
  }
7936
8136
  /** Project a nullable API usage object into our non-null snapshot shape.
7937
8137
  * Both SDK message_start and assistant message `usage` have `number | null`
@@ -8088,16 +8288,15 @@ const FAST_MODE_DESCRIPTION = "Faster responses on supported models";
8088
8288
  export function fastModeStateEnabled(state) {
8089
8289
  return state !== "off";
8090
8290
  }
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). */
8291
+ /** User-facing explanations for the SDK's `fast_mode_disabled_reason` values.
8292
+ * Every reason is explained except the two in
8293
+ * {@link FAST_MODE_UNEXPLAINED_REASONS}; a code missing here gets the generic
8294
+ * text from {@link explainFastModeDisabledReason}.
8295
+ *
8296
+ * `preference` and `unknown` were left out until upstream #1602: behind an API
8297
+ * gateway that authenticates with `ANTHROPIC_AUTH_TOKEN` only, Claude Code
8298
+ * reports `preference` on every turn without asking the server, so the toggle
8299
+ * snapped off with no reason. */
8101
8300
  const FAST_MODE_UNAVAILABLE_EXPLANATIONS = {
8102
8301
  free: "not available on the free plan",
8103
8302
  extra_usage_disabled: "requires extra usage to be enabled for this account",
@@ -8105,14 +8304,32 @@ const FAST_MODE_UNAVAILABLE_EXPLANATIONS = {
8105
8304
  not_first_party: "not available on this API provider",
8106
8305
  disabled_by_env: "disabled by environment configuration",
8107
8306
  network_error: "eligibility could not be verified (network error)",
8307
+ preference: "not enabled for your organization or API gateway",
8308
+ unknown: "currently unavailable",
8108
8309
  };
8310
+ /** Reasons that are never explained:
8311
+ * - `sdk_opt_in_required`: every SDK session starts here (the toggle IS the
8312
+ * opt-in), so it describes the default, not a problem.
8313
+ * - `pending`: eligibility is still resolving; the next report supersedes it. */
8314
+ const FAST_MODE_UNEXPLAINED_REASONS = new Set([
8315
+ "sdk_opt_in_required",
8316
+ "pending",
8317
+ ]);
8318
+ /** The user-facing explanation of a `fast_mode_disabled_reason`: `undefined`
8319
+ * for no reason, `sdk_opt_in_required` or `pending`; the table text when there
8320
+ * is one; else a generic text naming the code (a reason a newer SDK added). */
8321
+ export function explainFastModeDisabledReason(reason) {
8322
+ if (reason === undefined || FAST_MODE_UNEXPLAINED_REASONS.has(reason))
8323
+ return undefined;
8324
+ return FAST_MODE_UNAVAILABLE_EXPLANATIONS[reason] ?? `not available (${reason})`;
8325
+ }
8109
8326
  /** 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. */
8327
+ * a reason {@link explainFastModeDisabledReason} explains (including codes a
8328
+ * newer SDK adds), else `undefined`. State comparisons (see
8329
+ * `syncFastModeState`) then track exactly what the user can see, so
8330
+ * `sdk_opt_in_required` and `pending` never churn the config option. */
8114
8331
  export function normalizeFastModeDisabledReason(reason) {
8115
- return reason && FAST_MODE_UNAVAILABLE_EXPLANATIONS[reason] ? reason : undefined;
8332
+ return explainFastModeDisabledReason(reason) !== undefined ? reason : undefined;
8116
8333
  }
8117
8334
  /** Whether the Client advertised support for boolean session config options
8118
8335
  * (`session.configOptions.boolean`). Agents MUST only send `type: "boolean"`
@@ -8132,9 +8349,7 @@ export function clientSupportsBooleanConfigOptions(clientCapabilities) {
8132
8349
  * stay on. Ignored while enabled: a reason reported alongside an `on`/`cooldown`
8133
8350
  * state isn't blocking anything right now. */
8134
8351
  export function createFastModeConfigOption(enabled, useBooleanOption, disabledReason) {
8135
- const explanation = enabled
8136
- ? undefined
8137
- : disabledReason && FAST_MODE_UNAVAILABLE_EXPLANATIONS[disabledReason];
8352
+ const explanation = enabled ? undefined : explainFastModeDisabledReason(disabledReason);
8138
8353
  const base = {
8139
8354
  id: FAST_MODE_CONFIG_ID,
8140
8355
  name: "Fast mode",
@@ -8660,8 +8875,8 @@ export function applyAvailableModelsAllowlist(sdkModels, allowlist, settingsMode
8660
8875
  * any turn runs in the new process — unlike fresh sessions, where it stalls
8661
8876
  * until the first prompt turn (issues #886/#880) — so the same response that
8662
8877
  * 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
8878
+ * covering post-restart reloads whose window the default would misstate
8879
+ * (issue #596), and the occupancy with it: a thread reloaded carrying 150k of
8665
8880
  * context otherwise reports `used: 0` until its first turn ends, and the
8666
8881
  * client assigns that number to the ring unconditionally. All three come out
8667
8882
  * of ONE response — nothing here adds a control request.
@@ -8917,6 +9132,14 @@ terminalCommands) {
8917
9132
  input: { hint: "checkpoint number (omit to list)" },
8918
9133
  });
8919
9134
  }
9135
+ // `/btw` is answered by the adapter too (§6.8); the SDK lists no such command.
9136
+ if (!advertised.some((command) => command.name === "btw")) {
9137
+ advertised.push({
9138
+ name: "btw",
9139
+ description: "Ask a side question. The answer is not added to the conversation.",
9140
+ input: { hint: "question" },
9141
+ });
9142
+ }
8920
9143
  return advertised;
8921
9144
  }
8922
9145
  function formatUriAsLink(uri) {
@@ -9790,6 +10013,9 @@ export function runAcp(logger) {
9790
10013
  .onRequest(TASKS_OUTPUT_METHOD, { parse: parseTasksOutputRequest }, (ctx) => agent.taskOutput(ctx.params))
9791
10014
  .onRequest(TASKS_BACKGROUND_METHOD, { parse: parseTasksBackgroundRequest }, (ctx) => agent.backgroundTask(ctx.params))
9792
10015
  .onRequest(USAGE_REFRESH_METHOD, { parse: parseUsageRefreshRequest }, (ctx) => agent.refreshUsage(ctx.params))
10016
+ .onRequest(CONTEXT_USAGE_METHOD, { parse: parseContextUsageRequest }, (ctx) => agent.contextUsage(ctx.params))
10017
+ .onRequest(REWIND_METHOD, { parse: parseRewindRequest }, (ctx) => agent.rewind(ctx.params))
10018
+ .onRequest(BTW_METHOD, { parse: parseSideQuestionRequest }, (ctx) => agent.sideQuestion(ctx.params, ctx.signal))
9793
10019
  .onRequest(GOAL_CONTROL_METHOD, { parse: parseGoalRequest }, (ctx) => agent.goal(ctx.params))
9794
10020
  .connect(stream);
9795
10021
  agent = new ClaudeAcpAgent(new ClientConnection(connection.client), logger);
@@ -9802,29 +10028,6 @@ function commonPrefixLength(a, b) {
9802
10028
  }
9803
10029
  return i;
9804
10030
  }
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
10031
  /** Fetch the SDK's authoritative context-window occupancy via the
9829
10032
  * `getContextUsage` control request. Unlike the per-message API usage numbers
9830
10033
  * (which only count message tokens), this `totalTokens` includes the system
@@ -9896,7 +10099,7 @@ const PROVIDER_ROUTING_ENV_VARS = [
9896
10099
  * Header/credential values can be secrets; the key only ever lives as an
9897
10100
  * in-memory Map key and is never logged or surfaced. Over-keying is the safe
9898
10101
  * 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
10102
+ * miss (default seed until the background read or the next result), while under-keying would serve
9900
10103
  * one backend's window for another's. */
9901
10104
  function providerCacheKeyFor(env) {
9902
10105
  return PROVIDER_ROUTING_ENV_VARS.map((name) => env[name] ?? "").join("\0");
@@ -9915,20 +10118,22 @@ function cacheContextWindow(modelKey, window) {
9915
10118
  /** The context window to report *right now* for a model, with NO IPC on the
9916
10119
  * critical path: the cached authoritative value if we've learned it (from a
9917
10120
  * 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. */
10121
+ * else the default. Derives the cache key itself —
10122
+ * `modelInfo?.resolvedModel ?? modelId`, the same rule at every seed site — so
10123
+ * read keys can't drift from the write site's spelling. `authoritative` reports
10124
+ * whether the value came from the cache: an authoritative window can
10125
+ * legitimately equal DEFAULT_CONTEXT_WINDOW, so the value alone can't tell the
10126
+ * caller.
10127
+ *
10128
+ * There is no text heuristic any more (upstream #1613): it only turned the old
10129
+ * 200K default into 1M for a "1m" token in the model's id or description, and
10130
+ * a model's names do not give its window — `sonnet` is 1M, or 200K under
10131
+ * `CLAUDE_CODE_DISABLE_1M_CONTEXT=1`. */
9924
10132
  function immediateContextWindow(providerCacheKey, modelId, modelInfo) {
9925
10133
  const cached = contextWindowCache.get(contextWindowCacheKey(providerCacheKey, modelInfo?.resolvedModel ?? modelId));
9926
10134
  if (cached !== undefined)
9927
10135
  return { size: cached, authoritative: true };
9928
- return {
9929
- size: inferContextWindowFromModel(modelId, modelInfo?.resolvedModel, modelInfo?.displayName, modelInfo?.description) ?? DEFAULT_CONTEXT_WINDOW,
9930
- authoritative: false,
9931
- };
10136
+ return { size: DEFAULT_CONTEXT_WINDOW, authoritative: false };
9932
10137
  }
9933
10138
  function parseModelConfig(raw) {
9934
10139
  if (!raw)
@@ -9966,26 +10171,39 @@ function getMatchingModelUsage(modelUsage, currentModel) {
9966
10171
  }
9967
10172
  /**
9968
10173
  * 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.
10174
+ * the background. The message holds exactly one tool_result, of a Bash call,
10175
+ * and the task is the structured `BashOutput`'s `backgroundTaskId`.
10176
+ *
10177
+ * Upstream #1540: Claude Code sends no `tool_use_result` with a subagent's tool
10178
+ * results (none of 35 across CLI 2.1.293–2.1.318, per upstream). Without one,
10179
+ * the task is the live backgrounded `local_bash` task whose `task_started`
10180
+ * named this Bash call, which comes before the result. A failed result never
10181
+ * names one: the command did not start.
9971
10182
  */
9972
10183
  function backgroundBashTerminal(message, content, session) {
9973
10184
  if (message.type !== "user" || !Array.isArray(content))
9974
10185
  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
10186
  const blocks = content.filter((c) => typeof c === "object" && c !== null && c.type === "tool_result");
9983
10187
  if (blocks.length !== 1)
9984
10188
  return undefined;
9985
10189
  const toolCallId = blocks[0].tool_use_id;
9986
10190
  if (session.toolUseCache[toolCallId]?.name !== "Bash")
9987
10191
  return undefined;
9988
- return { taskId, toolCallId };
10192
+ const result = message.tool_use_result;
10193
+ if (typeof result === "object" && result !== null && "backgroundTaskId" in result) {
10194
+ const taskId = result.backgroundTaskId;
10195
+ return typeof taskId === "string" && taskId !== "" ? { taskId, toolCallId } : undefined;
10196
+ }
10197
+ if (result !== undefined || blocks[0].is_error === true)
10198
+ return undefined;
10199
+ for (const [taskId, task] of session.liveBackgroundTasks) {
10200
+ if (task.parentToolUseId === toolCallId &&
10201
+ task.taskType === "local_bash" &&
10202
+ task.backgrounded) {
10203
+ return { taskId, toolCallId };
10204
+ }
10205
+ }
10206
+ return undefined;
9989
10207
  }
9990
10208
  /**
9991
10209
  * Drops `terminal_exit` from the tool result update of `toolCallId`: the Bash