Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
feat: gather routing candidates from the catalog (not wired in)
Jack Rudenko4f4f765b4c46
diff --git a/packages/cli/src/providers/custom-endpoints-loader.ts b/packages/cli/src/providers/custom-endpoints-loader.tsindex 9fb62644..b352667a 100644--- a/packages/cli/src/providers/custom-endpoints-loader.ts+++ b/packages/cli/src/providers/custom-endpoints-loader.ts@@ -39,7 +39,8 @@ import type { ModelHandler } from "../handlers/types.js";import type { ClaudishProfileConfig } from "../profile-config.js";import { clearEndpointUnavailable, recordEndpointUnavailable } from "./endpoint-diagnostics.js";import {- type ProviderDefinition,+ type RouteTier,+ type TieredProviderDefinition,type TransportType,baseUrlOverrideCandidates,runtimeHandler,@@ -229,6 +230,24 @@ export function loadCustomEndpoints(config: ClaudishProfileConfig): LoadResult {return result;}+/**+ * The routing tier of EVERY endpoint that arrives from config — user-authored or+ * bundled.+ *+ * `gateway`, and deliberately the weakest true thing claudish can say. A row+ * carries CONNECTION FACTS ONLY (see predefined-endpoint-schema.ts): a URL, a+ * path, a wire format and the vendor's env var. Nothing in it distinguishes+ * Together AI reselling forty vendors from Cohere serving its own models, so+ * classifying one as `native` would be a guess, and guessing UPWARDS would sort a+ * third-party endpoint ahead of the vendor's own. `gateway` is the last tier+ * before the fallback, so an endpoint claudish cannot classify sorts last among+ * the ones it can — which is the recoverable direction.+ *+ * Not `fallback`: that tier is a POSITION held by whichever provider+ * `defaultProvider` names, and no definition may claim it.+ */+const CUSTOM_ENDPOINT_TIER: RouteTier = "gateway";+/*** Build a ProviderDefinition for a custom endpoint so it appears in lookups* (getProviderByName, getAllProviders, etc.). The definition is minimal —@@ -241,7 +260,7 @@ function buildProviderDefinition(name: string,ep: CustomEndpoint,ovr?: EndpointDefinitionOverrides-): ProviderDefinition {+): TieredProviderDefinition {const apiKeyEnvVar = ovr?.apiKeyEnvVar ?? customEndpointKeyEnvVar(name);const apiKeyAliases = ovr?.apiKeyAliases;const baseUrlEnvVars = ovr?.baseUrlEnvVars;@@ -250,6 +269,7 @@ function buildProviderDefinition(if (ep.kind === "simple") {return {createHandler: runtimeHandler(name),+ tier: CUSTOM_ENDPOINT_TIER,name,displayName: name,transport: ep.format as TransportType,@@ -275,6 +295,7 @@ function buildProviderDefinition(return {createHandler: runtimeHandler(name),+ tier: CUSTOM_ENDPOINT_TIER,name,displayName: ep.displayName,transport: ep.transport as TransportType,diff --git a/packages/cli/src/providers/provider-definitions.ts b/packages/cli/src/providers/provider-definitions.tsindex 48525517..b9db6f21 100644--- a/packages/cli/src/providers/provider-definitions.ts+++ b/packages/cli/src/providers/provider-definitions.ts@@ -43,6 +43,55 @@ export type TransportType =export type TokenStrategy = "delta-aware" | "accumulate-both" | undefined;+/**+ * WHICH KIND of way-to-call-a-model a provider is — the one routing fact the+ * cloud models catalog cannot publish.+ *+ * Everything else routing needs about a connection is in the catalog: the wire+ * id, the price, the context window, the vendor, and (since v3) the route+ * binding that names the transport. What the catalog does NOT say is how+ * claudish should PREFER one connection over another, because that depends on+ * how the user pays claudish's providers, not on what the model is. This field+ * is that statement, declared once per provider, and `route-candidates.ts`+ * orders by it.+ *+ * The five values, and the line between the two flat-rate ones:+ *+ * - `subscription` — flat-rate, and the catalog publishes the plan's MEMBERSHIP+ * (`subscriptionPlanIds[]`), so a candidate can be gathered from the catalog+ * alone: `kimi-coding`, `glm-coding`, `qwen-token-plan`, `opencode-zen-go`.+ * - `dynamic-subscription` — flat-rate, but the ACCOUNT's own list decides what+ * it serves, so the catalog publishes no connection for it at all and a+ * candidate can only come from a namespace claim plus the account's dynamic+ * models catalog: `antigravity`, `grok-subscription`, `devin`,+ * `sakana-subscription`. Measured on generation+ * `g-20260921062451697-f490edba`: all four appear in the probe map as+ * `client_model_selection_required` and publish zero `aggregators[]` rows.+ * - `native` — the vendor's own metered endpoint (`openai`, `google`, `kimi`,+ * `z-ai`, `qwen-payg`, …). Billed per token by the company that made the model.+ * - `gateway` — a metered service reselling many vendors (`openrouter`, `poe`,+ * `vertex`, `ollamacloud`, `litellm`, `opencode-zen`), plus every custom and+ * bundled endpoint, which claudish cannot classify more precisely than "a+ * metered endpoint someone else operates".+ * - `fallback` — the last-resort hop. A POSITION, never a property: whichever+ * provider `defaultProvider` names occupies it, so NO definition declares it+ * and a provider that would otherwise be a `gateway` does not become one+ * here.+ *+ * NOT a billing oracle, and must not be used as one. `SUBSCRIPTION_PROVIDERS`+ * (handlers/shared/remote-provider-types.ts) still decides whether a user is+ * quoted a per-token price, and the two tables deliberately disagree on+ * `openai-codex` and `native-anthropic`: both are CREDENTIAL-decided — a metered+ * key reaches the same provider name — so naming their flat-rate ROUTE here says+ * nothing about who pays for a given request. See `ai-docs/architecture/` and+ * CLAUDE.md's Invariants: a provider wrongly called flat-rate accrues $0 against+ * real spend, which is the one error this field must not be allowed to cause.+ *+ * Unrelated to `PredefinedEndpointEvidenceSchema.tier` ("live" | "probe"), which+ * records how a bundled row was VERIFIED. Different object, different question.+ */+export type RouteTier = "subscription" | "dynamic-subscription" | "native" | "gateway" | "fallback";+export interface ProviderCapabilities {supportsTools?: boolean;supportsVision?: boolean;@@ -120,6 +169,23 @@ export interface ProviderDefinition {* is a stronger guarantee than any test: you cannot merge code that forgot.*/createHandler: LazyHandlerFactory | NoHandler;+ /**+ * WHICH KIND of route this is — see {@link RouteTier}. Read at routing time by+ * `route-candidates.ts`; a provider with no tier can never become a gathered+ * candidate, which is the safe direction (it is skipped, never guessed at).+ *+ * Declared optional HERE and REQUIRED on every table that feeds routing:+ * `BUILTIN_PROVIDERS` and the custom-endpoint builder are both typed+ * {@link TieredProviderDefinition}, so adding a provider to either without a+ * tier does not compile — the same compiler-enforced completeness+ * `createHandler` gets, and for the same reason (a half-added provider+ * silently answering from somewhere else is this project's worst failure+ * class). The optionality exists only because four TEST files construct+ * `ProviderDefinition` literals for unrelated features, and a test's fixture+ * has no routing tier to declare. Promote it to required here once those+ * literals carry one.+ */+ tier?: RouteTier;/** Canonical provider name (lowercase, unique key) */name: string;/** Human-readable display name (proper capitalization) */@@ -238,6 +304,17 @@ export interface ProviderDefinition {description?: string;}+/**+ * A definition that MUST state its routing tier.+ *+ * Every table a routing decision reads is typed with this rather than with+ * `ProviderDefinition`, so "forgot the tier" is a compile error at the two+ * places a real provider is born — `BUILTIN_PROVIDERS` below and+ * `buildProviderDefinition` in custom-endpoints-loader.ts — instead of a silent+ * absence that drops the provider from every gathered chain.+ */+export type TieredProviderDefinition = ProviderDefinition & { tier: RouteTier };+// ---------------------------------------------------------------------------// Built-in provider definitions// ---------------------------------------------------------------------------@@ -289,10 +366,11 @@ export function runtimeHandler(name: string): LazyHandlerFactory {};}-export const BUILTIN_PROVIDERS: ProviderDefinition[] = [+export const BUILTIN_PROVIDERS: TieredProviderDefinition[] = [// ── Google Gemini (direct API) ─────────────────────────────────────{createHandler: geminiHandler,+ tier: "native",name: "google",displayName: "Gemini",transport: "gemini",@@ -321,6 +399,7 @@ export const BUILTIN_PROVIDERS: ProviderDefinition[] = [// token (the `agy` keychain item), NOT a GEMINI_API_KEY.{createHandler: antigravityHandler,+ tier: "dynamic-subscription",name: "antigravity",displayName: "Antigravity",transport: "antigravity",@@ -354,6 +433,7 @@ export const BUILTIN_PROVIDERS: ProviderDefinition[] = [// subscription serving several vendors' models over a Connect-protobuf rpc.{createHandler: devinHandler,+ tier: "dynamic-subscription",name: "devin",displayName: "Devin",transport: "devin",@@ -415,6 +495,7 @@ export const BUILTIN_PROVIDERS: ProviderDefinition[] = [// ── OpenAI (direct API) ────────────────────────────────────────────{createHandler: openaiHandler,+ tier: "native",name: "openai",displayName: "OpenAI",transport: "openai",@@ -442,6 +523,14 @@ export const BUILTIN_PROVIDERS: ProviderDefinition[] = [// ── OpenAI Codex (Responses API — ChatGPT Plus/Pro subscription) ────{createHandler: openaiCodexHandler,+ // The ROUTE is the ChatGPT plan, and the catalog publishes its membership+ // (`openai/codex-subscription`), so this is where routing should prefer it.+ // It is NOT a billing statement: `openai-codex` is CREDENTIAL-decided+ // (`CREDENTIAL_DECIDED_PROVIDERS`) because an `OPENAI_CODEX_API_KEY` reaches+ // the same name against api.openai.com and bills the developer — measured,+ // `"payer": "developer"`. So this provider must still never be derived into+ // `SUBSCRIPTION_PROVIDERS`; the name check there short-circuits the probe.+ tier: "subscription",name: "openai-codex",displayName: "OpenAI Codex",transport: "openai",@@ -469,6 +558,7 @@ export const BUILTIN_PROVIDERS: ProviderDefinition[] = ["dedicated-handler","Served by OpenRouterHandler, which predates this table. proxy-server returns null here on purpose so the request falls through to it."),+ tier: "gateway",name: "openrouter",displayName: "OpenRouter",transport: "openrouter",@@ -492,6 +582,7 @@ export const BUILTIN_PROVIDERS: ProviderDefinition[] = [// ── xAI / Grok (OpenAI-compatible) ──────────────────────────────────{createHandler: openaiHandler,+ tier: "native",name: "x-ai",displayName: "xAI",transport: "openai",@@ -521,6 +612,7 @@ export const BUILTIN_PROVIDERS: ProviderDefinition[] = [// Full protocol write-up: ai-docs/reports/grok-subscription/protocol-spec.md{createHandler: grokSubscriptionHandler,+ tier: "dynamic-subscription",name: "grok-subscription",displayName: "Grok Build (subscription)",transport: "grok-subscription",@@ -569,6 +661,7 @@ export const BUILTIN_PROVIDERS: ProviderDefinition[] = [// ── MiniMax (Anthropic-compatible) ─────────────────────────────────{createHandler: anthropicCompatHandler,+ tier: "native",name: "minimax",displayName: "MiniMax",transport: "anthropic",@@ -611,6 +704,7 @@ export const BUILTIN_PROVIDERS: ProviderDefinition[] = [// ── MiniMax Coding Plan ────────────────────────────────────────────{createHandler: anthropicCompatHandler,+ tier: "subscription",name: "minimax-coding",displayName: "MiniMax Coding",transport: "anthropic",@@ -632,6 +726,7 @@ export const BUILTIN_PROVIDERS: ProviderDefinition[] = [// ── Kimi Coding Plan (must be before Kimi — kimi-for-coding$ is more specific than kimi-*){createHandler: anthropicCompatHandler,+ tier: "subscription",name: "kimi-coding",displayName: "Kimi Coding",transport: "kimi-coding",@@ -660,6 +755,7 @@ export const BUILTIN_PROVIDERS: ProviderDefinition[] = [// ── Kimi / Moonshot (Anthropic-compatible) ─────────────────────────{createHandler: anthropicCompatHandler,+ tier: "native",name: "kimi",displayName: "Kimi",transport: "anthropic",@@ -689,6 +785,7 @@ export const BUILTIN_PROVIDERS: ProviderDefinition[] = [// ── GLM / Zhipu (OpenAI-compatible) ────────────────────────────────{createHandler: glmHandler,+ tier: "native",name: "glm",displayName: "GLM",transport: "openai",@@ -721,6 +818,7 @@ export const BUILTIN_PROVIDERS: ProviderDefinition[] = [// ── GLM Coding Plan ────────────────────────────────────────────────{createHandler: glmHandler,+ tier: "subscription",name: "glm-coding",displayName: "GLM Coding",transport: "openai",@@ -742,6 +840,7 @@ export const BUILTIN_PROVIDERS: ProviderDefinition[] = [// ── Z.AI (Anthropic-compatible GLM API) ────────────────────────────{createHandler: anthropicCompatHandler,+ tier: "native",name: "z-ai",displayName: "Z.AI",transport: "anthropic",@@ -764,6 +863,7 @@ export const BUILTIN_PROVIDERS: ProviderDefinition[] = [// ── OllamaCloud ────────────────────────────────────────────────────{createHandler: ollamaCloudHandler,+ tier: "gateway",name: "ollamacloud",displayName: "OllamaCloud",transport: "ollamacloud",@@ -790,6 +890,7 @@ export const BUILTIN_PROVIDERS: ProviderDefinition[] = [// ── OpenCode Zen ───────────────────────────────────────────────────{createHandler: openCodeZenHandler,+ tier: "gateway",name: "opencode-zen",displayName: "OpenCode Zen",transport: "openai",@@ -830,6 +931,7 @@ export const BUILTIN_PROVIDERS: ProviderDefinition[] = [// ── OpenCode Zen Go (lite plan) ────────────────────────────────────{createHandler: openCodeZenHandler,+ tier: "subscription",name: "opencode-zen-go",displayName: "OpenCode Zen Go",transport: "openai",@@ -891,6 +993,15 @@ export const BUILTIN_PROVIDERS: ProviderDefinition[] = [// ── Vertex AI ──────────────────────────────────────────────────────{createHandler: vertexHandler,+ // Account-SELECTED but METERED: which publishers a project may call is a GCP+ // fact the catalog cannot know (it sits in the probe map as+ // `client_model_selection_required`, beside the flat-rate four), yet every+ // call is billed per token. `dynamic-subscription` would say the opposite+ // about money, so the tier follows the BILLING and the selection stays a+ // fact about entitlement, settled by the availability filter. Consequence,+ // stated so it is not mistaken for an oversight: Vertex gets no namespace+ // claim, so a model only Vertex serves stays reachable by `v@model`.+ tier: "gateway",name: "vertex",displayName: "Vertex AI",transport: "vertex",@@ -923,6 +1034,9 @@ export const BUILTIN_PROVIDERS: ProviderDefinition[] = [// ── LiteLLM ────────────────────────────────────────────────────────{createHandler: litellmHandler,+ // A proxy in front of many vendors, whose own URL the user supplies: a+ // gateway in every sense the tier means, even when the instance is theirs.+ tier: "gateway",name: "litellm",displayName: "LiteLLM",transport: "litellm",@@ -945,6 +1059,7 @@ export const BUILTIN_PROVIDERS: ProviderDefinition[] = [// ── Poe ────────────────────────────────────────────────────────────{createHandler: poeHandler,+ tier: "gateway",name: "poe",displayName: "Poe",transport: "poe",@@ -966,11 +1081,29 @@ export const BUILTIN_PROVIDERS: ProviderDefinition[] = [},// ── Ollama (local) ─────────────────────────────────────────────────+ //+ // THE FOUR LOCAL PROVIDERS ARE `native`, and the tier is inert for them.+ //+ // Inert first, because that is what makes the choice cheap: a local server is+ // bound to no catalog route (`ollama/cloud` belongs to `ollamacloud`, not to+ // this entry), so no catalog connection can ever name one, and only a+ // `dynamic-subscription` may claim a namespace — so no local provider can be+ // gathered as a remote candidate at all. Local models reach a request the way+ // they always have: an explicit `[email protected]`, or the local-provider path.+ //+ // `native` among the four remaining values because the request goes to the+ // endpoint that runs the model, with no reseller and no plan in between —+ // which is what `native` means minus the metering. `gateway` would be false+ // (nothing is resold, nothing is billed) and `subscription` would be worse: it+ // claims a plan with a published membership, and would sort a local server+ // ahead of a subscription the user actually pays for if the tier ever stopped+ // being inert.{createHandler: noHandler("local","Built by the local-provider path; never reaches direct-api."),+ tier: "native",name: "ollama",displayName: "Ollama",transport: "local",@@ -1002,6 +1135,7 @@ export const BUILTIN_PROVIDERS: ProviderDefinition[] = ["local","Built by the local-provider path; never reaches direct-api."),+ tier: "native",name: "lmstudio",displayName: "LM Studio",transport: "local",@@ -1035,6 +1169,7 @@ export const BUILTIN_PROVIDERS: ProviderDefinition[] = ["local","Built by the local-provider path; never reaches direct-api."),+ tier: "native",name: "vllm",displayName: "vLLM",transport: "local",@@ -1061,6 +1196,7 @@ export const BUILTIN_PROVIDERS: ProviderDefinition[] = ["local","Built by the local-provider path; never reaches direct-api."),+ tier: "native",name: "mlx",displayName: "MLX",transport: "local",@@ -1083,6 +1219,7 @@ export const BUILTIN_PROVIDERS: ProviderDefinition[] = [// ── DeepSeek (OpenAI-compatible direct API) ─────────────────────────{createHandler: openaiHandler,+ tier: "native",name: "deepseek",displayName: "DeepSeek",transport: "openai",@@ -1115,6 +1252,7 @@ export const BUILTIN_PROVIDERS: ProviderDefinition[] = [// pinned id still reaches the alias, and no per-provider code is needed here.{createHandler: openaiHandler,+ tier: "native",name: "mistralai",displayName: "Mistral",transport: "openai",@@ -1152,6 +1290,7 @@ export const BUILTIN_PROVIDERS: ProviderDefinition[] = [// ── Sakana Fugu (OpenAI-compatible direct API / token plan) ────────{createHandler: openaiHandler,+ tier: "native",name: "sakana",displayName: "Sakana Fugu",transport: "openai",@@ -1188,6 +1327,10 @@ export const BUILTIN_PROVIDERS: ProviderDefinition[] = [// distinction lives in the key, set at creation in the console.){createHandler: openaiHandler,+ // Flat-rate, but `sakana/fugu-subscription` publishes no connection — it sits+ // in the probe map as `client_model_selection_required`, so what the plan+ // serves is settled by this key's own `/v1/models`, not by the catalog.+ tier: "dynamic-subscription",name: "sakana-subscription",displayName: "Sakana Fugu Subscription",transport: "openai",@@ -1215,6 +1358,7 @@ export const BUILTIN_PROVIDERS: ProviderDefinition[] = [// Alibaba Token Plan: subscription credits on its own host and credential.{createHandler: anthropicCompatHandler,+ tier: "subscription",name: "qwen-token-plan",displayName: "Alibaba Token Plan",transport: "anthropic",@@ -1238,6 +1382,7 @@ export const BUILTIN_PROVIDERS: ProviderDefinition[] = [// Alibaba Coding Plan: request-based subscription on its own host and credential.{createHandler: anthropicCompatHandler,+ tier: "subscription",name: "qwen-coding",displayName: "Alibaba Coding Plan",transport: "anthropic",@@ -1260,6 +1405,7 @@ export const BUILTIN_PROVIDERS: ProviderDefinition[] = [// Alibaba PAYG: token-metered access on its own host and credential.{createHandler: anthropicCompatHandler,+ tier: "native",name: "qwen-payg",displayName: "Alibaba PAYG",transport: "anthropic",@@ -1282,6 +1428,12 @@ export const BUILTIN_PROVIDERS: ProviderDefinition[] = [// ── Qwen (auto-routed, no direct API) ──────────────────────────────{createHandler: openaiHandler,+ // The vendor's own namespace, so `native` — but unreachable as a gathered+ // candidate either way: it shares `qwen/dashscope-direct` with `qwen-payg`,+ // which `providerForCatalogRoute` returns first (earlier key), and it holds+ // no credential of its own for the credential filter to find. This entry+ // exists so a bare `qwen*` name has a provider to be steered FROM.+ tier: "native",name: "qwen",displayName: "Qwen",transport: "openai",@@ -1303,6 +1455,17 @@ export const BUILTIN_PROVIDERS: ProviderDefinition[] = ["virtual","No baseUrl. Exists only so nativeModelPatterns can steer a bare claude-* name to the native path."),+ // The route IS the Claude Code subscription — the catalog's+ // `anthropic/claude-code-subscription` profile — so `subscription` is the+ // only honest tier for it. Two things it does NOT mean, both of which this+ // project has been bitten by: it is not a billing statement (an explicit+ // ANTHROPIC_API_KEY reaches this same name and is metered, which is why+ // deriving `SUBSCRIPTION_PROVIDERS` from tier must exclude it alongside+ // `openai-codex`), and it is not a claim that this provider is routable —+ // `nativeRouteFor()` must intercept a bare Claude name BEFORE `route()`,+ // because there is no credential store here for the credential filter to+ // consult and the chain would degrade to OpenRouter.+ tier: "subscription",name: "native-anthropic",displayName: "Anthropic (Native)",transport: "anthropic",diff --git a/packages/cli/src/providers/route-candidates.ts b/packages/cli/src/providers/route-candidates.tsnew file mode 100644index 00000000..661ca3a8--- /dev/null+++ b/packages/cli/src/providers/route-candidates.ts@@ -0,0 +1,353 @@+/**+ * 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.+ *+ * 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:+ *+ * - the CREDENTIAL filter (`hasCredentialsForProvider` → the credential+ * authority) — no key, no candidate;+ * - the AVAILABILITY filter (`providerServesModel`, `model-availability.ts`) —+ * the account's own dynamic models catalog may DENY, and absence of evidence+ * never denies.+ *+ * So a candidate returned from here is a claim about what the CATALOG publishes,+ * not a claim that this user can call it. Re-asking either question here would+ * create a second oracle, and the pair would disagree the first time one changed.+ *+ * ── Why the catalog can be the only source ─────────────────────────────────+ *+ * Measured on generation `g-20260921062451697-f490edba` (1,123 entries):+ *+ * - `aggregators[]` carries SUBSCRIPTION routes alongside gateways and native+ * APIs — `moonshotai/kimi-code-subscription`, `openai/codex-subscription`,+ * `z-ai/glm-coding-subscription`, `qwen/qwencloud-token-plan`,+ * `opencode/go-subscription`. One source therefore covers every tier, and the+ * tier is the only thing that has to come from claudish's own table.+ * - The VENDOR needs no local table either: a connection whose+ * `route.routeId` equals the entry's `provider` IS the vendor's own route.+ * 412 of 1,123 models have one; the remaining 709 are served only by+ * gateways, which is a fact about those models rather than a gap. 100 entries+ * carry vendor `unknown` and simply get no vendor preference.+ * - 25 of the 28 published route pairs map to a claudish provider. The three+ * that do not are `qwen/realtime-websocket` (a WebSocket API with no chat+ * transport here), `openrouter/decisions` (output modality `["decisions"]`,+ * not chat) and `opencode/systemone` (a profile claudish has never seen).+ * Each is SKIPPED and counted in {@link CandidateGathering.unmappedRoutes} —+ * never guessed at, because a guessed route binding sends a request to the+ * wrong transport and reads as the model's failure.+ * - Of 1,734 mapped connections, 923 carry a usable price and 811 do not.+ * Unknown is a large minority, so the comparator must order it rather than+ * treat it as an edge case: it sorts LAST among its tier.+ *+ * ── The order ──────────────────────────────────────────────────────────────+ *+ * Decided by the project owner; {@link compareRouteCandidates} implements exactly+ * this and nothing else:+ *+ * user rules (elsewhere, verbatim, never merged with any of this)+ * then tier: subscription → dynamic-subscription → native → gateway → fallback+ * within a tier: the model's own vendor first+ * then cheapest by catalog price (unknown last)+ * then larger context window+ * then provider name, ascending, for determinism+ *+ * No local preference list, and NO LOCAL STATE. A spent subscription limit is+ * never remembered: the request moves to the next hop, which is the existing+ * chain's job. A module that remembered would answer differently on two+ * identical inputs, and the reason would live nowhere a user could see.+ */++import { type SlimModelEntry, readAllModelsCache } from "./all-models-cache.js";+import { externalIdFor, getCatalogEntries } from "./catalog-client.js";+import {+ type CatalogRouteBinding,+ catalogRouteForProvider,+ providerForCatalogRoute,+} from "./catalog-route-bindings.js";+import {+ type ConnectionPrice,+ compareByConnectionPrice,+ connectionPrice,+} from "./connection-price.js";+import { type RouteTier, getAllProviders, getProviderByName } from "./provider-definitions.js";++export type { RouteTier };++/** One way to call one model, with everything the order needs to place it. */+export interface RouteCandidate {+ /** claudish provider name. */+ provider: string;+ /** The exact id to send that provider. */+ wireId: string;+ tier: RouteTier;+ /** route.routeId === the catalog entry's `provider`: this vendor makes the model. */+ isVendorOwn: boolean;+ price: ConnectionPrice;+ /** Per-connection context window, when the catalog publishes one. */+ contextWindow?: number;+ source: "catalog-connection" | "namespace-claim";+}++export interface CandidateGathering {+ candidates: RouteCandidate[];+ /** Mapped connections skipped because their route resolves to no claudish provider. */+ unmappedRoutes: string[];+ /** True when no catalog entry matched the name at all. */+ catalogMiss: boolean;+}++/**+ * Tier precedence, as a total map rather than a list.+ *+ * `Record<RouteTier, number>` is exhaustive by construction: adding a sixth tier+ * to the union stops this file compiling, which is the only way to be sure a new+ * tier gets a deliberate position instead of silently sorting as `undefined`.+ */+const TIER_RANK: Record<RouteTier, number> = {+ subscription: 0,+ "dynamic-subscription": 1,+ native: 2,+ gateway: 3,+ fallback: 4,+};++/** `routeId/routeProfileId`, the spelling the backend contract and the reports use. */+function routeLabel(route: CatalogRouteBinding | undefined): string {+ return route ? `${route.routeId}/${route.routeProfileId}` : "(no route)";+}++/**+ * The catalog entry for a requested name, or `undefined`.+ *+ * Canonical model id first, then alias — the order `resolveExternalId` already+ * uses, so both paths agree about which entry a name denotes. The+ * case-insensitive passes come last and exist because users paste ids from vendor+ * docs (`MiniMax-M3`) while the catalog is lowercase; `matchRoutingRule` lowers+ * for the same reason. Exact always wins, so a case-folded collision can never+ * displace a real id.+ */+function findCatalogEntry(entries: SlimModelEntry[], model: string): SlimModelEntry | undefined {+ const exact = entries.find((entry) => entry.modelId === model);+ if (exact) return exact;+ const byAlias = entries.find((entry) => entry.aliases.includes(model));+ if (byAlias) return byAlias;++ const lowered = model.toLowerCase();+ const loweredId = entries.find((entry) => entry.modelId.toLowerCase() === lowered);+ if (loweredId) return loweredId;+ return entries.find((entry) => entry.aliases.some((alias) => alias.toLowerCase() === lowered));+}++/**+ * Candidates from the catalog's own connections — the primary source.+ *+ * Every skip below is deliberate and each has a different reason:+ *+ * - a route that binds to no claudish provider is COUNTED (`unmappedRoutes`),+ * because "the catalog grew a route we cannot execute" is a fact the next+ * contract review needs, not noise;+ * - a provider name with no DEFINITION in this process is counted the same way.+ * That is how `together-ai/gateway` and `fireworks/gateway` read when the+ * bundled endpoint catalog has not registered them — which happens exactly+ * when the user holds no key for them, so the credential filter would have+ * dropped the candidate anyway;+ * - a connection whose own `externalModelId` is not the id+ * {@link externalIdFor} chose for its provider is skipped SILENTLY: another+ * connection of the same provider carries the chosen id, and this one is the+ * moving pointer beside it. Reading price and context window from the row+ * that actually carries the wire id is the whole point of the check;+ * - `externalIdFor` returning null means every id this provider publishes for+ * the model is a moving pointer. Its rule — never send a pointer the user did+ * not ask for — is the one claudish already applies everywhere, so there is+ * no honest id to send and no candidate.+ */+function gatherFromConnections(+ entry: SlimModelEntry,+ candidates: RouteCandidate[],+ unmappedRoutes: Set<string>+): void {+ 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) {+ unmappedRoutes.add(routeLabel(connection.route));+ continue;+ }++ 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",+ });+ }+}++/**+ * The vendor that MAKES the model is the vendor whose own route this is.+ *+ * False with no entry and false for the 100 entries whose vendor is `unknown`:+ * both are an absence of evidence, and this flag's only job is to promote a+ * candidate, so an absence must never promote one.+ */+function isVendorOwnRoute(+ route: CatalogRouteBinding | undefined,+ entry: SlimModelEntry | undefined+): boolean {+ return route !== undefined && entry?.provider !== undefined && route.routeId === entry.provider;+}++/**+ * Candidates from a provider's NAMESPACE CLAIM — dynamic subscriptions only.+ *+ * A dynamic subscription publishes no connection at all, because the ACCOUNT+ * selects what it serves: `antigravity`, `grok-subscription`, `devin` and+ * `sakana-subscription` sit in the probe map as+ * `client_model_selection_required`. The catalog cannot say what a seat was+ * given, so without this source a user's flat-rate plan would be invisible to+ * every gathered chain and the request would land on a metered hop — the one+ * ordering error that costs money rather than a better option.+ *+ * A claim is NOT evidence of service, and that asymmetry is the whole design:+ * the candidate exists so the AVAILABILITY filter can ask the account's own+ * dynamic models catalog, which is the only thing that can answer. Extending+ * this to any other tier would invent routes — a gateway's `nativeModelPatterns`+ * would claim every model in a namespace it may not carry, and nothing+ * 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.+ */+function gatherFromNamespaceClaims(+ model: string,+ entry: SlimModelEntry | undefined,+ candidates: RouteCandidate[]+): void {+ for (const def of getAllProviders()) {+ if (def.tier !== "dynamic-subscription") continue;+ if (!def.nativeModelPatterns?.some(({ pattern }) => pattern.test(model))) continue;++ candidates.push({+ provider: def.name,+ // The requested name verbatim. There is no catalog connection to read a+ // wire id from, and the transport resolves the account's own id itself.+ wireId: model,+ tier: def.tier,+ // Same rule as a connection's, asked of the provider's own binding: the+ // claim has no route of its own to compare.+ isVendorOwn: isVendorOwnRoute(catalogRouteForProvider(def.name), entry),+ // Unknown, and unknowable here: a flat-rate plan publishes no per-token+ // rate, and `connectionPrice` is the only thing allowed to say what a+ // missing price is.+ price: connectionPrice(undefined),+ // No context window either: a plan's window varies by tier and comes from+ // the account's own discovery (see `modelDiscovery`).+ source: "namespace-claim",+ });+ }+}++/**+ * Ascending: the candidate a request should be sent to comes first.+ *+ * Exported separately from {@link gatherRouteCandidates} so the order can be+ * tested on constructed candidates, without a catalog — the two halves fail for+ * different reasons and a test that could only reach the sort through a cache+ * file would attribute a gathering bug to the order.+ *+ * Total, not merely consistent: `(provider, wireId)` is unique after deduping, so+ * the last two keys guarantee one fixed answer for any input permutation. A+ * routing order that depended on the catalog's row order would change under a+ * backend re-publish with nothing in claudish having changed.+ */+export function compareRouteCandidates(a: RouteCandidate, b: RouteCandidate): number {+ const byTier = TIER_RANK[a.tier] - TIER_RANK[b.tier];+ if (byTier !== 0) return byTier;++ // The vendor's own route, before anyone reselling it.+ if (a.isVendorOwn !== b.isVendorOwn) return a.isVendorOwn ? -1 : 1;++ const byPrice = compareByConnectionPrice(a.price, b.price);+ if (byPrice !== 0) return byPrice;++ // Larger window first; an unpublished window sorts last, for the same reason an+ // unknown price does — a missing number is not a small number.+ const byContext = (b.contextWindow ?? -1) - (a.contextWindow ?? -1);+ if (byContext !== 0) return byContext;++ if (a.provider !== b.provider) return a.provider < b.provider ? -1 : 1;+ if (a.wireId !== b.wireId) return a.wireId < b.wireId ? -1 : 1;+ return 0;+}++/**+ * Every candidate for one model name, ordered.+ *+ * `cachePath` reads one specific catalog file instead of the process's own+ * snapshot — the seam every routing function already offers so a test can pin a+ * generation rather than depend on whatever the machine last refreshed.+ *+ * With no readable catalog and no namespace claim the answer is an EMPTY list and+ * `catalogMiss: true`. Not a guessed id, and not an invented gateway: the project+ * owner's rule is that with no catalog claudish serves local providers and+ * explicit `provider@model` specs only. Inventing `openrouter@<name>` here would+ * send a name nobody published to a metered gateway and bill for the 404.+ */+export function gatherRouteCandidates(model: string, cachePath?: string): CandidateGathering {+ const entries = cachePath ? readAllModelsCache(cachePath)?.entries : getCatalogEntries();+ const entry = entries ? findCatalogEntry(entries, model) : undefined;++ const gathered: RouteCandidate[] = [];+ const unmappedRoutes = new Set<string>();++ // Source order is the dedupe rule: a real catalog connection beats a namespace+ // claim for the same (provider, wireId), because it carries a price and a+ // window the claim cannot know.+ if (entry) gatherFromConnections(entry, gathered, unmappedRoutes);+ gatherFromNamespaceClaims(model, entry, gathered);++ const seen = new Set<string>();+ const candidates = gathered.filter((candidate) => {+ // JSON, not a delimiter: an injective key is the whole requirement, and any+ // literal separator is a guess about what a wire id cannot contain. This line+ // briefly held a raw NUL byte, which made `file(1)` report the module as+ // binary and grep stop matching it — the trap `devin.ts` hit once before.+ const key = JSON.stringify([candidate.provider, candidate.wireId]);+ if (seen.has(key)) return false;+ seen.add(key);+ return true;+ });+ candidates.sort(compareRouteCandidates);++ return {+ candidates,+ unmappedRoutes: [...unmappedRoutes],+ catalogMiss: entry === undefined,+ };+}diff --git a/scripts/route-candidates-preview.ts b/scripts/route-candidates-preview.tsnew file mode 100644index 00000000..448a788b--- /dev/null+++ b/scripts/route-candidates-preview.ts@@ -0,0 +1,123 @@+#!/usr/bin/env bun+/**+ * What the routing redesign WOULD do, without doing it.+ *+ * Phase 2A builds candidate gathering as a pure module that nothing calls. This+ * script calls it for every model in the cloud models catalog and compares the+ * result against the chain `route()` produces today, so the redesign can be+ * judged before it is wired in rather than after.+ *+ * It answers the only question that blocks the wiring: which models would LOSE a+ * provider they can reach today. A gain is a decision to review; a loss is a user+ * whose key stops working, with no error to read.+ *+ * bun run scripts/route-candidates-preview.ts [--limit=N] [--show=modelId]+ *+ * Read-only: it resolves routes and gathers candidates, and writes nothing.+ */++import { readAllModelsCache } from "../packages/cli/src/providers/all-models-cache.js";+import { ensureEndpointsRegistered } from "../packages/cli/src/providers/endpoint-registration.js";+import { gatherRouteCandidates } from "../packages/cli/src/providers/route-candidates.js";+import { route } from "../packages/cli/src/providers/routing-rules.js";++// MANDATORY before gathering. Bundled and user endpoints (together, fireworks,+// and every predefined row) only acquire a provider definition once this runs, and+// a provider with no definition has no tier, so it is dropped as unmappable. Left+// out, this script reports 241 together-ai connections as unroutable and blames the+// redesign for a loss it did not cause.+await ensureEndpointsRegistered();++const cache = readAllModelsCache();+if (!cache || cache.entries.length === 0) {+ console.error("No cloud models catalog cache. Refresh it first.");+ process.exit(1);+}++const limitArg = process.argv.find((arg) => arg.startsWith("--limit="));+const showArg = process.argv.find((arg) => arg.startsWith("--show="));+const limit = limitArg ? Number(limitArg.split("=")[1]) : undefined;+const show = showArg?.split("=")[1];++const entries = limit ? cache.entries.slice(0, limit) : cache.entries;++/** Providers the candidate list offers but today's chain does not, and the reverse. */+const gainedBy = new Map<string, number>();+const lostBy = new Map<string, number>();+const lostExamples: string[] = [];+let identical = 0;+let reordered = 0;+let candidateEmpty = 0;+const unmappedRoutes = new Map<string, number>();++for (const entry of entries) {+ const plan = await route(entry.modelId);+ const todayProviders =+ plan.kind === "ok" ? [plan.primary, ...plan.fallbacks].map((hop) => hop.provider) : [];++ const gathering = gatherRouteCandidates(entry.modelId);+ for (const unmapped of gathering.unmappedRoutes) {+ unmappedRoutes.set(unmapped, (unmappedRoutes.get(unmapped) ?? 0) + 1);+ }+ const tomorrowProviders = gathering.candidates.map((candidate) => candidate.provider);++ if (tomorrowProviders.length === 0) candidateEmpty++;++ const todaySet = new Set(todayProviders);+ const tomorrowSet = new Set(tomorrowProviders);+ const lost = todayProviders.filter((provider) => !tomorrowSet.has(provider));+ const gained = tomorrowProviders.filter((provider) => !todaySet.has(provider));++ for (const provider of lost) lostBy.set(provider, (lostBy.get(provider) ?? 0) + 1);+ for (const provider of gained) gainedBy.set(provider, (gainedBy.get(provider) ?? 0) + 1);++ if (lost.length > 0 && lostExamples.length < 25) {+ lostExamples.push(+ `${entry.modelId}: today ${todayProviders.join(" -> ")}\n candidates ${tomorrowProviders.join(" -> ")}`,+ );+ }+ if (lost.length === 0 && gained.length === 0) {+ if (todayProviders.join("|") === tomorrowProviders.join("|")) identical++;+ else reordered++;+ }++ if (show && entry.modelId === show) {+ console.log(`\n=== ${entry.modelId} (vendor ${entry.provider ?? "unknown"}) ===`);+ console.log(`today: ${todayProviders.join(" -> ") || "(no route)"}`);+ console.log("candidates:");+ for (const candidate of gathering.candidates) {+ console.log(+ ` ${candidate.tier.padEnd(21)} ${candidate.provider.padEnd(18)} ${candidate.wireId.padEnd(34)} ` ++ `${candidate.isVendorOwn ? "vendor" : " "} ${candidate.price.label.padEnd(22)} ` ++ `ctx ${candidate.contextWindow ?? "-"} ${candidate.source}`,+ );+ }+ }+}++console.log(`\nCompared ${entries.length} models on generation ${cache.catalogGenerationId}.`);+console.log(` identical provider sets, same order: ${identical}`);+console.log(` identical set, different order: ${reordered}`);+console.log(` no candidates gathered at all: ${candidateEmpty}`);++const table = (title: string, counts: Map<string, number>): void => {+ console.log(`\n## ${title}`);+ const rows = [...counts].sort((a, b) => b[1] - a[1]);+ if (rows.length === 0) console.log(" none");+ for (const [provider, count] of rows) console.log(` ${provider.padEnd(22)} ${count} models`);+};++table("Providers GAINED (reachable by bare name that are not today)", gainedBy);+table("Providers LOST (reachable today, absent from candidates) — must be justified", lostBy);++if (lostExamples.length > 0) {+ console.log(`\n## Loss examples (first ${lostExamples.length})`);+ for (const example of lostExamples) console.log(` ${example}`);+}++if (unmappedRoutes.size > 0) {+ console.log("\n## Catalog routes that resolve to no claudish provider");+ for (const [route_, count] of [...unmappedRoutes].sort((a, b) => b[1] - a[1])) {+ console.log(` ${route_.padEnd(38)} ${count} connections`);+ }+}