Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
fix(probe): show the chain route() calculates, with dropped candidates
Jack Rudenkod28cb1c11684
diff --git a/ai-docs/architecture/routing.md b/ai-docs/architecture/routing.mdindex ccc42f44..7d205586 100644--- a/ai-docs/architecture/routing.md+++ b/ai-docs/architecture/routing.md@@ -82,6 +82,26 @@ on stderr and keeps the `kept` candidates as its plan.provider in that provider's own spelling (see below).6. Primary + fallbacks.+**What `--probe` shows is that explanation, not a chain of its own.** It used to rebuild one+(`buildModelChain`): no credential filter, no availability filter, and a native test without+`route()`'s `/` check, so it probed hops a request never used and called `anthropic/<id>`+native. Now `chain` is the `kept` candidates in `route()`'s order (`[]` still means no route,+and an explicit target is a one-item chain), `dropped[]` lists every other candidate with its+outcome, and only kept candidates are probed (`probeTargets`, `providers/probe-runner.ts`).+Three consequences to know before reading its output:++- **A native name is one link, never probed** (`notProbed: "native-auth"`,+ `NATIVE_NOT_PROBED`). The native handler forwards the inbound Claude Code header, which a+ probe from this process does not have; substituting `ANTHROPIC_API_KEY` tested a different+ credential from the one a session uses.+- **`--no-probe` still asks providers.** The availability filter is part of `route()`, so an+ account's dynamic models catalog is read for each credentialed candidate that declares+ discovery (in memory, five minutes). `--no-probe` skips the model requests only.+- **The parser's provider is not a routing decision.** For a bare non-Claude name it is+ `auto-route`. It stays in `--probe --json` as `nativeProvider` and is never rendered: card+ headings and leaderboards name the first kept hop, or the explanation line when there is+ none.+**No catalog means local only.** With no readable catalog a bare name returns a no-route naming`claudish --models-refresh`. It is never guessed at `openrouter@<name>`: that sends an idnobody published to a metered gateway, and a RENAMED id looks identical.diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.tsindex 560365e5..0c912471 100644--- a/packages/cli/src/cli.ts+++ b/packages/cli/src/cli.ts@@ -30,6 +30,14 @@ import {} from "./model-loader.js";import { parseModelParams } from "./model-params.js";import { compareByReleaseDateDesc } from "./model-selector.js";+import {+ type CredentialLookup,+ type ProbeChainLink,+ type ProbeDroppedLink,+ probeChainFrom,+ resultLinksFrom,+ routingFieldsFrom,+} from "./probe/probe-chain.js";import {type ModelResult as PrintableModelResult,printProbeResults,@@ -41,34 +49,24 @@ import type {ProbeStepState,} from "./probe/probe-tui-app.js";import { startProbeTui } from "./probe/probe-tui-runtime.js";-import {- getModelMapping,- isLocalProviderEnabled,- loadConfig,- loadLocalConfig,- readProOnUltracode,-} from "./profile-config.js";+import { getModelMapping, loadConfig, readProOnUltracode } from "./profile-config.js";import { API_KEY_MAP } from "./providers/api-key-map.js";import { type KeyProvenance, resolveCredentialProvenance } from "./providers/api-key-provenance.js";-import type { FallbackRoute } from "./providers/auto-route.js";-import { latestAnthropicTierModelId } from "./providers/catalog-client.js";-import { claudeCodeTierAlias, normalizeNativeModelSpec } from "./providers/claude-code-aliases.js";+import { 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 { NATIVE_NOT_PROBED } 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";+import { type ProbeResult, describeProbeState, probeLink } from "./providers/probe-live.js";+import { type ProbeTarget, describeDropped, probeTargets } from "./providers/probe-runner.js";import { BUILTIN_PROVIDERS, getProviderByName } from "./providers/provider-definitions.js";import { resolveProviderSlug } from "./providers/provider-slug-resolve.js";import { nativeProviderForVendor } from "./providers/route-candidates.js";import {- buildCatalogChain,- buildRoutingChain,- effectiveDefaultProvider,- hasCredentialsForProvider,- loadRoutingRules,- matchRoutingRule,+ type RouteExplanation,+ type RouteWarning,+ type RuleScope,+ explainRoute,} from "./providers/routing-rules.js";import { setRecoveryFlagOverrides } from "./recovery/settings.js";import { cliAnsi } from "./theme/ansi.js";@@ -1339,11 +1337,18 @@ async function printVersion(): Promise<void> {}/**- * Probe model routing — show the fallback chain for each model.- * Warm caches first, then display a table of how each model would be routed.+ * Probe model routing — show the routing chain `route()` calculates for each+ * model, and probe its hops.+ *+ * The chain comes from `explainRoute`, the function `route()` itself is derived+ * from, so `--probe` shows exactly the chain a request uses: the kept candidates+ * in order, then the candidates the credential, availability and membership+ * filters dropped, each with its outcome. Only kept candidates are probed+ * (`probeTargets`). A native link is never probed: it is served on Claude Code's+ * own auth, which this process cannot forward (`NATIVE_NOT_PROBED`).** Two paths:- * - JSON path (--json): runs existing batch logic unchanged, prints JSON to stdout+ * - JSON path (--json): prints the decisions as JSON to stdout* - TUI path (interactive): live-updating progress bars via OpenTUI React on stderr*/async function probeModelRouting(@@ -1351,46 +1356,47 @@ async function probeModelRouting(jsonOutput: boolean,options: { live: boolean; timeoutMs: number } = { live: true, timeoutMs: 40000 }): Promise<void> {- // Shared types for both paths+ type Wiring = {+ formatAdapter: string;+ declaredStreamFormat: string;+ modelTranslator: string;+ contextWindow: number;+ supportsVision: boolean;+ transportOverride: string | null;+ effectiveStreamFormat: string;+ };++ /** One model in `--probe --json`: the routing decision, as `explainRoute` made it. */interface ChainProbe {model: string;+ /**+ * The parser's provider. Not a routing decision — a bare non-Claude name+ * reads `auto-route` here — so it is reported in JSON only and never rendered.+ */nativeProvider: string;+ /** An explicit target: `provider@model`, `poe:<id>` or `anthropic/<id>`. */isExplicit: boolean;- routingSource: "direct" | "custom-rules" | "auto-chain";+ routingSource: RouteExplanation["source"];+ /** `describeRouteExplanation`: the one line `--probe` and the config TUI share. */+ routingExplanation: string;+ via?: RouteExplanation["via"];matchedPattern?: string;- chain: Array<{- provider: string;- displayName: string;- modelSpec: string;- hasCredentials: boolean;- credentialHint?: string;- provenance?: KeyProvenance;- probe?: ProbeResult;- }>;+ ruleScope?: RuleScope;+ catalog?: RouteExplanation["catalog"];+ fallbackWithheld?: RouteExplanation["fallbackWithheld"];+ outcome: RouteExplanation["outcome"];+ warnings: RouteWarning[];+ /** The kept hops in `route()`'s order; a native target's one not-probed link. `[]` = no route. */+ chain: ProbeChainLink[];+ /** Every other candidate, in chain order, with its outcome. Never probed. */+ dropped: ProbeDroppedLink[];+ /** An explicit target's probe, for readers that predate its one-item chain. */directProbe?: ProbeResult;- wiring?: {- formatAdapter: string;- declaredStreamFormat: string;- modelTranslator: string;- contextWindow: number;- supportsVision: boolean;- transportOverride: string | null;- effectiveStreamFormat: string;- };+ wiring?: Wiring;}type LiveProxy = { url: string; shutdown: () => Promise<void> };- // Snapshot user-defined routing keys so we can label matches as- // "custom-rules" vs "auto-chain" in --probe output. Every rule- // `loadRoutingRules()` returns is now the user's own — there is no shipped- // table left to merge — so this set and that one have the same keys; the- // snapshot stays because the labelling reads more clearly for it.- const userRoutingKeys = new Set<string>([- ...Object.keys(loadConfig().routing ?? {}),- ...Object.keys(loadLocalConfig()?.routing ?? {}),- ]);-/*** The remedy a credential-less row shows.*@@ -1409,361 +1415,98 @@ async function probeModelRouting(return envVar;}- /** The same remedy where no provenance record has been built yet. */- function credentialHintFor(- provider: string,- envVar: string | undefined,- aliases: string[] | undefined- ): string | undefined {- if (!envVar) return undefined;- return credentialHintFrom(resolveCredentialProvenance(provider, envVar, aliases), envVar);- }-- /** Build chain + credential data for a single model (shared by both paths) */- function buildModelChain(modelInput: string) {- const parsed = parseModelSpec(modelInput);- // 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 (isDirectSpec) {- return {- routes: [] as FallbackRoute[],- source: "direct" as const,- matchedPattern: undefined,- };- }- // Native-anthropic passthrough: a bare name with no vendor "/" and no- // provider "@" (e.g. "internal") resolves to native-anthropic — the- // default Claude Code route. The real proxy returns nativeHandler for- // this (proxy-server.ts) BEFORE the routing engine runs, so the probe- // must mirror that here rather than letting matchRoutingRule send it to- // 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.- if (isNativeBranch) {- // Substitute a concrete id ONLY for a Claude Code TIER ALIAS.- //- // `parseModelSpec` sends every unrecognised bare name here, so this- // branch receives two different things. `opus` / `sonnet` / `internal`- // are Claude Code's own selectors: the API rejects them as model ids- // while the ROUTE is healthy, so they must be resolved to something real- // or the probe reports a failure that does not exist. A concrete name- // like `swe-1.7` or a typo is the opposite case — `native-handler.ts`- // forwards `payload.model` VERBATIM at runtime and Anthropic answers 404,- // so substituting here made `--probe` report `live` for a model that- // could not serve one request.- //- // That substitution is why `swe-1.7` "probed byte-identically to a- // nonsense string": both were rewritten to the same working id before- // the request went out, erasing the difference the probe exists to show.- // Unknown names now go through untouched and the API answers for itself.- const tier = claudeCodeTierAlias(parsed.model);- // The literal is a cold-catalog last resort (first run, no cache, no env- // override). It replaced `claude-opus-4-1`, which sat here under a- // comment asserting it was "the current Opus alias the API accepts- // (verified against api.anthropic.com)" and that `claude-opus-4-8` was- // rejected — measured 2026-08-18, that id returns 404 and 4-8 returns- // 200, so both halves had rotted. A verification note carries no expiry- // date, which is the failure the no-hardcoded-model-data rule prevents.- const tierEnv: Record<string, string | undefined> = {- opus:- process.env[ENV.CLAUDISH_MODEL_OPUS] || process.env[ENV.ANTHROPIC_DEFAULT_OPUS_MODEL],- sonnet:- process.env[ENV.CLAUDISH_MODEL_SONNET] ||- process.env[ENV.ANTHROPIC_DEFAULT_SONNET_MODEL],- haiku:- process.env[ENV.CLAUDISH_MODEL_HAIKU] || process.env[ENV.ANTHROPIC_DEFAULT_HAIKU_MODEL],- };- const opusModel = tier- ? tierEnv[tier] || latestAnthropicTierModelId(tier) || "claude-opus-5"- : parsed.model;- // IMPORTANT: pin a BARE model name (no `provider@`). The proxy resolves- // the native passthrough via `isNative` = no "/" AND no "@" — pinning- // `native-anthropic@...` would set hasExplicitProvider=true and DEFEAT- // the native branch (the request would 400 / fall to OpenRouter). So- // pinProbeModelSpec must keep this bare; the proxy then returns the- // nativeHandler (default Claude Code / Opus).- return {- routes: [- {- provider: "native-anthropic",- modelSpec: opusModel,- displayName: tier ? `Claude Code (${tier})` : "Claude Code",- },- ] as FallbackRoute[],- source: "auto-chain" as const,- matchedPattern: undefined,- };- }- // Only the USER's rules now — the shipped table is gone, so most models- // match nothing here and are routed from the catalog instead.- const routingRules = loadRoutingRules();- const matched = matchRoutingRule(parsed.model, routingRules);- if (matched) {- const matchedPattern = Object.keys(routingRules).find((k) => {- if (k === parsed.model) return true;- if (k.includes("*")) {- const star = k.indexOf("*");- const prefix = k.slice(0, star);- const suffix = k.slice(star + 1);- return parsed.model.startsWith(prefix) && parsed.model.endsWith(suffix);- }- return false;- });- const isUserKey = !!matchedPattern && userRoutingKeys.has(matchedPattern);- return {- routes: buildRoutingChain(matched, parsed.model),- source: isUserKey ? ("custom-rules" as const) : ("auto-chain" as const),- matchedPattern,- };- }- // No user rule: the SAME chain `routeBare` would assemble — gathered from- // the cloud models catalog, with the fallback hop appended. This used to- // read the shipped rules table; reproducing the gathering by hand here- // would be the second copy of a routing decision, and the two would- // disagree the first time either changed. `--probe` still owns the- // credential-provenance display below, which is why it builds a chain at- // all instead of calling `route()`. The fallback hop is `route()`'s too:- // `effectiveDefaultProvider()` reads the env variable before the config.- return {- routes: buildCatalogChain(parsed.model, effectiveDefaultProvider())- .routes as FallbackRoute[],- source: "auto-chain" as const,- matchedPattern: undefined,- };- })();-- const chainDetails = chain.routes.map((route) => {- const keyInfo = API_KEY_MAP[route.provider];- const providerDef = getProviderByName(route.provider);- let hasCredentials = false;- let credentialHint: string | undefined;- let provenance: KeyProvenance | undefined;-- if (route.provider === "native-anthropic") {- // The probe hits the Anthropic API DIRECTLY (api.anthropic.com) via the- // passthrough, so it needs a real ANTHROPIC_API_KEY. Without one we- // can't probe — surface that as a clean key-missing row (no request,- // no 400) telling the user what to set.- hasCredentials = !!process.env.ANTHROPIC_API_KEY;- if (!hasCredentials) {- credentialHint = "ANTHROPIC_API_KEY (required to probe Claude Code)";- }- } else if (providerDef?.isLocal) {- hasCredentials = isLocalProviderEnabled(route.provider);- if (!hasCredentials) {- credentialHint = "enable local provider in global config";- }- } else if (!keyInfo) {- hasCredentials = true;- } else if (!keyInfo.envVar) {- hasCredentials = true;- } else {- provenance = resolveCredentialProvenance(route.provider, keyInfo.envVar, keyInfo.aliases);- hasCredentials = provenance.hasValue;- if (!hasCredentials && keyInfo.aliases) {- hasCredentials = keyInfo.aliases.some((a) => !!process.env[a]);- }- if (!hasCredentials) {- credentialHint = credentialHintFrom(provenance, keyInfo.envVar);- }- }+ /**+ * Where `--probe` reads a provider's credential remedy and key provenance. The+ * credential DECISION is not here: `explainRoute` asked the credential+ * authority, exactly as `route()` does, and a dropped candidate carries its+ * verdict. This only names the key a user would set.+ */+ const probeCredentials: CredentialLookup = {+ hintFor(provider) {+ if (getProviderByName(provider)?.isLocal) return "enable local provider in global config";+ const keyInfo = API_KEY_MAP[provider];+ if (!keyInfo?.envVar) return undefined;+ return credentialHintFrom(+ resolveCredentialProvenance(provider, keyInfo.envVar, keyInfo.aliases),+ keyInfo.envVar+ );+ },+ provenanceFor(provider) {+ const keyInfo = API_KEY_MAP[provider];+ return keyInfo?.envVar+ ? resolveCredentialProvenance(provider, keyInfo.envVar, keyInfo.aliases)+ : undefined;+ },+ };- return {- provider: route.provider,- displayName: route.displayName,- modelSpec: route.modelSpec,- hasCredentials,- credentialHint,- provenance,- probe: undefined as ProbeResult | undefined,- };- });-- return { parsed, chain, chainDetails };+ /** One model's decision, its rows, and the hops a probe sends requests down. */+ interface ModelProbe {+ modelInput: string;+ explanation: RouteExplanation;+ chain: ProbeChainLink[];+ dropped: ProbeDroppedLink[];+ /** Each kept hop's probe target, beside the chain link its result lands on. */+ targets: Array<{ target: ProbeTarget; link: ProbeChainLink }>;}- const probeCredentialReadiness = new Map<string, boolean>();- async function credentialForProbe(provider: string): Promise<boolean> {- if (probeCredentialReadiness.has(provider)) return probeCredentialReadiness.get(provider)!;- const ready =- provider === "native-anthropic"- ? !!process.env.ANTHROPIC_API_KEY- : await hasCredentialsForProvider(provider);- probeCredentialReadiness.set(provider, ready);- return ready;+ /** The routing decision for one model (shared by both paths). */+ async function explainForProbe(modelInput: string): Promise<ModelProbe> {+ const explanation = await explainRoute(modelInput);+ const { chain, dropped } = probeChainFrom(explanation, probeCredentials);+ // Both are the kept candidates in chain order, so the i-th target is the+ // i-th link. A native target has one link and no targets.+ const targets = probeTargets(explanation).map((target, i) => ({ target, link: chain[i] }));+ return { modelInput, explanation, chain, dropped, targets };}- async function prepareModelChain(- modelInput: string- ): Promise<ReturnType<typeof buildModelChain>> {- const result = buildModelChain(modelInput);- await Promise.all(- result.chainDetails.map(async (link) => {- link.hasCredentials = await credentialForProbe(link.provider);- const keyInfo = API_KEY_MAP[link.provider];- if (keyInfo?.envVar)- link.provenance = resolveCredentialProvenance(- link.provider,- keyInfo.envVar,- keyInfo.aliases- );- link.credentialHint = link.hasCredentials- ? undefined- : link.provider === "native-anthropic"- ? "ANTHROPIC_API_KEY (required to probe Claude Code)"- : getProviderByName(link.provider)?.isLocal- ? "enable local provider in global config"- : credentialHintFrom(link.provenance, keyInfo?.envVar);+ /** One live request down one kept hop. `probeSpec` is final, so no second pinning. */+ function probeTarget(proxyUrl: string, target: ProbeTarget): Promise<ProbeResult> {+ return probeLink(+ proxyUrl,+ { provider: target.provider, modelSpec: target.probeSpec, hasCredentials: true },+ options.timeoutMs+ ).catch(+ (e): ProbeResult => ({+ state: "error",+ latencyMs: 0,+ errorMessage: String(e instanceof Error ? e.message : e),}));- if (result.chain.source === "direct") await credentialForProbe(result.parsed.provider);- return result;}- /**- * Routing-why one-liner shown on the right of each model header in the- * Details tab. Kept as a SINGLE function so a later routing worktree can swap- * the derivation in one place (the current buildModelChain has known bugs that- * a future worktree will reconcile — this only consumes its output).- */- function buildRoutingExplanation(- parsed: ReturnType<typeof parseModelSpec>,- chain: ReturnType<typeof buildModelChain>["chain"]- ): string {- if (parsed.provider === "native-anthropic") {- return "native passthrough · default Claude Code (Opus)";- }- if (chain.source === "direct") {- return `explicit · ${parsed.provider} (direct)`;- }- if (chain.source === "custom-rules" && chain.matchedPattern) {- return `custom-rules · matched \`${chain.matchedPattern}\``;- }- if (chain.source === "auto-chain") {- if (chain.matchedPattern && chain.matchedPattern !== "*") {- return `auto-chain · default rule \`${chain.matchedPattern}\``;- }- return "auto-chain · catch-all → openrouter";- }- return chain.source;- }-- /**- * The ONE chain entry an explicit `provider@model` address resolves to.- *- * `buildModelChain` returns `routes: []` for an explicit spec because there is- * no fallback chain to walk — it is pinned to a single provider. Emitting that- * raw made `--probe --json` report `chain: []` for a perfectly healthy model,- * with the real outcome hidden in `directProbe`. Anyone reading `chain` to- * decide routability concluded "dead route": `[email protected]` was filed as- * unroutable twice while it was serving 509-token replies.- *- * So an explicit address now yields a ONE-ITEM chain, and `[]` is reserved for- * its literal meaning — no provider can serve this, whether because the- * provider name resolves to nothing or because no fallback exists. Empty now- * says "no route" in both the bare and explicit cases instead of doubling as- * "not applicable here".- *- * Shared with `buildResultLinks` on purpose: the TUI row and the JSON chain- * disagreeing about the same address is the defect, not a rendering detail.- */- function buildDirectChainEntry(- parsed: ReturnType<typeof parseModelSpec>,- directProbe: ProbeResult | undefined- ): ReturnType<typeof buildModelChain>["chainDetails"] {- const providerDef = getProviderByName(parsed.provider);- const keyInfo = API_KEY_MAP[parsed.provider];- // Nothing known by this name — genuinely unroutable, so the chain stays- // empty and now MEANS empty.- if (!providerDef && !keyInfo) return [];-- const hasCredentials = probeCredentialReadiness.get(parsed.provider) ?? false;- const provenance = keyInfo?.envVar- ? resolveCredentialProvenance(parsed.provider, keyInfo.envVar, keyInfo.aliases)- : undefined;-- return [- {- provider: parsed.provider,- displayName: providerDef?.displayName ?? parsed.provider,- // The RESOLVED bare id, never the raw provider@-prefixed input, so the- // row never reads `provider@provider@model`.- modelSpec: parsed.model,- hasCredentials,- credentialHint: !hasCredentials- ? providerDef?.isLocal- ? "enable local provider in global config"- : credentialHintFrom(provenance, keyInfo?.envVar)- : undefined,- provenance,- probe: directProbe,- },- ];+ /** The JSON record for one model. */+ function chainProbeOf(probe: ModelProbe, wiring: Wiring | undefined): ChainProbe {+ const exp = probe.explanation;+ const directProbe = exp.source === "explicit" ? probe.chain[0]?.probe : undefined;+ return {+ model: probe.modelInput,+ nativeProvider: parseModelSpec(probe.modelInput).provider,+ isExplicit: exp.source === "explicit",+ routingSource: exp.source,+ routingExplanation: routingFieldsFrom(exp).routingExplanation,+ ...(exp.via ? { via: exp.via } : {}),+ ...(exp.matchedPattern !== undefined ? { matchedPattern: exp.matchedPattern } : {}),+ ...(exp.ruleScope ? { ruleScope: exp.ruleScope } : {}),+ ...(exp.catalog ? { catalog: exp.catalog } : {}),+ ...(exp.fallbackWithheld ? { fallbackWithheld: exp.fallbackWithheld } : {}),+ outcome: exp.outcome,+ warnings: exp.warnings,+ chain: probe.chain,+ dropped: probe.dropped,+ ...(directProbe ? { directProbe } : {}),+ ...(wiring ? { wiring } : {}),+ };}/**- * Build the provider-comparison links the Details tab renders. For EXPLICIT /- * direct models buildModelChain returns an empty chain (the probe lives in- * directProbe), so we synthesize a single link carrying that probe — the model- * still renders one row and the live-count derives from the SAME array as the- * rows. The model id is the RESOLVED bare id (parsed.model), never the raw- * provider@-prefixed input, so we never render `provider@provider@model`.+ * Compute wiring for the first kept hop. A native link has none to report: the+ * native passthrough forwards the request as is, through no adapter.*/- function buildResultLinks(- parsed: ReturnType<typeof parseModelSpec>,- chainDetails: ReturnType<typeof buildModelChain>["chainDetails"],- directProbe: ProbeResult | undefined- ): ProbeModelResult["links"] {- if (chainDetails.length === 0) {- // Explicit/direct model — one synthetic link from the native provider.- const directProviderDef = getProviderByName(parsed.provider);- const directKeyInfo = API_KEY_MAP[parsed.provider];- const directHasCreds = probeCredentialReadiness.get(parsed.provider) ?? false;- return [- {- provider: parsed.provider,- displayName: directProviderDef?.displayName ?? parsed.provider,- modelId: parsed.model,- hasCredentials: directHasCreds,- credentialHint: !directHasCreds- ? directProviderDef?.isLocal- ? "enable local provider in global config"- : credentialHintFor(parsed.provider, directKeyInfo?.envVar, directKeyInfo?.aliases)- : undefined,- probe: directProbe,- },- ];- }- return chainDetails.map((c) => ({- provider: c.provider,- displayName: c.displayName,- // Strip any redundant provider@ prefix so the row shows displayName + the- // resolved id only (e.g. "qwen/qwen3-coder", not "openrouter@qwen/…").- modelId: c.modelSpec.includes("@")- ? c.modelSpec.slice(c.modelSpec.indexOf("@") + 1)- : c.modelSpec,- hasCredentials: c.hasCredentials,- credentialHint: c.credentialHint,- probe: c.probe,- }));- }-- /** Compute wiring for the first-ready provider in a chain */async function computeWiring(- chainDetails: ReturnType<typeof buildModelChain>["chainDetails"],+ chain: ProbeChainLink[],parsedModel: string- ): Promise<ChainProbe["wiring"]> {- const firstReadyRoute = chainDetails.find((c) => c.hasCredentials);+ ): Promise<Wiring | undefined> {+ const firstReadyRoute = chain.find((c) => c.hasCredentials && !c.notProbed);if (!firstReadyRoute) return undefined;const providerName = firstReadyRoute.provider;@@ -1841,7 +1584,7 @@ async function probeModelRouting(};}- // ── JSON path: existing batch logic, completely unchanged output ──+ // ── JSON path: one record per model, printed to stdout ──if (jsonOutput) {const { DIM, YELLOW, RESET } = cliAnsi();@@ -1876,77 +1619,21 @@ async function probeModelRouting(const results: ChainProbe[] = [];for (const modelInput of models) {- const { parsed, chain, chainDetails } = await prepareModelChain(modelInput);-- // Direct probe- let directProbeResult: ProbeResult | undefined;- if (liveProxy && chain.source === "direct") {- const directKeyInfo = API_KEY_MAP[parsed.provider];- const directProviderDef = getProviderByName(parsed.provider);- const directHasCreds = await credentialForProbe(parsed.provider);- const directCredentialHint =- directProviderDef?.isLocal && !directHasCreds- ? "enable local provider in global config"- : credentialHintFor(parsed.provider, directKeyInfo?.envVar, directKeyInfo?.aliases);- directProbeResult = await probeProviderRoute(- liveProxy.url,- {- provider: parsed.provider,- modelSpec: modelInput,- hasCredentials: directHasCreds,- credentialHint: directCredentialHint,- },- options.timeoutMs- ).catch((e) => ({- state: "error" as const,- latencyMs: 0,- errorMessage: String(e instanceof Error ? e.message : e),- }));- }+ const probe = await explainForProbe(modelInput);- // Chain probes (batch)+ // Kept hops only. Dropped candidates and a native link are never probed.if (liveProxy) {+ const url = liveProxy.url;const probes = await Promise.all(- chainDetails.map((link) => {- return probeProviderRoute(- liveProxy!.url,- {- provider: link.provider,- modelSpec: link.modelSpec,- hasCredentials: link.hasCredentials,- credentialHint: link.credentialHint,- },- options.timeoutMs- ).catch((e) => ({- state: "error" as const,- latencyMs: 0,- errorMessage: String(e instanceof Error ? e.message : e),- }));- })+ probe.targets.map(({ target }) => probeTarget(url, target)));- for (let i = 0; i < chainDetails.length; i++) {- chainDetails[i].probe = probes[i];- }+ probe.targets.forEach(({ link }, i) => {+ link.probe = probes[i];+ });}- const wiring = await computeWiring(chainDetails, parsed.model);-- results.push({- model: modelInput,- nativeProvider: parsed.provider,- isExplicit: parsed.isExplicitProvider,- routingSource: chain.source,- matchedPattern: chain.matchedPattern,- // An explicit address resolves to exactly ONE route, so report it as a- // one-item chain rather than `[]`. `directProbe` stays for- // backwards-compatible readers.- chain:- chainDetails.length > 0- ? chainDetails- : buildDirectChainEntry(parsed, directProbeResult),- directProbe: directProbeResult,- wiring,- });+ const wiring = await computeWiring(probe.chain, probe.explanation.routedModel);+ results.push(chainProbeOf(probe, wiring));}console.log(JSON.stringify(results, null, 2));@@ -2013,12 +1700,7 @@ async function probeModelRouting(let liveProxy: LiveProxy | null = null;try {- // Step 1: Load routing rules- addStep("Loading routing rules", "running");- loadRoutingRules();- updateStep("Loading routing rules", "done");-- // Step 2: Start live proxy (if enabled)+ // Step 1: Start live proxy (if enabled)if (options.live) {addStep("Starting probe proxy", "running");try {@@ -2041,134 +1723,94 @@ async function probeModelRouting(}}- // Step 4: Build chains + credential checks+ // Step 2: The routing decision per model — explainRoute loads the rules+ // itself, so it can name the scope of the rule that matched.addStep("Resolving routing chains", "running");- const modelChains: Array<{- modelInput: string;- parsed: ReturnType<typeof parseModelSpec>;- chain: ReturnType<typeof buildModelChain>["chain"];- chainDetails: ReturnType<typeof buildModelChain>["chainDetails"];- }> = [];+ const modelProbes: ModelProbe[] = [];for (const modelInput of models) {- const { parsed, chain, chainDetails } = await prepareModelChain(modelInput);- modelChains.push({ modelInput, parsed, chain, chainDetails });+ modelProbes.push(await explainForProbe(modelInput));}updateStep("Resolving routing chains", "done");- // Step 5: Live probing with progress bars- const directProbeResults = new Map<string, ProbeResult>();-- if (liveProxy) {- // Collect all probe links across all models- const allLinks: Array<{- id: string;- displayName: string;- modelSpec: string;- provider: string;- pinnedSpec: string;- hasCredentials: boolean;- credentialHint?: string;- chainDetail: ReturnType<typeof buildModelChain>["chainDetails"][number] | null;- isDirect: boolean;- modelInput: string;- }> = [];-- for (const { modelInput, parsed, chain, chainDetails } of modelChains) {- if (chain.source === "direct") {- const directKeyInfo = API_KEY_MAP[parsed.provider];- const directProviderDef = getProviderByName(parsed.provider);- const directHasCreds = await credentialForProbe(parsed.provider);- const directCredentialHint =- directProviderDef?.isLocal && !directHasCreds- ? "enable local provider in global config"- : credentialHintFor(parsed.provider, directKeyInfo?.envVar, directKeyInfo?.aliases);- allLinks.push({- id: `${modelInput}:direct`,- displayName: parsed.provider,- modelSpec: modelInput,- provider: parsed.provider,- pinnedSpec: modelInput,- hasCredentials: directHasCreds,- credentialHint: directCredentialHint,- chainDetail: null,- isDirect: true,- modelInput,- });- }- for (const link of chainDetails) {- const pinnedSpec = pinProbeModelSpec(link);- allLinks.push({- id: `${modelInput}:${link.provider}`,- displayName: link.displayName,- modelSpec: pinnedSpec,- provider: link.provider,- pinnedSpec,- hasCredentials: link.hasCredentials,- credentialHint: link.credentialHint,- chainDetail: link,- isDirect: false,- modelInput,- });- }- }-- // Seed the store with waiting links- setLinks(- allLinks.map((l) => ({- id: l.id,- model: l.modelInput,- displayName: l.displayName,- modelSpec: l.modelSpec,- status: "waiting",- }))- );-- // Fire all probes concurrently, updating per-link state as results arrive- const probePromises = allLinks.map(async (link) => {- updateLink(link.id, { status: "probing", startTime: Date.now() });-- const result = await probeProviderRoute(- liveProxy!.url,- {- provider: link.provider,- modelSpec: link.modelSpec,- hasCredentials: link.hasCredentials,- credentialHint: link.credentialHint,- },- options.timeoutMs- ).catch(- (e): ProbeResult => ({- state: "error",- latencyMs: 0,- errorMessage: String(e instanceof Error ? e.message : e),- })- );-- if (result.state === "live") {- updateLink(link.id, {- status: "live",- endTime: Date.now(),- timing: result.timing,+ // Step 3: One row per link, per model: the kept hops (probed when a live+ // probe runs, otherwise not probed), the native link, then the dropped+ // candidates. Only the kept hops are ever sent a request.+ const liveRows: Array<{ id: string; target: ProbeTarget; link: ProbeChainLink }> = [];+ const rows: ProbeLinkState[] = [];+ for (const probe of modelProbes) {+ const model = probe.modelInput;+ probe.targets.forEach(({ target, link }, i) => {+ const id = `${model}:${i}:${target.provider}`;+ if (liveProxy) {+ liveRows.push({ id, target, link });+ rows.push({+ id,+ model,+ displayName: target.displayName,+ modelSpec: target.probeSpec,+ status: "waiting",});} else {- updateLink(link.id, {- status: "failed",- endTime: Date.now(),- error: describeProbeState(result),+ rows.push({+ id,+ model,+ displayName: target.displayName,+ modelSpec: target.probeSpec,+ status: "not-probed",+ tone: "ready",+ note: `○ ${link.label} · not probed (--no-probe)`,});}-- if (link.isDirect) {- directProbeResults.set(link.modelInput, result);- } else if (link.chainDetail) {- link.chainDetail.probe = result;- }});+ for (const link of probe.chain) {+ if (!link.notProbed) continue;+ rows.push({+ id: `${model}:native`,+ model,+ displayName: link.displayName,+ modelSpec: link.modelSpec,+ status: "not-probed",+ tone: "native",+ note: `◐ native — ${NATIVE_NOT_PROBED}`,+ });+ }+ probe.dropped.forEach((entry, i) => {+ rows.push({+ id: `${model}:dropped:${i}:${entry.provider}`,+ model,+ displayName: entry.displayName,+ modelSpec: entry.wireId,+ status: "not-probed",+ tone: "dropped",+ note: `– ${describeDropped(entry.outcome, entry.credentialHint)}`,+ });+ });+ }+ setLinks(rows);- await Promise.all(probePromises);+ // Step 4: Live probing with progress bars — every kept hop concurrently,+ // updating its row as its result arrives.+ if (liveProxy) {+ const url = liveProxy.url;+ await Promise.all(+ liveRows.map(async ({ id, target, link }) => {+ updateLink(id, { status: "probing", startTime: Date.now() });+ const result = await probeTarget(url, target);+ if (result.state === "live") {+ updateLink(id, { status: "live", endTime: Date.now(), timing: result.timing });+ } else {+ updateLink(id, {+ status: "failed",+ endTime: Date.now(),+ error: describeProbeState(result),+ });+ }+ link.probe = result;+ })+ );}- // Step 6: Compute wiring for each model while the progress UI is still up+ // Step 5: Compute wiring for each model while the progress UI is still up// (computeWiring does async imports we want to finish before the flip).// We build BOTH payloads from the same per-model data:// - `printable` (PrintableModelResult) feeds the non-TTY static printer@@ -2177,35 +1819,21 @@ async function probeModelRouting(const isLiveProbe = !!liveProxy;const printable: PrintableModelResult[] = [];const results: ProbeModelResult[] = [];- for (const { modelInput, parsed, chain, chainDetails } of modelChains) {- const wiring = await computeWiring(chainDetails, parsed.model);- const directProbe = directProbeResults.get(modelInput);+ for (const probe of modelProbes) {+ const wiring = await computeWiring(probe.chain, probe.explanation.routedModel);+ const fields = routingFieldsFrom(probe.explanation);printable.push({- model: modelInput,- nativeProvider: parsed.provider,- isExplicit: parsed.isExplicitProvider,- routingSource: chain.source,- matchedPattern: chain.matchedPattern,- chain: chainDetails.map((c) => ({- provider: c.provider,- displayName: c.displayName,- modelSpec: c.modelSpec,- hasCredentials: c.hasCredentials,- credentialHint: c.credentialHint,- provenance: c.provenance,- probe: c.probe,- })),- directProbe,+ model: probe.modelInput,+ ...fields,+ chain: probe.chain,+ dropped: probe.dropped,wiring,});results.push({- model: modelInput,- nativeProvider: parsed.provider,- isExplicit: parsed.isExplicitProvider,- routingSource: chain.source,- matchedPattern: chain.matchedPattern,- routingExplanation: buildRoutingExplanation(parsed, chain),- links: buildResultLinks(parsed, chainDetails, directProbe),+ model: probe.modelInput,+ isExplicit: probe.explanation.source === "explicit",+ ...fields,+ links: resultLinksFrom(probe.chain, probe.dropped),wiring,});}diff --git a/packages/cli/src/default-provider.test.ts b/packages/cli/src/default-provider.test.tsindex 6f44b739..51dc495c 100644--- a/packages/cli/src/default-provider.test.ts+++ b/packages/cli/src/default-provider.test.ts@@ -175,6 +175,12 @@ describe("resolveDefaultProvider precedence", () => {interface ProbeJson {chain: Array<{ provider: string }>;+ dropped: Array<{+ provider: string;+ position: "candidate" | "fallback";+ label: string;+ outcome: string;+ }>;}function sandboxedProbe(flagBeforeProbe: boolean, provider: string): ProbeJson {@@ -223,11 +229,29 @@ function sandboxedProbe(flagBeforeProbe: boolean, provider: string): ProbeJson {describe("--default-provider pre-scan reaches --probe", () => {test("uses poe when the flag appears before --probe", () => {- expect(sandboxedProbe(true, "poe").chain.map((entry) => entry.provider)).toEqual(["poe"]);+ const result = sandboxedProbe(true, "poe");+ expect([...result.chain, ...result.dropped].map((entry) => entry.provider)).toEqual(["poe"]);+ expect(result.dropped).toEqual([+ expect.objectContaining({+ provider: "poe",+ position: "fallback",+ label: "fallback",+ outcome: "no-credential",+ }),+ ]);});test("uses poe when the flag appears after the probed model", () => {- expect(sandboxedProbe(false, "poe").chain.map((entry) => entry.provider)).toEqual(["poe"]);+ const result = sandboxedProbe(false, "poe");+ expect([...result.chain, ...result.dropped].map((entry) => entry.provider)).toEqual(["poe"]);+ expect(result.dropped).toEqual([+ expect.objectContaining({+ provider: "poe",+ position: "fallback",+ label: "fallback",+ outcome: "no-credential",+ }),+ ]);});test("an empty flag value produces an empty chain", () => {diff --git a/packages/cli/src/mcp-server.ts b/packages/cli/src/mcp-server.tsindex 84676c09..7a2abadf 100644--- a/packages/cli/src/mcp-server.ts+++ b/packages/cli/src/mcp-server.ts@@ -45,7 +45,7 @@ import { findAvailablePort } from "./port-manager.js";import { ensureEndpointsRegistered } from "./providers/endpoint-registration.js";import { compareByReleaseDateDesc } from "./providers/model-ordering.js";import { isLocalProviderName } from "./providers/model-parser.js";-import { nativeRouteFor } from "./providers/native-route.js";+import { NATIVE_NOT_PROBED, nativeRouteFor } from "./providers/native-route.js";import { renderOpFailureBlock } from "./providers/onepassword.js";import { isReadyState, probeLink } from "./providers/probe-live.js";import { BUILTIN_PROVIDERS } from "./providers/provider-definitions.js";@@ -1099,7 +1099,7 @@ function defineTools(// auth, and that is all this process can say.nativeModels.push(model);rows.push(- `| \`${model}\` | ${native.displayName} | native | ${"not probed — served on Claude Code's own auth, which this process cannot forward"} | \`${native.modelSpec}\` |`+ `| \`${model}\` | ${native.displayName} | native | ${NATIVE_NOT_PROBED} | \`${native.modelSpec}\` |`);continue;}diff --git a/packages/cli/src/probe/probe-chain.ts b/packages/cli/src/probe/probe-chain.tsnew file mode 100644index 00000000..57d90c61--- /dev/null+++ b/packages/cli/src/probe/probe-chain.ts@@ -0,0 +1,227 @@+/**+ * `--probe`'s view of one routing decision: the chain `route()` calculates, the+ * candidates it dropped, and the fields every renderer shares.+ *+ * Pure: it maps a {@link RouteExplanation} onto the shapes the three renderers+ * read (the `--json` output, the static printer, the probe TUI). Nothing here+ * decides a route or reads a credential — `explainRoute` decided, and the+ * credential remedy is injected ({@link CredentialLookup}) — so a test can build+ * any of the three from an explanation with no network and no environment.+ *+ * The contract the renderers rely on:+ * - `chain` holds the KEPT candidates in `route()`'s order, and `[]` still means+ * no route. An explicit target is a one-item chain.+ * - A native target (no candidates: Claude Code's own auth serves it) is ONE+ * link that carries `notProbed: "native-auth"`. It is never probed.+ * - `dropped` holds every other candidate, in chain order, with its outcome.+ * Dropped candidates are listed, never probed (see `probeTargets`).+ * - The parser's provider (`nativeProvider`) is not here: it is not a routing+ * decision, and for a bare non-Claude name it is the internal `auto-route`.+ */++import type { KeyProvenance } from "../providers/api-key-provenance.js";+import type { ProbeResult } from "../providers/probe-live.js";+import type { DroppedOutcome } from "../providers/probe-runner.js";+import type { RouteTier } from "../providers/provider-definitions.js";+import {+ type ExplainedCandidate,+ type RouteExplanation,+ type RouteWarning,+ type RuleScope,+ TIER_LABEL,+ describeRouteExplanation,+} from "../providers/routing-rules.js";+import type { ProbeResultLink } from "./probe-tui-app.js";++/** One link of `--probe`'s chain: a kept hop, or a native target's one not-probed link. */+export interface ProbeChainLink {+ provider: string;+ displayName: string;+ /** Exactly the `Route.modelSpec` the hop becomes; for a native link, what the passthrough sends. */+ modelSpec: string;+ wireId: string;+ position: ExplainedCandidate["position"];+ tier?: RouteTier;+ /** The hop's label: its tier's, `fallback` for the fallback position, or the native auth. */+ label: string;+ /** Confirmed by the account (`serves`), or merely not denied (`unknown`). */+ availability?: ExplainedCandidate["availability"];+ /** Kept hops passed the credential filter, so this is true for every one of them. */+ hasCredentials: boolean;+ credentialHint?: string;+ provenance?: KeyProvenance;+ /** A native link: served on Claude Code's own auth, which this process cannot forward. */+ notProbed?: "native-auth";+ probe?: ProbeResult;+}++/** A candidate the routing chain did not keep, and why. Never probed. */+export interface ProbeDroppedLink {+ provider: string;+ displayName: string;+ wireId: string;+ position: ExplainedCandidate["position"];+ tier?: RouteTier;+ label: string;+ outcome: DroppedOutcome;+ /** The remedy, for a candidate the credential filter dropped. */+ credentialHint?: string;+}++/** Where `--probe` reads a provider's credential remedy and key provenance from. */+export interface CredentialLookup {+ /** The remedy a credential-less row shows (an env var name, or a sentence). */+ hintFor(provider: string): string | undefined;+ /** Where the provider's key comes from, when it is read from an env var. */+ provenanceFor(provider: string): KeyProvenance | undefined;+}++/** The label a native link shows in place of a tier. */+export const NATIVE_LINK_LABEL = "Claude Code's own auth";++/**+ * A hop's label: the fallback POSITION overrides the tier of whichever provider+ * holds it. The same rule `describeRouteExplanation` words its "… first" with.+ */+export function hopLabelOf(candidate: Pick<ExplainedCandidate, "position" | "tier">): string {+ if (candidate.position === "fallback") return TIER_LABEL.fallback;+ return candidate.tier ? TIER_LABEL[candidate.tier] : "unregistered provider";+}++/** The kept chain and the dropped candidates of one explanation. */+export function probeChainFrom(+ explanation: RouteExplanation,+ credentials: CredentialLookup+): { chain: ProbeChainLink[]; dropped: ProbeDroppedLink[] } {+ if (explanation.source === "native" && explanation.native) {+ return { chain: [nativeLinkOf(explanation.native)], dropped: [] };+ }+ const chain: ProbeChainLink[] = [];+ const dropped: ProbeDroppedLink[] = [];+ for (const candidate of explanation.candidates) {+ if (candidate.outcome === "kept") chain.push(keptLinkOf(candidate, credentials));+ else dropped.push(droppedLinkOf(candidate, candidate.outcome, credentials));+ }+ return { chain, dropped };+}++/** A native target's one link: what the passthrough sends, never probed. */+function nativeLinkOf(native: NonNullable<RouteExplanation["native"]>): ProbeChainLink {+ return {+ provider: native.provider,+ displayName: native.displayName,+ modelSpec: native.modelSpec,+ wireId: native.modelSpec,+ position: "candidate",+ label: NATIVE_LINK_LABEL,+ hasCredentials: true,+ notProbed: "native-auth",+ };+}++function keptLinkOf(candidate: ExplainedCandidate, credentials: CredentialLookup): ProbeChainLink {+ const provenance = credentials.provenanceFor(candidate.provider);+ return {+ provider: candidate.provider,+ displayName: candidate.displayName,+ modelSpec: candidate.modelSpec,+ wireId: candidate.wireId,+ position: candidate.position,+ ...(candidate.tier !== undefined ? { tier: candidate.tier } : {}),+ label: hopLabelOf(candidate),+ ...(candidate.availability ? { availability: candidate.availability } : {}),+ hasCredentials: true,+ ...(provenance ? { provenance } : {}),+ };+}++function droppedLinkOf(+ candidate: ExplainedCandidate,+ outcome: DroppedOutcome,+ credentials: CredentialLookup+): ProbeDroppedLink {+ const hint = outcome === "no-credential" ? credentials.hintFor(candidate.provider) : undefined;+ return {+ provider: candidate.provider,+ displayName: candidate.displayName,+ wireId: candidate.wireId,+ position: candidate.position,+ ...(candidate.tier !== undefined ? { tier: candidate.tier } : {}),+ label: hopLabelOf(candidate),+ outcome,+ ...(hint ? { credentialHint: hint } : {}),+ };+}++/** The fields the printer, the TUI and the JSON share, taken from the explanation. */+export interface ProbeRoutingFields {+ routingSource: RouteExplanation["source"];+ /** `describeRouteExplanation`: the one line `--probe` and the config TUI share. */+ routingExplanation: string;+ matchedPattern?: string;+ ruleScope?: RuleScope;+ /** Set when there is no route: `route()`'s reason and hint, verbatim. */+ noRoute?: { reason: string; hint?: string };+ warnings: RouteWarning[];+}++export function routingFieldsFrom(explanation: RouteExplanation): ProbeRoutingFields {+ const { outcome } = explanation;+ return {+ routingSource: explanation.source,+ routingExplanation: describeRouteExplanation(explanation),+ ...(explanation.matchedPattern !== undefined+ ? { matchedPattern: explanation.matchedPattern }+ : {}),+ ...(explanation.ruleScope ? { ruleScope: explanation.ruleScope } : {}),+ ...(outcome.kind === "no-route"+ ? {+ noRoute: {+ reason: outcome.reason,+ ...(outcome.hint !== undefined ? { hint: outcome.hint } : {}),+ },+ }+ : {}),+ warnings: explanation.warnings,+ };+}++/**+ * The TUI's rows for one model: the kept hops in chain order, then one row per+ * dropped candidate carrying its outcome and credential hint. Nothing else — no+ * row is invented for an empty chain; the explanation line says why it is empty.+ */+export function resultLinksFrom(+ chain: ProbeChainLink[],+ dropped: ProbeDroppedLink[]+): ProbeResultLink[] {+ return [+ ...chain.map(+ (link): ProbeResultLink => ({+ provider: link.provider,+ displayName: link.displayName,+ // The id the hop sends, with no redundant provider@ prefix: the row shows+ // displayName + the resolved id only (e.g. "k3", not "kc@k3").+ modelId: link.wireId,+ label: link.label,+ hasCredentials: link.hasCredentials,+ ...(link.credentialHint ? { credentialHint: link.credentialHint } : {}),+ ...(link.notProbed ? { notProbed: link.notProbed } : {}),+ ...(link.probe ? { probe: link.probe } : {}),+ })+ ),+ ...dropped.map(+ (entry): ProbeResultLink => ({+ provider: entry.provider,+ displayName: entry.displayName,+ modelId: entry.wireId,+ label: entry.label,+ // Only a not-served candidate proves a credential was read: the credential+ // filter runs before the availability filter, and membership before both.+ hasCredentials: entry.outcome === "not-served",+ ...(entry.credentialHint ? { credentialHint: entry.credentialHint } : {}),+ dropped: entry.outcome,+ })+ ),+ ];+}diff --git a/packages/cli/src/probe/probe-results-printer.test.ts b/packages/cli/src/probe/probe-results-printer.test.tsindex e78b5dba..8a7928a1 100644--- a/packages/cli/src/probe/probe-results-printer.test.ts+++ b/packages/cli/src/probe/probe-results-printer.test.ts@@ -5,7 +5,7 @@ import { type ModelResult, printProbeResults } from "./probe-results-printer.js"// biome-ignore lint/suspicious/noControlCharactersInRegex: ANSI escape sequences require control charsconst ANSI_RE = /\x1b\[[0-9;]*[A-Za-z]/g;-function renderDirectSpec(nativeProvider: string, model: string): string {+function render(result: ModelResult): string {let output = "";const originalWrite = process.stderr.write;process.stderr.write = ((chunk: string | Uint8Array) => {@@ -14,33 +14,46 @@ function renderDirectSpec(nativeProvider: string, model: string): string {}) as typeof process.stderr.write;try {- // The direct-row path reads only these fields. Keep the fixture minimal so- // any new dependency in the display path is explicit in this test.- const result = {- model,- nativeProvider,- routingSource: "direct",- chain: [],- } as unknown as ModelResult;-printProbeResults([result], false);} finally {process.stderr.write = originalWrite;}+ return output.replace(ANSI_RE, "");+}++function renderChainSpec(provider: string, modelSpec: string, native = false): string {+ const output = render({+ model: modelSpec,+ routingSource: native ? "native" : "explicit",+ routingExplanation: native+ ? "native · Claude Code's own auth · not probed"+ : `explicit · ${provider}`,+ chain: [+ {+ provider,+ displayName: provider,+ modelSpec,+ label: native ? "Claude Code's own auth" : "gateway",+ hasCredentials: true,+ ...(native ? { notProbed: "native-auth" as const } : {}),+ },+ ],+ dropped: [],+ });+const cells = output- .replace(ANSI_RE, "").split("\n").map((line) => line.split("│").map((cell) => cell.trim()))- .find((row) => row[1] === "1" && row[2] === nativeProvider);+ .find((row) => row[1] === "1" && row[2] === provider);expect(cells).toBeDefined();- return cells?.[3] ?? "";+ return cells?.[4] ?? "";}-describe("printProbeResults direct Model Spec", () => {- test("does not double an explicit provider prefix", () => {- const spec = renderDirectSpec("openrouter", "[email protected]");+describe("printProbeResults chain Model Spec", () => {+ test("does not double an explicit provider shortcut", () => {+ const spec = renderChainSpec("openrouter", "[email protected]");expect({ spec, atCount: spec.match(/@/g)?.length ?? 0 }).toEqual({spec: "[email protected]",@@ -48,22 +61,69 @@ describe("printProbeResults direct Model Spec", () => {});});- test("prefixes a bare model input", () => {- expect(renderDirectSpec("openrouter", "gpt-5.6-sol")).toBe("[email protected]");+ test("renders the prepared provider-pinned spec", () => {+ expect(renderChainSpec("openrouter", "[email protected]")).toBe("[email protected]");});test("keeps native-anthropic model inputs bare", () => {- const spec = renderDirectSpec("native-anthropic", "claude-opus-4-7");+ const spec = renderChainSpec("native-anthropic", "claude-opus-4-7", true);- // Prefixing this sets hasExplicitProvider=true and routes away from the- // passthrough, so native-anthropic must remain special-cased.expect(spec).toBe("claude-opus-4-7");expect(spec).not.toContain("@");});- test("prefixes a slash-qualified vendor model input", () => {- expect(renderDirectSpec("openrouter", "openai/gpt-5.6-sol")).toBe(- "openrouter@openai/gpt-5.6-sol"+ test("keeps a vendor-qualified id inside an explicit one-item chain", () => {+ expect(renderChainSpec("openrouter", "anthropic/claude-opus-5")).toBe(+ "anthropic/claude-opus-5");});});++describe("printProbeResults calculated-route headings", () => {+ test("uses the first kept hop for o4-mini and never the parser's auto-route provider", () => {+ const result = {+ model: "o4-mini",+ nativeProvider: "auto-route",+ routingSource: "catalog",+ routingExplanation: "catalog · native API first",+ chain: [+ {+ provider: "openai",+ displayName: "OpenAI",+ modelSpec: "oai@o4-mini",+ label: "native API",+ hasCredentials: true,+ },+ ],+ dropped: [],+ } as ModelResult & { nativeProvider: string };++ const output = render(result);+ const heading = output.split("\n").find((line) => line.startsWith("┌─")) ?? "";++ expect(heading).toContain("OpenAI · 0/1 live");+ expect(output).not.toContain("auto-route");+ });++ test("uses the explanation for a bare no-route and never invents an auto-route row", () => {+ const explanation = 'catalog has no entry for "no-such-model-xyz" · no fallback (disabled)';+ const result = {+ model: "no-such-model-xyz",+ nativeProvider: "auto-route",+ routingSource: "catalog",+ routingExplanation: explanation,+ chain: [],+ dropped: [],+ noRoute: {+ reason: 'No provider in the catalog serves "no-such-model-xyz".',+ },+ } as ModelResult & { nativeProvider: string };++ const output = render(result);+ const heading = output.split("\n").find((line) => line.startsWith("┌─")) ?? "";++ expect(heading).toContain(explanation);+ expect(output).not.toContain("auto-route");+ expect(output).not.toContain("auto-route@");+ });+});diff --git a/packages/cli/src/probe/probe-results-printer.ts b/packages/cli/src/probe/probe-results-printer.tsindex 69d79dff..a59c287a 100644--- a/packages/cli/src/probe/probe-results-printer.ts+++ b/packages/cli/src/probe/probe-results-printer.ts@@ -9,11 +9,13 @@* ANSI text that persists in the scrollback without any diff-based redraws.** The output is rendered as one bordered card per model. Each card contains- * a chain table with provider/spec/status columns, optional error detail- * sub-rows, and a compact key/wire footer.+ * a chain table with provider/tier/spec/status columns (the kept hops, then the+ * candidates the routing chain dropped), optional detail sub-rows, and a compact+ * key/wire/route footer.*/import type { KeyProvenance } from "../providers/api-key-provenance.js";+import { NATIVE_NOT_PROBED } from "../providers/native-route.js";import {type ProbeResult,type ProbeTiming,@@ -21,7 +23,8 @@ import {isFailureState,isReadyState,} from "../providers/probe-live.js";-import { pinProbeModelSpec } from "../providers/probe-runner.js";+import { DROPPED_LABEL, type DroppedOutcome, droppedRemedy } from "../providers/probe-runner.js";+import type { RouteExplanation, RouteWarning, RuleScope } from "../providers/routing-rules.js";import { bgHex, cliAnsi } from "../theme/ansi.js";import { getThemeMode } from "../theme/theme-mode.js";import {@@ -216,7 +219,6 @@ function computeBarScales(results: ModelResult[]): BarScales {if (scaledTps > maxTokPerSec) maxTokPerSec = scaledTps;};for (const r of results) {- consider(r.directProbe);for (const c of r.chain ?? []) consider(c.probe);}@@ -349,14 +351,29 @@ function buildBarsLine(return `${timeline} ${total}${breakdown}${tokBar}${tokValue}${crown}`;}+/** One hop of the routing chain `route()` calculates (or a native target's one link). */export interface ChainEntry {provider: string;displayName: string;modelSpec: string;+ /** The hop's tier label, or `fallback` for the fallback position. */+ label?: string;hasCredentials: boolean;credentialHint?: string;provenance?: KeyProvenance;probe?: ProbeResult;+ /** A native link: served on Claude Code's own auth, so it is never probed. */+ notProbed?: "native-auth";+}++/** A candidate the routing chain did not keep. Listed with its outcome, never probed. */+export interface DroppedEntry {+ provider: string;+ displayName: string;+ wireId: string;+ label?: string;+ outcome: DroppedOutcome;+ credentialHint?: string;}export interface WiringInfo {@@ -369,14 +386,25 @@ export interface WiringInfo {effectiveStreamFormat: string;}+/**+ * One model's routing decision, as `explainRoute` made it. The parser's provider+ * (`nativeProvider`) is deliberately absent: it is not a routing decision, and a+ * bare non-Claude name reads `auto-route` there. It stays in `--probe --json` only.+ */export interface ModelResult {model: string;- nativeProvider: string;- isExplicit: boolean;- routingSource: "direct" | "custom-rules" | "auto-chain";+ routingSource: RouteExplanation["source"];+ /** `describeRouteExplanation`: the one line `--probe` and the config TUI share. */+ routingExplanation: string;matchedPattern?: string;+ ruleScope?: RuleScope;+ /** The kept hops, in chain order; a native target's one not-probed link. `[]` = no route. */chain: ChainEntry[];- directProbe?: ProbeResult;+ /** The candidates the routing chain dropped, in chain order. */+ dropped?: DroppedEntry[];+ /** Set when there is no route: `route()`'s reason and hint, verbatim. */+ noRoute?: { reason: string; hint?: string };+ warnings?: RouteWarning[];wiring?: WiringInfo;}@@ -570,11 +598,16 @@ function renderSepRow(widths: number[], width: number): string {}interface RowData {+ /** The hop's position in the chain, or "–" for a dropped candidate (not a hop). */num: string;provider: string;+ /** Tier label (`subscription`, `gateway`, `fallback`, …). */+ label: string;spec: string;status: string;errorDetail?: string;+ /** A dim, non-error sub-row: why a link is not probed, or a dropped candidate's remedy. */+ note?: string;/** True if this is the fastest live provider in the chain (green bg) */fastest?: boolean;/** True if this is the slowest live provider in the chain (red bg) */@@ -617,6 +650,18 @@ function buildRowData(result: ModelResult, isLiveProbe: boolean): RowData[] {const isFastest = i === fastestIdx;const isSlowest = i === slowestIdx;+ // A native link is a third outcome, neither live nor failed: nothing was sent.+ if (entry.notProbed) {+ return {+ num: `${i + 1}`,+ provider: entry.displayName,+ label: entry.label ?? "",+ spec: entry.modelSpec,+ status: `${pc.cyan}◐ native — not probed${pc.reset}`,+ note: NATIVE_NOT_PROBED,+ };+ }+let status = shortStatusLabel(entry.probe, entry.hasCredentials, entry.credentialHint);if (isFastest) {status = `${status} ${pc.brightGreen}●${pc.reset}`;@@ -635,6 +680,7 @@ function buildRowData(result: ModelResult, isLiveProbe: boolean): RowData[] {return {num: `${i + 1}`,provider: entry.displayName,+ label: entry.label ?? "",spec: entry.modelSpec,status,errorDetail,@@ -645,46 +691,29 @@ function buildRowData(result: ModelResult, isLiveProbe: boolean): RowData[] {});}-function buildDirectRowData(result: ModelResult): RowData[] {- const probe = result.directProbe;- let status: string;- if (!probe) {- status = `${pc.dim}— no probe —${pc.reset}`;- } else {- status = shortStatusLabel(probe, true);- if (probe.state === "live") {- status = `${status} ${pc.brightGreen}●${pc.reset}`;- }- }- let errorDetail: string | undefined;- if (probe && isFailureState(probe.state) && probe.errorMessage) {- errorDetail = stripAnsi(probe.errorMessage).replace(/\s+/g, " ").trim();- }- const barsTiming = probe?.state === "live" && probe.timing ? probe.timing : undefined;- return [- {- num: "1",- provider: result.nativeProvider,- // `result.model` is the RAW user input, so it already carries the prefix- // whenever the user typed one — `--probe [email protected]` rendered- // as "openrouter@[email protected]". pinProbeModelSpec owns the- // prefixing rule (it also keeps native-anthropic bare, which a plain- // template would break); reuse it rather than repeat a second guard here.- spec: pinProbeModelSpec({ provider: result.nativeProvider, modelSpec: result.model }),- status,- errorDetail,- barsTiming,- },- ];+/**+ * One row per candidate the routing chain dropped, after the kept hops. Never+ * probed: the status is the outcome, and the sub-row names the remedy when the+ * credential filter dropped it.+ */+function buildDroppedRowData(result: ModelResult): RowData[] {+ return (result.dropped ?? []).map((entry) => ({+ num: "–",+ provider: entry.displayName,+ label: entry.label ?? "",+ spec: entry.wireId,+ status: `${pc.dim}– ${DROPPED_LABEL[entry.outcome]}${pc.reset}`,+ note: droppedRemedy(entry.credentialHint),+ }));}+const COLUMN_HEADERS = ["#", "Provider", "Tier", "Model Spec", "Status"];+function computeColumnWidths(rows: RowData[]): number[] {- const headers = ["#", "Provider", "Model Spec", "Status"];- const wNum = Math.max(headers[0].length, ...rows.map((r) => r.num.length));- const wProv = Math.max(headers[1].length, ...rows.map((r) => visibleLength(r.provider)));- const wSpec = Math.max(headers[2].length, ...rows.map((r) => visibleLength(r.spec)));- const wStatus = Math.max(headers[3].length, ...rows.map((r) => visibleLength(r.status)));- return [wNum, wProv, wSpec, wStatus];+ const cells = (r: RowData) => [r.num, r.provider, r.label, r.spec, r.status];+ return COLUMN_HEADERS.map((header, col) =>+ Math.max(header.length, ...rows.map((r) => visibleLength(cells(r)[col])))+ );}/**@@ -730,6 +759,9 @@ function formatContextWindow(ctx: number): string {}function buildKeyLine(activeEntry?: ChainEntry, directKeyVar?: string): string {+ if (activeEntry?.notProbed) {+ return `${pc.bold}Key${pc.reset} ${pc.dim}Claude Code's own auth (not visible to this process)${pc.reset}`;+ }if (activeEntry?.provenance) {const p = activeEntry.provenance;// `effectiveLabel` replaces `$ENV_VAR` for a provider whose credential is not@@ -750,7 +782,7 @@ function buildKeyLine(activeEntry?: ChainEntry, directKeyVar?: string): string {return `${pc.bold}Key${pc.reset} ${pc.dim}—${pc.reset}`;}-function buildWireLine(wiring: WiringInfo, activeProvider?: string): string {+function buildWireLine(wiring: WiringInfo, activeProvider: string | undefined): string {const ctx = formatContextWindow(wiring.contextWindow);const head = activeProvider ? `${activeProvider} → ` : "";return `${pc.bold}Wire${pc.reset} ${head}${wiring.effectiveStreamFormat} · ${wiring.modelTranslator} · ${ctx}`;@@ -768,44 +800,58 @@ interface CardLayout {summaryStyled: string;keyLine: string;wireLine: string;+ /** `Route <describeRouteExplanation>`: where the chain came from, in the shared wording. */+ routeLine: string;footerVis: number;activeEntry: ChainEntry | undefined;}+/**+ * The card heading's right-hand summary. It names the FIRST KEPT hop — the+ * provider a request uses — never the parser's provider, which for a bare+ * non-Claude name is the internal `auto-route`. A native link says "not probed";+ * an empty chain says why, in the shared explanation line.+ */+function cardSummary(result: ModelResult): { text: string; color: string } {+ const first = result.chain[0];+ if (!first) return { text: result.routingExplanation || "no route", color: pc.red };+ if (first.notProbed) return { text: `${first.displayName} · not probed`, color: pc.cyan };+ const probed = result.chain.filter((c) => !c.notProbed);+ const live = probed.filter((c) => c.probe?.state === "live").length;+ return {+ text: `${first.displayName} · ${live}/${probed.length} live`,+ color: summaryColor(live, probed.length),+ };+}+function buildCardLayout(result: ModelResult,isLiveProbe: boolean,directKeyVar?: string): CardLayout {- const rows =- result.routingSource === "direct"- ? buildDirectRowData(result)- : buildRowData(result, isLiveProbe);-- const totalLinks = rows.length;- const liveCount = result.chain- ? result.chain.filter((c) => c.probe?.state === "live").length- : result.directProbe?.state === "live"- ? 1- : 0;- const effLive = result.routingSource === "direct" ? liveCount : liveCount;- const effTotal = result.routingSource === "direct" ? totalLinks : result.chain.length;-- const titleText = result.model;- const sumColor = summaryColor(effLive, effTotal);- const summaryPlain = `${result.nativeProvider} · ${effLive}/${effTotal} live`;- const titleStyled = `${pc.bold}${pc.cyan}${titleText}${pc.reset}`;- const summaryStyled = `${sumColor}${summaryPlain}${pc.reset}`;+ const rows = [...buildRowData(result, isLiveProbe), ...buildDroppedRowData(result)];++ const summary = cardSummary(result);+ const titleStyled = `${pc.bold}${pc.cyan}${result.model}${pc.reset}`;+ const summaryStyled = `${summary.color}${summary.text}${pc.reset}`;const activeEntry =- result.chain?.find((c) => c.probe?.state === "live") ??- result.chain?.find((c) => c.hasCredentials);+ result.chain.find((c) => c.probe?.state === "live") ??+ result.chain.find((c) => c.hasCredentials);const keyLine = buildKeyLine(activeEntry, directKeyVar);- const wireLine = result.wiring- ? buildWireLine(result.wiring, activeEntry?.displayName ?? result.nativeProvider)+ const wireLine =+ result.wiring && !activeEntry?.notProbed+ ? buildWireLine(result.wiring, activeEntry?.displayName)+ : "";+ const routeLine = result.routingExplanation+ ? `${pc.bold}Route${pc.reset} ${result.routingExplanation}`: "";- const footerVis = Math.max(visibleLength(keyLine), visibleLength(wireLine));+ const footerVis = Math.max(+ visibleLength(keyLine),+ visibleLength(wireLine),+ visibleLength(routeLine)+ );const widths = computeColumnWidths(rows);@@ -816,6 +862,7 @@ function buildCardLayout(summaryStyled,keyLine,wireLine,+ routeLine,footerVis,activeEntry,};@@ -851,19 +898,14 @@ function renderCard(directKeyVar?: string): void {const layout = buildCardLayout(result, isLiveProbe, directKeyVar);- const { rows, widths, titleStyled, summaryStyled, keyLine, wireLine } = layout;+ const { rows, widths, titleStyled, summaryStyled, keyLine, wireLine, routeLine } = layout;// === Render ===w(`${renderBorderTop(titleStyled, summaryStyled, width)}\n`);w(`${renderBlankLine(width)}\n`);// Header row (dim styled headers)- const headerCells = [- `${pc.dim}#${pc.reset}`,- `${pc.dim}Provider${pc.reset}`,- `${pc.dim}Model Spec${pc.reset}`,- `${pc.dim}Status${pc.reset}`,- ];+ const headerCells = COLUMN_HEADERS.map((h) => `${pc.dim}${h}${pc.reset}`);w(`${renderRow(headerCells, widths, width)}\n`);w(`${renderSepRow(widths, width)}\n`);@@ -874,7 +916,13 @@ function renderCard(const r = rows[rowIdx];const bg = r.fastest ? pc.bgFastest : r.slowest ? pc.bgSlowest : undefined;- const cells = [r.num, r.provider, `${pc.dim}${r.spec}${pc.reset}`, r.status];+ const cells = [+ r.num,+ r.provider,+ `${pc.dim}${r.label}${pc.reset}`,+ `${pc.dim}${r.spec}${pc.reset}`,+ r.status,+ ];w(`${renderRow(cells, widths, width, bg)}\n`);// Bars sub-row beneath a live provider row (timeline + breakdown + tok/s).@@ -893,64 +941,98 @@ function renderCard(}}- if (r.errorDetail) {- // Render the error as a full-width sub-row (or rows) beneath the- // failed row, word-wrapped to fit the card's inner usable width.- // Layout inside the card for an error line:- // │{leftPad}{errorIndent}└ {text}{pad}{rightPad}│- // where errorIndent visually insets the error one column past the- // "#" column so it reads as a child of the failed row.- const innerUsable = width - 2 - CARD_PADDING_LEFT - CARD_PADDING_RIGHT;- const errorIndent = 4; // 4 spaces of indent inside the usable area- const prefixVis = 2; // "└ " or " "- const textWidth = innerUsable - errorIndent - prefixVis;- const MAX_ERROR_LINES = 4;-- if (textWidth > 0) {- let wrapped = wordWrap(r.errorDetail, textWidth);- let truncated = false;- if (wrapped.length > MAX_ERROR_LINES) {- wrapped = wrapped.slice(0, MAX_ERROR_LINES);- truncated = true;- }- if (truncated) {- const last = wrapped[wrapped.length - 1];- // Append an ellipsis to the last kept line (replace last char if needed).- if (last.length >= textWidth) {- wrapped[wrapped.length - 1] = `${last.slice(0, textWidth - 1)}…`;- } else {- wrapped[wrapped.length - 1] = `${last}…`;- }- }- const indentStr = " ".repeat(errorIndent);- for (let i = 0; i < wrapped.length; i++) {- const prefix = i === 0 ? "└ " : " ";- const body = `${indentStr}${pc.dim}${pc.red}${prefix}${wrapped[i]}${pc.reset}`;- w(`${renderTextLine(body, width, bg)}\n`);- }- }- }+ // A failed probe's error in dim red; a not-probed link's or a dropped+ // candidate's note in dim only — neither of those is a failure.+ if (r.errorDetail) writeSubRows(w, r.errorDetail, `${pc.dim}${pc.red}`, width, bg);+ if (r.note) writeSubRows(w, r.note, pc.dim, width, bg);}w(`${renderBlankLine(width)}\n`);- // Footer: Key + Wire+ // Footer: Key + Wire + Route (the shared explanation line)if (visibleLength(keyLine) > 0) {w(`${renderTextLine(keyLine, width)}\n`);}if (visibleLength(wireLine) > 0) {w(`${renderTextLine(wireLine, width)}\n`);}-- // Routing-source note (custom rules)- if (result.routingSource === "custom-rules" && result.matchedPattern) {- const note = `${pc.dim}Custom rule: ${pc.reset}${pc.cyan}${result.matchedPattern}${pc.reset}`;- w(`${renderTextLine(note, width)}\n`);+ if (visibleLength(routeLine) > 0) {+ w(`${renderTextLine(routeLine, width)}\n`);}+ writeDecisionNotes(w, result, width);w(`${renderBorderBottom(width)}\n`);}+/**+ * The card lines under the footer that only some decisions have: a no-route's+ * reason and hint (`route()`'s own, verbatim), then each billing notice `route()`+ * would print to stderr for this decision. Rule problems are printed once, above+ * the cards, because they are about the config rather than one model.+ */+function writeDecisionNotes(w: Writer, result: ModelResult, width: number): void {+ const textWidth = cardTextWidth(width);+ if (result.noRoute) {+ const head = "No route ";+ wordWrap(result.noRoute.reason, textWidth - head.length).forEach((line, i) => {+ const lead = i === 0 ? `${pc.red}No route${pc.reset} ` : " ".repeat(head.length);+ w(`${renderTextLine(`${lead}${line}`, width)}\n`);+ });+ // The hint is pre-formatted (its options are indented): a line that fits is+ // kept as written, and only a line too long for the card is re-wrapped.+ const hintLines = (result.noRoute.hint ?? "").split("\n").filter((l) => l.trim());+ const fitted = hintLines.flatMap((l) => (l.length <= textWidth ? [l] : wordWrap(l, textWidth)));+ for (const line of fitted) {+ w(`${renderTextLine(`${pc.dim}${line}${pc.reset}`, width)}\n`);+ }+ }+ const notices = (result.warnings ?? []).filter((warning) => warning.type !== "rule-problem");+ for (const line of notices.flatMap((warning) => wordWrap(`⚠ ${warning.message}`, textWidth))) {+ w(`${renderTextLine(`${pc.yellow}${line}${pc.reset}`, width)}\n`);+ }+}++/** Usable text width inside a card of `width` columns. */+function cardTextWidth(width: number): number {+ return Math.max(10, width - 2 - CARD_PADDING_LEFT - CARD_PADDING_RIGHT);+}++/**+ * Write `text` as a full-width sub-row (or rows) beneath its row, word-wrapped to+ * the card's inner usable width, in `color`. Layout inside the card:+ * │{leftPad}{indent}└ {text}{pad}{rightPad}│+ * where the indent insets it one column past the "#" column so it reads as a+ * child of the row above.+ */+function writeSubRows(+ w: Writer,+ text: string,+ color: string,+ width: number,+ bg: string | undefined+): void {+ const indent = 4; // 4 spaces of indent inside the usable area+ const prefixVis = 2; // "└ " or " "+ const textWidth = cardTextWidth(width) - indent - prefixVis;+ const MAX_LINES = 4;+ if (textWidth <= 0) return;++ let wrapped = wordWrap(text, textWidth);+ if (wrapped.length > MAX_LINES) {+ wrapped = wrapped.slice(0, MAX_LINES);+ const last = wrapped[wrapped.length - 1];+ // Append an ellipsis to the last kept line (replace last char if needed).+ wrapped[wrapped.length - 1] =+ last.length >= textWidth ? `${last.slice(0, textWidth - 1)}…` : `${last}…`;+ }+ const indentStr = " ".repeat(indent);+ for (let i = 0; i < wrapped.length; i++) {+ const prefix = i === 0 ? "└ " : " ";+ const body = `${indentStr}${color}${prefix}${wrapped[i]}${pc.reset}`;+ w(`${renderTextLine(body, width, bg)}\n`);+ }+}+/*** Stage + tok/s legend, printed once above the cards (only when bars are shown,* i.e. a live probe with at least one timed result). Mirrors the TUI legend.@@ -990,13 +1072,15 @@ interface LeaderRow {provider: string;/** Live+timed timing for the representative entry; undefined = unavailable. */timing?: ProbeTiming;+ /** Why an unavailable row has no timing: `no live route`, `not probed (native)`, `no route`. */+ missing?: string;}/*** Pick the representative entry for a model: the first chain link that probed- * live AND carried timing (the route claudish would actually use), else the- * direct probe if it's live+timed. Returns undefined timing for models with no- * usable route so they can be listed dim as "unavailable".+ * live AND carried timing (the route claudish would actually use). A model with+ * none is listed dim, under its first kept hop — or, with no hop at all, under+ * the explanation line. Never under the parser's provider (`auto-route`).*/function pickRepresentative(result: ModelResult): LeaderRow {for (const entry of result.chain ?? []) {@@ -1004,11 +1088,12 @@ function pickRepresentative(result: ModelResult): LeaderRow {return { model: result.model, provider: entry.displayName, timing: entry.probe.timing };}}- const direct = result.directProbe;- if (direct?.state === "live" && direct.timing) {- return { model: result.model, provider: result.nativeProvider, timing: direct.timing };- }- return { model: result.model, provider: result.nativeProvider };+ const first = result.chain?.[0];+ return {+ model: result.model,+ provider: first?.displayName ?? result.routingExplanation,+ missing: first?.notProbed ? "not probed (native)" : first ? "no live route" : "no route",+ };}/**@@ -1163,7 +1248,7 @@ function renderLeaderboard(const rankStr = " ".repeat(rankW);const name = padEnd(`${pc.dim}${truncate(row.model, nameW)}${pc.reset}`, nameW);const prov = padEnd(`${pc.dim}${truncate(row.provider, provW)}${pc.reset}`, provW);- w(`${margin}${rankStr} ${name} ${prov} ${pc.dim}— no live route${pc.reset}\n`);+ w(`${margin}${rankStr} ${name} ${prov} ${pc.dim}— ${row.missing}${pc.reset}\n`);}// ── Bottom rule — matches the ACTUAL rendered data-row width (not the@@ -1180,6 +1265,19 @@ function renderLeaderboard(w("\n");}+/** Rule problems are about the config, not one model: each is printed once, above the cards. */+function renderRuleProblems(results: ModelResult[], w: Writer): void {+ const messages = new Set(+ results.flatMap((r) =>+ (r.warnings ?? []).filter((x) => x.type === "rule-problem").map((x) => x.message)+ )+ );+ for (const message of messages) {+ w(` ${pc.yellow}⚠ routing rule: ${message}${pc.reset}\n`);+ }+ if (messages.size > 0) w("\n");+}+export function printProbeResults(results: ModelResult[], isLiveProbe: boolean): void {refreshPc();const w: Writer = process.stderr.write.bind(process.stderr);@@ -1192,11 +1290,11 @@ export function printProbeResults(results: ModelResult[], isLiveProbe: boolean):const scales = computeBarScales(results);// Has any live probe carried timing? Only then is the legend meaningful.- const anyTimedLive =- results.some((r) => r.directProbe?.state === "live" && r.directProbe.timing !== undefined) ||- results.some((r) =>- (r.chain ?? []).some((c) => c.probe?.state === "live" && c.probe.timing !== undefined)- );+ const anyTimedLive = results.some((r) =>+ (r.chain ?? []).some((c) => c.probe?.state === "live" && c.probe.timing !== undefined)+ );++ renderRuleProblems(results, w);if (isLiveProbe && anyTimedLive) {renderLegend(w);@@ -1238,9 +1336,14 @@ export function printProbeResults(results: ModelResult[], isLiveProbe: boolean):w("\n");}- // Compact tip footer (no legend — cards are self-describing).+ // Compact tip footer (no legend — cards are self-describing). It states the+ // rule the chain is calculated by, never a provider order: that comes from the+ // cloud models catalog and this account's credentials, per model.+ w(+ ` ${pc.dim}Tip: a matching user rule is used as written; otherwise the catalog orders hops by tier,${pc.reset}\n`+ );w(- ` ${pc.dim}Tip: chain order is LiteLLM → Zen Go → Subscription → Native API → OpenRouter${pc.reset}\n`+ ` ${pc.dim} subscription first, and the fallback hop comes last. Dropped candidates are never probed.${pc.reset}\n`);w("\n");diff --git a/packages/cli/src/probe/probe-tui-app.tsx b/packages/cli/src/probe/probe-tui-app.tsxindex f0fa2722..b10f5ca2 100644--- a/packages/cli/src/probe/probe-tui-app.tsx+++ b/packages/cli/src/probe/probe-tui-app.tsx@@ -13,12 +13,15 @@import type { ScrollBoxRenderable } from "@opentui/core";import { useKeyboard, useTerminalDimensions } from "@opentui/react";import { useEffect, useRef, useState } from "react";+import { NATIVE_NOT_PROBED } from "../providers/native-route.js";import {type ProbeResult,type ProbeTiming,STREAM_MS_FLOOR,describeProbeState,} from "../providers/probe-live.js";+import { type DroppedOutcome, describeDropped } from "../providers/probe-runner.js";+import type { RouteExplanation, RouteWarning, RuleScope } from "../providers/routing-rules.js";import { getThemeMode } from "../theme/theme-mode.js";import { useAnimationFrame } from "../tui/hooks/useAnimationFrame.js";import {@@ -51,48 +54,67 @@ export interface ProbeLinkState {displayName: string;/** Pinned model spec, e.g. "litellm@gpt-4o" */modelSpec: string;- status: "waiting" | "probing" | "live" | "failed";+ /**+ * `not-probed`: a row nothing is sent down — a native link, a dropped+ * candidate, or a kept hop under `--no-probe`. It shows `note`, never a bar.+ */+ status: "waiting" | "probing" | "live" | "failed" | "not-probed";startTime?: number;endTime?: number;error?: string;/** Granular timing breakdown — present on "live" links (threaded from cli.ts). */timing?: ProbeTiming;+ /** A `not-probed` row's text. */+ note?: string;+ /** A `not-probed` row's kind, which picks its colour at render time. */+ tone?: "native" | "dropped" | "ready";}-/** One link (provider candidate) in a model's resolved Details view. */+/**+ * One row in a model's Details view: a kept hop of the routing chain, a native+ * target's one link, or a candidate the chain dropped (after the kept hops).+ */export interface ProbeResultLink {provider: string;/** Provider display name, e.g. "OpenAI", "OpenRouter". */displayName: string;/** Resolved model id sent to the API, with NO redundant provider@ prefix. */modelId: string;+ /** The hop's tier label, `fallback` for the fallback position. */+ label?: string;hasCredentials: boolean;credentialHint?: string;probe?: ProbeResult;+ /** A native link: served on Claude Code's own auth, so it is never probed. */+ notProbed?: "native-auth";+ /** Set on a candidate the routing chain dropped: why. Never probed. */+ dropped?: DroppedOutcome;}-/** Per-model results payload the Details tab consumes (built in cli.ts). */+/**+ * Per-model results payload the Details tab consumes (built in cli.ts from+ * `explainRoute`). The parser's provider is deliberately absent: it is not a+ * routing decision, and it stays in `--probe --json` only.+ */export interface ProbeModelResult {/** User input, e.g. "gpt-5.5" or "or@deepseek-v4-pro". */model: string;- /** Parsed native provider name. */- nativeProvider: string;- /** Explicit provider@model spec. */+ /** An explicit target: `provider@model`, `poe:<id>` or `anthropic/<id>`. */isExplicit: boolean;- routingSource: "direct" | "custom-rules" | "auto-chain";- /** Routing rule key that matched (for the routing-why line). */+ routingSource: RouteExplanation["source"];+ /** User rule only: the rule key that matched. */matchedPattern?: string;- /**- * Pre-computed routing explanation string. Derived in ONE helper in cli.ts so- * a later routing worktree can swap the derivation in a single place.- */+ ruleScope?: RuleScope;+ /** `describeRouteExplanation`: the one line `--probe` and the config TUI share. */routingExplanation: string;/**- * Provider-comparison links. For explicit/direct models this is a single- * synthetic link carrying the directProbe (so the model still renders one row- * and the live-count derives from the SAME array as the rows).+ * The kept hops in chain order (a native target: its one not-probed link),+ * then one row per dropped candidate. The live count reads the kept rows only.*/links: ProbeResultLink[];+ /** Set when there is no route: `route()`'s reason and hint, verbatim. */+ noRoute?: { reason: string; hint?: string };+ warnings?: RouteWarning[];wiring?: {formatAdapter: string;declaredStreamFormat: string;@@ -460,7 +482,8 @@ function ProgressBar({: link.startTime? (link.endTime ?? Date.now()) - link.startTime: 0;- const elapsed = formatElapsed(elapsedMs);+ // A row nothing was sent down has no clock: a blank keeps the column aligned.+ const elapsed = link.status === "not-probed" ? " – " : formatElapsed(elapsedMs);const displayName = padEndSafe(link.displayName, maxNameLen);const prefix = (@@ -471,6 +494,20 @@ function ProgressBar({</>);+ // —— NOT PROBED: a native link, a dropped candidate, or a hop under --no-probe.+ // No bar, no status marker: the note is the whole story and runs to the edge.+ // Colour per kind, read from C at render time.+ if (link.status === "not-probed") {+ const used = ELAPSED_COL + maxNameLen + 2;+ const fg = link.tone === "native" ? C.cyan : link.tone === "ready" ? C.green : C.dim;+ return (+ <text>+ {prefix}+ <span fg={fg}>{clipReason(stripAnsi(link.note ?? "not probed"), layout.width - used)}</span>+ </text>+ );+ }+// \u2014\u2014 <60 col fallback: name + single latency pill (today's behavior) \u2014\u2014if (layout.pillFallback) {if (link.status === "live") {@@ -834,6 +871,22 @@ function shortFailureReason(probe: ProbeResult | undefined, hasCreds: boolean):return stripAnsi(describeProbeState(probe));}+/**+ * The marker and text of a Details row nothing was sent down, or null for a row+ * that was probed. A native link is a third outcome (neither ✓ nor ✗); a dropped+ * candidate says why the chain dropped it and, when known, the remedy; a kept hop+ * under `--no-probe` says only that it was not probed. Colours come from C at+ * render time.+ */+function notProbedRow(link: ProbeResultLink): { mark: string; text: string; fg: string } | null {+ if (link.notProbed) return { mark: "◐ ", text: `native — ${NATIVE_NOT_PROBED}`, fg: C.cyan };+ if (link.dropped) {+ return { mark: "– ", text: describeDropped(link.dropped, link.credentialHint), fg: C.dim };+ }+ if (!link.probe && link.hasCredentials) return { mark: "○ ", text: "not probed", fg: C.dim };+ return null;+}+/*** One Details row per provider link. Live links render the aligned* timeline/breakdown/tok columns; failed links render a dim-red reason. The@@ -869,12 +922,23 @@ function DetailLinkRow({</>);+ const used = 2 + 1 + 1 + provW + 2 + 3;+ const idle = notProbedRow(link);+ if (idle) {+ return (+ <text>+ {lead}+ <span fg={idle.fg}>{idle.mark}</span>+ <span fg={idle.fg}>{clipReason(idle.text, layout.width - used)}</span>+ </text>+ );+ }+if (!isLive || !probe?.timing) {// Failed / missing — keep the provider column aligned, then ✗ + dim reason,// CLIPPED to what is left of the terminal. `describeProbeState` returns the// provider's own sentence and a provider is free to make it 400 characters// long; unclipped it wrapped over the rows below instead of ending.- const used = 2 + 1 + 1 + provW + 2 + 3;return (<text>{lead}@@ -979,8 +1043,12 @@ function DetailModel({: "wire: —";// ── Routing advisor ────────────────────────────────────────────────- // Full route: the ordered chain of providers claudish would try.- const routeChain = result.links.map((l) => l.displayName).join(" → ");+ // Full route: the ordered chain of providers claudish would try — the kept+ // hops only, each with its tier label. Dropped rows are listed above, not here.+ const routeChain = result.links+ .filter((l) => !l.dropped)+ .map((l) => (l.label ? `${l.displayName} (${l.label})` : l.displayName))+ .join(" → ");const liveLinks = result.links.filter((l) => l.probe?.state === "live" && !!l.probe.timing);// Best live link on EACH axis: lowest total latency, and highest throughput.// We suggest a rule if the picked provider (winner) loses on EITHER axis —@@ -1043,6 +1111,21 @@ function DetailModel({<span fg={C.dim}>{" ".repeat(gap)}</span><span fg={C.dim}>{result.routingExplanation}</span></text>+ {/* No route: route()'s own reason, verbatim */}+ {result.noRoute && (+ <text>+ <span fg={C.red}>{" no route "}</span>+ <span fg={C.fg}>{clipReason(result.noRoute.reason, layout.width - 12)}</span>+ </text>+ )}+ {/* What route() would print to stderr for this decision (billing notices) */}+ {(result.warnings ?? [])+ .filter((w) => w.type !== "rule-problem")+ .map((w) => (+ <text key={`${result.model}:warn:${w.message}`}>+ <span fg={C.yellow}>{` ⚠ ${clipReason(w.message, layout.width - 4)}`}</span>+ </text>+ ))}{/* One row per provider link */}{result.links.map((link, i) => (<DetailLinkRow@@ -1117,8 +1200,23 @@ function DetailsView({// (minus a 1-col scrollbar gutter) so the routing explanation hugs the right// edge of the rows instead of running off-screen.const headerW = Math.max(24, Math.min(detailRowWidth(provW, layout), (termWidth || 100) - 3));+ // Rule problems are about the config, not one model: shown once, above the models.+ const ruleProblems = [+ ...new Set(+ results.flatMap((r) =>+ (r.warnings ?? []).filter((w) => w.type === "rule-problem").map((w) => w.message)+ )+ ),+ ];return (<box flexDirection="column">+ {ruleProblems.map((message) => (+ <text key={`rule-problem:${message}`}>+ <span fg={C.yellow}>+ {` ⚠ routing rule: ${clipReason(message, (termWidth || 100) - 20)}`}+ </span>+ </text>+ ))}{results.map((r, idx) => (<DetailModelkey={r.model}@@ -1151,13 +1249,16 @@ interface LeaderRowData {provider: string;/** Live+timed timing for the representative; undefined = no live route. */timing?: ProbeTiming;+ /** Why an unavailable row has no timing: `no live route`, `not probed (native)`, `no route`. */+ missing?: string;}/*** Representative entry for a model: the first link that probed live AND carried- * timing (the route claudish would actually use). The synthetic direct-probe- * link is already part of `links` (see ProbeModelResult docs), so iterating the- * links is the whole story — there is no separate directProbe field here.+ * timing (the route claudish would actually use). An explicit target is a+ * one-item chain, so iterating the links is the whole story. A model with none+ * is listed under its first kept hop — or, with no hop at all, under the+ * explanation line. Never under the parser's provider (`auto-route`).*/function pickRepresentativeLink(result: ProbeModelResult): LeaderRowData {for (const link of result.links) {@@ -1165,7 +1266,12 @@ function pickRepresentativeLink(result: ProbeModelResult): LeaderRowData {return { model: result.model, provider: link.displayName, timing: link.probe.timing };}}- return { model: result.model, provider: result.nativeProvider };+ const first = result.links.find((link) => !link.dropped);+ return {+ model: result.model,+ provider: first?.displayName ?? result.routingExplanation,+ missing: first?.notProbed ? "not probed (native)" : first ? "no live route" : "no route",+ };}/** One leaderboard data row (a live, timed representative). */@@ -1363,7 +1469,7 @@ function LeaderboardView({<span fg={C.dim}>{padEndSafe(row.model, nameW)}</span><span fg={C.dim}> </span><span fg={C.dim}>{padEndSafe(row.provider, provW)}</span>- <span fg={C.dim}>{" — no live route"}</span>+ <span fg={C.dim}>{` — ${row.missing}`}</span></text>))}</box>@@ -1555,7 +1661,9 @@ export function ProbeApp({indicator — the probing model rows below ARE the feedback. */}{isDone ? <TabBar activeTab={state.activeTab} /> : null}- {groups.length > 0 ? (+ {/* Results alone are enough: a run whose models are all native or all+ unroutable probes nothing, and its Details tab must still render. */}+ {groups.length > 0 || state.results.length > 0 ? (<>{/* The Summary tab keeps the run legend; the Leaderboard + Detailstabs have their own header text inside the scrollbox. Wrapped in adiff --git a/packages/cli/src/providers/api-key-map.ts b/packages/cli/src/providers/api-key-map.tsindex e9bc2a36..aa068005 100644--- a/packages/cli/src/providers/api-key-map.ts+++ b/packages/cli/src/providers/api-key-map.ts@@ -45,11 +45,12 @@ export const API_KEY_MAP: Record<string, { envVar: string; aliases?: string[] }>// NO alias (2026-09-02). The fix above left OPENCODE_API_KEY behind as one,// and the definition dropped its matching `apiKeyAliases` on the day the 401// claim was measured false. Keeping it HERE would have been worse than never- // fixing it: this table is what `--probe` uses to decide `hasCredentials`- // (`cli.ts` buildDirectChainEntry / buildResultLinks), so the probe would have- // printed a credentialed `zgo@` row for a key the credential authority now- // refuses to sign with — a row asserting readiness nothing has verified, the- // same defect as the removed publicKeyFallback.+ // fixing it: this table was then what `--probe` used to decide `hasCredentials`,+ // so the probe would have printed a credentialed `zgo@` row for a key the+ // credential authority now refuses to sign with — a row asserting readiness+ // nothing has verified, the same defect as the removed publicKeyFallback.+ // (`--probe` now takes that decision from `explainRoute`, i.e. the authority,+ // and reads this table only for the key it names in a dropped row's hint.)"opencode-zen-go": { envVar: "OPENCODE_GO_API_KEY" },// Vertex takes no API key: the project ID plus Application Default// Credentials. VERTEX_API_KEY (Express) was deleted on 2026-09-21, and it wasdiff --git a/packages/cli/src/providers/native-route.ts b/packages/cli/src/providers/native-route.tsindex 3194c848..66280920 100644--- a/packages/cli/src/providers/native-route.ts+++ b/packages/cli/src/providers/native-route.ts@@ -72,6 +72,20 @@ export type ProxyRouteDecision =/** `route()` decides. `model` is the parsed name: a known `vendor/` is stripped. */| { type: "bare"; model: string };+/**+ * What every surface says about a native link instead of a probe result: `--probe`,+ * the MCP preflight and the config TUI's route probe.+ *+ * A native link is never probed. The native handler authenticates by forwarding+ * the INBOUND request's Claude Code header, and a synthetic request from this+ * process carries none, so its answer is noise: "x-api-key header is required"+ * for a healthy model and a typo alike. Substituting `ANTHROPIC_API_KEY` probes a+ * different credential from the one a session uses. So it is a third outcome,+ * neither live nor failed.+ */+export const NATIVE_NOT_PROBED =+ "not probed — served on Claude Code's own auth, which this process cannot forward";+/** The prefix the proxy's `isPoeModel` tests, case-sensitively, as it always has. */const POE_PREFIX = "poe:";diff --git a/packages/cli/src/providers/probe-runner.ts b/packages/cli/src/providers/probe-runner.tsindex 0e0fec65..a821bbc3 100644--- a/packages/cli/src/providers/probe-runner.ts+++ b/packages/cli/src/providers/probe-runner.ts@@ -1,4 +1,5 @@import { type ProbeLinkInput, type ProbeResult, probeLink } from "./probe-live.js";+import type { CandidateOutcome, ExplainedCandidate, RouteExplanation } from "./routing-rules.js";// Interactive probes must outlive the slowest legitimate credential path.// Antigravity may spend up to 40s refreshing the shared token, and its own@@ -16,6 +17,70 @@ export function pinProbeModelSpec(link: Pick<ProbeLinkInput, "provider" | "modelreturn link.modelSpec.includes("@") ? link.modelSpec : `${link.provider}@${link.modelSpec}`;}+/** A candidate the routing chain did not keep. */+export type DroppedOutcome = Exclude<CandidateOutcome, "kept">;++/**+ * What a display says about a dropped candidate, in place of a probe result.+ * Strings only: a display picks the colour from `C.*` at render time.+ */+export const DROPPED_LABEL: Record<DroppedOutcome, string> = {+ "no-credential": "no credential",+ "credential-unreadable": "credential could not be read",+ "not-served": "account does not serve it",+ "excluded-by-membership": "not in the plan's membership",+};++/**+ * The remedy a dropped candidate's credential hint names. An environment variable+ * name reads as an instruction (`set KIMI_API_KEY`); any other hint is already a+ * sentence (a Vertex project source, "enable local provider in global config").+ */+export function droppedRemedy(credentialHint: string | undefined): string | undefined {+ if (!credentialHint) return undefined;+ return /^[A-Z][A-Z0-9_]*$/.test(credentialHint) ? `set ${credentialHint}` : credentialHint;+}++/** One line for a dropped candidate: its outcome, then the remedy when one is known. */+export function describeDropped(outcome: DroppedOutcome, credentialHint?: string): string {+ const remedy = droppedRemedy(credentialHint);+ return remedy ? `${DROPPED_LABEL[outcome]} · ${remedy}` : DROPPED_LABEL[outcome];+}++/** One hop a probe sends a request down: a kept candidate and the model spec to send. */+export type ProbeTarget = ExplainedCandidate & {+ /** The model spec the probe request carries through the proxy. */+ probeSpec: string;+};++/**+ * The hops a probe sends requests down: the KEPT candidates, in chain order.+ *+ * A dropped candidate is never probed. The routing chain will not use it, so a+ * probe result for it would describe a request no session makes; a display lists+ * it with its outcome instead. A native target has no candidates, so it has no+ * targets: its link is reported as not probed (`NATIVE_NOT_PROBED`, native-route.ts).+ *+ * An explicit target is probed as TYPED (`kc@kimi-k3`, `poe:x`,+ * `anthropic/claude-opus-5`), because that string is what a session sends and the+ * proxy serves it past its gate without `route()`. Every other hop is pinned to+ * its own provider, so each hop of a routed chain is probed on its own.+ *+ * `probeSpec` is final: send it with `probeLink`, not `probeProviderRoute`, whose+ * second pinning would turn `poe:x` into `poe@poe:x`.+ */+export function probeTargets(explanation: RouteExplanation): ProbeTarget[] {+ return explanation.candidates+ .filter((candidate) => candidate.outcome === "kept")+ .map((candidate) => ({+ ...candidate,+ probeSpec:+ explanation.source === "explicit"+ ? explanation.requestedModel+ : pinProbeModelSpec(candidate),+ }));+}+export function probeProviderRoute(proxyUrl: string,link: ProbeLinkInput,