@lucascouts/claude-agent-tui 0.14.13 → 0.15.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.
@@ -15,6 +15,7 @@ import type { ListSubagents, GetSubagentMessages } from "./subagent-source.js";
15
15
  import { type SidechainToolUse } from "./subagent-gate.js";
16
16
  import type { SubagentWatcher } from "./subagent-watcher.js";
17
17
  import type { DetectorSchedule, EndOfTurnDetector } from "./end-of-turn.js";
18
+ import { type SupportedModelsSource } from "./live-model-catalog.js";
18
19
  import { type AgentCatalogEntry } from "./agent-catalog.js";
19
20
  import type { SessionGate, SessionGateOptions } from "./permissions/gate-wiring.js";
20
21
  export declare const CLAUDE_CONFIG_DIR: string;
@@ -169,12 +170,28 @@ type Session = {
169
170
  */
170
171
  pendingEffortInjection?: string;
171
172
  /**
172
- * Story 060 (R2.1/R2.2) — true WHILE the "ultracode" effort-selector sentinel is selected for this
173
- * session. The LIVE activation it drives is a keyword prefix on the OUTGOING prompt (the binary's
174
- * documented per-turn Workflow opt-in) — Option A, no re-spawn. Cleared when a real effort level (or
175
- * `default`) is re-selected. The declarative spawn-time complement is {@link applyUltracodeSettings}.
173
+ * Item 84 — the user's Ultracode intent for this session (default off), set by
174
+ * {@link applyUltracodeChange} and cleared when the CLI refuses it. It survives a model switch: the
175
+ * option hides on a model that cannot run Ultracode and shows again, still on, when switching back —
176
+ * the CLI keeps the request the same way. Independent of the effort level.
176
177
  */
177
- ultracodeActive?: boolean;
178
+ ultracodeOn?: boolean;
179
+ /**
180
+ * Item 84 — the CLI's reason for refusing the last `/effort ultracode on`, shown in the option's
181
+ * description. `scope: "model"` (the model cannot run it) is cleared by a model switch;
182
+ * `scope: "workflows"` (dynamic workflows are disabled) is not, because a switch does not change it.
183
+ */
184
+ ultracodeRefusal?: {
185
+ scope: "model" | "workflows";
186
+ reason: string;
187
+ };
188
+ /**
189
+ * Item 84 — a `/effort ultracode on|off` requested WHILE a turn is in flight is deferred here
190
+ * (last-write-wins) and flushed once the turn settles (mirrors {@link pendingEffortInjection}).
191
+ */
192
+ pendingUltracodeInjection?: boolean;
193
+ /** Item 84 — stops the reply watch of the last `/effort ultracode on`, while one is running. */
194
+ ultracodeReplyStop?: () => void;
178
195
  /**
179
196
  * Story 073 (R2.3/R3.2) — the session's CURRENT fast-mode on/off state (default off). Set by
180
197
  * {@link applyFastModeChange} and read by {@link buildConfigOptions} for the `fast` option's
@@ -511,6 +528,12 @@ export interface AgentDeps {
511
528
  * `true`/`false` to exercise the toggle's advertise/apply/reconcile paths hermetically.
512
529
  */
513
530
  fastModeProbe?: FastModeProbe;
531
+ /**
532
+ * Item 93 — override where `createSession` reads the model picker from (default: the PATH `claude`'s
533
+ * `supportedModels()`, see live-model-catalog.ts). Tests inject a fixed catalogue so they assert this
534
+ * adapter's behaviour, not whatever the host CLI serves that day.
535
+ */
536
+ modelCatalogSource?: SupportedModelsSource;
514
537
  }
515
538
  /**
516
539
  * Production default for the {@link StartEngine} seam. Spawns the subscription `claude` TUI under a
@@ -699,6 +722,8 @@ export declare class ClaudeAcpAgent implements Agent {
699
722
  private readonly getSessionInfo;
700
723
  /** Story 073 (R1) — fast-mode availability probe seam; see {@link AgentDeps.fastModeProbe}. */
701
724
  private readonly fastModeProbe;
725
+ /** Item 93 — model-picker source seam; see {@link AgentDeps.modelCatalogSource}. */
726
+ private readonly modelCatalogSource;
702
727
  /** Live PTY-engine registry shared with the per-session engines (story 014 cleanup map). */
703
728
  private readonly engines;
704
729
  constructor(client: AgentSideConnection, logger?: Logger, engine?: Engine, deps?: AgentDeps);
@@ -814,24 +839,31 @@ export declare class ClaudeAcpAgent implements Agent {
814
839
  private currentEffort;
815
840
  /** Story 056 — the session's current agent configOption value (undefined when no agent option). */
816
841
  private currentAgent;
842
+ /** Item 84 — the session's current model configOption value (`default` when absent). */
843
+ private currentModel;
817
844
  /**
818
- * Story 060 (R2/R3.2) — apply an effort-selector choice, special-casing the `ultracode` sentinel.
819
- *
820
- * Selecting `ultracode` (Option A — keyword + scratch, NO re-spawn): activate the session flag (which
821
- * makes {@link prompt} prefix the OUTGOING prompt with the `ultracode` keyword — the binary's per-turn
822
- * Workflow opt-in, the effective live mechanism), write the scratch ultracode keys via
823
- * {@link applyUltracodeSettings} (the declarative spawn-time complement), and set the effort to xhigh
824
- * through the SAME live `/effort` inject as every other level — NEVER `/effort ultracode` (R1.2). The
825
- * `already` guard suppresses a redundant `/effort xhigh` re-inject when ultracode is re-selected while
826
- * already active.
827
- *
828
- * Selecting a real level (or `default`) DEACTIVATES ultracode: clear the flag, remove the scratch keys,
829
- * then apply that level through {@link applyEffortChange} (whose own no-op guard handles a same-level
830
- * pick). `applyConfigOptionValue` (the caller, after this returns) commits the selector's currentValue,
831
- * which for `ultracode` correctly stays `"ultracode"` (the {@link buildConfigOptions} `includes` guard
832
- * keeps it valid across rebuilds).
845
+ * Item 84 — turn the Ultracode switch on or off, LIVE via `/effort ultracode on|off` through the
846
+ * session's terminal, exactly as {@link applyFastModeChange} drives `/fast`: no re-spawn, no turn,
847
+ * works before the first prompt, deferred while a turn is in flight. Turning it on clears a previous
848
+ * refusal (the user is retrying). The scratch settings mirror the intent so a re-spawn keeps it.
849
+ * A no-op change sends nothing.
850
+ */
851
+ private applyUltracodeChange;
852
+ /** Item 84 — keep `ultracode:true` in the scratch `--settings` file only while the switch is on. */
853
+ private mirrorUltracodeIntoScratch;
854
+ /**
855
+ * Item 84 — side-channel `/effort ultracode on|off` write (synchronous, never a turn; `/effort`
856
+ * applies inline, no confirmation panel). After an `on`, watch the terminal for a bounded window
857
+ * for the CLI's answer: one of its two refusals turns the switch back off with the reason
858
+ * ({@link handleUltracodeRefusal}); its confirmation, or silence, ends the watch.
859
+ */
860
+ private injectUltracodeCommand;
861
+ private watchUltracodeReply;
862
+ /**
863
+ * Item 84 — the CLI refused `/effort ultracode on`: the switch goes back off, the reason is kept for
864
+ * the option's description, the scratch key is removed, and the client gets the new options.
833
865
  */
834
- private applyEffortSelection;
866
+ private handleUltracodeRefusal;
835
867
  /**
836
868
  * Story 046 (R2.2) + Story 056 v4 — apply a reasoning-effort change LIVE via `/effort <level>`.
837
869
  * SUPERSEDES the 046 Probe-B re-spawn: `claude` 2.1.195 DOES have a live `/effort <level>` local TUI
@@ -1082,7 +1114,7 @@ export declare function inferContextWindowFromModel(model: string): number | nul
1082
1114
  * field), used by the pump to refine the alias seed once the model is known. Exact-ID lookup first
1083
1115
  * (MODEL_ID_CONTEXT_WINDOWS), then a family+version heuristic for dated snapshots / future variants
1084
1116
  * (Opus is NOT uniform: 4.6 and earlier = 200K, 4.7+ = 1M; Sonnet 4.x = 200K but Sonnet 5+ = 1M;
1085
- * haiku = 200K; fable = 1M — story 071), then a
1117
+ * Haiku 4.x = 200K but Haiku 5+ = 1M — item 93; fable = 1M — story 071), then a
1086
1118
  * `\b1m\b` suffix, then null (R1.3: a missing / non-string id never refines). */
1087
1119
  export declare function inferContextWindowFromModelId(id: string): number | null;
1088
1120
  export {};
package/dist/acp-agent.js CHANGED
@@ -25,11 +25,11 @@ import { guardEvent } from "./billing/entrypoint-guard.js";
25
25
  import { usageUpdatesFor } from "./usage.js";
26
26
  import { createTurnResolver } from "./end-of-turn.js";
27
27
  import { sendPrompt } from "./engine-pty.js";
28
- import { MODEL_CONTEXT_WINDOWS, MODEL_ID_CONTEXT_WINDOWS, modelSelectorDescription, DEFAULT_MODEL_INFO, resolveCatalogValueFromModelId, isFastModeCapableModel, classifyFastModeSignal, FAST_MODE_CONFIG_ID, FAST_MODE_ON, FAST_MODE_OFF, createFastModeConfigOption, clientSupportsBooleanConfigOptions, resolveFastModeEnabled, ULTRACODE_EFFORT, ULTRACODE_EFFORT_LEVEL, ULTRACODE_EFFORT_LABEL, } from "./model-catalog.js";
28
+ import { MODEL_CONTEXT_WINDOWS, MODEL_ID_CONTEXT_WINDOWS, modelSelectorDescription, DEFAULT_MODEL_INFO, resolveCatalogValueFromModelId, isFastModeCapableModel, classifyFastModeSignal, FAST_MODE_CONFIG_ID, FAST_MODE_ON, FAST_MODE_OFF, createFastModeConfigOption, clientSupportsBooleanConfigOptions, resolveFastModeEnabled, ULTRACODE_CONFIG_ID, ultracodeCommand, isUltracodeCapableModel, resolveUltracodeEnabled, createUltracodeConfigOption, classifyUltracodeReply, } from "./model-catalog.js";
29
29
  import { resolveModelCatalog } from "./live-model-catalog.js";
30
- // Story 060 (R2.2/R2.3/R3.2) — the declarative spawn-time complement to the live ultracode keyword:
31
- // toggle the {ultracode,ultracodeKeywordTrigger} keys in the gate's per-session scratch settings file
32
- // (preserving the hook + every other key). Lives in the gate's settings-writer so it reuses durableWrite.
30
+ // Item 84 — mirror the Ultracode switch into the gate's per-session scratch settings file as
31
+ // `ultracode:true`, so a re-spawn of this session keeps it (`/effort ultracode on` is session-scoped
32
+ // and a fresh PTY would not have it). Lives in the gate's settings-writer so it reuses durableWrite.
33
33
  import { applyUltracodeSettings } from "./gate/settings-writer.js";
34
34
  import { discoverAgents } from "./agent-catalog.js";
35
35
  // Story 063 (R1) — OFFLINE disk discovery of the `available_commands` set (custom slash-commands +
@@ -662,6 +662,10 @@ const MODE_CYCLE_POLL_MS = 50;
662
662
  * late Enter still lands while an early (pre-render) one would be lost. 800 ms validated headless
663
663
  * (experiments/probe-c-model-then-prompt.mjs: the dialog rendered + the switch applied within it). */
664
664
  const MODEL_CONFIRM_DELAY_MS = 800;
665
+ /** Item 84 — how long to watch the terminal for the CLI's answer to `/effort ultracode on`. */
666
+ const ULTRACODE_REPLY_WINDOW_MS = 5000;
667
+ /** Item 84 — the tail of terminal output kept while watching for that answer. */
668
+ const ULTRACODE_REPLY_BUFFER_CHARS = 8192;
665
669
  /**
666
670
  * Builds the label for the "Always Allow" permission option so the user can see
667
671
  * the exact scope they are committing to. Uses the SDK-provided suggestions
@@ -782,6 +786,7 @@ export class ClaudeAcpAgent {
782
786
  this.engine = engine;
783
787
  this.startEngine = deps.startEngine ?? defaultStartEngine;
784
788
  this.fastModeProbe = deps.fastModeProbe ?? defaultFastModeProbe;
789
+ this.modelCatalogSource = deps.modelCatalogSource;
785
790
  // Story 043 (R2.1): when liveDiff is ON, the live JSONL reader is the diff-enriched reader
786
791
  // (getSessionMessages + uuid→toolUseResult hydration), which restores the story-021 Edit/Write
787
792
  // diff on BOTH the live pump and the session/load replay (both read this.getMessages once). The
@@ -1092,11 +1097,9 @@ export class ClaudeAcpAgent {
1092
1097
  // future promptToClaude were to throw mid-materialize, the teardown cleanup still reaches the paths.
1093
1098
  sessionRecord.turnTempImagePaths = turnTempImagePaths;
1094
1099
  const payload = promptToClaude(params, this.logger, turnTempImagePaths);
1095
- // Story 060 (R2.2) — while ultracode is active, prefix the OUTGOING prompt with the `ultracode`
1096
- // keyword (the binary's per-turn Workflow opt-in). This is the LIVE activation that needs no
1097
- // re-spawn (Option A) and works pre- AND post-first-interaction; the scratch settings keys are the
1098
- // declarative spawn-time complement. NEVER emitted as a `/effort` value (R1.2).
1099
- const outgoing = sessionRecord.ultracodeActive ? `${ULTRACODE_EFFORT} ${payload}` : payload;
1100
+ // Item 84: the prompt goes out as typed. Ultracode is a session switch the CLI holds
1101
+ // (`/effort ultracode on`), not a keyword prepended to every prompt.
1102
+ const outgoing = payload;
1100
1103
  // (2) Register the turn with the story-024 resolver: the detector that the live pump feeds, and
1101
1104
  // the awaitable that settles ONCE with { stopReason: mapStopReason(...) } on the terminal
1102
1105
  // boundary (or rejects on the watchdog). One shared `schedule` drives sendPrompt + the resolver.
@@ -1144,7 +1147,7 @@ export class ClaudeAcpAgent {
1144
1147
  sessionRecord.subagentWatcher?.stop();
1145
1148
  sessionRecord.subagentWatcher = undefined;
1146
1149
  // Story 046 (R1.3): the session is idle again — flush any model switch deferred mid-turn.
1147
- this.flushPendingControlInjections(sessionRecord);
1150
+ this.flushPendingControlInjections(params.sessionId, sessionRecord);
1148
1151
  }
1149
1152
  }
1150
1153
  // ─── Task 3.2 (R5.2, R5.3) — the session title, and what this port does NOT deliver ──────────
@@ -1363,6 +1366,17 @@ export class ClaudeAcpAgent {
1363
1366
  : o);
1364
1367
  return { configOptions: session.configOptions };
1365
1368
  }
1369
+ // Item 84: the `ultracode` switch, same shape as `fast` above — a boolean payload bypasses the
1370
+ // string-only validation below; the on/off string of the select fallback goes through it.
1371
+ if (params.configId === ULTRACODE_CONFIG_ID && typeof params.value === "boolean") {
1372
+ const option = session.configOptions.find((o) => o.id === ULTRACODE_CONFIG_ID);
1373
+ if (!option) {
1374
+ throw new Error(`Unknown config option: ${params.configId}`);
1375
+ }
1376
+ await this.applyUltracodeChange(params.sessionId, session, params.value);
1377
+ session.configOptions = this.rebuildConfigOptionsPreserving(session, this.currentModel(session));
1378
+ return { configOptions: session.configOptions };
1379
+ }
1366
1380
  if (typeof params.value !== "string") {
1367
1381
  throw new Error(`Invalid value for config option ${params.configId}: ${params.value}`);
1368
1382
  }
@@ -1434,9 +1448,9 @@ export class ClaudeAcpAgent {
1434
1448
  // mirroring /model — no re-spawn, works before the first interaction. Mid-turn it defers; it never
1435
1449
  // throws, so applyConfigOptionValue below always commits the new currentValue (optimistic, like
1436
1450
  // /model). The flag path stays only to seed/preserve effort across mode/agent re-spawns.
1437
- // Story 060 (R2/R3.2): route through applyEffortSelection so the `ultracode` sentinel is
1438
- // special-cased (activate keyword + scratch keys + /effort xhigh) while real levels deselect it.
1439
- await this.applyEffortSelection(session, resolvedValue);
1451
+ // Item 84: Ultracode is no longer an effort value, and an effort change leaves it alone (the
1452
+ // CLI keeps it "at any effort level").
1453
+ this.applyEffortChange(session, resolvedValue);
1440
1454
  }
1441
1455
  else if (params.configId === "agent") {
1442
1456
  // Story 056 (R3.3/R3.4): the agent persona has no live mid-session path either — apply it by an
@@ -1451,6 +1465,12 @@ export class ClaudeAcpAgent {
1451
1465
  // path; a boolean payload is resolved earlier (story 074, R4.3). resolveFastModeEnabled unifies both.
1452
1466
  this.applyFastModeChange(session, resolveFastModeEnabled(resolvedValue));
1453
1467
  }
1468
+ else if (params.configId === ULTRACODE_CONFIG_ID) {
1469
+ // Item 84 — the on/off select fallback of the Ultracode switch.
1470
+ await this.applyUltracodeChange(params.sessionId, session, resolveUltracodeEnabled(resolvedValue));
1471
+ session.configOptions = this.rebuildConfigOptionsPreserving(session, this.currentModel(session));
1472
+ return { configOptions: session.configOptions };
1473
+ }
1454
1474
  await this.applyConfigOptionValue(params.sessionId, session, params.configId, resolvedValue);
1455
1475
  return { configOptions: session.configOptions };
1456
1476
  }
@@ -1551,7 +1571,7 @@ export class ClaudeAcpAgent {
1551
1571
  * prompt()'s finally, the moment the turn settles). Last-write-wins: only the most recent queued
1552
1572
  * alias is injected; the field is cleared so a settled session with nothing queued injects nothing.
1553
1573
  */
1554
- flushPendingControlInjections(session) {
1574
+ flushPendingControlInjections(sessionId, session) {
1555
1575
  if (session.turnDetector !== undefined)
1556
1576
  return; // still not idle (defensive)
1557
1577
  const alias = session.pendingModelInjection;
@@ -1571,6 +1591,12 @@ export class ClaudeAcpAgent {
1571
1591
  session.pendingFastInjection = undefined;
1572
1592
  this.injectFastCommand(session, fast);
1573
1593
  }
1594
+ // Item 84 — flush a deferred `/effort ultracode on|off` too (last-write-wins).
1595
+ const ultracode = session.pendingUltracodeInjection;
1596
+ if (ultracode !== undefined) {
1597
+ session.pendingUltracodeInjection = undefined;
1598
+ this.injectUltracodeCommand(sessionId, session, ultracode);
1599
+ }
1574
1600
  }
1575
1601
  /**
1576
1602
  * Story 046 (R3.3, design §6b) — drive the TUI to `target` with closed-loop raw Shift+Tab. Writes
@@ -1657,14 +1683,9 @@ export class ClaudeAcpAgent {
1657
1683
  // does not reset the others — the argv carries all three flags. There are three selectors now
1658
1684
  // (Story 056 added agent): a mode re-spawn keeps effort+agent, an agent re-spawn keeps mode+effort.
1659
1685
  const permissionMode = change.permissionMode ?? session.modes.currentModeId;
1660
- // Story 060 (R1.2 fix): the preserved currentEffort can be the `ultracode` SENTINEL (it is the
1661
- // committed configOption value while active). It is NOT a real `--effort` enum value — the binary
1662
- // rejects `--effort ultracode` (story-060 probe), so a mode/agent re-spawn-while-active would
1663
- // silently degrade effort to default. Map the sentinel to its real component (xhigh) at THIS spawn
1664
- // seam (it feeds BOTH buildClaudeCmd and buildResumeArgv); the scratch `ultracode:true` already
1665
- // carries the orchestration activation declaratively at spawn.
1666
- const preservedEffort = change.effortLevel ?? this.currentEffort(session);
1667
- const effortLevel = preservedEffort === ULTRACODE_EFFORT ? ULTRACODE_EFFORT_LEVEL : preservedEffort;
1686
+ // Item 84: Ultracode is not an effort value any more, so the effort carries over as is; the
1687
+ // Ultracode switch reaches the new PTY through the scratch settings' `ultracode:true`.
1688
+ const effortLevel = change.effortLevel ?? this.currentEffort(session);
1668
1689
  const agent = change.agent ?? this.currentAgent(session);
1669
1690
  // Story 057 (R2.4): REGENERATE the MCP scratch so the re-spawned `claude` reads the CURRENT MCP
1670
1691
  // config at startup (its `--mcp-config` is bound only at spawn). Re-translate from the stored raw
@@ -1733,52 +1754,108 @@ export class ClaudeAcpAgent {
1733
1754
  const opt = session.configOptions.find((o) => o.id === "agent");
1734
1755
  return typeof opt?.currentValue === "string" ? opt.currentValue : undefined;
1735
1756
  }
1757
+ /** Item 84 — the session's current model configOption value (`default` when absent). */
1758
+ currentModel(session) {
1759
+ const opt = session.configOptions.find((o) => o.id === "model");
1760
+ return typeof opt?.currentValue === "string" ? opt.currentValue : DEFAULT_MODEL_INFO.value;
1761
+ }
1736
1762
  /**
1737
- * Story 060 (R2/R3.2) — apply an effort-selector choice, special-casing the `ultracode` sentinel.
1738
- *
1739
- * Selecting `ultracode` (Option A — keyword + scratch, NO re-spawn): activate the session flag (which
1740
- * makes {@link prompt} prefix the OUTGOING prompt with the `ultracode` keyword — the binary's per-turn
1741
- * Workflow opt-in, the effective live mechanism), write the scratch ultracode keys via
1742
- * {@link applyUltracodeSettings} (the declarative spawn-time complement), and set the effort to xhigh
1743
- * through the SAME live `/effort` inject as every other level — NEVER `/effort ultracode` (R1.2). The
1744
- * `already` guard suppresses a redundant `/effort xhigh` re-inject when ultracode is re-selected while
1745
- * already active.
1746
- *
1747
- * Selecting a real level (or `default`) DEACTIVATES ultracode: clear the flag, remove the scratch keys,
1748
- * then apply that level through {@link applyEffortChange} (whose own no-op guard handles a same-level
1749
- * pick). `applyConfigOptionValue` (the caller, after this returns) commits the selector's currentValue,
1750
- * which for `ultracode` correctly stays `"ultracode"` (the {@link buildConfigOptions} `includes` guard
1751
- * keeps it valid across rebuilds).
1763
+ * Item 84 — turn the Ultracode switch on or off, LIVE via `/effort ultracode on|off` through the
1764
+ * session's terminal, exactly as {@link applyFastModeChange} drives `/fast`: no re-spawn, no turn,
1765
+ * works before the first prompt, deferred while a turn is in flight. Turning it on clears a previous
1766
+ * refusal (the user is retrying). The scratch settings mirror the intent so a re-spawn keeps it.
1767
+ * A no-op change sends nothing.
1752
1768
  */
1753
- async applyEffortSelection(session, value) {
1754
- if (value === ULTRACODE_EFFORT) {
1755
- const already = session.ultracodeActive === true;
1756
- session.ultracodeActive = true;
1757
- // The gate's per-session SCRATCH settings file is the spawn's `--settings` target; on a live
1758
- // Session it is reachable via `session.gate?.settingsPath` (the value createSession also threads
1759
- // into StartEngineArgs.settingsFile). Absent on a no-gate / resume / replay session → keyword-only.
1760
- const scratchPath = session.gate?.settingsPath;
1761
- if (scratchPath) {
1762
- // Declarative scratch keys for any future (re-)spawn (NOT a re-spawn trigger — Option A).
1763
- await applyUltracodeSettings(scratchPath, true);
1764
- }
1765
- // Effort component is xhigh, applied via the live /effort inject — but only when not already active
1766
- // (re-selecting ultracode must not re-inject `/effort xhigh`). applyEffortChange's own no-op guard
1767
- // also short-circuits if xhigh already equals the current effort.
1768
- if (!already) {
1769
- this.applyEffortChange(session, ULTRACODE_EFFORT_LEVEL);
1770
- }
1769
+ async applyUltracodeChange(sessionId, session, enabled) {
1770
+ if (enabled)
1771
+ session.ultracodeRefusal = undefined;
1772
+ if (enabled === (session.ultracodeOn ?? false))
1773
+ return;
1774
+ session.ultracodeOn = enabled;
1775
+ await this.mirrorUltracodeIntoScratch(session, enabled);
1776
+ if (session.turnDetector !== undefined) {
1777
+ // A turn is in flight — injecting mid-turn corrupts the PTY input. Defer (mirrors /effort).
1778
+ session.pendingUltracodeInjection = enabled;
1771
1779
  return;
1772
1780
  }
1773
- // A real level (or `default`) was chosen → deactivate ultracode before applying it.
1774
- if (session.ultracodeActive) {
1775
- session.ultracodeActive = false;
1776
- const scratchPath = session.gate?.settingsPath;
1777
- if (scratchPath) {
1778
- await applyUltracodeSettings(scratchPath, false);
1779
- }
1781
+ this.injectUltracodeCommand(sessionId, session, enabled);
1782
+ }
1783
+ /** Item 84 — keep `ultracode:true` in the scratch `--settings` file only while the switch is on. */
1784
+ async mirrorUltracodeIntoScratch(session, enabled) {
1785
+ const scratchPath = session.gate?.settingsPath;
1786
+ if (!scratchPath)
1787
+ return; // no gate (resume/replay/test) → nothing to keep in sync
1788
+ try {
1789
+ await applyUltracodeSettings(scratchPath, enabled);
1790
+ }
1791
+ catch (err) {
1792
+ // Degraded, not fatal: the live command still applies; only a later re-spawn would miss it.
1793
+ this.logger.error(`[ultracode] event=scratch_write_failed enabled=${enabled} path=${scratchPath}: ${String(err)}`);
1780
1794
  }
1781
- this.applyEffortChange(session, value);
1795
+ }
1796
+ /**
1797
+ * Item 84 — side-channel `/effort ultracode on|off` write (synchronous, never a turn; `/effort`
1798
+ * applies inline, no confirmation panel). After an `on`, watch the terminal for a bounded window
1799
+ * for the CLI's answer: one of its two refusals turns the switch back off with the reason
1800
+ * ({@link handleUltracodeRefusal}); its confirmation, or silence, ends the watch.
1801
+ */
1802
+ injectUltracodeCommand(sessionId, session, on) {
1803
+ session.ultracodeReplyStop?.();
1804
+ session.ultracodeReplyStop = undefined;
1805
+ if (on)
1806
+ this.watchUltracodeReply(sessionId, session);
1807
+ sendPrompt(session.pty, ultracodeCommand(on), (fn) => fn());
1808
+ }
1809
+ watchUltracodeReply(sessionId, session) {
1810
+ let buffer = "";
1811
+ let done = false;
1812
+ const subscription = session.pty.onData((chunk) => {
1813
+ if (done)
1814
+ return;
1815
+ // Bounded: the reply is one short line; never let a chatty PTY grow this without limit.
1816
+ buffer = (buffer + chunk).slice(-ULTRACODE_REPLY_BUFFER_CHARS);
1817
+ const reply = classifyUltracodeReply(buffer);
1818
+ if (reply.kind === "pending")
1819
+ return;
1820
+ stop();
1821
+ if (reply.kind === "refused") {
1822
+ this.handleUltracodeRefusal(sessionId, session, reply.reason).catch((err) => this.logger.error(`[ultracode] event=refusal_handling_failed sessionId=${sessionId}: ${String(err)}`));
1823
+ }
1824
+ });
1825
+ // `onData` never fires synchronously, so `cancelTimer` is always assigned before `stop` runs.
1826
+ const stop = () => {
1827
+ if (done)
1828
+ return;
1829
+ done = true;
1830
+ subscription.dispose();
1831
+ cancelTimer();
1832
+ if (session.ultracodeReplyStop === stop)
1833
+ session.ultracodeReplyStop = undefined;
1834
+ };
1835
+ const cancelTimer = this.schedule(stop, ULTRACODE_REPLY_WINDOW_MS);
1836
+ session.ultracodeReplyStop = stop;
1837
+ }
1838
+ /**
1839
+ * Item 84 — the CLI refused `/effort ultracode on`: the switch goes back off, the reason is kept for
1840
+ * the option's description, the scratch key is removed, and the client gets the new options.
1841
+ */
1842
+ async handleUltracodeRefusal(sessionId, session, reason) {
1843
+ session.ultracodeOn = false;
1844
+ session.pendingUltracodeInjection = undefined;
1845
+ session.ultracodeRefusal = {
1846
+ scope: /dynamic workflows/i.test(reason) ? "workflows" : "model",
1847
+ reason,
1848
+ };
1849
+ // WARN-level by meaning (degraded, recovered by switching off); this logger has no warn.
1850
+ this.logger.log(`[ultracode] event=refused sessionId=${sessionId} reason="${reason}"`);
1851
+ await this.mirrorUltracodeIntoScratch(session, false);
1852
+ if (!this.sessions[sessionId])
1853
+ return; // torn down meanwhile
1854
+ session.configOptions = this.rebuildConfigOptionsPreserving(session, this.currentModel(session));
1855
+ await this.client.sessionUpdate({
1856
+ sessionId,
1857
+ update: { sessionUpdate: "config_option_update", configOptions: session.configOptions },
1858
+ });
1782
1859
  }
1783
1860
  /**
1784
1861
  * Story 046 (R2.2) + Story 056 v4 — apply a reasoning-effort change LIVE via `/effort <level>`.
@@ -1886,7 +1963,7 @@ export class ClaudeAcpAgent {
1886
1963
  const currentEffort = typeof effortOpt?.currentValue === "string" ? effortOpt.currentValue : undefined;
1887
1964
  const agentOpt = session.configOptions.find((o) => o.id === "agent");
1888
1965
  const currentAgent = typeof agentOpt?.currentValue === "string" ? agentOpt.currentValue : undefined;
1889
- return buildConfigOptions(session.modes, modelId, session.modelInfos, currentEffort, session.agents ?? [], currentAgent, session.fastModeAvailable ?? false, session.fastModeOn ?? false, clientSupportsBooleanConfigOptions(this.clientCapabilities));
1966
+ return buildConfigOptions(session.modes, modelId, session.modelInfos, currentEffort, session.agents ?? [], currentAgent, session.fastModeAvailable ?? false, session.fastModeOn ?? false, clientSupportsBooleanConfigOptions(this.clientCapabilities), { on: session.ultracodeOn ?? false, refusal: session.ultracodeRefusal?.reason });
1890
1967
  }
1891
1968
  /**
1892
1969
  * Story 056 (R3.3/R3.4) — apply a main-thread agent-persona change. Like effort, the persona has no
@@ -2501,8 +2578,12 @@ export class ClaudeAcpAgent {
2501
2578
  if (previousModelId !== value) {
2502
2579
  session.fastModeOn = false;
2503
2580
  session.fastModeAvailable = false;
2581
+ // Item 84 — Ultracode's intent survives the switch (the option just hides on a model that
2582
+ // cannot run it); a refusal about the OLD model no longer applies.
2583
+ if (session.ultracodeRefusal?.scope === "model")
2584
+ session.ultracodeRefusal = undefined;
2504
2585
  }
2505
- session.configOptions = buildConfigOptions(session.modes, value, session.modelInfos, currentEffort, session.agents ?? [], currentAgent, session.fastModeAvailable ?? false, session.fastModeOn ?? false, clientSupportsBooleanConfigOptions(this.clientCapabilities));
2586
+ session.configOptions = buildConfigOptions(session.modes, value, session.modelInfos, currentEffort, session.agents ?? [], currentAgent, session.fastModeAvailable ?? false, session.fastModeOn ?? false, clientSupportsBooleanConfigOptions(this.clientCapabilities), { on: session.ultracodeOn ?? false, refusal: session.ultracodeRefusal?.reason });
2506
2587
  // Story 073 (R4.2) — on a switch TO an Opus model, re-run availability detection out of band and
2507
2588
  // re-advertise the toggle (as off) when available. Fire-and-forget: the synchronous response above
2508
2589
  // ships without the toggle; refreshFastMode emits a follow-up config_option_update once it settles.
@@ -2733,7 +2814,7 @@ export class ClaudeAcpAgent {
2733
2814
  // written down goes stale silently. Falls back to the static MODEL_CATALOG on
2734
2815
  // any failure — see live-model-catalog.ts. `default` is present in both, which
2735
2816
  // is why the seed below can stay a constant.
2736
- const liveModelCatalog = await resolveModelCatalog(this.logger);
2817
+ const liveModelCatalog = await resolveModelCatalog(this.logger, this.modelCatalogSource);
2737
2818
  const availableModes = buildAvailableModes(DEFAULT_MODEL_INFO, allowBypass);
2738
2819
  const modes = {
2739
2820
  currentModeId: seededMode,
@@ -2745,7 +2826,9 @@ export class ClaudeAcpAgent {
2745
2826
  // is stored on the session record below so the model-change reconcile rebuilds it WITHOUT
2746
2827
  // re-globbing.
2747
2828
  const agents = this.discoverAgents(params.cwd);
2748
- const configOptions = buildConfigOptions(modes, DEFAULT_MODEL_INFO.value, liveModelCatalog, settingsManager.getSettings().effortLevel, agents, undefined);
2829
+ const configOptions = buildConfigOptions(modes, DEFAULT_MODEL_INFO.value, liveModelCatalog, settingsManager.getSettings().effortLevel, agents, undefined, false, false,
2830
+ // Item 84: the Ultracode switch shows from the first options, so negotiate its type here.
2831
+ clientSupportsBooleanConfigOptions(this.clientCapabilities));
2749
2832
  // Runtime cwd is read from inside the JSONL (story 015); fall back to the requested host cwd
2750
2833
  // until the first transcript line carries `.cwd` (the seam may return cwd === undefined early).
2751
2834
  const runtimeCwd = started.cwd ?? params.cwd;
@@ -2864,7 +2947,7 @@ function buildAvailableModes(modelInfo, allowBypass) {
2864
2947
  // `applyFlagSettings` in @anthropic-ai/claude-agent-sdk. Mapping both the
2865
2948
  // `"default"` sentinel and `undefined` (effort option absent for the model) to
2866
2949
  // `null` ensures any previously-applied flag is actually cleared.
2867
- function buildConfigOptions(modes, currentModelId, modelInfos, currentEffortLevel, agents = [], currentAgent, fastAvailable = false, currentFast = false, fastUsesBooleanOption = false) {
2950
+ function buildConfigOptions(modes, currentModelId, modelInfos, currentEffortLevel, agents = [], currentAgent, fastAvailable = false, currentFast = false, fastUsesBooleanOption = false, ultracode = { on: false }) {
2868
2951
  const options = [
2869
2952
  {
2870
2953
  id: "mode",
@@ -2924,13 +3007,8 @@ function buildConfigOptions(modes, currentModelId, modelInfos, currentEffortLeve
2924
3007
  .map((part) => (part ? part.charAt(0).toUpperCase() + part.slice(1) : part))
2925
3008
  .join(" "),
2926
3009
  })),
2927
- // Story 060 (R1.1) — the "ultracode" sentinel, LAST and after the five real levels. NOT a real
2928
- // `--effort` value (claude rejects `--effort ultracode`); it maps to xhigh + orchestration (Task 3).
2929
- { value: ULTRACODE_EFFORT, name: ULTRACODE_EFFORT_LABEL },
2930
3010
  ];
2931
- // `ultracode` is a valid current value so a configOptions rebuild (e.g. after a re-spawn) does not
2932
- // reset a selected ultracode back to "default". It stays OUT of supportedLevels (real --effort enum).
2933
- const includes = (l) => l === "default" || l === ULTRACODE_EFFORT || supportedLevels.includes(l);
3011
+ const includes = (l) => l === "default" || supportedLevels.includes(l);
2934
3012
  const validEffort = currentEffortLevel && includes(currentEffortLevel) ? currentEffortLevel : "default";
2935
3013
  options.push({
2936
3014
  id: "effort",
@@ -2942,6 +3020,12 @@ function buildConfigOptions(modes, currentModelId, modelInfos, currentEffortLeve
2942
3020
  options: effortOptions,
2943
3021
  });
2944
3022
  }
3023
+ // Item 84 — the Ultracode switch, right after effort and only on a model that can run it (xhigh).
3024
+ // Same boolean-or-select negotiation as fast mode. Hidden, not cleared, on other models: the
3025
+ // session keeps the intent and the switch reappears, still on, on a capable model.
3026
+ if (isUltracodeCapableModel(currentModelInfo)) {
3027
+ options.push(createUltracodeConfigOption(ultracode.on, fastUsesBooleanOption, ultracode.refusal));
3028
+ }
2945
3029
  // Story 056 (R3.2) — the `agent` (main-thread persona) selector, mirroring the effort option but
2946
3030
  // with a "default" no-persona sentinel. GATED on `agents.length > 0` (upstream #794): when nothing
2947
3031
  // is discovered the option is OMITTED entirely. The "default" entry = no persona (the spawn layer
@@ -3607,7 +3691,7 @@ export function inferContextWindowFromModel(model) {
3607
3691
  * field), used by the pump to refine the alias seed once the model is known. Exact-ID lookup first
3608
3692
  * (MODEL_ID_CONTEXT_WINDOWS), then a family+version heuristic for dated snapshots / future variants
3609
3693
  * (Opus is NOT uniform: 4.6 and earlier = 200K, 4.7+ = 1M; Sonnet 4.x = 200K but Sonnet 5+ = 1M;
3610
- * haiku = 200K; fable = 1M — story 071), then a
3694
+ * Haiku 4.x = 200K but Haiku 5+ = 1M — item 93; fable = 1M — story 071), then a
3611
3695
  * `\b1m\b` suffix, then null (R1.3: a missing / non-string id never refines). */
3612
3696
  export function inferContextWindowFromModelId(id) {
3613
3697
  if (typeof id !== "string" || id.length === 0)
@@ -3633,7 +3717,10 @@ export function inferContextWindowFromModelId(id) {
3633
3717
  const sonnet = id.match(/claude-sonnet-(\d+)/);
3634
3718
  if (sonnet)
3635
3719
  return Number(sonnet[1]) >= 5 ? 1_000_000 : 200_000;
3636
- if (/claude-haiku/.test(id))
3637
- return 200_000;
3720
+ // Haiku split the same way (item 93): Haiku 4.x is 200K, Haiku 5.5 is native 1M (the CLI's baked-in
3721
+ // catalogue: `context:{window:1e6,native_1m:!0}`). A blanket 200K under-sized every Haiku 5.5 turn.
3722
+ const haiku = id.match(/claude-haiku-(\d+)/);
3723
+ if (haiku)
3724
+ return Number(haiku[1]) >= 5 ? 1_000_000 : 200_000;
3638
3725
  return null;
3639
3726
  }
@@ -145,15 +145,13 @@ export declare function injectHook(opts: {
145
145
  */
146
146
  export declare function restore(backup: Backup): Promise<RestoreResult>;
147
147
  /**
148
- * Story 060 (R2.2/R2.3/R3.2) — toggle the ultracode keys in the per-session SCRATCH settings file the
149
- * gate wrote (preserving the hook + EVERY other key). `active` → set `ultracode:true` (the per-session
150
- * ACTIVATOR) + `ultracodeKeywordTrigger:true` (defensively ENABLE the keyword even if the user disabled
151
- * it). `!active` → remove BOTH keys. Read tolerantly (JSONC) + written durably (temp+fsync+rename),
152
- * mirroring {@link injectHook}. A missing/empty file is treated as an empty object. No-op-safe and
153
- * idempotent: re-applying the same `active` produces a byte-equivalent document.
148
+ * Item 84 — set (`active`) or remove the `ultracode` key in the per-session SCRATCH settings file the
149
+ * gate wrote, preserving the hook and EVERY other key. Read tolerantly (JSONC) and written durably
150
+ * (temp+fsync+rename), mirroring {@link injectHook}. A missing/empty file is treated as an empty
151
+ * object. Idempotent: re-applying the same `active` produces a byte-equivalent document.
154
152
  *
155
153
  * @param settingsPath absolute path to the per-session scratch `settings.local.json` (the gate's file).
156
- * @param active whether ultracode is selected (set the keys) or de-selected (remove them).
154
+ * @param active whether Ultracode is on (set the key) or off (remove it).
157
155
  * @throws {Error} only on a genuine read/parse/write failure — NEVER on the benign absence of the file
158
156
  * (ENOENT → treated as `{}`), mirroring the rest of the module's discipline.
159
157
  */
@@ -354,26 +354,25 @@ export async function restore(backup) {
354
354
  }
355
355
  }
356
356
  // ─────────────────────────────────────────────────────────────────────────────
357
- // Story 060 (R2.2 / R2.3 / R3.2) — toggle the ultracode keys in the per-session SCRATCH settings file.
357
+ // Item 84 — mirror the Ultracode switch into the per-session SCRATCH settings file.
358
358
  //
359
- // The "ultracode" effort-selector sentinel (story 060) activates the binary's Workflow keyword-trigger.
360
- // Its LIVE activation is a keyword prefix on the outgoing prompt (acp-agent.ts); THIS function is the
361
- // declarative spawn-time complement — the keys `claude` reads only at (re-)spawn, so the scratch stays
362
- // in sync for any (re-)spawn that DOES happen. It is NOT itself a re-spawn trigger (Option A).
359
+ // The switch is applied live with `/effort ultracode on|off`, which the CLI keeps for "this session
360
+ // only" — a re-spawn of the PTY (mode/agent change, resume) starts a new CLI process without it. The
361
+ // scratch file is that process's `--settings`, so `ultracode:true` here carries the switch across a
362
+ // re-spawn. It is NOT a re-spawn trigger. Story 060 also wrote `ultracodeKeywordTrigger:true`; that is
363
+ // not a settings key: CLI 2.1.261, 2.1.285, 2.1.296 (parity audit, round 21) and 2.1.299 use it only
364
+ // as a telemetry label — the real key is `workflowKeywordTriggerEnabled` — so it was dropped.
363
365
  // ─────────────────────────────────────────────────────────────────────────────
364
- /** The two settings keys that opt a session into the ultracode keyword-trigger (story 060). */
366
+ /** The settings key that keeps Ultracode on for a (re-)spawned session. */
365
367
  const ULTRACODE_SETTINGS_KEY = "ultracode";
366
- const ULTRACODE_KEYWORD_TRIGGER_KEY = "ultracodeKeywordTrigger";
367
368
  /**
368
- * Story 060 (R2.2/R2.3/R3.2) — toggle the ultracode keys in the per-session SCRATCH settings file the
369
- * gate wrote (preserving the hook + EVERY other key). `active` → set `ultracode:true` (the per-session
370
- * ACTIVATOR) + `ultracodeKeywordTrigger:true` (defensively ENABLE the keyword even if the user disabled
371
- * it). `!active` → remove BOTH keys. Read tolerantly (JSONC) + written durably (temp+fsync+rename),
372
- * mirroring {@link injectHook}. A missing/empty file is treated as an empty object. No-op-safe and
373
- * idempotent: re-applying the same `active` produces a byte-equivalent document.
369
+ * Item 84 — set (`active`) or remove the `ultracode` key in the per-session SCRATCH settings file the
370
+ * gate wrote, preserving the hook and EVERY other key. Read tolerantly (JSONC) and written durably
371
+ * (temp+fsync+rename), mirroring {@link injectHook}. A missing/empty file is treated as an empty
372
+ * object. Idempotent: re-applying the same `active` produces a byte-equivalent document.
374
373
  *
375
374
  * @param settingsPath absolute path to the per-session scratch `settings.local.json` (the gate's file).
376
- * @param active whether ultracode is selected (set the keys) or de-selected (remove them).
375
+ * @param active whether Ultracode is on (set the key) or off (remove it).
377
376
  * @throws {Error} only on a genuine read/parse/write failure — NEVER on the benign absence of the file
378
377
  * (ENOENT → treated as `{}`), mirroring the rest of the module's discipline.
379
378
  */
@@ -388,16 +387,14 @@ export async function applyUltracodeSettings(settingsPath, active) {
388
387
  current = parsePriorSettings(text);
389
388
  }
390
389
  }
391
- // 2) Clone (never mutate the parsed prior) and toggle ONLY the two ultracode keys — every other key
390
+ // 2) Clone (never mutate the parsed prior) and toggle ONLY the ultracode key — every other key
392
391
  // (the gate hook, the user's own config) is preserved verbatim.
393
392
  const next = structuredClone(current);
394
393
  if (active) {
395
394
  next[ULTRACODE_SETTINGS_KEY] = true;
396
- next[ULTRACODE_KEYWORD_TRIGGER_KEY] = true;
397
395
  }
398
396
  else {
399
397
  delete next[ULTRACODE_SETTINGS_KEY];
400
- delete next[ULTRACODE_KEYWORD_TRIGGER_KEY];
401
398
  }
402
399
  // 3) Durably write (temp+fsync+rename) so a concurrent (re-)spawn read never sees a half-written file.
403
400
  await durableWrite(settingsPath, `${JSON.stringify(next, null, 2)}\n`);
@@ -1,4 +1,4 @@
1
- import type { ModelInfo } from "@anthropic-ai/claude-agent-sdk";
1
+ import type { ModelInfo, Options, Query, SDKUserMessage } from "@anthropic-ai/claude-agent-sdk";
2
2
  /**
3
3
  * The model picker, read from the CLI at runtime instead of curated by hand.
4
4
  *
@@ -43,6 +43,84 @@ interface CatalogLogger {
43
43
  }
44
44
  /** Drop the memoised catalogue AND the once-per-process report latch. Tests use it; production does not. */
45
45
  export declare function resetLiveModelCatalogCache(): void;
46
+ /**
47
+ * Environment variable that selects where the default source reads from.
48
+ * `builtin` serves {@link MODEL_CATALOG} without spawning anything — an offline
49
+ * knob for production, and what the test harness sets on every adapter it spawns
50
+ * as a child process. Unset (or any other value) means the live CLI read.
51
+ */
52
+ export declare const MODEL_CATALOG_ENV = "CLAUDE_TUI_MODEL_CATALOG";
53
+ /**
54
+ * Opt-in for a test that genuinely needs the live CLI read. Without it, the live
55
+ * source refuses to run under the node test runner — see {@link LiveCatalogInTestsError}.
56
+ */
57
+ export declare const LIVE_CATALOG_TESTS_ENV = "CLAUDE_TUI_LIVE_CATALOG_TESTS";
58
+ /**
59
+ * Raised when the LIVE source is reached from inside `node --test` without the
60
+ * {@link LIVE_CATALOG_TESTS_ENV} opt-in.
61
+ *
62
+ * WHY IT EXISTS. Each test file runs in its own process with an empty cache, and
63
+ * most suites create sessions without injecting a catalogue. Before this guard,
64
+ * one `npm run test:fork` spawned ~50 real CLI sessions — each loading the
65
+ * user's hooks, plugins and MCP servers — and five runs made 248 SDK sessions in
66
+ * 17 minutes (measured 2026-10-14). The test setup module installs a stub as the
67
+ * default source; this error is the tripwire for anything that bypasses it.
68
+ *
69
+ * {@link resolveModelCatalog} rethrows it instead of falling back, so the test
70
+ * that reached the live read FAILS rather than passing on the built-in list.
71
+ * `NODE_TEST_CONTEXT` is set only by node's test runner, so production never
72
+ * sees this.
73
+ */
74
+ export declare class LiveCatalogInTestsError extends Error {
75
+ constructor();
76
+ }
77
+ /** Throws {@link LiveCatalogInTestsError} under `node --test` unless the live opt-in is set. */
78
+ export declare function assertLiveCatalogAllowed(env?: NodeJS.ProcessEnv): void;
79
+ /**
80
+ * Replace the source used when a caller passes none. Only the test setup module
81
+ * calls this (test/helpers/test-setup.ts, preloaded by `npm run test:fork`), so
82
+ * every session a test creates reads a fixed catalogue instead of the host CLI.
83
+ * Pass `undefined` to restore the live read. Production never calls it.
84
+ */
85
+ export declare function setDefaultModelCatalogSource(source: SupportedModelsSource | undefined): void;
86
+ /**
87
+ * A prompt stream that never yields a message and ends only when `signal` aborts.
88
+ *
89
+ * This is what keeps the catalogue read INERT. `query({ prompt: "" })` does not
90
+ * mean "no prompt": the SDK submits the empty string as a real user turn, the
91
+ * model answers it, and that answer is billed. Measured 2026-10-14: the session
92
+ * transcript held a user record with a `promptId`, and 51 Opus responses were
93
+ * billed across one day's test runs. With streaming input and no message, the
94
+ * CLI starts, answers control requests such as `supportedModels()`, and never
95
+ * has a turn to run.
96
+ */
97
+ export declare function silentPrompt(signal: AbortSignal): AsyncIterable<SDKUserMessage>;
98
+ /**
99
+ * The SDK options of the catalogue read, and why each one is there.
100
+ *
101
+ * - `settingSources: ["user"]` — the user's own settings still shape the list
102
+ * (`availableModels`, `env`, a model override), so the picker matches what
103
+ * their CLI would offer.
104
+ * - `settings: { disableAllHooks: true }` — the inline settings are the flag
105
+ * layer, which outranks the user file, so the user's hooks (SessionStart,
106
+ * SessionEnd, statusLine…) do not run for a read that is not a session.
107
+ * Without it, every catalogue read fired them like a real session.
108
+ * - `strictMcpConfig` with no `mcpServers` — no MCP server is started.
109
+ * - `persistSession: false` — nothing is written under `~/.claude/projects/`.
110
+ */
111
+ export declare function catalogQueryOptions(pathToClaudeCodeExecutable: string): Options;
112
+ /** The slice of the SDK's `query` the catalogue read uses; injectable so tests need no spawn. */
113
+ export type CatalogQueryFn = (params: {
114
+ prompt: AsyncIterable<SDKUserMessage>;
115
+ options: Options;
116
+ }) => Pick<Query, "supportedModels" | "close">;
117
+ /**
118
+ * Read the model list from a CLI started with {@link catalogQueryOptions} and
119
+ * {@link silentPrompt}, then close it. `supportedModels()` is a control request,
120
+ * not a turn: with no message on the prompt stream, no model call is made and
121
+ * no quota is used.
122
+ */
123
+ export declare function readSupportedModels(queryFn: CatalogQueryFn, pathToClaudeCodeExecutable: string): Promise<ModelInfo[]>;
46
124
  /**
47
125
  * Rewrite the `default` row's description to NAME the model it resolves to.
48
126
  *
@@ -73,7 +151,7 @@ export declare function nameDefaultRow(models: ModelInfo[]): ModelInfo[];
73
151
  * for the rest of the process.
74
152
  *
75
153
  * @param logger - Where a fallback is reported. Optional, for library callers.
76
- * @param source - Test seam; defaults to spawning the PATH `claude`.
154
+ * @param source - Test seam; defaults to spawning the PATH `claude` (see {@link defaultSource}).
77
155
  */
78
156
  export declare function resolveModelCatalog(logger?: CatalogLogger, source?: SupportedModelsSource): Promise<ModelInfo[]>;
79
157
  export {};
@@ -47,20 +47,120 @@ export function resetLiveModelCatalogCache() {
47
47
  fallbackReported = false;
48
48
  }
49
49
  /**
50
- * The production source: spawn the PATH `claude` through the SDK purely to read
51
- * its model list, then shut it down. `supportedModels()` is a control request,
52
- * not a turn — it sends no prompt and consumes no quota.
50
+ * Environment variable that selects where the default source reads from.
51
+ * `builtin` serves {@link MODEL_CATALOG} without spawning anything — an offline
52
+ * knob for production, and what the test harness sets on every adapter it spawns
53
+ * as a child process. Unset (or any other value) means the live CLI read.
53
54
  */
54
- async function defaultSource() {
55
- const { query } = await import("@anthropic-ai/claude-agent-sdk");
56
- const q = query({
57
- prompt: "",
58
- options: {
59
- pathToClaudeCodeExecutable: resolveClaudePath(),
60
- // Read the user's own settings, so the catalogue matches what their CLI
61
- // would offer; the fetch is otherwise inert.
62
- settingSources: ["user"],
63
- },
55
+ export const MODEL_CATALOG_ENV = "CLAUDE_TUI_MODEL_CATALOG";
56
+ /**
57
+ * Opt-in for a test that genuinely needs the live CLI read. Without it, the live
58
+ * source refuses to run under the node test runner — see {@link LiveCatalogInTestsError}.
59
+ */
60
+ export const LIVE_CATALOG_TESTS_ENV = "CLAUDE_TUI_LIVE_CATALOG_TESTS";
61
+ /**
62
+ * Raised when the LIVE source is reached from inside `node --test` without the
63
+ * {@link LIVE_CATALOG_TESTS_ENV} opt-in.
64
+ *
65
+ * WHY IT EXISTS. Each test file runs in its own process with an empty cache, and
66
+ * most suites create sessions without injecting a catalogue. Before this guard,
67
+ * one `npm run test:fork` spawned ~50 real CLI sessions — each loading the
68
+ * user's hooks, plugins and MCP servers — and five runs made 248 SDK sessions in
69
+ * 17 minutes (measured 2026-10-14). The test setup module installs a stub as the
70
+ * default source; this error is the tripwire for anything that bypasses it.
71
+ *
72
+ * {@link resolveModelCatalog} rethrows it instead of falling back, so the test
73
+ * that reached the live read FAILS rather than passing on the built-in list.
74
+ * `NODE_TEST_CONTEXT` is set only by node's test runner, so production never
75
+ * sees this.
76
+ */
77
+ export class LiveCatalogInTestsError extends Error {
78
+ constructor() {
79
+ super("the live model catalogue (a real `claude` spawn) was requested under the node test runner. " +
80
+ "Run tests through `npm run test:fork` (it preloads test/helpers/test-setup.ts, which installs " +
81
+ "the stub), inject `deps.modelCatalogSource`, or opt in with " +
82
+ `${LIVE_CATALOG_TESTS_ENV}=1 for a test that truly needs the CLI.`);
83
+ this.name = "LiveCatalogInTestsError";
84
+ }
85
+ }
86
+ /** Throws {@link LiveCatalogInTestsError} under `node --test` unless the live opt-in is set. */
87
+ export function assertLiveCatalogAllowed(env = process.env) {
88
+ if (env.NODE_TEST_CONTEXT && env[LIVE_CATALOG_TESTS_ENV] !== "1") {
89
+ throw new LiveCatalogInTestsError();
90
+ }
91
+ }
92
+ /** Set by {@link setDefaultModelCatalogSource}; `undefined` means the live CLI read. */
93
+ let defaultOverride;
94
+ /**
95
+ * Replace the source used when a caller passes none. Only the test setup module
96
+ * calls this (test/helpers/test-setup.ts, preloaded by `npm run test:fork`), so
97
+ * every session a test creates reads a fixed catalogue instead of the host CLI.
98
+ * Pass `undefined` to restore the live read. Production never calls it.
99
+ */
100
+ export function setDefaultModelCatalogSource(source) {
101
+ defaultOverride = source;
102
+ cache = null;
103
+ }
104
+ /** The source a caller without its own gets: the test override, or the live read. */
105
+ function defaultSource() {
106
+ return defaultOverride ? defaultOverride() : liveSource();
107
+ }
108
+ /**
109
+ * A prompt stream that never yields a message and ends only when `signal` aborts.
110
+ *
111
+ * This is what keeps the catalogue read INERT. `query({ prompt: "" })` does not
112
+ * mean "no prompt": the SDK submits the empty string as a real user turn, the
113
+ * model answers it, and that answer is billed. Measured 2026-10-14: the session
114
+ * transcript held a user record with a `promptId`, and 51 Opus responses were
115
+ * billed across one day's test runs. With streaming input and no message, the
116
+ * CLI starts, answers control requests such as `supportedModels()`, and never
117
+ * has a turn to run.
118
+ */
119
+ export function silentPrompt(signal) {
120
+ const ended = new Promise((resolve) => {
121
+ const end = () => resolve({ value: undefined, done: true });
122
+ if (signal.aborted)
123
+ end();
124
+ else
125
+ signal.addEventListener("abort", end, { once: true });
126
+ });
127
+ // Every `next()` waits for the abort and then reports the end: no message is ever produced.
128
+ return { [Symbol.asyncIterator]: () => ({ next: () => ended }) };
129
+ }
130
+ /**
131
+ * The SDK options of the catalogue read, and why each one is there.
132
+ *
133
+ * - `settingSources: ["user"]` — the user's own settings still shape the list
134
+ * (`availableModels`, `env`, a model override), so the picker matches what
135
+ * their CLI would offer.
136
+ * - `settings: { disableAllHooks: true }` — the inline settings are the flag
137
+ * layer, which outranks the user file, so the user's hooks (SessionStart,
138
+ * SessionEnd, statusLine…) do not run for a read that is not a session.
139
+ * Without it, every catalogue read fired them like a real session.
140
+ * - `strictMcpConfig` with no `mcpServers` — no MCP server is started.
141
+ * - `persistSession: false` — nothing is written under `~/.claude/projects/`.
142
+ */
143
+ export function catalogQueryOptions(pathToClaudeCodeExecutable) {
144
+ return {
145
+ pathToClaudeCodeExecutable,
146
+ settingSources: ["user"],
147
+ settings: { disableAllHooks: true },
148
+ strictMcpConfig: true,
149
+ mcpServers: {},
150
+ persistSession: false,
151
+ };
152
+ }
153
+ /**
154
+ * Read the model list from a CLI started with {@link catalogQueryOptions} and
155
+ * {@link silentPrompt}, then close it. `supportedModels()` is a control request,
156
+ * not a turn: with no message on the prompt stream, no model call is made and
157
+ * no quota is used.
158
+ */
159
+ export async function readSupportedModels(queryFn, pathToClaudeCodeExecutable) {
160
+ const stop = new AbortController();
161
+ const q = queryFn({
162
+ prompt: silentPrompt(stop.signal),
163
+ options: catalogQueryOptions(pathToClaudeCodeExecutable),
64
164
  });
65
165
  try {
66
166
  return await q.supportedModels();
@@ -68,13 +168,21 @@ async function defaultSource() {
68
168
  finally {
69
169
  // Never let a failed teardown mask a successful read.
70
170
  try {
71
- q.return(undefined);
171
+ q.close();
72
172
  }
73
173
  catch {
74
174
  /* the process is going away regardless */
75
175
  }
176
+ // Release the prompt stream, so nothing waits on it after the CLI is gone.
177
+ stop.abort();
76
178
  }
77
179
  }
180
+ /** The production source: the PATH `claude`, read inertly. See {@link readSupportedModels}. */
181
+ async function liveSource() {
182
+ assertLiveCatalogAllowed();
183
+ const { query } = await import("@anthropic-ai/claude-agent-sdk");
184
+ return readSupportedModels(query, resolveClaudePath());
185
+ }
78
186
  /** Reject after {@link CATALOG_TIMEOUT_MS} so a hung control request cannot stall session creation. */
79
187
  function withTimeout(promise, ms) {
80
188
  return new Promise((resolve, reject) => {
@@ -126,10 +234,14 @@ export function nameDefaultRow(models) {
126
234
  * for the rest of the process.
127
235
  *
128
236
  * @param logger - Where a fallback is reported. Optional, for library callers.
129
- * @param source - Test seam; defaults to spawning the PATH `claude`.
237
+ * @param source - Test seam; defaults to spawning the PATH `claude` (see {@link defaultSource}).
130
238
  */
131
239
  export async function resolveModelCatalog(logger, source = defaultSource) {
132
- if (cache && Date.now() - cache.at < CATALOG_TTL_MS)
240
+ // The offline knob: the built-in list, served as-is, with nothing spawned.
241
+ if (source === defaultSource && !defaultOverride && process.env[MODEL_CATALOG_ENV] === "builtin")
242
+ return MODEL_CATALOG;
243
+ // Keyed by source, so an injected catalogue never answers for the CLI and vice versa (item 93).
244
+ if (cache && cache.source === source && Date.now() - cache.at < CATALOG_TTL_MS)
133
245
  return cache.models;
134
246
  try {
135
247
  const raw = await withTimeout(source(), CATALOG_TIMEOUT_MS);
@@ -141,10 +253,13 @@ export async function resolveModelCatalog(logger, source = defaultSource) {
141
253
  // was empty — already excluded above. Guard anyway: an empty picker is worse
142
254
  // than a stale one, and this function must never return one.
143
255
  const resolved = models.length > 0 ? models : raw;
144
- cache = { models: resolved, at: Date.now() };
256
+ cache = { models: resolved, at: Date.now(), source };
145
257
  return resolved;
146
258
  }
147
259
  catch (error) {
260
+ // The test tripwire must fail the test that reached it, not degrade quietly.
261
+ if (error instanceof LiveCatalogInTestsError)
262
+ throw error;
148
263
  // `log`, NOT `error`, and ONCE per process. Both halves are deliberate.
149
264
  //
150
265
  // Level: this path is degraded-but-recovered — the picker still works, from
@@ -2,21 +2,10 @@ import type { ModelInfo } from "@anthropic-ai/claude-agent-sdk";
2
2
  import type { ClientCapabilities, SessionConfigOption } from "@agentclientprotocol/sdk";
3
3
  /**
4
4
  * Effort levels offered for reasoning-capable models — the SDK's `supportedEffortLevels` vocabulary.
5
- * Story 060: exported so the ultracode guard test can assert membership stays the five real levels
6
- * (it must NEVER contain {@link ULTRACODE_EFFORT}; the real `--effort` enum is exactly this set).
5
+ * Exactly the real `--effort` enum. Ultracode is NOT a level (item 84): it is its own switch, see
6
+ * {@link ULTRACODE_CONFIG_ID}.
7
7
  */
8
8
  export declare const REASONING_EFFORT_LEVELS: NonNullable<ModelInfo["supportedEffortLevels"]>;
9
- /**
10
- * Story 060 — the "ultracode" pseudo-level sentinel for the effort selector. NOT a real `--effort`
11
- * value (claude 2.1.195 rejects `--effort ultracode`; the enum stays {@link REASONING_EFFORT_LEVELS}).
12
- * Selecting it maps to `--effort xhigh` PLUS activating the ultracode keyword-trigger for the session
13
- * (story 060 Task 3). Kept OUT of REASONING_EFFORT_LEVELS so no real-effort code path ever emits it.
14
- */
15
- export declare const ULTRACODE_EFFORT = "ultracode";
16
- /** The real effort level the ultracode pseudo-level maps to (its documented effort component). */
17
- export declare const ULTRACODE_EFFORT_LEVEL = "xhigh";
18
- /** Selector label — makes clear it is xhigh + orchestration, NOT a duplicate of the plain `xhigh` entry. */
19
- export declare const ULTRACODE_EFFORT_LABEL = "ultracode (xhigh + orchestration)";
20
9
  /**
21
10
  * The FALLBACK model list — no longer what the picker normally shows.
22
11
  *
@@ -52,18 +41,20 @@ export declare const ULTRACODE_EFFORT_LABEL = "ultracode (xhigh + orchestration)
52
41
  * A tier alias always points at the newest member of its family, so these rows do NOT age out on a
53
42
  * model launch — only the version text in the row does. Verified 2026-09-23:
54
43
  * `opus` → `claude-opus-5-5`, `fable` → `claude-fable-5-1`, `sonnet` → `claude-sonnet-5`,
55
- * `haiku` → `claude-haiku-4-5-20251001`.
56
- *
57
- * Effort-capable models (`default`/`fable`/`opus`/`sonnet`) carry `supportsEffort` +
58
- * `supportedEffortLevels`; `haiku` advertises none. `supportsAutoMode: true` on the same four surfaces
59
- * the `auto` permission mode (a model classifier) — the original drops `auto` on `haiku` (the SDK signal
60
- * `reconcileModeFromTranscript` clamps), so haiku omits it.
44
+ * `haiku` → `claude-haiku-4-5-20251001`. Re-read 2026-10-14 from CLI 2.1.299's live
45
+ * `supportedModels()`: `sonnet` → `claude-sonnet-5-5`, `haiku` → `claude-haiku-5-5` (both moved in
46
+ * CLI 2.1.293).
47
+ *
48
+ * Every row is effort-capable (`supportsEffort` + `supportedEffortLevels`) and carries
49
+ * `supportsAutoMode: true`, which surfaces the `auto` permission mode (a model classifier). `haiku`
50
+ * used to advertise neither: Haiku 4.5 had no effort levels and the original drops `auto` on it.
51
+ * Haiku 5.5 has both, per the live CLI rows.
61
52
  */
62
53
  export declare const MODEL_CATALOG: ModelInfo[];
63
54
  /**
64
55
  * Story 068 (R1, R1.1, R2) — the REAL per-alias context window, keyed by the EXACT {@link MODEL_CATALOG}
65
- * `value`. These windows are NOT uniform: `default`/`fable`/`opus`/`sonnet` are natively 1M and `haiku`
66
- * is 200K. This map is the single source of truth that `inferContextWindowFromModel` (acp-agent.ts)
56
+ * `value`. Every alias is natively 1M today; `haiku` was 200K until it moved to Haiku 5.5 (item 93).
57
+ * Older generations are NOT uniform, which is why {@link MODEL_ID_CONTEXT_WINDOWS} refines per turn. This map is the single source of truth that `inferContextWindowFromModel` (acp-agent.ts)
67
58
  * consults BEFORE the `\b1m\b` regex fallback — the bug it fixes is `opus` having wrongly reported 200K
68
59
  * (the regex only ever matched the literal `1m` token).
69
60
  *
@@ -185,5 +176,50 @@ export type FastModeSignal = "available" | "unavailable" | "pending";
185
176
  * `pending`, and the caller fails closed on timeout (R1.2).
186
177
  */
187
178
  export declare function classifyFastModeSignal(raw: string): FastModeSignal;
179
+ /** Item 84 — the Ultracode config-option id. */
180
+ export declare const ULTRACODE_CONFIG_ID = "ultracode";
181
+ /**
182
+ * Item 84 — the CLI command that turns Ultracode on or off for the session. Always the explicit
183
+ * `on|off` form: never a bare `/effort ultracode`, whose meaning the CLI has changed between builds.
184
+ */
185
+ export declare function ultracodeCommand(on: boolean): string;
186
+ /**
187
+ * Item 84 — can this model run Ultracode? The CLI's own gate is "workflows are enabled AND the model
188
+ * supports xhigh"; the first half is not knowable from here (managed settings, org policy, env), so
189
+ * this checks the second and the CLI's refusal reply ({@link classifyUltracodeReply}) covers the rest.
190
+ */
191
+ export declare function isUltracodeCapableModel(info: ModelInfo | undefined): boolean;
192
+ /** Item 84 — the switch is on while this is true; a boolean payload or the on/off select string. */
193
+ export declare function resolveUltracodeEnabled(value: unknown): boolean;
194
+ /**
195
+ * Item 84 — build the `ultracode` config option: `type:"boolean"` when the client advertised boolean
196
+ * config options, else an on/off select, exactly as {@link createFastModeConfigOption} does. When the
197
+ * CLI refused the last attempt, `refusal` is appended to the description so the reason the switch
198
+ * went back off is visible where the switch is.
199
+ */
200
+ export declare function createUltracodeConfigOption(enabled: boolean, useBooleanOption: boolean, refusal?: string): SessionConfigOption;
201
+ /**
202
+ * Item 84 — what the CLI answered to `/effort ultracode on`:
203
+ * - `refused` — one of its two refusals; `reason` is the sentence to show the user.
204
+ * - `on` — "Ultracode on (this session only): …".
205
+ * - `pending` — neither yet; keep reading until the caller's window closes.
206
+ */
207
+ export type UltracodeReply = {
208
+ kind: "refused";
209
+ reason: string;
210
+ } | {
211
+ kind: "on";
212
+ } | {
213
+ kind: "pending";
214
+ };
215
+ /**
216
+ * Item 84 — classify the CLI's reply to `/effort ultracode on`. The two refusals are the CLI's own
217
+ * strings (claude 2.1.299, `/effort` handler):
218
+ * `Ultracode needs dynamic workflows enabled (see /config). Valid options are: …`
219
+ * `Ultracode isn't available on <model>. Valid options are: …`
220
+ * and its confirmation is `Ultracode on (this session only): …`. When the captured text holds more
221
+ * than one (a repaint can carry an older answer), the one written LAST is the answer to this command.
222
+ */
223
+ export declare function classifyUltracodeReply(raw: string): UltracodeReply;
188
224
  /** The safe fallback entry, kept as a named export so callers can seed/anchor on it without a lookup. */
189
225
  export declare const DEFAULT_MODEL_INFO: ModelInfo;
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Effort levels offered for reasoning-capable models — the SDK's `supportedEffortLevels` vocabulary.
3
- * Story 060: exported so the ultracode guard test can assert membership stays the five real levels
4
- * (it must NEVER contain {@link ULTRACODE_EFFORT}; the real `--effort` enum is exactly this set).
3
+ * Exactly the real `--effort` enum. Ultracode is NOT a level (item 84): it is its own switch, see
4
+ * {@link ULTRACODE_CONFIG_ID}.
5
5
  */
6
6
  export const REASONING_EFFORT_LEVELS = [
7
7
  "low",
@@ -10,17 +10,6 @@ export const REASONING_EFFORT_LEVELS = [
10
10
  "xhigh",
11
11
  "max",
12
12
  ];
13
- /**
14
- * Story 060 — the "ultracode" pseudo-level sentinel for the effort selector. NOT a real `--effort`
15
- * value (claude 2.1.195 rejects `--effort ultracode`; the enum stays {@link REASONING_EFFORT_LEVELS}).
16
- * Selecting it maps to `--effort xhigh` PLUS activating the ultracode keyword-trigger for the session
17
- * (story 060 Task 3). Kept OUT of REASONING_EFFORT_LEVELS so no real-effort code path ever emits it.
18
- */
19
- export const ULTRACODE_EFFORT = "ultracode";
20
- /** The real effort level the ultracode pseudo-level maps to (its documented effort component). */
21
- export const ULTRACODE_EFFORT_LEVEL = "xhigh";
22
- /** Selector label — makes clear it is xhigh + orchestration, NOT a duplicate of the plain `xhigh` entry. */
23
- export const ULTRACODE_EFFORT_LABEL = "ultracode (xhigh + orchestration)";
24
13
  /**
25
14
  * The FALLBACK model list — no longer what the picker normally shows.
26
15
  *
@@ -56,12 +45,14 @@ export const ULTRACODE_EFFORT_LABEL = "ultracode (xhigh + orchestration)";
56
45
  * A tier alias always points at the newest member of its family, so these rows do NOT age out on a
57
46
  * model launch — only the version text in the row does. Verified 2026-09-23:
58
47
  * `opus` → `claude-opus-5-5`, `fable` → `claude-fable-5-1`, `sonnet` → `claude-sonnet-5`,
59
- * `haiku` → `claude-haiku-4-5-20251001`.
48
+ * `haiku` → `claude-haiku-4-5-20251001`. Re-read 2026-10-14 from CLI 2.1.299's live
49
+ * `supportedModels()`: `sonnet` → `claude-sonnet-5-5`, `haiku` → `claude-haiku-5-5` (both moved in
50
+ * CLI 2.1.293).
60
51
  *
61
- * Effort-capable models (`default`/`fable`/`opus`/`sonnet`) carry `supportsEffort` +
62
- * `supportedEffortLevels`; `haiku` advertises none. `supportsAutoMode: true` on the same four surfaces
63
- * the `auto` permission mode (a model classifier) — the original drops `auto` on `haiku` (the SDK signal
64
- * `reconcileModeFromTranscript` clamps), so haiku omits it.
52
+ * Every row is effort-capable (`supportsEffort` + `supportedEffortLevels`) and carries
53
+ * `supportsAutoMode: true`, which surfaces the `auto` permission mode (a model classifier). `haiku`
54
+ * used to advertise neither: Haiku 4.5 had no effort levels and the original drops `auto` on it.
55
+ * Haiku 5.5 has both, per the live CLI rows.
65
56
  */
66
57
  export const MODEL_CATALOG = [
67
58
  {
@@ -98,22 +89,31 @@ export const MODEL_CATALOG = [
98
89
  },
99
90
  {
100
91
  value: "sonnet",
101
- displayName: "Sonnet 5",
102
- description: "Sonnet 5 with 1M context · Efficient for routine tasks",
92
+ // Item 93: `sonnet` resolves to `claude-sonnet-5-5` since CLI 2.1.293 (the baked-in catalogue's
93
+ // `aliases.sonnet.default`); the tagline is the live row's, verbatim (CLI 2.1.299).
94
+ displayName: "Sonnet 5.5",
95
+ description: "Sonnet 5.5 with 1M context · Most efficient for simpler tasks",
103
96
  supportsEffort: true,
104
97
  supportedEffortLevels: REASONING_EFFORT_LEVELS,
105
98
  supportsAutoMode: true,
106
99
  },
107
100
  {
108
101
  value: "haiku",
109
- displayName: "Haiku 4.5",
110
- description: "Haiku 4.5 · Fastest for quick answers",
102
+ // Item 93: `haiku` resolves to `claude-haiku-5-5` since CLI 2.1.293 — native 1M context, 128k
103
+ // output, and the full effort set (`capabilities: ["effort","max_effort","xhigh_effort",…]` in the
104
+ // baked-in catalogue). The live `supportedModels()` row (CLI 2.1.299) carries `supportsEffort`,
105
+ // all five levels and `supportsAutoMode`, so the fallback row does too.
106
+ displayName: "Haiku 5.5",
107
+ description: "Haiku 5.5 with 1M context · Fastest for quick answers",
108
+ supportsEffort: true,
109
+ supportedEffortLevels: REASONING_EFFORT_LEVELS,
110
+ supportsAutoMode: true,
111
111
  },
112
112
  ];
113
113
  /**
114
114
  * Story 068 (R1, R1.1, R2) — the REAL per-alias context window, keyed by the EXACT {@link MODEL_CATALOG}
115
- * `value`. These windows are NOT uniform: `default`/`fable`/`opus`/`sonnet` are natively 1M and `haiku`
116
- * is 200K. This map is the single source of truth that `inferContextWindowFromModel` (acp-agent.ts)
115
+ * `value`. Every alias is natively 1M today; `haiku` was 200K until it moved to Haiku 5.5 (item 93).
116
+ * Older generations are NOT uniform, which is why {@link MODEL_ID_CONTEXT_WINDOWS} refines per turn. This map is the single source of truth that `inferContextWindowFromModel` (acp-agent.ts)
117
117
  * consults BEFORE the `\b1m\b` regex fallback — the bug it fixes is `opus` having wrongly reported 200K
118
118
  * (the regex only ever matched the literal `1m` token).
119
119
  *
@@ -129,7 +129,8 @@ export const MODEL_CONTEXT_WINDOWS = {
129
129
  fable: 1_000_000,
130
130
  opus: 1_000_000,
131
131
  sonnet: 1_000_000,
132
- haiku: 200_000,
132
+ // Item 93: Haiku 5.5 is native 1M. Seeding 200K made every Haiku turn report 5x the real usage.
133
+ haiku: 1_000_000,
133
134
  };
134
135
  /**
135
136
  * Story 069 (R1.1) — the REAL context window per concrete model ID, mirroring the claude CLI's
@@ -150,10 +151,12 @@ export const MODEL_ID_CONTEXT_WINDOWS = {
150
151
  "claude-opus-4-6": 200_000,
151
152
  "claude-fable-5-1": 1_000_000,
152
153
  "claude-fable-5": 1_000_000,
154
+ "claude-sonnet-5-5": 1_000_000,
153
155
  "claude-sonnet-5": 1_000_000,
154
156
  "claude-sonnet-4-6": 200_000,
155
157
  "claude-sonnet-4-5-20250929": 200_000,
156
158
  "claude-sonnet-4-20250514": 200_000,
159
+ "claude-haiku-5-5": 1_000_000,
157
160
  "claude-haiku-4-5": 200_000,
158
161
  };
159
162
  /**
@@ -351,5 +354,118 @@ export function classifyFastModeSignal(raw) {
351
354
  return "available";
352
355
  return "pending"; // panel not rendered yet → keep waiting within the caller's bounded window
353
356
  }
357
+ // --- Item 84 — Ultracode as its own switch ----------------------------------------------------------
358
+ // Ultracode is "standing dynamic-workflow orchestration at any effort level", session-scoped. It used
359
+ // to be an `ultracode (xhigh + orchestration)` notch in the effort select (story 060) that forced
360
+ // xhigh, prefixed every prompt with the `ultracode` keyword and wrote a settings key the CLI does not
361
+ // read. The CLI (2.1.296+) exposes it as `/effort ultracode on|off`, independent of the effort level,
362
+ // and that is what this switch drives — built like the fast-mode option above.
363
+ /** Item 84 — the Ultracode config-option id. */
364
+ export const ULTRACODE_CONFIG_ID = "ultracode";
365
+ /**
366
+ * Item 84 — the CLI command that turns Ultracode on or off for the session. Always the explicit
367
+ * `on|off` form: never a bare `/effort ultracode`, whose meaning the CLI has changed between builds.
368
+ */
369
+ export function ultracodeCommand(on) {
370
+ return on ? "/effort ultracode on" : "/effort ultracode off";
371
+ }
372
+ /**
373
+ * Item 84 — can this model run Ultracode? The CLI's own gate is "workflows are enabled AND the model
374
+ * supports xhigh"; the first half is not knowable from here (managed settings, org policy, env), so
375
+ * this checks the second and the CLI's refusal reply ({@link classifyUltracodeReply}) covers the rest.
376
+ */
377
+ export function isUltracodeCapableModel(info) {
378
+ return info?.supportsEffort === true && (info.supportedEffortLevels ?? []).includes("xhigh");
379
+ }
380
+ /** Item 84 — the switch is on while this is true; a boolean payload or the on/off select string. */
381
+ export function resolveUltracodeEnabled(value) {
382
+ if (typeof value === "boolean")
383
+ return value;
384
+ return value === FAST_MODE_ON;
385
+ }
386
+ const ULTRACODE_DESCRIPTION = "Run dynamic workflows on every task (/effort ultracode).";
387
+ /**
388
+ * Item 84 — build the `ultracode` config option: `type:"boolean"` when the client advertised boolean
389
+ * config options, else an on/off select, exactly as {@link createFastModeConfigOption} does. When the
390
+ * CLI refused the last attempt, `refusal` is appended to the description so the reason the switch
391
+ * went back off is visible where the switch is.
392
+ */
393
+ export function createUltracodeConfigOption(enabled, useBooleanOption, refusal) {
394
+ const base = {
395
+ id: ULTRACODE_CONFIG_ID,
396
+ name: "Ultracode",
397
+ description: refusal ? `${ULTRACODE_DESCRIPTION} Off: ${refusal}` : ULTRACODE_DESCRIPTION,
398
+ category: "model_config",
399
+ };
400
+ if (useBooleanOption) {
401
+ return { ...base, type: "boolean", currentValue: enabled };
402
+ }
403
+ return {
404
+ ...base,
405
+ type: "select",
406
+ currentValue: enabled ? FAST_MODE_ON : FAST_MODE_OFF,
407
+ options: [
408
+ { value: FAST_MODE_OFF, name: "Off", description: "No standing orchestration." },
409
+ {
410
+ value: FAST_MODE_ON,
411
+ name: "On",
412
+ description: "Dynamic workflows on every task, at the current effort level.",
413
+ },
414
+ ],
415
+ };
416
+ }
417
+ /**
418
+ * Turn PTY output into plain text for phrase matching. Unlike {@link stripControlSequences}, a cursor-
419
+ * forward (`ESC [ n C`) becomes a space: Ink may draw a space by moving the cursor, and dropping it
420
+ * would glue two words together. Whitespace runs (line wraps included) collapse to one space.
421
+ */
422
+ function ptyTextForMatching(raw) {
423
+ // eslint-disable-next-line no-control-regex
424
+ const spaced = raw.replace(/\x1b\[\d*C/g, " ");
425
+ return stripControlSequences(spaced).replace(/\s+/g, " ");
426
+ }
427
+ /**
428
+ * Item 84 — classify the CLI's reply to `/effort ultracode on`. The two refusals are the CLI's own
429
+ * strings (claude 2.1.299, `/effort` handler):
430
+ * `Ultracode needs dynamic workflows enabled (see /config). Valid options are: …`
431
+ * `Ultracode isn't available on <model>. Valid options are: …`
432
+ * and its confirmation is `Ultracode on (this session only): …`. When the captured text holds more
433
+ * than one (a repaint can carry an older answer), the one written LAST is the answer to this command.
434
+ */
435
+ export function classifyUltracodeReply(raw) {
436
+ const text = ptyTextForMatching(raw);
437
+ const last = (re) => {
438
+ let found;
439
+ for (const match of text.matchAll(re))
440
+ found = { at: match.index ?? 0, match };
441
+ return found;
442
+ };
443
+ const candidates = [];
444
+ const workflows = last(/ultracode needs dynamic workflows enabled/gi);
445
+ if (workflows) {
446
+ candidates.push({
447
+ at: workflows.at,
448
+ reply: {
449
+ kind: "refused",
450
+ reason: "Ultracode needs dynamic workflows enabled (see /config).",
451
+ },
452
+ });
453
+ }
454
+ const model = last(/ultracode isn['\u2019]?t available on (\S+)/gi);
455
+ if (model) {
456
+ const name = model.match[1].replace(/\.$/, "");
457
+ candidates.push({
458
+ at: model.at,
459
+ reply: { kind: "refused", reason: `Ultracode isn't available on ${name}.` },
460
+ });
461
+ }
462
+ const on = last(/ultracode on \(this session only\)/gi);
463
+ if (on)
464
+ candidates.push({ at: on.at, reply: { kind: "on" } });
465
+ if (candidates.length === 0)
466
+ return { kind: "pending" };
467
+ candidates.sort((a, b) => b.at - a.at);
468
+ return candidates[0].reply;
469
+ }
354
470
  /** The safe fallback entry, kept as a named export so callers can seed/anchor on it without a lookup. */
355
471
  export const DEFAULT_MODEL_INFO = MODEL_CATALOG[0];
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "0.14.13",
6
+ "version": "0.15.0",
7
7
  "description": "Runs the official Claude Code TUI over a PTY and exposes it via ACP, so Claude Code threads render natively in Zed's agent panel. Built for Anthropic's June 2026 billing split (since paused).",
8
8
  "main": "dist/lib.js",
9
9
  "types": "dist/lib.d.ts",
@@ -35,7 +35,7 @@
35
35
  "format": "prettier --write .",
36
36
  "format:check": "prettier --check .",
37
37
  "check": "npm run lint && npm run format:check",
38
- "test": "npm run build && node --experimental-strip-types --test test/*.test.ts",
38
+ "test": "npm run build && node --experimental-strip-types --import ./test/helpers/test-setup.ts --test test/*.test.ts",
39
39
  "smoke:live": "node experiments/smoke-live.mjs",
40
40
  "prepublishOnly": "npm run build"
41
41
  },