Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
feat(catalog): refuse a stale cache when the catalog contract moves ahead
Jack Rudenkocb46b0a04f06
diff --git a/packages/cli/src/adapters/model-catalog.ts b/packages/cli/src/adapters/model-catalog.tsindex dd4bd19b..4bc3a067 100644--- a/packages/cli/src/adapters/model-catalog.ts+++ b/packages/cli/src/adapters/model-catalog.ts@@ -315,14 +315,21 @@ export function lookupModelForProvider(/*** Whether a subscription endpoint can serve a model, and under which wire id.*- * - `serves` — the plan includes this model; send `externalId` (the wire id- * the endpoint accepts, e.g. `k3` for catalog `kimi-k3`).+ * - `serves` — EVERY plan behind this route includes the model; send+ * `externalId` (the wire id the endpoint accepts, e.g. `k3` for+ * catalog `kimi-k3`).* - `not-served` — the provider IS a subscription plan, but this model isn't in* it. Routing should DROP the candidate: sending the model* anyway is a guaranteed rejection, and silently substituting a* different model gives the user something they didn't ask for.- * - `unknown` — not a subscription plan, or the model isn't in the catalog.- * Caller keeps its existing behaviour.+ * - `unknown` — not a subscription plan, the model isn't in the catalog, or+ * the catalog cannot answer for THIS user: the route's sibling+ * plans disagree about the model, or their membership lists are+ * not authoritative. Caller keeps its existing behaviour.+ *+ * Only `not-served` acts destructively, so every doubt resolves to `unknown`.+ * A wrong `not-served` drops a subscription provider and bills a flat-rate user+ * per token; a wrong `unknown` costs one upstream rejection.*/export type SubscriptionRouting =| { kind: "serves"; externalId: string }@@ -365,8 +372,38 @@ export function resolveSubscriptionRouting(if (providerPlans.length === 0) return { kind: "unknown" };const providerPlanIds = new Set(providerPlans.map((plan) => plan.id));- const hasMembership = entry.subscriptionPlans?.some((planId) => providerPlanIds.has(planId));- if (hasMembership) {+ const memberships = entry.subscriptionPlans ?? [];+ const includingPlans = providerPlans.filter((plan) => memberships.includes(plan.id));++ // A ROUTE is not a PLAN. `routing.providerUid` names the endpoint the CLI+ // talks to, and one endpoint sells several plans; `providerPlans` is therefore+ // a set, not a row. Testing membership against the UNION of that set — the+ // `.some()` this used to be — answers "does ANY plan behind this route include+ // the model?", while the caller reads the answer as "the credential in hand+ // can call it". Those are different questions whenever the route sells more+ // than one plan.+ //+ // Measured on the live cache: `alibaba-token-plan-individual` and+ // `alibaba-token-plan-team-edition` both carry+ // `routing.providerUid: "qwen-cloud"`. A model included only in Team Edition+ // answered `serves` to a holder of Individual, so routing pinned that plan's+ // wire id and the request went out against a plan the user does not own.+ //+ // Neither the cache nor the credential says WHICH sibling plan the user holds,+ // and claudish cannot find out, so unanimity is the only membership claim this+ // data supports:+ // in every plan for the route -> serves+ // in some but not all -> unknown (ambiguous plan membership)+ // in none -> fall through to the absence tests below+ // With one plan behind the route — z-ai's `z-ai-glm-coding-plan`, Kimi Code —+ // "every" and "some" are the same set, so single-plan vendors keep exactly+ // today's verdicts.+ //+ // The ambiguous case costs the user nothing: `unknown` keeps the candidate in+ // the chain and the caller still resolves a wire id through the generic+ // `aggregators[]` lookup. All it withholds is the plan-pinned id and the drop.+ if (includingPlans.length > 0) {+ if (includingPlans.length < providerPlans.length) return { kind: "unknown" };const agg = entry.aggregators?.find((a) => a.provider === provider);// A plan membership without an aggregator entry has no wire id to send;// keep the candidate as unknown rather than inventing one. The normal@@ -374,23 +411,40 @@ export function resolveSubscriptionRouting(return agg?.externalId ? { kind: "serves", externalId: agg.externalId } : { kind: "unknown" };}- // queryModels and queryPlans are separate requests, so a client can briefly- // pair a new plan contract with an older slim snapshot. Static absence only- // becomes authoritative after this cache demonstrates that it contains at- // least one membership row for the provider's plans. Otherwise treating- // zero coverage as a complete empty roster would drop every candidate during- // a backend rollout (the exact OpenAI/Anthropic gap that motivated the join).- const hasPublishedProviderRoster = cache.entries.some((candidate) =>+ // Everything from here down decides whether SILENCE is a verdict. Three+ // separate holes can put the model in this branch without the plan actually+ // excluding it, so each is tested on its own and any one of them withholds+ // `not-served`.+ //+ // Hole 1 — snapshot skew. queryModels and queryPlans are separate requests, so+ // a client can briefly pair a new plan contract with an older slim snapshot.+ // Requiring at least one membership row somewhere in the cache stops a+ // mid-rollout snapshot, which carries zero rows, from reading as a complete+ // empty roster and dropping every candidate (the OpenAI/Anthropic gap that+ // motivated the join).+ //+ // This is an EXISTENCE test and nothing more, which its old name —+ // `hasPublishedProviderRoster` — flatly misstated. `.some()` over the whole+ // cache means ONE membership row anywhere licenses the reading that this+ // route publishes rosters at all; it never checks that the roster is+ // COMPLETE. Read as a completeness proof it was the whole permission slip for+ // `not-served`, and a route that had published a single row could drop every+ // other model it serves. Completeness is not observable from row counts —+ // only the plan can state it, which is `modelDiscovery` below. Keep this+ // check, but keep it in its place: it can only withhold a verdict, never+ // license one.+ const hasAnyMembershipRow = cache.entries.some((candidate) =>candidate.subscriptionPlans?.some((planId) => providerPlanIds.has(planId)));- if (!hasPublishedProviderRoster) return { kind: "unknown" };-- // Absence of evidence is evidence of absence only when the view is whole, and- // this one has a hole in it by construction: `providerPlans` above keeps only- // plans carrying a `routing.providerUid`, so a plan with no routing block is- // never consulted. A SIBLING plan for the same vendor can still publish a- // roster, which makes `hasPublishedProviderRoster` true and turns this- // provider's silence into a verdict about a plan nobody looked at.+ if (!hasAnyMembershipRow) return { kind: "unknown" };++ // Hole 2 — a plan the filter cannot see. Absence of evidence is evidence of+ // absence only when the view is whole, and this one has a hole in it by+ // construction: `providerPlans` above keeps only plans carrying a+ // `routing.providerUid`, so a plan with no routing block is never consulted.+ // A SIBLING plan for the same vendor can still publish a roster, which makes+ // `hasAnyMembershipRow` true and turns this provider's silence into a verdict+ // about a plan nobody looked at.//// Measured on the live cache: `alibaba-ai-coding-plan` covers// `qwen3-coder-plus` and carries NO routing block, while@@ -417,11 +471,25 @@ export function resolveSubscriptionRouting();if (hasUnroutableSiblingPlan) return { kind: "unknown" };- // Static absence is conclusive only for catalog-authoritative plans. Client- // and hybrid plans may expose additional account-specific models after auth.- return providerPlans.every(isCatalogDiscoveredPlan)- ? { kind: "not-served" }- : { kind: "unknown" };+ // Hole 3 — a roster the catalog never claimed to hold. This is the only+ // completeness signal that exists, and it comes from the backend, per plan:+ // `modelDiscovery: "catalog"` is the plan stating that its membership list is+ // the whole callable roster. `client` and `hybrid` say the opposite — the+ // roster is discovered after auth, so the catalog's list is a subset by+ // design and a missing row means nothing. An absent value is not a quiet+ // "catalog" either; it is a plan contract this build predates.+ //+ // EVERY plan behind the route must say `catalog`, for the same reason+ // unanimity governs membership above: claudish does not know which sibling+ // plan the credential belongs to, so one `client` plan on the route is enough+ // to make the model reachable in a way this data cannot see.+ const hasCompleteMembershipView = providerPlans.every(isCatalogDiscoveredPlan);+ if (!hasCompleteMembershipView) return { kind: "unknown" };++ // All three holes closed: every plan on the route publishes an authoritative+ // roster, the cache proves it holds those rows, no sibling plan is invisible,+ // and none of the plans lists this model. Only now is silence a verdict.+ return { kind: "not-served" };}function isCatalogDiscoveredPlan(plan: CachedSubscriptionPlan): boolean {diff --git a/packages/cli/src/launcher/catalog-warm.ts b/packages/cli/src/launcher/catalog-warm.tsindex 3144eb13..32d0a27e 100644--- a/packages/cli/src/launcher/catalog-warm.ts+++ b/packages/cli/src/launcher/catalog-warm.ts@@ -17,6 +17,10 @@import { type DiskCacheV2, readAllModelsCache } from "../providers/all-models-cache.js";import { type RefreshOutcome, refreshCatalog } from "../providers/catalog-client.js";+import {+ catalogIncompatibilityMessage,+ readCatalogIncompatibility,+} from "../providers/catalog-compatibility.js";import type { ClaudishConfig } from "../types.js";import { VERSION } from "../version.js";@@ -273,6 +277,14 @@ export async function warmCatalogIfNeeded(return "ok";}+ // The server answered in a contract this build cannot read. Checked FIRST, and+ // the order is the argument: this variant carries no `reason`, and every branch+ // below says some version of "using cached version" — the cached version is+ // exactly what `readAllModelsCache` has just stopped handing out, so that line+ // would be false at the moment it matters most.+ if (outcome.kind === "incompatible") return reportIncompatibleCatalog(outcome);++// `disabled` is not a failure and must never reach the branches below. Nobody// attempted a fetch, so the cache state is irrelevant: with no cache at all// the `missing` branch would print HARD_FAIL_MESSAGE — "cannot reach model@@ -322,3 +334,27 @@ export async function warmCatalogIfNeeded(process.stderr.write(HARD_FAIL_MESSAGE);return "hard_fail";}+++/**+ * Announce a catalog this build cannot read, and let the launch proceed.+ *+ * "warned", not "hard_fail", and the distinction is the point: hard_fail exits+ * the CLI, which would strand a user running an explicit `gk@grok-code-fast`.+ * That spec names its own provider, so claudish infers no subscription and+ * substitutes nothing — there is no mis-billing to protect them from. The+ * launcher therefore says it once, plainly, and proceeds; the bare-name path+ * fails loudly per request in `routeBare` with this same text.+ *+ * Printed regardless of `--quiet`, like every other warning in this file.+ */+function reportIncompatibleCatalog(+ outcome: Extract<RefreshOutcome, { kind: "incompatible" }>+): WarmOutcome {+ const recorded = readCatalogIncompatibility() ?? {+ detectedAt: new Date().toISOString(),+ serverContractVersion: outcome.serverContractVersion,+ };+ process.stderr.write(`${catalogIncompatibilityMessage(recorded)}\n`);+ return "warned";+}\ No newline at end of filediff --git a/packages/cli/src/providers/all-models-cache.ts b/packages/cli/src/providers/all-models-cache.tsindex 1b9b8f92..2ee76d4d 100644--- a/packages/cli/src/providers/all-models-cache.ts+++ b/packages/cli/src/providers/all-models-cache.ts@@ -20,6 +20,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";import { homedir } from "node:os";import { dirname, join } from "node:path";import type { AggregatorEntry } from "../model-loader.js";+import { readCatalogIncompatibility } from "./catalog-compatibility.js";/*** Slim catalog entry from the Firebase queryModels?catalog=slim endpoint.@@ -315,10 +316,36 @@ export const ALL_MODELS_CACHE_PATH = join(homedir(), ".claudish", "all-models.js* `{version: 2, lastUpdated, entries: [], models}` so callers can treat both* the same way.*+ * Returns null unconditionally once a catalog incompatibility has been+ * recorded, whatever is on disk. This file is v2 and the reader is v2, so a+ * parse would SUCCEED — that is the trap. The rows would be structurally valid+ * and semantically obsolete: `subscriptionPlans` naming plan ids the server has+ * since redefined, `aggregators` missing whatever v3 added. `adapters/model-catalog.ts`+ * joins on those fields to decide whether a subscription covers a model, and a+ * confident wrong "no" there is the mis-billing this whole mechanism exists to+ * stop. The stale file stays put rather than being deleted — it is the last+ * known good catalog for the build that CAN read it, and `claudish update`+ * should not have to re-download it.+ ** @param path Override the cache path. Defaults to `ALL_MODELS_CACHE_PATH`.* Only tests should pass this.*/export function readAllModelsCache(path: string = ALL_MODELS_CACHE_PATH): DiskCacheV2 | null {+ if (readCatalogIncompatibility()) return null;+ return readCacheFile(path);+}++/**+ * The parse, without the contract gate.+ *+ * Split out for exactly one caller — {@link writeAllModelsCache}'s anti-clobber+ * merge, which is asking "what is already in this FILE?", not "may this process+ * route off it?". Routing them both through the gated read would make a legacy+ * `models`-only writer silently erase the `entries` catalog whenever a sentinel+ * was set, destroying the last-known-good file for the updated build that could+ * still have read it.+ */+function readCacheFile(path: string): DiskCacheV2 | null {if (!existsSync(path)) return null;let raw: unknown;@@ -370,7 +397,8 @@ export function writeAllModelsCache(data: Partial<DiskCacheV2>,path: string = ALL_MODELS_CACHE_PATH): void {- const existing = readAllModelsCache(path);+ // Ungated on purpose — see readCacheFile.+ const existing = readCacheFile(path);const merged: DiskCacheV2 = {version: 2,diff --git a/packages/cli/src/providers/catalog-client.ts b/packages/cli/src/providers/catalog-client.tsindex 5e01ea31..be3892b9 100644--- a/packages/cli/src/providers/catalog-client.ts+++ b/packages/cli/src/providers/catalog-client.ts@@ -41,6 +41,14 @@ import {readAllModelsCache,writeAllModelsCache,} from "./all-models-cache.js";+import {+ type ContractEnvelope,+ clearCatalogIncompatibility,+ isIncompatibleContractVersion,+ markCatalogIncompatible,+ parseContractEnvelope,+ readCatalogIncompatibility,+} from "./catalog-compatibility.js";/*** Firebase slim catalog endpoint. Override via:@@ -112,7 +120,16 @@ export type RefreshOutcome =| "revision_mismatch"/** The server said `hasMore` but the pages could not be completed. */| "incomplete";- };+ }+ /**+ * The server answered, and its answer is in a contract this build cannot+ * read. Deliberately NOT a `fetch_failed`: every caller of that variant+ * degrades to the cached file, which is the exact wrong move here — the cache+ * is v2 data whose subscription joins the server has since redefined, and+ * trusting it is what bills a flat-rate user per token. A refresh that ends+ * here has already written the persistent sentinel.+ */+ | { kind: "incompatible"; serverContractVersion: number | null };/** Result of resolving a user-typed model name for a provider. */export interface ModelResolutionResult {@@ -145,6 +162,28 @@ let _warmPromise: Promise<void> | null = null;*/export function getCatalogEntries(): SlimModelEntry[] | null {if (_catalogEntriesForTest !== undefined) return _catalogEntriesForTest;++ // Contract gate — BEFORE `_memCache`, and that ordering is the non-obvious+ // part. The obvious placement (next to the disk read below) would protect a+ // fresh process and no one else: a long-running session that warmed its+ // memory cache MINUTES BEFORE the server cut over keeps answering every+ // lookup from `_memCache` forever, and the sentinel it just wrote would never+ // be consulted. That session is the dangerous one — it is mid-conversation,+ // already routing requests, and its v2 entries are precisely the stale+ // subscription joins that send a flat-rate user to a metered provider. So the+ // gate goes ahead of every cache in the chain, and a warm process starts+ // refusing the moment the incompatibility is recorded.+ //+ // `_catalogEntriesForTest` still wins, above: it is an explicit tri-state+ // override, so a test that hands over entries is stating the catalog's+ // contents outright and must stay hermetic from the machine's sentinel file.+ //+ // Null keeps this function's existing contract — "cold", never "empty+ // catalog" — so every caller degrades to passthrough exactly as it does for a+ // missing cache file. The loud half of the response lives in `routing-rules`,+ // which is where a bare name would otherwise be silently re-billed.+ if (readCatalogIncompatibility()) return null;+if (_memCache) return _memCache;const cache = readAllModelsCache();@@ -518,7 +557,14 @@ interface CatalogPage {type PageResult =| { ok: true; page: CatalogPage; revision?: string }- | { ok: false; reason: "timeout" | "network" | "http_error" };+ | { ok: false; reason: "timeout" | "network" | "http_error" }+ /**+ * The page came back in a contract this build cannot read. Kept OUT of the+ * `reason` union above because every caller of those three degrades to the+ * cache, and the cache is the one thing a contract mismatch makes unusable.+ * The sentinel is already written by the time this is returned.+ */+ | { ok: false; reason: "incompatible"; serverContractVersion: number | null };/** Fetch one page. Never throws; classifies its own failure. */async function fetchCatalogPage(url: string, timeoutMs: number): Promise<PageResult> {@@ -532,7 +578,20 @@ async function fetchCatalogPage(url: string, timeoutMs: number): Promise<PageResreturn { ok: false, reason };}- if (!response.ok) return { ok: false, reason: "http_error" };+ if (!response.ok) {+ // Contract check on the ERROR path, ahead of the generic http_error return —+ // this is the branch that actually fires at cutover: a v3 server answers 426+ // to this build, and `http_error` alone would send every caller to the cache.+ const verdict = await contractVerdictForError(response);+ if (verdict) {+ return {+ ok: false,+ reason: "incompatible",+ serverContractVersion: verdict.serverContractVersion,+ };+ }+ return { ok: false, reason: "http_error" };+ }let page: CatalogPage;try {@@ -542,6 +601,23 @@ async function fetchCatalogPage(url: string, timeoutMs: number): Promise<PageResreturn { ok: false, reason: "network" };}+ // Contract check on the SUCCESS path. Unreachable while negotiation is by+ // Accept header (a v3 server 426s this build rather than serving it a v3+ // 200), and kept anyway because it costs one comparison and covers the day+ // negotiation changes. Placed HERE — after the parse, before the caller+ // accumulates the page — so a v3 body is never written into our v2 cache+ // file, where it would outlive this process as a catalog that looks present+ // and reads as empty.+ const bodyEnvelope = parseContractEnvelope(page);+ if (isIncompatibleContractVersion(bodyEnvelope.contractVersion)) {+ const verdict = recordIncompatibility(bodyEnvelope);+ return {+ ok: false,+ reason: "incompatible",+ serverContractVersion: verdict.serverContractVersion,+ };+ }+const revision = response.headers.get(CATALOG_REVISION_HEADER) ?? undefined;return { ok: true, page, revision };}@@ -606,6 +682,18 @@ export async function refreshCatalog(const url = buildCatalogPageUrl(catalogUrl(), offset, CATALOG_PAGE_LIMIT, revision);const result = await fetchCatalogPage(url, timeoutMs);if (!result.ok) {+ // Contract mismatch outranks the page index, and this check MUST precede+ // the ternary below. A 426 on page 3 is the same finding as a 426 on page+ // 1, but `pages === 0 ? … : "incomplete"` would relabel it — discarding+ // the one outcome whose whole purpose is to stop the caller reaching for+ // the cache the sentinel has just invalidated.+ if (result.reason === "incompatible") {+ return {+ kind: "incompatible",+ serverContractVersion: result.serverContractVersion,+ };+ }+// A first-page failure is the pre-existing "could not reach the catalog".// A LATER page failing is a torn read, and reporting it as a plain network// error would invite a caller to accept the partial pages already in hand.@@ -664,6 +752,18 @@ export async function refreshCatalog(if (id) backwardCompatModels.push({ id });}+ // A complete, parseable, non-empty refresh in a contract this build reads is+ // the only proof that an earlier incompatibility is over. Clearing on that and+ // not on any 200 is what makes the sentinel self-healing without making it+ // flappy: every partial outcome — bad body, empty roster, revision mismatch,+ // incomplete pagination — returned above and left the flag standing.+ //+ // Before the write, not after: `writeAllModelsCache`'s merge is gated on the+ // flag through `readAllModelsCache`, so clearing afterwards would have this+ // refresh merge against a catalog it was told to ignore.+ clearCatalogIncompatibility();++// ── Commit ──────────────────────────────────────────────────────────────_memCache = entries;writeAllModelsCache(@@ -682,9 +782,65 @@ export async function refreshCatalog(return { kind: "refreshed", modelCount: entries.length, catalogRevision: revision, pages };}+/**+ * The contract verdict for a NON-2xx response, or null when the failure is an+ * ordinary one this build should just retry or report.+ *+ * Shared by both endpoints because both negotiate the same version and both go+ * wrong at the same instant. Two checks, deliberately:+ *+ * - **status 426** is the documented signal, and the one that actually fires+ * at cutover. Every v3 endpoint negotiates on+ * `Accept: application/vnd.models-index.catalog+json;version=3`, and this+ * build sends no Accept header at all, so post-cutover it gets 426 and never+ * once sees a v3 200 body. (Not sending that header is deliberate: it+ * belongs to the v3 READER work. Asking for a contract we cannot parse would+ * be worse than not asking.)+ * - **a body `contractVersion` above ours**, because that field rides on every+ * v3 error body — 410 and 503 included — so this catches a cutover that+ * arrives wearing a status nobody wrote down.+ *+ * A body-less 426 still counts: the status alone is enough, and the sentinel+ * then records `serverContractVersion: null`, which the message renders as "a+ * newer catalog contract" rather than inventing a number.+ */+async function contractVerdictForError(+ response: Response+): Promise<Extract<RefreshOutcome, { kind: "incompatible" }> | null> {+ const envelope = parseContractEnvelope(await readJsonBody(response));+ if (response.status === 426 || isIncompatibleContractVersion(envelope.contractVersion)) {+ return recordIncompatibility(envelope);+ }+ return null;+}++/**+ * Read a response body as JSON, or undefined. Never throws.+ *+ * An error response may legitimately carry no body at all, an HTML proxy page,+ * or a truncated one — none of which is a reason for a catalog refresh to+ * explode. Returning undefined lets {@link parseContractEnvelope} answer "no+ * version stated", which is the same as no evidence.+ */+async function readJsonBody(response: Response): Promise<unknown> {+ try {+ return await response.json();+ } catch {+ return undefined;+ }+}+/*** queryPlans is additive to the model cache. A plan-endpoint failure must not* discard a valid model refresh or erase the last-known-good routing join.+ *+ * The one failure that is NOT merely additive is a contract mismatch. queryPlans+ * negotiates the same version as queryModels, so it 426s at the same instant —+ * and it is the endpoint that answers "which plan covers this model", which is+ * the exact question a mis-billed user needed answered. It still returns+ * undefined (the caller must not lose a model refresh over it), but it records+ * the sentinel on its way out, so whichever of the two requests lands first+ * protects the process.*/async function fetchSubscriptionPlans(timeoutMs: number,@@ -698,14 +854,49 @@ async function fetchSubscriptionPlans(const response = await fetch(url.toString(), {signal: AbortSignal.timeout(timeoutMs),});- if (!response.ok) return undefined;- const data = (await response.json()) as { plans?: CachedSubscriptionPlan[] };+ if (!response.ok) {+ // Records the sentinel as a side effect when the status or body says the+ // contract moved; the return stays `undefined` either way.+ await contractVerdictForError(response);+ return undefined;+ }+ const data = (await response.json()) as {+ plans?: CachedSubscriptionPlan[];+ contractVersion?: number;+ };+ const envelope = parseContractEnvelope(data);+ if (isIncompatibleContractVersion(envelope.contractVersion)) {+ recordIncompatibility(envelope);+ return undefined;+ }return Array.isArray(data.plans) ? data.plans : undefined;} catch {return undefined;}}+/**+ * Write the sentinel for a contract mismatch and shape the outcome.+ *+ * One helper for all three detection sites — both in `refreshCatalog` and the+ * one in `fetchSubscriptionPlans` — because they must record IDENTICAL facts.+ * `minimumContractVersion` is the field a hand-inlined copy drops, since it sits+ * nested under `error` while `contractVersion` is top-level, and dropping it is+ * invisible in testing: the guard still fires, the message just stops naming the+ * version the user needs to reach.+ */+function recordIncompatibility(+ envelope: ContractEnvelope+): Extract<RefreshOutcome, { kind: "incompatible" }> {+ markCatalogIncompatible({+ serverContractVersion: envelope.contractVersion,+ ...(envelope.minimumContractVersion !== undefined+ ? { minimumContractVersion: envelope.minimumContractVersion }+ : {}),+ });+ return { kind: "incompatible", serverContractVersion: envelope.contractVersion };+}+/** Fire-and-forget warm. Failures fall through to the disk-read fallback. */export async function warmCatalog(): Promise<void> {if (!_warmPromise) {diff --git a/packages/cli/src/providers/catalog-compatibility.ts b/packages/cli/src/providers/catalog-compatibility.tsnew file mode 100644index 00000000..9b18b005--- /dev/null+++ b/packages/cli/src/providers/catalog-compatibility.ts@@ -0,0 +1,318 @@+/**+ * Catalog contract compatibility — a PERSISTENT sentinel, not a detector.+ *+ * models-index publishes the model catalog under a contract version. This build+ * reads {@link SUPPORTED_CONTRACT_VERSION}. When the server moves past it, an+ * un-updated claudish does not crash — which is the problem. It reads a body+ * whose shape it does not recognise, finds no `entries`, no `plans`, no+ * `subscriptionPlans`, and concludes with complete confidence that it knows of+ * no subscription covering the model in hand. Routing then does what it does for+ * any model no plan covers: it picks a metered provider. A flat-rate user is+ * billed per token and nothing anywhere says so. That silence — not a crash — is+ * the defect this file exists to prevent.+ *+ * ## Why the finding has to outlive the process that made it+ *+ * Detection alone cannot help. `getCatalogEntries()` reads the memory cache,+ * then `~/.claudish/all-models.json`, and only fetches when both come back+ * empty. A client with a warm disk cache therefore never contacts the server at+ * all and never learns the contract moved. Worse, the one process that DOES see+ * the new contract is often a `claudish --models-refresh` that exits a second+ * later; if the finding died with it, the next launch would route off the stale+ * v2 file and mis-bill exactly as before.+ *+ * So the finding is written to `~/.claudish/catalog-incompatible.json` and read+ * back on every subsequent start, until a compatible response is seen again and+ * {@link clearCatalogIncompatibility} removes it.+ *+ * ## Why the disk write is best-effort but the flag is not+ *+ * A read-only home, a full disk or a sandboxed test must never turn a billing+ * guard into a crash, so every fs call here is wrapped. But swallowing a failed+ * write and returning nothing would leave the RUNNING process routing off a+ * catalog it has just proved it cannot read. The in-memory flag is therefore set+ * first and independently of the write: the file buys protection for the NEXT+ * process, the memory flag protects this one.+ *+ * ## Zero dependencies, on purpose+ *+ * Node builtins only. The catalog client, the disk cache and the routing engine+ * all import this module, and those three already import one another; a single+ * non-builtin import here would thread a cycle through the middle of routing.+ */++import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { homedir } from "node:os";+import { dirname, join } from "node:path";++/**+ * The catalog contract version THIS build knows how to read.+ *+ * Bumped only alongside the code that reads the new shape. It is a claim about+ * this binary's parser, never a preference — a server publishing anything higher+ * is not "newer than we like", it is unreadable.+ */+export const SUPPORTED_CONTRACT_VERSION = 2;++/** A recorded finding that the catalog server has moved past this build. */+export interface CatalogIncompatibility {+ /** ISO timestamp of the response that proved it. */+ detectedAt: string;+ /** The contract version the server published, when it said one. */+ serverContractVersion: number | null;+ /** The lowest version the server will serve, when it said one. */+ minimumContractVersion?: number;+}++/** Where the sentinel lives. Sibling of `~/.claudish/all-models.json`. */+export const CATALOG_INCOMPATIBLE_PATH = join(homedir(), ".claudish", "catalog-incompatible.json");++/**+ * The running process's own copy. Set by {@link markCatalogIncompatible} before+ * the write is attempted, so a failed write still protects this process.+ */+let _memFlag: CatalogIncompatibility | null = null;++/**+ * Memoized file read, keyed by path.+ *+ * {@link readCatalogIncompatibility} sits on hot paths — every bare-name route,+ * every catalog entry lookup — while the answer changes at most twice in a+ * process's life (a mark, or a clear), both of which write this memo directly.+ * Keying by path stops a test that passes an override from poisoning the+ * production path's memo, and vice versa.+ */+let _fileMemo: { path: string; value: CatalogIncompatibility | null } | null = null;++/**+ * Thrown by the routing engine when the catalog is unreadable.+ *+ * A dedicated class rather than a bare `Error` because the message's whole job+ * is to reach the user INLINE. `proxy-server.ts` maps routing-class failures to+ * HTTP 400 and everything else to 500, and a 500 is retryable: Claude Code would+ * loop on "API error · Retrying · attempt N/10" with this text buried, which is+ * the same silence wearing a different costume. It lives here rather than in+ * `routing-rules.ts` so the proxy can name it without importing the routing+ * engine.+ */+export class CatalogIncompatibleError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "CatalogIncompatibleError";+ }+}++// ---------------------------------------------------------------------------+// Wire-body parsing+// ---------------------------------------------------------------------------++/** What a models-index response body says about its own contract. */+export interface ContractEnvelope {+ /** Top-level `contractVersion`, or null when the body did not carry one. */+ contractVersion: number | null;+ /** `error.minimumContractVersion`, when the server named a floor. */+ minimumContractVersion?: number;+}++/**+ * Read the contract envelope off any models-index body. Never throws.+ *+ * The two fields sit at DIFFERENT depths, and that asymmetry is the whole reason+ * this is one shared function rather than two inline reads. The frozen v3 error+ * shape is:+ *+ * ```json+ * { "contractVersion": 3,+ * "error": { "code": "catalog_client_upgrade_required",+ * "message": "...",+ * "minimumContractVersion": 3 } }+ * ```+ *+ * `contractVersion` is top-level on EVERY error body (426, 410, 503 alike);+ * `minimumContractVersion` is nested under `error`. Reading the latter from the+ * top level returns `undefined` without failing, which would record a sentinel+ * that protects the user but cannot tell them which version to expect — a+ * degradation invisible in every test that only asserts "was it blocked?".+ *+ * Everything is optional because a 426 may carry no body at all.+ */+export function parseContractEnvelope(body: unknown): ContractEnvelope {+ if (!body || typeof body !== "object") return { contractVersion: null };++ const data = body as Record<string, unknown>;+ const contractVersion = typeof data.contractVersion === "number" ? data.contractVersion : null;++ const err = data.error;+ const minimum =+ err && typeof err === "object"+ ? (err as Record<string, unknown>).minimumContractVersion+ : undefined;++ return {+ contractVersion,+ ...(typeof minimum === "number" ? { minimumContractVersion: minimum } : {}),+ };+}++/**+ * Whether a version this build read off the wire is one it cannot serve.+ *+ * Null (no version in the body) is NOT incompatible. An absent field is absent+ * evidence — the same asymmetry `providerServesModel` keeps between `not-served`+ * and `unknown`, and for the same reason: a rule that treated silence as denial+ * would trip on every unrelated proxy error page and 404, blocking routing for+ * users whose catalog is perfectly readable.+ */+export function isIncompatibleContractVersion(version: number | null): version is number {+ return typeof version === "number" && version > SUPPORTED_CONTRACT_VERSION;+}++// ---------------------------------------------------------------------------+// The sentinel+// ---------------------------------------------------------------------------++/**+ * Record that the catalog server speaks a contract this build cannot read.+ *+ * Never throws. Sets the in-memory flag FIRST (see the header note on why a+ * best-effort write must not make the guard best-effort), then attempts the+ * file.+ *+ * @param info Everything but `detectedAt`, which is stamped here.+ * @param path Override the sentinel path. Only tests should pass this.+ */+export function markCatalogIncompatible(+ info: Omit<CatalogIncompatibility, "detectedAt">,+ path: string = CATALOG_INCOMPATIBLE_PATH+): void {+ const record: CatalogIncompatibility = {+ detectedAt: new Date().toISOString(),+ serverContractVersion: info.serverContractVersion,+ ...(info.minimumContractVersion !== undefined+ ? { minimumContractVersion: info.minimumContractVersion }+ : {}),+ };++ _memFlag = record;+ _fileMemo = { path, value: record };++ try {+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, JSON.stringify(record), "utf-8");+ } catch {+ // Best-effort. The memory flag above already covers this process, and the+ // next one re-detects on its first fetch — strictly no worse than where it+ // would have been with no sentinel at all.+ }+}++/**+ * The recorded incompatibility, or null when this build can read the catalog.+ *+ * In-memory flag first, then the file. Never throws.+ *+ * A file that exists but does not parse is still treated as a finding. This+ * module is the file's only writer, so its PRESENCE is the signal and the+ * contents are only detail for the message. Reading a truncated write as+ * "compatible" would put the user back on the silent-mis-billing path, which is+ * the one outcome the whole mechanism exists to rule out.+ *+ * @param path Override the sentinel path. Only tests should pass this.+ */+export function readCatalogIncompatibility(+ path: string = CATALOG_INCOMPATIBLE_PATH+): CatalogIncompatibility | null {+ if (_memFlag) return _memFlag;+ if (_fileMemo && _fileMemo.path === path) return _fileMemo.value;++ let value: CatalogIncompatibility | null = null;+ try {+ if (existsSync(path)) value = parseSentinelFile(readFileSync(path, "utf-8"));+ } catch {+ // Unreadable is not evidence of compatibility, but it is also nothing this+ // process can act on beyond what the next fetch rediscovers.+ }++ _fileMemo = { path, value };+ return value;+}++/** Coerce whatever is on disk into a finding. Never throws. */+function parseSentinelFile(raw: string): CatalogIncompatibility {+ const unspecific: CatalogIncompatibility = {+ detectedAt: new Date(0).toISOString(),+ serverContractVersion: null,+ };++ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch {+ return unspecific;+ }+ if (!parsed || typeof parsed !== "object") return unspecific;++ const data = parsed as Record<string, unknown>;+ return {+ detectedAt: typeof data.detectedAt === "string" ? data.detectedAt : unspecific.detectedAt,+ serverContractVersion:+ typeof data.serverContractVersion === "number" ? data.serverContractVersion : null,+ ...(typeof data.minimumContractVersion === "number"+ ? { minimumContractVersion: data.minimumContractVersion }+ : {}),+ };+}++/**+ * Forget the finding — the server answered in a contract this build reads.+ *+ * Called on every fully successful refresh, which is what makes the sentinel+ * self-healing: `claudish update` installs a build with a higher+ * {@link SUPPORTED_CONTRACT_VERSION}, its first refresh parses cleanly, and the+ * file is gone before the user notices it existed. Never throws.+ *+ * @param path Override the sentinel path. Only tests should pass this.+ */+export function clearCatalogIncompatibility(path: string = CATALOG_INCOMPATIBLE_PATH): void {+ _memFlag = null;+ _fileMemo = { path, value: null };++ try {+ rmSync(path, { force: true });+ } catch {+ // Best-effort, same as the write. A sentinel that survives its own deletion+ // costs the user one `claudish update` they have already run; it never costs+ // them money.+ }+}++/**+ * The user-facing text for an unreadable catalog.+ *+ * Three facts in the order the user needs them: what is broken, what continuing+ * anyway would cost, and the one command that fixes it. The cost sentence is the+ * point — "cannot read the catalog" on its own reads like a cosmetic warning,+ * and this failure is a billing one.+ */+export function catalogIncompatibilityMessage(i: CatalogIncompatibility): string {+ const serverSays =+ typeof i.serverContractVersion === "number"+ ? `catalog contract version ${i.serverContractVersion}`+ : typeof i.minimumContractVersion === "number"+ ? `catalog contract version ${i.minimumContractVersion} or newer`+ : "a newer catalog contract";++ return [+ `This claudish build cannot read the model catalog. The catalog server publishes ${serverSays}; this build reads version ${SUPPORTED_CONTRACT_VERSION}.`,+ "",+ "Routing cannot tell which models your subscriptions cover, so continuing would send this request to a provider that bills per token without saying so.",+ "",+ "Run `claudish update` to get a build that reads the current catalog.",+ ].join("\n");+}++/** Test seam: drop the memory flag AND the memoized file read. @internal */+export function _resetCatalogCompatibilityForTest(): void {+ _memFlag = null;+ _fileMemo = null;+}diff --git a/packages/cli/src/providers/routing-rules.ts b/packages/cli/src/providers/routing-rules.tsindex b68c208d..20e3b9b1 100644--- a/packages/cli/src/providers/routing-rules.ts+++ b/packages/cli/src/providers/routing-rules.ts@@ -7,6 +7,11 @@ import { loadConfig, loadLocalConfig } from "../profile-config.js";import type { RoutingEntry, RoutingRules } from "../profile-config.js";import { DISPLAY_NAMES, PROVIDER_TO_PREFIX } from "./auto-route.js";import { resolveExternalId } from "./catalog-client.js";+import {+ CatalogIncompatibleError,+ catalogIncompatibilityMessage,+ readCatalogIncompatibility,+} from "./catalog-compatibility.js";import { DEFAULT_ROUTING_RULES } from "./default-routing-rules.js";import { providerServesModel } from "./model-availability.js";import { PROVIDER_SHORTCUTS } from "./model-parser.js";@@ -333,9 +338,48 @@ export async function hasCredentialsForProvider(provider: string): Promise<boolereturn credentials.isAvailable(provider);}+/**+ * Emitted at most once per process — see `warnOnceIfCatalogIncompatible`.+ */+let _warnedCatalogIncompatible = false;++/**+ * Tell the user ONCE that the catalog is unreadable, on a path that still works.+ *+ * The explicit path is not gated (see routeExplicit), but it is degraded: wire-id+ * translation and the "does this provider serve it?" check both read a catalog+ * that now answers null, so a request may reach a provider under the name the+ * user typed rather than the id that provider actually uses. That is worth one+ * line. It is not worth one line PER REQUEST — an agent session routes hundreds,+ * and a warning repeated hundreds of times is one the user learns to scroll+ * past, which is how the important ones get missed too.+ */+function warnOnceIfCatalogIncompatible(): void {+ if (_warnedCatalogIncompatible) return;+ if (!readCatalogIncompatibility()) return;+ _warnedCatalogIncompatible = true;+ logStderr(+ "Model catalog is unavailable — this build cannot read the catalog server's current " ++ "contract. Explicit provider@model routing still works; bare model names do not. " ++ "Run `claudish update`."+ );+}++/** Test seam: allow the explicit-path warning to fire again. @internal */+export function _resetCatalogWarningForTest(): void {+ _warnedCatalogIncompatible = false;+}+/*** Path 1: an explicit "provider@model" spec. Probe ONLY that provider's* credentials; never fall back silently.+ *+ * NOT gated on catalog compatibility, unlike the bare path. The user named the+ * vendor, so claudish infers no subscription and substitutes no provider — there+ * is no decision here that an unreadable catalog could get wrong in the user's+ * favour or against it. Blocking this would strand a `gk@grok-code` user who+ * knows exactly what they want, for the sake of a risk their spec already ruled+ * out.*/async function routeExplicit(modelSpec: string,@@ -343,6 +387,8 @@ async function routeExplicit(provider: string,cachePath?: string): Promise<RoutePlan> {+ warnOnceIfCatalogIncompatible();+if (!(await hasCredentialsForProvider(provider))) {return {kind: "no-route",@@ -396,6 +442,28 @@ async function routeBare(defaultProvider?: string,cachePath?: string): Promise<RoutePlan> {+ // THE LOUD GATE. Fail rather than pick a metered fallback.+ //+ // This is the one path where claudish, not the user, chooses the vendor, and+ // it chooses it from catalog facts: which plan covers this model, which+ // provider serves it, under what id. With the catalog unreadable those facts+ // are not merely missing — `getCatalogEntries()` returns null, so every+ // subscription lookup answers "no plan covers this" with total confidence, the+ // filters below drop nothing, and the chain resolves to whatever metered+ // provider happens to sit in it. The user gets a working session and a bill.+ //+ // Throwing is deliberate where the rest of this function returns `no-route`.+ // A `no-route` is a routing VERDICT — claudish looked and found nothing — and+ // callers are entitled to treat it as data. This is the opposite: claudish+ // cannot look at all, and saying so has to be an exception so that no caller+ // can mistake it for an answer. `CatalogIncompatibleError` carries it to the+ // client as a 400 (see the class's own note on why not a 500), which renders+ // inline instead of behind Claude Code's retry banner.+ const incompatible = readCatalogIncompatibility();+ if (incompatible) {+ throw new CatalogIncompatibleError(catalogIncompatibilityMessage(incompatible));+ }+const matched = matchRoutingRule(model, rules) ?? [];const entries = [...matched];diff --git a/packages/cli/src/proxy-server.ts b/packages/cli/src/proxy-server.tsindex fb72473f..12783464 100644--- a/packages/cli/src/proxy-server.ts+++ b/packages/cli/src/proxy-server.ts@@ -34,6 +34,7 @@ import {resolveTargetForCatalog,warmCatalog,} from "./providers/catalog-client.js";+import { CatalogIncompatibleError } from "./providers/catalog-compatibility.js";import { getEndpointUnavailableReason } from "./providers/endpoint-diagnostics.js";import {ensureEndpointsRegistered,@@ -71,6 +72,19 @@ class RoutingError extends Error {}}+/**+ * Terminal for the same reason a RoutingError is: no provider can be chosen.+ *+ * `routeBare` throws `CatalogIncompatibleError` rather than returning a+ * `no-route`, so it arrives here as an exception and would otherwise fall into+ * the 500 branch below — where Claude Code's own retry loop would replay the+ * request ten times and show "API error · Retrying" instead of the one sentence+ * that names the fix. Grouped with RoutingError so it renders inline as a 400.+ */+function isTerminalRoutingFailure(e: unknown): e is Error {+ return e instanceof RoutingError || e instanceof CatalogIncompatibleError;+}+/*** A single slot-routing entry for `claudish serve`. Claude Desktop sends* `body.model = <slot>` (a Claude-recognized id it accepts into its picker);@@ -1088,7 +1102,7 @@ export async function createProxyServer(const txt = JSON.stringify(body);return c.json({ input_tokens: Math.ceil(txt.length / 4) });} catch (e) {- if (e instanceof RoutingError) {+ if (isTerminalRoutingFailure(e)) {return c.json(wrapAnthropicError(400, e.message, "invalid_request_error"), 400);}return c.json(wrapAnthropicError(500, String(e)), 500);@@ -1146,7 +1160,7 @@ export async function createProxyServer(// Routing failures are terminal — surface as a non-retryable 400 so the// client shows the real reason (e.g. missing key) instead of looping on// "API error · Retrying". Other errors stay 500.- if (e instanceof RoutingError) {+ if (isTerminalRoutingFailure(e)) {return c.json(wrapAnthropicError(400, e.message, "invalid_request_error"), 400);}return c.json(wrapAnthropicError(500, String(e)), 500);diff --git a/packages/cli/src/tui/hooks/useRouteProbe.ts b/packages/cli/src/tui/hooks/useRouteProbe.tsindex f9cd3114..38714e80 100644--- a/packages/cli/src/tui/hooks/useRouteProbe.ts+++ b/packages/cli/src/tui/hooks/useRouteProbe.ts@@ -11,11 +11,31 @@ const REASON_NATIVE ="Native Claude Code auth — not probed — served on Claude Code's own auth, which this process cannot forward";import { describeProbeState } from "../../providers/probe-live.js";import { INTERACTIVE_PROBE_TIMEOUT_MS, probeProviderRoute } from "../../providers/probe-runner.js";-import { type Route, route } from "../../providers/routing-rules.js";+import { type Route, type RoutePlan, route } from "../../providers/routing-rules.js";import { ensureProbeProxy } from "../probe-proxy.js";import { getProviderDefs, providerIsReady } from "../providers.js";import type { ProbeEntry, ProbeMode } from "../types.js";+/**+ * `route()`, with its one throwing case folded into the plan it already renders.+ *+ * A bare name makes `route()` THROW when the catalog contract is one this build+ * cannot read (providers/routing-rules.ts) — deliberately, so no caller mistakes+ * "claudish cannot look" for "claudish looked and found nothing". The probe is+ * the caller that wants exactly that flattening, though: it is a diagnostic+ * panel, its whole job is to display why a model will not route, and an+ * unhandled rejection inside an Ink render tree would take the config UI down+ * instead of answering the question. The message survives verbatim into the+ * panel's error column via `plan.reason`.+ */+async function routeForProbe(model: string): Promise<RoutePlan> {+ try {+ return await route(model);+ } catch (err) {+ return { kind: "no-route", reason: err instanceof Error ? err.message : String(err) };+ }+}+/*** Discriminated-union state for the route probe wizard.*@@ -115,7 +135,7 @@ export function useRouteProbe(config: ClaudishProfileConfig): UseRouteProbeReturif (native) {chain = [native];} else {- const plan = await route(model);+ const plan = await routeForProbe(model);if (plan.kind !== "ok") {setProbeResults([{