@lucascouts/claude-agent-tui 0.13.3 → 0.14.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.
@@ -617,7 +617,9 @@ export type ToolUseCache = {
617
617
  * Return user-message content with local-command marker tags removed, or
618
618
  * `null` if nothing meaningful remains (caller should skip the message).
619
619
  * Preserves real prose that's mixed in alongside the markers — e.g. a
620
- * message like `<command-name>…</command-name>hi` becomes `hi`.
620
+ * message like `<command-name>…</command-name>hi` becomes `hi`. A marker-only
621
+ * slash-skill record is reconstructed as `/name args` unless it is client-local
622
+ * (see REPLAY_HIDDEN_COMMANDS) or carries local stdout/stderr.
621
623
  */
622
624
  export declare function stripLocalCommandMetadata(content: unknown): unknown | null;
623
625
  export declare function isLocalCommandMetadata(content: unknown): boolean;
@@ -1051,7 +1053,7 @@ export declare function runAcp(deps?: AgentDeps): {
1051
1053
  * not call), as detailed below.
1052
1054
  *
1053
1055
  * Story 068 (R1, R1.1, R1.2): consults the static {@link MODEL_CONTEXT_WINDOWS}
1054
- * alias→window map FIRST (an exact catalog-`value` hit — `default`/`fable5`/`opus`/
1056
+ * alias→window map FIRST (an exact catalog-`value` hit — `default`/`fable`/`opus`/
1055
1057
  * `sonnet`=1M, `haiku`=200K). This fixes `opus` having wrongly reported 200K, and
1056
1058
  * `sonnet` now seeds 1M (Sonnet 5 is native 1M). An alias absent from the map then
1057
1059
  * falls back to the legacy `\b1m\b` inference: Anthropic 1M-context variants
package/dist/acp-agent.js CHANGED
@@ -25,7 +25,8 @@ import { guardEvent } from "./billing/entrypoint-guard.js";
25
25
  import { usageUpdatesFor } from "./usage.js";
26
26
  import { createTurnResolver } from "./end-of-turn.js";
27
27
  import { sendPrompt } from "./engine-pty.js";
28
- import { MODEL_CATALOG, MODEL_CONTEXT_WINDOWS, MODEL_ID_CONTEXT_WINDOWS, modelSelectorDescription, DEFAULT_MODEL_INFO, resolveCatalogValueFromModelId, isFastModeCapableModel, classifyFastModeSignal, FAST_MODE_CONFIG_ID, FAST_MODE_ON, FAST_MODE_OFF, createFastModeConfigOption, clientSupportsBooleanConfigOptions, resolveFastModeEnabled, ULTRACODE_EFFORT, ULTRACODE_EFFORT_LEVEL, ULTRACODE_EFFORT_LABEL, } from "./model-catalog.js";
28
+ import { MODEL_CONTEXT_WINDOWS, MODEL_ID_CONTEXT_WINDOWS, modelSelectorDescription, DEFAULT_MODEL_INFO, resolveCatalogValueFromModelId, isFastModeCapableModel, classifyFastModeSignal, FAST_MODE_CONFIG_ID, FAST_MODE_ON, FAST_MODE_OFF, createFastModeConfigOption, clientSupportsBooleanConfigOptions, resolveFastModeEnabled, ULTRACODE_EFFORT, ULTRACODE_EFFORT_LEVEL, ULTRACODE_EFFORT_LABEL, } from "./model-catalog.js";
29
+ import { resolveModelCatalog } from "./live-model-catalog.js";
29
30
  // Story 060 (R2.2/R2.3/R3.2) — the declarative spawn-time complement to the live ultracode keyword:
30
31
  // toggle the {ultracode,ultracodeKeywordTrigger} keys in the gate's per-session scratch settings file
31
32
  // (preserving the hook + every other key). Lives in the gate's settings-writer so it reuses durableWrite.
@@ -457,6 +458,24 @@ const IS_ROOT = (process.geteuid?.() ?? process.getuid?.()) === 0;
457
458
  const ALLOW_BYPASS = !IS_ROOT || !!process.env.IS_SANDBOX;
458
459
  // Slash commands that the SDK handles locally without replaying the user
459
460
  // message and without invoking the model.
461
+ const LOCAL_ONLY_COMMANDS = new Set(["/context", "/heapdump", "/extra-usage"]);
462
+ // Commands whose marker-only transcript records are client-local UI noise, not
463
+ // model-visible user prompts (port of upstream #1035, 97394d9). Marker-only
464
+ // custom slash skills are not in this list, so replay can reconstruct them from
465
+ // `<command-name>`/`<command-args>`. `/effort` and `/fast` are the tui's own:
466
+ // the config-option applies and the fast-mode probe type them into the PTY, and
467
+ // the CLI records them like any user-typed command — without an entry every
468
+ // config change would surface in the thread as a prompt the user never sent.
469
+ // `/model` is injected the same way and is already covered upstream.
470
+ const REPLAY_HIDDEN_COMMANDS = new Set([
471
+ ...LOCAL_ONLY_COMMANDS,
472
+ "/compact",
473
+ "/model",
474
+ "/status",
475
+ "/usage",
476
+ "/effort",
477
+ "/fast",
478
+ ]);
460
479
  // The Claude SDK persists local slash command invocations (e.g. `/model`) and
461
480
  // their output as user messages in the session transcript, wrapping the
462
481
  // payload in these XML-like markers that the CLI uses for its own display.
@@ -497,16 +516,49 @@ function stripMarkerTags(text) {
497
516
  }
498
517
  return result + text.slice(copiedUpTo);
499
518
  }
519
+ function markerTagText(text, tag) {
520
+ const open = `<${tag}>`;
521
+ const close = `</${tag}>`;
522
+ const start = text.indexOf(open);
523
+ if (start === -1)
524
+ return undefined;
525
+ const end = text.indexOf(close, start + open.length);
526
+ if (end === -1)
527
+ return undefined;
528
+ return text.slice(start + open.length, end);
529
+ }
530
+ function hasMarkerTag(text, tag) {
531
+ return markerTagText(text, tag) !== undefined;
532
+ }
533
+ function commandInvocationFromMarkerOnlyText(text) {
534
+ if (hasMarkerTag(text, "local-command-stdout") || hasMarkerTag(text, "local-command-stderr")) {
535
+ return null;
536
+ }
537
+ const commandName = markerTagText(text, "command-name")?.trim();
538
+ if (!commandName?.startsWith("/"))
539
+ return null;
540
+ if (REPLAY_HIDDEN_COMMANDS.has(commandName.split(" ", 1)[0]))
541
+ return null;
542
+ const commandArgs = markerTagText(text, "command-args")?.trim();
543
+ return commandArgs ? `${commandName} ${commandArgs}` : commandName;
544
+ }
545
+ function stripLocalCommandMetadataText(text) {
546
+ const stripped = stripMarkerTags(text);
547
+ if (stripped.trim() !== "")
548
+ return stripped;
549
+ return commandInvocationFromMarkerOnlyText(text);
550
+ }
500
551
  /**
501
552
  * Return user-message content with local-command marker tags removed, or
502
553
  * `null` if nothing meaningful remains (caller should skip the message).
503
554
  * Preserves real prose that's mixed in alongside the markers — e.g. a
504
- * message like `<command-name>…</command-name>hi` becomes `hi`.
555
+ * message like `<command-name>…</command-name>hi` becomes `hi`. A marker-only
556
+ * slash-skill record is reconstructed as `/name args` unless it is client-local
557
+ * (see REPLAY_HIDDEN_COMMANDS) or carries local stdout/stderr.
505
558
  */
506
559
  export function stripLocalCommandMetadata(content) {
507
560
  if (typeof content === "string") {
508
- const stripped = stripMarkerTags(content);
509
- return stripped.trim() === "" ? null : stripped;
561
+ return stripLocalCommandMetadataText(content);
510
562
  }
511
563
  if (!Array.isArray(content))
512
564
  return content;
@@ -518,8 +570,8 @@ export function stripLocalCommandMetadata(content) {
518
570
  block.type === "text" &&
519
571
  "text" in block &&
520
572
  typeof block.text === "string") {
521
- const stripped = stripMarkerTags(block.text);
522
- if (stripped.trim() === "")
573
+ const stripped = stripLocalCommandMetadataText(block.text);
574
+ if (stripped === null)
523
575
  continue;
524
576
  kept.push({ ...block, text: stripped });
525
577
  }
@@ -2654,6 +2706,12 @@ export class ClaudeAcpAgent {
2654
2706
  // with the current model seeded to the safe `default`. Populating the catalog also unlocks the
2655
2707
  // effort selector via buildConfigOptions (§5/§7). The current MODE is still seeded "default" here;
2656
2708
  // Task 4.1 reseeds it from settings.permissions.defaultMode.
2709
+ // The picker is READ FROM THE CLI, not curated here: the catalogue is served by
2710
+ // the backend and was measured changing shape twice in one day, so any list
2711
+ // written down goes stale silently. Falls back to the static MODEL_CATALOG on
2712
+ // any failure — see live-model-catalog.ts. `default` is present in both, which
2713
+ // is why the seed below can stay a constant.
2714
+ const liveModelCatalog = await resolveModelCatalog(this.logger);
2657
2715
  const availableModes = buildAvailableModes(DEFAULT_MODEL_INFO);
2658
2716
  const modes = {
2659
2717
  currentModeId: seededMode,
@@ -2665,7 +2723,7 @@ export class ClaudeAcpAgent {
2665
2723
  // is stored on the session record below so the model-change reconcile rebuilds it WITHOUT
2666
2724
  // re-globbing.
2667
2725
  const agents = this.discoverAgents(params.cwd);
2668
- const configOptions = buildConfigOptions(modes, DEFAULT_MODEL_INFO.value, MODEL_CATALOG, settingsManager.getSettings().effortLevel, agents, undefined);
2726
+ const configOptions = buildConfigOptions(modes, DEFAULT_MODEL_INFO.value, liveModelCatalog, settingsManager.getSettings().effortLevel, agents, undefined);
2669
2727
  // Runtime cwd is read from inside the JSONL (story 015); fall back to the requested host cwd
2670
2728
  // until the first transcript line carries `.cwd` (the seam may return cwd === undefined early).
2671
2729
  const runtimeCwd = started.cwd ?? params.cwd;
@@ -2696,7 +2754,7 @@ export class ClaudeAcpAgent {
2696
2754
  cachedWriteTokens: 0,
2697
2755
  },
2698
2756
  modes,
2699
- modelInfos: MODEL_CATALOG,
2757
+ modelInfos: liveModelCatalog,
2700
2758
  agents,
2701
2759
  configOptions,
2702
2760
  contextWindowSize: inferContextWindowFromModel(DEFAULT_MODEL_INFO.value) ?? DEFAULT_CONTEXT_WINDOW,
@@ -2812,7 +2870,7 @@ function buildConfigOptions(modes, currentModelId, modelInfos, currentEffortLeve
2812
2870
  options: modelInfos.map((m) => ({
2813
2871
  value: m.value,
2814
2872
  name: m.displayName,
2815
- // Story 072 — prepend the version/context label ("Opus 4.8 with 1M context · <tagline>"),
2873
+ // Story 072 — prepend the version/context label ("Opus 5.5 with 1M context · <tagline>"),
2816
2874
  // mirroring the live `/model` picker; bare tagline when no label (e.g. opusplan).
2817
2875
  description: modelSelectorDescription(m) || undefined,
2818
2876
  })),
@@ -3500,7 +3558,7 @@ export function runAcp(deps) {
3500
3558
  * not call), as detailed below.
3501
3559
  *
3502
3560
  * Story 068 (R1, R1.1, R1.2): consults the static {@link MODEL_CONTEXT_WINDOWS}
3503
- * alias→window map FIRST (an exact catalog-`value` hit — `default`/`fable5`/`opus`/
3561
+ * alias→window map FIRST (an exact catalog-`value` hit — `default`/`fable`/`opus`/
3504
3562
  * `sonnet`=1M, `haiku`=200K). This fixes `opus` having wrongly reported 200K, and
3505
3563
  * `sonnet` now seeds 1M (Sonnet 5 is native 1M). An alias absent from the map then
3506
3564
  * falls back to the legacy `\b1m\b` inference: Anthropic 1M-context variants
@@ -3514,7 +3572,12 @@ export function inferContextWindowFromModel(model) {
3514
3572
  return mapped; // exact alias hit (!== undefined, NOT truthiness)
3515
3573
  if (/\b1m\b/i.test(model))
3516
3574
  return 1_000_000; // unknown alias that still encodes a 1m token
3517
- return null; // caller applies ?? DEFAULT_CONTEXT_WINDOW
3575
+ // A LIVE picker value is often a full wire id (`claude-fable-5-1`), which the
3576
+ // curated alias map cannot contain and the `1m` token does not mark. Reuse the
3577
+ // id-shaped resolver rather than duplicating its family/version table — without
3578
+ // this, every live row seeds 200K and Fable/Opus under-report until the first
3579
+ // turn corrects them.
3580
+ return inferContextWindowFromModelId(model);
3518
3581
  }
3519
3582
  /** Story 069 (R1) — AUTHORITATIVE context window from a turn's REAL model ID (the JSONL `model`
3520
3583
  * field), used by the pump to refine the alias seed once the model is known. Exact-ID lookup first
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { resolveSettings } from "@anthropic-ai/claude-agent-sdk";
3
2
  import { runAcp, driveFastModeProbe } from "./acp-agent.js";
3
+ import { applyManagedPolicyEnv } from "./managed-policy.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";
@@ -50,13 +50,10 @@ else if (process.argv.includes("--version")) {
50
50
  }
51
51
  else {
52
52
  // Apply env vars from the managed-policy tier before any SDK call so the
53
- // SDK subprocess inherits them. Going through resolveSettings (vs. a raw
54
- // read of managed-settings.json) also picks up MDM sources on macOS and
55
- // HKLM/HKCU on Windows.
56
- const policy = await resolveSettings({ settingSources: [] });
57
- for (const [key, value] of Object.entries(policy.effective.env ?? {})) {
58
- process.env[key] = value;
59
- }
53
+ // SDK subprocess inherits them. Reading the tier is best-effort: a transient
54
+ // failure leaves the agent running with no policy env instead of aborting
55
+ // module evaluation here, before any ACP traffic (port of upstream #1146).
56
+ await applyManagedPolicyEnv();
60
57
  // stdout is used to send messages to the client
61
58
  // we redirect everything else to stderr to make sure it doesn't interfere with ACP
62
59
  console.log = console.error;
@@ -0,0 +1,79 @@
1
+ import type { ModelInfo } from "@anthropic-ai/claude-agent-sdk";
2
+ /**
3
+ * The model picker, read from the CLI at runtime instead of curated by hand.
4
+ *
5
+ * WHY THIS REPLACED A STATIC LIST. `model-catalog.ts` was written when the CLI
6
+ * appeared to expose no way to enumerate models, and that premise was wrong: the
7
+ * SDK's `query().supportedModels()` is exactly such an endpoint, and this package
8
+ * already depends on the SDK. The hand-curated list cost two silent bugs in one
9
+ * month — `fable51`/`fable5`, aliases the CLI rejects outright, and an `Opus 4.8`
10
+ * label on rows that had been serving Opus 5.5 for weeks. Neither failed a test,
11
+ * because there was nothing to compare the list against.
12
+ *
13
+ * WHAT MADE IT UNFIXABLE BY HAND. The catalogue is served by the BACKEND, not
14
+ * baked into the installed CLI. Measured 2026-09-23, it alternated between two
15
+ * shapes within minutes under a fixed binary — five rows with `[1m]`-suffixed
16
+ * values and bare family titles ("Fable", "Opus (1M context)"), and eleven rows
17
+ * with version-bearing titles ("Fable 5.1", "Opus 5.5") and different taglines
18
+ * entirely. No snapshot of either is right for long, so the only list that stays
19
+ * correct is the one fetched.
20
+ *
21
+ * **It must be the PATH `claude`, never the SDK's embedded binary.** That is the
22
+ * keystone this whole fork rests on: the PATH binary bills as subscription
23
+ * (`entrypoint == 'cli'`), the SDK-embedded one bills as credit — see
24
+ * `claude-path.ts`. Pointing the fetch at the embedded binary would also read a
25
+ * DIFFERENT catalogue from the one the PTY actually runs, which is the exact
26
+ * divergence this module exists to close. Both reasons point the same way.
27
+ *
28
+ * FAIL-SOFT, ALWAYS. Every failure path — no CLI on PATH, a spawn error, a
29
+ * control-request timeout, an empty answer — falls back to {@link MODEL_CATALOG}.
30
+ * The static list is therefore no longer the source of truth, but it is still the
31
+ * floor: a picker with stale rows beats a session that cannot start.
32
+ *
33
+ * @module live-model-catalog
34
+ */
35
+ /** How long a fetched catalogue is reused before the next session refetches it. */
36
+ export declare const CATALOG_TTL_MS: number;
37
+ /** How long to wait for `supportedModels()` before falling back. */
38
+ export declare const CATALOG_TIMEOUT_MS = 20000;
39
+ /** Injectable seam: returns the raw SDK rows. Replaced wholesale in tests — no spawn, no CLI. */
40
+ export type SupportedModelsSource = () => Promise<ModelInfo[]>;
41
+ interface CatalogLogger {
42
+ log: (...args: unknown[]) => void;
43
+ }
44
+ /** Drop the memoised catalogue AND the once-per-process report latch. Tests use it; production does not. */
45
+ export declare function resetLiveModelCatalogCache(): void;
46
+ /**
47
+ * Rewrite the `default` row's description to NAME the model it resolves to.
48
+ *
49
+ * The CLI ships `default` with a description of its own ("Opus 5.5 · Best for
50
+ * everyday, complex tasks"), which tells the user everything except the one thing
51
+ * the row is ambiguous about — which model "Default (recommended)" actually is
52
+ * today. Upstream `claude-agent-acp` and `claude-agent-plus` both replace it with
53
+ * the sibling row's title ("Opus 5.5"), and this fork matches them: three
54
+ * adapters rendering the same catalogue should render it the same way.
55
+ *
56
+ * The sibling is found by shared `resolvedModel`, never by family name or
57
+ * position — the alias that resolves alongside `default` is exactly the row whose
58
+ * title is the honest answer. With no sibling and no `resolvedModel` the row is
59
+ * returned UNTOUCHED, which is the only safe move: an invented description would
60
+ * be worse than the vendor's own.
61
+ *
62
+ * Returns a new array; the untouched rows keep their identity.
63
+ */
64
+ export declare function nameDefaultRow(models: ModelInfo[]): ModelInfo[];
65
+ /**
66
+ * The picker list for a new session: the live catalogue with superseded
67
+ * generations removed, or {@link MODEL_CATALOG} if anything at all goes wrong.
68
+ *
69
+ * Memoised for {@link CATALOG_TTL_MS}, because the alternative is one CLI spawn
70
+ * per session and the catalogue does not move on that timescale. A fallback is
71
+ * NEVER cached: a CLI that was missing when the first session started may be
72
+ * present by the next one, and caching the failure would keep the picker stale
73
+ * for the rest of the process.
74
+ *
75
+ * @param logger - Where a fallback is reported. Optional, for library callers.
76
+ * @param source - Test seam; defaults to spawning the PATH `claude`.
77
+ */
78
+ export declare function resolveModelCatalog(logger?: CatalogLogger, source?: SupportedModelsSource): Promise<ModelInfo[]>;
79
+ export {};
@@ -0,0 +1,167 @@
1
+ import { MODEL_CATALOG } from "./model-catalog.js";
2
+ import { filterSupersededModels } from "./model-recency.js";
3
+ import { resolveClaudePath } from "./claude-path.js";
4
+ /**
5
+ * The model picker, read from the CLI at runtime instead of curated by hand.
6
+ *
7
+ * WHY THIS REPLACED A STATIC LIST. `model-catalog.ts` was written when the CLI
8
+ * appeared to expose no way to enumerate models, and that premise was wrong: the
9
+ * SDK's `query().supportedModels()` is exactly such an endpoint, and this package
10
+ * already depends on the SDK. The hand-curated list cost two silent bugs in one
11
+ * month — `fable51`/`fable5`, aliases the CLI rejects outright, and an `Opus 4.8`
12
+ * label on rows that had been serving Opus 5.5 for weeks. Neither failed a test,
13
+ * because there was nothing to compare the list against.
14
+ *
15
+ * WHAT MADE IT UNFIXABLE BY HAND. The catalogue is served by the BACKEND, not
16
+ * baked into the installed CLI. Measured 2026-09-23, it alternated between two
17
+ * shapes within minutes under a fixed binary — five rows with `[1m]`-suffixed
18
+ * values and bare family titles ("Fable", "Opus (1M context)"), and eleven rows
19
+ * with version-bearing titles ("Fable 5.1", "Opus 5.5") and different taglines
20
+ * entirely. No snapshot of either is right for long, so the only list that stays
21
+ * correct is the one fetched.
22
+ *
23
+ * **It must be the PATH `claude`, never the SDK's embedded binary.** That is the
24
+ * keystone this whole fork rests on: the PATH binary bills as subscription
25
+ * (`entrypoint == 'cli'`), the SDK-embedded one bills as credit — see
26
+ * `claude-path.ts`. Pointing the fetch at the embedded binary would also read a
27
+ * DIFFERENT catalogue from the one the PTY actually runs, which is the exact
28
+ * divergence this module exists to close. Both reasons point the same way.
29
+ *
30
+ * FAIL-SOFT, ALWAYS. Every failure path — no CLI on PATH, a spawn error, a
31
+ * control-request timeout, an empty answer — falls back to {@link MODEL_CATALOG}.
32
+ * The static list is therefore no longer the source of truth, but it is still the
33
+ * floor: a picker with stale rows beats a session that cannot start.
34
+ *
35
+ * @module live-model-catalog
36
+ */
37
+ /** How long a fetched catalogue is reused before the next session refetches it. */
38
+ export const CATALOG_TTL_MS = 10 * 60 * 1000;
39
+ /** How long to wait for `supportedModels()` before falling back. */
40
+ export const CATALOG_TIMEOUT_MS = 20_000;
41
+ let cache = null;
42
+ /** Whether the fallback has already been reported in this process. See {@link resolveModelCatalog}. */
43
+ let fallbackReported = false;
44
+ /** Drop the memoised catalogue AND the once-per-process report latch. Tests use it; production does not. */
45
+ export function resetLiveModelCatalogCache() {
46
+ cache = null;
47
+ fallbackReported = false;
48
+ }
49
+ /**
50
+ * The production source: spawn the PATH `claude` through the SDK purely to read
51
+ * its model list, then shut it down. `supportedModels()` is a control request,
52
+ * not a turn — it sends no prompt and consumes no quota.
53
+ */
54
+ async function defaultSource() {
55
+ const { query } = await import("@anthropic-ai/claude-agent-sdk");
56
+ const q = query({
57
+ prompt: "",
58
+ options: {
59
+ pathToClaudeCodeExecutable: resolveClaudePath(),
60
+ // Read the user's own settings, so the catalogue matches what their CLI
61
+ // would offer; the fetch is otherwise inert.
62
+ settingSources: ["user"],
63
+ },
64
+ });
65
+ try {
66
+ return await q.supportedModels();
67
+ }
68
+ finally {
69
+ // Never let a failed teardown mask a successful read.
70
+ try {
71
+ q.return(undefined);
72
+ }
73
+ catch {
74
+ /* the process is going away regardless */
75
+ }
76
+ }
77
+ }
78
+ /** Reject after {@link CATALOG_TIMEOUT_MS} so a hung control request cannot stall session creation. */
79
+ function withTimeout(promise, ms) {
80
+ return new Promise((resolve, reject) => {
81
+ const timer = setTimeout(() => reject(new Error(`model catalogue fetch timed out after ${ms}ms`)), ms);
82
+ promise.then((value) => {
83
+ clearTimeout(timer);
84
+ resolve(value);
85
+ }, (error) => {
86
+ clearTimeout(timer);
87
+ reject(error);
88
+ });
89
+ });
90
+ }
91
+ /**
92
+ * Rewrite the `default` row's description to NAME the model it resolves to.
93
+ *
94
+ * The CLI ships `default` with a description of its own ("Opus 5.5 · Best for
95
+ * everyday, complex tasks"), which tells the user everything except the one thing
96
+ * the row is ambiguous about — which model "Default (recommended)" actually is
97
+ * today. Upstream `claude-agent-acp` and `claude-agent-plus` both replace it with
98
+ * the sibling row's title ("Opus 5.5"), and this fork matches them: three
99
+ * adapters rendering the same catalogue should render it the same way.
100
+ *
101
+ * The sibling is found by shared `resolvedModel`, never by family name or
102
+ * position — the alias that resolves alongside `default` is exactly the row whose
103
+ * title is the honest answer. With no sibling and no `resolvedModel` the row is
104
+ * returned UNTOUCHED, which is the only safe move: an invented description would
105
+ * be worse than the vendor's own.
106
+ *
107
+ * Returns a new array; the untouched rows keep their identity.
108
+ */
109
+ export function nameDefaultRow(models) {
110
+ const defaultRow = models.find((m) => m.value === "default");
111
+ const resolved = defaultRow?.resolvedModel;
112
+ if (!defaultRow || !resolved)
113
+ return models;
114
+ const sibling = models.find((m) => m.value !== "default" && m.resolvedModel === resolved);
115
+ const description = sibling?.displayName ?? resolved;
116
+ return models.map((m) => (m === defaultRow ? { ...m, description } : m));
117
+ }
118
+ /**
119
+ * The picker list for a new session: the live catalogue with superseded
120
+ * generations removed, or {@link MODEL_CATALOG} if anything at all goes wrong.
121
+ *
122
+ * Memoised for {@link CATALOG_TTL_MS}, because the alternative is one CLI spawn
123
+ * per session and the catalogue does not move on that timescale. A fallback is
124
+ * NEVER cached: a CLI that was missing when the first session started may be
125
+ * present by the next one, and caching the failure would keep the picker stale
126
+ * for the rest of the process.
127
+ *
128
+ * @param logger - Where a fallback is reported. Optional, for library callers.
129
+ * @param source - Test seam; defaults to spawning the PATH `claude`.
130
+ */
131
+ export async function resolveModelCatalog(logger, source = defaultSource) {
132
+ if (cache && Date.now() - cache.at < CATALOG_TTL_MS)
133
+ return cache.models;
134
+ try {
135
+ const raw = await withTimeout(source(), CATALOG_TIMEOUT_MS);
136
+ if (!Array.isArray(raw) || raw.length === 0) {
137
+ throw new Error("the CLI returned no models");
138
+ }
139
+ const models = nameDefaultRow(filterSupersededModels(raw));
140
+ // filterSupersededModels fails open, so an empty result here means the input
141
+ // was empty — already excluded above. Guard anyway: an empty picker is worse
142
+ // than a stale one, and this function must never return one.
143
+ const resolved = models.length > 0 ? models : raw;
144
+ cache = { models: resolved, at: Date.now() };
145
+ return resolved;
146
+ }
147
+ catch (error) {
148
+ // `log`, NOT `error`, and ONCE per process. Both halves are deliberate.
149
+ //
150
+ // Level: this path is degraded-but-recovered — the picker still works, from
151
+ // the built-in list. An unreachable CLI that actually matters surfaces
152
+ // LOUDLY a moment later, when `resolveClaudePath` throws out of the PTY
153
+ // engine; raising ERROR here would be a second alarm for a fault that
154
+ // already has one, or a false alarm for a fetch that merely timed out.
155
+ //
156
+ // Once: the condition does not change between sessions in a process, so
157
+ // re-reporting it per session is pure noise. It also stopped two unrelated
158
+ // suites dead — they assert an exact error count on the agent, and a
159
+ // per-session ERROR from here made it 2 where they expect 1. That was a real
160
+ // defect this caught, not a test to loosen.
161
+ if (!fallbackReported) {
162
+ fallbackReported = true;
163
+ logger?.log(`Could not read the model catalogue from the CLI; using the built-in list for this process. ${String(error)}`);
164
+ }
165
+ return MODEL_CATALOG;
166
+ }
167
+ }
@@ -0,0 +1,20 @@
1
+ import { resolveSettings } from "@anthropic-ai/claude-agent-sdk";
2
+ /**
3
+ * Applies the managed-policy tier's env vars to `process.env` before any SDK
4
+ * call, so the spawned CLI inherits them. Going through `resolveSettings`
5
+ * rather than a raw read of `managed-settings.json` also picks up MDM sources on
6
+ * macOS and `HKLM`/`HKCU` on Windows.
7
+ *
8
+ * Port of upstream #1146 (58c5db1). Reading the tier is best-effort by nature:
9
+ * on a host with no MDM and no managed policy the result is empty and the agent
10
+ * behaves identically. So a transient failure to read it — `EINTR`, `EMFILE`,
11
+ * `EAGAIN` — must leave the agent running with no policy env rather than stop
12
+ * it from starting.
13
+ *
14
+ * That guard matters because index.ts awaits this at module scope in an ESM
15
+ * entry point, before its `unhandledRejection` handler exists, where a
16
+ * rejection aborts module evaluation and the process exits before serving any
17
+ * ACP traffic. `SettingsManager` (settings.ts) wraps the same SDK call for the
18
+ * same reason.
19
+ */
20
+ export declare function applyManagedPolicyEnv(resolve?: typeof resolveSettings, env?: Record<string, string | undefined>): Promise<void>;
@@ -0,0 +1,33 @@
1
+ import { resolveSettings } from "@anthropic-ai/claude-agent-sdk";
2
+ /**
3
+ * Applies the managed-policy tier's env vars to `process.env` before any SDK
4
+ * call, so the spawned CLI inherits them. Going through `resolveSettings`
5
+ * rather than a raw read of `managed-settings.json` also picks up MDM sources on
6
+ * macOS and `HKLM`/`HKCU` on Windows.
7
+ *
8
+ * Port of upstream #1146 (58c5db1). Reading the tier is best-effort by nature:
9
+ * on a host with no MDM and no managed policy the result is empty and the agent
10
+ * behaves identically. So a transient failure to read it — `EINTR`, `EMFILE`,
11
+ * `EAGAIN` — must leave the agent running with no policy env rather than stop
12
+ * it from starting.
13
+ *
14
+ * That guard matters because index.ts awaits this at module scope in an ESM
15
+ * entry point, before its `unhandledRejection` handler exists, where a
16
+ * rejection aborts module evaluation and the process exits before serving any
17
+ * ACP traffic. `SettingsManager` (settings.ts) wraps the same SDK call for the
18
+ * same reason.
19
+ */
20
+ export async function applyManagedPolicyEnv(resolve = resolveSettings, env = process.env) {
21
+ let policy;
22
+ try {
23
+ policy = await resolve({ settingSources: [] });
24
+ }
25
+ catch (error) {
26
+ // stderr, so the ACP stream on stdout stays clean.
27
+ console.error("Failed to resolve managed policy settings:", error);
28
+ return;
29
+ }
30
+ for (const [key, value] of Object.entries(policy.effective.env ?? {})) {
31
+ env[key] = value;
32
+ }
33
+ }
@@ -18,18 +18,43 @@ export declare const ULTRACODE_EFFORT_LEVEL = "xhigh";
18
18
  /** Selector label — makes clear it is xhigh + orchestration, NOT a duplicate of the plain `xhigh` entry. */
19
19
  export declare const ULTRACODE_EFFORT_LABEL = "ultracode (xhigh + orchestration)";
20
20
  /**
21
+ * The FALLBACK model list — no longer what the picker normally shows.
22
+ *
23
+ * `live-model-catalog.ts` reads the real list from the CLI at session creation;
24
+ * this is what it falls back to when that read fails (no `claude` on PATH, a
25
+ * spawn error, a timeout). Everything below about hand-curation still applies to
26
+ * THESE rows, and the reason it is no longer the primary source is in that
27
+ * module's doc: the catalogue is backend-served and was measured changing shape
28
+ * twice in one day, which no hand-written list can track.
29
+ *
30
+ * Keep these rows CURRENT anyway. A fallback that nobody maintains is a fallback
31
+ * that ships a two-year-old model list on the day the CLI goes missing.
32
+ *
21
33
  * The static curated catalog advertised to the Zed Agent Panel's `model` selector. Each `value` is a
22
34
  * `claude` TUI alias accepted by `/model <alias>` (live) and `--model <alias>` (spawn). `default` is
23
35
  * first and is the safe fallback.
24
36
  *
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).
37
+ * ORDER + membership: `Default (recommended)`, `Fable`, `Opus`, `Sonnet`, `Haiku` — TIER aliases only,
38
+ * never a version-numbered one. The original gets its list from the SDK `supportedModels()` the fork
39
+ * cut, so we curate it statically. The redundant `sonnet[1m]` alias was dropped: Sonnet 5 is natively
40
+ * 1M, so plain `sonnet` already IS the 1M model. The fork-only `opusplan` extra was dropped too (three
41
+ * Sonnet-flavored entries + inconsistent Opus thinking made it more confusing than useful).
31
42
  *
32
- * Effort-capable models (`default`/`fable5`/`opus`/`sonnet`) carry `supportsEffort` +
43
+ * **The CLI's alias vocabulary is a CLOSED SET, and a version-numbered alias is not in it.** Measured
44
+ * on claude 2.1.280: the accepted spellings are exactly
45
+ * `["sonnet","opus","haiku","fable","best","sonnet[1m]","opus[1m]","fable[1m]","opusplan"]` — plus any
46
+ * full wire id (`claude-opus-5-5`). Anything else 404s at spawn with `[claude-code:unrecognized_model]`,
47
+ * which is how the `fable51` and `fable5` rows this catalogue used to carry were BOTH dead: the binary
48
+ * contains those tokens (they are the CLI's internal id→short-name map), so reading them out of
49
+ * `strings` looked like confirmation and was not. **Probe an alias with a real turn before adding a
50
+ * row**: `claude -p ok --model <alias> --output-format json | jq '.is_error, .modelUsage'`.
51
+ *
52
+ * A tier alias always points at the newest member of its family, so these rows do NOT age out on a
53
+ * model launch — only the version text in the row does. Verified 2026-09-23:
54
+ * `opus` → `claude-opus-5-5`, `fable` → `claude-fable-5-1`, `sonnet` → `claude-sonnet-5`,
55
+ * `haiku` → `claude-haiku-4-5-20251001`.
56
+ *
57
+ * Effort-capable models (`default`/`fable`/`opus`/`sonnet`) carry `supportsEffort` +
33
58
  * `supportedEffortLevels`; `haiku` advertises none. `supportsAutoMode: true` on the same four surfaces
34
59
  * the `auto` permission mode (a model classifier) — the original drops `auto` on `haiku` (the SDK signal
35
60
  * `reconcileModeFromTranscript` clamps), so haiku omits it.
@@ -37,14 +62,14 @@ export declare const ULTRACODE_EFFORT_LABEL = "ultracode (xhigh + orchestration)
37
62
  export declare const MODEL_CATALOG: ModelInfo[];
38
63
  /**
39
64
  * Story 068 (R1, R1.1, R2) — the REAL per-alias context window, keyed by the EXACT {@link MODEL_CATALOG}
40
- * `value`. These windows are NOT uniform: `default`/`fable5`/`opus`/`sonnet` are natively 1M and `haiku`
65
+ * `value`. These windows are NOT uniform: `default`/`fable`/`opus`/`sonnet` are natively 1M and `haiku`
41
66
  * is 200K. This map is the single source of truth that `inferContextWindowFromModel` (acp-agent.ts)
42
67
  * consults BEFORE the `\b1m\b` regex fallback — the bug it fixes is `opus` having wrongly reported 200K
43
68
  * (the regex only ever matched the literal `1m` token).
44
69
  *
45
70
  * `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
71
+ * redundant `sonnet[1m]` alias was dropped). `default` and `opus` both resolve to Opus 5.5 and `fable`
72
+ * to Fable 5.1 — all three natively 1M per the CLI's baked-in catalogue. This is only the
48
73
  * PRE-FIRST-TURN seed: once a turn arrives, `inferContextWindowFromModelId` (story 069) AUTHORITATIVELY
49
74
  * refines the window from the transcript's real `model`. Keys MIRROR `MODEL_CATALOG` `value`s; the drift
50
75
  * guard lives in the test (068 anti-drift: every catalog value has an explicit entry).
@@ -56,6 +81,10 @@ export declare const MODEL_CONTEXT_WINDOWS: Record<string, number>;
56
81
  * (the JSONL `model` field), correcting the alias seed. Opus is NOT uniform: 4.6 = 200K, 4.7+ = 1M.
57
82
  * Dated snapshots / future versions are covered by the family+version heuristic in
58
83
  * `inferContextWindowFromModelId`; this table is the exact-ID source of truth for today's gateway IDs.
84
+ *
85
+ * Windows are READ FROM THE CLI'S OWN BAKED-IN CATALOGUE (`context.window` / `native_1m` in the JSON
86
+ * the `claude` binary embeds), not from the picker copy: `claude-opus-5-5` and `claude-opus-5` are
87
+ * both `window: 1e6, native_1m: true`, which is why neither needs a `[1m]` suffix to get 1M.
59
88
  */
60
89
  export declare const MODEL_ID_CONTEXT_WINDOWS: Record<string, number>;
61
90
  /**
@@ -78,27 +107,33 @@ export declare const MODEL_ID_CONTEXT_WINDOWS: Record<string, number>;
78
107
  */
79
108
  export declare function resolveCatalogValueFromModelId(id: string): string | null;
80
109
  /**
81
- * Story 072 — the version/context PREFIX the claude `/model` picker now shows before the static tagline
82
- * (e.g. "Opus 4.8 with 1M context · Best for everyday, complex tasks"). Keyed by catalog `value`.
83
- *
84
- * CURATED + DRIFT-PRONE, exactly like MODEL_CATALOG membership: the fork holds only aliases pre-turn and
85
- * cannot derive the concrete version (the SDK `supportedModels()` was cut), so these MIRROR the LIVE
86
- * picker and MUST be re-verified on each model launch (source: the user's live `/model` output). The
87
- * static tagline stays on `ModelInfo.description` (069 R3 untouched); this only prepends "<version> · ".
88
- * Every current catalog entry carries a label; the no-label branch in {@link modelSelectorDescription}
89
- * stays as a total-function safeguard for any future label-less entry.
90
- */
91
- export declare const MODEL_VERSION_LABELS: Record<string, string>;
92
- /**
93
- * Story 072 — compose the Zed selector description: "<version label> · <tagline>", or the bare tagline
94
- * when no label exists. PURE + TOTAL: never throws on a missing label or tagline.
110
+ * The selector description, which is now simply the row's own `description`.
111
+ *
112
+ * Story 072 used to compose `"<version label> · <tagline>"` from a curated
113
+ * MODEL_VERSION_LABELS map, because the hand-written rows carried only a bare
114
+ * tagline and the concrete version lived nowhere else. That map is GONE, and
115
+ * removing it was not cleanup — it was a correctness fix. Rows now arrive from
116
+ * the CLI (see `live-model-catalog.ts`) already carrying the version in both
117
+ * `displayName` and `description`, so prepending a curated prefix produced
118
+ * doubled copy ("Opus 5.5 with 1M context · Opus 5.5 · Best for everyday…") and,
119
+ * worse, could contradict the live row outright once the label went stale.
120
+ *
121
+ * The static {@link MODEL_CATALOG} rows were made self-contained to match, so
122
+ * this function needs no branch: the fallback path and the live path render the
123
+ * same way, which is exactly what "the picker matches the CLI" has to mean.
124
+ *
125
+ * Kept as a named function rather than inlined at the call site: it is the one
126
+ * place to put display policy back if a client ever needs different copy.
127
+ * PURE + TOTAL — never throws on a missing description.
95
128
  */
96
129
  export declare function modelSelectorDescription(info: ModelInfo): string;
97
130
  /**
98
131
  * Story 073 (R5.1) — the catalog `value`s that support fast mode (`/fast on|off`). Fast mode "uses
99
- * Claude Opus with faster output (it does not downgrade to a smaller model)" and is available on Opus
100
- * 4.8/4.7 only; the CLI turns it off when switching to a non-Opus model. `default` resolves to the
101
- * recommended Opus, so both `default` and `opus` qualify; `fable5`/`sonnet`/`haiku` do NOT.
132
+ * Claude Opus with faster output (it does not downgrade to a smaller model)"; the CLI turns it off when
133
+ * switching to a model without it. The gate is a CAPABILITY, not a version range — the CLI's baked-in
134
+ * catalogue lists `fast_mode` on `claude-opus-5-5`, `claude-opus-5` and `claude-opus-4-8`, and on no
135
+ * Fable, Sonnet or Haiku row. `default` resolves to the recommended Opus, so both `default` and `opus`
136
+ * qualify; `fable`/`sonnet`/`haiku` do NOT.
102
137
  *
103
138
  * Kept HERE (not on {@link ModelInfo}) because `ModelInfo` is the SDK shape and cannot carry a
104
139
  * fork-only `supportsFastMode` field — the same reason the effort/auto flags that DO exist on the SDK
@@ -22,18 +22,43 @@ export const ULTRACODE_EFFORT_LEVEL = "xhigh";
22
22
  /** Selector label — makes clear it is xhigh + orchestration, NOT a duplicate of the plain `xhigh` entry. */
23
23
  export const ULTRACODE_EFFORT_LABEL = "ultracode (xhigh + orchestration)";
24
24
  /**
25
+ * The FALLBACK model list — no longer what the picker normally shows.
26
+ *
27
+ * `live-model-catalog.ts` reads the real list from the CLI at session creation;
28
+ * this is what it falls back to when that read fails (no `claude` on PATH, a
29
+ * spawn error, a timeout). Everything below about hand-curation still applies to
30
+ * THESE rows, and the reason it is no longer the primary source is in that
31
+ * module's doc: the catalogue is backend-served and was measured changing shape
32
+ * twice in one day, which no hand-written list can track.
33
+ *
34
+ * Keep these rows CURRENT anyway. A fallback that nobody maintains is a fallback
35
+ * that ships a two-year-old model list on the day the CLI goes missing.
36
+ *
25
37
  * The static curated catalog advertised to the Zed Agent Panel's `model` selector. Each `value` is a
26
38
  * `claude` TUI alias accepted by `/model <alias>` (live) and `--model <alias>` (spawn). `default` is
27
39
  * first and is the safe fallback.
28
40
  *
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).
41
+ * ORDER + membership: `Default (recommended)`, `Fable`, `Opus`, `Sonnet`, `Haiku` — TIER aliases only,
42
+ * never a version-numbered one. The original gets its list from the SDK `supportedModels()` the fork
43
+ * cut, so we curate it statically. The redundant `sonnet[1m]` alias was dropped: Sonnet 5 is natively
44
+ * 1M, so plain `sonnet` already IS the 1M model. The fork-only `opusplan` extra was dropped too (three
45
+ * Sonnet-flavored entries + inconsistent Opus thinking made it more confusing than useful).
46
+ *
47
+ * **The CLI's alias vocabulary is a CLOSED SET, and a version-numbered alias is not in it.** Measured
48
+ * on claude 2.1.280: the accepted spellings are exactly
49
+ * `["sonnet","opus","haiku","fable","best","sonnet[1m]","opus[1m]","fable[1m]","opusplan"]` — plus any
50
+ * full wire id (`claude-opus-5-5`). Anything else 404s at spawn with `[claude-code:unrecognized_model]`,
51
+ * which is how the `fable51` and `fable5` rows this catalogue used to carry were BOTH dead: the binary
52
+ * contains those tokens (they are the CLI's internal id→short-name map), so reading them out of
53
+ * `strings` looked like confirmation and was not. **Probe an alias with a real turn before adding a
54
+ * row**: `claude -p ok --model <alias> --output-format json | jq '.is_error, .modelUsage'`.
35
55
  *
36
- * Effort-capable models (`default`/`fable5`/`opus`/`sonnet`) carry `supportsEffort` +
56
+ * A tier alias always points at the newest member of its family, so these rows do NOT age out on a
57
+ * model launch — only the version text in the row does. Verified 2026-09-23:
58
+ * `opus` → `claude-opus-5-5`, `fable` → `claude-fable-5-1`, `sonnet` → `claude-sonnet-5`,
59
+ * `haiku` → `claude-haiku-4-5-20251001`.
60
+ *
61
+ * Effort-capable models (`default`/`fable`/`opus`/`sonnet`) carry `supportsEffort` +
37
62
  * `supportedEffortLevels`; `haiku` advertises none. `supportsAutoMode: true` on the same four surfaces
38
63
  * the `auto` permission mode (a model classifier) — the original drops `auto` on `haiku` (the SDK signal
39
64
  * `reconcileModeFromTranscript` clamps), so haiku omits it.
@@ -43,79 +68,65 @@ export const MODEL_CATALOG = [
43
68
  value: "default",
44
69
  displayName: "Default (recommended)",
45
70
  // Story 069 (R3): `default` resolves to the recommended Opus, so it carries the Opus description.
46
- description: "Best for everyday, complex tasks",
71
+ description: "Opus 5.5 with 1M context · Best for everyday, complex tasks",
47
72
  supportsEffort: true,
48
73
  supportedEffortLevels: REASONING_EFFORT_LEVELS,
49
74
  supportsAutoMode: true,
50
75
  },
51
76
  {
52
- value: "fable51",
53
- // Bare family name in the title, like fable5/Opus/Sonnet/Haiku; the "Fable 5.1" version lives
54
- // in the MODEL_VERSION_LABELS prefix that composes the selector description.
55
- displayName: "Fable",
56
- // Fable 5.1 (Claude 5 family). Alias and id READ FROM THE INSTALLED BINARY, not guessed:
57
- // `strings /opt/bin/claude` carries `fable51`, `claude-fable-5-1` and a
58
- // VERTEX_REGION_CLAUDE_FABLE_5_1 region entry, so the CLI treats it as first class.
77
+ value: "fable",
78
+ // The title carries the concrete version, matching the live CLI rows this list stands in for.
79
+ displayName: "Fable 5.1",
80
+ // The tier alias, PROBED not guessed: `--model fable` resolves to `claude-fable-5-1` on a real
81
+ // turn (2026-09-23). It replaces the `fable51`/`fable5` rows, which the CLI rejected outright —
82
+ // see the closed-set note on MODEL_CATALOG above.
59
83
  // The description is the same string the live `/model` picker shows for the top of the
60
84
  // family — the CLI ships exactly three taglines and none is 5.1-specific, so this is
61
85
  // verbatim rather than invented.
62
- description: "Most capable for your hardest and longest-running tasks",
63
- supportsEffort: true,
64
- supportedEffortLevels: REASONING_EFFORT_LEVELS,
65
- supportsAutoMode: true,
66
- },
67
- {
68
- value: "fable5",
69
- // Bare family name in the title (like Opus/Sonnet/Haiku); the "Fable 5" version lives in the
70
- // MODEL_VERSION_LABELS prefix that composes the selector description.
71
- displayName: "Fable",
72
- // Fable 5 (Claude 5 family, released 2026-07-01) — the most advanced generally available model.
73
- // Description verbatim from the live `/model` picker of the interactive `claude` CLI.
74
- description: "Most capable for your hardest and longest-running tasks",
86
+ description: "Fable 5.1 with 1M context · Most capable for your hardest and longest-running tasks",
75
87
  supportsEffort: true,
76
88
  supportedEffortLevels: REASONING_EFFORT_LEVELS,
77
89
  supportsAutoMode: true,
78
90
  },
79
91
  {
80
92
  value: "opus",
81
- displayName: "Opus",
82
- description: "Best for everyday, complex tasks",
93
+ displayName: "Opus 5.5",
94
+ description: "Opus 5.5 with 1M context · Best for everyday, complex tasks",
83
95
  supportsEffort: true,
84
96
  supportedEffortLevels: REASONING_EFFORT_LEVELS,
85
97
  supportsAutoMode: true,
86
98
  },
87
99
  {
88
100
  value: "sonnet",
89
- displayName: "Sonnet",
90
- description: "Efficient for routine tasks",
101
+ displayName: "Sonnet 5",
102
+ description: "Sonnet 5 with 1M context · Efficient for routine tasks",
91
103
  supportsEffort: true,
92
104
  supportedEffortLevels: REASONING_EFFORT_LEVELS,
93
105
  supportsAutoMode: true,
94
106
  },
95
107
  {
96
108
  value: "haiku",
97
- displayName: "Haiku",
98
- description: "Fastest for quick answers",
109
+ displayName: "Haiku 4.5",
110
+ description: "Haiku 4.5 · Fastest for quick answers",
99
111
  },
100
112
  ];
101
113
  /**
102
114
  * Story 068 (R1, R1.1, R2) — the REAL per-alias context window, keyed by the EXACT {@link MODEL_CATALOG}
103
- * `value`. These windows are NOT uniform: `default`/`fable5`/`opus`/`sonnet` are natively 1M and `haiku`
115
+ * `value`. These windows are NOT uniform: `default`/`fable`/`opus`/`sonnet` are natively 1M and `haiku`
104
116
  * is 200K. This map is the single source of truth that `inferContextWindowFromModel` (acp-agent.ts)
105
117
  * consults BEFORE the `\b1m\b` regex fallback — the bug it fixes is `opus` having wrongly reported 200K
106
118
  * (the regex only ever matched the literal `1m` token).
107
119
  *
108
120
  * `sonnet` seeds to 1M because plain `sonnet` now resolves to Sonnet 5, which is natively 1M (the
109
- * redundant `sonnet[1m]` alias was dropped). `default` is the recommended Opus (the claude TUI's `/model
110
- * default` resolves to `claude-opus-4-8[1m]`, a 1M model) and `fable5` is Fable 5 (1M). This is only the
121
+ * redundant `sonnet[1m]` alias was dropped). `default` and `opus` both resolve to Opus 5.5 and `fable`
122
+ * to Fable 5.1 — all three natively 1M per the CLI's baked-in catalogue. This is only the
111
123
  * PRE-FIRST-TURN seed: once a turn arrives, `inferContextWindowFromModelId` (story 069) AUTHORITATIVELY
112
124
  * refines the window from the transcript's real `model`. Keys MIRROR `MODEL_CATALOG` `value`s; the drift
113
125
  * guard lives in the test (068 anti-drift: every catalog value has an explicit entry).
114
126
  */
115
127
  export const MODEL_CONTEXT_WINDOWS = {
116
128
  default: 1_000_000,
117
- fable51: 1_000_000,
118
- fable5: 1_000_000,
129
+ fable: 1_000_000,
119
130
  opus: 1_000_000,
120
131
  sonnet: 1_000_000,
121
132
  haiku: 200_000,
@@ -126,8 +137,14 @@ export const MODEL_CONTEXT_WINDOWS = {
126
137
  * (the JSONL `model` field), correcting the alias seed. Opus is NOT uniform: 4.6 = 200K, 4.7+ = 1M.
127
138
  * Dated snapshots / future versions are covered by the family+version heuristic in
128
139
  * `inferContextWindowFromModelId`; this table is the exact-ID source of truth for today's gateway IDs.
140
+ *
141
+ * Windows are READ FROM THE CLI'S OWN BAKED-IN CATALOGUE (`context.window` / `native_1m` in the JSON
142
+ * the `claude` binary embeds), not from the picker copy: `claude-opus-5-5` and `claude-opus-5` are
143
+ * both `window: 1e6, native_1m: true`, which is why neither needs a `[1m]` suffix to get 1M.
129
144
  */
130
145
  export const MODEL_ID_CONTEXT_WINDOWS = {
146
+ "claude-opus-5-5": 1_000_000,
147
+ "claude-opus-5": 1_000_000,
131
148
  "claude-opus-4-8": 1_000_000,
132
149
  "claude-opus-4-7": 1_000_000,
133
150
  "claude-opus-4-6": 200_000,
@@ -163,7 +180,7 @@ export function resolveCatalogValueFromModelId(id) {
163
180
  if (/claude-opus/.test(id))
164
181
  return "opus";
165
182
  if (/claude-fable/.test(id))
166
- return "fable5";
183
+ return "fable";
167
184
  if (/claude-sonnet/.test(id))
168
185
  return "sonnet";
169
186
  if (/claude-haiku/.test(id))
@@ -171,40 +188,35 @@ export function resolveCatalogValueFromModelId(id) {
171
188
  return null;
172
189
  }
173
190
  /**
174
- * Story 072 — the version/context PREFIX the claude `/model` picker now shows before the static tagline
175
- * (e.g. "Opus 4.8 with 1M context · Best for everyday, complex tasks"). Keyed by catalog `value`.
191
+ * The selector description, which is now simply the row's own `description`.
176
192
  *
177
- * CURATED + DRIFT-PRONE, exactly like MODEL_CATALOG membership: the fork holds only aliases pre-turn and
178
- * cannot derive the concrete version (the SDK `supportedModels()` was cut), so these MIRROR the LIVE
179
- * picker and MUST be re-verified on each model launch (source: the user's live `/model` output). The
180
- * static tagline stays on `ModelInfo.description` (069 R3 untouched); this only prepends "<version> · ".
181
- * Every current catalog entry carries a label; the no-label branch in {@link modelSelectorDescription}
182
- * stays as a total-function safeguard for any future label-less entry.
183
- */
184
- export const MODEL_VERSION_LABELS = {
185
- default: "Opus 4.8 with 1M context",
186
- fable51: "Fable 5.1 with 1M context",
187
- fable5: "Fable 5 with 1M context",
188
- opus: "Opus 4.8 with 1M context",
189
- sonnet: "Sonnet 5 with 1M context",
190
- haiku: "Haiku 4.5",
191
- };
192
- /**
193
- * Story 072 — compose the Zed selector description: "<version label> · <tagline>", or the bare tagline
194
- * when no label exists. PURE + TOTAL: never throws on a missing label or tagline.
193
+ * Story 072 used to compose `"<version label> · <tagline>"` from a curated
194
+ * MODEL_VERSION_LABELS map, because the hand-written rows carried only a bare
195
+ * tagline and the concrete version lived nowhere else. That map is GONE, and
196
+ * removing it was not cleanup — it was a correctness fix. Rows now arrive from
197
+ * the CLI (see `live-model-catalog.ts`) already carrying the version in both
198
+ * `displayName` and `description`, so prepending a curated prefix produced
199
+ * doubled copy ("Opus 5.5 with 1M context · Opus 5.5 · Best for everyday…") and,
200
+ * worse, could contradict the live row outright once the label went stale.
201
+ *
202
+ * The static {@link MODEL_CATALOG} rows were made self-contained to match, so
203
+ * this function needs no branch: the fallback path and the live path render the
204
+ * same way, which is exactly what "the picker matches the CLI" has to mean.
205
+ *
206
+ * Kept as a named function rather than inlined at the call site: it is the one
207
+ * place to put display policy back if a client ever needs different copy.
208
+ * PURE + TOTAL — never throws on a missing description.
195
209
  */
196
210
  export function modelSelectorDescription(info) {
197
- const label = MODEL_VERSION_LABELS[info.value];
198
- const tagline = info.description ?? "";
199
- if (!label)
200
- return tagline;
201
- return tagline ? `${label} · ${tagline}` : label;
211
+ return info.description ?? "";
202
212
  }
203
213
  /**
204
214
  * Story 073 (R5.1) — the catalog `value`s that support fast mode (`/fast on|off`). Fast mode "uses
205
- * Claude Opus with faster output (it does not downgrade to a smaller model)" and is available on Opus
206
- * 4.8/4.7 only; the CLI turns it off when switching to a non-Opus model. `default` resolves to the
207
- * recommended Opus, so both `default` and `opus` qualify; `fable5`/`sonnet`/`haiku` do NOT.
215
+ * Claude Opus with faster output (it does not downgrade to a smaller model)"; the CLI turns it off when
216
+ * switching to a model without it. The gate is a CAPABILITY, not a version range — the CLI's baked-in
217
+ * catalogue lists `fast_mode` on `claude-opus-5-5`, `claude-opus-5` and `claude-opus-4-8`, and on no
218
+ * Fable, Sonnet or Haiku row. `default` resolves to the recommended Opus, so both `default` and `opus`
219
+ * qualify; `fable`/`sonnet`/`haiku` do NOT.
208
220
  *
209
221
  * Kept HERE (not on {@link ModelInfo}) because `ModelInfo` is the SDK shape and cannot carry a
210
222
  * fork-only `supportsFastMode` field — the same reason the effort/auto flags that DO exist on the SDK
@@ -0,0 +1,67 @@
1
+ import type { ModelInfo } from "@anthropic-ai/claude-agent-sdk";
2
+ /**
3
+ * Picker recency filter: show only the newest model of each family.
4
+ *
5
+ * The SDK catalogue carries every model the account may reach, superseded ones
6
+ * included — measured 2026-09-23 it returned eleven rows, of which six were
7
+ * older Opus/Fable/Sonnet generations (`claude-opus-4-6` … `claude-fable-5`).
8
+ * This module keeps the newest of each family and drops the rest, so the picker
9
+ * offers one current choice per family instead of a version history.
10
+ *
11
+ * **Why a RULE and not a list.** That catalogue is served by the backend, not
12
+ * baked into the pinned CLI, and it was measured changing twice in one day under
13
+ * a fixed build — five rows, then eleven, with different titles and taglines. A
14
+ * hardcoded set of "current" ids would therefore be stale within hours, and
15
+ * silently: nothing fails when a picker row is wrong, the user simply gets the
16
+ * wrong model. Ranking by parsed version means the next launch promotes itself
17
+ * and retires its predecessor with no edit here.
18
+ *
19
+ * **Total and fail-open.** Anything this cannot place — an alias with no
20
+ * `resolvedModel`, a third-party id, a naming scheme that changes — is KEPT.
21
+ * Hiding a model the user has is worse than showing one row too many, and a
22
+ * parser is exactly the kind of thing a vendor breaks without warning. For the
23
+ * same reason the caller falls back to the unfiltered list if this would empty
24
+ * it.
25
+ *
26
+ * **This module is duplicated in `claude-agent-plus`, deliberately.** The two
27
+ * adapters are independent packages with no shared library between them, and the
28
+ * rule is small enough that a copy costs less than a dependency. If you change
29
+ * the ranking here, change it there — the sibling is
30
+ * `claude-agent-plus/fork/src/model-recency.ts`.
31
+ *
32
+ * @module model-recency
33
+ */
34
+ /**
35
+ * A model's family and version, parsed from a canonical wire id such as
36
+ * `claude-opus-5-5` or `claude-haiku-4-5-20251001`.
37
+ */
38
+ interface ModelGeneration {
39
+ family: string;
40
+ /** Version components, most significant first: `5-5` becomes `[5, 5]`. */
41
+ version: number[];
42
+ }
43
+ /**
44
+ * Parse a row's family and version from its canonical id.
45
+ *
46
+ * Reads `resolvedModel` first and falls back to `value`: alias rows (`opus`,
47
+ * `sonnet`) carry no version in `value`, which is the whole reason the SDK
48
+ * ships `resolvedModel`. Returns `null` for anything unparseable, which the
49
+ * caller treats as "keep".
50
+ *
51
+ * @param info - A single SDK model row.
52
+ */
53
+ export declare function modelGeneration(info: ModelInfo): ModelGeneration | null;
54
+ /**
55
+ * Return a NEW array holding only the newest row of each model family.
56
+ *
57
+ * Rows preserve their original ORDER and IDENTITY — the same object references
58
+ * come back, not copies — so a caller may compare by reference. Rows this
59
+ * cannot place are kept (see the module doc); rows tying for newest within a
60
+ * family are all kept, because a tie means two spellings of one model
61
+ * (typically an alias and its wire id) and dropping either would be arbitrary.
62
+ *
63
+ * @param infos - The model catalogue to filter.
64
+ * @returns A new array containing only current rows.
65
+ */
66
+ export declare function filterSupersededModels(infos: ModelInfo[]): ModelInfo[];
67
+ export {};
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Canonical wire ids look like `claude-<family>-<major>[-<minor>][-<snapshot>]`,
3
+ * optionally carrying a `[1m]` context hint. The snapshot suffix on dated ids
4
+ * (`claude-haiku-4-5-20251001`) is a build stamp, not a version component, so
5
+ * it is excluded by capping the parsed components at two — otherwise a dated
6
+ * row would outrank its own undated sibling.
7
+ */
8
+ const WIRE_ID = /claude-([a-z]+)-(\d+(?:-\d+)*)/i;
9
+ /** The `[1m]`/`-1m` long-context markers, which name a context lane and never a version. */
10
+ const CONTEXT_HINT = /\[\dm\]|-\dm\b/gi;
11
+ /**
12
+ * Parse a row's family and version from its canonical id.
13
+ *
14
+ * Reads `resolvedModel` first and falls back to `value`: alias rows (`opus`,
15
+ * `sonnet`) carry no version in `value`, which is the whole reason the SDK
16
+ * ships `resolvedModel`. Returns `null` for anything unparseable, which the
17
+ * caller treats as "keep".
18
+ *
19
+ * @param info - A single SDK model row.
20
+ */
21
+ export function modelGeneration(info) {
22
+ const id = (info.resolvedModel ?? info.value ?? "").replace(CONTEXT_HINT, "");
23
+ const match = WIRE_ID.exec(id);
24
+ if (!match)
25
+ return null;
26
+ const version = match[2].split("-").slice(0, 2).map(Number);
27
+ if (version.some((part) => !Number.isFinite(part)))
28
+ return null;
29
+ return { family: match[1].toLowerCase(), version };
30
+ }
31
+ /** Compare two version component lists, most significant first. Missing components sort as 0. */
32
+ function compareVersions(a, b) {
33
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
34
+ const diff = (a[i] ?? 0) - (b[i] ?? 0);
35
+ if (diff !== 0)
36
+ return diff;
37
+ }
38
+ return 0;
39
+ }
40
+ /**
41
+ * Return a NEW array holding only the newest row of each model family.
42
+ *
43
+ * Rows preserve their original ORDER and IDENTITY — the same object references
44
+ * come back, not copies — so a caller may compare by reference. Rows this
45
+ * cannot place are kept (see the module doc); rows tying for newest within a
46
+ * family are all kept, because a tie means two spellings of one model
47
+ * (typically an alias and its wire id) and dropping either would be arbitrary.
48
+ *
49
+ * @param infos - The model catalogue to filter.
50
+ * @returns A new array containing only current rows.
51
+ */
52
+ export function filterSupersededModels(infos) {
53
+ const newest = new Map();
54
+ for (const info of infos) {
55
+ const generation = modelGeneration(info);
56
+ if (!generation)
57
+ continue;
58
+ const best = newest.get(generation.family);
59
+ if (!best || compareVersions(generation.version, best) > 0) {
60
+ newest.set(generation.family, generation.version);
61
+ }
62
+ }
63
+ return infos.filter((info) => {
64
+ const generation = modelGeneration(info);
65
+ if (!generation)
66
+ return true;
67
+ const best = newest.get(generation.family);
68
+ return !best || compareVersions(generation.version, best) === 0;
69
+ });
70
+ }
package/dist/tools.js CHANGED
@@ -29,6 +29,19 @@ export function toDisplayPath(filePath, cwd) {
29
29
  export function toolCallIdFor(toolUseId, sessionId, options = {}) {
30
30
  return options.namespaced ? `${sessionId}:${toolUseId}` : toolUseId;
31
31
  }
32
+ /** Read a Write tool_use input the way the CLI validates it. Port of upstream #1161 (90cde4b):
33
+ * since 2.1.280 the CLI accepts `path` for `file_path` and `file_text`/`file_content` for
34
+ * `content` when a model sends those spellings, but the transcript's tool_use block still carries
35
+ * them raw — without this the call renders as "Preparing file…" with no diff while the write goes
36
+ * through. The canonical fields win when both spellings are present. */
37
+ function normalizeWriteInput(input) {
38
+ if (!input || typeof input !== "object")
39
+ return undefined;
40
+ const raw = input;
41
+ const filePath = raw.file_path ?? (typeof raw.path === "string" ? raw.path : undefined);
42
+ const content = raw.content ?? raw.file_text ?? raw.file_content;
43
+ return { ...raw, file_path: filePath, content };
44
+ }
32
45
  export function toolInfoFromToolUse(toolUse, supportsTerminalOutput = false, cwd) {
33
46
  const name = toolUse.name;
34
47
  switch (name) {
@@ -110,7 +123,7 @@ export function toolInfoFromToolUse(toolUse, supportsTerminalOutput = false, cwd
110
123
  };
111
124
  }
112
125
  case "Write": {
113
- const input = toolUse.input;
126
+ const input = normalizeWriteInput(toolUse.input);
114
127
  let content = [];
115
128
  if (input && input.file_path) {
116
129
  content = [
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "0.13.3",
6
+ "version": "0.14.1",
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",