Skip to content

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

refactor(routing): extract proxyRouteDecision from the proxy gate

Jack Rudenko123be2bf6f39
diff --git a/packages/cli/src/auth/credentials/prehydrate.test.ts b/packages/cli/src/auth/credentials/prehydrate.test.ts
index 9ea992ca..50854f5a 100644
--- a/packages/cli/src/auth/credentials/prehydrate.test.ts
+++ b/packages/cli/src/auth/credentials/prehydrate.test.ts
@@ -1,7 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, mock } from "bun:test";
import { PROVIDER_TO_PREFIX } from "../../providers/auto-route.js";
import { parseModelChain, parseModelSpec } from "../../providers/model-parser.js";
-import { nativeRouteFor } from "../../providers/native-route.js";
+import { nativeRouteFor, proxyRouteDecision } from "../../providers/native-route.js";
import type { Route } from "../../providers/routing-rules.js";
import { __resetSniffForTests } from "./op-source.js";
import {
@@ -494,3 +494,61 @@ describe("pre-route target characterization", () => {
}
});
});
+
+describe("proxyRouteDecision consistency", () => {
+ const rows: Array<{
+ target: string;
+ type: ReturnType<typeof proxyRouteDecision>["type"];
+ }> = [
+ { target: "opus", type: "native" },
+ { target: "opus[1m]", type: "native" },
+ { target: "opusplan", type: "native" },
+ { target: "best", type: "native" },
+ { target: "internal", type: "native" },
+ { target: "claude-opus-4-6[1m]", type: "native" },
+ { target: "claude-haiku-4-5-20251001", type: "native" },
+ { target: "anthropic/claude-opus-5", type: "explicit" },
+ { target: "poe:x", type: "poe" },
+ { target: "kc@kimi-k3", type: "explicit" },
+ { target: "o4-mini", type: "native" },
+ { target: "no-such-model-xyz", type: "native" },
+ { target: "kimi-k3", type: "bare" },
+ { target: "openai/gpt-5", type: "bare" },
+ { target: "foo/bar", type: "bare" },
+ { target: "", type: "native" },
+ { target: "@model", type: "native" },
+ ];
+
+ it.each(rows)("classifies $target as $type", ({ target, type }) => {
+ expect(proxyRouteDecision(target).type).toBe(type);
+ });
+
+ it.each(rows)("keeps nativeRouteFor consistent for $target", ({ target }) => {
+ const decision = proxyRouteDecision(target);
+ expect(nativeRouteFor(target) !== null).toBe(decision.type === "native");
+ });
+
+ it.each(rows)("calls pinSpecFor's router exactly when $target is bare", async ({ target }) => {
+ const router = mock(async () => ({
+ kind: "no-route" as const,
+ reason: "decision consistency router",
+ }));
+ const decision = proxyRouteDecision(target);
+
+ await pinSpecFor(target, router);
+
+ expect(router).toHaveBeenCalledTimes(decision.type === "bare" ? 1 : 0);
+ if (decision.type === "bare") expect(router).toHaveBeenCalledWith(target);
+ });
+
+ it("keeps anthropic/<id> explicit when the parser attributes it to native-anthropic", () => {
+ expect(proxyRouteDecision("anthropic/claude-opus-5")).toEqual({
+ type: "explicit",
+ provider: "openrouter",
+ model: "anthropic/claude-opus-5",
+ spec: "anthropic/claude-opus-5",
+ via: "vendor-qualified-id",
+ });
+ expect(nativeRouteFor("anthropic/claude-opus-5")).toBeNull();
+ });
+});
diff --git a/packages/cli/src/auth/credentials/prehydrate.ts b/packages/cli/src/auth/credentials/prehydrate.ts
index 793f3b07..f5a9e927 100644
--- a/packages/cli/src/auth/credentials/prehydrate.ts
+++ b/packages/cli/src/auth/credentials/prehydrate.ts
@@ -100,7 +100,8 @@ import { loadConfig } from "../../profile-config.js";
import { PROVIDER_TO_PREFIX } from "../../providers/auto-route.js";
import { ensureCatalogReady } from "../../providers/catalog-client.js";
import { ensureEndpointsRegistered } from "../../providers/endpoint-registration.js";
-import { MODEL_CHAIN_SEPARATOR, parseModelSpec } from "../../providers/model-parser.js";
+import { MODEL_CHAIN_SEPARATOR } from "../../providers/model-parser.js";
+import { proxyRouteDecision } from "../../providers/native-route.js";
import { getOpFailures } from "../../providers/onepassword.js";
import { validateApiKeysForModels } from "../../providers/provider-resolver.js";
import type { Route, RoutePlan } from "../../providers/routing-rules.js";
@@ -227,9 +228,10 @@ async function pinRoutes(
/**
* Would the CHILD route this name at all?
*
- * This mirrors the child's own gate (`proxy-server.ts` step 2c) exactly. Pinning
- * a name the child would not have routed does not just waste a `route()` call —
- * it CHANGES the child's behaviour, which the pin must never do:
+ * This asks the child's own gate (`proxy-server.ts` step 2c), `proxyRouteDecision`,
+ * so the two cannot drift: only a `bare` decision is routed. Pinning a name the
+ * child would not have routed does not just waste a `route()` call — it CHANGES
+ * the child's behaviour, which the pin must never do:
*
* - **explicit spec** (`gc@glm-5`, `or@x/y`, `[email protected]:3`, a URL) —
* nothing to decide, the child already skips routing. Unconditional and
@@ -244,13 +246,10 @@ async function pinRoutes(
* `--model or@opus` and send a native model through OpenRouter. `team`
* screens these out upstream in `setupSession`, but `create_session` does
* not.
- * - **`poe:` models** — same gate, same reason (`isPoeModel` in
- * proxy-server.ts is a local closure; the test is just the prefix).
+ * - **`poe:` models** — same gate, same reason.
*/
function isRoutablyPinnable(model: string): boolean {
- if (model.startsWith("poe:")) return false;
- const parsed = parseModelSpec(model);
- return !parsed.isExplicitProvider && parsed.provider !== "native-anthropic";
+ return proxyRouteDecision(model).type === "bare";
}
/**
diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts
index 862a22f8..440c5bd1 100644
--- a/packages/cli/src/cli.ts
+++ b/packages/cli/src/cli.ts
@@ -58,6 +58,7 @@ import { latestAnthropicTierModelId } from "./providers/catalog-client.js";
import { claudeCodeTierAlias, normalizeNativeModelSpec } from "./providers/claude-code-aliases.js";
import { ensureEndpointsRegistered } from "./providers/endpoint-registration.js";
import { parseModelChain, parseModelSpec } from "./providers/model-parser.js";
+import { proxyRouteDecision } from "./providers/native-route.js";
import { fetchOllamaModels } from "./providers/ollama-discovery.js";
import { type ProbeResult, describeProbeState } from "./providers/probe-live.js";
import { pinProbeModelSpec, probeProviderRoute } from "./providers/probe-runner.js";
@@ -1449,8 +1450,19 @@ async function probeModelRouting(
/** Build chain + credential data for a single model (shared by both paths) */
function buildModelChain(modelInput: string) {
const parsed = parseModelSpec(modelInput);
+ // The proxy's own pre-route decision picks the branch below.
+ //
+ // A vendor-qualified `anthropic/<id>` takes the native branch, as it always
+ // has in `--probe`, although the proxy sends it to OpenRouter with the id
+ // unchanged (its `vendor-qualified-id` decision). That is a known divergence
+ // from the proxy, kept so that reading the decision changes no probe output.
+ const decision = proxyRouteDecision(modelInput);
+ const isDirectSpec = decision.type === "explicit" && decision.via === "model-spec";
+ const isNativeBranch =
+ decision.type === "native" ||
+ (decision.type === "explicit" && decision.via === "vendor-qualified-id");
const chain = (() => {
- if (parsed.isExplicitProvider) {
+ if (isDirectSpec) {
return {
routes: [] as FallbackRoute[],
source: "direct" as const,
@@ -1465,9 +1477,7 @@ async function probeModelRouting(
// the "*" catch-all → openrouter (which produced the wrong "no live
// route"). We pin the default Opus model so the probe sends a real
// request through the passthrough like any other link.
- // NOTE: mirrors the upstream proxy precedence; a later routing worktree
- // may fold this into a shared helper.
- if (parsed.provider === "native-anthropic") {
+ if (isNativeBranch) {
// Substitute a concrete id ONLY for a Claude Code TIER ALIAS.
//
// `parseModelSpec` sends every unrecognised bare name here, so this
diff --git a/packages/cli/src/providers/native-route.ts b/packages/cli/src/providers/native-route.ts
index f45553d2..f266b229 100644
--- a/packages/cli/src/providers/native-route.ts
+++ b/packages/cli/src/providers/native-route.ts
@@ -1,13 +1,14 @@
/**
- * The native-passthrough answer that `route()` cannot give.
+ * The native-passthrough answer that `route()` cannot give, and the proxy's
+ * pre-route decision that produces it.
*
* A bare Claude name (`claude-opus-5`, `opus`, `internal`) is served by the
* proxy's native branch on the harness's own Claude Code auth. `native-anthropic`
* has no credential store — on purpose, it is not a remote provider — so
* `route()`'s credential filter drops it and the chain degrades to OpenRouter.
- * The proxy avoids that by checking `parsed.provider !== "native-anthropic"`
- * BEFORE it ever routes (proxy-server.ts). Every other caller that consults
- * `route()` for a bare name must make the same check first, or it reports a
+ * The proxy avoids that by asking {@link proxyRouteDecision} BEFORE it ever
+ * routes (proxy-server.ts step 2c). Every other caller that consults `route()`
+ * for a bare name must ask the same question first, or it reports a
* subscription model as "no route" / "OpenRouter, metered" — which is what the
* MCP `preflight` tool and the TUI route probe did.
*
@@ -36,19 +37,80 @@ export interface NativeRoute {
}
/**
- * Non-null only for a BARE name (no `@`, no `/`) that `parseModelSpec` attributes
- * to native-anthropic — the same condition the proxy's native branch applies.
+ * What the proxy does with a target before `route()` could see it.
+ *
+ * Only `bare` reaches `route()`. The other three are served without a routing
+ * chain, by the proxy steps that follow its gate.
*/
-export function nativeRouteFor(model: string): NativeRoute | null {
- // Mirror proxy-server.ts's native branch EXACTLY:
- // const isNative = !target.includes("/") && !hasExplicitProvider;
- // A slash-qualified id (`anthropic/claude-opus-5`) matches native-anthropic's
- // `/^anthropic\//i` pattern in parseModelSpec, but the proxy does not serve it
- // natively — it goes to OpenRouter, metered. Reporting it native here would be
- // the same lie this helper exists to remove, in the other direction.
- if (model.includes("/")) return null;
- const parsed = parseModelSpec(model);
- if (parsed.isExplicitProvider || parsed.provider !== "native-anthropic") return null;
+export type ProxyRouteDecision =
+ /** Served on Claude Code's own auth by the native passthrough. */
+ | { type: "native"; route: NativeRoute }
+ /**
+ * No routing chain. `spec` is the target verbatim, the string the proxy carries
+ * past its gate. `via: "vendor-qualified-id"` is `anthropic/<id>`: it matches
+ * native-anthropic's `/^anthropic\//i` pattern, yet the proxy never serves it
+ * natively (its native branch refuses any `/`), so it reaches the OpenRouter
+ * handler with the id unchanged.
+ */
+ | {
+ type: "explicit";
+ provider: string;
+ model: string;
+ spec: string;
+ via: "model-spec" | "vendor-qualified-id";
+ }
+ /** `poe:<id>`, served by the Poe handler. `model` is the id without the prefix. */
+ | { type: "poe"; model: string }
+ /** `route()` decides. `model` is the parsed name: a known `vendor/` is stripped. */
+ | { type: "bare"; model: string };
+
+/** The prefix the proxy's `isPoeModel` tests, case-sensitively, as it always has. */
+const POE_PREFIX = "poe:";
+
+/**
+ * The proxy's gate (proxy-server.ts step 2c) as one function. The proxy, the
+ * native test below, prehydrate's pin and `--probe` all read this, so none of
+ * them can disagree with the proxy about which names reach `route()`.
+ *
+ * The checks run in the order the proxy applies them: an explicit spec (which
+ * covers `provider@model`, a URL and a legacy prefix), then `poe:`, then a name
+ * the parser attributes to native-anthropic, then everything else.
+ */
+export function proxyRouteDecision(target: string): ProxyRouteDecision {
+ const parsed = parseModelSpec(target);
+ if (parsed.isExplicitProvider) {
+ return {
+ type: "explicit",
+ provider: parsed.provider,
+ model: parsed.model,
+ spec: target,
+ via: "model-spec",
+ };
+ }
+ if (target.startsWith(POE_PREFIX)) {
+ return { type: "poe", model: target.slice(POE_PREFIX.length) };
+ }
+ if (parsed.provider === "native-anthropic") {
+ // A slash-qualified id (`anthropic/claude-opus-5`) matches native-anthropic's
+ // `/^anthropic\//i` pattern in parseModelSpec, but the proxy does not serve it
+ // natively — its native branch is `!target.includes("/") && !hasExplicitProvider`,
+ // so it goes to OpenRouter, metered. Calling it native would be the same lie
+ // the native test exists to remove, in the other direction.
+ if (target.includes("/")) {
+ return {
+ type: "explicit",
+ provider: "openrouter",
+ model: target,
+ spec: target,
+ via: "vendor-qualified-id",
+ };
+ }
+ return { type: "native", route: nativeRouteOf(target) };
+ }
+ return { type: "bare", model: parsed.model };
+}
+
+function nativeRouteOf(model: string): NativeRoute {
return {
provider: "native-anthropic",
modelSpec: normalizeNativeModelSpec(model),
@@ -56,3 +118,12 @@ export function nativeRouteFor(model: string): NativeRoute | null {
isTierAlias: claudeCodeTierAlias(model) !== null,
};
}
+
+/**
+ * Non-null only for a BARE name (no `@`, no `/`) that `parseModelSpec` attributes
+ * to native-anthropic — the proxy's `native` decision.
+ */
+export function nativeRouteFor(model: string): NativeRoute | null {
+ const decision = proxyRouteDecision(model);
+ return decision.type === "native" ? decision.route : null;
+}
diff --git a/packages/cli/src/proxy-server.ts b/packages/cli/src/proxy-server.ts
index ae24ef65..c2cc69b1 100644
--- a/packages/cli/src/proxy-server.ts
+++ b/packages/cli/src/proxy-server.ts
@@ -40,6 +40,7 @@ import {
getCustomEndpointResult,
} from "./providers/endpoint-registration.js";
import { parseModelSpec } from "./providers/model-parser.js";
+import { proxyRouteDecision } from "./providers/native-route.js";
import { describeMissingCredential } from "./providers/provider-definitions.js";
import { createHandlerForProvider } from "./providers/provider-profiles.js";
import {
@@ -787,13 +788,11 @@ export async function createProxyServer(
// When no explicit provider@ prefix is given, consult the routing engine
// (defaults + user overrides merged in loadRoutingRules), filter to
// credentialed providers, and wrap them in a FallbackHandler.
+ // `proxyRouteDecision` IS this gate: only a `bare` target is routed. Every
+ // other decision falls through to steps 3-7 below.
{
- const parsedForFallback = parseModelSpec(target);
- if (
- !parsedForFallback.isExplicitProvider &&
- parsedForFallback.provider !== "native-anthropic" &&
- !isPoeModel(target)
- ) {
+ const decision = proxyRouteDecision(target);
+ if (decision.type === "bare") {
const cacheKey = `fallback:${target}`;
if (fallbackHandlerCache.has(cacheKey)) {
return fallbackHandlerCache.get(cacheKey)!;
@@ -802,7 +801,7 @@ export async function createProxyServer(
// Ensure catalog is warm before route() builds OpenRouter modelSpecs.
await ensureCatalogReady(5000);
- const plan = await route(parsedForFallback.model, effectiveRoutingRules);
+ const plan = await route(decision.model, effectiveRoutingRules);
if (plan.kind === "ok") {
const chain = [plan.primary, ...plan.fallbacks];
const candidates: FallbackCandidate[] = [];
@@ -826,7 +825,7 @@ export async function createProxyServer(
if (!options.quiet && candidates.length > 1) {
logStderr(
- `[Route] ${candidates.length} providers for ${parsedForFallback.model}: ${candidates.map((c) => c.name).join(" → ")}`
+ `[Route] ${candidates.length} providers for ${decision.model}: ${candidates.map((c) => c.name).join(" → ")}`
);
}
return resultHandler;