Skip to content

Claude Code. Any Model. The most powerful AI coding agent now speaks every language.

test: rewrite routing's tests for the catalog-gathered chain

Jack Rudenko6db419d9787c
diff --git a/packages/cli/src/auth/credentials/types.test.ts b/packages/cli/src/auth/credentials/types.test.ts
new file mode 100644
index 00000000..a77507b0
--- /dev/null
+++ b/packages/cli/src/auth/credentials/types.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, test } from "bun:test";
+import { redactSecrets } from "./types.js";
+
+describe("credential readiness redaction", () => {
+ test("redacts a Google key carried in a URL query parameter", () => {
+ const secret = "AIzaSyD-1234567890abcdefghijklmnopqrs";
+ const output = redactSecrets(`request failed: https://example.test/models?key=${secret}`);
+
+ expect(output).toBe("request failed: https://example.test/models?key=[redacted]");
+ expect(output).not.toContain(secret);
+ });
+
+ test("redacts a bearer token while retaining the authentication scheme", () => {
+ const secret = "eyJhbGciOiJIUzI1NiJ9.fake-token-signature";
+ const output = redactSecrets(`Authorization: Bearer ${secret}`);
+
+ expect(output).toBe("Authorization: Bearer [redacted]");
+ expect(output).not.toContain(secret);
+ });
+
+ // Synthetic values only, and deliberately NOT in each vendor's real token
+ // shape. A fixture that mimics the real layout (Slack's `xoxb-<digits>-<alnum>`
+ // was the one that did) trips GitHub's push protection and blocks the release,
+ // even though nothing here is a live credential. These still exercise the
+ // regexes, which only require the prefix plus a run of allowed characters.
+ test.each([
+ ["sk-", "sk-EXAMPLEFAKEVALUENOTREAL"],
+ ["ghp_", "ghp_EXAMPLEFAKEVALUENOTREALabcdefghij"],
+ ["xoxb-", "xoxb-EXAMPLE-FAKE-VALUE-NOT-REAL"],
+ ])("retains the %s credential prefix while removing its secret", (prefix, secret) => {
+ const output = redactSecrets(`credential ${secret} failed`);
+
+ expect(output).toContain(`${prefix}[redacted]`);
+ expect(output).not.toContain(secret);
+ });
+
+ test("leaves a request id, model id, and plain diagnostic unchanged", () => {
+ const input =
+ "request req_01JZ8M6Y7Q2K9V4W3X1C failed for model gemini-3.8-flash: quota exhausted";
+
+ expect(redactSecrets(input)).toBe(input);
+ });
+});
diff --git a/packages/cli/src/handlers/default-provider-e2e.test.ts b/packages/cli/src/handlers/default-provider-e2e.test.ts
index bece6fa2..2725ddeb 100644
--- a/packages/cli/src/handlers/default-provider-e2e.test.ts
+++ b/packages/cli/src/handlers/default-provider-e2e.test.ts
@@ -288,19 +288,16 @@ const HAS_XAI = SKIP_LIVE_E2E ? false : await hasCredential("x-ai");
describe("Group B — real API routing", () => {
test.skipIf(!HAS_OR)(
- "B1a — defaultProvider=openrouter + gpt-5.4 bare → served by OpenRouter",
+ "B1a — catalog-gathered gpt-5.4 bare → served by credentialed OpenRouter",
async () => {
- // Pin routing for `gpt-*` to skip codex (commit 5: DEFAULT_ROUTING_RULES
- // puts openai-codex first for `gpt-*`, which can fire on dev boxes that
- // happen to have a codex OAuth file. The intent of this test is the
- // openrouter default-provider path, so we override the gpt-* chain to
- // exclude codex.)
+ // No user rule: the chain must come from the cloud models catalog. The
+ // gpt-5.4 row publishes OpenRouter, so defaultProvider is deduplicated
+ // rather than manufacturing a second connection.
sandboxHome({
version: "1.0.0",
defaultProfile: "default",
profiles: {},
defaultProvider: "openrouter",
- routing: { "gpt-*": ["openai", "openrouter"] },
});
captureStderr();
const t0 = Date.now();
@@ -328,7 +325,7 @@ describe("Group B — real API routing", () => {
// The proxy emits its `[Route] N providers for <model>: A → B` line ONLY
// when the credential-filtered chain has MORE THAN ONE candidate
// (proxy-server.ts: `if (!options.quiet && candidates.length > 1)`). The
- // chain pinned above is ["openai","openrouter"], so on a machine WITHOUT
+ // gathered chain includes OpenAI and OpenRouter, so on a machine WITHOUT
// an OpenAI credential it filters down to a single candidate and NO line
// is emitted — which is the common case for someone holding only an
// OpenRouter key. A bare `expect(stderr).toContain("openrouter")` therefore
@@ -401,7 +398,7 @@ describe("Group B — real API routing", () => {
);
test.skipIf(!HAS_LL)(
- "B2 — defaultProvider=litellm + minimax-m2.5 bare → served by LiteLLM first",
+ "B2 — defaultProvider=litellm + minimax-m2.5 bare → LiteLLM remains the fallback",
async () => {
sandboxHome({
version: "1.0.0",
@@ -429,10 +426,9 @@ describe("Group B — real API routing", () => {
`[B2] model=minimax-m2.5 ok=${ok} elapsed=${elapsed}ms litellm@${llIdx} openrouter@${orIdx} textLen=${text.length}`
);
expect(ok).toBe(true);
- // Proof LiteLLM came first when both are visible in stderr
- if (llIdx >= 0 && orIdx >= 0) {
- expect(llIdx).toBeLessThan(orIdx);
- }
+ // `defaultProvider` is the last-resort fallback position. If both names
+ // are visible, the catalog-gathered OpenRouter connection must precede it.
+ if (llIdx >= 0 && orIdx >= 0) expect(orIdx).toBeLessThan(llIdx);
},
90_000
);
@@ -564,7 +560,6 @@ describe("Group C — custom endpoint registration", () => {
test.skipIf(!HAS_OR)(
"C2 — invalid custom endpoint is warned but bare call still succeeds",
async () => {
- // Pin routing for `gpt-*` to skip codex (see B1a comment).
sandboxHome({
version: "1.0.0",
defaultProfile: "default",
@@ -584,7 +579,6 @@ describe("Group C — custom endpoint registration", () => {
},
},
defaultProvider: "openrouter",
- routing: { "gpt-*": ["openai", "openrouter"] },
});
captureStderr();
diff --git a/packages/cli/src/handlers/fallback-handler.test.ts b/packages/cli/src/handlers/fallback-handler.test.ts
index 357b65e4..0cbcbc98 100644
--- a/packages/cli/src/handlers/fallback-handler.test.ts
+++ b/packages/cli/src/handlers/fallback-handler.test.ts
@@ -173,9 +173,9 @@ function hasAnyCredentials(): boolean {
// ---------------------------------------------------------------------------
// (Group 1 — unit tests of getFallbackChain — removed in commit 5 of the
// model-catalog and routing redesign. The fallback chain construction logic
-// moved from auto-route.ts (now ~50 lines) into routing-rules.ts route()
-// + DEFAULT_ROUTING_RULES. Equivalent matrix coverage lives in
-// providers/routing-rules.test.ts and providers/default-routing-rules.test.ts.)
+// moved from auto-route.ts (now ~50 lines) into routing-rules.ts route().
+// Equivalent matrix coverage lives in providers/routing-rules.test.ts and
+// providers/route-candidates.test.ts.)
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
diff --git a/packages/cli/src/providers/default-routing-rules.test.ts b/packages/cli/src/providers/default-routing-rules.test.ts
deleted file mode 100644
index ad3ba4b3..00000000
--- a/packages/cli/src/providers/default-routing-rules.test.ts
+++ /dev/null
@@ -1,413 +0,0 @@
-import { catalogRouteForProvider } from "./catalog-route-bindings.js";
-/**
- * Unit tests for providers/default-routing-rules.ts
- *
- * Verifies that the shipped DEFAULT_ROUTING_RULES table:
- * - matches the patterns the migration plan §B.1 documents,
- * - feeds correctly through matchRoutingRule + buildRoutingChain,
- * - validates cleanly against provider-definitions.ts.
- *
- * These tests do not touch the disk or env — pure data assertions.
- *
- * Run: bun test packages/cli/src/providers/default-routing-rules.test.ts
- */
-
-import { describe, expect, test } from "bun:test";
-import { mkdtempSync, rmSync } from "node:fs";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import { type DiskCacheV3, writeAllModelsCache } from "./all-models-cache.js";
-import {
- DEFAULT_ROUTING_RULES,
- validateDefaultRoutingRules,
- validateRoutingRulesAgainstProviders,
-} from "./default-routing-rules.js";
-import { parseModelSpec } from "./model-parser.js";
-import { buildRoutingChain, matchRoutingRule } from "./routing-rules.js";
-
-function makeTempCatalog(
- model: {
- modelId: string;
- externalId?: string;
- subscriptionPlanIds?: string[];
- },
- /** Plan names to mark as active subscription plans in the catalog (defaults to the model's own plans). */
- plans: string[] = model.subscriptionPlanIds ?? [],
- routingProviderByPlan: Record<string, string> = {}
-): { path: string; cleanup: () => void } {
- const dir = mkdtempSync(join(tmpdir(), "claudish-routing-test-"));
- const path = join(dir, "all-models.json");
- const entries: DiskCacheV3["entries"] = [];
-
- // Plan-owner entries: a provider is only treated as a subscription plan if
- // some catalog entry lists it in subscriptionPlanIds[]. Add markers so tests can
- // model the "model is not in this plan" drop path without duplicating real
- // plan members.
- for (const plan of plans) {
- entries.push({
- modelId: `${plan}-plan-marker`,
- aliases: [],
-
- subscriptionPlanIds: [plan],
- aggregators: [
- {
- sourceCollectorId: "test",
- routeStatus: "mapped",
- route: catalogRouteForProvider(plan),
- sourceProviderId: plan,
- externalModelId: "any",
- confidence: "scrape_verified" as const,
- },
- ],
- });
- }
-
- entries.push({
- modelId: model.modelId,
- aliases: [],
-
- subscriptionPlanIds: model.subscriptionPlanIds ?? [],
- aggregators:
- model.externalId && model.subscriptionPlanIds
- ? model.subscriptionPlanIds.map((planId) => ({
- sourceProviderId: routingProviderByPlan[planId] ?? planId,
- sourceCollectorId: "test",
- routeStatus: "mapped" as const,
- route: catalogRouteForProvider(routingProviderByPlan[planId] ?? planId),
- externalModelId: model.externalId!,
- confidence: "scrape_verified" as const,
- }))
- : undefined,
- });
-
- const cache: DiskCacheV3 = {
- catalogGenerationId: "test-generation",
- version: 3,
- lastUpdated: new Date().toISOString(),
- entries,
- models: [],
- plans: plans.map((plan) => ({
- id: plan,
- modelDiscovery: "catalog",
- routeStatus: "supported",
- route: catalogRouteForProvider(routingProviderByPlan[plan] ?? plan),
- })),
- };
- writeAllModelsCache(cache, path);
- return { path, cleanup: () => rmSync(dir, { recursive: true, force: true }) };
-}
-
-// ---------------------------------------------------------------------------
-// Pattern matching against the shipped rules
-// ---------------------------------------------------------------------------
-
-describe("DEFAULT_ROUTING_RULES pattern matching", () => {
- test("'claude-opus-4-7' matches claude-* → [native-anthropic, openrouter]", () => {
- const matched = matchRoutingRule("claude-opus-4-7", DEFAULT_ROUTING_RULES);
- expect(matched).toEqual(["native-anthropic", "openrouter"]);
- });
-
- test("'gpt-5' matches gpt-* → [openai-codex, openai, openrouter]", () => {
- const matched = matchRoutingRule("gpt-5", DEFAULT_ROUTING_RULES);
- expect(matched).toEqual(["openai-codex", "openai", "openrouter"]);
- });
-
- test("'o1-mini' matches o1-* → [openai-codex, openai, openrouter]", () => {
- const matched = matchRoutingRule("o1-mini", DEFAULT_ROUTING_RULES);
- expect(matched).toEqual(["openai-codex", "openai", "openrouter"]);
- });
-
- test("'o3-pro' matches o3-* → [openai-codex, openai, openrouter]", () => {
- const matched = matchRoutingRule("o3-pro", DEFAULT_ROUTING_RULES);
- expect(matched).toEqual(["openai-codex", "openai", "openrouter"]);
- });
-
- test("'gemini-2.0-flash' matches gemini-* → [antigravity, google, openrouter]", () => {
- const matched = matchRoutingRule("gemini-2.0-flash", DEFAULT_ROUTING_RULES);
- expect(matched).toEqual(["antigravity", "google", "openrouter"]);
- });
-
- test("'grok-4' puts Grok subscription before metered x-ai to avoid silent per-token billing", () => {
- const matched = matchRoutingRule("grok-4", DEFAULT_ROUTING_RULES);
- // With both a Grok subscription and XAI_API_KEY present, the subscription must win.
- expect(matched).toEqual(["grok-subscription", "x-ai", "openrouter"]);
- });
-
- test("grok-subscription routing emits an explicit parser round-trip", () => {
- const { path, cleanup } = makeTempCatalog({
- modelId: "grok-4.6",
- externalId: "grok-4.6",
- subscriptionPlanIds: ["grok-subscription"],
- });
- try {
- const [route] = buildRoutingChain(["grok-subscription"], "grok-4.6", path);
- const parsed = parseModelSpec(route.modelSpec);
-
- // Losing explicitness would let the bare Grok id fall back to metered x-ai detection.
- expect(route.modelSpec).toBe("[email protected]");
- expect(parsed.provider).toBe("grok-subscription");
- expect(parsed.isExplicitProvider).toBe(true);
- } finally {
- cleanup();
- }
- });
-
- test("'kimi-k2.5' matches kimi-* → [kimi-coding, opencode-zen-go, kimi, openrouter] (no pinned model)", () => {
- const matched = matchRoutingRule("kimi-k2.5", DEFAULT_ROUTING_RULES);
- expect(matched).toEqual(["kimi-coding", "opencode-zen-go", "kimi", "openrouter"]);
- });
-
- test("kimi-coding candidate drops when model is not in its subscription plan", () => {
- const { path, cleanup } = makeTempCatalog(
- {
- modelId: "kimi-k2.5",
- // kimi-k2.5 is not part of the kimi-coding subscription plan in this
- // catalog snapshot, so the subscription candidate is dropped rather than
- // being silently answered by a different model.
- },
- ["kimi-coding"]
- );
- try {
- const matched = matchRoutingRule("kimi-k2.5", DEFAULT_ROUTING_RULES);
- expect(matched).not.toBeNull();
- const routes = buildRoutingChain(matched!, "kimi-k2.5", path);
- expect(routes).toHaveLength(3);
- // kimi-coding is dropped because the plan doesn't serve this model
- expect(routes.map((route) => route.provider)).not.toContain("kimi-coding");
- expect(routes[0].provider).toBe("opencode-zen-go");
- expect(routes[0].modelSpec).toBe("[email protected]");
- expect(routes[1].provider).toBe("kimi");
- expect(routes[1].modelSpec).toBe("[email protected]");
- expect(routes[2].provider).toBe("openrouter");
- } finally {
- cleanup();
- }
- });
-
- test("kimi-coding candidate translates K3 to the plan's wire id", () => {
- const { path, cleanup } = makeTempCatalog(
- {
- modelId: "kimi-k3",
- externalId: "k3",
- subscriptionPlanIds: ["kimi-coding"],
- },
- ["kimi-coding"]
- );
- try {
- const matched = matchRoutingRule("kimi-k3", DEFAULT_ROUTING_RULES);
- expect(matched).not.toBeNull();
- const routes = buildRoutingChain(matched!, "kimi-k3", path);
- expect(routes).toHaveLength(4);
- // catalog translates the subscription model to its wire id
- expect(routes[0].provider).toBe("kimi-coding");
- expect(routes[0].modelSpec).toBe("kc@k3");
- expect(routes[1].provider).toBe("opencode-zen-go");
- expect(routes[1].modelSpec).toBe("zengo@kimi-k3");
- expect(routes[2].provider).toBe("kimi");
- expect(routes[2].modelSpec).toBe("kimi@kimi-k3");
- } finally {
- cleanup();
- }
- });
-
- test("k3 bare name matches k3* rule and uses the plan wire id", () => {
- const { path, cleanup } = makeTempCatalog(
- {
- modelId: "kimi-k3",
- externalId: "k3",
- subscriptionPlanIds: ["kimi-coding"],
- },
- ["kimi-coding"]
- );
- try {
- // bare `k3` doesn't match `kimi-*`, so the dedicated `k3*` rule handles it
- const matched = matchRoutingRule("k3", DEFAULT_ROUTING_RULES);
- expect(matched).toEqual(["kimi-coding", "opencode-zen-go", "kimi", "openrouter"]);
- const routes = buildRoutingChain(matched!, "k3", path);
- expect(routes).toHaveLength(4);
- expect(routes[0].provider).toBe("kimi-coding");
- expect(routes[0].modelSpec).toBe("kc@k3");
- expect(routes[1].provider).toBe("opencode-zen-go");
- expect(routes[1].modelSpec).toBe("zengo@k3");
- expect(routes[2].provider).toBe("kimi");
- expect(routes[2].modelSpec).toBe("kimi@k3");
- } finally {
- cleanup();
- }
- });
-
- test("'minimax-m2.5' matches minimax-* → [minimax-coding, opencode-zen-go, minimax, openrouter]", () => {
- const matched = matchRoutingRule("minimax-m2.5", DEFAULT_ROUTING_RULES);
- expect(matched).toEqual(["minimax-coding", "opencode-zen-go", "minimax", "openrouter"]);
- });
-
- // Case-insensitive matching: docs use mixed casing (`MiniMax-M2.5`,
- // `GPT-4o`); the rule keys are lowercase but matchRoutingRule lowers both
- // sides before comparing.
- test("'MiniMax-M2.5' matches minimax-* (case-insensitive) → [minimax-coding, opencode-zen-go, minimax, openrouter]", () => {
- const matched = matchRoutingRule("MiniMax-M2.5", DEFAULT_ROUTING_RULES);
- expect(matched).toEqual(["minimax-coding", "opencode-zen-go", "minimax", "openrouter"]);
- });
-
- test("'GPT-4o' matches gpt-* (case-insensitive) → [openai-codex, openai, openrouter]", () => {
- const matched = matchRoutingRule("GPT-4o", DEFAULT_ROUTING_RULES);
- expect(matched).toEqual(["openai-codex", "openai", "openrouter"]);
- });
-
- test("'Gemini-2.5-Pro' matches gemini-* (case-insensitive) → [antigravity, google, openrouter]", () => {
- const matched = matchRoutingRule("Gemini-2.5-Pro", DEFAULT_ROUTING_RULES);
- expect(matched).toEqual(["antigravity", "google", "openrouter"]);
- });
-
- test("'glm-4.6' matches glm-* → [glm-coding, opencode-zen-go, glm, openrouter]", () => {
- const matched = matchRoutingRule("glm-4.6", DEFAULT_ROUTING_RULES);
- expect(matched).toEqual(["glm-coding", "opencode-zen-go", "glm", "openrouter"]);
- });
-
- test("'qwen3.7-plus' offers both Alibaba subscriptions before PAYG", () => {
- const matched = matchRoutingRule("qwen3.7-plus", DEFAULT_ROUTING_RULES);
- expect(matched).toEqual([
- "qwen-coding",
- "qwen-token-plan",
- "opencode-zen-go",
- "qwen-payg",
- "openrouter",
- ]);
- });
-
- test("'qwen3-coder-next' offers the Coding Plan before PAYG", () => {
- const matched = matchRoutingRule("qwen3-coder-next", DEFAULT_ROUTING_RULES);
- expect(matched).toEqual([
- "qwen-coding",
- "qwen-token-plan",
- "opencode-zen-go",
- "qwen-payg",
- "openrouter",
- ]);
- });
-
- test("cross-vendor default chains never include qwen-token-plan", () => {
- for (const model of ["glm-4.6", "glm-5.2", "deepseek-v4-pro"]) {
- const matched = matchRoutingRule(model, DEFAULT_ROUTING_RULES);
- expect(matched).not.toBeNull();
- expect(matched!).not.toContain("qwen-token-plan");
- }
- });
-
- test("'z-ai-glm-4.6' matches z-ai-* → [z-ai, openrouter]", () => {
- const matched = matchRoutingRule("z-ai-glm-4.6", DEFAULT_ROUTING_RULES);
- expect(matched).toEqual(["z-ai", "openrouter"]);
- });
-
- test("'deepseek-v3.5' matches deepseek-* → [opencode-zen-go, deepseek, openrouter]", () => {
- const matched = matchRoutingRule("deepseek-v3.5", DEFAULT_ROUTING_RULES);
- expect(matched).toEqual(["opencode-zen-go", "deepseek", "openrouter"]);
- });
-
- test("'mimo-v2-pro' matches mimo-* → [opencode-zen-go, openrouter]", () => {
- const matched = matchRoutingRule("mimo-v2-pro", DEFAULT_ROUTING_RULES);
- expect(matched).toEqual(["opencode-zen-go", "openrouter"]);
- });
-
- test("hy3* matches both 'hy3' and 'hy3-preview' → [opencode-zen-go, openrouter]", () => {
- expect(matchRoutingRule("hy3", DEFAULT_ROUTING_RULES)).toEqual([
- "opencode-zen-go",
- "openrouter",
- ]);
- expect(matchRoutingRule("hy3-preview", DEFAULT_ROUTING_RULES)).toEqual([
- "opencode-zen-go",
- "openrouter",
- ]);
- });
-
- test("gpt-* and grok-* deliberately exclude opencode-zen-go", () => {
- for (const model of ["gpt-5", "grok-4"]) {
- const matched = matchRoutingRule(model, DEFAULT_ROUTING_RULES);
- expect(matched).not.toBeNull();
- expect(matched!).not.toContain("opencode-zen-go");
- }
- });
-
- test("'fugu' matches the exact fugu rule → [sakana-subscription, sakana] (no openrouter)", () => {
- const matched = matchRoutingRule("fugu", DEFAULT_ROUTING_RULES);
- expect(matched).toEqual(["sakana-subscription", "sakana"]);
- });
-
- test("'fugu-ultra' matches fugu-* → [sakana-subscription, sakana] (no openrouter)", () => {
- const matched = matchRoutingRule("fugu-ultra", DEFAULT_ROUTING_RULES);
- expect(matched).toEqual(["sakana-subscription", "sakana"]);
- });
-
- test("'something-zen' matches *-zen → [opencode-zen]", () => {
- const matched = matchRoutingRule("something-zen", DEFAULT_ROUTING_RULES);
- expect(matched).toEqual(["opencode-zen"]);
- });
-
- test("'random-unknown-model' falls through to '*' → [openrouter]", () => {
- const matched = matchRoutingRule("random-unknown-model", DEFAULT_ROUTING_RULES);
- expect(matched).toEqual(["openrouter"]);
- });
-});
-
-// ---------------------------------------------------------------------------
-// Validator
-// ---------------------------------------------------------------------------
-
-describe("validateDefaultRoutingRules", () => {
- test("does NOT throw with the shipped rules", () => {
- expect(() => validateDefaultRoutingRules()).not.toThrow();
- });
-
- test("throws when a rule references an unknown provider", () => {
- expect(() =>
- validateRoutingRulesAgainstProviders({
- "fake-*": ["totally-not-a-real-provider"],
- })
- ).toThrow(/unknown providers/);
- });
-
- test("throws and lists all unknown providers when multiple typos exist", () => {
- let err: Error | null = null;
- try {
- validateRoutingRulesAgainstProviders({
- "a-*": ["typo-one"],
- "b-*": ["typo-two", "openrouter"],
- });
- } catch (e) {
- err = e as Error;
- }
- expect(err).not.toBeNull();
- expect(err!.message).toContain("typo-one");
- expect(err!.message).toContain("typo-two");
- // Real provider should not appear in the error
- expect(err!.message).not.toContain('→ unknown provider "openrouter"');
- });
-
- test("accepts provider@model rewrite syntax — only validates the provider portion", () => {
- expect(() =>
- validateRoutingRulesAgainstProviders({
- "kimi-*": ["kimi-coding@whatever-model-name", "kimi"],
- })
- ).not.toThrow();
- });
-
- test("accepts provider shortcuts (e.g. 'or' resolves to 'openrouter')", () => {
- expect(() =>
- validateRoutingRulesAgainstProviders({
- "*": ["or"],
- })
- ).not.toThrow();
- });
-
- test("rejects a typo in the provider portion of a provider@model rewrite", () => {
- expect(() =>
- validateRoutingRulesAgainstProviders({
- "kimi-*": ["typo-coding@kimi-for-coding"],
- })
- ).toThrow(/typo-coding/);
- });
-});
-
-// ---------------------------------------------------------------------------
-// Shape of the rules table
-// ---------------------------------------------------------------------------
diff --git a/packages/cli/src/providers/missing-credential-hint.test.ts b/packages/cli/src/providers/missing-credential-hint.test.ts
index b36e19a0..e584ffcb 100644
--- a/packages/cli/src/providers/missing-credential-hint.test.ts
+++ b/packages/cli/src/providers/missing-credential-hint.test.ts
@@ -112,9 +112,9 @@ describe("describeMissingCredential — local providers", () => {
});
describe("describeMissingCredential — everything else is unchanged", () => {
- const plain = BUILTIN_PROVIDERS.filter((d) => !d.oauthFallback && !isLocalTransport(d.name)).map(
- (d) => d.name
- );
+ const plain = BUILTIN_PROVIDERS.filter(
+ (d) => d.name !== "vertex" && !d.oauthFallback && !isLocalTransport(d.name)
+ ).map((d) => d.name);
test("plain providers keep today's exact sentence", () => {
expect(plain.length).toBeGreaterThan(0);
@@ -156,3 +156,12 @@ describe("describeMissingCredential — everything else is unchanged", () => {
);
});
});
+
+describe("describeMissingCredential — Vertex", () => {
+ test("names project remedies and ADC instead of asking for an API key", () => {
+ expect(describeMissingCredential("vertex")).toBe(
+ 'No Google Cloud project for provider "vertex". set VERTEX_PROJECT or run `gcloud config set project <id>`. Application Default Credentials already handles the credential; Vertex takes no API key.'
+ );
+ expect(describeMissingCredential("vertex")).not.toContain("Get one at");
+ });
+});
diff --git a/packages/cli/src/providers/predefined-containment.test.ts b/packages/cli/src/providers/predefined-containment.test.ts
index 3bf30f04..994bd9f9 100644
--- a/packages/cli/src/providers/predefined-containment.test.ts
+++ b/packages/cli/src/providers/predefined-containment.test.ts
@@ -8,63 +8,24 @@
* than a request billed to a vendor the user never chose. The moment a catalog
* name can be reached by typing a BARE model id, the inference can move money.
*
- * Three doors, all pinned here:
+ * Two doors, both pinned here:
*
* 1. `nativeModelPatterns` — the schema has no such field, so a row cannot
* declare one; asserted anyway against the live derived table, because the
* schema could gain one and the assertion is what would notice.
* 2. `legacyPrefixes` — same shape.
- * 3. `DEFAULT_ROUTING_RULES` — the door neither of the first two covers, and
- * the only one a future contributor can open with a one-line, entirely
- * well-meaning edit ("`llama-*` should try Groq first, it's faster"). That
- * edit re-opens silent bare-name billing for every user who happens to have
- * a `GROQ_API_KEY` exported. It is data in a different file from the
- * catalog, so nothing else connects the two.
*
- * Door 3 is NOT wide open today, and the reason is worth recording because it
- * decides how much this assertion is worth. `default-routing-rules.ts` runs
- * `validateDefaultRoutingRules()` at module load and THROWS on a provider name
- * it cannot resolve, so adding `"llama-*": ["groq", …]` today crashes at import
- * (verified). But `getProviderByName` is runtime-aware, so that validator stops
- * refusing the name the moment the catalog row is registered — i.e. exactly
- * when the user has the vendor's key, which is exactly the user who would be
- * silently billed. The load-order accident is the protection, and load order is
- * not a guarantee anybody is maintaining. Hence an explicit assertion.
- *
- * Note what is deliberately NOT asserted: that a catalog name never appears in
- * a chain at all. `defaultProvider` is appended to EVERY bare chain
- * (`routing-rules.ts`), so a user who sets `"defaultProvider": "groq"` really
- * does put a catalog row in bare chains — explicit user action, not a silent
- * path. The invariant is about what claudish SHIPS.
+ * The shipped routing table was deleted. Catalog connections now decide which
+ * providers may receive a bare name, so there is no third hand-written surface
+ * to inspect here.
*/
import { describe, expect, test } from "bun:test";
-import type { RoutingRules } from "../profile-config.js";
-import { DEFAULT_ROUTING_RULES } from "./default-routing-rules.js";
import { PREDEFINED_ENDPOINTS } from "./predefined-catalog.js";
import { getLegacyPrefixPatterns, getNativeModelPatterns } from "./provider-definitions.js";
const catalogNames = PREDEFINED_ENDPOINTS.map((e) => e.name.toLowerCase());
-/**
- * Every (pattern, entry) in a rules table whose provider half names a catalog
- * row. Applied to the shipped table AND to a synthetic leaking one, so the
- * assertion's discriminating power is proved here rather than assumed — a
- * containment check that cannot fail is worse than none, and this one cannot be
- * mutation-tested against the real file (the load-time validator throws first).
- */
-function routingRuleLeaks(rules: RoutingRules): Array<{ pattern: string; candidate: string }> {
- const leaked: Array<{ pattern: string; candidate: string }> = [];
- for (const [pattern, chain] of Object.entries(rules)) {
- for (const candidate of chain ?? []) {
- // Entries are `provider` or `provider@model`; compare the provider half.
- const provider = String(candidate).split("@")[0].trim().toLowerCase();
- if (catalogNames.includes(provider)) leaked.push({ pattern, candidate });
- }
- }
- return leaked;
-}
-
describe("catalog containment", () => {
test("the catalog is non-empty (or every assertion below is vacuous)", () => {
expect(catalogNames.length).toBeGreaterThan(0);
@@ -88,28 +49,4 @@ describe("catalog containment", () => {
const leaked = catalogNames.filter((n) => owners.has(n));
expect(leaked).toEqual([]);
});
-
- test("no catalog name appears anywhere in DEFAULT_ROUTING_RULES", () => {
- expect(routingRuleLeaks(DEFAULT_ROUTING_RULES)).toEqual([]);
- });
-
- test("the leak checker actually catches a leak (bare and provider@model)", () => {
- const vendor = catalogNames[0];
- expect(routingRuleLeaks({ "llama-*": [vendor, "openrouter"] })).toEqual([
- { pattern: "llama-*", candidate: vendor },
- ]);
- expect(routingRuleLeaks({ "llama-*": [`${vendor}@llama-3.3-70b`] })).toEqual([
- { pattern: "llama-*", candidate: `${vendor}@llama-3.3-70b` },
- ]);
- expect(routingRuleLeaks({ "llama-*": ["openrouter"] })).toEqual([]);
- });
-
- test("no catalog name is a routing-rule PATTERN either", () => {
- // A rule keyed on a vendor name (`"groq-*": [...]`) would not make the
- // vendor a destination, but it is the same class of edit and reads as
- // sanctioned precedent for the one that would.
- const keys = Object.keys(DEFAULT_ROUTING_RULES).map((k) => k.toLowerCase());
- const leaked = catalogNames.filter((n) => keys.some((k) => k === n || k === `${n}-*`));
- expect(leaked).toEqual([]);
- });
});
diff --git a/packages/cli/src/providers/provider-definitions.test.ts b/packages/cli/src/providers/provider-definitions.test.ts
index 46539c49..ed7e0d49 100644
--- a/packages/cli/src/providers/provider-definitions.test.ts
+++ b/packages/cli/src/providers/provider-definitions.test.ts
@@ -133,14 +133,16 @@ describe("BUILTIN_PROVIDERS structural integrity", () => {
expect(getProviderByName("qwen-payg")?.displayName).toBe("Alibaba PAYG");
});
- test("grok-subscription does not compete with x-ai for native Grok patterns", () => {
+ test("grok-subscription claims the namespace without displacing x-ai auto-detection", () => {
const subscription = getProviderByName("grok-subscription")!;
const grokPatternOwner = getNativeModelPatterns().find((entry) =>
entry.pattern.test("grok-4.6")
);
- // Native patterns are first-wins; the metered x-ai definition remains their sole owner.
- expect(subscription.nativeModelPatterns).toBeUndefined();
+ // Namespace claims may overlap; parseModelSpec remains first-wins and x-ai is declared first.
+ expect(subscription.nativeModelPatterns?.map(({ pattern }) => pattern.source)).toEqual([
+ "^grok-",
+ ]);
expect(grokPatternOwner?.provider).toBe("x-ai");
});
diff --git a/packages/cli/src/providers/provider-definitions.ts b/packages/cli/src/providers/provider-definitions.ts
index 4b276b5f..2dc1e3ac 100644
--- a/packages/cli/src/providers/provider-definitions.ts
+++ b/packages/cli/src/providers/provider-definitions.ts
@@ -9,6 +9,7 @@
* for identity/routing — only transport and adapter wiring in provider-profiles.ts.
*/
+import { VERTEX_SET_PROJECT_REMEDY } from "../auth/vertex-auth.js";
import type { RemoteProvider } from "../handlers/shared/remote-provider-types.js";
import type { ModelHandler } from "../handlers/types.js";
import { getEndpoint as getConfigEndpoint } from "../profile-config.js";
@@ -1706,6 +1707,13 @@ export function describeMissingCredential(providerName: string): string {
const def = getProviderByName(providerName);
const sibling = describeSiblingKeys(def);
+ if (providerName === "vertex") {
+ return (
+ `No Google Cloud project for provider "vertex". ${VERTEX_SET_PROJECT_REMEDY}. ` +
+ "Application Default Credentials already handles the credential; Vertex takes no API key."
+ );
+ }
+
if (isLocalTransport(providerName)) {
const where = def ? ` Claudish will use ${getEffectiveBaseUrl(def)}.` : "";
const keyClause = keyNames
diff --git a/packages/cli/src/providers/route-candidates.test.ts b/packages/cli/src/providers/route-candidates.test.ts
new file mode 100644
index 00000000..efb44b83
--- /dev/null
+++ b/packages/cli/src/providers/route-candidates.test.ts
@@ -0,0 +1,416 @@
+import { afterAll, beforeAll, describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { credentials } from "../auth/credentials/authority.js";
+import { type DiskCacheV3, type SlimModelEntry, writeAllModelsCache } from "./all-models-cache.js";
+import { _resetCatalogClient, _setCatalogEntriesForTest } from "./catalog-client.js";
+import { providersForCatalogRoute } from "./catalog-route-bindings.js";
+import {
+ getModelDiscoveryFetcher,
+ invalidateModelDiscovery,
+ registerModelDiscoveryFetcher,
+} from "./model-discovery.js";
+import "./model-discovery-builtins.js";
+import {
+ type RouteCandidate,
+ catalogDeniesProvider,
+ compareRouteCandidates,
+ gatherRouteCandidates,
+ routeOwnership,
+} from "./route-candidates.js";
+import { buildCatalogChain, route } from "./routing-rules.js";
+
+const GENERATION = "g-20260921062451697-f490edba";
+
+/**
+ * Trimmed verbatim from ~/.claudish/cloud-models-catalog-v3.json at GENERATION.
+ * The comments name every canonical model id used by a test; fields irrelevant
+ * to gathering are omitted, while route bindings, wire ids, prices, vendor and
+ * context windows remain exactly as published.
+ */
+const REAL_ENTRIES: SlimModelEntry[] = [
+ // gpt-6-astra: subscription + native API + gateways.
+ {
+ modelId: "gpt-6-astra",
+ provider: "openai",
+ aliases: ["openai/gpt-6-astra", "~openai/gpt-astra-latest"],
+ contextWindow: 1_050_000,
+ subscriptionPlanIds: ["openai-codex"],
+ aggregators: [
+ {
+ sourceProviderId: "openai-codex",
+ sourceCollectorId: "openai-codex-models",
+ confidence: "scrape_verified",
+ routeStatus: "mapped",
+ route: { routeId: "openai", routeProfileId: "codex-subscription" },
+ externalModelId: "gpt-6-astra",
+ },
+ {
+ sourceProviderId: "openai",
+ sourceCollectorId: "openai-api",
+ confidence: "api_official",
+ routeStatus: "mapped",
+ route: { routeId: "openai", routeProfileId: "direct-api" },
+ externalModelId: "gpt-6-astra",
+ pricing: { type: "flat", input: 10, output: 50 },
+ },
+ {
+ sourceProviderId: "opencode-zen",
+ sourceCollectorId: "opencode-zen-pricing-scrape",
+ confidence: "gateway_official",
+ routeStatus: "mapped",
+ route: { routeId: "opencode", routeProfileId: "zen" },
+ externalModelId: "gpt-6-astra",
+ pricing: { type: "flat", input: 10, output: 50 },
+ },
+ {
+ sourceProviderId: "openrouter",
+ sourceCollectorId: "openrouter-api",
+ confidence: "aggregator_reported",
+ routeStatus: "mapped",
+ route: { routeId: "openrouter", routeProfileId: "gateway" },
+ externalModelId: "openai/gpt-6-astra",
+ pricing: { type: "flat", input: 10, output: 50 },
+ },
+ ],
+ },
+ // glm-4.7: z-ai/direct-api is bound to both z-ai and glm credential silos.
+ {
+ modelId: "glm-4.7",
+ provider: "z-ai",
+ aliases: ["z-ai/glm-4.7", "zai-org/GLM-4.7", "GLM-4.7"],
+ contextWindow: 202_752,
+ aggregators: [
+ {
+ sourceProviderId: "openrouter",
+ sourceCollectorId: "openrouter-api",
+ confidence: "aggregator_reported",
+ routeStatus: "mapped",
+ route: { routeId: "openrouter", routeProfileId: "gateway" },
+ externalModelId: "z-ai/glm-4.7",
+ pricing: { type: "flat", input: 0.4, output: 1.75 },
+ },
+ {
+ sourceProviderId: "z-ai",
+ sourceCollectorId: "zhipu-api",
+ confidence: "api_official",
+ routeStatus: "mapped",
+ route: { routeId: "z-ai", routeProfileId: "direct-api" },
+ externalModelId: "glm-4.7",
+ pricing: { type: "unavailable" },
+ },
+ ],
+ },
+ // kimi-k3: vendor connection plus priced and unpriced alternatives.
+ {
+ modelId: "kimi-k3",
+ provider: "moonshotai",
+ aliases: ["moonshotai/kimi-k3", "~moonshotai/kimi-latest", "k3"],
+ contextWindow: 1_048_576,
+ aggregators: [
+ {
+ sourceProviderId: "moonshotai",
+ sourceCollectorId: "moonshot-api",
+ confidence: "api_official",
+ routeStatus: "mapped",
+ route: { routeId: "moonshotai", routeProfileId: "direct-api" },
+ externalModelId: "kimi-k3",
+ pricing: { type: "unavailable" },
+ },
+ {
+ sourceProviderId: "opencode-zen",
+ sourceCollectorId: "opencode-zen-pricing-scrape",
+ confidence: "gateway_official",
+ routeStatus: "mapped",
+ route: { routeId: "opencode", routeProfileId: "zen" },
+ externalModelId: "kimi-k3",
+ pricing: { type: "flat", input: 3, output: 15 },
+ },
+ {
+ sourceProviderId: "openrouter",
+ sourceCollectorId: "openrouter-api",
+ confidence: "aggregator_reported",
+ routeStatus: "mapped",
+ route: { routeId: "openrouter", routeProfileId: "gateway" },
+ externalModelId: "moonshotai/kimi-k3",
+ pricing: { type: "flat", input: 1.7, output: 8.5 },
+ },
+ ],
+ },
+ // qwen3.8-max: subscriptions + native API, positively no OpenRouter connection.
+ {
+ modelId: "qwen3.8-max",
+ provider: "qwen",
+ aliases: ["accounts/fireworks/models/qwen3p8-max"],
+ contextWindow: 1_000_000,
+ subscriptionPlanIds: [
+ "alibaba-token-plan-individual",
+ "alibaba-token-plan-team-edition",
+ "opencode-go",
+ ],
+ aggregators: [
+ {
+ sourceProviderId: "opencode-go",
+ sourceCollectorId: "popular-coding-subscriptions",
+ confidence: "gateway_official",
+ routeStatus: "mapped",
+ route: { routeId: "opencode", routeProfileId: "go-subscription" },
+ externalModelId: "qwen3.8-max",
+ },
+ {
+ sourceProviderId: "qwen-cloud",
+ sourceCollectorId: "qwen-cloud-token-plan-scrape",
+ confidence: "scrape_verified",
+ routeStatus: "mapped",
+ route: { routeId: "qwen", routeProfileId: "qwencloud-token-plan" },
+ externalModelId: "qwen3.8-max",
+ },
+ {
+ sourceProviderId: "qwen",
+ sourceCollectorId: "dashscope-api",
+ confidence: "api_official",
+ routeStatus: "mapped",
+ route: { routeId: "qwen", routeProfileId: "dashscope-direct" },
+ externalModelId: "qwen3.8-max",
+ pricing: { type: "flat", input: 2, output: 6 },
+ },
+ ],
+ },
+ // gemini-3.8-flash: metered connections plus Antigravity's namespace claim.
+ {
+ modelId: "gemini-3.8-flash",
+ provider: "google",
+ aliases: ["google/gemini-3.8-flash"],
+ contextWindow: 1_048_576,
+ aggregators: [
+ {
+ sourceProviderId: "google",
+ sourceCollectorId: "google-model-get-api",
+ confidence: "api_official",
+ routeStatus: "mapped",
+ route: { routeId: "google", routeProfileId: "direct-api" },
+ externalModelId: "gemini-3.8-flash",
+ pricing: { type: "flat", input: 0.75, output: 3.75 },
+ },
+ {
+ sourceProviderId: "openrouter",
+ sourceCollectorId: "openrouter-api",
+ confidence: "aggregator_reported",
+ routeStatus: "mapped",
+ route: { routeId: "openrouter", routeProfileId: "gateway" },
+ externalModelId: "google/gemini-3.8-flash",
+ pricing: { type: "flat", input: 0.75, output: 3.75 },
+ },
+ ],
+ },
+];
+
+const tempDir = mkdtempSync(join(tmpdir(), "claudish-route-candidates-"));
+const cachePath = join(tempDir, "cloud-models-catalog-v3.json");
+const missingCachePath = join(tempDir, "missing-catalog.json");
+
+beforeAll(() => {
+ const cache: DiskCacheV3 = {
+ version: 3,
+ catalogGenerationId: GENERATION,
+ lastUpdated: "2026-09-21T06:24:51.697Z",
+ entries: REAL_ENTRIES,
+ models: [],
+ plans: [],
+ };
+ writeAllModelsCache(cache, cachePath);
+});
+
+afterAll(() => {
+ _resetCatalogClient();
+ rmSync(tempDir, { recursive: true, force: true });
+});
+
+function gatheredCandidate(model: string, provider: string): RouteCandidate {
+ const candidate = gatherRouteCandidates(model, cachePath).candidates.find(
+ (item) => item.provider === provider
+ );
+ if (!candidate) throw new Error(`fixture produced no ${provider} candidate for ${model}`);
+ return candidate;
+}
+
+describe("catalog route candidate gathering and order", () => {
+ test("puts a flat-rate subscription before a metered connection", () => {
+ const candidates = gatherRouteCandidates("gpt-6-astra", cachePath).candidates;
+
+ expect(candidates[0]?.provider).toBe("openai-codex");
+ expect(candidates.map(({ provider }) => provider)).toContain("openrouter");
+ });
+
+ test("gathers every provider bound to z-ai/direct-api", () => {
+ const binding = { routeId: "z-ai", routeProfileId: "direct-api" };
+ expect(providersForCatalogRoute(binding)).toEqual(["z-ai", "glm"]);
+
+ const direct = gatherRouteCandidates("glm-4.7", cachePath).candidates.filter(
+ ({ wireId }) => wireId === "glm-4.7"
+ );
+ expect(direct.map(({ provider }) => provider).sort()).toEqual(["glm", "z-ai"]);
+ });
+
+ test("the vendor comes first when candidates share a tier", () => {
+ const vendor = gatheredCandidate("kimi-k3", "kimi");
+ const gateway = gatheredCandidate("kimi-k3", "openrouter");
+
+ // No current row puts a vendor-native connection and a gateway in one tier:
+ // RouteTier defines those separately. Equalising only the tier isolates the
+ // comparator contract while retaining kimi-k3's real wire ids, prices and
+ // moonshotai vendor binding.
+ const tied = [
+ { ...gateway, tier: "gateway" as const },
+ { ...vendor, tier: "gateway" as const },
+ ].sort(compareRouteCandidates);
+ expect(tied[0]?.provider).toBe("kimi");
+ });
+
+ test("orders known prices cheapest-first and every unknown price last", () => {
+ const openrouter = gatheredCandidate("kimi-k3", "openrouter");
+ const zen = gatheredCandidate("kimi-k3", "opencode-zen");
+ const unknown = gatheredCandidate("kimi-k3", "kimi");
+ const comparable = [openrouter, zen, unknown]
+ .map((candidate) => ({ ...candidate, tier: "gateway" as const, isVendorOwn: false }))
+ .sort(compareRouteCandidates);
+
+ expect(comparable.map(({ provider }) => provider)).toEqual([
+ "openrouter",
+ "opencode-zen",
+ "kimi",
+ ]);
+ expect(comparable.at(-1)?.price.known).toBe(false);
+ });
+
+ test("uses larger context next and provider name as the deterministic final tie-break", () => {
+ const kimi = gatheredCandidate("kimi-k3", "kimi");
+ const zai = gatheredCandidate("glm-4.7", "z-ai");
+
+ // Generation g-20260921062451697-f490edba publishes zero per-connection
+ // windows. The AggregatorEntry contract says omission inherits the model's
+ // headline window, so these are the real 1,048,576 and 202,752 values.
+ const neitherVendor = [zai, kimi].map((candidate) => ({
+ ...candidate,
+ isVendorOwn: false,
+ }));
+ expect(neitherVendor.sort(compareRouteCandidates).map(({ provider }) => provider)).toEqual([
+ "kimi",
+ "z-ai",
+ ]);
+
+ const sameContext = neitherVendor
+ .map((candidate) => ({ ...candidate, contextWindow: kimi.contextWindow }))
+ .sort(compareRouteCandidates);
+ expect(sameContext.map(({ provider }) => provider)).toEqual(["kimi", "z-ai"]);
+ });
+});
+
+describe("namespace claims and availability", () => {
+ test("a namespace claim is gathered but the dynamic models catalog may remove it", async () => {
+ const gathered = gatherRouteCandidates("gemini-3.8-flash", cachePath);
+ expect(gathered.candidates).toContainEqual(
+ expect.objectContaining({
+ provider: "antigravity",
+ tier: "dynamic-subscription",
+ source: "namespace-claim",
+ })
+ );
+
+ const originalFetcher = getModelDiscoveryFetcher("antigravity");
+ const originalIsAvailable = credentials.isAvailable;
+ const originalDescribeReadiness = credentials.describeReadiness;
+ if (!originalFetcher) throw new Error("Antigravity discovery fetcher was not registered");
+
+ try {
+ registerModelDiscoveryFetcher("antigravity", async () => [{ id: "gemini-2.5-flash" }]);
+ invalidateModelDiscovery("antigravity");
+ credentials.isAvailable = async (provider: string) => provider === "antigravity";
+ credentials.describeReadiness = async (provider: string) => ({
+ readiness: provider === "antigravity" ? "present" : "absent",
+ });
+
+ const plan = await route("gemini-3.8-flash", {}, "", cachePath);
+ expect(plan.kind).toBe("no-route");
+ if (plan.kind === "no-route") {
+ expect(plan.reason).toBe('No provider serves "gemini-3.8-flash" (checked: antigravity).');
+ }
+ } finally {
+ registerModelDiscoveryFetcher("antigravity", originalFetcher);
+ invalidateModelDiscovery("antigravity");
+ credentials.isAvailable = originalIsAvailable;
+ credentials.describeReadiness = originalDescribeReadiness;
+ }
+ });
+});
+
+describe("fallback placement and no-catalog behavior", () => {
+ test("appends the fallback last and does not duplicate an existing candidate", () => {
+ const missingModel = buildCatalogChain("swe-1.7", undefined, cachePath);
+ expect(missingModel.routes.map(({ provider }) => provider)).toEqual(["devin", "openrouter"]);
+
+ const alreadyGathered = buildCatalogChain("gpt-6-astra", "openrouter", cachePath);
+ expect(alreadyGathered.routes.at(-1)?.provider).toBe("openrouter");
+ expect(alreadyGathered.routes.filter(({ provider }) => provider === "openrouter")).toHaveLength(
+ 1
+ );
+ });
+
+ test("does not append a fallback when defaultProvider is explicitly empty", () => {
+ expect(
+ buildCatalogChain("swe-1.7", "", cachePath).routes.map(({ provider }) => provider)
+ ).toEqual(["devin"]);
+ });
+
+ test.skipIf(routeOwnership("openrouter") !== "backend-owned")(
+ "does not append a backend-owned gateway the cloud models catalog positively denies",
+ () => {
+ // The probe ownership cache and qwen3.8-max row are both generation
+ // g-20260921062451697-f490edba. The branch cannot be isolated from the
+ // default probe-cache path because production exposes no injection seam.
+ expect(catalogDeniesProvider("openrouter", "qwen3.8-max", cachePath)).toBe(true);
+ expect(
+ buildCatalogChain("qwen3.8-max", "openrouter", cachePath).routes.map(
+ ({ provider }) => provider
+ )
+ ).not.toContain("openrouter");
+ }
+ );
+
+ test("a matching empty user rule suppresses every fallback", async () => {
+ const originalIsAvailable = credentials.isAvailable;
+ try {
+ credentials.isAvailable = async () => true;
+ const plan = await route("gpt-6-astra", { "*": [] }, "openrouter", cachePath);
+ expect(plan).toEqual({
+ kind: "no-route",
+ reason: 'A routing rule matched "gpt-6-astra" and named no provider.',
+ hint: expect.any(String),
+ });
+ } finally {
+ credentials.isAvailable = originalIsAvailable;
+ }
+ });
+
+ test("no cloud models catalog blocks bare names but explicit model specs still work", async () => {
+ const originalIsAvailable = credentials.isAvailable;
+ _setCatalogEntriesForTest([]);
+ try {
+ credentials.isAvailable = async (provider: string) => provider === "openai";
+ const bare = await route("gpt-5", {}, undefined, missingCachePath);
+ expect(bare.kind).toBe("no-route");
+ if (bare.kind === "no-route") {
+ expect(bare.reason).toContain("No model catalog available");
+ expect(bare.hint).toContain("claudish --models-refresh");
+ }
+
+ const explicit = await route("openai@gpt-5", {}, undefined, missingCachePath);
+ expect(explicit.kind).toBe("ok");
+ if (explicit.kind === "ok") expect(explicit.primary.modelSpec).toBe("oai@gpt-5");
+ } finally {
+ credentials.isAvailable = originalIsAvailable;
+ _resetCatalogClient();
+ }
+ });
+});
diff --git a/packages/cli/src/providers/routing-rules.test.ts b/packages/cli/src/providers/routing-rules.test.ts
index d696f029..4db4d6a1 100644
--- a/packages/cli/src/providers/routing-rules.test.ts
+++ b/packages/cli/src/providers/routing-rules.test.ts
@@ -2,8 +2,8 @@ import { catalogRouteForProvider } from "./catalog-route-bindings.js";
/**
* Unit tests for providers/routing-rules.ts
*
- * Tests matchRoutingRule, buildRoutingChain, loadRoutingRules, mergeRoutingRules,
- * and route() without hitting any real APIs or machine routing configuration.
+ * Tests matchRoutingRule, buildRoutingChain, loadRoutingRules, and route()
+ * without hitting any real APIs or machine routing configuration.
*
* Run: bun test packages/cli/src/providers/routing-rules.test.ts
*/
@@ -15,65 +15,24 @@ import { join } from "node:path";
import { credentials } from "../auth/credentials/authority.js";
import { __resetSniffForTests } from "../auth/credentials/op-source.js";
-import type { RecommendedModelsDoc } from "../model-loader.js";
import type { RoutingRules } from "../profile-config.js";
import { type DiskCacheV3, type SlimModelEntry, writeAllModelsCache } from "./all-models-cache.js";
import { DISPLAY_NAMES } from "./auto-route.js";
import { _resetCatalogClient, _setCatalogEntriesForTest } from "./catalog-client.js";
-import { DEFAULT_ROUTING_RULES } from "./default-routing-rules.js";
import { invalidateModelDiscovery } from "./model-discovery.js";
import type { ProviderDefinition } from "./provider-definitions.js";
import {
buildRoutingChain,
loadRoutingRules,
matchRoutingRule,
- mergeRoutingRules,
normalizeGlmSlug,
- retainKnownCatalogRoutingRules,
route,
+ validateRoutingRulesAgainstProviders,
} from "./routing-rules.js";
import { clearRuntimeRegistry, registerRuntimeProvider } from "./runtime-providers.js";
const SYNTHETIC_MODEL_ID = "acme-x1.0";
const SYNTHETIC_MINIMAX_EXTERNAL_ID = "ACME-X1.0";
-const CATALOG_EXACT_MODEL_ID = "grok-4.6";
-
-const CATALOG_EXACT_ROUTE_DOC: RecommendedModelsDoc = {
- version: "test",
- lastUpdated: "2026-09-03T00:00:00.000Z",
- models: [
- {
- id: CATALOG_EXACT_MODEL_ID,
- name: "Grok 4.6",
- description: "Synthetic catalog route used to isolate rule composition",
- provider: "xAI",
- category: "subscription",
- priority: 1,
- pricing: { input: "N/A", output: "N/A", average: "N/A" },
- context: "N/A",
- subscriptions: [
- {
- plan: "OpenCode Zen Go",
- command: "[email protected]",
- routingProvider: "opencode-zen-go",
- tier: "general",
- },
- ],
- },
- ],
-};
-
-function loadRulesWithCatalogExact(
- globalRules: RoutingRules = {},
- localRules: RoutingRules = {}
-): RoutingRules {
- return loadRoutingRules({
- globalRules,
- localRules,
- recommendedModels: CATALOG_EXACT_ROUTE_DOC,
- });
-}
-
function seedDefaultCatalog(entries: DiskCacheV3["entries"]): () => void {
_setCatalogEntriesForTest(entries);
return _resetCatalogClient;
@@ -82,12 +41,14 @@ function seedDefaultCatalog(entries: DiskCacheV3["entries"]): () => void {
function makeTempCatalog(
model: {
modelId: string;
+ aliases?: string[];
externalId?: string;
subscriptionPlanIds?: string[];
},
/** Plan names to mark as active subscription plans in the catalog (defaults to the model's own plans). */
plans: string[] = model.subscriptionPlanIds ?? [],
- routingProviderByPlan: Record<string, string> = {}
+ routingProviderByPlan: Record<string, string> = {},
+ additionalProviders: string[] = []
): { path: string; cleanup: () => void } {
const dir = mkdtempSync(join(tmpdir(), "claudish-routing-test-"));
const path = join(dir, "all-models.json");
@@ -118,20 +79,29 @@ function makeTempCatalog(
entries.push({
modelId: model.modelId,
- aliases: [],
+ aliases: model.aliases ?? [],
subscriptionPlanIds: model.subscriptionPlanIds ?? [],
- aggregators:
- model.externalId && model.subscriptionPlanIds
- ? model.subscriptionPlanIds.map((planId) => ({
+ aggregators: model.externalId
+ ? [
+ ...(model.subscriptionPlanIds ?? []).map((planId) => ({
sourceProviderId: routingProviderByPlan[planId] ?? planId,
sourceCollectorId: "test",
routeStatus: "mapped" as const,
route: catalogRouteForProvider(routingProviderByPlan[planId] ?? planId),
externalModelId: model.externalId!,
confidence: "scrape_verified" as const,
- }))
- : undefined,
+ })),
+ ...additionalProviders.map((provider) => ({
+ sourceProviderId: provider,
+ sourceCollectorId: "test",
+ routeStatus: "mapped" as const,
+ route: catalogRouteForProvider(provider),
+ externalModelId: model.externalId!,
+ confidence: "api_official" as const,
+ })),
+ ]
+ : undefined,
});
const cache: DiskCacheV3 = {
@@ -442,11 +412,7 @@ describe("buildRoutingChain", () => {
// loadRoutingRules — source composition without disk I/O
// ---------------------------------------------------------------------------
-describe("loadRoutingRules merges defaults", () => {
- // The three behavioural tests below seed `sources.recommendedModels`, but the
- // v9.0.1 path bypassed that seam and read a homedir-derived cache path. They
- // can therefore stay green on a cold CI checkout; this source-boundary guard
- // survives that cold cache by forbidding model-loader runtime imports here.
+describe("loadRoutingRules composes only user rules", () => {
test("keeps model-loader imports type-only so routing rules cannot read ambient cache state", () => {
const source = readFileSync(join(import.meta.dir, "routing-rules.ts"), "utf8");
const modelLoaderImports = [
@@ -461,96 +427,84 @@ describe("loadRoutingRules merges defaults", () => {
expect(valueImports).toEqual([]);
});
- test("default glob stays reachable when the catalog has an exact model key", () => {
- // Catalog keys are exact, so retaining one here used to bypass the broader
- // fallback chain solely because exact matching runs before glob matching.
- const rules = loadRulesWithCatalogExact();
-
- expect(matchRoutingRule(CATALOG_EXACT_MODEL_ID, rules)).toEqual(
- DEFAULT_ROUTING_RULES["grok-*"]
- );
+ test("returns an empty table when the user configured no rules", () => {
+ expect(loadRoutingRules({ globalRules: {}, localRules: {} })).toEqual({});
});
- test("user glob wins when the catalog has an exact model key", () => {
+ test("honours a user glob verbatim", () => {
const userRules: RoutingRules = { "grok-*": ["x-ai", "openrouter"] };
-
- // Docs recommend family globs; an exact cache row must not silently make a
- // user's supported configuration style unreachable.
- const rules = loadRulesWithCatalogExact(userRules);
-
- expect(matchRoutingRule(CATALOG_EXACT_MODEL_ID, rules)).toEqual(userRules["grok-*"]);
+ const rules = loadRoutingRules({ globalRules: userRules, localRules: {} });
+ expect(matchRoutingRule("grok-4.6", rules)).toEqual(userRules["grok-*"]);
});
- test("returns only rule keys supplied by defaults or user config", () => {
+ test("returns only user-supplied rule keys", () => {
const globalRules: RoutingRules = { "team-*": ["openrouter"] };
const localRules: RoutingRules = { "project-model": ["x-ai"] };
+ expect(loadRoutingRules({ globalRules, localRules })).toEqual({
+ "team-*": ["openrouter"],
+ "project-model": ["x-ai"],
+ });
+ });
- // Cache contents vary by machine and over time, so they cannot be allowed
- // to expand the effective configuration's key space.
- const rules = loadRulesWithCatalogExact(globalRules, localRules);
- const configuredRules = mergeRoutingRules(DEFAULT_ROUTING_RULES, globalRules, localRules);
+ test("an exact key beats a glob inside the user's own rules", () => {
+ const rules = loadRoutingRules({
+ globalRules: {
+ "grok-*": ["x-ai", "openrouter"],
+ "grok-4.6": ["grok-subscription"],
+ },
+ localRules: {},
+ });
+ expect(matchRoutingRule("grok-4.6", rules)).toEqual(["grok-subscription"]);
+ });
- expect(Object.keys(rules).sort()).toEqual(Object.keys(configuredRules).sort());
+ test("local rules override global rules by exact key", () => {
+ const userGlobal: RoutingRules = { "claude-*": ["openrouter"] };
+ const userLocal: RoutingRules = { "claude-*": ["native-anthropic"] };
+ const rules = loadRoutingRules({ globalRules: userGlobal, localRules: userLocal });
+ expect(rules).toEqual({ "claude-*": ["native-anthropic"] });
});
- test("catalog routes keep known providers and cannot shadow defaults with an unknown provider", () => {
- expect(
- retainKnownCatalogRoutingRules({
- "mixed-model": ["future-provider@future-wire", "openrouter@vendor/model"],
- "future-only-model": ["future-provider@future-wire"],
- })
- ).toEqual({
- "mixed-model": ["openrouter@vendor/model"],
- });
+ test("preserves an explicit empty catch-all", () => {
+ const rules = loadRoutingRules({ globalRules: { "*": [] }, localRules: {} });
+ expect(matchRoutingRule("totally-unknown-model-xyz", rules)).toEqual([]);
});
+});
- test("with no user rules: merge returns defaults exactly", () => {
- const merged = mergeRoutingRules(DEFAULT_ROUTING_RULES, {}, {});
- expect(merged).toEqual(DEFAULT_ROUTING_RULES);
+describe("validateRoutingRulesAgainstProviders", () => {
+ test("throws when a rule references an unknown provider", () => {
+ expect(() =>
+ validateRoutingRulesAgainstProviders({ "fake-*": ["totally-not-a-real-provider"] })
+ ).toThrow(/unknown providers/);
});
- test("user rule that overrides 'claude-*' wins; defaults still cover other patterns", () => {
- const userGlobal: RoutingRules = {
- "claude-*": ["openrouter"],
- };
- const merged = mergeRoutingRules(DEFAULT_ROUTING_RULES, userGlobal, {});
- expect(merged["claude-*"]).toEqual(["openrouter"]);
- // Defaults still apply to unrelated patterns
- expect(merged["gpt-*"]).toEqual(DEFAULT_ROUTING_RULES["gpt-*"]);
- expect(merged["*"]).toEqual(DEFAULT_ROUTING_RULES["*"]);
+ test("lists every unknown provider without blaming known providers", () => {
+ expect(() =>
+ validateRoutingRulesAgainstProviders({
+ "a-*": ["typo-one"],
+ "b-*": ["typo-two", "openrouter"],
+ })
+ ).toThrow(/typo-one[\s\S]*typo-two/);
+ try {
+ validateRoutingRulesAgainstProviders({ "a-*": ["typo-one", "openrouter"] });
+ } catch (error) {
+ expect((error as Error).message).not.toContain('→ unknown provider "openrouter"');
+ }
});
- test("user '*' = [] removes the catch-all (verify match returns empty)", () => {
- const userGlobal: RoutingRules = {
- "*": [],
- };
- const merged = mergeRoutingRules(DEFAULT_ROUTING_RULES, userGlobal, {});
- expect(merged["*"]).toEqual([]);
- // Other defaults still apply
- expect(merged["claude-*"]).toEqual(DEFAULT_ROUTING_RULES["claude-*"]);
- // matchRoutingRule on a pattern only the catch-all would have caught
- // returns the empty array (caller treats as "no route").
- const m = matchRoutingRule("totally-unknown-model-xyz", merged);
- expect(m).toEqual([]);
+ test("accepts provider@wire-id rewrites", () => {
+ expect(() =>
+ validateRoutingRulesAgainstProviders({ "kimi-*": ["kimi-coding@whatever-model", "kimi"] })
+ ).not.toThrow();
});
- test("local overrides global; defaults still cover untouched patterns", () => {
- const userGlobal: RoutingRules = { "claude-*": ["openrouter"] };
- const userLocal: RoutingRules = { "claude-*": ["native-anthropic"] };
- const merged = mergeRoutingRules(DEFAULT_ROUTING_RULES, userGlobal, userLocal);
- // Local wins
- expect(merged["claude-*"]).toEqual(["native-anthropic"]);
- // Defaults still cover unrelated patterns
- expect(merged["gpt-*"]).toEqual(DEFAULT_ROUTING_RULES["gpt-*"]);
+ test("accepts provider shortcuts", () => {
+ expect(() => validateRoutingRulesAgainstProviders({ "*": ["or"] })).not.toThrow();
});
- test("local + global add new patterns without disturbing defaults", () => {
- const userGlobal: RoutingRules = { "my-custom-*": ["openrouter"] };
- const userLocal: RoutingRules = { "my-other-*": ["openai"] };
- const merged = mergeRoutingRules(DEFAULT_ROUTING_RULES, userGlobal, userLocal);
- expect(merged["my-custom-*"]).toEqual(["openrouter"]);
- expect(merged["my-other-*"]).toEqual(["openai"]);
- expect(merged["claude-*"]).toEqual(DEFAULT_ROUTING_RULES["claude-*"]);
+ test("rejects a typo in a provider@wire-id rewrite", () => {
+ expect(() =>
+ validateRoutingRulesAgainstProviders({ "kimi-*": ["typo-coding@kimi-for-coding"] })
+ ).toThrow(/typo-coding/);
});
});
@@ -653,7 +607,7 @@ describe("route()", () => {
test("claude-opus-4-7 with ANTHROPIC_API_KEY → primary native-anthropic", async () => {
process.env.ANTHROPIC_API_KEY = "sk-ant-test";
- const plan = await route("claude-opus-4-7", DEFAULT_ROUTING_RULES);
+ const plan = await route("claude-opus-4-7", {});
expect(plan.kind).toBe("ok");
if (plan.kind !== "ok") return;
expect(plan.primary.provider).toBe("native-anthropic");
@@ -668,7 +622,7 @@ describe("route()", () => {
test("explicit Devin dv@glm-5-2 preserves the dash-native uid without normalization", async () => {
process.env.WINDSURF_API_KEY = "devin-session-token$test";
- const plan = await route("dv@glm-5-2", DEFAULT_ROUTING_RULES);
+ const plan = await route("dv@glm-5-2", {});
expect(plan.kind).toBe("ok");
if (plan.kind !== "ok") return;
expect(plan.primary.modelSpec).toBe("dv@glm-5-2");
@@ -677,14 +631,14 @@ describe("route()", () => {
test("claude-opus-4-7 with only OPENROUTER_API_KEY → primary openrouter", async () => {
process.env.OPENROUTER_API_KEY = "or-test";
- const plan = await route("claude-opus-4-7", DEFAULT_ROUTING_RULES);
+ const plan = await route("claude-opus-4-7", {});
expect(plan.kind).toBe("ok");
if (plan.kind !== "ok") return;
expect(plan.primary.provider).toBe("openrouter");
});
test("claude-opus-4-7 with no credentials → no-route, hint mentions both providers", async () => {
- const plan = await route("claude-opus-4-7", DEFAULT_ROUTING_RULES);
+ const plan = await route("claude-opus-4-7", {});
expect(plan.kind).toBe("no-route");
if (plan.kind !== "no-route") return;
expect(plan.hint).toBeDefined();
@@ -696,7 +650,7 @@ describe("route()", () => {
test("explicit prefix native-anthropic@claude-opus-4-7 with ANTHROPIC_API_KEY → ok", async () => {
process.env.ANTHROPIC_API_KEY = "sk-ant-test";
- const plan = await route("native-anthropic@claude-opus-4-7", DEFAULT_ROUTING_RULES);
+ const plan = await route("native-anthropic@claude-opus-4-7", {});
expect(plan.kind).toBe("ok");
if (plan.kind !== "ok") return;
expect(plan.primary.provider).toBe("native-anthropic");
@@ -707,7 +661,7 @@ describe("route()", () => {
// Even with OPENROUTER_API_KEY set, an explicit openai@ prefix must NOT
// silently reroute to OpenRouter.
process.env.OPENROUTER_API_KEY = "or-test";
- const plan = await route("openai@gpt-5", DEFAULT_ROUTING_RULES);
+ const plan = await route("openai@gpt-5", {});
expect(plan.kind).toBe("no-route");
if (plan.kind !== "no-route") return;
// Hint should mention the missing OpenAI key, not OpenRouter
@@ -729,7 +683,7 @@ describe("route()", () => {
if (existsSync(codexOauth)) return;
process.env.OPENAI_API_KEY = "sk-openai-test";
- const plan = await route("gpt-5", DEFAULT_ROUTING_RULES);
+ const plan = await route("gpt-5", {});
expect(plan.kind).toBe("ok");
if (plan.kind !== "ok") return;
expect(plan.primary.provider).toBe("openai");
@@ -751,7 +705,7 @@ describe("route()", () => {
const cachePath = join(dir, "all-models.json");
try {
process.env.OPENAI_CODEX_API_KEY = "sk-codex-test";
- const plan = await route("gpt-5", DEFAULT_ROUTING_RULES, undefined, cachePath);
+ const plan = await route("gpt-5", {}, undefined, cachePath);
expect(plan.kind).toBe("ok");
if (plan.kind !== "ok") return;
expect(plan.primary.provider).toBe("openai-codex");
@@ -763,13 +717,18 @@ describe("route()", () => {
test("qwen3.7-plus prefers qwen-token-plan over qwen-payg when both credentials are present", async () => {
process.env.QWEN_TOKEN_PLAN_API_KEY = "qwen-plan-test";
process.env.DASHSCOPE_API_KEY = "qwen-payg-test";
- const { path, cleanup } = makeTempCatalog({
- modelId: "qwen3.7-plus",
- externalId: "qwen3.7-plus",
- subscriptionPlanIds: ["qwen-token-plan"],
- });
+ const { path, cleanup } = makeTempCatalog(
+ {
+ modelId: "qwen3.7-plus",
+ externalId: "qwen3.7-plus",
+ subscriptionPlanIds: ["qwen-token-plan"],
+ },
+ undefined,
+ {},
+ ["qwen-payg"]
+ );
try {
- const plan = await route("qwen3.7-plus", DEFAULT_ROUTING_RULES, undefined, path);
+ const plan = await route("qwen3.7-plus", {}, undefined, path);
expect(plan.kind).toBe("ok");
if (plan.kind !== "ok") return;
expect(plan.primary.provider).toBe("qwen-token-plan");
@@ -792,10 +751,11 @@ describe("route()", () => {
{
"alibaba-ai-coding-plan": "qwen-coding",
"alibaba-token-plan-individual": "qwen-token-plan",
- }
+ },
+ ["qwen-payg"]
);
try {
- const result = await route("qwen3.7-plus", DEFAULT_ROUTING_RULES, undefined, path);
+ const result = await route("qwen3.7-plus", {}, undefined, path);
expect(result.kind).toBe("ok");
if (result.kind !== "ok") return;
expect(result.primary.modelSpec).toBe("[email protected]");
@@ -810,13 +770,18 @@ describe("route()", () => {
test("qwen3.7-plus falls through to qwen-payg with only DASHSCOPE_API_KEY", async () => {
process.env.DASHSCOPE_API_KEY = "qwen-payg-test";
- const { path, cleanup } = makeTempCatalog({
- modelId: "qwen3.7-plus",
- externalId: "qwen3.7-plus",
- subscriptionPlanIds: ["qwen-token-plan"],
- });
+ const { path, cleanup } = makeTempCatalog(
+ {
+ modelId: "qwen3.7-plus",
+ externalId: "qwen3.7-plus",
+ subscriptionPlanIds: ["qwen-token-plan"],
+ },
+ undefined,
+ {},
+ ["qwen-payg"]
+ );
try {
- const plan = await route("qwen3.7-plus", DEFAULT_ROUTING_RULES, undefined, path);
+ const plan = await route("qwen3.7-plus", {}, undefined, path);
expect(plan.kind).toBe("ok");
if (plan.kind !== "ok") return;
expect(plan.primary.provider).toBe("qwen-payg");
@@ -838,7 +803,7 @@ describe("route()", () => {
{ "kimi-code": "kimi-coding" }
);
try {
- const plan = await route("kimi-k3", DEFAULT_ROUTING_RULES, undefined, path);
+ const plan = await route("kimi-k3", {}, undefined, path);
expect(plan.kind).toBe("ok");
if (plan.kind !== "ok") return;
expect(plan.primary.provider).toBe("kimi-coding");
@@ -930,13 +895,14 @@ describe("route()", () => {
const { path, cleanup } = makeTempCatalog(
{
modelId: "kimi-k3",
+ aliases: ["k3"],
externalId: "k3",
subscriptionPlanIds: ["kimi-coding"],
},
["kimi-coding"]
);
try {
- const plan = await route("k3", DEFAULT_ROUTING_RULES, undefined, path);
+ const plan = await route("k3", {}, undefined, path);
expect(plan.kind).toBe("ok");
if (plan.kind !== "ok") return;
expect(plan.primary.provider).toBe("kimi-coding");
@@ -951,13 +917,14 @@ describe("route()", () => {
const { path, cleanup } = makeTempCatalog(
{
modelId: "kimi-k3-256k",
+ aliases: ["k3-256k"],
externalId: "k3-256k",
subscriptionPlanIds: ["kimi-coding"],
},
["kimi-coding"]
);
try {
- const plan = await route("k3-256k", DEFAULT_ROUTING_RULES, undefined, path);
+ const plan = await route("k3-256k", {}, undefined, path);
expect(plan.kind).toBe("ok");
if (plan.kind !== "ok") return;
expect(plan.primary.provider).toBe("kimi-coding");
@@ -973,13 +940,16 @@ describe("route()", () => {
const { path, cleanup } = makeTempCatalog(
{
modelId: "kimi-k2.5",
+ externalId: "kimi-k2.5",
// No subscriptionPlanIds — this model is not part of the kimi-coding plan,
// so the subscription candidate is dropped instead of silently substituting.
},
- ["kimi-coding"]
+ ["kimi-coding"],
+ {},
+ ["kimi"]
);
try {
- const plan = await route("kimi-k2.5", DEFAULT_ROUTING_RULES, undefined, path);
+ const plan = await route("kimi-k2.5", {}, undefined, path);
expect(plan.kind).toBe("ok");
if (plan.kind !== "ok") return;
expect(plan.primary.provider).toBe("kimi");
@@ -990,7 +960,7 @@ describe("route()", () => {
});
test("user disables catch-all with '*' = [] → no-route for unknown bare names", async () => {
- const userRules: RoutingRules = mergeRoutingRules(DEFAULT_ROUTING_RULES, { "*": [] }, {});
+ const userRules: RoutingRules = { "*": [] };
process.env.OPENROUTER_API_KEY = "or-test";
const plan = await route("totally-unknown-xyz", userRules);
expect(plan.kind).toBe("no-route");
@@ -1014,7 +984,7 @@ describe("route()", () => {
process.env.OPENAI_CODEX_API_KEY = "cx-test";
process.env.OPENAI_API_KEY = "oai-test";
process.env.OPENROUTER_API_KEY = "or-test";
- const plan = await route("gpt-5", DEFAULT_ROUTING_RULES, undefined, cachePath);
+ const plan = await route("gpt-5", {}, undefined, cachePath);
expect(plan.kind).toBe("ok");
if (plan.kind !== "ok") return;
expect(plan.primary.provider).toBe("openai-codex");
@@ -1058,14 +1028,14 @@ describe("route() with defaultProvider", () => {
credentials.invalidate();
});
- test("defaultProvider appended after matched chain when not already present", async () => {
+ test("a matched user rule is honoured verbatim without appending defaultProvider", async () => {
process.env.OPENAI_API_KEY = "oai-test";
process.env.XAI_API_KEY = "xai-test";
const plan = await route("gpt-5", { "gpt-*": ["openai"] }, "x-ai");
expect(plan.kind).toBe("ok");
if (plan.kind !== "ok") return;
expect(plan.primary.provider).toBe("openai");
- expect(plan.fallbacks.map((r) => r.provider)).toEqual(["x-ai"]);
+ expect(plan.fallbacks).toEqual([]);
});
test("defaultProvider deduped if already present in chain", async () => {
@@ -1080,30 +1050,33 @@ describe("route() with defaultProvider", () => {
test("defaultProvider rescues unmatched model with no rule", async () => {
process.env.OPENROUTER_API_KEY = "or-test";
- const plan = await route("totally-unknown-xyz", {}, "openrouter");
- expect(plan.kind).toBe("ok");
- if (plan.kind !== "ok") return;
- expect(plan.primary.provider).toBe("openrouter");
+ const { path, cleanup } = makeTempCatalog({ modelId: "catalog-readable-marker" });
+ try {
+ const plan = await route("totally-unknown-xyz", {}, "openrouter", path);
+ expect(plan.kind).toBe("ok");
+ if (plan.kind !== "ok") return;
+ expect(plan.primary.provider).toBe("openrouter");
+ } finally {
+ cleanup();
+ }
});
- test("defaultProvider rescues when matched chain has no credentialed providers", async () => {
+ test("defaultProvider does not rescue a matched user chain with no credentials", async () => {
process.env.XAI_API_KEY = "xai-test";
const plan = await route("deepseek-r1", { "deepseek-*": ["deepseek"] }, "x-ai");
- expect(plan.kind).toBe("ok");
- if (plan.kind !== "ok") return;
- expect(plan.primary.provider).toBe("x-ai");
+ expect(plan.kind).toBe("no-route");
});
- test("defaultProvider undefined → identical behavior to omitted argument", () => {
+ test("defaultProvider undefined has the same effect as an omitted argument", async () => {
process.env.OPENAI_API_KEY = "oai-test";
- const planA = route("gpt-5", { "gpt-*": ["openai"] }, undefined);
- const planB = route("gpt-5", { "gpt-*": ["openai"] });
+ const planA = await route("gpt-5", { "gpt-*": ["openai"] }, undefined);
+ const planB = await route("gpt-5", { "gpt-*": ["openai"] });
expect(planA).toEqual(planB);
});
test("defaultProvider not consulted for explicit provider@model spec", async () => {
process.env.OPENROUTER_API_KEY = "or-test";
- const plan = await route("openrouter@gpt-5", DEFAULT_ROUTING_RULES, "xai");
+ const plan = await route("openrouter@gpt-5", {}, "xai");
expect(plan.kind).toBe("ok");
if (plan.kind !== "ok") return;
expect(plan.primary.provider).toBe("openrouter");
diff --git a/packages/cli/src/providers/swe-routing.test.ts b/packages/cli/src/providers/swe-routing.test.ts
index 505e27b4..a68e9009 100644
--- a/packages/cli/src/providers/swe-routing.test.ts
+++ b/packages/cli/src/providers/swe-routing.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, test } from "bun:test";
-import { DEFAULT_ROUTING_RULES } from "./default-routing-rules.js";
import { parseModelSpec } from "./model-parser.js";
+import { getProviderByName } from "./provider-definitions.js";
+import { gatherRouteCandidates } from "./route-candidates.js";
describe("SWE model routing", () => {
test("auto-detects bare swe-* names as Devin without marking them explicit", () => {
@@ -12,11 +13,22 @@ describe("SWE model routing", () => {
}
});
- test("routes swe-* only to Devin with no fallback", () => {
- const routes = DEFAULT_ROUTING_RULES["swe-*"];
+ test("Devin claims the swe-* namespace and gathering emits that route candidate", () => {
+ const devin = getProviderByName("devin")!;
+ expect(devin.nativeModelPatterns?.map(({ pattern }) => pattern.source)).toEqual(["^swe-"]);
- expect(routes).toEqual(["devin"]);
- expect(routes).toHaveLength(1);
+ const gathered = gatherRouteCandidates(
+ "swe-1.7",
+ `${import.meta.dir}/fixtures/intentionally-missing-catalog.json`
+ );
+ expect(gathered.candidates).toContainEqual({
+ provider: "devin",
+ wireId: "swe-1.7",
+ tier: "dynamic-subscription",
+ isVendorOwn: false,
+ price: { known: false, label: "unknown" },
+ source: "namespace-claim",
+ });
});
test("never auto-detects Devin's re-served vendor model collisions", () => {
diff --git a/packages/cli/src/providers/transport/vertex-discovery.test.ts b/packages/cli/src/providers/transport/vertex-discovery.test.ts
new file mode 100644
index 00000000..8537a2e0
--- /dev/null
+++ b/packages/cli/src/providers/transport/vertex-discovery.test.ts
@@ -0,0 +1,101 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { credentials } from "../../auth/credentials/authority.js";
+import { resetVertexProjectDiscovery } from "../../auth/vertex-auth.js";
+import { _clearVertexDiscoveryCache, discoverVertexProbeModel } from "./vertex-discovery.js";
+import { parseVertexModel } from "./vertex-oauth.js";
+
+const originalFetch = globalThis.fetch;
+const originalGetRequestAuth = credentials.getRequestAuth;
+const originalProject = process.env.VERTEX_PROJECT;
+const originalLocation = process.env.VERTEX_LOCATION;
+
+const listedModels = [
+ {
+ name: "publishers/google/models/gemini-3.8-flash",
+ launchStage: "GA",
+ publisherModelTemplate:
+ "projects/{project}/locations/{location}/publishers/google/models/gemini-3.8-flash",
+ },
+ {
+ name: "publishers/google/models/gemini-2.5-flash",
+ launchStage: "GA",
+ publisherModelTemplate:
+ "projects/{project}/locations/{location}/publishers/google/models/gemini-2.5-flash",
+ },
+];
+
+function installHttpFixture(statuses: Record<string, number>): string[] {
+ const requests: string[] = [];
+ globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
+ requests.push(url);
+
+ if (url.endsWith("/v1beta1/publishers/google/models")) {
+ expect(init?.method).toBe("GET");
+ expect(new Headers(init?.headers).get("x-goog-user-project")).toBe("vertex-test-project");
+ return Response.json({ publisherModels: listedModels });
+ }
+
+ const match = url.match(/\/models\/([^/:]+):countTokens$/);
+ if (!match) throw new Error(`unexpected Vertex discovery request: ${url}`);
+ expect(init?.method).toBe("POST");
+ const status = statuses[match[1]] ?? 200;
+ return new Response(status === 200 ? "{}" : `fixture HTTP ${status}`, { status });
+ }) as typeof fetch;
+ return requests;
+}
+
+describe.serial("Vertex discovery confirmation", () => {
+ beforeEach(() => {
+ process.env.VERTEX_PROJECT = "vertex-test-project";
+ process.env.VERTEX_LOCATION = "us-central1";
+ resetVertexProjectDiscovery();
+ _clearVertexDiscoveryCache();
+ credentials.getRequestAuth = async () => ({
+ headers: { Authorization: "Bearer offline-vertex-test-token" },
+ });
+ });
+
+ afterEach(() => {
+ globalThis.fetch = originalFetch;
+ credentials.getRequestAuth = originalGetRequestAuth;
+ if (originalProject === undefined) delete process.env.VERTEX_PROJECT;
+ else process.env.VERTEX_PROJECT = originalProject;
+ if (originalLocation === undefined) delete process.env.VERTEX_LOCATION;
+ else process.env.VERTEX_LOCATION = originalLocation;
+ resetVertexProjectDiscovery();
+ _clearVertexDiscoveryCache();
+ });
+
+ test("a 404 removes a listed model and the returned id round-trips", async () => {
+ const requests = installHttpFixture({ "gemini-3.8-flash": 404 });
+
+ const result = await discoverVertexProbeModel();
+ expect(result).toEqual({ model: "gemini-2.5-flash" });
+ expect(parseVertexModel(result.model!)).toEqual({
+ publisher: "google",
+ model: "gemini-2.5-flash",
+ });
+ expect(requests.filter((url) => url.endsWith(":countTokens"))).toHaveLength(2);
+ });
+
+ for (const status of [429, 503]) {
+ test(`HTTP ${status} keeps the candidate because the confirmation is inconclusive`, async () => {
+ installHttpFixture({ "gemini-3.8-flash": status });
+
+ expect(await discoverVertexProbeModel()).toEqual({ model: "gemini-3.8-flash" });
+ });
+ }
+
+ test("exclude returns the next confirmed candidate without re-listing", async () => {
+ const requests = installHttpFixture({});
+
+ expect(await discoverVertexProbeModel()).toEqual({ model: "gemini-3.8-flash" });
+ expect(await discoverVertexProbeModel(new Set(["gemini-3.8-flash"]))).toEqual({
+ model: "gemini-2.5-flash",
+ });
+ expect(
+ requests.filter((url) => url.endsWith("/v1beta1/publishers/google/models"))
+ ).toHaveLength(1);
+ });
+});