@lucascouts/claude-agent-tui 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  An [ACP](https://agentclientprotocol.com)-compatible agent that drives the **Claude Code subscription TUI** over a PTY, so your Claude Code threads render natively in [Zed](https://zed.dev) and other ACP clients.
6
6
 
7
- > **Fork** of [`@agentclientprotocol/claude-agent-acp`](https://github.com/agentclientprotocol/claude-agent-acp) v0.53.0. Where the upstream adapter calls the Claude Agent **SDK**, this fork spawns the `claude` **subscription CLI** in a pseudo-terminal and translates its JSONL transcript into ACP `session/update` notifications. See [`.fork-provenance.json`](.fork-provenance.json) for the exact fork point.
7
+ > **Fork** of [`@agentclientprotocol/claude-agent-acp`](https://github.com/agentclientprotocol/claude-agent-acp) v0.57.0. Where the upstream adapter calls the Claude Agent **SDK**, this fork spawns the `claude` **subscription CLI** in a pseudo-terminal and translates its JSONL transcript into ACP `session/update` notifications. See [`.fork-provenance.json`](.fork-provenance.json) for the exact fork point.
8
8
 
9
9
  ## Why this exists
10
10
 
@@ -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
@@ -917,6 +1008,7 @@ export declare function toAcpNotifications(content: string | ContentBlockParam[]
917
1008
  parentToolUseId?: string | null;
918
1009
  cwd?: string;
919
1010
  taskState?: TaskState;
1011
+ toolUseResult?: unknown;
920
1012
  }): SessionNotification[];
921
1013
  export declare function streamEventToAcpNotifications(message: SDKPartialAssistantMessage, sessionId: string, toolUseCache: ToolUseCache, client: AgentSideConnection, logger: Logger, options?: {
922
1014
  clientCapabilities?: ClientCapabilities;
@@ -934,9 +1026,9 @@ export declare function runAcp(deps?: AgentDeps): {
934
1026
  * not call), as detailed below.
935
1027
  *
936
1028
  * 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
1029
+ * alias→window map FIRST (an exact catalog-`value` hit — `default`/`fable5`/`opus`/
1030
+ * `sonnet`=1M, `haiku`=200K). This fixes `opus` having wrongly reported 200K, and
1031
+ * `sonnet` now seeds 1M (Sonnet 5 is native 1M). An alias absent from the map then
940
1032
  * falls back to the legacy `\b1m\b` inference: Anthropic 1M-context variants
941
1033
  * encode "1m" as a distinct token in the SDK model ID (e.g., "claude-opus-4-6-1m"),
942
1034
  * 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
@@ -1581,6 +1772,10 @@ export class ClaudeAcpAgent {
1581
1772
  if (content === null)
1582
1773
  return;
1583
1774
  }
1775
+ // Story 079 (R4): the same JSONL-hydrated `toolUseResult` the diff block reads below, handed to
1776
+ // the translator so Read/Bash/Agent/WebSearch render from the structured Output. Undefined on a
1777
+ // transcript line that carries no such field — the translator then keeps the raw rendering.
1778
+ const turnToolUseResult = turn.message.toolUseResult;
1584
1779
  for (const notification of toAcpNotifications(
1585
1780
  // @ts-expect-error - message.content/role are untyped in the reduced SDK shape
1586
1781
  content, role, sessionId, toolUseCache, this.client, this.logger, {
@@ -1588,6 +1783,7 @@ export class ClaudeAcpAgent {
1588
1783
  clientCapabilities: this.clientCapabilities,
1589
1784
  cwd: session?.cwd,
1590
1785
  taskState: session?.taskState,
1786
+ toolUseResult: turnToolUseResult,
1591
1787
  })) {
1592
1788
  await this.client.sessionUpdate(notification);
1593
1789
  }
@@ -1698,6 +1894,9 @@ export class ClaudeAcpAgent {
1698
1894
  clientCapabilities: this.clientCapabilities,
1699
1895
  cwd: session?.cwd,
1700
1896
  taskState: session?.taskState,
1897
+ // Story 079 (R4): a nested sidechain row carries its own hydrated `toolUseResult`, so the
1898
+ // sub-agent's Read/Bash results render structured too.
1899
+ toolUseResult: message.toolUseResult,
1701
1900
  });
1702
1901
  // Re-target every translated update as `ToolCallContent` on the PARENT id. A `tool_call_update`
1703
1902
  // replaces the content collection (ToolCallUpdate.content semantics), and Zed APPENDS across
@@ -2048,7 +2247,20 @@ export class ClaudeAcpAgent {
2048
2247
  // keeps the option absent when none were discovered (the gate).
2049
2248
  const agentOpt = session.configOptions.find((o) => o.id === "agent");
2050
2249
  const currentAgent = typeof agentOpt?.currentValue === "string" ? agentOpt.currentValue : undefined;
2051
- session.configOptions = buildConfigOptions(session.modes, value, session.modelInfos, currentEffort, session.agents ?? [], currentAgent);
2250
+ // Story 073 (R4.1) — a model switch turns fast mode OFF and drops its availability (mirroring the
2251
+ // CLI's "switching to other models turns off fast mode"). The rebuild below therefore omits the
2252
+ // toggle; if the new model is Opus, refreshFastMode (kicked off after) re-probes and re-advertises.
2253
+ if (previousModelId !== value) {
2254
+ session.fastModeOn = false;
2255
+ session.fastModeAvailable = false;
2256
+ }
2257
+ session.configOptions = buildConfigOptions(session.modes, value, session.modelInfos, currentEffort, session.agents ?? [], currentAgent, session.fastModeAvailable ?? false, session.fastModeOn ?? false, clientSupportsBooleanConfigOptions(this.clientCapabilities));
2258
+ // Story 073 (R4.2) — on a switch TO an Opus model, re-run availability detection out of band and
2259
+ // re-advertise the toggle (as off) when available. Fire-and-forget: the synchronous response above
2260
+ // ships without the toggle; refreshFastMode emits a follow-up config_option_update once it settles.
2261
+ if (previousModelId !== value && isFastModeCapableModel(value)) {
2262
+ void this.refreshFastMode(sessionId, session);
2263
+ }
2052
2264
  // === SEAM(023) Group 1: the SDK effort sync (query.applyFlagSettings) after a model switch is
2053
2265
  // dropped — configOptions already reflects the new effort locally.
2054
2266
  // Degrau 2 (030/032): PTY-backed control. ===
@@ -2312,6 +2524,11 @@ export class ClaudeAcpAgent {
2312
2524
  taskState,
2313
2525
  gate,
2314
2526
  };
2527
+ // Story 073 (R1) — the seed model is Opus (`default`), so probe fast-mode availability out of band
2528
+ // and advertise the toggle when available. Fire-and-forget (like sendAvailableCommandsUpdate): the
2529
+ // response below ships the seed options; refreshFastMode emits a follow-up config_option_update. The
2530
+ // production probe fails closed, so today's stream is byte-for-byte unaffected until the spike wires it.
2531
+ void this.refreshFastMode(startedSessionId, this.sessions[startedSessionId]);
2315
2532
  return {
2316
2533
  sessionId: startedSessionId,
2317
2534
  modes,
@@ -2367,7 +2584,7 @@ function buildAvailableModes(modelInfo) {
2367
2584
  // `applyFlagSettings` in @anthropic-ai/claude-agent-sdk. Mapping both the
2368
2585
  // `"default"` sentinel and `undefined` (effort option absent for the model) to
2369
2586
  // `null` ensures any previously-applied flag is actually cleared.
2370
- function buildConfigOptions(modes, currentModelId, modelInfos, currentEffortLevel, agents = [], currentAgent) {
2587
+ function buildConfigOptions(modes, currentModelId, modelInfos, currentEffortLevel, agents = [], currentAgent, fastAvailable = false, currentFast = false, fastUsesBooleanOption = false) {
2371
2588
  const options = [
2372
2589
  {
2373
2590
  id: "mode",
@@ -2398,6 +2615,15 @@ function buildConfigOptions(modes, currentModelId, modelInfos, currentEffortLeve
2398
2615
  })),
2399
2616
  },
2400
2617
  ];
2618
+ // Story 073 (R2) — the fast-mode toggle, positioned right after the model selector. GATED on an
2619
+ // Opus alias (R2.2, isFastModeCapableModel) AND detected availability (R1, fastAvailable): fast mode
2620
+ // is Opus-only and account-gated, so a non-Opus model or an unavailable account omits it entirely.
2621
+ // Story 074 (#828, R4.1): the option is emitted as `type:"boolean"` when the client advertised
2622
+ // boolean config options (fastUsesBooleanOption), else the `on`/`off` select fallback — via the
2623
+ // model-catalog helper. currentValue mirrors the session's fast-mode state.
2624
+ if (isFastModeCapableModel(currentModelId) && fastAvailable) {
2625
+ options.push(createFastModeConfigOption(currentFast, fastUsesBooleanOption));
2626
+ }
2401
2627
  // Add effort level option based on the currently selected model
2402
2628
  const currentModelInfo = modelInfos.find((m) => m.value === currentModelId);
2403
2629
  const supportedLevels = currentModelInfo?.supportsEffort
@@ -2702,6 +2928,12 @@ export function toAcpNotifications(content, role, sessionId, toolUseCache, clien
2702
2928
  const registerHooks = options?.registerHooks !== false;
2703
2929
  const supportsTerminalOutput = options?.clientCapabilities?._meta?.["terminal_output"] === true;
2704
2930
  if (typeof content === "string") {
2931
+ // Story 074 (#841): an empty full-string content block must emit NO message chunk
2932
+ // (an empty agent_message_chunk breaks strict ACP clients — e.g. JetBrains Air
2933
+ // freezes the transcript). Mirrors the empty-thinking guard (#793). The
2934
+ // `case "text"`/`text_delta` block path stays DEAD (no content_block_delta, 034).
2935
+ if (content.length === 0)
2936
+ return [];
2705
2937
  const update = {
2706
2938
  sessionUpdate: role === "assistant" ? "agent_message_chunk" : "user_message_chunk",
2707
2939
  content: {
@@ -2720,6 +2952,15 @@ export function toAcpNotifications(content, role, sessionId, toolUseCache, clien
2720
2952
  }
2721
2953
  return [{ sessionId, update }];
2722
2954
  }
2955
+ // Story 079 (R3/R4): `toolUseResult` is message-level and carries no tool_use_id of its own — it
2956
+ // describes "the" tool_result block of the message it rode in on. If several tool_result blocks
2957
+ // were ever batched into one message it couldn't be attributed, so it is only honored when the
2958
+ // message carries exactly one.
2959
+ const toolUseResult = options?.toolUseResult !== undefined &&
2960
+ content.filter((c) => typeof c === "object" && c !== null && c.type === "tool_result")
2961
+ .length === 1
2962
+ ? options.toolUseResult
2963
+ : undefined;
2723
2964
  const output = [];
2724
2965
  // Only handle the first chunk for streaming; extend as needed for batching
2725
2966
  for (const chunk of content) {
@@ -2907,7 +3148,7 @@ export function toAcpNotifications(content, role, sessionId, toolUseCache, clien
2907
3148
  }
2908
3149
  }
2909
3150
  else if (toolUse.name !== "TodoWrite") {
2910
- const { _meta: toolMeta, ...toolUpdate } = toolUpdateFromToolResult(chunk, toolUseCache[chunk.tool_use_id], supportsTerminalOutput);
3151
+ const { _meta: toolMeta, ...toolUpdate } = toolUpdateFromToolResult(chunk, toolUseCache[chunk.tool_use_id], supportsTerminalOutput, toolUseResult);
2911
3152
  // When terminal output is supported, send terminal_output as a
2912
3153
  // separate notification to match codex-acp's streaming lifecycle:
2913
3154
  // 1. tool_call → _meta.terminal_info (already sent above)
@@ -3030,9 +3271,9 @@ export function runAcp(deps) {
3030
3271
  * not call), as detailed below.
3031
3272
  *
3032
3273
  * 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
3274
+ * alias→window map FIRST (an exact catalog-`value` hit — `default`/`fable5`/`opus`/
3275
+ * `sonnet`=1M, `haiku`=200K). This fixes `opus` having wrongly reported 200K, and
3276
+ * `sonnet` now seeds 1M (Sonnet 5 is native 1M). An alias absent from the map then
3036
3277
  * falls back to the legacy `\b1m\b` inference: Anthropic 1M-context variants
3037
3278
  * encode "1m" as a distinct token in the SDK model ID (e.g., "claude-opus-4-6-1m"),
3038
3279
  * 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);