Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
feat: routing gathers candidates from the catalog; Vertex discovers its own models
Jack Rudenkoaf98f4f232ab
diff --git a/ai-docs/architecture/README.md b/ai-docs/architecture/README.mdindex a3d584d3..8c5f1435 100644--- a/ai-docs/architecture/README.md+++ b/ai-docs/architecture/README.md@@ -17,7 +17,7 @@ three earlier write-ups this material cites were lost.| Document | What it covers | Read it before you… ||---|---|---|-| [`routing.md`](routing.md) | The `provider@model` syntax, the full provider-prefix table, local models, `defaultProvider` semantics, `ModelCatalogResolver` vendor-prefix resolution, the DERIVED picker roster, and why subscription pricing is decided by billing rather than by `modelDiscovery` | change `DEFAULT_ROUTING_RULES`, `defaultProvider`, the picker, a catalog resolver, or `SUBSCRIPTION_PROVIDERS` |+| [`routing.md`](routing.md) | The `provider@model` syntax, the full provider-prefix table, local models, where a bare name's chain comes from now that there is NO built-in rules table, the fallback hop and its three empty states, `ModelCatalogResolver` vendor-prefix resolution, the DERIVED picker roster, and why subscription pricing is decided by billing rather than by `modelDiscovery` | change `routeBare`, `route-candidates.ts`, a `nativeModelPatterns` claim, `defaultProvider`, the picker, a catalog resolver, or `SUBSCRIPTION_PROVIDERS` || [`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 |diff --git a/ai-docs/architecture/providers/antigravity.md b/ai-docs/architecture/providers/antigravity.mdindex ab7e9246..4c66e81f 100644--- a/ai-docs/architecture/providers/antigravity.md+++ b/ai-docs/architecture/providers/antigravity.md@@ -11,7 +11,9 @@ Two separate Gemini flows, deliberately split:| Direct Gemini API | `g@` / `google@` | `GEMINI_API_KEY` | `generativelanguage.googleapis.com` | pay-per-use || **Antigravity** | `ag@` / `antigravity@` | your Antigravity OAuth token (shared with the `agy` CLI) | `daily-cloudcode-pa.googleapis.com/v1internal` | your Antigravity subscription (free / Pro / Ultra) |-**The `gemini-codeassist` provider was fully REMOVED (v7.36.0)** — definition, transport, credential provider, OAuth registration, quota adapter, probe entry, and the `--gemini-login`/`--gemini-logout` flags. It could not authenticate for any consumer account, yet it sat FIRST in the `gemini-*` routing chain, so every bare `gemini-*` name paid a guaranteed-failing round-trip before falling through to the metered `google` API — silently billing per-token for a model the user's subscription already covered. The chain is now `["antigravity", "google", "openrouter"]`, matching the subscription-first convention every other family already follows. A leftover `~/.claudish/gemini-oauth.json` no longer reads as a live credential (its `oauth-registry.ts` entries are gone), which is what kept a dead provider in the config TUI's Test All list.+**The `gemini-codeassist` provider was fully REMOVED (v7.36.0)** — definition, transport, credential provider, OAuth registration, quota adapter, probe entry, and the `--gemini-login`/`--gemini-logout` flags. It could not authenticate for any consumer account, yet it sat FIRST in the `gemini-*` routing chain, so every bare `gemini-*` name paid a guaranteed-failing round-trip before falling through to the metered `google` API — silently billing per-token for a model the user's subscription already covered. A leftover `~/.claudish/gemini-oauth.json` no longer reads as a live credential (its `oauth-registry.ts` entries are gone), which is what kept a dead provider in the config TUI's Test All list.++**Bare `gemini-*` reaches `ag@` through a NAMESPACE CLAIM, not a routing table.** The hand-written `"gemini-*": ["antigravity", "google", "openrouter"]` chain was deleted with the rest of `default-routing-rules.ts`. `google/antigravity-subscription` sits in the probe map as `client_model_selection_required` and publishes zero `aggregators[]` rows — the catalog cannot say what a seat was given — so the provider declares `nativeModelPatterns: [{ pattern: /^gemini-/i }]` and `route-candidates.ts` turns that into a `dynamic-subscription`-tier candidate, which the tier order puts ahead of the metered `google` hop. The claim deliberately does not win auto-detection (`google` declares the same pattern and is defined earlier in `BUILTIN_PROVIDERS`, and `getNativeModelPatterns()` is first-wins), and it deliberately does NOT cover `/^claude-/i` even though the backend serves Claude ids: a bare Claude name must never reach `route()` at all — `nativeRouteFor()` handles it first.The Antigravity half of the old `auth/gemini-oauth.ts` was extracted to **`auth/antigravity-user.ts`** (project/tier resolution, `retrieveUserQuota`, live served-set discovery) before that file was deleted — Antigravity depends on it, so deleting wholesale would have taken `ag@` down too. All three calls now share ONE identity (the Antigravity User-Agent). `retrieveUserQuota` used to keep the gemini-cli UA it was written with; measured 2026-08-18 on a real Ultra account, same token and project, only the UA varying — the gemini-cli UA returned 4 quota buckets (the retired free Code Assist served set) and the Antigravity UA returned 24. This backend gates its ANSWER on request identity, not just the tier label it displays.diff --git a/ai-docs/architecture/providers/devin.md b/ai-docs/architecture/providers/devin.mdindex 21569e1d..411263fc 100644--- a/ai-docs/architecture/providers/devin.md+++ b/ai-docs/architecture/providers/devin.md@@ -26,10 +26,14 @@ handler is never built and the model **silently falls through to OpenRouter**. Aquietly succeeding is worse than a crash. Same pattern as Antigravity: empty env var + a dedicated`CredentialProvider` + transport-side `credentials.getRequestAuth()`.-**Access is always EXPLICIT — no bare name ever routes to Devin.** Its uids collide head-on with-other 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 definition-declares **no `nativeModelPatterns`** and there is **no `DEFAULT_ROUTING_RULES` entry**. Same+**Access to a RE-SERVED model is always EXPLICIT — no colliding bare name ever routes to Devin.**+Its uids collide head-on with other 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). The definition therefore declares exactly ONE `nativeModelPatterns`+entry, `/^swe-/i` — Cognition's own line, which collides with nothing — and that claim is the+only way a bare name reaches Devin. Nothing else can: Devin is a dynamic subscription, so it+publishes no catalog connection for `route-candidates.ts` to gather, and the+`DEFAULT_ROUTING_RULES` table that once held a `"swe-*": ["devin"]` entry is deleted. Samereasoning 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` atdiff --git a/ai-docs/architecture/providers/grok-subscription.md b/ai-docs/architecture/providers/grok-subscription.mdindex babf206d..e41f81ed 100644--- a/ai-docs/architecture/providers/grok-subscription.md+++ b/ai-docs/architecture/providers/grok-subscription.md@@ -96,11 +96,23 @@ the exact ambiguity that keeps `openai-codex` out of `SUBSCRIPTION_PROVIDERS`. Bhas no metered path, it is *not* dual-mode and **is** in that set. `GROK_DEPLOYMENT_KEY` (enterprise)is 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 Alibaba Token Plan, which are explicit-access-only because their-uids 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 are-first-wins on array order); bare-name reachability comes from the routing chain instead.+**Bare `grok-*` routes subscription-FIRST.** Unlike Devin and Alibaba Token Plan, which are+explicit-access-only because their uids collide with other vendors' namespaces, these ids are+xAI's own, so a bare name is safe here.++That used to come from a hand-written chain, `["grok-subscription", "x-ai", "openrouter"]`. That+table is gone. The provider now declares `nativeModelPatterns: [{ pattern: /^grok-/i }]` — a+NAMESPACE CLAIM, which is the only way a dynamic subscription can enter a gathered chain at all:+`x-ai/supergrok-subscription` is `client_model_selection_required` in the probe map and+publishes zero `aggregators[]` rows, so the catalog cannot see the plan. `route-candidates.ts`+turns the claim into a `dynamic-subscription`-tier candidate, which the tier order puts ahead of+the metered `x-ai` hop.++The claim does NOT win auto-detection, and that is deliberate: `x-ai` declares the same pattern+and is defined earlier in `BUILTIN_PROVIDERS`, and `getNativeModelPatterns()` is first-wins on+array order, so `parseModelSpec("grok-4.6").provider` is still `x-ai`. Two claimants on one+namespace is fine now — the function that picked a single winner, `getProviderForModel`, no+longer exists.**The roster is discovered, never pinned.** `/v1/models` is genuinely authenticated (401 without atoken — unlike Alibaba's `coding-intl` roster, where a 200 proves nothing) and the served set isdiff --git a/ai-docs/architecture/routing.md b/ai-docs/architecture/routing.mdindex 41c9efe3..1cbdfb75 100644--- a/ai-docs/architecture/routing.md+++ b/ai-docs/architecture/routing.md@@ -56,9 +56,49 @@ Claudish supports local models via:Local APIs report `prompt_tokens` as the FULL conversation context on every request, not anincrement — see `ai-docs/architecture/context-window.md`.+## Where a bare name's chain comes from++**There is no built-in routing table.** `providers/default-routing-rules.ts` — 24 hand-written+globs (`"gpt-*": ["openai-codex", "openai", "openrouter"]`, `"*": ["openrouter"]`) — was+DELETED, together with `mergeRoutingRules`, `retainKnownCatalogRoutingRules` and+`validateDefaultRoutingRules`. `loadRoutingRules()` now returns the user's own global and+project rules and nothing else.++`routeBare` (`providers/routing-rules.ts`) has six steps, and only the first changed:++1. **A user rule matches?** Use that chain **verbatim** — never merged, reordered or appended+ to, including by the fallback hop. `[]` is a match: the user said "no route".+2. **Otherwise gather from the catalog** — `gatherRouteCandidates` (`route-candidates.ts`)+ reads every `aggregators[]` connection the cloud models catalog publishes for the model+ and orders them: tier (`subscription` → `dynamic-subscription` → `native` → `gateway`),+ then the model's own vendor, then cheapest (unknown price last), then larger context+ window, then provider name.+3. **Append the fallback hop** (below).+4. Credential filter (unchanged).+5. Availability filter (unchanged) — only a POSITIVE "not-served" removes anything.+6. Primary + fallbacks.++**No catalog means local only.** With no readable catalog a bare name returns a no-route naming+`claudish --models-refresh`. It is never guessed at `openrouter@<name>`: that sends an id+nobody published to a metered gateway, and a RENAMED id looks identical.++**A dynamic subscription is invisible to the catalog, so it claims a namespace instead.**+`antigravity`, `grok-subscription`, `sakana-subscription` and `devin` sit in the probe map as+`client_model_selection_required` and publish zero connections — the ACCOUNT decides what the+seat serves. Each therefore declares a `nativeModelPatterns` claim (`/^gemini-/i`, `/^grok-/i`,+`/^fugu/i`, `/^swe-/i`) that `gatherFromNamespaceClaims` turns into a candidate. The claim is+not evidence of service; the availability filter asks the account's own dynamic models catalog.+Each claim's namespace is ALSO owned by a metered sibling defined EARLIER in+`BUILTIN_PROVIDERS` (`google`, `x-ai`, `sakana`), which keeps `parseModelSpec`'s first-wins+auto-detection unchanged — two claimants on one namespace is now fine, because the function+that picked a single winner (`getProviderForModel`) no longer exists.+## Default Provider Configuration (v7.0.0+)-`defaultProvider` is a **last-resort fallback** appended to every bare-name routing chain. It is not a "front of the line" override — specific patterns (`gpt-*`, `gemini-*`, etc.) still try their normal providers first. `defaultProvider` only catches models whose explicit chain has zero credentialed providers, or models that match no rule at all.+`defaultProvider` names the **fallback hop** — the last position in a gathered chain. It is a+POSITION, not a property of any provider: whichever provider it names occupies it, and no+definition declares `tier: "fallback"`. It is not a "front of the line" override; everything the+catalog maps is tried first.Set it via:@@ -83,7 +123,35 @@ Set it via:Valid values: any built-in provider name (`"openrouter"`, `"openai"`, `"google"`, `"litellm"`, etc.) or a custom endpoint name defined in `customEndpoints`.-**How it interacts with routing rules**: For each bare-name model, `route()` matches against the rules table, builds the candidate chain, then **appends `defaultProvider` to the end** if it isn't already in the chain (deduped against shortcuts — `or` and `openrouter` are treated as the same provider). The combined chain is then credential-filtered. Explicit `provider@model` specs are not affected — `defaultProvider` only applies to bare names.+**How it interacts with routing rules**: it applies ONLY to the catalog-gathered path. A bare+name that matched a user rule gets that chain verbatim with no fallback appended — which is what+makes `routing["*"] = []` a complete no-route switch. On the gathered path the hop is appended+last, deduped against shortcuts (`or` and `openrouter` are the same provider), and then the+whole chain is credential-filtered. Explicit `provider@model` specs are unaffected.++**Three ways it is EMPTY, and they are different:**++| Setting | Fallback hop |+|---|---|+| unset (`undefined`) | `openrouter` — "no preference" is not "disabled" |+| `""` (explicit empty string) | none |+| a matching user rule, e.g. `routing["*"] = []` | none — the rule is verbatim |++**It is not appended when the catalog positively denies it.** The catalog draws the line itself:+a route the probe map marks `client_model_selection_required` is ACCOUNT-selected, so absence+from a model's connections proves nothing; every other probed route is BACKEND-owned and+publishes its complete connection list, so for those absence IS denial. When the fallback+provider is backend-owned and the model has a catalog entry with no mapped connection to it, the+append is skipped (`catalogDeniesProvider`). Measured on generation+`g-20260921062451697-f490edba`: only 492 of 1,123 models have an OpenRouter connection, so the+deleted `"*": ["openrouter"]` catch-all was sending 417 chat models to a hop the catalog never+mapped — `qwen3.8-max` among them, which has four mapped connections and no OpenRouter.++This is NOT the availability filter and does not duplicate it. `providerServesModel` may never+conclude "not served" from the catalog alone (catalog coverage of SUBSCRIPTION providers is+partial by nature — `openai-codex` appears on 5 rows of 1,123). The route-ownership split is+what makes the narrower question answerable, and only the fallback APPEND asks it: the+difference is inventing a hop nobody published versus dropping one something else put there.**No more LiteLLM auto-promotion** (removed in commit 5 of the model-catalog and routing redesign): Setting `LITELLM_BASE_URL` + `LITELLM_API_KEY` no longer makes LiteLLM the default. Users who want LiteLLM as the catch-all must set `defaultProvider: "litellm"` explicitly.@@ -125,9 +193,10 @@ Plan absence has two different meanings:The backend recommendation projection supplies canonical model IDs and exactroute/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.+catalog for model wire IDs. A user routing rule decides preference when one+matches; otherwise the catalog's own connections do, ordered by tier. 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/packages/cli/src/auth/credentials/source.ts b/packages/cli/src/auth/credentials/source.tsindex f9dad998..e4dbad05 100644--- a/packages/cli/src/auth/credentials/source.ts+++ b/packages/cli/src/auth/credentials/source.ts@@ -44,6 +44,7 @@ import { isLocalProviderEnabled } from "../../profile-config.js";import { hasDevinCredentials } from "../../providers/devin/devin-credentials.js";import { hasSharedAntigravityToken } from "../antigravity-token.js";import { hasOAuthCredentials } from "../oauth-registry.js";+import { peekVertexProjectOrigin } from "../vertex-auth.js";import { realValue } from "./api-key-credential.js";import { credentials } from "./authority.js";@@ -129,6 +130,22 @@ export function describeSourceSync(p: SourceClassifiable, config: SourceConfig):if (realValue(process.env.WINDSURF_API_KEY)) return "env";if (hasDevinCredentials()) return "oauth";}+ // Vertex's `apiKeyEnvVar` is not a key: it is a Google Cloud PROJECT id, and+ // `resolveVertexConfig` reads it from the ADC file's `quota_project_id` or+ // `gcloud config` as readily as from the environment. Without this branch the+ // env/cfg rules below report `null` — "not configured" — for an install that+ // signs every request, which is the display half of the defect this fixes.+ //+ // `"oauth"` rather than a new union member, for the same reason Devin reuses+ // it: the credential really is a login-minted token on disk+ // (`gcloud auth application-default login`), and `CredentialSource` is a WIRE+ // CONTRACT read by claude-desktop-profiles — a new member costs a coordinated+ // release. An env-supplied project falls through to the generic rules, which+ // are already exactly right for it.+ if (p.catalogName === "vertex") {+ const origin = peekVertexProjectOrigin();+ if (origin && origin.source !== "env") return "oauth";+ }// realValue() drops an unexpanded `${VAR}` placeholder — the literal string a// host passes through when the referenced shell variable is unset. Sign-time// refuses to use one, so it must not count as a credential here either.diff --git a/packages/cli/src/auth/vertex-auth.ts b/packages/cli/src/auth/vertex-auth.tsindex 67c2a80c..6956d57e 100644--- a/packages/cli/src/auth/vertex-auth.ts+++ b/packages/cli/src/auth/vertex-auth.ts@@ -16,7 +16,7 @@*/import { exec } from "node:child_process";-import { existsSync } from "node:fs";+import { existsSync, readFileSync } from "node:fs";import { readFile } from "node:fs/promises";import { homedir } from "node:os";import { join } from "node:path";@@ -32,13 +32,22 @@ const execAsync = promisify(exec);* credential-presence check and the project resolution all read the SAME file,* and a copy that drifted would make one of them disagree with the others.*/-function adcCredentialsPath(): string {+export function adcCredentialsPath(): string {return join(homedir(), ".config/gcloud/application_default_credentials.json");}/** Vertex location used when VERTEX_LOCATION is unset — a DEFAULT, never a guess. */const DEFAULT_VERTEX_LOCATION = "us-central1";+/**+ * Environment variables that name the Google Cloud project, in precedence order.+ *+ * Exported because provenance reporting has to inspect the SAME list+ * `resolveVertexConfig` reads. A second spelling in `api-key-provenance.ts` is+ * how a display surface ends up saying "not set" about a variable that is set.+ */+export const VERTEX_PROJECT_ENV_VARS = ["VERTEX_PROJECT", "GOOGLE_CLOUD_PROJECT"] as const;+interface VertexAccessToken {token: string;expiresAt: number;@@ -216,29 +225,135 @@ export class VertexAuthManager {* machine's CURRENT gcloud state; a cached copy would outlive* `gcloud config set project` and silently bill the previous project.*/-let discoveredProjectPromise: Promise<string | null> | null = null;+let discoveredProjectPromise: Promise<VertexProjectOrigin | null> | null = null;/**- * Reset the discovery memo. Test seam — production resolves once per process.+ * The SETTLED value of the promise above, once it has settled.+ *+ * Exists for the sync surfaces (React render paths, `describeSourceSync`), which+ * cannot await a promise but must not report a working Vertex as unconfigured.+ * `undefined` means "discovery has not finished"; `null` means "it finished and+ * found nothing" — two different answers, so it is deliberately a tri-state.+ */+let discoveredProjectSettled: VertexProjectOrigin | null | undefined;++/**+ * Per-process memo of the SYNC ADC-file read, both outcomes.+ *+ * Same lifetime and rationale as the async memo: nothing is written to disk, and+ * a resolved project is a fact about this machine's current gcloud state. Kept+ * separate because the sync path can answer only the first discovery tier — it+ * must never shell out to `gcloud` (a subprocess per React render), so a sync+ * miss is not the same statement as an async miss.+ */+let syncAdcOrigin: VertexProjectOrigin | null | undefined;++/**+ * Reset the discovery memos. Test seam — production resolves once per process.*/export function resetVertexProjectDiscovery(): void {discoveredProjectPromise = null;+ discoveredProjectSettled = undefined;+ syncAdcOrigin = undefined;+}++/** Which of the three tiers supplied the Google Cloud project. */+export type VertexProjectSource = "env" | "adc-file" | "gcloud-config";++/**+ * A resolved project AND the thing that supplied it.+ *+ * The project alone is not enough for any surface that has to tell the user what+ * to change: "not set" about `VERTEX_PROJECT` is a lie on a machine where the+ * project came from the ADC file, and it sends the reader looking for an API key+ * that does not exist.+ */+export interface VertexProjectOrigin {+ projectId: string;+ source: VertexProjectSource;+ /** Exactly what supplied it: an env var NAME, a file path, or a command. */+ detail: string;+}++/**+ * A short, display-ready phrase naming the source — one wording, every surface.+ *+ * Deliberately WITHOUT the ADC file's full path: this goes in a table cell and a+ * fixed-height detail row, and `~/.config/gcloud/application_default_credentials.json`+ * is 52 characters that push the project id itself off the end. The exact path+ * still appears as a provenance LAYER, which is the place that names locations.+ */+export function describeVertexProjectSource(origin: VertexProjectOrigin): string {+ switch (origin.source) {+ case "env":+ return `$${origin.detail}`;+ case "adc-file":+ return "the ADC file's quota_project_id";+ case "gcloud-config":+ return `\`${origin.detail}\``;+ }+}++/**+ * What to do when no project resolves — ONE sentence, used by every surface.+ *+ * Names BOTH remedies and no API key, because Vertex has none: the Express+ * API-key mode was deleted on 2026-09-21 and the credential is Application+ * Default Credentials. `validateVertexOAuthConfig` is the long-form version for+ * error paths; this is the one-liner for a table cell or a status row.+ */+export const VERTEX_SET_PROJECT_REMEDY =+ "set VERTEX_PROJECT or run `gcloud config set project <id>`";++/** The same two remedies, plus the fact that rules out the third guess. */+export const VERTEX_NO_PROJECT_REMEDY = `${VERTEX_SET_PROJECT_REMEDY} — Vertex takes no API key`;++/** The remedy with its cause in front, for a cell that stands on its own. */+export const VERTEX_NO_PROJECT_HINT = `no Google Cloud project: ${VERTEX_NO_PROJECT_REMEDY}`;++/** The project from the environment, read fresh on every call. */+function envProjectOrigin(): VertexProjectOrigin | null {+ for (const name of VERTEX_PROJECT_ENV_VARS) {+ const value = process.env[name]?.trim();+ if (value) return { projectId: value, source: "env", detail: name };+ }+ return null;}/** `quota_project_id` from the ADC file — the same file the token path reads. */-async function readAdcQuotaProject(): Promise<string | null> {+async function readAdcQuotaProject(): Promise<VertexProjectOrigin | null> {try {const raw = await readFile(adcCredentialsPath(), "utf-8");- const parsed = JSON.parse(raw) as { quota_project_id?: unknown };- const project =- typeof parsed.quota_project_id === "string" ? parsed.quota_project_id.trim() : "";- return project || null;+ return adcOriginFromJson(raw);} catch (e: any) {log(`[VertexAuth] No project in ADC file: ${e.message}`);return null;}}+/**+ * The SYNC twin of the read above — the only discovery tier a render path can+ * afford. A ~1KB JSON read, memoized per process; `gcloud config` is NOT+ * consulted here, because spawning a subprocess on a React render is the+ * mistake `keychain.md` records.+ */+export function peekVertexAdcProject(): VertexProjectOrigin | null {+ if (syncAdcOrigin !== undefined) return syncAdcOrigin;+ try {+ syncAdcOrigin = adcOriginFromJson(readFileSync(adcCredentialsPath(), "utf-8"));+ } catch {+ syncAdcOrigin = null;+ }+ return syncAdcOrigin;+}++/** Parse one ADC file body into an origin. Shared by the sync and async reads. */+function adcOriginFromJson(raw: string): VertexProjectOrigin | null {+ const parsed = JSON.parse(raw) as { quota_project_id?: unknown };+ const project = typeof parsed.quota_project_id === "string" ? parsed.quota_project_id.trim() : "";+ return project ? { projectId: project, source: "adc-file", detail: adcCredentialsPath() } : null;+}+/*** The project from `gcloud config`.*@@ -252,7 +367,7 @@ async function readAdcQuotaProject(): Promise<string | null> {* Same 10s timeout as the token calls above: a hung gcloud must not hang a* request.*/-async function readGcloudConfigProject(): Promise<string | null> {+async function readGcloudConfigProject(): Promise<VertexProjectOrigin | null> {for (const command of ["gcloud config get project", "gcloud config get-value project"]) {try {const { stdout } = await execAsync(command, { timeout: 10000 });@@ -271,7 +386,7 @@ async function readGcloudConfigProject(): Promise<string | null> {// the user is waiting for an error message.if (!value || value === "(unset)" || /\s/.test(value)) return null;log(`[VertexAuth] Project from \`${command}\``);- return value;+ return { projectId: value, source: "gcloud-config", detail: command };} catch (e: any) {log(`[VertexAuth] \`${command}\` failed: ${e.message}`);}@@ -286,15 +401,21 @@ async function readGcloudConfigProject(): Promise<string | null> {* project would otherwise pay two `gcloud` invocations (up to their 10s timeout)* on every single request.*/-function discoverOnce(): Promise<string | null> {+function discoverOnce(): Promise<VertexProjectOrigin | null> {if (!discoveredProjectPromise) {- discoveredProjectPromise = discoverVertexProject();+ // The settled value is recorded as a SIDE EFFECT of the same promise, so the+ // sync peek can never disagree with the async answer: there is one+ // resolution, published twice.+ discoveredProjectPromise = discoverVertexProject().then((origin) => {+ discoveredProjectSettled = origin;+ return origin;+ });}return discoveredProjectPromise;}/** Discovery tiers only — the env tier lives in resolveVertexConfig. */-async function discoverVertexProject(): Promise<string | null> {+async function discoverVertexProject(): Promise<VertexProjectOrigin | null> {const fromAdc = await readAdcQuotaProject();if (fromAdc) {log("[VertexAuth] Project from ADC quota_project_id");@@ -303,6 +424,43 @@ async function discoverVertexProject(): Promise<string | null> {return readGcloudConfigProject();}+/**+ * The project AND its source, with the same precedence as+ * {@link resolveVertexConfig} — which is implemented in terms of this.+ */+export async function resolveVertexProjectOrigin(): Promise<VertexProjectOrigin | null> {+ return envProjectOrigin() ?? (await discoverOnce());+}++/**+ * The best answer available WITHOUT awaiting: the environment, then a settled+ * discovery, then the ADC file read synchronously.+ *+ * Never shells out, so it can be called from a React render or any other sync+ * classifier. `null` here means "nothing resolved by the tiers a sync caller can+ * afford" — on a machine whose project comes only from `gcloud config`, that+ * stays null until something async (the credential authority, a probe, a+ * request) has run `resolveVertexProjectOrigin` once.+ */+export function peekVertexProjectOrigin(): VertexProjectOrigin | null {+ const fromEnv = envProjectOrigin();+ if (fromEnv) return fromEnv;+ if (discoveredProjectSettled !== undefined) return discoveredProjectSettled;+ return peekVertexAdcProject();+}++/**+ * Whether an Application Default Credential (or a service-account file) is+ * present at all — the thing that signs a Vertex request, as opposed to the+ * project that addresses it.+ *+ * Sync and cheap (one `existsSync`, one env read) so display paths can tell+ * "signed in but no project" from "no credential at all".+ */+export function hasVertexAdcCredentials(): boolean {+ return existsSync(adcCredentialsPath()) || !!process.env.GOOGLE_APPLICATION_CREDENTIALS;+}+/*** Resolve the Vertex project and location.*@@ -319,14 +477,13 @@ async function discoverVertexProject(): Promise<string | null> {* invented id. `validateVertexOAuthConfig` turns that null into the remedy.*/export async function resolveVertexConfig(): Promise<VertexConfig | null> {- const projectId =- process.env.VERTEX_PROJECT || process.env.GOOGLE_CLOUD_PROJECT || (await discoverOnce());- if (!projectId) {+ const origin = await resolveVertexProjectOrigin();+ if (!origin) {return null;}return {- projectId,+ projectId: origin.projectId,location: process.env.VERTEX_LOCATION || DEFAULT_VERTEX_LOCATION,};}@@ -353,6 +510,8 @@ export function selectVertexAuthMode(configured: { project?: string }): "projectexport async function validateVertexOAuthConfig(): Promise<string | null> {const hasADC = existsSync(adcCredentialsPath());const hasServiceAccount = !!process.env.GOOGLE_APPLICATION_CREDENTIALS;+ // One sentence per failure, and NEITHER of them mentions an API key: there is+ // no key to find. The Express mode was deleted on 2026-09-21.const noCredentials ="No Vertex AI credentials found.\n\n" +"Options:\n" +diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.tsindex c3b759d1..1b73a2bd 100644--- a/packages/cli/src/cli.ts+++ b/packages/cli/src/cli.ts@@ -51,7 +51,7 @@ import {readProOnUltracode,} from "./profile-config.js";import { API_KEY_MAP } from "./providers/api-key-map.js";-import { type KeyProvenance, resolveApiKeyProvenance } from "./providers/api-key-provenance.js";+import { type KeyProvenance, resolveCredentialProvenance } from "./providers/api-key-provenance.js";import type { FallbackRoute } from "./providers/auto-route.js";import { latestAnthropicTierModelId } from "./providers/catalog-client.js";import { claudeCodeTierAlias, normalizeNativeModelSpec } from "./providers/claude-code-aliases.js";@@ -63,6 +63,7 @@ import { pinProbeModelSpec, probeProviderRoute } from "./providers/probe-runner.import { BUILTIN_PROVIDERS, getProviderByName } from "./providers/provider-definitions.js";import { resolveProviderSlug } from "./providers/provider-slug-resolve.js";import {+ buildCatalogChain,buildRoutingChain,hasCredentialsForProvider,loadRoutingRules,@@ -1393,15 +1394,43 @@ async function probeModelRouting(type LiveProxy = { url: string; shutdown: () => Promise<void> };// Snapshot user-defined routing keys so we can label matches as- // "custom-rules" vs "auto-chain" (default rules) in --probe output.- // Defaults are merged INSIDE loadRoutingRules() but are not returned- // from loadConfig/loadLocalConfig directly — those reads see only user- // overrides, which is exactly the discriminator we need here.+ // "custom-rules" vs "auto-chain" in --probe output. Every rule+ // `loadRoutingRules()` returns is now the user's own — there is no shipped+ // table left to merge — so this set and that one have the same keys; the+ // snapshot stays because the labelling reads more clearly for it.const userRoutingKeys = new Set<string>([...Object.keys(loadConfig().routing ?? {}),...Object.keys(loadLocalConfig()?.routing ?? {}),]);+ /**+ * The remedy a credential-less row shows.+ *+ * Reads it off the PROVENANCE rather than naming providers here: a record that+ * carries an `effectiveLabel` is one whose credential is not an environment+ * variable at all (Vertex, whose Google Cloud project comes from the ADC file+ * or `gcloud config`), and for those the variable name is the wrong+ * instruction — its `effectiveSource` is the sentence that names both+ * remedies. Everyone else keeps the bare variable name they always had.+ */+ function credentialHintFrom(+ provenance: KeyProvenance | undefined,+ envVar: string | undefined+ ): string | undefined {+ if (provenance?.effectiveLabel) return provenance.effectiveSource;+ return envVar;+ }++ /** The same remedy where no provenance record has been built yet. */+ function credentialHintFor(+ provider: string,+ envVar: string | undefined,+ aliases: string[] | undefined+ ): string | undefined {+ if (!envVar) return undefined;+ return credentialHintFrom(resolveCredentialProvenance(provider, envVar, aliases), envVar);+ }+/** Build chain + credential data for a single model (shared by both paths) */function buildModelChain(modelInput: string) {const parsed = parseModelSpec(modelInput);@@ -1478,8 +1507,8 @@ async function probeModelRouting(matchedPattern: undefined,};}- // Routing rules now always include DEFAULT_ROUTING_RULES merged with- // user overrides — see loadRoutingRules() in providers/routing-rules.ts.+ // Only the USER's rules now — the shipped table is gone, so most models+ // match nothing here and are routed from the catalog instead.const routingRules = loadRoutingRules();const matched = matchRoutingRule(parsed.model, routingRules);if (matched) {@@ -1493,8 +1522,6 @@ async function probeModelRouting(}return false;});- // Distinguish user overrides from shipped defaults so --probe can show- // "custom-rules" vs "auto-chain" exactly as before.const isUserKey = !!matchedPattern && userRoutingKeys.has(matchedPattern);return {routes: buildRoutingChain(matched, parsed.model),@@ -1502,8 +1529,16 @@ async function probeModelRouting(matchedPattern,};}+ // No user rule: the SAME chain `routeBare` would assemble — gathered from+ // the cloud models catalog, with the fallback hop appended. This used to+ // read the shipped rules table; reproducing the gathering by hand here+ // would be the second copy of a routing decision, and the two would+ // disagree the first time either changed. `--probe` still owns the+ // credential-provenance display below, which is why it builds a chain at+ // all instead of calling `route()`.return {- routes: [] as FallbackRoute[],+ routes: buildCatalogChain(parsed.model, loadConfig().defaultProvider)+ .routes as FallbackRoute[],source: "auto-chain" as const,matchedPattern: undefined,};@@ -1535,13 +1570,13 @@ async function probeModelRouting(} else if (!keyInfo.envVar) {hasCredentials = true;} else {- provenance = resolveApiKeyProvenance(keyInfo.envVar, keyInfo.aliases);+ provenance = resolveCredentialProvenance(route.provider, keyInfo.envVar, keyInfo.aliases);hasCredentials = provenance.hasValue;if (!hasCredentials && keyInfo.aliases) {hasCredentials = keyInfo.aliases.some((a) => !!process.env[a]);}if (!hasCredentials) {- credentialHint = keyInfo.envVar;+ credentialHint = credentialHintFrom(provenance, keyInfo.envVar);}}@@ -1577,16 +1612,20 @@ async function probeModelRouting(await Promise.all(result.chainDetails.map(async (link) => {link.hasCredentials = await credentialForProbe(link.provider);+ const keyInfo = API_KEY_MAP[link.provider];+ if (keyInfo?.envVar)+ link.provenance = resolveCredentialProvenance(+ link.provider,+ keyInfo.envVar,+ keyInfo.aliases+ );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);+ : credentialHintFrom(link.provenance, keyInfo?.envVar);}));if (result.chain.source === "direct") await credentialForProbe(result.parsed.provider);@@ -1652,7 +1691,7 @@ async function probeModelRouting(const hasCredentials = probeCredentialReadiness.get(parsed.provider) ?? false;const provenance = keyInfo?.envVar- ? resolveApiKeyProvenance(keyInfo.envVar, keyInfo.aliases)+ ? resolveCredentialProvenance(parsed.provider, keyInfo.envVar, keyInfo.aliases): undefined;return [@@ -1666,7 +1705,7 @@ async function probeModelRouting(credentialHint: !hasCredentials? providerDef?.isLocal? "enable local provider in global config"- : keyInfo?.envVar+ : credentialHintFrom(provenance, keyInfo?.envVar): undefined,provenance,probe: directProbe,@@ -1701,7 +1740,7 @@ async function probeModelRouting(credentialHint: !directHasCreds? directProviderDef?.isLocal? "enable local provider in global config"- : directKeyInfo?.envVar+ : credentialHintFor(parsed.provider, directKeyInfo?.envVar, directKeyInfo?.aliases): undefined,probe: directProbe,},@@ -1850,7 +1889,7 @@ async function probeModelRouting(const directCredentialHint =directProviderDef?.isLocal && !directHasCreds? "enable local provider in global config"- : directKeyInfo?.envVar;+ : credentialHintFor(parsed.provider, directKeyInfo?.envVar, directKeyInfo?.aliases);directProbeResult = await probeProviderRoute(liveProxy.url,{@@ -2027,7 +2066,7 @@ async function probeModelRouting(const directCredentialHint =directProviderDef?.isLocal && !directHasCreds? "enable local provider in global config"- : directKeyInfo?.envVar;+ : credentialHintFor(parsed.provider, directKeyInfo?.envVar, directKeyInfo?.aliases);allLinks.push({id: `${modelInput}:direct`,displayName: parsed.provider,diff --git a/packages/cli/src/probe/probe-results-printer.ts b/packages/cli/src/probe/probe-results-printer.tsindex 78722ac9..69d79dff 100644--- a/packages/cli/src/probe/probe-results-printer.ts+++ b/packages/cli/src/probe/probe-results-printer.ts@@ -732,10 +732,16 @@ function formatContextWindow(ctx: number): string {function buildKeyLine(activeEntry?: ChainEntry, directKeyVar?: string): string {if (activeEntry?.provenance) {const p = activeEntry.provenance;+ // `effectiveLabel` replaces `$ENV_VAR` for a provider whose credential is not+ // an environment variable — Vertex, whose project comes from the ADC file or+ // `gcloud config`. Printing `$VERTEX_PROJECT (not set)` there names a+ // variable that is not how the install works.+ const subject = p.effectiveLabel ?? `$${p.envVar}`;if (p.hasValue) {- return `${pc.bold}Key${pc.reset} $${p.envVar} ${pc.dim}(${p.effectiveSource})${pc.reset}`;+ return `${pc.bold}Key${pc.reset} ${subject} ${pc.dim}(${p.effectiveSource})${pc.reset}`;}- return `${pc.bold}Key${pc.reset} $${p.envVar} ${pc.dim}(not set)${pc.reset}`;+ const why = p.effectiveLabel ? p.effectiveSource : "not set";+ return `${pc.bold}Key${pc.reset} ${subject} ${pc.dim}(${why})${pc.reset}`;}if (directKeyVar) {const has = !!process.env[directKeyVar];diff --git a/packages/cli/src/providers/api-key-provenance.ts b/packages/cli/src/providers/api-key-provenance.tsindex 6dacab9c..29c65649 100644--- a/packages/cli/src/providers/api-key-provenance.ts+++ b/packages/cli/src/providers/api-key-provenance.ts@@ -27,6 +27,14 @@ import { homedir } from "node:os";import { join, resolve } from "node:path";import { parse as parseDotenv } from "dotenv";import { isKeychainHydratedVar } from "../auth/credentials/keychain-source.js";+import {+ VERTEX_NO_PROJECT_REMEDY,+ VERTEX_PROJECT_ENV_VARS,+ adcCredentialsPath,+ describeVertexProjectSource,+ peekVertexAdcProject,+ peekVertexProjectOrigin,+} from "../auth/vertex-auth.js";import { activeGlobalConfigFile, getConfigFileOverride } from "../config-override.js";import { isOpHydratedVar } from "./onepassword.js";@@ -75,6 +83,25 @@ export interface KeyProvenance {effectiveMasked: string | null;effectiveSource: string;layers: KeyLayer[];+ /**+ * What to print INSTEAD of `$envVar` when the credential did not come from an+ * environment variable at all.+ *+ * Undefined for every provider whose credential is an env-var API key — which+ * is all but one — so their lines are unchanged. It exists because Vertex has+ * no API key: it authenticates with Application Default Credentials and+ * addresses a Google Cloud project that may come from the ADC file or+ * `gcloud config`, and a row reading `$VERTEX_PROJECT (not set)` about a+ * working install is worse than no row at all.+ *+ * SECURITY: display-safe by construction, like `effectiveMasked`. A builder+ * that sets it must put no key material in it. Vertex's is a GCP project id,+ * which is an identifier rather than a secret — it appears in every Vertex+ * request URL and in the proxy's own handler log line — so it is shown whole:+ * masking it would hide the one fact the row exists to report, WHICH project+ * this machine will bill.+ */+ effectiveLabel?: string;}function maskKey(key: string | undefined | null): string | null {@@ -173,12 +200,101 @@ export function resolveApiKeyProvenance(envVar: string, aliases?: string[]): Key};}+/**+ * Provenance for ONE provider's credential — the entry point every display+ * surface should call.+ *+ * Identical to {@link resolveApiKeyProvenance} for every provider whose+ * credential is an env-var API key. It exists for the one that is not: Vertex+ * resolves a PROJECT (not a key) from the environment, the ADC file's+ * `quota_project_id`, or `gcloud config`, so the env/config layers alone report+ * "not set" about an install that works perfectly.+ *+ * The branch lives here, in the module that owns provenance, rather than in each+ * of the four call sites (`--probe`'s three chain builders and the handler log).+ * Four copies of one provider rule is the second-table coupling this codebase+ * keeps paying for.+ */+export function resolveCredentialProvenance(+ provider: string,+ envVar: string,+ aliases?: string[]+): KeyProvenance {+ if (provider === "vertex") return vertexProjectProvenance(envVar, aliases);+ return resolveApiKeyProvenance(envVar, aliases);+}++/**+ * Vertex's provenance: the env/config layers, PLUS the two tiers+ * `resolveVertexConfig` consults that no environment inspection can see.+ *+ * `GOOGLE_CLOUD_PROJECT` is passed as an alias because `resolveVertexConfig`+ * reads it — not because `API_KEY_MAP` lists it. The variable list comes from+ * `VERTEX_PROJECT_ENV_VARS`, the same constant the resolution uses, so this+ * cannot drift from what actually decides the project.+ *+ * The non-env tiers are read through `peekVertexProjectOrigin`, which is sync+ * and never shells out; a project that only `gcloud config` knows therefore+ * shows up here once anything async (the credential authority, a probe, a real+ * request) has resolved it. Until then this reports the honest "no project yet"+ * with both remedies, never a missing API key.+ */+function vertexProjectProvenance(envVar: string, aliases?: string[]): KeyProvenance {+ const envNames = [...new Set([envVar, ...(aliases ?? []), ...VERTEX_PROJECT_ENV_VARS])];+ const base = resolveApiKeyProvenance(envNames[0], envNames.slice(1));+ const origin = peekVertexProjectOrigin();+ // Always shown, value included when known, so a project the ADC file holds is+ // visible even while an env var shadows it — the same "(shadowed)" honesty the+ // config layer already gets.+ const adc = peekVertexAdcProject();+ const adcLayer: KeyLayer = {+ source: `${adcCredentialsPath()} (quota_project_id)`,+ maskedValue: adc?.projectId ?? null,+ isActive: origin?.source === "adc-file",+ };+ const gcloudLayer: KeyLayer = {+ source: "`gcloud config get project`",+ maskedValue: origin?.source === "gcloud-config" ? origin.projectId : null,+ isActive: origin?.source === "gcloud-config",+ };++ if (!origin) {+ return {+ ...base,+ hasValue: false,+ effectiveMasked: null,+ effectiveLabel: "no project",+ effectiveSource: VERTEX_NO_PROJECT_REMEDY,+ layers: [...base.layers, adcLayer, gcloudLayer],+ };+ }+ if (origin.source === "env") {+ // The env tiers are exactly what `resolveApiKeyProvenance` already models —+ // including .env and the config file, which reach Vertex the same way they+ // reach any other provider. Only the two extra layers are appended.+ return { ...base, layers: [...base.layers, adcLayer, gcloudLayer] };+ }+ return {+ ...base,+ hasValue: true,+ // The project id, whole and unmasked — see `KeyProvenance.effectiveLabel`.+ effectiveMasked: origin.projectId,+ effectiveLabel: `project ${origin.projectId}`,+ effectiveSource: describeVertexProjectSource(origin),+ // Nothing in the environment supplied the value, so no env layer is active.+ layers: [...base.layers.map((l) => ({ ...l, isActive: false })), adcLayer, gcloudLayer],+ };+}+/*** Format provenance for debug log output (single line).*/export function formatProvenanceLog(p: KeyProvenance): string {if (!p.hasValue) {- return `${p.envVar}=(not set)`;+ return p.effectiveLabel ? `${p.effectiveLabel}: ${p.effectiveSource}` : `${p.envVar}=(not set)`;+ }+ if (p.effectiveLabel) {+ return `${p.effectiveLabel} [from: ${p.effectiveSource}]`;}return `${p.envVar}=${p.effectiveMasked} [from: ${p.effectiveSource}]`;}@@ -190,11 +306,21 @@ export function formatProvenanceProbe(p: KeyProvenance, indent = " "): stringconst lines: string[] = [];if (!p.hasValue) {- lines.push(`${indent}${p.envVar}: not set`);+ // `effectiveLabel` carries the remedy for a provider with no env-var key at+ // all (Vertex), where "VERTEX_PROJECT: not set" is the wrong instruction.+ lines.push(+ p.effectiveLabel+ ? `${indent}${p.effectiveLabel}: ${p.effectiveSource}`+ : `${indent}${p.envVar}: not set`+ );return lines;}- lines.push(`${indent}${p.envVar} = ${p.effectiveMasked} [from: ${p.effectiveSource}]`);+ lines.push(+ p.effectiveLabel+ ? `${indent}${p.effectiveLabel} [from: ${p.effectiveSource}]`+ : `${indent}${p.envVar} = ${p.effectiveMasked} [from: ${p.effectiveSource}]`+ );for (const layer of p.layers) {const marker = layer.isActive ? ">>>" : " ";diff --git a/packages/cli/src/providers/auto-route.ts b/packages/cli/src/providers/auto-route.tsindex 66bc7759..f82afe34 100644--- a/packages/cli/src/providers/auto-route.ts+++ b/packages/cli/src/providers/auto-route.ts@@ -3,11 +3,12 @@** After commit 5 of the model-catalog and routing redesign, this file is no* longer the home of the routing chain logic — that lives in- * `providers/routing-rules.ts` (`route()`) and ships defaults via- * `providers/default-routing-rules.ts`. What remains here are the two derived- * lookup tables (canonical name → shortest @ prefix, canonical name → display- * name) that the routing engine still needs, plus a `FallbackRoute` type alias- * preserved for callers that imported it from here pre-commit-5.+ * `providers/routing-rules.ts` (`route()`), which gathers its candidates from+ * the cloud models catalog (`providers/route-candidates.ts`). What remains here+ * are the two derived lookup tables (canonical name → shortest @ prefix,+ * canonical name → display name) that the routing engine still needs, plus a+ * `FallbackRoute` type alias preserved for callers that imported it from here+ * pre-commit-5.** Kept at the same path for import-stability across the codebase.*/diff --git a/packages/cli/src/providers/catalog-query.ts b/packages/cli/src/providers/catalog-query.tsindex 6c62034b..46900856 100644--- a/packages/cli/src/providers/catalog-query.ts+++ b/packages/cli/src/providers/catalog-query.ts@@ -53,6 +53,17 @@ export interface CatalogEntryQueryResult {supportsVision?: boolean;/** Context window in tokens. Optional — may be absent on older entries. */contextWindow?: number;+ /**+ * ISO release date (`YYYY-MM-DD`) the catalog publishes for this model.+ *+ * Surfaced for Vertex probe discovery: Vertex's publisher listing reports no+ * date at all, so a dynamic models catalog built from it would rank by the+ * version digits in the id alone and put a 2-year-old `gemma`-style row above+ * the newest Gemini. The date is a property of the MODEL, which the catalog+ * already publishes, so reading it here asserts nothing about the project.+ * Optional — older cache files and unlisted models carry none.+ */+ releaseDate?: string;/*** Multi-aggregator routing index. Each entry is `{provider, externalId, confidence}`.* Surfaced for the pricing-cache lookup (item 6.2) which needs to find the@@ -68,6 +79,7 @@ function project(entry: SlimModelEntry): CatalogEntryQueryResult {aliases: entry.aliases,supportsVision: entry.supportsVision,contextWindow: entry.contextWindow,+ releaseDate: entry.releaseDate,aggregators: entry.aggregators,};}diff --git a/packages/cli/src/providers/catalog-route-bindings.ts b/packages/cli/src/providers/catalog-route-bindings.tsindex 98126db4..7e6216ef 100644--- a/packages/cli/src/providers/catalog-route-bindings.ts+++ b/packages/cli/src/providers/catalog-route-bindings.ts@@ -18,6 +18,13 @@ export const CATALOG_ROUTE_BINDINGS: Readonly<Record<string, CatalogRouteBindingmoonshotai: { routeId: "moonshotai", routeProfileId: "direct-api" },"glm-coding": { routeId: "z-ai", routeProfileId: "glm-coding-subscription" },"z-ai": { routeId: "z-ai", routeProfileId: "direct-api" },+ // The SAME endpoint as `z-ai` (both are https://api.z.ai) under a second+ // claudish name, because the two carry different key silos: ZHIPU_API_KEY and+ // ZAI_API_KEY. Both must bind, or a user whose key sits in the other variable+ // loses Z.ai by bare name with nothing printed — measured on 11 models when+ // only `z-ai` was bound. Which one serves is then the credential filter's+ // decision, which is where it belongs.+ glm: { 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" },@@ -51,13 +58,32 @@ export function catalogRouteForProvider(provider: string): CatalogRouteBinding |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;+ return providersForCatalogRoute(route)[0];+}++/**+ * EVERY claudish provider bound to one catalog route, in declaration order.+ *+ * The binding table is many-to-one on purpose: one endpoint can wear several+ * claudish names because each name owns a different key silo (`glm` and `z-ai`+ * are both https://api.z.ai, under ZHIPU_API_KEY and ZAI_API_KEY), and some+ * names are legacy spellings kept so an old `provider@model` spec still parses.+ *+ * Routing must consider all of them, and {@link providerForCatalogRoute} — which+ * answers with the first — silently hid the rest: a user whose key sat in the+ * second silo lost the model by bare name, with no error, because the candidate+ * carrying their credential was never gathered. Deciding WHICH of them serves is+ * the credential filter's job; a name with no provider definition drops out on+ * its own, one layer down, since it has no tier.+ */+export function providersForCatalogRoute(route: CatalogRouteBinding | undefined): string[] {+ if (!route) return [];+ return Object.entries(CATALOG_ROUTE_BINDINGS)+ .filter(+ ([, binding]) =>+ binding.routeId === route.routeId && binding.routeProfileId === route.routeProfileId+ )+ .map(([provider]) => provider);}export function catalogRouteMatchesProvider(diff --git a/packages/cli/src/providers/default-routing-rules.ts b/packages/cli/src/providers/default-routing-rules.tsdeleted file mode 100644index e204b244..00000000--- a/packages/cli/src/providers/default-routing-rules.ts+++ /dev/null@@ -1,203 +0,0 @@-/**- * Default routing rules shipped with claudish.- *- * Same shape users edit via `claudish config route` (see `RoutingRules` in- * `profile-config.ts`). Users can override any pattern (including the catch-all- * `"*"`) by writing their own routing rules in `~/.claudish/config.json` or a- * project-local `.claudish.json` — user rules merge ON TOP of these defaults at- * load time (see `loadRoutingRules` in `routing-rules.ts`).- *- * Rule design notes:- * - Subscription endpoints come FIRST (people who paid for them want them- * used; the chain falls through automatically when subscription credentials- * are missing because route() filters by credential availability).- * - Direct-API providers come second.- * - OpenRouter is last by convention — it's a universal aggregator. Users- * who don't want OpenRouter as the catch-all override "*" with their own- * chain or [].- * - The `provider@model` rewrite syntax (see kimi-* below) is used when a- * subscription endpoint expects a different model name than the direct API.- *- */-import type { RoutingRules } from "../profile-config.js";-import { PROVIDER_SHORTCUTS } from "./model-parser.js";-import { getProviderByName } from "./provider-definitions.js";--export const DEFAULT_ROUTING_RULES: RoutingRules = {- // Anthropic Claude — native first, then OpenRouter.- "claude-*": ["native-anthropic", "openrouter"],-- // OpenAI families: Codex subscription first, then direct API, then OpenRouter.- "gpt-*": ["openai-codex", "openai", "openrouter"],- "o1-*": ["openai-codex", "openai", "openrouter"],- "o3-*": ["openai-codex", "openai", "openrouter"],-- // Google Gemini: Antigravity subscription, direct API, OpenRouter.- //- // `antigravity` holds the subscription slot that `gemini-codeassist` used to.- // Google retired Code Assist for individuals (UNSUPPORTED_CLIENT for- // gemini-cli's OAuth client), so leaving the retired provider at the head of- // this chain cost a guaranteed-failing round-trip and then silently billed the- // metered `google` API for a model the user's subscription already covers.- //- // Antigravity's served ids carry a reasoning-tier suffix- // (`gemini-3.6-flash-high`); the transport resolves a bare family name against- // the account's LIVE served set, so a bare `gemini-3.6-flash` routes correctly- // here. No token → route() filters the candidate out and `google` takes over.- "gemini-*": ["antigravity", "google", "openrouter"],-- // 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-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 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 `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- // metered Moonshot API rather than being silently answered by a different- // 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, gated by catalog membership.- "kimi-*": ["kimi-coding", "opencode-zen-go", "kimi", "openrouter"],- "k3*": ["kimi-coding", "opencode-zen-go", "kimi", "openrouter"],-- // MiniMax (matchRoutingRule is case-insensitive, so a single rule covers- // both `MiniMax-M2.5` and `minimax-m2.5`).- "minimax-*": ["minimax-coding", "opencode-zen-go", "minimax", "openrouter"],-- // GLM: coding plan, Zen Go plan, direct, OpenRouter.- "glm-*": ["glm-coding", "opencode-zen-go", "glm", "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).- //- // 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"],-- // DeepSeek: Zen Go plan, then the metered direct API, then OpenRouter.- "deepseek-*": ["opencode-zen-go", "deepseek", "openrouter"],-- // MiMo and HunYuan are served by the Zen Go plan and had no rule at all, so- // they fell to the `*` catch-all and were billed through OpenRouter.- "mimo-*": ["opencode-zen-go", "openrouter"],- "hy3*": ["opencode-zen-go", "openrouter"],-- // Mistral: direct API, then OpenRouter. Three separate product lines —- // `ministral-` and `codestral-` are not prefixes of `mistral-`, so a single- // glob cannot cover them. `magistral-*` is deliberately NOT claimed: it is not- // in the catalog's mistralai set, so routing it here would send it to a- // provider that does not serve it.- "mistral-*": ["mistralai", "openrouter"],- "ministral-*": ["mistralai", "openrouter"],- "codestral-*": ["mistralai", "openrouter"],- // Mistral Labs ships under its own prefix. NO openrouter fallback: this is- // the one mistralai model no other provider in the catalog serves, so naming- // a fallback would claim a reachability that does not exist.- "labs-*": ["mistralai"],-- // Cognition SWE: Devin only, NO fallback — same shape as `labs-*` above, and- // for the same reason: no other provider in the catalog serves it, so naming- // a fallback would claim a reachability that does not exist.- //- // This is a DELIBERATE, NARROW amendment to the "no bare name ever routes to- // Devin" rule. That rule exists because Devin re-serves other vendors' models- // under uids that collide head-on with their namespaces — `claude-opus-5-high`- // matches native-anthropic's `/^claude-/i`, `gpt-5-6-luna-medium` matches- // OpenAI's, `glm-5-2` GLM's — so a bare name reaching Devin would answer as- // the wrong vendor. `swe-*` is the one family that is COGNITION'S OWN: it- // collides with nothing, no other provider in the catalog carries it, and the- // hosted catalog attributes it to `cognition-devin`. Without this rule the- // bare id matched nothing, fell through to native-anthropic, and was silently- // rewritten to `claude-opus-4-1` — a healthy backend made unreachable through- // the catalog's own identifier, answered by another vendor's model.- //- // The invariant still holds everywhere it was aimed: no COLLIDING bare name- // reaches Devin. Do not generalise this entry to Devin's re-served families.- "swe-*": ["devin"],-- // Sakana Fugu: subscription first, then token API. NO hardcoded openrouter —- // we don't claim OpenRouter carries the model; it's reachable explicitly via- // or@sakana/fugu (catalog-resolved). The bare "fugu" id needs its own exact- // rule because "fugu-*" only matches hyphenated names.- fugu: ["sakana-subscription", "sakana"],- "fugu-*": ["sakana-subscription", "sakana"],-- // OpenCode Zen owns/serves a few model lines exclusively.- // Pragmatic shim until Firebase aggregators[] coverage closes the gap.- "*-zen": ["opencode-zen"],-- // 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 own- // chain.- "*": ["openrouter"],-};--/**- * Validate that every provider name referenced by a routing rules table exists- * in `provider-definitions.ts`. Walks each entry, strips the optional- * `@model` suffix, resolves shortcuts (e.g. `or` → `openrouter`), and looks- * each canonical provider up.- *- * Throws if any rule references a typo provider — dev-time only; the cost is- * a single sweep at module load and prevents silent no-op rules from shipping- * to users.- *- * Exposed (not just internal) so tests can pass intentionally-broken rule- * tables to verify the validator's contract.- */-export function validateRoutingRulesAgainstProviders(rules: RoutingRules): void {- const unknown: Array<{ rule: string; entry: string; provider: string }> = [];-- for (const ruleKey of Object.keys(rules)) {- const entries = rules[ruleKey] ?? [];- for (const entry of entries) {- const atIdx = entry.indexOf("@");- const providerRaw = atIdx === -1 ? entry : entry.slice(0, atIdx);- const canonical = PROVIDER_SHORTCUTS[providerRaw.toLowerCase()] ?? providerRaw.toLowerCase();- if (!getProviderByName(canonical)) {- unknown.push({ rule: ruleKey, entry, provider: canonical });- }- }- }-- if (unknown.length > 0) {- const lines = unknown.map(- (u) => ` rule "${u.rule}" → entry "${u.entry}" → unknown provider "${u.provider}"`- );- throw new Error(- `[claudish] DEFAULT_ROUTING_RULES references unknown providers:\n${lines.join("\n")}`- );- }-}--/**- * Validate the shipped DEFAULT_ROUTING_RULES at module load. Throws on a typo- * so the bug surfaces in `bun run build` / test runs instead of as a silent- * no-route at runtime.- */-export function validateDefaultRoutingRules(): void {- validateRoutingRulesAgainstProviders(DEFAULT_ROUTING_RULES);-}--// Eager validation at import time.-validateDefaultRoutingRules();diff --git a/packages/cli/src/providers/provider-definitions.ts b/packages/cli/src/providers/provider-definitions.tsindex b9db6f21..4b276b5f 100644--- a/packages/cli/src/providers/provider-definitions.ts+++ b/packages/cli/src/providers/provider-definitions.ts@@ -418,6 +418,27 @@ export const BUILTIN_PROVIDERS: TieredProviderDefinition[] = [{ prefix: "ag/", stripPrefix: true },{ prefix: "antigravity/", stripPrefix: true },],+ // THE NAMESPACE CLAIM, not an auto-detect win. `google` declares the same+ // `/^gemini-/i` and is defined ABOVE, so `getNativeModelPatterns()` — which+ // is first-wins on array order — still answers `google` for a bare+ // `gemini-3.6-flash`, exactly as before. What this adds is the one thing+ // `route-candidates.ts` needs: `google/antigravity-subscription` sits in the+ // probe map as `client_model_selection_required` and publishes ZERO+ // `aggregators[]` rows, so gathering from the catalog alone can never see+ // this plan. Without a claim here, the 5 Gemini models a seat actually+ // serves (measured on generation g-20260921062451697-f490edba) would move+ // off a flat-rate plan onto the metered `google` hop — the one ordering+ // error that costs money.+ //+ // The family, not a list of ids: which VARIANTS a seat serves is per-account+ // and drifts (`v1internal:fetchAvailableModels`), and the AVAILABILITY+ // filter asks the account itself. This only says "Gemini is the namespace+ // this plan sells", which is the provider's product definition.+ //+ // Deliberately NOT `/^claude-/i`: the Antigravity backend does serve Claude+ // ids, but a bare Claude name must never reach `route()` at all+ // (`nativeRouteFor` handles it first — see CLAUDE.md's Invariants).+ nativeModelPatterns: [{ pattern: /^gemini-/i }],// Not a GET — an OAuth POST to v1internal:fetchAvailableModels, so `path`// is ignored. Declared so the picker prefers the per-subscription dynamic// models catalog and, more importantly, its per-model `maxTokens`: the backend and@@ -642,11 +663,23 @@ export const BUILTIN_PROVIDERS: TieredProviderDefinition[] = [shortcuts: ["gk", "grok-subscription"],shortestPrefix: "gk",legacyPrefixes: [{ prefix: "gk/", stripPrefix: true }],- // NO nativeModelPatterns: `x-ai` already owns /^grok-/i, and patterns are- // first-wins on array order. Bare-name reachability comes from the `grok-*`- // routing chain instead, where this provider sits FIRST — subscription- // before metered, so a user holding both credentials is never silently- // billed per token for a model their subscription already covers.+ // THE NAMESPACE CLAIM. `x-ai` declares the same `/^grok-/i` and is defined+ // ABOVE, so `getNativeModelPatterns()` — first-wins on array order — still+ // answers `x-ai` for a bare `grok-4.6`, and this provider does NOT win+ // auto-detection. A claim is not an auto-detect: it exists so+ // `route-candidates.ts` can emit a candidate the CATALOG cannot publish.+ // `x-ai/supergrok-subscription` sits in the probe map as+ // `client_model_selection_required` with ZERO `aggregators[]` rows, so+ // gathering would otherwise put a SuperGrok seat's 2 models (measured on+ // generation g-20260921062451697-f490edba) on the metered `x-ai` hop and+ // bill per token for what the plan already covers.+ //+ // Safe as a bare name for the reason the routing chain relied on before:+ // these ids are xAI's OWN, so — unlike Devin's re-served uids — there is no+ // other vendor's namespace to collide with. Which grok ids a seat serves+ // stays ACCOUNT-SCOPED, so the claim names the family and the availability+ // filter asks `/v1/models`.+ nativeModelPatterns: [{ pattern: /^grok-/i }],// The dynamic models catalog is ACCOUNT-SCOPED and drifts, so it is discovered, never// pinned. `/v1/models` is genuinely authenticated here (401 without a token,// unlike Alibaba's coding-intl model list where a 200 proves nothing), and it@@ -1350,6 +1383,20 @@ export const BUILTIN_PROVIDERS: TieredProviderDefinition[] = [shortcuts: ["sc"],shortestPrefix: "sc",legacyPrefixes: [{ prefix: "sc/", stripPrefix: true }],+ // THE NAMESPACE CLAIM. `sakana` above declares the same `/^fugu/i` (plus+ // `/^sakana\//i`, which `parseModelSpec` strips to a bare `fugu…` before+ // routing ever sees it) and is defined FIRST, so auto-detection is+ // unchanged. This claim is what lets `route-candidates.ts` emit a+ // subscription candidate at all: `sakana/fugu-subscription` is+ // `client_model_selection_required` in the probe map with ZERO+ // `aggregators[]` rows, and without it the 8 Fugu models a plan serves+ // (measured on generation g-20260921062451697-f490edba) would silently move+ // onto the metered `sakana` key — which draws PREPAID CREDITS, a different+ // wallet from the subscription, and has already billed a user once.+ //+ // `/^fugu/i` rather than `/^fugu-/i`: the bare id `fugu` is a real model, so+ // a hyphen-anchored rule would miss the family's own head.+ nativeModelPatterns: [{ pattern: /^fugu/i }],isDirectApi: true,description: "Sakana Fugu Subscription (sc@)",},diff --git a/packages/cli/src/providers/provider-profiles.ts b/packages/cli/src/providers/provider-profiles.tsindex 21a39529..6b4f97e9 100644--- a/packages/cli/src/providers/provider-profiles.ts+++ b/packages/cli/src/providers/provider-profiles.ts@@ -35,7 +35,7 @@ import {import { ComposedHandler } from "../handlers/composed-handler.js";import type { ModelHandler } from "../handlers/types.js";import { log, logStderr } from "../logger.js";-import { formatProvenanceLog, resolveApiKeyProvenance } from "./api-key-provenance.js";+import { formatProvenanceLog, resolveCredentialProvenance } from "./api-key-provenance.js";import { getProviderByName } from "./provider-definitions.js";import { getRuntimeProfiles } from "./runtime-providers.js";import { AnthropicProviderTransport } from "./transport/anthropic-compat.js";@@ -579,10 +579,13 @@ export async function createHandlerForProvider(ctx: ProfileContext): Promise<Modreturn null;}- // Log API key provenance so debug logs show exactly which key is used and where it came from+ // Log credential provenance so debug logs show exactly which credential is in+ // use and where it came from. Provider-aware: Vertex's `apiKeyEnvVar` holds a+ // PROJECT id, which may come from the ADC file or `gcloud config`, so the+ // env-only reading logged "VERTEX_PROJECT=(not set)" for a working install.if (ctx.provider.apiKeyEnvVar) {- const provenance = resolveApiKeyProvenance(ctx.provider.apiKeyEnvVar);- log(`[Proxy] API key: ${formatProvenanceLog(provenance)}`);+ const provenance = resolveCredentialProvenance(definitionName, ctx.provider.apiKeyEnvVar);+ log(`[Proxy] Credential: ${formatProvenanceLog(provenance)}`);}log(`[Proxy] Handler: provider=${ctx.provider.name}, model=${ctx.modelName}`);diff --git a/packages/cli/src/providers/route-candidates.ts b/packages/cli/src/providers/route-candidates.tsindex 661ca3a8..d628fe08 100644--- a/packages/cli/src/providers/route-candidates.ts+++ b/packages/cli/src/providers/route-candidates.ts@@ -2,11 +2,11 @@* Every way claudish could call one model, gathered from the catalog and ordered.** This is the replacement for the FIRST step of `routeBare` — the 24-entry- * hand-written table in `default-routing-rules.ts`, which names providers per- * model family and must be edited whenever a vendor, a plan or a gateway- * changes. Nothing here is wired into routing yet, by design: gathering and- * wiring are separate steps so the wiring can be measured against what the table- * does today.+ * hand-written table in `default-routing-rules.ts`, which named providers per+ * model family and had to be edited whenever a vendor, a plan or a gateway+ * changed. That file is now DELETED and this module is wired in:+ * `routeBare` calls `buildCatalogChain`, which calls+ * {@link gatherRouteCandidates} for every bare name no USER rule matches.** WHAT THIS MODULE IS NOT. It does not decide whether a candidate can be USED.* Two filters already own that question and neither is duplicated here:@@ -69,13 +69,15 @@ import { externalIdFor, getCatalogEntries } from "./catalog-client.js";import {type CatalogRouteBinding,catalogRouteForProvider,- providerForCatalogRoute,+ catalogRouteMatchesProvider,+ providersForCatalogRoute,} from "./catalog-route-bindings.js";import {type ConnectionPrice,compareByConnectionPrice,connectionPrice,} from "./connection-price.js";+import { readProbeModelsCache } from "./probe-catalog.js";import { type RouteTier, getAllProviders, getProviderByName } from "./provider-definitions.js";export type { RouteTier };@@ -101,6 +103,20 @@ export interface CandidateGathering {unmappedRoutes: string[];/** True when no catalog entry matched the name at all. */catalogMiss: boolean;+ /**+ * Whether a catalog could be READ, independent of whether it knew this name.+ *+ * `catalogMiss` alone conflates two situations a caller must treat+ * differently: "there is no catalog on this machine" and "the catalog is here+ * and does not publish this id". The first means claudish knows nothing and+ * must say so — the project owner's rule is that with no catalog claudish+ * serves local providers and explicit `provider@model` specs only, never a+ * guessed hop. The second is ordinary: a name the backend has not published+ * yet still has a last-resort fallback, because absence from a catalog that+ * IS readable is only denial for a route the catalog owns (see+ * `routing-rules.ts`, the fallback append).+ */+ catalogReadable: boolean;}/**@@ -176,31 +192,39 @@ function gatherFromConnections(for (const connection of entry.aggregators ?? []) {if (connection.routeStatus !== "mapped") continue;- const provider = providerForCatalogRoute(connection.route);- const tier = provider ? getProviderByName(provider)?.tier : undefined;- if (!provider || !tier) {+ // EVERY provider bound to this route, not just the first. One endpoint can+ // wear several claudish names, each owning a different key silo, and the+ // user's credential may be in any of them — see `providersForCatalogRoute`.+ const bound = providersForCatalogRoute(connection.route);+ const routable = bound.filter((name) => getProviderByName(name)?.tier !== undefined);+ if (routable.length === 0) {unmappedRoutes.add(routeLabel(connection.route));continue;}- const wireId = externalIdFor(entry, provider);- if (!wireId || wireId !== connection.externalModelId) continue;+ for (const provider of routable) {+ const tier = getProviderByName(provider)?.tier;+ if (!tier) continue;- candidates.push({- provider,- wireId,- tier,- isVendorOwn: isVendorOwnRoute(connection.route, entry),- price: connectionPrice(connection.pricing),- // A connection that omits `contextWindow` serves the model's headline- // window — that is what the field's absence MEANS in the contract, not- // missing data. Carrying the entry's value is therefore reading the- // catalog, not defaulting: without it, `openai-codex`'s measured 372K cap- // on gpt-5.6-sol would sort AHEAD of the OpenAI API's full 1.05M, which- // publishes no per-connection number because it is the headline one.- contextWindow: connection.contextWindow ?? entry.contextWindow,- source: "catalog-connection",- });+ const wireId = externalIdFor(entry, provider);+ if (!wireId || wireId !== connection.externalModelId) continue;++ candidates.push({+ provider,+ wireId,+ tier,+ isVendorOwn: isVendorOwnRoute(connection.route, entry),+ price: connectionPrice(connection.pricing),+ // A connection that omits `contextWindow` serves the model's headline+ // window — that is what the field's absence MEANS in the contract, not+ // missing data. Carrying the entry's value is therefore reading the+ // catalog, not defaulting: without it, `openai-codex`'s measured 372K cap+ // on gpt-5.6-sol would sort AHEAD of the OpenAI API's full 1.05M, which+ // publishes no per-connection number because it is the headline one.+ contextWindow: connection.contextWindow ?? entry.contextWindow,+ source: "catalog-connection",+ });+ }}}@@ -237,12 +261,27 @@ function isVendorOwnRoute(* downstream would contradict it, because a gateway answers a model it does not* have with a 4xx that reads as a credential problem.*- * Today exactly one provider can produce a claim: `devin` (`/^swe-/i`). The- * other three declare no `nativeModelPatterns` — deliberately, since `x-ai`- * already owns `/^grok-/i` and Devin's re-served ids collide with four other- * vendors' namespaces — so their bare-name reachability still comes from the- * hand-written table. Whoever wires this module in has to close that gap; see- * the implementation notes for this phase.+ * All four dynamic subscriptions now declare one: `devin` (`/^swe-/i`),+ * `antigravity` (`/^gemini-/i`), `grok-subscription` (`/^grok-/i`) and+ * `sakana-subscription` (`/^fugu/i`). The last three were added when the+ * hand-written table was deleted — without them the 15 models measured on+ * generation `g-20260921062451697-f490edba` as CLAIM-GAP would have moved off a+ * flat-rate plan onto a metered hop.+ *+ * A SECOND CLAIMANT ON A NAMESPACE IS FINE HERE, and that is a change from the+ * rule the old note stated. `getProviderForModel` — the function that picked one+ * winner per pattern — no longer exists. The two surviving consumers of+ * `nativeModelPatterns` both tolerate the overlap:+ *+ * - `getNativeModelPatterns()` → `parseModelSpec` is FIRST-WINS on+ * `BUILTIN_PROVIDERS` order, and each new claimant is defined BELOW the+ * metered sibling that already owned the pattern (`google` < `antigravity`,+ * `x-ai` < `grok-subscription`, `sakana` < `sakana-subscription`), so bare-name+ * auto-detection is byte-identical to before;+ * - this function, which iterates ALL providers and pushes every match — it+ * wants the overlap, because that is how a flat-rate plan and the metered+ * vendor both reach the ordering in {@link compareRouteCandidates}, where the+ * tier puts the subscription first.*/function gatherFromNamespaceClaims(model: string,@@ -349,5 +388,83 @@ export function gatherRouteCandidates(model: string, cachePath?: string): Candidcandidates,unmappedRoutes: [...unmappedRoutes],catalogMiss: entry === undefined,+ catalogReadable: entries !== null && entries !== undefined,};}++/**+ * Does the CATALOG deny that `provider` carries `model`?+ *+ * Only ever true for a BACKEND-OWNED route, and the catalog draws that line+ * itself. A route the probe map marks `client_model_selection_required` is+ * ACCOUNT-SELECTED: the backend cannot enumerate what a seat was given, so+ * absence from a model's connections proves nothing about it. Every other+ * probed route publishes its complete connection list, so for those, absence IS+ * denial.+ *+ * Deliberately three-valued in effect, collapsed to a boolean that is false+ * whenever anything is unknown:+ *+ * - no catalog entry for the model → no denial (the id may simply be newer+ * than this machine's catalog);+ * - the provider has no catalog route binding at all (a local transport, a+ * custom endpoint, a bundled row) → the catalog never speaks about it, so+ * its silence says nothing;+ * - no probe map cached → route ownership is unknown, so nothing is denied.+ * The cost is one hop that may 404, which is exactly today's behaviour;+ * the alternative is dropping a real route on missing evidence.+ *+ * This is NOT the availability filter and does not duplicate it.+ * `providerServesModel` may never conclude "not served" from the catalog alone+ * (see its comment — `openai-codex` appears on one row out of ~760 and the rule+ * was unsound). This asks a narrower question that the route-ownership split+ * makes answerable, and only the fallback APPEND uses it: the difference is+ * whether claudish is about to invent a hop nobody published, versus drop one+ * something else put in the chain.+ */+export function catalogDeniesProvider(+ provider: string,+ model: string,+ cachePath?: string+): boolean {+ if (!catalogRouteForProvider(provider)) return false;+ if (routeOwnership(provider) !== "backend-owned") return false;++ const entries = cachePath ? readAllModelsCache(cachePath)?.entries : getCatalogEntries();+ if (!entries) return false;+ const entry = findCatalogEntry(entries, model);+ if (!entry) return false;++ // `catalogRouteMatchesProvider`, NOT `providerForCatalogRoute(...) === provider`.+ // The reverse lookup returns the FIRST provider bound to a route pair, and+ // four pairs have two claudish names each (`kimi`/`moonshotai`,+ // `opencode-zen`/`zen`, `qwen-payg`/`qwen`). Comparing its answer would have+ // declared `moonshotai` denied on every model `kimi` serves — a real denial+ // built out of an alias. Comparing BINDINGS is what `externalIdFor` and+ // `model-availability.ts` already do, for this reason.+ return !(entry.aggregators ?? []).some(+ (connection) =>+ connection.routeStatus === "mapped" && catalogRouteMatchesProvider(connection.route, provider)+ );+}++/** Who decides which models a route serves. `unknown` denies nothing. */+export type RouteOwnership = "backend-owned" | "account-selected" | "unknown";++/**+ * Read route ownership out of the probe map — the backend's own statement.+ *+ * `tier === "dynamic-subscription"` is claudish's local transcription of the+ * same fact and the two agree on all four providers today, but the probe map is+ * the source and is what this asks, so a backend that reclassifies a route moves+ * claudish without an edit here.+ */+export function routeOwnership(provider: string): RouteOwnership {+ const probe = readProbeModelsCache();+ if (!probe) return "unknown";+ if (probe.unavailable[provider] === "client_model_selection_required") {+ return "account-selected";+ }+ if (provider in probe.providers || provider in probe.unavailable) return "backend-owned";+ return "unknown";+}diff --git a/packages/cli/src/providers/routing-rules.ts b/packages/cli/src/providers/routing-rules.tsindex 29466096..8d92121c 100644--- a/packages/cli/src/providers/routing-rules.ts+++ b/packages/cli/src/providers/routing-rules.ts@@ -8,25 +8,14 @@ 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 { DEFAULT_ROUTING_RULES } from "./default-routing-rules.js";+import { ensureEndpointsRegistered } from "./endpoint-registration.js";import { providerServesModel } from "./model-availability.js";import { PROVIDER_SHORTCUTS } from "./model-parser.js";import { parseModelSpec } from "./model-parser.js";import { getProviderByName } from "./provider-definitions.js";+import { catalogDeniesProvider, gatherRouteCandidates } from "./route-candidates.js";import { buildCredentialHint } from "./routing-hints.js";-/**- * Pure merge — defaults < global < local. Exposed for testability so callers- * can verify merge semantics without touching the disk.- */-export function mergeRoutingRules(- defaults: RoutingRules,- global_: RoutingRules,- local: RoutingRules-): RoutingRules {- return { ...defaults, ...global_, ...local };-}-export interface RoutingRuleSources {globalRules: RoutingRules;localRules: RoutingRules;@@ -34,21 +23,25 @@ export interface RoutingRuleSources {}/**- * Load effective routing rules. Layers:- * 1. DEFAULT_ROUTING_RULES (built-in, see default-routing-rules.ts)- * 2. Global config (~/.claudish/config.json)- * 3. Local config (./.claudish.json)+ * Load the user's effective routing rules. Two layers, both the user's own:+ * 1. Global config (~/.claudish/config.json)+ * 2. Local config (./.claudish.json)*- * Local rules overwrite global rules overwrite defaults — same key wins.- * User patterns OVERWRITE default patterns by exact key match (no glob-vs-glob- * interleaving).+ * Local overwrites global by exact key match — no glob-vs-glob interleaving.*- * Always returns a non-null `RoutingRules` because defaults are baked in.- * To get strict no-fallback mode, set `routing["*"] = []` in user config.+ * THERE ARE NO BUILT-IN RULES. The 24-entry `DEFAULT_ROUTING_RULES` table this+ * used to merge under the user's rules is gone: the providers that can serve a+ * bare name are now GATHERED from the cloud models catalog+ * (`route-candidates.ts`), which publishes every tier — subscriptions, native+ * APIs and gateways — for every model, and which the table could only+ * approximate by hand. So the result here is frequently `{}`, and `routeBare`+ * treats "no rule matched" as "ask the catalog" rather than as an error.*- * 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.+ * What a user rule now MEANS is therefore stronger than it was: a match is used+ * VERBATIM and is never merged with, reordered by or appended to by anything —+ * including the fallback hop. `routing["*"] = []` is consequently still the+ * strict no-route switch it always was, and `routing["*"] = [...]` replaces the+ * fallback outright.** `sources` keeps rule composition testable without reading machine config.* The recommended-model projection is not a routing-rule override.@@ -60,23 +53,45 @@ export function loadRoutingRules(sources?: RoutingRuleSources): RoutingRules {validateRoutingRules(local);validateRoutingRules(global_);- return mergeRoutingRules(DEFAULT_ROUTING_RULES, global_, local);+ return { ...global_, ...local };}/**- * Keep only catalog routing entries whose provider has an executable transport.+ * Validate that every provider name a routing rules table references exists in+ * `provider-definitions.ts`. Walks each entry, strips the optional `@model`+ * suffix, resolves shortcuts (e.g. `or` → `openrouter`), and looks each+ * canonical provider up.+ *+ * Throws, so it is for a caller that wants a typo to be loud — a config+ * validator or a test — never the request path. `loadRoutingRules` deliberately+ * does not call it: a user whose hand-written rule names a provider claudish+ * dropped should get a degraded chain and a warning, not a crash on every+ * request.+ *+ * Its subject used to be the shipped table, which is gone. What remains to+ * check is the USER's rules, which is the only table left.*/-export function retainKnownCatalogRoutingRules(rules: RoutingRules): RoutingRules {- const retained: RoutingRules = {};- for (const [modelId, entries] of Object.entries(rules)) {- const knownEntries = entries.filter((entry) => {- const providerRaw = entry.split("@", 1)[0]?.toLowerCase() ?? "";- const provider = PROVIDER_SHORTCUTS[providerRaw] ?? providerRaw;- return getProviderByName(provider) !== undefined;- });- if (knownEntries.length > 0) retained[modelId] = knownEntries;+export function validateRoutingRulesAgainstProviders(rules: RoutingRules): void {+ const unknown: Array<{ rule: string; entry: string; provider: string }> = [];++ for (const ruleKey of Object.keys(rules)) {+ const entries = rules[ruleKey] ?? [];+ for (const entry of entries) {+ const atIdx = entry.indexOf("@");+ const providerRaw = atIdx === -1 ? entry : entry.slice(0, atIdx);+ const canonical = PROVIDER_SHORTCUTS[providerRaw.toLowerCase()] ?? providerRaw.toLowerCase();+ if (!getProviderByName(canonical)) {+ unknown.push({ rule: ruleKey, entry, provider: canonical });+ }+ }+ }++ if (unknown.length > 0) {+ const lines = unknown.map(+ (u) => ` rule "${u.rule}" → entry "${u.entry}" → unknown provider "${u.provider}"`+ );+ throw new Error(`[claudish] routing rules reference unknown providers:\n${lines.join("\n")}`);}- return retained;}/** Warn about config issues that would silently misbehave. */@@ -196,23 +211,29 @@ export function buildRoutingChain(modelName = resolveExternalId(modelName, provider, cachePath) ?? modelName;}- // Build modelSpec. OpenRouter's ids are already vendor-qualified, so they- // are their own spec; everyone else takes a provider prefix.- let modelSpec: string;- if (provider === "openrouter") {- modelSpec = modelName;- } else {- const prefix = PROVIDER_TO_PREFIX[provider] ?? provider;- modelSpec = `${prefix}@${modelName}`;- }-- const displayName = DISPLAY_NAMES[provider] ?? provider;- routes.push({ provider, modelSpec, displayName });+ routes.push(routeFor(provider, modelName));}return routes;}+/**+ * One provider plus the id it will actually be SENT → a `Route`.+ *+ * The ONE copy of the modelSpec rule, which has exactly one exception:+ * OpenRouter's ids are already vendor-qualified (`moonshotai/kimi-k3`), so they+ * are their own spec, while everyone else takes a provider prefix. Both callers+ * go through here — `buildRoutingChain`, which resolves a wire id from a user+ * rule, and the catalog-candidate adapter, which is HANDED one — so the rule+ * cannot drift between the two paths. `wireIdOf` is its inverse and would+ * silently disagree if a second copy appeared.+ */+function routeFor(provider: string, wireId: string): Route {+ const modelSpec =+ provider === "openrouter" ? wireId : `${PROVIDER_TO_PREFIX[provider] ?? provider}@${wireId}`;+ return { provider, modelSpec, displayName: DISPLAY_NAMES[provider] ?? provider };+}+/*** Single-wildcard glob: "kimi-*" matches "kimi-k2.5". Case-INSENSITIVE so* `MiniMax-M2.5` matches `minimax-*` and `GPT-4o` matches `gpt-*`. Provider@@ -329,13 +350,125 @@ async function routeExplicit(}/**- * Path 2: a bare model name. Consult rules, build candidates, filter to those- * with credentials, and return ok/no-route accordingly.+ * The provider that occupies the LAST hop, or null when the user disabled it.+ *+ * The fallback is a POSITION, not a property of any provider (see `RouteTier`).+ * Two ways to empty that position, and BOTH are preserved from the design this+ * replaced:+ *+ * - `defaultProvider: ""` — an explicitly empty string. `undefined` is not the+ * same thing: unset means "no preference", which takes `openrouter`, and+ * that is what the deleted `"*": ["openrouter"]` catch-all used to supply+ * for 1,109 models. Only a deliberate empty string disables.+ * - a user rule that matches — `routing["*"] = []` most explicitly. That+ * never reaches here at all: a matched rule is used verbatim and this+ * function is only consulted on the gathered path.+ */+function fallbackProviderFor(defaultProvider: string | undefined): string | null {+ if (defaultProvider !== undefined && defaultProvider.length === 0) return null;+ const named = defaultProvider ?? DEFAULT_FALLBACK_PROVIDER;+ return PROVIDER_SHORTCUTS[named.toLowerCase()] ?? named.toLowerCase();+}++/**+ * The provider the last hop takes when the user expressed no preference.*- * If `defaultProvider` is set and not already present in the matched chain, it- * is appended as a final entry — a safety net that catches models whose chain- * has no credentialed providers. Deduped: if the chain already lists the- * default provider, no second copy is added.+ * A rule, not a pinned model id: it names the one gateway that resells nearly+ * every vendor, which is why the deleted table used it as its catch-all. It is+ * overridden by `defaultProvider` and emptied by `defaultProvider: ""`.+ */+export const DEFAULT_FALLBACK_PROVIDER = "openrouter";++/** A chain assembled from the catalog, plus whether a catalog could be read. */+export interface CatalogChain {+ routes: Route[];+ /**+ * False means NO catalog was readable — not merely that it lacked this name.+ * A caller must treat that as "claudish cannot answer", never as "no provider+ * serves it": the two look identical in `routes` and only this tells them+ * apart.+ */+ catalogReadable: boolean;+}++/**+ * Steps 2 and 3 of the bare-name path: gather from the catalog, then append the+ * fallback hop. No credential or availability filtering — those belong to+ * `routeBare`, which owns them, and duplicating either here would create the+ * second oracle `route-candidates.ts` exists to avoid.+ *+ * Exported because `--probe` reconstructs the chain it is about to test rather+ * than calling `route()` (it needs per-hop credential provenance that a+ * `RoutePlan` does not carry). Before this existed, the probe read the same+ * hand-written table `route()` did; with that table gone, a probe that only+ * consulted user rules would have shown an EMPTY chain for every model the user+ * had not written a rule for — a display that says "nothing routes this" about+ * models that route fine.+ */+export function buildCatalogChain(+ model: string,+ defaultProvider?: string,+ cachePath?: string+): CatalogChain {+ // Bundled endpoints (`together`, `fireworks`) have no provider DEFINITION+ // until this has run, and `gatherFromConnections` drops a connection whose+ // provider it cannot resolve — silently, because that is also what a provider+ // the user holds no key for looks like. An earlier preview ran without it and+ // blamed this redesign for 241 unroutable `together-ai` connections it had+ // not caused.+ //+ // Called HERE rather than trusted from a caller: six startup paths register+ // endpoints and this is reachable from all of them plus the MCP server, the+ // launcher's context-window probe and the TUI. Sync, config-only and latched,+ // so every call after the first is free.+ ensureEndpointsRegistered();++ const gathering = gatherRouteCandidates(model, cachePath);+ const routes = gathering.candidates.map((candidate) =>+ routeFor(candidate.provider, candidate.wireId)+ );++ const fallback = fallbackProviderFor(defaultProvider);+ if (+ fallback &&+ // NEVER invent a hop with no catalog: `openrouter@<name>` for a name nobody+ // published is a metered request billed for its own 404, and a name the+ // backend has since RENAMED looks identical.+ gathering.catalogReadable &&+ !routes.some((route) => route.provider === fallback) &&+ !catalogDeniesProvider(fallback, model, cachePath)+ ) {+ // Through `buildRoutingChain`, not `routeFor`: the fallback is named by+ // PROVIDER only, so its wire id still has to be resolved, and that+ // resolution (subscription plan ids, then the catalog's `aggregators[]`)+ // lives there. It legitimately yields nothing when a subscription's plan+ // does not include the model.+ routes.push(...buildRoutingChain([fallback], model, cachePath));+ }++ return { routes, catalogReadable: gathering.catalogReadable };+}++/**+ * Path 2: a bare model name.+ *+ * ── STEP 1 IS THE ONLY THING THIS PHASE CHANGED ────────────────────────────+ *+ * 1. a user rule matches? → that chain, VERBATIM. Never merged, reordered or+ * appended to, including by the fallback. A match+ * of `[]` is a match: the user said "no route".+ * 2. otherwise → `gatherRouteCandidates`, which reads every+ * connection the catalog publishes for this model+ * and orders them by tier, vendor, price, window.+ * 3. append the fallback → last, deduped, disableable, and NOT appended when+ * the catalog positively denies it.+ * 4. credential filter → unchanged, below.+ * 5. availability filter → unchanged, below.+ * 6. primary + fallbacks.+ *+ * Steps 4 and 5 are deliberately NOT duplicated by step 2 — see the header of+ * `route-candidates.ts`. A gathered candidate is a claim about what the catalog+ * publishes, never a claim that this user can call it.*/async function routeBare(model: string,@@ -344,30 +477,50 @@ async function routeBare(defaultProvider?: string,cachePath?: string): Promise<RoutePlan> {- const matched = matchRoutingRule(model, rules) ?? [];- const entries = [...matched];-- if (defaultProvider && defaultProvider.length > 0) {- const canonicalDefault =- PROVIDER_SHORTCUTS[defaultProvider.toLowerCase()] ?? defaultProvider.toLowerCase();- const alreadyPresent = entries.some((e) => {- const atIdx = e.indexOf("@");- const providerRaw = atIdx === -1 ? e : e.slice(0, atIdx);- const canonical = PROVIDER_SHORTCUTS[providerRaw.toLowerCase()] ?? providerRaw.toLowerCase();- return canonical === canonicalDefault;- });- if (!alreadyPresent) entries.push(defaultProvider);+ // `null` and `[]` are DIFFERENT answers and the old `?? []` conflated them.+ // `[]` is a user rule that matched and named no provider — strict no-route,+ // and the one thing that must not then collect a fallback.+ const matched = matchRoutingRule(model, rules);++ let candidates: Route[];+ if (matched !== null) {+ candidates = buildRoutingChain(matched, model, cachePath);+ } else {+ const gathered = buildCatalogChain(model, defaultProvider, cachePath);++ // NO CATALOG MEANS LOCAL ONLY. With nothing readable, claudish knows no+ // provider serves this name and must say so rather than guess. A namespace+ // claim still counts — that is claudish's own statement about a plan the+ // user holds, not an inference from a catalog it could not read — so the+ // check is on an EMPTY result, not on `catalogReadable` alone. Local+ // providers and explicit `provider@model` specs are unaffected: neither+ // comes through here.+ if (!gathered.catalogReadable && gathered.routes.length === 0) {+ return {+ kind: "no-route",+ reason: `No model catalog available, so "${model}" cannot be routed by name.`,+ hint:+ "Run `claudish --models-refresh` to fetch the catalog, or name the provider " ++ `explicitly (e.g. \`openrouter@${model}\`).`,+ };+ }+ candidates = gathered.routes;}- if (entries.length === 0) {+ if (candidates.length === 0) {+ // Two very different causes, and a user reading the message needs to know+ // which: their OWN rule named nothing (they asked for this), or the catalog+ // publishes no way to call the model (nobody serves it).return {kind: "no-route",- reason: `No routing rule matched "${model}".`,+ reason:+ matched !== null+ ? `A routing rule matched "${model}" and named no provider.`+ : `No provider in the catalog serves "${model}".`,hint: buildCredentialHint(model, [nativeProvider]) ?? undefined,};}- const candidates = buildRoutingChain(entries, model, cachePath);const credentialed: Route[] = [];const skipped: string[] = [];const skippedFailed: string[] = [];@@ -520,10 +673,10 @@ function wireIdOf(route: Route): string {* probe ONLY that vendor's credentials; missing credentials → no-route* with a credential hint. **No silent fallback** — `defaultProvider` is* not consulted because the user named a specific vendor.- * 2. Bare name: consult routing rules (defaults + user overrides), append- * `defaultProvider` as a final fallback if set and not already present,- * build the candidate chain, filter to credentialed entries, return the- * filtered chain. Empty filtered chain → no-route with hints.+ * 2. Bare name: a matching USER rule wins verbatim; otherwise the chain is+ * gathered from the cloud models catalog and the fallback hop is appended+ * last. Then the credential and availability filters. Empty filtered chain+ * → no-route with hints. See `routeBare`.** Rules and the default provider are loaded fresh each call (via `loadRoutingRules()`* and `loadConfig()`) unless overrides are supplied. Tests should pass overrides@@ -531,8 +684,8 @@ function wireIdOf(route: Route): string {*//*** Rewrite a dash-slugified GLM version to its canonical dotted form- * (`glm-5-2` → `glm-5.2`), so a client that slugifies dots still matches the- * routing rule instead of falling through to `defaultProvider`.+ * (`glm-5-2` → `glm-5.2`), so a client that slugifies dots still finds the+ * catalog entry instead of missing it and falling through to the fallback hop.** Anchored and deliberately narrow. The second group must be ALL digits to the* end (or to a `-suffix`), which is what keeps dash-native open-model ids@@ -552,10 +705,14 @@ function wireIdOf(route: Route): string {* That matters because Devin re-serves other vendors' models under uids that* legitimately contain dashes, `glm-5-2` and `glm-5-2-1m` among them (see* providers/devin/model-id-resolver.ts). Those are matched against Devin's LIVE- * served set, so a `dv@glm-5-2` that ever became `[email protected]` would request a- * uid that does not exist. Bare names cannot reach Devin at all — it declares- * no nativeModelPatterns and has no DEFAULT_ROUTING_RULES entry — so the bare- * path is the only place this rewrite can apply and the only place it needs to.+ * dynamic models catalog, so a `dv@glm-5-2` that ever became `[email protected]` would+ * request a uid that does not exist.+ *+ * No bare name can reach Devin through a COLLIDING family, which is what makes+ * the bare path safe to rewrite. Devin is a dynamic subscription, so it+ * publishes no catalog connection and can only be gathered from its namespace+ * claim — and that claim is exactly `/^swe-/i`, Cognition's own line. A bare+ * `glm-5-2` therefore never produces a Devin candidate, by either route.*/export function normalizeGlmSlug(model: string): string {return model.replace(diff --git a/packages/cli/src/providers/transport/vertex-discovery.ts b/packages/cli/src/providers/transport/vertex-discovery.tsnew file mode 100644index 00000000..e3aac512--- /dev/null+++ b/packages/cli/src/providers/transport/vertex-discovery.ts@@ -0,0 +1,391 @@+/**+ * Vertex AI probe-model discovery — the models THIS project can actually call.+ *+ * WHY THIS EXISTS+ *+ * The cloud models catalog marks `vertex/google-cloud`+ * `client_model_selection_required` (measured on generation+ * `g-20260921062451697-f490edba`), by agreement with the backend: what a Vertex+ * caller may invoke depends on the user's project, its enabled APIs, its+ * permissions and its region, so no hosted pick can be right for everyone. That+ * is correct, and it also meant Test All had nothing to try and reported "no+ * probe model: transport does not support discovery" for a working install.+ *+ * So the account decides, which is the whole point: nothing here is a model id.+ *+ * WHAT THE ENDPOINT IS, MEASURED 2026-09-22 against ADC on a real project+ *+ * GET https://<host>/v1beta1/publishers/google/models+ * Authorization: Bearer <ADC token>+ * x-goog-user-project: <project>+ *+ * - `v1beta1` is the ONLY version that answers: `/v1/publishers/google/models`+ * is 404, as is a project-scoped `/v1beta1/projects/<p>/locations/<l>/…`.+ * - `x-goog-user-project` is REQUIRED for a user ADC credential. Without it the+ * API answers 403 `SERVICE_DISABLED`: "authenticating by using local+ * Application Default Credentials. The aiplatform.googleapis.com API requires+ * a quota project". A request against a project-scoped URL (every generate+ * call) carries the project in the path instead, which is why the transport+ * itself never needed the header.+ * - The list is genuinely PER LOCATION, which is why the location comes from+ * `resolveVertexConfig`: the same credential saw 132 models in `us-central1`,+ * 27 on the `global` host and 13 in `europe-west4`.+ *+ * WHAT IT RETURNS, AND WHY MOST OF IT IS NOT A CHAT MODEL+ *+ * The response is the Model Garden, not a chat menu: `{ publisherModels: [{+ * name, versionId, launchStage?, openSourceCategory?, publisherModelTemplate?,+ * supportedActions? }] }`. Alongside Gemini it lists notebook samples, OSS+ * checkpoints you deploy to your own endpoint, request-access research models+ * and the legacy vision/language APIs. Every filter below reads a field the API+ * itself publishes — there is no name list here, and adding one would be the+ * pinned-id failure this module exists to avoid.+ *+ * AND THE LISTING OVER-REPORTS, WHICH IS WHY THERE IS A SECOND STEP+ *+ * Measured 2026-09-22 on `us-central1`: the listing offers `gemini-3.8-flash`,+ * `gemini-3.7-flash`, `gemini-3.6-flash`, `gemini-3.5-flash` and every other+ * 3.x row, and ALL of them answer `404 NOT_FOUND "Publisher model … was not+ * found or your project does not have access to it"` when called there. The+ * same ids answer 200 on `global`. Only the 2.5 family is actually served in+ * `us-central1`. Nothing in the listing distinguishes the two: a per-model+ * `GET …/models/<id>?view=PUBLISHER_MODEL_VIEW_FULL` returns byte-identical+ * field sets for a servable and an unservable model, and no other endpoint+ * reports a per-region served set (`…/endpoints/openapi/models` is 404,+ * `…/locations/<l>/models` is the empty tuned-model registry).+ *+ * So the listing narrows the field and `:countTokens` decides it: measured on+ * the same account, countTokens answers 404 for exactly the models+ * generateContent 404s and 200 for the ones it serves. It bills nothing, it is+ * idempotent, and every candidate is checked in ONE parallel round (~1.6s for+ * five, bounded by the slowest call).+ *+ * The probe pick is therefore a model this PROJECT, in THIS location, answered+ * for — which is the only honest form the claim can take.+ */++import { credentials } from "../../auth/credentials/authority.js";+import { resolveVertexConfig, vertexApiHost } from "../../auth/vertex-auth.js";+import { log } from "../../logger.js";+import { findEntryByModelId } from "../catalog-query.js";+import { type DiscoveredModel, rankDiscoveredModels } from "../model-discovery.js";+import { type DiscoveryOutcome, isChatCapable } from "./probe-discovery.js";+import { VERTEX_DEFAULT_PUBLISHER, parseVertexModel } from "./vertex-oauth.js";++/** Same TTL and timeout as the other discovery helpers (`probe-discovery.ts`). */+const CACHE_TTL_MS = 5 * 60 * 1000;+const FETCH_TIMEOUT_MS = 8000;+/** Shorter than the list fetch: a verification round runs many of these at once. */+const VERIFY_TIMEOUT_MS = 6000;+/**+ * How many ranked candidates are verified.+ *+ * A bound rather than a budget: the checks are free and issued in ONE parallel+ * round, so the cost is the slowest call, not the count — but a publisher list+ * is not claudish's to size, and an unbounded fan-out at Test All time (30+ * providers at once) is how the Devin discovery timeout was earned. 24 covers+ * every chat-capable candidate seen on a real project (21 in `us-central1`).+ */+const MAX_VERIFIED_CANDIDATES = 24;++/**+ * The ranked candidate list per project+location, so the probe loop's `exclude`+ * set can walk to the next candidate without re-listing. Keyed by both, because+ * the answer genuinely differs per location (see the header).+ */+const _cache = new Map<string, { ranked: string[]; reason?: string; expiresAt: number }>();++/** Test seam: drop the memo between cases. */+export function _clearVertexDiscoveryCache(): void {+ _cache.clear();+}++/** One row of the `publisherModels` array, in the shape this module reads. */+interface PublisherModel {+ name: string;+ versionId?: string;+ launchStage?: string;+ openSourceCategory?: string;+ publisherModelTemplate?: string;+ supportedActions?: Record<string, unknown>;+}++/**+ * Whether Vertex serves this row as a managed model claudish could call.+ *+ * Each clause quotes the API's own metadata:+ *+ * 1. `publisherModelTemplate` — the `projects/{project}/locations/{location}/+ * publishers/…/models/<id>@<version>` address the row is served at. A row+ * without one is not served as a managed model at all (it is a notebook, a+ * fine-tuning pipeline or a deploy-it-yourself checkpoint), so there is no+ * endpoint for the probe to call.+ * 2. `openSourceCategory` naming OSS weights — `GOOGLE_OWNED_OSS`,+ * `THIRD_PARTY_OWNED_OSS`, `*_WITH_GOOGLE_CHECKPOINT` — means "deploy this+ * yourself". Belt and braces with (1), which it mostly implies, but not+ * always: `imageclassification-efficientnet` carries a template AND is OSS.+ * 3. `PRIVATE_PREVIEW` is allowlist-only by definition; `GA`,+ * `PUBLIC_PREVIEW` and `EXPERIMENTAL` are all callable.+ * 4. A `requestAccess` action is the API saying access must be requested first.+ */+function isServedByVertex(m: PublisherModel): boolean {+ if (!m.publisherModelTemplate) return false;+ if (m.openSourceCategory && /OSS/.test(m.openSourceCategory)) return false;+ if (m.launchStage === "PRIVATE_PREVIEW") return false;+ if (m.supportedActions && "requestAccess" in m.supportedActions) return false;+ return true;+}++/** `publishers/google/models/gemini-3.8-flash` → `gemini-3.8-flash`. */+function shortModelId(name: string): string {+ const at = name.lastIndexOf("/");+ return at >= 0 ? name.slice(at + 1) : name;+}++/**+ * The id claudish will send, for the publisher this listing belongs to.+ *+ * `parseVertexModel` defaults a bare id to the `google` publisher, so a google+ * row round-trips bare; anything else is publisher-qualified. Derived from that+ * same default rather than restated, so the two cannot disagree about which+ * publisher a bare id means.+ */+function wireIdFor(publisher: string, modelId: string): string {+ return publisher === VERTEX_DEFAULT_PUBLISHER ? modelId : `${publisher}/${modelId}`;+}++/** A field the API may omit or send as something other than a string. */+function str(value: unknown): string | undefined {+ return typeof value === "string" && value.length > 0 ? value : undefined;+}++function parsePublisherModels(body: unknown): PublisherModel[] {+ const rows = (body as { publisherModels?: unknown })?.publisherModels;+ if (!Array.isArray(rows)) return [];+ const out: PublisherModel[] = [];+ for (const raw of rows) {+ const row = (raw ?? {}) as Record<string, unknown>;+ const name = str(row.name);+ if (!name) continue;+ const actions = row.supportedActions;+ out.push({+ name,+ versionId: str(row.versionId),+ launchStage: str(row.launchStage),+ openSourceCategory: str(row.openSourceCategory),+ publisherModelTemplate: str(row.publisherModelTemplate),+ supportedActions:+ actions && typeof actions === "object" ? (actions as Record<string, unknown>) : undefined,+ });+ }+ return out;+}++/**+ * List the publisher models this project can SEE from this location.+ *+ * A catalogue, NOT a served set — the header records the measurement: this+ * endpoint offers `gemini-3.x` rows in `us-central1` that 404 when called there.+ * `discoverVertexProbeModel` narrows it with `:countTokens`; anything else+ * consuming this must do the same rather than treat the list as availability.+ *+ * Exported so a human (or a verification script) can see the raw answer without+ * going through the probe loop. Throws on transport failure; the caller turns+ * that into a `reason`.+ */+export async function listVertexPublisherModels(+ publisher: string = VERTEX_DEFAULT_PUBLISHER+): Promise<{ models: DiscoveredModel[]; endpoint: string; listed: number }> {+ const config = await resolveVertexConfig();+ if (!config) {+ // Not a network failure: nothing has been asked yet. The caller's message+ // names both remedies; inventing a project here would bill someone else's.+ throw new Error("no Google Cloud project resolved");+ }+ const endpoint = `https://${vertexApiHost(config.location)}/v1beta1/publishers/${publisher}/models`;++ // The same credential the transport signs with, via the authority — not a+ // second path to a token. `x-goog-user-project` is added because a LIST is not+ // project-scoped in its URL; see the header note.+ const auth = await credentials.getRequestAuth("vertex", { model: "" });+ const response = await fetch(endpoint, {+ method: "GET",+ headers: { ...auth.headers, "x-goog-user-project": config.projectId },+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),+ });++ if (!response.ok) {+ // The upstream sentence is the whole value of this path: a 403 here says+ // precisely which permission or quota project is missing, and a guess would+ // send the user to the wrong console page.+ const detail = await response.text().catch(() => "");+ throw new Error(+ `HTTP ${response.status} from ${endpoint}${detail ? ` — ${oneLine(detail)}` : ""}`+ );+ }++ const listed = parsePublisherModels(await response.json());+ const models: DiscoveredModel[] = listed.filter(isServedByVertex).map((m) => {+ const id = shortModelId(m.name);+ return {+ id: wireIdFor(publisher, id),+ // The listing publishes no date and no context window. The catalog's+ // release date is a fact about the MODEL, and `DiscoveredModel.releaseDate`+ // exists for exactly this ordering job; the context window is deliberately+ // left undefined, because nothing here measured what this project may send.+ releaseDate: findEntryByModelId(id)?.releaseDate,+ };+ });+ return { models, endpoint, listed: listed.length };+}++function oneLine(text: string, max = 200): string {+ const flat = text.replace(/\s+/g, " ").trim();+ return flat.length > max ? `${flat.slice(0, max)}…` : flat;+}++/** What one `:countTokens` check established about one candidate. */+interface VerifiedCandidate {+ id: string;+ /** False ONLY when the API said the model is not there; see `verifyServed`. */+ served: boolean;+ /** The upstream sentence for a refusal, for the failure message. */+ detail?: string;+}++/**+ * Ask the project, in its own location, which of these candidates it will serve.+ *+ * `:countTokens` is the question: it is free, idempotent, needs no generation+ * config, and — measured — answers 404 for exactly the models `generateContent`+ * 404s. One parallel round, so the wall time is the slowest check.+ *+ * The asymmetry is deliberate. A 404 DENIES a candidate, because that is the+ * API saying the model is not there. Every other outcome — 403, 429, 5xx, a+ * timeout, a transport error — KEEPS it: an inconclusive check must not delete a+ * model from the list, or a rate limit during Test All would report an empty+ * Vertex and the user would go looking for a missing permission that does not+ * exist.+ */+async function verifyServed(+ ids: string[],+ config: { projectId: string; location: string },+ headers: Record<string, string>+): Promise<VerifiedCandidate[]> {+ const base =+ `https://${vertexApiHost(config.location)}/v1/` ++ `projects/${config.projectId}/locations/${config.location}/publishers`;+ return Promise.all(+ ids.map(async (id): Promise<VerifiedCandidate> => {+ const parsed = parseVertexModel(id);+ const url = `${base}/${parsed.publisher}/models/${parsed.model}:countTokens`;+ try {+ const res = await fetch(url, {+ method: "POST",+ headers: { ...headers, "Content-Type": "application/json" },+ // The shortest legal prompt: this measures existence, not the model.+ body: JSON.stringify({ contents: [{ role: "user", parts: [{ text: "." }] }] }),+ signal: AbortSignal.timeout(VERIFY_TIMEOUT_MS),+ });+ if (res.ok) return { id, served: true };+ const detail = oneLine(await res.text().catch(() => ""), 160);+ if (res.status === 404) return { id, served: false, detail };+ return { id, served: true, detail: `HTTP ${res.status} ${detail}` };+ } catch (e: unknown) {+ return { id, served: true, detail: e instanceof Error ? e.message : String(e) };+ }+ })+ );+}++/**+ * Pick a probe model from the project's own publisher models.+ *+ * Ranked by the SHARED `rankDiscoveredModels` — the comparator the picker and+ * every other provider's discovery already use — so Vertex orders newest-first+ * like everything else rather than by a second rule invented here. Filtered by+ * the SHARED `isChatCapable`, so an embedding, image, TTS or video model is+ * never offered. Then narrowed to what the project answers for in its own+ * location (see the header), and only then does `exclude` choose, so the Test+ * All retry loop gets the NEXT candidate rather than the same one again.+ */+export async function discoverVertexProbeModel(+ exclude?: ReadonlySet<string>+): Promise<DiscoveryOutcome> {+ const config = await resolveVertexConfig();+ const cacheKey = config ? `vertex:${config.projectId}:${config.location}` : "vertex:unresolved";+ const hit = _cache.get(cacheKey);+ if (hit && hit.expiresAt > Date.now()) {+ return pickFrom(hit.ranked, hit.reason, exclude);+ }++ const fail = (reason: string): DiscoveryOutcome => {+ log(`[vertex-discovery] ${reason}`);+ _cache.set(cacheKey, { ranked: [], reason, expiresAt: Date.now() + CACHE_TTL_MS });+ return { model: null, reason };+ };++ let listing: Awaited<ReturnType<typeof listVertexPublisherModels>>;+ try {+ listing = await listVertexPublisherModels();+ } catch (e: unknown) {+ return fail(`Vertex AI model list failed: ${e instanceof Error ? e.message : String(e)}`);+ }++ const ranked = rankDiscoveredModels(listing.models)+ .map((m) => m.id)+ .filter(isChatCapable);+ if (ranked.length === 0) {+ return fail(+ listing.listed === 0+ ? `${listing.endpoint} listed no models for this project`+ : `no chat-capable model among the ${listing.listed} that ${listing.endpoint} listed for this project`+ );+ }+ if (!config) {+ // Unreachable: the listing above needs the project too. Narrowing only.+ return fail("no Google Cloud project resolved");+ }++ const auth = await credentials.getRequestAuth("vertex", { model: "" });+ const checked = await verifyServed(+ ranked.slice(0, MAX_VERIFIED_CANDIDATES),+ config,+ auth.headers+ );+ const served = checked.filter((c) => c.served).map((c) => c.id);+ log(+ `[vertex-discovery] ${listing.listed} listed → ${ranked.length} chat-capable → ` ++ `${served.length} served in ${config.location}: ` ++ `${served.slice(0, 5).join(", ")}${served.length > 5 ? ", …" : ""}`+ );+ if (served.length === 0) {+ // Every candidate was refused by name. Quote one upstream sentence: it names+ // the project and the location, which is what makes this actionable.+ const example = checked.find((c) => c.detail);+ return fail(+ `${config.projectId} lists ${ranked.length} chat model(s) but serves none of them in ` ++ `${config.location} — another location may (VERTEX_LOCATION)` ++ (example ? `. ${example.id}: ${example.detail}` : "")+ );+ }+ _cache.set(cacheKey, { ranked: served, expiresAt: Date.now() + CACHE_TTL_MS });+ return pickFrom(served, undefined, exclude);+}++function pickFrom(+ ranked: string[],+ reason: string | undefined,+ exclude?: ReadonlySet<string>+): DiscoveryOutcome {+ if (ranked.length === 0) return { model: null, reason };+ const pick = ranked.find((m) => !exclude?.has(m));+ if (!pick) {+ return { model: null, reason: `all ${ranked.length} candidate model(s) already tried` };+ }+ // The contract the probe depends on: whatever is returned has to parse back+ // into the publisher + model the endpoint builder expects. Cheap, and it fails+ // loudly here rather than as a 404 three layers down.+ parseVertexModel(pick);+ return { model: pick };+}diff --git a/packages/cli/src/providers/transport/vertex-oauth.ts b/packages/cli/src/providers/transport/vertex-oauth.tsindex 03031cb8..7873b191 100644--- a/packages/cli/src/providers/transport/vertex-oauth.ts+++ b/packages/cli/src/providers/transport/vertex-oauth.ts@@ -20,6 +20,7 @@ import {getVertexAuthManager,} from "../../auth/vertex-auth.js";import { log } from "../../logger.js";+import type { DiscoveryOutcome } from "./probe-discovery.js";import type { ProviderTransport, StreamFormat } from "./types.js";export interface ParsedVertexModel {@@ -27,6 +28,16 @@ export interface ParsedVertexModel {model: string;}+/**+ * The publisher a BARE Vertex model id belongs to.+ *+ * A rule, not a list: it is the default `parseVertexModel` applies, and probe+ * discovery reads it so a bare id round-trips to the same publisher it was+ * listed under. Other publishers (anthropic, mistralai, …) are reached by+ * qualifying the id, never by enumerating them here.+ */+export const VERTEX_DEFAULT_PUBLISHER = "google";+/*** Parse vertex model string into publisher and model.* "gemini-2.5-flash" → { publisher: "google", model: "gemini-2.5-flash" }@@ -35,7 +46,7 @@ export interface ParsedVertexModel {export function parseVertexModel(modelId: string): ParsedVertexModel {const parts = modelId.split("/");if (parts.length === 1) {- return { publisher: "google", model: parts[0] };+ return { publisher: VERTEX_DEFAULT_PUBLISHER, model: parts[0] };}return { publisher: parts[0], model: parts.slice(1).join("/") };}@@ -73,6 +84,25 @@ export class VertexProviderTransport implements ProviderTransport {);}+ /**+ * Pick a probe model from this PROJECT's own publisher models.+ *+ * Vertex has no catalog probe pick and never will: the cloud models catalog+ * marks it `client_model_selection_required` because availability depends on+ * the user's project, permissions and region. Without this, Test All had no+ * candidate and reported "transport does not support discovery" for an install+ * that answers normally. See `vertex-discovery.ts` for the endpoint and the+ * filters, every one of which reads a field the API itself publishes.+ *+ * Imported DYNAMICALLY: that module reads this one (for the default publisher+ * and the round-trip check), and discovery is a probe-time path that has no+ * business on the request path's import graph.+ */+ async discoverProbeModel(exclude?: ReadonlySet<string>): Promise<DiscoveryOutcome> {+ const { discoverVertexProbeModel } = await import("./vertex-discovery.js");+ return discoverVertexProbeModel(exclude);+ }+async getHeaders(): Promise<Record<string, string>> {return { ...(this.cachedAuth?.headers ?? {}) };}diff --git a/packages/cli/src/proxy-server.ts b/packages/cli/src/proxy-server.tsindex 89313314..8e7e2917 100644--- a/packages/cli/src/proxy-server.ts+++ b/packages/cli/src/proxy-server.ts@@ -572,9 +572,10 @@ export async function createProxyServer(// Firebase catalogs now. The OpenRouter catalog is still warmed below via// warmAllCatalogs() since it backs vendor-prefix resolution.- // Load effective routing rules once at startup. Returns a merged view of- // DEFAULT_ROUTING_RULES + global config + local config (local wins). The- // routing engine consults these via route() for every bare-name request.+ // Load effective routing rules once at startup: the USER's global config ++ // local config (local wins), and nothing else — there is no shipped table any+ // more. The routing engine consults these via route() for every bare-name+ // request, and falls through to the catalog-gathered chain when none matches.const effectiveRoutingRules = loadRoutingRules();// Cache fallback handlers by target model string.@@ -830,9 +831,9 @@ export async function createProxyServer(}} else {// No routable provider for a bare model name. Routing is fully- // data-driven now (DEFAULT_ROUTING_RULES + user overrides) — if the- // chain is empty and credential filtering produces nothing, that's- // the user's configured outcome. Throw so the request handler+ // data-driven now (the user's own rules, else the cloud models+ // catalog) — if the chain is empty and credential filtering produces+ // nothing, that is what the data says. Throw so the request handler// surfaces a clean error instead of silently falling through to a// legacy OpenRouter fallback. (Pre-commit-5 there was a hidden// OpenRouter step 7 that masked the no-route case.)diff --git a/packages/cli/src/tui/App.tsx b/packages/cli/src/tui/App.tsxindex 91546f27..1f4d84b9 100644--- a/packages/cli/src/tui/App.tsx+++ b/packages/cli/src/tui/App.tsx@@ -33,7 +33,6 @@ import {setEndpoint,setKeychainEnabled,} from "../profile-config.js";-import { DEFAULT_ROUTING_RULES } from "../providers/default-routing-rules.js";import { ensureEndpointsRegistered } from "../providers/endpoint-registration.js";import {deleteKeychainSecret,@@ -136,6 +135,7 @@ import {maskKey,providerAuthCapabilities,providerAuthSource,+ providerCredentialNote,providerIsReady,providerIsReadyForDisplay,} from "./providers.js";@@ -628,47 +628,39 @@ export function App({ requestLogin }: AppProps = {}) {process.env.CLAUDISH_STATS === "0" || process.env.CLAUDISH_STATS === "false";const statsEnabled = !statsDisabledByEnv && config.stats?.enabled === true;- // Merged routing rules: built-in defaults + global config + project-local- // config rendered as a flat list with NO shadowing. If a pattern exists at- // multiple layers (e.g. a global override AND a project rule for `gpt-*`),- // BOTH rows are visible — the user can edit/delete each independently.+ // The USER's routing rules — global config + project-local config — rendered+ // as a flat list with NO shadowing. If a pattern exists at both layers (e.g.+ // a global rule AND a project rule for `gpt-*`), BOTH rows are visible and+ // the user can edit/delete each independently.+ //+ // There is no third "built-in defaults" layer to show. `DEFAULT_ROUTING_RULES`+ // was deleted when routing began gathering candidates from the cloud models+ // catalog, so there is no shipped table these rules could override; a model+ // with no user rule is routed from the catalog, which is per-model data this+ // table cannot enumerate. The catch-all header above shows the one thing that+ // remains global: the fallback hop in force.//// The runtime routing engine (loadRoutingRules + matchRoutingRule) still- // applies precedence (project beats global beats default), but the TUI- // shows the data as it exists on disk, not the runtime resolution.+ // applies precedence (project beats global), but the TUI shows the data as it+ // exists on disk, not the runtime resolution.//// Catch-all `*` is rendered separately above the table and excluded here.//- // Sort order: defaults first (alphabetical), then global, then project.- // `loadLocalConfig()` is called inside the memo so a `refreshConfig()`- // after a project save triggers re-derivation.+ // Sort order: global, then project. `loadLocalConfig()` is called inside the+ // memo so a `refreshConfig()` after a project save triggers re-derivation.// biome-ignore lint/correctness/useExhaustiveDependencies: deps deliberately tuned to control re-derivationconst mergedRules: MergedRule[] = useMemo(() => {const out: MergedRule[] = [];const localCfg = loadLocalConfig();- for (const [pat, chain] of Object.entries(DEFAULT_ROUTING_RULES)) {- if (pat === "*") continue;- out.push({ kind: "default", pattern: pat, chain, overridesDefault: false });- }for (const [pat, chain] of Object.entries(config.routing ?? {})) {if (pat === "*") continue;- out.push({- kind: "global",- pattern: pat,- chain,- overridesDefault: pat in DEFAULT_ROUTING_RULES,- });+ out.push({ kind: "global", pattern: pat, chain });}if (localCfg?.routing) {for (const [pat, chain] of Object.entries(localCfg.routing)) {if (pat === "*") continue;- out.push({- kind: "project",- pattern: pat,- chain,- overridesDefault: pat in DEFAULT_ROUTING_RULES,- });+ out.push({ kind: "project", pattern: pat, chain });}}return out;@@ -2487,12 +2479,12 @@ export function App({ requestLogin }: AppProps = {}) {setChainOrder([...rule.chain]);setChainCursor(0);setStatusMsg(null);- // Default scope to the rule's current scope (or "global" for defaults- // — matches the typical case where users write personal overrides).+ // Default scope to the rule's current scope. Every row is now a user+ // rule, so there is no third case to fold into "global".const initialScope: RoutingScope = rule.kind === "project" ? "project" : "global";setRoutingScope(initialScope);setRoutingScopeCursor(initialScope === "global" ? 0 : 1);- setEditingExistingScope(rule.kind === "default" ? null : rule.kind);+ setEditingExistingScope(rule.kind);setEditingExistingPattern(rule.pattern);setRoutingScopeReturnsToEdit(true);setMode("pick_routing_scope");@@ -2504,11 +2496,7 @@ export function App({ requestLogin }: AppProps = {}) {} else {const idx = Math.min(providerIndex, mergedRules.length - 1);const rule = mergedRules[idx]!;- if (rule.kind === "default") {- setStatusMsg(- `Built-in default '${rule.pattern}' cannot be deleted. Press e to override.`- );- } else if (rule.kind === "project") {+ if (rule.kind === "project") {const local = loadLocalConfig();if (local?.routing && local.routing[rule.pattern] !== undefined) {delete local.routing[rule.pattern];@@ -2725,6 +2713,7 @@ export function App({ requestLogin }: AppProps = {}) {isKcKey={isKcKey}hasKcKey={hasKcKey}keySaveTarget={keychainSupported ? "macOS Keychain" : "config.json"}+ credentialNote={providerCredentialNote(selectedProvider)}cfgKeyMask={cfgKeyMask}envKeyMask={envKeyMask}activeEndpoint={activeEndpoint}diff --git a/packages/cli/src/tui/components/ProviderDetail.tsx b/packages/cli/src/tui/components/ProviderDetail.tsxindex 4a828600..28cfe377 100644--- a/packages/cli/src/tui/components/ProviderDetail.tsx+++ b/packages/cli/src/tui/components/ProviderDetail.tsx@@ -73,6 +73,13 @@ interface ProviderDetailProps {* the kind of thing a user is entitled to see before pressing Enter.*/keySaveTarget: string;+ /**+ * Where this provider's credential actually came from, when the generic+ * env/config row cannot say it (Vertex: a Google Cloud project out of the ADC+ * file or `gcloud config`). Undefined for every env-var provider, which leaves+ * their pane byte-identical.+ */+ credentialNote?: string;cfgKeyMask: string;envKeyMask: string;activeEndpoint: string;@@ -110,6 +117,7 @@ export function ProviderDetail({isKcKey,hasKcKey,keySaveTarget,+ credentialNote,cfgKeyMask,envKeyMask,activeEndpoint,@@ -246,17 +254,20 @@ export function ProviderDetail({expects, so "Not configured" is actionable without leaving the TUI.Fits here because the "From:" segment only renders when a key ISset — the two never share the row. */}- {!hasKey && !selectedProvider.isLocal && selectedProvider.apiKeyEnvVar && (- <>- <span fg={C.dim}>{" "}</span>- <span fg={C.blue} attributes={A.bold}>- {"Env: "}- </span>- <span fg={C.yellow}>- {[selectedProvider.apiKeyEnvVar, ...(selectedProvider.aliases ?? [])].join(" | ")}- </span>- </>- )}+ {!hasKey &&+ !selectedProvider.isLocal &&+ selectedProvider.apiKeyEnvVar &&+ !credentialNote && (+ <>+ <span fg={C.dim}>{" "}</span>+ <span fg={C.blue} attributes={A.bold}>+ {"Env: "}+ </span>+ <span fg={C.yellow}>+ {[selectedProvider.apiKeyEnvVar, ...(selectedProvider.aliases ?? [])].join(" | ")}+ </span>+ </>+ )}{hasKey && selectedProvider.isLocal && (<><span fg={C.dim}>{" "}</span>@@ -271,7 +282,7 @@ export function ProviderDetail({{/* OAuth branch FIRST among the non-local sources. Without it anOAuth-only provider reaches the env/cfg block below, where bothflags are false and "From: " renders with nothing after it. */}- {hasKey && !selectedProvider.isLocal && isOAuth && (+ {hasKey && !selectedProvider.isLocal && isOAuth && !credentialNote && (<><span fg={C.dim}>{" "}</span><span fg={C.blue} attributes={A.bold}>@@ -283,7 +294,7 @@ export function ProviderDetail({<span fg={C.fgMuted}>{" (used)"}</span></>)}- {hasKey && !selectedProvider.isLocal && isOAuth && (+ {hasKey && !selectedProvider.isLocal && isOAuth && !credentialNote && (<><span fg={C.dim}>{" "}</span><span fg={C.blue} attributes={A.bold}>@@ -294,7 +305,7 @@ export function ProviderDetail({</span></>)}- {hasKey && !selectedProvider.isLocal && !isOAuth && (+ {hasKey && !selectedProvider.isLocal && !isOAuth && !credentialNote && (<><span fg={C.dim}>{" "}</span><span fg={C.blue} attributes={A.bold}>@@ -330,6 +341,18 @@ export function ProviderDetail({</>)}</text>+ {/* Replaces the `Env:` / `From:` segments above for a provider whose+ credential is not an environment variable — it names the source+ precisely (which project, from the ADC file or `gcloud config`) or, when+ nothing resolved, both remedies. */}+ {credentialNote && (+ <text>+ <span fg={C.blue} attributes={A.bold}>+ {"Auth: "}+ </span>+ <span fg={hasKey ? C.green : C.yellow}>{credentialNote}</span>+ </text>+ )}{selectedProvider.endpointEnvVar && (<text><span fg={C.blue} attributes={A.bold}>@@ -354,7 +377,9 @@ export function ProviderDetail({{selectedProvider.keyUrl && !failureText && (<text><span fg={C.blue} attributes={A.bold}>- Get Key:{" "}+ {/* "Get Key" is the wrong instruction for a provider that has no key+ to get — the URL is its console, not a key page. */}+ {credentialNote ? "Console: " : "Get Key: "}</span><span fg={C.cyan}>{selectedProvider.keyUrl}</span></text>diff --git a/packages/cli/src/tui/components/RoutingContent.tsx b/packages/cli/src/tui/components/RoutingContent.tsxindex b7603612..49fdac3f 100644--- a/packages/cli/src/tui/components/RoutingContent.tsx+++ b/packages/cli/src/tui/components/RoutingContent.tsx@@ -2,7 +2,7 @@ import type { ScrollBoxRenderable } from "@opentui/core";/** @jsxImportSource @opentui/react */import { useEffect, useRef } from "react";import type { ClaudishProfileConfig } from "../../profile-config.js";-import { DEFAULT_ROUTING_RULES } from "../../providers/default-routing-rules.js";+import { DEFAULT_FALLBACK_PROVIDER } from "../../providers/routing-rules.js";import { DETAIL_H, getChainProviders } from "../constants.js";import { deriveProbeOutcome } from "../probe-outcome.js";import { providerIsReady } from "../providers.js";@@ -362,34 +362,50 @@ export function RoutingContent({flexDirection="column"paddingX={1}>- {/* Catch-all default — the only "global" default that actually exists.- Per-pattern defaults (gpt-* → codex/openai/openrouter, etc.) are- visible in the rule table below alongside any user overrides.- Each header `<text>` is pinned to height={1} so flex layout doesn't- collapse them into the scrollbox below in tight viewports. */}+ {/* The FALLBACK hop — the last-resort provider appended after the chain+ gathered from the cloud models catalog, and the only routing fact left+ that is global rather than per-model.++ This used to compare `defaultProvider` against the shipped+ DEFAULT_ROUTING_RULES catch-all and report which "overrode" which.+ That table is gone, so there is no built-in to override; what is true+ now is simply which provider occupies the last position, and whether+ the user emptied it. Each header `<text>` is pinned to height={1} so+ flex layout doesn't collapse them into the scrollbox below in tight+ viewports. */}<text height={1}><span fg={C.blue} attributes={A.bold}>- {" Catch-all default:"}+ {" Fallback hop:"}</span>- <span fg={C.fgMuted}>{" (used for any model not matched by a rule)"}</span>+ <span fg={C.fgMuted}>{" (tried last, after every provider the catalog maps)"}</span></text><text height={1}>- <span fg={C.dim}>{" * "}</span>- <span fg={C.dim}>{"→ "}</span>- <span fg={C.cyan}>- {config.defaultProvider && config.defaultProvider.length > 0- ? config.defaultProvider- : (DEFAULT_ROUTING_RULES["*"]?.[0] ?? "openrouter")}- </span>{(() => {- const builtIn = DEFAULT_ROUTING_RULES["*"]?.[0] ?? "openrouter";- const override = config.defaultProvider;- const hasOverride = !!(override && override.length > 0);- const overridesBuiltIn = hasOverride && override !== builtIn;- return overridesBuiltIn ? (- <span fg={C.fgMuted}>{` (defaultProvider — overrides built-in '${builtIn}')`}</span>- ) : (- <span fg={C.fgMuted}>{" (built-in)"}</span>+ const configured = config.defaultProvider;+ // An explicitly EMPTY string disables the hop; unset means "no+ // preference" and takes openrouter. `routeBare` draws the same line.+ if (configured !== undefined && configured.length === 0) {+ return (+ <>+ <span fg={C.dim}>{" → "}</span>+ <span fg={C.yellow}>{"disabled"}</span>+ <span fg={C.fgMuted}>+ {" (defaultProvider is empty — an unroutable model errors instead)"}+ </span>+ </>+ );+ }+ const hasOverride = configured !== undefined && configured.length > 0;+ return (+ <>+ <span fg={C.dim}>{" → "}</span>+ <span fg={C.cyan}>{hasOverride ? configured : DEFAULT_FALLBACK_PROVIDER}</span>+ <span fg={C.fgMuted}>+ {hasOverride+ ? " (defaultProvider)"+ : " (default — set defaultProvider to change)"}+ </span>+ </>);})()}</text>@@ -463,47 +479,19 @@ export function RoutingContent({>{mergedRules.map((rule, idx) => {const sel = idx === providerIndex;- const isDefault = rule.kind === "default";const isProject = rule.kind === "project";- // Marker priority: project (▴ cyan) > override (★ yellow) >- // user (• green) > default (· dim). Each row owns one scope- // — no shadowing in the table — so override + project never- // collide on the same row.- let marker: string;- let markerFg: string;- if (isDefault) {- marker = "·";- markerFg = C.dim;- } else if (isProject) {- marker = "▴";- markerFg = C.cyan;- } else if (rule.overridesDefault) {- marker = "★";- markerFg = C.yellow;- } else {- marker = "•";- markerFg = C.green;- }+ // Marker: project (▴ cyan) > global (• green). Every row is one+ // of the user's own rules and owns one scope — no shadowing in+ // the table. The dim "·" built-in row and the yellow "★"+ // override-of-a-default row are both gone, because the shipped+ // rules table they compared against no longer exists.+ const marker = isProject ? "▴" : "•";+ const markerFg = isProject ? C.cyan : C.green;// SCOPE column: explicit text, color-coded.- // default → "—" (dim)- // global → "global" (green)- // project → "project" (cyan)- let scopeText: string;- let scopeFg: string;- if (isDefault) {- scopeText = "— ";- scopeFg = C.dim;- } else if (isProject) {- scopeText = "project ";- scopeFg = C.cyan;- } else {- scopeText = "global ";- scopeFg = C.green;- }- // Pattern column: white when selected, cyan when user, dim when default.- const patFg = sel ? C.strong : isDefault ? C.fgMuted : C.cyan;- // Chain column: cyan when selected, fgMuted when user, dim when default.- const chainFg = sel ? C.cyan : isDefault ? C.dim : C.fgMuted;+ const scopeText = isProject ? "project " : "global ";+ const scopeFg = isProject ? C.cyan : C.green;+ const patFg = sel ? C.strong : C.cyan;+ const chainFg = sel ? C.cyan : C.fgMuted;return (<boxkey={`${rule.kind}-${rule.pattern}`}@@ -512,7 +500,7 @@ export function RoutingContent({backgroundColor={sel ? C.bgHighlight : C.bg}><text>- <span fg={markerFg} attributes={A.boldIf(!isDefault)}>{` ${marker} `}</span>+ <span fg={markerFg} attributes={A.bold}>{` ${marker} `}</span><span fg={patFg} attributes={A.boldIf(sel)}>{rule.pattern.padEnd(16).substring(0, 16)}</span>diff --git a/packages/cli/src/tui/components/RoutingDetail.tsx b/packages/cli/src/tui/components/RoutingDetail.tsxindex 679277af..bb247be5 100644--- a/packages/cli/src/tui/components/RoutingDetail.tsx+++ b/packages/cli/src/tui/components/RoutingDetail.tsx@@ -15,14 +15,13 @@ export function RoutingDetail({ probeMode, mergedRules }: RoutingDetailProps) {return null;}- const defaults = mergedRules.filter((r) => r.kind === "default").length;- const globalRules = mergedRules.filter((r) => r.kind === "global");+ // Two kinds of row, because a row can only be one of the user's own rules+ // now. The "built-in default" and "override of default" counts this panel+ // used to carry were both about the shipped DEFAULT_ROUTING_RULES table,+ // which was deleted when routing started gathering candidates from the cloud+ // models catalog — they would now read 0 and 0 forever.+ const globalCustom = mergedRules.filter((r) => r.kind === "global").length;const projectRules = mergedRules.filter((r) => r.kind === "project");- // Among global rules, how many override a built-in default? (Project rules- // get the ▴ marker regardless, so their override status doesn't change- // the count.)- const globalOverrides = globalRules.filter((r) => r.overridesDefault).length;- const globalCustom = globalRules.length - globalOverrides;// Format counts with a fixed-width number column so the labels line up// even when counts grow into double digits.@@ -44,40 +43,16 @@ export function RoutingDetail({ probeMode, mergedRules }: RoutingDetailProps) {and counts line up via fixed-width pads. */}<box height={1} flexDirection="row"><box width={32}>- <text>- <span fg={C.dim} attributes={A.bold}>- {" · "}- </span>- <span fg={C.fgMuted}>{"built-in default "}</span>- <span fg={C.cyan} attributes={A.bold}>- {fmtCount(defaults)}- </span>- </text>- </box>- <box><text><span fg={C.green} attributes={A.bold}>- {" • "}+ {" • "}</span>- <span fg={C.fgMuted}>{"global custom "}</span>+ <span fg={C.fgMuted}>{"global rule "}</span><span fg={C.green} attributes={A.bold}>{fmtCount(globalCustom)}</span></text></box>- </box>- <box height={1} flexDirection="row">- <box width={32}>- <text>- <span fg={C.yellow} attributes={A.bold}>- {" ★ "}- </span>- <span fg={C.fgMuted}>{"override of default "}</span>- <span fg={C.yellow} attributes={A.bold}>- {fmtCount(globalOverrides)}- </span>- </text>- </box><box><text><span fg={C.cyan} attributes={A.bold}>@@ -90,6 +65,15 @@ export function RoutingDetail({ probeMode, mergedRules }: RoutingDetailProps) {</text></box></box>+ <box height={1} flexDirection="row">+ <box>+ <text>+ <span fg={C.fgMuted}>+ {" Anything with no rule here is routed from the models catalog."}+ </span>+ </text>+ </box>+ </box></box>);}diff --git a/packages/cli/src/tui/providers.ts b/packages/cli/src/tui/providers.tsindex 8841dae4..5ec9c0ad 100644--- a/packages/cli/src/tui/providers.ts+++ b/packages/cli/src/tui/providers.ts@@ -6,6 +6,12 @@import { hasSharedAntigravityToken } from "../auth/antigravity-token.js";import { type CredentialSource, describeSourceSync } from "../auth/credentials/source.js";import { hasOAuthCredentials } from "../auth/oauth-registry.js";+import {+ VERTEX_SET_PROJECT_REMEDY,+ describeVertexProjectSource,+ hasVertexAdcCredentials,+ peekVertexProjectOrigin,+} from "../auth/vertex-auth.js";import { hasDevinCredentials } from "../providers/devin/devin-credentials.js";import type { LocalLiveness } from "../providers/local-liveness.js";import { type ProviderDefinition, getAllProviders } from "../providers/provider-definitions.js";@@ -179,20 +185,55 @@ export function providerAuthCapabilities(// render the row as "not configurable" for a user who is signed in. Relaxing// the local expression is the narrow fix; adding a slug would advertise a// `claudish login devin` command that does not exist.- const oauthSupported = !!p.oauthSlug || p.catalogName === "devin";+ // Vertex joins Devin here for the same reason: it is token-authenticated+ // (Application Default Credentials, or a service-account file) with no+ // claudish-side login, so it declares no oauthLoginSlug — but a row rendering+ // "no auth method available" for a machine that holds a live `ya29…` token is+ // the wrong statement, and the `l` keybinding stays gated on `oauthSlug` so no+ // `claudish login vertex` is advertised.+ const oauthSupported = !!p.oauthSlug || p.catalogName === "devin" || p.catalogName === "vertex";// Antigravity's OAuth token is in the shared keychain, not an oauth-file — so// hasOAuthCredentials can't see it; check the keychain directly (memoized).const oauthSet =oauthSupported &&(hasOAuthCredentials(p.catalogName) ||(p.catalogName === "antigravity" && hasSharedAntigravityToken()) ||- (p.catalogName === "devin" && hasDevinCredentials()));+ (p.catalogName === "devin" && hasDevinCredentials()) ||+ (p.catalogName === "vertex" && hasVertexAdcCredentials()));return {apiKey: { supported: apiKeySupported, set: apiKeySet },oauth: { supported: oauthSupported, set: oauthSet },};}+/**+ * One line naming WHERE this provider's credential came from, for providers the+ * generic `Env: <VAR>` / `From: env|config` row cannot describe.+ *+ * Returns undefined for every env-var provider, so the detail pane is unchanged+ * for them. Vertex is the case it exists for: its `apiKeyEnvVar` is a Google+ * Cloud PROJECT id, resolvable from the ADC file or `gcloud config`, and there+ * is NO API key to go and find — the Express mode was deleted on 2026-09-21, so+ * "Env: VERTEX_PROJECT" plus "Get Key" sent the reader after a credential that+ * does not exist.+ *+ * Sync and free of subprocesses (see `peekVertexProjectOrigin`), so it is safe+ * on a render path.+ */+export function providerCredentialNote(p: ProviderDef): string | undefined {+ if (p.catalogName !== "vertex") return undefined;+ const origin = peekVertexProjectOrigin();+ if (!origin) {+ // The two failures are different and so are their fixes: a credential that+ // signs nothing, versus a signed credential with nowhere to send it. Neither+ // sentence mentions an API key, because there is none to find.+ return hasVertexAdcCredentials()+ ? `ADC present, no project — ${VERTEX_SET_PROJECT_REMEDY}`+ : `No credential — run \`gcloud auth application-default login\`, then ${VERTEX_SET_PROJECT_REMEDY}`;+ }+ return `Project ${origin.projectId} from ${describeVertexProjectSource(origin)}`;+}+/*** The provider list, built LIVE from the catalog on every call.*diff --git a/packages/cli/src/tui/types.ts b/packages/cli/src/tui/types.tsindex 6ce34108..16d7bdb7 100644--- a/packages/cli/src/tui/types.ts+++ b/packages/cli/src/tui/types.ts@@ -39,24 +39,27 @@ export type Mode =export type RoutingScope = "global" | "project";/**- * A single row in the routing rules table. Rows from all three layers- * (built-in defaults, global config, project-local config) are shown- * concurrently — no shadowing in the UI. If a pattern exists at multiple- * layers, multiple rows render and each is independently editable.+ * A single row in the routing rules table — one of the USER's own rules, from+ * global config or from project-local config. Both layers are shown+ * concurrently, with no shadowing in the UI: if a pattern exists at both,+ * two rows render and each is independently editable.*- * Marker priority: project (▴ cyan) > override (★ yellow) > user (• green)- * > default (· dim). `overridesDefault` is true when a user rule (global- * or project) shares an exact pattern key with a built-in default — used- * to pick ★ vs • for the marker. The runtime routing engine still applies- * precedence (project beats global beats default), but the table reflects- * disk state.+ * There is no third `"default"` kind and no `overridesDefault` flag any more.+ * Both described the shipped `DEFAULT_ROUTING_RULES` table, which was deleted+ * when routing started gathering its candidates from the cloud models catalog.+ * Nothing is left for a user rule to "override": a rule that matches is the+ * whole chain, used verbatim, and a model with no matching rule is routed from+ * the catalog. Keeping the flag would have gone on drawing a ★ against a+ * comparison that no longer exists.+ *+ * Marker priority: project (▴ cyan) > global (• green). The runtime routing+ * engine still applies precedence (project beats global), but the table+ * reflects disk state.*/export interface MergedRule {- kind: "default" | "global" | "project";+ kind: "global" | "project";pattern: string;chain: string[];- /** True when a user rule (global or project) shares a key with a built-in default. */- overridesDefault: boolean;}export type ProbeMode = "idle" | "input" | "running" | "done";