mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-08-03 13:52:09 +03:00
* chore(release): open v3.8.37 development cycle * chore(ci): harden release flow — ratchet decoupling, fast-path drift gates, build-scope guard, heap default (#5054) Implements improvements 1-4 from the v3.8.36 release benchmark (_tasks/release-bench/v3.8.36/PLANO-MELHORIA.md): 1. Quality Ratchet decoupled from flaky coverage (ci.yml): the shard→coverage→ratchet chain meant a single flaky Coverage Shard SKIPPED the whole Quality Ratchet on the release PR (v3.8.36 #4854), so cycle drift only surfaced post-merge in #5029. The job now runs on !cancelled(); coverage download is continue-on-error and the ratchet runs --allow-missing, so the DETERMINISTIC gates (eslint/complexity/cognitive/duplication/ codeql) stay blocking even when coverage is unavailable. 2. Fast-path drift gates (quality.yml PR→release): added check:complexity, check:cognitive-complexity, and a new lightweight check:pack-policy (pack-artifact unexpected-files check WITHOUT a build, via --policy-only) so drift + stray-tarball-file regressions are caught/rebaselined PER-PR instead of cascading onto the release PR. 3. Build heap default 4096→8192 MB (build-next-isolated.mjs): the clean graph peaks ~3.9 GB and brushed the old 4 GB ceiling; 8 GB gives headroom. Comment notes heap is NOT the fix for a poisoned scope (run check:build-scope instead). 4. check:build-scope gate (new): fails if .ts/.tsx/.js/.jsx files in the tsconfig scope exceed a threshold — catches worktrees/cruft leaking into the build scope (the v3.8.36 OOM root cause: 355,215 vs 4,547 files) BEFORE it detonates next build. Wired into the fast-path. * fix(auth): only trust forwarding headers from loopback TCP peers (#4689) Integrated into release/v3.8.37 — loopback-gated forwarding headers (IP spoofing fix). Cherry-picked onto current release tip; ipUtils.test.ts 9/9 green. * fix(codex): treat OAuth 401 as unrecoverable refresh failure (#4686) Integrated into release/v3.8.37 — codex OAuth 401 treated as unrecoverable refresh. Cherry-picked onto release tip; token-refresh-service.test.ts 38/38 green. * fix(translator): preserve reasoning_effort for non-Copilot Responses clients (#4688) Integrated into release/v3.8.37 — preserve reasoning_effort for non-Copilot Responses clients. Cherry-picked onto release tip; tests 47/47 green. * fix(translator): coerce tool descriptions to strings in OpenAI normalization (#4675) Integrated into release/v3.8.37 — coerce tool descriptions to strings in OpenAI normalization. Cherry-picked onto release tip; tests 3/3 green. * feat(sse): x-omniroute-strip-reasoning header to drop reasoning_content (#4678) Integrated into release/v3.8.37 — x-omniroute-strip-reasoning header. Cherry-picked onto release tip (resolved chatCore.ts/headers.ts adjacency conflict, kept resolveCompressionHeader + isStripReasoningRequested); tests 8/8 green. * fix(combo): flatten Anthropic tool messages + tool history to prevent upstream 503 (#4648) Integrated into release/v3.8.37 — flattenToolHistory helper (combo anti-503). Cherry-picked onto release tip; tests 9/9 green. * feat(headroom): proxy lifecycle management + dashboard UI (Docker sidecar supported) (#4649) Integrated into release/v3.8.37 — headroom proxy lifecycle (status/start/stop, local-only + spawn-capable per Rules #15/#17). Cherry-picked onto release tip; lifecycle 7/7 + route-guard 43/43 + check:cycles green. * feat(cli): multi-model support for Factory Droid CLI (#4682) Integrated into release/v3.8.37 — Factory Droid multi-model support. Cherry-picked onto release tip (kept readJsoncConfig + droidCustomModels imports); droid-custom-models 11/11 green. * fix(providers): require Default Model in compatible-provider API-key setup (#4641) Integrated into release/v3.8.37 — require Default Model in compatible-provider API-key setup. Cherry-picked fix + test-move onto release tip (kept release providerSpecificData + QuotaScrapingFields; fixed moved-test import path; baseline rebaseline unneeded, 865<866); UI test 2/2 green. * fix(dashboard): stop double-masking already-masked API key in list (E2E 3/9 regression) (#4671) Integrated into release/v3.8.37 — render server-masked key verbatim (drop redundant maskKey call). Note: release's maskKey already guards '****' (since v3.8.34), so this is a safe simplification; added a contract test pinning the **** passthrough invariant (2/2 green, would fail against the pre-guard maskKey = the historical double-mask bug). * chore(quality): rebaseline file-size for rc17 PR batch drift Own growth from the merged rc17 PRs (#4678/#4686/#4688) at existing chokepoints — cohesive, not extractable: - open-sse/handlers/responseSanitizer.ts 1103->1122 (SanitizeOpenAIResponseOptions + stripReasoning, #4678) - open-sse/services/tokenRefresh.ts 2070->2090 (codex 401 unrecoverable-refresh guard, #4686) - tests/unit/token-refresh-service.test.ts 1322->1353 (401 regression case, #4686) - tests/unit/translator-openai-responses-req.test.ts 1047->1050 (reasoning_effort assertion, #4688) * docs(env): document HEADROOM_URL in .env.example + ENVIRONMENT.md The headroom proxy lifecycle (#4649) reads HEADROOM_URL (src/lib/headroom/detect.ts, default http://localhost:8787) but it was missing from the env contract, tripping check:env-doc-sync. Adds the var to both .env.example (commented, has a default) and the Proxy Health table in ENVIRONMENT.md. * fix(sse): stream writer mock abort() returns a Promise (#4788) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; tests green. * fix(cli): fall back to default data dir when DATA_DIR is not writable (#4767) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; tests green. * fix(oauth): verify Cursor installation on Linux before auto-import (#4770) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; tests green. * fix(sse): track Ollama streaming usage from raw NDJSON chunks (#4754) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; tests green. * fix(sse): strip enumDescriptions from antigravity tool schema (#4740) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; tests green. * fix(sse): include low-level cause details in formatProviderError (#4741) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; tests green. * fix(translator): strip x-anthropic-billing-header in claude-to-openai (#4728) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; tests green. * fix(sse): gate Kiro image attachments behind a Claude-capability check (#4763) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; tests green. * fix(sse): read Antigravity usage from the response.usageMetadata envelope (#4785) Integrated into release/v3.8.37 — Antigravity response.usageMetadata envelope. Cherry-picked onto release tip (resolved test-tail adjacency with #4754 Ollama block); usage-extractor 23/23 green. * fix(api): fall back to existing access token for any OAuth provider on refresh failure (#4786) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; tests green. * fix(cli): verify launchd registration + skip self-SIGTERM in macOS autostart (#4765) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; tests green. * fix(executors): anthropic-compatible-* gateways get Bearer alongside x-api-key (#4729) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; tests green. * fix(sse): json_schema fallback for OpenAI-compatible providers (#4766) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; tests green. * fix(sse): use workos auth token shape for cline (#4787) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; tests green. * feat(sse): parse Gemini CLI 429 retryDelay from structured RetryInfo (#4738) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; tests green. * fix(sse): finalize tool_calls finish_reason on early stream end in OpenAI Responses translator (#4764) Integrated into release/v3.8.37 — computeFinishReason finalizes tool_calls on early stream end (Responses translator). Cherry-picked onto release tip; responses-translation-fixes 29/29 green. * test(sse): golden-lock provider.ts translate-path across all providers (#4734) Integrated into release/v3.8.37 — golden-lock for provider.ts translate-path. Cherry-picked onto release tip; snapshot regenerated against the current provider set (UPDATE_GOLDEN=1, 167 entries); golden test 3/3 deterministic. * chore(quality): rebaseline file-size for rc17 leva2 PR batch drift Own growth from the merged leva2 PRs (cohesive, not extractable): - src/lib/usage/providerLimits.ts 950->955 (#4786) - open-sse/executors/default.ts NEW frozen @828 (#4729 + #4766 + #4787 header branches) - open-sse/translator/request/openai-to-kiro.ts 807->814 (#4763) - open-sse/translator/response/openai-responses.ts 923->937 (#4764) - tests/unit/executor-default-base.test.ts 1339->1440 (#4766) - tests/unit/translator-openai-to-kiro.test.ts 918->980 (#4763) * fix(dashboard): align Engine Combos editor engines with API schema (#4955) (#5062) The named-combos pipeline dropdown offered four engines (headroom, session-dedup, ccr, llmlingua) that stackedPipelineStepSchema rejects, so selecting one made PUT /api/context/combos/[id] return HTTP 400 while saveCombo swallowed the non-OK response (if (!res.ok) return). Editing the default 'Standard Savings' combo and changing an engine reproduced the 400. - Add canonical STACKED_PIPELINE_ENGINE_INTENSITIES next to the schema as the single source of truth; the client dropdown imports it so it can never drift from the discriminated union the API validates against. - Surface save errors and empty-name/empty-pipeline validation in the editor instead of failing silently. - Add a parity unit test asserting the UI engine map equals the schema union and that every (engine, intensity) the UI emits is accepted. * fix(sse): filter nameless hosted tools when converting Responses API to Chat format (#4789) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(dashboard): keep desktop sidebar visible via explicit CSS class (#4812) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(sse): strip enumDescriptions from Antigravity tool schemas (#4813) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(dashboard): resolve passthrough model aliases by providerId in ModelSelectModal (#4815) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(oauth): allow per-connection refresh lead-time override via providerSpecificData.refreshLeadMs (#4818) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(sse): strip X-Stainless-* headers and normalize SDK User-Agent for OpenAI-compatible endpoints (#4820) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(sse): strip Gemini built-in tools when functionDeclarations present in Antigravity envelope (#4821) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(api): surface a Docker-localhost hint on provider-node validation connection errors (#4822) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(sse): resolve bare model names to connection defaultModel before upstream calls (#4825) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(build): trace-include sql.js sql-wasm.wasm in standalone bundle (#4839) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(sse): strip Composer <|final|> sentinel markers leaking after Composer reasoning (#4842) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(config): sync full SiliconFlow model list into registry (#4844) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(sse): close reasoning before message content in Responses stream (#4848) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(sse): reject unsupported Kiro [1m] context suffix (#4816) Integrated into release/v3.8.37 — cherry-picked onto release tip; test-tail conflict with #4763 resolved (kept both image + [1m] test blocks); CHANGELOG re-merged; 29/29 green. * fix(db): validate HuggingFace tokens via whoami-v2 auth probe (#4819) Integrated into release/v3.8.37 — defining commit re-homed onto the god-file-split validation module (validateHuggingFaceProvider in validation/openaiFormat.ts + map wiring); 115/115 green. * fix(sse): make anthropic-version default-guard case-insensitive (#4823) Integrated into release/v3.8.37 — conflict with #4729 Bearer-fallback resolved (kept both Bearer fallback + case-insensitive anthropic-version guard); 48/48 green. * fix(sse): sanitize Kiro tool schemas to avoid 400 "Improperly formed request" (#4847) Integrated into release/v3.8.37 — conflict in kiro-to-openai.ts resolved (kept release fallbackToolCallId + adopted #1375 toolNameMap remap); 7/7 green. * feat(sse): add GPT-4 to the GitHub Copilot provider (#4798) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * feat(sse): add GPT-4o mini to GitHub Copilot provider (#4797) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * feat(api): add MiniMax-M3 pricing row (#4814) Integrated into release/v3.8.37 — pricing row re-homed onto god-file-split pricing/regional.ts (pricing.ts is now a barrel); 4/4 green. * fix(cli): save runtime deps with --save-exact so a sibling install can't prune them (#4841) Integrated into release/v3.8.37 — trayRuntime conflict resolved (kept release SYSTRAY_SPEC + added --save-exact); 2/2 green. * fix(sse): preserve required fields in antigravity tool schemas (#4843) Integrated into release/v3.8.37 — conflict resolved (kept #4740/#4813 enumDescriptions strip + typed normalizeSchemaTypes, added required-preservation helpers; test-tail merged keeping both enumDescriptions + required tests); 7/7 green. * chore(quality): rebaseline file-size for rc17b leva3 PR batch drift * fix(sse): strip reasoning blobs from agentic context to prevent O(n^2) token growth (#4849) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(sse): unwrap Qoder HTTP 200 SSE error envelope so fallback can trigger (#4850) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(sse): strip temperature for Claude models with extended thinking (#4853) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(sse): emit valid concatenable kiro tool_calls.arguments deltas (#4855) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * feat(sse): add toggleable tool-source diagnostics (#4856) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(sse): redact api key from the AUTH debug log in the chat handler (#4858) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(sse): forward AI SDK image parts in Responses translator (#4859) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(sse): resolve custom combos by id and case-insensitive name (#4446) (#4869) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(sse): exclude WS bridge controller-closed error from provider breaker (#4602) (#4870) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * feat(providers): add xAI Grok inbound translators and thinking patcher (#4910) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * feat(embeddings): add dimensions override field to embedding combos (#4913) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * feat(oauth): Codex bulk-import endpoint — POST /api/oauth/codex/import (#4914) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(antigravity): retry transient upstream failures (#4941) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(sse): surface malformed HTTP-200 upstream responses (#4942) Integrated into release/v3.8.37 — cherry-picked defining commit onto release tip; CHANGELOG re-merged; tests green. * fix(sse): normalize Codex custom tools (apply_patch) to { input: string } schema (#4862) Integrated into release/v3.8.37 — conflict in request/openai-responses.ts resolved (kept #4789 nameless-tool skip + added #1007 custom-tool {input:string} normalization); 48/48 green incl. #4789/#4859 regression. * fix(sse): dense, deterministic output ordering in Responses API response.completed (#4906) Integrated into release/v3.8.37 — manual integration with #4862 in response/openai-responses.ts (custom-tool funcItem + dense recordCompletedItem). Fixed a latent #4848 interaction: the close-reasoning-before-message guard force-closed <think>-tag reasoning prematurely, which dense output (#4906) then snapshotted as a partial buffer ("plan" vs "planning") — scoped the guard to native reasoning_content (!inThinking) in BOTH transformer + translator paths. Full Responses suite 203/203 green incl. #4848/#4862 regression. * feat(sse): auto-promote successful combo model to position #1 (#4852) Integrated into release/v3.8.37 — dropped the stale file-size-baseline.json hunk (re-derived against the rc17b rebaseline); code+test applied clean; 13/13 green. * feat(providers): add Pioneer AI (Fastino Labs) provider (#4909) Integrated into release/v3.8.37 — providers.ts apikey block re-homed onto god-file-split src/shared/constants/providers/apikey/frontier-labs.ts (inline APIKEY_PROVIDERS no longer exists); registry/pioneer + providers/index.ts applied clean; 6/6 green. * add DGrid AI gateway provider (#4931) Integrated into release/v3.8.37 — rebased the contributor's commit onto the release tip; providers.ts god-file-split conflict resolved by relocating the dgrid APIKEY_PROVIDERS entry into apikey/gateways.ts; CHANGELOG added. 7/7 green. Thanks @dgridOP! * chore(quality): rebaseline file-size for rc17b leva4 PR batch drift * docs(routing): sync combo strategy docs for Fusion (17 strategies) (#5067) Fusion (16th strategy, panel fan-out + judge synthesis) and headroom shipped but the strategy-count docs were stale (14/15) and omitted both. Update every combo-strategy reference to the canonical 17, add fusion + headroom to all strategy tables, and add a dedicated Fusion section to AUTO-COMBO.md documenting judgeModel / fusionTuning config + an example. - CLAUDE.md, README.md, FEATURES.md, RESILIENCE_GUIDE.md, ARCHITECTURE.md, OPEN_SSE_ARCHITECTURE.md, OMNIROUTE_VS_ALTERNATIVES.md, docs/README.md, request-pipeline.mmd: 14/15 -> 17, list fusion + headroom - docs/routing/AUTO-COMBO.md: strategy table + new Fusion strategy section - docs/openapi.yaml: add reset-window, headroom, fusion to the strategy enum * fix(oauth): classify /api/oauth/cursor/auto-import as local-only (route-guard) (#5070) The Cursor auto-import route runs execFile("which", ["cursor"]) to verify a local Cursor install before importing credentials — a child-process spawn. The check:route-guard-membership gate (Hard Rules #15/#17) flagged it as an unclassified spawn-capable route: reachable past the loopback gate, an RCE-via-tunnel surface (a leaked JWT over a tunnel could trigger the spawn). Classify the specific path in LOCAL_ONLY_API_PREFIXES so loopback enforcement runs unconditionally before any auth check. Scoped to the exact path — the rest of /api/oauth/ (browser redirect/callback flows) stays remote-reachable. TDD: added a failing-then-passing assertion in route-guard-local-prefix.test.ts (classification + an over-broadening guard proving sibling OAuth paths stay remote). check:route-guard-membership now reports 0 new gaps. * chore(release): v3.8.37 — 2026-06-26 --------- Co-authored-by: dgridOP <dgrid_op@outlook.com>
713 lines
25 KiB
TypeScript
713 lines
25 KiB
TypeScript
import { PROVIDER_ID_TO_ALIAS, PROVIDER_MODELS } from "../config/providerModels.ts";
|
|
import { resolveWildcardAlias } from "./wildcardRouter.ts";
|
|
|
|
type ProviderModelAliasMap = Record<string, Record<string, string>>;
|
|
type ModelAliasValue = string | { provider?: string; model?: string };
|
|
type ModelAliasMap = Record<string, ModelAliasValue>;
|
|
type ParsedModel = {
|
|
provider: string | null;
|
|
model: string | null;
|
|
isAlias: boolean;
|
|
providerAlias: string | null;
|
|
extendedContext: boolean;
|
|
};
|
|
type ResolvedModelTarget = {
|
|
provider?: string | null;
|
|
model: string | null;
|
|
};
|
|
|
|
// Derive alias→provider mapping from the single source of truth (PROVIDER_ID_TO_ALIAS)
|
|
// This prevents the two maps from drifting out of sync
|
|
const ALIAS_TO_PROVIDER_ID: Record<string, string> = {};
|
|
for (const [id, alias] of Object.entries(PROVIDER_ID_TO_ALIAS)) {
|
|
if (ALIAS_TO_PROVIDER_ID[alias]) {
|
|
console.log(
|
|
`[MODEL] Warning: alias "${alias}" maps to both "${ALIAS_TO_PROVIDER_ID[alias]}" and "${id}". Using "${id}".`
|
|
);
|
|
}
|
|
ALIAS_TO_PROVIDER_ID[alias] = id;
|
|
}
|
|
// Manual alias overrides — maps slug-style prefixes to canonical provider IDs.
|
|
// These live outside the registry because they represent multiple providers
|
|
// or backward-compatible slug changes, not a single provider's display name.
|
|
// opencode/ → opencode-zen (the main free/open tier; opencode-go is a separate paid tier)
|
|
ALIAS_TO_PROVIDER_ID["opencode"] = "opencode-zen";
|
|
|
|
// Manual aliases for external compatibility not covered by PROVIDER_ID_TO_ALIAS.
|
|
// OpenCode's Zen provider now uses the "opencode" slug, but OmniRoute registers
|
|
// it as "opencode-zen". This alias ensures `opencode/<model>` resolves correctly.
|
|
ALIAS_TO_PROVIDER_ID["opencode"] = "opencode-zen";
|
|
// xiaomi/ is the user-visible prefix for MiMo models; register it so
|
|
// parseModel("xiaomi/mimo-v2-flash") resolves provider = "xiaomi-mimo" instead
|
|
// of falling through to the identity fallback ("xiaomi").
|
|
ALIAS_TO_PROVIDER_ID["xiaomi"] = "xiaomi-mimo";
|
|
// llamacpp/ is the user-visible alias for the llama-cpp self-hosted provider.
|
|
// The canonical ID is "llama-cpp" (with a hyphen), but the catalog and user-facing
|
|
// prefix is "llamacpp". Register it so parseModel("llamacpp/<model>") resolves
|
|
// provider = "llama-cpp" instead of the identity fallback ("llamacpp").
|
|
ALIAS_TO_PROVIDER_ID["llamacpp"] = "llama-cpp";
|
|
|
|
// Provider-scoped legacy model aliases. Used to normalize provider/model inputs
|
|
// and keep backward compatibility when upstream IDs change.
|
|
const PROVIDER_MODEL_ALIASES: ProviderModelAliasMap = {
|
|
openai: {
|
|
"gpt-4o-mini": "gpt-4o-mini",
|
|
},
|
|
github: {
|
|
"claude-4.5-opus": "claude-opus-4-5-20251101",
|
|
"claude-opus-4.5": "claude-opus-4-5-20251101",
|
|
"gemini-3-pro": "gemini-3.1-pro-preview",
|
|
"gemini-3-pro-preview": "gemini-3.1-pro-preview",
|
|
"gemini-3-flash": "gemini-3-flash-preview",
|
|
"raptor-mini": "oswe-vscode-prime",
|
|
},
|
|
gemini: {
|
|
"gemini-3.1-pro": "gemini-3.1-pro-preview",
|
|
"gemini-3-1-pro": "gemini-3.1-pro-preview",
|
|
},
|
|
"gemini-cli": {
|
|
"gemini-3.1-pro": "gemini-3.1-pro-preview",
|
|
"gemini-3-1-pro": "gemini-3.1-pro-preview",
|
|
},
|
|
nvidia: {
|
|
"gpt-oss-120b": "openai/gpt-oss-120b",
|
|
"nvidia/gpt-oss-120b": "openai/gpt-oss-120b",
|
|
"gpt-oss-20b": "openai/gpt-oss-20b",
|
|
"nvidia/gpt-oss-20b": "openai/gpt-oss-20b",
|
|
},
|
|
// Antigravity model aliases must be applied by the Antigravity executor, not by
|
|
// the global model resolver. Applying them here rewrites the client-visible model
|
|
// before credential/account routing and before UI/logging, causing clean IDs like
|
|
// gemini-3.5-flash-high to be exposed and retried as upstream-only legacy ids such
|
|
// as gemini-3-flash-agent. The executor owns provider-wire normalization.
|
|
antigravity: {},
|
|
kiro: {
|
|
"claude-opus-4-7": "claude-opus-4.7",
|
|
"claude-opus-4-6": "claude-opus-4.6",
|
|
"claude-sonnet-4-6": "claude-sonnet-4.6",
|
|
"claude-sonnet-4-5": "claude-sonnet-4.5",
|
|
"claude-haiku-4-5": "claude-haiku-4.5",
|
|
},
|
|
};
|
|
|
|
const CROSS_PROXY_MODEL_ALIASES: Record<string, string> = {
|
|
"gpt-oss:120b": "gpt-oss-120b",
|
|
"deepseek-v3.2-chat": "deepseek-v3.2",
|
|
"deepseek-v3-2": "deepseek-v3.2",
|
|
"qwen3-coder:480b": "Qwen/Qwen3-Coder-480B-A35B-Instruct",
|
|
"claude-opus-4.5": "claude-opus-4-5-20251101",
|
|
"anthropic/claude-opus-4.5": "claude-opus-4-5-20251101",
|
|
};
|
|
|
|
const CROSS_PROXY_MODEL_ALIASES_LOWER = Object.fromEntries(
|
|
Object.entries(CROSS_PROXY_MODEL_ALIASES).map(([alias, canonical]) => [
|
|
alias.toLowerCase(),
|
|
canonical,
|
|
])
|
|
);
|
|
|
|
// Reverse index: modelId -> providerIds that expose this model
|
|
const MODEL_TO_PROVIDERS = new Map<string, string[]>();
|
|
for (const [aliasOrId, models] of Object.entries(PROVIDER_MODELS)) {
|
|
const providerId = ALIAS_TO_PROVIDER_ID[aliasOrId] || aliasOrId;
|
|
for (const modelEntry of models || []) {
|
|
const modelId = modelEntry?.id;
|
|
if (!modelId) continue;
|
|
const providers = MODEL_TO_PROVIDERS.get(modelId) || [];
|
|
if (!providers.includes(providerId)) {
|
|
providers.push(providerId);
|
|
MODEL_TO_PROVIDERS.set(modelId, providers);
|
|
}
|
|
}
|
|
}
|
|
const KNOWN_MODEL_IDS = new Set(MODEL_TO_PROVIDERS.keys());
|
|
// #2877(B): include the effort-suffixed variants so a bare `gpt-5.5-xhigh`
|
|
// (and -high/-medium/-low) infers the codex provider instead of falling through
|
|
// the `/^gpt-/` → openai fallback (which 500s for codex-only credentials).
|
|
const CODEX_PREFERRED_UNPREFIXED_MODELS = new Set([
|
|
"gpt-5.5",
|
|
"gpt-5.5-xhigh",
|
|
"gpt-5.5-high",
|
|
"gpt-5.5-medium",
|
|
"gpt-5.5-low",
|
|
]);
|
|
const CODEX_PREFERRED_UNPREFIXED_MODEL_ALIASES = new Map([["gpt-5.5", "gpt-5.5-medium"]]);
|
|
export const CODEX_NATIVE_UNPREFIXED_MODELS = new Set(["codex-auto-review"]);
|
|
|
|
interface ProviderConnectionLike {
|
|
provider?: unknown;
|
|
isActive?: unknown;
|
|
is_active?: unknown;
|
|
}
|
|
|
|
/**
|
|
* Resolve provider alias to provider ID
|
|
*/
|
|
export function resolveProviderAlias(aliasOrId: string | null | undefined): string | null {
|
|
if (typeof aliasOrId !== "string") return null;
|
|
return ALIAS_TO_PROVIDER_ID[aliasOrId] || aliasOrId;
|
|
}
|
|
|
|
/**
|
|
* #474 — Resolve a bare model name to the selected connection's `defaultModel`.
|
|
*
|
|
* When the client requested a bare model name (no "/", e.g. an alias that
|
|
* resolved to "auto") and the chosen connection declares a `defaultModel`, the
|
|
* upstream provider must receive that concrete model ID instead of the
|
|
* placeholder. A "/"-qualified model name is an explicit provider/model choice
|
|
* and is always returned untouched.
|
|
*
|
|
* Pure function — `requestedModelStr` is the raw client-facing model string
|
|
* (used only to decide whether the name is "bare"); `resolvedModel` is the
|
|
* already-resolved model that would otherwise be sent upstream.
|
|
*/
|
|
export function resolveBareModelToConnectionDefault(
|
|
requestedModelStr: string | null | undefined,
|
|
resolvedModel: string | null | undefined,
|
|
connectionDefaultModel: string | null | undefined
|
|
): string | null {
|
|
const fallback = typeof resolvedModel === "string" ? resolvedModel : null;
|
|
if (typeof requestedModelStr !== "string" || requestedModelStr.includes("/")) {
|
|
return fallback;
|
|
}
|
|
if (typeof connectionDefaultModel === "string" && connectionDefaultModel.length > 0) {
|
|
return connectionDefaultModel;
|
|
}
|
|
return fallback;
|
|
}
|
|
|
|
function isCrossProxyModelCompatEnabled() {
|
|
const raw = process.env.MODEL_ALIAS_COMPAT_ENABLED;
|
|
return raw !== "false" && raw !== "0";
|
|
}
|
|
|
|
export function normalizeCrossProxyModelId(modelId: unknown): {
|
|
modelId: string | null;
|
|
applied: boolean;
|
|
original: string | null;
|
|
} {
|
|
if (!modelId || typeof modelId !== "string" || !isCrossProxyModelCompatEnabled()) {
|
|
return {
|
|
modelId: typeof modelId === "string" ? modelId : null,
|
|
applied: false,
|
|
original: null,
|
|
};
|
|
}
|
|
|
|
const normalized =
|
|
CROSS_PROXY_MODEL_ALIASES[modelId] || CROSS_PROXY_MODEL_ALIASES_LOWER[modelId.toLowerCase()];
|
|
|
|
if (!normalized || normalized === modelId) {
|
|
return { modelId, applied: false, original: null };
|
|
}
|
|
|
|
console.debug(`[MODEL] Cross-proxy alias applied: "${modelId}" → "${normalized}"`);
|
|
return { modelId: normalized, applied: true, original: modelId };
|
|
}
|
|
|
|
/**
|
|
* Resolve provider-specific legacy model alias to canonical model ID.
|
|
*/
|
|
function resolveProviderModelAlias(
|
|
providerOrAlias: string | null | undefined,
|
|
modelId: string | null | undefined
|
|
) {
|
|
if (!modelId || typeof modelId !== "string") return modelId;
|
|
const providerId = resolveProviderAlias(providerOrAlias);
|
|
if (typeof providerId !== "string") return modelId;
|
|
const aliases = PROVIDER_MODEL_ALIASES[providerId];
|
|
return aliases?.[modelId] || modelId;
|
|
}
|
|
|
|
function hasKnownProviderModel(providerOrAlias: string | null | undefined, modelId: string | null) {
|
|
if (!providerOrAlias || !modelId) return false;
|
|
|
|
const providerId = resolveProviderAlias(providerOrAlias);
|
|
if (typeof providerId !== "string") return false;
|
|
const providerAlias = PROVIDER_ID_TO_ALIAS[providerId] || providerId;
|
|
const models = PROVIDER_MODELS[providerAlias] || PROVIDER_MODELS[providerId] || [];
|
|
|
|
if (models.some((entry) => entry?.id === modelId)) return true;
|
|
|
|
const aliases = PROVIDER_MODEL_ALIASES[providerId];
|
|
if (aliases && Object.prototype.hasOwnProperty.call(aliases, modelId)) return true;
|
|
|
|
const canonicalModel = resolveProviderModelAlias(providerId, modelId);
|
|
if (canonicalModel === modelId) return false;
|
|
|
|
return true;
|
|
}
|
|
|
|
function hasCodexPreferredUnprefixedModel(modelId: string) {
|
|
const canonicalModel = CODEX_PREFERRED_UNPREFIXED_MODEL_ALIASES.get(modelId);
|
|
if (!canonicalModel) return false;
|
|
|
|
const providerAlias = PROVIDER_ID_TO_ALIAS.codex || "codex";
|
|
const models = PROVIDER_MODELS[providerAlias] || PROVIDER_MODELS.codex || [];
|
|
return models.some((entry) => entry?.id === canonicalModel);
|
|
}
|
|
|
|
function resolveInferredProviderModel(provider: string, modelId: string) {
|
|
const codexPreferredModel = CODEX_PREFERRED_UNPREFIXED_MODEL_ALIASES.get(modelId);
|
|
if (provider === "codex" && codexPreferredModel) {
|
|
return codexPreferredModel;
|
|
}
|
|
return resolveProviderModelAlias(provider, modelId);
|
|
}
|
|
|
|
function getInferredProvidersForModel(modelId: string) {
|
|
const providers = [...(MODEL_TO_PROVIDERS.get(modelId) || [])];
|
|
|
|
if (
|
|
CODEX_PREFERRED_UNPREFIXED_MODELS.has(modelId) &&
|
|
hasCodexPreferredUnprefixedModel(modelId) &&
|
|
!providers.includes("codex")
|
|
) {
|
|
providers.push("codex");
|
|
}
|
|
|
|
return providers;
|
|
}
|
|
|
|
function isProviderConnectionActive(connection: ProviderConnectionLike) {
|
|
if (connection.isActive !== undefined) {
|
|
return connection.isActive !== false && connection.isActive !== 0;
|
|
}
|
|
if (connection.is_active !== undefined) {
|
|
return connection.is_active !== false && connection.is_active !== 0;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
function getProviderIdFromConnection(connection: unknown) {
|
|
if (!connection || typeof connection !== "object") return null;
|
|
const record = connection as ProviderConnectionLike;
|
|
if (typeof record.provider !== "string" || !record.provider) return null;
|
|
if (!isProviderConnectionActive(record)) return null;
|
|
return resolveProviderAlias(record.provider);
|
|
}
|
|
|
|
async function getActiveProviderSet() {
|
|
try {
|
|
const { getProviderConnections } = await import("@/lib/localDb");
|
|
const conns = (await getProviderConnections()) as unknown[];
|
|
const providers = conns
|
|
.map(getProviderIdFromConnection)
|
|
.filter((provider): provider is string => Boolean(provider));
|
|
return new Set(providers);
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function isTruthyEnv(value: string | undefined) {
|
|
return typeof value === "string" && /^(1|true|yes|on)$/i.test(value.trim());
|
|
}
|
|
|
|
async function getPreferClaudeCodeForUnprefixedClaudeModels() {
|
|
try {
|
|
const { getCachedSettings } = await import("@/lib/localDb");
|
|
const settings = (await getCachedSettings()) as Record<string, unknown>;
|
|
if (typeof settings.preferClaudeCodeForUnprefixedClaudeModels === "boolean") {
|
|
return settings.preferClaudeCodeForUnprefixedClaudeModels;
|
|
}
|
|
} catch {
|
|
// Standalone open-sse usage may not have the app DB layer available.
|
|
}
|
|
|
|
return isTruthyEnv(process.env.OMNIROUTE_PREFER_CLAUDE_CODE_FOR_UNPREFIXED_CLAUDE_MODELS);
|
|
}
|
|
|
|
function shouldPreferClaudeCodeForUnprefixedClaudeModel(
|
|
modelId: string,
|
|
activeProviders: Set<string> | null,
|
|
preferClaudeCode: boolean
|
|
) {
|
|
if (!preferClaudeCode || !/^claude-/i.test(modelId)) {
|
|
return false;
|
|
}
|
|
|
|
// If DB/provider state is unavailable in a lightweight runtime, honor the
|
|
// explicit operator flag and let the normal credential path report any missing
|
|
// Claude Code account. When state is available, avoid stealing traffic from
|
|
// other Claude-family providers unless Claude Code is actually active.
|
|
return activeProviders === null || activeProviders.size === 0 || activeProviders.has("claude");
|
|
}
|
|
|
|
function shouldTreatAsExactModelId(modelStr: string | null) {
|
|
if (!modelStr || typeof modelStr !== "string" || !modelStr.includes("/")) return false;
|
|
if (!KNOWN_MODEL_IDS.has(modelStr)) return false;
|
|
|
|
const firstSlash = modelStr.indexOf("/");
|
|
const providerOrAlias = modelStr.slice(0, firstSlash).trim();
|
|
const providerScopedModel = modelStr.slice(firstSlash + 1).trim();
|
|
return !hasKnownProviderModel(providerOrAlias, providerScopedModel);
|
|
}
|
|
|
|
/**
|
|
* Resolve a provider/model pair into canonical provider ID + provider-scoped model ID.
|
|
* Keeps provider-specific legacy aliases out of downstream capability and budget lookups.
|
|
*/
|
|
export function resolveCanonicalProviderModel(
|
|
providerOrAlias: string | null | undefined,
|
|
modelId: string | null | undefined
|
|
) {
|
|
if (!modelId || typeof modelId !== "string") {
|
|
return {
|
|
provider: resolveProviderAlias(providerOrAlias),
|
|
model: modelId || null,
|
|
};
|
|
}
|
|
|
|
const provider = resolveProviderAlias(providerOrAlias);
|
|
return {
|
|
provider,
|
|
model: resolveProviderModelAlias(provider, modelId),
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Parse model string: "alias/model" or "provider/model" or just alias
|
|
* Supports [1m] suffix for extended 1M context window (e.g. "claude-sonnet-4-6[1m]")
|
|
*/
|
|
export function parseModel(modelStr: string | null | undefined): ParsedModel {
|
|
// Guard truthy non-strings (object/number/array), not just falsy values — a
|
|
// malformed combo `modelStr` or providerSpecificData saved as an object would
|
|
// otherwise reach `cleanStr.endsWith("[1m]")` and crash with
|
|
// `endsWith is not a function`. Same class as #2359 / #2463.
|
|
if (!modelStr || typeof modelStr !== "string") {
|
|
return {
|
|
provider: null,
|
|
model: null,
|
|
isAlias: false,
|
|
providerAlias: null,
|
|
extendedContext: false,
|
|
};
|
|
}
|
|
|
|
// Sanitize: reject strings with path traversal or control characters
|
|
if (/\.\.[\/\\]/.test(modelStr) || /[\x00-\x1f]/.test(modelStr)) {
|
|
console.log(`[MODEL] Warning: rejected malformed model string: "${modelStr.substring(0, 50)}"`);
|
|
return {
|
|
provider: null,
|
|
model: null,
|
|
isAlias: false,
|
|
providerAlias: null,
|
|
extendedContext: false,
|
|
};
|
|
}
|
|
|
|
// Extract [1m] suffix before parsing provider/model
|
|
let extendedContext = false;
|
|
let cleanStr = modelStr;
|
|
if (cleanStr.endsWith("[1m]")) {
|
|
extendedContext = true;
|
|
cleanStr = cleanStr.slice(0, -4);
|
|
}
|
|
cleanStr = cleanStr.trim();
|
|
|
|
// Normalize known cross-proxy provider/model dialects before deciding whether
|
|
// the slash belongs to a provider prefix or to the model ID itself.
|
|
if (cleanStr.includes("/")) {
|
|
cleanStr = normalizeCrossProxyModelId(cleanStr).modelId || cleanStr;
|
|
}
|
|
|
|
if (shouldTreatAsExactModelId(cleanStr)) {
|
|
console.debug(`[MODEL] Treating "${cleanStr}" as an exact model id`);
|
|
return { provider: null, model: cleanStr, isAlias: true, providerAlias: null, extendedContext };
|
|
}
|
|
|
|
// Check if standard format: provider/model or alias/model
|
|
if (cleanStr.includes("/")) {
|
|
const firstSlash = cleanStr.indexOf("/");
|
|
const providerOrAlias = cleanStr.slice(0, firstSlash).trim();
|
|
const model = cleanStr.slice(firstSlash + 1).trim();
|
|
const provider = resolveProviderAlias(providerOrAlias);
|
|
return { provider, model, isAlias: false, providerAlias: providerOrAlias, extendedContext };
|
|
}
|
|
|
|
// Alias format (model alias, not provider alias)
|
|
return { provider: null, model: cleanStr, isAlias: true, providerAlias: null, extendedContext };
|
|
}
|
|
|
|
/**
|
|
* Resolve model alias from aliases object
|
|
* Format: { "alias": "provider/model" }
|
|
*/
|
|
export function resolveModelAliasFromMap(alias: string | null, aliases: ModelAliasMap | null) {
|
|
const resolved = resolveModelAliasTarget(alias, aliases);
|
|
if (!resolved?.provider) return null;
|
|
return {
|
|
provider: resolved.provider,
|
|
model: resolved.model,
|
|
};
|
|
}
|
|
|
|
function resolveModelAliasTarget(
|
|
alias: string | null,
|
|
aliases: ModelAliasMap | null
|
|
): ResolvedModelTarget | null {
|
|
if (!alias || !aliases) return null;
|
|
|
|
const resolved = aliases[alias];
|
|
if (!resolved) return null;
|
|
|
|
if (typeof resolved === "string") {
|
|
return parseAliasTarget(resolved);
|
|
}
|
|
|
|
if (
|
|
resolved &&
|
|
typeof resolved === "object" &&
|
|
typeof resolved.provider === "string" &&
|
|
typeof resolved.model === "string"
|
|
) {
|
|
const normalizedPair = normalizeCrossProxyModelId(
|
|
`${resolved.provider}/${resolved.model}`
|
|
).modelId;
|
|
if (normalizedPair && normalizedPair !== `${resolved.provider}/${resolved.model}`) {
|
|
return parseAliasTarget(normalizedPair);
|
|
}
|
|
|
|
return {
|
|
provider: resolveProviderAlias(resolved.provider),
|
|
model: normalizeCrossProxyModelId(resolved.model).modelId || resolved.model,
|
|
};
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
function parseAliasTarget(target: string): ResolvedModelTarget | null {
|
|
const normalizedTarget = normalizeCrossProxyModelId(target).modelId;
|
|
if (!normalizedTarget || typeof normalizedTarget !== "string") return null;
|
|
|
|
if (normalizedTarget.includes("/")) {
|
|
if (shouldTreatAsExactModelId(normalizedTarget)) {
|
|
return { model: normalizedTarget };
|
|
}
|
|
|
|
const firstSlash = normalizedTarget.indexOf("/");
|
|
return {
|
|
provider: resolveProviderAlias(normalizedTarget.slice(0, firstSlash)),
|
|
model: normalizedTarget.slice(firstSlash + 1),
|
|
};
|
|
}
|
|
|
|
return { model: normalizedTarget };
|
|
}
|
|
|
|
async function resolveModelByProviderInference(modelId: string, extendedContext: boolean) {
|
|
const providers = getInferredProvidersForModel(modelId);
|
|
|
|
const nonOpenAIProviders = providers.filter((p) => p !== "openai");
|
|
|
|
if (CODEX_NATIVE_UNPREFIXED_MODELS.has(modelId)) {
|
|
return {
|
|
provider: "codex",
|
|
model: modelId,
|
|
extendedContext,
|
|
};
|
|
}
|
|
|
|
const [activeProviders, preferClaudeCodeForUnprefixedClaudeModels] = await Promise.all([
|
|
getActiveProviderSet(),
|
|
getPreferClaudeCodeForUnprefixedClaudeModels(),
|
|
]);
|
|
|
|
// Preserve historical behavior: OpenAI stays default when model exists there.
|
|
// Connection availability must not make unprefixed OpenAI models resolve to a
|
|
// different provider; callers can still force Codex with an explicit prefix.
|
|
if (providers.includes("openai")) {
|
|
return {
|
|
provider: "openai",
|
|
model: modelId,
|
|
extendedContext,
|
|
};
|
|
}
|
|
|
|
if (
|
|
activeProviders?.has("codex") &&
|
|
!activeProviders.has("openai") &&
|
|
providers.includes("codex") &&
|
|
CODEX_PREFERRED_UNPREFIXED_MODELS.has(modelId)
|
|
) {
|
|
return {
|
|
provider: "codex",
|
|
model: resolveInferredProviderModel("codex", modelId),
|
|
extendedContext,
|
|
};
|
|
}
|
|
|
|
// Fallback for newly released OpenAI-family model IDs that may not be in the local catalog yet.
|
|
if (/^gpt-/i.test(modelId) || /^o1/i.test(modelId) || /^o3/i.test(modelId)) {
|
|
return {
|
|
provider: "openai",
|
|
model: modelId,
|
|
extendedContext,
|
|
};
|
|
}
|
|
|
|
const candidatesToUse = nonOpenAIProviders;
|
|
|
|
if (
|
|
candidatesToUse.includes("claude") &&
|
|
shouldPreferClaudeCodeForUnprefixedClaudeModel(
|
|
modelId,
|
|
activeProviders,
|
|
preferClaudeCodeForUnprefixedClaudeModels
|
|
)
|
|
) {
|
|
return {
|
|
provider: "claude",
|
|
model: resolveInferredProviderModel("claude", modelId),
|
|
extendedContext,
|
|
};
|
|
}
|
|
|
|
if (candidatesToUse.length === 1) {
|
|
const provider = candidatesToUse[0];
|
|
const canonicalModel = resolveInferredProviderModel(provider, modelId);
|
|
return { provider, model: canonicalModel, extendedContext };
|
|
}
|
|
|
|
if (candidatesToUse.length > 1) {
|
|
const aliasesForHint = candidatesToUse.map((p) => PROVIDER_ID_TO_ALIAS[p] || p);
|
|
const hints = aliasesForHint.slice(0, 2).map((alias) => `${alias}/${modelId}`);
|
|
const message = `Ambiguous model '${modelId}'. Use provider/model prefix (ex: ${hints.join(" or ")}).`;
|
|
console.warn(`[MODEL] ${message} Candidates: ${aliasesForHint.join(", ")}`);
|
|
return {
|
|
provider: null,
|
|
model: modelId,
|
|
errorType: "ambiguous_model",
|
|
errorMessage: message,
|
|
candidateProviders: candidatesToUse,
|
|
candidateAliases: aliasesForHint,
|
|
};
|
|
}
|
|
|
|
// Fallback: infer provider from known model name prefixes before defaulting to openai
|
|
// FIX #73: Models like claude-haiku-4-5-20251001 sent without provider prefix
|
|
// would incorrectly route to OpenAI. Use heuristic prefix detection first.
|
|
if (/^claude-/i.test(modelId)) {
|
|
if (
|
|
shouldPreferClaudeCodeForUnprefixedClaudeModel(
|
|
modelId,
|
|
activeProviders,
|
|
preferClaudeCodeForUnprefixedClaudeModels
|
|
)
|
|
) {
|
|
return { provider: "claude", model: modelId, extendedContext };
|
|
}
|
|
// Claude models → Anthropic provider (canonical source for Claude models)
|
|
return { provider: "anthropic", model: modelId, extendedContext };
|
|
}
|
|
if (/^gemini-/i.test(modelId) || /^gemma-/i.test(modelId)) {
|
|
// Gemini/Gemma models → Gemini provider
|
|
return { provider: "gemini", model: modelId, extendedContext };
|
|
}
|
|
|
|
// Last resort: no provider could be inferred — return a clear error instead
|
|
// of silently defaulting to "openai", which would produce a misleading
|
|
// "No credentials for provider: openai" response when the model name
|
|
// is unrecognised (e.g. a missing combo, a typo, or a bare model id
|
|
// that doesn't exist in any provider's catalog).
|
|
return {
|
|
provider: null,
|
|
model: modelId,
|
|
extendedContext,
|
|
errorType: "model_not_found",
|
|
errorMessage: `Unable to determine provider for model '${modelId}'. Use a provider/model prefix (e.g. openai/${modelId}) or ensure the model is added as a combo entry.`,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Get full model info (parse or resolve)
|
|
* @param {string} modelStr - Model string
|
|
* @param {object|function} aliasesOrGetter - Aliases object or async function to get aliases
|
|
*/
|
|
export async function getModelInfoCore(
|
|
modelStr: string,
|
|
aliasesOrGetter: ModelAliasMap | (() => Promise<ModelAliasMap>) | null
|
|
) {
|
|
const parsed = parseModel(modelStr);
|
|
const { extendedContext } = parsed;
|
|
|
|
if (!parsed.isAlias) {
|
|
const normalizedModel = normalizeCrossProxyModelId(parsed.model).modelId;
|
|
const canonicalModel = resolveProviderModelAlias(parsed.provider, normalizedModel);
|
|
return {
|
|
provider: parsed.provider,
|
|
model: canonicalModel,
|
|
extendedContext,
|
|
};
|
|
}
|
|
|
|
// Get aliases (from object or function)
|
|
const aliases = typeof aliasesOrGetter === "function" ? await aliasesOrGetter() : aliasesOrGetter;
|
|
|
|
// Local alias map (user-provided 2nd arg) wins over all cross-proxy /
|
|
// provider inference paths. When the alias target is a slashful string like
|
|
// "openai/gpt-4o", parse it directly as <provider>/<model> and return
|
|
// immediately — before shouldTreatAsExactModelId() or cross-proxy inference
|
|
// can misclassify the target (e.g. because bazaarlink catalogs it verbatim).
|
|
if (aliases && parsed.model) {
|
|
const directTarget = aliases[parsed.model];
|
|
if (typeof directTarget === "string") {
|
|
const slashIdx = directTarget.indexOf("/");
|
|
if (slashIdx !== -1) {
|
|
const providerPart = directTarget.slice(0, slashIdx);
|
|
const modelPart = directTarget.slice(slashIdx + 1);
|
|
const provider = resolveProviderAlias(providerPart);
|
|
const canonicalModel = resolveProviderModelAlias(provider, modelPart);
|
|
return { provider, model: canonicalModel, extendedContext };
|
|
}
|
|
}
|
|
}
|
|
|
|
// Resolve exact alias
|
|
const resolved = resolveModelAliasTarget(parsed.model, aliases);
|
|
if (resolved?.provider) {
|
|
const canonicalModel = resolveProviderModelAlias(resolved.provider, resolved.model);
|
|
return {
|
|
provider: resolved.provider,
|
|
model: canonicalModel,
|
|
extendedContext,
|
|
};
|
|
}
|
|
if (resolved?.model) {
|
|
return await resolveModelByProviderInference(resolved.model, extendedContext);
|
|
}
|
|
|
|
// T13: Try wildcard alias (glob patterns like "claude-sonnet-*" → "anthropic/claude-sonnet-4-...")
|
|
if (aliases && typeof aliases === "object") {
|
|
const aliasEntries = Object.entries(aliases).map(([pattern, target]) => ({
|
|
pattern,
|
|
target: typeof target === "string" ? target : "",
|
|
}));
|
|
const wildcardMatch = parsed.model ? resolveWildcardAlias(parsed.model, aliasEntries) : null;
|
|
if (wildcardMatch) {
|
|
const target = wildcardMatch.target as string;
|
|
if (target.includes("/")) {
|
|
const firstSlash = target.indexOf("/");
|
|
const providerOrAlias = target.slice(0, firstSlash);
|
|
const targetModel = target.slice(firstSlash + 1);
|
|
const provider = resolveProviderAlias(providerOrAlias);
|
|
const canonicalModel = resolveProviderModelAlias(provider, targetModel);
|
|
return {
|
|
provider,
|
|
model: canonicalModel,
|
|
extendedContext,
|
|
wildcardPattern: wildcardMatch.pattern,
|
|
};
|
|
}
|
|
}
|
|
}
|
|
|
|
const normalizedModelId = normalizeCrossProxyModelId(parsed.model).modelId;
|
|
if (!normalizedModelId) {
|
|
return { provider: null, model: null, extendedContext };
|
|
}
|
|
return await resolveModelByProviderInference(normalizedModelId, extendedContext);
|
|
}
|