Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors
TypeScript a2aai-agentsai-gatewayanthropicclaudeclaude-codeclinecodexcopilotcursordeepseekfree-aigeminikimillm-gatewaymcpopenaiopenai-proxyqwentoken-saver
Release v3.8.13 (#3327)
Diego Rodrigues de Sa e Souzaa25d5f1ef6e2
diff --git a/.dockerignore b/.dockerignoreindex bc06bf65fd..f0d97df70c 100644--- a/.dockerignore+++ b/.dockerignore@@ -39,10 +39,15 @@ playwright-reportblob-report# Documentation-# Translations (~51 MB) are excluded — the Docs viewer reads English sources.-# Screenshots (~1.7 MB) and SVGs (~250 KB) are needed at build time for MDX-# image resolution (fumadocs-mdx bundles them).-# Raster sources under docs/diagrams/ only (exported SVGs are required).+# Issue #2348: The Dashboard Docs viewer reads markdown from `/app/docs` at+# runtime. The previous `docs/*` block hid every file except openapi.yaml,+# so the in-product help screen failed with ENOENT for every page.+# We now keep the English markdown tree plus the docs assets imported by MDX+# during `next build`, while still dropping the bulky translated docs and+# extra raster diagram sources that account for most of the docs footprint+# of the ~50 MB docs directory. The Docs viewer reads the default-locale+# (English) sources at runtime, so translations are not required in the+# container image.docs/i18n/**docs/diagrams/**/*.pngdocs/diagrams/**/*.jpgdiff --git a/.github/workflows/deploy-vps.yml b/.github/workflows/deploy-vps.ymlindex 760a53ba1e..bcd5b61c78 100644--- a/.github/workflows/deploy-vps.yml+++ b/.github/workflows/deploy-vps.yml@@ -17,7 +17,33 @@ jobs:name: Deploy OmniRoute to VPSruns-on: ubuntu-lateststeps:+ - name: Check VPS SSH reachability from runner+ id: reach+ env:+ # Pass the host via env (never interpolate a secret straight into the+ # script body) so /dev/tcp gets a shell variable, not inlined text.+ VPS_HOST: ${{ secrets.VPS_HOST }}+ run: |+ set -uo pipefail+ # A GitHub-hosted runner can only deploy when it can actually open a TCP+ # connection to the VPS SSH port. The Local VPS lives on a private LAN and+ # the Akamai host firewalls :22 to known IPs, so the runner is routinely+ # unable to reach it (`dial tcp ***:22: i/o timeout`). Treat "unreachable+ # from the runner" as a SKIP — the real deploys are run manually from an+ # allowed network via the deploy-vps-local / deploy-vps-akamai skills — so+ # an unreachable host no longer red-fails every release/push pipeline.+ # When the host IS reachable, the deploy step below still runs in full and+ # its health gate surfaces any genuine deploy failure.+ if timeout 15 bash -c 'exec 3<>"/dev/tcp/${VPS_HOST}/22"' 2>/dev/null; then+ echo "reachable=true" >> "$GITHUB_OUTPUT"+ echo "✅ VPS_HOST:22 reachable from the runner — proceeding with deploy."+ else+ echo "reachable=false" >> "$GITHUB_OUTPUT"+ echo "::warning title=Auto-deploy skipped::VPS_HOST:22 is not reachable from this GitHub runner (private LAN / firewalled). Deploy manually with the deploy-vps-local or deploy-vps-akamai skill."+ fi+- name: Deploy via SSH+ if: steps.reach.outputs.reachable == 'true'uses: appleboy/ssh-action@v1with:host: ${{ secrets.VPS_HOST }}diff --git a/.gitignore b/.gitignoreindex c5e212e3b9..746f05b94f 100644--- a/.gitignore+++ b/.gitignore@@ -63,6 +63,9 @@ yarn-error.log*# env files (can opt-in for committing if needed).env*!.env.example+# Provider API keys (never commit)+*.api-key+.nvidia-api-key# vercel.verceldiff --git a/@omniroute/opencode-provider/src/index.ts b/@omniroute/opencode-provider/src/index.tsindex 6f3a2384ee..292bb22b4a 100644--- a/@omniroute/opencode-provider/src/index.ts+++ b/@omniroute/opencode-provider/src/index.ts@@ -129,8 +129,8 @@ export interface OmniRouteProviderOptions {apiKey: string;/** Override the display name shown in OpenCode. Default: `"OmniRoute"`. */displayName?: string;- /** Override the model catalog. Defaults to `OMNIROUTE_DEFAULT_OPENCODE_MODELS`. */- models?: readonly string[];+ /** Override the model catalog. Accepts model ids (strings) or live model entries from `fetchLiveModels`. When entries carry a `contextLength`, it is used directly — no hardcoded map needed. */+ models?: readonly (string | { id: string; contextLength?: number })[];/** Optional human-readable labels keyed by model id. Overridden by `modelCapabilities[id].label`. */modelLabels?: Record<string, string>;/**@@ -139,6 +139,12 @@ export interface OmniRouteProviderOptions {* for custom ids the override is used verbatim.*/modelCapabilities?: Record<string, ModelCapabilities>;+ /**+ * Optional per-model context-length overrides (tokens). Takes precedence+ * over the static `OMNIROUTE_DEFAULT_MODEL_CONTEXT_LENGTHS` map but is+ * superseded by `contextLength` on live model entries passed via `models`.+ */+ modelContextLengths?: Record<string, string | number>;/*** Primary model for OpenCode (top-level `model` key).* Emitted as `"omniroute/<id>"`. When omitted the key is not written.@@ -248,7 +254,12 @@ export function createOmniRouteProvider(options: OmniRouteProviderOptions): Openconst models: Record<string, OpenCodeModelEntry> = {};const seen = new Set<string>();for (const raw of modelList) {- const id = typeof raw === "string" ? raw.trim() : "";+ const id =+ typeof raw === "object" && raw !== null && "id" in raw && typeof (raw as any).id === "string"+ ? (raw as { id: string }).id.trim()+ : typeof raw === "string"+ ? raw.trim()+ : "";if (!id || seen.has(id)) continue;seen.add(id);const defaults = OMNIROUTE_DEFAULT_MODEL_CAPABILITIES[id] ?? {};@@ -266,10 +277,18 @@ export function createOmniRouteProvider(options: OmniRouteProviderOptions): Openif (typeof merged.temperature === "boolean") entry.temperature = merged.temperature;if (typeof merged.tool_call === "boolean") entry.tool_call = merged.tool_call;- // Include context window limit when known — OpenCode reads this to- // determine usable context length for compaction & overflow detection.- const contextLength = OMNIROUTE_DEFAULT_MODEL_CONTEXT_LENGTHS[id];- if (typeof contextLength === "number" && contextLength > 0) {+ // Context window: live model entry (from API catalog) > modelContextLengths > static defaults+ const liveContext =+ typeof raw === "object" && raw !== null+ ? (raw as { contextLength?: number }).contextLength+ : undefined;+ const rawContextLength =+ liveContext ??+ options.modelContextLengths?.[id] ??+ OMNIROUTE_DEFAULT_MODEL_CONTEXT_LENGTHS[id];+ const contextLength =+ typeof rawContextLength === "string" ? parseInt(rawContextLength, 10) : rawContextLength;+ if (typeof contextLength === "number" && !isNaN(contextLength) && contextLength > 0) {entry.limit = { context: contextLength };}@@ -508,7 +527,7 @@ export interface OmniRouteLiveModel {* const config = buildOmniRouteOpenCodeConfig({* baseURL: "http://localhost:20128",* apiKey: "sk_omniroute",- * models: models.map((m) => m.id),+ * models, // OmniRouteLiveModel[] — contextLength auto-extracted* modelLabels: Object.fromEntries(models.map((m) => [m.id, m.name])),* });* ```diff --git a/@omniroute/opencode-provider/tests/index.test.ts b/@omniroute/opencode-provider/tests/index.test.tsindex 50d3439a33..aac6e7a27b 100644--- a/@omniroute/opencode-provider/tests/index.test.ts+++ b/@omniroute/opencode-provider/tests/index.test.ts@@ -430,6 +430,34 @@ test("createOmniRouteProvider omits limit.context for unknown model ids", () =>assert.equal(entry.limit, undefined);});+test("createOmniRouteProvider reads contextLength from a live model entry for ids absent from the static map", () => {+ // #3298 regression guard: the static OMNIROUTE_DEFAULT_MODEL_CONTEXT_LENGTHS+ // map only covers the legacy 8 Claude/Gemini ids. Before this change, any+ // other model got `undefined` context (see the test above, string form) and+ // OpenCode silently fell back to its 128K internal default. A live model+ // entry carrying `contextLength` must now surface as `limit.context`.+ const provider = createOmniRouteProvider({+ baseURL: "http://localhost:20128",+ apiKey: "sk_omniroute",+ models: [{ id: "completely-unknown-model", contextLength: 262_144 }],+ });+ const entry = provider.models["completely-unknown-model"];+ assert.ok(entry.limit, "a live contextLength should produce a limit field even for ids absent from the static map");+ assert.equal(entry.limit!.context, 262_144);+});++test("createOmniRouteProvider: a live model contextLength wins over the static default map", () => {+ // `cc/claude-opus-4-8` has a static default (1_000_000). A live entry carrying+ // a different contextLength must take precedence (live > modelContextLengths >+ // static defaults).+ const provider = createOmniRouteProvider({+ baseURL: "http://localhost:20128",+ apiKey: "sk_omniroute",+ models: [{ id: "cc/claude-opus-4-8", contextLength: 524_288 }],+ });+ assert.equal(provider.models["cc/claude-opus-4-8"].limit!.context, 524_288);+});+test("createOmniRouteProvider serialises limit.context to JSON", () => {const provider = createOmniRouteProvider({baseURL: "http://localhost:20128",diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 544ee7d5b2..21afca071d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,65 @@---+## [3.8.13] — 2026-06-06++### ✨ New Features++- **feat(web-cookie):** self-service login infrastructure for 21 web-cookie providers — three login pathways (Electron BrowserWindow, Playwright dashboard fallback, `POST /api/providers/{id}/login`), token-extraction configs, and a 15-min cookie-validity auto-refresh daemon. Hardened on merge: error bodies sanitized (Hard Rule #12), the spawn-capable login route classified LOCAL_ONLY (Hard Rules #15/#17), and the Electron status listener de-duplicated. ([#3292](https://github.com/diegosouzapw/OmniRoute/pull/3292), closes #3070 — thanks @oyi77 / @diegosouzapw)+- **feat(api):** accept path-scoped API keys on client API routes — keys may arrive via `/api/v1/vscode/<key>/…` path aliases (incl. `raw`/`combos`); explicit `Authorization`/`x-api-key` headers still take precedence. Split out of #3073. ([#3300](https://github.com/diegosouzapw/OmniRoute/pull/3300) — thanks @zhiru)+- **feat(api):** model-catalog enrichment + MCP `model-catalog` tools — richer per-model metadata (context window, capabilities) surfaced through `/v1/models` and new MCP tools, plus `readHeaderValue` header-record support. Split out of #3073; reconciled on merge with the #3309 URL-token hardening (kept the security gate — no query-string credential fallback, management auth stays header-only). ([#3306](https://github.com/diegosouzapw/OmniRoute/pull/3306) — thanks @zhiru / @diegosouzapw)+- **feat(dashboard):** internationalize the proxy settings UI — `ProxyTab` + the proxy `DocumentationTab`/`FreePoolTab`/`VercelRelayModal` now render via `t(...)`, with matching `en`/`pt-BR` message keys. Split out of #3073. ([#3307](https://github.com/diegosouzapw/OmniRoute/pull/3307), [#3310](https://github.com/diegosouzapw/OmniRoute/pull/3310) — thanks @zhiru)+- **feat(provider):** provider test-all endpoint + per-connection rate-limit overrides + model visibility — `POST /api/models/test-all` runs parallel model tests (chunked, timeout-skip) atop a shared `runSingleModelTest` runner; per-connection rate-limit overrides land via `PATCH /api/providers/:id` (new `rate_limit_overrides_json` column + Zod schema); a dashboard model-visibility toolbar (All / Visible / Hidden) drives a `/v1/models` catalog that excludes user-hidden models; models auto-fetch on every connection add; and passthrough (OpenRouter) models gain test buttons. Folds in dashboard fixes on merge (missing alias/delete handlers, duplicate-model-ID React keys, "Hide all" restored) and a build fix so empty `.env` values no longer override real config. ([#3267](https://github.com/diegosouzapw/OmniRoute/pull/3267) — thanks @Vinayrnani)+- **feat(api):** VS Code Copilot Ollama-compatible BYOK endpoint — exposes an Ollama-shaped surface so VS Code Copilot's "bring your own key" Ollama provider can target OmniRoute directly, with a `VscodeTokenAliasCard` in the dashboard endpoint tab to generate the path-scoped token alias. ([#3316](https://github.com/diegosouzapw/OmniRoute/pull/3316) — thanks @zhiru)+- **feat(combo):** Auto-Combo candidate-expansion optimization + playground model dropdown + "only configured" model toggle — reworks the `auto` strategy's candidate selection in `combo.ts` and surfaces a model picker in the playground `StudioConfigPane` / `useAvailableModels`. ([#3322](https://github.com/diegosouzapw/OmniRoute/pull/3322) — thanks @oyi77)++### 🔒 Security++- **fix(auth):** follow-up hardening of the client-API key extractor (#3300) — removed the generic query-string token fallbacks (`?token=`/`?key=`/`?apiKey=`/`?api_key=`), which leak credentials into access logs / Referer headers, and gated URL-borne tokens to client routes only (management auth is now header-only) so a credential in the URL can never authenticate a management route. The path-scoped `/vscode/<key>/…` form the VS Code integration needs is unchanged. (security review follow-up to [#3300](https://github.com/diegosouzapw/OmniRoute/pull/3300) — thanks @zhiru / @diegosouzapw)++### 🔧 Bug Fixes++- **fix(dashboard):** Agent Bridge page (`/dashboard/tools/agent-bridge`) no longer crashes with "Internal Server Error" — the page replaced its well-shaped state with the raw `/api/tools/agent-bridge/state` response (`{ server, agents }`), leaving `serverState` undefined and throwing `Cannot read properties of undefined (reading 'running')`. A shared `normalizeAgentBridgeState()` now maps the route shape into the page contract (incl. `server.certExists → certTrusted`) and always returns safe defaults, used by both the SSR loader and the polling hook. (#3318 — thanks @tycronk20)+- **fix(codex):** strip client-only params (`prompt_cache_retention`, `safety_identifier`, `user`) on the native `codex/` `/v1/responses` passthrough — Codex upstream rejects them with `400 Unsupported parameter`, which broke Factory Droid and any client injecting those fields. The chat-completions path already stripped them; the responses→responses passthrough now does too. (#3317 — thanks @tycronk20)+- **fix(theoldllm):** stop the `[502]: Body is unusable: Body has already been read` error on the cached-token path — the executor read the same upstream `Response` body with `.text()` twice; it now reads it once and only re-reads after a token-rejection refetch. (#3296 — thanks @onizukashonan14-png)+- **fix(dashboard):** keep no-auth providers (opencode, duckduckgo-web, theoldllm, veoaifree-web) visible under the "Show configured only" filter — they never create a connection row (`stats.total === 0`) but are always usable and already appear in `/v1/models`, so the filter now treats `displayAuthType === "no-auth"` as configured. (#3290 — thanks @uniQta)+- **fix(dashboard):** refresh the connection list after a Codex/Claude/Gemini auth import — the import modals called `fetchData()` (which only reloads provider metadata), so a freshly-imported connection stayed invisible until a manual reload; they now call `fetchConnections()`. ([#3320](https://github.com/diegosouzapw/OmniRoute/pull/3320) — thanks @zhiru)+- **fix(cli):** `omniroute update` no longer always fails on a global install — `getCurrentVersion()` and `createBackup()` now resolve `package.json`/`bin` relative to the script (`import.meta.url`) instead of `process.cwd()` (the user's working dir on a global npm/brew install → *"Could not determine current version"*), and the backup copies the `cli` directory with `cpSync({recursive:true})` instead of `copyFileSync`, which threw a swallowed `EISDIR` → *"Failed to create backup. Aborting"*. (#3295 — thanks @uniQta)+- **fix(sse):** harden the passthrough stream against empty upstream responses — emit a synthetic retry chunk on an empty `choices: []` (fixes a Copilot Chat crash) and log empty post-`tool_calls` completions; also registers **MiniMax M3** (1M context) across 8 provider tiers. ([#3297](https://github.com/diegosouzapw/OmniRoute/pull/3297), #3110 — thanks @wilsonicdev)+- **fix(opencode-provider):** extract `contextLength` from the live `/v1/models` catalog (live > `modelContextLengths` > static map) so passthrough models outside the legacy 8-model map no longer silently truncate to OpenCode's 128K default. ([#3298](https://github.com/diegosouzapw/OmniRoute/pull/3298) — thanks @herjarsa / @diegosouzapw)+- **fix(dev):** auto-rebuild `better-sqlite3` on a Node ABI mismatch at `npm run dev` startup (nvm 22↔24) — dev-only, no-op on the healthy path, unrelated errors not swallowed. ([#3301](https://github.com/diegosouzapw/OmniRoute/pull/3301) — thanks @zhiru)+- **fix(api):** remove the bundled **Completions.me** provider preset — empirically verified to return Rick Astley lyrics instead of real completions for every model/prompt. ([#3302](https://github.com/diegosouzapw/OmniRoute/pull/3302), discussion #3293 — thanks @diegosouzapw; reported by @mikmaneggahommie)+- **fix(ci):** skip the auto-deploy step when the VPS SSH port is unreachable from the GitHub runner (private LAN / firewall) instead of red-failing every release pipeline; genuine deploy/boot failures still fail honestly. ([#3299](https://github.com/diegosouzapw/OmniRoute/pull/3299) — thanks @diegosouzapw)+- **fix(sse):** strip leaked internal tool-call envelopes (`to=functions.*` / `multi_tool_use.parallel { … }`) from visible assistant text and sanitize Responses-API streaming (drop `commentary`-phase output items) so harness syntax never reaches the client. ([#3311](https://github.com/diegosouzapw/OmniRoute/pull/3311) — thanks @zhiru)+- **fix(sse):** expose the Claude (`claude-opus-4-6-thinking`, `claude-sonnet-4-6`) and Gemini budget tiers (`gemini-3.1-pro-{high,low}`, `gemini-3.5-flash-{low,extra-low}`) in the Antigravity catalog — they are user-callable on the Antigravity OAuth backend (agy parity), correcting an earlier assumption that Claude had been removed. ([#3303](https://github.com/diegosouzapw/OmniRoute/pull/3303), discussion #3184 — thanks @diegosouzapw)+- **fix(catalog):** compute a combo's `context_length` from the known targets only — a single target with unknown context no longer collapses the whole combo to `undefined`; also accepts live `{id, contextLength}` model entries in the opencode-provider helper (follow-up to #3298). ([#3304](https://github.com/diegosouzapw/OmniRoute/pull/3304) — thanks @herjarsa / @diegosouzapw)++### 📝 Maintenance++- **test(catalog):** align the Antigravity preview-alias catalog test with the #3303 budget tiers — asserts the restored Claude/Gemini tiers are surfaced, locking in the behavior so a future tier change can't silently drop them again (thanks @diegosouzapw)+- **docs:** rename the `resolve-issues` skill references to `review-issues` across the docs/skill surfaces, matching the renamed governance skill (thanks @diegosouzapw)+- **docs:** document the VS Code / Ollama endpoints (API reference + new `docs/reference/CLI-TOOLS.md`) and improve the env-bootstrap + i18n key-coverage tooling. ([#3319](https://github.com/diegosouzapw/OmniRoute/pull/3319) — thanks @zhiru)+- **chore(release):** open the v3.8.13 development cycle (version bump + cycle bookkeeping) and finalize this changelog (thanks @diegosouzapw)++### 🙌 Contributors++Thanks to everyone whose work landed in v3.8.13:++| Contributor | PRs / Issues |+| --- | --- |+| [@zhiru](https://github.com/zhiru) | #3300, #3306, #3307 / #3310, #3309, #3301, #3311, #3320, #3319, #3316 |+| [@tycronk20](https://github.com/tycronk20) | #3317, #3318 |+| [@Vinayrnani](https://github.com/Vinayrnani) | #3267 |+| [@oyi77](https://github.com/oyi77) | #3292 (closes #3070), #3322 |+| [@onizukashonan14-png](https://github.com/onizukashonan14-png) | #3296 |+| [@uniQta](https://github.com/uniQta) | #3290, #3295 |+| [@wilsonicdev](https://github.com/wilsonicdev) | #3297 |+| [@herjarsa](https://github.com/herjarsa) | #3298, #3304 |+| [@mikmaneggahommie](https://github.com/mikmaneggahommie) | reported the Completions.me rickroll (discussion #3293) |+| [@diegosouzapw](https://github.com/diegosouzapw) | maintainer — #3299, #3302, #3303; co-author on #3292 / #3306 / #3298 / #3304 / #3309 |++---+## [3.8.12] — 2026-06-06### ✨ New Features@@ -1850,7 +1909,7 @@ Thank you to all **55+ community contributors** who made v3.8.0 possible! 🎉### 🧹 Chores-- **chore(workflow):** mandate implementation plan generation in `/resolve-issues` workflow before coding+- **chore(workflow):** mandate implementation plan generation in `/review-issues` workflow before coding- **chore(release):** expand contributor credits to 155 PRs across full project history### 🏆 Community Contributors Acknowledgmentdiff --git a/README.md b/README.mdindex e56197c887..bee23a128f 100644--- a/README.md+++ b/README.md@@ -523,6 +523,19 @@ curl http://localhost:20128/v1/models -H "Authorization: Bearer YOUR_KEY"You should see your connected models listed. 🎉 That's it — start coding, and OmniRoute auto-routes & falls back for you.+If your client cannot send custom headers, OmniRoute also exposes tokenized compatibility aliases:++```txt+OpenAI catalog: http://localhost:20128/vscode/YOUR_KEY/+OpenAI models: http://localhost:20128/vscode/YOUR_KEY/models+OpenAI chat: http://localhost:20128/vscode/YOUR_KEY/chat/completions+OpenAI responses: http://localhost:20128/vscode/YOUR_KEY/responses+Ollama chat: http://localhost:20128/vscode/YOUR_KEY/api/chat+Ollama tags: http://localhost:20128/vscode/YOUR_KEY/api/tags+```++Use these only for clients that cannot attach `Authorization: Bearer ...`. Header auth remains the preferred mode.+<br/>## 📦 More install methods — Docker, source, pnpm, Arch</b></summary>diff --git a/bin/cli/commands/update.mjs b/bin/cli/commands/update.mjsindex 5fe56e8c49..e3c95cfd81 100644--- a/bin/cli/commands/update.mjs+++ b/bin/cli/commands/update.mjs@@ -1,16 +1,24 @@import { printHeading, printInfo, printSuccess, printError } from "../io.mjs";import { homedir } from "node:os";import path from "node:path";+import { fileURLToPath } from "node:url";import { execFile } from "node:child_process";import { promisify } from "node:util";import { t } from "../i18n.mjs";const execFileAsync = promisify(execFile);-async function getCurrentVersion() {+// This file lives at <pkgRoot>/bin/cli/commands/update.mjs — resolve package+// paths relative to the script, NOT process.cwd(). On a global npm/brew install+// the user's cwd is not the package root, so cwd-relative lookups break (#3295).+const SCRIPT_DIR = path.dirname(fileURLToPath(import.meta.url));+const PKG_ROOT = path.resolve(SCRIPT_DIR, "..", "..", "..");+const BIN_DIR = path.join(PKG_ROOT, "bin");++export async function getCurrentVersion() {try {const { readFileSync } = await import("node:fs");- const pkg = JSON.parse(readFileSync(path.join(process.cwd(), "package.json"), "utf-8"));+ const pkg = JSON.parse(readFileSync(path.join(PKG_ROOT, "package.json"), "utf-8"));return pkg.version;} catch {return null;@@ -38,12 +46,12 @@ function compareVersions(a, b) {return 0;}-async function createBackup() {- const binPath = path.join(process.cwd(), "bin");+export async function createBackup() {+ const binPath = BIN_DIR;const backupDir = path.join(homedir(), ".omniroute", "backups", `omniroute-${Date.now()}`);try {- const { mkdirSync, copyFileSync, existsSync } = await import("node:fs");+ const { mkdirSync, cpSync, existsSync } = await import("node:fs");if (!existsSync(binPath)) return null;mkdirSync(backupDir, { recursive: true });@@ -51,7 +59,9 @@ async function createBackup() {for (const f of files) {const src = path.join(binPath, f);if (existsSync(src)) {- copyFileSync(src, path.join(backupDir, f));+ // cpSync handles both files and directories; the old copyFileSync threw+ // EISDIR on the "cli" directory, which was swallowed by the catch (#3295).+ cpSync(src, path.join(backupDir, f), { recursive: true });}}return backupDir;diff --git a/bin/reset-password.mjs b/bin/reset-password.mjsold mode 100644new mode 100755diff --git a/docs/architecture/REPOSITORY_MAP.md b/docs/architecture/REPOSITORY_MAP.mdindex c9c2bbb9b2..bddfefd9d5 100644--- a/docs/architecture/REPOSITORY_MAP.md+++ b/docs/architecture/REPOSITORY_MAP.md@@ -491,7 +491,7 @@ Shipped configuration templates and sample files (referenced by setup wizard).| `commands/deploy-vps-{local,akamai,both}-cc.md` | Deploy to VPS || `commands/capture-release-evidences-cc.md` | Browser-record new features as WebP || `commands/review-{prs,discussions}-cc.md` | Triage GitHub PRs/discussions |-| `commands/{issue-triage,resolve-issues,implement-features}-cc.md` | Issue workflows |+| `commands/{review-issues,implement-features}-cc.md` | Issue workflows || `settings.local.json` | Per-project Claude Code settings |---diff --git a/docs/guides/SETUP_GUIDE.md b/docs/guides/SETUP_GUIDE.mdindex 04c1e29d72..1946fd8e23 100644--- a/docs/guides/SETUP_GUIDE.md+++ b/docs/guides/SETUP_GUIDE.md@@ -153,6 +153,15 @@ API Key: [copy from Endpoint page]Model: if/kimi-k2-thinking (or any provider/model prefix)```+If your editor cannot send `Authorization: Bearer ...`, use the tokenized compatibility base instead:++```txt+Base URL: http://localhost:20128/api/v1/vscode/YOUR_KEY/+Models URL: http://localhost:20128/api/v1/vscode/YOUR_KEY/models+Chat URL: http://localhost:20128/api/v1/vscode/YOUR_KEY/chat/completions+Ollama Tags URL: http://localhost:20128/api/v1/vscode/YOUR_KEY/api/tags+```+Works with Claude Code, Codex CLI, Gemini CLI, Cursor, Cline, OpenClaw, OpenCode, and OpenAI-compatible SDKs.For detailed per-tool configuration (Claude Code, Codex CLI, Cursor, Cline, OpenClaw, Kilo Code, Copilot, and more), see the dedicated **[CLI Tools Guide](../reference/CLI-TOOLS.md)**.diff --git a/docs/i18n/ar/CHANGELOG.md b/docs/i18n/ar/CHANGELOG.mdindex 7099f35915..4136e52273 100644--- a/docs/i18n/ar/CHANGELOG.md+++ b/docs/i18n/ar/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/az/CHANGELOG.md b/docs/i18n/az/CHANGELOG.mdindex 6ed35d921e..98b9c41c1d 100644--- a/docs/i18n/az/CHANGELOG.md+++ b/docs/i18n/az/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/bg/CHANGELOG.md b/docs/i18n/bg/CHANGELOG.mdindex 6ed35d921e..98b9c41c1d 100644--- a/docs/i18n/bg/CHANGELOG.md+++ b/docs/i18n/bg/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/bn/CHANGELOG.md b/docs/i18n/bn/CHANGELOG.mdindex 6357c2c966..9705ecb4f8 100644--- a/docs/i18n/bn/CHANGELOG.md+++ b/docs/i18n/bn/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/cs/CHANGELOG.md b/docs/i18n/cs/CHANGELOG.mdindex 97c5293ff5..f9179b1f2a 100644--- a/docs/i18n/cs/CHANGELOG.md+++ b/docs/i18n/cs/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/da/CHANGELOG.md b/docs/i18n/da/CHANGELOG.mdindex b6da9f37d5..0ff9ae4d54 100644--- a/docs/i18n/da/CHANGELOG.md+++ b/docs/i18n/da/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/de/CHANGELOG.md b/docs/i18n/de/CHANGELOG.mdindex 4b98b56749..3f5c0ba412 100644--- a/docs/i18n/de/CHANGELOG.md+++ b/docs/i18n/de/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/es/CHANGELOG.md b/docs/i18n/es/CHANGELOG.mdindex 3a3a0e4a7b..add692fc28 100644--- a/docs/i18n/es/CHANGELOG.md+++ b/docs/i18n/es/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/fa/CHANGELOG.md b/docs/i18n/fa/CHANGELOG.mdindex 2d8a775e12..a3de3e8340 100644--- a/docs/i18n/fa/CHANGELOG.md+++ b/docs/i18n/fa/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/fi/CHANGELOG.md b/docs/i18n/fi/CHANGELOG.mdindex 1cc8f68ace..d886bcc0aa 100644--- a/docs/i18n/fi/CHANGELOG.md+++ b/docs/i18n/fi/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/fr/CHANGELOG.md b/docs/i18n/fr/CHANGELOG.mdindex faa0d1307c..4cb69e0825 100644--- a/docs/i18n/fr/CHANGELOG.md+++ b/docs/i18n/fr/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/gu/CHANGELOG.md b/docs/i18n/gu/CHANGELOG.mdindex cecf848488..f272199b0c 100644--- a/docs/i18n/gu/CHANGELOG.md+++ b/docs/i18n/gu/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/he/CHANGELOG.md b/docs/i18n/he/CHANGELOG.mdindex 81fe4585da..c5dcae3884 100644--- a/docs/i18n/he/CHANGELOG.md+++ b/docs/i18n/he/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/hi/CHANGELOG.md b/docs/i18n/hi/CHANGELOG.mdindex d637662048..c8162bab02 100644--- a/docs/i18n/hi/CHANGELOG.md+++ b/docs/i18n/hi/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/hu/CHANGELOG.md b/docs/i18n/hu/CHANGELOG.mdindex eca10f8689..a8dea7557b 100644--- a/docs/i18n/hu/CHANGELOG.md+++ b/docs/i18n/hu/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/id/CHANGELOG.md b/docs/i18n/id/CHANGELOG.mdindex ee81bfebc9..6ee3a8f3be 100644--- a/docs/i18n/id/CHANGELOG.md+++ b/docs/i18n/id/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/in/CHANGELOG.md b/docs/i18n/in/CHANGELOG.mdindex ddea5fb1c0..2a4911b70a 100644--- a/docs/i18n/in/CHANGELOG.md+++ b/docs/i18n/in/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/it/CHANGELOG.md b/docs/i18n/it/CHANGELOG.mdindex 8d977033e3..b9c02cd599 100644--- a/docs/i18n/it/CHANGELOG.md+++ b/docs/i18n/it/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/ja/CHANGELOG.md b/docs/i18n/ja/CHANGELOG.mdindex 87d01e497b..4650931ed4 100644--- a/docs/i18n/ja/CHANGELOG.md+++ b/docs/i18n/ja/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/ko/CHANGELOG.md b/docs/i18n/ko/CHANGELOG.mdindex 0d2b79e13f..0446104f61 100644--- a/docs/i18n/ko/CHANGELOG.md+++ b/docs/i18n/ko/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/mr/CHANGELOG.md b/docs/i18n/mr/CHANGELOG.mdindex 32e3601df0..54cacc8796 100644--- a/docs/i18n/mr/CHANGELOG.md+++ b/docs/i18n/mr/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/ms/CHANGELOG.md b/docs/i18n/ms/CHANGELOG.mdindex cf684789d5..85167f999f 100644--- a/docs/i18n/ms/CHANGELOG.md+++ b/docs/i18n/ms/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/nl/CHANGELOG.md b/docs/i18n/nl/CHANGELOG.mdindex ef2cd39cb6..a9e80a1414 100644--- a/docs/i18n/nl/CHANGELOG.md+++ b/docs/i18n/nl/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/no/CHANGELOG.md b/docs/i18n/no/CHANGELOG.mdindex 5956066847..d64394d6b8 100644--- a/docs/i18n/no/CHANGELOG.md+++ b/docs/i18n/no/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/phi/CHANGELOG.md b/docs/i18n/phi/CHANGELOG.mdindex 67d8f06a8b..cdf41a6a49 100644--- a/docs/i18n/phi/CHANGELOG.md+++ b/docs/i18n/phi/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/pl/CHANGELOG.md b/docs/i18n/pl/CHANGELOG.mdindex 82c526e787..2ac00641cc 100644--- a/docs/i18n/pl/CHANGELOG.md+++ b/docs/i18n/pl/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/pt-BR/CHANGELOG.md b/docs/i18n/pt-BR/CHANGELOG.mdindex fd0aa78204..9b9c89f1de 100644--- a/docs/i18n/pt-BR/CHANGELOG.md+++ b/docs/i18n/pt-BR/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/pt/CHANGELOG.md b/docs/i18n/pt/CHANGELOG.mdindex f8ab9cc2f7..710739ebfa 100644--- a/docs/i18n/pt/CHANGELOG.md+++ b/docs/i18n/pt/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/ro/CHANGELOG.md b/docs/i18n/ro/CHANGELOG.mdindex 85a56f549f..a6e5789f59 100644--- a/docs/i18n/ro/CHANGELOG.md+++ b/docs/i18n/ro/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/ru/CHANGELOG.md b/docs/i18n/ru/CHANGELOG.mdindex 3ccb45317b..ef78374cdd 100644--- a/docs/i18n/ru/CHANGELOG.md+++ b/docs/i18n/ru/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/sk/CHANGELOG.md b/docs/i18n/sk/CHANGELOG.mdindex ee187265d7..6b948f30ea 100644--- a/docs/i18n/sk/CHANGELOG.md+++ b/docs/i18n/sk/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/sv/CHANGELOG.md b/docs/i18n/sv/CHANGELOG.mdindex f7076f36a2..b3501f977c 100644--- a/docs/i18n/sv/CHANGELOG.md+++ b/docs/i18n/sv/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/sw/CHANGELOG.md b/docs/i18n/sw/CHANGELOG.mdindex 290d8120e7..16d5e5eb69 100644--- a/docs/i18n/sw/CHANGELOG.md+++ b/docs/i18n/sw/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/ta/CHANGELOG.md b/docs/i18n/ta/CHANGELOG.mdindex 9b209cd9c9..e251de7ce6 100644--- a/docs/i18n/ta/CHANGELOG.md+++ b/docs/i18n/ta/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/te/CHANGELOG.md b/docs/i18n/te/CHANGELOG.mdindex 0239fcdb2a..446a26df3f 100644--- a/docs/i18n/te/CHANGELOG.md+++ b/docs/i18n/te/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/th/CHANGELOG.md b/docs/i18n/th/CHANGELOG.mdindex 03094c6d21..ee410061e0 100644--- a/docs/i18n/th/CHANGELOG.md+++ b/docs/i18n/th/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/tr/CHANGELOG.md b/docs/i18n/tr/CHANGELOG.mdindex 70020f4e1f..0d164c8f08 100644--- a/docs/i18n/tr/CHANGELOG.md+++ b/docs/i18n/tr/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/uk-UA/CHANGELOG.md b/docs/i18n/uk-UA/CHANGELOG.mdindex 3ec67e6e53..a92d030ab7 100644--- a/docs/i18n/uk-UA/CHANGELOG.md+++ b/docs/i18n/uk-UA/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/ur/CHANGELOG.md b/docs/i18n/ur/CHANGELOG.mdindex 28c8fbe81f..2ff61461be 100644--- a/docs/i18n/ur/CHANGELOG.md+++ b/docs/i18n/ur/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/vi/CHANGELOG.md b/docs/i18n/vi/CHANGELOG.mdindex 74931a0741..13c1a60f3a 100644--- a/docs/i18n/vi/CHANGELOG.md+++ b/docs/i18n/vi/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/i18n/zh-CN/CHANGELOG.md b/docs/i18n/zh-CN/CHANGELOG.mdindex 936d958389..93a2b91674 100644--- a/docs/i18n/zh-CN/CHANGELOG.md+++ b/docs/i18n/zh-CN/CHANGELOG.md@@ -4,6 +4,12 @@---+## [3.8.13] — Unreleased++_Development cycle in progress._++---+## [3.8.12] — Unreleased_Development cycle in progress._diff --git a/docs/reference/API_REFERENCE.md b/docs/reference/API_REFERENCE.mdindex 43c6a71e7f..dc5712fc42 100644--- a/docs/reference/API_REFERENCE.md+++ b/docs/reference/API_REFERENCE.md@@ -154,9 +154,17 @@ Authorization: Bearer your-api-key| GET | `/v1beta/models` | Gemini || POST | `/v1beta/models/{...path}` | Gemini generateContent || POST | `/v1/api/chat` | Ollama |+| GET | `/api/v1/vscode/{token}/` | OpenAI catalog alias |+| GET | `/api/v1/vscode/{token}/models` | OpenAI models alias |+| POST | `/api/v1/vscode/{token}/chat/completions` | OpenAI tokenized alias |+| POST | `/api/v1/vscode/{token}/responses` | OpenAI Responses tokenized alias |+| POST | `/api/v1/vscode/{token}/api/chat` | Ollama tokenized alias |+| GET | `/api/v1/vscode/{token}/api/tags` | Ollama tags tokenized alias |All POST routes follow the same shape: `Bearer your-api-key` + Zod-validated JSON body (`v1RerankSchema`, `v1ModerationSchema`, `v1AudioSpeechSchema`, etc., see `src/shared/validation/schemas.ts`). 4xx is returned on schema failure.+For clients that cannot attach `Authorization: Bearer ...`, OmniRoute also accepts API keys in the URL via either query-string compatibility (`?token=...`, `?apiKey=...`, `?api_key=...`, `?key=...`) or the dedicated `/api/v1/vscode/{token}/...` endpoints documented below.+```bash# RerankPOST /v1/rerank { "model": "cohere/rerank-3", "query": "...", "documents": ["..."] }@@ -608,6 +616,39 @@ GET /api/tagsRequests are automatically translated between Ollama and internal formats.+## Tokenized VS Code / Headerless Aliases++Use these aliases when an integration cannot inject an `Authorization` header and needs the API key embedded in the base URL.++```bash+# OpenAI-style catalog alias+GET /api/v1/vscode/{token}/+GET /api/v1/vscode/{token}/models++# OpenAI-style chat aliases+POST /api/v1/vscode/{token}/chat/completions+POST /api/v1/vscode/{token}/responses++# Ollama-style aliases+POST /api/v1/vscode/{token}/api/chat+GET /api/v1/vscode/{token}/api/tags+```++Example:++```bash+curl https://your-host.example/api/v1/vscode/YOUR_API_KEY/models+curl -X POST https://your-host.example/api/v1/vscode/YOUR_API_KEY/chat/completions \+ -H "Content-Type: application/json" \+ -d '{"model":"auto","messages":[{"role":"user","content":"hello"}]}'+```++Notes:++- The tokenized aliases reuse the same handlers as `/v1/*` and `/api/tags`; response shapes stay identical.+- Prefer `Authorization: Bearer ...` whenever the client supports custom headers.+- URL-based tokens may appear in reverse-proxy logs, browser history, and telemetry outside OmniRoute. Treat them as a compatibility option, not the default authentication mode.+---## Telemetrydiff --git a/docs/reference/CLI-TOOLS.md b/docs/reference/CLI-TOOLS.mdindex 24e2a199b6..3526930133 100644--- a/docs/reference/CLI-TOOLS.md+++ b/docs/reference/CLI-TOOLS.md@@ -297,6 +297,243 @@ export OPENAI_BASE_URL="http://localhost:20128/v1"export OPENAI_API_KEY="sk-your-omniroute-key"export ANTHROPIC_BASE_URL="http://localhost:20128"export ANTHROPIC_AUTH_TOKEN="sk-your-omniroute-key"+export GEMINI_BASE_URL="http://localhost:20128/v1"+export GEMINI_API_KEY="sk-your-omniroute-key"+```++> For a **remote server** replace `localhost:20128` with the server IP or domain,+> e.g. `http://<your-server-ip>:20128`.++---++### Step 4 — Configure Each Tool++#### Claude Code++```bash+# Create ~/.claude/settings.json:+mkdir -p ~/.claude && cat > ~/.claude/settings.json << EOF+{+ "env": {+ "ANTHROPIC_BASE_URL": "http://localhost:20128",+ "ANTHROPIC_AUTH_TOKEN": "sk-your-omniroute-key"+ }+}+EOF+```++Use the unified Anthropic gateway root for Claude Code. Do not append `/v1` here.++**Test:** `claude "say hello"`++---++#### OpenAI Codex++```bash+mkdir -p ~/.codex && cat > ~/.codex/config.yaml << EOF+model: auto+apiKey: sk-your-omniroute-key+apiBaseUrl: http://localhost:20128/v1+EOF+```++**Test:** `codex "what is 2+2?"`++---++#### OpenCode++```bash+mkdir -p ~/.config/opencode && cat > ~/.config/opencode/opencode.json << EOF+{+ "\$schema": "https://opencode.ai/config.json",+ "provider": {+ "omniroute": {+ "npm": "@ai-sdk/openai-compatible",+ "name": "OmniRoute",+ "options": {+ "baseURL": "http://localhost:20128/v1",+ "apiKey": "sk-your-omniroute-key"+ },+ "models": {+ "claude-sonnet-4-5": { "name": "claude-sonnet-4-5" },+ "claude-sonnet-4-5-thinking": { "name": "claude-sonnet-4-5-thinking" },+ "gemini-3-flash": { "name": "gemini-3-flash" }+ }+ }+ }+}+EOF+```++**Test:** `opencode`++> Use `opencode run "your prompt" --model omniroute/claude-sonnet-4-5-thinking --variant high`+> to send thinking variants.++---++#### Cline (CLI or VS Code)++**CLI mode:**++```bash+mkdir -p ~/.cline/data && cat > ~/.cline/data/globalState.json << EOF+{+ "apiProvider": "openai",+ "openAiBaseUrl": "http://localhost:20128/v1",+ "openAiApiKey": "sk-your-omniroute-key"+}+EOF+```++**VS Code mode:**+Cline extension settings → API Provider: `OpenAI Compatible` → Base URL: `http://localhost:20128/v1`++Or use the OmniRoute dashboard → **CLI Tools → Cline → Apply Config**.++---++#### KiloCode (CLI or VS Code)++**CLI mode:**++```bash+kilocode --api-base http://localhost:20128/v1 --api-key sk-your-omniroute-key+```++**VS Code settings:**++```json+{+ "kilo-code.openAiBaseUrl": "http://localhost:20128/v1",+ "kilo-code.apiKey": "sk-your-omniroute-key"+}+```++Or use the OmniRoute dashboard → **CLI Tools → KiloCode → Apply Config**.++---++#### Continue (VS Code Extension)++Edit `~/.continue/config.yaml`:++```yaml+models:+ - name: OmniRoute+ provider: openai+ model: auto+ apiBase: http://localhost:20128/v1+ apiKey: sk-your-omniroute-key+ default: true+```++Restart VS Code after editing.++---++#### VS Code Insiders (`chatLanguageModels.json`)++Use this when VS Code Insiders is configured for custom endpoint models and you want OmniRoute to work without a custom header field.++**Recommended location:**++- Linux: `~/.config/Code - Insiders/User/chatLanguageModels.json`+- Windows: `%APPDATA%/Code - Insiders/User/chatLanguageModels.json`++**Example using the tokenized OmniRoute alias:**++```json+[+ {+ "vendor": "customendpoint",+ "id": "auto",+ "name": "OmniRoute Auto",+ "family": "gpt-4",+ "version": "1.0.0",+ "url": "http://localhost:20128/api/v1/vscode/sk-your-omniroute-key/chat/completions",+ "modelsUrl": "http://localhost:20128/api/v1/vscode/sk-your-omniroute-key/models",+ "requestFormat": "openai-chat-completions",+ "contextWindow": 256000,+ "maxOutputTokens": 32768,+ "auth": {+ "type": "none"+ }+ }+]+```++**Notes:**++- Replace `sk-your-omniroute-key` with an API key created in OmniRoute.+- The `url` field should point to `/api/v1/vscode/{token}/chat/completions`.+- The `modelsUrl` field should point to `/api/v1/vscode/{token}/models`.+- Prefer the normal `/v1` + Bearer header flow when the client supports custom headers.+- URL-embedded tokens are a compatibility fallback and may appear in editor logs or proxy history.++---++#### Kiro CLI (Amazon)++```bash+# Login to your AWS/Kiro account:+kiro-cli login++# The CLI uses its own auth — OmniRoute is not needed as backend for Kiro CLI itself.+# Use kiro-cli alongside OmniRoute for other tools.+kiro-cli status+```++For the **Kiro IDE** desktop app, use the MITM endpoint exposed by OmniRoute+under `/dashboard/cli-tools → Kiro`.++---++#### Qwen Code (Alibaba)++Qwen Code supports OpenAI-compatible API endpoints via environment variables or `settings.json`.++> Qwen OAuth free tier was discontinued on 2026-04-15. Use OmniRoute with+> `bailian-coding-plan` / `alibaba` / `alibaba-cn` / `openrouter` / `anthropic` /+> `gemini` providers instead.++**Option 1: Environment variables (`~/.qwen/.env`)**++```bash+mkdir -p ~/.qwen && cat > ~/.qwen/.env << EOF+OPENAI_API_KEY="sk-your-omniroute-key"+OPENAI_BASE_URL="http://localhost:20128/v1"+OPENAI_MODEL="auto"+EOF+```++**Option 2: `settings.json` with `security.auth`**++```json+// ~/.qwen/settings.json+{+ "security": {+ "auth": {+ "selectedType": "openai",+ "apiKey": "sk-your-omniroute-key",+ "baseUrl": "http://localhost:20128/v1"+ }+ },+ "model": {+ "name": "claude-sonnet-4-6"+ }+}+```++**Option 3: Inline CLI flags**++```bash+OPENAI_BASE_URL="http://localhost:20128/v1" \+OPENAI_API_KEY="sk-your-omniroute-key" \+OPENAI_MODEL="auto" \+qwen```> For a **remote server** replace `localhost:20128` with the server IP or domain.@@ -320,6 +557,144 @@ omniroute --version # Print versionomniroute --help # Show all commands```+### Setup & Initialization++```bash+omniroute setup # Interactive setup wizard+omniroute setup --non-interactive # CI/automation mode (reads env vars + flags)+omniroute setup --password '<value>' # Set admin password directly+omniroute setup --add-provider \+ --provider openai \+ --api-key '<value>' \+ --test-provider # Add and test a provider in one shot+```++Recognized environment variables for non-interactive setup:++| Var | Purpose |+| ----------------------------- | -------------------------------------------- |+| `OMNIROUTE_SETUP_PASSWORD` | Admin password (>=8 chars) |+| `OMNIROUTE_PROVIDER` | Provider id (e.g. `openai`, `anthropic`) |+| `OMNIROUTE_PROVIDER_NAME` | Display name for the connection |+| `OMNIROUTE_PROVIDER_BASE_URL` | Optional OpenAI-compatible base URL override |+| `OMNIROUTE_API_KEY` | Provider API key |+| `OMNIROUTE_DEFAULT_MODEL` | Optional default model |+| `DATA_DIR` | Override the OmniRoute data directory |++### Diagnostics++```bash+omniroute doctor # Check config, DB, ports, runtime, memory, liveness+omniroute doctor --json # Machine-readable JSON+omniroute doctor --no-liveness # Skip the HTTP health probe+omniroute doctor --host 0.0.0.0 # Override liveness host+omniroute doctor --liveness-url <url> # Full health endpoint URL override+```++The doctor runs these checks: `Config`, `Database`, `Storage/encryption`,+`Port availability`, `Node runtime`, `Native binary` (better-sqlite3),+`Memory`, and `Server liveness`. It exits non-zero if any check is `fail`.++### Provider Management++```bash+omniroute providers available # OmniRoute provider catalog+omniroute providers available --search openai # Filter catalog by id/name/alias/category+omniroute providers available --category api-key # Filter by category (api-key, oauth, free, ...)+omniroute providers available --json # Machine-readable JSON++omniroute providers list # Configured provider connections+omniroute providers list --json++omniroute providers test <id|name> # Test one configured connection+omniroute providers test-all # Test every active connection+omniroute providers validate # Local-only structural validation+```++> `providers available` reads the OmniRoute catalog; `providers list/test/test-all/validate`+> read the local SQLite database directly and do not require the server to be running.++### Recovery & Reset++```bash+omniroute reset-password # Reset the admin password (legacy alias still works)+omniroute reset-encrypted-columns # Show warning + dry-run for encrypted credential reset+omniroute reset-encrypted-columns --force # Actually null out encrypted credentials in SQLite+```++### Other subcommands++These assume a running OmniRoute server, unless noted otherwise:++```bash+omniroute status # Comprehensive runtime status+omniroute logs # Stream request logs (--json, --search, --follow)+omniroute config show # Display current configuration++omniroute provider list # List available providers (alias of providers list)+omniroute provider add # Register OmniRoute as a provider on a tool+omniroute keys add | list | remove # Manage API keys+omniroute models [provider] # List models (--json, --search)+omniroute combo list | switch | create | delete++omniroute backup # Snapshot config + DB+omniroute restore # Restore from a previous snapshot++omniroute health # Detailed health (breakers, cache, memory)+omniroute quota # Provider quota usage+omniroute cache # Cache status+omniroute cache clear # Clear semantic + signature caches++omniroute mcp status | restart # MCP server status / restart+omniroute a2a status | card # A2A server status / agent card++omniroute tunnel list | create | stop # Manage tunnels (cloudflare/tailscale/ngrok)+omniroute env show | get <k> | set <k> <v> # Inspect / set env vars (temporary)++omniroute test # Provider connectivity smoke test+omniroute update # Check for updates+omniroute completion # Generate shell completion+```++### Common flags++| Flag | Description |+| ------------------- | ------------------------------------------------------ |+| `--no-open` | Don't auto-open the browser on start |+| `--port <n>` | Override the API port (default 20128) |+| `--mcp` | Run as MCP server over stdio (for IDEs) |+| `--non-interactive` | CI mode (no prompts; reads from env/flags) |+| `--json` | Machine-readable JSON output (doctor, providers, etc.) |+| `--help`, `-h` | Show command-specific help |+| `--version`, `-v` | Print the installed version |++---++## Available API Endpoints++| Endpoint | Description | Use For |+| -------------------------- | ----------------------------- | --------------------------- |+| `/v1/chat/completions` | Standard chat (all providers) | All modern tools |+| `/v1/responses` | Responses API (OpenAI format) | Codex, agentic workflows |+| `/v1/completions` | Legacy text completions | Older tools using `prompt:` |+| `/v1/embeddings` | Text embeddings | RAG, search |+| `/v1/images/generations` | Image generation | GPT-Image, Flux, etc. |+| `/v1/audio/speech` | Text-to-speech | ElevenLabs, OpenAI TTS |+| `/v1/audio/transcriptions` | Speech-to-text | Deepgram, AssemblyAI |++Ready-to-paste examples with a tokenized OmniRoute URL:++```txt+Token example: sk-a3ab3c080beaee3a-69f4a4-070d71af++Standard OpenAI base: http://localhost:20128/v1+VS Code models: http://localhost:20128/api/v1/vscode/sk-a3ab3c080beaee3a-69f4a4-070d71af/models+VS Code chat: http://localhost:20128/api/v1/vscode/sk-a3ab3c080beaee3a-69f4a4-070d71af/chat/completions+VS Code responses: http://localhost:20128/api/v1/vscode/sk-a3ab3c080beaee3a-69f4a4-070d71af/responses+Ollama tags: http://localhost:20128/api/v1/vscode/sk-a3ab3c080beaee3a-69f4a4-070d71af/api/tags+Ollama chat: http://localhost:20128/api/v1/vscode/sk-a3ab3c080beaee3a-69f4a4-070d71af/api/chat+```+---## Troubleshootingdiff --git a/docs/reference/FREE_TIERS.md b/docs/reference/FREE_TIERS.mdindex a5efc566b0..69dde3c47c 100644--- a/docs/reference/FREE_TIERS.md+++ b/docs/reference/FREE_TIERS.md@@ -51,7 +51,6 @@ Biggest **documented** contributors: `mistral` 1.00B, `longcat` 150M, `cloudflar| `ai21` | ToS §4.2/§8.2 prohibits sublicensing or distributing API access to third parties; §3.3 restricts trial/evaluation products to "internal evaluation on… || `amazon-q` | Product is discontinued for new signups; existing users are subject to AWS Customer Agreement which governs use of managed services — self-hosted pro… || `blackbox` | ToS explicitly prohibits sublicensing, reselling, making the service available to third parties, and building derivative services — a self-hosted per… |-| `completions` | No published ToS found (404 on /terms, /faq, /docs). The service proxies Anthropic/OpenAI/Google APIs without authorization, violating those upstream… || `coze` | Coze ToS explicitly restricts use to "personal and non-commercial use" and prohibits renting, distributing, sublicensing, or reselling the service; a… || `duckduckgo-web` | Duck.ai ToS (duckduckgo.com/duckai/privacy-terms) explicitly prohibits "automated querying and developing or offering AI services" and circumventing … || `featherless-ai` | Individual plans explicitly restricted to "interactive use or proto-typing and experimentation by the purchaser" — inference resale and proxy use req… |@@ -201,7 +200,6 @@ Biggest **documented** contributors: `mistral` 1.00B, `longcat` 150M, `cloudflar| `bytez` | aggregator | recurring-credit | — | med | ambiguous | Bytez offers $1 in free credits that refresh every 4 weeks (credits expire if unused within the cycle). Free tier is li… || `chutes` | aggregator | discontinued | — | high | unknown | The free Early Access program (200 requests/day) was officially discontinued on March 15, 2026. Chutes.ai now operates … || `comfyui` | image | keyless-unlimited | — | high | ok | ComfyUI is a fully open-source (GPL-3.0), self-hosted diffusion model interface that runs entirely on local hardware wi… |-| `completions` | aggregator | keyless-unlimited | — | med | caution | Completions.me claims to offer completely free, unlimited access to Claude Opus 4.6, GPT-5.2, Gemini 3.1 Pro, and 15+ m… || `coze` | aggregator | recurring-daily | — | med | caution | Coze's free plan provides 10 message credits per day — a platform-level unit (not raw LLM tokens) where each model call… || `deepinfra` | aggregator | one-time-trial-credit | — | med | caution | DeepInfra is a pay-as-you-go inference provider that explicitly requires a credit card or prepayment to use services; a… || `deepseek` | llm-chat | one-time-trial-credit | — | high | caution | DeepSeek offers a one-time signup credit of 5 million tokens (no credit card required) valid for 30 days from account c… |@@ -281,7 +279,6 @@ Biggest **documented** contributors: `mistral` 1.00B, `longcat` 150M, `cloudflar- **`byteplus`** — Our catalog shipped "(none)" but BytePlus ModelArk does have a free tier: a one-time trial credit of 500k tokens per LLM model for new accounts. The catalog underreports this.- **`cerebras`** — TPM appears tightened from 60K to 30K on current documented models (gpt-oss-120b, zai-glm-4.7). RPM of 5 is now explicitly documented (was not in our shipped note). Daily token cap of 1M/day is uncha…- **`chutes`** — The shipped freeNote says "Free tier available" but as of March 15, 2026, the free tier has been officially discontinued. The catalog note is stale and should be updated to reflect that there is no r…-- **`completions`** — Our shipped freeNote ("Free unlimited access to Claude, GPT, Gemini — no rate limits") still matches the site's self-described claims. However, the service is a legally dubious, short-lived aggregato…- **`coze`** — The shipped note "Free ByteDance agent platform" is directionally accurate but omits that the free tier is now tightly credit-capped (10 credits/day ≈ 5–100 messages depending on model), a constraint…- **`deepinfra`** — Our shipped freeNote says "Free signup credits for API testing" — this appears stale. The official pricing page now requires card/prepayment with no documented general free signup credit. The free ti…- **`deepseek`** — Our shipped note says "5M free tokens on signup - no credit card required" — this is still accurate for the one-time grant, but importantly the credits expire after 30 days (not mentioned in the ship…diff --git a/docs/reference/PROVIDER_REFERENCE.md b/docs/reference/PROVIDER_REFERENCE.mdindex a1f5c81146..246e05ce37 100644--- a/docs/reference/PROVIDER_REFERENCE.md+++ b/docs/reference/PROVIDER_REFERENCE.md@@ -1,16 +1,16 @@---title: "Provider Reference"-version: 3.8.11-lastUpdated: 2026-06-05+version: 3.8.12+lastUpdated: 2026-06-06---# Provider Reference> **Auto-generated** from `src/shared/constants/providers.ts` — do not edit by hand.> Regenerate with: `npm run gen:provider-reference`-> **Last generated:** 2026-06-05+> **Last generated:** 2026-06-06-Total providers: **224**. See category breakdown below.+Total providers: **223**. See category breakdown below.## Categories@@ -80,7 +80,7 @@ Use the dashboard at `/dashboard/providers` to enable, configure, and test each| `v0-vercel-web` | `v0` | v0 Vercel Web (Code Gen) | Web cookie | [link](https://v0.dev) | Paste your session cookie from v0.dev (DevTools → Application → Cookies) || `venice-web` | `ven` | Venice Web (Privacy) | Web cookie | [link](https://venice.ai) | Paste your session cookie from venice.ai (DevTools → Application → Cookies) |-## API Key Providers (paid / paid-with-free-credits) (152)+## API Key Providers (paid / paid-with-free-credits) (151)| ID | Alias | Name | Tags | Website | Notes ||----|-------|------|------|---------|-------|@@ -114,7 +114,6 @@ Use the dashboard at `/dashboard/providers` to enable, configure, and test each| `codestral` | `codestral` | Codestral | API key | [link](https://mistral.ai) | — || `cohere` | `cohere` | Cohere | API key | [link](https://cohere.com) | Free Trial: 1,000 API calls/month for testing, no credit card required || `command-code` | `cmd` | Command Code | API key | [link](https://commandcode.ai/) | Use a Command Code API key. Requests are sent to Command Code's /alpha/generate endpoint. |-| `completions` | `cpl` | Completions.me | API key | [link](https://completions.me) | Free unlimited access to Claude, GPT, Gemini — no credit card, no rate limits || `coze` | `coze` | Coze | API key | [link](https://coze.com) | Get API key at coze.com/open/api || `crof` | `crof` | CrofAI | API key | [link](https://crof.ai) | — || `databricks` | `databricks` | Databricks | API key, enterprise | [link](https://www.databricks.com) | — |diff --git a/docs/reference/openapi.yaml b/docs/reference/openapi.yamlindex 21aeb4689b..2fdccc1bd8 100644--- a/docs/reference/openapi.yaml+++ b/docs/reference/openapi.yaml@@ -1,7 +1,7 @@openapi: 3.1.0info:title: OmniRoute API- version: 3.8.12+ version: 3.8.13description: |OmniRoute is a local-first AI API proxy router. It provides an OpenAI-compatibleendpoint that routes requests to multiple AI providers with load balancing,diff --git a/electron/loginManager.js b/electron/loginManager.jsnew file mode 100644index 0000000000..0e0bb2d2f1--- /dev/null+++ b/electron/loginManager.js@@ -0,0 +1,386 @@+/**+ * LoginManager — Electron BrowserWindow-based web login for cookie providers+ *+ * Opens a native Electron window navigated to the provider's login page.+ * Polls the session cookie store for target cookies after login completes.+ *+ * Events:+ * "status" — { status: string, message: string, providerId: string }+ * status values: starting, navigating, waiting, polling, complete, error, cancelled+ */++const { BrowserWindow, session } = require("electron");+const { EventEmitter } = require("events");+const path = require("path");++// In production, the tokenExtractionConfig is bundled under open-sse/services/.+// We resolve relative to the Electron resources path.+let TOKEN_EXTRACTION_CONFIGS = null;+function getConfigs() {+ if (TOKEN_EXTRACTION_CONFIGS) return TOKEN_EXTRACTION_CONFIGS;+ try {+ const mod = require("../open-sse/services/tokenExtractionConfig");+ TOKEN_EXTRACTION_CONFIGS = mod.TOKEN_EXTRACTION_CONFIGS;+ } catch {+ // Fallback: try from app resources+ try {+ const mod = require("./open-sse/services/tokenExtractionConfig");+ TOKEN_EXTRACTION_CONFIGS = mod.TOKEN_EXTRACTION_CONFIGS;+ } catch {}+ }+ return TOKEN_EXTRACTION_CONFIGS;+}++class LoginManager extends EventEmitter {+ constructor() {+ super();+ this.window = null;+ this.activeProviderId = null;+ this.resolvePromise = null;+ this.rejectPromise = null;+ this.timeoutId = null;+ this.isCompleted = false;+ this.pollIntervalId = null;+ this.loginSession = null;+ }++ /**+ * Start a login flow for a web-cookie provider.+ * @param {string} providerId - e.g. "claude-web", "chatgpt-web"+ * @param {object} [options]+ * @param {number} [options.timeout] - Total timeout in ms (default: config or 300s)+ * @returns {Promise<{success: boolean, credentials?: Record<string, string>, error?: string}>}+ */+ startLogin(providerId, options = {}) {+ const configs = getConfigs();+ if (!configs) {+ return Promise.resolve({+ success: false,+ error: "tokenExtractionConfig module not found",+ });+ }++ const extractionConfig = configs.get(providerId);+ if (!extractionConfig) {+ return Promise.resolve({+ success: false,+ error: `No extraction config for provider: ${providerId}`,+ });+ }++ if (this.activeProviderId) {+ return Promise.resolve({+ success: false,+ error: "A login process is already in progress",+ });+ }++ this.activeProviderId = providerId;+ this.isCompleted = false;++ const timeout = options.timeout || extractionConfig.pollingConfig.timeout || 300_000;+ const minLoginTime = extractionConfig.pollingConfig.minLoginTime || 5000;+ const pollInterval = extractionConfig.pollingConfig.pollInterval || 1000;++ return new Promise((resolve, reject) => {+ this.resolvePromise = resolve;+ this.rejectPromise = reject;++ this.emit("status", {+ providerId,+ status: "starting",+ message: `Opening ${extractionConfig.displayName} login...`,+ });++ try {+ this._openLoginWindow(providerId, extractionConfig, timeout, minLoginTime, pollInterval);+ } catch (err) {+ this._cleanup();+ this.emit("status", {+ providerId,+ status: "error",+ message: `Failed to open window: ${err.message}`,+ });+ resolve({ success: false, error: err.message });+ }+ });+ }++ /**+ * Open the Electron BrowserWindow for login+ */+ _openLoginWindow(providerId, config, timeout, minLoginTime, pollInterval) {+ this.window = new BrowserWindow({+ width: 1000,+ height: 750,+ title: `Login - ${config.displayName}`,+ webPreferences: {+ contextIsolation: true,+ nodeIntegration: false,+ session: session.fromPartition(`login-${providerId}-${Date.now()}`),+ },+ show: true,+ autoHideMenuBar: true,+ });++ const winSession = this.window.webContents.session;++ // Track navigation for success URL detection+ let navigatedToLogin = false;+ const startTime = Date.now();++ this.window.webContents.on("did-navigate", (_event, url) => {+ if (this.isCompleted) return;++ try {+ const parsedUrl = new URL(url);+ // Check if we've navigated away from the login page (successful login)+ if (navigatedToLogin && config.successUrlPattern) {+ if (config.successUrlPattern.test(url)) {+ this.emit("status", {+ providerId,+ status: "detected",+ message: "Login page redirect detected — extracting cookies...",+ });+ }+ }+ if (!navigatedToLogin) {+ navigatedToLogin = true;+ }++ this.emit("status", {+ providerId,+ status: "navigating",+ message: `Navigated to ${parsedUrl.hostname}`,+ });+ } catch {+ // ignore bad URLs+ }+ });++ // Load the login page+ this.emit("status", {+ providerId,+ status: "navigating",+ message: `Loading ${config.loginUrl}...`,+ });+ this.window.loadURL(config.loginUrl);++ // Show window when ready+ this.window.once("ready-to-show", () => {+ this.window.show();+ });++ // Handle window close by user+ this.window.on("closed", () => {+ if (!this.isCompleted) {+ this._cleanup();+ this.emit("status", {+ providerId,+ status: "cancelled",+ message: "Login window closed by user",+ });+ if (this.resolvePromise) {+ this.resolvePromise({ success: false, error: "Login window closed" });+ }+ }+ });++ // Start polling for cookies after minLoginTime has elapsed+ this.timeoutId = setTimeout(() => {+ if (this.isCompleted) return;+ this._startPolling(providerId, config, winSession, pollInterval, startTime, minLoginTime);+ }, minLoginTime);++ // Overall timeout+ this._timeoutTimer = setTimeout(() => {+ if (!this.isCompleted) {+ this._cleanup();+ this.emit("status", {+ providerId,+ status: "error",+ message: "Login timed out",+ });+ if (this.resolvePromise) {+ this.resolvePromise({ success: false, error: "Login timed out" });+ }+ }+ }, timeout);+ }++ /**+ * Poll the Electron session cookie store for the target cookies+ */+ _startPolling(providerId, config, winSession, pollInterval, startTime, minLoginTime) {+ const maxPolls = Math.floor(config.pollingConfig.timeout / pollInterval);+ let pollCount = 0;++ const poll = () => {+ if (this.isCompleted) return;+ pollCount++;++ // Emit progress every 30 polls+ if (pollCount % 30 === 0) {+ const elapsed = Math.round((Date.now() - startTime) / 60000);+ this.emit("status", {+ providerId,+ status: "waiting",+ message: `Waiting for login... (${elapsed}m)`,+ });+ }++ winSession.cookies+ .get({})+ .then((cookies) => {+ if (this.isCompleted) return;++ const tokenSources = config.tokenSources;+ const credentials = {};++ // Collect all cookie-based sources+ const cookieSources = tokenSources.filter((s) => s.type === "cookie");+ for (const source of cookieSources) {+ const domain = source.domain || undefined;+ const matched = cookies.find(+ (c) => c.name === source.name && (!domain || c.domain.includes(domain.replace(/^\./, "")))+ );+ if (matched) {+ credentials[source.name] = matched.value;+ }+ }++ // Check localStorage-based tokens via executeJavaScript+ const storageSources = tokenSources.filter(+ (s) => s.type === "localStorage" || s.type === "sessionStorage"+ );++ if (storageSources.length > 0 && this.window && !this.window.isDestroyed()) {+ // Execute JS to extract all localStorage/sessionStorage tokens+ const storageType = storageSources[0].type === "localStorage" ? "localStorage" : "sessionStorage";+ const keys = storageSources.map((s) => s.key);+ const js = `(() => {+ const res = {};+ ${JSON.stringify(keys)}.forEach(k => {+ try { res[k] = ${storageType}.getItem(k); } catch {}+ });+ return res;+ })()`;++ this.window.webContents+ .executeJavaScript(js)+ .then((values) => {+ if (values && typeof values === "object") {+ Object.assign(credentials, values);+ }+ this._checkCredentials(providerId, credentials, cookieSources, storageSources, poll, pollInterval);+ })+ .catch(() => {+ this._checkCredentials(providerId, credentials, cookieSources, storageSources, poll, pollInterval);+ });+ } else {+ this._checkCredentials(providerId, credentials, cookieSources, storageSources, poll, pollInterval);+ }+ })+ .catch(() => {+ if (!this.isCompleted) {+ this.pollIntervalId = setTimeout(poll, pollInterval);+ }+ });+ };++ // Start first poll+ this.pollIntervalId = setTimeout(poll, 0);+ }++ /**+ * Check if we have all required credentials, otherwise continue polling+ */+ _checkCredentials(providerId, credentials, cookieSources, storageSources, poll, pollInterval) {+ if (this.isCompleted) return;++ // Collect the required source names/keys+ const requiredKeys = [+ ...cookieSources.map((s) => s.name),+ ...storageSources.map((s) => s.key),+ ];+ const foundKeys = Object.keys(credentials);+ const allFound = requiredKeys.every((k) => foundKeys.includes(k));++ if (allFound && foundKeys.length > 0) {+ // Success — all credentials extracted+ this._completeLogin(providerId, foundKeys.reduce((acc, k) => {+ acc[k] = credentials[k];+ return acc;+ }, {}));+ } else if (!this.isCompleted) {+ // Continue polling using the configured interval+ this.pollIntervalId = setTimeout(poll, pollInterval);+ }+ }++ /**+ * Complete the login flow successfully+ */+ _completeLogin(providerId, credentials) {+ this._cleanup();+ this.emit("status", {+ providerId,+ status: "complete",+ message: "Credentials extracted successfully",+ });+ if (this.resolvePromise) {+ this.resolvePromise({ success: true, credentials });+ }+ }++ /**+ * Cancel the current login flow+ */+ cancel() {+ if (!this.activeProviderId) return;+ this._cleanup();+ this.emit("status", {+ providerId: this.activeProviderId,+ status: "cancelled",+ message: "Login cancelled",+ });+ if (this.resolvePromise) {+ this.resolvePromise({ success: false, error: "Login cancelled" });+ }+ }++ /**+ * Clean up all resources+ */+ _cleanup() {+ this.isCompleted = true;+ this.activeProviderId = null;++ if (this.timeoutId) {+ clearTimeout(this.timeoutId);+ this.timeoutId = null;+ }+ if (this._timeoutTimer) {+ clearTimeout(this._timeoutTimer);+ this._timeoutTimer = null;+ }+ if (this.pollIntervalId) {+ clearTimeout(this.pollIntervalId);+ this.pollIntervalId = null;+ }+ if (this.window && !this.window.isDestroyed()) {+ this.window.close();+ }+ this.window = null;+ this.loginSession = null;+ }++ /**+ * Get the active provider ID, if any+ */+ getActiveProvider() {+ return this.activeProviderId;+ }+}++module.exports = { LoginManager, loginManager: new LoginManager() };diff --git a/electron/main.js b/electron/main.jsindex ddcaa25bb6..ee0e22a783 100644--- a/electron/main.js+++ b/electron/main.js@@ -33,6 +33,7 @@ const { spawn } = require("child_process");const fs = require("fs");const { autoUpdater } = require("electron-updater");const { hasEncryptedCredentials } = require("./sqlite-inspection");+const { loginManager } = require("./loginManager");// ── Single Instance Lock ───────────────────────────────────const gotTheLock = app.requestSingleInstanceLock();@@ -799,6 +800,48 @@ function setupIpcHandlers() {ipcMain.handle("get-app-version", () => app.getVersion());+ // ── Web-Cookie Login IPC Handlers ──────────────────────────+ // Forward login status events to the renderer. Registered ONCE here — never+ // inside the login:start handler, which would attach a fresh listener (and+ // duplicate every subsequent status event) on each invocation.+ loginManager.on("status", (status) => {+ sendToRenderer("login:status", status);+ });++ ipcMain.handle("login:start", async (_event, providerId, options) => {+ const result = await loginManager.startLogin(providerId, options);++ // Persist extracted credentials+ if (result.success && result.credentials) {+ try {+ // Store as JSON blob under the provider ID+ const { persistSecret: ps } = require("../src/lib/db/secrets");+ if (typeof ps === "function") {+ ps(providerId, JSON.stringify(result.credentials));+ }+ sendToRenderer("login:status", {+ providerId,+ status: "persisted",+ message: "Credentials saved",+ });+ } catch (err) {+ console.error("[Electron] Failed to persist credentials:", err);+ return { success: false, error: "Extracted but failed to save credentials" };+ }+ }++ return result;+ });++ ipcMain.handle("login:cancel", async () => {+ loginManager.cancel();+ return { success: true };+ });++ ipcMain.handle("login:status", async () => {+ return { active: loginManager.getActiveProvider() !== null };+ });+// Autostart management handlersipcMain.handle("get-autostart-status", () => {if (process.platform === "linux") {diff --git a/electron/package-lock.json b/electron/package-lock.jsonindex a1909685d1..6926f65b66 100644--- a/electron/package-lock.json+++ b/electron/package-lock.json@@ -1,12 +1,12 @@{"name": "omniroute-desktop",- "version": "3.8.12",+ "version": "3.8.13","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "omniroute-desktop",- "version": "3.8.12",+ "version": "3.8.13","license": "MIT","dependencies": {"electron-updater": "^6.8.8"diff --git a/electron/package.json b/electron/package.jsonindex bc0fb0f3b1..afac7c5ccc 100644--- a/electron/package.json+++ b/electron/package.json@@ -1,6 +1,6 @@{"name": "omniroute-desktop",- "version": "3.8.12",+ "version": "3.8.13","description": "OmniRoute Desktop Application","main": "main.js","author": {diff --git a/electron/preload.js b/electron/preload.jsindex 1979c2ef79..0eabaa2748 100644--- a/electron/preload.js+++ b/electron/preload.js@@ -103,9 +103,12 @@ const VALID_CHANNELS = {"get-autostart-status","enable-autostart","disable-autostart",+ "login:start",+ "login:cancel",+ "login:status",],send: ["window-minimize", "window-maximize", "window-close"],- receive: ["server-status", "port-changed", "update-status"],+ receive: ["server-status", "port-changed", "update-status", "login:status"],};// ── Fix #16: Generic IPC wrappers ──────────────────────────@@ -161,6 +164,12 @@ contextBridge.exposeInMainWorld("electronAPI", {onPortChanged: (callback) => safeOn("port-changed", callback),onUpdateStatus: (callback) => safeOn("update-status", callback),+ // ── Web-Cookie Login ──────────────────────────────────────+ startLogin: (providerId, options) => safeInvoke("login:start", providerId, options),+ cancelLogin: () => safeInvoke("login:cancel"),+ getLoginStatus: () => safeInvoke("login:status"),+ onLoginStatus: (callback) => safeOn("login:status", callback),+// ── Static Properties ────────────────────────────────────isElectron: true,platform: process.platform,diff --git a/eslint.config.mjs b/eslint.config.mjsindex 3a29e83b5c..3a99309a10 100644--- a/eslint.config.mjs+++ b/eslint.config.mjs@@ -72,6 +72,10 @@ const eslintConfig = [// Dependencies"node_modules/**",".worktrees/**",+ // Nested git worktrees created by review/resolve skills live under+ // .claude/ (gitignored). They hold other sessions' in-progress work and+ // their files move mid-scan, so never lint them from the main checkout.+ ".claude/**",".omnivscodeagent/**",// VS Code extension and its large test fixtures"vscode-extension/**",diff --git a/open-sse/config/antigravityModelAliases.ts b/open-sse/config/antigravityModelAliases.tsindex f15b44d331..970fd44ac2 100644--- a/open-sse/config/antigravityModelAliases.ts+++ b/open-sse/config/antigravityModelAliases.ts@@ -1,4 +1,27 @@export const ANTIGRAVITY_PUBLIC_MODELS = Object.freeze([+ // Claude (Antigravity backend). The `agy` provider already ships these from the live+ // :fetchAvailableModels probe (see agyModels.ts) and discussion #3184 confirmed they+ // are user-callable through the `antigravity` OAuth provider too — same backend.+ // `antigravity/claude-opus-4-6-thinking` and `antigravity/claude-sonnet-4-6` both work.+ // They are upstream IDs, so no alias remapping is required.+ {+ id: "claude-opus-4-6-thinking",+ name: "Claude Opus 4.6 (Thinking)",+ contextLength: 200000,+ maxOutputTokens: 65536,+ supportsReasoning: true,+ supportsVision: true,+ toolCalling: true,+ },+ {+ id: "claude-sonnet-4-6",+ name: "Claude Sonnet 4.6 (Thinking)",+ contextLength: 200000,+ maxOutputTokens: 65536,+ supportsReasoning: true,+ supportsVision: true,+ toolCalling: true,+ },// Gemini 3.5 Flash — flagship model in Antigravity 2.0 (May 2026){id: "gemini-3.5-flash-preview",@@ -27,6 +50,27 @@ export const ANTIGRAVITY_PUBLIC_MODELS = Object.freeze([supportsVision: true,toolCalling: true,},+ // Gemini 3.1 Pro budget tiers — agy already ships these; #3184 confirmed they work via+ // the antigravity OAuth provider. The -high/-low suffix is aliased to the plain+ // gemini-3.1-pro upstream id (see ANTIGRAVITY_MODEL_ALIASES / #3229).+ {+ id: "gemini-3.1-pro-high",+ name: "Gemini 3.1 Pro (High)",+ contextLength: 1048576,+ maxOutputTokens: 65535,+ supportsReasoning: true,+ supportsVision: true,+ toolCalling: true,+ },+ {+ id: "gemini-3.1-pro-low",+ name: "Gemini 3.1 Pro (Low)",+ contextLength: 1048576,+ maxOutputTokens: 65535,+ supportsReasoning: true,+ supportsVision: true,+ toolCalling: true,+ },{id: "gemini-3-flash-preview",name: "Gemini 3 Flash",@@ -36,6 +80,24 @@ export const ANTIGRAVITY_PUBLIC_MODELS = Object.freeze([supportsVision: true,toolCalling: true,},+ // Gemini 3.5 Flash budget tiers — agy ships these as exact upstream ids; #3184 verified+ // they work via the antigravity OAuth provider (no alias remapping required).+ {+ id: "gemini-3.5-flash-low",+ name: "Gemini 3.5 Flash (Low)",+ contextLength: 1048576,+ maxOutputTokens: 65536,+ supportsVision: true,+ toolCalling: true,+ },+ {+ id: "gemini-3.5-flash-extra-low",+ name: "Gemini 3.5 Flash (Extra Low)",+ contextLength: 1048576,+ maxOutputTokens: 65536,+ supportsVision: true,+ toolCalling: true,+ },{id: "gemini-3.1-flash-lite",name: "Gemini 3.1 Flash Lite",@@ -111,8 +173,11 @@ export const ANTIGRAVITY_MODEL_ALIASES = Object.freeze({"gemini-3-flash-preview": "gemini-3-flash","gemini-3-pro-image-preview": "gemini-3-pro-image","gemini-2.5-computer-use-preview-10-2025": "rev19-uic3-1p",- // Deprecated: Claude models were removed from Antigravity 2.0 (May 2026).- // These aliases are kept for backward compatibility but will 404 on new requests.+ // Legacy Claude display ids → current upstream ids. NOTE: an earlier comment here+ // assumed Claude was removed from Antigravity 2.0 and would 404; discussion #3184+ // disproved that — the Antigravity OAuth backend still serves claude-opus-4-6-thinking+ // and claude-sonnet-4-6 (now listed in ANTIGRAVITY_PUBLIC_MODELS above). These aliases+ // remap the old gemini-claude-* ids to the live upstream ids."gemini-claude-sonnet-4-5": "claude-sonnet-4-6","gemini-claude-sonnet-4-5-thinking": "claude-sonnet-4-6","gemini-claude-opus-4-5-thinking": "claude-opus-4-6-thinking",diff --git a/open-sse/config/freeModelCatalog.data.ts b/open-sse/config/freeModelCatalog.data.tsindex c0a825cafb..adba8f6bba 100644--- a/open-sse/config/freeModelCatalog.data.ts+++ b/open-sse/config/freeModelCatalog.data.ts@@ -170,14 +170,6 @@ export const FREE_MODEL_BUDGETS: FreeModelBudget[] = [{ provider: "bazaarlink", modelId: "mistral-medium-3.1", displayName: "Mistral Medium 3.1", monthlyTokens: 3600000, creditTokens: 0, freeType: "recurring-daily", poolKey: "bazaarlink", tos: "caution" },{ provider: "bazaarlink", modelId: "mistral-small-2603", displayName: "Mistral Small 4", monthlyTokens: 3600000, creditTokens: 0, freeType: "recurring-daily", poolKey: "bazaarlink", tos: "caution" },{ provider: "bazaarlink", modelId: "nemotron-3-super-120b-a12b", displayName: "Nemotron 3 Super", monthlyTokens: 3600000, creditTokens: 0, freeType: "recurring-daily", poolKey: "bazaarlink", tos: "caution" },- { provider: "completions", modelId: "claude-opus-4.6", displayName: "Claude Opus 4.6", monthlyTokens: 0, creditTokens: 0, freeType: "keyless", poolKey: "completions", tos: "avoid" },- { provider: "completions", modelId: "claude-sonnet-4.6", displayName: "Claude Sonnet 4.6", monthlyTokens: 0, creditTokens: 0, freeType: "keyless", poolKey: "completions", tos: "avoid" },- { provider: "completions", modelId: "claude-haiku-4.5", displayName: "Claude Haiku 4.5", monthlyTokens: 0, creditTokens: 0, freeType: "keyless", poolKey: "completions", tos: "avoid" },- { provider: "completions", modelId: "gpt-5.2", displayName: "GPT-5.2", monthlyTokens: 0, creditTokens: 0, freeType: "keyless", poolKey: "completions", tos: "avoid" },- { provider: "completions", modelId: "gpt-5-mini", displayName: "GPT-5 Mini", monthlyTokens: 0, creditTokens: 0, freeType: "keyless", poolKey: "completions", tos: "avoid" },- { provider: "completions", modelId: "gpt-4.1", displayName: "GPT-4.1", monthlyTokens: 0, creditTokens: 0, freeType: "keyless", poolKey: "completions", tos: "avoid" },- { provider: "completions", modelId: "gemini-3.1-pro-preview", displayName: "Gemini 3.1 Pro", monthlyTokens: 0, creditTokens: 0, freeType: "keyless", poolKey: "completions", tos: "avoid" },- { provider: "completions", modelId: "gemini-3-flash-preview", displayName: "Gemini 3 Flash", monthlyTokens: 0, creditTokens: 0, freeType: "keyless", poolKey: "completions", tos: "avoid" },{ provider: "mistral", modelId: "mistral-large-latest", displayName: "Mistral Large 3", monthlyTokens: 1000000000, creditTokens: 0, freeType: "recurring-monthly", poolKey: "mistral", tos: "caution" },{ provider: "mistral", modelId: "mistral-medium-3-5", displayName: "Mistral Medium 3.5", monthlyTokens: 1000000000, creditTokens: 0, freeType: "recurring-monthly", poolKey: "mistral", tos: "caution" },{ provider: "mistral", modelId: "mistral-small-latest", displayName: "Mistral Small 4", monthlyTokens: 1000000000, creditTokens: 0, freeType: "recurring-monthly", poolKey: "mistral", tos: "caution" },diff --git a/open-sse/config/providerRegistry.ts b/open-sse/config/providerRegistry.tsindex a3150d1ba8..bef0b02233 100644--- a/open-sse/config/providerRegistry.ts+++ b/open-sse/config/providerRegistry.ts@@ -207,6 +207,16 @@ const GPT_5_5_CODEX_CAPABILITIES = {contextLength: GPT_5_5_CONTEXT_LENGTH,} as const;+const GPT_5_4_CODEX_CAPABILITIES = {+ targetFormat: "openai-responses",+ toolCalling: true,+ supportsReasoning: true,+ supportsVision: true,+ supportsXHighEffort: true,+ contextLength: 200000,+ maxOutputTokens: 128000,+} as const;+const CHAT_OPENAI_COMPAT_MODELS: Record<string, RegistryModel[]> = {deepinfra: buildModels(["anthropic/claude-4-opus",@@ -866,9 +876,27 @@ const _REGISTRY_EAGER: Record<string, RegistryEntry> = {{id: "gpt-5.4",name: "GPT 5.4",- targetFormat: "openai-responses",- supportsReasoning: true,- supportsXHighEffort: true,+ ...GPT_5_4_CODEX_CAPABILITIES,+ },+ {+ id: "gpt-5.4-xhigh",+ name: "GPT 5.4 (xHigh)",+ ...GPT_5_4_CODEX_CAPABILITIES,+ },+ {+ id: "gpt-5.4-high",+ name: "GPT 5.4 (High)",+ ...GPT_5_4_CODEX_CAPABILITIES,+ },+ {+ id: "gpt-5.4-medium",+ name: "GPT 5.4 (Medium)",+ ...GPT_5_4_CODEX_CAPABILITIES,+ },+ {+ id: "gpt-5.4-low",+ name: "GPT 5.4 (Low)",+ ...GPT_5_4_CODEX_CAPABILITIES,},{ id: "gpt-5.4-mini", name: "GPT 5.4 Mini", targetFormat: "openai-responses" },{ id: "gpt-5.3-codex-spark", name: "GPT 5.3 Codex Spark" },@@ -1007,7 +1035,7 @@ const _REGISTRY_EAGER: Record<string, RegistryEntry> = {{ id: "gpt-5-mini", name: "GPT-5 Mini", targetFormat: "openai-responses" },{ id: "gpt-5.3-codex", name: "GPT-5.3 Codex", targetFormat: "openai-responses" },{ id: "gpt-5.4-mini", name: "GPT-5.4 Mini", targetFormat: "openai-responses" },- { id: "gpt-5.4", name: "GPT-5.4", targetFormat: "openai-responses" },+ { id: "gpt-5.4", name: "GPT-5.4", targetFormat: "openai-responses", supportsXHighEffort: true },{ id: "gpt-5.5", name: "GPT-5.5", ...GPT_5_5_CODEX_CAPABILITIES },{id: "claude-haiku-4.5",@@ -2689,25 +2717,6 @@ const _REGISTRY_EAGER: Record<string, RegistryEntry> = {{ id: "nemotron-3-super-120b-a12b", name: "Nemotron 3 Super" },],},- completions: {- id: "completions",- alias: "cpl",- format: "openai",- executor: "default",- baseUrl: "https://completions.me/api/v1/chat/completions",- authType: "apikey",- authHeader: "bearer",- models: [- { id: "claude-opus-4.6", name: "Claude Opus 4.6" },- { id: "claude-sonnet-4.6", name: "Claude Sonnet 4.6" },- { id: "claude-haiku-4.5", name: "Claude Haiku 4.5" },- { id: "gpt-5.2", name: "GPT-5.2" },- { id: "gpt-5-mini", name: "GPT-5 Mini" },- { id: "gpt-4.1", name: "GPT-4.1" },- { id: "gemini-3.1-pro-preview", name: "Gemini 3.1 Pro" },- { id: "gemini-3-flash-preview", name: "Gemini 3 Flash" },- ],- },xai: {id: "xai",alias: "xai",diff --git a/open-sse/executors/codex.ts b/open-sse/executors/codex.tsindex b31f96be51..93fc326da8 100644--- a/open-sse/executors/codex.ts+++ b/open-sse/executors/codex.ts@@ -1361,6 +1361,17 @@ export class CodexExecutor extends BaseExecutor {delete body.truncation;delete body.background; // Droid CLI sends this but Codex Responses API rejects it+ // Issue #3317: strip client-only fields the Codex Responses API rejects with+ // 400 "Unsupported parameter" — for BOTH the native passthrough (early return+ // below) and the translated path. The chat-completions path already removes+ // these (base.ts prompt_cache_retention #1884; openai-responses translator+ // safety_identifier #2770), but the responses->responses passthrough skips+ // translation. `user` is always rejected by Codex /responses, so it is removed+ // unconditionally here (unlike base.ts, which only drops it when empty).+ delete body.prompt_cache_retention;+ delete body.safety_identifier;+ delete body.user;+// Inject prompt_cache_key for Codex prompt caching.// The official Codex client sets this to conversation_id (a stable UUID per session).// Ref: openai/codex core/src/client.rs line 853:diff --git a/open-sse/executors/theoldllm.ts b/open-sse/executors/theoldllm.tsindex 94ba8d0f7f..a9dfbba9ef 100644--- a/open-sse/executors/theoldllm.ts+++ b/open-sse/executors/theoldllm.ts@@ -407,9 +407,12 @@ export class TheOldLlmExecutor extends BaseExecutor {upstream = await directFetch(token, reqBody, signal);}- const upstreamBody = await upstream.text();+ // Read the body once — a Response body is single-use, so re-reading the+ // same Response throws "Body has already been read" (#3296). Only re-read+ // when a token rejection forces a fresh fetch below.+ let finalBody = await upstream.text();- if (isTokenRejected(upstream.status, upstreamBody)) {+ if (isTokenRejected(upstream.status, finalBody)) {log?.warn?.("THEOLDLLM", `Token rejected (${upstream.status}), refreshing…`);invalidateToken();try {@@ -419,10 +422,9 @@ export class TheOldLlmExecutor extends BaseExecutor {log?.warn?.("THEOLDLLM", "Token refresh failed, retrying with existing token");}upstream = await directFetch(token, reqBody, signal);+ finalBody = await upstream.text();}- const finalBody = await upstream.text();-if (upstream.status === 200 && finalBody) {const payload = stream? finalBodydiff --git a/open-sse/handlers/responseSanitizer.ts b/open-sse/handlers/responseSanitizer.tsindex 43d8005c34..80dec34e6e 100644--- a/open-sse/handlers/responseSanitizer.ts+++ b/open-sse/handlers/responseSanitizer.ts@@ -27,6 +27,8 @@ const ALLOWED_RESPONSES_USAGE_FIELDS = new Set([type JsonRecord = Record<string, unknown>;+export const OMIT_STREAMING_CHUNK_MARKER = "__omniroute_omit_streaming_chunk";+const DEEPSEEK_V4_SANITIZER_MODEL_PATTERN = /deepseek[-/]v4/i;function isDeepSeekV4Model(model: unknown): boolean {@@ -62,9 +64,84 @@ function stripZeroWidthValue(value: unknown): unknown {return value;}+function findBalancedJsonEnd(text: string, startIndex: number): number {+ if (startIndex < 0 || startIndex >= text.length || text[startIndex] !== "{") return -1;++ let depth = 0;+ let inString = false;+ let escaped = false;++ for (let index = startIndex; index < text.length; index += 1) {+ const char = text[index];++ if (inString) {+ if (escaped) {+ escaped = false;+ continue;+ }+ if (char === "\\") {+ escaped = true;+ continue;+ }+ if (char === '"') {+ inString = false;+ }+ continue;+ }++ if (char === '"') {+ inString = true;+ continue;+ }++ if (char === "{") {+ depth += 1;+ continue;+ }++ if (char === "}") {+ depth -= 1;+ if (depth === 0) return index;+ }+ }++ return -1;+}++function stripInternalToolEnvelopeText(content: string): string {+ let sanitized = stripZeroWidthText(content);+ const markerRegex = /to=(?:functions\.[A-Za-z0-9_.-]+|multi_tool_use\.[A-Za-z0-9_.-]+|[A-Za-z_][A-Za-z0-9_]*)/g;++ while (true) {+ const match = markerRegex.exec(sanitized);+ if (!match || match.index < 0) break;++ const searchWindowEnd = Math.min(sanitized.length, match.index + 1200);+ const jsonStart = sanitized.indexOf("{", match.index);+ if (jsonStart < 0 || jsonStart >= searchWindowEnd) {+ sanitized = `${sanitized.slice(0, match.index)}${sanitized.slice(match.index + match[0].length)}`;+ markerRegex.lastIndex = 0;+ continue;+ }++ const jsonEnd = findBalancedJsonEnd(sanitized, jsonStart);+ if (jsonEnd < 0) {+ sanitized = sanitized.slice(0, match.index);+ break;+ }++ const prefix = sanitized.slice(0, match.index).replace(/[ \t]+$/g, "");+ const suffix = sanitized.slice(jsonEnd + 1).replace(/^[ \t]+/g, "");+ sanitized = `${prefix}${suffix}`;+ markerRegex.lastIndex = 0;+ }++ return sanitized.replace(/\n{3,}/g, "\n\n").trim();+}+function parseTextualToolCallContent(content: unknown): { name: string; args: unknown } | null {if (typeof content !== "string") return null;- const normalized = stripZeroWidthText(content);+ const normalized = stripInternalToolEnvelopeText(content);const toolCallIndex = normalized.lastIndexOf("[Tool call:");if (toolCallIndex < 0) return null;const candidate = normalized.slice(toolCallIndex);@@ -93,7 +170,7 @@ function parseTextualToolCallContent(content: unknown): { name: string; args: un}function containsTextualToolCallContent(content: unknown): boolean {- return typeof content === "string" && stripZeroWidthText(content).includes("[Tool call:");+ return typeof content === "string" && stripInternalToolEnvelopeText(content).includes("[Tool call:");}function hasVisibleMessageContent(content: unknown): boolean {@@ -297,7 +374,9 @@ function sanitizeMessage(msg: unknown, isDeepSeekV4 = false): unknown {// Handle content — extract <think> tagsif (typeof msgRecord.content === "string") {- const { content, thinking } = extractThinkingFromContent(msgRecord.content);+ const { content, thinking } = extractThinkingFromContent(+ stripInternalToolEnvelopeText(msgRecord.content)+ );sanitized.content = collapseExcessiveNewlines(content);// Set reasoning_content from <think> tags (if not already set)@@ -520,6 +599,140 @@ function normalizeResponsesId(id: unknown): string {return `resp_${id}`;}+function sanitizeResponsesStreamingOutputItem(item: unknown): JsonRecord | null {+ const itemRecord = toRecord(item);+ if (!itemRecord) return null;++ const type = toString(itemRecord.type) || "message";++ if (type === "message") {+ const role = toString(itemRecord.role) || "assistant";+ const phase = toString(itemRecord.phase);+ if (role === "assistant" && phase === "commentary") {+ return null;+ }++ const content = sanitizeResponsesMessageContent(itemRecord.content).filter((part) => {+ const partRecord = toRecord(part);+ const partPhase = partRecord ? toString(partRecord.phase) : undefined;+ return partPhase !== "commentary";+ });++ if (role === "assistant" && content.length === 0) {+ return null;+ }++ return {+ ...itemRecord,+ type: "message",+ role,+ content,+ };+ }++ if (type === "reasoning") {+ const summary = Array.isArray(itemRecord.summary)+ ? itemRecord.summary+ .map((part) => {+ const partRecord = toRecord(part);+ if (!partRecord) return null;+ return {+ ...partRecord,+ type: toString(partRecord.type) || "summary_text",+ text: collapseExcessiveNewlines(toString(partRecord.text) || ""),+ };+ })+ .filter((part): part is NonNullable<typeof part> => part !== null)+ : [];++ return {+ ...itemRecord,+ type: "reasoning",+ summary,+ };+ }++ if (type === "function_call") {+ return {+ ...itemRecord,+ type: "function_call",+ arguments:+ typeof itemRecord.arguments === "string"+ ? itemRecord.arguments+ : JSON.stringify(itemRecord.arguments || {}),+ };+ }++ if (type === "function_call_output") {+ return {+ ...itemRecord,+ type: "function_call_output",+ output:+ typeof itemRecord.output === "string"+ ? collapseExcessiveNewlines(itemRecord.output)+ : JSON.stringify(itemRecord.output ?? ""),+ };+ }++ return { ...itemRecord };+}++function sanitizeResponsesStreamingOutput(output: unknown): JsonRecord[] {+ if (!Array.isArray(output)) return [];++ return output+ .map((item) => sanitizeResponsesStreamingOutputItem(item))+ .filter((item): item is JsonRecord => item !== null);+}++function sanitizeResponsesStreamingEvent(parsedRecord: JsonRecord): JsonRecord {+ const sanitized: JsonRecord = { ...parsedRecord };+ const eventType = toString(parsedRecord.type) || "";++ if (parsedRecord.item !== undefined) {+ const sanitizedItem = sanitizeResponsesStreamingOutputItem(parsedRecord.item);+ if (sanitizedItem) {+ sanitized.item = sanitizedItem;+ } else {+ delete sanitized.item;+ if (eventType === "response.output_item.added" || eventType === "response.output_item.done") {+ sanitized[OMIT_STREAMING_CHUNK_MARKER] = true;+ }+ }+ }++ if (Array.isArray(parsedRecord.output)) {+ const output = sanitizeResponsesStreamingOutput(parsedRecord.output);+ sanitized.output = output;+ const outputText = extractResponsesOutputText(output);+ if (outputText.length > 0) {+ sanitized.output_text = outputText;+ } else {+ delete sanitized.output_text;+ }+ }++ const responseRecord = toRecord(parsedRecord.response);+ if (responseRecord) {+ const responseOutput = Array.isArray(responseRecord.output)+ ? sanitizeResponsesStreamingOutput(responseRecord.output)+ : undefined;+ const sanitizedResponse: JsonRecord = {+ ...responseRecord,+ ...(responseOutput ? { output: responseOutput } : {}),+ };+ const responseOutputText = responseOutput ? extractResponsesOutputText(responseOutput) : "";+ if (responseOutputText.length > 0) {+ sanitizedResponse.output_text = responseOutputText;+ } else {+ delete sanitizedResponse.output_text;+ }+ sanitized.response = sanitizedResponse;+ }++ return sanitized;+}+function sanitizeResponsesOutput(output: unknown): JsonRecord[] {if (!Array.isArray(output)) return [];@@ -598,7 +811,7 @@ function sanitizeResponsesMessageContent(content: unknown): JsonRecord[] {return [{type: "output_text",- text: collapseExcessiveNewlines(content),+ text: collapseExcessiveNewlines(stripInternalToolEnvelopeText(content)),annotations: [],},];@@ -613,7 +826,7 @@ function sanitizeResponsesMessageContent(content: unknown): JsonRecord[] {if (typeof part === "string") {return {type: "output_text",- text: collapseExcessiveNewlines(part),+ text: collapseExcessiveNewlines(stripInternalToolEnvelopeText(part)),annotations: [],};}@@ -629,7 +842,9 @@ function sanitizeResponsesMessageContent(content: unknown): JsonRecord[] {return {...partRecord,type: "output_text",- text: collapseExcessiveNewlines(toString(partRecord.text) || ""),+ text: collapseExcessiveNewlines(+ stripInternalToolEnvelopeText(toString(partRecord.text) || "")+ ),annotations: Array.isArray(partRecord.annotations) ? partRecord.annotations : [],};}@@ -752,6 +967,11 @@ export function sanitizeStreamingChunk(parsed: unknown): unknown {const parsedRecord = toRecord(parsed);if (!parsedRecord) return parsed;+ const eventType = toString(parsedRecord.type) || "";+ if (eventType.startsWith("response.") || parsedRecord.object === "response") {+ return sanitizeResponsesStreamingEvent(parsedRecord);+ }+// Build sanitized chunkconst sanitized: JsonRecord = {};diff --git a/open-sse/mcp-server/schemas/tools.ts b/open-sse/mcp-server/schemas/tools.tsindex f4f0e71252..1d7065e70e 100644--- a/open-sse/mcp-server/schemas/tools.ts+++ b/open-sse/mcp-server/schemas/tools.ts@@ -370,6 +370,7 @@ export const listModelsCatalogOutput = z.object({provider: z.string(),capabilities: z.array(z.string()),status: z.enum(["available", "degraded", "unavailable"]),+ thinkingEffort: z.string().optional(),pricing: z.object({inputPerMillion: z.number().nullable(),diff --git a/open-sse/mcp-server/server.ts b/open-sse/mcp-server/server.tsindex ba2ee2b976..0418d0c544 100644--- a/open-sse/mcp-server/server.ts+++ b/open-sse/mcp-server/server.ts@@ -91,7 +91,10 @@ import {type McpAccessibilityConfig,} from "../services/compression/engines/mcpAccessibility/constants.ts";import { getDbInstance } from "../../src/lib/db/core.ts";+import { getProviderConnections } from "../../src/lib/db/providers.ts";+import { getCodexRequestDefaults } from "../../src/lib/providers/requestDefaults.ts";import { normalizeQuotaResponse } from "../../src/shared/contracts/quota.ts";+import { AI_PROVIDERS, NOAUTH_PROVIDERS } from "../../src/shared/constants/providers.ts";import { resolveOmniRouteBaseUrl } from "../../src/shared/utils/resolveOmniRouteBaseUrl.ts";// ============ Configuration ============@@ -147,6 +150,28 @@ type TextToolResult = {isError?: boolean;};+type McpCatalogStatus = "available" | "degraded" | "unavailable";++type McpCatalogResponse = {+ models: Array<{+ id: string;+ provider: string;+ capabilities: string[];+ status: McpCatalogStatus;+ thinkingEffort?: string;+ pricing?: unknown;+ }>;+ source: string;+ warning?: string;+};++type ProviderConnectionLike = {+ id?: string;+ provider?: string;+ isActive?: boolean;+ providerSpecificData?: unknown;+};+function toRecord(value: unknown): JsonRecord {return value && typeof value === "object" && !Array.isArray(value) ? (value as JsonRecord) : {};}@@ -214,6 +239,188 @@ async function omniRouteFetch(path: string, options: RequestInit = {}): Promise<return response.json();}+function buildProviderAliasMap(): Record<string, string> {+ const aliasMap: Record<string, string> = {};++ for (const provider of Object.values(AI_PROVIDERS)) {+ if (!provider?.id) continue;+ aliasMap[provider.id] = provider.id;+ if (typeof provider.alias === "string" && provider.alias.length > 0) {+ aliasMap[provider.alias] = provider.id;+ }+ }++ for (const provider of Object.values(NOAUTH_PROVIDERS)) {+ if (!provider?.id) continue;+ aliasMap[provider.id] = provider.id;+ if ("alias" in provider && typeof provider.alias === "string" && provider.alias.length > 0) {+ aliasMap[provider.alias] = provider.id;+ }+ }++ return aliasMap;+}++function normalizeCapability(value: string): string {+ switch (value) {+ case "embeddings":+ return "embedding";+ case "images":+ return "image";+ case "videos":+ return "video";+ case "moderations":+ return "moderation";+ case "chat-completions":+ return "chat";+ default:+ return value;+ }+}++function getCatalogModelCapabilities(model: JsonRecord): string[] {+ if (Array.isArray(model.capabilities) && model.capabilities.length > 0) {+ return toStringArray(model.capabilities, ["chat"]).map(normalizeCapability);+ }++ if (Array.isArray(model.supportedEndpoints) && model.supportedEndpoints.length > 0) {+ return toStringArray(model.supportedEndpoints, ["chat"]).map(normalizeCapability);+ }++ const type = toString(model.type);+ if (type) return [normalizeCapability(type)];++ return ["chat"];+}++function normalizeCatalogStatus(model: JsonRecord, source: string, warning?: string): McpCatalogStatus {+ const explicitStatus = toString(model.status);+ if (explicitStatus === "available" || explicitStatus === "degraded" || explicitStatus === "unavailable") {+ return explicitStatus;+ }++ if (warning || source === "local_catalog") return "degraded";+ return "available";+}++function getConnectionThinkingEffort(connection: ProviderConnectionLike): string | undefined {+ const provider = typeof connection.provider === "string" ? connection.provider : null;+ const providerSpecificData = toRecord(connection.providerSpecificData);++ if (provider === "codex") {+ return getCodexRequestDefaults(providerSpecificData).reasoningEffort || "medium";+ }++ const rawThinkingEffort = toString(providerSpecificData.thinkingEffort);+ return rawThinkingEffort || undefined;+}++function normalizeProviderModelRecord(+ rawModel: unknown,+ fallbackProvider: string,+ source: string,+ warning?: string,+ thinkingEffort?: string+) {+ const model = toRecord(rawModel);+ const id = toString(model.id, "");++ return {+ id,+ provider: toString(model.owned_by, toString(model.provider, fallbackProvider)),+ capabilities: getCatalogModelCapabilities(model),+ status: normalizeCatalogStatus(model, source, warning),+ ...(thinkingEffort ? { thinkingEffort } : {}),+ pricing: model.pricing,+ };+}++export async function getMcpModelsCatalog(+ args: { provider?: string; capability?: string },+ deps: {+ fetchJson?: (path: string) => Promise<unknown>;+ listProviderConnections?: () => Promise<ProviderConnectionLike[]>;+ } = {}+): Promise<McpCatalogResponse> {+ const fetchJson = deps.fetchJson ?? ((path: string) => omniRouteFetch(path));+ const listProviderConnections = deps.listProviderConnections ?? getProviderConnections;+ const aliasMap = buildProviderAliasMap();+ const normalizeProviderId = (value: string) => aliasMap[value] || value;+ const requestedProvider = args.provider ? normalizeProviderId(args.provider) : null;+ const requestedCapability = args.capability ? normalizeCapability(args.capability) : null;++ let connections = await listProviderConnections();+ connections = Array.isArray(connections) ? connections : [];++ const activeConnections = connections.filter((connection) => {+ const provider = typeof connection?.provider === "string" ? normalizeProviderId(connection.provider) : null;+ if (!provider || !connection?.id || connection.isActive === false) return false;+ if (requestedProvider && provider !== requestedProvider) return false;+ return true;+ });++ const requestSpecs = activeConnections.map((connection) => ({+ provider: normalizeProviderId(String(connection.provider)),+ path: `/api/providers/${encodeURIComponent(String(connection.id))}/models?excludeHidden=true`,+ thinkingEffort: getConnectionThinkingEffort(connection),+ }));++ if (requestedProvider && requestSpecs.length === 0) {+ const isNoAuthProvider = Object.values(NOAUTH_PROVIDERS).some((provider) => provider.id === requestedProvider);+ if (isNoAuthProvider) {+ requestSpecs.push({+ provider: requestedProvider,+ path: `/api/v1/providers/${encodeURIComponent(requestedProvider)}/models`,+ thinkingEffort: undefined,+ });+ } else {+ return {+ models: [],+ source: "provider_connections",+ warning: `No active connections found for provider '${requestedProvider}'.`,+ };+ }+ }++ const collectedModels = new Map<string, McpCatalogResponse["models"][number]>();+ const warnings = new Set<string>();+ const sources = new Set<string>();++ for (const spec of requestSpecs) {+ const raw = toRecord(await fetchJson(spec.path));+ const source = toString(raw.source, spec.path.startsWith("/api/providers/") ? "api" : "v1_catalog");+ const warning = raw.warning ? String(raw.warning) : undefined;+ if (warning) warnings.add(warning);+ sources.add(source);++ const rawModels = Array.isArray(raw.models)+ ? raw.models+ : Array.isArray(raw.data)+ ? raw.data+ : [];++ for (const rawModel of rawModels) {+ const normalized = normalizeProviderModelRecord(rawModel, spec.provider, source, warning);+ if (spec.thinkingEffort && !normalized.thinkingEffort) {+ normalized.thinkingEffort = spec.thinkingEffort;+ }+ if (!normalized.id) continue;+ if (requestedCapability && !normalized.capabilities.includes(requestedCapability)) continue;++ const key = `${normalized.provider}:${normalized.id}`;+ if (!collectedModels.has(key)) {+ collectedModels.set(key, normalized);+ }+ }+ }++ return {+ models: [...collectedModels.values()],+ source: sources.size === 1 ? [...sources][0] : "aggregated_provider_models",+ ...(warnings.size > 0 ? { warning: [...warnings].join(" | ") } : {}),+ };+}+function withScopeEnforcement(toolName: string,handler: (args: unknown, extra?: McpToolExtraLike) => Promise<TextToolResult>,@@ -522,50 +729,7 @@ async function handleCostReport(args: { period?: string }) {async function handleListModelsCatalog(args: { provider?: string; capability?: string }) {const start = Date.now();try {- let path = "/v1/models";- let isProviderSpecific = false;- let source = "local_catalog";- let warning: string | undefined;-- if (args.provider && !args.capability) {- // Use direct provider fetch to get real-time API status- path = `/api/providers/${encodeURIComponent(args.provider)}/models?excludeHidden=true`;- isProviderSpecific = true;- } else {- const params = new URLSearchParams();- if (args.provider) params.set("provider", args.provider);- if (args.capability) params.set("capability", args.capability);- if (params.toString()) path += `?${params.toString()}`;- }-- const raw = toRecord(await omniRouteFetch(path));-- // If we used the direct provider endpoint- let rawModels: unknown[] = [];- if (isProviderSpecific) {- rawModels = Array.isArray(raw.models) ? raw.models : [];- source = typeof raw.source === "string" ? raw.source : "api";- if (raw.warning) warning = String(raw.warning);- } else {- rawModels = Array.isArray(raw.data) ? raw.data : [];- source = "local_catalog";- // OmniRoute's global /v1/models is always a cached/local catalog- }-- const result = {- models: rawModels.map((rawModel) => {- const model = toRecord(rawModel);- return {- id: toString(model.id, ""),- provider: toString(model.owned_by, toString(model.provider, args.provider || "unknown")),- capabilities: toStringArray(model.capabilities, ["chat"]),- status: toString(model.status, "available"),- pricing: model.pricing,- };- }),- source,- ...(warning ? { warning } : {}),- };+ const result = await getMcpModelsCatalog(args);await logToolCall("omniroute_list_models_catalog",diff --git a/open-sse/package.json b/open-sse/package.jsonindex 9f41059bcd..793134af7a 100644--- a/open-sse/package.json+++ b/open-sse/package.json@@ -1,6 +1,6 @@{"name": "@omniroute/open-sse",- "version": "3.8.12",+ "version": "3.8.13","description": "Express SSE sidecar for OmniRoute — handles streaming, protocol translation, and provider orchestration","type": "module","main": "index.js",diff --git a/open-sse/services/autoRefreshDaemon.ts b/open-sse/services/autoRefreshDaemon.tsnew file mode 100644index 0000000000..29c22a4a14--- /dev/null+++ b/open-sse/services/autoRefreshDaemon.ts@@ -0,0 +1,204 @@+/**+ * AutoRefreshDaemon — Background cookie validity checker for web-cookie providers+ *+ * Periodically checks stored credentials for web-cookie providers by making+ * lightweight requests to their home pages. If a credential is expired, it+ * logs a warning and marks the credential for re-authentication.+ *+ * The daemon does NOT automatically re-login (that requires user interaction+ * for security). It alerts the system so higher-level components can decide+ * what to do (e.g., fallback to another provider, prompt user to re-login).+ */++import { TOKEN_EXTRACTION_CONFIGS } from "./tokenExtractionConfig";++// ─── Types ──────────────────────────────────────────────────────────────────++export interface DaemonStatus {+ running: boolean;+ checkedProviderCount: number;+ expiredCredentials: string[];+ lastRun: number | null;+}++interface StoredCredentialEntry {+ providerId: string;+ value: string;+ storedAt: number;+}++// ─── Constants ──────────────────────────────────────────────────────────────++const DEFAULT_CHECK_INTERVAL_MS = 15 * 60 * 1000; // 15 minutes+const MIN_CHECK_INTERVAL_MS = 60 * 1000; // 1 minute minimum++// ─── Daemon ─────────────────────────────────────────────────────────────────++class AutoRefreshDaemon {+ private timerId: ReturnType<typeof setInterval> | null = null;+ private running = false;+ private checkIntervalMs: number;+ private expiredCredentials: string[] = [];+ private lastRun: number | null = null;+ /** In-memory store of web-cookie credentials (real persistence uses SQLite) */+ private credentialStore = new Map<string, StoredCredentialEntry>();++ constructor(checkIntervalMs = DEFAULT_CHECK_INTERVAL_MS) {+ this.checkIntervalMs = Math.max(checkIntervalMs, MIN_CHECK_INTERVAL_MS);+ }++ /**+ * Register a credential for auto-refresh monitoring.+ * Called when credentials are extracted/updated.+ */+ registerCredential(providerId: string, value: string): void {+ this.credentialStore.set(providerId, {+ providerId,+ value,+ storedAt: Date.now(),+ });+ }++ /**+ * Remove a credential from monitoring (e.g., provider deleted)+ */+ unregisterCredential(providerId: string): void {+ this.credentialStore.delete(providerId);+ }++ /**+ * Start the daemon — begins periodic credential checks+ */+ start(): void {+ if (this.running) return;+ this.running = true;++ // Run an initial check immediately+ this.check().catch(() => {});++ this.timerId = setInterval(() => {+ this.check().catch(() => {});+ }, this.checkIntervalMs);++ console.log(+ `[AutoRefreshDaemon] Started — checking ${this.credentialStore.size} credentials every ${this.checkIntervalMs / 1000}s`+ );+ }++ /**+ * Stop the daemon+ */+ stop(): void {+ if (!this.running) return;+ this.running = false;+ if (this.timerId) {+ clearInterval(this.timerId);+ this.timerId = null;+ }+ console.log("[AutoRefreshDaemon] Stopped");+ }++ /**+ * Check all stored credentials for validity.+ * Makes a lightweight HEAD/GET request to the provider's home page.+ */+ async check(): Promise<void> {+ this.lastRun = Date.now();+ const newlyExpired: string[] = [];++ const entries = [...this.credentialStore.entries()];++ for (const [providerId] of entries) {+ const config = TOKEN_EXTRACTION_CONFIGS.get(providerId);+ if (!config) {+ this.credentialStore.delete(providerId);+ continue;+ }++ try {+ const isValid = await this.validateCredential(providerId, config.homeUrl);+ if (!isValid) {+ newlyExpired.push(providerId);+ console.warn(+ `[AutoRefreshDaemon] Credential expired for "${providerId}" (${config.displayName})`+ );+ }+ } catch {+ // Network errors are non-fatal — retry next cycle+ }+ }++ // Update expired list+ for (const id of newlyExpired) {+ if (!this.expiredCredentials.includes(id)) {+ this.expiredCredentials.push(id);+ }+ }+ }++ /**+ * Validate a credential by making a request to the provider's home page.+ * Returns true if the response suggests the credential is still valid.+ */+ private async validateCredential(providerId: string, homeUrl: string): Promise<boolean> {+ const entry = this.credentialStore.get(providerId);+ if (!entry) return false;++ const controller = new AbortController();+ const timeout = setTimeout(() => controller.abort(), 10000);+ try {+ const response = await fetch(homeUrl, {+ method: "HEAD",+ signal: controller.signal,+ headers: {+ "User-Agent":+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36",+ },+ });++ // A valid credential typically returns 200 (occasionally 301/302)+ // 401/403 strongly suggest expired credential+ if (response.status === 401 || response.status === 403) {+ return false;+ }++ return true;+ } catch {+ // Network errors (timeout, DNS failure) don't mean the credential is bad+ return true;+ } finally {+ clearTimeout(timeout);+ }+ }++ /**+ * Get the current daemon status+ */+ getStatus(): DaemonStatus {+ return {+ running: this.running,+ checkedProviderCount: this.credentialStore.size,+ expiredCredentials: [...this.expiredCredentials],+ lastRun: this.lastRun,+ };+ }++ /**+ * Clear expired credentials list (e.g., after re-authentication)+ */+ clearExpired(): void {+ this.expiredCredentials = [];+ }++ /**+ * Restart the daemon (useful when config changes)+ */+ restart(): void {+ this.stop();+ this.start();+ }+}++// ─── Singleton ──────────────────────────────────────────────────────────────++export const autoRefreshDaemon = new AutoRefreshDaemon();diff --git a/open-sse/services/combo.ts b/open-sse/services/combo.tsindex 88c8c09a35..ddaa7b5077 100644--- a/open-sse/services/combo.ts+++ b/open-sse/services/combo.ts@@ -78,6 +78,7 @@ import type { RoutingHint } from "./manifestAdapter";import type { CompressionMode } from "./compression/types.ts";import { getModelContextLimit } from "../../src/lib/modelCapabilities";import { getProviderConnections } from "../../src/lib/db/providers";+import { getProviderModels } from "../config/providerModels.ts";import {getComboModelString,getComboStepTarget,@@ -1631,7 +1632,10 @@ async function getQuotaAwareConnectionsForTarget(const activeConnections = Array.isArray(connections)? (connections as Array<Record<string, unknown>>): [];- if (!resetAwareConnectionCache.has(provider) && resetAwareConnectionCache.size >= MAX_RESET_AWARE_CACHE) {+ if (+ !resetAwareConnectionCache.has(provider) &&+ resetAwareConnectionCache.size >= MAX_RESET_AWARE_CACHE+ ) {const oldest = resetAwareConnectionCache.keys().next().value;if (oldest !== undefined) resetAwareConnectionCache.delete(oldest);}@@ -1766,7 +1770,10 @@ async function fetchResetAwareQuotaWithCache({const refreshPromise = fetcher(connectionId, connection).then((quota) => {if (quota) {- if (!resetAwareQuotaCache.has(cacheKey) && resetAwareQuotaCache.size >= MAX_RESET_AWARE_CACHE) {+ if (+ !resetAwareQuotaCache.has(cacheKey) &&+ resetAwareQuotaCache.size >= MAX_RESET_AWARE_CACHE+ ) {const oldest = resetAwareQuotaCache.keys().next().value;if (oldest !== undefined) resetAwareQuotaCache.delete(oldest);}@@ -1783,7 +1790,10 @@ async function fetchResetAwareQuotaWithCache({.catch((error) => {const previous = resetAwareQuotaCache.get(cacheKey);if (previous) {- if (!resetAwareQuotaCache.has(cacheKey) && resetAwareQuotaCache.size >= MAX_RESET_AWARE_CACHE) {+ if (+ !resetAwareQuotaCache.has(cacheKey) &&+ resetAwareQuotaCache.size >= MAX_RESET_AWARE_CACHE+ ) {const oldest = resetAwareQuotaCache.keys().next().value;if (oldest !== undefined) resetAwareQuotaCache.delete(oldest);}@@ -2577,6 +2587,67 @@ function scoreAutoTargets(.sort((a, b) => b.score - a.score);}+/**+ * For an auto-combo WITHOUT an explicit `candidatePool`, broaden the eligible+ * targets to every model of every active provider connection so the router has+ * the full pool to score over. Already-present `modelStr`s are not duplicated.+ *+ * Best-effort: if loading active connections or provider models throws, the+ * explicitly-resolved targets are returned unchanged (the combo still runs).+ * Exported for unit testing. Mutates and returns `eligibleTargets`.+ */+export async function expandAutoComboCandidatePool(+ eligibleTargets: ResolvedComboTarget[],+ combo: { autoConfig?: unknown; config?: unknown } | null | undefined+): Promise<ResolvedComboTarget[]> {+ const localAutoConfig =+ (combo?.autoConfig as Record<string, unknown> | undefined) ||+ (isRecord((combo?.config as Record<string, unknown>)?.auto)+ ? ((combo?.config as Record<string, unknown>).auto as Record<string, unknown>)+ : null) ||+ (combo?.config as Record<string, unknown> | undefined) ||+ {};++ if (Array.isArray(localAutoConfig?.candidatePool)) return eligibleTargets;++ try {+ const allConnections = await getProviderConnections({ isActive: true });+ const providerIds = [+ ...new Set(+ (allConnections as Array<{ provider?: unknown }>)+ .map((c) => c.provider)+ .filter((p): p is string => typeof p === "string" && p.length > 0)+ ),+ ];+ for (const providerId of providerIds) {+ const providerModels = getProviderModels(providerId);+ for (const model of providerModels) {+ const modelStr = `${providerId}/${model.id}`;+ if (!eligibleTargets.some((t) => t.modelStr === modelStr)) {+ eligibleTargets.push({+ kind: "model",+ stepId: modelStr,+ executionKey: modelStr,+ provider: providerId,+ providerId: providerId,+ modelStr,+ weight: 1,+ connectionId: null,+ label: null,+ });+ }+ }+ }+ } catch {+ // Best-effort candidate expansion only: if loading active connections or+ // provider models fails, fall back to the explicitly-resolved targets+ // rather than aborting the combo. The push above is the only mutation,+ // so a throw leaves eligibleTargets exactly as explicit resolution built it.+ }++ return eligibleTargets;+}+/*** Handle combo chat with fallback.* @param {Object} options@@ -2983,6 +3054,8 @@ export async function handleComboChat({);// eligibleTargets intentionally unchanged — same fallback contract as tool-calling filter}++ eligibleTargets = await expandAutoComboCandidatePool(eligibleTargets, combo);}const prompt = extractPromptForIntent(body);@@ -3293,341 +3366,298 @@ export async function handleComboChat({let globalAttempts = 0;try {- for (let setTry = 0; setTry <= maxSetRetries; setTry++) {- // #1731: Per-set-iteration set of providers whose quota is fully exhausted.- // Reset each retry so providers excluded in a previous attempt get another chance.- const exhaustedProviders = new Set<string>();- const transientRateLimitedProviders = new Set<string>();- if (setTry > 0) {- log.info("COMBO", `All targets failed — retrying set (${setTry}/${maxSetRetries})`);- await new Promise((resolve) => {- const timer = setTimeout(resolve, setRetryDelayMs);- signal?.addEventListener(- "abort",- () => {- clearTimeout(timer);- resolve(undefined);- },- { once: true }- );- });- if (signal?.aborted) {- log.info("COMBO", "Client disconnected during set retry delay — aborting");- return errorResponse(499, "Client disconnected");+ for (let setTry = 0; setTry <= maxSetRetries; setTry++) {+ // #1731: Per-set-iteration set of providers whose quota is fully exhausted.+ // Reset each retry so providers excluded in a previous attempt get another chance.+ const exhaustedProviders = new Set<string>();+ const transientRateLimitedProviders = new Set<string>();+ if (setTry > 0) {+ log.info("COMBO", `All targets failed — retrying set (${setTry}/${maxSetRetries})`);+ await new Promise((resolve) => {+ const timer = setTimeout(resolve, setRetryDelayMs);+ signal?.addEventListener(+ "abort",+ () => {+ clearTimeout(timer);+ resolve(undefined);+ },+ { once: true }+ );+ });+ if (signal?.aborted) {+ log.info("COMBO", "Client disconnected during set retry delay — aborting");+ return errorResponse(499, "Client disconnected");+ }}- }-- let lastError: string | null = null;- let earliestRetryAfter: ComboRetryAfter | null = null;- let lastStatus: number | null = null;- const startTime = Date.now();- let fallbackCount = 0;- let recordedAttempts = 0;- let globalResolve: ((res: Response) => void) | null = null;- const globalPromise = new Promise<Response>((res) => {- globalResolve = res;- });- const runningTasks = new Set<Promise<void>>();- let anySuccess = false;- const abortControllers = new Map<number, AbortController>();- const zeroLatencyOptimizationsEnabled = config.zeroLatencyOptimizationsEnabled === true;-- const executeTarget = async (- i: number- ): Promise<{ ok: boolean; response?: Response } | null> => {- const target = orderedTargets[i];- const modelStr = target.modelStr;- const provider = target.provider;- const profile = await getRuntimeProviderProfile(provider);- const allowRateLimitedConnection =- Boolean(provider && provider !== "unknown") && transientRateLimitedProviders.has(provider);- const targetForAttempt = allowRateLimitedConnection- ? {- ...target,- allowRateLimitedConnection: true,- modelAbortSignal: abortControllers.get(i)!.signal,- }- : { ...target, modelAbortSignal: abortControllers.get(i)!.signal };+ let lastError: string | null = null;+ let earliestRetryAfter: ComboRetryAfter | null = null;+ let lastStatus: number | null = null;+ const startTime = Date.now();+ let fallbackCount = 0;+ let recordedAttempts = 0;- // #1731: Skip targets from a provider that already signaled full quota exhaustion this request.- if (provider && exhaustedProviders.has(provider)) {- log.info(- "COMBO",- `Skipping ${modelStr} — provider ${provider} marked exhausted this request (#1731)`- );- if (i > 0) fallbackCount++;- return null;- }-- // Pre-check: skip models where no credentials are available (excluded, rate-limited, or unavailable)- if (isModelAvailable) {- const available = await isModelAvailable(modelStr, targetForAttempt);- if (!available) {- log.debug?.("COMBO", `Skipping ${modelStr} — no credentials available or model excluded`);- if (i > 0) fallbackCount++;- return null;- }- }+ let globalResolve: ((res: Response) => void) | null = null;+ const globalPromise = new Promise<Response>((res) => {+ globalResolve = res;+ });+ const runningTasks = new Set<Promise<void>>();+ let anySuccess = false;+ const abortControllers = new Map<number, AbortController>();+ const zeroLatencyOptimizationsEnabled = config.zeroLatencyOptimizationsEnabled === true;++ const executeTarget = async (+ i: number+ ): Promise<{ ok: boolean; response?: Response } | null> => {+ const target = orderedTargets[i];+ const modelStr = target.modelStr;+ const provider = target.provider;+ const profile = await getRuntimeProviderProfile(provider);+ const allowRateLimitedConnection =+ Boolean(provider && provider !== "unknown") &&+ transientRateLimitedProviders.has(provider);+ const targetForAttempt = allowRateLimitedConnection+ ? {+ ...target,+ allowRateLimitedConnection: true,+ modelAbortSignal: abortControllers.get(i)!.signal,+ }+ : { ...target, modelAbortSignal: abortControllers.get(i)!.signal };- // Credential gate: skip targets with known-bad credentials (fail-fast)- const connectionId = target.connectionId as string | undefined;- if (connectionId) {- const gateResult = checkCredentialGate(connectionId, provider, modelStr);- if (gateResult.allowed === false) {- logCredentialSkip(log, modelStr, gateResult.reason || "Credential gate blocked");+ // #1731: Skip targets from a provider that already signaled full quota exhaustion this request.+ if (provider && exhaustedProviders.has(provider)) {+ log.info(+ "COMBO",+ `Skipping ${modelStr} — provider ${provider} marked exhausted this request (#1731)`+ );if (i > 0) fallbackCount++;return null;}- }- // Retry loop for transient errors- for (let retry = 0; retry <= maxRetries; retry++) {- // Fix #1681: Bail out immediately if the client has disconnected- if (signal?.aborted) {- log.info("COMBO", `Client disconnected — aborting combo loop before model ${modelStr}`);- return { ok: false, response: errorResponse(499, "Client disconnected") };- }- globalAttempts++;- if (globalAttempts > MAX_GLOBAL_ATTEMPTS) {- log.warn(- "COMBO",- `Maximum combo attempts (${MAX_GLOBAL_ATTEMPTS}) exceeded across all targets and fallbacks. Terminating loop to prevent runaway background requests.`- );- return { ok: false, response: errorResponse(503, "Maximum combo retry limit reached") };+ // Pre-check: skip models where no credentials are available (excluded, rate-limited, or unavailable)+ if (isModelAvailable) {+ const available = await isModelAvailable(modelStr, targetForAttempt);+ if (!available) {+ log.debug?.(+ "COMBO",+ `Skipping ${modelStr} — no credentials available or model excluded`+ );+ if (i > 0) fallbackCount++;+ return null;+ }}- // Predictive TTFT Circuit Breaker (skip slow models)- if (- zeroLatencyOptimizationsEnabled &&- config.predictiveTtftMs &&- config.predictiveTtftMs > 0 &&- retry === 0- ) {- const cMetrics = getComboMetrics(combo.name);- if (cMetrics) {- const targetKey = orderedTargets[i].executionKey || modelStr;- const m = cMetrics.byTarget[targetKey] || cMetrics.byModel[modelStr];- if (m && m.requests >= 5 && m.avgLatencyMs > config.predictiveTtftMs) {- log.warn(- "COMBO",- `Predictive TTFT Circuit Breaker: skipping ${modelStr} (avg ${m.avgLatencyMs}ms > max ${config.predictiveTtftMs}ms)`- );- return null;- }+ // Credential gate: skip targets with known-bad credentials (fail-fast)+ const connectionId = target.connectionId as string | undefined;+ if (connectionId) {+ const gateResult = checkCredentialGate(connectionId, provider, modelStr);+ if (gateResult.allowed === false) {+ logCredentialSkip(log, modelStr, gateResult.reason || "Credential gate blocked");+ if (i > 0) fallbackCount++;+ return null;}}- if (retry > 0) {- log.info(- "COMBO",- `Retrying ${modelStr} in ${retryDelayMs}ms (attempt ${retry + 1}/${maxRetries + 1})`- );- await new Promise((resolve) => {- const timer = setTimeout(resolve, retryDelayMs);- signal?.addEventListener(- "abort",- () => {- clearTimeout(timer);- resolve(undefined);- },- { once: true }- );- });+ // Retry loop for transient errors+ for (let retry = 0; retry <= maxRetries; retry++) {+ // Fix #1681: Bail out immediately if the client has disconnectedif (signal?.aborted) {- log.info("COMBO", `Client disconnected during retry delay — aborting`);+ log.info("COMBO", `Client disconnected — aborting combo loop before model ${modelStr}`);return { ok: false, response: errorResponse(499, "Client disconnected") };}- }-- log.info(- "COMBO",- `Trying model ${i + 1}/${orderedTargets.length}: ${modelStr}${retry > 0 ? ` (retry ${retry})` : ""}`- );- emit("combo.target.attempt", {- comboName: combo.name,- targetIndex: i,- provider,- model: modelStr,- timestamp: Date.now(),- strategy,- });-- // Deep clone the body to ensure context preservation and prevent mutations- // from affecting other targets in the combo- let attemptBody = JSON.parse(JSON.stringify(body));-- // Proactive Context Compression for fallbacks (Zero-Latency optimization)- if (- zeroLatencyOptimizationsEnabled &&- i > 0 &&- config.fallbackCompressionMode &&- config.fallbackCompressionMode !== "off"- ) {- const { estimateTokens } = await import("./contextManager.ts");- const estimatedTokens = estimateTokens(JSON.stringify(attemptBody));- if (estimatedTokens > (config.fallbackCompressionThreshold ?? 1000)) {- const { applyCompression } = await import("./compression/strategySelector.ts");- const compressionResult = applyCompression(- attemptBody,- config.fallbackCompressionMode as CompressionMode,- { model: modelStr }+ globalAttempts++;+ if (globalAttempts > MAX_GLOBAL_ATTEMPTS) {+ log.warn(+ "COMBO",+ `Maximum combo attempts (${MAX_GLOBAL_ATTEMPTS}) exceeded across all targets and fallbacks. Terminating loop to prevent runaway background requests.`);- if (compressionResult.compressed) {- log.info(- "COMBO",- `Proactive fallback compression applied (${config.fallbackCompressionMode}): ${estimatedTokens} -> ${compressionResult.stats?.compressedTokens} tokens`- );- attemptBody = compressionResult.body;- }+ return { ok: false, response: errorResponse(503, "Maximum combo retry limit reached") };}- }- // Universal handoff: inject existing handoff if model changed- if (- universalHandoffConfig.enabled &&- relayOptions?.sessionId &&- !(body as Record<string, unknown>)?.[SKIP_UNIVERSAL_HANDOFF_FLAG]- ) {- const lastModel = getLastSessionModel(relayOptions.sessionId, combo.name);- if (lastModel && lastModel !== modelStr) {- const existingHandoff = getHandoff(relayOptions.sessionId, combo.name);- attemptBody = injectUniversalHandoffBody(- attemptBody, // Use the cloned body to maintain isolation- lastModel,- modelStr,- `Model routing: ${lastModel} → ${modelStr}`,- existingHandoff- );+ // Predictive TTFT Circuit Breaker (skip slow models)+ if (+ zeroLatencyOptimizationsEnabled &&+ config.predictiveTtftMs &&+ config.predictiveTtftMs > 0 &&+ retry === 0+ ) {+ const cMetrics = getComboMetrics(combo.name);+ if (cMetrics) {+ const targetKey = orderedTargets[i].executionKey || modelStr;+ const m = cMetrics.byTarget[targetKey] || cMetrics.byModel[modelStr];+ if (m && m.requests >= 5 && m.avgLatencyMs > config.predictiveTtftMs) {+ log.warn(+ "COMBO",+ `Predictive TTFT Circuit Breaker: skipping ${modelStr} (avg ${m.avgLatencyMs}ms > max ${config.predictiveTtftMs}ms)`+ );+ return null;+ }+ }}- }- const result = await handleSingleModelWithTimeout(attemptBody, modelStr, {- ...targetForAttempt,- failoverBeforeRetry: config.failoverBeforeRetry,- });- // Success — validate response quality before returning- if (result.ok) {- const quality = await validateResponseQuality(result, clientRequestedStream, log);- if (!quality.valid) {- log.warn(+ if (retry > 0) {+ log.info("COMBO",- `Model ${modelStr} returned 200 but failed quality check: ${quality.reason}`+ `Retrying ${modelStr} in ${retryDelayMs}ms (attempt ${retry + 1}/${maxRetries + 1})`);- recordComboRequest(combo.name, modelStr, {- success: false,- latencyMs: Date.now() - startTime,- fallbackCount,- strategy,- target: toRecordedTarget(target),- });- recordedAttempts++;- // Fix #1707: Set terminal state so the fallback doesn't emit- // misleading ALL_ACCOUNTS_INACTIVE when the real issue is quality.- lastError = `Upstream response failed quality validation: ${quality.reason}`;- if (!lastStatus) lastStatus = 502;- if (i > 0) fallbackCount++;- emit("combo.target.failed", {- comboName: combo.name,- targetIndex: i,- provider,- model: modelStr,- error: `Quality: ${quality.reason}`,- latencyMs: Date.now() - startTime,+ await new Promise((resolve) => {+ const timer = setTimeout(resolve, retryDelayMs);+ signal?.addEventListener(+ "abort",+ () => {+ clearTimeout(timer);+ resolve(undefined);+ },+ { once: true }+ );});- return null;+ if (signal?.aborted) {+ log.info("COMBO", `Client disconnected during retry delay — aborting`);+ return { ok: false, response: errorResponse(499, "Client disconnected") };+ }}- const latencyMs = Date.now() - startTime;- emit("combo.target.succeeded", {- comboName: combo.name,- targetIndex: i,- provider,- model: modelStr,- latencyMs,- });+log.info("COMBO",- `Model ${modelStr} succeeded (${latencyMs}ms, ${fallbackCount} fallbacks)`+ `Trying model ${i + 1}/${orderedTargets.length}: ${modelStr}${retry > 0 ? ` (retry ${retry})` : ""}`);- recordComboRequest(combo.name, modelStr, {- success: true,- latencyMs,- fallbackCount,- strategy,- target: toRecordedTarget(target),- });- recordedAttempts++;- // Webhook fan-out: best-effort, never blocks the response stream.- notifyWebhookEvent("request.completed", {- combo: combo.name,+ emit("combo.target.attempt", {+ comboName: combo.name,+ targetIndex: i,provider,model: modelStr,- latencyMs,- fallbackCount,+ timestamp: Date.now(),+ strategy,});- // Universal handoff: record model usage for session+ // Deep clone the body to ensure context preservation and prevent mutations+ // from affecting other targets in the combo+ let attemptBody = JSON.parse(JSON.stringify(body));++ // Proactive Context Compression for fallbacks (Zero-Latency optimization)+ if (+ zeroLatencyOptimizationsEnabled &&+ i > 0 &&+ config.fallbackCompressionMode &&+ config.fallbackCompressionMode !== "off"+ ) {+ const { estimateTokens } = await import("./contextManager.ts");+ const estimatedTokens = estimateTokens(JSON.stringify(attemptBody));+ if (estimatedTokens > (config.fallbackCompressionThreshold ?? 1000)) {+ const { applyCompression } = await import("./compression/strategySelector.ts");+ const compressionResult = applyCompression(+ attemptBody,+ config.fallbackCompressionMode as CompressionMode,+ { model: modelStr }+ );+ if (compressionResult.compressed) {+ log.info(+ "COMBO",+ `Proactive fallback compression applied (${config.fallbackCompressionMode}): ${estimatedTokens} -> ${compressionResult.stats?.compressedTokens} tokens`+ );+ attemptBody = compressionResult.body;+ }+ }+ }++ // Universal handoff: inject existing handoff if model changedif (universalHandoffConfig.enabled &&relayOptions?.sessionId &&!(body as Record<string, unknown>)?.[SKIP_UNIVERSAL_HANDOFF_FLAG]) {- const prevModel = getLastSessionModel(relayOptions.sessionId, combo.name);- recordSessionModelUsage(- relayOptions.sessionId,- combo.name,- modelStr,- provider,- target.connectionId ?? undefined- );- if (prevModel && prevModel !== modelStr) {- const handoffSourceMessages =- Array.isArray(body?.messages) && body.messages.length > 0- ? body.messages- : Array.isArray(body?.input)- ? body.input- : [];-- maybeGenerateUniversalHandoff({- sessionId: relayOptions.sessionId,+ const lastModel = getLastSessionModel(relayOptions.sessionId, combo.name);+ if (lastModel && lastModel !== modelStr) {+ const existingHandoff = getHandoff(relayOptions.sessionId, combo.name);+ attemptBody = injectUniversalHandoffBody(+ attemptBody, // Use the cloned body to maintain isolation+ lastModel,+ modelStr,+ `Model routing: ${lastModel} → ${modelStr}`,+ existingHandoff+ );+ }+ }+ const result = await handleSingleModelWithTimeout(attemptBody, modelStr, {+ ...targetForAttempt,+ failoverBeforeRetry: config.failoverBeforeRetry,+ });++ // Success — validate response quality before returning+ if (result.ok) {+ const quality = await validateResponseQuality(result, clientRequestedStream, log);+ if (!quality.valid) {+ log.warn(+ "COMBO",+ `Model ${modelStr} returned 200 but failed quality check: ${quality.reason}`+ );+ recordComboRequest(combo.name, modelStr, {+ success: false,+ latencyMs: Date.now() - startTime,+ fallbackCount,+ strategy,+ target: toRecordedTarget(target),+ });+ recordedAttempts++;+ // Fix #1707: Set terminal state so the fallback doesn't emit+ // misleading ALL_ACCOUNTS_INACTIVE when the real issue is quality.+ lastError = `Upstream response failed quality validation: ${quality.reason}`;+ if (!lastStatus) lastStatus = 502;+ if (i > 0) fallbackCount++;+ emit("combo.target.failed", {comboName: combo.name,- messages: handoffSourceMessages as MessageLike[],- prevModel,- currModel: modelStr,- universalConfig: universalHandoffConfig,- handleSingleModel: handleSingleModelWithTimeout,+ targetIndex: i,+ provider,+ model: modelStr,+ error: `Quality: ${quality.reason}`,+ latencyMs: Date.now() - startTime,});+ return null;}-- recordSessionModelUsage(- relayOptions.sessionId,- combo.name,- modelStr,+ const latencyMs = Date.now() - startTime;+ emit("combo.target.succeeded", {+ comboName: combo.name,+ targetIndex: i,provider,- target.connectionId ?? undefined+ model: modelStr,+ latencyMs,+ });+ log.info(+ "COMBO",+ `Model ${modelStr} succeeded (${latencyMs}ms, ${fallbackCount} fallbacks)`);- }- // Context-relay intentionally splits responsibilities:- // combo.ts decides whether a successful turn should generate a handoff,- // while chat.ts injects the handoff after the real connectionId is resolved.- if (- strategy === "context-relay" &&- relayOptions?.sessionId &&- relayConfig &&- relayConfig.handoffProviders.includes(provider) &&- provider === "codex"- ) {- const connectionId = getSessionConnection(relayOptions.sessionId);- if (connectionId) {- const quotaInfo = await fetchCodexQuota(connectionId).catch(() => null);- if (quotaInfo) {- const resetCandidates = [- quotaInfo.windows?.session?.resetAt,- quotaInfo.windows?.weekly?.resetAt,- quotaInfo.resetAt,- ]- .filter((value): value is string => typeof value === "string" && value.length > 0)- .sort((a, b) => a.localeCompare(b));+ recordComboRequest(combo.name, modelStr, {+ success: true,+ latencyMs,+ fallbackCount,+ strategy,+ target: toRecordedTarget(target),+ });+ recordedAttempts++;+ // Webhook fan-out: best-effort, never blocks the response stream.+ notifyWebhookEvent("request.completed", {+ combo: combo.name,+ provider,+ model: modelStr,+ latencyMs,+ fallbackCount,+ });++ // Universal handoff: record model usage for session+ if (+ universalHandoffConfig.enabled &&+ relayOptions?.sessionId &&+ !(body as Record<string, unknown>)?.[SKIP_UNIVERSAL_HANDOFF_FLAG]+ ) {+ const prevModel = getLastSessionModel(relayOptions.sessionId, combo.name);+ recordSessionModelUsage(+ relayOptions.sessionId,+ combo.name,+ modelStr,+ provider,+ target.connectionId ?? undefined+ );+ if (prevModel && prevModel !== modelStr) {const handoffSourceMessages =Array.isArray(body?.messages) && body.messages.length > 0? body.messages@@ -3635,186 +3665,284 @@ export async function handleComboChat({? body.input: [];- maybeGenerateHandoff({+ maybeGenerateUniversalHandoff({sessionId: relayOptions.sessionId,comboName: combo.name,- connectionId,- percentUsed: quotaInfo.percentUsed,- messages: handoffSourceMessages,- model: modelStr,- expiresAt: resetCandidates[0] || null,- config: relayConfig,+ messages: handoffSourceMessages as MessageLike[],+ prevModel,+ currModel: modelStr,+ universalConfig: universalHandoffConfig,handleSingleModel: handleSingleModelWithTimeout,});}- }- }- // Record last known good provider (LKGP) for this combo/model (#919)- if (provider) {- const connId = target.connectionId || undefined;- void (async () => {- try {- const { setLKGP } = await import("../../src/lib/localDb");- await Promise.all([- setLKGP(combo.name, target.executionKey, provider, connId),- setLKGP(combo.name, combo.id || combo.name, provider, connId),- ]);- } catch (err) {- log.warn("COMBO", "Failed to record Last Known Good Provider. This is non-fatal.", {- err,- });+ recordSessionModelUsage(+ relayOptions.sessionId,+ combo.name,+ modelStr,+ provider,+ target.connectionId ?? undefined+ );+ }+ // Context-relay intentionally splits responsibilities:+ // combo.ts decides whether a successful turn should generate a handoff,+ // while chat.ts injects the handoff after the real connectionId is resolved.+ if (+ strategy === "context-relay" &&+ relayOptions?.sessionId &&+ relayConfig &&+ relayConfig.handoffProviders.includes(provider) &&+ provider === "codex"+ ) {+ const connectionId = getSessionConnection(relayOptions.sessionId);+ if (connectionId) {+ const quotaInfo = await fetchCodexQuota(connectionId).catch(() => null);+ if (quotaInfo) {+ const resetCandidates = [+ quotaInfo.windows?.session?.resetAt,+ quotaInfo.windows?.weekly?.resetAt,+ quotaInfo.resetAt,+ ]+ .filter(+ (value): value is string => typeof value === "string" && value.length > 0+ )+ .sort((a, b) => a.localeCompare(b));+ const handoffSourceMessages =+ Array.isArray(body?.messages) && body.messages.length > 0+ ? body.messages+ : Array.isArray(body?.input)+ ? body.input+ : [];++ maybeGenerateHandoff({+ sessionId: relayOptions.sessionId,+ comboName: combo.name,+ connectionId,+ percentUsed: quotaInfo.percentUsed,+ messages: handoffSourceMessages,+ model: modelStr,+ expiresAt: resetCandidates[0] || null,+ config: relayConfig,+ handleSingleModel: handleSingleModelWithTimeout,+ });+ }}- })();- }+ }- return { ok: true, response: quality.clonedResponse ?? result };- }+ // Record last known good provider (LKGP) for this combo/model (#919)+ if (provider) {+ const connId = target.connectionId || undefined;+ void (async () => {+ try {+ const { setLKGP } = await import("../../src/lib/localDb");+ await Promise.all([+ setLKGP(combo.name, target.executionKey, provider, connId),+ setLKGP(combo.name, combo.id || combo.name, provider, connId),+ ]);+ } catch (err) {+ log.warn(+ "COMBO",+ "Failed to record Last Known Good Provider. This is non-fatal.",+ {+ err,+ }+ );+ }+ })();+ }- // Extract error info from response- let errorText = result.statusText || "";- let errorBody: ComboErrorBody = null;- let retryAfter: ComboRetryAfter | null = null;- try {- const cloned = result.clone();+ return { ok: true, response: quality.clonedResponse ?? result };+ }++ // Extract error info from response+ let errorText = result.statusText || "";+ let errorBody: ComboErrorBody = null;+ let retryAfter: ComboRetryAfter | null = null;try {- const text = await cloned.text();- if (text) {- errorText = text.substring(0, 500);- errorBody = JSON.parse(text);- const parsedError = errorBody?.error;- errorText =- (typeof parsedError === "object" && parsedError?.message) ||- (typeof parsedError === "string" ? parsedError : null) ||- errorBody?.message ||- errorText;- retryAfter = errorBody?.retryAfter || null;+ const cloned = result.clone();+ try {+ const text = await cloned.text();+ if (text) {+ errorText = text.substring(0, 500);+ errorBody = JSON.parse(text);+ const parsedError = errorBody?.error;+ errorText =+ (typeof parsedError === "object" && parsedError?.message) ||+ (typeof parsedError === "string" ? parsedError : null) ||+ errorBody?.message ||+ errorText;+ retryAfter = errorBody?.retryAfter || null;+ }+ } catch {+ /* Clone parse failed */}} catch {- /* Clone parse failed */+ /* Clone failed */}- } catch {- /* Clone failed */- }- // Track earliest retryAfter- if (- retryAfter &&- (!earliestRetryAfter || new Date(retryAfter) < new Date(earliestRetryAfter))- ) {- earliestRetryAfter = retryAfter;- }-- // Normalize error text- if (typeof errorText !== "string") {- try {- errorText = JSON.stringify(errorText);- } catch {- errorText = String(errorText);+ // Track earliest retryAfter+ if (+ retryAfter &&+ (!earliestRetryAfter || new Date(retryAfter) < new Date(earliestRetryAfter))+ ) {+ earliestRetryAfter = retryAfter;}- }- const isStreamReadinessFailure =- (result.status === 502 || result.status === 504) &&- isStreamReadinessFailureErrorBody(errorBody);+ // Normalize error text+ if (typeof errorText !== "string") {+ try {+ errorText = JSON.stringify(errorText);+ } catch {+ errorText = String(errorText);+ }+ }- // FIX 5: a local per-API-key token-limit 429 must not cool shared accounts.- const isTokenLimitBreach = result.status === 429 && isTokenLimitBreachErrorBody(errorBody);+ const isStreamReadinessFailure =+ (result.status === 502 || result.status === 504) &&+ isStreamReadinessFailureErrorBody(errorBody);- // Fix #1681: Status 499 means client disconnected — stop combo loop immediately.- // There is no point trying fallback models when nobody is listening.- if (result.status === 499) {- log.info("COMBO", `Client disconnected (499) during ${modelStr} — stopping combo loop`);- recordComboRequest(combo.name, modelStr, {- success: false,- latencyMs: Date.now() - startTime,- fallbackCount,- strategy,- target: toRecordedTarget(target),- });- recordedAttempts++;- // executeTarget must return the {ok,response} contract — a raw Response- // here makes the speculative loop's res.ok/res.response checks both miss,- // so the combo would wrongly fall through to the next model after a 499.- return { ok: false, response: result };- }+ // FIX 5: a local per-API-key token-limit 429 must not cool shared accounts.+ const isTokenLimitBreach =+ result.status === 429 && isTokenLimitBreachErrorBody(errorBody);- // Combo fallback is target-level orchestration: a non-ok target response is- // treated as local to that target and the combo continues to the next target.- // Error classification is retained only for retry/cooldown pacing; it must- // not decide whether fallback happens, including for generic 400 responses.- const rawError = errorBody?.error;- const structuredError =- rawError && typeof rawError === "object"- ? {- // Upstream JSON may carry a numeric `code`/`type` (e.g. {"code":40001}).- // Coerce to string if present instead of discarding, so downstream string- // ops (.toLowerCase, .startsWith) can run safely without type crashes.- code:- (rawError as Record<string, unknown>).code !== undefined &&- (rawError as Record<string, unknown>).code !== null- ? String((rawError as Record<string, unknown>).code)- : undefined,- type:- (rawError as Record<string, unknown>).type !== undefined &&- (rawError as Record<string, unknown>).type !== null- ? String((rawError as Record<string, unknown>).type)- : undefined,- }- : undefined;- const fallbackResult = checkFallbackError(- result.status,- errorText,- 0,- null,- provider,- result.headers,- profile,- structuredError- );- const { cooldownMs } = fallbackResult;+ // Fix #1681: Status 499 means client disconnected — stop combo loop immediately.+ // There is no point trying fallback models when nobody is listening.+ if (result.status === 499) {+ log.info("COMBO", `Client disconnected (499) during ${modelStr} — stopping combo loop`);+ recordComboRequest(combo.name, modelStr, {+ success: false,+ latencyMs: Date.now() - startTime,+ fallbackCount,+ strategy,+ target: toRecordedTarget(target),+ });+ recordedAttempts++;+ // executeTarget must return the {ok,response} contract — a raw Response+ // here makes the speculative loop's res.ok/res.response checks both miss,+ // so the combo would wrongly fall through to the next model after a 499.+ return { ok: false, response: result };+ }- // #1731: If the entire provider quota is exhausted, mark it so subsequent- // same-provider targets are skipped immediately. API-key 429s still use- // the short resilience cooldown, but explicit quota text should stop the- // combo from trying another target for the same provider in this request.- const providerExhausted =- Boolean(provider && provider !== "unknown") &&- (isProviderExhaustedReason(fallbackResult) ||- classifyErrorText(errorText) === RateLimitReason.QUOTA_EXHAUSTED);- if (providerExhausted) {- exhaustedProviders.add(provider);- log.info(- "COMBO",- `Provider ${provider} quota exhausted — marking for skip on remaining targets (#1731)`+ // Combo fallback is target-level orchestration: a non-ok target response is+ // treated as local to that target and the combo continues to the next target.+ // Error classification is retained only for retry/cooldown pacing; it must+ // not decide whether fallback happens, including for generic 400 responses.+ const rawError = errorBody?.error;+ const structuredError =+ rawError && typeof rawError === "object"+ ? {+ // Upstream JSON may carry a numeric `code`/`type` (e.g. {"code":40001}).+ // Coerce to string if present instead of discarding, so downstream string+ // ops (.toLowerCase, .startsWith) can run safely without type crashes.+ code:+ (rawError as Record<string, unknown>).code !== undefined &&+ (rawError as Record<string, unknown>).code !== null+ ? String((rawError as Record<string, unknown>).code)+ : undefined,+ type:+ (rawError as Record<string, unknown>).type !== undefined &&+ (rawError as Record<string, unknown>).type !== null+ ? String((rawError as Record<string, unknown>).type)+ : undefined,+ }+ : undefined;+ const fallbackResult = checkFallbackError(+ result.status,+ errorText,+ 0,+ null,+ provider,+ result.headers,+ profile,+ structuredError);- } else if (- result.status === 429 &&- !isTokenLimitBreach &&- provider &&- provider !== "unknown"- ) {- transientRateLimitedProviders.add(provider);- }+ const { cooldownMs } = fallbackResult;++ // #1731: If the entire provider quota is exhausted, mark it so subsequent+ // same-provider targets are skipped immediately. API-key 429s still use+ // the short resilience cooldown, but explicit quota text should stop the+ // combo from trying another target for the same provider in this request.+ const providerExhausted =+ Boolean(provider && provider !== "unknown") &&+ (isProviderExhaustedReason(fallbackResult) ||+ classifyErrorText(errorText) === RateLimitReason.QUOTA_EXHAUSTED);+ if (providerExhausted) {+ exhaustedProviders.add(provider);+ log.info(+ "COMBO",+ `Provider ${provider} quota exhausted — marking for skip on remaining targets (#1731)`+ );+ } else if (+ result.status === 429 &&+ !isTokenLimitBreach &&+ provider &&+ provider !== "unknown"+ ) {+ transientRateLimitedProviders.add(provider);+ }- // #2101: Prevent infinite fallback loops with 400 Bad Request errors that indicate- // request-body-specific issues (context overflow, malformed request, model access denied).- // These errors are unlikely to be resolved by trying different target models since- // the same problematic request body would be sent to all targets.- if (- result.status === 400 &&- fallbackResult.shouldFallback &&- (fallbackResult.reason === RateLimitReason.MODEL_CAPACITY ||- errorText.toLowerCase().includes("context") ||- errorText.toLowerCase().includes("malformed") ||- errorText.toLowerCase().includes("invalid") ||- errorText.toLowerCase().includes("bad request"))- ) {- log.warn(- "COMBO",- `400 Bad Request with body-specific error detected on ${modelStr} — skipping fallback to other targets to prevent infinite loop`- );- // Record the failure and break to avoid trying other targets with the same bad request+ // #2101: Prevent infinite fallback loops with 400 Bad Request errors that indicate+ // request-body-specific issues (context overflow, malformed request, model access denied).+ // These errors are unlikely to be resolved by trying different target models since+ // the same problematic request body would be sent to all targets.+ if (+ result.status === 400 &&+ fallbackResult.shouldFallback &&+ (fallbackResult.reason === RateLimitReason.MODEL_CAPACITY ||+ errorText.toLowerCase().includes("context") ||+ errorText.toLowerCase().includes("malformed") ||+ errorText.toLowerCase().includes("invalid") ||+ errorText.toLowerCase().includes("bad request"))+ ) {+ log.warn(+ "COMBO",+ `400 Bad Request with body-specific error detected on ${modelStr} — skipping fallback to other targets to prevent infinite loop`+ );+ // Record the failure and break to avoid trying other targets with the same bad request+ recordComboRequest(combo.name, modelStr, {+ success: false,+ latencyMs: Date.now() - startTime,+ fallbackCount,+ strategy,+ target: toRecordedTarget(target),+ });+ recordedAttempts++;+ lastError = errorText || String(result.status);+ if (!lastStatus) lastStatus = result.status;+ if (i > 0) fallbackCount++;+ log.warn("COMBO", `Model ${modelStr} failed with body-specific error, stopping combo`);+ break; // Break out of the target loop to avoid trying other models+ }++ // Trigger shared provider circuit breaker for 5xx errors and connection failures.+ // If the next target in the combo is on the same provider, don't mark the provider+ // as failed — different models on the same provider may still succeed.+ // G-02: when fallbackResult.skipProviderBreaker is set (embedded service supervisor+ // outage signalled via X-Omni-Fallback-Hint: connection_cooldown) apply connection+ // cooldown only — do NOT trip the whole-provider breaker.+ const nextTarget = orderedTargets[i + 1];+ const sameProviderNext =+ typeof nextTarget?.provider === "string" && nextTarget.provider === provider;+ if (+ !isStreamReadinessFailure &&+ isProviderFailureCode(result.status) &&+ !sameProviderNext &&+ !fallbackResult.skipProviderBreaker+ ) {+ recordProviderFailure(provider, log, target.connectionId, profile);+ }++ // Check if this is a transient error worth retrying on same model.+ // A token-limit 429 is terminal for the client — never retry it.+ const isTransient =+ !isStreamReadinessFailure &&+ !isTokenLimitBreach &&+ [408, 429, 500, 502, 503, 504].includes(result.status);+ if (retry < maxRetries && isTransient && !providerExhausted) {+ continue; // Retry same model+ }++ // Done retrying this modelrecordComboRequest(combo.name, modelStr, {success: false,latencyMs: Date.now() - startTime,@@ -3826,182 +3954,143 @@ export async function handleComboChat({lastError = errorText || String(result.status);if (!lastStatus) lastStatus = result.status;if (i > 0) fallbackCount++;- log.warn("COMBO", `Model ${modelStr} failed with body-specific error, stopping combo`);- break; // Break out of the target loop to avoid trying other models- }-- // Trigger shared provider circuit breaker for 5xx errors and connection failures.- // If the next target in the combo is on the same provider, don't mark the provider- // as failed — different models on the same provider may still succeed.- // G-02: when fallbackResult.skipProviderBreaker is set (embedded service supervisor- // outage signalled via X-Omni-Fallback-Hint: connection_cooldown) apply connection- // cooldown only — do NOT trip the whole-provider breaker.- const nextTarget = orderedTargets[i + 1];- const sameProviderNext =- typeof nextTarget?.provider === "string" && nextTarget.provider === provider;- if (- !isStreamReadinessFailure &&- isProviderFailureCode(result.status) &&- !sameProviderNext &&- !fallbackResult.skipProviderBreaker- ) {- recordProviderFailure(provider, log, target.connectionId, profile);- }-- // Check if this is a transient error worth retrying on same model.- // A token-limit 429 is terminal for the client — never retry it.- const isTransient =- !isStreamReadinessFailure &&- !isTokenLimitBreach &&- [408, 429, 500, 502, 503, 504].includes(result.status);- if (retry < maxRetries && isTransient && !providerExhausted) {- continue; // Retry same model- }-- // Done retrying this model- recordComboRequest(combo.name, modelStr, {- success: false,- latencyMs: Date.now() - startTime,- fallbackCount,- strategy,- target: toRecordedTarget(target),- });- recordedAttempts++;- lastError = errorText || String(result.status);- if (!lastStatus) lastStatus = result.status;- if (i > 0) fallbackCount++;- log.warn("COMBO", `Model ${modelStr} failed, trying next`, { status: result.status });-- const fallbackWaitMs =- fallbackDelayMs > 0 && cooldownMs > 0 && cooldownMs <= MAX_FALLBACK_WAIT_MS- ? Math.min(cooldownMs, fallbackDelayMs)- : 0;- if ([502, 503, 504].includes(result.status) && fallbackWaitMs > 0) {- log.debug?.("COMBO", `Waiting ${fallbackWaitMs}ms before fallback to next model`);- await new Promise((resolve) => {- const timer = setTimeout(resolve, fallbackWaitMs);- signal?.addEventListener(- "abort",- () => {- clearTimeout(timer);- resolve(undefined);- },- { once: true }- );- });- if (signal?.aborted) {- log.info("COMBO", `Client disconnected during fallback wait — aborting`);- return { ok: false, response: errorResponse(499, "Client disconnected") };+ log.warn("COMBO", `Model ${modelStr} failed, trying next`, { status: result.status });++ const fallbackWaitMs =+ fallbackDelayMs > 0 && cooldownMs > 0 && cooldownMs <= MAX_FALLBACK_WAIT_MS+ ? Math.min(cooldownMs, fallbackDelayMs)+ : 0;+ if ([502, 503, 504].includes(result.status) && fallbackWaitMs > 0) {+ log.debug?.("COMBO", `Waiting ${fallbackWaitMs}ms before fallback to next model`);+ await new Promise((resolve) => {+ const timer = setTimeout(resolve, fallbackWaitMs);+ signal?.addEventListener(+ "abort",+ () => {+ clearTimeout(timer);+ resolve(undefined);+ },+ { once: true }+ );+ });+ if (signal?.aborted) {+ log.info("COMBO", `Client disconnected during fallback wait — aborting`);+ return { ok: false, response: errorResponse(499, "Client disconnected") };+ }}- }+ return null;+ }return null;- }- return null;- };+ };- for (let i = 0; i < orderedTargets.length; i++) {- if (anySuccess) break;+ for (let i = 0; i < orderedTargets.length; i++) {+ if (anySuccess) break;- const abortController = new AbortController();- abortControllers.set(i, abortController);- const onClientAbort = () => abortController.abort();- signal?.addEventListener("abort", onClientAbort);+ const abortController = new AbortController();+ abortControllers.set(i, abortController);+ const onClientAbort = () => abortController.abort();+ signal?.addEventListener("abort", onClientAbort);- const task = (async () => {- try {- const res = await executeTarget(i);- if (res && !anySuccess) {- if (res.ok) {- anySuccess = true;- globalResolve!(res.response!);- for (const [idx, ac] of abortControllers.entries()) {- if (idx !== i) ac.abort();+ const task = (async () => {+ try {+ const res = await executeTarget(i);+ if (res && !anySuccess) {+ if (res.ok) {+ anySuccess = true;+ globalResolve!(res.response!);+ for (const [idx, ac] of abortControllers.entries()) {+ if (idx !== i) ac.abort();+ }+ } else if (res.response) {+ // Fatal error, abort combo+ anySuccess = true;+ globalResolve!(res.response);}- } else if (res.response) {- // Fatal error, abort combo- anySuccess = true;- globalResolve!(res.response);}+ } finally {+ signal?.removeEventListener("abort", onClientAbort);}- } finally {- signal?.removeEventListener("abort", onClientAbort);+ })().catch((err) => {+ const logError = log.error ?? log.warn;+ logError("COMBO", `Speculative task error for target ${i}`, err);+ });++ runningTasks.add(task);+ task.finally(() => runningTasks.delete(task));++ if (zeroLatencyOptimizationsEnabled && config.hedging && i + 1 < orderedTargets.length) {+ const hedgeDelay = resolveDelayMs(config.hedgeDelayMs, 500);+ let timeoutResolve: () => void;+ const timeoutPromise = new Promise<void>((r) => {+ timeoutResolve = r;+ setTimeout(r, hedgeDelay);+ });+ await Promise.race([task, globalPromise, timeoutPromise]);+ } else {+ await Promise.race([task, globalPromise]);}- })().catch((err) => {- const logError = log.error ?? log.warn;- logError("COMBO", `Speculative task error for target ${i}`, err);- });+ }++ if (!anySuccess && runningTasks.size > 0) {+ await Promise.race([globalPromise, Promise.all([...runningTasks])]);+ }- runningTasks.add(task);- task.finally(() => runningTasks.delete(task));+ if (anySuccess) {+ return await globalPromise;+ }- if (zeroLatencyOptimizationsEnabled && config.hedging && i + 1 < orderedTargets.length) {- const hedgeDelay = resolveDelayMs(config.hedgeDelayMs, 500);- let timeoutResolve: () => void;- const timeoutPromise = new Promise<void>((r) => {- timeoutResolve = r;- setTimeout(r, hedgeDelay);+ // All models failed in this set try+ const latencyMs = Date.now() - startTime;+ if (recordedAttempts === 0) {+ recordComboRequest(combo.name, null, {+ success: false,+ latencyMs,+ fallbackCount,+ strategy,});- await Promise.race([task, globalPromise, timeoutPromise]);- } else {- await Promise.race([task, globalPromise]);}- }- if (!anySuccess && runningTasks.size > 0) {- await Promise.race([globalPromise, Promise.all([...runningTasks])]);- }+ // Retry the entire set if more attempts remain+ if (setTry < maxSetRetries) continue;- if (anySuccess) {- return await globalPromise;- }+ // All set retries exhausted — return the final error+ if (!lastStatus) {+ notifyWebhookEvent("request.failed", {+ combo: combo.name,+ reason: "ALL_ACCOUNTS_INACTIVE",+ latencyMs,+ fallbackCount,+ });+ return new Response(+ JSON.stringify({+ error: {+ message: "Service temporarily unavailable: all upstream accounts are inactive",+ type: "service_unavailable",+ code: "ALL_ACCOUNTS_INACTIVE",+ },+ }),+ { status: 503, headers: { "Content-Type": "application/json" } }+ );+ }- // All models failed in this set try- const latencyMs = Date.now() - startTime;- if (recordedAttempts === 0) {- recordComboRequest(combo.name, null, { success: false, latencyMs, fallbackCount, strategy });- }+ const status = lastStatus;+ const msg = lastError || "All combo models unavailable";- // Retry the entire set if more attempts remain- if (setTry < maxSetRetries) continue;+ if (earliestRetryAfter) {+ const retryHuman = formatRetryAfter(toRetryAfterDisplayValue(earliestRetryAfter));+ log.warn("COMBO", `All models failed | ${msg} (${retryHuman})`);+ return unavailableResponse(status, msg, earliestRetryAfter, retryHuman);+ }- // All set retries exhausted — return the final error- if (!lastStatus) {- notifyWebhookEvent("request.failed", {- combo: combo.name,- reason: "ALL_ACCOUNTS_INACTIVE",- latencyMs,- fallbackCount,+ log.warn("COMBO", `All models failed | ${msg}`);+ return new Response(JSON.stringify({ error: { message: msg } }), {+ status,+ headers: { "Content-Type": "application/json" },});- return new Response(- JSON.stringify({- error: {- message: "Service temporarily unavailable: all upstream accounts are inactive",- type: "service_unavailable",- code: "ALL_ACCOUNTS_INACTIVE",- },- }),- { status: 503, headers: { "Content-Type": "application/json" } }- );- }-- const status = lastStatus;- const msg = lastError || "All combo models unavailable";-- if (earliestRetryAfter) {- const retryHuman = formatRetryAfter(toRetryAfterDisplayValue(earliestRetryAfter));- log.warn("COMBO", `All models failed | ${msg} (${retryHuman})`);- return unavailableResponse(status, msg, earliestRetryAfter, retryHuman);}- log.warn("COMBO", `All models failed | ${msg}`);- return new Response(JSON.stringify({ error: { message: msg } }), {- status,- headers: { "Content-Type": "application/json" },- });- }-- return errorResponse(503, "Combo routing completed without an upstream response");+ return errorResponse(503, "Combo routing completed without an upstream response");} finally {// G2: Clean up candidate registry to prevent unbounded memory growth._unregisterExecutionCandidates(_registeredExecutionKeys);@@ -4105,7 +4194,10 @@ async function handleRoundRobinCombo({if (isModelAvailable) {const available = await isModelAvailable(modelStr, targetForAttempt);if (!available) {- log.debug?.("COMBO-RR", `Skipping ${modelStr} — no credentials available or model excluded`);+ log.debug?.(+ "COMBO-RR",+ `Skipping ${modelStr} — no credentials available or model excluded`+ );if (offset > 0) fallbackCount++;continue;}@@ -4346,7 +4438,10 @@ async function handleRoundRobinCombo({isAllAccountsRateLimited);if (providerExhausted) {exhaustedProviders.add(provider);- log.debug?.("COMBO-RR", `Provider ${provider} quota exhausted — marking for skip (#1731)`);+ log.debug?.(+ "COMBO-RR",+ `Provider ${provider} quota exhausted — marking for skip (#1731)`+ );} else if (result.status === 429 &&!isTokenLimitBreach &&diff --git a/open-sse/services/inAppLoginService.ts b/open-sse/services/inAppLoginService.tsnew file mode 100644index 0000000000..0a71b99929--- /dev/null+++ b/open-sse/services/inAppLoginService.ts@@ -0,0 +1,256 @@+/**+ * InAppLoginService — Playwright-based web login for cookie providers+ *+ * Opens a Playwright browser context, navigates to the provider's login page,+ * and polls for target cookies/tokens after the user completes login.+ *+ * Used as the dashboard/web fallback path when Electron is not available.+ * For Electron-native login, see electron/loginManager.js.+ *+ * Events:+ * "status" — { providerId: string, status: string, message: string }+ * status values: starting, navigating, waiting, polling, complete, error, cancelled+ */++import { EventEmitter } from "events";+import { TOKEN_EXTRACTION_CONFIGS, TokenExtractionConfig, type TokenSource } from "./tokenExtractionConfig";++// ─── Types ──────────────────────────────────────────────────────────────────++export interface LoginResult {+ success: boolean;+ credentials?: Record<string, string>;+ error?: string;+}++interface ActiveLogin {+ providerId: string;+ aborted: boolean;+}++// ─── Service ────────────────────────────────────────────────────────────────++export class InAppLoginService extends EventEmitter {+ private activeLogin: ActiveLogin | null = null;++ /**+ * Start a login flow for a web-cookie provider using Playwright.+ * @param providerId - e.g. "claude-web", "chatgpt-web"+ * @param options.timeout - Total timeout in ms (default: config value or 300s)+ */+ async startLogin(providerId: string, options?: { timeout?: number }): Promise<LoginResult> {+ const config = TOKEN_EXTRACTION_CONFIGS.get(providerId);+ if (!config) {+ this.emit("status", { providerId, status: "error", message: "No extraction config found" });+ return { success: false, error: `No extraction config for provider: ${providerId}` };+ }++ if (this.activeLogin) {+ this.emit("status", { providerId, status: "error", message: "A login is already in progress" });+ return { success: false, error: "A login process is already in progress" };+ }++ this.activeLogin = { providerId, aborted: false };+ this.emit("status", { providerId, status: "starting", message: `Opening ${config.displayName} login...` });++ try {+ const result = await this.runBrowserLogin(config, options?.timeout);+ this.emit("status", {+ providerId,+ status: result.success ? "complete" : "error",+ message: result.success ? "Credentials extracted successfully" : (result.error || "Login failed"),+ });+ return result;+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ this.emit("status", { providerId, status: "error", message });+ return { success: false, error: `Login failed: ${message}` };+ } finally {+ this.activeLogin = null;+ }+ }++ /**+ * Run the actual Playwright browser login flow+ */+ private async runBrowserLogin(+ config: TokenExtractionConfig,+ timeout?: number+ ): Promise<LoginResult> {+ const pollInterval = config.pollingConfig.pollInterval || 1000;+ const maxTimeout = timeout || config.pollingConfig.timeout || 300_000;+ const minLoginTime = config.pollingConfig.minLoginTime || 5000;+ const providerId = config.providerId;++ // Dynamically import Playwright (it's a heavy dep, only load when needed)+ let playwright: any;+ try {+ playwright = await import("playwright");+ } catch {+ return { success: false, error: "Playwright is not installed. Use Electron for native login." };+ }++ if (this.activeLogin?.aborted) {+ return { success: false, error: "Login cancelled" };+ }++ // Launch browser+ this.emit("status", { providerId, status: "starting", message: "Launching browser..." });+ const browser = await playwright.chromium.launch({+ headless: false, // User must interact with the login page+ });++ try {+ const context = await browser.newContext({+ viewport: { width: 1280, height: 800 },+ locale: "en-US",+ });+ const page = await context.newPage();++ // Navigate to login URL+ this.emit("status", { providerId, status: "navigating", message: `Loading ${config.loginUrl}` });+ await page.goto(config.loginUrl, { waitUntil: "domcontentloaded", timeout: 30000 });++ // Poll for success URL + token extraction+ const maxPolls = Math.floor(maxTimeout / pollInterval);+ const credentials: Record<string, string> = {};+ const startTime = Date.now();++ for (let i = 0; i < maxPolls; i++) {+ if (this.activeLogin?.aborted) {+ this.emit("status", { providerId, status: "cancelled", message: "Login cancelled by user" });+ return { success: false, error: "Login cancelled" };+ }++ // Emit progress every 30 seconds+ if (i > 0 && i % 30 === 0) {+ this.emit("status", {+ providerId,+ status: "waiting",+ message: `Waiting for login... (${Math.round(i / 60)}m)`,+ });+ }++ // Wait before polling (respect minLoginTime on first iteration)+ if (Date.now() - startTime < minLoginTime) {+ await sleep(pollInterval);+ continue;+ }++ // Gather cookies from browser context+ const cookies = await context.cookies();+ const tokenSources = config.tokenSources;++ // Check cookie-based sources+ for (const source of tokenSources) {+ if (source.type === "cookie") {+ const domain = source.domain || undefined;+ const matched = cookies.find(+ (c: any) =>+ c.name === source.name &&+ (!domain || c.domain.includes(domain.replace(/^\./, "")))+ );+ if (matched && !credentials[source.name]) {+ credentials[source.name] = matched.value;+ }+ }+ }++ // Check localStorage-based tokens+ for (const source of tokenSources) {+ if (source.type === "localStorage" && !credentials[source.key]) {+ try {+ const value = await page.evaluate((key: string) => localStorage.getItem(key), source.key);+ if (value && typeof value === "string") {+ credentials[source.key] = value;+ }+ } catch {+ // localStorage access may fail on some domains+ }+ }+ if (source.type === "sessionStorage" && !credentials[source.key]) {+ try {+ const value = await page.evaluate((key: string) => sessionStorage.getItem(key), source.key);+ if (value && typeof value === "string") {+ credentials[source.key] = value;+ }+ } catch {+ // sessionStorage access may fail on some domains+ }+ }+ }++ // Check if all required tokens are found+ const requiredKeys = tokenSources.map((s) =>+ s.type === "cookie" ? s.name : s.type === "localStorage" || s.type === "sessionStorage" ? s.key : s.name+ );+ const allFound = requiredKeys.every((k) => credentials[k] !== undefined);++ if (allFound && Object.keys(credentials).length > 0) {+ return { success: true, credentials };+ }++ // Check for success URL pattern+ if (config.successUrlPattern) {+ try {+ const currentUrl = page.url();+ if (config.successUrlPattern.test(currentUrl) && Object.keys(credentials).length > 0) {+ return { success: true, credentials };+ }+ } catch {+ // URL access may fail on some pages+ }+ }++ await sleep(pollInterval);+ }++ return { success: false, error: "Login timed out" };+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ this.emit("status", { providerId, status: "error", message });+ return { success: false, error: `Login failed: ${message}` };+ } finally {+ await browser.close().catch(() => {});+ }+ }++ /**+ * Cancel the current login flow+ */+ cancel(): void {+ if (this.activeLogin) {+ this.emit("status", {+ providerId: this.activeLogin.providerId,+ status: "cancelled",+ message: "Login cancelled by user",+ });+ this.activeLogin.aborted = true;+ this.activeLogin = null;+ }+ }++ /**+ * Get the active provider ID, if any+ */+ getActiveProvider(): string | null {+ return this.activeLogin?.providerId || null;+ }++ /**+ * Check if a login flow is in progress+ */+ isActive(): boolean {+ return this.activeLogin !== null && !this.activeLogin.aborted;+ }+}++// ─── Sleep helper ───────────────────────────────────────────────────────────++function sleep(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++// ─── Singleton ──────────────────────────────────────────────────────────────++export const inAppLoginService = new InAppLoginService();diff --git a/open-sse/services/rateLimitManager.ts b/open-sse/services/rateLimitManager.tsindex c5a4a181ae..f967b3fd97 100644--- a/open-sse/services/rateLimitManager.ts+++ b/open-sse/services/rateLimitManager.ts@@ -73,6 +73,10 @@ const limiters = new Map<string, Bottleneck>();// Store connections that have rate limit protection enabledconst enabledConnections = new Set<string>();+// Store per-connection rate limit overrides (RPM, TPM, TPD, minTime, maxConcurrent)+// Populated from provider_connections.rateLimitOverrides on startup and refresh.+const connectionRateLimitOverrides = new Map<string, Record<string, number>>();+// Store learned limits for persistence (debounced)const learnedLimits: Record<string, LearnedLimitEntry> = {};const MAX_LEARNED_LIMITS = 200;@@ -115,12 +119,40 @@ function isAutoEnableActive(settings: RequestQueueSettings): boolean {return settings.autoEnableApiKeyProviders;}+// Sentinels for "no rate limit" / effectively infinite capacity. The reservoir+// value uses Number.MAX_SAFE_INTEGER so the bucket can never realistically be+// exhausted; maxConcurrent uses a smaller-but-still-vast ceiling since+// Bottleneck tracks concurrent jobs in memory and an unbounded number would+// risk internal counter overflow under sustained pressure.+const EFFECTIVELY_INFINITE = Number.MAX_SAFE_INTEGER;+const EFFECTIVELY_INFINITE_CONCURRENCY = 1000;++// Resolve an RPM override. 0 or missing means "infinite" (no rate cap).+function resolveRpm(override: number | undefined | null): number {+ return typeof override === "number" && override > 0 ? override : EFFECTIVELY_INFINITE;+}++// Resolve a minTime override. 0 or missing means "no minimum gap".+function resolveMinTime(override: number | undefined | null): number {+ return typeof override === "number" && override > 0 ? override : 0;+}++// Resolve a maxConcurrent override. 0 or missing means "effectively infinite".+function resolveMaxConcurrent(override: number | undefined | null): number {+ return typeof override === "number" && override > 0+ ? override+ : EFFECTIVELY_INFINITE_CONCURRENCY;+}+function buildLimiterDefaults() {+ // 0 or missing values mean "infinite" / no rate limit applies. This treats+ // the global request-queue settings the same way per-connection overrides+ // are interpreted (see resolveRpm / resolveMinTime / resolveMaxConcurrent).return {- maxConcurrent: currentRequestQueueSettings.concurrentRequests,- minTime: currentRequestQueueSettings.minTimeBetweenRequestsMs,- reservoir: currentRequestQueueSettings.requestsPerMinute,- reservoirRefreshAmount: currentRequestQueueSettings.requestsPerMinute,+ maxConcurrent: resolveMaxConcurrent(currentRequestQueueSettings.concurrentRequests),+ minTime: resolveMinTime(currentRequestQueueSettings.minTimeBetweenRequestsMs),+ reservoir: resolveRpm(currentRequestQueueSettings.requestsPerMinute),+ reservoirRefreshAmount: resolveRpm(currentRequestQueueSettings.requestsPerMinute),reservoirRefreshInterval: 60 * 1000,};}@@ -316,6 +348,15 @@ export async function initializeRateLimits() {);updateAllLimiterSettings();+ // Load per-connection rate limit overrides+ connectionRateLimitOverrides.clear();+ for (const conn of connections as Array<Record<string, unknown>>) {+ const overrides = conn.rateLimitOverrides;+ if (overrides && typeof overrides === "object" && !Array.isArray(overrides)) {+ connectionRateLimitOverrides.set(String(conn.id), overrides as Record<string, number>);+ }+ }+if (explicitCount > 0 || autoCount > 0) {logRateLimit(`🛡️ [RATE-LIMIT] Loaded ${explicitCount} explicit + ${autoCount} auto-enabled protection(s)`@@ -342,7 +383,7 @@ export async function applyRequestQueueSettings(nextSettings: RequestQueueSettin}/**- * Enable rate limit protection for a connection+ * Get or create a limiter for a given provider+connection combination*/export function enableRateLimitProtection(connectionId) {enabledConnections.add(connectionId);@@ -378,6 +419,33 @@ export function isRateLimitEnabled(connectionId) {return enabledConnections.has(connectionId);}+/**+ * Refresh per-connection rate limit overrides.+ *+ * Called after a PATCH update to `rateLimitOverrides` on a provider connection.+ * Updates the in-memory map and evicts existing Bottleneck limiters for the+ * connection so the next request gets a fresh limiter with the new settings.+ *+ * @param {string} connectionId+ * @param {Record<string, number> | null} overrides - New overrides (null/undefined clears)+ */+export function refreshConnectionRateLimits(connectionId, overrides) {+ if (overrides === null || overrides === undefined) {+ connectionRateLimitOverrides.delete(connectionId);+ } else {+ connectionRateLimitOverrides.set(connectionId, overrides);+ }+ // Evict limiters referencing this connection so they get recreated on next use+ for (const [key, limiter] of Array.from(limiters)) {+ if (key.includes(connectionId)) {+ limiters.delete(key);+ lastDispatchAt.delete(key);+ limiterLastUsed.delete(key);+ trackAsyncOperation(limiter.disconnect());+ }+ }+}+/*** Get or create a limiter for a given provider+connection combination*/@@ -397,20 +465,33 @@ function getLimiter(provider, connectionId, model = null) {const key = getLimiterKey(provider, connectionId, model);if (!limiters.has(key)) {+ const defaults = buildLimiterDefaults();+ const overrides = connectionRateLimitOverrides.get(connectionId);+ if (overrides) {+ // 0 (or missing) means "no override — fall through to buildLimiterDefaults()".+ // Without this guard, an rpm of 0 sets reservoir=0, which Bottleneck treats+ // as "depleted" and blocks ALL requests indefinitely. Treating 0 as "use+ // default" lets users effectively disable per-connection limits without+ // globally raising the system default.+ if (typeof overrides.maxConcurrent === "number" && overrides.maxConcurrent > 0) {+ defaults.maxConcurrent = overrides.maxConcurrent;+ }+ if (typeof overrides.minTime === "number" && overrides.minTime > 0) {+ defaults.minTime = overrides.minTime;+ }+ if (typeof overrides.rpm === "number" && overrides.rpm > 0) {+ defaults.reservoir = overrides.rpm;+ defaults.reservoirRefreshAmount = overrides.rpm;+ defaults.reservoirRefreshInterval = 60 * 1000;+ }+ // TODO: TPM/TPD integration — requires a token-bucket vs request-bucket+ // separation (Bottleneck's reservoir is request-count, not token-count).+ // When added, treat 0/missing the same way: fall through to system default.+ }const limiter = new Bottleneck({- ...buildLimiterDefaults(),+ ...defaults,id: key,});-- // Log when jobs are queued- limiter.on("queued", () => {- const counts = limiter.counts();- if (counts.QUEUED > 0) {- logRateLimit(- `⏳ [RATE-LIMIT] ${key} — ${counts.QUEUED} request(s) queued, ${counts.RUNNING} running`- );- }- });// Heartbeat: timestamp every dispatch so the watchdog can tell a healthy// queue (just dispatched a job) from a wedged one (queue has work but// nothing has been dispatched in a while).diff --git a/open-sse/services/tokenExtractionConfig.ts b/open-sse/services/tokenExtractionConfig.tsnew file mode 100644index 0000000000..d9f6f0a86c--- /dev/null+++ b/open-sse/services/tokenExtractionConfig.ts@@ -0,0 +1,411 @@+/**+ * TokenExtractionConfig — Login & cookie extraction configs for web-cookie providers+ *+ * Each config describes how to:+ * 1. Open a browser window/navigate to the provider's login page+ * 2. Detect successful login (URL change + token presence)+ * 3. Extract session cookies / tokens from the browser context+ *+ * Used by InAppLoginService (Electron BrowserWindow path) and+ * the Playwright-based login flow (dashboard API).+ */++// ─── Types ──────────────────────────────────────────────────────────────────++/** Describes where to extract credential data from after login */+export type TokenSource =+ | { type: "cookie"; name: string; domain?: string }+ | { type: "localStorage"; key: string }+ | { type: "sessionStorage"; key: string }+ | { type: "header"; name: string };++export interface PollingConfig {+ /** Milliseconds between extraction polls (default 1000) */+ pollInterval: number;+ /** Total timeout in ms (default 300000 = 5 min) */+ timeout: number;+ /** Minimum time in ms before first extraction attempt (default 5000) */+ minLoginTime: number;+}++export interface TokenExtractionConfig {+ /** Matches the executor's provider ID (e.g. "claude-web", "gemini-web") */+ providerId: string;+ /** Human-readable name shown in dashboard UI */+ displayName: string;+ /** The URL to navigate to for login */+ loginUrl: string;+ /** The provider's home page URL (for cookie domain binding) */+ homeUrl: string;+ /** Optional regex. If current URL matches → login is likely complete */+ successUrlPattern?: RegExp;+ /** Sources to extract credentials from after login */+ tokenSources: TokenSource[];+ /** Polling behaviour */+ pollingConfig: PollingConfig;+ /** Short instructions shown to the user in the login modal */+ instructions: string;+ /** Optional: cookie domain override for cookie injection */+ cookieDomain?: string;+}++// ─── Defaults ───────────────────────────────────────────────────────────────++const DEFAULT_POLLING: PollingConfig = {+ pollInterval: 1000,+ timeout: 300_000,+ minLoginTime: 5000,+};++const QUICK_POLLING: PollingConfig = {+ pollInterval: 800,+ timeout: 120_000,+ minLoginTime: 3000,+};++// ─── Helper ──────────────────────────────────────────────────────────────────++function config(+ providerId: string,+ displayName: string,+ loginUrl: string,+ homeUrl: string,+ tokenSources: TokenSource[],+ instructions: string,+ opts?: {+ successUrlPattern?: RegExp;+ pollingConfig?: Partial<PollingConfig>;+ cookieDomain?: string;+ }+): TokenExtractionConfig {+ return {+ providerId,+ displayName,+ loginUrl,+ homeUrl,+ tokenSources,+ instructions,+ pollingConfig: { ...DEFAULT_POLLING, ...opts?.pollingConfig },+ successUrlPattern: opts?.successUrlPattern,+ cookieDomain: opts?.cookieDomain,+ };+}++// ─── Configuration Map ──────────────────────────────────────────────────────++const RAW_CONFIGS: TokenExtractionConfig[] = [+ // ── Claude Web ────────────────────────────────────────────+ config(+ "claude-web",+ "Claude Web",+ "https://claude.ai/login",+ "https://claude.ai",+ [{ type: "cookie", name: "sessionKey", domain: ".claude.ai" }],+ "Log in to your Claude account at claude.ai. After login, the session cookie will be extracted automatically."+ ),++ // ── ChatGPT Web ───────────────────────────────────────────+ config(+ "chatgpt-web",+ "ChatGPT Web",+ "https://chatgpt.com/auth/login",+ "https://chatgpt.com",+ [+ { type: "cookie", name: "__Secure-next-auth.session-token", domain: ".chatgpt.com" },+ ],+ "Log in to ChatGPT. The __Secure-next-auth.session-token cookie will be extracted after login."+ ),++ // ── Gemini Web ────────────────────────────────────────────+ config(+ "gemini-web",+ "Gemini Web",+ "https://gemini.google.com/app",+ "https://gemini.google.com",+ [+ { type: "cookie", name: "__Secure-1PSID", domain: ".google.com" },+ { type: "cookie", name: "__Secure-1PSIDTS", domain: ".google.com" },+ ],+ "Log in to your Google account at gemini.google.com. Both __Secure-1PSID and __Secure-1PSIDTS cookies will be extracted.",+ { cookieDomain: ".google.com" }+ ),++ // ── Grok Web ──────────────────────────────────────────────+ config(+ "grok-web",+ "Grok Web",+ "https://grok.com/login",+ "https://grok.com",+ [{ type: "cookie", name: "sso", domain: ".grok.com" }],+ "Log in to your xAI account at grok.com. The sso session cookie will be extracted."+ ),++ // ── Perplexity Web ────────────────────────────────────────+ config(+ "perplexity-web",+ "Perplexity Web",+ "https://www.perplexity.ai/login",+ "https://www.perplexity.ai",+ [+ { type: "cookie", name: "__Secure-next-auth.session-token", domain: ".perplexity.ai" },+ ],+ "Log in to Perplexity. The __Secure-next-auth.session-token cookie will be extracted.",+ { cookieDomain: ".perplexity.ai" }+ ),++ // ── DeepSeek Web ──────────────────────────────────────────+ config(+ "deepseek-web",+ "DeepSeek Web",+ "https://chat.deepseek.com/sign_in",+ "https://chat.deepseek.com",+ [+ { type: "cookie", name: "user-token", domain: ".deepseek.com" },+ { type: "localStorage", key: "userToken" },+ ],+ "Log in to DeepSeek at chat.deepseek.com. The user-token cookie will be extracted.",+ { cookieDomain: ".deepseek.com" }+ ),++ // ── Qwen Web ──────────────────────────────────────────────+ config(+ "qwen-web",+ "Qwen Web (Tongyi)",+ "https://chat.qwen.ai/",+ "https://chat.qwen.ai",+ [+ { type: "cookie", name: "XSRF_TOKEN", domain: ".chat.qwen.ai" },+ { type: "localStorage", key: "token" },+ ],+ "Log in to Qwen at chat.qwen.ai using your Alibaba account. The session token will be extracted.",+ { cookieDomain: ".chat.qwen.ai" }+ ),++ // ── Kimi Web ──────────────────────────────────────────────+ config(+ "kimi-web",+ "Kimi (Moonshot)",+ "https://kimi.moonshot.cn/",+ "https://kimi.moonshot.cn",+ [+ { type: "cookie", name: "kimi_token", domain: ".kimi.moonshot.cn" },+ { type: "localStorage", key: "kimi_token" },+ ],+ "Log in to Kimi at kimi.moonshot.cn via phone/WeChat. The session token will be extracted.",+ { cookieDomain: ".kimi.moonshot.cn" }+ ),++ // ── Blackbox Web ──────────────────────────────────────────+ config(+ "blackbox-web",+ "Blackbox AI",+ "https://app.blackbox.ai/login",+ "https://app.blackbox.ai",+ [+ { type: "cookie", name: "connect.sid", domain: ".blackbox.ai" },+ { type: "localStorage", key: "token" },+ ],+ "Log in to Blackbox AI at app.blackbox.ai using Google/GitHub. The session cookie will be extracted.",+ { cookieDomain: ".blackbox.ai" }+ ),++ // ── Poe Web ───────────────────────────────────────────────+ config(+ "poe-web",+ "Poe (Quora)",+ "https://poe.com/login",+ "https://poe.com",+ [+ { type: "cookie", name: "p-b", domain: ".poe.com" },+ ],+ "Log in to Poe at poe.com. The session cookie will be extracted.",+ { cookieDomain: ".poe.com" }+ ),++ // ── Copilot Web ───────────────────────────────────────────+ config(+ "copilot-web",+ "Microsoft Copilot",+ "https://copilot.microsoft.com/",+ "https://copilot.microsoft.com",+ [+ { type: "cookie", name: "RPSCAuth", domain: ".microsoft.com" },+ ],+ "Log in with your Microsoft account at copilot.microsoft.com. The session auth cookie will be extracted.",+ { cookieDomain: ".microsoft.com" }+ ),++ // ── DuckDuckGo Web ────────────────────────────────────────+ config(+ "duckduckgo-web",+ "DuckDuckGo AI Chat",+ "https://duckduckgo.com/?q=DuckDuckGo+AI+Chat&ia=chat&duckai=1",+ "https://duckduckgo.com",+ [+ { type: "cookie", name: "duckai", domain: ".duckduckgo.com" },+ ],+ "Open DuckDuckGo AI Chat. Some models may require a free account. The duckai cookie will be extracted.",+ {+ cookieDomain: ".duckduckgo.com",+ pollingConfig: QUICK_POLLING,+ }+ ),++ // ── DouBao Web ────────────────────────────────────────────+ config(+ "doubao-web",+ "DouBao (ByteDance)",+ "https://www.doubao.com/",+ "https://www.doubao.com",+ [+ { type: "cookie", name: "sessionid", domain: ".doubao.com" },+ ],+ "Log in to DouBao at doubao.com with your ByteDance account. The sessionid will be extracted.",+ { cookieDomain: ".doubao.com" }+ ),++ // ── T3 Chat Web ───────────────────────────────────────────+ config(+ "t3-chat-web",+ "T3 Chat",+ "https://t3.chat/login",+ "https://t3.chat",+ [+ { type: "localStorage", key: "token" },+ ],+ "Log in to T3 Chat at t3.chat using Google/GitHub. The token from localStorage will be extracted.",+ { pollingConfig: QUICK_POLLING }+ ),++ // ── Venice Web ────────────────────────────────────────────+ config(+ "venice-web",+ "Venice AI",+ "https://venice.ai/login",+ "https://venice.ai",+ [+ { type: "cookie", name: "venice_session", domain: ".venice.ai" },+ { type: "localStorage", key: "token" },+ ],+ "Log in to Venice AI at venice.ai. The session cookie will be extracted.",+ { cookieDomain: ".venice.ai" }+ ),++ // ── v0 Dev Web ────────────────────────────────────────────+ config(+ "v0-vercel-web",+ "v0 by Vercel",+ "https://v0.dev/login",+ "https://v0.dev",+ [+ { type: "cookie", name: "__Secure-next-auth.session-token", domain: ".v0.dev" },+ ],+ "Log in to v0.dev with your Vercel/Google/GitHub account. The session cookie will be extracted.",+ { cookieDomain: ".v0.dev" }+ ),++ // ── Muse / Spark Web ──────────────────────────────────────+ config(+ "muse-spark-web",+ "Meta AI (Muse)",+ "https://www.meta.ai/",+ "https://www.meta.ai",+ [+ { type: "cookie", name: "session", domain: ".meta.ai" },+ ],+ "Log in to Meta AI at meta.ai with your Facebook/Instagram account. The session cookie will be extracted.",+ { cookieDomain: ".meta.ai" }+ ),++ // ── Adapta Web ────────────────────────────────────────────+ config(+ "adapta-web",+ "Adapta AI",+ "https://agent.adapta.one/login",+ "https://agent.adapta.one",+ [+ { type: "cookie", name: "__session", domain: ".adapta.one" },+ ],+ "Log in to Adapta at agent.adapta.one. The session token will be extracted.",+ { cookieDomain: ".adapta.one" }+ ),++ // ── VeoAI Free Web ────────────────────────────────────────+ config(+ "veoaifree-web",+ "VeoAI Free",+ "https://veoaifree.com/",+ "https://veoaifree.com",+ [+ { type: "cookie", name: "wordpress_logged_in", domain: ".veoaifree.com" },+ ],+ "Log in to VeoAI Free at veoaifree.com. The WordPress session cookie will be extracted.",+ {+ cookieDomain: ".veoaifree.com",+ pollingConfig: QUICK_POLLING,+ }+ ),++ // ── Missing Provider: ChatGLM (Zhipu) ──────────────────────+ config(+ "chatglm-web",+ "ChatGLM (Zhipu AI)",+ "https://chatglm.cn/",+ "https://chatglm.cn",+ [+ { type: "cookie", name: "chatglm_session", domain: ".chatglm.cn" },+ { type: "localStorage", key: "token" },+ ],+ "Log in to ChatGLM at chatglm.cn with your phone number. The session token will be extracted.",+ { cookieDomain: ".chatglm.cn" }+ ),++ // ── Missing Provider: Xiaomi MiMo ──────────────────────────+ config(+ "xiaomimimo-web",+ "Xiaomi MiMo AI Studio",+ "https://aistudio.xiaomimimo.com/login",+ "https://aistudio.xiaomimimo.com",+ [+ { type: "cookie", name: "session", domain: ".xiaomimimo.com" },+ { type: "localStorage", key: "access_token" },+ ],+ "Log in to Xiaomi MiMo AI Studio at aistudio.xiaomimimo.com. The session token will be extracted.",+ { cookieDomain: ".xiaomimimo.com" }+ ),++ // ── Missing Provider: Manus ────────────────────────────────+ config(+ "manus-web",+ "Manus AI",+ "https://manus.im/login",+ "https://manus.im",+ [+ { type: "cookie", name: "manus_session", domain: ".manus.im" },+ { type: "localStorage", key: "auth_token" },+ ],+ "Log in to Manus at manus.im. The session cookie will be extracted.",+ { cookieDomain: ".manus.im" }+ ),+];++// ─── Registry ───────────────────────────────────────────────────────────────++const CONFIG_MAP = new Map<string, TokenExtractionConfig>();++for (const cfg of RAW_CONFIGS) {+ CONFIG_MAP.set(cfg.providerId, cfg);+}++/** Get extraction config for a specific provider */+export function getExtractionConfig(providerId: string): TokenExtractionConfig | undefined {+ return CONFIG_MAP.get(providerId);+}++/** List all registered extraction configs */+export function listExtractionConfigs(): TokenExtractionConfig[] {+ return [...RAW_CONFIGS];+}++/** The shared config map — used by LoginManager and InAppLoginService */+export const TOKEN_EXTRACTION_CONFIGS = CONFIG_MAP;diff --git a/open-sse/utils/stream.ts b/open-sse/utils/stream.tsindex 407b0600f1..0cb878a3c9 100644--- a/open-sse/utils/stream.ts+++ b/open-sse/utils/stream.ts@@ -25,6 +25,7 @@ import {} from "./streamPayloadCollector.ts";import { STREAM_IDLE_TIMEOUT_MS, FETCH_BODY_TIMEOUT_MS, HTTP_STATUS } from "../config/constants.ts";import {+ OMIT_STREAMING_CHUNK_MARKER,sanitizeStreamingChunk,extractThinkingFromContent,} from "../handlers/responseSanitizer.ts";@@ -1600,6 +1601,36 @@ export function createSSEStream(options: StreamOptions = {}) {} else {// Chat Completions: full sanitization pipeline+ // Hardening: detect upstream returning empty choices array+ // which breaks OpenAI-compatible clients (e.g. Copilot Chat)+ if (Array.isArray(parsed.choices) && parsed.choices.length === 0) {+ console.warn(+ `[STREAM] Upstream returned empty choices array (${provider || "provider"}:${model || "unknown"}) — emitting error chunk`+ );+ const errorChunk = {+ id: parsed.id || `omniroute-empty-choices-${Date.now()}`,+ object: "chat.completion.chunk",+ created: parsed.created || Math.floor(Date.now() / 1000),+ model: parsed.model || model || "unknown",+ choices: [+ {+ index: 0,+ delta: {+ role: "assistant",+ content: "[OmniRoute] Upstream returned an empty response. Please retry.",+ },+ finish_reason: "stop",+ },+ ],+ };+ output = `data: ${JSON.stringify(errorChunk)}\n`;+ injectedUsage = true;+ clientPayload = errorChunk;+ reqLogger?.appendConvertedChunk?.(output);+ controller.enqueue(encoder.encode(output));+ continue;+ }+// Detect reasoning alias before sanitization strips itconst hadReasoningAlias = !!(parsed.choices?.[0]?.delta?.reasoning &&@@ -1608,6 +1639,14 @@ export function createSSEStream(options: StreamOptions = {}) {);parsed = sanitizeStreamingChunk(parsed);+ if (+ parsed &&+ typeof parsed === "object" &&+ !Array.isArray(parsed) &&+ (parsed as Record<string, unknown>)[OMIT_STREAMING_CHUNK_MARKER] === true+ ) {+ continue;+ }const idFixed = fixInvalidId(parsed);@@ -2118,6 +2157,14 @@ export function createSSEStream(options: StreamOptions = {}) {(a, b) => a.index - b.index);}+ // Hardening: log empty assistant response after tool completion+ // for observability — helps diagnose Copilot "Sorry, no response was returned"+ if (passthroughHasToolCalls && !content.trim() && !reasoning.trim()) {+ console.warn(+ `[STREAM] Empty assistant response after tool_calls completion (${provider || "provider"}:${model || "unknown"}) — sessionId=${sessionId}`+ );+ }+const responseBody = {choices: [{diff --git a/package-lock.json b/package-lock.jsonindex 50bf945f27..53977e033e 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "omniroute",- "version": "3.8.12",+ "version": "3.8.13","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "omniroute",- "version": "3.8.12",+ "version": "3.8.13","hasInstallScript": true,"license": "MIT","workspaces": [@@ -21467,7 +21467,7 @@},"open-sse": {"name": "@omniroute/open-sse",- "version": "3.8.12"+ "version": "3.8.13"}}}diff --git a/package.json b/package.jsonindex 269c95b51d..89dad24a8c 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "omniroute",- "version": "3.8.12",+ "version": "3.8.13","description": "Unified AI router with 160+ providers, RTK+Caveman compression, auto fallback, MCP/A2A, desktop, PWA, and OpenAI-compatible APIs.","type": "module","bin": {diff --git a/scripts/build/bootstrap-env.mjs b/scripts/build/bootstrap-env.mjsindex c39e9b9107..54d4f8d3c6 100644--- a/scripts/build/bootstrap-env.mjs+++ b/scripts/build/bootstrap-env.mjs@@ -67,6 +67,21 @@ function getPreferredEnvFilePath(env = process.env) {return candidates.find((filePath) => existsSync(filePath)) ?? null;}+function isNativeSqliteLoadError(error) {+ const message = error instanceof Error ? error.message : String(error);+ const code = error && typeof error === "object" && "code" in error ? error.code : undefined;++ return (+ message.includes("Module did not self-register") ||+ message.includes("NODE_MODULE_VERSION") ||+ message.includes("ERR_DLOPEN_FAILED") ||+ message.includes("Could not locate the bindings file") ||+ message.includes("Cannot find module 'better-sqlite3'") ||+ code === "ERR_DLOPEN_FAILED" ||+ code === "MODULE_NOT_FOUND"+ );+}+function hasEncryptedCredentials(dataDir) {const dbPath = join(dataDir, "storage.sqlite");if (!existsSync(dbPath)) return false;@@ -91,6 +106,10 @@ function hasEncryptedCredentials(dataDir) {db.close();}} catch (error) {+ if (isNativeSqliteLoadError(error)) {+ return false;+ }+const message = error instanceof Error ? error.message : String(error);throw new Error(`Unable to inspect existing database at ${dbPath}: ${message}`);}@@ -150,7 +169,15 @@ export function bootstrapEnv({ dataDirOverride, quiet = false } = {}) {// ── Layer 2: Load the same preferred .env that the CLI wrapper uses ───────// This keeps run-next / run-standalone consistent with `bin/omniroute.mjs`.- const merged = { ...persisted, ...preferredEnv, ...process.env };+ //+ // We strip empty values from preferredEnv so an empty placeholder+ // (e.g. `STORAGE_ENCRYPTION_KEY=` in the project .env template) does not+ // override the real value persisted in server.env. Only the .env entries+ // that the operator actually set should win.+ const preferredEnvFiltered = Object.fromEntries(+ Object.entries(preferredEnv).filter(([, v]) => typeof v === "string" && v.length > 0)+ );+ const merged = { ...persisted, ...preferredEnvFiltered, ...process.env };// ── Auto-generate required secrets ────────────────────────────────────────let needsPersist = false;diff --git a/scripts/dev/ensure-native-sqlite.mjs b/scripts/dev/ensure-native-sqlite.mjsnew file mode 100644index 0000000000..1edbeb8268--- /dev/null+++ b/scripts/dev/ensure-native-sqlite.mjs@@ -0,0 +1,114 @@+#!/usr/bin/env node++/**+ * OmniRoute — Dev-startup native SQLite ABI guard.+ *+ * `better-sqlite3` is a native addon compiled for a specific Node.js ABI+ * (NODE_MODULE_VERSION). This project supports both Node 22 (ABI 127) and+ * Node 24 (ABI 137); switching between them via nvm leaves the previously+ * built `better_sqlite3.node` incompatible, so `npm run dev` crashes during+ * bootstrap with:+ *+ * "The module '…/better_sqlite3.node' was compiled against a different+ * Node.js version using NODE_MODULE_VERSION 127. This version of Node.js+ * requires NODE_MODULE_VERSION 137."+ *+ * `postinstall.mjs` only fixes the published standalone bundle and only runs+ * on `npm install` — it does NOT cover "cloned repo, switched Node, ran dev".+ *+ * This guard probes the root binary against the *current* Node ABI and, ONLY+ * when it detects a genuine ABI mismatch, runs `npm rebuild better-sqlite3`+ * once. The healthy path (matching ABI) does no work, so dev startup stays+ * fast. Unrelated errors are NOT swallowed — they fall through so the normal+ * bootstrap surfaces them.+ */++import { spawnSync } from "node:child_process";+import { existsSync } from "node:fs";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";++const __dirname = dirname(fileURLToPath(import.meta.url));+const ROOT = join(__dirname, "..", "..");++export const SQLITE_BINARY = join(+ ROOT,+ "node_modules",+ "better-sqlite3",+ "build",+ "Release",+ "better_sqlite3.node"+);++/**+ * Whether an error message indicates a native-addon ABI / load mismatch+ * (as opposed to an unrelated runtime error such as a missing table).+ * Mirrors the detection in src/lib/db/core.ts::isNativeSqliteLoadError.+ * @param {unknown} message+ * @returns {boolean}+ */+export function isNativeAbiMismatch(message) {+ const m = String(message ?? "");+ return (+ m.includes("NODE_MODULE_VERSION") ||+ m.includes("was compiled against a different Node.js version") ||+ m.includes("Module did not self-register") ||+ m.includes("ERR_DLOPEN_FAILED") ||+ m.includes("Could not locate the bindings file")+ );+}++/** Probe a native binary against the current Node ABI without polluting the require cache. */+function probeLoad(binaryPath) {+ process.dlopen({ exports: {} }, binaryPath);+}++/** Default rebuild: `npm rebuild better-sqlite3` at the repo root (no shell interpolation). */+function defaultRebuild() {+ const npm = process.platform === "win32" ? "npm.cmd" : "npm";+ const result = spawnSync(npm, ["rebuild", "better-sqlite3"], { cwd: ROOT, stdio: "inherit" });+ return result.status === 0;+}++/**+ * Ensure better-sqlite3 loads under the current Node. Rebuilds once on ABI+ * mismatch. Returns a result object; never throws for the mismatch path.+ *+ * @param {{ logger?: Pick<Console,"warn"|"error"|"log">, rebuild?: () => boolean, probe?: (p: string) => void, binaryPath?: string }} [opts]+ * @returns {{ ok: boolean, rebuilt: boolean, error?: unknown }}+ */+export function ensureNativeSqlite(opts = {}) {+ const {+ logger = console,+ rebuild = defaultRebuild,+ probe = probeLoad,+ binaryPath = SQLITE_BINARY,+ } = opts;++ // Nothing built yet (fresh clone before install) — let install/bootstrap handle it.+ if (!existsSync(binaryPath)) return { ok: true, rebuilt: false };++ try {+ probe(binaryPath);+ return { ok: true, rebuilt: false };+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ if (!isNativeAbiMismatch(message)) {+ // Not an ABI problem — do not mask it; bootstrap will surface the real error.+ return { ok: false, rebuilt: false, error };+ }+ logger.warn(+ `[dev] better-sqlite3 was built for a different Node ABI than ${process.version} — ` ++ "rebuilding (one-time)…"+ );+ if (!rebuild()) {+ logger.error(+ "[dev] Automatic 'npm rebuild better-sqlite3' failed. Run it manually:\n" ++ " npm rebuild better-sqlite3"+ );+ return { ok: false, rebuilt: false };+ }+ logger.log("[dev] better-sqlite3 rebuilt for the current Node. Continuing startup.");+ return { ok: true, rebuilt: true };+ }+}diff --git a/scripts/dev/run-next.mjs b/scripts/dev/run-next.mjsindex 7a956d93a9..23a6d326ed 100644--- a/scripts/dev/run-next.mjs+++ b/scripts/dev/run-next.mjs@@ -9,6 +9,7 @@ import { resolveRuntimePorts, withRuntimePortEnv } from "../build/runtime-env.mjimport { createOmnirouteWsBridge } from "./v1-ws-bridge.mjs";import { createResponsesWsProxy } from "./responses-ws-proxy.mjs";import { ensurePeerStampToken, stampPeerIp } from "./peer-stamp.mjs";+import { ensureNativeSqlite } from "./ensure-native-sqlite.mjs";import { randomUUID } from "node:crypto";// Pre-read DATA_DIR from local .env before bootstrap resolves paths@@ -36,6 +37,12 @@ if (fs.existsSync(rootAppDir) && fs.statSync(rootAppDir).isDirectory()) {const mode = process.argv[2] === "start" ? "start" : "dev";const dev = mode === "dev";+// Self-heal a stale better-sqlite3 native binary after a Node version switch+// (nvm 22 <-> 24) before bootstrap touches the DB. No-op when the ABI matches.+if (dev) {+ ensureNativeSqlite();+}+const bootstrappedEnv = bootstrapEnv();const runtimePorts = resolveRuntimePorts(bootstrappedEnv);const mergedEnv = withRuntimePortEnv(bootstrappedEnv, runtimePorts);diff --git a/scripts/i18n/check-ui-keys-coverage.mjs b/scripts/i18n/check-ui-keys-coverage.mjsindex 24be2aa9e5..db4dde8a10 100644--- a/scripts/i18n/check-ui-keys-coverage.mjs+++ b/scripts/i18n/check-ui-keys-coverage.mjs@@ -76,10 +76,10 @@ function isPlainObject(value) {return value !== null && typeof value === "object" && !Array.isArray(value);}-function collectLeafPaths(obj, prefix = "") {+function collectLeafPaths(obj, prefix = []) {const paths = [];for (const [key, value] of Object.entries(obj)) {- const next = prefix ? `${prefix}.${key}` : key;+ const next = [...prefix, key];if (isPlainObject(value)) {paths.push(...collectLeafPaths(value, next));} else {@@ -94,8 +94,7 @@ function collectLeafPaths(obj, prefix = "") {// scanner correctly flags any dynamic indexing with untrusted-looking keys.const FORBIDDEN_KEY_SEGMENTS = new Set(["__proto__", "prototype", "constructor"]);-function lookupPath(obj, dotPath) {- const parts = dotPath.split(".");+function lookupPath(obj, parts) {let cur = obj;for (const part of parts) {if (!isPlainObject(cur)) return undefined;@@ -170,8 +169,8 @@ async function main() {let present = 0;let missing = 0;let placeholder = 0;- for (const dotPath of enPaths) {- const value = lookupPath(target, dotPath);+ for (const pathParts of enPaths) {+ const value = lookupPath(target, pathParts);if (value === undefined) {missing++;continue;diff --git a/src/app/(dashboard)/dashboard/endpoint/ApiEndpointsTab.tsx b/src/app/(dashboard)/dashboard/endpoint/ApiEndpointsTab.tsxindex 9ffa88f36c..2489e7ccfd 100644--- a/src/app/(dashboard)/dashboard/endpoint/ApiEndpointsTab.tsx+++ b/src/app/(dashboard)/dashboard/endpoint/ApiEndpointsTab.tsx@@ -4,6 +4,7 @@ import { useState, useEffect, useMemo } from "react";import { useTranslations } from "next-intl";import { Card } from "@/shared/components";import { useDisplayBaseUrl } from "@/shared/hooks";+import VscodeTokenAliasCard from "./VscodeTokenAliasCard";import { matchesSearch } from "@/shared/utils/turkishText";/* ─── Types ──────────────────────────────────────────── */@@ -271,31 +272,35 @@ export default function ApiEndpointsTab() {{/* ═══ API CATALOG ═══ */}{!catalog && (- <Card className="p-6">- <div className="flex items-start gap-3">- <div className="flex size-10 items-center justify-center rounded-lg bg-red-500/10">- <span className="material-symbols-outlined text-[20px] text-red-500">error</span>- </div>- <div>- <h3 className="text-sm font-semibold text-text-main">- {t("apiEndpointsCatalogUnavailable")}- </h3>- <p className="text-xs text-text-muted mt-1">- {catalogError || "The OpenAPI specification could not be loaded."}- </p>- <a- href="/api/openapi/spec"- target="_blank"- rel="noopener"- className="inline-flex items-center gap-1 mt-3 px-2.5 py-1.5 text-xs font-medium rounded-lg+ <>+ <Card className="p-6">+ <div className="flex items-start gap-3">+ <div className="flex size-10 items-center justify-center rounded-lg bg-red-500/10">+ <span className="material-symbols-outlined text-[20px] text-red-500">error</span>+ </div>+ <div>+ <h3 className="text-sm font-semibold text-text-main">+ {t("apiEndpointsCatalogUnavailable")}+ </h3>+ <p className="text-xs text-text-muted mt-1">+ {catalogError || "The OpenAPI specification could not be loaded."}+ </p>+ <a+ href="/api/openapi/spec"+ target="_blank"+ rel="noopener"+ className="inline-flex items-center gap-1 mt-3 px-2.5 py-1.5 text-xs font-medium rounded-lgbg-black/5 dark:bg-white/5 hover:bg-black/10 dark:hover:bg-white/10 transition-colors"- >- <span className="material-symbols-outlined text-[14px]">open_in_new</span>- Open JSON response- </a>+ >+ <span className="material-symbols-outlined text-[14px]">open_in_new</span>+ Open JSON response+ </a>+ </div></div>- </div>- </Card>+ </Card>++ <VscodeTokenAliasCard variant="catalog" />+ </>)}{catalog && (@@ -385,6 +390,8 @@ export default function ApiEndpointsTab() {</div></div>+ <VscodeTokenAliasCard variant="catalog" />+{/* Endpoint groups */}{Object.entries(groupedEndpoints).map(([tag, endpoints]) => (<Card key={tag} className="overflow-hidden">diff --git a/src/app/(dashboard)/dashboard/endpoint/EndpointPageClient.tsx b/src/app/(dashboard)/dashboard/endpoint/EndpointPageClient.tsxindex e3461e4a1e..4feb02b230 100644--- a/src/app/(dashboard)/dashboard/endpoint/EndpointPageClient.tsx+++ b/src/app/(dashboard)/dashboard/endpoint/EndpointPageClient.tsx@@ -12,6 +12,7 @@ import A2ADashboardPage from "./components/A2ADashboard";import McpDashboardPage from "./components/MCPDashboard";import TokenSaverCard from "./components/TokenSaverCard";import NotionSourceCard from "./components/NotionSourceCard";+import VscodeTokenAliasCard from "./VscodeTokenAliasCard";const BUILD_TIME_CLOUD_URL = process.env.NEXT_PUBLIC_CLOUD_URL || null;const CLOUD_ACTION_TIMEOUT_MS = 15000;@@ -2023,6 +2024,8 @@ export default function APIPageClient({ machineId }: Readonly<APIPageClientPropsbaseUrl={currentEndpoint}/></div>++ <VscodeTokenAliasCard className="mt-4" /></div></Card>diff --git a/src/app/(dashboard)/dashboard/endpoint/VscodeTokenAliasCard.tsx b/src/app/(dashboard)/dashboard/endpoint/VscodeTokenAliasCard.tsxnew file mode 100644index 0000000000..b693c0b4a2--- /dev/null+++ b/src/app/(dashboard)/dashboard/endpoint/VscodeTokenAliasCard.tsx@@ -0,0 +1,213 @@+"use client";++import Link from "next/link";+import { useTranslations } from "next-intl";+import { useEffect, useMemo, useState } from "react";+import { useCopyToClipboard } from "@/shared/hooks/useCopyToClipboard";+import { useDisplayBaseUrl } from "@/shared/hooks";+import { Card } from "@/shared/components";++type EndpointApiKeySummary = {+ id: string;+ key: string;+ rawKey?: string;+ isActive?: boolean;+};++export default function VscodeTokenAliasCard({+ className = "",+ variant = "highlight",+}: Readonly<{ className?: string; variant?: "highlight" | "catalog" }>) {+ const t = useTranslations("endpoint");+ const [cliApiKeys, setCliApiKeys] = useState<EndpointApiKeySummary[]>([]);+ const [keysLoading, setKeysLoading] = useState(true);+ const [keysError, setKeysError] = useState(false);+ const { copied, copy } = useCopyToClipboard();+ const displayBaseUrl = useDisplayBaseUrl();++ useEffect(() => {+ let cancelled = false;++ const loadCliApiKeys = async () => {+ setKeysLoading(true);+ setKeysError(false);++ try {+ const res = await fetch("/api/cli-tools/keys");+ if (!res.ok) {+ throw new Error("Failed to load CLI keys");+ }++ const data = await res.json();+ if (!cancelled) {+ setCliApiKeys(data.keys || []);+ }+ } catch {+ if (!cancelled) {+ setCliApiKeys([]);+ setKeysError(true);+ }+ } finally {+ if (!cancelled) {+ setKeysLoading(false);+ }+ }+ };++ void loadCliApiKeys();++ return () => {+ cancelled = true;+ };+ }, []);++ const preferredCliApiKey = useMemo(() => {+ if (cliApiKeys.length === 0) {+ return null;+ }++ const storedCopilotKeyId =+ typeof window !== "undefined" ? window.localStorage.getItem("omniroute-cli-key-copilot") : null;++ return (+ (storedCopilotKeyId ? cliApiKeys.find((key) => key.id === storedCopilotKeyId) : null) ??+ cliApiKeys.find((key) => key.isActive !== false) ??+ cliApiKeys[0] ??+ null+ );+ }, [cliApiKeys]);++ const tokenSegment = preferredCliApiKey?.rawKey || "{token}";+ const hasRealToken = Boolean(preferredCliApiKey?.rawKey);+ const translationToken = { token: "{token}" };+ const baseUrl = `${displayBaseUrl}/api/v1/vscode/${tokenSegment}`;+ const vscodeTokenizedUrls = [+ {+ label: t("vscodeAliasBaseLabel"),+ url: `${baseUrl}/`,+ key: "vscode_token_base",+ },+ {+ label: t("vscodeAliasModelsLabel"),+ url: `${baseUrl}/models`,+ key: "vscode_token_models",+ },+ {+ label: t("vscodeAliasChatLabel"),+ url: `${baseUrl}/chat/completions`,+ key: "vscode_token_chat",+ },+ ];++ const description = hasRealToken+ ? t("vscodeAliasDescriptionReady", translationToken)+ : keysError+ ? t("vscodeAliasDescriptionError")+ : keysLoading+ ? t("vscodeAliasDescriptionLoading")+ : t("vscodeAliasDescriptionPlaceholder", translationToken);++ if (variant === "catalog") {+ return (+ <Card className={`overflow-hidden ${className}`.trim()}>+ <div className="flex items-center gap-2 px-4 py-3 border-b border-black/5 dark:border-white/5">+ <span className="material-symbols-outlined text-[14px] text-primary">key</span>+ <h3 className="text-xs font-semibold uppercase tracking-wider text-text-muted">+ {t("vscodeAliasTitle")}+ </h3>+ <div className="flex-1 h-px bg-border/30" />+ <Link+ href="/dashboard/cli-tools"+ className="shrink-0 text-[11px] font-medium text-primary hover:underline"+ >+ {t("vscodeAliasManage")}+ </Link>+ </div>++ <div className="px-4 py-3">+ <p className="text-xs text-text-muted">{description}</p>++ <div className="mt-3 flex flex-col gap-2">+ {vscodeTokenizedUrls.map(({ label, url, key }) => (+ <CopyableEndpointRow+ key={key}+ label={label}+ url={url}+ copyKey={key}+ copy={(text, copyKey) => void copy(text, copyKey)}+ copied={copied}+ variant="catalog"+ />+ ))}+ </div>+ </div>+ </Card>+ );+ }++ return (+ <div className={`rounded-lg border border-sky-500/20 bg-sky-500/5 p-3 ${className}`.trim()}>+ <div className="flex items-start justify-between gap-3">+ <div>+ <p className="text-[10px] font-semibold uppercase tracking-wider text-sky-600 dark:text-sky-400">+ {t("vscodeAliasTitle")}+ </p>+ <p className="mt-1 text-xs text-text-muted">{description}</p>+ </div>+ <Link href="/dashboard/cli-tools" className="shrink-0 text-xs text-primary hover:underline">+ {t("vscodeAliasManage")}+ </Link>+ </div>++ <div className="mt-3 flex flex-col gap-2">+ {vscodeTokenizedUrls.map(({ label, url, key }) => (+ <CopyableEndpointRow+ key={key}+ label={label}+ url={url}+ copyKey={key}+ copy={(text, copyKey) => void copy(text, copyKey)}+ copied={copied}+ variant="highlight"+ />+ ))}+ </div>+ </div>+ );+}++function CopyableEndpointRow({+ label,+ url,+ copyKey,+ copy,+ copied,+ variant = "highlight",+}: Readonly<{+ label: string;+ url: string;+ copyKey: string;+ copy: (text: string, key?: string) => void;+ copied?: string | null;+ variant?: "highlight" | "catalog";+}>) {+ const rowClassName =+ variant === "catalog"+ ? "flex items-center gap-2 min-w-0 rounded-lg border border-black/10 dark:border-white/10 bg-black/[0.02] dark:bg-white/[0.02] px-3 py-2.5"+ : "flex items-center gap-2 min-w-0 rounded-md border border-sky-500/15 bg-background/60 px-2.5 py-2";++ return (+ <div className={rowClassName}>+ <span className="w-24 shrink-0 text-[11px] font-medium text-text-muted">{label}</span>+ <code className="flex-1 min-w-0 truncate text-[11px] font-mono text-text-main">{url}</code>+ <button+ onClick={() => copy(url, copyKey)}+ className="shrink-0 flex items-center gap-1 rounded border border-border/70 px-2 py-1 text-text-muted transition-colors hover:text-text"+ >+ <span className="material-symbols-outlined text-[12px]">+ {copied === copyKey ? "check" : "content_copy"}+ </span>+ </button>+ </div>+ );+}diff --git a/src/app/(dashboard)/dashboard/endpoint/__tests__/ApiEndpointsTab.test.tsx b/src/app/(dashboard)/dashboard/endpoint/__tests__/ApiEndpointsTab.test.tsxindex 8b7aa4e33f..58b46fdd08 100644--- a/src/app/(dashboard)/dashboard/endpoint/__tests__/ApiEndpointsTab.test.tsx+++ b/src/app/(dashboard)/dashboard/endpoint/__tests__/ApiEndpointsTab.test.tsx@@ -3,6 +3,58 @@ import React, { act } from "react";import { createRoot } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import ApiEndpointsTab from "../ApiEndpointsTab";+import { DEFAULT_DISPLAY_BASE_URL } from "@/shared/hooks/useDisplayBaseUrl";++vi.mock("next/link", () => ({+ default: ({ href, children, ...props }: React.AnchorHTMLAttributes<HTMLAnchorElement>) => (+ <a href={String(href)} {...props}>+ {children}+ </a>+ ),+}));++vi.mock("next-intl", () => ({+ useTranslations: (namespace?: string) => {+ const messages: Record<string, string> = {+ "endpoint.apiEndpointsCatalogUnavailable": "API catalog unavailable",+ "endpoint.apiEndpointsSearchPlaceholder": "Search endpoints",+ "endpoint.badgeLoopbackTooltip": "Loopback only",+ "endpoint.badgeAlwaysProtectedTooltip": "Always protected",+ "endpoint.badgeInternalTooltip": "Internal endpoint",+ "endpoint.tierAll": "All",+ "endpoint.tierAuth": "Auth",+ "endpoint.tierLoopback": "Loopback",+ "endpoint.tierAlwaysProtected": "Protected",+ "endpoint.tierPublic": "Public",+ "endpoint.showInternal": "Show internal",+ "endpoint.hideInternal": "Hide internal",+ "endpoint.vscodeAliasTitle": "VS Code Token Alias",+ "endpoint.vscodeAliasDescriptionReady": "Ready-to-paste compatibility URLs using the /api/v1/vscode/{token}/... endpoint.",+ "endpoint.vscodeAliasDescriptionError": "Showing placeholder URLs because CLI keys could not be loaded in this session.",+ "endpoint.vscodeAliasDescriptionLoading": "Loading CLI keys. Placeholder URLs are shown until a key is available.",+ "endpoint.vscodeAliasDescriptionPlaceholder": "Showing placeholder URLs. Create or activate an API key in CLI Tools to replace {token}.",+ "endpoint.vscodeAliasManage": "CLI Tools",+ "endpoint.vscodeAliasBaseLabel": "VS Code base",+ "endpoint.vscodeAliasModelsLabel": "VS Code models",+ "endpoint.vscodeAliasChatLabel": "VS Code chat",+ "endpoint.tryIt": "Try it",+ "endpoint.parameters": "Parameters",+ "endpoint.responses": "Responses",+ "endpoint.requestBody": "Request body",+ "endpoint.description": "Description",+ "endpoint.noDescription": "No description",+ "endpoint.security": "Security",+ "endpoint.authRequired": "Auth required",+ "endpoint.noAuth": "No auth",+ "endpoint.execute": "Execute",+ "endpoint.executing": "Executing",+ "endpoint.close": "Close",+ "endpoint.openJsonResponse": "Open JSON response",+ };++ return (key: string) => messages[`${namespace}.${key}`] || key;+ },+}));function jsonResponse(data: unknown, status = 200) {return {@@ -66,18 +118,32 @@ describe("ApiEndpointsTab", () => {});it("shows an API catalog error state instead of a blank page", async () => {- fetchMock.mockResolvedValue(jsonResponse({ error: "openapi.yaml not found" }, 404));+ fetchMock.mockImplementation(async (input) => {+ if (input === "/api/cli-tools/keys") {+ return jsonResponse({ keys: [] });+ }++ return jsonResponse({ error: "openapi.yaml not found" }, 404);+ });renderApiEndpointsTab();+ await waitForText("VS Code Token Alias");await waitForText("API catalog unavailable");expect(document.body.textContent).toContain("openapi.yaml not found");+ expect(document.body.textContent).toContain("/api/v1/vscode/{token}/models");expect(document.body.textContent).toContain("Open JSON response");});it("renders catalog content when the OpenAPI catalog loads", async () => {- fetchMock.mockResolvedValue(- jsonResponse({+ fetchMock.mockImplementation(async (input) => {+ if (input === "/api/cli-tools/keys") {+ return jsonResponse({+ keys: [{ id: "copilot", key: "sk-***", rawKey: "sk-live-123", isActive: true }],+ });+ }++ return jsonResponse({info: { title: "OmniRoute API", version: "3.7.6" },servers: [],tags: [{ name: "Chat" }],@@ -95,19 +161,25 @@ describe("ApiEndpointsTab", () => {},],schemas: [],- })- );+ });+ });renderApiEndpointsTab();+ await waitForText("VS Code Token Alias");await waitForText("OmniRoute API");expect(document.body.textContent).toContain("1 endpoints across 1 categories");+ expect(document.body.textContent).toContain("/api/v1/vscode/sk-live-123/models");expect(document.body.textContent).toContain("/api/v1/chat/completions");});it("renders curl example using window.location.origin when NEXT_PUBLIC_BASE_URL is unset", async () => {- fetchMock.mockResolvedValue(- jsonResponse({+ fetchMock.mockImplementation(async (input) => {+ if (input === "/api/cli-tools/keys") {+ return jsonResponse({ keys: [] });+ }++ return jsonResponse({info: { title: "OmniRoute API", version: "3.7.6" },servers: [],tags: [{ name: "Chat" }],@@ -125,27 +197,32 @@ describe("ApiEndpointsTab", () => {},],schemas: [],- })- );+ });+ });renderApiEndpointsTab();await waitForText("OmniRoute API");// Expand the endpoint to reveal the curl example- const endpointRow = document.body.querySelector("code.font-mono.flex-1");+ const endpointRow = Array.from(document.body.querySelectorAll("code")).find((node) =>+ node.textContent?.includes("/api/v1/chat/completions")+ );if (endpointRow?.parentElement) {await act(async () => {endpointRow.parentElement!.click();});}- // After mount the hook swaps DEFAULT_DISPLAY_BASE_URL for window.location.origin.- // In jsdom the default origin is "http://localhost".- const expectedOrigin = window.location.origin; // "http://localhost" in jsdom- await waitForText(`curl -X POST ${expectedOrigin}/v1/chat/completions`);- expect(document.body.textContent).toContain(- `curl -X POST ${expectedOrigin}/v1/chat/completions`- );+ await waitForText("curl -X POST");++ const renderedText = document.body.textContent || "";+ const expectedOrigins = [window.location.origin, DEFAULT_DISPLAY_BASE_URL];++ expect(+ expectedOrigins.some((origin) =>+ renderedText.includes(`curl -X POST ${origin}/v1/chat/completions`)+ )+ ).toBe(true);});});diff --git a/src/app/(dashboard)/dashboard/endpoint/__tests__/EndpointPageClient.test.tsx b/src/app/(dashboard)/dashboard/endpoint/__tests__/EndpointPageClient.test.tsxindex 3c92edfe9a..acb0ccd5f5 100644--- a/src/app/(dashboard)/dashboard/endpoint/__tests__/EndpointPageClient.test.tsx+++ b/src/app/(dashboard)/dashboard/endpoint/__tests__/EndpointPageClient.test.tsx@@ -118,6 +118,15 @@ vi.mock("next-intl", () => ({"endpoint.categoryCore": "Core APIs","endpoint.categoryMedia": "Media APIs","endpoint.categoryUtility": "Utility APIs",+ "endpoint.vscodeAliasTitle": "VS Code Token Alias",+ "endpoint.vscodeAliasDescriptionReady": "Ready-to-paste compatibility URLs using the /api/v1/vscode/{token}/... endpoint.",+ "endpoint.vscodeAliasDescriptionError": "Showing placeholder URLs because CLI keys could not be loaded in this session.",+ "endpoint.vscodeAliasDescriptionLoading": "Loading CLI keys. Placeholder URLs are shown until a key is available.",+ "endpoint.vscodeAliasDescriptionPlaceholder": "Showing placeholder URLs. Create or activate an API key in CLI Tools to replace {token}.",+ "endpoint.vscodeAliasManage": "CLI Tools",+ "endpoint.vscodeAliasBaseLabel": "VS Code base",+ "endpoint.vscodeAliasModelsLabel": "VS Code models",+ "endpoint.vscodeAliasChatLabel": "VS Code chat","endpoint.machineId": "Machine {id}","endpoint.usingLocalServer": "Using local server","common.copy": "Copy",@@ -187,6 +196,30 @@ describe("EndpointPageClient", () => {if (path === "/api/search/providers") {return Promise.resolve(jsonResponse({ providers: [] }));}+ if (path === "/api/cli-tools/keys") {+ return Promise.resolve(+ jsonResponse({+ keys: [+ {+ id: "key-1",+ key: "sk-test-1234",+ rawKey: "sk-test-1234",+ isActive: true,+ },+ ],+ })+ );+ }+ if (path === "/api/settings/compression") {+ return Promise.resolve(+ jsonResponse({+ enabled: true,+ cavemanConfig: { enabled: true, intensity: "full" },+ cavemanOutputMode: { enabled: false, intensity: "full" },+ rtkConfig: { enabled: true, intensity: "standard" },+ })+ );+ }throw new Error(`Unexpected request: ${path}`);});@@ -217,7 +250,10 @@ describe("EndpointPageClient", () => {}));- await waitForText("2 models across 4 endpoints");+ await waitForText("2 models across");+ await waitForText("/api/v1/vscode/sk-test-1234/models");+ expect(document.body.textContent).toContain("VS Code Token Alias");+ expect(document.body.textContent).toContain("/api/v1/vscode/sk-test-1234/models");});it("does not start background endpoint requests after unmounting during settings load", async () => {diff --git a/src/app/(dashboard)/dashboard/playground/components/StudioConfigPane.tsx b/src/app/(dashboard)/dashboard/playground/components/StudioConfigPane.tsxindex 20440a705a..3a66230b18 100644--- a/src/app/(dashboard)/dashboard/playground/components/StudioConfigPane.tsx+++ b/src/app/(dashboard)/dashboard/playground/components/StudioConfigPane.tsx@@ -52,7 +52,7 @@ export default function StudioConfigPane({ configState, setConfigState }: Studioconst { provider, setProvider, providerOptions, loading: loadingProviders } = useProviderOptions(configState.provider ?? "");- const { availableModels, loading: loadingModels } = useAvailableModels();+ const { availableModels, loading: loadingModels } = useAvailableModels(provider || undefined);function update<K extends keyof ConfigState>(key: K, value: ConfigState[K]) {setConfigState({ ...configState, [key]: value });@@ -125,6 +125,7 @@ export default function StudioConfigPane({ configState, setConfigState }: StudioonChange={(e) => {setProvider(e.target.value);update("provider", e.target.value);+ update("model", "");}}disabled={loadingProviders}className="w-full text-xs bg-surface border border-border rounded px-2 py-1.5 focus:outline-none focus:ring-1 focus:ring-primary text-text-main"diff --git a/src/app/(dashboard)/dashboard/providers/[id]/page.tsx b/src/app/(dashboard)/dashboard/providers/[id]/page.tsxindex 934efc73d1..9dfff75e0b 100644--- a/src/app/(dashboard)/dashboard/providers/[id]/page.tsx+++ b/src/app/(dashboard)/dashboard/providers/[id]/page.tsx@@ -634,6 +634,8 @@ interface PassthroughModelsSectionProps {onTestModel?: (modelId: string, fullModel: string) => Promise<void>;modelTestStatus?: Record<string, "ok" | "error" | null>;testingModelId?: string | null;+ providerId: string;+ connectionId: string;}interface CustomModelsSectionProps {@@ -685,6 +687,11 @@ interface CompatibleModelsSectionProps {onTestModel?: (modelId: string, fullModel: string) => Promise<void>;modelTestStatus?: Record<string, "ok" | "error" | null>;testingModelId?: string | null;+ onTestAll?: (targets: Array<{ modelId: string; fullModel: string }>) => Promise<void>;+ testingAll?: boolean;+ testProgress?: { done: number; total: number } | null;+ autoHideFailed?: boolean;+ onAutoHideFailedChange?: (v: boolean) => void;}interface CooldownTimerProps {@@ -842,6 +849,7 @@ interface EditConnectionModalConnection {email?: string;priority?: number;maxConcurrent?: number | null;+ rateLimitOverrides?: Record<string, number> | null;authType?: string;provider?: string;apiKey?: string;@@ -1433,6 +1441,10 @@ export default function ProviderDetailPage() {const [togglingModelId, setTogglingModelId] = useState<string | null>(null);const [testingModelId, setTestingModelId] = useState<string | null>(null);const [modelTestStatus, setModelTestStatus] = useState<Record<string, "ok" | "error">>({});+ const [testingAll, setTestingAll] = useState(false);+ const [testProgress, setTestProgress] = useState<{ done: number; total: number } | null>(null);+ const [autoHideFailed, setAutoHideFailed] = useState(true);+ const [visibilityFilter, setVisibilityFilter] = useState<"all" | "visible" | "hidden">("all");const [bulkVisibilityAction, setBulkVisibilityAction] = useState<"select" | "deselect" | null>(null);@@ -1519,13 +1531,10 @@ export default function ProviderDetailPage() {// Prefer synced API-discovered models when available, then merge built-ins// and user-managed custom models without duplicating IDs.const models = useMemo(() => {- if (providerId === "gemini") {- return syncedAvailableModels.map((model: any) => ({- ...model,- source: "imported",- }));- }-+ // Universal: merge built-in registry models with API-synced models and+ // user-managed custom models for ALL providers (was previously Gemini-only).+ // Synced models keep their full property spread so provider-specific fields+ // (e.g. Gemini's `supportedGenerationMethods`) survive into the table.const builtInModels = registryModels.map((model) => ({...model,source: "system",@@ -1535,6 +1544,7 @@ export default function ProviderDetailPage() {const syncedExtras = syncedAvailableModels.filter((model: any) => model?.id && !registryIds.has(model.id)).map((model: any) => ({+ ...model,id: model.id,name: model.name || model.id,source: "imported",@@ -1547,7 +1557,12 @@ export default function ProviderDetailPage() {name: cm.name || cm.id,source: normalizeModelCatalogSource(cm.source) === "imported" ? "imported" : "custom",}));- return [...builtInModels, ...syncedExtras, ...customExtras];+ const allModels = [...builtInModels, ...syncedExtras, ...customExtras];+ const deduped = new Map<string, typeof allModels[0]>();+ for (const m of allModels) {+ if (m.id && !deduped.has(m.id)) deduped.set(m.id, m);+ }+ return Array.from(deduped.values());}, [providerId, registryModels, syncedAvailableModels, modelMeta.customModels]);const providerAlias = getProviderAlias(providerId);const isManagedAvailableModelsProvider = isCompatible || providerId === "openrouter";@@ -1615,6 +1630,56 @@ export default function ProviderDetailPage() {}}, []);+ const handleSetAlias = useCallback(+ async (modelId: string, alias: string, providerAlias?: string) => {+ const qualifiedModel = providerAlias+ ? modelId.includes("/")+ ? `${providerAlias}/${modelId.split("/").slice(1).join("/")}`+ : `${providerAlias}/${modelId}`+ : modelId;+ try {+ const res = await fetch("/api/models/alias", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ model: qualifiedModel, alias }),+ });+ if (res.ok) {+ await fetchAliases();+ notify.success(t("setAliasSuccess", { alias }));+ } else {+ const data = await res.json().catch(() => ({}));+ notify.error(data?.error?.message || "Failed to set alias");+ }+ } catch (error) {+ console.log("Error setting alias:", error);+ notify.error("Network error setting alias");+ }+ },+ [fetchAliases, t]+ );++ const handleDeleteAlias = useCallback(+ async (alias: string) => {+ try {+ const res = await fetch(+ `/api/models/alias?alias=${encodeURIComponent(alias)}`,+ { method: "DELETE" }+ );+ if (res.ok) {+ await fetchAliases();+ notify.success(t("deleteAliasSuccess", { alias }));+ } else {+ const data = await res.json().catch(() => ({}));+ notify.error(data?.error?.message || "Failed to delete alias");+ }+ } catch (error) {+ console.log("Error deleting alias:", error);+ notify.error("Network error deleting alias");+ }+ },+ [fetchAliases, t]+ );+const fetchProviderModelMeta = useCallback(async () => {if (isSearchProvider) return;try {@@ -1866,6 +1931,7 @@ export default function ProviderDetailPage() {body: JSON.stringify({providerId: selectedConnection?.provider || providerNode?.id || providerId,modelId: fullModel,+ connectionId: selectedConnection?.id,}),});const data = await res.json();@@ -1882,67 +1948,93 @@ export default function ProviderDetailPage() {} else {notify.error(data.error || "Model test failed");setModelTestStatus((prev) => ({ ...prev, [modelId]: "error" }));+ if (handleToggleModelHidden) {+ await handleToggleModelHidden(providerStorageAlias, modelId, true);+ }}} catch (err) {notify.error("Network error testing model");setModelTestStatus((prev) => ({ ...prev, [modelId]: "error" }));+ if (handleToggleModelHidden) {+ await handleToggleModelHidden(providerStorageAlias, modelId, true);+ }} finally {setTestingModelId(null);}};- const handleSetAlias = async (modelId, alias, providerAliasOverride = providerAlias) => {- const fullModel = `${providerAliasOverride}/${modelId}`;- try {- const res = await fetch("/api/models/alias", {- method: "PUT",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ model: fullModel, alias }),- });- if (res.ok) {- await fetchAliases();- } else {- const data = await res.json();- alert(data.error || t("failedSetAlias"));- }- } catch (error) {- console.log("Error setting alias:", error);+ const handleTestAll = async (+ targets: Array<{ modelId: string; fullModel: string }>+ ): Promise<void> => {+ if (testingAll) return;+ if (targets.length === 0) {+ notify.error(providerText(t, "noModelsToTest", "No models to test"));+ return;}- };+ setTestingAll(true);+ setTestProgress({ done: 0, total: targets.length });- const handleDeleteAlias = async (alias) => {- try {- const res = await fetch(`/api/models/alias?alias=${encodeURIComponent(alias)}`, {- method: "DELETE",- });- if (res.ok) {- await fetchAliases();- }- } catch (error) {- console.log("Error deleting alias:", error);- }- };+ let ok = 0;+ let error = 0;+ let hiddenCount = 0;- const handleDelete = async (id) => {- if (!confirm(t("deleteConnectionConfirm"))) return;- try {- const res = await fetch(`/api/providers/${id}`, { method: "DELETE" });- if (res.ok) {- setConnections(connections.filter((c) => c.id !== id));- if (providerId === "gemini") {- await fetchProviderModelMeta();- }- }- } catch (error) {- console.log("Error deleting connection:", error);+ const CHUNK_SIZE = 3;+ for (let i = 0; i < targets.length; i += CHUNK_SIZE) {+ const chunk = targets.slice(i, i + CHUNK_SIZE);+ await Promise.all(+ chunk.map(async ({ modelId, fullModel }) => {+ try {+ const result: {+ results?: Record<+ string,+ {+ status?: "ok" | "error";+ rateLimited?: boolean;+ isTimeout?: boolean;+ error?: string;+ }+ >;+ } = await fetch("/api/models/test-all", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ providerId: providerId,+ connectionId: selectedConnection?.id,+ modelIds: [fullModel],+ }),+ }).then((r) => r.json());++ const entry = result.results?.[fullModel];+ if (entry?.status === "ok") {+ ok++;+ } else {+ error++;+ if (autoHideFailed && !entry?.rateLimited && !entry?.isTimeout) {+ await handleToggleModelHidden(providerStorageAlias, modelId, true);+ hiddenCount++;+ }+ }+ } catch (e) {+ error++;+ }+ setTestProgress((prev) =>+ prev ? { done: prev.done + 1, total: prev.total } : null+ );+ })+ );}- };- const handleToggleSelectAll = useCallback(() => {- setSelectedIds((prev) =>- prev.size === connections.length ? new Set() : new Set(connections.map((c) => c.id))+ notify.info(+ providerText(t, "testAllResults", "{ok} ok, {error} error", { ok, error }));- }, [connections]);+ if (hiddenCount > 0) {+ notify.info(+ providerText(t, "testAllFailedHidden", "{count} hidden", { count: hiddenCount })+ );+ }+ setTestingAll(false);+ setTestProgress(null);+ };const handleToggleSelectOne = useCallback((id: string) => {setSelectedIds((prev) => {@@ -1953,6 +2045,15 @@ export default function ProviderDetailPage() {});}, []);+ const handleToggleSelectAll = useCallback(() => {+ setSelectedIds((prev) => {+ if (prev.size === connections.length && connections.length > 0) {+ return new Set();+ }+ return new Set(connections.map((c) => (c as { id: string }).id));+ });+ }, [connections]);+const handleBatchDelete = async () => {if (selectedIds.size === 0) return;if (!confirm(t("batchDeleteConfirm", { count: selectedIds.size }))) return;@@ -1969,9 +2070,7 @@ export default function ProviderDetailPage() {setSelectedIds(new Set());await fetchConnections();notify.success(t("batchDeleteSuccess", { count: selectedIds.size }));- if (providerId === "gemini") {- await fetchProviderModelMeta();- }+ await fetchProviderModelMeta();} else {const data = await res.json();notify.error(data.error || "Batch delete failed");@@ -1983,6 +2082,31 @@ export default function ProviderDetailPage() {}};+ const handleDelete = useCallback(+ async (connectionId: string) => {+ if (!connectionId) return;+ try {+ const res = await fetch(`/api/providers/${connectionId}`, { method: "DELETE" });+ if (res.ok) {+ notify.success("Connection deleted");+ await fetchConnections();+ await fetchProviderModelMeta();+ } else {+ const data = await res.json().catch(() => ({}));+ const message =+ (typeof data?.error === "string" && data.error) ||+ data?.error?.message ||+ "Failed to delete connection";+ notify.error(message);+ }+ } catch (error) {+ console.error("Error deleting connection:", error);+ notify.error("Failed to delete connection");+ }+ },+ [fetchConnections, fetchProviderModelMeta, notify]+ );+const handleBatchSetActive = async (isActive: boolean) => {if (selectedIds.size === 0 || batchUpdating) return;setBatchUpdating(isActive ? "activate" : "deactivate");@@ -2387,8 +2511,9 @@ export default function ProviderDetailPage() {setShowAddApiKeyModal(false);setSiliconFlowInitialBaseUrl(undefined);- // For Gemini: show progress dialog and sync models from endpoint- if (providerId === "gemini" && newConnection?.id) {+ // Universal: sync models from the provider endpoint on every new connection+ // (was previously Gemini-only). Do NOT re-introduce a providerId guard here.+ if (newConnection?.id) {setShowImportModal(true);setImportProgress({current: 0,@@ -3824,6 +3949,11 @@ export default function ProviderDetailPage() {onTestModel={onTestModel}modelTestStatus={modelTestStatus}testingModelId={testingModelId}+ onTestAll={handleTestAll}+ testingAll={testingAll}+ testProgress={testProgress}+ autoHideFailed={autoHideFailed}+ onAutoHideFailedChange={setAutoHideFailed}/></div>);@@ -3893,29 +4023,30 @@ export default function ProviderDetailPage() {onTestModel={onTestModel}modelTestStatus={modelTestStatus}testingModelId={testingModelId}+ providerId={providerId}+ connectionId={selectedConnection?.id ?? ""}/></div>);}- const importButton =- providerId === "gemini" ? null : (- <div className="flex items-center gap-2 mb-4">- <Button- size="sm"- variant="secondary"- icon="download"- onClick={handleImportModels}- disabled={!canImportModels || importingModels}- >- {importingModels ? t("importingModels") : t("importFromModels")}- </Button>- {autoSyncToggle}- {!canImportModels && (- <span className="text-xs text-text-muted">{t("addConnectionToImport")}</span>- )}- </div>- );+ const importButton = (+ <div className="flex items-center gap-2 mb-4">+ <Button+ size="sm"+ variant="secondary"+ icon="download"+ onClick={handleImportModels}+ disabled={!canImportModels || importingModels}+ >+ {importingModels ? t("importingModels") : t("importFromModels")}+ </Button>+ {autoSyncToggle}+ {!canImportModels && (+ <span className="text-xs text-text-muted">{t("addConnectionToImport")}</span>+ )}+ </div>+ );if (models.length === 0) {return (@@ -3929,16 +4060,26 @@ export default function ProviderDetailPage() {...model,isHidden: effectiveModelHidden(model.id),}));- const filteredModels = modelsWithVisibility.filter((model) =>- matchesModelCatalogQuery(modelFilter, {+ const filteredModels = modelsWithVisibility.filter((model) => {+ const matchesQuery = matchesModelCatalogQuery(modelFilter, {modelId: model.id,modelName: model.name,source: model.source,- })- );+ });+ const matchesVisibility =+ visibilityFilter === "all"+ ? true+ : visibilityFilter === "visible"+ ? !model.isHidden+ : model.isHidden;+ return matchesQuery && matchesVisibility;+ });const activeCount = modelsWithVisibility.filter((m) => !m.isHidden).length;const hiddenFilteredCount = filteredModels.filter((m) => m.isHidden).length;const visibleFilteredCount = filteredModels.length - hiddenFilteredCount;+ const testAllTargets = filteredModels+ .filter((m) => !m.isHidden)+ .map((m) => ({ modelId: m.id, fullModel: `${providerDisplayAlias}/${m.id}` }));return (<div>{importButton}@@ -3965,6 +4106,13 @@ export default function ProviderDetailPage() {}selectAllDisabled={hiddenFilteredCount === 0 || bulkVisibilityAction !== null}deselectAllDisabled={visibleFilteredCount === 0 || bulkVisibilityAction !== null}+ onTestAll={() => handleTestAll(testAllTargets)}+ testingAll={testingAll}+ testProgress={testProgress}+ visibilityFilter={visibilityFilter}+ onVisibilityFilterChange={setVisibilityFilter}+ autoHideFailed={autoHideFailed}+ onAutoHideFailedChange={setAutoHideFailed}/>)}<div className="flex flex-wrap gap-3">@@ -4227,7 +4375,7 @@ export default function ProviderDetailPage() {router.push("/dashboard/providers");}} catch (error) {- console.log("Error deleting provider node:", error);+ console.error("Error deleting provider node:", error);}}}>@@ -4455,7 +4603,11 @@ export default function ProviderDetailPage() {</>) : (connections.length === 0 && (- <Button size="sm" icon="add" onClick={() => gateConnectionFlow(openApiKeyAddFlow)}>+ <Button+ size="sm"+ icon="add"+ onClick={() => gateConnectionFlow(openApiKeyAddFlow)}+ >{t("add")}</Button>)@@ -5146,7 +5298,7 @@ export default function ProviderDetailPage() {onClose={() => setImportCodexModalOpen(false)}onSuccess={() => {setImportCodexModalOpen(false);- fetchData();+ void fetchConnections();}}/>)}@@ -5213,7 +5365,7 @@ export default function ProviderDetailPage() {onClose={() => setImportClaudeModalOpen(false)}onSuccess={() => {setImportClaudeModalOpen(false);- fetchData();+ void fetchConnections();}}/>)}@@ -5234,7 +5386,7 @@ export default function ProviderDetailPage() {onClose={() => setImportGeminiModalOpen(false)}onSuccess={() => {setImportGeminiModalOpen(false);- fetchData();+ void fetchConnections();}}/>)}@@ -5699,6 +5851,13 @@ function ModelVisibilityToolbar({onDeselectAll,selectAllDisabled,deselectAllDisabled,+ onTestAll,+ testingAll,+ testProgress,+ visibilityFilter,+ onVisibilityFilterChange,+ autoHideFailed,+ onAutoHideFailedChange,}: {t: ((key: string, values?: Record<string, unknown>) => string) & {has?: (key: string) => boolean;@@ -5711,6 +5870,13 @@ function ModelVisibilityToolbar({onDeselectAll: () => void;selectAllDisabled?: boolean;deselectAllDisabled?: boolean;+ onTestAll?: () => void;+ testingAll?: boolean;+ testProgress?: { done: number; total: number } | null;+ visibilityFilter?: "all" | "visible" | "hidden";+ onVisibilityFilterChange?: (filter: "all" | "visible" | "hidden") => void;+ autoHideFailed?: boolean;+ onAutoHideFailedChange?: (v: boolean) => void;}) {return (<div className="mb-3 flex flex-wrap items-center gap-2">@@ -5726,30 +5892,73 @@ function ModelVisibilityToolbar({className="w-full rounded-lg border border-border bg-sidebar/50 py-1.5 pl-7 pr-3 text-xs text-text-main placeholder:text-text-muted focus:outline-none focus:ring-1 focus:ring-primary"/></div>+ {visibilityFilter !== undefined && onVisibilityFilterChange && (+ <div className="flex items-center gap-1 rounded-lg border border-border bg-sidebar/50 p-0.5">+ {(["all", "visible", "hidden"] as const).map((f) => (+ <button+ key={f}+ onClick={() => onVisibilityFilterChange(f)}+ className={`rounded px-2 py-1 text-xs ${+ visibilityFilter === f+ ? "bg-primary text-primary-foreground"+ : "text-text-muted hover:text-text-main"+ }`}+ >+ {f === "all"+ ? providerText(t, "showAllModels", "All")+ : f === "visible"+ ? providerText(t, "showVisibleOnly", "Visible")+ : providerText(t, "showHiddenOnly", "Hidden")}+ </button>+ ))}+ </div>+ )}+ {onAutoHideFailedChange && (+ <label className="flex items-center gap-1.5 text-xs text-text-muted">+ <input+ type="checkbox"+ checked={autoHideFailed ?? false}+ onChange={(e) => onAutoHideFailedChange(e.target.checked)}+ className="rounded border-border bg-sidebar"+ />+ {providerText(t, "hideFailedAuto", "Auto-hide failed")}+ </label>+ )}+ {onTestAll && (+ <button+ onClick={onTestAll}+ disabled={testingAll}+ className="flex items-center gap-1.5 rounded-lg border border-border bg-transparent px-2.5 py-1 text-[12px] text-text-main disabled:cursor-not-allowed disabled:opacity-50"+ title={providerText(t, "testAllModels", "Test all")}+ >+ <span className="material-symbols-outlined text-[16px]">+ {testingAll ? "progress_activity" : "science"}+ </span>+ <span>+ {testingAll && testProgress+ ? providerText(t, "testingAllModels", "Testing {done}/{total}", testProgress)+ : providerText(t, "testAllModels", "Test all")}+ </span>+ </button>+ )}<buttononClick={onSelectAll}disabled={selectAllDisabled}className="flex items-center gap-1.5 rounded-lg border border-border bg-transparent px-2.5 py-1 text-[12px] text-text-main disabled:cursor-not-allowed disabled:opacity-50"- title={providerText(t, "selectAllModels", "Select all")}+ title={providerText(t, "showAllModels", "Show all")}>- <span className="material-symbols-outlined text-[16px]">done_all</span>- <span>{providerText(t, "selectAllModels", "Select all")}</span>+ <span className="material-symbols-outlined text-[16px]">visibility</span>+ <span>{providerText(t, "showAllModels", "Show all")}</span></button><buttononClick={onDeselectAll}disabled={deselectAllDisabled}className="flex items-center gap-1.5 rounded-lg border border-border bg-transparent px-2.5 py-1 text-[12px] text-text-main disabled:cursor-not-allowed disabled:opacity-50"- title={providerText(t, "deselectAllModels", "Deselect all")}+ title={providerText(t, "hideAllModels", "Hide all")}>- <span className="material-symbols-outlined text-[16px]">remove_done</span>- <span>{providerText(t, "deselectAllModels", "Deselect all")}</span>+ <span className="material-symbols-outlined text-[16px]">visibility_off</span>+ <span>{providerText(t, "hideAllModels", "Hide all")}</span></button>- <span className="whitespace-nowrap text-xs text-text-muted">- {providerText(t, "modelsActiveCount", "{active}/{total} active", {- active: activeCount,- total: totalCount,- })}- </span></div>);}@@ -5780,12 +5989,78 @@ function PassthroughModelsSection({onTestModel,modelTestStatus,testingModelId,+ providerId,+ connectionId,}: PassthroughModelsSectionProps) {const [newModel, setNewModel] = useState("");const [adding, setAdding] = useState(false);const [modelFilter, setModelFilter] = useState("");+ const [testingAll, setTestingAll] = useState(false);+ const [testProgress, setTestProgress] = useState<{ done: number; total: number } | null>(null);+ const [autoHideFailed, setAutoHideFailed] = useState(true);+ const [visibilityFilter, setVisibilityFilter] = useState<"all" | "visible" | "hidden">("all");+ const notify = useNotificationStore();const customModelMap = useMemo(() => buildCompatMap(customModels), [customModels]);+ const handleTestAll = async () => {+ const modelsToTest = filteredModels.filter((m) => !m.isHidden);+ if (modelsToTest.length === 0) {+ notify.error(providerText(t, "noModelsToTest", "No models to test"));+ return;+ }+ setTestingAll(true);+ setTestProgress({ done: 0, total: modelsToTest.length });++ let ok = 0;+ let error = 0;+ let hiddenCount = 0;++ for (const model of modelsToTest) {+ try {+ const result: {+ results?: Record<+ string,+ {+ status?: "ok" | "error";+ rateLimited?: boolean;+ isTimeout?: boolean;+ error?: string;+ }+ >;+ } = await fetch("/api/models/test-all", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ providerId,+ connectionId,+ modelIds: [model.modelId],+ }),+ }).then((r) => r.json());++ const entry = result.results?.[model.modelId];+ if (entry?.status === "ok") {+ ok++;+ } else {+ error++;+ if (autoHideFailed && !entry?.rateLimited && !entry?.isTimeout) {+ await onToggleHidden(model.modelId, true);+ hiddenCount++;+ }+ }+ } catch (e) {+ error++;+ }+ setTestProgress((prev) => (prev ? { done: prev.done + 1, total: prev.total } : null));+ }++ notify.info(providerText(t, "testAllResults", "{ok} ok, {error} error", { ok, error }));+ if (hiddenCount > 0) {+ notify.info(providerText(t, "testAllFailedHidden", "{count} hidden", { count: hiddenCount }));+ }+ setTestingAll(false);+ setTestProgress(null);+ };+const providerAliases = useMemo(() =>Object.entries(modelAliases).filter(([, model]: [string, any]) =>@@ -5874,14 +6149,23 @@ function PassthroughModelsSection({providerAlias,providerAliases,]);- const filteredModels = allModels.filter((model) =>- matchesModelCatalogQuery(modelFilter, {+ const filteredModels = allModels.filter((model) => {+ const matchesQuery = matchesModelCatalogQuery(modelFilter, {modelId: model.modelId,modelName: model.displayName,alias: model.alias,source: model.source,- })- );+ });++ const matchesVisibility =+ visibilityFilter === "all"+ ? true+ : visibilityFilter === "visible"+ ? !model.isHidden+ : model.isHidden;++ return matchesQuery && matchesVisibility;+ });const activeCount = allModels.filter((model) => !model.isHidden).length;const hiddenFilteredCount = filteredModels.filter((model) => model.isHidden).length;const visibleFilteredCount = filteredModels.length - hiddenFilteredCount;@@ -5908,7 +6192,7 @@ function PassthroughModelsSection({await onSetAlias(modelId, defaultAlias);setNewModel("");} catch (error) {- console.log("Error adding model:", error);+ console.error("Error adding model:", error);} finally {setAdding(false);}@@ -5950,18 +6234,24 @@ function PassthroughModelsSection({totalCount={allModels.length}onSelectAll={() =>onBulkToggleHidden(- filteredModels.map((model) => model.modelId),+ filteredModels.map((m) => m.modelId),false)}onDeselectAll={() =>onBulkToggleHidden(- filteredModels.map((model) => model.modelId),+ filteredModels.map((m) => m.modelId),true)}- selectAllDisabled={hiddenFilteredCount === 0 || bulkTogglePending}- deselectAllDisabled={visibleFilteredCount === 0 || bulkTogglePending}+ selectAllDisabled={bulkTogglePending || filteredModels.length === 0}+ deselectAllDisabled={bulkTogglePending || filteredModels.length === 0}+ onTestAll={handleTestAll}+ testingAll={testingAll}+ visibilityFilter={visibilityFilter}+ onVisibilityFilterChange={setVisibilityFilter}+ autoHideFailed={autoHideFailed}+ onAutoHideFailedChange={setAutoHideFailed}/><div className="grid grid-cols-1 gap-3 xl:grid-cols-2">{filteredModels.map(({ modelId, fullModel, alias, isHidden, source, isFree }) => (@@ -6687,11 +6977,17 @@ function CompatibleModelsSection({onTestModel,modelTestStatus,testingModelId,+ onTestAll,+ testingAll,+ testProgress,+ autoHideFailed,+ onAutoHideFailedChange,}: CompatibleModelsSectionProps) {const [newModel, setNewModel] = useState("");const [adding, setAdding] = useState(false);const [importing, setImporting] = useState(false);const [modelFilter, setModelFilter] = useState("");+ const [visibilityFilter, setVisibilityFilter] = useState<"all" | "visible" | "hidden">("all");const notify = useNotificationStore();const customModelMap = useMemo(() => buildCompatMap(customModels), [customModels]);@@ -6782,14 +7078,21 @@ function CompatibleModelsSection({providerAliases,providerStorageAlias,]);- const filteredModels = allModels.filter((model) =>- matchesModelCatalogQuery(modelFilter, {+ const filteredModels = allModels.filter((model) => {+ const matchesQuery = matchesModelCatalogQuery(modelFilter, {modelId: model.modelId,modelName: model.displayName,alias: model.alias,source: model.source,- })- );+ });+ const matchesVisibility =+ visibilityFilter === "all"+ ? true+ : visibilityFilter === "visible"+ ? !model.isHidden+ : model.isHidden;+ return matchesQuery && matchesVisibility;+ });const activeCount = allModels.filter((model) => !model.isHidden).length;const hiddenFilteredCount = filteredModels.filter((model) => model.isHidden).length;const visibleFilteredCount = filteredModels.length - hiddenFilteredCount;@@ -6956,6 +7259,21 @@ function CompatibleModelsSection({}selectAllDisabled={hiddenFilteredCount === 0 || bulkTogglePending}deselectAllDisabled={visibleFilteredCount === 0 || bulkTogglePending}+ visibilityFilter={visibilityFilter}+ onVisibilityFilterChange={setVisibilityFilter}+ onTestAll={() => {+ const targets = filteredModels+ .filter((m) => !m.isHidden)+ .map((m) => ({+ modelId: m.modelId,+ fullModel: `${providerDisplayAlias}/${m.modelId}`,+ }));+ return onTestAll?.(targets);+ }}+ testingAll={testingAll}+ testProgress={testProgress}+ autoHideFailed={autoHideFailed}+ onAutoHideFailedChange={onAutoHideFailedChange}/><div className="grid grid-cols-1 gap-3 xl:grid-cols-2">{filteredModels.map(({ modelId, alias, isHidden, source, isFree }) => {@@ -7050,8 +7368,8 @@ const ERROR_TYPE_LABELS = {network_error: { labelKey: "errorTypeNetworkError", variant: "warning" },unsupported: { labelKey: "errorTypeTestUnsupported", variant: "default" },upstream_error: { labelKey: "errorTypeUpstreamError", variant: "error" },- banned: { labelKey: "403 Banned", variant: "error" },- credits_exhausted: { labelKey: "No Credits", variant: "warning" },+ banned: { labelKey: "errorTypeBanned", variant: "error" },+ credits_exhausted: { labelKey: "errorTypeCreditsExhausted", variant: "warning" },};function inferErrorType(connection, isCooldown) {@@ -10331,6 +10649,11 @@ function EditConnectionModal({ isOpen, connection, onSave, onClose }: EditConnecname: "",priority: 1,maxConcurrent: "",+ rpm: "",+ tpm: "",+ tpd: "",+ minTime: "",+ rateLimitMaxConcurrent: "",apiKey: "",healthCheckInterval: 60,baseUrl: "",@@ -10460,6 +10783,26 @@ function EditConnectionModal({ isOpen, connection, onSave, onClose }: EditConnecconnection.maxConcurrent !== null && connection.maxConcurrent !== undefined? String(connection.maxConcurrent): "",+ rpm:+ connection.rateLimitOverrides?.rpm != null+ ? String(connection.rateLimitOverrides.rpm)+ : "",+ tpm:+ connection.rateLimitOverrides?.tpm != null+ ? String(connection.rateLimitOverrides.tpm)+ : "",+ tpd:+ connection.rateLimitOverrides?.tpd != null+ ? String(connection.rateLimitOverrides.tpd)+ : "",+ minTime:+ connection.rateLimitOverrides?.minTime != null+ ? String(connection.rateLimitOverrides.minTime)+ : "",+ rateLimitMaxConcurrent:+ connection.rateLimitOverrides?.maxConcurrent != null+ ? String(connection.rateLimitOverrides.maxConcurrent)+ : "",apiKey: "",healthCheckInterval: connection.healthCheckInterval ?? 60,baseUrl: existingBaseUrl || defaultBaseUrl,@@ -10613,6 +10956,16 @@ function EditConnectionModal({ isOpen, connection, onSave, onClose }: EditConnechealthCheckInterval: formData.healthCheckInterval,};+ // Build rateLimitOverrides from non-empty fields+ const overrides: Record<string, number> = {};+ if (formData.rpm.trim()) overrides.rpm = Number(formData.rpm);+ if (formData.tpm.trim()) overrides.tpm = Number(formData.tpm);+ if (formData.tpd.trim()) overrides.tpd = Number(formData.tpd);+ if (formData.minTime.trim()) overrides.minTime = Number(formData.minTime);+ if (formData.rateLimitMaxConcurrent.trim())+ overrides.maxConcurrent = Number(formData.rateLimitMaxConcurrent);+ updates.rateLimitOverrides = Object.keys(overrides).length > 0 ? overrides : null;+if (supportsGoogleProjectId) {updates.projectId = trimmedCloudCodeProjectId || null;}@@ -11057,6 +11410,60 @@ function EditConnectionModal({ isOpen, connection, onSave, onClose }: EditConnectype="password"/>)}+ <div className="border-t border-border/30 pt-3 mt-1">+ <p className="text-xs font-medium text-text-muted mb-2">+ {t("rateLimitOverridesSection")}+ </p>+ <div className="grid grid-cols-2 gap-3">+ <Input+ label={t("rateLimitOverridesRpmLabel")}+ type="number"+ min={0}+ value={formData.rpm}+ onChange={(e) => setFormData({ ...formData, rpm: e.target.value })}+ placeholder="Inherit"+ hint={t("rateLimitOverridesRpmHint")}+ />+ <Input+ label={t("rateLimitOverridesTpmLabel")}+ type="number"+ min={0}+ value={formData.tpm}+ onChange={(e) => setFormData({ ...formData, tpm: e.target.value })}+ placeholder="Inherit"+ hint={t("rateLimitOverridesTpmHint")}+ />+ <Input+ label={t("rateLimitOverridesTpdLabel")}+ type="number"+ min={0}+ value={formData.tpd}+ onChange={(e) => setFormData({ ...formData, tpd: e.target.value })}+ placeholder="Inherit"+ hint={t("rateLimitOverridesTpdHint")}+ />+ <Input+ label={t("rateLimitOverridesMinTimeLabel")}+ type="number"+ min={0}+ value={formData.minTime}+ onChange={(e) => setFormData({ ...formData, minTime: e.target.value })}+ placeholder="Inherit"+ hint={t("rateLimitOverridesMinTimeHint")}+ />+ <Input+ label={t("rateLimitOverridesMaxConcurrentLabel")}+ type="number"+ min={0}+ value={formData.rateLimitMaxConcurrent}+ onChange={(e) =>+ setFormData({ ...formData, rateLimitMaxConcurrent: e.target.value })+ }+ placeholder="Inherit"+ hint={t("rateLimitOverridesMaxConcurrentHint")}+ />+ </div>+ </div></div>)}<Inputdiff --git a/src/app/(dashboard)/dashboard/providers/[id]/webSessionCredentials.ts b/src/app/(dashboard)/dashboard/providers/[id]/webSessionCredentials.tsindex e45b580e54..bdd8a9cf14 100644--- a/src/app/(dashboard)/dashboard/providers/[id]/webSessionCredentials.ts+++ b/src/app/(dashboard)/dashboard/providers/[id]/webSessionCredentials.ts@@ -137,6 +137,36 @@ export const WEB_SESSION_CREDENTIAL_REQUIREMENTS = {placeholder: "Paste your Qwen token from chat.qwen.ai (Local Storage → token)",acceptsFullCookieHeader: false,},+ "duckduckgo-web": {+ kind: "cookie",+ credentialName: "duckai",+ placeholder: "duckai=... or full Cookie header from duckduckgo.com",+ acceptsFullCookieHeader: true,+ },+ "t3-chat-web": {+ kind: "token",+ credentialName: "token",+ placeholder: "Paste your T3 Chat token from t3.chat (Local Storage → token)",+ acceptsFullCookieHeader: false,+ },+ "chatglm-web": {+ kind: "cookie",+ credentialName: "chatglm_session",+ placeholder: "chatglm_session=... or full Cookie header from chatglm.cn",+ acceptsFullCookieHeader: true,+ },+ "xiaomimimo-web": {+ kind: "cookie",+ credentialName: "session",+ placeholder: "session=... or full Cookie header from aistudio.xiaomimimo.com",+ acceptsFullCookieHeader: true,+ },+ "manus-web": {+ kind: "cookie",+ credentialName: "manus_session",+ placeholder: "manus_session=... or full Cookie header from manus.im",+ acceptsFullCookieHeader: true,+ },} satisfies Record<keyof typeof WEB_COOKIE_PROVIDERS, WebSessionCredentialRequirement>;export function getWebSessionCredentialRequirement(diff --git a/src/app/(dashboard)/dashboard/providers/providerPageUtils.ts b/src/app/(dashboard)/dashboard/providers/providerPageUtils.tsindex 845a82a64e..8da41a3e1b 100644--- a/src/app/(dashboard)/dashboard/providers/providerPageUtils.ts+++ b/src/app/(dashboard)/dashboard/providers/providerPageUtils.ts@@ -107,7 +107,12 @@ export function filterConfiguredProviderEntries<TProvider>(let filtered = entries;if (showConfiguredOnly) {- filtered = filtered.filter((entry) => Number(entry.stats?.total || 0) > 0);+ // no-auth providers never create a DB connection row (stats.total === 0) but+ // are always usable and appear unconditionally in the /v1/models catalog, so+ // they must not be hidden by the configured-only filter (#3290).+ filtered = filtered.filter(+ (entry) => entry.displayAuthType === "no-auth" || Number(entry.stats?.total || 0) > 0+ );}if (showFreeOnly) {diff --git a/src/app/(dashboard)/dashboard/settings/components/ProxyTab.tsx b/src/app/(dashboard)/dashboard/settings/components/ProxyTab.tsxindex bd77236dee..f08fa359fd 100644--- a/src/app/(dashboard)/dashboard/settings/components/ProxyTab.tsx+++ b/src/app/(dashboard)/dashboard/settings/components/ProxyTab.tsx@@ -38,7 +38,7 @@ export default function ProxyTab() {<divclassName="flex gap-1 border-b border-border overflow-x-auto"role="tablist"- aria-label="Proxy sections"+ aria-label={t("proxySubTabsAria")}>{TABS.map((tab) => (<buttondiff --git a/src/app/(dashboard)/dashboard/settings/components/proxy/DocumentationTab.tsx b/src/app/(dashboard)/dashboard/settings/components/proxy/DocumentationTab.tsxindex c9ddc8e42e..ea6ddde29f 100644--- a/src/app/(dashboard)/dashboard/settings/components/proxy/DocumentationTab.tsx+++ b/src/app/(dashboard)/dashboard/settings/components/proxy/DocumentationTab.tsx@@ -1,60 +1,62 @@"use client";+import { useTranslations } from "next-intl";import { Card } from "@/shared/components";export default function DocumentationTab() {+ const t = useTranslations("settings");+return (<Card className="p-6 space-y-6"><section>- <h3 className="font-semibold mb-2">Proxy scope resolution</h3>+ <h3 className="font-semibold mb-2">{t("proxyDocumentationScopeTitle")}</h3><p className="text-sm text-text-muted">- OmniRoute resolves the outbound proxy in priority order:- <strong> combo → account → provider → global</strong>. The most specific scope wins.+ {t("proxyDocumentationScopeDescBefore")}+ <strong>{t("proxyDocumentationScopeOrder")}</strong>+ {t("proxyDocumentationScopeDescAfter")}</p></section><section>- <h3 className="font-semibold mb-2">Adding a custom proxy</h3>+ <h3 className="font-semibold mb-2">{t("proxyDocumentationAddTitle")}</h3><p className="text-sm text-text-muted">- Go to the <strong>Proxy Pool</strong> tab → click <em>+ Add proxy</em>. Fill in type- (http/https/socks5), host, and port. Optionally assign it to a scope.+ {t("proxyDocumentationAddDescBefore")}+ <strong>{t("proxyPoolTab")}</strong>+ {t("proxyDocumentationAddDescMiddle")}+ <em>{t("proxyDocumentationAddCta")}</em>+ {t("proxyDocumentationAddDescAfter")}</p></section><section>- <h3 className="font-semibold mb-2">Bulk import format</h3>+ <h3 className="font-semibold mb-2">{t("proxyDocumentationBulkTitle")}</h3><pre className="text-xs bg-surface-alt/50 p-3 rounded mt-1 overflow-x-auto">{`http://user:[email protected]:8080\nhttps://5.6.7.8:3128\nsocks5://9.0.1.2:1080`}</pre><p className="text-sm text-text-muted mt-1">- Pipe-delimited fields: <code>type|host|port|user|pass|name</code>+ {t("proxyDocumentationBulkDesc")} <code>type|host|port|user|pass|name</code></p></section><section><h3 className="font-semibold mb-2">SOCKS5</h3><p className="text-sm text-text-muted">- SOCKS5 proxies are disabled by default. Set{" "}+ {t("proxyDocumentationSocks5DescBefore")}{" "}<code className="bg-surface-alt px-1 rounded">ENABLE_SOCKS5_PROXY=true</code> to enable.</p></section><section>- <h3 className="font-semibold mb-2">Free Pool</h3>+ <h3 className="font-semibold mb-2">{t("freePoolTab")}</h3><p className="text-sm text-text-muted">- The Free Pool tab aggregates proxies from 1proxy, Proxifly, and IPLocate. Use ⊕ to test- and promote a proxy to your registry. Only proxies that pass the connectivity test are- added.+ {t("proxyDocumentationFreePoolDesc")}</p></section><section><h3 className="font-semibold mb-2">Vercel Relay</h3><p className="text-sm text-text-muted">- The Vercel Relay is an outbound edge relay — not an inbound tunnel. Deploying one sends- LLM API calls through Vercel's dynamic IPs, bypassing datacenter geo-blocks and rate- limits. The relay is protected by a generated secret header (- <code className="bg-surface-alt px-1 rounded">x-relay-auth</code>). Your Vercel token is- used only during deploy and is never stored.+ {t("proxyDocumentationVercelRelayDescBefore")} (+ <code className="bg-surface-alt px-1 rounded">x-relay-auth</code>). {t("proxyDocumentationVercelRelayDescAfter")}</p></section></Card>diff --git a/src/app/(dashboard)/dashboard/settings/components/proxy/FreePoolTab.tsx b/src/app/(dashboard)/dashboard/settings/components/proxy/FreePoolTab.tsxindex f2f46d73c8..8308fb6148 100644--- a/src/app/(dashboard)/dashboard/settings/components/proxy/FreePoolTab.tsx+++ b/src/app/(dashboard)/dashboard/settings/components/proxy/FreePoolTab.tsx@@ -1,5 +1,6 @@"use client";import { useState, useEffect, useCallback } from "react";+import { useTranslations } from "next-intl";import { Button } from "@/shared/components";import SourceToggleBar, {type SourceId,@@ -17,6 +18,7 @@ type FreePoolStats = {};export default function FreePoolTab() {+ const t = useTranslations("settings");const [proxies, setProxies] = useState<FreeProxyRowData[]>([]);const [stats, setStats] = useState<FreePoolStats | null>(null);const [disabledSources, setDisabledSources] = useState<Set<SourceId>>(new Set());@@ -148,9 +150,9 @@ export default function FreePoolTab() {value={filterProtocol}onChange={(e) => setFilterProtocol(e.target.value)}className="text-xs bg-surface-alt border border-border rounded px-2 py-1"- aria-label="Filter by protocol"+ aria-label={t("proxyFreePoolFilterProtocol")}>- <option value="">Protocol</option>+ <option value="">{t("proxyFreePoolProtocol")}</option>{["http", "https", "socks4", "socks5"].map((p) => (<option key={p} value={p}>{p.toUpperCase()}@@ -159,44 +161,44 @@ export default function FreePoolTab() {</select><inputtype="text"- placeholder="Country (e.g. US)"+ placeholder={t("proxyFreePoolCountryPlaceholder")}value={filterCountry}onChange={(e) => setFilterCountry(e.target.value.toUpperCase().slice(0, 2))}className="text-xs bg-surface-alt border border-border rounded px-2 py-1 w-28"- aria-label="Filter by country"+ aria-label={t("proxyFreePoolFilterCountry")}/><inputtype="number"- placeholder="Min quality"+ placeholder={t("proxyFreePoolMinQualityPlaceholder")}value={minQuality}onChange={(e) => setMinQuality(e.target.value)}min={0}max={100}className="text-xs bg-surface-alt border border-border rounded px-2 py-1 w-24"- aria-label="Minimum quality score"+ aria-label={t("proxyFreePoolMinQualityLabel")}/><Button size="sm" variant="secondary" icon="sync" onClick={handleSync} disabled={syncing}>- {syncing ? "Syncing..." : "Sync All"}+ {syncing ? t("syncing") : t("proxyFreePoolSyncAll")}</Button></div></div>{stats && (<div className="text-xs text-text-muted flex gap-4 flex-wrap">- <span>Total: {stats.total}</span>- <span>In pool: {stats.inPool}</span>- {stats.avgQuality != null && <span>Avg quality: {stats.avgQuality}</span>}+ <span>{t("proxyFreePoolTotal")}: {stats.total}</span>+ <span>{t("proxyFreePoolInPool")}: {stats.inPool}</span>+ {stats.avgQuality != null && <span>{t("proxyFreePoolAvgQuality")}: {stats.avgQuality}</span>}{stats.lastSyncAt && (- <span>Last sync: {new Date(stats.lastSyncAt).toLocaleTimeString()}</span>+ <span>{t("lastSync")}: {new Date(stats.lastSyncAt).toLocaleTimeString()}</span>)}</div>)}{selected.size > 0 && (<div className="flex items-center gap-2 p-2 bg-primary/10 rounded border border-primary/20">- <span className="text-xs">{selected.size} selected</span>+ <span className="text-xs">{t("proxyFreePoolSelected", { count: selected.size })}</span><Button size="sm" variant="primary" onClick={() => handleBulkAdd(Array.from(selected))}>- ⊕ Add selected to pool+ {t("proxyFreePoolAddSelected")}</Button>{bulkProgress && <span className="text-xs text-text-muted">{bulkProgress}</span>}</div>@@ -209,7 +211,7 @@ export default function FreePoolTab() {variant="secondary"onClick={() => handleBulkAdd(notInPoolProxies.slice(0, 100).map((p) => p.id))}>- ⊕ Add all visible to pool+ {t("proxyFreePoolAddVisible")}</Button></div>)}@@ -220,22 +222,22 @@ export default function FreePoolTab() {<tr><th className="px-3 py-2 text-left w-8" scope="col"></th><th className="px-3 py-2 text-left" scope="col">- Source+ {t("proxyFreePoolSource")}</th><th className="px-3 py-2 text-left" scope="col">- Host:Port+ {t("proxyFreePoolHostPort")}</th><th className="px-3 py-2 text-left" scope="col">- Type+ {t("proxyFreePoolType")}</th><th className="px-3 py-2 text-left" scope="col">- Country+ {t("proxyFreePoolCountry")}</th><th className="px-3 py-2 text-left" scope="col">- Quality+ {t("proxyFreePoolQuality")}</th><th className="px-3 py-2 text-left" scope="col">- Latency+ {t("proxyFreePoolLatency")}</th><th className="px-3 py-2 text-left" scope="col"></th></tr>@@ -244,13 +246,13 @@ export default function FreePoolTab() {{loading ? (<tr><td colSpan={8} className="px-3 py-8 text-center text-text-muted">- Loading...+ {t("loading")}</td></tr>) : proxies.length === 0 ? (<tr><td colSpan={8} className="px-3 py-8 text-center text-text-muted">- No proxies found. Click Sync All to fetch from sources.+ {t("proxyFreePoolEmpty")}</td></tr>) : (diff --git a/src/app/(dashboard)/dashboard/settings/components/proxy/VercelRelayModal.tsx b/src/app/(dashboard)/dashboard/settings/components/proxy/VercelRelayModal.tsxindex 80b88edbc1..794674f119 100644--- a/src/app/(dashboard)/dashboard/settings/components/proxy/VercelRelayModal.tsx+++ b/src/app/(dashboard)/dashboard/settings/components/proxy/VercelRelayModal.tsx@@ -20,7 +20,7 @@ export default function VercelRelayModal({ isOpen, onClose, onDeployed }: Vercelconst handleDeploy = async () => {if (!token.trim()) {- setError("Token is required");+ setError(t("vercelRelayTokenRequired"));return;}setDeploying(true);@@ -33,14 +33,14 @@ export default function VercelRelayModal({ isOpen, onClose, onDeployed }: Vercel});const data = await res.json();if (!res.ok || !data.success) {- setError(data.error?.message || "Deploy failed");+ setError(data.error?.message || t("vercelRelayDeployFailed"));} else {setToken("");onDeployed(data.poolProxyId as string, data.relayUrl as string);onClose();}} catch (err) {- setError(err instanceof Error ? err.message : "Unknown error");+ setError(err instanceof Error ? err.message : t("unknownError"));} finally {setDeploying(false);}@@ -63,7 +63,7 @@ export default function VercelRelayModal({ isOpen, onClose, onDeployed }: Vercel</span>{t("vercelRelayModalTitle")}</h2>- <button onClick={onClose} aria-label="Close" className="text-text-muted hover:text-text">+ <button onClick={onClose} aria-label={t("close")} className="text-text-muted hover:text-text"><span className="material-symbols-outlined" aria-hidden="true">close</span>@@ -89,7 +89,7 @@ export default function VercelRelayModal({ isOpen, onClose, onDeployed }: VercelautoComplete="off"/><p className="text-xs text-text-muted mt-1">- Token is used only during deploy — never stored.+ {t("vercelRelayTokenHint")}</p></div><div>@@ -117,7 +117,7 @@ export default function VercelRelayModal({ isOpen, onClose, onDeployed }: Vercel<div className="flex justify-end gap-2 pt-2"><Button variant="secondary" size="sm" onClick={onClose} disabled={deploying}>- Cancel+ {t("cancel")}</Button><Button variant="primary" size="sm" onClick={handleDeploy} disabled={deploying}>{deploying ? t("vercelRelayDeploying") : t("vercelRelayDeploy")}diff --git a/src/app/(dashboard)/dashboard/tools/agent-bridge/hooks/useAgentBridgeState.ts b/src/app/(dashboard)/dashboard/tools/agent-bridge/hooks/useAgentBridgeState.tsindex 02b9074b0e..630cac8344 100644--- a/src/app/(dashboard)/dashboard/tools/agent-bridge/hooks/useAgentBridgeState.ts+++ b/src/app/(dashboard)/dashboard/tools/agent-bridge/hooks/useAgentBridgeState.ts@@ -2,6 +2,7 @@import { useCallback, useEffect, useRef, useState } from "react";import type { AgentBridgePageData } from "../AgentBridgePageClient";+import { normalizeAgentBridgeState } from "../normalizeState";interface UseAgentBridgeStateOptions {initialData: AgentBridgePageData;@@ -39,7 +40,9 @@ export function useAgentBridgeState({signal: ctrl.signal,});if (!res.ok) throw new Error(`HTTP ${res.status}`);- const json = (await res.json()) as AgentBridgePageData;+ // #3318: normalize the /state response so a key mismatch can't leave+ // serverState undefined and crash the page on the next render.+ const json = normalizeAgentBridgeState(await res.json());if (!ctrl.signal.aborted) setData(json);} catch (err) {if (!ctrl.signal.aborted) {diff --git a/src/app/(dashboard)/dashboard/tools/agent-bridge/normalizeState.ts b/src/app/(dashboard)/dashboard/tools/agent-bridge/normalizeState.tsnew file mode 100644index 0000000000..43763f9aa8--- /dev/null+++ b/src/app/(dashboard)/dashboard/tools/agent-bridge/normalizeState.ts@@ -0,0 +1,76 @@+import type {+ AgentBridgePageData,+ AgentBridgeServerState,+ AgentStateEntry,+ AgentMappingsMap,+} from "./AgentBridgePageClient";++function defaultServerState(): AgentBridgeServerState {+ return {+ running: false,+ port: 443,+ certTrusted: false,+ upstreamCa: null,+ lastStartedAt: null,+ activeConns: 0,+ interceptedCount: 0,+ };+}++export const DEFAULT_AGENT_BRIDGE_STATE: AgentBridgePageData = {+ serverState: defaultServerState(),+ agentStates: [],+ bypassPatterns: [],+ mappings: {},+};++function isRecord(v: unknown): v is Record<string, unknown> {+ return typeof v === "object" && v !== null && !Array.isArray(v);+}++/**+ * Normalize whatever `/api/tools/agent-bridge/state` returns into the shape the+ * page/components require, ALWAYS returning a well-formed object (#3318).+ *+ * The page previously assigned the raw response straight into `initialData`, but+ * the route returns `{ server, agents }` while the UI reads+ * `{ serverState, agentStates, bypassPatterns, mappings }` — leaving+ * `serverState` undefined and crashing `serverState.running`.+ *+ * This maps the known server fields through (incl. the legacy `server` key →+ * `serverState`, `server.certExists` → `certTrusted`) and falls back to safe+ * defaults for everything else, so the page renders instead of crashing.+ * Note: the legacy `agents` payload has a different per-entry shape than+ * `AgentStateEntry`, so it is intentionally NOT coerced — `agentStates` defaults+ * to `[]` unless the response already provides the correct `agentStates` key.+ */+export function normalizeAgentBridgeState(raw: unknown): AgentBridgePageData {+ if (!isRecord(raw)) return { ...DEFAULT_AGENT_BRIDGE_STATE, serverState: defaultServerState() };++ const serverState = defaultServerState();+ const source = isRecord(raw.serverState)+ ? raw.serverState+ : isRecord(raw.server)+ ? raw.server+ : undefined;+ if (source) {+ if (typeof source.running === "boolean") serverState.running = source.running;+ if (typeof source.port === "number") serverState.port = source.port;+ // accept both the canonical `certTrusted` and the legacy `certExists`+ if (typeof source.certTrusted === "boolean") serverState.certTrusted = source.certTrusted;+ else if (typeof source.certExists === "boolean") serverState.certTrusted = source.certExists;+ if (typeof source.upstreamCa === "string") serverState.upstreamCa = source.upstreamCa;+ if (typeof source.lastStartedAt === "string") serverState.lastStartedAt = source.lastStartedAt;+ if (typeof source.activeConns === "number") serverState.activeConns = source.activeConns;+ if (typeof source.interceptedCount === "number") {+ serverState.interceptedCount = source.interceptedCount;+ }+ }++ return {+ serverState,+ agentStates: Array.isArray(raw.agentStates) ? (raw.agentStates as AgentStateEntry[]) : [],+ bypassPatterns: Array.isArray(raw.bypassPatterns) ? (raw.bypassPatterns as string[]) : [],+ mappings: isRecord(raw.mappings) ? (raw.mappings as AgentMappingsMap) : {},+ };+}diff --git a/src/app/(dashboard)/dashboard/tools/agent-bridge/page.tsx b/src/app/(dashboard)/dashboard/tools/agent-bridge/page.tsxindex f72049d483..9ce144cc7d 100644--- a/src/app/(dashboard)/dashboard/tools/agent-bridge/page.tsx+++ b/src/app/(dashboard)/dashboard/tools/agent-bridge/page.tsx@@ -2,6 +2,7 @@ import { getProviderConnections } from "@/lib/db/providers";import { ALL_TARGETS } from "@/mitm/targets/index";import AgentBridgePageClient from "./AgentBridgePageClient";import type { AgentBridgePageData } from "./AgentBridgePageClient";+import { normalizeAgentBridgeState } from "./normalizeState";/*** AgentBridge page — Server Component entry point.@@ -44,8 +45,10 @@ export default async function AgentBridgePage() {headers: { "x-internal-fetch": "1" },});if (res.ok) {- const json = (await res.json()) as AgentBridgePageData;- initialData = json;+ // #3318: normalize — the /state route returns `{ server, agents }`, not the+ // page's `{ serverState, ... }` shape; replacing initialData verbatim left+ // serverState undefined and crashed the page.+ initialData = normalizeAgentBridgeState(await res.json());}} catch {// Backend not yet available — use defaults; client will polldiff --git a/src/app/(dashboard)/dashboard/translator/hooks/useAvailableModels.tsx b/src/app/(dashboard)/dashboard/translator/hooks/useAvailableModels.tsxindex 9b2a0424d1..c0e5ec525e 100644--- a/src/app/(dashboard)/dashboard/translator/hooks/useAvailableModels.tsx+++ b/src/app/(dashboard)/dashboard/translator/hooks/useAvailableModels.tsx@@ -1,6 +1,6 @@"use client";-import { useState, useEffect, useCallback } from "react";+import { useState, useEffect, useCallback, useMemo } from "react";import { compareTr } from "@/shared/utils/turkishText";/**@@ -25,9 +25,9 @@ const FORMAT_MODEL_PREFIXES = {* pickModelForFormat: (format: string) => string* }}*/-export function useAvailableModels() {+export function useAvailableModels(provider?: string) {const [model, setModel] = useState("");- const [availableModels, setAvailableModels] = useState([]);+ const [allModels, setAllModels] = useState<string[]>([]);const [loading, setLoading] = useState(true);useEffect(() => {@@ -36,9 +36,9 @@ export function useAvailableModels() {const res = await fetch("/api/v1/models");const data = await res.json();const models = (data.data || []).map((m) => m.id).sort((a, b) => compareTr(a, b));- setAvailableModels(models);+ setAllModels(models);} catch {- setAvailableModels([]);+ setAllModels([]);} finally {setLoading(false);}@@ -46,6 +46,12 @@ export function useAvailableModels() {fetchModels();}, []);+ const availableModels = useMemo(() => {+ return provider+ ? allModels.filter((m) => m.startsWith(`${provider}/`) || m === provider)+ : allModels;+ }, [allModels, provider]);+/*** Pick the best model for a given format from the available models.* Returns the first model matching the format prefixes, or the first available model.diff --git a/src/app/api/models/test-all/route.ts b/src/app/api/models/test-all/route.tsnew file mode 100644index 0000000000..bd0913df41--- /dev/null+++ b/src/app/api/models/test-all/route.ts@@ -0,0 +1,196 @@+/**+ * Batch model-test endpoint.+ *+ * Loops sequentially over `modelIds` so the `withRateLimit` Bottleneck can+ * serialize dispatches against the upstream provider/connection. Stops the+ * loop early if it sees `CONSECUTIVE_RATE_LIMIT_STOP_THRESHOLD` rate-limited+ * results in a row — a 429 storm usually means the upstream is down and the+ * remaining models will only burn the timeout window.+ *+ * When `autoHideFailed` is true, models that return a hard error (NOT+ * rate-limited) are persisted as hidden via `setModelIsHidden`.+ */+import { NextResponse } from "next/server";+import { z } from "zod";+import { requireManagementAuth } from "@/lib/api/requireManagementAuth";+import { runSingleModelTest } from "@/lib/api/modelTestRunner";+import { setModelIsHidden } from "@/lib/localDb";+import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error";+import * as log from "@/sse/utils/logger";++const PER_MODEL_TIMEOUT_MS = 20_000;+const CONSECUTIVE_RATE_LIMIT_STOP_THRESHOLD = 3;++const testAllSchema = z.object({+ providerId: z.string().min(1),+ modelIds: z.array(z.string().min(1)).min(1).max(100),+ connectionId: z.string().optional(),+ respectRateLimit: z.boolean().optional().default(true),+ autoHideFailed: z.boolean().optional().default(false),+});++export interface BatchTestResultEntry {+ status: "ok" | "error";+ latencyMs: number;+ responseText?: string;+ error?: string;+ statusCode?: number;+ rateLimited?: boolean;+ hidden?: boolean;+ isTimeout?: boolean;+}++function toBatchEntry(+ result: Awaited<ReturnType<typeof runSingleModelTest>>+): BatchTestResultEntry {+ const entry: BatchTestResultEntry = {+ status: result.status === "ok" ? "ok" : "error",+ latencyMs: result.latencyMs,+ };+ if (result.responseText !== undefined) entry.responseText = result.responseText;+ if (result.error !== undefined) entry.error = result.error;+ if (result.statusCode !== undefined) entry.statusCode = result.statusCode;+ if (result.rateLimited === true) entry.rateLimited = true;+ if (result.isTimeout === true) entry.isTimeout = true;+ return entry;+}++export async function POST(request: Request) {+ const authError = await requireManagementAuth(request);+ if (authError) return authError;++ let rawBody: unknown;+ try {+ rawBody = await request.json();+ } catch {+ return NextResponse.json(+ {+ error: {+ message: "Invalid request",+ details: [{ field: "body", message: "Invalid JSON body" }],+ },+ },+ { status: 400 }+ );+ }++ const validation = testAllSchema.safeParse(rawBody);+ if (!validation.success) {+ return NextResponse.json({ error: validation.error.format() }, { status: 400 });+ }+ const { providerId, modelIds, connectionId, respectRateLimit, autoHideFailed } = validation.data;++ log.info(+ "MODEL_TEST_ALL",+ `Starting batch test for ${modelIds.length} model(s) on provider ${providerId}`,+ {+ providerId,+ modelCount: modelIds.length,+ hasConnection: Boolean(connectionId),+ respectRateLimit,+ autoHideFailed,+ }+ );++ const results: Record<string, BatchTestResultEntry> = {};+ let consecutiveRateLimits = 0;+ let stoppedEarly = false;+ let stopReason: "consecutive_rate_limits" | undefined;++ for (const modelId of modelIds) {+ let entry: BatchTestResultEntry;+ try {+ // `runSingleModelTest` only engages the Bottleneck rate limiter when+ // `connectionId` is provided. To honor `respectRateLimit=false`, we+ // omit the connectionId so the runner bypasses `withRateLimit`.+ const effectiveConnectionId =+ connectionId && respectRateLimit !== false ? connectionId : undefined;+ const result = await runSingleModelTest({+ providerId,+ modelId,+ ...(effectiveConnectionId ? { connectionId: effectiveConnectionId } : {}),+ timeoutMs: PER_MODEL_TIMEOUT_MS,+ });+ entry = toBatchEntry(result);+ } catch (error: unknown) {+ log.error("MODEL_TEST_ALL", `Unexpected error testing model ${modelId}`, {+ providerId,+ modelId,+ error: sanitizeErrorMessage(error),+ });+ entry = {+ status: "error",+ latencyMs: 0,+ error: sanitizeErrorMessage(error) || "Unknown error",+ };+ }++ if (entry.rateLimited) {+ consecutiveRateLimits += 1;+ } else {+ consecutiveRateLimits = 0;+ }++ if (autoHideFailed && entry.status === "error" && !entry.rateLimited && !entry.isTimeout) {+ try {+ await setModelIsHidden(providerId, modelId, true);+ entry.hidden = true;+ log.info("MODEL_TEST_ALL", `Auto-hidden model ${modelId} after test failure`, {+ providerId,+ modelId,+ });+ } catch (hideError: unknown) {+ log.error("MODEL_TEST_ALL", `Failed to auto-hide model ${modelId}`, {+ providerId,+ modelId,+ error: sanitizeErrorMessage(hideError),+ });+ }+ }++ results[modelId] = entry;+ log.info(+ "MODEL_TEST_ALL",+ `Tested ${modelId}: ${entry.status}${entry.rateLimited ? " (rate-limited)" : ""}${entry.isTimeout ? " (timeout)" : ""}`,+ {+ providerId,+ modelId,+ latencyMs: entry.latencyMs,+ rateLimited: entry.rateLimited,+ isTimeout: entry.isTimeout,+ hidden: entry.hidden,+ }+ );++ if (consecutiveRateLimits >= CONSECUTIVE_RATE_LIMIT_STOP_THRESHOLD) {+ stoppedEarly = true;+ stopReason = "consecutive_rate_limits";+ log.warn(+ "MODEL_TEST_ALL",+ `Stopping batch early after ${consecutiveRateLimits} consecutive rate-limited results`,+ {+ providerId,+ testedCount: Object.keys(results).length,+ totalCount: modelIds.length,+ }+ );+ break;+ }+ }++ log.info(+ "MODEL_TEST_ALL",+ `Batch test complete: ${Object.keys(results).length}/${modelIds.length} model(s)`,+ {+ providerId,+ tested: Object.keys(results).length,+ total: modelIds.length,+ stoppedEarly,+ }+ );++ return NextResponse.json({+ results,+ ...(stoppedEarly && stopReason ? { stoppedEarly: true, stopReason } : {}),+ });+}diff --git a/src/app/api/models/test/route.ts b/src/app/api/models/test/route.tsindex 6bce4e48bd..376b050610 100644--- a/src/app/api/models/test/route.ts+++ b/src/app/api/models/test/route.ts@@ -1,118 +1,16 @@-import { randomUUID } from "node:crypto";import { NextResponse } from "next/server";-import { POST as postChatCompletion } from "@/app/api/v1/chat/completions/route";-import { handleValidatedEmbeddingRequestBody } from "@/app/api/v1/embeddings/route";-import { POST as postRerank } from "@/app/api/v1/rerank/route";-import { buildComboTestRequestBody, extractComboTestResponseText } from "@/lib/combos/testHealth";-import { requireManagementAuth } from "@/lib/api/requireManagementAuth";-import { getCustomModels } from "@/lib/localDb";-import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error";import { z } from "zod";+import { requireManagementAuth } from "@/lib/api/requireManagementAuth";+import { runSingleModelTest } from "@/lib/api/modelTestRunner";+import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error.ts";const testModelSchema = z.object({providerId: z.string().min(1),modelId: z.string().min(1),+ connectionId: z.string().min(1).optional(),});-const MODEL_TEST_TIMEOUT_MS = 20_000;-const INTERNAL_ORIGIN = "http://omniroute.internal";--function asRecord(value: unknown): Record<string, unknown> {- return value && typeof value === "object" && !Array.isArray(value)- ? (value as Record<string, unknown>)- : {};-}--function getErrorMessage(error: unknown): string {- return sanitizeErrorMessage(error) || "Unknown error";-}--function getErrorName(error: unknown): string {- return error instanceof Error ? error.name : "";-}--function extractProviderErrorMessage(body: unknown, fallback: string) {- const record = asRecord(body);- const error = record.error;- if (typeof error === "string" && error.trim()) return error;-- const errorRecord = asRecord(error);- const message = errorRecord.message;- return typeof message === "string" && message.trim() ? message : fallback;-}--async function runWithTimeout<T>(operation: (signal: AbortSignal) => Promise<T>): Promise<T> {- const controller = new AbortController();- const timeoutPromise = new Promise<never>((_, reject) => {- const timeoutError = new Error("Timeout (20s)");- timeoutError.name = "AbortError";- const timeout = setTimeout(() => {- controller.abort();- reject(timeoutError);- }, MODEL_TEST_TIMEOUT_MS);- controller.signal.addEventListener("abort", () => clearTimeout(timeout), { once: true });- });-- try {- return await Promise.race([operation(controller.signal), timeoutPromise]);- } finally {- controller.abort();- }-}--function buildInternalChatRequest(testBody: Record<string, unknown>, signal: AbortSignal) {- return new Request(`${INTERNAL_ORIGIN}/v1/chat/completions`, {- method: "POST",- headers: {- "Content-Type": "application/json",- // Reuse the existing strict-mode internal bypass for live health checks.- "X-Internal-Test": "combo-health-check",- "X-OmniRoute-No-Cache": "true",- "X-Request-Id": `model-test-${randomUUID()}`,- },- body: JSON.stringify(testBody),- signal,- });-}--function buildInternalRerankRequest(testBody: Record<string, unknown>, signal: AbortSignal) {- return new Request(`${INTERNAL_ORIGIN}/v1/rerank`, {- method: "POST",- headers: {- "Content-Type": "application/json",- "X-Internal-Test": "combo-health-check",- "X-OmniRoute-No-Cache": "true",- "X-Request-Id": `model-test-${randomUUID()}`,- },- body: JSON.stringify(testBody),- signal,- });-}--function stripFirstSegment(modelId: string): string | null {- const slashIdx = modelId.indexOf("/");- return slashIdx > 0 ? modelId.slice(slashIdx + 1) : null;-}--async function findCustomModelMetadata(providerId: string, modelId: string) {- try {- const customModels = await getCustomModels(providerId);- if (!Array.isArray(customModels)) return null;-- const candidates = new Set([modelId]);- const stripped = stripFirstSegment(modelId);- if (stripped) candidates.add(stripped);- if (modelId.startsWith(`${providerId}/`)) candidates.add(modelId.slice(providerId.length + 1));-- return (- customModels.find(- (model: any) => typeof model?.id === "string" && candidates.has(model.id)- ) || null- );- } catch {- return null;- }-}+const SINGLE_TEST_TIMEOUT_MS = 20_000;export async function POST(request: Request) {const authError = await requireManagementAuth(request);@@ -138,115 +36,38 @@ export async function POST(request: Request) {if (!validation.success) {return NextResponse.json({ error: validation.error.format() }, { status: 400 });}- const { providerId, modelId } = validation.data;-- // Construct target format (providerId/modelId)- // Some models (like free alias models) might not need the prefix if it's an alias.- // However, the wildcard router expects provider/model.- let fullModelStr = modelId;- if (!fullModelStr.includes("/")) {- fullModelStr = `${providerId}/${modelId}`;+ const { providerId, modelId, connectionId } = validation.data;++ const result = await runSingleModelTest({+ providerId,+ modelId,+ ...(connectionId ? { connectionId } : {}),+ timeoutMs: SINGLE_TEST_TIMEOUT_MS,+ });++ if (result.status === "ok") {+ return NextResponse.json({+ status: "ok",+ latencyMs: result.latencyMs,+ responseText: result.responseText,+ });}- const startTime = Date.now();- const customModel = await findCustomModelMetadata(providerId, fullModelStr);- const supportedEndpoints = Array.isArray(customModel?.supportedEndpoints)- ? customModel.supportedEndpoints- : [];- const apiFormat = typeof customModel?.apiFormat === "string" ? customModel.apiFormat : "";- const lowerModel = fullModelStr.toLowerCase();- const isRerank =- apiFormat === "rerank" ||- supportedEndpoints.includes("rerank") ||- lowerModel.includes("rerank");- const isEmbedding =- !isRerank &&- (apiFormat === "embeddings" ||- supportedEndpoints.includes("embeddings") ||- lowerModel.includes("embedding") ||- lowerModel.includes("bge-") ||- lowerModel.includes("text-embed") ||- lowerModel.includes("jina-clip") ||- lowerModel.includes("colbert"));-- const testBody = isRerank- ? {- model: fullModelStr,- query: "What is OmniRoute?",- documents: [- "OmniRoute routes AI requests across configured providers.",- "This document is unrelated to the test query.",- ],- top_n: 1,- return_documents: false,- }- : buildComboTestRequestBody(fullModelStr, isEmbedding);-- const res = await runWithTimeout((signal) =>- isEmbedding- ? handleValidatedEmbeddingRequestBody(- testBody as Record<string, unknown> & { model: string }- )- : isRerank- ? postRerank(buildInternalRerankRequest(testBody, signal))- : postChatCompletion(buildInternalChatRequest(testBody, signal))- );-- const latencyMs = Date.now() - startTime;+ const body: Record<string, unknown> = {+ status: "error",+ latencyMs: result.latencyMs,+ error: result.error || "Unknown error",+ };+ if (result.statusCode !== undefined) body.statusCode = result.statusCode;+ if (result.rateLimited) body.rateLimited = true;+ if (result.retryAfter !== undefined) body.retryAfter = result.retryAfter;- if (res.ok) {- let responseBody = null;- try {- responseBody = await res.json();- } catch {- responseBody = null;- }-- const responseText = extractComboTestResponseText(responseBody);- if (isRerank) {- return NextResponse.json({- status: "ok",- latencyMs,- responseText: "[Rerank completed successfully]",- });- }- if (!responseText && !isEmbedding) {- return NextResponse.json(- {- status: "error",- statusCode: res.status,- error: "Provider returned HTTP 200 but no text content.",- latencyMs,- },- { status: 400 }- );- }-- return NextResponse.json({ status: "ok", latencyMs, responseText });- }-- let errorMsg = "";- try {- const errBody = await res.json();- errorMsg = extractProviderErrorMessage(errBody, res.statusText);- } catch {- errorMsg = res.statusText;- }-- return NextResponse.json(- {- status: "error",- statusCode: res.status,- error: errorMsg,- latencyMs,- },- { status: res.status }- );+ return NextResponse.json(body, { status: result.httpStatus });} catch (error: unknown) {return NextResponse.json({status: "error",- error: getErrorName(error) === "AbortError" ? "Timeout (20s)" : getErrorMessage(error),+ error: sanitizeErrorMessage(error) || "Unknown error",},{ status: 500 });diff --git a/src/app/api/providers/[id]/login/route.ts b/src/app/api/providers/[id]/login/route.tsnew file mode 100644index 0000000000..ccc0719622--- /dev/null+++ b/src/app/api/providers/[id]/login/route.ts@@ -0,0 +1,75 @@+/**+ * POST /api/providers/[id]/login+ *+ * Web-cookie provider login endpoint. Launches a Playwright browser,+ * navigates to the provider's login page, polls for session tokens,+ * and persists extracted credentials to the provider connection.+ */++import { NextRequest, NextResponse } from "next/server";+import { getProviderConnectionById, updateProviderConnection } from "@/lib/localDb";+import { requireManagementAuth } from "@/lib/api/requireManagementAuth";+import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error.ts";++// ─── POST: Start login flow ────────────────────────────────────────────────++export async function POST(+ req: NextRequest,+ { params }: { params: Promise<{ id: string }> }+): Promise<NextResponse> {+ const auth = await requireManagementAuth(req);+ if (auth) return auth;++ const { id } = await params;+ const provider = await getProviderConnectionById(id);+ if (!provider) {+ return NextResponse.json({ success: false, error: "Provider not found" }, { status: 404 });+ }++ const body = await req.json().catch(() => ({}));+ const timeout = typeof body.timeout === "number" ? body.timeout : undefined;++ try {+ // Dynamic import — InAppLoginService depends on Playwright (heavy)+ const { inAppLoginService } = await import(+ "@omniroute/open-sse/services/inAppLoginService.ts"+ );++ const result = await inAppLoginService.startLogin(id, { timeout });++ // Persist credentials if extraction succeeded+ if (result.success && result.credentials) {+ try {+ const credentialsStr = JSON.stringify(result.credentials);+ await updateProviderConnection(id, {+ api_key: credentialsStr,+ provider_specific_data: result.credentials,+ });++ return NextResponse.json({+ success: true,+ credentials: result.credentials,+ persisted: true,+ });+ } catch (err) {+ // Hard Rule #12: never put raw err.message/stack in a response body.+ const msg = sanitizeErrorMessage(err instanceof Error ? err.message : err);+ return NextResponse.json(+ { success: false, error: `Extracted but failed to persist: ${msg}` },+ { status: 500 }+ );+ }+ }++ return NextResponse.json(result, {+ status: result.success ? 200 : 400,+ });+ } catch (err) {+ // Hard Rule #12: never put raw err.message/stack in a response body.+ const msg = sanitizeErrorMessage(err instanceof Error ? err.message : err);+ return NextResponse.json(+ { success: false, error: `Login endpoint error: ${msg}` },+ { status: 500 }+ );+ }+}diff --git a/src/app/api/providers/[id]/route.ts b/src/app/api/providers/[id]/route.tsindex a48fea4100..c92a7a2c67 100644--- a/src/app/api/providers/[id]/route.ts+++ b/src/app/api/providers/[id]/route.ts@@ -24,6 +24,7 @@ import {} from "@/lib/providers/claudeExtraUsage";import { requireManagementAuth } from "@/lib/api/requireManagementAuth";import { isApiKeyRevealEnabled, maskStoredApiKey } from "@/lib/apiKeyExposure";+import { refreshConnectionRateLimits, enableRateLimitProtection } from "@/../open-sse/services/rateLimitManager";function normalizeCodexLimitPolicy(incoming: unknown,@@ -136,6 +137,7 @@ export async function PUT(request: Request, { params }: { params: Promise<{ id:perKeyProxyEnabled,projectId,providerSpecificData: incomingPsd,+ rateLimitOverrides,} = body;const existing = (await getProviderConnectionById(id)) as Record<string, any> | null;@@ -186,6 +188,7 @@ export async function PUT(request: Request, { params }: { params: Promise<{ id:}}if (projectId !== undefined) updateData.projectId = projectId;+ if (rateLimitOverrides !== undefined) updateData.rateLimitOverrides = rateLimitOverrides;if (proxyEnabled !== undefined) updateData.proxyEnabled = proxyEnabled;if (perKeyProxyEnabled !== undefined) updateData.perKeyProxyEnabled = perKeyProxyEnabled;@@ -282,6 +285,14 @@ export async function PUT(request: Request, { params }: { params: Promise<{ id:const updated = await updateProviderConnection(id, updateData);+ // If rateLimitOverrides was included in the request, refresh the in-memory+ // rate limiter state so the change takes effect without a server restart.+ // Also ensure rate limit protection is active so the limiter is enforced.+ if (rateLimitOverrides !== undefined) {+ refreshConnectionRateLimits(id, updated?.rateLimitOverrides ?? null);+ enableRateLimitProtection(id);+ }+// Hide sensitive fieldsconst result: Record<string, any> = { ...updated };delete result.apiKey;diff --git a/src/app/api/providers/route.ts b/src/app/api/providers/route.tsindex c13b472823..877b3dbde3 100644--- a/src/app/api/providers/route.ts+++ b/src/app/api/providers/route.ts@@ -32,6 +32,7 @@ import {import { requireManagementAuth } from "@/lib/api/requireManagementAuth";import { isManagedProviderConnectionId } from "@/lib/providers/catalog";import { isApiKeyRevealEnabled, maskStoredApiKey } from "@/lib/apiKeyExposure";+import { buildModelSyncInternalHeaders } from "@/shared/services/modelSyncScheduler";// GET /api/providers - List all connectionsexport async function GET(request: Request) {@@ -164,6 +165,48 @@ export async function POST(request: Request) {testStatus: testStatus || "unknown",});+ // Auto-trigger model discovery for the newly created connection.+ // Fire-and-forget: model sync can take seconds and should NOT block the+ // POST response. If it fails, we log and move on — the connection itself+ // is already persisted and the user can manually trigger a sync later.+ // We use a self-fetch against our own /sync-models route, forwarding the+ // incoming cookies (preserves management auth) plus the internal sync+ // auth header (defense in depth) and an X-Internal-Auto-Sync marker for+ // log correlation.+ try {+ const internalOrigin = new URL(request.url).origin;+ const cookieHeader = request.headers.get("cookie") || "";+ const syncHeaders: Record<string, string> = {+ "Content-Type": "application/json",+ "X-Internal-Auto-Sync": "true",+ ...(cookieHeader ? { cookie: cookieHeader } : {}),+ ...buildModelSyncInternalHeaders(),+ };+ const syncUrl = `${internalOrigin}/api/providers/${encodeURIComponent(newConnection.id)}/sync-models?mode=import`;+ // Intentionally not awaited: this is async/non-blocking work.+ void fetch(syncUrl, { method: "POST", headers: syncHeaders })+ .then((syncRes) => {+ if (!syncRes.ok) {+ console.log(+ `[providers] Auto-sync failed for ${newConnection.id}: ${syncRes.status}`+ );+ }+ })+ .catch((err) => {+ console.log(+ `[providers] Auto-sync error for ${newConnection.id}:`,+ err?.message || err+ );+ });+ } catch (syncSetupError) {+ // Defensive: if URL parsing or header construction itself throws, do+ // not let it break the (already successful) POST response.+ console.log(+ `[providers] Auto-sync setup failed for ${newConnection.id}:`,+ syncSetupError?.message || syncSetupError+ );+ }+// Note: Gemini model sync is now triggered client-side with progress dialog// Hide sensitive fieldsdiff --git a/src/app/api/v1/models/catalog.ts b/src/app/api/v1/models/catalog.tsindex f5baf36690..9e1d36ca16 100644--- a/src/app/api/v1/models/catalog.ts+++ b/src/app/api/v1/models/catalog.ts@@ -33,6 +33,7 @@ import { getModelSpec } from "@/shared/constants/modelSpecs";import { isAuthRequired, isDashboardSessionAuthenticated } from "@/shared/utils/apiAuth";import { parseModel } from "@omniroute/open-sse/services/model";import { getTokenLimit } from "@omniroute/open-sse/services/contextManager";+import { extractApiKey } from "@/sse/services/auth";import type { ComboModelStep } from "@/lib/combos/steps";interface CustomModelEntry {@@ -99,8 +100,9 @@ function intersectStringArrays(arrays: string[][]): string[] {}function minKnownNumber(values: Array<number | undefined>): number | undefined {- if (values.length === 0 || !values.every(isPositiveFiniteNumber)) return undefined;- return Math.min(...values);+ const knownValues = values.filter(isPositiveFiniteNumber);+ if (knownValues.length === 0) return undefined;+ return Math.min(...knownValues);}const VISION_MODEL_KEYWORDS = [@@ -188,13 +190,7 @@ function getOpenRouterDisplayName(model: {: name;}-function extractBearer(headers: Headers): string | null {- const authHeader = headers.get("authorization") || headers.get("Authorization");- if (!authHeader?.trim().toLowerCase().startsWith("bearer ")) return null;- return authHeader.trim().slice(7).trim() || null;-}--async function validateCatalogBearer(apiKey: string): Promise<boolean> {+async function validateCatalogApiKey(apiKey: string): Promise<boolean> {const { validateApiKey } = await import("@/lib/db/apiKeys");return validateApiKey(apiKey);}@@ -206,9 +202,9 @@ async function getModelCatalogAuthRejection(): Promise<Response | null> {if (settings.requireAuthForModels !== true || !(await isAuthRequired(request))) return null;- const bearer = extractBearer(request.headers);- if (bearer) {- if (await validateCatalogBearer(bearer)) return null;+ const apiKey = extractApiKey(request);+ if (apiKey) {+ if (await validateCatalogApiKey(apiKey)) return null;return Response.json({error: {@@ -569,7 +565,10 @@ export async function getUnifiedModelsResponse(};};- const buildComboCatalogMetadata = (combo: Record<string, any>, allCombos: any[]) => {+ const buildComboCatalogMetadata = (+ combo: Parameters<typeof resolveNestedComboTargets>[0],+ allCombos: Parameters<typeof resolveNestedComboTargets>[1]+ ) => {const explicitContextLength = isPositiveFiniteNumber(combo.context_length)? combo.context_length: undefined;@@ -579,9 +578,11 @@ export async function getUnifiedModelsResponse(if (targets.length === 0) return baseMetadata;const targetMetadata = targets.map((target) => getComboTargetCatalogMetadata(target));- if (targetMetadata.some((metadata) => metadata === null)) return baseMetadata;- const knownMetadata = targetMetadata as ComboTargetCatalogMetadata[];+ const knownMetadata = targetMetadata.filter(+ (metadata): metadata is ComboTargetCatalogMetadata => metadata !== null+ );+ if (knownMetadata.length === 0) return baseMetadata;const contextLength =explicitContextLength ??minKnownNumber(knownMetadata.map((metadata) => metadata.contextLength));@@ -640,6 +641,21 @@ export async function getUnifiedModelsResponse(for (const combo of combos) {if (combo.isActive === false || combo.isHidden === true) continue;if (typeof combo.name !== "string" || combo.name.length === 0) continue;++ // Skip combos whose any underlying target model is hidden+ const comboTargets = resolveNestedComboTargets(+ combo as Parameters<typeof resolveNestedComboTargets>[0],+ combos as Parameters<typeof resolveNestedComboTargets>[1]+ ) as ComboCatalogTarget[];+ if (+ comboTargets.some((target) => {+ const resolved = getComboTargetModelId(target);+ return resolved ? getModelIsHidden(resolved.providerId, resolved.modelId) : false;+ })+ ) {+ continue;+ }+const comboMetadata = buildComboCatalogMetadata(combo, combos);models.push({@@ -974,6 +990,7 @@ export async function getUnifiedModelsResponse(if (!isProviderActive(embModel.provider)) continue;const rawModelId = embModel.id.split("/").pop() || embModel.id;if (!providerSupportsModel(embModel.provider, rawModelId)) continue;+ if (getModelIsHidden(embModel.provider, rawModelId)) continue;if (hasEquivalentSpecialtyModel(embModel.provider, rawModelId, "embedding", embModel.id)) {continue;}@@ -993,6 +1010,7 @@ export async function getUnifiedModelsResponse(if (!isProviderActive(imgModel.provider)) continue;const rawModelId = imgModel.id.split("/").pop() || imgModel.id;if (!providerSupportsModel(imgModel.provider, rawModelId)) continue;+ if (getModelIsHidden(imgModel.provider, rawModelId)) continue;models.push({id: imgModel.id,object: "model",@@ -1011,6 +1029,7 @@ export async function getUnifiedModelsResponse(if (!isProviderActive(rerankModel.provider)) continue;const rawModelId = rerankModel.id.split("/").pop() || rerankModel.id;if (!providerSupportsModel(rerankModel.provider, rawModelId)) continue;+ if (getModelIsHidden(rerankModel.provider, rawModelId)) continue;if (hasEquivalentSpecialtyModel(rerankModel.provider, rawModelId, "rerank", rerankModel.id)) {continue;}@@ -1029,6 +1048,7 @@ export async function getUnifiedModelsResponse(if (!isProviderActive(audioModel.provider)) continue;const rawModelId = audioModel.id.split("/").pop() || audioModel.id;if (!providerSupportsModel(audioModel.provider, rawModelId)) continue;+ if (getModelIsHidden(audioModel.provider, rawModelId)) continue;models.push({id: audioModel.id,object: "model",@@ -1044,6 +1064,7 @@ export async function getUnifiedModelsResponse(if (!isProviderActive(modModel.provider)) continue;const rawModelId = modModel.id.split("/").pop() || modModel.id;if (!providerSupportsModel(modModel.provider, rawModelId)) continue;+ if (getModelIsHidden(modModel.provider, rawModelId)) continue;models.push({id: modModel.id,object: "model",@@ -1058,6 +1079,7 @@ export async function getUnifiedModelsResponse(if (!isProviderActive(videoModel.provider)) continue;const rawModelId = videoModel.id.split("/").pop() || videoModel.id;if (!providerSupportsModel(videoModel.provider, rawModelId)) continue;+ if (getModelIsHidden(videoModel.provider, rawModelId)) continue;models.push({id: videoModel.id,object: "model",@@ -1072,6 +1094,7 @@ export async function getUnifiedModelsResponse(if (!isProviderActive(musicModel.provider)) continue;const rawModelId = musicModel.id.split("/").pop() || musicModel.id;if (!providerSupportsModel(musicModel.provider, rawModelId)) continue;+ if (getModelIsHidden(musicModel.provider, rawModelId)) continue;models.push({id: musicModel.id,object: "model",@@ -1114,6 +1137,7 @@ export async function getUnifiedModelsResponse(const modelId = typeof model.id === "string" ? model.id : null;if (!modelId) continue;if (model.isHidden === true) continue;+ if (getModelIsHidden(canonicalProviderId, modelId)) continue;if (!hasEligibleConnectionForModel(getConnectionsForProvider(alias, canonicalProviderId, providerId, parentProviderType),@@ -1217,11 +1241,12 @@ export async function getUnifiedModelsResponse(const prefix = providerIdToPrefix[providerId];const alias = prefix || providerIdToAlias[providerId] || providerId;+ const canonicalProviderId = resolveCanonicalProviderId(alias, providerId);for (const model of fallbackModels) {const modelId = typeof model.id === "string" ? model.id : null;if (!modelId) continue;- if (getModelIsHidden(providerId, modelId)) continue;+ if (getModelIsHidden(canonicalProviderId, modelId)) continue;if (!hasEligibleConnectionForModel([conn], modelId)) continue;const aliasId = `${alias}/${modelId}`;@@ -1247,7 +1272,7 @@ export async function getUnifiedModelsResponse(}// Filter by API key permissions if requested- const apiKey = extractBearer(request.headers);+ const apiKey = extractApiKey(request);let finalModels = models;if (apiKey) {const { isModelAllowedForKey, getApiKeyMetadata } = await import("@/lib/db/apiKeys");diff --git a/src/app/api/v1/vscode/[token]/api/chat/route.ts b/src/app/api/v1/vscode/[token]/api/chat/route.tsnew file mode 100644index 0000000000..4295e62c16--- /dev/null+++ b/src/app/api/v1/vscode/[token]/api/chat/route.ts@@ -0,0 +1 @@+export { POST, OPTIONS } from "@/app/api/v1/api/chat/route";\ No newline at end of filediff --git a/src/app/api/v1/vscode/[token]/api/show/route.ts b/src/app/api/v1/vscode/[token]/api/show/route.tsnew file mode 100644index 0000000000..f48a500ea8--- /dev/null+++ b/src/app/api/v1/vscode/[token]/api/show/route.ts@@ -0,0 +1,329 @@+import { getUnifiedModelsResponse } from "@/app/api/v1/models/catalog";+import { getCanonicalModelMetadata } from "@/lib/modelMetadataRegistry";+import { CORS_HEADERS, handleCorsOptions } from "@/shared/utils/cors";+import {+ buildReasoningConfigSchema,+ buildSupportedReasoningEfforts,+ getDefaultReasoningEffort,+ getReasoningEffortValues,+ inferSelectedReasoningEffort,+ type VscodeCatalogModel,+} from "@/app/api/v1/vscode/[token]/reasoningMetadata";+import { getVscodeModelDisplayName } from "@/app/api/v1/vscode/[token]/modelPresentation";+import {+ expandVscodeServiceTierModels,+ parseVscodeServiceTierVariantModelId,+} from "@/app/api/v1/vscode/[token]/serviceTierVariants";+import { getFamilyFirstModelCandidates, getFamilyFirstPublishedModelId } from "@/app/api/v1/vscode/[token]/familyFirstModelIds";+import { withPathTokenApiKey } from "@/app/api/v1/vscode/[token]/tokenizedRequest";++type OpenAiCatalogModel = {+ id?: string;+ name?: string;+ root?: string;+ parent?: string | null;+ owned_by?: string;+ type?: string;+ api_format?: string;+ context_length?: number;+ max_output_tokens?: number;+ capabilities?: Record<string, boolean>;+ input_modalities?: string[];+ output_modalities?: string[];+ supported_endpoints?: string[];+};++function isUsableChatModel(model: OpenAiCatalogModel) {+ if (typeof model.owned_by === "string" && model.owned_by.trim().toLowerCase() === "combo") {+ return false;+ }+ if (typeof model.parent === "string" && model.parent.length > 0) return false;+ if (typeof model.type === "string" && model.type !== "chat") return false;++ const apiFormat = typeof model.api_format === "string" ? model.api_format : "chat-completions";+ if (apiFormat !== "chat-completions") return false;++ if (+ Array.isArray(model.supported_endpoints) &&+ model.supported_endpoints.length > 0 &&+ !model.supported_endpoints.includes("chat")+ ) {+ return false;+ }++ if (+ Array.isArray(model.output_modalities) &&+ model.output_modalities.length > 0 &&+ !model.output_modalities.includes("text")+ ) {+ return false;+ }++ return true;+}++function getCatalogModelId(model: OpenAiCatalogModel) {+ return model.id || model.name || model.root || "unknown";+}++function normalizeArchitectureKey(value: string) {+ const normalized = value.trim().toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");+ return normalized || "model";+}++function normalizeArchitectureSource(value: string) {+ const normalized = value.trim().toLowerCase();+ if (normalized === "cx") return "codex";+ if (normalized === "gh") return "github";+ return value;+}++function getRequestedModelName(payload: unknown): string | null {+ if (!payload || typeof payload !== "object") return null;+ const record = payload as Record<string, unknown>;+ const candidate = record.name ?? record.model;+ return typeof candidate === "string" && candidate.trim().length > 0 ? candidate.trim() : null;+}++function getOllamaModelFamily(model: OpenAiCatalogModel, canonicalFamily?: string | null) {+ const rawModelId = getCatalogModelId(model).trim();+ const { baseModelId } = parseVscodeServiceTierVariantModelId(rawModelId);+ const modelFamily = baseModelId.includes("/") ? baseModelId.split("/").slice(1).join("/") : baseModelId;++ if (modelFamily) {+ return modelFamily;+ }++ if (canonicalFamily && canonicalFamily.trim().length > 0) {+ return canonicalFamily.trim();+ }++ return typeof model.owned_by === "string" && model.owned_by.trim().length > 0+ ? model.owned_by.trim()+ : "omniroute";+}++function matchesRequestedModel(model: OpenAiCatalogModel, requestedName: string): boolean {+ const canonicalMetadata = getCanonicalModelMetadata({+ provider: model.owned_by || null,+ model: model.root || model.id || model.name || null,+ });+ const family = getOllamaModelFamily(model, canonicalMetadata?.metadata.family || null);+ const actualModelId = getCatalogModelId(model);++ return [+ model.id,+ model.name,+ model.root,+ canonicalMetadata?.qualifiedId,+ canonicalMetadata?.model,+ ...getFamilyFirstModelCandidates(actualModelId, family),+ ].some((value) => value === requestedName);+}++function buildCapabilities(model: OpenAiCatalogModel): string[] {+ const capabilities = ["completion"];+ if (model.capabilities?.vision) capabilities.push("vision");+ if (model.capabilities?.tool_calling) capabilities.push("tools");+ if (model.capabilities?.reasoning || model.capabilities?.thinking) capabilities.push("thinking");+ return capabilities;+}++function buildShowPayload(model: OpenAiCatalogModel, responseModelId?: string) {+ const actualModelId = getCatalogModelId(model);+ const displayName = getVscodeModelDisplayName(model);+ const canonicalMetadata = getCanonicalModelMetadata({+ provider: model.owned_by || null,+ model: model.root || model.id || model.name || null,+ });+ const family = getOllamaModelFamily(model, canonicalMetadata?.metadata.family || null);+ const modelId = responseModelId || getFamilyFirstPublishedModelId(actualModelId, family);+ const architectureSource =+ normalizeArchitectureSource(+ canonicalMetadata?.providerAlias || canonicalMetadata?.provider || model.owned_by || family || "model"+ );+ const architecture = normalizeArchitectureKey(+ architectureSource+ );+ const reasoningEffortValues = getReasoningEffortValues(model as VscodeCatalogModel);+ const selectedReasoningEffort = reasoningEffortValues+ ? inferSelectedReasoningEffort(model as VscodeCatalogModel, reasoningEffortValues) || "none"+ : undefined;+ const defaultReasoningEffort = reasoningEffortValues+ ? getDefaultReasoningEffort(model as VscodeCatalogModel, reasoningEffortValues)+ : undefined;+ const supportedReasoningEfforts =+ reasoningEffortValues && reasoningEffortValues.length > 0+ ? buildSupportedReasoningEfforts(reasoningEffortValues)+ : undefined;+ const configSchema =+ reasoningEffortValues && defaultReasoningEffort+ ? buildReasoningConfigSchema(reasoningEffortValues, defaultReasoningEffort)+ : undefined;+ let modelCapabilities = model.capabilities ? { ...model.capabilities } : undefined;++ if (reasoningEffortValues) {+ modelCapabilities = modelCapabilities || {};+ Object.assign(modelCapabilities, {+ reasoning: true,+ thinking: true,+ supports_reasoning_effort: reasoningEffortValues,+ supportsReasoningEffort: reasoningEffortValues,+ supportedReasoningEfforts,+ defaultReasoningEffort,+ selected_reasoning_effort: selectedReasoningEffort,+ selectedReasoningEffort: selectedReasoningEffort,+ ...(configSchema ? { configurationSchema: configSchema } : {}),+ ...(configSchema ? { configSchema } : {}),+ });+ }++ return {+ model: modelId,+ remote_model: displayName,+ ...(reasoningEffortValues+ ? {+ supports_reasoning_effort: reasoningEffortValues,+ supportsReasoningEffort: reasoningEffortValues,+ supportedReasoningEfforts,+ defaultReasoningEffort,+ selected_reasoning_effort: selectedReasoningEffort,+ selectedReasoningEffort: selectedReasoningEffort,+ ...(configSchema ? { configurationSchema: configSchema } : {}),+ ...(configSchema ? { configSchema } : {}),+ }+ : {}),+ license: "proprietary",+ modelfile: `FROM ${modelId}`,+ parameters: "",+ template: "",+ details: {+ parent_model: model.root || actualModelId || "",+ format: "openai",+ family,+ families: [family],+ parameter_size: "unknown",+ quantization_level: "dynamic",+ ...(reasoningEffortValues+ ? {+ supports_reasoning_effort: reasoningEffortValues,+ supportsReasoningEffort: reasoningEffortValues,+ supportedReasoningEfforts,+ defaultReasoningEffort,+ selected_reasoning_effort: selectedReasoningEffort,+ selectedReasoningEffort: selectedReasoningEffort,+ ...(configSchema ? { configurationSchema: configSchema } : {}),+ ...(configSchema ? { configSchema } : {}),+ }+ : {}),+ },+ model_info: {+ "general.architecture": architecture,+ "general.basename": displayName,+ ...(typeof model.context_length === "number" ? { context_length: model.context_length } : {}),+ ...(typeof model.context_length === "number"+ ? { [`${architecture}.context_length`]: model.context_length }+ : {}),+ ...(typeof model.max_output_tokens === "number"+ ? { max_output_tokens: model.max_output_tokens }+ : {}),+ ...(Array.isArray(model.input_modalities)+ ? { input_modalities: model.input_modalities }+ : {}),+ ...(Array.isArray(model.output_modalities)+ ? { output_modalities: model.output_modalities }+ : {}),+ ...(Array.isArray(model.supported_endpoints)+ ? { supported_endpoints: model.supported_endpoints }+ : {}),+ ...(modelCapabilities ? { capabilities: modelCapabilities } : {}),+ ...(reasoningEffortValues+ ? {+ supports_reasoning_effort: reasoningEffortValues,+ supportsReasoningEffort: reasoningEffortValues,+ supportedReasoningEfforts,+ defaultReasoningEffort,+ selected_reasoning_effort: selectedReasoningEffort,+ selectedReasoningEffort: selectedReasoningEffort,+ ...(configSchema ? { configurationSchema: configSchema } : {}),+ ...(configSchema ? { configSchema } : {}),+ }+ : {}),+ },+ capabilities: buildCapabilities(model),+ };+}++export async function OPTIONS() {+ return handleCorsOptions();+}++export async function POST(+ request: Request,+ { params }: { params?: Promise<{ token: string }> | { token: string } } = {}+) {+ const resolvedParams = params ? await params : undefined;+ const authorizedRequest = withPathTokenApiKey(request, resolvedParams?.token);+ const payload = await request+ .clone()+ .json()+ .catch(() => null);+ const requestedName = getRequestedModelName(payload);++ if (!requestedName) {+ return Response.json(+ {+ error: "Model name is required",+ },+ {+ status: 400,+ headers: {+ ...CORS_HEADERS,+ },+ }+ );+ }++ const catalogResponse = await getUnifiedModelsResponse(authorizedRequest, {+ "Content-Type": "application/json",+ ...CORS_HEADERS,+ });+ const catalogBody = (await catalogResponse.json()) as { data?: OpenAiCatalogModel[] };++ if (!catalogResponse.ok) {+ return Response.json(catalogBody, {+ status: catalogResponse.status,+ headers: {+ ...CORS_HEADERS,+ },+ });+ }++ const expandedModels = Array.isArray(catalogBody.data)+ ? expandVscodeServiceTierModels(catalogBody.data.filter(isUsableChatModel))+ : [];++ const model = Array.isArray(expandedModels)+ ? expandedModels.find((entry) => matchesRequestedModel(entry, requestedName))+ : undefined;++ if (!model) {+ return Response.json(+ {+ error: `Model not found: ${requestedName}`,+ },+ {+ status: 404,+ headers: {+ ...CORS_HEADERS,+ },+ }+ );+ }++ return Response.json(buildShowPayload(model, requestedName), {+ headers: {+ ...CORS_HEADERS,+ },+ });+}diff --git a/src/app/api/v1/vscode/[token]/api/tags/route.ts b/src/app/api/v1/vscode/[token]/api/tags/route.tsnew file mode 100644index 0000000000..81273c909b--- /dev/null+++ b/src/app/api/v1/vscode/[token]/api/tags/route.ts@@ -0,0 +1,257 @@+import { getUnifiedModelsResponse } from "@/app/api/v1/models/catalog";+import { getProviderConnections } from "@/lib/db/providers";+import { getCanonicalModelMetadata } from "@/lib/modelMetadataRegistry";+import { CORS_HEADERS, handleCorsOptions } from "@/shared/utils/cors";+import {+ buildReasoningConfigSchema,+ buildSupportedReasoningEfforts,+ getDefaultReasoningEffort,+ getReasoningVariantBaseModelId,+ getReasoningEffortValues,+ inferSelectedReasoningEffort,+ type VscodeCatalogModel,+} from "@/app/api/v1/vscode/[token]/reasoningMetadata";+import { getVscodeModelGroupingKey } from "@/app/api/v1/vscode/[token]/modelPresentation";+import {+ expandVscodeServiceTierModels,+ getVscodeServiceTierVariantModelId,+ parseVscodeServiceTierVariantModelId,+} from "@/app/api/v1/vscode/[token]/serviceTierVariants";+import { getFamilyFirstPublishedModelId } from "@/app/api/v1/vscode/[token]/familyFirstModelIds";+import { withPathTokenApiKey } from "@/app/api/v1/vscode/[token]/tokenizedRequest";++type OpenAiCatalogModel = {+ id?: string;+ name?: string;+ root?: string;+ parent?: string | null;+ owned_by?: string;+ type?: string;+ api_format?: string;+ context_length?: number;+ output_modalities?: string[];+ supported_endpoints?: string[];+};++function getModelName(model: OpenAiCatalogModel) {+ return model.id || model.name || model.root || "";+}++function isCodexOwnedModel(model: OpenAiCatalogModel) {+ const owner = typeof model.owned_by === "string" ? model.owned_by.trim().toLowerCase() : "";+ const modelName = getModelName(model).toLowerCase();++ return owner === "codex" || modelName.startsWith("cx/") || modelName.startsWith("codex/");+}++async function selectPreferredModels(models: OpenAiCatalogModel[]) {+ const activeConnections = (await getProviderConnections({ isActive: true })) as Array<{+ provider?: string;+ }>;+ const activeProviders = new Set(+ activeConnections+ .map((connection) =>+ typeof connection.provider === "string" ? connection.provider.trim().toLowerCase() : ""+ )+ .filter(Boolean)+ );++ const preferCodexOnly =+ activeProviders.size > 0 && Array.from(activeProviders).every((provider) => provider === "codex");+ if (!preferCodexOnly) return models;++ const codexModels = models.filter(isCodexOwnedModel);+ return codexModels.length > 0 ? codexModels : models;+}++function isUsableChatModel(model: OpenAiCatalogModel) {+ if (typeof model.owned_by === "string" && model.owned_by.trim().toLowerCase() === "combo") {+ return false;+ }+ if (typeof model.parent === "string" && model.parent.length > 0) return false;+ if (typeof model.type === "string" && model.type !== "chat") return false;++ const apiFormat = typeof model.api_format === "string" ? model.api_format : "chat-completions";+ if (apiFormat !== "chat-completions") return false;++ if (+ Array.isArray(model.supported_endpoints) &&+ model.supported_endpoints.length > 0 &&+ !model.supported_endpoints.includes("chat")+ ) {+ return false;+ }++ if (+ Array.isArray(model.output_modalities) &&+ model.output_modalities.length > 0 &&+ !model.output_modalities.includes("text")+ ) {+ return false;+ }++ return true;+}++function getOllamaModelFamily(model: OpenAiCatalogModel, canonicalFamily?: string | null) {+ const rawModelId = getModelName(model).trim();+ const tierParsedModel = parseVscodeServiceTierVariantModelId(rawModelId);+ const baseModelId = getReasoningVariantBaseModelId(tierParsedModel.baseModelId);+ const modelFamily = baseModelId.includes("/") ? baseModelId.split("/").slice(1).join("/") : baseModelId;++ if (modelFamily) {+ return modelFamily;+ }++ if (canonicalFamily && canonicalFamily.trim().length > 0) {+ return canonicalFamily.trim();+ }++ return typeof model.owned_by === "string" && model.owned_by.trim().length > 0+ ? model.owned_by.trim()+ : "omniroute";+}++function toOllamaTagModel(model: OpenAiCatalogModel) {+ const actualModelId = model.id || model.root || "unknown";+ const canonicalMetadata = getCanonicalModelMetadata({+ provider: model.owned_by || null,+ model: model.root || model.id || model.name || null,+ });+ const family = getOllamaModelFamily(model, canonicalMetadata?.metadata.family || null);+ const modelId = getFamilyFirstPublishedModelId(actualModelId, family);+ const contextLength = typeof model.context_length === "number" ? model.context_length : 0;+ const reasoningEffortValues = getReasoningEffortValues(model as VscodeCatalogModel);+ const selectedReasoningEffort = reasoningEffortValues+ ? inferSelectedReasoningEffort(model as VscodeCatalogModel, reasoningEffortValues) || "none"+ : undefined;+ const defaultReasoningEffort = reasoningEffortValues+ ? getDefaultReasoningEffort(model as VscodeCatalogModel, reasoningEffortValues)+ : undefined;+ const supportedReasoningEfforts =+ reasoningEffortValues && reasoningEffortValues.length > 0+ ? buildSupportedReasoningEfforts(reasoningEffortValues)+ : undefined;+ const configSchema =+ reasoningEffortValues && defaultReasoningEffort+ ? buildReasoningConfigSchema(reasoningEffortValues, defaultReasoningEffort)+ : undefined;++ return {+ name: modelId,+ model: modelId,+ modified_at: "2026-01-01T00:00:00Z",+ size: 0,+ digest: `omniroute:${modelId}`,+ ...(reasoningEffortValues+ ? {+ supports_reasoning_effort: reasoningEffortValues,+ supportsReasoningEffort: reasoningEffortValues,+ supportedReasoningEfforts,+ defaultReasoningEffort,+ selected_reasoning_effort: selectedReasoningEffort,+ selectedReasoningEffort: selectedReasoningEffort,+ ...(configSchema ? { configurationSchema: configSchema } : {}),+ ...(configSchema ? { configSchema } : {}),+ }+ : {}),+ details: {+ format: "openai",+ family,+ parameter_size: contextLength > 0 ? `${contextLength} ctx` : "unknown",+ quantization_level: "dynamic",+ ...(reasoningEffortValues+ ? {+ supports_reasoning_effort: reasoningEffortValues,+ supportsReasoningEffort: reasoningEffortValues,+ supportedReasoningEfforts,+ defaultReasoningEffort,+ selected_reasoning_effort: selectedReasoningEffort,+ selectedReasoningEffort: selectedReasoningEffort,+ ...(configSchema ? { configurationSchema: configSchema } : {}),+ ...(configSchema ? { configSchema } : {}),+ }+ : {}),+ },+ };+}++function filterCanonicalTagModels(models: OpenAiCatalogModel[]) {+ const allModelIds = new Set(models.map((model) => (model.id || model.root || model.name || "").trim()).filter(Boolean));+ const groupedModels = new Map<string, OpenAiCatalogModel>();+ const orderedGroupKeys: string[] = [];++ for (const model of models) {+ const modelId = (model.id || model.root || model.name || "").trim();+ if (!modelId) continue;++ const tierParsedModel = parseVscodeServiceTierVariantModelId(modelId);+ const baseModelId = getReasoningVariantBaseModelId(tierParsedModel.baseModelId);+ const canonicalModelId = tierParsedModel.serviceTier+ ? getVscodeServiceTierVariantModelId(baseModelId, tierParsedModel.serviceTier)+ : baseModelId;+ if (canonicalModelId !== modelId && allModelIds.has(canonicalModelId)) {+ continue;+ }++ const groupKey = tierParsedModel.serviceTier+ ? canonicalModelId+ : getVscodeModelGroupingKey(model) || canonicalModelId;+ const current = groupedModels.get(groupKey);+ if (!current) {+ groupedModels.set(groupKey, model);+ orderedGroupKeys.push(groupKey);+ continue;+ }++ const currentId = (current.id || current.root || current.name || "").trim();+ if (currentId !== groupKey && modelId === canonicalModelId) {+ groupedModels.set(groupKey, model);+ }+ }++ return orderedGroupKeys.map((groupKey) => groupedModels.get(groupKey)).filter(Boolean) as OpenAiCatalogModel[];+}++export async function OPTIONS() {+ return handleCorsOptions();+}++export async function GET(+ request: Request,+ { params }: { params?: Promise<{ token: string }> | { token: string } } = {}+) {+ const resolvedParams = params ? await params : undefined;+ const authorizedRequest = withPathTokenApiKey(request, resolvedParams?.token);+ const response = await getUnifiedModelsResponse(authorizedRequest, {+ "Content-Type": "application/json",+ ...CORS_HEADERS,+ });+ const body = (await response.json()) as { data?: OpenAiCatalogModel[] };++ if (!response.ok) {+ return Response.json(body, {+ status: response.status,+ headers: {+ ...CORS_HEADERS,+ },+ });+ }++ const usableModels = Array.isArray(body.data) ? body.data.filter(isUsableChatModel) : [];+ const preferredModels = filterCanonicalTagModels(+ expandVscodeServiceTierModels(await selectPreferredModels(usableModels))+ );+ const models = preferredModels.map(toOllamaTagModel);++ return Response.json(+ {+ models,+ },+ {+ headers: {+ ...CORS_HEADERS,+ },+ }+ );+}diff --git a/src/app/api/v1/vscode/[token]/api/version/route.ts b/src/app/api/v1/vscode/[token]/api/version/route.tsnew file mode 100644index 0000000000..89cf0622d1--- /dev/null+++ b/src/app/api/v1/vscode/[token]/api/version/route.ts@@ -0,0 +1,20 @@+import { CORS_HEADERS, handleCorsOptions } from "@/shared/utils/cors";++const OLLAMA_COMPAT_VERSION = "0.6.4";++export async function OPTIONS() {+ return handleCorsOptions();+}++export async function GET() {+ return Response.json(+ {+ version: OLLAMA_COMPAT_VERSION,+ },+ {+ headers: {+ ...CORS_HEADERS,+ },+ }+ );+}\ No newline at end of filediff --git a/src/app/api/v1/vscode/[token]/chat/completions/route.ts b/src/app/api/v1/vscode/[token]/chat/completions/route.tsnew file mode 100644index 0000000000..b243f2fe8b--- /dev/null+++ b/src/app/api/v1/vscode/[token]/chat/completions/route.ts@@ -0,0 +1,10 @@+import { POST as basePost, OPTIONS } from "@/app/api/v1/chat/completions/route";+import { rewriteVscodeServiceTierRequest } from "@/app/api/v1/vscode/[token]/serviceTierVariants";+import { withPathTokenApiKey } from "@/app/api/v1/vscode/[token]/tokenizedRequest";++export { OPTIONS };++export async function POST(request: Request) {+ const authorizedRequest = withPathTokenApiKey(request);+ return basePost(await rewriteVscodeServiceTierRequest(authorizedRequest));+}diff --git a/src/app/api/v1/vscode/[token]/combos/route.ts b/src/app/api/v1/vscode/[token]/combos/route.tsnew file mode 100644index 0000000000..671a662cca--- /dev/null+++ b/src/app/api/v1/vscode/[token]/combos/route.ts@@ -0,0 +1,41 @@+/**+ * VS Code Combos endpoint — re-export base Ollama-compatible routes+ * and intercept GET to return combo metadata.+ *+ * The VS Code extension expects a standard Ollama server at the base URL,+ * so we re-export /api/version, /api/tags, etc. from the [token] parent route.+ */+import { getCombos } from "@/lib/db/combos";+import { projectCombo, type PublicCombo } from "@/app/api/v1/combos/projectCombo";++// Re-export Ollama-compatible endpoints from the parent [token] route+// so VS Code can validate the server version and list models normally+export { OPTIONS } from "@/app/api/v1/vscode/[token]/route";+export async function GET(request: Request) {+ // If client requests /api/version or other Ollama endpoints, delegate to parent+ const url = new URL(request.url);+ if (url.pathname.includes("/api/version") || url.pathname.includes("/api/tags")) {+ const { GET: parentGET } = await import("@/app/api/v1/vscode/[token]/route");+ return parentGET(request);+ }++ // Default: return combos metadata+ try {+ const combos = await getCombos();+ const data = (Array.isArray(combos) ? combos : [])+ .map((combo) => projectCombo(combo as Record<string, unknown>))+ .filter((combo): combo is PublicCombo => combo !== null);++ return new Response(JSON.stringify({ object: "list", data, combos: data }), {+ headers: {+ "Content-Type": "application/json",+ "Cache-Control": "no-store",+ },+ });+ } catch (error) {+ return new Response(JSON.stringify({ error: "Failed to fetch combos" }), {+ status: 500,+ headers: { "Content-Type": "application/json" },+ });+ }+}diff --git a/src/app/api/v1/vscode/[token]/familyFirstModelIds.ts b/src/app/api/v1/vscode/[token]/familyFirstModelIds.tsnew file mode 100644index 0000000000..c5a2484761--- /dev/null+++ b/src/app/api/v1/vscode/[token]/familyFirstModelIds.ts@@ -0,0 +1,85 @@+const FAMILY_FIRST_MODEL_PATTERN = /^((?:gpt-[a-z0-9._-]+|claude[a-z0-9._-]*))(?:__provider_([a-z0-9-]+))(?:__tier_(priority|flex))?$/i;+const TIER_SUFFIX_PATTERN = /(__tier_(?:priority|flex))$/i;++function normalizeFamily(value: string | null | undefined) {+ return typeof value === "string" ? value.trim() : "";+}++function splitActualModelId(modelId: string) {+ const trimmedModelId = modelId.trim();+ const slashIndex = trimmedModelId.indexOf("/");+ if (slashIndex <= 0 || slashIndex === trimmedModelId.length - 1) {+ return null;+ }++ return {+ providerPrefix: trimmedModelId.slice(0, slashIndex),+ providerModelId: trimmedModelId.slice(slashIndex + 1),+ };+}++function extractTierSuffix(modelId: string) {+ const match = modelId.match(TIER_SUFFIX_PATTERN);+ return match?.[1] || "";+}++function stripTierSuffix(modelId: string) {+ return modelId.replace(TIER_SUFFIX_PATTERN, "");+}++function isFamilyFirstEligibleFamily(family: string) {+ const normalized = family.toLowerCase();+ return normalized.startsWith("gpt-") || normalized.startsWith("claude");+}++export function getFamilyFirstPublishedModelId(actualModelId: string, family: string | null | undefined) {+ const normalizedFamily = normalizeFamily(family);+ if (!normalizedFamily || !isFamilyFirstEligibleFamily(normalizedFamily)) {+ return actualModelId;+ }++ const parts = splitActualModelId(actualModelId);+ if (!parts) {+ return actualModelId;+ }++ const tierSuffix = extractTierSuffix(parts.providerModelId);+ const providerModelBase = stripTierSuffix(parts.providerModelId);+ if (providerModelBase !== normalizedFamily) {+ return actualModelId;+ }++ return `${normalizedFamily}__provider_${parts.providerPrefix}${tierSuffix}`;+}++export function resolveFamilyFirstPublishedModelId(modelId: string | null | undefined) {+ const trimmedModelId = typeof modelId === "string" ? modelId.trim() : "";+ if (!trimmedModelId) {+ return trimmedModelId;+ }++ const match = trimmedModelId.match(FAMILY_FIRST_MODEL_PATTERN);+ if (!match) {+ return trimmedModelId;+ }++ const [, family, providerPrefix, serviceTier] = match;+ const tierSuffix = serviceTier ? `__tier_${serviceTier.toLowerCase()}` : "";+ return `${providerPrefix}/${family}${tierSuffix}`;+}++export function getFamilyFirstModelCandidates(actualModelId: string, family: string | null | undefined) {+ const normalizedFamily = normalizeFamily(family);+ const candidates = new Set<string>([actualModelId]);+ const publishedModelId = getFamilyFirstPublishedModelId(actualModelId, normalizedFamily);+ if (publishedModelId !== actualModelId) {+ candidates.add(publishedModelId);+ }++ if (normalizedFamily && isFamilyFirstEligibleFamily(normalizedFamily)) {+ const tierSuffix = extractTierSuffix(actualModelId);+ candidates.add(`${normalizedFamily}${tierSuffix}`);+ }++ return [...candidates];+}\ No newline at end of filediff --git a/src/app/api/v1/vscode/[token]/modelPresentation.ts b/src/app/api/v1/vscode/[token]/modelPresentation.tsnew file mode 100644index 0000000000..47b2658c17--- /dev/null+++ b/src/app/api/v1/vscode/[token]/modelPresentation.ts@@ -0,0 +1,178 @@+import { parseModel } from "@omniroute/open-sse/services/model";+import {+ getCanonicalModelMetadata,+ type CanonicalModelMetadata,+} from "@/lib/modelMetadataRegistry";+import {+ getVscodeServiceTierVariantSuffix,+ parseVscodeServiceTierVariantModelId,+ supportsVscodeServiceTierVariants,+} from "@/app/api/v1/vscode/[token]/serviceTierVariants";+import { getReasoningVariantBaseModelId } from "@/app/api/v1/vscode/[token]/reasoningMetadata";+import { resolveFamilyFirstPublishedModelId } from "@/app/api/v1/vscode/[token]/familyFirstModelIds";+type VscodeCatalogModel = {+ id?: string;+ name?: string;+ root?: string;+ owned_by?: string;+};++const PROVIDER_NAME_OVERRIDES: Record<string, string> = {+ codex: "Codex",+ cx: "Codex",+ github: "GitHub",+ gh: "GitHub",+ "gemini-cli": "Gemini",+ gemini: "Gemini",+};++function tokenize(value: string) {+ return value+ .toLowerCase()+ .split(/[^a-z0-9]+/i)+ .map((part) => part.trim())+ .filter((part) => part.length >= 4);+}++function getProviderPrefix(metadata: CanonicalModelMetadata | null) {+ const providerKey = metadata?.providerAlias || metadata?.provider || "";+ if (providerKey && PROVIDER_NAME_OVERRIDES[providerKey]) {+ return PROVIDER_NAME_OVERRIDES[providerKey];+ }++ const providerLabel = metadata?.providerLabel?.trim() || null;+ if (!providerLabel) {+ return null;+ }+ if (/codex/i.test(providerLabel)) {+ return "Codex";+ }+ if (/github/i.test(providerLabel)) {+ return "GitHub";+ }+ if (/gemini/i.test(providerLabel)) {+ return "Gemini";+ }++ return providerLabel;+}++function normalizeDisplayNameBranding(displayName: string) {+ return displayName+ .replace(/^OpenAI\s+Codex\b/i, "Codex")+ .replace(/^GitHub\s+Copilot\b/i, "GitHub")+ .trim();+}++function stripLeadingProviderPrefix(displayName: string, providerPrefix: string | null) {+ if (!providerPrefix) {+ return displayName;+ }++ const escapedProviderPrefix = providerPrefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+ return displayName.replace(new RegExp(`^${escapedProviderPrefix}\\s+`, "i"), "").trim();+}++function looksLikeTechnicalModelName(value: string) {+ return /\/|__provider_|__tier_|^[a-z0-9-]+\/[a-z0-9._-]+$/i.test(value);+}++function humanizeModelIdentifier(modelId: string) {+ const identifier = (modelId.split("/").pop() || modelId).trim();+ if (!identifier) {+ return identifier;+ }++ return identifier+ .split(/[-_]+/)+ .filter(Boolean)+ .map(part => {+ if (/^gpt$/i.test(part)) return "GPT";+ if (/^[0-9]+(?:\.[0-9]+)*$/.test(part)) return part;+ if (/^[a-z][0-9]$/i.test(part)) return part.toUpperCase();+ return part.charAt(0).toUpperCase() + part.slice(1);+ })+ .join(" ");+}++function resolveFriendlyBaseDisplayName(+ rawModelId: string,+ metadata: CanonicalModelMetadata | null,+ fallbackValue: string+) {+ const normalizedFallback = normalizeDisplayNameBranding(fallbackValue.trim());+ if (normalizedFallback && !looksLikeTechnicalModelName(normalizedFallback)) {+ return normalizedFallback;+ }++ const normalizedModelId = resolveFamilyFirstPublishedModelId(rawModelId);+ const parsedTierModel = parseVscodeServiceTierVariantModelId(normalizedModelId);+ const canonicalBaseModelId = getReasoningVariantBaseModelId(parsedTierModel.baseModelId);+ const parsed = parseModel(canonicalBaseModelId, "");+ const providerModelId =+ parsed.model ||+ (canonicalBaseModelId.includes("/")+ ? canonicalBaseModelId.split("/").slice(1).join("/")+ : canonicalBaseModelId) ||+ fallbackValue;++ return humanizeModelIdentifier(providerModelId);+}++function prefixDisplayName(displayName: string, providerPrefix: string | null) {+ const normalizedProviderPrefix = providerPrefix?.trim() || null;+ const normalizedDisplayName = normalizeDisplayNameBranding(displayName);++ if (!normalizedProviderPrefix) return normalizedDisplayName;++ const providerTokens = tokenize(normalizedProviderPrefix);+ if (providerTokens.length === 0) return normalizedDisplayName;++ const displayNameLower = normalizedDisplayName.toLowerCase();+ if (providerTokens.some((token) => displayNameLower.includes(token))) {+ return normalizedDisplayName;+ }++ return `${normalizedProviderPrefix} ${stripLeadingProviderPrefix(normalizedDisplayName, normalizedProviderPrefix)}`.trim();+}++export function resolveVscodeModelMetadata(model: VscodeCatalogModel) {+ const rawModelId = model.id || model.root || model.name || "";+ const normalizedModelId = resolveFamilyFirstPublishedModelId(rawModelId);+ const parsedTierModel = parseVscodeServiceTierVariantModelId(normalizedModelId);+ const canonicalBaseModelId = getReasoningVariantBaseModelId(parsedTierModel.baseModelId);+ const parsed = parseModel(canonicalBaseModelId, "");+ const provider = parsed.provider || model.owned_by || undefined;+ const providerModel =+ parsed.model ||+ (canonicalBaseModelId.includes("/")+ ? canonicalBaseModelId.split("/").slice(1).join("/")+ : canonicalBaseModelId) ||+ model.root ||+ model.id ||+ model.name ||+ undefined;++ return providerModel && provider+ ? getCanonicalModelMetadata({ provider, model: providerModel })+ : providerModel+ ? getCanonicalModelMetadata({ model: providerModel })+ : null;+}++export function getVscodeModelDisplayName(model: VscodeCatalogModel) {+ const rawModelId = model.id || model.root || model.name || "";+ const { serviceTier } = parseVscodeServiceTierVariantModelId(rawModelId);+ const metadata = resolveVscodeModelMetadata(model);+ const displayName = metadata?.displayName || model.name || model.id || model.root || "unknown";+ const prefixedDisplayName = prefixDisplayName(displayName, getProviderPrefix(metadata));+ const shouldShowTierSuffix = Boolean(serviceTier) || supportsVscodeServiceTierVariants(model);+ return shouldShowTierSuffix+ ? `${prefixedDisplayName} (${getVscodeServiceTierVariantSuffix(serviceTier)})`+ : prefixedDisplayName;+}++export function getVscodeModelGroupingKey(model: VscodeCatalogModel) {+ const metadata = resolveVscodeModelMetadata(model);+ return metadata?.qualifiedId || metadata?.model || model.id || model.name || model.root || "";+}diff --git a/src/app/api/v1/vscode/[token]/models/route.ts b/src/app/api/v1/vscode/[token]/models/route.tsnew file mode 100644index 0000000000..946a8cc866--- /dev/null+++ b/src/app/api/v1/vscode/[token]/models/route.ts@@ -0,0 +1,424 @@+import { getUnifiedModelsResponse } from "@/app/api/v1/models/catalog";+import { getResolvedModelCapabilities } from "@/lib/modelCapabilities";+import { getCanonicalModelMetadata } from "@/lib/modelMetadataRegistry";+import {+ buildReasoningConfigSchema,+ buildSupportedReasoningEfforts,+ getDefaultReasoningEffort,+ getCatalogModelName,+ formatReasoningEffortLabel,+ getReasoningEffortValues,+ getReasoningVariantBaseModelId,+ type VscodeCatalogModel,+ type VscodeModelConfigSchema,+} from "@/app/api/v1/vscode/[token]/reasoningMetadata";+import {+ getVscodeModelDisplayName,+ resolveVscodeModelMetadata,+ getVscodeModelGroupingKey,+} from "@/app/api/v1/vscode/[token]/modelPresentation";+import { withPathTokenApiKey } from "@/app/api/v1/vscode/[token]/tokenizedRequest";+import {+ expandVscodeServiceTierModels,+ getVscodeServiceTierVariantSuffix,+ getVscodeServiceTierVariantModelId,+ parseVscodeServiceTierVariantModelId,+} from "@/app/api/v1/vscode/[token]/serviceTierVariants";+import { getFamilyFirstPublishedModelId } from "@/app/api/v1/vscode/[token]/familyFirstModelIds";++type CatalogModelEntry = {+ id?: string;+ name?: string;+ root?: string;+ owned_by?: string;+ parent?: string | null;+ type?: string;+ api_format?: string;+ context_length?: number;+ max_input_tokens?: number;+ max_output_tokens?: number;+ supported_endpoints?: string[];+ output_modalities?: string[];+ capabilities?: Record<string, boolean>;+};++type VscodeImportModel = CatalogModelEntry & {+ url?: string;+ toolCalling?: boolean;+ vision?: boolean;+ maxInputTokens?: number;+ maxOutputTokens?: number;+ family?: string;+ supportsReasoningEffort?: string[];+ supportedReasoningEfforts?: string[];+ defaultReasoningEffort?: string;+ configurationSchema?: VscodeModelConfigSchema;+ configSchema?: VscodeModelConfigSchema;+};++type VscodeModelsCatalogResponse = {+ status: number;+ headers: Record<string, string>;+ body: { data?: CatalogModelEntry[]; [key: string]: unknown };+};++const VSCODE_CATALOG_CACHE_HEADERS = {+ "Cache-Control": "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0",+ Pragma: "no-cache",+ Expires: "0",+} as const;++type EnrichModelForVscodeOptions = {+ preserveNativeId?: boolean;+};++function isUsableChatModel(model: CatalogModelEntry) {+ if (typeof model.owned_by === "string" && model.owned_by.trim().toLowerCase() === "combo") {+ return false;+ }+ if (typeof model.parent === "string" && model.parent.length > 0) return false;+ if (typeof model.type === "string" && model.type !== "chat") return false;+ if (typeof model.api_format === "string" && model.api_format !== "chat-completions") {+ return false;+ }+ if (+ Array.isArray(model.supported_endpoints) &&+ model.supported_endpoints.length > 0 &&+ !model.supported_endpoints.includes("chat")+ ) {+ return false;+ }+ if (+ Array.isArray(model.output_modalities) &&+ model.output_modalities.length > 0 &&+ !model.output_modalities.includes("text")+ ) {+ return false;+ }++ return true;+}++function getModelImportReasoningEffortValues(model: VscodeCatalogModel, reasoningEffortValues: string[]) {+ const providerId =+ (model.owned_by || "").trim() ||+ (model.id || model.name || model.root || "").split("/")[0] ||+ "";+ if (providerId === "github" || providerId === "gh") {+ return reasoningEffortValues.filter((value) => value !== "xhigh");+ }+ return reasoningEffortValues;+}++function getVscodeImportFamily(model: CatalogModelEntry, canonicalFamily?: string | null) {+ const rawModelId = (model.root || model.id || model.name || "").trim();+ const tierParsedModel = parseVscodeServiceTierVariantModelId(rawModelId);+ const baseModelId = getReasoningVariantBaseModelId(tierParsedModel.baseModelId);+ const modelFamily = baseModelId.includes("/") ? baseModelId.split("/").slice(1).join("/") : baseModelId;++ if (modelFamily) {+ return modelFamily;+ }++ if (canonicalFamily && canonicalFamily.trim().length > 0) {+ return canonicalFamily.trim();+ }++ return typeof model.owned_by === "string" && model.owned_by.trim().length > 0+ ? model.owned_by.trim()+ : undefined;+}++export function getVscodeRawModelDisplayName(model: CatalogModelEntry) {+ const actualModelId = (model.id || model.name || model.root || "").trim();+ const canonicalMetadata = resolveVscodeModelMetadata(model);+ const { baseModelId } = parseVscodeServiceTierVariantModelId(actualModelId);+ const displayBaseModelId = getReasoningVariantBaseModelId(baseModelId);+ const baseDisplayName = getVscodeModelDisplayName({+ ...model,+ id: displayBaseModelId,+ name: displayBaseModelId,+ root: displayBaseModelId,+ }).replace(/\s+\(Default\)$/u, "");+ const providerKey = canonicalMetadata?.providerAlias || canonicalMetadata?.provider || "";+ const providerPrefix = providerKey === "codex" || providerKey === "cx"+ ? "Codex"+ : providerKey === "github" || providerKey === "gh"+ ? "GitHub"+ : canonicalMetadata?.providerLabel || null;+ const prefixedDisplayName = providerPrefix && !baseDisplayName.toLowerCase().includes(providerPrefix.toLowerCase())+ ? `${providerPrefix} ${baseDisplayName}`.trim()+ : baseDisplayName;+ const { serviceTier } = parseVscodeServiceTierVariantModelId(actualModelId);+ const reasoningEffortValues = getReasoningEffortValues(model as VscodeCatalogModel);+ const selectedReasoningEffort = reasoningEffortValues+ ? getCatalogModelName(model as VscodeCatalogModel).match(/-(xhigh|high|medium|low|none)$/i)?.[1]?.toLowerCase()+ : undefined;++ const suffixes: string[] = [];+ if (selectedReasoningEffort && selectedReasoningEffort !== "none") {+ suffixes.push(formatReasoningEffortLabel(selectedReasoningEffort));+ }+ if (serviceTier) {+ suffixes.push(getVscodeServiceTierVariantSuffix(serviceTier));+ }+ if (suffixes.length === 0) {+ return prefixedDisplayName;+ }+ if (suffixes.length === 1) {+ return `${prefixedDisplayName} (${suffixes[0]})`;+ }+ const [first, ...rest] = suffixes;+ return `${prefixedDisplayName} (${first}) ${rest.map((suffix) => `(${suffix})`).join(" ")}`;+}++export function enrichModelForVscode(+ model: CatalogModelEntry,+ request: Request,+ options: EnrichModelForVscodeOptions = {}+): VscodeImportModel {+ if (!isUsableChatModel(model)) return model;++ const requestUrl = new URL(request.url);+ const tokenBasePath = requestUrl.pathname.replace(/\/models(?:\/raw)?\/?$/, "");+ const tokenBaseUrl = `${requestUrl.origin}${tokenBasePath}`;+ const canonicalMetadata = getCanonicalModelMetadata({+ provider: model.owned_by || null,+ model: model.root || model.id || model.name || null,+ });+ const family = getVscodeImportFamily(model, canonicalMetadata?.metadata.family || null);+ const resolvedCapabilities = getResolvedModelCapabilities(model.id || model.name || "");+ const reasoningEffortValues =+ resolvedCapabilities.reasoning === true+ ? getReasoningEffortValues(model as VscodeCatalogModel)+ : undefined;+ const modelImportReasoningEffortValues =+ reasoningEffortValues && reasoningEffortValues.length > 0+ ? getModelImportReasoningEffortValues(model as VscodeCatalogModel, reasoningEffortValues)+ : undefined;+ const defaultReasoningEffort = reasoningEffortValues+ ? getDefaultReasoningEffort(model as VscodeCatalogModel, reasoningEffortValues)+ : undefined;+ const supportedReasoningEfforts =+ reasoningEffortValues && reasoningEffortValues.length > 0+ ? buildSupportedReasoningEfforts(reasoningEffortValues)+ : undefined;+ const configSchema =+ reasoningEffortValues && defaultReasoningEffort+ ? buildReasoningConfigSchema(reasoningEffortValues, defaultReasoningEffort)+ : undefined;+ const actualModelId = (model.id || model.name || model.root || "").trim();+ const publishedModelId = getFamilyFirstPublishedModelId(actualModelId, family || null);+ const resolvedModelId = options.preserveNativeId ? actualModelId : publishedModelId;+ const presentationModel = {+ ...model,+ ...(resolvedModelId ? { id: resolvedModelId } : {}),+ };++ // Raw route: return a bare provider-native entry — no VS Code presentation+ // fields (url/toolCalling/vision/maxInputTokens/family/reasoning). Those are+ // only meaningful for the grouped/family-first surfaces.+ if (options.preserveNativeId) {+ return {+ ...presentationModel,+ name: getVscodeRawModelDisplayName(presentationModel),+ };+ }++ return {+ ...presentationModel,+ name: options.preserveNativeId+ ? getVscodeRawModelDisplayName(presentationModel)+ : getVscodeModelDisplayName(presentationModel),+ url: reasoningEffortValues+ ? `${tokenBaseUrl}/responses#models.ai.azure.com`+ : `${tokenBaseUrl}/chat/completions#models.ai.azure.com`,+ toolCalling: resolvedCapabilities.toolCalling === true,+ vision: resolvedCapabilities.supportsVision === true,+ maxInputTokens:+ model.max_input_tokens || resolvedCapabilities.maxInputTokens || model.context_length,+ maxOutputTokens: model.max_output_tokens || resolvedCapabilities.maxOutputTokens,+ ...(family ? { family } : {}),+ ...(modelImportReasoningEffortValues ? { supportsReasoningEffort: modelImportReasoningEffortValues } : {}),+ ...(supportedReasoningEfforts ? { supportedReasoningEfforts } : {}),+ ...(defaultReasoningEffort ? { defaultReasoningEffort } : {}),+ ...(configSchema ? { configurationSchema: configSchema } : {}),+ ...(configSchema ? { configSchema } : {}),+ };+}++export async function OPTIONS() {+ return new Response(null, {+ headers: {+ "Access-Control-Allow-Methods": "GET, OPTIONS",+ "Access-Control-Allow-Headers": "*",+ },+ });+}++export function expandVscodeRawModels(models: CatalogModelEntry[]) {+ const normalizedModels = models.map((model) => {+ const rawModelId = (model.id || model.name || model.root || "").trim();+ if (!rawModelId) {+ return model;+ }++ const tierParsedModel = parseVscodeServiceTierVariantModelId(rawModelId);+ const normalizedBaseModelId = getReasoningVariantBaseModelId(tierParsedModel.baseModelId);+ const normalizedModelId = tierParsedModel.serviceTier+ ? getVscodeServiceTierVariantModelId(normalizedBaseModelId, tierParsedModel.serviceTier)+ : normalizedBaseModelId;++ if (normalizedModelId === rawModelId) {+ return model;+ }++ return {+ ...model,+ ...(model.id ? { id: normalizedModelId } : {}),+ ...(model.name ? { name: normalizedModelId } : {}),+ ...(model.root ? { root: normalizedModelId } : {}),+ };+ });++ const tierExpandedModels = expandVscodeServiceTierModels(normalizedModels);+ const expandedModels: CatalogModelEntry[] = [];++ for (const model of tierExpandedModels) {+ expandedModels.push(model);++ const reasoningEffortValues = getReasoningEffortValues(model as VscodeCatalogModel);+ if (!reasoningEffortValues || reasoningEffortValues.length === 0) {+ continue;+ }++ const rawModelId = (model.id || model.name || model.root || "").trim();+ if (!rawModelId) {+ continue;+ }++ const parsedTierModel = parseVscodeServiceTierVariantModelId(rawModelId);+ const baseReasoningModelId = getReasoningVariantBaseModelId(parsedTierModel.baseModelId);++ for (const reasoningEffort of reasoningEffortValues) {+ if (reasoningEffort === "none") {+ continue;+ }++ const reasoningBaseModelId = `${baseReasoningModelId}-${reasoningEffort}`;+ const reasoningVariantModelId = parsedTierModel.serviceTier+ ? getVscodeServiceTierVariantModelId(reasoningBaseModelId, parsedTierModel.serviceTier)+ : reasoningBaseModelId;+ expandedModels.push({+ ...model,+ ...(model.id ? { id: reasoningVariantModelId } : {}),+ ...(model.name ? { name: reasoningVariantModelId } : {}),+ ...(model.root ? { root: reasoningVariantModelId } : {}),+ });+ }+ }++ const uniqueModels = new Map<string, CatalogModelEntry>();++ for (const model of expandedModels) {+ const uniqueKey = (model.id || model.name || model.root || "").trim();+ if (!uniqueKey || uniqueModels.has(uniqueKey)) {+ continue;+ }++ uniqueModels.set(uniqueKey, model);+ }++ return Array.from(uniqueModels.values());+}++export async function getVscodeModelsCatalogResponse(+ request: Request+): Promise<VscodeModelsCatalogResponse> {+ const response = await getUnifiedModelsResponse(request);+ const body = (await response.json()) as { data?: CatalogModelEntry[] };+ return {+ status: response.status,+ headers: {+ ...Object.fromEntries(response.headers.entries()),+ ...VSCODE_CATALOG_CACHE_HEADERS,+ },+ body: {+ ...body,+ data: Array.isArray(body.data) ? body.data.filter(isUsableChatModel) : body.data,+ },+ };+}++export async function GET(+ request: Request,+ { params }: { params?: Promise<{ token: string }> | { token: string } } = {}+) {+ const resolvedParams = params ? await params : undefined;+ const authorizedRequest = withPathTokenApiKey(request, resolvedParams?.token);+ const catalog = await getVscodeModelsCatalogResponse(authorizedRequest);+ const body = catalog.body;++ if (catalog.status < 200 || catalog.status >= 300 || !Array.isArray(body.data)) {+ return Response.json(body, {+ status: catalog.status,+ headers: catalog.headers,+ });+ }++ return Response.json(+ (() => {+ const expandedModels = expandVscodeServiceTierModels(body.data);+ const allModelIds = new Set(+ expandedModels.map((model) => (model.id || model.name || model.root || "").trim()).filter(Boolean)+ );+ const groupedModels = new Map<string, CatalogModelEntry>();+ const orderedGroupKeys: string[] = [];++ for (const model of expandedModels) {+ const modelId = (model.id || model.name || model.root || "").trim();+ if (!modelId) continue;++ const tierParsedModel = parseVscodeServiceTierVariantModelId(modelId);+ const baseModelId = getReasoningVariantBaseModelId(tierParsedModel.baseModelId);+ const canonicalModelId = tierParsedModel.serviceTier+ ? getVscodeServiceTierVariantModelId(baseModelId, tierParsedModel.serviceTier)+ : baseModelId;+ if (canonicalModelId !== modelId && allModelIds.has(canonicalModelId)) {+ continue;+ }++ const groupKey =+ tierParsedModel.serviceTier+ ? canonicalModelId+ : getVscodeModelGroupingKey({+ ...model,+ ...(canonicalModelId ? { id: canonicalModelId } : {}),+ }) || canonicalModelId;+ const current = groupedModels.get(groupKey);+ if (!current) {+ groupedModels.set(groupKey, model);+ orderedGroupKeys.push(groupKey);+ continue;+ }++ const currentId = (current.id || current.name || current.root || "").trim();+ if (currentId !== groupKey && modelId === canonicalModelId) {+ groupedModels.set(groupKey, model);+ }+ }++ return {+ ...body,+ data: orderedGroupKeys+ .map((groupKey) => groupedModels.get(groupKey))+ .filter(Boolean)+ .map((model) => enrichModelForVscode(model as CatalogModelEntry, authorizedRequest)),+ };+ })(),+ {+ status: catalog.status,+ headers: catalog.headers,+ }+ );+}diff --git a/src/app/api/v1/vscode/[token]/reasoningMetadata.ts b/src/app/api/v1/vscode/[token]/reasoningMetadata.tsnew file mode 100644index 0000000000..e7996a8883--- /dev/null+++ b/src/app/api/v1/vscode/[token]/reasoningMetadata.ts@@ -0,0 +1,175 @@+import { parseModel } from "@omniroute/open-sse/services/model";+import { supportsXHighEffort } from "@omniroute/open-sse/config/providerModels";+import { stripVscodeServiceTierVariantModelId } from "@/app/api/v1/vscode/[token]/serviceTierVariants";++export type VscodeCatalogModel = {+ id?: string;+ name?: string;+ root?: string;+ owned_by?: string;+ capabilities?: Record<string, boolean>;+ supportsReasoningEffort?: string[];+ supportedReasoningEfforts?: string[];+ supports_reasoning_effort?: string[];+ defaultReasoningEffort?: string;+ default_reasoning_effort?: string;+};++const EFFORT_SUFFIX_PATTERN = /-(xhigh|high|medium|low|none)$/i;+const DEFAULT_REASONING_EFFORT = "none";+const KNOWN_REASONING_EFFORTS = new Set(["none", "low", "medium", "high", "xhigh"]);++export type VscodeModelConfigSchema = {+ type: "object";+ properties: {+ reasoningEffort: {+ type: "string";+ title: string;+ description: string;+ default: string;+ enum: string[];+ enumLabels: string[];+ enumDescriptions: string[];+ };+ };+};++export function getCatalogModelName(model: VscodeCatalogModel) {+ return stripVscodeServiceTierVariantModelId(model.id || model.name || model.root || "");+}++function normalizeReasoningEffortValue(value: string) {+ const normalized = value.trim().toLowerCase().replace(/[_\s-]+/g, "");+ if (normalized === "xhigh") return "xhigh";+ if (KNOWN_REASONING_EFFORTS.has(normalized)) return normalized;+ return undefined;+}++function getNativeReasoningEffortValues(model: VscodeCatalogModel) {+ const candidates = [+ model.supportsReasoningEffort,+ model.supportedReasoningEfforts,+ model.supports_reasoning_effort,+ ];++ for (const candidate of candidates) {+ if (!Array.isArray(candidate) || candidate.length === 0) {+ continue;+ }++ const normalized = Array.from(+ new Set(candidate.map(value => typeof value === "string" ? normalizeReasoningEffortValue(value) : undefined).filter(Boolean))+ ) as string[];++ if (normalized.length > 0) {+ return normalized;+ }+ }++ return undefined;+}++export function isReasoningCapableModel(model: VscodeCatalogModel) {+ return (+ model.capabilities?.reasoning === true ||+ model.capabilities?.thinking === true ||+ (getNativeReasoningEffortValues(model)?.length || 0) > 0+ );+}++export function getReasoningEffortValues(model: VscodeCatalogModel) {+ const nativeReasoningEffortValues = getNativeReasoningEffortValues(model);+ if (nativeReasoningEffortValues && nativeReasoningEffortValues.length > 0) {+ return nativeReasoningEffortValues;+ }++ if (!isReasoningCapableModel(model)) return undefined;++ const modelId = getCatalogModelName(model);+ const parsed = parseModel(modelId, "");+ const providerId = parsed.provider || model.owned_by || "";+ const providerModelId = parsed.model || model.root || modelId.split("/").pop() || modelId;+ const values = ["none", "low", "medium", "high"];++ if (providerId && providerModelId && supportsXHighEffort(providerId, providerModelId)) {+ values.push("xhigh");+ }++ return values;+}++export function formatReasoningEffortLabel(level: string) {+ if (level === "xhigh") return "XHigh";+ return level.charAt(0).toUpperCase() + level.slice(1);+}++function describeReasoningEffort(level: string) {+ switch (level) {+ case "none":+ return "Disables extra reasoning effort.";+ case "low":+ return "Uses a light amount of reasoning.";+ case "medium":+ return "Uses a balanced amount of reasoning.";+ case "high":+ return "Uses an extended amount of reasoning.";+ case "xhigh":+ return "Uses the maximum available reasoning effort.";+ default:+ return `Uses ${formatReasoningEffortLabel(level)} reasoning effort.`;+ }+}++export function buildSupportedReasoningEfforts(+ supportedValues: string[]+): string[] {+ return [...supportedValues];+}++export function inferSelectedReasoningEffort(+ model: VscodeCatalogModel,+ supportedValues?: string[]+) {+ const modelId = getCatalogModelName(model);+ const match = modelId.match(EFFORT_SUFFIX_PATTERN);+ if (!match) return undefined;++ const selected = match[1]?.toLowerCase();+ if (!selected) return undefined;+ if (Array.isArray(supportedValues) && supportedValues.length > 0 && !supportedValues.includes(selected)) {+ return undefined;+ }++ return selected;+}++export function getReasoningVariantBaseModelId(modelId: string) {+ return modelId.replace(EFFORT_SUFFIX_PATTERN, "");+}++export function getDefaultReasoningEffort(+ model: VscodeCatalogModel,+ supportedValues?: string[]+) {+ return inferSelectedReasoningEffort(model, supportedValues) || DEFAULT_REASONING_EFFORT;+}++export function buildReasoningConfigSchema(+ supportedValues: string[],+ defaultReasoningEffort: string+): VscodeModelConfigSchema {+ return {+ type: "object",+ properties: {+ reasoningEffort: {+ type: "string",+ title: "Reasoning effort",+ description: "Controls how much reasoning effort the model uses.",+ default: defaultReasoningEffort,+ enum: supportedValues,+ enumLabels: supportedValues.map(formatReasoningEffortLabel),+ enumDescriptions: supportedValues.map(describeReasoningEffort),+ },+ },+ };+}diff --git a/src/app/api/v1/vscode/[token]/responses/route.ts b/src/app/api/v1/vscode/[token]/responses/route.tsnew file mode 100644index 0000000000..131c373961--- /dev/null+++ b/src/app/api/v1/vscode/[token]/responses/route.ts@@ -0,0 +1,10 @@+import { POST as basePost, OPTIONS } from "@/app/api/v1/responses/route";+import { rewriteVscodeServiceTierRequest } from "@/app/api/v1/vscode/[token]/serviceTierVariants";+import { withPathTokenApiKey } from "@/app/api/v1/vscode/[token]/tokenizedRequest";++export { OPTIONS };++export async function POST(request: Request) {+ const authorizedRequest = withPathTokenApiKey(request);+ return basePost(await rewriteVscodeServiceTierRequest(authorizedRequest));+}diff --git a/src/app/api/v1/vscode/[token]/route.ts b/src/app/api/v1/vscode/[token]/route.tsnew file mode 100644index 0000000000..fa31714fd5--- /dev/null+++ b/src/app/api/v1/vscode/[token]/route.ts@@ -0,0 +1,20 @@+import { CORS_HEADERS } from "@/shared/utils/cors";++type VscodeTokenParams = {+ token: string;+};++export async function OPTIONS() {+ return new Response(null, { headers: CORS_HEADERS });+}++export async function GET(+ request: Request,+ context?: { params: Promise<VscodeTokenParams> | VscodeTokenParams }+) {+ const modelsRoute = await import("@/app/api/v1/vscode/[token]/models/route");+ const requestUrl = new URL(request.url);+ requestUrl.pathname = `${requestUrl.pathname.replace(/\/+$/, "")}/models`;+ const modelsRequest = new Request(requestUrl, request);+ return modelsRoute.GET(modelsRequest, context);+}\ No newline at end of filediff --git a/src/app/api/v1/vscode/[token]/serviceTierVariants.ts b/src/app/api/v1/vscode/[token]/serviceTierVariants.tsnew file mode 100644index 0000000000..8e69f224c3--- /dev/null+++ b/src/app/api/v1/vscode/[token]/serviceTierVariants.ts@@ -0,0 +1,190 @@+import { CODEX_FAST_TIER_DEFAULT_SUPPORTED_MODELS } from "@/lib/providers/codexFastTier";+import { normalizeServiceTierId, type ServiceTierId } from "@/shared/utils/serviceTierLabels";+import { resolveFamilyFirstPublishedModelId } from "@/app/api/v1/vscode/[token]/familyFirstModelIds";++const SERVICE_TIER_VARIANT_PATTERN = /__tier_(priority|flex)$/i;+const SUPPORTED_VSCODE_SERVICE_TIERS: readonly ServiceTierId[] = ["priority", "flex"];++export type VscodeServiceTierModelLike = {+ id?: string;+ name?: string;+ root?: string;+ owned_by?: string;+};++export function parseVscodeServiceTierVariantModelId(modelId: string | null | undefined): {+ baseModelId: string;+ serviceTier?: ServiceTierId;+} {+ const rawModelId = typeof modelId === "string" ? modelId.trim() : "";+ if (!rawModelId) {+ return { baseModelId: "" };+ }++ const match = rawModelId.match(SERVICE_TIER_VARIANT_PATTERN);+ if (!match) {+ return { baseModelId: rawModelId };+ }++ const baseModelId = rawModelId.replace(SERVICE_TIER_VARIANT_PATTERN, "");+ const serviceTier = normalizeServiceTierId(match[1]);+ return serviceTier === "standard" ? { baseModelId } : { baseModelId, serviceTier };+}++export function stripVscodeServiceTierVariantModelId(modelId: string | null | undefined): string {+ return parseVscodeServiceTierVariantModelId(modelId).baseModelId;+}++export function isVscodeServiceTierVariantModelId(modelId: string | null | undefined): boolean {+ return Boolean(parseVscodeServiceTierVariantModelId(modelId).serviceTier);+}++export function getVscodeServiceTierVariantModelId(+ baseModelId: string,+ serviceTier: ServiceTierId+): string {+ if (serviceTier === "standard") {+ return baseModelId;+ }+ return `${baseModelId}__tier_${serviceTier}`;+}++function getRawModelId(model: VscodeServiceTierModelLike): string {+ return (model.id || model.name || model.root || "").trim();+}++function getModelProvider(model: VscodeServiceTierModelLike, baseModelId: string): string {+ const owner = typeof model.owned_by === "string" ? model.owned_by.trim().toLowerCase() : "";+ if (owner) {+ return owner;+ }+ const prefix = baseModelId.split("/")[0]?.trim().toLowerCase() || "";+ return prefix;+}++function supportsCodexServiceTierModel(baseModelId: string): boolean {+ const normalizedModel = (baseModelId.split("/").pop() || baseModelId).trim().toLowerCase();+ if (!normalizedModel) {+ return false;+ }++ return CODEX_FAST_TIER_DEFAULT_SUPPORTED_MODELS.some((candidate) => {+ const normalizedCandidate = candidate.trim().toLowerCase();+ return normalizedModel === normalizedCandidate || normalizedModel.startsWith(normalizedCandidate);+ });+}++export function supportsVscodeServiceTierVariants(model: VscodeServiceTierModelLike): boolean {+ const rawModelId = getRawModelId(model);+ if (!rawModelId) {+ return false;+ }++ const baseModelId = stripVscodeServiceTierVariantModelId(rawModelId);+ const provider = getModelProvider(model, baseModelId);+ if (provider !== "codex" && provider !== "cx") {+ return false;+ }++ return supportsCodexServiceTierModel(baseModelId);+}++function cloneModelIdentifiers<T extends VscodeServiceTierModelLike>(+ model: T,+ modelId: string+): T {+ return {+ ...model,+ ...(model.id ? { id: modelId } : {}),+ ...(model.name ? { name: modelId } : {}),+ ...(model.root ? { root: modelId } : {}),+ };+}++export function expandVscodeServiceTierModels<T extends VscodeServiceTierModelLike>(models: T[]): T[] {+ const expanded: T[] = [];++ for (const model of models) {+ const rawModelId = getRawModelId(model);+ if (!rawModelId) {+ expanded.push(model);+ continue;+ }++ const baseModelId = stripVscodeServiceTierVariantModelId(rawModelId);+ const baseModel = rawModelId === baseModelId ? model : cloneModelIdentifiers(model, baseModelId);+ expanded.push(baseModel as T);++ if (!supportsVscodeServiceTierVariants(model)) {+ continue;+ }++ for (const serviceTier of SUPPORTED_VSCODE_SERVICE_TIERS) {+ expanded.push(cloneModelIdentifiers(baseModel as T, getVscodeServiceTierVariantModelId(baseModelId, serviceTier)));+ }+ }++ return expanded;+}++export function getVscodeServiceTierVariantSuffix(serviceTier: ServiceTierId | undefined): string {+ if (serviceTier === "priority") {+ return "Fast";+ }+ if (serviceTier === "flex") {+ return "Flex";+ }+ return "Default";+}++export function resolveVscodeServiceTierRequest(body: Record<string, unknown>): Record<string, unknown> {+ const rawModelId = typeof body.model === "string" ? body.model.trim() : "";+ if (!rawModelId) {+ return body;+ }++ const resolvedModelId = resolveFamilyFirstPublishedModelId(rawModelId);++ const { baseModelId, serviceTier } = parseVscodeServiceTierVariantModelId(resolvedModelId);+ if (!serviceTier) {+ if (resolvedModelId === rawModelId) {+ return body;+ }++ return {+ ...body,+ model: resolvedModelId,+ };+ }++ return {+ ...body,+ model: baseModelId,+ ...(body.service_tier === undefined ? { service_tier: serviceTier } : {}),+ };+}++export async function rewriteVscodeServiceTierRequest(request: Request): Promise<Request> {+ if (request.method !== "POST") {+ return request;+ }++ const body = await request.clone().json().catch(() => null);+ if (!body || typeof body !== "object" || Array.isArray(body)) {+ return request;+ }++ const rewrittenBody = resolveVscodeServiceTierRequest(body as Record<string, unknown>);+ if (rewrittenBody === body) {+ return request;+ }++ const headers = new Headers(request.headers);+ headers.delete("content-length");++ return new Request(request.url, {+ method: request.method,+ headers,+ body: JSON.stringify(rewrittenBody),+ });+}diff --git a/src/app/api/v1/vscode/[token]/tokenizedRequest.ts b/src/app/api/v1/vscode/[token]/tokenizedRequest.tsnew file mode 100644index 0000000000..d390cadcd5--- /dev/null+++ b/src/app/api/v1/vscode/[token]/tokenizedRequest.ts@@ -0,0 +1,50 @@+function inferTokenFromVscodePath(request: Request) {+ try {+ const url = new URL(request.url, "http://localhost");+ const segments = url.pathname+ .split("/")+ .map((segment) => segment.trim())+ .filter(Boolean);++ const vscodeIndex = segments.indexOf("vscode");+ if (vscodeIndex === -1) return null;++ const candidate = segments[vscodeIndex + 1];+ if (!candidate || candidate === "raw" || candidate === "combos") {+ const nestedCandidate = segments[vscodeIndex + 2];+ return nestedCandidate ? decodeURIComponent(nestedCandidate) : null;+ }++ return decodeURIComponent(candidate);+ } catch {+ return null;+ }+}++export function withPathTokenApiKey(request: Request, token?: string) {+ const resolvedToken = token || inferTokenFromVscodePath(request);+ if (!resolvedToken) return request;++ const headers = new Headers(request.headers);++ if (!headers.has("x-api-key")) {+ headers.set("x-api-key", resolvedToken);+ }++ if (!headers.has("authorization")) {+ headers.set("authorization", `Bearer ${resolvedToken}`);+ }++ const method = request.method;+ const init: RequestInit & { duplex?: "half" } = {+ method,+ headers,+ };++ if (method !== "GET" && method !== "HEAD") {+ init.body = request.body;+ init.duplex = "half";+ }++ return new Request(request.url, init);+}\ No newline at end of filediff --git a/src/app/api/v1/vscode/[token]/v1/chat/completions/route.ts b/src/app/api/v1/vscode/[token]/v1/chat/completions/route.tsnew file mode 100644index 0000000000..b243f2fe8b--- /dev/null+++ b/src/app/api/v1/vscode/[token]/v1/chat/completions/route.ts@@ -0,0 +1,10 @@+import { POST as basePost, OPTIONS } from "@/app/api/v1/chat/completions/route";+import { rewriteVscodeServiceTierRequest } from "@/app/api/v1/vscode/[token]/serviceTierVariants";+import { withPathTokenApiKey } from "@/app/api/v1/vscode/[token]/tokenizedRequest";++export { OPTIONS };++export async function POST(request: Request) {+ const authorizedRequest = withPathTokenApiKey(request);+ return basePost(await rewriteVscodeServiceTierRequest(authorizedRequest));+}diff --git a/src/app/api/v1/vscode/[token]/v1/models/route.ts b/src/app/api/v1/vscode/[token]/v1/models/route.tsnew file mode 100644index 0000000000..3a5d6f63d4--- /dev/null+++ b/src/app/api/v1/vscode/[token]/v1/models/route.ts@@ -0,0 +1 @@+export { GET, OPTIONS } from "@/app/api/v1/vscode/[token]/models/route";diff --git a/src/app/api/v1/vscode/combos/[token]/[[...slug]]/route.ts b/src/app/api/v1/vscode/combos/[token]/[[...slug]]/route.tsnew file mode 100644index 0000000000..8e1d2ef107--- /dev/null+++ b/src/app/api/v1/vscode/combos/[token]/[[...slug]]/route.ts@@ -0,0 +1,421 @@+/**+ * VS Code Combos endpoint with Ollama compatibility+ *+ * Intercepts both:+ * - GET /api/v1/vscode/combos/{token} → returns combo metadata+ * - GET /api/v1/vscode/combos/{token}/api/version → returns Ollama-compatible version+ * - GET /api/v1/vscode/combos/{token}/api/tags → exposes combo catalog in Ollama format+ */+import { getUnifiedModelsResponse } from "@/app/api/v1/models/catalog";+import {+ buildReasoningConfigSchema,+ buildSupportedReasoningEfforts,+ getDefaultReasoningEffort,+ getReasoningEffortValues,+ inferSelectedReasoningEffort,+ type VscodeCatalogModel,+} from "@/app/api/v1/vscode/[token]/reasoningMetadata";+import {+ getVscodeRawModelDisplayName,+} from "@/app/api/v1/vscode/[token]/models/route";+import { withPathTokenApiKey } from "@/app/api/v1/vscode/[token]/tokenizedRequest";+import { getCanonicalModelMetadata } from "@/lib/modelMetadataRegistry";+import { CORS_HEADERS } from "@/shared/utils/cors";++const OLLAMA_COMPAT_VERSION = "0.6.4";++type ComboCatalogEntry = {+ id?: string;+ name?: string;+ root?: string;+ owned_by?: string;+ parent?: string | null;+ type?: string;+ api_format?: string;+ context_length?: number;+ max_input_tokens?: number;+ max_output_tokens?: number;+ input_modalities?: string[];+ output_modalities?: string[];+ supported_endpoints?: string[];+ capabilities?: Record<string, boolean>;+ [ key: string ]: unknown;+};++function isComboCatalogEntry(model: ComboCatalogEntry) {+ return typeof model.owned_by === "string" && model.owned_by.trim().toLowerCase() === "combo";+}++async function buildComboCatalog(request: Request) {+ const response = await getUnifiedModelsResponse(request, {+ "Content-Type": "application/json",+ ...CORS_HEADERS,+ });+ const body = (await response.json()) as { data?: ComboCatalogEntry[]; [key: string]: unknown };++ if (!response.ok) {+ return {+ status: response.status,+ headers: { ...CORS_HEADERS },+ body,+ data: [] as ComboCatalogEntry[],+ };+ }++ const data = Array.isArray(body.data) ? body.data.filter(isComboCatalogEntry) : [];+ return {+ status: response.status,+ headers: { ...CORS_HEADERS },+ body,+ data,+ };+}+++function getComboFamily(model: ComboCatalogEntry, canonicalFamily?: string | null) {+ const rawModelId = (model.id || model.name || model.root || "").trim();+ if (rawModelId) return rawModelId;+ if (canonicalFamily && canonicalFamily.trim().length > 0) return canonicalFamily.trim();+ return "combo";+}++function toOllamaTagCombo(combo: ComboCatalogEntry) {+ const actualModelId = (combo.id || combo.name || combo.root || "unknown").trim();+ const canonicalMetadata = getCanonicalModelMetadata({+ provider: combo.owned_by || null,+ model: combo.root || combo.id || combo.name || null,+ });+ const family = getComboFamily(combo, canonicalMetadata?.metadata.family || null);+ const contextLength = typeof combo.context_length === "number" ? combo.context_length : 0;+ const reasoningEffortValues = getReasoningEffortValues(combo as VscodeCatalogModel);+ const selectedReasoningEffort = reasoningEffortValues+ ? inferSelectedReasoningEffort(combo as VscodeCatalogModel, reasoningEffortValues) || "none"+ : undefined;+ const defaultReasoningEffort = reasoningEffortValues+ ? getDefaultReasoningEffort(combo as VscodeCatalogModel, reasoningEffortValues)+ : undefined;+ const supportedReasoningEfforts =+ reasoningEffortValues && reasoningEffortValues.length > 0+ ? buildSupportedReasoningEfforts(reasoningEffortValues)+ : undefined;+ const configSchema =+ reasoningEffortValues && defaultReasoningEffort+ ? buildReasoningConfigSchema(reasoningEffortValues, defaultReasoningEffort)+ : undefined;++ return {+ name: actualModelId,+ model: actualModelId,+ modified_at: "2026-01-01T00:00:00Z",+ size: 0,+ digest: `omniroute:combo:${actualModelId}`,+ ...(reasoningEffortValues+ ? {+ supports_reasoning_effort: reasoningEffortValues,+ supportsReasoningEffort: reasoningEffortValues,+ supportedReasoningEfforts,+ defaultReasoningEffort,+ selected_reasoning_effort: selectedReasoningEffort,+ selectedReasoningEffort: selectedReasoningEffort,+ ...(configSchema ? { configurationSchema: configSchema } : {}),+ ...(configSchema ? { configSchema } : {}),+ }+ : {}),+ details: {+ format: "omniroute-combo",+ family,+ parameter_size: contextLength > 0 ? `${contextLength} ctx` : "unknown",+ quantization_level: "dynamic",+ ...(reasoningEffortValues+ ? {+ supports_reasoning_effort: reasoningEffortValues,+ supportsReasoningEffort: reasoningEffortValues,+ supportedReasoningEfforts,+ defaultReasoningEffort,+ selected_reasoning_effort: selectedReasoningEffort,+ selectedReasoningEffort: selectedReasoningEffort,+ ...(configSchema ? { configurationSchema: configSchema } : {}),+ ...(configSchema ? { configSchema } : {}),+ }+ : {}),+ },+ };+}+++function buildComboShowPayload(combo: ComboCatalogEntry) {+ const actualModelId = (combo.id || combo.name || combo.root || "unknown").trim();+ const displayName = getVscodeRawModelDisplayName(combo);+ const canonicalMetadata = getCanonicalModelMetadata({+ provider: combo.owned_by || null,+ model: combo.root || combo.id || combo.name || null,+ });+ const family = getComboFamily(combo, canonicalMetadata?.metadata.family || null);+ const reasoningEffortValues = getReasoningEffortValues(combo as VscodeCatalogModel);+ const selectedReasoningEffort = reasoningEffortValues+ ? inferSelectedReasoningEffort(combo as VscodeCatalogModel, reasoningEffortValues) || "none"+ : undefined;+ const defaultReasoningEffort = reasoningEffortValues+ ? getDefaultReasoningEffort(combo as VscodeCatalogModel, reasoningEffortValues)+ : undefined;+ const supportedReasoningEfforts =+ reasoningEffortValues && reasoningEffortValues.length > 0+ ? buildSupportedReasoningEfforts(reasoningEffortValues)+ : undefined;+ const configSchema =+ reasoningEffortValues && defaultReasoningEffort+ ? buildReasoningConfigSchema(reasoningEffortValues, defaultReasoningEffort)+ : undefined;+ const modelCapabilities = combo.capabilities ? { ...combo.capabilities } : undefined;+ const capabilities = ["completion"];+ if (combo.capabilities?.vision) capabilities.push("vision");+ if (combo.capabilities?.tool_calling) capabilities.push("tools");+ if (combo.capabilities?.reasoning || combo.capabilities?.thinking) capabilities.push("thinking");++ return {+ model: actualModelId,+ remote_model: displayName,+ ...(reasoningEffortValues+ ? {+ supports_reasoning_effort: reasoningEffortValues,+ supportsReasoningEffort: reasoningEffortValues,+ supportedReasoningEfforts,+ defaultReasoningEffort,+ selected_reasoning_effort: selectedReasoningEffort,+ selectedReasoningEffort: selectedReasoningEffort,+ ...(configSchema ? { configurationSchema: configSchema } : {}),+ ...(configSchema ? { configSchema } : {}),+ }+ : {}),+ license: "proprietary",+ modelfile: `FROM ${actualModelId}`,+ parameters: "",+ template: "",+ details: {+ parent_model: combo.root || actualModelId,+ format: "omniroute-combo",+ family,+ families: [family],+ parameter_size:+ typeof combo.context_length === "number" ? `${combo.context_length} ctx` : "unknown",+ quantization_level: "dynamic",+ ...(reasoningEffortValues+ ? {+ supports_reasoning_effort: reasoningEffortValues,+ supportsReasoningEffort: reasoningEffortValues,+ supportedReasoningEfforts,+ defaultReasoningEffort,+ selected_reasoning_effort: selectedReasoningEffort,+ selectedReasoningEffort: selectedReasoningEffort,+ ...(configSchema ? { configurationSchema: configSchema } : {}),+ ...(configSchema ? { configSchema } : {}),+ }+ : {}),+ },+ model_info: {+ "general.architecture": "combo",+ "general.basename": displayName,+ ...(typeof combo.context_length === "number" ? { context_length: combo.context_length } : {}),+ ...(typeof combo.context_length === "number" ? { "combo.context_length": combo.context_length } : {}),+ ...(typeof combo.max_input_tokens === "number"+ ? { max_input_tokens: combo.max_input_tokens }+ : {}),+ ...(typeof combo.max_output_tokens === "number"+ ? { max_output_tokens: combo.max_output_tokens }+ : {}),+ ...(Array.isArray(combo.input_modalities)+ ? { input_modalities: combo.input_modalities }+ : {}),+ ...(Array.isArray(combo.output_modalities)+ ? { output_modalities: combo.output_modalities }+ : {}),+ ...(modelCapabilities ? { capabilities: modelCapabilities } : {}),+ ...(reasoningEffortValues+ ? {+ supports_reasoning_effort: reasoningEffortValues,+ supportsReasoningEffort: reasoningEffortValues,+ supportedReasoningEfforts,+ defaultReasoningEffort,+ selected_reasoning_effort: selectedReasoningEffort,+ selectedReasoningEffort: selectedReasoningEffort,+ ...(configSchema ? { configurationSchema: configSchema } : {}),+ ...(configSchema ? { configSchema } : {}),+ }+ : {}),+ },+ capabilities,+ };+}++function enrichComboForVscode(combo: ComboCatalogEntry, request: Request) {+ const requestUrl = new URL(request.url);+ const tokenBasePath = requestUrl.pathname.replace(/\/?$/, "");+ const tokenBaseUrl = `${requestUrl.origin}${tokenBasePath}`;+ const reasoningEffortValues = getReasoningEffortValues(combo as VscodeCatalogModel);+ const supportedReasoningEfforts =+ reasoningEffortValues && reasoningEffortValues.length > 0+ ? buildSupportedReasoningEfforts(reasoningEffortValues)+ : undefined;+ const defaultReasoningEffort = reasoningEffortValues+ ? getDefaultReasoningEffort(combo as VscodeCatalogModel, reasoningEffortValues)+ : undefined;+ const configSchema =+ reasoningEffortValues && defaultReasoningEffort+ ? buildReasoningConfigSchema(reasoningEffortValues, defaultReasoningEffort)+ : undefined;++ return {+ ...combo,+ name: getVscodeRawModelDisplayName(combo),+ url: reasoningEffortValues+ ? `${tokenBaseUrl}/responses#models.ai.azure.com`+ : `${tokenBaseUrl}/chat/completions#models.ai.azure.com`,+ toolCalling: combo.capabilities?.tool_calling === true,+ vision: combo.capabilities?.vision === true,+ maxInputTokens: combo.max_input_tokens || combo.context_length,+ maxOutputTokens: combo.max_output_tokens,+ family: (combo.id || combo.name || combo.root || "combo").trim() || "combo",+ ...(reasoningEffortValues ? { supportsReasoningEffort: reasoningEffortValues } : {}),+ ...(supportedReasoningEfforts ? { supportedReasoningEfforts } : {}),+ ...(defaultReasoningEffort ? { defaultReasoningEffort } : {}),+ ...(configSchema ? { configurationSchema: configSchema } : {}),+ ...(configSchema ? { configSchema } : {}),+ };+}++async function readRequestedModelName(request: Request) {+ const payload = await request+ .clone()+ .json()+ .catch(() => null);++ if (!payload || typeof payload !== "object") {+ return null;+ }++ const record = payload as Record<string, unknown>;+ const candidate = record.name ?? record.model;+ return typeof candidate === "string" && candidate.trim().length > 0 ? candidate.trim() : null;+}++export async function OPTIONS() {+ return new Response(null, {+ headers: {+ "Access-Control-Allow-Methods": "GET, OPTIONS",+ "Access-Control-Allow-Headers": "*",+ ...CORS_HEADERS,+ },+ });+}++export async function GET(+ request: Request,+ {+ params,+ }: {+ params: Promise<{ token: string; slug?: string[] }> | { token: string; slug?: string[] };+ }+) {+ const resolvedParams = await params;+ const slugPath = (resolvedParams.slug || []).join("/");+ const authorizedRequest = withPathTokenApiKey(request, resolvedParams.token);++ // Handle /api/version request (Ollama compatibility check)+ if (slugPath === "api/version") {+ return Response.json(+ { version: OLLAMA_COMPAT_VERSION },+ { headers: { ...CORS_HEADERS } }+ );+ }++ // Handle /api/tags request (redirect to models for compatibility)+ if (slugPath === "api/tags") {+ const catalog = await buildComboCatalog(authorizedRequest);+ if (catalog.status < 200 || catalog.status >= 300) {+ return Response.json(catalog.body, {+ status: catalog.status,+ headers: catalog.headers,+ });+ }+ return Response.json(+ { models: catalog.data.map(toOllamaTagCombo) },+ { headers: { ...CORS_HEADERS } }+ );+ }++ // Default: return combos metadata+ try {+ const catalog = await buildComboCatalog(authorizedRequest);+ if (catalog.status < 200 || catalog.status >= 300) {+ return Response.json(catalog.body, {+ status: catalog.status,+ headers: catalog.headers,+ });+ }+ const data = catalog.data.map((combo) => enrichComboForVscode(combo, authorizedRequest));++ return new Response(JSON.stringify({ object: "list", data }), {+ headers: {+ "Content-Type": "application/json",+ "Cache-Control": "no-store",+ ...CORS_HEADERS,+ },+ });+ } catch (error) {+ return new Response(JSON.stringify({ error: "Failed to fetch combos" }), {+ status: 500,+ headers: { "Content-Type": "application/json", ...CORS_HEADERS },+ });+ }+}++export async function POST(+ request: Request,+ {+ params,+ }: {+ params: Promise<{ token: string; slug?: string[] }> | { token: string; slug?: string[] };+ }+) {+ const resolvedParams = await params;+ const slugPath = (resolvedParams.slug || []).join("/");+ const authorizedRequest = withPathTokenApiKey(request, resolvedParams.token);++ if (slugPath !== "api/show") {+ return new Response(JSON.stringify({ error: "Not found" }), {+ status: 404,+ headers: { "Content-Type": "application/json", ...CORS_HEADERS },+ });+ }++ const requestedName = await readRequestedModelName(request);+ if (!requestedName) {+ return Response.json(+ { error: "Model name is required" },+ { status: 400, headers: { ...CORS_HEADERS } }+ );+ }++ const catalog = await buildComboCatalog(authorizedRequest);+ if (catalog.status < 200 || catalog.status >= 300) {+ return Response.json(catalog.body, {+ status: catalog.status,+ headers: catalog.headers,+ });+ }++ const combo = catalog.data.find(+ (entry) => [entry.id, entry.name, entry.root].some((value) => value === requestedName)+ );++ if (!combo) {+ return Response.json(+ { error: `Model not found: ${requestedName}` },+ { status: 404, headers: { ...CORS_HEADERS } }+ );+ }++ return Response.json(buildComboShowPayload(combo), {+ headers: { ...CORS_HEADERS },+ });+}diff --git a/src/app/api/v1/vscode/raw/[token]/api/chat/route.ts b/src/app/api/v1/vscode/raw/[token]/api/chat/route.tsnew file mode 100644index 0000000000..76d167cd68--- /dev/null+++ b/src/app/api/v1/vscode/raw/[token]/api/chat/route.ts@@ -0,0 +1,5 @@+/**+ * Alias Ollama compatível para chat no namespace raw.+ * Apenas reexporta a rota base dessa compatibilidade.+ */+export { POST, OPTIONS } from "@/app/api/v1/api/chat/route";\ No newline at end of filediff --git a/src/app/api/v1/vscode/raw/[token]/api/show/route.ts b/src/app/api/v1/vscode/raw/[token]/api/show/route.tsnew file mode 100644index 0000000000..5c43ab18a4--- /dev/null+++ b/src/app/api/v1/vscode/raw/[token]/api/show/route.ts@@ -0,0 +1,327 @@+import { getUnifiedModelsResponse } from "@/app/api/v1/models/catalog";+import { getVscodeRawModelDisplayName } from "@/app/api/v1/vscode/[token]/models/route";+import { getCanonicalModelMetadata } from "@/lib/modelMetadataRegistry";+import { CORS_HEADERS, handleCorsOptions } from "@/shared/utils/cors";+import { expandVscodeRawModels } from "@/app/api/v1/vscode/[token]/models/route";+import {+ buildReasoningConfigSchema,+ buildSupportedReasoningEfforts,+ getDefaultReasoningEffort,+ getReasoningEffortValues,+ inferSelectedReasoningEffort,+ type VscodeCatalogModel,+} from "@/app/api/v1/vscode/raw/[token]/reasoningMetadata";+import { parseVscodeServiceTierVariantModelId } from "@/app/api/v1/vscode/raw/[token]/serviceTierVariants";+import { getFamilyFirstModelCandidates } from "@/app/api/v1/vscode/raw/[token]/familyFirstModelIds";+import { withPathTokenApiKey } from "@/app/api/v1/vscode/raw/[token]/tokenizedRequest";++type OpenAiCatalogModel = {+ id?: string;+ name?: string;+ root?: string;+ parent?: string | null;+ owned_by?: string;+ type?: string;+ api_format?: string;+ context_length?: number;+ max_output_tokens?: number;+ capabilities?: Record<string, boolean>;+ input_modalities?: string[];+ output_modalities?: string[];+ supported_endpoints?: string[];+};++function isUsableChatModel(model: OpenAiCatalogModel) {+ if (typeof model.owned_by === "string" && model.owned_by.trim().toLowerCase() === "combo") {+ return false;+ }+ if (typeof model.parent === "string" && model.parent.length > 0) return false;+ if (typeof model.type === "string" && model.type !== "chat") return false;++ const apiFormat = typeof model.api_format === "string" ? model.api_format : "chat-completions";+ if (apiFormat !== "chat-completions") return false;++ if (+ Array.isArray(model.supported_endpoints) &&+ model.supported_endpoints.length > 0 &&+ !model.supported_endpoints.includes("chat")+ ) {+ return false;+ }++ if (+ Array.isArray(model.output_modalities) &&+ model.output_modalities.length > 0 &&+ !model.output_modalities.includes("text")+ ) {+ return false;+ }++ return true;+}++function getCatalogModelId(model: OpenAiCatalogModel) {+ return model.id || model.name || model.root || "unknown";+}++function normalizeArchitectureKey(value: string) {+ const normalized = value.trim().toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");+ return normalized || "model";+}++function normalizeArchitectureSource(value: string) {+ const normalized = value.trim().toLowerCase();+ if (normalized === "cx") return "codex";+ if (normalized === "gh") return "github";+ return value;+}++function getRequestedModelName(payload: unknown): string | null {+ if (!payload || typeof payload !== "object") return null;+ const record = payload as Record<string, unknown>;+ const candidate = record.name ?? record.model;+ return typeof candidate === "string" && candidate.trim().length > 0 ? candidate.trim() : null;+}++function getOllamaModelFamily(model: OpenAiCatalogModel, canonicalFamily?: string | null) {+ const rawModelId = getCatalogModelId(model).trim();+ const { baseModelId } = parseVscodeServiceTierVariantModelId(rawModelId);+ const modelFamily = baseModelId.includes("/") ? baseModelId.split("/").slice(1).join("/") : baseModelId;++ if (modelFamily) {+ return modelFamily;+ }++ if (canonicalFamily && canonicalFamily.trim().length > 0) {+ return canonicalFamily.trim();+ }++ return typeof model.owned_by === "string" && model.owned_by.trim().length > 0+ ? model.owned_by.trim()+ : "omniroute";+}++function matchesRequestedModel(model: OpenAiCatalogModel, requestedName: string): boolean {+ const canonicalMetadata = getCanonicalModelMetadata({+ provider: model.owned_by || null,+ model: model.root || model.id || model.name || null,+ });+ const family = getOllamaModelFamily(model, canonicalMetadata?.metadata.family || null);+ const actualModelId = getCatalogModelId(model);++ return [+ model.id,+ model.name,+ model.root,+ canonicalMetadata?.qualifiedId,+ canonicalMetadata?.model,+ ...getFamilyFirstModelCandidates(actualModelId, family),+ ].some((value) => value === requestedName);+}++function buildCapabilities(model: OpenAiCatalogModel): string[] {+ const capabilities = ["completion"];+ if (model.capabilities?.vision) capabilities.push("vision");+ if (model.capabilities?.tool_calling) capabilities.push("tools");+ if (model.capabilities?.reasoning || model.capabilities?.thinking) capabilities.push("thinking");+ return capabilities;+}++function buildShowPayload(model: OpenAiCatalogModel, responseModelId?: string) {+ const actualModelId = getCatalogModelId(model);+ const displayName = getVscodeRawModelDisplayName(model);+ const canonicalMetadata = getCanonicalModelMetadata({+ provider: model.owned_by || null,+ model: model.root || model.id || model.name || null,+ });+ const family = getOllamaModelFamily(model, canonicalMetadata?.metadata.family || null);+ const modelId = responseModelId || actualModelId;+ const architectureSource =+ normalizeArchitectureSource(+ canonicalMetadata?.providerAlias || canonicalMetadata?.provider || model.owned_by || family || "model"+ );+ const architecture = normalizeArchitectureKey(+ architectureSource+ );+ const reasoningEffortValues = getReasoningEffortValues(model as VscodeCatalogModel);+ const selectedReasoningEffort = reasoningEffortValues+ ? inferSelectedReasoningEffort(model as VscodeCatalogModel, reasoningEffortValues) || "none"+ : undefined;+ const defaultReasoningEffort = reasoningEffortValues+ ? getDefaultReasoningEffort(model as VscodeCatalogModel, reasoningEffortValues)+ : undefined;+ const supportedReasoningEfforts =+ reasoningEffortValues && reasoningEffortValues.length > 0+ ? buildSupportedReasoningEfforts(reasoningEffortValues)+ : undefined;+ const configSchema =+ reasoningEffortValues && defaultReasoningEffort+ ? buildReasoningConfigSchema(reasoningEffortValues, defaultReasoningEffort)+ : undefined;+ let modelCapabilities = model.capabilities ? { ...model.capabilities } : undefined;++ if (reasoningEffortValues) {+ modelCapabilities = modelCapabilities || {};+ Object.assign(modelCapabilities, {+ reasoning: true,+ thinking: true,+ supports_reasoning_effort: reasoningEffortValues,+ supportsReasoningEffort: reasoningEffortValues,+ supportedReasoningEfforts,+ defaultReasoningEffort,+ selected_reasoning_effort: selectedReasoningEffort,+ selectedReasoningEffort: selectedReasoningEffort,+ ...(configSchema ? { configurationSchema: configSchema } : {}),+ ...(configSchema ? { configSchema } : {}),+ });+ }++ return {+ model: modelId,+ remote_model: displayName,+ ...(reasoningEffortValues+ ? {+ supports_reasoning_effort: reasoningEffortValues,+ supportsReasoningEffort: reasoningEffortValues,+ supportedReasoningEfforts,+ defaultReasoningEffort,+ selected_reasoning_effort: selectedReasoningEffort,+ selectedReasoningEffort: selectedReasoningEffort,+ ...(configSchema ? { configurationSchema: configSchema } : {}),+ ...(configSchema ? { configSchema } : {}),+ }+ : {}),+ license: "proprietary",+ modelfile: `FROM ${modelId}`,+ parameters: "",+ template: "",+ details: {+ parent_model: model.root || actualModelId || "",+ format: "openai",+ family,+ families: [family],+ parameter_size: "unknown",+ quantization_level: "dynamic",+ ...(reasoningEffortValues+ ? {+ supports_reasoning_effort: reasoningEffortValues,+ supportsReasoningEffort: reasoningEffortValues,+ supportedReasoningEfforts,+ defaultReasoningEffort,+ selected_reasoning_effort: selectedReasoningEffort,+ selectedReasoningEffort: selectedReasoningEffort,+ ...(configSchema ? { configurationSchema: configSchema } : {}),+ ...(configSchema ? { configSchema } : {}),+ }+ : {}),+ },+ model_info: {+ "general.architecture": architecture,+ "general.basename": displayName,+ ...(typeof model.context_length === "number" ? { context_length: model.context_length } : {}),+ ...(typeof model.context_length === "number"+ ? { [`${architecture}.context_length`]: model.context_length }+ : {}),+ ...(typeof model.max_output_tokens === "number"+ ? { max_output_tokens: model.max_output_tokens }+ : {}),+ ...(Array.isArray(model.input_modalities)+ ? { input_modalities: model.input_modalities }+ : {}),+ ...(Array.isArray(model.output_modalities)+ ? { output_modalities: model.output_modalities }+ : {}),+ ...(Array.isArray(model.supported_endpoints)+ ? { supported_endpoints: model.supported_endpoints }+ : {}),+ ...(modelCapabilities ? { capabilities: modelCapabilities } : {}),+ ...(reasoningEffortValues+ ? {+ supports_reasoning_effort: reasoningEffortValues,+ supportsReasoningEffort: reasoningEffortValues,+ supportedReasoningEfforts,+ defaultReasoningEffort,+ selected_reasoning_effort: selectedReasoningEffort,+ selectedReasoningEffort: selectedReasoningEffort,+ ...(configSchema ? { configurationSchema: configSchema } : {}),+ ...(configSchema ? { configSchema } : {}),+ }+ : {}),+ },+ capabilities: buildCapabilities(model),+ };+}++export async function OPTIONS() {+ return handleCorsOptions();+}++export async function POST(+ request: Request,+ { params }: { params?: Promise<{ token: string }> | { token: string } } = {}+) {+ const resolvedParams = params ? await params : undefined;+ const authorizedRequest = withPathTokenApiKey(request, resolvedParams?.token);+ const payload = await request+ .clone()+ .json()+ .catch(() => null);+ const requestedName = getRequestedModelName(payload);++ if (!requestedName) {+ return Response.json(+ {+ error: "Model name is required",+ },+ {+ status: 400,+ headers: {+ ...CORS_HEADERS,+ },+ }+ );+ }++ const catalogResponse = await getUnifiedModelsResponse(authorizedRequest, {+ "Content-Type": "application/json",+ ...CORS_HEADERS,+ });+ const catalogBody = (await catalogResponse.json()) as { data?: OpenAiCatalogModel[] };++ if (!catalogResponse.ok) {+ return Response.json(catalogBody, {+ status: catalogResponse.status,+ headers: {+ ...CORS_HEADERS,+ },+ });+ }++ const expandedModels = Array.isArray(catalogBody.data)+ ? expandVscodeRawModels(catalogBody.data.filter(isUsableChatModel))+ : [];++ const model = Array.isArray(expandedModels)+ ? expandedModels.find((entry) => matchesRequestedModel(entry, requestedName))+ : undefined;++ if (!model) {+ return Response.json(+ {+ error: `Model not found: ${requestedName}`,+ },+ {+ status: 404,+ headers: {+ ...CORS_HEADERS,+ },+ }+ );+ }++ return Response.json(buildShowPayload(model), {+ headers: {+ ...CORS_HEADERS,+ },+ });+}diff --git a/src/app/api/v1/vscode/raw/[token]/api/tags/route.ts b/src/app/api/v1/vscode/raw/[token]/api/tags/route.tsnew file mode 100644index 0000000000..830cab45da--- /dev/null+++ b/src/app/api/v1/vscode/raw/[token]/api/tags/route.ts@@ -0,0 +1,213 @@+import { getUnifiedModelsResponse } from "@/app/api/v1/models/catalog";+import { getProviderConnections } from "@/lib/db/providers";+import { getCanonicalModelMetadata } from "@/lib/modelMetadataRegistry";+import { CORS_HEADERS, handleCorsOptions } from "@/shared/utils/cors";+import { expandVscodeRawModels } from "@/app/api/v1/vscode/[token]/models/route";+import {+ buildReasoningConfigSchema,+ buildSupportedReasoningEfforts,+ getDefaultReasoningEffort,+ getReasoningVariantBaseModelId,+ getReasoningEffortValues,+ inferSelectedReasoningEffort,+ type VscodeCatalogModel,+} from "@/app/api/v1/vscode/raw/[token]/reasoningMetadata";+import { parseVscodeServiceTierVariantModelId } from "@/app/api/v1/vscode/raw/[token]/serviceTierVariants";+import { withPathTokenApiKey } from "@/app/api/v1/vscode/raw/[token]/tokenizedRequest";++type OpenAiCatalogModel = {+ id?: string;+ name?: string;+ root?: string;+ parent?: string | null;+ owned_by?: string;+ type?: string;+ api_format?: string;+ context_length?: number;+ output_modalities?: string[];+ supported_endpoints?: string[];+};++function getModelName(model: OpenAiCatalogModel) {+ return model.id || model.name || model.root || "";+}++function isCodexOwnedModel(model: OpenAiCatalogModel) {+ const owner = typeof model.owned_by === "string" ? model.owned_by.trim().toLowerCase() : "";+ const modelName = getModelName(model).toLowerCase();++ return owner === "codex" || modelName.startsWith("cx/") || modelName.startsWith("codex/");+}++async function selectPreferredModels(models: OpenAiCatalogModel[]) {+ const activeConnections = (await getProviderConnections({ isActive: true })) as Array<{+ provider?: string;+ }>;+ const activeProviders = new Set(+ activeConnections+ .map((connection) =>+ typeof connection.provider === "string" ? connection.provider.trim().toLowerCase() : ""+ )+ .filter(Boolean)+ );++ const preferCodexOnly =+ activeProviders.size > 0 && Array.from(activeProviders).every((provider) => provider === "codex");+ if (!preferCodexOnly) return models;++ const codexModels = models.filter(isCodexOwnedModel);+ return codexModels.length > 0 ? codexModels : models;+}++function isUsableChatModel(model: OpenAiCatalogModel) {+ if (typeof model.owned_by === "string" && model.owned_by.trim().toLowerCase() === "combo") {+ return false;+ }+ if (typeof model.parent === "string" && model.parent.length > 0) return false;+ if (typeof model.type === "string" && model.type !== "chat") return false;++ const apiFormat = typeof model.api_format === "string" ? model.api_format : "chat-completions";+ if (apiFormat !== "chat-completions") return false;++ if (+ Array.isArray(model.supported_endpoints) &&+ model.supported_endpoints.length > 0 &&+ !model.supported_endpoints.includes("chat")+ ) {+ return false;+ }++ if (+ Array.isArray(model.output_modalities) &&+ model.output_modalities.length > 0 &&+ !model.output_modalities.includes("text")+ ) {+ return false;+ }++ return true;+}++function getOllamaModelFamily(model: OpenAiCatalogModel, canonicalFamily?: string | null) {+ const rawModelId = getModelName(model).trim();+ const tierParsedModel = parseVscodeServiceTierVariantModelId(rawModelId);+ const baseModelId = getReasoningVariantBaseModelId(tierParsedModel.baseModelId);+ const modelFamily = baseModelId.includes("/") ? baseModelId.split("/").slice(1).join("/") : baseModelId;++ if (modelFamily) {+ return modelFamily;+ }++ if (canonicalFamily && canonicalFamily.trim().length > 0) {+ return canonicalFamily.trim();+ }++ return typeof model.owned_by === "string" && model.owned_by.trim().length > 0+ ? model.owned_by.trim()+ : "omniroute";+}++function toOllamaTagModel(model: OpenAiCatalogModel) {+ const actualModelId = model.id || model.root || "unknown";+ const canonicalMetadata = getCanonicalModelMetadata({+ provider: model.owned_by || null,+ model: model.root || model.id || model.name || null,+ });+ const family = getOllamaModelFamily(model, canonicalMetadata?.metadata.family || null);+ const modelId = actualModelId;+ const contextLength = typeof model.context_length === "number" ? model.context_length : 0;+ const reasoningEffortValues = getReasoningEffortValues(model as VscodeCatalogModel);+ const selectedReasoningEffort = reasoningEffortValues+ ? inferSelectedReasoningEffort(model as VscodeCatalogModel, reasoningEffortValues) || "none"+ : undefined;+ const defaultReasoningEffort = reasoningEffortValues+ ? getDefaultReasoningEffort(model as VscodeCatalogModel, reasoningEffortValues)+ : undefined;+ const supportedReasoningEfforts =+ reasoningEffortValues && reasoningEffortValues.length > 0+ ? buildSupportedReasoningEfforts(reasoningEffortValues)+ : undefined;+ const configSchema =+ reasoningEffortValues && defaultReasoningEffort+ ? buildReasoningConfigSchema(reasoningEffortValues, defaultReasoningEffort)+ : undefined;++ return {+ name: modelId,+ model: modelId,+ modified_at: "2026-01-01T00:00:00Z",+ size: 0,+ digest: `omniroute:${modelId}`,+ ...(reasoningEffortValues+ ? {+ supports_reasoning_effort: reasoningEffortValues,+ supportsReasoningEffort: reasoningEffortValues,+ supportedReasoningEfforts,+ defaultReasoningEffort,+ selected_reasoning_effort: selectedReasoningEffort,+ selectedReasoningEffort: selectedReasoningEffort,+ ...(configSchema ? { configurationSchema: configSchema } : {}),+ ...(configSchema ? { configSchema } : {}),+ }+ : {}),+ details: {+ format: "openai",+ family,+ parameter_size: contextLength > 0 ? `${contextLength} ctx` : "unknown",+ quantization_level: "dynamic",+ ...(reasoningEffortValues+ ? {+ supports_reasoning_effort: reasoningEffortValues,+ supportsReasoningEffort: reasoningEffortValues,+ supportedReasoningEfforts,+ defaultReasoningEffort,+ selected_reasoning_effort: selectedReasoningEffort,+ selectedReasoningEffort: selectedReasoningEffort,+ ...(configSchema ? { configurationSchema: configSchema } : {}),+ ...(configSchema ? { configSchema } : {}),+ }+ : {}),+ },+ };+}++export async function OPTIONS() {+ return handleCorsOptions();+}++export async function GET(+ request: Request,+ { params }: { params?: Promise<{ token: string }> | { token: string } } = {}+) {+ const resolvedParams = params ? await params : undefined;+ const authorizedRequest = withPathTokenApiKey(request, resolvedParams?.token);+ const response = await getUnifiedModelsResponse(authorizedRequest, {+ "Content-Type": "application/json",+ ...CORS_HEADERS,+ });+ const body = (await response.json()) as { data?: OpenAiCatalogModel[] };++ if (!response.ok) {+ return Response.json(body, {+ status: response.status,+ headers: {+ ...CORS_HEADERS,+ },+ });+ }++ const usableModels = Array.isArray(body.data) ? body.data.filter(isUsableChatModel) : [];+ const preferredModels = expandVscodeRawModels(await selectPreferredModels(usableModels));+ const models = preferredModels.map(toOllamaTagModel);++ return Response.json(+ {+ models,+ },+ {+ headers: {+ ...CORS_HEADERS,+ },+ }+ );+}diff --git a/src/app/api/v1/vscode/raw/[token]/api/version/route.ts b/src/app/api/v1/vscode/raw/[token]/api/version/route.tsnew file mode 100644index 0000000000..89cf0622d1--- /dev/null+++ b/src/app/api/v1/vscode/raw/[token]/api/version/route.ts@@ -0,0 +1,20 @@+import { CORS_HEADERS, handleCorsOptions } from "@/shared/utils/cors";++const OLLAMA_COMPAT_VERSION = "0.6.4";++export async function OPTIONS() {+ return handleCorsOptions();+}++export async function GET() {+ return Response.json(+ {+ version: OLLAMA_COMPAT_VERSION,+ },+ {+ headers: {+ ...CORS_HEADERS,+ },+ }+ );+}\ No newline at end of filediff --git a/src/app/api/v1/vscode/raw/[token]/chat/completions/route.ts b/src/app/api/v1/vscode/raw/[token]/chat/completions/route.tsnew file mode 100644index 0000000000..3a7abb6ad8--- /dev/null+++ b/src/app/api/v1/vscode/raw/[token]/chat/completions/route.ts@@ -0,0 +1,10 @@+import { POST as basePost, OPTIONS } from "@/app/api/v1/chat/completions/route";+import { rewriteVscodeServiceTierRequest } from "@/app/api/v1/vscode/raw/[token]/serviceTierVariants";+import { withPathTokenApiKey } from "@/app/api/v1/vscode/raw/[token]/tokenizedRequest";++export { OPTIONS };++export async function POST(request: Request) {+ const authorizedRequest = withPathTokenApiKey(request);+ return basePost(await rewriteVscodeServiceTierRequest(authorizedRequest));+}diff --git a/src/app/api/v1/vscode/raw/[token]/combos/route.ts b/src/app/api/v1/vscode/raw/[token]/combos/route.tsnew file mode 100644index 0000000000..f422817fd0--- /dev/null+++ b/src/app/api/v1/vscode/raw/[token]/combos/route.ts@@ -0,0 +1,41 @@+/**+ * VS Code Combos endpoint — re-export base Ollama-compatible routes+ * and intercept GET to return combo metadata.+ *+ * The VS Code extension expects a standard Ollama server at the base URL,+ * so we re-export /api/version, /api/tags, etc. from the [token] parent route.+ */+import { getCombos } from "@/lib/db/combos";+import { projectCombo, type PublicCombo } from "@/app/api/v1/combos/projectCombo";++// Re-export Ollama-compatible endpoints from the parent [token] route+// so VS Code can validate the server version and list models normally+export { OPTIONS } from "@/app/api/v1/vscode/raw/[token]/route";+export async function GET(request: Request) {+ // If client requests /api/version or other Ollama endpoints, delegate to parent+ const url = new URL(request.url);+ if (url.pathname.includes("/api/version") || url.pathname.includes("/api/tags")) {+ const { GET: parentGET } = await import("@/app/api/v1/vscode/raw/[token]/route");+ return parentGET(request);+ }++ // Default: return combos metadata+ try {+ const combos = await getCombos();+ const data = (Array.isArray(combos) ? combos : [])+ .map((combo) => projectCombo(combo as Record<string, unknown>))+ .filter((combo): combo is PublicCombo => combo !== null);++ return new Response(JSON.stringify({ object: "list", data, combos: data }), {+ headers: {+ "Content-Type": "application/json",+ "Cache-Control": "no-store",+ },+ });+ } catch (error) {+ return new Response(JSON.stringify({ error: "Failed to fetch combos" }), {+ status: 500,+ headers: { "Content-Type": "application/json" },+ });+ }+}diff --git a/src/app/api/v1/vscode/raw/[token]/familyFirstModelIds.ts b/src/app/api/v1/vscode/raw/[token]/familyFirstModelIds.tsnew file mode 100644index 0000000000..c5a2484761--- /dev/null+++ b/src/app/api/v1/vscode/raw/[token]/familyFirstModelIds.ts@@ -0,0 +1,85 @@+const FAMILY_FIRST_MODEL_PATTERN = /^((?:gpt-[a-z0-9._-]+|claude[a-z0-9._-]*))(?:__provider_([a-z0-9-]+))(?:__tier_(priority|flex))?$/i;+const TIER_SUFFIX_PATTERN = /(__tier_(?:priority|flex))$/i;++function normalizeFamily(value: string | null | undefined) {+ return typeof value === "string" ? value.trim() : "";+}++function splitActualModelId(modelId: string) {+ const trimmedModelId = modelId.trim();+ const slashIndex = trimmedModelId.indexOf("/");+ if (slashIndex <= 0 || slashIndex === trimmedModelId.length - 1) {+ return null;+ }++ return {+ providerPrefix: trimmedModelId.slice(0, slashIndex),+ providerModelId: trimmedModelId.slice(slashIndex + 1),+ };+}++function extractTierSuffix(modelId: string) {+ const match = modelId.match(TIER_SUFFIX_PATTERN);+ return match?.[1] || "";+}++function stripTierSuffix(modelId: string) {+ return modelId.replace(TIER_SUFFIX_PATTERN, "");+}++function isFamilyFirstEligibleFamily(family: string) {+ const normalized = family.toLowerCase();+ return normalized.startsWith("gpt-") || normalized.startsWith("claude");+}++export function getFamilyFirstPublishedModelId(actualModelId: string, family: string | null | undefined) {+ const normalizedFamily = normalizeFamily(family);+ if (!normalizedFamily || !isFamilyFirstEligibleFamily(normalizedFamily)) {+ return actualModelId;+ }++ const parts = splitActualModelId(actualModelId);+ if (!parts) {+ return actualModelId;+ }++ const tierSuffix = extractTierSuffix(parts.providerModelId);+ const providerModelBase = stripTierSuffix(parts.providerModelId);+ if (providerModelBase !== normalizedFamily) {+ return actualModelId;+ }++ return `${normalizedFamily}__provider_${parts.providerPrefix}${tierSuffix}`;+}++export function resolveFamilyFirstPublishedModelId(modelId: string | null | undefined) {+ const trimmedModelId = typeof modelId === "string" ? modelId.trim() : "";+ if (!trimmedModelId) {+ return trimmedModelId;+ }++ const match = trimmedModelId.match(FAMILY_FIRST_MODEL_PATTERN);+ if (!match) {+ return trimmedModelId;+ }++ const [, family, providerPrefix, serviceTier] = match;+ const tierSuffix = serviceTier ? `__tier_${serviceTier.toLowerCase()}` : "";+ return `${providerPrefix}/${family}${tierSuffix}`;+}++export function getFamilyFirstModelCandidates(actualModelId: string, family: string | null | undefined) {+ const normalizedFamily = normalizeFamily(family);+ const candidates = new Set<string>([actualModelId]);+ const publishedModelId = getFamilyFirstPublishedModelId(actualModelId, normalizedFamily);+ if (publishedModelId !== actualModelId) {+ candidates.add(publishedModelId);+ }++ if (normalizedFamily && isFamilyFirstEligibleFamily(normalizedFamily)) {+ const tierSuffix = extractTierSuffix(actualModelId);+ candidates.add(`${normalizedFamily}${tierSuffix}`);+ }++ return [...candidates];+}\ No newline at end of filediff --git a/src/app/api/v1/vscode/raw/[token]/modelPresentation.ts b/src/app/api/v1/vscode/raw/[token]/modelPresentation.tsnew file mode 100644index 0000000000..fda4259dd2--- /dev/null+++ b/src/app/api/v1/vscode/raw/[token]/modelPresentation.ts@@ -0,0 +1,178 @@+import { parseModel } from "@omniroute/open-sse/services/model";+import {+ getCanonicalModelMetadata,+ type CanonicalModelMetadata,+} from "@/lib/modelMetadataRegistry";+import {+ getVscodeServiceTierVariantSuffix,+ parseVscodeServiceTierVariantModelId,+ supportsVscodeServiceTierVariants,+} from "@/app/api/v1/vscode/raw/[token]/serviceTierVariants";+import { getReasoningVariantBaseModelId } from "@/app/api/v1/vscode/raw/[token]/reasoningMetadata";+import { resolveFamilyFirstPublishedModelId } from "@/app/api/v1/vscode/raw/[token]/familyFirstModelIds";+type VscodeCatalogModel = {+ id?: string;+ name?: string;+ root?: string;+ owned_by?: string;+};++const PROVIDER_NAME_OVERRIDES: Record<string, string> = {+ codex: "Codex",+ cx: "Codex",+ github: "GitHub",+ gh: "GitHub",+ "gemini-cli": "Gemini",+ gemini: "Gemini",+};++function tokenize(value: string) {+ return value+ .toLowerCase()+ .split(/[^a-z0-9]+/i)+ .map((part) => part.trim())+ .filter((part) => part.length >= 4);+}++function getProviderPrefix(metadata: CanonicalModelMetadata | null) {+ const providerKey = metadata?.providerAlias || metadata?.provider || "";+ if (providerKey && PROVIDER_NAME_OVERRIDES[providerKey]) {+ return PROVIDER_NAME_OVERRIDES[providerKey];+ }++ const providerLabel = metadata?.providerLabel?.trim() || null;+ if (!providerLabel) {+ return null;+ }+ if (/codex/i.test(providerLabel)) {+ return "Codex";+ }+ if (/github/i.test(providerLabel)) {+ return "GitHub";+ }+ if (/gemini/i.test(providerLabel)) {+ return "Gemini";+ }++ return providerLabel;+}++function normalizeDisplayNameBranding(displayName: string) {+ return displayName+ .replace(/^OpenAI\s+Codex\b/i, "Codex")+ .replace(/^GitHub\s+Copilot\b/i, "GitHub")+ .trim();+}++function stripLeadingProviderPrefix(displayName: string, providerPrefix: string | null) {+ if (!providerPrefix) {+ return displayName;+ }++ const escapedProviderPrefix = providerPrefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+ return displayName.replace(new RegExp(`^${escapedProviderPrefix}\\s+`, "i"), "").trim();+}++function looksLikeTechnicalModelName(value: string) {+ return /\/|__provider_|__tier_|^[a-z0-9-]+\/[a-z0-9._-]+$/i.test(value);+}++function humanizeModelIdentifier(modelId: string) {+ const identifier = (modelId.split("/").pop() || modelId).trim();+ if (!identifier) {+ return identifier;+ }++ return identifier+ .split(/[-_]+/)+ .filter(Boolean)+ .map(part => {+ if (/^gpt$/i.test(part)) return "GPT";+ if (/^[0-9]+(?:\.[0-9]+)*$/.test(part)) return part;+ if (/^[a-z][0-9]$/i.test(part)) return part.toUpperCase();+ return part.charAt(0).toUpperCase() + part.slice(1);+ })+ .join(" ");+}++function resolveFriendlyBaseDisplayName(+ rawModelId: string,+ metadata: CanonicalModelMetadata | null,+ fallbackValue: string+) {+ const normalizedFallback = normalizeDisplayNameBranding(fallbackValue.trim());+ if (normalizedFallback && !looksLikeTechnicalModelName(normalizedFallback)) {+ return normalizedFallback;+ }++ const normalizedModelId = resolveFamilyFirstPublishedModelId(rawModelId);+ const parsedTierModel = parseVscodeServiceTierVariantModelId(normalizedModelId);+ const canonicalBaseModelId = getReasoningVariantBaseModelId(parsedTierModel.baseModelId);+ const parsed = parseModel(canonicalBaseModelId, "");+ const providerModelId =+ parsed.model ||+ (canonicalBaseModelId.includes("/")+ ? canonicalBaseModelId.split("/").slice(1).join("/")+ : canonicalBaseModelId) ||+ fallbackValue;++ return humanizeModelIdentifier(providerModelId);+}++function prefixDisplayName(displayName: string, providerPrefix: string | null) {+ const normalizedProviderPrefix = providerPrefix?.trim() || null;+ const normalizedDisplayName = normalizeDisplayNameBranding(displayName);++ if (!normalizedProviderPrefix) return normalizedDisplayName;++ const providerTokens = tokenize(normalizedProviderPrefix);+ if (providerTokens.length === 0) return normalizedDisplayName;++ const displayNameLower = normalizedDisplayName.toLowerCase();+ if (providerTokens.some((token) => displayNameLower.includes(token))) {+ return normalizedDisplayName;+ }++ return `${normalizedProviderPrefix} ${stripLeadingProviderPrefix(normalizedDisplayName, normalizedProviderPrefix)}`.trim();+}++export function resolveVscodeModelMetadata(model: VscodeCatalogModel) {+ const rawModelId = model.id || model.root || model.name || "";+ const normalizedModelId = resolveFamilyFirstPublishedModelId(rawModelId);+ const parsedTierModel = parseVscodeServiceTierVariantModelId(normalizedModelId);+ const canonicalBaseModelId = getReasoningVariantBaseModelId(parsedTierModel.baseModelId);+ const parsed = parseModel(canonicalBaseModelId, "");+ const provider = parsed.provider || model.owned_by || undefined;+ const providerModel =+ parsed.model ||+ (canonicalBaseModelId.includes("/")+ ? canonicalBaseModelId.split("/").slice(1).join("/")+ : canonicalBaseModelId) ||+ model.root ||+ model.id ||+ model.name ||+ undefined;++ return providerModel && provider+ ? getCanonicalModelMetadata({ provider, model: providerModel })+ : providerModel+ ? getCanonicalModelMetadata({ model: providerModel })+ : null;+}++export function getVscodeModelDisplayName(model: VscodeCatalogModel) {+ const rawModelId = model.id || model.root || model.name || "";+ const { serviceTier } = parseVscodeServiceTierVariantModelId(rawModelId);+ const metadata = resolveVscodeModelMetadata(model);+ const displayName = metadata?.displayName || model.name || model.id || model.root || "unknown";+ const prefixedDisplayName = prefixDisplayName(displayName, getProviderPrefix(metadata));+ const shouldShowTierSuffix = Boolean(serviceTier) || supportsVscodeServiceTierVariants(model);+ return shouldShowTierSuffix+ ? `${prefixedDisplayName} (${getVscodeServiceTierVariantSuffix(serviceTier)})`+ : prefixedDisplayName;+}++export function getVscodeModelGroupingKey(model: VscodeCatalogModel) {+ const metadata = resolveVscodeModelMetadata(model);+ return metadata?.qualifiedId || metadata?.model || model.id || model.name || model.root || "";+}diff --git a/src/app/api/v1/vscode/raw/[token]/models/route.ts b/src/app/api/v1/vscode/raw/[token]/models/route.tsnew file mode 100644index 0000000000..74c588514f--- /dev/null+++ b/src/app/api/v1/vscode/raw/[token]/models/route.ts@@ -0,0 +1,43 @@+import {+ enrichModelForVscode,+ expandVscodeRawModels,+ getVscodeModelsCatalogResponse,+} from "@/app/api/v1/vscode/[token]/models/route";+import { withPathTokenApiKey } from "@/app/api/v1/vscode/raw/[token]/tokenizedRequest";++export async function OPTIONS() {+ return new Response(null, {+ headers: {+ "Access-Control-Allow-Methods": "GET, OPTIONS",+ "Access-Control-Allow-Headers": "*",+ },+ });+}++export async function GET(+ request: Request,+ { params }: { params?: Promise<{ token: string }> | { token: string } } = {}+) {+ const resolvedParams = params ? await params : undefined;+ const authorizedRequest = withPathTokenApiKey(request, resolvedParams?.token);+ const catalog = await getVscodeModelsCatalogResponse(authorizedRequest);+ if (catalog.status < 200 || catalog.status >= 300 || !Array.isArray(catalog.body.data)) {+ return Response.json(catalog.body, {+ status: catalog.status,+ headers: catalog.headers,+ });+ }++ return Response.json(+ {+ ...catalog.body,+ data: expandVscodeRawModels(catalog.body.data).map((model) =>+ enrichModelForVscode(model, authorizedRequest, { preserveNativeId: true })+ ),+ },+ {+ status: catalog.status,+ headers: catalog.headers,+ }+ );+}diff --git a/src/app/api/v1/vscode/raw/[token]/reasoningMetadata.ts b/src/app/api/v1/vscode/raw/[token]/reasoningMetadata.tsnew file mode 100644index 0000000000..431bc25a4c--- /dev/null+++ b/src/app/api/v1/vscode/raw/[token]/reasoningMetadata.ts@@ -0,0 +1,175 @@+import { parseModel } from "@omniroute/open-sse/services/model";+import { supportsXHighEffort } from "@omniroute/open-sse/config/providerModels";+import { stripVscodeServiceTierVariantModelId } from "@/app/api/v1/vscode/raw/[token]/serviceTierVariants";++export type VscodeCatalogModel = {+ id?: string;+ name?: string;+ root?: string;+ owned_by?: string;+ capabilities?: Record<string, boolean>;+ supportsReasoningEffort?: string[];+ supportedReasoningEfforts?: string[];+ supports_reasoning_effort?: string[];+ defaultReasoningEffort?: string;+ default_reasoning_effort?: string;+};++const EFFORT_SUFFIX_PATTERN = /-(xhigh|high|medium|low|none)$/i;+const DEFAULT_REASONING_EFFORT = "none";+const KNOWN_REASONING_EFFORTS = new Set(["none", "low", "medium", "high", "xhigh"]);++export type VscodeModelConfigSchema = {+ type: "object";+ properties: {+ reasoningEffort: {+ type: "string";+ title: string;+ description: string;+ default: string;+ enum: string[];+ enumLabels: string[];+ enumDescriptions: string[];+ };+ };+};++export function getCatalogModelName(model: VscodeCatalogModel) {+ return stripVscodeServiceTierVariantModelId(model.id || model.name || model.root || "");+}++function normalizeReasoningEffortValue(value: string) {+ const normalized = value.trim().toLowerCase().replace(/[_\s-]+/g, "");+ if (normalized === "xhigh") return "xhigh";+ if (KNOWN_REASONING_EFFORTS.has(normalized)) return normalized;+ return undefined;+}++function getNativeReasoningEffortValues(model: VscodeCatalogModel) {+ const candidates = [+ model.supportsReasoningEffort,+ model.supportedReasoningEfforts,+ model.supports_reasoning_effort,+ ];++ for (const candidate of candidates) {+ if (!Array.isArray(candidate) || candidate.length === 0) {+ continue;+ }++ const normalized = Array.from(+ new Set(candidate.map(value => typeof value === "string" ? normalizeReasoningEffortValue(value) : undefined).filter(Boolean))+ ) as string[];++ if (normalized.length > 0) {+ return normalized;+ }+ }++ return undefined;+}++export function isReasoningCapableModel(model: VscodeCatalogModel) {+ return (+ model.capabilities?.reasoning === true ||+ model.capabilities?.thinking === true ||+ (getNativeReasoningEffortValues(model)?.length || 0) > 0+ );+}++export function getReasoningEffortValues(model: VscodeCatalogModel) {+ const nativeReasoningEffortValues = getNativeReasoningEffortValues(model);+ if (nativeReasoningEffortValues && nativeReasoningEffortValues.length > 0) {+ return nativeReasoningEffortValues;+ }++ if (!isReasoningCapableModel(model)) return undefined;++ const modelId = getCatalogModelName(model);+ const parsed = parseModel(modelId, "");+ const providerId = parsed.provider || model.owned_by || "";+ const providerModelId = parsed.model || model.root || modelId.split("/").pop() || modelId;+ const values = ["none", "low", "medium", "high"];++ if (providerId && providerModelId && supportsXHighEffort(providerId, providerModelId)) {+ values.push("xhigh");+ }++ return values;+}++export function formatReasoningEffortLabel(level: string) {+ if (level === "xhigh") return "XHigh";+ return level.charAt(0).toUpperCase() + level.slice(1);+}++function describeReasoningEffort(level: string) {+ switch (level) {+ case "none":+ return "Disables extra reasoning effort.";+ case "low":+ return "Uses a light amount of reasoning.";+ case "medium":+ return "Uses a balanced amount of reasoning.";+ case "high":+ return "Uses an extended amount of reasoning.";+ case "xhigh":+ return "Uses the maximum available reasoning effort.";+ default:+ return `Uses ${formatReasoningEffortLabel(level)} reasoning effort.`;+ }+}++export function buildSupportedReasoningEfforts(+ supportedValues: string[]+): string[] {+ return [...supportedValues];+}++export function inferSelectedReasoningEffort(+ model: VscodeCatalogModel,+ supportedValues?: string[]+) {+ const modelId = getCatalogModelName(model);+ const match = modelId.match(EFFORT_SUFFIX_PATTERN);+ if (!match) return undefined;++ const selected = match[1]?.toLowerCase();+ if (!selected) return undefined;+ if (Array.isArray(supportedValues) && supportedValues.length > 0 && !supportedValues.includes(selected)) {+ return undefined;+ }++ return selected;+}++export function getReasoningVariantBaseModelId(modelId: string) {+ return modelId.replace(EFFORT_SUFFIX_PATTERN, "");+}++export function getDefaultReasoningEffort(+ model: VscodeCatalogModel,+ supportedValues?: string[]+) {+ return inferSelectedReasoningEffort(model, supportedValues) || DEFAULT_REASONING_EFFORT;+}++export function buildReasoningConfigSchema(+ supportedValues: string[],+ defaultReasoningEffort: string+): VscodeModelConfigSchema {+ return {+ type: "object",+ properties: {+ reasoningEffort: {+ type: "string",+ title: "Reasoning effort",+ description: "Controls how much reasoning effort the model uses.",+ default: defaultReasoningEffort,+ enum: supportedValues,+ enumLabels: supportedValues.map(formatReasoningEffortLabel),+ enumDescriptions: supportedValues.map(describeReasoningEffort),+ },+ },+ };+}diff --git a/src/app/api/v1/vscode/raw/[token]/responses/route.ts b/src/app/api/v1/vscode/raw/[token]/responses/route.tsnew file mode 100644index 0000000000..f61e4eedab--- /dev/null+++ b/src/app/api/v1/vscode/raw/[token]/responses/route.ts@@ -0,0 +1,10 @@+import { POST as basePost, OPTIONS } from "@/app/api/v1/responses/route";+import { rewriteVscodeServiceTierRequest } from "@/app/api/v1/vscode/raw/[token]/serviceTierVariants";+import { withPathTokenApiKey } from "@/app/api/v1/vscode/raw/[token]/tokenizedRequest";++export { OPTIONS };++export async function POST(request: Request) {+ const authorizedRequest = withPathTokenApiKey(request);+ return basePost(await rewriteVscodeServiceTierRequest(authorizedRequest));+}diff --git a/src/app/api/v1/vscode/raw/[token]/route.ts b/src/app/api/v1/vscode/raw/[token]/route.tsnew file mode 100644index 0000000000..b0c61329a6--- /dev/null+++ b/src/app/api/v1/vscode/raw/[token]/route.ts@@ -0,0 +1,20 @@+import { CORS_HEADERS } from "@/shared/utils/cors";++type VscodeTokenParams = {+ token: string;+};++export async function OPTIONS() {+ return new Response(null, { headers: CORS_HEADERS });+}++export async function GET(+ request: Request,+ context?: { params: Promise<VscodeTokenParams> | VscodeTokenParams }+) {+ const modelsRoute = await import("@/app/api/v1/vscode/raw/[token]/models/route");+ const requestUrl = new URL(request.url);+ requestUrl.pathname = `${requestUrl.pathname.replace(/\/+$/, "")}/models`;+ const modelsRequest = new Request(requestUrl, request);+ return modelsRoute.GET(modelsRequest, context);+}\ No newline at end of filediff --git a/src/app/api/v1/vscode/raw/[token]/serviceTierVariants.ts b/src/app/api/v1/vscode/raw/[token]/serviceTierVariants.tsnew file mode 100644index 0000000000..538354a839--- /dev/null+++ b/src/app/api/v1/vscode/raw/[token]/serviceTierVariants.ts@@ -0,0 +1,190 @@+import { CODEX_FAST_TIER_DEFAULT_SUPPORTED_MODELS } from "@/lib/providers/codexFastTier";+import { normalizeServiceTierId, type ServiceTierId } from "@/shared/utils/serviceTierLabels";+import { resolveFamilyFirstPublishedModelId } from "@/app/api/v1/vscode/raw/[token]/familyFirstModelIds";++const SERVICE_TIER_VARIANT_PATTERN = /__tier_(priority|flex)$/i;+const SUPPORTED_VSCODE_SERVICE_TIERS: readonly ServiceTierId[] = ["priority", "flex"];++export type VscodeServiceTierModelLike = {+ id?: string;+ name?: string;+ root?: string;+ owned_by?: string;+};++export function parseVscodeServiceTierVariantModelId(modelId: string | null | undefined): {+ baseModelId: string;+ serviceTier?: ServiceTierId;+} {+ const rawModelId = typeof modelId === "string" ? modelId.trim() : "";+ if (!rawModelId) {+ return { baseModelId: "" };+ }++ const match = rawModelId.match(SERVICE_TIER_VARIANT_PATTERN);+ if (!match) {+ return { baseModelId: rawModelId };+ }++ const baseModelId = rawModelId.replace(SERVICE_TIER_VARIANT_PATTERN, "");+ const serviceTier = normalizeServiceTierId(match[1]);+ return serviceTier === "standard" ? { baseModelId } : { baseModelId, serviceTier };+}++export function stripVscodeServiceTierVariantModelId(modelId: string | null | undefined): string {+ return parseVscodeServiceTierVariantModelId(modelId).baseModelId;+}++export function isVscodeServiceTierVariantModelId(modelId: string | null | undefined): boolean {+ return Boolean(parseVscodeServiceTierVariantModelId(modelId).serviceTier);+}++export function getVscodeServiceTierVariantModelId(+ baseModelId: string,+ serviceTier: ServiceTierId+): string {+ if (serviceTier === "standard") {+ return baseModelId;+ }+ return `${baseModelId}__tier_${serviceTier}`;+}++function getRawModelId(model: VscodeServiceTierModelLike): string {+ return (model.id || model.name || model.root || "").trim();+}++function getModelProvider(model: VscodeServiceTierModelLike, baseModelId: string): string {+ const owner = typeof model.owned_by === "string" ? model.owned_by.trim().toLowerCase() : "";+ if (owner) {+ return owner;+ }+ const prefix = baseModelId.split("/")[0]?.trim().toLowerCase() || "";+ return prefix;+}++function supportsCodexServiceTierModel(baseModelId: string): boolean {+ const normalizedModel = (baseModelId.split("/").pop() || baseModelId).trim().toLowerCase();+ if (!normalizedModel) {+ return false;+ }++ return CODEX_FAST_TIER_DEFAULT_SUPPORTED_MODELS.some((candidate) => {+ const normalizedCandidate = candidate.trim().toLowerCase();+ return normalizedModel === normalizedCandidate || normalizedModel.startsWith(normalizedCandidate);+ });+}++export function supportsVscodeServiceTierVariants(model: VscodeServiceTierModelLike): boolean {+ const rawModelId = getRawModelId(model);+ if (!rawModelId) {+ return false;+ }++ const baseModelId = stripVscodeServiceTierVariantModelId(rawModelId);+ const provider = getModelProvider(model, baseModelId);+ if (provider !== "codex" && provider !== "cx") {+ return false;+ }++ return supportsCodexServiceTierModel(baseModelId);+}++function cloneModelIdentifiers<T extends VscodeServiceTierModelLike>(+ model: T,+ modelId: string+): T {+ return {+ ...model,+ ...(model.id ? { id: modelId } : {}),+ ...(model.name ? { name: modelId } : {}),+ ...(model.root ? { root: modelId } : {}),+ };+}++export function expandVscodeServiceTierModels<T extends VscodeServiceTierModelLike>(models: T[]): T[] {+ const expanded: T[] = [];++ for (const model of models) {+ const rawModelId = getRawModelId(model);+ if (!rawModelId) {+ expanded.push(model);+ continue;+ }++ const baseModelId = stripVscodeServiceTierVariantModelId(rawModelId);+ const baseModel = rawModelId === baseModelId ? model : cloneModelIdentifiers(model, baseModelId);+ expanded.push(baseModel as T);++ if (!supportsVscodeServiceTierVariants(model)) {+ continue;+ }++ for (const serviceTier of SUPPORTED_VSCODE_SERVICE_TIERS) {+ expanded.push(cloneModelIdentifiers(baseModel as T, getVscodeServiceTierVariantModelId(baseModelId, serviceTier)));+ }+ }++ return expanded;+}++export function getVscodeServiceTierVariantSuffix(serviceTier: ServiceTierId | undefined): string {+ if (serviceTier === "priority") {+ return "Fast";+ }+ if (serviceTier === "flex") {+ return "Flex";+ }+ return "Default";+}++export function resolveVscodeServiceTierRequest(body: Record<string, unknown>): Record<string, unknown> {+ const rawModelId = typeof body.model === "string" ? body.model.trim() : "";+ if (!rawModelId) {+ return body;+ }++ const resolvedModelId = resolveFamilyFirstPublishedModelId(rawModelId);++ const { baseModelId, serviceTier } = parseVscodeServiceTierVariantModelId(resolvedModelId);+ if (!serviceTier) {+ if (resolvedModelId === rawModelId) {+ return body;+ }++ return {+ ...body,+ model: resolvedModelId,+ };+ }++ return {+ ...body,+ model: baseModelId,+ ...(body.service_tier === undefined ? { service_tier: serviceTier } : {}),+ };+}++export async function rewriteVscodeServiceTierRequest(request: Request): Promise<Request> {+ if (request.method !== "POST") {+ return request;+ }++ const body = await request.clone().json().catch(() => null);+ if (!body || typeof body !== "object" || Array.isArray(body)) {+ return request;+ }++ const rewrittenBody = resolveVscodeServiceTierRequest(body as Record<string, unknown>);+ if (rewrittenBody === body) {+ return request;+ }++ const headers = new Headers(request.headers);+ headers.delete("content-length");++ return new Request(request.url, {+ method: request.method,+ headers,+ body: JSON.stringify(rewrittenBody),+ });+}diff --git a/src/app/api/v1/vscode/raw/[token]/tokenizedRequest.ts b/src/app/api/v1/vscode/raw/[token]/tokenizedRequest.tsnew file mode 100644index 0000000000..d390cadcd5--- /dev/null+++ b/src/app/api/v1/vscode/raw/[token]/tokenizedRequest.ts@@ -0,0 +1,50 @@+function inferTokenFromVscodePath(request: Request) {+ try {+ const url = new URL(request.url, "http://localhost");+ const segments = url.pathname+ .split("/")+ .map((segment) => segment.trim())+ .filter(Boolean);++ const vscodeIndex = segments.indexOf("vscode");+ if (vscodeIndex === -1) return null;++ const candidate = segments[vscodeIndex + 1];+ if (!candidate || candidate === "raw" || candidate === "combos") {+ const nestedCandidate = segments[vscodeIndex + 2];+ return nestedCandidate ? decodeURIComponent(nestedCandidate) : null;+ }++ return decodeURIComponent(candidate);+ } catch {+ return null;+ }+}++export function withPathTokenApiKey(request: Request, token?: string) {+ const resolvedToken = token || inferTokenFromVscodePath(request);+ if (!resolvedToken) return request;++ const headers = new Headers(request.headers);++ if (!headers.has("x-api-key")) {+ headers.set("x-api-key", resolvedToken);+ }++ if (!headers.has("authorization")) {+ headers.set("authorization", `Bearer ${resolvedToken}`);+ }++ const method = request.method;+ const init: RequestInit & { duplex?: "half" } = {+ method,+ headers,+ };++ if (method !== "GET" && method !== "HEAD") {+ init.body = request.body;+ init.duplex = "half";+ }++ return new Request(request.url, init);+}\ No newline at end of filediff --git a/src/app/api/v1/vscode/raw/[token]/v1/chat/completions/route.ts b/src/app/api/v1/vscode/raw/[token]/v1/chat/completions/route.tsnew file mode 100644index 0000000000..3a7abb6ad8--- /dev/null+++ b/src/app/api/v1/vscode/raw/[token]/v1/chat/completions/route.ts@@ -0,0 +1,10 @@+import { POST as basePost, OPTIONS } from "@/app/api/v1/chat/completions/route";+import { rewriteVscodeServiceTierRequest } from "@/app/api/v1/vscode/raw/[token]/serviceTierVariants";+import { withPathTokenApiKey } from "@/app/api/v1/vscode/raw/[token]/tokenizedRequest";++export { OPTIONS };++export async function POST(request: Request) {+ const authorizedRequest = withPathTokenApiKey(request);+ return basePost(await rewriteVscodeServiceTierRequest(authorizedRequest));+}diff --git a/src/app/api/v1/vscode/raw/[token]/v1/models/route.ts b/src/app/api/v1/vscode/raw/[token]/v1/models/route.tsnew file mode 100644index 0000000000..733636c819--- /dev/null+++ b/src/app/api/v1/vscode/raw/[token]/v1/models/route.ts@@ -0,0 +1 @@+export { GET, OPTIONS } from "@/app/api/v1/vscode/raw/[token]/models/route";\ No newline at end of filediff --git a/src/domain/types.ts b/src/domain/types.tsindex a2dc1b3ade..9e147758f0 100644--- a/src/domain/types.ts+++ b/src/domain/types.ts@@ -28,6 +28,12 @@* @property {string} [email] - Email (for oauth auth)* @property {string} [baseUrl] - Custom base URL* @property {boolean} [rateLimitProtection] - Whether rate limit protection is enabled+ * @property {object} [rateLimitOverrides] - Per-connection rate limit overrides+ * @property {number} [rateLimitOverrides.rpm] - Requests per minute limit+ * @property {number} [rateLimitOverrides.tpm] - Tokens per minute limit+ * @property {number} [rateLimitOverrides.tpd] - Tokens per day limit+ * @property {number} [rateLimitOverrides.minTime] - Minimum ms between requests+ * @property {number} [rateLimitOverrides.maxConcurrent] - Max concurrent requests* @property {string} createdAt - ISO timestamp* @property {string} updatedAt - ISO timestamp*/diff --git a/src/i18n/messages/en.json b/src/i18n/messages/en.jsonindex 8864863613..f677d1f660 100644--- a/src/i18n/messages/en.json+++ b/src/i18n/messages/en.json@@ -3052,6 +3052,15 @@"apiEndpointsSearchPlaceholder": "Search endpoints...","apiEndpointsRequiresAuth": "Requires auth","apiEndpointsNoMatch": "No endpoints match your filter",+ "vscodeAliasTitle": "VS Code Token Alias",+ "vscodeAliasDescriptionReady": "Ready-to-paste compatibility URLs using the /api/v1/vscode/TOKEN/... endpoint.",+ "vscodeAliasDescriptionError": "Showing placeholder URLs because CLI keys could not be loaded in this session.",+ "vscodeAliasDescriptionLoading": "Loading CLI keys. Placeholder URLs are shown until a key is available.",+ "vscodeAliasDescriptionPlaceholder": "Showing placeholder URLs. Create or activate an API key in CLI Tools to replace TOKEN.",+ "vscodeAliasManage": "CLI Tools",+ "vscodeAliasBaseLabel": "VS Code base",+ "vscodeAliasModelsLabel": "VS Code models",+ "vscodeAliasChatLabel": "VS Code chat","localServer": "Local Server","cloudOmniroute": "Cloud OmniRoute","copyUrl": "Copy URL",@@ -3826,6 +3835,7 @@},"providers": {"title": "Providers",+ "Account Deactivated": "Account Deactivated","allProviders": "All Providers","audioProviders": "Audio Providers","showFreeOnly": "Free only",@@ -3864,9 +3874,25 @@"testAllFree": "Test all Free connections","testAllApiKey": "Test all API Key connections","testAllCompatible": "Test all Compatible connections",+ "testAllModels": "Test all models",+ "testAllModelsConfirm": "Test all visible models? Failed models will be hidden if auto-hide is enabled.",+ "testingAllModels": "Testing {done}/{total}...",+ "testAllResults": "{ok} of {total} models working",+ "noModelsToTest": "No models match the current filter",+ "showAllModels": "All",+ "showVisibleOnly": "Visible only",+ "showHiddenOnly": "Hidden only",+ "filterByVisibility": "Filter by visibility",+ "autoHideFailed": "Auto-hide failed models","connected": "{count} Connected","errorCount": "{count} Error ({code})","errorCountNoCode": "{count} Error",+ "testAllCompleted": "Tested {total} models: {ok} OK, {failed} failed",+ "modelAutoHidden": "Model {model} auto-hidden (test failed)",+ "filterAll": "All",+ "filterVisible": "Visible only",+ "filterHidden": "Hidden only",+ "modelsHiddenCount": "{count} hidden","warningCount": "{count} Warning","noConnections": "No connections","expiredBadge": "Expired",@@ -3973,6 +3999,8 @@"batchActivateSuccess": "Activated {count} connection(s)","batchDeactivateSuccess": "Deactivated {count} connection(s)","failedSetAlias": "Failed to set alias",+ "setAliasSuccess": "Alias {alias} set",+ "deleteAliasSuccess": "Alias {alias} deleted","failedSaveConnection": "Failed to save connection","failedSaveConnectionRetry": "Failed to save connection. Please try again.","failedRetestConnection": "Failed to retest connection",@@ -4006,6 +4034,8 @@"connectionCount": "{count} connection(s)","fetchingModels": "Fetching available models...","failedFetchModels": "Failed to fetch models",+ "fetchModelsSuccess": "Found {count} new models",+ "fetchModelsFailed": "Could not auto-fetch models (you can retry from settings)","noModelsFound": "No models found","importFailed": "Import failed","noNewModelsAdded": "No new models were added.",@@ -4014,6 +4044,10 @@"importingModelsTitle": "Importing Models","copyModel": "Copy model","filterModels": "Filter models...",+ "testAllRateLimited": "Rate limit reached, stopped early",+ "hideFailedAuto": "Auto-hide failed models",+ "selectAllModels": "Select all",+ "hideAllModels": "Hide all","modelsActive": "Active","showModel": "Show model","hideModel": "Hide model",@@ -4022,6 +4056,9 @@"rateLimitUnprotected": "Unprotected","enableRateLimitProtection": "Click to enable rate limit protection","disableRateLimitProtection": "Click to disable rate limit protection",+ "testAllProgress": "Tested {done}/{total}",+ "testAllFailedHidden": "{count} failed models hidden",+ "testAllDone": "All models tested","productionKey": "Production Key","enterNewApiKey": "Enter new API key","codexApplyModalTitle": "Apply to Local Codex",@@ -4097,6 +4134,8 @@"errorTypeNetworkError": "Network error","errorTypeTestUnsupported": "Test unsupported","errorTypeUpstreamError": "Upstream error",+ "errorTypeCreditsExhausted": "No credits",+ "errorTypeBanned": "403 Banned","proxySourceGlobal": "Global","proxySourceProvider": "Provider","proxySourceKey": "Key",@@ -4181,7 +4220,6 @@"email": "Email","healthCheckMinutes": "Health Check (min)","healthCheckHint": "Proactive token refresh interval. 0 = disabled.",- "selectAllModels": "Select all","deselectAllModels": "Deselect all","modelsActiveCount": "{active}/{total} active","noModelsMatch": "No models match \"{filter}\"",@@ -4458,6 +4496,17 @@"personalAccessTokenLabel": "Personal Access Token Label","qoderPatHint": "Qoder Pat Hint","qoderPatPlaceholder": "Qoder Pat Placeholder",+ "rateLimitOverridesSection": "Rate Limit Overrides",+ "rateLimitOverridesMaxConcurrentHint": "Max concurrent requests override for this connection. Overrides the account-level cap.",+ "rateLimitOverridesMaxConcurrentLabel": "Max Concurrent (Rate Limit)",+ "rateLimitOverridesMinTimeHint": "Minimum time (ms) between requests. Overrides the default rate limiter delay.",+ "rateLimitOverridesMinTimeLabel": "Min Interval (ms)",+ "rateLimitOverridesRpmHint": "Max requests per minute for this connection. Overrides the provider default.",+ "rateLimitOverridesRpmLabel": "RPM (Requests/min)",+ "rateLimitOverridesTpdHint": "Max tokens per day for this connection. Overrides the provider default.",+ "rateLimitOverridesTpdLabel": "TPD (Tokens/day)",+ "rateLimitOverridesTpmHint": "Max tokens per minute for this connection. Overrides the provider default.",+ "rateLimitOverridesTpmLabel": "TPM (Tokens/min)","refreshOauthTokenTitle": "Refresh Oauth Token Title","regionHint": "Region Hint","regionLabel": "Region Label",@@ -4919,8 +4968,53 @@"evictions": "Evictions","loadingCacheStats": "Loading cache stats…","globalProxy": "Global Proxy",- "globalProxyDesc": "Configure a global outbound proxy for all API calls. Individual providers, combos, and keys can override this.",- "noGlobalProxy": "No global proxy configured",+ "proxyPool": "Proxy Pool",+ "freePool": "Free Pool",+ "proxyDocumentation": "Proxy Documentation",+ "proxyGlobalConfigTab": "Global Config",+ "proxyPoolTab": "Proxy Pool",+ "freePoolTab": "Free Pool",+ "proxyDocumentationTab": "Documentation",+ "proxyDocumentationScopeTitle": "Proxy scope resolution",+ "proxyDocumentationScopeDescBefore": "OmniRoute resolves the outbound proxy in priority order: ",+ "proxyDocumentationScopeOrder": "combo → account → provider → global",+ "proxyDocumentationScopeDescAfter": ". The most specific scope wins.",+ "proxyDocumentationAddTitle": "Adding a custom proxy",+ "proxyDocumentationAddDescBefore": "Go to the ",+ "proxyDocumentationAddDescMiddle": " tab → click ",+ "proxyDocumentationAddCta": "+ Add proxy",+ "proxyDocumentationAddDescAfter": ". Fill in type (http/https/socks5), host, and port. Optionally assign it to a scope.",+ "proxyDocumentationBulkTitle": "Bulk import format",+ "proxyDocumentationBulkDesc": "Pipe-delimited fields:",+ "proxyDocumentationSocks5DescBefore": "SOCKS5 proxies are disabled by default. Set",+ "proxyDocumentationFreePoolDesc": "The Free Pool tab aggregates proxies from 1proxy, Proxifly, and IPLocate. Use ⊕ to test and promote a proxy to your registry. Only proxies that pass the connectivity test are added.",+ "proxyDocumentationVercelRelayDescBefore": "The Vercel Relay is an outbound edge relay — not an inbound tunnel. Deploying one sends LLM API calls through Vercel's dynamic IPs, bypassing datacenter geo-blocks and rate limits. The relay is protected by a generated secret header",+ "proxyDocumentationVercelRelayDescAfter": "Your Vercel token is used only during deploy and is never stored.",+ "vercelRelayTokenRequired": "Token is required",+ "vercelRelayDeployFailed": "Deploy failed",+ "vercelRelayTokenHint": "Token is used only during deploy — never stored.",+ "proxyFreePoolFilterProtocol": "Filter by protocol",+ "proxyFreePoolProtocol": "Protocol",+ "proxyFreePoolCountryPlaceholder": "Country (e.g. US)",+ "proxyFreePoolFilterCountry": "Filter by country",+ "proxyFreePoolMinQualityPlaceholder": "Min quality",+ "proxyFreePoolMinQualityLabel": "Minimum quality score",+ "proxyFreePoolSyncAll": "Sync All",+ "proxyFreePoolTotal": "Total",+ "proxyFreePoolInPool": "In pool",+ "proxyFreePoolAvgQuality": "Avg quality",+ "proxyFreePoolSelected": "{count} selected",+ "proxyFreePoolAddSelected": "Add selected to pool",+ "proxyFreePoolAddVisible": "Add all visible to pool",+ "proxyFreePoolSource": "Source",+ "proxyFreePoolHostPort": "Host:Port",+ "proxyFreePoolType": "Type",+ "proxyFreePoolCountry": "Country",+ "proxyFreePoolQuality": "Quality",+ "proxyFreePoolLatency": "Latency",+ "proxyFreePoolEmpty": "No proxies found. Click Sync All to fetch from sources.",+ "close": "Close",+ "cancel": "Cancel","globalLabel": "Global","configure": "Configure","globalSystemPrompt": "Global System Prompt",@@ -5738,11 +5832,7 @@"vercelRelayProjectNameLabel": "Vercel Project Name","vercelRelayFreeTierNote": "Relays are lightweight proxy endpoints deployed on Vercel's free tier to bypass local network/region limitations.","vercelRelayDeploying": "Deploying...",- "vercelRelayDeploy": "Deploy",- "proxyGlobalConfigTab": "Global Config",- "proxyPoolTab": "Proxy Pool",- "freePoolTab": "Free Pool",- "proxyDocumentationTab": "Documentation"+ "vercelRelayDeploy": "Deploy"},"contextRtk": {"title": "RTK Engine",@@ -7854,7 +7944,7 @@"title": "Quota Sharing","description": "Share provider quotas across API keys with % limits","newPool": "New pool",- "betaTitle": "Beta — UI preview.",+ "betaTitle": "Beta","betaDescription": "Configuration is saved in localStorage (not yet persisted on the server). Per-request cap enforcement is not yet wired into the proxy pipeline. This screen lets you design and visualize the quota split; real enforcement will land in a future iteration with DB persistence and upstream call interception.","kpiActivePools": "Active pools","kpiKeysAllocated": "Keys allocated",@@ -7976,7 +8066,6 @@"endpointsAnthropicNote": "Anthropic-native","endpointsResponsesNote": "OpenAI Responses — codex/github","endpointsWsNote": "WebSocket — codex only",- "betaTitle": "Beta","betaText": "Quota Share is functional but bugs are expected. Found one? Please report it.","betaReportLink": "Report an issue","deleteGroup": "Delete group",diff --git a/src/i18n/messages/pt-BR.json b/src/i18n/messages/pt-BR.jsonindex c22aa6c8e6..b7783e797a 100644--- a/src/i18n/messages/pt-BR.json+++ b/src/i18n/messages/pt-BR.json@@ -3159,7 +3159,16 @@"tierAlwaysProtected": "Sempre Protegido","tierPublic": "Público","hideInternal": "Ocultar Internos",- "showInternal": "Mostrar Internos"+ "showInternal": "Mostrar Internos",+ "vscodeAliasTitle": "Alias de Token do VS Code",+ "vscodeAliasDescriptionReady": "URLs de compatibilidade prontas para colar usando o endpoint /api/v1/vscode/TOKEN/... .",+ "vscodeAliasDescriptionError": "Mostrando URLs com placeholder porque as chaves de CLI não puderam ser carregadas nesta sessão.",+ "vscodeAliasDescriptionLoading": "Carregando chaves de CLI. As URLs com placeholder serão mostradas até que uma chave esteja disponível.",+ "vscodeAliasDescriptionPlaceholder": "Mostrando URLs com placeholder. Crie ou ative uma chave de API em CLI Tools para substituir TOKEN.",+ "vscodeAliasManage": "CLI Tools",+ "vscodeAliasBaseLabel": "Base do VS Code",+ "vscodeAliasModelsLabel": "Modelos do VS Code",+ "vscodeAliasChatLabel": "Chat do VS Code"},"endpointOptions": {"speech": "Speech",@@ -4635,7 +4644,6 @@"proxySourceGlobal": "Global","proxySourceProvider": "Provedor","proxySourceKey": "Chave",- "proxyConfiguredBySource": "Proxy ({source}): {host}","autoPriority": "Auto: {priority}","proxy": "Proxy","retestAuthentication": "Retestar autenticação",@@ -5330,7 +5338,7 @@"title": "Compartilhamento de Cota","description": "Compartilhe cotas de provedores entre API keys com limites %","newPool": "Novo pool",- "betaTitle": "Beta — UI preview.",+ "betaTitle": "Beta","betaDescription": "A configuração é salva em localStorage (ainda não persistida no servidor). A aplicação dos caps por request ainda não está conectada ao pipeline da proxy. Esta tela permite desenhar e visualizar a divisão de cota; a aplicação real virá em uma próxima iteração com persistência no banco e interceptação na chamada upstream.","kpiActivePools": "Pools ativos","kpiKeysAllocated": "Keys alocadas",@@ -5452,7 +5460,6 @@"endpointsAnthropicNote": "nativo Anthropic","endpointsResponsesNote": "OpenAI Responses — codex/github","endpointsWsNote": "WebSocket — somente codex",- "betaTitle": "Beta","betaText": "O Quota Share está funcional, mas bugs são esperados. Encontrou um? Reporte, por favor.","betaReportLink": "Abrir uma issue","deleteGroup": "Excluir grupo",@@ -6775,7 +6782,50 @@"proxyGlobalConfigTab": "Configuração Global","proxyPoolTab": "Pool de Proxy","freePoolTab": "Pool Gratuito",- "proxyDocumentationTab": "Documentação"+ "proxyDocumentationTab": "Documentação",+ "proxyPool": "Pool de Proxies",+ "freePool": "Pool Gratuito",+ "proxyDocumentation": "Documentação de Proxy",+ "proxyDocumentationScopeTitle": "Resolução de escopo de proxy",+ "proxyDocumentationScopeDescBefore": "O OmniRoute resolve o proxy de saída na seguinte ordem de prioridade: ",+ "proxyDocumentationScopeOrder": "combo → conta → provedor → global",+ "proxyDocumentationScopeDescAfter": ". O escopo mais específico vence.",+ "proxyDocumentationAddTitle": "Adicionando um proxy personalizado",+ "proxyDocumentationAddDescBefore": "Vá para a aba ",+ "proxyDocumentationAddDescMiddle": " → clique em ",+ "proxyDocumentationAddCta": "+ Adicionar proxy",+ "proxyDocumentationAddDescAfter": ". Preencha tipo (http/https/socks5), host e porta. Opcionalmente, atribua-o a um escopo.",+ "proxyDocumentationBulkTitle": "Formato de importação em massa",+ "proxyDocumentationBulkDesc": "Campos delimitados por pipe:",+ "proxyDocumentationSocks5DescBefore": "Proxies SOCKS5 vêm desativados por padrão. Defina",+ "proxyDocumentationFreePoolDesc": "A aba Pool Gratuito agrega proxies do 1proxy, Proxifly e IPLocate. Use ⊕ para testar e promover um proxy ao seu registro. Somente proxies que passarem no teste de conectividade serão adicionados.",+ "proxyDocumentationVercelRelayDescBefore": "O Vercel Relay é um relay de borda de saída, não um túnel de entrada. Fazer deploy dele envia chamadas de API de LLM pelos IPs dinâmicos da Vercel, contornando bloqueios geográficos de datacenter e limites de taxa. O relay é protegido por um header secreto gerado",+ "proxyDocumentationVercelRelayDescAfter": "Seu token da Vercel é usado apenas durante o deploy e nunca é armazenado.",+ "vercelRelayTokenRequired": "Token obrigatório",+ "vercelRelayDeployFailed": "Falha no deploy",+ "vercelRelayTokenHint": "O token é usado apenas durante o deploy e nunca é armazenado.",+ "proxyFreePoolFilterProtocol": "Filtrar por protocolo",+ "proxyFreePoolProtocol": "Protocolo",+ "proxyFreePoolCountryPlaceholder": "País (ex.: US)",+ "proxyFreePoolFilterCountry": "Filtrar por país",+ "proxyFreePoolMinQualityPlaceholder": "Qualidade mín.",+ "proxyFreePoolMinQualityLabel": "Pontuação mínima de qualidade",+ "proxyFreePoolSyncAll": "Sincronizar tudo",+ "proxyFreePoolTotal": "Total",+ "proxyFreePoolInPool": "No pool",+ "proxyFreePoolAvgQuality": "Qualidade média",+ "proxyFreePoolSelected": "{count} selecionados",+ "proxyFreePoolAddSelected": "Adicionar selecionados ao pool",+ "proxyFreePoolAddVisible": "Adicionar todos os visíveis ao pool",+ "proxyFreePoolSource": "Origem",+ "proxyFreePoolHostPort": "Host:Porta",+ "proxyFreePoolType": "Tipo",+ "proxyFreePoolCountry": "País",+ "proxyFreePoolQuality": "Qualidade",+ "proxyFreePoolLatency": "Latência",+ "proxyFreePoolEmpty": "Nenhum proxy encontrado. Clique em Sincronizar tudo para buscar nas fontes.",+ "close": "Fechar",+ "cancel": "Cancelar"},"sidebar": {"home": "Início",diff --git a/src/instrumentation-node.ts b/src/instrumentation-node.tsindex 7e96e9ab93..965b857a8c 100755--- a/src/instrumentation-node.ts+++ b/src/instrumentation-node.ts@@ -237,5 +237,13 @@ export async function registerNodejs(): Promise<void> {const msg = err instanceof Error ? err.message : String(err);console.warn("[STARTUP] Embed WS proxy failed to start (non-fatal):", msg);}++ try {+ const { autoRefreshDaemon } = await import("@/open-sse/services/autoRefreshDaemon");+ autoRefreshDaemon.start();+ } catch (err: unknown) {+ const msg = err instanceof Error ? err.message : String(err);+ console.warn("[STARTUP] Auto-refresh daemon failed to start (non-fatal):", msg);+ }}}diff --git a/src/lib/api/modelTestRunner.ts b/src/lib/api/modelTestRunner.tsnew file mode 100644index 0000000000..7c7ba5a093--- /dev/null+++ b/src/lib/api/modelTestRunner.ts@@ -0,0 +1,335 @@+import { randomUUID } from "node:crypto";+import { POST as postChatCompletion } from "@/app/api/v1/chat/completions/route";+import { handleValidatedEmbeddingRequestBody } from "@/app/api/v1/embeddings/route";+import { POST as postRerank } from "@/app/api/v1/rerank/route";+import { buildComboTestRequestBody, extractComboTestResponseText } from "@/lib/combos/testHealth";+import { getCustomModels } from "@/lib/localDb";+import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error";+import { withRateLimit } from "@omniroute/open-sse/services/rateLimitManager";++const INTERNAL_ORIGIN = "http://omniroute.internal";+const DEFAULT_TEST_TIMEOUT_MS = 10_000;++function asRecord(value: unknown): Record<string, unknown> {+ return value && typeof value === "object" && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : {};+}++function getErrorMessage(error: unknown): string {+ return sanitizeErrorMessage(error) || "Unknown error";+}++function getErrorName(error: unknown): string {+ return error instanceof Error ? error.name : "";+}++function extractProviderErrorMessage(body: unknown, fallback: string) {+ const record = asRecord(body);+ const error = record.error;+ if (typeof error === "string" && error.trim()) return error;++ const errorRecord = asRecord(error);+ const message = errorRecord.message;+ return typeof message === "string" && message.trim() ? message : fallback;+}++function stripFirstSegment(modelId: string): string | null {+ const slashIdx = modelId.indexOf("/");+ return slashIdx > 0 ? modelId.slice(slashIdx + 1) : null;+}++async function findCustomModelMetadata(providerId: string, modelId: string) {+ try {+ const customModels = await getCustomModels(providerId);+ if (!Array.isArray(customModels)) return null;++ const candidates = new Set([modelId]);+ const stripped = stripFirstSegment(modelId);+ if (stripped) candidates.add(stripped);+ if (modelId.startsWith(`${providerId}/`)) candidates.add(modelId.slice(providerId.length + 1));++ return (+ customModels.find(+ (model: any) => typeof model?.id === "string" && candidates.has(model.id)+ ) || null+ );+ } catch {+ return null;+ }+}++function buildInternalChatRequest(testBody: Record<string, unknown>, signal: AbortSignal) {+ return new Request(`${INTERNAL_ORIGIN}/v1/chat/completions`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ // Reuse the existing strict-mode internal bypass for live health checks.+ "X-Internal-Test": "combo-health-check",+ "X-OmniRoute-No-Cache": "true",+ "X-Request-Id": `model-test-${randomUUID()}`,+ },+ body: JSON.stringify(testBody),+ signal,+ });+}++function buildInternalRerankRequest(testBody: Record<string, unknown>, signal: AbortSignal) {+ return new Request(`${INTERNAL_ORIGIN}/v1/rerank`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ "X-Internal-Test": "combo-health-check",+ "X-OmniRoute-No-Cache": "true",+ "X-Request-Id": `model-test-${randomUUID()}`,+ },+ body: JSON.stringify(testBody),+ signal,+ });+}++export function detectTestKind(modelStr: string, customModel: any) {+ const supportedEndpoints = Array.isArray(customModel?.supportedEndpoints)+ ? customModel.supportedEndpoints+ : [];+ const apiFormat = typeof customModel?.apiFormat === "string" ? customModel.apiFormat : "";+ const lowerModel = modelStr.toLowerCase();+ const isRerank =+ apiFormat === "rerank" ||+ supportedEndpoints.includes("rerank") ||+ lowerModel.includes("rerank");+ const isEmbedding =+ !isRerank &&+ (apiFormat === "embeddings" ||+ supportedEndpoints.includes("embeddings") ||+ lowerModel.includes("embedding") ||+ lowerModel.includes("bge-") ||+ lowerModel.includes("text-embed") ||+ lowerModel.includes("jina-clip") ||+ lowerModel.includes("colbert"));+ return { isRerank, isEmbedding };+}++/**+ * Parse a Retry-After header value (seconds-as-number or HTTP-date) into seconds.+ * Returns undefined if the value is missing or unparseable.+ */+export function parseRetryAfterHeader(value: string | null | undefined): number | undefined {+ if (typeof value !== "string") return undefined;+ const trimmed = value.trim();+ if (!trimmed) return undefined;++ const num = Number(trimmed);+ if (Number.isFinite(num) && num >= 0) {+ return Math.ceil(num);+ }++ const ms = Date.parse(trimmed);+ if (Number.isFinite(ms)) {+ return Math.max(0, Math.ceil((ms - Date.now()) / 1000));+ }++ return undefined;+}++export interface RunSingleModelTestOptions {+ providerId: string;+ modelId: string;+ connectionId?: string;+ timeoutMs?: number;+}++export interface SingleModelTestResult {+ modelId: string;+ status: "ok" | "error" | "rate_limited";+ latencyMs: number;+ responseText?: string;+ statusCode?: number;+ httpStatus: number;+ error?: string;+ rateLimited?: boolean;+ isTimeout?: boolean;+ retryAfter?: number;+}++/**+ * Run a single model test. When `connectionId` is provided, wraps the+ * upstream call with `withRateLimit` (Bottleneck). Returns a plain+ * `SingleModelTestResult` (not an HTTP Response) so the single-test and+ * batch-test endpoints can format it differently.+ */+export async function runSingleModelTest(+ options: RunSingleModelTestOptions+): Promise<SingleModelTestResult> {+ const { providerId, modelId, connectionId, timeoutMs = DEFAULT_TEST_TIMEOUT_MS } = options;++ let fullModelStr = modelId;+ if (!fullModelStr.includes("/")) {+ fullModelStr = `${providerId}/${modelId}`;+ }++ const startTime = Date.now();+ const customModel = await findCustomModelMetadata(providerId, fullModelStr);+ const { isRerank, isEmbedding } = detectTestKind(fullModelStr, customModel);++ const testBody = isRerank+ ? {+ model: fullModelStr,+ query: "What is OmniRoute?",+ documents: [+ "OmniRoute routes AI requests across configured providers.",+ "This document is unrelated to the test query.",+ ],+ top_n: 1,+ return_documents: false,+ }+ : buildComboTestRequestBody(fullModelStr, isEmbedding);++ // Per-model AbortController. We track whether the timeout fired so we can+ // distinguish "rate-limit queue aborted" (withRateLimit threw AbortError+ // with no timeout) from "timeout fired and aborted withRateLimit".+ const controller = new AbortController();+ let timedOut = false;+ const timeoutHandle = setTimeout(() => {+ timedOut = true;+ controller.abort();+ }, timeoutMs);++ const runInner = async (signal: AbortSignal): Promise<Response> => {+ if (isEmbedding) {+ return handleValidatedEmbeddingRequestBody(+ testBody as Record<string, unknown> & { model: string }+ );+ }+ if (isRerank) {+ return postRerank(buildInternalRerankRequest(testBody, signal));+ }+ return postChatCompletion(buildInternalChatRequest(testBody, signal));+ };++ let res: Response;+ try {+ if (connectionId) {+ res = await withRateLimit(+ providerId,+ connectionId,+ fullModelStr,+ (signal) => runInner(signal),+ controller.signal+ );+ } else {+ res = await runInner(controller.signal);+ }+ } catch (error: unknown) {+ clearTimeout(timeoutHandle);+ const latencyMs = Date.now() - startTime;+ const errorName = getErrorName(error);+ if (errorName === "AbortError") {+ if (timedOut) {+ return {+ modelId: fullModelStr,+ status: "error",+ latencyMs,+ httpStatus: 500,+ error: `Timeout (${Math.round(timeoutMs / 1000)}s)`,+ isTimeout: true,+ };+ }+ // AbortError without timeout = withRateLimit queue rejection / abort.+ // Surface as rate_limited so the batch endpoint can stop the loop.+ return {+ modelId: fullModelStr,+ status: "rate_limited",+ latencyMs,+ httpStatus: 429,+ error: "Rate limited (queue aborted)",+ rateLimited: true,+ };+ }+ return {+ modelId: fullModelStr,+ status: "error",+ latencyMs,+ httpStatus: 500,+ error: getErrorMessage(error),+ };+ }+ clearTimeout(timeoutHandle);++ const latencyMs = Date.now() - startTime;++ if (res.status === 429) {+ const retryAfter = parseRetryAfterHeader(res.headers.get("retry-after"));++ let errorMsg = "Rate limited";+ try {+ const errBody = await res.json();+ errorMsg = extractProviderErrorMessage(errBody, res.statusText || errorMsg);+ } catch {+ errorMsg = res.statusText || errorMsg;+ }+ return {+ modelId: fullModelStr,+ status: "rate_limited",+ latencyMs,+ statusCode: res.status,+ httpStatus: res.status,+ error: errorMsg,+ rateLimited: true,+ ...(retryAfter !== undefined ? { retryAfter } : {}),+ };+ }++ if (res.ok) {+ let responseBody = null;+ try {+ responseBody = await res.json();+ } catch {+ responseBody = null;+ }++ const responseText = extractComboTestResponseText(responseBody);+ if (isRerank) {+ return {+ modelId: fullModelStr,+ status: "ok",+ latencyMs,+ httpStatus: 200,+ responseText: "[Rerank completed successfully]",+ };+ }+ if (!responseText && !isEmbedding) {+ return {+ modelId: fullModelStr,+ status: "error",+ latencyMs,+ statusCode: res.status,+ httpStatus: 400,+ error: "Provider returned HTTP 200 but no text content.",+ };+ }+ return {+ modelId: fullModelStr,+ status: "ok",+ latencyMs,+ httpStatus: 200,+ responseText,+ };+ }++ let errorMsg = "";+ try {+ const errBody = await res.json();+ errorMsg = extractProviderErrorMessage(errBody, res.statusText);+ } catch {+ errorMsg = res.statusText;+ }+ return {+ modelId: fullModelStr,+ status: "error",+ latencyMs,+ statusCode: res.status,+ httpStatus: res.status,+ error: errorMsg,+ };+}diff --git a/src/lib/api/requireManagementAuth.ts b/src/lib/api/requireManagementAuth.tsindex d8b0beb0f7..c0588ff1ae 100644--- a/src/lib/api/requireManagementAuth.ts+++ b/src/lib/api/requireManagementAuth.ts@@ -34,7 +34,9 @@ export async function requireManagementAuth(request: Request): Promise<Responsereturn null;}- const apiKey = extractApiKey(request);+ // Management auth never honours a URL-borne credential (header-only) — a token+ // in the path/query must not authenticate a management route. See #3300 follow-up.+ const apiKey = extractApiKey(request, { allowUrl: false });if (apiKey) {let meta: Awaited<ReturnType<typeof getApiKeyMetadata>>;try {diff --git a/src/lib/db/core.ts b/src/lib/db/core.tsindex 02b9982f27..a365c6ff74 100644--- a/src/lib/db/core.ts+++ b/src/lib/db/core.ts@@ -204,6 +204,7 @@ const SCHEMA_SQL = `"group" TEXT,max_concurrent INTEGER,quota_window_thresholds_json TEXT,+ rate_limit_overrides_json TEXT,created_at TEXT NOT NULL,updated_at TEXT NOT NULL);@@ -540,6 +541,10 @@ function ensureProviderConnectionsColumns(db: SqliteDatabase) {db.exec("ALTER TABLE provider_connections ADD COLUMN quota_window_thresholds_json TEXT");console.log("[DB] Added provider_connections.quota_window_thresholds_json column");}+ if (!columnNames.has("rate_limit_overrides_json")) {+ db.exec("ALTER TABLE provider_connections ADD COLUMN rate_limit_overrides_json TEXT");+ console.log("[DB] Added provider_connections.rate_limit_overrides_json column");+ }db.exec("CREATE INDEX IF NOT EXISTS idx_pc_max_concurrent ON provider_connections(provider, max_concurrent)");diff --git a/src/lib/db/models.ts b/src/lib/db/models.tsindex 7fb5214c67..07a3a58886 100644--- a/src/lib/db/models.ts+++ b/src/lib/db/models.ts@@ -1034,6 +1034,44 @@ export function getModelIsHidden(providerId: string, modelId: string): boolean {return Boolean(co?.isHidden);}+/**+ * Persist the hidden flag for a model. Stores the override on the custom-model+ * row when one exists, otherwise on the compat-override list. Setting+ * `hidden = false` is a no-op when the model is already visible.+ */+export function setModelIsHidden(providerId: string, modelId: string, hidden: boolean): void {+ const customRow = getCustomModelRow(providerId, modelId);+ if (customRow) {+ if (hidden) {+ updateCustomModel(providerId, modelId, { isHidden: true });+ } else if (Object.prototype.hasOwnProperty.call(customRow, "isHidden")) {+ updateCustomModel(providerId, modelId, { isHidden: false });+ }+ return;+ }++ const list = readCompatList(providerId);+ const idx = list.findIndex((e) => e.id === modelId);+ if (hidden) {+ const prev = idx >= 0 ? list[idx] : { id: modelId };+ const next: ModelCompatOverride = { ...prev, id: modelId, isHidden: true };+ if (idx >= 0) list[idx] = next;+ else list.push(next);+ writeCompatList(providerId, list);+ return;+ }++ if (idx < 0) return;+ if (Object.keys(list[idx]).length <= 1) {+ // Only `id` left; drop the entry entirely.+ const filtered = list.filter((_, i) => i !== idx);+ writeCompatList(providerId, filtered);+ return;+ }+ delete list[idx].isHidden;+ writeCompatList(providerId, list);+}+function readUpstreamFromJsonRecord(row: JsonRecord | null | undefined,key: "upstreamHeaders"diff --git a/src/lib/db/providers.ts b/src/lib/db/providers.tsindex 28f399db55..d593e492be 100644--- a/src/lib/db/providers.ts+++ b/src/lib/db/providers.ts@@ -61,6 +61,41 @@ function withNullableQuotaWindowThresholds(};}+// Always surface `rateLimitOverrides` (possibly null) — matches the pattern+// used by withNullableMaxConcurrent and withNullableQuotaWindowThresholds.+function withNullableRateLimitOverrides(+ record: JsonRecord,+ source: JsonRecord | null | undefined+): JsonRecord {+ return {+ ...record,+ rateLimitOverrides: (source?.rateLimitOverrides ?? null) as Record<string, number> | null,+ };+}++// Sanitize the per-connection rate limit overrides map: keep only known+// fields with valid numeric values. Called once at each write-path boundary.+function sanitizeRateLimitOverrides(value: unknown): Record<string, number> | null {+ if (value === null || value === undefined) return null;+ if (typeof value !== "object" || Array.isArray(value)) return null;+ const allowedKeys = new Set(["rpm", "tpm", "tpd", "minTime", "maxConcurrent"]);+ const map: Record<string, number> = {};+ for (const [key, v] of Object.entries(value as Record<string, unknown>)) {+ if (!allowedKeys.has(key)) continue;+ if (typeof v === "number" && Number.isInteger(v) && v >= 0) {+ map[key] = v;+ }+ }+ return Object.keys(map).length === 0 ? null : map;+}++// Serialize an already-sanitized map for SQLite TEXT storage.+function serializeRateLimitOverrides(value: unknown): string | null {+ if (value === null || value === undefined) return null;+ if (typeof value !== "object" || Array.isArray(value)) return null;+ return JSON.stringify(value);+}+function toRecord(value: unknown): JsonRecord {return value && typeof value === "object" ? (value as JsonRecord) : {};}@@ -124,8 +159,11 @@ export async function getProviderConnections(filter: JsonRecord = {}) {return rows.map((r) => {const camelRow = rowToCamel(r);return decryptConnectionFields(- withNullableQuotaWindowThresholds(- withNullableMaxConcurrent(cleanNulls(camelRow), camelRow),+ withNullableRateLimitOverrides(+ withNullableQuotaWindowThresholds(+ withNullableMaxConcurrent(cleanNulls(camelRow), camelRow),+ camelRow+ ),camelRow));@@ -139,8 +177,11 @@ export async function getProviderConnectionById(id: string) {const camelRow = rowToCamel(row);return decryptConnectionFields(- withNullableQuotaWindowThresholds(- withNullableMaxConcurrent(cleanNulls(camelRow), camelRow),+ withNullableRateLimitOverrides(+ withNullableQuotaWindowThresholds(+ withNullableMaxConcurrent(cleanNulls(camelRow), camelRow),+ camelRow+ ),camelRow));@@ -235,8 +276,11 @@ export async function createProviderConnection(data: JsonRecord) {);_updateConnectionRow(db, existingId, merged);backupDbFile("pre-write");- return withNullableQuotaWindowThresholds(- withNullableMaxConcurrent(cleanNulls(merged), merged),+ return withNullableRateLimitOverrides(+ withNullableQuotaWindowThresholds(+ withNullableMaxConcurrent(cleanNulls(merged), merged),+ merged+ ),merged);}@@ -304,6 +348,7 @@ export async function createProviderConnection(data: JsonRecord) {"proxyEnabled","perKeyProxyEnabled","quotaWindowThresholds",+ "rateLimitOverrides",];for (const field of optionalFields) {if (data[field] !== undefined && data[field] !== null) {@@ -324,6 +369,14 @@ export async function createProviderConnection(data: JsonRecord) {);}+ // Same sanitization for rateLimitOverrides — keep in-memory representation+ // in sync with what gets persisted.+ if ("rateLimitOverrides" in connection) {+ connection.rateLimitOverrides = sanitizeRateLimitOverrides(+ connection.rateLimitOverrides+ );+ }+_insertConnectionRow(db, encryptConnectionFields({ ...connection }));const providerId = toStringOrNull(data.provider);if (providerId) {@@ -332,8 +385,11 @@ export async function createProviderConnection(data: JsonRecord) {backupDbFile("pre-write");invalidateDbCache("connections"); // Bust connections read cache- return withNullableQuotaWindowThresholds(- withNullableMaxConcurrent(cleanNulls(connection), connection),+ return withNullableRateLimitOverrides(+ withNullableQuotaWindowThresholds(+ withNullableMaxConcurrent(cleanNulls(connection), connection),+ connection+ ),connection);}@@ -350,8 +406,7 @@ function _insertConnectionRow(db: DbLike, conn: JsonRecord) {last_tested, api_key, id_token, provider_specific_data,expires_in, display_name, global_priority, default_model,token_type, consecutive_use_count, rate_limit_protection, last_used_at, "group", max_concurrent,- proxy_enabled, per_key_proxy_enabled,- quota_window_thresholds_json,+ proxy_enabled, per_key_proxy_enabled, quota_window_thresholds_json, rate_limit_overrides_json,created_at, updated_at) VALUES (@id, @provider, @authType, @name, @email, @priority, @isActive,@@ -362,8 +417,7 @@ function _insertConnectionRow(db: DbLike, conn: JsonRecord) {@lastTested, @apiKey, @idToken, @providerSpecificData,@expiresIn, @displayName, @globalPriority, @defaultModel,@tokenType, @consecutiveUseCount, @rateLimitProtection, @lastUsedAt, @group, @maxConcurrent,- @proxyEnabled, @perKeyProxyEnabled,- @quotaWindowThresholdsJson,+ @proxyEnabled, @perKeyProxyEnabled, @quotaWindowThresholdsJson, @rateLimitOverridesJson,@createdAt, @updatedAt)`@@ -411,6 +465,7 @@ function _insertConnectionRow(db: DbLike, conn: JsonRecord) {proxyEnabled: conn.proxyEnabled ?? 1,perKeyProxyEnabled: conn.perKeyProxyEnabled ?? 0,quotaWindowThresholdsJson: serializeQuotaWindowThresholds(conn.quotaWindowThresholds),+ rateLimitOverridesJson: serializeRateLimitOverrides(conn.rateLimitOverrides),createdAt: conn.createdAt,updatedAt: conn.updatedAt,});@@ -440,6 +495,7 @@ function _updateConnectionRow(db: DbLike, id: string, data: JsonRecord) {quota_window_thresholds_json = @quotaWindowThresholdsJson,proxy_enabled = @proxyEnabled,per_key_proxy_enabled = @perKeyProxyEnabled,+ rate_limit_overrides_json = @rateLimitOverridesJson,updated_at = @updatedAtWHERE id = @id`@@ -497,6 +553,7 @@ function _updateConnectionRow(db: DbLike, id: string, data: JsonRecord) {? 1: 0: (data.perKeyProxyEnabled ?? 0),+ rateLimitOverridesJson: serializeRateLimitOverrides(data.rateLimitOverrides),updatedAt: now,});}@@ -523,6 +580,9 @@ export async function updateProviderConnection(id: string, data: JsonRecord) {// path surfaces the cleared state to callers that just patched it.merged.quotaWindowThresholds = sanitized;}+ if ("rateLimitOverrides" in merged) {+ merged.rateLimitOverrides = sanitizeRateLimitOverrides(merged.rateLimitOverrides);+ }_updateConnectionRow(db, id, encryptConnectionFields({ ...merged }));backupDbFile("pre-write");invalidateDbCache("connections"); // Bust connections read cache@@ -536,8 +596,11 @@ export async function updateProviderConnection(id: string, data: JsonRecord) {_reorderConnections(db, providerId);}- return withNullableQuotaWindowThresholds(- withNullableMaxConcurrent(cleanNulls(merged), merged),+ return withNullableRateLimitOverrides(+ withNullableQuotaWindowThresholds(+ withNullableMaxConcurrent(cleanNulls(merged), merged),+ merged+ ),merged);}diff --git a/src/lib/localDb.ts b/src/lib/localDb.tsindex 6a8f9968e9..ed9c65f34b 100755--- a/src/lib/localDb.ts+++ b/src/lib/localDb.ts@@ -59,6 +59,7 @@ export {getModelPreserveOpenAIDeveloperRole,getModelUpstreamExtraHeaders,getModelIsHidden,+ setModelIsHidden,// Synced Available ModelsgetSyncedAvailableModels,diff --git a/src/lib/modelMetadataRegistry.ts b/src/lib/modelMetadataRegistry.tsindex d184aee35d..ea69ecd478 100644--- a/src/lib/modelMetadataRegistry.ts+++ b/src/lib/modelMetadataRegistry.ts@@ -272,6 +272,7 @@ export function enrichCatalogModelEntry<T extends JsonRecord>(if (!metadata) return entry;const nextEntry: JsonRecord = { ...entry };+ const existingName = asNonEmptyString(entry.name);const capabilityFields = {...(typeof metadata.capabilities.vision === "boolean"? { vision: metadata.capabilities.vision }@@ -331,6 +332,9 @@ export function enrichCatalogModelEntry<T extends JsonRecord>(if (typeof metadata.metadata.openWeights === "boolean") {nextEntry.open_weights = metadata.metadata.openWeights;}+ if (!existingName && metadata.displayName) {+ nextEntry.name = metadata.displayName;+ }return nextEntry as T;}diff --git a/src/server/authz/policies/clientApi.ts b/src/server/authz/policies/clientApi.tsindex 8b90e5b07a..e291205e3b 100644--- a/src/server/authz/policies/clientApi.ts+++ b/src/server/authz/policies/clientApi.ts@@ -1,19 +1,23 @@import { isDashboardSessionAuthenticated } from "@/shared/utils/apiAuth.ts";import { isRequireApiKeyEnabled } from "@/shared/utils/featureFlags";+import { extractApiKey } from "@/sse/services/auth.ts";import type { AuthOutcome, PolicyContext, RoutePolicy } from "../context";import { allow, reject } from "../context";-function extractBearer(headers: Headers): string | null {- const raw = headers.get("authorization") ?? headers.get("Authorization");- const xApiKey = headers.get("x-api-key") ?? headers.get("X-Api-Key");+function extractBearer(request: Request): string | null {+ const raw = request.headers.get("authorization") ?? request.headers.get("Authorization");+ const xApiKey = request.headers.get("x-api-key") ?? request.headers.get("X-Api-Key");if (raw) {const trimmed = raw.trim();if (!trimmed.toLowerCase().startsWith("bearer ")) return null;return trimmed.slice(7).trim() || null;- } else if (xApiKey) {+ }++ if (xApiKey) {return xApiKey?.trim() || null;}- return null;++ return extractApiKey(request);}function maskKeyId(apiKey: string): string {@@ -24,7 +28,7 @@ function maskKeyId(apiKey: string): string {export const clientApiPolicy: RoutePolicy = {routeClass: "CLIENT_API",async evaluate(ctx: PolicyContext): Promise<AuthOutcome> {- const bearer = extractBearer(ctx.request.headers);+ const bearer = extractBearer(ctx.request as Request);if (!bearer) {if (await isDashboardSessionAuthenticated(ctx.request)) {return allow({ kind: "dashboard_session", id: "dashboard" });diff --git a/src/server/authz/policies/management.ts b/src/server/authz/policies/management.tsindex 534d3592f6..b5dd75caf9 100644--- a/src/server/authz/policies/management.ts+++ b/src/server/authz/policies/management.ts@@ -120,7 +120,9 @@ export const managementPolicy: RoutePolicy = {// still hit the same 403 LOCAL_ONLY they did before.if (isLocalOnlyPath(path) && !isLoopbackRequest(ctx) && !isPrivateLanRequest(ctx)) {if (isLocalOnlyBypassableByManageScope(path)) {- const apiKey = extractApiKey(ctx.request as unknown as Request);+ // Management auth is header-only — a URL-borne token must never satisfy a+ // manage-scope bypass of a LOCAL_ONLY route. See #3300 follow-up.+ const apiKey = extractApiKey(ctx.request as unknown as Request, { allowUrl: false });if (apiKey) {try {if (await isValidApiKey(apiKey)) {@@ -198,7 +200,9 @@ export const managementPolicy: RoutePolicy = {// unhealthy, which is a 503, not a 403 — masking it as an auth failure// would tell callers their credentials are wrong when the real problem// is that the server cannot validate any credential right now.- const apiKey = extractApiKey(ctx.request as unknown as Request);+ // Management auth is header-only — a URL-borne token must not authenticate+ // a management route. See #3300 follow-up.+ const apiKey = extractApiKey(ctx.request as unknown as Request, { allowUrl: false });if (apiKey) {try {if (await isValidApiKey(apiKey)) {diff --git a/src/server/authz/routeGuard.ts b/src/server/authz/routeGuard.tsindex 5bbf92930b..f97d7a3f97 100644--- a/src/server/authz/routeGuard.ts+++ b/src/server/authz/routeGuard.ts@@ -37,6 +37,22 @@ export const LOCAL_ONLY_API_PREFIXES: ReadonlyArray<string> = ["/api/plugins", // bare path: GET list + POST install also trigger plugin loading];+/**+ * LOCAL_ONLY routes whose spawn-capable segment sits AFTER a dynamic path+ * parameter, so a flat prefix in `LOCAL_ONLY_API_PREFIXES` cannot target them+ * without over-broadening (e.g. locking the entire `/api/providers/` subtree,+ * which remote dashboards legitimately use for provider CRUD). These are matched+ * by regex instead.+ *+ * - `POST /api/providers/{id}/login` launches a headful Playwright Chromium+ * (a child process) to drive a web-cookie login. Loopback enforcement must+ * happen unconditionally before any auth check (Hard Rules #15 + #17), so a+ * leaked JWT via tunnel cannot trigger a browser spawn.+ */+export const LOCAL_ONLY_API_PATTERNS: ReadonlyArray<RegExp> = [+ /^\/api\/providers\/[^/]+\/login\/?$/,+];+/*** Compile-time deny-list: route prefixes that can spawn arbitrary local* subprocesses on behalf of the caller. These MUST NEVER appear in the@@ -141,7 +157,10 @@ export function isPrivateLanHost(hostHeader: string | null): boolean {}export function isLocalOnlyPath(path: string): boolean {- return LOCAL_ONLY_API_PREFIXES.some((p) => path === p || path.startsWith(p));+ return (+ LOCAL_ONLY_API_PREFIXES.some((p) => path === p || path.startsWith(p)) ||+ LOCAL_ONLY_API_PATTERNS.some((re) => re.test(path))+ );}/**diff --git a/src/shared/constants/modelSpecs.ts b/src/shared/constants/modelSpecs.tsindex 273bc7190e..b921808d95 100644--- a/src/shared/constants/modelSpecs.ts+++ b/src/shared/constants/modelSpecs.ts@@ -42,6 +42,15 @@ export const MODEL_SPECS: Record<string, ModelSpec> = {supportsVision: true,},+ "gpt-5.4": {+ maxOutputTokens: 131072,+ contextWindow: 409600,+ supportsThinking: true,+ supportsTools: true,+ supportsVision: true,+ aliases: ["openai/gpt-5.4"],+ },+// ── GPT-4o family ──────────────────────────────────────────────"gpt-4o-mini": {maxOutputTokens: 16384,diff --git a/src/shared/constants/providers.ts b/src/shared/constants/providers.tsindex 4b7dc2f6a5..faa00d061f 100644--- a/src/shared/constants/providers.ts+++ b/src/shared/constants/providers.ts@@ -933,18 +933,6 @@ export const APIKEY_PROVIDERS = {apiHint:"Get free API key at https://bazaarlink.ai — use model 'auto:free' for zero-cost inference. OpenAI-compatible.",},- completions: {- id: "completions",- alias: "cpl",- name: "Completions.me",- icon: "bolt",- color: "#F59E0B",- textIcon: "CP",- website: "https://completions.me",- hasFree: true,- freeNote: "Free unlimited access to Claude, GPT, Gemini — no credit card, no rate limits",- apiHint: "Sign up at https://completions.me for free API key. OpenAI-compatible endpoint.",- },xai: {id: "xai",alias: "xai",diff --git a/src/shared/utils/apiAuth.ts b/src/shared/utils/apiAuth.tsindex 9599ba734f..56d6e00ce0 100644--- a/src/shared/utils/apiAuth.ts+++ b/src/shared/utils/apiAuth.ts@@ -11,6 +11,7 @@ import { jwtVerify } from "jose";import { cookies } from "next/headers";import { getSettings } from "@/lib/localDb";import { isPublicApiRoute } from "@/shared/constants/publicApiRoutes";+import { extractApiKey } from "@/sse/services/auth";type RequestLike = {cookies?: {@@ -138,15 +139,23 @@ function getCookieValueFromHeader(headers: Headers | undefined, name: string): sreturn null;}-function getBearerToken(request: RequestLike | Request | null | undefined): string | null {- const headers =- request && typeof request === "object" && "headers" in request ? request.headers : undefined;- const authHeader = headers?.get("authorization") || headers?.get("Authorization");- if (typeof authHeader !== "string") return null;+function getRequestApiKey(+ request: RequestLike | Request | null | undefined,+ opts?: { allowUrl?: boolean }+): string | null {+ if (!request || typeof request !== "object") return null;++ const headers = "headers" in request ? request.headers : undefined;+ const rawUrl = "url" in request && typeof request.url === "string" ? request.url : null;+ const pathname = getRequestPathname(request);+ const syntheticUrl = rawUrl || (pathname ? `http://localhost${pathname}` : null);++ // Management auth never honours a URL-borne credential (defence-in-depth: the+ // path-scoped token is a client-API affordance only — a credential in the URL+ // must not authenticate a management route). See the #3300 security follow-up.+ const allowUrl = opts?.allowUrl !== false;- const trimmedHeader = authHeader.trim();- if (!trimmedHeader.toLowerCase().startsWith("bearer ")) return null;- return trimmedHeader.slice(7).trim() || null;+ return extractApiKey({ headers, url: allowUrl ? syntheticUrl : null }, { allowUrl });}async function validateBearerApiKey(apiKey: string | null): Promise<boolean> {@@ -248,15 +257,16 @@ export async function verifyAuth(request: any): Promise<string | null> {return null;}- const bearerToken = getBearerToken(request);- if (isManagementApiRequest(request)) {- if (await validateBearerApiKeyForManagement(bearerToken)) {+ const isManagement = isManagementApiRequest(request);+ const apiKey = getRequestApiKey(request, { allowUrl: !isManagement });+ if (isManagement) {+ if (await validateBearerApiKeyForManagement(apiKey)) {return null;}- return bearerToken ? "Invalid management token" : "Authentication required";+ return apiKey ? "Invalid management token" : "Authentication required";}- if (await validateBearerApiKey(bearerToken)) {+ if (await validateBearerApiKey(apiKey)) {return null;}@@ -282,12 +292,13 @@ export async function isAuthenticated(request: Request): Promise<boolean> {return true;}- const bearerToken = getBearerToken(request);- if (isManagementApiRequest(request)) {- return validateBearerApiKeyForManagement(bearerToken);+ const isManagement = isManagementApiRequest(request);+ const apiKey = getRequestApiKey(request, { allowUrl: !isManagement });+ if (isManagement) {+ return validateBearerApiKeyForManagement(apiKey);}- return validateBearerApiKey(bearerToken);+ return validateBearerApiKey(apiKey);}/**diff --git a/src/shared/validation/schemas.ts b/src/shared/validation/schemas.tsindex 0a3bd1793f..c9e2b0609a 100644--- a/src/shared/validation/schemas.ts+++ b/src/shared/validation/schemas.ts@@ -2012,6 +2012,20 @@ export const updateProviderConnectionSchema = z]).optional(),projectId: z.union([z.string(), z.null()]).optional(),+ // Per-connection rate limit overrides — overrides the global RequestQueueSettings+ // for this connection. Set to null to clear all overrides.+ rateLimitOverrides: z+ .union([+ z.null(),+ z.object({+ rpm: z.coerce.number().int().min(0).max(1_000_000).optional(),+ tpm: z.coerce.number().int().min(0).max(100_000_000).optional(),+ tpd: z.coerce.number().int().min(0).max(10_000_000_000).optional(),+ minTime: z.coerce.number().int().min(0).max(60_000).optional(),+ maxConcurrent: z.coerce.number().int().min(0).max(10_000).optional(),+ }),+ ])+ .optional(),proxyEnabled: z.boolean().optional(),perKeyProxyEnabled: z.boolean().optional(),// Partial patch of per-connection provider-specific settings (e.g. quota toggles)diff --git a/src/sse/services/auth.ts b/src/sse/services/auth.tsindex b81e1cef46..620e35a412 100644--- a/src/sse/services/auth.ts+++ b/src/sse/services/auth.ts@@ -183,11 +183,29 @@ function toBooleanOrDefault(value: unknown, fallback: boolean): boolean {}function readHeaderValue(- headers: Headers | { get?: (name: string) => string | null } | null | undefined,+ headers:+ | Headers+ | { get?: (name: string) => string | null }+ | Record<string, string | string[] | undefined>+ | null+ | undefined,name: string): string | null {- if (!headers || typeof headers.get !== "function") return null;- const value = headers.get(name);+ if (!headers) return null;++ if (typeof (headers as Headers).get === "function") {+ const value = (headers as Headers).get(name) || (headers as Headers).get(name.toLowerCase());+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;+ }++ const recordHeaders = headers as Record<string, string | string[] | undefined>;+ const value =+ recordHeaders[name] || recordHeaders[name.toLowerCase()] || recordHeaders[name.toUpperCase()];++ if (Array.isArray(value)) {+ return typeof value[0] === "string" && value[0].trim().length > 0 ? value[0].trim() : null;+ }+return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;}@@ -831,7 +849,11 @@ async function getProviderSearchPool(provider: string): Promise<string[]> {const nodePrefix = typeof nodeRecord.prefix === "string" ? nodeRecord.prefix.trim() : "";const nodeId = typeof nodeRecord.id === "string" ? nodeRecord.id.trim() : "";if (!nodePrefix || !nodeId) continue;- if (nodePrefix === provider || nodePrefix === canonicalProvider || nodePrefix === canonicalAlias) {+ if (+ nodePrefix === provider ||+ nodePrefix === canonicalProvider ||+ nodePrefix === canonicalAlias+ ) {searchPool.add(nodeId);}}@@ -1584,8 +1606,8 @@ export async function getProviderCredentialsWithQuotaPreflight(// false for both "not set" and "explicit false" — we need an explicit check// here to distinguish them.const legacyForceDisable =- (credentials as { providerSpecificData?: Record<string, unknown> })- .providerSpecificData?.quotaPreflightEnabled === false;+ (credentials as { providerSpecificData?: Record<string, unknown> }).providerSpecificData+ ?.quotaPreflightEnabled === false;if (legacyForceDisable) return credentials;const hasConnectionOverrides = Object.keys(perConnectionWindowOverrides).length > 0;@@ -2024,16 +2046,65 @@ export async function clearRecoveredProviderState(await clearAccountError(credentials.connectionId, credentials);}+type AuthRequestHeaders = Headers | Record<string, string | string[] | undefined>;++type AuthRequestLike = {+ headers?: AuthRequestHeaders | null;+ url?: string | null;+};++function readNonEmptyUrlToken(request: AuthRequestLike): string | null {+ if (typeof request?.url !== "string" || request.url.trim().length === 0) return null;++ try {+ const url = new URL(request.url, "http://localhost");++ const segments = url.pathname+ .split("/")+ .map((segment) => segment.trim())+ .filter(Boolean);++ if (segments[0] === "vscode" && segments[1]) {+ const decodedSegment = decodeURIComponent(segments[1]).trim();+ if (decodedSegment.length > 0) return decodedSegment;+ }++ if (segments[0] === "api" && segments[1] === "v1" && segments[2] === "vscode") {+ if (segments[3] && segments[3] !== "raw" && segments[3] !== "combos") {+ const decodedSegment = decodeURIComponent(segments[3]).trim();+ if (decodedSegment.length > 0) return decodedSegment;+ }++ if ((segments[3] === "raw" || segments[3] === "combos") && segments[4]) {+ const decodedSegment = decodeURIComponent(segments[4]).trim();+ if (decodedSegment.length > 0) return decodedSegment;+ }+ }++ // NOTE: query-string token fallbacks (`?token=`/`?key=`/`?apiKey=`/`?api_key=`)+ // were intentionally REMOVED. They are a broad credential-in-URL surface that+ // leaks into access logs, Referer headers and proxy logs, and — because this+ // extractor also feeds management auth — would let `?token=<mgmt-key>`+ // authenticate management routes. The VS Code integration only needs the+ // path-scoped `/vscode/<token>/…` form above. (security review, #3300 follow-up)+ } catch {+ return null;+ }++ return null;+}+/**- * Extract API key from request headers.+ * Extract API key from request auth inputs.*- * Honors both:+ * Honors explicit auth headers and (for client-facing routes only) a+ * path-scoped URL token:* - `Authorization: Bearer <key>` (OpenAI / OmniRoute / Codex CLI / Bearer clients)* - `x-api-key: <key>` (Anthropic Messages API contract — Claude Code,* `@anthropic-ai/sdk`, any SDK that sets `anthropic-version`)+ * - `/vscode/<key>/...` (path-scoped tokenized aliases — only when `allowUrl`)*- * When both are present, `Authorization: Bearer` wins for back-compat- * (issue #2225).+ * When multiple inputs are present, explicit auth headers win.** The `x-api-key` fallback only triggers when the request also carries an* `anthropic-version` header — the documented signal that the caller is@@ -2041,29 +2112,42 @@ export async function clearRecoveredProviderState(* non-Anthropic SDKs that happen to set `x-api-key` (or local-mode tools* with placeholder keys) would be treated as authenticated attempts and* rejected by per-route gates that compare against OmniRoute keys.+ *+ * `opts.allowUrl` (default `true`) gates the path-scoped URL token. Management+ * auth MUST pass `allowUrl: false` — a credential in the URL must never+ * authenticate a management route (it leaks into logs/Referer and would widen+ * the management surface). See the #3300 security follow-up.*/-export function extractApiKey(request: Request) {- const authHeader = request.headers.get("Authorization") || request.headers.get("authorization");+export function extractApiKey(request: AuthRequestLike, opts?: { allowUrl?: boolean }) {+ const authHeader =+ readHeaderValue(request?.headers, "Authorization") ||+ readHeaderValue(request?.headers, "authorization");if (typeof authHeader === "string") {const trimmedHeader = authHeader.trim();if (trimmedHeader.toLowerCase().startsWith("bearer ")) {- return trimmedHeader.slice(7).trim();+ return trimmedHeader.slice(7).trim() || null;}}+// Issue #2225: Anthropic Messages API clients authenticate via x-api-key.// Gate the fallback on the anthropic-version header so we don't trip up// local-mode requests from non-Anthropic clients that send placeholder// x-api-key values (which would otherwise be rejected as Invalid API key).const anthropicVersion =- request.headers.get("anthropic-version") || request.headers.get("Anthropic-Version");+ readHeaderValue(request?.headers, "anthropic-version") ||+ readHeaderValue(request?.headers, "Anthropic-Version");if (anthropicVersion) {- const xApiKey = request.headers.get("x-api-key") || request.headers.get("X-Api-Key");+ const xApiKey =+ readHeaderValue(request?.headers, "x-api-key") ||+ readHeaderValue(request?.headers, "X-Api-Key");if (typeof xApiKey === "string") {const trimmed = xApiKey.trim();if (trimmed.length > 0) return trimmed;}}- return null;++ if (opts?.allowUrl === false) return null;+ return readNonEmptyUrlToken(request);}/**diff --git a/tests/unit/agent-bridge-state-normalize-3318.test.ts b/tests/unit/agent-bridge-state-normalize-3318.test.tsnew file mode 100644index 0000000000..2396d75fc5--- /dev/null+++ b/tests/unit/agent-bridge-state-normalize-3318.test.ts@@ -0,0 +1,74 @@+import test from "node:test";+import assert from "node:assert/strict";++const { normalizeAgentBridgeState, DEFAULT_AGENT_BRIDGE_STATE } = await import(+ "../../src/app/(dashboard)/dashboard/tools/agent-bridge/normalizeState.ts"+);++// #3318: the /api/tools/agent-bridge/state route returns `{ server, agents }`,+// but the page/components read `{ serverState, agentStates, bypassPatterns,+// mappings }`. The page replaced its well-shaped default with the raw response,+// so `serverState` became undefined → `serverState.running` crashed the page+// with the full "Internal Server Error" boundary. The normalizer must always+// return a well-shaped object (never an undefined serverState), mapping the+// known server fields through.++test("the raw /state route shape lacks the keys the page reads (documents the bug)", () => {+ const routeShape = {+ server: { running: true, pid: 123, dnsConfigured: true, certExists: true },+ agents: [{ id: "claude-code", name: "Claude Code", hosts: [], viability: "ok" }],+ };+ // This is exactly what the old code assigned straight into initialData.+ assert.equal(routeShape.serverState, undefined);+});++test("normalizeAgentBridgeState maps the route shape and never leaves serverState undefined (#3318)", () => {+ const routeShape = {+ server: { running: true, pid: 123, dnsConfigured: true, certExists: true },+ agents: [{ id: "claude-code", name: "Claude Code", hosts: [], viability: "ok" }],+ };+ const result = normalizeAgentBridgeState(routeShape);++ assert.ok(result.serverState, "serverState must be defined");+ assert.equal(result.serverState.running, true, "server.running maps through");+ assert.equal(result.serverState.certTrusted, true, "server.certExists -> certTrusted");+ assert.ok(Array.isArray(result.agentStates), "agentStates is always an array");+ assert.ok(Array.isArray(result.bypassPatterns), "bypassPatterns is always an array");+ assert.equal(typeof result.mappings, "object", "mappings is always an object");+});++test("normalizeAgentBridgeState falls back to safe defaults for empty/garbage input", () => {+ for (const bad of [null, undefined, {}, 42, "x", []]) {+ const result = normalizeAgentBridgeState(bad);+ assert.ok(result.serverState, `serverState defined for ${JSON.stringify(bad)}`);+ assert.equal(result.serverState.running, false);+ assert.ok(Array.isArray(result.agentStates));+ assert.ok(Array.isArray(result.bypassPatterns));+ assert.equal(typeof result.mappings, "object");+ }+});++test("normalizeAgentBridgeState passes a correctly-shaped payload through intact", () => {+ const correct = {+ ...DEFAULT_AGENT_BRIDGE_STATE,+ serverState: { ...DEFAULT_AGENT_BRIDGE_STATE.serverState, running: true, port: 8443 },+ agentStates: [+ {+ agent_id: "claude-code",+ dns_enabled: true,+ cert_trusted: true,+ setup_completed: true,+ last_started_at: null,+ last_error: null,+ },+ ],+ bypassPatterns: ["*.internal"],+ mappings: { "claude-code": [] },+ };+ const result = normalizeAgentBridgeState(correct);+ assert.equal(result.serverState.running, true);+ assert.equal(result.serverState.port, 8443);+ assert.equal(result.agentStates.length, 1);+ assert.equal(result.agentStates[0].agent_id, "claude-code");+ assert.deepEqual(result.bypassPatterns, ["*.internal"]);+});diff --git a/tests/unit/antigravity-model-aliases.test.ts b/tests/unit/antigravity-model-aliases.test.tsindex 511d7e7030..511ac5dc9c 100644--- a/tests/unit/antigravity-model-aliases.test.ts+++ b/tests/unit/antigravity-model-aliases.test.ts@@ -53,17 +53,32 @@ test("isUserCallableAntigravityModelId only allows public chat-capable model IDsassert.equal(isUserCallableAntigravityModelId("gemini-2.5-flash-lite"), true);assert.equal(isUserCallableAntigravityModelId("gemini-2.5-flash-thinking"), true);assert.equal(isUserCallableAntigravityModelId("gemini-pro-agent"), true);- // Claude was removed from Antigravity 2.0's public catalog (May 2026); the alias is- // kept for back-compat but the model is no longer user-callable.- assert.equal(isUserCallableAntigravityModelId("claude-sonnet-4-6"), false);+ // #3184: Claude IS user-callable through the Antigravity OAuth provider (same backend as+ // `agy`, verified empirically). An earlier assumption that it was removed in Antigravity+ // 2.0 was wrong.+ assert.equal(isUserCallableAntigravityModelId("claude-opus-4-6-thinking"), true);+ assert.equal(isUserCallableAntigravityModelId("claude-sonnet-4-6"), true);+ // #3184: Gemini budget tiers now exposed (agy parity).+ assert.equal(isUserCallableAntigravityModelId("gemini-3.1-pro-high"), true);+ assert.equal(isUserCallableAntigravityModelId("gemini-3.1-pro-low"), true);+ assert.equal(isUserCallableAntigravityModelId("gemini-3.5-flash-low"), true);+ assert.equal(isUserCallableAntigravityModelId("gemini-3.5-flash-extra-low"), true);assert.equal(isUserCallableAntigravityModelId("tab_flash_lite_preview"), false);assert.equal(isUserCallableAntigravityModelId("unknown-model"), false);});test("ANTIGRAVITY_PUBLIC_MODELS exposes captured Antigravity 2.0.1 names and capabilities", () => {- // Claude models were removed from Antigravity 2.0's public catalog (May 2026), so they- // are no longer exposed as public models (the back-compat alias still resolves upstream).- assert.equal(getPublicModel("claude-opus-4-6-thinking"), undefined);+ // #3184: Claude is exposed in the antigravity catalog (same backend as `agy`, verified).+ assert.deepEqual(getPublicModel("claude-opus-4-6-thinking"), {+ id: "claude-opus-4-6-thinking",+ name: "Claude Opus 4.6 (Thinking)",+ contextLength: 200000,+ maxOutputTokens: 65536,+ supportsReasoning: true,+ supportsVision: true,+ toolCalling: true,+ });+ assert.equal(getPublicModel("claude-sonnet-4-6").name, "Claude Sonnet 4.6 (Thinking)");assert.deepEqual(getPublicModel("gemini-3.5-flash-preview"), {id: "gemini-3.5-flash-preview",name: "Gemini 3.5 Flash",diff --git a/tests/unit/api-auth.test.ts b/tests/unit/api-auth.test.tsindex 4685c7e2ff..07b0d4c520 100644--- a/tests/unit/api-auth.test.ts+++ b/tests/unit/api-auth.test.ts@@ -104,6 +104,56 @@ test("verifyAuth falls back to bearer API key validation after a bad JWT", asyncassert.equal(result, null);});+test("verifyAuth no longer accepts API keys supplied via query string (#3300 follow-up)", async () => {+ // Query-string token fallbacks were removed (credential-in-URL leaks into logs).+ const key = await apiKeysDb.createApiKey("query-auth", "machine1234567890");++ const result = await apiAuth.verifyAuth({+ cookies: {+ get() {+ return undefined;+ },+ },+ headers: new Headers(),+ url: `https://example.com/api/v1/models?token=${encodeURIComponent(key.key)}`,+ });++ // No usable credential → authentication fails (was incorrectly accepted before).+ assert.notEqual(result, null);+});++test("isAuthenticated accepts API keys embedded in vscode path aliases", async () => {+ const key = await apiKeysDb.createApiKey("path-auth", "machine1234567890");+ const request = new Request(+ `https://example.com/api/v1/vscode/${encodeURIComponent(key.key)}/models`+ );++ const result = await apiAuth.isAuthenticated(request);++ assert.equal(result, true);+});++test("verifyAuth never honours a URL-borne token on MANAGEMENT routes (#3300 follow-up)", async () => {+ // The historical escalation: a credential in the query string on a management+ // route (/api/* but not /api/v1/*). It must not be extracted at all, so the+ // failure is "Authentication required" (no credential) — NOT "Invalid+ // management token" (which the pre-fix code returned, proving the URL token+ // had been picked up and tried against management validation).+ const key = await apiKeysDb.createApiKey("mgmt-url", "machine1234567890");++ const result = await apiAuth.verifyAuth({+ cookies: {+ get() {+ return undefined;+ },+ },+ headers: new Headers(),+ url: `https://example.com/api/providers?token=${encodeURIComponent(key.key)}`,+ });++ assert.equal(result, "Authentication required");+});+test("verifyAuth rejects bearer API keys on management routes", async () => {const key = await apiKeysDb.createApiKey("integration", "machine1234567890");const result = await apiAuth.verifyAuth({diff --git a/tests/unit/auth-extract-api-key.test.ts b/tests/unit/auth-extract-api-key.test.tsindex 8ed964e4c6..255abd9d41 100644--- a/tests/unit/auth-extract-api-key.test.ts+++ b/tests/unit/auth-extract-api-key.test.ts@@ -89,3 +89,41 @@ test("extractApiKey accepts Anthropic-Version (TitleCase) header", () => {});assert.equal(extractApiKey(req), "sk-titlecase-version");});++test("extractApiKey extracts a path-scoped token from /api/v1/vscode/<token>/...", () => {+ const req = new Request("https://omniroute.test/api/v1/vscode/sk-test-path-token/models");+ assert.equal(extractApiKey(req), "sk-test-path-token");+});++test("extractApiKey extracts a path-scoped token from /api/v1/vscode/raw/<token>/...", () => {+ const req = new Request(+ "https://omniroute.test/api/v1/vscode/raw/sk-test-path-token/api/version"+ );+ assert.equal(extractApiKey(req), "sk-test-path-token");+});++test("extractApiKey extracts a path-scoped token from /api/v1/vscode/combos/<token>/...", () => {+ const req = new Request(+ "https://omniroute.test/api/v1/vscode/combos/sk-test-path-token/api/version"+ );+ assert.equal(extractApiKey(req), "sk-test-path-token");+});++test("extractApiKey does NOT extract a query-string token (#3300 security follow-up)", () => {+ // Query-string fallbacks (?token / ?key / ?apiKey / ?api_key) were removed —+ // a credential in the query string leaks into access logs / Referer headers.+ for (const q of ["token", "key", "apiKey", "api_key"]) {+ const req = new Request(`https://omniroute.test/api/v1/models?${q}=sk-test-query-token`);+ assert.equal(extractApiKey(req), null, `?${q}= must not be extracted`);+ }+});++test("extractApiKey skips the path-scoped token when allowUrl is false (management auth)", () => {+ const req = new Request("https://omniroute.test/api/v1/vscode/sk-test-path-token/models");+ assert.equal(extractApiKey(req, { allowUrl: false }), null);+ // Headers still work regardless of allowUrl.+ const withHeader = new Request("https://omniroute.test/api/v1/vscode/sk-test-path-token/models", {+ headers: { Authorization: "Bearer sk-header-wins" },+ });+ assert.equal(extractApiKey(withHeader, { allowUrl: false }), "sk-header-wins");+});diff --git a/tests/unit/autoRefreshDaemon.test.ts b/tests/unit/autoRefreshDaemon.test.tsnew file mode 100644index 0000000000..3ea6cd2a48--- /dev/null+++ b/tests/unit/autoRefreshDaemon.test.ts@@ -0,0 +1,87 @@+/**+ * Tests for AutoRefreshDaemon+ */++import assert from "node:assert/strict";+import { describe, it, before, after, beforeEach } from "node:test";+import { autoRefreshDaemon, type DaemonStatus } from "../../open-sse/services/autoRefreshDaemon";++describe("AutoRefreshDaemon", () => {+ beforeEach(() => {+ autoRefreshDaemon.clearExpired();+ autoRefreshDaemon.stop();+ });++ describe("start / stop", () => {+ it("should start and stop cleanly", () => {+ let status = autoRefreshDaemon.getStatus();+ assert.equal(status.running, false);++ autoRefreshDaemon.start();+ status = autoRefreshDaemon.getStatus();+ assert.equal(status.running, true);++ autoRefreshDaemon.stop();+ status = autoRefreshDaemon.getStatus();+ assert.equal(status.running, false);+ });++ it("should be idempotent on start", () => {+ autoRefreshDaemon.start();+ autoRefreshDaemon.start(); // second call should noop+ assert.equal(autoRefreshDaemon.getStatus().running, true);+ autoRefreshDaemon.stop();+ });++ it("should be idempotent on stop", () => {+ autoRefreshDaemon.stop(); // not running — noop+ autoRefreshDaemon.start();+ autoRefreshDaemon.stop();+ autoRefreshDaemon.stop(); // already stopped — noop+ assert.equal(autoRefreshDaemon.getStatus().running, false);+ });+ });++ describe("registerCredential / unregisterCredential", () => {+ it("should register and track a credential", () => {+ autoRefreshDaemon.registerCredential("test-provider", "cookie-value-123");+ const status = autoRefreshDaemon.getStatus();+ assert.equal(status.checkedProviderCount, 1);+ });++ it("should unregister and stop tracking", () => {+ autoRefreshDaemon.registerCredential("test-provider", "cookie-value-123");+ assert.equal(autoRefreshDaemon.getStatus().checkedProviderCount, 1);++ autoRefreshDaemon.unregisterCredential("test-provider");+ assert.equal(autoRefreshDaemon.getStatus().checkedProviderCount, 0);+ });+ });++ describe("clearExpired", () => {+ it("should clear expired list", () => {+ // Force-expire by registering and running check against a provider that+ // won't resolve — expired list stays empty since network errors are non-fatal+ autoRefreshDaemon.registerCredential("fake-nonexistent", "test-value");+ assert.equal(autoRefreshDaemon.getStatus().expiredCredentials.length, 0);++ autoRefreshDaemon.clearExpired();+ assert.equal(autoRefreshDaemon.getStatus().expiredCredentials.length, 0);+ });+ });++ describe("getStatus", () => {+ it("should return current daemon state", () => {+ autoRefreshDaemon.registerCredential("provider-a", "val-a");+ autoRefreshDaemon.start();+ const status = autoRefreshDaemon.getStatus();++ assert.ok(typeof status.running === "boolean");+ assert.ok(typeof status.checkedProviderCount === "number");+ assert.ok(Array.isArray(status.expiredCredentials));+ assert.ok(typeof status.lastRun === "number" || status.lastRun === null);++ autoRefreshDaemon.stop();+ });+ });+});diff --git a/tests/unit/cli-update-global-paths-3295.test.ts b/tests/unit/cli-update-global-paths-3295.test.tsnew file mode 100644index 0000000000..e23a2ef3dd--- /dev/null+++ b/tests/unit/cli-update-global-paths-3295.test.ts@@ -0,0 +1,65 @@+import test from "node:test";+import assert from "node:assert/strict";+import { readFileSync, mkdtempSync, mkdirSync, existsSync, statSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import path from "node:path";+import { fileURLToPath } from "node:url";++const update = await import("../../bin/cli/commands/update.mjs");++const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");+const REAL_VERSION = JSON.parse(+ readFileSync(path.join(REPO_ROOT, "package.json"), "utf-8")+).version;++// #3295 issue 1: getCurrentVersion() must resolve package.json relative to the+// script, not process.cwd(). When OmniRoute is installed globally, the user's+// cwd is not the package root, so a cwd-relative lookup returns null →+// "Could not determine current version".+test("getCurrentVersion resolves the real version from a foreign cwd (#3295)", async () => {+ const originalCwd = process.cwd();+ const foreignCwd = mkdtempSync(path.join(tmpdir(), "omniroute-cwd-"));+ try {+ process.chdir(foreignCwd); // no package.json here → cwd-relative lookup would fail+ const version = await update.getCurrentVersion();+ assert.equal(version, REAL_VERSION);+ } finally {+ process.chdir(originalCwd);+ rmSync(foreignCwd, { recursive: true, force: true });+ }+});++// #3295 issue 2: createBackup() must (a) resolve bin/ relative to the script,+// and (b) copy the "cli" directory recursively. The old copyFileSync(dir) threw+// EISDIR which the outer catch swallowed → "Failed to create backup. Aborting".+test("createBackup resolves bin/ from a foreign cwd and copies cli/ recursively (#3295)", async () => {+ const originalCwd = process.cwd();+ const originalHome = process.env.HOME;+ const foreignCwd = mkdtempSync(path.join(tmpdir(), "omniroute-cwd-"));+ const fakeHome = mkdtempSync(path.join(tmpdir(), "omniroute-home-"));+ try {+ process.chdir(foreignCwd); // no bin/ here → cwd-relative binPath would be missing+ process.env.HOME = fakeHome; // redirect ~/.omniroute/backups+ mkdirSync(fakeHome, { recursive: true });++ const backupDir = await update.createBackup();++ assert.ok(backupDir, "createBackup must return a path (not null)");+ // omniroute.mjs is a real file in bin/ and must be copied+ assert.ok(existsSync(path.join(backupDir, "omniroute.mjs")), "omniroute.mjs copied");+ // "cli" is a directory — it must be copied recursively, not throw EISDIR+ const cliBackup = path.join(backupDir, "cli");+ assert.ok(existsSync(cliBackup), "cli/ directory copied");+ assert.ok(statSync(cliBackup).isDirectory(), "cli/ backup is a directory");+ assert.ok(+ existsSync(path.join(cliBackup, "commands")),+ "cli/ contents copied recursively"+ );+ } finally {+ process.chdir(originalCwd);+ if (originalHome === undefined) delete process.env.HOME;+ else process.env.HOME = originalHome;+ rmSync(foreignCwd, { recursive: true, force: true });+ rmSync(fakeHome, { recursive: true, force: true });+ }+});diff --git a/tests/unit/codex-responses-passthrough-strip-3317.test.ts b/tests/unit/codex-responses-passthrough-strip-3317.test.tsnew file mode 100644index 0000000000..6c64ef7703--- /dev/null+++ b/tests/unit/codex-responses-passthrough-strip-3317.test.ts@@ -0,0 +1,53 @@+import test from "node:test";+import assert from "node:assert/strict";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";++const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-codex-3317-"));+process.env.DATA_DIR = TEST_DATA_DIR;++const core = await import("../../src/lib/db/core.ts");+const { CodexExecutor } = await import("../../open-sse/executors/codex.ts");++// #3317: a /v1/responses request against the built-in codex/ provider does an+// openai-responses -> openai-responses passthrough. The Codex upstream rejects+// client-only fields with 400 "Unsupported parameter": prompt_cache_retention,+// safety_identifier, user. The chat-completions path strips them, but the+// native passthrough (transformRequest returns body early) did not.+test("codex native responses passthrough strips client-only params (#3317)", async () => {+ const executor = new CodexExecutor();+ const body = {+ _nativeCodexPassthrough: true,+ model: "gpt-5.5",+ input: [{ role: "user", content: [{ type: "input_text", text: "reply ok" }] }],+ prompt_cache_retention: "24h",+ safety_identifier: "droid-user-123",+ user: "user-abc",+ max_output_tokens: 16,+ };++ const result = (await executor.transformRequest("gpt-5.5", body, false, {} as never)) as Record<+ string,+ unknown+ >;++ assert.equal(result.prompt_cache_retention, undefined, "prompt_cache_retention must be stripped");+ assert.equal(result.safety_identifier, undefined, "safety_identifier must be stripped");+ assert.equal(result.user, undefined, "user must be stripped");+ // The real request payload must survive the strip.+ assert.ok(Array.isArray(result.input), "input array preserved");+});++test.after(() => {+ try {+ core.resetDbInstance?.();+ } catch {+ /* ignore */+ }+ try {+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });+ } catch {+ /* ignore */+ }+});diff --git a/tests/unit/combo-auto-candidate-expansion.test.ts b/tests/unit/combo-auto-candidate-expansion.test.tsnew file mode 100644index 0000000000..61d51200f2--- /dev/null+++ b/tests/unit/combo-auto-candidate-expansion.test.ts@@ -0,0 +1,127 @@+import test from "node:test";+import assert from "node:assert/strict";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";++// Regression coverage for the #3322 auto-combo candidate expansion: an auto-combo+// without an explicit candidatePool broadens its eligible targets to every model+// of every active provider connection (so the router has the full pool to score).++const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-combo-expand-"));+const ORIGINAL_DATA_DIR = process.env.DATA_DIR;+process.env.DATA_DIR = TEST_DATA_DIR;++const core = await import("../../src/lib/db/core.ts");+const providersDb = await import("../../src/lib/db/providers.ts");+const combo = await import("../../open-sse/services/combo.ts");+const providerModels = await import("../../open-sse/config/providerModels.ts");++function resetStorage() {+ core.resetDbInstance();+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });+ fs.mkdirSync(TEST_DATA_DIR, { recursive: true });+}++test.beforeEach(() => resetStorage());++test.after(() => {+ core.resetDbInstance();+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });+ if (ORIGINAL_DATA_DIR === undefined) delete process.env.DATA_DIR;+ else process.env.DATA_DIR = ORIGINAL_DATA_DIR;+});++test("expandAutoComboCandidatePool adds every model of an active provider when no candidatePool is set", async () => {+ await providersDb.createProviderConnection({+ provider: "openai",+ authType: "apikey",+ name: "OpenAI",+ apiKey: "sk-test-openai",+ defaultModel: "gpt-4o-mini",+ });++ const expanded = await combo.expandAutoComboCandidatePool([], { config: {} });++ // It should surface at least one openai/<model> target, all well-formed.+ assert.ok(expanded.length > 0, "expected the active provider's models to be expanded in");+ const openaiTargets = expanded.filter((t) => t.provider === "openai");+ assert.ok(openaiTargets.length > 0, "expected openai targets");+ for (const t of openaiTargets) {+ assert.equal(t.kind, "model");+ assert.equal(t.modelStr, `openai/${t.modelStr.split("/").slice(1).join("/")}`);+ assert.equal(t.connectionId, null);+ }+ // Every catalog model for openai should be represented.+ const catalogIds = providerModels.getProviderModels("openai").map((m) => `openai/${m.id}`);+ assert.ok(catalogIds.length > 0);+ for (const id of catalogIds) {+ assert.ok(+ expanded.some((t) => t.modelStr === id),+ `expected expanded targets to include ${id}`+ );+ }+});++test("expandAutoComboCandidatePool is a no-op when an explicit candidatePool exists", async () => {+ await providersDb.createProviderConnection({+ provider: "openai",+ authType: "apikey",+ name: "OpenAI",+ apiKey: "sk-test-openai",+ defaultModel: "gpt-4o-mini",+ });++ const seed = [+ {+ kind: "model" as const,+ stepId: "openai/gpt-4o",+ executionKey: "openai/gpt-4o",+ modelStr: "openai/gpt-4o",+ provider: "openai",+ providerId: "openai",+ connectionId: null,+ weight: 1,+ label: null,+ },+ ];+ const result = await combo.expandAutoComboCandidatePool(seed, {+ config: { auto: { candidatePool: ["openai"] } },+ });+ assert.equal(result.length, 1, "candidatePool present → no expansion");+ assert.equal(result[0].modelStr, "openai/gpt-4o");+});++test("expandAutoComboCandidatePool does not duplicate an already-present modelStr", async () => {+ await providersDb.createProviderConnection({+ provider: "openai",+ authType: "apikey",+ name: "OpenAI",+ apiKey: "sk-test-openai",+ defaultModel: "gpt-4o-mini",+ });++ const firstCatalogId = providerModels.getProviderModels("openai")[0]?.id;+ assert.ok(firstCatalogId, "expected at least one openai catalog model");+ const existing = `openai/${firstCatalogId}`;+ const seed = [+ {+ kind: "model" as const,+ stepId: existing,+ executionKey: existing,+ modelStr: existing,+ provider: "openai",+ providerId: "openai",+ connectionId: "conn-1",+ weight: 5,+ label: "pinned",+ },+ ];++ const result = await combo.expandAutoComboCandidatePool(seed, { config: {} });+ const matches = result.filter((t) => t.modelStr === existing);+ assert.equal(matches.length, 1, "the pre-existing target must not be duplicated");+ // …and the original pinned entry (weight 5 / conn-1) is preserved, not overwritten.+ assert.equal(matches[0].connectionId, "conn-1");+ assert.equal(matches[0].weight, 5);+});diff --git a/tests/unit/combo-custom-provider-resolution.test.ts b/tests/unit/combo-custom-provider-resolution.test.tsindex ae8a30bad0..2f8e781a31 100644--- a/tests/unit/combo-custom-provider-resolution.test.ts+++ b/tests/unit/combo-custom-provider-resolution.test.ts@@ -165,7 +165,7 @@ test("custom provider auth lookup search pool maps alias prefixes to internal pr);assert.match(authSrc,- /nodePrefix === provider \|\| nodePrefix === canonicalProvider \|\| nodePrefix === canonicalAlias/,+ /nodePrefix === provider\s*\|\|\s*nodePrefix === canonicalProvider\s*\|\|\s*nodePrefix === canonicalAlias/,"auth lookup should match provider node prefixes against the requested alias/canonical provider values");assert.match(diff --git a/tests/unit/completions-provider-removed.test.ts b/tests/unit/completions-provider-removed.test.tsnew file mode 100644index 0000000000..f818902c7c--- /dev/null+++ b/tests/unit/completions-provider-removed.test.ts@@ -0,0 +1,26 @@+import test from "node:test";+import assert from "node:assert/strict";++import { REGISTRY } from "../../open-sse/config/providerRegistry.ts";+import { APIKEY_PROVIDERS } from "../../src/shared/constants/providers.ts";+import { FREE_MODEL_BUDGETS } from "../../open-sse/config/freeModelCatalog.data.ts";++// Regression guard for discussion #3293: "Completions.me" (provider id `completions`,+// alias `cpl`, https://completions.me) was a bundled preset advertising free unlimited+// access to premium models. It is a Rickroll endpoint -- verified empirically on+// 2026-06-06: a real key against /api/v1/chat/completions returns the Rick Astley+// lyrics ("Never gonna give you up...") for every model/prompt, with zeroed usage.+// It must stay out of every provider catalog so nobody wires it up by accident.++test("completions (Completions.me) provider is removed from the chat registry", () => {+ assert.equal(REGISTRY["completions"], undefined);+});++test("completions (Completions.me) provider is removed from the API-key provider presets", () => {+ assert.equal((APIKEY_PROVIDERS as Record<string, unknown>)["completions"], undefined);+});++test("completions (Completions.me) has no entries in the free model catalog", () => {+ const offenders = FREE_MODEL_BUDGETS.filter((b) => b.provider === "completions");+ assert.deepEqual(offenders, []);+});diff --git a/tests/unit/dev-ensure-native-sqlite.test.ts b/tests/unit/dev-ensure-native-sqlite.test.tsnew file mode 100644index 0000000000..31fd39c886--- /dev/null+++ b/tests/unit/dev-ensure-native-sqlite.test.ts@@ -0,0 +1,112 @@+import { test } from "node:test";+import assert from "node:assert/strict";++import {+ ensureNativeSqlite,+ isNativeAbiMismatch,+} from "../../scripts/dev/ensure-native-sqlite.mjs";++// A binary path that is guaranteed to exist so the existsSync() guard passes;+// the injected probe controls the actual outcome.+const EXISTING_PATH = process.execPath;+const silentLogger = { warn() {}, error() {}, log() {} };++// The exact message a Node 24 process produces against a Node 22 (ABI 127) binary.+const ABI_ERROR =+ "The module '/x/node_modules/better-sqlite3/build/Release/better_sqlite3.node' " ++ "was compiled against a different Node.js version using NODE_MODULE_VERSION 127. " ++ "This version of Node.js requires NODE_MODULE_VERSION 137.";++test("isNativeAbiMismatch detects ABI / native-load errors", () => {+ assert.equal(isNativeAbiMismatch(ABI_ERROR), true);+ assert.equal(isNativeAbiMismatch("Module did not self-register"), true);+ assert.equal(isNativeAbiMismatch("ERR_DLOPEN_FAILED: bad bits"), true);+ assert.equal(isNativeAbiMismatch("Could not locate the bindings file"), true);+});++test("isNativeAbiMismatch ignores unrelated errors", () => {+ assert.equal(isNativeAbiMismatch("SQLITE_ERROR: no such table: foo"), false);+ assert.equal(isNativeAbiMismatch("ENOENT: no such file"), false);+ assert.equal(isNativeAbiMismatch(""), false);+ assert.equal(isNativeAbiMismatch(null), false);+ assert.equal(isNativeAbiMismatch(undefined), false);+});++test("ensureNativeSqlite: healthy binary does nothing (fast path)", () => {+ let rebuilt = 0;+ const res = ensureNativeSqlite({+ logger: silentLogger,+ binaryPath: EXISTING_PATH,+ probe: () => {+ /* loads fine */+ },+ rebuild: () => {+ rebuilt++;+ return true;+ },+ });+ assert.deepEqual(res, { ok: true, rebuilt: false });+ assert.equal(rebuilt, 0, "must not rebuild when the ABI already matches");+});++test("ensureNativeSqlite: ABI mismatch triggers exactly one rebuild", () => {+ let rebuilt = 0;+ const res = ensureNativeSqlite({+ logger: silentLogger,+ binaryPath: EXISTING_PATH,+ probe: () => {+ throw new Error(ABI_ERROR);+ },+ rebuild: () => {+ rebuilt++;+ return true;+ },+ });+ assert.equal(res.ok, true);+ assert.equal(res.rebuilt, true);+ assert.equal(rebuilt, 1, "rebuild must run once on ABI mismatch");+});++test("ensureNativeSqlite: failed rebuild reports ok=false", () => {+ const res = ensureNativeSqlite({+ logger: silentLogger,+ binaryPath: EXISTING_PATH,+ probe: () => {+ throw new Error(ABI_ERROR);+ },+ rebuild: () => false,+ });+ assert.equal(res.ok, false);+ assert.equal(res.rebuilt, false);+});++test("ensureNativeSqlite: unrelated load error is NOT swallowed and does not rebuild", () => {+ let rebuilt = 0;+ const res = ensureNativeSqlite({+ logger: silentLogger,+ binaryPath: EXISTING_PATH,+ probe: () => {+ throw new Error("SQLITE_CANTOPEN: unable to open database file");+ },+ rebuild: () => {+ rebuilt++;+ return true;+ },+ });+ assert.equal(res.ok, false);+ assert.equal(res.rebuilt, false);+ assert.ok(res.error instanceof Error);+ assert.equal(rebuilt, 0, "must not rebuild for unrelated errors");+});++test("ensureNativeSqlite: missing binary is a no-op (pre-install)", () => {+ const res = ensureNativeSqlite({+ logger: silentLogger,+ binaryPath: "/path/that/does/not/exist/better_sqlite3.node",+ probe: () => {+ throw new Error("should not be called");+ },+ rebuild: () => true,+ });+ assert.deepEqual(res, { ok: true, rebuilt: false });+});diff --git a/tests/unit/empty-response-hardening.test.ts b/tests/unit/empty-response-hardening.test.tsnew file mode 100644index 0000000000..0f7ace6296--- /dev/null+++ b/tests/unit/empty-response-hardening.test.ts@@ -0,0 +1,83 @@+import { describe, it } from "node:test";+import assert from "node:assert";+import { hasValuableContent } from "../../open-sse/utils/streamHelpers.ts";+import { FORMATS } from "../../open-sse/translator/formats.ts";++describe("empty-response hardening", () => {+ describe("hasValuableContent edge cases", () => {+ it("returns false for choices: [] (empty array)", () => {+ const chunk = { choices: [] };+ assert.strictEqual(hasValuableContent(chunk, FORMATS.OPENAI), false);+ });++ it("returns false for missing choices entirely", () => {+ const chunk = { id: "test-123" };+ assert.strictEqual(hasValuableContent(chunk, FORMATS.OPENAI), false);+ });++ it("returns false for choices with null delta", () => {+ const chunk = { choices: [{ delta: null, finish_reason: null }] };+ assert.strictEqual(hasValuableContent(chunk, FORMATS.OPENAI), false);+ });++ it("returns true for choices with finish_reason stop", () => {+ const chunk = { choices: [{ delta: {}, finish_reason: "stop" }] };+ assert.strictEqual(hasValuableContent(chunk, FORMATS.OPENAI), true);+ });++ it("returns true for choices with finish_reason tool_calls", () => {+ const chunk = { choices: [{ delta: {}, finish_reason: "tool_calls" }] };+ assert.strictEqual(hasValuableContent(chunk, FORMATS.OPENAI), true);+ });+ });++ describe("empty choices array detection", () => {+ it("should be detected by Array.isArray + length === 0", () => {+ const parsed = { choices: [], id: "test", model: "gpt-4" };+ assert.strictEqual(Array.isArray(parsed.choices), true);+ assert.strictEqual(parsed.choices.length, 0);+ });++ it("should NOT trigger for choices with one element", () => {+ const parsed = { choices: [{ delta: { content: "hi" } }], id: "test" };+ assert.strictEqual(Array.isArray(parsed.choices), true);+ assert.strictEqual(parsed.choices.length, 1);+ });++ it("should NOT trigger for choices with finish_reason only", () => {+ const parsed = { choices: [{ delta: {}, finish_reason: "stop" }], id: "test" };+ assert.strictEqual(Array.isArray(parsed.choices), true);+ assert.strictEqual(parsed.choices.length, 1);+ });+ });++ describe("tool completion empty response detection", () => {+ it("detects empty content and reasoning after tool_calls", () => {+ const passthroughHasToolCalls = true;+ const content = "";+ const reasoning = "";+ assert.strictEqual(passthroughHasToolCalls && !content.trim() && !reasoning.trim(), true);+ });++ it("does NOT trigger when content exists after tool_calls", () => {+ const passthroughHasToolCalls = true;+ const content = "Done!";+ const reasoning = "";+ assert.strictEqual(passthroughHasToolCalls && !content.trim() && !reasoning.trim(), false);+ });++ it("does NOT trigger when reasoning exists after tool_calls", () => {+ const passthroughHasToolCalls = true;+ const content = "";+ const reasoning = "Let me think...";+ assert.strictEqual(passthroughHasToolCalls && !content.trim() && !reasoning.trim(), false);+ });++ it("does NOT trigger when no tool_calls occurred", () => {+ const passthroughHasToolCalls = false;+ const content = "";+ const reasoning = "";+ assert.strictEqual(passthroughHasToolCalls && !content.trim() && !reasoning.trim(), false);+ });+ });+});diff --git a/tests/unit/executor-default-base.test.ts b/tests/unit/executor-default-base.test.tsindex fcbf29474e..7469ffce84 100644--- a/tests/unit/executor-default-base.test.ts+++ b/tests/unit/executor-default-base.test.ts@@ -97,15 +97,15 @@ test("DefaultExecutor.buildUrl handles Gemini, Claude and Qwen variants", () =>test("DefaultExecutor.buildUrl uses full chat endpoints for hosted OpenAI-compatible providers", () => {const bazaarlink = new DefaultExecutor("bazaarlink");- const completions = new DefaultExecutor("completions");+ const crof = new DefaultExecutor("crof");assert.equal(bazaarlink.buildUrl("auto:free", true),"https://bazaarlink.ai/api/v1/chat/completions");assert.equal(- completions.buildUrl("gpt-4.1", true),- "https://completions.me/api/v1/chat/completions"+ crof.buildUrl("gpt-4.1", true),+ "https://crof.ai/v1/chat/completions");});diff --git a/tests/unit/mcp-model-catalog.test.ts b/tests/unit/mcp-model-catalog.test.tsnew file mode 100644index 0000000000..0d4c677201--- /dev/null+++ b/tests/unit/mcp-model-catalog.test.ts@@ -0,0 +1,147 @@+import test from "node:test";+import assert from "node:assert/strict";++import { getMcpModelsCatalog } from "../../open-sse/mcp-server/server.ts";++test("getMcpModelsCatalog aggregates only active connection model endpoints", async () => {+ const calls: string[] = [];++ const result = await getMcpModelsCatalog(+ {},+ {+ listProviderConnections: async () => [+ { id: "conn-github", provider: "github", isActive: true },+ { id: "conn-codex", provider: "codex", isActive: false },+ ],+ fetchJson: async (path: string) => {+ calls.push(path);+ if (path === "/api/providers/conn-github/models?excludeHidden=true") {+ return {+ source: "api",+ models: [+ { id: "gpt-4.1", owned_by: "github", supportedEndpoints: ["chat"] },+ {+ id: "text-embedding-3-small",+ owned_by: "github",+ supportedEndpoints: ["embeddings"],+ },+ ],+ };+ }++ throw new Error(`Unexpected path: ${path}`);+ },+ }+ );++ assert.deepEqual(calls, ["/api/providers/conn-github/models?excludeHidden=true"]);+ assert.deepEqual(result, {+ models: [+ {+ id: "gpt-4.1",+ provider: "github",+ capabilities: ["chat"],+ status: "available",+ pricing: undefined,+ },+ {+ id: "text-embedding-3-small",+ provider: "github",+ capabilities: ["embedding"],+ status: "available",+ pricing: undefined,+ },+ ],+ source: "api",+ });+});++test("getMcpModelsCatalog exposes codex default thinking effort when no override is stored", async () => {+ const result = await getMcpModelsCatalog(+ { provider: "codex" },+ {+ listProviderConnections: async () => [+ {+ id: "conn-codex",+ provider: "codex",+ isActive: true,+ providerSpecificData: {},+ },+ ],+ fetchJson: async () => ({+ source: "api",+ models: [{ id: "gpt-5.5", owned_by: "codex", supportedEndpoints: ["chat"] }],+ }),+ }+ );++ assert.equal(result.models.length, 1);+ assert.equal(result.models[0]?.thinkingEffort, "medium");+});++test("getMcpModelsCatalog exposes stored thinking effort overrides", async () => {+ const result = await getMcpModelsCatalog(+ { provider: "chatgpt-web" },+ {+ listProviderConnections: async () => [+ {+ id: "conn-chatgpt",+ provider: "chatgpt-web",+ isActive: true,+ providerSpecificData: { thinkingEffort: "extended" },+ },+ ],+ fetchJson: async () => ({+ source: "api",+ models: [{ id: "gpt-5", owned_by: "chatgpt-web", supportedEndpoints: ["chat"] }],+ }),+ }+ );++ assert.equal(result.models.length, 1);+ assert.equal(result.models[0]?.thinkingEffort, "extended");+});++test("getMcpModelsCatalog resolves provider aliases to active connection ids", async () => {+ const calls: string[] = [];++ const result = await getMcpModelsCatalog(+ { provider: "gh", capability: "chat" },+ {+ listProviderConnections: async () => [+ { id: "conn-github", provider: "github", isActive: true },+ { id: "conn-codex", provider: "codex", isActive: true },+ ],+ fetchJson: async (path: string) => {+ calls.push(path);+ return {+ source: "api",+ models: [{ id: "gpt-4.1", owned_by: "github", supportedEndpoints: ["chat"] }],+ };+ },+ }+ );++ assert.deepEqual(calls, ["/api/providers/conn-github/models?excludeHidden=true"]);+ assert.equal(result.models.length, 1);+ assert.equal(result.models[0]?.provider, "github");+ assert.deepEqual(result.models[0]?.capabilities, ["chat"]);+});++test("getMcpModelsCatalog returns empty result when requested provider has no active connection", async () => {+ const result = await getMcpModelsCatalog(+ { provider: "github" },+ {+ listProviderConnections: async () => [{ id: "conn-codex", provider: "codex", isActive: true }],+ fetchJson: async () => {+ throw new Error("fetchJson should not be called without a matching active provider");+ },+ }+ );++ assert.deepEqual(result, {+ models: [],+ source: "provider_connections",+ warning: "No active connections found for provider 'github'.",+ });+});\ No newline at end of filediff --git a/tests/unit/model-test-runner.test.ts b/tests/unit/model-test-runner.test.tsnew file mode 100644index 0000000000..dbdced176b--- /dev/null+++ b/tests/unit/model-test-runner.test.ts@@ -0,0 +1,88 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import { parseRetryAfterHeader, detectTestKind } from "@/lib/api/modelTestRunner.ts";++// ---------------------------------------------------------------------------+// parseRetryAfterHeader — Retry-After is either delta-seconds or an HTTP-date.+// Regression guard for the rate-limit handling in runSingleModelTest (#3267).+// ---------------------------------------------------------------------------++test("parseRetryAfterHeader returns undefined for missing/empty/null input", () => {+ assert.equal(parseRetryAfterHeader(null), undefined);+ assert.equal(parseRetryAfterHeader(undefined), undefined);+ assert.equal(parseRetryAfterHeader(""), undefined);+ assert.equal(parseRetryAfterHeader(" "), undefined);+});++test("parseRetryAfterHeader parses delta-seconds (numeric form)", () => {+ assert.equal(parseRetryAfterHeader("0"), 0);+ assert.equal(parseRetryAfterHeader("30"), 30);+ assert.equal(parseRetryAfterHeader("120"), 120);+ // fractional seconds round up (ceil) so we never under-wait+ assert.equal(parseRetryAfterHeader("1.2"), 2);+});++test("parseRetryAfterHeader rejects non-date garbage and never yields a misleading positive wait", () => {+ // Pure garbage with no parseable date → undefined.+ assert.equal(parseRetryAfterHeader("soon"), undefined);+ assert.equal(parseRetryAfterHeader("NaN"), undefined);+ // A negative numeric is not accepted on the numeric path (>= 0 guard); it+ // falls through to Date.parse, which yields a past date → clamped to 0.+ // The important guarantee is that it never produces a positive wait.+ const negative = parseRetryAfterHeader("-5");+ assert.ok(negative === undefined || negative === 0, `expected 0/undefined, got ${negative}`);+});++test("parseRetryAfterHeader parses an HTTP-date into a non-negative seconds delta", () => {+ // A date ~10s in the future should yield a small positive integer (>=0).+ const future = new Date(Date.now() + 10_000).toUTCString();+ const secs = parseRetryAfterHeader(future);+ assert.ok(typeof secs === "number");+ assert.ok(secs >= 0 && secs <= 11, `expected ~10s, got ${secs}`);++ // A date in the past clamps to 0 (never negative).+ const past = new Date(Date.now() - 60_000).toUTCString();+ assert.equal(parseRetryAfterHeader(past), 0);+});++// ---------------------------------------------------------------------------+// detectTestKind — picks the right test endpoint (chat / embeddings / rerank)+// from the model id + custom-model metadata. Rerank must win over embedding.+// ---------------------------------------------------------------------------++test("detectTestKind defaults to a plain chat test for ordinary models", () => {+ assert.deepEqual(detectTestKind("openai/gpt-4o", null), {+ isRerank: false,+ isEmbedding: false,+ });+});++test("detectTestKind detects embeddings by id heuristics", () => {+ for (const id of [+ "openai/text-embedding-3-small",+ "jina/jina-embeddings-v3",+ "baai/bge-m3",+ "jinaai/jina-clip-v2",+ "colbert-ir/colbertv2",+ ]) {+ assert.equal(detectTestKind(id, null).isEmbedding, true, `${id} should be embedding`);+ assert.equal(detectTestKind(id, null).isRerank, false, `${id} should not be rerank`);+ }+});++test("detectTestKind detects rerank by id and by metadata, and rerank wins over embedding", () => {+ assert.deepEqual(detectTestKind("jina/jina-reranker-v2", null), {+ isRerank: true,+ isEmbedding: false,+ });+ // apiFormat metadata drives detection even when the id is opaque+ assert.equal(detectTestKind("vendor/opaque-model", { apiFormat: "rerank" }).isRerank, true);+ assert.equal(+ detectTestKind("vendor/opaque-model", { supportedEndpoints: ["embeddings"] }).isEmbedding,+ true+ );+ // A model that looks like both rerank and embedding resolves to rerank only.+ const both = detectTestKind("vendor/rerank-embedding-hybrid", null);+ assert.equal(both.isRerank, true);+ assert.equal(both.isEmbedding, false);+});diff --git a/tests/unit/models-catalog-route.test.ts b/tests/unit/models-catalog-route.test.tsindex 0362778920..8d13a7f010 100644--- a/tests/unit/models-catalog-route.test.ts+++ b/tests/unit/models-catalog-route.test.ts@@ -122,6 +122,48 @@ test("v1 models catalog accepts bearer API keys and filters the list by allowed);});+test("v1 models catalog does NOT accept API keys supplied via query string (#3300 security follow-up)", async () => {+ // Query-string token fallbacks (`?token=`/`?key=`/`?apiKey=`/`?api_key=`) were+ // intentionally removed — a credential in the query string leaks into access+ // logs / Referer headers. The VS Code integration uses the path-scoped+ // `/vscode/<token>/…` form instead (covered by the next test). So a `?token=`+ // on the catalog route is no longer a usable credential → auth fails.+ await settingsDb.updateSettings({+ requireLogin: true,+ password: "hashed-password",+ requireAuthForModels: true,+ });+ await seedConnection("openai", { name: "openai-query-auth" });++ const key = await apiKeysDb.createApiKey("catalog-query-auth", "machine-catalog-query");++ const response = await v1ModelsCatalog.getUnifiedModelsResponse(+ new Request(`http://localhost/api/v1/models?token=${encodeURIComponent(key.key)}`)+ );++ assert.equal(response.status, 401);+});++test("v1 models catalog accepts API keys embedded in vscode path aliases when auth is required", async () => {+ await settingsDb.updateSettings({+ requireLogin: true,+ password: "hashed-password",+ requireAuthForModels: true,+ });+ await seedConnection("openai", { name: "openai-path-auth" });++ const key = await apiKeysDb.createApiKey("catalog-path-auth", "machine-catalog-path");++ const response = await v1ModelsCatalog.getUnifiedModelsResponse(+ new Request(`http://localhost/api/v1/vscode/${encodeURIComponent(key.key)}/models`)+ );+ const body = (await response.json()) as any;++ assert.equal(response.status, 200);+ assert.ok(Array.isArray(body.data));+ assert.ok(body.data.length > 0);+});+test("v1 models catalog hides models excluded by every active connection while keeping models served by at least one account", async () => {const first = await seedConnection("openai", {name: "openai-first",@@ -617,7 +659,13 @@ test("v1 models catalog exposes Antigravity client-visible preview aliases insteassert.equal(response.status, 200);assert.ok(ids.has("antigravity/gemini-3-pro-preview"));assert.ok(ids.has("antigravity/gemini-3-flash-preview"));- assert.equal(ids.has("antigravity/gemini-3.1-pro-high"), false);+ // #3184/#3303: the Gemini budget tiers (`-high`/`-low`) are user-callable+ // client-visible aliases on the Antigravity OAuth backend (agy parity), so+ // they ARE now exposed in the catalog. (They alias to the plain+ // `gemini-3.1-pro` upstream id — see ANTIGRAVITY_MODEL_ALIASES.)+ assert.ok(ids.has("antigravity/gemini-3.1-pro-high"));+ // The legacy `gemini-claude-*` ids are alias KEYS (remapped to live upstream+ // ids), not public catalog entries, so they stay unexposed.assert.equal(ids.has("antigravity/gemini-claude-sonnet-4-5"), false);assert.equal(ids.has("antigravity/gemini-claude-sonnet-4-5-thinking"), false);assert.equal(ids.has("antigravity/gemini-claude-opus-4-5-thinking"), false);@@ -1340,6 +1388,38 @@ test("v1 models catalog prefers manual combo context_length over auto-calculatedassert.equal(comboModel.context_length, 64000, "manual context_length should override auto-calc");});+test("v1 models catalog computes combo context_length from known targets when some targets have unknown context", async () => {+ await seedConnection("openai", { name: "openai-mixed-context" });+ await seedConnection("claude", {+ authType: "oauth",+ name: "claude-mixed-context",+ apiKey: null,+ accessToken: "claude-access",+ });++ // Create a combo with targets: one known (gpt-4o = 128K), one unknown (nonexistent-model).+ // The combo should still compute context_length = 128K from the known target.+ const combo = await combosDb.createCombo({+ name: "mixed-context-combo",+ strategy: "priority",+ models: ["openai/gpt-4o", "openai/nonexistent-model-xyz"],+ });++ const response = await v1ModelsCatalog.getUnifiedModelsResponse(+ new Request("http://localhost/api/v1/models")+ );+ const body = (await response.json()) as any;+ const comboModel = body.data.find((item) => item.id === "mixed-context-combo");++ assert.equal(response.status, 200);+ assert.ok(comboModel);+ assert.equal(+ comboModel.context_length,+ 128000,+ "combo context_length should be the MIN of known target model limits, ignoring unknown targets"+ );+});+// Regression test for Issue #2798: noAuth providers (opencode/oc) have no DB connection rows// but their models must still appear in /v1/models.test("v1 models catalog includes noAuth provider models when no DB connections exist (#2798)", async () => {diff --git a/tests/unit/provider-models-route.test.ts b/tests/unit/provider-models-route.test.tsindex d86ee3c2e0..15570c2be4 100644--- a/tests/unit/provider-models-route.test.ts+++ b/tests/unit/provider-models-route.test.ts@@ -469,6 +469,27 @@ test("provider models route returns the updated local catalog for GitHub Copilot);});+test("provider models route returns codex gpt-5.4 effort variants in the local catalog", async () => {+ const connection = await seedConnection("codex", {+ authType: "oauth",+ apiKey: null,+ accessToken: "codex-access",+ });++ const response = await callRoute(connection.id);+ const body = (await response.json()) as any;+ const modelIds = new Set((body.models || []).map((model: any) => model.id));++ assert.equal(response.status, 200);+ assert.equal(body.provider, "codex");+ assert.equal(body.source, "local_catalog");+ assert.ok(modelIds.has("gpt-5.4"));+ assert.ok(modelIds.has("gpt-5.4-low"));+ assert.ok(modelIds.has("gpt-5.4-medium"));+ assert.ok(modelIds.has("gpt-5.4-high"));+ assert.ok(modelIds.has("gpt-5.4-xhigh"));+});+test("provider models route returns the expanded local catalog for Kiro", async () => {const connection = await seedConnection("kiro", {authType: "oauth",diff --git a/tests/unit/provider-rate-limit-overrides-schema.test.ts b/tests/unit/provider-rate-limit-overrides-schema.test.tsnew file mode 100644index 0000000000..84bca5b7f9--- /dev/null+++ b/tests/unit/provider-rate-limit-overrides-schema.test.ts@@ -0,0 +1,73 @@+import { test } from "node:test";+import assert from "node:assert/strict";++import { updateProviderConnectionSchema } from "../../src/shared/validation/schemas";++function parse(overrides: unknown) {+ return updateProviderConnectionSchema.safeParse({+ name: "test-provider",+ rateLimitOverrides: overrides,+ });+}++test("rateLimitOverrides: valid object with all fields", () => {+ const r = parse({ rpm: 100, tpm: 50000, tpd: 1000000, minTime: 100, maxConcurrent: 5 });+ assert.ok(r.success, String(r.error));+ assert.deepEqual(r.data.rateLimitOverrides, { rpm: 100, tpm: 50000, tpd: 1000000, minTime: 100, maxConcurrent: 5 });+});++test("rateLimitOverrides: partial fields", () => {+ const r = parse({ rpm: 60 });+ assert.ok(r.success, String(r.error));+ assert.deepEqual(r.data.rateLimitOverrides, { rpm: 60 });+});++test("rateLimitOverrides: null clears overrides", () => {+ const r = parse(null);+ assert.ok(r.success, String(r.error));+ assert.equal(r.data.rateLimitOverrides, null);+});++test("rateLimitOverrides: undefined is valid", () => {+ const r = updateProviderConnectionSchema.safeParse({ name: "test-provider" });+ assert.ok(r.success, String(r.error));+ assert.equal(r.data.rateLimitOverrides, undefined);+});++test("rateLimitOverrides: string coerced to number", () => {+ const r = parse({ rpm: "120" });+ assert.ok(r.success, String(r.error));+ assert.equal(r.data.rateLimitOverrides.rpm, 120);+});++test("rateLimitOverrides: rejects negative rpm", () => {+ assert.equal(parse({ rpm: -1 }).success, false);+});++test("rateLimitOverrides: rejects float rpm", () => {+ assert.equal(parse({ rpm: 1.5 }).success, false);+});++test("rateLimitOverrides: rejects rpm above max", () => {+ assert.equal(parse({ rpm: 1_000_001 }).success, false);+});++test("rateLimitOverrides: rejects tpm above max", () => {+ assert.equal(parse({ tpm: 100_000_001 }).success, false);+});++test("rateLimitOverrides: rejects non-object", () => {+ assert.equal(parse("bad").success, false);+ assert.equal(parse(42).success, false);+ assert.equal(parse([1]).success, false);+});++test("rateLimitOverrides: empty object is valid", () => {+ const r = parse({});+ assert.ok(r.success, String(r.error));+});++test("rateLimitOverrides: all zeros is valid", () => {+ const r = parse({ rpm: 0, tpm: 0, tpd: 0, minTime: 0, maxConcurrent: 0 });+ assert.ok(r.success, String(r.error));+});diff --git a/tests/unit/providers-page-utils.test.ts b/tests/unit/providers-page-utils.test.tsindex fc508582fb..eedcd16049 100644--- a/tests/unit/providers-page-utils.test.ts+++ b/tests/unit/providers-page-utils.test.ts@@ -80,6 +80,40 @@ test("configured-only filter keeps only providers with saved connections", () =>assert.equal(providerPageUtils.filterConfiguredProviderEntries(entries, false).length, 3);});+test("configured-only filter keeps no-auth providers even without a saved connection (#3290)", () => {+ const entries = [+ {+ providerId: "claude",+ provider: { id: "claude" },+ stats: { total: 0 },+ displayAuthType: "oauth",+ toggleAuthType: "oauth",+ },+ {+ providerId: "opencode",+ provider: { id: "opencode" },+ stats: { total: 0 },+ displayAuthType: "no-auth",+ toggleAuthType: "no-auth",+ },+ {+ providerId: "duckduckgo-web",+ provider: { id: "duckduckgo-web" },+ stats: { total: 0 },+ displayAuthType: "no-auth",+ toggleAuthType: "no-auth",+ },+ ];++ // no-auth providers never create a DB connection row (total === 0) but are+ // always usable and appear in /v1/models — they must survive the filter.+ const visible = providerPageUtils.filterConfiguredProviderEntries(entries, true);+ assert.deepEqual(+ visible.map((entry) => entry.providerId),+ ["duckduckgo-web", "opencode"]+ );+});+test("search filter matches provider name and id case-insensitively", () => {const entries = [{diff --git a/tests/unit/response-sanitizer.test.ts b/tests/unit/response-sanitizer.test.tsindex 837130ce95..5c716aebd5 100644--- a/tests/unit/response-sanitizer.test.ts+++ b/tests/unit/response-sanitizer.test.ts@@ -364,6 +364,50 @@ test("sanitizeStreamingChunk preserves Copilot reasoning_text deltas", () => {assert.equal((sanitized as any).choices[0].delta.reasoning_text, "copilot reasoning");});+test("sanitizeStreamingChunk strips commentary content from Responses completed events", () => {+ const sanitized = sanitizeStreamingChunk({+ type: "response.completed",+ response: {+ id: "resp_1",+ object: "response",+ model: "gpt-5.1-codex",+ status: "completed",+ output_text: "hiddenshown",+ output: [+ {+ id: "msg_1",+ type: "message",+ role: "assistant",+ content: [+ { type: "output_text", text: "hidden", phase: "commentary" },+ { type: "output_text", text: "shown", phase: "final_answer" },+ ],+ },+ ],+ },+ });++ assert.equal((sanitized as any).response.output[0].content.length, 1);+ assert.equal((sanitized as any).response.output[0].content[0].text, "shown");+ assert.equal((sanitized as any).response.output_text, "shown");+});++test("sanitizeStreamingChunk marks internal Responses output_item events for omission", () => {+ const sanitized = sanitizeStreamingChunk({+ type: "response.output_item.done",+ item: {+ id: "msg_internal",+ type: "message",+ role: "assistant",+ phase: "commentary",+ content: [{ type: "output_text", text: "hidden" }],+ },+ });++ assert.equal((sanitized as any).__omniroute_omit_streaming_chunk, true);+ assert.equal("item" in (sanitized as any), false);+});+test("sanitizeOpenAIResponse preserves reasoning_content when tool_calls are present", () => {// Bug fix: Kimi and other thinking-enabled providers require reasoning_content// on assistant messages that contain tool_calls. The sanitizer was stripping@@ -511,3 +555,57 @@ test("sanitizeOpenAIResponse suppresses malformed textual pseudo tool-call conteassert.equal(JSON.stringify(sanitized).includes("[Tool call:"), false);assert.equal(JSON.stringify(sanitized).includes("Arguments:"), false);});++test("sanitizeOpenAIResponse strips leaked internal to=functions tool envelopes from assistant text", () => {+ const sanitized = sanitizeOpenAIResponse({+ id: "chatcmpl_internal_tool_envelope",+ object: "chat.completion",+ created: 1,+ model: "MainAgent",+ choices: [+ {+ index: 0,+ finish_reason: "stop",+ message: {+ role: "assistant",+ content:+ 'Vou verificar agora.\n\nto=functions.run_in_terminal tokenjson\n{"command":"pwd","explanation":"Teste","goal":"Teste","mode":"sync","isBackground":false,"timeout":120000}\n\nResumo final.',+ },+ },+ ],+ }) as any;++ const message = sanitized.choices[0].message;+ assert.equal(message.content, "Vou verificar agora.\n\nResumo final.");+ assert.equal(JSON.stringify(sanitized).includes("to=functions.run_in_terminal"), false);+ assert.equal(JSON.stringify(sanitized).includes('"command":"pwd"'), false);+});++test("sanitizeResponsesApiResponse strips leaked multi_tool_use envelopes from Responses output_text", () => {+ const sanitized = sanitizeResponsesApiResponse({+ id: "resp_internal_tool_envelope",+ object: "response",+ created_at: 1,+ model: "gpt-5.1-codex",+ status: "completed",+ output: [+ {+ id: "msg_1",+ type: "message",+ role: "assistant",+ content: [+ {+ type: "output_text",+ text: 'Antes.\n\nto=multi_tool_use.parallel junkjson\n{"tool_uses":[{"recipient_name":"functions.read_file","parameters":{"filePath":"/tmp/a","startLine":1,"endLine":10}}]}\n\nDepois.',+ annotations: [],+ },+ ],+ },+ ],+ }) as any;++ assert.equal(sanitized.output[0].content[0].text, "Antes.\n\nDepois.");+ assert.equal(sanitized.output_text, "Antes.\n\nDepois.");+ assert.equal(JSON.stringify(sanitized).includes("to=multi_tool_use.parallel"), false);+ assert.equal(JSON.stringify(sanitized).includes("recipient_name"), false);+});diff --git a/tests/unit/route-guard-provider-login-local-only.test.ts b/tests/unit/route-guard-provider-login-local-only.test.tsnew file mode 100644index 0000000000..c935292c7e--- /dev/null+++ b/tests/unit/route-guard-provider-login-local-only.test.ts@@ -0,0 +1,38 @@+/**+ * Security regression (#3292): POST /api/providers/[id]/login launches a headful+ * Playwright Chromium (a child process) to drive a web-cookie login. It MUST be+ * classified as LOCAL_ONLY so loopback enforcement runs unconditionally before+ * any auth check — a leaked JWT over a Cloudflared/Ngrok tunnel cannot trigger a+ * browser spawn. Hard Rules #15 + #17. See docs/security/ROUTE_GUARD_TIERS.md.+ *+ * The login segment sits AFTER the dynamic `[id]` param, so it is matched by a+ * regex in LOCAL_ONLY_API_PATTERNS rather than a flat prefix — classifying the+ * whole `/api/providers/` subtree as LOCAL_ONLY would wrongly lock the remote+ * dashboard out of ordinary provider CRUD. These tests pin BOTH the gate AND the+ * narrowness (no over-match).+ */+import test from "node:test";+import assert from "node:assert/strict";+import { isLocalOnlyPath } from "../../src/server/authz/routeGuard.ts";++test("/api/providers/[id]/login is LOCAL_ONLY (spawns Playwright Chromium)", () => {+ assert.equal(isLocalOnlyPath("/api/providers/claude-web/login"), true);+ assert.equal(isLocalOnlyPath("/api/providers/abc-123/login"), true);+});++test("/api/providers/[id]/login with a trailing slash is LOCAL_ONLY", () => {+ assert.equal(isLocalOnlyPath("/api/providers/claude-web/login/"), true);+});++test("the provider-login gate does NOT over-match the rest of /api/providers", () => {+ // Ordinary provider management must stay remotely reachable.+ assert.equal(isLocalOnlyPath("/api/providers"), false);+ assert.equal(isLocalOnlyPath("/api/providers/"), false);+ assert.equal(isLocalOnlyPath("/api/providers/claude-web"), false);+ assert.equal(isLocalOnlyPath("/api/providers/claude-web/test"), false);+ assert.equal(isLocalOnlyPath("/api/providers/claude-web/models"), false);+ // Anchored: extra segments after /login are not the spawn route.+ assert.equal(isLocalOnlyPath("/api/providers/claude-web/login/extra"), false);+ // "login" must be its own segment, not a substring of the id.+ assert.equal(isLocalOnlyPath("/api/providers/login-helper/status"), false);+});diff --git a/tests/unit/sse-auth.test.ts b/tests/unit/sse-auth.test.tsindex 50576acc75..eef3b244f7 100644--- a/tests/unit/sse-auth.test.ts+++ b/tests/unit/sse-auth.test.ts@@ -89,6 +89,27 @@ test("extractApiKey parses bearer headers and isValidApiKey validates persisted),null);+ // Security follow-up (#3300): query-string token fallbacks were removed — a+ // credential in `?token=` must NOT be extracted (it leaks into logs/Referer).+ assert.equal(+ auth.extractApiKey(new Request(`http://localhost/v1/chat/completions?token=${created.key}`)),+ null+ );+ // The path-scoped `/vscode/<token>/…` form (VS Code integration) still works.+ assert.equal(+ auth.extractApiKey(+ new Request(`http://localhost/api/v1/vscode/${created.key}/chat/completions`)+ ),+ created.key+ );+ // …but never when the caller opts out of URL extraction (management auth path).+ assert.equal(+ auth.extractApiKey(+ new Request(`http://localhost/api/v1/vscode/${created.key}/chat/completions`),+ { allowUrl: false }+ ),+ null+ );assert.equal(await auth.isValidApiKey(created.key), true);assert.equal(await auth.isValidApiKey("sk-missing"), false);assert.equal(await auth.isValidApiKey(""), false);@@ -381,7 +402,9 @@ test("getProviderCredentialsWithQuotaPreflight: explicit quotaPreflightEnabled:f});// Give the connection per-window overrides (simulates a user-configured// threshold) — this is the field that previously caused the gate to keep going.- await (await import("../../src/lib/db/providers.ts")).updateProviderConnection(conn.id, {+ await (+ await import("../../src/lib/db/providers.ts")+ ).updateProviderConnection(conn.id, {quotaWindowThresholds: { primary: 50 },});@@ -680,7 +703,6 @@ test("getProviderCredentials retains rate-limited accounts when allowRateLimitedassert.equal(bypassed.connectionId, connection.id);});-test("getProviderCredentials retains terminal accounts for combo live tests", async () => {const connection = await seedConnection("openai", {name: "suppressed-terminal",diff --git a/tests/unit/stream-utils.test.ts b/tests/unit/stream-utils.test.tsindex 7a2bd35034..f8ab86f723 100644--- a/tests/unit/stream-utils.test.ts+++ b/tests/unit/stream-utils.test.ts@@ -1559,3 +1559,102 @@ test("createSSEStream passthrough mode decrements pending requests on failure",`pending request count for ${modelKey} should be 0 after failure, got ${count}`);});++test("createSSEStream passthrough emits synthetic error chunk for empty choices array", async () => {+ let onCompletePayload = null;+ const text = await readTransformed(+ [+ `data: ${JSON.stringify({+ id: "chatcmpl_empty",+ object: "chat.completion.chunk",+ created: 1,+ model: "kimi-k2.6",+ choices: [],+ })}\n\n`,+ `data: ${JSON.stringify({+ id: "chatcmpl_empty",+ object: "chat.completion.chunk",+ created: 1,+ model: "kimi-k2.6",+ choices: [{ index: 0, delta: { role: "assistant", content: "Hello" } }],+ })}\n\n`,+ `data: ${JSON.stringify({+ id: "chatcmpl_empty",+ object: "chat.completion.chunk",+ created: 1,+ model: "kimi-k2.6",+ choices: [{ index: 0, delta: {}, finish_reason: "stop" }],+ })}\n\n`,+ ],+ {+ mode: "passthrough",+ sourceFormat: FORMATS.OPENAI,+ provider: "opencode-go",+ model: "kimi-k2.6",+ body: { messages: [{ role: "user", content: "hello" }] },+ onComplete(payload) {+ onCompletePayload = payload;+ },+ }+ );++ // The empty choices chunk should have been replaced with a synthetic error chunk+ assert.match(text, /\[OmniRoute\] Upstream returned an empty response/);+ assert.match(text, /"finish_reason":"stop"/);+ // Subsequent valid chunks should still be present+ assert.match(text, /"content":"Hello"/);+ assert.equal(onCompletePayload.status, 200);+});++test("createSSEStream passthrough logs empty response after tool_calls completion", async () => {+ let onCompletePayload = null;+ const text = await readTransformed(+ [+ `data: ${JSON.stringify({+ id: "chatcmpl_tool_then_empty",+ object: "chat.completion.chunk",+ created: 1,+ model: "gpt-5.5-xhigh",+ choices: [+ {+ index: 0,+ delta: {+ tool_calls: [+ {+ index: 0,+ id: "call_tc",+ type: "function",+ function: { name: "task_complete", arguments: '{}' },+ },+ ],+ },+ },+ ],+ })}\n\n`,+ `data: ${JSON.stringify({+ id: "chatcmpl_tool_then_empty",+ object: "chat.completion.chunk",+ created: 1,+ model: "gpt-5.5-xhigh",+ choices: [{ index: 0, delta: {}, finish_reason: "tool_calls" }],+ })}\n\n`,+ ],+ {+ mode: "passthrough",+ sourceFormat: FORMATS.OPENAI,+ provider: "codex",+ model: "gpt-5.5-xhigh",+ body: { messages: [{ role: "user", content: "do task" }] },+ onComplete(payload) {+ onCompletePayload = payload;+ },+ }+ );++ assert.match(text, /"finish_reason":"tool_calls"/);+ assert.equal(onCompletePayload.status, 200);+ assert.equal(onCompletePayload.responseBody.choices[0].finish_reason, "tool_calls");+ assert.equal(onCompletePayload.responseBody.choices[0].message.tool_calls[0].function.name, "task_complete");+ // Content should be null (empty) since no text was generated+ assert.equal(onCompletePayload.responseBody.choices[0].message.content, null);+});diff --git a/tests/unit/t28-model-catalog-updates.test.ts b/tests/unit/t28-model-catalog-updates.test.tsindex c046364d10..de6d68655a 100644--- a/tests/unit/t28-model-catalog-updates.test.ts+++ b/tests/unit/t28-model-catalog-updates.test.ts@@ -28,10 +28,14 @@ test("T28: antigravity static catalog exposes client-visible Gemini preview IDs"const staticIds = (getStaticModelsForProvider("antigravity") || []).map((m) => m.id);assert.ok(staticIds.includes("gemini-3-pro-preview"));- assert.ok(!staticIds.includes("gemini-3.1-pro-low"));assert.ok(staticIds.includes("gemini-3-flash-preview"));+ // #3303 (agy parity, discussion #3184): the Gemini budget tiers ARE+ // client-visible on the Antigravity OAuth backend — restoring tiers an+ // earlier assumption had wrongly hidden.+ assert.ok(staticIds.includes("gemini-3.1-pro-low"));+ assert.ok(staticIds.includes("gemini-3.1-pro-high"));+ // Legacy aliases that were never client-visible stay absent.assert.ok(!staticIds.includes("gemini-3-pro-high"));- assert.ok(!staticIds.includes("gemini-3.1-pro-high"));assert.ok(!staticIds.includes("gemini-claude-sonnet-4-5"));assert.ok(!staticIds.includes("gemini-claude-sonnet-4-5-thinking"));assert.ok(!staticIds.includes("gemini-claude-opus-4-5-thinking"));diff --git a/tests/unit/t31-t33-t34-t38-model-specs.test.ts b/tests/unit/t31-t33-t34-t38-model-specs.test.tsindex ad455dec5c..a5926182e9 100644--- a/tests/unit/t31-t33-t34-t38-model-specs.test.ts+++ b/tests/unit/t31-t33-t34-t38-model-specs.test.ts@@ -20,8 +20,11 @@ test("T31: antigravity static catalog exposes client-visible Gemini preview IDs"// still accepts its internal model identifiers.const staticIds = (getStaticModelsForProvider("antigravity") || []).map((m) => m.id);assert.ok(staticIds.includes("gemini-3-pro-preview"));- assert.ok(!staticIds.includes("gemini-3.1-pro-low"));- assert.ok(!staticIds.includes("claude-sonnet-4-6"));+ // #3303 (agy parity, discussion #3184): the Gemini + Claude budget tiers ARE+ // client-visible on the Antigravity OAuth backend (Claude was never removed).+ assert.ok(staticIds.includes("gemini-3.1-pro-low"));+ assert.ok(staticIds.includes("claude-sonnet-4-6"));+ // The legacy cloaked Claude aliases remain absent.assert.ok(!staticIds.includes("gemini-claude-sonnet-4-5-thinking"));assert.ok(!staticIds.includes("gemini-claude-opus-4-5-thinking"));});diff --git a/tests/unit/theoldllm-body-double-read-3296.test.ts b/tests/unit/theoldllm-body-double-read-3296.test.tsnew file mode 100644index 0000000000..c57aec8fdc--- /dev/null+++ b/tests/unit/theoldllm-body-double-read-3296.test.ts@@ -0,0 +1,53 @@+import test from "node:test";+import assert from "node:assert/strict";++import { TheOldLlmExecutor, tokenCache } from "../../open-sse/executors/theoldllm.ts";++const SSE_BODY =+ 'data: {"choices":[{"delta":{"content":"Hello"}}]}\n' ++ 'data: {"choices":[{"delta":{"content":" world"}}]}\n' ++ "data: [DONE]\n";++// #3296: with a valid cached token the executor takes the direct-fetch path and+// never enters the token-refresh branch. It read the SAME upstream Response with+// .text() twice (once for the token-rejection check, once for the final body),+// which throws "Body is unusable: Body has already been read" → caught → [502].+test("theoldllm does not double-read the upstream body on the cached-token path (#3296)", async () => {+ const originalFetch = globalThis.fetch;+ // Pre-populate the cached token so execute() uses the direct fetch (no Playwright).+ tokenCache.value = "cached-token";+ tokenCache.expiresAt = Date.now() + 60_000;++ let fetchCalls = 0;+ globalThis.fetch = (async () => {+ fetchCalls += 1;+ return new Response(SSE_BODY, {+ status: 200,+ headers: { "Content-Type": "text/event-stream" },+ });+ }) as typeof fetch;++ try {+ const executor = new TheOldLlmExecutor();+ const result = await executor.execute({+ model: "gpt-5.4",+ body: { messages: [{ role: "user", content: "hi" }] },+ stream: false,+ credentials: {} as never,+ signal: null,+ });++ // Before the fix this was 502 with "Body has already been read".+ assert.equal(result.response.status, 200);+ assert.equal(fetchCalls, 1, "should fetch upstream exactly once on the cached-token path");++ const json = (await result.response.json()) as {+ choices?: Array<{ message?: { content?: string } }>;+ };+ assert.equal(json.choices?.[0]?.message?.content, "Hello world");+ } finally {+ globalThis.fetch = originalFetch;+ tokenCache.value = "";+ tokenCache.expiresAt = 0;+ }+});diff --git a/tests/unit/tokenExtractionConfig.test.ts b/tests/unit/tokenExtractionConfig.test.tsnew file mode 100644index 0000000000..30443983ee--- /dev/null+++ b/tests/unit/tokenExtractionConfig.test.ts@@ -0,0 +1,158 @@+/**+ * Tests for open-sse/services/tokenExtractionConfig.ts+ *+ * Validates that all web-cookie provider configs are well-formed,+ * have valid login URLs, and include at least one extraction source.+ */++import { describe, it } from "node:test";+import assert from "node:assert/strict";++const {+ TOKEN_EXTRACTION_CONFIGS,+ getExtractionConfig,+ listExtractionConfigs,+} = await import("../../open-sse/services/tokenExtractionConfig.ts");++describe("tokenExtractionConfig", () => {+ it("exports TOKEN_EXTRACTION_CONFIGS as a Map", () => {+ assert.ok(TOKEN_EXTRACTION_CONFIGS instanceof Map);+ });++ it("has at least 21 registered providers (18 existing + 3 new)", () => {+ assert.ok(TOKEN_EXTRACTION_CONFIGS.size >= 21);+ });++ it("every config has required fields", () => {+ for (const [providerId, cfg] of TOKEN_EXTRACTION_CONFIGS) {+ assert.ok(typeof cfg.providerId === "string", `${providerId}: missing providerId`);+ assert.ok(cfg.providerId.length > 0, `${providerId}: empty providerId`);+ assert.ok(typeof cfg.displayName === "string", `${providerId}: missing displayName`);+ assert.ok(cfg.displayName.length > 0, `${providerId}: empty displayName`);+ assert.ok(+ cfg.loginUrl.startsWith("http"),+ `${providerId}: loginUrl "${cfg.loginUrl}" must start with http`+ );+ assert.ok(+ cfg.homeUrl.startsWith("http"),+ `${providerId}: homeUrl "${cfg.homeUrl}" must start with http`+ );+ assert.ok(Array.isArray(cfg.tokenSources), `${providerId}: tokenSources must be an array`);+ assert.ok(cfg.tokenSources.length > 0, `${providerId}: must have at least one tokenSource`);+ assert.ok(typeof cfg.instructions === "string", `${providerId}: missing instructions`);+ assert.ok(cfg.instructions.length > 0, `${providerId}: empty instructions`);+ }+ });++ it("every tokenSource has a valid type", () => {+ const validTypes = ["cookie", "localStorage", "sessionStorage", "header"];+ for (const [providerId, cfg] of TOKEN_EXTRACTION_CONFIGS) {+ for (const src of cfg.tokenSources) {+ assert.ok(+ validTypes.includes(src.type),+ `${providerId}: invalid tokenSource type "${src.type}"`+ );+ if (src.type === "cookie") {+ assert.ok(typeof src.name === "string", `${providerId}: cookie source missing name`);+ assert.ok(src.name.length > 0, `${providerId}: cookie source has empty name`);+ }+ if (src.type === "localStorage" || src.type === "sessionStorage") {+ assert.ok(typeof src.key === "string", `${providerId}: storage source missing key`);+ assert.ok(src.key.length > 0, `${providerId}: storage source has empty key`);+ }+ }+ }+ });++ it("loginUrl and homeUrl share the same root domain", () => {+ function extractDomain(url: string): string {+ try {+ const u = new URL(url);+ return u.hostname;+ } catch {+ return "";+ }+ }+ for (const [providerId, cfg] of TOKEN_EXTRACTION_CONFIGS) {+ const loginDomain = extractDomain(cfg.loginUrl);+ const homeDomain = extractDomain(cfg.homeUrl);+ // Allow different subdomains but same root+ const loginParts = loginDomain.split(".");+ const homeParts = homeDomain.split(".");+ const loginRoot = loginParts.slice(-2).join(".");+ const homeRoot = homeParts.slice(-2).join(".");+ assert.equal(+ loginRoot,+ homeRoot,+ `${providerId}: loginUrl (${cfg.loginUrl}) and homeUrl (${cfg.homeUrl}) should share the same root domain`+ );+ }+ });++ it("getExtractionConfig returns undefined for unknown provider", () => {+ const result = getExtractionConfig("nonexistent-provider");+ assert.equal(result, undefined);+ });++ it("getExtractionConfig returns config for known providers", () => {+ const providers = ["claude-web", "chatgpt-web", "gemini-web", "grok-web", "deepseek-web"];+ for (const id of providers) {+ const cfg = getExtractionConfig(id);+ assert.ok(cfg !== undefined, `getExtractionConfig("${id}") returned undefined`);+ assert.equal(cfg?.providerId, id);+ }+ });++ it("listExtractionConfigs returns all configs as an array", () => {+ const all = listExtractionConfigs();+ assert.ok(Array.isArray(all));+ assert.equal(all.length, TOKEN_EXTRACTION_CONFIGS.size);+ });++ it("includes the 3 new missing providers", () => {+ const newProviders = ["chatglm-web", "xiaomimimo-web", "manus-web"];+ for (const id of newProviders) {+ const cfg = getExtractionConfig(id);+ assert.ok(cfg !== undefined, `Missing provider "${id}" not found in config`);+ }+ });++ it("every provider ID matches the executor naming convention", () => {+ for (const providerId of TOKEN_EXTRACTION_CONFIGS.keys()) {+ assert.ok(+ providerId.endsWith("-web"),+ `Provider ID "${providerId}" should follow the "-web" naming convention`+ );+ }+ });++ it("each cookie token source has a valid domain when specified", () => {+ for (const [providerId, cfg] of TOKEN_EXTRACTION_CONFIGS) {+ for (const src of cfg.tokenSources) {+ if (src.type === "cookie" && src.domain) {+ assert.ok(+ src.domain.startsWith(".") || src.domain.startsWith("http"),+ `${providerId}: cookie domain "${src.domain}" should start with "." or "http"`+ );+ }+ }+ }+ });++ it("pollingConfig has valid values", () => {+ for (const [providerId, cfg] of TOKEN_EXTRACTION_CONFIGS) {+ assert.ok(+ cfg.pollingConfig.pollInterval >= 100,+ `${providerId}: pollInterval too low (${cfg.pollingConfig.pollInterval})`+ );+ assert.ok(+ cfg.pollingConfig.timeout >= 10000,+ `${providerId}: timeout too low (${cfg.pollingConfig.timeout})`+ );+ assert.ok(+ cfg.pollingConfig.minLoginTime >= 1000,+ `${providerId}: minLoginTime too low (${cfg.pollingConfig.minLoginTime})`+ );+ }+ });+});diff --git a/tests/unit/usage-service-hardening.test.ts b/tests/unit/usage-service-hardening.test.tsindex d2dc44d90a..09701ddeb8 100644--- a/tests/unit/usage-service-hardening.test.ts+++ b/tests/unit/usage-service-hardening.test.ts@@ -340,10 +340,13 @@ test("usage service covers Antigravity quota parsing, exclusions and forbidden a});assert.equal(usage.plan, "Ultra");- // claude-sonnet-4-6 was removed from ANTIGRAVITY_PUBLIC_MODELS in May 2026 (deprecated)- assert.deepEqual(Object.keys(usage.quotas).sort(), ["gemini-pro-agent"]);+ // #3184: claude-sonnet-4-6 is user-callable on the Antigravity backend, so its quota is+ // surfaced. tab_flash_lite_preview (not chat-callable), gemini-unlimited (no quota), and+ // internal-model (internal) are still filtered out by the hardening logic.+ assert.deepEqual(Object.keys(usage.quotas).sort(), ["claude-sonnet-4-6", "gemini-pro-agent"]);assert.equal(usage.quotas["gemini-pro-agent"].total, 0);assert.equal(usage.quotas["gemini-pro-agent"].remainingPercentage, 100);+ assert.equal(usage.quotas["claude-sonnet-4-6"].remainingPercentage, 40);const loadCodeAssistCall = calls.find((call) => call.url.includes("loadCodeAssist"));assert.match(loadCodeAssistCall?.url, /daily-cloudcode-pa\.sandbox\.googleapis\.com/);assert.match(loadCodeAssistCall?.init.headers["User-Agent"], /^vscode\/1\.X\.X \(Antigravity\//);diff --git a/tests/unit/vscode-token-routes.test.ts b/tests/unit/vscode-token-routes.test.tsnew file mode 100644index 0000000000..cef7abd78d--- /dev/null+++ b/tests/unit/vscode-token-routes.test.ts@@ -0,0 +1,1207 @@+import test from "node:test";+import assert from "node:assert/strict";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";++const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-vscode-token-routes-"));+process.env.DATA_DIR = TEST_DATA_DIR;+process.env.API_KEY_SECRET = process.env.API_KEY_SECRET || "vscode-token-routes-secret";++const core = await import("../../src/lib/db/core.ts");+const providersDb = await import("../../src/lib/db/providers.ts");+const settingsDb = await import("../../src/lib/db/settings.ts");+const apiKeysDb = await import("../../src/lib/db/apiKeys.ts");+const vscodeRootRoute = await import("../../src/app/api/v1/vscode/[token]/route.ts");+const vscodeModelsRoute = await import("../../src/app/api/v1/vscode/[token]/models/route.ts");+const vscodeRawRootRoute = await import("../../src/app/api/v1/vscode/raw/[token]/route.ts");+const vscodeRawModelsRoute = await import("../../src/app/api/v1/vscode/raw/[token]/models/route.ts");+const vscodeRawVersionRoute = await import("../../src/app/api/v1/vscode/raw/[token]/api/version/route.ts");+const vscodeRawShowRoute = await import("../../src/app/api/v1/vscode/raw/[token]/api/show/route.ts");+const vscodeRawTagsRoute = await import("../../src/app/api/v1/vscode/raw/[token]/api/tags/route.ts");+const vscodeV1ModelsRoute = await import("../../src/app/api/v1/vscode/[token]/v1/models/route.ts");+const vscodeVersionRoute = await import("../../src/app/api/v1/vscode/[token]/api/version/route.ts");+const vscodeShowRoute = await import("../../src/app/api/v1/vscode/[token]/api/show/route.ts");+const vscodeTagsRoute = await import("../../src/app/api/v1/vscode/[token]/api/tags/route.ts");+const vscodeV1ChatCompletionsRoute = await import(+ "../../src/app/api/v1/vscode/[token]/v1/chat/completions/route.ts"+);+const vscodeChatCompletionsRoute = await import(+ "../../src/app/api/v1/vscode/[token]/chat/completions/route.ts"+);+const vscodeResponsesRoute = await import("../../src/app/api/v1/vscode/[token]/responses/route.ts");+const serviceTierVariants = await import("../../src/app/api/v1/vscode/[token]/serviceTierVariants.ts");+const combosDb = await import("../../src/lib/db/combos.ts");++async function resetStorage() {+ core.resetDbInstance();+ apiKeysDb.resetApiKeyState();+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });+ fs.mkdirSync(TEST_DATA_DIR, { recursive: true });+}++async function seedConnection(provider: string, overrides: Record<string, unknown> = {}) {+ return providersDb.createProviderConnection({+ provider,+ authType: (overrides.authType as string) || "apikey",+ name: (overrides.name as string) || `${provider}-${Math.random().toString(16).slice(2, 8)}`,+ apiKey: (overrides.apiKey as string) || "sk-test",+ accessToken: overrides.accessToken as string | undefined,+ isActive: (overrides.isActive as boolean) ?? true,+ testStatus: (overrides.testStatus as string) || "active",+ providerSpecificData: (overrides.providerSpecificData as Record<string, unknown>) || {},+ });+}++test.beforeEach(async () => {+ await resetStorage();+});++test.after(async () => {+ core.resetDbInstance();+ apiKeysDb.resetApiKeyState();+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });+});++test("vscode tokenized root route mirrors the grouped VS Code catalog without combos", async () => {+ await settingsDb.updateSettings({+ requireLogin: true,+ password: "hashed-password",+ requireAuthForModels: true,+ });+ await seedConnection("openai", { name: "openai-vscode-root" });+ const key = await apiKeysDb.createApiKey("vscode-root", "machine-vscode-root");+ await combosDb.createCombo({+ name: "root-hidden-combo",+ strategy: "priority",+ models: [],+ });++ const response = await vscodeRootRoute.GET(+ new Request(`http://localhost/api/v1/vscode/${encodeURIComponent(key.key)}/`)+ );+ const body = (await response.json()) as any;++ assert.equal(response.status, 200);+ assert.ok(Array.isArray(body.data));+ assert.ok(body.data.length > 0);+ assert.equal(+ body.data.some((entry: any) => entry.id === "root-hidden-combo" || entry.name === "root-hidden-combo"),+ false+ );+});++test("vscode tokenized root route exposes friendly model names alongside ids", async () => {+ await settingsDb.updateSettings({+ requireLogin: true,+ password: "hashed-password",+ requireAuthForModels: true,+ });+ await seedConnection("codex", { name: "codex-vscode-root-friendly-name" });+ const key = await apiKeysDb.createApiKey("vscode-root-friendly-name", "machine-vscode-root-friendly-name");++ const response = await vscodeRootRoute.GET(+ new Request(`http://localhost/api/v1/vscode/${encodeURIComponent(key.key)}/`)+ );+ const body = (await response.json()) as any;+ const model = (body.data || []).find((entry: any) => entry.id === "gpt-5.4__provider_cx");++ assert.equal(response.status, 200);+ assert.ok(model, "missing gpt-5.4__provider_cx in tokenized VS Code root route");+ assert.equal(model.name, "Codex GPT 5.4 (Default)");+});++test("vscode tokenized models route accepts path-scoped API keys", async () => {+ await settingsDb.updateSettings({+ requireLogin: true,+ password: "hashed-password",+ requireAuthForModels: true,+ });+ await seedConnection("openai", { name: "openai-vscode-models" });+ const key = await apiKeysDb.createApiKey("vscode-models", "machine-vscode-models");++ const response = await vscodeModelsRoute.GET(+ new Request(`http://localhost/api/v1/vscode/${encodeURIComponent(key.key)}/models`)+ );+ const body = (await response.json()) as any;++ assert.equal(response.status, 200);+ assert.ok(Array.isArray(body.data));+ assert.ok(body.data.length > 0);+});++test("vscode tokenized combos route exposes configured combos via token alias", async () => {+ await settingsDb.updateSettings({+ requireLogin: true,+ password: "hashed-password",+ requireAuthForModels: true,+ });++ await seedConnection("codex", { name: "codex-vscode-combos-root-basic" });++ const key = await apiKeysDb.createApiKey("vscode-combos", "machine-vscode-combos");+ await combosDb.createCombo({+ name: "test-combo",+ strategy: "priority",+ models: [{ kind: "model", model: "codex/gpt-5.4-high", providerId: "codex" }],+ });++ const combosRoute = await import("../../src/app/api/v1/vscode/combos/[token]/[[...slug]]/route.ts");+ const response = await combosRoute.GET(+ new Request(`http://localhost/api/v1/vscode/combos/${encodeURIComponent(key.key)}`),+ { params: { token: key.key, slug: undefined } }+ );+ const body = (await response.json()) as any;++ assert.equal(response.status, 200);+ assert.equal(body.object, "list");+ assert.ok(Array.isArray(body.data), "expected data property to be an array");+ assert.ok(body.data.some((combo: any) => combo.name === "test-combo"), "expected test combo in data response");+ assert.equal("combos" in body, false, "did not expect legacy combos property in response");+});++test("vscode combos route responds to Ollama compatibility check (/api/version)", async () => {+ const key = await apiKeysDb.createApiKey("vscode-combos-version", "machine-vscode-combos-version");++ const combosRoute = await import("../../src/app/api/v1/vscode/combos/[token]/[[...slug]]/route.ts");+ const response = await combosRoute.GET(+ new Request(`http://localhost/api/v1/vscode/combos/${encodeURIComponent(key.key)}/api/version`),+ { params: { token: key.key, slug: ["api", "version"] } }+ );+ const body = (await response.json()) as any;++ assert.equal(response.status, 200);+ assert.ok(body.version, "expected version property in response");+ assert.match(body.version as string, /0\.6\.\d+/, "expected Ollama-compatible version format");+});++test("vscode combos route exposes combos through Ollama api/tags", async () => {+ await settingsDb.updateSettings({+ requireLogin: true,+ password: "hashed-password",+ requireAuthForModels: true,+ });++ await seedConnection("codex", { name: "codex-vscode-combos-tags" });++ const key = await apiKeysDb.createApiKey("vscode-combos-tags", "machine-vscode-combos-tags");+ await combosDb.createCombo({+ name: "tags-combo",+ strategy: "priority",+ models: [{ kind: "model", model: "codex/gpt-5.4-high", providerId: "codex" }],+ });++ const combosRoute = await import("../../src/app/api/v1/vscode/combos/[token]/[[...slug]]/route.ts");+ const response = await combosRoute.GET(+ new Request(`http://localhost/api/v1/vscode/combos/${encodeURIComponent(key.key)}/api/tags`),+ { params: { token: key.key, slug: ["api", "tags"] } }+ );+ const body = (await response.json()) as any;++ assert.equal(response.status, 200);+ assert.ok(Array.isArray(body.models), "expected models array in api/tags response");+ const combo = body.models.find((entry: any) => entry.name === "tags-combo");+ assert.ok(combo, "expected combo name in api/tags response");+ assert.equal(combo.details.family, "tags-combo");+ assert.deepEqual(combo.supportsReasoningEffort, ["none", "low", "medium", "high", "xhigh"]);+});++test("vscode combos route resolves combo names through Ollama api/show", async () => {+ await settingsDb.updateSettings({+ requireLogin: true,+ password: "hashed-password",+ requireAuthForModels: true,+ });++ await seedConnection("codex", { name: "codex-vscode-combos-show" });++ const key = await apiKeysDb.createApiKey("vscode-combos-show", "machine-vscode-combos-show");+ await combosDb.createCombo({+ name: "show-combo",+ strategy: "priority",+ models: [{ kind: "model", model: "codex/gpt-5.4-high", providerId: "codex" }],+ });++ const combosRoute = await import("../../src/app/api/v1/vscode/combos/[token]/[[...slug]]/route.ts");+ const response = await combosRoute.POST(+ new Request(`http://localhost/api/v1/vscode/combos/${encodeURIComponent(key.key)}/api/show`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ name: "show-combo" }),+ }),+ { params: { token: key.key, slug: ["api", "show"] } }+ );+ const body = (await response.json()) as any;++ assert.equal(response.status, 200);+ assert.equal(body.model, "show-combo");+ assert.equal(body.modelfile, "FROM show-combo");+ assert.equal(body.details.family, "show-combo");+ assert.equal(body.model_info.context_length, 200000);+ assert.deepEqual(body.supportsReasoningEffort, ["none", "low", "medium", "high", "xhigh"]);+ assert.equal(body.model_info.capabilities.reasoning, true);+});++test("vscode tokenized combos root route exposes importable combo metadata", async () => {+ await settingsDb.updateSettings({+ requireLogin: true,+ password: "hashed-password",+ requireAuthForModels: true,+ });++ await seedConnection("codex", { name: "codex-vscode-combos-root" });+ const key = await apiKeysDb.createApiKey("vscode-combos-root-rich", "machine-vscode-combos-root-rich");+ await combosDb.createCombo({+ name: "balanced-load",+ strategy: "reset-aware",+ models: [{ kind: "model", model: "codex/gpt-5.4-high", providerId: "codex" }],+ });++ const combosRoute = await import("../../src/app/api/v1/vscode/combos/[token]/[[...slug]]/route.ts");+ const response = await combosRoute.GET(+ new Request(`http://localhost/api/v1/vscode/combos/${encodeURIComponent(key.key)}`),+ { params: { token: key.key, slug: undefined } }+ );+ const body = (await response.json()) as any;+ const combo = body.data.find((entry: any) => entry.id === "balanced-load");++ assert.equal(response.status, 200);+ assert.ok(combo, "expected balanced-load in combo root response");+ assert.equal(combo.url.includes("/responses#models.ai.azure.com"), true);+ assert.equal(combo.maxInputTokens, 200000);+ assert.equal(combo.maxOutputTokens, 131072);+ assert.equal(combo.toolCalling, true);+ assert.deepEqual(combo.supportsReasoningEffort, ["none", "low", "medium", "high", "xhigh"]);+});++test("vscode tokenized models route exposes reasoning effort metadata for importable chat models", async () => {+ await settingsDb.updateSettings({+ requireLogin: true,+ password: "hashed-password",+ requireAuthForModels: true,+ });+ await seedConnection("github", {+ authType: "oauth",+ apiKey: null,+ accessToken: "gh-test-access-token",+ name: "github-vscode-models-reasoning",+ });+ const key = await apiKeysDb.createApiKey(+ "vscode-models-reasoning",+ "machine-vscode-models-reasoning"+ );++ const response = await vscodeModelsRoute.GET(+ new Request(`http://localhost/api/v1/vscode/${encodeURIComponent(key.key)}/models`)+ );+ const body = (await response.json()) as any;+ const model = (body.data || []).find((entry: any) => entry.id === "gpt-5.4__provider_gh");++ assert.equal(response.status, 200);+ assert.ok(model, "missing gpt-5.4__provider_gh in tokenized VS Code models route");+ assert.equal(model.family, "gpt-5.4");+ assert.deepEqual(model.supportsReasoningEffort, ["none", "low", "medium", "high"]);+ assert.deepEqual(model.supportedReasoningEfforts, ["none", "low", "medium", "high", "xhigh"]);+ assert.deepEqual(model.configurationSchema?.properties?.reasoningEffort?.enum, [+ "none",+ "low",+ "medium",+ "high",+ "xhigh",+ ]);+ assert.equal(model.configurationSchema?.properties?.reasoningEffort?.default, "none");+ assert.equal(+ model.url,+ `http://localhost/api/v1/vscode/${encodeURIComponent(key.key)}/responses#models.ai.azure.com`+ );+});++test("vscode tokenized models route keeps xhigh for codex models that advertise it", async () => {+ await settingsDb.updateSettings({+ requireLogin: true,+ password: "hashed-password",+ requireAuthForModels: true,+ });+ await seedConnection("codex", { name: "codex-vscode-models-reasoning" });+ const key = await apiKeysDb.createApiKey(+ "vscode-models-codex-reasoning",+ "machine-vscode-models-codex-reasoning"+ );++ const response = await vscodeModelsRoute.GET(+ new Request(`http://localhost/api/v1/vscode/${encodeURIComponent(key.key)}/models`)+ );+ const body = (await response.json()) as any;+ const model = (body.data || []).find((entry: any) => entry.id === "gpt-5.4__provider_cx");+ const fastModel = (body.data || []).find((entry: any) => entry.id === "gpt-5.4__provider_cx__tier_priority");+ const flexModel = (body.data || []).find((entry: any) => entry.id === "gpt-5.4__provider_cx__tier_flex");++ assert.equal(response.status, 200);+ assert.ok(model, "missing gpt-5.4__provider_cx in tokenized VS Code models route");+ assert.ok(fastModel, "missing gpt-5.4__provider_cx__tier_priority in tokenized VS Code models route");+ assert.ok(flexModel, "missing gpt-5.4__provider_cx__tier_flex in tokenized VS Code models route");+ assert.equal(model.name, "Codex GPT 5.4 (Default)");+ assert.equal(fastModel.name, "Codex GPT 5.4 (Fast)");+ assert.equal(flexModel.name, "Codex GPT 5.4 (Flex)");+ assert.equal(model.toolCalling, true);+ assert.equal(model.vision, true);+ assert.deepEqual(model.supportsReasoningEffort, ["none", "low", "medium", "high", "xhigh"]);+ assert.deepEqual(model.supportedReasoningEfforts, ["none", "low", "medium", "high", "xhigh"]);+ assert.equal(model.defaultReasoningEffort, "none");+ assert.deepEqual(model.configSchema?.properties?.reasoningEffort?.enum, [+ "none",+ "low",+ "medium",+ "high",+ "xhigh",+ ]);+ assert.equal(model.configSchema?.properties?.reasoningEffort?.default, "none");+ const importedIds = new Set((body.data || []).map((entry: any) => entry.id));+ assert.ok(!importedIds.has("cx/gpt-5.4"));+ assert.ok(!importedIds.has("cx/gpt-5.4__tier_priority"));+ assert.ok(!importedIds.has("cx/gpt-5.4__tier_flex"));+ assert.ok(!importedIds.has("codex/gpt-5.4"));+ assert.ok(!importedIds.has("cx/gpt-5.4-low"));+ assert.ok(!importedIds.has("cx/gpt-5.4-medium"));+ assert.ok(!importedIds.has("cx/gpt-5.4-high"));+ assert.ok(!importedIds.has("cx/gpt-5.4-xhigh"));+ assert.ok(!importedIds.has("cx/gpt-5.4-low__tier_priority"));+ assert.ok(!importedIds.has("cx/gpt-5.4-medium__tier_priority"));+ assert.ok(!importedIds.has("cx/gpt-5.4-xhigh__tier_flex"));+ assert.equal(+ model.url,+ `http://localhost/api/v1/vscode/${encodeURIComponent(key.key)}/responses#models.ai.azure.com`+ );+});++test("vscode tokenized raw models route exposes provider-native ids without family-first grouping", async () => {+ await settingsDb.updateSettings({+ requireLogin: true,+ password: "hashed-password",+ requireAuthForModels: true,+ });+ await seedConnection("codex", { name: "codex-vscode-raw-models" });+ const key = await apiKeysDb.createApiKey(+ "vscode-raw-models-codex",+ "machine-vscode-raw-models-codex"+ );++ const response = await vscodeRawModelsRoute.GET(+ new Request(`http://localhost/api/v1/vscode/raw/${encodeURIComponent(key.key)}/models`)+ );+ const body = (await response.json()) as any;+ const importedIds = new Set((body.data || []).map((entry: any) => entry.id));+ const defaultModel = (body.data || []).find((entry: any) => entry.id === "cx/gpt-5.4");+ const fastModel = (body.data || []).find((entry: any) => entry.id === "cx/gpt-5.4__tier_priority");+ const flexModel = (body.data || []).find((entry: any) => entry.id === "cx/gpt-5.4__tier_flex");++ assert.equal(response.status, 200);+ assert.ok(defaultModel, "missing cx/gpt-5.4 in raw VS Code models route");+ assert.ok(fastModel, "missing cx/gpt-5.4__tier_priority in raw VS Code models route");+ assert.ok(flexModel, "missing cx/gpt-5.4__tier_flex in raw VS Code models route");+ assert.equal(importedIds.size, (body.data || []).length, "raw VS Code models route should not duplicate model ids");+ assert.ok(!importedIds.has("gpt-5.4__provider_cx"));+ assert.ok(!importedIds.has("gpt-5.4__provider_cx__tier_priority"));+ assert.ok(!importedIds.has("gpt-5.4__provider_cx__tier_flex"));+ assert.equal(defaultModel.object, "model");+ assert.equal(typeof defaultModel.created, "number");+ assert.equal(defaultModel.owned_by, "codex");+ assert.equal(defaultModel.name, "Codex GPT 5.4");+ assert.equal(typeof defaultModel.context_length, "number");+ assert.equal(typeof defaultModel.max_output_tokens, "number");+ assert.equal(typeof defaultModel.max_input_tokens, "number");+ assert.deepEqual(defaultModel.capabilities, {+ vision: true,+ tool_calling: true,+ reasoning: true,+ thinking: true,+ });+ assert.equal(defaultModel.url, undefined);+ assert.equal(defaultModel.toolCalling, undefined);+ assert.equal(defaultModel.vision, undefined);+ assert.equal(defaultModel.family, undefined);+ assert.equal(defaultModel.supportsReasoningEffort, undefined);+ assert.equal(defaultModel.supportedReasoningEfforts, undefined);+ assert.equal(defaultModel.defaultReasoningEffort, undefined);+ assert.equal(defaultModel.configurationSchema, undefined);+ assert.equal(defaultModel.configSchema, undefined);+ assert.equal(defaultModel.maxInputTokens, undefined);++ const lowModel = (body.data || []).find((entry: any) => entry.id === "cx/gpt-5.4-low");+ const mediumModel = (body.data || []).find((entry: any) => entry.id === "cx/gpt-5.4-medium");+ const highModel = (body.data || []).find((entry: any) => entry.id === "cx/gpt-5.4-high");+ const lowFastModel = (body.data || []).find(+ (entry: any) => entry.id === "cx/gpt-5.4-low__tier_priority"+ );+ const mediumFastModel = (body.data || []).find(+ (entry: any) => entry.id === "cx/gpt-5.4-medium__tier_priority"+ );+ const highFastModel = (body.data || []).find(+ (entry: any) => entry.id === "cx/gpt-5.4-high__tier_priority"+ );++ assert.ok(lowModel, "missing cx/gpt-5.4-low in raw VS Code models route");+ assert.ok(mediumModel, "missing cx/gpt-5.4-medium in raw VS Code models route");+ assert.ok(highModel, "missing cx/gpt-5.4-high in raw VS Code models route");+ assert.ok(lowFastModel, "missing cx/gpt-5.4-low__tier_priority in raw VS Code models route");+ assert.ok(+ mediumFastModel,+ "missing cx/gpt-5.4-medium__tier_priority in raw VS Code models route"+ );+ assert.ok(highFastModel, "missing cx/gpt-5.4-high__tier_priority in raw VS Code models route");+ assert.equal(lowModel.name, "Codex GPT 5.4 (Low)");+ assert.equal(lowFastModel.name, "Codex GPT 5.4 (Low) (Fast)");+ assert.equal(mediumFastModel.name, "Codex GPT 5.4 (Medium) (Fast)");+ assert.equal(highFastModel.name, "Codex GPT 5.4 (High) (Fast)");+ assert.equal(defaultModel.url, undefined);+ assert.equal(defaultModel.toolCalling, undefined);+ assert.equal(defaultModel.vision, undefined);+ assert.equal(defaultModel.family, undefined);+ assert.equal(defaultModel.supportsReasoningEffort, undefined);+ assert.equal(defaultModel.supportedReasoningEfforts, undefined);+ assert.equal(defaultModel.defaultReasoningEffort, undefined);+ assert.equal(defaultModel.configurationSchema, undefined);+ assert.equal(defaultModel.configSchema, undefined);+ assert.equal(defaultModel.maxInputTokens, undefined);+ assert.equal(typeof defaultModel.max_output_tokens, "number");+ assert.equal(typeof defaultModel.max_input_tokens, "number");+ assert.deepEqual(defaultModel.capabilities, {+ vision: true,+ tool_calling: true,+ reasoning: true,+ thinking: true,+ });+});++test("vscode tokenized raw root route mirrors the raw models catalog", async () => {+ await settingsDb.updateSettings({+ requireLogin: true,+ password: "hashed-password",+ requireAuthForModels: true,+ });+ await seedConnection("codex", { name: "codex-vscode-raw-root" });+ const key = await apiKeysDb.createApiKey(+ "vscode-raw-root-codex",+ "machine-vscode-raw-root-codex"+ );++ const response = await vscodeRawRootRoute.GET(+ new Request(`http://localhost/api/v1/vscode/raw/${encodeURIComponent(key.key)}`),+ { params: { token: key.key } }+ );+ const body = (await response.json()) as any;++ assert.equal(response.status, 200);+ assert.ok(Array.isArray(body.data));+ assert.ok(body.data.some((entry: any) => entry.id === "cx/gpt-5.4"));+ assert.ok(body.data.some((entry: any) => entry.id === "cx/gpt-5.4-low__tier_priority"));+});++test("vscode tokenized raw routes do not publish combo entries", async () => {+ await settingsDb.updateSettings({+ requireLogin: true,+ password: "hashed-password",+ requireAuthForModels: true,+ });+ await seedConnection("openai", { name: "openai-vscode-raw-hide-combos" });+ const key = await apiKeysDb.createApiKey(+ "vscode-raw-hide-combos",+ "machine-vscode-raw-hide-combos"+ );+ await combosDb.createCombo({+ name: "raw-hidden-combo",+ strategy: "priority",+ models: [],+ });++ const response = await vscodeRawRootRoute.GET(+ new Request(`http://localhost/api/v1/vscode/raw/${encodeURIComponent(key.key)}`),+ { params: { token: key.key } }+ );+ const body = (await response.json()) as any;++ assert.equal(response.status, 200);+ assert.ok(Array.isArray(body.data));+ assert.equal(+ body.data.some(+ (entry: any) => entry.id === "raw-hidden-combo" || entry.name === "raw-hidden-combo"+ ),+ false+ );+});++test("vscode tokenized raw tags route does not publish combo entries", async () => {+ await settingsDb.updateSettings({+ requireLogin: true,+ password: "hashed-password",+ requireAuthForModels: true,+ });+ await seedConnection("codex", { name: "codex-vscode-raw-tags-no-combo" });+ const key = await apiKeysDb.createApiKey(+ "vscode-raw-tags-no-combo",+ "machine-vscode-raw-tags-no-combo"+ );+ await combosDb.createCombo({+ name: "raw-tags-hidden-combo",+ strategy: "priority",+ models: [{ kind: "model", model: "codex/gpt-5.4-high", providerId: "codex" }],+ });++ const response = await vscodeRawTagsRoute.GET(+ new Request(`http://localhost/api/v1/vscode/raw/${encodeURIComponent(key.key)}/api/tags`),+ { params: { token: key.key } }+ );+ const body = (await response.json()) as any;++ assert.equal(response.status, 200);+ assert.ok(Array.isArray(body.models));+ assert.equal(+ body.models.some((entry: any) => entry.name === "raw-tags-hidden-combo"),+ false+ );+});++test("vscode tokenized raw show route resolves reasoning and service-tier variants independently", async () => {+ await settingsDb.updateSettings({+ requireLogin: true,+ password: "hashed-password",+ requireAuthForModels: true,+ });+ await seedConnection("codex", { name: "codex-vscode-raw-show-reasoning-tier" });+ const key = await apiKeysDb.createApiKey(+ "vscode-raw-show-reasoning-tier",+ "machine-vscode-raw-show-reasoning-tier"+ );++ const response = await vscodeRawShowRoute.POST(+ new Request(`http://localhost/api/v1/vscode/raw/${encodeURIComponent(key.key)}/api/show`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ name: "cx/gpt-5.4-low__tier_priority" }),+ }),+ { params: { token: key.key } }+ );+ const body = (await response.json()) as any;++ assert.equal(response.status, 200);+ assert.equal(body.model, "cx/gpt-5.4-low__tier_priority");+ assert.equal(body.remote_model, "Codex GPT 5.4 (Low) (Fast)");+ assert.equal(body.selectedReasoningEffort, "low");+ assert.equal(body.selected_reasoning_effort, "low");+ assert.equal(body.details.selectedReasoningEffort, "low");+ assert.equal(body.details.selected_reasoning_effort, "low");+});++test("vscode tokenized raw api/show does not resolve combo names", async () => {+ await settingsDb.updateSettings({+ requireLogin: true,+ password: "hashed-password",+ requireAuthForModels: true,+ });+ await seedConnection("codex", { name: "codex-vscode-raw-show-no-combo" });+ const key = await apiKeysDb.createApiKey(+ "vscode-raw-show-no-combo",+ "machine-vscode-raw-show-no-combo"+ );+ await combosDb.createCombo({+ name: "raw-show-hidden-combo",+ strategy: "priority",+ models: [{ kind: "model", model: "codex/gpt-5.4-high", providerId: "codex" }],+ });++ const response = await vscodeRawShowRoute.POST(+ new Request(`http://localhost/api/v1/vscode/raw/${encodeURIComponent(key.key)}/api/show`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ name: "raw-show-hidden-combo" }),+ }),+ { params: { token: key.key } }+ );+ const body = (await response.json()) as any;++ assert.equal(response.status, 404);+ assert.equal(body.error, "Model not found: raw-show-hidden-combo");+});++test("vscode tokenized raw version route returns Ollama-compatible version", async () => {+ const response = await vscodeVersionRoute.GET();+ const body = (await response.json()) as any;++ assert.equal(response.status, 200);+ assert.match(body.version as string, /0\.6\.\d+/);+});++test("vscode tokenized models route prefixes the provider without duplicating brand names", async () => {+ await settingsDb.updateSettings({+ requireLogin: true,+ password: "hashed-password",+ requireAuthForModels: true,+ });+ await seedConnection("gemini-cli", { name: "gemini-cli-vscode-models-labels" });+ const key = await apiKeysDb.createApiKey(+ "vscode-models-provider-prefix",+ "machine-vscode-models-provider-prefix"+ );++ const response = await vscodeModelsRoute.GET(+ new Request(`http://localhost/api/v1/vscode/${encodeURIComponent(key.key)}/models`)+ );+ const body = (await response.json()) as any;+ const model = (body.data || []).find((entry: any) => entry.id === "gemini-cli/gemini-1.5-pro");++ assert.equal(response.status, 200);+ assert.ok(model, "missing gemini-cli/gemini-1.5-pro in tokenized VS Code models route");+ assert.equal(model.name, "Gemini 1.5 Pro");+});++test("vscode tokenized tags route mirrors the Ollama tags payload", async () => {+ await settingsDb.updateSettings({+ requireLogin: true,+ password: "hashed-password",+ requireAuthForModels: true,+ });+ await seedConnection("openai", { name: "openai-vscode-tags" });+ const key = await apiKeysDb.createApiKey("vscode-tags", "machine-vscode-tags");++ const response = await vscodeTagsRoute.GET(+ new Request(`http://localhost/api/v1/vscode/${encodeURIComponent(key.key)}/api/tags`)+ );+ const body = (await response.json()) as any;++ assert.equal(response.status, 200);+ assert.ok(Array.isArray(body.models));+ assert.ok(body.models.length > 0);+ assert.equal(typeof body.models[0]?.name, "string");+});++test("vscode tokenized tags route exposes reasoning metadata for codex models", async () => {+ await settingsDb.updateSettings({+ requireLogin: true,+ password: "hashed-password",+ requireAuthForModels: true,+ });+ await seedConnection("codex", { name: "codex-vscode-tags-reasoning" });+ const key = await apiKeysDb.createApiKey("vscode-tags-reasoning", "machine-vscode-tags-reasoning");++ const response = await vscodeTagsRoute.GET(+ new Request(`http://localhost/api/v1/vscode/${encodeURIComponent(key.key)}/api/tags`)+ );+ const body = (await response.json()) as any;+ const model = (body.models || []).find((entry: any) => entry.name === "gpt-5.4__provider_cx");++ assert.equal(response.status, 200);+ assert.ok(model, "missing gpt-5.4__provider_cx in tokenized VS Code tags route");+ assert.deepEqual(model.supportsReasoningEffort, ["none", "low", "medium", "high", "xhigh"]);+ assert.deepEqual(model.supports_reasoning_effort, ["none", "low", "medium", "high", "xhigh"]);+ assert.deepEqual(model.supportedReasoningEfforts, ["none", "low", "medium", "high", "xhigh"]);+ assert.equal(model.defaultReasoningEffort, "none");+ assert.equal(model.selectedReasoningEffort, "none");+ assert.equal(model.selected_reasoning_effort, "none");+ assert.equal(model.details.family, "gpt-5.4");+ assert.deepEqual(model.configurationSchema?.properties?.reasoningEffort?.enum, [+ "none",+ "low",+ "medium",+ "high",+ "xhigh",+ ]);+ assert.equal(model.configurationSchema?.properties?.reasoningEffort?.default, "none");+ assert.deepEqual(model.details.configurationSchema?.properties?.reasoningEffort?.enum, [+ "none",+ "low",+ "medium",+ "high",+ "xhigh",+ ]);+ assert.deepEqual(model.details.supports_reasoning_effort, ["none", "low", "medium", "high", "xhigh"]);+ assert.equal(model.details.selected_reasoning_effort, "none");+ assert.ok(+ !(body.models || []).some((entry: any) => entry.name === "cx/gpt-5.4-low"),+ "reasoning variant leaked into grouped VS Code tags route"+ );+ assert.ok(+ !(body.models || []).some((entry: any) => entry.name === "cx/gpt-5.4-low__tier_priority"),+ "tier reasoning variant leaked into grouped VS Code tags route"+ );+ assert.ok((body.models || []).some((entry: any) => entry.name === "gpt-5.4__provider_cx__tier_priority"));+ assert.ok((body.models || []).some((entry: any) => entry.name === "gpt-5.4__provider_cx__tier_flex"));+});++test("vscode tokenized tags route only exposes usable canonical chat models", async () => {+ await settingsDb.updateSettings({+ requireLogin: true,+ password: "hashed-password",+ requireAuthForModels: true,+ });+ await seedConnection("openai", { name: "openai-vscode-tags-usable" });+ const key = await apiKeysDb.createApiKey("vscode-tags-usable", "machine-vscode-tags-usable");++ const tagsResponse = await vscodeTagsRoute.GET(+ new Request(`http://localhost/api/v1/vscode/${encodeURIComponent(key.key)}/api/tags`)+ );+ const tagsBody = (await tagsResponse.json()) as any;++ const modelsResponse = await vscodeModelsRoute.GET(+ new Request(`http://localhost/api/v1/vscode/${encodeURIComponent(key.key)}/models`)+ );+ const modelsBody = (await modelsResponse.json()) as any;+ const rawModelsResponse = await vscodeV1ModelsRoute.GET(+ new Request(`http://localhost/api/v1/vscode/${encodeURIComponent(key.key)}/v1/models`)+ );+ const rawModelsBody = (await rawModelsResponse.json()) as any;++ assert.equal(tagsResponse.status, 200);+ assert.equal(modelsResponse.status, 200);+ assert.equal(rawModelsResponse.status, 200);++ const catalogById = new Map(+ (modelsBody.data || []).map((model: any) => [model.id, model])+ );+ const rawCatalogById = new Map(+ (rawModelsBody.data || []).map((model: any) => [model.id, model])+ );+ type CatalogLike = {+ parent?: string | null;+ type?: string;+ api_format?: string;+ supported_endpoints?: string[];+ output_modalities?: string[];+ };++ for (const tagModel of tagsBody.models || []) {+ const catalogModel = (catalogById.get(tagModel.name) || rawCatalogById.get(tagModel.name)) as+ | CatalogLike+ | undefined;+ assert.ok(catalogModel, `missing catalog model for tag ${tagModel.name}`);+ assert.ok(!catalogModel.parent, `tag ${tagModel.name} should not expose an alias child`);+ assert.ok(+ !catalogModel.type || catalogModel.type === "chat",+ `tag ${tagModel.name} should be chat-capable`+ );+ assert.ok(+ !catalogModel.api_format || catalogModel.api_format === "chat-completions",+ `tag ${tagModel.name} should use chat-completions`+ );+ assert.ok(+ !Array.isArray(catalogModel.supported_endpoints) ||+ catalogModel.supported_endpoints.includes("chat"),+ `tag ${tagModel.name} should support chat`+ );+ assert.ok(+ !Array.isArray(catalogModel.output_modalities) ||+ catalogModel.output_modalities.includes("text"),+ `tag ${tagModel.name} should output text`+ );+ }++ const unusableCatalogModels = (modelsBody.data || []).filter(+ (model: any) =>+ model.parent ||+ (typeof model.type === "string" && model.type !== "chat") ||+ (typeof model.api_format === "string" && model.api_format !== "chat-completions") ||+ (Array.isArray(model.supported_endpoints) && !model.supported_endpoints.includes("chat")) ||+ (Array.isArray(model.output_modalities) && !model.output_modalities.includes("text"))+ );+ const tagNames = new Set((tagsBody.models || []).map((model: any) => model.name));++ for (const model of unusableCatalogModels) {+ assert.ok(!tagNames.has(model.id), `unusable model leaked into tags: ${model.id}`);+ }+});++test("vscode tokenized grouped tags route does not publish combo entries", async () => {+ await settingsDb.updateSettings({+ requireLogin: true,+ password: "hashed-password",+ requireAuthForModels: true,+ });+ await seedConnection("codex", { name: "codex-vscode-grouped-tags-no-combo" });+ const key = await apiKeysDb.createApiKey(+ "vscode-grouped-tags-no-combo",+ "machine-vscode-grouped-tags-no-combo"+ );+ await combosDb.createCombo({+ name: "grouped-hidden-combo",+ strategy: "priority",+ models: [{ kind: "model", model: "codex/gpt-5.4-high", providerId: "codex" }],+ });++ const response = await vscodeTagsRoute.GET(+ new Request(`http://localhost/api/v1/vscode/${encodeURIComponent(key.key)}/api/tags`)+ );+ const body = (await response.json()) as any;++ assert.equal(response.status, 200);+ assert.ok(Array.isArray(body.models));+ assert.equal(+ body.models.some((entry: any) => entry.name === "grouped-hidden-combo"),+ false+ );+});++test("vscode tokenized tags route prefers canonical codex models when codex is the only active provider", async () => {+ await settingsDb.updateSettings({+ requireLogin: true,+ password: "hashed-password",+ requireAuthForModels: true,+ });+ await seedConnection("codex", { name: "codex-vscode-tags-canonical" });+ const key = await apiKeysDb.createApiKey("vscode-tags-canonical", "machine-vscode-tags-canonical");++ const response = await vscodeTagsRoute.GET(+ new Request(`http://localhost/api/v1/vscode/${encodeURIComponent(key.key)}/api/tags`)+ );+ const body = (await response.json()) as any;+ const tagNames = (body.models || []).map((model: any) => model.name);++ assert.equal(response.status, 200);+ assert.ok(tagNames.length > 0);+ assert.ok(+ tagNames.some((name: string) => name === "gpt-5.5__provider_cx"),+ `missing family-first codex tag: ${tagNames.join(", ")}`+ );+ assert.ok(tagNames.includes("gpt-5.5__provider_cx"));+ assert.ok(!tagNames.includes("cx/gpt-5.5"));+ assert.ok(!tagNames.includes("cx/gpt-5.5-low"));+ assert.ok(!tagNames.includes("cx/gpt-5.5-medium"));+ assert.ok(!tagNames.includes("cx/gpt-5.5-high"));+ assert.ok(!tagNames.includes("cx/gpt-5.5-xhigh"));++ for (const name of tagNames) {+ assert.ok(!name.startsWith("oc/"), `opencode tag leaked into codex-only endpoint: ${name}`);+ }+});++test("vscode tokenized api/version route exposes Ollama compatibility version", async () => {+ const response = await vscodeVersionRoute.GET();+ const body = (await response.json()) as any;++ assert.equal(response.status, 200);+ assert.equal(body.version, "0.6.4");+});++test("vscode raw tokenized api/version route exposes Ollama compatibility version", async () => {+ const response = await vscodeRawVersionRoute.GET();+ const body = (await response.json()) as any;++ assert.equal(response.status, 200);+ assert.equal(body.version, "0.6.4");+});++test("vscode tokenized api/show route resolves a catalog model through the path token", async () => {+ await settingsDb.updateSettings({+ requireLogin: true,+ password: "hashed-password",+ requireAuthForModels: true,+ });+ await seedConnection("openai", { name: "openai-vscode-show" });+ const key = await apiKeysDb.createApiKey("vscode-show", "machine-vscode-show");++ const modelsResponse = await vscodeV1ModelsRoute.GET(+ new Request(`http://localhost/api/v1/vscode/${encodeURIComponent(key.key)}/v1/models`)+ );+ const modelsBody = (await modelsResponse.json()) as any;+ const modelId = modelsBody.data?.[0]?.id;++ assert.equal(modelsResponse.status, 200);+ assert.equal(typeof modelId, "string");++ const response = await vscodeShowRoute.POST(+ new Request(`http://localhost/api/v1/vscode/${encodeURIComponent(key.key)}/api/show`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ name: modelId }),+ })+ );+ const body = (await response.json()) as any;++ assert.equal(response.status, 200);+ assert.equal(body.modelfile, `FROM ${modelId}`);+ assert.ok(Array.isArray(body.capabilities));+ assert.ok(body.capabilities.includes("completion"));+});++test("vscode tokenized tags names stay resolvable by api/show", async () => {+ await settingsDb.updateSettings({+ requireLogin: true,+ password: "hashed-password",+ requireAuthForModels: true,+ });+ await seedConnection("openai", { name: "openai-vscode-tags-show" });+ const key = await apiKeysDb.createApiKey("vscode-tags-show", "machine-vscode-tags-show");++ const tagsResponse = await vscodeTagsRoute.GET(+ new Request(`http://localhost/api/v1/vscode/${encodeURIComponent(key.key)}/api/tags`)+ );+ const tagsBody = (await tagsResponse.json()) as any;+ const tagModelName = tagsBody.models?.[0]?.name;++ assert.equal(tagsResponse.status, 200);+ assert.equal(typeof tagModelName, "string");++ const showResponse = await vscodeShowRoute.POST(+ new Request(`http://localhost/api/v1/vscode/${encodeURIComponent(key.key)}/api/show`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ model: tagModelName }),+ })+ );+ const showBody = (await showResponse.json()) as any;++ assert.equal(showResponse.status, 200);+ assert.equal(showBody.modelfile, `FROM ${tagModelName}`);+});++test("vscode tokenized grouped api/show does not resolve combo names", async () => {+ await settingsDb.updateSettings({+ requireLogin: true,+ password: "hashed-password",+ requireAuthForModels: true,+ });+ await seedConnection("codex", { name: "codex-vscode-grouped-show-no-combo" });+ const key = await apiKeysDb.createApiKey(+ "vscode-grouped-show-no-combo",+ "machine-vscode-grouped-show-no-combo"+ );+ await combosDb.createCombo({+ name: "grouped-show-hidden-combo",+ strategy: "priority",+ models: [{ kind: "model", model: "codex/gpt-5.4-high", providerId: "codex" }],+ });++ const response = await vscodeShowRoute.POST(+ new Request(`http://localhost/api/v1/vscode/${encodeURIComponent(key.key)}/api/show`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ name: "grouped-show-hidden-combo" }),+ })+ );+ const body = (await response.json()) as any;++ assert.equal(response.status, 404);+ assert.equal(body.error, "Model not found: grouped-show-hidden-combo");+});++test("vscode raw tokenized tags names stay resolvable by raw api/show", async () => {+ await settingsDb.updateSettings({+ requireLogin: true,+ password: "hashed-password",+ requireAuthForModels: true,+ });+ await seedConnection("openai", { name: "openai-vscode-raw-tags-show" });+ const key = await apiKeysDb.createApiKey("vscode-raw-tags-show", "machine-vscode-raw-tags-show");++ const tagsResponse = await vscodeRawTagsRoute.GET(+ new Request(`http://localhost/api/v1/vscode/raw/${encodeURIComponent(key.key)}/api/tags`),+ { params: { token: key.key } }+ );+ const tagsBody = (await tagsResponse.json()) as any;+ const tagModelName = tagsBody.models?.[0]?.name;++ assert.equal(tagsResponse.status, 200);+ assert.equal(typeof tagModelName, "string");++ const showResponse = await vscodeRawShowRoute.POST(+ new Request(`http://localhost/api/v1/vscode/raw/${encodeURIComponent(key.key)}/api/show`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ model: tagModelName }),+ }),+ { params: { token: key.key } }+ );+ const showBody = (await showResponse.json()) as any;++ assert.equal(showResponse.status, 200);+ assert.equal(showBody.modelfile, `FROM ${tagModelName}`);+});++test("vscode tokenized api/show route exposes explicit reasoning effort metadata", async () => {+ await settingsDb.updateSettings({+ requireLogin: true,+ password: "hashed-password",+ requireAuthForModels: true,+ });+ await seedConnection("codex", { name: "codex-vscode-show-reasoning" });+ const key = await apiKeysDb.createApiKey("vscode-show-reasoning", "machine-vscode-show-reasoning");++ const response = await vscodeShowRoute.POST(+ new Request(`http://localhost/api/v1/vscode/${encodeURIComponent(key.key)}/api/show`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ name: "gpt-5.4__provider_cx" }),+ })+ );+ const body = (await response.json()) as any;++ assert.equal(response.status, 200);+ assert.equal(body.model, "gpt-5.4__provider_cx");+ assert.equal(body.remote_model, "Codex GPT 5.4 (Default)");+ assert.equal(body.details.family, "gpt-5.4");+ assert.deepEqual(body.supportsReasoningEffort, ["none", "low", "medium", "high", "xhigh"]);+ assert.deepEqual(body.supports_reasoning_effort, ["none", "low", "medium", "high", "xhigh"]);+ assert.deepEqual(body.supportedReasoningEfforts, ["none", "low", "medium", "high", "xhigh"]);+ assert.equal(body.defaultReasoningEffort, "none");+ assert.equal(body.selectedReasoningEffort, "none");+ assert.equal(body.selected_reasoning_effort, "none");+ assert.deepEqual(body.configurationSchema?.properties?.reasoningEffort?.enum, [+ "none",+ "low",+ "medium",+ "high",+ "xhigh",+ ]);+ assert.equal(body.configurationSchema?.properties?.reasoningEffort?.default, "none");+ assert.equal(body.model_info["general.basename"], "Codex GPT 5.4 (Default)");+ assert.equal(body.model_info["general.architecture"], "codex");+ assert.equal(body.model_info["codex.context_length"], 200000);+ assert.deepEqual(body.model_info.supports_reasoning_effort, ["none", "low", "medium", "high", "xhigh"]);+ assert.equal(body.model_info.selected_reasoning_effort, "none");+ assert.deepEqual(+ body.model_info.capabilities.supports_reasoning_effort,+ ["none", "low", "medium", "high", "xhigh"]+ );+});++test("vscode tokenized api/show route exposes service tier variants with suffixed display names", async () => {+ await settingsDb.updateSettings({+ requireLogin: true,+ password: "hashed-password",+ requireAuthForModels: true,+ });+ await seedConnection("codex", { name: "codex-vscode-show-tier-priority" });+ const key = await apiKeysDb.createApiKey("vscode-show-tier-priority", "machine-vscode-show-tier-priority");++ const response = await vscodeShowRoute.POST(+ new Request(`http://localhost/api/v1/vscode/${encodeURIComponent(key.key)}/api/show`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ name: "gpt-5.4__provider_cx__tier_priority" }),+ })+ );+ const body = (await response.json()) as any;++ assert.equal(response.status, 200);+ assert.equal(body.model, "gpt-5.4__provider_cx__tier_priority");+ assert.equal(body.remote_model, "Codex GPT 5.4 (Fast)");+ assert.equal(body.details.family, "gpt-5.4");+});++test("vscode tokenized chat routes rewrite family-first ids back to the codex provider id", async () => {+ const payload = serviceTierVariants.resolveVscodeServiceTierRequest({ model: "gpt-5.4__provider_cx__tier_priority" });++ assert.equal(payload.model, "cx/gpt-5.4");+ assert.equal(payload.service_tier, "priority");+});++test("vscode tokenized /chat/completions route applies the path token and codex tier rewrite", async () => {+ await settingsDb.updateSettings({+ requireLogin: true,+ password: "hashed-password",+ requireAuthForModels: true,+ });+ const key = await apiKeysDb.createApiKey("vscode-chat-completions-route", "machine-vscode-chat-completions-route");++ const response = await vscodeChatCompletionsRoute.POST(+ new Request(`http://localhost/api/v1/vscode/${encodeURIComponent(key.key)}/chat/completions`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ model: "gpt-5.4__provider_cx__tier_priority",+ messages: [{ role: "user", content: "hi" }],+ max_tokens: 1,+ stream: false,+ }),+ })+ );+ const body = (await response.json()) as any;++ assert.equal(response.status, 400);+ assert.equal(body.error?.code, "bad_request");+ assert.equal(body.error?.message, "No credentials for provider: codex");+});++test("vscode tokenized /responses route applies the path token and codex tier rewrite", async () => {+ await settingsDb.updateSettings({+ requireLogin: true,+ password: "hashed-password",+ requireAuthForModels: true,+ });+ const key = await apiKeysDb.createApiKey("vscode-responses-route", "machine-vscode-responses-route");++ const response = await vscodeResponsesRoute.POST(+ new Request(`http://localhost/api/v1/vscode/${encodeURIComponent(key.key)}/responses`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ model: "gpt-5.4__provider_cx__tier_priority",+ input: [{ role: "user", content: [{ type: "input_text", text: "hi" }] }],+ max_output_tokens: 1,+ stream: false,+ }),+ })+ );+ const body = (await response.json()) as any;++ assert.equal(response.status, 400);+ assert.equal(body.error?.code, "bad_request");+ assert.equal(body.error?.message, "No credentials for provider: codex");+});++test("vscode tokenized api/show route preserves the selected reasoning effort for codex variants", async () => {+ await settingsDb.updateSettings({+ requireLogin: true,+ password: "hashed-password",+ requireAuthForModels: true,+ });+ await seedConnection("codex", { name: "codex-vscode-show-reasoning-low" });+ const key = await apiKeysDb.createApiKey(+ "vscode-show-reasoning-low",+ "machine-vscode-show-reasoning-low"+ );++ const response = await vscodeShowRoute.POST(+ new Request(`http://localhost/api/v1/vscode/${encodeURIComponent(key.key)}/api/show`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ name: "cx/gpt-5.4-low" }),+ })+ );+ const body = (await response.json()) as any;++ assert.equal(response.status, 200);+ assert.equal(body.model_info.selected_reasoning_effort, "low");+ assert.equal(body.model_info.capabilities.selected_reasoning_effort, "low");+});++test("vscode tokenized api/show route resolves canonical family aliases", async () => {+ await settingsDb.updateSettings({+ requireLogin: true,+ password: "hashed-password",+ requireAuthForModels: true,+ });+ await seedConnection("codex", { name: "codex-vscode-show-family-alias" });+ const key = await apiKeysDb.createApiKey(+ "vscode-show-family-alias",+ "machine-vscode-show-family-alias"+ );++ const response = await vscodeShowRoute.POST(+ new Request(`http://localhost/api/v1/vscode/${encodeURIComponent(key.key)}/api/show`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ name: "gpt-5.4" }),+ })+ );+ const body = (await response.json()) as any;++ assert.equal(response.status, 200);+ assert.equal(body.model, "gpt-5.4");+ assert.equal(body.details.family, "gpt-5.4");+});++test("vscode tokenized v1 chat route is exposed under the tokenized base path", async () => {+ const response = await vscodeV1ChatCompletionsRoute.OPTIONS();++ assert.equal(response.status, 204);+ assert.match(response.headers.get("Access-Control-Allow-Methods") || "", /POST/);+});