diff --git a/README.md b/README.md index f67f686..15af8d0 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,7 @@ Four properties are, and each one is a design constraint in this repository rath | Property | What it rules out | Where it is enforced | |---|---|---| -| **Fails closed** | A cheap model winning a request it cannot physically serve — no tools, no vision, no context room | Hard filters run *before* scoring, and never fail open ([stage 2](#2--apply-hard-eligibility)) | +| **Fails closed** | A cheap model winning a request it cannot physically serve — no tools, no vision, no context room | Hard filters run *before* scoring; the only fail-open is a request no listed model can serve at all, and it is visible in the decision ([stage 2](#2--apply-hard-eligibility)) | | **No inference on the hot path** | Paying a model, a vendor or a round trip to decide which model to pay | Deterministic feature extraction only: ~0.05 ms, $0.00, zero network calls | | **One decision everywhere** | Six products quietly disagreeing about the same request | Single engine, plus a line-by-line Python port held to cross-language parity | | **Auditable by construction** | "The router picked it" as the whole explanation | `tier`, `taskType`, `confidence`, per-candidate `candidateScores` and a `reasoning` string on every decision, and an 88-request snapshot that fails CI when any of them move | @@ -183,10 +183,15 @@ Candidates that cannot satisfy the request are removed before anything is scored - insufficient context window for the conversation - insufficient max-output capacity for the requested length - incompatible structured-output path -- absent from the active model catalog +- reported dead by the host (`unavailableModels`) **Capability errors never enter the preference stage.** This is what "constraint-first" means, and it is why the router fails closed rather than optimistically cheap. +Two deliberate edges, so they are not mistaken for bugs: + +- **Absence from the catalog listing is not a filter.** The gateway keeps serving hidden and aliased ids, so a configured model that is missing from `GET /api/v1/models` stays routable; only an explicit `available: false` row or a host-observed failure removes it. A model with no capability entry passes eligibility, and a model with no price ranks as the most expensive candidate rather than being dropped. +- **When nothing survives, nothing is invented.** If every candidate fails a hard filter, the configured chain still competes (scored as incapable) instead of returning an empty decision; if every rung of a tier is in `unavailableModels`, the tier keeps its original chain so the outage stays visible to the host that reported it. In both cases the host sees a model it knows is wrong and can stop, rather than a substitute it never configured. + ### 3 · Rank the survivors Six bounded factors, per profile. Auto's defaults: @@ -263,7 +268,7 @@ Two rules govern this file, and both are load-bearing: 1. **These are weak priors, never task-quality labels.** They inform the `speed` and `reliability` terms only. A model is not "better" because it is fast. 2. **Historical numbers are never presented as a current provider SLA.** Hosts are expected to inject fresher observations (see below); the committed snapshot exists so the engine is safe and useful when a catalog is temporarily unavailable. -The repository ships 66 live performance profiles (2026-08-29, three samples per model), 9 auditable historical seeds, 74 function-calling probe results, and a built-in snapshot of all 90 text models in the public catalog (2026-10-20 sync). Eleven newly listed models passed a real structured tool-call probe and are admitted as availability fallbacks for tool-required turns. DeepSeek V4 Flash Vision Experimental and Qwen 3.8 Flash did not return a valid tool call and remain fail-closed. GPT-6.1 Sol and DeepSeek V4.1 Flash also passed a structured tool-call probe in the subsequent capability refresh. Mistral Large 4 and Gemini 4 Argon have no probe evidence yet. A model with no probe evidence can serve plain chat but never a tool-required turn. +The repository ships 68 live performance profiles (three samples per model), 9 auditable historical seeds, 82 function-calling probe results, and a built-in snapshot of the 92 text models in the public catalog (2026-11-08 sync, plus routed ids the listing omits). Eleven newly listed models passed a real structured tool-call probe and are admitted as availability fallbacks for tool-required turns. DeepSeek V4 Flash Vision Experimental and Qwen 3.8 Flash did not return a valid tool call and remain fail-closed. GPT-6.1 Sol and DeepSeek V4.1 Flash also passed a structured tool-call probe in the subsequent capability refresh. Mistral Large 4 and Gemini 4 Argon have no probe evidence yet. A model with no probe evidence can serve plain chat but never a tool-required turn. Passing the function-call probe does **not** promote a model to primary. New tool-capable models are appended after the configured and trajectory-benchmarked candidate chains with neutral task affinity; they can recover an unavailable route immediately (cheapest first outside Premium), while primary promotion still requires an end-to-end agent evaluation. @@ -340,7 +345,7 @@ The engine never makes a network call. Everything current is **injected** by the const decision = route(prompt, systemPrompt, maxOutputTokens, { config: DEFAULT_ROUTING_CONFIG, modelPricing, // required — current prices from your catalog - modelCapabilities, // optional — overrides the built-in 86-model snapshot + modelCapabilities, // optional — overrides the built-in 92-model snapshot modelPerformance, // optional — fresh speed/reliability, e.g. the Observatory feed routingProfile: "auto", hasTools, toolCount, toolNames, requiresTools, @@ -414,7 +419,7 @@ Omitted entries fall back to a weak historical prior rather than disqualifying a ### Escape hatches - **One-line rollback.** `config.strategy = "rules"` reverts to the V2 tier selector without a code change. -- **Shadow evaluation.** `config.shadow = { strategy: "rules", sampleRate: 0.1 }` recomputes a comparison decision locally without changing the model that serves the request. The host emits decision metadata only — it never persists prompt content and never makes a second call. +- **Shadow evaluation.** `config.shadow = { strategy: "rules", sampleRate: 0.1 }` tells the host to recompute a comparison decision locally (`getStrategy(config.shadow.strategy).route(...)`) without changing the model that serves the request. Core's `route()` does not read this field; the sampling and the emission belong to the host. The host emits decision metadata only — it never persists prompt content and never makes a second call. - **Promotions.** Time-windowed `tierOverrides` that apply themselves inside their date range and are ignored outside it, so a launch promo needs no release. - **Dead-rung kill-switch.** `options.unavailableModels` hard-removes models the host has observed dead at the gateway (a 400/404/410 on a direct call, a provider EOL) from every chain before selection — never restored by an eligibility fail-open. Effective on the next request, no core release or consumer repin required; the committed chains then catch up in their own time. - **Custom strategies.** Implement `RouterStrategy`, `registerStrategy(yours)`, point `config.strategy` at it. @@ -426,14 +431,14 @@ Omitted entries fall back to a weak historical prior rather than disqualifying a ```bash npm ci npm run typecheck # tsc --noEmit -npm test # vitest — 122 tests across 7 files +npm test # vitest — 189 tests across 11 files npm run build # tsup → dist/ npm run check # all three, and what CI runs # Catalog refresh (needs network; the probe needs a funded Base wallet) npm i --no-save @blockrun/llm -BLOCKRUN_WALLET_KEY=0x… npm run probe:profiles # → model-profiles.generated.json + scripts/probe-tools.json -npm run sync:capabilities # → model-capabilities.ts from GET /api/v1/models +BLOCKRUN_WALLET_KEY=0x… npm run probe:profiles # → src/model-profiles.generated.json + scripts/probe-tools.json +npm run sync:capabilities # → src/model-capabilities.ts from GET /api/v1/models UPDATE_DECISION_SNAPSHOT=1 npm test # then review the snapshot diff ``` @@ -442,7 +447,7 @@ These two scripts update the committed capability and performance snapshots. Run Three rules keep consumers safe: 1. **`dist/` is committed and must match source.** Tarball installs run no build step, so a source edit without a rebuild would silently ship a stale artifact to every pinned consumer. CI runs `git diff --exit-code -- dist`. -2. **Routing changes need test coverage.** The decision path is the product for six downstream packages; `portfolio.test.ts`, `selector.test.ts`, `strategy.test.ts` and `tool-intent.test.ts` are the contract. +2. **Routing changes need test coverage.** The decision path is the product for six downstream packages; `portfolio.test.ts`, `selector.test.ts`, `strategy.test.ts`, `tool-intent.test.ts` and `hardening.test.ts` (malformed-input and multilingual regressions) are the contract. Sources and tests live under `src/`, and tests are typechecked with the library. 3. **Refactors must not move a decision.** `decisions.snapshot.test.ts` routes a frozen 88-request corpus (22 prompts × 4 profiles, mixed tool/vision/structured-output shapes) and compares full decisions byte-for-byte against `decisions.snapshot.json`. A behavior-preserving change leaves it green untouched; a deliberate routing change regenerates it with `UPDATE_DECISION_SNAPSHOT=1 npm test`, and the fixture diff in review shows exactly which requests moved. When the routing logic changes, the [Python port](https://github.com/BlockRunAI/blockrun-llm) has to follow — it is pinned to an upstream commit and its tests assert cross-language parity. diff --git a/dist/index.d.ts b/dist/index.d.ts index ab40969..8ae2aef 100644 --- a/dist/index.d.ts +++ b/dist/index.d.ts @@ -32,7 +32,7 @@ declare const HISTORICAL_MODEL_PROFILES: Readonly): string[]; +/** + * Calculate charge-accurate cost fields for a specific model (server margin + * and minimum-payment floor included — see the cost contract on selectModel). + * Hosts call this to display money and to recost a decision after a fallback. + */ declare function calculateModelCost(model: string, modelPricing: Map, estimatedInputTokens: number, maxOutputTokens: number, routingProfile?: "free" | "eco" | "auto" | "premium"): { costEstimate: number; baselineCost: number; @@ -109,11 +114,12 @@ declare function filterCandidatesByCapacity(models: string[], estimatedInputToke /** * Smart Router Types * - * Four classification tiers — REASONING is distinct from COMPLEX because - * reasoning tasks need different models (o3, gemini-pro) than general - * complex tasks (gpt-4o, sonnet-4). + * Four capability tiers. REASONING is distinct from COMPLEX because proof, + * derivation and multi-step math reward a different model set than broad + * complex work; the configured chains in config.ts carry the current picks. * - * Scoring uses weighted float dimensions with sigmoid confidence calibration. + * Tier scoring uses weighted float dimensions with sigmoid confidence + * calibration (rules.ts); the portfolio strategy ranks within a tier. */ type Tier = "SIMPLE" | "MEDIUM" | "COMPLEX" | "REASONING"; type ScoringResult = { @@ -132,6 +138,7 @@ type RoutingDecision = { model: string; tier: Tier; confidence: number; + /** `"llm"` is reserved for a host-side classifier; core strategies emit `"rules"` or `"portfolio"`. */ method: "rules" | "llm" | "portfolio"; reasoning: string; costEstimate: number; @@ -188,6 +195,9 @@ type RouterOptions = { * selection and never restored by an eligibility fail-open — the operational * kill-switch for a dead chain rung, usable the moment the host observes the * failure instead of waiting on a core release and two consumer repins. + * One exception: a tier whose every rung is listed keeps its configured + * chain, because inventing a substitute would hide the outage from the host + * that reported it (see `applyUnavailableModels`). * Distinct from user-preference exclusion (`filterByExcludeList`), which * deliberately fail-opens rather than empty a chain. */ diff --git a/dist/index.js b/dist/index.js index 2a6d002..d114f1e 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1,4 +1,4 @@ -// rules.ts +// src/rules.ts var UNSEGMENTED_SCRIPT = /[؀-ۿ -ヿ㐀-䶿一-鿿가-힯豈-﫿＀-￯]/; var WORD_CHAR = /[\p{L}\p{N}]/u; var ASCII_PHRASE = /^[a-z0-9' -]+$/; @@ -89,7 +89,7 @@ function scoreKeywordMatch(text, keywords, name, signalLabel, thresholds, scores return { name, score: scores.none, signal: null }; } function scoreMultiStep(text) { - const patterns = [/first.*then/i, /step \d/i, /\d\.\s/]; + const patterns = [/first.*then/i, /step \d/i, /(?:^|\n)\s*\d+[.)]\s/]; const hits = patterns.filter((p) => p.test(text)); if (hits.length > 0) { return { name: "multiStepPatterns", score: 0.5, signal: "multi-step" }; @@ -97,7 +97,7 @@ function scoreMultiStep(text) { return { name: "multiStepPatterns", score: 0, signal: null }; } function scoreQuestionComplexity(prompt) { - const count = (prompt.match(/\?/g) || []).length; + const count = (prompt.match(/[??]/g) || []).length; if (count > 3) { return { name: "questionComplexity", score: 0.5, signal: `${count} questions` }; } @@ -149,6 +149,14 @@ function scoreAgenticTask(text, keywords) { } function classifyByRules(prompt, systemPrompt, estimatedTokens, config) { const userText = prompt.toLowerCase(); + const reasoningDimension = scoreKeywordMatch( + userText, + config.reasoningKeywords, + "reasoningMarkers", + "reasoning", + { low: 1, high: 2 }, + { none: 0, low: 0.7, high: 1 } + ); const dimensions = [ // Token count uses total estimated tokens (system + user) — context size matters for model selection scoreTokenCount(estimatedTokens, config.tokenCountThresholds), @@ -160,14 +168,7 @@ function classifyByRules(prompt, systemPrompt, estimatedTokens, config) { { low: 1, high: 2 }, { none: 0, low: 0.5, high: 1 } ), - scoreKeywordMatch( - userText, - config.reasoningKeywords, - "reasoningMarkers", - "reasoning", - { low: 1, high: 2 }, - { none: 0, low: 0.7, high: 1 } - ), + reasoningDimension, scoreKeywordMatch( userText, config.technicalKeywords, @@ -254,8 +255,7 @@ function classifyByRules(prompt, systemPrompt, estimatedTokens, config) { const w = weights[d.name] ?? 0; weightedScore += d.score * w; } - const reasoningMatches = config.reasoningKeywords.filter((kw) => matchesKeyword(userText, kw)); - if (reasoningMatches.length >= 2) { + if (reasoningDimension.score === 1) { const confidence2 = calibrateConfidence( Math.max(weightedScore, 0.3), // ensure positive for confidence calc @@ -299,29 +299,39 @@ function calibrateConfidence(distance, steepness) { return 1 / (1 + Math.exp(-steepness * distance)); } -// selector.ts +// src/selector.ts var BASELINE_MODEL_ID = "anthropic/claude-opus-4.7"; var BASELINE_INPUT_PRICE = 5; var BASELINE_OUTPUT_PRICE = 25; +function usablePricing(pricing) { + if (!pricing) return void 0; + const ok = (value) => value === void 0 || Number.isFinite(value) && value >= 0; + if (pricing.flatPrice !== void 0) return ok(pricing.flatPrice) ? pricing : void 0; + return ok(pricing.inputPrice) && ok(pricing.outputPrice) ? pricing : void 0; +} +function rawCost(pricing, estimatedInputTokens, maxOutputTokens) { + if (pricing?.flatPrice !== void 0) return pricing.flatPrice; + const inputPrice = pricing?.inputPrice ?? 0; + const outputPrice = pricing?.outputPrice ?? 0; + return estimatedInputTokens / 1e6 * inputPrice + maxOutputTokens / 1e6 * outputPrice; +} +function baselineCostFor(modelPricing, estimatedInputTokens, maxOutputTokens) { + const opusPricing = usablePricing(modelPricing.get(BASELINE_MODEL_ID)); + const inputPrice = opusPricing?.inputPrice ?? BASELINE_INPUT_PRICE; + const outputPrice = opusPricing?.outputPrice ?? BASELINE_OUTPUT_PRICE; + return estimatedInputTokens / 1e6 * inputPrice + maxOutputTokens / 1e6 * outputPrice; +} +function savingsFor(costEstimate, baselineCost, pricing, routingProfile) { + if (routingProfile === "premium" || pricing === void 0 || !(baselineCost > 0)) return 0; + return Math.max(0, (baselineCost - costEstimate) / baselineCost); +} function selectModel(tier, confidence, method, reasoning, tierConfigs, modelPricing, estimatedInputTokens, maxOutputTokens, routingProfile, agenticScore) { const tierConfig = tierConfigs[tier]; const model = tierConfig.primary; - const pricing = modelPricing.get(model); - let costEstimate; - if (pricing?.flatPrice !== void 0) { - costEstimate = pricing.flatPrice; - } else { - const inputPrice = pricing?.inputPrice ?? 0; - const outputPrice = pricing?.outputPrice ?? 0; - costEstimate = estimatedInputTokens / 1e6 * inputPrice + maxOutputTokens / 1e6 * outputPrice; - } - const opusPricing = modelPricing.get(BASELINE_MODEL_ID); - const opusInputPrice = opusPricing?.inputPrice ?? BASELINE_INPUT_PRICE; - const opusOutputPrice = opusPricing?.outputPrice ?? BASELINE_OUTPUT_PRICE; - const baselineInput = estimatedInputTokens / 1e6 * opusInputPrice; - const baselineOutput = maxOutputTokens / 1e6 * opusOutputPrice; - const baselineCost = baselineInput + baselineOutput; - const savings = routingProfile === "premium" || pricing === void 0 ? 0 : baselineCost > 0 ? Math.max(0, (baselineCost - costEstimate) / baselineCost) : 0; + const pricing = usablePricing(modelPricing.get(model)); + const costEstimate = rawCost(pricing, estimatedInputTokens, maxOutputTokens); + const baselineCost = baselineCostFor(modelPricing, estimatedInputTokens, maxOutputTokens); + const savings = savingsFor(costEstimate, baselineCost, pricing, routingProfile); return { model, tier, @@ -341,43 +351,28 @@ function getFallbackChain(tier, tierConfigs) { var SERVER_MARGIN_PERCENT = 5; var MIN_PAYMENT_USD = 1e-3; function calculateModelCost(model, modelPricing, estimatedInputTokens, maxOutputTokens, routingProfile) { - const pricing = modelPricing.get(model); - let costEstimate; - if (pricing?.flatPrice !== void 0) { - costEstimate = Math.max(pricing.flatPrice * (1 + SERVER_MARGIN_PERCENT / 100), MIN_PAYMENT_USD); - } else { - const inputPrice = pricing?.inputPrice ?? 0; - const outputPrice = pricing?.outputPrice ?? 0; - const inputCost = estimatedInputTokens / 1e6 * inputPrice; - const outputCost = maxOutputTokens / 1e6 * outputPrice; - costEstimate = Math.max( - (inputCost + outputCost) * (1 + SERVER_MARGIN_PERCENT / 100), - MIN_PAYMENT_USD - ); - } - const opusPricing = modelPricing.get(BASELINE_MODEL_ID); - const opusInputPrice = opusPricing?.inputPrice ?? BASELINE_INPUT_PRICE; - const opusOutputPrice = opusPricing?.outputPrice ?? BASELINE_OUTPUT_PRICE; - const baselineInput = estimatedInputTokens / 1e6 * opusInputPrice; - const baselineOutput = maxOutputTokens / 1e6 * opusOutputPrice; - const baselineCost = baselineInput + baselineOutput; - const savings = routingProfile === "premium" ? 0 : baselineCost > 0 ? Math.max(0, (baselineCost - costEstimate) / baselineCost) : 0; + const pricing = usablePricing(modelPricing.get(model)); + const costEstimate = Math.max( + rawCost(pricing, estimatedInputTokens, maxOutputTokens) * (1 + SERVER_MARGIN_PERCENT / 100), + MIN_PAYMENT_USD + ); + const baselineCost = baselineCostFor(modelPricing, estimatedInputTokens, maxOutputTokens); + const savings = savingsFor(costEstimate, baselineCost, pricing, routingProfile); return { costEstimate, baselineCost, savings }; } -function filterByToolCalling(models, hasTools, supportsToolCalling) { - if (!hasTools) return models; - const filtered = models.filter(supportsToolCalling); +function keepOrFailOpen(models, keep) { + const filtered = models.filter(keep); return filtered.length > 0 ? filtered : models; } +function filterByToolCalling(models, hasTools, supportsToolCalling) { + return hasTools ? keepOrFailOpen(models, supportsToolCalling) : models; +} function filterByVision(models, hasVision, supportsVision) { - if (!hasVision) return models; - const filtered = models.filter(supportsVision); - return filtered.length > 0 ? filtered : models; + return hasVision ? keepOrFailOpen(models, supportsVision) : models; } function filterByExcludeList(models, excludeList) { if (excludeList.size === 0) return models; - const filtered = models.filter((m) => !excludeList.has(m)); - return filtered.length > 0 ? filtered : models; + return keepOrFailOpen(models, (m) => !excludeList.has(m)); } function getFallbackChainFiltered(tier, tierConfigs, estimatedTotalTokens, getContextWindow) { const fullChain = getFallbackChain(tier, tierConfigs); @@ -402,31 +397,36 @@ function filterCandidatesByCapacity(models, estimatedInputTokens, requestedOutpu return filtered; } -// tokens.ts +// src/tokens.ts var CJK_CHARS = /[ -ヿ㐀-䶿一-鿿가-힯豈-﫿＀-￯]/g; function estimateTokens(text) { if (text.length === 0) return 0; const cjk = text.match(CJK_CHARS)?.length ?? 0; return cjk + Math.ceil((text.length - cjk) / 4); } +var MAX_SCAN_CHARS = 8e3; function scanLimit(promptTruncationChars) { - return Math.max(1, Math.min(8e3, promptTruncationChars)); + if (!Number.isFinite(promptTruncationChars)) return MAX_SCAN_CHARS; + return Math.max(1, Math.min(MAX_SCAN_CHARS, Math.floor(promptTruncationChars))); } function sampleForScan(value, limit) { if (value.length <= limit) return value; const prefixLength = Math.ceil(limit / 2); + const suffixLength = limit - prefixLength; + if (suffixLength <= 0) return value.slice(0, prefixLength); return `${value.slice(0, prefixLength)} -${value.slice(-(limit - prefixLength))}`; +${value.slice(-suffixLength)}`; } -// strategy.ts +// src/strategy.ts function applyPromotions(tierConfigs, promotions, profile, now = /* @__PURE__ */ new Date()) { if (!promotions || promotions.length === 0) return tierConfigs; let result = tierConfigs; for (const promo of promotions) { - const start = new Date(promo.startDate); - const end = new Date(promo.endDate); - if (now < start || now >= end) continue; + const start = Date.parse(promo.startDate); + const end = Date.parse(promo.endDate); + if (!Number.isFinite(start) || !Number.isFinite(end)) continue; + if (now.getTime() < start || now.getTime() >= end) continue; if (promo.profiles && !promo.profiles.includes(profile)) continue; if (result === tierConfigs) { result = { ...tierConfigs }; @@ -569,2094 +569,46 @@ function registerStrategy(strategy) { registry.set(strategy.name, strategy); } -// model-capabilities.ts -var DEFAULT_MODEL_CAPABILITIES = Object.freeze({ - "anthropic/claude-fable-5": { - contextWindow: 1e6, - maxOutputTokens: 128e3, - supportsTools: true, - supportsVision: true - }, - "anthropic/claude-fable-5.1": { - contextWindow: 1e6, - maxOutputTokens: 128e3, - supportsTools: true, - supportsVision: true - }, - "anthropic/claude-haiku-4.5": { - // override: The public catalog's `categories` omit "vision" for this Anthropic model even though the gateway accepts image input for it (the prior hand-maintained snapshot had it, and Anthropic's model card lists it). Without this the vision filter would silently drop it — reported against the catalog; remove once the categories carry vision. - contextWindow: 2e5, - maxOutputTokens: 64e3, - supportsTools: true, - supportsVision: true - }, - "anthropic/claude-opus-4.5": { - contextWindow: 2e5, - maxOutputTokens: 64e3, - supportsTools: true, - supportsVision: true - }, - "anthropic/claude-opus-4.7": { - contextWindow: 1e6, - maxOutputTokens: 128e3, - supportsTools: true, - supportsVision: true - }, - "anthropic/claude-opus-4.8": { - contextWindow: 1e6, - maxOutputTokens: 128e3, - supportsTools: true, - supportsVision: true - }, - "anthropic/claude-opus-5": { - contextWindow: 1e6, - maxOutputTokens: 128e3, - supportsTools: true, - supportsVision: true - }, - "anthropic/claude-opus-5.5": { - contextWindow: 1e6, - maxOutputTokens: 128e3, - supportsTools: true, - supportsVision: true - }, - "anthropic/claude-sonnet-4.5": { - contextWindow: 2e5, - maxOutputTokens: 64e3, - supportsTools: true, - supportsVision: true - }, - "anthropic/claude-sonnet-4.6": { - // override: The public catalog's `categories` omit "vision" for this Anthropic model even though the gateway accepts image input for it (the prior hand-maintained snapshot had it, and Anthropic's model card lists it). Without this the vision filter would silently drop it — reported against the catalog; remove once the categories carry vision. - contextWindow: 1e6, - maxOutputTokens: 128e3, - supportsTools: true, - supportsVision: true - }, - "anthropic/claude-sonnet-5": { - contextWindow: 1e6, - maxOutputTokens: 128e3, - supportsTools: true, - supportsVision: true - }, - "anthropic/claude-sonnet-5.5": { - contextWindow: 1e6, - maxOutputTokens: 128e3, - supportsTools: true, - supportsVision: true - }, - "cohere/north-mini-code": { - // supportsTools: not probed — fails closed - contextWindow: 256e3, - maxOutputTokens: 16384, - supportsTools: false, - supportsVision: false - }, - "deepseek/deepseek-chat": { - contextWindow: 1048576, - maxOutputTokens: 65536, - supportsTools: true, - supportsVision: false - }, - "deepseek/deepseek-reasoner": { - contextWindow: 1048576, - maxOutputTokens: 65536, - supportsTools: true, - supportsVision: false - }, - "deepseek/deepseek-v4-flash-vision-exp": { - contextWindow: 1048576, - maxOutputTokens: 65536, - supportsTools: false, - supportsVision: true - }, - "deepseek/deepseek-v4-pro": { - contextWindow: 1048576, - maxOutputTokens: 65536, - supportsTools: true, - supportsVision: false - }, - "deepseek/deepseek-v4.1-flash": { - contextWindow: 1048576, - maxOutputTokens: 65536, - supportsTools: true, - supportsVision: false - }, - "google/gemini-2.5-flash": { - contextWindow: 1048576, - maxOutputTokens: 65536, - supportsTools: true, - supportsVision: true - }, - "google/gemini-2.5-flash-lite": { - contextWindow: 1048576, - maxOutputTokens: 65536, - supportsTools: true, - supportsVision: false - }, - "google/gemini-2.5-pro": { - contextWindow: 1048576, - maxOutputTokens: 65536, - supportsTools: true, - supportsVision: true - }, - "google/gemini-3-flash-preview": { - contextWindow: 1048576, - maxOutputTokens: 65536, - supportsTools: true, - supportsVision: true - }, - "google/gemini-3.1-flash-lite": { - contextWindow: 1048576, - maxOutputTokens: 65536, - supportsTools: true, - supportsVision: false - }, - "google/gemini-3.1-pro": { - contextWindow: 1048576, - maxOutputTokens: 65536, - supportsTools: true, - supportsVision: true - }, - "google/gemini-3.5-flash": { - contextWindow: 1048576, - maxOutputTokens: 65536, - supportsTools: true, - supportsVision: true - }, - "google/gemini-3.5-flash-lite": { - contextWindow: 1048576, - maxOutputTokens: 65536, - supportsTools: true, - supportsVision: false - }, - "google/gemini-3.6-flash": { - contextWindow: 1048576, - maxOutputTokens: 65536, - supportsTools: true, - supportsVision: true - }, - "google/gemini-3.8-flash": { - contextWindow: 1048576, - maxOutputTokens: 65536, - supportsTools: true, - supportsVision: true - }, - "google/gemini-4-argon": { - // supportsTools: not probed — fails closed - contextWindow: 1048576, - maxOutputTokens: 65536, - supportsTools: false, - supportsVision: true - }, - "minimax/minimax-m2.7": { - contextWindow: 204800, - maxOutputTokens: 16384, - supportsTools: true, - supportsVision: false - }, - "minimax/minimax-m3": { - contextWindow: 1048576, - maxOutputTokens: 65536, - supportsTools: true, - supportsVision: false +// src/config.ts +var DEFAULT_ROUTING_CONFIG = { + version: "3.5", + strategy: "portfolio", + portfolio: { + auto: { + quality: 0.47, + capability: 0.2, + cost: 0.18, + speed: 0.07, + reliability: 0.03, + legacy: 0.05 + }, + eco: { + quality: 0.36, + capability: 0.2, + cost: 0.28, + speed: 0.1, + reliability: 0.04, + legacy: 0.02 + }, + premium: { + quality: 0.58, + capability: 0.2, + cost: 0.08, + speed: 0.06, + reliability: 0.06, + legacy: 0.02 + }, + highStakesBoost: { quality: 0.08, reliability: 0.05 }, + latencySensitiveSpeedBoost: 0.08, + affinityFloorGap: { auto: 0.1, eco: 0.22, premium: 0.05 } }, - "mistral/mistral-large-4": { - // supportsTools: not probed — fails closed - contextWindow: 524288, - maxOutputTokens: 262144, - supportsTools: false, - supportsVision: true - }, - "moonshot/kimi-k3": { - contextWindow: 1048576, - maxOutputTokens: 65536, - supportsTools: true, - supportsVision: true - }, - "nvidia/llama-3.2-11b-vision": { - // supportsTools: not probed — fails closed - contextWindow: 128e3, - maxOutputTokens: 16384, - supportsTools: false, - supportsVision: true - }, - "nvidia/muse-glimmer-30b": { - // supportsTools: not probed — fails closed - contextWindow: 131072, - maxOutputTokens: 16384, - supportsTools: false, - supportsVision: false - }, - "nvidia/nemotron-3-nano-omni-30b-a3b-reasoning": { - // override: The catalog tags this model "vision", but a correctly sized probe does not hold up (ClawRouter, 2026-08-31): a 64x64 solid-red PNG was named correctly 1 of 4 times on Base, and on Solana the image was silently dropped and a text model answered "white". An HTTP 200 with a confident wrong answer gives the caller nothing to branch on, so image turns must not be routed here. It is ecoTiers.SIMPLE.fallback[0] since nemotron-3-nano-30b was delisted (2026-09-08); remove once a probe of this size comes back right on both chains. - contextWindow: 256e3, - maxOutputTokens: 16384, - supportsTools: false, - supportsVision: false - }, - "nvidia/nemotron-3-ultra-550b": { - // supportsTools: not probed — fails closed - contextWindow: 1e6, - maxOutputTokens: 16384, - supportsTools: false, - supportsVision: false - }, - "nvidia/nemotron-3.5-lightning": { - // supportsTools: not probed — fails closed - contextWindow: 1e6, - maxOutputTokens: 16384, - supportsTools: false, - supportsVision: false - }, - "openai/chat-latest": { - contextWindow: 128e3, - maxOutputTokens: 128e3, - supportsTools: true, - supportsVision: true - }, - "openai/gpt-4.1": { - contextWindow: 128e3, - maxOutputTokens: 32768, - supportsTools: true, - supportsVision: true - }, - "openai/gpt-4.1-mini": { - contextWindow: 128e3, - maxOutputTokens: 32768, - supportsTools: true, - supportsVision: false - }, - "openai/gpt-4.1-nano": { - contextWindow: 128e3, - maxOutputTokens: 32768, - supportsTools: true, - supportsVision: false - }, - "openai/gpt-4o": { - contextWindow: 128e3, - maxOutputTokens: 16384, - supportsTools: true, - supportsVision: true - }, - "openai/gpt-4o-mini": { - contextWindow: 128e3, - maxOutputTokens: 16384, - supportsTools: true, - supportsVision: false - }, - "openai/gpt-5-mini": { - contextWindow: 2e5, - maxOutputTokens: 128e3, - supportsTools: true, - supportsVision: false - }, - "openai/gpt-5.1": { - contextWindow: 4e5, - maxOutputTokens: 128e3, - supportsTools: true, - supportsVision: true - }, - "openai/gpt-5.2": { - contextWindow: 4e5, - maxOutputTokens: 128e3, - supportsTools: true, - supportsVision: true - }, - "openai/gpt-5.2-pro": { - // supportsTools: not probed — fails closed - contextWindow: 4e5, - maxOutputTokens: 128e3, - supportsTools: false, - supportsVision: true - }, - "openai/gpt-5.3-codex": { - // supportsTools: gateway unavailable at probe time — fails closed; override: 2026-08-29 probe: every request (6 plain + 3 tool attempts) returned a gateway 500, so the probe measured an incident, not the model. Codex's function calling is established by the 2026-07 Terminal-Bench / tau2 calibration trajectories in portfolio.ts. Hosts observing the 500s should drop it with RouterOptions.unavailableModels rather than this snapshot claiming the model cannot call tools. - contextWindow: 4e5, - maxOutputTokens: 128e3, - supportsTools: true, - supportsVision: false - }, - "openai/gpt-5.4": { - contextWindow: 105e4, - maxOutputTokens: 128e3, - supportsTools: true, - supportsVision: true - }, - "openai/gpt-5.4-mini": { - contextWindow: 4e5, - maxOutputTokens: 128e3, - supportsTools: true, - supportsVision: true - }, - "openai/gpt-5.4-nano": { - contextWindow: 105e4, - maxOutputTokens: 128e3, - supportsTools: true, - supportsVision: false - }, - "openai/gpt-5.4-pro": { - // supportsTools: not probed — fails closed - contextWindow: 105e4, - maxOutputTokens: 128e3, - supportsTools: false, - supportsVision: true - }, - "openai/gpt-5.5": { - contextWindow: 105e4, - maxOutputTokens: 128e3, - supportsTools: true, - supportsVision: true - }, - "openai/gpt-5.5-pro": { - // supportsTools: not probed — fails closed - contextWindow: 105e4, - maxOutputTokens: 128e3, - supportsTools: false, - supportsVision: true - }, - "openai/gpt-5.6-luna": { - contextWindow: 105e4, - maxOutputTokens: 128e3, - supportsTools: true, - supportsVision: true - }, - "openai/gpt-5.6-luna-pro": { - contextWindow: 105e4, - maxOutputTokens: 128e3, - supportsTools: false, - supportsVision: true - }, - "openai/gpt-5.6-sol": { - contextWindow: 105e4, - maxOutputTokens: 128e3, - supportsTools: true, - supportsVision: true - }, - "openai/gpt-5.6-sol-pro": { - contextWindow: 105e4, - maxOutputTokens: 128e3, - supportsTools: true, - supportsVision: true - }, - "openai/gpt-5.6-terra": { - contextWindow: 105e4, - maxOutputTokens: 128e3, - supportsTools: true, - supportsVision: true - }, - "openai/gpt-5.6-terra-pro": { - contextWindow: 105e4, - maxOutputTokens: 128e3, - supportsTools: true, - supportsVision: true - }, - "openai/gpt-6-astra": { - contextWindow: 105e4, - maxOutputTokens: 128e3, - supportsTools: true, - supportsVision: true - }, - "openai/gpt-6-luna": { - contextWindow: 105e4, - maxOutputTokens: 128e3, - supportsTools: true, - supportsVision: true - }, - "openai/gpt-6-sol": { - contextWindow: 105e4, - maxOutputTokens: 128e3, - supportsTools: true, - supportsVision: true - }, - "openai/gpt-6.1-sol": { - contextWindow: 105e4, - maxOutputTokens: 128e3, - supportsTools: true, - supportsVision: true - }, - "openai/o1": { - contextWindow: 2e5, - maxOutputTokens: 1e5, - supportsTools: true, - supportsVision: false - }, - "openai/o3": { - contextWindow: 2e5, - maxOutputTokens: 1e5, - supportsTools: true, - supportsVision: false - }, - "openai/o3-mini": { - contextWindow: 128e3, - maxOutputTokens: 1e5, - supportsTools: true, - supportsVision: false - }, - "openai/o4-mini": { - contextWindow: 128e3, - maxOutputTokens: 1e5, - supportsTools: true, - supportsVision: false - }, - "poolside/laguna-s-2.1": { - // supportsTools: not probed — fails closed - contextWindow: 1048576, - maxOutputTokens: 131072, - supportsTools: false, - supportsVision: false - }, - "poolside/laguna-xs-2.1": { - // supportsTools: not probed — fails closed - contextWindow: 131072, - maxOutputTokens: 16384, - supportsTools: false, - supportsVision: false - }, - "qwen/qwen3.7-flash": { - contextWindow: 1e6, - maxOutputTokens: 65536, - supportsTools: true, - supportsVision: false - }, - "qwen/qwen3.7-max": { - contextWindow: 1e6, - maxOutputTokens: 65536, - supportsTools: true, - supportsVision: false - }, - "qwen/qwen3.7-plus": { - contextWindow: 1e6, - maxOutputTokens: 131072, - supportsTools: true, - supportsVision: false - }, - "qwen/qwen3.8-flash": { - contextWindow: 1e6, - maxOutputTokens: 131072, - supportsTools: false, - supportsVision: true - }, - "qwen/qwen3.8-max": { - // supportsTools: not probed — fails closed - contextWindow: 1e6, - maxOutputTokens: 131072, - supportsTools: false, - supportsVision: false - }, - "tencent/hy4-preview": { - // supportsTools: not probed — fails closed - contextWindow: 1048576, - maxOutputTokens: 64e3, - supportsTools: false, - supportsVision: false - }, - "xai/grok-4.3": { - contextWindow: 1e6, - maxOutputTokens: 16384, - supportsTools: true, - supportsVision: true - }, - "xai/grok-4.5": { - contextWindow: 5e5, - maxOutputTokens: 16384, - supportsTools: true, - supportsVision: true - }, - "xai/grok-4.6": { - contextWindow: 5e5, - maxOutputTokens: 16384, - supportsTools: true, - supportsVision: true - }, - "xai/grok-4.7": { - contextWindow: 5e5, - maxOutputTokens: 16384, - supportsTools: true, - supportsVision: true - }, - "xai/grok-build-0.1": { - contextWindow: 256e3, - maxOutputTokens: 16384, - supportsTools: true, - supportsVision: false - }, - "xiaomi/mimo-v2.5": { - contextWindow: 1048576, - maxOutputTokens: 131072, - supportsTools: true, - supportsVision: true - }, - "xiaomi/mimo-v2.5-pro": { - contextWindow: 1048576, - maxOutputTokens: 131072, - supportsTools: true, - supportsVision: false - }, - "zai/glm-5": { - contextWindow: 2e5, - maxOutputTokens: 128e3, - supportsTools: true, - supportsVision: false - }, - "zai/glm-5-turbo": { - contextWindow: 2e5, - maxOutputTokens: 128e3, - supportsTools: true, - supportsVision: false - }, - "zai/glm-5.1": { - contextWindow: 2e5, - maxOutputTokens: 128e3, - supportsTools: true, - supportsVision: false - }, - "zai/glm-5.2": { - contextWindow: 1e6, - maxOutputTokens: 131072, - supportsTools: true, - supportsVision: false - }, - "zai/glm-5.3": { - contextWindow: 1e6, - maxOutputTokens: 131072, - supportsTools: true, - supportsVision: false - }, - "zai/glm-5.3-flash": { - contextWindow: 1e6, - maxOutputTokens: 131072, - supportsTools: true, - supportsVision: true - } -}); - -// model-profiles.generated.json -var model_profiles_generated_default = { - "anthropic/claude-fable-5": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 9298.5, - p95LatencyMs: 9873.4, - outputTokensPerSecond: 55.17, - errorRate: 0, - samples: 3 - }, - "anthropic/claude-haiku-4.5": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 3157.4, - p95LatencyMs: 3170.7, - outputTokensPerSecond: 162.16, - errorRate: 0, - samples: 3 - }, - "anthropic/claude-opus-4.5": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 6497.7, - p95LatencyMs: 6953.7, - outputTokensPerSecond: 78.99, - errorRate: 0, - samples: 3 - }, - "anthropic/claude-opus-4.7": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 5316.5, - p95LatencyMs: 6121.5, - outputTokensPerSecond: 97.34, - errorRate: 0, - samples: 3 - }, - "anthropic/claude-opus-4.8": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 6216.1, - p95LatencyMs: 6847.7, - outputTokensPerSecond: 82.81, - errorRate: 0, - samples: 3 - }, - "anthropic/claude-opus-5": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 7309, - p95LatencyMs: 7745.2, - outputTokensPerSecond: 70.17, - errorRate: 0, - samples: 3 - }, - "anthropic/claude-sonnet-4.5": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 6330.4, - p95LatencyMs: 6631.6, - outputTokensPerSecond: 81.03, - errorRate: 0, - samples: 3 - }, - "anthropic/claude-sonnet-4.6": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 6508, - p95LatencyMs: 6698.3, - outputTokensPerSecond: 78.6, - errorRate: 0, - samples: 3 - }, - "anthropic/claude-sonnet-5": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 6165.4, - p95LatencyMs: 6582.9, - outputTokensPerSecond: 83.62, - errorRate: 0, - samples: 3 - }, - "deepseek/deepseek-chat": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 4351.4, - p95LatencyMs: 4543.7, - outputTokensPerSecond: 117.78, - errorRate: 0, - samples: 3 - }, - "deepseek/deepseek-reasoner": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 5201.2, - p95LatencyMs: 6079.6, - outputTokensPerSecond: 99.77, - errorRate: 0, - samples: 3 - }, - "deepseek/deepseek-v4-pro": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 8781.2, - p95LatencyMs: 9881.1, - outputTokensPerSecond: 58.98, - errorRate: 0, - samples: 3 - }, - "deepseek/deepseek-v4.1-flash": { - measuredAt: "2026-10-20T18:12:51Z", - latencyMs: 2383.5, - p95LatencyMs: 2547.8, - outputTokensPerSecond: 216.53, - errorRate: 0, - samples: 3 - }, - "google/gemini-2.5-flash": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 5416.4, - p95LatencyMs: 6442.8, - outputTokensPerSecond: 213.07, - errorRate: 0, - samples: 3 - }, - "google/gemini-2.5-flash-lite": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 5002.6, - p95LatencyMs: 5780.3, - outputTokensPerSecond: 408.43, - errorRate: 0, - samples: 3 - }, - "google/gemini-2.5-pro": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 28169.5, - p95LatencyMs: 29491.4, - outputTokensPerSecond: 147.3, - errorRate: 0, - samples: 3 - }, - "google/gemini-3-flash-preview": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 4717.1, - p95LatencyMs: 5037.1, - outputTokensPerSecond: 198.71, - errorRate: 0, - samples: 3 - }, - "google/gemini-3.1-flash-lite": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 2855.8, - p95LatencyMs: 3172.7, - outputTokensPerSecond: 286.91, - errorRate: 0, - samples: 3 - }, - "google/gemini-3.1-pro": { - measuredAt: "2026-08-29T16:59:54Z", - latencyMs: 24194.1, - p95LatencyMs: 27269.6, - outputTokensPerSecond: 109.47, - errorRate: 0, - samples: 3 - }, - "google/gemini-3.5-flash": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 5320.6, - p95LatencyMs: 5429.8, - outputTokensPerSecond: 226.21, - errorRate: 0, - samples: 3 - }, - "google/gemini-3.5-flash-lite": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 3515.8, - p95LatencyMs: 4363.4, - outputTokensPerSecond: 248.9, - errorRate: 0, - samples: 3 - }, - "google/gemini-3.6-flash": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 13020, - p95LatencyMs: 15383.1, - outputTokensPerSecond: 187.87, - errorRate: 0, - samples: 3 - }, - "minimax/minimax-m2.7": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 8761.1, - p95LatencyMs: 10199.3, - outputTokensPerSecond: 59.18, - errorRate: 0, - samples: 3 - }, - "minimax/minimax-m3": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 11101.9, - p95LatencyMs: 26087.1, - outputTokensPerSecond: 101.12, - errorRate: 0, - samples: 3 - }, - "moonshot/kimi-k3": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 24498.9, - p95LatencyMs: 40365.3, - outputTokensPerSecond: 25.11, - errorRate: 0, - samples: 3 - }, - "nvidia/mistral-nemotron": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 7349.6, - p95LatencyMs: 9932.3, - outputTokensPerSecond: 79.48, - errorRate: 0.3333, - samples: 3 - }, - "nvidia/nemotron-3-nano-omni-30b-a3b-reasoning": { - measuredAt: "2026-08-29T16:59:54Z", - latencyMs: 9324.6, - p95LatencyMs: 12992, - outputTokensPerSecond: 64.96, - errorRate: 0.3333, - samples: 3 - }, - "nvidia/nemotron-nano-12b-v2-vl": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 5846.9, - p95LatencyMs: 5846.9, - outputTokensPerSecond: 87.57, - errorRate: 0.6667, - samples: 3 - }, - "nvidia/nemotron-nano-9b-v2": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 5282.5, - p95LatencyMs: 5282.5, - outputTokensPerSecond: 96.92, - errorRate: 0.6667, - samples: 3 - }, - "nvidia/step-3.7-flash": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 4617.4, - p95LatencyMs: 5237.4, - outputTokensPerSecond: 112.92, - errorRate: 0.3333, - samples: 3 - }, - "openai/chat-latest": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 3690.9, - p95LatencyMs: 4344, - outputTokensPerSecond: 111.85, - errorRate: 0, - samples: 3 - }, - "openai/gpt-4.1": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 3527.9, - p95LatencyMs: 3831.7, - outputTokensPerSecond: 141.27, - errorRate: 0, - samples: 3 - }, - "openai/gpt-4.1-mini": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 4268.2, - p95LatencyMs: 5101.5, - outputTokensPerSecond: 103.42, - errorRate: 0, - samples: 3 - }, - "openai/gpt-4.1-nano": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 3088.3, - p95LatencyMs: 3369.2, - outputTokensPerSecond: 150.31, - errorRate: 0, - samples: 3 - }, - "openai/gpt-4o": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 2995.2, - p95LatencyMs: 3174.2, - outputTokensPerSecond: 171.32, - errorRate: 0, - samples: 3 - }, - "openai/gpt-4o-mini": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 4751.5, - p95LatencyMs: 4930.4, - outputTokensPerSecond: 107.84, - errorRate: 0, - samples: 3 - }, - "openai/gpt-5-mini": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 4558.1, - p95LatencyMs: 5081.9, - outputTokensPerSecond: 113.25, - errorRate: 0, - samples: 3 - }, - "openai/gpt-5.2": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 5436.6, - p95LatencyMs: 5928.8, - outputTokensPerSecond: 95.47, - errorRate: 0, - samples: 3 - }, - "openai/gpt-5.3-codex": { - measuredAt: "2026-08-29T16:59:54Z", - latencyMs: 15290.4, - p95LatencyMs: 15290.4, - outputTokensPerSecond: 33.49, - errorRate: 0.6667, - samples: 3 - }, - "openai/gpt-5.4": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 5596, - p95LatencyMs: 5919.4, - outputTokensPerSecond: 91.67, - errorRate: 0, - samples: 3 - }, - "openai/gpt-5.4-mini": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 3377.8, - p95LatencyMs: 3646.8, - outputTokensPerSecond: 138.08, - errorRate: 0, - samples: 3 - }, - "openai/gpt-5.4-nano": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 4040.4, - p95LatencyMs: 4205.9, - outputTokensPerSecond: 118.52, - errorRate: 0, - samples: 3 - }, - "openai/gpt-5.5": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 6367.8, - p95LatencyMs: 7330.7, - outputTokensPerSecond: 81.29, - errorRate: 0, - samples: 3 - }, - "openai/gpt-5.6-luna": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 6064.5, - p95LatencyMs: 7347.3, - outputTokensPerSecond: 87.93, - errorRate: 0, - samples: 3 - }, - "openai/gpt-5.6-luna-pro": { - measuredAt: "2026-08-29T16:59:54Z", - latencyMs: 13914.9, - p95LatencyMs: 13914.9, - outputTokensPerSecond: 36.79, - errorRate: 0.6667, - samples: 3 - }, - "openai/gpt-5.6-sol": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 7720.2, - p95LatencyMs: 9108.2, - outputTokensPerSecond: 67.47, - errorRate: 0, - samples: 3 - }, - "openai/gpt-5.6-sol-pro": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 11442.7, - p95LatencyMs: 13363.1, - outputTokensPerSecond: 148.75, - errorRate: 0, - samples: 3 - }, - "openai/gpt-5.6-terra": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 4941, - p95LatencyMs: 5095.3, - outputTokensPerSecond: 103.69, - errorRate: 0, - samples: 3 - }, - "openai/gpt-5.6-terra-pro": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 3574.1, - p95LatencyMs: 4126.3, - outputTokensPerSecond: 133.59, - errorRate: 0, - samples: 3 - }, - "openai/gpt-6.1-sol": { - measuredAt: "2026-10-20T18:12:51Z", - latencyMs: 11324, - p95LatencyMs: 12747.6, - outputTokensPerSecond: 45.11, - errorRate: 0, - samples: 3 - }, - "openai/o1": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 4324.9, - p95LatencyMs: 5838.1, - outputTokensPerSecond: 125.86, - errorRate: 0, - samples: 3 - }, - "openai/o3": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 5463.4, - p95LatencyMs: 5613.1, - outputTokensPerSecond: 93.8, - errorRate: 0, - samples: 3 - }, - "openai/o3-mini": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 2912.7, - p95LatencyMs: 3092.1, - outputTokensPerSecond: 176.49, - errorRate: 0, - samples: 3 - }, - "openai/o4-mini": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 4958.7, - p95LatencyMs: 5313, - outputTokensPerSecond: 103.81, - errorRate: 0, - samples: 3 - }, - "qwen/qwen3.7-flash": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 3385.5, - p95LatencyMs: 4042.7, - outputTokensPerSecond: 153.94, - errorRate: 0, - samples: 3 - }, - "qwen/qwen3.7-max": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 9387.1, - p95LatencyMs: 10490.2, - outputTokensPerSecond: 54.92, - errorRate: 0, - samples: 3 - }, - "qwen/qwen3.7-plus": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 9766.6, - p95LatencyMs: 9798.2, - outputTokensPerSecond: 52.42, - errorRate: 0, - samples: 3 - }, - "tencent/hy3": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 6062.3, - p95LatencyMs: 7070.2, - outputTokensPerSecond: 87.3, - errorRate: 0, - samples: 3 - }, - "xai/grok-4.3": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 9467.7, - p95LatencyMs: 10087.9, - outputTokensPerSecond: 48.36, - errorRate: 0, - samples: 3 - }, - "xai/grok-4.5": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 13564.8, - p95LatencyMs: 17351.9, - outputTokensPerSecond: 60.71, - errorRate: 0, - samples: 3 - }, - "xai/grok-build-0.1": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 16394.8, - p95LatencyMs: 18035.4, - outputTokensPerSecond: 96.86, - errorRate: 0, - samples: 3 - }, - "xiaomi/mimo-v2.5-pro": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 12070.7, - p95LatencyMs: 12386.8, - outputTokensPerSecond: 42.44, - errorRate: 0, - samples: 3 - }, - "zai/glm-5": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 6839.7, - p95LatencyMs: 7261.4, - outputTokensPerSecond: 75.16, - errorRate: 0, - samples: 3 - }, - "zai/glm-5-turbo": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 55348.5, - p95LatencyMs: 114086.6, - outputTokensPerSecond: 14.64, - errorRate: 0, - samples: 3 - }, - "zai/glm-5.1": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 15658.4, - p95LatencyMs: 17307.1, - outputTokensPerSecond: 32.9, - errorRate: 0, - samples: 3 - }, - "zai/glm-5.2": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 10308.5, - p95LatencyMs: 15127.6, - outputTokensPerSecond: 54.87, - errorRate: 0, - samples: 3 - }, - "zai/glm-5.3": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 7272.4, - p95LatencyMs: 7998.1, - outputTokensPerSecond: 71.09, - errorRate: 0, - samples: 3 - }, - "zai/glm-5.3-flash": { - measuredAt: "2026-08-29T16:51:33Z", - latencyMs: 10545.3, - p95LatencyMs: 11672.4, - outputTokensPerSecond: 49.01, - errorRate: 0, - samples: 3 - } -}; - -// model-profiles.ts -var LIVE_MODEL_PROFILES = Object.freeze( - model_profiles_generated_default -); -var HISTORICAL_MODEL_PROFILES = Object.freeze({ - "anthropic/claude-haiku-4.5": { - measuredAt: "2026-03-16T13:50:48Z", - latencyMs: 2305, - outputTokensPerSecond: 140.6 - }, - "anthropic/claude-sonnet-4.6": { - measuredAt: "2026-03-16T13:50:48Z", - latencyMs: 2110, - outputTokensPerSecond: 121.3 - }, - "deepseek/deepseek-chat": { - measuredAt: "2026-03-16T13:50:48Z", - latencyMs: 1431, - outputTokensPerSecond: 179.2, - intelligenceIndex: 32 - }, - "google/gemini-2.5-flash": { - measuredAt: "2026-03-16T13:50:48Z", - latencyMs: 1238, - outputTokensPerSecond: 207.6, - intelligenceIndex: 20 - }, - "google/gemini-2.5-flash-lite": { - measuredAt: "2026-03-16T13:50:48Z", - latencyMs: 1353, - outputTokensPerSecond: 192.5, - intelligenceIndex: 20 - }, - "google/gemini-2.5-pro": { - measuredAt: "2026-03-16T13:50:48Z", - latencyMs: 1294, - outputTokensPerSecond: 197.8 - }, - "google/gemini-3.1-pro": { - measuredAt: "2026-03-16T13:50:48Z", - latencyMs: 1609, - outputTokensPerSecond: 167.2 - }, - "openai/gpt-4o-mini": { - measuredAt: "2026-03-16T13:50:48Z", - latencyMs: 2764, - outputTokensPerSecond: 92.8 - }, - "openai/gpt-5.3-codex": { - measuredAt: "2026-03-16T13:50:48Z", - latencyMs: 7935, - outputTokensPerSecond: 32.3 - } -}); - -// tool-intent.ts -function inferToolRequirement(prompt, _systemPrompt, toolChoice) { - if (toolChoice === "none") return false; - if (toolChoice === "required") return true; - if (typeof toolChoice === "object" && toolChoice !== null && toolChoice.type === "function") { - return true; - } - const text = prompt; - const explicitTool = /\b(?:use|call|invoke)\s+(?:the\s+)?[\w.-]+\s+(?:tool|function|api)\b|\btool[_ -]?call\b|使用.{0,20}(?:工具|函数|接口)|调用.{0,20}(?:工具|函数|接口)/i; - const codeEnvironment = /\b(?:run|execute)\s+(?:the\s+)?(?:tests?|command|script|build|linter)|\b(?:edit|modify|patch|create|write|save|delete|rename|move|inspect|read)\b.{0,60}\b(?:file|repository|repo|codebase|directory|folder)\b|\b(?:terminal|shell|bash|zsh|pytest|npm test|pnpm test|git\s+(?:status|diff|commit)|docker)\b|(?:运行|执行).{0,20}(?:测试|命令|脚本|构建)|(?:修改|编辑|修复|创建|读取|检查|保存).{0,30}(?:文件|仓库|代码库|目录)/i; - const webAction = /\b(?:browse|search|look up|fetch|open)\b.{0,80}\b(?:web|website|url|online|documentation|docs|news|weather|price)\b|(?:浏览|搜索|查询|打开).{0,30}(?:网页|网站|链接|文档|新闻|天气|价格)/i; - const statefulAction = /\b(?:refund|cancel|book|reserve|purchase|buy|return|exchange|transfer|update|change)\b.{0,80}\b(?:order|booking|reservation|account|address|payment|subscription|ticket|flight|item)\b|(?:退款|取消|预订|购买|退货|换货|转账|更新|修改).{0,30}(?:订单|预订|账户|地址|付款|订阅|票|航班|商品)/i; - return explicitTool.test(text) || codeEnvironment.test(text) || webAction.test(text) || statefulAction.test(text); -} - -// portfolio.ts -var DEFAULT_PORTFOLIO_WEIGHTS = { - auto: { - quality: 0.47, - capability: 0.2, - cost: 0.18, - speed: 0.07, - reliability: 0.03, - legacy: 0.05 - }, - eco: { quality: 0.36, capability: 0.2, cost: 0.28, speed: 0.1, reliability: 0.04, legacy: 0.02 }, - premium: { - quality: 0.58, - capability: 0.2, - cost: 0.08, - speed: 0.06, - reliability: 0.06, - legacy: 0.02 - }, - highStakesBoost: { quality: 0.08, reliability: 0.05 }, - latencySensitiveSpeedBoost: 0.08, - affinityFloorGap: { auto: 0.1, eco: 0.22, premium: 0.05 } -}; -function likelyNeedsParallelToolCalls(prompt, needsTools, toolCount, toolNames) { - if (!needsTools || toolCount === void 0 || toolCount < 1) return false; - const text = prompt.trim(); - const explicitRepeat = /\b(?:in parallel|simultaneously|concurrently|for each|each of|every one|both|(?:two|three|multiple|several)\s+(?:cities|locations|items|tasks|orders|users|files))\b|并行|同时|分别|每个|各自|(?:两个|三个|多个)(?:城市|地点|项目|任务|订单|用户|文件)|cada uno|para cada|simult[aá]neamente/i.test( - text - ); - if (explicitRepeat) return true; - const sentenceClauses = text.split(/[.!?。!?]+/).map((part) => part.trim()).filter((part) => part.length >= 8); - if (/\b(?:also|additionally|furthermore)\b|另外|此外|그리고/i.test(text) && sentenceClauses.length >= 2 || /\band\s+(?:also|for the)\b/i.test(text)) - return true; - const pairedQuantity = /\b\d+(?:\.\d+)?\s+(?:and|or)\s+\d+(?:\.\d+)?\s*(?:gb|mb|tb|kg|g|ml|oz|cups?|cores?|cpus?)\b/i.test( - text - ); - if (pairedQuantity) return true; - const operationTokens = /* @__PURE__ */ new Set([ - "add", - "delete", - "remove", - "cancel", - "return", - "exchange", - "modify", - "book", - "transfer", - "send", - "upload", - "download", - "create", - "close" - ]); - const lowered = text.toLowerCase(); - const matchedOperationTokens = new Set( - (toolNames ?? []).flatMap((name) => name.toLowerCase().split(/[^a-z0-9\u3400-\u9fff]+/)).filter((token) => operationTokens.has(token) && lowered.includes(token)) - ); - if (matchedOperationTokens.size >= 2) return true; - const nonEmptyLines = text.split(/\r?\n/).map((line) => line.trim()).filter(Boolean); - const quantityMentions = text.match( - /\b(?:\d+(?:\.\d+)?|one|two|three|four|five|six|seven|eight|nine|ten)\s*(?:oz|ounce|ounces|g|gram|grams|kg|ml|cups?|pieces?|tablespoons?)\b/gi - ) ?? []; - if (nonEmptyLines.length >= 2 && quantityMentions.length >= 2) return true; - const repeatedLookup = /\b(?:weather|climate|clima|tiempo|temperature|snow|news|report)\b|天气|气象|温度|降雪|新闻|报告/i.test( - text - ); - const multiLocationConnector = /\b(?:and also|both|y|e)\b|还有|以及|和|、/i.test(text); - const commaSeparatedLocations = (text.match(/[,,]/g) ?? []).length >= 2; - if (repeatedLookup && (multiLocationConnector || commaSeparatedLocations)) return true; - const distinctOrderParts = /\b(?:food|meal)\b[\s\S]*\bdrink\b|\bdrink\b[\s\S]*\b(?:food|meal)\b/i.test(text); - const koreanParallelClauses = (text.match(/,/g) ?? []).length >= 3 && /하고|그리고/.test(text); - return distinctOrderParts || koreanParallelClauses; -} -function classifyTask(prompt, systemPrompt, options) { - const fullText = `${systemPrompt ?? ""} ${prompt}`; - const estimatedInputTokens = estimateTokens(fullText); - const limit = scanLimit(options.config.classifier.promptTruncationChars); - const scannedPrompt = sampleForScan(prompt, limit); - const scannedSystemPrompt = sampleForScan(systemPrompt ?? "", limit); - const scannedFullText = `${scannedSystemPrompt} ${scannedPrompt}`; - const text = scannedPrompt.toLowerCase(); - const explicitCodeSignal = /```|\b(?:typescript|javascript|python|rust|java|sql|stack trace|traceback|exception)\b|\.(?:ts|tsx|js|py|go|rs)\b/i.test( - scannedPrompt - ); - const codeConstructSignal = /\b(?:implement|refactor|debug|write|edit|modify|create|define|review|fix)\b[\s\S]{0,48}\b(?:api|function|class|method)\b|\b(?:api|function|class|method)\b[\s\S]{0,48}\b(?:code|implementation|typescript|javascript|python|rust|java)\b/i.test( - scannedPrompt - ); - const nativeCodeSignal = /\b(?:programmed|written|implemented?|code)\s+(?:in|using)\s+(?:c\+\+|c|rust|go)\b/i.test( - scannedPrompt - ); - const errorClassSignal = /\b[A-Z][A-Za-z]*(?:Error|Exception)\b/.test(scannedPrompt); - const hasCode = explicitCodeSignal || codeConstructSignal || nativeCodeSignal || errorClassSignal; - const codeArtifact = /```|\b(?:stack trace|traceback)\b|\.(?:ts|tsx|js|py|go|rs)\b/i.test(scannedPrompt) || codeConstructSignal || nativeCodeSignal || errorClassSignal; - const toolsAvailable = options.hasTools ?? false; - const needsTools = options.requiresTools ?? (toolsAvailable && inferToolRequirement(scannedPrompt, scannedSystemPrompt)); - const likelyParallelToolCalls = likelyNeedsParallelToolCalls( - scannedPrompt, - needsTools, - options.toolCount, - options.toolNames - ); - const normalizedToolNames = (options.toolNames ?? []).map((name) => name.toLowerCase()); - const airlineToolSignal = normalizedToolNames.some( - (name) => /(?:flight|reservation|airport|baggage|passenger)/.test(name) - ); - const retailToolSignal = normalizedToolNames.some( - (name) => /(?:order|product|item|return|exchange|address)/.test(name) - ); - const webResearchToolSignal = normalizedToolNames.some( - (name) => /^(?:web_?search|web_?fetch)$/.test(name) - ); - const agentDomain = airlineToolSignal && !retailToolSignal ? "airline" : retailToolSignal && !airlineToolSignal ? "retail" : webResearchToolSignal ? "web_research" : "other"; - const clueConnectors = scannedFullText.match( - /\b(?:after|before|while|where|whose|which|in \d{4}|as of|over \d+|another|also|furthermore)\b|(?:之后|之前|其中|截至|超过|另一个|此外)/gi - ) ?? []; - const entityResolutionSignal = /\b(?:identify|who (?:is|was)|what (?:is|was) the name|which (?:person|player|company|country|city)|find the (?:person|player|name|entity))\b|(?:找出|识别|是谁|哪位|名称是什么)/i.test( - scannedFullText - ); - const exactAnswerSignal = /\b(?:exact answer|single best-supported answer|following clues|multiple public sources)\b|(?:精确答案|根据.*线索|多个公开来源)/i.test( - scannedFullText - ); - const deepWebResearch = agentDomain === "web_research" && (exactAnswerSignal || entityResolutionSignal && (clueConnectors.length >= 3 || prompt.length >= 320)); - const globalOptimizationSignal = /\b(?:cheapest|lowest[- ]price|least expensive|most expensive|highest(?:[- ]priced)?|largest|smallest|maximum|minimum|best available|closest|not (?:cost|exceed))\b|最便宜|最低价|最贵|最高价|最大|最小/i.test( - scannedPrompt - ); - const globalScopeSignal = /\b(?:everything|all (?:(?:my|your|their|the) )?(?:future |upcoming )?(?:items|orders|passengers|flights|reservations|bookings)|every (?:item|order|passenger|flight|reservation|booking))\b|全部|所有|每个/i.test( - scannedPrompt - ); - const globalChoiceSignal = globalOptimizationSignal || globalScopeSignal; - const crossRecordSignal = /\b(?:another|other|different|previous)\s+(?:order|reservation|booking|account|address)\b|另一(?:个)?(?:订单|预订|账户|地址)|其他(?:订单|预订|账户|地址)/i.test( - scannedPrompt - ); - const reservationIds = scannedPrompt.match(/\b[A-Z0-9]{6}\b/g) ?? []; - const crossReservationBatchSignal = agentDomain === "airline" && (/\b(?:two|three|multiple|several)(?:\s+of\s+(?:my|our|the))?\s+(?:upcoming\s+)?(?:reservations?|bookings?)\b|\b(?:a\s+)?(?:second|third)\s+(?:reservation|booking)\b/i.test( - scannedPrompt - ) || new Set(reservationIds).size >= 2); - const conditionalGlobalWorkflowSignal = agentDomain === "airline" && globalScopeSignal && /\b(?:if|that (?:contain|have)|longer than|shorter than|under|over|at (?:most|least)|wherever possible)\b|如果|超过|少于|不超过|尽可能/i.test( - scannedPrompt - ) && /\b(?:cancel|change|upgrade|move|book)\b[\s\S]*\b(?:cancel|change|upgrade|move|book)\b|取消[\s\S]*(?:升级|更改)|升级[\s\S]*(?:取消|更改)/i.test( - scannedPrompt - ); - const policyExceptionSignal = agentDomain === "retail" && /\b(?:return|refund|send back|get (?:my |the )?money back)\b|退货|退款|退回/i.test( - scannedPrompt - ) && /\b(?:amex|american express|visa|mastercard|credit card|debit card|different card|another card|other card)\b|信用卡|借记卡|其他卡|另一张卡/i.test( - scannedPrompt - ); - const singleSelectedPolicyException = policyExceptionSignal && /\b(?:return|refund|send back)\b[^.!?。!?]{0,96}\b(?:the )?(?:pricier|cheaper|more expensive|less expensive|costlier|one)\b/i.test( - scannedPrompt - ); - const negotiatedWorkflowSignal = agentDomain === "retail" && /\b(?:return|exchange)\b|退货|退回|换货|交换/i.test(scannedPrompt); - const numberedSteps = (scannedPrompt.match(/(?:^|\s)\d+(?:\.\d+)*[.)]\s+/g) ?? []).length; - const complexMultiToolPlan = likelyParallelToolCalls && ((options.toolCount ?? 0) >= 6 || numberedSteps >= 3 || prompt.length > 1200); - let agentRisk = needsTools && singleSelectedPolicyException ? "policy_exception_simple" : needsTools && policyExceptionSignal ? "policy_exception" : ( - // Airline prompts that require a global optimum (for example the - // cheapest itinerary across several candidates) are materially harder - // than applying one change to every passenger in a known reservation. - // Full-session evidence supports Sonnet for the former, while upgrading - // the latter merely because it says "all passengers" caused a large cost - // increase without a quality gain. - needsTools && agentDomain === "airline" && (globalOptimizationSignal || conditionalGlobalWorkflowSignal) ? "complex_high" : needsTools && (likelyParallelToolCalls || globalChoiceSignal || crossRecordSignal || crossReservationBatchSignal || negotiatedWorkflowSignal) ? "high" : "standard" - ); - const needsVision = options.hasVision ?? false; - const needsStructuredOutput = options.requiresStructuredOutput ?? false; - const latencySensitive = /\b(?:urgent|asap|fast|quick|low latency|real[- ]time)\b|尽快|马上|快速|低延迟/i.test( - scannedPrompt - ); - const highStakes = /\b(?:production|security|payment|legal|medical|financial|audit)\b|生产|安全|支付|法律|医疗|财务|审计/i.test( - scannedPrompt - ); - const terminalToolSignal = normalizedToolNames.some( - (name) => /^(?:terminalexec|terminalinspect|terminalsendkeys)$/.test(name) - ); - const simpleTerminalArtifact = /\b(?:create|write|convert|generate|build|implement|run|fix|repair|debug|make)\b[\s\S]{0,120}\b(?:file|script|csv|parquet|json|txt|server|endpoint)\b/i.test( - scannedPrompt - ); - const terminalComplexRepair = terminalToolSignal && /\b(?:multiple|several)\s+(?:scripts?|files?|components?)\b|\b(?:pipeline|dependencies)\b[\s\S]{0,100}\b(?:fail|issue|fix|repair|run|execute)\b|\b(?:identify|find|fix|repair)\s+(?:and\s+)?(?:fix\s+)?all\s+(?:the\s+)?issues\b/i.test( - scannedPrompt - ); - const mentionedTerminalRuntimes = new Set( - (scannedPrompt.match(/\b(?:gcc|clang|rustc|javac|go\s+build|node|python)\b/gi) ?? []).map( - (name) => name.toLowerCase().replace(/\s+/g, " ") - ) - ); - const terminalCrossRuntimeArtifact = terminalToolSignal && (/\bpolyglot\b/i.test(scannedPrompt) || /\b(?:both|each)\b[\s\S]{0,120}\b(?:compilers?|runtimes?|toolchains?)\b/i.test( - scannedPrompt - ) || mentionedTerminalRuntimes.size >= 2 && /\b(?:compile|build|run|execute)\b/i.test(scannedPrompt)); - const terminalFrameworkToNativeArtifact = terminalToolSignal && /\b(?:pytorch|tensorflow|jax|onnx|state[_ -]?dict|checkpoint|safetensors?)\b|\.(?:pth|pt|onnx)\b/i.test( - scannedPrompt - ) && /\b(?:pure|native|programmed|written|implemented?)\s+(?:in|using)\s+(?:c\+\+|c|rust|go)\b|\b(?:c\+\+|c|rust|go)\s+(?:program|binary|executable|cli|tool|implementation)\b/i.test( - scannedPrompt - ) && /\b(?:inference|model|weights?|tensor|export|convert|load)\b/i.test(scannedPrompt); - if (needsTools && (terminalComplexRepair || terminalCrossRuntimeArtifact || terminalFrameworkToNativeArtifact) && (agentRisk === "standard" || agentRisk === "high")) - agentRisk = "complex_high"; - const complexTerminalOperation = /\b(?:git|ssh|nginx|https|certificate|authentication|credential|deploy|production|encrypt|gpg|shred|securely delete|decommission|benchmark|evaluate|embedding|chess|image|search the web|schema|statistical|statistics|aggregate|join|multiple inputs?)\b/i.test( - scannedPrompt - ); - const terminalCredentialSignal = /\b(?:ssh|nginx|certificate|authentication|credentials?|passwords?|api keys?|deploy|production|encrypt|gpg|shred|securely delete|decommission)\b/i.test( - scannedPrompt - ) || /\b(?:access|auth|authentication|bearer|secret|api)\s+tokens?\b|\btokens?\s+(?:secret|credential|authentication)\b/i.test( - scannedPrompt - ); - const terminalSafetySensitive = terminalToolSignal && (highStakes || terminalCredentialSignal); - const implicitTerminalCode = needsTools && terminalToolSignal && agentRisk === "standard" && !highStakes && !complexTerminalOperation && numberedSteps < 3 && prompt.length <= 1e3 && simpleTerminalArtifact; - const language = /[\u3400-\u9fff]/.test(scannedPrompt) ? "zh" : "other"; - const multipleChoiceSignals = (scannedPrompt.match(/(?:^|\n)\s*[A-D][.)]\s+/gim) ?? []).length; - const numericSignals = (scannedPrompt.match(/-?\d+(?:[.,]\d+)?/g) ?? []).length; - const compactMathProblem = !hasCode && prompt.length < 2500 && numericSignals >= 2 && (/[+×÷=%$€£¥]|\b(?:total|each|per|times|half|twice|percent|how many|how much|calculate)\b/i.test( - scannedPrompt - ) || /[??]\s*$/.test(scannedPrompt.trim()) || numericSignals >= 3); - let taskType = "chat"; - if (needsVision) taskType = "vision"; - else if (estimatedInputTokens > 8e4) taskType = "long_context"; - else if (needsTools && (hasCode || implicitTerminalCode)) taskType = "code_agent"; - else if (needsTools && likelyParallelToolCalls && !complexMultiToolPlan) - taskType = "tool_agent_parallel"; - else if (needsTools) taskType = "tool_agent"; - else if (multipleChoiceSignals >= 3) taskType = "reasoning_mcq"; - else if (compactMathProblem) taskType = "reasoning_math"; - else if (errorClassSignal || /\b(?:bug|debug|error|failure|failing|regression|crash|修复|报错|错误|调试)\b/i.test(text)) - taskType = "debug"; - else if (hasCode || /\b(?:refactor|implement|patch|edit|rewrite|重构|实现|修改)\b/i.test(text)) - taskType = "code_edit"; - else if (needsStructuredOutput || /\b(?:extract|json|schema|csv|字段|提取)\b/i.test(text)) - taskType = "extraction"; - else if (/\b(?:prove|derive|theorem|formal|mathematical|reasoning|证明|推导|定理|数学)\b/i.test(text)) - taskType = "reasoning"; - return { - taskType, - estimatedInputTokens, - hasCode, - needsTools, - toolsAvailable, - needsVision, - needsStructuredOutput, - latencySensitive, - highStakes, - language, - likelyParallelToolCalls, - complexMultiToolPlan, - agentDomain, - deepWebResearch, - agentRisk, - terminalToolSignal, - terminalSafetySensitive, - implicitTerminalCode, - codeArtifact - }; -} -function affinity(modelId, task, language = "other", agentDomain = "other", deepWebResearch = false, agentRisk = "standard", terminalToolSignal = false, terminalSafetySensitive = false) { - const id = modelId.toLowerCase(); - const modelName = id.slice(id.indexOf("/") + 1); - const match = (values, score) => values.some((value) => modelName === value) ? score : 0; - const base = 0.68; - switch (task) { - case "code_agent": - if (terminalToolSignal && agentRisk === "complex_high") { - return Math.max( - base, - match(["claude-sonnet-5"], 1), - match(["gpt-5.3-codex"], 0.87), - match(["gpt-5-mini"], 0.78), - match(["gemini-3.5-flash"], 0.76) - ); - } - return Math.max( - base, - match(["gpt-5.3-codex"], 1), - match(["claude-sonnet-5"], 0.98), - match(["gpt-5-mini"], 0.96), - match(["gemini-3.5-flash"], 0.92), - match(["kimi-k3"], 0.9), - match(["deepseek-v4-pro", "glm-5.2"], 0.88) - ); - case "tool_agent": - if (terminalToolSignal && agentRisk === "complex_high") { - return Math.max( - base, - match(["claude-sonnet-5"], 1), - match(["gpt-5.3-codex"], 0.87), - match(["gpt-5-mini"], 0.78), - match(["gemini-3.5-flash"], 0.76) - ); - } - if (terminalToolSignal && !terminalSafetySensitive) { - return Math.max( - base, - match(["gpt-5-mini"], 1), - match(["gpt-5.3-codex"], 0.98), - match(["claude-sonnet-5"], 0.9), - match(["gemini-3.5-flash"], 0.89) - ); - } - if (terminalToolSignal && terminalSafetySensitive) { - return Math.max( - base, - match(["claude-sonnet-5"], 1), - match(["claude-opus-4.8"], 0.9), - match(["gpt-5.3-codex"], 0.84) - ); - } - if (agentDomain === "web_research") { - return deepWebResearch ? Math.max( - base, - match(["claude-sonnet-5"], 1), - match(["gpt-5-mini"], 0.88), - match(["gemini-3.5-flash"], 0.84), - match(["claude-opus-5"], 0.8), - match(["claude-opus-4.8"], 0.78) - ) : Math.max( - base, - match(["claude-sonnet-5"], 1), - match(["gpt-5-mini"], 0.88), - match(["gemini-3.5-flash"], 0.86), - match(["claude-opus-5"], 0.84), - match(["claude-opus-4.8"], 0.82) - ); - } - if (agentDomain === "retail") { - if (agentRisk === "standard") { - return Math.max( - base, - match(["gpt-5-mini"], 1), - match(["claude-sonnet-5"], 0.88), - match(["gemini-3.5-flash"], 0.82), - match(["gpt-5.3-codex"], 0.81), - match(["kimi-k3"], 0.78), - match(["deepseek-v4-pro"], 0.76) - ); - } - if (agentRisk === "policy_exception") { - return Math.max( - base, - match(["gpt-4.1"], 1), - match(["claude-sonnet-5"], 0.9), - match(["deepseek-v4-pro"], 0.82), - match(["gpt-5-mini"], 0.8), - match(["gpt-4o-mini"], 0.76) - ); - } - if (agentRisk === "policy_exception_simple") { - return Math.max( - base, - match(["gpt-5-mini"], 1), - match(["gpt-4.1"], 0.86), - match(["deepseek-v4-pro"], 0.82), - match(["gpt-4o-mini"], 0.8) - ); - } - return Math.max( - base, - match(["deepseek-v4-pro"], 1), - match(["claude-sonnet-5"], 0.88), - match(["gemini-3.5-flash"], 0.82), - match(["gpt-5.3-codex"], 0.81), - match(["kimi-k3"], 0.78), - match(["gpt-5-mini"], 0.76) - ); - } - if (agentDomain === "airline") { - if (agentRisk === "complex_high") { - return Math.max( - base, - match(["claude-sonnet-5"], 1), - match(["gpt-5-mini"], 0.78), - match(["gemini-3.5-flash"], 0.76), - match(["deepseek-v4-pro"], 0.74) - ); - } - return Math.max( - base, - match(["gpt-5-mini"], 1), - match(["claude-sonnet-5"], 0.9), - match(["gemini-3.5-flash"], 0.8), - match(["deepseek-v4-pro"], 0.76) - ); - } - return Math.max( - base, - match(["claude-sonnet-5"], 1), - match(["gemini-3.5-flash"], 0.88), - match(["gpt-5.3-codex"], 0.87), - match(["gpt-5-mini"], 0.84), - match(["kimi-k3"], 0.85), - match(["deepseek-v4-pro"], 0.82) - ); - case "tool_agent_parallel": - if (terminalToolSignal) { - return terminalSafetySensitive ? Math.max( - base, - match(["claude-sonnet-5"], 1), - match(["claude-opus-4.8"], 0.9), - match(["gpt-5.3-codex"], 0.86) - ) : Math.max( - base, - match(["gpt-5-mini"], 1), - match(["gpt-5.3-codex"], 0.98), - match(["claude-sonnet-5"], 0.92), - match(["gemini-3.5-flash"], 0.88) - ); - } - if (agentDomain === "web_research") { - return deepWebResearch ? Math.max( - base, - match(["claude-sonnet-5"], 1), - match(["gpt-5-mini"], 0.88), - match(["gemini-3.5-flash"], 0.84), - match(["claude-opus-5"], 0.8), - match(["claude-opus-4.8"], 0.78) - ) : Math.max( - base, - match(["claude-sonnet-5"], 1), - match(["gpt-5-mini"], 0.88), - match(["gemini-3.5-flash"], 0.86), - match(["claude-opus-5"], 0.84), - match(["claude-opus-4.8"], 0.82) - ); - } - if (agentDomain === "retail") { - if (agentRisk === "policy_exception") { - return Math.max( - base, - match(["gpt-4.1"], 1), - match(["claude-sonnet-5"], 0.9), - match(["deepseek-v4-pro"], 0.82), - match(["gpt-5-mini"], 0.8), - match(["gpt-4o-mini"], 0.76) - ); - } - if (agentRisk === "policy_exception_simple") { - return Math.max( - base, - match(["gpt-5-mini"], 1), - match(["gpt-4.1"], 0.86), - match(["deepseek-v4-pro"], 0.82), - match(["gpt-4o-mini"], 0.8) - ); - } - return Math.max( - base, - match(["deepseek-v4-pro"], 1), - match(["claude-sonnet-5"], 0.88), - match(["claude-opus-4.8"], 0.84), - match(["gpt-5-mini"], 0.78), - match(["gemini-3.5-flash"], 0.76) - ); - } - if (agentDomain === "airline") { - return agentRisk === "complex_high" ? Math.max( - base, - match(["claude-sonnet-5"], 1), - match(["gpt-5-mini"], 0.78), - match(["claude-opus-4.8"], 0.76), - match(["gemini-3.5-flash"], 0.74) - ) : Math.max( - base, - match(["gpt-5-mini"], 1), - match(["claude-sonnet-5"], 0.9), - match(["gemini-3.5-flash"], 0.8) - ); - } - return Math.max( - base, - match(["claude-opus-4.8"], 1), - match(["claude-sonnet-5"], 0.84), - match(["grok-4.5"], 0.82), - match(["gemini-3.5-flash"], 0.8), - match(["deepseek-v4-pro"], 0.78) - ); - case "code_edit": - case "debug": - return Math.max( - base, - match(["gpt-5.3-codex"], 1), - match(["claude-sonnet-4.6"], 0.94), - match(["glm-5.2"], 0.9), - match(["deepseek-v4-pro"], 0.86) - ); - case "reasoning": - return Math.max( - base, - match(["claude-sonnet-5", "claude-sonnet-4.6"], 0.98), - match(["deepseek-v4-pro"], 0.95), - match(["grok-4.5"], 0.94), - match(["gemini-3.1-pro", "gemini-3.5-flash"], 0.92) - ); - case "reasoning_mcq": - return Math.max( - base, - match(["gemini-3-flash-preview"], 1), - match(["gemini-3.5-flash"], 0.91), - match(["grok-4.5"], 0.9), - match(["claude-sonnet-5"], 0.88), - match(["deepseek-v4-pro"], 0.84) - ); - case "reasoning_math": - return Math.max( - base, - match(["gemini-3.5-flash"], 1), - match(["grok-4.5"], 0.93), - match(["claude-sonnet-5", "deepseek-v4-pro", "kimi-k3"], 0.9) - ); - case "vision": - return Math.max( - base, - match(["gemini-3.1-pro"], 0.96), - match(["qwen3.7-max", "claude-sonnet-4.6", "kimi-k3", "grok-4.3"], 0.9) - ); - case "long_context": - return Math.max( - base, - match(["gemini-3.1-pro"], 1), - match(["qwen3.7-max", "glm-5.2"], 0.89), - match(["gemini-3.5-flash"], 0.88), - match(["deepseek-v4-pro"], 0.85) - ); - case "extraction": { - const kimiExtractionAffinity = language === "zh" ? 1 : 0.9; - const otherExtractionAffinity = language === "zh" ? 0.88 : 0.9; - return Math.max( - base, - match(["gemini-3.5-flash", "gemini-2.5-flash", "gpt-4o-mini"], otherExtractionAffinity), - match(["claude-sonnet-5", "claude-sonnet-4.6"], otherExtractionAffinity), - match(["kimi-k3"], kimiExtractionAffinity) - ); - } - default: - return Math.max( - base, - match(["gemini-3.5-flash", "gemini-2.5-flash", "kimi-k3"], 0.86) - ); - } -} -function evidenceCandidates(task) { - if (task === "code_agent") { - return [ - "openai/gpt-5.3-codex", - "anthropic/claude-sonnet-5", - "openai/gpt-5-mini", - "google/gemini-3.5-flash", - "moonshot/kimi-k3", - "deepseek/deepseek-v4-pro" - ]; - } - if (task === "tool_agent") { - return [ - "anthropic/claude-sonnet-5", - "anthropic/claude-opus-5", - "openai/gpt-5-mini", - "openai/gpt-4.1", - "openai/gpt-4o-mini", - "google/gemini-3.5-flash", - "openai/gpt-5.3-codex", - "moonshot/kimi-k3", - "deepseek/deepseek-v4-pro" - ]; - } - if (task === "tool_agent_parallel") { - return [ - "anthropic/claude-opus-5", - "anthropic/claude-opus-4.8", - "anthropic/claude-sonnet-5", - "openai/gpt-5-mini", - "openai/gpt-4.1", - "openai/gpt-4o-mini", - "xai/grok-4.5", - "google/gemini-3.5-flash", - "deepseek/deepseek-v4-pro" - ]; - } - if (task === "long_context") { - return [ - "google/gemini-3.1-pro", - "deepseek/deepseek-v4-pro", - "qwen/qwen3.7-max", - "zai/glm-5.2", - "google/gemini-3.5-flash" - ]; - } - if (task === "reasoning_mcq") { - return [ - "google/gemini-3-flash-preview", - "google/gemini-3.5-flash", - "xai/grok-4.5", - "anthropic/claude-sonnet-5", - "deepseek/deepseek-v4-pro" - ]; - } - if (task === "extraction") { - return ["moonshot/kimi-k3", "google/gemini-3.5-flash", "anthropic/claude-sonnet-5"]; - } - if (task === "reasoning_math") { - return [ - "google/gemini-3.5-flash", - "xai/grok-4.5", - "anthropic/claude-sonnet-5", - "deepseek/deepseek-v4-pro", - "moonshot/kimi-k3" - ]; - } - return []; -} -var VERIFIED_TOOL_FALLBACKS = [ - "anthropic/claude-fable-5.1", - "anthropic/claude-opus-5.5", - "anthropic/claude-sonnet-5.5", - "deepseek/deepseek-v4.1-flash", - "google/gemini-3.8-flash", - "openai/gpt-5.1", - "openai/gpt-6-astra", - "openai/gpt-6-luna", - "openai/gpt-6-sol", - "openai/gpt-6.1-sol", - "xai/grok-4.6", - "xai/grok-4.7", - "xiaomi/mimo-v2.5" -]; -function isEligible(modelId, features, maxOutputTokens, options) { - const model = options.modelCapabilities?.[modelId] ?? DEFAULT_MODEL_CAPABILITIES[modelId]; - if (!model) return true; - if (features.needsTools && !model.supportsTools) return false; - if (features.needsVision && !model.supportsVision) return false; - if (features.needsStructuredOutput && !model.supportsTools) return false; - if (model.maxOutputTokens < maxOutputTokens) return false; - return model.contextWindow >= (features.estimatedInputTokens + maxOutputTokens) * 1.1; -} -function estimatedCost(modelId, options, inputTokens, outputTokens) { - const price2 = options.modelPricing.get(modelId); - if (!price2) return Number.POSITIVE_INFINITY; - if (price2.flatPrice !== void 0) return price2.flatPrice; - return (inputTokens * price2.inputPrice + outputTokens * price2.outputPrice) / 1e6; -} -function profileScore(modelId, options, now) { - const profile = options.modelPerformance?.[modelId] ?? LIVE_MODEL_PROFILES[modelId] ?? HISTORICAL_MODEL_PROFILES[modelId]; - if (!profile) return void 0; - const measuredAt = Date.parse(profile.measuredAt); - if (!Number.isFinite(measuredAt)) return void 0; - const ageDays = Math.max(0, (now.getTime() - measuredAt) / 864e5); - const sampleConfidence = profile.samples === void 0 ? 1 : Math.min(1, Math.max(0, profile.samples) / 10); - const freshness = Math.pow(0.5, ageDays / 30) * sampleConfidence; - const quality = profile.intelligenceIndex === void 0 ? void 0 : Math.min(1, profile.intelligenceIndex / 50); - const speed = Math.min( - 1, - (2e3 / Math.max(500, profile.latencyMs) + profile.outputTokensPerSecond / 250) / 2 - ); - const tailSpeed = Math.min(1, 3e3 / Math.max(750, profile.p95LatencyMs ?? profile.latencyMs)); - const reliability = Math.max(0, 1 - (profile.errorRate ?? 0)); - return { quality, speed, tailSpeed, reliability, freshness }; -} -var PortfolioStrategy = class { - name = "portfolio"; - // Rules set the capability tier; the strategy is stateless, so one instance serves every request. - rules = new RulesStrategy(); - route(prompt, systemPrompt, maxOutputTokens, options) { - const features = classifyTask(prompt, systemPrompt, options); - const base = this.rules.route(prompt, systemPrompt, maxOutputTokens, { - ...options, - requiresTools: features.needsTools - }); - const tierConfigs = base.tierConfigs; - if (!tierConfigs) return base; - const targetTier = (features.taskType === "reasoning_mcq" || features.taskType === "reasoning_math") && (base.tier === "SIMPLE" || base.tier === "MEDIUM") ? "REASONING" : (features.taskType === "debug" || features.taskType === "code_edit") && features.codeArtifact && base.tier === "SIMPLE" ? "MEDIUM" : base.tier; - const tierConfig = tierConfigs[targetTier]; - const configuredCandidates = tierConfig ? getFallbackChain(targetTier, tierConfigs) : []; - const unavailable = new Set(options.unavailableModels ?? []); - const verifiedToolFallbacks = features.needsTools ? VERIFIED_TOOL_FALLBACKS.filter((model2) => options.modelPricing.has(model2)) : []; - if (options.routingProfile !== "premium") { - const fallbackCost = (model2) => estimatedCost(model2, options, features.estimatedInputTokens, maxOutputTokens); - verifiedToolFallbacks.sort((a, b) => fallbackCost(a) - fallbackCost(b)); - } - const chain = [ - .../* @__PURE__ */ new Set([ - ...configuredCandidates, - ...evidenceCandidates(features.taskType), - ...verifiedToolFallbacks - ]) - ].filter( - (model2) => typeof model2 === "string" && model2.length > 0 && !unavailable.has(model2) - ); - const eligible = new Set( - chain.filter((model2) => isEligible(model2, features, maxOutputTokens, options)) - ); - const eligibleCandidates = eligible.size > 0 ? [...eligible] : chain; - if (eligibleCandidates.length === 0) return base; - const profileName = options.routingProfile === "eco" ? "eco" : options.routingProfile === "premium" ? "premium" : "auto"; - const portfolio = options.config.portfolio ?? DEFAULT_PORTFOLIO_WEIGHTS; - const getAffinity = (model2) => affinity( - model2, - features.taskType, - features.language, - features.agentDomain, - features.deepWebResearch, - features.agentRisk, - features.terminalToolSignal, - features.terminalSafetySensitive - ); - const bestAffinity = Math.max(...eligibleCandidates.map(getAffinity)); - const specificAffinity = eligibleCandidates.filter((model2) => getAffinity(model2) > 0.68); - const affinityPool = specificAffinity.length > 0 ? specificAffinity : [eligibleCandidates[0]]; - const affinityFloorGap = features.terminalToolSignal ? Math.max( - portfolio.affinityFloorGap[profileName], - features.terminalSafetySensitive ? 0.15 : 0.12 - ) : portfolio.affinityFloorGap[profileName]; - const candidates = affinityPool.filter( - (model2) => getAffinity(model2) >= bestAffinity - affinityFloorGap - ); - const costs = candidates.map( - (model2) => estimatedCost(model2, options, features.estimatedInputTokens, maxOutputTokens) - ); - const finiteCosts = costs.filter(Number.isFinite); - const minCost = finiteCosts.length > 0 ? Math.min(...finiteCosts) : 0; - const maxCost = finiteCosts.length > 0 ? Math.max(...finiteCosts) : 1; - const now = options.now ?? /* @__PURE__ */ new Date(); - const profileWeights = portfolio[profileName]; - const rankedEntries = candidates.map((model2, index) => { - const cost = estimatedCost(model2, options, features.estimatedInputTokens, maxOutputTokens); - const costScore = Number.isFinite(cost) && maxCost > minCost ? 1 - (cost - minCost) / (maxCost - minCost) : 0.5; - const capabilityScore = eligible.has(model2) ? 1 : 0; - const profile = profileScore(model2, options, now); - const observedQuality = profile?.quality === void 0 ? getAffinity(model2) : getAffinity(model2) * (1 - profile.freshness) + profile.quality * profile.freshness; - const observedSpeed = profile ? profile.speed * profile.freshness + 0.5 * (1 - profile.freshness) : 0.5; - const observedTailSpeed = profile ? profile.tailSpeed * profile.freshness + 0.5 * (1 - profile.freshness) : 0.5; - const observedReliability = profile ? profile.reliability * profile.freshness + (1 - profile.freshness) : 1; - const legacyScore = 1 - index / Math.max(1, candidates.length - 1); - const qualityWeight = profileWeights.quality + (features.highStakes ? portfolio.highStakesBoost.quality : 0); - const speedScore = features.latencySensitive ? observedTailSpeed : observedSpeed; - const speedWeight = profileWeights.speed + (features.latencySensitive ? portfolio.latencySensitiveSpeedBoost : 0); - const reliabilityWeight = profileWeights.reliability + (features.highStakes ? portfolio.highStakesBoost.reliability : 0); - const score = observedQuality * qualityWeight + capabilityScore * profileWeights.capability + costScore * profileWeights.cost + speedScore * speedWeight + observedReliability * reliabilityWeight + legacyScore * profileWeights.legacy; - return { - model: model2, - score, - quality: observedQuality, - cost: costScore, - speed: speedScore, - reliability: observedReliability - }; - }).sort((a, b) => b.score - a.score); - const scoredModels = rankedEntries.map((item) => item.model); - const webResearchFallbackOrder = [ - "anthropic/claude-sonnet-5", - "openai/gpt-5-mini", - "google/gemini-3.5-flash", - "anthropic/claude-opus-5", - "anthropic/claude-opus-4.8", - "openai/gpt-5.3-codex" - ]; - const ranked = features.agentDomain === "web_research" ? [ - ...scoredModels, - ...webResearchFallbackOrder.filter( - (model2) => eligibleCandidates.includes(model2) && !scoredModels.includes(model2) - ), - ...eligibleCandidates.filter( - (model2) => !scoredModels.includes(model2) && !webResearchFallbackOrder.includes(model2) - ) - ] : [...scoredModels, ...eligibleCandidates.filter((model2) => !scoredModels.includes(model2))]; - const model = ranked[0] ?? base.model; - const selectedTierConfigs = { - ...tierConfigs, - [targetTier]: { primary: model, fallback: ranked.slice(1) } - }; - const decision = selectModel( - targetTier, - base.confidence, - "portfolio", - `${base.reasoning} | v3 task=${features.taskType} agentRisk=${features.agentRisk} deepWebResearch=${features.deepWebResearch} terminalCode=${features.implicitTerminalCode} terminalSafety=${features.terminalSafetySensitive} candidates=${ranked.length}`, - selectedTierConfigs, - options.modelPricing, - features.estimatedInputTokens, - maxOutputTokens, - options.routingProfile, - base.agenticScore - ); - return { - ...decision, - tierConfigs: selectedTierConfigs, - profile: base.profile, - candidates: ranked, - candidateScores: rankedEntries.map(({ model: model2, score, quality, cost, speed, reliability }) => ({ - model: model2, - score, - quality, - cost, - speed, - reliability - })), - taskType: features.taskType, - routerVersion: "v3-portfolio" - }; - } -}; - -// catalog.ts -var MODEL_KINDS = ["chat", "image", "video", "music"]; -var PRICE_KEYS = [ - "input", - "output", - "per_image", - "per_second", - "per_track", - "cache_read", - "cache_write", - "transaction_fee", - "per_call_surcharge", - "default_duration_seconds", - "max_duration_seconds" -]; -var UNIT_PRICE = { image: "per_image", video: "per_second", music: "per_track" }; -var MODEL_ID = /^[a-z0-9][a-z0-9._-]*\/[a-zA-Z0-9][a-zA-Z0-9._:+-]*$/; -var record = (value) => value !== null && typeof value === "object" && !Array.isArray(value); -var price = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0; -var capacity = (value) => typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0; -function parseModelCatalog(value) { - if (!record(value) || !Array.isArray(value.data)) { - throw new TypeError("Model catalog must contain a data array"); - } - const entries = /* @__PURE__ */ new Map(); - for (const entry of value.data) { - if (record(entry) && typeof entry.id === "string" && entry.id.length <= 200 && MODEL_ID.test(entry.id)) { - entries.set(entry.id, entry); - } - } - const result = { models: [], chat: [], image: [], video: [], music: [], unavailable: [] }; - const models = []; - const unavailable = []; - for (const [id, entry] of entries) { - if (entry.available === false) unavailable.push(id); - if (entry.available !== void 0 && entry.available !== true || entry.hidden !== void 0 && entry.hidden !== false || !Array.isArray(entry.categories) || !record(entry.pricing)) continue; - const categories = [...new Set(entry.categories.filter((c) => typeof c === "string"))]; - const rawPricing = entry.pricing; - const pricing = {}; - for (const key of PRICE_KEYS) if (price(rawPricing[key])) pricing[key] = rawPricing[key]; - const kinds = MODEL_KINDS.filter((kind) => categories.includes(kind) && (kind === "chat" ? price(rawPricing.input) && price(rawPricing.output) : price(rawPricing[UNIT_PRICE[kind]]))); - if (!kinds.length) continue; - const model = { - id, - name: typeof entry.name === "string" && entry.name.trim() ? entry.name : id, - categories, - kinds, - pricing, - free: kinds.includes("chat") && entry.billing_mode === "free" && pricing.input === 0 && pricing.output === 0, - ...typeof entry.billing_mode === "string" ? { billingMode: entry.billing_mode } : {}, - ...capacity(entry.context_window) !== void 0 ? { contextWindow: capacity(entry.context_window) } : {}, - ...capacity(entry.max_output) !== void 0 ? { maxOutputTokens: capacity(entry.max_output) } : {} - }; - models.push(model); - } - result.models = models; - result.unavailable = unavailable; - for (const kind of MODEL_KINDS) result[kind] = models.filter((model) => model.kinds.includes(kind)); - return result; -} -function toRoutingCatalog(catalog, options = {}) { - const verified = { ...DEFAULT_MODEL_CAPABILITIES, ...options.verifiedCapabilities }; - const modelPricing = /* @__PURE__ */ new Map(); - const modelCapabilities = {}; - for (const model of catalog.chat) { - modelPricing.set(model.id, { inputPrice: model.pricing.input, outputPrice: model.pricing.output }); - const evidence = verified[model.id]; - modelCapabilities[model.id] = { - contextWindow: model.contextWindow ?? evidence?.contextWindow ?? 0, - maxOutputTokens: model.maxOutputTokens ?? evidence?.maxOutputTokens ?? 0, - supportsTools: evidence?.supportsTools === true, - supportsVision: model.categories.includes("vision") - }; - } - return { modelPricing, modelCapabilities, unavailableModels: [...catalog.unavailable] }; -} - -// config.ts -var DEFAULT_ROUTING_CONFIG = { - version: "3.5", - strategy: "portfolio", - portfolio: { - auto: { - quality: 0.47, - capability: 0.2, - cost: 0.18, - speed: 0.07, - reliability: 0.03, - legacy: 0.05 - }, - eco: { - quality: 0.36, - capability: 0.2, - cost: 0.28, - speed: 0.1, - reliability: 0.04, - legacy: 0.02 - }, - premium: { - quality: 0.58, - capability: 0.2, - cost: 0.08, - speed: 0.06, - reliability: 0.06, - legacy: 0.02 - }, - highStakesBoost: { quality: 0.08, reliability: 0.05 }, - latencySensitiveSpeedBoost: 0.08, - affinityFloorGap: { auto: 0.1, eco: 0.22, premium: 0.05 } - }, - classifier: { - llmModel: "google/gemini-2.5-flash", - llmMaxTokens: 10, - llmTemperature: 0, - promptTruncationChars: 500, - cacheTtlMs: 36e5 - // 1 hour + classifier: { + llmModel: "google/gemini-2.5-flash", + llmMaxTokens: 10, + llmTemperature: 0, + promptTruncationChars: 500, + cacheTtlMs: 36e5 + // 1 hour }, scoring: { tokenCountThresholds: { simple: 50, complex: 500 }, @@ -3660,452 +1612,2540 @@ var DEFAULT_ROUTING_CONFIG = { agenticTask: 0.04 // Reduced - agentic signals influence tier selection, not dominate it }, - // Tier boundaries on weighted score axis - tierBoundaries: { - simpleMedium: 0, - mediumComplex: 0.3, - // Raised from 0.18 - prevent simple tasks from reaching expensive COMPLEX tier - complexReasoning: 0.5 - // Raised from 0.4 - reserve for true reasoning tasks + // Tier boundaries on weighted score axis + tierBoundaries: { + simpleMedium: 0, + mediumComplex: 0.3, + // Raised from 0.18 - prevent simple tasks from reaching expensive COMPLEX tier + complexReasoning: 0.5 + // Raised from 0.4 - reserve for true reasoning tasks + }, + // Sigmoid steepness for confidence calibration + confidenceSteepness: 12, + // Below this confidence → ambiguous (null tier) + confidenceThreshold: 0.7 + }, + // ─── Tier chains ─── + // + // Catalog refresh 2026-08-29 (V3.5). Every chain below names only models + // the public catalog lists (GET https://blockrun.ai/api/v1/models). Ids the + // gateway withholds (`hidden: true`) — kimi-k2.5/k2.6/k2.7, the grok-4-fast + // and grok-4-1-fast pairs, grok-4-0709, claude-opus-4.6, gemini-3-pro-preview, + // the whole `free/*` namespace — were removed everywhere, including fallback + // rungs, so a routed model is always one a user can find on blockrun.ai/models. + // + // Primaries moved only where portfolio.ts already carries calibration + // evidence for the successor (Sonnet 5 over Sonnet 4.6, GPT-5 Mini for + // agentic MEDIUM, Gemini 3.5 Flash where Kimi K2.7 was). Newcomers with no + // trajectory evidence yet (gemini-3.6-flash, glm-5.3, glm-5.3-flash, + // gpt-5.6-luna, grok-4.3, minimax-m3, qwen3.7-plus) enter as fallback rungs; + // promotion waits for a calibration run, because version recency is not a + // quality signal. + // + // Latency figures in comments are the 2026-08-29 gateway probe + // (model-profiles.generated.json); prices are the catalog list. + // Auto (balanced) tier configs - current default smart routing + tiers: { + SIMPLE: { + primary: "google/gemini-2.5-flash", + // $0.30/$2.50 — 60% retention (best) in the 2026-03 run; still the fastest quality answer + fallback: [ + "google/gemini-3-flash-preview", + // $0.50/$3 — GPQA 5/6 in the 2026-07 calibration + "google/gemini-3.5-flash-lite", + // $0.30/$2.50, 1M ctx, thinking mode — same price as 2.5 Flash, newer generation + "deepseek/deepseek-chat", + // $0.14/$0.28, 1M ctx + "google/gemini-3.1-flash-lite", + // $0.25/$1.50, 1M ctx + "openai/gpt-5.6-luna", + // $0.20/$1.20, 1M ctx — GPT-5.6 cost tier (cut 2026-07-30) + "openai/gpt-5.4-nano", + // $0.20/$1.25, 1M ctx + "google/gemini-2.5-flash-lite", + // $0.10/$0.40 + "nvidia/nemotron-3.5-lightning" + // FREE backstop — NVIDIA free tier (probed 2026-08-30) + ] + }, + MEDIUM: { + // Was moonshot/kimi-k2.7 (hidden 2026-08). Gemini 3.5 Flash is the + // calibrated successor: MGSM 5/5, GPQA 4/6, extraction band (portfolio.ts). + primary: "google/gemini-3.5-flash", + // $1.50/$9, 1M ctx, vision + tools + fallback: [ + "google/gemini-3.6-flash", + // $1.50/$7.50 — newest Flash, output 17% cheaper than 3.5; awaiting calibration + "zai/glm-5.3-flash", + // $0.15/$0.50, 1M ctx, vision + tools verified live 2026-08-27 + "openai/gpt-5.6-terra", + // $2/$12, 1M ctx — GPT-5.6 balanced tier + "google/gemini-3-flash-preview", + // $0.50/$3 + "deepseek/deepseek-chat", + // $0.14/$0.28 + "google/gemini-2.5-flash", + // $0.30/$2.50 + "minimax/minimax-m3", + // $0.30/$1.20, 1M ctx + "google/gemini-3.1-flash-lite", + // $0.25/$1.50 + "openai/gpt-5.6-luna", + // $0.20/$1.20 + "google/gemini-2.5-flash-lite" + // $0.10/$0.40 + ] + }, + COMPLEX: { + primary: "google/gemini-3.1-pro", + // $2/$12 — proven long-context flagship (portfolio.ts long_context lead) + fallback: [ + "google/gemini-3.6-flash", + // $1.50/$7.50 — Pro-level quality at Flash price (Google's claim; uncalibrated here) + "google/gemini-3.5-flash", + // $1.50/$9 — calibrated + "anthropic/claude-sonnet-5", + // $3/$15 — near-Opus quality, tau2 + Terminal-Bench calibrated + "xai/grok-4.5", + // $2.50/$9 — 503-resistant, independent infra (was grok-4-0709, now hidden) + "google/gemini-2.5-pro", + // $1.25/$10 + "anthropic/claude-sonnet-4.6", + // $3/$15 + "openai/gpt-5.6-terra", + // $2/$12 — GPT-5.6 balanced tier (Sol excluded: #202) + "openai/gpt-5.5", + // $5/$30 — prior OpenAI flagship + "openai/gpt-5.4", + // $2.50/$15 — previous flagship, benchmarked + "zai/glm-5.3", + // $1.40/$4.40, 1M ctx, always-on thinking — verified live 2026-08-19 + "moonshot/kimi-k3", + // $3/$15, 1M ctx — Moonshot flagship (K2.7 successor) + "deepseek/deepseek-v4-pro", + // $0.435/$0.87 — strongest open-weight reasoner + "deepseek/deepseek-chat", + // $0.14/$0.28 — cheap last resort + "google/gemini-2.5-flash" + // $0.30/$2.50 + ] + }, + REASONING: { + // Was xai/grok-4-1-fast-reasoning ($0.20/$0.50, hidden 2026-08). DeepSeek + // Reasoner is the cheapest listed reasoner at the same 1M context. + primary: "deepseek/deepseek-reasoner", + // $0.14/$0.28, 1M ctx + fallback: [ + "deepseek/deepseek-v4-pro", + // $0.435/$0.87 — calibrated reasoning band 0.95 + "xai/grok-4.3", + // $1.50/$4, 1M ctx — xAI reasoning model, vision + "qwen/qwen3.7-plus", + // $0.32/$1.28, 1M ctx — reasoning; needs a generous max_tokens (thinking is billed) + "google/gemini-3.5-flash", + // $1.50/$9 — MGSM 5/5 + "openai/o4-mini", + // $1.10/$4.40 + "openai/o3" + // $2/$8 + ] + } + }, + // Eco tier configs - absolute cheapest (blockrun/eco) + ecoTiers: { + SIMPLE: { + primary: "nvidia/nemotron-3.5-lightning", + // FREE — NVIDIA free tier flagship, 1M ctx + fallback: [ + // Was nvidia/nemotron-3-nano-30b until blockrun delisted it on 2026-09-08 + // (NVIDIA deprovisioned it for the account — a structured per-account + // 404). nano-omni is blockrun's own redirect target for that id, so this + // follows the same rule as the head: the router and the gateway name the + // same model. + "nvidia/nemotron-3-nano-omni-30b-a3b-reasoning", + // FREE — nano-30b's successor, 256K ctx + // The free head keeps rotting with NVIDIA's hosting (deepseek-v4-flash + // 410 2026-08-12, seed-oss-36b 410 2026-08-03, gpt-oss-120b/20b 400 + // 2026-08-21, and on 2026-08-30 FOUR of the five visible free models at + // once — step-3.7-flash, nemotron-nano-9b-v2 and nemotron-nano-12b-v2-vl + // all 410, mistral-nemotron hung). Each retirement retargets the two + // free rungs to the current free tier; the paid rungs below never move. + // The head follows blockrun's own redirect of the model it replaces, so + // the router and the gateway never name different models. + "google/gemini-2.5-flash-lite", + // $0.10/$0.40 — cheapest paid rung + "zai/glm-5.3-flash", + // $0.15/$0.50, 1M ctx, vision + tools + "openai/gpt-5.6-luna", + // $0.20/$1.20, 1M ctx + "openai/gpt-5.4-nano", + // $0.20/$1.25 + "google/gemini-3.1-flash-lite" + // $0.25/$1.50 + ] + }, + MEDIUM: { + primary: "zai/glm-5.3-flash", + // $0.15/$0.50, 1M ctx, vision + tools verified live — cheapest full-capability model + fallback: [ + "deepseek/deepseek-chat", + // $0.14/$0.28 + "google/gemini-3.1-flash-lite", + // $0.25/$1.50 + "openai/gpt-5.6-luna", + // $0.20/$1.20 + "openai/gpt-5.4-nano", + // $0.20/$1.25 + "google/gemini-2.5-flash-lite", + // $0.10/$0.40 + "google/gemini-2.5-flash" + // $0.30/$2.50 + ] + }, + COMPLEX: { + primary: "zai/glm-5.3-flash", + // $0.15/$0.50, 1M ctx + fallback: [ + "deepseek/deepseek-chat", + // $0.14/$0.28, 1M ctx + "minimax/minimax-m3", + // $0.30/$1.20, 1M ctx + "deepseek/deepseek-v4-pro", + // $0.435/$0.87 + "google/gemini-3.1-flash-lite", + // $0.25/$1.50 + "google/gemini-2.5-flash" + // $0.30/$2.50 + ] + }, + REASONING: { + primary: "deepseek/deepseek-reasoner", + // $0.14/$0.28, 1M ctx — cheapest listed reasoner + fallback: [ + "deepseek/deepseek-v4-pro", + // $0.435/$0.87 + "qwen/qwen3.7-plus", + // $0.32/$1.28 — reasoning + "minimax/minimax-m3", + // $0.30/$1.20 — reasoning + coding + "zai/glm-5.3-flash" + // $0.15/$0.50 — reasoning tokens alongside content + ] + } + }, + // Premium tier configs - best quality (blockrun/premium) + // codex=complex coding, flash=simple coding, sonnet=reasoning/instructions, fable/opus=architecture/PM/audits + premiumTiers: { + SIMPLE: { + // Was moonshot/kimi-k2.7 (hidden 2026-08). + primary: "google/gemini-3.5-flash", + // $1.50/$9, 1M ctx, vision + tools — calibrated + fallback: [ + "google/gemini-3.6-flash", + // $1.50/$7.50 — newest Flash + "anthropic/claude-haiku-4.5", + // $1/$5 + "zai/glm-5.3", + // $1.40/$4.40, 1M ctx + "google/gemini-2.5-flash", + // $0.30/$2.50 + "google/gemini-3.5-flash-lite", + // $0.30/$2.50 + "deepseek/deepseek-chat" + // $0.14/$0.28 + ] + }, + MEDIUM: { + primary: "openai/gpt-5.3-codex", + // $1.75/$14 - 400K context, 128K output — code_edit/debug lead (portfolio.ts) + fallback: [ + "anthropic/claude-sonnet-5", + // $3/$15 — code_agent band 0.98 + "moonshot/kimi-k3", + // $3/$15, 1M ctx — Moonshot flagship + "zai/glm-5.3", + // $1.40/$4.40 — long-horizon coding + "google/gemini-3.6-flash", + // $1.50/$7.50 + "google/gemini-3.5-flash", + // $1.50/$9 + "google/gemini-2.5-pro", + // $1.25/$10 + "xai/grok-4.5", + // $2.50/$9 + "anthropic/claude-sonnet-4.6", + // $3/$15 + "openai/gpt-5.6-terra" + // $2/$12 + ] + }, + COMPLEX: { + // fable-5 was promoted here 2026-06-11, force-reverted 2026-06-13 when Anthropic + // withdrew the offer, and restored 2026-07-14 now that BlockRun has relisted it. + primary: "anthropic/claude-fable-5", + // Best quality for complex tasks — Mythos-class flagship above Opus ($10/$50, 1M ctx, always-on thinking) + // Fallback chain de-Gemini'd 2026-04-22: when Anthropic 503s, Gemini is + // also prone to "high demand" 503s (correlated failure — everyone falls + // back to Google at the same time). Prefer in-family → xAI → Moonshot → + // OpenAI flagship → Z.AI → DeepSeek → NVIDIA free instead. + fallback: [ + "anthropic/claude-opus-5", + // in-family hot swap first (half the price, 1M ctx + adaptive thinking) + "anthropic/claude-opus-4.8", + // in-family hot swap (identical cost to 5) + "anthropic/claude-opus-4.7", + // in-family hot swap (identical cost to 4.8) + "anthropic/claude-sonnet-5", + // Sonnet-tier drop-down, near-Opus quality + "anthropic/claude-sonnet-4.6", + "xai/grok-4.5", + // xAI flagship — 503-resistant, direct-xAI SKU + "moonshot/kimi-k3", + // Moonshot flagship, independent infra + "openai/gpt-5.6-terra", + // GPT-5.6 balanced tier — stable (Sol excluded: #202) + "openai/gpt-5.5", + // Prior OpenAI flagship — 1M+ ctx, native agent + computer use + "openai/gpt-5.4", + // Previous flagship (slow but stable, benchmarked at 6,213ms) + "openai/gpt-5.3-codex", + "zai/glm-5.3", + // Z.AI flagship, 1M ctx + "deepseek/deepseek-v4-pro", + // strongest open-weight reasoner + "deepseek/deepseek-chat", + // Cheap, reliable + "nvidia/nemotron-3.5-lightning" + // NVIDIA free ultimate backstop + ] + }, + REASONING: { + // Sonnet 5 promoted over Sonnet 4.6 (same price; reasoning band 0.98 for both, + // plus Sonnet 5's tau2/BrowseComp trajectory evidence). + primary: "anthropic/claude-sonnet-5", + // $3/$15, 1M ctx, adaptive thinking + fallback: [ + "anthropic/claude-sonnet-4.6", + // in-family hot swap — same cost + "anthropic/claude-opus-5", + // Newest flagship Opus w/ adaptive thinking + "anthropic/claude-opus-4.8", + // Prior flagship Opus — identical cost to 5 + "anthropic/claude-opus-4.7", + // Flagship Opus w/ adaptive thinking + "xai/grok-4.5", + // reasoning band 0.94 + "deepseek/deepseek-v4-pro", + // reasoning band 0.95 + "xai/grok-4.3", + // $1.50/$4 — xAI reasoning model + "openai/o4-mini", + // $1.10/$4.40 + "openai/o3" + // $2/$8 + ] + } + }, + // Agentic tier configs - models that excel at multi-step autonomous tasks + agenticTiers: { + SIMPLE: { + primary: "openai/gpt-4o-mini", + // $0.15/$0.60 - best tool compliance at lowest cost + fallback: [ + "openai/gpt-5.6-luna", + // $0.20/$1.20 — lightweight agentic tier of GPT-5.6 + "zai/glm-5.3-flash", + // $0.15/$0.50 — tool calls verified live 2026-08-27 + "anthropic/claude-haiku-4.5", + // $1/$5 + "google/gemini-2.5-flash" + // $0.30/$2.50 + ] + }, + MEDIUM: { + // Was moonshot/kimi-k2.7 (hidden 2026-08). GPT-5 Mini carries the + // Terminal-Bench and tau2 trajectory evidence in portfolio.ts. + primary: "openai/gpt-5-mini", + // $0.25/$2 — 4/7 Terminal-Bench, 5/6 tau2 airline + fallback: [ + "google/gemini-3.5-flash", + // $1.50/$9 — tool_agent band 0.88 + "zai/glm-5.3-flash", + // $0.15/$0.50 — tools verified + "openai/gpt-5.6-terra", + // $2/$12 + "openai/gpt-4o-mini", + // $0.15/$0.60 — reliable tool calling + "anthropic/claude-haiku-4.5", + // $1/$5 + "deepseek/deepseek-chat", + // $0.14/$0.28 + "moonshot/kimi-k3" + // $3/$15 — tool_agent band 0.85 + ] }, - // Sigmoid steepness for confidence calibration - confidenceSteepness: 12, - // Below this confidence → ambiguous (null tier) - confidenceThreshold: 0.7 + COMPLEX: { + // Sonnet 5 promoted over Sonnet 4.6: tau2 airline + retail reward 1.0, + // Terminal-Bench safety band lead (portfolio.ts). + primary: "anthropic/claude-sonnet-5", + // $3/$15 — best agentic quality per trajectory evidence + // Fallback chain de-Gemini'd 2026-04-22: Gemini's "high demand" 503s + // correlate with Anthropic outages (everyone falls back together). + // Prefer 503-resistant providers first. + fallback: [ + "anthropic/claude-sonnet-4.6", + // in-family hot swap — same cost + "anthropic/claude-opus-5", + // Newest flagship Opus — in-family hot swap + "anthropic/claude-opus-4.8", + // Prior flagship Opus — identical cost to 5 + "anthropic/claude-opus-4.7", + // Flagship Opus — in-family hot swap + "xai/grok-4.5", + // xAI flagship — strong tool use, independent infra + "moonshot/kimi-k3", + // Moonshot flagship — independent infra + "openai/gpt-5.6-terra", + // GPT-5.6 balanced tier — stable (Sol excluded: #202) + "openai/gpt-5.5", + // Prior flagship — native agent + computer use (exactly the agentic-tier use case) + "openai/gpt-5.4", + // Previous flagship — reliable + "openai/gpt-5.3-codex", + // code_agent lead + "zai/glm-5.3", + // long-horizon coding + "deepseek/deepseek-v4-pro", + // retail high-risk 3/3 + "deepseek/deepseek-chat", + // cheap, reliable + "nvidia/nemotron-3.5-lightning" + // NVIDIA free ultimate backstop + ] + }, + REASONING: { + primary: "anthropic/claude-sonnet-5", + // $3/$15 — strong tool use + adaptive thinking + fallback: [ + "anthropic/claude-sonnet-4.6", + // in-family hot swap — same cost + "anthropic/claude-opus-5", + // Newest flagship Opus w/ adaptive thinking + "anthropic/claude-opus-4.8", + // Prior flagship Opus — identical cost to 5 + "anthropic/claude-opus-4.7", + // Flagship Opus w/ adaptive thinking + "xai/grok-4.5", + // reasoning band 0.94 + "deepseek/deepseek-v4-pro", + // reasoning band 0.95 + "deepseek/deepseek-reasoner" + // $0.14/$0.28 + ] + } + }, + // Time-windowed promotions — auto-applied when active, ignored when expired. + // The GLM-5.1 launch promo (2026-04-01 → 2026-05-01) was the last entry and + // has expired; the list is kept empty so the mechanism stays wired. + promotions: [], + overrides: { + maxTokensForceComplex: 1e5, + structuredOutputMinTier: "MEDIUM", + ambiguousDefaultTier: "MEDIUM" + // agenticMode left undefined → auto-detect via tools/agenticScore. + // Set to `true` to force agentic tiers; `false` to disable them entirely. + } +}; + +// src/model-capabilities.ts +var DEFAULT_MODEL_CAPABILITIES = Object.freeze({ + "anthropic/claude-fable-5": { + contextWindow: 1e6, + maxOutputTokens: 128e3, + supportsTools: true, + supportsVision: true + }, + "anthropic/claude-fable-5.1": { + contextWindow: 1e6, + maxOutputTokens: 128e3, + supportsTools: true, + supportsVision: true + }, + "anthropic/claude-haiku-4.5": { + // override: The public catalog's `categories` omit "vision" for this Anthropic model even though the gateway accepts image input for it (the prior hand-maintained snapshot had it, and Anthropic's model card lists it). Without this the vision filter would silently drop it — reported against the catalog; remove once the categories carry vision. + contextWindow: 2e5, + maxOutputTokens: 64e3, + supportsTools: true, + supportsVision: true + }, + "anthropic/claude-opus-4.5": { + contextWindow: 2e5, + maxOutputTokens: 64e3, + supportsTools: true, + supportsVision: true + }, + "anthropic/claude-opus-4.7": { + contextWindow: 1e6, + maxOutputTokens: 128e3, + supportsTools: true, + supportsVision: true + }, + "anthropic/claude-opus-4.8": { + contextWindow: 1e6, + maxOutputTokens: 128e3, + supportsTools: true, + supportsVision: true + }, + "anthropic/claude-opus-5": { + contextWindow: 1e6, + maxOutputTokens: 128e3, + supportsTools: true, + supportsVision: true + }, + "anthropic/claude-opus-5.5": { + contextWindow: 1e6, + maxOutputTokens: 128e3, + supportsTools: true, + supportsVision: true + }, + "anthropic/claude-sonnet-4.5": { + contextWindow: 2e5, + maxOutputTokens: 64e3, + supportsTools: true, + supportsVision: true + }, + "anthropic/claude-sonnet-4.6": { + // override: The public catalog's `categories` omit "vision" for this Anthropic model even though the gateway accepts image input for it (the prior hand-maintained snapshot had it, and Anthropic's model card lists it). Without this the vision filter would silently drop it — reported against the catalog; remove once the categories carry vision. + contextWindow: 1e6, + maxOutputTokens: 128e3, + supportsTools: true, + supportsVision: true + }, + "anthropic/claude-sonnet-5": { + contextWindow: 1e6, + maxOutputTokens: 128e3, + supportsTools: true, + supportsVision: true + }, + "anthropic/claude-sonnet-5.5": { + contextWindow: 1e6, + maxOutputTokens: 128e3, + supportsTools: true, + supportsVision: true + }, + "cohere/north-mini-code": { + // supportsTools: not probed — fails closed + contextWindow: 256e3, + maxOutputTokens: 16384, + supportsTools: false, + supportsVision: false + }, + "deepseek/deepseek-chat": { + // override: The 2026-11-08 catalog began tagging deepseek/deepseek-chat "vision" (it was text-only through 2026-10-20), and DeepSeek still ships image input as a separate experimental id (deepseek/deepseek-v4-flash-vision-exp). No image probe has confirmed the tag. Routing an image turn to a model that silently drops the image returns a confident 200 the caller cannot branch on, so this fails closed until a correctly sized image probe passes on both chains; then remove this entry. + contextWindow: 1048576, + maxOutputTokens: 65536, + supportsTools: true, + supportsVision: false + }, + "deepseek/deepseek-reasoner": { + // override: The 2026-11-08 catalog began tagging deepseek/deepseek-reasoner "vision" (it was text-only through 2026-10-20), and DeepSeek still ships image input as a separate experimental id (deepseek/deepseek-v4-flash-vision-exp). No image probe has confirmed the tag. Routing an image turn to a model that silently drops the image returns a confident 200 the caller cannot branch on, so this fails closed until a correctly sized image probe passes on both chains; then remove this entry. + contextWindow: 1048576, + maxOutputTokens: 65536, + supportsTools: true, + supportsVision: false + }, + "deepseek/deepseek-v4-flash-vision-exp": { + contextWindow: 1048576, + maxOutputTokens: 65536, + supportsTools: false, + supportsVision: true + }, + "deepseek/deepseek-v4-pro": { + contextWindow: 1048576, + maxOutputTokens: 65536, + supportsTools: true, + supportsVision: false + }, + "deepseek/deepseek-v4.1-flash": { + // override: The 2026-11-08 catalog began tagging deepseek/deepseek-v4.1-flash "vision" (it was text-only through 2026-10-20), and DeepSeek still ships image input as a separate experimental id (deepseek/deepseek-v4-flash-vision-exp). No image probe has confirmed the tag. Routing an image turn to a model that silently drops the image returns a confident 200 the caller cannot branch on, so this fails closed until a correctly sized image probe passes on both chains; then remove this entry. + contextWindow: 1048576, + maxOutputTokens: 65536, + supportsTools: true, + supportsVision: false + }, + "google/gemini-2.5-flash": { + contextWindow: 1048576, + maxOutputTokens: 65536, + supportsTools: true, + supportsVision: true + }, + "google/gemini-2.5-flash-lite": { + contextWindow: 1048576, + maxOutputTokens: 65536, + supportsTools: true, + supportsVision: false + }, + "google/gemini-2.5-pro": { + contextWindow: 1048576, + maxOutputTokens: 65536, + supportsTools: true, + supportsVision: true + }, + "google/gemini-3-flash-preview": { + contextWindow: 1048576, + maxOutputTokens: 65536, + supportsTools: true, + supportsVision: true + }, + "google/gemini-3.1-flash-lite": { + contextWindow: 1048576, + maxOutputTokens: 65536, + supportsTools: true, + supportsVision: false + }, + "google/gemini-3.1-pro": { + contextWindow: 1048576, + maxOutputTokens: 65536, + supportsTools: true, + supportsVision: true + }, + "google/gemini-3.5-flash": { + contextWindow: 1048576, + maxOutputTokens: 65536, + supportsTools: true, + supportsVision: true + }, + "google/gemini-3.5-flash-lite": { + contextWindow: 1048576, + maxOutputTokens: 65536, + supportsTools: true, + supportsVision: false + }, + "google/gemini-3.6-flash": { + contextWindow: 1048576, + maxOutputTokens: 65536, + supportsTools: true, + supportsVision: true + }, + "google/gemini-3.8-flash": { + contextWindow: 1048576, + maxOutputTokens: 65536, + supportsTools: true, + supportsVision: true + }, + "google/gemini-4-argon": { + // supportsTools: not probed — fails closed + contextWindow: 1048576, + maxOutputTokens: 65536, + supportsTools: false, + supportsVision: true + }, + "minimax/minimax-m2.7": { + contextWindow: 204800, + maxOutputTokens: 16384, + supportsTools: true, + supportsVision: false + }, + "minimax/minimax-m3": { + contextWindow: 1048576, + maxOutputTokens: 65536, + supportsTools: true, + supportsVision: false + }, + "mistral/mistral-large-4": { + // supportsTools: not probed — fails closed + contextWindow: 524288, + maxOutputTokens: 262144, + supportsTools: false, + supportsVision: true + }, + "moonshot/kimi-k3": { + // absent from the 2026-11-08 listing but still routed — previous entry retained; probe before removing + contextWindow: 1048576, + maxOutputTokens: 65536, + supportsTools: true, + supportsVision: true + }, + "moonshot/kimi-k3.1-pro": { + // supportsTools: not probed — fails closed + contextWindow: 1048576, + maxOutputTokens: 65536, + supportsTools: false, + supportsVision: true + }, + "nvidia/minimax-m3.1-flash": { + // supportsTools: not probed — fails closed + contextWindow: 1048576, + maxOutputTokens: 16384, + supportsTools: false, + supportsVision: false + }, + "nvidia/muse-glimmer-30b": { + // supportsTools: not probed — fails closed + contextWindow: 131072, + maxOutputTokens: 16384, + supportsTools: false, + supportsVision: false + }, + "nvidia/nemotron-3-nano-omni-30b-a3b-reasoning": { + // override: The catalog tags this model "vision", but a correctly sized probe does not hold up (ClawRouter, 2026-08-31): a 64x64 solid-red PNG was named correctly 1 of 4 times on Base, and on Solana the image was silently dropped and a text model answered "white". An HTTP 200 with a confident wrong answer gives the caller nothing to branch on, so image turns must not be routed here. It is ecoTiers.SIMPLE.fallback[0] since nemotron-3-nano-30b was delisted (2026-09-08); remove once a probe of this size comes back right on both chains. + contextWindow: 256e3, + maxOutputTokens: 16384, + supportsTools: false, + supportsVision: false + }, + "nvidia/nemotron-3-super-120b": { + // supportsTools: not probed — fails closed + contextWindow: 131072, + maxOutputTokens: 16384, + supportsTools: false, + supportsVision: true + }, + "nvidia/nemotron-3-ultra-550b": { + // supportsTools: not probed — fails closed + contextWindow: 1e6, + maxOutputTokens: 16384, + supportsTools: false, + supportsVision: false + }, + "nvidia/nemotron-3.5-bolt": { + // supportsTools: not probed — fails closed + contextWindow: 131072, + maxOutputTokens: 16384, + supportsTools: false, + supportsVision: true + }, + "nvidia/nemotron-3.5-lightning": { + // supportsTools: not probed — fails closed + contextWindow: 1e6, + maxOutputTokens: 16384, + supportsTools: false, + supportsVision: false + }, + "openai/chat-latest": { + contextWindow: 128e3, + maxOutputTokens: 128e3, + supportsTools: true, + supportsVision: true + }, + "openai/gpt-4.1": { + contextWindow: 128e3, + maxOutputTokens: 32768, + supportsTools: true, + supportsVision: true + }, + "openai/gpt-4.1-mini": { + contextWindow: 128e3, + maxOutputTokens: 32768, + supportsTools: true, + supportsVision: false + }, + "openai/gpt-4o": { + contextWindow: 128e3, + maxOutputTokens: 16384, + supportsTools: true, + supportsVision: true + }, + "openai/gpt-4o-mini": { + contextWindow: 128e3, + maxOutputTokens: 16384, + supportsTools: true, + supportsVision: false + }, + "openai/gpt-5-mini": { + contextWindow: 2e5, + maxOutputTokens: 128e3, + supportsTools: true, + supportsVision: false + }, + "openai/gpt-5.1": { + contextWindow: 4e5, + maxOutputTokens: 128e3, + supportsTools: true, + supportsVision: true + }, + "openai/gpt-5.2": { + contextWindow: 4e5, + maxOutputTokens: 128e3, + supportsTools: true, + supportsVision: true + }, + "openai/gpt-5.2-pro": { + // supportsTools: not probed — fails closed + contextWindow: 4e5, + maxOutputTokens: 128e3, + supportsTools: false, + supportsVision: true + }, + "openai/gpt-5.3-codex": { + // supportsTools: gateway unavailable at probe time — fails closed; override: 2026-08-29 probe: every request (6 plain + 3 tool attempts) returned a gateway 500, so the probe measured an incident, not the model. Codex's function calling is established by the 2026-07 Terminal-Bench / tau2 calibration trajectories in portfolio.ts. Hosts observing the 500s should drop it with RouterOptions.unavailableModels rather than this snapshot claiming the model cannot call tools. + contextWindow: 4e5, + maxOutputTokens: 128e3, + supportsTools: true, + supportsVision: false + }, + "openai/gpt-5.4": { + contextWindow: 105e4, + maxOutputTokens: 128e3, + supportsTools: true, + supportsVision: true + }, + "openai/gpt-5.4-mini": { + contextWindow: 4e5, + maxOutputTokens: 128e3, + supportsTools: true, + supportsVision: true + }, + "openai/gpt-5.4-nano": { + contextWindow: 105e4, + maxOutputTokens: 128e3, + supportsTools: true, + supportsVision: false + }, + "openai/gpt-5.4-pro": { + // supportsTools: not probed — fails closed + contextWindow: 105e4, + maxOutputTokens: 128e3, + supportsTools: false, + supportsVision: true + }, + "openai/gpt-5.5": { + contextWindow: 105e4, + maxOutputTokens: 128e3, + supportsTools: true, + supportsVision: true + }, + "openai/gpt-5.5-pro": { + // supportsTools: not probed — fails closed + contextWindow: 105e4, + maxOutputTokens: 128e3, + supportsTools: false, + supportsVision: true + }, + "openai/gpt-5.6-luna": { + contextWindow: 105e4, + maxOutputTokens: 128e3, + supportsTools: true, + supportsVision: true + }, + "openai/gpt-5.6-luna-pro": { + contextWindow: 105e4, + maxOutputTokens: 128e3, + supportsTools: false, + supportsVision: true + }, + "openai/gpt-5.6-sol": { + contextWindow: 105e4, + maxOutputTokens: 128e3, + supportsTools: true, + supportsVision: true + }, + "openai/gpt-5.6-sol-pro": { + contextWindow: 105e4, + maxOutputTokens: 128e3, + supportsTools: true, + supportsVision: true + }, + "openai/gpt-5.6-terra": { + contextWindow: 105e4, + maxOutputTokens: 128e3, + supportsTools: true, + supportsVision: true + }, + "openai/gpt-5.6-terra-pro": { + contextWindow: 105e4, + maxOutputTokens: 128e3, + supportsTools: true, + supportsVision: true + }, + "openai/gpt-6-astra": { + contextWindow: 105e4, + maxOutputTokens: 128e3, + supportsTools: true, + supportsVision: true + }, + "openai/gpt-6-luna": { + contextWindow: 105e4, + maxOutputTokens: 128e3, + supportsTools: true, + supportsVision: true + }, + "openai/gpt-6-sol": { + contextWindow: 105e4, + maxOutputTokens: 128e3, + supportsTools: true, + supportsVision: true + }, + "openai/gpt-6.1-sol": { + contextWindow: 105e4, + maxOutputTokens: 128e3, + supportsTools: true, + supportsVision: true + }, + "openai/o1": { + contextWindow: 2e5, + maxOutputTokens: 1e5, + supportsTools: true, + supportsVision: false + }, + "openai/o3": { + contextWindow: 2e5, + maxOutputTokens: 1e5, + supportsTools: true, + supportsVision: false + }, + "openai/o3-mini": { + contextWindow: 128e3, + maxOutputTokens: 1e5, + supportsTools: true, + supportsVision: false + }, + "openai/o4-mini": { + contextWindow: 128e3, + maxOutputTokens: 1e5, + supportsTools: true, + supportsVision: false + }, + "poolside/laguna-s-2.1": { + // supportsTools: not probed — fails closed + contextWindow: 1048576, + maxOutputTokens: 131072, + supportsTools: false, + supportsVision: false + }, + "poolside/laguna-xs-2.1": { + // supportsTools: not probed — fails closed + contextWindow: 131072, + maxOutputTokens: 16384, + supportsTools: false, + supportsVision: false + }, + "qwen/qwen3.7-flash": { + contextWindow: 1e6, + maxOutputTokens: 65536, + supportsTools: true, + supportsVision: false + }, + "qwen/qwen3.7-max": { + contextWindow: 1e6, + maxOutputTokens: 65536, + supportsTools: true, + supportsVision: false + }, + "qwen/qwen3.7-plus": { + contextWindow: 1e6, + maxOutputTokens: 131072, + supportsTools: true, + supportsVision: false + }, + "qwen/qwen3.8-flash": { + contextWindow: 1e6, + maxOutputTokens: 131072, + supportsTools: false, + supportsVision: true + }, + "qwen/qwen3.8-max": { + // supportsTools: not probed — fails closed + contextWindow: 1e6, + maxOutputTokens: 131072, + supportsTools: false, + supportsVision: false + }, + "tencent/hy4-preview": { + // supportsTools: not probed — fails closed + contextWindow: 1048576, + maxOutputTokens: 64e3, + supportsTools: false, + supportsVision: false + }, + "xai/grok-4.3": { + contextWindow: 1e6, + maxOutputTokens: 16384, + supportsTools: true, + supportsVision: true + }, + "xai/grok-4.5": { + contextWindow: 5e5, + maxOutputTokens: 16384, + supportsTools: true, + supportsVision: true + }, + "xai/grok-4.6": { + contextWindow: 5e5, + maxOutputTokens: 16384, + supportsTools: true, + supportsVision: true + }, + "xai/grok-4.7": { + contextWindow: 5e5, + maxOutputTokens: 16384, + supportsTools: true, + supportsVision: true + }, + "xai/grok-build-0.1": { + contextWindow: 256e3, + maxOutputTokens: 16384, + supportsTools: true, + supportsVision: false + }, + "xiaomi/mimo-v2.5": { + contextWindow: 1048576, + maxOutputTokens: 131072, + supportsTools: true, + supportsVision: true + }, + "xiaomi/mimo-v2.5-pro": { + contextWindow: 1048576, + maxOutputTokens: 131072, + supportsTools: true, + supportsVision: false + }, + "zai/glm-5": { + contextWindow: 2e5, + maxOutputTokens: 128e3, + supportsTools: true, + supportsVision: false + }, + "zai/glm-5-turbo": { + contextWindow: 2e5, + maxOutputTokens: 128e3, + supportsTools: true, + supportsVision: false + }, + "zai/glm-5.1": { + contextWindow: 2e5, + maxOutputTokens: 128e3, + supportsTools: true, + supportsVision: false + }, + "zai/glm-5.2": { + contextWindow: 1e6, + maxOutputTokens: 131072, + supportsTools: true, + supportsVision: false + }, + "zai/glm-5.3": { + contextWindow: 1e6, + maxOutputTokens: 131072, + supportsTools: true, + supportsVision: false + }, + "zai/glm-5.3-flash": { + contextWindow: 1e6, + maxOutputTokens: 131072, + supportsTools: true, + supportsVision: true + } +}); + +// src/model-profiles.generated.json +var model_profiles_generated_default = { + "anthropic/claude-fable-5": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 9298.5, + p95LatencyMs: 9873.4, + outputTokensPerSecond: 55.17, + errorRate: 0, + samples: 3 + }, + "anthropic/claude-haiku-4.5": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 3157.4, + p95LatencyMs: 3170.7, + outputTokensPerSecond: 162.16, + errorRate: 0, + samples: 3 + }, + "anthropic/claude-opus-4.5": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 6497.7, + p95LatencyMs: 6953.7, + outputTokensPerSecond: 78.99, + errorRate: 0, + samples: 3 + }, + "anthropic/claude-opus-4.7": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 5316.5, + p95LatencyMs: 6121.5, + outputTokensPerSecond: 97.34, + errorRate: 0, + samples: 3 + }, + "anthropic/claude-opus-4.8": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 6216.1, + p95LatencyMs: 6847.7, + outputTokensPerSecond: 82.81, + errorRate: 0, + samples: 3 + }, + "anthropic/claude-opus-5": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 7309, + p95LatencyMs: 7745.2, + outputTokensPerSecond: 70.17, + errorRate: 0, + samples: 3 + }, + "anthropic/claude-sonnet-4.5": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 6330.4, + p95LatencyMs: 6631.6, + outputTokensPerSecond: 81.03, + errorRate: 0, + samples: 3 + }, + "anthropic/claude-sonnet-4.6": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 6508, + p95LatencyMs: 6698.3, + outputTokensPerSecond: 78.6, + errorRate: 0, + samples: 3 + }, + "anthropic/claude-sonnet-5": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 6165.4, + p95LatencyMs: 6582.9, + outputTokensPerSecond: 83.62, + errorRate: 0, + samples: 3 + }, + "deepseek/deepseek-chat": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 4351.4, + p95LatencyMs: 4543.7, + outputTokensPerSecond: 117.78, + errorRate: 0, + samples: 3 + }, + "deepseek/deepseek-reasoner": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 5201.2, + p95LatencyMs: 6079.6, + outputTokensPerSecond: 99.77, + errorRate: 0, + samples: 3 + }, + "deepseek/deepseek-v4-pro": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 8781.2, + p95LatencyMs: 9881.1, + outputTokensPerSecond: 58.98, + errorRate: 0, + samples: 3 + }, + "deepseek/deepseek-v4.1-flash": { + measuredAt: "2026-10-20T18:12:51Z", + latencyMs: 2383.5, + p95LatencyMs: 2547.8, + outputTokensPerSecond: 216.53, + errorRate: 0, + samples: 3 + }, + "google/gemini-2.5-flash": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 5416.4, + p95LatencyMs: 6442.8, + outputTokensPerSecond: 213.07, + errorRate: 0, + samples: 3 + }, + "google/gemini-2.5-flash-lite": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 5002.6, + p95LatencyMs: 5780.3, + outputTokensPerSecond: 408.43, + errorRate: 0, + samples: 3 + }, + "google/gemini-2.5-pro": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 28169.5, + p95LatencyMs: 29491.4, + outputTokensPerSecond: 147.3, + errorRate: 0, + samples: 3 + }, + "google/gemini-3-flash-preview": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 4717.1, + p95LatencyMs: 5037.1, + outputTokensPerSecond: 198.71, + errorRate: 0, + samples: 3 + }, + "google/gemini-3.1-flash-lite": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 2855.8, + p95LatencyMs: 3172.7, + outputTokensPerSecond: 286.91, + errorRate: 0, + samples: 3 + }, + "google/gemini-3.1-pro": { + measuredAt: "2026-08-29T16:59:54Z", + latencyMs: 24194.1, + p95LatencyMs: 27269.6, + outputTokensPerSecond: 109.47, + errorRate: 0, + samples: 3 + }, + "google/gemini-3.5-flash": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 5320.6, + p95LatencyMs: 5429.8, + outputTokensPerSecond: 226.21, + errorRate: 0, + samples: 3 + }, + "google/gemini-3.5-flash-lite": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 3515.8, + p95LatencyMs: 4363.4, + outputTokensPerSecond: 248.9, + errorRate: 0, + samples: 3 + }, + "google/gemini-3.6-flash": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 13020, + p95LatencyMs: 15383.1, + outputTokensPerSecond: 187.87, + errorRate: 0, + samples: 3 + }, + "minimax/minimax-m2.7": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 8761.1, + p95LatencyMs: 10199.3, + outputTokensPerSecond: 59.18, + errorRate: 0, + samples: 3 + }, + "minimax/minimax-m3": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 11101.9, + p95LatencyMs: 26087.1, + outputTokensPerSecond: 101.12, + errorRate: 0, + samples: 3 + }, + "moonshot/kimi-k3": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 24498.9, + p95LatencyMs: 40365.3, + outputTokensPerSecond: 25.11, + errorRate: 0, + samples: 3 + }, + "nvidia/mistral-nemotron": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 7349.6, + p95LatencyMs: 9932.3, + outputTokensPerSecond: 79.48, + errorRate: 0.3333, + samples: 3 + }, + "nvidia/nemotron-3-nano-omni-30b-a3b-reasoning": { + measuredAt: "2026-08-29T16:59:54Z", + latencyMs: 9324.6, + p95LatencyMs: 12992, + outputTokensPerSecond: 64.96, + errorRate: 0.3333, + samples: 3 + }, + "nvidia/nemotron-nano-12b-v2-vl": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 5846.9, + p95LatencyMs: 5846.9, + outputTokensPerSecond: 87.57, + errorRate: 0.6667, + samples: 3 + }, + "nvidia/nemotron-nano-9b-v2": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 5282.5, + p95LatencyMs: 5282.5, + outputTokensPerSecond: 96.92, + errorRate: 0.6667, + samples: 3 + }, + "nvidia/step-3.7-flash": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 4617.4, + p95LatencyMs: 5237.4, + outputTokensPerSecond: 112.92, + errorRate: 0.3333, + samples: 3 + }, + "openai/chat-latest": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 3690.9, + p95LatencyMs: 4344, + outputTokensPerSecond: 111.85, + errorRate: 0, + samples: 3 + }, + "openai/gpt-4.1": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 3527.9, + p95LatencyMs: 3831.7, + outputTokensPerSecond: 141.27, + errorRate: 0, + samples: 3 + }, + "openai/gpt-4.1-mini": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 4268.2, + p95LatencyMs: 5101.5, + outputTokensPerSecond: 103.42, + errorRate: 0, + samples: 3 + }, + "openai/gpt-4.1-nano": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 3088.3, + p95LatencyMs: 3369.2, + outputTokensPerSecond: 150.31, + errorRate: 0, + samples: 3 + }, + "openai/gpt-4o": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 2995.2, + p95LatencyMs: 3174.2, + outputTokensPerSecond: 171.32, + errorRate: 0, + samples: 3 + }, + "openai/gpt-4o-mini": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 4751.5, + p95LatencyMs: 4930.4, + outputTokensPerSecond: 107.84, + errorRate: 0, + samples: 3 + }, + "openai/gpt-5-mini": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 4558.1, + p95LatencyMs: 5081.9, + outputTokensPerSecond: 113.25, + errorRate: 0, + samples: 3 + }, + "openai/gpt-5.2": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 5436.6, + p95LatencyMs: 5928.8, + outputTokensPerSecond: 95.47, + errorRate: 0, + samples: 3 + }, + "openai/gpt-5.3-codex": { + measuredAt: "2026-08-29T16:59:54Z", + latencyMs: 15290.4, + p95LatencyMs: 15290.4, + outputTokensPerSecond: 33.49, + errorRate: 0.6667, + samples: 3 + }, + "openai/gpt-5.4": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 5596, + p95LatencyMs: 5919.4, + outputTokensPerSecond: 91.67, + errorRate: 0, + samples: 3 + }, + "openai/gpt-5.4-mini": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 3377.8, + p95LatencyMs: 3646.8, + outputTokensPerSecond: 138.08, + errorRate: 0, + samples: 3 }, - // ─── Tier chains ─── - // - // Catalog refresh 2026-08-29 (V3.5). Every chain below names only models - // the public catalog lists (GET https://blockrun.ai/api/v1/models). Ids the - // gateway withholds (`hidden: true`) — kimi-k2.5/k2.6/k2.7, the grok-4-fast - // and grok-4-1-fast pairs, grok-4-0709, claude-opus-4.6, gemini-3-pro-preview, - // the whole `free/*` namespace — were removed everywhere, including fallback - // rungs, so a routed model is always one a user can find on blockrun.ai/models. - // - // Primaries moved only where portfolio.ts already carries calibration - // evidence for the successor (Sonnet 5 over Sonnet 4.6, GPT-5 Mini for - // agentic MEDIUM, Gemini 3.5 Flash where Kimi K2.7 was). Newcomers with no - // trajectory evidence yet (gemini-3.6-flash, glm-5.3, glm-5.3-flash, - // gpt-5.6-luna, grok-4.3, minimax-m3, qwen3.7-plus) enter as fallback rungs; - // promotion waits for a calibration run, because version recency is not a - // quality signal. - // - // Latency figures in comments are the 2026-08-29 gateway probe - // (model-profiles.generated.json); prices are the catalog list. - // Auto (balanced) tier configs - current default smart routing - tiers: { - SIMPLE: { - primary: "google/gemini-2.5-flash", - // $0.30/$2.50 — 60% retention (best) in the 2026-03 run; still the fastest quality answer - fallback: [ - "google/gemini-3-flash-preview", - // $0.50/$3 — GPQA 5/6 in the 2026-07 calibration - "google/gemini-3.5-flash-lite", - // $0.30/$2.50, 1M ctx, thinking mode — same price as 2.5 Flash, newer generation - "deepseek/deepseek-chat", - // $0.14/$0.28, 1M ctx - "google/gemini-3.1-flash-lite", - // $0.25/$1.50, 1M ctx - "openai/gpt-5.6-luna", - // $0.20/$1.20, 1M ctx — GPT-5.6 cost tier (cut 2026-07-30) - "openai/gpt-5.4-nano", - // $0.20/$1.25, 1M ctx - "google/gemini-2.5-flash-lite", - // $0.10/$0.40 - "nvidia/nemotron-3.5-lightning" - // FREE backstop — NVIDIA free tier (probed 2026-08-30) - ] - }, - MEDIUM: { - // Was moonshot/kimi-k2.7 (hidden 2026-08). Gemini 3.5 Flash is the - // calibrated successor: MGSM 5/5, GPQA 4/6, extraction band (portfolio.ts). - primary: "google/gemini-3.5-flash", - // $1.50/$9, 1M ctx, vision + tools - fallback: [ - "google/gemini-3.6-flash", - // $1.50/$7.50 — newest Flash, output 17% cheaper than 3.5; awaiting calibration - "zai/glm-5.3-flash", - // $0.15/$0.50, 1M ctx, vision + tools verified live 2026-08-27 - "openai/gpt-5.6-terra", - // $2/$12, 1M ctx — GPT-5.6 balanced tier - "google/gemini-3-flash-preview", - // $0.50/$3 - "deepseek/deepseek-chat", - // $0.14/$0.28 - "google/gemini-2.5-flash", - // $0.30/$2.50 - "minimax/minimax-m3", - // $0.30/$1.20, 1M ctx - "google/gemini-3.1-flash-lite", - // $0.25/$1.50 - "openai/gpt-5.6-luna", - // $0.20/$1.20 - "google/gemini-2.5-flash-lite" - // $0.10/$0.40 - ] - }, - COMPLEX: { - primary: "google/gemini-3.1-pro", - // $2/$12 — proven long-context flagship (portfolio.ts long_context lead) - fallback: [ - "google/gemini-3.6-flash", - // $1.50/$7.50 — Pro-level quality at Flash price (Google's claim; uncalibrated here) - "google/gemini-3.5-flash", - // $1.50/$9 — calibrated - "anthropic/claude-sonnet-5", - // $3/$15 — near-Opus quality, tau2 + Terminal-Bench calibrated - "xai/grok-4.5", - // $2.50/$9 — 503-resistant, independent infra (was grok-4-0709, now hidden) - "google/gemini-2.5-pro", - // $1.25/$10 - "anthropic/claude-sonnet-4.6", - // $3/$15 - "openai/gpt-5.6-terra", - // $2/$12 — GPT-5.6 balanced tier (Sol excluded: #202) - "openai/gpt-5.5", - // $5/$30 — prior OpenAI flagship - "openai/gpt-5.4", - // $2.50/$15 — previous flagship, benchmarked - "zai/glm-5.3", - // $1.40/$4.40, 1M ctx, always-on thinking — verified live 2026-08-19 - "moonshot/kimi-k3", - // $3/$15, 1M ctx — Moonshot flagship (K2.7 successor) - "deepseek/deepseek-v4-pro", - // $0.435/$0.87 — strongest open-weight reasoner - "deepseek/deepseek-chat", - // $0.14/$0.28 — cheap last resort - "google/gemini-2.5-flash" - // $0.30/$2.50 - ] - }, - REASONING: { - // Was xai/grok-4-1-fast-reasoning ($0.20/$0.50, hidden 2026-08). DeepSeek - // Reasoner is the cheapest listed reasoner at the same 1M context. - primary: "deepseek/deepseek-reasoner", - // $0.14/$0.28, 1M ctx - fallback: [ - "deepseek/deepseek-v4-pro", - // $0.435/$0.87 — calibrated reasoning band 0.95 - "xai/grok-4.3", - // $1.50/$4, 1M ctx — xAI reasoning model, vision - "qwen/qwen3.7-plus", - // $0.32/$1.28, 1M ctx — reasoning; needs a generous max_tokens (thinking is billed) - "google/gemini-3.5-flash", - // $1.50/$9 — MGSM 5/5 - "openai/o4-mini", - // $1.10/$4.40 - "openai/o3" - // $2/$8 - ] - } + "openai/gpt-5.4-nano": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 4040.4, + p95LatencyMs: 4205.9, + outputTokensPerSecond: 118.52, + errorRate: 0, + samples: 3 + }, + "openai/gpt-5.5": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 6367.8, + p95LatencyMs: 7330.7, + outputTokensPerSecond: 81.29, + errorRate: 0, + samples: 3 + }, + "openai/gpt-5.6-luna": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 6064.5, + p95LatencyMs: 7347.3, + outputTokensPerSecond: 87.93, + errorRate: 0, + samples: 3 + }, + "openai/gpt-5.6-luna-pro": { + measuredAt: "2026-08-29T16:59:54Z", + latencyMs: 13914.9, + p95LatencyMs: 13914.9, + outputTokensPerSecond: 36.79, + errorRate: 0.6667, + samples: 3 + }, + "openai/gpt-5.6-sol": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 7720.2, + p95LatencyMs: 9108.2, + outputTokensPerSecond: 67.47, + errorRate: 0, + samples: 3 + }, + "openai/gpt-5.6-sol-pro": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 11442.7, + p95LatencyMs: 13363.1, + outputTokensPerSecond: 148.75, + errorRate: 0, + samples: 3 + }, + "openai/gpt-5.6-terra": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 4941, + p95LatencyMs: 5095.3, + outputTokensPerSecond: 103.69, + errorRate: 0, + samples: 3 + }, + "openai/gpt-5.6-terra-pro": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 3574.1, + p95LatencyMs: 4126.3, + outputTokensPerSecond: 133.59, + errorRate: 0, + samples: 3 + }, + "openai/gpt-6.1-sol": { + measuredAt: "2026-10-20T18:12:51Z", + latencyMs: 11324, + p95LatencyMs: 12747.6, + outputTokensPerSecond: 45.11, + errorRate: 0, + samples: 3 + }, + "openai/o1": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 4324.9, + p95LatencyMs: 5838.1, + outputTokensPerSecond: 125.86, + errorRate: 0, + samples: 3 + }, + "openai/o3": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 5463.4, + p95LatencyMs: 5613.1, + outputTokensPerSecond: 93.8, + errorRate: 0, + samples: 3 + }, + "openai/o3-mini": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 2912.7, + p95LatencyMs: 3092.1, + outputTokensPerSecond: 176.49, + errorRate: 0, + samples: 3 + }, + "openai/o4-mini": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 4958.7, + p95LatencyMs: 5313, + outputTokensPerSecond: 103.81, + errorRate: 0, + samples: 3 + }, + "qwen/qwen3.7-flash": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 3385.5, + p95LatencyMs: 4042.7, + outputTokensPerSecond: 153.94, + errorRate: 0, + samples: 3 + }, + "qwen/qwen3.7-max": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 9387.1, + p95LatencyMs: 10490.2, + outputTokensPerSecond: 54.92, + errorRate: 0, + samples: 3 + }, + "qwen/qwen3.7-plus": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 9766.6, + p95LatencyMs: 9798.2, + outputTokensPerSecond: 52.42, + errorRate: 0, + samples: 3 }, - // Eco tier configs - absolute cheapest (blockrun/eco) - ecoTiers: { - SIMPLE: { - primary: "nvidia/nemotron-3.5-lightning", - // FREE — NVIDIA free tier flagship, 1M ctx - fallback: [ - // Was nvidia/nemotron-3-nano-30b until blockrun delisted it on 2026-09-08 - // (NVIDIA deprovisioned it for the account — a structured per-account - // 404). nano-omni is blockrun's own redirect target for that id, so this - // follows the same rule as the head: the router and the gateway name the - // same model. - "nvidia/nemotron-3-nano-omni-30b-a3b-reasoning", - // FREE — nano-30b's successor, 256K ctx - // The free head keeps rotting with NVIDIA's hosting (deepseek-v4-flash - // 410 2026-08-12, seed-oss-36b 410 2026-08-03, gpt-oss-120b/20b 400 - // 2026-08-21, and on 2026-08-30 FOUR of the five visible free models at - // once — step-3.7-flash, nemotron-nano-9b-v2 and nemotron-nano-12b-v2-vl - // all 410, mistral-nemotron hung). Each retirement retargets the two - // free rungs to the current free tier; the paid rungs below never move. - // The head follows blockrun's own redirect of the model it replaces, so - // the router and the gateway never name different models. - "google/gemini-2.5-flash-lite", - // $0.10/$0.40 — cheapest paid rung - "zai/glm-5.3-flash", - // $0.15/$0.50, 1M ctx, vision + tools - "openai/gpt-5.6-luna", - // $0.20/$1.20, 1M ctx - "openai/gpt-5.4-nano", - // $0.20/$1.25 - "google/gemini-3.1-flash-lite" - // $0.25/$1.50 - ] - }, - MEDIUM: { - primary: "zai/glm-5.3-flash", - // $0.15/$0.50, 1M ctx, vision + tools verified live — cheapest full-capability model - fallback: [ - "deepseek/deepseek-chat", - // $0.14/$0.28 - "google/gemini-3.1-flash-lite", - // $0.25/$1.50 - "openai/gpt-5.6-luna", - // $0.20/$1.20 - "openai/gpt-5.4-nano", - // $0.20/$1.25 - "google/gemini-2.5-flash-lite", - // $0.10/$0.40 - "google/gemini-2.5-flash" - // $0.30/$2.50 - ] - }, - COMPLEX: { - primary: "zai/glm-5.3-flash", - // $0.15/$0.50, 1M ctx - fallback: [ - "deepseek/deepseek-chat", - // $0.14/$0.28, 1M ctx - "minimax/minimax-m3", - // $0.30/$1.20, 1M ctx - "deepseek/deepseek-v4-pro", - // $0.435/$0.87 - "google/gemini-3.1-flash-lite", - // $0.25/$1.50 - "google/gemini-2.5-flash" - // $0.30/$2.50 - ] - }, - REASONING: { - primary: "deepseek/deepseek-reasoner", - // $0.14/$0.28, 1M ctx — cheapest listed reasoner - fallback: [ - "deepseek/deepseek-v4-pro", - // $0.435/$0.87 - "qwen/qwen3.7-plus", - // $0.32/$1.28 — reasoning - "minimax/minimax-m3", - // $0.30/$1.20 — reasoning + coding - "zai/glm-5.3-flash" - // $0.15/$0.50 — reasoning tokens alongside content - ] - } + "tencent/hy3": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 6062.3, + p95LatencyMs: 7070.2, + outputTokensPerSecond: 87.3, + errorRate: 0, + samples: 3 }, - // Premium tier configs - best quality (blockrun/premium) - // codex=complex coding, flash=simple coding, sonnet=reasoning/instructions, fable/opus=architecture/PM/audits - premiumTiers: { - SIMPLE: { - // Was moonshot/kimi-k2.7 (hidden 2026-08). - primary: "google/gemini-3.5-flash", - // $1.50/$9, 1M ctx, vision + tools — calibrated - fallback: [ - "google/gemini-3.6-flash", - // $1.50/$7.50 — newest Flash - "anthropic/claude-haiku-4.5", - // $1/$5 - "zai/glm-5.3", - // $1.40/$4.40, 1M ctx - "google/gemini-2.5-flash", - // $0.30/$2.50 - "google/gemini-3.5-flash-lite", - // $0.30/$2.50 - "deepseek/deepseek-chat" - // $0.14/$0.28 - ] - }, - MEDIUM: { - primary: "openai/gpt-5.3-codex", - // $1.75/$14 - 400K context, 128K output — code_edit/debug lead (portfolio.ts) - fallback: [ - "anthropic/claude-sonnet-5", - // $3/$15 — code_agent band 0.98 - "moonshot/kimi-k3", - // $3/$15, 1M ctx — Moonshot flagship - "zai/glm-5.3", - // $1.40/$4.40 — long-horizon coding - "google/gemini-3.6-flash", - // $1.50/$7.50 - "google/gemini-3.5-flash", - // $1.50/$9 - "google/gemini-2.5-pro", - // $1.25/$10 - "xai/grok-4.5", - // $2.50/$9 - "anthropic/claude-sonnet-4.6", - // $3/$15 - "openai/gpt-5.6-terra" - // $2/$12 - ] - }, - COMPLEX: { - // fable-5 was promoted here 2026-06-11, force-reverted 2026-06-13 when Anthropic - // withdrew the offer, and restored 2026-07-14 now that BlockRun has relisted it. - primary: "anthropic/claude-fable-5", - // Best quality for complex tasks — Mythos-class flagship above Opus ($10/$50, 1M ctx, always-on thinking) - // Fallback chain de-Gemini'd 2026-04-22: when Anthropic 503s, Gemini is - // also prone to "high demand" 503s (correlated failure — everyone falls - // back to Google at the same time). Prefer in-family → xAI → Moonshot → - // OpenAI flagship → Z.AI → DeepSeek → NVIDIA free instead. - fallback: [ - "anthropic/claude-opus-5", - // in-family hot swap first (half the price, 1M ctx + adaptive thinking) - "anthropic/claude-opus-4.8", - // in-family hot swap (identical cost to 5) - "anthropic/claude-opus-4.7", - // in-family hot swap (identical cost to 4.8) - "anthropic/claude-sonnet-5", - // Sonnet-tier drop-down, near-Opus quality - "anthropic/claude-sonnet-4.6", - "xai/grok-4.5", - // xAI flagship — 503-resistant, direct-xAI SKU - "moonshot/kimi-k3", - // Moonshot flagship, independent infra - "openai/gpt-5.6-terra", - // GPT-5.6 balanced tier — stable (Sol excluded: #202) - "openai/gpt-5.5", - // Prior OpenAI flagship — 1M+ ctx, native agent + computer use - "openai/gpt-5.4", - // Previous flagship (slow but stable, benchmarked at 6,213ms) - "openai/gpt-5.3-codex", - "zai/glm-5.3", - // Z.AI flagship, 1M ctx - "deepseek/deepseek-v4-pro", - // strongest open-weight reasoner - "deepseek/deepseek-chat", - // Cheap, reliable - "nvidia/nemotron-3.5-lightning" - // NVIDIA free ultimate backstop - ] - }, - REASONING: { - // Sonnet 5 promoted over Sonnet 4.6 (same price; reasoning band 0.98 for both, - // plus Sonnet 5's tau2/BrowseComp trajectory evidence). - primary: "anthropic/claude-sonnet-5", - // $3/$15, 1M ctx, adaptive thinking - fallback: [ - "anthropic/claude-sonnet-4.6", - // in-family hot swap — same cost - "anthropic/claude-opus-5", - // Newest flagship Opus w/ adaptive thinking - "anthropic/claude-opus-4.8", - // Prior flagship Opus — identical cost to 5 - "anthropic/claude-opus-4.7", - // Flagship Opus w/ adaptive thinking - "xai/grok-4.5", - // reasoning band 0.94 - "deepseek/deepseek-v4-pro", - // reasoning band 0.95 - "xai/grok-4.3", - // $1.50/$4 — xAI reasoning model - "openai/o4-mini", - // $1.10/$4.40 - "openai/o3" - // $2/$8 - ] - } + "xai/grok-4.3": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 9467.7, + p95LatencyMs: 10087.9, + outputTokensPerSecond: 48.36, + errorRate: 0, + samples: 3 + }, + "xai/grok-4.5": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 13564.8, + p95LatencyMs: 17351.9, + outputTokensPerSecond: 60.71, + errorRate: 0, + samples: 3 + }, + "xai/grok-build-0.1": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 16394.8, + p95LatencyMs: 18035.4, + outputTokensPerSecond: 96.86, + errorRate: 0, + samples: 3 + }, + "xiaomi/mimo-v2.5-pro": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 12070.7, + p95LatencyMs: 12386.8, + outputTokensPerSecond: 42.44, + errorRate: 0, + samples: 3 + }, + "zai/glm-5": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 6839.7, + p95LatencyMs: 7261.4, + outputTokensPerSecond: 75.16, + errorRate: 0, + samples: 3 + }, + "zai/glm-5-turbo": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 55348.5, + p95LatencyMs: 114086.6, + outputTokensPerSecond: 14.64, + errorRate: 0, + samples: 3 + }, + "zai/glm-5.1": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 15658.4, + p95LatencyMs: 17307.1, + outputTokensPerSecond: 32.9, + errorRate: 0, + samples: 3 + }, + "zai/glm-5.2": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 10308.5, + p95LatencyMs: 15127.6, + outputTokensPerSecond: 54.87, + errorRate: 0, + samples: 3 }, - // Agentic tier configs - models that excel at multi-step autonomous tasks - agenticTiers: { - SIMPLE: { - primary: "openai/gpt-4o-mini", - // $0.15/$0.60 - best tool compliance at lowest cost - fallback: [ - "openai/gpt-5.6-luna", - // $0.20/$1.20 — lightweight agentic tier of GPT-5.6 - "zai/glm-5.3-flash", - // $0.15/$0.50 — tool calls verified live 2026-08-27 - "anthropic/claude-haiku-4.5", - // $1/$5 - "google/gemini-2.5-flash" - // $0.30/$2.50 - ] - }, - MEDIUM: { - // Was moonshot/kimi-k2.7 (hidden 2026-08). GPT-5 Mini carries the - // Terminal-Bench and tau2 trajectory evidence in portfolio.ts. - primary: "openai/gpt-5-mini", - // $0.25/$2 — 4/7 Terminal-Bench, 5/6 tau2 airline - fallback: [ - "google/gemini-3.5-flash", - // $1.50/$9 — tool_agent band 0.88 - "zai/glm-5.3-flash", - // $0.15/$0.50 — tools verified - "openai/gpt-5.6-terra", - // $2/$12 - "openai/gpt-4o-mini", - // $0.15/$0.60 — reliable tool calling - "anthropic/claude-haiku-4.5", - // $1/$5 - "deepseek/deepseek-chat", - // $0.14/$0.28 - "moonshot/kimi-k3" - // $3/$15 — tool_agent band 0.85 - ] - }, - COMPLEX: { - // Sonnet 5 promoted over Sonnet 4.6: tau2 airline + retail reward 1.0, - // Terminal-Bench safety band lead (portfolio.ts). - primary: "anthropic/claude-sonnet-5", - // $3/$15 — best agentic quality per trajectory evidence - // Fallback chain de-Gemini'd 2026-04-22: Gemini's "high demand" 503s - // correlate with Anthropic outages (everyone falls back together). - // Prefer 503-resistant providers first. - fallback: [ - "anthropic/claude-sonnet-4.6", - // in-family hot swap — same cost - "anthropic/claude-opus-5", - // Newest flagship Opus — in-family hot swap - "anthropic/claude-opus-4.8", - // Prior flagship Opus — identical cost to 5 - "anthropic/claude-opus-4.7", - // Flagship Opus — in-family hot swap - "xai/grok-4.5", - // xAI flagship — strong tool use, independent infra - "moonshot/kimi-k3", - // Moonshot flagship — independent infra - "openai/gpt-5.6-terra", - // GPT-5.6 balanced tier — stable (Sol excluded: #202) - "openai/gpt-5.5", - // Prior flagship — native agent + computer use (exactly the agentic-tier use case) - "openai/gpt-5.4", - // Previous flagship — reliable - "openai/gpt-5.3-codex", - // code_agent lead - "zai/glm-5.3", - // long-horizon coding - "deepseek/deepseek-v4-pro", - // retail high-risk 3/3 - "deepseek/deepseek-chat", - // cheap, reliable - "nvidia/nemotron-3.5-lightning" - // NVIDIA free ultimate backstop - ] - }, - REASONING: { - primary: "anthropic/claude-sonnet-5", - // $3/$15 — strong tool use + adaptive thinking - fallback: [ - "anthropic/claude-sonnet-4.6", - // in-family hot swap — same cost - "anthropic/claude-opus-5", - // Newest flagship Opus w/ adaptive thinking - "anthropic/claude-opus-4.8", - // Prior flagship Opus — identical cost to 5 - "anthropic/claude-opus-4.7", - // Flagship Opus w/ adaptive thinking - "xai/grok-4.5", - // reasoning band 0.94 - "deepseek/deepseek-v4-pro", - // reasoning band 0.95 - "deepseek/deepseek-reasoner" - // $0.14/$0.28 - ] + "zai/glm-5.3": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 7272.4, + p95LatencyMs: 7998.1, + outputTokensPerSecond: 71.09, + errorRate: 0, + samples: 3 + }, + "zai/glm-5.3-flash": { + measuredAt: "2026-08-29T16:51:33Z", + latencyMs: 10545.3, + p95LatencyMs: 11672.4, + outputTokensPerSecond: 49.01, + errorRate: 0, + samples: 3 + } +}; + +// src/model-profiles.ts +var LIVE_MODEL_PROFILES = Object.freeze( + model_profiles_generated_default +); +var HISTORICAL_MODEL_PROFILES = Object.freeze({ + "anthropic/claude-haiku-4.5": { + measuredAt: "2026-03-16T13:50:48Z", + latencyMs: 2305, + outputTokensPerSecond: 140.6 + }, + "anthropic/claude-sonnet-4.6": { + measuredAt: "2026-03-16T13:50:48Z", + latencyMs: 2110, + outputTokensPerSecond: 121.3 + }, + "deepseek/deepseek-chat": { + measuredAt: "2026-03-16T13:50:48Z", + latencyMs: 1431, + outputTokensPerSecond: 179.2, + intelligenceIndex: 32 + }, + "google/gemini-2.5-flash": { + measuredAt: "2026-03-16T13:50:48Z", + latencyMs: 1238, + outputTokensPerSecond: 207.6, + intelligenceIndex: 20 + }, + "google/gemini-2.5-flash-lite": { + measuredAt: "2026-03-16T13:50:48Z", + latencyMs: 1353, + outputTokensPerSecond: 192.5, + intelligenceIndex: 20 + }, + "google/gemini-2.5-pro": { + measuredAt: "2026-03-16T13:50:48Z", + latencyMs: 1294, + outputTokensPerSecond: 197.8 + }, + "google/gemini-3.1-pro": { + measuredAt: "2026-03-16T13:50:48Z", + latencyMs: 1609, + outputTokensPerSecond: 167.2 + }, + "openai/gpt-4o-mini": { + measuredAt: "2026-03-16T13:50:48Z", + latencyMs: 2764, + outputTokensPerSecond: 92.8 + }, + "openai/gpt-5.3-codex": { + measuredAt: "2026-03-16T13:50:48Z", + latencyMs: 7935, + outputTokensPerSecond: 32.3 + } +}); + +// src/tool-intent.ts +function inferToolRequirement(prompt, _systemPrompt, toolChoice) { + if (toolChoice === "none") return false; + if (toolChoice === "required") return true; + if (typeof toolChoice === "object" && toolChoice !== null && toolChoice.type === "function") { + return true; + } + const text = prompt; + const explicitTool = /\b(?:use|call|invoke)\s+(?:the\s+)?[\w.-]+\s+(?:tool|function|api)\b|\btool[_ -]?call\b|使用.{0,20}(?:工具|函数|接口)|调用.{0,20}(?:工具|函数|接口)/i; + const codeEnvironment = /\b(?:run|execute)\s+(?:the\s+)?(?:tests?|command|script|build|linter)|\b(?:edit|modify|patch|create|write|save|delete|rename|move|inspect|read)\b.{0,60}\b(?:file|repository|repo|codebase|directory|folder)\b|\b(?:terminal|shell|bash|zsh|pytest|npm test|pnpm test|git\s+(?:status|diff|commit)|docker)\b|(?:运行|执行).{0,20}(?:测试|命令|脚本|构建)|(?:修改|编辑|修复|创建|读取|检查|保存).{0,30}(?:文件|仓库|代码库|目录)/i; + const webAction = /\b(?:browse|search|look up|fetch|open)\b.{0,80}\b(?:web|website|url|online|documentation|docs|news|weather|price)\b|(?:浏览|搜索|查询|打开).{0,30}(?:网页|网站|链接|文档|新闻|天气|价格)/i; + const statefulAction = /\b(?:refund|cancel|book|reserve|purchase|buy|return|exchange|transfer|update|change)\b.{0,80}\b(?:order|booking|reservation|account|address|payment|subscription|ticket|flight|item)\b|(?:退款|取消|预订|购买|退货|换货|转账|更新|修改).{0,30}(?:订单|预订|账户|地址|付款|订阅|票|航班|商品)/i; + return explicitTool.test(text) || codeEnvironment.test(text) || webAction.test(text) || statefulAction.test(text); +} + +// src/portfolio.ts +var DEFAULT_PORTFOLIO_WEIGHTS = DEFAULT_ROUTING_CONFIG.portfolio; +function likelyNeedsParallelToolCalls(prompt, needsTools, toolCount, toolNames) { + if (!needsTools || toolCount === void 0 || toolCount < 1) return false; + const text = prompt.trim(); + const explicitRepeat = /\b(?:in parallel|simultaneously|concurrently|for each|each of|every one|both|(?:two|three|multiple|several)\s+(?:cities|locations|items|tasks|orders|users|files))\b|并行|同时|分别|每个|各自|(?:两个|三个|多个)(?:城市|地点|项目|任务|订单|用户|文件)|cada uno|para cada|simult[aá]neamente/i.test( + text + ); + if (explicitRepeat) return true; + const sentenceClauses = text.split(/[.!?。!?]+/).map((part) => part.trim()).filter((part) => part.length >= 8); + if (/\b(?:also|additionally|furthermore)\b|另外|此外|그리고/i.test(text) && sentenceClauses.length >= 2 || /\band\s+(?:also|for the)\b/i.test(text)) + return true; + const pairedQuantity = /\b\d+(?:\.\d+)?\s+(?:and|or)\s+\d+(?:\.\d+)?\s*(?:gb|mb|tb|kg|g|ml|oz|cups?|cores?|cpus?)\b/i.test( + text + ); + if (pairedQuantity) return true; + const operationTokens = /* @__PURE__ */ new Set([ + "add", + "delete", + "remove", + "cancel", + "return", + "exchange", + "modify", + "book", + "transfer", + "send", + "upload", + "download", + "create", + "close" + ]); + const lowered = text.toLowerCase(); + const matchedOperationTokens = new Set( + (toolNames ?? []).flatMap((name) => name.toLowerCase().split(/[^a-z0-9\u3400-\u9fff]+/)).filter( + (token) => operationTokens.has(token) && new RegExp(`\\b${token}(?:s|es|d|ed|ing)?\\b`).test(lowered) + ) + ); + if (matchedOperationTokens.size >= 2) return true; + const nonEmptyLines = text.split(/\r?\n/).map((line) => line.trim()).filter(Boolean); + const quantityMentions = text.match( + /\b(?:\d+(?:\.\d+)?|one|two|three|four|five|six|seven|eight|nine|ten)\s*(?:oz|ounce|ounces|g|gram|grams|kg|ml|cups?|pieces?|tablespoons?)\b/gi + ) ?? []; + if (nonEmptyLines.length >= 2 && quantityMentions.length >= 2) return true; + const repeatedLookup = /\b(?:weather|climate|clima|tiempo|temperature|snow|news|report)\b|天气|气象|温度|降雪|新闻|报告/i.test( + text + ); + const multiLocationConnector = /\b(?:and also|both)\b|\s(?:y|e)\s|还有|以及|和|、/i.test(text); + const commaSeparatedLocations = (text.match(/[,,]/g) ?? []).length >= 2; + if (repeatedLookup && (multiLocationConnector || commaSeparatedLocations)) return true; + const distinctOrderParts = /\b(?:food|meal)\b[\s\S]*\bdrink\b|\bdrink\b[\s\S]*\b(?:food|meal)\b/i.test(text); + const koreanParallelClauses = (text.match(/,/g) ?? []).length >= 3 && /하고|그리고/.test(text); + return distinctOrderParts || koreanParallelClauses; +} +function classifyTask(prompt, systemPrompt, options) { + const fullText = `${systemPrompt ?? ""} ${prompt}`; + const estimatedInputTokens = estimateTokens(fullText); + const limit = scanLimit(options.config.classifier.promptTruncationChars); + const scannedPrompt = sampleForScan(prompt, limit); + const scannedSystemPrompt = sampleForScan(systemPrompt ?? "", limit); + const scannedFullText = `${scannedSystemPrompt} ${scannedPrompt}`; + const text = scannedPrompt.toLowerCase(); + const explicitCodeSignal = /```|\b(?:typescript|javascript|python|rust|java|sql|stack trace|traceback|exception)\b|\.(?:ts|tsx|js|py|go|rs)\b/i.test( + scannedPrompt + ); + const codeConstructSignal = /\b(?:implement|refactor|debug|write|edit|modify|create|define|review|fix)\b[\s\S]{0,48}\b(?:api|function|class|method)\b|\b(?:api|function|class|method)\b[\s\S]{0,48}\b(?:code|implementation|typescript|javascript|python|rust|java)\b/i.test( + scannedPrompt + ); + const nativeCodeSignal = /\b(?:programmed|written|implemented?|code)\s+(?:in|using)\s+(?:c\+\+|c|rust|go)\b/i.test( + scannedPrompt + ); + const errorClassSignal = /\b[A-Z][A-Za-z]*(?:Error|Exception)\b/.test(scannedPrompt); + const hasCode = explicitCodeSignal || codeConstructSignal || nativeCodeSignal || errorClassSignal; + const codingAction = /\b(?:write|implement|refactor|debug|fix|patch|compile|build|run|test|script|program|code|function|class|module|repo(?:sitory)?)\b|编写|实现|重构|调试|修复|编译|脚本|代码/i.test( + scannedPrompt + ); + const codeArtifact = /```|\b(?:stack trace|traceback)\b|\.(?:ts|tsx|js|py|go|rs)\b/i.test(scannedPrompt) || codeConstructSignal || nativeCodeSignal || errorClassSignal; + const toolsAvailable = options.hasTools ?? false; + const needsTools = options.requiresTools ?? (toolsAvailable && inferToolRequirement(scannedPrompt, scannedSystemPrompt)); + const likelyParallelToolCalls = likelyNeedsParallelToolCalls( + scannedPrompt, + needsTools, + options.toolCount, + options.toolNames + ); + const normalizedToolNames = (options.toolNames ?? []).map((name) => name.toLowerCase()); + const airlineToolSignal = normalizedToolNames.some( + (name) => /(?:flight|reservation|airport|baggage|passenger)/.test(name) + ); + const retailToolSignal = normalizedToolNames.some( + (name) => /(?:order|product|item|return|exchange|address)/.test(name) + ); + const webResearchToolSignal = normalizedToolNames.some( + (name) => /^(?:web_?search|web_?fetch)$/.test(name) + ); + const agentDomain = airlineToolSignal && !retailToolSignal ? "airline" : retailToolSignal && !airlineToolSignal ? "retail" : webResearchToolSignal ? "web_research" : "other"; + const clueConnectors = scannedFullText.match( + /\b(?:after|before|while|where|whose|which|in \d{4}|as of|over \d+|another|also|furthermore)\b|(?:之后|之前|其中|截至|超过|另一个|此外)/gi + ) ?? []; + const entityResolutionSignal = /\b(?:identify|who (?:is|was)|what (?:is|was) the name|which (?:person|player|company|country|city)|find the (?:person|player|name|entity))\b|(?:找出|识别|是谁|哪位|名称是什么)/i.test( + scannedFullText + ); + const exactAnswerSignal = /\b(?:exact answer|single best-supported answer|following clues|multiple public sources)\b|(?:精确答案|根据.*线索|多个公开来源)/i.test( + scannedFullText + ); + const deepWebResearch = agentDomain === "web_research" && (exactAnswerSignal || entityResolutionSignal && (clueConnectors.length >= 3 || prompt.length >= 320)); + const globalOptimizationSignal = /\b(?:cheapest|lowest[- ]price|least expensive|most expensive|highest(?:[- ]priced)?|largest|smallest|maximum|minimum|best available|closest|not (?:cost|exceed))\b|最便宜|最低价|最贵|最高价|最大|最小/i.test( + scannedPrompt + ); + const globalScopeSignal = /\b(?:everything|all (?:(?:my|your|their|the) )?(?:future |upcoming )?(?:items|orders|passengers|flights|reservations|bookings)|every (?:item|order|passenger|flight|reservation|booking))\b|全部|所有|每个/i.test( + scannedPrompt + ); + const globalChoiceSignal = globalOptimizationSignal || globalScopeSignal; + const crossRecordSignal = /\b(?:another|other|different|previous)\s+(?:order|reservation|booking|account|address)\b|另一(?:个)?(?:订单|预订|账户|地址)|其他(?:订单|预订|账户|地址)/i.test( + scannedPrompt + ); + const reservationIds = scannedPrompt.match(/\b(?=[A-Z0-9]*\d)(?=[A-Z0-9]*[A-Z])[A-Z0-9]{6}\b/g) ?? []; + const crossReservationBatchSignal = agentDomain === "airline" && (/\b(?:two|three|multiple|several)(?:\s+of\s+(?:my|our|the))?\s+(?:upcoming\s+)?(?:reservations?|bookings?)\b|\b(?:a\s+)?(?:second|third)\s+(?:reservation|booking)\b/i.test( + scannedPrompt + ) || new Set(reservationIds).size >= 2); + const conditionalGlobalWorkflowSignal = agentDomain === "airline" && globalScopeSignal && /\b(?:if|that (?:contain|have)|longer than|shorter than|under|over|at (?:most|least)|wherever possible)\b|如果|超过|少于|不超过|尽可能/i.test( + scannedPrompt + ) && /\b(?:cancel|change|upgrade|move|book)\b[\s\S]*\b(?:cancel|change|upgrade|move|book)\b|取消[\s\S]*(?:升级|更改)|升级[\s\S]*(?:取消|更改)/i.test( + scannedPrompt + ); + const policyExceptionSignal = agentDomain === "retail" && /\b(?:return|refund|send back|get (?:my |the )?money back)\b|退货|退款|退回/i.test( + scannedPrompt + ) && /\b(?:amex|american express|visa|mastercard|credit card|debit card|different card|another card|other card)\b|信用卡|借记卡|其他卡|另一张卡/i.test( + scannedPrompt + ); + const singleSelectedPolicyException = policyExceptionSignal && /\b(?:return|refund|send back)\b[^.!?。!?]{0,96}\b(?:the )?(?:pricier|cheaper|more expensive|less expensive|costlier|one)\b/i.test( + scannedPrompt + ); + const negotiatedWorkflowSignal = agentDomain === "retail" && /\b(?:return|exchange)\b|退货|退回|换货|交换/i.test(scannedPrompt); + const numberedSteps = (scannedPrompt.match(/(?:^|\s)\d+(?:\.\d+)*[.)]\s+/g) ?? []).length; + const complexMultiToolPlan = likelyParallelToolCalls && ((options.toolCount ?? 0) >= 6 || numberedSteps >= 3 || prompt.length > 1200); + let agentRisk = needsTools && singleSelectedPolicyException ? "policy_exception_simple" : needsTools && policyExceptionSignal ? "policy_exception" : ( + // Airline prompts that require a global optimum (for example the + // cheapest itinerary across several candidates) are materially harder + // than applying one change to every passenger in a known reservation. + // Full-session evidence supports Sonnet for the former, while upgrading + // the latter merely because it says "all passengers" caused a large cost + // increase without a quality gain. + needsTools && agentDomain === "airline" && (globalOptimizationSignal || conditionalGlobalWorkflowSignal) ? "complex_high" : needsTools && (likelyParallelToolCalls || globalChoiceSignal || crossRecordSignal || crossReservationBatchSignal || negotiatedWorkflowSignal) ? "high" : "standard" + ); + const needsVision = options.hasVision ?? false; + const needsStructuredOutput = options.requiresStructuredOutput ?? false; + const latencySensitive = /\b(?:urgent|asap|fast|quick|low latency|real[- ]time)\b|尽快|马上|快速|低延迟/i.test( + scannedPrompt + ); + const highStakes = /\b(?:production|security|payment|legal|medical|financial|audit)\b|生产|安全|支付|法律|医疗|财务|审计/i.test( + scannedPrompt + ); + const terminalToolSignal = normalizedToolNames.some( + (name) => /^(?:terminalexec|terminalinspect|terminalsendkeys)$/.test(name) + ); + const simpleTerminalArtifact = /\b(?:create|write|convert|generate|build|implement|run|fix|repair|debug|make)\b[\s\S]{0,120}\b(?:file|script|csv|parquet|json|txt|server|endpoint)\b/i.test( + scannedPrompt + ); + const terminalComplexRepair = terminalToolSignal && /\b(?:multiple|several)\s+(?:scripts?|files?|components?)\b|\b(?:pipeline|dependencies)\b[\s\S]{0,100}\b(?:fail|issue|fix|repair|run|execute)\b|\b(?:identify|find|fix|repair)\s+(?:and\s+)?(?:fix\s+)?all\s+(?:the\s+)?issues\b/i.test( + scannedPrompt + ); + const mentionedTerminalRuntimes = new Set( + (scannedPrompt.match(/\b(?:gcc|clang|rustc|javac|go\s+build|node|python)\b/gi) ?? []).map( + (name) => name.toLowerCase().replace(/\s+/g, " ") + ) + ); + const terminalCrossRuntimeArtifact = terminalToolSignal && (/\bpolyglot\b/i.test(scannedPrompt) || /\b(?:both|each)\b[\s\S]{0,120}\b(?:compilers?|runtimes?|toolchains?)\b/i.test( + scannedPrompt + ) || mentionedTerminalRuntimes.size >= 2 && /\b(?:compile|build|run|execute)\b/i.test(scannedPrompt)); + const terminalFrameworkToNativeArtifact = terminalToolSignal && /\b(?:pytorch|tensorflow|jax|onnx|state[_ -]?dict|checkpoint|safetensors?)\b|\.(?:pth|pt|onnx)\b/i.test( + scannedPrompt + ) && /\b(?:pure|native|programmed|written|implemented?)\s+(?:in|using)\s+(?:c\+\+|c|rust|go)\b|\b(?:c\+\+|c|rust|go)\s+(?:program|binary|executable|cli|tool|implementation)\b/i.test( + scannedPrompt + ) && /\b(?:inference|model|weights?|tensor|export|convert|load)\b/i.test(scannedPrompt); + if (needsTools && (terminalComplexRepair || terminalCrossRuntimeArtifact || terminalFrameworkToNativeArtifact) && (agentRisk === "standard" || agentRisk === "high")) + agentRisk = "complex_high"; + const complexTerminalOperation = /\b(?:git|ssh|nginx|https|certificate|authentication|credential|deploy|production|encrypt|gpg|shred|securely delete|decommission|benchmark|evaluate|embedding|chess|image|search the web|schema|statistical|statistics|aggregate|join|multiple inputs?)\b/i.test( + scannedPrompt + ); + const terminalCredentialSignal = /\b(?:ssh|nginx|certificate|authentication|credentials?|passwords?|api keys?|deploy|production|encrypt|gpg|shred|securely delete|decommission)\b/i.test( + scannedPrompt + ) || /\b(?:access|auth|authentication|bearer|secret|api)\s+tokens?\b|\btokens?\s+(?:secret|credential|authentication)\b/i.test( + scannedPrompt + ); + const terminalSafetySensitive = terminalToolSignal && (highStakes || terminalCredentialSignal); + const implicitTerminalCode = needsTools && terminalToolSignal && agentRisk === "standard" && !highStakes && !complexTerminalOperation && numberedSteps < 3 && prompt.length <= 1e3 && simpleTerminalArtifact; + const language = /[\u3400-\u9fff]/.test(scannedPrompt) && !/[\u3040-\u30ff]/.test(scannedPrompt) ? "zh" : "other"; + const multipleChoiceSignals = (scannedPrompt.match(/(?:^|\n)\s*[A-D][.)]\s+/gim) ?? []).length; + const numericSignals = (scannedPrompt.match(/-?\d+(?:[.,]\d+)?/g) ?? []).length; + const compactMathProblem = !hasCode && prompt.length < 2500 && numericSignals >= 2 && (/[+×÷=%$€£¥]|\b(?:total|each|per|times|half|twice|percent|how many|how much|calculate)\b/i.test( + scannedPrompt + ) || /[??]\s*$/.test(scannedPrompt.trim()) || numericSignals >= 3); + let taskType = "chat"; + if (needsVision) taskType = "vision"; + else if (estimatedInputTokens > 8e4) taskType = "long_context"; + else if (needsTools && (codeArtifact || hasCode && codingAction || implicitTerminalCode)) + taskType = "code_agent"; + else if (needsTools && likelyParallelToolCalls && !complexMultiToolPlan) + taskType = "tool_agent_parallel"; + else if (needsTools) taskType = "tool_agent"; + else if (multipleChoiceSignals >= 3) taskType = "reasoning_mcq"; + else if (compactMathProblem) taskType = "reasoning_math"; + else if (errorClassSignal || /\b(?:bug|debug|error|failure|failing|regression|crash)\b|修复|报错|错误|调试/i.test(text)) + taskType = "debug"; + else if (hasCode || /\b(?:refactor|implement|patch|edit|rewrite)\b|重构|实现|修改/i.test(text)) + taskType = "code_edit"; + else if (needsStructuredOutput || /\b(?:extract|json|schema|csv)\b|字段|提取/i.test(text)) + taskType = "extraction"; + else if (/\b(?:prove|derive|theorem|formal|mathematical|reasoning)\b|证明|推导|定理|数学/i.test(text)) + taskType = "reasoning"; + return { + taskType, + estimatedInputTokens, + hasCode, + needsTools, + toolsAvailable, + needsVision, + needsStructuredOutput, + latencySensitive, + highStakes, + language, + likelyParallelToolCalls, + complexMultiToolPlan, + agentDomain, + deepWebResearch, + agentRisk, + terminalToolSignal, + terminalSafetySensitive, + implicitTerminalCode, + codeArtifact + }; +} +var NEUTRAL_AFFINITY = 0.68; +var TERMINAL_COMPLEX_HIGH = { + "claude-sonnet-5": 1, + "gpt-5.3-codex": 0.87, + "gpt-5-mini": 0.78, + "gemini-3.5-flash": 0.76 +}; +var WEB_RESEARCH_DEEP = { + "claude-sonnet-5": 1, + "gpt-5-mini": 0.88, + "gemini-3.5-flash": 0.84, + "claude-opus-5": 0.8, + "claude-opus-4.8": 0.78 +}; +var WEB_RESEARCH = { + "claude-sonnet-5": 1, + "gpt-5-mini": 0.88, + "gemini-3.5-flash": 0.86, + "claude-opus-5": 0.84, + "claude-opus-4.8": 0.82 +}; +var RETAIL_POLICY_EXCEPTION = { + "gpt-4.1": 1, + "claude-sonnet-5": 0.9, + "deepseek-v4-pro": 0.82, + "gpt-5-mini": 0.8, + "gpt-4o-mini": 0.76 +}; +var RETAIL_POLICY_EXCEPTION_SIMPLE = { + "gpt-5-mini": 1, + "gpt-4.1": 0.86, + "deepseek-v4-pro": 0.82, + "gpt-4o-mini": 0.8 +}; +var AFFINITY = { + // Seven valid full agent + official Terminal-Bench trajectories (2026-07-28) + // gave GPT-5 Mini 4/7 resolved tasks versus 1/7 for the prior dynamic + // code-agent choice. Its token-normalized total cost was higher in this small + // calibration, so Codex and Sonnet keep quality priors above it; admitting + // Mini to the scoring band lets the normal quality/cost profile choose it + // without erasing stronger fallbacks. DeepSeek V4 Pro is kept below the + // primary band after two consecutive mid-trajectory provider timeouts + // contaminated its calibration runs. + codeAgent: { + "gpt-5.3-codex": 1, + "claude-sonnet-5": 0.98, + "gpt-5-mini": 0.96, + "gemini-3.5-flash": 0.92, + "kimi-k3": 0.9, + "deepseek-v4-pro": 0.88, + "glm-5.2": 0.88 + }, + // Seven official Terminal-Bench calibration trajectories favoured GPT-5 Mini + // over the prior dynamic choice. Codex/Sonnet are close fallbacks; actual + // request cost breaks the tie. + terminalTool: { + "gpt-5-mini": 1, + "gpt-5.3-codex": 0.98, + "claude-sonnet-5": 0.9, + "gemini-3.5-flash": 0.89 + }, + // Two complete agent observations on the public Terminal-Bench + // new-encrypt-command task ended in Codex repeating the same TerminalExec + // input until the loop guard fired. Codex stays an availability fallback, + // below the safety-band affinity floor, until its Responses function-output + // path is verified on both gateways. + terminalToolSafety: { + "claude-sonnet-5": 1, + "claude-opus-4.8": 0.9, + "gpt-5.3-codex": 0.84 + }, + // Full-session calibration: GPT-5 Mini completed two local/single retail + // workflows at a fraction of Sonnet's token cost. It stays ineligible for + // promotion when the prompt asks for multiple actions, cross-record + // discovery or a global optimum; those trajectories exposed unstable write + // arguments. DeepSeek V4 Pro completed all three high-risk retail calibration + // trajectories (global-choice, cross-record, multi-write); Sonnet one. + retailStandard: { + "gpt-5-mini": 1, + "claude-sonnet-5": 0.88, + "gemini-3.5-flash": 0.82, + "gpt-5.3-codex": 0.81, + "kimi-k3": 0.78, + "deepseek-v4-pro": 0.76 + }, + retailHigh: { + "deepseek-v4-pro": 1, + "claude-sonnet-5": 0.88, + "gemini-3.5-flash": 0.82, + "gpt-5.3-codex": 0.81, + "kimi-k3": 0.78, + "gpt-5-mini": 0.76 + }, + // Standard airline workflows stay on GPT-5 Mini: six full-session + // development trajectories gave it the same 5/6 success as Sonnet at roughly + // one order of magnitude lower normalized token cost. A held-out high-risk + // cabin/date negotiation then produced a persistent empty assistant turn on + // Mini even after a semantic retry, while Sonnet 5 completed the identical + // official tau2 trajectory with reward 1.0. Only global optimization / + // conditional-global work is promoted. A known batch of reservations is + // operationally high-risk but still a structured tool workflow: current Tau + // evidence has Mini and Sonnet at equal task reward there, while Sonnet costs + // roughly two orders of magnitude more on the long-tail case. + airlineComplex: { + "claude-sonnet-5": 1, + "gpt-5-mini": 0.78, + "gemini-3.5-flash": 0.76, + "deepseek-v4-pro": 0.74 + }, + airlineStandard: { + "gpt-5-mini": 1, + "claude-sonnet-5": 0.9, + "gemini-3.5-flash": 0.8, + "deepseek-v4-pro": 0.76 + }, + // Full-trajectory tau2 calibration (2026-07-28, official gpt-4.1 simulator): + // Sonnet 5 completed both an airline policy task and a retail multi-write + // task with reward 1.0. Gemini 3.5 Flash emitted function calls as plain text + // after the first structured calls and looped to the 100-step ceiling on the + // airline task. + toolAgent: { + "claude-sonnet-5": 1, + "gemini-3.5-flash": 0.88, + "gpt-5.3-codex": 0.87, + "kimi-k3": 0.85, + "gpt-5-mini": 0.84, + "deepseek-v4-pro": 0.82 + }, + // Multi-file Terminal work is not equivalent to a one-turn parallel + // function-call benchmark. Sonnet is the strongest trajectory-tested + // cost-controlled default; Opus remains a close safety fallback. + parallelTerminalSafety: { + "claude-sonnet-5": 1, + "claude-opus-4.8": 0.9, + "gpt-5.3-codex": 0.86 + }, + parallelTerminal: { + "gpt-5-mini": 1, + "gpt-5.3-codex": 0.98, + "claude-sonnet-5": 0.92, + "gemini-3.5-flash": 0.88 + }, + parallelRetail: { + "deepseek-v4-pro": 1, + "claude-sonnet-5": 0.88, + "claude-opus-4.8": 0.84, + "gpt-5-mini": 0.78, + "gemini-3.5-flash": 0.76 + }, + parallelAirlineComplex: { + "claude-sonnet-5": 1, + "gpt-5-mini": 0.78, + "claude-opus-4.8": 0.76, + "gemini-3.5-flash": 0.74 + }, + parallelAirline: { + "gpt-5-mini": 1, + "claude-sonnet-5": 0.9, + "gemini-3.5-flash": 0.8 + }, + // RouterBench calibration, 2026-07-26: Opus 4.8 produced complete multi-call + // payloads on 2/3 multilingual BFCL parallel cases. Gemini 3.5 Flash, Sonnet + // 5, DeepSeek V4 Pro and Grok 4.5 were 0/3. This narrow prior only applies + // after the conservative prompt feature in likelyNeedsParallelToolCalls. + parallel: { + "claude-opus-4.8": 1, + "claude-sonnet-5": 0.84, + "grok-4.5": 0.82, + "gemini-3.5-flash": 0.8, + "deepseek-v4-pro": 0.78 + }, + codeEdit: { + "gpt-5.3-codex": 1, + "claude-sonnet-4.6": 0.94, + "glm-5.2": 0.9, + "deepseek-v4-pro": 0.86 + }, + reasoning: { + "claude-sonnet-5": 0.98, + "claude-sonnet-4.6": 0.98, + "deepseek-v4-pro": 0.95, + "grok-4.5": 0.94, + "gemini-3.1-pro": 0.92, + "gemini-3.5-flash": 0.92 + }, + // RouterBench calibration (2026-07-28, six stratified GPQA Diamond tasks, + // identical agent adapter and 512-token budget): Gemini 3 Flash Preview + // scored 5/6, Gemini 3.5 Flash 4/6, and Gemini 3.1 Pro 3/6 while costing + // ~170x more than Flash. The measured winner is the narrow default; version + // recency alone is not a quality signal. Unused host tools must not change + // this reasoning-only model choice. + reasoningMcq: { + "gemini-3-flash-preview": 1, + "gemini-3.5-flash": 0.91, + "grok-4.5": 0.9, + "claude-sonnet-5": 0.88, + "deepseek-v4-pro": 0.84 + }, + // Same calibration, five multilingual MGSM tasks: Gemini 3.5 Flash was 5/5 + // with the lowest cost and latency; four current flagships were 4/5 and Kimi + // K2.7 was 3/5. + reasoningMath: { + "gemini-3.5-flash": 1, + "grok-4.5": 0.93, + "claude-sonnet-5": 0.9, + "deepseek-v4-pro": 0.9, + "kimi-k3": 0.9 + }, + vision: { + "gemini-3.1-pro": 0.96, + "qwen3.7-max": 0.9, + "claude-sonnet-4.6": 0.9, + "kimi-k3": 0.9, + "grok-4.3": 0.9 + }, + // Long-context eligibility is necessary but not sufficient: a provider can + // advertise a 1M window yet return an empty completion near that boundary. + // The proven long-context flagship leads, and less-established alternatives + // sit in a separate band so price alone cannot displace it. + longContext: { + "gemini-3.1-pro": 1, + "qwen3.7-max": 0.89, + "glm-5.2": 0.89, + "gemini-3.5-flash": 0.88, + "deepseek-v4-pro": 0.85 + }, + // A structured extraction must preserve both the output contract and the + // source-language fields. For Mandarin input the language-native Kimi + // candidate gets a distinct band — a candidate-pool decision, not a post-hoc + // override, so it still falls back normally when Kimi is unavailable. Kimi + // K3 costs ~5x its retired sibling K2.7, so the band must be wider than the + // auto affinityFloorGap (0.10) or price alone re-selects a non-native model + // for Mandarin input; 0.12 keeps K3 alone in the primary band for zh and + // leaves every other language untouched. + extractionZh: { + "kimi-k3": 1, + "gemini-3.5-flash": 0.88, + "gemini-2.5-flash": 0.88, + "gpt-4o-mini": 0.88, + "claude-sonnet-5": 0.88, + "claude-sonnet-4.6": 0.88 + }, + extraction: { + "kimi-k3": 0.9, + "gemini-3.5-flash": 0.9, + "gemini-2.5-flash": 0.9, + "gpt-4o-mini": 0.9, + "claude-sonnet-5": 0.9, + "claude-sonnet-4.6": 0.9 + }, + chat: { + "gemini-3.5-flash": 0.86, + "gemini-2.5-flash": 0.86, + "kimi-k3": 0.86 + } +}; +function affinityBand(features) { + const { taskType, agentDomain, agentRisk, deepWebResearch, terminalToolSignal } = features; + const terminalSafety = features.terminalSafetySensitive; + switch (taskType) { + case "code_agent": + return terminalToolSignal && agentRisk === "complex_high" ? TERMINAL_COMPLEX_HIGH : AFFINITY.codeAgent; + case "tool_agent": + if (terminalToolSignal && agentRisk === "complex_high") return TERMINAL_COMPLEX_HIGH; + if (terminalToolSignal) return terminalSafety ? AFFINITY.terminalToolSafety : AFFINITY.terminalTool; + if (agentDomain === "web_research") return deepWebResearch ? WEB_RESEARCH_DEEP : WEB_RESEARCH; + if (agentDomain === "retail") { + if (agentRisk === "standard") return AFFINITY.retailStandard; + if (agentRisk === "policy_exception") return RETAIL_POLICY_EXCEPTION; + if (agentRisk === "policy_exception_simple") return RETAIL_POLICY_EXCEPTION_SIMPLE; + return AFFINITY.retailHigh; + } + if (agentDomain === "airline") { + return agentRisk === "complex_high" ? AFFINITY.airlineComplex : AFFINITY.airlineStandard; + } + return AFFINITY.toolAgent; + case "tool_agent_parallel": + if (terminalToolSignal) { + return terminalSafety ? AFFINITY.parallelTerminalSafety : AFFINITY.parallelTerminal; + } + if (agentDomain === "web_research") return deepWebResearch ? WEB_RESEARCH_DEEP : WEB_RESEARCH; + if (agentDomain === "retail") { + if (agentRisk === "policy_exception") return RETAIL_POLICY_EXCEPTION; + if (agentRisk === "policy_exception_simple") return RETAIL_POLICY_EXCEPTION_SIMPLE; + return AFFINITY.parallelRetail; + } + if (agentDomain === "airline") { + return agentRisk === "complex_high" ? AFFINITY.parallelAirlineComplex : AFFINITY.parallelAirline; + } + return AFFINITY.parallel; + case "code_edit": + case "debug": + return AFFINITY.codeEdit; + case "reasoning": + return AFFINITY.reasoning; + case "reasoning_mcq": + return AFFINITY.reasoningMcq; + case "reasoning_math": + return AFFINITY.reasoningMath; + case "vision": + return AFFINITY.vision; + case "long_context": + return AFFINITY.longContext; + case "extraction": + return features.language === "zh" ? AFFINITY.extractionZh : AFFINITY.extraction; + case "chat": + return AFFINITY.chat; + } +} +function affinityIn(band, modelId) { + const name = modelId.toLowerCase().slice(modelId.indexOf("/") + 1); + return Math.max(NEUTRAL_AFFINITY, band[name] ?? 0); +} +function evidenceCandidates(task) { + if (task === "code_agent") { + return [ + "openai/gpt-5.3-codex", + "anthropic/claude-sonnet-5", + "openai/gpt-5-mini", + "google/gemini-3.5-flash", + "moonshot/kimi-k3", + "deepseek/deepseek-v4-pro" + ]; + } + if (task === "tool_agent") { + return [ + "anthropic/claude-sonnet-5", + "anthropic/claude-opus-5", + "openai/gpt-5-mini", + "openai/gpt-4.1", + "openai/gpt-4o-mini", + "google/gemini-3.5-flash", + "openai/gpt-5.3-codex", + "moonshot/kimi-k3", + "deepseek/deepseek-v4-pro" + ]; + } + if (task === "tool_agent_parallel") { + return [ + "anthropic/claude-opus-5", + "anthropic/claude-opus-4.8", + "anthropic/claude-sonnet-5", + "openai/gpt-5-mini", + "openai/gpt-4.1", + "openai/gpt-4o-mini", + "xai/grok-4.5", + "google/gemini-3.5-flash", + "deepseek/deepseek-v4-pro" + ]; + } + if (task === "long_context") { + return [ + "google/gemini-3.1-pro", + "deepseek/deepseek-v4-pro", + "qwen/qwen3.7-max", + "zai/glm-5.2", + "google/gemini-3.5-flash" + ]; + } + if (task === "reasoning_mcq") { + return [ + "google/gemini-3-flash-preview", + "google/gemini-3.5-flash", + "xai/grok-4.5", + "anthropic/claude-sonnet-5", + "deepseek/deepseek-v4-pro" + ]; + } + if (task === "extraction") { + return ["moonshot/kimi-k3", "google/gemini-3.5-flash", "anthropic/claude-sonnet-5"]; + } + if (task === "reasoning_math") { + return [ + "google/gemini-3.5-flash", + "xai/grok-4.5", + "anthropic/claude-sonnet-5", + "deepseek/deepseek-v4-pro", + "moonshot/kimi-k3" + ]; + } + return []; +} +var VERIFIED_TOOL_FALLBACKS = [ + "anthropic/claude-fable-5.1", + "anthropic/claude-opus-5.5", + "anthropic/claude-sonnet-5.5", + "deepseek/deepseek-v4.1-flash", + "google/gemini-3.8-flash", + "openai/gpt-5.1", + "openai/gpt-6-astra", + "openai/gpt-6-luna", + "openai/gpt-6-sol", + "openai/gpt-6.1-sol", + "xai/grok-4.6", + "xai/grok-4.7", + "xiaomi/mimo-v2.5" +]; +function isEligible(modelId, features, maxOutputTokens, options) { + const model = options.modelCapabilities?.[modelId] ?? DEFAULT_MODEL_CAPABILITIES[modelId]; + if (!model) return true; + if (features.needsTools && !model.supportsTools) return false; + if (features.needsVision && !model.supportsVision) return false; + if (features.needsStructuredOutput && !model.supportsTools) return false; + if (model.maxOutputTokens < maxOutputTokens) return false; + return model.contextWindow >= (features.estimatedInputTokens + maxOutputTokens) * 1.1; +} +function estimatedCost(modelId, options, inputTokens, outputTokens) { + const price2 = usablePricing(options.modelPricing.get(modelId)); + if (!price2) return Number.POSITIVE_INFINITY; + if (price2.flatPrice !== void 0) return price2.flatPrice; + return (inputTokens * price2.inputPrice + outputTokens * price2.outputPrice) / 1e6; +} +function profileScore(modelId, options, now) { + const profile = options.modelPerformance?.[modelId] ?? LIVE_MODEL_PROFILES[modelId] ?? HISTORICAL_MODEL_PROFILES[modelId]; + if (!profile) return void 0; + const measuredAt = Date.parse(profile.measuredAt); + if (!Number.isFinite(measuredAt)) return void 0; + const finite = (value, optional) => value === void 0 ? optional : Number.isFinite(value) && value >= 0; + if (!finite(profile.latencyMs, false) || !finite(profile.outputTokensPerSecond, false) || !finite(profile.p95LatencyMs, true) || !finite(profile.intelligenceIndex, true) || !finite(profile.errorRate, true) || !finite(profile.samples, true)) { + return void 0; + } + const ageDays = Math.max(0, (now.getTime() - measuredAt) / 864e5); + const sampleConfidence = profile.samples === void 0 ? 1 : Math.min(1, Math.max(0, profile.samples) / 10); + const freshness = Math.pow(0.5, ageDays / 30) * sampleConfidence; + const quality = profile.intelligenceIndex === void 0 ? void 0 : Math.min(1, profile.intelligenceIndex / 50); + const speed = Math.min( + 1, + (2e3 / Math.max(500, profile.latencyMs) + profile.outputTokensPerSecond / 250) / 2 + ); + const tailSpeed = Math.min(1, 3e3 / Math.max(750, profile.p95LatencyMs ?? profile.latencyMs)); + const reliability = Math.max(0, 1 - (profile.errorRate ?? 0)); + return { quality, speed, tailSpeed, reliability, freshness }; +} +var PortfolioStrategy = class { + name = "portfolio"; + // Rules set the capability tier; the strategy is stateless, so one instance serves every request. + rules = new RulesStrategy(); + route(prompt, systemPrompt, maxOutputTokens, options) { + const features = classifyTask(prompt, systemPrompt, options); + const base = this.rules.route(prompt, systemPrompt, maxOutputTokens, { + ...options, + requiresTools: features.needsTools + }); + const tierConfigs = base.tierConfigs; + if (!tierConfigs) return base; + const targetTier = (features.taskType === "reasoning_mcq" || features.taskType === "reasoning_math") && (base.tier === "SIMPLE" || base.tier === "MEDIUM") ? "REASONING" : (features.taskType === "debug" || features.taskType === "code_edit") && features.codeArtifact && base.tier === "SIMPLE" ? "MEDIUM" : base.tier; + const tierConfig = tierConfigs[targetTier]; + const configuredCandidates = tierConfig ? getFallbackChain(targetTier, tierConfigs) : []; + const unavailable = new Set(options.unavailableModels ?? []); + const verifiedToolFallbacks = features.needsTools ? VERIFIED_TOOL_FALLBACKS.filter((model2) => options.modelPricing.has(model2)) : []; + if (options.routingProfile !== "premium") { + const fallbackCost = (model2) => estimatedCost(model2, options, features.estimatedInputTokens, maxOutputTokens); + verifiedToolFallbacks.sort((a, b) => fallbackCost(a) - fallbackCost(b)); } - }, - // Time-windowed promotions — auto-applied when active, ignored when expired. - // The GLM-5.1 launch promo (2026-04-01 → 2026-05-01) was the last entry and - // has expired; the list is kept empty so the mechanism stays wired. - promotions: [], - overrides: { - maxTokensForceComplex: 1e5, - structuredOutputMinTier: "MEDIUM", - ambiguousDefaultTier: "MEDIUM" - // agenticMode left undefined → auto-detect via tools/agenticScore. - // Set to `true` to force agentic tiers; `false` to disable them entirely. + const chain = [ + .../* @__PURE__ */ new Set([ + ...configuredCandidates, + ...evidenceCandidates(features.taskType), + ...verifiedToolFallbacks + ]) + ].filter( + (model2) => typeof model2 === "string" && model2.length > 0 && !unavailable.has(model2) + ); + const eligible = new Set( + chain.filter((model2) => isEligible(model2, features, maxOutputTokens, options)) + ); + const eligibleCandidates = eligible.size > 0 ? [...eligible] : chain; + if (eligibleCandidates.length === 0) return base; + const profileName = options.routingProfile === "eco" ? "eco" : options.routingProfile === "premium" ? "premium" : "auto"; + const portfolio = options.config.portfolio ?? DEFAULT_PORTFOLIO_WEIGHTS; + const band = affinityBand(features); + const affinityCache = /* @__PURE__ */ new Map(); + const getAffinity = (model2) => { + let value = affinityCache.get(model2); + if (value === void 0) { + value = affinityIn(band, model2); + affinityCache.set(model2, value); + } + return value; + }; + const bestAffinity = Math.max(...eligibleCandidates.map(getAffinity)); + const specificAffinity = eligibleCandidates.filter((model2) => getAffinity(model2) > NEUTRAL_AFFINITY); + const affinityPool = specificAffinity.length > 0 ? specificAffinity : [eligibleCandidates[0]]; + const affinityFloorGap = features.terminalToolSignal ? Math.max( + portfolio.affinityFloorGap[profileName], + features.terminalSafetySensitive ? 0.15 : 0.12 + ) : portfolio.affinityFloorGap[profileName]; + const candidates = affinityPool.filter( + (model2) => getAffinity(model2) >= bestAffinity - affinityFloorGap + ); + const costs = candidates.map( + (model2) => estimatedCost(model2, options, features.estimatedInputTokens, maxOutputTokens) + ); + const finiteCosts = costs.filter(Number.isFinite); + const minCost = finiteCosts.length > 0 ? Math.min(...finiteCosts) : 0; + const maxCost = finiteCosts.length > 0 ? Math.max(...finiteCosts) : 1; + const now = options.now ?? /* @__PURE__ */ new Date(); + const profileWeights = portfolio[profileName]; + const rankedEntries = candidates.map((model2, index) => { + const cost = costs[index]; + const costScore = !Number.isFinite(cost) ? 0 : maxCost > minCost ? 1 - (cost - minCost) / (maxCost - minCost) : 0.5; + const capabilityScore = eligible.has(model2) ? 1 : 0; + const profile = profileScore(model2, options, now); + const observedQuality = profile?.quality === void 0 ? getAffinity(model2) : getAffinity(model2) * (1 - profile.freshness) + profile.quality * profile.freshness; + const observedSpeed = profile ? profile.speed * profile.freshness + 0.5 * (1 - profile.freshness) : 0.5; + const observedTailSpeed = profile ? profile.tailSpeed * profile.freshness + 0.5 * (1 - profile.freshness) : 0.5; + const observedReliability = profile ? profile.reliability * profile.freshness + (1 - profile.freshness) : 1; + const legacyScore = 1 - index / Math.max(1, candidates.length - 1); + const qualityWeight = profileWeights.quality + (features.highStakes ? portfolio.highStakesBoost.quality : 0); + const speedScore = features.latencySensitive ? observedTailSpeed : observedSpeed; + const speedWeight = profileWeights.speed + (features.latencySensitive ? portfolio.latencySensitiveSpeedBoost : 0); + const reliabilityWeight = profileWeights.reliability + (features.highStakes ? portfolio.highStakesBoost.reliability : 0); + const score = observedQuality * qualityWeight + capabilityScore * profileWeights.capability + costScore * profileWeights.cost + speedScore * speedWeight + observedReliability * reliabilityWeight + legacyScore * profileWeights.legacy; + return { + model: model2, + score, + quality: observedQuality, + cost: costScore, + speed: speedScore, + reliability: observedReliability + }; + }).sort((a, b) => b.score - a.score); + const scoredModels = rankedEntries.map((item) => item.model); + const webResearchFallbackOrder = [ + "anthropic/claude-sonnet-5", + "openai/gpt-5-mini", + "google/gemini-3.5-flash", + "anthropic/claude-opus-5", + "anthropic/claude-opus-4.8", + "openai/gpt-5.3-codex" + ]; + const ranked = features.agentDomain === "web_research" ? [ + ...scoredModels, + ...webResearchFallbackOrder.filter( + (model2) => eligibleCandidates.includes(model2) && !scoredModels.includes(model2) + ), + ...eligibleCandidates.filter( + (model2) => !scoredModels.includes(model2) && !webResearchFallbackOrder.includes(model2) + ) + ] : [...scoredModels, ...eligibleCandidates.filter((model2) => !scoredModels.includes(model2))]; + const model = ranked[0] ?? base.model; + const selectedTierConfigs = { + ...tierConfigs, + [targetTier]: { primary: model, fallback: ranked.slice(1) } + }; + const decision = selectModel( + targetTier, + base.confidence, + "portfolio", + `${base.reasoning} | v3 task=${features.taskType} agentRisk=${features.agentRisk} deepWebResearch=${features.deepWebResearch} terminalCode=${features.implicitTerminalCode} terminalSafety=${features.terminalSafetySensitive} candidates=${ranked.length}`, + selectedTierConfigs, + options.modelPricing, + features.estimatedInputTokens, + maxOutputTokens, + options.routingProfile, + base.agenticScore + ); + return { + ...decision, + tierConfigs: selectedTierConfigs, + profile: base.profile, + candidates: ranked, + candidateScores: rankedEntries.map(({ model: model2, score, quality, cost, speed, reliability }) => ({ + model: model2, + score, + quality, + cost, + speed, + reliability + })), + taskType: features.taskType, + routerVersion: "v3-portfolio" + }; } }; -// index.ts +// src/catalog.ts +var MODEL_KINDS = ["chat", "image", "video", "music"]; +var PRICE_KEYS = [ + "input", + "output", + "per_image", + "per_second", + "per_track", + "cache_read", + "cache_write", + "transaction_fee", + "per_call_surcharge", + "default_duration_seconds", + "max_duration_seconds" +]; +var UNIT_PRICE = { image: "per_image", video: "per_second", music: "per_track" }; +var MODEL_ID = /^[a-z0-9][a-z0-9._-]*\/[a-zA-Z0-9][a-zA-Z0-9._:+-]*$/; +var record = (value) => value !== null && typeof value === "object" && !Array.isArray(value); +var price = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0; +var capacity = (value) => typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0; +function parseModelCatalog(value) { + if (!record(value) || !Array.isArray(value.data)) { + throw new TypeError("Model catalog must contain a data array"); + } + const entries = /* @__PURE__ */ new Map(); + for (const entry of value.data) { + if (record(entry) && typeof entry.id === "string" && entry.id.length <= 200 && MODEL_ID.test(entry.id)) { + entries.set(entry.id, entry); + } + } + const result = { models: [], chat: [], image: [], video: [], music: [], unavailable: [] }; + const models = []; + const unavailable = []; + for (const [id, entry] of entries) { + if (entry.available === false) unavailable.push(id); + if (entry.available !== void 0 && entry.available !== true || entry.hidden !== void 0 && entry.hidden !== false || !Array.isArray(entry.categories) || !record(entry.pricing)) continue; + const categories = [...new Set(entry.categories.filter((c) => typeof c === "string"))]; + const rawPricing = entry.pricing; + const pricing = {}; + for (const key of PRICE_KEYS) if (price(rawPricing[key])) pricing[key] = rawPricing[key]; + const kinds = MODEL_KINDS.filter((kind) => categories.includes(kind) && (kind === "chat" ? price(rawPricing.input) && price(rawPricing.output) : price(rawPricing[UNIT_PRICE[kind]]))); + if (!kinds.length) continue; + const model = { + id, + name: typeof entry.name === "string" && entry.name.trim() ? entry.name : id, + categories, + kinds, + pricing, + free: kinds.includes("chat") && entry.billing_mode === "free" && pricing.input === 0 && pricing.output === 0, + ...typeof entry.billing_mode === "string" ? { billingMode: entry.billing_mode } : {}, + ...capacity(entry.context_window) !== void 0 ? { contextWindow: capacity(entry.context_window) } : {}, + ...capacity(entry.max_output) !== void 0 ? { maxOutputTokens: capacity(entry.max_output) } : {} + }; + models.push(model); + } + result.models = models; + result.unavailable = unavailable; + for (const kind of MODEL_KINDS) result[kind] = models.filter((model) => model.kinds.includes(kind)); + return result; +} +function toRoutingCatalog(catalog, options = {}) { + const verified = { ...DEFAULT_MODEL_CAPABILITIES, ...options.verifiedCapabilities }; + const modelPricing = /* @__PURE__ */ new Map(); + const modelCapabilities = {}; + for (const model of catalog.chat) { + modelPricing.set(model.id, { inputPrice: model.pricing.input, outputPrice: model.pricing.output }); + const evidence = verified[model.id]; + modelCapabilities[model.id] = { + contextWindow: model.contextWindow ?? evidence?.contextWindow ?? 0, + maxOutputTokens: model.maxOutputTokens ?? evidence?.maxOutputTokens ?? 0, + supportsTools: evidence?.supportsTools === true, + // Verified evidence wins over the category tag in both directions: the + // catalog omits "vision" for some models that accept images and tags + // others whose image input does not hold up (see capability-overrides). + supportsVision: evidence?.supportsVision ?? model.categories.includes("vision") + }; + } + return { modelPricing, modelCapabilities, unavailableModels: [...catalog.unavailable] }; +} + +// src/index.ts registerStrategy(new PortfolioStrategy()); function route(prompt, systemPrompt, maxOutputTokens, options) { const strategy = getStrategy(options.config.strategy ?? "portfolio"); diff --git a/dist/index.js.map b/dist/index.js.map index 5d62399..6078bc6 100644 --- a/dist/index.js.map +++ b/dist/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../rules.ts","../selector.ts","../tokens.ts","../strategy.ts","../model-capabilities.ts","../model-profiles.generated.json","../model-profiles.ts","../tool-intent.ts","../portfolio.ts","../catalog.ts","../config.ts","../index.ts"],"sourcesContent":["/**\n * Rule-Based Classifier (v2 — Weighted Scoring)\n *\n * Scores a request across 15 weighted dimensions and maps the aggregate\n * score to a tier using configurable boundaries. Confidence is calibrated\n * via sigmoid — low confidence triggers the fallback classifier.\n *\n * Handles 70-80% of requests in < 1ms with zero cost.\n */\n\nimport type { Tier, ScoringResult, ScoringConfig } from \"./types.js\";\n\ntype DimensionScore = { name: string; score: number; signal: string | null };\n\n// ─── Keyword Matching ───\n//\n// A plain substring test counted `class` in \"classic\", `story` in \"history\",\n// `edit` in \"credit\" and `fix` in \"prefix\", so everyday prose picked up code,\n// creative and agentic signals it did not carry. Alphabetic keywords now have\n// to start at a word boundary. Short ASCII keywords additionally have to end\n// at one, after an optional inflection, graded by how much a stray suffix can\n// change the word: a three-letter keyword takes only the English endings that\n// cannot spell another word (fix → fixes, never pip → pipe or def → defer); a\n// four-to-six-letter keyword also takes the common German and Romance endings,\n// because the lists spell those languages in ASCII too (beweis → beweise,\n// klasse → klassen); anything longer stays trailing-open like the substring\n// test it replaces, since its false-positive surface is small and its\n// inflection surface is large. Non-ASCII alphabetic keywords keep a\n// trailing-open match because several are deliberate stems (`оптимизаци`,\n// `рассуждени`). CJK, Hangul and Arabic keywords keep the substring test:\n// those scripts have no word boundaries, or attach particles and articles\n// directly to the word.\n\nconst UNSEGMENTED_SCRIPT =\n /[؀-ۿ -ヿ㐀-䶿一-鿿가-힯豈-﫿＀-￯]/;\nconst WORD_CHAR = /[\\p{L}\\p{N}]/u;\nconst ASCII_PHRASE = /^[a-z0-9' -]+$/;\n// A word boundary is a transition out of the segmented scripts. A CJK\n// character next to a Latin keyword (\"请step by step证明\") is a boundary, not\n// part of the word: mixed-script prompts carry no spaces between scripts.\nconst SEGMENTED_WORD_CHAR = \"\\\\p{Script=Latin}\\\\p{Script=Cyrillic}\\\\p{Script=Greek}\\\\p{N}\";\nconst BOUNDARY_BEFORE = `(?();\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction keywordMatcher(keyword: string): KeywordMatcher {\n const cached = matcherCache.get(keyword);\n if (cached) return cached;\n\n const kw = keyword.toLowerCase();\n let matcher: KeywordMatcher;\n if (UNSEGMENTED_SCRIPT.test(kw) || kw.length === 0) {\n matcher = { needle: kw, pattern: null };\n } else {\n const lead = WORD_CHAR.test(kw[0]) ? BOUNDARY_BEFORE : \"\";\n const escaped = escapeRegExp(kw);\n let body = escaped;\n let trail = \"\";\n let needle = kw;\n const lastWord = kw.slice(kw.lastIndexOf(\" \") + 1);\n if (\n WORD_CHAR.test(kw[kw.length - 1]) &&\n ASCII_PHRASE.test(kw) &&\n lastWord.length <= BOUNDED_LAST_WORD_LENGTH\n ) {\n // ASCII phrases contain no regex metacharacters, so `escaped` slices\n // align with `kw` slices below.\n const forms: string[] = [];\n if (/\\d$/.test(kw)) {\n // \"step 1\" must not absorb \"step 10\".\n forms.push(escaped);\n } else if (lastWord.length <= 3) {\n forms.push(`${escaped}${SHORT_SUFFIXES}`);\n if (/(?:x|s|z|ch|sh)$/.test(kw)) forms.push(`${escaped}${SIBILANT_PLURAL}`);\n } else {\n forms.push(`${escaped}${MID_SUFFIXES}`);\n if (kw.endsWith(\"e\")) {\n forms.push(`${escaped.slice(0, -1)}${DROPPED_E_SUFFIXES}`);\n needle = kw.slice(0, -1);\n } else if (kw.endsWith(\"y\")) {\n forms.push(`${escaped.slice(0, -1)}(?:ies|ied)`);\n needle = kw.slice(0, -1);\n } else if (/[aeiou][bdgmnprt]$/.test(kw)) {\n // debug → debugging, plan → planned\n forms.push(`${escaped}${kw[kw.length - 1]}${DOUBLED_CONSONANT_SUFFIXES}`);\n }\n }\n body = `(?:${forms.join(\"|\")})`;\n trail = BOUNDARY_AFTER;\n }\n matcher = { needle, pattern: new RegExp(`${lead}${body}${trail}`, \"u\") };\n }\n matcherCache.set(keyword, matcher);\n return matcher;\n}\n\n/** Whether lower-cased `text` contains `keyword` as a word (or as a substring for CJK). */\nfunction matchesKeyword(text: string, keyword: string): boolean {\n const { needle, pattern } = keywordMatcher(keyword);\n if (!text.includes(needle)) return false;\n return pattern === null ? true : pattern.test(text);\n}\n\n// ─── Dimension Scorers ───\n// Each returns a score in [-1, 1] and an optional signal string.\n\nfunction scoreTokenCount(\n estimatedTokens: number,\n thresholds: { simple: number; complex: number },\n): DimensionScore {\n if (estimatedTokens < thresholds.simple) {\n return { name: \"tokenCount\", score: -1.0, signal: `short (${estimatedTokens} tokens)` };\n }\n if (estimatedTokens > thresholds.complex) {\n return { name: \"tokenCount\", score: 1.0, signal: `long (${estimatedTokens} tokens)` };\n }\n return { name: \"tokenCount\", score: 0, signal: null };\n}\n\nfunction scoreKeywordMatch(\n text: string,\n keywords: string[],\n name: string,\n signalLabel: string,\n thresholds: { low: number; high: number },\n scores: { none: number; low: number; high: number },\n): DimensionScore {\n const matches = keywords.filter((kw) => matchesKeyword(text, kw));\n if (matches.length >= thresholds.high) {\n return {\n name,\n score: scores.high,\n signal: `${signalLabel} (${matches.slice(0, 3).join(\", \")})`,\n };\n }\n if (matches.length >= thresholds.low) {\n return {\n name,\n score: scores.low,\n signal: `${signalLabel} (${matches.slice(0, 3).join(\", \")})`,\n };\n }\n return { name, score: scores.none, signal: null };\n}\n\nfunction scoreMultiStep(text: string): DimensionScore {\n const patterns = [/first.*then/i, /step \\d/i, /\\d\\.\\s/];\n const hits = patterns.filter((p) => p.test(text));\n if (hits.length > 0) {\n return { name: \"multiStepPatterns\", score: 0.5, signal: \"multi-step\" };\n }\n return { name: \"multiStepPatterns\", score: 0, signal: null };\n}\n\nfunction scoreQuestionComplexity(prompt: string): DimensionScore {\n const count = (prompt.match(/\\?/g) || []).length;\n if (count > 3) {\n return { name: \"questionComplexity\", score: 0.5, signal: `${count} questions` };\n }\n return { name: \"questionComplexity\", score: 0, signal: null };\n}\n\n/**\n * Score agentic task indicators.\n * Returns agenticScore (0-1) based on keyword matches:\n * - 4+ matches = 1.0 (high agentic)\n * - 3 matches = 0.6 (moderate agentic, triggers auto-agentic mode)\n * - 1-2 matches = 0.2 (low agentic)\n *\n * Thresholds raised because common keywords were pruned from the list.\n */\nfunction scoreAgenticTask(\n text: string,\n keywords: string[],\n): { dimensionScore: DimensionScore; agenticScore: number } {\n let matchCount = 0;\n const signals: string[] = [];\n\n for (const keyword of keywords) {\n if (matchesKeyword(text, keyword)) {\n matchCount++;\n if (signals.length < 3) {\n signals.push(keyword);\n }\n }\n }\n\n // Threshold-based scoring (raised thresholds after keyword pruning)\n if (matchCount >= 4) {\n return {\n dimensionScore: {\n name: \"agenticTask\",\n score: 1.0,\n signal: `agentic (${signals.join(\", \")})`,\n },\n agenticScore: 1.0,\n };\n } else if (matchCount >= 3) {\n return {\n dimensionScore: {\n name: \"agenticTask\",\n score: 0.6,\n signal: `agentic (${signals.join(\", \")})`,\n },\n agenticScore: 0.6,\n };\n } else if (matchCount >= 1) {\n return {\n dimensionScore: {\n name: \"agenticTask\",\n score: 0.2,\n signal: `agentic-light (${signals.join(\", \")})`,\n },\n agenticScore: 0.2,\n };\n }\n\n return {\n dimensionScore: { name: \"agenticTask\", score: 0, signal: null },\n agenticScore: 0,\n };\n}\n\n// ─── Main Classifier ───\n\nexport function classifyByRules(\n prompt: string,\n systemPrompt: string | undefined,\n estimatedTokens: number,\n config: ScoringConfig,\n): ScoringResult {\n // Score against user prompt only — system prompts contain boilerplate keywords\n // (tool definitions, skill descriptions, behavioral rules) that dominate scoring\n // and make every request score identically. See GitHub issue #50.\n const userText = prompt.toLowerCase();\n\n // Score the base dimensions against user text only; the agentic dimension is\n // appended below, so the scored total is one more than this list.\n const dimensions: DimensionScore[] = [\n // Token count uses total estimated tokens (system + user) — context size matters for model selection\n scoreTokenCount(estimatedTokens, config.tokenCountThresholds),\n scoreKeywordMatch(\n userText,\n config.codeKeywords,\n \"codePresence\",\n \"code\",\n { low: 1, high: 2 },\n { none: 0, low: 0.5, high: 1.0 },\n ),\n scoreKeywordMatch(\n userText,\n config.reasoningKeywords,\n \"reasoningMarkers\",\n \"reasoning\",\n { low: 1, high: 2 },\n { none: 0, low: 0.7, high: 1.0 },\n ),\n scoreKeywordMatch(\n userText,\n config.technicalKeywords,\n \"technicalTerms\",\n \"technical\",\n { low: 2, high: 4 },\n { none: 0, low: 0.5, high: 1.0 },\n ),\n scoreKeywordMatch(\n userText,\n config.creativeKeywords,\n \"creativeMarkers\",\n \"creative\",\n { low: 1, high: 2 },\n { none: 0, low: 0.5, high: 0.7 },\n ),\n scoreKeywordMatch(\n userText,\n config.simpleKeywords,\n \"simpleIndicators\",\n \"simple\",\n { low: 1, high: 2 },\n { none: 0, low: -1.0, high: -1.0 },\n ),\n scoreMultiStep(userText),\n scoreQuestionComplexity(prompt),\n\n // 6 new dimensions\n scoreKeywordMatch(\n userText,\n config.imperativeVerbs,\n \"imperativeVerbs\",\n \"imperative\",\n { low: 1, high: 2 },\n { none: 0, low: 0.3, high: 0.5 },\n ),\n scoreKeywordMatch(\n userText,\n config.constraintIndicators,\n \"constraintCount\",\n \"constraints\",\n { low: 1, high: 3 },\n { none: 0, low: 0.3, high: 0.7 },\n ),\n scoreKeywordMatch(\n userText,\n config.outputFormatKeywords,\n \"outputFormat\",\n \"format\",\n { low: 1, high: 2 },\n { none: 0, low: 0.4, high: 0.7 },\n ),\n scoreKeywordMatch(\n userText,\n config.referenceKeywords,\n \"referenceComplexity\",\n \"references\",\n { low: 1, high: 2 },\n { none: 0, low: 0.3, high: 0.5 },\n ),\n scoreKeywordMatch(\n userText,\n config.negationKeywords,\n \"negationComplexity\",\n \"negation\",\n { low: 2, high: 3 },\n { none: 0, low: 0.3, high: 0.5 },\n ),\n scoreKeywordMatch(\n userText,\n config.domainSpecificKeywords,\n \"domainSpecificity\",\n \"domain-specific\",\n { low: 1, high: 2 },\n { none: 0, low: 0.5, high: 0.8 },\n ),\n ];\n\n // Score agentic task indicators — user prompt only\n // System prompt describes assistant behavior, not user's intent.\n // e.g. a coding assistant system prompt with \"edit files\" / \"fix bugs\" should NOT\n // force every request into agentic mode.\n const agenticResult = scoreAgenticTask(userText, config.agenticTaskKeywords);\n dimensions.push(agenticResult.dimensionScore);\n const agenticScore = agenticResult.agenticScore;\n\n // Collect signals\n const signals = dimensions.filter((d) => d.signal !== null).map((d) => d.signal!);\n\n // Compute weighted score\n const weights = config.dimensionWeights;\n let weightedScore = 0;\n for (const d of dimensions) {\n const w = weights[d.name] ?? 0;\n weightedScore += d.score * w;\n }\n\n // Count reasoning markers for override — only check USER prompt, not system prompt\n // This prevents system prompts with \"step by step\" from triggering REASONING for simple queries\n const reasoningMatches = config.reasoningKeywords.filter((kw) => matchesKeyword(userText, kw));\n\n // Direct reasoning override: 2+ reasoning markers = high confidence REASONING\n if (reasoningMatches.length >= 2) {\n const confidence = calibrateConfidence(\n Math.max(weightedScore, 0.3), // ensure positive for confidence calc\n config.confidenceSteepness,\n );\n return {\n score: weightedScore,\n tier: \"REASONING\",\n confidence: Math.max(confidence, 0.85),\n signals,\n agenticScore,\n dimensions,\n };\n }\n\n // Map weighted score to tier using boundaries\n const { simpleMedium, mediumComplex, complexReasoning } = config.tierBoundaries;\n let tier: Tier;\n let distanceFromBoundary: number;\n\n if (weightedScore < simpleMedium) {\n tier = \"SIMPLE\";\n distanceFromBoundary = simpleMedium - weightedScore;\n } else if (weightedScore < mediumComplex) {\n tier = \"MEDIUM\";\n distanceFromBoundary = Math.min(weightedScore - simpleMedium, mediumComplex - weightedScore);\n } else if (weightedScore < complexReasoning) {\n tier = \"COMPLEX\";\n distanceFromBoundary = Math.min(\n weightedScore - mediumComplex,\n complexReasoning - weightedScore,\n );\n } else {\n tier = \"REASONING\";\n distanceFromBoundary = weightedScore - complexReasoning;\n }\n\n // Calibrate confidence via sigmoid of distance from nearest boundary\n const confidence = calibrateConfidence(distanceFromBoundary, config.confidenceSteepness);\n\n // If confidence is below threshold → ambiguous\n if (confidence < config.confidenceThreshold) {\n return { score: weightedScore, tier: null, confidence, signals, agenticScore, dimensions };\n }\n\n return { score: weightedScore, tier, confidence, signals, agenticScore, dimensions };\n}\n\n/**\n * Sigmoid confidence calibration.\n * Maps distance from tier boundary to [0.5, 1.0] confidence range.\n */\nfunction calibrateConfidence(distance: number, steepness: number): number {\n return 1 / (1 + Math.exp(-steepness * distance));\n}\n","/**\n * Tier → Model Selection\n *\n * Maps a classification tier to the cheapest capable model.\n * Builds RoutingDecision metadata with cost estimates and savings.\n */\n\nimport type { Tier, TierConfig, RoutingDecision } from \"./types.js\";\n\nexport type ModelPricing = {\n inputPrice: number; // per 1M tokens\n outputPrice: number; // per 1M tokens\n /** Active promo flat price per request (overrides token-based pricing when set) */\n flatPrice?: number;\n};\n\n// The savings baseline is a price anchor, not \"the current flagship\" — it is\n// deliberately NOT bumped every time a new Opus ships. Opus 4.7, 4.8 and 5 all\n// bill $5/$25, so moving it would change no reported number while breaking\n// comparability with historical journal entries. Only move it if the Opus tier\n// itself is repriced.\nconst BASELINE_MODEL_ID = \"anthropic/claude-opus-4.7\";\n\n// Hardcoded fallback: Claude Opus 4.7 pricing (per 1M tokens)\n// Used when baseline model not found in dynamic pricing map\nconst BASELINE_INPUT_PRICE = 5.0;\nconst BASELINE_OUTPUT_PRICE = 25.0;\n\n/**\n * Select the primary model for a tier and build the RoutingDecision.\n *\n * Cost contract: the estimates here are raw token economics — no server\n * margin, no minimum-payment floor. `calculateModelCost` below applies both\n * to match the actual x402 charge, and hosts that display money (ClawRouter's\n * proxy does) recompute through it rather than reading these fields. Folding\n * the margin in here would double-apply it in every such host.\n */\nexport function selectModel(\n tier: Tier,\n confidence: number,\n method: \"rules\" | \"llm\" | \"portfolio\",\n reasoning: string,\n tierConfigs: Record,\n modelPricing: Map,\n estimatedInputTokens: number,\n maxOutputTokens: number,\n routingProfile?: \"free\" | \"eco\" | \"auto\" | \"premium\",\n agenticScore?: number,\n): RoutingDecision {\n const tierConfig = tierConfigs[tier];\n const model = tierConfig.primary;\n const pricing = modelPricing.get(model);\n\n let costEstimate: number;\n if (pricing?.flatPrice !== undefined) {\n costEstimate = pricing.flatPrice;\n } else {\n const inputPrice = pricing?.inputPrice ?? 0;\n const outputPrice = pricing?.outputPrice ?? 0;\n costEstimate =\n (estimatedInputTokens / 1_000_000) * inputPrice + (maxOutputTokens / 1_000_000) * outputPrice;\n }\n\n // Baseline: what the anchor Opus tier would cost (see BASELINE_MODEL_ID)\n const opusPricing = modelPricing.get(BASELINE_MODEL_ID);\n const opusInputPrice = opusPricing?.inputPrice ?? BASELINE_INPUT_PRICE;\n const opusOutputPrice = opusPricing?.outputPrice ?? BASELINE_OUTPUT_PRICE;\n const baselineInput = (estimatedInputTokens / 1_000_000) * opusInputPrice;\n const baselineOutput = (maxOutputTokens / 1_000_000) * opusOutputPrice;\n const baselineCost = baselineInput + baselineOutput;\n\n // Premium profile doesn't calculate savings (it's about quality, not cost).\n // A model the host has no price for costs an unknown amount, not nothing;\n // reporting its savings as 100% would be a fabricated figure.\n const savings =\n routingProfile === \"premium\" || pricing === undefined\n ? 0\n : baselineCost > 0\n ? Math.max(0, (baselineCost - costEstimate) / baselineCost)\n : 0;\n\n return {\n model,\n tier,\n confidence,\n method,\n reasoning,\n costEstimate,\n baselineCost,\n savings,\n ...(agenticScore !== undefined && { agenticScore }),\n };\n}\n\n/**\n * Get the ordered fallback chain for a tier: [primary, ...fallbacks].\n */\nexport function getFallbackChain(tier: Tier, tierConfigs: Record): string[] {\n const config = tierConfigs[tier];\n return [config.primary, ...config.fallback];\n}\n\n/**\n * Calculate charge-accurate cost fields for a specific model (server margin\n * and minimum-payment floor included — see the cost contract on selectModel).\n * Hosts call this to display money and to recost a decision after a fallback.\n */\n// Server-side margin applied to all x402 payments (must match blockrun server's MARGIN_PERCENT)\nconst SERVER_MARGIN_PERCENT = 5;\n// Minimum payment enforced by CDP Facilitator (must match blockrun server's MIN_PAYMENT_USD)\nconst MIN_PAYMENT_USD = 0.001;\n\nexport function calculateModelCost(\n model: string,\n modelPricing: Map,\n estimatedInputTokens: number,\n maxOutputTokens: number,\n routingProfile?: \"free\" | \"eco\" | \"auto\" | \"premium\",\n): { costEstimate: number; baselineCost: number; savings: number } {\n const pricing = modelPricing.get(model);\n\n let costEstimate: number;\n if (pricing?.flatPrice !== undefined) {\n // Active promo: fixed cost per request\n costEstimate = Math.max(pricing.flatPrice * (1 + SERVER_MARGIN_PERCENT / 100), MIN_PAYMENT_USD);\n } else {\n // Defensive: guard against undefined price fields (not just undefined pricing)\n const inputPrice = pricing?.inputPrice ?? 0;\n const outputPrice = pricing?.outputPrice ?? 0;\n const inputCost = (estimatedInputTokens / 1_000_000) * inputPrice;\n const outputCost = (maxOutputTokens / 1_000_000) * outputPrice;\n // Include server margin + minimum payment to match actual x402 charge\n costEstimate = Math.max(\n (inputCost + outputCost) * (1 + SERVER_MARGIN_PERCENT / 100),\n MIN_PAYMENT_USD,\n );\n }\n\n // Baseline: what the anchor Opus tier would cost (see BASELINE_MODEL_ID)\n const opusPricing = modelPricing.get(BASELINE_MODEL_ID);\n const opusInputPrice = opusPricing?.inputPrice ?? BASELINE_INPUT_PRICE;\n const opusOutputPrice = opusPricing?.outputPrice ?? BASELINE_OUTPUT_PRICE;\n const baselineInput = (estimatedInputTokens / 1_000_000) * opusInputPrice;\n const baselineOutput = (maxOutputTokens / 1_000_000) * opusOutputPrice;\n const baselineCost = baselineInput + baselineOutput;\n\n // Premium profile doesn't calculate savings (it's about quality, not cost)\n const savings =\n routingProfile === \"premium\"\n ? 0\n : baselineCost > 0\n ? Math.max(0, (baselineCost - costEstimate) / baselineCost)\n : 0;\n\n return { costEstimate, baselineCost, savings };\n}\n\n/**\n * Filter a model list to only those that support tool calling.\n * When hasTools is false, returns the list unchanged.\n * When all models lack tool calling support, returns the full list as a fallback\n * (better to let the API error than produce an empty chain).\n */\nexport function filterByToolCalling(\n models: string[],\n hasTools: boolean,\n supportsToolCalling: (modelId: string) => boolean,\n): string[] {\n if (!hasTools) return models;\n const filtered = models.filter(supportsToolCalling);\n return filtered.length > 0 ? filtered : models;\n}\n\n/**\n * Filter a model list to only those that support vision (image inputs).\n * When hasVision is false, returns the list unchanged.\n * When all models lack vision support, returns the full list as a fallback\n * (better to let the API error than produce an empty chain).\n */\nexport function filterByVision(\n models: string[],\n hasVision: boolean,\n supportsVision: (modelId: string) => boolean,\n): string[] {\n if (!hasVision) return models;\n const filtered = models.filter(supportsVision);\n return filtered.length > 0 ? filtered : models;\n}\n\n/**\n * Filter a model list to remove user-excluded models.\n * When all models are excluded, returns the full list as a fallback\n * (same safety pattern as filterByToolCalling/filterByVision).\n */\nexport function filterByExcludeList(models: string[], excludeList: Set): string[] {\n if (excludeList.size === 0) return models;\n const filtered = models.filter((m) => !excludeList.has(m));\n return filtered.length > 0 ? filtered : models;\n}\n\n/**\n * Get the fallback chain filtered by context length.\n * Only returns models that can handle the estimated total context.\n *\n * @param tier - The tier to get fallback chain for\n * @param tierConfigs - Tier configurations\n * @param estimatedTotalTokens - Estimated total context (input + output)\n * @param getContextWindow - Function to get context window for a model ID\n * @returns Filtered list of models that can handle the context\n */\nexport function getFallbackChainFiltered(\n tier: Tier,\n tierConfigs: Record,\n estimatedTotalTokens: number,\n getContextWindow: (modelId: string) => number | undefined,\n): string[] {\n const fullChain = getFallbackChain(tier, tierConfigs);\n\n // Filter to models that can handle the context\n const filtered = fullChain.filter((modelId) => {\n const contextWindow = getContextWindow(modelId);\n if (contextWindow === undefined) {\n // Unknown model - include it (let API reject if needed)\n return true;\n }\n // Add 10% buffer for safety\n return contextWindow >= estimatedTotalTokens * 1.1;\n });\n\n // If all models filtered out, return the original chain\n // (let the API error out - better than no options)\n if (filtered.length === 0) {\n return fullChain;\n }\n\n return filtered;\n}\n\n/**\n * Filter an already-ranked candidate list by total context and requested output.\n * Unlike the legacy tier helper, this supports the V3 portfolio order.\n */\nexport function filterCandidatesByCapacity(\n models: string[],\n estimatedInputTokens: number,\n requestedOutputTokens: number,\n getCapabilities: (modelId: string) => { contextWindow: number; maxOutput: number } | undefined,\n): string[] {\n const filtered = models.filter((modelId) => {\n const capabilities = getCapabilities(modelId);\n if (!capabilities) return true;\n return (\n capabilities.contextWindow >= (estimatedInputTokens + requestedOutputTokens) * 1.1 &&\n capabilities.maxOutput >= requestedOutputTokens\n );\n });\n return filtered;\n}\n","/**\n * Request-size helpers shared by the rules and portfolio strategies.\n *\n * The router never tokenizes — it is on the hot path and model-agnostic — so\n * sizes are estimates. The estimate only has to be honest enough for the\n * decisions that consume it: the long-context task type, the COMPLEX\n * override and the per-model capacity filter.\n */\n\n// Han, kana, Hangul, CJK punctuation and fullwidth forms. Every production\n// tokenizer spends roughly one token per character here, so the Latin\n// four-characters-per-token rule under-counts these scripts about fourfold:\n// a 200k-character Chinese contract would read as 50k tokens, slip under the\n// 80k long-context boundary and pass the capacity filter for models that\n// cannot hold it.\nconst CJK_CHARS = /[ -ヿ㐀-䶿一-鿿가-힯豈-﫿＀-￯]/g;\n\n/** Approximate token count: one per CJK character, one per four of anything else. */\nexport function estimateTokens(text: string): number {\n if (text.length === 0) return 0;\n const cjk = text.match(CJK_CHARS)?.length ?? 0;\n return cjk + Math.ceil((text.length - cjk) / 4);\n}\n\n/** The scan window the feature regexes read, bounded so a pasted document cannot stall routing. */\nexport function scanLimit(promptTruncationChars: number): number {\n return Math.max(1, Math.min(8_000, promptTruncationChars));\n}\n\n/**\n * Feature regexes need request shape and intent, not the entire document.\n * Sample both ends so a long pasted artifact keeps the task instruction at\n * either boundary, while the full length still drives capacity decisions.\n */\nexport function sampleForScan(value: string, limit: number): string {\n if (value.length <= limit) return value;\n const prefixLength = Math.ceil(limit / 2);\n return `${value.slice(0, prefixLength)}\\n${value.slice(-(limit - prefixLength))}`;\n}\n","/**\n * Router Strategy Registry\n *\n * Pluggable strategy system for request routing.\n * Default: RulesStrategy — identical to the original inline route() logic, <1ms.\n */\n\nimport type {\n Tier,\n TierConfig,\n Promotion,\n RoutingDecision,\n RouterStrategy,\n RouterOptions,\n} from \"./types.js\";\nimport { classifyByRules } from \"./rules.js\";\nimport { selectModel } from \"./selector.js\";\nimport { estimateTokens, sampleForScan, scanLimit } from \"./tokens.js\";\n\n/**\n * Apply active time-windowed promotions to tier configs.\n * Returns a new tierConfigs object with promotion overrides merged in.\n * Expired or not-yet-active promotions are ignored.\n */\nfunction applyPromotions(\n tierConfigs: Record,\n promotions: Promotion[] | undefined,\n profile: \"auto\" | \"eco\" | \"premium\" | \"agentic\",\n now: Date = new Date(),\n): Record {\n if (!promotions || promotions.length === 0) return tierConfigs;\n\n let result = tierConfigs;\n for (const promo of promotions) {\n // Check time window\n const start = new Date(promo.startDate);\n const end = new Date(promo.endDate);\n if (now < start || now >= end) continue;\n\n // Check profile filter\n if (promo.profiles && !promo.profiles.includes(profile)) continue;\n\n // Shallow-clone on first mutation\n if (result === tierConfigs) {\n result = { ...tierConfigs };\n for (const t of Object.keys(result) as Tier[]) {\n result[t] = { ...result[t] };\n }\n }\n\n // Merge overrides\n for (const [tier, override] of Object.entries(promo.tierOverrides) as [\n Tier,\n Partial,\n ][]) {\n if (!result[tier]) continue;\n if (override.primary) result[tier].primary = override.primary;\n if (override.fallback) result[tier].fallback = override.fallback;\n }\n }\n\n return result;\n}\n\n/**\n * Remove host-declared-dead models from every tier chain, promoting the first\n * surviving rung to primary. A tier whose chain is entirely dead keeps its\n * original config — the router has nothing live to offer there, and inventing\n * a model would hide the outage from the host that reported it.\n */\nexport function applyUnavailableModels(\n tierConfigs: Record,\n unavailableModels: readonly string[] | undefined,\n): Record {\n if (!unavailableModels || unavailableModels.length === 0) return tierConfigs;\n const dead = new Set(unavailableModels);\n let result = tierConfigs;\n for (const tier of Object.keys(tierConfigs) as Tier[]) {\n const config = tierConfigs[tier];\n const alive = [config.primary, ...config.fallback].filter((model) => !dead.has(model));\n if (alive.length === 0 || (alive[0] === config.primary && alive.length === config.fallback.length + 1)) {\n continue;\n }\n if (result === tierConfigs) result = { ...tierConfigs };\n result[tier] = { primary: alive[0], fallback: alive.slice(1) };\n }\n return result;\n}\n\n/**\n * Rules-based routing strategy.\n * Extracted from the original route() in index.ts — logic is identical.\n * Attaches tierConfigs and profile to the decision for downstream use.\n */\nexport class RulesStrategy implements RouterStrategy {\n readonly name = \"rules\";\n\n route(\n prompt: string,\n systemPrompt: string | undefined,\n maxOutputTokens: number,\n options: RouterOptions,\n ): RoutingDecision {\n const { config, modelPricing } = options;\n\n const fullText = `${systemPrompt ?? \"\"} ${prompt}`;\n const estimatedTokens = estimateTokens(fullText);\n const limit = scanLimit(config.classifier.promptTruncationChars);\n const scannedPrompt = sampleForScan(prompt, limit);\n const scannedSystemPrompt = systemPrompt ? sampleForScan(systemPrompt, limit) : undefined;\n\n // --- Rule-based classification (runs first to get agenticScore) ---\n const ruleResult = classifyByRules(\n scannedPrompt,\n scannedSystemPrompt,\n estimatedTokens,\n config.scoring,\n );\n\n // --- Select tier configs based on routing profile ---\n const { routingProfile } = options;\n let tierConfigs: Record;\n let profileSuffix: string;\n let profile: RoutingDecision[\"profile\"];\n\n if (routingProfile === \"eco\") {\n // `ecoTiers: null` explicitly disables the special eco tier set while\n // keeping eco routing semantics. Fall back to regular tiers instead of\n // dropping into auto routing (which could select agentic tiers).\n tierConfigs = config.ecoTiers ?? config.tiers;\n profileSuffix = config.ecoTiers ? \" | eco\" : \" | eco (default tiers)\";\n profile = \"eco\";\n } else if (routingProfile === \"premium\") {\n // `premiumTiers: null` disables the premium-specific tier set but the\n // request is still a premium-profile request, so use regular tiers while\n // preserving premium metadata/cost semantics.\n tierConfigs = config.premiumTiers ?? config.tiers;\n profileSuffix = config.premiumTiers ? \" | premium\" : \" | premium (default tiers)\";\n profile = \"premium\";\n } else {\n // Auto profile (or undefined): intelligent routing with agentic detection.\n //\n // `agenticMode` semantics:\n // - `true` → force agentic tiers (ignore heuristics)\n // - `false` → disable agentic tiers entirely (even if tools are present)\n // - `undefined` → auto-detect via heuristics (tools present OR high agenticScore)\n const agenticScore = ruleResult.agenticScore ?? 0;\n const isAutoAgentic = agenticScore >= 0.5;\n const agenticModeSetting = config.overrides.agenticMode;\n const hasToolsInRequest = options.requiresTools ?? options.hasTools ?? false;\n let useAgenticTiers: boolean;\n if (agenticModeSetting === false) {\n // Explicitly disabled — never use agentic tiers\n useAgenticTiers = false;\n } else if (agenticModeSetting === true) {\n // Explicitly enabled — use agentic tiers if available\n useAgenticTiers = config.agenticTiers != null;\n } else {\n // Auto-detect\n useAgenticTiers = (hasToolsInRequest || isAutoAgentic) && config.agenticTiers != null;\n }\n tierConfigs = useAgenticTiers ? config.agenticTiers! : config.tiers;\n profileSuffix = useAgenticTiers ? ` | agentic${hasToolsInRequest ? \" (tools)\" : \"\"}` : \"\";\n profile = useAgenticTiers ? \"agentic\" : \"auto\";\n }\n\n // Apply time-windowed promotions\n tierConfigs = applyPromotions(tierConfigs, config.promotions, profile!, options.now);\n\n // Hard-remove models the host has observed dead at the gateway. After\n // promotions, so a promo cannot resurrect a rung the host just killed.\n tierConfigs = applyUnavailableModels(tierConfigs, options.unavailableModels);\n\n const agenticScoreValue = ruleResult.agenticScore;\n\n // --- Override: large context → force COMPLEX ---\n if (estimatedTokens > config.overrides.maxTokensForceComplex) {\n const decision = selectModel(\n \"COMPLEX\",\n 0.95,\n \"rules\",\n `Input exceeds ${config.overrides.maxTokensForceComplex} tokens${profileSuffix}`,\n tierConfigs,\n modelPricing,\n estimatedTokens,\n maxOutputTokens,\n routingProfile,\n agenticScoreValue,\n );\n return { ...decision, tierConfigs, profile };\n }\n\n // Structured output is a protocol fact the host states (`response_format`\n // → requiresStructuredOutput). It used to be inferred from the system\n // prompt as well, but agent hosts describe their tool schemas there on\n // every turn, which upgraded every one of their requests off SIMPLE.\n const hasStructuredOutput = options.requiresStructuredOutput === true;\n\n let tier: Tier;\n let confidence: number;\n const method: \"rules\" | \"llm\" = \"rules\";\n let reasoning = `score=${ruleResult.score.toFixed(2)} | ${ruleResult.signals.join(\", \")}`;\n\n if (ruleResult.tier !== null) {\n tier = ruleResult.tier;\n confidence = ruleResult.confidence;\n } else {\n // Ambiguous — default to configurable tier (no external API call)\n tier = config.overrides.ambiguousDefaultTier;\n confidence = 0.5;\n reasoning += ` | ambiguous -> default: ${tier}`;\n }\n\n // Apply structured output minimum tier\n if (hasStructuredOutput) {\n const tierRank: Record = { SIMPLE: 0, MEDIUM: 1, COMPLEX: 2, REASONING: 3 };\n const minTier = config.overrides.structuredOutputMinTier;\n if (tierRank[tier] < tierRank[minTier]) {\n reasoning += ` | upgraded to ${minTier} (structured output)`;\n tier = minTier;\n }\n }\n\n // Add routing profile suffix to reasoning\n reasoning += profileSuffix;\n\n const decision = selectModel(\n tier,\n confidence,\n method,\n reasoning,\n tierConfigs,\n modelPricing,\n estimatedTokens,\n maxOutputTokens,\n routingProfile,\n agenticScoreValue,\n );\n return { ...decision, tierConfigs, profile };\n }\n}\n\n// --- Strategy Registry ---\n\nconst registry = new Map();\nregistry.set(\"rules\", new RulesStrategy());\n\nexport function getStrategy(name: string): RouterStrategy {\n const strategy = registry.get(name);\n if (!strategy) {\n throw new Error(`Unknown routing strategy: ${name}`);\n }\n return strategy;\n}\n\nexport function registerStrategy(strategy: RouterStrategy): void {\n registry.set(strategy.name, strategy);\n}\n","/**\n * Model capabilities used for hard routing constraints.\n *\n * Hosts may inject fresher values through RouterOptions.modelCapabilities.\n * Keeping a small built-in snapshot makes the core safe and useful when a\n * product catalog is temporarily unavailable, without importing product code.\n *\n * GENERATED by scripts/sync-model-capabilities.mjs from the public catalog\n * (GET https://blockrun.ai/api/v1/models) on 2026-10-20; supportsTools comes\n * from a live function-calling probe (scripts/probe-tools.json). Regenerate\n * rather than editing by hand — a hand edit is overwritten on the next sync.\n */\nexport type ModelCapabilities = {\n contextWindow: number;\n maxOutputTokens: number;\n supportsTools: boolean;\n supportsVision: boolean;\n};\n\nexport const DEFAULT_MODEL_CAPABILITIES: Readonly> =\n Object.freeze({\n \"anthropic/claude-fable-5\": {\n contextWindow: 1_000_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"anthropic/claude-fable-5.1\": {\n contextWindow: 1_000_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"anthropic/claude-haiku-4.5\": { // override: The public catalog's `categories` omit \"vision\" for this Anthropic model even though the gateway accepts image input for it (the prior hand-maintained snapshot had it, and Anthropic's model card lists it). Without this the vision filter would silently drop it — reported against the catalog; remove once the categories carry vision.\n contextWindow: 200_000,\n maxOutputTokens: 64_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"anthropic/claude-opus-4.5\": {\n contextWindow: 200_000,\n maxOutputTokens: 64_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"anthropic/claude-opus-4.7\": {\n contextWindow: 1_000_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"anthropic/claude-opus-4.8\": {\n contextWindow: 1_000_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"anthropic/claude-opus-5\": {\n contextWindow: 1_000_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"anthropic/claude-opus-5.5\": {\n contextWindow: 1_000_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"anthropic/claude-sonnet-4.5\": {\n contextWindow: 200_000,\n maxOutputTokens: 64_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"anthropic/claude-sonnet-4.6\": { // override: The public catalog's `categories` omit \"vision\" for this Anthropic model even though the gateway accepts image input for it (the prior hand-maintained snapshot had it, and Anthropic's model card lists it). Without this the vision filter would silently drop it — reported against the catalog; remove once the categories carry vision.\n contextWindow: 1_000_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"anthropic/claude-sonnet-5\": {\n contextWindow: 1_000_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"anthropic/claude-sonnet-5.5\": {\n contextWindow: 1_000_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"cohere/north-mini-code\": { // supportsTools: not probed — fails closed\n contextWindow: 256_000,\n maxOutputTokens: 16_384,\n supportsTools: false,\n supportsVision: false,\n },\n \"deepseek/deepseek-chat\": {\n contextWindow: 1_048_576,\n maxOutputTokens: 65_536,\n supportsTools: true,\n supportsVision: false,\n },\n \"deepseek/deepseek-reasoner\": {\n contextWindow: 1_048_576,\n maxOutputTokens: 65_536,\n supportsTools: true,\n supportsVision: false,\n },\n \"deepseek/deepseek-v4-flash-vision-exp\": {\n contextWindow: 1_048_576,\n maxOutputTokens: 65_536,\n supportsTools: false,\n supportsVision: true,\n },\n \"deepseek/deepseek-v4-pro\": {\n contextWindow: 1_048_576,\n maxOutputTokens: 65_536,\n supportsTools: true,\n supportsVision: false,\n },\n \"deepseek/deepseek-v4.1-flash\": {\n contextWindow: 1_048_576,\n maxOutputTokens: 65_536,\n supportsTools: true,\n supportsVision: false,\n },\n \"google/gemini-2.5-flash\": {\n contextWindow: 1_048_576,\n maxOutputTokens: 65_536,\n supportsTools: true,\n supportsVision: true,\n },\n \"google/gemini-2.5-flash-lite\": {\n contextWindow: 1_048_576,\n maxOutputTokens: 65_536,\n supportsTools: true,\n supportsVision: false,\n },\n \"google/gemini-2.5-pro\": {\n contextWindow: 1_048_576,\n maxOutputTokens: 65_536,\n supportsTools: true,\n supportsVision: true,\n },\n \"google/gemini-3-flash-preview\": {\n contextWindow: 1_048_576,\n maxOutputTokens: 65_536,\n supportsTools: true,\n supportsVision: true,\n },\n \"google/gemini-3.1-flash-lite\": {\n contextWindow: 1_048_576,\n maxOutputTokens: 65_536,\n supportsTools: true,\n supportsVision: false,\n },\n \"google/gemini-3.1-pro\": {\n contextWindow: 1_048_576,\n maxOutputTokens: 65_536,\n supportsTools: true,\n supportsVision: true,\n },\n \"google/gemini-3.5-flash\": {\n contextWindow: 1_048_576,\n maxOutputTokens: 65_536,\n supportsTools: true,\n supportsVision: true,\n },\n \"google/gemini-3.5-flash-lite\": {\n contextWindow: 1_048_576,\n maxOutputTokens: 65_536,\n supportsTools: true,\n supportsVision: false,\n },\n \"google/gemini-3.6-flash\": {\n contextWindow: 1_048_576,\n maxOutputTokens: 65_536,\n supportsTools: true,\n supportsVision: true,\n },\n \"google/gemini-3.8-flash\": {\n contextWindow: 1_048_576,\n maxOutputTokens: 65_536,\n supportsTools: true,\n supportsVision: true,\n },\n \"google/gemini-4-argon\": { // supportsTools: not probed — fails closed\n contextWindow: 1_048_576,\n maxOutputTokens: 65_536,\n supportsTools: false,\n supportsVision: true,\n },\n \"minimax/minimax-m2.7\": {\n contextWindow: 204_800,\n maxOutputTokens: 16_384,\n supportsTools: true,\n supportsVision: false,\n },\n \"minimax/minimax-m3\": {\n contextWindow: 1_048_576,\n maxOutputTokens: 65_536,\n supportsTools: true,\n supportsVision: false,\n },\n \"mistral/mistral-large-4\": { // supportsTools: not probed — fails closed\n contextWindow: 524_288,\n maxOutputTokens: 262_144,\n supportsTools: false,\n supportsVision: true,\n },\n \"moonshot/kimi-k3\": {\n contextWindow: 1_048_576,\n maxOutputTokens: 65_536,\n supportsTools: true,\n supportsVision: true,\n },\n \"nvidia/llama-3.2-11b-vision\": { // supportsTools: not probed — fails closed\n contextWindow: 128_000,\n maxOutputTokens: 16_384,\n supportsTools: false,\n supportsVision: true,\n },\n \"nvidia/muse-glimmer-30b\": { // supportsTools: not probed — fails closed\n contextWindow: 131_072,\n maxOutputTokens: 16_384,\n supportsTools: false,\n supportsVision: false,\n },\n \"nvidia/nemotron-3-nano-omni-30b-a3b-reasoning\": { // override: The catalog tags this model \"vision\", but a correctly sized probe does not hold up (ClawRouter, 2026-08-31): a 64x64 solid-red PNG was named correctly 1 of 4 times on Base, and on Solana the image was silently dropped and a text model answered \"white\". An HTTP 200 with a confident wrong answer gives the caller nothing to branch on, so image turns must not be routed here. It is ecoTiers.SIMPLE.fallback[0] since nemotron-3-nano-30b was delisted (2026-09-08); remove once a probe of this size comes back right on both chains.\n contextWindow: 256_000,\n maxOutputTokens: 16_384,\n supportsTools: false,\n supportsVision: false,\n },\n \"nvidia/nemotron-3-ultra-550b\": { // supportsTools: not probed — fails closed\n contextWindow: 1_000_000,\n maxOutputTokens: 16_384,\n supportsTools: false,\n supportsVision: false,\n },\n \"nvidia/nemotron-3.5-lightning\": { // supportsTools: not probed — fails closed\n contextWindow: 1_000_000,\n maxOutputTokens: 16_384,\n supportsTools: false,\n supportsVision: false,\n },\n \"openai/chat-latest\": {\n contextWindow: 128_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"openai/gpt-4.1\": {\n contextWindow: 128_000,\n maxOutputTokens: 32_768,\n supportsTools: true,\n supportsVision: true,\n },\n \"openai/gpt-4.1-mini\": {\n contextWindow: 128_000,\n maxOutputTokens: 32_768,\n supportsTools: true,\n supportsVision: false,\n },\n \"openai/gpt-4.1-nano\": {\n contextWindow: 128_000,\n maxOutputTokens: 32_768,\n supportsTools: true,\n supportsVision: false,\n },\n \"openai/gpt-4o\": {\n contextWindow: 128_000,\n maxOutputTokens: 16_384,\n supportsTools: true,\n supportsVision: true,\n },\n \"openai/gpt-4o-mini\": {\n contextWindow: 128_000,\n maxOutputTokens: 16_384,\n supportsTools: true,\n supportsVision: false,\n },\n \"openai/gpt-5-mini\": {\n contextWindow: 200_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: false,\n },\n \"openai/gpt-5.1\": {\n contextWindow: 400_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"openai/gpt-5.2\": {\n contextWindow: 400_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"openai/gpt-5.2-pro\": { // supportsTools: not probed — fails closed\n contextWindow: 400_000,\n maxOutputTokens: 128_000,\n supportsTools: false,\n supportsVision: true,\n },\n \"openai/gpt-5.3-codex\": { // supportsTools: gateway unavailable at probe time — fails closed; override: 2026-08-29 probe: every request (6 plain + 3 tool attempts) returned a gateway 500, so the probe measured an incident, not the model. Codex's function calling is established by the 2026-07 Terminal-Bench / tau2 calibration trajectories in portfolio.ts. Hosts observing the 500s should drop it with RouterOptions.unavailableModels rather than this snapshot claiming the model cannot call tools.\n contextWindow: 400_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: false,\n },\n \"openai/gpt-5.4\": {\n contextWindow: 1_050_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"openai/gpt-5.4-mini\": {\n contextWindow: 400_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"openai/gpt-5.4-nano\": {\n contextWindow: 1_050_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: false,\n },\n \"openai/gpt-5.4-pro\": { // supportsTools: not probed — fails closed\n contextWindow: 1_050_000,\n maxOutputTokens: 128_000,\n supportsTools: false,\n supportsVision: true,\n },\n \"openai/gpt-5.5\": {\n contextWindow: 1_050_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"openai/gpt-5.5-pro\": { // supportsTools: not probed — fails closed\n contextWindow: 1_050_000,\n maxOutputTokens: 128_000,\n supportsTools: false,\n supportsVision: true,\n },\n \"openai/gpt-5.6-luna\": {\n contextWindow: 1_050_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"openai/gpt-5.6-luna-pro\": {\n contextWindow: 1_050_000,\n maxOutputTokens: 128_000,\n supportsTools: false,\n supportsVision: true,\n },\n \"openai/gpt-5.6-sol\": {\n contextWindow: 1_050_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"openai/gpt-5.6-sol-pro\": {\n contextWindow: 1_050_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"openai/gpt-5.6-terra\": {\n contextWindow: 1_050_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"openai/gpt-5.6-terra-pro\": {\n contextWindow: 1_050_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"openai/gpt-6-astra\": {\n contextWindow: 1_050_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"openai/gpt-6-luna\": {\n contextWindow: 1_050_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"openai/gpt-6-sol\": {\n contextWindow: 1_050_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"openai/gpt-6.1-sol\": {\n contextWindow: 1_050_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"openai/o1\": {\n contextWindow: 200_000,\n maxOutputTokens: 100_000,\n supportsTools: true,\n supportsVision: false,\n },\n \"openai/o3\": {\n contextWindow: 200_000,\n maxOutputTokens: 100_000,\n supportsTools: true,\n supportsVision: false,\n },\n \"openai/o3-mini\": {\n contextWindow: 128_000,\n maxOutputTokens: 100_000,\n supportsTools: true,\n supportsVision: false,\n },\n \"openai/o4-mini\": {\n contextWindow: 128_000,\n maxOutputTokens: 100_000,\n supportsTools: true,\n supportsVision: false,\n },\n \"poolside/laguna-s-2.1\": { // supportsTools: not probed — fails closed\n contextWindow: 1_048_576,\n maxOutputTokens: 131_072,\n supportsTools: false,\n supportsVision: false,\n },\n \"poolside/laguna-xs-2.1\": { // supportsTools: not probed — fails closed\n contextWindow: 131_072,\n maxOutputTokens: 16_384,\n supportsTools: false,\n supportsVision: false,\n },\n \"qwen/qwen3.7-flash\": {\n contextWindow: 1_000_000,\n maxOutputTokens: 65_536,\n supportsTools: true,\n supportsVision: false,\n },\n \"qwen/qwen3.7-max\": {\n contextWindow: 1_000_000,\n maxOutputTokens: 65_536,\n supportsTools: true,\n supportsVision: false,\n },\n \"qwen/qwen3.7-plus\": {\n contextWindow: 1_000_000,\n maxOutputTokens: 131_072,\n supportsTools: true,\n supportsVision: false,\n },\n \"qwen/qwen3.8-flash\": {\n contextWindow: 1_000_000,\n maxOutputTokens: 131_072,\n supportsTools: false,\n supportsVision: true,\n },\n \"qwen/qwen3.8-max\": { // supportsTools: not probed — fails closed\n contextWindow: 1_000_000,\n maxOutputTokens: 131_072,\n supportsTools: false,\n supportsVision: false,\n },\n \"tencent/hy4-preview\": { // supportsTools: not probed — fails closed\n contextWindow: 1_048_576,\n maxOutputTokens: 64_000,\n supportsTools: false,\n supportsVision: false,\n },\n \"xai/grok-4.3\": {\n contextWindow: 1_000_000,\n maxOutputTokens: 16_384,\n supportsTools: true,\n supportsVision: true,\n },\n \"xai/grok-4.5\": {\n contextWindow: 500_000,\n maxOutputTokens: 16_384,\n supportsTools: true,\n supportsVision: true,\n },\n \"xai/grok-4.6\": {\n contextWindow: 500_000,\n maxOutputTokens: 16_384,\n supportsTools: true,\n supportsVision: true,\n },\n \"xai/grok-4.7\": {\n contextWindow: 500_000,\n maxOutputTokens: 16_384,\n supportsTools: true,\n supportsVision: true,\n },\n \"xai/grok-build-0.1\": {\n contextWindow: 256_000,\n maxOutputTokens: 16_384,\n supportsTools: true,\n supportsVision: false,\n },\n \"xiaomi/mimo-v2.5\": {\n contextWindow: 1_048_576,\n maxOutputTokens: 131_072,\n supportsTools: true,\n supportsVision: true,\n },\n \"xiaomi/mimo-v2.5-pro\": {\n contextWindow: 1_048_576,\n maxOutputTokens: 131_072,\n supportsTools: true,\n supportsVision: false,\n },\n \"zai/glm-5\": {\n contextWindow: 200_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: false,\n },\n \"zai/glm-5-turbo\": {\n contextWindow: 200_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: false,\n },\n \"zai/glm-5.1\": {\n contextWindow: 200_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: false,\n },\n \"zai/glm-5.2\": {\n contextWindow: 1_000_000,\n maxOutputTokens: 131_072,\n supportsTools: true,\n supportsVision: false,\n },\n \"zai/glm-5.3\": {\n contextWindow: 1_000_000,\n maxOutputTokens: 131_072,\n supportsTools: true,\n supportsVision: false,\n },\n \"zai/glm-5.3-flash\": {\n contextWindow: 1_000_000,\n maxOutputTokens: 131_072,\n supportsTools: true,\n supportsVision: true,\n },\n });\n","{\n \"anthropic/claude-fable-5\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 9298.5,\n \"p95LatencyMs\": 9873.4,\n \"outputTokensPerSecond\": 55.17,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"anthropic/claude-haiku-4.5\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 3157.4,\n \"p95LatencyMs\": 3170.7,\n \"outputTokensPerSecond\": 162.16,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"anthropic/claude-opus-4.5\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 6497.7,\n \"p95LatencyMs\": 6953.7,\n \"outputTokensPerSecond\": 78.99,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"anthropic/claude-opus-4.7\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 5316.5,\n \"p95LatencyMs\": 6121.5,\n \"outputTokensPerSecond\": 97.34,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"anthropic/claude-opus-4.8\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 6216.1,\n \"p95LatencyMs\": 6847.7,\n \"outputTokensPerSecond\": 82.81,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"anthropic/claude-opus-5\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 7309,\n \"p95LatencyMs\": 7745.2,\n \"outputTokensPerSecond\": 70.17,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"anthropic/claude-sonnet-4.5\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 6330.4,\n \"p95LatencyMs\": 6631.6,\n \"outputTokensPerSecond\": 81.03,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"anthropic/claude-sonnet-4.6\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 6508,\n \"p95LatencyMs\": 6698.3,\n \"outputTokensPerSecond\": 78.6,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"anthropic/claude-sonnet-5\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 6165.4,\n \"p95LatencyMs\": 6582.9,\n \"outputTokensPerSecond\": 83.62,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"deepseek/deepseek-chat\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 4351.4,\n \"p95LatencyMs\": 4543.7,\n \"outputTokensPerSecond\": 117.78,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"deepseek/deepseek-reasoner\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 5201.2,\n \"p95LatencyMs\": 6079.6,\n \"outputTokensPerSecond\": 99.77,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"deepseek/deepseek-v4-pro\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 8781.2,\n \"p95LatencyMs\": 9881.1,\n \"outputTokensPerSecond\": 58.98,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"deepseek/deepseek-v4.1-flash\": {\n \"measuredAt\": \"2026-10-20T18:12:51Z\",\n \"latencyMs\": 2383.5,\n \"p95LatencyMs\": 2547.8,\n \"outputTokensPerSecond\": 216.53,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"google/gemini-2.5-flash\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 5416.4,\n \"p95LatencyMs\": 6442.8,\n \"outputTokensPerSecond\": 213.07,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"google/gemini-2.5-flash-lite\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 5002.6,\n \"p95LatencyMs\": 5780.3,\n \"outputTokensPerSecond\": 408.43,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"google/gemini-2.5-pro\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 28169.5,\n \"p95LatencyMs\": 29491.4,\n \"outputTokensPerSecond\": 147.3,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"google/gemini-3-flash-preview\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 4717.1,\n \"p95LatencyMs\": 5037.1,\n \"outputTokensPerSecond\": 198.71,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"google/gemini-3.1-flash-lite\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 2855.8,\n \"p95LatencyMs\": 3172.7,\n \"outputTokensPerSecond\": 286.91,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"google/gemini-3.1-pro\": {\n \"measuredAt\": \"2026-08-29T16:59:54Z\",\n \"latencyMs\": 24194.1,\n \"p95LatencyMs\": 27269.6,\n \"outputTokensPerSecond\": 109.47,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"google/gemini-3.5-flash\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 5320.6,\n \"p95LatencyMs\": 5429.8,\n \"outputTokensPerSecond\": 226.21,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"google/gemini-3.5-flash-lite\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 3515.8,\n \"p95LatencyMs\": 4363.4,\n \"outputTokensPerSecond\": 248.9,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"google/gemini-3.6-flash\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 13020,\n \"p95LatencyMs\": 15383.1,\n \"outputTokensPerSecond\": 187.87,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"minimax/minimax-m2.7\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 8761.1,\n \"p95LatencyMs\": 10199.3,\n \"outputTokensPerSecond\": 59.18,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"minimax/minimax-m3\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 11101.9,\n \"p95LatencyMs\": 26087.1,\n \"outputTokensPerSecond\": 101.12,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"moonshot/kimi-k3\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 24498.9,\n \"p95LatencyMs\": 40365.3,\n \"outputTokensPerSecond\": 25.11,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"nvidia/mistral-nemotron\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 7349.6,\n \"p95LatencyMs\": 9932.3,\n \"outputTokensPerSecond\": 79.48,\n \"errorRate\": 0.3333,\n \"samples\": 3\n },\n \"nvidia/nemotron-3-nano-omni-30b-a3b-reasoning\": {\n \"measuredAt\": \"2026-08-29T16:59:54Z\",\n \"latencyMs\": 9324.6,\n \"p95LatencyMs\": 12992,\n \"outputTokensPerSecond\": 64.96,\n \"errorRate\": 0.3333,\n \"samples\": 3\n },\n \"nvidia/nemotron-nano-12b-v2-vl\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 5846.9,\n \"p95LatencyMs\": 5846.9,\n \"outputTokensPerSecond\": 87.57,\n \"errorRate\": 0.6667,\n \"samples\": 3\n },\n \"nvidia/nemotron-nano-9b-v2\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 5282.5,\n \"p95LatencyMs\": 5282.5,\n \"outputTokensPerSecond\": 96.92,\n \"errorRate\": 0.6667,\n \"samples\": 3\n },\n \"nvidia/step-3.7-flash\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 4617.4,\n \"p95LatencyMs\": 5237.4,\n \"outputTokensPerSecond\": 112.92,\n \"errorRate\": 0.3333,\n \"samples\": 3\n },\n \"openai/chat-latest\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 3690.9,\n \"p95LatencyMs\": 4344,\n \"outputTokensPerSecond\": 111.85,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/gpt-4.1\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 3527.9,\n \"p95LatencyMs\": 3831.7,\n \"outputTokensPerSecond\": 141.27,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/gpt-4.1-mini\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 4268.2,\n \"p95LatencyMs\": 5101.5,\n \"outputTokensPerSecond\": 103.42,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/gpt-4.1-nano\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 3088.3,\n \"p95LatencyMs\": 3369.2,\n \"outputTokensPerSecond\": 150.31,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/gpt-4o\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 2995.2,\n \"p95LatencyMs\": 3174.2,\n \"outputTokensPerSecond\": 171.32,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/gpt-4o-mini\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 4751.5,\n \"p95LatencyMs\": 4930.4,\n \"outputTokensPerSecond\": 107.84,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/gpt-5-mini\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 4558.1,\n \"p95LatencyMs\": 5081.9,\n \"outputTokensPerSecond\": 113.25,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/gpt-5.2\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 5436.6,\n \"p95LatencyMs\": 5928.8,\n \"outputTokensPerSecond\": 95.47,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/gpt-5.3-codex\": {\n \"measuredAt\": \"2026-08-29T16:59:54Z\",\n \"latencyMs\": 15290.4,\n \"p95LatencyMs\": 15290.4,\n \"outputTokensPerSecond\": 33.49,\n \"errorRate\": 0.6667,\n \"samples\": 3\n },\n \"openai/gpt-5.4\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 5596,\n \"p95LatencyMs\": 5919.4,\n \"outputTokensPerSecond\": 91.67,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/gpt-5.4-mini\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 3377.8,\n \"p95LatencyMs\": 3646.8,\n \"outputTokensPerSecond\": 138.08,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/gpt-5.4-nano\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 4040.4,\n \"p95LatencyMs\": 4205.9,\n \"outputTokensPerSecond\": 118.52,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/gpt-5.5\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 6367.8,\n \"p95LatencyMs\": 7330.7,\n \"outputTokensPerSecond\": 81.29,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/gpt-5.6-luna\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 6064.5,\n \"p95LatencyMs\": 7347.3,\n \"outputTokensPerSecond\": 87.93,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/gpt-5.6-luna-pro\": {\n \"measuredAt\": \"2026-08-29T16:59:54Z\",\n \"latencyMs\": 13914.9,\n \"p95LatencyMs\": 13914.9,\n \"outputTokensPerSecond\": 36.79,\n \"errorRate\": 0.6667,\n \"samples\": 3\n },\n \"openai/gpt-5.6-sol\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 7720.2,\n \"p95LatencyMs\": 9108.2,\n \"outputTokensPerSecond\": 67.47,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/gpt-5.6-sol-pro\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 11442.7,\n \"p95LatencyMs\": 13363.1,\n \"outputTokensPerSecond\": 148.75,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/gpt-5.6-terra\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 4941,\n \"p95LatencyMs\": 5095.3,\n \"outputTokensPerSecond\": 103.69,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/gpt-5.6-terra-pro\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 3574.1,\n \"p95LatencyMs\": 4126.3,\n \"outputTokensPerSecond\": 133.59,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/gpt-6.1-sol\": {\n \"measuredAt\": \"2026-10-20T18:12:51Z\",\n \"latencyMs\": 11324,\n \"p95LatencyMs\": 12747.6,\n \"outputTokensPerSecond\": 45.11,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/o1\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 4324.9,\n \"p95LatencyMs\": 5838.1,\n \"outputTokensPerSecond\": 125.86,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/o3\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 5463.4,\n \"p95LatencyMs\": 5613.1,\n \"outputTokensPerSecond\": 93.8,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/o3-mini\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 2912.7,\n \"p95LatencyMs\": 3092.1,\n \"outputTokensPerSecond\": 176.49,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/o4-mini\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 4958.7,\n \"p95LatencyMs\": 5313,\n \"outputTokensPerSecond\": 103.81,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"qwen/qwen3.7-flash\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 3385.5,\n \"p95LatencyMs\": 4042.7,\n \"outputTokensPerSecond\": 153.94,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"qwen/qwen3.7-max\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 9387.1,\n \"p95LatencyMs\": 10490.2,\n \"outputTokensPerSecond\": 54.92,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"qwen/qwen3.7-plus\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 9766.6,\n \"p95LatencyMs\": 9798.2,\n \"outputTokensPerSecond\": 52.42,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"tencent/hy3\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 6062.3,\n \"p95LatencyMs\": 7070.2,\n \"outputTokensPerSecond\": 87.3,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"xai/grok-4.3\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 9467.7,\n \"p95LatencyMs\": 10087.9,\n \"outputTokensPerSecond\": 48.36,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"xai/grok-4.5\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 13564.8,\n \"p95LatencyMs\": 17351.9,\n \"outputTokensPerSecond\": 60.71,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"xai/grok-build-0.1\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 16394.8,\n \"p95LatencyMs\": 18035.4,\n \"outputTokensPerSecond\": 96.86,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"xiaomi/mimo-v2.5-pro\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 12070.7,\n \"p95LatencyMs\": 12386.8,\n \"outputTokensPerSecond\": 42.44,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"zai/glm-5\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 6839.7,\n \"p95LatencyMs\": 7261.4,\n \"outputTokensPerSecond\": 75.16,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"zai/glm-5-turbo\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 55348.5,\n \"p95LatencyMs\": 114086.6,\n \"outputTokensPerSecond\": 14.64,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"zai/glm-5.1\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 15658.4,\n \"p95LatencyMs\": 17307.1,\n \"outputTokensPerSecond\": 32.9,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"zai/glm-5.2\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 10308.5,\n \"p95LatencyMs\": 15127.6,\n \"outputTokensPerSecond\": 54.87,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"zai/glm-5.3\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 7272.4,\n \"p95LatencyMs\": 7998.1,\n \"outputTokensPerSecond\": 71.09,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"zai/glm-5.3-flash\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 10545.3,\n \"p95LatencyMs\": 11672.4,\n \"outputTokensPerSecond\": 49.01,\n \"errorRate\": 0,\n \"samples\": 3\n }\n}\n","/**\n * Model-performance priors consumed by the portfolio router.\n *\n * The entries below are a small, auditable seed extracted from the 2026-03-16\n * BlockRun performance run. They are deliberately weak priors: live data\n * injected by the host should replace them through configuration before a\n * release. Historical numbers must never be presented as a current\n * provider SLA or as task-quality measurements.\n */\n\nimport liveProfiles from \"./model-profiles.generated.json\";\n\nexport type ModelPerformanceProfile = {\n measuredAt: string;\n /** Gateway end-to-end latency for the benchmark workload. */\n latencyMs: number;\n /** Tail latency is more relevant than mean latency for urgent requests. */\n p95LatencyMs?: number;\n outputTokensPerSecond: number;\n /** External intelligence index when one was available; not task success. */\n intelligenceIndex?: number;\n /** Failure fraction observed in the same benchmark run. */\n errorRate?: number;\n /** Number of sampled calls behind the observation. */\n samples?: number;\n};\n\n// Generated from benchmark files that satisfy the uncached-inference\n// invariant. These are weak performance priors (speed/reliability), never\n// task-quality labels.\nexport const LIVE_MODEL_PROFILES: Readonly> = Object.freeze(\n liveProfiles as Record,\n);\n\nexport const HISTORICAL_MODEL_PROFILES: Readonly> =\n Object.freeze({\n \"anthropic/claude-haiku-4.5\": {\n measuredAt: \"2026-03-16T13:50:48Z\",\n latencyMs: 2305,\n outputTokensPerSecond: 140.6,\n },\n \"anthropic/claude-sonnet-4.6\": {\n measuredAt: \"2026-03-16T13:50:48Z\",\n latencyMs: 2110,\n outputTokensPerSecond: 121.3,\n },\n \"deepseek/deepseek-chat\": {\n measuredAt: \"2026-03-16T13:50:48Z\",\n latencyMs: 1431,\n outputTokensPerSecond: 179.2,\n intelligenceIndex: 32,\n },\n \"google/gemini-2.5-flash\": {\n measuredAt: \"2026-03-16T13:50:48Z\",\n latencyMs: 1238,\n outputTokensPerSecond: 207.6,\n intelligenceIndex: 20,\n },\n \"google/gemini-2.5-flash-lite\": {\n measuredAt: \"2026-03-16T13:50:48Z\",\n latencyMs: 1353,\n outputTokensPerSecond: 192.5,\n intelligenceIndex: 20,\n },\n \"google/gemini-2.5-pro\": {\n measuredAt: \"2026-03-16T13:50:48Z\",\n latencyMs: 1294,\n outputTokensPerSecond: 197.8,\n },\n \"google/gemini-3.1-pro\": {\n measuredAt: \"2026-03-16T13:50:48Z\",\n latencyMs: 1609,\n outputTokensPerSecond: 167.2,\n },\n \"openai/gpt-4o-mini\": {\n measuredAt: \"2026-03-16T13:50:48Z\",\n latencyMs: 2764,\n outputTokensPerSecond: 92.8,\n },\n \"openai/gpt-5.3-codex\": {\n measuredAt: \"2026-03-16T13:50:48Z\",\n latencyMs: 7935,\n outputTokensPerSecond: 32.3,\n },\n });\n","/**\n * Whether the request actually requires an external action/tool, as distinct\n * from merely being sent by a host that exposes tools on every turn.\n *\n * The detector intentionally looks for action+target pairs. A generic factual\n * or multiple-choice question must stay false even when the host attaches a\n * large tool schema; otherwise every tool-enabled host turn is over-routed as\n * an agent task and models may browse or mutate state unnecessarily.\n */\nexport function inferToolRequirement(\n prompt: string,\n _systemPrompt?: string,\n toolChoice?: unknown,\n): boolean {\n // OpenAI-compatible clients can state this requirement directly. Treat that\n // protocol signal as authoritative instead of trying to infer it from prose.\n if (toolChoice === \"none\") return false;\n if (toolChoice === \"required\") return true;\n if (\n typeof toolChoice === \"object\" &&\n toolChoice !== null &&\n (toolChoice as { type?: unknown }).type === \"function\"\n ) {\n return true;\n }\n\n // System prompts commonly describe every tool a host exposes. They are not\n // evidence that the user asked to perform an action on this turn. Explicit\n // host requirements should use tool_choice/requiresTools instead.\n const text = prompt;\n const explicitTool =\n /\\b(?:use|call|invoke)\\s+(?:the\\s+)?[\\w.-]+\\s+(?:tool|function|api)\\b|\\btool[_ -]?call\\b|使用.{0,20}(?:工具|函数|接口)|调用.{0,20}(?:工具|函数|接口)/i;\n const codeEnvironment =\n /\\b(?:run|execute)\\s+(?:the\\s+)?(?:tests?|command|script|build|linter)|\\b(?:edit|modify|patch|create|write|save|delete|rename|move|inspect|read)\\b.{0,60}\\b(?:file|repository|repo|codebase|directory|folder)\\b|\\b(?:terminal|shell|bash|zsh|pytest|npm test|pnpm test|git\\s+(?:status|diff|commit)|docker)\\b|(?:运行|执行).{0,20}(?:测试|命令|脚本|构建)|(?:修改|编辑|修复|创建|读取|检查|保存).{0,30}(?:文件|仓库|代码库|目录)/i;\n const webAction =\n /\\b(?:browse|search|look up|fetch|open)\\b.{0,80}\\b(?:web|website|url|online|documentation|docs|news|weather|price)\\b|(?:浏览|搜索|查询|打开).{0,30}(?:网页|网站|链接|文档|新闻|天气|价格)/i;\n const statefulAction =\n /\\b(?:refund|cancel|book|reserve|purchase|buy|return|exchange|transfer|update|change)\\b.{0,80}\\b(?:order|booking|reservation|account|address|payment|subscription|ticket|flight|item)\\b|(?:退款|取消|预订|购买|退货|换货|转账|更新|修改).{0,30}(?:订单|预订|账户|地址|付款|订阅|票|航班|商品)/i;\n return (\n explicitTool.test(text) ||\n codeEnvironment.test(text) ||\n webAction.test(text) ||\n statefulAction.test(text)\n );\n}\n","/**\n * V3 portfolio router.\n *\n * This is deliberately local and deterministic: feature extraction, eligibility\n * checks and scoring read only request data plus the in-process model registry.\n * It is therefore safe for the hot path and provides a stable baseline for the\n * RouterBench evaluation before health telemetry / an optional judge are added.\n */\n\nimport { DEFAULT_MODEL_CAPABILITIES } from \"./model-capabilities.js\";\nimport { getFallbackChain, selectModel } from \"./selector.js\";\nimport { RulesStrategy } from \"./strategy.js\";\nimport {\n HISTORICAL_MODEL_PROFILES,\n LIVE_MODEL_PROFILES,\n type ModelPerformanceProfile,\n} from \"./model-profiles.js\";\nimport type { RouterOptions, RouterStrategy, TaskType, Tier, TierConfig } from \"./types.js\";\nimport { inferToolRequirement } from \"./tool-intent.js\";\nimport { estimateTokens, sampleForScan, scanLimit } from \"./tokens.js\";\n\ntype TaskFeatures = {\n taskType: TaskType;\n estimatedInputTokens: number;\n hasCode: boolean;\n needsTools: boolean;\n toolsAvailable: boolean;\n needsVision: boolean;\n needsStructuredOutput: boolean;\n latencySensitive: boolean;\n highStakes: boolean;\n language: \"zh\" | \"other\";\n likelyParallelToolCalls: boolean;\n complexMultiToolPlan: boolean;\n agentDomain: \"airline\" | \"retail\" | \"web_research\" | \"other\";\n deepWebResearch: boolean;\n agentRisk: \"standard\" | \"high\" | \"complex_high\" | \"policy_exception_simple\" | \"policy_exception\";\n terminalToolSignal: boolean;\n terminalSafetySensitive: boolean;\n implicitTerminalCode: boolean;\n /** A code artifact or coding action is present, not merely a language name. */\n codeArtifact: boolean;\n};\n\nconst DEFAULT_PORTFOLIO_WEIGHTS = {\n auto: {\n quality: 0.47,\n capability: 0.2,\n cost: 0.18,\n speed: 0.07,\n reliability: 0.03,\n legacy: 0.05,\n },\n eco: { quality: 0.36, capability: 0.2, cost: 0.28, speed: 0.1, reliability: 0.04, legacy: 0.02 },\n premium: {\n quality: 0.58,\n capability: 0.2,\n cost: 0.08,\n speed: 0.06,\n reliability: 0.06,\n legacy: 0.02,\n },\n highStakesBoost: { quality: 0.08, reliability: 0.05 },\n latencySensitiveSpeedBoost: 0.08,\n affinityFloorGap: { auto: 0.1, eco: 0.22, premium: 0.05 },\n} as const;\n\n/**\n * Detect turns that probably need several tool calls. This is a\n * deliberately conservative request-side feature: it uses only the prompt\n * and visible tool count, never benchmark categories or expected answers.\n */\nfunction likelyNeedsParallelToolCalls(\n prompt: string,\n needsTools: boolean,\n toolCount: number | undefined,\n toolNames: readonly string[] | undefined,\n): boolean {\n if (!needsTools || toolCount === undefined || toolCount < 1) return false;\n const text = prompt.trim();\n const explicitRepeat =\n /\\b(?:in parallel|simultaneously|concurrently|for each|each of|every one|both|(?:two|three|multiple|several)\\s+(?:cities|locations|items|tasks|orders|users|files))\\b|并行|同时|分别|每个|各自|(?:两个|三个|多个)(?:城市|地点|项目|任务|订单|用户|文件)|cada uno|para cada|simult[aá]neamente/i.test(\n text,\n );\n if (explicitRepeat) return true;\n\n const sentenceClauses = text\n .split(/[.!?。!?]+/)\n .map((part) => part.trim())\n .filter((part) => part.length >= 8);\n if (\n (/\\b(?:also|additionally|furthermore)\\b|另外|此外|그리고/i.test(text) &&\n sentenceClauses.length >= 2) ||\n /\\band\\s+(?:also|for the)\\b/i.test(text)\n )\n return true;\n\n const pairedQuantity =\n /\\b\\d+(?:\\.\\d+)?\\s+(?:and|or)\\s+\\d+(?:\\.\\d+)?\\s*(?:gb|mb|tb|kg|g|ml|oz|cups?|cores?|cpus?)\\b/i.test(\n text,\n );\n if (pairedQuantity) return true;\n\n // Distinctive tokens from two visible tool names are a strong local signal\n // for a multi-operation turn (for example add_task + delete_task).\n const operationTokens = new Set([\n \"add\",\n \"delete\",\n \"remove\",\n \"cancel\",\n \"return\",\n \"exchange\",\n \"modify\",\n \"book\",\n \"transfer\",\n \"send\",\n \"upload\",\n \"download\",\n \"create\",\n \"close\",\n ]);\n const lowered = text.toLowerCase();\n const matchedOperationTokens = new Set(\n (toolNames ?? [])\n .flatMap((name) => name.toLowerCase().split(/[^a-z0-9\\u3400-\\u9fff]+/))\n .filter((token) => operationTokens.has(token) && lowered.includes(token)),\n );\n // A single workflow naturally mentions domain nouns like order/item plus\n // one action. Upgrade only when two different visible operation verbs are\n // requested (for example cancel + book or add + delete).\n if (matchedOperationTokens.size >= 2) return true;\n\n // Repeated food/logging entries are commonly expressed as several lines,\n // each with its own quantity rather than an explicit \"for each\" phrase.\n const nonEmptyLines = text\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter(Boolean);\n const quantityMentions =\n text.match(\n /\\b(?:\\d+(?:\\.\\d+)?|one|two|three|four|five|six|seven|eight|nine|ten)\\s*(?:oz|ounce|ounces|g|gram|grams|kg|ml|cups?|pieces?|tablespoons?)\\b/gi,\n ) ?? [];\n if (nonEmptyLines.length >= 2 && quantityMentions.length >= 2) return true;\n\n // Weather prompts provide a useful language-independent high-confidence\n // pattern: a single lookup tool plus multiple locations joined in one turn.\n const repeatedLookup =\n /\\b(?:weather|climate|clima|tiempo|temperature|snow|news|report)\\b|天气|气象|温度|降雪|新闻|报告/i.test(\n text,\n );\n const multiLocationConnector = /\\b(?:and also|both|y|e)\\b|还有|以及|和|、/i.test(text);\n const commaSeparatedLocations = (text.match(/[,,]/g) ?? []).length >= 2;\n if (repeatedLookup && (multiLocationConnector || commaSeparatedLocations)) return true;\n\n const distinctOrderParts =\n /\\b(?:food|meal)\\b[\\s\\S]*\\bdrink\\b|\\bdrink\\b[\\s\\S]*\\b(?:food|meal)\\b/i.test(text);\n const koreanParallelClauses = (text.match(/,/g) ?? []).length >= 3 && /하고|그리고/.test(text);\n return distinctOrderParts || koreanParallelClauses;\n}\n\nfunction classifyTask(\n prompt: string,\n systemPrompt: string | undefined,\n options: RouterOptions,\n): TaskFeatures {\n const fullText = `${systemPrompt ?? \"\"} ${prompt}`;\n const estimatedInputTokens = estimateTokens(fullText);\n const limit = scanLimit(options.config.classifier.promptTruncationChars);\n const scannedPrompt = sampleForScan(prompt, limit);\n const scannedSystemPrompt = sampleForScan(systemPrompt ?? \"\", limit);\n // Only the deep-web-research clue detectors below read the system prompt,\n // and they are gated on a web-research tool surface. Every other feature\n // reads the user turn: a host's standing instructions (\"be quick\", \"follow\n // security best practices\", a Mandarin persona) describe the assistant, not\n // this request, and must not move its scoring or language band.\n const scannedFullText = `${scannedSystemPrompt} ${scannedPrompt}`;\n const text = scannedPrompt.toLowerCase();\n const explicitCodeSignal =\n /```|\\b(?:typescript|javascript|python|rust|java|sql|stack trace|traceback|exception)\\b|\\.(?:ts|tsx|js|py|go|rs)\\b/i.test(\n scannedPrompt,\n );\n // `class` is common in non-code Agent domains (for example airline cabin\n // class). Treat code constructs as code only when the prompt also contains\n // an implementation/editing cue, instead of letting a single ambiguous\n // noun redirect an entire tool session to the code-agent portfolio.\n const codeConstructSignal =\n /\\b(?:implement|refactor|debug|write|edit|modify|create|define|review|fix)\\b[\\s\\S]{0,48}\\b(?:api|function|class|method)\\b|\\b(?:api|function|class|method)\\b[\\s\\S]{0,48}\\b(?:code|implementation|typescript|javascript|python|rust|java)\\b/i.test(\n scannedPrompt,\n );\n const nativeCodeSignal =\n /\\b(?:programmed|written|implemented?|code)\\s+(?:in|using)\\s+(?:c\\+\\+|c|rust|go)\\b/i.test(\n scannedPrompt,\n );\n // A CamelCase error class (TypeError, NullPointerException) is a runtime\n // artifact, not prose about errors; case-sensitive on purpose.\n const errorClassSignal = /\\b[A-Z][A-Za-z]*(?:Error|Exception)\\b/.test(scannedPrompt);\n const hasCode = explicitCodeSignal || codeConstructSignal || nativeCodeSignal || errorClassSignal;\n // Stronger than hasCode: an actual code artifact or coding action, never a\n // bare language name (\"What is Python?\" is trivia, not a code task) and\n // never the English word \"exception\" on its own (\"please make an\n // exception\"); a thrown exception shows up as a CamelCase class above.\n const codeArtifact =\n /```|\\b(?:stack trace|traceback)\\b|\\.(?:ts|tsx|js|py|go|rs)\\b/i.test(scannedPrompt) ||\n codeConstructSignal ||\n nativeCodeSignal ||\n errorClassSignal;\n const toolsAvailable = options.hasTools ?? false;\n const needsTools =\n options.requiresTools ??\n (toolsAvailable && inferToolRequirement(scannedPrompt, scannedSystemPrompt));\n const likelyParallelToolCalls = likelyNeedsParallelToolCalls(\n scannedPrompt,\n needsTools,\n options.toolCount,\n options.toolNames,\n );\n const normalizedToolNames = (options.toolNames ?? []).map((name) => name.toLowerCase());\n const airlineToolSignal = normalizedToolNames.some((name) =>\n /(?:flight|reservation|airport|baggage|passenger)/.test(name),\n );\n const retailToolSignal = normalizedToolNames.some((name) =>\n /(?:order|product|item|return|exchange|address)/.test(name),\n );\n const webResearchToolSignal = normalizedToolNames.some((name) =>\n /^(?:web_?search|web_?fetch)$/.test(name),\n );\n const agentDomain =\n airlineToolSignal && !retailToolSignal\n ? \"airline\"\n : retailToolSignal && !airlineToolSignal\n ? \"retail\"\n : webResearchToolSignal\n ? \"web_research\"\n : \"other\";\n // Distinguish a cheap lookup from a BrowseComp-like investigation. These\n // prompts require joining several clues, resolving an entity, and ending in\n // one exact answer; complete agent trajectories show that treating them as\n // ordinary search causes long, costly loops. This is request/tool-surface\n // evidence only and does not depend on a benchmark id or hidden answer.\n const clueConnectors =\n scannedFullText.match(\n /\\b(?:after|before|while|where|whose|which|in \\d{4}|as of|over \\d+|another|also|furthermore)\\b|(?:之后|之前|其中|截至|超过|另一个|此外)/gi,\n ) ?? [];\n const entityResolutionSignal =\n /\\b(?:identify|who (?:is|was)|what (?:is|was) the name|which (?:person|player|company|country|city)|find the (?:person|player|name|entity))\\b|(?:找出|识别|是谁|哪位|名称是什么)/i.test(\n scannedFullText,\n );\n const exactAnswerSignal =\n /\\b(?:exact answer|single best-supported answer|following clues|multiple public sources)\\b|(?:精确答案|根据.*线索|多个公开来源)/i.test(\n scannedFullText,\n );\n const deepWebResearch =\n agentDomain === \"web_research\" &&\n (exactAnswerSignal ||\n (entityResolutionSignal && (clueConnectors.length >= 3 || prompt.length >= 320)));\n const globalOptimizationSignal =\n /\\b(?:cheapest|lowest[- ]price|least expensive|most expensive|highest(?:[- ]priced)?|largest|smallest|maximum|minimum|best available|closest|not (?:cost|exceed))\\b|最便宜|最低价|最贵|最高价|最大|最小/i.test(\n scannedPrompt,\n );\n const globalScopeSignal =\n /\\b(?:everything|all (?:(?:my|your|their|the) )?(?:future |upcoming )?(?:items|orders|passengers|flights|reservations|bookings)|every (?:item|order|passenger|flight|reservation|booking))\\b|全部|所有|每个/i.test(\n scannedPrompt,\n );\n const globalChoiceSignal = globalOptimizationSignal || globalScopeSignal;\n const crossRecordSignal =\n /\\b(?:another|other|different|previous)\\s+(?:order|reservation|booking|account|address)\\b|另一(?:个)?(?:订单|预订|账户|地址)|其他(?:订单|预订|账户|地址)/i.test(\n scannedPrompt,\n );\n const reservationIds = scannedPrompt.match(/\\b[A-Z0-9]{6}\\b/g) ?? [];\n const crossReservationBatchSignal =\n agentDomain === \"airline\" &&\n (/\\b(?:two|three|multiple|several)(?:\\s+of\\s+(?:my|our|the))?\\s+(?:upcoming\\s+)?(?:reservations?|bookings?)\\b|\\b(?:a\\s+)?(?:second|third)\\s+(?:reservation|booking)\\b/i.test(\n scannedPrompt,\n ) ||\n new Set(reservationIds).size >= 2);\n const conditionalGlobalWorkflowSignal =\n agentDomain === \"airline\" &&\n globalScopeSignal &&\n /\\b(?:if|that (?:contain|have)|longer than|shorter than|under|over|at (?:most|least)|wherever possible)\\b|如果|超过|少于|不超过|尽可能/i.test(\n scannedPrompt,\n ) &&\n /\\b(?:cancel|change|upgrade|move|book)\\b[\\s\\S]*\\b(?:cancel|change|upgrade|move|book)\\b|取消[\\s\\S]*(?:升级|更改)|升级[\\s\\S]*(?:取消|更改)/i.test(\n scannedPrompt,\n );\n // A refund explicitly targeted at a named/non-original card can conflict\n // with account state and require escalation rather than a substitute action.\n // This narrow feature is visible on the first turn and avoids sending every\n // ordinary return workflow to the expensive policy specialist.\n const policyExceptionSignal =\n agentDomain === \"retail\" &&\n /\\b(?:return|refund|send back|get (?:my |the )?money back)\\b|退货|退款|退回/i.test(\n scannedPrompt,\n ) &&\n /\\b(?:amex|american express|visa|mastercard|credit card|debit card|different card|another card|other card)\\b|信用卡|借记卡|其他卡|另一张卡/i.test(\n scannedPrompt,\n );\n // A comparative selector can mention two products while requesting only\n // one write (for example \"send back the pricier one\"). Three-repeat tau2\n // calibration found no quality gain from the policy specialist on these\n // single-write cases, so keep them in a distinct, lower-cost risk band.\n const singleSelectedPolicyException =\n policyExceptionSignal &&\n /\\b(?:return|refund|send back)\\b[^.!?。!?]{0,96}\\b(?:the )?(?:pricier|cheaper|more expensive|less expensive|costlier|one)\\b/i.test(\n scannedPrompt,\n );\n // Returns and exchanges often pivot after confirmation (return -> rethink\n // -> exchange -> choose a variant). That future state is not visible to a\n // task-start router, so treat the observable workflow verb as the risk cue.\n // Simpler cancellation and one-field order edits stay on the standard path.\n const negotiatedWorkflowSignal =\n agentDomain === \"retail\" && /\\b(?:return|exchange)\\b|退货|退回|换货|交换/i.test(scannedPrompt);\n const numberedSteps = (scannedPrompt.match(/(?:^|\\s)\\d+(?:\\.\\d+)*[.)]\\s+/g) ?? []).length;\n const complexMultiToolPlan =\n likelyParallelToolCalls &&\n ((options.toolCount ?? 0) >= 6 || numberedSteps >= 3 || prompt.length > 1_200);\n let agentRisk: TaskFeatures[\"agentRisk\"] =\n needsTools && singleSelectedPolicyException\n ? \"policy_exception_simple\"\n : needsTools && policyExceptionSignal\n ? \"policy_exception\"\n : // Airline prompts that require a global optimum (for example the\n // cheapest itinerary across several candidates) are materially harder\n // than applying one change to every passenger in a known reservation.\n // Full-session evidence supports Sonnet for the former, while upgrading\n // the latter merely because it says \"all passengers\" caused a large cost\n // increase without a quality gain.\n needsTools &&\n agentDomain === \"airline\" &&\n (globalOptimizationSignal || conditionalGlobalWorkflowSignal)\n ? \"complex_high\"\n : needsTools &&\n (likelyParallelToolCalls ||\n globalChoiceSignal ||\n crossRecordSignal ||\n crossReservationBatchSignal ||\n negotiatedWorkflowSignal)\n ? \"high\"\n : \"standard\";\n const needsVision = options.hasVision ?? false;\n const needsStructuredOutput = options.requiresStructuredOutput ?? false;\n const latencySensitive =\n /\\b(?:urgent|asap|fast|quick|low latency|real[- ]time)\\b|尽快|马上|快速|低延迟/i.test(\n scannedPrompt,\n );\n const highStakes =\n /\\b(?:production|security|payment|legal|medical|financial|audit)\\b|生产|安全|支付|法律|医疗|财务|审计/i.test(\n scannedPrompt,\n );\n // Terminal tasks often describe the desired artifact rather than naming a\n // programming language. Treat only small, deterministic local build/file\n // work as implicit code. Operational deployment, credentials, destructive\n // work, evaluation, vision, and broad search stay on the stronger generic\n // tool-agent path. This is a request-side feature, not a benchmark ID list.\n const terminalToolSignal = normalizedToolNames.some((name) =>\n /^(?:terminalexec|terminalinspect|terminalsendkeys)$/.test(name),\n );\n const simpleTerminalArtifact =\n /\\b(?:create|write|convert|generate|build|implement|run|fix|repair|debug|make)\\b[\\s\\S]{0,120}\\b(?:file|script|csv|parquet|json|txt|server|endpoint)\\b/i.test(\n scannedPrompt,\n );\n // Multi-file repair is qualitatively different from fixing one known local\n // script. The agent must preserve state across inspections, infer ordering\n // and dependencies, edit several artifacts, and close the loop with tests.\n // A frozen Terminal-Bench trajectory showed the economy model spending 27\n // turns repeatedly rereading files without making an edit, while Opus solved\n // the same task in eight turns. Promote this request-visible pattern before\n // model scoring; no benchmark ID or expected answer is consulted.\n const terminalComplexRepair =\n terminalToolSignal &&\n /\\b(?:multiple|several)\\s+(?:scripts?|files?|components?)\\b|\\b(?:pipeline|dependencies)\\b[\\s\\S]{0,100}\\b(?:fail|issue|fix|repair|run|execute)\\b|\\b(?:identify|find|fix|repair)\\s+(?:and\\s+)?(?:fix\\s+)?all\\s+(?:the\\s+)?issues\\b/i.test(\n scannedPrompt,\n );\n // One artifact that must be accepted by multiple compilers/runtimes is not\n // a routine file-writing task. It requires reasoning across incompatible\n // grammars and validating every execution path; cheap code models can\n // produce plausible-looking source that satisfies neither toolchain.\n const mentionedTerminalRuntimes = new Set(\n (scannedPrompt.match(/\\b(?:gcc|clang|rustc|javac|go\\s+build|node|python)\\b/gi) ?? []).map(\n (name) => name.toLowerCase().replace(/\\s+/g, \" \"),\n ),\n );\n const terminalCrossRuntimeArtifact =\n terminalToolSignal &&\n (/\\bpolyglot\\b/i.test(scannedPrompt) ||\n /\\b(?:both|each)\\b[\\s\\S]{0,120}\\b(?:compilers?|runtimes?|toolchains?)\\b/i.test(\n scannedPrompt,\n ) ||\n (mentionedTerminalRuntimes.size >= 2 &&\n /\\b(?:compile|build|run|execute)\\b/i.test(scannedPrompt)));\n // Framework-to-native ports combine binary checkpoint inspection, weight\n // export, tensor-layout reasoning, image/data decoding, and a separately\n // compiled runtime. A task-start router can see this boundary directly in\n // the request (for example PyTorch state_dict -> a pure C CLI); treating it\n // like routine single-file C work caused a 30-turn read/retry loop in a\n // frozen official Terminal-Bench trajectory.\n const terminalFrameworkToNativeArtifact =\n terminalToolSignal &&\n /\\b(?:pytorch|tensorflow|jax|onnx|state[_ -]?dict|checkpoint|safetensors?)\\b|\\.(?:pth|pt|onnx)\\b/i.test(\n scannedPrompt,\n ) &&\n /\\b(?:pure|native|programmed|written|implemented?)\\s+(?:in|using)\\s+(?:c\\+\\+|c|rust|go)\\b|\\b(?:c\\+\\+|c|rust|go)\\s+(?:program|binary|executable|cli|tool|implementation)\\b/i.test(\n scannedPrompt,\n ) &&\n /\\b(?:inference|model|weights?|tensor|export|convert|load)\\b/i.test(scannedPrompt);\n if (\n needsTools &&\n (terminalComplexRepair || terminalCrossRuntimeArtifact || terminalFrameworkToNativeArtifact) &&\n (agentRisk === \"standard\" || agentRisk === \"high\")\n )\n agentRisk = \"complex_high\";\n const complexTerminalOperation =\n /\\b(?:git|ssh|nginx|https|certificate|authentication|credential|deploy|production|encrypt|gpg|shred|securely delete|decommission|benchmark|evaluate|embedding|chess|image|search the web|schema|statistical|statistics|aggregate|join|multiple inputs?)\\b/i.test(\n scannedPrompt,\n );\n // A bare \"token\" is not a credential signal: blockchain, tokenizer, and\n // LLM tasks use that word routinely (for example \"token transfers\"). Only\n // treat it as sensitive when the prompt gives it an authentication/secret\n // qualifier. API keys remain an unambiguous high-risk signal on their own.\n const terminalCredentialSignal =\n /\\b(?:ssh|nginx|certificate|authentication|credentials?|passwords?|api keys?|deploy|production|encrypt|gpg|shred|securely delete|decommission)\\b/i.test(\n scannedPrompt,\n ) ||\n /\\b(?:access|auth|authentication|bearer|secret|api)\\s+tokens?\\b|\\btokens?\\s+(?:secret|credential|authentication)\\b/i.test(\n scannedPrompt,\n );\n const terminalSafetySensitive = terminalToolSignal && (highStakes || terminalCredentialSignal);\n const implicitTerminalCode =\n needsTools &&\n terminalToolSignal &&\n agentRisk === \"standard\" &&\n !highStakes &&\n !complexTerminalOperation &&\n numberedSteps < 3 &&\n prompt.length <= 1_000 &&\n simpleTerminalArtifact;\n const language = /[\\u3400-\\u9fff]/.test(scannedPrompt) ? \"zh\" : \"other\";\n const multipleChoiceSignals = (scannedPrompt.match(/(?:^|\\n)\\s*[A-D][.)]\\s+/gim) ?? []).length;\n const numericSignals = (scannedPrompt.match(/-?\\d+(?:[.,]\\d+)?/g) ?? []).length;\n const compactMathProblem =\n !hasCode &&\n prompt.length < 2_500 &&\n numericSignals >= 2 &&\n (/[+×÷=%$€£¥]|\\b(?:total|each|per|times|half|twice|percent|how many|how much|calculate)\\b/i.test(\n scannedPrompt,\n ) ||\n /[??]\\s*$/.test(scannedPrompt.trim()) ||\n numericSignals >= 3);\n\n let taskType: TaskType = \"chat\";\n if (needsVision) taskType = \"vision\";\n else if (estimatedInputTokens > 80_000) taskType = \"long_context\";\n else if (needsTools && (hasCode || implicitTerminalCode)) taskType = \"code_agent\";\n else if (needsTools && likelyParallelToolCalls && !complexMultiToolPlan)\n taskType = \"tool_agent_parallel\";\n else if (needsTools) taskType = \"tool_agent\";\n else if (multipleChoiceSignals >= 3) taskType = \"reasoning_mcq\";\n else if (compactMathProblem) taskType = \"reasoning_math\";\n else if (\n errorClassSignal ||\n /\\b(?:bug|debug|error|failure|failing|regression|crash|修复|报错|错误|调试)\\b/i.test(text)\n )\n taskType = \"debug\";\n else if (hasCode || /\\b(?:refactor|implement|patch|edit|rewrite|重构|实现|修改)\\b/i.test(text))\n taskType = \"code_edit\";\n else if (needsStructuredOutput || /\\b(?:extract|json|schema|csv|字段|提取)\\b/i.test(text))\n taskType = \"extraction\";\n else if (\n /\\b(?:prove|derive|theorem|formal|mathematical|reasoning|证明|推导|定理|数学)\\b/i.test(text)\n )\n taskType = \"reasoning\";\n\n return {\n taskType,\n estimatedInputTokens,\n hasCode,\n needsTools,\n toolsAvailable,\n needsVision,\n needsStructuredOutput,\n latencySensitive,\n highStakes,\n language,\n likelyParallelToolCalls,\n complexMultiToolPlan,\n agentDomain,\n deepWebResearch,\n agentRisk,\n terminalToolSignal,\n terminalSafetySensitive,\n implicitTerminalCode,\n codeArtifact,\n };\n}\n\nfunction affinity(\n modelId: string,\n task: TaskType,\n language: TaskFeatures[\"language\"] = \"other\",\n agentDomain: TaskFeatures[\"agentDomain\"] = \"other\",\n deepWebResearch = false,\n agentRisk: TaskFeatures[\"agentRisk\"] = \"standard\",\n terminalToolSignal = false,\n terminalSafetySensitive = false,\n): number {\n const id = modelId.toLowerCase();\n // Model family names are intentionally similar (for example\n // `gemini-2.5-flash` vs `gemini-2.5-flash-lite`). A substring match lets a\n // smaller sibling inherit a capability claim that was measured only for the\n // flagship. Keep these assignments model-exact; a sibling can be added only\n // with its own evidence.\n const modelName = id.slice(id.indexOf(\"/\") + 1);\n const match = (values: string[], score: number) =>\n values.some((value) => modelName === value) ? score : 0;\n const base = 0.68;\n\n switch (task) {\n case \"code_agent\":\n if (terminalToolSignal && agentRisk === \"complex_high\") {\n // Strong native tool loop until the Responses function-output fix is\n // deployed on both gateways; keep Codex available below the floor.\n return Math.max(\n base,\n match([\"claude-sonnet-5\"], 1),\n match([\"gpt-5.3-codex\"], 0.87),\n match([\"gpt-5-mini\"], 0.78),\n match([\"gemini-3.5-flash\"], 0.76),\n );\n }\n // Seven valid full agent + official Terminal-Bench trajectories\n // (2026-07-28) gave GPT-5 Mini 4/7 resolved tasks versus 1/7 for the\n // prior dynamic code-agent choice. Its token-normalized total cost was\n // higher in this small calibration, so keep Codex and Sonnet's quality\n // priors above it; admitting Mini to the scoring band lets the normal\n // quality/cost profile choose it without erasing stronger fallbacks.\n // DeepSeek V4 Pro is kept below the primary band after two consecutive\n // mid-trajectory provider timeouts contaminated its calibration runs.\n return Math.max(\n base,\n match([\"gpt-5.3-codex\"], 1),\n match([\"claude-sonnet-5\"], 0.98),\n match([\"gpt-5-mini\"], 0.96),\n match([\"gemini-3.5-flash\"], 0.92),\n match([\"kimi-k3\"], 0.9),\n match([\"deepseek-v4-pro\", \"glm-5.2\"], 0.88),\n );\n case \"tool_agent\":\n if (terminalToolSignal && agentRisk === \"complex_high\") {\n // Keep the Responses-API Codex path outside auto's affinity floor\n // until the gateway fix that preserves function_call_output is live\n // on both chains. Sonnet has a verified native multi-turn tool loop\n // and is the safe strong default for this band today.\n return Math.max(\n base,\n match([\"claude-sonnet-5\"], 1),\n match([\"gpt-5.3-codex\"], 0.87),\n match([\"gpt-5-mini\"], 0.78),\n match([\"gemini-3.5-flash\"], 0.76),\n );\n }\n if (terminalToolSignal && !terminalSafetySensitive) {\n // Seven official Terminal-Bench calibration trajectories favoured\n // GPT-5 Mini over the prior dynamic choice. Admit Codex/Sonnet as\n // close fallbacks, but let actual request cost break the tie.\n return Math.max(\n base,\n match([\"gpt-5-mini\"], 1),\n match([\"gpt-5.3-codex\"], 0.98),\n match([\"claude-sonnet-5\"], 0.9),\n match([\"gemini-3.5-flash\"], 0.89),\n );\n }\n if (terminalToolSignal && terminalSafetySensitive) {\n // Two complete agent observations on the public\n // Terminal-Bench new-encrypt-command task ended in Codex repeating\n // the same TerminalExec input until the loop guard fired. Keep Codex\n // as an availability fallback, but below the safety-band affinity\n // floor until its Responses function-output path is verified on both\n // gateways. This does not change explicit code-agent routing.\n return Math.max(\n base,\n match([\"claude-sonnet-5\"], 1),\n match([\"claude-opus-4.8\"], 0.9),\n match([\"gpt-5.3-codex\"], 0.84),\n );\n }\n if (agentDomain === \"web_research\") {\n // Complete-session BrowseComp calibration supersedes the earlier\n // single-case Opus promotion: strict deduplicated evidence has Sonnet\n // 5 at 2/9 versus Opus 5 at 0/3, while Opus also costs more and has a\n // much longer tail. Keep Opus as an availability fallback until a\n // larger stable-provider sample supports promotion.\n return deepWebResearch\n ? Math.max(\n base,\n match([\"claude-sonnet-5\"], 1),\n match([\"gpt-5-mini\"], 0.88),\n match([\"gemini-3.5-flash\"], 0.84),\n match([\"claude-opus-5\"], 0.8),\n match([\"claude-opus-4.8\"], 0.78),\n )\n : Math.max(\n base,\n match([\"claude-sonnet-5\"], 1),\n match([\"gpt-5-mini\"], 0.88),\n match([\"gemini-3.5-flash\"], 0.86),\n match([\"claude-opus-5\"], 0.84),\n match([\"claude-opus-4.8\"], 0.82),\n );\n }\n // Full-trajectory tau2 calibration (2026-07-28, official gpt-4.1\n // simulator): Sonnet 5 completed both an airline policy task and a\n // retail multi-write task with reward 1.0. Gemini 3.5 Flash emitted\n // function calls as plain text after the first structured calls and\n // looped to the 100-step ceiling on the airline task. Keep only the\n // trajectory-validated primary inside the scoring band; the remaining\n // eligible models are retained below as availability fallbacks.\n if (agentDomain === \"retail\") {\n // Full-session calibration: GPT-5 Mini completed two local/single\n // retail workflows at a fraction of Sonnet's token cost. It remains\n // ineligible for promotion when the prompt asks for multiple actions,\n // cross-record discovery, or a global optimum; those trajectories\n // exposed unstable write arguments in prior calibration. DeepSeek V4\n // Pro completed all three high-risk retail calibration trajectories\n // that included global-choice, cross-record, and multi-write behavior;\n // Sonnet completed one of the same three.\n if (agentRisk === \"standard\") {\n return Math.max(\n base,\n match([\"gpt-5-mini\"], 1),\n match([\"claude-sonnet-5\"], 0.88),\n match([\"gemini-3.5-flash\"], 0.82),\n match([\"gpt-5.3-codex\"], 0.81),\n match([\"kimi-k3\"], 0.78),\n match([\"deepseek-v4-pro\"], 0.76),\n );\n }\n if (agentRisk === \"policy_exception\") {\n return Math.max(\n base,\n match([\"gpt-4.1\"], 1),\n match([\"claude-sonnet-5\"], 0.9),\n match([\"deepseek-v4-pro\"], 0.82),\n match([\"gpt-5-mini\"], 0.8),\n match([\"gpt-4o-mini\"], 0.76),\n );\n }\n if (agentRisk === \"policy_exception_simple\") {\n return Math.max(\n base,\n match([\"gpt-5-mini\"], 1),\n match([\"gpt-4.1\"], 0.86),\n match([\"deepseek-v4-pro\"], 0.82),\n match([\"gpt-4o-mini\"], 0.8),\n );\n }\n return Math.max(\n base,\n match([\"deepseek-v4-pro\"], 1),\n match([\"claude-sonnet-5\"], 0.88),\n match([\"gemini-3.5-flash\"], 0.82),\n match([\"gpt-5.3-codex\"], 0.81),\n match([\"kimi-k3\"], 0.78),\n match([\"gpt-5-mini\"], 0.76),\n );\n }\n // Standard airline workflows stay on GPT-5 Mini: six full-session\n // development trajectories gave it the same 5/6 success as Sonnet at\n // roughly one order of magnitude lower normalized token cost. A held-out\n // high-risk cabin/date negotiation then produced a persistent empty\n // assistant turn on Mini even after a semantic retry, while Sonnet 5\n // completed the identical official tau2 trajectory with reward 1.0.\n // Promote only global optimization / conditional-global work. A known\n // batch of reservations is operationally high-risk but still a\n // structured tool workflow: current Tau evidence has Mini and Sonnet at\n // equal task reward there, while Sonnet costs roughly two orders of\n // magnitude more on the long-tail case.\n if (agentDomain === \"airline\") {\n if (agentRisk === \"complex_high\") {\n return Math.max(\n base,\n match([\"claude-sonnet-5\"], 1),\n match([\"gpt-5-mini\"], 0.78),\n match([\"gemini-3.5-flash\"], 0.76),\n match([\"deepseek-v4-pro\"], 0.74),\n );\n }\n return Math.max(\n base,\n match([\"gpt-5-mini\"], 1),\n match([\"claude-sonnet-5\"], 0.9),\n match([\"gemini-3.5-flash\"], 0.8),\n match([\"deepseek-v4-pro\"], 0.76),\n );\n }\n return Math.max(\n base,\n match([\"claude-sonnet-5\"], 1),\n match([\"gemini-3.5-flash\"], 0.88),\n match([\"gpt-5.3-codex\"], 0.87),\n match([\"gpt-5-mini\"], 0.84),\n match([\"kimi-k3\"], 0.85),\n match([\"deepseek-v4-pro\"], 0.82),\n );\n case \"tool_agent_parallel\":\n if (terminalToolSignal) {\n // Multi-file Terminal work is not equivalent to a one-turn parallel\n // function-call benchmark. Sonnet is the strongest trajectory-tested\n // cost-controlled default; Opus remains a close safety fallback.\n return terminalSafetySensitive\n ? Math.max(\n base,\n match([\"claude-sonnet-5\"], 1),\n match([\"claude-opus-4.8\"], 0.9),\n match([\"gpt-5.3-codex\"], 0.86),\n )\n : Math.max(\n base,\n match([\"gpt-5-mini\"], 1),\n match([\"gpt-5.3-codex\"], 0.98),\n match([\"claude-sonnet-5\"], 0.92),\n match([\"gemini-3.5-flash\"], 0.88),\n );\n }\n if (agentDomain === \"web_research\") {\n return deepWebResearch\n ? Math.max(\n base,\n match([\"claude-sonnet-5\"], 1),\n match([\"gpt-5-mini\"], 0.88),\n match([\"gemini-3.5-flash\"], 0.84),\n match([\"claude-opus-5\"], 0.8),\n match([\"claude-opus-4.8\"], 0.78),\n )\n : Math.max(\n base,\n match([\"claude-sonnet-5\"], 1),\n match([\"gpt-5-mini\"], 0.88),\n match([\"gemini-3.5-flash\"], 0.86),\n match([\"claude-opus-5\"], 0.84),\n match([\"claude-opus-4.8\"], 0.82),\n );\n }\n if (agentDomain === \"retail\") {\n if (agentRisk === \"policy_exception\") {\n return Math.max(\n base,\n match([\"gpt-4.1\"], 1),\n match([\"claude-sonnet-5\"], 0.9),\n match([\"deepseek-v4-pro\"], 0.82),\n match([\"gpt-5-mini\"], 0.8),\n match([\"gpt-4o-mini\"], 0.76),\n );\n }\n if (agentRisk === \"policy_exception_simple\") {\n return Math.max(\n base,\n match([\"gpt-5-mini\"], 1),\n match([\"gpt-4.1\"], 0.86),\n match([\"deepseek-v4-pro\"], 0.82),\n match([\"gpt-4o-mini\"], 0.8),\n );\n }\n return Math.max(\n base,\n match([\"deepseek-v4-pro\"], 1),\n match([\"claude-sonnet-5\"], 0.88),\n match([\"claude-opus-4.8\"], 0.84),\n match([\"gpt-5-mini\"], 0.78),\n match([\"gemini-3.5-flash\"], 0.76),\n );\n }\n if (agentDomain === \"airline\") {\n return agentRisk === \"complex_high\"\n ? Math.max(\n base,\n match([\"claude-sonnet-5\"], 1),\n match([\"gpt-5-mini\"], 0.78),\n match([\"claude-opus-4.8\"], 0.76),\n match([\"gemini-3.5-flash\"], 0.74),\n )\n : Math.max(\n base,\n match([\"gpt-5-mini\"], 1),\n match([\"claude-sonnet-5\"], 0.9),\n match([\"gemini-3.5-flash\"], 0.8),\n );\n }\n // RouterBench calibration, 2026-07-26: Opus 4.8 produced complete\n // multi-call payloads on 2/3 multilingual BFCL parallel cases. Gemini\n // 3.5 Flash, Sonnet 5, DeepSeek V4 Pro, and Grok 4.5 were 0/3. This\n // narrow prior only applies after the conservative prompt feature above.\n return Math.max(\n base,\n match([\"claude-opus-4.8\"], 1),\n match([\"claude-sonnet-5\"], 0.84),\n match([\"grok-4.5\"], 0.82),\n match([\"gemini-3.5-flash\"], 0.8),\n match([\"deepseek-v4-pro\"], 0.78),\n );\n case \"code_edit\":\n case \"debug\":\n return Math.max(\n base,\n match([\"gpt-5.3-codex\"], 1),\n match([\"claude-sonnet-4.6\"], 0.94),\n match([\"glm-5.2\"], 0.9),\n match([\"deepseek-v4-pro\"], 0.86),\n );\n case \"reasoning\":\n return Math.max(\n base,\n match([\"claude-sonnet-5\", \"claude-sonnet-4.6\"], 0.98),\n match([\"deepseek-v4-pro\"], 0.95),\n match([\"grok-4.5\"], 0.94),\n match([\"gemini-3.1-pro\", \"gemini-3.5-flash\"], 0.92),\n );\n case \"reasoning_mcq\":\n // RouterBench calibration (2026-07-28, six stratified GPQA Diamond\n // tasks, identical agent adapter and 512-token budget): Gemini 3\n // Flash Preview scored 5/6, Gemini 3.5 Flash 4/6, and Gemini 3.1 Pro\n // 3/6 while costing ~170x more than Flash. Keep the measured winner as\n // the narrow default; version recency alone is not a quality signal.\n // Unused host tools must not change this reasoning-only model choice.\n return Math.max(\n base,\n match([\"gemini-3-flash-preview\"], 1),\n match([\"gemini-3.5-flash\"], 0.91),\n match([\"grok-4.5\"], 0.9),\n match([\"claude-sonnet-5\"], 0.88),\n match([\"deepseek-v4-pro\"], 0.84),\n );\n case \"reasoning_math\":\n // Same calibration, five multilingual MGSM tasks: Gemini 3.5 Flash was\n // 5/5 with the lowest cost and latency; four current flagships were 4/5\n // and Kimi K2.7 was 3/5.\n return Math.max(\n base,\n match([\"gemini-3.5-flash\"], 1),\n match([\"grok-4.5\"], 0.93),\n match([\"claude-sonnet-5\", \"deepseek-v4-pro\", \"kimi-k3\"], 0.9),\n );\n case \"vision\":\n return Math.max(\n base,\n match([\"gemini-3.1-pro\"], 0.96),\n match([\"qwen3.7-max\", \"claude-sonnet-4.6\", \"kimi-k3\", \"grok-4.3\"], 0.9),\n );\n case \"long_context\":\n // Long-context eligibility is necessary but not sufficient: a provider\n // can advertise a 1M window yet return an empty completion near that\n // boundary. Keep the proven long-context flagship in the lead and put\n // less-established alternatives in a separate affinity band so price\n // alone cannot displace it.\n return Math.max(\n base,\n match([\"gemini-3.1-pro\"], 1),\n match([\"qwen3.7-max\", \"glm-5.2\"], 0.89),\n match([\"gemini-3.5-flash\"], 0.88),\n match([\"deepseek-v4-pro\"], 0.85),\n );\n case \"extraction\": {\n // A structured extraction must preserve both the output contract and the\n // source-language fields. For Mandarin input, keep the language-native\n // Kimi candidate in a distinct affinity band. This is deliberately a\n // candidate-pool decision (rather than a brittle post-hoc override): it\n // still falls back normally if that model is unavailable or ineligible.\n // Kimi K3 costs ~5x its retired sibling K2.7, so the band must be wider\n // than the auto affinityFloorGap (0.10) or price alone re-selects a\n // non-native model for Mandarin input; 0.12 keeps K3 alone in the\n // primary band for zh and leaves every other language untouched.\n const kimiExtractionAffinity = language === \"zh\" ? 1 : 0.9;\n const otherExtractionAffinity = language === \"zh\" ? 0.88 : 0.9;\n return Math.max(\n base,\n match([\"gemini-3.5-flash\", \"gemini-2.5-flash\", \"gpt-4o-mini\"], otherExtractionAffinity),\n match([\"claude-sonnet-5\", \"claude-sonnet-4.6\"], otherExtractionAffinity),\n match([\"kimi-k3\"], kimiExtractionAffinity),\n );\n }\n default:\n return Math.max(\n base,\n match([\"gemini-3.5-flash\", \"gemini-2.5-flash\", \"kimi-k3\"], 0.86),\n );\n }\n}\n\nfunction evidenceCandidates(task: TaskType): string[] {\n if (task === \"code_agent\") {\n return [\n \"openai/gpt-5.3-codex\",\n \"anthropic/claude-sonnet-5\",\n \"openai/gpt-5-mini\",\n \"google/gemini-3.5-flash\",\n \"moonshot/kimi-k3\",\n \"deepseek/deepseek-v4-pro\",\n ];\n }\n if (task === \"tool_agent\") {\n return [\n \"anthropic/claude-sonnet-5\",\n \"anthropic/claude-opus-5\",\n \"openai/gpt-5-mini\",\n \"openai/gpt-4.1\",\n \"openai/gpt-4o-mini\",\n \"google/gemini-3.5-flash\",\n \"openai/gpt-5.3-codex\",\n \"moonshot/kimi-k3\",\n \"deepseek/deepseek-v4-pro\",\n ];\n }\n if (task === \"tool_agent_parallel\") {\n return [\n \"anthropic/claude-opus-5\",\n \"anthropic/claude-opus-4.8\",\n \"anthropic/claude-sonnet-5\",\n \"openai/gpt-5-mini\",\n \"openai/gpt-4.1\",\n \"openai/gpt-4o-mini\",\n \"xai/grok-4.5\",\n \"google/gemini-3.5-flash\",\n \"deepseek/deepseek-v4-pro\",\n ];\n }\n if (task === \"long_context\") {\n return [\n \"google/gemini-3.1-pro\",\n \"deepseek/deepseek-v4-pro\",\n \"qwen/qwen3.7-max\",\n \"zai/glm-5.2\",\n \"google/gemini-3.5-flash\",\n ];\n }\n if (task === \"reasoning_mcq\") {\n return [\n \"google/gemini-3-flash-preview\",\n \"google/gemini-3.5-flash\",\n \"xai/grok-4.5\",\n \"anthropic/claude-sonnet-5\",\n \"deepseek/deepseek-v4-pro\",\n ];\n }\n if (task === \"extraction\") {\n // Kimi K3 is no longer on the auto MEDIUM chain (K2.7 was); the\n // language-native extraction band in affinity() needs it in the pool.\n return [\"moonshot/kimi-k3\", \"google/gemini-3.5-flash\", \"anthropic/claude-sonnet-5\"];\n }\n if (task === \"reasoning_math\") {\n return [\n \"google/gemini-3.5-flash\",\n \"xai/grok-4.5\",\n \"anthropic/claude-sonnet-5\",\n \"deepseek/deepseek-v4-pro\",\n \"moonshot/kimi-k3\",\n ];\n }\n return [];\n}\n\n/**\n * Recently added catalog models with a verified structured function call.\n *\n * Tool compliance is enough to make these models safe availability fallbacks,\n * but it is not evidence that they should displace a trajectory-benchmarked\n * primary. Keep them after the configured and benchmark-backed chains until a\n * full agent evaluation earns a task-specific affinity above the neutral 0.68\n * floor. `isEligible` still applies every host capability override, context\n * limit, vision constraint, and unavailable-model guard before they are used.\n */\nconst VERIFIED_TOOL_FALLBACKS = [\n \"anthropic/claude-fable-5.1\",\n \"anthropic/claude-opus-5.5\",\n \"anthropic/claude-sonnet-5.5\",\n \"deepseek/deepseek-v4.1-flash\",\n \"google/gemini-3.8-flash\",\n \"openai/gpt-5.1\",\n \"openai/gpt-6-astra\",\n \"openai/gpt-6-luna\",\n \"openai/gpt-6-sol\",\n \"openai/gpt-6.1-sol\",\n \"xai/grok-4.6\",\n \"xai/grok-4.7\",\n \"xiaomi/mimo-v2.5\",\n] as const;\n\nfunction isEligible(\n modelId: string,\n features: TaskFeatures,\n maxOutputTokens: number,\n options: RouterOptions,\n): boolean {\n const model = options.modelCapabilities?.[modelId] ?? DEFAULT_MODEL_CAPABILITIES[modelId];\n // Preserve compatibility for temporarily catalog-less fallback IDs. They are\n // kept behind known-model candidates but are not silently dropped.\n if (!model) return true;\n if (features.needsTools && !model.supportsTools) return false;\n if (features.needsVision && !model.supportsVision) return false;\n if (features.needsStructuredOutput && !model.supportsTools) return false;\n if (model.maxOutputTokens < maxOutputTokens) return false;\n return model.contextWindow >= (features.estimatedInputTokens + maxOutputTokens) * 1.1;\n}\n\nfunction estimatedCost(\n modelId: string,\n options: RouterOptions,\n inputTokens: number,\n outputTokens: number,\n): number {\n const price = options.modelPricing.get(modelId);\n if (!price) return Number.POSITIVE_INFINITY;\n if (price.flatPrice !== undefined) return price.flatPrice;\n return (inputTokens * price.inputPrice + outputTokens * price.outputPrice) / 1_000_000;\n}\n\nfunction profileScore(\n modelId: string,\n options: RouterOptions,\n now: Date,\n):\n | { quality?: number; speed: number; tailSpeed: number; reliability: number; freshness: number }\n | undefined {\n const profile: ModelPerformanceProfile | undefined =\n options.modelPerformance?.[modelId] ??\n LIVE_MODEL_PROFILES[modelId] ??\n HISTORICAL_MODEL_PROFILES[modelId];\n if (!profile) return undefined;\n const measuredAt = Date.parse(profile.measuredAt);\n if (!Number.isFinite(measuredAt)) return undefined;\n const ageDays = Math.max(0, (now.getTime() - measuredAt) / 86_400_000);\n // A 30-day half-life makes old data a tie-breaker only. Small probe runs are\n // also weak evidence: three quick samples should not overturn a curated\n // tier ordering merely because of a transient provider tail. Callers that\n // inject an observation without a sample count retain the legacy full\n // confidence behaviour for compatibility.\n const sampleConfidence =\n profile.samples === undefined ? 1 : Math.min(1, Math.max(0, profile.samples) / 10);\n const freshness = Math.pow(0.5, ageDays / 30) * sampleConfidence;\n const quality =\n profile.intelligenceIndex === undefined\n ? undefined\n : Math.min(1, profile.intelligenceIndex / 50);\n const speed = Math.min(\n 1,\n (2_000 / Math.max(500, profile.latencyMs) + profile.outputTokensPerSecond / 250) / 2,\n );\n const tailSpeed = Math.min(1, 3_000 / Math.max(750, profile.p95LatencyMs ?? profile.latencyMs));\n const reliability = Math.max(0, 1 - (profile.errorRate ?? 0));\n return { quality, speed, tailSpeed, reliability, freshness };\n}\n\n/** Candidate router used for Auto. Rules still set the capability tier; V3 ranks within it. */\nexport class PortfolioStrategy implements RouterStrategy {\n readonly name = \"portfolio\";\n // Rules set the capability tier; the strategy is stateless, so one instance serves every request.\n private readonly rules = new RulesStrategy();\n\n route(\n prompt: string,\n systemPrompt: string | undefined,\n maxOutputTokens: number,\n options: RouterOptions,\n ) {\n const features = classifyTask(prompt, systemPrompt, options);\n const base = this.rules.route(prompt, systemPrompt, maxOutputTokens, {\n ...options,\n requiresTools: features.needsTools,\n });\n const tierConfigs = base.tierConfigs;\n if (!tierConfigs) return base;\n // The rules score sets the capability tier, but two task types carry a\n // floor of their own: a compact reasoning problem belongs on the\n // reasoning chain however short it is, and a code edit or stack trace\n // belongs at least on the MEDIUM chain — the SIMPLE chain is curated for\n // trivia and translation and has no model with code affinity. The code\n // floor requires a code artifact or coding action: `debug` and `code_edit`\n // are also assigned from bare verbs (\"rewrite this sentence\", \"margin of\n // error\") and bare language names (\"What is Python?\"), and that prose\n // must stay on the cheap chain.\n const targetTier: Tier =\n (features.taskType === \"reasoning_mcq\" || features.taskType === \"reasoning_math\") &&\n (base.tier === \"SIMPLE\" || base.tier === \"MEDIUM\")\n ? \"REASONING\"\n : (features.taskType === \"debug\" || features.taskType === \"code_edit\") &&\n features.codeArtifact &&\n base.tier === \"SIMPLE\"\n ? \"MEDIUM\"\n : base.tier;\n const tierConfig = tierConfigs[targetTier];\n const configuredCandidates = tierConfig ? getFallbackChain(targetTier, tierConfigs) : [];\n // Evidence candidates join the configured chain, but the host's\n // unavailable set applies to both: the configured side arrives filtered\n // through RulesStrategy, and a dead evidence model must not re-enter here.\n const unavailable = new Set(options.unavailableModels ?? []);\n // `modelPricing` is the host's live catalog view. Do not introduce a\n // built-in fallback that the current gateway does not advertise. These\n // models carry no task evidence, so outside Premium the cheapest one is\n // the first recovery hop; otherwise an outage of the curated chain would\n // jump an Eco turn straight to the most expensive model in the list.\n const verifiedToolFallbacks = features.needsTools\n ? VERIFIED_TOOL_FALLBACKS.filter((model) => options.modelPricing.has(model))\n : [];\n if (options.routingProfile !== \"premium\") {\n const fallbackCost = (model: string) =>\n estimatedCost(model, options, features.estimatedInputTokens, maxOutputTokens);\n verifiedToolFallbacks.sort((a, b) => fallbackCost(a) - fallbackCost(b));\n }\n const chain = [\n ...new Set([\n ...configuredCandidates,\n ...evidenceCandidates(features.taskType),\n ...verifiedToolFallbacks,\n ]),\n ].filter(\n (model): model is string =>\n typeof model === \"string\" && model.length > 0 && !unavailable.has(model),\n );\n const eligible = new Set(\n chain.filter((model) => isEligible(model, features, maxOutputTokens, options)),\n );\n // When nothing is eligible the whole chain competes, scored as incapable.\n const eligibleCandidates = eligible.size > 0 ? [...eligible] : chain;\n if (eligibleCandidates.length === 0) return base;\n const profileName =\n options.routingProfile === \"eco\"\n ? \"eco\"\n : options.routingProfile === \"premium\"\n ? \"premium\"\n : \"auto\";\n const portfolio = options.config.portfolio ?? DEFAULT_PORTFOLIO_WEIGHTS;\n const getAffinity = (model: string) =>\n affinity(\n model,\n features.taskType,\n features.language,\n features.agentDomain,\n features.deepWebResearch,\n features.agentRisk,\n features.terminalToolSignal,\n features.terminalSafetySensitive,\n );\n const bestAffinity = Math.max(...eligibleCandidates.map(getAffinity));\n const specificAffinity = eligibleCandidates.filter((model) => getAffinity(model) > 0.68);\n // A tier's fallback list is primarily an availability/recovery chain, not a\n // set of equally validated substitutes. Re-ranking every fallback lets a\n // cheap generic model displace the curated primary merely because it has a\n // favourable short performance probe. Only promote models with explicit\n // task affinity; otherwise retain the first capability-eligible tier model.\n const affinityPool = specificAffinity.length > 0 ? specificAffinity : [eligibleCandidates[0]];\n // Generic Terminal work has much wider trajectory variance than a BFCL-like\n // one-turn parallel call. Keep the strong-model safety band, but admit the\n // next capable tier so Auto's cost/reliability score can reject an Opus\n // primary that is materially more expensive without measured benefit.\n const affinityFloorGap = features.terminalToolSignal\n ? Math.max(\n portfolio.affinityFloorGap[profileName],\n features.terminalSafetySensitive ? 0.15 : 0.12,\n )\n : portfolio.affinityFloorGap[profileName];\n const candidates = affinityPool.filter(\n (model) => getAffinity(model) >= bestAffinity - affinityFloorGap,\n );\n const costs = candidates.map((model) =>\n estimatedCost(model, options, features.estimatedInputTokens, maxOutputTokens),\n );\n const finiteCosts = costs.filter(Number.isFinite);\n const minCost = finiteCosts.length > 0 ? Math.min(...finiteCosts) : 0;\n const maxCost = finiteCosts.length > 0 ? Math.max(...finiteCosts) : 1;\n\n const now = options.now ?? new Date();\n const profileWeights = portfolio[profileName];\n const rankedEntries = candidates\n .map((model, index) => {\n const cost = estimatedCost(model, options, features.estimatedInputTokens, maxOutputTokens);\n const costScore =\n Number.isFinite(cost) && maxCost > minCost\n ? 1 - (cost - minCost) / (maxCost - minCost)\n : 0.5;\n const capabilityScore = eligible.has(model) ? 1 : 0;\n const profile = profileScore(model, options, now);\n // Fresh observations can refine affinity. Historical observations fade\n // quickly and never replace task-level RouterBench evidence.\n const observedQuality =\n profile?.quality === undefined\n ? getAffinity(model)\n : getAffinity(model) * (1 - profile.freshness) + profile.quality * profile.freshness;\n // Every observed dimension fades toward its neutral prior as the\n // observation ages, exactly like reliability below. Fading speed\n // toward zero instead ranked any model with a stale probe below a\n // model nobody had measured, which the latter's 0.5 silently won.\n const observedSpeed = profile\n ? profile.speed * profile.freshness + 0.5 * (1 - profile.freshness)\n : 0.5;\n const observedTailSpeed = profile\n ? profile.tailSpeed * profile.freshness + 0.5 * (1 - profile.freshness)\n : 0.5;\n const observedReliability = profile\n ? profile.reliability * profile.freshness + (1 - profile.freshness)\n : 1;\n // Preserve a small amount of the hand-curated fallback order while V3's\n // task affinity and real request constraints do the primary work.\n const legacyScore = 1 - index / Math.max(1, candidates.length - 1);\n const qualityWeight =\n profileWeights.quality + (features.highStakes ? portfolio.highStakesBoost.quality : 0);\n const speedScore = features.latencySensitive ? observedTailSpeed : observedSpeed;\n const speedWeight =\n profileWeights.speed +\n (features.latencySensitive ? portfolio.latencySensitiveSpeedBoost : 0);\n const reliabilityWeight =\n profileWeights.reliability +\n (features.highStakes ? portfolio.highStakesBoost.reliability : 0);\n const score =\n observedQuality * qualityWeight +\n capabilityScore * profileWeights.capability +\n costScore * profileWeights.cost +\n speedScore * speedWeight +\n observedReliability * reliabilityWeight +\n legacyScore * profileWeights.legacy;\n return {\n model,\n score,\n quality: observedQuality,\n cost: costScore,\n speed: speedScore,\n reliability: observedReliability,\n };\n })\n .sort((a, b) => b.score - a.score);\n const scoredModels = rankedEntries.map((item) => item.model);\n // The affinity floor controls which models may compete for the primary;\n // it must not erase availability fallbacks. Append all remaining eligible\n // models in their curated chain order after the scored primary pool.\n const webResearchFallbackOrder = [\n \"anthropic/claude-sonnet-5\",\n \"openai/gpt-5-mini\",\n \"google/gemini-3.5-flash\",\n \"anthropic/claude-opus-5\",\n \"anthropic/claude-opus-4.8\",\n \"openai/gpt-5.3-codex\",\n ];\n const ranked =\n features.agentDomain === \"web_research\"\n ? [\n ...scoredModels,\n ...webResearchFallbackOrder.filter(\n (model) => eligibleCandidates.includes(model) && !scoredModels.includes(model),\n ),\n ...eligibleCandidates.filter(\n (model) => !scoredModels.includes(model) && !webResearchFallbackOrder.includes(model),\n ),\n ]\n : [...scoredModels, ...eligibleCandidates.filter((model) => !scoredModels.includes(model))];\n\n const model = ranked[0] ?? base.model;\n const selectedTierConfigs: Record = {\n ...tierConfigs,\n [targetTier]: { primary: model, fallback: ranked.slice(1) },\n };\n // selectModel only reads the selected tier; retain the complete tier map for host fallback.\n const decision = selectModel(\n targetTier,\n base.confidence,\n \"portfolio\",\n `${base.reasoning} | v3 task=${features.taskType} agentRisk=${features.agentRisk} deepWebResearch=${features.deepWebResearch} terminalCode=${features.implicitTerminalCode} terminalSafety=${features.terminalSafetySensitive} candidates=${ranked.length}`,\n selectedTierConfigs,\n options.modelPricing,\n features.estimatedInputTokens,\n maxOutputTokens,\n options.routingProfile,\n base.agenticScore,\n );\n return {\n ...decision,\n tierConfigs: selectedTierConfigs,\n profile: base.profile,\n candidates: ranked,\n candidateScores: rankedEntries.map(({ model, score, quality, cost, speed, reliability }) => ({\n model,\n score,\n quality,\n cost,\n speed,\n reliability,\n })),\n taskType: features.taskType,\n routerVersion: \"v3-portfolio\" as const,\n };\n }\n}\n","/** Pure public-catalog parsing. Fetching, caching and UI ordering belong to hosts. */\nimport { DEFAULT_MODEL_CAPABILITIES, type ModelCapabilities } from \"./model-capabilities.js\";\nimport type { ModelPricing } from \"./selector.js\";\n\nexport const MODEL_KINDS = [\"chat\", \"image\", \"video\", \"music\"] as const;\nexport type ModelKind = (typeof MODEL_KINDS)[number];\n\n/** Gateway units are preserved: token prices per 1M tokens; media per unit. */\nexport interface CatalogPricing {\n input?: number;\n output?: number;\n per_image?: number;\n per_second?: number;\n per_track?: number;\n cache_read?: number;\n cache_write?: number;\n transaction_fee?: number;\n per_call_surcharge?: number;\n default_duration_seconds?: number;\n max_duration_seconds?: number;\n}\n\nexport interface CatalogModel {\n id: string;\n name: string;\n categories: readonly string[];\n kinds: readonly ModelKind[];\n billingMode?: string;\n /** Zero pricing alone does not imply a free model. */\n free: boolean;\n pricing: CatalogPricing;\n contextWindow?: number;\n maxOutputTokens?: number;\n}\n\nexport interface ModelCatalog {\n models: readonly CatalogModel[];\n chat: readonly CatalogModel[];\n image: readonly CatalogModel[];\n video: readonly CatalogModel[];\n music: readonly CatalogModel[];\n /**\n * IDs whose authoritative row says `available: false`. The gateway does not\n * reject these; it substitutes another model. Absence from the listing is\n * not unavailability: hidden IDs are still served.\n */\n unavailable: readonly string[];\n}\n\nconst PRICE_KEYS = [\n \"input\", \"output\", \"per_image\", \"per_second\", \"per_track\", \"cache_read\", \"cache_write\",\n \"transaction_fee\", \"per_call_surcharge\", \"default_duration_seconds\", \"max_duration_seconds\",\n] as const;\nconst UNIT_PRICE = { image: \"per_image\", video: \"per_second\", music: \"per_track\" } as const;\nconst MODEL_ID = /^[a-z0-9][a-z0-9._-]*\\/[a-zA-Z0-9][a-zA-Z0-9._:+-]*$/;\nconst record = (value: unknown): value is Record =>\n value !== null && typeof value === \"object\" && !Array.isArray(value);\nconst price = (value: unknown): value is number =>\n typeof value === \"number\" && Number.isFinite(value) && value >= 0;\nconst capacity = (value: unknown): number | undefined =>\n typeof value === \"number\" && Number.isSafeInteger(value) && value > 0 ? value : undefined;\n\n/**\n * Normalize GET /api/v1/models without a model-ID allowlist. New provider IDs\n * appear immediately. Hidden/unavailable rows and invalid per-kind prices are\n * omitted. A malformed envelope throws so a host can retain its last good list;\n * an explicitly empty `data` array is a valid empty catalog.\n *\n * IDs explicitly marked `available: false` are also listed in `unavailable`.\n * Rows outside MODEL_KINDS (speech, sound effects) are omitted.\n *\n * Last duplicate wins, including a final unavailable/invalid row. No sorting,\n * price markup, network request, capability probe or media routing is performed.\n */\nexport function parseModelCatalog(value: unknown): ModelCatalog {\n if (!record(value) || !Array.isArray(value.data)) {\n throw new TypeError(\"Model catalog must contain a data array\");\n }\n const entries = new Map>();\n for (const entry of value.data) {\n if (record(entry) && typeof entry.id === \"string\" && entry.id.length <= 200 && MODEL_ID.test(entry.id)) {\n entries.set(entry.id, entry);\n }\n }\n const result: ModelCatalog = { models: [], chat: [], image: [], video: [], music: [], unavailable: [] };\n const models: CatalogModel[] = [];\n const unavailable: string[] = [];\n for (const [id, entry] of entries) {\n if (entry.available === false) unavailable.push(id);\n if ((entry.available !== undefined && entry.available !== true) ||\n (entry.hidden !== undefined && entry.hidden !== false) ||\n !Array.isArray(entry.categories) || !record(entry.pricing)) continue;\n const categories = [...new Set(entry.categories.filter((c): c is string => typeof c === \"string\"))];\n const rawPricing = entry.pricing;\n const pricing: CatalogPricing = {};\n for (const key of PRICE_KEYS) if (price(rawPricing[key])) pricing[key] = rawPricing[key];\n const kinds = MODEL_KINDS.filter(kind => categories.includes(kind) && (kind === \"chat\"\n ? price(rawPricing.input) && price(rawPricing.output)\n : price(rawPricing[UNIT_PRICE[kind]])));\n if (!kinds.length) continue;\n const model: CatalogModel = {\n id, name: typeof entry.name === \"string\" && entry.name.trim() ? entry.name : id,\n categories, kinds, pricing,\n free: kinds.includes(\"chat\") && entry.billing_mode === \"free\" && pricing.input === 0 && pricing.output === 0,\n ...(typeof entry.billing_mode === \"string\" ? { billingMode: entry.billing_mode } : {}),\n ...(capacity(entry.context_window) !== undefined ? { contextWindow: capacity(entry.context_window) } : {}),\n ...(capacity(entry.max_output) !== undefined ? { maxOutputTokens: capacity(entry.max_output) } : {}),\n };\n models.push(model);\n }\n result.models = models;\n result.unavailable = unavailable;\n for (const kind of MODEL_KINDS) result[kind] = models.filter(model => model.kinds.includes(kind));\n return result;\n}\n\nexport interface CatalogRoutingOptions {\n /** Host evidence, merged over (and overriding per ID) the bundled verified table. */\n verifiedCapabilities?: Readonly>;\n}\n\nexport interface RoutingCatalog {\n modelPricing: Map;\n modelCapabilities: Record;\n unavailableModels: string[];\n}\n\n/**\n * Adapt only the chat catalog for route(). Media never enters LLM candidate\n * chains. Tool support comes from verified evidence, never a name or category.\n * Unknown capacities are zero, rather than invented defaults.\n *\n * Only rows the gateway explicitly marks `available: false` become\n * unavailableModels. Configured IDs that are merely absent from the listing\n * stay routable: the gateway serves hidden IDs, and only the configured chain\n * knows about them.\n */\nexport function toRoutingCatalog(catalog: ModelCatalog, options: CatalogRoutingOptions = {}): RoutingCatalog {\n const verified = { ...DEFAULT_MODEL_CAPABILITIES, ...options.verifiedCapabilities };\n const modelPricing = new Map();\n const modelCapabilities: Record = {};\n for (const model of catalog.chat) {\n modelPricing.set(model.id, { inputPrice: model.pricing.input!, outputPrice: model.pricing.output! });\n const evidence = verified[model.id];\n modelCapabilities[model.id] = {\n contextWindow: model.contextWindow ?? evidence?.contextWindow ?? 0,\n maxOutputTokens: model.maxOutputTokens ?? evidence?.maxOutputTokens ?? 0,\n supportsTools: evidence?.supportsTools === true,\n supportsVision: model.categories.includes(\"vision\"),\n };\n }\n return { modelPricing, modelCapabilities, unavailableModels: [...catalog.unavailable] };\n}\n","/**\n * Default Routing Config\n *\n * All routing parameters as a TypeScript constant.\n * Operators override via openclaw.yaml plugin config.\n *\n * Scoring uses 15 weighted dimensions with sigmoid confidence calibration.\n */\n\nimport type { RoutingConfig } from \"./types.js\";\n\nexport const DEFAULT_ROUTING_CONFIG: RoutingConfig = {\n version: \"3.5\",\n strategy: \"portfolio\",\n portfolio: {\n auto: {\n quality: 0.47,\n capability: 0.2,\n cost: 0.18,\n speed: 0.07,\n reliability: 0.03,\n legacy: 0.05,\n },\n eco: {\n quality: 0.36,\n capability: 0.2,\n cost: 0.28,\n speed: 0.1,\n reliability: 0.04,\n legacy: 0.02,\n },\n premium: {\n quality: 0.58,\n capability: 0.2,\n cost: 0.08,\n speed: 0.06,\n reliability: 0.06,\n legacy: 0.02,\n },\n highStakesBoost: { quality: 0.08, reliability: 0.05 },\n latencySensitiveSpeedBoost: 0.08,\n affinityFloorGap: { auto: 0.1, eco: 0.22, premium: 0.05 },\n },\n\n classifier: {\n llmModel: \"google/gemini-2.5-flash\",\n llmMaxTokens: 10,\n llmTemperature: 0,\n promptTruncationChars: 500,\n cacheTtlMs: 3_600_000, // 1 hour\n },\n\n scoring: {\n tokenCountThresholds: { simple: 50, complex: 500 },\n\n // Multilingual keywords: EN + ZH + JA + RU + DE + ES + PT + KO + AR\n codeKeywords: [\n // English\n \"function\",\n \"class\",\n \"import\",\n \"def\",\n \"SELECT\",\n \"async\",\n \"await\",\n \"const\",\n \"let\",\n \"var\",\n \"return\",\n \"```\",\n // Chinese\n \"函数\",\n \"类\",\n \"导入\",\n \"定义\",\n \"查询\",\n \"异步\",\n \"等待\",\n \"常量\",\n \"变量\",\n \"返回\",\n // Japanese\n \"関数\",\n \"クラス\",\n \"インポート\",\n \"非同期\",\n \"定数\",\n \"変数\",\n // Russian\n \"функция\",\n \"класс\",\n \"импорт\",\n \"определ\",\n \"запрос\",\n \"асинхронный\",\n \"ожидать\",\n \"константа\",\n \"переменная\",\n \"вернуть\",\n // German\n \"funktion\",\n \"klasse\",\n \"importieren\",\n \"definieren\",\n \"abfrage\",\n \"asynchron\",\n \"erwarten\",\n \"konstante\",\n \"variable\",\n \"zurückgeben\",\n // Spanish\n \"función\",\n \"clase\",\n \"importar\",\n \"definir\",\n \"consulta\",\n \"asíncrono\",\n \"esperar\",\n \"constante\",\n \"variable\",\n \"retornar\",\n // Portuguese\n \"função\",\n \"classe\",\n \"importar\",\n \"definir\",\n \"consulta\",\n \"assíncrono\",\n \"aguardar\",\n \"constante\",\n \"variável\",\n \"retornar\",\n // Korean\n \"함수\",\n \"클래스\",\n \"가져오기\",\n \"정의\",\n \"쿼리\",\n \"비동기\",\n \"대기\",\n \"상수\",\n \"변수\",\n \"반환\",\n // Arabic\n \"دالة\",\n \"فئة\",\n \"استيراد\",\n \"تعريف\",\n \"استعلام\",\n \"غير متزامن\",\n \"انتظار\",\n \"ثابت\",\n \"متغير\",\n \"إرجاع\",\n ],\n reasoningKeywords: [\n // English\n \"prove\",\n \"theorem\",\n \"derive\",\n \"step by step\",\n \"chain of thought\",\n \"formally\",\n \"mathematical\",\n \"proof\",\n \"logically\",\n // Chinese\n \"证明\",\n \"定理\",\n \"推导\",\n \"逐步\",\n \"思维链\",\n \"形式化\",\n \"数学\",\n \"逻辑\",\n // Japanese\n \"証明\",\n \"定理\",\n \"導出\",\n \"ステップバイステップ\",\n \"論理的\",\n // Russian\n \"доказать\",\n \"докажи\",\n \"доказательств\",\n \"теорема\",\n \"вывести\",\n \"шаг за шагом\",\n \"пошагово\",\n \"поэтапно\",\n \"цепочка рассуждений\",\n \"рассуждени\",\n \"формально\",\n \"математически\",\n \"логически\",\n // German\n \"beweisen\",\n \"beweis\",\n \"theorem\",\n \"ableiten\",\n \"schritt für schritt\",\n \"gedankenkette\",\n \"formal\",\n \"mathematisch\",\n \"logisch\",\n // Spanish\n \"demostrar\",\n \"teorema\",\n \"derivar\",\n \"paso a paso\",\n \"cadena de pensamiento\",\n \"formalmente\",\n \"matemático\",\n \"prueba\",\n \"lógicamente\",\n // Portuguese\n \"provar\",\n \"teorema\",\n \"derivar\",\n \"passo a passo\",\n \"cadeia de pensamento\",\n \"formalmente\",\n \"matemático\",\n \"prova\",\n \"logicamente\",\n // Korean\n \"증명\",\n \"정리\",\n \"도출\",\n \"단계별\",\n \"사고의 연쇄\",\n \"형식적\",\n \"수학적\",\n \"논리적\",\n // Arabic\n \"إثبات\",\n \"نظرية\",\n \"اشتقاق\",\n \"خطوة بخطوة\",\n \"سلسلة التفكير\",\n \"رسمياً\",\n \"رياضي\",\n \"برهان\",\n \"منطقياً\",\n ],\n simpleKeywords: [\n // English\n \"what is\",\n \"define\",\n \"translate\",\n \"hello\",\n \"yes or no\",\n \"capital of\",\n \"how old\",\n \"who is\",\n \"when was\",\n // Chinese\n \"什么是\",\n \"定义\",\n \"翻译\",\n \"你好\",\n \"是否\",\n \"首都\",\n \"多大\",\n \"谁是\",\n \"何时\",\n // Japanese\n \"とは\",\n \"定義\",\n \"翻訳\",\n \"こんにちは\",\n \"はいかいいえ\",\n \"首都\",\n \"誰\",\n // Russian\n \"что такое\",\n \"определение\",\n \"перевести\",\n \"переведи\",\n \"привет\",\n \"да или нет\",\n \"столица\",\n \"сколько лет\",\n \"кто такой\",\n \"когда\",\n \"объясни\",\n // German\n \"was ist\",\n \"definiere\",\n \"übersetze\",\n \"hallo\",\n \"ja oder nein\",\n \"hauptstadt\",\n \"wie alt\",\n \"wer ist\",\n \"wann\",\n \"erkläre\",\n // Spanish\n \"qué es\",\n \"definir\",\n \"traducir\",\n \"hola\",\n \"sí o no\",\n \"capital de\",\n \"cuántos años\",\n \"quién es\",\n \"cuándo\",\n // Portuguese\n \"o que é\",\n \"definir\",\n \"traduzir\",\n \"olá\",\n \"sim ou não\",\n \"capital de\",\n \"quantos anos\",\n \"quem é\",\n \"quando\",\n // Korean\n \"무엇\",\n \"정의\",\n \"번역\",\n \"안녕하세요\",\n \"예 또는 아니오\",\n \"수도\",\n \"누구\",\n \"언제\",\n // Arabic\n \"ما هو\",\n \"تعريف\",\n \"ترجم\",\n \"مرحبا\",\n \"نعم أو لا\",\n \"عاصمة\",\n \"من هو\",\n \"متى\",\n ],\n technicalKeywords: [\n // English\n \"algorithm\",\n \"optimize\",\n \"architecture\",\n \"distributed\",\n \"kubernetes\",\n \"microservice\",\n \"database\",\n \"infrastructure\",\n // Chinese\n \"算法\",\n \"优化\",\n \"架构\",\n \"分布式\",\n \"微服务\",\n \"数据库\",\n \"基础设施\",\n // Japanese\n \"アルゴリズム\",\n \"最適化\",\n \"アーキテクチャ\",\n \"分散\",\n \"マイクロサービス\",\n \"データベース\",\n // Russian\n \"алгоритм\",\n \"оптимизировать\",\n \"оптимизаци\",\n \"оптимизируй\",\n \"архитектура\",\n \"распределённый\",\n \"микросервис\",\n \"база данных\",\n \"инфраструктура\",\n // German\n \"algorithmus\",\n \"optimieren\",\n \"architektur\",\n \"verteilt\",\n \"kubernetes\",\n \"mikroservice\",\n \"datenbank\",\n \"infrastruktur\",\n // Spanish\n \"algoritmo\",\n \"optimizar\",\n \"arquitectura\",\n \"distribuido\",\n \"microservicio\",\n \"base de datos\",\n \"infraestructura\",\n // Portuguese\n \"algoritmo\",\n \"otimizar\",\n \"arquitetura\",\n \"distribuído\",\n \"microsserviço\",\n \"banco de dados\",\n \"infraestrutura\",\n // Korean\n \"알고리즘\",\n \"최적화\",\n \"아키텍처\",\n \"분산\",\n \"마이크로서비스\",\n \"데이터베이스\",\n \"인프라\",\n // Arabic\n \"خوارزمية\",\n \"تحسين\",\n \"بنية\",\n \"موزع\",\n \"خدمة مصغرة\",\n \"قاعدة بيانات\",\n \"بنية تحتية\",\n ],\n creativeKeywords: [\n // English\n \"story\",\n \"poem\",\n \"compose\",\n \"brainstorm\",\n \"creative\",\n \"imagine\",\n \"write a\",\n // Chinese\n \"故事\",\n \"诗\",\n \"创作\",\n \"头脑风暴\",\n \"创意\",\n \"想象\",\n \"写一个\",\n // Japanese\n \"物語\",\n \"詩\",\n \"作曲\",\n \"ブレインストーム\",\n \"創造的\",\n \"想像\",\n // Russian\n \"история\",\n \"рассказ\",\n \"стихотворение\",\n \"сочинить\",\n \"сочини\",\n \"мозговой штурм\",\n \"творческий\",\n \"представить\",\n \"придумай\",\n \"напиши\",\n // German\n \"geschichte\",\n \"gedicht\",\n \"komponieren\",\n \"brainstorming\",\n \"kreativ\",\n \"vorstellen\",\n \"schreibe\",\n \"erzählung\",\n // Spanish\n \"historia\",\n \"poema\",\n \"componer\",\n \"lluvia de ideas\",\n \"creativo\",\n \"imaginar\",\n \"escribe\",\n // Portuguese\n \"história\",\n \"poema\",\n \"compor\",\n \"criativo\",\n \"imaginar\",\n \"escreva\",\n // Korean\n \"이야기\",\n \"시\",\n \"작곡\",\n \"브레인스토밍\",\n \"창의적\",\n \"상상\",\n \"작성\",\n // Arabic\n \"قصة\",\n \"قصيدة\",\n \"تأليف\",\n \"عصف ذهني\",\n \"إبداعي\",\n \"تخيل\",\n \"اكتب\",\n ],\n\n // New dimension keyword lists (multilingual)\n imperativeVerbs: [\n // English\n \"build\",\n \"create\",\n \"implement\",\n \"design\",\n \"develop\",\n \"construct\",\n \"generate\",\n \"deploy\",\n \"configure\",\n \"set up\",\n // Chinese\n \"构建\",\n \"创建\",\n \"实现\",\n \"设计\",\n \"开发\",\n \"生成\",\n \"部署\",\n \"配置\",\n \"设置\",\n // Japanese\n \"構築\",\n \"作成\",\n \"実装\",\n \"設計\",\n \"開発\",\n \"生成\",\n \"デプロイ\",\n \"設定\",\n // Russian\n \"построить\",\n \"построй\",\n \"создать\",\n \"создай\",\n \"реализовать\",\n \"реализуй\",\n \"спроектировать\",\n \"разработать\",\n \"разработай\",\n \"сконструировать\",\n \"сгенерировать\",\n \"сгенерируй\",\n \"развернуть\",\n \"разверни\",\n \"настроить\",\n \"настрой\",\n // German\n \"erstellen\",\n \"bauen\",\n \"implementieren\",\n \"entwerfen\",\n \"entwickeln\",\n \"konstruieren\",\n \"generieren\",\n \"bereitstellen\",\n \"konfigurieren\",\n \"einrichten\",\n // Spanish\n \"construir\",\n \"crear\",\n \"implementar\",\n \"diseñar\",\n \"desarrollar\",\n \"generar\",\n \"desplegar\",\n \"configurar\",\n // Portuguese\n \"construir\",\n \"criar\",\n \"implementar\",\n \"projetar\",\n \"desenvolver\",\n \"gerar\",\n \"implantar\",\n \"configurar\",\n // Korean\n \"구축\",\n \"생성\",\n \"구현\",\n \"설계\",\n \"개발\",\n \"배포\",\n \"설정\",\n // Arabic\n \"بناء\",\n \"إنشاء\",\n \"تنفيذ\",\n \"تصميم\",\n \"تطوير\",\n \"توليد\",\n \"نشر\",\n \"إعداد\",\n ],\n constraintIndicators: [\n // English\n \"under\",\n \"at most\",\n \"at least\",\n \"within\",\n \"no more than\",\n \"o(\",\n \"maximum\",\n \"minimum\",\n \"limit\",\n \"budget\",\n // Chinese\n \"不超过\",\n \"至少\",\n \"最多\",\n \"在内\",\n \"最大\",\n \"最小\",\n \"限制\",\n \"预算\",\n // Japanese\n \"以下\",\n \"最大\",\n \"最小\",\n \"制限\",\n \"予算\",\n // Russian\n \"не более\",\n \"не менее\",\n \"как минимум\",\n \"в пределах\",\n \"максимум\",\n \"минимум\",\n \"ограничение\",\n \"бюджет\",\n // German\n \"höchstens\",\n \"mindestens\",\n \"innerhalb\",\n \"nicht mehr als\",\n \"maximal\",\n \"minimal\",\n \"grenze\",\n \"budget\",\n // Spanish\n \"como máximo\",\n \"al menos\",\n \"dentro de\",\n \"no más de\",\n \"máximo\",\n \"mínimo\",\n \"límite\",\n \"presupuesto\",\n // Portuguese\n \"no máximo\",\n \"pelo menos\",\n \"dentro de\",\n \"não mais que\",\n \"máximo\",\n \"mínimo\",\n \"limite\",\n \"orçamento\",\n // Korean\n \"이하\",\n \"이상\",\n \"최대\",\n \"최소\",\n \"제한\",\n \"예산\",\n // Arabic\n \"على الأكثر\",\n \"على الأقل\",\n \"ضمن\",\n \"لا يزيد عن\",\n \"أقصى\",\n \"أدنى\",\n \"حد\",\n \"ميزانية\",\n ],\n outputFormatKeywords: [\n // English\n \"json\",\n \"yaml\",\n \"xml\",\n \"table\",\n \"csv\",\n \"markdown\",\n \"schema\",\n \"format as\",\n \"structured\",\n // Chinese\n \"表格\",\n \"格式化为\",\n \"结构化\",\n // Japanese\n \"テーブル\",\n \"フォーマット\",\n \"構造化\",\n // Russian\n \"таблица\",\n \"форматировать как\",\n \"структурированный\",\n // German\n \"tabelle\",\n \"formatieren als\",\n \"strukturiert\",\n // Spanish\n \"tabla\",\n \"formatear como\",\n \"estructurado\",\n // Portuguese\n \"tabela\",\n \"formatar como\",\n \"estruturado\",\n // Korean\n \"테이블\",\n \"형식\",\n \"구조화\",\n // Arabic\n \"جدول\",\n \"تنسيق\",\n \"منظم\",\n ],\n referenceKeywords: [\n // English\n \"above\",\n \"below\",\n \"previous\",\n \"following\",\n \"the docs\",\n \"the api\",\n \"the code\",\n \"earlier\",\n \"attached\",\n // Chinese\n \"上面\",\n \"下面\",\n \"之前\",\n \"接下来\",\n \"文档\",\n \"代码\",\n \"附件\",\n // Japanese\n \"上記\",\n \"下記\",\n \"前の\",\n \"次の\",\n \"ドキュメント\",\n \"コード\",\n // Russian\n \"выше\",\n \"ниже\",\n \"предыдущий\",\n \"следующий\",\n \"документация\",\n \"код\",\n \"ранее\",\n \"вложение\",\n // German\n \"oben\",\n \"unten\",\n \"vorherige\",\n \"folgende\",\n \"dokumentation\",\n \"der code\",\n \"früher\",\n \"anhang\",\n // Spanish\n \"arriba\",\n \"abajo\",\n \"anterior\",\n \"siguiente\",\n \"documentación\",\n \"el código\",\n \"adjunto\",\n // Portuguese\n \"acima\",\n \"abaixo\",\n \"anterior\",\n \"seguinte\",\n \"documentação\",\n \"o código\",\n \"anexo\",\n // Korean\n \"위\",\n \"아래\",\n \"이전\",\n \"다음\",\n \"문서\",\n \"코드\",\n \"첨부\",\n // Arabic\n \"أعلاه\",\n \"أدناه\",\n \"السابق\",\n \"التالي\",\n \"الوثائق\",\n \"الكود\",\n \"مرفق\",\n ],\n negationKeywords: [\n // English\n \"don't\",\n \"do not\",\n \"avoid\",\n \"never\",\n \"without\",\n \"except\",\n \"exclude\",\n \"no longer\",\n // Chinese\n \"不要\",\n \"避免\",\n \"从不\",\n \"没有\",\n \"除了\",\n \"排除\",\n // Japanese\n \"しないで\",\n \"避ける\",\n \"決して\",\n \"なしで\",\n \"除く\",\n // Russian\n \"не делай\",\n \"не надо\",\n \"нельзя\",\n \"избегать\",\n \"никогда\",\n \"без\",\n \"кроме\",\n \"исключить\",\n \"больше не\",\n // German\n \"nicht\",\n \"vermeide\",\n \"niemals\",\n \"ohne\",\n \"außer\",\n \"ausschließen\",\n \"nicht mehr\",\n // Spanish\n \"no hagas\",\n \"evitar\",\n \"nunca\",\n \"sin\",\n \"excepto\",\n \"excluir\",\n // Portuguese\n \"não faça\",\n \"evitar\",\n \"nunca\",\n \"sem\",\n \"exceto\",\n \"excluir\",\n // Korean\n \"하지 마\",\n \"피하다\",\n \"절대\",\n \"없이\",\n \"제외\",\n // Arabic\n \"لا تفعل\",\n \"تجنب\",\n \"أبداً\",\n \"بدون\",\n \"باستثناء\",\n \"استبعاد\",\n ],\n domainSpecificKeywords: [\n // English\n \"quantum\",\n \"fpga\",\n \"vlsi\",\n \"risc-v\",\n \"asic\",\n \"photonics\",\n \"genomics\",\n \"proteomics\",\n \"topological\",\n \"homomorphic\",\n \"zero-knowledge\",\n \"lattice-based\",\n // Chinese\n \"量子\",\n \"光子学\",\n \"基因组学\",\n \"蛋白质组学\",\n \"拓扑\",\n \"同态\",\n \"零知识\",\n \"格密码\",\n // Japanese\n \"量子\",\n \"フォトニクス\",\n \"ゲノミクス\",\n \"トポロジカル\",\n // Russian\n \"квантовый\",\n \"фотоника\",\n \"геномика\",\n \"протеомика\",\n \"топологический\",\n \"гомоморфный\",\n \"с нулевым разглашением\",\n \"на основе решёток\",\n // German\n \"quanten\",\n \"photonik\",\n \"genomik\",\n \"proteomik\",\n \"topologisch\",\n \"homomorph\",\n \"zero-knowledge\",\n \"gitterbasiert\",\n // Spanish\n \"cuántico\",\n \"fotónica\",\n \"genómica\",\n \"proteómica\",\n \"topológico\",\n \"homomórfico\",\n // Portuguese\n \"quântico\",\n \"fotônica\",\n \"genômica\",\n \"proteômica\",\n \"topológico\",\n \"homomórfico\",\n // Korean\n \"양자\",\n \"포토닉스\",\n \"유전체학\",\n \"위상\",\n \"동형\",\n // Arabic\n \"كمي\",\n \"ضوئيات\",\n \"جينوميات\",\n \"طوبولوجي\",\n \"تماثلي\",\n ],\n\n // Agentic task keywords - file ops, execution, multi-step, iterative work\n // Pruned: removed overly common words like \"then\", \"first\", \"run\", \"test\", \"build\"\n agenticTaskKeywords: [\n // English - File operations (clearly agentic)\n \"read file\",\n \"read the file\",\n \"look at\",\n \"check the\",\n \"open the\",\n \"edit\",\n \"modify\",\n \"update the\",\n \"change the\",\n \"write to\",\n \"create file\",\n // English - Execution (specific commands only)\n \"execute\",\n \"deploy\",\n \"install\",\n \"npm\",\n \"pip\",\n \"compile\",\n // English - Multi-step patterns (specific only)\n \"after that\",\n \"and also\",\n \"once done\",\n \"step 1\",\n \"step 2\",\n // English - Iterative work\n \"fix\",\n \"debug\",\n \"until it works\",\n \"keep trying\",\n \"iterate\",\n \"make sure\",\n \"verify\",\n \"confirm\",\n // Chinese (keep specific ones)\n \"读取文件\",\n \"查看\",\n \"打开\",\n \"编辑\",\n \"修改\",\n \"更新\",\n \"创建\",\n \"执行\",\n \"部署\",\n \"安装\",\n \"第一步\",\n \"第二步\",\n \"修复\",\n \"调试\",\n \"直到\",\n \"确认\",\n \"验证\",\n // Spanish\n \"leer archivo\",\n \"editar\",\n \"modificar\",\n \"actualizar\",\n \"ejecutar\",\n \"desplegar\",\n \"instalar\",\n \"paso 1\",\n \"paso 2\",\n \"arreglar\",\n \"depurar\",\n \"verificar\",\n // Portuguese\n \"ler arquivo\",\n \"editar\",\n \"modificar\",\n \"atualizar\",\n \"executar\",\n \"implantar\",\n \"instalar\",\n \"passo 1\",\n \"passo 2\",\n \"corrigir\",\n \"depurar\",\n \"verificar\",\n // Korean\n \"파일 읽기\",\n \"편집\",\n \"수정\",\n \"업데이트\",\n \"실행\",\n \"배포\",\n \"설치\",\n \"단계 1\",\n \"단계 2\",\n \"디버그\",\n \"확인\",\n // Arabic\n \"قراءة ملف\",\n \"تحرير\",\n \"تعديل\",\n \"تحديث\",\n \"تنفيذ\",\n \"نشر\",\n \"تثبيت\",\n \"الخطوة 1\",\n \"الخطوة 2\",\n \"إصلاح\",\n \"تصحيح\",\n \"تحقق\",\n ],\n\n // Dimension weights (sum to 1.0)\n dimensionWeights: {\n tokenCount: 0.08,\n codePresence: 0.15,\n reasoningMarkers: 0.18,\n technicalTerms: 0.1,\n creativeMarkers: 0.05,\n simpleIndicators: 0.02, // Reduced from 0.12 to make room for agenticTask\n multiStepPatterns: 0.12,\n questionComplexity: 0.05,\n imperativeVerbs: 0.03,\n constraintCount: 0.04,\n outputFormat: 0.03,\n referenceComplexity: 0.02,\n negationComplexity: 0.01,\n domainSpecificity: 0.02,\n agenticTask: 0.04, // Reduced - agentic signals influence tier selection, not dominate it\n },\n\n // Tier boundaries on weighted score axis\n tierBoundaries: {\n simpleMedium: 0.0,\n mediumComplex: 0.3, // Raised from 0.18 - prevent simple tasks from reaching expensive COMPLEX tier\n complexReasoning: 0.5, // Raised from 0.4 - reserve for true reasoning tasks\n },\n\n // Sigmoid steepness for confidence calibration\n confidenceSteepness: 12,\n // Below this confidence → ambiguous (null tier)\n confidenceThreshold: 0.7,\n },\n\n // ─── Tier chains ───\n //\n // Catalog refresh 2026-08-29 (V3.5). Every chain below names only models\n // the public catalog lists (GET https://blockrun.ai/api/v1/models). Ids the\n // gateway withholds (`hidden: true`) — kimi-k2.5/k2.6/k2.7, the grok-4-fast\n // and grok-4-1-fast pairs, grok-4-0709, claude-opus-4.6, gemini-3-pro-preview,\n // the whole `free/*` namespace — were removed everywhere, including fallback\n // rungs, so a routed model is always one a user can find on blockrun.ai/models.\n //\n // Primaries moved only where portfolio.ts already carries calibration\n // evidence for the successor (Sonnet 5 over Sonnet 4.6, GPT-5 Mini for\n // agentic MEDIUM, Gemini 3.5 Flash where Kimi K2.7 was). Newcomers with no\n // trajectory evidence yet (gemini-3.6-flash, glm-5.3, glm-5.3-flash,\n // gpt-5.6-luna, grok-4.3, minimax-m3, qwen3.7-plus) enter as fallback rungs;\n // promotion waits for a calibration run, because version recency is not a\n // quality signal.\n //\n // Latency figures in comments are the 2026-08-29 gateway probe\n // (model-profiles.generated.json); prices are the catalog list.\n\n // Auto (balanced) tier configs - current default smart routing\n tiers: {\n SIMPLE: {\n primary: \"google/gemini-2.5-flash\", // $0.30/$2.50 — 60% retention (best) in the 2026-03 run; still the fastest quality answer\n fallback: [\n \"google/gemini-3-flash-preview\", // $0.50/$3 — GPQA 5/6 in the 2026-07 calibration\n \"google/gemini-3.5-flash-lite\", // $0.30/$2.50, 1M ctx, thinking mode — same price as 2.5 Flash, newer generation\n \"deepseek/deepseek-chat\", // $0.14/$0.28, 1M ctx\n \"google/gemini-3.1-flash-lite\", // $0.25/$1.50, 1M ctx\n \"openai/gpt-5.6-luna\", // $0.20/$1.20, 1M ctx — GPT-5.6 cost tier (cut 2026-07-30)\n \"openai/gpt-5.4-nano\", // $0.20/$1.25, 1M ctx\n \"google/gemini-2.5-flash-lite\", // $0.10/$0.40\n \"nvidia/nemotron-3.5-lightning\", // FREE backstop — NVIDIA free tier (probed 2026-08-30)\n ],\n },\n MEDIUM: {\n // Was moonshot/kimi-k2.7 (hidden 2026-08). Gemini 3.5 Flash is the\n // calibrated successor: MGSM 5/5, GPQA 4/6, extraction band (portfolio.ts).\n primary: \"google/gemini-3.5-flash\", // $1.50/$9, 1M ctx, vision + tools\n fallback: [\n \"google/gemini-3.6-flash\", // $1.50/$7.50 — newest Flash, output 17% cheaper than 3.5; awaiting calibration\n \"zai/glm-5.3-flash\", // $0.15/$0.50, 1M ctx, vision + tools verified live 2026-08-27\n \"openai/gpt-5.6-terra\", // $2/$12, 1M ctx — GPT-5.6 balanced tier\n \"google/gemini-3-flash-preview\", // $0.50/$3\n \"deepseek/deepseek-chat\", // $0.14/$0.28\n \"google/gemini-2.5-flash\", // $0.30/$2.50\n \"minimax/minimax-m3\", // $0.30/$1.20, 1M ctx\n \"google/gemini-3.1-flash-lite\", // $0.25/$1.50\n \"openai/gpt-5.6-luna\", // $0.20/$1.20\n \"google/gemini-2.5-flash-lite\", // $0.10/$0.40\n ],\n },\n COMPLEX: {\n primary: \"google/gemini-3.1-pro\", // $2/$12 — proven long-context flagship (portfolio.ts long_context lead)\n fallback: [\n \"google/gemini-3.6-flash\", // $1.50/$7.50 — Pro-level quality at Flash price (Google's claim; uncalibrated here)\n \"google/gemini-3.5-flash\", // $1.50/$9 — calibrated\n \"anthropic/claude-sonnet-5\", // $3/$15 — near-Opus quality, tau2 + Terminal-Bench calibrated\n \"xai/grok-4.5\", // $2.50/$9 — 503-resistant, independent infra (was grok-4-0709, now hidden)\n \"google/gemini-2.5-pro\", // $1.25/$10\n \"anthropic/claude-sonnet-4.6\", // $3/$15\n \"openai/gpt-5.6-terra\", // $2/$12 — GPT-5.6 balanced tier (Sol excluded: #202)\n \"openai/gpt-5.5\", // $5/$30 — prior OpenAI flagship\n \"openai/gpt-5.4\", // $2.50/$15 — previous flagship, benchmarked\n \"zai/glm-5.3\", // $1.40/$4.40, 1M ctx, always-on thinking — verified live 2026-08-19\n \"moonshot/kimi-k3\", // $3/$15, 1M ctx — Moonshot flagship (K2.7 successor)\n \"deepseek/deepseek-v4-pro\", // $0.435/$0.87 — strongest open-weight reasoner\n \"deepseek/deepseek-chat\", // $0.14/$0.28 — cheap last resort\n \"google/gemini-2.5-flash\", // $0.30/$2.50\n ],\n },\n REASONING: {\n // Was xai/grok-4-1-fast-reasoning ($0.20/$0.50, hidden 2026-08). DeepSeek\n // Reasoner is the cheapest listed reasoner at the same 1M context.\n primary: \"deepseek/deepseek-reasoner\", // $0.14/$0.28, 1M ctx\n fallback: [\n \"deepseek/deepseek-v4-pro\", // $0.435/$0.87 — calibrated reasoning band 0.95\n \"xai/grok-4.3\", // $1.50/$4, 1M ctx — xAI reasoning model, vision\n \"qwen/qwen3.7-plus\", // $0.32/$1.28, 1M ctx — reasoning; needs a generous max_tokens (thinking is billed)\n \"google/gemini-3.5-flash\", // $1.50/$9 — MGSM 5/5\n \"openai/o4-mini\", // $1.10/$4.40\n \"openai/o3\", // $2/$8\n ],\n },\n },\n\n // Eco tier configs - absolute cheapest (blockrun/eco)\n ecoTiers: {\n SIMPLE: {\n primary: \"nvidia/nemotron-3.5-lightning\", // FREE — NVIDIA free tier flagship, 1M ctx\n fallback: [\n // Was nvidia/nemotron-3-nano-30b until blockrun delisted it on 2026-09-08\n // (NVIDIA deprovisioned it for the account — a structured per-account\n // 404). nano-omni is blockrun's own redirect target for that id, so this\n // follows the same rule as the head: the router and the gateway name the\n // same model.\n \"nvidia/nemotron-3-nano-omni-30b-a3b-reasoning\", // FREE — nano-30b's successor, 256K ctx\n // The free head keeps rotting with NVIDIA's hosting (deepseek-v4-flash\n // 410 2026-08-12, seed-oss-36b 410 2026-08-03, gpt-oss-120b/20b 400\n // 2026-08-21, and on 2026-08-30 FOUR of the five visible free models at\n // once — step-3.7-flash, nemotron-nano-9b-v2 and nemotron-nano-12b-v2-vl\n // all 410, mistral-nemotron hung). Each retirement retargets the two\n // free rungs to the current free tier; the paid rungs below never move.\n // The head follows blockrun's own redirect of the model it replaces, so\n // the router and the gateway never name different models.\n \"google/gemini-2.5-flash-lite\", // $0.10/$0.40 — cheapest paid rung\n \"zai/glm-5.3-flash\", // $0.15/$0.50, 1M ctx, vision + tools\n \"openai/gpt-5.6-luna\", // $0.20/$1.20, 1M ctx\n \"openai/gpt-5.4-nano\", // $0.20/$1.25\n \"google/gemini-3.1-flash-lite\", // $0.25/$1.50\n ],\n },\n MEDIUM: {\n primary: \"zai/glm-5.3-flash\", // $0.15/$0.50, 1M ctx, vision + tools verified live — cheapest full-capability model\n fallback: [\n \"deepseek/deepseek-chat\", // $0.14/$0.28\n \"google/gemini-3.1-flash-lite\", // $0.25/$1.50\n \"openai/gpt-5.6-luna\", // $0.20/$1.20\n \"openai/gpt-5.4-nano\", // $0.20/$1.25\n \"google/gemini-2.5-flash-lite\", // $0.10/$0.40\n \"google/gemini-2.5-flash\", // $0.30/$2.50\n ],\n },\n COMPLEX: {\n primary: \"zai/glm-5.3-flash\", // $0.15/$0.50, 1M ctx\n fallback: [\n \"deepseek/deepseek-chat\", // $0.14/$0.28, 1M ctx\n \"minimax/minimax-m3\", // $0.30/$1.20, 1M ctx\n \"deepseek/deepseek-v4-pro\", // $0.435/$0.87\n \"google/gemini-3.1-flash-lite\", // $0.25/$1.50\n \"google/gemini-2.5-flash\", // $0.30/$2.50\n ],\n },\n REASONING: {\n primary: \"deepseek/deepseek-reasoner\", // $0.14/$0.28, 1M ctx — cheapest listed reasoner\n fallback: [\n \"deepseek/deepseek-v4-pro\", // $0.435/$0.87\n \"qwen/qwen3.7-plus\", // $0.32/$1.28 — reasoning\n \"minimax/minimax-m3\", // $0.30/$1.20 — reasoning + coding\n \"zai/glm-5.3-flash\", // $0.15/$0.50 — reasoning tokens alongside content\n ],\n },\n },\n\n // Premium tier configs - best quality (blockrun/premium)\n // codex=complex coding, flash=simple coding, sonnet=reasoning/instructions, fable/opus=architecture/PM/audits\n premiumTiers: {\n SIMPLE: {\n // Was moonshot/kimi-k2.7 (hidden 2026-08).\n primary: \"google/gemini-3.5-flash\", // $1.50/$9, 1M ctx, vision + tools — calibrated\n fallback: [\n \"google/gemini-3.6-flash\", // $1.50/$7.50 — newest Flash\n \"anthropic/claude-haiku-4.5\", // $1/$5\n \"zai/glm-5.3\", // $1.40/$4.40, 1M ctx\n \"google/gemini-2.5-flash\", // $0.30/$2.50\n \"google/gemini-3.5-flash-lite\", // $0.30/$2.50\n \"deepseek/deepseek-chat\", // $0.14/$0.28\n ],\n },\n MEDIUM: {\n primary: \"openai/gpt-5.3-codex\", // $1.75/$14 - 400K context, 128K output — code_edit/debug lead (portfolio.ts)\n fallback: [\n \"anthropic/claude-sonnet-5\", // $3/$15 — code_agent band 0.98\n \"moonshot/kimi-k3\", // $3/$15, 1M ctx — Moonshot flagship\n \"zai/glm-5.3\", // $1.40/$4.40 — long-horizon coding\n \"google/gemini-3.6-flash\", // $1.50/$7.50\n \"google/gemini-3.5-flash\", // $1.50/$9\n \"google/gemini-2.5-pro\", // $1.25/$10\n \"xai/grok-4.5\", // $2.50/$9\n \"anthropic/claude-sonnet-4.6\", // $3/$15\n \"openai/gpt-5.6-terra\", // $2/$12\n ],\n },\n COMPLEX: {\n // fable-5 was promoted here 2026-06-11, force-reverted 2026-06-13 when Anthropic\n // withdrew the offer, and restored 2026-07-14 now that BlockRun has relisted it.\n primary: \"anthropic/claude-fable-5\", // Best quality for complex tasks — Mythos-class flagship above Opus ($10/$50, 1M ctx, always-on thinking)\n // Fallback chain de-Gemini'd 2026-04-22: when Anthropic 503s, Gemini is\n // also prone to \"high demand\" 503s (correlated failure — everyone falls\n // back to Google at the same time). Prefer in-family → xAI → Moonshot →\n // OpenAI flagship → Z.AI → DeepSeek → NVIDIA free instead.\n fallback: [\n \"anthropic/claude-opus-5\", // in-family hot swap first (half the price, 1M ctx + adaptive thinking)\n \"anthropic/claude-opus-4.8\", // in-family hot swap (identical cost to 5)\n \"anthropic/claude-opus-4.7\", // in-family hot swap (identical cost to 4.8)\n \"anthropic/claude-sonnet-5\", // Sonnet-tier drop-down, near-Opus quality\n \"anthropic/claude-sonnet-4.6\",\n \"xai/grok-4.5\", // xAI flagship — 503-resistant, direct-xAI SKU\n \"moonshot/kimi-k3\", // Moonshot flagship, independent infra\n \"openai/gpt-5.6-terra\", // GPT-5.6 balanced tier — stable (Sol excluded: #202)\n \"openai/gpt-5.5\", // Prior OpenAI flagship — 1M+ ctx, native agent + computer use\n \"openai/gpt-5.4\", // Previous flagship (slow but stable, benchmarked at 6,213ms)\n \"openai/gpt-5.3-codex\",\n \"zai/glm-5.3\", // Z.AI flagship, 1M ctx\n \"deepseek/deepseek-v4-pro\", // strongest open-weight reasoner\n \"deepseek/deepseek-chat\", // Cheap, reliable\n \"nvidia/nemotron-3.5-lightning\", // NVIDIA free ultimate backstop\n ],\n },\n REASONING: {\n // Sonnet 5 promoted over Sonnet 4.6 (same price; reasoning band 0.98 for both,\n // plus Sonnet 5's tau2/BrowseComp trajectory evidence).\n primary: \"anthropic/claude-sonnet-5\", // $3/$15, 1M ctx, adaptive thinking\n fallback: [\n \"anthropic/claude-sonnet-4.6\", // in-family hot swap — same cost\n \"anthropic/claude-opus-5\", // Newest flagship Opus w/ adaptive thinking\n \"anthropic/claude-opus-4.8\", // Prior flagship Opus — identical cost to 5\n \"anthropic/claude-opus-4.7\", // Flagship Opus w/ adaptive thinking\n \"xai/grok-4.5\", // reasoning band 0.94\n \"deepseek/deepseek-v4-pro\", // reasoning band 0.95\n \"xai/grok-4.3\", // $1.50/$4 — xAI reasoning model\n \"openai/o4-mini\", // $1.10/$4.40\n \"openai/o3\", // $2/$8\n ],\n },\n },\n\n // Agentic tier configs - models that excel at multi-step autonomous tasks\n agenticTiers: {\n SIMPLE: {\n primary: \"openai/gpt-4o-mini\", // $0.15/$0.60 - best tool compliance at lowest cost\n fallback: [\n \"openai/gpt-5.6-luna\", // $0.20/$1.20 — lightweight agentic tier of GPT-5.6\n \"zai/glm-5.3-flash\", // $0.15/$0.50 — tool calls verified live 2026-08-27\n \"anthropic/claude-haiku-4.5\", // $1/$5\n \"google/gemini-2.5-flash\", // $0.30/$2.50\n ],\n },\n MEDIUM: {\n // Was moonshot/kimi-k2.7 (hidden 2026-08). GPT-5 Mini carries the\n // Terminal-Bench and tau2 trajectory evidence in portfolio.ts.\n primary: \"openai/gpt-5-mini\", // $0.25/$2 — 4/7 Terminal-Bench, 5/6 tau2 airline\n fallback: [\n \"google/gemini-3.5-flash\", // $1.50/$9 — tool_agent band 0.88\n \"zai/glm-5.3-flash\", // $0.15/$0.50 — tools verified\n \"openai/gpt-5.6-terra\", // $2/$12\n \"openai/gpt-4o-mini\", // $0.15/$0.60 — reliable tool calling\n \"anthropic/claude-haiku-4.5\", // $1/$5\n \"deepseek/deepseek-chat\", // $0.14/$0.28\n \"moonshot/kimi-k3\", // $3/$15 — tool_agent band 0.85\n ],\n },\n COMPLEX: {\n // Sonnet 5 promoted over Sonnet 4.6: tau2 airline + retail reward 1.0,\n // Terminal-Bench safety band lead (portfolio.ts).\n primary: \"anthropic/claude-sonnet-5\", // $3/$15 — best agentic quality per trajectory evidence\n // Fallback chain de-Gemini'd 2026-04-22: Gemini's \"high demand\" 503s\n // correlate with Anthropic outages (everyone falls back together).\n // Prefer 503-resistant providers first.\n fallback: [\n \"anthropic/claude-sonnet-4.6\", // in-family hot swap — same cost\n \"anthropic/claude-opus-5\", // Newest flagship Opus — in-family hot swap\n \"anthropic/claude-opus-4.8\", // Prior flagship Opus — identical cost to 5\n \"anthropic/claude-opus-4.7\", // Flagship Opus — in-family hot swap\n \"xai/grok-4.5\", // xAI flagship — strong tool use, independent infra\n \"moonshot/kimi-k3\", // Moonshot flagship — independent infra\n \"openai/gpt-5.6-terra\", // GPT-5.6 balanced tier — stable (Sol excluded: #202)\n \"openai/gpt-5.5\", // Prior flagship — native agent + computer use (exactly the agentic-tier use case)\n \"openai/gpt-5.4\", // Previous flagship — reliable\n \"openai/gpt-5.3-codex\", // code_agent lead\n \"zai/glm-5.3\", // long-horizon coding\n \"deepseek/deepseek-v4-pro\", // retail high-risk 3/3\n \"deepseek/deepseek-chat\", // cheap, reliable\n \"nvidia/nemotron-3.5-lightning\", // NVIDIA free ultimate backstop\n ],\n },\n REASONING: {\n primary: \"anthropic/claude-sonnet-5\", // $3/$15 — strong tool use + adaptive thinking\n fallback: [\n \"anthropic/claude-sonnet-4.6\", // in-family hot swap — same cost\n \"anthropic/claude-opus-5\", // Newest flagship Opus w/ adaptive thinking\n \"anthropic/claude-opus-4.8\", // Prior flagship Opus — identical cost to 5\n \"anthropic/claude-opus-4.7\", // Flagship Opus w/ adaptive thinking\n \"xai/grok-4.5\", // reasoning band 0.94\n \"deepseek/deepseek-v4-pro\", // reasoning band 0.95\n \"deepseek/deepseek-reasoner\", // $0.14/$0.28\n ],\n },\n },\n\n // Time-windowed promotions — auto-applied when active, ignored when expired.\n // The GLM-5.1 launch promo (2026-04-01 → 2026-05-01) was the last entry and\n // has expired; the list is kept empty so the mechanism stays wired.\n promotions: [],\n\n overrides: {\n maxTokensForceComplex: 100_000,\n structuredOutputMinTier: \"MEDIUM\",\n ambiguousDefaultTier: \"MEDIUM\",\n // agenticMode left undefined → auto-detect via tools/agenticScore.\n // Set to `true` to force agentic tiers; `false` to disable them entirely.\n },\n};\n","/**\n * Smart Router Entry Point\n *\n * Classifies requests and routes to the cheapest capable model.\n * Delegates to pluggable RouterStrategy (default: RulesStrategy, <1ms).\n */\n\nimport type { RoutingDecision, RouterOptions } from \"./types.js\";\nimport { getStrategy, registerStrategy } from \"./strategy.js\";\nimport { PortfolioStrategy } from \"./portfolio.js\";\n\n// Register here instead of strategy.ts so PortfolioStrategy can reuse the\n// stable RulesStrategy without introducing a module cycle.\nregisterStrategy(new PortfolioStrategy());\n\n/**\n * Route a request to the cheapest capable model.\n * Delegates to the configured strategy (PortfolioStrategy by default).\n */\nexport function route(\n prompt: string,\n systemPrompt: string | undefined,\n maxOutputTokens: number,\n options: RouterOptions,\n): RoutingDecision {\n const strategy = getStrategy(options.config.strategy ?? \"portfolio\");\n return strategy.route(prompt, systemPrompt, maxOutputTokens, options);\n}\n\nexport { getStrategy, registerStrategy, applyUnavailableModels } from \"./strategy.js\";\nexport { RulesStrategy } from \"./strategy.js\";\nexport { PortfolioStrategy } from \"./portfolio.js\";\nexport { classifyByRules } from \"./rules.js\";\nexport { inferToolRequirement } from \"./tool-intent.js\";\nexport { estimateTokens } from \"./tokens.js\";\nexport { MODEL_KINDS, parseModelCatalog, toRoutingCatalog } from \"./catalog.js\";\nexport type {\n ModelKind, CatalogPricing, CatalogModel, ModelCatalog, CatalogRoutingOptions, RoutingCatalog,\n} from \"./catalog.js\";\nexport {\n getFallbackChain,\n getFallbackChainFiltered,\n filterByToolCalling,\n filterByVision,\n filterByExcludeList,\n filterCandidatesByCapacity,\n calculateModelCost,\n} from \"./selector.js\";\nexport { DEFAULT_ROUTING_CONFIG } from \"./config.js\";\nexport { DEFAULT_MODEL_CAPABILITIES } from \"./model-capabilities.js\";\nexport { LIVE_MODEL_PROFILES, HISTORICAL_MODEL_PROFILES } from \"./model-profiles.js\";\nexport type {\n RoutingDecision,\n Tier,\n TaskType,\n RoutingConfig,\n RouterOptions,\n RouterStrategy,\n} from \"./types.js\";\nexport type { ModelPricing } from \"./selector.js\";\nexport type { ModelCapabilities } from \"./model-capabilities.js\";\nexport type { ModelPerformanceProfile } from \"./model-profiles.js\";\n"],"mappings":";AAiCA,IAAM,qBACJ;AACF,IAAM,YAAY;AAClB,IAAM,eAAe;AAIrB,IAAM,sBAAsB;AAC5B,IAAM,kBAAkB,QAAQ,mBAAmB;AACnD,IAAM,iBAAiB,OAAO,mB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O;AACtE;","names":["confidence","decision","price","model"]} \ No newline at end of file +{"version":3,"sources":["../src/rules.ts","../src/selector.ts","../src/tokens.ts","../src/strategy.ts","../src/config.ts","../src/model-capabilities.ts","../src/model-profiles.generated.json","../src/model-profiles.ts","../src/tool-intent.ts","../src/portfolio.ts","../src/catalog.ts","../src/index.ts"],"sourcesContent":["/**\n * Rule-Based Classifier (v2 — Weighted Scoring)\n *\n * Scores a request across 15 weighted dimensions and maps the aggregate\n * score to a tier using configurable boundaries. Confidence is calibrated\n * via sigmoid — low confidence triggers the fallback classifier.\n *\n * Handles 70-80% of requests in < 1ms with zero cost.\n */\n\nimport type { Tier, ScoringResult, ScoringConfig } from \"./types.js\";\n\ntype DimensionScore = { name: string; score: number; signal: string | null };\n\n// ─── Keyword Matching ───\n//\n// A plain substring test counted `class` in \"classic\", `story` in \"history\",\n// `edit` in \"credit\" and `fix` in \"prefix\", so everyday prose picked up code,\n// creative and agentic signals it did not carry. Alphabetic keywords now have\n// to start at a word boundary. Short ASCII keywords additionally have to end\n// at one, after an optional inflection, graded by how much a stray suffix can\n// change the word: a three-letter keyword takes only the English endings that\n// cannot spell another word (fix → fixes, never pip → pipe or def → defer); a\n// four-to-six-letter keyword also takes the common German and Romance endings,\n// because the lists spell those languages in ASCII too (beweis → beweise,\n// klasse → klassen); anything longer stays trailing-open like the substring\n// test it replaces, since its false-positive surface is small and its\n// inflection surface is large. Non-ASCII alphabetic keywords keep a\n// trailing-open match because several are deliberate stems (`оптимизаци`,\n// `рассуждени`). CJK, Hangul and Arabic keywords keep the substring test:\n// those scripts have no word boundaries, or attach particles and articles\n// directly to the word.\n\nconst UNSEGMENTED_SCRIPT =\n /[؀-ۿ -ヿ㐀-䶿一-鿿가-힯豈-﫿＀-￯]/;\nconst WORD_CHAR = /[\\p{L}\\p{N}]/u;\nconst ASCII_PHRASE = /^[a-z0-9' -]+$/;\n// A word boundary is a transition out of the segmented scripts. A CJK\n// character next to a Latin keyword (\"请step by step证明\") is a boundary, not\n// part of the word: mixed-script prompts carry no spaces between scripts.\nconst SEGMENTED_WORD_CHAR = \"\\\\p{Script=Latin}\\\\p{Script=Cyrillic}\\\\p{Script=Greek}\\\\p{N}\";\nconst BOUNDARY_BEFORE = `(?();\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction keywordMatcher(keyword: string): KeywordMatcher {\n const cached = matcherCache.get(keyword);\n if (cached) return cached;\n\n const kw = keyword.toLowerCase();\n let matcher: KeywordMatcher;\n if (UNSEGMENTED_SCRIPT.test(kw) || kw.length === 0) {\n matcher = { needle: kw, pattern: null };\n } else {\n const lead = WORD_CHAR.test(kw[0]) ? BOUNDARY_BEFORE : \"\";\n const escaped = escapeRegExp(kw);\n let body = escaped;\n let trail = \"\";\n let needle = kw;\n const lastWord = kw.slice(kw.lastIndexOf(\" \") + 1);\n if (\n WORD_CHAR.test(kw[kw.length - 1]) &&\n ASCII_PHRASE.test(kw) &&\n lastWord.length <= BOUNDED_LAST_WORD_LENGTH\n ) {\n // ASCII phrases contain no regex metacharacters, so `escaped` slices\n // align with `kw` slices below.\n const forms: string[] = [];\n if (/\\d$/.test(kw)) {\n // \"step 1\" must not absorb \"step 10\".\n forms.push(escaped);\n } else if (lastWord.length <= 3) {\n forms.push(`${escaped}${SHORT_SUFFIXES}`);\n if (/(?:x|s|z|ch|sh)$/.test(kw)) forms.push(`${escaped}${SIBILANT_PLURAL}`);\n } else {\n forms.push(`${escaped}${MID_SUFFIXES}`);\n if (kw.endsWith(\"e\")) {\n forms.push(`${escaped.slice(0, -1)}${DROPPED_E_SUFFIXES}`);\n needle = kw.slice(0, -1);\n } else if (kw.endsWith(\"y\")) {\n forms.push(`${escaped.slice(0, -1)}(?:ies|ied)`);\n needle = kw.slice(0, -1);\n } else if (/[aeiou][bdgmnprt]$/.test(kw)) {\n // debug → debugging, plan → planned\n forms.push(`${escaped}${kw[kw.length - 1]}${DOUBLED_CONSONANT_SUFFIXES}`);\n }\n }\n body = `(?:${forms.join(\"|\")})`;\n trail = BOUNDARY_AFTER;\n }\n matcher = { needle, pattern: new RegExp(`${lead}${body}${trail}`, \"u\") };\n }\n matcherCache.set(keyword, matcher);\n return matcher;\n}\n\n/** Whether lower-cased `text` contains `keyword` as a word (or as a substring for CJK). */\nfunction matchesKeyword(text: string, keyword: string): boolean {\n const { needle, pattern } = keywordMatcher(keyword);\n if (!text.includes(needle)) return false;\n return pattern === null ? true : pattern.test(text);\n}\n\n// ─── Dimension Scorers ───\n// Each returns a score in [-1, 1] and an optional signal string.\n\nfunction scoreTokenCount(\n estimatedTokens: number,\n thresholds: { simple: number; complex: number },\n): DimensionScore {\n if (estimatedTokens < thresholds.simple) {\n return { name: \"tokenCount\", score: -1.0, signal: `short (${estimatedTokens} tokens)` };\n }\n if (estimatedTokens > thresholds.complex) {\n return { name: \"tokenCount\", score: 1.0, signal: `long (${estimatedTokens} tokens)` };\n }\n return { name: \"tokenCount\", score: 0, signal: null };\n}\n\nfunction scoreKeywordMatch(\n text: string,\n keywords: string[],\n name: string,\n signalLabel: string,\n thresholds: { low: number; high: number },\n scores: { none: number; low: number; high: number },\n): DimensionScore {\n const matches = keywords.filter((kw) => matchesKeyword(text, kw));\n if (matches.length >= thresholds.high) {\n return {\n name,\n score: scores.high,\n signal: `${signalLabel} (${matches.slice(0, 3).join(\", \")})`,\n };\n }\n if (matches.length >= thresholds.low) {\n return {\n name,\n score: scores.low,\n signal: `${signalLabel} (${matches.slice(0, 3).join(\", \")})`,\n };\n }\n return { name, score: scores.none, signal: null };\n}\n\nfunction scoreMultiStep(text: string): DimensionScore {\n // A numbered list item must start a line: a bare \"\\d\\.\\s\" also matched\n // every sentence that ends in a number (\"born in 1990. How old…\").\n const patterns = [/first.*then/i, /step \\d/i, /(?:^|\\n)\\s*\\d+[.)]\\s/];\n const hits = patterns.filter((p) => p.test(text));\n if (hits.length > 0) {\n return { name: \"multiStepPatterns\", score: 0.5, signal: \"multi-step\" };\n }\n return { name: \"multiStepPatterns\", score: 0, signal: null };\n}\n\nfunction scoreQuestionComplexity(prompt: string): DimensionScore {\n const count = (prompt.match(/[??]/g) || []).length;\n if (count > 3) {\n return { name: \"questionComplexity\", score: 0.5, signal: `${count} questions` };\n }\n return { name: \"questionComplexity\", score: 0, signal: null };\n}\n\n/**\n * Score agentic task indicators.\n * Returns agenticScore (0-1) based on keyword matches:\n * - 4+ matches = 1.0 (high agentic)\n * - 3 matches = 0.6 (moderate agentic, triggers auto-agentic mode)\n * - 1-2 matches = 0.2 (low agentic)\n *\n * Thresholds raised because common keywords were pruned from the list.\n */\nfunction scoreAgenticTask(\n text: string,\n keywords: string[],\n): { dimensionScore: DimensionScore; agenticScore: number } {\n let matchCount = 0;\n const signals: string[] = [];\n\n for (const keyword of keywords) {\n if (matchesKeyword(text, keyword)) {\n matchCount++;\n if (signals.length < 3) {\n signals.push(keyword);\n }\n }\n }\n\n // Threshold-based scoring (raised thresholds after keyword pruning)\n if (matchCount >= 4) {\n return {\n dimensionScore: {\n name: \"agenticTask\",\n score: 1.0,\n signal: `agentic (${signals.join(\", \")})`,\n },\n agenticScore: 1.0,\n };\n } else if (matchCount >= 3) {\n return {\n dimensionScore: {\n name: \"agenticTask\",\n score: 0.6,\n signal: `agentic (${signals.join(\", \")})`,\n },\n agenticScore: 0.6,\n };\n } else if (matchCount >= 1) {\n return {\n dimensionScore: {\n name: \"agenticTask\",\n score: 0.2,\n signal: `agentic-light (${signals.join(\", \")})`,\n },\n agenticScore: 0.2,\n };\n }\n\n return {\n dimensionScore: { name: \"agenticTask\", score: 0, signal: null },\n agenticScore: 0,\n };\n}\n\n// ─── Main Classifier ───\n\nexport function classifyByRules(\n prompt: string,\n systemPrompt: string | undefined,\n estimatedTokens: number,\n config: ScoringConfig,\n): ScoringResult {\n // Score against user prompt only — system prompts contain boilerplate keywords\n // (tool definitions, skill descriptions, behavioral rules) that dominate scoring\n // and make every request score identically. See GitHub issue #50.\n const userText = prompt.toLowerCase();\n\n const reasoningDimension = scoreKeywordMatch(\n userText,\n config.reasoningKeywords,\n \"reasoningMarkers\",\n \"reasoning\",\n { low: 1, high: 2 },\n { none: 0, low: 0.7, high: 1.0 },\n );\n\n // Score the base dimensions against user text only; the agentic dimension is\n // appended below, so the scored total is one more than this list.\n const dimensions: DimensionScore[] = [\n // Token count uses total estimated tokens (system + user) — context size matters for model selection\n scoreTokenCount(estimatedTokens, config.tokenCountThresholds),\n scoreKeywordMatch(\n userText,\n config.codeKeywords,\n \"codePresence\",\n \"code\",\n { low: 1, high: 2 },\n { none: 0, low: 0.5, high: 1.0 },\n ),\n reasoningDimension,\n scoreKeywordMatch(\n userText,\n config.technicalKeywords,\n \"technicalTerms\",\n \"technical\",\n { low: 2, high: 4 },\n { none: 0, low: 0.5, high: 1.0 },\n ),\n scoreKeywordMatch(\n userText,\n config.creativeKeywords,\n \"creativeMarkers\",\n \"creative\",\n { low: 1, high: 2 },\n { none: 0, low: 0.5, high: 0.7 },\n ),\n scoreKeywordMatch(\n userText,\n config.simpleKeywords,\n \"simpleIndicators\",\n \"simple\",\n { low: 1, high: 2 },\n { none: 0, low: -1.0, high: -1.0 },\n ),\n scoreMultiStep(userText),\n scoreQuestionComplexity(prompt),\n\n // 6 new dimensions\n scoreKeywordMatch(\n userText,\n config.imperativeVerbs,\n \"imperativeVerbs\",\n \"imperative\",\n { low: 1, high: 2 },\n { none: 0, low: 0.3, high: 0.5 },\n ),\n scoreKeywordMatch(\n userText,\n config.constraintIndicators,\n \"constraintCount\",\n \"constraints\",\n { low: 1, high: 3 },\n { none: 0, low: 0.3, high: 0.7 },\n ),\n scoreKeywordMatch(\n userText,\n config.outputFormatKeywords,\n \"outputFormat\",\n \"format\",\n { low: 1, high: 2 },\n { none: 0, low: 0.4, high: 0.7 },\n ),\n scoreKeywordMatch(\n userText,\n config.referenceKeywords,\n \"referenceComplexity\",\n \"references\",\n { low: 1, high: 2 },\n { none: 0, low: 0.3, high: 0.5 },\n ),\n scoreKeywordMatch(\n userText,\n config.negationKeywords,\n \"negationComplexity\",\n \"negation\",\n { low: 2, high: 3 },\n { none: 0, low: 0.3, high: 0.5 },\n ),\n scoreKeywordMatch(\n userText,\n config.domainSpecificKeywords,\n \"domainSpecificity\",\n \"domain-specific\",\n { low: 1, high: 2 },\n { none: 0, low: 0.5, high: 0.8 },\n ),\n ];\n\n // Score agentic task indicators — user prompt only\n // System prompt describes assistant behavior, not user's intent.\n // e.g. a coding assistant system prompt with \"edit files\" / \"fix bugs\" should NOT\n // force every request into agentic mode.\n const agenticResult = scoreAgenticTask(userText, config.agenticTaskKeywords);\n dimensions.push(agenticResult.dimensionScore);\n const agenticScore = agenticResult.agenticScore;\n\n // Collect signals\n const signals = dimensions.filter((d) => d.signal !== null).map((d) => d.signal!);\n\n // Compute weighted score\n const weights = config.dimensionWeights;\n let weightedScore = 0;\n for (const d of dimensions) {\n const w = weights[d.name] ?? 0;\n weightedScore += d.score * w;\n }\n\n // Direct reasoning override: 2+ reasoning markers in the USER prompt = high\n // confidence REASONING. The system prompt is never read here, so a host\n // instruction like \"think step by step\" cannot lift every query to REASONING.\n // The reasoning dimension already counted those matches; its score is 1.0\n // exactly when two or more matched.\n if (reasoningDimension.score === 1.0) {\n const confidence = calibrateConfidence(\n Math.max(weightedScore, 0.3), // ensure positive for confidence calc\n config.confidenceSteepness,\n );\n return {\n score: weightedScore,\n tier: \"REASONING\",\n confidence: Math.max(confidence, 0.85),\n signals,\n agenticScore,\n dimensions,\n };\n }\n\n // Map weighted score to tier using boundaries\n const { simpleMedium, mediumComplex, complexReasoning } = config.tierBoundaries;\n let tier: Tier;\n let distanceFromBoundary: number;\n\n if (weightedScore < simpleMedium) {\n tier = \"SIMPLE\";\n distanceFromBoundary = simpleMedium - weightedScore;\n } else if (weightedScore < mediumComplex) {\n tier = \"MEDIUM\";\n distanceFromBoundary = Math.min(weightedScore - simpleMedium, mediumComplex - weightedScore);\n } else if (weightedScore < complexReasoning) {\n tier = \"COMPLEX\";\n distanceFromBoundary = Math.min(\n weightedScore - mediumComplex,\n complexReasoning - weightedScore,\n );\n } else {\n tier = \"REASONING\";\n distanceFromBoundary = weightedScore - complexReasoning;\n }\n\n // Calibrate confidence via sigmoid of distance from nearest boundary\n const confidence = calibrateConfidence(distanceFromBoundary, config.confidenceSteepness);\n\n // If confidence is below threshold → ambiguous\n if (confidence < config.confidenceThreshold) {\n return { score: weightedScore, tier: null, confidence, signals, agenticScore, dimensions };\n }\n\n return { score: weightedScore, tier, confidence, signals, agenticScore, dimensions };\n}\n\n/**\n * Sigmoid confidence calibration.\n * Maps distance from tier boundary to [0.5, 1.0] confidence range.\n */\nfunction calibrateConfidence(distance: number, steepness: number): number {\n return 1 / (1 + Math.exp(-steepness * distance));\n}\n","/**\n * Tier → Model Selection\n *\n * Maps a classification tier to the cheapest capable model.\n * Builds RoutingDecision metadata with cost estimates and savings.\n */\n\nimport type { Tier, TierConfig, RoutingDecision } from \"./types.js\";\n\nexport type ModelPricing = {\n inputPrice: number; // per 1M tokens\n outputPrice: number; // per 1M tokens\n /** Active promo flat price per request (overrides token-based pricing when set) */\n flatPrice?: number;\n};\n\n// The savings baseline is a price anchor, not \"the current flagship\" — it is\n// deliberately NOT bumped every time a new Opus ships. Opus 4.7, 4.8 and 5 all\n// bill $5/$25, so moving it would change no reported number while breaking\n// comparability with historical journal entries. Only move it if the Opus tier\n// itself is repriced.\nconst BASELINE_MODEL_ID = \"anthropic/claude-opus-4.7\";\n\n// Hardcoded fallback: Claude Opus 4.7 pricing (per 1M tokens)\n// Used when baseline model not found in dynamic pricing map\nconst BASELINE_INPUT_PRICE = 5.0;\nconst BASELINE_OUTPUT_PRICE = 25.0;\n\n/**\n * The pricing entry, or undefined when any field it carries is not a finite,\n * non-negative number. A hand-built price map with a NaN would otherwise put\n * NaN into costEstimate and savings; a malformed price is an unknown price.\n */\nexport function usablePricing(pricing: ModelPricing | undefined): ModelPricing | undefined {\n if (!pricing) return undefined;\n const ok = (value: number | undefined) =>\n value === undefined || (Number.isFinite(value) && value >= 0);\n if (pricing.flatPrice !== undefined) return ok(pricing.flatPrice) ? pricing : undefined;\n return ok(pricing.inputPrice) && ok(pricing.outputPrice) ? pricing : undefined;\n}\n\n/** Raw token cost (no margin, no floor), or the flat promo price when one is set. */\nfunction rawCost(\n pricing: ModelPricing | undefined,\n estimatedInputTokens: number,\n maxOutputTokens: number,\n): number {\n if (pricing?.flatPrice !== undefined) return pricing.flatPrice;\n const inputPrice = pricing?.inputPrice ?? 0;\n const outputPrice = pricing?.outputPrice ?? 0;\n return (estimatedInputTokens / 1_000_000) * inputPrice + (maxOutputTokens / 1_000_000) * outputPrice;\n}\n\n/** What the anchor Opus tier would cost for the same request (see BASELINE_MODEL_ID). */\nfunction baselineCostFor(\n modelPricing: Map,\n estimatedInputTokens: number,\n maxOutputTokens: number,\n): number {\n const opusPricing = usablePricing(modelPricing.get(BASELINE_MODEL_ID));\n const inputPrice = opusPricing?.inputPrice ?? BASELINE_INPUT_PRICE;\n const outputPrice = opusPricing?.outputPrice ?? BASELINE_OUTPUT_PRICE;\n return (estimatedInputTokens / 1_000_000) * inputPrice + (maxOutputTokens / 1_000_000) * outputPrice;\n}\n\n/**\n * Fractional savings against the baseline. Premium reports none (it is about\n * quality, not cost), and a model the host has no price for costs an unknown\n * amount, not nothing: reporting its savings as 100% would be a fabricated\n * figure.\n */\nfunction savingsFor(\n costEstimate: number,\n baselineCost: number,\n pricing: ModelPricing | undefined,\n routingProfile: string | undefined,\n): number {\n if (routingProfile === \"premium\" || pricing === undefined || !(baselineCost > 0)) return 0;\n return Math.max(0, (baselineCost - costEstimate) / baselineCost);\n}\n\n/**\n * Select the primary model for a tier and build the RoutingDecision.\n *\n * Cost contract: the estimates here are raw token economics — no server\n * margin, no minimum-payment floor. `calculateModelCost` below applies both\n * to match the actual x402 charge, and hosts that display money (ClawRouter's\n * proxy does) recompute through it rather than reading these fields. Folding\n * the margin in here would double-apply it in every such host.\n */\nexport function selectModel(\n tier: Tier,\n confidence: number,\n method: \"rules\" | \"llm\" | \"portfolio\",\n reasoning: string,\n tierConfigs: Record,\n modelPricing: Map,\n estimatedInputTokens: number,\n maxOutputTokens: number,\n routingProfile?: \"free\" | \"eco\" | \"auto\" | \"premium\",\n agenticScore?: number,\n): RoutingDecision {\n const tierConfig = tierConfigs[tier];\n const model = tierConfig.primary;\n const pricing = usablePricing(modelPricing.get(model));\n\n const costEstimate = rawCost(pricing, estimatedInputTokens, maxOutputTokens);\n const baselineCost = baselineCostFor(modelPricing, estimatedInputTokens, maxOutputTokens);\n const savings = savingsFor(costEstimate, baselineCost, pricing, routingProfile);\n\n return {\n model,\n tier,\n confidence,\n method,\n reasoning,\n costEstimate,\n baselineCost,\n savings,\n ...(agenticScore !== undefined && { agenticScore }),\n };\n}\n\n/**\n * Get the ordered fallback chain for a tier: [primary, ...fallbacks].\n */\nexport function getFallbackChain(tier: Tier, tierConfigs: Record): string[] {\n const config = tierConfigs[tier];\n return [config.primary, ...config.fallback];\n}\n\n// Server-side margin applied to all x402 payments (must match blockrun server's MARGIN_PERCENT)\nconst SERVER_MARGIN_PERCENT = 5;\n// Minimum payment enforced by CDP Facilitator (must match blockrun server's MIN_PAYMENT_USD)\nconst MIN_PAYMENT_USD = 0.001;\n\n/**\n * Calculate charge-accurate cost fields for a specific model (server margin\n * and minimum-payment floor included — see the cost contract on selectModel).\n * Hosts call this to display money and to recost a decision after a fallback.\n */\nexport function calculateModelCost(\n model: string,\n modelPricing: Map,\n estimatedInputTokens: number,\n maxOutputTokens: number,\n routingProfile?: \"free\" | \"eco\" | \"auto\" | \"premium\",\n): { costEstimate: number; baselineCost: number; savings: number } {\n const pricing = usablePricing(modelPricing.get(model));\n\n // Server margin + minimum payment, to match the actual x402 charge.\n const costEstimate = Math.max(\n rawCost(pricing, estimatedInputTokens, maxOutputTokens) * (1 + SERVER_MARGIN_PERCENT / 100),\n MIN_PAYMENT_USD,\n );\n const baselineCost = baselineCostFor(modelPricing, estimatedInputTokens, maxOutputTokens);\n const savings = savingsFor(costEstimate, baselineCost, pricing, routingProfile);\n\n return { costEstimate, baselineCost, savings };\n}\n\n/** The models satisfying `keep`, or every model when none does. */\nfunction keepOrFailOpen(models: string[], keep: (modelId: string) => boolean): string[] {\n const filtered = models.filter(keep);\n return filtered.length > 0 ? filtered : models;\n}\n\n/**\n * Filter a model list to only those that support tool calling.\n * When hasTools is false, returns the list unchanged.\n * When all models lack tool calling support, returns the full list as a fallback\n * (better to let the API error than produce an empty chain).\n */\nexport function filterByToolCalling(\n models: string[],\n hasTools: boolean,\n supportsToolCalling: (modelId: string) => boolean,\n): string[] {\n return hasTools ? keepOrFailOpen(models, supportsToolCalling) : models;\n}\n\n/**\n * Filter a model list to only those that support vision (image inputs).\n * When hasVision is false, returns the list unchanged.\n * When all models lack vision support, returns the full list as a fallback\n * (better to let the API error than produce an empty chain).\n */\nexport function filterByVision(\n models: string[],\n hasVision: boolean,\n supportsVision: (modelId: string) => boolean,\n): string[] {\n return hasVision ? keepOrFailOpen(models, supportsVision) : models;\n}\n\n/**\n * Filter a model list to remove user-excluded models.\n * When all models are excluded, returns the full list as a fallback\n * (same safety pattern as filterByToolCalling/filterByVision).\n */\nexport function filterByExcludeList(models: string[], excludeList: Set): string[] {\n if (excludeList.size === 0) return models;\n return keepOrFailOpen(models, (m) => !excludeList.has(m));\n}\n\n/**\n * Get the fallback chain filtered by context length.\n * Only returns models that can handle the estimated total context.\n *\n * @param tier - The tier to get fallback chain for\n * @param tierConfigs - Tier configurations\n * @param estimatedTotalTokens - Estimated total context (input + output)\n * @param getContextWindow - Function to get context window for a model ID\n * @returns Filtered list of models that can handle the context\n */\nexport function getFallbackChainFiltered(\n tier: Tier,\n tierConfigs: Record,\n estimatedTotalTokens: number,\n getContextWindow: (modelId: string) => number | undefined,\n): string[] {\n const fullChain = getFallbackChain(tier, tierConfigs);\n\n // Filter to models that can handle the context\n const filtered = fullChain.filter((modelId) => {\n const contextWindow = getContextWindow(modelId);\n if (contextWindow === undefined) {\n // Unknown model - include it (let API reject if needed)\n return true;\n }\n // Add 10% buffer for safety\n return contextWindow >= estimatedTotalTokens * 1.1;\n });\n\n // If all models filtered out, return the original chain\n // (let the API error out - better than no options)\n if (filtered.length === 0) {\n return fullChain;\n }\n\n return filtered;\n}\n\n/**\n * Filter an already-ranked candidate list by total context and requested output.\n * Unlike the legacy tier helper, this supports the V3 portfolio order.\n */\nexport function filterCandidatesByCapacity(\n models: string[],\n estimatedInputTokens: number,\n requestedOutputTokens: number,\n getCapabilities: (modelId: string) => { contextWindow: number; maxOutput: number } | undefined,\n): string[] {\n const filtered = models.filter((modelId) => {\n const capabilities = getCapabilities(modelId);\n if (!capabilities) return true;\n return (\n capabilities.contextWindow >= (estimatedInputTokens + requestedOutputTokens) * 1.1 &&\n capabilities.maxOutput >= requestedOutputTokens\n );\n });\n return filtered;\n}\n","/**\n * Request-size helpers shared by the rules and portfolio strategies.\n *\n * The router never tokenizes — it is on the hot path and model-agnostic — so\n * sizes are estimates. The estimate only has to be honest enough for the\n * decisions that consume it: the long-context task type, the COMPLEX\n * override and the per-model capacity filter.\n */\n\n// Han, kana, Hangul, CJK punctuation and fullwidth forms. Every production\n// tokenizer spends roughly one token per character here, so the Latin\n// four-characters-per-token rule under-counts these scripts about fourfold:\n// a 200k-character Chinese contract would read as 50k tokens, slip under the\n// 80k long-context boundary and pass the capacity filter for models that\n// cannot hold it.\nconst CJK_CHARS = /[ -ヿ㐀-䶿一-鿿가-힯豈-﫿＀-￯]/g;\n\n/** Approximate token count: one per CJK character, one per four of anything else. */\nexport function estimateTokens(text: string): number {\n if (text.length === 0) return 0;\n const cjk = text.match(CJK_CHARS)?.length ?? 0;\n return cjk + Math.ceil((text.length - cjk) / 4);\n}\n\nconst MAX_SCAN_CHARS = 8_000;\n\n/** The scan window the feature regexes read, bounded so a pasted document cannot stall routing. */\nexport function scanLimit(promptTruncationChars: number): number {\n if (!Number.isFinite(promptTruncationChars)) return MAX_SCAN_CHARS;\n return Math.max(1, Math.min(MAX_SCAN_CHARS, Math.floor(promptTruncationChars)));\n}\n\n\n/**\n * Feature regexes need request shape and intent, not the entire document.\n * Sample both ends so a long pasted artifact keeps the task instruction at\n * either boundary, while the full length still drives capacity decisions.\n */\nexport function sampleForScan(value: string, limit: number): string {\n if (value.length <= limit) return value;\n const prefixLength = Math.ceil(limit / 2);\n const suffixLength = limit - prefixLength;\n // slice(-0) is the whole string, so a one-character limit needs its own case.\n if (suffixLength <= 0) return value.slice(0, prefixLength);\n return `${value.slice(0, prefixLength)}\\n${value.slice(-suffixLength)}`;\n}\n","/**\n * Router Strategy Registry\n *\n * Pluggable strategy system for request routing.\n * Default: RulesStrategy — identical to the original inline route() logic, <1ms.\n */\n\nimport type {\n Tier,\n TierConfig,\n Promotion,\n RoutingDecision,\n RouterStrategy,\n RouterOptions,\n} from \"./types.js\";\nimport { classifyByRules } from \"./rules.js\";\nimport { selectModel } from \"./selector.js\";\nimport { estimateTokens, sampleForScan, scanLimit } from \"./tokens.js\";\n\n/**\n * Apply active time-windowed promotions to tier configs.\n * Returns a new tierConfigs object with promotion overrides merged in.\n * Expired or not-yet-active promotions are ignored.\n */\nfunction applyPromotions(\n tierConfigs: Record,\n promotions: Promotion[] | undefined,\n profile: \"auto\" | \"eco\" | \"premium\" | \"agentic\",\n now: Date = new Date(),\n): Record {\n if (!promotions || promotions.length === 0) return tierConfigs;\n\n let result = tierConfigs;\n for (const promo of promotions) {\n // Check time window\n // An unparseable date compares false both ways, which used to make the\n // promotion active forever. A window that cannot be read is not a window.\n const start = Date.parse(promo.startDate);\n const end = Date.parse(promo.endDate);\n if (!Number.isFinite(start) || !Number.isFinite(end)) continue;\n if (now.getTime() < start || now.getTime() >= end) continue;\n\n // Check profile filter\n if (promo.profiles && !promo.profiles.includes(profile)) continue;\n\n // Shallow-clone on first mutation\n if (result === tierConfigs) {\n result = { ...tierConfigs };\n for (const t of Object.keys(result) as Tier[]) {\n result[t] = { ...result[t] };\n }\n }\n\n // Merge overrides\n for (const [tier, override] of Object.entries(promo.tierOverrides) as [\n Tier,\n Partial,\n ][]) {\n if (!result[tier]) continue;\n if (override.primary) result[tier].primary = override.primary;\n if (override.fallback) result[tier].fallback = override.fallback;\n }\n }\n\n return result;\n}\n\n/**\n * Remove host-declared-dead models from every tier chain, promoting the first\n * surviving rung to primary. A tier whose chain is entirely dead keeps its\n * original config — the router has nothing live to offer there, and inventing\n * a model would hide the outage from the host that reported it.\n */\nexport function applyUnavailableModels(\n tierConfigs: Record,\n unavailableModels: readonly string[] | undefined,\n): Record {\n if (!unavailableModels || unavailableModels.length === 0) return tierConfigs;\n const dead = new Set(unavailableModels);\n let result = tierConfigs;\n for (const tier of Object.keys(tierConfigs) as Tier[]) {\n const config = tierConfigs[tier];\n const alive = [config.primary, ...config.fallback].filter((model) => !dead.has(model));\n if (alive.length === 0 || (alive[0] === config.primary && alive.length === config.fallback.length + 1)) {\n continue;\n }\n if (result === tierConfigs) result = { ...tierConfigs };\n result[tier] = { primary: alive[0], fallback: alive.slice(1) };\n }\n return result;\n}\n\n/**\n * Rules-based routing strategy.\n * Extracted from the original route() in index.ts — logic is identical.\n * Attaches tierConfigs and profile to the decision for downstream use.\n */\nexport class RulesStrategy implements RouterStrategy {\n readonly name = \"rules\";\n\n route(\n prompt: string,\n systemPrompt: string | undefined,\n maxOutputTokens: number,\n options: RouterOptions,\n ): RoutingDecision {\n const { config, modelPricing } = options;\n\n const fullText = `${systemPrompt ?? \"\"} ${prompt}`;\n const estimatedTokens = estimateTokens(fullText);\n const limit = scanLimit(config.classifier.promptTruncationChars);\n const scannedPrompt = sampleForScan(prompt, limit);\n const scannedSystemPrompt = systemPrompt ? sampleForScan(systemPrompt, limit) : undefined;\n\n // --- Rule-based classification (runs first to get agenticScore) ---\n const ruleResult = classifyByRules(\n scannedPrompt,\n scannedSystemPrompt,\n estimatedTokens,\n config.scoring,\n );\n\n // --- Select tier configs based on routing profile ---\n const { routingProfile } = options;\n let tierConfigs: Record;\n let profileSuffix: string;\n let profile: NonNullable;\n\n if (routingProfile === \"eco\") {\n // `ecoTiers: null` explicitly disables the special eco tier set while\n // keeping eco routing semantics. Fall back to regular tiers instead of\n // dropping into auto routing (which could select agentic tiers).\n tierConfigs = config.ecoTiers ?? config.tiers;\n profileSuffix = config.ecoTiers ? \" | eco\" : \" | eco (default tiers)\";\n profile = \"eco\";\n } else if (routingProfile === \"premium\") {\n // `premiumTiers: null` disables the premium-specific tier set but the\n // request is still a premium-profile request, so use regular tiers while\n // preserving premium metadata/cost semantics.\n tierConfigs = config.premiumTiers ?? config.tiers;\n profileSuffix = config.premiumTiers ? \" | premium\" : \" | premium (default tiers)\";\n profile = \"premium\";\n } else {\n // Auto profile (or undefined): intelligent routing with agentic detection.\n //\n // `agenticMode` semantics:\n // - `true` → force agentic tiers (ignore heuristics)\n // - `false` → disable agentic tiers entirely (even if tools are present)\n // - `undefined` → auto-detect via heuristics (tools present OR high agenticScore)\n const agenticScore = ruleResult.agenticScore ?? 0;\n const isAutoAgentic = agenticScore >= 0.5;\n const agenticModeSetting = config.overrides.agenticMode;\n const hasToolsInRequest = options.requiresTools ?? options.hasTools ?? false;\n let useAgenticTiers: boolean;\n if (agenticModeSetting === false) {\n // Explicitly disabled — never use agentic tiers\n useAgenticTiers = false;\n } else if (agenticModeSetting === true) {\n // Explicitly enabled — use agentic tiers if available\n useAgenticTiers = config.agenticTiers != null;\n } else {\n // Auto-detect\n useAgenticTiers = (hasToolsInRequest || isAutoAgentic) && config.agenticTiers != null;\n }\n tierConfigs = useAgenticTiers ? config.agenticTiers! : config.tiers;\n profileSuffix = useAgenticTiers ? ` | agentic${hasToolsInRequest ? \" (tools)\" : \"\"}` : \"\";\n profile = useAgenticTiers ? \"agentic\" : \"auto\";\n }\n\n // Apply time-windowed promotions\n tierConfigs = applyPromotions(tierConfigs, config.promotions, profile, options.now);\n\n // Hard-remove models the host has observed dead at the gateway. After\n // promotions, so a promo cannot resurrect a rung the host just killed.\n tierConfigs = applyUnavailableModels(tierConfigs, options.unavailableModels);\n\n const agenticScoreValue = ruleResult.agenticScore;\n\n // --- Override: large context → force COMPLEX ---\n if (estimatedTokens > config.overrides.maxTokensForceComplex) {\n const decision = selectModel(\n \"COMPLEX\",\n 0.95,\n \"rules\",\n `Input exceeds ${config.overrides.maxTokensForceComplex} tokens${profileSuffix}`,\n tierConfigs,\n modelPricing,\n estimatedTokens,\n maxOutputTokens,\n routingProfile,\n agenticScoreValue,\n );\n return { ...decision, tierConfigs, profile };\n }\n\n // Structured output is a protocol fact the host states (`response_format`\n // → requiresStructuredOutput). It used to be inferred from the system\n // prompt as well, but agent hosts describe their tool schemas there on\n // every turn, which upgraded every one of their requests off SIMPLE.\n const hasStructuredOutput = options.requiresStructuredOutput === true;\n\n let tier: Tier;\n let confidence: number;\n const method: \"rules\" | \"llm\" = \"rules\";\n let reasoning = `score=${ruleResult.score.toFixed(2)} | ${ruleResult.signals.join(\", \")}`;\n\n if (ruleResult.tier !== null) {\n tier = ruleResult.tier;\n confidence = ruleResult.confidence;\n } else {\n // Ambiguous — default to configurable tier (no external API call)\n tier = config.overrides.ambiguousDefaultTier;\n confidence = 0.5;\n reasoning += ` | ambiguous -> default: ${tier}`;\n }\n\n // Apply structured output minimum tier\n if (hasStructuredOutput) {\n const tierRank: Record = { SIMPLE: 0, MEDIUM: 1, COMPLEX: 2, REASONING: 3 };\n const minTier = config.overrides.structuredOutputMinTier;\n if (tierRank[tier] < tierRank[minTier]) {\n reasoning += ` | upgraded to ${minTier} (structured output)`;\n tier = minTier;\n }\n }\n\n // Add routing profile suffix to reasoning\n reasoning += profileSuffix;\n\n const decision = selectModel(\n tier,\n confidence,\n method,\n reasoning,\n tierConfigs,\n modelPricing,\n estimatedTokens,\n maxOutputTokens,\n routingProfile,\n agenticScoreValue,\n );\n return { ...decision, tierConfigs, profile };\n }\n}\n\n// --- Strategy Registry ---\n\nconst registry = new Map();\nregistry.set(\"rules\", new RulesStrategy());\n\nexport function getStrategy(name: string): RouterStrategy {\n const strategy = registry.get(name);\n if (!strategy) {\n throw new Error(`Unknown routing strategy: ${name}`);\n }\n return strategy;\n}\n\nexport function registerStrategy(strategy: RouterStrategy): void {\n registry.set(strategy.name, strategy);\n}\n","/**\n * Default Routing Config\n *\n * All routing parameters as a TypeScript constant.\n * Operators override via openclaw.yaml plugin config.\n *\n * Scoring uses 15 weighted dimensions with sigmoid confidence calibration.\n */\n\nimport type { RoutingConfig } from \"./types.js\";\n\nexport const DEFAULT_ROUTING_CONFIG: RoutingConfig = {\n version: \"3.5\",\n strategy: \"portfolio\",\n portfolio: {\n auto: {\n quality: 0.47,\n capability: 0.2,\n cost: 0.18,\n speed: 0.07,\n reliability: 0.03,\n legacy: 0.05,\n },\n eco: {\n quality: 0.36,\n capability: 0.2,\n cost: 0.28,\n speed: 0.1,\n reliability: 0.04,\n legacy: 0.02,\n },\n premium: {\n quality: 0.58,\n capability: 0.2,\n cost: 0.08,\n speed: 0.06,\n reliability: 0.06,\n legacy: 0.02,\n },\n highStakesBoost: { quality: 0.08, reliability: 0.05 },\n latencySensitiveSpeedBoost: 0.08,\n affinityFloorGap: { auto: 0.1, eco: 0.22, premium: 0.05 },\n },\n\n classifier: {\n llmModel: \"google/gemini-2.5-flash\",\n llmMaxTokens: 10,\n llmTemperature: 0,\n promptTruncationChars: 500,\n cacheTtlMs: 3_600_000, // 1 hour\n },\n\n scoring: {\n tokenCountThresholds: { simple: 50, complex: 500 },\n\n // Multilingual keywords: EN + ZH + JA + RU + DE + ES + PT + KO + AR\n codeKeywords: [\n // English\n \"function\",\n \"class\",\n \"import\",\n \"def\",\n \"SELECT\",\n \"async\",\n \"await\",\n \"const\",\n \"let\",\n \"var\",\n \"return\",\n \"```\",\n // Chinese\n \"函数\",\n \"类\",\n \"导入\",\n \"定义\",\n \"查询\",\n \"异步\",\n \"等待\",\n \"常量\",\n \"变量\",\n \"返回\",\n // Japanese\n \"関数\",\n \"クラス\",\n \"インポート\",\n \"非同期\",\n \"定数\",\n \"変数\",\n // Russian\n \"функция\",\n \"класс\",\n \"импорт\",\n \"определ\",\n \"запрос\",\n \"асинхронный\",\n \"ожидать\",\n \"константа\",\n \"переменная\",\n \"вернуть\",\n // German\n \"funktion\",\n \"klasse\",\n \"importieren\",\n \"definieren\",\n \"abfrage\",\n \"asynchron\",\n \"erwarten\",\n \"konstante\",\n \"variable\",\n \"zurückgeben\",\n // Spanish\n \"función\",\n \"clase\",\n \"importar\",\n \"definir\",\n \"consulta\",\n \"asíncrono\",\n \"esperar\",\n \"constante\",\n \"variable\",\n \"retornar\",\n // Portuguese\n \"função\",\n \"classe\",\n \"importar\",\n \"definir\",\n \"consulta\",\n \"assíncrono\",\n \"aguardar\",\n \"constante\",\n \"variável\",\n \"retornar\",\n // Korean\n \"함수\",\n \"클래스\",\n \"가져오기\",\n \"정의\",\n \"쿼리\",\n \"비동기\",\n \"대기\",\n \"상수\",\n \"변수\",\n \"반환\",\n // Arabic\n \"دالة\",\n \"فئة\",\n \"استيراد\",\n \"تعريف\",\n \"استعلام\",\n \"غير متزامن\",\n \"انتظار\",\n \"ثابت\",\n \"متغير\",\n \"إرجاع\",\n ],\n reasoningKeywords: [\n // English\n \"prove\",\n \"theorem\",\n \"derive\",\n \"step by step\",\n \"chain of thought\",\n \"formally\",\n \"mathematical\",\n \"proof\",\n \"logically\",\n // Chinese\n \"证明\",\n \"定理\",\n \"推导\",\n \"逐步\",\n \"思维链\",\n \"形式化\",\n \"数学\",\n \"逻辑\",\n // Japanese\n \"証明\",\n \"定理\",\n \"導出\",\n \"ステップバイステップ\",\n \"論理的\",\n // Russian\n \"доказать\",\n \"докажи\",\n \"доказательств\",\n \"теорема\",\n \"вывести\",\n \"шаг за шагом\",\n \"пошагово\",\n \"поэтапно\",\n \"цепочка рассуждений\",\n \"рассуждени\",\n \"формально\",\n \"математически\",\n \"логически\",\n // German\n \"beweisen\",\n \"beweis\",\n \"theorem\",\n \"ableiten\",\n \"schritt für schritt\",\n \"gedankenkette\",\n \"formal\",\n \"mathematisch\",\n \"logisch\",\n // Spanish\n \"demostrar\",\n \"teorema\",\n \"derivar\",\n \"paso a paso\",\n \"cadena de pensamiento\",\n \"formalmente\",\n \"matemático\",\n \"prueba\",\n \"lógicamente\",\n // Portuguese\n \"provar\",\n \"teorema\",\n \"derivar\",\n \"passo a passo\",\n \"cadeia de pensamento\",\n \"formalmente\",\n \"matemático\",\n \"prova\",\n \"logicamente\",\n // Korean\n \"증명\",\n \"정리\",\n \"도출\",\n \"단계별\",\n \"사고의 연쇄\",\n \"형식적\",\n \"수학적\",\n \"논리적\",\n // Arabic\n \"إثبات\",\n \"نظرية\",\n \"اشتقاق\",\n \"خطوة بخطوة\",\n \"سلسلة التفكير\",\n \"رسمياً\",\n \"رياضي\",\n \"برهان\",\n \"منطقياً\",\n ],\n simpleKeywords: [\n // English\n \"what is\",\n \"define\",\n \"translate\",\n \"hello\",\n \"yes or no\",\n \"capital of\",\n \"how old\",\n \"who is\",\n \"when was\",\n // Chinese\n \"什么是\",\n \"定义\",\n \"翻译\",\n \"你好\",\n \"是否\",\n \"首都\",\n \"多大\",\n \"谁是\",\n \"何时\",\n // Japanese\n \"とは\",\n \"定義\",\n \"翻訳\",\n \"こんにちは\",\n \"はいかいいえ\",\n \"首都\",\n \"誰\",\n // Russian\n \"что такое\",\n \"определение\",\n \"перевести\",\n \"переведи\",\n \"привет\",\n \"да или нет\",\n \"столица\",\n \"сколько лет\",\n \"кто такой\",\n \"когда\",\n \"объясни\",\n // German\n \"was ist\",\n \"definiere\",\n \"übersetze\",\n \"hallo\",\n \"ja oder nein\",\n \"hauptstadt\",\n \"wie alt\",\n \"wer ist\",\n \"wann\",\n \"erkläre\",\n // Spanish\n \"qué es\",\n \"definir\",\n \"traducir\",\n \"hola\",\n \"sí o no\",\n \"capital de\",\n \"cuántos años\",\n \"quién es\",\n \"cuándo\",\n // Portuguese\n \"o que é\",\n \"definir\",\n \"traduzir\",\n \"olá\",\n \"sim ou não\",\n \"capital de\",\n \"quantos anos\",\n \"quem é\",\n \"quando\",\n // Korean\n \"무엇\",\n \"정의\",\n \"번역\",\n \"안녕하세요\",\n \"예 또는 아니오\",\n \"수도\",\n \"누구\",\n \"언제\",\n // Arabic\n \"ما هو\",\n \"تعريف\",\n \"ترجم\",\n \"مرحبا\",\n \"نعم أو لا\",\n \"عاصمة\",\n \"من هو\",\n \"متى\",\n ],\n technicalKeywords: [\n // English\n \"algorithm\",\n \"optimize\",\n \"architecture\",\n \"distributed\",\n \"kubernetes\",\n \"microservice\",\n \"database\",\n \"infrastructure\",\n // Chinese\n \"算法\",\n \"优化\",\n \"架构\",\n \"分布式\",\n \"微服务\",\n \"数据库\",\n \"基础设施\",\n // Japanese\n \"アルゴリズム\",\n \"最適化\",\n \"アーキテクチャ\",\n \"分散\",\n \"マイクロサービス\",\n \"データベース\",\n // Russian\n \"алгоритм\",\n \"оптимизировать\",\n \"оптимизаци\",\n \"оптимизируй\",\n \"архитектура\",\n \"распределённый\",\n \"микросервис\",\n \"база данных\",\n \"инфраструктура\",\n // German\n \"algorithmus\",\n \"optimieren\",\n \"architektur\",\n \"verteilt\",\n \"kubernetes\",\n \"mikroservice\",\n \"datenbank\",\n \"infrastruktur\",\n // Spanish\n \"algoritmo\",\n \"optimizar\",\n \"arquitectura\",\n \"distribuido\",\n \"microservicio\",\n \"base de datos\",\n \"infraestructura\",\n // Portuguese\n \"algoritmo\",\n \"otimizar\",\n \"arquitetura\",\n \"distribuído\",\n \"microsserviço\",\n \"banco de dados\",\n \"infraestrutura\",\n // Korean\n \"알고리즘\",\n \"최적화\",\n \"아키텍처\",\n \"분산\",\n \"마이크로서비스\",\n \"데이터베이스\",\n \"인프라\",\n // Arabic\n \"خوارزمية\",\n \"تحسين\",\n \"بنية\",\n \"موزع\",\n \"خدمة مصغرة\",\n \"قاعدة بيانات\",\n \"بنية تحتية\",\n ],\n creativeKeywords: [\n // English\n \"story\",\n \"poem\",\n \"compose\",\n \"brainstorm\",\n \"creative\",\n \"imagine\",\n \"write a\",\n // Chinese\n \"故事\",\n \"诗\",\n \"创作\",\n \"头脑风暴\",\n \"创意\",\n \"想象\",\n \"写一个\",\n // Japanese\n \"物語\",\n \"詩\",\n \"作曲\",\n \"ブレインストーム\",\n \"創造的\",\n \"想像\",\n // Russian\n \"история\",\n \"рассказ\",\n \"стихотворение\",\n \"сочинить\",\n \"сочини\",\n \"мозговой штурм\",\n \"творческий\",\n \"представить\",\n \"придумай\",\n \"напиши\",\n // German\n \"geschichte\",\n \"gedicht\",\n \"komponieren\",\n \"brainstorming\",\n \"kreativ\",\n \"vorstellen\",\n \"schreibe\",\n \"erzählung\",\n // Spanish\n \"historia\",\n \"poema\",\n \"componer\",\n \"lluvia de ideas\",\n \"creativo\",\n \"imaginar\",\n \"escribe\",\n // Portuguese\n \"história\",\n \"poema\",\n \"compor\",\n \"criativo\",\n \"imaginar\",\n \"escreva\",\n // Korean\n \"이야기\",\n \"시\",\n \"작곡\",\n \"브레인스토밍\",\n \"창의적\",\n \"상상\",\n \"작성\",\n // Arabic\n \"قصة\",\n \"قصيدة\",\n \"تأليف\",\n \"عصف ذهني\",\n \"إبداعي\",\n \"تخيل\",\n \"اكتب\",\n ],\n\n // New dimension keyword lists (multilingual)\n imperativeVerbs: [\n // English\n \"build\",\n \"create\",\n \"implement\",\n \"design\",\n \"develop\",\n \"construct\",\n \"generate\",\n \"deploy\",\n \"configure\",\n \"set up\",\n // Chinese\n \"构建\",\n \"创建\",\n \"实现\",\n \"设计\",\n \"开发\",\n \"生成\",\n \"部署\",\n \"配置\",\n \"设置\",\n // Japanese\n \"構築\",\n \"作成\",\n \"実装\",\n \"設計\",\n \"開発\",\n \"生成\",\n \"デプロイ\",\n \"設定\",\n // Russian\n \"построить\",\n \"построй\",\n \"создать\",\n \"создай\",\n \"реализовать\",\n \"реализуй\",\n \"спроектировать\",\n \"разработать\",\n \"разработай\",\n \"сконструировать\",\n \"сгенерировать\",\n \"сгенерируй\",\n \"развернуть\",\n \"разверни\",\n \"настроить\",\n \"настрой\",\n // German\n \"erstellen\",\n \"bauen\",\n \"implementieren\",\n \"entwerfen\",\n \"entwickeln\",\n \"konstruieren\",\n \"generieren\",\n \"bereitstellen\",\n \"konfigurieren\",\n \"einrichten\",\n // Spanish\n \"construir\",\n \"crear\",\n \"implementar\",\n \"diseñar\",\n \"desarrollar\",\n \"generar\",\n \"desplegar\",\n \"configurar\",\n // Portuguese\n \"construir\",\n \"criar\",\n \"implementar\",\n \"projetar\",\n \"desenvolver\",\n \"gerar\",\n \"implantar\",\n \"configurar\",\n // Korean\n \"구축\",\n \"생성\",\n \"구현\",\n \"설계\",\n \"개발\",\n \"배포\",\n \"설정\",\n // Arabic\n \"بناء\",\n \"إنشاء\",\n \"تنفيذ\",\n \"تصميم\",\n \"تطوير\",\n \"توليد\",\n \"نشر\",\n \"إعداد\",\n ],\n constraintIndicators: [\n // English\n \"under\",\n \"at most\",\n \"at least\",\n \"within\",\n \"no more than\",\n \"o(\",\n \"maximum\",\n \"minimum\",\n \"limit\",\n \"budget\",\n // Chinese\n \"不超过\",\n \"至少\",\n \"最多\",\n \"在内\",\n \"最大\",\n \"最小\",\n \"限制\",\n \"预算\",\n // Japanese\n \"以下\",\n \"最大\",\n \"最小\",\n \"制限\",\n \"予算\",\n // Russian\n \"не более\",\n \"не менее\",\n \"как минимум\",\n \"в пределах\",\n \"максимум\",\n \"минимум\",\n \"ограничение\",\n \"бюджет\",\n // German\n \"höchstens\",\n \"mindestens\",\n \"innerhalb\",\n \"nicht mehr als\",\n \"maximal\",\n \"minimal\",\n \"grenze\",\n \"budget\",\n // Spanish\n \"como máximo\",\n \"al menos\",\n \"dentro de\",\n \"no más de\",\n \"máximo\",\n \"mínimo\",\n \"límite\",\n \"presupuesto\",\n // Portuguese\n \"no máximo\",\n \"pelo menos\",\n \"dentro de\",\n \"não mais que\",\n \"máximo\",\n \"mínimo\",\n \"limite\",\n \"orçamento\",\n // Korean\n \"이하\",\n \"이상\",\n \"최대\",\n \"최소\",\n \"제한\",\n \"예산\",\n // Arabic\n \"على الأكثر\",\n \"على الأقل\",\n \"ضمن\",\n \"لا يزيد عن\",\n \"أقصى\",\n \"أدنى\",\n \"حد\",\n \"ميزانية\",\n ],\n outputFormatKeywords: [\n // English\n \"json\",\n \"yaml\",\n \"xml\",\n \"table\",\n \"csv\",\n \"markdown\",\n \"schema\",\n \"format as\",\n \"structured\",\n // Chinese\n \"表格\",\n \"格式化为\",\n \"结构化\",\n // Japanese\n \"テーブル\",\n \"フォーマット\",\n \"構造化\",\n // Russian\n \"таблица\",\n \"форматировать как\",\n \"структурированный\",\n // German\n \"tabelle\",\n \"formatieren als\",\n \"strukturiert\",\n // Spanish\n \"tabla\",\n \"formatear como\",\n \"estructurado\",\n // Portuguese\n \"tabela\",\n \"formatar como\",\n \"estruturado\",\n // Korean\n \"테이블\",\n \"형식\",\n \"구조화\",\n // Arabic\n \"جدول\",\n \"تنسيق\",\n \"منظم\",\n ],\n referenceKeywords: [\n // English\n \"above\",\n \"below\",\n \"previous\",\n \"following\",\n \"the docs\",\n \"the api\",\n \"the code\",\n \"earlier\",\n \"attached\",\n // Chinese\n \"上面\",\n \"下面\",\n \"之前\",\n \"接下来\",\n \"文档\",\n \"代码\",\n \"附件\",\n // Japanese\n \"上記\",\n \"下記\",\n \"前の\",\n \"次の\",\n \"ドキュメント\",\n \"コード\",\n // Russian\n \"выше\",\n \"ниже\",\n \"предыдущий\",\n \"следующий\",\n \"документация\",\n \"код\",\n \"ранее\",\n \"вложение\",\n // German\n \"oben\",\n \"unten\",\n \"vorherige\",\n \"folgende\",\n \"dokumentation\",\n \"der code\",\n \"früher\",\n \"anhang\",\n // Spanish\n \"arriba\",\n \"abajo\",\n \"anterior\",\n \"siguiente\",\n \"documentación\",\n \"el código\",\n \"adjunto\",\n // Portuguese\n \"acima\",\n \"abaixo\",\n \"anterior\",\n \"seguinte\",\n \"documentação\",\n \"o código\",\n \"anexo\",\n // Korean\n \"위\",\n \"아래\",\n \"이전\",\n \"다음\",\n \"문서\",\n \"코드\",\n \"첨부\",\n // Arabic\n \"أعلاه\",\n \"أدناه\",\n \"السابق\",\n \"التالي\",\n \"الوثائق\",\n \"الكود\",\n \"مرفق\",\n ],\n negationKeywords: [\n // English\n \"don't\",\n \"do not\",\n \"avoid\",\n \"never\",\n \"without\",\n \"except\",\n \"exclude\",\n \"no longer\",\n // Chinese\n \"不要\",\n \"避免\",\n \"从不\",\n \"没有\",\n \"除了\",\n \"排除\",\n // Japanese\n \"しないで\",\n \"避ける\",\n \"決して\",\n \"なしで\",\n \"除く\",\n // Russian\n \"не делай\",\n \"не надо\",\n \"нельзя\",\n \"избегать\",\n \"никогда\",\n \"без\",\n \"кроме\",\n \"исключить\",\n \"больше не\",\n // German\n \"nicht\",\n \"vermeide\",\n \"niemals\",\n \"ohne\",\n \"außer\",\n \"ausschließen\",\n \"nicht mehr\",\n // Spanish\n \"no hagas\",\n \"evitar\",\n \"nunca\",\n \"sin\",\n \"excepto\",\n \"excluir\",\n // Portuguese\n \"não faça\",\n \"evitar\",\n \"nunca\",\n \"sem\",\n \"exceto\",\n \"excluir\",\n // Korean\n \"하지 마\",\n \"피하다\",\n \"절대\",\n \"없이\",\n \"제외\",\n // Arabic\n \"لا تفعل\",\n \"تجنب\",\n \"أبداً\",\n \"بدون\",\n \"باستثناء\",\n \"استبعاد\",\n ],\n domainSpecificKeywords: [\n // English\n \"quantum\",\n \"fpga\",\n \"vlsi\",\n \"risc-v\",\n \"asic\",\n \"photonics\",\n \"genomics\",\n \"proteomics\",\n \"topological\",\n \"homomorphic\",\n \"zero-knowledge\",\n \"lattice-based\",\n // Chinese\n \"量子\",\n \"光子学\",\n \"基因组学\",\n \"蛋白质组学\",\n \"拓扑\",\n \"同态\",\n \"零知识\",\n \"格密码\",\n // Japanese\n \"量子\",\n \"フォトニクス\",\n \"ゲノミクス\",\n \"トポロジカル\",\n // Russian\n \"квантовый\",\n \"фотоника\",\n \"геномика\",\n \"протеомика\",\n \"топологический\",\n \"гомоморфный\",\n \"с нулевым разглашением\",\n \"на основе решёток\",\n // German\n \"quanten\",\n \"photonik\",\n \"genomik\",\n \"proteomik\",\n \"topologisch\",\n \"homomorph\",\n \"zero-knowledge\",\n \"gitterbasiert\",\n // Spanish\n \"cuántico\",\n \"fotónica\",\n \"genómica\",\n \"proteómica\",\n \"topológico\",\n \"homomórfico\",\n // Portuguese\n \"quântico\",\n \"fotônica\",\n \"genômica\",\n \"proteômica\",\n \"topológico\",\n \"homomórfico\",\n // Korean\n \"양자\",\n \"포토닉스\",\n \"유전체학\",\n \"위상\",\n \"동형\",\n // Arabic\n \"كمي\",\n \"ضوئيات\",\n \"جينوميات\",\n \"طوبولوجي\",\n \"تماثلي\",\n ],\n\n // Agentic task keywords - file ops, execution, multi-step, iterative work\n // Pruned: removed overly common words like \"then\", \"first\", \"run\", \"test\", \"build\"\n agenticTaskKeywords: [\n // English - File operations (clearly agentic)\n \"read file\",\n \"read the file\",\n \"look at\",\n \"check the\",\n \"open the\",\n \"edit\",\n \"modify\",\n \"update the\",\n \"change the\",\n \"write to\",\n \"create file\",\n // English - Execution (specific commands only)\n \"execute\",\n \"deploy\",\n \"install\",\n \"npm\",\n \"pip\",\n \"compile\",\n // English - Multi-step patterns (specific only)\n \"after that\",\n \"and also\",\n \"once done\",\n \"step 1\",\n \"step 2\",\n // English - Iterative work\n \"fix\",\n \"debug\",\n \"until it works\",\n \"keep trying\",\n \"iterate\",\n \"make sure\",\n \"verify\",\n \"confirm\",\n // Chinese (keep specific ones)\n \"读取文件\",\n \"查看\",\n \"打开\",\n \"编辑\",\n \"修改\",\n \"更新\",\n \"创建\",\n \"执行\",\n \"部署\",\n \"安装\",\n \"第一步\",\n \"第二步\",\n \"修复\",\n \"调试\",\n \"直到\",\n \"确认\",\n \"验证\",\n // Spanish\n \"leer archivo\",\n \"editar\",\n \"modificar\",\n \"actualizar\",\n \"ejecutar\",\n \"desplegar\",\n \"instalar\",\n \"paso 1\",\n \"paso 2\",\n \"arreglar\",\n \"depurar\",\n \"verificar\",\n // Portuguese\n \"ler arquivo\",\n \"editar\",\n \"modificar\",\n \"atualizar\",\n \"executar\",\n \"implantar\",\n \"instalar\",\n \"passo 1\",\n \"passo 2\",\n \"corrigir\",\n \"depurar\",\n \"verificar\",\n // Korean\n \"파일 읽기\",\n \"편집\",\n \"수정\",\n \"업데이트\",\n \"실행\",\n \"배포\",\n \"설치\",\n \"단계 1\",\n \"단계 2\",\n \"디버그\",\n \"확인\",\n // Arabic\n \"قراءة ملف\",\n \"تحرير\",\n \"تعديل\",\n \"تحديث\",\n \"تنفيذ\",\n \"نشر\",\n \"تثبيت\",\n \"الخطوة 1\",\n \"الخطوة 2\",\n \"إصلاح\",\n \"تصحيح\",\n \"تحقق\",\n ],\n\n // Dimension weights (sum to 1.0)\n dimensionWeights: {\n tokenCount: 0.08,\n codePresence: 0.15,\n reasoningMarkers: 0.18,\n technicalTerms: 0.1,\n creativeMarkers: 0.05,\n simpleIndicators: 0.02, // Reduced from 0.12 to make room for agenticTask\n multiStepPatterns: 0.12,\n questionComplexity: 0.05,\n imperativeVerbs: 0.03,\n constraintCount: 0.04,\n outputFormat: 0.03,\n referenceComplexity: 0.02,\n negationComplexity: 0.01,\n domainSpecificity: 0.02,\n agenticTask: 0.04, // Reduced - agentic signals influence tier selection, not dominate it\n },\n\n // Tier boundaries on weighted score axis\n tierBoundaries: {\n simpleMedium: 0.0,\n mediumComplex: 0.3, // Raised from 0.18 - prevent simple tasks from reaching expensive COMPLEX tier\n complexReasoning: 0.5, // Raised from 0.4 - reserve for true reasoning tasks\n },\n\n // Sigmoid steepness for confidence calibration\n confidenceSteepness: 12,\n // Below this confidence → ambiguous (null tier)\n confidenceThreshold: 0.7,\n },\n\n // ─── Tier chains ───\n //\n // Catalog refresh 2026-08-29 (V3.5). Every chain below names only models\n // the public catalog lists (GET https://blockrun.ai/api/v1/models). Ids the\n // gateway withholds (`hidden: true`) — kimi-k2.5/k2.6/k2.7, the grok-4-fast\n // and grok-4-1-fast pairs, grok-4-0709, claude-opus-4.6, gemini-3-pro-preview,\n // the whole `free/*` namespace — were removed everywhere, including fallback\n // rungs, so a routed model is always one a user can find on blockrun.ai/models.\n //\n // Primaries moved only where portfolio.ts already carries calibration\n // evidence for the successor (Sonnet 5 over Sonnet 4.6, GPT-5 Mini for\n // agentic MEDIUM, Gemini 3.5 Flash where Kimi K2.7 was). Newcomers with no\n // trajectory evidence yet (gemini-3.6-flash, glm-5.3, glm-5.3-flash,\n // gpt-5.6-luna, grok-4.3, minimax-m3, qwen3.7-plus) enter as fallback rungs;\n // promotion waits for a calibration run, because version recency is not a\n // quality signal.\n //\n // Latency figures in comments are the 2026-08-29 gateway probe\n // (model-profiles.generated.json); prices are the catalog list.\n\n // Auto (balanced) tier configs - current default smart routing\n tiers: {\n SIMPLE: {\n primary: \"google/gemini-2.5-flash\", // $0.30/$2.50 — 60% retention (best) in the 2026-03 run; still the fastest quality answer\n fallback: [\n \"google/gemini-3-flash-preview\", // $0.50/$3 — GPQA 5/6 in the 2026-07 calibration\n \"google/gemini-3.5-flash-lite\", // $0.30/$2.50, 1M ctx, thinking mode — same price as 2.5 Flash, newer generation\n \"deepseek/deepseek-chat\", // $0.14/$0.28, 1M ctx\n \"google/gemini-3.1-flash-lite\", // $0.25/$1.50, 1M ctx\n \"openai/gpt-5.6-luna\", // $0.20/$1.20, 1M ctx — GPT-5.6 cost tier (cut 2026-07-30)\n \"openai/gpt-5.4-nano\", // $0.20/$1.25, 1M ctx\n \"google/gemini-2.5-flash-lite\", // $0.10/$0.40\n \"nvidia/nemotron-3.5-lightning\", // FREE backstop — NVIDIA free tier (probed 2026-08-30)\n ],\n },\n MEDIUM: {\n // Was moonshot/kimi-k2.7 (hidden 2026-08). Gemini 3.5 Flash is the\n // calibrated successor: MGSM 5/5, GPQA 4/6, extraction band (portfolio.ts).\n primary: \"google/gemini-3.5-flash\", // $1.50/$9, 1M ctx, vision + tools\n fallback: [\n \"google/gemini-3.6-flash\", // $1.50/$7.50 — newest Flash, output 17% cheaper than 3.5; awaiting calibration\n \"zai/glm-5.3-flash\", // $0.15/$0.50, 1M ctx, vision + tools verified live 2026-08-27\n \"openai/gpt-5.6-terra\", // $2/$12, 1M ctx — GPT-5.6 balanced tier\n \"google/gemini-3-flash-preview\", // $0.50/$3\n \"deepseek/deepseek-chat\", // $0.14/$0.28\n \"google/gemini-2.5-flash\", // $0.30/$2.50\n \"minimax/minimax-m3\", // $0.30/$1.20, 1M ctx\n \"google/gemini-3.1-flash-lite\", // $0.25/$1.50\n \"openai/gpt-5.6-luna\", // $0.20/$1.20\n \"google/gemini-2.5-flash-lite\", // $0.10/$0.40\n ],\n },\n COMPLEX: {\n primary: \"google/gemini-3.1-pro\", // $2/$12 — proven long-context flagship (portfolio.ts long_context lead)\n fallback: [\n \"google/gemini-3.6-flash\", // $1.50/$7.50 — Pro-level quality at Flash price (Google's claim; uncalibrated here)\n \"google/gemini-3.5-flash\", // $1.50/$9 — calibrated\n \"anthropic/claude-sonnet-5\", // $3/$15 — near-Opus quality, tau2 + Terminal-Bench calibrated\n \"xai/grok-4.5\", // $2.50/$9 — 503-resistant, independent infra (was grok-4-0709, now hidden)\n \"google/gemini-2.5-pro\", // $1.25/$10\n \"anthropic/claude-sonnet-4.6\", // $3/$15\n \"openai/gpt-5.6-terra\", // $2/$12 — GPT-5.6 balanced tier (Sol excluded: #202)\n \"openai/gpt-5.5\", // $5/$30 — prior OpenAI flagship\n \"openai/gpt-5.4\", // $2.50/$15 — previous flagship, benchmarked\n \"zai/glm-5.3\", // $1.40/$4.40, 1M ctx, always-on thinking — verified live 2026-08-19\n \"moonshot/kimi-k3\", // $3/$15, 1M ctx — Moonshot flagship (K2.7 successor)\n \"deepseek/deepseek-v4-pro\", // $0.435/$0.87 — strongest open-weight reasoner\n \"deepseek/deepseek-chat\", // $0.14/$0.28 — cheap last resort\n \"google/gemini-2.5-flash\", // $0.30/$2.50\n ],\n },\n REASONING: {\n // Was xai/grok-4-1-fast-reasoning ($0.20/$0.50, hidden 2026-08). DeepSeek\n // Reasoner is the cheapest listed reasoner at the same 1M context.\n primary: \"deepseek/deepseek-reasoner\", // $0.14/$0.28, 1M ctx\n fallback: [\n \"deepseek/deepseek-v4-pro\", // $0.435/$0.87 — calibrated reasoning band 0.95\n \"xai/grok-4.3\", // $1.50/$4, 1M ctx — xAI reasoning model, vision\n \"qwen/qwen3.7-plus\", // $0.32/$1.28, 1M ctx — reasoning; needs a generous max_tokens (thinking is billed)\n \"google/gemini-3.5-flash\", // $1.50/$9 — MGSM 5/5\n \"openai/o4-mini\", // $1.10/$4.40\n \"openai/o3\", // $2/$8\n ],\n },\n },\n\n // Eco tier configs - absolute cheapest (blockrun/eco)\n ecoTiers: {\n SIMPLE: {\n primary: \"nvidia/nemotron-3.5-lightning\", // FREE — NVIDIA free tier flagship, 1M ctx\n fallback: [\n // Was nvidia/nemotron-3-nano-30b until blockrun delisted it on 2026-09-08\n // (NVIDIA deprovisioned it for the account — a structured per-account\n // 404). nano-omni is blockrun's own redirect target for that id, so this\n // follows the same rule as the head: the router and the gateway name the\n // same model.\n \"nvidia/nemotron-3-nano-omni-30b-a3b-reasoning\", // FREE — nano-30b's successor, 256K ctx\n // The free head keeps rotting with NVIDIA's hosting (deepseek-v4-flash\n // 410 2026-08-12, seed-oss-36b 410 2026-08-03, gpt-oss-120b/20b 400\n // 2026-08-21, and on 2026-08-30 FOUR of the five visible free models at\n // once — step-3.7-flash, nemotron-nano-9b-v2 and nemotron-nano-12b-v2-vl\n // all 410, mistral-nemotron hung). Each retirement retargets the two\n // free rungs to the current free tier; the paid rungs below never move.\n // The head follows blockrun's own redirect of the model it replaces, so\n // the router and the gateway never name different models.\n \"google/gemini-2.5-flash-lite\", // $0.10/$0.40 — cheapest paid rung\n \"zai/glm-5.3-flash\", // $0.15/$0.50, 1M ctx, vision + tools\n \"openai/gpt-5.6-luna\", // $0.20/$1.20, 1M ctx\n \"openai/gpt-5.4-nano\", // $0.20/$1.25\n \"google/gemini-3.1-flash-lite\", // $0.25/$1.50\n ],\n },\n MEDIUM: {\n primary: \"zai/glm-5.3-flash\", // $0.15/$0.50, 1M ctx, vision + tools verified live — cheapest full-capability model\n fallback: [\n \"deepseek/deepseek-chat\", // $0.14/$0.28\n \"google/gemini-3.1-flash-lite\", // $0.25/$1.50\n \"openai/gpt-5.6-luna\", // $0.20/$1.20\n \"openai/gpt-5.4-nano\", // $0.20/$1.25\n \"google/gemini-2.5-flash-lite\", // $0.10/$0.40\n \"google/gemini-2.5-flash\", // $0.30/$2.50\n ],\n },\n COMPLEX: {\n primary: \"zai/glm-5.3-flash\", // $0.15/$0.50, 1M ctx\n fallback: [\n \"deepseek/deepseek-chat\", // $0.14/$0.28, 1M ctx\n \"minimax/minimax-m3\", // $0.30/$1.20, 1M ctx\n \"deepseek/deepseek-v4-pro\", // $0.435/$0.87\n \"google/gemini-3.1-flash-lite\", // $0.25/$1.50\n \"google/gemini-2.5-flash\", // $0.30/$2.50\n ],\n },\n REASONING: {\n primary: \"deepseek/deepseek-reasoner\", // $0.14/$0.28, 1M ctx — cheapest listed reasoner\n fallback: [\n \"deepseek/deepseek-v4-pro\", // $0.435/$0.87\n \"qwen/qwen3.7-plus\", // $0.32/$1.28 — reasoning\n \"minimax/minimax-m3\", // $0.30/$1.20 — reasoning + coding\n \"zai/glm-5.3-flash\", // $0.15/$0.50 — reasoning tokens alongside content\n ],\n },\n },\n\n // Premium tier configs - best quality (blockrun/premium)\n // codex=complex coding, flash=simple coding, sonnet=reasoning/instructions, fable/opus=architecture/PM/audits\n premiumTiers: {\n SIMPLE: {\n // Was moonshot/kimi-k2.7 (hidden 2026-08).\n primary: \"google/gemini-3.5-flash\", // $1.50/$9, 1M ctx, vision + tools — calibrated\n fallback: [\n \"google/gemini-3.6-flash\", // $1.50/$7.50 — newest Flash\n \"anthropic/claude-haiku-4.5\", // $1/$5\n \"zai/glm-5.3\", // $1.40/$4.40, 1M ctx\n \"google/gemini-2.5-flash\", // $0.30/$2.50\n \"google/gemini-3.5-flash-lite\", // $0.30/$2.50\n \"deepseek/deepseek-chat\", // $0.14/$0.28\n ],\n },\n MEDIUM: {\n primary: \"openai/gpt-5.3-codex\", // $1.75/$14 - 400K context, 128K output — code_edit/debug lead (portfolio.ts)\n fallback: [\n \"anthropic/claude-sonnet-5\", // $3/$15 — code_agent band 0.98\n \"moonshot/kimi-k3\", // $3/$15, 1M ctx — Moonshot flagship\n \"zai/glm-5.3\", // $1.40/$4.40 — long-horizon coding\n \"google/gemini-3.6-flash\", // $1.50/$7.50\n \"google/gemini-3.5-flash\", // $1.50/$9\n \"google/gemini-2.5-pro\", // $1.25/$10\n \"xai/grok-4.5\", // $2.50/$9\n \"anthropic/claude-sonnet-4.6\", // $3/$15\n \"openai/gpt-5.6-terra\", // $2/$12\n ],\n },\n COMPLEX: {\n // fable-5 was promoted here 2026-06-11, force-reverted 2026-06-13 when Anthropic\n // withdrew the offer, and restored 2026-07-14 now that BlockRun has relisted it.\n primary: \"anthropic/claude-fable-5\", // Best quality for complex tasks — Mythos-class flagship above Opus ($10/$50, 1M ctx, always-on thinking)\n // Fallback chain de-Gemini'd 2026-04-22: when Anthropic 503s, Gemini is\n // also prone to \"high demand\" 503s (correlated failure — everyone falls\n // back to Google at the same time). Prefer in-family → xAI → Moonshot →\n // OpenAI flagship → Z.AI → DeepSeek → NVIDIA free instead.\n fallback: [\n \"anthropic/claude-opus-5\", // in-family hot swap first (half the price, 1M ctx + adaptive thinking)\n \"anthropic/claude-opus-4.8\", // in-family hot swap (identical cost to 5)\n \"anthropic/claude-opus-4.7\", // in-family hot swap (identical cost to 4.8)\n \"anthropic/claude-sonnet-5\", // Sonnet-tier drop-down, near-Opus quality\n \"anthropic/claude-sonnet-4.6\",\n \"xai/grok-4.5\", // xAI flagship — 503-resistant, direct-xAI SKU\n \"moonshot/kimi-k3\", // Moonshot flagship, independent infra\n \"openai/gpt-5.6-terra\", // GPT-5.6 balanced tier — stable (Sol excluded: #202)\n \"openai/gpt-5.5\", // Prior OpenAI flagship — 1M+ ctx, native agent + computer use\n \"openai/gpt-5.4\", // Previous flagship (slow but stable, benchmarked at 6,213ms)\n \"openai/gpt-5.3-codex\",\n \"zai/glm-5.3\", // Z.AI flagship, 1M ctx\n \"deepseek/deepseek-v4-pro\", // strongest open-weight reasoner\n \"deepseek/deepseek-chat\", // Cheap, reliable\n \"nvidia/nemotron-3.5-lightning\", // NVIDIA free ultimate backstop\n ],\n },\n REASONING: {\n // Sonnet 5 promoted over Sonnet 4.6 (same price; reasoning band 0.98 for both,\n // plus Sonnet 5's tau2/BrowseComp trajectory evidence).\n primary: \"anthropic/claude-sonnet-5\", // $3/$15, 1M ctx, adaptive thinking\n fallback: [\n \"anthropic/claude-sonnet-4.6\", // in-family hot swap — same cost\n \"anthropic/claude-opus-5\", // Newest flagship Opus w/ adaptive thinking\n \"anthropic/claude-opus-4.8\", // Prior flagship Opus — identical cost to 5\n \"anthropic/claude-opus-4.7\", // Flagship Opus w/ adaptive thinking\n \"xai/grok-4.5\", // reasoning band 0.94\n \"deepseek/deepseek-v4-pro\", // reasoning band 0.95\n \"xai/grok-4.3\", // $1.50/$4 — xAI reasoning model\n \"openai/o4-mini\", // $1.10/$4.40\n \"openai/o3\", // $2/$8\n ],\n },\n },\n\n // Agentic tier configs - models that excel at multi-step autonomous tasks\n agenticTiers: {\n SIMPLE: {\n primary: \"openai/gpt-4o-mini\", // $0.15/$0.60 - best tool compliance at lowest cost\n fallback: [\n \"openai/gpt-5.6-luna\", // $0.20/$1.20 — lightweight agentic tier of GPT-5.6\n \"zai/glm-5.3-flash\", // $0.15/$0.50 — tool calls verified live 2026-08-27\n \"anthropic/claude-haiku-4.5\", // $1/$5\n \"google/gemini-2.5-flash\", // $0.30/$2.50\n ],\n },\n MEDIUM: {\n // Was moonshot/kimi-k2.7 (hidden 2026-08). GPT-5 Mini carries the\n // Terminal-Bench and tau2 trajectory evidence in portfolio.ts.\n primary: \"openai/gpt-5-mini\", // $0.25/$2 — 4/7 Terminal-Bench, 5/6 tau2 airline\n fallback: [\n \"google/gemini-3.5-flash\", // $1.50/$9 — tool_agent band 0.88\n \"zai/glm-5.3-flash\", // $0.15/$0.50 — tools verified\n \"openai/gpt-5.6-terra\", // $2/$12\n \"openai/gpt-4o-mini\", // $0.15/$0.60 — reliable tool calling\n \"anthropic/claude-haiku-4.5\", // $1/$5\n \"deepseek/deepseek-chat\", // $0.14/$0.28\n \"moonshot/kimi-k3\", // $3/$15 — tool_agent band 0.85\n ],\n },\n COMPLEX: {\n // Sonnet 5 promoted over Sonnet 4.6: tau2 airline + retail reward 1.0,\n // Terminal-Bench safety band lead (portfolio.ts).\n primary: \"anthropic/claude-sonnet-5\", // $3/$15 — best agentic quality per trajectory evidence\n // Fallback chain de-Gemini'd 2026-04-22: Gemini's \"high demand\" 503s\n // correlate with Anthropic outages (everyone falls back together).\n // Prefer 503-resistant providers first.\n fallback: [\n \"anthropic/claude-sonnet-4.6\", // in-family hot swap — same cost\n \"anthropic/claude-opus-5\", // Newest flagship Opus — in-family hot swap\n \"anthropic/claude-opus-4.8\", // Prior flagship Opus — identical cost to 5\n \"anthropic/claude-opus-4.7\", // Flagship Opus — in-family hot swap\n \"xai/grok-4.5\", // xAI flagship — strong tool use, independent infra\n \"moonshot/kimi-k3\", // Moonshot flagship — independent infra\n \"openai/gpt-5.6-terra\", // GPT-5.6 balanced tier — stable (Sol excluded: #202)\n \"openai/gpt-5.5\", // Prior flagship — native agent + computer use (exactly the agentic-tier use case)\n \"openai/gpt-5.4\", // Previous flagship — reliable\n \"openai/gpt-5.3-codex\", // code_agent lead\n \"zai/glm-5.3\", // long-horizon coding\n \"deepseek/deepseek-v4-pro\", // retail high-risk 3/3\n \"deepseek/deepseek-chat\", // cheap, reliable\n \"nvidia/nemotron-3.5-lightning\", // NVIDIA free ultimate backstop\n ],\n },\n REASONING: {\n primary: \"anthropic/claude-sonnet-5\", // $3/$15 — strong tool use + adaptive thinking\n fallback: [\n \"anthropic/claude-sonnet-4.6\", // in-family hot swap — same cost\n \"anthropic/claude-opus-5\", // Newest flagship Opus w/ adaptive thinking\n \"anthropic/claude-opus-4.8\", // Prior flagship Opus — identical cost to 5\n \"anthropic/claude-opus-4.7\", // Flagship Opus w/ adaptive thinking\n \"xai/grok-4.5\", // reasoning band 0.94\n \"deepseek/deepseek-v4-pro\", // reasoning band 0.95\n \"deepseek/deepseek-reasoner\", // $0.14/$0.28\n ],\n },\n },\n\n // Time-windowed promotions — auto-applied when active, ignored when expired.\n // The GLM-5.1 launch promo (2026-04-01 → 2026-05-01) was the last entry and\n // has expired; the list is kept empty so the mechanism stays wired.\n promotions: [],\n\n overrides: {\n maxTokensForceComplex: 100_000,\n structuredOutputMinTier: \"MEDIUM\",\n ambiguousDefaultTier: \"MEDIUM\",\n // agenticMode left undefined → auto-detect via tools/agenticScore.\n // Set to `true` to force agentic tiers; `false` to disable them entirely.\n },\n};\n","/**\n * Model capabilities used for hard routing constraints.\n *\n * Hosts may inject fresher values through RouterOptions.modelCapabilities.\n * Keeping a small built-in snapshot makes the core safe and useful when a\n * product catalog is temporarily unavailable, without importing product code.\n *\n * GENERATED by scripts/sync-model-capabilities.mjs from the public catalog\n * (GET https://blockrun.ai/api/v1/models) on 2026-11-08; supportsTools comes\n * from a live function-calling probe (scripts/probe-tools.json). Regenerate\n * rather than editing by hand — a hand edit is overwritten on the next sync.\n */\nexport type ModelCapabilities = {\n contextWindow: number;\n maxOutputTokens: number;\n supportsTools: boolean;\n supportsVision: boolean;\n};\n\nexport const DEFAULT_MODEL_CAPABILITIES: Readonly> =\n Object.freeze({\n \"anthropic/claude-fable-5\": {\n contextWindow: 1_000_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"anthropic/claude-fable-5.1\": {\n contextWindow: 1_000_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"anthropic/claude-haiku-4.5\": { // override: The public catalog's `categories` omit \"vision\" for this Anthropic model even though the gateway accepts image input for it (the prior hand-maintained snapshot had it, and Anthropic's model card lists it). Without this the vision filter would silently drop it — reported against the catalog; remove once the categories carry vision.\n contextWindow: 200_000,\n maxOutputTokens: 64_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"anthropic/claude-opus-4.5\": {\n contextWindow: 200_000,\n maxOutputTokens: 64_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"anthropic/claude-opus-4.7\": {\n contextWindow: 1_000_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"anthropic/claude-opus-4.8\": {\n contextWindow: 1_000_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"anthropic/claude-opus-5\": {\n contextWindow: 1_000_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"anthropic/claude-opus-5.5\": {\n contextWindow: 1_000_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"anthropic/claude-sonnet-4.5\": {\n contextWindow: 200_000,\n maxOutputTokens: 64_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"anthropic/claude-sonnet-4.6\": { // override: The public catalog's `categories` omit \"vision\" for this Anthropic model even though the gateway accepts image input for it (the prior hand-maintained snapshot had it, and Anthropic's model card lists it). Without this the vision filter would silently drop it — reported against the catalog; remove once the categories carry vision.\n contextWindow: 1_000_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"anthropic/claude-sonnet-5\": {\n contextWindow: 1_000_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"anthropic/claude-sonnet-5.5\": {\n contextWindow: 1_000_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"cohere/north-mini-code\": { // supportsTools: not probed — fails closed\n contextWindow: 256_000,\n maxOutputTokens: 16_384,\n supportsTools: false,\n supportsVision: false,\n },\n \"deepseek/deepseek-chat\": { // override: The 2026-11-08 catalog began tagging deepseek/deepseek-chat \"vision\" (it was text-only through 2026-10-20), and DeepSeek still ships image input as a separate experimental id (deepseek/deepseek-v4-flash-vision-exp). No image probe has confirmed the tag. Routing an image turn to a model that silently drops the image returns a confident 200 the caller cannot branch on, so this fails closed until a correctly sized image probe passes on both chains; then remove this entry.\n contextWindow: 1_048_576,\n maxOutputTokens: 65_536,\n supportsTools: true,\n supportsVision: false,\n },\n \"deepseek/deepseek-reasoner\": { // override: The 2026-11-08 catalog began tagging deepseek/deepseek-reasoner \"vision\" (it was text-only through 2026-10-20), and DeepSeek still ships image input as a separate experimental id (deepseek/deepseek-v4-flash-vision-exp). No image probe has confirmed the tag. Routing an image turn to a model that silently drops the image returns a confident 200 the caller cannot branch on, so this fails closed until a correctly sized image probe passes on both chains; then remove this entry.\n contextWindow: 1_048_576,\n maxOutputTokens: 65_536,\n supportsTools: true,\n supportsVision: false,\n },\n \"deepseek/deepseek-v4-flash-vision-exp\": {\n contextWindow: 1_048_576,\n maxOutputTokens: 65_536,\n supportsTools: false,\n supportsVision: true,\n },\n \"deepseek/deepseek-v4-pro\": {\n contextWindow: 1_048_576,\n maxOutputTokens: 65_536,\n supportsTools: true,\n supportsVision: false,\n },\n \"deepseek/deepseek-v4.1-flash\": { // override: The 2026-11-08 catalog began tagging deepseek/deepseek-v4.1-flash \"vision\" (it was text-only through 2026-10-20), and DeepSeek still ships image input as a separate experimental id (deepseek/deepseek-v4-flash-vision-exp). No image probe has confirmed the tag. Routing an image turn to a model that silently drops the image returns a confident 200 the caller cannot branch on, so this fails closed until a correctly sized image probe passes on both chains; then remove this entry.\n contextWindow: 1_048_576,\n maxOutputTokens: 65_536,\n supportsTools: true,\n supportsVision: false,\n },\n \"google/gemini-2.5-flash\": {\n contextWindow: 1_048_576,\n maxOutputTokens: 65_536,\n supportsTools: true,\n supportsVision: true,\n },\n \"google/gemini-2.5-flash-lite\": {\n contextWindow: 1_048_576,\n maxOutputTokens: 65_536,\n supportsTools: true,\n supportsVision: false,\n },\n \"google/gemini-2.5-pro\": {\n contextWindow: 1_048_576,\n maxOutputTokens: 65_536,\n supportsTools: true,\n supportsVision: true,\n },\n \"google/gemini-3-flash-preview\": {\n contextWindow: 1_048_576,\n maxOutputTokens: 65_536,\n supportsTools: true,\n supportsVision: true,\n },\n \"google/gemini-3.1-flash-lite\": {\n contextWindow: 1_048_576,\n maxOutputTokens: 65_536,\n supportsTools: true,\n supportsVision: false,\n },\n \"google/gemini-3.1-pro\": {\n contextWindow: 1_048_576,\n maxOutputTokens: 65_536,\n supportsTools: true,\n supportsVision: true,\n },\n \"google/gemini-3.5-flash\": {\n contextWindow: 1_048_576,\n maxOutputTokens: 65_536,\n supportsTools: true,\n supportsVision: true,\n },\n \"google/gemini-3.5-flash-lite\": {\n contextWindow: 1_048_576,\n maxOutputTokens: 65_536,\n supportsTools: true,\n supportsVision: false,\n },\n \"google/gemini-3.6-flash\": {\n contextWindow: 1_048_576,\n maxOutputTokens: 65_536,\n supportsTools: true,\n supportsVision: true,\n },\n \"google/gemini-3.8-flash\": {\n contextWindow: 1_048_576,\n maxOutputTokens: 65_536,\n supportsTools: true,\n supportsVision: true,\n },\n \"google/gemini-4-argon\": { // supportsTools: not probed — fails closed\n contextWindow: 1_048_576,\n maxOutputTokens: 65_536,\n supportsTools: false,\n supportsVision: true,\n },\n \"minimax/minimax-m2.7\": {\n contextWindow: 204_800,\n maxOutputTokens: 16_384,\n supportsTools: true,\n supportsVision: false,\n },\n \"minimax/minimax-m3\": {\n contextWindow: 1_048_576,\n maxOutputTokens: 65_536,\n supportsTools: true,\n supportsVision: false,\n },\n \"mistral/mistral-large-4\": { // supportsTools: not probed — fails closed\n contextWindow: 524_288,\n maxOutputTokens: 262_144,\n supportsTools: false,\n supportsVision: true,\n },\n \"moonshot/kimi-k3\": { // absent from the 2026-11-08 listing but still routed — previous entry retained; probe before removing\n contextWindow: 1_048_576,\n maxOutputTokens: 65_536,\n supportsTools: true,\n supportsVision: true,\n },\n \"moonshot/kimi-k3.1-pro\": { // supportsTools: not probed — fails closed\n contextWindow: 1_048_576,\n maxOutputTokens: 65_536,\n supportsTools: false,\n supportsVision: true,\n },\n \"nvidia/minimax-m3.1-flash\": { // supportsTools: not probed — fails closed\n contextWindow: 1_048_576,\n maxOutputTokens: 16_384,\n supportsTools: false,\n supportsVision: false,\n },\n \"nvidia/muse-glimmer-30b\": { // supportsTools: not probed — fails closed\n contextWindow: 131_072,\n maxOutputTokens: 16_384,\n supportsTools: false,\n supportsVision: false,\n },\n \"nvidia/nemotron-3-nano-omni-30b-a3b-reasoning\": { // override: The catalog tags this model \"vision\", but a correctly sized probe does not hold up (ClawRouter, 2026-08-31): a 64x64 solid-red PNG was named correctly 1 of 4 times on Base, and on Solana the image was silently dropped and a text model answered \"white\". An HTTP 200 with a confident wrong answer gives the caller nothing to branch on, so image turns must not be routed here. It is ecoTiers.SIMPLE.fallback[0] since nemotron-3-nano-30b was delisted (2026-09-08); remove once a probe of this size comes back right on both chains.\n contextWindow: 256_000,\n maxOutputTokens: 16_384,\n supportsTools: false,\n supportsVision: false,\n },\n \"nvidia/nemotron-3-super-120b\": { // supportsTools: not probed — fails closed\n contextWindow: 131_072,\n maxOutputTokens: 16_384,\n supportsTools: false,\n supportsVision: true,\n },\n \"nvidia/nemotron-3-ultra-550b\": { // supportsTools: not probed — fails closed\n contextWindow: 1_000_000,\n maxOutputTokens: 16_384,\n supportsTools: false,\n supportsVision: false,\n },\n \"nvidia/nemotron-3.5-bolt\": { // supportsTools: not probed — fails closed\n contextWindow: 131_072,\n maxOutputTokens: 16_384,\n supportsTools: false,\n supportsVision: true,\n },\n \"nvidia/nemotron-3.5-lightning\": { // supportsTools: not probed — fails closed\n contextWindow: 1_000_000,\n maxOutputTokens: 16_384,\n supportsTools: false,\n supportsVision: false,\n },\n \"openai/chat-latest\": {\n contextWindow: 128_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"openai/gpt-4.1\": {\n contextWindow: 128_000,\n maxOutputTokens: 32_768,\n supportsTools: true,\n supportsVision: true,\n },\n \"openai/gpt-4.1-mini\": {\n contextWindow: 128_000,\n maxOutputTokens: 32_768,\n supportsTools: true,\n supportsVision: false,\n },\n \"openai/gpt-4o\": {\n contextWindow: 128_000,\n maxOutputTokens: 16_384,\n supportsTools: true,\n supportsVision: true,\n },\n \"openai/gpt-4o-mini\": {\n contextWindow: 128_000,\n maxOutputTokens: 16_384,\n supportsTools: true,\n supportsVision: false,\n },\n \"openai/gpt-5-mini\": {\n contextWindow: 200_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: false,\n },\n \"openai/gpt-5.1\": {\n contextWindow: 400_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"openai/gpt-5.2\": {\n contextWindow: 400_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"openai/gpt-5.2-pro\": { // supportsTools: not probed — fails closed\n contextWindow: 400_000,\n maxOutputTokens: 128_000,\n supportsTools: false,\n supportsVision: true,\n },\n \"openai/gpt-5.3-codex\": { // supportsTools: gateway unavailable at probe time — fails closed; override: 2026-08-29 probe: every request (6 plain + 3 tool attempts) returned a gateway 500, so the probe measured an incident, not the model. Codex's function calling is established by the 2026-07 Terminal-Bench / tau2 calibration trajectories in portfolio.ts. Hosts observing the 500s should drop it with RouterOptions.unavailableModels rather than this snapshot claiming the model cannot call tools.\n contextWindow: 400_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: false,\n },\n \"openai/gpt-5.4\": {\n contextWindow: 1_050_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"openai/gpt-5.4-mini\": {\n contextWindow: 400_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"openai/gpt-5.4-nano\": {\n contextWindow: 1_050_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: false,\n },\n \"openai/gpt-5.4-pro\": { // supportsTools: not probed — fails closed\n contextWindow: 1_050_000,\n maxOutputTokens: 128_000,\n supportsTools: false,\n supportsVision: true,\n },\n \"openai/gpt-5.5\": {\n contextWindow: 1_050_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"openai/gpt-5.5-pro\": { // supportsTools: not probed — fails closed\n contextWindow: 1_050_000,\n maxOutputTokens: 128_000,\n supportsTools: false,\n supportsVision: true,\n },\n \"openai/gpt-5.6-luna\": {\n contextWindow: 1_050_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"openai/gpt-5.6-luna-pro\": {\n contextWindow: 1_050_000,\n maxOutputTokens: 128_000,\n supportsTools: false,\n supportsVision: true,\n },\n \"openai/gpt-5.6-sol\": {\n contextWindow: 1_050_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"openai/gpt-5.6-sol-pro\": {\n contextWindow: 1_050_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"openai/gpt-5.6-terra\": {\n contextWindow: 1_050_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"openai/gpt-5.6-terra-pro\": {\n contextWindow: 1_050_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"openai/gpt-6-astra\": {\n contextWindow: 1_050_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"openai/gpt-6-luna\": {\n contextWindow: 1_050_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"openai/gpt-6-sol\": {\n contextWindow: 1_050_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"openai/gpt-6.1-sol\": {\n contextWindow: 1_050_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: true,\n },\n \"openai/o1\": {\n contextWindow: 200_000,\n maxOutputTokens: 100_000,\n supportsTools: true,\n supportsVision: false,\n },\n \"openai/o3\": {\n contextWindow: 200_000,\n maxOutputTokens: 100_000,\n supportsTools: true,\n supportsVision: false,\n },\n \"openai/o3-mini\": {\n contextWindow: 128_000,\n maxOutputTokens: 100_000,\n supportsTools: true,\n supportsVision: false,\n },\n \"openai/o4-mini\": {\n contextWindow: 128_000,\n maxOutputTokens: 100_000,\n supportsTools: true,\n supportsVision: false,\n },\n \"poolside/laguna-s-2.1\": { // supportsTools: not probed — fails closed\n contextWindow: 1_048_576,\n maxOutputTokens: 131_072,\n supportsTools: false,\n supportsVision: false,\n },\n \"poolside/laguna-xs-2.1\": { // supportsTools: not probed — fails closed\n contextWindow: 131_072,\n maxOutputTokens: 16_384,\n supportsTools: false,\n supportsVision: false,\n },\n \"qwen/qwen3.7-flash\": {\n contextWindow: 1_000_000,\n maxOutputTokens: 65_536,\n supportsTools: true,\n supportsVision: false,\n },\n \"qwen/qwen3.7-max\": {\n contextWindow: 1_000_000,\n maxOutputTokens: 65_536,\n supportsTools: true,\n supportsVision: false,\n },\n \"qwen/qwen3.7-plus\": {\n contextWindow: 1_000_000,\n maxOutputTokens: 131_072,\n supportsTools: true,\n supportsVision: false,\n },\n \"qwen/qwen3.8-flash\": {\n contextWindow: 1_000_000,\n maxOutputTokens: 131_072,\n supportsTools: false,\n supportsVision: true,\n },\n \"qwen/qwen3.8-max\": { // supportsTools: not probed — fails closed\n contextWindow: 1_000_000,\n maxOutputTokens: 131_072,\n supportsTools: false,\n supportsVision: false,\n },\n \"tencent/hy4-preview\": { // supportsTools: not probed — fails closed\n contextWindow: 1_048_576,\n maxOutputTokens: 64_000,\n supportsTools: false,\n supportsVision: false,\n },\n \"xai/grok-4.3\": {\n contextWindow: 1_000_000,\n maxOutputTokens: 16_384,\n supportsTools: true,\n supportsVision: true,\n },\n \"xai/grok-4.5\": {\n contextWindow: 500_000,\n maxOutputTokens: 16_384,\n supportsTools: true,\n supportsVision: true,\n },\n \"xai/grok-4.6\": {\n contextWindow: 500_000,\n maxOutputTokens: 16_384,\n supportsTools: true,\n supportsVision: true,\n },\n \"xai/grok-4.7\": {\n contextWindow: 500_000,\n maxOutputTokens: 16_384,\n supportsTools: true,\n supportsVision: true,\n },\n \"xai/grok-build-0.1\": {\n contextWindow: 256_000,\n maxOutputTokens: 16_384,\n supportsTools: true,\n supportsVision: false,\n },\n \"xiaomi/mimo-v2.5\": {\n contextWindow: 1_048_576,\n maxOutputTokens: 131_072,\n supportsTools: true,\n supportsVision: true,\n },\n \"xiaomi/mimo-v2.5-pro\": {\n contextWindow: 1_048_576,\n maxOutputTokens: 131_072,\n supportsTools: true,\n supportsVision: false,\n },\n \"zai/glm-5\": {\n contextWindow: 200_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: false,\n },\n \"zai/glm-5-turbo\": {\n contextWindow: 200_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: false,\n },\n \"zai/glm-5.1\": {\n contextWindow: 200_000,\n maxOutputTokens: 128_000,\n supportsTools: true,\n supportsVision: false,\n },\n \"zai/glm-5.2\": {\n contextWindow: 1_000_000,\n maxOutputTokens: 131_072,\n supportsTools: true,\n supportsVision: false,\n },\n \"zai/glm-5.3\": {\n contextWindow: 1_000_000,\n maxOutputTokens: 131_072,\n supportsTools: true,\n supportsVision: false,\n },\n \"zai/glm-5.3-flash\": {\n contextWindow: 1_000_000,\n maxOutputTokens: 131_072,\n supportsTools: true,\n supportsVision: true,\n },\n });\n","{\n \"anthropic/claude-fable-5\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 9298.5,\n \"p95LatencyMs\": 9873.4,\n \"outputTokensPerSecond\": 55.17,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"anthropic/claude-haiku-4.5\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 3157.4,\n \"p95LatencyMs\": 3170.7,\n \"outputTokensPerSecond\": 162.16,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"anthropic/claude-opus-4.5\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 6497.7,\n \"p95LatencyMs\": 6953.7,\n \"outputTokensPerSecond\": 78.99,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"anthropic/claude-opus-4.7\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 5316.5,\n \"p95LatencyMs\": 6121.5,\n \"outputTokensPerSecond\": 97.34,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"anthropic/claude-opus-4.8\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 6216.1,\n \"p95LatencyMs\": 6847.7,\n \"outputTokensPerSecond\": 82.81,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"anthropic/claude-opus-5\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 7309,\n \"p95LatencyMs\": 7745.2,\n \"outputTokensPerSecond\": 70.17,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"anthropic/claude-sonnet-4.5\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 6330.4,\n \"p95LatencyMs\": 6631.6,\n \"outputTokensPerSecond\": 81.03,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"anthropic/claude-sonnet-4.6\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 6508,\n \"p95LatencyMs\": 6698.3,\n \"outputTokensPerSecond\": 78.6,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"anthropic/claude-sonnet-5\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 6165.4,\n \"p95LatencyMs\": 6582.9,\n \"outputTokensPerSecond\": 83.62,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"deepseek/deepseek-chat\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 4351.4,\n \"p95LatencyMs\": 4543.7,\n \"outputTokensPerSecond\": 117.78,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"deepseek/deepseek-reasoner\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 5201.2,\n \"p95LatencyMs\": 6079.6,\n \"outputTokensPerSecond\": 99.77,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"deepseek/deepseek-v4-pro\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 8781.2,\n \"p95LatencyMs\": 9881.1,\n \"outputTokensPerSecond\": 58.98,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"deepseek/deepseek-v4.1-flash\": {\n \"measuredAt\": \"2026-10-20T18:12:51Z\",\n \"latencyMs\": 2383.5,\n \"p95LatencyMs\": 2547.8,\n \"outputTokensPerSecond\": 216.53,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"google/gemini-2.5-flash\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 5416.4,\n \"p95LatencyMs\": 6442.8,\n \"outputTokensPerSecond\": 213.07,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"google/gemini-2.5-flash-lite\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 5002.6,\n \"p95LatencyMs\": 5780.3,\n \"outputTokensPerSecond\": 408.43,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"google/gemini-2.5-pro\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 28169.5,\n \"p95LatencyMs\": 29491.4,\n \"outputTokensPerSecond\": 147.3,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"google/gemini-3-flash-preview\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 4717.1,\n \"p95LatencyMs\": 5037.1,\n \"outputTokensPerSecond\": 198.71,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"google/gemini-3.1-flash-lite\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 2855.8,\n \"p95LatencyMs\": 3172.7,\n \"outputTokensPerSecond\": 286.91,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"google/gemini-3.1-pro\": {\n \"measuredAt\": \"2026-08-29T16:59:54Z\",\n \"latencyMs\": 24194.1,\n \"p95LatencyMs\": 27269.6,\n \"outputTokensPerSecond\": 109.47,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"google/gemini-3.5-flash\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 5320.6,\n \"p95LatencyMs\": 5429.8,\n \"outputTokensPerSecond\": 226.21,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"google/gemini-3.5-flash-lite\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 3515.8,\n \"p95LatencyMs\": 4363.4,\n \"outputTokensPerSecond\": 248.9,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"google/gemini-3.6-flash\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 13020,\n \"p95LatencyMs\": 15383.1,\n \"outputTokensPerSecond\": 187.87,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"minimax/minimax-m2.7\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 8761.1,\n \"p95LatencyMs\": 10199.3,\n \"outputTokensPerSecond\": 59.18,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"minimax/minimax-m3\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 11101.9,\n \"p95LatencyMs\": 26087.1,\n \"outputTokensPerSecond\": 101.12,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"moonshot/kimi-k3\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 24498.9,\n \"p95LatencyMs\": 40365.3,\n \"outputTokensPerSecond\": 25.11,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"nvidia/mistral-nemotron\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 7349.6,\n \"p95LatencyMs\": 9932.3,\n \"outputTokensPerSecond\": 79.48,\n \"errorRate\": 0.3333,\n \"samples\": 3\n },\n \"nvidia/nemotron-3-nano-omni-30b-a3b-reasoning\": {\n \"measuredAt\": \"2026-08-29T16:59:54Z\",\n \"latencyMs\": 9324.6,\n \"p95LatencyMs\": 12992,\n \"outputTokensPerSecond\": 64.96,\n \"errorRate\": 0.3333,\n \"samples\": 3\n },\n \"nvidia/nemotron-nano-12b-v2-vl\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 5846.9,\n \"p95LatencyMs\": 5846.9,\n \"outputTokensPerSecond\": 87.57,\n \"errorRate\": 0.6667,\n \"samples\": 3\n },\n \"nvidia/nemotron-nano-9b-v2\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 5282.5,\n \"p95LatencyMs\": 5282.5,\n \"outputTokensPerSecond\": 96.92,\n \"errorRate\": 0.6667,\n \"samples\": 3\n },\n \"nvidia/step-3.7-flash\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 4617.4,\n \"p95LatencyMs\": 5237.4,\n \"outputTokensPerSecond\": 112.92,\n \"errorRate\": 0.3333,\n \"samples\": 3\n },\n \"openai/chat-latest\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 3690.9,\n \"p95LatencyMs\": 4344,\n \"outputTokensPerSecond\": 111.85,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/gpt-4.1\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 3527.9,\n \"p95LatencyMs\": 3831.7,\n \"outputTokensPerSecond\": 141.27,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/gpt-4.1-mini\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 4268.2,\n \"p95LatencyMs\": 5101.5,\n \"outputTokensPerSecond\": 103.42,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/gpt-4.1-nano\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 3088.3,\n \"p95LatencyMs\": 3369.2,\n \"outputTokensPerSecond\": 150.31,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/gpt-4o\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 2995.2,\n \"p95LatencyMs\": 3174.2,\n \"outputTokensPerSecond\": 171.32,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/gpt-4o-mini\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 4751.5,\n \"p95LatencyMs\": 4930.4,\n \"outputTokensPerSecond\": 107.84,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/gpt-5-mini\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 4558.1,\n \"p95LatencyMs\": 5081.9,\n \"outputTokensPerSecond\": 113.25,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/gpt-5.2\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 5436.6,\n \"p95LatencyMs\": 5928.8,\n \"outputTokensPerSecond\": 95.47,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/gpt-5.3-codex\": {\n \"measuredAt\": \"2026-08-29T16:59:54Z\",\n \"latencyMs\": 15290.4,\n \"p95LatencyMs\": 15290.4,\n \"outputTokensPerSecond\": 33.49,\n \"errorRate\": 0.6667,\n \"samples\": 3\n },\n \"openai/gpt-5.4\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 5596,\n \"p95LatencyMs\": 5919.4,\n \"outputTokensPerSecond\": 91.67,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/gpt-5.4-mini\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 3377.8,\n \"p95LatencyMs\": 3646.8,\n \"outputTokensPerSecond\": 138.08,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/gpt-5.4-nano\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 4040.4,\n \"p95LatencyMs\": 4205.9,\n \"outputTokensPerSecond\": 118.52,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/gpt-5.5\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 6367.8,\n \"p95LatencyMs\": 7330.7,\n \"outputTokensPerSecond\": 81.29,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/gpt-5.6-luna\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 6064.5,\n \"p95LatencyMs\": 7347.3,\n \"outputTokensPerSecond\": 87.93,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/gpt-5.6-luna-pro\": {\n \"measuredAt\": \"2026-08-29T16:59:54Z\",\n \"latencyMs\": 13914.9,\n \"p95LatencyMs\": 13914.9,\n \"outputTokensPerSecond\": 36.79,\n \"errorRate\": 0.6667,\n \"samples\": 3\n },\n \"openai/gpt-5.6-sol\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 7720.2,\n \"p95LatencyMs\": 9108.2,\n \"outputTokensPerSecond\": 67.47,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/gpt-5.6-sol-pro\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 11442.7,\n \"p95LatencyMs\": 13363.1,\n \"outputTokensPerSecond\": 148.75,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/gpt-5.6-terra\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 4941,\n \"p95LatencyMs\": 5095.3,\n \"outputTokensPerSecond\": 103.69,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/gpt-5.6-terra-pro\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 3574.1,\n \"p95LatencyMs\": 4126.3,\n \"outputTokensPerSecond\": 133.59,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/gpt-6.1-sol\": {\n \"measuredAt\": \"2026-10-20T18:12:51Z\",\n \"latencyMs\": 11324,\n \"p95LatencyMs\": 12747.6,\n \"outputTokensPerSecond\": 45.11,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/o1\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 4324.9,\n \"p95LatencyMs\": 5838.1,\n \"outputTokensPerSecond\": 125.86,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/o3\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 5463.4,\n \"p95LatencyMs\": 5613.1,\n \"outputTokensPerSecond\": 93.8,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/o3-mini\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 2912.7,\n \"p95LatencyMs\": 3092.1,\n \"outputTokensPerSecond\": 176.49,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"openai/o4-mini\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 4958.7,\n \"p95LatencyMs\": 5313,\n \"outputTokensPerSecond\": 103.81,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"qwen/qwen3.7-flash\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 3385.5,\n \"p95LatencyMs\": 4042.7,\n \"outputTokensPerSecond\": 153.94,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"qwen/qwen3.7-max\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 9387.1,\n \"p95LatencyMs\": 10490.2,\n \"outputTokensPerSecond\": 54.92,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"qwen/qwen3.7-plus\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 9766.6,\n \"p95LatencyMs\": 9798.2,\n \"outputTokensPerSecond\": 52.42,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"tencent/hy3\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 6062.3,\n \"p95LatencyMs\": 7070.2,\n \"outputTokensPerSecond\": 87.3,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"xai/grok-4.3\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 9467.7,\n \"p95LatencyMs\": 10087.9,\n \"outputTokensPerSecond\": 48.36,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"xai/grok-4.5\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 13564.8,\n \"p95LatencyMs\": 17351.9,\n \"outputTokensPerSecond\": 60.71,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"xai/grok-build-0.1\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 16394.8,\n \"p95LatencyMs\": 18035.4,\n \"outputTokensPerSecond\": 96.86,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"xiaomi/mimo-v2.5-pro\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 12070.7,\n \"p95LatencyMs\": 12386.8,\n \"outputTokensPerSecond\": 42.44,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"zai/glm-5\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 6839.7,\n \"p95LatencyMs\": 7261.4,\n \"outputTokensPerSecond\": 75.16,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"zai/glm-5-turbo\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 55348.5,\n \"p95LatencyMs\": 114086.6,\n \"outputTokensPerSecond\": 14.64,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"zai/glm-5.1\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 15658.4,\n \"p95LatencyMs\": 17307.1,\n \"outputTokensPerSecond\": 32.9,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"zai/glm-5.2\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 10308.5,\n \"p95LatencyMs\": 15127.6,\n \"outputTokensPerSecond\": 54.87,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"zai/glm-5.3\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 7272.4,\n \"p95LatencyMs\": 7998.1,\n \"outputTokensPerSecond\": 71.09,\n \"errorRate\": 0,\n \"samples\": 3\n },\n \"zai/glm-5.3-flash\": {\n \"measuredAt\": \"2026-08-29T16:51:33Z\",\n \"latencyMs\": 10545.3,\n \"p95LatencyMs\": 11672.4,\n \"outputTokensPerSecond\": 49.01,\n \"errorRate\": 0,\n \"samples\": 3\n }\n}\n","/**\n * Model-performance priors consumed by the portfolio router.\n *\n * The entries below are a small, auditable seed extracted from the 2026-03-16\n * BlockRun performance run. They are deliberately weak priors: live data\n * injected by the host should replace them through configuration before a\n * release. Historical numbers must never be presented as a current\n * provider SLA or as task-quality measurements.\n */\n\nimport liveProfiles from \"./model-profiles.generated.json\";\n\nexport type ModelPerformanceProfile = {\n measuredAt: string;\n /** Gateway end-to-end latency for the benchmark workload. */\n latencyMs: number;\n /** Tail latency is more relevant than mean latency for urgent requests. */\n p95LatencyMs?: number;\n outputTokensPerSecond: number;\n /** External intelligence index when one was available; not task success. */\n intelligenceIndex?: number;\n /** Failure fraction observed in the same benchmark run. */\n errorRate?: number;\n /** Number of sampled calls behind the observation. */\n samples?: number;\n};\n\n// Generated from benchmark files that satisfy the uncached-inference\n// invariant. These are weak performance priors (speed/reliability), never\n// task-quality labels.\nexport const LIVE_MODEL_PROFILES: Readonly> = Object.freeze(\n liveProfiles as Record,\n);\n\nexport const HISTORICAL_MODEL_PROFILES: Readonly> =\n Object.freeze({\n \"anthropic/claude-haiku-4.5\": {\n measuredAt: \"2026-03-16T13:50:48Z\",\n latencyMs: 2305,\n outputTokensPerSecond: 140.6,\n },\n \"anthropic/claude-sonnet-4.6\": {\n measuredAt: \"2026-03-16T13:50:48Z\",\n latencyMs: 2110,\n outputTokensPerSecond: 121.3,\n },\n \"deepseek/deepseek-chat\": {\n measuredAt: \"2026-03-16T13:50:48Z\",\n latencyMs: 1431,\n outputTokensPerSecond: 179.2,\n intelligenceIndex: 32,\n },\n \"google/gemini-2.5-flash\": {\n measuredAt: \"2026-03-16T13:50:48Z\",\n latencyMs: 1238,\n outputTokensPerSecond: 207.6,\n intelligenceIndex: 20,\n },\n \"google/gemini-2.5-flash-lite\": {\n measuredAt: \"2026-03-16T13:50:48Z\",\n latencyMs: 1353,\n outputTokensPerSecond: 192.5,\n intelligenceIndex: 20,\n },\n \"google/gemini-2.5-pro\": {\n measuredAt: \"2026-03-16T13:50:48Z\",\n latencyMs: 1294,\n outputTokensPerSecond: 197.8,\n },\n \"google/gemini-3.1-pro\": {\n measuredAt: \"2026-03-16T13:50:48Z\",\n latencyMs: 1609,\n outputTokensPerSecond: 167.2,\n },\n \"openai/gpt-4o-mini\": {\n measuredAt: \"2026-03-16T13:50:48Z\",\n latencyMs: 2764,\n outputTokensPerSecond: 92.8,\n },\n \"openai/gpt-5.3-codex\": {\n measuredAt: \"2026-03-16T13:50:48Z\",\n latencyMs: 7935,\n outputTokensPerSecond: 32.3,\n },\n });\n","/**\n * Whether the request actually requires an external action/tool, as distinct\n * from merely being sent by a host that exposes tools on every turn.\n *\n * The detector intentionally looks for action+target pairs. A generic factual\n * or multiple-choice question must stay false even when the host attaches a\n * large tool schema; otherwise every tool-enabled host turn is over-routed as\n * an agent task and models may browse or mutate state unnecessarily.\n */\nexport function inferToolRequirement(\n prompt: string,\n _systemPrompt?: string,\n toolChoice?: unknown,\n): boolean {\n // OpenAI-compatible clients can state this requirement directly. Treat that\n // protocol signal as authoritative instead of trying to infer it from prose.\n if (toolChoice === \"none\") return false;\n if (toolChoice === \"required\") return true;\n if (\n typeof toolChoice === \"object\" &&\n toolChoice !== null &&\n (toolChoice as { type?: unknown }).type === \"function\"\n ) {\n return true;\n }\n\n // System prompts commonly describe every tool a host exposes. They are not\n // evidence that the user asked to perform an action on this turn. Explicit\n // host requirements should use tool_choice/requiresTools instead.\n const text = prompt;\n const explicitTool =\n /\\b(?:use|call|invoke)\\s+(?:the\\s+)?[\\w.-]+\\s+(?:tool|function|api)\\b|\\btool[_ -]?call\\b|使用.{0,20}(?:工具|函数|接口)|调用.{0,20}(?:工具|函数|接口)/i;\n const codeEnvironment =\n /\\b(?:run|execute)\\s+(?:the\\s+)?(?:tests?|command|script|build|linter)|\\b(?:edit|modify|patch|create|write|save|delete|rename|move|inspect|read)\\b.{0,60}\\b(?:file|repository|repo|codebase|directory|folder)\\b|\\b(?:terminal|shell|bash|zsh|pytest|npm test|pnpm test|git\\s+(?:status|diff|commit)|docker)\\b|(?:运行|执行).{0,20}(?:测试|命令|脚本|构建)|(?:修改|编辑|修复|创建|读取|检查|保存).{0,30}(?:文件|仓库|代码库|目录)/i;\n const webAction =\n /\\b(?:browse|search|look up|fetch|open)\\b.{0,80}\\b(?:web|website|url|online|documentation|docs|news|weather|price)\\b|(?:浏览|搜索|查询|打开).{0,30}(?:网页|网站|链接|文档|新闻|天气|价格)/i;\n const statefulAction =\n /\\b(?:refund|cancel|book|reserve|purchase|buy|return|exchange|transfer|update|change)\\b.{0,80}\\b(?:order|booking|reservation|account|address|payment|subscription|ticket|flight|item)\\b|(?:退款|取消|预订|购买|退货|换货|转账|更新|修改).{0,30}(?:订单|预订|账户|地址|付款|订阅|票|航班|商品)/i;\n return (\n explicitTool.test(text) ||\n codeEnvironment.test(text) ||\n webAction.test(text) ||\n statefulAction.test(text)\n );\n}\n","/**\n * V3 portfolio router.\n *\n * This is deliberately local and deterministic: feature extraction, eligibility\n * checks and scoring read only request data plus the in-process model registry.\n * It is therefore safe for the hot path and provides a stable baseline for the\n * RouterBench evaluation before health telemetry / an optional judge are added.\n */\n\nimport { DEFAULT_ROUTING_CONFIG } from \"./config.js\";\nimport { DEFAULT_MODEL_CAPABILITIES } from \"./model-capabilities.js\";\nimport { getFallbackChain, selectModel, usablePricing } from \"./selector.js\";\nimport { RulesStrategy } from \"./strategy.js\";\nimport {\n HISTORICAL_MODEL_PROFILES,\n LIVE_MODEL_PROFILES,\n type ModelPerformanceProfile,\n} from \"./model-profiles.js\";\nimport type { RouterOptions, RouterStrategy, TaskType, Tier, TierConfig } from \"./types.js\";\nimport { inferToolRequirement } from \"./tool-intent.js\";\nimport { estimateTokens, sampleForScan, scanLimit } from \"./tokens.js\";\n\ntype TaskFeatures = {\n taskType: TaskType;\n estimatedInputTokens: number;\n hasCode: boolean;\n needsTools: boolean;\n toolsAvailable: boolean;\n needsVision: boolean;\n needsStructuredOutput: boolean;\n latencySensitive: boolean;\n highStakes: boolean;\n language: \"zh\" | \"other\";\n likelyParallelToolCalls: boolean;\n complexMultiToolPlan: boolean;\n agentDomain: \"airline\" | \"retail\" | \"web_research\" | \"other\";\n deepWebResearch: boolean;\n agentRisk: \"standard\" | \"high\" | \"complex_high\" | \"policy_exception_simple\" | \"policy_exception\";\n terminalToolSignal: boolean;\n terminalSafetySensitive: boolean;\n implicitTerminalCode: boolean;\n /** A code artifact or coding action is present, not merely a language name. */\n codeArtifact: boolean;\n};\n\n// The bundled config carries the calibrated weights; a host config that omits\n// `portfolio` scores with the same numbers rather than a second copy of them.\nconst DEFAULT_PORTFOLIO_WEIGHTS = DEFAULT_ROUTING_CONFIG.portfolio!;\n\n/**\n * Detect turns that probably need several tool calls. This is a\n * deliberately conservative request-side feature: it uses only the prompt\n * and visible tool count, never benchmark categories or expected answers.\n */\nfunction likelyNeedsParallelToolCalls(\n prompt: string,\n needsTools: boolean,\n toolCount: number | undefined,\n toolNames: readonly string[] | undefined,\n): boolean {\n if (!needsTools || toolCount === undefined || toolCount < 1) return false;\n const text = prompt.trim();\n const explicitRepeat =\n /\\b(?:in parallel|simultaneously|concurrently|for each|each of|every one|both|(?:two|three|multiple|several)\\s+(?:cities|locations|items|tasks|orders|users|files))\\b|并行|同时|分别|每个|各自|(?:两个|三个|多个)(?:城市|地点|项目|任务|订单|用户|文件)|cada uno|para cada|simult[aá]neamente/i.test(\n text,\n );\n if (explicitRepeat) return true;\n\n const sentenceClauses = text\n .split(/[.!?。!?]+/)\n .map((part) => part.trim())\n .filter((part) => part.length >= 8);\n if (\n (/\\b(?:also|additionally|furthermore)\\b|另外|此外|그리고/i.test(text) &&\n sentenceClauses.length >= 2) ||\n /\\band\\s+(?:also|for the)\\b/i.test(text)\n )\n return true;\n\n const pairedQuantity =\n /\\b\\d+(?:\\.\\d+)?\\s+(?:and|or)\\s+\\d+(?:\\.\\d+)?\\s*(?:gb|mb|tb|kg|g|ml|oz|cups?|cores?|cpus?)\\b/i.test(\n text,\n );\n if (pairedQuantity) return true;\n\n // Distinctive tokens from two visible tool names are a strong local signal\n // for a multi-operation turn (for example add_task + delete_task).\n const operationTokens = new Set([\n \"add\",\n \"delete\",\n \"remove\",\n \"cancel\",\n \"return\",\n \"exchange\",\n \"modify\",\n \"book\",\n \"transfer\",\n \"send\",\n \"upload\",\n \"download\",\n \"create\",\n \"close\",\n ]);\n // Whole words only, with an optional inflection: a substring test read\n // \"add\" out of \"address\", \"book\" out of \"facebook\" and \"close\" out of\n // \"closet\" (the same failure rules.ts fixed for its keyword lists).\n const lowered = text.toLowerCase();\n const matchedOperationTokens = new Set(\n (toolNames ?? [])\n .flatMap((name) => name.toLowerCase().split(/[^a-z0-9\\u3400-\\u9fff]+/))\n .filter(\n (token) =>\n operationTokens.has(token) &&\n new RegExp(`\\\\b${token}(?:s|es|d|ed|ing)?\\\\b`).test(lowered),\n ),\n );\n // A single workflow naturally mentions domain nouns like order/item plus\n // one action. Upgrade only when two different visible operation verbs are\n // requested (for example cancel + book or add + delete).\n if (matchedOperationTokens.size >= 2) return true;\n\n // Repeated food/logging entries are commonly expressed as several lines,\n // each with its own quantity rather than an explicit \"for each\" phrase.\n const nonEmptyLines = text\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter(Boolean);\n const quantityMentions =\n text.match(\n /\\b(?:\\d+(?:\\.\\d+)?|one|two|three|four|five|six|seven|eight|nine|ten)\\s*(?:oz|ounce|ounces|g|gram|grams|kg|ml|cups?|pieces?|tablespoons?)\\b/gi,\n ) ?? [];\n if (nonEmptyLines.length >= 2 && quantityMentions.length >= 2) return true;\n\n // Weather prompts provide a useful language-independent high-confidence\n // pattern: a single lookup tool plus multiple locations joined in one turn.\n const repeatedLookup =\n /\\b(?:weather|climate|clima|tiempo|temperature|snow|news|report)\\b|天气|气象|温度|降雪|新闻|报告/i.test(\n text,\n );\n const multiLocationConnector =\n /\\b(?:and also|both)\\b|\\s(?:y|e)\\s|还有|以及|和|、/i.test(text);\n const commaSeparatedLocations = (text.match(/[,,]/g) ?? []).length >= 2;\n if (repeatedLookup && (multiLocationConnector || commaSeparatedLocations)) return true;\n\n const distinctOrderParts =\n /\\b(?:food|meal)\\b[\\s\\S]*\\bdrink\\b|\\bdrink\\b[\\s\\S]*\\b(?:food|meal)\\b/i.test(text);\n const koreanParallelClauses = (text.match(/,/g) ?? []).length >= 3 && /하고|그리고/.test(text);\n return distinctOrderParts || koreanParallelClauses;\n}\n\nfunction classifyTask(\n prompt: string,\n systemPrompt: string | undefined,\n options: RouterOptions,\n): TaskFeatures {\n const fullText = `${systemPrompt ?? \"\"} ${prompt}`;\n const estimatedInputTokens = estimateTokens(fullText);\n const limit = scanLimit(options.config.classifier.promptTruncationChars);\n const scannedPrompt = sampleForScan(prompt, limit);\n const scannedSystemPrompt = sampleForScan(systemPrompt ?? \"\", limit);\n // Only the deep-web-research clue detectors below read the system prompt,\n // and they are gated on a web-research tool surface. Every other feature\n // reads the user turn: a host's standing instructions (\"be quick\", \"follow\n // security best practices\", a Mandarin persona) describe the assistant, not\n // this request, and must not move its scoring or language band.\n const scannedFullText = `${scannedSystemPrompt} ${scannedPrompt}`;\n const text = scannedPrompt.toLowerCase();\n const explicitCodeSignal =\n /```|\\b(?:typescript|javascript|python|rust|java|sql|stack trace|traceback|exception)\\b|\\.(?:ts|tsx|js|py|go|rs)\\b/i.test(\n scannedPrompt,\n );\n // `class` is common in non-code Agent domains (for example airline cabin\n // class). Treat code constructs as code only when the prompt also contains\n // an implementation/editing cue, instead of letting a single ambiguous\n // noun redirect an entire tool session to the code-agent portfolio.\n const codeConstructSignal =\n /\\b(?:implement|refactor|debug|write|edit|modify|create|define|review|fix)\\b[\\s\\S]{0,48}\\b(?:api|function|class|method)\\b|\\b(?:api|function|class|method)\\b[\\s\\S]{0,48}\\b(?:code|implementation|typescript|javascript|python|rust|java)\\b/i.test(\n scannedPrompt,\n );\n const nativeCodeSignal =\n /\\b(?:programmed|written|implemented?|code)\\s+(?:in|using)\\s+(?:c\\+\\+|c|rust|go)\\b/i.test(\n scannedPrompt,\n );\n // A CamelCase error class (TypeError, NullPointerException) is a runtime\n // artifact, not prose about errors; case-sensitive on purpose.\n const errorClassSignal = /\\b[A-Z][A-Za-z]*(?:Error|Exception)\\b/.test(scannedPrompt);\n const hasCode = explicitCodeSignal || codeConstructSignal || nativeCodeSignal || errorClassSignal;\n // A language name alone (\"java coffee prices\", \"python snake habitat\") is\n // not code work, even on a tool turn. It joins the code-agent pool only\n // together with a coding action.\n const codingAction =\n /\\b(?:write|implement|refactor|debug|fix|patch|compile|build|run|test|script|program|code|function|class|module|repo(?:sitory)?)\\b|编写|实现|重构|调试|修复|编译|脚本|代码/i.test(\n scannedPrompt,\n );\n // Stronger than hasCode: an actual code artifact or coding action, never a\n // bare language name (\"What is Python?\" is trivia, not a code task) and\n // never the English word \"exception\" on its own (\"please make an\n // exception\"); a thrown exception shows up as a CamelCase class above.\n const codeArtifact =\n /```|\\b(?:stack trace|traceback)\\b|\\.(?:ts|tsx|js|py|go|rs)\\b/i.test(scannedPrompt) ||\n codeConstructSignal ||\n nativeCodeSignal ||\n errorClassSignal;\n const toolsAvailable = options.hasTools ?? false;\n const needsTools =\n options.requiresTools ??\n (toolsAvailable && inferToolRequirement(scannedPrompt, scannedSystemPrompt));\n const likelyParallelToolCalls = likelyNeedsParallelToolCalls(\n scannedPrompt,\n needsTools,\n options.toolCount,\n options.toolNames,\n );\n const normalizedToolNames = (options.toolNames ?? []).map((name) => name.toLowerCase());\n const airlineToolSignal = normalizedToolNames.some((name) =>\n /(?:flight|reservation|airport|baggage|passenger)/.test(name),\n );\n const retailToolSignal = normalizedToolNames.some((name) =>\n /(?:order|product|item|return|exchange|address)/.test(name),\n );\n const webResearchToolSignal = normalizedToolNames.some((name) =>\n /^(?:web_?search|web_?fetch)$/.test(name),\n );\n const agentDomain =\n airlineToolSignal && !retailToolSignal\n ? \"airline\"\n : retailToolSignal && !airlineToolSignal\n ? \"retail\"\n : webResearchToolSignal\n ? \"web_research\"\n : \"other\";\n // Distinguish a cheap lookup from a BrowseComp-like investigation. These\n // prompts require joining several clues, resolving an entity, and ending in\n // one exact answer; complete agent trajectories show that treating them as\n // ordinary search causes long, costly loops. This is request/tool-surface\n // evidence only and does not depend on a benchmark id or hidden answer.\n const clueConnectors =\n scannedFullText.match(\n /\\b(?:after|before|while|where|whose|which|in \\d{4}|as of|over \\d+|another|also|furthermore)\\b|(?:之后|之前|其中|截至|超过|另一个|此外)/gi,\n ) ?? [];\n const entityResolutionSignal =\n /\\b(?:identify|who (?:is|was)|what (?:is|was) the name|which (?:person|player|company|country|city)|find the (?:person|player|name|entity))\\b|(?:找出|识别|是谁|哪位|名称是什么)/i.test(\n scannedFullText,\n );\n const exactAnswerSignal =\n /\\b(?:exact answer|single best-supported answer|following clues|multiple public sources)\\b|(?:精确答案|根据.*线索|多个公开来源)/i.test(\n scannedFullText,\n );\n const deepWebResearch =\n agentDomain === \"web_research\" &&\n (exactAnswerSignal ||\n (entityResolutionSignal && (clueConnectors.length >= 3 || prompt.length >= 320)));\n const globalOptimizationSignal =\n /\\b(?:cheapest|lowest[- ]price|least expensive|most expensive|highest(?:[- ]priced)?|largest|smallest|maximum|minimum|best available|closest|not (?:cost|exceed))\\b|最便宜|最低价|最贵|最高价|最大|最小/i.test(\n scannedPrompt,\n );\n const globalScopeSignal =\n /\\b(?:everything|all (?:(?:my|your|their|the) )?(?:future |upcoming )?(?:items|orders|passengers|flights|reservations|bookings)|every (?:item|order|passenger|flight|reservation|booking))\\b|全部|所有|每个/i.test(\n scannedPrompt,\n );\n const globalChoiceSignal = globalOptimizationSignal || globalScopeSignal;\n const crossRecordSignal =\n /\\b(?:another|other|different|previous)\\s+(?:order|reservation|booking|account|address)\\b|另一(?:个)?(?:订单|预订|账户|地址)|其他(?:订单|预订|账户|地址)/i.test(\n scannedPrompt,\n );\n // Reservation locators mix letters and digits (ZFA04Y, 4WQ150). Requiring\n // both keeps shouted words (\"CANCEL MY FLIGHT\") and plain six-digit numbers\n // from reading as two reservations.\n const reservationIds =\n scannedPrompt.match(/\\b(?=[A-Z0-9]*\\d)(?=[A-Z0-9]*[A-Z])[A-Z0-9]{6}\\b/g) ?? [];\n const crossReservationBatchSignal =\n agentDomain === \"airline\" &&\n (/\\b(?:two|three|multiple|several)(?:\\s+of\\s+(?:my|our|the))?\\s+(?:upcoming\\s+)?(?:reservations?|bookings?)\\b|\\b(?:a\\s+)?(?:second|third)\\s+(?:reservation|booking)\\b/i.test(\n scannedPrompt,\n ) ||\n new Set(reservationIds).size >= 2);\n const conditionalGlobalWorkflowSignal =\n agentDomain === \"airline\" &&\n globalScopeSignal &&\n /\\b(?:if|that (?:contain|have)|longer than|shorter than|under|over|at (?:most|least)|wherever possible)\\b|如果|超过|少于|不超过|尽可能/i.test(\n scannedPrompt,\n ) &&\n /\\b(?:cancel|change|upgrade|move|book)\\b[\\s\\S]*\\b(?:cancel|change|upgrade|move|book)\\b|取消[\\s\\S]*(?:升级|更改)|升级[\\s\\S]*(?:取消|更改)/i.test(\n scannedPrompt,\n );\n // A refund explicitly targeted at a named/non-original card can conflict\n // with account state and require escalation rather than a substitute action.\n // This narrow feature is visible on the first turn and avoids sending every\n // ordinary return workflow to the expensive policy specialist.\n const policyExceptionSignal =\n agentDomain === \"retail\" &&\n /\\b(?:return|refund|send back|get (?:my |the )?money back)\\b|退货|退款|退回/i.test(\n scannedPrompt,\n ) &&\n /\\b(?:amex|american express|visa|mastercard|credit card|debit card|different card|another card|other card)\\b|信用卡|借记卡|其他卡|另一张卡/i.test(\n scannedPrompt,\n );\n // A comparative selector can mention two products while requesting only\n // one write (for example \"send back the pricier one\"). Three-repeat tau2\n // calibration found no quality gain from the policy specialist on these\n // single-write cases, so keep them in a distinct, lower-cost risk band.\n const singleSelectedPolicyException =\n policyExceptionSignal &&\n /\\b(?:return|refund|send back)\\b[^.!?。!?]{0,96}\\b(?:the )?(?:pricier|cheaper|more expensive|less expensive|costlier|one)\\b/i.test(\n scannedPrompt,\n );\n // Returns and exchanges often pivot after confirmation (return -> rethink\n // -> exchange -> choose a variant). That future state is not visible to a\n // task-start router, so treat the observable workflow verb as the risk cue.\n // Simpler cancellation and one-field order edits stay on the standard path.\n const negotiatedWorkflowSignal =\n agentDomain === \"retail\" && /\\b(?:return|exchange)\\b|退货|退回|换货|交换/i.test(scannedPrompt);\n const numberedSteps = (scannedPrompt.match(/(?:^|\\s)\\d+(?:\\.\\d+)*[.)]\\s+/g) ?? []).length;\n const complexMultiToolPlan =\n likelyParallelToolCalls &&\n ((options.toolCount ?? 0) >= 6 || numberedSteps >= 3 || prompt.length > 1_200);\n let agentRisk: TaskFeatures[\"agentRisk\"] =\n needsTools && singleSelectedPolicyException\n ? \"policy_exception_simple\"\n : needsTools && policyExceptionSignal\n ? \"policy_exception\"\n : // Airline prompts that require a global optimum (for example the\n // cheapest itinerary across several candidates) are materially harder\n // than applying one change to every passenger in a known reservation.\n // Full-session evidence supports Sonnet for the former, while upgrading\n // the latter merely because it says \"all passengers\" caused a large cost\n // increase without a quality gain.\n needsTools &&\n agentDomain === \"airline\" &&\n (globalOptimizationSignal || conditionalGlobalWorkflowSignal)\n ? \"complex_high\"\n : needsTools &&\n (likelyParallelToolCalls ||\n globalChoiceSignal ||\n crossRecordSignal ||\n crossReservationBatchSignal ||\n negotiatedWorkflowSignal)\n ? \"high\"\n : \"standard\";\n const needsVision = options.hasVision ?? false;\n const needsStructuredOutput = options.requiresStructuredOutput ?? false;\n const latencySensitive =\n /\\b(?:urgent|asap|fast|quick|low latency|real[- ]time)\\b|尽快|马上|快速|低延迟/i.test(\n scannedPrompt,\n );\n const highStakes =\n /\\b(?:production|security|payment|legal|medical|financial|audit)\\b|生产|安全|支付|法律|医疗|财务|审计/i.test(\n scannedPrompt,\n );\n // Terminal tasks often describe the desired artifact rather than naming a\n // programming language. Treat only small, deterministic local build/file\n // work as implicit code. Operational deployment, credentials, destructive\n // work, evaluation, vision, and broad search stay on the stronger generic\n // tool-agent path. This is a request-side feature, not a benchmark ID list.\n const terminalToolSignal = normalizedToolNames.some((name) =>\n /^(?:terminalexec|terminalinspect|terminalsendkeys)$/.test(name),\n );\n const simpleTerminalArtifact =\n /\\b(?:create|write|convert|generate|build|implement|run|fix|repair|debug|make)\\b[\\s\\S]{0,120}\\b(?:file|script|csv|parquet|json|txt|server|endpoint)\\b/i.test(\n scannedPrompt,\n );\n // Multi-file repair is qualitatively different from fixing one known local\n // script. The agent must preserve state across inspections, infer ordering\n // and dependencies, edit several artifacts, and close the loop with tests.\n // A frozen Terminal-Bench trajectory showed the economy model spending 27\n // turns repeatedly rereading files without making an edit, while Opus solved\n // the same task in eight turns. Promote this request-visible pattern before\n // model scoring; no benchmark ID or expected answer is consulted.\n const terminalComplexRepair =\n terminalToolSignal &&\n /\\b(?:multiple|several)\\s+(?:scripts?|files?|components?)\\b|\\b(?:pipeline|dependencies)\\b[\\s\\S]{0,100}\\b(?:fail|issue|fix|repair|run|execute)\\b|\\b(?:identify|find|fix|repair)\\s+(?:and\\s+)?(?:fix\\s+)?all\\s+(?:the\\s+)?issues\\b/i.test(\n scannedPrompt,\n );\n // One artifact that must be accepted by multiple compilers/runtimes is not\n // a routine file-writing task. It requires reasoning across incompatible\n // grammars and validating every execution path; cheap code models can\n // produce plausible-looking source that satisfies neither toolchain.\n const mentionedTerminalRuntimes = new Set(\n (scannedPrompt.match(/\\b(?:gcc|clang|rustc|javac|go\\s+build|node|python)\\b/gi) ?? []).map(\n (name) => name.toLowerCase().replace(/\\s+/g, \" \"),\n ),\n );\n const terminalCrossRuntimeArtifact =\n terminalToolSignal &&\n (/\\bpolyglot\\b/i.test(scannedPrompt) ||\n /\\b(?:both|each)\\b[\\s\\S]{0,120}\\b(?:compilers?|runtimes?|toolchains?)\\b/i.test(\n scannedPrompt,\n ) ||\n (mentionedTerminalRuntimes.size >= 2 &&\n /\\b(?:compile|build|run|execute)\\b/i.test(scannedPrompt)));\n // Framework-to-native ports combine binary checkpoint inspection, weight\n // export, tensor-layout reasoning, image/data decoding, and a separately\n // compiled runtime. A task-start router can see this boundary directly in\n // the request (for example PyTorch state_dict -> a pure C CLI); treating it\n // like routine single-file C work caused a 30-turn read/retry loop in a\n // frozen official Terminal-Bench trajectory.\n const terminalFrameworkToNativeArtifact =\n terminalToolSignal &&\n /\\b(?:pytorch|tensorflow|jax|onnx|state[_ -]?dict|checkpoint|safetensors?)\\b|\\.(?:pth|pt|onnx)\\b/i.test(\n scannedPrompt,\n ) &&\n /\\b(?:pure|native|programmed|written|implemented?)\\s+(?:in|using)\\s+(?:c\\+\\+|c|rust|go)\\b|\\b(?:c\\+\\+|c|rust|go)\\s+(?:program|binary|executable|cli|tool|implementation)\\b/i.test(\n scannedPrompt,\n ) &&\n /\\b(?:inference|model|weights?|tensor|export|convert|load)\\b/i.test(scannedPrompt);\n if (\n needsTools &&\n (terminalComplexRepair || terminalCrossRuntimeArtifact || terminalFrameworkToNativeArtifact) &&\n (agentRisk === \"standard\" || agentRisk === \"high\")\n )\n agentRisk = \"complex_high\";\n const complexTerminalOperation =\n /\\b(?:git|ssh|nginx|https|certificate|authentication|credential|deploy|production|encrypt|gpg|shred|securely delete|decommission|benchmark|evaluate|embedding|chess|image|search the web|schema|statistical|statistics|aggregate|join|multiple inputs?)\\b/i.test(\n scannedPrompt,\n );\n // A bare \"token\" is not a credential signal: blockchain, tokenizer, and\n // LLM tasks use that word routinely (for example \"token transfers\"). Only\n // treat it as sensitive when the prompt gives it an authentication/secret\n // qualifier. API keys remain an unambiguous high-risk signal on their own.\n const terminalCredentialSignal =\n /\\b(?:ssh|nginx|certificate|authentication|credentials?|passwords?|api keys?|deploy|production|encrypt|gpg|shred|securely delete|decommission)\\b/i.test(\n scannedPrompt,\n ) ||\n /\\b(?:access|auth|authentication|bearer|secret|api)\\s+tokens?\\b|\\btokens?\\s+(?:secret|credential|authentication)\\b/i.test(\n scannedPrompt,\n );\n const terminalSafetySensitive = terminalToolSignal && (highStakes || terminalCredentialSignal);\n const implicitTerminalCode =\n needsTools &&\n terminalToolSignal &&\n agentRisk === \"standard\" &&\n !highStakes &&\n !complexTerminalOperation &&\n numberedSteps < 3 &&\n prompt.length <= 1_000 &&\n simpleTerminalArtifact;\n // Han characters alone also spell Japanese; kana marks the prompt as not\n // Mandarin, so it does not get the Mandarin-native extraction band.\n const language =\n /[\\u3400-\\u9fff]/.test(scannedPrompt) && !/[\\u3040-\\u30ff]/.test(scannedPrompt)\n ? \"zh\"\n : \"other\";\n const multipleChoiceSignals = (scannedPrompt.match(/(?:^|\\n)\\s*[A-D][.)]\\s+/gim) ?? []).length;\n const numericSignals = (scannedPrompt.match(/-?\\d+(?:[.,]\\d+)?/g) ?? []).length;\n const compactMathProblem =\n !hasCode &&\n prompt.length < 2_500 &&\n numericSignals >= 2 &&\n (/[+×÷=%$€£¥]|\\b(?:total|each|per|times|half|twice|percent|how many|how much|calculate)\\b/i.test(\n scannedPrompt,\n ) ||\n /[??]\\s*$/.test(scannedPrompt.trim()) ||\n numericSignals >= 3);\n\n let taskType: TaskType = \"chat\";\n if (needsVision) taskType = \"vision\";\n else if (estimatedInputTokens > 80_000) taskType = \"long_context\";\n else if (needsTools && (codeArtifact || (hasCode && codingAction) || implicitTerminalCode))\n taskType = \"code_agent\";\n else if (needsTools && likelyParallelToolCalls && !complexMultiToolPlan)\n taskType = \"tool_agent_parallel\";\n else if (needsTools) taskType = \"tool_agent\";\n else if (multipleChoiceSignals >= 3) taskType = \"reasoning_mcq\";\n else if (compactMathProblem) taskType = \"reasoning_math\";\n else if (\n errorClassSignal ||\n /\\b(?:bug|debug|error|failure|failing|regression|crash)\\b|修复|报错|错误|调试/i.test(text)\n )\n taskType = \"debug\";\n else if (hasCode || /\\b(?:refactor|implement|patch|edit|rewrite)\\b|重构|实现|修改/i.test(text))\n taskType = \"code_edit\";\n else if (needsStructuredOutput || /\\b(?:extract|json|schema|csv)\\b|字段|提取/i.test(text))\n taskType = \"extraction\";\n else if (\n /\\b(?:prove|derive|theorem|formal|mathematical|reasoning)\\b|证明|推导|定理|数学/i.test(text)\n )\n taskType = \"reasoning\";\n\n return {\n taskType,\n estimatedInputTokens,\n hasCode,\n needsTools,\n toolsAvailable,\n needsVision,\n needsStructuredOutput,\n latencySensitive,\n highStakes,\n language,\n likelyParallelToolCalls,\n complexMultiToolPlan,\n agentDomain,\n deepWebResearch,\n agentRisk,\n terminalToolSignal,\n terminalSafetySensitive,\n implicitTerminalCode,\n codeArtifact,\n };\n}\n\n/**\n * Task-affinity bands. Each table maps a model name (the id after the\n * provider slash) to its calibrated affinity for one request shape; anything\n * absent scores the neutral `NEUTRAL_AFFINITY`. Names are matched exactly:\n * model family names are intentionally similar (`gemini-2.5-flash` vs\n * `gemini-2.5-flash-lite`), and a substring match would let a smaller sibling\n * inherit a capability claim measured only for the flagship. A sibling joins a\n * band only with its own evidence.\n */\ntype AffinityBand = Readonly>;\n\n/** Affinity of a model with no task-specific evidence. */\nconst NEUTRAL_AFFINITY = 0.68;\n\n// Strong native tool loop until the Responses function-output fix is deployed\n// on both gateways; Codex stays available below auto's affinity floor. Sonnet\n// has a verified native multi-turn tool loop and is the safe strong default.\nconst TERMINAL_COMPLEX_HIGH: AffinityBand = {\n \"claude-sonnet-5\": 1,\n \"gpt-5.3-codex\": 0.87,\n \"gpt-5-mini\": 0.78,\n \"gemini-3.5-flash\": 0.76,\n};\n\n// Complete-session BrowseComp calibration supersedes the earlier single-case\n// Opus promotion: strict deduplicated evidence has Sonnet 5 at 2/9 versus Opus\n// 5 at 0/3, while Opus also costs more and has a much longer tail. Opus stays\n// an availability fallback until a larger stable-provider sample supports it.\nconst WEB_RESEARCH_DEEP: AffinityBand = {\n \"claude-sonnet-5\": 1,\n \"gpt-5-mini\": 0.88,\n \"gemini-3.5-flash\": 0.84,\n \"claude-opus-5\": 0.8,\n \"claude-opus-4.8\": 0.78,\n};\nconst WEB_RESEARCH: AffinityBand = {\n \"claude-sonnet-5\": 1,\n \"gpt-5-mini\": 0.88,\n \"gemini-3.5-flash\": 0.86,\n \"claude-opus-5\": 0.84,\n \"claude-opus-4.8\": 0.82,\n};\n\nconst RETAIL_POLICY_EXCEPTION: AffinityBand = {\n \"gpt-4.1\": 1,\n \"claude-sonnet-5\": 0.9,\n \"deepseek-v4-pro\": 0.82,\n \"gpt-5-mini\": 0.8,\n \"gpt-4o-mini\": 0.76,\n};\nconst RETAIL_POLICY_EXCEPTION_SIMPLE: AffinityBand = {\n \"gpt-5-mini\": 1,\n \"gpt-4.1\": 0.86,\n \"deepseek-v4-pro\": 0.82,\n \"gpt-4o-mini\": 0.8,\n};\n\nconst AFFINITY = {\n // Seven valid full agent + official Terminal-Bench trajectories (2026-07-28)\n // gave GPT-5 Mini 4/7 resolved tasks versus 1/7 for the prior dynamic\n // code-agent choice. Its token-normalized total cost was higher in this small\n // calibration, so Codex and Sonnet keep quality priors above it; admitting\n // Mini to the scoring band lets the normal quality/cost profile choose it\n // without erasing stronger fallbacks. DeepSeek V4 Pro is kept below the\n // primary band after two consecutive mid-trajectory provider timeouts\n // contaminated its calibration runs.\n codeAgent: {\n \"gpt-5.3-codex\": 1,\n \"claude-sonnet-5\": 0.98,\n \"gpt-5-mini\": 0.96,\n \"gemini-3.5-flash\": 0.92,\n \"kimi-k3\": 0.9,\n \"deepseek-v4-pro\": 0.88,\n \"glm-5.2\": 0.88,\n },\n // Seven official Terminal-Bench calibration trajectories favoured GPT-5 Mini\n // over the prior dynamic choice. Codex/Sonnet are close fallbacks; actual\n // request cost breaks the tie.\n terminalTool: {\n \"gpt-5-mini\": 1,\n \"gpt-5.3-codex\": 0.98,\n \"claude-sonnet-5\": 0.9,\n \"gemini-3.5-flash\": 0.89,\n },\n // Two complete agent observations on the public Terminal-Bench\n // new-encrypt-command task ended in Codex repeating the same TerminalExec\n // input until the loop guard fired. Codex stays an availability fallback,\n // below the safety-band affinity floor, until its Responses function-output\n // path is verified on both gateways.\n terminalToolSafety: {\n \"claude-sonnet-5\": 1,\n \"claude-opus-4.8\": 0.9,\n \"gpt-5.3-codex\": 0.84,\n },\n // Full-session calibration: GPT-5 Mini completed two local/single retail\n // workflows at a fraction of Sonnet's token cost. It stays ineligible for\n // promotion when the prompt asks for multiple actions, cross-record\n // discovery or a global optimum; those trajectories exposed unstable write\n // arguments. DeepSeek V4 Pro completed all three high-risk retail calibration\n // trajectories (global-choice, cross-record, multi-write); Sonnet one.\n retailStandard: {\n \"gpt-5-mini\": 1,\n \"claude-sonnet-5\": 0.88,\n \"gemini-3.5-flash\": 0.82,\n \"gpt-5.3-codex\": 0.81,\n \"kimi-k3\": 0.78,\n \"deepseek-v4-pro\": 0.76,\n },\n retailHigh: {\n \"deepseek-v4-pro\": 1,\n \"claude-sonnet-5\": 0.88,\n \"gemini-3.5-flash\": 0.82,\n \"gpt-5.3-codex\": 0.81,\n \"kimi-k3\": 0.78,\n \"gpt-5-mini\": 0.76,\n },\n // Standard airline workflows stay on GPT-5 Mini: six full-session\n // development trajectories gave it the same 5/6 success as Sonnet at roughly\n // one order of magnitude lower normalized token cost. A held-out high-risk\n // cabin/date negotiation then produced a persistent empty assistant turn on\n // Mini even after a semantic retry, while Sonnet 5 completed the identical\n // official tau2 trajectory with reward 1.0. Only global optimization /\n // conditional-global work is promoted. A known batch of reservations is\n // operationally high-risk but still a structured tool workflow: current Tau\n // evidence has Mini and Sonnet at equal task reward there, while Sonnet costs\n // roughly two orders of magnitude more on the long-tail case.\n airlineComplex: {\n \"claude-sonnet-5\": 1,\n \"gpt-5-mini\": 0.78,\n \"gemini-3.5-flash\": 0.76,\n \"deepseek-v4-pro\": 0.74,\n },\n airlineStandard: {\n \"gpt-5-mini\": 1,\n \"claude-sonnet-5\": 0.9,\n \"gemini-3.5-flash\": 0.8,\n \"deepseek-v4-pro\": 0.76,\n },\n // Full-trajectory tau2 calibration (2026-07-28, official gpt-4.1 simulator):\n // Sonnet 5 completed both an airline policy task and a retail multi-write\n // task with reward 1.0. Gemini 3.5 Flash emitted function calls as plain text\n // after the first structured calls and looped to the 100-step ceiling on the\n // airline task.\n toolAgent: {\n \"claude-sonnet-5\": 1,\n \"gemini-3.5-flash\": 0.88,\n \"gpt-5.3-codex\": 0.87,\n \"kimi-k3\": 0.85,\n \"gpt-5-mini\": 0.84,\n \"deepseek-v4-pro\": 0.82,\n },\n // Multi-file Terminal work is not equivalent to a one-turn parallel\n // function-call benchmark. Sonnet is the strongest trajectory-tested\n // cost-controlled default; Opus remains a close safety fallback.\n parallelTerminalSafety: {\n \"claude-sonnet-5\": 1,\n \"claude-opus-4.8\": 0.9,\n \"gpt-5.3-codex\": 0.86,\n },\n parallelTerminal: {\n \"gpt-5-mini\": 1,\n \"gpt-5.3-codex\": 0.98,\n \"claude-sonnet-5\": 0.92,\n \"gemini-3.5-flash\": 0.88,\n },\n parallelRetail: {\n \"deepseek-v4-pro\": 1,\n \"claude-sonnet-5\": 0.88,\n \"claude-opus-4.8\": 0.84,\n \"gpt-5-mini\": 0.78,\n \"gemini-3.5-flash\": 0.76,\n },\n parallelAirlineComplex: {\n \"claude-sonnet-5\": 1,\n \"gpt-5-mini\": 0.78,\n \"claude-opus-4.8\": 0.76,\n \"gemini-3.5-flash\": 0.74,\n },\n parallelAirline: {\n \"gpt-5-mini\": 1,\n \"claude-sonnet-5\": 0.9,\n \"gemini-3.5-flash\": 0.8,\n },\n // RouterBench calibration, 2026-07-26: Opus 4.8 produced complete multi-call\n // payloads on 2/3 multilingual BFCL parallel cases. Gemini 3.5 Flash, Sonnet\n // 5, DeepSeek V4 Pro and Grok 4.5 were 0/3. This narrow prior only applies\n // after the conservative prompt feature in likelyNeedsParallelToolCalls.\n parallel: {\n \"claude-opus-4.8\": 1,\n \"claude-sonnet-5\": 0.84,\n \"grok-4.5\": 0.82,\n \"gemini-3.5-flash\": 0.8,\n \"deepseek-v4-pro\": 0.78,\n },\n codeEdit: {\n \"gpt-5.3-codex\": 1,\n \"claude-sonnet-4.6\": 0.94,\n \"glm-5.2\": 0.9,\n \"deepseek-v4-pro\": 0.86,\n },\n reasoning: {\n \"claude-sonnet-5\": 0.98,\n \"claude-sonnet-4.6\": 0.98,\n \"deepseek-v4-pro\": 0.95,\n \"grok-4.5\": 0.94,\n \"gemini-3.1-pro\": 0.92,\n \"gemini-3.5-flash\": 0.92,\n },\n // RouterBench calibration (2026-07-28, six stratified GPQA Diamond tasks,\n // identical agent adapter and 512-token budget): Gemini 3 Flash Preview\n // scored 5/6, Gemini 3.5 Flash 4/6, and Gemini 3.1 Pro 3/6 while costing\n // ~170x more than Flash. The measured winner is the narrow default; version\n // recency alone is not a quality signal. Unused host tools must not change\n // this reasoning-only model choice.\n reasoningMcq: {\n \"gemini-3-flash-preview\": 1,\n \"gemini-3.5-flash\": 0.91,\n \"grok-4.5\": 0.9,\n \"claude-sonnet-5\": 0.88,\n \"deepseek-v4-pro\": 0.84,\n },\n // Same calibration, five multilingual MGSM tasks: Gemini 3.5 Flash was 5/5\n // with the lowest cost and latency; four current flagships were 4/5 and Kimi\n // K2.7 was 3/5.\n reasoningMath: {\n \"gemini-3.5-flash\": 1,\n \"grok-4.5\": 0.93,\n \"claude-sonnet-5\": 0.9,\n \"deepseek-v4-pro\": 0.9,\n \"kimi-k3\": 0.9,\n },\n vision: {\n \"gemini-3.1-pro\": 0.96,\n \"qwen3.7-max\": 0.9,\n \"claude-sonnet-4.6\": 0.9,\n \"kimi-k3\": 0.9,\n \"grok-4.3\": 0.9,\n },\n // Long-context eligibility is necessary but not sufficient: a provider can\n // advertise a 1M window yet return an empty completion near that boundary.\n // The proven long-context flagship leads, and less-established alternatives\n // sit in a separate band so price alone cannot displace it.\n longContext: {\n \"gemini-3.1-pro\": 1,\n \"qwen3.7-max\": 0.89,\n \"glm-5.2\": 0.89,\n \"gemini-3.5-flash\": 0.88,\n \"deepseek-v4-pro\": 0.85,\n },\n // A structured extraction must preserve both the output contract and the\n // source-language fields. For Mandarin input the language-native Kimi\n // candidate gets a distinct band — a candidate-pool decision, not a post-hoc\n // override, so it still falls back normally when Kimi is unavailable. Kimi\n // K3 costs ~5x its retired sibling K2.7, so the band must be wider than the\n // auto affinityFloorGap (0.10) or price alone re-selects a non-native model\n // for Mandarin input; 0.12 keeps K3 alone in the primary band for zh and\n // leaves every other language untouched.\n extractionZh: {\n \"kimi-k3\": 1,\n \"gemini-3.5-flash\": 0.88,\n \"gemini-2.5-flash\": 0.88,\n \"gpt-4o-mini\": 0.88,\n \"claude-sonnet-5\": 0.88,\n \"claude-sonnet-4.6\": 0.88,\n },\n extraction: {\n \"kimi-k3\": 0.9,\n \"gemini-3.5-flash\": 0.9,\n \"gemini-2.5-flash\": 0.9,\n \"gpt-4o-mini\": 0.9,\n \"claude-sonnet-5\": 0.9,\n \"claude-sonnet-4.6\": 0.9,\n },\n chat: {\n \"gemini-3.5-flash\": 0.86,\n \"gemini-2.5-flash\": 0.86,\n \"kimi-k3\": 0.86,\n },\n} as const satisfies Record;\n\n/** The affinity band that applies to a classified request. */\nfunction affinityBand(features: TaskFeatures): AffinityBand {\n const { taskType, agentDomain, agentRisk, deepWebResearch, terminalToolSignal } = features;\n const terminalSafety = features.terminalSafetySensitive;\n switch (taskType) {\n case \"code_agent\":\n return terminalToolSignal && agentRisk === \"complex_high\"\n ? TERMINAL_COMPLEX_HIGH\n : AFFINITY.codeAgent;\n case \"tool_agent\":\n if (terminalToolSignal && agentRisk === \"complex_high\") return TERMINAL_COMPLEX_HIGH;\n if (terminalToolSignal) return terminalSafety ? AFFINITY.terminalToolSafety : AFFINITY.terminalTool;\n if (agentDomain === \"web_research\") return deepWebResearch ? WEB_RESEARCH_DEEP : WEB_RESEARCH;\n if (agentDomain === \"retail\") {\n if (agentRisk === \"standard\") return AFFINITY.retailStandard;\n if (agentRisk === \"policy_exception\") return RETAIL_POLICY_EXCEPTION;\n if (agentRisk === \"policy_exception_simple\") return RETAIL_POLICY_EXCEPTION_SIMPLE;\n return AFFINITY.retailHigh;\n }\n if (agentDomain === \"airline\") {\n return agentRisk === \"complex_high\" ? AFFINITY.airlineComplex : AFFINITY.airlineStandard;\n }\n return AFFINITY.toolAgent;\n case \"tool_agent_parallel\":\n if (terminalToolSignal) {\n return terminalSafety ? AFFINITY.parallelTerminalSafety : AFFINITY.parallelTerminal;\n }\n if (agentDomain === \"web_research\") return deepWebResearch ? WEB_RESEARCH_DEEP : WEB_RESEARCH;\n if (agentDomain === \"retail\") {\n if (agentRisk === \"policy_exception\") return RETAIL_POLICY_EXCEPTION;\n if (agentRisk === \"policy_exception_simple\") return RETAIL_POLICY_EXCEPTION_SIMPLE;\n return AFFINITY.parallelRetail;\n }\n if (agentDomain === \"airline\") {\n return agentRisk === \"complex_high\" ? AFFINITY.parallelAirlineComplex : AFFINITY.parallelAirline;\n }\n return AFFINITY.parallel;\n case \"code_edit\":\n case \"debug\":\n return AFFINITY.codeEdit;\n case \"reasoning\":\n return AFFINITY.reasoning;\n case \"reasoning_mcq\":\n return AFFINITY.reasoningMcq;\n case \"reasoning_math\":\n return AFFINITY.reasoningMath;\n case \"vision\":\n return AFFINITY.vision;\n case \"long_context\":\n return AFFINITY.longContext;\n case \"extraction\":\n return features.language === \"zh\" ? AFFINITY.extractionZh : AFFINITY.extraction;\n case \"chat\":\n return AFFINITY.chat;\n }\n}\n\n/** A model's affinity within a band: its calibrated score, never below neutral. */\nfunction affinityIn(band: AffinityBand, modelId: string): number {\n const name = modelId.toLowerCase().slice(modelId.indexOf(\"/\") + 1);\n return Math.max(NEUTRAL_AFFINITY, band[name] ?? 0);\n}\n\nfunction evidenceCandidates(task: TaskType): string[] {\n if (task === \"code_agent\") {\n return [\n \"openai/gpt-5.3-codex\",\n \"anthropic/claude-sonnet-5\",\n \"openai/gpt-5-mini\",\n \"google/gemini-3.5-flash\",\n \"moonshot/kimi-k3\",\n \"deepseek/deepseek-v4-pro\",\n ];\n }\n if (task === \"tool_agent\") {\n return [\n \"anthropic/claude-sonnet-5\",\n \"anthropic/claude-opus-5\",\n \"openai/gpt-5-mini\",\n \"openai/gpt-4.1\",\n \"openai/gpt-4o-mini\",\n \"google/gemini-3.5-flash\",\n \"openai/gpt-5.3-codex\",\n \"moonshot/kimi-k3\",\n \"deepseek/deepseek-v4-pro\",\n ];\n }\n if (task === \"tool_agent_parallel\") {\n return [\n \"anthropic/claude-opus-5\",\n \"anthropic/claude-opus-4.8\",\n \"anthropic/claude-sonnet-5\",\n \"openai/gpt-5-mini\",\n \"openai/gpt-4.1\",\n \"openai/gpt-4o-mini\",\n \"xai/grok-4.5\",\n \"google/gemini-3.5-flash\",\n \"deepseek/deepseek-v4-pro\",\n ];\n }\n if (task === \"long_context\") {\n return [\n \"google/gemini-3.1-pro\",\n \"deepseek/deepseek-v4-pro\",\n \"qwen/qwen3.7-max\",\n \"zai/glm-5.2\",\n \"google/gemini-3.5-flash\",\n ];\n }\n if (task === \"reasoning_mcq\") {\n return [\n \"google/gemini-3-flash-preview\",\n \"google/gemini-3.5-flash\",\n \"xai/grok-4.5\",\n \"anthropic/claude-sonnet-5\",\n \"deepseek/deepseek-v4-pro\",\n ];\n }\n if (task === \"extraction\") {\n // Kimi K3 is no longer on the auto MEDIUM chain (K2.7 was); the\n // language-native extraction band (AFFINITY.extractionZh) needs it in the pool.\n return [\"moonshot/kimi-k3\", \"google/gemini-3.5-flash\", \"anthropic/claude-sonnet-5\"];\n }\n if (task === \"reasoning_math\") {\n return [\n \"google/gemini-3.5-flash\",\n \"xai/grok-4.5\",\n \"anthropic/claude-sonnet-5\",\n \"deepseek/deepseek-v4-pro\",\n \"moonshot/kimi-k3\",\n ];\n }\n return [];\n}\n\n/**\n * Recently added catalog models with a verified structured function call.\n *\n * Tool compliance is enough to make these models safe availability fallbacks,\n * but it is not evidence that they should displace a trajectory-benchmarked\n * primary. Keep them after the configured and benchmark-backed chains until a\n * full agent evaluation earns a task-specific affinity above NEUTRAL_AFFINITY\n * floor. `isEligible` still applies every host capability override, context\n * limit, vision constraint, and unavailable-model guard before they are used.\n */\nconst VERIFIED_TOOL_FALLBACKS = [\n \"anthropic/claude-fable-5.1\",\n \"anthropic/claude-opus-5.5\",\n \"anthropic/claude-sonnet-5.5\",\n \"deepseek/deepseek-v4.1-flash\",\n \"google/gemini-3.8-flash\",\n \"openai/gpt-5.1\",\n \"openai/gpt-6-astra\",\n \"openai/gpt-6-luna\",\n \"openai/gpt-6-sol\",\n \"openai/gpt-6.1-sol\",\n \"xai/grok-4.6\",\n \"xai/grok-4.7\",\n \"xiaomi/mimo-v2.5\",\n] as const;\n\nfunction isEligible(\n modelId: string,\n features: TaskFeatures,\n maxOutputTokens: number,\n options: RouterOptions,\n): boolean {\n const model = options.modelCapabilities?.[modelId] ?? DEFAULT_MODEL_CAPABILITIES[modelId];\n // Preserve compatibility for temporarily catalog-less fallback IDs. They are\n // kept behind known-model candidates but are not silently dropped.\n if (!model) return true;\n if (features.needsTools && !model.supportsTools) return false;\n if (features.needsVision && !model.supportsVision) return false;\n if (features.needsStructuredOutput && !model.supportsTools) return false;\n if (model.maxOutputTokens < maxOutputTokens) return false;\n return model.contextWindow >= (features.estimatedInputTokens + maxOutputTokens) * 1.1;\n}\n\nfunction estimatedCost(\n modelId: string,\n options: RouterOptions,\n inputTokens: number,\n outputTokens: number,\n): number {\n const price = usablePricing(options.modelPricing.get(modelId));\n if (!price) return Number.POSITIVE_INFINITY;\n if (price.flatPrice !== undefined) return price.flatPrice;\n return (inputTokens * price.inputPrice + outputTokens * price.outputPrice) / 1_000_000;\n}\n\nfunction profileScore(\n modelId: string,\n options: RouterOptions,\n now: Date,\n):\n | { quality?: number; speed: number; tailSpeed: number; reliability: number; freshness: number }\n | undefined {\n const profile: ModelPerformanceProfile | undefined =\n options.modelPerformance?.[modelId] ??\n LIVE_MODEL_PROFILES[modelId] ??\n HISTORICAL_MODEL_PROFILES[modelId];\n if (!profile) return undefined;\n const measuredAt = Date.parse(profile.measuredAt);\n if (!Number.isFinite(measuredAt)) return undefined;\n // A host-injected observation with a missing or non-numeric field would\n // turn the whole score into NaN, and NaN compares as \"equal\" in the sort,\n // freezing that candidate wherever it landed. Treat it as no observation.\n const finite = (value: number | undefined, optional: boolean) =>\n value === undefined ? optional : Number.isFinite(value) && value >= 0;\n if (\n !finite(profile.latencyMs, false) ||\n !finite(profile.outputTokensPerSecond, false) ||\n !finite(profile.p95LatencyMs, true) ||\n !finite(profile.intelligenceIndex, true) ||\n !finite(profile.errorRate, true) ||\n !finite(profile.samples, true)\n ) {\n return undefined;\n }\n const ageDays = Math.max(0, (now.getTime() - measuredAt) / 86_400_000);\n // A 30-day half-life makes old data a tie-breaker only. Small probe runs are\n // also weak evidence: three quick samples should not overturn a curated\n // tier ordering merely because of a transient provider tail. Callers that\n // inject an observation without a sample count retain the legacy full\n // confidence behaviour for compatibility.\n const sampleConfidence =\n profile.samples === undefined ? 1 : Math.min(1, Math.max(0, profile.samples) / 10);\n const freshness = Math.pow(0.5, ageDays / 30) * sampleConfidence;\n const quality =\n profile.intelligenceIndex === undefined\n ? undefined\n : Math.min(1, profile.intelligenceIndex / 50);\n const speed = Math.min(\n 1,\n (2_000 / Math.max(500, profile.latencyMs) + profile.outputTokensPerSecond / 250) / 2,\n );\n const tailSpeed = Math.min(1, 3_000 / Math.max(750, profile.p95LatencyMs ?? profile.latencyMs));\n const reliability = Math.max(0, 1 - (profile.errorRate ?? 0));\n return { quality, speed, tailSpeed, reliability, freshness };\n}\n\n/** Candidate router used for Auto. Rules still set the capability tier; V3 ranks within it. */\nexport class PortfolioStrategy implements RouterStrategy {\n readonly name = \"portfolio\";\n // Rules set the capability tier; the strategy is stateless, so one instance serves every request.\n private readonly rules = new RulesStrategy();\n\n route(\n prompt: string,\n systemPrompt: string | undefined,\n maxOutputTokens: number,\n options: RouterOptions,\n ) {\n const features = classifyTask(prompt, systemPrompt, options);\n const base = this.rules.route(prompt, systemPrompt, maxOutputTokens, {\n ...options,\n requiresTools: features.needsTools,\n });\n const tierConfigs = base.tierConfigs;\n if (!tierConfigs) return base;\n // The rules score sets the capability tier, but two task types carry a\n // floor of their own: a compact reasoning problem belongs on the\n // reasoning chain however short it is, and a code edit or stack trace\n // belongs at least on the MEDIUM chain — the SIMPLE chain is curated for\n // trivia and translation and has no model with code affinity. The code\n // floor requires a code artifact or coding action: `debug` and `code_edit`\n // are also assigned from bare verbs (\"rewrite this sentence\", \"margin of\n // error\") and bare language names (\"What is Python?\"), and that prose\n // must stay on the cheap chain.\n const targetTier: Tier =\n (features.taskType === \"reasoning_mcq\" || features.taskType === \"reasoning_math\") &&\n (base.tier === \"SIMPLE\" || base.tier === \"MEDIUM\")\n ? \"REASONING\"\n : (features.taskType === \"debug\" || features.taskType === \"code_edit\") &&\n features.codeArtifact &&\n base.tier === \"SIMPLE\"\n ? \"MEDIUM\"\n : base.tier;\n const tierConfig = tierConfigs[targetTier];\n const configuredCandidates = tierConfig ? getFallbackChain(targetTier, tierConfigs) : [];\n // Evidence candidates join the configured chain, but the host's\n // unavailable set applies to both: the configured side arrives filtered\n // through RulesStrategy, and a dead evidence model must not re-enter here.\n const unavailable = new Set(options.unavailableModels ?? []);\n // `modelPricing` is the host's live catalog view. Do not introduce a\n // built-in fallback that the current gateway does not advertise. These\n // models carry no task evidence, so outside Premium the cheapest one is\n // the first recovery hop; otherwise an outage of the curated chain would\n // jump an Eco turn straight to the most expensive model in the list.\n const verifiedToolFallbacks = features.needsTools\n ? VERIFIED_TOOL_FALLBACKS.filter((model) => options.modelPricing.has(model))\n : [];\n if (options.routingProfile !== \"premium\") {\n const fallbackCost = (model: string) =>\n estimatedCost(model, options, features.estimatedInputTokens, maxOutputTokens);\n verifiedToolFallbacks.sort((a, b) => fallbackCost(a) - fallbackCost(b));\n }\n const chain = [\n ...new Set([\n ...configuredCandidates,\n ...evidenceCandidates(features.taskType),\n ...verifiedToolFallbacks,\n ]),\n ].filter(\n (model): model is string =>\n typeof model === \"string\" && model.length > 0 && !unavailable.has(model),\n );\n const eligible = new Set(\n chain.filter((model) => isEligible(model, features, maxOutputTokens, options)),\n );\n // When nothing is eligible the whole chain competes, scored as incapable.\n const eligibleCandidates = eligible.size > 0 ? [...eligible] : chain;\n if (eligibleCandidates.length === 0) return base;\n const profileName =\n options.routingProfile === \"eco\"\n ? \"eco\"\n : options.routingProfile === \"premium\"\n ? \"premium\"\n : \"auto\";\n const portfolio = options.config.portfolio ?? DEFAULT_PORTFOLIO_WEIGHTS;\n const band = affinityBand(features);\n const affinityCache = new Map();\n const getAffinity = (model: string) => {\n let value = affinityCache.get(model);\n if (value === undefined) {\n value = affinityIn(band, model);\n affinityCache.set(model, value);\n }\n return value;\n };\n const bestAffinity = Math.max(...eligibleCandidates.map(getAffinity));\n const specificAffinity = eligibleCandidates.filter((model) => getAffinity(model) > NEUTRAL_AFFINITY);\n // A tier's fallback list is primarily an availability/recovery chain, not a\n // set of equally validated substitutes. Re-ranking every fallback lets a\n // cheap generic model displace the curated primary merely because it has a\n // favourable short performance probe. Only promote models with explicit\n // task affinity; otherwise retain the first capability-eligible tier model.\n const affinityPool = specificAffinity.length > 0 ? specificAffinity : [eligibleCandidates[0]];\n // Generic Terminal work has much wider trajectory variance than a BFCL-like\n // one-turn parallel call. Keep the strong-model safety band, but admit the\n // next capable tier so Auto's cost/reliability score can reject an Opus\n // primary that is materially more expensive without measured benefit.\n const affinityFloorGap = features.terminalToolSignal\n ? Math.max(\n portfolio.affinityFloorGap[profileName],\n features.terminalSafetySensitive ? 0.15 : 0.12,\n )\n : portfolio.affinityFloorGap[profileName];\n const candidates = affinityPool.filter(\n (model) => getAffinity(model) >= bestAffinity - affinityFloorGap,\n );\n const costs = candidates.map((model) =>\n estimatedCost(model, options, features.estimatedInputTokens, maxOutputTokens),\n );\n const finiteCosts = costs.filter(Number.isFinite);\n const minCost = finiteCosts.length > 0 ? Math.min(...finiteCosts) : 0;\n const maxCost = finiteCosts.length > 0 ? Math.max(...finiteCosts) : 1;\n\n const now = options.now ?? new Date();\n const profileWeights = portfolio[profileName];\n const rankedEntries = candidates\n .map((model, index) => {\n const cost = costs[index];\n // An unpriced candidate costs an unknown amount, so it scores as the\n // most expensive rather than a neutral 0.5 that let it outrank\n // priced models. Pricing presence still never filters a candidate.\n const costScore = !Number.isFinite(cost)\n ? 0\n : maxCost > minCost\n ? 1 - (cost - minCost) / (maxCost - minCost)\n : 0.5;\n const capabilityScore = eligible.has(model) ? 1 : 0;\n const profile = profileScore(model, options, now);\n // Fresh observations can refine affinity. Historical observations fade\n // quickly and never replace task-level RouterBench evidence.\n const observedQuality =\n profile?.quality === undefined\n ? getAffinity(model)\n : getAffinity(model) * (1 - profile.freshness) + profile.quality * profile.freshness;\n // Every observed dimension fades toward its neutral prior as the\n // observation ages, exactly like reliability below. Fading speed\n // toward zero instead ranked any model with a stale probe below a\n // model nobody had measured, which the latter's 0.5 silently won.\n const observedSpeed = profile\n ? profile.speed * profile.freshness + 0.5 * (1 - profile.freshness)\n : 0.5;\n const observedTailSpeed = profile\n ? profile.tailSpeed * profile.freshness + 0.5 * (1 - profile.freshness)\n : 0.5;\n const observedReliability = profile\n ? profile.reliability * profile.freshness + (1 - profile.freshness)\n : 1;\n // Preserve a small amount of the hand-curated fallback order while V3's\n // task affinity and real request constraints do the primary work.\n const legacyScore = 1 - index / Math.max(1, candidates.length - 1);\n const qualityWeight =\n profileWeights.quality + (features.highStakes ? portfolio.highStakesBoost.quality : 0);\n const speedScore = features.latencySensitive ? observedTailSpeed : observedSpeed;\n const speedWeight =\n profileWeights.speed +\n (features.latencySensitive ? portfolio.latencySensitiveSpeedBoost : 0);\n const reliabilityWeight =\n profileWeights.reliability +\n (features.highStakes ? portfolio.highStakesBoost.reliability : 0);\n const score =\n observedQuality * qualityWeight +\n capabilityScore * profileWeights.capability +\n costScore * profileWeights.cost +\n speedScore * speedWeight +\n observedReliability * reliabilityWeight +\n legacyScore * profileWeights.legacy;\n return {\n model,\n score,\n quality: observedQuality,\n cost: costScore,\n speed: speedScore,\n reliability: observedReliability,\n };\n })\n .sort((a, b) => b.score - a.score);\n const scoredModels = rankedEntries.map((item) => item.model);\n // The affinity floor controls which models may compete for the primary;\n // it must not erase availability fallbacks. Append all remaining eligible\n // models in their curated chain order after the scored primary pool.\n const webResearchFallbackOrder = [\n \"anthropic/claude-sonnet-5\",\n \"openai/gpt-5-mini\",\n \"google/gemini-3.5-flash\",\n \"anthropic/claude-opus-5\",\n \"anthropic/claude-opus-4.8\",\n \"openai/gpt-5.3-codex\",\n ];\n const ranked =\n features.agentDomain === \"web_research\"\n ? [\n ...scoredModels,\n ...webResearchFallbackOrder.filter(\n (model) => eligibleCandidates.includes(model) && !scoredModels.includes(model),\n ),\n ...eligibleCandidates.filter(\n (model) => !scoredModels.includes(model) && !webResearchFallbackOrder.includes(model),\n ),\n ]\n : [...scoredModels, ...eligibleCandidates.filter((model) => !scoredModels.includes(model))];\n\n const model = ranked[0] ?? base.model;\n const selectedTierConfigs: Record = {\n ...tierConfigs,\n [targetTier]: { primary: model, fallback: ranked.slice(1) },\n };\n // selectModel only reads the selected tier; retain the complete tier map for host fallback.\n const decision = selectModel(\n targetTier,\n base.confidence,\n \"portfolio\",\n `${base.reasoning} | v3 task=${features.taskType} agentRisk=${features.agentRisk} deepWebResearch=${features.deepWebResearch} terminalCode=${features.implicitTerminalCode} terminalSafety=${features.terminalSafetySensitive} candidates=${ranked.length}`,\n selectedTierConfigs,\n options.modelPricing,\n features.estimatedInputTokens,\n maxOutputTokens,\n options.routingProfile,\n base.agenticScore,\n );\n return {\n ...decision,\n tierConfigs: selectedTierConfigs,\n profile: base.profile,\n candidates: ranked,\n candidateScores: rankedEntries.map(({ model, score, quality, cost, speed, reliability }) => ({\n model,\n score,\n quality,\n cost,\n speed,\n reliability,\n })),\n taskType: features.taskType,\n routerVersion: \"v3-portfolio\" as const,\n };\n }\n}\n","/** Pure public-catalog parsing. Fetching, caching and UI ordering belong to hosts. */\nimport { DEFAULT_MODEL_CAPABILITIES, type ModelCapabilities } from \"./model-capabilities.js\";\nimport type { ModelPricing } from \"./selector.js\";\n\nexport const MODEL_KINDS = [\"chat\", \"image\", \"video\", \"music\"] as const;\nexport type ModelKind = (typeof MODEL_KINDS)[number];\n\n/** Gateway units are preserved: token prices per 1M tokens; media per unit. */\nexport interface CatalogPricing {\n input?: number;\n output?: number;\n per_image?: number;\n per_second?: number;\n per_track?: number;\n cache_read?: number;\n cache_write?: number;\n transaction_fee?: number;\n per_call_surcharge?: number;\n default_duration_seconds?: number;\n max_duration_seconds?: number;\n}\n\nexport interface CatalogModel {\n id: string;\n name: string;\n categories: readonly string[];\n kinds: readonly ModelKind[];\n billingMode?: string;\n /** Zero pricing alone does not imply a free model. */\n free: boolean;\n pricing: CatalogPricing;\n contextWindow?: number;\n maxOutputTokens?: number;\n}\n\nexport interface ModelCatalog {\n models: readonly CatalogModel[];\n chat: readonly CatalogModel[];\n image: readonly CatalogModel[];\n video: readonly CatalogModel[];\n music: readonly CatalogModel[];\n /**\n * IDs whose authoritative row says `available: false`. The gateway does not\n * reject these; it substitutes another model. Absence from the listing is\n * not unavailability: hidden IDs are still served.\n */\n unavailable: readonly string[];\n}\n\nconst PRICE_KEYS = [\n \"input\", \"output\", \"per_image\", \"per_second\", \"per_track\", \"cache_read\", \"cache_write\",\n \"transaction_fee\", \"per_call_surcharge\", \"default_duration_seconds\", \"max_duration_seconds\",\n] as const;\nconst UNIT_PRICE = { image: \"per_image\", video: \"per_second\", music: \"per_track\" } as const;\nconst MODEL_ID = /^[a-z0-9][a-z0-9._-]*\\/[a-zA-Z0-9][a-zA-Z0-9._:+-]*$/;\nconst record = (value: unknown): value is Record =>\n value !== null && typeof value === \"object\" && !Array.isArray(value);\nconst price = (value: unknown): value is number =>\n typeof value === \"number\" && Number.isFinite(value) && value >= 0;\nconst capacity = (value: unknown): number | undefined =>\n typeof value === \"number\" && Number.isSafeInteger(value) && value > 0 ? value : undefined;\n\n/**\n * Normalize GET /api/v1/models without a model-ID allowlist. New provider IDs\n * appear immediately. Hidden/unavailable rows and invalid per-kind prices are\n * omitted. A malformed envelope throws so a host can retain its last good list;\n * an explicitly empty `data` array is a valid empty catalog.\n *\n * IDs explicitly marked `available: false` are also listed in `unavailable`.\n * Rows outside MODEL_KINDS (speech, sound effects) are omitted.\n *\n * Last duplicate wins, including a final unavailable/invalid row. No sorting,\n * price markup, network request, capability probe or media routing is performed.\n */\nexport function parseModelCatalog(value: unknown): ModelCatalog {\n if (!record(value) || !Array.isArray(value.data)) {\n throw new TypeError(\"Model catalog must contain a data array\");\n }\n const entries = new Map>();\n for (const entry of value.data) {\n if (record(entry) && typeof entry.id === \"string\" && entry.id.length <= 200 && MODEL_ID.test(entry.id)) {\n entries.set(entry.id, entry);\n }\n }\n const result: ModelCatalog = { models: [], chat: [], image: [], video: [], music: [], unavailable: [] };\n const models: CatalogModel[] = [];\n const unavailable: string[] = [];\n for (const [id, entry] of entries) {\n if (entry.available === false) unavailable.push(id);\n if ((entry.available !== undefined && entry.available !== true) ||\n (entry.hidden !== undefined && entry.hidden !== false) ||\n !Array.isArray(entry.categories) || !record(entry.pricing)) continue;\n const categories = [...new Set(entry.categories.filter((c): c is string => typeof c === \"string\"))];\n const rawPricing = entry.pricing;\n const pricing: CatalogPricing = {};\n for (const key of PRICE_KEYS) if (price(rawPricing[key])) pricing[key] = rawPricing[key];\n const kinds = MODEL_KINDS.filter(kind => categories.includes(kind) && (kind === \"chat\"\n ? price(rawPricing.input) && price(rawPricing.output)\n : price(rawPricing[UNIT_PRICE[kind]])));\n if (!kinds.length) continue;\n const model: CatalogModel = {\n id, name: typeof entry.name === \"string\" && entry.name.trim() ? entry.name : id,\n categories, kinds, pricing,\n free: kinds.includes(\"chat\") && entry.billing_mode === \"free\" && pricing.input === 0 && pricing.output === 0,\n ...(typeof entry.billing_mode === \"string\" ? { billingMode: entry.billing_mode } : {}),\n ...(capacity(entry.context_window) !== undefined ? { contextWindow: capacity(entry.context_window) } : {}),\n ...(capacity(entry.max_output) !== undefined ? { maxOutputTokens: capacity(entry.max_output) } : {}),\n };\n models.push(model);\n }\n result.models = models;\n result.unavailable = unavailable;\n for (const kind of MODEL_KINDS) result[kind] = models.filter(model => model.kinds.includes(kind));\n return result;\n}\n\nexport interface CatalogRoutingOptions {\n /** Host evidence, merged over (and overriding per ID) the bundled verified table. */\n verifiedCapabilities?: Readonly>;\n}\n\nexport interface RoutingCatalog {\n modelPricing: Map;\n modelCapabilities: Record;\n unavailableModels: string[];\n}\n\n/**\n * Adapt only the chat catalog for route(). Media never enters LLM candidate\n * chains. Tool support comes from verified evidence, never a name or category.\n * Unknown capacities are zero, rather than invented defaults.\n *\n * Only rows the gateway explicitly marks `available: false` become\n * unavailableModels. Configured IDs that are merely absent from the listing\n * stay routable: the gateway serves hidden IDs, and only the configured chain\n * knows about them.\n */\nexport function toRoutingCatalog(catalog: ModelCatalog, options: CatalogRoutingOptions = {}): RoutingCatalog {\n const verified = { ...DEFAULT_MODEL_CAPABILITIES, ...options.verifiedCapabilities };\n const modelPricing = new Map();\n const modelCapabilities: Record = {};\n for (const model of catalog.chat) {\n modelPricing.set(model.id, { inputPrice: model.pricing.input!, outputPrice: model.pricing.output! });\n const evidence = verified[model.id];\n modelCapabilities[model.id] = {\n contextWindow: model.contextWindow ?? evidence?.contextWindow ?? 0,\n maxOutputTokens: model.maxOutputTokens ?? evidence?.maxOutputTokens ?? 0,\n supportsTools: evidence?.supportsTools === true,\n // Verified evidence wins over the category tag in both directions: the\n // catalog omits \"vision\" for some models that accept images and tags\n // others whose image input does not hold up (see capability-overrides).\n supportsVision: evidence?.supportsVision ?? model.categories.includes(\"vision\"),\n };\n }\n return { modelPricing, modelCapabilities, unavailableModels: [...catalog.unavailable] };\n}\n","/**\n * Smart Router Entry Point\n *\n * Classifies requests and routes to the cheapest capable model.\n * Delegates to pluggable RouterStrategy (default: RulesStrategy, <1ms).\n */\n\nimport type { RoutingDecision, RouterOptions } from \"./types.js\";\nimport { getStrategy, registerStrategy } from \"./strategy.js\";\nimport { PortfolioStrategy } from \"./portfolio.js\";\n\n// Register here instead of strategy.ts so PortfolioStrategy can reuse the\n// stable RulesStrategy without introducing a module cycle.\nregisterStrategy(new PortfolioStrategy());\n\n/**\n * Route a request to the cheapest capable model.\n * Delegates to the configured strategy (PortfolioStrategy by default).\n */\nexport function route(\n prompt: string,\n systemPrompt: string | undefined,\n maxOutputTokens: number,\n options: RouterOptions,\n): RoutingDecision {\n const strategy = getStrategy(options.config.strategy ?? \"portfolio\");\n return strategy.route(prompt, systemPrompt, maxOutputTokens, options);\n}\n\nexport { getStrategy, registerStrategy, applyUnavailableModels } from \"./strategy.js\";\nexport { RulesStrategy } from \"./strategy.js\";\nexport { PortfolioStrategy } from \"./portfolio.js\";\nexport { classifyByRules } from \"./rules.js\";\nexport { inferToolRequirement } from \"./tool-intent.js\";\nexport { estimateTokens } from \"./tokens.js\";\nexport { MODEL_KINDS, parseModelCatalog, toRoutingCatalog } from \"./catalog.js\";\nexport type {\n ModelKind, CatalogPricing, CatalogModel, ModelCatalog, CatalogRoutingOptions, RoutingCatalog,\n} from \"./catalog.js\";\nexport {\n getFallbackChain,\n getFallbackChainFiltered,\n filterByToolCalling,\n filterByVision,\n filterByExcludeList,\n filterCandidatesByCapacity,\n calculateModelCost,\n} from \"./selector.js\";\nexport { DEFAULT_ROUTING_CONFIG } from \"./config.js\";\nexport { DEFAULT_MODEL_CAPABILITIES } from \"./model-capabilities.js\";\nexport { LIVE_MODEL_PROFILES, HISTORICAL_MODEL_PROFILES } from \"./model-profiles.js\";\nexport type {\n RoutingDecision,\n Tier,\n TaskType,\n RoutingConfig,\n RouterOptions,\n RouterStrategy,\n} from \"./types.js\";\nexport type { ModelPricing } from \"./selector.js\";\nexport type { ModelCapabilities } from \"./model-capabilities.js\";\nexport type { ModelPerformanceProfile } from \"./model-profiles.js\";\n"],"mappings":";AAiCA,IAAM,qBACJ;AACF,IAAM,YAAY;AAClB,IAAM,eAAe;AAIrB,IAAM,sBAAsB;AAC5B,IAAM,kBAAkB,QAAQ,mBAAmB;AACnD,IAAM,iBAAiB,OAAO,mBAAmB;AACjD,IAAM,2BAA2B;AACjC,IAAM,iBAAiB;AACvB,IAAM,kBAAkB;AACxB,IAAM,eACJ;AACF,IAAM,qBAAqB;AAC3B,IAAM,6BAA6B;AAQnC,IAAM,eAAe,oBAAI,IAA4B;AAErD,SAAS,aAAa,OAAuB;AAC3C,SAAO,MAAM,QAAQ,uBAAuB,MAAM;AACpD;AAEA,SAAS,eAAe,SAAiC;AACvD,QAAM,SAAS,aAAa,IAAI,OAAO;AACvC,MAAI,OAAQ,QAAO;AAEnB,QAAM,KAAK,QAAQ,YAAY;AAC/B,MAAI;AACJ,MAAI,mBAAmB,KAAK,EAAE,KAAK,GAAG,WAAW,GAAG;AAClD,cAAU,EAAE,QAAQ,IAAI,SAAS,KAAK;AAAA,EACxC,OAAO;AACL,UAAM,OAAO,UAAU,KAAK,GAAG,CAAC,CAAC,IAAI,kBAAkB;AACvD,UAAM,UAAU,aAAa,EAAE;AAC/B,QAAI,OAAO;AACX,QAAI,QAAQ;AACZ,QAAI,SAAS;AACb,UAAM,WAAW,GAAG,MAAM,GAAG,YAAY,GAAG,IAAI,CAAC;AACjD,QACE,UAAU,KAAK,GAAG,GAAG,SAAS,CAAC,CAAC,KAChC,aAAa,KAAK,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,EAAE;AACxF;;;AC9IA,iBAAiB,IAAI,kBAAkB,CAAC;AAMjC,SAAS,MACd,QACA,cACA,iBACA,SACiB;AACjB,QAAM,WAAW,YAAY,QAAQ,OAAO,YAAY,WAAW;AACnE,SAAO,SAAS,MAAM,QAAQ,cAAc,iBAAiB,OAAO;AACtE;","names":["confidence","decision","price","model"]} \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 14b2e5c..ea45005 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,6 +9,7 @@ "version": "0.3.0", "license": "MIT", "devDependencies": { + "@types/node": "^20.19.43", "tsup": "^8.0.0", "typescript": "^5.7.0", "vitest": "^4.1.3" @@ -506,9 +507,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -621,9 +619,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -641,9 +636,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -661,9 +653,6 @@ "ppc64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -681,9 +670,6 @@ "s390x" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -701,9 +687,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -721,9 +704,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -883,9 +863,6 @@ "arm" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -900,9 +877,6 @@ "arm" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -917,9 +891,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -934,9 +905,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -951,9 +919,6 @@ "loong64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -968,9 +933,6 @@ "loong64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -985,9 +947,6 @@ "ppc64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1002,9 +961,6 @@ "ppc64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1019,9 +975,6 @@ "riscv64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1036,9 +989,6 @@ "riscv64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1053,9 +1003,6 @@ "s390x" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1070,9 +1017,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1087,9 +1031,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1212,6 +1153,16 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/node": { + "version": "20.19.43", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.43.tgz", + "integrity": "sha512-6oYBAi5ikg4Pl+kGsoYtawUMBT2zZMCvPNF7pVLnHZfd1zf38DRiWn/gT01RYCdUqkv7Fhr+C9ot4/tb+2sVvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, "node_modules/@vitest/expect": { "version": "4.1.10", "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.10.tgz", @@ -1736,9 +1687,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -1760,9 +1708,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -1784,9 +1729,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -1808,9 +1750,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -2424,6 +2363,13 @@ "dev": true, "license": "MIT" }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + }, "node_modules/vite": { "version": "8.2.1", "resolved": "https://registry.npmjs.org/vite/-/vite-8.2.1.tgz", diff --git a/package.json b/package.json index 09592cf..bef6b14 100644 --- a/package.json +++ b/package.json @@ -49,6 +49,7 @@ "node": ">=20.19.0" }, "devDependencies": { + "@types/node": "^20.19.43", "tsup": "^8.0.0", "typescript": "^5.7.0", "vitest": "^4.1.3" diff --git a/scripts/capability-overrides.json b/scripts/capability-overrides.json index 2940f32..582f3a4 100644 --- a/scripts/capability-overrides.json +++ b/scripts/capability-overrides.json @@ -14,5 +14,17 @@ "nvidia/nemotron-3-nano-omni-30b-a3b-reasoning": { "supportsVision": false, "reason": "The catalog tags this model \"vision\", but a correctly sized probe does not hold up (ClawRouter, 2026-08-31): a 64x64 solid-red PNG was named correctly 1 of 4 times on Base, and on Solana the image was silently dropped and a text model answered \"white\". An HTTP 200 with a confident wrong answer gives the caller nothing to branch on, so image turns must not be routed here. It is ecoTiers.SIMPLE.fallback[0] since nemotron-3-nano-30b was delisted (2026-09-08); remove once a probe of this size comes back right on both chains." + }, + "deepseek/deepseek-chat": { + "supportsVision": false, + "reason": "The 2026-11-08 catalog began tagging deepseek/deepseek-chat \"vision\" (it was text-only through 2026-10-20), and DeepSeek still ships image input as a separate experimental id (deepseek/deepseek-v4-flash-vision-exp). No image probe has confirmed the tag. Routing an image turn to a model that silently drops the image returns a confident 200 the caller cannot branch on, so this fails closed until a correctly sized image probe passes on both chains; then remove this entry." + }, + "deepseek/deepseek-reasoner": { + "supportsVision": false, + "reason": "The 2026-11-08 catalog began tagging deepseek/deepseek-reasoner \"vision\" (it was text-only through 2026-10-20), and DeepSeek still ships image input as a separate experimental id (deepseek/deepseek-v4-flash-vision-exp). No image probe has confirmed the tag. Routing an image turn to a model that silently drops the image returns a confident 200 the caller cannot branch on, so this fails closed until a correctly sized image probe passes on both chains; then remove this entry." + }, + "deepseek/deepseek-v4.1-flash": { + "supportsVision": false, + "reason": "The 2026-11-08 catalog began tagging deepseek/deepseek-v4.1-flash \"vision\" (it was text-only through 2026-10-20), and DeepSeek still ships image input as a separate experimental id (deepseek/deepseek-v4-flash-vision-exp). No image probe has confirmed the tag. Routing an image turn to a model that silently drops the image returns a confident 200 the caller cannot branch on, so this fails closed until a correctly sized image probe passes on both chains; then remove this entry." } } diff --git a/scripts/probe-model-profiles.mjs b/scripts/probe-model-profiles.mjs index 7049343..e97201c 100644 --- a/scripts/probe-model-profiles.mjs +++ b/scripts/probe-model-profiles.mjs @@ -243,7 +243,7 @@ const toolsOut = Object.fromEntries( const partial = ONLY.length > 0 || SKIP.size > 0; const readJson = (path) => (existsSync(path) ? JSON.parse(readFileSync(path, "utf8")) : {}); const sortKeys = (obj) => Object.fromEntries(Object.entries(obj).sort(([a], [b]) => a.localeCompare(b))); -const profilesPath = resolve(ROOT, "model-profiles.generated.json"); +const profilesPath = resolve(ROOT, "src/model-profiles.generated.json"); const toolsPath = resolve(ROOT, "scripts/probe-tools.json"); const mergedProfiles = partial ? sortKeys({ ...readJson(profilesPath), ...profiles }) : profiles; const mergedTools = partial ? sortKeys({ ...readJson(toolsPath), ...toolsOut }) : toolsOut; diff --git a/scripts/sync-model-capabilities.mjs b/scripts/sync-model-capabilities.mjs index 224efdc..64489d1 100644 --- a/scripts/sync-model-capabilities.mjs +++ b/scripts/sync-model-capabilities.mjs @@ -21,9 +21,13 @@ * so the exception stays visible in review. * * Only text models are emitted (image/video/music/speech rows carry no - * context window). Ids the catalog withholds — `hidden: true` on the gateway — - * are deliberately absent: the router should only ever name a model a user - * can see on blockrun.ai/models. + * context window). An id that is merely absent from the listing is NOT + * treated as dead: the gateway keeps serving aliased and hidden ids, so a + * model that a routing chain still names (src/config.ts, src/portfolio.ts) + * keeps its previous entry, annotated, until a direct call proves it gone. + * Dropping it would leave the eligibility stage with no context window or + * tool flag for a model the router keeps selecting. Only an explicit + * `available: false` row removes a routed id. * * Usage: * node scripts/sync-model-capabilities.mjs [--catalog path/to/models.json] @@ -35,6 +39,8 @@ import { fileURLToPath } from "node:url"; import { dirname, resolve } from "node:path"; const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const SRC = resolve(ROOT, "src"); +const SNAPSHOT_PATH = resolve(SRC, "model-capabilities.ts"); const CATALOG_URL = "https://blockrun.ai/api/v1/models"; const args = process.argv.slice(2); @@ -58,10 +64,58 @@ for (const [id, o] of Object.entries(overrides)) { } } +if (!catalog || !Array.isArray(catalog.data)) { + throw new Error("Catalog response has no data array — refusing to overwrite the snapshot"); +} + const textModels = catalog.data .filter((m) => typeof m.context_window === "number" && typeof m.max_output === "number") .filter((m) => m.billing_mode === "paid" || m.billing_mode === "free") - .sort((a, b) => a.id.localeCompare(b.id)); + .map((m) => ({ + id: m.id, + contextWindow: m.context_window, + maxOutputTokens: m.max_output, + catalogVision: Array.isArray(m.categories) && m.categories.includes("vision"), + })); + +// Ids any routing chain or evidence list names. Read from source text so the +// script needs no build step. +const ID_LITERAL = /"([a-z0-9][a-z0-9._-]*\/[a-zA-Z0-9][a-zA-Z0-9._:+-]*)"/g; +const routedIds = new Set( + ["config.ts", "portfolio.ts"].flatMap((file) => + [...readFileSync(resolve(SRC, file), "utf8").matchAll(ID_LITERAL)].map((match) => match[1]), + ), +); + +// The previous snapshot, so a routed id absent from this listing keeps the +// capability evidence it already had. +const previous = new Map(); +if (existsSync(SNAPSHOT_PATH)) { + const ENTRY = + /"([^"]+)": \{[^\n]*\n\s*contextWindow: ([\d_]+),\n\s*maxOutputTokens: ([\d_]+),\n\s*supportsTools: (true|false),\n\s*supportsVision: (true|false),/g; + for (const m of readFileSync(SNAPSHOT_PATH, "utf8").matchAll(ENTRY)) { + previous.set(m[1], { + contextWindow: Number(m[2].replace(/_/g, "")), + maxOutputTokens: Number(m[3].replace(/_/g, "")), + supportsTools: m[4] === "true", + supportsVision: m[5] === "true", + }); + } +} + +const listed = new Set(catalog.data.map((m) => m.id)); +const explicitlyUnavailable = new Set( + catalog.data.filter((m) => m.available === false).map((m) => m.id), +); +const retained = []; +for (const id of routedIds) { + if (listed.has(id) || explicitlyUnavailable.has(id)) continue; + const prior = previous.get(id); + if (!prior) continue; + retained.push(id); + textModels.push({ id, ...prior, retained: true }); +} +textModels.sort((a, b) => a.id.localeCompare(b.id)); const fmt = (n) => n.toLocaleString("en-US").replace(/,/g, "_"); const today = new Date().toISOString().slice(0, 10); @@ -69,17 +123,22 @@ const today = new Date().toISOString().slice(0, 10); const entries = textModels.map((m) => { const probe = toolProbe[m.id]; const override = overrides[m.id] ?? {}; - const supportsTools = override.supportsTools ?? probe?.supportsTools === true; - const supportsVision = - override.supportsVision ?? (Array.isArray(m.categories) && m.categories.includes("vision")); + const supportsTools = m.retained + ? (override.supportsTools ?? m.supportsTools) + : (override.supportsTools ?? probe?.supportsTools === true); + const supportsVision = m.retained + ? (override.supportsVision ?? m.supportsVision) + : (override.supportsVision ?? m.catalogVision); const notes = []; - if (probe === undefined) notes.push("supportsTools: not probed — fails closed"); + if (m.retained) { + notes.push(`absent from the ${today} listing but still routed — previous entry retained; probe before removing`); + } else if (probe === undefined) notes.push("supportsTools: not probed — fails closed"); else if (probe.unavailable) notes.push("supportsTools: gateway unavailable at probe time — fails closed"); if (override.reason) notes.push(`override: ${override.reason}`); const note = notes.length ? ` // ${notes.join("; ")}` : ""; return ` "${m.id}": {${note} - contextWindow: ${fmt(m.context_window)}, - maxOutputTokens: ${fmt(m.max_output)}, + contextWindow: ${fmt(m.contextWindow)}, + maxOutputTokens: ${fmt(m.maxOutputTokens)}, supportsTools: ${supportsTools}, supportsVision: ${supportsVision}, },`; @@ -110,10 +169,13 @@ ${entries.join("\n")} }); `; -writeFileSync(resolve(ROOT, "model-capabilities.ts"), out); +writeFileSync(SNAPSHOT_PATH, out); const probed = textModels.filter((m) => toolProbe[m.id] !== undefined).length; console.log( `Wrote ${textModels.length} models to model-capabilities.ts (${probed} with tool-probe evidence, ${ textModels.filter((m) => toolProbe[m.id]?.supportsTools).length } tool-capable).`, ); +if (retained.length > 0) { + console.log(`Retained ${retained.length} routed id(s) absent from the listing: ${retained.join(", ")}`); +} diff --git a/catalog.test.ts b/src/catalog.test.ts similarity index 100% rename from catalog.test.ts rename to src/catalog.test.ts diff --git a/catalog.ts b/src/catalog.ts similarity index 95% rename from catalog.ts rename to src/catalog.ts index d828649..2fa3204 100644 --- a/catalog.ts +++ b/src/catalog.ts @@ -146,7 +146,10 @@ export function toRoutingCatalog(catalog: ModelCatalog, options: CatalogRoutingO contextWindow: model.contextWindow ?? evidence?.contextWindow ?? 0, maxOutputTokens: model.maxOutputTokens ?? evidence?.maxOutputTokens ?? 0, supportsTools: evidence?.supportsTools === true, - supportsVision: model.categories.includes("vision"), + // Verified evidence wins over the category tag in both directions: the + // catalog omits "vision" for some models that accept images and tags + // others whose image input does not hold up (see capability-overrides). + supportsVision: evidence?.supportsVision ?? model.categories.includes("vision"), }; } return { modelPricing, modelCapabilities, unavailableModels: [...catalog.unavailable] }; diff --git a/config.ts b/src/config.ts similarity index 100% rename from config.ts rename to src/config.ts diff --git a/decisions.snapshot.json b/src/decisions.snapshot.json similarity index 97% rename from decisions.snapshot.json rename to src/decisions.snapshot.json index 8a9758e..9afeec4 100644 --- a/decisions.snapshot.json +++ b/src/decisions.snapshot.json @@ -499,31 +499,27 @@ { "prompt": 12, "profile": "auto", - "model": "google/gemini-3.5-flash", - "tier": "MEDIUM", - "confidence": 0.5, + "model": "google/gemini-2.5-flash", + "tier": "SIMPLE", + "confidence": 0.708477270409738, "method": "portfolio", - "reasoning": "score=-0.01 | short (32 tokens), multi-step, references (following) | ambiguous -> default: MEDIUM | v3 task=vision agentRisk=standard deepWebResearch=false terminalCode=false terminalSafety=false candidates=7", - "costEstimate": 0.0018304000000000003, + "reasoning": "score=-0.07 | short (32 tokens), references (following) | v3 task=vision agentRisk=standard deepWebResearch=false terminalCode=false terminalSafety=false candidates=3", + "costEstimate": 0.00019519999999999997, "baselineCost": 0.00656, - "savings": 0.7209756097560975, + "savings": 0.9702439024390245, "agenticScore": 0, "candidates": [ - "google/gemini-3.5-flash", - "google/gemini-3.6-flash", - "zai/glm-5.3-flash", - "openai/gpt-5.6-terra", - "google/gemini-3-flash-preview", "google/gemini-2.5-flash", + "google/gemini-3-flash-preview", "openai/gpt-5.6-luna" ], "candidateScores": [ { - "model": "google/gemini-3.5-flash", - "score": 0.7275477432793295, + "model": "google/gemini-2.5-flash", + "score": 0.7269260539502254, "quality": 0.68, "cost": 0.5, - "speed": 0.5421106182761342, + "speed": 0.5332293421460749, "reliability": 1 } ], @@ -535,9 +531,9 @@ "profile": "auto", "model": "xai/grok-4.5", "tier": "REASONING", - "confidence": 0.5, + "confidence": 0.7231218051243898, "method": "portfolio", - "reasoning": "score=-0.02 | short (13 tokens), multi-step | ambiguous -> default: MEDIUM | v3 task=reasoning_math agentRisk=standard deepWebResearch=false terminalCode=false terminalSafety=false candidates=10", + "reasoning": "score=-0.08 | short (13 tokens) | upgraded to MEDIUM (structured output) | v3 task=reasoning_math agentRisk=standard deepWebResearch=false terminalCode=false terminalSafety=false candidates=10", "costEstimate": 0.0005406000000000001, "baselineCost": 0.032065, "savings": 0.9831404958677685, @@ -1611,18 +1607,17 @@ "prompt": 12, "profile": "eco", "model": "zai/glm-5.3-flash", - "tier": "MEDIUM", - "confidence": 0.5, + "tier": "SIMPLE", + "confidence": 0.708477270409738, "method": "portfolio", - "reasoning": "score=-0.01 | short (32 tokens), multi-step, references (following) | ambiguous -> default: MEDIUM | eco | v3 task=vision agentRisk=standard deepWebResearch=false terminalCode=false terminalSafety=false candidates=3", + "reasoning": "score=-0.07 | short (32 tokens), references (following) | eco | v3 task=vision agentRisk=standard deepWebResearch=false terminalCode=false terminalSafety=false candidates=2", "costEstimate": 0.0022784000000000003, "baselineCost": 0.00656, "savings": 0.6526829268292683, "agenticScore": 0, "candidates": [ "zai/glm-5.3-flash", - "openai/gpt-5.6-luna", - "google/gemini-2.5-flash" + "openai/gpt-5.6-luna" ], "candidateScores": [ { @@ -1642,9 +1637,9 @@ "profile": "eco", "model": "xai/grok-4.5", "tier": "REASONING", - "confidence": 0.5, + "confidence": 0.7231218051243898, "method": "portfolio", - "reasoning": "score=-0.02 | short (13 tokens), multi-step | ambiguous -> default: MEDIUM | eco | v3 task=reasoning_math agentRisk=standard deepWebResearch=false terminalCode=false terminalSafety=false candidates=9", + "reasoning": "score=-0.08 | short (13 tokens) | upgraded to MEDIUM (structured output) | eco | v3 task=reasoning_math agentRisk=standard deepWebResearch=false terminalCode=false terminalSafety=false candidates=9", "costEstimate": 0.0005406000000000001, "baselineCost": 0.032065, "savings": 0.9831404958677685, @@ -2685,31 +2680,27 @@ { "prompt": 12, "profile": "auto", - "model": "google/gemini-3.5-flash", - "tier": "MEDIUM", - "confidence": 0.5, + "model": "google/gemini-2.5-flash", + "tier": "SIMPLE", + "confidence": 0.708477270409738, "method": "portfolio", - "reasoning": "score=-0.01 | short (32 tokens), multi-step, references (following) | ambiguous -> default: MEDIUM | v3 task=vision agentRisk=standard deepWebResearch=false terminalCode=false terminalSafety=false candidates=7", - "costEstimate": 0.0018304000000000003, + "reasoning": "score=-0.07 | short (32 tokens), references (following) | v3 task=vision agentRisk=standard deepWebResearch=false terminalCode=false terminalSafety=false candidates=3", + "costEstimate": 0.00019519999999999997, "baselineCost": 0.00656, - "savings": 0.7209756097560975, + "savings": 0.9702439024390245, "agenticScore": 0, "candidates": [ - "google/gemini-3.5-flash", - "google/gemini-3.6-flash", - "zai/glm-5.3-flash", - "openai/gpt-5.6-terra", - "google/gemini-3-flash-preview", "google/gemini-2.5-flash", + "google/gemini-3-flash-preview", "openai/gpt-5.6-luna" ], "candidateScores": [ { - "model": "google/gemini-3.5-flash", - "score": 0.7275477432793295, + "model": "google/gemini-2.5-flash", + "score": 0.7269260539502254, "quality": 0.68, "cost": 0.5, - "speed": 0.5421106182761342, + "speed": 0.5332293421460749, "reliability": 1 } ], @@ -2721,9 +2712,9 @@ "profile": "auto", "model": "xai/grok-4.5", "tier": "REASONING", - "confidence": 0.5, + "confidence": 0.7231218051243898, "method": "portfolio", - "reasoning": "score=-0.02 | short (13 tokens), multi-step | ambiguous -> default: MEDIUM | v3 task=reasoning_math agentRisk=standard deepWebResearch=false terminalCode=false terminalSafety=false candidates=10", + "reasoning": "score=-0.08 | short (13 tokens) | upgraded to MEDIUM (structured output) | v3 task=reasoning_math agentRisk=standard deepWebResearch=false terminalCode=false terminalSafety=false candidates=10", "costEstimate": 0.0005406000000000001, "baselineCost": 0.032065, "savings": 0.9831404958677685, @@ -3722,40 +3713,28 @@ { "prompt": 12, "profile": "premium", - "model": "anthropic/claude-sonnet-4.6", - "tier": "MEDIUM", - "confidence": 0.5, + "model": "google/gemini-3.5-flash", + "tier": "SIMPLE", + "confidence": 0.708477270409738, "method": "portfolio", - "reasoning": "score=-0.01 | short (32 tokens), multi-step, references (following) | ambiguous -> default: MEDIUM | premium | v3 task=vision agentRisk=standard deepWebResearch=false terminalCode=false terminalSafety=false candidates=8", - "costEstimate": 0.0017856000000000003, + "reasoning": "score=-0.07 | short (32 tokens), references (following) | premium | v3 task=vision agentRisk=standard deepWebResearch=false terminalCode=false terminalSafety=false candidates=4", + "costEstimate": 0.0018304000000000003, "baselineCost": 0.00656, "savings": 0, "agenticScore": 0, "candidates": [ - "anthropic/claude-sonnet-4.6", - "moonshot/kimi-k3", - "anthropic/claude-sonnet-5", - "google/gemini-3.6-flash", "google/gemini-3.5-flash", - "google/gemini-2.5-pro", - "xai/grok-4.5", - "openai/gpt-5.6-terra" + "google/gemini-3.6-flash", + "anthropic/claude-haiku-4.5", + "google/gemini-2.5-flash" ], "candidateScores": [ { - "model": "anthropic/claude-sonnet-4.6", - "score": 0.8885954266748617, - "quality": 0.9, - "cost": 1, - "speed": 0.4432571112476951, - "reliability": 1 - }, - { - "model": "moonshot/kimi-k3", - "score": 0.8246386868652877, - "quality": 0.9, - "cost": 0, - "speed": 0.37731144775479714, + "model": "google/gemini-3.5-flash", + "score": 0.7469266370965681, + "quality": 0.68, + "cost": 0.5, + "speed": 0.5421106182761342, "reliability": 1 } ], @@ -3767,9 +3746,9 @@ "profile": "premium", "model": "google/gemini-3.5-flash", "tier": "REASONING", - "confidence": 0.5, + "confidence": 0.7231218051243898, "method": "portfolio", - "reasoning": "score=-0.02 | short (13 tokens), multi-step | ambiguous -> default: MEDIUM | premium | v3 task=reasoning_math agentRisk=standard deepWebResearch=false terminalCode=false terminalSafety=false candidates=12", + "reasoning": "score=-0.08 | short (13 tokens) | upgraded to MEDIUM (structured output) | premium | v3 task=reasoning_math agentRisk=standard deepWebResearch=false terminalCode=false terminalSafety=false candidates=12", "costEstimate": 0.008622800000000002, "baselineCost": 0.032065, "savings": 0, diff --git a/decisions.snapshot.test.ts b/src/decisions.snapshot.test.ts similarity index 100% rename from decisions.snapshot.test.ts rename to src/decisions.snapshot.test.ts diff --git a/src/hardening.test.ts b/src/hardening.test.ts new file mode 100644 index 0000000..7140f1c --- /dev/null +++ b/src/hardening.test.ts @@ -0,0 +1,310 @@ +/** + * Regression tests for the 2026-11 audit: inputs that produced a wrong + * classification, a NaN ranking, an unbounded scan or a fabricated figure. + * Each case names the input that used to fail. + */ +import { describe, expect, it } from "vitest"; + +import { route } from "./index.js"; +import { DEFAULT_ROUTING_CONFIG } from "./config.js"; +import { RulesStrategy } from "./strategy.js"; +import { classifyByRules } from "./rules.js"; +import { calculateModelCost, selectModel, type ModelPricing } from "./selector.js"; +import { sampleForScan, scanLimit } from "./tokens.js"; +import { parseModelCatalog, toRoutingCatalog } from "./catalog.js"; +import type { RouterOptions, RoutingConfig, Tier, TierConfig } from "./types.js"; + +const pricing = new Map([ + ["anthropic/claude-sonnet-5", { inputPrice: 3, outputPrice: 15 }], + ["anthropic/claude-opus-4.8", { inputPrice: 5, outputPrice: 25 }], + ["openai/gpt-5.3-codex", { inputPrice: 1.75, outputPrice: 14 }], + ["openai/gpt-5-mini", { inputPrice: 0.25, outputPrice: 2 }], + ["google/gemini-3.5-flash", { inputPrice: 1.5, outputPrice: 9 }], + ["google/gemini-2.5-flash", { inputPrice: 0.3, outputPrice: 2.5 }], + ["deepseek/deepseek-v4-pro", { inputPrice: 0.435, outputPrice: 0.87 }], + ["moonshot/kimi-k3", { inputPrice: 3, outputPrice: 15 }], +]); + +const options = (extra: Partial = {}): RouterOptions => ({ + config: DEFAULT_ROUTING_CONFIG, + modelPricing: pricing, + ...extra, +}); + +describe("Chinese task keywords", () => { + // `\b` without the `u` flag only sees ASCII word characters, so these + // alternatives sat inside a boundary that can never fire between two Han + // characters and every prompt below classified as chat. + it.each([ + ["请修复这个报错", "debug"], + ["请重构这个模块", "code_edit"], + ["提取所有字段", "extraction"], + ["证明这个定理", "reasoning"], + ])("classifies %s as %s", (prompt, taskType) => { + expect(route(prompt, undefined, 512, options()).taskType).toBe(taskType); + }); +}); + +describe("code-agent detection", () => { + const web = { hasTools: true, requiresTools: true, toolCount: 1, toolNames: ["web_search"] }; + + it("does not treat a bare language name in a web lookup as code work", () => { + for (const prompt of [ + "look up current java coffee bean prices online", + "search the web for python snake habitat facts", + ]) { + const decision = route(prompt, undefined, 512, options(web)); + expect(decision.taskType).toBe("tool_agent"); + expect(decision.model).not.toBe("openai/gpt-5.3-codex"); + } + }); + + it("still routes real code work with tools to the code-agent pool", () => { + for (const prompt of [ + "Fix the TypeScript payment retry bug, run tests, and update the patch.", + "Write a python script that parses the CSV and run it", + "```ts\nconst x = 1\n``` refactor this", + ]) { + const decision = route(prompt, undefined, 512, options({ hasTools: true, requiresTools: true })); + expect(decision.taskType).toBe("code_agent"); + } + }); +}); + +describe("parallel tool-call detection", () => { + it("does not read 'add' out of 'address' when matching tool operation verbs", () => { + const decision = route( + "Please update my address to 12 Main St and send me a confirmation", + undefined, + 512, + options({ + hasTools: true, + requiresTools: true, + toolCount: 2, + toolNames: ["add_item", "send_email"], + }), + ); + expect(decision.taskType).toBe("tool_agent"); + }); + + it("still detects two distinct operation verbs", () => { + const decision = route( + "Add milk to my list and delete the eggs entry", + undefined, + 512, + options({ + hasTools: true, + requiresTools: true, + toolCount: 2, + toolNames: ["add_task", "delete_task"], + }), + ); + expect(decision.taskType).toBe("tool_agent_parallel"); + }); +}); + +describe("airline reservation ids", () => { + it("does not count shouted six-letter words as two reservation ids", () => { + const airline = { + hasTools: true, + requiresTools: true, + toolCount: 3, + toolNames: ["get_reservation_details", "cancel_reservation", "search_flights"], + }; + const shouted = route("CANCEL MY FLIGHT please", undefined, 512, options(airline)); + expect(shouted.reasoning).toContain("agentRisk=standard"); + const twoIds = route( + "Cancel reservations ZFA04Y and 4WQ150", + undefined, + 512, + options(airline), + ); + expect(twoIds.reasoning).toContain("agentRisk=high"); + }); +}); + +describe("portfolio ranking robustness", () => { + it("does not let an unpriced candidate win on cost", () => { + const withoutDeepseek = new Map(pricing); + withoutDeepseek.delete("deepseek/deepseek-v4-pro"); + const decision = route( + "Return the pricier of my two orders and exchange the other one for a larger size", + undefined, + 1024, + options({ + modelPricing: withoutDeepseek, + hasTools: true, + requiresTools: true, + toolCount: 4, + toolNames: ["get_order_details", "return_delivered_order_items", "exchange_delivered_order_items", "get_product_details"], + }), + ); + const unpriced = decision.candidateScores?.find((c) => c.model === "deepseek/deepseek-v4-pro"); + expect(unpriced?.cost).toBe(0); + }); + + it("ignores a malformed performance profile instead of scoring NaN", () => { + const decision = route( + "Summarize the plot of Hamlet in two sentences.", + undefined, + 512, + options({ + modelPerformance: { + "google/gemini-2.5-flash": { + measuredAt: "2026-11-01T00:00:00Z", + latencyMs: 900, + outputTokensPerSecond: Number.NaN, + samples: Number.NaN, + }, + }, + }), + ); + for (const candidate of decision.candidateScores ?? []) { + expect(Number.isFinite(candidate.score)).toBe(true); + } + }); +}); + +describe("cost fields", () => { + const tiers = { + SIMPLE: { primary: "acme/nan", fallback: [] }, + MEDIUM: { primary: "acme/nan", fallback: [] }, + COMPLEX: { primary: "acme/nan", fallback: [] }, + REASONING: { primary: "acme/nan", fallback: [] }, + } satisfies Record; + const badPricing = new Map([ + ["acme/nan", { inputPrice: Number.NaN, outputPrice: 1 }], + ]); + + it("treats a non-finite price as unknown rather than reporting NaN", () => { + const decision = selectModel("SIMPLE", 1, "rules", "", tiers, badPricing, 1000, 1000); + expect(Number.isFinite(decision.costEstimate)).toBe(true); + expect(decision.savings).toBe(0); + const cost = calculateModelCost("acme/nan", badPricing, 1000, 1000); + expect(Number.isFinite(cost.costEstimate)).toBe(true); + expect(cost.savings).toBe(0); + }); + + it("reports no savings for an unpriced model in calculateModelCost", () => { + expect(calculateModelCost("acme/unknown", new Map(), 1000, 1000).savings).toBe(0); + }); +}); + +describe("promotions", () => { + const promoConfig = (startDate: string, endDate: string): RoutingConfig => ({ + ...DEFAULT_ROUTING_CONFIG, + strategy: "rules", + promotions: [ + { + name: "typo", + startDate, + endDate, + tierOverrides: { SIMPLE: { primary: "acme/promo" } }, + }, + ], + }); + const now = new Date("2026-11-08T00:00:00Z"); + + it("ignores a promotion whose dates do not parse instead of applying it forever", () => { + for (const [start, end] of [ + ["2026-13-01", "2026-12-01"], + ["2026-11-01", "soon"], + ]) { + const decision = new RulesStrategy().route("hi", undefined, 64, { + config: promoConfig(start, end), + modelPricing: pricing, + now, + }); + expect(decision.model).not.toBe("acme/promo"); + } + }); + + it("still applies a promotion inside a valid window", () => { + const decision = new RulesStrategy().route("hi", undefined, 64, { + config: promoConfig("2026-11-01", "2026-11-15"), + modelPricing: pricing, + now, + }); + expect(decision.tierConfigs?.[decision.tier].primary).toBe("acme/promo"); + }); +}); + +describe("scan bounds", () => { + it("bounds the sample even at the smallest limit", () => { + const long = "x".repeat(100_000); + expect(sampleForScan(long, 1).length).toBeLessThanOrEqual(2); + expect(sampleForScan(long, scanLimit(0)).length).toBeLessThanOrEqual(2); + }); + + it("treats a non-numeric truncation setting as the default bound", () => { + expect(scanLimit(Number.NaN)).toBe(8_000); + expect(sampleForScan("x".repeat(100_000), scanLimit(Number.NaN)).length).toBeLessThanOrEqual(8_001); + }); +}); + +describe("rules signals", () => { + const scoring = DEFAULT_ROUTING_CONFIG.scoring; + const signalsOf = (prompt: string) => + classifyByRules(prompt, undefined, 20, scoring).signals.join(" | "); + + it("does not call a sentence that ends in a number multi-step", () => { + expect(signalsOf("I was born in 1990. How old am I?")).not.toContain("multi-step"); + }); + + it("still sees a numbered list as multi-step", () => { + expect(signalsOf("Do this:\n1. install it\n2. configure it")).toContain("multi-step"); + }); + + it("counts full-width question marks", () => { + expect(signalsOf("这是什么?为什么?怎么做?什么时候?")).toContain("4 questions"); + }); +}); + +describe("routing catalog adapter", () => { + it("keeps bundled vision evidence when the catalog omits the vision category", () => { + const catalog = parseModelCatalog({ + data: [ + { + id: "anthropic/claude-haiku-4.5", + categories: ["chat"], + pricing: { input: 1, output: 5 }, + context_window: 200_000, + max_output: 64_000, + }, + ], + }); + expect(toRoutingCatalog(catalog).modelCapabilities["anthropic/claude-haiku-4.5"].supportsVision).toBe(true); + }); + + it("lets explicit host evidence turn vision off", () => { + const catalog = parseModelCatalog({ + data: [ + { + id: "acme/seer", + categories: ["chat", "vision"], + pricing: { input: 1, output: 5 }, + }, + ], + }); + const routing = toRoutingCatalog(catalog, { + verifiedCapabilities: { + "acme/seer": { contextWindow: 1, maxOutputTokens: 1, supportsTools: false, supportsVision: false }, + }, + }); + expect(routing.modelCapabilities["acme/seer"].supportsVision).toBe(false); + }); +}); + +describe("language band", () => { + it("does not give Japanese extraction the Mandarin band", () => { + const decision = route( + "次の文章から氏名と住所を抽出して、JSONで出力してください。山田太郎、東京都。", + undefined, + 512, + options({ requiresStructuredOutput: true }), + ); + expect(decision.taskType).toBe("extraction"); + const kimi = decision.candidateScores?.find((c) => c.model === "moonshot/kimi-k3"); + if (kimi) expect(kimi.quality).toBeLessThan(1); + }); +}); diff --git a/index.ts b/src/index.ts similarity index 100% rename from index.ts rename to src/index.ts diff --git a/model-capabilities.test.ts b/src/model-capabilities.test.ts similarity index 100% rename from model-capabilities.test.ts rename to src/model-capabilities.test.ts diff --git a/model-capabilities.ts b/src/model-capabilities.ts similarity index 87% rename from model-capabilities.ts rename to src/model-capabilities.ts index 91f238a..5a26e9b 100644 --- a/model-capabilities.ts +++ b/src/model-capabilities.ts @@ -6,7 +6,7 @@ * product catalog is temporarily unavailable, without importing product code. * * GENERATED by scripts/sync-model-capabilities.mjs from the public catalog - * (GET https://blockrun.ai/api/v1/models) on 2026-10-20; supportsTools comes + * (GET https://blockrun.ai/api/v1/models) on 2026-11-08; supportsTools comes * from a live function-calling probe (scripts/probe-tools.json). Regenerate * rather than editing by hand — a hand edit is overwritten on the next sync. */ @@ -97,13 +97,13 @@ export const DEFAULT_MODEL_CAPABILITIES: Readonly name.toLowerCase().split(/[^a-z0-9\u3400-\u9fff]+/)) - .filter((token) => operationTokens.has(token) && lowered.includes(token)), + .filter( + (token) => + operationTokens.has(token) && + new RegExp(`\\b${token}(?:s|es|d|ed|ing)?\\b`).test(lowered), + ), ); // A single workflow naturally mentions domain nouns like order/item plus // one action. Upgrade only when two different visible operation verbs are @@ -148,7 +137,8 @@ function likelyNeedsParallelToolCalls( /\b(?:weather|climate|clima|tiempo|temperature|snow|news|report)\b|天气|气象|温度|降雪|新闻|报告/i.test( text, ); - const multiLocationConnector = /\b(?:and also|both|y|e)\b|还有|以及|和|、/i.test(text); + const multiLocationConnector = + /\b(?:and also|both)\b|\s(?:y|e)\s|还有|以及|和|、/i.test(text); const commaSeparatedLocations = (text.match(/[,,]/g) ?? []).length >= 2; if (repeatedLookup && (multiLocationConnector || commaSeparatedLocations)) return true; @@ -195,6 +185,13 @@ function classifyTask( // artifact, not prose about errors; case-sensitive on purpose. const errorClassSignal = /\b[A-Z][A-Za-z]*(?:Error|Exception)\b/.test(scannedPrompt); const hasCode = explicitCodeSignal || codeConstructSignal || nativeCodeSignal || errorClassSignal; + // A language name alone ("java coffee prices", "python snake habitat") is + // not code work, even on a tool turn. It joins the code-agent pool only + // together with a coding action. + const codingAction = + /\b(?:write|implement|refactor|debug|fix|patch|compile|build|run|test|script|program|code|function|class|module|repo(?:sitory)?)\b|编写|实现|重构|调试|修复|编译|脚本|代码/i.test( + scannedPrompt, + ); // Stronger than hasCode: an actual code artifact or coding action, never a // bare language name ("What is Python?" is trivia, not a code task) and // never the English word "exception" on its own ("please make an @@ -266,7 +263,11 @@ function classifyTask( /\b(?:another|other|different|previous)\s+(?:order|reservation|booking|account|address)\b|另一(?:个)?(?:订单|预订|账户|地址)|其他(?:订单|预订|账户|地址)/i.test( scannedPrompt, ); - const reservationIds = scannedPrompt.match(/\b[A-Z0-9]{6}\b/g) ?? []; + // Reservation locators mix letters and digits (ZFA04Y, 4WQ150). Requiring + // both keeps shouted words ("CANCEL MY FLIGHT") and plain six-digit numbers + // from reading as two reservations. + const reservationIds = + scannedPrompt.match(/\b(?=[A-Z0-9]*\d)(?=[A-Z0-9]*[A-Z])[A-Z0-9]{6}\b/g) ?? []; const crossReservationBatchSignal = agentDomain === "airline" && (/\b(?:two|three|multiple|several)(?:\s+of\s+(?:my|our|the))?\s+(?:upcoming\s+)?(?:reservations?|bookings?)\b|\b(?:a\s+)?(?:second|third)\s+(?:reservation|booking)\b/i.test( @@ -433,7 +434,12 @@ function classifyTask( numberedSteps < 3 && prompt.length <= 1_000 && simpleTerminalArtifact; - const language = /[\u3400-\u9fff]/.test(scannedPrompt) ? "zh" : "other"; + // Han characters alone also spell Japanese; kana marks the prompt as not + // Mandarin, so it does not get the Mandarin-native extraction band. + const language = + /[\u3400-\u9fff]/.test(scannedPrompt) && !/[\u3040-\u30ff]/.test(scannedPrompt) + ? "zh" + : "other"; const multipleChoiceSignals = (scannedPrompt.match(/(?:^|\n)\s*[A-D][.)]\s+/gim) ?? []).length; const numericSignals = (scannedPrompt.match(/-?\d+(?:[.,]\d+)?/g) ?? []).length; const compactMathProblem = @@ -449,7 +455,8 @@ function classifyTask( let taskType: TaskType = "chat"; if (needsVision) taskType = "vision"; else if (estimatedInputTokens > 80_000) taskType = "long_context"; - else if (needsTools && (hasCode || implicitTerminalCode)) taskType = "code_agent"; + else if (needsTools && (codeArtifact || (hasCode && codingAction) || implicitTerminalCode)) + taskType = "code_agent"; else if (needsTools && likelyParallelToolCalls && !complexMultiToolPlan) taskType = "tool_agent_parallel"; else if (needsTools) taskType = "tool_agent"; @@ -457,15 +464,15 @@ function classifyTask( else if (compactMathProblem) taskType = "reasoning_math"; else if ( errorClassSignal || - /\b(?:bug|debug|error|failure|failing|regression|crash|修复|报错|错误|调试)\b/i.test(text) + /\b(?:bug|debug|error|failure|failing|regression|crash)\b|修复|报错|错误|调试/i.test(text) ) taskType = "debug"; - else if (hasCode || /\b(?:refactor|implement|patch|edit|rewrite|重构|实现|修改)\b/i.test(text)) + else if (hasCode || /\b(?:refactor|implement|patch|edit|rewrite)\b|重构|实现|修改/i.test(text)) taskType = "code_edit"; - else if (needsStructuredOutput || /\b(?:extract|json|schema|csv|字段|提取)\b/i.test(text)) + else if (needsStructuredOutput || /\b(?:extract|json|schema|csv)\b|字段|提取/i.test(text)) taskType = "extraction"; else if ( - /\b(?:prove|derive|theorem|formal|mathematical|reasoning|证明|推导|定理|数学)\b/i.test(text) + /\b(?:prove|derive|theorem|formal|mathematical|reasoning)\b|证明|推导|定理|数学/i.test(text) ) taskType = "reasoning"; @@ -492,399 +499,349 @@ function classifyTask( }; } -function affinity( - modelId: string, - task: TaskType, - language: TaskFeatures["language"] = "other", - agentDomain: TaskFeatures["agentDomain"] = "other", - deepWebResearch = false, - agentRisk: TaskFeatures["agentRisk"] = "standard", - terminalToolSignal = false, - terminalSafetySensitive = false, -): number { - const id = modelId.toLowerCase(); - // Model family names are intentionally similar (for example - // `gemini-2.5-flash` vs `gemini-2.5-flash-lite`). A substring match lets a - // smaller sibling inherit a capability claim that was measured only for the - // flagship. Keep these assignments model-exact; a sibling can be added only - // with its own evidence. - const modelName = id.slice(id.indexOf("/") + 1); - const match = (values: string[], score: number) => - values.some((value) => modelName === value) ? score : 0; - const base = 0.68; +/** + * Task-affinity bands. Each table maps a model name (the id after the + * provider slash) to its calibrated affinity for one request shape; anything + * absent scores the neutral `NEUTRAL_AFFINITY`. Names are matched exactly: + * model family names are intentionally similar (`gemini-2.5-flash` vs + * `gemini-2.5-flash-lite`), and a substring match would let a smaller sibling + * inherit a capability claim measured only for the flagship. A sibling joins a + * band only with its own evidence. + */ +type AffinityBand = Readonly>; + +/** Affinity of a model with no task-specific evidence. */ +const NEUTRAL_AFFINITY = 0.68; + +// Strong native tool loop until the Responses function-output fix is deployed +// on both gateways; Codex stays available below auto's affinity floor. Sonnet +// has a verified native multi-turn tool loop and is the safe strong default. +const TERMINAL_COMPLEX_HIGH: AffinityBand = { + "claude-sonnet-5": 1, + "gpt-5.3-codex": 0.87, + "gpt-5-mini": 0.78, + "gemini-3.5-flash": 0.76, +}; + +// Complete-session BrowseComp calibration supersedes the earlier single-case +// Opus promotion: strict deduplicated evidence has Sonnet 5 at 2/9 versus Opus +// 5 at 0/3, while Opus also costs more and has a much longer tail. Opus stays +// an availability fallback until a larger stable-provider sample supports it. +const WEB_RESEARCH_DEEP: AffinityBand = { + "claude-sonnet-5": 1, + "gpt-5-mini": 0.88, + "gemini-3.5-flash": 0.84, + "claude-opus-5": 0.8, + "claude-opus-4.8": 0.78, +}; +const WEB_RESEARCH: AffinityBand = { + "claude-sonnet-5": 1, + "gpt-5-mini": 0.88, + "gemini-3.5-flash": 0.86, + "claude-opus-5": 0.84, + "claude-opus-4.8": 0.82, +}; + +const RETAIL_POLICY_EXCEPTION: AffinityBand = { + "gpt-4.1": 1, + "claude-sonnet-5": 0.9, + "deepseek-v4-pro": 0.82, + "gpt-5-mini": 0.8, + "gpt-4o-mini": 0.76, +}; +const RETAIL_POLICY_EXCEPTION_SIMPLE: AffinityBand = { + "gpt-5-mini": 1, + "gpt-4.1": 0.86, + "deepseek-v4-pro": 0.82, + "gpt-4o-mini": 0.8, +}; + +const AFFINITY = { + // Seven valid full agent + official Terminal-Bench trajectories (2026-07-28) + // gave GPT-5 Mini 4/7 resolved tasks versus 1/7 for the prior dynamic + // code-agent choice. Its token-normalized total cost was higher in this small + // calibration, so Codex and Sonnet keep quality priors above it; admitting + // Mini to the scoring band lets the normal quality/cost profile choose it + // without erasing stronger fallbacks. DeepSeek V4 Pro is kept below the + // primary band after two consecutive mid-trajectory provider timeouts + // contaminated its calibration runs. + codeAgent: { + "gpt-5.3-codex": 1, + "claude-sonnet-5": 0.98, + "gpt-5-mini": 0.96, + "gemini-3.5-flash": 0.92, + "kimi-k3": 0.9, + "deepseek-v4-pro": 0.88, + "glm-5.2": 0.88, + }, + // Seven official Terminal-Bench calibration trajectories favoured GPT-5 Mini + // over the prior dynamic choice. Codex/Sonnet are close fallbacks; actual + // request cost breaks the tie. + terminalTool: { + "gpt-5-mini": 1, + "gpt-5.3-codex": 0.98, + "claude-sonnet-5": 0.9, + "gemini-3.5-flash": 0.89, + }, + // Two complete agent observations on the public Terminal-Bench + // new-encrypt-command task ended in Codex repeating the same TerminalExec + // input until the loop guard fired. Codex stays an availability fallback, + // below the safety-band affinity floor, until its Responses function-output + // path is verified on both gateways. + terminalToolSafety: { + "claude-sonnet-5": 1, + "claude-opus-4.8": 0.9, + "gpt-5.3-codex": 0.84, + }, + // Full-session calibration: GPT-5 Mini completed two local/single retail + // workflows at a fraction of Sonnet's token cost. It stays ineligible for + // promotion when the prompt asks for multiple actions, cross-record + // discovery or a global optimum; those trajectories exposed unstable write + // arguments. DeepSeek V4 Pro completed all three high-risk retail calibration + // trajectories (global-choice, cross-record, multi-write); Sonnet one. + retailStandard: { + "gpt-5-mini": 1, + "claude-sonnet-5": 0.88, + "gemini-3.5-flash": 0.82, + "gpt-5.3-codex": 0.81, + "kimi-k3": 0.78, + "deepseek-v4-pro": 0.76, + }, + retailHigh: { + "deepseek-v4-pro": 1, + "claude-sonnet-5": 0.88, + "gemini-3.5-flash": 0.82, + "gpt-5.3-codex": 0.81, + "kimi-k3": 0.78, + "gpt-5-mini": 0.76, + }, + // Standard airline workflows stay on GPT-5 Mini: six full-session + // development trajectories gave it the same 5/6 success as Sonnet at roughly + // one order of magnitude lower normalized token cost. A held-out high-risk + // cabin/date negotiation then produced a persistent empty assistant turn on + // Mini even after a semantic retry, while Sonnet 5 completed the identical + // official tau2 trajectory with reward 1.0. Only global optimization / + // conditional-global work is promoted. A known batch of reservations is + // operationally high-risk but still a structured tool workflow: current Tau + // evidence has Mini and Sonnet at equal task reward there, while Sonnet costs + // roughly two orders of magnitude more on the long-tail case. + airlineComplex: { + "claude-sonnet-5": 1, + "gpt-5-mini": 0.78, + "gemini-3.5-flash": 0.76, + "deepseek-v4-pro": 0.74, + }, + airlineStandard: { + "gpt-5-mini": 1, + "claude-sonnet-5": 0.9, + "gemini-3.5-flash": 0.8, + "deepseek-v4-pro": 0.76, + }, + // Full-trajectory tau2 calibration (2026-07-28, official gpt-4.1 simulator): + // Sonnet 5 completed both an airline policy task and a retail multi-write + // task with reward 1.0. Gemini 3.5 Flash emitted function calls as plain text + // after the first structured calls and looped to the 100-step ceiling on the + // airline task. + toolAgent: { + "claude-sonnet-5": 1, + "gemini-3.5-flash": 0.88, + "gpt-5.3-codex": 0.87, + "kimi-k3": 0.85, + "gpt-5-mini": 0.84, + "deepseek-v4-pro": 0.82, + }, + // Multi-file Terminal work is not equivalent to a one-turn parallel + // function-call benchmark. Sonnet is the strongest trajectory-tested + // cost-controlled default; Opus remains a close safety fallback. + parallelTerminalSafety: { + "claude-sonnet-5": 1, + "claude-opus-4.8": 0.9, + "gpt-5.3-codex": 0.86, + }, + parallelTerminal: { + "gpt-5-mini": 1, + "gpt-5.3-codex": 0.98, + "claude-sonnet-5": 0.92, + "gemini-3.5-flash": 0.88, + }, + parallelRetail: { + "deepseek-v4-pro": 1, + "claude-sonnet-5": 0.88, + "claude-opus-4.8": 0.84, + "gpt-5-mini": 0.78, + "gemini-3.5-flash": 0.76, + }, + parallelAirlineComplex: { + "claude-sonnet-5": 1, + "gpt-5-mini": 0.78, + "claude-opus-4.8": 0.76, + "gemini-3.5-flash": 0.74, + }, + parallelAirline: { + "gpt-5-mini": 1, + "claude-sonnet-5": 0.9, + "gemini-3.5-flash": 0.8, + }, + // RouterBench calibration, 2026-07-26: Opus 4.8 produced complete multi-call + // payloads on 2/3 multilingual BFCL parallel cases. Gemini 3.5 Flash, Sonnet + // 5, DeepSeek V4 Pro and Grok 4.5 were 0/3. This narrow prior only applies + // after the conservative prompt feature in likelyNeedsParallelToolCalls. + parallel: { + "claude-opus-4.8": 1, + "claude-sonnet-5": 0.84, + "grok-4.5": 0.82, + "gemini-3.5-flash": 0.8, + "deepseek-v4-pro": 0.78, + }, + codeEdit: { + "gpt-5.3-codex": 1, + "claude-sonnet-4.6": 0.94, + "glm-5.2": 0.9, + "deepseek-v4-pro": 0.86, + }, + reasoning: { + "claude-sonnet-5": 0.98, + "claude-sonnet-4.6": 0.98, + "deepseek-v4-pro": 0.95, + "grok-4.5": 0.94, + "gemini-3.1-pro": 0.92, + "gemini-3.5-flash": 0.92, + }, + // RouterBench calibration (2026-07-28, six stratified GPQA Diamond tasks, + // identical agent adapter and 512-token budget): Gemini 3 Flash Preview + // scored 5/6, Gemini 3.5 Flash 4/6, and Gemini 3.1 Pro 3/6 while costing + // ~170x more than Flash. The measured winner is the narrow default; version + // recency alone is not a quality signal. Unused host tools must not change + // this reasoning-only model choice. + reasoningMcq: { + "gemini-3-flash-preview": 1, + "gemini-3.5-flash": 0.91, + "grok-4.5": 0.9, + "claude-sonnet-5": 0.88, + "deepseek-v4-pro": 0.84, + }, + // Same calibration, five multilingual MGSM tasks: Gemini 3.5 Flash was 5/5 + // with the lowest cost and latency; four current flagships were 4/5 and Kimi + // K2.7 was 3/5. + reasoningMath: { + "gemini-3.5-flash": 1, + "grok-4.5": 0.93, + "claude-sonnet-5": 0.9, + "deepseek-v4-pro": 0.9, + "kimi-k3": 0.9, + }, + vision: { + "gemini-3.1-pro": 0.96, + "qwen3.7-max": 0.9, + "claude-sonnet-4.6": 0.9, + "kimi-k3": 0.9, + "grok-4.3": 0.9, + }, + // Long-context eligibility is necessary but not sufficient: a provider can + // advertise a 1M window yet return an empty completion near that boundary. + // The proven long-context flagship leads, and less-established alternatives + // sit in a separate band so price alone cannot displace it. + longContext: { + "gemini-3.1-pro": 1, + "qwen3.7-max": 0.89, + "glm-5.2": 0.89, + "gemini-3.5-flash": 0.88, + "deepseek-v4-pro": 0.85, + }, + // A structured extraction must preserve both the output contract and the + // source-language fields. For Mandarin input the language-native Kimi + // candidate gets a distinct band — a candidate-pool decision, not a post-hoc + // override, so it still falls back normally when Kimi is unavailable. Kimi + // K3 costs ~5x its retired sibling K2.7, so the band must be wider than the + // auto affinityFloorGap (0.10) or price alone re-selects a non-native model + // for Mandarin input; 0.12 keeps K3 alone in the primary band for zh and + // leaves every other language untouched. + extractionZh: { + "kimi-k3": 1, + "gemini-3.5-flash": 0.88, + "gemini-2.5-flash": 0.88, + "gpt-4o-mini": 0.88, + "claude-sonnet-5": 0.88, + "claude-sonnet-4.6": 0.88, + }, + extraction: { + "kimi-k3": 0.9, + "gemini-3.5-flash": 0.9, + "gemini-2.5-flash": 0.9, + "gpt-4o-mini": 0.9, + "claude-sonnet-5": 0.9, + "claude-sonnet-4.6": 0.9, + }, + chat: { + "gemini-3.5-flash": 0.86, + "gemini-2.5-flash": 0.86, + "kimi-k3": 0.86, + }, +} as const satisfies Record; - switch (task) { +/** The affinity band that applies to a classified request. */ +function affinityBand(features: TaskFeatures): AffinityBand { + const { taskType, agentDomain, agentRisk, deepWebResearch, terminalToolSignal } = features; + const terminalSafety = features.terminalSafetySensitive; + switch (taskType) { case "code_agent": - if (terminalToolSignal && agentRisk === "complex_high") { - // Strong native tool loop until the Responses function-output fix is - // deployed on both gateways; keep Codex available below the floor. - return Math.max( - base, - match(["claude-sonnet-5"], 1), - match(["gpt-5.3-codex"], 0.87), - match(["gpt-5-mini"], 0.78), - match(["gemini-3.5-flash"], 0.76), - ); - } - // Seven valid full agent + official Terminal-Bench trajectories - // (2026-07-28) gave GPT-5 Mini 4/7 resolved tasks versus 1/7 for the - // prior dynamic code-agent choice. Its token-normalized total cost was - // higher in this small calibration, so keep Codex and Sonnet's quality - // priors above it; admitting Mini to the scoring band lets the normal - // quality/cost profile choose it without erasing stronger fallbacks. - // DeepSeek V4 Pro is kept below the primary band after two consecutive - // mid-trajectory provider timeouts contaminated its calibration runs. - return Math.max( - base, - match(["gpt-5.3-codex"], 1), - match(["claude-sonnet-5"], 0.98), - match(["gpt-5-mini"], 0.96), - match(["gemini-3.5-flash"], 0.92), - match(["kimi-k3"], 0.9), - match(["deepseek-v4-pro", "glm-5.2"], 0.88), - ); + return terminalToolSignal && agentRisk === "complex_high" + ? TERMINAL_COMPLEX_HIGH + : AFFINITY.codeAgent; case "tool_agent": - if (terminalToolSignal && agentRisk === "complex_high") { - // Keep the Responses-API Codex path outside auto's affinity floor - // until the gateway fix that preserves function_call_output is live - // on both chains. Sonnet has a verified native multi-turn tool loop - // and is the safe strong default for this band today. - return Math.max( - base, - match(["claude-sonnet-5"], 1), - match(["gpt-5.3-codex"], 0.87), - match(["gpt-5-mini"], 0.78), - match(["gemini-3.5-flash"], 0.76), - ); - } - if (terminalToolSignal && !terminalSafetySensitive) { - // Seven official Terminal-Bench calibration trajectories favoured - // GPT-5 Mini over the prior dynamic choice. Admit Codex/Sonnet as - // close fallbacks, but let actual request cost break the tie. - return Math.max( - base, - match(["gpt-5-mini"], 1), - match(["gpt-5.3-codex"], 0.98), - match(["claude-sonnet-5"], 0.9), - match(["gemini-3.5-flash"], 0.89), - ); - } - if (terminalToolSignal && terminalSafetySensitive) { - // Two complete agent observations on the public - // Terminal-Bench new-encrypt-command task ended in Codex repeating - // the same TerminalExec input until the loop guard fired. Keep Codex - // as an availability fallback, but below the safety-band affinity - // floor until its Responses function-output path is verified on both - // gateways. This does not change explicit code-agent routing. - return Math.max( - base, - match(["claude-sonnet-5"], 1), - match(["claude-opus-4.8"], 0.9), - match(["gpt-5.3-codex"], 0.84), - ); - } - if (agentDomain === "web_research") { - // Complete-session BrowseComp calibration supersedes the earlier - // single-case Opus promotion: strict deduplicated evidence has Sonnet - // 5 at 2/9 versus Opus 5 at 0/3, while Opus also costs more and has a - // much longer tail. Keep Opus as an availability fallback until a - // larger stable-provider sample supports promotion. - return deepWebResearch - ? Math.max( - base, - match(["claude-sonnet-5"], 1), - match(["gpt-5-mini"], 0.88), - match(["gemini-3.5-flash"], 0.84), - match(["claude-opus-5"], 0.8), - match(["claude-opus-4.8"], 0.78), - ) - : Math.max( - base, - match(["claude-sonnet-5"], 1), - match(["gpt-5-mini"], 0.88), - match(["gemini-3.5-flash"], 0.86), - match(["claude-opus-5"], 0.84), - match(["claude-opus-4.8"], 0.82), - ); - } - // Full-trajectory tau2 calibration (2026-07-28, official gpt-4.1 - // simulator): Sonnet 5 completed both an airline policy task and a - // retail multi-write task with reward 1.0. Gemini 3.5 Flash emitted - // function calls as plain text after the first structured calls and - // looped to the 100-step ceiling on the airline task. Keep only the - // trajectory-validated primary inside the scoring band; the remaining - // eligible models are retained below as availability fallbacks. + if (terminalToolSignal && agentRisk === "complex_high") return TERMINAL_COMPLEX_HIGH; + if (terminalToolSignal) return terminalSafety ? AFFINITY.terminalToolSafety : AFFINITY.terminalTool; + if (agentDomain === "web_research") return deepWebResearch ? WEB_RESEARCH_DEEP : WEB_RESEARCH; if (agentDomain === "retail") { - // Full-session calibration: GPT-5 Mini completed two local/single - // retail workflows at a fraction of Sonnet's token cost. It remains - // ineligible for promotion when the prompt asks for multiple actions, - // cross-record discovery, or a global optimum; those trajectories - // exposed unstable write arguments in prior calibration. DeepSeek V4 - // Pro completed all three high-risk retail calibration trajectories - // that included global-choice, cross-record, and multi-write behavior; - // Sonnet completed one of the same three. - if (agentRisk === "standard") { - return Math.max( - base, - match(["gpt-5-mini"], 1), - match(["claude-sonnet-5"], 0.88), - match(["gemini-3.5-flash"], 0.82), - match(["gpt-5.3-codex"], 0.81), - match(["kimi-k3"], 0.78), - match(["deepseek-v4-pro"], 0.76), - ); - } - if (agentRisk === "policy_exception") { - return Math.max( - base, - match(["gpt-4.1"], 1), - match(["claude-sonnet-5"], 0.9), - match(["deepseek-v4-pro"], 0.82), - match(["gpt-5-mini"], 0.8), - match(["gpt-4o-mini"], 0.76), - ); - } - if (agentRisk === "policy_exception_simple") { - return Math.max( - base, - match(["gpt-5-mini"], 1), - match(["gpt-4.1"], 0.86), - match(["deepseek-v4-pro"], 0.82), - match(["gpt-4o-mini"], 0.8), - ); - } - return Math.max( - base, - match(["deepseek-v4-pro"], 1), - match(["claude-sonnet-5"], 0.88), - match(["gemini-3.5-flash"], 0.82), - match(["gpt-5.3-codex"], 0.81), - match(["kimi-k3"], 0.78), - match(["gpt-5-mini"], 0.76), - ); + if (agentRisk === "standard") return AFFINITY.retailStandard; + if (agentRisk === "policy_exception") return RETAIL_POLICY_EXCEPTION; + if (agentRisk === "policy_exception_simple") return RETAIL_POLICY_EXCEPTION_SIMPLE; + return AFFINITY.retailHigh; } - // Standard airline workflows stay on GPT-5 Mini: six full-session - // development trajectories gave it the same 5/6 success as Sonnet at - // roughly one order of magnitude lower normalized token cost. A held-out - // high-risk cabin/date negotiation then produced a persistent empty - // assistant turn on Mini even after a semantic retry, while Sonnet 5 - // completed the identical official tau2 trajectory with reward 1.0. - // Promote only global optimization / conditional-global work. A known - // batch of reservations is operationally high-risk but still a - // structured tool workflow: current Tau evidence has Mini and Sonnet at - // equal task reward there, while Sonnet costs roughly two orders of - // magnitude more on the long-tail case. if (agentDomain === "airline") { - if (agentRisk === "complex_high") { - return Math.max( - base, - match(["claude-sonnet-5"], 1), - match(["gpt-5-mini"], 0.78), - match(["gemini-3.5-flash"], 0.76), - match(["deepseek-v4-pro"], 0.74), - ); - } - return Math.max( - base, - match(["gpt-5-mini"], 1), - match(["claude-sonnet-5"], 0.9), - match(["gemini-3.5-flash"], 0.8), - match(["deepseek-v4-pro"], 0.76), - ); + return agentRisk === "complex_high" ? AFFINITY.airlineComplex : AFFINITY.airlineStandard; } - return Math.max( - base, - match(["claude-sonnet-5"], 1), - match(["gemini-3.5-flash"], 0.88), - match(["gpt-5.3-codex"], 0.87), - match(["gpt-5-mini"], 0.84), - match(["kimi-k3"], 0.85), - match(["deepseek-v4-pro"], 0.82), - ); + return AFFINITY.toolAgent; case "tool_agent_parallel": if (terminalToolSignal) { - // Multi-file Terminal work is not equivalent to a one-turn parallel - // function-call benchmark. Sonnet is the strongest trajectory-tested - // cost-controlled default; Opus remains a close safety fallback. - return terminalSafetySensitive - ? Math.max( - base, - match(["claude-sonnet-5"], 1), - match(["claude-opus-4.8"], 0.9), - match(["gpt-5.3-codex"], 0.86), - ) - : Math.max( - base, - match(["gpt-5-mini"], 1), - match(["gpt-5.3-codex"], 0.98), - match(["claude-sonnet-5"], 0.92), - match(["gemini-3.5-flash"], 0.88), - ); - } - if (agentDomain === "web_research") { - return deepWebResearch - ? Math.max( - base, - match(["claude-sonnet-5"], 1), - match(["gpt-5-mini"], 0.88), - match(["gemini-3.5-flash"], 0.84), - match(["claude-opus-5"], 0.8), - match(["claude-opus-4.8"], 0.78), - ) - : Math.max( - base, - match(["claude-sonnet-5"], 1), - match(["gpt-5-mini"], 0.88), - match(["gemini-3.5-flash"], 0.86), - match(["claude-opus-5"], 0.84), - match(["claude-opus-4.8"], 0.82), - ); + return terminalSafety ? AFFINITY.parallelTerminalSafety : AFFINITY.parallelTerminal; } + if (agentDomain === "web_research") return deepWebResearch ? WEB_RESEARCH_DEEP : WEB_RESEARCH; if (agentDomain === "retail") { - if (agentRisk === "policy_exception") { - return Math.max( - base, - match(["gpt-4.1"], 1), - match(["claude-sonnet-5"], 0.9), - match(["deepseek-v4-pro"], 0.82), - match(["gpt-5-mini"], 0.8), - match(["gpt-4o-mini"], 0.76), - ); - } - if (agentRisk === "policy_exception_simple") { - return Math.max( - base, - match(["gpt-5-mini"], 1), - match(["gpt-4.1"], 0.86), - match(["deepseek-v4-pro"], 0.82), - match(["gpt-4o-mini"], 0.8), - ); - } - return Math.max( - base, - match(["deepseek-v4-pro"], 1), - match(["claude-sonnet-5"], 0.88), - match(["claude-opus-4.8"], 0.84), - match(["gpt-5-mini"], 0.78), - match(["gemini-3.5-flash"], 0.76), - ); + if (agentRisk === "policy_exception") return RETAIL_POLICY_EXCEPTION; + if (agentRisk === "policy_exception_simple") return RETAIL_POLICY_EXCEPTION_SIMPLE; + return AFFINITY.parallelRetail; } if (agentDomain === "airline") { - return agentRisk === "complex_high" - ? Math.max( - base, - match(["claude-sonnet-5"], 1), - match(["gpt-5-mini"], 0.78), - match(["claude-opus-4.8"], 0.76), - match(["gemini-3.5-flash"], 0.74), - ) - : Math.max( - base, - match(["gpt-5-mini"], 1), - match(["claude-sonnet-5"], 0.9), - match(["gemini-3.5-flash"], 0.8), - ); + return agentRisk === "complex_high" ? AFFINITY.parallelAirlineComplex : AFFINITY.parallelAirline; } - // RouterBench calibration, 2026-07-26: Opus 4.8 produced complete - // multi-call payloads on 2/3 multilingual BFCL parallel cases. Gemini - // 3.5 Flash, Sonnet 5, DeepSeek V4 Pro, and Grok 4.5 were 0/3. This - // narrow prior only applies after the conservative prompt feature above. - return Math.max( - base, - match(["claude-opus-4.8"], 1), - match(["claude-sonnet-5"], 0.84), - match(["grok-4.5"], 0.82), - match(["gemini-3.5-flash"], 0.8), - match(["deepseek-v4-pro"], 0.78), - ); + return AFFINITY.parallel; case "code_edit": case "debug": - return Math.max( - base, - match(["gpt-5.3-codex"], 1), - match(["claude-sonnet-4.6"], 0.94), - match(["glm-5.2"], 0.9), - match(["deepseek-v4-pro"], 0.86), - ); + return AFFINITY.codeEdit; case "reasoning": - return Math.max( - base, - match(["claude-sonnet-5", "claude-sonnet-4.6"], 0.98), - match(["deepseek-v4-pro"], 0.95), - match(["grok-4.5"], 0.94), - match(["gemini-3.1-pro", "gemini-3.5-flash"], 0.92), - ); + return AFFINITY.reasoning; case "reasoning_mcq": - // RouterBench calibration (2026-07-28, six stratified GPQA Diamond - // tasks, identical agent adapter and 512-token budget): Gemini 3 - // Flash Preview scored 5/6, Gemini 3.5 Flash 4/6, and Gemini 3.1 Pro - // 3/6 while costing ~170x more than Flash. Keep the measured winner as - // the narrow default; version recency alone is not a quality signal. - // Unused host tools must not change this reasoning-only model choice. - return Math.max( - base, - match(["gemini-3-flash-preview"], 1), - match(["gemini-3.5-flash"], 0.91), - match(["grok-4.5"], 0.9), - match(["claude-sonnet-5"], 0.88), - match(["deepseek-v4-pro"], 0.84), - ); + return AFFINITY.reasoningMcq; case "reasoning_math": - // Same calibration, five multilingual MGSM tasks: Gemini 3.5 Flash was - // 5/5 with the lowest cost and latency; four current flagships were 4/5 - // and Kimi K2.7 was 3/5. - return Math.max( - base, - match(["gemini-3.5-flash"], 1), - match(["grok-4.5"], 0.93), - match(["claude-sonnet-5", "deepseek-v4-pro", "kimi-k3"], 0.9), - ); + return AFFINITY.reasoningMath; case "vision": - return Math.max( - base, - match(["gemini-3.1-pro"], 0.96), - match(["qwen3.7-max", "claude-sonnet-4.6", "kimi-k3", "grok-4.3"], 0.9), - ); + return AFFINITY.vision; case "long_context": - // Long-context eligibility is necessary but not sufficient: a provider - // can advertise a 1M window yet return an empty completion near that - // boundary. Keep the proven long-context flagship in the lead and put - // less-established alternatives in a separate affinity band so price - // alone cannot displace it. - return Math.max( - base, - match(["gemini-3.1-pro"], 1), - match(["qwen3.7-max", "glm-5.2"], 0.89), - match(["gemini-3.5-flash"], 0.88), - match(["deepseek-v4-pro"], 0.85), - ); - case "extraction": { - // A structured extraction must preserve both the output contract and the - // source-language fields. For Mandarin input, keep the language-native - // Kimi candidate in a distinct affinity band. This is deliberately a - // candidate-pool decision (rather than a brittle post-hoc override): it - // still falls back normally if that model is unavailable or ineligible. - // Kimi K3 costs ~5x its retired sibling K2.7, so the band must be wider - // than the auto affinityFloorGap (0.10) or price alone re-selects a - // non-native model for Mandarin input; 0.12 keeps K3 alone in the - // primary band for zh and leaves every other language untouched. - const kimiExtractionAffinity = language === "zh" ? 1 : 0.9; - const otherExtractionAffinity = language === "zh" ? 0.88 : 0.9; - return Math.max( - base, - match(["gemini-3.5-flash", "gemini-2.5-flash", "gpt-4o-mini"], otherExtractionAffinity), - match(["claude-sonnet-5", "claude-sonnet-4.6"], otherExtractionAffinity), - match(["kimi-k3"], kimiExtractionAffinity), - ); - } - default: - return Math.max( - base, - match(["gemini-3.5-flash", "gemini-2.5-flash", "kimi-k3"], 0.86), - ); + return AFFINITY.longContext; + case "extraction": + return features.language === "zh" ? AFFINITY.extractionZh : AFFINITY.extraction; + case "chat": + return AFFINITY.chat; } } +/** A model's affinity within a band: its calibrated score, never below neutral. */ +function affinityIn(band: AffinityBand, modelId: string): number { + const name = modelId.toLowerCase().slice(modelId.indexOf("/") + 1); + return Math.max(NEUTRAL_AFFINITY, band[name] ?? 0); +} + function evidenceCandidates(task: TaskType): string[] { if (task === "code_agent") { return [ @@ -942,7 +899,7 @@ function evidenceCandidates(task: TaskType): string[] { } if (task === "extraction") { // Kimi K3 is no longer on the auto MEDIUM chain (K2.7 was); the - // language-native extraction band in affinity() needs it in the pool. + // language-native extraction band (AFFINITY.extractionZh) needs it in the pool. return ["moonshot/kimi-k3", "google/gemini-3.5-flash", "anthropic/claude-sonnet-5"]; } if (task === "reasoning_math") { @@ -963,7 +920,7 @@ function evidenceCandidates(task: TaskType): string[] { * Tool compliance is enough to make these models safe availability fallbacks, * but it is not evidence that they should displace a trajectory-benchmarked * primary. Keep them after the configured and benchmark-backed chains until a - * full agent evaluation earns a task-specific affinity above the neutral 0.68 + * full agent evaluation earns a task-specific affinity above NEUTRAL_AFFINITY * floor. `isEligible` still applies every host capability override, context * limit, vision constraint, and unavailable-model guard before they are used. */ @@ -1006,7 +963,7 @@ function estimatedCost( inputTokens: number, outputTokens: number, ): number { - const price = options.modelPricing.get(modelId); + const price = usablePricing(options.modelPricing.get(modelId)); if (!price) return Number.POSITIVE_INFINITY; if (price.flatPrice !== undefined) return price.flatPrice; return (inputTokens * price.inputPrice + outputTokens * price.outputPrice) / 1_000_000; @@ -1026,6 +983,21 @@ function profileScore( if (!profile) return undefined; const measuredAt = Date.parse(profile.measuredAt); if (!Number.isFinite(measuredAt)) return undefined; + // A host-injected observation with a missing or non-numeric field would + // turn the whole score into NaN, and NaN compares as "equal" in the sort, + // freezing that candidate wherever it landed. Treat it as no observation. + const finite = (value: number | undefined, optional: boolean) => + value === undefined ? optional : Number.isFinite(value) && value >= 0; + if ( + !finite(profile.latencyMs, false) || + !finite(profile.outputTokensPerSecond, false) || + !finite(profile.p95LatencyMs, true) || + !finite(profile.intelligenceIndex, true) || + !finite(profile.errorRate, true) || + !finite(profile.samples, true) + ) { + return undefined; + } const ageDays = Math.max(0, (now.getTime() - measuredAt) / 86_400_000); // A 30-day half-life makes old data a tie-breaker only. Small probe runs are // also weak evidence: three quick samples should not overturn a curated @@ -1127,19 +1099,18 @@ export class PortfolioStrategy implements RouterStrategy { ? "premium" : "auto"; const portfolio = options.config.portfolio ?? DEFAULT_PORTFOLIO_WEIGHTS; - const getAffinity = (model: string) => - affinity( - model, - features.taskType, - features.language, - features.agentDomain, - features.deepWebResearch, - features.agentRisk, - features.terminalToolSignal, - features.terminalSafetySensitive, - ); + const band = affinityBand(features); + const affinityCache = new Map(); + const getAffinity = (model: string) => { + let value = affinityCache.get(model); + if (value === undefined) { + value = affinityIn(band, model); + affinityCache.set(model, value); + } + return value; + }; const bestAffinity = Math.max(...eligibleCandidates.map(getAffinity)); - const specificAffinity = eligibleCandidates.filter((model) => getAffinity(model) > 0.68); + const specificAffinity = eligibleCandidates.filter((model) => getAffinity(model) > NEUTRAL_AFFINITY); // A tier's fallback list is primarily an availability/recovery chain, not a // set of equally validated substitutes. Re-ranking every fallback lets a // cheap generic model displace the curated primary merely because it has a @@ -1170,9 +1141,13 @@ export class PortfolioStrategy implements RouterStrategy { const profileWeights = portfolio[profileName]; const rankedEntries = candidates .map((model, index) => { - const cost = estimatedCost(model, options, features.estimatedInputTokens, maxOutputTokens); - const costScore = - Number.isFinite(cost) && maxCost > minCost + const cost = costs[index]; + // An unpriced candidate costs an unknown amount, so it scores as the + // most expensive rather than a neutral 0.5 that let it outrank + // priced models. Pricing presence still never filters a candidate. + const costScore = !Number.isFinite(cost) + ? 0 + : maxCost > minCost ? 1 - (cost - minCost) / (maxCost - minCost) : 0.5; const capabilityScore = eligible.has(model) ? 1 : 0; diff --git a/rules.test.ts b/src/rules.test.ts similarity index 100% rename from rules.test.ts rename to src/rules.test.ts diff --git a/rules.ts b/src/rules.ts similarity index 93% rename from rules.ts rename to src/rules.ts index ab413fe..608009f 100644 --- a/rules.ts +++ b/src/rules.ts @@ -162,7 +162,9 @@ function scoreKeywordMatch( } function scoreMultiStep(text: string): DimensionScore { - const patterns = [/first.*then/i, /step \d/i, /\d\.\s/]; + // A numbered list item must start a line: a bare "\d\.\s" also matched + // every sentence that ends in a number ("born in 1990. How old…"). + const patterns = [/first.*then/i, /step \d/i, /(?:^|\n)\s*\d+[.)]\s/]; const hits = patterns.filter((p) => p.test(text)); if (hits.length > 0) { return { name: "multiStepPatterns", score: 0.5, signal: "multi-step" }; @@ -171,7 +173,7 @@ function scoreMultiStep(text: string): DimensionScore { } function scoreQuestionComplexity(prompt: string): DimensionScore { - const count = (prompt.match(/\?/g) || []).length; + const count = (prompt.match(/[??]/g) || []).length; if (count > 3) { return { name: "questionComplexity", score: 0.5, signal: `${count} questions` }; } @@ -252,6 +254,15 @@ export function classifyByRules( // and make every request score identically. See GitHub issue #50. const userText = prompt.toLowerCase(); + const reasoningDimension = scoreKeywordMatch( + userText, + config.reasoningKeywords, + "reasoningMarkers", + "reasoning", + { low: 1, high: 2 }, + { none: 0, low: 0.7, high: 1.0 }, + ); + // Score the base dimensions against user text only; the agentic dimension is // appended below, so the scored total is one more than this list. const dimensions: DimensionScore[] = [ @@ -265,14 +276,7 @@ export function classifyByRules( { low: 1, high: 2 }, { none: 0, low: 0.5, high: 1.0 }, ), - scoreKeywordMatch( - userText, - config.reasoningKeywords, - "reasoningMarkers", - "reasoning", - { low: 1, high: 2 }, - { none: 0, low: 0.7, high: 1.0 }, - ), + reasoningDimension, scoreKeywordMatch( userText, config.technicalKeywords, @@ -370,12 +374,12 @@ export function classifyByRules( weightedScore += d.score * w; } - // Count reasoning markers for override — only check USER prompt, not system prompt - // This prevents system prompts with "step by step" from triggering REASONING for simple queries - const reasoningMatches = config.reasoningKeywords.filter((kw) => matchesKeyword(userText, kw)); - - // Direct reasoning override: 2+ reasoning markers = high confidence REASONING - if (reasoningMatches.length >= 2) { + // Direct reasoning override: 2+ reasoning markers in the USER prompt = high + // confidence REASONING. The system prompt is never read here, so a host + // instruction like "think step by step" cannot lift every query to REASONING. + // The reasoning dimension already counted those matches; its score is 1.0 + // exactly when two or more matched. + if (reasoningDimension.score === 1.0) { const confidence = calibrateConfidence( Math.max(weightedScore, 0.3), // ensure positive for confidence calc config.confidenceSteepness, diff --git a/selector.test.ts b/src/selector.test.ts similarity index 100% rename from selector.test.ts rename to src/selector.test.ts diff --git a/selector.ts b/src/selector.ts similarity index 65% rename from selector.ts rename to src/selector.ts index 8373d8c..e2606a0 100644 --- a/selector.ts +++ b/src/selector.ts @@ -26,6 +26,59 @@ const BASELINE_MODEL_ID = "anthropic/claude-opus-4.7"; const BASELINE_INPUT_PRICE = 5.0; const BASELINE_OUTPUT_PRICE = 25.0; +/** + * The pricing entry, or undefined when any field it carries is not a finite, + * non-negative number. A hand-built price map with a NaN would otherwise put + * NaN into costEstimate and savings; a malformed price is an unknown price. + */ +export function usablePricing(pricing: ModelPricing | undefined): ModelPricing | undefined { + if (!pricing) return undefined; + const ok = (value: number | undefined) => + value === undefined || (Number.isFinite(value) && value >= 0); + if (pricing.flatPrice !== undefined) return ok(pricing.flatPrice) ? pricing : undefined; + return ok(pricing.inputPrice) && ok(pricing.outputPrice) ? pricing : undefined; +} + +/** Raw token cost (no margin, no floor), or the flat promo price when one is set. */ +function rawCost( + pricing: ModelPricing | undefined, + estimatedInputTokens: number, + maxOutputTokens: number, +): number { + if (pricing?.flatPrice !== undefined) return pricing.flatPrice; + const inputPrice = pricing?.inputPrice ?? 0; + const outputPrice = pricing?.outputPrice ?? 0; + return (estimatedInputTokens / 1_000_000) * inputPrice + (maxOutputTokens / 1_000_000) * outputPrice; +} + +/** What the anchor Opus tier would cost for the same request (see BASELINE_MODEL_ID). */ +function baselineCostFor( + modelPricing: Map, + estimatedInputTokens: number, + maxOutputTokens: number, +): number { + const opusPricing = usablePricing(modelPricing.get(BASELINE_MODEL_ID)); + const inputPrice = opusPricing?.inputPrice ?? BASELINE_INPUT_PRICE; + const outputPrice = opusPricing?.outputPrice ?? BASELINE_OUTPUT_PRICE; + return (estimatedInputTokens / 1_000_000) * inputPrice + (maxOutputTokens / 1_000_000) * outputPrice; +} + +/** + * Fractional savings against the baseline. Premium reports none (it is about + * quality, not cost), and a model the host has no price for costs an unknown + * amount, not nothing: reporting its savings as 100% would be a fabricated + * figure. + */ +function savingsFor( + costEstimate: number, + baselineCost: number, + pricing: ModelPricing | undefined, + routingProfile: string | undefined, +): number { + if (routingProfile === "premium" || pricing === undefined || !(baselineCost > 0)) return 0; + return Math.max(0, (baselineCost - costEstimate) / baselineCost); +} + /** * Select the primary model for a tier and build the RoutingDecision. * @@ -49,35 +102,11 @@ export function selectModel( ): RoutingDecision { const tierConfig = tierConfigs[tier]; const model = tierConfig.primary; - const pricing = modelPricing.get(model); - - let costEstimate: number; - if (pricing?.flatPrice !== undefined) { - costEstimate = pricing.flatPrice; - } else { - const inputPrice = pricing?.inputPrice ?? 0; - const outputPrice = pricing?.outputPrice ?? 0; - costEstimate = - (estimatedInputTokens / 1_000_000) * inputPrice + (maxOutputTokens / 1_000_000) * outputPrice; - } - - // Baseline: what the anchor Opus tier would cost (see BASELINE_MODEL_ID) - const opusPricing = modelPricing.get(BASELINE_MODEL_ID); - const opusInputPrice = opusPricing?.inputPrice ?? BASELINE_INPUT_PRICE; - const opusOutputPrice = opusPricing?.outputPrice ?? BASELINE_OUTPUT_PRICE; - const baselineInput = (estimatedInputTokens / 1_000_000) * opusInputPrice; - const baselineOutput = (maxOutputTokens / 1_000_000) * opusOutputPrice; - const baselineCost = baselineInput + baselineOutput; + const pricing = usablePricing(modelPricing.get(model)); - // Premium profile doesn't calculate savings (it's about quality, not cost). - // A model the host has no price for costs an unknown amount, not nothing; - // reporting its savings as 100% would be a fabricated figure. - const savings = - routingProfile === "premium" || pricing === undefined - ? 0 - : baselineCost > 0 - ? Math.max(0, (baselineCost - costEstimate) / baselineCost) - : 0; + const costEstimate = rawCost(pricing, estimatedInputTokens, maxOutputTokens); + const baselineCost = baselineCostFor(modelPricing, estimatedInputTokens, maxOutputTokens); + const savings = savingsFor(costEstimate, baselineCost, pricing, routingProfile); return { model, @@ -100,16 +129,16 @@ export function getFallbackChain(tier: Tier, tierConfigs: Record, @@ -117,44 +146,25 @@ export function calculateModelCost( maxOutputTokens: number, routingProfile?: "free" | "eco" | "auto" | "premium", ): { costEstimate: number; baselineCost: number; savings: number } { - const pricing = modelPricing.get(model); + const pricing = usablePricing(modelPricing.get(model)); - let costEstimate: number; - if (pricing?.flatPrice !== undefined) { - // Active promo: fixed cost per request - costEstimate = Math.max(pricing.flatPrice * (1 + SERVER_MARGIN_PERCENT / 100), MIN_PAYMENT_USD); - } else { - // Defensive: guard against undefined price fields (not just undefined pricing) - const inputPrice = pricing?.inputPrice ?? 0; - const outputPrice = pricing?.outputPrice ?? 0; - const inputCost = (estimatedInputTokens / 1_000_000) * inputPrice; - const outputCost = (maxOutputTokens / 1_000_000) * outputPrice; - // Include server margin + minimum payment to match actual x402 charge - costEstimate = Math.max( - (inputCost + outputCost) * (1 + SERVER_MARGIN_PERCENT / 100), - MIN_PAYMENT_USD, - ); - } - - // Baseline: what the anchor Opus tier would cost (see BASELINE_MODEL_ID) - const opusPricing = modelPricing.get(BASELINE_MODEL_ID); - const opusInputPrice = opusPricing?.inputPrice ?? BASELINE_INPUT_PRICE; - const opusOutputPrice = opusPricing?.outputPrice ?? BASELINE_OUTPUT_PRICE; - const baselineInput = (estimatedInputTokens / 1_000_000) * opusInputPrice; - const baselineOutput = (maxOutputTokens / 1_000_000) * opusOutputPrice; - const baselineCost = baselineInput + baselineOutput; - - // Premium profile doesn't calculate savings (it's about quality, not cost) - const savings = - routingProfile === "premium" - ? 0 - : baselineCost > 0 - ? Math.max(0, (baselineCost - costEstimate) / baselineCost) - : 0; + // Server margin + minimum payment, to match the actual x402 charge. + const costEstimate = Math.max( + rawCost(pricing, estimatedInputTokens, maxOutputTokens) * (1 + SERVER_MARGIN_PERCENT / 100), + MIN_PAYMENT_USD, + ); + const baselineCost = baselineCostFor(modelPricing, estimatedInputTokens, maxOutputTokens); + const savings = savingsFor(costEstimate, baselineCost, pricing, routingProfile); return { costEstimate, baselineCost, savings }; } +/** The models satisfying `keep`, or every model when none does. */ +function keepOrFailOpen(models: string[], keep: (modelId: string) => boolean): string[] { + const filtered = models.filter(keep); + return filtered.length > 0 ? filtered : models; +} + /** * Filter a model list to only those that support tool calling. * When hasTools is false, returns the list unchanged. @@ -166,9 +176,7 @@ export function filterByToolCalling( hasTools: boolean, supportsToolCalling: (modelId: string) => boolean, ): string[] { - if (!hasTools) return models; - const filtered = models.filter(supportsToolCalling); - return filtered.length > 0 ? filtered : models; + return hasTools ? keepOrFailOpen(models, supportsToolCalling) : models; } /** @@ -182,9 +190,7 @@ export function filterByVision( hasVision: boolean, supportsVision: (modelId: string) => boolean, ): string[] { - if (!hasVision) return models; - const filtered = models.filter(supportsVision); - return filtered.length > 0 ? filtered : models; + return hasVision ? keepOrFailOpen(models, supportsVision) : models; } /** @@ -194,8 +200,7 @@ export function filterByVision( */ export function filterByExcludeList(models: string[], excludeList: Set): string[] { if (excludeList.size === 0) return models; - const filtered = models.filter((m) => !excludeList.has(m)); - return filtered.length > 0 ? filtered : models; + return keepOrFailOpen(models, (m) => !excludeList.has(m)); } /** diff --git a/strategy.test.ts b/src/strategy.test.ts similarity index 100% rename from strategy.test.ts rename to src/strategy.test.ts diff --git a/strategy.ts b/src/strategy.ts similarity index 95% rename from strategy.ts rename to src/strategy.ts index 229d4e7..7d7c1ec 100644 --- a/strategy.ts +++ b/src/strategy.ts @@ -33,9 +33,12 @@ function applyPromotions( let result = tierConfigs; for (const promo of promotions) { // Check time window - const start = new Date(promo.startDate); - const end = new Date(promo.endDate); - if (now < start || now >= end) continue; + // An unparseable date compares false both ways, which used to make the + // promotion active forever. A window that cannot be read is not a window. + const start = Date.parse(promo.startDate); + const end = Date.parse(promo.endDate); + if (!Number.isFinite(start) || !Number.isFinite(end)) continue; + if (now.getTime() < start || now.getTime() >= end) continue; // Check profile filter if (promo.profiles && !promo.profiles.includes(profile)) continue; @@ -121,7 +124,7 @@ export class RulesStrategy implements RouterStrategy { const { routingProfile } = options; let tierConfigs: Record; let profileSuffix: string; - let profile: RoutingDecision["profile"]; + let profile: NonNullable; if (routingProfile === "eco") { // `ecoTiers: null` explicitly disables the special eco tier set while @@ -165,7 +168,7 @@ export class RulesStrategy implements RouterStrategy { } // Apply time-windowed promotions - tierConfigs = applyPromotions(tierConfigs, config.promotions, profile!, options.now); + tierConfigs = applyPromotions(tierConfigs, config.promotions, profile, options.now); // Hard-remove models the host has observed dead at the gateway. After // promotions, so a promo cannot resurrect a rung the host just killed. diff --git a/tokens.test.ts b/src/tokens.test.ts similarity index 100% rename from tokens.test.ts rename to src/tokens.test.ts diff --git a/tokens.ts b/src/tokens.ts similarity index 78% rename from tokens.ts rename to src/tokens.ts index 0d9a973..9339ffc 100644 --- a/tokens.ts +++ b/src/tokens.ts @@ -22,11 +22,15 @@ export function estimateTokens(text: string): number { return cjk + Math.ceil((text.length - cjk) / 4); } +const MAX_SCAN_CHARS = 8_000; + /** The scan window the feature regexes read, bounded so a pasted document cannot stall routing. */ export function scanLimit(promptTruncationChars: number): number { - return Math.max(1, Math.min(8_000, promptTruncationChars)); + if (!Number.isFinite(promptTruncationChars)) return MAX_SCAN_CHARS; + return Math.max(1, Math.min(MAX_SCAN_CHARS, Math.floor(promptTruncationChars))); } + /** * Feature regexes need request shape and intent, not the entire document. * Sample both ends so a long pasted artifact keeps the task instruction at @@ -35,5 +39,8 @@ export function scanLimit(promptTruncationChars: number): number { export function sampleForScan(value: string, limit: number): string { if (value.length <= limit) return value; const prefixLength = Math.ceil(limit / 2); - return `${value.slice(0, prefixLength)}\n${value.slice(-(limit - prefixLength))}`; + const suffixLength = limit - prefixLength; + // slice(-0) is the whole string, so a one-character limit needs its own case. + if (suffixLength <= 0) return value.slice(0, prefixLength); + return `${value.slice(0, prefixLength)}\n${value.slice(-suffixLength)}`; } diff --git a/tool-intent.test.ts b/src/tool-intent.test.ts similarity index 100% rename from tool-intent.test.ts rename to src/tool-intent.test.ts diff --git a/tool-intent.ts b/src/tool-intent.ts similarity index 100% rename from tool-intent.ts rename to src/tool-intent.ts diff --git a/types.ts b/src/types.ts similarity index 92% rename from types.ts rename to src/types.ts index a288cd1..22c6e48 100644 --- a/types.ts +++ b/src/types.ts @@ -1,11 +1,12 @@ /** * Smart Router Types * - * Four classification tiers — REASONING is distinct from COMPLEX because - * reasoning tasks need different models (o3, gemini-pro) than general - * complex tasks (gpt-4o, sonnet-4). + * Four capability tiers. REASONING is distinct from COMPLEX because proof, + * derivation and multi-step math reward a different model set than broad + * complex work; the configured chains in config.ts carry the current picks. * - * Scoring uses weighted float dimensions with sigmoid confidence calibration. + * Tier scoring uses weighted float dimensions with sigmoid confidence + * calibration (rules.ts); the portfolio strategy ranks within a tier. */ export type Tier = "SIMPLE" | "MEDIUM" | "COMPLEX" | "REASONING"; @@ -23,6 +24,7 @@ export type RoutingDecision = { model: string; tier: Tier; confidence: number; + /** `"llm"` is reserved for a host-side classifier; core strategies emit `"rules"` or `"portfolio"`. */ method: "rules" | "llm" | "portfolio"; reasoning: string; costEstimate: number; @@ -101,6 +103,9 @@ export type RouterOptions = { * selection and never restored by an eligibility fail-open — the operational * kill-switch for a dead chain rung, usable the moment the host observes the * failure instead of waiting on a core release and two consumer repins. + * One exception: a tier whose every rung is listed keeps its configured + * chain, because inventing a substitute would hide the outage from the host + * that reported it (see `applyUnavailableModels`). * Distinct from user-preference exclusion (`filterByExcludeList`), which * deliberately fail-opens rather than empty a chain. */ diff --git a/unavailable-models.test.ts b/src/unavailable-models.test.ts similarity index 100% rename from unavailable-models.test.ts rename to src/unavailable-models.test.ts diff --git a/tsconfig.json b/tsconfig.json index e1039a1..b48839d 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -8,8 +8,10 @@ "resolveJsonModule": true, "esModuleInterop": true, "skipLibCheck": true, - "noEmit": true + "noEmit": true, + "noUnusedLocals": true, + "noFallthroughCasesInSwitch": true }, - "include": ["*.ts"], - "exclude": ["*.test.ts", "dist", "node_modules"] + "include": ["src/**/*.ts", "tsup.config.ts"], + "exclude": ["dist", "node_modules"] } diff --git a/tsup.config.ts b/tsup.config.ts index bdb4ae3..6ad88e3 100644 --- a/tsup.config.ts +++ b/tsup.config.ts @@ -1,7 +1,7 @@ import { defineConfig } from "tsup"; export default defineConfig({ - entry: ["index.ts"], + entry: ["src/index.ts"], format: ["esm"], dts: true, clean: true,