@lucascouts/claude-agent-tui 0.14.13 → 0.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/acp-agent.js CHANGED
@@ -17,6 +17,8 @@ import { createJsonlWatcher } from "./engine-watcher.js";
17
17
  import { resolveWatchTarget } from "./jsonl.js";
18
18
  import { linearizeTurns, readOrderedMessages, defaultGetMessages } from "./linearize.js";
19
19
  import { createDiffEnrichedReader } from "./diff-enriched-reader.js";
20
+ import { backgroundTaskEnds } from "./background-task-end.js";
21
+ import { readTranscriptPermissionMode } from "./resumed-permission-mode.js";
20
22
  import { sourceSubagentRows, defaultListSubagents, defaultGetSubagentMessages, hasSubagentSpawn, spawnIdsOpen, } from "./subagent-source.js";
21
23
  import { collectSidechainToolUses, registerSidechainGateToolUses, } from "./subagent-gate.js";
22
24
  import { createSubagentWatcher } from "./subagent-watcher.js";
@@ -25,11 +27,11 @@ import { guardEvent } from "./billing/entrypoint-guard.js";
25
27
  import { usageUpdatesFor } from "./usage.js";
26
28
  import { createTurnResolver } from "./end-of-turn.js";
27
29
  import { sendPrompt } from "./engine-pty.js";
28
- import { MODEL_CONTEXT_WINDOWS, MODEL_ID_CONTEXT_WINDOWS, modelSelectorDescription, DEFAULT_MODEL_INFO, resolveCatalogValueFromModelId, isFastModeCapableModel, classifyFastModeSignal, FAST_MODE_CONFIG_ID, FAST_MODE_ON, FAST_MODE_OFF, createFastModeConfigOption, clientSupportsBooleanConfigOptions, resolveFastModeEnabled, ULTRACODE_EFFORT, ULTRACODE_EFFORT_LEVEL, ULTRACODE_EFFORT_LABEL, } from "./model-catalog.js";
30
+ import { MODEL_CONTEXT_WINDOWS, MODEL_ID_CONTEXT_WINDOWS, modelSelectorDescription, DEFAULT_MODEL_INFO, resolveCatalogValueFromModelId, isFastModeCapableModel, classifyFastModeSignal, FAST_MODE_CONFIG_ID, FAST_MODE_ON, FAST_MODE_OFF, createFastModeConfigOption, clientSupportsBooleanConfigOptions, resolveFastModeEnabled, ULTRACODE_CONFIG_ID, ultracodeCommand, isUltracodeCapableModel, resolveUltracodeEnabled, createUltracodeConfigOption, classifyUltracodeReply, } from "./model-catalog.js";
29
31
  import { resolveModelCatalog } from "./live-model-catalog.js";
30
- // Story 060 (R2.2/R2.3/R3.2) — the declarative spawn-time complement to the live ultracode keyword:
31
- // toggle the {ultracode,ultracodeKeywordTrigger} keys in the gate's per-session scratch settings file
32
- // (preserving the hook + every other key). Lives in the gate's settings-writer so it reuses durableWrite.
32
+ // Item 84 — mirror the Ultracode switch into the gate's per-session scratch settings file as
33
+ // `ultracode:true`, so a re-spawn of this session keeps it (`/effort ultracode on` is session-scoped
34
+ // and a fresh PTY would not have it). Lives in the gate's settings-writer so it reuses durableWrite.
33
35
  import { applyUltracodeSettings } from "./gate/settings-writer.js";
34
36
  import { discoverAgents } from "./agent-catalog.js";
35
37
  // Story 063 (R1) — OFFLINE disk discovery of the `available_commands` set (custom slash-commands +
@@ -193,13 +195,16 @@ export async function defaultStartEngine(args) {
193
195
  // sessionId glob ambiguous → resourceNotFound on the next load. A missing/ambiguous transcript
194
196
  // throws here → createSession's resume catch maps it to resourceNotFound (unchanged client
195
197
  // contract). No PTY, no tail watcher, no live engine — the only emission is replaySessionHistory.
196
- const { cwd } = await resolveWatchTarget(args.sessionId, { ...args.locateOptions });
198
+ const { cwd, transcriptPath } = await resolveWatchTarget(args.sessionId, {
199
+ ...args.locateOptions,
200
+ });
197
201
  return {
198
202
  sessionId: args.sessionId,
199
203
  pty: REPLAY_ONLY_NOOP_PTY,
200
204
  watcher: undefined,
201
205
  engine: undefined,
202
206
  cwd,
207
+ transcriptPath,
203
208
  };
204
209
  }
205
210
  if (args.resume && args.sessionId) {
@@ -662,6 +667,10 @@ const MODE_CYCLE_POLL_MS = 50;
662
667
  * late Enter still lands while an early (pre-render) one would be lost. 800 ms validated headless
663
668
  * (experiments/probe-c-model-then-prompt.mjs: the dialog rendered + the switch applied within it). */
664
669
  const MODEL_CONFIRM_DELAY_MS = 800;
670
+ /** Item 84 — how long to watch the terminal for the CLI's answer to `/effort ultracode on`. */
671
+ const ULTRACODE_REPLY_WINDOW_MS = 5000;
672
+ /** Item 84 — the tail of terminal output kept while watching for that answer. */
673
+ const ULTRACODE_REPLY_BUFFER_CHARS = 8192;
665
674
  /**
666
675
  * Builds the label for the "Always Allow" permission option so the user can see
667
676
  * the exact scope they are committing to. Uses the SDK-provided suggestions
@@ -782,6 +791,7 @@ export class ClaudeAcpAgent {
782
791
  this.engine = engine;
783
792
  this.startEngine = deps.startEngine ?? defaultStartEngine;
784
793
  this.fastModeProbe = deps.fastModeProbe ?? defaultFastModeProbe;
794
+ this.modelCatalogSource = deps.modelCatalogSource;
785
795
  // Story 043 (R2.1): when liveDiff is ON, the live JSONL reader is the diff-enriched reader
786
796
  // (getSessionMessages + uuid→toolUseResult hydration), which restores the story-021 Edit/Write
787
797
  // diff on BOTH the live pump and the session/load replay (both read this.getMessages once). The
@@ -789,7 +799,16 @@ export class ClaudeAcpAgent {
789
799
  // (index.ts) is what defaults it ON. OFF → byte-for-byte the pre-043 reduced reader (R5.1).
790
800
  this.getMessages =
791
801
  (deps.liveDiff ?? false)
792
- ? createDiffEnrichedReader(deps.getMessages ?? defaultGetMessages, deps.diffEnrichOptions)
802
+ ? createDiffEnrichedReader(deps.getMessages ?? defaultGetMessages, {
803
+ ...deps.diffEnrichOptions,
804
+ // Item 92 (#1312): the same raw read yields the ended background tasks, so a held terminal
805
+ // exit costs no second read of the transcript.
806
+ onRawLines: (sid, lines) => {
807
+ const session = this.sessions[sid];
808
+ if (session)
809
+ session.backgroundTaskEnds = backgroundTaskEnds(lines);
810
+ },
811
+ })
793
812
  : deps.getMessages;
794
813
  this.listSubagents = deps.listSubagents ?? defaultListSubagents;
795
814
  this.getSubagentMessages = deps.getSubagentMessages ?? defaultGetSubagentMessages;
@@ -1092,11 +1111,9 @@ export class ClaudeAcpAgent {
1092
1111
  // future promptToClaude were to throw mid-materialize, the teardown cleanup still reaches the paths.
1093
1112
  sessionRecord.turnTempImagePaths = turnTempImagePaths;
1094
1113
  const payload = promptToClaude(params, this.logger, turnTempImagePaths);
1095
- // Story 060 (R2.2) — while ultracode is active, prefix the OUTGOING prompt with the `ultracode`
1096
- // keyword (the binary's per-turn Workflow opt-in). This is the LIVE activation that needs no
1097
- // re-spawn (Option A) and works pre- AND post-first-interaction; the scratch settings keys are the
1098
- // declarative spawn-time complement. NEVER emitted as a `/effort` value (R1.2).
1099
- const outgoing = sessionRecord.ultracodeActive ? `${ULTRACODE_EFFORT} ${payload}` : payload;
1114
+ // Item 84: the prompt goes out as typed. Ultracode is a session switch the CLI holds
1115
+ // (`/effort ultracode on`), not a keyword prepended to every prompt.
1116
+ const outgoing = payload;
1100
1117
  // (2) Register the turn with the story-024 resolver: the detector that the live pump feeds, and
1101
1118
  // the awaitable that settles ONCE with { stopReason: mapStopReason(...) } on the terminal
1102
1119
  // boundary (or rejects on the watchdog). One shared `schedule` drives sendPrompt + the resolver.
@@ -1144,7 +1161,7 @@ export class ClaudeAcpAgent {
1144
1161
  sessionRecord.subagentWatcher?.stop();
1145
1162
  sessionRecord.subagentWatcher = undefined;
1146
1163
  // Story 046 (R1.3): the session is idle again — flush any model switch deferred mid-turn.
1147
- this.flushPendingControlInjections(sessionRecord);
1164
+ this.flushPendingControlInjections(params.sessionId, sessionRecord);
1148
1165
  }
1149
1166
  }
1150
1167
  // ─── Task 3.2 (R5.2, R5.3) — the session title, and what this port does NOT deliver ──────────
@@ -1363,6 +1380,17 @@ export class ClaudeAcpAgent {
1363
1380
  : o);
1364
1381
  return { configOptions: session.configOptions };
1365
1382
  }
1383
+ // Item 84: the `ultracode` switch, same shape as `fast` above — a boolean payload bypasses the
1384
+ // string-only validation below; the on/off string of the select fallback goes through it.
1385
+ if (params.configId === ULTRACODE_CONFIG_ID && typeof params.value === "boolean") {
1386
+ const option = session.configOptions.find((o) => o.id === ULTRACODE_CONFIG_ID);
1387
+ if (!option) {
1388
+ throw new Error(`Unknown config option: ${params.configId}`);
1389
+ }
1390
+ await this.applyUltracodeChange(params.sessionId, session, params.value);
1391
+ session.configOptions = this.rebuildConfigOptionsPreserving(session, this.currentModel(session));
1392
+ return { configOptions: session.configOptions };
1393
+ }
1366
1394
  if (typeof params.value !== "string") {
1367
1395
  throw new Error(`Invalid value for config option ${params.configId}: ${params.value}`);
1368
1396
  }
@@ -1434,9 +1462,9 @@ export class ClaudeAcpAgent {
1434
1462
  // mirroring /model — no re-spawn, works before the first interaction. Mid-turn it defers; it never
1435
1463
  // throws, so applyConfigOptionValue below always commits the new currentValue (optimistic, like
1436
1464
  // /model). The flag path stays only to seed/preserve effort across mode/agent re-spawns.
1437
- // Story 060 (R2/R3.2): route through applyEffortSelection so the `ultracode` sentinel is
1438
- // special-cased (activate keyword + scratch keys + /effort xhigh) while real levels deselect it.
1439
- await this.applyEffortSelection(session, resolvedValue);
1465
+ // Item 84: Ultracode is no longer an effort value, and an effort change leaves it alone (the
1466
+ // CLI keeps it "at any effort level").
1467
+ this.applyEffortChange(session, resolvedValue);
1440
1468
  }
1441
1469
  else if (params.configId === "agent") {
1442
1470
  // Story 056 (R3.3/R3.4): the agent persona has no live mid-session path either — apply it by an
@@ -1451,6 +1479,12 @@ export class ClaudeAcpAgent {
1451
1479
  // path; a boolean payload is resolved earlier (story 074, R4.3). resolveFastModeEnabled unifies both.
1452
1480
  this.applyFastModeChange(session, resolveFastModeEnabled(resolvedValue));
1453
1481
  }
1482
+ else if (params.configId === ULTRACODE_CONFIG_ID) {
1483
+ // Item 84 — the on/off select fallback of the Ultracode switch.
1484
+ await this.applyUltracodeChange(params.sessionId, session, resolveUltracodeEnabled(resolvedValue));
1485
+ session.configOptions = this.rebuildConfigOptionsPreserving(session, this.currentModel(session));
1486
+ return { configOptions: session.configOptions };
1487
+ }
1454
1488
  await this.applyConfigOptionValue(params.sessionId, session, params.configId, resolvedValue);
1455
1489
  return { configOptions: session.configOptions };
1456
1490
  }
@@ -1551,7 +1585,7 @@ export class ClaudeAcpAgent {
1551
1585
  * prompt()'s finally, the moment the turn settles). Last-write-wins: only the most recent queued
1552
1586
  * alias is injected; the field is cleared so a settled session with nothing queued injects nothing.
1553
1587
  */
1554
- flushPendingControlInjections(session) {
1588
+ flushPendingControlInjections(sessionId, session) {
1555
1589
  if (session.turnDetector !== undefined)
1556
1590
  return; // still not idle (defensive)
1557
1591
  const alias = session.pendingModelInjection;
@@ -1571,6 +1605,12 @@ export class ClaudeAcpAgent {
1571
1605
  session.pendingFastInjection = undefined;
1572
1606
  this.injectFastCommand(session, fast);
1573
1607
  }
1608
+ // Item 84 — flush a deferred `/effort ultracode on|off` too (last-write-wins).
1609
+ const ultracode = session.pendingUltracodeInjection;
1610
+ if (ultracode !== undefined) {
1611
+ session.pendingUltracodeInjection = undefined;
1612
+ this.injectUltracodeCommand(sessionId, session, ultracode);
1613
+ }
1574
1614
  }
1575
1615
  /**
1576
1616
  * Story 046 (R3.3, design §6b) — drive the TUI to `target` with closed-loop raw Shift+Tab. Writes
@@ -1657,14 +1697,9 @@ export class ClaudeAcpAgent {
1657
1697
  // does not reset the others — the argv carries all three flags. There are three selectors now
1658
1698
  // (Story 056 added agent): a mode re-spawn keeps effort+agent, an agent re-spawn keeps mode+effort.
1659
1699
  const permissionMode = change.permissionMode ?? session.modes.currentModeId;
1660
- // Story 060 (R1.2 fix): the preserved currentEffort can be the `ultracode` SENTINEL (it is the
1661
- // committed configOption value while active). It is NOT a real `--effort` enum value — the binary
1662
- // rejects `--effort ultracode` (story-060 probe), so a mode/agent re-spawn-while-active would
1663
- // silently degrade effort to default. Map the sentinel to its real component (xhigh) at THIS spawn
1664
- // seam (it feeds BOTH buildClaudeCmd and buildResumeArgv); the scratch `ultracode:true` already
1665
- // carries the orchestration activation declaratively at spawn.
1666
- const preservedEffort = change.effortLevel ?? this.currentEffort(session);
1667
- const effortLevel = preservedEffort === ULTRACODE_EFFORT ? ULTRACODE_EFFORT_LEVEL : preservedEffort;
1700
+ // Item 84: Ultracode is not an effort value any more, so the effort carries over as is; the
1701
+ // Ultracode switch reaches the new PTY through the scratch settings' `ultracode:true`.
1702
+ const effortLevel = change.effortLevel ?? this.currentEffort(session);
1668
1703
  const agent = change.agent ?? this.currentAgent(session);
1669
1704
  // Story 057 (R2.4): REGENERATE the MCP scratch so the re-spawned `claude` reads the CURRENT MCP
1670
1705
  // config at startup (its `--mcp-config` is bound only at spawn). Re-translate from the stored raw
@@ -1733,52 +1768,108 @@ export class ClaudeAcpAgent {
1733
1768
  const opt = session.configOptions.find((o) => o.id === "agent");
1734
1769
  return typeof opt?.currentValue === "string" ? opt.currentValue : undefined;
1735
1770
  }
1771
+ /** Item 84 — the session's current model configOption value (`default` when absent). */
1772
+ currentModel(session) {
1773
+ const opt = session.configOptions.find((o) => o.id === "model");
1774
+ return typeof opt?.currentValue === "string" ? opt.currentValue : DEFAULT_MODEL_INFO.value;
1775
+ }
1736
1776
  /**
1737
- * Story 060 (R2/R3.2) — apply an effort-selector choice, special-casing the `ultracode` sentinel.
1738
- *
1739
- * Selecting `ultracode` (Option A — keyword + scratch, NO re-spawn): activate the session flag (which
1740
- * makes {@link prompt} prefix the OUTGOING prompt with the `ultracode` keyword — the binary's per-turn
1741
- * Workflow opt-in, the effective live mechanism), write the scratch ultracode keys via
1742
- * {@link applyUltracodeSettings} (the declarative spawn-time complement), and set the effort to xhigh
1743
- * through the SAME live `/effort` inject as every other level — NEVER `/effort ultracode` (R1.2). The
1744
- * `already` guard suppresses a redundant `/effort xhigh` re-inject when ultracode is re-selected while
1745
- * already active.
1746
- *
1747
- * Selecting a real level (or `default`) DEACTIVATES ultracode: clear the flag, remove the scratch keys,
1748
- * then apply that level through {@link applyEffortChange} (whose own no-op guard handles a same-level
1749
- * pick). `applyConfigOptionValue` (the caller, after this returns) commits the selector's currentValue,
1750
- * which for `ultracode` correctly stays `"ultracode"` (the {@link buildConfigOptions} `includes` guard
1751
- * keeps it valid across rebuilds).
1777
+ * Item 84 — turn the Ultracode switch on or off, LIVE via `/effort ultracode on|off` through the
1778
+ * session's terminal, exactly as {@link applyFastModeChange} drives `/fast`: no re-spawn, no turn,
1779
+ * works before the first prompt, deferred while a turn is in flight. Turning it on clears a previous
1780
+ * refusal (the user is retrying). The scratch settings mirror the intent so a re-spawn keeps it.
1781
+ * A no-op change sends nothing.
1752
1782
  */
1753
- async applyEffortSelection(session, value) {
1754
- if (value === ULTRACODE_EFFORT) {
1755
- const already = session.ultracodeActive === true;
1756
- session.ultracodeActive = true;
1757
- // The gate's per-session SCRATCH settings file is the spawn's `--settings` target; on a live
1758
- // Session it is reachable via `session.gate?.settingsPath` (the value createSession also threads
1759
- // into StartEngineArgs.settingsFile). Absent on a no-gate / resume / replay session → keyword-only.
1760
- const scratchPath = session.gate?.settingsPath;
1761
- if (scratchPath) {
1762
- // Declarative scratch keys for any future (re-)spawn (NOT a re-spawn trigger — Option A).
1763
- await applyUltracodeSettings(scratchPath, true);
1764
- }
1765
- // Effort component is xhigh, applied via the live /effort inject — but only when not already active
1766
- // (re-selecting ultracode must not re-inject `/effort xhigh`). applyEffortChange's own no-op guard
1767
- // also short-circuits if xhigh already equals the current effort.
1768
- if (!already) {
1769
- this.applyEffortChange(session, ULTRACODE_EFFORT_LEVEL);
1770
- }
1783
+ async applyUltracodeChange(sessionId, session, enabled) {
1784
+ if (enabled)
1785
+ session.ultracodeRefusal = undefined;
1786
+ if (enabled === (session.ultracodeOn ?? false))
1787
+ return;
1788
+ session.ultracodeOn = enabled;
1789
+ await this.mirrorUltracodeIntoScratch(session, enabled);
1790
+ if (session.turnDetector !== undefined) {
1791
+ // A turn is in flight — injecting mid-turn corrupts the PTY input. Defer (mirrors /effort).
1792
+ session.pendingUltracodeInjection = enabled;
1771
1793
  return;
1772
1794
  }
1773
- // A real level (or `default`) was chosen → deactivate ultracode before applying it.
1774
- if (session.ultracodeActive) {
1775
- session.ultracodeActive = false;
1776
- const scratchPath = session.gate?.settingsPath;
1777
- if (scratchPath) {
1778
- await applyUltracodeSettings(scratchPath, false);
1779
- }
1795
+ this.injectUltracodeCommand(sessionId, session, enabled);
1796
+ }
1797
+ /** Item 84 — keep `ultracode:true` in the scratch `--settings` file only while the switch is on. */
1798
+ async mirrorUltracodeIntoScratch(session, enabled) {
1799
+ const scratchPath = session.gate?.settingsPath;
1800
+ if (!scratchPath)
1801
+ return; // no gate (resume/replay/test) → nothing to keep in sync
1802
+ try {
1803
+ await applyUltracodeSettings(scratchPath, enabled);
1804
+ }
1805
+ catch (err) {
1806
+ // Degraded, not fatal: the live command still applies; only a later re-spawn would miss it.
1807
+ this.logger.error(`[ultracode] event=scratch_write_failed enabled=${enabled} path=${scratchPath}: ${String(err)}`);
1780
1808
  }
1781
- this.applyEffortChange(session, value);
1809
+ }
1810
+ /**
1811
+ * Item 84 — side-channel `/effort ultracode on|off` write (synchronous, never a turn; `/effort`
1812
+ * applies inline, no confirmation panel). After an `on`, watch the terminal for a bounded window
1813
+ * for the CLI's answer: one of its two refusals turns the switch back off with the reason
1814
+ * ({@link handleUltracodeRefusal}); its confirmation, or silence, ends the watch.
1815
+ */
1816
+ injectUltracodeCommand(sessionId, session, on) {
1817
+ session.ultracodeReplyStop?.();
1818
+ session.ultracodeReplyStop = undefined;
1819
+ if (on)
1820
+ this.watchUltracodeReply(sessionId, session);
1821
+ sendPrompt(session.pty, ultracodeCommand(on), (fn) => fn());
1822
+ }
1823
+ watchUltracodeReply(sessionId, session) {
1824
+ let buffer = "";
1825
+ let done = false;
1826
+ const subscription = session.pty.onData((chunk) => {
1827
+ if (done)
1828
+ return;
1829
+ // Bounded: the reply is one short line; never let a chatty PTY grow this without limit.
1830
+ buffer = (buffer + chunk).slice(-ULTRACODE_REPLY_BUFFER_CHARS);
1831
+ const reply = classifyUltracodeReply(buffer);
1832
+ if (reply.kind === "pending")
1833
+ return;
1834
+ stop();
1835
+ if (reply.kind === "refused") {
1836
+ this.handleUltracodeRefusal(sessionId, session, reply.reason).catch((err) => this.logger.error(`[ultracode] event=refusal_handling_failed sessionId=${sessionId}: ${String(err)}`));
1837
+ }
1838
+ });
1839
+ // `onData` never fires synchronously, so `cancelTimer` is always assigned before `stop` runs.
1840
+ const stop = () => {
1841
+ if (done)
1842
+ return;
1843
+ done = true;
1844
+ subscription.dispose();
1845
+ cancelTimer();
1846
+ if (session.ultracodeReplyStop === stop)
1847
+ session.ultracodeReplyStop = undefined;
1848
+ };
1849
+ const cancelTimer = this.schedule(stop, ULTRACODE_REPLY_WINDOW_MS);
1850
+ session.ultracodeReplyStop = stop;
1851
+ }
1852
+ /**
1853
+ * Item 84 — the CLI refused `/effort ultracode on`: the switch goes back off, the reason is kept for
1854
+ * the option's description, the scratch key is removed, and the client gets the new options.
1855
+ */
1856
+ async handleUltracodeRefusal(sessionId, session, reason) {
1857
+ session.ultracodeOn = false;
1858
+ session.pendingUltracodeInjection = undefined;
1859
+ session.ultracodeRefusal = {
1860
+ scope: /dynamic workflows/i.test(reason) ? "workflows" : "model",
1861
+ reason,
1862
+ };
1863
+ // WARN-level by meaning (degraded, recovered by switching off); this logger has no warn.
1864
+ this.logger.log(`[ultracode] event=refused sessionId=${sessionId} reason="${reason}"`);
1865
+ await this.mirrorUltracodeIntoScratch(session, false);
1866
+ if (!this.sessions[sessionId])
1867
+ return; // torn down meanwhile
1868
+ session.configOptions = this.rebuildConfigOptionsPreserving(session, this.currentModel(session));
1869
+ await this.client.sessionUpdate({
1870
+ sessionId,
1871
+ update: { sessionUpdate: "config_option_update", configOptions: session.configOptions },
1872
+ });
1782
1873
  }
1783
1874
  /**
1784
1875
  * Story 046 (R2.2) + Story 056 v4 — apply a reasoning-effort change LIVE via `/effort <level>`.
@@ -1886,7 +1977,7 @@ export class ClaudeAcpAgent {
1886
1977
  const currentEffort = typeof effortOpt?.currentValue === "string" ? effortOpt.currentValue : undefined;
1887
1978
  const agentOpt = session.configOptions.find((o) => o.id === "agent");
1888
1979
  const currentAgent = typeof agentOpt?.currentValue === "string" ? agentOpt.currentValue : undefined;
1889
- return buildConfigOptions(session.modes, modelId, session.modelInfos, currentEffort, session.agents ?? [], currentAgent, session.fastModeAvailable ?? false, session.fastModeOn ?? false, clientSupportsBooleanConfigOptions(this.clientCapabilities));
1980
+ return buildConfigOptions(session.modes, modelId, session.modelInfos, currentEffort, session.agents ?? [], currentAgent, session.fastModeAvailable ?? false, session.fastModeOn ?? false, clientSupportsBooleanConfigOptions(this.clientCapabilities), { on: session.ultracodeOn ?? false, refusal: session.ultracodeRefusal?.reason });
1890
1981
  }
1891
1982
  /**
1892
1983
  * Story 056 (R3.3/R3.4) — apply a main-thread agent-persona change. Like effort, the persona has no
@@ -1965,7 +2056,7 @@ export class ClaudeAcpAgent {
1965
2056
  * live pump) rendered Edit/Write WITHOUT a diff; story 038 moved usage_update HERE for the SAME
1966
2057
  * reason (loaded==live for usage). Only dedup and the billing guard-rail stay with the callers.
1967
2058
  */
1968
- async emitTurnUpdates(sessionId, turn, toolUseCache) {
2059
+ async emitTurnUpdates(sessionId, turn, toolUseCache, live = false) {
1969
2060
  const session = this.sessions[sessionId];
1970
2061
  const source = turn.message;
1971
2062
  const role = source.message?.role;
@@ -1988,6 +2079,12 @@ export class ClaudeAcpAgent {
1988
2079
  cwd: session?.cwd,
1989
2080
  taskState: session?.taskState,
1990
2081
  toolUseResult: turnToolUseResult,
2082
+ // Item 92 (#1312): only the live pump can send a backgrounded command's exit later, so only
2083
+ // it holds the exit back; replay exits at the result.
2084
+ background: {
2085
+ ended: (id) => session?.backgroundTaskEnds?.get(id),
2086
+ held: live && session ? (session.heldBackgroundExits ??= new Set()) : undefined,
2087
+ },
1991
2088
  })) {
1992
2089
  await this.client.sessionUpdate(notification);
1993
2090
  }
@@ -2292,7 +2389,8 @@ export class ClaudeAcpAgent {
2292
2389
  // The merge MUST NOT reach the detector / §10 guard / §9 gate above — those already consumed the
2293
2390
  // un-merged `messages` slice exactly-once (R4.1 structural: sub-agent rows never advance
2294
2391
  // `detectorCursor` nor register as gate tool_uses).
2295
- await this.emitLinearizedWithNested(sessionId, session, messages);
2392
+ await this.emitLinearizedWithNested(sessionId, session, messages, true);
2393
+ await this.flushBackgroundExits(sessionId, session);
2296
2394
  // === SEAM(054) — feed the gate correlator from the sidechain rows (R3). Gated + LIVE-ONLY: runs
2297
2395
  // only with a present, non-torndown gate, and NEVER inside the shared emitLinearizedWithNested that
2298
2396
  // session/load replay also calls — so replay stays pure (U3). Additive: touches only the correlator +
@@ -2330,7 +2428,7 @@ export class ClaudeAcpAgent {
2330
2428
  schedule: this.schedule,
2331
2429
  onActivity: async () => {
2332
2430
  session.turnDetector?.noteActivity();
2333
- await this.emitLinearizedWithNested(sessionId, session, session.lastMessages ?? messages);
2431
+ await this.emitLinearizedWithNested(sessionId, session, session.lastMessages ?? messages, true);
2334
2432
  },
2335
2433
  });
2336
2434
  }
@@ -2344,6 +2442,33 @@ export class ClaudeAcpAgent {
2344
2442
  }
2345
2443
  }
2346
2444
  }
2445
+ /**
2446
+ * Item 92 (upstream #1312) — send the terminal exit of each backgrounded command whose task has now
2447
+ * ended. The live pump held that exit back at the tool result (the command was still running); the
2448
+ * task's `<task-notification>` in the raw transcript is its end, and its summary the code. Each held
2449
+ * exit is sent once. Live-only: replay never holds an exit, so it has nothing to flush.
2450
+ */
2451
+ async flushBackgroundExits(sessionId, session) {
2452
+ const held = session.heldBackgroundExits;
2453
+ if (!held?.size)
2454
+ return;
2455
+ for (const terminalId of [...held]) {
2456
+ const end = session.backgroundTaskEnds?.get(terminalId);
2457
+ if (!end)
2458
+ continue;
2459
+ held.delete(terminalId);
2460
+ await this.client.sessionUpdate({
2461
+ sessionId,
2462
+ update: {
2463
+ sessionUpdate: "tool_call_update",
2464
+ toolCallId: terminalId,
2465
+ _meta: {
2466
+ terminal_exit: { terminal_id: terminalId, exit_code: end.exitCode, signal: null },
2467
+ },
2468
+ },
2469
+ });
2470
+ }
2471
+ }
2347
2472
  /**
2348
2473
  * Story 041 (R3.1, R3.2) — the SHARED source+merge+linearize+emit loop run by BOTH the live tail pump
2349
2474
  * ({@link pumpUpdates}) and the `session/load` replay ({@link replaySessionHistory}), so a LOADED
@@ -2366,7 +2491,7 @@ export class ClaudeAcpAgent {
2366
2491
  * un-merged main chain in the caller (sub-agent rows must never advance the detector cursor or register
2367
2492
  * as gate tool_uses). The replay caller has no detector/gate feed, so it simply does not run one.
2368
2493
  */
2369
- async emitLinearizedWithNested(sessionId, session, messages) {
2494
+ async emitLinearizedWithNested(sessionId, session, messages, live = false) {
2370
2495
  const subagentRows = await sourceSubagentRows(sessionId, messages, {
2371
2496
  dir: session.cwd,
2372
2497
  listSubagents: this.listSubagents,
@@ -2379,7 +2504,7 @@ export class ClaudeAcpAgent {
2379
2504
  // so live and loaded render byte-for-byte the same (story 026 R3.3; story 038 moved usage_update
2380
2505
  // into the shared emit).
2381
2506
  if (!(turn.uuid && session.emitted.has(turn.uuid))) {
2382
- await this.emitTurnUpdates(sessionId, turn, session.toolUseCache);
2507
+ await this.emitTurnUpdates(sessionId, turn, session.toolUseCache, live);
2383
2508
  if (turn.uuid)
2384
2509
  session.emitted.add(turn.uuid);
2385
2510
  }
@@ -2501,8 +2626,12 @@ export class ClaudeAcpAgent {
2501
2626
  if (previousModelId !== value) {
2502
2627
  session.fastModeOn = false;
2503
2628
  session.fastModeAvailable = false;
2629
+ // Item 84 — Ultracode's intent survives the switch (the option just hides on a model that
2630
+ // cannot run it); a refusal about the OLD model no longer applies.
2631
+ if (session.ultracodeRefusal?.scope === "model")
2632
+ session.ultracodeRefusal = undefined;
2504
2633
  }
2505
- session.configOptions = buildConfigOptions(session.modes, value, session.modelInfos, currentEffort, session.agents ?? [], currentAgent, session.fastModeAvailable ?? false, session.fastModeOn ?? false, clientSupportsBooleanConfigOptions(this.clientCapabilities));
2634
+ session.configOptions = buildConfigOptions(session.modes, value, session.modelInfos, currentEffort, session.agents ?? [], currentAgent, session.fastModeAvailable ?? false, session.fastModeOn ?? false, clientSupportsBooleanConfigOptions(this.clientCapabilities), { on: session.ultracodeOn ?? false, refusal: session.ultracodeRefusal?.reason });
2506
2635
  // Story 073 (R4.2) — on a switch TO an Opus model, re-run availability detection out of band and
2507
2636
  // re-advertise the toggle (as off) when available. Fire-and-forget: the synchronous response above
2508
2637
  // ships without the toggle; refreshFastMode emits a follow-up config_option_update once it settles.
@@ -2733,10 +2862,23 @@ export class ClaudeAcpAgent {
2733
2862
  // written down goes stale silently. Falls back to the static MODEL_CATALOG on
2734
2863
  // any failure — see live-model-catalog.ts. `default` is present in both, which
2735
2864
  // is why the seed below can stay a constant.
2736
- const liveModelCatalog = await resolveModelCatalog(this.logger);
2865
+ const liveModelCatalog = await resolveModelCatalog(this.logger, this.modelCatalogSource);
2737
2866
  const availableModes = buildAvailableModes(DEFAULT_MODEL_INFO, allowBypass);
2867
+ // Item 107 (plus 0.23.5 / upstream #1218's mode half): a replay-only load starts no engine, so the
2868
+ // pump that reconciles the mode from the transcript never runs, and the thread would advertise the
2869
+ // settings default. Seed it from the mode the transcript last recorded instead — only a mode this
2870
+ // session offers, so the bypass guard above still holds. Display-only: a loaded session runs
2871
+ // nothing until it is resumed.
2872
+ let currentModeId = seededMode;
2873
+ if (creationOpts.replayOnly && started.transcriptPath) {
2874
+ const recorded = await readTranscriptPermissionMode(started.transcriptPath);
2875
+ if (recorded !== undefined && availableModes.some((m) => m.id === recorded)) {
2876
+ // Every advertised mode id is a PermissionMode (buildAvailableModes builds them from it).
2877
+ currentModeId = recorded;
2878
+ }
2879
+ }
2738
2880
  const modes = {
2739
- currentModeId: seededMode,
2881
+ currentModeId,
2740
2882
  availableModes,
2741
2883
  };
2742
2884
  // Story 056 (R3.2): discover the main-thread agent personas for THIS session's cwd (glob-only via
@@ -2745,7 +2887,9 @@ export class ClaudeAcpAgent {
2745
2887
  // is stored on the session record below so the model-change reconcile rebuilds it WITHOUT
2746
2888
  // re-globbing.
2747
2889
  const agents = this.discoverAgents(params.cwd);
2748
- const configOptions = buildConfigOptions(modes, DEFAULT_MODEL_INFO.value, liveModelCatalog, settingsManager.getSettings().effortLevel, agents, undefined);
2890
+ const configOptions = buildConfigOptions(modes, DEFAULT_MODEL_INFO.value, liveModelCatalog, settingsManager.getSettings().effortLevel, agents, undefined, false, false,
2891
+ // Item 84: the Ultracode switch shows from the first options, so negotiate its type here.
2892
+ clientSupportsBooleanConfigOptions(this.clientCapabilities));
2749
2893
  // Runtime cwd is read from inside the JSONL (story 015); fall back to the requested host cwd
2750
2894
  // until the first transcript line carries `.cwd` (the seam may return cwd === undefined early).
2751
2895
  const runtimeCwd = started.cwd ?? params.cwd;
@@ -2864,7 +3008,7 @@ function buildAvailableModes(modelInfo, allowBypass) {
2864
3008
  // `applyFlagSettings` in @anthropic-ai/claude-agent-sdk. Mapping both the
2865
3009
  // `"default"` sentinel and `undefined` (effort option absent for the model) to
2866
3010
  // `null` ensures any previously-applied flag is actually cleared.
2867
- function buildConfigOptions(modes, currentModelId, modelInfos, currentEffortLevel, agents = [], currentAgent, fastAvailable = false, currentFast = false, fastUsesBooleanOption = false) {
3011
+ function buildConfigOptions(modes, currentModelId, modelInfos, currentEffortLevel, agents = [], currentAgent, fastAvailable = false, currentFast = false, fastUsesBooleanOption = false, ultracode = { on: false }) {
2868
3012
  const options = [
2869
3013
  {
2870
3014
  id: "mode",
@@ -2924,13 +3068,8 @@ function buildConfigOptions(modes, currentModelId, modelInfos, currentEffortLeve
2924
3068
  .map((part) => (part ? part.charAt(0).toUpperCase() + part.slice(1) : part))
2925
3069
  .join(" "),
2926
3070
  })),
2927
- // Story 060 (R1.1) — the "ultracode" sentinel, LAST and after the five real levels. NOT a real
2928
- // `--effort` value (claude rejects `--effort ultracode`); it maps to xhigh + orchestration (Task 3).
2929
- { value: ULTRACODE_EFFORT, name: ULTRACODE_EFFORT_LABEL },
2930
3071
  ];
2931
- // `ultracode` is a valid current value so a configOptions rebuild (e.g. after a re-spawn) does not
2932
- // reset a selected ultracode back to "default". It stays OUT of supportedLevels (real --effort enum).
2933
- const includes = (l) => l === "default" || l === ULTRACODE_EFFORT || supportedLevels.includes(l);
3072
+ const includes = (l) => l === "default" || supportedLevels.includes(l);
2934
3073
  const validEffort = currentEffortLevel && includes(currentEffortLevel) ? currentEffortLevel : "default";
2935
3074
  options.push({
2936
3075
  id: "effort",
@@ -2942,6 +3081,12 @@ function buildConfigOptions(modes, currentModelId, modelInfos, currentEffortLeve
2942
3081
  options: effortOptions,
2943
3082
  });
2944
3083
  }
3084
+ // Item 84 — the Ultracode switch, right after effort and only on a model that can run it (xhigh).
3085
+ // Same boolean-or-select negotiation as fast mode. Hidden, not cleared, on other models: the
3086
+ // session keeps the intent and the switch reappears, still on, on a capable model.
3087
+ if (isUltracodeCapableModel(currentModelInfo)) {
3088
+ options.push(createUltracodeConfigOption(ultracode.on, fastUsesBooleanOption, ultracode.refusal));
3089
+ }
2945
3090
  // Story 056 (R3.2) — the `agent` (main-thread persona) selector, mirroring the effort option but
2946
3091
  // with a "default" no-persona sentinel. GATED on `agents.length > 0` (upstream #794): when nothing
2947
3092
  // is discovered the option is OMITTED entirely. The "default" entry = no persona (the spawn layer
@@ -3456,7 +3601,15 @@ export function toAcpNotifications(content, role, sessionId, toolUseCache, clien
3456
3601
  }
3457
3602
  }
3458
3603
  else if (toolUse.name !== "TodoWrite") {
3459
- const { _meta: toolMeta, ...toolUpdate } = toolUpdateFromToolResult(chunk, toolUseCache[chunk.tool_use_id], supportsTerminalOutput, toolUseResult);
3604
+ const background = options?.background;
3605
+ const { _meta: toolMeta, ...toolUpdate } = toolUpdateFromToolResult(chunk, toolUseCache[chunk.tool_use_id], supportsTerminalOutput, toolUseResult, background
3606
+ ? { ended: background.ended, holdRunning: background.held !== undefined }
3607
+ : undefined);
3608
+ // A terminal announced without its exit is a backgrounded command still running: remember it
3609
+ // so the live pump sends the exit when the task ends.
3610
+ if (background?.held && toolMeta?.terminal_info && !toolMeta.terminal_exit) {
3611
+ background.held.add(toolMeta.terminal_info.terminal_id);
3612
+ }
3460
3613
  // When terminal output is supported, send terminal_output as a
3461
3614
  // separate notification to match codex-acp's streaming lifecycle:
3462
3615
  // 1. tool_call → _meta.terminal_info (already sent above)
@@ -3607,7 +3760,7 @@ export function inferContextWindowFromModel(model) {
3607
3760
  * field), used by the pump to refine the alias seed once the model is known. Exact-ID lookup first
3608
3761
  * (MODEL_ID_CONTEXT_WINDOWS), then a family+version heuristic for dated snapshots / future variants
3609
3762
  * (Opus is NOT uniform: 4.6 and earlier = 200K, 4.7+ = 1M; Sonnet 4.x = 200K but Sonnet 5+ = 1M;
3610
- * haiku = 200K; fable = 1M — story 071), then a
3763
+ * Haiku 4.x = 200K but Haiku 5+ = 1M — item 93; fable = 1M — story 071), then a
3611
3764
  * `\b1m\b` suffix, then null (R1.3: a missing / non-string id never refines). */
3612
3765
  export function inferContextWindowFromModelId(id) {
3613
3766
  if (typeof id !== "string" || id.length === 0)
@@ -3633,7 +3786,10 @@ export function inferContextWindowFromModelId(id) {
3633
3786
  const sonnet = id.match(/claude-sonnet-(\d+)/);
3634
3787
  if (sonnet)
3635
3788
  return Number(sonnet[1]) >= 5 ? 1_000_000 : 200_000;
3636
- if (/claude-haiku/.test(id))
3637
- return 200_000;
3789
+ // Haiku split the same way (item 93): Haiku 4.x is 200K, Haiku 5.5 is native 1M (the CLI's baked-in
3790
+ // catalogue: `context:{window:1e6,native_1m:!0}`). A blanket 200K under-sized every Haiku 5.5 turn.
3791
+ const haiku = id.match(/claude-haiku-(\d+)/);
3792
+ if (haiku)
3793
+ return Number(haiku[1]) >= 5 ? 1_000_000 : 200_000;
3638
3794
  return null;
3639
3795
  }
@@ -0,0 +1,11 @@
1
+ /** How a backgrounded command's task ended, as the notification reports it. */
2
+ export type BackgroundTaskEnd = {
3
+ status: string;
4
+ exitCode: number;
5
+ };
6
+ /**
7
+ * Index every ended background task in the raw transcript lines by the `tool_use_id` of the call that
8
+ * started it. Lines that are not JSON, or carry no notification, are skipped; the last notification for
9
+ * an id wins. Pure; never throws.
10
+ */
11
+ export declare function backgroundTaskEnds(lines: readonly string[]): Map<string, BackgroundTaskEnd>;