@lucascouts/claude-agent-tui 0.7.0 → 0.8.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.
@@ -168,6 +168,23 @@ type Session = {
168
168
  * `default`) is re-selected. The declarative spawn-time complement is {@link applyUltracodeSettings}.
169
169
  */
170
170
  ultracodeActive?: boolean;
171
+ /**
172
+ * Story 073 (R2.3/R3.2) — the session's CURRENT fast-mode on/off state (default off). Set by
173
+ * {@link applyFastModeChange} and read by {@link buildConfigOptions} for the `fast` option's
174
+ * `currentValue`. Reset to `false` on a switch away from an Opus model (R4.1).
175
+ */
176
+ fastModeOn?: boolean;
177
+ /**
178
+ * Story 073 (R1.3) — cached fast-mode availability for this session (the {@link FastModeProbe}
179
+ * result). `undefined` = not yet probed; `false` = unavailable/non-Opus (option omitted); `true` =
180
+ * available (option advertised). Re-probed on a return to an Opus model (R4.2).
181
+ */
182
+ fastModeAvailable?: boolean;
183
+ /**
184
+ * Story 073 (R3.1) — a `/fast on|off` inject requested WHILE a turn is in flight is deferred here
185
+ * (last-write-wins) and flushed once the turn settles (mirrors {@link pendingEffortInjection}).
186
+ */
187
+ pendingFastInjection?: boolean;
171
188
  /**
172
189
  * Story 046 (R3.8) — true WHILE an in-place re-spawn (R3.4 dontAsk/bypass switch) is between the old
173
190
  * PTY teardown and the new PTY being ready. Selector changes arriving in this window are rejected
@@ -334,6 +351,43 @@ export interface StartEngineArgs {
334
351
  }
335
352
  /** The createSession injection seam: spawn the PTY engine + JSONL watcher + locate the transcript. */
336
353
  export type StartEngine = (args: StartEngineArgs) => Promise<StartedEngine> | StartedEngine;
354
+ /** Context passed to a {@link FastModeProbe}: enough to drive/observe the live PTY when the real
355
+ * detector is wired (story 073 Task 1), without exposing the private `Session` type. */
356
+ export interface FastModeProbeContext {
357
+ pty: IPty;
358
+ cwd: string;
359
+ }
360
+ /**
361
+ * Story 073 (R1) — the fast-mode availability-detection seam. Returns whether fast mode (`/fast`) is
362
+ * available for THIS session's account. The production default {@link defaultFastModeProbe} fails CLOSED
363
+ * (returns `false`): the live spike (Task 1) found that OBTAINING the signal requires DRIVING `/fast`
364
+ * over the PTY (there is no passive signal when gated — verified live), and an unsolicited session-start
365
+ * PTY write violates the fork's read-only-load (R4.3) and no-Ctrl+U-in-closed-loop invariants. The live
366
+ * driver therefore ships as the OPT-IN {@link driveFastModeProbe} (wired via `deps.fastModeProbe` after
367
+ * the R7.3 live-proof), not as the default. Tests inject a fake returning `true` to exercise the
368
+ * advertise/apply/reconcile paths (R2–R4).
369
+ */
370
+ export type FastModeProbe = (ctx: FastModeProbeContext) => Promise<boolean> | boolean;
371
+ /** Production default — fail-closed (R1.2), invariant-safe: performs NO PTY write, so it preserves the
372
+ * read-only-load (R4.3) and no-unsolicited-Ctrl+U invariants. The live signal is characterized (see
373
+ * {@link classifyFastModeSignal}) and the live driver is {@link driveFastModeProbe}; wiring it as the
374
+ * default is deferred to the R7.3 live-proof + a non-intrusive (idle-gated) wiring follow-up. */
375
+ export declare const defaultFastModeProbe: FastModeProbe;
376
+ /**
377
+ * Story 073 (R1) — the OPT-IN live fast-mode detector (Task 1 spike + Task 3.1 parser). Opens the
378
+ * `/fast` panel via the SAME live PTY inject as `/effort` (no re-spawn, no `-p`/credit path — R3.3),
379
+ * collects the panel text on a temporary onData listener, classifies it with {@link classifyFastModeSignal},
380
+ * then writes Esc to dismiss the panel. Fails CLOSED (returns `false`) on timeout, a broken/dead PTY, or
381
+ * any throw (R1.2).
382
+ *
383
+ * NOT the production default: it writes to the PTY at probe time, which is safe only when the input box
384
+ * is idle. Wiring it as {@link defaultFastModeProbe} would break the read-only-load (R4.3) and
385
+ * no-Ctrl+U-in-closed-loop invariants (an unsolicited session-start write). It is exported so it can be
386
+ * injected via `deps.fastModeProbe` once the R7.3 live-proof validates it on a fast-available account and
387
+ * a non-intrusive (idle-gated) wiring lands. The pure classifier it delegates to IS unit-tested against
388
+ * the spike's live capture; this thin live-drive glue is exercised offline via a fake signal-emitting pty.
389
+ */
390
+ export declare const driveFastModeProbe: FastModeProbe;
337
391
  /** Optional bundle of injectable dependencies for {@link ClaudeAcpAgent} (Degrau-1 PTY engine). */
338
392
  export interface AgentDeps {
339
393
  /** Override the PTY-engine + JSONL-watcher start (production default: {@link defaultStartEngine}). */
@@ -438,6 +492,12 @@ export interface AgentDeps {
438
492
  }) => Promise<{
439
493
  summary: string;
440
494
  } | undefined>;
495
+ /**
496
+ * Story 073 (R1) — override the fast-mode availability probe (default: {@link defaultFastModeProbe},
497
+ * which fails closed until the live spike wires the real detector). Tests inject a fake returning
498
+ * `true`/`false` to exercise the toggle's advertise/apply/reconcile paths hermetically.
499
+ */
500
+ fastModeProbe?: FastModeProbe;
441
501
  }
442
502
  /**
443
503
  * Production default for the {@link StartEngine} seam. Spawns the subscription `claude` TUI under a
@@ -611,6 +671,8 @@ export declare class ClaudeAcpAgent implements Agent {
611
671
  /** Story 056 (#812) — SDK session-metadata reader for the end-of-turn title push; see
612
672
  * {@link AgentDeps.getSessionInfo}. */
613
673
  private readonly getSessionInfo;
674
+ /** Story 073 (R1) — fast-mode availability probe seam; see {@link AgentDeps.fastModeProbe}. */
675
+ private readonly fastModeProbe;
614
676
  /** Live PTY-engine registry shared with the per-session engines (story 014 cleanup map). */
615
677
  private readonly engines;
616
678
  constructor(client: AgentSideConnection, logger?: Logger, engine?: Engine, deps?: AgentDeps);
@@ -758,6 +820,35 @@ export declare class ClaudeAcpAgent implements Agent {
758
820
  * sendPrompt's own submit `\r` is sufficient and NO confirm Enter is scheduled.
759
821
  */
760
822
  private injectEffortCommand;
823
+ /**
824
+ * Story 073 (R3) — apply a fast-mode toggle LIVE via `/fast on|off`, mirroring {@link applyEffortChange}
825
+ * exactly: a side-channel PTY write, no re-spawn, no turn, works before the first interaction. A no-op
826
+ * (same on/off state) applies nothing; mid-turn it defers (pendingFastInjection) and flushes when the
827
+ * turn settles. `enabled` is the resolved boolean state (story 074 R4.3 — resolveFastModeEnabled maps
828
+ * a boolean payload OR the on/off string to it). NO billing/spawn/credential change (R3.3).
829
+ */
830
+ private applyFastModeChange;
831
+ /**
832
+ * Side-channel `/fast on|off` write — synchronous, resolves immediately (never a turn). In claude
833
+ * 2.1.201 `/fast` is a `local-jsx` command: `/fast on|off` opens the "Fast mode (research preview)"
834
+ * confirmation panel (`tengu_fast_mode_picker_shown`) and leaves it OPEN — the arg pre-selects the
835
+ * target but does NOT auto-apply. So, exactly like {@link injectModelCommand}'s "Switch model?"
836
+ * dialog, schedule ONE blind confirm Enter once the panel has rendered; if no panel appears (same
837
+ * state / flag flipped) Enter-on-empty-input is a harmless no-op. (Superseded the earlier INLINE
838
+ * assumption, which left the panel unconfirmed so the toggle never took — story 073 R7.3 live-proof.)
839
+ */
840
+ private injectFastCommand;
841
+ /**
842
+ * Story 073 (R1) — (re-)probe fast-mode availability for a session and reconcile the `fast` toggle.
843
+ * On a non-Opus model it forces the toggle OFF/absent WITHOUT probing (R4.1); on an Opus model it
844
+ * consults the injectable {@link FastModeProbe} (production default fails closed), caches the result
845
+ * (R1.3), rebuilds `configOptions`, and emits a `config_option_update` only when the visible option
846
+ * set changes. Fire-and-forget from createSession + the model-switch reconcile (R4.2).
847
+ */
848
+ private refreshFastMode;
849
+ /** Story 073 — rebuild `configOptions` from the session's current selections (model/effort/agent) plus
850
+ * the fast-mode state, without re-globbing agents. Used by {@link refreshFastMode}. */
851
+ private rebuildConfigOptionsPreserving;
761
852
  /**
762
853
  * Story 056 (R3.3/R3.4) — apply a main-thread agent-persona change. Like effort, the persona has no
763
854
  * live mid-session mechanism (`--agent "<name>"` is a spawn flag), so a change re-spawns in place
@@ -934,9 +1025,9 @@ export declare function runAcp(deps?: AgentDeps): {
934
1025
  * not call), as detailed below.
935
1026
  *
936
1027
  * Story 068 (R1, R1.1, R1.2): consults the static {@link MODEL_CONTEXT_WINDOWS}
937
- * alias→window map FIRST (an exact catalog-`value` hit — `opus`=1M, `sonnet`=200K,
938
- * `sonnet[1m]`=1M, `haiku`=200K, `default`/`opusplan`=200K conservative). This
939
- * fixes `opus` having wrongly reported 200K. An alias absent from the map then
1028
+ * alias→window map FIRST (an exact catalog-`value` hit — `default`/`fable5`/`opus`/
1029
+ * `sonnet`=1M, `haiku`=200K). This fixes `opus` having wrongly reported 200K, and
1030
+ * `sonnet` now seeds 1M (Sonnet 5 is native 1M). An alias absent from the map then
940
1031
  * falls back to the legacy `\b1m\b` inference: Anthropic 1M-context variants
941
1032
  * encode "1m" as a distinct token in the SDK model ID (e.g., "claude-opus-4-6-1m"),
942
1033
  * which `\b1m\b` catches without also matching "10m" or embedded substrings.
package/dist/acp-agent.js CHANGED
@@ -24,7 +24,7 @@ import { guardEvent } from "./billing/entrypoint-guard.js";
24
24
  import { usageUpdatesFor } from "./usage.js";
25
25
  import { createTurnResolver } from "./end-of-turn.js";
26
26
  import { sendPrompt } from "./engine-pty.js";
27
- import { MODEL_CATALOG, MODEL_CONTEXT_WINDOWS, MODEL_ID_CONTEXT_WINDOWS, modelSelectorDescription, DEFAULT_MODEL_INFO, ULTRACODE_EFFORT, ULTRACODE_EFFORT_LEVEL, ULTRACODE_EFFORT_LABEL, } from "./model-catalog.js";
27
+ import { MODEL_CATALOG, MODEL_CONTEXT_WINDOWS, MODEL_ID_CONTEXT_WINDOWS, modelSelectorDescription, DEFAULT_MODEL_INFO, 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
28
  // Story 060 (R2.2/R2.3/R3.2) — the declarative spawn-time complement to the live ultracode keyword:
29
29
  // toggle the {ultracode,ultracodeKeywordTrigger} keys in the gate's per-session scratch settings file
30
30
  // (preserving the hook + every other key). Lives in the gate's settings-writer so it reuses durableWrite.
@@ -55,6 +55,83 @@ function sanitizeTitle(text) {
55
55
  return sanitized.slice(0, MAX_TITLE_LENGTH - 1) + "…";
56
56
  }
57
57
  export const DEFAULT_CONTEXT_WINDOW = 200000;
58
+ /** Production default — fail-closed (R1.2), invariant-safe: performs NO PTY write, so it preserves the
59
+ * read-only-load (R4.3) and no-unsolicited-Ctrl+U invariants. The live signal is characterized (see
60
+ * {@link classifyFastModeSignal}) and the live driver is {@link driveFastModeProbe}; wiring it as the
61
+ * default is deferred to the R7.3 live-proof + a non-intrusive (idle-gated) wiring follow-up. */
62
+ export const defaultFastModeProbe = () => false;
63
+ /** Story 073 (R1) — bounded window the live driver waits for the `/fast` panel to render before failing
64
+ * closed, polled every {@link FAST_PROBE_POLL_MS}. Generous because at session start the TUI needs a
65
+ * beat to become input-ready. While still pending, the `/fast` inject is re-sent every
66
+ * {@link FAST_PROBE_REINJECT_MS} — a session-start TUI can swallow the first inject before it is
67
+ * input-ready (the createSession race the R7.3 live-proof surfaced), so a single inject would miss it. */
68
+ const FAST_PROBE_WINDOW_MS = 6000;
69
+ const FAST_PROBE_POLL_MS = 150;
70
+ const FAST_PROBE_REINJECT_MS = 2000;
71
+ /**
72
+ * Story 073 (R1) — the OPT-IN live fast-mode detector (Task 1 spike + Task 3.1 parser). Opens the
73
+ * `/fast` panel via the SAME live PTY inject as `/effort` (no re-spawn, no `-p`/credit path — R3.3),
74
+ * collects the panel text on a temporary onData listener, classifies it with {@link classifyFastModeSignal},
75
+ * then writes Esc to dismiss the panel. Fails CLOSED (returns `false`) on timeout, a broken/dead PTY, or
76
+ * any throw (R1.2).
77
+ *
78
+ * NOT the production default: it writes to the PTY at probe time, which is safe only when the input box
79
+ * is idle. Wiring it as {@link defaultFastModeProbe} would break the read-only-load (R4.3) and
80
+ * no-Ctrl+U-in-closed-loop invariants (an unsolicited session-start write). It is exported so it can be
81
+ * injected via `deps.fastModeProbe` once the R7.3 live-proof validates it on a fast-available account and
82
+ * a non-intrusive (idle-gated) wiring lands. The pure classifier it delegates to IS unit-tested against
83
+ * the spike's live capture; this thin live-drive glue is exercised offline via a fake signal-emitting pty.
84
+ */
85
+ export const driveFastModeProbe = async ({ pty }) => {
86
+ let sub;
87
+ try {
88
+ let buffer = "";
89
+ sub = pty.onData((d) => {
90
+ buffer += d;
91
+ });
92
+ // Open the panel with the SAME seam every live inject uses (Ctrl+U clear + `/fast` + \r). Safe ONLY on
93
+ // an idle input box; interactive-only, so billing is untouched (R3.3).
94
+ const openPanel = () => {
95
+ sendPrompt(pty, "/fast", (fn) => fn());
96
+ };
97
+ openPanel();
98
+ const deadline = Date.now() + FAST_PROBE_WINDOW_MS;
99
+ let nextReinject = Date.now() + FAST_PROBE_REINJECT_MS;
100
+ while (Date.now() < deadline) {
101
+ await new Promise((resolve) => setTimeout(resolve, FAST_PROBE_POLL_MS));
102
+ const verdict = classifyFastModeSignal(buffer);
103
+ if (verdict === "available")
104
+ return true;
105
+ if (verdict === "unavailable")
106
+ return false;
107
+ // "pending" → the panel has not rendered a decisive line yet. A session-start TUI may have swallowed
108
+ // the inject before it was input-ready, so re-open periodically until it takes. We ONLY re-inject
109
+ // while pending (no panel rendered), so an already-open panel is never disturbed.
110
+ if (Date.now() >= nextReinject) {
111
+ openPanel();
112
+ nextReinject = Date.now() + FAST_PROBE_REINJECT_MS;
113
+ }
114
+ }
115
+ return false; // window elapsed without a decisive panel → fail closed (R1.2)
116
+ }
117
+ catch {
118
+ return false; // dead/broken PTY or any inject error → fail closed (R1.2)
119
+ }
120
+ finally {
121
+ try {
122
+ pty.write("\x1b"); // Esc — dismiss the `/fast` panel (raw escape, NEVER via sendPrompt — GOTCHA)
123
+ }
124
+ catch {
125
+ /* pty already gone — nothing to dismiss */
126
+ }
127
+ try {
128
+ sub?.dispose();
129
+ }
130
+ catch {
131
+ /* listener already disposed */
132
+ }
133
+ }
134
+ };
58
135
  /**
59
136
  * No-op {@link IPty} stub for the Degrau-1 replay-only load path: there is no live `claude` process,
60
137
  * but the session record's `pty` field is typed `IPty`. Every method is inert — teardown's `kill()`
@@ -552,6 +629,7 @@ export class ClaudeAcpAgent {
552
629
  this.logger = logger ?? console;
553
630
  this.engine = engine;
554
631
  this.startEngine = deps.startEngine ?? defaultStartEngine;
632
+ this.fastModeProbe = deps.fastModeProbe ?? defaultFastModeProbe;
555
633
  // Story 043 (R2.1): when liveDiff is ON, the live JSONL reader is the diff-enriched reader
556
634
  // (getSessionMessages + uuid→toolUseResult hydration), which restores the story-021 Edit/Write
557
635
  // diff on BOTH the live pump and the session/load replay (both read this.getMessages once). The
@@ -1061,6 +1139,26 @@ export class ClaudeAcpAgent {
1061
1139
  if (!session) {
1062
1140
  throw new Error("Session not found");
1063
1141
  }
1142
+ // Story 074 (#828, R4.3): the `fast` option may be advertised as a boolean (when the client
1143
+ // advertised boolean config options) OR as the on/off select. A boolean payload has no select
1144
+ // `options` to validate against and would trip the string-only guard below — resolve it directly and
1145
+ // apply it via the SAME PTY `/fast on|off` inject (mechanism unchanged), then reflect the toggle in
1146
+ // the option's currentValue (boolean or on/off, matching how it was advertised). The on/off STRING
1147
+ // payload still flows through the generic select validation below. NO createSession/prompt touch.
1148
+ if (params.configId === FAST_MODE_CONFIG_ID && typeof params.value === "boolean") {
1149
+ const option = session.configOptions.find((o) => o.id === FAST_MODE_CONFIG_ID);
1150
+ if (!option) {
1151
+ throw new Error(`Unknown config option: ${params.configId}`);
1152
+ }
1153
+ const enabled = resolveFastModeEnabled(params.value);
1154
+ this.applyFastModeChange(session, enabled);
1155
+ session.configOptions = session.configOptions.map((o) => o.id === FAST_MODE_CONFIG_ID
1156
+ ? o.type === "boolean"
1157
+ ? { ...o, currentValue: enabled }
1158
+ : { ...o, currentValue: enabled ? FAST_MODE_ON : FAST_MODE_OFF }
1159
+ : o);
1160
+ return { configOptions: session.configOptions };
1161
+ }
1064
1162
  if (typeof params.value !== "string") {
1065
1163
  throw new Error(`Invalid value for config option ${params.configId}: ${params.value}`);
1066
1164
  }
@@ -1142,6 +1240,13 @@ export class ClaudeAcpAgent {
1142
1240
  // skipped so the prior currentValue stays unchanged (R3.7-style failure path).
1143
1241
  await this.applyAgentChange(params.sessionId, session, resolvedValue);
1144
1242
  }
1243
+ else if (params.configId === FAST_MODE_CONFIG_ID) {
1244
+ // Story 073 (R3): fast mode is a LIVE `/fast on|off` inject (mirrors /effort — no re-spawn, works
1245
+ // pre-first-interaction, defers mid-turn). It never throws, so applyConfigOptionValue below always
1246
+ // commits the new currentValue (optimistic, like /effort). This is the SELECT (on/off string)
1247
+ // path; a boolean payload is resolved earlier (story 074, R4.3). resolveFastModeEnabled unifies both.
1248
+ this.applyFastModeChange(session, resolveFastModeEnabled(resolvedValue));
1249
+ }
1145
1250
  await this.applyConfigOptionValue(params.sessionId, session, params.configId, resolvedValue);
1146
1251
  return { configOptions: session.configOptions };
1147
1252
  }
@@ -1256,6 +1361,12 @@ export class ClaudeAcpAgent {
1256
1361
  session.pendingEffortInjection = undefined;
1257
1362
  this.injectEffortCommand(session, effort);
1258
1363
  }
1364
+ // Story 073 (R3.1) — flush a deferred `/fast on|off` injection too (last-write-wins).
1365
+ const fast = session.pendingFastInjection;
1366
+ if (fast !== undefined) {
1367
+ session.pendingFastInjection = undefined;
1368
+ this.injectFastCommand(session, fast);
1369
+ }
1259
1370
  }
1260
1371
  /**
1261
1372
  * Story 046 (R3.3, design §6b) — drive the TUI to `target` with closed-loop raw Shift+Tab. Writes
@@ -1493,6 +1604,86 @@ export class ClaudeAcpAgent {
1493
1604
  injectEffortCommand(session, level) {
1494
1605
  sendPrompt(session.pty, `/effort ${level}`, (fn) => fn());
1495
1606
  }
1607
+ /**
1608
+ * Story 073 (R3) — apply a fast-mode toggle LIVE via `/fast on|off`, mirroring {@link applyEffortChange}
1609
+ * exactly: a side-channel PTY write, no re-spawn, no turn, works before the first interaction. A no-op
1610
+ * (same on/off state) applies nothing; mid-turn it defers (pendingFastInjection) and flushes when the
1611
+ * turn settles. `enabled` is the resolved boolean state (story 074 R4.3 — resolveFastModeEnabled maps
1612
+ * a boolean payload OR the on/off string to it). NO billing/spawn/credential change (R3.3).
1613
+ */
1614
+ applyFastModeChange(session, enabled) {
1615
+ if (enabled === (session.fastModeOn ?? false))
1616
+ return; // no state change → no-op
1617
+ session.fastModeOn = enabled;
1618
+ if (session.turnDetector !== undefined) {
1619
+ // A turn is in flight — injecting mid-turn corrupts the PTY input. Defer (mirrors /effort, /model).
1620
+ session.pendingFastInjection = enabled;
1621
+ return;
1622
+ }
1623
+ this.injectFastCommand(session, enabled);
1624
+ }
1625
+ /**
1626
+ * Side-channel `/fast on|off` write — synchronous, resolves immediately (never a turn). In claude
1627
+ * 2.1.201 `/fast` is a `local-jsx` command: `/fast on|off` opens the "Fast mode (research preview)"
1628
+ * confirmation panel (`tengu_fast_mode_picker_shown`) and leaves it OPEN — the arg pre-selects the
1629
+ * target but does NOT auto-apply. So, exactly like {@link injectModelCommand}'s "Switch model?"
1630
+ * dialog, schedule ONE blind confirm Enter once the panel has rendered; if no panel appears (same
1631
+ * state / flag flipped) Enter-on-empty-input is a harmless no-op. (Superseded the earlier INLINE
1632
+ * assumption, which left the panel unconfirmed so the toggle never took — story 073 R7.3 live-proof.)
1633
+ */
1634
+ injectFastCommand(session, on) {
1635
+ sendPrompt(session.pty, on ? "/fast on" : "/fast off", (fn) => fn());
1636
+ // Confirm the fast-mode panel — blind + scheduled, mirroring the /model "Switch?" confirm.
1637
+ this.schedule(() => {
1638
+ if (session.engine?.isDisposed)
1639
+ return; // PTY exited meanwhile → nothing to confirm
1640
+ session.pty.write("\r");
1641
+ }, MODEL_CONFIRM_DELAY_MS);
1642
+ }
1643
+ /**
1644
+ * Story 073 (R1) — (re-)probe fast-mode availability for a session and reconcile the `fast` toggle.
1645
+ * On a non-Opus model it forces the toggle OFF/absent WITHOUT probing (R4.1); on an Opus model it
1646
+ * consults the injectable {@link FastModeProbe} (production default fails closed), caches the result
1647
+ * (R1.3), rebuilds `configOptions`, and emits a `config_option_update` only when the visible option
1648
+ * set changes. Fire-and-forget from createSession + the model-switch reconcile (R4.2).
1649
+ */
1650
+ async refreshFastMode(sessionId, session) {
1651
+ const modelOpt = session.configOptions.find((o) => o.id === "model");
1652
+ const modelId = typeof modelOpt?.currentValue === "string" ? modelOpt.currentValue : DEFAULT_MODEL_INFO.value;
1653
+ let available;
1654
+ if (!isFastModeCapableModel(modelId)) {
1655
+ available = false; // non-Opus → never advertise, never probe (R2.2/R4.1)
1656
+ }
1657
+ else {
1658
+ try {
1659
+ available = await this.fastModeProbe({ pty: session.pty, cwd: session.cwd });
1660
+ }
1661
+ catch {
1662
+ available = false; // a throwing probe fails CLOSED (R1.2)
1663
+ }
1664
+ }
1665
+ const before = session.fastModeAvailable ?? false;
1666
+ session.fastModeAvailable = available;
1667
+ if (available === before)
1668
+ return; // no visible change → no rebuild/emit
1669
+ session.configOptions = this.rebuildConfigOptionsPreserving(session, modelId);
1670
+ // The session may have been torn down while the probe was awaited — guard the emit.
1671
+ if (!this.sessions[sessionId])
1672
+ return;
1673
+ await this.client.sessionUpdate({
1674
+ sessionId,
1675
+ update: { sessionUpdate: "config_option_update", configOptions: session.configOptions },
1676
+ });
1677
+ }
1678
+ /** Story 073 — rebuild `configOptions` from the session's current selections (model/effort/agent) plus
1679
+ * the fast-mode state, without re-globbing agents. Used by {@link refreshFastMode}. */
1680
+ rebuildConfigOptionsPreserving(session, modelId) {
1681
+ const effortOpt = session.configOptions.find((o) => o.id === "effort");
1682
+ const currentEffort = typeof effortOpt?.currentValue === "string" ? effortOpt.currentValue : undefined;
1683
+ const agentOpt = session.configOptions.find((o) => o.id === "agent");
1684
+ const currentAgent = typeof agentOpt?.currentValue === "string" ? agentOpt.currentValue : undefined;
1685
+ return buildConfigOptions(session.modes, modelId, session.modelInfos, currentEffort, session.agents ?? [], currentAgent, session.fastModeAvailable ?? false, session.fastModeOn ?? false, clientSupportsBooleanConfigOptions(this.clientCapabilities));
1686
+ }
1496
1687
  /**
1497
1688
  * Story 056 (R3.3/R3.4) — apply a main-thread agent-persona change. Like effort, the persona has no
1498
1689
  * live mid-session mechanism (`--agent "<name>"` is a spawn flag), so a change re-spawns in place
@@ -2048,7 +2239,20 @@ export class ClaudeAcpAgent {
2048
2239
  // keeps the option absent when none were discovered (the gate).
2049
2240
  const agentOpt = session.configOptions.find((o) => o.id === "agent");
2050
2241
  const currentAgent = typeof agentOpt?.currentValue === "string" ? agentOpt.currentValue : undefined;
2051
- session.configOptions = buildConfigOptions(session.modes, value, session.modelInfos, currentEffort, session.agents ?? [], currentAgent);
2242
+ // Story 073 (R4.1) — a model switch turns fast mode OFF and drops its availability (mirroring the
2243
+ // CLI's "switching to other models turns off fast mode"). The rebuild below therefore omits the
2244
+ // toggle; if the new model is Opus, refreshFastMode (kicked off after) re-probes and re-advertises.
2245
+ if (previousModelId !== value) {
2246
+ session.fastModeOn = false;
2247
+ session.fastModeAvailable = false;
2248
+ }
2249
+ session.configOptions = buildConfigOptions(session.modes, value, session.modelInfos, currentEffort, session.agents ?? [], currentAgent, session.fastModeAvailable ?? false, session.fastModeOn ?? false, clientSupportsBooleanConfigOptions(this.clientCapabilities));
2250
+ // Story 073 (R4.2) — on a switch TO an Opus model, re-run availability detection out of band and
2251
+ // re-advertise the toggle (as off) when available. Fire-and-forget: the synchronous response above
2252
+ // ships without the toggle; refreshFastMode emits a follow-up config_option_update once it settles.
2253
+ if (previousModelId !== value && isFastModeCapableModel(value)) {
2254
+ void this.refreshFastMode(sessionId, session);
2255
+ }
2052
2256
  // === SEAM(023) Group 1: the SDK effort sync (query.applyFlagSettings) after a model switch is
2053
2257
  // dropped — configOptions already reflects the new effort locally.
2054
2258
  // Degrau 2 (030/032): PTY-backed control. ===
@@ -2312,6 +2516,11 @@ export class ClaudeAcpAgent {
2312
2516
  taskState,
2313
2517
  gate,
2314
2518
  };
2519
+ // Story 073 (R1) — the seed model is Opus (`default`), so probe fast-mode availability out of band
2520
+ // and advertise the toggle when available. Fire-and-forget (like sendAvailableCommandsUpdate): the
2521
+ // response below ships the seed options; refreshFastMode emits a follow-up config_option_update. The
2522
+ // production probe fails closed, so today's stream is byte-for-byte unaffected until the spike wires it.
2523
+ void this.refreshFastMode(startedSessionId, this.sessions[startedSessionId]);
2315
2524
  return {
2316
2525
  sessionId: startedSessionId,
2317
2526
  modes,
@@ -2367,7 +2576,7 @@ function buildAvailableModes(modelInfo) {
2367
2576
  // `applyFlagSettings` in @anthropic-ai/claude-agent-sdk. Mapping both the
2368
2577
  // `"default"` sentinel and `undefined` (effort option absent for the model) to
2369
2578
  // `null` ensures any previously-applied flag is actually cleared.
2370
- function buildConfigOptions(modes, currentModelId, modelInfos, currentEffortLevel, agents = [], currentAgent) {
2579
+ function buildConfigOptions(modes, currentModelId, modelInfos, currentEffortLevel, agents = [], currentAgent, fastAvailable = false, currentFast = false, fastUsesBooleanOption = false) {
2371
2580
  const options = [
2372
2581
  {
2373
2582
  id: "mode",
@@ -2398,6 +2607,15 @@ function buildConfigOptions(modes, currentModelId, modelInfos, currentEffortLeve
2398
2607
  })),
2399
2608
  },
2400
2609
  ];
2610
+ // Story 073 (R2) — the fast-mode toggle, positioned right after the model selector. GATED on an
2611
+ // Opus alias (R2.2, isFastModeCapableModel) AND detected availability (R1, fastAvailable): fast mode
2612
+ // is Opus-only and account-gated, so a non-Opus model or an unavailable account omits it entirely.
2613
+ // Story 074 (#828, R4.1): the option is emitted as `type:"boolean"` when the client advertised
2614
+ // boolean config options (fastUsesBooleanOption), else the `on`/`off` select fallback — via the
2615
+ // model-catalog helper. currentValue mirrors the session's fast-mode state.
2616
+ if (isFastModeCapableModel(currentModelId) && fastAvailable) {
2617
+ options.push(createFastModeConfigOption(currentFast, fastUsesBooleanOption));
2618
+ }
2401
2619
  // Add effort level option based on the currently selected model
2402
2620
  const currentModelInfo = modelInfos.find((m) => m.value === currentModelId);
2403
2621
  const supportedLevels = currentModelInfo?.supportsEffort
@@ -2702,6 +2920,12 @@ export function toAcpNotifications(content, role, sessionId, toolUseCache, clien
2702
2920
  const registerHooks = options?.registerHooks !== false;
2703
2921
  const supportsTerminalOutput = options?.clientCapabilities?._meta?.["terminal_output"] === true;
2704
2922
  if (typeof content === "string") {
2923
+ // Story 074 (#841): an empty full-string content block must emit NO message chunk
2924
+ // (an empty agent_message_chunk breaks strict ACP clients — e.g. JetBrains Air
2925
+ // freezes the transcript). Mirrors the empty-thinking guard (#793). The
2926
+ // `case "text"`/`text_delta` block path stays DEAD (no content_block_delta, 034).
2927
+ if (content.length === 0)
2928
+ return [];
2705
2929
  const update = {
2706
2930
  sessionUpdate: role === "assistant" ? "agent_message_chunk" : "user_message_chunk",
2707
2931
  content: {
@@ -3030,9 +3254,9 @@ export function runAcp(deps) {
3030
3254
  * not call), as detailed below.
3031
3255
  *
3032
3256
  * Story 068 (R1, R1.1, R1.2): consults the static {@link MODEL_CONTEXT_WINDOWS}
3033
- * alias→window map FIRST (an exact catalog-`value` hit — `opus`=1M, `sonnet`=200K,
3034
- * `sonnet[1m]`=1M, `haiku`=200K, `default`/`opusplan`=200K conservative). This
3035
- * fixes `opus` having wrongly reported 200K. An alias absent from the map then
3257
+ * alias→window map FIRST (an exact catalog-`value` hit — `default`/`fable5`/`opus`/
3258
+ * `sonnet`=1M, `haiku`=200K). This fixes `opus` having wrongly reported 200K, and
3259
+ * `sonnet` now seeds 1M (Sonnet 5 is native 1M). An alias absent from the map then
3036
3260
  * falls back to the legacy `\b1m\b` inference: Anthropic 1M-context variants
3037
3261
  * encode "1m" as a distinct token in the SDK model ID (e.g., "claude-opus-4-6-1m"),
3038
3262
  * which `\b1m\b` catches without also matching "10m" or embedded substrings.
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { resolveSettings } from "@anthropic-ai/claude-agent-sdk";
3
- import { runAcp } from "./acp-agent.js";
3
+ import { runAcp, driveFastModeProbe } from "./acp-agent.js";
4
4
  import { resolveClaudePath } from "./claude-path.js";
5
5
  import { usageUpdateEnabled } from "./usage-env.js";
6
6
  import { liveDiffEnabled } from "./live-diff-env.js";
@@ -94,7 +94,25 @@ else {
94
94
  // the unit suite — which imports modules directly without this flag — stays on the hermetic glob
95
95
  // fallback and never spawns the real binary. `??=` keeps a user opt-out (`FORK_AGENT_PROBE=0`).
96
96
  process.env.FORK_AGENT_PROBE ??= "1";
97
- const { connection, agent } = runAcp({ usageUpdate, gate, liveDiff, liveSubagentWatch });
97
+ // Story 073 (R1 / R7.3): OPT-IN live fast-mode detector. OFF by default — driveFastModeProbe writes
98
+ // `/fast` to the PTY at session start, which would break the read-only-load (R4.3)/no-Ctrl+U invariants
99
+ // as a default (see ## Spike findings). `FAST_MODE_LIVE=1` wires it for the manual R7.3 live-proof (and
100
+ // is the candidate seam for the idle-gated wiring follow-up). Unset → the fail-closed default stands.
101
+ // `FAST_MODE_FORCE=1` force-advertises the toggle WITHOUT probing (skips the account gate) — the R7.3
102
+ // UI proof on a gated account: it makes the selector render (position/tooltip/hide-on-non-Opus) even
103
+ // when fast credits are absent. It does NOT make fast actually work — toggling On still hits the gate.
104
+ const fastModeProbe = process.env.FAST_MODE_FORCE === "1"
105
+ ? () => true
106
+ : process.env.FAST_MODE_LIVE === "1"
107
+ ? driveFastModeProbe
108
+ : undefined;
109
+ const { connection, agent } = runAcp({
110
+ usageUpdate,
111
+ gate,
112
+ liveDiff,
113
+ liveSubagentWatch,
114
+ fastModeProbe,
115
+ });
98
116
  async function shutdown() {
99
117
  await agent.dispose().catch((err) => {
100
118
  console.error("Error during cleanup:", err);
@@ -1,4 +1,5 @@
1
1
  import type { ModelInfo } from "@anthropic-ai/claude-agent-sdk";
2
+ import type { ClientCapabilities, SessionConfigOption } from "@agentclientprotocol/sdk";
2
3
  /**
3
4
  * Effort levels offered for reasoning-capable models — the SDK's `supportedEffortLevels` vocabulary.
4
5
  * Story 060: exported so the ultracode guard test can assert membership stays the five real levels
@@ -21,30 +22,32 @@ export declare const ULTRACODE_EFFORT_LABEL = "ultracode (xhigh + orchestration)
21
22
  * `claude` TUI alias accepted by `/model <alias>` (live) and `--model <alias>` (spawn). `default` is
22
23
  * first and is the safe fallback.
23
24
  *
24
- * ORDER + membership mirror the ORIGINAL's `/model` picker, LIVE-VERIFIED against 2.1.195 (PTY probe):
25
- * `Default (recommended)`, `Opus`, `Sonnet`, `Sonnet (1M context)`, `Haiku`. The original gets this
26
- * from the SDK `supportedModels()` the fork cut, so we curate it statically. The 1M alias is literally
27
- * `sonnet[1m]` (`/model sonnet[1m]` accepted; `sonnet-1m` → "not found"). `opusplan` is a fork-only
28
- * EXTRA (a real `claude` plan-mode preset the original does not list) kept as the trailing entry.
25
+ * ORDER + membership: `Default (recommended)`, `Fable 5`, `Opus`, `Sonnet`, `Haiku`. The original gets
26
+ * its list from the SDK `supportedModels()` the fork cut, so we curate it statically. `fable5` (`/model
27
+ * fable5` — the Claude 5 family's top model, released 2026-07-01) sits right after `default`. The
28
+ * redundant `sonnet[1m]` alias was dropped: Sonnet 5 is natively 1M, so plain `sonnet` already IS the 1M
29
+ * model. The fork-only `opusplan` extra was dropped too (three Sonnet-flavored entries + inconsistent
30
+ * Opus thinking made it more confusing than useful).
29
31
  *
30
- * Effort-capable models (`default`/`opus`/`sonnet`/`sonnet[1m]`) carry `supportsEffort` +
31
- * `supportedEffortLevels`; `haiku`/`opusplan` advertise none. `supportsAutoMode: true` on the same four
32
- * surfaces the `auto` permission mode (a model classifier) — the original drops `auto` on `haiku`
33
- * (the SDK signal `reconcileModeFromTranscript` clamps), so haiku/opusplan omit it.
32
+ * Effort-capable models (`default`/`fable5`/`opus`/`sonnet`) carry `supportsEffort` +
33
+ * `supportedEffortLevels`; `haiku` advertises none. `supportsAutoMode: true` on the same four surfaces
34
+ * the `auto` permission mode (a model classifier) — the original drops `auto` on `haiku` (the SDK signal
35
+ * `reconcileModeFromTranscript` clamps), so haiku omits it.
34
36
  */
35
37
  export declare const MODEL_CATALOG: ModelInfo[];
36
38
  /**
37
39
  * Story 068 (R1, R1.1, R2) — the REAL per-alias context window, keyed by the EXACT {@link MODEL_CATALOG}
38
- * `value`. These windows are NOT uniform: `opus` is natively 1M, `sonnet`/`haiku` are 200K, and
39
- * `sonnet[1m]` is the explicit 1M variant. This map is the single source of truth that
40
- * `inferContextWindowFromModel` (acp-agent.ts) consults BEFORE the `\b1m\b` regex fallback — the bug it
41
- * fixes is `opus` having wrongly reported 200K (the regex only ever matched the literal `1m` token).
40
+ * `value`. These windows are NOT uniform: `default`/`fable5`/`opus`/`sonnet` are natively 1M and `haiku`
41
+ * is 200K. This map is the single source of truth that `inferContextWindowFromModel` (acp-agent.ts)
42
+ * consults BEFORE the `\b1m\b` regex fallback — the bug it fixes is `opus` having wrongly reported 200K
43
+ * (the regex only ever matched the literal `1m` token).
42
44
  *
43
- * Story 069 (R2): `default` and `opusplan` seed to 1M — `default` is the recommended Opus (the claude TUI's
44
- * `/model default` resolves to `claude-opus-4-8[1m]`, a 1M model) and `opusplan` plans with Opus. This is
45
- * only the PRE-FIRST-TURN seed: once a turn arrives, `inferContextWindowFromModelId` (story 069)
46
- * AUTHORITATIVELY refines the window from the transcript's real `model`. Keys MIRROR `MODEL_CATALOG`
47
- * `value`s; the drift guard lives in the test (068 anti-drift: every catalog value has an explicit entry).
45
+ * `sonnet` seeds to 1M because plain `sonnet` now resolves to Sonnet 5, which is natively 1M (the
46
+ * redundant `sonnet[1m]` alias was dropped). `default` is the recommended Opus (the claude TUI's `/model
47
+ * default` resolves to `claude-opus-4-8[1m]`, a 1M model) and `fable5` is Fable 5 (1M). This is only the
48
+ * PRE-FIRST-TURN seed: once a turn arrives, `inferContextWindowFromModelId` (story 069) AUTHORITATIVELY
49
+ * refines the window from the transcript's real `model`. Keys MIRROR `MODEL_CATALOG` `value`s; the drift
50
+ * guard lives in the test (068 anti-drift: every catalog value has an explicit entry).
48
51
  */
49
52
  export declare const MODEL_CONTEXT_WINDOWS: Record<string, number>;
50
53
  /**
@@ -63,14 +66,70 @@ export declare const MODEL_ID_CONTEXT_WINDOWS: Record<string, number>;
63
66
  * cannot derive the concrete version (the SDK `supportedModels()` was cut), so these MIRROR the LIVE
64
67
  * picker and MUST be re-verified on each model launch (source: the user's live `/model` output). The
65
68
  * static tagline stays on `ModelInfo.description` (069 R3 untouched); this only prepends "<version> · ".
66
- * `opusplan` is intentionally absent — its tagline ("Use Opus in plan mode, Sonnet otherwise") already
67
- * names the models, so it renders bare.
69
+ * Every current catalog entry carries a label; the no-label branch in {@link modelSelectorDescription}
70
+ * stays as a total-function safeguard for any future label-less entry.
68
71
  */
69
72
  export declare const MODEL_VERSION_LABELS: Record<string, string>;
70
73
  /**
71
74
  * Story 072 — compose the Zed selector description: "<version label> · <tagline>", or the bare tagline
72
- * when no label exists (e.g. `opusplan`). PURE + TOTAL: never throws on a missing label or tagline.
75
+ * when no label exists. PURE + TOTAL: never throws on a missing label or tagline.
73
76
  */
74
77
  export declare function modelSelectorDescription(info: ModelInfo): string;
78
+ /**
79
+ * Story 073 (R5.1) — the catalog `value`s that support fast mode (`/fast on|off`). Fast mode "uses
80
+ * Claude Opus with faster output (it does not downgrade to a smaller model)" and is available on Opus
81
+ * 4.8/4.7 only; the CLI turns it off when switching to a non-Opus model. `default` resolves to the
82
+ * recommended Opus, so both `default` and `opus` qualify; `fable5`/`sonnet`/`haiku` do NOT.
83
+ *
84
+ * Kept HERE (not on {@link ModelInfo}) because `ModelInfo` is the SDK shape and cannot carry a
85
+ * fork-only `supportsFastMode` field — the same reason the effort/auto flags that DO exist on the SDK
86
+ * type live inline while this predicate is external.
87
+ */
88
+ export declare const FAST_MODE_MODELS: ReadonlySet<string>;
89
+ /** Story 073 (R5.1) — true when the catalog `value` is an Opus alias that supports fast mode. */
90
+ export declare function isFastModeCapableModel(value: string): boolean;
91
+ /** Story 074 (R4.2) — the fork's fast-mode config-option id, replacing the inline `"fast"` literal. */
92
+ export declare const FAST_MODE_CONFIG_ID = "fast";
93
+ /** Story 074 (R4.2) — the on/off select values, replacing the inline `"on"`/`"off"` literals. */
94
+ export declare const FAST_MODE_ON = "on";
95
+ export declare const FAST_MODE_OFF = "off";
96
+ /**
97
+ * Story 074 (R4.1) — did the client advertise support for boolean session config options
98
+ * (`clientCapabilities.session.configOptions.boolean`)? A present (non-null) object — even `{}` —
99
+ * means the agent may emit `type:"boolean"` entries and the client may send boolean `set_config_option`
100
+ * values. Read from the `initialize()`-stored capabilities; NO createSession/prompt touch (R4.5).
101
+ */
102
+ export declare function clientSupportsBooleanConfigOptions(caps?: ClientCapabilities | null): boolean;
103
+ /**
104
+ * Story 074 (R4.3) — resolve the intended fast-mode ENABLED state from a `set_config_option` payload
105
+ * that may be a boolean (a client using the boolean option) OR the `"on"`/`"off"` string (the select
106
+ * fallback). Any non-`"on"` string (and any other shape) resolves to OFF — a toggle never half-applies.
107
+ */
108
+ export declare function resolveFastModeEnabled(value: unknown): boolean;
109
+ /**
110
+ * Story 074 (R4.1) — build the `fast` config option. Emits `type:"boolean"` (currentValue tracks the
111
+ * toggle) when the client advertised boolean config options, else the `on`/`off` select fallback. The
112
+ * external ACP `id` and on/off values are unchanged from story 073; only the type negotiation aligns
113
+ * with upstream #828. The PTY `/fast on|off` inject mechanism and the FAST_MODE_MODELS gate are kept.
114
+ */
115
+ export declare function createFastModeConfigOption(enabled: boolean, useBooleanOption: boolean): SessionConfigOption;
116
+ /**
117
+ * Story 073 (R1) — the verdict of parsing the `/fast` panel captured from the live PTY:
118
+ * - `"available"` — the panel rendered its On/Off toggle (no gate line) → advertise the toggle.
119
+ * - `"unavailable"` — the panel rendered a gate line ("requires usage credits", etc.) → omit it.
120
+ * - `"pending"` — the panel has not fully rendered yet (or is still checking) → keep waiting; the
121
+ * caller fails CLOSED (treats it as unavailable) once its bounded window elapses.
122
+ */
123
+ export type FastModeSignal = "available" | "unavailable" | "pending";
124
+ /**
125
+ * Story 073 (R1) — classify the `/fast` panel text captured from the live PTY into a {@link FastModeSignal}.
126
+ *
127
+ * Pure and side-effect free so it is unit-testable against the spike's live capture; the live PTY drive
128
+ * that FEEDS it lives behind the `FastModeProbe` seam (acp-agent `defaultFastModeProbe`). Order matters:
129
+ * pending is checked first (its text also matches a gate substring), then the gate markers, then — only
130
+ * once the panel anchor confirms a full render with NO gate line — `available`. Anything else is
131
+ * `pending`, and the caller fails closed on timeout (R1.2).
132
+ */
133
+ export declare function classifyFastModeSignal(raw: string): FastModeSignal;
75
134
  /** The safe fallback entry, kept as a named export so callers can seed/anchor on it without a lookup. */
76
135
  export declare const DEFAULT_MODEL_INFO: ModelInfo;
@@ -26,16 +26,17 @@ export const ULTRACODE_EFFORT_LABEL = "ultracode (xhigh + orchestration)";
26
26
  * `claude` TUI alias accepted by `/model <alias>` (live) and `--model <alias>` (spawn). `default` is
27
27
  * first and is the safe fallback.
28
28
  *
29
- * ORDER + membership mirror the ORIGINAL's `/model` picker, LIVE-VERIFIED against 2.1.195 (PTY probe):
30
- * `Default (recommended)`, `Opus`, `Sonnet`, `Sonnet (1M context)`, `Haiku`. The original gets this
31
- * from the SDK `supportedModels()` the fork cut, so we curate it statically. The 1M alias is literally
32
- * `sonnet[1m]` (`/model sonnet[1m]` accepted; `sonnet-1m` → "not found"). `opusplan` is a fork-only
33
- * EXTRA (a real `claude` plan-mode preset the original does not list) kept as the trailing entry.
29
+ * ORDER + membership: `Default (recommended)`, `Fable 5`, `Opus`, `Sonnet`, `Haiku`. The original gets
30
+ * its list from the SDK `supportedModels()` the fork cut, so we curate it statically. `fable5` (`/model
31
+ * fable5` — the Claude 5 family's top model, released 2026-07-01) sits right after `default`. The
32
+ * redundant `sonnet[1m]` alias was dropped: Sonnet 5 is natively 1M, so plain `sonnet` already IS the 1M
33
+ * model. The fork-only `opusplan` extra was dropped too (three Sonnet-flavored entries + inconsistent
34
+ * Opus thinking made it more confusing than useful).
34
35
  *
35
- * Effort-capable models (`default`/`opus`/`sonnet`/`sonnet[1m]`) carry `supportsEffort` +
36
- * `supportedEffortLevels`; `haiku`/`opusplan` advertise none. `supportsAutoMode: true` on the same four
37
- * surfaces the `auto` permission mode (a model classifier) — the original drops `auto` on `haiku`
38
- * (the SDK signal `reconcileModeFromTranscript` clamps), so haiku/opusplan omit it.
36
+ * Effort-capable models (`default`/`fable5`/`opus`/`sonnet`) carry `supportsEffort` +
37
+ * `supportedEffortLevels`; `haiku` advertises none. `supportsAutoMode: true` on the same four surfaces
38
+ * the `auto` permission mode (a model classifier) — the original drops `auto` on `haiku` (the SDK signal
39
+ * `reconcileModeFromTranscript` clamps), so haiku omits it.
39
40
  */
40
41
  export const MODEL_CATALOG = [
41
42
  {
@@ -47,6 +48,18 @@ export const MODEL_CATALOG = [
47
48
  supportedEffortLevels: REASONING_EFFORT_LEVELS,
48
49
  supportsAutoMode: true,
49
50
  },
51
+ {
52
+ value: "fable5",
53
+ // Bare family name in the title (like Opus/Sonnet/Haiku); the "Fable 5" version lives in the
54
+ // MODEL_VERSION_LABELS prefix that composes the selector description.
55
+ displayName: "Fable",
56
+ // Fable 5 (Claude 5 family, released 2026-07-01) — the most advanced generally available model.
57
+ // Description verbatim from the live `/model` picker of the interactive `claude` CLI.
58
+ description: "Most capable for your hardest and longest-running tasks",
59
+ supportsEffort: true,
60
+ supportedEffortLevels: REASONING_EFFORT_LEVELS,
61
+ supportsAutoMode: true,
62
+ },
50
63
  {
51
64
  value: "opus",
52
65
  displayName: "Opus",
@@ -63,46 +76,32 @@ export const MODEL_CATALOG = [
63
76
  supportedEffortLevels: REASONING_EFFORT_LEVELS,
64
77
  supportsAutoMode: true,
65
78
  },
66
- {
67
- value: "sonnet[1m]",
68
- displayName: "Sonnet (1M context)",
69
- // Story 069 (R3): fork-only 1M variant — the Sonnet description plus its 1M-window note.
70
- description: "Efficient for routine tasks, with a 1M-token context window",
71
- supportsEffort: true,
72
- supportedEffortLevels: REASONING_EFFORT_LEVELS,
73
- supportsAutoMode: true,
74
- },
75
79
  {
76
80
  value: "haiku",
77
81
  displayName: "Haiku",
78
82
  description: "Fastest for quick answers",
79
83
  },
80
- {
81
- value: "opusplan",
82
- displayName: "Opus Plan Mode",
83
- description: "Use Opus in plan mode, Sonnet otherwise",
84
- },
85
84
  ];
86
85
  /**
87
86
  * Story 068 (R1, R1.1, R2) — the REAL per-alias context window, keyed by the EXACT {@link MODEL_CATALOG}
88
- * `value`. These windows are NOT uniform: `opus` is natively 1M, `sonnet`/`haiku` are 200K, and
89
- * `sonnet[1m]` is the explicit 1M variant. This map is the single source of truth that
90
- * `inferContextWindowFromModel` (acp-agent.ts) consults BEFORE the `\b1m\b` regex fallback — the bug it
91
- * fixes is `opus` having wrongly reported 200K (the regex only ever matched the literal `1m` token).
87
+ * `value`. These windows are NOT uniform: `default`/`fable5`/`opus`/`sonnet` are natively 1M and `haiku`
88
+ * is 200K. This map is the single source of truth that `inferContextWindowFromModel` (acp-agent.ts)
89
+ * consults BEFORE the `\b1m\b` regex fallback — the bug it fixes is `opus` having wrongly reported 200K
90
+ * (the regex only ever matched the literal `1m` token).
92
91
  *
93
- * Story 069 (R2): `default` and `opusplan` seed to 1M — `default` is the recommended Opus (the claude TUI's
94
- * `/model default` resolves to `claude-opus-4-8[1m]`, a 1M model) and `opusplan` plans with Opus. This is
95
- * only the PRE-FIRST-TURN seed: once a turn arrives, `inferContextWindowFromModelId` (story 069)
96
- * AUTHORITATIVELY refines the window from the transcript's real `model`. Keys MIRROR `MODEL_CATALOG`
97
- * `value`s; the drift guard lives in the test (068 anti-drift: every catalog value has an explicit entry).
92
+ * `sonnet` seeds to 1M because plain `sonnet` now resolves to Sonnet 5, which is natively 1M (the
93
+ * redundant `sonnet[1m]` alias was dropped). `default` is the recommended Opus (the claude TUI's `/model
94
+ * default` resolves to `claude-opus-4-8[1m]`, a 1M model) and `fable5` is Fable 5 (1M). This is only the
95
+ * PRE-FIRST-TURN seed: once a turn arrives, `inferContextWindowFromModelId` (story 069) AUTHORITATIVELY
96
+ * refines the window from the transcript's real `model`. Keys MIRROR `MODEL_CATALOG` `value`s; the drift
97
+ * guard lives in the test (068 anti-drift: every catalog value has an explicit entry).
98
98
  */
99
99
  export const MODEL_CONTEXT_WINDOWS = {
100
100
  default: 1_000_000,
101
+ fable5: 1_000_000,
101
102
  opus: 1_000_000,
102
- sonnet: 200_000,
103
- "sonnet[1m]": 1_000_000,
103
+ sonnet: 1_000_000,
104
104
  haiku: 200_000,
105
- opusplan: 1_000_000,
106
105
  };
107
106
  /**
108
107
  * Story 069 (R1.1) — the REAL context window per concrete model ID, mirroring the claude CLI's
@@ -130,19 +129,19 @@ export const MODEL_ID_CONTEXT_WINDOWS = {
130
129
  * cannot derive the concrete version (the SDK `supportedModels()` was cut), so these MIRROR the LIVE
131
130
  * picker and MUST be re-verified on each model launch (source: the user's live `/model` output). The
132
131
  * static tagline stays on `ModelInfo.description` (069 R3 untouched); this only prepends "<version> · ".
133
- * `opusplan` is intentionally absent — its tagline ("Use Opus in plan mode, Sonnet otherwise") already
134
- * names the models, so it renders bare.
132
+ * Every current catalog entry carries a label; the no-label branch in {@link modelSelectorDescription}
133
+ * stays as a total-function safeguard for any future label-less entry.
135
134
  */
136
135
  export const MODEL_VERSION_LABELS = {
137
136
  default: "Opus 4.8 with 1M context",
137
+ fable5: "Fable 5 with 1M context",
138
138
  opus: "Opus 4.8 with 1M context",
139
- sonnet: "Sonnet 5",
140
- "sonnet[1m]": "Sonnet 5 with 1M context",
139
+ sonnet: "Sonnet 5 with 1M context",
141
140
  haiku: "Haiku 4.5",
142
141
  };
143
142
  /**
144
143
  * Story 072 — compose the Zed selector description: "<version label> · <tagline>", or the bare tagline
145
- * when no label exists (e.g. `opusplan`). PURE + TOTAL: never throws on a missing label or tagline.
144
+ * when no label exists. PURE + TOTAL: never throws on a missing label or tagline.
146
145
  */
147
146
  export function modelSelectorDescription(info) {
148
147
  const label = MODEL_VERSION_LABELS[info.value];
@@ -151,5 +150,144 @@ export function modelSelectorDescription(info) {
151
150
  return tagline;
152
151
  return tagline ? `${label} · ${tagline}` : label;
153
152
  }
153
+ /**
154
+ * Story 073 (R5.1) — the catalog `value`s that support fast mode (`/fast on|off`). Fast mode "uses
155
+ * Claude Opus with faster output (it does not downgrade to a smaller model)" and is available on Opus
156
+ * 4.8/4.7 only; the CLI turns it off when switching to a non-Opus model. `default` resolves to the
157
+ * recommended Opus, so both `default` and `opus` qualify; `fable5`/`sonnet`/`haiku` do NOT.
158
+ *
159
+ * Kept HERE (not on {@link ModelInfo}) because `ModelInfo` is the SDK shape and cannot carry a
160
+ * fork-only `supportsFastMode` field — the same reason the effort/auto flags that DO exist on the SDK
161
+ * type live inline while this predicate is external.
162
+ */
163
+ export const FAST_MODE_MODELS = new Set(["default", "opus"]);
164
+ /** Story 073 (R5.1) — true when the catalog `value` is an Opus alias that supports fast mode. */
165
+ export function isFastModeCapableModel(value) {
166
+ return FAST_MODE_MODELS.has(value);
167
+ }
168
+ // --- Story 074 / #828 — fast-mode config-option surface (reconcile with upstream v0.57) ----------
169
+ // Upstream #828 exports the fast-mode identity as constants, negotiates `type:"boolean"` when the
170
+ // client advertises it (select fallback otherwise), and resolves a boolean OR on/off payload. The fork
171
+ // adopts that SURFACE while keeping its PTY `/fast on|off` inject and the FAST_MODE_MODELS gate (the
172
+ // SDK `applyFlagSettings`/`fast_mode_state`/`cooldown` reconcile has no PTY equivalent — CUT).
173
+ /** Story 074 (R4.2) — the fork's fast-mode config-option id, replacing the inline `"fast"` literal. */
174
+ export const FAST_MODE_CONFIG_ID = "fast";
175
+ /** Story 074 (R4.2) — the on/off select values, replacing the inline `"on"`/`"off"` literals. */
176
+ export const FAST_MODE_ON = "on";
177
+ export const FAST_MODE_OFF = "off";
178
+ /**
179
+ * Story 074 (R4.1) — did the client advertise support for boolean session config options
180
+ * (`clientCapabilities.session.configOptions.boolean`)? A present (non-null) object — even `{}` —
181
+ * means the agent may emit `type:"boolean"` entries and the client may send boolean `set_config_option`
182
+ * values. Read from the `initialize()`-stored capabilities; NO createSession/prompt touch (R4.5).
183
+ */
184
+ export function clientSupportsBooleanConfigOptions(caps) {
185
+ const booleanCap = caps?.session?.configOptions?.boolean;
186
+ return booleanCap !== null && booleanCap !== undefined;
187
+ }
188
+ /**
189
+ * Story 074 (R4.3) — resolve the intended fast-mode ENABLED state from a `set_config_option` payload
190
+ * that may be a boolean (a client using the boolean option) OR the `"on"`/`"off"` string (the select
191
+ * fallback). Any non-`"on"` string (and any other shape) resolves to OFF — a toggle never half-applies.
192
+ */
193
+ export function resolveFastModeEnabled(value) {
194
+ if (typeof value === "boolean")
195
+ return value;
196
+ return value === FAST_MODE_ON;
197
+ }
198
+ /**
199
+ * Story 074 (R4.1) — build the `fast` config option. Emits `type:"boolean"` (currentValue tracks the
200
+ * toggle) when the client advertised boolean config options, else the `on`/`off` select fallback. The
201
+ * external ACP `id` and on/off values are unchanged from story 073; only the type negotiation aligns
202
+ * with upstream #828. The PTY `/fast on|off` inject mechanism and the FAST_MODE_MODELS gate are kept.
203
+ */
204
+ export function createFastModeConfigOption(enabled, useBooleanOption) {
205
+ const base = {
206
+ id: FAST_MODE_CONFIG_ID,
207
+ name: "Fast Mode",
208
+ description: "Faster Opus output at a higher usage-credit rate (/fast). Turns off on non-Opus models.",
209
+ category: "model",
210
+ };
211
+ if (useBooleanOption) {
212
+ return { ...base, type: "boolean", currentValue: enabled };
213
+ }
214
+ return {
215
+ ...base,
216
+ type: "select",
217
+ currentValue: enabled ? FAST_MODE_ON : FAST_MODE_OFF,
218
+ // Per-option descriptions mirror the `model` selector — Zed renders the selected option's
219
+ // description as the selector tooltip (an omitted per-option description shows no tooltip).
220
+ options: [
221
+ { value: FAST_MODE_OFF, name: "Off", description: "Standard Opus output speed." },
222
+ {
223
+ value: FAST_MODE_ON,
224
+ name: "On",
225
+ description: "Faster Opus output — draws from usage credits at a higher rate.",
226
+ },
227
+ ],
228
+ };
229
+ }
230
+ /**
231
+ * Story 073 (R1) — strip the ANSI/OSC/CSI control sequences the interactive TUI interleaves so the
232
+ * marker substrings below match on the plain text. Deliberately conservative (removes only escape
233
+ * sequences, never printable bytes) so a marker can never be split apart by cursor-addressing codes.
234
+ */
235
+ function stripControlSequences(raw) {
236
+ // Control chars in these regexes are intentional: we are matching ANSI/OSC
237
+ // escape sequences (ESC/BEL), never printable text, so no-control-regex is
238
+ // suppressed by design.
239
+ /* eslint-disable no-control-regex */
240
+ return raw
241
+ .replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, "") // OSC ...BEL / ST
242
+ .replace(/\x1b[@-Z\\-_]/g, "") // 2-byte ESC (Fe)
243
+ .replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, ""); // CSI ...final
244
+ /* eslint-enable no-control-regex */
245
+ }
246
+ /**
247
+ * Story 073 (R1) — the `/fast` panel header, present in BOTH the available and gated renders (verified
248
+ * live in the spike). Its presence means the panel finished rendering, so a verdict can be reached; its
249
+ * absence means "not rendered yet" → pending.
250
+ */
251
+ const FAST_PANEL_ANCHORS = [/fast mode \(research preview\)/i, /high-speed mode for opus/i];
252
+ /** Story 073 (R1) — still resolving. Checked BEFORE the gate markers because the CLI renders this as
253
+ * `Fast mode unavailable: Checking fast mode availability`, which also matches a gate substring. */
254
+ const FAST_PENDING_MARKERS = ["checking fast mode availability"];
255
+ /**
256
+ * Story 073 (R1) — gate lines that mean fast mode is NOT usable for this account. ANY match ⇒
257
+ * unavailable. `requires usage credits` is the LIVE-captured signal from the spike (Opus 4.8 · Claude
258
+ * Max, no credits); the rest are the sibling reasons mined from the pinned CLI binary (2.1.198): free/
259
+ * oauth → paid subscription, org preference → disabled, first-party gate → Anthropic-API-only, plus the
260
+ * generic `Fast mode unavailable: <reason>` and `Fast mode is not available` families.
261
+ */
262
+ const FAST_UNAVAILABLE_MARKERS = [
263
+ "requires usage credits",
264
+ "requires a paid subscription",
265
+ "unavailable during evaluation",
266
+ "has been disabled by your organization",
267
+ "only available when using the anthropic api directly",
268
+ "fast mode unavailable", // generic `Fast mode unavailable: <reason>`
269
+ "fast mode is not available",
270
+ "fast mode is currently unavailable",
271
+ ];
272
+ /**
273
+ * Story 073 (R1) — classify the `/fast` panel text captured from the live PTY into a {@link FastModeSignal}.
274
+ *
275
+ * Pure and side-effect free so it is unit-testable against the spike's live capture; the live PTY drive
276
+ * that FEEDS it lives behind the `FastModeProbe` seam (acp-agent `defaultFastModeProbe`). Order matters:
277
+ * pending is checked first (its text also matches a gate substring), then the gate markers, then — only
278
+ * once the panel anchor confirms a full render with NO gate line — `available`. Anything else is
279
+ * `pending`, and the caller fails closed on timeout (R1.2).
280
+ */
281
+ export function classifyFastModeSignal(raw) {
282
+ const text = stripControlSequences(raw).toLowerCase();
283
+ if (FAST_PENDING_MARKERS.some((m) => text.includes(m)))
284
+ return "pending";
285
+ if (FAST_UNAVAILABLE_MARKERS.some((m) => text.includes(m)))
286
+ return "unavailable";
287
+ // No gate line. If the panel finished rendering (anchor present), the On/Off toggle is usable.
288
+ if (FAST_PANEL_ANCHORS.some((re) => re.test(text)))
289
+ return "available";
290
+ return "pending"; // panel not rendered yet → keep waiting within the caller's bounded window
291
+ }
154
292
  /** The safe fallback entry, kept as a named export so callers can seed/anchor on it without a lookup. */
155
293
  export const DEFAULT_MODEL_INFO = MODEL_CATALOG[0];
package/dist/tools.js CHANGED
@@ -48,6 +48,26 @@ export function toolInfoFromToolUse(toolUse, supportsTerminalOutput = false, cwd
48
48
  : [],
49
49
  };
50
50
  }
51
+ case "ReportFindings": {
52
+ // Story 074 (#826): render the code-review ReportFindings tool as a think-kind
53
+ // label — `Report N finding(s)` with one `file:line — summary` block per finding
54
+ // (`:line` omitted when absent), or `Report findings: none found` when empty.
55
+ const input = toolUse.input;
56
+ const findings = input?.findings ?? [];
57
+ return {
58
+ title: findings.length > 0
59
+ ? `Report ${findings.length} finding${findings.length === 1 ? "" : "s"}`
60
+ : "Report findings: none found",
61
+ kind: "think",
62
+ content: findings.map((f) => ({
63
+ type: "content",
64
+ content: {
65
+ type: "text",
66
+ text: `${f.file}${typeof f.line === "number" ? `:${f.line}` : ""} — ${f.summary}`,
67
+ },
68
+ })),
69
+ };
70
+ }
51
71
  case "Bash": {
52
72
  const input = toolUse.input;
53
73
  return {
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "0.7.0",
6
+ "version": "0.8.0",
7
7
  "description": "Run the official Claude Code TUI in Zed's agent panel on your Claude Pro/Max subscription — an ACP-over-PTY bridge created for Anthropic's billing split (paused June 15; see README).",
8
8
  "main": "dist/lib.js",
9
9
  "types": "dist/lib.d.ts",
@@ -63,21 +63,21 @@
63
63
  "node": ">=20"
64
64
  },
65
65
  "dependencies": {
66
- "@agentclientprotocol/sdk": "1.0.0",
67
- "@anthropic-ai/claude-agent-sdk": "0.3.195",
66
+ "@agentclientprotocol/sdk": "1.2.0",
67
+ "@anthropic-ai/claude-agent-sdk": "0.3.202",
68
68
  "node-pty": "1.1.0",
69
69
  "zod": "^3.25.0 || ^4.0.0"
70
70
  },
71
71
  "devDependencies": {
72
- "@anthropic-ai/sdk": "0.106.0",
72
+ "@anthropic-ai/sdk": "0.110.0",
73
73
  "@eslint/js": "10.0.1",
74
- "@types/node": "26.0.1",
75
- "@typescript-eslint/eslint-plugin": "8.62.0",
76
- "@typescript-eslint/parser": "8.62.0",
77
- "eslint": "10.5.0",
74
+ "@types/node": "26.1.0",
75
+ "@typescript-eslint/eslint-plugin": "8.62.1",
76
+ "@typescript-eslint/parser": "8.62.1",
77
+ "eslint": "10.6.0",
78
78
  "eslint-config-prettier": "10.1.8",
79
79
  "globals": "17.7.0",
80
- "prettier": "3.8.4",
80
+ "prettier": "3.9.4",
81
81
  "ts-node": "10.9.2",
82
82
  "typescript": "6.0.3"
83
83
  }