Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
feat: consume catalog v3 and separate Alibaba products
Jack Rudenko9a1206e56952
diff --git a/CLAUDE.md b/CLAUDE.mdindex 0fc77dae..e7514938 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -39,7 +39,7 @@ Evidence behind them: `ai-docs/reports/`. Evals: `ai-docs/benches/`. User-facing- A provider absent from `SUBSCRIPTION_PROVIDERS` quotes flat-rate users a per-token price and accrues fictional spend.- `openai-codex` bills by the CREDENTIAL that signed, never by its name, so it is in `CREDENTIAL_DECIDED_PROVIDERS` and must never also be in `SUBSCRIPTION_PROVIDERS` — the name check short-circuits the probe. The probe is installed only as a side effect of importing `auth/credentials/authority.ts`; unregistered, `cx@` silently reports metered (safe as money, but it also suppresses the `routing-rules.ts:413` cost warning). Probe with `CodexOAuth.hasCredentials()`, never `hasOAuthCredentials`/`describeSourceSync`.- What makes an arm the SUBSCRIPTION arm is `RequestAuth.arm === "oauth"`, set by the credential half itself — never "the composite returned an artifact". `CompositeCredentialProvider` falls through to the api-key half, which ALWAYS returns an object (`{headers:{}}` even with no key), so a truthiness test on the cached artifact labels every metered request SUB and accrues $0. Absent `arm` ⇒ metered. This shipped once and three reviewers read it as correct.-- Providers whose uids collide with another vendor's namespace (`devin`, `qwen-cloud`) declare no `nativeModelPatterns` and no routing rule — explicit `provider@model` access only.+- Cross-vendor subscription rosters such as Devin and Alibaba Token Plan must use exact catalog route/profile membership before a candidate is sent; account-selected models remain discoverable through their provider transport.- `gk@` is the Grok SUBSCRIPTION; `grok@`/`xai@` is the metered `x-ai`. `moonshot-cn@` is a different service from `moonshot@`.- A bare Claude name (`claude-opus-5`, `opus`, `internal`) must never reach `route()`: `native-anthropic` has no credential store, so the credential filter drops it and the chain degrades to OpenRouter. Check `nativeRouteFor()` (`providers/native-route.ts`) FIRST, as the proxy does — `preflight` and the TUI probe once didn't and told agents to drop their own subscription's models. Native routes also cannot be probed from outside a session (the handler forwards the inbound Claude Code header); report them as a third outcome, never as success or failure.- A new `ClaudishProfileConfig` field MUST be added to `loadConfig`'s allowlist in `profile-config.ts`; otherwise it survives on disk until the first global save and is then dropped. Bit `onepasswordEnvironments`, then `keychain`.diff --git a/README.md b/README.mdindex b866eea8..3d7eec9a 100644--- a/README.md+++ b/README.md@@ -37,7 +37,9 @@| **MiniMax** | `claudish --model [email protected]` || **OllamaCloud** | `claudish --model oc@qwen3-next` || **OpenCode Zen Go** | `claudish --model zgo@glm-5` |-| **Qwen Plan** | `claudish --model [email protected]` |+| **Alibaba Coding Plan** | `claudish --model [email protected]` |+| **Alibaba Token Plan** | `claudish --model [email protected]` |+| **Alibaba PAYG** | `claudish --model [email protected]` |**100% Offline Option — Your code never leaves your machine:**```bash@@ -357,10 +359,12 @@ Claudish automatically loads `.env` from the current directory at startup. For t| `ZAI_API_KEY` | Z.AI (`zai@`) | || `SAKANA_API_KEY` | Sakana Fugu (`sakana@`, `fugu@`) | || `SAKANA_CODING_API_KEY` | Sakana Fugu Subscription (`sc@`) | `SAKANA_API_KEY` |-| `QWEN_CLOUD_PLAN_API_KEY` | Qwen Plan (`qc@`) — Alibaba Cloud Model Studio | _(none — billing mode is fixed when the key is minted)_ |+| `QWEN_CODING_PLAN_API_KEY` | Alibaba Coding Plan (`qcode@`) | _(separate key and host)_ |+| `QWEN_TOKEN_PLAN_API_KEY` | Alibaba Token Plan (`qtoken@`) | _(separate key and host)_ |+| `DASHSCOPE_API_KEY` | Alibaba PAYG (`qpay@`) | _(separate key and host)_ || `OLLAMA_API_KEY` | OllamaCloud (`oc@`) | || `OPENCODE_API_KEY` | OpenCode Zen (`zen@`) | |-| `OPENCODE_GO_API_KEY` | OpenCode Zen Go plan (`zgo@`) | _(none — the Zen key is a different plan and is not accepted)_ |+| `OPENCODE_GO_API_KEY` | OpenCode Zen Go plan (`zgo@`) | _(separate from the metered Zen credential)_ || `LITELLM_API_KEY` | LiteLLM (`ll@`) — requires `LITELLM_BASE_URL` | || `POE_API_KEY` | Poe (`poe@`) | || `VERTEX_API_KEY` | Vertex AI Express (`v@`) | |@@ -446,7 +450,9 @@ Every one of these also accepts `CUSTOM_<NAME>_KEY` as an alias, and any of them| `MOONSHOT_BASE_URL` | Kimi/Moonshot | `https://api.moonshot.ai` || `ZHIPU_BASE_URL` | GLM/Zhipu | `https://open.bigmodel.cn` || `ZAI_BASE_URL` | Z.AI | `https://api.z.ai` |-| `QWEN_CLOUD_PLAN_BASE_URL` | Qwen Plan | `https://token-plan.ap-southeast-1.maas.aliyuncs.com` |+| `QWEN_CODING_PLAN_BASE_URL` | Alibaba Coding Plan | `https://coding-intl.dashscope.aliyuncs.com` |+| `QWEN_TOKEN_PLAN_BASE_URL` | Alibaba Token Plan | `https://token-plan.ap-southeast-1.maas.aliyuncs.com` |+| `DASHSCOPE_BASE_URL` | Alibaba PAYG | `https://dashscope-intl.aliyuncs.com` || `OLLAMACLOUD_BASE_URL` | OllamaCloud | `https://ollama.com` || `OPENCODE_BASE_URL` | OpenCode Zen | `https://opencode.ai/zen` || `LITELLM_BASE_URL` | LiteLLM proxy server | _(required with LITELLM_API_KEY)_ |@@ -632,7 +638,9 @@ claudish --model [email protected]:3 "code review" # 3 concurrent requests| `mistral@` | Mistral | `MISTRAL_API_KEY` | `mistral@mistral-large-2512` || `sakana@`, `fugu@` | Sakana Fugu | `SAKANA_API_KEY` | `fugu@fugu-ultra` || `sc@` | Sakana Fugu Subscription | `SAKANA_CODING_API_KEY` | `sc@fugu-ultra` |-| `qc@` | Qwen Plan | `QWEN_CLOUD_PLAN_API_KEY` | `[email protected]` |+| `qcode@` | Alibaba Coding Plan | `QWEN_CODING_PLAN_API_KEY` | `[email protected]` |+| `qtoken@` | Alibaba Token Plan | `QWEN_TOKEN_PLAN_API_KEY` | `[email protected]` |+| `qpay@` | Alibaba PAYG | `DASHSCOPE_API_KEY` | `[email protected]` || `llama@`, `lc@`, `meta@` | OllamaCloud | `OLLAMA_API_KEY` | `[email protected]` || `oc@` | OllamaCloud | `OLLAMA_API_KEY` | `[email protected]` || `zen@` | OpenCode Zen | `OPENCODE_API_KEY` | `zen@gpt-5-nano` |@@ -659,12 +667,12 @@ When no provider is specified, Claudish auto-detects from model name:| `kimi-*`, `moonshot-*` | Kimi Direct | `kimi-k2` || `glm-*`, `zhipu/*` | GLM Direct | `glm-4` || `fugu-*`, `sakana/*` | Sakana Fugu | `fugu-ultra` |-| `qwen3.*` (dotted Model Studio names) | Qwen Plan, then OpenRouter | `qwen3.7-plus` |+| `qwen3.*`, `qwen3-*` | Alibaba subscriptions, OpenCode Go, PAYG, then OpenRouter | `qwen3.7-plus` || `poe:*` | Poe | `poe:GPT-4o` || `claude-*`, `anthropic/*` | Native Anthropic | `claude-sonnet-4` || **Unknown `vendor/model`** | **Error** | Use `openrouter@vendor/model` |-**Qwen Plan roster**: discovered live from the plan's own model endpoint, never hardcoded — Alibaba's published docs both deny that endpoint exists and name models the host does not serve, and entitlement differs per subscription. The plan also serves `glm-5.2` and `deepseek-v4-*`, reachable only as an explicit `[email protected]`; bare `glm-*` / `deepseek-*` names keep their existing routing.+**Alibaba product rosters**: Coding Plan, Token Plan, and PAYG use separate credentials and endpoints. The catalog supplies each product's route and model wire ID; account discovery narrows the models actually available to your key. Cross-vendor models on an Alibaba plan can be selected explicitly, for example `[email protected]`.### Examples@@ -687,10 +695,11 @@ claudish --model [email protected] "analyze image"VERTEX_API_KEY=... claudish --model [email protected] "task"VERTEX_PROJECT=my-project claudish --model [email protected] "OAuth mode"-# Qwen Plan - Alibaba Cloud Model Studio subscription-claudish --model [email protected] "implement feature"-claudish --model qwen3.7-plus "implement feature" # bare dotted qwen3.* routes here-claudish --model [email protected] "review" # plan also serves GLM/DeepSeek, explicit qc@ only+# Alibaba Cloud Model Studio products+claudish --model [email protected] "implement feature"+claudish --model [email protected] "implement feature"+claudish --model [email protected] "implement feature"+claudish --model [email protected] "review"# Local models with concurrency controlclaudish --model [email protected]:3 "review" # 3 concurrent requestsdiff --git a/ai-docs/architecture/README.md b/ai-docs/architecture/README.mdindex 0dcc60bd..a3d584d3 100644--- a/ai-docs/architecture/README.md+++ b/ai-docs/architecture/README.md@@ -21,7 +21,7 @@ three earlier write-ups this material cites were lost.| [`providers/devin.md`](providers/devin.md) | The only binary wire in the pipeline — Connect envelopes carrying protobuf, live uid resolution, errors that ride an HTTP 200, and the three wire facts that cost real money to get wrong | touch `providers/devin/`, the codec, or `dv@` model resolution || [`providers/grok-subscription.md`](providers/grok-subscription.md) | `gk@` on a SuperGrok / X Premium+ plan: RFC 8628 device flow, exact-scope matching, 6-hour token refresh with write-back, three mandatory client headers | touch `gk@`, `claudish login grok`, or its OAuth refresh || [`providers/antigravity.md`](providers/antigravity.md) | Gemini on an Antigravity subscription: the shared `agy` keychain token, runtime client-secret extraction, live served-set discovery | touch `ag@`, `auth/antigravity-*`, or the keychain token |-| [`providers/qwen-alibaba.md`](providers/qwen-alibaba.md) | One service, two consoles, three mutually-rejecting key+host silos — plus the two measurement traps (a PUBLIC roster endpoint, and a rule generalised from one key) | touch `qc@`/`qp@`, or assume anything about Alibaba's silos |+| [`providers/qwen-alibaba.md`](providers/qwen-alibaba.md) | One service, two consoles, three isolated key+host products and account-discovery caveats | touch `qcode@`/`qtoken@`/`qpay@`, or assume anything about Alibaba's credentials || [`custom-endpoints.md`](custom-endpoints.md) | User-defined `customEndpoints`: schema, `${VAR}` expansion, and `authScheme: "none"` for endpoints that take NO credential | change `customEndpoints`, `config-schema.ts`, or `authScheme` handling || [`predefined-endpoints.md`](predefined-endpoints.md) | The 25-vendor bundled catalog: credential-gated activation, the single registration seam, evidence tiers (all `probe`, none `live`), and the no-model-data rule | add a vendor to `providers/predefined-catalog.ts`, or change endpoint registration || [`onepassword.md`](onepassword.md) | SDK-only secret resolution, the FOUR causes of an identical denial error, the cross-process handshake lock, parent-side route pinning, and the config TUI tab | touch `providers/onepassword*.ts`, credential pre-hydration, or the 1Password TUI tab |diff --git a/ai-docs/architecture/predefined-endpoints.md b/ai-docs/architecture/predefined-endpoints.mdindex a1d1daad..3b1d2c78 100644--- a/ai-docs/architecture/predefined-endpoints.md+++ b/ai-docs/architecture/predefined-endpoints.md@@ -151,6 +151,6 @@ The schema is `.strict()` and has no `models`, `contextWindow`, `maxOutputTokensA user who exported `PERPLEXITY_API_KEY` for some unrelated tool silently gains a claudish provider they never asked for. That is real, and it is stated rather than argued away.-It is acceptable for one specific reason: **nothing claudish ships puts a catalog row in a bare-name routing chain.** No row declares `nativeModelPatterns` (the schema has no such field), none owns a legacy prefix, and none appears anywhere in `DEFAULT_ROUTING_RULES` — all three are pinned by `predefined-containment.test.ts`, the third because it is the one a future contributor can open with a single well-meaning edit ("`llama-*` should try Groq first"). So a row is reachable only by typing `perplexity@model` — the same explicit-access rule Devin and Qwen Plan already follow, for the same reason. The cost of the wrong inference is therefore one extra row in a picker, never a request billed to a provider the user did not choose.+It is acceptable for one specific reason: **nothing claudish ships puts a catalog row in a bare-name routing chain.** No row declares `nativeModelPatterns` (the schema has no such field), none owns a legacy prefix, and none appears anywhere in `DEFAULT_ROUTING_RULES` — all three are pinned by `predefined-containment.test.ts`, the third because it is the one a future contributor can open with a single well-meaning edit ("`llama-*` should try Groq first"). So a row is reachable only by typing `perplexity@model` — the same explicit-access rule Devin and Alibaba Token Plan already follow, for the same reason. The cost of the wrong inference is therefore one extra row in a picker, never a request billed to a provider the user did not choose.The one qualification, stated because the absolute version is false: `route()` appends `defaultProvider` to EVERY bare chain, so a user who sets `"defaultProvider": "groq"` really does put a catalog row in bare chains. That is explicit user action naming the vendor, not a silent path, so the safety argument survives — but "can never" does not. If a catalog row ever becomes bare-name reachable WITHOUT the user naming it, this gate has to be revisited, because the inference would then be able to move money.diff --git a/ai-docs/architecture/providers/devin.md b/ai-docs/architecture/providers/devin.mdindex 30f89183..21569e1d 100644--- a/ai-docs/architecture/providers/devin.md+++ b/ai-docs/architecture/providers/devin.md@@ -30,7 +30,7 @@ quietly succeeding is worse than a crash. Same pattern as Antigravity: empty envother providers' namespaces (`claude-opus-5-medium` matches native-anthropic's `/^claude-/i`,`gpt-5-6-luna-medium` matches OpenAI's, `glm-5-2` GLM's, `kimi-k3-high` Kimi's), so the definitiondeclares **no `nativeModelPatterns`** and there is **no `DEFAULT_ROUTING_RULES` entry**. Same-reasoning as Qwen Plan, which also re-serves other vendors' models.+reasoning as Alibaba Token Plan, which also re-serves other vendors' models.**The reasoning tier is IN the model id — there is no effort parameter.** `dv@claude-opus-5` ateffort `high` resolves to the uid `claude-opus-5-high` via `resolveDevinModelUid` against the LIVEdiff --git a/ai-docs/architecture/providers/grok-subscription.md b/ai-docs/architecture/providers/grok-subscription.mdindex 0394c5dd..babf206d 100644--- a/ai-docs/architecture/providers/grok-subscription.md+++ b/ai-docs/architecture/providers/grok-subscription.md@@ -97,7 +97,7 @@ has no metered path, it is *not* dual-mode and **is** in that set. `GROK_DEPLOYMis out of scope for v1 for the same reason: it would reintroduce the ambiguity.**Bare `grok-*` routes subscription-FIRST** — `["grok-subscription", "x-ai", "openrouter"]`, matching-every other split family. Unlike Devin and Qwen Plan, which are explicit-access-only because their+every other split family. Unlike Devin and Alibaba Token Plan, which are explicit-access-only because theiruids collide with other vendors' namespaces, these ids are xAI's own, so a bare name is safe here.The provider declares **no `nativeModelPatterns`** (`x-ai` already owns `/^grok-/i`, and patterns arefirst-wins on array order); bare-name reachability comes from the routing chain instead.diff --git a/ai-docs/architecture/providers/qwen-alibaba.md b/ai-docs/architecture/providers/qwen-alibaba.mdindex 4e5591ef..7e1f4c73 100644--- a/ai-docs/architecture/providers/qwen-alibaba.md+++ b/ai-docs/architecture/providers/qwen-alibaba.md@@ -1,64 +1,29 @@-> One service, two consoles, three isolated key+host silos — and the two measurement traps.->-> Extracted from `CLAUDE.md` (v7.64.0). Indexed in [`README.md`](./README.md).--# Qwen / Alibaba: ONE service, TWO consoles, THREE isolated silos--The single most confusing provider in claudish, so state it plainly:--**Alibaba Model Studio and QwenCloud are the same service.** Two consoles run in-parallel (`modelstudio.console.alibabacloud.com` and `home.qwencloud.com`), neither doc-set mentions the other, and there is no migration notice — which is exactly why it reads-as two products. A QwenCloud account *is* an Alibaba Cloud International account; closing-one kills the other. There is **no `*.qwencloud.com` API host** (`api.qwencloud.com`-serves a placeholder page); every published endpoint is on `aliyuncs.com`.--**qwen.ai OAuth is a genuinely separate, DEAD product** — the `chat.qwen.ai` device flow-(`~/.qwen/oauth_creds.json`) had its free tier discontinued 2026-04-15 with no paid-replacement, and Qwen Code CLI now points at the Alibaba plans. Nothing to support.--What actually splits three ways is the **plan silo**. Alibaba's own words: keys and base-URLs are "completely isolated and must be used in matching pairs" — **every silo rejects-every other silo's key**, with near-identical 401s.--| Silo | Anthropic host (+ `/v1/messages`) | Provider |-|---|---|---|-| Token Plan (subscription) | `token-plan.ap-southeast-1.maas.aliyuncs.com/apps/anthropic` | `qc@` → `qwen-cloud` |-| Coding Plan | `coding-intl.dashscope.aliyuncs.com/apps/anthropic` | **not built** |-| Pay-as-you-go (metered) | `dashscope-intl.aliyuncs.com/apps/anthropic` | `qp@` → `qwen-payg` |--`qwen-payg` is deliberately **absent from `SUBSCRIPTION_PROVIDERS`** (it is metered, so it-must show real per-token pricing, never `SUB`) and carries **no `nativeModelPatterns`**-(`qwen-cloud` owns the dotted `/^qwen3\.\d/i` namespace; patterns are first-wins on array-order). Bare-name reachability comes from the `qwen3.*` chain, where it sits AFTER the-subscription — subscription-first, so a user holding both keys is never silently billed-per token for a model their plan covers. `DASHSCOPE_API_KEY` may alias `QWEN_API_KEY`-(both are metered, i.e. one billing mode in two spellings); **neither may ever alias onto-the plan key**, which is the same reasoning as the sakana-subscription precedent.--**Two measurement traps, both of which cost real time:**--- **`coding-intl…/v1/models` is PUBLIC** — it returns the full roster with a bogus key- and with no auth header at all. A 200 there proves *nothing* about a credential. Always- re-test a list endpoint with a deliberately bogus key before believing it. By contrast- `token-plan…/compatible-mode/v1/models` IS authenticated, provable because a fake path- under the same prefix 404s while the real path 401s.-- **`provider-definitions.ts`'s "a plan key authenticates ONLY against token-plan" was- generalised from probing ONE Token Plan key.** True for that key; the actual rule is- symmetric across all three silos.--**Dotted vs hyphenated is a PRODUCT LINE, not a vendor.** `/^qwen3\.\d/i` used to justify-itself by claiming dotted = Model Studio and hyphenated = OpenRouter/HuggingFace. Measured-2026-08-10, false: Token Plan serves only dotted ids (`qwen3.8-max`, `qwen3.7-max`,-`qwen3.7-plus`, `qwen3.6-flash`) while the Coding Plan serves both — `qwen3-coder-plus`,-`qwen3-coder-next`, `qwen3-max-2026-01-23` next to `qwen3.5-plus`/`qwen3.6-plus`. The coder-line and dated snapshots are hyphenated *Alibaba* names.--The pattern is nonetheless CORRECT for `qwen-cloud`, since Token Plan is dotted-only, and a-bare `qwen3-coder-plus` correctly reaches OpenRouter — no silo claudish implements serves-it. **Do not point hyphenated names at `qwen-payg` on the strength of the id shape**:-routing filters by CREDENTIAL, not by model, so an unserved id earns a `400 Model not exist`-and STOPS (400 is non-retryable), the same dead-end documented for `glm-*`. Unlike the-Coding Plan's public list, the PAYG roster is authenticated (401 without a key), so that-change needs a real `DASHSCOPE_API_KEY` to verify against — or routing that consults live-`modelDiscovery` rather than guessing from the name.+# Alibaba Cloud Model Studio and QwenCloud products++Alibaba Model Studio and QwenCloud are two consoles for the same account. Their+API products have separate credentials and hosts: a key must be used with its+matching product endpoint. Account rosters can differ from public documentation.++| Product | Anthropic host (+ `/v1/messages`) | Claudish | Credential |+|---|---|---|---|+| Coding Plan | `coding-intl.dashscope.aliyuncs.com/apps/anthropic` | `qwen-coding` / `qcode@` | `QWEN_CODING_PLAN_API_KEY` |+| Token Plan | `token-plan.ap-southeast-1.maas.aliyuncs.com/apps/anthropic` | `qwen-token-plan` / `qtoken@` | `QWEN_TOKEN_PLAN_API_KEY` |+| PAYG | `dashscope-intl.aliyuncs.com/apps/anthropic` | `qwen-payg` / `qpay@` | `DASHSCOPE_API_KEY` |++The v3 catalog binds these transports to `qwen/modelstudio-coding-plan`,+`qwen/qwencloud-token-plan`, and `qwen/dashscope-direct`, respectively. A+model's `subscriptionPlanIds` declares published plan membership, while the+matching mapped aggregator connection carries the exact wire ID. Coding Plan+has ten published models, and Token Plan's Individual and Team editions have+20 and 31; verify counts against the current catalog generation when releasing.++For bare Qwen names, the default chain considers Coding Plan, Token Plan,+OpenCode Go, PAYG, then OpenRouter. Each candidate is checked against the+catalog and local credentials. Models from other vendors on an Alibaba product+are explicit `qcode@` or `qtoken@` selections to avoid claiming their entire+vendor namespace.++The Coding Plan `/v1/models` endpoint can respond without authentication, so+its roster response alone does not prove a key works. Validate credentialed+inference for account access. Token Plan's model list is authenticated; product+keys cannot be substituted across the three hosts.diff --git a/ai-docs/architecture/routing.md b/ai-docs/architecture/routing.mdindex f15c7fb8..cedd24a0 100644--- a/ai-docs/architecture/routing.md+++ b/ai-docs/architecture/routing.md@@ -33,8 +33,9 @@ claudish --model [email protected]:3 "task" # 3 concurrent requests- `gc@` → GLM Coding Plan- `sakana@`, `fugu@` → Sakana Fugu- `sc@` → Sakana Fugu Subscription-- `qc@` → Qwen Plan (Alibaba Model Studio **Token Plan** subscription)-- `qp@`, `dashscope@` → Qwen API (Alibaba Model Studio **pay-as-you-go**, `DASHSCOPE_API_KEY`)+- `qcode@` → Alibaba Coding Plan (`QWEN_CODING_PLAN_API_KEY`)+- `qtoken@` → Alibaba Token Plan (`QWEN_TOKEN_PLAN_API_KEY`)+- `qpay@` → Alibaba PAYG (`DASHSCOPE_API_KEY`)- `dv@`, `devin@` → Devin (Cognition/Codeium subscription — see `ai-docs/architecture/providers/devin.md`)- `gk@` → Grok Build subscription (SuperGrok / X Premium+ — see `ai-docs/architecture/providers/grok-subscription.md`). `grok@` stays with the METERED `x-ai` provider- `x-ai@`, `xai@`, `grok@` → xAI direct API, metered (`XAI_API_KEY`)@@ -107,10 +108,12 @@ API aggregators (OpenRouter, LiteLLM) require vendor-prefixed model names that u## Runtime subscription routes come from the backend contract-Claudish refreshes the slim model catalog and `queryPlans` together and stores both in-`~/.claudish/all-models.json`. A model's `subscriptionPlans[]` contains canonical commercial-plan IDs such as `kimi-code`; those values are NOT provider names. The client joins each ID to-`queryPlans[].routing.providerUid` before deciding whether a provider serves the model.+Claudish refreshes the v3 slim model catalog and `queryPlans` together, pins+each page to one generation, and stores the complete snapshot in+`~/.claudish/all-models.json`. A model's `subscriptionPlanIds[]` contains+commercial plan IDs such as `kimi-code`. The client joins those IDs with a+plan's exact `route.routeId` and `route.routeProfileId`, then sends the matched+model connection's `externalModelId` to that transport.Plan absence has two different meanings:@@ -120,17 +123,11 @@ Plan absence has two different meanings:public backend cannot know, so absence remains unknown and the candidate is retained. Devin,Antigravity, and the `xai-supergrok` plan use this account-scoped behavior.-The backend recommendation document supplies `routingProvider`, `tier`, and an exact `command`-for each callable route. Claudish turns those rows into exact-model routing rules, orders them by-`tier` (`native` before `general`, `metered`, and `aggregator`), and places them ahead of bundled-defaults. `DEFAULT_ROUTING_RULES` remain the cold-cache and uncovered-model fallback. Global and-local user routing config still overlay both backend and bundled rules with the existing-exact-key merge semantics; an exact backend model route is replaced by a user rule for that same-model ID.--If `queryPlans` cannot refresh, the model refresh still succeeds and the last-known-good plan-cache is preserved. Old cache files without a plan snapshot retain their legacy behavior until a-successful refresh.+The backend recommendation projection supplies canonical model IDs and exact+route/profile identities. Claudish resolves them against the generation-pinned+catalog for model wire IDs. Default and user routing rules determine preference;+catalog availability removes only known-unserved candidates. A failed model or+plan refresh does not replace a complete cached snapshot.**Adding a new aggregator resolver**: Implement `ModelCatalogResolver` interface in `providers/catalog-resolvers/`, register in `model-catalog-resolver.ts`. No changes to proxy-server or provider-resolver needed.diff --git a/ai-docs/reports/CLAUDISH_V3_RELEASE_VALIDATION_20260919.md b/ai-docs/reports/CLAUDISH_V3_RELEASE_VALIDATION_20260919.mdnew file mode 100644index 00000000..c1b5442e--- /dev/null+++ b/ai-docs/reports/CLAUDISH_V3_RELEASE_VALIDATION_20260919.md@@ -0,0 +1,60 @@+# Claudish catalog v3 release validation — 2026-09-19++The release candidate is 9.8.0. The live Models Index generation read in this+session is `g-20260919013346169-feffb8ad`: 886 slim models and 19 plans, read+with the v3 media type and pinned to the same generation. The published+Alibaba memberships are 10 Coding Plan, 20 Token Plan Individual, and 31+Token Plan Team Edition models. The client reads all pages before caching a+model/plan snapshot and rejects changed generations, incomplete pages, and+unsupported contracts.++Alibaba transport identities and credentials:++| Product | Client prefix | Credential | Catalog route/profile |+| --- | --- | --- | --- |+| Coding Plan | `qcode@` | `QWEN_CODING_PLAN_API_KEY` | `qwen/modelstudio-coding-plan` |+| Token Plan | `qtoken@` | `QWEN_TOKEN_PLAN_API_KEY` | `qwen/qwencloud-token-plan` |+| PAYG | `qpay@` | `DASHSCOPE_API_KEY` | `qwen/dashscope-direct` |++The current Zen pricing rows in this generation match the [OpenCode model+table](https://opencode.ai/v2/docs/console/models/), in USD per million tokens:++| Model | Input | Output | Cached read | Cached write |+| --- | ---: | ---: | ---: | ---: |+| Qwen3.7 Max | 2.50 | 7.50 | 0.50 | 3.125 |+| Qwen3.7 Plus | 0.40 | 1.60 | 0.04 | 0.50 |+| Qwen3.6 Plus | 0.50 | 3.00 | 0.05 | 0.625 |+| Qwen3.5 Plus | 0.20 | 1.20 | 0.02 | 0.25 |++The client maps all five requested subscription profiles: Grok, MiniMax+Coding, Sakana Fugu, Devin, and Antigravity. An authenticated account discovery+read returned 30 OpenCode Go, 8 MiniMax Coding, 2 Grok, 8 Sakana, 209 Devin,+and 21 Antigravity entries. Dedicated local probes returned live inference for+OpenCode Go Kimi, Grok, Sakana, Devin, and Antigravity. MiniMax Coding+authenticated but its request received HTTP 429, provider code 2056, stating+that the Token Plan usage limit was reached. The reader retains both verified+and explicitly unavailable probe maps, rather than promoting an unavailable+probe selection to an account entitlement.++OpenCode documents the [Zen](https://opencode.ai/v2/docs/console/models/)+and [Go](https://opencode.ai/v2/docs/console/go) Qwen families on Anthropic+Messages. This candidate pairs the Messages payload, parser, endpoint, session+header, and API-key header for those routes. Go MiniMax also uses Messages;+metered Zen MiniMax uses Chat Completions. Local `--probe` returned live+inference for `[email protected]` and `zengo@minimax-m3` after fixing the+Messages-specific API-key header. The explicit Qwen and gateway wire IDs are+resolved from mapped v3 connections.++Poe now has a handler factory; Vertex chooses a configured project before an+Express key. Composition and project-selection tests pass, but authenticated+requests for those routes have not been run because this local environment has+neither Poe credentials nor Vertex project access. The three Alibaba+credentials and a metered OpenCode Zen key are also absent locally, so their+account entitlements and live inference cannot yet be claimed. A public plan+roster or public model endpoint is not evidence of access to those accounts.++Candidate validation: `bun run typecheck`, `bun run lint`, and `bun run build`+passed. The guarded full suite passed after the Zen endpoint correction:+3,545 CLI tests, 20 macOS bridge tests, and 4 guard tests; zero failures.+Release remains pending the missing authenticated product checks and the+merged-source release workflow.diff --git a/package.json b/package.jsonindex fb073377..f22c4213 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "claudish-monorepo",- "version": "9.7.1",+ "version": "9.8.0","private": true,"description": "Monorepo for Claudish - Run Claude Code with any model","type": "module",diff --git a/packages/cli/package.json b/packages/cli/package.jsonindex 8b4ad720..9664c740 100644--- a/packages/cli/package.json+++ b/packages/cli/package.json@@ -1,6 +1,6 @@{"name": "claudish",- "version": "9.7.1",+ "version": "9.8.0","description": "Run Claude Code with any model - OpenRouter, Ollama, LM Studio & local models","type": "module","main": "./dist/index.js",diff --git a/packages/cli/src/adapters/base-api-format.ts b/packages/cli/src/adapters/base-api-format.tsindex d589a82e..b858ca2b 100644--- a/packages/cli/src/adapters/base-api-format.ts+++ b/packages/cli/src/adapters/base-api-format.ts@@ -98,7 +98,7 @@ export function isEffortLevel(value: unknown): value is EffortLevel {** Two of them (`enable_thinking`, `thinking_budget`) are DashScope's; the third* (`reasoning_effort`) is OpenAI's and is also accepted by DeepSeek's and xAI's- * own APIs. Measured against Qwen Plan's Anthropic endpoint on 2026-08-02:+ * own APIs. Measured against Alibaba Token Plan's Anthropic endpoint on 2026-08-02:* a top-level `reasoning_effort` of `"max"` AND of `"banana"` both return 200,* i.e. the field is silently ignored — a dialect emitting it there believes it* set the depth and did nothing.@@ -202,14 +202,14 @@ export abstract class BaseAPIFormat implements APIFormat, ModelDialect {* own it cannot tell whether the same model is being reached over the* OpenAI/Chat-Completions wire or the Anthropic Messages wire. Providers do* exist that serve one model family over both (Qwen: DashScope- * OpenAI-compatible vs. Qwen Plan's /apps/anthropic/v1/messages), and their+ * OpenAI-compatible vs. Alibaba Token Plan's /apps/anthropic/v1/messages), and their* reasoning knobs are named differently on each.** DIALECTS SHOULD NOT READ THIS. It is consumed by {@link prepareRequest}'s* template and by {@link shouldFilterThinking}, which is what makes the* Anthropic-wire behaviour automatic for every dialect — including ones* written before the endpoint existed. A dialect that branches on it is- * re-creating the bug this replaced (see the qwen-cloud session log).+ * re-creating the bug this replaced (see the qwen-token-plan session log).** `undefined` means "not composed / caller didn't say" — treat it as the* historical OpenAI default so nothing changes for existing call sites.@@ -441,7 +441,7 @@ export abstract class BaseAPIFormat implements APIFormat, ModelDialect {* The split exists because WHICH reasoning knob a request must carry is a* property of the WIRE, not of the model family — and dialects are selected* by model NAME (see DialectManager), so a dialect cannot know the wire.- * Alibaba's Qwen Plan is the worked example: one Anthropic-compatible+ * Alibaba's Alibaba Token Plan is the worked example: one Anthropic-compatible* endpoint serving qwen3.x AND glm-5.2 AND deepseek-v4-*, i.e. three* different dialects reaching the SAME wire. Before this hoist only* QwenModelDialect had been taught the wire, so glm/deepseek on that endpoint@@ -524,7 +524,7 @@ export abstract class BaseAPIFormat implements APIFormat, ModelDialect {* it, for every dialect.** The SHAPE of the knob is a PER-MODEL fact read from the slim catalog's- * `reasoning` record, never from a table here. Alibaba's Qwen Plan roster is+ * `reasoning` record, never from a table here. Alibaba's Alibaba Token Plan roster is* why a fixed ladder is wrong: `qwen3.7-plus` is `control: "toggle"` (it* exposes no depth parameter at all, so a `budget_tokens` would be an* invented field), while `glm-5.2` and `deepseek-v4-pro` on the SAME endpoint@@ -536,7 +536,7 @@ export abstract class BaseAPIFormat implements APIFormat, ModelDialect {* Anthropic Messages endpoint and which AnthropicAPIFormat drops when* rebuilding the payload. Restoring it (clamped) is how a discrete level* reaches a model whose only other knob is `budget_tokens`, which these- * models do not accept. Verified live 2026-08-02 against Qwen Plan:+ * models do not accept. Verified live 2026-08-02 against Alibaba Token Plan:* `output_config.effort: "high"` → 200, `"banana"` → 400 naming the seven* accepted levels, so the field IS read.*@@ -1025,8 +1025,8 @@ export abstract class BaseAPIFormat implements APIFormat, ModelDialect {** Gating on the WIRE rather than a model roster is deliberate — a hardcoded* list would silently miss the next model added to a multi-vendor plan, which- * is exactly how `[email protected]` and `qc@deepseek-v4-pro` kept leaking after- * `[email protected]` was fixed. `wireFormat` is the composition hint+ * is exactly how `[email protected]` and `qtoken@deepseek-v4-pro` kept leaking after+ * `[email protected]` was fixed. `wireFormat` is the composition hint* ComposedHandler supplies from `explicitAdapter.getStreamFormat()`.** NOTE this is keyed on the composed `wireFormat`, which is supplied ONLY bydiff --git a/packages/cli/src/adapters/catalog-contract-payload.test.ts b/packages/cli/src/adapters/catalog-contract-payload.test.tsindex 56a6c797..9892a279 100644--- a/packages/cli/src/adapters/catalog-contract-payload.test.ts+++ b/packages/cli/src/adapters/catalog-contract-payload.test.ts@@ -4,7 +4,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import {type CachedSubscriptionPlan,- type DiskCacheV2,+ type DiskCacheV3,type ReasoningCapability,type SlimModelEntry,writeAllModelsCache,@@ -45,8 +45,9 @@ afterEach(() => {});function writeCatalog(entries: SlimModelEntry[], plans: CachedSubscriptionPlan[] = []): void {- const cache: DiskCacheV2 = {- version: 2,+ const cache: DiskCacheV3 = {+ catalogGenerationId: "test-generation",+ version: 3,lastUpdated: "2030-01-01T00:00:00.000Z",entries,models: [],@@ -64,7 +65,7 @@ function entry(return {modelId,aliases: [],- sources: {},+reasoningStatus,...(reasoning ? { reasoning } : {}),...(supportsThinking !== undefined ? { supportsThinking } : {}),@@ -140,10 +141,16 @@ describe("catalog-driven Anthropic request payloads", () => {[entry("qwen3.8-max-preview", "unknown", undefined, true)],[{+ routeStatus: "supported",id: "future-plan",- modelDescriptions: {- "qwen3.8-max": { status: "described", modelId: "qwen3.8-max-preview" },- },+ route: { routeId: "qwen", routeProfileId: "qwencloud-token-plan" },+ inclusions: [+ {+ kind: "provider_model",+ externalModelId: "qwen3.8-max",+ resolution: { status: "mapped", modelId: "qwen3.8-max-preview" },+ },+ ],},]);@@ -169,13 +176,16 @@ describe("catalog-driven Anthropic request payloads", () => {],[{+ routeStatus: "supported",id: "future-plan",- modelDescriptions: {- "qwen3.8-flash": {- status: "described",- modelId: "qwen3.8-flash-canonical",+ route: { routeId: "qwen", routeProfileId: "qwencloud-token-plan" },+ inclusions: [+ {+ kind: "provider_model",+ externalModelId: "qwen3.8-flash",+ resolution: { status: "mapped", modelId: "qwen3.8-flash-canonical" },},- },+ ],},]);diff --git a/packages/cli/src/adapters/deepseek-model-dialect.ts b/packages/cli/src/adapters/deepseek-model-dialect.tsindex 956ae688..65ae4654 100644--- a/packages/cli/src/adapters/deepseek-model-dialect.ts+++ b/packages/cli/src/adapters/deepseek-model-dialect.ts@@ -25,7 +25,7 @@ export class DeepSeekModelDialect extends BaseAPIFormat {* V4 controls, or strip on legacy models (which reason by model name only).** Not called on the Anthropic wire. Measured 2026-08-02 against Alibaba's- * Qwen Plan endpoint (which serves deepseek-v4-*): a top-level+ * Alibaba Token Plan endpoint (which serves deepseek-v4-*): a top-level* `reasoning_effort` is accepted with ANY value, including `"banana"` → 200,* i.e. it is not read at all there. BaseAPIFormat.applyAnthropicWireReasoning()* emits `output_config.effort` instead, clamped to the catalog's advertiseddiff --git a/packages/cli/src/adapters/dialect-manager.ts b/packages/cli/src/adapters/dialect-manager.tsindex e9c63eb1..a54cf209 100644--- a/packages/cli/src/adapters/dialect-manager.ts+++ b/packages/cli/src/adapters/dialect-manager.ts@@ -51,7 +51,7 @@ const DIALECT_FACTORIES: ReadonlyArray<(modelId: string, wire?: StreamFormat) =>* cannot, because selection is by model NAME). BaseAPIFormat — not the* dialect — consumes it, substituting the Anthropic Messages reasoning knob* and enabling unsigned-thinking filtering on `anthropic-sse`. That is why- * a multi-vendor Anthropic endpoint (Alibaba's Qwen Plan serves qwen3.x,+ * a multi-vendor Anthropic endpoint (Alibaba's Alibaba Token Plan serves qwen3.x,* glm-5.2 and deepseek-v4-* over one URL, i.e. three different dialects)* works without each dialect opting in. Omit for "unknown" → the OpenAI* default, which keeps every pre-existing call site byte-identical.diff --git a/packages/cli/src/adapters/effort-mapping.test.ts b/packages/cli/src/adapters/effort-mapping.test.tsindex 4707fab4..d2472172 100644--- a/packages/cli/src/adapters/effort-mapping.test.ts+++ b/packages/cli/src/adapters/effort-mapping.test.ts@@ -16,7 +16,7 @@ import { existsSync, readFileSync, rmSync, rmdirSync, writeFileSync } from "nodeimport { dirname } from "node:path";import {ALL_MODELS_CACHE_PATH,- type DiskCacheV2,+ type DiskCacheV3,writeAllModelsCache,} from "../providers/all-models-cache.js";import { type AdapterResult, BaseAPIFormat, type EffortLevel } from "./base-api-format.js";@@ -31,7 +31,7 @@ import { QwenModelDialect } from "./qwen-model-dialect.js";const SYNTHETIC_FUGU_MODEL_ID = "fugu-acme-ultra";-function seedDefaultCatalog(entries: DiskCacheV2["entries"]): () => void {+function seedDefaultCatalog(entries: DiskCacheV3["entries"]): () => void {const cacheDir = dirname(ALL_MODELS_CACHE_PATH);const cacheDirExisted = existsSync(cacheDir);const previousContents = existsSync(ALL_MODELS_CACHE_PATH)@@ -40,7 +40,9 @@ function seedDefaultCatalog(entries: DiskCacheV2["entries"]): () => void {writeAllModelsCache({- version: 2,+ catalogGenerationId: "test-generation",+ plans: [],+ version: 3,lastUpdated: new Date().toISOString(),entries,models: [],@@ -177,7 +179,7 @@ describe("Sakana Fugu (OpenAI-compatible path) clamps UP to high", () => {{modelId: SYNTHETIC_FUGU_MODEL_ID,aliases: [],- sources: {},+reasoning: {supported: true,control: "effort",@@ -700,7 +702,6 @@ describe("DeepSeek V4 reasoning_effort + thinking", () => {{modelId: SYNTHETIC_FUGU_MODEL_ID,aliases: [],- sources: {},},]);});@@ -764,7 +765,7 @@ describe("DeepSeek V4 reasoning_effort + thinking", () => {{modelId: "deepseek-chat",aliases: [],- sources: {},+reasoning: { supported: false, control: "none" },},]);diff --git a/packages/cli/src/adapters/effort-override.test.ts b/packages/cli/src/adapters/effort-override.test.tsindex 994c5dcd..8cd43416 100644--- a/packages/cli/src/adapters/effort-override.test.ts+++ b/packages/cli/src/adapters/effort-override.test.ts@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test";import { mkdtempSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import { type DiskCacheV2, writeAllModelsCache } from "../providers/all-models-cache.js";+import { type DiskCacheV3, writeAllModelsCache } from "../providers/all-models-cache.js";import { GLMModelDialect } from "./glm-model-dialect.js";import {type ReasoningCapability,@@ -43,11 +43,11 @@ let format: CatalogBackedGLMFormat;beforeEach(() => {tempDir = mkdtempSync(join(tmpdir(), "claudish-effort-override-"));cachePath = join(tempDir, "all-models.json");- const entries: DiskCacheV2["entries"] = [+ const entries: DiskCacheV3["entries"] = [{modelId: MODEL_ID,aliases: [],- sources: {},+reasoning: {supported: true,control: "effort",@@ -56,7 +56,17 @@ beforeEach(() => {},},];- writeAllModelsCache({ entries }, cachePath);+ writeAllModelsCache(+ {+ version: 3,+ catalogGenerationId: "test-generation",+ lastUpdated: new Date().toISOString(),+ entries,+ models: [],+ plans: [],+ },+ cachePath+ );format = new CatalogBackedGLMFormat(MODEL_ID, cachePath);});diff --git a/packages/cli/src/adapters/glm-model-dialect.ts b/packages/cli/src/adapters/glm-model-dialect.tsindex 97ed9065..e872da59 100644--- a/packages/cli/src/adapters/glm-model-dialect.ts+++ b/packages/cli/src/adapters/glm-model-dialect.ts@@ -31,7 +31,7 @@ export class GLMModelDialect extends BaseAPIFormat {* `zai@` both serve Z.AI GLM models; they differ in the WIRE, not the vendor.** Not called on the Anthropic wire, which is `zai@` (z-ai →- * anthropicCompatProfile, /api/anthropic/v1/messages) and `[email protected]` (Qwen+ * anthropicCompatProfile, /api/anthropic/v1/messages) and `[email protected]` (Qwen* Plan, also anthropicCompatProfile, serves GLM alongside Qwen). There* BaseAPIFormat.applyAnthropicWireReasoning() takes over.*diff --git a/packages/cli/src/adapters/model-catalog.test.ts b/packages/cli/src/adapters/model-catalog.test.tsindex 6e9f7790..fc78a2a6 100644--- a/packages/cli/src/adapters/model-catalog.test.ts+++ b/packages/cli/src/adapters/model-catalog.test.ts@@ -4,10 +4,11 @@ import { tmpdir } from "node:os";import { join } from "node:path";import {type CachedSubscriptionPlan,- type DiskCacheV2,+ type DiskCacheV3,type SlimModelEntry,writeAllModelsCache,} from "../providers/all-models-cache.js";+import { catalogRouteForProvider } from "../providers/catalog-route-bindings.js";import {lookupModel,lookupModelReasoning,@@ -35,21 +36,24 @@ afterEach(() => {function modelEntry(modelId: string,- subscriptionPlans: string[] = [],+ subscriptionPlanIds: string[] = [],provider?: string,externalId: string = modelId): SlimModelEntry {return {modelId,aliases: [],- sources: {},- subscriptionPlans,++ subscriptionPlanIds,...(provider? {aggregators: [{- provider,- externalId,+ sourceCollectorId: "test",+ routeStatus: "mapped",+ route: catalogRouteForProvider(provider),+ sourceProviderId: provider,+ externalModelId: externalId,confidence: "api_official" as const,},],@@ -63,13 +67,15 @@ function routedPlan(id: string, provider: string, providerUid: string): VendorPlid,provider,modelDiscovery: "catalog",- routing: { providerUid, nativeModelProviders: [] },+ routeStatus: "supported",+ route: catalogRouteForProvider(providerUid),};}function writeCatalog(entries: SlimModelEntry[], plans: CachedSubscriptionPlan[]): void {- const cache: DiskCacheV2 = {- version: 2,+ const cache: DiskCacheV3 = {+ catalogGenerationId: "test-generation",+ version: 3,lastUpdated: new Date().toISOString(),entries,models: [],@@ -85,17 +91,17 @@ describe("resolveSubscriptionRouting", () => {modelEntry("qwen3-coder-plus",["alibaba-token-plan-individual", "alibaba-token-plan-team-edition"],- "qwen-cloud",+ "qwen-token-plan","qwen3-coder-plus-wire"),],[- routedPlan("alibaba-token-plan-individual", "alibaba", "qwen-cloud"),- routedPlan("alibaba-token-plan-team-edition", "alibaba", "qwen-cloud"),+ routedPlan("alibaba-token-plan-individual", "alibaba", "qwen-token-plan"),+ routedPlan("alibaba-token-plan-team-edition", "alibaba", "qwen-token-plan"),]);- expect(resolveSubscriptionRouting("qwen3-coder-plus", "qwen-cloud", cachePath)).toEqual({+ expect(resolveSubscriptionRouting("qwen3-coder-plus", "qwen-token-plan", cachePath)).toEqual({kind: "serves",externalId: "qwen3-coder-plus-wire",});@@ -107,17 +113,17 @@ describe("resolveSubscriptionRouting", () => {modelEntry("qwen3-coder-plus",["alibaba-token-plan-team-edition"],- "qwen-cloud",+ "qwen-token-plan","qwen3-coder-plus-wire"),],[- routedPlan("alibaba-token-plan-individual", "alibaba", "qwen-cloud"),- routedPlan("alibaba-token-plan-team-edition", "alibaba", "qwen-cloud"),+ routedPlan("alibaba-token-plan-individual", "alibaba", "qwen-token-plan"),+ routedPlan("alibaba-token-plan-team-edition", "alibaba", "qwen-token-plan"),]);- expect(resolveSubscriptionRouting("qwen3-coder-plus", "qwen-cloud", cachePath)).toEqual({+ expect(resolveSubscriptionRouting("qwen3-coder-plus", "qwen-token-plan", cachePath)).toEqual({kind: "unknown",});});@@ -125,44 +131,46 @@ describe("resolveSubscriptionRouting", () => {test("preserves not-served when no Qwen plan includes the model and both rosters are catalog-authoritative", () => {writeCatalog([- modelEntry("qwen3-coder-plus", [], "qwen-cloud"),+ modelEntry("qwen3-coder-plus", [], "qwen-token-plan"),modelEntry("qwen-roster-proof", ["alibaba-token-plan-individual","alibaba-token-plan-team-edition",]),],[- routedPlan("alibaba-token-plan-individual", "alibaba", "qwen-cloud"),- routedPlan("alibaba-token-plan-team-edition", "alibaba", "qwen-cloud"),+ routedPlan("alibaba-token-plan-individual", "alibaba", "qwen-token-plan"),+ routedPlan("alibaba-token-plan-team-edition", "alibaba", "qwen-token-plan"),]);// This is not a new destructive verdict: the pre-bc7fd79 implementation// already returned not-served for a complete, catalog-authoritative view.- expect(resolveSubscriptionRouting("qwen3-coder-plus", "qwen-cloud", cachePath)).toEqual({+ expect(resolveSubscriptionRouting("qwen3-coder-plus", "qwen-token-plan", cachePath)).toEqual({kind: "not-served",});});- test("keeps the v9.0.4 guard: a same-vendor plan without routing forces unknown", () => {+ test("keeps Coding Plan separate from Token Plan membership", () => {writeCatalog([- modelEntry("qwen3-coder-plus", [], "qwen-cloud"),+ modelEntry("qwen3-coder-plus", [], "qwen-token-plan"),modelEntry("qwen3.8-max", ["alibaba-token-plan-individual"]),],[{id: "alibaba-ai-coding-plan",+ routeStatus: "supported",+ route: catalogRouteForProvider("qwen-coding"),provider: "alibaba",modelDiscovery: "catalog",},- routedPlan("alibaba-token-plan-individual", "alibaba", "qwen-cloud"),- routedPlan("alibaba-token-plan-team-edition", "alibaba", "qwen-cloud"),+ routedPlan("alibaba-token-plan-individual", "alibaba", "qwen-token-plan"),+ routedPlan("alibaba-token-plan-team-edition", "alibaba", "qwen-token-plan"),]);- expect(resolveSubscriptionRouting("qwen3-coder-plus", "qwen-cloud", cachePath)).toEqual({- kind: "unknown",+ expect(resolveSubscriptionRouting("qwen3-coder-plus", "qwen-token-plan", cachePath)).toEqual({+ kind: "not-served",});});@@ -183,14 +191,14 @@ describe("resolveSubscriptionRouting", () => {modelEntry("qwen3-coder-plus",["alibaba-token-plan-individual"],- "qwen-cloud",+ "qwen-token-plan","qwen3-coder-plus-wire"),],- [routedPlan("alibaba-token-plan-individual", "alibaba", "qwen-cloud")]+ [routedPlan("alibaba-token-plan-individual", "alibaba", "qwen-token-plan")]);- expect(resolveSubscriptionRouting("qwen3-coder-plus", "qwen-cloud", cachePath)).toEqual({+ expect(resolveSubscriptionRouting("qwen3-coder-plus", "qwen-token-plan", cachePath)).toEqual({kind: "serves",externalId: "qwen3-coder-plus-wire",});@@ -198,11 +206,11 @@ describe("resolveSubscriptionRouting", () => {test("returns unknown when the provider publishes no membership rows", () => {writeCatalog(- [modelEntry("qwen3-coder-plus", [], "qwen-cloud"), modelEntry("unrelated-model")],- [routedPlan("alibaba-token-plan-individual", "alibaba", "qwen-cloud")]+ [modelEntry("qwen3-coder-plus", [], "qwen-token-plan"), modelEntry("unrelated-model")],+ [routedPlan("alibaba-token-plan-individual", "alibaba", "qwen-token-plan")]);- expect(resolveSubscriptionRouting("qwen3-coder-plus", "qwen-cloud", cachePath)).toEqual({+ expect(resolveSubscriptionRouting("qwen3-coder-plus", "qwen-token-plan", cachePath)).toEqual({kind: "unknown",});});@@ -213,7 +221,7 @@ describe("plan modelDescriptions metadata lookup", () => {{modelId: "qwen3.8-max-preview",aliases: [],- sources: {},+contextWindow: 262_144,reasoningStatus: "known",reasoning: { supported: true, control: "budget", supportsBudgetTokens: true },@@ -221,7 +229,7 @@ describe("plan modelDescriptions metadata lookup", () => {{modelId: "qwen3.8-flash-canonical",aliases: [],- sources: {},+contextWindow: 131_072,reasoningStatus: "known",reasoning: { supported: true, control: "effort", efforts: ["low", "high"] },@@ -229,7 +237,7 @@ describe("plan modelDescriptions metadata lookup", () => {{modelId: "claude-opus-4-5",aliases: [],- sources: {},+contextWindow: 200_000,reasoningStatus: "known",reasoning: { supported: true, control: "effort", efforts: ["high", "max"] },@@ -239,12 +247,26 @@ describe("plan modelDescriptions metadata lookup", () => {function writeDescribedCatalog(): void {writeCatalog(describedEntries, [{+ routeStatus: "supported",id: "future-subscription-plan",- modelDescriptions: {- "qwen3.8-max": { status: "described", modelId: "qwen3.8-max-preview" },- "qwen3.8-flash": { status: "described", modelId: "qwen3.8-flash-canonical" },- "claude-opus-4-5-20251101": { status: "described", modelId: "claude-opus-4-5" },- },+ route: { routeId: "qwen", routeProfileId: "qwencloud-token-plan" },+ inclusions: [+ {+ kind: "provider_model",+ externalModelId: "qwen3.8-max",+ resolution: { status: "mapped", modelId: "qwen3.8-max-preview" },+ },+ {+ kind: "provider_model",+ externalModelId: "qwen3.8-flash",+ resolution: { status: "mapped", modelId: "qwen3.8-flash-canonical" },+ },+ {+ kind: "provider_model",+ externalModelId: "claude-opus-4-5-20251101",+ resolution: { status: "mapped", modelId: "claude-opus-4-5" },+ },+ ],},]);}@@ -274,7 +296,7 @@ describe("plan modelDescriptions metadata lookup", () => {{modelId: "qwen3.9-max-preview",aliases: [],- sources: {},+contextWindow: 262_144,reasoningStatus: "known",reasoning: { supported: true, control: "budget" },@@ -282,7 +304,7 @@ describe("plan modelDescriptions metadata lookup", () => {{modelId: "qwen3.9-flash-preview",aliases: [],- sources: {},+contextWindow: 131_072,reasoningStatus: "known",reasoning: { supported: true, control: "effort", efforts: ["high"] },@@ -290,11 +312,21 @@ describe("plan modelDescriptions metadata lookup", () => {],[{+ routeStatus: "supported",id: "future-subscription-plan",- modelDescriptions: {- "qwen3.9-max": { status: "missing" },- "qwen3.9-flash": { status: "ambiguous" },- },+ route: { routeId: "qwen", routeProfileId: "qwencloud-token-plan" },+ inclusions: [+ {+ kind: "provider_model",+ externalModelId: "qwen3.9-max",+ resolution: { status: "missing" },+ },+ {+ kind: "provider_model",+ externalModelId: "qwen3.9-flash",+ resolution: { status: "ambiguous" },+ },+ ],},]);@@ -306,18 +338,18 @@ describe("plan modelDescriptions metadata lookup", () => {}});- test("keeps old caches without modelDescriptions working through ids and aliases", () => {+ test("looks up models through ids and aliases when plans have no inclusions", () => {writeCatalog([{modelId: "legacy-canonical-model",aliases: ["legacy-wire-model"],- sources: {},+contextWindow: 98_304,reasoning: { supported: true, control: "toggle" },},],- [{ id: "legacy-plan" }]+ [{ id: "test-plan", routeStatus: "unknown" }]);expect(lookupModel("legacy-canonical-model", cachePath)?.contextWindow).toBe(98_304);@@ -327,43 +359,53 @@ describe("plan modelDescriptions metadata lookup", () => {});describe("lookupModelReasoningStatus", () => {- test("preserves explicit and legacy knowledge without manufacturing a control", () => {+ test("preserves explicit and described reasoning without manufacturing a control", () => {writeCatalog([{modelId: "explicit-unknown",aliases: [],- sources: {},+reasoningStatus: "unknown",supportsThinking: true,},{modelId: "explicit-known",aliases: [],- sources: {},+reasoningStatus: "known",reasoning: { supported: false, control: "none" },},{- modelId: "legacy-described",+ modelId: "reasoning-described",aliases: [],- sources: {},+reasoning: { supported: true, control: "toggle" },},{- modelId: "legacy-undescribed",+ modelId: "reasoning-undescribed",aliases: [],- sources: {},+supportsThinking: false,},],[{+ routeStatus: "supported",id: "negative-plan",- modelDescriptions: {- "missing-wire": { status: "missing" },- "ambiguous-wire": { status: "ambiguous" },- },+ route: { routeId: "qwen", routeProfileId: "qwencloud-token-plan" },+ inclusions: [+ {+ kind: "provider_model",+ externalModelId: "missing-wire",+ resolution: { status: "missing" },+ },+ {+ kind: "provider_model",+ externalModelId: "ambiguous-wire",+ resolution: { status: "ambiguous" },+ },+ ],},]);@@ -371,9 +413,9 @@ describe("lookupModelReasoningStatus", () => {expect(lookupModelReasoningStatus("explicit-unknown", cachePath)).toBe("unknown");expect(lookupModelReasoning("explicit-unknown", cachePath)).toBeUndefined();expect(lookupModelReasoningStatus("explicit-known", cachePath)).toBe("known");- expect(lookupModelReasoningStatus("legacy-described", cachePath)).toBe("known");- expect(lookupModelReasoningStatus("legacy-undescribed", cachePath)).toBe("unknown");- expect(lookupModelReasoning("legacy-undescribed", cachePath)).toBeUndefined();+ expect(lookupModelReasoningStatus("reasoning-described", cachePath)).toBe("known");+ expect(lookupModelReasoningStatus("reasoning-undescribed", cachePath)).toBe("unknown");+ expect(lookupModelReasoning("reasoning-undescribed", cachePath)).toBeUndefined();for (const modelId of ["not-in-the-catalog", "missing-wire", "ambiguous-wire"]) {expect(lookupModelReasoningStatus(modelId, cachePath)).toBeUndefined();diff --git a/packages/cli/src/adapters/model-catalog.ts b/packages/cli/src/adapters/model-catalog.tsindex 4bc3a067..c8dc96b9 100644--- a/packages/cli/src/adapters/model-catalog.ts+++ b/packages/cli/src/adapters/model-catalog.ts@@ -20,6 +20,7 @@ import {readAllModelsCache,reasoningStatusOf,} from "../providers/all-models-cache.js";+import { catalogRouteMatchesProvider } from "../providers/catalog-route-bindings.js";import { compareByReleaseDateDesc } from "../providers/model-ordering.js";export type {@@ -181,8 +182,8 @@ export function lookupRouteReasoningMode(provider: string,cachePath?: string): ReasoningModeCapabilities | undefined {- return findCacheEntry(modelId, cachePath)?.aggregators?.find(- (aggregator) => aggregator.provider === provider+ return findCacheEntry(modelId, cachePath)?.aggregators?.find((aggregator) =>+ catalogRouteMatchesProvider(aggregator.route, provider))?.reasoning?.mode;}@@ -308,199 +309,51 @@ export function lookupModelForProvider(const entry = findCacheEntry(modelId, cachePath);if (!entry) return undefined;return (- entry.aggregators?.find((a) => a.provider === provider)?.contextWindow ?? entry.contextWindow+ entry.aggregators?.find((a) => catalogRouteMatchesProvider(a.route, provider))?.contextWindow ??+ entry.contextWindow);}-/**- * Whether a subscription endpoint can serve a model, and under which wire id.- *- * - `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, 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.- */+/** A subscription route's catalog answer for one model. */export type SubscriptionRouting =| { kind: "serves"; externalId: string }| { kind: "not-served" }| { kind: "unknown" };-/**- * Resolve how a subscription provider should route a model, from catalog data- * alone (`subscriptionPlans[]` plan IDs joined through cached `queryPlans`,- * plus `aggregators[].externalId`).- *- * Nothing about which models a plan includes is hardcoded — that is exactly the- * data that goes stale. Kimi Code shipping K3 while the CLI pinned- * `kimi-for-coding` is the worked example.- */export function resolveSubscriptionRouting(modelId: string,provider: string,cachePath?: string): SubscriptionRouting {+ const cache = readAllModelsCache(cachePath);const entry = findCacheEntry(modelId, cachePath);- if (!entry) return { kind: "unknown" };+ if (!cache || !entry) return { kind: "unknown" };- const cache = readAllModelsCache(cachePath);- const providerPlans =- cache?.plans?.filter((plan) => plan.routing?.providerUid === provider) ?? [];-- // Legacy v2 caches predate queryPlans and stored provider UIDs directly in- // subscriptionPlans. Preserve their old behavior until the next refresh.- if (cache?.plans === undefined) {- if (entry.subscriptionPlans?.includes(provider)) {- const agg = entry.aggregators?.find((a) => a.provider === provider);- return agg?.externalId ? { kind: "serves", externalId: agg.externalId } : { kind: "unknown" };- }- return isLegacySubscriptionPlan(provider, cachePath)- ? { kind: "not-served" }+ const plans = cache.plans.filter(+ (plan) => plan.routeStatus === "supported" && catalogRouteMatchesProvider(plan.route, provider)+ );+ if (plans.length === 0) return { kind: "unknown" };++ const memberships = entry.subscriptionPlanIds ?? [];+ const included = plans.filter((plan) => memberships.includes(plan.id));+ if (included.length > 0) {+ if (included.length !== plans.length) return { kind: "unknown" };+ const connection = entry.aggregators?.find(+ (candidate) =>+ candidate.routeStatus === "mapped" && catalogRouteMatchesProvider(candidate.route, provider)+ );+ return connection?.externalModelId+ ? { kind: "serves", externalId: connection.externalModelId }: { kind: "unknown" };}- if (providerPlans.length === 0) return { kind: "unknown" };-- const providerPlanIds = new Set(providerPlans.map((plan) => plan.id));- 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- // catalog resolver may still know the canonical provider wire ID.- return agg?.externalId ? { kind: "serves", externalId: agg.externalId } : { kind: "unknown" };- }-- // 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 (!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- // `alibaba-token-plan-individual` and `-team-edition` share- // `routing.providerUid: "qwen-cloud"` and do publish memberships. Without this- // guard `qwen3-coder-plus` resolved `not-served`, `qwen-cloud` was dropped,- // and a holder of Alibaba's $50/month coding plan was billed per token —- // the flat-rate-user invariant CLAUDE.md names.- //- // Deliberately narrow: it only withholds the verdict when a same-vendor plan- // is genuinely invisible. Where every plan for the vendor is routable — z-ai's- // sole `z-ai-glm-coding-plan`, for one — the view is complete and- // `not-served` still stands, so this does not degrade into never dropping- // anything. The right long-term fix is a `routing` block on every plan the- // backend publishes; this keeps the client honest until then.- const vendorsInView = new Set(- providerPlans.map((plan) => plan.provider).filter((v): v is string => v !== undefined)+ // Client-selected and hybrid rosters are decided by the user's live session.+ if (plans.some((plan) => plan.modelDiscovery !== "catalog")) return { kind: "unknown" };+ const ids = new Set(plans.map((plan) => plan.id));+ const hasRoster = cache.entries.some((candidate) =>+ candidate.subscriptionPlanIds?.some((planId) => ids.has(planId)));- const hasUnroutableSiblingPlan = (cache.plans ?? []).some(- (plan) =>- plan.provider !== undefined &&- vendorsInView.has(plan.provider) &&- plan.routing?.providerUid === undefined- );- if (hasUnroutableSiblingPlan) return { 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 {- return plan.modelDiscovery === "catalog";-}--/** Legacy provider-UID membership detection for caches without queryPlans. */-function isLegacySubscriptionPlan(provider: string, cachePath?: string): boolean {- const cache = readAllModelsCache(cachePath);- if (!cache) return false;- return cache.entries.some((e) => e.subscriptionPlans?.includes(provider));+ return hasRoster ? { kind: "not-served" } : { kind: "unknown" };}/**@@ -588,8 +441,8 @@ export function resolvePlanDescribedModelId(): string | undefined {if (!plans) return undefined;for (const plan of plans) {- const described = plan.modelDescriptions?.[wireId];- if (described?.status === "described" && described.modelId) return described.modelId;+ const inclusion = plan.inclusions?.find((item) => item.externalModelId === wireId);+ if (inclusion?.resolution?.status === "mapped") return inclusion.resolution.modelId;}return undefined;}@@ -615,7 +468,7 @@ export interface CatalogSearchMatch {modelId: string;aliases: string[];/** Subscription plans that include this model, verbatim from the catalog. */- subscriptionPlans: string[];+ subscriptionPlanIds: string[];/** Set when the query matched an alias rather than the model id itself. */matchedAlias?: string;}@@ -684,7 +537,7 @@ export function searchCatalogModels(match: {modelId: entry.modelId,aliases: entry.aliases ?? [],- subscriptionPlans: entry.subscriptionPlans ?? [],+ subscriptionPlanIds: entry.subscriptionPlanIds ?? [],...(hit.matchedAlias ? { matchedAlias: hit.matchedAlias } : {}),},};diff --git a/packages/cli/src/adapters/qwen-model-dialect.ts b/packages/cli/src/adapters/qwen-model-dialect.tsindex 5f467da4..cb5a3eeb 100644--- a/packages/cli/src/adapters/qwen-model-dialect.ts+++ b/packages/cli/src/adapters/qwen-model-dialect.ts@@ -11,7 +11,7 @@* do not share a reasoning knob. Only the DashScope half lives here: the* Anthropic half is a property of the WIRE, not of the Qwen family, so it lives* in BaseAPIFormat.applyAnthropicWireReasoning() where every dialect inherits- * it. (Qwen Plan serves glm-5.2 and deepseek-v4-* over the same endpoint, so a+ * it. (Alibaba Token Plan serves glm-5.2 and deepseek-v4-* over the same endpoint, so a* Qwen-only implementation left those two emitting knobs that endpoint ignores.)** `applyNativeReasoning` is not called at all on the Anthropic wire, so nothingdiff --git a/packages/cli/src/adapters/variant-presets.test.ts b/packages/cli/src/adapters/variant-presets.test.tsindex 0abeaa80..2c02a77a 100644--- a/packages/cli/src/adapters/variant-presets.test.ts+++ b/packages/cli/src/adapters/variant-presets.test.ts@@ -3,6 +3,7 @@ import { mkdtempSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { writeAllModelsCache } from "../providers/all-models-cache.js";+import { catalogRouteForProvider } from "../providers/catalog-route-bindings.js";import { lookupRouteReasoningMode, lookupVariantPresets } from "./model-catalog.js";const BASE_MODEL_ID = "gpt-5.6-sol";@@ -18,15 +19,23 @@ beforeEach(() => {cachePath = join(tempDir, "all-models.json");writeAllModelsCache({+ version: 3,+ catalogGenerationId: "test-generation",+ lastUpdated: new Date().toISOString(),+ models: [],+ plans: [],entries: [{modelId: BASE_MODEL_ID,aliases: ["openai/gpt-5.6-sol"],- sources: {},+aggregators: [{- provider: "openai",- externalId: BASE_MODEL_ID,+ sourceCollectorId: "test",+ routeStatus: "mapped",+ route: catalogRouteForProvider("openai"),+ sourceProviderId: "openai",+ externalModelId: BASE_MODEL_ID,confidence: "api_official",reasoning: {mode: {@@ -37,14 +46,20 @@ beforeEach(() => {},},{- provider: "openai-codex",- externalId: BASE_MODEL_ID,+ sourceCollectorId: "test",+ routeStatus: "mapped",+ route: catalogRouteForProvider("openai-codex"),+ sourceProviderId: "openai-codex",+ externalModelId: BASE_MODEL_ID,confidence: "gateway_official",reasoning: { mode: { status: "rejected" } },},{- provider: "opencode-zen",- externalId: BASE_MODEL_ID,+ sourceCollectorId: "test",+ routeStatus: "mapped",+ route: catalogRouteForProvider("opencode-zen"),+ sourceProviderId: "opencode-zen",+ externalModelId: BASE_MODEL_ID,confidence: "gateway_official",reasoning: { mode: { status: "unknown" } },},@@ -53,7 +68,7 @@ beforeEach(() => {{modelId: VARIANT_MODEL_ID,aliases: [],- sources: {},+routeVariant: {kind: "provider-preset",baseModelId: BASE_MODEL_ID,diff --git a/packages/cli/src/auth/credentials/vertex-credential.ts b/packages/cli/src/auth/credentials/vertex-credential.tsindex f8de53b4..d664356c 100644--- a/packages/cli/src/auth/credentials/vertex-credential.ts+++ b/packages/cli/src/auth/credentials/vertex-credential.ts@@ -2,32 +2,30 @@* Vertex AI credential — ADC / service-account based (no interactive login).** Availability mirrors the existing vertex profile (provider-profiles.ts):- * either VERTEX_API_KEY (Express mode) is set OR a Vertex project is configured- * (VERTEX_PROJECT / GOOGLE_CLOUD_PROJECT, via getVertexConfig()). The request+ * a Vertex project is configured (VERTEX_PROJECT / GOOGLE_CLOUD_PROJECT), or+ * VERTEX_API_KEY selects Express mode in the absence of a project. The request* token is obtained from the shared VertexAuthManager (gcloud ADC or service* account); there is no login/logout because auth is ADC-based.*/-import { getVertexAuthManager, getVertexConfig } from "../vertex-auth.js";+import { getVertexAuthManager, selectVertexAuthMode } from "../vertex-auth.js";import type { CredentialProvider, RequestAuth, RequestAuthContext } from "./types.js";export class VertexCredentialProvider implements CredentialProvider {readonly catalogName = "vertex";async isAvailable(): Promise<boolean> {- return !!process.env.VERTEX_API_KEY || !!getVertexConfig();+ return selectVertexAuthMode() !== null;}async getRequestAuth(_ctx: RequestAuthContext): Promise<RequestAuth> {- // Express mode: VERTEX_API_KEY is a plain bearer key (standard Gemini- // endpoint). It is the authority-sourced credential for Express, so the- // proxy no longer reads process.env.VERTEX_API_KEY directly at sign-time.- const expressKey = process.env.VERTEX_API_KEY;- if (expressKey) {- return { headers: { Authorization: `Bearer ${expressKey}` } };+ // A project selects OAuth even when an Express key is also configured.+ if (selectVertexAuthMode() === "project") {+ const token = await getVertexAuthManager().getAccessToken();+ return { headers: { Authorization: `Bearer ${token}` } };}- // ADC / service-account mode: mint an OAuth access token.- const token = await getVertexAuthManager().getAccessToken();- return { headers: { Authorization: `Bearer ${token}` } };+ const expressKey = process.env.VERTEX_API_KEY;+ if (expressKey) return { headers: { Authorization: `Bearer ${expressKey}` } };+ throw new Error("Vertex requires a configured project or Express key");}}diff --git a/packages/cli/src/auth/quota-command.ts b/packages/cli/src/auth/quota-command.tsindex 6568d02a..0c5b8c53 100644--- a/packages/cli/src/auth/quota-command.ts+++ b/packages/cli/src/auth/quota-command.ts@@ -172,7 +172,7 @@ const FRIENDLY_NAMES: Record<string, string> = {sakana: "sakana-subscription",fugu: "sakana-subscription",zen: "opencode-zen-go",- qwen: "qwen-cloud",+ qwen: "qwen-token-plan",// Same divergence as `gemini` above, in the other direction: as a ROUTING// prefix `grok` means the metered `x-ai` API, but someone typing// `claudish quota grok` is asking about the subscription — the only one ofdiff --git a/packages/cli/src/auth/quota/registry.ts b/packages/cli/src/auth/quota/registry.tsindex 4c3c8d8c..ae5f1288 100644--- a/packages/cli/src/auth/quota/registry.ts+++ b/packages/cli/src/auth/quota/registry.ts@@ -169,8 +169,8 @@ const NO_SURFACE: Array<{ id: string; label: string; evidence: ProbeRecord }> =},},{- id: "qwen-cloud",- label: "Qwen Plan",+ id: "qwen-token-plan",+ label: "Alibaba Token Plan",evidence: {researched_at: "2026-08-03",probed: [diff --git a/packages/cli/src/auth/vertex-auth-mode.test.ts b/packages/cli/src/auth/vertex-auth-mode.test.tsnew file mode 100644index 00000000..5727dac9--- /dev/null+++ b/packages/cli/src/auth/vertex-auth-mode.test.ts@@ -0,0 +1,18 @@+import { describe, expect, test } from "bun:test";+import { selectVertexAuthMode } from "./vertex-auth.js";++describe("Vertex account selection", () => {+ test("a selected project takes precedence over an Express key", () => {+ expect(selectVertexAuthMode({ project: "chosen-project", expressKey: "configured-key" })).toBe(+ "project"+ );+ });++ test("the Express key is selected only without a project", () => {+ expect(selectVertexAuthMode({ expressKey: "configured-key" })).toBe("express");+ });++ test("neither mode is available without configuration", () => {+ expect(selectVertexAuthMode({})).toBeNull();+ });+});diff --git a/packages/cli/src/auth/vertex-auth.ts b/packages/cli/src/auth/vertex-auth.tsindex b1351fcb..847b069a 100644--- a/packages/cli/src/auth/vertex-auth.ts+++ b/packages/cli/src/auth/vertex-auth.ts@@ -199,6 +199,17 @@ export function getVertexConfig(): VertexConfig | null {};}+/** A configured project selects OAuth; Express applies only without a project. */+export function selectVertexAuthMode(+ configured: { project?: string; expressKey?: string } = {+ project: getVertexConfig()?.projectId,+ expressKey: process.env.VERTEX_API_KEY,+ }+): "project" | "express" | null {+ if (configured.project) return "project";+ return configured.expressKey ? "express" : null;+}+/*** Validate Vertex AI OAuth configuration* Returns error message if invalid, null if OKdiff --git a/packages/cli/src/claude-runner-child-stderr.test.ts b/packages/cli/src/claude-runner-child-stderr.test.tsindex 6cd83466..7f479580 100644--- a/packages/cli/src/claude-runner-child-stderr.test.ts+++ b/packages/cli/src/claude-runner-child-stderr.test.ts@@ -4,9 +4,9 @@ import { PassThrough } from "node:stream";import { isSuppressibleChildStderrLine, relayChildStderr } from "./claude-runner.js";const SDK_NOISE =- '[claude-code:unrecognized_model] {"model":"[email protected]","query_source":"sdk"}';+ '[claude-code:unrecognized_model] {"model":"[email protected]","query_source":"sdk"}';const TITLE_NOISE =- '[claude-code:unrecognized_model] {"model":"[email protected]","query_source":"generate_session_title"}';+ '[claude-code:unrecognized_model] {"model":"[email protected]","query_source":"generate_session_title"}';describe("isSuppressibleChildStderrLine", () => {test("suppresses the unrecognized-model line from both observed query sources", () => {@@ -73,7 +73,7 @@ describe("relayChildStderr", () => {const ended = once(stream, "end");stream.write("[claude-code:unrecog");- stream.end('nized_model] {"model":"[email protected]","query_source":"sdk"}\n');+ stream.end('nized_model] {"model":"[email protected]","query_source":"sdk"}\n');await ended;expect(stderrWrites).toEqual([]);diff --git a/packages/cli/src/claude-runner-context-window.test.ts b/packages/cli/src/claude-runner-context-window.test.tsindex 092d86e5..f61f6e05 100644--- a/packages/cli/src/claude-runner-context-window.test.ts+++ b/packages/cli/src/claude-runner-context-window.test.ts@@ -8,6 +8,7 @@ import {resolveContextWindowEnv,} from "./claude-runner.js";import { ENV } from "./config.js";+import { catalogRouteForProvider } from "./providers/catalog-route-bindings.js";import type { ClaudishConfig } from "./types.js";const REDUCED_WINDOW_SPEC = "[email protected]";@@ -25,24 +26,33 @@ beforeAll(() => {{modelId: "gpt-5.6-sol",aliases: [],- sources: {},+contextWindow: 1_050_000,aggregators: [{- provider: "openai",- externalId: "gpt-5.6-sol",+ sourceCollectorId: "test",+ routeStatus: "mapped",+ route: catalogRouteForProvider("openai"),+ sourceProviderId: "openai",+ externalModelId: "gpt-5.6-sol",confidence: "api_official",contextWindow: 1_050_000,},{- provider: "openai-codex",- externalId: "gpt-5.6-sol",+ sourceCollectorId: "test",+ routeStatus: "mapped",+ route: catalogRouteForProvider("openai-codex"),+ sourceProviderId: "openai-codex",+ externalModelId: "gpt-5.6-sol",confidence: "api_official",contextWindow: 372_000,},{- provider: "openrouter",- externalId: "openai/gpt-5.6-sol",+ sourceCollectorId: "test",+ routeStatus: "mapped",+ route: catalogRouteForProvider("openrouter"),+ sourceProviderId: "openrouter",+ externalModelId: "openai/gpt-5.6-sol",confidence: "gateway_official",},],@@ -50,12 +60,15 @@ beforeAll(() => {{modelId: "small-context-model",aliases: [],- sources: {},+contextWindow: 128_000,aggregators: [{- provider: "openai-codex",- externalId: "small-context-model",+ sourceCollectorId: "test",+ routeStatus: "mapped",+ route: catalogRouteForProvider("openai-codex"),+ sourceProviderId: "openai-codex",+ externalModelId: "small-context-model",confidence: "api_official",contextWindow: 128_000,},@@ -66,7 +79,9 @@ beforeAll(() => {writeFileSync(mockCachePath,JSON.stringify({- version: 2,+ catalogGenerationId: "test-generation",+ plans: [],+ version: 3,lastUpdated: new Date().toISOString(),entries,models: entries.map((entry) => ({ id: entry.modelId })),diff --git a/packages/cli/src/claude-runner.ts b/packages/cli/src/claude-runner.tsindex 0583381b..1bba166b 100644--- a/packages/cli/src/claude-runner.ts+++ b/packages/cli/src/claude-runner.ts@@ -518,7 +518,7 @@ const MAX_TOKEN_FILES_SCANNED = 4000;* `~/.claudish/tokens-<port>.json` is keyed by PORT, not by session, and nothing* used to initialise it. Ports get reused, so a new session that happened to* bind a port some long-dead run had used inherited that run's numbers: a fresh- * LM Studio-free session displayed `cli • LMStudio [email protected] • $0.000 •+ * LM Studio-free session displayed `cli • LMStudio [email protected] • $0.000 •* 0% (36k/32k)`, where every figure came from a five-week-old leftover file.** The zeroed record is deliberately NEUTRAL rather than pre-populated: no@@ -888,7 +888,7 @@ export function createTempSettingsFile(// silently dropped provider_name and model_name too. (macOS BSD grep// exits 0, which is why it was invisible locally.)// 2. Only newlines are stripped, never spaces. `tr -d ' '` mangled every- // value containing one — "Qwen Plan" rendered as "QwenPlan". The patterns+ // value containing one — "Alibaba Token Plan" rendered as "QwenPlan". The patterns// instead tolerate optional whitespace after each colon, so a// pretty-printed token file still parses.// 3. The "unknown" sentinel keeps working: an unmatched numeric field leaves@@ -912,8 +912,8 @@ export function createTempSettingsFile(// The CHAINED segment deliberately drops the model name that// segmentWithDir shows. It is appended to the user's OWN status line, which// already renders the model — printing it again produced- // "… [email protected] … • [email protected] • $0.000 • N/A". The provider- // ("Qwen Plan") is the part the user's line cannot know, so it takes the+ // "… [email protected] … • [email protected] • $0.000 • N/A". The provider+ // ("Alibaba Token Plan") is the part the user's line cannot know, so it takes the// slot instead. When the token file hasn't reported one yet (a fresh// session, before the first response), the field is omitted ENTIRELY rather// than falling back to the model name or emitting an empty segment with a@@ -1677,7 +1677,7 @@ export async function runClaudeWithProxy(// summary nothing will ever resume. Both are billed on the ROUTED model, so a// three-slot `team` run pays for three of them.//- // Measured 2026-09-17, same prompt and model (`[email protected]`), counting+ // Measured 2026-09-17, same prompt and model (`[email protected]`), counting// upstream responses in the session log://// suppressed : 1 upstream requestdiff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.tsindex 9d400411..275d05e1 100644--- a/packages/cli/src/cli.ts+++ b/packages/cli/src/cli.ts@@ -64,6 +64,7 @@ import { BUILTIN_PROVIDERS, getProviderByName } from "./providers/provider-definimport { resolveProviderSlug } from "./providers/provider-slug-resolve.js";import {buildRoutingChain,+ hasCredentialsForProvider,loadRoutingRules,matchRoutingRule,} from "./providers/routing-rules.js";@@ -1150,7 +1151,7 @@ async function printByProvider(typedSlug: string, jsonOutput: boolean): Promise<const providerSlug = resolved.canonical ?? typedSlug;let models: ModelDoc[];try {- models = await getModelsByProvider(providerSlug, 200);+ models = await getModelsByProvider(providerSlug);} catch (error) {console.error(`❌ Failed to load provider catalog from Firebase: ${@@ -1557,6 +1558,40 @@ async function probeModelRouting(return { parsed, chain, chainDetails };}+ const probeCredentialReadiness = new Map<string, boolean>();+ async function credentialForProbe(provider: string): Promise<boolean> {+ if (probeCredentialReadiness.has(provider)) return probeCredentialReadiness.get(provider)!;+ const ready =+ provider === "native-anthropic"+ ? !!process.env.ANTHROPIC_API_KEY+ : await hasCredentialsForProvider(provider);+ probeCredentialReadiness.set(provider, ready);+ return ready;+ }++ async function prepareModelChain(+ modelInput: string+ ): Promise<ReturnType<typeof buildModelChain>> {+ const result = buildModelChain(modelInput);+ await Promise.all(+ result.chainDetails.map(async (link) => {+ link.hasCredentials = await credentialForProbe(link.provider);+ link.credentialHint = link.hasCredentials+ ? undefined+ : link.provider === "native-anthropic"+ ? "ANTHROPIC_API_KEY (required to probe Claude Code)"+ : getProviderByName(link.provider)?.isLocal+ ? "enable local provider in global config"+ : API_KEY_MAP[link.provider]?.envVar;+ const keyInfo = API_KEY_MAP[link.provider];+ if (keyInfo?.envVar)+ link.provenance = resolveApiKeyProvenance(keyInfo.envVar, keyInfo.aliases);+ })+ );+ if (result.chain.source === "direct") await credentialForProbe(result.parsed.provider);+ return result;+ }+/*** Routing-why one-liner shown on the right of each model header in the* Details tab. Kept as a SINGLE function so a later routing worktree can swap@@ -1614,17 +1649,10 @@ async function probeModelRouting(// empty and now MEANS empty.if (!providerDef && !keyInfo) return [];- let hasCredentials: boolean;- let provenance: KeyProvenance | undefined;- if (providerDef?.isLocal) {- hasCredentials = isLocalProviderEnabled(parsed.provider);- } else if (!keyInfo?.envVar) {- hasCredentials = true;- } else {- provenance = resolveApiKeyProvenance(keyInfo.envVar, keyInfo.aliases);- hasCredentials =- provenance.hasValue || (keyInfo.aliases?.some((a) => !!process.env[a]) ?? false);- }+ const hasCredentials = probeCredentialReadiness.get(parsed.provider) ?? false;+ const provenance = keyInfo?.envVar+ ? resolveApiKeyProvenance(keyInfo.envVar, keyInfo.aliases)+ : undefined;return [{@@ -1662,22 +1690,18 @@ async function probeModelRouting(// Explicit/direct model — one synthetic link from the native provider.const directProviderDef = getProviderByName(parsed.provider);const directKeyInfo = API_KEY_MAP[parsed.provider];- const directHasCreds = directProviderDef?.isLocal- ? isLocalProviderEnabled(parsed.provider)- : directKeyInfo?.envVar- ? !!process.env[directKeyInfo.envVar] ||- (directKeyInfo.aliases?.some((a) => !!process.env[a]) ?? false)- : true;+ const directHasCreds = probeCredentialReadiness.get(parsed.provider) ?? false;return [{provider: parsed.provider,displayName: directProviderDef?.displayName ?? parsed.provider,modelId: parsed.model,hasCredentials: directHasCreds,- credentialHint:- directProviderDef?.isLocal && !directHasCreds+ credentialHint: !directHasCreds+ ? directProviderDef?.isLocal? "enable local provider in global config"- : directKeyInfo?.envVar,+ : directKeyInfo?.envVar+ : undefined,probe: directProbe,},];@@ -1717,7 +1741,8 @@ async function probeModelRouting("minimax-coding","kimi","kimi-coding",- "qwen-cloud",+ "qwen-token-plan",+ "qwen-coding","qwen-payg","z-ai",];@@ -1813,19 +1838,14 @@ async function probeModelRouting(const results: ChainProbe[] = [];for (const modelInput of models) {- const { parsed, chain, chainDetails } = buildModelChain(modelInput);+ const { parsed, chain, chainDetails } = await prepareModelChain(modelInput);// Direct probelet directProbeResult: ProbeResult | undefined;if (liveProxy && chain.source === "direct") {const directKeyInfo = API_KEY_MAP[parsed.provider];const directProviderDef = getProviderByName(parsed.provider);- const directHasCreds = directProviderDef?.isLocal- ? isLocalProviderEnabled(parsed.provider)- : directKeyInfo?.envVar- ? !!process.env[directKeyInfo.envVar] ||- (directKeyInfo.aliases?.some((a) => !!process.env[a]) ?? false)- : true;+ const directHasCreds = await credentialForProbe(parsed.provider);const directCredentialHint =directProviderDef?.isLocal && !directHasCreds? "enable local provider in global config"@@ -1975,7 +1995,7 @@ async function probeModelRouting(chainDetails: ReturnType<typeof buildModelChain>["chainDetails"];}> = [];for (const modelInput of models) {- const { parsed, chain, chainDetails } = buildModelChain(modelInput);+ const { parsed, chain, chainDetails } = await prepareModelChain(modelInput);modelChains.push({ modelInput, parsed, chain, chainDetails });}updateStep("Resolving routing chains", "done");@@ -2002,12 +2022,7 @@ async function probeModelRouting(if (chain.source === "direct") {const directKeyInfo = API_KEY_MAP[parsed.provider];const directProviderDef = getProviderByName(parsed.provider);- const directHasCreds = directProviderDef?.isLocal- ? isLocalProviderEnabled(parsed.provider)- : directKeyInfo?.envVar- ? !!process.env[directKeyInfo.envVar] ||- (directKeyInfo.aliases?.some((a) => !!process.env[a]) ?? false)- : true;+ const directHasCreds = await credentialForProbe(parsed.provider);const directCredentialHint =directProviderDef?.isLocal && !directHasCreds? "enable local provider in global config"diff --git a/packages/cli/src/config.ts b/packages/cli/src/config.tsindex 340f497d..6c7f1300 100644--- a/packages/cli/src/config.ts+++ b/packages/cli/src/config.ts@@ -14,7 +14,7 @@ export const ENV = {// CLAUDISH_TOKEN_FILE is running against a proxied, non-Anthropic account and// must not render Anthropic plan/rate-limit data.CLAUDISH_TOKEN_FILE: "CLAUDISH_TOKEN_FILE", // Absolute path to ~/.claudish/tokens-<port>.json for this session- CLAUDISH_PROVIDER_NAME: "CLAUDISH_PROVIDER_NAME", // Provider display name (e.g. "Qwen Plan"); UNSET when not known at spawn time+ CLAUDISH_PROVIDER_NAME: "CLAUDISH_PROVIDER_NAME", // Provider display name (e.g. "Alibaba Token Plan"); UNSET when not known at spawn timeANTHROPIC_MODEL: "ANTHROPIC_MODEL", // Claude Code standard env var for model selectionANTHROPIC_SMALL_FAST_MODEL: "ANTHROPIC_SMALL_FAST_MODEL", // Claude Code standard env var for fast model// Claudish model mapping overrides (highest priority)diff --git a/packages/cli/src/handlers/advisor-routing-and-state.test.ts b/packages/cli/src/handlers/advisor-routing-and-state.test.tsindex fdbea47c..63d9d60e 100644--- a/packages/cli/src/handlers/advisor-routing-and-state.test.ts+++ b/packages/cli/src/handlers/advisor-routing-and-state.test.ts@@ -190,9 +190,6 @@ describe("OpenRouter advisor wire-model resolution", () => {{modelId: "kimi-k3",aliases: [],- sources: {- "fireworks-api": { externalId: "accounts/fireworks/models/kimi-k3" },- },},]);@@ -204,7 +201,16 @@ describe("OpenRouter advisor wire-model resolution", () => {{modelId: "grok-4.6",aliases: [],- sources: { "openrouter-api": { externalId: "x-ai/grok-4.6" } },+ aggregators: [+ {+ sourceProviderId: "openrouter",+ sourceCollectorId: "test",+ confidence: "aggregator_reported",+ routeStatus: "mapped",+ route: { routeId: "openrouter", routeProfileId: "gateway" },+ externalModelId: "x-ai/grok-4.6",+ },+ ],},]);@@ -216,7 +222,16 @@ describe("OpenRouter advisor wire-model resolution", () => {{modelId: "gpt-5.6-sol",aliases: [],- sources: { "openrouter-api": { externalId: "openai/gpt-5.6-sol" } },+ aggregators: [+ {+ sourceProviderId: "openrouter",+ sourceCollectorId: "test",+ confidence: "aggregator_reported",+ routeStatus: "mapped",+ route: { routeId: "openrouter", routeProfileId: "gateway" },+ externalModelId: "openai/gpt-5.6-sol",+ },+ ],},]);diff --git a/packages/cli/src/handlers/composed-handler.ts b/packages/cli/src/handlers/composed-handler.tsindex e745df89..7e078564 100644--- a/packages/cli/src/handlers/composed-handler.ts+++ b/packages/cli/src/handlers/composed-handler.ts@@ -206,7 +206,7 @@ export class ComposedHandler implements ModelHandler {// The second argument is the REQUEST wire format, which only this class// knows: dialects self-select by model name, and the same model can be// served over different wires by different providers (Qwen: DashScope- // OpenAI-compatible vs. Qwen Plan's Anthropic Messages endpoint),+ // OpenAI-compatible vs. Alibaba Token Plan's Anthropic Messages endpoint),// each with a differently-named reasoning knob. The Layer 1 FormatConverter// decides the request shape, so its getStreamFormat() is the signal — NOT// provider.overrideStreamFormat(), which only re-labels the RESPONSE for@@ -1575,7 +1575,7 @@ export class ComposedHandler implements ModelHandler {// default `false` — which silently made the one dialect override of// it (MiniMaxModelDialect's `true`) unreachable dead code, and would// do the same to the base's wire-keyed `true` for every other model- // on this wire (qc@'s qwen / glm / deepseek rosters).+ // on this wire (qtoken@'s qwen / glm / deepseek rosters).adapter: (this.modelAdapter ?? adapter) as BaseAPIFormat,shouldBufferTool: (name) => behaviorSession?.interceptsTool(name) ?? false,repairToolArgs: (name, argsJson) =>diff --git a/packages/cli/src/handlers/default-provider-e2e.test.ts b/packages/cli/src/handlers/default-provider-e2e.test.tsindex c1da5947..bece6fa2 100644--- a/packages/cli/src/handlers/default-provider-e2e.test.ts+++ b/packages/cli/src/handlers/default-provider-e2e.test.ts@@ -697,10 +697,13 @@ describe.skipIf(SKIP_LIVE_E2E)("Group D — Firebase slim catalog", () => {async function fetchCatalog(): Promise<any> {if (cachedBody) return cachedBody;const res = await fetch(- "https://us-central1-claudish-6da10.cloudfunctions.net/queryModels?status=active&catalog=slim&limit=100"+ "https://us-central1-claudish-6da10.cloudfunctions.net/queryModels?status=active&catalog=slim&limit=100",+ { headers: { Accept: "application/vnd.models-index.catalog+json;version=3" } });expect(res.status).toBe(200);- cachedBody = await res.json();+ const envelope = await res.json();+ expect(envelope.contractVersion).toBe(3);+ cachedBody = envelope.data;return cachedBody;}@@ -729,10 +732,13 @@ describe.skipIf(SKIP_LIVE_E2E)("Group D — Firebase slim catalog", () => {const seenProviders = new Set<string>();for (const m of withAgg) {for (const agg of m.aggregators) {- expect(typeof agg.provider).toBe("string");- expect(typeof agg.externalId).toBe("string");+ expect(typeof agg.sourceProviderId).toBe("string");+ if (agg.routeStatus !== "mapped") continue;+ expect(typeof agg.route?.routeId).toBe("string");+ expect(typeof agg.route?.routeProfileId).toBe("string");+ expect(typeof agg.externalModelId).toBe("string");expect(typeof agg.confidence).toBe("string");- seenProviders.add(agg.provider);+ seenProviders.add(agg.sourceProviderId);}}diff --git a/packages/cli/src/handlers/native-handler-advisor.ts b/packages/cli/src/handlers/native-handler-advisor.tsindex ccfc85ca..19db9ea4 100644--- a/packages/cli/src/handlers/native-handler-advisor.ts+++ b/packages/cli/src/handlers/native-handler-advisor.ts@@ -1,3 +1,4 @@+import { catalogRouteMatchesProvider } from "../providers/catalog-route-bindings.js";/*** Advisor-tool transformer for NativeHandler (monitor mode).*@@ -1589,9 +1590,10 @@ export function advisorRouteFor(modelSpec: string, role: "panel" | "collector"):* OpenRouter's own catalog data.*/function openRouterIdOf(entry: SlimModelEntry): string | null {- const fromAggregator = entry.aggregators?.find((a) => a.provider === "openrouter")?.externalId;- if (fromAggregator) return fromAggregator;- return entry.sources["openrouter-api"]?.externalId ?? null;+ return (+ entry.aggregators?.find((a) => catalogRouteMatchesProvider(a.route, "openrouter"))+ ?.externalModelId ?? null+ );}/**@@ -1682,8 +1684,9 @@ function nativeVendorsForProvider(providerUid: string): string[] {const vendors = new Set<string>();try {for (const plan of readAllModelsCache()?.plans ?? []) {- if (plan.routing?.providerUid !== providerUid) continue;- for (const native of plan.routing.nativeModelProviders ?? []) vendors.add(native);+ if (plan.routeStatus !== "supported" || !catalogRouteMatchesProvider(plan.route, providerUid))+ continue;+ if (plan.route?.routeId) vendors.add(plan.route.routeId);}} catch {// a cache that will not read is the cold case belowdiff --git a/packages/cli/src/handlers/shared/remote-provider-types.ts b/packages/cli/src/handlers/shared/remote-provider-types.tsindex e19beb8f..19e5f37c 100644--- a/packages/cli/src/handlers/shared/remote-provider-types.ts+++ b/packages/cli/src/handlers/shared/remote-provider-types.ts@@ -165,7 +165,8 @@ export const SUBSCRIPTION_PROVIDERS = new Set(["minimax-coding","kimi-coding","glm-coding",- "qwen-cloud",+ "qwen-token-plan",+ "qwen-coding",// Devin bills one flat subscription across every vendor's models it serves.// Without this the picker prints an invented per-token price and TokenTracker// accrues fictional cost.diff --git a/packages/cli/src/handlers/shared/stream-parsers/anthropic-sse.ts b/packages/cli/src/handlers/shared/stream-parsers/anthropic-sse.tsindex 35cac498..185ac413 100644--- a/packages/cli/src/handlers/shared/stream-parsers/anthropic-sse.ts+++ b/packages/cli/src/handlers/shared/stream-parsers/anthropic-sse.ts@@ -43,7 +43,7 @@ interface AnthropicPassthroughOpts {* leading space. Every anthropic-transport provider we had fixtures for* (MiniMax, Z.AI) emits the spaced form, so the older* `startsWith("data: ")` gate silently skipped every line from Alibaba Model- * Studio (qwen-cloud), which emits the bare form. The stream still reached+ * Studio (qwen-token-plan), which emits the bare form. The stream still reached* Claude Code verbatim, so sessions worked — but claudish's own inspection* (token accounting, in-stream error detection, thinking re-indexing,* Layer-4 repairToolArgs) never ran.diff --git a/packages/cli/src/handlers/shared/token-tracker.ts b/packages/cli/src/handlers/shared/token-tracker.tsindex 3920d0ae..54ab1e51 100644--- a/packages/cli/src/handlers/shared/token-tracker.ts+++ b/packages/cli/src/handlers/shared/token-tracker.ts@@ -48,8 +48,8 @@ export interface UsageCacheDetail {* Strip a `provider@` routing prefix from a model spec.** The status line renders `"<provider_name> <model_name>"`, so a model_name that- * still carries its routing prefix names the provider twice — `[email protected]`- * under the "Qwen Plan" label reads as "Qwen Plan [email protected]".+ * still carries its routing prefix names the provider twice — `[email protected]`+ * under the "Alibaba Token Plan" label reads as "Alibaba Token Plan [email protected]".* ComposedHandler already enforces a bare `modelName`, but a fallback override* comes from a transport and this is cheap insurance.*/@@ -521,8 +521,8 @@ export class TokenTracker {};// model_name is ALWAYS written, not just when a fallback override is active.// The status line's fallback for a missing key is $CLAUDISH_ACTIVE_MODEL_NAME,- // which is the full routed spec (`[email protected]`) — rendered next to the- // provider label that produces "Qwen Plan [email protected]". The override+ // which is the full routed spec (`[email protected]`) — rendered next to the+ // provider label that produces "Alibaba Token Plan [email protected]". The override// still wins when set, because a capacity fallback legitimately needs to show// the SUBSTITUTED model rather than the one the user asked for.const displayModel = stripProviderPrefix(diff --git a/packages/cli/src/launcher/catalog-warm.test.ts b/packages/cli/src/launcher/catalog-warm.test.tsindex 37d0a507..1c236c91 100644--- a/packages/cli/src/launcher/catalog-warm.test.ts+++ b/packages/cli/src/launcher/catalog-warm.test.ts@@ -10,7 +10,7 @@*/import { afterAll, afterEach, beforeEach, describe, expect, mock, test } from "bun:test";-import type { DiskCacheV2 } from "../providers/all-models-cache.js";+import type { DiskCacheV3 } from "../providers/all-models-cache.js";// Value imports captured BEFORE the mock.module calls below so we can restore// the REAL modules in afterAll. Bun's mock.module is PROCESS-GLOBAL and// persists across files, so without this restore the stubs here bleed into@@ -33,7 +33,7 @@ const __realCatalogClientExports = { ...__realCatalogClient };// here BEFORE importing catalog-warm. The mocks are mutated in beforeEach to// configure each test case.-let mockReadResult: DiskCacheV2 | null = null;+let mockReadResult: DiskCacheV3 | null = null;let mockRefreshOutcome: RefreshOutcome = { kind: "refreshed", modelCount: 0 };const refreshSpy = mock(async (_timeoutMs: number): Promise<RefreshOutcome> => {return mockRefreshOutcome;@@ -130,11 +130,13 @@ describe("shouldWarmCatalog", () => {describe("classifyCatalogState", () => {const NOW = new Date("2026-05-08T12:00:00.000Z");- function diskCache(overrides: Partial<DiskCacheV2> = {}): DiskCacheV2 {+ function diskCache(overrides: Partial<DiskCacheV3> = {}): DiskCacheV3 {return {- version: 2,+ catalogGenerationId: "test-generation",+ plans: [],+ version: 3,lastUpdated: NOW.toISOString(),- entries: [{ modelId: "alpha", aliases: [], sources: {} }],+ entries: [{ modelId: "alpha", aliases: [] }],models: [{ id: "vendor/alpha" }],...overrides,};@@ -197,20 +199,24 @@ describe("warmCatalogIfNeeded", () => {} as ClaudishConfig;}- function freshCache(): DiskCacheV2 {+ function freshCache(): DiskCacheV3 {return {- version: 2,+ catalogGenerationId: "test-generation",+ plans: [],+ version: 3,lastUpdated: new Date(NOW.getTime() - 60 * 60 * 1000).toISOString(), // 1h old- entries: [{ modelId: "alpha", aliases: [], sources: {} }],+ entries: [{ modelId: "alpha", aliases: [] }],models: [{ id: "vendor/alpha" }],};}- function staleCache(): DiskCacheV2 {+ function staleCache(): DiskCacheV3 {return {- version: 2,+ catalogGenerationId: "test-generation",+ plans: [],+ version: 3,lastUpdated: new Date(NOW.getTime() - 30 * 60 * 60 * 1000).toISOString(), // 30h old- entries: [{ modelId: "alpha", aliases: [], sources: {} }],+ entries: [{ modelId: "alpha", aliases: [] }],models: [{ id: "vendor/alpha" }],};}@@ -331,9 +337,11 @@ describe("warmCatalogIfNeeded", () => {// 24h boundary because classifyCatalogState uses strict-less-than.const oneDayAgo = new Date(NOW.getTime() - 24 * 3_600_000).toISOString();mockReadResult = {- version: 2,+ catalogGenerationId: "test-generation",+ plans: [],+ version: 3,lastUpdated: oneDayAgo,- entries: [{ modelId: "alpha", aliases: [], sources: {} }],+ entries: [{ modelId: "alpha", aliases: [] }],models: [{ id: "vendor/alpha" }],};mockRefreshOutcome = { kind: "fetch_failed", reason: "network" };diff --git a/packages/cli/src/launcher/catalog-warm.ts b/packages/cli/src/launcher/catalog-warm.tsindex 6dcc8f1d..9535451a 100644--- a/packages/cli/src/launcher/catalog-warm.ts+++ b/packages/cli/src/launcher/catalog-warm.ts@@ -15,13 +15,8 @@* is harmless if the launcher already populated the cache.*/-import { type DiskCacheV2, readAllModelsCache } from "../providers/all-models-cache.js";+import { type DiskCacheV3, readAllModelsCache } from "../providers/all-models-cache.js";import { type RefreshOutcome, refreshCatalog } from "../providers/catalog-client.js";-import {- type CatalogIncompatibility,- catalogIncompatibilityMessage,- readCatalogIncompatibility,-} from "../providers/catalog-compatibility.js";import type { ClaudishConfig } from "../types.js";import { VERSION } from "../version.js";@@ -120,7 +115,7 @@ export function shouldWarmCatalog(args: {* silently drift past the policy.*/export function classifyCatalogState(- cache: DiskCacheV2 | null,+ cache: DiskCacheV3 | null,ttlHours: number,now: Date): "fresh" | "stale" | "missing" {@@ -266,13 +261,6 @@ export async function warmCatalogIfNeeded(opts?.ttlHours ?? Number.parseFloat(process.env.CLAUDISH_CATALOG_TTL_HOURS ?? "24");const ttlHours = Number.isFinite(ttlHoursRaw) && ttlHoursRaw > 0 ? ttlHoursRaw : 24;const now = opts?.now ?? new Date();- // This read is GATED: it returns null while a contract sentinel is set, so- // `state` is "missing" for a cache that is sitting right there on disk. Two- // consequences, both wanted, and both undone by "simplifying" this to an- // ungated read. (1) A sentinel can never take the `fresh` early-return below,- // so every launch under one attempts the refresh that would heal it. (2) Every- // downstream branch that reasons from `state` has to be sentinel-aware — the- // reason `reportFetchFailure` is guarded rather than trusted.const cache = readAllModelsCache();const state = classifyCatalogState(cache, ttlHours, now);@@ -316,32 +304,15 @@ export async function warmCatalogIfNeeded(function reportUnusableCatalog(outcome: Exclude<RefreshOutcome, { kind: "refreshed" }>,state: ReturnType<typeof classifyCatalogState>,- cache: DiskCacheV2 | null,+ cache: DiskCacheV3 | null,now: Date,quiet: boolean): WarmOutcome {- // The server answered in a contract this build cannot read. This is NOT a- // fetch failure and must not fall into the branches below, every one of which- // 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.- //- // "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, infers no subscription, and is safe. So- // the launcher 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 here.if (outcome.kind === "incompatible") {- // `refreshCatalog` has already recorded the finding; the fallback only- // covers a sentinel whose disk write failed, where the message still has to- // name the version the server just reported.- return reportIncompatibleCatalog(- readCatalogIncompatibility() ?? {- detectedAt: new Date().toISOString(),- serverContractVersion: outcome.serverContractVersion,- }+ process.stderr.write(+ `Model catalog contract v${outcome.serverContractVersion ?? "unknown"} is not supported by this build.\n`);+ return cache === null ? "hard_fail" : "warned";}// `disabled` is not a failure and must never reach the branches below. Nobody@@ -367,66 +338,12 @@ function reportUnusableCatalog(return "skipped";}- // The refresh never got an answer — offline, DNS, a corporate proxy, or just- // slower than the 8s budget. Before classifying that against the cache, ask- // whether an EARLIER run already recorded a contract mismatch, because if it- // did, `state` is a lie: `readAllModelsCache()` refuses to hand out a cache- // while the sentinel is set, so a present-but-unreadable catalog classifies as- // "missing" and `reportFetchFailure` would hard-fail with "no cached copy- // found" — false, unactionable, and pointing at the network when the remedy is- // `claudish update`.- //- // Exiting is wrong on its own terms too. `hard_fail` ends the launch before- // routing runs, so an explicit `gk@grok-4` dies with it — and that spec names- // its own provider, infers no subscription and substitutes nothing, so there- // is nothing to protect it from. Deciding per name is the routing gate's job- // and it already does it: `routeBare` throws, `routeExplicit` proceeds. The- // launcher's job is to say so once, and get out of the way.- const recorded = readCatalogIncompatibility();- if (recorded !== null) return reportIncompatibleCatalog(recorded);-return reportFetchFailure(state, cache, now);}-/**- * 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.- *- * Both callers reach this with the RECORD rather than the refresh outcome, so- * the two paths in — the server answered in a contract we cannot read, and a- * previous run already found that out — print the identical text. The second is- * the common one after a cutover: most launches never get an answer at all.- *- * Printed regardless of `--quiet`, like every other warning in this file.- */-function reportIncompatibleCatalog(recorded: CatalogIncompatibility): WarmOutcome {- process.stderr.write(`${catalogIncompatibilityMessage(recorded)}\n`);- return "warned";-}--/**- * The fetch-failed decision tree, keyed on what was already on disk.- *- * Split out of `warmCatalogIfNeeded` unchanged. Every branch here ends in some- * form of "using cached version" or "no cached copy found", which is what makes- * it the wrong home for a contract mismatch: there, the cached version is- * precisely what stopped being usable while still sitting on disk. Keeping the- * two apart is the whole reason `incompatible` is not a `fetch_failed` variant.- *- * PRECONDITION, and the caller enforces it: no sentinel is set. `state` is- * computed from the GATED `readAllModelsCache()`, so under a sentinel it reads- * "missing" for a cache that exists — every branch below would then be- * describing a different failure than the one that happened.- */function reportFetchFailure(state: ReturnType<typeof classifyCatalogState>,- cache: DiskCacheV2 | null,+ cache: DiskCacheV3 | null,now: Date): WarmOutcome {if (state === "stale") {diff --git a/packages/cli/src/mcp-server.ts b/packages/cli/src/mcp-server.tsindex 19b31b03..345c0156 100644--- a/packages/cli/src/mcp-server.ts+++ b/packages/cli/src/mcp-server.ts@@ -871,7 +871,7 @@ function defineTools(s += "| Bare name | Matched alias | Subscription plan |\n";s += "|-----------|---------------|-------------------|\n";for (const m of catalogMatches) {- const plans = m.subscriptionPlans.length > 0 ? m.subscriptionPlans.join(", ") : "-";+ const plans = m.subscriptionPlanIds.length > 0 ? m.subscriptionPlanIds.join(", ") : "-";s += `| ${m.modelId} | ${m.matchedAlias ?? "-"} | ${plans} |\n`;}s +=diff --git a/packages/cli/src/model-catalog.test.ts b/packages/cli/src/model-catalog.test.tsindex 913897f7..ca6bb123 100644--- a/packages/cli/src/model-catalog.test.ts+++ b/packages/cli/src/model-catalog.test.ts@@ -1,3 +1,4 @@+import { catalogRouteForProvider } from "./providers/catalog-route-bindings.js";/*** E2E tests for the model catalog and translation layer.*@@ -46,58 +47,67 @@ beforeAll(() => {{modelId: "minimax-m2.7",aliases: ["MiniMax-M2.7", "minimax-m2-7"],- sources: {},+contextWindow: 204_800,supportsVision: false,},{modelId: "minimax-m2.5",aliases: ["MiniMax-M2.5", "minimax-m2-5"],- sources: {},+contextWindow: 204_800,supportsVision: false,},{modelId: "minimax-m1",aliases: [],- sources: {},+contextWindow: 1_000_000,supportsVision: false,},{modelId: "minimax-01",aliases: [],- sources: {},+contextWindow: 1_000_000,supportsVision: false,},{modelId: "grok-4",aliases: [],- sources: {},+contextWindow: 256_000,},{modelId: "gpt-5.6-sol",aliases: [],- sources: {},+contextWindow: 1_050_000,aggregators: [{- provider: "openai",- externalId: "gpt-5.6-sol",+ sourceCollectorId: "test",+ routeStatus: "mapped",+ route: catalogRouteForProvider("openai"),+ sourceProviderId: "openai",+ externalModelId: "gpt-5.6-sol",confidence: "api_official",contextWindow: 1_050_000,},{- provider: "openai-codex",- externalId: "gpt-5.6-sol",+ sourceCollectorId: "test",+ routeStatus: "mapped",+ route: catalogRouteForProvider("openai-codex"),+ sourceProviderId: "openai-codex",+ externalModelId: "gpt-5.6-sol",confidence: "api_official",contextWindow: 372_000,},{- provider: "openrouter",- externalId: "openai/gpt-5.6-sol",+ sourceCollectorId: "test",+ routeStatus: "mapped",+ route: catalogRouteForProvider("openrouter"),+ sourceProviderId: "openrouter",+ externalModelId: "openai/gpt-5.6-sol",confidence: "gateway_official",},],@@ -105,76 +115,76 @@ beforeAll(() => {{modelId: "grok-4-fast",aliases: ["x-ai/grok-4-fast"],- sources: {},+contextWindow: 2_000_000,},{modelId: "grok-3",aliases: [],- sources: {},+contextWindow: 131_072,},{modelId: "glm-5",aliases: [],- sources: {},+contextWindow: 204_800,supportsVision: true,},{modelId: "glm-4-long",aliases: [],- sources: {},+contextWindow: 1_000_000,},{modelId: "glm-4v",aliases: [],- sources: {},+contextWindow: 128_000,supportsVision: true,},{modelId: "glm-4-flash",aliases: [],- sources: {},+contextWindow: 128_000,supportsVision: false,},{modelId: "glm-5-turbo",aliases: [],- sources: {},+contextWindow: 202_752,},{modelId: "kimi-k3",aliases: ["moonshotai/kimi-k3", "k3"],- sources: {},- subscriptionPlans: ["kimi-coding", "opencode-zen-go"],++ subscriptionPlanIds: ["kimi-coding", "opencode-zen-go"],},{modelId: "kimi-k3-256k",aliases: [],- sources: {},+releaseDate: "2026-07-16",},{modelId: "kimi-k3-fast",aliases: [],- sources: {},},{modelId: "kimi-k2.6",aliases: [],- sources: {},},];writeFileSync(mockCachePath,JSON.stringify({- version: 2,+ catalogGenerationId: "test-generation",+ plans: [],+ version: 3,lastUpdated: new Date().toISOString(),entries,models: entries.map((e) => ({ id: e.modelId })),@@ -304,8 +314,8 @@ describe("searchCatalogModels", () => {const withPlans = searchCatalogModels("kimi-k3", 10, mockCachePath);const withoutPlans = searchCatalogModels("kimi-k3-fast", 10, mockCachePath);- expect(withPlans[0]?.subscriptionPlans).toEqual(["kimi-coding", "opencode-zen-go"]);- expect(withoutPlans[0]?.subscriptionPlans).toEqual([]);+ expect(withPlans[0]?.subscriptionPlanIds).toEqual(["kimi-coding", "opencode-zen-go"]);+ expect(withoutPlans[0]?.subscriptionPlanIds).toEqual([]);});test("matches model ids case-insensitively", () => {diff --git a/packages/cli/src/model-loader-v3.test.ts b/packages/cli/src/model-loader-v3.test.tsnew file mode 100644index 00000000..2a4d3fa4--- /dev/null+++ b/packages/cli/src/model-loader-v3.test.ts@@ -0,0 +1,60 @@+import { afterEach, describe, expect, mock, test } from "bun:test";+import { getModelsByProvider } from "./model-loader.js";+import { CATALOG_V3_ACCEPT } from "./providers/catalog-v3.js";++const realFetch = globalThis.fetch;+afterEach(() => {+ globalThis.fetch = realFetch;+});++const envelope = (+ models: Array<{ modelId: string }>,+ nextCursor?: string,+ generationId = "generation-a"+) =>+ Response.json({+ contractVersion: 3,+ generationId,+ generatedAt: "2026-09-19T01:33:46.169Z",+ data: { models, total: 3, ...(nextCursor ? { nextCursor } : {}) },+ });++describe("v3 provider-scoped pagination", () => {+ test("returns the complete provider roster from one generation", async () => {+ const requests: Array<{+ cursor: string | null;+ generation: string | null;+ accept: string | null;+ }> = [];+ globalThis.fetch = mock(async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = new URL(String(input));+ requests.push({+ cursor: url.searchParams.get("cursor"),+ generation: url.searchParams.get("generationId"),+ accept: new Headers(init?.headers).get("accept"),+ });+ return url.searchParams.has("cursor")+ ? envelope([{ modelId: "qwen3.8-max" }])+ : envelope([{ modelId: "qwen3.7-plus" }, { modelId: "qwen3.6-plus" }], "opaque-cursor");+ }) as unknown as typeof fetch;++ expect((await getModelsByProvider("qwen", 2)).map((model) => model.modelId)).toEqual([+ "qwen3.7-plus",+ "qwen3.6-plus",+ "qwen3.8-max",+ ]);+ expect(requests).toEqual([+ { cursor: null, generation: null, accept: CATALOG_V3_ACCEPT },+ { cursor: "opaque-cursor", generation: "generation-a", accept: CATALOG_V3_ACCEPT },+ ]);+ });++ test("rejects a later page from another generation", async () => {+ globalThis.fetch = mock(async (input: RequestInfo | URL) =>+ new URL(String(input)).searchParams.has("cursor")+ ? envelope([{ modelId: "qwen3.8-max" }], undefined, "generation-b")+ : envelope([{ modelId: "qwen3.7-plus" }, { modelId: "qwen3.6-plus" }], "opaque-cursor")+ ) as unknown as typeof fetch;+ await expect(getModelsByProvider("qwen", 2)).rejects.toThrow("generation changed");+ });+});diff --git a/packages/cli/src/model-loader.test.ts b/packages/cli/src/model-loader.test.tsindex 7de736ed..5f705b15 100644--- a/packages/cli/src/model-loader.test.ts+++ b/packages/cli/src/model-loader.test.ts@@ -1,10 +1,6 @@import { describe, expect, it } from "bun:test";-import type { RecommendedModelGroup, RecommendedModelsDoc } from "./model-loader.js";-import {- buildCatalogRoutingRules,- collectRoutingPrefixes,- formatListingPrice,-} from "./model-loader.js";+import type { RecommendedModelGroup } from "./model-loader.js";+import { collectRoutingPrefixes, formatListingPrice } from "./model-loader.js";const swe17Entry = {pricing: { input: "N/A", output: "N/A", average: "N/A" },@@ -323,79 +319,3 @@ describe("collectRoutingPrefixes", () => {expect(collided).toEqual([NATIVE_PREFIX, "aa", "bb"]);});});--describe("buildCatalogRoutingRules", () => {- it("uses routingProvider, command wire IDs, and declared tier", () => {- const base = {- id: "synth-live-route",- name: "Synthetic live route",- description: "synthetic fixture",- provider: "Synthetic",- category: "subscription",- priority: 1,- pricing: { input: "N/A", output: "N/A", average: "N/A" },- context: "N/A",- };- const doc = {- version: "2.1.0",- lastUpdated: "2026-09-02",- models: [- {- ...base,- subscription: {- prefix: "np",- plan: "Native plan",- planIds: ["commercial-native-plan"],- routingProvider: "native-provider",- tier: "native",- command: "np@native-wire-id",- },- subscriptions: [- {- prefix: "mp",- plan: "Metered route",- planIds: [],- routingProvider: "metered-provider",- tier: "metered",- command: "mp@metered/wire-id",- },- {- prefix: "np",- plan: "Native plan",- planIds: ["commercial-native-plan"],- routingProvider: "native-provider",- tier: "native",- command: "np@native-wire-id",- },- ],- },- ],- } as RecommendedModelsDoc;-- expect(buildCatalogRoutingRules(doc)).toEqual({- "synth-live-route": ["native-provider@native-wire-id", "metered-provider@metered/wire-id"],- });- });-- it("ignores legacy routes that do not declare routingProvider", () => {- const doc = {- version: "1",- lastUpdated: "2026-08-01",- models: [- {- id: "legacy-model",- name: "Legacy",- description: "legacy fixture",- provider: "Synthetic",- category: "subscription",- priority: 1,- pricing: { input: "N/A", output: "N/A", average: "N/A" },- context: "N/A",- subscription: { prefix: "old", plan: "Old", command: "old@legacy-model" },- },- ],- } as RecommendedModelsDoc;-- expect(buildCatalogRoutingRules(doc)).toEqual({});- });-});diff --git a/packages/cli/src/model-loader.ts b/packages/cli/src/model-loader.tsindex 6f0fbd56..dda7a619 100644--- a/packages/cli/src/model-loader.ts+++ b/packages/cli/src/model-loader.ts@@ -1,7 +1,16 @@import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";import { homedir } from "node:os";import { join } from "node:path";+import { readAllModelsCache } from "./providers/all-models-cache.js";+import { PROVIDER_TO_PREFIX } from "./providers/auto-route.js";import { FIREBASE_CACHE_TTL_HOURS } from "./providers/cache-ttl.js";+import { ensureCatalogReady } from "./providers/catalog-client.js";+import { providerForCatalogRoute } from "./providers/catalog-route-bindings.js";+import {+ CATALOG_V3_ACCEPT,+ type CatalogV3Envelope,+ parseCatalogV3Envelope,+} from "./providers/catalog-v3.js";import { compareByReleaseDateDesc } from "./providers/model-ordering.js";import type { OpenRouterModel } from "./types.js";@@ -41,23 +50,15 @@ export interface RecommendedModelEntry {recommended?: boolean;subscription?: RecommendedSubscriptionRoute;/**- * Every plan that serves this model, in the order the backend sent them.- * `subscription` above MIRRORS element 0 — measured across all 18 subscription- * rows of the live payload: mirrors=18, diverges=0 (research.md R1). It is not- * a curated primary, so the plural is the complete answer and the singular is- * the compatibility fallback, never an addition.- *- * `prefix` is OPTIONAL and genuinely absent: the four native Claude rows carry- * `{plan, command}` with no prefix, because their command is the bare model id- * (research.md R2). The singular above still declares it required; that type- * is already lying and is left alone here — see risk R-6.+ * Every executable subscription route for this model, in preference order.+ * Native Claude routes use a bare model command without a provider prefix.*/subscriptions?: RecommendedSubscriptionRoute[];}export type RecommendedRouteTier = "native" | "general" | "metered" | "aggregator";-/** Backend-declared callable route. New fields stay optional for old disk caches. */+/** A callable route projected from catalog v3 recommendations. */export interface RecommendedSubscriptionRoute {prefix?: string;plan: string;@@ -72,6 +73,8 @@ export interface RecommendedSubscriptionRoute {* Matches `RecommendedModelsDoc` in firebase/functions/src/schema.ts.*/export interface RecommendedModelsDoc {+ contractVersion?: 3;+ generationId?: string;version: string;lastUpdated: string;generatedAt?: string;@@ -111,9 +114,12 @@ export interface RouteReasoningCapabilities {* aggregators (OpenRouter, Fireworks, etc.) serve a given model.*/export interface AggregatorEntry {- provider: string;- externalId: string;+ sourceProviderId: string;+ sourceCollectorId: string;confidence: ConfidenceTier;+ routeStatus: "mapped" | "unmapped";+ route?: { routeId: string; routeProfileId: string };+ externalModelId?: string;/*** True per-aggregator price for this (provider, externalId), as served by the* `?catalog=slim` endpoint. Present when the catalog knows this vendor's rate,@@ -196,12 +202,12 @@ export interface ModelDoc {* IDs of subscription plans (e.g. "cognition-devin", "z-ai-glm-coding-plan")* that include this model.*- * NAME MATTERS: the backend sends `subscriptionPlans`. This field was declared+ * NAME MATTERS: the backend sends `subscriptionPlanIds`. This field was declared* as `availableInPlans` and read by nothing, so claudish was blind to it —* which is how a subscription-only model with no published per-token rate came* out as a bare "N/A" that reads as "unknown / not provisioned".*/- subscriptionPlans?: string[];+ subscriptionPlanIds?: string[];/*** Vendor's own prose explaining an ABSENT `pricing` — e.g. "Cognition does not* publish standalone token pricing" / "Z.ai says the standalone API is coming@@ -237,7 +243,7 @@ export interface ModelDoc {vendors?: VendorRecord[];}-// ─── Legacy ModelMetadata (used by --model flag resolution) ──────────────────+// ─── Model metadata for --model flag resolution ──────────────────────────────interface ModelMetadata {name: string;@@ -265,6 +271,122 @@ export const RECOMMENDED_MODELS_CACHE_PATH = join(const RECOMMENDED_FETCH_TIMEOUT_MS = 5000;const SEARCH_FETCH_TIMEOUT_MS = 10000;+async function fetchCatalogPage<T>(+ url: string,+ timeoutMs: number,+ generationId?: string+): Promise<CatalogV3Envelope<T>> {+ const requestUrl = new URL(url);+ if (generationId) requestUrl.searchParams.set("generationId", generationId);+ const response = await fetch(requestUrl, {+ headers: { Accept: CATALOG_V3_ACCEPT },+ signal: AbortSignal.timeout(timeoutMs),+ });+ if (!response.ok) throw new Error(`Model catalog returned HTTP ${response.status}`);+ const envelope = parseCatalogV3Envelope<T>(await response.json());+ if (!envelope) throw new Error("Model catalog returned an invalid v3 response");+ if (generationId && envelope.generationId !== generationId) {+ throw new Error("Model catalog generation changed during the read");+ }+ return envelope;+}++async function fetchCatalogData<T>(+ url: string,+ timeoutMs: number,+ generationId?: string+): Promise<T> {+ return (await fetchCatalogPage<T>(url, timeoutMs, generationId)).data;+}++function recommendationProjection(+ recommendations: {+ contractVersion: number;+ generationId: string;+ entries: Array<{+ modelId: string;+ tier: "flagship" | "lightweight" | "subscription";+ route?: { routeId: string; routeProfileId: string };+ planId?: string;+ }>;+ },+ richModels: ModelDoc[] = []+): RecommendedModelsDoc {+ if (recommendations.contractVersion !== 3 || !Array.isArray(recommendations.entries)) {+ throw new Error("Model catalog recommendations do not match v3");+ }+ const cache = readAllModelsCache();+ if (!cache || cache.catalogGenerationId !== recommendations.generationId) {+ throw new Error("Recommendation and model catalog generations differ");+ }+ const byId = new Map(cache?.entries.map((entry) => [entry.modelId, entry]) ?? []);+ const richById = new Map(richModels.map((model) => [model.modelId, model]));+ return {+ contractVersion: 3,+ generationId: recommendations.generationId,+ version: recommendations.generationId,+ lastUpdated: new Date().toISOString(),+ generatedAt: new Date().toISOString(),+ models: recommendations.entries.map((recommended, index) => {+ const model = byId.get(recommended.modelId);+ const rich = richById.get(recommended.modelId);+ const provider = recommended.route ? providerForCatalogRoute(recommended.route) : undefined;+ const connection = model?.aggregators?.find(+ (candidate) =>+ candidate.route?.routeId === recommended.route?.routeId &&+ candidate.route?.routeProfileId === recommended.route?.routeProfileId+ );+ const plan = cache?.plans.find((candidate) => candidate.id === recommended.planId);+ const prefix = provider ? (PROVIDER_TO_PREFIX[provider] ?? provider) : undefined;+ const command =+ prefix && connection?.externalModelId+ ? provider === "native-anthropic"+ ? connection.externalModelId+ : `${prefix}@${connection.externalModelId}`+ : undefined;+ const subscription =+ recommended.tier === "subscription" && provider && command+ ? {+ ...(provider === "native-anthropic" ? {} : { prefix }),+ plan: plan?.id ?? recommended.planId ?? provider,+ command,+ planIds: recommended.planId ? [recommended.planId] : [],+ routingProvider: provider,+ tier: provider === "native-anthropic" ? ("native" as const) : ("general" as const),+ }+ : undefined;+ return {+ id: recommended.modelId,+ name: rich?.displayName ?? model?.displayName ?? recommended.modelId,+ description: rich?.description ?? "",+ provider: rich?.provider ?? model?.provider ?? "",+ category:+ recommended.tier === "flagship"+ ? "programming"+ : recommended.tier === "lightweight"+ ? "fast"+ : "subscription",+ priority: index + 1,+ pricing: {+ input: typeof rich?.pricing?.input === "number" ? `$${rich.pricing.input}/1M` : "N/A",+ output: typeof rich?.pricing?.output === "number" ? `$${rich.pricing.output}/1M` : "N/A",+ average:+ typeof rich?.pricing?.input === "number" && typeof rich?.pricing?.output === "number"+ ? `$${((rich.pricing.input + rich.pricing.output) / 2).toFixed(2)}/1M`+ : "N/A",+ },+ context: rich?.contextWindow+ ? String(rich.contextWindow)+ : model?.contextWindow+ ? String(model.contextWindow)+ : "N/A",+ releaseDate: model?.releaseDate,+ ...(subscription ? { subscription, subscriptions: [subscription] } : {}),+ };+ }),+ };+}+// ─── Recommended models grouping + formatting helpers ───────────────────────/**@@ -452,74 +574,6 @@ function compareRecommendedRoutes(return leftRank - rightRank;}-/**- * Convert the live recommended contract into exact routing rules. Each route- * uses routingProvider (not the commercial plan ID) and the backend-confirmed- * command wire ID. Tier is the ordering authority; array position is only the- * stable tiebreak within one tier or for a legacy cached document.- *- * NO PRODUCTION CALLER as of v9.0.3. Its output was merged into the routing- * dictionary in v9.0.1, where its EXACT model-id keys made the default and user- * GLOB rules unreachable and deleted every provider it did not name — see the- * long note on `loadRoutingRules` in providers/routing-rules.ts. Kept exported- * and tested for the catalog-driven redesign; do not wire it back into routing- * rules.- *- * Note also what it reads: `subscriptions[]` on the RECOMMENDED-models document,- * which is a 34-model editorial list, not the serving graph. Plan-backed routes- * only — never a vendor's metered API, never OpenRouter.- */-export function buildCatalogRoutingRules(doc: RecommendedModelsDoc): Record<string, string[]> {- const routesByModel = new Map<- string,- Array<{ route: RecommendedSubscriptionRoute; sourceIndex: number }>- >();- let sourceIndex = 0;-- for (const entry of doc.models) {- const routes =- entry.subscriptions && entry.subscriptions.length > 0- ? entry.subscriptions- : entry.subscription- ? [entry.subscription]- : [];- for (const route of routes) {- routesByModel.set(entry.id, [...(routesByModel.get(entry.id) ?? []), { route, sourceIndex }]);- sourceIndex += 1;- }- }-- const rules: Record<string, string[]> = {};- for (const [modelId, candidates] of routesByModel) {- const seen = new Set<string>();- const entries = candidates- .filter(- ({ route }) =>- typeof route?.routingProvider === "string" &&- route.routingProvider.length > 0 &&- typeof route.command === "string" &&- route.command.length > 0- )- .sort(- (left, right) =>- compareRecommendedRoutes(left.route, right.route) || left.sourceIndex - right.sourceIndex- )- .map(({ route }) => {- const at = route.command.indexOf("@");- const wireId = at >= 0 ? route.command.slice(at + 1) : route.command;- return `${route.routingProvider}@${wireId}`;- })- .filter((entry) => {- if (seen.has(entry)) return false;- seen.add(entry);- return true;- });- if (entries.length > 0) rules[modelId] = entries;- }-- return rules;-}-/** Parse "$1.32/1M" → 1.32, "FREE" → 0, "N/A"/"varies"/undefined → Infinity */export function parsePriceAvg(s?: string): number {if (!s || s === "N/A") return Number.POSITIVE_INFINITY;@@ -666,10 +720,15 @@ export async function getRecommendedModels(opts: { forceRefresh?: boolean } = {}): Promise<RecommendedModelsDoc> {const { forceRefresh = false } = opts;+ const cached = _cachedRecommendedModels;// Tier 1: in-memory cache- if (!forceRefresh && _cachedRecommendedModels) {- return _cachedRecommendedModels;+ if (+ !forceRefresh &&+ cached &&+ cached.generationId === readAllModelsCache()?.catalogGenerationId+ ) {+ return cached;}// Tier 2: disk cache (if fresh)@@ -680,7 +739,13 @@ export async function getRecommendedModels(const cacheData = JSON.parse(readFileSync(RECOMMENDED_MODELS_CACHE_PATH, "utf-8")) as RecommendedModelsDoc;- if (cacheData.models && cacheData.models.length > 0 && isFreshEnough(cacheData)) {+ if (+ cacheData.contractVersion === 3 &&+ cacheData.generationId === readAllModelsCache()?.catalogGenerationId &&+ cacheData.models &&+ cacheData.models.length > 0 &&+ isFreshEnough(cacheData)+ ) {_cachedRecommendedModels = cacheData;return cacheData;}@@ -690,32 +755,42 @@ export async function getRecommendedModels(}// Tier 3: Firebase fetch+ let fetchFailure: unknown;try {- const response = await fetch(FIREBASE_RECOMMENDED_URL, {- signal: AbortSignal.timeout(RECOMMENDED_FETCH_TIMEOUT_MS),- });- if (response.ok) {- const data = (await response.json()) as RecommendedModelsDoc;- if (data.models && data.models.length > 0) {- _cachedRecommendedModels = data;- // Write disk cache (best-effort)- try {- const cacheDir = join(homedir(), ".claudish");- mkdirSync(cacheDir, { recursive: true });- writeFileSync(RECOMMENDED_MODELS_CACHE_PATH, JSON.stringify(data), "utf-8");- } catch {- // Don't fail the call if we can't write the cache- }- return data;+ await ensureCatalogReady(20000);+ const generationId = readAllModelsCache()?.catalogGenerationId;+ if (!generationId) throw new Error("No complete v3 model and plan snapshot");+ const response = await fetchCatalogData<{+ mode: "recommended";+ recommendations: Parameters<typeof recommendationProjection>[0];+ }>(FIREBASE_RECOMMENDED_URL, RECOMMENDED_FETCH_TIMEOUT_MS, generationId);+ if (response.mode !== "recommended") throw new Error("Unexpected recommendation mode");+ if (response.recommendations.generationId !== generationId) {+ throw new Error("Recommendation and model catalog generations differ");+ }+ const top100 = await fetchCatalogData<{ mode: "top100"; models: ModelDoc[] }>(+ `${FIREBASE_BASE_URL}?catalog=top100`,+ RECOMMENDED_FETCH_TIMEOUT_MS,+ generationId+ );+ const data = recommendationProjection(response.recommendations, top100.models);+ if (data.models.length > 0) {+ _cachedRecommendedModels = data;+ try {+ const cacheDir = join(homedir(), ".claudish");+ mkdirSync(cacheDir, { recursive: true });+ writeFileSync(RECOMMENDED_MODELS_CACHE_PATH, JSON.stringify(data), "utf-8");+ } catch {+ // A disk write failure does not invalidate the fetched result.}+ return data;}- } catch {- // Silent — fall through to the explicit error below+ } catch (error) {+ fetchFailure = error;}throw new Error(- "Unable to load recommended models: Firebase unreachable and no local cache. " +- "Check connectivity."+ `Unable to load v3 recommended models: ${fetchFailure instanceof Error ? fetchFailure.message : "empty recommendation projection"}`);}@@ -732,14 +807,22 @@ export async function getRecommendedModels(* flag help) handle empty data.*/export function getRecommendedModelsSync(): RecommendedModelsDoc {- if (_cachedRecommendedModels) return _cachedRecommendedModels;+ const generationId = readAllModelsCache()?.catalogGenerationId;+ const cached = _cachedRecommendedModels;+ if (cached && cached.generationId === generationId) return cached;if (existsSync(RECOMMENDED_MODELS_CACHE_PATH)) {try {const cacheData = JSON.parse(readFileSync(RECOMMENDED_MODELS_CACHE_PATH, "utf-8")) as RecommendedModelsDoc;- if (cacheData.models && cacheData.models.length > 0 && isFreshEnough(cacheData)) {+ if (+ cacheData.contractVersion === 3 &&+ cacheData.generationId === generationId &&+ cacheData.models &&+ cacheData.models.length > 0 &&+ isFreshEnough(cacheData)+ ) {_cachedRecommendedModels = cacheData;return cacheData;}@@ -752,7 +835,7 @@ export function getRecommendedModelsSync(): RecommendedModelsDoc {}/**- * Thin backward-compatible wrapper — fetches the Firebase catalog and warms caches.+ * Fetches the current recommendation projection — fetches the Firebase catalog and warms caches.* Used by proxy-server.ts to kick off the background warm on startup.*/export async function warmRecommendedModels(): Promise<RecommendedModelsDoc | null> {@@ -765,7 +848,7 @@ export async function warmRecommendedModels(): Promise<RecommendedModelsDoc | nufunction isFreshEnough(doc: RecommendedModelsDoc): boolean {const generatedAt = doc.generatedAt;- if (!generatedAt) return true; // No timestamp — treat as usable+ if (!generatedAt) return false;const ageHours = (Date.now() - new Date(generatedAt).getTime()) / (1000 * 60 * 60);return ageHours <= FIREBASE_CACHE_TTL_HOURS;}@@ -780,13 +863,10 @@ export async function searchModels(query: string, limit = 50): Promise<ModelDoc[const url = `${FIREBASE_BASE_URL}?search=${encodeURIComponent(query)}&limit=${limit}&status=active`;- const response = await fetch(url, {- signal: AbortSignal.timeout(SEARCH_FETCH_TIMEOUT_MS),- });- if (!response.ok) {- throw new Error(`Firebase search returned ${response.status} ${response.statusText}`);- }- const data = (await response.json()) as { models?: ModelDoc[]; total?: number };+ const data = await fetchCatalogData<{ models?: ModelDoc[]; total?: number }>(+ url,+ SEARCH_FETCH_TIMEOUT_MS+ );return data.models ?? [];}@@ -802,13 +882,10 @@ export async function searchModelsByProvider(const url = `${FIREBASE_BASE_URL}?provider=${encodeURIComponent(provider)}&search=${encodeURIComponent(query)}&limit=${limit}&status=active`;- const response = await fetch(url, {- signal: AbortSignal.timeout(SEARCH_FETCH_TIMEOUT_MS),- });- if (!response.ok) {- throw new Error(`Firebase provider search returned ${response.status} ${response.statusText}`);- }- const data = (await response.json()) as { models?: ModelDoc[]; total?: number };+ const data = await fetchCatalogData<{ models?: ModelDoc[]; total?: number }>(+ url,+ SEARCH_FETCH_TIMEOUT_MS+ );return data.models ?? [];}@@ -817,21 +894,12 @@ export async function searchModelsByProvider(* Returns null if not found, throws on network error.*/export async function getModelByIdFromFirebase(modelId: string): Promise<ModelDoc | null> {- const url = `${FIREBASE_BASE_URL}?search=${encodeURIComponent(modelId)}&limit=5`;- const response = await fetch(url, {- signal: AbortSignal.timeout(SEARCH_FETCH_TIMEOUT_MS),- });- if (!response.ok) {- throw new Error(`Firebase lookup returned ${response.status} ${response.statusText}`);- }- const data = (await response.json()) as { models?: ModelDoc[] };- const models = data.models ?? [];- // Exact match on modelId or aliases- for (const m of models) {- if (m.modelId === modelId) return m;- if (m.aliases?.includes(modelId)) return m;- }- return null;+ const url = `${FIREBASE_BASE_URL}?modelId=${encodeURIComponent(modelId)}`;+ const data = await fetchCatalogData<{ mode: "exact"; model: ModelDoc | null }>(+ url,+ SEARCH_FETCH_TIMEOUT_MS+ );+ return data.mode === "exact" ? data.model : null;}/**@@ -884,13 +952,7 @@ export interface Top100Response {*/export async function getTop100Models(): Promise<Top100Response> {const url = `${FIREBASE_BASE_URL}?catalog=top100`;- const response = await fetch(url, {- signal: AbortSignal.timeout(SEARCH_FETCH_TIMEOUT_MS),- });- if (!response.ok) {- throw new Error(`Firebase top100 fetch failed: ${response.status} ${response.statusText}`);- }- const data = (await response.json()) as Top100Response;+ const data = await fetchCatalogData<Top100Response>(url, SEARCH_FETCH_TIMEOUT_MS);return data;}@@ -910,35 +972,55 @@ export interface ProviderListEntry {*/export async function getProviderList(): Promise<ProviderListEntry[]> {const url = `${FIREBASE_BASE_URL}?catalog=providers`;- const response = await fetch(url, {- signal: AbortSignal.timeout(SEARCH_FETCH_TIMEOUT_MS),- });- if (!response.ok) {- throw new Error(`Firebase providers fetch failed: ${response.status} ${response.statusText}`);- }- const data = (await response.json()) as { providers?: ProviderListEntry[] };+ const data = await fetchCatalogData<{ providers?: ProviderListEntry[] }>(+ url,+ SEARCH_FETCH_TIMEOUT_MS+ );return data.providers ?? [];}-/**- * Fetch active models for a given provider.- */-export async function getModelsByProvider(provider: string, limit = 200): Promise<ModelDoc[]> {- const url = `${FIREBASE_BASE_URL}?provider=${encodeURIComponent(- provider- )}&status=active&limit=${limit}`;- const response = await fetch(url, {- signal: AbortSignal.timeout(SEARCH_FETCH_TIMEOUT_MS),- });- if (!response.ok) {- throw new Error(`Firebase provider query returned ${response.status} ${response.statusText}`);+/** Fetch every active model for a provider from one pinned generation. */+export async function getModelsByProvider(provider: string, pageSize = 200): Promise<ModelDoc[]> {+ const base = `${FIREBASE_BASE_URL}?provider=${encodeURIComponent(provider)}&status=active&limit=${pageSize}`;+ const models: ModelDoc[] = [];+ const seenCursors = new Set<string>();+ let cursor: string | undefined;+ let generationId: string | undefined;+ let expectedTotal: number | undefined;+ for (let page = 0; page < 40; page++) {+ const url = new URL(base);+ if (cursor) url.searchParams.set("cursor", cursor);+ const envelope = await fetchCatalogPage<{+ models: ModelDoc[];+ total: number;+ nextCursor?: string;+ }>(url.toString(), SEARCH_FETCH_TIMEOUT_MS, generationId);+ if (!Array.isArray(envelope.data.models) || !Number.isSafeInteger(envelope.data.total)) {+ throw new Error("Incomplete provider catalog response");+ }+ generationId = envelope.generationId;+ expectedTotal ??= envelope.data.total;+ if (envelope.data.total !== expectedTotal)+ throw new Error("Provider catalog total changed during pagination");+ models.push(...envelope.data.models);+ const nextCursor = envelope.data.nextCursor;+ if (!nextCursor) {+ if (+ models.length !== expectedTotal ||+ new Set(models.map((model) => model.modelId)).size !== models.length+ ) {+ throw new Error("Incomplete provider catalog snapshot");+ }+ return models;+ }+ if (seenCursors.has(nextCursor)) throw new Error("Provider catalog cursor repeated");+ seenCursors.add(nextCursor);+ cursor = nextCursor;}- const data = (await response.json()) as ModelDoc[] | { models?: ModelDoc[] };- if (Array.isArray(data)) return data;- return data.models ?? [];+ throw new Error("Provider catalog exceeded the pagination limit");}-// ─── Legacy loaders retained for cli.ts --model flag validation ──────────────+// ─── Model loaders for cli.ts --model flag validation ────────────────────────/*** Load ModelMetadata keyed by model ID for the --model flag help text.diff --git a/packages/cli/src/model-selector.test.ts b/packages/cli/src/model-selector.test.tsindex 10ab2598..5711954e 100644--- a/packages/cli/src/model-selector.test.ts+++ b/packages/cli/src/model-selector.test.ts@@ -1,3 +1,4 @@+import { catalogRouteForProvider } from "./providers/catalog-route-bindings.js";/*** Tests for the pure-logic helpers in `model-selector.ts`.*@@ -44,8 +45,8 @@ import { BUILTIN_PROVIDERS, getProviderByName } from "./providers/provider-defin// ─── buildExplicitModelSpec ──────────────────────────────────────────────────describe("warnDiscoveryFailure", () => {- const provider = "qwen-cloud";- const displayName = "Qwen Plan";+ const provider = "qwen-token-plan";+ const displayName = "Alibaba Token Plan";const def = getProviderByName(provider)!;const realFetch = globalThis.fetch;const realGetRequestAuth = credentials.getRequestAuth;@@ -138,10 +139,8 @@ describe("warnDiscoveryFailure", () => {const output = captureWarning();expect(output.stderr).toContain(displayName);- expect(output.stderr).toContain("QWEN_CLOUD_PLAN_API_KEY");- expect(output.stderr).toContain(- "https://www.alibabacloud.com/help/en/model-studio/claude-code"- );+ expect(output.stderr).toContain("QWEN_TOKEN_PLAN_API_KEY");+ expect(output.stderr).toContain("https://docs.qwencloud.com/token-plan/overview");expect(output.stderr).toContain("Falling back to manual model entry.");expect(output.stderrCalls).toBeGreaterThan(0);expect(output.stdout).toBe("");@@ -157,10 +156,8 @@ describe("warnDiscoveryFailure", () => {const output = captureWarning();expect(output.stderr).toContain(displayName);expect(output.stderr).toContain("Falling back to manual model entry.");- expect(output.stderr).not.toContain("QWEN_CLOUD_PLAN_API_KEY");- expect(output.stderr).not.toContain(- "https://www.alibabacloud.com/help/en/model-studio/claude-code"- );+ expect(output.stderr).not.toContain("QWEN_TOKEN_PLAN_API_KEY");+ expect(output.stderr).not.toContain("https://docs.qwencloud.com/token-plan/overview");expect(output.stderrCalls).toBeGreaterThan(0);expect(output.stdout).toBe("");expect(output.stdoutCalls).toBe(0);@@ -181,7 +178,7 @@ describe("buildExplicitModelSpec", () => {["minimax-coding", "MiniMax-M2", "mmc@MiniMax-M2"],["kimi", "kimi-k2", "kimi@kimi-k2"],["kimi-coding", "kimi-for-coding", "kc@kimi-for-coding"],- ["qwen-payg", "qwen3.7-plus", "[email protected]"],+ ["qwen-payg", "qwen3.7-plus", "[email protected]"],// antigravity renders google-catalog rows in the picker; without a prefix// entry, rows would emit a bare id that won't route to Antigravity.["antigravity", "gemini-3-pro", "ag@gemini-3-pro"],@@ -316,8 +313,11 @@ describe("picker provider roster", () => {provider: "Google",aggregators: [{- provider: "antigravity",- externalId: "gemini-3.1-pro-high",+ sourceCollectorId: "test",+ routeStatus: "mapped" as const,+ route: catalogRouteForProvider("antigravity"),+ sourceProviderId: "antigravity",+ externalModelId: "gemini-3.1-pro-high",confidence: "gateway_official",},],@@ -329,8 +329,11 @@ describe("picker provider roster", () => {provider: "Google",aggregators: [{- provider: "antigravity",- externalId: "gemini-3.1-pro-high",+ sourceCollectorId: "test",+ routeStatus: "mapped" as const,+ route: catalogRouteForProvider("antigravity"),+ sourceProviderId: "antigravity",+ externalModelId: "gemini-3.1-pro-high",confidence: "gateway_official",},],@@ -358,8 +361,11 @@ describe("picker provider roster", () => {provider: "Google",aggregators: [{- provider: "antigravity",- externalId: "gemini-3.1-flash",+ sourceCollectorId: "test",+ routeStatus: "mapped" as const,+ route: catalogRouteForProvider("antigravity"),+ sourceProviderId: "antigravity",+ externalModelId: "gemini-3.1-flash",confidence: "gateway_official",},],@@ -379,8 +385,11 @@ describe("picker provider roster", () => {provider: "Google",aggregators: [{- provider: "openrouter",- externalId: "google/gemini-3.1-pro-preview",+ sourceCollectorId: "test",+ routeStatus: "mapped" as const,+ route: catalogRouteForProvider("openrouter"),+ sourceProviderId: "openrouter",+ externalModelId: "google/gemini-3.1-pro-preview",confidence: "gateway_official",},],@@ -404,9 +413,30 @@ describe("resolveProviderExternalId", () => {description: "",provider: "OpenAI",aggregators: [- { provider: "openai", externalId: "gpt-5", confidence: "api_official" },- { provider: "openrouter", externalId: "openai/gpt-5", confidence: "gateway_official" },- { provider: "opencode-zen", externalId: "openai/gpt-5", confidence: "gateway_official" },+ {+ sourceCollectorId: "test",+ routeStatus: "mapped" as const,+ route: catalogRouteForProvider("openai"),+ sourceProviderId: "openai",+ externalModelId: "gpt-5",+ confidence: "api_official",+ },+ {+ sourceCollectorId: "test",+ routeStatus: "mapped" as const,+ route: catalogRouteForProvider("openrouter"),+ sourceProviderId: "openrouter",+ externalModelId: "openai/gpt-5",+ confidence: "gateway_official",+ },+ {+ sourceCollectorId: "test",+ routeStatus: "mapped" as const,+ route: catalogRouteForProvider("opencode-zen"),+ sourceProviderId: "opencode-zen",+ externalModelId: "openai/gpt-5",+ confidence: "gateway_official",+ },],};@@ -471,20 +501,29 @@ describe("resolveProviderDisplayPrice", () => {pricing: { input: "$1.25", output: "$10.00", average: "$5.63/1M" },aggregators: [{- provider: "openai",- externalId: "gpt-5",+ sourceCollectorId: "test",+ routeStatus: "mapped" as const,+ route: catalogRouteForProvider("openai"),+ sourceProviderId: "openai",+ externalModelId: "gpt-5",confidence: "api_official",pricing: { input: 1.25, output: 10 },},{- provider: "openrouter",- externalId: "openai/gpt-5",+ sourceCollectorId: "test",+ routeStatus: "mapped" as const,+ route: catalogRouteForProvider("openrouter"),+ sourceProviderId: "openrouter",+ externalModelId: "openai/gpt-5",confidence: "gateway_official",pricing: { input: 1.3, output: 10.5 }, // marked-up gateway rate},{- provider: "opencode-zen",- externalId: "openai/gpt-5",+ sourceCollectorId: "test",+ routeStatus: "mapped" as const,+ route: catalogRouteForProvider("opencode-zen"),+ sourceProviderId: "opencode-zen",+ externalModelId: "openai/gpt-5",confidence: "gateway_official",pricing: { input: 1.07, output: 8.5 }, // cheaper gateway rate},@@ -499,20 +538,29 @@ describe("resolveProviderDisplayPrice", () => {pricing: { input: "$1.25", output: "$10.00", average: "$5.63/1M" },aggregators: [{- provider: "openai",- externalId: "priced-model",+ sourceCollectorId: "test",+ routeStatus: "mapped" as const,+ route: catalogRouteForProvider("openai"),+ sourceProviderId: "openai",+ externalModelId: "priced-model",confidence: "api_official",pricing: { input: 1.25, output: 10 },},{- provider: "antigravity",- externalId: "priced-model",+ sourceCollectorId: "test",+ routeStatus: "mapped" as const,+ route: catalogRouteForProvider("antigravity"),+ sourceProviderId: "antigravity",+ externalModelId: "priced-model",confidence: "gateway_official",pricing: { input: 2, output: 12 },},{- provider: "sakana",- externalId: "priced-model",+ sourceCollectorId: "test",+ routeStatus: "mapped" as const,+ route: catalogRouteForProvider("sakana"),+ sourceProviderId: "sakana",+ externalModelId: "priced-model",confidence: "gateway_official",pricing: { input: 3, output: 13 },},@@ -530,9 +578,9 @@ describe("resolveProviderDisplayPrice", () => {expect(resolveProviderDisplayPrice("openai", pricedAcrossBillingModes)).toBe("$5.63/1M");});- test("keeps qwen-payg metered while qwen-cloud remains subscription-priced", () => {+ test("keeps qwen-payg metered while qwen-token-plan remains subscription-priced", () => {expect(isSubscriptionProvider("qwen-payg")).toBe(false);- expect(isSubscriptionProvider("qwen-cloud")).toBe(true);+ expect(isSubscriptionProvider("qwen-token-plan")).toBe(true);expect(resolveProviderDisplayPrice("qwen-payg", pricedAcrossBillingModes)).toBe("$5.63/1M");expect(resolveProviderDisplayPrice("qwen-payg", pricedAcrossBillingModes)).not.toBe("SUB");});@@ -578,7 +626,14 @@ describe("resolveProviderDisplayPrice", () => {pricing: { input: "$1.00", output: "$2.00", average: "$1.50/1M" },aggregators: [// openrouter entry exists but carries NO pricing → fall back to model.pricing- { provider: "openrouter", externalId: "x/m", confidence: "gateway_official" },+ {+ sourceCollectorId: "test",+ routeStatus: "mapped" as const,+ route: catalogRouteForProvider("openrouter"),+ sourceProviderId: "openrouter",+ externalModelId: "x/m",+ confidence: "gateway_official",+ },],};expect(resolveProviderDisplayPrice("openrouter", noEntryPrice)).toBe("$1.50/1M");@@ -590,7 +645,16 @@ describe("resolveProviderDisplayPrice", () => {name: "m",description: "",provider: "OpenAI",- aggregators: [{ provider: "openrouter", externalId: "x/m", confidence: "gateway_official" }],+ aggregators: [+ {+ sourceCollectorId: "test",+ routeStatus: "mapped" as const,+ route: catalogRouteForProvider("openrouter"),+ sourceProviderId: "openrouter",+ externalModelId: "x/m",+ confidence: "gateway_official",+ },+ ],};expect(resolveProviderDisplayPrice("openrouter", noPrice)).toBe("N/A");});@@ -606,22 +670,30 @@ describe("CatalogClient integration for the original Zen bug", () => {// aggregators[].provider. This test verifies the data plumbing is intact// independent of the inquirer widgets.const fakeReadSlimCache = mock(() => ({- version: 2 as const,+ version: 3 as const,+ catalogGenerationId: "test-generation",+ plans: [],lastUpdated: new Date().toISOString(),entries: [{modelId: "claude-opus-4-7",aliases: [],- sources: {},+aggregators: [{- provider: "anthropic",- externalId: "claude-opus-4-7",+ sourceCollectorId: "test",+ routeStatus: "mapped" as const,+ route: catalogRouteForProvider("anthropic"),+ sourceProviderId: "anthropic",+ externalModelId: "claude-opus-4-7",confidence: "api_official" as const,},{- provider: "opencode-zen",- externalId: "anthropic/claude-opus-4-7",+ sourceCollectorId: "test",+ routeStatus: "mapped" as const,+ route: catalogRouteForProvider("opencode-zen"),+ sourceProviderId: "opencode-zen",+ externalModelId: "anthropic/claude-opus-4-7",confidence: "gateway_official" as const,},],@@ -629,12 +701,22 @@ describe("CatalogClient integration for the original Zen bug", () => {{modelId: "gpt-5",aliases: [],- sources: {},+aggregators: [- { provider: "openai", externalId: "gpt-5", confidence: "api_official" as const },{- provider: "opencode-zen",- externalId: "openai/gpt-5",+ sourceCollectorId: "test",+ routeStatus: "mapped" as const,+ route: catalogRouteForProvider("openai"),+ sourceProviderId: "openai",+ externalModelId: "gpt-5",+ confidence: "api_official" as const,+ },+ {+ sourceCollectorId: "test",+ routeStatus: "mapped" as const,+ route: catalogRouteForProvider("opencode-zen"),+ sourceProviderId: "opencode-zen",+ externalModelId: "openai/gpt-5",confidence: "gateway_official" as const,},],@@ -642,9 +724,16 @@ describe("CatalogClient integration for the original Zen bug", () => {{modelId: "grok-4",aliases: [],- sources: {},+aggregators: [- { provider: "x-ai", externalId: "grok-4", confidence: "api_official" as const },+ {+ sourceCollectorId: "test",+ routeStatus: "mapped" as const,+ route: catalogRouteForProvider("x-ai"),+ sourceProviderId: "x-ai",+ externalModelId: "grok-4",+ confidence: "api_official" as const,+ },],},],diff --git a/packages/cli/src/model-selector.ts b/packages/cli/src/model-selector.tsindex bfcc5eda..291d5f13 100644--- a/packages/cli/src/model-selector.ts+++ b/packages/cli/src/model-selector.ts@@ -1,3 +1,4 @@+import { catalogRouteMatchesProvider } from "./providers/catalog-route-bindings.js";/*** Model Selector with Fuzzy Search*@@ -120,7 +121,7 @@ export const pickerProviderToFirebaseSlug: Record<string, string> = {"opencode-zen": "opencode-zen","opencode-zen-go": "opencode-zen-go",ollamacloud: "ollamacloud",- // NOTE: "qwen-cloud" is deliberately absent. `selectModelFromProvider` tries+ // NOTE: "qwen-token-plan" is deliberately absent. `selectModelFromProvider` tries// `modelDiscovery` BEFORE this map, and the plan's /compatible-mode/v1/models// endpoint is authenticated — it answers with exactly what the subscription// is entitled to. The catalog's "qwen" vendor would be a bad fall-through@@ -128,7 +129,7 @@ export const pickerProviderToFirebaseSlug: Record<string, string> = {// plan host does not serve. Adding it would also poison// `firebaseSlugToProviderName`, whose reverse lookup takes the FIRST picker// value for a slug — with no canonical `qwen` entry above it, every plain- // catalog Qwen model would render as "Qwen Plan". Discovery failure+ // catalog Qwen model would render as "Alibaba Token Plan". Discovery failure// already degrades to the free-text prompt below, which is the right answer.};@@ -360,7 +361,8 @@ function catalogModelToModelInfo(model: CatalogModel): ModelInfo {// Catalog models from the slim cache don't carry the owner provider — fall// back to the first aggregator's name so the picker still shows something// useful in the column.- const ownerOrFirstAggregator = model.provider || model.aggregators?.[0]?.provider || "unknown";+ const ownerOrFirstAggregator =+ model.provider || model.aggregators?.[0]?.sourceProviderId || "unknown";const providerLabel = formatFirebaseProviderLabel(ownerOrFirstAggregator);const contextLength = model.contextWindow || 0;@@ -860,8 +862,12 @@ const PICKER_COPY: Record<string, { name?: string; description?: string }> = {"minimax-coding": { name: "MiniMax Coding", description: "Coding subscription" },kimi: { name: "Kimi / Moonshot", description: "Direct API" },"kimi-coding": { name: "Kimi Coding", description: "Coding subscription" },- "qwen-cloud": { name: "Qwen Plan", description: "Alibaba Model Studio subscription" },- "qwen-payg": { name: "Qwen API", description: "Alibaba Model Studio pay-as-you-go" },+ "qwen-token-plan": {+ name: "Alibaba Token Plan",+ description: "Model Studio subscription credits",+ },+ "qwen-coding": { name: "Alibaba Coding Plan", description: "Model Studio subscription requests" },+ "qwen-payg": { name: "Alibaba PAYG", description: "Model Studio pay-as-you-go tokens" },glm: { name: "GLM / Zhipu", description: "Direct API" },"glm-coding": { name: "GLM Coding Plan", description: "Coding subscription" },"z-ai": { name: "Z.AI", description: "Direct API" },@@ -896,7 +902,8 @@ const PICKER_ORDER = ["minimax-coding","kimi","kimi-coding",- "qwen-cloud",+ "qwen-token-plan",+ "qwen-coding","qwen-payg","glm","glm-coding",@@ -1101,7 +1108,7 @@ export function buildExplicitModelSpec(provider: string, modelId: string): strin*/export function resolveProviderExternalId(provider: string, model: ModelInfo): string {const match = resolveProviderAggregatorEntry(provider, model);- if (match?.externalId) return match.externalId;+ if (match?.externalModelId) return match.externalModelId;return model.id;}@@ -1119,9 +1126,10 @@ function resolveProviderAggregatorEntry(// actually holds. Without this, removing an alias silently degrades the row// to the catalog id — `[email protected]` instead of the wire id// `kc@kimi-for-coding` — and drops the per-aggregator price with it.- const firebaseSlug = pickerProviderToFirebaseSlug[provider] ?? provider;if (!model.aggregators) return undefined;- return model.aggregators.find((a) => a.provider.toLowerCase() === firebaseSlug.toLowerCase());+ return model.aggregators.find(+ (a) => a.routeStatus === "mapped" && catalogRouteMatchesProvider(a.route, provider)+ );}/**diff --git a/packages/cli/src/providers/all-models-cache.test.ts b/packages/cli/src/providers/all-models-cache.test.tsindex 809813b0..754650a6 100644--- a/packages/cli/src/providers/all-models-cache.test.ts+++ b/packages/cli/src/providers/all-models-cache.test.ts@@ -1,210 +1,62 @@-/**- * Tests for the shared ~/.claudish/all-models.json cache helpers.- *- * Each test uses a unique tmp path via `node:os.tmpdir()` to isolate state.- *- * Run: bun test packages/cli/src/providers/all-models-cache.test.ts- */-import { afterEach, describe, expect, test } from "bun:test";import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import {- type DiskCacheV2,+ type DiskCacheV3,type SlimModelEntry,readAllModelsCache,reasoningStatusOf,writeAllModelsCache,} from "./all-models-cache.js";-/**- * Create a unique tmp directory for a single test. Returns (path, cleanup).- * The path points at a file inside a fresh tmp dir — callers can pass it- * as the optional path argument to readAllModelsCache/writeAllModelsCache.- */-function makeTmpCachePath(): { path: string; dir: string; cleanup: () => void } {- const dir = mkdtempSync(join(tmpdir(), "claudish-cache-test-"));- const path = join(dir, "all-models.json");- return {- path,- dir,- cleanup: () => {- try {- rmSync(dir, { recursive: true, force: true });- } catch {- // best effort- }- },- };+const dirs: string[] = [];+function cachePath(): string {+ const dir = mkdtempSync(join(tmpdir(), "claudish-cache-v3-"));+ dirs.push(dir);+ return join(dir, "nested", "all-models.json");}--const cleanups: Array<() => void> = [];afterEach(() => {- while (cleanups.length > 0) {- const c = cleanups.pop();- c?.();- }+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });});-const sampleEntry = (modelId: string, externalId: string): SlimModelEntry => ({+const sampleEntry = (modelId: string, _externalId: string): SlimModelEntry => ({modelId,aliases: [],- sources: { "openrouter-api": { externalId } },});-describe("all-models-cache helpers", () => {- test("reads v1 file and normalizes to v2", () => {- const { path, cleanup } = makeTmpCachePath();- cleanups.push(cleanup);-- const v1Payload = {- lastUpdated: "2026-01-01T00:00:00.000Z",- models: [{ id: "openai/gpt-4" }, { id: "anthropic/claude-3" }],- };- writeFileSync(path, JSON.stringify(v1Payload), "utf-8");-- const result = readAllModelsCache(path);- expect(result).not.toBeNull();- expect(result!.version).toBe(2);- expect(result!.lastUpdated).toBe("2026-01-01T00:00:00.000Z");- expect(result!.entries).toEqual([]);- expect(result!.models).toEqual([{ id: "openai/gpt-4" }, { id: "anthropic/claude-3" }]);- });-- test("reads v2 file unchanged", () => {- const { path, cleanup } = makeTmpCachePath();- cleanups.push(cleanup);-- const v2Payload: DiskCacheV2 = {- version: 2,- lastUpdated: "2026-02-02T12:00:00.000Z",- entries: [- sampleEntry("grok-4", "x-ai/grok-4"),- sampleEntry("claude-3", "anthropic/claude-3"),- ],- models: [{ id: "x-ai/grok-4" }, { id: "anthropic/claude-3" }],- };- writeFileSync(path, JSON.stringify(v2Payload), "utf-8");-- const result = readAllModelsCache(path);- expect(result).toEqual(v2Payload);- });-- test("writer preserves existing entries when new data has no entries", () => {- const { path, cleanup } = makeTmpCachePath();- cleanups.push(cleanup);-- // Seed with v2 data containing rich entries- const seed: DiskCacheV2 = {- version: 2,- lastUpdated: "2026-03-03T00:00:00.000Z",- entries: [- sampleEntry("firebase-model", "vendor/firebase-model"),- sampleEntry("other-model", "vendor/other-model"),- ],- models: [{ id: "vendor/firebase-model" }, { id: "vendor/other-model" }],- };- writeFileSync(path, JSON.stringify(seed), "utf-8");-- // Legacy writer style: only supplies models- const legacyModels = [{ id: "openai/gpt-4" }, { id: "anthropic/claude-3" }];- writeAllModelsCache({ models: legacyModels }, path);-- const result = readAllModelsCache(path);- expect(result).not.toBeNull();- // Critical: entries must still be present after legacy write- expect(result!.entries).toHaveLength(2);- expect(result!.entries).toEqual(seed.entries);- // Models were overwritten by the legacy write- expect(result!.models).toEqual(legacyModels);- });-- test("writer merges when new data has entries", () => {- const { path, cleanup } = makeTmpCachePath();- cleanups.push(cleanup);-- // Seed with partial data- const seed: DiskCacheV2 = {- version: 2,- lastUpdated: "2026-04-04T00:00:00.000Z",- entries: [sampleEntry("old-model", "vendor/old-model")],- models: [{ id: "vendor/old-model" }],- };- writeFileSync(path, JSON.stringify(seed), "utf-8");-- // OpenRouter-style write: supplies fresh entries AND models- const newEntries = [- sampleEntry("grok-4", "x-ai/grok-4"),- sampleEntry("claude-3", "anthropic/claude-3"),- ];- const newModels = [{ id: "x-ai/grok-4" }, { id: "anthropic/claude-3" }];- writeAllModelsCache({ entries: newEntries, models: newModels }, path);-- const result = readAllModelsCache(path);- expect(result).not.toBeNull();- // New entries replace the old ones wholesale (this is the full refresh path)- expect(result!.entries).toEqual(newEntries);- expect(result!.models).toEqual(newModels);- });-- test("stores queryPlans routing and preserves it across a model-only refresh", () => {- const { path, cleanup } = makeTmpCachePath();- cleanups.push(cleanup);- const plans = [- {- id: "commercial-plan",- modelDiscovery: "catalog" as const,- routing: { providerUid: "subscription-provider", nativeModelProviders: [] },- },- ];-- writeAllModelsCache(- {- entries: [sampleEntry("model-one", "vendor/model-one")],- models: [],- plans,- },- path- );- writeAllModelsCache(- {- entries: [sampleEntry("model-two", "vendor/model-two")],- models: [],- },- path- );+function snapshot(entries: SlimModelEntry[], generation: string): DiskCacheV3 {+ return {+ version: 3,+ lastUpdated: "2026-09-19T01:33:46.169Z",+ catalogGenerationId: generation,+ entries,+ models: [],+ plans: [],+ };+}- expect(readAllModelsCache(path)?.plans).toEqual(plans);+describe("all-models-cache v3", () => {+ test("rejects a cache without the current contract or complete snapshot", () => {+ const path = cachePath();+ expect(readAllModelsCache(path)).toBeNull();+ writeAllModelsCache(snapshot([], "generation-a"), path);+ const partial = { version: 3, entries: [], models: [], plans: [] };+ writeFileSync(path, JSON.stringify(partial));+ expect(readAllModelsCache(path)).toBeNull();+ writeFileSync(path, JSON.stringify({ ...snapshot([], "generation-a"), version: 2 }));+ expect(readAllModelsCache(path)).toBeNull();});- test("writer creates parent directory if missing", () => {- // Use a path inside a nested dir that doesn't exist yet- const base = mkdtempSync(join(tmpdir(), "claudish-cache-test-"));- const nestedDir = join(base, "nested", "cache", "dir");- const path = join(nestedDir, "all-models.json");- cleanups.push(() => {- try {- rmSync(base, { recursive: true, force: true });- } catch {- // best effort- }- });-- expect(existsSync(nestedDir)).toBe(false);-- writeAllModelsCache(- {- models: [{ id: "openai/gpt-4" }],- },- path- );-+ test("writes one complete generation without merging earlier rows", () => {+ const path = cachePath();+ const first = snapshot([sampleEntry("model-one", "model-one")], "generation-a");+ const second = snapshot([sampleEntry("model-two", "model-two")], "generation-b");+ writeAllModelsCache(first, path);expect(existsSync(path)).toBe(true);- const result = readAllModelsCache(path);- expect(result).not.toBeNull();- expect(result!.models).toEqual([{ id: "openai/gpt-4" }]);- expect(result!.entries).toEqual([]);+ expect(readAllModelsCache(path)).toEqual(first);+ writeAllModelsCache(second, path);+ expect(readAllModelsCache(path)).toEqual(second);});});@@ -228,16 +80,16 @@ describe("reasoningStatusOf", () => {).toBe("known");});- test("infers only from a self-describing reasoning record in older caches", () => {+ test("infers known only from a self-describing reasoning record", () => {expect(reasoningStatusOf({- ...sampleEntry("legacy-described", "future-labs/legacy-described"),+ ...sampleEntry("reasoning-described", "future-labs/reasoning-described"),reasoning: { supported: true, control: "toggle" },})).toBe("known");expect(reasoningStatusOf({- ...sampleEntry("legacy-undescribed", "future-labs/legacy-undescribed"),+ ...sampleEntry("reasoning-undescribed", "future-labs/reasoning-undescribed"),supportsThinking: true,})).toBe("unknown");diff --git a/packages/cli/src/providers/all-models-cache.ts b/packages/cli/src/providers/all-models-cache.tsindex 2ee76d4d..09e37d00 100644--- a/packages/cli/src/providers/all-models-cache.ts+++ b/packages/cli/src/providers/all-models-cache.ts@@ -1,228 +1,57 @@-/**- * Shared helpers for ~/.claudish/all-models.json- *- * This file is written and read by four independent consumers:- * - providers/catalog-resolvers/openrouter.ts (v2 authoritative — Firebase slim catalog)- * - cli.ts (fetchRemoteModels + printAllModels)- * - mcp-server.ts (loadAllModels)- * - model-selector.ts (fetchAllModels + shouldRefreshForFreeModels)- *- * Historically each consumer wrote its own v1-shape `{lastUpdated, models}` blob,- * clobbering the v2 `entries` array that the OpenRouter catalog resolver relies on.- *- * This module provides a single normalized v2 read/write API:- * - `readAllModelsCache()` returns a v2 shape (normalizing v1 files on the fly)- * - `writeAllModelsCache(partial)` merges with the existing file so callers that- * only supply `models` do NOT destroy the Firebase `entries` catalog.- */-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.- * Contains model name resolution data plus optional model metadata.- *- * The slim catalog includes `aggregators` per entry — verified live against- * `?catalog=slim` (see `models-index/functions/src/query-handler.ts:267-269`).- * This is the multi-aggregator routing index used by `CatalogClient` to- * answer "which vendors serve model X?" without a Firebase round-trip.- */-/**- * How a model exposes its reasoning depth, as reported by the slim catalog.- *- * - `toggle` — reasoning is on/off only; there is no depth parameter.- * - `effort` — a discrete level from the model's own `efforts` list.- * - `adaptive` — the model chooses; a level may optionally be suggested.- * - `budget` — a token budget (`budget_tokens`).- * - `none` — the model exposes no knob. The catalog pairs it with- * `supported: false`, and `query-handler.ts` also uses it as the default for- * an entry that carries no `reasoning` block at all, so it is the single- * commonest value on the wire rather than an edge case.- *- * Kept as a string union of what Firebase currently emits, but consumers must- * treat an unrecognized value as "no information" rather than an error —- * the catalog is external data and may grow new kinds.- *- * `none` was missing here until 2026-09-15 while the backend had always sent- * it (`models-index/functions/src/schema.ts:105` declares the same five, and- * `schema-runtime.ts:610` validates against them). Nothing failed at runtime,- * because every consumer tests for the value it wants — `control === "effort"`,- * `control === "budget"` — so an unlisted member falls through to the right- * answer. It failed at the type level instead: a test fixture could not write- * the value the live catalog returns, which is how the gap surfaced.- */export type ReasoningControl = "toggle" | "effort" | "adaptive" | "budget" | "none";-/**- * Per-model reasoning capability from the Firebase slim catalog.- *- * This is the ONLY sanctioned source for "does this model take an effort- * level / a token budget / just an on-switch?". Hardcoding that per model is- * exactly the data that goes stale (a `control: "toggle"` model handed a- * `budget_tokens` is being sent a parameter it does not expose).- */export interface ReasoningCapability {- /** Whether the model can reason at all. */supported: boolean;- /** Which knob the model exposes. Absent = unknown. */control?: ReasoningControl;- /** Whether reasoning cannot be turned off. */mandatory?: boolean;- /** The discrete levels this model advertises (catalog vocabulary). */efforts?: string[];- /** The level the provider applies when none is requested. */defaultEffort?: string;- /** Whether an explicit `budget_tokens` is accepted. */supportsBudgetTokens?: boolean;}-/**- * How a provider-preset variant relates to its base model.- *- * The catalog lists a preset variant (e.g. `gemini-3.6-flash-high`) as its own- * top-level model, and `routeVariant` is the back-pointer: which family it- * belongs to, which base model it presets, and whether it is that family's- * default. `isDefault` is the authoritative answer to "if the user names the- * family, which variant should we send?" — a fact the client cannot derive,- * because the variant suffix is provider vocabulary, not a version number.- */export interface RouteVariant {- /** Discriminator, e.g. `provider-preset`. Treat unknown kinds as no info. */kind: string;- /** The catalog model this variant presets (e.g. `gemini-3.6-flash`). */baseModelId?: string;- /** The family a user would name (e.g. `gemini-3.1-pro`). */familyId?: string;- /** The serving provider this variant exists on (e.g. `antigravity`). */provider?: string;- /** Provider vocabulary for the preset (e.g. `reasoning-tier=high`). */preset?: string;- /** Whether this variant is the family's default on that provider. */isDefault?: boolean;}-/**- * Which wire API a model is reachable on, keyed by transport family.- *- * `api` names the concrete endpoint shape (`chat-completions` / `responses` /- * `anthropic-messages` / `gemini`), and `toolsWithReasoning` records whether- * tools and reasoning can be combined on it — `requires-responses` means the- * Chat Completions path cannot carry both.- */export interface ModelEndpoint {api?: string;toolsWithReasoning?: string;}export interface SlimModelEntry {+ contractVersion?: 3;modelId: string;+ displayName?: string;+ provider?: string;aliases: string[];- sources: Record<string, { externalId: string }>;- /** Official/curated release date in ISO date format, when Firebase has one */+ status?: string;releaseDate?: string;- /** Context window in tokens (present when Firebase has it) */contextWindow?: number;- /**- * The model's own output ceiling, when the catalog publishes one.- *- * ABSENT MEANS UNKNOWN, never zero. The slim projection omits the field- * entirely when it has no value, and it does NOT carry the- * `maxOutputTokensNotApplicable` flag that the fuller projections use — so- * "no number here" cannot be told apart from "the concept does not apply to- * this model", and both must be treated as "we do not know".- *- * A reasoning budget is clamped against the REQUEST's ceiling rather than- * this one (`max_tokens` is what the provider validates against), so this- * value informs reporting, not request shaping.- */maxOutputTokens?: number;- /**- * Whether the catalog KNOWS this model's reasoning control.- *- * `"known"` — the `reasoning` record below describes the real wire control.- * `"unknown"` — the source never described it. This is NOT the same as an- * explicit unsupported record (`reasoning.supported === false`), and the two- * demand opposite behaviour: unsupported means "switch reasoning off",- * unknown means "emit no reasoning knob at all and change nothing".- *- * Absent on caches written before the field existed. Treat absent as- * `"known"` only when a `reasoning` record is present — see- * {@link reasoningStatusOf}, which is the single place that rule lives.- *- * Do NOT derive a control from {@link supportsThinking} when this is- * `"unknown"`. The backend sets `reasoningStatus: "unknown"` while still- * publishing `supportsThinking` from coarse capability data, so the flag is- * present precisely in the case where it proves nothing about the knob.- */reasoningStatus?: "known" | "unknown";- /**- * Reasoning capability (present when Firebase has it). Already carried by the- * on-disk `?catalog=slim` payload; the type previously dropped it, so every- * consumer had to guess a model's reasoning knob instead of reading it.- */reasoning?: ReasoningCapability;- /** Whether model supports vision/image input (present when Firebase has it) */supportsVision?: boolean;- /**- * Multi-aggregator routing index. Each entry is `{provider, externalId, confidence}`.- * Populated by Firebase ingest from per-source data. Optional — older cache- * files may not include this field.- */- aggregators?: AggregatorEntry[];- /**- * Subscription plan ids that include this model (e.g. `["kimi-code"]`).- * Populated by Firebase ingest. Used by routing to decide whether a- * subscription endpoint can serve a given model at all — a plan that doesn't- * list the model would reject it, so the candidate is dropped rather than- * silently substituted. Optional — older cache files may not include it.- */- subscriptionPlans?: string[];- /**- * Whether the model accepts tool/function definitions. Shipped by the catalog- * for ~97% of models.- */supportsTools?: boolean;- /**- * Whether the model can produce thinking/reasoning content at all. Coarser- * than {@link ReasoningCapability} (which describes the KNOB); this is the- * plain yes/no.- */supportsThinking?: boolean;- /**- * The name of the output-token parameter this model's API expects —- * `max_tokens`, `max_completion_tokens`, or `max_output_tokens`.- *- * This exists because the correct parameter is NOT derivable from the model- * name. Guessing it from a version substring (`gpt-5` → max_completion_tokens)- * is wrong for the gpt-5.6-* family, which takes `max_output_tokens`, and- * breaks silently for every model released after the guess was written.- */+ videoInput?: boolean;+ videoOutput?: boolean;+ aggregators?: AggregatorEntry[];+ subscriptionPlanIds?: string[];tokenParam?: string;- /** Preset-variant back-pointer — see {@link RouteVariant}. */routeVariant?: RouteVariant;- /** Wire APIs this model is reachable on, keyed by transport family. */endpoints?: Record<string, ModelEndpoint>;}-/**- * Whether this entry's reasoning control is KNOWN, for entries written by any- * catalog version.- *- * The backend always sends `reasoningStatus` now, so the live path is a plain- * read. The inference below exists only for a cache written before the field- * shipped, and it is deliberately conservative: a `reasoning` record is- * self-describing, so its presence means known; its absence on an old cache is- * indistinguishable from "never described", so it reads unknown.- *- * That inference matches what the backend itself does- * (`reasoningStatus: reasoning !== undefined ? "known" : "unknown"`), so an old- * cache degrades to the same answer a fresh one would give rather than to a- * guess of its own.- */export function reasoningStatusOf(entry: SlimModelEntry): "known" | "unknown" {if (entry.reasoningStatus === "known" || entry.reasoningStatus === "unknown") {return entry.reasoningStatus;@@ -230,122 +59,87 @@ export function reasoningStatusOf(entry: SlimModelEntry): "known" | "unknown" {return entry.reasoning !== undefined ? "known" : "unknown";}-/**- * How one exact plan roster id resolves to a canonical catalog description.- *- * The KEY this is stored under is the wire id the provider expects for- * inference; `modelId` is the canonical id that carries the metadata. They are- * frequently different (`claude-opus-4-5-20251101` is the wire id, the row is- * stored undated), and conflating them is the whole point of the map: resolve- * metadata through `modelId`, keep sending the key.- *- * `missing` and `ambiguous` are explicit negative answers, not absence. They- * say the catalog looked and could not resolve the id, which is information —- * it must not be read as "this model has no reasoning" or as grounds to drop a- * subscription route.- */-export type CatalogPlanModelDescription =- | { status: "described"; modelId: string }- | { status: "missing" | "ambiguous" };-export type SubscriptionModelDiscovery = "catalog" | "client" | "hybrid";-/** Minimal queryPlans projection needed by the synchronous routing engine. */+export interface CachedPlanInclusion {+ kind: string;+ sourceText?: string;+ provider?: string;+ externalModelId?: string;+ resolution?: { status: "mapped"; modelId: string } | { status: "missing" | "ambiguous" };+}+export interface CachedSubscriptionPlan {- /** Canonical commercial plan ID referenced by SlimModelEntry.subscriptionPlans. */+ contractVersion?: 3;id: string;- /**- * The VENDOR selling the plan (`alibaba`, `z-ai`, `moonshotai`) — not a- * routing identity. Several plans can share one vendor while only some carry a- * `routing` block, which is exactly what `resolveSubscriptionRouting` needs it- * for: to notice that its view of a vendor's plans is incomplete and withhold- * a `not-served` verdict. Do not use it to route; use `routing.providerUid`.- */provider?: string;- /** Where the exact callable roster comes from. */modelDiscovery?: SubscriptionModelDiscovery;- /** Consumer routing identity; absent when the catalog has no supported route. */- routing?: {- providerUid: string;- prefix?: string;- nativeModelProviders?: string[];- };- /**- * Exact plan roster id → canonical catalog description.- *- * Published for routed catalog/hybrid plans. Absent on `client`-discovery- * plans, whose `includedModels` are display labels rather than wire ids, and- * absent on caches written before the field shipped — in both cases callers- * fall back to matching the id directly against the catalog.- */- modelDescriptions?: Record<string, CatalogPlanModelDescription>;+ routeStatus: "supported" | "unsupported" | "unknown";+ route?: { routeId: string; routeProfileId: string };+ routeReason?: string;+ inclusions?: CachedPlanInclusion[];}-/**- * Disk cache format (version 2).- * Contains both the slim Firebase data (for resolver) and a backward-compatible- * models array (for existing consumers in cli.ts/mcp-server.ts that expect {id: string}).- */-export interface DiskCacheV2 {- version: 2;+export interface DiskCacheV3 {+ version: 3;lastUpdated: string;entries: SlimModelEntry[];- /** Backward-compatible: [{id: "vendor/model"}] for legacy consumers */models: Array<{ id: string }>;- /** Additive queryPlans cache. Absent on legacy v2 files. */- plans?: CachedSubscriptionPlan[];- /**- * The catalog generation every page in `entries` AND `plans` was read from.- *- * Recorded so the file can state which snapshot it is, rather than being an- * undated merge. A refresh writes this only when every page and the plans- * document agreed on one revision, so its presence is the assertion that the- * file is internally consistent. Absent on files written before pinning- * existed, which are still readable and are simply not known to be coherent.- */- catalogRevision?: string;+ plans: CachedSubscriptionPlan[];+ catalogGenerationId: string;}export const ALL_MODELS_CACHE_PATH = join(homedir(), ".claudish", "all-models.json");-/**- * Read the cache from disk, normalizing legacy v1 files to a v2 shape.- *- * Returns null if the file doesn't exist or is unparseable.- * A legacy v1 file `{lastUpdated, models}` is normalized to- * `{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);+function hasRoute(value: unknown): value is { routeId: string; routeProfileId: string } {+ if (!value || typeof value !== "object") return false;+ const route = value as Record<string, unknown>;+ return typeof route.routeId === "string" && typeof route.routeProfileId === "string";}-/**- * 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 {+export function isSlimModelEntry(value: unknown): value is SlimModelEntry {+ if (!value || typeof value !== "object") return false;+ const entry = value as Record<string, unknown>;+ if (+ typeof entry.modelId !== "string" ||+ !Array.isArray(entry.aliases) ||+ !entry.aliases.every((alias) => typeof alias === "string")+ )+ return false;+ if (+ entry.subscriptionPlanIds !== undefined &&+ (!Array.isArray(entry.subscriptionPlanIds) ||+ !entry.subscriptionPlanIds.every((id) => typeof id === "string"))+ )+ return false;+ if (entry.aggregators === undefined) return true;+ if (!Array.isArray(entry.aggregators)) return false;+ return entry.aggregators.every((candidate: unknown) => {+ if (!candidate || typeof candidate !== "object") return false;+ const connection = candidate as Record<string, unknown>;+ return connection.routeStatus === "mapped"+ ? hasRoute(connection.route) &&+ typeof connection.externalModelId === "string" &&+ connection.externalModelId.length > 0+ : connection.routeStatus === "unknown" || connection.routeStatus === "unsupported";+ });+}++export function isCachedSubscriptionPlan(value: unknown): value is CachedSubscriptionPlan {+ if (!value || typeof value !== "object") return false;+ const plan = value as Record<string, unknown>;+ return (+ typeof plan.id === "string" &&+ plan.id.length > 0 &&+ (plan.routeStatus === "supported"+ ? hasRoute(plan.route)+ : plan.routeStatus === "unsupported" || plan.routeStatus === "unknown") &&+ (plan.modelDiscovery === undefined ||+ ["catalog", "client", "hybrid"].includes(String(plan.modelDiscovery)))+ );+}++export function readAllModelsCache(path: string = ALL_MODELS_CACHE_PATH): DiskCacheV3 | null {if (!existsSync(path)) return null;let raw: unknown;@@ -357,64 +151,24 @@ function readCacheFile(path: string): DiskCacheV2 | null {if (!raw || typeof raw !== "object") return null;const data = raw as Record<string, unknown>;+ if (+ data.version !== 3 ||+ typeof data.lastUpdated !== "string" ||+ typeof data.catalogGenerationId !== "string" ||+ data.catalogGenerationId.length === 0 ||+ !Array.isArray(data.entries) ||+ !data.entries.every(isSlimModelEntry) ||+ !Array.isArray(data.models) ||+ !Array.isArray(data.plans) ||+ !data.plans.every(isCachedSubscriptionPlan)+ ) {+ return null;+ }- const lastUpdated =- typeof data.lastUpdated === "string" ? data.lastUpdated : new Date(0).toISOString();- const models = Array.isArray(data.models) ? (data.models as Array<{ id: string }>) : [];- const entries = Array.isArray(data.entries) ? (data.entries as SlimModelEntry[]) : [];- const plans = Array.isArray(data.plans) ? (data.plans as CachedSubscriptionPlan[]) : undefined;- // Read back explicitly. This function rebuilds the object from a known field- // list rather than spreading `data`, so any field not named here is silently- // dropped on the way in — which is what happened to `catalogRevision` until- // a round-trip check caught it writing correctly and reading back undefined.- const catalogRevision =- typeof data.catalogRevision === "string" ? data.catalogRevision : undefined;-- return {- version: 2,- lastUpdated,- entries,- models,- ...(plans !== undefined ? { plans } : {}),- ...(catalogRevision !== undefined ? { catalogRevision } : {}),- };+ return data as unknown as DiskCacheV3;}-/**- * Write the cache to disk in v2 format, preserving any existing `entries`- * or `models` the caller did not explicitly supply.- *- * This is the critical anti-clobber behavior: legacy writers that only know- * about `models` will merge on top of the existing v2 `entries`, leaving the- * OpenRouter Firebase catalog intact.- *- * @param data Partial DiskCacheV2. Any omitted fields are filled from the- * existing file (if present) rather than reset to defaults.- * @param path Override the cache path. Defaults to `ALL_MODELS_CACHE_PATH`.- * Only tests should pass this.- */-export function writeAllModelsCache(- data: Partial<DiskCacheV2>,- path: string = ALL_MODELS_CACHE_PATH-): void {- // Ungated on purpose — see readCacheFile.- const existing = readCacheFile(path);-- const merged: DiskCacheV2 = {- version: 2,- lastUpdated: data.lastUpdated ?? new Date().toISOString(),- entries: data.entries ?? existing?.entries ?? [],- models: data.models ?? existing?.models ?? [],- ...(data.plans !== undefined || existing?.plans !== undefined- ? { plans: data.plans ?? existing?.plans ?? [] }- : {}),- // Carried, never merged from `existing`. The revision describes the entries- // and plans written in THIS call; inheriting the previous file's value onto- // a partial write would stamp new data with an old snapshot's identity and- // make the coherence claim a lie.- ...(data.catalogRevision !== undefined ? { catalogRevision: data.catalogRevision } : {}),- };-+export function writeAllModelsCache(data: DiskCacheV3, path: string = ALL_MODELS_CACHE_PATH): void {mkdirSync(dirname(path), { recursive: true });- writeFileSync(path, JSON.stringify(merged), "utf-8");+ writeFileSync(path, JSON.stringify(data), "utf-8");}diff --git a/packages/cli/src/providers/api-key-map.ts b/packages/cli/src/providers/api-key-map.tsindex ed4bc19b..59c59ae6 100644--- a/packages/cli/src/providers/api-key-map.ts+++ b/packages/cli/src/providers/api-key-map.ts@@ -26,14 +26,10 @@ export const API_KEY_MAP: Record<string, { envVar: string; aliases?: string[] }>envVar: "SAKANA_SUBSCRIPTION_API_KEY",aliases: ["SAKANA_CODING_API_KEY"],},- // No alias by design: a Qwen Plan key authenticates ONLY against the- // plan host; the DashScope/PAYG hosts reject it (401/403), so aliasing onto- // DASHSCOPE_API_KEY / QWEN_API_KEY could only mis-route or mis-bill.- "qwen-cloud": { envVar: "QWEN_CLOUD_PLAN_API_KEY" },- // The PAYG sibling is the inverse case: both of these names hold a metered- // Model Studio key, so they are two spellings of ONE billing mode and may- // safely alias. Neither may ever alias onto the plan key above.- "qwen-payg": { envVar: "DASHSCOPE_API_KEY", aliases: ["QWEN_API_KEY"] },+ // Alibaba products use isolated credentials and hosts.+ "qwen-token-plan": { envVar: "QWEN_TOKEN_PLAN_API_KEY" },+ "qwen-coding": { envVar: "QWEN_CODING_PLAN_API_KEY" },+ "qwen-payg": { envVar: "DASHSCOPE_API_KEY" },ollamacloud: { envVar: "OLLAMA_API_KEY" },"opencode-zen": { envVar: "OPENCODE_API_KEY" },// The Go plan has its OWN key. This entry used to name OPENCODE_API_KEY — thediff --git a/packages/cli/src/providers/catalog-client-contract.test.ts b/packages/cli/src/providers/catalog-client-contract.test.tsdeleted file mode 100644index 9ea5a613..00000000--- a/packages/cli/src/providers/catalog-client-contract.test.ts+++ /dev/null@@ -1,234 +0,0 @@-import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";-import { tmpdir } from "node:os";-import { join } from "node:path";-import { pathToFileURL } from "node:url";--interface EndpointReply {- status: number;- body?: unknown;-}--interface RefreshChildResult {- outcome: unknown;- sentinel: unknown;-}--interface WarmCacheChildResult {- before: unknown;- after: unknown;-}--let tempHome = "";-let server: ReturnType<typeof Bun.serve> | undefined;--beforeEach(() => {- tempHome = mkdtempSync(join(tmpdir(), "claudish-catalog-client-contract-"));-});--afterEach(() => {- server?.stop(true);- server = undefined;- rmSync(tempHome, { recursive: true, force: true });- tempHome = "";-});--function startCatalogServer(- modelsReply: EndpointReply,- plansReply: EndpointReply = { status: 200, body: { contractVersion: 2, plans: [] } }-): { catalogUrl: string; plansUrl: string } {- server = Bun.serve({- port: 0,- fetch(request) {- const { pathname } = new URL(request.url);- const reply = pathname === "/queryPlans" ? plansReply : modelsReply;- return new Response(reply.body === undefined ? undefined : JSON.stringify(reply.body), {- status: reply.status,- headers: reply.body === undefined ? undefined : { "content-type": "application/json" },- });- },- });-- return {- catalogUrl: `http://127.0.0.1:${server.port}/queryModels`,- plansUrl: `http://127.0.0.1:${server.port}/queryPlans`,- };-}--async function runRefreshChild(urls: {- catalogUrl: string;- plansUrl: string;-}): Promise<RefreshChildResult> {- const clientUrl = pathToFileURL(join(import.meta.dir, "catalog-client.ts")).href;- const compatibilityUrl = pathToFileURL(join(import.meta.dir, "catalog-compatibility.ts")).href;- const sentinelPath = join(tempHome, ".claudish", "catalog-incompatible.json");- const source = `- const compatibility = await import(${JSON.stringify(compatibilityUrl)});- const client = await import(${JSON.stringify(clientUrl)});- compatibility._resetCatalogCompatibilityForTest();- client._resetCatalogClient();- const outcome = await client.refreshCatalog(2_000);- const sentinel = compatibility.readCatalogIncompatibility(- ${JSON.stringify(sentinelPath)}- );- console.log(JSON.stringify({ outcome, sentinel }));- `;- const env: Record<string, string | undefined> = {- ...process.env,- HOME: tempHome,- CLAUDISH_CATALOG_URL: urls.catalogUrl,- CLAUDISH_PLANS_URL: urls.plansUrl,- };- // Safe: the loopback CLAUDISH_CATALOG_URL override and temp HOME's isolated- // cachePath keep this hermetic. The child has its own HOME, so remove an- // inherited shared sentinel path that would leak state between children.- delete env.CLAUDISH_DISABLE_CATALOG_WARM;- delete env.CLAUDISH_CATALOG_INCOMPATIBLE_PATH;- const child = Bun.spawn([process.execPath, "-e", source], {- cwd: import.meta.dir,- env,- stdout: "pipe",- stderr: "pipe",- });- const [stdout, stderr, exitCode] = await Promise.all([- new Response(child.stdout).text(),- new Response(child.stderr).text(),- child.exited,- ]);- if (exitCode !== 0) {- throw new Error(`catalog child exited ${exitCode}: ${stderr || stdout}`);- }- return JSON.parse(stdout.trim()) as RefreshChildResult;-}--async function runWarmCacheChild(urls: {- catalogUrl: string;- plansUrl: string;-}): Promise<WarmCacheChildResult> {- const clientUrl = pathToFileURL(join(import.meta.dir, "catalog-client.ts")).href;- const compatibilityUrl = pathToFileURL(join(import.meta.dir, "catalog-compatibility.ts")).href;- const sentinelPath = join(tempHome, ".claudish", "catalog-incompatible.json");- const source = `- const compatibility = await import(${JSON.stringify(compatibilityUrl)});- const client = await import(${JSON.stringify(clientUrl)});- compatibility._resetCatalogCompatibilityForTest();- client._resetCatalogClient();- const before = client.getCatalogEntries();- compatibility.markCatalogIncompatible(- { serverContractVersion: 3, minimumContractVersion: 3 },- ${JSON.stringify(sentinelPath)}- );- const after = client.getCatalogEntries();- console.log(JSON.stringify({ before, after }));- `;- const env: Record<string, string | undefined> = {- ...process.env,- HOME: tempHome,- CLAUDISH_CATALOG_URL: urls.catalogUrl,- CLAUDISH_PLANS_URL: urls.plansUrl,- };- // The child has its own HOME, so remove an inherited shared sentinel path- // that would leak state between children.- delete env.CLAUDISH_CATALOG_INCOMPATIBLE_PATH;- const child = Bun.spawn([process.execPath, "-e", source], {- cwd: import.meta.dir,- env,- stdout: "pipe",- stderr: "pipe",- });- const [stdout, stderr, exitCode] = await Promise.all([- new Response(child.stdout).text(),- new Response(child.stderr).text(),- child.exited,- ]);- if (exitCode !== 0) {- throw new Error(`catalog child exited ${exitCode}: ${stderr || stdout}`);- }- return JSON.parse(stdout.trim()) as WarmCacheChildResult;-}--describe("catalog contract compatibility over HTTP", () => {- test("refreshCatalog returns incompatible for a body-less 426 response", async () => {- const urls = startCatalogServer({ status: 426 });-- const result = await runRefreshChild(urls);-- expect(result.outcome).toEqual({ kind: "incompatible", serverContractVersion: null });- expect(result.sentinel).toMatchObject({ serverContractVersion: null });- });-- test("any non-2xx response is incompatible when its body reports a newer contract", async () => {- for (const status of [400, 410, 429, 503]) {- server?.stop(true);- server = undefined;- const urls = startCatalogServer({- status,- body: {- contractVersion: 3,- error: {- code: "catalog_unavailable",- minimumContractVersion: 3,- },- },- });-- const result = await runRefreshChild(urls);-- expect(result.outcome).toEqual({ kind: "incompatible", serverContractVersion: 3 });- expect(result.sentinel).toMatchObject({- serverContractVersion: 3,- minimumContractVersion: 3,- });- }- });-- test("never writes a v3 success body into the existing v2 disk cache", async () => {- const cacheDir = join(tempHome, ".claudish");- const cachePath = join(cacheDir, "all-models.json");- const originalBytes = Buffer.from(- '{\n "version": 2,\n "lastUpdated": "2026-09-10T00:00:00.000Z",\n "entries": [{"modelId":"safe-v2-model","aliases":[],"sources":{}}],\n "models": []\n}\n',- "utf8"- );- mkdirSync(cacheDir, { recursive: true });- writeFileSync(cachePath, originalBytes);- const urls = startCatalogServer({- status: 200,- body: {- contractVersion: 3,- total: 1,- models: [{ modelId: "unsafe-v3-model", aliases: [], sources: {} }],- },- });-- const result = await runRefreshChild(urls);-- expect(result.outcome).toEqual({ kind: "incompatible", serverContractVersion: 3 });- expect(readFileSync(cachePath).equals(originalBytes)).toBe(true);- });-- test("returns null after the sentinel is set even when the module cache is warm", async () => {- const cacheDir = join(tempHome, ".claudish");- mkdirSync(cacheDir, { recursive: true });- writeFileSync(- join(cacheDir, "all-models.json"),- JSON.stringify({- version: 2,- lastUpdated: "2026-09-10T00:00:00.000Z",- entries: [{ modelId: "warm-v2-model", aliases: [], sources: {} }],- models: [],- }),- "utf8"- );- // This path does not fetch; the URLs only ensure module evaluation stays- // hermetic from production endpoints while the disk cache is warmed.- const urls = {- catalogUrl: "http://127.0.0.1:1/queryModels",- plansUrl: "http://127.0.0.1:1/queryPlans",- };-- const result = await runWarmCacheChild(urls);-- expect(result.before).toEqual([{ modelId: "warm-v2-model", aliases: [], sources: {} }]);- expect(result.after).toBeNull();- });-});diff --git a/packages/cli/src/providers/catalog-client.test.ts b/packages/cli/src/providers/catalog-client.test.tsindex 6a7617cd..653b5a8d 100644--- a/packages/cli/src/providers/catalog-client.test.ts+++ b/packages/cli/src/providers/catalog-client.test.ts@@ -10,354 +10,228 @@ import {refreshCatalog,resolveTargetForCatalog,} from "./catalog-client.js";+import { CATALOG_V3_ACCEPT } from "./catalog-v3.js";import { parseModelSpec } from "./model-parser.js";const realFetch = globalThis.fetch;-let previousDisableCatalogWarm: string | undefined;-let previousCatalogUrl: string | undefined;-let previousPlansUrl: string | undefined;-const tempDirs: string[] = [];--function tempCachePath(prefix = "claudish-catalog-client-"): string {- const dir = mkdtempSync(join(tmpdir(), prefix));- tempDirs.push(dir);+const originalEnv = {+ warm: process.env.CLAUDISH_DISABLE_CATALOG_WARM,+ catalog: process.env.CLAUDISH_CATALOG_URL,+ plans: process.env.CLAUDISH_PLANS_URL,+};+const dirs: string[] = [];+function tempCachePath(): string {+ const dir = mkdtempSync(join(tmpdir(), "claudish-catalog-v3-"));+ dirs.push(dir);return join(dir, "all-models.json");}--function restoreEnv(name: string, value: string | undefined): void {+function restore(name: string, value: string | undefined): void {if (value === undefined) delete process.env[name];else process.env[name] = value;}-beforeEach(() => {- previousDisableCatalogWarm = process.env.CLAUDISH_DISABLE_CATALOG_WARM;- previousCatalogUrl = process.env.CLAUDISH_CATALOG_URL;- previousPlansUrl = process.env.CLAUDISH_PLANS_URL;_resetCatalogClient();+ delete process.env.CLAUDISH_DISABLE_CATALOG_WARM;+ process.env.CLAUDISH_CATALOG_URL = "https://catalog.test/queryModels?catalog=slim";+ process.env.CLAUDISH_PLANS_URL = "https://catalog.test/queryPlans";});-afterEach(() => {- restoreEnv("CLAUDISH_DISABLE_CATALOG_WARM", previousDisableCatalogWarm);- restoreEnv("CLAUDISH_CATALOG_URL", previousCatalogUrl);- restoreEnv("CLAUDISH_PLANS_URL", previousPlansUrl);- while (tempDirs.length > 0) {- const dir = tempDirs.pop();- if (dir) rmSync(dir, { recursive: true, force: true });- }globalThis.fetch = realFetch;+ restore("CLAUDISH_DISABLE_CATALOG_WARM", originalEnv.warm);+ restore("CLAUDISH_CATALOG_URL", originalEnv.catalog);+ restore("CLAUDISH_PLANS_URL", originalEnv.plans);+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });_resetCatalogClient();});-describe("refreshCatalog catalog-warm kill switch", () => {- // This regression is a race: a sibling test's sticky empty-catalog override- // could let the process exit before a live fetch reached the developer's- // cache. The fetch assertion proves the kill switch returns before that path.- test("returns disabled before network or disk side effects", async () => {- process.env.CLAUDISH_DISABLE_CATALOG_WARM = "1";- const fetchStub = mock(- async () =>- new Response(- JSON.stringify({- models: [- {- modelId: "offline-test-model",- aliases: [],- sources: { test: { externalId: "test/offline-test-model" } },- },- ],- plans: [],- }),- { status: 200, headers: { "Content-Type": "application/json" } }- )- );- globalThis.fetch = fetchStub as unknown as typeof fetch;-- const outcome = await refreshCatalog(100, { cachePath: tempCachePath() });-- expect(outcome).toEqual({ kind: "fetch_failed", reason: "disabled" });- expect(fetchStub).not.toHaveBeenCalled();- });-- test('recognizes only "1" as disabled', () => {- expect(catalogWarmDisabledFor("1")).toBe(true);+function envelope(data: unknown, generationId = "generation-a"): Response {+ return Response.json({+ contractVersion: 3,+ generationId,+ generatedAt: "2026-09-19T01:33:46.169Z",+ data,});+}+function entry(modelId: string, provider: string, externalModelId: string): SlimModelEntry {+ const routes: Record<string, { routeId: string; routeProfileId: string }> = {+ "qwen-coding": { routeId: "qwen", routeProfileId: "modelstudio-coding-plan" },+ "qwen-token-plan": { routeId: "qwen", routeProfileId: "qwencloud-token-plan" },+ "qwen-payg": { routeId: "qwen", routeProfileId: "dashscope-direct" },+ };+ return {+ modelId,+ aliases: [],+ aggregators: [+ {+ sourceProviderId: "qwen",+ sourceCollectorId: "test",+ confidence: "api_official",+ routeStatus: "mapped",+ route: routes[provider],+ externalModelId,+ },+ ],+ };+}- // Pass negative values as arguments: this avoids writing a process-global- // another file's detached warmCatalog() may read, and a required parameter is- // the only way to express "explicitly unset" because a default fires on undefined.- for (const [label, switchValue] of [- ['"true"', "true"],- ['"0"', "0"],- ['""', ""],- ["undefined", undefined],- ] as const) {- test(`does not disable catalog warm for ${label}`, () => {- expect(catalogWarmDisabledFor(switchValue)).toBe(false);- });- }-});--const catalogEntry = (modelId: string): SlimModelEntry => ({- modelId,- aliases: [],- sources: { "openrouter-api": { externalId: `future-labs/${modelId}` } },- reasoningStatus: "unknown",-});--describe("refreshCatalog revision-pinned pagination", () => {- let server: ReturnType<typeof Bun.serve> | undefined;- let cachePath = "";- let handleRequest: (request: Request) => Response | Promise<Response>;-- beforeEach(() => {- cachePath = tempCachePath();- handleRequest = () => new Response(null, { status: 500 });- server = Bun.serve({- port: 0,- fetch: (request) => handleRequest(request),+describe("v3 catalog refresh", () => {+ test("the warm switch prevents network and disk writes", async () => {+ process.env.CLAUDISH_DISABLE_CATALOG_WARM = "1";+ const fetchStub = mock(async () => envelope({ mode: "slim", models: [] }));+ globalThis.fetch = fetchStub as unknown as typeof fetch;+ expect(await refreshCatalog(100, { cachePath: tempCachePath() })).toEqual({+ kind: "fetch_failed",+ reason: "disabled",});- const origin = `http://127.0.0.1:${server.port}`;-- // ORDER IS LOAD-BEARING. The URL redirect goes up BEFORE the warm gate comes- // down, and never the other way round.- //- // `proxy-server.ts` fires an un-awaited `warmCatalog()` on every- // `createProxyServer`, so a detached refresh can reach `catalogWarmDisabled()`- // at any instant while this suite runs. Clearing the gate first leaves a- // window in which such a refresh is enabled AND still pointed at the live- // catalog — it then fetches over the network and writes the developer's real- // `~/.claudish/all-models.json`.- //- // That is not hypothetical. It is the leak `catalog-client.ts` documents- // having measured on 2026-09-15, and this file reproduced it on 2026-09-17:- // `guard-real-config` reported "REAL MODEL CATALOG CACHE MUTATED — changed- // lastUpdated" on one `test:safe` run and not the next, because whether the- // detached warm lands inside the window depends on file ordering.- //- // With this order, anything that slips through hits the local server instead,- // and the guard's remaining job is a backstop rather than a cleanup.- process.env.CLAUDISH_CATALOG_URL = `${origin}/queryModels?status=active&catalog=slim&limit=7`;- process.env.CLAUDISH_PLANS_URL = `${origin}/queryPlans`;- delete process.env.CLAUDISH_DISABLE_CATALOG_WARM;- });-- afterEach(() => {- server?.stop(true);- server = undefined;+ expect(fetchStub).not.toHaveBeenCalled();+ expect(catalogWarmDisabledFor("true")).toBe(false);});- function json(data: unknown, revision?: string, status = 200): Response {- const headers = new Headers({ "Content-Type": "application/json" });- if (revision) headers.set("X-Catalog-Revision", revision);- return new Response(JSON.stringify(data), { status, headers });- }-- async function seedPreviousGeneration(): Promise<{- bytes: string;- memory: SlimModelEntry[];- }> {- const previousEntry = catalogEntry("orion-7.3-future");- handleRequest = (request) => {- const url = new URL(request.url);- if (url.pathname === "/queryModels") {- return json(- { models: [previousEntry], total: 1, offset: 0, limit: 1000, hasMore: false },- "revision-previous"- );- }- if (url.pathname === "/queryPlans") {- return json({ plans: [{ id: "previous-plan" }] }, "revision-previous");- }- return new Response(null, { status: 404 });- };-- expect(await refreshCatalog(1000, { cachePath })).toEqual({- kind: "refreshed",- modelCount: 1,- catalogRevision: "revision-previous",- pages: 1,- });- const memory = getCatalogEntries();- expect(memory).toEqual([previousEntry]);- return { bytes: readFileSync(cachePath, "utf-8"), memory: memory! };- }-- function expectPreviousGenerationPreserved(previous: {- bytes: string;- memory: SlimModelEntry[];- }): void {- expect(readFileSync(cachePath, "utf-8")).toBe(previous.bytes);- expect(getCatalogEntries()).toBe(previous.memory);- }-- test("follows every page, advances by returned rows, and pins pages and plans", async () => {+ test("pins opaque model and plan cursors and commits exact routes together", async () => {+ const cachePath = tempCachePath();const requests: Array<{- path: string;- offset: string | null;- limit: string | null;- revision: string | null;- revisionHeader: string | null;+ pathname: string;+ cursor: string | null;+ generation: string | null;+ accept: string | null;}> = [];- const first = [catalogEntry("orion-7.4-future"), catalogEntry("qwen4.2-nebula")];- const second = [catalogEntry("claude-opus-6-future")];-- handleRequest = (request) => {- const url = new URL(request.url);+ const first = entry("qwen3.7-plus", "qwen-coding", "qwen3.7-plus");+ const second = entry("qwen3.8-max", "qwen-token-plan", "qwen3.8-max");+ const plan = {+ id: "alibaba-ai-coding-plan",+ routeStatus: "supported" as const,+ route: { routeId: "qwen", routeProfileId: "modelstudio-coding-plan" },+ modelDiscovery: "catalog" as const,+ };+ const stub = mock(async (url: string | URL | Request, init?: RequestInit) => {+ const request = new URL(String(url));requests.push({- path: url.pathname,- offset: url.searchParams.get("offset"),- limit: url.searchParams.get("limit"),- revision: url.searchParams.get("revision"),- revisionHeader: request.headers.get("revision"),+ pathname: request.pathname,+ cursor: request.searchParams.get("cursor"),+ generation: request.searchParams.get("generationId"),+ accept: new Headers(init?.headers).get("accept"),});- if (url.pathname === "/queryPlans") {- return json({ plans: [{ id: "future-plan" }] }, "revision-a");- }- if (url.searchParams.get("offset") === "0") {- return json(- { models: first, total: 3, offset: 0, limit: 1000, hasMore: true },- "revision-a"- );- }- return json(- { models: second, total: 3, offset: 2, limit: 1000, hasMore: false },- "revision-a"- );- };-+ if (request.pathname === "/queryModels")+ return envelope({+ mode: "slim",+ models: request.searchParams.has("cursor") ? [second] : [first],+ total: 2,+ ...(request.searchParams.has("cursor") ? {} : { nextCursor: "opaque-model" }),+ });+ return envelope({ plans: [plan], total: 1 });+ });+ globalThis.fetch = stub as unknown as typeof fetch;expect(await refreshCatalog(1000, { cachePath })).toEqual({kind: "refreshed",- modelCount: 3,- catalogRevision: "revision-a",+ modelCount: 2,+ catalogGenerationId: "generation-a",pages: 2,});-expect(requests).toEqual([+ { pathname: "/queryModels", cursor: null, generation: null, accept: CATALOG_V3_ACCEPT },{- path: "/queryModels",- offset: "0",- limit: "1000",- revision: null,- revisionHeader: null,+ pathname: "/queryModels",+ cursor: "opaque-model",+ generation: "generation-a",+ accept: CATALOG_V3_ACCEPT,},{- path: "/queryModels",- offset: "2",- limit: "1000",- revision: "revision-a",- revisionHeader: null,- },- {- path: "/queryPlans",- offset: null,- limit: null,- revision: "revision-a",- revisionHeader: null,+ pathname: "/queryPlans",+ cursor: null,+ generation: "generation-a",+ accept: CATALOG_V3_ACCEPT,},]);- const cache = readAllModelsCache(cachePath);- expect(cache?.entries).toEqual([...first, ...second]);- expect(cache?.plans).toEqual([{ id: "future-plan" }]);- expect(cache?.catalogRevision).toBe("revision-a");+ expect(readAllModelsCache(cachePath)?.entries).toEqual([first, second]);+ expect(readAllModelsCache(cachePath)?.plans).toEqual([plan]);+ expect(getCatalogEntries()).toEqual([first, second]);});- test("accepts the currently deployed one-page response when hasMore is omitted", async () => {- const onlyPage = [catalogEntry("orion-8.0-future")];- let modelRequests = 0;- handleRequest = (request) => {- const url = new URL(request.url);- if (url.pathname === "/queryPlans") return json({ plans: [] }, "revision-current");- modelRequests++;- return json({ models: onlyPage, total: 1, offset: 0, limit: 1000 }, "revision-current");- };-- expect(await refreshCatalog(1000, { cachePath })).toEqual({- kind: "refreshed",- modelCount: 1,- catalogRevision: "revision-current",- pages: 1,- });- expect(modelRequests).toBe(1);- expect(readAllModelsCache(cachePath)?.entries).toEqual(onlyPage);- expect(readAllModelsCache(cachePath)?.catalogRevision).toBe("revision-current");- });-- test("rejects a later page from another revision and preserves both caches byte-for-byte", async () => {- const previous = await seedPreviousGeneration();- handleRequest = (request) => {- const url = new URL(request.url);- if (url.searchParams.get("offset") === "0") {- return json({ models: [catalogEntry("new-page-one")], hasMore: true }, "revision-new");- }- expect(url.searchParams.get("revision")).toBe("revision-new");- return json({ models: [catalogEntry("new-page-two")], hasMore: false }, "revision-other");- };-+ test("a different plan generation does not replace the complete cache", async () => {+ const cachePath = tempCachePath();+ let planGeneration = "generation-a";+ globalThis.fetch = mock(async (url: string | URL | Request) => {+ const path = new URL(String(url)).pathname;+ return path === "/queryPlans"+ ? envelope(+ {+ plans: [+ {+ id: "plan",+ routeStatus: "supported",+ route: { routeId: "qwen", routeProfileId: "modelstudio-coding-plan" },+ },+ ],+ total: 1,+ },+ planGeneration+ )+ : envelope({+ mode: "slim",+ models: [entry("qwen3.7-plus", "qwen-coding", "qwen3.7-plus")],+ total: 1,+ });+ }) as unknown as typeof fetch;+ expect((await refreshCatalog(1000, { cachePath })).kind).toBe("refreshed");+ const bytes = readFileSync(cachePath, "utf-8");+ planGeneration = "generation-b";expect(await refreshCatalog(1000, { cachePath })).toEqual({kind: "fetch_failed",- reason: "revision_mismatch",+ reason: "generation_mismatch",});- expectPreviousGenerationPreserved(previous);+ expect(readFileSync(cachePath, "utf-8")).toBe(bytes);});- test("rejects a later HTTP failure as incomplete and preserves both caches byte-for-byte", async () => {- const previous = await seedPreviousGeneration();- handleRequest = (request) => {- const url = new URL(request.url);- if (url.searchParams.get("offset") === "0") {- return json({ models: [catalogEntry("new-page-one")], hasMore: true }, "revision-new");- }- expect(url.searchParams.get("revision")).toBe("revision-new");- return new Response("later page failed", { status: 500 });- };-+ test("rejects a truncated model snapshot without replacing the cache", async () => {+ const cachePath = tempCachePath();+ let total = 1;+ globalThis.fetch = mock(async (url: string | URL | Request) => {+ const path = new URL(String(url)).pathname;+ return path === "/queryPlans"+ ? envelope({+ plans: [+ {+ id: "plan",+ routeStatus: "supported",+ route: { routeId: "qwen", routeProfileId: "modelstudio-coding-plan" },+ },+ ],+ total: 1,+ })+ : envelope({+ mode: "slim",+ models: [entry("qwen3.7-plus", "qwen-coding", "qwen3.7-plus")],+ total,+ });+ }) as unknown as typeof fetch;+ expect((await refreshCatalog(1000, { cachePath })).kind).toBe("refreshed");+ const complete = readFileSync(cachePath, "utf-8");+ total = 2;expect(await refreshCatalog(1000, { cachePath })).toEqual({kind: "fetch_failed",reason: "incomplete",});- expectPreviousGenerationPreserved(previous);+ expect(readFileSync(cachePath, "utf-8")).toBe(complete);});- test("rejects a later network failure as incomplete and preserves both caches byte-for-byte", async () => {- const previous = await seedPreviousGeneration();- const stopped = Bun.serve({ port: 0, fetch: () => new Response(null, { status: 204 }) });- const stoppedPort = stopped.port;- stopped.stop(true);-- handleRequest = (request) => {- const url = new URL(request.url);- if (url.searchParams.get("offset") !== "0") {- return new Response("unexpected second request to live server", { status: 500 });- }- process.env.CLAUDISH_CATALOG_URL = `http://127.0.0.1:${stoppedPort}/queryModels?status=active&catalog=slim`;- return json({ models: [catalogEntry("new-page-one")], hasMore: true }, "revision-new");- };-- expect(await refreshCatalog(1000, { cachePath })).toEqual({- kind: "fetch_failed",- reason: "incomplete",+ test("classifies a bodyless upgrade response as an incompatible contract", async () => {+ globalThis.fetch = mock(+ async () => new Response(null, { status: 426 })+ ) as unknown as typeof fetch;+ expect(await refreshCatalog(1000, { cachePath: tempCachePath() })).toEqual({+ kind: "incompatible",+ serverContractVersion: null,});- expectPreviousGenerationPreserved(previous);});- test("rejects hasMore with an empty page instead of looping or committing a prefix", async () => {- const previous = await seedPreviousGeneration();- let pageRequests = 0;- handleRequest = (request) => {- const url = new URL(request.url);- pageRequests++;- if (url.searchParams.get("offset") === "0") {- return json({ models: [catalogEntry("new-page-one")], hasMore: true }, "revision-new");- }- return json({ models: [], hasMore: true }, "revision-new");- };-- expect(await refreshCatalog(1000, { cachePath })).toEqual({- kind: "fetch_failed",- reason: "incomplete",+ test("rejects a response outside contract v3", async () => {+ globalThis.fetch = mock(async () =>+ Response.json({ contractVersion: 2, models: [] })+ ) as unknown as typeof fetch;+ expect(await refreshCatalog(1000, { cachePath: tempCachePath() })).toEqual({+ kind: "incompatible",+ serverContractVersion: 2,});- expect(pageRequests).toBe(2);- expectPreviousGenerationPreserved(previous);});});diff --git a/packages/cli/src/providers/catalog-client.ts b/packages/cli/src/providers/catalog-client.tsindex 74fafa49..346a5a18 100644--- a/packages/cli/src/providers/catalog-client.ts+++ b/packages/cli/src/providers/catalog-client.ts@@ -1,90 +1,27 @@-/**- * The model catalog client — fetch, cache, and resolve, for ALL providers.- *- * This is the single source of truth for model facts. It fetches the Firebase- * slim catalog, keeps it in memory and on disk (`~/.claudish/all-models.json`),- * and answers "what does provider P call model M?" from `aggregators[]`.- *- * ## Why this file exists- *- * All of this previously lived inside `catalog-resolvers/openrouter.ts` behind- * an `OpenRouterCatalogResolver` class, which made the app-wide catalog loader- * look like an OpenRouter feature. It was not: `writeAllModelsCache` had exactly- * one caller in the codebase, and every catalog read — context windows,- * reasoning capability, tokenParam, routeVariant — depended on that class- * having run. The name hid the dependency and made "why is there only one- * resolver?" unanswerable.- *- * The per-provider resolver interface is gone with it. Name resolution was- * never provider-specific logic — it is one lookup, `aggregators[]`, which the- * catalog now populates for 18 providers. A registry of classes to perform one- * table lookup per provider is a registry of one thing repeated.- *- * ## The two data sources, and which owns what- *- * - **This catalog (cloud, TTL'd)** owns model IDENTITY: what a model is, what- * it can do, what each provider calls it, what it costs. Same for everyone.- * - **A provider's own live endpoint** (`model-discovery.ts`) owns ENTITLEMENT:- * which subset of those models THIS key may use, and the context window for- * THIS subscription tier. Per-user, and impossible to hold statically.- *- * They are joined on model id, not chained as fallbacks. There is deliberately- * NO per-model cloud lookup for gaps: re-querying the same cloud one model at a- * time returns the same answer N times more slowly. A field missing here is a- * models-index gap to fix there.- */-import {type CachedSubscriptionPlan,- type DiskCacheV2,+ type DiskCacheV3,type SlimModelEntry,+ isCachedSubscriptionPlan,+ isSlimModelEntry,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:- * - `CLAUDISH_CATALOG_URL` (preferred, documented spelling)- * - `FIREBASE_CATALOG_URL` (backwards-compat alias)- *- * Chiefly useful for integration tests that point at a local server to force- * fetch failures.- */+import { catalogRouteMatchesProvider } from "./catalog-route-bindings.js";+import { CATALOG_V3_ACCEPT, type CatalogV3Envelope, parseCatalogV3Envelope } from "./catalog-v3.js";+const DEFAULT_CATALOG_URL =- "https://us-central1-claudish-6da10.cloudfunctions.net/queryModels?status=active&catalog=slim&limit=1000";--/**- * Resolved PER CALL rather than once at import.- *- * A module-level constant freezes whatever the environment held at the instant- * this file was first imported, which makes the documented override untestable:- * a test that points `CLAUDISH_CATALOG_URL` at a local server only takes effect- * if it happens to run before any other file imports this module. Reading the- * variable at call time makes the override mean what it says, and costs one- * property read per refresh.- */-function catalogUrl(): string {- return (- process.env.CLAUDISH_CATALOG_URL ?? process.env.FIREBASE_CATALOG_URL ?? DEFAULT_CATALOG_URL- );-}+ "https://us-central1-claudish-6da10.cloudfunctions.net/queryModels?status=all&catalog=slim&limit=1000";+const MAX_CATALOG_PAGES = 40;+const CATALOG_PAGE_LIMIT = 1000;-/** The plans endpoint, derived from the catalog URL unless overridden. */-function plansUrl(): string {- return process.env.CLAUDISH_PLANS_URL ?? derivePlansUrl(catalogUrl());+function catalogUrl(): string {+ return process.env.CLAUDISH_CATALOG_URL ?? DEFAULT_CATALOG_URL;}-function derivePlansUrl(catalogUrl: string): string {+function derivePlansUrl(modelsUrl: string): string {try {- const url = new URL(catalogUrl);+ const url = new URL(modelsUrl);url.pathname = url.pathname.replace(/\/queryModels$/, "/queryPlans");url.search = "";return url.toString();@@ -93,21 +30,14 @@ function derivePlansUrl(catalogUrl: string): string {}}-// Re-export so existing imports of the DiskCache type keep working.-export type DiskCache = DiskCacheV2;+function plansUrl(): string {+ return process.env.CLAUDISH_PLANS_URL ?? derivePlansUrl(catalogUrl());+}++export type DiskCache = DiskCacheV3;-/**- * Outcome of an explicit `refreshCatalog()` call.- *- * Unlike `warmCatalog()` (fire-and-forget, silent on failure), this returns- * ground truth so the launcher can make a policy decision.- */export type RefreshOutcome =- // `catalogRevision` and `pages` are diagnostics, and OPTIONAL so that- // constructing a success outcome (which several callers and fakes do) does not- // require knowing them. Requiring them would buy no safety: no caller branches- // on either value.- | { kind: "refreshed"; modelCount: number; catalogRevision?: string; pages?: number }+ | { kind: "refreshed"; modelCount: number; catalogGenerationId?: string; pages?: number }| {kind: "fetch_failed";reason:@@ -116,133 +46,42 @@ export type RefreshOutcome =| "http_error"| "empty"| "disabled"- /** A later page came from a different catalog generation than page 1. */- | "revision_mismatch"- /** The server said `hasMore` but the pages could not be completed. */+ | "generation_mismatch"| "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 {- /** The resolved model ID (e.g. "qwen/qwen3-coder-next"). */resolvedId: string;- /** Whether resolution changed the input (false = passthrough unchanged). */wasResolved: boolean;- /** Human-readable source label for the log line. */sourceLabel: string;}-/** Module-level memory cache of slim catalog entries. */let _memCache: SlimModelEntry[] | null = null;--/** Explicit tri-state catalog override for hermetic tests. */let _catalogEntriesForTest: SlimModelEntry[] | null | undefined;--/** In-flight warm, so concurrent callers await one fetch rather than N. */let _warmPromise: Promise<void> | null = null;-// ----------------------------------------------------------------------------// Cache access-// -----------------------------------------------------------------------------/**- * All catalog entries: memory first, then the disk cache, then null.- *- * Null means "cold" — never "empty catalog". Callers must degrade to- * passthrough rather than concluding a model does not exist.- */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();- if (!cache) return null;-- if (cache.entries.length > 0) {- _memCache = cache.entries;- return _memCache;- }-- // Backward-compat: synthesize entries from a legacy v1 models array.- if (cache.models.length > 0) {- _memCache = cache.models.map((m) => ({- modelId: m.id.includes("/") ? m.id.split("/").slice(1).join("/") : m.id,- aliases: [],- sources: { "openrouter-api": { externalId: m.id } },- }));- return _memCache;- }-- return null;+ if (!cache || cache.entries.length === 0) return null;+ _memCache = cache.entries;+ return _memCache;}-/**- * The newest Anthropic Opus id the catalog knows, or null when the catalog is- * cold. For the `--probe` native-Claude-Code link, which must send a REAL- * API-valid model id because it hits api.anthropic.com directly.- *- * Derived rather than pinned, because a pinned id here rots into a hard failure- * and did: `claude-opus-4-1` sat in `cli.ts` under a comment asserting it was- * "the current Opus alias the API accepts (verified against api.anthropic.com)".- * Measured 2026-08-18, that id returns **404 not_found_error**, while the same- * comment's claim that the API rejects `claude-opus-4-8` is also false — it- * returns 200. A verification note has no expiry date, so the comment stayed- * confident long after the fact changed.- *- * The rule is "newest released `claude-opus-*` the catalog lists", so a new Opus- * is picked up by the next catalog refresh with no code change. `-fast` variants- * are deprioritised only as a tiebreak within the same release date: either- * serves a probe, and preferring the base id keeps the choice deterministic.- */export function latestOpusModelId(): string | null {return latestAnthropicTierModelId("opus");}-/**- * The newest Anthropic model id for a Claude Code tier, or null when the catalog- * is cold or lists none. Same rule as `latestOpusModelId` (which delegates here),- * generalised because `--probe sonnet` and `--probe haiku` need the same answer- * for their own tiers — substituting an Opus id for `sonnet` would report a- * different model than the one asked about.- */export function latestAnthropicTierModelId(tier: "opus" | "sonnet" | "haiku"): string | null {const entries = getCatalogEntries();if (!entries) return null;const family = new RegExp(`^claude-${tier}-`, "i");- const opus = entries.filter((e) => family.test(e.modelId));- if (opus.length === 0) return null;- opus.sort((a, b) => {+ const matches = entries.filter((entry) => family.test(entry.modelId));+ if (matches.length === 0) return null;+ matches.sort((a, b) => {const byDate = (b.releaseDate ?? "").localeCompare(a.releaseDate ?? "");if (byDate !== 0) return byDate;const aFast = /-fast$/i.test(a.modelId) ? 1 : 0;@@ -250,139 +89,82 @@ export function latestAnthropicTierModelId(tier: "opus" | "sonnet" | "haiku"): sif (aFast !== bFast) return aFast - bFast;return b.modelId.localeCompare(a.modelId);});- return opus[0].modelId;+ return matches[0].modelId;}-/** Whether the in-memory catalog is populated. */export function isCatalogWarm(): boolean {return _memCache !== null && _memCache.length > 0;}-/** Test seam: override catalog entries without reading disk or fetching. @internal */export function _setCatalogEntriesForTest(entries: SlimModelEntry[] | null): void {_catalogEntriesForTest = entries;}-/** Test seam: drop the in-memory catalog and any in-flight warm. @internal */export function _resetCatalogClient(): void {_catalogEntriesForTest = undefined;_memCache = null;_warmPromise = null;}-// ----------------------------------------------------------------------------// Name resolution — generic over aggregators[]-// -----------------------------------------------------------------------------/**- * What `provider` calls `entry`, or null if it does not serve it.- *- * `aggregators[]` is the typed multi-provider routing index and the primary- * source. The `sources` fallbacks below exist only for OpenRouter, whose- * catalog rows predate `aggregators[]`; without them a cold or partially- * ingested row would stop resolving vendor prefixes that used to work.- */-export function externalIdFor(entry: SlimModelEntry, provider: string): string | null {- const agg = entry.aggregators?.find((a) => a.provider === provider);- if (agg?.externalId) return agg.externalId;-- if (provider !== "openrouter") return null;-- const orSource = entry.sources["openrouter-api"];- if (orSource?.externalId) return orSource.externalId;+function allExternalIds(entry: SlimModelEntry): string[] {+ return (entry.aggregators ?? []).flatMap((connection) =>+ typeof connection.externalModelId === "string" ? [connection.externalModelId] : []+ );+}- // Last resort: any source carrying a vendor-prefixed id.- for (const src of Object.values(entry.sources)) {- if (src.externalId.includes("/")) return src.externalId;- }- return null;+export function externalIdFor(entry: SlimModelEntry, provider: string): string | null {+ const connection = entry.aggregators?.find(+ (candidate) =>+ candidate.routeStatus === "mapped" &&+ catalogRouteMatchesProvider(candidate.route, provider) &&+ typeof candidate.externalModelId === "string"+ );+ return connection?.externalModelId ?? null;}-/**- * Resolve a user-typed model name to the id `provider` accepts.- *- * Chain (first hit wins):- * 1. Already vendor-prefixed → exact `externalId` match, else passthrough.- * 2. Exact `modelId` match.- * 3. `aliases[]` match.- * 4. Any provider's `externalId` matches the input (cross-provider hop).- * 5. Suffix match on this provider's external ids (`/name`).- * 6. Case-insensitive suffix match.- *- * Returns null on a cold cache or no match — the caller sends the input- * unchanged.- */-export function resolveExternalId(userInput: string, provider: string): string | null {- const entries = getCatalogEntries();+export function resolveExternalId(+ userInput: string,+ provider: string,+ cachePath?: string+): string | null {+ const entries = cachePath ? readAllModelsCache(cachePath)?.entries : getCatalogEntries();- // Step 1: already vendor-prefixed.if (userInput.includes("/")) {- if (entries) {- for (const entry of entries) {- for (const src of Object.values(entry.sources)) {- if (src.externalId === userInput) return userInput;- }- }- }+ if (entries?.some((entry) => allExternalIds(entry).includes(userInput))) return userInput;return userInput;}-if (!entries) return null;- // Step 2: exact modelId. AUTHORITATIVE — if the user named a canonical- // catalog id, that row's answer is final, including "this provider does not- // serve it" (null). Falling through to the alias/suffix steps below would- // resolve to a DIFFERENT model that merely shares the name.- //- // Not hypothetical: the catalog currently lists `mistral-medium-3.5` as a- // canonical id AND as an alias of `mistral-medium-2604`. Without this early- // return, asking OpenRouter for 3.5 silently answered with- // `mistralai/mistral-medium-3` — a real model, so no error, just the wrong- // one. Serving a different model than the user asked for is worse than- // failing to route.- const byModelId = entries.find((e) => e.modelId === userInput);+ const byModelId = entries.find((entry) => entry.modelId === userInput);if (byModelId) return externalIdFor(byModelId, provider);- // Step 3: aliases.- const byAlias = entries.find((e) => e.aliases.includes(userInput));+ const byAlias = entries.find((entry) => entry.aliases.includes(userInput));if (byAlias) {- const id = externalIdFor(byAlias, provider);- if (id) return id;+ const resolved = externalIdFor(byAlias, provider);+ if (resolved) return resolved;}- // Step 4: the input is some other provider's external id.for (const entry of entries) {- for (const src of Object.values(entry.sources)) {- if (src.externalId === userInput) {- const id = externalIdFor(entry, provider);- if (id) return id;- }+ if (allExternalIds(entry).includes(userInput)) {+ const resolved = externalIdFor(entry, provider);+ if (resolved) return resolved;}}- // Step 5: suffix match.const suffix = `/${userInput}`;for (const entry of entries) {- const id = externalIdFor(entry, provider);- if (id?.endsWith(suffix)) return id;+ const resolved = externalIdFor(entry, provider);+ if (resolved?.endsWith(suffix)) return resolved;}- // Step 6: case-insensitive suffix match.- const lowerSuffix = `/${userInput.toLowerCase()}`;+ const lowerSuffix = suffix.toLowerCase();for (const entry of entries) {- const id = externalIdFor(entry, provider);- if (id?.toLowerCase().endsWith(lowerSuffix)) return id;+ const resolved = externalIdFor(entry, provider);+ if (resolved?.toLowerCase().endsWith(lowerSuffix)) return resolved;}-return null;}-/**- * Synchronous resolution entry point, called before handler construction.- *- * OpenRouter is the one provider that resolves even an already-prefixed name,- * because the vendor part users type is frequently wrong.- */export function resolveModelNameSync(userInput: string,targetProvider: string@@ -390,40 +172,19 @@ export function resolveModelNameSync(if (targetProvider !== "openrouter" && userInput.includes("/")) {return { resolvedId: userInput, wasResolved: false, sourceLabel: "passthrough" };}-const resolved = resolveExternalId(userInput, targetProvider);if (!resolved || resolved === userInput) {return { resolvedId: userInput, wasResolved: false, sourceLabel: "passthrough" };}-return { resolvedId: resolved, wasResolved: true, sourceLabel: `${targetProvider} catalog` };}-/**- * Decide what a request's target string becomes after catalog resolution.- *- * The rule this encodes: catalog resolution rewrites a target into an- * `provider@model` string, and that shape MEANS "the user named this provider".- * So it may only be applied to a spec that was already explicit. For a BARE name- * the `provider` field is merely auto-DETECTED from the model id, and emitting- * `detected@canonicalId` manufactures a user intent that was never expressed —- * downstream, `parseModelSpec().isExplicitProvider` then reads true and the whole- * routing chain (subscription tiers first) is skipped.- *- * Pulled out of proxy-server's request path as a pure function precisely because- * the failure it prevents is invisible in situ: the bug only fires when the- * canonical id DIFFERS from the typed name, which across the whole catalog was- * true for exactly one family (MiniMax, which differs only in case). A live test- * of any other model passes whether or not the guard exists.- *- * `resolve` is injected so callers can test without a warm catalog.- */export function resolveTargetForCatalog(target: string,isExplicitProvider: boolean,model: string,provider: string,- resolve: (m: string, p: string) => ModelResolutionResult = resolveModelNameSync+ resolve: (model: string, provider: string) => ModelResolutionResult = resolveModelNameSync): { target: string; resolution: ModelResolutionResult | null } {if (!isExplicitProvider) return { target, resolution: null };const resolution = resolve(model, provider);@@ -433,7 +194,6 @@ export function resolveTargetForCatalog(};}-/** Emit a resolution notice to stderr (after `wasResolved=true`). */export function logResolution(userInput: string,result: ModelResolutionResult,@@ -446,195 +206,93 @@ export function logResolution(}}-// ----------------------------------------------------------------------------// Fetch / warm-// -----------------------------------------------------------------------------/**- * One-shot catalog fetch with explicit success/failure return.- *- * On success replaces `_memCache` atomically AFTER the body parses, writes the- * disk cache, and marks the warm as settled. On any failure leaves both caches- * untouched and returns the reason. Never throws.- */-/**- * The RULE for `CLAUDISH_DISABLE_CATALOG_WARM`: exactly `"1"` disables the warm.- * Every other value — `"true"`, `"0"`, `""`, and unset — leaves it enabled.- *- * Separated from the environment read, and taking a REQUIRED parameter, because- * both halves of that shape matter:- *- * - Taking the value as an argument is what lets the rule be tested WITHOUT- * writing the real `process.env`. That is not a convenience. `proxy-server.ts`- * fires an un-awaited `warmCatalog()` on every `createProxyServer`, so a- * detached refresh can reach this check at any instant during a suite. A test- * that proves "only 1 disables" by assigning `"true"` to the shared variable- * opens a window in which such a refresh passes the gate and reads the live- * catalog — the leak the switch exists to stop, reintroduced by the test for- * it, and intermittent because it depends on file ordering. Measured- * 2026-09-15: that is how a full `test:safe` run rewrote the real- * `~/.claudish/all-models.json` while every assertion passed.- *- * - The parameter is required rather than defaulted to the env var, because a- * default fires on `undefined` and so cannot express "explicitly unset". The- * defaulted version made `catalogWarmDisabled(undefined)` read the real- * environment — which the guard sets to `"1"` — so the case asserting that an- * unset variable leaves the warm ENABLED could never pass under `test:safe`.- */export function catalogWarmDisabledFor(value: string | undefined): boolean {return value === "1";}-/** The rule above, applied to the live environment. */function catalogWarmDisabled(): boolean {return catalogWarmDisabledFor(process.env.CLAUDISH_DISABLE_CATALOG_WARM);}-// ----------------------------------------------------------------------------// Revision-pinned pagination-// -----------------------------------------------------------------------------/**- * The header the catalog stamps every response with, naming the immutable- * generation that served it.- */-const CATALOG_REVISION_HEADER = "x-catalog-revision";--/**- * Hard ceiling on pages per refresh.- *- * A stop condition that does not depend on the server agreeing with itself.- * `hasMore` is the server's claim; this is ours. Without it, a server that- * always answers `hasMore: true` turns a warm into an unbounded fetch loop on- * the request path.- */-const MAX_CATALOG_PAGES = 40;--/**- * Page size requested per call.- *- * The backend clamps `limit` to 2000 (`query-handler.ts`, slim branch), so a- * single request can NOT be relied on to return the whole catalog however large- * a number is asked for. Paging is therefore mandatory, not an optimisation.- */-const CATALOG_PAGE_LIMIT = 1000;--/**- * Build one page request from the configured base URL.- *- * `offset`/`limit` are overwritten rather than appended, so a base URL that- * already carries them (the default does: `limit=1000`) pages correctly instead- * of sending the parameter twice. Every other parameter the user configured —- * `status`, `catalog`, and anything a test server needs — is preserved.- *- * `revision` pins the page to one immutable generation. It is a QUERY- * PARAMETER, not a request header: the backend reads `req.query.revision`.- * Sending it as a header would be silently ignored and every page would be- * served from whatever generation was current at that instant, which is exactly- * the torn read the pinning exists to prevent.- */export function buildCatalogPageUrl(baseUrl: string,- offset: number,+ cursor: string | undefined,limit: number,- revision?: string+ generationId?: string): string {const url = new URL(baseUrl);- url.searchParams.set("offset", String(offset));+ url.searchParams.delete("offset");+ url.searchParams.delete("revision");url.searchParams.set("limit", String(limit));- if (revision) url.searchParams.set("revision", revision);+ if (cursor) url.searchParams.set("cursor", cursor);+ else url.searchParams.delete("cursor");+ if (generationId) url.searchParams.set("generationId", generationId);+ else url.searchParams.delete("generationId");return url.toString();}-/** One slim page as the catalog returns it. */-interface CatalogPage {+interface ModelsPageData {+ mode: "slim";models: SlimModelEntry[];- total?: number;- offset?: number;- limit?: number;- hasMore?: boolean;+ total: number;+ nextCursor?: string;+}++interface PlansPageData {+ plans: CachedSubscriptionPlan[];+ total: number;+ nextCursor?: string;}-type PageResult =- | { ok: true; page: CatalogPage; revision?: string }+type FetchFailure =| { 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> {+async function fetchEnvelope<T>(+ url: string,+ timeoutMs: number+): Promise<{ ok: true; envelope: CatalogV3Envelope<T> } | FetchFailure> {let response: Response;try {- response = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });- } catch (err) {- const name = (err as { name?: string } | null | undefined)?.name;- const reason: "timeout" | "network" =- name === "TimeoutError" || name === "AbortError" ? "timeout" : "network";- return { ok: false, reason };- }-- 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" };+ response = await fetch(url, {+ headers: { Accept: CATALOG_V3_ACCEPT },+ signal: AbortSignal.timeout(timeoutMs),+ });+ } catch (error) {+ const name = (error as { name?: string } | null)?.name;+ return {+ ok: false,+ reason: name === "TimeoutError" || name === "AbortError" ? "timeout" : "network",+ };}- let page: CatalogPage;+ let body: unknown;try {- page = (await response.json()) as CatalogPage;+ body = await response.json();} catch {- // Got a response but could not read it — network-class, distinct from "empty".- return { ok: false, reason: "network" };+ if (response.status === 426) {+ return { ok: false, reason: "incompatible", serverContractVersion: null };+ }+ return { ok: false, reason: response.ok ? "network" : "http_error" };}- // 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 statedVersion =+ body &&+ typeof body === "object" &&+ typeof (body as { contractVersion?: unknown }).contractVersion === "number"+ ? ((body as { contractVersion: number }).contractVersion ?? null)+ : null;+ if (response.status === 426 || (statedVersion !== null && statedVersion !== 3)) {+ return { ok: false, reason: "incompatible", serverContractVersion: statedVersion };}+ if (!response.ok) return { ok: false, reason: "http_error" };- const revision = response.headers.get(CATALOG_REVISION_HEADER) ?? undefined;- return { ok: true, page, revision };+ const envelope = parseCatalogV3Envelope<T>(body);+ if (!envelope) return { ok: false, reason: "network" };+ return { ok: true, envelope };}-/** Options for {@link refreshCatalog}. */export interface RefreshCatalogOptions {- /**- * Override the disk cache path.- *- * TESTS ONLY, and load-bearing for them. Without this seam a test that- * exercises a refresh writes the developer's real- * `~/.claudish/all-models.json` — which has happened: a suite seeded the live- * catalog because a refresh reached the default path, and the repo's- * guard-real-config list had to grow a second file afterwards. Coverage for- * pagination and revision mismatches inherently drives a refresh to- * completion, so that coverage cannot exist safely without this parameter.- */cachePath?: string;}@@ -642,281 +300,177 @@ export async function refreshCatalog(timeoutMs: number,options: RefreshCatalogOptions = {}): Promise<RefreshOutcome> {- // `CLAUDISH_DISABLE_CATALOG_WARM=1` turns every refresh into a no-op, which is- // the same contract `CLAUDISH_DISABLE_KEYCHAIN` and `CLAUDISH_DISABLE_OP` give- // the other two shared resources a test must not reach.- //- // This is the gate for ALL callers rather than one inside `warmCatalog`,- // because `ensureCatalogReady` refreshes too and a second entry point is how- // the first gate stops being true.- //- // Measured 2026-09-15: `handlers/explicit-spec-no-credential.test.ts` calls- // `createProxyServer`, `proxy-server.ts:1193` fires `warmCatalog()` on every- // create, and the fetch below then rewrote the developer's real- // `~/.claudish/all-models.json` with a fresh `lastUpdated` — a live network- // read inside a suite that is supposed to be hermetic. It hid itself by- // RACING: a sibling file that leaves a sticky empty-catalog override lets the- // process exit before the ~2s fetch resolves, so whether the leak appeared- // depended on which files ran alongside it.- //- // Returning `disabled` rather than `network` matters. A caller that logs- // "the catalog could not be reached" when nobody tried to reach it sends the- // reader to debug their connection.- if (catalogWarmDisabled()) {- return { kind: "fetch_failed", reason: "disabled" };- }+ if (catalogWarmDisabled()) return { kind: "fetch_failed", reason: "disabled" };- // ── Page the catalog, pinned to one generation ───────────────────────────- //- // NOTHING below touches `_memCache` or the disk file until every page AND the- // plans document have been read successfully from the SAME revision. A- // partial catalog is worse than a stale one: a model missing because its page- // never arrived is indistinguishable from a model the catalog does not serve,- // and the second reading silently drops a working route.const entries: SlimModelEntry[] = [];- let revision: string | undefined;+ let generationId: string | undefined;+ let generatedAt: string | undefined;+ let cursor: string | undefined;let pages = 0;- let offset = 0;+ const seenCursors = new Set<string>();+ let expectedTotal: number | undefined;for (;;) {- const url = buildCatalogPageUrl(catalogUrl(), offset, CATALOG_PAGE_LIMIT, revision);- const result = await fetchCatalogPage(url, timeoutMs);+ const result = await fetchEnvelope<ModelsPageData>(+ buildCatalogPageUrl(catalogUrl(), cursor, CATALOG_PAGE_LIMIT, generationId),+ 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,- };+ 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.- return {- kind: "fetch_failed",- reason: pages === 0 ? result.reason : "incomplete",- };+ return { kind: "fetch_failed", reason: pages === 0 ? result.reason : "incomplete" };}- const { page } = result;- if (!Array.isArray(page.models)) return { kind: "fetch_failed", reason: "empty" };-- if (pages === 0) {- // Pin to whatever generation served page 1. When the deployment predates- // revision headers this stays undefined and the pages are simply- // unpinned — the previous behaviour, not a failure.- revision = result.revision;- if (page.models.length === 0) return { kind: "fetch_failed", reason: "empty" };- } else if (revision && result.revision && result.revision !== revision) {- // The generation rolled over mid-refresh. The pages in hand describe two- // different snapshots and must not be stitched together.- return { kind: "fetch_failed", reason: "revision_mismatch" };+ const { envelope } = result;+ if (generationId === undefined) {+ generationId = envelope.generationId;+ generatedAt = envelope.generatedAt;+ } else if (envelope.generationId !== generationId) {+ return { kind: "fetch_failed", reason: "generation_mismatch" };+ }+ if (+ envelope.data.mode !== "slim" ||+ !Array.isArray(envelope.data.models) ||+ !envelope.data.models.every(isSlimModelEntry)+ ) {+ return { kind: "fetch_failed", reason: pages === 0 ? "empty" : "incomplete" };+ }+ if (!Number.isSafeInteger(envelope.data.total) || envelope.data.total < 0) {+ return { kind: "fetch_failed", reason: "incomplete" };+ }+ if (expectedTotal === undefined) expectedTotal = envelope.data.total;+ else if (envelope.data.total !== expectedTotal) {+ return { kind: "fetch_failed", reason: "incomplete" };}- entries.push(...page.models);+ entries.push(...envelope.data.models);pages++;-- if (page.hasMore !== true) break;-- // `hasMore` with an empty page cannot make progress. Believing the flag- // would spin until MAX_CATALOG_PAGES; believing the page would silently- // truncate. Neither is a catalog, so refuse both.- if (page.models.length === 0) return { kind: "fetch_failed", reason: "incomplete" };-- offset += page.models.length;-- if (pages >= MAX_CATALOG_PAGES) {- // Our own stop condition, reached while the server still claims more.+ const nextCursor = envelope.data.nextCursor;+ if (!nextCursor) break;+ if (seenCursors.has(nextCursor) || pages >= MAX_CATALOG_PAGES) {return { kind: "fetch_failed", reason: "incomplete" };}+ seenCursors.add(nextCursor);+ cursor = nextCursor;}- if (entries.length === 0) return { kind: "fetch_failed", reason: "empty" };+ if (!generationId || !generatedAt || entries.length === 0) {+ return { kind: "fetch_failed", reason: "empty" };+ }+ if (+ entries.length !== expectedTotal ||+ new Set(entries.map((entry) => entry.modelId)).size !== entries.length+ ) {+ return { kind: "fetch_failed", reason: "incomplete" };+ }- // Plans are read AFTER the models and pinned to the same generation, so the- // `modelDescriptions` map joins against the exact snapshot in `entries`.- // Fetching it concurrently (as this once did) cannot be pinned at all: the- // revision is only known once page 1 has answered.- const plans = await fetchSubscriptionPlans(timeoutMs, revision);+ const planResult = await fetchSubscriptionPlans(timeoutMs, generationId);+ if (!planResult.ok) {+ if (planResult.reason === "incompatible") {+ return { kind: "incompatible", serverContractVersion: planResult.serverContractVersion };+ }+ return { kind: "fetch_failed", reason: planResult.reason };+ }- // Build the backward-compat models array BEFORE mutating shared state, so a- // throw below leaves _memCache and the disk file untouched.- const backwardCompatModels: Array<{ id: string }> = [];- for (const entry of entries) {+ const models = entries.flatMap((entry) => {const id = externalIdFor(entry, "openrouter");- if (id) backwardCompatModels.push({ id });- }+ return id ? [{ id }] : [];+ });+ const cache: DiskCacheV3 = {+ version: 3,+ lastUpdated: generatedAt,+ entries,+ models,+ plans: planResult.plans,+ catalogGenerationId: generationId,+ };- // 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 ──────────────────────────────────────────────────────────────+ writeAllModelsCache(cache, options.cachePath);_memCache = entries;- writeAllModelsCache(- {- entries,- models: backwardCompatModels,- ...(plans !== undefined ? { plans } : {}),- ...(revision !== undefined ? { catalogRevision: revision } : {}),- },- options.cachePath- );-- // Short-circuit the proxy-server background warm._warmPromise = Promise.resolve();-- 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;- }+ return {+ kind: "refreshed",+ modelCount: entries.length,+ catalogGenerationId: generationId,+ pages,+ };}-/**- * 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,- revision?: string-): Promise<CachedSubscriptionPlan[] | undefined> {- try {- const url = new URL(plansUrl());- // Same generation as the model pages, so `modelDescriptions` resolves- // against the rows actually in hand rather than a newer snapshot's.- if (revision) url.searchParams.set("revision", revision);- const response = await fetch(url.toString(), {- signal: AbortSignal.timeout(timeoutMs),- });- 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;+ generationId: string+): Promise<+ | { ok: true; plans: CachedSubscriptionPlan[] }+ | FetchFailure+ | { ok: false; reason: "empty" | "generation_mismatch" | "incomplete" }+> {+ const plans: CachedSubscriptionPlan[] = [];+ let cursor: string | undefined;+ let pages = 0;+ const seenCursors = new Set<string>();+ let expectedTotal: number | undefined;++ for (;;) {+ const result = await fetchEnvelope<PlansPageData>(+ buildCatalogPageUrl(plansUrl(), cursor, 100, generationId),+ timeoutMs+ );+ if (!result.ok) return result;+ if (result.envelope.generationId !== generationId) {+ return { ok: false, reason: "generation_mismatch" };}- const data = (await response.json()) as {- plans?: CachedSubscriptionPlan[];- contractVersion?: number;- };- const envelope = parseContractEnvelope(data);- if (isIncompatibleContractVersion(envelope.contractVersion)) {- recordIncompatibility(envelope);- return undefined;+ if (+ !Array.isArray(result.envelope.data.plans) ||+ !result.envelope.data.plans.every(isCachedSubscriptionPlan)+ ) {+ return { ok: false, reason: plans.length === 0 ? "empty" : "incomplete" };}- return Array.isArray(data.plans) ? data.plans : undefined;- } catch {- return undefined;+ if (!Number.isSafeInteger(result.envelope.data.total) || result.envelope.data.total < 0) {+ return { ok: false, reason: "incomplete" };+ }+ if (expectedTotal === undefined) expectedTotal = result.envelope.data.total;+ else if (result.envelope.data.total !== expectedTotal) {+ return { ok: false, reason: "incomplete" };+ }+ plans.push(...result.envelope.data.plans);+ pages++;+ const nextCursor = result.envelope.data.nextCursor;+ if (!nextCursor) break;+ if (seenCursors.has(nextCursor) || pages >= MAX_CATALOG_PAGES) {+ return { ok: false, reason: "incomplete" };+ }+ seenCursors.add(nextCursor);+ cursor = nextCursor;+ }++ if (plans.length === 0) return { ok: false, reason: "empty" };+ if (+ plans.length !== expectedTotal ||+ new Set(plans.map((plan) => plan.id)).size !== plans.length+ ) {+ return { ok: false, reason: "incomplete" };}+ return { ok: true, plans };}-/**- * 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 }- : {}),+function startCatalogWarm(): Promise<void> {+ if (_warmPromise) return _warmPromise;+ const promise = refreshCatalog(8000).then((result) => {+ if (result.kind !== "refreshed" && _warmPromise === promise) _warmPromise = null;});- return { kind: "incompatible", serverContractVersion: envelope.contractVersion };+ _warmPromise = promise;+ return promise;}-/** Fire-and-forget warm. Failures fall through to the disk-read fallback. */export async function warmCatalog(): Promise<void> {- if (!_warmPromise) {- _warmPromise = refreshCatalog(8000).then(() => undefined);- }- await _warmPromise;+ await startCatalogWarm();}-/**- * Wait for the catalog to be usable, bounded by `timeoutMs`. Never throws —- * on timeout the caller proceeds with whatever the disk cache holds.- */export async function ensureCatalogReady(timeoutMs = 5000): Promise<void> {- if (isCatalogWarm()) return;-- if (!_warmPromise) {- _warmPromise = refreshCatalog(8000).then(() => undefined);- }-+ if (isCatalogWarm() || (readAllModelsCache()?.entries.length ?? 0) > 0) return;await Promise.race([- _warmPromise,+ startCatalogWarm(),new Promise<void>((resolve) => setTimeout(resolve, timeoutMs)),]);}diff --git a/packages/cli/src/providers/catalog-compatibility.test.ts b/packages/cli/src/providers/catalog-compatibility.test.tsdeleted file mode 100644index d4b709a2..00000000--- a/packages/cli/src/providers/catalog-compatibility.test.ts+++ /dev/null@@ -1,131 +0,0 @@-import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";-import { tmpdir } from "node:os";-import { join } from "node:path";-import {- type CatalogIncompatibility,- SUPPORTED_CONTRACT_VERSION,- _resetCatalogCompatibilityForTest,- clearCatalogIncompatibility,- markCatalogIncompatible,- parseContractEnvelope,- readCatalogIncompatibility,-} from "./catalog-compatibility.js";--let tempDir = "";--beforeEach(() => {- tempDir = mkdtempSync(join(tmpdir(), "claudish-catalog-compatibility-"));- _resetCatalogCompatibilityForTest();-});--afterEach(() => {- _resetCatalogCompatibilityForTest();- rmSync(tempDir, { recursive: true, force: true });- tempDir = "";-});--describe("parseContractEnvelope", () => {- test("reads the frozen backend envelope with a top-level version and nested minimum", () => {- expect(- parseContractEnvelope({- contractVersion: SUPPORTED_CONTRACT_VERSION + 1,- error: {- code: "catalog_client_upgrade_required",- message: "Upgrade required",- minimumContractVersion: SUPPORTED_CONTRACT_VERSION + 1,- },- })- ).toEqual({- contractVersion: SUPPORTED_CONTRACT_VERSION + 1,- minimumContractVersion: SUPPORTED_CONTRACT_VERSION + 1,- });- });-- test("returns an unknown version when the body declares neither envelope field", () => {- expect(parseContractEnvelope({ models: [] })).toEqual({ contractVersion: null });- });-- test("returns an unknown version for null and non-object bodies", () => {- for (const body of [null, undefined, "not-json", 3, true]) {- expect(parseContractEnvelope(body)).toEqual({ contractVersion: null });- }- });-});--describe("catalog incompatibility sentinel", () => {- test("keeps the process blocked in memory when the disk write fails", () => {- const fileWhereDirectoryIsRequired = join(tempDir, "not-a-directory");- writeFileSync(fileWhereDirectoryIsRequired, "blocks mkdir", "utf8");- const unwritableSentinel = join(fileWhereDirectoryIsRequired, "catalog-incompatible.json");- const unrelatedMissingPath = join(tempDir, "missing", "catalog-incompatible.json");-- markCatalogIncompatible(- {- serverContractVersion: SUPPORTED_CONTRACT_VERSION + 1,- minimumContractVersion: SUPPORTED_CONTRACT_VERSION + 1,- },- unwritableSentinel- );-- expect(existsSync(unwritableSentinel)).toBe(false);- expect(readCatalogIncompatibility(unrelatedMissingPath)).toMatchObject({- serverContractVersion: SUPPORTED_CONTRACT_VERSION + 1,- minimumContractVersion: SUPPORTED_CONTRACT_VERSION + 1,- });- });-- test("memoizes the first disk read for the supplied path", () => {- const sentinelPath = join(tempDir, "catalog-incompatible.json");- const firstRecord: CatalogIncompatibility = {- detectedAt: "2026-09-10T00:00:00.000Z",- serverContractVersion: 3,- minimumContractVersion: 3,- };- const replacementRecord: CatalogIncompatibility = {- detectedAt: "2026-09-10T01:00:00.000Z",- serverContractVersion: 4,- minimumContractVersion: 4,- };- writeFileSync(sentinelPath, JSON.stringify(firstRecord), "utf8");-- expect(readCatalogIncompatibility(sentinelPath)).toEqual(firstRecord);- writeFileSync(sentinelPath, JSON.stringify(replacementRecord), "utf8");- expect(readCatalogIncompatibility(sentinelPath)).toEqual(firstRecord);- });-- test("reset clears both the in-memory flag and the memoized disk read", () => {- const blocker = join(tempDir, "reset-blocker");- writeFileSync(blocker, "blocks mkdir", "utf8");- const unwritableSentinel = join(blocker, "catalog-incompatible.json");- const missingPath = join(tempDir, "missing-after-reset.json");- markCatalogIncompatible({ serverContractVersion: 3 }, unwritableSentinel);-- _resetCatalogCompatibilityForTest();- expect(readCatalogIncompatibility(missingPath)).toBeNull();-- const memoPath = join(tempDir, "memoized-before-reset.json");- const record: CatalogIncompatibility = {- detectedAt: "2026-09-10T02:00:00.000Z",- serverContractVersion: 3,- };- writeFileSync(memoPath, JSON.stringify(record), "utf8");- expect(readCatalogIncompatibility(memoPath)).toEqual(record);- rmSync(memoPath);-- _resetCatalogCompatibilityForTest();- expect(readCatalogIncompatibility(memoPath)).toBeNull();- });-- test("clear removes the supplied sentinel path and clears its cached value", () => {- const sentinelPath = join(tempDir, "custom", "catalog-incompatible.json");- markCatalogIncompatible({ serverContractVersion: 3 }, sentinelPath);- expect(existsSync(sentinelPath)).toBe(true);- expect(readCatalogIncompatibility(sentinelPath)).not.toBeNull();-- clearCatalogIncompatibility(sentinelPath);-- expect(existsSync(sentinelPath)).toBe(false);- expect(readCatalogIncompatibility(sentinelPath)).toBeNull();- });-});diff --git a/packages/cli/src/providers/catalog-compatibility.ts b/packages/cli/src/providers/catalog-compatibility.tsdeleted file mode 100644index 7e74b58a..00000000--- a/packages/cli/src/providers/catalog-compatibility.ts+++ /dev/null@@ -1,453 +0,0 @@-/**- * 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 record is RE-JUDGED on every read, never merely read back- *- * What is persisted is not a fact about the world. It is a RELATIONSHIP between- * two versions — what the server was serving, and what the build that met it- * could read — and persisting a relationship only freezes one half of it. The- * other half, {@link SUPPORTED_CONTRACT_VERSION}, changes underneath the file- * the moment `claudish update` runs.- *- * Keyed on presence alone, a record written by a v2 build against a v3 server- * still fires on the v3 build shipped to end it, and- * {@link catalogIncompatibilityMessage} then reads "the catalog serves contract- * version 3; this build reads version 3 ... run `claudish update`" — naming the- * remedy the user has just applied. That is a permanent brick delivered by the- * release meant to fix the problem, and it needs no network to happen. So every- * read re-evaluates the record against the CURRENT constant- * ({@link isSentinelStale}) and drops it once this build has caught up.- *- * ## 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;- /**- * The {@link SUPPORTED_CONTRACT_VERSION} of the build that WROTE this record.- *- * Stamped by {@link markCatalogIncompatible} like `detectedAt`, never supplied- * by a caller. It exists for the one case the server-side fields cannot- * decide: a 426 with no body records `serverContractVersion: null`, so the- * record says nothing about what the server wanted, and only the writer's own- * version can tell a later build whether the finding is about a build that no- * longer exists.- *- * Optional because a record written before this field existed is still a valid- * finding. Absent, it means "written by a build older than this scheme", which- * licenses no conclusion in either direction — see {@link isSentinelStale}.- */- clientContractVersion?: number;-}--/** Where the sentinel lives. Sibling of `~/.claudish/all-models.json`. */-export const CATALOG_INCOMPATIBLE_PATH = join(homedir(), ".claudish", "catalog-incompatible.json");--/**- * The sentinel path in effect: `CLAUDISH_CATALOG_INCOMPATIBLE_PATH` when set,- * otherwise {@link CATALOG_INCOMPATIBLE_PATH}.- *- * A TEST seam, set for the whole run by `scripts/guard-real-config.ts`. It is- * read per call rather than at import, so it takes effect whenever it is set.- * Without it, every default-path read in a test reaches the developer's real- * file — and once a machine has run a build against a v3 catalog, that file- * exists and says "incompatible". Measured 2026-09-18: 25 tests across- * catalog-warm, model-catalog and the context-window suite failed on exactly- * that, while CI, whose home directory never holds the file, stayed green.- */-export function catalogIncompatiblePath(): string {- const override = process.env.CLAUDISH_CATALOG_INCOMPATIBLE_PATH;- return override !== undefined && override.length > 0 ? override : CATALOG_INCOMPATIBLE_PATH;-}--/**- * 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.- *- * `detectedAt` and `clientContractVersion` are stamped here rather than passed- * in: both describe the act of recording, not the response, and a caller that- * could set `clientContractVersion` could write a record that outlives its own- * staleness test.- *- * @param info What the RESPONSE said. Everything else is stamped here.- * @param path Override the sentinel path. Only tests should pass this.- */-export function markCatalogIncompatible(- info: Omit<CatalogIncompatibility, "detectedAt" | "clientContractVersion">,- path: string = catalogIncompatiblePath()-): void {- const record: CatalogIncompatibility = {- detectedAt: new Date().toISOString(),- serverContractVersion: info.serverContractVersion,- clientContractVersion: SUPPORTED_CONTRACT_VERSION,- ...(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.- *- * Presence is not the whole answer, though: a record this build has outgrown is- * dropped and deleted here, before any caller sees it ({@link isSentinelStale}).- * That judgement applies to the FILE only. `_memFlag` was set by a response this- * very process read off the wire — a live observation, not persisted state — and- * a 426 outranks any version arithmetic we could do against it.- *- * @param path Override the sentinel path. Only tests should pass this.- */-export function readCatalogIncompatibility(- path: string = catalogIncompatiblePath()-): 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.- }-- if (value !== null && isSentinelStale(value)) {- // Delete as well as ignore, so the next process does no work at all and the- // user never trips over a file describing a problem they no longer have.- // Best-effort, like every other fs call here; the read-time test is what- // actually protects them, the removal is housekeeping. This also parks the- // `null` in `_fileMemo`, so the whole check runs at most once per process.- clearCatalogIncompatibility(path);- return null;- }-- _fileMemo = { path, value };- return value;-}--/**- * Has this build caught up with what the record describes?- *- * The trap, stated once: persisted state that describes a RELATIONSHIP between- * two versions must be re-evaluated against the current version, never merely- * read back. Only the server's half of this record is frozen on disk; ours moves- * every time the user updates. See the header section on re-judging.- *- * Three questions, ordered by how much each one actually knows:- *- * 1. **Did the server name a floor we are still below?** Then no amount of- * other evidence matters — the server has said in as many words that it will- * not serve this build. Decisive, and it cannot brick: a build at or above- * the floor never reaches this branch.- *- * 2. **Did the server name the version it was serving?** Then judge by that- * alone: `<=` ours means we now read what it was serving, so the finding is- * spent. `>` ours means we still cannot, and the message stays true and- * actionable ("publishes 4, this build reads 3"). Note this deliberately- * answers the question WITHOUT consulting the writer's version — a record- * saying "server 4" written by a v2 build still applies to this v3 build,- * and clearing it on the writer's age alone would hand a stale v2 cache to- * bare-name routing, which is the mis-billing this module exists to stop.- *- * 3. **Nothing on the wire to judge** (a body-less 426 records `null` for both- * server fields). Then judge the WRITER: a record from a build that read an- * OLDER contract than we do describes a client that no longer exists, and- * nothing else will ever clear it — the updated user who is offline, or whom- * the server has since started answering, would carry it forever. Strictly- * less than, so the ordinary "same build, still too old" record keeps firing.- *- * An absent `clientContractVersion` (a record from before that field existed)- * falls out of question 3 as "not stale": unknown, so assume nothing. Question 2- * is then the only thing that can clear it, which is exactly the pre-existing- * behaviour for those records.- */-function isSentinelStale(record: CatalogIncompatibility): boolean {- if (- typeof record.minimumContractVersion === "number" &&- record.minimumContractVersion > SUPPORTED_CONTRACT_VERSION- ) {- return false;- }-- if (record.serverContractVersion !== null) {- return record.serverContractVersion <= SUPPORTED_CONTRACT_VERSION;- }-- if (typeof record.clientContractVersion === "number") {- return record.clientContractVersion < SUPPORTED_CONTRACT_VERSION;- }-- return false;-}--/** 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 }- : {}),- // Carried through only when the file really has it. Defaulting it to- // anything would be a lie about which build wrote the record, and- // `isSentinelStale` reads a missing field as "unknown" on purpose.- ...(typeof data.clientContractVersion === "number"- ? { clientContractVersion: data.clientContractVersion }- : {}),- };-}--/**- * Forget the finding — the server answered in a contract this build reads.- *- * Called on every fully successful refresh, which is one of the two ways the- * sentinel heals: `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. That route needs a network- * round trip, which is why it is not the only one — {@link readCatalogIncompatibility}- * also clears through here the moment the RECORD shows this build has caught up,- * offline or not. Never throws.- *- * @param path Override the sentinel path. Only tests should pass this.- */-export function clearCatalogIncompatibility(path: string = catalogIncompatiblePath()): 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/catalog-query.test.ts b/packages/cli/src/providers/catalog-query.test.tsindex 7da23147..3b89b0dd 100644--- a/packages/cli/src/providers/catalog-query.test.ts+++ b/packages/cli/src/providers/catalog-query.test.ts@@ -12,12 +12,12 @@** Mock strategy mirrors `catalog-warm.test.ts` — `mock.module` swaps the* `./all-models-cache.js` module so `readAllModelsCache()` returns a synthetic- * `DiskCacheV2` (or null) configured per-test. No real disk I/O.+ * `DiskCacheV3` (or null) configured per-test. No real disk I/O.*/import { afterAll, beforeAll, beforeEach, describe, expect, mock, test } from "bun:test";import { existsSync, unlinkSync, writeFileSync } from "node:fs";-import type { DiskCacheV2, SlimModelEntry } from "./all-models-cache.js";+import type { DiskCacheV3, SlimModelEntry } from "./all-models-cache.js";// Value import captured BEFORE the mock.module below so afterAll can restore// the REAL module. mock.module is PROCESS-GLOBAL and bleeds across files, so// without this restore the stub here breaks the sibling all-models-cache.test@@ -42,7 +42,7 @@ const __realAllModelsCacheExports = { ...__realAllModelsCache };const TEST_CACHE_PATH = "/tmp/test-all-models.json";-let mockReadResult: DiskCacheV2 | null = null;+let mockReadResult: DiskCacheV3 | null = null;mock.module("./all-models-cache.js", () => ({readAllModelsCache: () => mockReadResult,@@ -96,9 +96,11 @@ beforeEach(() => {* Build a synthetic disk cache from a list of slim entries. Wraps them in the* v2 envelope with a fixed `lastUpdated` so tests don't depend on `now`.*/-function diskCache(entries: SlimModelEntry[]): DiskCacheV2 {+function diskCache(entries: SlimModelEntry[]): DiskCacheV3 {return {- version: 2,+ catalogGenerationId: "test-generation",+ plans: [],+ version: 3,lastUpdated: "2026-05-08T12:00:00.000Z",entries,models: entries.map((e) => ({ id: e.modelId })),@@ -122,21 +124,21 @@ function standardEntries(): SlimModelEntry[] {{modelId: "claude-sonnet-4-6",aliases: ["sonnet", "claude-sonnet-4"],- sources: { "openrouter-api": { externalId: "anthropic/claude-sonnet-4" } },+supportsVision: true,contextWindow: 200000,},{modelId: "claude-haiku-4-6",aliases: ["haiku"],- sources: { "openrouter-api": { externalId: "anthropic/claude-haiku-4" } },+supportsVision: false,contextWindow: 200000,},{modelId: "claude-opus-4-7",aliases: ["opus"],- sources: { "openrouter-api": { externalId: "anthropic/claude-opus-4" } },+supportsVision: true,contextWindow: 200000,},diff --git a/packages/cli/src/providers/catalog-route-bindings.test.ts b/packages/cli/src/providers/catalog-route-bindings.test.tsnew file mode 100644index 00000000..c45bb58e--- /dev/null+++ b/packages/cli/src/providers/catalog-route-bindings.test.ts@@ -0,0 +1,106 @@+import { afterAll, describe, expect, test } from "bun:test";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { type DiskCacheV3, writeAllModelsCache } from "./all-models-cache.js";+import { resolveExternalId } from "./catalog-client.js";+import { catalogRouteForProvider, providerForCatalogRoute } from "./catalog-route-bindings.js";++const subscriptionBindings = [+ ["native-anthropic", "anthropic", "claude-code-subscription"],+ ["openai-codex", "openai", "codex-subscription"],+ ["kimi-coding", "moonshotai", "kimi-code-subscription"],+ ["glm-coding", "z-ai", "glm-coding-subscription"],+ ["grok-subscription", "x-ai", "supergrok-subscription"],+ ["minimax-coding", "minimax", "coding-plan-subscription"],+ ["sakana-subscription", "sakana", "fugu-subscription"],+ ["devin", "cognition", "devin-subscription"],+ ["antigravity", "google", "antigravity-subscription"],+ ["qwen-coding", "qwen", "modelstudio-coding-plan"],+ ["qwen-token-plan", "qwen", "qwencloud-token-plan"],+ ["opencode-zen-go", "opencode", "go-subscription"],+ ["ollamacloud", "ollama", "cloud"],+] as const;++const gatewayBindings = [+ ["openrouter", "openrouter", "gateway"],+ ["together", "together-ai", "gateway"],+ ["fireworks", "fireworks", "gateway"],+ ["poe", "poe", "gateway"],+ ["vertex", "vertex", "google-cloud"],+] as const;++describe("v3 route bindings", () => {+ for (const [provider, routeId, routeProfileId] of [...subscriptionBindings, ...gatewayBindings]) {+ test(`${provider} executes only ${routeId}/${routeProfileId}`, () => {+ const route = { routeId, routeProfileId };+ expect(catalogRouteForProvider(provider)).toEqual(route);+ expect(providerForCatalogRoute(route)).toBe(provider);+ });+ }++ test("the three Alibaba products have isolated route profiles", () => {+ expect(catalogRouteForProvider("qwen-payg")).toEqual({+ routeId: "qwen",+ routeProfileId: "dashscope-direct",+ });+ expect(+ providerForCatalogRoute({ routeId: "qwen", routeProfileId: "unrecognised" })+ ).toBeUndefined();+ });+});++const translations = [+ ["ollamacloud", "ollama", "cloud", "deepseek-v4.1-flash", "deepseek-v4.1-flash:cloud"],+ ["minimax", "minimax", "direct-api", "minimax-m3", "MiniMax-M3"],+ ["opencode-zen", "opencode", "zen", "gpt-6-astra", "gpt-6-astra"],+ ["anthropic", "anthropic", "direct-api", "claude-opus-5", "claude-opus-5"],+ ["x-ai", "x-ai", "direct-api", "grok-4.6", "grok-4.6"],+ ["deepseek", "deepseek", "direct-api", "deepseek-v4.1-flash", "deepseek-flash"],+ ["openrouter", "openrouter", "gateway", "minimax-m3", "minimax/minimax-m3"],+ ["together", "together-ai", "gateway", "minimax-m3", "minimaxai/MiniMax-M3"],+ ["fireworks", "fireworks", "gateway", "minimax-m3", "accounts/fireworks/models/minimax-m3"],+ ["poe", "poe", "gateway", "minimax-m3", "MiniMax-M3"],+ ["vertex", "vertex", "google-cloud", "minimax-m3", "publishers/custom/models/minimax-m3"],+ ["qwen-coding", "qwen", "modelstudio-coding-plan", "qwen3.7-plus", "coding-wire"],+ ["qwen-token-plan", "qwen", "qwencloud-token-plan", "qwen3.7-plus", "token-wire"],+ ["qwen-payg", "qwen", "dashscope-direct", "qwen3.7-plus", "payg-wire"],+] as const;++describe("exact route wire IDs", () => {+ const dir = mkdtempSync(join(tmpdir(), "claudish-route-v3-"));+ const path = join(dir, "all-models.json");+ const entries = [...new Set(translations.map((row) => row[3]))].map((modelId) => ({+ modelId,+ aliases: [],+ aggregators: translations+ .filter((row) => row[3] === modelId)+ .map(([, routeId, routeProfileId, , externalModelId]) => ({+ sourceProviderId: routeId,+ sourceCollectorId: "fixture",+ confidence: "api_official" as const,+ routeStatus: "mapped" as const,+ route: { routeId, routeProfileId },+ externalModelId,+ })),+ }));+ const cache: DiskCacheV3 = {+ version: 3,+ catalogGenerationId: "fixture-generation",+ lastUpdated: new Date().toISOString(),+ entries,+ models: [],+ plans: [],+ };+ writeAllModelsCache(cache, path);++ for (const [provider, , , modelId, externalModelId] of translations) {+ test(`${provider} sends ${externalModelId} for ${modelId}`, () => {+ expect(resolveExternalId(modelId, provider, path)).toBe(externalModelId);+ });+ }+ test("a sibling Alibaba wire ID cannot stand in for a missing route", () => {+ expect(resolveExternalId("qwen3.7-plus", "opencode-zen-go", path)).toBeNull();+ });+ afterAll(() => rmSync(dir, { recursive: true, force: true }));+});diff --git a/packages/cli/src/providers/catalog-route-bindings.ts b/packages/cli/src/providers/catalog-route-bindings.tsnew file mode 100644index 00000000..98126db4--- /dev/null+++ b/packages/cli/src/providers/catalog-route-bindings.ts@@ -0,0 +1,74 @@+export interface CatalogRouteBinding {+ routeId: string;+ routeProfileId: string;+}++/**+ * Transport bindings between Claudish providers and catalog v3 routes.+ * Model membership and wire IDs remain catalog data; this table only identifies+ * the transport adapter that can execute each canonical route.+ */+export const CATALOG_ROUTE_BINDINGS: Readonly<Record<string, CatalogRouteBinding>> = {+ "native-anthropic": { routeId: "anthropic", routeProfileId: "claude-code-subscription" },+ anthropic: { routeId: "anthropic", routeProfileId: "direct-api" },+ "openai-codex": { routeId: "openai", routeProfileId: "codex-subscription" },+ openai: { routeId: "openai", routeProfileId: "direct-api" },+ "kimi-coding": { routeId: "moonshotai", routeProfileId: "kimi-code-subscription" },+ kimi: { routeId: "moonshotai", routeProfileId: "direct-api" },+ moonshotai: { routeId: "moonshotai", routeProfileId: "direct-api" },+ "glm-coding": { routeId: "z-ai", routeProfileId: "glm-coding-subscription" },+ "z-ai": { routeId: "z-ai", routeProfileId: "direct-api" },+ "grok-subscription": { routeId: "x-ai", routeProfileId: "supergrok-subscription" },+ "x-ai": { routeId: "x-ai", routeProfileId: "direct-api" },+ "minimax-coding": { routeId: "minimax", routeProfileId: "coding-plan-subscription" },+ minimax: { routeId: "minimax", routeProfileId: "direct-api" },+ "sakana-subscription": { routeId: "sakana", routeProfileId: "fugu-subscription" },+ sakana: { routeId: "sakana", routeProfileId: "direct-api" },+ devin: { routeId: "cognition", routeProfileId: "devin-subscription" },+ antigravity: { routeId: "google", routeProfileId: "antigravity-subscription" },+ google: { routeId: "google", routeProfileId: "direct-api" },+ "qwen-coding": { routeId: "qwen", routeProfileId: "modelstudio-coding-plan" },+ "qwen-token-plan": { routeId: "qwen", routeProfileId: "qwencloud-token-plan" },+ "qwen-payg": { routeId: "qwen", routeProfileId: "dashscope-direct" },+ qwen: { routeId: "qwen", routeProfileId: "dashscope-direct" },+ "opencode-zen-go": { routeId: "opencode", routeProfileId: "go-subscription" },+ "opencode-zen": { routeId: "opencode", routeProfileId: "zen" },+ zen: { routeId: "opencode", routeProfileId: "zen" },+ ollamacloud: { routeId: "ollama", routeProfileId: "cloud" },+ openrouter: { routeId: "openrouter", routeProfileId: "gateway" },+ together: { routeId: "together-ai", routeProfileId: "gateway" },+ fireworks: { routeId: "fireworks", routeProfileId: "gateway" },+ poe: { routeId: "poe", routeProfileId: "gateway" },+ vertex: { routeId: "vertex", routeProfileId: "google-cloud" },+ deepseek: { routeId: "deepseek", routeProfileId: "direct-api" },+ mistralai: { routeId: "mistralai", routeProfileId: "direct-api" },+};++export function catalogRouteForProvider(provider: string): CatalogRouteBinding | undefined {+ return CATALOG_ROUTE_BINDINGS[provider];+}++export function providerForCatalogRoute(+ route: CatalogRouteBinding | undefined+): string | undefined {+ if (!route) return undefined;+ for (const [provider, binding] of Object.entries(CATALOG_ROUTE_BINDINGS)) {+ if (binding.routeId === route.routeId && binding.routeProfileId === route.routeProfileId) {+ return provider;+ }+ }+ return undefined;+}++export function catalogRouteMatchesProvider(+ route: CatalogRouteBinding | undefined,+ provider: string+): boolean {+ const binding = catalogRouteForProvider(provider);+ return (+ route !== undefined &&+ binding !== undefined &&+ route.routeId === binding.routeId &&+ route.routeProfileId === binding.routeProfileId+ );+}diff --git a/packages/cli/src/providers/catalog-v3.ts b/packages/cli/src/providers/catalog-v3.tsnew file mode 100644index 00000000..7bb5b4e9--- /dev/null+++ b/packages/cli/src/providers/catalog-v3.ts@@ -0,0 +1,24 @@+export const CATALOG_V3_ACCEPT = "application/vnd.models-index.catalog+json;version=3";++export interface CatalogV3Envelope<T> {+ contractVersion: 3;+ generationId: string;+ generatedAt: string;+ data: T;+}++export function parseCatalogV3Envelope<T>(value: unknown): CatalogV3Envelope<T> | null {+ if (!value || typeof value !== "object") return null;+ const envelope = value as Record<string, unknown>;+ if (+ envelope.contractVersion !== 3 ||+ typeof envelope.generationId !== "string" ||+ envelope.generationId.length === 0 ||+ typeof envelope.generatedAt !== "string" ||+ !envelope.data ||+ typeof envelope.data !== "object"+ ) {+ return null;+ }+ return envelope as unknown as CatalogV3Envelope<T>;+}diff --git a/packages/cli/src/providers/custom-endpoints-loader.test.ts b/packages/cli/src/providers/custom-endpoints-loader.test.tsindex 89cb48fa..d550942f 100644--- a/packages/cli/src/providers/custom-endpoints-loader.test.ts+++ b/packages/cli/src/providers/custom-endpoints-loader.test.ts@@ -699,7 +699,7 @@ describe("custom-endpoints-loader", () => {test("anthropic-transport + streamFormat=anthropic-sse: propages to transport.overrideStreamFormat()", () => {loadCustomEndpoints(makeConfig({- "qwen-token-plan": {+ "test-anthropic-sse": {kind: "complex",displayName: "Qwen Cloud Token Plan",transport: "anthropic",@@ -711,7 +711,7 @@ describe("custom-endpoints-loader", () => {}));- const profile = getRuntimeProfiles().get("qwen-token-plan");+ const profile = getRuntimeProfiles().get("test-anthropic-sse");expect(profile).toBeDefined();const handler = profile!.createHandler(makeCtx("qwen3.8-max"))!;expect(handler).toBeDefined();diff --git a/packages/cli/src/providers/default-routing-rules.test.ts b/packages/cli/src/providers/default-routing-rules.test.tsindex c3c48ba8..ad3ba4b3 100644--- a/packages/cli/src/providers/default-routing-rules.test.ts+++ b/packages/cli/src/providers/default-routing-rules.test.ts@@ -1,3 +1,4 @@+import { catalogRouteForProvider } from "./catalog-route-bindings.js";/*** Unit tests for providers/default-routing-rules.ts*@@ -15,7 +16,7 @@ import { describe, expect, test } from "bun:test";import { mkdtempSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import { type DiskCacheV2, writeAllModelsCache } from "./all-models-cache.js";+import { type DiskCacheV3, writeAllModelsCache } from "./all-models-cache.js";import {DEFAULT_ROUTING_RULES,validateDefaultRoutingRules,@@ -28,57 +29,68 @@ function makeTempCatalog(model: {modelId: string;externalId?: string;- subscriptionPlans?: string[];+ subscriptionPlanIds?: string[];},/** Plan names to mark as active subscription plans in the catalog (defaults to the model's own plans). */- plans: string[] = model.subscriptionPlans ?? [],+ plans: string[] = model.subscriptionPlanIds ?? [],routingProviderByPlan: Record<string, string> = {}): { path: string; cleanup: () => void } {const dir = mkdtempSync(join(tmpdir(), "claudish-routing-test-"));const path = join(dir, "all-models.json");- const entries: DiskCacheV2["entries"] = [];+ const entries: DiskCacheV3["entries"] = [];// Plan-owner entries: a provider is only treated as a subscription plan if- // some catalog entry lists it in subscriptionPlans[]. Add markers so tests can+ // some catalog entry lists it in subscriptionPlanIds[]. Add markers so tests can// model the "model is not in this plan" drop path without duplicating real// plan members.for (const plan of plans) {entries.push({modelId: `${plan}-plan-marker`,aliases: [],- sources: {},- subscriptionPlans: [plan],- aggregators: [{ provider: plan, externalId: "any", confidence: "scrape_verified" as const }],++ subscriptionPlanIds: [plan],+ aggregators: [+ {+ sourceCollectorId: "test",+ routeStatus: "mapped",+ route: catalogRouteForProvider(plan),+ sourceProviderId: plan,+ externalModelId: "any",+ confidence: "scrape_verified" as const,+ },+ ],});}entries.push({modelId: model.modelId,aliases: [],- sources: {},- subscriptionPlans: model.subscriptionPlans ?? [],++ subscriptionPlanIds: model.subscriptionPlanIds ?? [],aggregators:- model.externalId && model.subscriptionPlans- ? model.subscriptionPlans.map((planId) => ({- provider: routingProviderByPlan[planId] ?? planId,- externalId: model.externalId!,+ model.externalId && model.subscriptionPlanIds+ ? model.subscriptionPlanIds.map((planId) => ({+ sourceProviderId: routingProviderByPlan[planId] ?? planId,+ sourceCollectorId: "test",+ routeStatus: "mapped" as const,+ route: catalogRouteForProvider(routingProviderByPlan[planId] ?? planId),+ externalModelId: model.externalId!,confidence: "scrape_verified" as const,})): undefined,});- const cache: DiskCacheV2 = {- version: 2,+ const cache: DiskCacheV3 = {+ catalogGenerationId: "test-generation",+ version: 3,lastUpdated: new Date().toISOString(),entries,models: [],plans: plans.map((plan) => ({id: plan,modelDiscovery: "catalog",- routing: {- providerUid: routingProviderByPlan[plan] ?? plan,- nativeModelProviders: [],- },+ routeStatus: "supported",+ route: catalogRouteForProvider(routingProviderByPlan[plan] ?? plan),})),};writeAllModelsCache(cache, path);@@ -125,7 +137,7 @@ describe("DEFAULT_ROUTING_RULES pattern matching", () => {const { path, cleanup } = makeTempCatalog({modelId: "grok-4.6",externalId: "grok-4.6",- subscriptionPlans: ["grok-subscription"],+ subscriptionPlanIds: ["grok-subscription"],});try {const [route] = buildRoutingChain(["grok-subscription"], "grok-4.6", path);@@ -177,7 +189,7 @@ describe("DEFAULT_ROUTING_RULES pattern matching", () => {{modelId: "kimi-k3",externalId: "k3",- subscriptionPlans: ["kimi-coding"],+ subscriptionPlanIds: ["kimi-coding"],},["kimi-coding"]);@@ -203,7 +215,7 @@ describe("DEFAULT_ROUTING_RULES pattern matching", () => {{modelId: "kimi-k3",externalId: "k3",- subscriptionPlans: ["kimi-coding"],+ subscriptionPlanIds: ["kimi-coding"],},["kimi-coding"]);@@ -252,22 +264,33 @@ describe("DEFAULT_ROUTING_RULES pattern matching", () => {expect(matched).toEqual(["glm-coding", "opencode-zen-go", "glm", "openrouter"]);});- test("'qwen3.7-plus' matches qwen3.* → [qwen-cloud, opencode-zen-go, qwen-payg, openrouter]", () => {+ test("'qwen3.7-plus' offers both Alibaba subscriptions before PAYG", () => {const matched = matchRoutingRule("qwen3.7-plus", DEFAULT_ROUTING_RULES);- expect(matched).toEqual(["qwen-cloud", "opencode-zen-go", "qwen-payg", "openrouter"]);+ expect(matched).toEqual([+ "qwen-coding",+ "qwen-token-plan",+ "opencode-zen-go",+ "qwen-payg",+ "openrouter",+ ]);});- test("'qwen3-coder-next' does not match the dotted Qwen Plan rule", () => {+ test("'qwen3-coder-next' offers the Coding Plan before PAYG", () => {const matched = matchRoutingRule("qwen3-coder-next", DEFAULT_ROUTING_RULES);- expect(matched).toEqual(["openrouter"]);- expect(matched).not.toContain("qwen-cloud");+ expect(matched).toEqual([+ "qwen-coding",+ "qwen-token-plan",+ "opencode-zen-go",+ "qwen-payg",+ "openrouter",+ ]);});- test("cross-vendor default chains never include qwen-cloud", () => {+ test("cross-vendor default chains never include qwen-token-plan", () => {for (const model of ["glm-4.6", "glm-5.2", "deepseek-v4-pro"]) {const matched = matchRoutingRule(model, DEFAULT_ROUTING_RULES);expect(matched).not.toBeNull();- expect(matched!).not.toContain("qwen-cloud");+ expect(matched!).not.toContain("qwen-token-plan");}});diff --git a/packages/cli/src/providers/default-routing-rules.ts b/packages/cli/src/providers/default-routing-rules.tsindex 9c601c84..e204b244 100644--- a/packages/cli/src/providers/default-routing-rules.ts+++ b/packages/cli/src/providers/default-routing-rules.ts@@ -18,7 +18,6 @@* - The `provider@model` rewrite syntax (see kimi-* below) is used when a* subscription endpoint expects a different model name than the direct API.*- * Migration plan §B.1 — Commit 4 of the model-catalog and routing redesign.*/import type { RoutingRules } from "../profile-config.js";import { PROVIDER_SHORTCUTS } from "./model-parser.js";@@ -49,17 +48,17 @@ export const DEFAULT_ROUTING_RULES: RoutingRules = {// xAI Grok: account-discovered subscription, direct API, then OpenRouter.// Subscription BEFORE metered, the same order every other split family uses- // (glm-coding before glm, qwen-cloud before qwen-payg). A user holding both a+ // (glm-coding before glm, qwen-token-plan before qwen-payg). A user holding both a// Grok subscription and an XAI_API_KEY must never be silently billed per token// for a model their plan already covers. Safe to put in the bare chain — and- // unlike Devin or Qwen Plan, which are explicit-access only — because these+ // unlike Devin or cross-vendor Alibaba plan models, which need explicit routing — because these// ids are xAI's own, so there is no other vendor's namespace to collide with."grok-*": ["grok-subscription", "x-ai", "openrouter"],// Kimi: the subscription endpoint speaks its own wire ids (kimi-for-coding,// kimi-for-coding-highspeed, k3, k3-256k) — NOT catalog names like// "kimi-k2.7-code". No model is pinned here: buildRoutingChain translates the- // catalog name to the plan's wire id via `subscriptionPlans[]` plan IDs,+ // catalog name to the plan's wire id via `subscriptionPlanIds[]` plan IDs,// cached `queryPlans.routing.providerUid`, and `aggregators[].externalId`.// It drops the kimi-coding candidate when the// plan doesn't include the model (e.g. kimi-k2.5) so it falls through to the@@ -67,8 +66,7 @@ export const DEFAULT_ROUTING_RULES: RoutingRules = {// model. `k3*` needs its own rule: it doesn't match `kimi-*`, and the catalog// alias would otherwise send bare `k3` to the paid OpenRouter listing.// `opencode-zen-go` sits between the vendor's own plan and the metered API on- // every family below — see "Zen Go placement" at the bottom of this table for- // why that is safe here but is NOT safe for qwen-cloud.+ // every family below, gated by catalog membership."kimi-*": ["kimi-coding", "opencode-zen-go", "kimi", "openrouter"],"k3*": ["kimi-coding", "opencode-zen-go", "kimi", "openrouter"],@@ -79,35 +77,15 @@ export const DEFAULT_ROUTING_RULES: RoutingRules = {// GLM: coding plan, Zen Go plan, direct, OpenRouter."glm-*": ["glm-coding", "opencode-zen-go", "glm", "openrouter"],- // Qwen Plan (Alibaba Model Studio subscription), then OpenRouter.+ // Alibaba Coding Plan, Token Plan, OpenCode Go, PAYG, then the aggregator fallback.// `globMatch` is a literal prefix/suffix split, so the "." is matched// literally: this claims the DOTTED names (qwen3.7-plus) and not the// hyphenated ones (qwen3-coder-next).//- // Hyphenated is NOT a synonym for "third-party name" — see the measured- // rosters in provider-definitions.ts's qwen-cloud note. Alibaba ships both- // conventions; the Token Plan this chain leads with just happens to serve- // only dotted ids, which is why the split lands correctly here. Extending- // this rule to `qwen3-*` is the same 400-dead-end hazard described for glm-*- // below, and needs a verified PAYG roster first.- //- // The plan ALSO serves glm-5.2 and deepseek-v4-*, but their chains are left- // untouched on purpose. Routing filters by CREDENTIAL availability, not by- // model availability — putting qwen-cloud in front of "glm-*" would send- // glm-4.6 to Alibaba on the strength of the plan key alone, earn a- // `400 Model not exist`, and stop there, because 400 is deliberately- // non-retryable in fallback-handler.ts. Cross-vendor access to the plan- // stays explicit: `[email protected]`.- //- // `qwen-payg` (Alibaba's metered dashscope-intl host) sits after the plan and- // the Go plan, exactly where `kimi` / `glm` / `minimax` sit in their own- // chains: subscription → Go plan → metered vendor API → aggregator. Its key- // is a DIFFERENT credential from the plan's (each Alibaba silo rejects the- // others'), so a user holding both is answered by the plan they already pay- // for, while a user holding only a PAYG key now reaches Alibaba at all —- // before this entry existed, the sole Qwen chain pointed at a host their key- // could never authenticate against.- "qwen3.*": ["qwen-cloud", "opencode-zen-go", "qwen-payg", "openrouter"],+ // Product discovery decides entitlement; names do not imply access to a+ // sibling Alibaba product.+ "qwen3.*": ["qwen-coding", "qwen-token-plan", "opencode-zen-go", "qwen-payg", "openrouter"],+ "qwen3-*": ["qwen-coding", "qwen-token-plan", "opencode-zen-go", "qwen-payg", "openrouter"],// Z.AI native models."z-ai-*": ["z-ai", "openrouter"],@@ -164,38 +142,9 @@ export const DEFAULT_ROUTING_RULES: RoutingRules = {// Pragmatic shim until Firebase aggregators[] coverage closes the gap."*-zen": ["opencode-zen"],- // ── Zen Go placement ──────────────────────────────────────────────────────- //- // `opencode-zen-go` appears above on kimi/glm/minimax/deepseek/qwen3/mimo/hy3- // because the Go plan serves all of those families, and without it a bare name- // skipped a subscription the user already pays for and was billed per-token by- // the vendor's metered API (or by OpenRouter, for mimo/hy3 which had no rule).- //- // Why this is safe where the same move is NOT safe for qwen-cloud (see the- // `qwen3.*` note above): the catalog join now drops known-unserved Go models.- // On a cold or legacy cache, `resolveSubscriptionRouting` remains `unknown`- // and the candidate is kept for every model in the family — including ones- // the plan does not serve. What- // happens next is the whole argument, and it is provider-specific:- //- // Zen Go, unserved model → 401 {"type":"ModelError","message":"Model X is- // not supported"} → RETRYABLE → chain falls- // through to the metered provider. Verified live- // 2026-08-06 against kimi-k2.7, glm-4.6,- // minimax-m2, deepseek-v3.2 and a nonsense id.- // Alibaba, unserved model → 400 "Model not exist" → NOT retryable → the- // chain STOPS and the user gets an error instead- // of a working provider.- //- // So the cost of a miss here is one wasted round-trip, not a dead request.- // That is also why the broad `gpt-*` and `grok-*` families are deliberately- // left alone: the Go plan carries only `gpt-5.6-luna` and `grok-4.5`, so- // adding it there would buy a subscription hit on one model in exchange for a- // wasted 401 on every other call in the family.- //- // Current caches get that answer by joining the `opencode-go` commercial plan- // ID to provider `opencode-zen-go`; no provider UID is stored in- // `subscriptionPlans[]`.+ // Zen Go is offered before metered routes for its supported families. The+ // plan's published membership and exact route mapping decide availability;+ // account discovery handles any additional account-specific access.// Catch-all: try OpenRouter (it covers most things). Users disable with// routing["*"] = [] for strict no-fallback mode, or replace with their owndiff --git a/packages/cli/src/providers/latest-opus.test.ts b/packages/cli/src/providers/latest-opus.test.tsindex b3abad3e..232b9aa3 100644--- a/packages/cli/src/providers/latest-opus.test.ts+++ b/packages/cli/src/providers/latest-opus.test.ts@@ -12,7 +12,7 @@ function catalogEntry(modelId: string, releaseDate?: string): SlimModelEntry {return {modelId,aliases: [],- sources: { test: { externalId: modelId } },+...(releaseDate === undefined ? {} : { releaseDate }),};}diff --git a/packages/cli/src/providers/model-availability.test.ts b/packages/cli/src/providers/model-availability.test.tsindex 429c9adf..0740f4fd 100644--- a/packages/cli/src/providers/model-availability.test.ts+++ b/packages/cli/src/providers/model-availability.test.ts@@ -1,4 +1,5 @@import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";+import { catalogRouteForProvider } from "./catalog-route-bindings.js";import { credentials } from "../auth/credentials/authority.js";import type { SlimModelEntry } from "./all-models-cache.js";@@ -8,8 +9,8 @@ import { invalidateModelDiscovery } from "./model-discovery.js";import type { ProviderDefinition } from "./provider-definitions.js";import { clearRuntimeRegistry, registerRuntimeProvider } from "./runtime-providers.js";-const CATALOG_PROVIDER = "catalog-primary";-const OTHER_CATALOG_PROVIDER = "catalog-secondary";+const CATALOG_PROVIDER = "openrouter";+const OTHER_CATALOG_PROVIDER = "fireworks";const DISCOVERY_PROVIDER = "availability-discovery-test";const realFetch = globalThis.fetch;@@ -23,10 +24,13 @@ function catalogEntry(return {modelId,aliases,- sources: { test: { externalId: modelId } },+aggregators: providers.map(({ provider, externalId }) => ({- provider,- externalId: externalId ?? modelId,+ sourceProviderId: provider,+ sourceCollectorId: "test",+ routeStatus: "mapped",+ route: catalogRouteForProvider(provider),+ externalModelId: externalId ?? modelId,confidence: "api_official",})),};diff --git a/packages/cli/src/providers/model-availability.ts b/packages/cli/src/providers/model-availability.tsindex 2900cf77..200facf6 100644--- a/packages/cli/src/providers/model-availability.ts+++ b/packages/cli/src/providers/model-availability.ts@@ -1,3 +1,4 @@+import { catalogRouteMatchesProvider } from "./catalog-route-bindings.js";/*** "Does provider P actually serve model M?" — answered from BOTH data sources.*@@ -13,7 +14,7 @@* Neither is sufficient alone. Measured 2026-08-18: the catalog's `aggregators[]`* vocabulary names 18 providers while claudish routes to 23, and the 10 it never* mentions are almost entirely the SUBSCRIPTION providers — `glm-coding`,- * `minimax-coding`, `qwen-cloud`, `sakana-subscription`, `devin`,+ * `minimax-coding`, `qwen-token-plan`, `sakana-subscription`, `devin`,* `opencode-zen-go`. That is not a catalog defect: a plan's contents are an* entitlement, so they were never in scope for a field describing marketplaces.*@@ -120,9 +121,13 @@ export async function providerServesModel((e) =>e.modelId.toLowerCase() === needle ||e.aliases.some((a) => a.toLowerCase() === needle) ||- (e.aggregators ?? []).some((a) => a.externalId?.toLowerCase() === needle)+ (e.aggregators ?? []).some((a) => a.externalModelId?.toLowerCase() === needle));if (!row) return "unknown";- return (row.aggregators ?? []).some((a) => a.provider === provider) ? "serves" : "unknown";+ return (row.aggregators ?? []).some(+ (a) => a.routeStatus === "mapped" && catalogRouteMatchesProvider(a.route, provider)+ )+ ? "serves"+ : "unknown";}diff --git a/packages/cli/src/providers/model-catalog.test.ts b/packages/cli/src/providers/model-catalog.test.tsindex 220909e6..0ac2b15f 100644--- a/packages/cli/src/providers/model-catalog.test.ts+++ b/packages/cli/src/providers/model-catalog.test.ts@@ -1,3 +1,4 @@+import { catalogRouteForProvider } from "./catalog-route-bindings.js";/*** Tests for `providers/model-catalog.ts` — the `CatalogClient` interface.*@@ -11,14 +12,21 @@import { describe, expect, mock, test } from "bun:test";import type { AggregatorEntry, ModelDoc } from "../model-loader.js";-import type { DiskCacheV2, SlimModelEntry } from "./all-models-cache.js";+import type { DiskCacheV3, SlimModelEntry } from "./all-models-cache.js";import { FIREBASE_CACHE_TTL_MS } from "./cache-ttl.js";import { createCatalogClient } from "./model-catalog.js";// ─── Fixture helpers ─────────────────────────────────────────────────────────function aggregator(provider: string, externalId: string): AggregatorEntry {- return { provider, externalId, confidence: "gateway_official" };+ return {+ sourceProviderId: provider,+ sourceCollectorId: "test",+ routeStatus: "mapped",+ route: catalogRouteForProvider(provider.toLowerCase()),+ externalModelId: externalId,+ confidence: "gateway_official",+ };}function slimEntry(@@ -29,7 +37,7 @@ function slimEntry(return {modelId,aliases,- sources: {},+aggregators,};}@@ -43,18 +51,22 @@ function modelDoc(modelId: string, provider: string, extra: Partial<ModelDoc> =};}-function freshCache(entries: SlimModelEntry[]): DiskCacheV2 {+function freshCache(entries: SlimModelEntry[]): DiskCacheV3 {return {- version: 2,+ catalogGenerationId: "test-generation",+ plans: [],+ version: 3,lastUpdated: new Date().toISOString(),entries,models: [],};}-function staleCache(entries: SlimModelEntry[]): DiskCacheV2 {+function staleCache(entries: SlimModelEntry[]): DiskCacheV3 {return {- version: 2,+ catalogGenerationId: "test-generation",+ plans: [],+ version: 3,// Twice the TTL — definitely expired.lastUpdated: new Date(Date.now() - 2 * FIREBASE_CACHE_TTL_MS).toISOString(),entries,@@ -87,7 +99,11 @@ describe("modelsByVendor", () => {expect(result.map((m) => m.modelId).sort()).toEqual(["gpt-5"]);// The kept model carries the grafted served-by aggregators (owner query// returns aggregators: null).- expect(result[0]?.aggregators?.some((a) => a.provider === "openai")).toBe(true);+ expect(+ result[0]?.aggregators?.some(+ (a) => a.route?.routeId === "openai" && a.route?.routeProfileId === "direct-api"+ )+ ).toBe(true);});test("owner path keeps a direct-API owner's models once the catalog indexes them", async () => {diff --git a/packages/cli/src/providers/model-catalog.ts b/packages/cli/src/providers/model-catalog.tsindex 157d8f98..b7ffe96d 100644--- a/packages/cli/src/providers/model-catalog.ts+++ b/packages/cli/src/providers/model-catalog.ts@@ -1,3 +1,4 @@+import { catalogRouteMatchesProvider, providerForCatalogRoute } from "./catalog-route-bindings.js";/*** CatalogClient — single entry point for all Firebase-backed model catalog* questions. Replaces the three independent slug maps and per-provider@@ -149,7 +150,10 @@ function aggregatorProviderSlugs(const slugs = new Set<string>();for (const entry of cache.entries) {for (const agg of entry.aggregators ?? []) {- if (agg.provider) slugs.add(agg.provider.toLowerCase());+ if (agg.routeStatus === "mapped") {+ const provider = providerForCatalogRoute(agg.route!);+ if (provider) slugs.add(provider.toLowerCase());+ }}}// Union with the seed: a provider claudish knows how to reach should not@@ -216,7 +220,7 @@ function filterToServedByProvider(const kept: CatalogModel[] = [];for (const model of models) {const slim = byId.get(model.modelId.toLowerCase());- const served = slim?.aggregators?.some((agg) => agg.provider.toLowerCase() === slug);+ const served = slim?.aggregators?.some((agg) => catalogRouteMatchesProvider(agg.route, slug));if (served) {kept.push({ ...model, aggregators: slim?.aggregators ?? model.aggregators });}@@ -316,7 +320,7 @@ export function createCatalogClient(deps: CatalogClientDeps = {}): CatalogClientif (aggregatorProviderSlugs(_readSlimCache).has(slug)) {const { entries } = readSlimCacheWithFreshness(_readSlimCache);const matches = entries.filter((entry) =>- entry.aggregators?.some((agg) => agg.provider.toLowerCase() === slug)+ entry.aggregators?.some((agg) => catalogRouteMatchesProvider(agg.route, slug)));return matches.map(slimEntryToCatalogModel);}diff --git a/packages/cli/src/providers/model-discovery.test.ts b/packages/cli/src/providers/model-discovery.test.tsindex 11afb43c..156a3467 100644--- a/packages/cli/src/providers/model-discovery.test.ts+++ b/packages/cli/src/providers/model-discovery.test.ts@@ -344,16 +344,16 @@ describe("model discovery cache and context lookup", () => {) as unknown as typeof fetch;await discoverProviderModels("kimi-coding");- await discoverProviderModels("qwen-cloud");+ await discoverProviderModels("qwen-token-plan");expect(getDiscoveryFailure("kimi-coding")?.kind).toBe("http-error");- expect(getDiscoveryFailure("qwen-cloud")?.kind).toBe("http-error");+ expect(getDiscoveryFailure("qwen-token-plan")?.kind).toBe("http-error");invalidateModelDiscovery("kimi-coding");expect(getDiscoveryFailure("kimi-coding")).toBeUndefined();- expect(getDiscoveryFailure("qwen-cloud")?.kind).toBe("http-error");+ expect(getDiscoveryFailure("qwen-token-plan")?.kind).toBe("http-error");invalidateModelDiscovery();- expect(getDiscoveryFailure("qwen-cloud")).toBeUndefined();+ expect(getDiscoveryFailure("qwen-token-plan")).toBeUndefined();});test("caches within the TTL and provider invalidation forces a refetch", async () => {diff --git a/packages/cli/src/providers/model-discovery.ts b/packages/cli/src/providers/model-discovery.tsindex db6e5b41..d8279369 100644--- a/packages/cli/src/providers/model-discovery.ts+++ b/packages/cli/src/providers/model-discovery.ts@@ -186,7 +186,7 @@ const _cache = new Map<string, { models: DiscoveredModel[]; expiresAt: number }>* behind a `--debug`-only log line. Callers could not tell "your API key was* rejected" from "this provider genuinely publishes no roster", so the picker* rendered a rejected credential as a free-text prompt, which reads as a- * feature rather than an error. (Measured on qwen-cloud: a 401 from Alibaba's+ * feature rather than an error. (Measured on qwen-token-plan: a 401 from Alibaba's* plan host was indistinguishable in the UI from a provider with no list.)** The kinds are ordered by what the user should do about them, not by HTTPdiff --git a/packages/cli/src/providers/probe-catalog.test.ts b/packages/cli/src/providers/probe-catalog.test.tsindex 956e0f04..b2dad95b 100644--- a/packages/cli/src/providers/probe-catalog.test.ts+++ b/packages/cli/src/providers/probe-catalog.test.ts@@ -30,7 +30,8 @@ function makeTmpPath(): { path: string; cleanup: () => void } {}const SAMPLE: ProbeModelsResponse = {- version: 1,+ version: 3,+ generationId: "test-generation",generatedAt: "2026-05-25T13:24:22.364Z",providers: {xai: "grok-build-0.1",@@ -38,13 +39,14 @@ const SAMPLE: ProbeModelsResponse = {zhipu: "glm-4.5-air",moonshot: "moonshot-v1-auto",},+ unavailable: {},};const REAL_426_BODY ='{"contractVersion":3,"error":{"code":"catalog_client_upgrade_required","message":"This endpoint requires catalog contract version 3","minimumContractVersion":3}}';const REAL_V3_PROBE_MODELS_BODY =- '{"contractVersion":3,"generationId":"g-20260918072314542-9c5a9567","generatedAt":"2026-09-18T07:23:14.542Z","data":{"routes":{"deepseek/direct-api":{"modelId":"deepseek-v4.1-flash","externalModelId":"deepseek-flash","route":{"routeId":"deepseek","routeProfileId":"direct-api"},"confidence":"api_official"}}}}';+ '{"contractVersion":3,"generationId":"g-20260918072314542-9c5a9567","generatedAt":"2026-09-18T07:23:14.542Z","data":{"routes":{"deepseek/direct-api":{"modelId":"deepseek-v4.1-flash","externalModelId":"deepseek-flash","route":{"routeId":"deepseek","routeProfileId":"direct-api"},"confidence":"api_official"}},"unavailableRoutes":{"google/antigravity-subscription":{"route":{"routeId":"google","routeProfileId":"antigravity-subscription"},"reason":"client_model_selection_required"},"poe/gateway":{"route":{"routeId":"poe","routeProfileId":"gateway"},"reason":"no_verified_probe_model"}}}}';describe("readProbeModelsCache / writeProbeModelsCache", () => {let tmp: ReturnType<typeof makeTmpPath>;@@ -139,11 +141,17 @@ describe("fetchProbeModels", () => {test("returns ok with parsed response on 200", async () => {globalThis.fetch = mock(- async () => new Response(JSON.stringify(SAMPLE), { status: 200 })+ async () => new Response(REAL_V3_PROBE_MODELS_BODY, { status: 200 })) as unknown as typeof fetch;const outcome = await fetchProbeModels("http://stub.local", 1000);expect(outcome.kind).toBe("ok");- if (outcome.kind === "ok") expect(outcome.data).toEqual(SAMPLE);+ if (outcome.kind === "ok") {+ expect(outcome.data.providers).toEqual({ deepseek: "deepseek-flash" });+ expect(outcome.data.unavailable).toEqual({+ antigravity: "client_model_selection_required",+ poe: "no_verified_probe_model",+ });+ }});test("returns incompatible with the server contract version on 426", async () => {@@ -162,12 +170,19 @@ describe("fetchProbeModels", () => {expect(outcome).toEqual({ kind: "incompatible", serverContractVersion: null });});- test("returns incompatible before validating the shape of a newer 200 response", async () => {+ test("maps exact provider routes in a v3 response", async () => {globalThis.fetch = mock(async () => new Response(REAL_V3_PROBE_MODELS_BODY, { status: 200 })) as unknown as typeof fetch;const outcome = await fetchProbeModels("http://stub.local", 1000);- expect(outcome).toEqual({ kind: "incompatible", serverContractVersion: 3 });+ expect(outcome.kind).toBe("ok");+ if (outcome.kind === "ok") {+ expect(outcome.data.providers).toEqual({ deepseek: "deepseek-flash" });+ expect(outcome.data.unavailable).toEqual({+ antigravity: "client_model_selection_required",+ poe: "no_verified_probe_model",+ });+ }});test("returns http with status on a non-contract non-2xx response with no body", async () => {diff --git a/packages/cli/src/providers/probe-catalog.ts b/packages/cli/src/providers/probe-catalog.tsindex 359f19b4..752cb795 100644--- a/packages/cli/src/providers/probe-catalog.ts+++ b/packages/cli/src/providers/probe-catalog.ts@@ -1,54 +1,35 @@-/**- * Probe-model catalog client.- *- * Fetches `{ providers: { <slug>: <modelId> } }` from the models-index- * `/probeModels` endpoint and caches it at `~/.claudish/probe-models.json`.- * The TUI's "Test Connections" feature uses this to ask the catalog- * "what model should I send to provider X to verify the link?" instead of- * carrying stale string literals in source.- *- * Selection logic (cheapest active model per provider, tiebreak by recency)- * lives server-side in models-index — see- * `models-index/TASK_probe_models_endpoint.md`.- *- * Lazy fetch: the first caller to need a probe model triggers a network- * fetch. Subsequent reads hit the disk cache. A failed fetch never overwrites- * the cache, and `getProbeModel` returns the last cached pick whatever its age.- *- * Using an old pick is safe, which is why a failed fetch is not fatal to the- * TUI. The pick is only the first model to TRY: the probe is a live request to- * the provider, so an outdated pick cannot produce a false pass. At worst it- * fails model-not-found and the TUI moves on to endpoint discovery. Failing- * every provider on a failed fetch — the previous behaviour — turned the v3- * cutover (this endpoint answers 426 to a v2 build) into 18 red rows, none of- * which had contacted its provider.- */-import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";import { homedir } from "node:os";import { dirname, join } from "node:path";-import { isIncompatibleContractVersion, parseContractEnvelope } from "./catalog-compatibility.js";+import { providerForCatalogRoute } from "./catalog-route-bindings.js";+import { CATALOG_V3_ACCEPT, parseCatalogV3Envelope } from "./catalog-v3.js";const PROBE_MODELS_URL = "https://us-central1-claudish-6da10.cloudfunctions.net/probeModels";-// 1h TTL (matches the server's own instance cache). A 24h TTL meant a-// server-side catalog correction (e.g. fixing a probe model that 404s) took up-// to a day to reach users. 1h propagates fixes promptly without re-fetching on-// every probe; a stale-but-fresh wrong pick is additionally self-healed by the-// refresh-on-404 path in the TUI (forceRefreshProbeModels).const CACHE_TTL_MS = 60 * 60 * 1000;-// Generous timeout — the endpoint typically responds in ~400ms, but the TUI-// fires this concurrently with proxy startup and N parallel probe handlers.-// Under load on a cold cache we've seen the network round-trip pushed past-// 5s. 15s matches the per-probe timeout, so the fetch budget is bounded by-// the same UX deadline the user already accepts for a single probe.const FETCH_TIMEOUT_MS = 15000;export const PROBE_MODELS_CACHE_PATH = join(homedir(), ".claudish", "probe-models.json");export interface ProbeModelsResponse {- version: number;+ version: 3;+ generationId: string;generatedAt: string;providers: Record<string, string>;+ unavailable: Record<string, string>;+}++interface ProbeRoute {+ modelId: string;+ externalModelId: string;+ route: { routeId: string; routeProfileId: string };+}++interface ProbeData {+ routes: Record<string, ProbeRoute>;+ unavailableRoutes: Record<+ string,+ { route: { routeId: string; routeProfileId: string }; reason: string }+ >;}export type FetchOutcome =@@ -57,31 +38,18 @@ export type FetchOutcome =| { kind: "network"; reason: string }| { kind: "http"; status: number }| { kind: "invalid"; reason: string }- /**- * The endpoint answered in a catalog contract this build cannot read: a 426,- * or a body whose `contractVersion` is newer than this build supports. Kept- * apart from `http` because it is not a connectivity problem, and a caller- * that reports it as one sends the user to debug a working network.- */| { kind: "incompatible"; serverContractVersion: number | null };let _inFlight: Promise<FetchOutcome> | null = null;-/**- * One line naming why the probe catalog supplied no fresh pick, for the TUI.- *- * Only a connectivity failure says "could not reach". A contract mismatch says- * what it is: the network is fine, and a message that blames it sends the user- * to debug the wrong thing.- */export function describeProbeCatalogFailure(outcome: Exclude<FetchOutcome, { kind: "ok" }>): string {switch (outcome.kind) {case "incompatible":return outcome.serverContractVersion === null- ? "model catalog uses a newer contract than this build reads"- : `model catalog uses contract v${outcome.serverContractVersion}, newer than this build reads`;+ ? "model catalog contract is not supported by this build"+ : `model catalog contract v${outcome.serverContractVersion} is not supported by this build`;case "http":return `model catalog returned HTTP ${outcome.status}`;case "timeout":@@ -103,8 +71,7 @@ export function readProbeModelsCache(} catch {return null;}- if (!isValidResponse(raw)) return null;- return raw;+ return isValidResponse(raw) ? raw : null;}export function writeProbeModelsCache(@@ -119,10 +86,9 @@ export function isCacheFresh(data: ProbeModelsResponse | null,ttlMs: number = CACHE_TTL_MS): boolean {- if (!data?.generatedAt) return false;+ if (!data) return false;const generatedMs = Date.parse(data.generatedAt);- if (Number.isNaN(generatedMs)) return false;- return Date.now() - generatedMs < ttlMs;+ return !Number.isNaN(generatedMs) && Date.now() - generatedMs < ttlMs;}export async function fetchProbeModels(@@ -131,79 +97,83 @@ export async function fetchProbeModels(): Promise<FetchOutcome> {let response: Response;try {- response = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });- } catch (e: unknown) {- const name = (e as { name?: string } | null)?.name ?? "";- if (name === "TimeoutError" || name === "AbortError") {- return { kind: "timeout" };- }- return {- kind: "network",- reason: e instanceof Error ? e.message : String(e),- };- }-- if (!response.ok) {- // /probeModels negotiates the catalog contract like queryModels does, so at- // the v3 cutover it answers this build 426. Read the body before calling it- // a plain HTTP failure. The body is optional: a bare 426 is still a verdict.- let errorBody: unknown = null;- try {- errorBody = await response.json();- } catch {- // No JSON body. The status alone decides below.- }- const envelope = parseContractEnvelope(errorBody);- if (response.status === 426 || isIncompatibleContractVersion(envelope.contractVersion)) {- return { kind: "incompatible", serverContractVersion: envelope.contractVersion };- }- return { kind: "http", status: response.status };+ response = await fetch(url, {+ headers: { Accept: CATALOG_V3_ACCEPT },+ signal: AbortSignal.timeout(timeoutMs),+ });+ } catch (error) {+ const name = (error as { name?: string } | null)?.name;+ if (name === "TimeoutError" || name === "AbortError") return { kind: "timeout" };+ return { kind: "network", reason: error instanceof Error ? error.message : String(error) };}let body: unknown;try {body = await response.json();- } catch (e: unknown) {- return {- kind: "invalid",- reason: e instanceof Error ? e.message : "json parse error",- };+ } catch {+ if (response.status === 426) {+ return { kind: "incompatible", serverContractVersion: null };+ }+ return response.ok+ ? { kind: "invalid", reason: "json parse error" }+ : { kind: "http", status: response.status };+ }++ const statedVersion =+ body &&+ typeof body === "object" &&+ typeof (body as { contractVersion?: unknown }).contractVersion === "number"+ ? (body as { contractVersion: number }).contractVersion+ : null;+ if (response.status === 426 || (statedVersion !== null && statedVersion !== 3)) {+ return { kind: "incompatible", serverContractVersion: statedVersion };+ }+ if (!response.ok) return { kind: "http", status: response.status };++ const envelope = parseCatalogV3Envelope<ProbeData>(body);+ if (+ !envelope ||+ !envelope.data.routes ||+ typeof envelope.data.routes !== "object" ||+ !envelope.data.unavailableRoutes ||+ typeof envelope.data.unavailableRoutes !== "object"+ ) {+ return { kind: "invalid", reason: "missing route maps" };+ }++ const providers: Record<string, string> = {};+ for (const route of Object.values(envelope.data.routes)) {+ if (!route || typeof route !== "object" || typeof route.externalModelId !== "string") continue;+ const provider = providerForCatalogRoute(route.route);+ if (provider) providers[provider] = route.externalModelId;}- // A 200 in a newer contract is the same verdict. It must be caught here,- // before `isValidResponse`, which would otherwise report it as "missing- // providers map" and hide the real cause.- const bodyEnvelope = parseContractEnvelope(body);- if (isIncompatibleContractVersion(bodyEnvelope.contractVersion)) {- return { kind: "incompatible", serverContractVersion: bodyEnvelope.contractVersion };+ const unavailable: Record<string, string> = {};+ for (const route of Object.values(envelope.data.unavailableRoutes)) {+ if (!route || typeof route !== "object" || typeof route.reason !== "string") continue;+ const provider = providerForCatalogRoute(route.route);+ if (provider) unavailable[provider] = route.reason;}- if (!isValidResponse(body)) {- return { kind: "invalid", reason: "missing providers map" };+ if (Object.keys(providers).length + Object.keys(unavailable).length === 0) {+ return { kind: "invalid", reason: "no supported probe routes" };}- return { kind: "ok", data: body };++ return {+ kind: "ok",+ data: {+ version: 3,+ generationId: envelope.generationId,+ generatedAt: envelope.generatedAt,+ providers,+ unavailable,+ },+ };}-/**- * Ensure the probe-models cache is fresh. If the cached file is missing or- * older than the TTL, fetch fresh data and write it.- *- * Concurrent calls share a single in-flight fetch via `_inFlight` so the- * TUI's parallel "test all" loop only opens one network connection.- *- * Returns the outcome so callers can render an error state on failure.- * Never throws.- */export async function ensureProbeModelsCached(): Promise<FetchOutcome> {const cached = readProbeModelsCache();if (isCacheFresh(cached)) return { kind: "ok", data: cached! };-if (_inFlight) return _inFlight;-- _inFlight = (async () => {- const outcome = await fetchProbeModels();- if (outcome.kind === "ok") writeProbeModelsCache(outcome.data);- return outcome;- })();-+ _inFlight = fetchAndCacheProbeModels();try {return await _inFlight;} finally {@@ -211,26 +181,9 @@ export async function ensureProbeModelsCached(): Promise<FetchOutcome> {}}-/**- * Force a re-fetch of the probe catalog, IGNORING the TTL, and overwrite the- * cache on success. Used as a self-heal when the cached probe model for a- * provider fails with model-not-found/404 — the catalog may have been corrected- * server-side while the local cache is still "fresh" by its generatedAt clock.- *- * Shares the same in-flight dedupe as ensureProbeModelsCached so a parallel- * "test all" only triggers ONE forced refetch. Returns the outcome; never throws.- * On success the in-memory + on-disk cache is updated, so a subsequent- * getProbeModel() returns the fresh pick.- */export async function forceRefreshProbeModels(): Promise<FetchOutcome> {if (_inFlight) return _inFlight;-- _inFlight = (async () => {- const outcome = await fetchProbeModels();- if (outcome.kind === "ok") writeProbeModelsCache(outcome.data);- return outcome;- })();-+ _inFlight = fetchAndCacheProbeModels();try {return await _inFlight;} finally {@@ -238,42 +191,26 @@ export async function forceRefreshProbeModels(): Promise<FetchOutcome> {}}-/**- * Sync lookup of the probe model for a claudish provider slug.- *- * The backend `/probeModels` endpoint is the single source of truth and emits- * one entry per claudish provider name. Direct lookup, no shortcut walking,- * no fallback heuristics. A missing entry means the catalog doesn't yet have- * coverage for that slug — that's a backend gap, not a client problem.- *- * Returns `null` if no cache, no entry, or invalid entry. Callers must call- * `ensureProbeModelsCached()` first if they need a fresh fetch.- */+async function fetchAndCacheProbeModels(): Promise<FetchOutcome> {+ const outcome = await fetchProbeModels();+ if (outcome.kind === "ok") writeProbeModelsCache(outcome.data);+ return outcome;+}+export function getProbeModel(claudishSlug: string): string | null {- const cache = readProbeModelsCache();- if (!cache) return null;- const entry = cache.providers[claudishSlug];- return typeof entry === "string" && entry.length > 0 ? entry : null;+ const value = readProbeModelsCache()?.providers[claudishSlug];+ return typeof value === "string" && value.length > 0 ? value : null;+}++export function getProbeUnavailability(claudishSlug: string): string | null {+ return readProbeModelsCache()?.unavailable[claudishSlug] ?? null;}export interface DiscoveryResult {model: string | null;- /** Why discovery failed (only set when model is null). */reason?: string;}-/**- * Discover a probe model by asking the provider's endpoint directly.- *- * For self-hosted / user-deployed providers (LiteLLM, Ollama, LM Studio,- * vLLM, MLX, OllamaCloud) the cloud catalog can't enumerate models — each- * deployment has its own list. The proxy exposes `/v1/probe-discover` which- * delegates to the provider's transport.discoverProbeModel() method.- *- * Returns `{ model, reason? }`. When discovery fails, `reason` carries the- * proxy's explanation (e.g. "transport does not support discovery", "no- * model available") so the TUI can surface why.- */export async function discoverProbeModelFromEndpoint(proxyUrl: string,providerSlug: string,@@ -287,8 +224,8 @@ export async function discoverProbeModelFromEndpoint(`${proxyUrl}/v1/probe-discover?provider=${encodeURIComponent(providerSlug)}${excludeParam}`,{ signal: AbortSignal.timeout(8000) });- } catch (e: unknown) {- return { model: null, reason: e instanceof Error ? e.message : "fetch failed" };+ } catch (error) {+ return { model: null, reason: error instanceof Error ? error.message : "fetch failed" };}let body: unknown;try {@@ -298,20 +235,21 @@ export async function discoverProbeModelFromEndpoint(}const model = (body as { model?: unknown })?.model;const reason = (body as { reason?: unknown })?.reason;- if (typeof model === "string" && model.length > 0) {- return { model };- }- return {- model: null,- reason: typeof reason === "string" ? reason : `proxy ${response.status}`,- };+ if (typeof model === "string" && model.length > 0) return { model };+ return { model: null, reason: typeof reason === "string" ? reason : `proxy ${response.status}` };}function isValidResponse(raw: unknown): raw is ProbeModelsResponse {if (!raw || typeof raw !== "object") return false;const data = raw as Record<string, unknown>;- if (typeof data.version !== "number") return false;- if (typeof data.generatedAt !== "string") return false;- if (!data.providers || typeof data.providers !== "object") return false;- return true;+ return (+ data.version === 3 &&+ typeof data.generationId === "string" &&+ data.generationId.length > 0 &&+ typeof data.generatedAt === "string" &&+ !!data.providers &&+ typeof data.providers === "object" &&+ !!data.unavailable &&+ typeof data.unavailable === "object"+ );}diff --git a/packages/cli/src/providers/provider-definitions.test.ts b/packages/cli/src/providers/provider-definitions.test.tsindex 3ffe369f..6cb3b394 100644--- a/packages/cli/src/providers/provider-definitions.test.ts+++ b/packages/cli/src/providers/provider-definitions.test.ts@@ -59,17 +59,17 @@ describe("BUILTIN_PROVIDERS structural integrity", () => {expect(kimiCoding!.apiKeyAliases ?? []).not.toContain("MOONSHOT_API_KEY");});- test("qwen-cloud keeps Qwen Plan credentials isolated and uses Anthropic transport", () => {- const plan = BUILTIN_PROVIDERS.find((d) => d.name === "qwen-cloud");+ test("qwen-token-plan keeps Alibaba Token Plan credentials isolated and uses Anthropic transport", () => {+ const plan = BUILTIN_PROVIDERS.find((d) => d.name === "qwen-token-plan");expect(plan).toBeDefined();- expect(plan!.apiKeyEnvVar).toBe("QWEN_CLOUD_PLAN_API_KEY");+ expect(plan!.apiKeyEnvVar).toBe("QWEN_TOKEN_PLAN_API_KEY");expect(plan!.apiKeyAliases).toBeUndefined();expect(plan!.transport).toBe("anthropic");expect(plan!.authScheme).toBe("bearer");});- test("qwen-cloud composes message and discovery URLs on the same origin", () => {- const plan = BUILTIN_PROVIDERS.find((d) => d.name === "qwen-cloud")!;+ test("qwen-token-plan composes message and discovery URLs on the same origin", () => {+ const plan = BUILTIN_PROVIDERS.find((d) => d.name === "qwen-token-plan")!;const messagesUrl = plan.baseUrl + plan.apiPath;const modelsUrl = plan.baseUrl + plan.modelDiscovery!.path;@@ -86,8 +86,7 @@ describe("BUILTIN_PROVIDERS structural integrity", () => {const payg = BUILTIN_PROVIDERS.find((d) => d.name === "qwen-payg");expect(payg).toBeDefined();expect(payg!.apiKeyEnvVar).toBe("DASHSCOPE_API_KEY");- expect(payg!.apiKeyAliases).toEqual(["QWEN_API_KEY"]);- expect(payg!.apiKeyAliases).not.toContain("QWEN_CLOUD_PLAN_API_KEY");+ expect(payg!.apiKeyAliases).toBeUndefined();expect(payg!.transport).toBe("anthropic");expect(payg!.authScheme).toBe("bearer");expect(payg!.nativeModelPatterns).toBeUndefined();@@ -131,7 +130,7 @@ describe("BUILTIN_PROVIDERS structural integrity", () => {});test("Qwen's metered row follows the API naming convention", () => {- expect(getProviderByName("qwen-payg")?.displayName).toBe("Qwen API");+ expect(getProviderByName("qwen-payg")?.displayName).toBe("Alibaba PAYG");});test("grok-subscription does not compete with x-ai for native Grok patterns", () => {@@ -198,7 +197,6 @@ describe("BUILTIN_PROVIDERS structural integrity", () => {"native-anthropic","ollama","openrouter",- "poe","vllm",]);});@@ -400,21 +398,21 @@ describe("getEffectiveBaseUrl", () => {expect(getEffectiveBaseUrl(def)).toBe("https://openrouter.ai");});- test("QWEN_CLOUD_PLAN_BASE_URL overrides the qwen-cloud default host", () => {- const envVar = "QWEN_CLOUD_PLAN_BASE_URL";+ test("QWEN_TOKEN_PLAN_BASE_URL overrides the qwen-token-plan default host", () => {+ const envVar = "QWEN_TOKEN_PLAN_BASE_URL";const previousEnv = process.env[envVar];const previousConfigOverride = getConfigFileOverride();const missingConfig = join(tmpdir(),- `claudish-qwen-cloud-provider-definitions-${process.pid}-missing.json`+ `claudish-qwen-token-plan-provider-definitions-${process.pid}-missing.json`);setConfigFileOverride(missingConfig);- process.env[envVar] = "https://qwen-cloud.test.invalid";+ process.env[envVar] = "https://qwen-token-plan.test.invalid";try {- const def = getProviderByName("qwen-cloud")!;+ const def = getProviderByName("qwen-token-plan")!;expect(def.baseUrlEnvVars).toEqual([envVar]);- expect(getEffectiveBaseUrl(def)).toBe("https://qwen-cloud.test.invalid");+ expect(getEffectiveBaseUrl(def)).toBe("https://qwen-token-plan.test.invalid");} finally {setConfigFileOverride(previousConfigOverride);if (previousEnv === undefined) {@@ -576,7 +574,8 @@ describe("billing classification", () => {"kimi-coding","minimax-coding","opencode-zen-go",- "qwen-cloud",+ "qwen-coding",+ "qwen-token-plan","sakana-subscription",]);});diff --git a/packages/cli/src/providers/provider-definitions.ts b/packages/cli/src/providers/provider-definitions.tsindex 5f7aa3e3..60562daf 100644--- a/packages/cli/src/providers/provider-definitions.ts+++ b/packages/cli/src/providers/provider-definitions.ts@@ -150,7 +150,7 @@ export interface ProviderDefinition {* Declared today only by `opencode-zen-go`, which carried* `apiKeyAliases: ["OPENCODE_API_KEY"]` until 2026-09-02 and so has an* installed base of users for whom that key used to work. `sakana-subscription`- * / `sakana`, `qwen-cloud` / `qwen-payg` and `kimi-coding` / `kimi` are the same+ * / `sakana`, `qwen-token-plan` / `qwen-payg` and `kimi-coding` / `kimi` are the same* two-tier shape and could adopt it; each is a user-visible message change and* belongs to whichever change is looking at that provider.*/@@ -242,6 +242,7 @@ const openCodeZenHandler = lazyHandler((m) => m.openCodeZenProfile);const ollamaCloudHandler = lazyHandler((m) => m.ollamaCloudProfile);const litellmHandler = lazyHandler((m) => m.litellmProfile);const vertexHandler = lazyHandler((m) => m.vertexProfile);+const poeHandler = lazyHandler((m) => m.poeProfile);/** Shorthand for the five documented reasons a provider builds nothing here. */const noHandler = (reason: NoHandlerReason, note: string): NoHandler => ({@@ -365,7 +366,7 @@ export const BUILTIN_PROVIDERS: ProviderDefinition[] = [// GLM's, `kimi-k3-high` matches Kimi's — so those must never auto-detect as// Devin, and Devin must never be prepended to their chains. That reasoning// is intact: access to another vendor's model through the plan stays- // EXPLICIT (`dv@claude-opus-5`), same as Qwen Plan.+ // EXPLICIT (`dv@claude-opus-5`), same as Alibaba Token Plan.//// `swe-*` is different in kind: it is Cognition's own model line, no other// provider in the catalog carries it, and it collides with nothing. Without@@ -494,7 +495,7 @@ export const BUILTIN_PROVIDERS: ProviderDefinition[] = [// Same models as `x-ai` above, different BILLING: this one is covered by the// user's Grok subscription, while `x-ai` is metered per token against// XAI_API_KEY. The same subscription-vs-metered split claudish already models- // for GLM (gc@/glm@), MiniMax (mmc@/mm@), Qwen (qc@/qp@) and Sakana (sc@/sakana@).+ // for GLM (gc@/glm@), MiniMax (mmc@/mm@), Qwen (qtoken@/qpay@) and Sakana (sc@/sakana@).//// Full protocol write-up: ai-docs/reports/grok-subscription/protocol-spec.md{@@ -906,10 +907,7 @@ export const BUILTIN_PROVIDERS: ProviderDefinition[] = [// ── Poe ────────────────────────────────────────────────────────────{- createHandler: noHandler(- "unimplemented",- "PoeProvider exists in transport/poe.ts but no builder was ever written; --probe reports 'no probe model in catalog'."- ),+ createHandler: poeHandler,name: "poe",displayName: "Poe",transport: "poe",@@ -1164,159 +1162,72 @@ export const BUILTIN_PROVIDERS: ProviderDefinition[] = [description: "Sakana Fugu Subscription (sc@)",},- // ── Qwen Plan (must be before Qwen — /^qwen/i would swallow it) ──- // Alibaba Cloud Model Studio's subscription ("Qwen Plan"), served over- // a NATIVE Anthropic-compatible endpoint (it exists so Claude Code can point- // at it directly), so responses arrive as real Anthropic SSE — `thinking`- // blocks included — and ride the anthropic-sse passthrough parser.- //- // baseUrl is the BARE HOST with `/apps/anthropic` folded into apiPath, the- // same shape as minimax-coding. That's deliberate: modelDiscovery's path is- // `/compatible-mode/v1/models`, which is a SIBLING of `/apps/anthropic`, not- // a child. Folding the prefix into apiPath keeps both on one origin so a- // single baseUrl override (QWEN_CLOUD_PLAN_BASE_URL) redirects messages AND- // discovery together.- //- // NO apiKeyAliases, and specifically none onto DASHSCOPE_API_KEY /- // QWEN_API_KEY. Like the sakana-subscription precedent, the BILLING MODE is- // fixed when the key is minted: a plan key authenticates ONLY against- // token-plan.ap-southeast-1.maas.aliyuncs.com. Probed live 2026-08-02, the- // sibling Alibaba hosts reject it outright — coding-intl.dashscope.aliyuncs.com- // → 401 invalid_api_key; dashscope.aliyuncs.com (Beijing) and- // dashscope-intl.aliyuncs.com → 403 invalid api-key. An alias could only ever- // send the wrong key to the wrong host, or bill the wrong plan.- //- // The ROSTER is discovered, never listed. Alibaba's docs claim this host has- // no model-list endpoint and then name the wrong models: the docs say- // qwen3.6-plus/qwen3.6-flash, but qwen3.6-plus answers 403 "Access to model- // denied" while qwen3.7-plus answers 200. `/compatible-mode/v1/models` does- // exist (OpenAI-shaped list) and is authenticated, so it reports what THIS- // subscription is entitled to — including the non-Qwen models the plan also- // carries (glm-5.2, deepseek-v4-*). Ask the endpoint; hardcode nothing.- //- // nativeModelPatterns is NAMESPACE ownership only, not a pinned roster.- // `/^qwen3\.\d/i` claims the DOTTED names, and it keeps working as new dotted- // versions ship. This entry MUST stay above `qwen` below, whose `/^qwen/i`- // matches first-wins on array order and would otherwise claim these names.- //- // CAUTION — the rule this pattern is right for is NOT the one it used to- // claim. The old note said dotted versions are "Model Studio" while- // hyphenated ones are "OpenRouter/HuggingFace", i.e. that the separator- // discriminates VENDOR. Measured 2026-08-10, that is false: Alibaba uses both- // conventions, and the split is PRODUCT LINE inside Alibaba.- //- // Token Plan (authenticated, this provider) → qwen3.8-max, qwen3.7-max,- // qwen3.7-plus, qwen3.6-flash — all DOTTED- // Coding Plan (public list, not built here) → qwen3-coder-plus,- // qwen3-coder-next, qwen3-max-2026-01-23 (HYPHENATED)- // alongside qwen3.5-plus, qwen3.6-plus — MIXED- //- // So the pattern is correct for THIS provider — Token Plan genuinely serves- // only dotted ids — but for a narrower reason than "hyphenated means an- // aggregator". The coder line and dated snapshots are hyphenated Alibaba- // names, not third-party ones.- //- // Consequence, deliberately left alone: a bare `qwen3-coder-plus` does not- // match `qwen3.*` (globMatch treats the "." literally), falls to `qwen`'s- // `/^qwen/i`, and is served by OpenRouter. That is CORRECT today, because no- // silo claudish implements serves it — Token Plan does not, and the Coding- // Plan has no provider. Do NOT "fix" this by pointing hyphenated names at- // qwen-payg on the strength of the name shape: routing filters by CREDENTIAL,- // not by model, so an id that host does not serve earns a `400 Model not- // exist` and STOPS (400 is non-retryable in fallback-handler.ts) — the exact- // dead-end documented for glm-* in default-routing-rules.ts. The PAYG roster- // is authenticated (401 without a key, unlike the Coding Plan's public list),- // so that change needs a DASHSCOPE_API_KEY to verify against, or routing that- // consults live `modelDiscovery` instead of guessing from the id.+ // ── Alibaba Token Plan (must be before Qwen — /^qwen/i would swallow it) ──+ // Alibaba Token Plan: subscription credits on its own host and credential.{createHandler: anthropicCompatHandler,- name: "qwen-cloud",- displayName: "Qwen Plan",+ name: "qwen-token-plan",+ displayName: "Alibaba Token Plan",transport: "anthropic",baseUrl: "https://token-plan.ap-southeast-1.maas.aliyuncs.com",- baseUrlEnvVars: ["QWEN_CLOUD_PLAN_BASE_URL"],+ baseUrlEnvVars: ["QWEN_TOKEN_PLAN_BASE_URL"],apiPath: "/apps/anthropic/v1/messages",- // The DISPLAY name is "Qwen Plan", but the env var deliberately keeps the- // longer QWEN_CLOUD_PLAN_ prefix (same for QWEN_CLOUD_PLAN_BASE_URL) for- // back-compat with existing setups — do NOT rename it to match the label.- apiKeyEnvVar: "QWEN_CLOUD_PLAN_API_KEY",- apiKeyDescription: "Qwen Plan API Key",- apiKeyUrl: "https://www.alibabacloud.com/help/en/model-studio/claude-code",+ apiKeyEnvVar: "QWEN_TOKEN_PLAN_API_KEY",+ siblingKeyEnvVars: ["QWEN_CODING_PLAN_API_KEY", "DASHSCOPE_API_KEY"],+ apiKeyDescription: "Alibaba Model Studio Token Plan API Key (subscription credits)",+ apiKeyUrl: "https://docs.qwencloud.com/token-plan/overview",authScheme: "bearer",- shortcuts: ["qc"],- shortestPrefix: "qc",- legacyPrefixes: [{ prefix: "qc/", stripPrefix: true }],+ shortcuts: ["qtoken"],+ shortestPrefix: "qtoken",+ legacyPrefixes: [],nativeModelPatterns: [{ pattern: /^qwen3\.\d/i }],modelDiscovery: { path: "/compatible-mode/v1/models", format: "openai-models-list" },isDirectApi: true,- description: "Qwen Plan (qc@)",+ description: "Alibaba Token Plan subscription (qtoken@)",},- // ── Alibaba Model Studio, PAY-AS-YOU-GO (the third silo) ───────────- // Same vendor as qwen-cloud above, DIFFERENT billing and a different host.- // Alibaba sells three products whose keys and base URLs are, in its own- // words, "completely isolated and must be used in matching pairs":- //- // Token Plan token-plan.ap-southeast-1.maas.aliyuncs.com → qwen-cloud- // Coding Plan coding-intl.dashscope.aliyuncs.com → (not built)- // PAYG dashscope-intl.aliyuncs.com → THIS entry- //- // Every silo rejects every other silo's key. That symmetry is the point, and- // it is why claudish needs one provider per silo rather than one "Qwen"- // provider with a swappable host: a user holding a PAYG key had NO way to- // reach Alibaba at all, because the only entry pointed at the plan host and- // answered 401 for them forever.- //- // Verified live 2026-08-10: this host's /compatible-mode/v1/models EXISTS and- // is AUTHENTICATED — a Token Plan key gets 401 "Incorrect API key provided",- // not a 404. (Contrast coding-intl's /v1/models, which serves the full roster- // to an unauthenticated caller — a 200 from THAT one proves nothing about a- // credential, and briefly convinced this investigation of the opposite.)- //- // apiKeyAliases onto QWEN_API_KEY is safe HERE where it would be wrong on- // qwen-cloud: both names hold a metered PAYG credential, so they are two- // spellings of one billing mode. Aliasing either onto the plan key would- // instead cross a subscription with a per-token bill.- //- // Deliberately NO nativeModelPatterns: qwen-cloud already owns the dotted- // `/^qwen3\.\d/i` namespace, and patterns are first-wins on array order, so a- // duplicate here would be dead weight that reads like a live rule. Bare-name- // reachability comes from the `qwen3.*` chain in default-routing-rules.ts,- // where this sits AFTER the subscription — the subscription-first ordering- // every other family already follows, so a user with both keys is never- // silently billed per token for a model their plan covers.+ // Alibaba Coding Plan: request-based subscription on its own host and credential.+ {+ createHandler: anthropicCompatHandler,+ name: "qwen-coding",+ displayName: "Alibaba Coding Plan",+ transport: "anthropic",+ baseUrl: "https://coding-intl.dashscope.aliyuncs.com",+ baseUrlEnvVars: ["QWEN_CODING_PLAN_BASE_URL"],+ apiPath: "/apps/anthropic/v1/messages",+ apiKeyEnvVar: "QWEN_CODING_PLAN_API_KEY",+ siblingKeyEnvVars: ["QWEN_TOKEN_PLAN_API_KEY", "DASHSCOPE_API_KEY"],+ apiKeyDescription: "Alibaba Model Studio Coding Plan API Key (subscription requests)",+ apiKeyUrl: "https://www.alibabacloud.com/help/en/model-studio/coding-plan",+ authScheme: "bearer",+ shortcuts: ["qcode"],+ shortestPrefix: "qcode",+ legacyPrefixes: [],+ modelDiscovery: { path: "/v1/models", format: "openai-models-list" },+ isDirectApi: true,+ description: "Alibaba Coding Plan subscription (qcode@)",+ },++ // Alibaba PAYG: token-metered access on its own host and credential.{createHandler: anthropicCompatHandler,name: "qwen-payg",- // "Qwen API", not "Qwen PAYG". Every other metered provider in this catalog- // is named "<vendor> API" (Gemini/MiniMax/GLM/Kimi/DeepSeek/Mistral/Sakana),- // and this row sits directly beneath "Qwen Plan (qc@)" — so "PAYG" made the- // pair read as two unrelated products rather than metered-vs-plan. The- // pay-as-you-go distinction, which genuinely matters when picking a key,- // stays in apiKeyDescription below. The `name` is untouched: it is the- // routing slug and a wire identifier, not a label.- displayName: "Qwen API",+ displayName: "Alibaba PAYG",transport: "anthropic",- // International endpoint. A mainland-China (aliyun.com) account is a- // different account system on dashscope.aliyuncs.com; that user repoints- // via DASHSCOPE_BASE_URL rather than getting a fourth near-identical entry.baseUrl: "https://dashscope-intl.aliyuncs.com",baseUrlEnvVars: ["DASHSCOPE_BASE_URL"],apiPath: "/apps/anthropic/v1/messages",apiKeyEnvVar: "DASHSCOPE_API_KEY",- apiKeyAliases: ["QWEN_API_KEY"],- apiKeyDescription: "Alibaba Model Studio API Key (pay-as-you-go)",+ siblingKeyEnvVars: ["QWEN_TOKEN_PLAN_API_KEY", "QWEN_CODING_PLAN_API_KEY"],+ apiKeyDescription: "Alibaba Model Studio PAYG API Key",apiKeyUrl: "https://www.alibabacloud.com/help/en/model-studio/get-api-key",authScheme: "bearer",- shortcuts: ["qp", "dashscope"],- shortestPrefix: "qp",- legacyPrefixes: [{ prefix: "qp/", stripPrefix: true }],- // Sibling of /apps/anthropic on the same origin, so one DASHSCOPE_BASE_URL- // override redirects messages AND discovery together — the same reason- // qwen-cloud folds its prefix into apiPath rather than into baseUrl.+ shortcuts: ["qpay"],+ shortestPrefix: "qpay",+ legacyPrefixes: [],modelDiscovery: { path: "/compatible-mode/v1/models", format: "openai-models-list" },isDirectApi: true,- description: "Alibaba Model Studio API, pay-as-you-go (qp@)",+ description: "Alibaba Model Studio PAYG (qpay@)",},// ── Qwen (auto-routed, no direct API) ──────────────────────────────diff --git a/packages/cli/src/providers/provider-profiles.test.ts b/packages/cli/src/providers/provider-profiles.test.tsindex 8a14bb1e..242d7c89 100644--- a/packages/cli/src/providers/provider-profiles.test.ts+++ b/packages/cli/src/providers/provider-profiles.test.ts@@ -16,13 +16,15 @@ afterAll(() => {writeFileSync(catalogCachePath,JSON.stringify({- version: 2,+ catalogGenerationId: "test-generation",+ plans: [],+ version: 3,lastUpdated: new Date().toISOString(),entries: [{modelId: "acme-responses-x1.0",aliases: [],- sources: {},+endpoints: {openai: { api: "responses", toolsWithReasoning: "requires-responses" },},@@ -58,8 +60,8 @@ const expectedCompositions = [{provider: "opencode-zen-go",model: "minimax-m2.5",- streamFormat: "openai-sse",- endpoint: "https://opencode.ai/zen/go/v1/chat/completions",+ streamFormat: "anthropic-sse",+ endpoint: "https://opencode.ai/zen/go/v1/messages",},{provider: "opencode-zen-go",@@ -91,6 +93,30 @@ const expectedCompositions = [streamFormat: "openai-responses-sse",endpoint: "https://opencode.ai/zen/v1/responses",},+ {+ provider: "opencode-zen-go",+ model: "qwen3.7-plus",+ streamFormat: "anthropic-sse",+ endpoint: "https://opencode.ai/zen/go/v1/messages",+ },+ {+ provider: "opencode-zen",+ model: "qwen3.7-max",+ streamFormat: "anthropic-sse",+ endpoint: "https://opencode.ai/zen/v1/messages",+ },+ {+ provider: "opencode-zen",+ model: "claude-fable-5",+ streamFormat: "anthropic-sse",+ endpoint: "https://opencode.ai/zen/v1/messages",+ },+ {+ provider: "opencode-zen",+ model: "grok-4.5",+ streamFormat: "openai-responses-sse",+ endpoint: "https://opencode.ai/zen/v1/responses",+ },] as const;describe("OpenCode Zen provider composition", () => {@@ -104,32 +130,58 @@ describe("OpenCode Zen provider composition", () => {});}- for (const provider of ["opencode-zen-go", "opencode-zen"] as const) {- test(`${provider} pairs MiniMax's OpenAI format with its chat-completions endpoint`, async () => {- const composition = await describeHandler(provider, "minimax-m2.5");-- // An Anthropic format paired with a chat-completions endpoint is the exact- // mismatch that produced the 400. This pins the PAIRING, not either field alone.- expect(composition.streamFormat).not.toBe("anthropic-sse");- expect(composition.endpoint.endsWith("/v1/chat/completions")).toBe(true);- });+ test("Go MiniMax and metered Zen MiniMax use their documented distinct APIs", async () => {+ expect(+ (await describeHandler("opencode-zen-go", "minimax-m3")).endpoint.endsWith("/v1/messages")+ ).toBe(true);+ expect(+ (await describeHandler("opencode-zen", "minimax-m3")).endpoint.endsWith(+ "/v1/chat/completions"+ )+ ).toBe(true);+ });+});- test(`${provider} gives MiniMax the same composition as an ordinary chat model`, async () => {- expect(await describeHandler(provider, "minimax-m2.5")).toEqual(- await describeHandler(provider, "glm-5")- );+describe("Poe gateway composition", () => {+ test("builds a callable OpenAI-compatible handler", async () => {+ expect(await describeHandler("poe", "GPT-4o")).toEqual({+ transport: "poe",+ streamFormat: "openai-sse",+ endpoint: "https://api.poe.com/v1/chat/completions",});+ });+});- // The deleted special case used a case-insensitive MiniMax substring match,- // so both casing changes and future MiniMax model ids must remain ordinary.- for (const model of ["MiniMax-M2.5", "minimax-m3"] as const) {- test(`${provider} has no resurrected MiniMax special case for ${model}`, async () => {- expect(await describeHandler(provider, model)).toEqual(- await describeHandler(provider, "minimax-m2.5")- );+describe("Vertex project-aware composition", () => {+ test("a selected project constructs its regional OAuth endpoint even with an Express key", async () => {+ const prior = {+ project: process.env.VERTEX_PROJECT,+ key: process.env.VERTEX_API_KEY,+ credentials: process.env.GOOGLE_APPLICATION_CREDENTIALS,+ location: process.env.VERTEX_LOCATION,+ };+ try {+ process.env.VERTEX_PROJECT = "selected-project";+ process.env.VERTEX_API_KEY = "express-key";+ process.env.GOOGLE_APPLICATION_CREDENTIALS = "/tmp/vertex-test-credentials";+ process.env.VERTEX_LOCATION = "us-central1";+ expect(await describeHandler("vertex", "gemini-3.6-flash")).toEqual({+ transport: "vertex",+ streamFormat: "gemini-sse",+ endpoint:+ "https://us-central1-aiplatform.googleapis.com/v1/projects/selected-project/locations/us-central1/publishers/google/models/gemini-3.6-flash:streamGenerateContent?alt=sse",});+ } finally {+ if (prior.project === undefined) delete process.env.VERTEX_PROJECT;+ else process.env.VERTEX_PROJECT = prior.project;+ if (prior.key === undefined) delete process.env.VERTEX_API_KEY;+ else process.env.VERTEX_API_KEY = prior.key;+ if (prior.credentials === undefined) delete process.env.GOOGLE_APPLICATION_CREDENTIALS;+ else process.env.GOOGLE_APPLICATION_CREDENTIALS = prior.credentials;+ if (prior.location === undefined) delete process.env.VERTEX_LOCATION;+ else process.env.VERTEX_LOCATION = prior.location;}- }+ });});describe("OpenAI Responses-API gate", () => {diff --git a/packages/cli/src/providers/provider-profiles.ts b/packages/cli/src/providers/provider-profiles.tsindex 2ce768c5..eb364f0f 100644--- a/packages/cli/src/providers/provider-profiles.ts+++ b/packages/cli/src/providers/provider-profiles.ts@@ -27,7 +27,11 @@ import { LiteLLMAPIFormat } from "../adapters/litellm-api-format.js";import { lookupModelEndpoint } from "../adapters/model-catalog.js";import { OllamaAPIFormat } from "../adapters/ollama-api-format.js";import { OpenAIAPIFormat } from "../adapters/openai-api-format.js";-import { getVertexConfig, validateVertexOAuthConfig } from "../auth/vertex-auth.js";+import {+ getVertexConfig,+ selectVertexAuthMode,+ validateVertexOAuthConfig,+} from "../auth/vertex-auth.js";import { ComposedHandler } from "../handlers/composed-handler.js";import type { ModelHandler } from "../handlers/types.js";import { log, logStderr } from "../logger.js";@@ -44,7 +48,8 @@ import { LiteLLMProviderTransport } from "./transport/litellm.js";import { OllamaProviderTransport } from "./transport/ollamacloud.js";import { OpenAICodexTransport } from "./transport/openai-codex.js";import { OpenAIProviderTransport } from "./transport/openai.js";-import { OpenCodeZenTransport } from "./transport/opencode-zen.js";+import { OpenCodeZenMessagesTransport, OpenCodeZenTransport } from "./transport/opencode-zen.js";+import { PoeProvider } from "./transport/poe.js";import { VertexProviderTransport, parseVertexModel } from "./transport/vertex-oauth.js";// ---------------------------------------------------------------------------@@ -307,6 +312,18 @@ export const openaiProfile: ProviderProfile = {},};+export const poeProfile: ProviderProfile = {+ createHandler(ctx) {+ const transport = new PoeProvider();+ const adapter = new OpenAIAPIFormat(ctx.modelName);+ return new ComposedHandler(transport, ctx.targetModel, ctx.modelName, ctx.port, {+ adapter,+ tokenStrategy: "delta-aware",+ ...ctx.sharedOpts,+ });+ },+};+/** OpenAI Codex — uses the Responses API (/v1/responses) with CodexAPIFormat.* Uses OpenAICodexTransport which checks for OAuth credentials first (ChatGPT subscription),* falling back to API key (OPENAI_CODEX_API_KEY). */@@ -354,61 +371,39 @@ export const glmProfile: ProviderProfile = {};/**- * OpenCode Zen / Zen Go — two tiers:- * zen/ (opencode-zen): OPENCODE_API_KEY- * zgo/ (opencode-zen-go): go-plan models (glm-5, minimax-m2.5, kimi-k2.5) via zen/go/v1/- *- * ZEN REQUIRES A REAL KEY (changed 2026-08-22). The catalog used to declare- * `publicKeyFallback: "public"`, so the credential authority emitted the literal- * string "public" whenever no real key resolved and `ctx.apiKey` was always- * populated here. Measured: the endpoint answers `401 — Missing API key` to- * that token, so the "free anonymous" tier it modelled does not exist (or no- * longer does). The affordance is removed entirely; `ctx.apiKey` can now be- * empty here, exactly as for any other keyed provider without a key.- *- * Model routing inside the profile:- * - GPT-* models → OpenCodeZenTransport (/v1/responses) + CodexAPIFormat (Responses API)- * - All other models → OpenCodeZenTransport (/v1/chat/completions) + OpenAIAPIFormat (delta-aware)- *- * Both branches use OpenCodeZenTransport, the OpenAI transport plus the per-conversation- * `x-opencode-session` header that Zen Go answers `400 MissingSessionID` without.- *- * MiniMax models take the SAME OpenAI path as everything else. They briefly had- * their own Anthropic branch (AnthropicProviderTransport + AnthropicAPIFormat),- * added to cure a `401 {"type":"AuthError","message":"Missing API key."}` — but- * that 401 was purely an auth-HEADER problem: the Anthropic transport defaults to- * `x-api-key` and only sends Bearer when the provider declares- * `authScheme: "bearer"`, which neither Zen definition does (their own OpenAI- * transport is Bearer-only, so they never needed to). Swapping in an entire- * transport+format pair to fix a header carried an endpoint assumption that does- * not hold here: AnthropicProviderTransport builds its URL as- * `baseUrl + provider.apiPath`, and BOTH Zen tiers declare- * `apiPath: "/v1/chat/completions"`. So an Anthropic-shaped body was being posted- * to an OpenAI endpoint.- *- * That survived verification because a tool-free Anthropic body is close enough to- * an OpenAI one to be accepted. Tools are where the shapes diverge: Anthropic tools- * carry `input_schema` and NO `type` field, and MiniMax validates them OpenAI-style,- * reporting the missing type as empty. Measured live 2026-08-08 against- * `opencode.ai/zen/go/v1/chat/completions`:- *- * anthropic body + tools → 400 "invalid params, invalid tool type: (2013)"- * anthropic body, NO tools → 200 ← why the original fix looked correct- * openai body + tools → 200- * openai body + tools + stream → 200, real tool_calls frames (m2.5 and m3)- * anthropic body → /v1/messages → 401 AuthError (no usable Anthropic route)- *- * Every Claude Code request carries tools, so this failed 100% of real turns. The- * non-Go tier is structurally identical (same apiPath, same transport) and shares- * the fix; it could not be re-measured without an OPENCODE_API_KEY.+ * OpenCode Zen and Go use model-specific wire APIs. The official endpoint tables+ * assign Qwen to Messages on both products, MiniMax to Messages on Go, GPT to+ * Responses, and most other listed families to Chat Completions. All paths+ * carry a stable per-conversation session header and the resolved product key.*/export const openCodeZenProfile: ProviderProfile = {createHandler(ctx) {const zenApiKey = ctx.apiKey;const isGoProvider = ctx.provider.name === "opencode-zen-go";+ const model = ctx.modelName.toLowerCase();++ // OpenCode serves these model families over its Anthropic Messages endpoint.+ // The Go MiniMax route differs from the metered Zen route.+ if (+ model.startsWith("qwen3") ||+ (!isGoProvider && model.startsWith("claude-")) ||+ (isGoProvider && model.startsWith("minimax-"))+ ) {+ const messagesProvider = {+ ...ctx.provider,+ apiPath: "/v1/messages",+ authScheme: "x-api-key" as const,+ };+ const transport = new OpenCodeZenMessagesTransport(messagesProvider, zenApiKey);+ const adapter = new AnthropicAPIFormat(ctx.modelName, ctx.provider.name);+ return new ComposedHandler(transport, ctx.targetModel, ctx.modelName, ctx.port, {+ adapter,+ ...ctx.sharedOpts,+ });+ }// GPT models are served via the OpenAI Responses API (/v1/responses), not /v1/chat/completions.- if (ctx.modelName.toLowerCase().startsWith("gpt-")) {+ if (model.startsWith("gpt-") || (!isGoProvider && model.startsWith("grok-"))) {const responsesProvider = { ...ctx.provider, apiPath: "/v1/responses" };const transport = new OpenCodeZenTransport(responsesProvider, ctx.modelName, zenApiKey);const adapter = new CodexAPIFormat(ctx.modelName);@@ -472,39 +467,19 @@ export const litellmProfile: ProviderProfile = {/*** Vertex AI — supports two modes:- * 1. Express Mode (VERTEX_API_KEY) — uses the Gemini API endpoint with a Vertex key.- * Uses GeminiProviderTransport (with the gemini provider config) + GeminiAPIFormat.- * 2. OAuth Mode (VERTEX_PROJECT) — full project-based access with OAuth tokens.+ * 1. OAuth Mode (VERTEX_PROJECT) — full project-based access with OAuth tokens.* Uses VertexProviderTransport + publisher-specific format (Gemini/Anthropic/Default).+ * 2. Express Mode (VERTEX_API_KEY) — used when no project is configured.+ * Uses GeminiProviderTransport (with the gemini provider config) + GeminiAPIFormat.** Returns null if neither key nor project config is available.*/export const vertexProfile: ProviderProfile = {createHandler(ctx) {- const hasApiKey = !!process.env.VERTEX_API_KEY;+ const mode = selectVertexAuthMode();const vertexConfig = getVertexConfig();- if (hasApiKey) {- // Express Mode — Vertex Express uses the standard Gemini API endpoint- // but with VERTEX_API_KEY instead of GEMINI_API_KEY.- // Must use the Gemini provider config (which has the correct baseUrl/apiPath)- // because the vertex provider config has empty baseUrl/apiPath (designed for OAuth mode).- const geminiConfig = getRegisteredRemoteProviders().find((p) => p.name === "gemini");- const expressProvider = geminiConfig || ctx.provider;- // ctx.apiKey is the authority-resolved Vertex credential (Express key when- // VERTEX_API_KEY is set) — single source of truth, no raw env read here.- const transport = new GeminiProviderTransport(expressProvider, ctx.modelName, ctx.apiKey);- const adapter = new GeminiAPIFormat(ctx.modelName);- const handler = new ComposedHandler(transport, ctx.targetModel, ctx.modelName, ctx.port, {- adapter,- ...ctx.sharedOpts,- });- log(`[Proxy] Created Vertex AI Express handler (composed): ${ctx.modelName}`);- return handler;- }-- if (vertexConfig) {- // OAuth Mode — ComposedHandler with publisher-specific adapter+ if (mode === "project" && vertexConfig) {const oauthError = validateVertexOAuthConfig();if (oauthError) {log(`[Proxy] Vertex OAuth config error: ${oauthError}`);@@ -519,7 +494,6 @@ export const vertexProfile: ProviderProfile = {} else if (parsed.publisher === "anthropic") {adapter = new AnthropicAPIFormat(parsed.model, "vertex");} else {- // Mistral/Meta use OpenAI format; Mistral rawPredict uses bare model nameconst modelId =parsed.publisher === "mistralai" ? parsed.model : `${parsed.publisher}/${parsed.model}`;adapter = new DefaultAPIFormat(modelId);@@ -535,6 +509,25 @@ export const vertexProfile: ProviderProfile = {return handler;}+ if (mode === "express") {+ // Express Mode — Vertex Express uses the standard Gemini API endpoint+ // but with VERTEX_API_KEY instead of GEMINI_API_KEY.+ // Must use the Gemini provider config (which has the correct baseUrl/apiPath)+ // because the vertex provider config has empty baseUrl/apiPath (designed for OAuth mode).+ const geminiConfig = getRegisteredRemoteProviders().find((p) => p.name === "gemini");+ const expressProvider = geminiConfig || ctx.provider;+ // ctx.apiKey is the authority-resolved Vertex credential (Express key when+ // VERTEX_API_KEY is set) — single source of truth, no raw env read here.+ const transport = new GeminiProviderTransport(expressProvider, ctx.modelName, ctx.apiKey);+ const adapter = new GeminiAPIFormat(ctx.modelName);+ const handler = new ComposedHandler(transport, ctx.targetModel, ctx.modelName, ctx.port, {+ adapter,+ ...ctx.sharedOpts,+ });+ log(`[Proxy] Created Vertex AI Express handler (composed): ${ctx.modelName}`);+ return handler;+ }+log("[Proxy] Vertex AI requires either VERTEX_API_KEY or VERTEX_PROJECT");return null;},diff --git a/packages/cli/src/providers/provider-routing.test.ts b/packages/cli/src/providers/provider-routing.test.tsindex 940aa5fd..c61b39be 100644--- a/packages/cli/src/providers/provider-routing.test.ts+++ b/packages/cli/src/providers/provider-routing.test.ts@@ -36,14 +36,21 @@ describe("parseModelSpec — shortcut resolution", () => {expect(parsed2.provider).toBe("openrouter");});- test("[email protected] resolves to qwen-cloud", () => {- const parsed = parseModelSpec("[email protected]");- expect(parsed.provider).toBe("qwen-cloud");+ test("[email protected] resolves to qwen-token-plan", () => {+ const parsed = parseModelSpec("[email protected]");+ expect(parsed.provider).toBe("qwen-token-plan");expect(parsed.model).toBe("qwen3.7-plus");expect(parsed.isExplicitProvider).toBe(true);});- test.each(["qp", "dashscope"])("%[email protected] resolves explicitly to qwen-payg", (shortcut) => {+ test("[email protected] resolves to qwen-coding", () => {+ const parsed = parseModelSpec("[email protected]");+ expect(parsed.provider).toBe("qwen-coding");+ expect(parsed.model).toBe("qwen3.7-plus");+ expect(parsed.isExplicitProvider).toBe(true);+ });++ test.each(["qpay"])("%[email protected] resolves explicitly to qwen-payg", (shortcut) => {const parsed = parseModelSpec(`${shortcut}@qwen3.7-plus`);expect(parsed.provider).toBe("qwen-payg");expect(parsed.model).toBe("qwen3.7-plus");@@ -82,21 +89,6 @@ describe("parseModelSpec — legacy prefix patterns", () => {expect(parsed.provider).toBe("ollama");expect(parsed.model).toBe("llama3.2");});-- test("qc/qwen3.7-plus resolves to qwen-cloud", () => {- const parsed = parseModelSpec("qc/qwen3.7-plus");- expect(parsed.provider).toBe("qwen-cloud");- expect(parsed.model).toBe("qwen3.7-plus");- expect(parsed.isLegacySyntax).toBe(true);- });-- test("qp/qwen3.7-plus resolves explicitly to qwen-payg", () => {- const parsed = parseModelSpec("qp/qwen3.7-plus");- expect(parsed.provider).toBe("qwen-payg");- expect(parsed.model).toBe("qwen3.7-plus");- expect(parsed.isExplicitProvider).toBe(true);- expect(parsed.isLegacySyntax).toBe(true);- });});describe("parseModelSpec — native model auto-detection", () => {@@ -156,17 +148,17 @@ describe("parseModelSpec — native model auto-detection", () => {expect(parsed.provider).toBe("qwen");});- test("qwen3.7-plus auto-detects as qwen-cloud before the general qwen provider", () => {+ test("qwen3.7-plus auto-detects as qwen-token-plan before the general qwen provider", () => {const parsed = parseModelSpec("qwen3.7-plus");- expect(parsed.provider).toBe("qwen-cloud");+ expect(parsed.provider).toBe("qwen-token-plan");expect(parsed.model).toBe("qwen3.7-plus");expect(parsed.isExplicitProvider).toBe(false);});- test("hyphenated qwen3-coder-next remains owned by qwen, not qwen-cloud", () => {+ test("hyphenated qwen3-coder-next remains owned by qwen, not qwen-token-plan", () => {const parsed = parseModelSpec("qwen3-coder-next");expect(parsed.provider).toBe("qwen");- expect(parsed.provider).not.toBe("qwen-cloud");+ expect(parsed.provider).not.toBe("qwen-token-plan");});test("llama3 auto-detects as ollamacloud", () => {@@ -204,8 +196,8 @@ describe("parseModelSpec — native model auto-detection", () => {// ---------------------------------------------------------------------------describe("Provider handlers", () => {- test("qwen-cloud shares the Anthropic-compatible handler builder", () => {- const createHandler = getProviderByName("qwen-cloud")?.createHandler;+ test("qwen-token-plan shares the Anthropic-compatible handler builder", () => {+ const createHandler = getProviderByName("qwen-token-plan")?.createHandler;expect(typeof createHandler).toBe("function");// These four providers are all natively Anthropic-compatible and must not@@ -219,7 +211,6 @@ describe("Provider handlers", () => {test("every handler omission is explicit and qwen-payg uses the Anthropic-compatible builder", () => {const expectedHandlerlessProviders = ["openrouter",- "poe","ollama","lmstudio","vllm",@@ -233,7 +224,7 @@ describe("Provider handlers", () => {expect(handlerlessProviders).toEqual(expectedHandlerlessProviders);expect(typeof qwenPaygHandler).toBe("function");- expect(qwenPaygHandler).toBe(getProviderByName("qwen-cloud")?.createHandler);+ expect(qwenPaygHandler).toBe(getProviderByName("qwen-token-plan")?.createHandler);});});diff --git a/packages/cli/src/providers/responses-api-gate.test.ts b/packages/cli/src/providers/responses-api-gate.test.tsindex f242f6ce..98975c8e 100644--- a/packages/cli/src/providers/responses-api-gate.test.ts+++ b/packages/cli/src/providers/responses-api-gate.test.ts@@ -2,7 +2,7 @@ import { afterAll, describe, expect, test } from "bun:test";import { mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import type { DiskCacheV2 } from "./all-models-cache.js";+import type { DiskCacheV3 } from "./all-models-cache.js";import { requiresResponsesApi } from "./provider-profiles.js";const fixtureDir = mkdtempSync(join(tmpdir(), "responses-api-gate-"));@@ -13,14 +13,16 @@ afterAll(() => {rmSync(fixtureDir, { recursive: true, force: true });});-const fixture: DiskCacheV2 = {- version: 2,+const fixture: DiskCacheV3 = {+ catalogGenerationId: "test-generation",+ plans: [],+ version: 3,lastUpdated: new Date().toISOString(),entries: [{modelId: "acme-x1.0",aliases: ["openai/acme-x1.0"],- sources: {},+contextWindow: 1050000,endpoints: { openai: { api: "responses" } },tokenParam: "max_output_tokens",@@ -28,7 +30,7 @@ const fixture: DiskCacheV2 = {{modelId: "acme-x2.0",aliases: ["openai/acme-x2.0"],- sources: {},+contextWindow: 1050000,endpoints: { openai: { toolsWithReasoning: "requires-responses" } },tokenParam: "max_output_tokens",@@ -36,14 +38,14 @@ const fixture: DiskCacheV2 = {{modelId: "acme-x3.0",aliases: ["openai/acme-x3.0"],- sources: {},+contextWindow: 1050000,tokenParam: "max_output_tokens",},{modelId: "acme-codex-x4.0",aliases: ["openai/acme-codex-x4.0"],- sources: {},+contextWindow: 1050000,endpoints: { openai: { api: "chat-completions" } },tokenParam: "max_output_tokens",diff --git a/packages/cli/src/providers/routing-hints.ts b/packages/cli/src/providers/routing-hints.tsindex d4da2709..d0bba77d 100644--- a/packages/cli/src/providers/routing-hints.ts+++ b/packages/cli/src/providers/routing-hints.ts@@ -44,7 +44,7 @@ const PROVIDER_HINT_MAP: Record<string, ProviderHintInfo> = {mistralai: { apiKeyEnvVar: "MISTRAL_API_KEY" },sakana: { apiKeyEnvVar: "SAKANA_API_KEY" },"sakana-subscription": { apiKeyEnvVar: "SAKANA_SUBSCRIPTION_API_KEY" },- "qwen-cloud": { apiKeyEnvVar: "QWEN_CLOUD_PLAN_API_KEY" },+ "qwen-token-plan": { apiKeyEnvVar: "QWEN_TOKEN_PLAN_API_KEY" },"qwen-payg": { apiKeyEnvVar: "DASHSCOPE_API_KEY" },ollamacloud: { apiKeyEnvVar: "OLLAMA_API_KEY" },"native-anthropic": { apiKeyEnvVar: "ANTHROPIC_API_KEY" },diff --git a/packages/cli/src/providers/routing-rules.test.ts b/packages/cli/src/providers/routing-rules.test.tsindex f9f117e7..6fc2536e 100644--- a/packages/cli/src/providers/routing-rules.test.ts+++ b/packages/cli/src/providers/routing-rules.test.ts@@ -1,3 +1,4 @@+import { catalogRouteForProvider } from "./catalog-route-bindings.js";/*** Unit tests for providers/routing-rules.ts*@@ -16,7 +17,7 @@ import { credentials } from "../auth/credentials/authority.js";import { __resetSniffForTests } from "../auth/credentials/op-source.js";import type { RecommendedModelsDoc } from "../model-loader.js";import type { RoutingRules } from "../profile-config.js";-import { type DiskCacheV2, type SlimModelEntry, writeAllModelsCache } from "./all-models-cache.js";+import { type DiskCacheV3, type SlimModelEntry, writeAllModelsCache } from "./all-models-cache.js";import { DISPLAY_NAMES } from "./auto-route.js";import { _resetCatalogClient, _setCatalogEntriesForTest } from "./catalog-client.js";import { DEFAULT_ROUTING_RULES } from "./default-routing-rules.js";@@ -73,7 +74,7 @@ function loadRulesWithCatalogExact(});}-function seedDefaultCatalog(entries: DiskCacheV2["entries"]): () => void {+function seedDefaultCatalog(entries: DiskCacheV3["entries"]): () => void {_setCatalogEntriesForTest(entries);return _resetCatalogClient;}@@ -82,57 +83,68 @@ function makeTempCatalog(model: {modelId: string;externalId?: string;- subscriptionPlans?: string[];+ subscriptionPlanIds?: string[];},/** Plan names to mark as active subscription plans in the catalog (defaults to the model's own plans). */- plans: string[] = model.subscriptionPlans ?? [],+ plans: string[] = model.subscriptionPlanIds ?? [],routingProviderByPlan: Record<string, string> = {}): { path: string; cleanup: () => void } {const dir = mkdtempSync(join(tmpdir(), "claudish-routing-test-"));const path = join(dir, "all-models.json");- const entries: DiskCacheV2["entries"] = [];+ const entries: DiskCacheV3["entries"] = [];// Plan-owner entries: a provider is only treated as a subscription plan if- // some catalog entry lists it in subscriptionPlans[]. Add markers so tests can+ // some catalog entry lists it in subscriptionPlanIds[]. Add markers so tests can// model the "model is not in this plan" drop path without duplicating real// plan members.for (const plan of plans) {entries.push({modelId: `${plan}-plan-marker`,aliases: [],- sources: {},- subscriptionPlans: [plan],- aggregators: [{ provider: plan, externalId: "any", confidence: "scrape_verified" as const }],++ subscriptionPlanIds: [plan],+ aggregators: [+ {+ sourceCollectorId: "test",+ routeStatus: "mapped",+ route: catalogRouteForProvider(routingProviderByPlan[plan] ?? plan),+ sourceProviderId: plan,+ externalModelId: "any",+ confidence: "scrape_verified" as const,+ },+ ],});}entries.push({modelId: model.modelId,aliases: [],- sources: {},- subscriptionPlans: model.subscriptionPlans ?? [],++ subscriptionPlanIds: model.subscriptionPlanIds ?? [],aggregators:- model.externalId && model.subscriptionPlans- ? model.subscriptionPlans.map((planId) => ({- provider: routingProviderByPlan[planId] ?? planId,- externalId: model.externalId!,+ model.externalId && model.subscriptionPlanIds+ ? model.subscriptionPlanIds.map((planId) => ({+ sourceProviderId: routingProviderByPlan[planId] ?? planId,+ sourceCollectorId: "test",+ routeStatus: "mapped" as const,+ route: catalogRouteForProvider(routingProviderByPlan[planId] ?? planId),+ externalModelId: model.externalId!,confidence: "scrape_verified" as const,})): undefined,});- const cache: DiskCacheV2 = {- version: 2,+ const cache: DiskCacheV3 = {+ catalogGenerationId: "test-generation",+ version: 3,lastUpdated: new Date().toISOString(),entries,models: [],plans: plans.map((plan) => ({id: plan,modelDiscovery: "catalog",- routing: {- providerUid: routingProviderByPlan[plan] ?? plan,- nativeModelProviders: [],- },+ routeStatus: "supported",+ route: catalogRouteForProvider(routingProviderByPlan[plan] ?? plan),})),};writeAllModelsCache(cache, path);@@ -306,11 +318,14 @@ describe("buildRoutingChain", () => {{modelId: SYNTHETIC_MODEL_ID,aliases: [],- sources: {},+aggregators: [{- provider: "minimax",- externalId: SYNTHETIC_MINIMAX_EXTERNAL_ID,+ sourceCollectorId: "test",+ routeStatus: "mapped",+ route: catalogRouteForProvider("minimax"),+ sourceProviderId: "minimax",+ externalModelId: SYNTHETIC_MINIMAX_EXTERNAL_ID,confidence: "scrape_verified",},],@@ -582,9 +597,9 @@ const ENV_KEYS_TO_CLEAR = ["MOONSHOT_API_KEY","KIMI_API_KEY","KIMI_CODING_API_KEY",- "QWEN_CLOUD_PLAN_API_KEY",+ "QWEN_TOKEN_PLAN_API_KEY",+ "QWEN_CODING_PLAN_API_KEY","DASHSCOPE_API_KEY",- "QWEN_API_KEY","MINIMAX_API_KEY","MINIMAX_CODING_API_KEY","ZHIPU_API_KEY",@@ -745,22 +760,49 @@ describe("route()", () => {}});- test("qwen3.7-plus prefers qwen-cloud over qwen-payg when both credentials are present", async () => {- process.env.QWEN_CLOUD_PLAN_API_KEY = "qwen-plan-test";+ test("qwen3.7-plus prefers qwen-token-plan over qwen-payg when both credentials are present", async () => {+ process.env.QWEN_TOKEN_PLAN_API_KEY = "qwen-plan-test";process.env.DASHSCOPE_API_KEY = "qwen-payg-test";const { path, cleanup } = makeTempCatalog({modelId: "qwen3.7-plus",externalId: "qwen3.7-plus",- subscriptionPlans: ["qwen-cloud"],+ subscriptionPlanIds: ["qwen-token-plan"],});try {const plan = await route("qwen3.7-plus", DEFAULT_ROUTING_RULES, undefined, path);expect(plan.kind).toBe("ok");if (plan.kind !== "ok") return;- expect(plan.primary.provider).toBe("qwen-cloud");- expect(plan.primary.modelSpec).toBe("[email protected]");+ expect(plan.primary.provider).toBe("qwen-token-plan");+ expect(plan.primary.modelSpec).toBe("[email protected]");expect(plan.fallbacks.map((fallback) => fallback.provider)).toEqual(["qwen-payg"]);- expect(plan.fallbacks[0]?.modelSpec).toBe("[email protected]");+ expect(plan.fallbacks[0]?.modelSpec).toBe("[email protected]");+ } finally {+ cleanup();+ }+ });++ test("qwen3.7-plus prefers Coding Plan when all three Alibaba credentials are present", async () => {+ process.env.QWEN_CODING_PLAN_API_KEY = "coding-test";+ process.env.QWEN_TOKEN_PLAN_API_KEY = "token-test";+ process.env.DASHSCOPE_API_KEY = "payg-test";+ const planIds = ["alibaba-ai-coding-plan", "alibaba-token-plan-individual"];+ const { path, cleanup } = makeTempCatalog(+ { modelId: "qwen3.7-plus", externalId: "qwen3.7-plus", subscriptionPlanIds: planIds },+ planIds,+ {+ "alibaba-ai-coding-plan": "qwen-coding",+ "alibaba-token-plan-individual": "qwen-token-plan",+ }+ );+ try {+ const result = await route("qwen3.7-plus", DEFAULT_ROUTING_RULES, undefined, path);+ expect(result.kind).toBe("ok");+ if (result.kind !== "ok") return;+ expect(result.primary.modelSpec).toBe("[email protected]");+ expect(result.fallbacks.map((candidate) => candidate.modelSpec)).toEqual([+ "[email protected]",+ "[email protected]",+ ]);} finally {cleanup();}@@ -771,14 +813,14 @@ describe("route()", () => {const { path, cleanup } = makeTempCatalog({modelId: "qwen3.7-plus",externalId: "qwen3.7-plus",- subscriptionPlans: ["qwen-cloud"],+ subscriptionPlanIds: ["qwen-token-plan"],});try {const plan = await route("qwen3.7-plus", DEFAULT_ROUTING_RULES, undefined, path);expect(plan.kind).toBe("ok");if (plan.kind !== "ok") return;expect(plan.primary.provider).toBe("qwen-payg");- expect(plan.primary.modelSpec).toBe("[email protected]");+ expect(plan.primary.modelSpec).toBe("[email protected]");} finally {cleanup();}@@ -790,7 +832,7 @@ describe("route()", () => {{modelId: "kimi-k3",externalId: "k3",- subscriptionPlans: ["kimi-code"],+ subscriptionPlanIds: ["kimi-code"],},["kimi-code"],{ "kimi-code": "kimi-coding" }@@ -826,15 +868,17 @@ describe("route()", () => {const path = join(dir, "all-models.json");writeAllModelsCache({- version: 2,+ catalogGenerationId: "test-generation",+ version: 3,lastUpdated: new Date().toISOString(),- entries: [{ modelId: "gpt-rollout-model", aliases: [], sources: {} }],+ entries: [{ modelId: "gpt-rollout-model", aliases: [] }],models: [],plans: [{id: "openai-codex",modelDiscovery: "catalog",- routing: { providerUid: "openai-codex", nativeModelProviders: ["openai"] },+ routeStatus: "supported",+ route: catalogRouteForProvider("openai-codex"),},],},@@ -854,15 +898,17 @@ describe("route()", () => {const path = join(dir, "all-models.json");writeAllModelsCache({- version: 2,+ catalogGenerationId: "test-generation",+ version: 3,lastUpdated: new Date().toISOString(),- entries: [{ modelId: "grok-account-model", aliases: [], sources: {} }],+ entries: [{ modelId: "grok-account-model", aliases: [] }],models: [],plans: [{id: "xai-supergrok",modelDiscovery: "client",- routing: { providerUid: "grok-subscription", nativeModelProviders: ["x-ai"] },+ routeStatus: "supported",+ route: catalogRouteForProvider("grok-subscription"),},],},@@ -885,7 +931,7 @@ describe("route()", () => {{modelId: "kimi-k3",externalId: "k3",- subscriptionPlans: ["kimi-coding"],+ subscriptionPlanIds: ["kimi-coding"],},["kimi-coding"]);@@ -906,7 +952,7 @@ describe("route()", () => {{modelId: "kimi-k3-256k",externalId: "k3-256k",- subscriptionPlans: ["kimi-coding"],+ subscriptionPlanIds: ["kimi-coding"],},["kimi-coding"]);@@ -927,7 +973,7 @@ describe("route()", () => {const { path, cleanup } = makeTempCatalog({modelId: "kimi-k2.5",- // No subscriptionPlans — this model is not part of the kimi-coding plan,+ // No subscriptionPlanIds — this model is not part of the kimi-coding plan,// so the subscription candidate is dropped instead of silently substituting.},["kimi-coding"]@@ -1099,10 +1145,13 @@ function routingCatalogEntry(modelId: string, providers: string[]): SlimModelEntreturn {modelId,aliases: [],- sources: { test: { externalId: modelId } },+aggregators: providers.map((provider) => ({- provider,- externalId: modelId,+ sourceProviderId: provider,+ sourceCollectorId: "test",+ routeStatus: "mapped" as const,+ route: catalogRouteForProvider(provider),+ externalModelId: modelId,confidence: "api_official",})),};diff --git a/packages/cli/src/providers/routing-rules.ts b/packages/cli/src/providers/routing-rules.tsindex 20e3b9b1..371c9a97 100644--- a/packages/cli/src/providers/routing-rules.ts+++ b/packages/cli/src/providers/routing-rules.ts@@ -7,11 +7,6 @@ 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";@@ -50,56 +45,12 @@ export interface RoutingRuleSources {* Always returns a non-null `RoutingRules` because defaults are baked in.* To get strict no-fallback mode, set `routing["*"] = []` in user config.*- * ── The catalog does NOT belong here. Do not add it back. ──────────────────+ * Catalog routes describe availability and wire IDs. They do not replace+ * routing preferences: bundled rules, then global and local overrides decide+ * order. The model and plan snapshot is consulted when building candidates.*- * v9.0.1 merged `buildCatalogRoutingRules(...)` into this dictionary and it- * deleted providers from every chain it touched. The mechanism, in two facts- * that are individually harmless:- *- * - catalog keys are EXACT model ids (`grok-4.6`); default and user keys are- * GLOBS (`grok-*`);- * - `matchRoutingRule` below returns on the first exact hit, before it ever- * looks at a glob.- *- * So one catalog key makes the matching glob unreachable for that model, and- * every provider the catalog did not name is gone. `buildCatalogRoutingRules`- * reads `subscriptions[]`, which enumerates PLAN-backed routes only — never a- * vendor's metered API, never OpenRouter — so its list is structurally- * incomplete. Measured on a real cache: `grok-4.6` became- * `["[email protected]"]`, leaving a user holding XAI_API_KEY and- * OPENROUTER_API_KEY with no route at all. A user's own `grok-*` rule was- * shadowed the same way, silently.- *- * Catalog knowledge reaches routing through two other call sites, and they are- * NOT equally safe. Be precise about which:- *- * - `providerServesModel` in `routeBare` IS safe. It is three-valued and drops- * a candidate only on `not-served`; `unknown` keeps it exactly where it was.- * - `resolveSubscriptionRouting` in `buildRoutingChain` is NOT, as of v9.0.1.- * Its `hasPublishedProviderRoster` check (model-catalog.ts:335) is evaluated- * at PROVIDER granularity across the whole cache, so one model publishing a- * plan membership makes every OTHER model's silence authoritative. Measured- * on the live cache: only `glm-5.3` and `glm-5.3-flash` list- * `z-ai-glm-coding-plan`, so `glm-4.7` resolves to- * `["[email protected]", "openrouter@z-ai/glm-4.7"]` — both subscriptions deleted,- * and a GLM Coding Plan holder is billed per token. Same shape for- * `qwen-cloud` on `qwen3-coder-plus`. At v9.0.0 this could not happen: the- * old code tested `subscriptionPlans.includes(providerUid)`, which was false- * for every provider, so it returned `unknown` and kept the candidate.- *- * That second one is a LIVE defect, not fixed here. This change restores the- * routing-rule COMPOSITION to v9.0.0; it deliberately retains v9.0.1's- * subscription-availability join, gap included. Do not read this file's fix as- * "v9.0.3 == v9.0.0 routing" — see ai-docs/reports/ for the follow-up.- *- * `sources` keeps this composition boundary testable without reading machine- * config or the recommended-models cache. `sources.recommendedModels` is- * optional and deliberately unused: a regression test hands it a shadowing entry- * and asserts it never reaches the output. That test alone is not a sufficient- * guard, because the v9.0.1 bug read the cache AMBIENTLY rather than through- * this seam — the guard that survives a cold CI checkout is the import-shape- * test in routing-rules.test.ts, which fails on any VALUE import from- * model-loader.js. Keep this file's model-loader import `import type`.+ * `sources` keeps rule composition testable without reading machine config.+ * The recommended-model projection is not a routing-rule override.*/export function loadRoutingRules(sources?: RoutingRuleSources): RoutingRules {const local = sources ? sources.localRules : (loadLocalConfig()?.routing ?? {});@@ -112,17 +63,7 @@ export function loadRoutingRules(sources?: RoutingRuleSources): RoutingRules {}/**- * Drop catalog entries naming a provider this client cannot execute.- *- * NO PRODUCTION CALLER as of v9.0.3 — `loadRoutingRules` no longer consumes the- * catalog, for the reasons documented there. Kept because the filter itself is- * correct and the catalog-driven routing redesign will need it; its test pins- * the behaviour meanwhile.- *- * Note what the premise of the original comment got wrong, since it is the same- * mistake that shipped the v9.0.1 regression: the backend does not own route- * PREFERENCE. It owns availability — who serves a model, under what id. Order is- * the user's, then claudish's defaults.+ * Keep only catalog routing entries whose provider has an executable transport.*/export function retainKnownCatalogRoutingRules(rules: RoutingRules): RoutingRules {const retained: RoutingRules = {};@@ -251,7 +192,7 @@ export function buildRoutingChain(// `together-ai@glm-5` reach `zai-org/GLM-5` without either provider// needing bespoke code. No match → the name passes through unchanged.if (!wireIdResolved) {- modelName = resolveExternalId(modelName, provider) ?? modelName;+ modelName = resolveExternalId(modelName, provider, cachePath) ?? modelName;}// Build modelSpec. OpenRouter's ids are already vendor-qualified, so they@@ -338,48 +279,10 @@ 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,@@ -387,8 +290,6 @@ async function routeExplicit(provider: string,cachePath?: string): Promise<RoutePlan> {- warnOnceIfCatalogIncompatible();-if (!(await hasCredentialsForProvider(provider))) {return {kind: "no-route",@@ -442,28 +343,6 @@ 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/providers/transport/anthropic-compat.ts b/packages/cli/src/providers/transport/anthropic-compat.tsindex 32490ba7..b94321a7 100644--- a/packages/cli/src/providers/transport/anthropic-compat.ts+++ b/packages/cli/src/providers/transport/anthropic-compat.ts@@ -100,7 +100,7 @@ export class AnthropicProviderTransport implements ProviderTransport {* model list.** Why this transport needs it at all: several Anthropic-compat providers are- * SUBSCRIPTIONS (Qwen Plan, Kimi Coding). The cloud /probeModels+ * SUBSCRIPTIONS (Alibaba Token Plan, Kimi Coding). The cloud /probeModels* catalog fundamentally cannot know which models a given key is entitled to* — that is a property of the caller's plan, not of the provider — so the* TUI falls back to GET /v1/probe-discover, which requires this method.@@ -108,7 +108,7 @@ export class AnthropicProviderTransport implements ProviderTransport {* support discovery" for every subscription provider.** Source of truth is the provider's own `modelDiscovery` descriptor (already- * declared by qwen-cloud and kimi-coding), reached through the shared+ * declared by qwen-token-plan and kimi-coding), reached through the shared* `discoverProviderModels()` — the same authenticated call the picker and* the context-window resolver use, so it shares their cache and their* credential-authority auth path. No new HTTP path is introduced here.@@ -118,7 +118,7 @@ export class AnthropicProviderTransport implements ProviderTransport {* probe exercises the model the user would actually get.** Non-chat rows are dropped with the shared `isChatCapable()` filter rather- * than a per-provider skip list: qwen-cloud's roster mixes image/TTS models+ * than a per-provider skip list: qwen-token-plan's roster mixes image/TTS models* (`wan2.7-image`, `qwen-audio-3.0-tts-plus`) in with the text models, and* hardcoding model ids here would rot the moment Alibaba ships the next one.*/@@ -181,7 +181,7 @@ export class AnthropicProviderTransport implements ProviderTransport {"minimax-coding": "MiniMax Coding",kimi: "Kimi","kimi-coding": "Kimi Coding",- "qwen-cloud": "Qwen Plan",+ "qwen-token-plan": "Alibaba Token Plan","qwen-payg": "Qwen API",moonshot: "Kimi","z-ai": "Z.AI",diff --git a/packages/cli/src/providers/transport/opencode-zen.test.ts b/packages/cli/src/providers/transport/opencode-zen.test.tsindex d65d0569..739268d1 100644--- a/packages/cli/src/providers/transport/opencode-zen.test.ts+++ b/packages/cli/src/providers/transport/opencode-zen.test.ts@@ -4,7 +4,7 @@ import { getProviderByName, toRemoteProvider } from "../provider-definitions.js"import { openCodeZenProfile } from "../provider-profiles.js";import { conversationKey } from "./conversation-key.js";import { OpenAICodexTransport } from "./openai-codex.js";-import { OpenCodeZenTransport } from "./opencode-zen.js";+import { OpenCodeZenMessagesTransport, OpenCodeZenTransport } from "./opencode-zen.js";const DEVICE_ID = "073c1234567890abcdef1234567890ab";const SESSION_ID_A = "ce7d2f89-90c2-4a15-93ed-f2c41b531111";@@ -117,10 +117,32 @@ describe("OpenCodeZenTransport", () => {});});+describe("OpenCodeZenMessagesTransport", () => {+ test("signs Messages with the product key and scopes the session header", async () => {+ const provider = {+ ...remoteProvider("opencode-zen-go"),+ apiPath: "/v1/messages",+ authScheme: "x-api-key" as const,+ };+ const transport = new OpenCodeZenMessagesTransport(provider, "go-key");+ const request = requestFor(SESSION_ID_A);+ const headers = await transport.getHeaders(request);+ expect(transport.getEndpoint()).toBe("https://opencode.ai/zen/go/v1/messages");+ expect(headers.Authorization).toBeUndefined();+ expect(headers["x-api-key"]).toBe("go-key");+ expect(headers["anthropic-version"]).toBe("2023-06-01");+ expect(headers["User-Agent"]).toMatch(/^claudish\/\d+\.\d+\.\d+$/);+ expect(headers["x-opencode-session"]).toBe(conversationKey(request));+ expect((await transport.getHeaders(requestFor(SESSION_ID_B)))["x-opencode-session"]).not.toBe(+ headers["x-opencode-session"]+ );+ });+});+describe("openCodeZenProfile", () => {for (const providerName of ["opencode-zen-go", "opencode-zen"] as const) {- for (const modelName of ["minimax-m3", "gpt-5.4"] as const) {- test(`${providerName} ${modelName} uses OpenCodeZenTransport`, () => {+ for (const modelName of ["minimax-m3", "gpt-5.4", "qwen3.7-plus"] as const) {+ test(`${providerName} ${modelName} uses the matching transport`, () => {const provider = remoteProvider(providerName);const handler = openCodeZenProfile.createHandler({provider,@@ -131,7 +153,12 @@ describe("openCodeZenProfile", () => {sharedOpts: {},} as any);- expect((handler as any).provider).toBeInstanceOf(OpenCodeZenTransport);+ const messages =+ modelName.startsWith("qwen") ||+ (providerName === "opencode-zen-go" && modelName.startsWith("minimax"));+ expect((handler as any).provider).toBeInstanceOf(+ messages ? OpenCodeZenMessagesTransport : OpenCodeZenTransport+ );});}}diff --git a/packages/cli/src/providers/transport/opencode-zen.ts b/packages/cli/src/providers/transport/opencode-zen.tsindex ce5af9e7..d123dadc 100644--- a/packages/cli/src/providers/transport/opencode-zen.ts+++ b/packages/cli/src/providers/transport/opencode-zen.ts@@ -26,6 +26,7 @@*/import { VERSION } from "../../version.js";+import { AnthropicProviderTransport } from "./anthropic-compat.js";import { conversationKey } from "./conversation-key.js";import { OpenAIProviderTransport } from "./openai.js";@@ -57,3 +58,14 @@ export class OpenCodeZenTransport extends OpenAIProviderTransport {};}}++/** OpenCode's Messages endpoint uses Bearer authentication and a session header. */+export class OpenCodeZenMessagesTransport extends AnthropicProviderTransport {+ override async getHeaders(claudeRequest?: unknown): Promise<Record<string, string>> {+ return {+ "User-Agent": `claudish/${VERSION}`,+ "x-opencode-session": conversationKey(claudeRequest),+ ...(await super.getHeaders()),+ };+ }+}diff --git a/packages/cli/src/providers/transport/vertex-oauth.ts b/packages/cli/src/providers/transport/vertex-oauth.tsindex 23f999e1..03031cb8 100644--- a/packages/cli/src/providers/transport/vertex-oauth.ts+++ b/packages/cli/src/providers/transport/vertex-oauth.ts@@ -1,5 +1,5 @@/**- * VertexOAuthProvider — Vertex AI transport with OAuth authentication.+ * VertexProviderTransport — Vertex AI transport with OAuth authentication.** Supports multiple publishers via dynamic stream format:* - Google (Gemini): gemini-sse stream format@@ -128,7 +128,3 @@ export class VertexProviderTransport implements ProviderTransport {return this.parsed;}}--// Backward-compatible alias-/** @deprecated Use VertexProviderTransport */-export { VertexProviderTransport as VertexOAuthProvider };diff --git a/packages/cli/src/proxy-server.ts b/packages/cli/src/proxy-server.tsindex 12783464..13ef8c5a 100644--- a/packages/cli/src/proxy-server.ts+++ b/packages/cli/src/proxy-server.ts@@ -34,7 +34,6 @@ import {resolveTargetForCatalog,warmCatalog,} from "./providers/catalog-client.js";-import { CatalogIncompatibleError } from "./providers/catalog-compatibility.js";import { getEndpointUnavailableReason } from "./providers/endpoint-diagnostics.js";import {ensureEndpointsRegistered,@@ -72,17 +71,8 @@ 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;+ return e instanceof RoutingError;}/**diff --git a/packages/cli/src/services/pricing-cache.ts b/packages/cli/src/services/pricing-cache.tsindex 91b4c932..2084649e 100644--- a/packages/cli/src/services/pricing-cache.ts+++ b/packages/cli/src/services/pricing-cache.ts@@ -1,3 +1,4 @@+import { catalogRouteMatchesProvider } from "../providers/catalog-route-bindings.js";/*** Dynamic pricing cache service*@@ -88,10 +89,10 @@ export function getDynamicPricingSync(const entry = findEntryByAlias(modelName) ?? findEntryByModelId(modelName);if (!entry) return undefined;- const orAgg = entry.aggregators?.find((a) => a.provider === "openrouter");+ const orAgg = entry.aggregators?.find((a) => catalogRouteMatchesProvider(a.route, "openrouter"));if (!orAgg) return undefined;- return pricingMap.get(orAgg.externalId);+ return orAgg.externalModelId ? pricingMap.get(orAgg.externalModelId) : undefined;}/**diff --git a/packages/cli/src/session-events/pro-injection.test.ts b/packages/cli/src/session-events/pro-injection.test.tsindex 993bbaf9..dcfb1860 100644--- a/packages/cli/src/session-events/pro-injection.test.ts+++ b/packages/cli/src/session-events/pro-injection.test.ts@@ -6,6 +6,7 @@ import type { Context } from "hono";import { ComposedHandler } from "../handlers/composed-handler.js";import type { ReasoningModeCapabilities } from "../model-loader.js";import { type SlimModelEntry, writeAllModelsCache } from "../providers/all-models-cache.js";+import { catalogRouteForProvider } from "../providers/catalog-route-bindings.js";import type { ProviderTransport } from "../providers/transport/types.js";import { SessionEventRegistry } from "./index.js";import {@@ -52,7 +53,7 @@ function variantEntry(return {modelId: VARIANT_MODEL_ID,aliases: [],- sources: {},+routeVariant: {kind: "provider-preset",baseModelId,@@ -66,11 +67,14 @@ function routeCapabilityEntry(provider: string, mode: ReasoningModeCapabilities)return {modelId: BASE_MODEL_ID,aliases: [`openai/${BASE_MODEL_ID}`],- sources: {},+aggregators: [{- provider,- externalId: BASE_MODEL_ID,+ sourceCollectorId: "test",+ routeStatus: "mapped",+ route: catalogRouteForProvider(provider),+ sourceProviderId: provider,+ externalModelId: BASE_MODEL_ID,confidence: provider === "openai" ? "api_official" : "gateway_official",reasoning: { mode },},@@ -79,7 +83,17 @@ function routeCapabilityEntry(provider: string, mode: ReasoningModeCapabilities)}function writeCatalog(entries: SlimModelEntry[] = [variantEntry()]): void {- writeAllModelsCache({ entries }, cachePath);+ writeAllModelsCache(+ {+ version: 3,+ catalogGenerationId: "test-generation",+ lastUpdated: new Date().toISOString(),+ entries,+ models: [],+ plans: [],+ },+ cachePath+ );}function makeProOptions(overrides: Partial<ProInjectionOptions> = {}): ProInjectionOptions {@@ -165,7 +179,7 @@ describe("resolveVariantPreset", () => {test("returns undefined when the catalog model has no variant", () => {makeHome();- writeCatalog([{ modelId: BASE_MODEL_ID, aliases: [], sources: {} }]);+ writeCatalog([{ modelId: BASE_MODEL_ID, aliases: [] }]);expect(resolveVariantPreset(BASE_MODEL_ID, PROVIDER, cachePath)).toBeUndefined();});diff --git a/packages/cli/src/session/baseline-pricing.ts b/packages/cli/src/session/baseline-pricing.tsindex 60426f4e..76c820ee 100644--- a/packages/cli/src/session/baseline-pricing.ts+++ b/packages/cli/src/session/baseline-pricing.ts@@ -1,3 +1,4 @@+import { catalogRouteMatchesProvider } from "../providers/catalog-route-bindings.js";/*** baseline-pricing — what the same tokens would have cost on Anthropic's own models.*@@ -63,7 +64,7 @@ function resolveBaseline(alias: string, label: string): Baseline | null {if (!entry) return null;const firstParty = entry.aggregators?.find(- (a) => a.provider === FIRST_PARTY && typeof a.pricing?.input === "number"+ (a) => catalogRouteMatchesProvider(a.route, FIRST_PARTY) && typeof a.pricing?.input === "number");const input = firstParty?.pricing?.input;const output = firstParty?.pricing?.output;diff --git a/packages/cli/src/telemetry.ts b/packages/cli/src/telemetry.tsindex 3dd8c27f..31f5e2f3 100644--- a/packages/cli/src/telemetry.ts+++ b/packages/cli/src/telemetry.ts@@ -60,7 +60,8 @@ const PUBLIC_PROVIDERS = new Set(["minimax-coding","kimi-coding","glm-coding",- "qwen-cloud",+ "qwen-token-plan",+ "qwen-coding","qwen-payg",]);diff --git a/packages/cli/src/tui/components/RoutingContent.tsx b/packages/cli/src/tui/components/RoutingContent.tsxindex 7364c55f..780ba4ce 100644--- a/packages/cli/src/tui/components/RoutingContent.tsx+++ b/packages/cli/src/tui/components/RoutingContent.tsx@@ -25,7 +25,7 @@ const PROVIDER_REASONS: Record<string, string> = {"minimax-coding": "MiniMax Coding Plan",glm: "Native GLM API","glm-coding": "GLM Coding Plan",- "qwen-cloud": "Qwen Plan",+ "qwen-token-plan": "Alibaba Token Plan",google: "Direct Gemini API",openai: "Direct OpenAI API","openai-codex": "OpenAI Codex (Responses API)",diff --git a/packages/cli/src/version.ts b/packages/cli/src/version.tsindex d74f411c..38334eea 100644--- a/packages/cli/src/version.ts+++ b/packages/cli/src/version.ts@@ -1,2 +1,2 @@// Auto-generated by scripts/generate-version.ts — do not edit-export const VERSION = "9.7.1";+export const VERSION = "9.8.0";