Skip to content

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

Revert "fix(config): externalize ws for copilot-m365-web executor (#6098, closes #6062)"

Diego Rodrigues de Sa e Souza604afeacf478
diff --git a/.env.example b/.env.example
index ba419dac43..2206a5d566 100644
--- a/.env.example
+++ b/.env.example
@@ -73,11 +73,6 @@ DISABLE_SQLITE_AUTO_BACKUP=false
# Default: 20128
PORT=20128
-# Base path (URL subpath) when serving OmniRoute behind a reverse proxy under a subpath.
-# Used by: next.config.mjs — sets Next.js `basePath`; auth redirects are basePath-aware.
-# Default: "" (served at the domain root). Example: /omniroute to serve under https://host/omniroute
-# OMNIROUTE_BASE_PATH=
-
# Split-port mode: serve Dashboard and API on separate ports for network isolation.
# Used by: src/lib/runtime/ports.ts — overrides PORT for each service.
# API_PORT=20129
@@ -418,15 +413,6 @@ NEXT_PUBLIC_BASE_URL=http://localhost:20128
# Do not include /v1; if included accidentally it will be normalized away.
# OMNIROUTE_PUBLIC_BASE_URL=http://192.168.0.15:20128
-# Absolute provider plugin manifest URL advertised to sidecar clients.
-# Used by: open-sse/config/providerPluginManifestUrl.ts. When unset, OmniRoute
-# derives the URL from request origin or HOST/PORT using OMNIROUTE_PUBLIC_PROTOCOL.
-# OMNIROUTE_PROVIDER_MANIFEST_URL=https://omniroute.example.com/api/v1/provider-plugin-manifest
-
-# Protocol used when deriving provider plugin manifest URLs without a request origin.
-# Used by: open-sse/config/providerPluginManifestUrl.ts. Defaults to http.
-# OMNIROUTE_PUBLIC_PROTOCOL=http
-
# Max wait time for an async chatgpt-web image to land via the celsius
# WebSocket, in milliseconds. Default 180000 (3 minutes). Increase during
# upstream queue-deep windows ("Lots of people are creating images right now").
@@ -582,8 +568,6 @@ NEXT_PUBLIC_ENABLE_SOCKS5_PROXY=true
# CLI_CONTINUE_BIN=cn
# CLI_QODER_BIN=qoder
# CLI_QWEN_BIN=qwen
-# CLI_AUGGIE_BIN=auggie
-# AUGGIE_BIN=auggie
# Override the Hermes Agent home directory (where OmniRoute reads/writes the
# Hermes CLI config). Matches the env var the Hermes PowerShell installer sets
@@ -885,8 +869,6 @@ GITHUB_OAUTH_CLIENT_ID=Iv1.b507a08c87ecfe98
# QODER_PERSONAL_ACCESS_TOKEN=
# QODER_CLI_WORKSPACE=
# OMNIROUTE_QODER_WORKSPACE=
-# Override the Qoder CLI config dir (isolated PAT session, avoids clobbering a browser login).
-# QODER_CLI_CONFIG_DIR=
# ── Blackbox Web validated-token override (issue #2252) ──
# Used by: open-sse/executors/blackbox-web.ts. Blackbox `/api/chat` rejects
@@ -1055,12 +1037,6 @@ CURSOR_USER_AGENT="Cursor/3.4"
# fallback when FETCH_TIMEOUT_MS is unset. Default: 120000 (2 min).
# OMNIROUTE_DEFAULT_FETCH_TIMEOUT_MS=120000
-# ── Firecrawl web-fetch executor ──
-# Point at a self-hosted Firecrawl instance (defaults to the public cloud API).
-# When set to a non-cloud base URL, the API key becomes optional.
-# FIRECRAWL_BASE_URL=https://api.firecrawl.dev
-# FIRECRAWL_TIMEOUT_MS=30000 # Per-request timeout (default: 30000 = 30s)
-
# ── ChatGPT TLS sidecar (Firefox-fingerprinted client) ──
# Used by: open-sse/services/chatgptTlsClient.ts — wire-level timeout for
# the bogdanfinn/tls-client koffi binding and the JS-side grace window
@@ -1466,13 +1442,6 @@ APP_LOG_TO_FILE=true
# CLIPROXYAPI_PORT=5544
# CLIPROXYAPI_CONFIG_DIR=~/.cli-proxy-api
-# ── Mux embedded service ──
-# Override the port where the embedded Mux (coder/mux) agent-orchestration
-# daemon listens. Always bound to 127.0.0.1 — never configurable to 0.0.0.0.
-# Rarely needed — defaults to 8322.
-# Used by: src/lib/services/bootstrap.ts, src/app/api/services/mux/_lib.ts
-# MUX_SERVICE_PORT=8322
-
# ── Local hostnames (Docker networking) ──
# Comma-separated additional hostnames treated as "local" for provider routing.
# Used by: open-sse/config/providerRegistry.ts — allows Docker service names.
@@ -1495,20 +1464,6 @@ APP_LOG_TO_FILE=true
# healthy-result cache window under high concurrency.
# PROXY_HEALTH_UNHEALTHY_CACHE_TTL_MS=2000
-# Background proxy health scheduler (src/lib/proxyHealth/scheduler.ts).
-# Periodically probes every registered proxy and (optionally) removes dead ones.
-# Set "false" to disable the scheduler entirely. Default: enabled.
-# PROXY_HEALTH_ENABLED=true
-# Sweep interval in ms (minimum 60000). Default: 600000 (10min).
-# PROXY_HEALTH_INTERVAL_MS=600000
-# Reachability probe target for the scheduler and the auto-test endpoint.
-# Point it at an internal/self-hosted URL to avoid the public default.
-# PROXY_HEALTH_TEST_URL=https://httpbin.org/ip
-# Set "true" to let the scheduler auto-remove proxies after repeated failures.
-# PROXY_AUTO_REMOVE=false
-# Consecutive failures before an auto-remove fires. Default: 3.
-# PROXY_AUTO_REMOVE_AFTER=3
-
# Allow OAuth and provider validation flows to bypass a pinned proxy and connect
# directly when proxy reachability pre-checks fail. Default: false.
# Also configurable from Dashboard > Settings > Feature Flags.
@@ -1720,15 +1675,6 @@ APP_LOG_TO_FILE=true
# FREE_PROXY_IPLOCATE_ENABLED=false
# FREE_PROXY_IPLOCATE_BASE_URL=https://raw.githubusercontent.com/iplocate/free-proxy-list/main/protocols
-# ── Free Proxy Pool (Webshare source) ──
-# Used by: src/lib/freeProxyProviders/webshare.ts
-# Paid, per-account proxy list — requires FREE_PROXY_WEBSHARE_API_KEY to activate,
-# regardless of FREE_PROXY_WEBSHARE_ENABLED.
-# FREE_PROXY_WEBSHARE_ENABLED=true
-# FREE_PROXY_WEBSHARE_API_KEY=
-# FREE_PROXY_WEBSHARE_API_URL=https://proxy.webshare.io/api/v2/proxy/list/
-# FREE_PROXY_WEBSHARE_MAX=500
-
# ── Vercel Relay ──
# Used by: src/app/api/settings/proxy/vercel-deploy/route.ts
# Hides the "Deploy Relay" button when set to false.
@@ -1933,10 +1879,6 @@ QUOTA_STORE_DRIVER=sqlite # sqlite | redis
# duplicated). Falls back to TS path via X-Bifrost-Fallback header on
# timeout/failure. See bin/omniroute for the local-redis companion.
# BIFROST_BASE_URL=
-# Port the supervised Bifrost embedded service binds to (127.0.0.1:<port>), read by
-# src/lib/services/bootstrap.ts when OmniRoute manages the Bifrost sidecar lifecycle.
-# Default: 8080.
-# BIFROST_PORT=8080
# API key for the Bifrost gateway (sent as Authorization: Bearer ...). If
# unset, the route expects the request to carry a valid OmniRoute API key;
# this key is for gateway-side auth only.
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index f5cd3afdfb..906c02bb7f 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -624,7 +624,7 @@ jobs:
cache: npm
- uses: ./.github/actions/npm-ci-retry
- run: npm run check:node-runtime
- - run: node --max-old-space-size=4096 --import tsx --import ./tests/_setup/isolateDataDir.ts --test --test-force-exit --test-concurrency=4 --test-shard=${{ matrix.shard }}/8 tests/unit/*.test.ts "tests/unit/{api,auth,authz,build,cli,cli-helper,combo,compression,correctness,cors,dashboard,db,db-adapters,docs,executors,gamification,guardrails,lib,mcp,memory,runtime,security,services,settings,shared,ui,usage}/**/*.test.ts"
+ - run: node --max-old-space-size=4096 --import tsx --import ./tests/_setup/isolateDataDir.ts --test --test-force-exit --test-concurrency=4 --test-shard=${{ matrix.shard }}/8 tests/unit/*.test.ts "tests/unit/{api,auth,authz,build,cli,cli-helper,combo,compression,correctness,cors,dashboard,db,db-adapters,docs,gamification,guardrails,lib,mcp,memory,runtime,security,services,settings,shared,ui,usage}/**/*.test.ts"
test-vitest:
name: Vitest (MCP / autoCombo / UI components)
@@ -676,7 +676,7 @@ jobs:
cache: npm
- uses: ./.github/actions/npm-ci-retry
- run: npm run check:node-runtime
- - run: node --max-old-space-size=4096 --import tsx --import ./tests/_setup/isolateDataDir.ts --test --test-force-exit --test-concurrency=4 --test-shard=${{ matrix.shard }}/4 tests/unit/*.test.ts "tests/unit/{api,auth,authz,build,cli,cli-helper,combo,compression,correctness,cors,dashboard,db,db-adapters,docs,executors,gamification,guardrails,lib,mcp,memory,runtime,security,services,settings,shared,ui,usage}/**/*.test.ts"
+ - run: node --max-old-space-size=4096 --import tsx --import ./tests/_setup/isolateDataDir.ts --test --test-force-exit --test-concurrency=4 --test-shard=${{ matrix.shard }}/4 tests/unit/*.test.ts "tests/unit/{api,auth,authz,build,cli,cli-helper,combo,compression,correctness,cors,dashboard,db,db-adapters,docs,gamification,guardrails,lib,mcp,memory,runtime,security,services,settings,shared,ui,usage}/**/*.test.ts"
node-26-compat-build:
name: Node 26 Compatibility Build
@@ -729,7 +729,7 @@ jobs:
cache: npm
- uses: ./.github/actions/npm-ci-retry
- run: npm run check:node-runtime
- - run: node --max-old-space-size=4096 --import tsx --import ./tests/_setup/isolateDataDir.ts --test --test-force-exit --test-concurrency=4 --test-shard=${{ matrix.shard }}/4 tests/unit/*.test.ts "tests/unit/{api,auth,authz,build,cli,cli-helper,combo,compression,correctness,cors,dashboard,db,db-adapters,docs,executors,gamification,guardrails,lib,mcp,memory,runtime,security,services,settings,shared,ui,usage}/**/*.test.ts"
+ - run: node --max-old-space-size=4096 --import tsx --import ./tests/_setup/isolateDataDir.ts --test --test-force-exit --test-concurrency=4 --test-shard=${{ matrix.shard }}/4 tests/unit/*.test.ts "tests/unit/{api,auth,authz,build,cli,cli-helper,combo,compression,correctness,cors,dashboard,db,db-adapters,docs,gamification,guardrails,lib,mcp,memory,runtime,security,services,settings,shared,ui,usage}/**/*.test.ts"
test-coverage-shard:
name: Coverage Shard (${{ matrix.shard }}/8)
@@ -770,7 +770,7 @@ jobs:
--exclude=tests/** \
--exclude=**/*.test.* \
node --max-old-space-size=4096 --import tsx --import ./tests/_setup/isolateDataDir.ts --test --test-force-exit --test-concurrency=4 \
- --test-shard=${{ matrix.shard }}/8 tests/unit/*.test.ts "tests/unit/{api,auth,authz,build,cli,cli-helper,combo,compression,correctness,cors,dashboard,db,db-adapters,docs,executors,gamification,guardrails,lib,mcp,memory,runtime,security,services,settings,shared,ui,usage}/**/*.test.ts"
+ --test-shard=${{ matrix.shard }}/8 tests/unit/*.test.ts "tests/unit/{api,auth,authz,build,cli,cli-helper,combo,compression,correctness,cors,dashboard,db,db-adapters,docs,gamification,guardrails,lib,mcp,memory,runtime,security,services,settings,shared,ui,usage}/**/*.test.ts"
- name: Upload raw shard coverage
if: always()
uses: actions/upload-artifact@v7
diff --git a/.github/workflows/quality.yml b/.github/workflows/quality.yml
index e578122d0b..bc9a307d3b 100644
--- a/.github/workflows/quality.yml
+++ b/.github/workflows/quality.yml
@@ -145,4 +145,4 @@ jobs:
--import ./tests/_setup/isolateDataDir.ts
--test --test-force-exit --test-concurrency=4 --test-shard=${{ matrix.shard }}/2
tests/unit/*.test.ts
- "tests/unit/{api,auth,authz,build,cli,cli-helper,combo,compression,correctness,cors,dashboard,db,db-adapters,docs,executors,gamification,guardrails,lib,mcp,runtime,security,services,settings,shared,ui}/**/*.test.ts"
+ "tests/unit/{api,auth,authz,build,cli,cli-helper,combo,compression,correctness,cors,dashboard,db,db-adapters,docs,gamification,guardrails,lib,mcp,runtime,security,services,settings,shared,ui}/**/*.test.ts"
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 15e699bbe1..468959521e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,34 +4,6 @@
---
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-- **feat(api):** add `/v1/ocr` endpoint (Mistral OCR), an OCR provider category, and Mistral moderation support. (thanks @waguriagentic)
-- **Discovery tool (Phase 2):** add the `discoveryResults` DB module (CRUD over the `discovery_results` table, migration 074) and wire the opt-in provider-discovery service to persist and read findings through it (`persistDiscoveryResult`, `getDiscoveryResults`, `getDiscoveryResultById`, `markVerified`, `deleteDiscoveryResult`) with `(provider, method, endpoint)` upsert de-duplication. Adds the `/api/discovery/*` HTTP surface — `GET /results`, `GET|DELETE /results/:id`, `POST /scan`, `POST /verify/:id` — under **strict loopback-only** authorization (`/api/discovery/` is in `LOCAL_ONLY_API_PREFIXES` and is NOT manage-scope-bypassable, so the `scan` route's outbound probes can never be reached from a tunnel/remote origin). Adds a **dashboard UI tab** (Tools → Discovery, `/dashboard/discovery`) to run scans and review, verify, or delete findings. The service stays **opt-in / default-off**.
-- **feat(api):** expose a read-only provider plugin manifest at `GET /api/v1/provider-plugin-manifest` for sidecar/relay discovery. (thanks @KooshaPari)
-- **feat(sidecar):** advertise the provider manifest URL to Bifrost/CLIProxyAPI via the `X-OmniRoute-Provider-Manifest-Url` header (`OMNIROUTE_PROVIDER_MANIFEST_URL`). (thanks @KooshaPari)
-- **feat(autoCombo):** add a latency/speed-optimized routing mode (shared `rankBySpeed` scoring core) plus the `omniroute_pick_fastest_model` MCP tool. (thanks @KooshaPari)
-- **feat(providers):** refresh The Old LLM (Free) model catalog ([#5181](https://github.com/diegosouzapw/OmniRoute/issues/5181)) — seed the current free `/api/chatgpt` tier (GPT-5/5.1/5.2/5.3/5.4, o3/o4-mini, Gemini 3 Pro / 2.5 Pro / 2.0 Flash / 1.5 Flash, Claude 4.6 Opus/Sonnet & 4.5 Haiku, GPT-4o, Grok 4, DeepSeek V3/R1, Sonar Pro) while keeping the legacy alias IDs for saved-preference compatibility. Also fixes a latent routing bug: `mapModel()` now passes known upstream IDs through unchanged, so Gemini/o-series/Grok/DeepSeek/Sonar models no longer silently collapse onto `GPT_5_4`. Regression guard: `tests/unit/theoldllm-model-refresh-5181.test.ts`. (thanks @WslzGmzs)
-- **feat(resilience):** surface Codex **banked reset credits** per connected account ([#5199](https://github.com/diegosouzapw/OmniRoute/issues/5199)) — the Codex quota parsers (`buildCodexUsageQuotas`, `parseCodexUsageResponse`) now additively read `rate_limit_reset_credits.available_count` (+ optional `rate_limit_reached_type`) from the `/wham/usage` payload OmniRoute already fetches, and the provider-limits dashboard renders a **"Banked Reset Credits"** row when a positive count is present. Display-only and **fail-open** — the field is eligibility-gated, so accounts without it are unaffected (parsers never throw on absent/garbage shapes); redemption (an unofficial mutating endpoint) is intentionally out of scope. Regression guard: `tests/unit/codex-banked-reset-credits-5199.test.ts` (8). (thanks @ofekbetzalel)
-- **feat(providers):** add sign-up geo-restriction notices for **SenseNova** and **StepFun** ([#5462](https://github.com/diegosouzapw/OmniRoute/issues/5462)) — the provider add-form now warns that SenseNova's console appears to require a Chinese (+86) phone number with no documented international path, and that StepFun's default endpoint is its China platform while a global StepFun Open Platform (`platform.stepfun.ai`, operated by Sparkling AI Pte. Ltd., Singapore) with email/Google/Discord login exists for international users. Informational `notice` only — neither provider is disabled. Regression guard: `tests/unit/regional-provider-cn-notices-5462.test.ts`. (thanks @chirag127)
-- **feat(usage):** add on-demand period-scoped usage-data reset (Settings → System Storage) with a purge API and time-window selector.
-- **feat(claude-code):** add an opt-in auto-permission classifier compat mode (off/auto/always) for Claude Code, toggleable from the CLI Code settings.
-- **feat(providers):** add optional client-identity header profiles for compatible nodes — preset User-Agent/fingerprint headers (e.g. matching a known CLI) merged into the existing customHeaders field.
-
-### 🔧 Bug Fixes
-
-- **dashboard ("Update now" → Internal Server Error):** clicking **Update now** on the dashboard home could crash the page with a blank "Internal Server Error" screen (`Minified React error #31`). The handler POSTs the loopback-only `/api/system/version` auto-update endpoint and, on a non-OK JSON response (e.g. a `403` when the dashboard is reached through a reverse proxy / non-loopback origin), passed the raw error envelope object `{ error: { code, message, correlation_id } }` straight to `notify.error()`, which rendered the object as a React child and threw #31. The update-error path now funnels the body through `extractApiErrorMessage()` (the same safe extractor added in #5340), so a readable string always reaches the toast. Regression guard: `tests/unit/ui/home-update-error-render-5991.test.ts`. ([#5991](https://github.com/diegosouzapw/OmniRoute/issues/5991))
-
-### 📝 Maintenance
-
-- **test (deflake `setup-claude`):** `tests/unit/cli/setup-claude.test.ts` failed ~50% of runs with `Unable to deserialize cloned data due to invalid or unsupported version` at file teardown (all subtests passed), randomly reddening `Unit Tests fast-path (2/2)` / `Fast Quality Gates` across the PR→release queue. Root cause: `node --test` streams each file's report to the parent as V8-serialized frames on fd 1 (stdout), and the CLI helper under test (`syncClaudeProfilesFromModels`) prints progress via `console.log` — that stdout output interleaved with the serialized frames and corrupted the stream. The test now silences the stdout-writing `console` methods for the file's duration (no assertion inspects stdout), making it deterministic (15/15 green locally). ([#5959](https://github.com/diegosouzapw/OmniRoute/issues/5959))
-
-- **API validation:** add a `validatedJsonBody(request, schema)` helper in `src/shared/validation/helpers.ts` that fuses JSON body parsing and Zod validation into a single call, returning either the type-narrowed data or a ready-to-return 400 `NextResponse` with the standard error envelope. Salvaged from the closed refactor PR #5075 (Tier 1 portable helper) with a focused 6-case regression test. Co-authored-by: KooshaPari <[email protected]>
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
@@ -102,8 +74,6 @@
- **providers (CLI profile auto-sync):** opt-in CLI profile auto-sync toggles, including Claude Code auto-sync, so generated CLI profiles can track provider changes automatically. ([#5755](https://github.com/diegosouzapw/OmniRoute/pull/5755) — thanks @diegosouzapw)
-- **feat(minimax):** surface MiniMax M3 `<think>` reasoning as `reasoning_content` on OpenAI-format provider tiers. (thanks @zmf963)
-
### 🔧 Bug Fixes
- **fix(opencode):** stop fabricating `User-Agent: opencode/local` and `x-opencode-client: cli` headers when the client sends none — the executor-dedup refactor ([#5720](https://github.com/diegosouzapw/OmniRoute/pull/5720)) accidentally re-introduced header fabrication, violating the forward-only contract (inventing opencode-internal values risks upstream rejection). Restored to forward-only: those headers are emitted only when a real client source is present. Regression guard: `tests/unit/opencode-executor.test.ts`. (thanks @diegosouzapw)
diff --git a/CLAUDE.md b/CLAUDE.md
index 12d4e1c41e..dcfda7c548 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -541,9 +541,6 @@ the stale-enforcement added in Fase 6A.3.
19. Never develop on the shared main checkout. Every development task runs in its own git worktree on its own dedicated branch, and you MUST confirm the base branch with the operator (e.g. via `AskUserQuestion`) before creating the worktree/branch — never assume `main` or the currently checked-out branch. A `git checkout` in the shared checkout silently destroys other sessions' uncommitted work. Tear down only the worktrees/branches you created (by name, never `fix/*`/`feat/*` wildcards), leave other sessions' worktrees untouched, and end on the branch you started on (the active `release/vX.Y.Z`, never `main`). See Git Workflow → "Worktree isolation".
20. PII redaction/sanitization is **opt-in — never on by default**. OmniRoute proxies for self-hosted/local LLMs where the operator owns the data, so mutating request/response payloads by default would silently corrupt legitimate traffic. The two data-mutating PII feature flags **MUST** keep `defaultValue: "false"` in `src/shared/constants/featureFlagDefinitions.ts`: `PII_REDACTION_ENABLED` (request-side) and `PII_RESPONSE_SANITIZATION` (response + streaming). All three application points — `src/lib/guardrails/piiMasker.ts` (request guardrail), `src/lib/piiSanitizer.ts` (response), `src/lib/streamingPiiTransform.ts` (SSE) — are gated on these flags; with both off the `pii-masker` guardrail still runs but never mutates payloads (data passes through untouched). Flipping either default to `"true"` requires explicit operator approval. The regression guard is `tests/unit/pii-opt-in-default.test.ts` (asserts both definition defaults + behavioral pass-through). Opt-in is per-operator via env or the settings/DB override (`src/lib/db/featureFlags.ts`), never a silent default. See `docs/security/GUARDRAILS.md`.
21. **Release-freeze — the release branch is frozen to campaign merges while a `/generate-release` is running.** `/generate-release` opens a marker issue labeled `release-freeze` at the start of reconciliation (Phase 0a) and closes it once the release PR squash-merges to `main`. Before merging **any** PR into the active `release/vX.Y.Z` branch, every campaign workflow (`/review-issues`, `/review-prs`, `/implement-features`, `/green-prs`, `/port-upstream-*`) **MUST** check `gh issue list --repo diegosouzapw/OmniRoute --label release-freeze --state open` — if a freeze is active, **HOLD the merge** (leave the PR ready and open; do NOT merge to the release branch), tell the operator, and resume once the freeze lifts. This is a **coordination signal, not a permission lock**: the release captain and the campaign sessions share the `diegosouzapw` identity, so a GitHub branch-protection lock cannot distinguish them — only this honored marker prevents the mid-release commit races that forced full CHANGELOG re-reconciliation in v3.8.40/v3.8.41 (a parallel campaign advanced `release/vX.Y.Z` by 34 commits mid-run). The release captain's own reconciliation/cycle-open pushes are exempt — they _are_ the release. Fixes that must land during a freeze (a homologation finding) follow the post-merge read-only rule: land on `main` first via `fix/release-vX.Y.Z-*`. **⛔ ONLY `/generate-release` may raise a release-freeze, and ONLY at its Phase 0a (start of generating a new version) — lifted at Phase 12c after the squash-merge to `main`.** No campaign, session, or agent may open a `release-freeze` marker at any other time — a freeze is **never** a mid-development coordination tool. If a session ever believes a freeze is genuinely, unavoidably necessary outside the `/generate-release` flow, it **MUST first ask the operator (`diegosouzapw`) in chat, explicitly alert "estou criando um freeze" and get an explicit yes** — never open, extend, or re-open a `release-freeze` autonomously. Conversely, do **not** close/lift an active `/generate-release` freeze to unblock campaign merges: it protects the captain's single clean CI run and auto-lifts at Phase 12c — closing it early re-triggers the exact commit race it prevents. Verify a freeze is legitimate before acting on it: an open `release-freeze` whose title/body references an **OPEN** release PR (`gh pr view <N> --json state`) is the authorized captain freeze — hold, don't touch.
-22. **Cross-session safety — this repo is worked by MANY parallel sessions/agents at once; never step on another's in-flight work.** Two absolute bans, both recurring incidents (this rule exists because they keep happening):
- - **(a) Never `git stash` / `git stash pop` — ANYWHERE in this repo, including inside an isolated worktree, and including inside any subagent you dispatch.** `git stash` operates on the **shared repository object store**, not the per-worktree working tree — so a stash pushed or popped in one session can silently clobber or resurrect another parallel session's uncommitted changes. This is not hypothetical: 2026-07-02 a `#5923` quotaCache change leaked into the unrelated `#2296` worktree via a global `stash pop`, and the same class reincided through a **subagent**. To compare working changes against a base ref **without** stashing, use `git show <ref>:<path>` or `git diff <ref> -- <path>`; to confirm a typecheck/lint error is pre-existing on the base, inspect the base ref directly (`git show origin/release/vX.Y.Z:<path>`) — never stash your tree away to "get it clean". **Put this ban verbatim in the prompt of every subagent that touches git** (agents don't inherit this file's context — the recurrence was a subagent).
- - **(b) Never merge, push, rebase, or force-push a PR / branch / worktree that another session is actively working.** An open PR whose head is a live fix worktree in `.claude/worktrees/` you did **not** create (e.g. `fix-5852`/`fix-5923` carrying fresh commits, even when they share your `diegosouzapw` identity), or any branch another session owns, is **off-limits — HOLD**, and let the owning session merge it. **Before** merging or pushing to any PR you did not create *this* session, run `git worktree list` to check for a matching in-flight worktree and re-check `gh pr view <N> --json state,headRefOid`. Only the owning session merges its own in-flight PR; mid-flight merges race the owner and re-trigger the exact commit/CHANGELOG races Rule #19 and Rule #21 guard against. (Reinforces Rule #19.)
---
diff --git a/bin/cli/commands/setup-claude.mjs b/bin/cli/commands/setup-claude.mjs
index 6badd3aa3c..2bdedfa64b 100644
--- a/bin/cli/commands/setup-claude.mjs
+++ b/bin/cli/commands/setup-claude.mjs
@@ -56,7 +56,7 @@ export function buildProfileSettings(modelId, baseUrl, cfg) {
* behaviorally identical. Writes `<claudeHome>/profiles/<name>/settings.json`
* (directory-per-profile); never touches the active/default Claude config.
* @param {Array} models
- * @param {{claudeHome?:string, baseUrl:string, dryRun?:boolean, only?:string, log?:(line:string)=>void}} opts
+ * @param {{claudeHome?:string, baseUrl:string, dryRun?:boolean, only?:string}} opts
* @returns {Promise<{written:number, skipped:number, profiles:Array<{name:string, model:string, filePath:string}>}>}
*/
export async function syncClaudeProfilesFromModels(models, opts = {}) {
@@ -64,12 +64,6 @@ export async function syncClaudeProfilesFromModels(models, opts = {}) {
const profilesRoot = join(claudeHome, "profiles");
const baseUrl = opts.baseUrl;
const dryRun = Boolean(opts.dryRun);
- // Injectable dry-run printer (#5959): under the node:test runner, a child
- // process writing multi-byte UTF-8 (the "──" box-drawing heading) to stdout
- // corrupts the runner's V8-serialized event stream ~50% of the time
- // ("Unable to deserialize cloned data due to invalid or unsupported
- // version"). Tests inject a collector; the CLI default stays console.log.
- const log = opts.log ?? console.log;
const onlyFilter = opts.only ? opts.only.split(",").map((s) => s.trim()) : null;
if (!dryRun && !existsSync(profilesRoot)) {
@@ -102,8 +96,8 @@ export async function syncClaudeProfilesFromModels(models, opts = {}) {
const content = buildProfileSettings(id, baseUrl, cfg);
if (dryRun) {
- log(`\n── [dry-run] ${filePath} ──`);
- log(content);
+ console.log(`\n── [dry-run] ${filePath} ──`);
+ console.log(content);
} else {
mkdirSync(dir, { recursive: true });
writeFileSync(filePath, content, "utf8");
diff --git a/config/quality/complexity-baseline.json b/config/quality/complexity-baseline.json
index ba285566ed..4114fd995a 100644
--- a/config/quality/complexity-baseline.json
+++ b/config/quality/complexity-baseline.json
@@ -1,10 +1,6 @@
{
"_comment": "Catraca de complexidade (check-complexity.mjs, ESLint core rules complexity>=15 e max-lines-per-function>80 sobre src+open-sse+electron+bin via eslint.complexity.config.mjs). Conta total de violacoes; so pode cair. --update ratcheta.",
- "count": 2015,
- "_rebaseline_2026_07_03_6007_sidecar_manifest": "2007->2015. PR #6007 (re-cut) adds sidecar/provider-manifest header wiring and the public manifest URL helper; the feature files themselves introduce 0 new complexity violations (check-complexity flags none in providerPluginManifestUrl.ts). The +8 vs the 2007 release baseline is inherited release/v3.8.44 drift absorbed at merge (check:complexity measures 2015 on the current release tip). Tighten via --update next cycle / at /generate-release Phase 0.",
- "_rebaseline_2026_07_02_v3844_ci_observed": "2006->2007 (+1). Local Ubuntu measures 2006 on this tree; the GitHub fast-gates runner measures 2007 (same local-vs-CI off-by-one already documented in _rebaseline_2026_06_26_v3838_release_fast_gate). Use the CI-observed value so the gate is deterministic where it actually runs.",
- "_rebaseline_2026_07_02_v3844_post_5939": "2003->2006 (+3). Inherited drift from the release/v3.8.44 merges after 3a3d618fe (#5809 audio translations et al.), surfaced by PR fix#5959: check:complexity measures 2006 on the pristine base (cbd08ef78) WITH AND WITHOUT this PR's one-line CLI change (verified by reverting the file and re-measuring) — the PR is complexity-net-zero. Tighten via --update next cycle.",
- "_rebaseline_2026_07_02_v3844_merge_burst": "1995->2003 (+8). Inherited v3.8.44 cycle drift surfaced by PR #5939: check:complexity measures 2003 on BOTH the pristine release tip (3a3d618fe) and this PR's merged HEAD — identical, so all +8 came from the 2026-07-02 merge burst into release/v3.8.44 (#5933 codex schema, #5950 OCR, #5904/#5920 combo, #6000/#6008 executor refactors, etc.) merged while the fast-gates queue was base-red (file-size #5933). PR #5939 itself was verified complexity-net-zero during its own CI cycle (DiscoveryPageClient refactored into hooks/sub-components to stay under max-lines-per-function). Tighten via --update next cycle.",
+ "count": 1995,
"_rebaseline_2026_07_02_5798_release_green": "1982->1995 (+13). Inherited v3.8.43 cycle drift surfaced by the release-green unblock #5798 / PR #5896: check:complexity measures 1995 on BOTH the pristine release tip (0d3875a98) and this PR's HEAD — identical, so all +13 came from the 2026-07-01/02 merge burst (providers/usage/dashboard fixes merged via --admin while the fast-gates queue was base-red). This PR touches only gate scripts, docs, baselines and test files — 0 production logic. Tighten via --update next cycle.",
"_rebaseline_2026_07_01_v3843_release": "1981->1982 (+1). v3.8.43 cycle drift, surfaced after check:mutation-test-coverage was fixed (it was masked behind that earlier step in the Fast Quality Gates chain). 1982 = the value measured by check:complexity on BOTH fce85136c (release tip) and 6d7060e21 (release + the 5 CI fixes) — identical, so all +1 is inherited cycle drift; the fixes touch only test files + linkify.ts safeHttpHref (cyclomatic ~4, well under the >=15 threshold, 0 new violations) + config JSON. Tighten via --update next cycle.",
"_rebaseline_2026_06_28_v3840_5237_reconcile": "1980->1981 (+1). Inherited release/v3.8.40 drift surfaced while merging PR #5237 (impersonation-UA refresh) — the +1 is present on the pristine release tip (d8a392a47) WITHOUT #5237's changes, so it is #5222 (antigravity fallback-LRU retry) / #5221 (command-code) growth that merged via --admin without ratcheting complexity (the PR->release fast-gates do not run check:complexity). #5237 itself is complexity-net-zero: its only edits are a single UA constant, a regenerated golden snapshot, and baseline JSONs. Structural reduction tracked in #3501.",
diff --git a/config/quality/file-size-baseline.json b/config/quality/file-size-baseline.json
index c014e793d3..15a134b796 100644
--- a/config/quality/file-size-baseline.json
+++ b/config/quality/file-size-baseline.json
@@ -1,6 +1,5 @@
{
"_comment": "Catraca de tamanho (check-file-size.mjs). frozen so pode encolher; arquivos novos <= cap. --update ratcheta.",
- "_rebaseline_2026_07_03_review_prs_release_green": "Release-green unblock (2026-07-03, /review-prs): the quality.yml fast-gates job was base-red for EVERY PR->release from growth inherited via already-merged PRs on the release tip — no offending PR branch left to fix in-place. Prod frozen raised: ApiManagerPageClient.tsx 3017->3058, OAuthModal.tsx 969->989, cliRuntime.ts 1090->1100, webProvidersA.ts 805->809. Test frozen raised: deepseek-web.test.ts 1081->1092. Real sizes (check-file-size.mjs reported). These stay frozen (cannot grow further); structural shrink tracked under decomposition roadmap #3501; the release captain's rebaseline-at-release supersedes this note. Bundled with the #5695 quick-start test regex fix (multi-line <Link> tolerance) in the same release-green PR.",
"_rebaseline_2026_07_02_5798_release_green": "Release-green unblock #5798 / PR #5896 (2026-07-02): the quality.yml fast-gates job was base-red for EVERY PR->release (whole queue failing), from growth inherited via already-merged PRs — no offending PR branch left to fix. Prod frozen raised: AddApiKeyModal.tsx 869->905, providerPageHelpers.ts 996->1021, RequestLoggerV2.tsx 1316->1553, src/sse/services/auth.ts 2403->2405, antigravity.ts 1806->1813, base.ts 1502->1536 (1533 inherited + 3 lines from this PR's own typecheck:core fix in resolveBaseUrl), advancedTools.ts 1118->1120, accountFallback.ts 1783->1790, openai-to-kiro.ts 842->853, openai-responses.ts 1035->1092, stream.ts 2710->2727; new-above-cap frozen: webProvidersA.ts 805, tokenHealthCheck.ts 830. Test frozen raised: cc-compatible-provider 1179->1217, translator-openai-to-kiro 999->1088, web-cookie-providers-new 827->845; new-above-cap: response-sanitizer.test.ts 906. These files remain frozen (cannot grow further); the release captain's rebaseline-at-release supersedes this note.",
"_rebaseline_2026_06_30_5552_flat_rate_cost": "Issue #5552 own growth: src/app/api/usage/analytics/route.ts 941->942 (+1 = the `flatRateAsZero: true` cost option at the existing computeUsageRowCost chokepoint, so subscription/cookie-web providers show $0 instead of an inflated per-token estimate in analytics). The flat-rate classifier (isFlatRateProvider + the provider-id set) lives in a new leaf src/lib/usage/flatRateProviders.ts (61 LOC, <cap) and the guard in computeCostFromPricing (src/lib/usage/costCalculator.ts, not baselined). Irreducible 1-line wiring at the analytics chokepoint; covered by tests/unit/flat-rate-cost-5552.test.ts.",
"_rebaseline_2026_06_30_5483_force_responses_upstream": "PR #5637 (@KooshaPari, #5483) own growth: open-sse/executors/base.ts 1500->1502 (+2 = import + the single `requestCredentials = withForcedResponsesUpstream(...)` const threaded through buildUrl/buildHeaders/applyConfiguredUserAgent/ccRequestDefaults/transformRequest at the existing fetch-loop chokepoint), open-sse/executors/default.ts 876->877 (+1 = the `_omnirouteForceResponsesUpstream` short-circuit in the buildUrl `/responses` vs `/chat/completions` decision), tests/unit/executor-default-base.test.ts 1477->1523 (+46 = the new regression test that asserts a Responses-shaped MCP request routes to /responses for openai-compatible providers). The detection helpers (shouldForceResponsesUpstream/withForcedResponsesUpstream/isRecord, ~50 LOC) were EXTRACTED out of base.ts into a new leaf open-sse/executors/forceResponsesUpstream.ts (60 LOC, <cap) so the frozen god-file only takes the irreducible 2-line wiring. The contributor PR's incidental prettier reformats were reverted to keep the diff scoped to the fix. Covered by tests/unit/executor-default-base.test.ts.",
@@ -132,8 +131,6 @@
"_rebaseline_2026_06_20_4389_thinking_toolchoice": "Re-baseline base.ts 1387->1399 (#4389): tool_choice-forced thinking guard at the existing Claude wire-image injection chokepoint (effThinking gate avoids the Anthropic 400 when tool_choice forces a tool). Cohesive guard; structural shrink tracked in #3501.",
"cap": 800,
"frozen": {
- "_rebaseline_2026_07_02_5816_qoder": "PR #5816 (@AgentKiller45, qoder PAT via qodercli): qoderCli.ts 666->989, new-above-cap frozen (owner-approved baseline freeze). The growth is the legitimate PAT job-token exchange + quota parsing CLI transport (the pure-JS Cosy path 500'd on every PAT request); extracting the spawn/parse helpers now would just add indirection to a contributor PR mid-merge. Test frozen also raised for this PR's coverage growth: providers-page-utils.test.ts 1052->1092. Additionally clears an inherited base-red from the already-merged #5933 (codex json_schema->text.format): translator-openai-responses-req.test.ts 1097->1172 (+75 regression tests, no offending branch left). All remain frozen (cannot grow further); release captain's rebaseline-at-release supersedes.",
- "open-sse/services/qoderCli.ts": 989,
"_rebaseline_pr1043_minimax_tts": "Upstream port decolua/9router#1043 (toanalien) own growth: audioSpeech.ts 965->1061 (+96). Adds MiniMax T2A v2 TTS dispatch (handleMinimaxSpeech + hexToBytes helper) — provider entry was already in audioRegistry (format: minimax-tts) but no handler existed, falling through to the OpenAI-compatible default that fails (T2A has custom shape + hex-encoded audio + base_resp envelope). New branch sits next to the other inline provider branches (xiaomi-mimo, coqui, tortoise, aws-polly) — extracting would just create indirection. Covered by tests/unit/minimax-tts-1043.test.ts (3 tests, GREEN: success, base_resp error, invalid-hex).",
"open-sse/config/providerRegistry.ts": 4731,
"open-sse/executors/antigravity.ts": 1813,
@@ -185,7 +182,7 @@
"open-sse/utils/stream.ts": 2727,
"src/app/(dashboard)/dashboard/HomePageClient.tsx": 1385,
"src/app/(dashboard)/dashboard/analytics/ComboHealthTab.tsx": 1028,
- "src/app/(dashboard)/dashboard/api-manager/ApiManagerPageClient.tsx": 3058,
+ "src/app/(dashboard)/dashboard/api-manager/ApiManagerPageClient.tsx": 3017,
"src/app/(dashboard)/dashboard/cache/media/MediaPageClient.tsx": 1105,
"src/app/(dashboard)/dashboard/cache/page.tsx": 845,
"src/app/(dashboard)/dashboard/cli-code/components/CodexToolCard.tsx": 900,
@@ -212,7 +209,7 @@
"src/app/(dashboard)/dashboard/settings/components/CompressionSettingsTab.tsx": 974,
"src/app/(dashboard)/dashboard/settings/components/MemorySkillsTab.tsx": 898,
"src/app/(dashboard)/dashboard/settings/components/PricingTab.tsx": 1012,
- "src/app/(dashboard)/dashboard/settings/components/ProxyRegistryManager.tsx": 1117,
+ "src/app/(dashboard)/dashboard/settings/components/ProxyRegistryManager.tsx": 1089,
"src/app/(dashboard)/dashboard/settings/components/ResilienceTab.tsx": 1183,
"src/app/(dashboard)/dashboard/settings/components/RoutingTab.tsx": 1629,
"src/app/(dashboard)/dashboard/settings/components/SystemStorageTab.tsx": 1924,
@@ -243,14 +240,14 @@
"src/lib/usage/providerLimits.ts": 955,
"src/lib/usage/usageHistory.ts": 988,
"_rebaseline_2026_06_27_5193_5203_antigravity_oauthmodal": "Antigravity remote-login own growth: OAuthModal.tsx 960->969 (gate units). #5193 (+~4: remote paste instruction shown for all remote incl. Google + its rationale comment) and #5203 (+~5: handleManualSubmit credential-blob branch + button guard; submit logic extracted to oauthBlobSubmit.ts to minimize). Frozen set to the SUM so either merge order passes. Cohesive at the existing manual-submit chokepoint.",
- "src/shared/components/OAuthModal.tsx": 989,
+ "src/shared/components/OAuthModal.tsx": 969,
"src/shared/components/RequestLoggerV2.tsx": 1553,
"src/shared/components/analytics/charts.tsx": 1558,
"src/shared/constants/cliTools.ts": 875,
"src/shared/constants/pricing.ts": 1662,
"src/shared/constants/providers.ts": 3276,
"src/shared/constants/sidebarVisibility.ts": 1198,
- "src/shared/services/cliRuntime.ts": 1100,
+ "src/shared/services/cliRuntime.ts": 1090,
"src/shared/validation/schemas.ts": 2523,
"_rebaseline_2026_06_28_5275_correlation_id_extract": "Extraction of the safe CorrelationId subset of #5275 (hartmark) — request correlation id stored in call_logs (migration 109) and returned via the X-Correlation-Id response header, WITHOUT the combo/resilience or build/lazy-loading changes (those stay in #5275). Own growth: callLogs.ts 975->985 (correlation_id column on CallLogSummaryRow + read/map), usageHistory.ts 983->988 (correlationId metadata normalize), chat.ts 1575->1632 (withCorrelationId response wiring + combo-failure log carrying correlationId), chatHelpers.ts new 811 (withCorrelationId helper + reqId threading; was 791<cap pre-feature). Cohesive request/logging chokepoint wiring; structural shrink of chat.ts tracked in #3501.",
"src/sse/handlers/chat.ts": 1647,
@@ -264,7 +261,7 @@
"tests/unit/provider-validation-specialty.test.ts": 2843,
"open-sse/executors/huggingchat.ts": 813,
"_rebaseline_2026_07_01_v3843_release_5609": "Rebaseline v3.8.43 (PR #5609 release reconciliation). DRIFT dos 109 commits do ciclo: 8 god-files existentes cresceram (ApiManagerPageClient 2983->3017, combos/page 4594->4608, AddApiKeyModal 868->869, providerPageHelpers 974->996, chat.ts 1635->1647, auth.ts 2401->2403, batchProcessor 828->915, combo.ts 3368->3387) + 2 novos acima do cap (huggingchat.ts 813, tests web-cookie-providers-new 827) + 4 test files cresceram. Modularizacao deferida (blast-radius mid-release); congelado no estado atual p/ o proximo ciclo ratchetar daqui.",
- "src/lib/providers/validation/webProvidersA.ts": 809,
+ "src/lib/providers/validation/webProvidersA.ts": 805,
"src/lib/tokenHealthCheck.ts": 830
},
"testCap": 800,
@@ -284,7 +281,7 @@
"tests/unit/db-core-init.test.ts": 877,
"tests/unit/db-migration-runner.test.ts": 1491,
"tests/unit/db-settings-crud.test.ts": 941,
- "tests/unit/deepseek-web.test.ts": 1092,
+ "tests/unit/deepseek-web.test.ts": 1081,
"tests/unit/executor-antigravity.test.ts": 942,
"tests/unit/executor-codex.test.ts": 1347,
"tests/unit/executor-default-base.test.ts": 1523,
@@ -297,10 +294,10 @@
"_rebaseline_2026_06_27_5193_antigravity_test": "#5193 own test growth: oauth-providers-config.test.ts 870->873 (+3: antigravity projectId assertion + 50ms tick for the now fire-and-forget onboarding, matching the no-PKCE/no-openid flow).",
"tests/unit/oauth-providers-config.test.ts": 873,
"tests/unit/perplexity-web.test.ts": 959,
- "tests/unit/provider-models-route.test.ts": 1752,
+ "tests/unit/provider-models-route.test.ts": 1628,
"tests/unit/provider-validation-specialty.test.ts": 2874,
"_rebaseline_pr4613_compatible_provider_groups": "Reconcile #4613 already-merged growth: providers-page-utils.test.ts 1004->1052 (+48, buildCompatibleProviderGroups partition unit test). Fast-gate PR->release does not run check:file-size, so this surfaced post-merge.",
- "tests/unit/providers-page-utils.test.ts": 1109,
+ "tests/unit/providers-page-utils.test.ts": 1052,
"tests/unit/reasoning-cache.test.ts": 980,
"tests/unit/route-edge-coverage.test.ts": 1234,
"tests/unit/search-handler-extended.test.ts": 1124,
@@ -309,15 +306,14 @@
"tests/unit/token-refresh-service.test.ts": 1353,
"tests/unit/translator-friendly-test-bench.test.tsx": 848,
"tests/unit/translator-helper-branches.test.ts": 870,
- "tests/unit/translator-openai-responses-req.test.ts": 1172,
+ "tests/unit/translator-openai-responses-req.test.ts": 1097,
"tests/unit/translator-openai-to-gemini.test.ts": 1579,
- "tests/unit/translator-openai-to-kiro.test.ts": 1093,
+ "tests/unit/translator-openai-to-kiro.test.ts": 1088,
"tests/unit/translator-resp-gemini-to-openai.test.ts": 1234,
"tests/unit/usage-service-hardening.test.ts": 1633,
"tests/unit/vscode-token-routes.test.ts": 1212,
"tests/unit/combo-config.test.ts": 881,
- "_rebaseline_2026_07_02_5928_base_red": "web-cookie-providers-new.test.ts 845->850: #5928 (test(security) Kimi Web URL host parse, CodeQL #689) grew the file +5 lines and merged into release/v3.8.44 WITHOUT rebaselining, leaving a fast-gates base-red that blocked every subsequent PR->release. Test growth is legitimate (a security regression test); maintainer absorbs the drift here. Frozen at 850.",
- "tests/unit/web-cookie-providers-new.test.ts": 850,
+ "tests/unit/web-cookie-providers-new.test.ts": 845,
"tests/unit/response-sanitizer.test.ts": 906
},
"_rebaseline_2026_06_09": "Re-baseline consciente pre-release v3.8.19: 9 arquivos cresceram durante o ciclo (features mergeadas: RequestLoggerV2 +281 request-logger rework, stream +101, combo +73, chatCore +45, catalog +32 fable-5/catalog-flag, callLogs +4, accountFallback +2, usageHistory novo 840) + core.ts +7 (fix resetAllDbModuleState, PR 3536). A catraca segue valendo destes valores — proximo crescimento falha. Decisao: encolher (esp. RequestLoggerV2/chatCore) e a issue #3501 ficam para o ciclo seguinte.",
@@ -342,7 +338,6 @@
"_rebaseline_2026_06_13_2743d_skipbreaker": "Re-baseline #2743 gap-d (testar consumer do skipProviderBreaker): combo.ts 5131→5162 (+31). Crescimento = extração do boolean inline da decisão de circuit-breaker para o predicado puro EXPORTADO shouldRecordProviderBreakerFailure() (byte-idêntico) + JSDoc, para torná-lo unit-testável sem o harness completo de combo. Shrink estrutural segue com #3501.",
"_rebaseline_2026_06_13_v3825_prettier_reconcile": "Reconciliação tardia: o prettier do pre-commit reformatou 3 arquivos DEPOIS da medição de file-size dos PRs, inflando linhas além do baseline setado — OAuthModal.tsx 956→960 e providers.ts 3146→3147 (#3324), combo.ts 5162→5164 (#2743d). Bumps de reformatação automática (sem lógica nova). LIÇÃO: medir file-size pós-commit (pós-prettier), não antes.",
"_rebaseline_2026_06_14_3826_release_drift": "Re-baseline release/v3.8.25 drift already documented from #3809 owner changes: ProxyRegistryManager.tsx 1072→1089, sidebarVisibility.ts 990→1006, schemas.ts 2519→2522. This PR does not touch those source files; updating the frozen values restores Fast Quality Gates on the current release branch.",
- "_rebaseline_2026_07_03_5918_proxy_batch": "PR #5918 own growth: ProxyRegistryManager.tsx 1089→1117 (+28 = wiring the new batch-select/Test-All proxy management components — checkboxes, batch actions bar, health cells). Cohesive UI wiring for the batch-delete/auto-test feature; the reusable pieces already live in separate leaf components (ProxyBatchActions/ProxyCheckboxCell/ProxyHealthCell/useProxyBatchOperations). Legitimate feature growth, not a quality regression.",
"_rebaseline_2026_06_14_3825_combo_stickiness": "Re-baseline #3825 (sessionless combo stickiness + reasoning-aware readiness): combo.ts 5164→5198 (+34, pós-prettier). Crescimento = deriveComboSessionKey() + effectiveSessionId threading nos sites de read/write do pin server-side. streamReadinessPolicy.ts não-frozen (sob cap). Lógica coesa no handler de combo; não-extraível.",
"_rebaseline_2026_06_14_r3_3835_kiro_pricing": "PR #3835 own growth: pricing.ts 1470→1508 (+38 = missing Kiro pricing rows, claude-sonnet-4.6 etc., pure data). Also carries inherited release/v3.8.25 drift not yet frozen by prior r2 merges: RequestLoggerV2.tsx 1276→1282 (#3820 resizable log table) and combo.ts 5198→5203 (#3811 round-robin replay-response fix). This PR does not touch RequestLoggerV2/combo.ts source; updating the frozen values restores Fast Quality Gates on the current release branch.",
"_rebaseline_2026_06_14_r3_3849_transient_hide": "PR #3849 own growth: providerPageHelpers.ts 939→955 (+16 = expanded JSDoc on the auto-hide policy + transient-failure guard in evaluateTestAllEntry). Cohesive helper logic; not extractable.",
@@ -360,7 +355,6 @@
"_rebaseline_2026_06_17_4107_pending_reaper": "PR #4107 own growth: usageHistory.ts 854->934 (+80 = orphaned-pending-request reaper — sweepStalePendingRequests() evicts pending details older than 15min + a hard 5000 cap, plus an unref'd 5min sweep timer wired lazily into trackPendingRequest). Fixes an unbounded memory leak where abnormally-terminated requests left payload previews in pendingById forever. Cohesive with the existing pending-request bookkeeping (mirrors the normal removal path: decrement counters + cleanup buckets); not extractable.",
"_rebaseline_2026_06_17_4116_combo_hedge_listener": "combo.ts: +9 lines from #4116 (detach per-target listener from shared hedge abort signal to fix a listener leak). Behavior-preserving cleanup; 5289 -> 5298.",
"_rebaseline_2026_06_20_4355_gpt5x_pro_pricing": "PR #4355 own growth: pricing.ts 1581->1592 (+11 = pure-data pricing rows for openai gpt-5.5-pro + gpt-5.4-pro, closing the $0 gap that tripped the catalog pricing gate after the #4324 sweep added them to the registry; -pro mirrors its base family tier). provider-models-route.test.ts 1616->1618 (+2 = test-only alignment to the intentional opencode-go discovery behavior: owned_by stamp + T39 two-endpoint fail-path fetchCalls). Both are data/test-only; not extractable.",
- "_rebaseline_2026_07_02_5899_airforce_v1_discovery": "PR #5904 own growth: provider-models-route.test.ts 1628->1752 (+124 = test-only Rule #18 regression guards for the Api Airforce /v1/v1/models discovery bug (#5899): (a) a baseUrl ending in /v1/chat/completions must probe .../v1/models not the doubled .../v1/v1/models, and the host-guard case http://v1; (b) a REDIRECT_BLOCKED on one candidate must continue to the next endpoint instead of aborting the probe loop. Both guards fail on the pre-fix code. Test-only additions cohesive with the existing provider-models discovery suite (shared seedConnection/callRoute harness); not separately extractable without duplicating the harness.",
"_rebaseline_2026_06_19_4293_codex_spark_scope": "PR #4293 (isolate Codex Spark quota scope) own growth, MEASURED on the actual merged tree (release/v3.8.30 + #4293). Production: auth.ts 2219->2279 (+60) threads requestedModel into Codex quota-policy/headroom/preflight/P2C scoring so normal Codex and GPT-5.3-Codex-Spark windows are evaluated independently; chatCore.ts 5116->5125 (+9) passes the failing model scope into Codex 429 failover (markCodexScopeRateLimited) instead of a connection-wide rateLimitedUntil write; accountFallback.ts 1727->1731 (+4) scopes Codex model-lock keys to codex vs spark. Heavy parsing/display logic lives in new leaf helpers under the cap (codexQuotaScopes.ts, codexUsageQuotas.ts, codexFailover.ts). Tests: account-fallback-service 1544->1569, executor-codex 1336->1339, sse-auth 1527->1553, usage-service-hardening 1612->1633 (added Spark-scope regression coverage). Cohesive wiring at existing selection/failover lockout boundaries; not extractable.",
"_rebaseline_2026_06_20_4447_openai_gpt41mini_o_mini_pricing": "PR #4447 own growth: pricing.ts 1592->1620 (+28 = pure-data pricing rows closing the null/$0 gap for registry-exposed OpenAI ids gpt-4.1-mini, gpt-4.1-nano, o3-mini, o4-mini that tripped the catalog pricing gate; getPricingForModel does an exact lookup, so a missing key resolves to null. Official OpenAI per-1M prices + the table's derived-field convention (reasoning=output*1.5, cache_creation=input, cached=official). Restore-green for a pre-existing release/v3.8.32 red surfaced by #4432's __RUN_ALL__ run. Cohesive data; not extractable.",
"_rebaseline_2026_06_20_web_cookie_validator_shadow_fix": "validation.ts 4518->4522 (+4 = move the generic web-cookie validateWebCookieProvider dispatch from the TOP of validateProviderApiKey to a FALLBACK after SPECIALTY_VALIDATORS, plus a comment, so #4023's generic AUTH_007 ping no longer shadows the rich per-provider validators (grok-web #3474 IP-reputation/Cloudflare, chatgpt-web cf-mitigated, claude/gemini/copilot/qwen/t3-web). Restores provider-validation-specialty.test.ts (112/112) while keeping web-cookie-auth007 (5/5). Behavior fix at an existing dispatch boundary; not extractable.",
diff --git a/config/quality/quality-baseline.json b/config/quality/quality-baseline.json
index 0dcd251ef2..e85d042676 100644
--- a/config/quality/quality-baseline.json
+++ b/config/quality/quality-baseline.json
@@ -2,8 +2,7 @@
"_comment": "Catraca de qualidade. 'down' = nao pode aumentar; 'up' = nao pode cair. Atualize via 'npm run quality:ratchet -- --update' (somente quando melhora). Cada valor e um numero REAL medido, nunca um chute. Cobertura entra na Fase 4 a partir de um run de cobertura mergeada no CI.",
"metrics": {
"eslintWarnings": {
- "value": 4256,
- "_rebaseline_2026_07_03_v3844_review_prs_fix_batch": "4199->4256 (+57). Inherited v3.8.44 cycle drift surfaced by the release-green pre-flight (the Quality Ratchet does NOT run on PR->release fast-gates, so warnings accrue unmeasured across the cycle). 4256 = measured by `node scripts/quality/collect-metrics.mjs` on the release tip 72ee80649 during the /review-prs fix-batch round. The round's own merges (#5958 SSE-accept, #5988 deepseek-web, #6013/#5974 retry-after-json, #5975 embeddings-proxy, #5973 non-json-guard) plus the parallel-session merge burst into release/v3.8.44 account for the delta; all `any`-warn-allowed in open-sse/ + tests/. Cyclomatic is already green (2012 < baseline 2015) and needs no bump. Tighten via --require-tighten next cycle.",
+ "value": 4199,
"_rebaseline_2026_07_02_v3843_release_close": "4158->4199 (+41). v3.8.43 release-close drift measured by the release-green pre-flight (the Quality Ratchet does NOT run on PR->release fast-gates, so warnings accrued unmeasured across the ~120 commits merged after the mid-cycle 4158 rebaseline — the compression T02/T05/T06/T07/T08/T10 engine families, memory typed decay, provider adds Ollama/SenseNova, ~55 SSE/translator/kiro/oauth/dashboard fixes, and the god-file decomposition wave). Trust-but-verify: measured 4199 via `npm run lint` on the release-finalize working tree INCLUDING my changes (CHANGELOG/i18n/README docs + kiro pricing data entry + the 3 base-red CODE fixes: opencode fabrication removal, resolveEffectiveKey type-widen, openai-to-claude claudeFinishEmitted flag + 4 test-alignment files + golden snapshot regen) — the code fixes NET-REMOVE lines and add no `any`/unused, and lint reported 4199 both before and after them, so all +41 is inherited cycle drift (`any` warn-allowed in open-sse/ + tests/). Tighten via --require-tighten next cycle.",
"direction": "down",
"_rebaseline_2026_07_01_v3843_release": "4121->4158 (+37). v3.8.43 cycle drift surfaced by the release-green pre-flight; the Quality Ratchet does NOT run on PR->release fast-gates, so warnings accrued unmeasured across this cycle. 4158 = the value measured by the CI Quality Ratchet on the release tip fce85136c (release PR #5609). Trust-but-verify: the fix/release-v3843-ci-reds branch touches only test files (rtk-mcp-tools de-flake, compression-studio e2e anchor, oauth-error-linkify hardening test) + src/shared/utils/linkify.ts (eslint-clean, 0 warnings) + stryker.conf.json + this baseline -> 0 new warnings, so all +37 is inherited cycle drift (any warn-allowed in open-sse/ + tests/). Tighten via --require-tighten next cycle.",
@@ -115,10 +114,7 @@
"_rebaseline_2026_06_26_v3837_release": "343->345. v3.8.37 cycle drift surfaced by the release-green pre-flight (the Quality Ratchet does NOT run on PR->release fast-gates, so warnings/complexity accrued unmeasured across this cycle's 76 commits — provider adds DGrid/Pioneer/xAI, headroom proxy lifecycle #4649, ~50 SSE/translator fixes, Engine Combos #5062). Trust-but-verify: this release-finalize working tree touches ONLY CHANGELOG.md, docs/i18n/*/CHANGELOG.md mirrors, and these baselines — 0 production-code change, so all drift is inherited cycle drift (`any` warn-allowed in open-sse/ + tests/). Tighten via --require-tighten next cycle."
},
"cognitiveComplexity": {
- "value": 861,
- "_rebaseline_2026_07_03_v3844_review_prs_fix_batch": "860->861 (+1). Inherited v3.8.44 cycle drift surfaced by the release-green pre-flight during the /review-prs fix-batch round; check:cognitive-complexity measures 861 on the release tip 72ee80649. Negligible +1 from the round's / parallel-session merge burst (cognitive-complexity does NOT run on PR->release fast-gates). Structural shrink tracked in #3501. Tighten via --update next cycle.",
- "_rebaseline_2026_07_02_v3844_post_5939": "859->860 (+1). Same inherited post-3a3d618fe release drift as the complexity note of this date; this PR touches one CLI line (nullish default, no new function over the threshold) and one test file (not scanned). Tighten via --update next cycle.",
- "_rebaseline_2026_07_02_v3844_merge_burst": "856->859 (+3). Inherited v3.8.44 cycle drift surfaced by PR #5939: check:cognitive-complexity measures 859 on BOTH the pristine release tip (3a3d618fe) and this PR's merged HEAD — identical, so the PR is cognitive-net-zero (its DiscoveryPageClient was refactored into hooks/sub-components during its own CI cycle). Drift from the 2026-07-02 merge burst into release/v3.8.44. Tighten via --update next cycle.",
+ "value": 856,
"_rebaseline_2026_07_02_5798_release_green": "845->856 (+11). Inherited v3.8.43 cycle drift surfaced by the release-green unblock #5798 / PR #5896: check:cognitive-complexity measures 856 on BOTH the pristine release tip (0d3875a98) and this PR's HEAD — identical, so the PR is cognitive-net-zero (it touches only gate scripts, docs, baselines and test files). Drift from the 2026-07-01/02 merge burst. Tighten via --update next cycle.",
"direction": "down",
"_rebaseline_2026_07_01_v3843_release": "842->845 (+3). v3.8.43 cycle drift, surfaced after check:mutation-test-coverage was fixed (masked behind it in the Fast Quality Gates chain). 845 = measured by check:cognitive-complexity on BOTH fce85136c and 6d7060e21 (identical) — all +3 is inherited cycle drift; the 5 CI fixes add 0 (safeHttpHref cognitive ~2, under the 15 threshold). Tighten via --update next cycle.",
diff --git a/docs/README.md b/docs/README.md
index d43de85363..df0040172e 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -71,7 +71,6 @@ Lookup material — API surface, environment variables, CLI flags, provider cata
- [API_REFERENCE.md](reference/API_REFERENCE.md) — REST API endpoints and shapes.
- [PROVIDER_REFERENCE.md](reference/PROVIDER_REFERENCE.md) — auto-generated provider catalog (do not edit by hand).
-- [PROVIDER_PLUGIN_MANIFEST.md](reference/PROVIDER_PLUGIN_MANIFEST.md) — sidecar-safe provider plugin contract for Bifrost and CLIProxyAPI migration.
- [openapi.yaml](openapi.yaml) — OpenAPI spec for the public API.
- [ENVIRONMENT.md](reference/ENVIRONMENT.md) — environment variables reference.
- [FEATURE_FLAGS.md](reference/FEATURE_FLAGS.md) — feature flags and their defaults.
diff --git a/docs/compression/EXTENDING_COMPRESSION.md b/docs/compression/EXTENDING_COMPRESSION.md
index 7b33f5b37d..9aea461674 100644
--- a/docs/compression/EXTENDING_COMPRESSION.md
+++ b/docs/compression/EXTENDING_COMPRESSION.md
@@ -1,7 +1,7 @@
---
title: "Extending the Compression Pipeline"
-version: 3.8.44
-lastUpdated: 2026-07-02
+version: 3.8.40
+lastUpdated: 2026-06-28
---
# Extending the Compression Pipeline
@@ -512,62 +512,6 @@ To drive it from config, set `mode: "stacked"` and provide the step array under
---
-## Upstream Sync Policy
-
-OmniRoute's compression engines credit several upstream projects in the README
-("inspired by RTK, Caveman, LLMLingua-2, Troglodita"). A common contributor
-question is: **when upstream RTK adds a new tool filter or Caveman adds a rule
-pack, how does that reach OmniRoute?** This section is the authoritative answer.
-
-### Vendored copies vs. independent implementations
-
-| Engine | Relationship to upstream | Location |
-| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- |
-| **RTK** | **Independent reimplementation** (inspired-by, not a copy) | `open-sse/services/compression/engines/rtk/` |
-| **Caveman** | **Independent reimplementation** (inspired-by) | `open-sse/services/compression/engines/cavemanAdapter.ts` |
-| **Headroom** | Mostly internal; only the `gcf/` codec is **genuinely vendored** from `gcf-typescript` (MIT, SPDX-marked, generic profile only) | `open-sse/services/compression/engines/headroom/gcf/` |
-| **LLMLingua-2 / Troglodita** | Inspired-by (drive the `llmlingua` + `session-dedup` engines) | `open-sse/services/compression/engines/llmlingua/`, `session-dedup` |
-
-Key point: **RTK and Caveman are clean-room TypeScript implementations of the
-_ideas_ (filter rules, rule packs), not vendored source trees.** There is no
-upstream copy to `git pull` from — which is exactly why the README says
-"inspired by" rather than "bundled".
-
-### How upstream improvements are merged
-
-There is **no automated upstream-release tracking and no `compression-sync`
-label** — by design. Because the engines are reimplementations, an upstream RTK
-filter or Caveman rule pack is not merged as code; it is **re-expressed as a new
-rule/filter in OmniRoute's own format** (see
-[COMPRESSION_RULES_FORMAT.md](./COMPRESSION_RULES_FORMAT.md)) and lands ad-hoc via
-a normal PR. The extension points above (custom engine, language pack, RTK filter)
-are the sanctioned way to contribute one.
-
-Recent examples of exactly this flow:
-
-- RTK filters for Gradle & `dotnet` build output (v3.8.42)
-- RTK filters for kubectl / docker-build / composer / gh (#2824)
-- Caveman Indonesian language pack (#3975), plus German / French / Japanese / Chinese packs
-
-### Headroom (input-compression proxy)
-
-Headroom is **fully internal** — a pinned vendored `gcf` codec snapshot plus
-OmniRoute's own `smartcrusher` / `toon` / `tabular` layers. There is no live
-upstream to track beyond the vendored copy; updates to `gcf` are refreshed
-manually when the codec changes and re-validated against the compression budget
-gate (`check:compression-budget`).
-
-### Proposing an upstream-inspired improvement
-
-1. **Don't vendor** — re-express the upstream rule/filter in OmniRoute's format.
-2. Add it via the matching extension point below (language pack, RTK filter, or
- custom engine).
-3. Reference the upstream project in the PR description (attribution), not by
- copying its license-bearing source.
-4. Include tests and confirm the `check:compression-budget` gate still passes.
-
----
-
## Best Practices
### Engine Development
diff --git a/docs/frameworks/EMBEDDED-SERVICES.md b/docs/frameworks/EMBEDDED-SERVICES.md
index 66b2f59acd..dd578c992d 100644
--- a/docs/frameworks/EMBEDDED-SERVICES.md
+++ b/docs/frameworks/EMBEDDED-SERVICES.md
@@ -1,13 +1,13 @@
---
title: "Embedded Services"
-description: "Reference for 9Router, CLIProxyAPI, Mux, and Bifrost"
+description: "Reference for 9Router and CLIProxyAPI"
---
# Embedded Services
-> **Version:** v3.8.44
-> **Last updated:** 2026-07-03
-> **Audience:** Engineers adding, maintaining, or debugging embedded services (9Router, CLIProxyAPI, Mux, Bifrost).
+> **Version:** v3.8.4
+> **Last updated:** 2026-06-28
+> **Audience:** Engineers adding, maintaining, or debugging embedded services (9Router, CLIProxyAPI).
Embedded services are locally-installed process sidecar tools that OmniRoute installs, supervises, and
exposes as first-class routing targets. Unlike external providers (which are reached over the internet
@@ -32,20 +32,18 @@ via API keys), embedded services run on the same machine as OmniRoute and commun
### Why embedded services?
-Four services are embedded as of v3.8.44:
+Two services are embedded as of v3.8.4:
-| Service | npm package | Default port | Purpose |
-| --------------- | ----------------------------------------------- | :----------: | ------------------------------------------------------------------------------------------------------------------ |
-| **9Router** | `9router` | 20130 | AI router that OmniRoute can use as a sub-provider. Models exposed as `9router/{sub}/{model}` |
-| **CLIProxyAPI** | `@anthropic/cli-proxy` (via `cliproxy` binary) | auto | Local proxy adapter for Anthropic CLI auth flows. Provides fallback routing when OAuth tokens expire |
-| **Mux** | `mux` (headless `mux server`) | 8322 | Local agent-orchestration daemon (coder/mux). Lifecycle-managed only — not a routing target (no LLM proxying). |
-| **Bifrost** | `@maximhq/bifrost` | 8080 | Go AI-gateway relay backend. When running, auto-selected by the relay route (`/v1/relay/`) |
+| Service | npm package | Default port | Purpose |
+| --------------- | ---------------------------------------------- | :----------: | ---------------------------------------------------------------------------------------------------- |
+| **9Router** | `9router` | 20130 | AI router that OmniRoute can use as a sub-provider. Models exposed as `9router/{sub}/{model}` |
+| **CLIProxyAPI** | `@anthropic/cli-proxy` (via `cliproxy` binary) | auto | Local proxy adapter for Anthropic CLI auth flows. Provides fallback routing when OAuth tokens expire |
-All four follow the same supervisory model:
+Both follow the same supervisory model:
- OmniRoute installs them under `DATA_DIR/services/{name}/` (isolated from OmniRoute's own `package.json`)
- OmniRoute spawns and monitors them as child processes
-- OmniRoute injects an ephemeral API key into the child's environment and rotates it without downtime (where applicable)
+- OmniRoute injects an ephemeral API key into the child's environment and rotates it without downtime
- All management routes (`/api/services/*`) are **LOCAL_ONLY** — accessible only from loopback (hard rule #17)
### Key decisions (from design plan)
@@ -56,7 +54,7 @@ All four follow the same supervisory model:
| Installation mechanism | `npm install {package}` via `execFile` (no shell interpolation) |
| Consumption mode | Provider registered as `9router/{sub}/{model}` in routing engine |
| API key management | OmniRoute generates, encrypts at-rest (AES-256-GCM), and injects via env |
-| Dashboard location | `/dashboard/providers/services` (three tabs) |
+| Dashboard location | `/dashboard/providers/services` (two tabs) |
| Auto-start | Toggle per service, default OFF |
---
@@ -66,13 +64,12 @@ All four follow the same supervisory model:
```
┌────────────────────────────────────────────────────────────────────┐
│ Layer 1 — UI │
-│ /dashboard/providers/services (tabs: CLIProxyAPI | 9Router | Mux)│
+│ /dashboard/providers/services (tabs: CLIProxyAPI | 9Router) │
│ Logs live (SSE), Start/Stop/Restart/Update, Settings, Install │
│ │
│ src/app/(dashboard)/dashboard/providers/services/ │
│ ├── page.tsx Shell + tab routing by ?tab= │
-│ ├── tabs/ CliproxyServiceTab, NinerouterServiceTab,│
-│ │ MuxServiceTab │
+│ ├── tabs/ CliproxyServiceTab, NinerouterServiceTab│
│ └── components/ ServiceStatusCard, ServiceLifecycleButtons,│
│ ServiceLogsPanel, ApiKeyCard, ... │
└──────────────────────┬─────────────────────────────────────────────┘
@@ -84,8 +81,6 @@ All four follow the same supervisory model:
│ rotate-key|status|auto-start|logs} │
│ /api/services/cliproxy/{install|start|stop|restart|update| │
│ status|auto-start|logs} │
-│ /api/services/mux/{install|start|stop|restart|update| │
-│ status|auto-start|logs} │
│ /dashboard/providers/services/9router/embed/[...path] │
│ (reverse HTTP + WebSocket proxy → 9Router upstream) │
│ │
@@ -111,8 +106,7 @@ All four follow the same supervisory model:
│ modelSync.ts Periodic GET /v1/models → service_models table │
│ ringBuffer.ts Circular log buffer (5 MB per service) │
│ healthCheck.ts Polling HTTP health probe │
-│ installers/ ninerouter.ts, cliproxy.ts, mux.ts │
-│ (installer adapters) │
+│ installers/ ninerouter.ts, cliproxy.ts (installer adapters)│
└──────────────────────┬─────────────────────────────────────────────┘
│ OpenAI-compatible HTTP (loopback)
┌──────────────────────▼─────────────────────────────────────────────┐
@@ -129,10 +123,6 @@ All four follow the same supervisory model:
│ open-sse/config/providerRegistry.ts │
│ Models stored as "9router/{sub}/{model}" (prefixed). │
│ Synced every 5 min by modelSync.ts. │
-│ │
-│ Mux is lifecycle-managed ONLY (Layers 1-3) — it is an agent- │
-│ orchestration daemon, not an LLM proxy, so it has no Layer 4 │
-│ executor/provider entry and is never a routing target. │
└────────────────────────────────────────────────────────────────────┘
```
@@ -149,7 +139,6 @@ All four follow the same supervisory model:
| `src/lib/services/healthCheck.ts` | HTTP health probe (configurable interval) |
| `src/lib/services/installers/ninerouter.ts` | npm install/update/uninstall for 9Router |
| `src/lib/services/installers/cliproxy.ts` | npm install/update/uninstall for CLIProxyAPI |
-| `src/lib/services/installers/mux.ts` | npm install/update/uninstall for Mux |
| `src/app/api/services/9router/_lib.ts` | `getOrInitSupervisor()` helper |
| `src/app/api/services/[name]/logs/route.ts` | Shared SSE logs endpoint |
| `open-sse/executors/ninerouter.ts` | Provider executor (Layer 4) |
@@ -445,56 +434,12 @@ config) and `status` includes fewer fields.
| `GET` | `/api/services/cliproxy/status` | Live + DB status (no `apiKeyMasked`) |
| `POST` | `/api/services/cliproxy/auto-start` | Toggle auto-start |
-The shared `GET /api/services/{name}/logs` endpoint (see §4.1) works for all
-four services using the `[name]` dynamic segment.
+The shared `GET /api/services/{name}/logs` endpoint (see §4.1) works for both
+services using the `[name]` dynamic segment.
---
-### 4.3 Mux endpoints (7 routes)
-
-Mux has the same endpoint shape as CLIProxyAPI — no `rotate-key` route in the API
-surface (the bearer token is generated the same way as 9Router's via
-`getOrCreateApiKey("mux")` and injected via the `MUX_SERVER_AUTH_TOKEN` env var, but
-there is no dedicated rotation endpoint yet). Mux is lifecycle-managed only: unlike
-9Router, it has no Layer 4 executor and is never registered as a routing provider.
-
-| Method | Path | Description |
-| ------ | -------------------------------- | ------------------------------------- |
-| `POST` | `/api/services/mux/install` | Install Mux from npm (`npm i mux`) |
-| `POST` | `/api/services/mux/start` | Start Mux (`mux server`) |
-| `POST` | `/api/services/mux/stop` | Stop Mux |
-| `POST` | `/api/services/mux/restart` | Restart Mux |
-| `POST` | `/api/services/mux/update` | Update to newer npm version |
-| `GET` | `/api/services/mux/status` | Live + DB status |
-| `POST` | `/api/services/mux/auto-start` | Toggle auto-start |
-
----
-
-### 4.4 Bifrost endpoints (7 routes)
-
-Bifrost is a Go AI-gateway relay backend (`@maximhq/bifrost`). It uses the same
-endpoint shape as CLIProxyAPI (no `rotate-key` — Bifrost manages its own provider
-keys in `config.json` under its `-app-dir`).
-
-| Method | Path | Description |
-| ------ | ---------------------------------- | ------------------------------------------------------ |
-| `POST` | `/api/services/bifrost/install` | Install Bifrost from npm (`@maximhq/bifrost`) |
-| `POST` | `/api/services/bifrost/start` | Start Bifrost on port 8080 (default) |
-| `POST` | `/api/services/bifrost/stop` | Stop Bifrost |
-| `POST` | `/api/services/bifrost/restart` | Restart Bifrost |
-| `POST` | `/api/services/bifrost/update` | Update to newer version |
-| `GET` | `/api/services/bifrost/status` | Live + DB status |
-| `POST` | `/api/services/bifrost/auto-start` | Toggle auto-start |
-| `GET` | `/api/services/bifrost/logs` | SSE log tail (via shared `[name]/logs` dynamic route) |
-
-**Routing wiring:** When `BIFROST_BASE_URL` is unset and the supervised Bifrost
-instance is running, `getBifrostRoutingConfig()` (in `routingBackend.ts`) automatically
-uses `http://127.0.0.1:{port}` as the relay base URL. Explicit `BIFROST_BASE_URL` env
-always takes precedence.
-
----
-
-### 4.4 Reverse proxy (9Router dashboard embed)
+### 4.3 Reverse proxy (9Router dashboard embed)
The dashboard embeds the 9Router web UI inside an iframe via an internal reverse
proxy at:
@@ -541,20 +486,14 @@ matrix.
### API key injection
-9Router and Mux require an API key/bearer token for their own HTTP endpoints.
-OmniRoute:
+9Router requires an API key for its own HTTP endpoints. OmniRoute:
1. Generates a key via `crypto.randomBytes(32).toString("base64url")` with a
- service-specific prefix (`nr_` for 9Router, `mx_` for Mux).
+ service-specific prefix (`nr_` for 9Router).
2. Encrypts it at-rest using AES-256-GCM (same cipher used for provider credentials).
-3. Decrypts and injects it as an environment variable at spawn time —
- `NINEROUTER_API_KEY` for 9Router, `MUX_SERVER_AUTH_TOKEN` for Mux (never a CLI
- flag, so the token never appears in `ps`/process listings).
+3. Decrypts and injects it as `NINEROUTER_API_KEY` environment variable at spawn time.
4. Never returns the plaintext key in any HTTP response.
-CLIProxyAPI does not require an injected key (it authenticates via the host's
-existing CLI config).
-
### SSRF defense
The reverse HTTP proxy (`/dashboard/.../embed/[...path]`) is hardcoded to forward
diff --git a/docs/i18n/ar/CHANGELOG.md b/docs/i18n/ar/CHANGELOG.md
index b4c82b1fd6..595fc5acd6 100644
--- a/docs/i18n/ar/CHANGELOG.md
+++ b/docs/i18n/ar/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/az/CHANGELOG.md b/docs/i18n/az/CHANGELOG.md
index 8de9ab05bb..31584a5e8a 100644
--- a/docs/i18n/az/CHANGELOG.md
+++ b/docs/i18n/az/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/bg/CHANGELOG.md b/docs/i18n/bg/CHANGELOG.md
index 8de9ab05bb..31584a5e8a 100644
--- a/docs/i18n/bg/CHANGELOG.md
+++ b/docs/i18n/bg/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/bn/CHANGELOG.md b/docs/i18n/bn/CHANGELOG.md
index 617accb78e..ecb7c8e47d 100644
--- a/docs/i18n/bn/CHANGELOG.md
+++ b/docs/i18n/bn/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/cs/CHANGELOG.md b/docs/i18n/cs/CHANGELOG.md
index e62fbf84b6..b33dcd9dcb 100644
--- a/docs/i18n/cs/CHANGELOG.md
+++ b/docs/i18n/cs/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/da/CHANGELOG.md b/docs/i18n/da/CHANGELOG.md
index 80fbdba782..0525ff7242 100644
--- a/docs/i18n/da/CHANGELOG.md
+++ b/docs/i18n/da/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/de/CHANGELOG.md b/docs/i18n/de/CHANGELOG.md
index 9e14f4b4c3..b5b2b63797 100644
--- a/docs/i18n/de/CHANGELOG.md
+++ b/docs/i18n/de/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/es/CHANGELOG.md b/docs/i18n/es/CHANGELOG.md
index 69e027a78a..7bd26eab9b 100644
--- a/docs/i18n/es/CHANGELOG.md
+++ b/docs/i18n/es/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/fa/CHANGELOG.md b/docs/i18n/fa/CHANGELOG.md
index ffbe0a483e..de9a2f73cd 100644
--- a/docs/i18n/fa/CHANGELOG.md
+++ b/docs/i18n/fa/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/fi/CHANGELOG.md b/docs/i18n/fi/CHANGELOG.md
index f871b94115..4d44cfd43a 100644
--- a/docs/i18n/fi/CHANGELOG.md
+++ b/docs/i18n/fi/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/fr/CHANGELOG.md b/docs/i18n/fr/CHANGELOG.md
index 9e2fcaafd4..6d251e12b6 100644
--- a/docs/i18n/fr/CHANGELOG.md
+++ b/docs/i18n/fr/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/gu/CHANGELOG.md b/docs/i18n/gu/CHANGELOG.md
index 4c7a87e6c2..b456a14e03 100644
--- a/docs/i18n/gu/CHANGELOG.md
+++ b/docs/i18n/gu/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/he/CHANGELOG.md b/docs/i18n/he/CHANGELOG.md
index 2e4bd19326..89d09bc81d 100644
--- a/docs/i18n/he/CHANGELOG.md
+++ b/docs/i18n/he/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/hi/CHANGELOG.md b/docs/i18n/hi/CHANGELOG.md
index df76512c74..022cc03f83 100644
--- a/docs/i18n/hi/CHANGELOG.md
+++ b/docs/i18n/hi/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/hu/CHANGELOG.md b/docs/i18n/hu/CHANGELOG.md
index a18e470447..7e1094da11 100644
--- a/docs/i18n/hu/CHANGELOG.md
+++ b/docs/i18n/hu/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/id/CHANGELOG.md b/docs/i18n/id/CHANGELOG.md
index 8d2aed4eab..2813e7ac16 100644
--- a/docs/i18n/id/CHANGELOG.md
+++ b/docs/i18n/id/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/in/CHANGELOG.md b/docs/i18n/in/CHANGELOG.md
index fcf2ed56fa..bcfeaade5e 100644
--- a/docs/i18n/in/CHANGELOG.md
+++ b/docs/i18n/in/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/it/CHANGELOG.md b/docs/i18n/it/CHANGELOG.md
index c94f8141bd..800b252e70 100644
--- a/docs/i18n/it/CHANGELOG.md
+++ b/docs/i18n/it/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/ja/CHANGELOG.md b/docs/i18n/ja/CHANGELOG.md
index b85edc2f77..be80401d52 100644
--- a/docs/i18n/ja/CHANGELOG.md
+++ b/docs/i18n/ja/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/ko/CHANGELOG.md b/docs/i18n/ko/CHANGELOG.md
index 15379d4c50..35281cc458 100644
--- a/docs/i18n/ko/CHANGELOG.md
+++ b/docs/i18n/ko/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/mr/CHANGELOG.md b/docs/i18n/mr/CHANGELOG.md
index 04f2941515..edde061766 100644
--- a/docs/i18n/mr/CHANGELOG.md
+++ b/docs/i18n/mr/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/ms/CHANGELOG.md b/docs/i18n/ms/CHANGELOG.md
index 0716d956ae..c20b9f5284 100644
--- a/docs/i18n/ms/CHANGELOG.md
+++ b/docs/i18n/ms/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/nl/CHANGELOG.md b/docs/i18n/nl/CHANGELOG.md
index 7310fa3d05..3a49f71458 100644
--- a/docs/i18n/nl/CHANGELOG.md
+++ b/docs/i18n/nl/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/no/CHANGELOG.md b/docs/i18n/no/CHANGELOG.md
index 5120498b4a..aa3ecfc80f 100644
--- a/docs/i18n/no/CHANGELOG.md
+++ b/docs/i18n/no/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/phi/CHANGELOG.md b/docs/i18n/phi/CHANGELOG.md
index b70c00c980..3fed9c0458 100644
--- a/docs/i18n/phi/CHANGELOG.md
+++ b/docs/i18n/phi/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/pl/CHANGELOG.md b/docs/i18n/pl/CHANGELOG.md
index 3ea2df224e..b2b275f538 100644
--- a/docs/i18n/pl/CHANGELOG.md
+++ b/docs/i18n/pl/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/pt-BR/CHANGELOG.md b/docs/i18n/pt-BR/CHANGELOG.md
index 544c063285..2603b1352c 100644
--- a/docs/i18n/pt-BR/CHANGELOG.md
+++ b/docs/i18n/pt-BR/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/pt/CHANGELOG.md b/docs/i18n/pt/CHANGELOG.md
index 50d165299b..794882a1bc 100644
--- a/docs/i18n/pt/CHANGELOG.md
+++ b/docs/i18n/pt/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/ro/CHANGELOG.md b/docs/i18n/ro/CHANGELOG.md
index 85c2e5f0a9..442c9577ad 100644
--- a/docs/i18n/ro/CHANGELOG.md
+++ b/docs/i18n/ro/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/ru/CHANGELOG.md b/docs/i18n/ru/CHANGELOG.md
index 559cc49cd9..f2bcc29907 100644
--- a/docs/i18n/ru/CHANGELOG.md
+++ b/docs/i18n/ru/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/sk/CHANGELOG.md b/docs/i18n/sk/CHANGELOG.md
index f64d625fa0..b691acf9bb 100644
--- a/docs/i18n/sk/CHANGELOG.md
+++ b/docs/i18n/sk/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/sv/CHANGELOG.md b/docs/i18n/sv/CHANGELOG.md
index cb14cfd613..8cd03360d7 100644
--- a/docs/i18n/sv/CHANGELOG.md
+++ b/docs/i18n/sv/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/sw/CHANGELOG.md b/docs/i18n/sw/CHANGELOG.md
index 4db8d7f643..f96f4493fe 100644
--- a/docs/i18n/sw/CHANGELOG.md
+++ b/docs/i18n/sw/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/ta/CHANGELOG.md b/docs/i18n/ta/CHANGELOG.md
index 12fe054a6a..87e0bd9ccb 100644
--- a/docs/i18n/ta/CHANGELOG.md
+++ b/docs/i18n/ta/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/te/CHANGELOG.md b/docs/i18n/te/CHANGELOG.md
index 5d4d5d2b0f..6ae74a28db 100644
--- a/docs/i18n/te/CHANGELOG.md
+++ b/docs/i18n/te/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/th/CHANGELOG.md b/docs/i18n/th/CHANGELOG.md
index e914ae4e52..893556f19e 100644
--- a/docs/i18n/th/CHANGELOG.md
+++ b/docs/i18n/th/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/tr/CHANGELOG.md b/docs/i18n/tr/CHANGELOG.md
index de9f3a3504..e39fb48283 100644
--- a/docs/i18n/tr/CHANGELOG.md
+++ b/docs/i18n/tr/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/uk-UA/CHANGELOG.md b/docs/i18n/uk-UA/CHANGELOG.md
index 28140682bc..9a17657000 100644
--- a/docs/i18n/uk-UA/CHANGELOG.md
+++ b/docs/i18n/uk-UA/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/ur/CHANGELOG.md b/docs/i18n/ur/CHANGELOG.md
index 889b71d4ff..e405d76c37 100644
--- a/docs/i18n/ur/CHANGELOG.md
+++ b/docs/i18n/ur/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/vi/CHANGELOG.md b/docs/i18n/vi/CHANGELOG.md
index 63fcd348f0..ae3daff0c5 100644
--- a/docs/i18n/vi/CHANGELOG.md
+++ b/docs/i18n/vi/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/zh-CN/CHANGELOG.md b/docs/i18n/zh-CN/CHANGELOG.md
index c12a4802f3..30f8a24b68 100644
--- a/docs/i18n/zh-CN/CHANGELOG.md
+++ b/docs/i18n/zh-CN/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/i18n/zh-TW/CHANGELOG.md b/docs/i18n/zh-TW/CHANGELOG.md
index b06956abe3..d8dcc93c70 100644
--- a/docs/i18n/zh-TW/CHANGELOG.md
+++ b/docs/i18n/zh-TW/CHANGELOG.md
@@ -6,24 +6,6 @@
## [3.8.31] — 2026-06-20
-## [3.8.44] — TBD
-
-### ✨ New Features
-
-_TBD_
-
-### 🔧 Bug Fixes
-
-_TBD_
-
-### 📝 Maintenance
-
-- **chore(release):** release-pipeline hardening — `check:test-masking` (vs `origin/main`) is now a HARD gate in the release-green pre-flight (`validate-release-green.mjs`), so a non-allowlisted net-assert reduction surfaces locally instead of in a ~40-min CI layer on the release PR; plus two reconciliation helpers — `npm run release:contributors` (reproducible `### 🙌 Contributors` table via a parenthetical-group parser) and `npm run release:uncovered` (lists commits with no CHANGELOG bullet). ([#5926](https://github.com/diegosouzapw/OmniRoute/pull/5926) — thanks @diegosouzapw)
-
-- **chore(ci):** the `check:pr-evidence` FAIL report now tells you that editing the PR body does not re-run the gate (`ci.yml` ignores the `edited` event) — push a commit to re-validate. ([#5944](https://github.com/diegosouzapw/OmniRoute/pull/5944) — thanks @diegosouzapw)
-
----
-
## [3.8.43] — 2026-07-02
### ✨ New Features
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index aab8d0169d..764ee2cb37 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -1,7 +1,7 @@
openapi: 3.1.0
info:
title: OmniRoute API
- version: 3.8.44
+ version: 3.8.43
description: |
OmniRoute is a local-first AI API proxy router. It provides an OpenAI-compatible
endpoint that routes requests to multiple AI providers with load balancing,
@@ -3444,276 +3444,6 @@ paths:
"400":
description: Invalid request body
- /api/services/mux/install:
- post:
- tags: [Embedded Services]
- summary: Install Mux from npm
- description: >-
- Installs the `mux` npm package (coder/mux — local agent-orchestration
- daemon) under DATA_DIR/services/mux/. **LOCAL_ONLY** — loopback only.
- requestBody:
- required: false
- content:
- application/json:
- schema:
- type: object
- properties:
- version:
- type: string
- default: latest
- responses:
- "200":
- description: Install succeeded
- content:
- application/json:
- schema:
- type: object
- properties:
- ok:
- type: boolean
- installedVersion:
- type: string
- "400":
- description: Invalid request body
- "500":
- description: npm install failed
-
- /api/services/mux/start:
- post:
- tags: [Embedded Services]
- summary: Start Mux
- description: >-
- Spawns `mux server --host 127.0.0.1 --port <port>`. Idempotent if
- already running. **LOCAL_ONLY** — loopback only.
- responses:
- "200":
- description: Service started
- content:
- application/json:
- schema:
- $ref: "#/components/schemas/ServiceStatus"
- "409":
- description: Mux is not installed
- "503":
- description: Start failed
-
- /api/services/mux/stop:
- post:
- tags: [Embedded Services]
- summary: Stop Mux
- description: >-
- Gracefully stops Mux. Idempotent.
- **LOCAL_ONLY** — loopback only.
- responses:
- "200":
- description: Service stopped
- content:
- application/json:
- schema:
- $ref: "#/components/schemas/ServiceStatus"
-
- /api/services/mux/restart:
- post:
- tags: [Embedded Services]
- summary: Restart Mux
- description: >-
- stop() then start() under the operation lock.
- **LOCAL_ONLY** — loopback only.
- responses:
- "200":
- description: Service restarted
- content:
- application/json:
- schema:
- $ref: "#/components/schemas/ServiceStatus"
-
- /api/services/mux/update:
- post:
- tags: [Embedded Services]
- summary: Update Mux to a newer npm version
- description: >-
- Stops, installs newer version, restarts.
- **LOCAL_ONLY** — loopback only.
- requestBody:
- required: false
- content:
- application/json:
- schema:
- type: object
- properties:
- version:
- type: string
- default: latest
- responses:
- "200":
- description: Update succeeded
- content:
- application/json:
- schema:
- type: object
- properties:
- ok:
- type: boolean
- installedVersion:
- type: string
- "500":
- description: Update failed
-
- /api/services/mux/status:
- get:
- tags: [Embedded Services]
- summary: Get Mux status
- description: >-
- Returns live supervisor state and DB metadata.
- **LOCAL_ONLY** — loopback only.
- responses:
- "200":
- description: Status response
- content:
- application/json:
- schema:
- $ref: "#/components/schemas/ServiceStatus"
-
- /api/services/mux/auto-start:
- post:
- tags: [Embedded Services]
- summary: Toggle Mux auto-start
- description: >-
- When enabled, Mux starts automatically on the next OmniRoute boot.
- **LOCAL_ONLY** — loopback only.
- requestBody:
- required: true
- content:
- application/json:
- schema:
- type: object
- required: [enabled]
- properties:
- enabled:
- type: boolean
- responses:
- "200":
- description: Auto-start flag updated
- content:
- application/json:
- schema:
- type: object
- properties:
- autoStart:
- type: boolean
- "400":
- description: Invalid request body
-
- /api/services/bifrost/install:
- post:
- tags: [Embedded Services]
- summary: Install Bifrost
- description: >-
- Installs the `@maximhq/bifrost` npm package under DATA_DIR/services/bifrost/.
- The package downloads the Go binary on first run. Accepts an optional `version`
- field (semver or `latest`). **LOCAL_ONLY** — loopback only.
- requestBody:
- required: false
- content:
- application/json:
- schema:
- type: object
- properties:
- version:
- type: string
- default: latest
- responses:
- "200":
- description: Installation result
- content:
- application/json:
- schema:
- type: object
- properties:
- ok:
- type: boolean
- installedVersion:
- type: string
- installPath:
- type: string
- durationMs:
- type: number
-
- /api/services/bifrost/start:
- post:
- tags: [Embedded Services]
- summary: Start Bifrost
- description: Starts the supervised Bifrost process. **LOCAL_ONLY** — loopback only.
- responses:
- "200":
- description: Service status after start
- "409":
- description: Bifrost is not installed
-
- /api/services/bifrost/stop:
- post:
- tags: [Embedded Services]
- summary: Stop Bifrost
- description: Stops the supervised Bifrost process. **LOCAL_ONLY** — loopback only.
- responses:
- "200":
- description: Service status after stop
-
- /api/services/bifrost/restart:
- post:
- tags: [Embedded Services]
- summary: Restart Bifrost
- description: Restarts the supervised Bifrost process. **LOCAL_ONLY** — loopback only.
- responses:
- "200":
- description: Service status after restart
- "409":
- description: Bifrost is not installed
-
- /api/services/bifrost/update:
- post:
- tags: [Embedded Services]
- summary: Update Bifrost
- description: >-
- Updates Bifrost to the latest npm version. Stops the running process,
- installs the new version, and restarts if it was previously running.
- **LOCAL_ONLY** — loopback only.
- responses:
- "200":
- description: Update result
-
- /api/services/bifrost/status:
- get:
- tags: [Embedded Services]
- summary: Get Bifrost status
- description: Returns live and DB status for the supervised Bifrost service. **LOCAL_ONLY** — loopback only.
- responses:
- "200":
- description: Bifrost service status
-
- /api/services/bifrost/auto-start:
- post:
- tags: [Embedded Services]
- summary: Toggle Bifrost auto-start
- description: >-
- When enabled, Bifrost starts automatically on the next OmniRoute boot.
- **LOCAL_ONLY** — loopback only.
- requestBody:
- required: true
- content:
- application/json:
- schema:
- type: object
- required: [enabled]
- properties:
- enabled:
- type: boolean
- responses:
- "204":
- description: Auto-start flag updated
- "400":
- description: Invalid request body
-
/api/services/{name}/logs:
get:
tags: [Embedded Services]
@@ -5534,214 +5264,6 @@ paths:
$ref: "#/components/responses/InternalError"
"503":
description: Generator module not available
- /api/v1/ocr:
- post:
- tags:
- - Images
- summary: Document OCR
- description: >-
- Mistral OCR–compatible document OCR endpoint. Accepts a JSON body
- referencing a document/image and returns extracted text. Success
- responses carry the `X-OmniRoute-*` cost-telemetry headers.
- security:
- - BearerAuth: []
- requestBody:
- required: true
- content:
- application/json:
- schema:
- type: object
- properties:
- model:
- type: string
- document:
- type: object
- responses:
- "200":
- description: OCR result with extracted text.
- "400":
- $ref: "#/components/responses/BadRequest"
- "401":
- $ref: "#/components/responses/Unauthorized"
- "500":
- $ref: "#/components/responses/InternalError"
- /api/v1/audio/translations:
- post:
- tags:
- - Audio
- summary: Translate audio to English
- description: >-
- OpenAI Whisper–compatible audio translation (multipart/form-data).
- Unlike `/api/v1/audio/transcriptions`, output is always English
- regardless of the source language. Success responses carry the
- `X-OmniRoute-*` cost-telemetry headers.
- security:
- - BearerAuth: []
- requestBody:
- required: true
- content:
- multipart/form-data:
- schema:
- type: object
- required:
- - file
- properties:
- file:
- type: string
- format: binary
- model:
- type: string
- responses:
- "200":
- description: English translation of the audio.
- "400":
- $ref: "#/components/responses/BadRequest"
- "401":
- $ref: "#/components/responses/Unauthorized"
- "500":
- $ref: "#/components/responses/InternalError"
- /api/v1/providers/suggested-models:
- get:
- tags:
- - Providers
- summary: Suggested media models
- description: >-
- Read-only server-side proxy to the public HuggingFace Hub models search
- API, used by the dashboard to suggest models for a media provider kind
- without exposing an HF token client-side. Never accepts or returns
- credentials.
- parameters:
- - name: type
- in: query
- schema:
- type: string
- description: Media kind to search for (e.g. `image`, `audio`, `video`).
- responses:
- "200":
- description: List of suggested HuggingFace Hub models.
- "500":
- $ref: "#/components/responses/InternalError"
- /api/v1/provider-plugin-manifest:
- get:
- tags:
- - Providers
- summary: Provider plugin manifest
- description: Returns the manifest describing installed provider plugins.
- responses:
- "200":
- description: Provider plugin manifest.
- "500":
- $ref: "#/components/responses/InternalError"
- /api/keys/{id}/devices:
- get:
- tags:
- - API Keys
- summary: List devices for an API key
- description: >-
- Lists the distinct devices (masked IP + User-Agent fingerprints)
- tracked for an API key by the in-memory device tracker. IPs are masked
- before storage; the route never sees the raw client IP.
- x-internal: true
- parameters:
- - name: id
- in: path
- required: true
- schema:
- type: string
- responses:
- "200":
- description: Distinct devices seen for the API key.
- "401":
- $ref: "#/components/responses/Unauthorized"
- "404":
- $ref: "#/components/responses/NotFound"
- /api/settings/purge-usage-history:
- post:
- tags:
- - Settings
- summary: Purge usage history
- description: Dashboard-only. Purges stored usage-history records.
- x-internal: true
- responses:
- "200":
- description: Usage history purged.
- "401":
- $ref: "#/components/responses/Unauthorized"
- /api/oauth/codex/import-token:
- post:
- tags:
- - OAuth
- summary: Import a Codex connection from a bare access token
- description: >-
- Dashboard-only. Creates a Codex (ChatGPT/OpenAI) connection from a raw
- access token with no refresh token (authType `access_token`).
- x-internal: true
- responses:
- "200":
- description: Connection imported.
- "400":
- $ref: "#/components/responses/BadRequest"
- "401":
- $ref: "#/components/responses/Unauthorized"
- /api/cli-tools/crush-settings:
- get:
- tags:
- - CLI Tools
- summary: Read Crush CLI OmniRoute config
- description: Local-only. Reads the OmniRoute provider block in Crush's config.
- x-internal: true
- responses:
- "200":
- description: Current Crush config state.
- post:
- tags:
- - CLI Tools
- summary: Write Crush CLI OmniRoute config
- description: Local-only. Registers OmniRoute as an `openai-compat` provider in Crush's config.
- x-internal: true
- responses:
- "200":
- description: Crush config updated.
- delete:
- tags:
- - CLI Tools
- summary: Remove OmniRoute from Crush CLI config
- description: Local-only. Removes the OmniRoute provider block from Crush's config.
- x-internal: true
- responses:
- "200":
- description: Crush config entry removed.
- /api/cli-tools/codewhale-settings:
- get:
- tags:
- - CLI Tools
- summary: Read CodeWhale CLI OmniRoute config
- description: >-
- Local-only. Reads the OmniRoute config block from
- `~/.codewhale/config.toml` (with `~/.deepseek/config.toml` legacy
- fallback).
- x-internal: true
- responses:
- "200":
- description: Current CodeWhale config state.
- post:
- tags:
- - CLI Tools
- summary: Write CodeWhale CLI OmniRoute config
- description: Local-only. Writes the OmniRoute config block in CodeWhale TOML format.
- x-internal: true
- responses:
- "200":
- description: CodeWhale config updated.
- delete:
- tags:
- - CLI Tools
- summary: Remove OmniRoute from CodeWhale CLI config
- description: Local-only. Removes the OmniRoute config block from CodeWhale's config.
- x-internal: true
- responses:
- "200":
- description: CodeWhale config entry removed.
components:
securitySchemes:
diff --git a/docs/reference/API_REFERENCE.md b/docs/reference/API_REFERENCE.md
index 02bba19fa9..9e8003697a 100644
--- a/docs/reference/API_REFERENCE.md
+++ b/docs/reference/API_REFERENCE.md
@@ -18,7 +18,6 @@ Complete reference for all OmniRoute API endpoints.
- [Embeddings](#embeddings)
- [Image Generation](#image-generation)
- [List Models](#list-models)
-- [Provider Plugin Manifest](#provider-plugin-manifest)
- [Compatibility Endpoints](#compatibility-endpoints)
- [Files API](#files-api)
- [Batches API](#batches-api)
@@ -179,22 +178,6 @@ Selecting this id (e.g. in a Claude Code config that always attaches a `thinking
---
-## Provider Plugin Manifest
-
-```bash
-GET /api/v1/provider-plugin-manifest
-```
-
-Returns the JSON-safe provider plugin manifest used by Bifrost, CLIProxyAPI, and
-future sidecar routers. The response is generated from the TypeScript provider
-registry and intentionally excludes OAuth client secrets, runtime environment
-resolution, executor functions, request headers, and account data.
-
-Use this endpoint when a sidecar runs out-of-process and cannot import
-`open-sse/config/providerPluginManifestRegistry.ts` directly.
-
----
-
## Compatibility Endpoints
| Method | Path | Format |
diff --git a/docs/reference/CLI-TOOLS.md b/docs/reference/CLI-TOOLS.md
index 42529429d2..15d1162af1 100644
--- a/docs/reference/CLI-TOOLS.md
+++ b/docs/reference/CLI-TOOLS.md
@@ -12,7 +12,7 @@ OmniRoute integrates with three categories of CLI tools spread across three dedi
| Page | Route | Concept | Count |
| -------------- | ----------------------- | ------------------------------------------------------------------------- | ------------ |
-| **CLI Code's** | `/dashboard/cli-code` | Coding tools you point at OmniRoute (Client → CLI → OmniRoute → Provider) | 20 |
+| **CLI Code's** | `/dashboard/cli-code` | Coding tools you point at OmniRoute (Client → CLI → OmniRoute → Provider) | 19 |
| **CLI Agents** | `/dashboard/cli-agents` | Autonomous agents you point at OmniRoute (same flow, broader scope) | 6 |
| **ACP Agents** | `/dashboard/acp-agents` | CLIs that OmniRoute spawns as backend via stdio/ACP (reverse flow) | see registry |
@@ -90,7 +90,7 @@ Entries with `baseUrlSupport: "none"` are **not shown** in the dashboard pages
---
-## 1. CLI Code's Catalog (20 tools)
+## 1. CLI Code's Catalog (19 tools)
Tools that support custom base URL and appear in `/dashboard/cli-code`:
@@ -107,7 +107,6 @@ Tools that support custom base URL and appear in `/dashboard/cli-code`:
| forge | ForgeCode | Antinomy HQ | full | custom | true |
| jcode | jcode | 1jehuang (OSS) | full | custom | false |
| deepseek-tui | DeepSeek TUI | Hunter Bown (OSS) | full | custom | false |
-| codewhale | CodeWhale | Hmbown (OSS) | full | custom | false |
| opencode | OpenCode | Anomaly (ex-SST) | full | guide | true |
| droid | Factory Droid | Factory AI | partial | guide | false |
| copilot | GitHub Copilot CLI | GitHub/MS | full | custom | false |
@@ -199,8 +198,7 @@ New tools with `configType: "custom"` have dedicated settings API routes:
| ------------------------------------------- | ------------------------------ |
| `POST /api/cli-tools/forge-settings` | ForgeCode (.forge.toml) |
| `POST /api/cli-tools/jcode-settings` | jcode (--base-url flag) |
-| `POST /api/cli-tools/deepseek-tui-settings` | DeepSeek TUI (OPENAI_BASE_URL, legacy) |
-| `POST /api/cli-tools/codewhale-settings` | CodeWhale (OPENAI_BASE_URL, primary + legacy `~/.deepseek` sync) |
+| `POST /api/cli-tools/deepseek-tui-settings` | DeepSeek TUI (OPENAI_BASE_URL) |
| `POST /api/cli-tools/smelt-settings` | Smelt |
| `POST /api/cli-tools/pi-settings` | Pi coding agent |
diff --git a/docs/reference/ENVIRONMENT.md b/docs/reference/ENVIRONMENT.md
index e45e4f1897..b307c1b1fb 100644
--- a/docs/reference/ENVIRONMENT.md
+++ b/docs/reference/ENVIRONMENT.md
@@ -117,7 +117,6 @@ OmniRoute uses **SQLite** (via `better-sqlite3`) for all persistence. These vari
| Variable | Default | Source File | Description |
| ------------------------------------------- | ------------------------------- | ------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `PORT` | `20128` | `src/lib/runtime/ports.ts` | Primary port for both Dashboard UI and API endpoints (single-port mode). |
-| `OMNIROUTE_BASE_PATH` | _(empty = root)_ | `next.config.mjs` | URL subpath for serving OmniRoute behind a reverse proxy under a subpath (sets Next.js `basePath`; auth redirects are basePath-aware). E.g. `/omniroute`. |
| `API_PORT` | _(unset)_ | `src/lib/runtime/ports.ts` | When set, serves the `/v1/*` proxy API on this separate port. |
| `API_HOST` | `0.0.0.0` | `src/lib/runtime/ports.ts` | Bind address for the API port. |
| `DASHBOARD_PORT` | _(unset)_ | `src/lib/runtime/ports.ts` | When set, serves the Dashboard UI on this separate port. |
@@ -265,8 +264,6 @@ OmniRoute provides a two-layer defense: request-side injection scanning and resp
| `NEXT_PUBLIC_CLOUD_URL` | _(empty)_ | Client-side | Client-side mirror of `CLOUD_URL`. |
| `NEXT_PUBLIC_APP_URL` | _(unset)_ | `src/shared/services/cloudSyncScheduler.ts` | Legacy fallback for `NEXT_PUBLIC_BASE_URL`. |
| `OMNIROUTE_PUBLIC_BASE_URL` | _(unset)_ | Public-origin resolver, image URLs | Highest-priority browser-facing OmniRoute origin used for public URL generation and non-dashboard browser-origin validation (for example `/v1/chatgpt-web/image/<id>`). Set this when OpenWebUI or another relay reaches OmniRoute by an internal URL but the user's browser must fetch images from a LAN, tunnel, or public origin. Do **not** include `/v1`. |
-| `OMNIROUTE_PROVIDER_MANIFEST_URL` | _(unset)_ | `open-sse/config/providerPluginManifestUrl.ts` | Absolute provider plugin manifest URL advertised to sidecar clients. When unset, OmniRoute derives `/api/v1/provider-plugin-manifest` from request origin or HOST/PORT. |
-| `OMNIROUTE_PUBLIC_PROTOCOL` | `http` | `open-sse/config/providerPluginManifestUrl.ts` | Protocol used when deriving the provider plugin manifest URL from HOST/PORT without a request origin. Set to `https` behind a TLS-terminating public proxy when no explicit `OMNIROUTE_PROVIDER_MANIFEST_URL` is set. |
| `OMNIROUTE_TRUST_PROXY` | _(unset)_ | `src/server/origin/publicOrigin.ts` | Optional trust mode for forwarded public-origin headers. Unset = do not trust `Forwarded` / `X-Forwarded-*` for security decisions. `true` / `loopback` trusts forwarded host/proto only from a token-stamped loopback proxy. `private` / `lan` also trusts private-LAN proxy peers. Prefer explicit `NEXT_PUBLIC_BASE_URL` in production. |
| `OMNIROUTE_CGPT_WEB_IMAGE_TIMEOUT_MS` | `180000` (3 min) | `open-sse/executors/chatgpt-web.ts` | Max wait time for an async chatgpt-web image to land via the celsius WebSocket. Increase during upstream queue-deep windows. |
| `OMNIROUTE_CGPT_WEB_IMAGE_CACHE_MAX_MB` | `256` | `open-sse/services/chatgptImageCache.ts` | Total in-memory byte budget (MB) for the chatgpt-web image cache serving `/v1/chatgpt-web/image/<id>`. Lower on memory-constrained hosts; raise if image generation is heavy and clients race the 30-minute TTL. |
@@ -356,8 +353,6 @@ Controls how OmniRoute discovers and launches CLI sidecars (Claude Code, Codex,
| `CLI_QODER_BIN` | `qoder` | `src/shared/services/cliRuntime.ts` | Custom path to Qoder CLI binary. |
| `CLI_QWEN_BIN` | `qwen` | `src/shared/services/cliRuntime.ts` | Custom path to the Qwen Code CLI binary. |
| `CLI_DEVIN_BIN` | `devin` | `open-sse/executors/devin-cli.ts` | Custom path to the Devin CLI binary (v3.8.0). Used by the Windsurf/Devin executor. |
-| `AUGGIE_BIN` | `auggie` | `open-sse/executors/auggie.ts` | Absolute-path override for the Augment (Auggie) CLI binary used by the local `auggie` provider. Falls back to `CLI_AUGGIE_BIN`, then a PATH lookup. |
-| `CLI_AUGGIE_BIN` | `auggie` | `open-sse/executors/auggie.ts` | Alias override for the Augment (Auggie) CLI binary path (checked after `AUGGIE_BIN`). |
| `HERMES_HOME` | `~/.hermes` | `src/lib/cli-helper/config-generator/hermesHome.ts` | Hermes Agent home directory where OmniRoute reads/writes the Hermes CLI config. Matches the env var the Hermes PowerShell installer sets on Windows (`%LOCALAPPDATA%\hermes`). |
### CLI Profile Auto-Sync
@@ -480,7 +475,6 @@ Built-in credentials for **localhost development**. For remote deployments, regi
| `QODER_PERSONAL_ACCESS_TOKEN` | Qoder | Direct API key fallback (bypasses OAuth). |
| `QODER_CLI_WORKSPACE` | Qoder | Workspace ID for Qoder CLI. |
| `OMNIROUTE_QODER_WORKSPACE` | Qoder | Alias for `QODER_CLI_WORKSPACE`. |
-| `QODER_CLI_CONFIG_DIR` | Qoder | Override the Qoder CLI config dir (isolated PAT session, avoids clobbering a browser login). |
| `BLACKBOX_WEB_VALIDATED_TOKEN` | Blackbox Web | Frontend `tk` token to send as `validated` on `/api/chat`. Required when Blackbox enforces token matching; otherwise OmniRoute falls back to a random UUID. See issue #2252. |
| `VISION_BRIDGE_BASE_URL` | Vision Bridge guardrail | OpenAI-compatible base URL for non-Anthropic vision-bridge calls. Defaults to the legacy OpenAI URL env or api.openai.com. Point at OmniRoute's `/v1` self-loop or any OpenAI-compat endpoint (Gemini OpenAI-compat, OpenRouter). Issue #2232. |
| `VISION_BRIDGE_API_KEY` | Vision Bridge guardrail | API key for the URL above. Overrides per-provider OpenAI / Google env vars for non-Anthropic vision-bridge calls. Anthropic models keep their dedicated Anthropic key path. Issue #2232. |
@@ -624,8 +618,6 @@ REQUEST_TIMEOUT_MS (global override)
| `FETCH_KEEPALIVE_TIMEOUT_MS` | `4000` | Keep-alive socket idle timeout. |
| `TLS_CLIENT_TIMEOUT_MS` | = `FETCH_TIMEOUT_MS` | TLS fingerprint proxy (wreq-js) timeout. |
| `API_BRIDGE_PROXY_TIMEOUT_MS` | `30000` | Proxy hop timeout for `/v1` bridge requests. |
-| `FIRECRAWL_BASE_URL` | `https://api.firecrawl.dev` | Point the Firecrawl web-fetch executor at a self-hosted instance (API key optional off-cloud). |
-| `FIRECRAWL_TIMEOUT_MS` | `30000` | Per-request timeout for the Firecrawl web-fetch executor. |
| `API_BRIDGE_SERVER_REQUEST_TIMEOUT_MS` | `300000` | Overall server request timeout for the bridge. |
| `API_BRIDGE_SERVER_HEADERS_TIMEOUT_MS` | `60000` | Time to send response headers via the bridge. |
| `API_BRIDGE_SERVER_KEEPALIVE_TIMEOUT_MS` | `5000` | Bridge keep-alive idle timeout. |
@@ -814,7 +806,6 @@ Automatic model pricing data synchronization from external sources.
| `CLIPROXYAPI_HOST` | `127.0.0.1` | `open-sse/executors/cliproxyapi.ts` | CLIProxyAPI bridge host (legacy integration). |
| `CLIPROXYAPI_PORT` | `5544` | `open-sse/executors/cliproxyapi.ts` | CLIProxyAPI bridge port. |
| `CLIPROXYAPI_CONFIG_DIR` | `~/.cli-proxy-api` | `src/lib/versionManager/processManager.ts` | CLIProxyAPI config directory. |
-| `MUX_SERVICE_PORT` | `8322` | `src/lib/services/bootstrap.ts` | Override the port where the embedded Mux (coder/mux) agent-orchestration daemon listens (always 127.0.0.1). |
| `LOCAL_HOSTNAMES` | _(empty)_ | `open-sse/config/providerRegistry.ts` | Comma-separated additional hostnames treated as "local" (Docker service names, etc.). |
`ENABLE_CC_COMPATIBLE_PROVIDER` is only for third-party relays that accept Claude Code clients
@@ -831,11 +822,6 @@ Anthropic-compatible provider instead.
| `PROXY_FAST_FAIL_TIMEOUT_MS` | `2000` | `src/lib/proxyHealth.ts` | Fast-fail health check timeout. |
| `PROXY_HEALTH_CACHE_TTL_MS` | `30000` | `src/lib/proxyHealth.ts` | Health check result cache TTL. |
| `PROXY_HEALTH_UNHEALTHY_CACHE_TTL_MS` | `2000` | `src/lib/proxyHealth.ts` | Cache TTL for failed proxy health probes. Keep this shorter than `PROXY_HEALTH_CACHE_TTL_MS` so transient proxy timeouts under high concurrency retry quickly without disabling fast-fail for truly dead proxies. |
-| `PROXY_HEALTH_ENABLED` | `true` | `src/lib/proxyHealth/scheduler.ts` | Set `false` to disable the background proxy health scheduler that periodically probes registered proxies. |
-| `PROXY_HEALTH_INTERVAL_MS` | `600000` | `src/lib/proxyHealth/scheduler.ts` | Background health-scheduler sweep interval in ms (minimum `60000`). |
-| `PROXY_HEALTH_TEST_URL` | `https://httpbin.org/ip` | `src/lib/proxyHealth/scheduler.ts` | Reachability probe target used by the scheduler and the `/api/settings/proxies/auto-test` endpoint. Point it at an internal/self-hosted URL to avoid the public default. |
-| `PROXY_AUTO_REMOVE` | `false` | `src/lib/proxyHealth/scheduler.ts` | Set `true` to let the scheduler auto-remove proxies after repeated consecutive failures. |
-| `PROXY_AUTO_REMOVE_AFTER` | `3` | `src/lib/proxyHealth/scheduler.ts` | Consecutive failures before the scheduler auto-removes a proxy (when `PROXY_AUTO_REMOVE=true`). |
| `OMNIROUTE_CONTROL_PLANE_PROXY_DIRECT_FALLBACK` | `false` | `src/shared/constants/featureFlagDefinitions.ts` | Allow OAuth and provider validation flows to bypass a pinned proxy and connect directly when proxy reachability pre-checks fail. Effective precedence is Feature Flags DB override > env var > default. |
| `RATE_LIMIT_MAX_WAIT_MS` | `120000` (2 min) | `open-sse/services/rateLimitManager.ts` | Max time to wait on a 429 before failing the request. |
| `RATE_LIMIT_AUTO_ENABLE` | _(unset)_ | `open-sse/services/rateLimitManager.ts` | Force the auto-enable rate limit safety net on/off regardless of the persisted Dashboard setting. Accepts `true`/`1`/`on` to force on, `false`/`0`/`off` to force off. |
@@ -1019,10 +1005,6 @@ Provider quota endpoints, network tunnels (Tailscale, Ngrok, MITM debug proxy),
| `FREE_PROXY_PROXIFLY_ANONYMITY` | `elite` | `src/lib/freeProxyProviders/proxifly.ts` | Anonymity level filter for Proxifly (`elite`, `anonymous`, `transparent`). |
| `FREE_PROXY_IPLOCATE_ENABLED` | `false` | `src/lib/freeProxyProviders/iplocate.ts` | Enable the IPLocate free proxy source. Opt-in only. |
| `FREE_PROXY_IPLOCATE_BASE_URL` | `https://raw.githubusercontent.com/iplocate/free-proxy-list/main/protocols` | `src/lib/freeProxyProviders/iplocate.ts` | IPLocate proxy list base URL override. |
-| `FREE_PROXY_WEBSHARE_ENABLED` | `true` | `src/lib/freeProxyProviders/webshare.ts` | Enable the Webshare proxy pool source. Set to `false` to disable; also requires `FREE_PROXY_WEBSHARE_API_KEY` to be set. |
-| `FREE_PROXY_WEBSHARE_API_KEY` | _(none)_ | `src/lib/freeProxyProviders/webshare.ts` | Webshare account API token (`Authorization: Token <key>`). Required — the provider stays disabled without it. |
-| `FREE_PROXY_WEBSHARE_API_URL` | `https://proxy.webshare.io/api/v2/proxy/list/` | `src/lib/freeProxyProviders/webshare.ts` | Webshare proxy list API URL override. |
-| `FREE_PROXY_WEBSHARE_MAX` | `500` | `src/lib/freeProxyProviders/webshare.ts` | Maximum proxies imported per Webshare sync. |
| `NEXT_PUBLIC_VERCEL_RELAY_ENABLED` | `true` | `src/app/(dashboard)/…/ProxyPoolTab.tsx` | Show/hide the Deploy Vercel Relay button in the Proxy Pool tab. |
| `VERCEL_API_BASE` | `https://api.vercel.com` | `src/app/api/settings/proxy/vercel-deploy/route.ts` | Vercel API base URL override (for testing). |
| `NEXT_PUBLIC_VERCEL_RELAY_DEFAULT_PROJECT` | `omniroute-relay` | `src/app/(dashboard)/…/VercelRelayModal.tsx` | Default project name pre-filled in the Vercel Relay deploy modal. |
@@ -1056,7 +1038,6 @@ Provider quota endpoints, network tunnels (Tailscale, Ngrok, MITM debug proxy),
| `PLAYGROUND_IMPROVE_PROMPT_DEFAULT_MODEL` | _(unset)_ | `src/app/(dashboard)/dashboard/playground/` | Default model for the Playground 'improve prompt' action (falls back to the active model when unset). |
| `BIFROST_ENABLED` | `1` | `src/app/api/v1/relay/chat/completions/bifrost/route.ts` | Master kill switch for the bifrost sidecar proxy. When set to `0`, the route returns 503 with the `X-Bifrost-Killswitch` header and the operator is bounced to the TS path. Use to disable the sidecar without redeploying (tier-1 router incident, key rotation). |
| `BIFROST_BASE_URL` | _(unset)_ | `src/app/api/v1/relay/chat/completions/bifrost/route.ts` | When set, the Bifrost sidecar proxy route forwards `/v1/chat/completions` traffic to this Go gateway instead of the TS relay handler. Unset → 503-with-fallback. Trailing slash is stripped. |
-| `BIFROST_PORT` | `8080` | `src/lib/services/bootstrap.ts` | Port the supervised Bifrost embedded service binds to (`127.0.0.1:<port>`) when OmniRoute manages the Bifrost sidecar lifecycle. Defaults to `8080`. |
| `BIFROST_API_KEY` | _(unset)_ | `src/app/api/v1/relay/chat/completions/bifrost/route.ts` | API key for the Bifrost gateway (sent as `Authorization: Bearer ...`). If unset, the route expects the request to carry a valid OmniRoute API key; this key is for gateway-side auth only. |
| `BIFROST_STREAMING_ENABLED` | `true` | `src/app/api/v1/relay/chat/completions/bifrost/route.ts` | When true, the Bifrost sidecar route streams responses back via SSE through the gateway rather than the TS streaming executor. Set to `0` to force non-streaming JSON responses through the gateway. |
| `BIFROST_TIMEOUT_MS` | `30000` | `src/app/api/v1/relay/chat/completions/bifrost/route.ts` | Per-request timeout when proxying to the Bifrost gateway (ms). On timeout the route returns the TS relay path via the `X-Bifrost-Fallback` header. |
diff --git a/docs/reference/PROVIDER_PLUGIN_MANIFEST.md b/docs/reference/PROVIDER_PLUGIN_MANIFEST.md
deleted file mode 100644
index 9f91dc39ed..0000000000
--- a/docs/reference/PROVIDER_PLUGIN_MANIFEST.md
+++ /dev/null
@@ -1,81 +0,0 @@
----
-title: "Provider Plugin Manifest"
-version: 3.8.42
-lastUpdated: 2026-07-01
----
-
-# Provider Plugin Manifest
-
-`open-sse/config/providerPluginManifest.ts` defines the JSON-safe provider
-plugin contract. `open-sse/config/providerPluginManifestRegistry.ts` binds that
-contract to the current provider registry for sidecars such as Bifrost,
-CLIProxyAPI, or a future Go/Rust router. The TypeScript registry remains the
-source of truth, but sidecars can consume the manifest without importing
-executor code, OAuth defaults, headers, or process environment state.
-
-The same manifest is available over HTTP at
-`GET /api/v1/provider-plugin-manifest` for sidecars that run out-of-process.
-
-OmniRoute advertises that URL to Bifrost and CLIProxyAPI via the
-`X-OmniRoute-Provider-Manifest-Url` request header. Set
-`OMNIROUTE_PROVIDER_MANIFEST_URL` when the sidecar needs a public or container
-network URL instead of the local request origin.
-
-## Goal
-
-Move provider metadata toward a plugin contract so the hot request path can
-eventually be owned by a lower-latency sidecar while OmniRoute keeps the
-TypeScript route as the policy gate and fallback. The manifest is additive: it
-does not change request routing by itself.
-
-## Contract
-
-The manifest contains:
-
-- provider id and alias
-- upstream format and executor name
-- auth type, auth header, and optional auth prefix
-- static endpoint metadata
-- sidecar eligibility and explicit reasons when a provider should stay on TS
-- JSON-safe model metadata such as context length, vision/reasoning flags, and
- unsupported params
-- capability tags including `apikey`, `oauth`, `custom-executor`,
- `passthrough-models`, `responses`, and `sidecar-candidate`
-
-The manifest intentionally excludes:
-
-- OAuth client secrets and default secret values
-- runtime environment resolution
-- request headers and public credential helpers
-- dynamic URL builders
-- executor functions
-- session pool internals
-
-## Sidecar Use
-
-Sidecars should treat `sidecar.eligible` as a conservative candidate signal, not
-as an unconditional routing decision. The first import target should be
-API-key, static-endpoint providers using the default executor. Providers with
-custom web executors, OAuth/session flows, dynamic URL builders, or pool config
-stay on the TypeScript fallback path until a sidecar implements equivalent
-behavior and telemetry proves parity.
-
-Suggested migration phases:
-
-1. Generate and validate the provider plugin manifest from the TS registry.
-2. Teach Bifrost or CLIProxyAPI to import the manifest for API-key/static
- providers.
-3. Route eligible providers through the sidecar behind `OMNIROUTE_RELAY_BACKEND`
- while keeping TS fallback enabled.
-4. Promote providers only when success rate, p99 latency, streaming behavior,
- and unsupported-param handling match the TS path.
-5. Add sidecar-native plugins for custom executors one provider family at a
- time.
-
-## Why Not Embed Providers Directly In Next
-
-The Next frontend should not own provider execution. It should call the API
-boundary. The backend can then decide whether to use the TypeScript executor,
-Bifrost, CLIProxyAPI, or a future native sidecar. This keeps request signing,
-allowlist checks, DB policy, and fallback behavior centralized before any
-sidecar handoff.
diff --git a/docs/reference/RELAY_BACKEND_STRATEGY.md b/docs/reference/RELAY_BACKEND_STRATEGY.md
index 69e38f28a0..6db4942e74 100644
--- a/docs/reference/RELAY_BACKEND_STRATEGY.md
+++ b/docs/reference/RELAY_BACKEND_STRATEGY.md
@@ -75,10 +75,3 @@ For sustained high RPM/RPS and strict success SLO:
- `BIFROST_ENABLED=1`
- Keep API keys, allowlist, sanitizer, and rate-limit checks enabled in route handlers (they always run before downstream forwarding).
- Export fallback metrics from your reverse proxy and request logs so sidecar outages are visible within one minute.
-
-## Provider plugin contract
-
-Sidecars should import provider metadata through the JSON-safe provider plugin
-manifest instead of depending on TypeScript executor internals. See
-[Provider Plugin Manifest](./PROVIDER_PLUGIN_MANIFEST.md) for the sidecar
-eligibility contract and migration phases.
diff --git a/docs/security/CORS.md b/docs/security/CORS.md
deleted file mode 100644
index 557f7fa610..0000000000
--- a/docs/security/CORS.md
+++ /dev/null
@@ -1,162 +0,0 @@
----
-title: CORS Configuration & Security
----
-
-# CORS Configuration & Security
-
-OmniRoute controls which **browser origins** may read cross-origin responses
-from a single, centralized allowlist. The model is **fail-closed by default**:
-no origin is allowed until you opt one in. This page documents how the allowlist
-resolves, what `CORS_ALLOW_ALL=true` actually exposes (and, importantly, what it
-does **not**), how to configure dev vs production safely, and the runtime warning
-the dashboard shows when a wildcard is live.
-
-**Source of truth:** `src/server/cors/origins.ts` (`resolveAllowedOrigin`,
-`applyCorsHeaders`, `getCorsStatus`). The allowlist is applied once, in the
-middleware (`src/server/authz/pipeline.ts`) — per-route handlers do not set
-`Access-Control-Allow-Origin` themselves.
-
-## How an origin is resolved
-
-For each request the middleware computes the `Access-Control-Allow-Origin` value
-in this order:
-
-1. **`CORS_ALLOW_ALL=true`** (or the legacy `CORS_ORIGIN=*`) → echo the caller's
- `Origin` back (or `*` when there is no `Origin` header), with `Vary: Origin`
- so caches stay correct.
-2. Otherwise, the request `Origin` is normalized (lower-cased, trailing slash
- stripped) and matched against the **merged allowlist**:
- - env **`CORS_ALLOWED_ORIGINS`** — comma-separated list, and
- - the runtime **`corsOrigins`** setting (Dashboard → Security → _CORS Allowed
- Origins_), injected via `setRuntimeAllowedOrigins()` from
- `src/lib/config/runtimeSettings.ts`.
-3. No match → **no `Access-Control-Allow-Origin` header is emitted**. The browser
- blocks the cross-origin read. This is the intended fail-closed default.
-
-| Env var | Meaning |
-| ---------------------- | ------------------------------------------------------------------------------------ |
-| `CORS_ALLOWED_ORIGINS` | CSV of exact origins to allow (recommended). |
-| `CORS_ALLOW_ALL` | `true`/`1` → echo any origin (wildcard). Dev only. |
-| `CORS_ORIGIN` | Legacy. `*` behaves like `CORS_ALLOW_ALL`; a single value is added to the allowlist. |
-
-## Threat model — what `CORS_ALLOW_ALL=true` really exposes
-
-The generic OWASP warning ("wildcard CORS = any site can call your API") is worth
-taking seriously, but OmniRoute's exposure is **narrower than the generic case**,
-because of one concrete implementation fact:
-
-> **The central `applyCorsHeaders()` never emits
-> `Access-Control-Allow-Credentials`.** A browser will not expose a _credentialed_
-> (cookie-bearing) cross-origin response unless the server sends
-> `Access-Control-Allow-Credentials: true`. OmniRoute's shared CORS path never
-> does.
-
-What that means per surface, even with `CORS_ALLOW_ALL=true`:
-
-| Surface | Auth mechanism | Effect of wildcard CORS |
-| ----------------------------------- | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Dashboard / MANAGEMENT `/api/*` | Cookie session | Origin is echoed, but **without `Allow-Credentials`** the browser **blocks** the credentialed read. A malicious cross-origin site **cannot read** your authenticated dashboard responses, and the session cookie is not exposed. |
-| Client API `/v1/*`, `/v1beta/*` | Bearer / `x-api-key` header | Already permissive **by design** (`relaxForTokenAuth`): browsers never auto-attach `Authorization`/`x-api-key`, so an attacker's page cannot supply your key. `CORS_ALLOW_ALL` does not widen this. |
-| Public read-only (`/api/health`, …) | None | Non-sensitive; wildcard is harmless. |
-
-So the **residual** exposure of `CORS_ALLOW_ALL=true` is limited to: (a)
-non-credentialed cross-origin **reads** of already-unauthenticated data, and (b)
-letting CORS **preflight pass** on management routes — which still require auth
-that a cross-origin page cannot provide. It is **not** a session-hijack or
-credential-theft vector on the shared CORS path.
-
-### One genuine exception — `/api/v1/agents/`
-
-The Cloud-Agent routes (`/api/v1/agents/{health,credentials,tasks,tasks/[id]}`) set
-their **own** CORS headers
-(`src/lib/cloudAgent/api.ts`, `getCloudAgentCorsHeaders`) and **do** emit
-`Access-Control-Allow-Origin: <origin>|*` together with
-`Access-Control-Allow-Credentials: true`. This is the single surface where
-origin-echo and credentials coexist, and it is **independent of
-`CORS_ALLOW_ALL`**. These routes are management-authenticated
-(`requireManagementAuth`); operators who expose the dashboard off-host should be
-aware that this is the one place a cross-origin credentialed read is permitted by
-the response headers. Tightening it to an explicit allowlist is tracked
-separately from this CORS guidance.
-
-## Production checklist
-
-- **Never set `CORS_ALLOW_ALL=true` in production.** Leave it unset.
-- Set an **explicit** origin list — either the env var or the Security-tab field:
-
- ```bash
- CORS_ALLOWED_ORIGINS="https://app.example.com, https://admin.example.com"
- ```
-
-- If OmniRoute runs behind a reverse proxy / tunnel (nginx, Caddy, Cloudflare
- Tunnel, Tailscale), CORS is **not** your only control — the loopback route
- guard still protects spawn-capable routes (see
- [ROUTE_GUARD_TIERS](./ROUTE_GUARD_TIERS.md)). Do not forge
- `X-Forwarded-For: 127.0.0.1` to "fix" a 403; that re-opens the RCE class the
- route guard closes.
-- Confirm the runtime state: the dashboard shows a **persistent amber banner**
- under Dashboard → Security → Authorization Inventory whenever
- `CORS_ALLOW_ALL=true` is live, and `/api/settings/authz-inventory` returns a
- `cors: { allowAll, allowedOrigins }` envelope monitoring tools can poll.
-
-## Development convenience — allow specific local origins
-
-You rarely need the wildcard even in dev. Allow just the dev servers you use:
-
-```bash
-# Vite (5173) + Next.js (3000) dev servers calling a local OmniRoute
-CORS_ALLOWED_ORIGINS="http://localhost:5173, http://localhost:3000"
-```
-
-Origins are matched case-insensitively with the trailing slash ignored, so
-`http://localhost:3000` and `http://localhost:3000/` are equivalent. The same CSV
-can be set at runtime in **Dashboard → Security → CORS Allowed Origins** without a
-restart.
-
-## API keys vs cookie sessions
-
-- **Bearer / `x-api-key` (the `/v1/*` inference surface):** browsers never attach
- these automatically. CORS is not a meaningful barrier here — the API key is the
- barrier — which is why that surface is intentionally permissive so browser and
- Electron clients can read responses they are already entitled to.
-- **Cookie session (the dashboard):** protected by the fail-closed default **and**
- by the absence of `Access-Control-Allow-Credentials` on the shared path. Keep
- management/dashboard origins out of any permissive config; they must stay exactly
- fail-closed.
-
-## Example: reverse proxy in front of OmniRoute
-
-CORS is enforced by OmniRoute itself, so the proxy generally should **not** add or
-rewrite `Access-Control-*` headers (double headers break browsers). Terminate TLS
-and forward — let OmniRoute answer preflight:
-
-```nginx
-# nginx — forward to OmniRoute; do NOT inject Access-Control-* here
-location / {
- proxy_pass http://127.0.0.1:20128;
- proxy_set_header Host $host;
- proxy_set_header X-Forwarded-Proto $scheme;
- # Do NOT set X-Forwarded-For to 127.0.0.1 — it defeats the loopback route guard.
-}
-```
-
-Set the allowed browser origins in OmniRoute (`CORS_ALLOWED_ORIGINS` or the
-Security tab), not in the proxy.
-
-## Source files
-
-| Concern | File |
-| ----------------------------------------------- | -------------------------------------------------------------------- |
-| Allowlist resolution + `getCorsStatus()` | `src/server/cors/origins.ts` |
-| Middleware application (single source of truth) | `src/server/authz/pipeline.ts` |
-| Settings → runtime origin injection | `src/lib/config/runtimeSettings.ts` |
-| Runtime status for the dashboard | `src/app/api/settings/authz-inventory/route.ts` |
-| Dashboard warning banner | `src/app/(dashboard)/dashboard/settings/components/AuthzSection.tsx` |
-| CORS Allowed Origins field | `src/app/(dashboard)/dashboard/settings/components/SecurityTab.tsx` |
-| Cloud-Agent per-route CORS (the exception) | `src/lib/cloudAgent/api.ts` |
-
-## See also
-
-- [Route Guard Tiers](./ROUTE_GUARD_TIERS.md) — loopback enforcement for
- spawn-capable routes (a separate, complementary control).
-- [Authorization Guide](../architecture/AUTHZ_GUIDE.md) — the full auth pipeline.
diff --git a/electron/package-lock.json b/electron/package-lock.json
index 4bd0d087ca..a2073848e4 100644
--- a/electron/package-lock.json
+++ b/electron/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "omniroute-desktop",
- "version": "3.8.44",
+ "version": "3.8.43",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "omniroute-desktop",
- "version": "3.8.44",
+ "version": "3.8.43",
"license": "MIT",
"dependencies": {
"electron-updater": "^6.8.9"
diff --git a/electron/package.json b/electron/package.json
index 6cca7ee884..0563f35ae5 100644
--- a/electron/package.json
+++ b/electron/package.json
@@ -1,6 +1,6 @@
{
"name": "omniroute-desktop",
- "version": "3.8.44",
+ "version": "3.8.43",
"description": "OmniRoute Desktop Application",
"main": "main.js",
"author": {
diff --git a/next.config.mjs b/next.config.mjs
index 415f5b986e..24bbc30de5 100644
--- a/next.config.mjs
+++ b/next.config.mjs
@@ -94,13 +94,6 @@ function readTimeoutMs(...values) {
/** @type {import('next').NextConfig} */
const nextConfig = {
- // Opt-in subpath deployment behind a reverse proxy (e.g. nginx/Caddy serving
- // OmniRoute under https://host/omniroute/). Empty by default so root-path
- // deployments are unaffected. Next.js strips this prefix from `pathname`
- // before route matching, so authz classification (classifyRoute/isLocalOnlyPath)
- // keeps operating on un-prefixed paths — see src/server/authz/pipeline.ts for
- // the two redirect call sites that re-add it via `request.nextUrl.basePath`.
- basePath: process.env.OMNIROUTE_BASE_PATH || "",
distDir,
// Turbopack config: redirect native modules to stubs at build time
turbopack: {
@@ -214,13 +207,6 @@ const nextConfig = {
"tough-cookie",
"@ngrok/ngrok",
"@huggingface/transformers",
- // copilot-m365-web.ts imports 'ws' as a client-side WebSocket. When bundled,
- // ws cannot resolve its 'bufferutil' native addon (frame masking) and throws
- // TypeError: b.mask is not a function on the first outgoing frame, causing
- // every chat request to time out at the stream-readiness watchdog. (#6062)
- "ws",
- "bufferutil",
- "utf-8-validate",
"child_process",
"fs",
"path",
diff --git a/open-sse/config/audioRegistry.ts b/open-sse/config/audioRegistry.ts
index cbeaa789e5..b281a94e35 100644
--- a/open-sse/config/audioRegistry.ts
+++ b/open-sse/config/audioRegistry.ts
@@ -3,7 +3,6 @@
*
* Defines providers that support audio endpoints:
* - /v1/audio/transcriptions (Whisper API)
- * - /v1/audio/translations (Whisper translate-to-English API)
* - /v1/audio/speech (TTS API)
*/
@@ -161,30 +160,6 @@ export const AUDIO_TRANSCRIPTION_PROVIDERS: Record<string, AudioProvider> = {
},
};
-/**
- * Providers that expose an OpenAI-Whisper-compatible /audio/translations
- * endpoint (translate-to-English). This is a narrower surface than
- * transcription: only Whisper-family models support it, and there is no
- * `language` input — output is always English regardless of source audio.
- */
-export const AUDIO_TRANSLATION_PROVIDERS: Record<string, AudioProvider> = {
- openai: {
- id: "openai",
- baseUrl: "https://api.openai.com/v1/audio/translations",
- authType: "apikey",
- authHeader: "bearer",
- models: [{ id: "whisper-1", name: "Whisper 1" }],
- },
-
- groq: {
- id: "groq",
- baseUrl: "https://api.groq.com/openai/v1/audio/translations",
- authType: "apikey",
- authHeader: "bearer",
- models: [{ id: "whisper-large-v3", name: "Whisper Large v3" }],
- },
-};
-
export const AUDIO_SPEECH_PROVIDERS: Record<string, AudioProvider> = {
vertex: {
id: "vertex",
@@ -428,13 +403,6 @@ export function getTranscriptionProvider(providerId: string): AudioProvider | nu
return AUDIO_TRANSCRIPTION_PROVIDERS[providerId] || null;
}
-/**
- * Get translation provider config by ID
- */
-export function getTranslationProvider(providerId: string): AudioProvider | null {
- return AUDIO_TRANSLATION_PROVIDERS[providerId] || null;
-}
-
/**
* Get speech provider config by ID
*/
@@ -512,13 +480,6 @@ export function parseSpeechModel(modelStr: string | null, dynamicProviders?: Aud
return parseAudioModel(modelStr, AUDIO_SPEECH_PROVIDERS, dynamicProviders);
}
-export function parseTranslationModel(
- modelStr: string | null,
- dynamicProviders?: AudioProvider[]
-) {
- return parseAudioModel(modelStr, AUDIO_TRANSLATION_PROVIDERS, dynamicProviders);
-}
-
/**
* Get all audio models as a flat list
*/
diff --git a/open-sse/config/embeddingRegistry.ts b/open-sse/config/embeddingRegistry.ts
index 16ffcd68ab..d7ba0777f5 100644
--- a/open-sse/config/embeddingRegistry.ts
+++ b/open-sse/config/embeddingRegistry.ts
@@ -93,17 +93,6 @@ export const EMBEDDING_PROVIDERS: Record<string, EmbeddingProvider> = {
],
},
- "vercel-ai-gateway": {
- id: "vercel-ai-gateway",
- baseUrl: "https://ai-gateway.vercel.sh/v1/embeddings",
- authType: "apikey",
- authHeader: "bearer",
- models: [
- { id: "text-embedding-3-small", name: "Text Embedding 3 Small", dimensions: 1536 },
- { id: "text-embedding-3-large", name: "Text Embedding 3 Large", dimensions: 3072 },
- ],
- },
-
upstage: {
id: "upstage",
baseUrl: "https://api.upstage.ai/v1/embeddings",
diff --git a/open-sse/config/imageRegistry.ts b/open-sse/config/imageRegistry.ts
index 330a37c730..bc83b37c84 100644
--- a/open-sse/config/imageRegistry.ts
+++ b/open-sse/config/imageRegistry.ts
@@ -175,20 +175,6 @@ export const IMAGE_PROVIDERS: Record<string, ImageProviderConfig> = {
supportedSizes: ["1024x1024", "2048x2048"],
},
- "vercel-ai-gateway": {
- id: "vercel-ai-gateway",
- alias: "vag",
- baseUrl: "https://ai-gateway.vercel.sh/v1/images/generations",
- authType: "apikey",
- authHeader: "bearer",
- format: "openai",
- models: [
- { id: "gpt-image-1", name: "GPT Image 1" },
- { id: "black-forest-labs/flux-1.1-pro", name: "FLUX 1.1 Pro" },
- ],
- supportedSizes: ["1024x1024", "1024x1792", "1792x1024"],
- },
-
together: {
id: "together",
baseUrl: "https://api.together.xyz/v1/images/generations",
@@ -563,35 +549,6 @@ export const IMAGE_PROVIDERS: Record<string, ImageProviderConfig> = {
supportedSizes: ["1024x1024", "1024x1280", "1280x1024"],
},
- // NVIDIA NIM image generation (FLUX models). Distinct from the NVIDIA *chat* entry
- // (open-sse/config/providers/registry/nvidia/index.ts, host integrate.api.nvidia.com,
- // OpenAI-compatible) — image generation lives on ai.api.nvidia.com/v1/genai/<model>
- // with a native NIM body per model, so it gets a dedicated `nvidia-nim` format/handler
- // (handleNvidiaNimImageGeneration) rather than reusing the OpenAI image path.
- // Ported from upstream 9router#1195.
- nvidia: {
- id: "nvidia",
- baseUrl: "https://ai.api.nvidia.com/v1/genai",
- authType: "apikey",
- authHeader: "bearer",
- format: "nvidia-nim",
- models: [
- { id: "black-forest-labs/flux.1-dev", name: "FLUX.1 Dev", inputModalities: ["text", "image"] },
- { id: "black-forest-labs/flux.1-schnell", name: "FLUX.1 Schnell" },
- {
- id: "black-forest-labs/flux.1-kontext-dev",
- name: "FLUX.1 Kontext Dev (Edit)",
- inputModalities: ["text", "image"],
- },
- {
- id: "black-forest-labs/flux.2-klein-4b",
- name: "FLUX.2 Klein 4B",
- inputModalities: ["text", "image"],
- },
- ],
- supportedSizes: ["1024x1024", "768x1344", "512x512"],
- },
-
// SenseNova (商汤日日新) Text-to-Image on the free Token Plan. OpenAI-compatible
// `/v1/images/generations`, so the generic OpenAI image handler routes it — same
// SenseNova api-key/connection as the chat provider. (9router#2233)
@@ -604,27 +561,6 @@ export const IMAGE_PROVIDERS: Record<string, ImageProviderConfig> = {
models: [{ id: "sensenova-u1-fast", name: "SenseNova U1 Fast" }],
supportedSizes: ["1024x1024"],
},
-
- // HuggingFace Hub Inference API text-to-image task. Returns raw image bytes
- // (not JSON), so it uses a dedicated "huggingface-image" format handled by
- // handleHuggingFaceImageGeneration. Same base URL convention as the HF
- // STT/TTS entries in audioRegistry.ts. Model list is deliberately small —
- // the dashboard's "suggested models" chip row (GET
- // /api/v1/providers/suggested-models) surfaces additional HF Hub models
- // beyond this seed list.
- huggingface: {
- id: "huggingface",
- baseUrl: "https://api-inference.huggingface.co/models",
- authType: "apikey",
- authHeader: "bearer",
- format: "huggingface-image",
- models: [
- { id: "black-forest-labs/FLUX.1-dev", name: "FLUX.1 Dev (HF)" },
- { id: "black-forest-labs/FLUX.1-schnell", name: "FLUX.1 Schnell (HF)" },
- { id: "stabilityai/stable-diffusion-xl-base-1.0", name: "Stable Diffusion XL (HF)" },
- ],
- supportedSizes: ["1024x1024"],
- },
};
/**
diff --git a/open-sse/config/mediaServiceKinds.ts b/open-sse/config/mediaServiceKinds.ts
index 22a692c971..95e831ce40 100644
--- a/open-sse/config/mediaServiceKinds.ts
+++ b/open-sse/config/mediaServiceKinds.ts
@@ -17,12 +17,14 @@
* still declared explicitly via `serviceKinds` on the provider entry; callers
* union the two sources.
*/
-import { AUDIO_TRANSCRIPTION_PROVIDERS, AUDIO_SPEECH_PROVIDERS } from "./audioRegistry.ts";
+import {
+ AUDIO_TRANSCRIPTION_PROVIDERS,
+ AUDIO_SPEECH_PROVIDERS,
+} from "./audioRegistry.ts";
import { VIDEO_PROVIDERS } from "./videoRegistry.ts";
import { MUSIC_PROVIDERS } from "./musicRegistry.ts";
import { IMAGE_PROVIDERS } from "./imageRegistry.ts";
import { EMBEDDING_PROVIDERS } from "./embeddingRegistry.ts";
-import { OCR_PROVIDERS } from "./ocrRegistry.ts";
/** Media kinds whose provider membership is defined by a backend registry. */
export const MEDIA_KIND_REGISTRIES = {
@@ -32,7 +34,6 @@ export const MEDIA_KIND_REGISTRIES = {
music: MUSIC_PROVIDERS,
image: IMAGE_PROVIDERS,
embedding: EMBEDDING_PROVIDERS,
- ocr: OCR_PROVIDERS,
} as const satisfies Record<string, Record<string, unknown>>;
export type RegistryMediaKind = keyof typeof MEDIA_KIND_REGISTRIES;
diff --git a/open-sse/config/moderationRegistry.ts b/open-sse/config/moderationRegistry.ts
index c63d9e17b4..4a3f621998 100644
--- a/open-sse/config/moderationRegistry.ts
+++ b/open-sse/config/moderationRegistry.ts
@@ -5,25 +5,7 @@
* Follows OpenAI's moderation API format.
*/
-export interface ModerationModel {
- id: string;
- name: string;
-}
-
-export interface ModerationProvider {
- id: string;
- baseUrl: string;
- authType: string;
- authHeader: string;
- models: ModerationModel[];
-}
-
-export interface ParsedModerationModel {
- provider: string | null;
- model: string | null;
-}
-
-export const MODERATION_PROVIDERS: Record<string, ModerationProvider> = {
+export const MODERATION_PROVIDERS = {
openai: {
id: "openai",
baseUrl: "https://api.openai.com/v1/moderations",
@@ -34,29 +16,22 @@ export const MODERATION_PROVIDERS: Record<string, ModerationProvider> = {
{ id: "text-moderation-latest", name: "Text Moderation Latest" },
],
},
- mistral: {
- id: "mistral",
- baseUrl: "https://api.mistral.ai/v1/moderations",
- authType: "apikey",
- authHeader: "bearer",
- models: [{ id: "mistral-moderation-latest", name: "Mistral Moderation" }],
- },
};
/**
- * Get moderation provider config by ID.
+ * Get moderation provider config by ID
*/
-export function getModerationProvider(providerId: string): ModerationProvider | null {
+export function getModerationProvider(providerId) {
return MODERATION_PROVIDERS[providerId] || null;
}
/**
- * Parse a moderation model string.
+ * Parse moderation model string
*/
-export function parseModerationModel(modelStr: string | null | undefined): ParsedModerationModel {
+export function parseModerationModel(modelStr) {
if (!modelStr) return { provider: null, model: null };
- for (const providerId of Object.keys(MODERATION_PROVIDERS)) {
+ for (const [providerId, config] of Object.entries(MODERATION_PROVIDERS)) {
if (modelStr.startsWith(providerId + "/")) {
return { provider: providerId, model: modelStr.slice(providerId.length + 1) };
}
@@ -72,10 +47,10 @@ export function parseModerationModel(modelStr: string | null | undefined): Parse
}
/**
- * Get all moderation models as a flat list.
+ * Get all moderation models as a flat list
*/
-export function getAllModerationModels(): Array<{ id: string; name: string; provider: string }> {
- const models: Array<{ id: string; name: string; provider: string }> = [];
+export function getAllModerationModels() {
+ const models = [];
for (const [providerId, config] of Object.entries(MODERATION_PROVIDERS)) {
for (const model of config.models) {
models.push({
diff --git a/open-sse/config/ocrRegistry.ts b/open-sse/config/ocrRegistry.ts
deleted file mode 100644
index fdf47d44f1..0000000000
--- a/open-sse/config/ocrRegistry.ts
+++ /dev/null
@@ -1,82 +0,0 @@
-/**
- * OCR Provider Registry
- *
- * Defines providers that support the /v1/ocr endpoint.
- * Follows Mistral's OCR API format.
- */
-
-export interface OcrModel {
- id: string;
- name: string;
-}
-
-export interface OcrProvider {
- id: string;
- baseUrl: string;
- authType: string;
- authHeader: string;
- models: OcrModel[];
-}
-
-export interface ParsedOcrModel {
- provider: string | null;
- model: string | null;
-}
-
-export const OCR_PROVIDERS: Record<string, OcrProvider> = {
- mistral: {
- id: "mistral",
- baseUrl: "https://api.mistral.ai/v1/ocr",
- authType: "apikey",
- authHeader: "bearer",
- models: [{ id: "mistral-ocr-latest", name: "Mistral OCR" }],
- },
-};
-
-/**
- * Get OCR provider config by ID.
- */
-export function getOcrProvider(providerId: string): OcrProvider | null {
- return OCR_PROVIDERS[providerId] || null;
-}
-
-/**
- * Parse an OCR model string.
- *
- * Accepts either a "provider/model" prefixed string or a bare model id that
- * matches one of the registered OCR models.
- */
-export function parseOcrModel(modelStr: string | null | undefined): ParsedOcrModel {
- if (!modelStr) return { provider: null, model: null };
-
- for (const providerId of Object.keys(OCR_PROVIDERS)) {
- if (modelStr.startsWith(providerId + "/")) {
- return { provider: providerId, model: modelStr.slice(providerId.length + 1) };
- }
- }
-
- for (const [providerId, config] of Object.entries(OCR_PROVIDERS)) {
- if (config.models.some((m) => m.id === modelStr)) {
- return { provider: providerId, model: modelStr };
- }
- }
-
- return { provider: null, model: modelStr };
-}
-
-/**
- * Get all OCR models as a flat list.
- */
-export function getAllOcrModels(): Array<{ id: string; name: string; provider: string }> {
- const models: Array<{ id: string; name: string; provider: string }> = [];
- for (const [providerId, config] of Object.entries(OCR_PROVIDERS)) {
- for (const model of config.models) {
- models.push({
- id: `${providerId}/${model.id}`,
- name: model.name,
- provider: providerId,
- });
- }
- }
- return models;
-}
diff --git a/open-sse/config/providerPluginManifest.ts b/open-sse/config/providerPluginManifest.ts
deleted file mode 100644
index b0a773e17c..0000000000
--- a/open-sse/config/providerPluginManifest.ts
+++ /dev/null
@@ -1,186 +0,0 @@
-import type { RegistryEntry, RegistryModel } from "./providers/shared.ts";
-
-export type ProviderPluginCapability =
- | "apikey"
- | "custom-executor"
- | "oauth"
- | "passthrough-models"
- | "responses"
- | "sidecar-candidate";
-
-export interface ProviderPluginModel {
- id: string;
- name: string;
- contextLength?: number;
- maxOutputTokens?: number;
- toolCalling?: boolean;
- supportsReasoning?: boolean;
- supportsVision?: boolean;
- unsupportedParams?: readonly string[];
- targetFormat?: string;
-}
-
-export interface ProviderPluginManifestEntry {
- id: string;
- alias?: string;
- format: string;
- executor: string;
- auth: {
- type: string;
- header: string;
- prefix?: string;
- };
- endpoints: {
- baseUrl?: string;
- baseUrls?: string[];
- responsesBaseUrl?: string;
- chatPath?: string;
- modelsUrl?: string;
- };
- capabilities: ProviderPluginCapability[];
- passthroughModels: boolean;
- defaultContextLength?: number;
- timeoutMs?: number;
- models: ProviderPluginModel[];
- sidecar: {
- eligible: boolean;
- reasons: string[];
- };
-}
-
-export interface ProviderPluginManifest {
- schemaVersion: 1;
- generatedFrom: "open-sse/config/providers";
- providers: ProviderPluginManifestEntry[];
-}
-
-const SIDECAR_COMPATIBLE_EXECUTORS = new Set(["default"]);
-
-function compactObject<T extends Record<string, unknown>>(value: T): Partial<T> {
- return Object.fromEntries(
- Object.entries(value).filter(([, entryValue]) => entryValue !== undefined),
- ) as Partial<T>;
-}
-
-function mapModel(model: RegistryModel): ProviderPluginModel {
- return compactObject({
- id: model.id,
- name: model.name,
- contextLength: model.contextLength,
- maxOutputTokens: model.maxOutputTokens,
- toolCalling: model.toolCalling,
- supportsReasoning: model.supportsReasoning,
- supportsVision: model.supportsVision,
- unsupportedParams: model.unsupportedParams,
- targetFormat: model.targetFormat,
- }) as ProviderPluginModel;
-}
-
-function sidecarEligibility(entry: RegistryEntry): { eligible: boolean; reasons: string[] } {
- const reasons: string[] = [];
-
- if (!SIDECAR_COMPATIBLE_EXECUTORS.has(entry.executor)) {
- reasons.push(`custom executor: ${entry.executor}`);
- }
- if (entry.authType !== "apikey" && entry.authType !== "optional" && entry.authType !== "none") {
- reasons.push(`auth type requires TS handling: ${entry.authType}`);
- }
- if (!entry.baseUrl && !entry.baseUrls?.length && !entry.responsesBaseUrl) {
- reasons.push("no static upstream endpoint");
- }
- if (typeof entry.urlBuilder === "function") {
- reasons.push("dynamic URL builder");
- }
- if (entry.oauth) {
- reasons.push("oauth metadata");
- }
- if (entry.poolConfig) {
- reasons.push("session pool config");
- }
-
- return {
- eligible: reasons.length === 0,
- reasons,
- };
-}
-
-function capabilitiesFor(entry: RegistryEntry, eligible: boolean): ProviderPluginCapability[] {
- const capabilities = new Set<ProviderPluginCapability>();
-
- if (entry.authType === "apikey" || entry.authType === "optional") {
- capabilities.add("apikey");
- }
- if (entry.authType === "oauth" || entry.oauth) {
- capabilities.add("oauth");
- }
- if (entry.responsesBaseUrl) {
- capabilities.add("responses");
- }
- if (entry.passthroughModels) {
- capabilities.add("passthrough-models");
- }
- if (entry.executor !== "default") {
- capabilities.add("custom-executor");
- }
- if (eligible) {
- capabilities.add("sidecar-candidate");
- }
-
- return [...capabilities].sort();
-}
-
-export function createProviderPluginManifestEntry(
- entry: RegistryEntry,
-): ProviderPluginManifestEntry {
- const sidecar = sidecarEligibility(entry);
-
- return {
- id: entry.id,
- ...(entry.alias ? { alias: entry.alias } : {}),
- format: entry.format,
- executor: entry.executor,
- auth: compactObject({
- type: entry.authType,
- header: entry.authHeader,
- prefix: entry.authPrefix,
- }) as ProviderPluginManifestEntry["auth"],
- endpoints: compactObject({
- baseUrl: entry.baseUrl,
- baseUrls: entry.baseUrls,
- responsesBaseUrl: entry.responsesBaseUrl,
- chatPath: entry.chatPath,
- modelsUrl: entry.modelsUrl,
- }) as ProviderPluginManifestEntry["endpoints"],
- capabilities: capabilitiesFor(entry, sidecar.eligible),
- passthroughModels: entry.passthroughModels === true,
- ...(typeof entry.defaultContextLength === "number"
- ? { defaultContextLength: entry.defaultContextLength }
- : {}),
- ...(typeof entry.timeoutMs === "number" ? { timeoutMs: entry.timeoutMs } : {}),
- models: (entry.models ?? []).map(mapModel),
- sidecar,
- };
-}
-
-export function generateProviderPluginManifestFromRegistry(
- registry: Record<string, RegistryEntry>,
-): ProviderPluginManifest {
- return {
- schemaVersion: 1,
- generatedFrom: "open-sse/config/providers",
- providers: Object.values(registry)
- .map(createProviderPluginManifestEntry)
- .sort((a, b) => a.id.localeCompare(b.id)),
- };
-}
-
-export function getProviderPluginManifestEntryFromRegistry(
- registry: Record<string, RegistryEntry>,
- provider: string,
-): ProviderPluginManifestEntry | null {
- const entry =
- registry[provider] ||
- Object.values(registry).find((candidate) => candidate.alias === provider);
-
- return entry ? createProviderPluginManifestEntry(entry) : null;
-}
diff --git a/open-sse/config/providerPluginManifestRegistry.ts b/open-sse/config/providerPluginManifestRegistry.ts
deleted file mode 100644
index 37b92ba4fb..0000000000
--- a/open-sse/config/providerPluginManifestRegistry.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { REGISTRY } from "./providers/index.ts";
-import {
- generateProviderPluginManifestFromRegistry,
- getProviderPluginManifestEntryFromRegistry,
- type ProviderPluginManifestEntry,
-} from "./providerPluginManifest.ts";
-
-export function generateProviderPluginManifest() {
- return generateProviderPluginManifestFromRegistry(REGISTRY);
-}
-
-export function getProviderPluginManifestEntry(provider: string) {
- return getProviderPluginManifestEntryFromRegistry(REGISTRY, provider);
-}
-
-export function getProviderPluginManifestEntryForModel(
- model: string | undefined,
-): ProviderPluginManifestEntry | null {
- if (!model) return null;
-
- const providerPrefix = model.includes("/") ? model.split("/", 1)[0] : "";
- if (providerPrefix) {
- const prefixed = getProviderPluginManifestEntry(providerPrefix);
- if (prefixed) return prefixed;
- }
-
- const manifest = generateProviderPluginManifest();
- return manifest.providers.find((provider) =>
- provider.models.some((candidate) => candidate.id === model),
- ) ?? null;
-}
diff --git a/open-sse/config/providerPluginManifestUrl.ts b/open-sse/config/providerPluginManifestUrl.ts
deleted file mode 100644
index c896770f30..0000000000
--- a/open-sse/config/providerPluginManifestUrl.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-export const PROVIDER_PLUGIN_MANIFEST_HEADER = "X-OmniRoute-Provider-Manifest-Url";
-export const PROVIDER_PLUGIN_MANIFEST_PATH = "/api/v1/provider-plugin-manifest";
-
-function trimTrailingSlash(value: string): string {
- return value.replace(/\/$/, "");
-}
-
-export function resolveProviderPluginManifestUrl(origin?: string | null): string {
- const configured = process.env.OMNIROUTE_PROVIDER_MANIFEST_URL?.trim();
- if (configured) return configured;
-
- if (origin) {
- return `${trimTrailingSlash(origin)}${PROVIDER_PLUGIN_MANIFEST_PATH}`;
- }
-
- const host = process.env.HOST || "127.0.0.1";
- const port = process.env.PORT || process.env.DASHBOARD_PORT || process.env.API_PORT || "20128";
- const protocol = process.env.OMNIROUTE_PUBLIC_PROTOCOL || "http";
- return `${protocol}://${host}:${port}${PROVIDER_PLUGIN_MANIFEST_PATH}`;
-}
-
-export function getProviderPluginManifestHeader(origin?: string | null): Record<string, string> {
- return {
- [PROVIDER_PLUGIN_MANIFEST_HEADER]: resolveProviderPluginManifestUrl(origin),
- };
-}
diff --git a/open-sse/config/providers/index.ts b/open-sse/config/providers/index.ts
index 9239a5b7d2..ac9847e86d 100644
--- a/open-sse/config/providers/index.ts
+++ b/open-sse/config/providers/index.ts
@@ -41,8 +41,6 @@ import { yiProvider } from "./registry/yi/index.ts";
import { deepseekProvider } from "./registry/deepseek/index.ts";
import { deepseek_webProvider } from "./registry/deepseek/web/index.ts";
import { dgridProvider } from "./registry/dgrid/index.ts";
-import { baiProvider } from "./registry/bai/index.ts";
-import { qiniuProvider } from "./registry/qiniu/index.ts";
import { kimi_coding_apikeyProvider } from "./registry/kimi/coding-apikey/index.ts";
import { kimi_codingProvider } from "./registry/kimi/coding/index.ts";
import { kimiProvider } from "./registry/kimi/index.ts";
@@ -51,9 +49,6 @@ import { groqProvider } from "./registry/groq/index.ts";
import { inference_netProvider } from "./registry/inference-net/index.ts";
import { llm7Provider } from "./registry/llm7/index.ts";
import { cerebrasProvider } from "./registry/cerebras/index.ts";
-import { charmHyperProvider } from "./registry/charm-hyper/index.ts";
-import { nubeProvider } from "./registry/nube/index.ts";
-import { clinepassProvider } from "./registry/clinepass/index.ts";
import { sparkdeskProvider } from "./registry/sparkdesk/index.ts";
import { nlpcloudProvider } from "./registry/nlpcloud/index.ts";
import { nvidiaProvider } from "./registry/nvidia/index.ts";
@@ -83,7 +78,6 @@ import { leonardoProvider } from "./registry/leonardo/index.ts";
import { grok_webProvider } from "./registry/grok-web/index.ts";
import { kieProvider } from "./registry/kie/index.ts";
import { monsterapiProvider } from "./registry/monsterapi/index.ts";
-import { modelscopeProvider } from "./registry/modelscope/index.ts";
import { sensenovaProvider } from "./registry/sensenova/index.ts";
import { hyperbolicProvider } from "./registry/hyperbolic/index.ts";
import { lambda_aiProvider } from "./registry/lambda-ai/index.ts";
@@ -147,7 +141,6 @@ import { kilo_gatewayProvider } from "./registry/kilo-gateway/index.ts";
import { bailian_coding_planProvider } from "./registry/bailian-coding-plan/index.ts";
import { gigachatProvider } from "./registry/gigachat/index.ts";
import { devin_cliProvider } from "./registry/devin-cli/index.ts";
-import { auggieProvider } from "./registry/auggie/index.ts";
import { chutesProvider } from "./registry/chutes/index.ts";
import { factoryProvider } from "./registry/factory/index.ts";
import { databricksProvider } from "./registry/databricks/index.ts";
@@ -178,8 +171,6 @@ import { grok_cliProvider } from "./registry/grok-cli/index.ts";
import { codebuddy_cnProvider } from "./registry/codebuddy-cn/index.ts";
import { pioneerProvider } from "./registry/pioneer/index.ts";
import { zenmux_freeProvider } from "./registry/zenmux-free/index.ts";
-import { sumopodProvider } from "./registry/sumopod/index.ts";
-import { x5labProvider } from "./registry/x5lab/index.ts";
export const REGISTRY: Record<string, RegistryEntry> = {
aimlapi: aimlapiProvider,
@@ -221,8 +212,6 @@ export const REGISTRY: Record<string, RegistryEntry> = {
deepseek: deepseekProvider,
"deepseek-web": deepseek_webProvider,
dgrid: dgridProvider,
- bai: baiProvider,
- qiniu: qiniuProvider,
"kimi-coding-apikey": kimi_coding_apikeyProvider,
"kimi-coding": kimi_codingProvider,
kimi: kimiProvider,
@@ -231,9 +220,6 @@ export const REGISTRY: Record<string, RegistryEntry> = {
"inference-net": inference_netProvider,
llm7: llm7Provider,
cerebras: cerebrasProvider,
- "charm-hyper": charmHyperProvider,
- nube: nubeProvider,
- clinepass: clinepassProvider,
sparkdesk: sparkdeskProvider,
nlpcloud: nlpcloudProvider,
nvidia: nvidiaProvider,
@@ -263,7 +249,6 @@ export const REGISTRY: Record<string, RegistryEntry> = {
"grok-web": grok_webProvider,
kie: kieProvider,
monsterapi: monsterapiProvider,
- modelscope: modelscopeProvider,
sensenova: sensenovaProvider,
hyperbolic: hyperbolicProvider,
"lambda-ai": lambda_aiProvider,
@@ -326,7 +311,6 @@ export const REGISTRY: Record<string, RegistryEntry> = {
"bailian-coding-plan": bailian_coding_planProvider,
gigachat: gigachatProvider,
"devin-cli": devin_cliProvider,
- auggie: auggieProvider,
chutes: chutesProvider,
factory: factoryProvider,
databricks: databricksProvider,
@@ -360,6 +344,4 @@ export const REGISTRY: Record<string, RegistryEntry> = {
"codebuddy-cn": codebuddy_cnProvider,
pioneer: pioneerProvider,
"zenmux-free": zenmux_freeProvider,
- sumopod: sumopodProvider,
- x5lab: x5labProvider,
};
diff --git a/open-sse/config/providers/registry/anthropic/index.ts b/open-sse/config/providers/registry/anthropic/index.ts
index 4ea19e8381..b990c8fb23 100644
--- a/open-sse/config/providers/registry/anthropic/index.ts
+++ b/open-sse/config/providers/registry/anthropic/index.ts
@@ -38,13 +38,6 @@ export const anthropicProvider: RegistryEntry = {
},
{ id: "claude-opus-4.6", name: "Claude Opus 4.6" },
{ id: "claude-opus-4.5", name: "Claude Opus 4.5" },
- {
- id: "claude-sonnet-5",
- name: "Claude Sonnet 5",
- contextLength: 1048576,
- // Sonnet 5 rejects non-default sampling params with a 400 (adaptive-only).
- unsupportedParams: ["temperature", "top_p", "top_k"],
- },
{ id: "claude-sonnet-4.6", name: "Claude Sonnet 4.6" },
{ id: "claude-sonnet-4.5", name: "Claude Sonnet 4.6" },
{ id: "claude-haiku-4.5", name: "Claude Haiku 4.5" },
diff --git a/open-sse/config/providers/registry/auggie/index.ts b/open-sse/config/providers/registry/auggie/index.ts
deleted file mode 100644
index ee346426a0..0000000000
--- a/open-sse/config/providers/registry/auggie/index.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-import type { RegistryEntry } from "../../shared.ts";
-
-// Augment / Auggie CLI — local no-auth provider. The executor spawns the
-// user's local `auggie` binary (auth handled entirely by `auggie login`);
-// OmniRoute never stores credentials for this connection.
-export const auggieProvider: RegistryEntry = {
- id: "auggie",
- alias: "aug",
- format: "openai",
- executor: "auggie",
- baseUrl: "auggie://cli/stdio",
- authType: "none",
- authHeader: "none",
- defaultContextLength: 200000,
- models: [
- // Claude
- { id: "claude-sonnet-4.6", name: "Claude Sonnet 4.6", contextLength: 200000 },
- {
- id: "claude-sonnet-4.6-thinking",
- name: "Claude Sonnet 4.6 Thinking",
- contextLength: 200000,
- },
- { id: "claude-opus-4.6", name: "Claude Opus 4.6", contextLength: 200000 },
- { id: "claude-haiku-4.5", name: "Claude Haiku 4.5", contextLength: 200000 },
- // Gemini
- { id: "gemini-3.1-pro", name: "Gemini 3.1 Pro", contextLength: 1000000 },
- { id: "gemini-3.0-flash", name: "Gemini 3 Flash", contextLength: 1000000 },
- // GPT-5.x
- { id: "gpt-5.5-high", name: "GPT-5.5 High", contextLength: 200000 },
- { id: "gpt-5.5-medium", name: "GPT-5.5 Medium", contextLength: 200000 },
- { id: "gpt-5.4-high", name: "GPT-5.4 High", contextLength: 200000 },
- { id: "gpt-5.4-medium", name: "GPT-5.4 Medium", contextLength: 200000 },
- // Kimi
- { id: "kimi-k2.6", name: "Kimi K2.6", contextLength: 131000 },
- // Prism (Augment's in-house model)
- { id: "prism", name: "Augment Prism", contextLength: 200000 },
- ],
-};
diff --git a/open-sse/config/providers/registry/bai/index.ts b/open-sse/config/providers/registry/bai/index.ts
deleted file mode 100644
index 574362693c..0000000000
--- a/open-sse/config/providers/registry/bai/index.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import type { RegistryEntry } from "../../shared.ts";
-
-export const baiProvider: RegistryEntry = {
- id: "bai",
- alias: "bai",
- format: "openai",
- executor: "default",
- baseUrl: "https://api.b.ai/v1/chat/completions",
- authType: "apikey",
- authHeader: "bearer",
- modelsUrl: "https://api.b.ai/v1/models",
- models: [],
- passthroughModels: true,
-};
diff --git a/open-sse/config/providers/registry/blackbox/index.ts b/open-sse/config/providers/registry/blackbox/index.ts
index 87d0ce26d7..e5fba3d9f8 100644
--- a/open-sse/config/providers/registry/blackbox/index.ts
+++ b/open-sse/config/providers/registry/blackbox/index.ts
@@ -12,7 +12,6 @@ export const blackboxProvider: RegistryEntry = {
models: [
{ id: "claude-fable-5", name: "Claude Fable 5" },
{ id: "claude-opus-4.8", name: "Claude Opus 4.8" },
- { id: "claude-sonnet-5", name: "Claude Sonnet 5" },
{ id: "claude-sonnet-4.6", name: "Claude Sonnet 4.6" },
{ id: "gpt-5.5", name: "GPT-5.5" },
{ id: "gpt-5.4-pro", name: "GPT-5.4 Pro" },
diff --git a/open-sse/config/providers/registry/charm-hyper/index.ts b/open-sse/config/providers/registry/charm-hyper/index.ts
deleted file mode 100644
index dfbf994891..0000000000
--- a/open-sse/config/providers/registry/charm-hyper/index.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import type { RegistryEntry } from "../../shared.ts";
-
-export const charmHyperProvider: RegistryEntry = {
- id: "charm-hyper",
- alias: "charm-hyper",
- format: "openai",
- executor: "default",
- baseUrl: "https://hyper.charm.land/v1/chat/completions",
- authType: "apikey",
- authHeader: "bearer",
- modelsUrl: "https://hyper.charm.land/v1/models",
- models: [{ id: "hyper/auto", name: "Charm Hyper Auto" }],
- passthroughModels: true,
-};
diff --git a/open-sse/config/providers/registry/claude/index.ts b/open-sse/config/providers/registry/claude/index.ts
index 19b2c5a509..e5e181a985 100644
--- a/open-sse/config/providers/registry/claude/index.ts
+++ b/open-sse/config/providers/registry/claude/index.ts
@@ -65,18 +65,6 @@ export const claudeProvider: RegistryEntry = {
contextLength: 200000,
maxOutputTokens: 64000,
},
- {
- id: "claude-sonnet-5",
- name: "Claude Sonnet 5",
- contextLength: 1000000,
- maxOutputTokens: 128000,
- // Sonnet 5 is the first Sonnet-tier model to support xhigh effort — do NOT copy
- // the `supportsXHighEffort: false` from the older claude-sonnet-4-6/4-5 entries.
- supportsXHighEffort: true,
- // Sonnet 5 rejects non-default temperature/top_p/top_k with a 400 (adaptive-only;
- // reasoning steered by output_config.effort). Mirrors the Opus/Fable entries.
- unsupportedParams: ["temperature", "top_p", "top_k"],
- },
{
id: "claude-sonnet-4-6",
name: "Claude 4.6 Sonnet",
diff --git a/open-sse/config/providers/registry/clinepass/index.ts b/open-sse/config/providers/registry/clinepass/index.ts
deleted file mode 100644
index 3ea7dbcb3a..0000000000
--- a/open-sse/config/providers/registry/clinepass/index.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import type { RegistryEntry } from "../../shared.ts";
-
-// ClinePass — Cline's $9.99/mo BYOK API-key gateway (https://cline.bot). Distinct
-// from the OAuth `cline` provider: same host (api.cline.bot) but a plain Bearer
-// API key and the `cline-pass/*` model namespace. Responses are wrapped in a
-// {success, data} envelope — unwrapped by open-sse/utils/clinepassEnvelope.ts.
-export const clinepassProvider: RegistryEntry = {
- id: "clinepass",
- alias: "clinepass",
- format: "openai",
- executor: "default",
- baseUrl: "https://api.cline.bot/api/v1/chat/completions",
- authType: "apikey",
- authHeader: "bearer",
- extraHeaders: {
- "HTTP-Referer": "https://cline.bot",
- "X-Title": "Cline",
- },
- models: [
- { id: "cline-pass/glm-5.2", name: "GLM-5.2 (ClinePass)" },
- { id: "cline-pass/kimi-k2.7-code", name: "Kimi K2.7 Code (ClinePass)" },
- { id: "cline-pass/kimi-k2.6", name: "Kimi K2.6 (ClinePass)" },
- {
- id: "cline-pass/deepseek-v4-pro",
- name: "DeepSeek V4 Pro (ClinePass)",
- supportsReasoning: true,
- maxOutputTokens: 50000,
- },
- {
- id: "cline-pass/deepseek-v4-flash",
- name: "DeepSeek V4 Flash (ClinePass)",
- supportsReasoning: true,
- maxOutputTokens: 50000,
- },
- { id: "cline-pass/mimo-v2.5", name: "MiMo-V2.5 (ClinePass)" },
- { id: "cline-pass/mimo-v2.5-pro", name: "MiMo-V2.5-Pro (ClinePass)" },
- { id: "cline-pass/minimax-m3", name: "MiniMax M3 (ClinePass)", supportsVision: true },
- { id: "cline-pass/qwen3.7-max", name: "Qwen3.7 Max (ClinePass)" },
- { id: "cline-pass/qwen3.7-plus", name: "Qwen3.7 Plus (ClinePass)" },
- ],
- passthroughModels: true,
-};
diff --git a/open-sse/config/providers/registry/grok-cli/index.ts b/open-sse/config/providers/registry/grok-cli/index.ts
index 463e103ba6..af6e11153c 100644
--- a/open-sse/config/providers/registry/grok-cli/index.ts
+++ b/open-sse/config/providers/registry/grok-cli/index.ts
@@ -14,13 +14,13 @@ export const grok_cliProvider: RegistryEntry = {
{
id: "grok-build",
name: "Grok Build",
- contextLength: 256000,
+ contextLength: 128000,
unsupportedParams: ["presencePenalty", "frequencyPenalty", "logprobs", "topLogprobs"],
},
{
id: "grok-composer-2.5-fast",
name: "Grok Composer 2.5 Fast",
- contextLength: 200000,
+ contextLength: 128000,
unsupportedParams: ["presencePenalty", "frequencyPenalty", "logprobs", "topLogprobs"],
},
],
diff --git a/open-sse/config/providers/registry/kimi/web/index.ts b/open-sse/config/providers/registry/kimi/web/index.ts
index 1bcd615615..c86d3ce426 100644
--- a/open-sse/config/providers/registry/kimi/web/index.ts
+++ b/open-sse/config/providers/registry/kimi/web/index.ts
@@ -14,14 +14,8 @@ export const kimi_webProvider: RegistryEntry = {
authType: "apikey",
authHeader: "cookie",
models: [
- // Model ids are the `key` field from www.kimi.com's
- // `/apiv2/kimi.gateway.config.v1.ConfigService/GetAvailableModels` response.
- // Agent / Agent-Swarm variants (`k2d6-agent`, `k2d6-agent-ultra`) are
- // intentionally NOT exposed — they need a different scenario
- // (`SCENARIO_OK_COMPUTER`) plus `kimiPlusId` / `agentMode` fields, which
- // the executor does not yet shape. Use `kimi-coding` (api.kimi.com) for
- // agentic flows.
- { id: "k2d6", name: "K2.6 Instant" },
- { id: "k2d6-thinking", name: "K2.6 Thinking", supportsReasoning: true },
+ { id: "kimi-default", name: "Kimi Default" },
+ { id: "kimi-k2.6", name: "Kimi K2.6 (Thinking)" },
+ { id: "kimi-128k", name: "Kimi 128K (Long Context)" },
],
};
diff --git a/open-sse/config/providers/registry/modelscope/index.ts b/open-sse/config/providers/registry/modelscope/index.ts
deleted file mode 100644
index f82b7cbe72..0000000000
--- a/open-sse/config/providers/registry/modelscope/index.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import type { RegistryEntry } from "../../shared.ts";
-
-// ModelScope (Alibaba 魔搭) — OpenAI-compatible API-Inference, ported from upstream
-// 9router PR #1764 (@tn5052). The upstream PR hardcoded `https://api-inference.modelscope.ai/...`
-// (`.ai` TLD) and a static 5-model list. Both were dropped here after verification:
-//
-// - baseUrl: ModelScope's own API-Inference docs (modelscope.cn/docs/model-service/API-Inference)
-// and third-party integration guides (e.g. Alibaba Cloud Model Studio compatibility docs)
-// consistently confirm the production domain is `api-inference.modelscope.cn` — the `.cn` TLD,
-// not `.ai`. Using the unverified `.ai` domain would have shipped a broken provider.
-// - models: passthrough + empty static seed instead of copying the PR's 5-model snapshot, since
-// ModelScope hosts a large and fast-moving open-model catalog — `modelsUrl` keeps the list live.
-export const modelscopeProvider: RegistryEntry = {
- id: "modelscope",
- alias: "ms",
- format: "openai",
- executor: "default",
- baseUrl: "https://api-inference.modelscope.cn/v1/chat/completions",
- modelsUrl: "https://api-inference.modelscope.cn/v1/models",
- authType: "apikey",
- authHeader: "bearer",
- passthroughModels: true,
- models: [],
-};
diff --git a/open-sse/config/providers/registry/nube/index.ts b/open-sse/config/providers/registry/nube/index.ts
deleted file mode 100644
index f0e25b56b9..0000000000
--- a/open-sse/config/providers/registry/nube/index.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import type { RegistryEntry } from "../../shared.ts";
-
-export const nubeProvider: RegistryEntry = {
- id: "nube",
- alias: "nube",
- format: "openai",
- executor: "default",
- baseUrl: "https://ai.nube.sh/api/v1/chat/completions",
- modelsUrl: "https://ai.nube.sh/api/v1/models",
- authType: "apikey",
- authHeader: "bearer",
- // Nube.sh is an OpenAI-compatible LiteLLM gateway (BYOK). Its live catalog is only
- // reachable with a valid key (/api/v1/models returns 401 unauthenticated), so we ship
- // no hardcoded model IDs and rely on passthrough + live enumeration via modelsUrl.
- passthroughModels: true,
- models: [],
-};
diff --git a/open-sse/config/providers/registry/qiniu/index.ts b/open-sse/config/providers/registry/qiniu/index.ts
deleted file mode 100644
index 1bbf5021d8..0000000000
--- a/open-sse/config/providers/registry/qiniu/index.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import type { RegistryEntry } from "../../shared.ts";
-
-export const qiniuProvider: RegistryEntry = {
- id: "qiniu",
- alias: "qiniu",
- format: "openai",
- executor: "default",
- baseUrl: "https://api.qnaigc.com/v1/chat/completions",
- authType: "apikey",
- authHeader: "bearer",
- modelsUrl: "https://api.qnaigc.com/v1/models",
- defaultContextLength: 128000,
- models: [],
- passthroughModels: true,
-};
diff --git a/open-sse/config/providers/registry/qoder/index.ts b/open-sse/config/providers/registry/qoder/index.ts
index 844cf5a945..e0b5721848 100644
--- a/open-sse/config/providers/registry/qoder/index.ts
+++ b/open-sse/config/providers/registry/qoder/index.ts
@@ -18,8 +18,6 @@ export const qoderProvider: RegistryEntry = {
},
models: [
{ id: "qoder-rome-30ba3b", name: "Qoder ROME" },
- { id: "glm-5.2", name: "GLM-5.2" },
- { id: "minimax-m3", name: "MiniMax M3", supportsVision: true },
{ id: "qwen3-coder-plus", name: "Qwen3 Coder Plus" },
{ id: "qwen3-max", name: "Qwen3 Max" },
{ id: "qwen3-vl-plus", name: "Qwen3 Vision Plus", supportsVision: true },
diff --git a/open-sse/config/providers/registry/sumopod/index.ts b/open-sse/config/providers/registry/sumopod/index.ts
deleted file mode 100644
index 1a5414e879..0000000000
--- a/open-sse/config/providers/registry/sumopod/index.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import type { RegistryEntry } from "../../shared.ts";
-
-export const sumopodProvider: RegistryEntry = {
- id: "sumopod",
- alias: "sumopod",
- format: "openai",
- executor: "default",
- baseUrl: "https://ai.sumopod.com/v1/chat/completions",
- authType: "apikey",
- authHeader: "bearer",
- modelsUrl: "https://ai.sumopod.com/v1/models",
- defaultContextLength: 128000,
- models: [],
- passthroughModels: true,
-};
diff --git a/open-sse/config/providers/registry/theoldllm/index.ts b/open-sse/config/providers/registry/theoldllm/index.ts
index a22d9901ae..1b1c7691cb 100644
--- a/open-sse/config/providers/registry/theoldllm/index.ts
+++ b/open-sse/config/providers/registry/theoldllm/index.ts
@@ -11,41 +11,15 @@ export const theoldllmProvider: RegistryEntry = {
authType: "none",
authHeader: "none",
defaultContextLength: 200000,
- // Catalog seed. `passthroughModels: true` means live /api/chatgpt discovery is
- // authoritative; this list is the curated display/fallback set. The upstream IDs
- // (GPT_5_*, gemini_*, CLAUDE_4_*, openrouter_*, etc.) mirror the site's free
- // "chatgpt" tier and MUST match `CHATGPT_UPSTREAM_MODELS` in the executor so they
- // route unchanged. Legacy alias IDs (GPT_4o, claude_opus_4, …) are kept for
- // backward compatibility with saved model preferences (mapped in the executor).
models: [
- // ── Current free tier (refreshed for #5181) ──
{ id: "GPT_5_4", name: "GPT-5.4 (The Old LLM 🆓)", contextLength: 400000 },
- { id: "GPT_5_3", name: "GPT-5.3 (The Old LLM 🆓)", contextLength: 400000 },
- { id: "GPT_5_2", name: "GPT-5.2 (The Old LLM 🆓)", contextLength: 400000 },
- { id: "GPT_5_1", name: "GPT-5.1 (The Old LLM 🆓)", contextLength: 400000 },
- { id: "GPT_5", name: "GPT-5 (The Old LLM 🆓)", contextLength: 400000 },
- { id: "GPT_o4_mini", name: "o4-mini (The Old LLM 🆓)" },
- { id: "GPT_o3_mini", name: "o3-mini (The Old LLM 🆓)" },
- { id: "gemini_3_pro", name: "Gemini 3 Pro (The Old LLM 🆓)", contextLength: 1000000 },
- { id: "gemini_2_5_pro", name: "Gemini 2.5 Pro (The Old LLM 🆓)", contextLength: 1000000 },
- { id: "gemini_2_0_flash", name: "Gemini 2.0 Flash (The Old LLM 🆓)", contextLength: 1000000 },
- { id: "gemini_1_5_flash", name: "Gemini 1.5 Flash (The Old LLM 🆓)", contextLength: 1000000 },
- { id: "CLAUDE_4_6_OPUS", name: "Claude 4.6 Opus (The Old LLM 🆓)", contextLength: 200000 },
- { id: "CLAUDE_4_6_SONNET", name: "Claude 4.6 Sonnet (The Old LLM 🆓)", contextLength: 200000 },
- { id: "CLAUDE_4_5_HAIKU", name: "Claude 4.5 Haiku (The Old LLM 🆓)", contextLength: 200000 },
- { id: "openrouter_gpt_4_o", name: "GPT-4o (The Old LLM 🆓)" },
- { id: "openrouter_gpt_4_o_mini", name: "GPT-4o mini (The Old LLM 🆓)" },
- { id: "openrouter_grok_4", name: "Grok 4 (The Old LLM 🆓)" },
- { id: "together_deepseek_v3", name: "DeepSeek V3 (The Old LLM 🆓)" },
- { id: "openrouter_deepseek_r1", name: "DeepSeek R1 (The Old LLM 🆓)" },
- { id: "sonar-pro", name: "Sonar Pro (The Old LLM 🆓)" },
- // ── Legacy alias IDs (kept for saved-preference backward compatibility) ──
{ id: "GPT_4o", name: "GPT-4o (The Old LLM 🆓)" },
{ id: "claude_opus_4", name: "Claude Opus 4 (The Old LLM 🆓)", contextLength: 200000 },
{ id: "claude_sonnet_4", name: "Claude Sonnet 4 (The Old LLM 🆓)", contextLength: 200000 },
{ id: "claude_haiku_3_5", name: "Claude Haiku 3.5 (The Old LLM 🆓)", contextLength: 200000 },
{ id: "deepseek_v4", name: "DeepSeek V4 (The Old LLM 🆓)", contextLength: 200000 },
{ id: "gemini_3_flash", name: "Gemini 3 Flash (The Old LLM 🆓)", contextLength: 1000000 },
+ { id: "gemini_3_pro", name: "Gemini 3 Pro (The Old LLM 🆓)", contextLength: 1000000 },
],
passthroughModels: true,
};
diff --git a/open-sse/config/providers/registry/x5lab/index.ts b/open-sse/config/providers/registry/x5lab/index.ts
deleted file mode 100644
index ac5112a3a1..0000000000
--- a/open-sse/config/providers/registry/x5lab/index.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import type { RegistryEntry } from "../../shared.ts";
-
-export const x5labProvider: RegistryEntry = {
- id: "x5lab",
- alias: "x5lab",
- format: "openai",
- executor: "default",
- baseUrl: "https://api.x5lab.dev/v1/chat/completions",
- authType: "apikey",
- authHeader: "bearer",
- modelsUrl: "https://api.x5lab.dev/v1/models",
- defaultContextLength: 128000,
- models: [],
- passthroughModels: true,
-};
diff --git a/open-sse/config/providers/registry/xai/index.ts b/open-sse/config/providers/registry/xai/index.ts
index 501fa4fcbf..82d6314a5c 100644
--- a/open-sse/config/providers/registry/xai/index.ts
+++ b/open-sse/config/providers/registry/xai/index.ts
@@ -4,7 +4,7 @@ export const xaiProvider: RegistryEntry = {
id: "xai",
alias: "xai",
format: "openai",
- executor: "xai",
+ executor: "default",
baseUrl: "https://api.x.ai/v1/chat/completions",
authType: "apikey",
authHeader: "bearer",
diff --git a/open-sse/executors/antigravity.ts b/open-sse/executors/antigravity.ts
index a66f58df06..74393938ed 100644
--- a/open-sse/executors/antigravity.ts
+++ b/open-sse/executors/antigravity.ts
@@ -46,13 +46,7 @@ import {
} from "../services/cloudCodeThinking.ts";
import { buildGeminiTools } from "../translator/helpers/geminiToolsSanitizer.ts";
import { DEFAULT_SAFETY_SETTINGS } from "../translator/helpers/geminiHelper.ts";
-import {
- type AntigravityCollectedStream,
- processAntigravitySSEText,
- flushAntigravitySSEText,
-} from "./antigravity/sseCollect.ts";
-// processAntigravitySSEPayload re-exported for external importers (tests).
-export { processAntigravitySSEPayload } from "./antigravity/sseCollect.ts";
+import { normalizeOpenAICompatibleFinishReasonString } from "../utils/finishReason.ts";
import {
applyAntigravityClientProfileHeaders,
removeHeaderCaseInsensitive,
@@ -161,6 +155,70 @@ function serializeAntigravityRequest(
return applyFingerprint(provider, { ...headers }, serializedBody);
}
+type AntigravityCollectedStream = {
+ textContent: string;
+ finishReason: string;
+ toolCalls: Array<{
+ id: string;
+ index: number;
+ type: "function";
+ function: { name: string; arguments: string };
+ }>;
+ usage: Record<string, unknown> | null;
+ remainingCredits: Array<{ creditType: string; creditAmount: string }> | null;
+};
+
+function stripZeroWidth(value: unknown): unknown {
+ if (typeof value === "string") {
+ return value.replace(/[\u200B-\u200D\uFEFF]/g, "");
+ }
+ if (Array.isArray(value)) {
+ return value.map((item) => stripZeroWidth(item));
+ }
+ if (value && typeof value === "object") {
+ return Object.fromEntries(
+ Object.entries(value as Record<string, unknown>).map(([key, item]) => [
+ key,
+ stripZeroWidth(item),
+ ])
+ );
+ }
+ return value;
+}
+
+function parseAntigravityTextualToolCall(text: unknown): { name: string; args: unknown } | null {
+ if (typeof text !== "string") return null;
+ const normalized = text.replace(/[\u200B-\u200D\uFEFF]/g, "");
+ const match = normalized.match(
+ /^[\s\S]*?\[Tool call:\s*([^\]\n]+)\]\s*\nArguments:\s*([\s\S]+?)\s*$/
+ );
+ if (!match) return null;
+ const name = match[1]?.trim();
+ const rawArgs = match[2]?.trim();
+ if (!name || !rawArgs) return null;
+ try {
+ return { name, args: stripZeroWidth(JSON.parse(rawArgs)) };
+ } catch {
+ return null;
+ }
+}
+
+function addAntigravityTextualToolCall(
+ collected: AntigravityCollectedStream,
+ parsed: { name: string; args: unknown }
+): void {
+ collected.toolCalls.push({
+ id: `${parsed.name}-${Date.now()}-${collected.toolCalls.length}`,
+ index: collected.toolCalls.length,
+ type: "function",
+ function: {
+ name: parsed.name,
+ arguments: JSON.stringify(parsed.args || {}),
+ },
+ });
+ collected.finishReason = "tool_calls";
+}
+
type AntigravityRequestEnvelope = Record<string, unknown> & {
project: string;
model?: string;
@@ -314,6 +372,84 @@ export function markConnectionQuotaExhausted(connectionId: string, retryAfterMs:
* Accumulate one Antigravity SSE `data:` payload into `collected`. Exported for unit
* tests (the markdown / candidate-parts extraction branches). @internal
*/
+export function processAntigravitySSEPayload(
+ payload: string,
+ collected: AntigravityCollectedStream,
+ log?: { debug?: (scope: string, message: string) => void }
+) {
+ if (!payload || payload === "[DONE]") return;
+ try {
+ const parsed = JSON.parse(payload);
+ const markdown =
+ typeof parsed?.markdown === "string"
+ ? parsed.markdown
+ : typeof parsed?.response?.markdown === "string"
+ ? parsed.response.markdown
+ : null;
+ if (markdown) {
+ collected.textContent += markdown;
+ }
+ const candidate = parsed?.response?.candidates?.[0];
+ if (candidate?.content?.parts) {
+ for (const part of candidate.content.parts) {
+ if (typeof part.text === "string" && !part.thought && !part.thoughtSignature) {
+ const textualToolCall = parseAntigravityTextualToolCall(part.text);
+ if (textualToolCall) {
+ addAntigravityTextualToolCall(collected, textualToolCall);
+ } else {
+ collected.textContent += part.text;
+ }
+ }
+ }
+ }
+ if (candidate?.finishReason) {
+ collected.finishReason = normalizeOpenAICompatibleFinishReasonString(
+ String(candidate.finishReason).toLowerCase()
+ );
+ }
+ if (parsed?.response?.usageMetadata) {
+ const um = parsed.response.usageMetadata;
+ collected.usage = {
+ prompt_tokens: um.promptTokenCount || 0,
+ completion_tokens: um.candidatesTokenCount || 0,
+ total_tokens: um.totalTokenCount || 0,
+ };
+ }
+ if (Array.isArray(parsed?.remainingCredits)) {
+ collected.remainingCredits = parsed.remainingCredits;
+ }
+ } catch {
+ log?.debug?.("SSE_PARSE", `Skipping malformed SSE line: ${payload.slice(0, 80)}`);
+ }
+}
+
+function processAntigravitySSEText(
+ text: string,
+ partialLine: { value: string },
+ collected: AntigravityCollectedStream,
+ log?: { debug?: (scope: string, message: string) => void }
+) {
+ partialLine.value += text;
+ const lines = partialLine.value.split("\n");
+ partialLine.value = lines.pop() || "";
+
+ for (const line of lines) {
+ const trimmed = line.trim();
+ if (!trimmed.startsWith("data:")) continue;
+ processAntigravitySSEPayload(trimmed.slice(5).trim(), collected, log);
+ }
+}
+
+function flushAntigravitySSEText(
+ partialLine: { value: string },
+ collected: AntigravityCollectedStream,
+ log?: { debug?: (scope: string, message: string) => void }
+) {
+ const trimmed = partialLine.value.trim();
+ partialLine.value = "";
+ if (!trimmed.startsWith("data:")) return;
+ processAntigravitySSEPayload(trimmed.slice(5).trim(), collected, log);
+}
/**
* Strip provider prefixes (e.g. "antigravity/model" → "model").
diff --git a/open-sse/executors/antigravity/sseCollect.ts b/open-sse/executors/antigravity/sseCollect.ts
deleted file mode 100644
index d42bab72e9..0000000000
--- a/open-sse/executors/antigravity/sseCollect.ts
+++ /dev/null
@@ -1,148 +0,0 @@
-// Pure SSE-payload -> collected-stream parsing for the Antigravity executor.
-// Extracted verbatim from antigravity.ts (no host state, no fetch/auth).
-import { normalizeOpenAICompatibleFinishReasonString } from "../../utils/finishReason.ts";
-
-export type AntigravityCollectedStream = {
- textContent: string;
- finishReason: string;
- toolCalls: Array<{
- id: string;
- index: number;
- type: "function";
- function: { name: string; arguments: string };
- }>;
- usage: Record<string, unknown> | null;
- remainingCredits: Array<{ creditType: string; creditAmount: string }> | null;
-};
-
-export function stripZeroWidth(value: unknown): unknown {
- if (typeof value === "string") {
- return value.replace(/[\u200B-\u200D\uFEFF]/g, "");
- }
- if (Array.isArray(value)) {
- return value.map((item) => stripZeroWidth(item));
- }
- if (value && typeof value === "object") {
- return Object.fromEntries(
- Object.entries(value as Record<string, unknown>).map(([key, item]) => [
- key,
- stripZeroWidth(item),
- ])
- );
- }
- return value;
-}
-
-export function parseAntigravityTextualToolCall(
- text: unknown
-): { name: string; args: unknown } | null {
- if (typeof text !== "string") return null;
- const normalized = text.replace(/[\u200B-\u200D\uFEFF]/g, "");
- const match = normalized.match(
- /^[\s\S]*?\[Tool call:\s*([^\]\n]+)\]\s*\nArguments:\s*([\s\S]+?)\s*$/
- );
- if (!match) return null;
- const name = match[1]?.trim();
- const rawArgs = match[2]?.trim();
- if (!name || !rawArgs) return null;
- try {
- return { name, args: stripZeroWidth(JSON.parse(rawArgs)) };
- } catch {
- return null;
- }
-}
-
-export function addAntigravityTextualToolCall(
- collected: AntigravityCollectedStream,
- parsed: { name: string; args: unknown }
-): void {
- collected.toolCalls.push({
- id: `${parsed.name}-${Date.now()}-${collected.toolCalls.length}`,
- index: collected.toolCalls.length,
- type: "function",
- function: {
- name: parsed.name,
- arguments: JSON.stringify(parsed.args || {}),
- },
- });
- collected.finishReason = "tool_calls";
-}
-
-export function processAntigravitySSEPayload(
- payload: string,
- collected: AntigravityCollectedStream,
- log?: { debug?: (scope: string, message: string) => void }
-) {
- if (!payload || payload === "[DONE]") return;
- try {
- const parsed = JSON.parse(payload);
- const markdown =
- typeof parsed?.markdown === "string"
- ? parsed.markdown
- : typeof parsed?.response?.markdown === "string"
- ? parsed.response.markdown
- : null;
- if (markdown) {
- collected.textContent += markdown;
- }
- const candidate = parsed?.response?.candidates?.[0];
- if (candidate?.content?.parts) {
- for (const part of candidate.content.parts) {
- if (typeof part.text === "string" && !part.thought && !part.thoughtSignature) {
- const textualToolCall = parseAntigravityTextualToolCall(part.text);
- if (textualToolCall) {
- addAntigravityTextualToolCall(collected, textualToolCall);
- } else {
- collected.textContent += part.text;
- }
- }
- }
- }
- if (candidate?.finishReason) {
- collected.finishReason = normalizeOpenAICompatibleFinishReasonString(
- String(candidate.finishReason).toLowerCase()
- );
- }
- if (parsed?.response?.usageMetadata) {
- const um = parsed.response.usageMetadata;
- collected.usage = {
- prompt_tokens: um.promptTokenCount || 0,
- completion_tokens: um.candidatesTokenCount || 0,
- total_tokens: um.totalTokenCount || 0,
- };
- }
- if (Array.isArray(parsed?.remainingCredits)) {
- collected.remainingCredits = parsed.remainingCredits;
- }
- } catch {
- log?.debug?.("SSE_PARSE", `Skipping malformed SSE line: ${payload.slice(0, 80)}`);
- }
-}
-
-export function processAntigravitySSEText(
- text: string,
- partialLine: { value: string },
- collected: AntigravityCollectedStream,
- log?: { debug?: (scope: string, message: string) => void }
-) {
- partialLine.value += text;
- const lines = partialLine.value.split("\n");
- partialLine.value = lines.pop() || "";
-
- for (const line of lines) {
- const trimmed = line.trim();
- if (!trimmed.startsWith("data:")) continue;
- processAntigravitySSEPayload(trimmed.slice(5).trim(), collected, log);
- }
-}
-
-export function flushAntigravitySSEText(
- partialLine: { value: string },
- collected: AntigravityCollectedStream,
- log?: { debug?: (scope: string, message: string) => void }
-) {
- const trimmed = partialLine.value.trim();
- partialLine.value = "";
- if (!trimmed.startsWith("data:")) return;
- processAntigravitySSEPayload(trimmed.slice(5).trim(), collected, log);
-}
diff --git a/open-sse/executors/auggie.ts b/open-sse/executors/auggie.ts
deleted file mode 100644
index f15d82c7e3..0000000000
--- a/open-sse/executors/auggie.ts
+++ /dev/null
@@ -1,569 +0,0 @@
-/**
- * AuggieExecutor — routes completions through the local Augment CLI ("auggie")
- * binary via a one-shot stdin/stdout text pipe (no JSON-RPC / ACP protocol).
- *
- * Flow:
- * 1. Flatten the OpenAI-shaped `messages[]` into a single prompt string.
- * 2. Spawn `auggie --print --quiet --model <model>` and pipe the prompt on stdin.
- * 3. Relay stdout chunks as OpenAI-compatible SSE deltas (stream=true) or
- * buffer them into a single chat.completion JSON body (stream=false).
- * 4. Kill the subprocess on abort / stream close.
- *
- * Authentication:
- * None. Auggie delegates auth entirely to the user's local `auggie login`
- * session — OmniRoute never sees or stores credentials for this provider.
- * The connection is registered `noAuth: true` and `refreshCredentials()` is
- * a no-op (nothing to refresh).
- *
- * Binary discovery:
- * 1. AUGGIE_BIN / CLI_AUGGIE_BIN env var (absolute path override)
- * 2. PATH lookup ("auggie" / "auggie.cmd")
- * 3. %LOCALAPPDATA%\auggie\bin\auggie.exe (Windows installer)
- * 4. ~/.local/share/auggie/bin/auggie (Linux installer)
- * 5. ~/.auggie/bin/auggie (alternate installer layout)
- */
-
-import { spawn } from "node:child_process";
-import path from "node:path";
-import os from "node:os";
-import fs from "node:fs";
-import { BaseExecutor, type ExecuteInput, type ProviderCredentials } from "./base.ts";
-import { buildErrorBody, errorResponse, sanitizeErrorMessage } from "../utils/error.ts";
-import { auggieProvider } from "../config/providers/registry/auggie/index.ts";
-
-const AUGGIE_URL = "auggie://cli/stdio";
-
-// ─── Model allowlist (argument-injection defense) ─────────────────────────────
-// The `model` value is forwarded straight into the `auggie` argv, so it is an
-// untrusted-input sink. We only ever pass a model that is declared in the
-// registry entry — this closes flag-smuggling (a `model` starting with "-" would
-// otherwise be parsed by auggie as an option) and unknown-model passthrough.
-const AUGGIE_MODEL_ALLOWLIST: ReadonlySet<string> = new Set(
- auggieProvider.models.map((m) => m.id)
-);
-const DEFAULT_AUGGIE_MODEL = auggieProvider.models[0]?.id ?? "claude-sonnet-4.6";
-
-type AuggieModelResolution = { ok: true; model: string } | { ok: false; error: string };
-
-/**
- * Validate + resolve the requested model against the registry allowlist.
- * Rejects flag-smuggling (leading "-") and any id not declared in the registry.
- * An empty/absent model resolves to the registry's first (default) model.
- */
-export function resolveAuggieModel(model: unknown): AuggieModelResolution {
- const requested = typeof model === "string" ? model.trim() : "";
- if (!requested) return { ok: true, model: DEFAULT_AUGGIE_MODEL };
- if (requested.startsWith("-")) {
- return {
- ok: false,
- error: `Invalid Auggie model "${requested}": model must not start with "-".`,
- };
- }
- if (!AUGGIE_MODEL_ALLOWLIST.has(requested)) {
- return {
- ok: false,
- error: `Unknown Auggie model "${requested}". Supported models: ${[
- ...AUGGIE_MODEL_ALLOWLIST,
- ].join(", ")}.`,
- };
- }
- return { ok: true, model: requested };
-}
-
-/**
- * Build the auggie argv. `model` MUST already be allowlist-validated via
- * resolveAuggieModel(). The trailing `--` marks the end of options so no
- * later positional value can be reinterpreted as a flag.
- */
-function buildAuggieArgs(model: string): string[] {
- return ["--print", "--quiet", "--model", model, "--"];
-}
-
-// ─── Binary discovery ────────────────────────────────────────────────────────
-
-export function resolveAuggieBin(): string {
- // 1. Explicit override
- const envBin = (process.env.AUGGIE_BIN || process.env.CLI_AUGGIE_BIN || "").trim();
- if (envBin) return envBin;
-
- const isWin = process.platform === "win32";
-
- // 2. Windows installer default: %LOCALAPPDATA%\auggie\bin\auggie.exe
- if (isWin) {
- const localAppData = process.env.LOCALAPPDATA || path.join(os.homedir(), "AppData", "Local");
- const winPath = path.join(localAppData, "auggie", "bin", "auggie.exe");
- if (fs.existsSync(winPath)) return winPath;
- }
-
- // 3. Linux/macOS installer paths
- const home = os.homedir();
- for (const candidate of [
- path.join(home, ".local", "share", "auggie", "bin", "auggie"),
- path.join(home, ".auggie", "bin", "auggie"),
- ]) {
- if (fs.existsSync(candidate)) return candidate;
- }
-
- // Fallback — rely on PATH
- return isWin ? "auggie.cmd" : "auggie";
-}
-
-// ─── Multi-turn message → single prompt builder ───────────────────────────────
-
-type OpenAIMsg = { role?: string; content?: unknown };
-
-export function buildAuggiePrompt(messages: OpenAIMsg[]): string {
- const lines: string[] = [];
- for (const m of messages) {
- const role = String(m.role || "user");
- let text = "";
- if (typeof m.content === "string") {
- text = m.content;
- } else if (Array.isArray(m.content)) {
- for (const p of m.content) {
- if (p && typeof p === "object" && (p as Record<string, unknown>).type === "text") {
- text += String((p as Record<string, unknown>).text || "");
- }
- }
- }
- if (!text.trim()) continue;
- if (role === "system") {
- lines.push(`[System]\n${text}`);
- } else if (role === "assistant") {
- lines.push(`[Assistant]\n${text}`);
- } else {
- lines.push(`[User]\n${text}`);
- }
- }
- return lines.join("\n\n") || "(empty)";
-}
-
-function isEnoentLike(message: string): boolean {
- return message.includes("ENOENT") || message.includes("not found");
-}
-
-export type AuggieCliVersionCheck = { ok: boolean; version?: string; error?: string };
-
-/**
- * Spawn `auggie --version` to confirm the local CLI is installed and runnable.
- * Used by the provider "Test Connection" flow — auggie has no API key, so this
- * is the only real signal we can give the operator before their first chat call.
- */
-export function checkAuggieCliVersion(timeoutMs = 5000): Promise<AuggieCliVersionCheck> {
- const bin = resolveAuggieBin();
- return new Promise((resolve) => {
- let settled = false;
- const settle = (result: AuggieCliVersionCheck) => {
- if (settled) return;
- settled = true;
- resolve(result);
- };
-
- let child: ReturnType<typeof spawn>;
- try {
- // No `shell` option — fixed argv, no cmd.exe interpretation.
- child = spawn(bin, ["--version"], {
- env: process.env,
- stdio: ["ignore", "pipe", "pipe"],
- });
- } catch (err) {
- const message = err instanceof Error ? err.message : String(err);
- settle({ ok: false, error: isEnoentLike(message) ? cliNotFoundMessage(bin) : message });
- return;
- }
-
- const timer = setTimeout(() => {
- if (!child.killed) child.kill("SIGKILL");
- settle({ ok: false, error: "Auggie CLI version check timed out" });
- }, timeoutMs);
-
- let stdout = "";
- child.stdout?.on("data", (chunk: Buffer) => {
- stdout += chunk.toString("utf8");
- });
- child.on("error", (err: NodeJS.ErrnoException) => {
- clearTimeout(timer);
- const message = err?.message || String(err);
- settle({ ok: false, error: isEnoentLike(message) ? cliNotFoundMessage(bin) : message });
- });
- child.on("close", (code) => {
- clearTimeout(timer);
- if (code === 0 && stdout.trim()) {
- settle({ ok: true, version: stdout.trim().slice(0, 200) });
- } else {
- settle({ ok: false, error: `Auggie CLI exited with code ${code}` });
- }
- });
- });
-}
-
-function cliNotFoundMessage(bin: string): string {
- return sanitizeErrorMessage(
- `Auggie CLI not found: ${bin}. Install it and run "auggie login", or set AUGGIE_BIN to an absolute path.`
- );
-}
-
-// ─── AuggieExecutor ─────────────────────────────────────────────────────────
-
-export class AuggieExecutor extends BaseExecutor {
- constructor() {
- super("auggie", { id: "auggie", baseUrl: "" });
- }
-
- buildUrl(): string {
- return AUGGIE_URL;
- }
-
- buildHeaders(): Record<string, string> {
- return {};
- }
-
- transformRequest(): unknown {
- return null;
- }
-
- /** No-op — auggie has no OmniRoute-managed credentials to refresh. */
- async refreshCredentials(
- _credentials: ProviderCredentials
- ): Promise<Partial<ProviderCredentials> | null> {
- return null;
- }
-
- async execute({
- model,
- body,
- stream,
- signal,
- log,
- }: ExecuteInput): Promise<{
- response: Response;
- url: string;
- headers: Record<string, string>;
- transformedBody: unknown;
- }> {
- const b = (body ?? {}) as Record<string, unknown>;
- const messages: OpenAIMsg[] = Array.isArray(b.messages) ? (b.messages as OpenAIMsg[]) : [];
- const promptText = buildAuggiePrompt(messages);
- const auggieBin = resolveAuggieBin();
- const wantsStream = stream !== false;
-
- // Argument-injection defense: never forward an unvalidated model into the argv.
- const modelResolution = resolveAuggieModel(model);
- if (!modelResolution.ok) {
- const response = wantsStream
- ? buildAuggieSseError(modelResolution.error)
- : errorResponse(400, modelResolution.error);
- return { response, url: AUGGIE_URL, headers: {}, transformedBody: { error: true } };
- }
- const safeModel = modelResolution.model;
-
- log?.info?.(
- "AUGGIE",
- `auggie --print → model=${safeModel}, bin=${auggieBin}, stream=${wantsStream}`
- );
-
- const response = wantsStream
- ? this.runStreaming(auggieBin, safeModel, promptText, signal, log)
- : await this.runNonStreaming(auggieBin, safeModel, promptText, signal, log);
-
- return {
- response,
- url: AUGGIE_URL,
- headers: {},
- transformedBody: { model: safeModel, promptLength: promptText.length },
- };
- }
-
- private spawnAuggie(auggieBin: string, model: string, promptText: string) {
- // No `shell` option: argv is passed directly to the OS loader, so no cmd.exe
- // metacharacter interpretation is possible even on Windows. `model` is already
- // allowlist-validated by resolveAuggieModel() before reaching here.
- const child = spawn(auggieBin, buildAuggieArgs(model), {
- env: process.env,
- stdio: ["pipe", "pipe", "pipe"],
- });
- try {
- child.stdin.write(promptText);
- child.stdin.end();
- } catch {
- /* ignore write errors — 'error'/'close' handlers surface the failure */
- }
- return child;
- }
-
- private runStreaming(
- auggieBin: string,
- model: string,
- promptText: string,
- signal: AbortSignal | null | undefined,
- log: ExecuteInput["log"]
- ): Response {
- const responseId = `chatcmpl-auggie-${Date.now()}`;
- const created = Math.floor(Date.now() / 1000);
-
- const sseStream = new ReadableStream<Uint8Array>({
- start(controller) {
- const enc = new TextEncoder();
- const emit = (data: string) => controller.enqueue(enc.encode(data));
- let closed = false;
- let roleEmitted = false;
- let finished = false;
-
- const finish = () => {
- if (finished) return;
- finished = true;
- if (!closed) {
- closed = true;
- try {
- controller.close();
- } catch {
- /* already closed */
- }
- }
- };
-
- const emitDelta = (delta: string) => {
- if (!delta) return;
- if (!roleEmitted) {
- emit(
- `data: ${JSON.stringify({
- id: responseId,
- object: "chat.completion.chunk",
- created,
- model,
- choices: [
- { index: 0, delta: { role: "assistant", content: "" }, finish_reason: null },
- ],
- })}\n\n`
- );
- roleEmitted = true;
- }
- emit(
- `data: ${JSON.stringify({
- id: responseId,
- object: "chat.completion.chunk",
- created,
- model,
- choices: [{ index: 0, delta: { content: delta }, finish_reason: null }],
- })}\n\n`
- );
- };
-
- const emitError = (message: string) => {
- emit(`data: ${JSON.stringify(buildErrorBody(502, message))}\n\n`);
- emit("data: [DONE]\n\n");
- finish();
- };
-
- const emitStop = () => {
- emit(
- `data: ${JSON.stringify({
- id: responseId,
- object: "chat.completion.chunk",
- created,
- model,
- choices: [{ index: 0, delta: {}, finish_reason: "stop" }],
- })}\n\n`
- );
- emit("data: [DONE]\n\n");
- finish();
- };
-
- let child: ReturnType<typeof spawn>;
- try {
- // No `shell` option — argv goes straight to the OS loader (no cmd.exe
- // interpretation). `model` is already allowlist-validated upstream.
- child = spawn(auggieBin, buildAuggieArgs(model), {
- env: process.env,
- stdio: ["pipe", "pipe", "pipe"],
- });
- } catch (err) {
- const message = err instanceof Error ? err.message : String(err);
- emitError(isEnoentLike(message) ? cliNotFoundMessage(auggieBin) : sanitizeErrorMessage(message));
- return;
- }
-
- try {
- child.stdin.write(promptText);
- child.stdin.end();
- } catch {
- /* ignore — error/close handlers below surface failures */
- }
-
- if (signal) {
- signal.addEventListener("abort", () => {
- if (!child.killed) child.kill("SIGTERM");
- finish();
- });
- }
-
- child.on("error", (err: NodeJS.ErrnoException) => {
- const message = err?.message || String(err);
- emitError(isEnoentLike(message) ? cliNotFoundMessage(auggieBin) : sanitizeErrorMessage(message));
- });
-
- let stderrTail = "";
- child.stdout?.on("data", (chunk: Buffer) => {
- emitDelta(chunk.toString("utf8"));
- });
-
- child.stderr?.on("data", (chunk: Buffer) => {
- stderrTail = (stderrTail + chunk.toString("utf8")).slice(-2000);
- log?.debug?.("AUGGIE", `stderr: ${chunk.toString("utf8").slice(0, 200)}`);
- });
-
- child.on("close", (code) => {
- if (finished) return;
- if (code !== 0) {
- emitError(
- sanitizeErrorMessage(
- `Auggie CLI exited with code ${code}${stderrTail ? `: ${stderrTail}` : ""}`
- )
- );
- return;
- }
- emitStop();
- });
- },
- cancel() {
- // Stream cancelled by the consumer — nothing extra to clean up here;
- // the abort-signal listener above (if provided) handles process kill.
- },
- });
-
- return new Response(sseStream, {
- status: 200,
- headers: {
- "Content-Type": "text/event-stream",
- "Cache-Control": "no-cache",
- Connection: "keep-alive",
- },
- });
- }
-
- private runNonStreaming(
- auggieBin: string,
- model: string,
- promptText: string,
- signal: AbortSignal | null | undefined,
- log: ExecuteInput["log"]
- ): Promise<Response> {
- return new Promise((resolve) => {
- let child: ReturnType<typeof spawn>;
- try {
- child = this.spawnAuggie(auggieBin, model, promptText);
- } catch (err) {
- const message = err instanceof Error ? err.message : String(err);
- resolve(
- buildAuggieErrorResponse(
- isEnoentLike(message) ? cliNotFoundMessage(auggieBin) : sanitizeErrorMessage(message)
- )
- );
- return;
- }
-
- let stdout = "";
- let stderrTail = "";
- let settled = false;
-
- const settle = (response: Response) => {
- if (settled) return;
- settled = true;
- resolve(response);
- };
-
- if (signal) {
- signal.addEventListener("abort", () => {
- if (!child.killed) child.kill("SIGTERM");
- settle(buildAuggieErrorResponse(sanitizeErrorMessage("Auggie CLI request aborted")));
- });
- }
-
- child.stdout?.on("data", (chunk: Buffer) => {
- stdout += chunk.toString("utf8");
- });
- child.stderr?.on("data", (chunk: Buffer) => {
- stderrTail = (stderrTail + chunk.toString("utf8")).slice(-2000);
- log?.debug?.("AUGGIE", `stderr: ${chunk.toString("utf8").slice(0, 200)}`);
- });
-
- child.on("error", (err: NodeJS.ErrnoException) => {
- const message = err?.message || String(err);
- settle(
- buildAuggieErrorResponse(
- isEnoentLike(message) ? cliNotFoundMessage(auggieBin) : sanitizeErrorMessage(message)
- )
- );
- });
-
- child.on("close", (code) => {
- if (code !== 0) {
- settle(
- buildAuggieErrorResponse(
- sanitizeErrorMessage(
- `Auggie CLI exited with code ${code}${stderrTail ? `: ${stderrTail}` : ""}`
- )
- )
- );
- return;
- }
- settle(buildChatCompletionResponse(model, promptText, stdout));
- });
- });
- }
-}
-
-function buildChatCompletionResponse(model: string, promptText: string, content: string): Response {
- const trimmed = content.trim();
- const body = {
- id: `chatcmpl-auggie-${Date.now()}`,
- object: "chat.completion",
- created: Math.floor(Date.now() / 1000),
- model,
- choices: [
- {
- index: 0,
- message: { role: "assistant", content: trimmed },
- finish_reason: "stop",
- },
- ],
- usage: {
- prompt_tokens: Math.ceil(promptText.length / 4),
- completion_tokens: Math.ceil(trimmed.length / 4),
- total_tokens: Math.ceil((promptText.length + trimmed.length) / 4),
- estimated: true,
- },
- };
- return new Response(JSON.stringify(body), {
- status: 200,
- headers: { "Content-Type": "application/json" },
- });
-}
-
-function buildAuggieErrorResponse(message: string): Response {
- return errorResponse(502, message);
-}
-
-/**
- * Build a one-shot SSE error Response (single sanitized error event + [DONE]).
- * Used for pre-spawn rejections on the streaming path (e.g. an invalid model)
- * where no subprocess is ever started.
- */
-function buildAuggieSseError(message: string): Response {
- const enc = new TextEncoder();
- const sseStream = new ReadableStream<Uint8Array>({
- start(controller) {
- controller.enqueue(enc.encode(`data: ${JSON.stringify(buildErrorBody(400, message))}\n\n`));
- controller.enqueue(enc.encode("data: [DONE]\n\n"));
- controller.close();
- },
- });
- return new Response(sseStream, {
- status: 200,
- headers: {
- "Content-Type": "text/event-stream",
- "Cache-Control": "no-cache",
- Connection: "keep-alive",
- },
- });
-}
diff --git a/open-sse/executors/base.ts b/open-sse/executors/base.ts
index 59e64bde69..96685152c2 100644
--- a/open-sse/executors/base.ts
+++ b/open-sse/executors/base.ts
@@ -66,26 +66,6 @@ import {
stripProxyToolPrefix,
} from "./claudeIdentity.ts";
import { withForcedResponsesUpstream } from "./forceResponsesUpstream.ts";
-import {
- mergeUpstreamExtraHeaders,
- setUserAgentHeader,
- applyConfiguredUserAgent,
- stripStainlessHeadersForOpenAICompat,
-} from "./base/headers.ts";
-// Header helpers extracted to a pure leaf; re-exported for external importers
-// (executors + tests) that import them from "./base.ts".
-export {
- mergeUpstreamExtraHeaders,
- getCustomUserAgent,
- setUserAgentHeader,
- applyConfiguredUserAgent,
- isOpenAICompatibleEndpoint,
- stripStainlessHeadersForOpenAICompat,
-} from "./base/headers.ts";
-import { sanitizeReasoningEffortForProvider } from "./base/reasoningEffort.ts";
-// Reasoning-effort sanitation extracted to a pure leaf; re-exported for external
-// importers (mimoThinking service + tests) that import it from "./base.ts".
-export { sanitizeReasoningEffortForProvider } from "./base/reasoningEffort.ts";
/**
* Sanitizes a custom API path to prevent path traversal attacks.
@@ -175,6 +155,95 @@ export type CountTokensInput = {
signal?: AbortSignal | null;
};
+/** Apply model-level extra upstream headers (e.g. Authentication, X-Custom-Auth). */
+export function mergeUpstreamExtraHeaders(
+ headers: Record<string, string>,
+ extra?: Record<string, string> | null
+): void {
+ if (!extra) return;
+ for (const [k, v] of Object.entries(extra)) {
+ if (typeof k === "string" && k.length > 0 && typeof v === "string") {
+ if (k.toLowerCase() === "user-agent") {
+ setUserAgentHeader(headers, v);
+ continue;
+ }
+ headers[k] = v;
+ }
+ }
+}
+
+export function getCustomUserAgent(providerSpecificData?: JsonRecord | null): string | null {
+ const customUserAgent =
+ typeof providerSpecificData?.customUserAgent === "string"
+ ? providerSpecificData.customUserAgent.trim()
+ : "";
+ return customUserAgent || null;
+}
+
+export function setUserAgentHeader(headers: Record<string, string>, userAgent: string): void {
+ headers["User-Agent"] = userAgent;
+ if ("user-agent" in headers) {
+ headers["user-agent"] = userAgent;
+ }
+}
+
+export function applyConfiguredUserAgent(
+ headers: Record<string, string>,
+ providerSpecificData?: JsonRecord | null
+): void {
+ const customUserAgent = getCustomUserAgent(providerSpecificData);
+ if (customUserAgent) {
+ setUserAgentHeader(headers, customUserAgent);
+ }
+}
+
+/**
+ * Returns true when the outbound request targets an OpenAI-compatible endpoint
+ * (a `openai-compatible-*` provider, or a Chat Completions / Responses URL).
+ * Used to scope the X-Stainless strip narrowly so genuine SDK-spoofing paths
+ * (e.g. Claude Code compat, which legitimately ADDS X-Stainless-*) are untouched.
+ */
+export function isOpenAICompatibleEndpoint(provider: string, url: string): boolean {
+ if (provider?.startsWith?.("openai-compatible-")) return true;
+ return url.includes("/v1/chat/completions") || url.includes("/v1/responses");
+}
+
+/**
+ * Strip OpenAI SDK (`X-Stainless-*`) metadata headers and normalize an SDK-derived
+ * User-Agent for OpenAI-compatible passthrough requests. Some upstream gateways
+ * 403 on these SDK-identifying headers. Only applied to OpenAI-compatible endpoints —
+ * other providers (Claude/Claude Code compat) may legitimately send X-Stainless-*.
+ *
+ * Mutates `headers` in place and returns the list of stripped header keys (for logging).
+ */
+export function stripStainlessHeadersForOpenAICompat(
+ headers: Record<string, string>,
+ provider: string,
+ url: string
+): string[] {
+ if (!isOpenAICompatibleEndpoint(provider, url)) return [];
+
+ const strippedKeys: string[] = [];
+ for (const key of Object.keys(headers)) {
+ if (key.toLowerCase().startsWith("x-stainless-")) {
+ delete headers[key];
+ strippedKeys.push(key);
+ }
+ }
+
+ // Normalize User-Agent: SDK-based clients send verbose product strings that some
+ // upstreams block. Replace with a clean browser-like UA only when it looks SDK-derived.
+ const ua = (headers["User-Agent"] || headers["user-agent"] || "").toLowerCase();
+ if (
+ ua.includes("openai") &&
+ (ua.includes("node") || ua.includes("axios") || ua.includes("undici"))
+ ) {
+ setUserAgentHeader(headers, "Mozilla/5.0 (compatible; OpenAI Compatible)");
+ }
+
+ return strippedKeys;
+}
+
export function mergeAbortSignals(primary: AbortSignal, secondary: AbortSignal): AbortSignal {
const controller = new AbortController();
@@ -203,6 +272,161 @@ function hasActiveClaudeThinking(body: Record<string, unknown>): boolean {
return thinking?.type === "enabled" || thinking?.type === "adaptive";
}
+/**
+ * Sanitize reasoning_effort for providers that don't accept all values.
+ *
+ * The claude→openai translator may emit reasoning_effort=max/xhigh when the
+ * client sends output_config.effort=max on a Claude-shape request. Combined with
+ * runtime alias remapping (e.g. claude-opus-4-6 → mimo/mimo-v2.5-pro), this
+ * routes xhigh to OpenAI-shape providers that don't accept the value:
+ *
+ * xiaomi-mimo : low|medium|high only — 400 literal_error on xhigh
+ * mistral : devstral models reject reasoning_effort entirely
+ * github : claude/haiku/oswe models reject reasoning_effort entirely
+ *
+ * Each rejection burns a combo fallback attempt before reaching a working
+ * provider. Apply provider-aware sanitation here (after transformRequest, so
+ * reintroductions by per-provider transforms are also caught) before fetch.
+ * xhigh support is opt-out: pass through unchanged unless the registry marks
+ * a model as unsupported. Literal max support is provider-specific and
+ * intentionally separate: some upstreams accept max even when they do not
+ * accept xhigh. For OpenAI-shape providers, max normalizes to xhigh by default
+ * and falls back to high only for explicit xhigh opt-outs.
+ */
+const MISTRAL_NO_REASONING_EFFORT_PATTERN = /devstral/i;
+// GitHub Copilot Claude routing is granular (upstream port: decolua/9router#791):
+// ✅ Pass through — Claude Opus 4.6, Claude Sonnet 4.6. Copilot routes both to
+// Anthropic's chat/completions surface, which honors reasoning_effort and
+// emits visible reasoning tokens (verified upstream: 3× token increase
+// between low/medium/high).
+// ❌ Strip — Claude Haiku 4.5 and Claude Opus 4.7 (rejected upstream by
+// Copilot's Claude backend), older Claude variants, all `haiku`-named
+// models, and the `oswe-*` family (Raptor) which still rejects
+// reasoning_effort.
+// Order matters: the opt-in check must run BEFORE the broad Claude/haiku/oswe strip.
+const GITHUB_REASONING_EFFORT_OPT_IN_PATTERN = /claude[-_.]?(?:opus|sonnet)[-_.]?4[-_.]6/i;
+const GITHUB_NO_REASONING_EFFORT_PATTERN = /(claude|haiku|oswe)/i;
+
+function supportsMaxEffortForProvider(provider: string, model: string): boolean {
+ const isClaude =
+ (provider === PROVIDER_CLAUDE || isClaudeCodeCompatible(provider)) &&
+ supportsClaudeMaxEffort(model);
+ // opencode-go proxies DeepSeek with the native DeepSeek API contract, which
+ // accepts {high, max} literally. Without this opt-in, max would be
+ // normalized to xhigh (the OmniRoute-internal top tier) and rejected by the
+ // upstream. Scoped to opencode-go deliberately: OpenRouter's DeepSeek path
+ // (pi#4055) is the documented inverse and expects xhigh, not max.
+ // Ollama Cloud also accepts literal max (for example GLM 5.2 supports
+ // low|medium|high|max|none) and rejects xhigh.
+ const isOpencodeGoDeepSeek =
+ provider === "opencode-go" && model.toLowerCase().includes("deepseek");
+ const isOllamaCloud = provider === "ollama-cloud";
+ return isClaude || isOpencodeGoDeepSeek || isOllamaCloud;
+}
+
+export function sanitizeReasoningEffortForProvider(
+ body: unknown,
+ provider: string,
+ model: string | undefined,
+ log?: { info?: (tag: string, msg: string) => void } | null
+): unknown {
+ if (!body || typeof body !== "object" || Array.isArray(body)) return body;
+ const b = body as Record<string, unknown>;
+ const reasoning =
+ b.reasoning && typeof b.reasoning === "object" && !Array.isArray(b.reasoning)
+ ? (b.reasoning as Record<string, unknown>)
+ : null;
+ const hasTopLevelReasoningEffort = Object.prototype.hasOwnProperty.call(b, "reasoning_effort");
+ const effort = b.reasoning_effort ?? reasoning?.effort;
+ if (effort === undefined) return body;
+ const effortStr = typeof effort === "string" ? effort.toLowerCase() : "";
+ const modelStr = model || "";
+
+ const githubOptIn =
+ provider === "github" && GITHUB_REASONING_EFFORT_OPT_IN_PATTERN.test(modelStr);
+ const rejecting =
+ (provider === "mistral" && MISTRAL_NO_REASONING_EFFORT_PATTERN.test(modelStr)) ||
+ (provider === "github" && !githubOptIn && GITHUB_NO_REASONING_EFFORT_PATTERN.test(modelStr));
+ if (rejecting) {
+ log?.info?.(
+ "REASONING_SANITIZE",
+ `${provider}/${modelStr}: removed unsupported reasoning_effort`
+ );
+ const next: Record<string, unknown> = { ...b };
+ delete next.reasoning_effort;
+ if (reasoning) {
+ const r = { ...reasoning };
+ delete r.effort;
+ if (Object.keys(r).length === 0) delete next.reasoning;
+ else next.reasoning = r;
+ }
+ return next;
+ }
+
+ // Native DeepSeek (api.deepseek.com) — V4 thinking mode accepts reasoning_effort
+ // ONLY as {high, max} (its own top tier is literally "max"). OmniRoute's internal
+ // scale is low|medium|high|xhigh where xhigh is the top, so map onto DeepSeek's
+ // vocabulary: xhigh → max (top→top), low|medium → high (below the enum floor).
+ // high/max pass through unchanged. Without this, the claude→openai translator's
+ // xhigh (and max-normalized-to-xhigh below) reaches DeepSeek as an unknown value,
+ // silently dropping the client's requested effort. This is the INVERSE of the
+ // OpenRouter-DeepSeek path, whose normalized API expects xhigh, not max (pi#4055).
+ if (provider === "deepseek") {
+ const mapped =
+ effortStr === "xhigh" ? "max" : effortStr === "low" || effortStr === "medium" ? "high" : null;
+ if (mapped && mapped !== effortStr) {
+ log?.info?.(
+ "REASONING_SANITIZE",
+ `deepseek/${modelStr}: normalized reasoning_effort ${effortStr} → ${mapped}`
+ );
+ const next: Record<string, unknown> = { ...b };
+ if (hasTopLevelReasoningEffort) next.reasoning_effort = mapped;
+ if (reasoning) next.reasoning = { ...reasoning, effort: mapped };
+ return next;
+ }
+ return body;
+ }
+
+ const supportsXHigh = supportsXHighEffort(provider, modelStr);
+ const shouldDowngradeXHigh = effortStr === "xhigh" && !supportsXHigh;
+ const supportsXHighForMax = supportsXHigh;
+ const supportsMax = supportsMaxEffortForProvider(provider, modelStr);
+ const shouldNormalizeMaxToXHigh = effortStr === "max" && !supportsMax && supportsXHighForMax;
+ const shouldDowngradeMax = effortStr === "max" && !supportsMax && !supportsXHighForMax;
+
+ if (shouldNormalizeMaxToXHigh) {
+ log?.info?.(
+ "REASONING_SANITIZE",
+ `${provider}/${modelStr}: normalized reasoning_effort max → xhigh`
+ );
+ const next: Record<string, unknown> = { ...b };
+ if (hasTopLevelReasoningEffort) {
+ next.reasoning_effort = "xhigh";
+ }
+ if (reasoning) {
+ next.reasoning = { ...reasoning, effort: "xhigh" };
+ }
+ return next;
+ }
+
+ if (shouldDowngradeXHigh || shouldDowngradeMax) {
+ log?.info?.(
+ "REASONING_SANITIZE",
+ `${provider}/${modelStr}: downgraded reasoning_effort ${effortStr} → high`
+ );
+ const next: Record<string, unknown> = { ...b };
+ if (hasTopLevelReasoningEffort) {
+ next.reasoning_effort = "high";
+ }
+ if (reasoning) {
+ next.reasoning = { ...reasoning, effort: "high" };
+ }
+ return next;
+ }
+
+ return body;
+}
+
/**
* Strip the OmniRoute provider prefix from versioned built-in tool model
* fields (e.g. `cc/claude-opus-4-8` → `claude-opus-4-8`). Versioned built-in
diff --git a/open-sse/executors/base/headers.ts b/open-sse/executors/base/headers.ts
deleted file mode 100644
index 5aebfbb5cb..0000000000
--- a/open-sse/executors/base/headers.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-// Pure upstream header helpers (User-Agent, extra headers, OpenAI-compat stripping).
-// Extracted verbatim from base.ts. Module-private JsonRecord kept local to avoid a cycle.
-
-type JsonRecord = Record<string, unknown>;
-
-/** Apply model-level extra upstream headers (e.g. Authentication, X-Custom-Auth). */
-export function mergeUpstreamExtraHeaders(
- headers: Record<string, string>,
- extra?: Record<string, string> | null
-): void {
- if (!extra) return;
- for (const [k, v] of Object.entries(extra)) {
- if (typeof k === "string" && k.length > 0 && typeof v === "string") {
- if (k.toLowerCase() === "user-agent") {
- setUserAgentHeader(headers, v);
- continue;
- }
- headers[k] = v;
- }
- }
-}
-
-export function getCustomUserAgent(providerSpecificData?: JsonRecord | null): string | null {
- const customUserAgent =
- typeof providerSpecificData?.customUserAgent === "string"
- ? providerSpecificData.customUserAgent.trim()
- : "";
- return customUserAgent || null;
-}
-
-export function setUserAgentHeader(headers: Record<string, string>, userAgent: string): void {
- headers["User-Agent"] = userAgent;
- if ("user-agent" in headers) {
- headers["user-agent"] = userAgent;
- }
-}
-
-export function applyConfiguredUserAgent(
- headers: Record<string, string>,
- providerSpecificData?: JsonRecord | null
-): void {
- const customUserAgent = getCustomUserAgent(providerSpecificData);
- if (customUserAgent) {
- setUserAgentHeader(headers, customUserAgent);
- }
-}
-
-/**
- * Returns true when the outbound request targets an OpenAI-compatible endpoint
- * (a `openai-compatible-*` provider, or a Chat Completions / Responses URL).
- * Used to scope the X-Stainless strip narrowly so genuine SDK-spoofing paths
- * (e.g. Claude Code compat, which legitimately ADDS X-Stainless-*) are untouched.
- */
-export function isOpenAICompatibleEndpoint(provider: string, url: string): boolean {
- if (provider?.startsWith?.("openai-compatible-")) return true;
- return url.includes("/v1/chat/completions") || url.includes("/v1/responses");
-}
-
-/**
- * Strip OpenAI SDK (`X-Stainless-*`) metadata headers and normalize an SDK-derived
- * User-Agent for OpenAI-compatible passthrough requests. Some upstream gateways
- * 403 on these SDK-identifying headers. Only applied to OpenAI-compatible endpoints —
- * other providers (Claude/Claude Code compat) may legitimately send X-Stainless-*.
- *
- * Mutates `headers` in place and returns the list of stripped header keys (for logging).
- */
-export function stripStainlessHeadersForOpenAICompat(
- headers: Record<string, string>,
- provider: string,
- url: string
-): string[] {
- if (!isOpenAICompatibleEndpoint(provider, url)) return [];
-
- const strippedKeys: string[] = [];
- for (const key of Object.keys(headers)) {
- if (key.toLowerCase().startsWith("x-stainless-")) {
- delete headers[key];
- strippedKeys.push(key);
- }
- }
-
- // Normalize User-Agent: SDK-based clients send verbose product strings that some
- // upstreams block. Replace with a clean browser-like UA only when it looks SDK-derived.
- const ua = (headers["User-Agent"] || headers["user-agent"] || "").toLowerCase();
- if (
- ua.includes("openai") &&
- (ua.includes("node") || ua.includes("axios") || ua.includes("undici"))
- ) {
- setUserAgentHeader(headers, "Mozilla/5.0 (compatible; OpenAI Compatible)");
- }
-
- return strippedKeys;
-}
diff --git a/open-sse/executors/base/reasoningEffort.ts b/open-sse/executors/base/reasoningEffort.ts
deleted file mode 100644
index dcabf6ef26..0000000000
--- a/open-sse/executors/base/reasoningEffort.ts
+++ /dev/null
@@ -1,160 +0,0 @@
-// Provider-aware reasoning_effort sanitation (xhigh/max normalization + reject strip).
-// Extracted verbatim from base.ts. Deps are config/services only (no host import → no cycle).
-import { PROVIDER_CLAUDE } from "../../services/systemTransforms.ts";
-import { isClaudeCodeCompatible } from "../../services/provider.ts";
-import { supportsClaudeMaxEffort, supportsXHighEffort } from "../../config/providerModels.ts";
-
-/**
- * Sanitize reasoning_effort for providers that don't accept all values.
- *
- * The claude→openai translator may emit reasoning_effort=max/xhigh when the
- * client sends output_config.effort=max on a Claude-shape request. Combined with
- * runtime alias remapping (e.g. claude-opus-4-6 → mimo/mimo-v2.5-pro), this
- * routes xhigh to OpenAI-shape providers that don't accept the value:
- *
- * xiaomi-mimo : low|medium|high only — 400 literal_error on xhigh
- * mistral : devstral models reject reasoning_effort entirely
- * github : claude/haiku/oswe models reject reasoning_effort entirely
- *
- * Each rejection burns a combo fallback attempt before reaching a working
- * provider. Apply provider-aware sanitation here (after transformRequest, so
- * reintroductions by per-provider transforms are also caught) before fetch.
- * xhigh support is opt-out: pass through unchanged unless the registry marks
- * a model as unsupported. Literal max support is provider-specific and
- * intentionally separate: some upstreams accept max even when they do not
- * accept xhigh. For OpenAI-shape providers, max normalizes to xhigh by default
- * and falls back to high only for explicit xhigh opt-outs.
- */
-export const MISTRAL_NO_REASONING_EFFORT_PATTERN = /devstral/i;
-// GitHub Copilot Claude routing is granular (upstream port: decolua/9router#791):
-// ✅ Pass through — Claude Opus 4.6, Claude Sonnet 4.6. Copilot routes both to
-// Anthropic's chat/completions surface, which honors reasoning_effort and
-// emits visible reasoning tokens (verified upstream: 3× token increase
-// between low/medium/high).
-// ❌ Strip — Claude Haiku 4.5 and Claude Opus 4.7 (rejected upstream by
-// Copilot's Claude backend), older Claude variants, all `haiku`-named
-// models, and the `oswe-*` family (Raptor) which still rejects
-// reasoning_effort.
-// Order matters: the opt-in check must run BEFORE the broad Claude/haiku/oswe strip.
-export const GITHUB_REASONING_EFFORT_OPT_IN_PATTERN = /claude[-_.]?(?:opus|sonnet)[-_.]?4[-_.]6/i;
-export const GITHUB_NO_REASONING_EFFORT_PATTERN = /(claude|haiku|oswe)/i;
-
-export function supportsMaxEffortForProvider(provider: string, model: string): boolean {
- const isClaude =
- (provider === PROVIDER_CLAUDE || isClaudeCodeCompatible(provider)) &&
- supportsClaudeMaxEffort(model);
- // opencode-go proxies DeepSeek with the native DeepSeek API contract, which
- // accepts {high, max} literally. Without this opt-in, max would be
- // normalized to xhigh (the OmniRoute-internal top tier) and rejected by the
- // upstream. Scoped to opencode-go deliberately: OpenRouter's DeepSeek path
- // (pi#4055) is the documented inverse and expects xhigh, not max.
- // Ollama Cloud also accepts literal max (for example GLM 5.2 supports
- // low|medium|high|max|none) and rejects xhigh.
- const isOpencodeGoDeepSeek =
- provider === "opencode-go" && model.toLowerCase().includes("deepseek");
- const isOllamaCloud = provider === "ollama-cloud";
- return isClaude || isOpencodeGoDeepSeek || isOllamaCloud;
-}
-
-export function sanitizeReasoningEffortForProvider(
- body: unknown,
- provider: string,
- model: string | undefined,
- log?: { info?: (tag: string, msg: string) => void } | null
-): unknown {
- if (!body || typeof body !== "object" || Array.isArray(body)) return body;
- const b = body as Record<string, unknown>;
- const reasoning =
- b.reasoning && typeof b.reasoning === "object" && !Array.isArray(b.reasoning)
- ? (b.reasoning as Record<string, unknown>)
- : null;
- const hasTopLevelReasoningEffort = Object.prototype.hasOwnProperty.call(b, "reasoning_effort");
- const effort = b.reasoning_effort ?? reasoning?.effort;
- if (effort === undefined) return body;
- const effortStr = typeof effort === "string" ? effort.toLowerCase() : "";
- const modelStr = model || "";
-
- const githubOptIn =
- provider === "github" && GITHUB_REASONING_EFFORT_OPT_IN_PATTERN.test(modelStr);
- const rejecting =
- (provider === "mistral" && MISTRAL_NO_REASONING_EFFORT_PATTERN.test(modelStr)) ||
- (provider === "github" && !githubOptIn && GITHUB_NO_REASONING_EFFORT_PATTERN.test(modelStr));
- if (rejecting) {
- log?.info?.(
- "REASONING_SANITIZE",
- `${provider}/${modelStr}: removed unsupported reasoning_effort`
- );
- const next: Record<string, unknown> = { ...b };
- delete next.reasoning_effort;
- if (reasoning) {
- const r = { ...reasoning };
- delete r.effort;
- if (Object.keys(r).length === 0) delete next.reasoning;
- else next.reasoning = r;
- }
- return next;
- }
-
- // Native DeepSeek (api.deepseek.com) — V4 thinking mode accepts reasoning_effort
- // ONLY as {high, max} (its own top tier is literally "max"). OmniRoute's internal
- // scale is low|medium|high|xhigh where xhigh is the top, so map onto DeepSeek's
- // vocabulary: xhigh → max (top→top), low|medium → high (below the enum floor).
- // high/max pass through unchanged. Without this, the claude→openai translator's
- // xhigh (and max-normalized-to-xhigh below) reaches DeepSeek as an unknown value,
- // silently dropping the client's requested effort. This is the INVERSE of the
- // OpenRouter-DeepSeek path, whose normalized API expects xhigh, not max (pi#4055).
- if (provider === "deepseek") {
- const mapped =
- effortStr === "xhigh" ? "max" : effortStr === "low" || effortStr === "medium" ? "high" : null;
- if (mapped && mapped !== effortStr) {
- log?.info?.(
- "REASONING_SANITIZE",
- `deepseek/${modelStr}: normalized reasoning_effort ${effortStr} → ${mapped}`
- );
- const next: Record<string, unknown> = { ...b };
- if (hasTopLevelReasoningEffort) next.reasoning_effort = mapped;
- if (reasoning) next.reasoning = { ...reasoning, effort: mapped };
- return next;
- }
- return body;
- }
-
- const supportsXHigh = supportsXHighEffort(provider, modelStr);
- const shouldDowngradeXHigh = effortStr === "xhigh" && !supportsXHigh;
- const supportsXHighForMax = supportsXHigh;
- const supportsMax = supportsMaxEffortForProvider(provider, modelStr);
- const shouldNormalizeMaxToXHigh = effortStr === "max" && !supportsMax && supportsXHighForMax;
- const shouldDowngradeMax = effortStr === "max" && !supportsMax && !supportsXHighForMax;
-
- if (shouldNormalizeMaxToXHigh) {
- log?.info?.(
- "REASONING_SANITIZE",
- `${provider}/${modelStr}: normalized reasoning_effort max → xhigh`
- );
- const next: Record<string, unknown> = { ...b };
- if (hasTopLevelReasoningEffort) {
- next.reasoning_effort = "xhigh";
- }
- if (reasoning) {
- next.reasoning = { ...reasoning, effort: "xhigh" };
- }
- return next;
- }
-
- if (shouldDowngradeXHigh || shouldDowngradeMax) {
- log?.info?.(
- "REASONING_SANITIZE",
- `${provider}/${modelStr}: downgraded reasoning_effort ${effortStr} → high`
- );
- const next: Record<string, unknown> = { ...b };
- if (hasTopLevelReasoningEffort) {
- next.reasoning_effort = "high";
- }
- if (reasoning) {
- next.reasoning = { ...reasoning, effort: "high" };
- }
- return next;
- }
-
- return body;
-}
diff --git a/open-sse/executors/chatgpt-web.ts b/open-sse/executors/chatgpt-web.ts
index 27085cf3c6..87a4bd3f29 100644
--- a/open-sse/executors/chatgpt-web.ts
+++ b/open-sse/executors/chatgpt-web.ts
@@ -32,7 +32,6 @@ import {
__resetChatGptImageCacheForTesting,
type ChatGptImageConversationContext,
} from "../services/chatgptImageCache.ts";
-import { isThinkingCapableModel, resolveChatGptModel } from "./chatgpt-web/models.ts";
// ─── Constants ──────────────────────────────────────────────────────────────
@@ -85,6 +84,52 @@ function deviceIdFor(cookie: string): string {
// ChatGPT's backend routes use dash-form slugs (e.g. "gpt-5-5-pro"). The slug
// catalog comes from /backend-api/models on a logged-in account;
// "gpt-5-4-t-mini" is ChatGPT's abbreviated slug for "GPT-5.4 Thinking Mini".
+const MODEL_MAP: Record<string, string> = {
+ // ChatGPT backend slugs are also accepted directly for power users / tests.
+ "gpt-5-5-pro": "gpt-5-5-pro",
+ "gpt-5-5-pro-extended": "gpt-5-5-pro",
+ "gpt-5-5-thinking": "gpt-5-5-thinking",
+ "gpt-5-5": "gpt-5-5",
+ "gpt-5-4-pro": "gpt-5-4-pro",
+ "gpt-5-4-thinking": "gpt-5-4-thinking",
+ "gpt-5-4-t-mini": "gpt-5-4-t-mini",
+ "gpt-5-3": "gpt-5-3",
+ "gpt-5-3-mini": "gpt-5-3-mini",
+
+ // Public OmniRoute dot-form ids exposed by the provider catalog.
+ "gpt-5.5-pro": "gpt-5-5-pro",
+ "gpt-5.5-pro-extended": "gpt-5-5-pro",
+ "gpt-5.5-thinking": "gpt-5-5-thinking",
+ "gpt-5.5": "gpt-5-5",
+ "gpt-5.4-pro": "gpt-5-4-pro",
+ "gpt-5.4-thinking": "gpt-5-4-thinking",
+ "gpt-5.4-thinking-mini": "gpt-5-4-t-mini",
+ "gpt-5.3-instant": "gpt-5-3-instant",
+ "gpt-5.3": "gpt-5-3",
+ "gpt-5.3-mini": "gpt-5-3-mini",
+ o3: "o3",
+};
+
+const MODEL_FORCED_EFFORT: Record<string, "standard" | "extended"> = {
+ "gpt-5-5-pro": "standard",
+ "gpt-5-5-pro-extended": "extended",
+ "gpt-5.5-pro": "standard",
+ "gpt-5.5-pro-extended": "extended",
+};
+
+/** Set of chatgpt.com slugs that the user_last_used_model_config endpoint
+ * accepts a `thinking_effort` value for, derived from MODEL_MAP so adding a
+ * new thinking entry there automatically extends this set. Includes the
+ * abbreviated slug `gpt-5-4-t-mini` (no literal "thinking" substring) — the
+ * reason this set exists at all rather than a substring match.
+ *
+ * Derived from MODEL_MAP keys (always dot-form) that contain "thinking" or
+ * are the `o3` reasoning model; the values are the chatgpt.com-side slugs. */
+const THINKING_CAPABLE_SLUGS: ReadonlySet<string> = new Set(
+ Object.entries(MODEL_MAP)
+ .filter(([k]) => k.includes("thinking") || k === "o3")
+ .map(([, v]) => v)
+);
// ─── Browser-like default headers ──────────────────────────────────────────
@@ -427,6 +472,90 @@ const thinkingEffortCache = new Map<string, number>();
const THINKING_EFFORT_TTL_MS = 5 * 60 * 1000;
const THINKING_EFFORT_CACHE_MAX = 400;
+/** chatgpt.com only exposes the thinking-effort toggle on dedicated thinking
+ * models and the o-series. PATCHing for a non-thinking surface is a no-op
+ * (the server accepts it but the routing-time read picks the wrong knob).
+ *
+ * Three branches because the input can arrive in three shapes:
+ * 1. OmniRoute dot-form id (`gpt-5.4-thinking-mini`) — every thinking
+ * variant carries the literal "thinking" substring here.
+ * 2. Resolved chatgpt.com slug containing "thinking" (`gpt-5-5-thinking`).
+ * 3. Resolved chatgpt.com slug that drops the substring under abbreviation
+ * (`gpt-5-4-t-mini`). Looked up via THINKING_CAPABLE_SLUGS, which is
+ * derived from MODEL_MAP itself so adding a new abbreviated thinking
+ * mapping automatically extends the check.
+ *
+ * Branch 3 also catches the case where a caller passes the chatgpt.com slug
+ * directly as the `model` field (no MODEL_MAP translation needed), which
+ * would otherwise silently bypass the PATCH. */
+function isThinkingCapableModel(modelId: string, slug: string): boolean {
+ return (
+ modelId.includes("thinking") ||
+ modelId === "o3" ||
+ slug.includes("thinking") ||
+ THINKING_CAPABLE_SLUGS.has(slug) ||
+ THINKING_CAPABLE_SLUGS.has(modelId)
+ );
+}
+
+/** Map either a chatgpt.com-native value (`standard`/`extended`) or the
+ * OpenAI Chat Completions `reasoning_effort` field to the value the
+ * `user_last_used_model_config` endpoint expects.
+ *
+ * minimal | low | medium | standard → standard
+ * high | xhigh | extended → extended
+ *
+ * `medium` collapses to `standard` because chatgpt.com only has two levels —
+ * there is no separate medium tier on the web product. Returns null for
+ * absent/unknown inputs. */
+function normalizeThinkingEffort(input: unknown): "standard" | "extended" | null {
+ if (typeof input !== "string") return null;
+ const v = input.trim().toLowerCase();
+ if (v === "extended" || v === "high" || v === "xhigh") return "extended";
+ if (v === "standard" || v === "low" || v === "medium" || v === "minimal") {
+ return "standard";
+ }
+ return null;
+}
+
+/** Resolve the requested effort for this turn.
+ * Order: `providerSpecificData.thinkingEffort` (raw override, takes
+ * `standard`/`extended` directly) > `body.reasoning_effort` (top-level OpenAI
+ * Chat Completions field) > `body.reasoning.effort` (Responses-API nesting).
+ * Returns null when the caller did not request one. */
+function resolveThinkingEffort(
+ body: unknown,
+ providerSpecificData: Record<string, unknown> | undefined
+): "standard" | "extended" | null {
+ if (providerSpecificData && providerSpecificData.thinkingEffort !== undefined) {
+ return normalizeThinkingEffort(providerSpecificData.thinkingEffort);
+ }
+ const b = (body as Record<string, unknown> | null) ?? null;
+ if (!b) return null;
+ const top = normalizeThinkingEffort(b.reasoning_effort);
+ if (top) return top;
+ const nested = (b.reasoning as Record<string, unknown> | undefined)?.effort;
+ return normalizeThinkingEffort(nested);
+}
+
+interface ResolvedChatGptModel {
+ slug: string;
+ effort: "standard" | "extended" | null;
+ isPro: boolean;
+}
+
+function resolveChatGptModel(
+ model: string,
+ body: unknown,
+ providerSpecificData: Record<string, unknown> | undefined
+): ResolvedChatGptModel {
+ const slug = MODEL_MAP[model] ?? model;
+ const forcedEffort = MODEL_FORCED_EFFORT[model] ?? null;
+ const effort = forcedEffort ?? resolveThinkingEffort(body, providerSpecificData);
+ const isPro = slug === "gpt-5-5-pro";
+ return { slug, effort, isPro };
+}
+
function configuredProPollTimeoutMs(): number {
const raw = Number(process.env.OMNIROUTE_CGPT_WEB_PRO_TIMEOUT_MS);
if (!Number.isFinite(raw) || raw <= 0) return DEFAULT_PRO_POLL_TIMEOUT_MS;
@@ -1270,7 +1399,8 @@ async function* extractContent(
// on a tool-role message (handled below).
if (event.type === "server_ste_metadata") {
const meta = (event as Record<string, unknown>).metadata as
- Record<string, unknown> | undefined;
+ | Record<string, unknown>
+ | undefined;
if (meta && meta.turn_use_case === "image gen") {
imageGenAsync = true;
}
@@ -2650,7 +2780,8 @@ export class ChatGptWebExecutor extends BaseExecutor {
clientHeaders,
}: ExecuteInput) {
const messages = (body as Record<string, unknown> | null)?.messages as
- Array<Record<string, unknown>> | undefined;
+ | Array<Record<string, unknown>>
+ | undefined;
if (!messages || !Array.isArray(messages) || messages.length === 0) {
return {
response: errorResponse(400, "Missing or empty messages array"),
diff --git a/open-sse/executors/chatgpt-web/models.ts b/open-sse/executors/chatgpt-web/models.ts
deleted file mode 100644
index 72738f43b0..0000000000
--- a/open-sse/executors/chatgpt-web/models.ts
+++ /dev/null
@@ -1,133 +0,0 @@
-// Pure model-mapping / thinking-effort resolution for the ChatGPT-web executor.
-// Extracted verbatim from chatgpt-web.ts (static maps + pure resolvers, no state).
-
-export const MODEL_MAP: Record<string, string> = {
- // ChatGPT backend slugs are also accepted directly for power users / tests.
- "gpt-5-5-pro": "gpt-5-5-pro",
- "gpt-5-5-pro-extended": "gpt-5-5-pro",
- "gpt-5-5-thinking": "gpt-5-5-thinking",
- "gpt-5-5": "gpt-5-5",
- "gpt-5-4-pro": "gpt-5-4-pro",
- "gpt-5-4-thinking": "gpt-5-4-thinking",
- "gpt-5-4-t-mini": "gpt-5-4-t-mini",
- "gpt-5-3": "gpt-5-3",
- "gpt-5-3-mini": "gpt-5-3-mini",
-
- // Public OmniRoute dot-form ids exposed by the provider catalog.
- "gpt-5.5-pro": "gpt-5-5-pro",
- "gpt-5.5-pro-extended": "gpt-5-5-pro",
- "gpt-5.5-thinking": "gpt-5-5-thinking",
- "gpt-5.5": "gpt-5-5",
- "gpt-5.4-pro": "gpt-5-4-pro",
- "gpt-5.4-thinking": "gpt-5-4-thinking",
- "gpt-5.4-thinking-mini": "gpt-5-4-t-mini",
- "gpt-5.3-instant": "gpt-5-3-instant",
- "gpt-5.3": "gpt-5-3",
- "gpt-5.3-mini": "gpt-5-3-mini",
- o3: "o3",
-};
-
-export const MODEL_FORCED_EFFORT: Record<string, "standard" | "extended"> = {
- "gpt-5-5-pro": "standard",
- "gpt-5-5-pro-extended": "extended",
- "gpt-5.5-pro": "standard",
- "gpt-5.5-pro-extended": "extended",
-};
-
-/** Set of chatgpt.com slugs that the user_last_used_model_config endpoint
- * accepts a `thinking_effort` value for, derived from MODEL_MAP so adding a
- * new thinking entry there automatically extends this set. Includes the
- * abbreviated slug `gpt-5-4-t-mini` (no literal "thinking" substring) — the
- * reason this set exists at all rather than a substring match.
- *
- * Derived from MODEL_MAP keys (always dot-form) that contain "thinking" or
- * are the `o3` reasoning model; the values are the chatgpt.com-side slugs. */
-export const THINKING_CAPABLE_SLUGS: ReadonlySet<string> = new Set(
- Object.entries(MODEL_MAP)
- .filter(([k]) => k.includes("thinking") || k === "o3")
- .map(([, v]) => v)
-);
-
-/** chatgpt.com only exposes the thinking-effort toggle on dedicated thinking
- * models and the o-series. PATCHing for a non-thinking surface is a no-op
- * (the server accepts it but the routing-time read picks the wrong knob).
- *
- * Three branches because the input can arrive in three shapes:
- * 1. OmniRoute dot-form id (`gpt-5.4-thinking-mini`) — every thinking
- * variant carries the literal "thinking" substring here.
- * 2. Resolved chatgpt.com slug containing "thinking" (`gpt-5-5-thinking`).
- * 3. Resolved chatgpt.com slug that drops the substring under abbreviation
- * (`gpt-5-4-t-mini`). Looked up via THINKING_CAPABLE_SLUGS, which is
- * derived from MODEL_MAP itself so adding a new abbreviated thinking
- * mapping automatically extends the check.
- *
- * Branch 3 also catches the case where a caller passes the chatgpt.com slug
- * directly as the `model` field (no MODEL_MAP translation needed), which
- * would otherwise silently bypass the PATCH. */
-export function isThinkingCapableModel(modelId: string, slug: string): boolean {
- return (
- modelId.includes("thinking") ||
- modelId === "o3" ||
- slug.includes("thinking") ||
- THINKING_CAPABLE_SLUGS.has(slug) ||
- THINKING_CAPABLE_SLUGS.has(modelId)
- );
-}
-
-/** Map either a chatgpt.com-native value (`standard`/`extended`) or the
- * OpenAI Chat Completions `reasoning_effort` field to the value the
- * `user_last_used_model_config` endpoint expects.
- *
- * minimal | low | medium | standard → standard
- * high | xhigh | extended → extended
- *
- * `medium` collapses to `standard` because chatgpt.com only has two levels —
- * there is no separate medium tier on the web product. Returns null for
- * absent/unknown inputs. */
-export function normalizeThinkingEffort(input: unknown): "standard" | "extended" | null {
- if (typeof input !== "string") return null;
- const v = input.trim().toLowerCase();
- if (v === "extended" || v === "high" || v === "xhigh") return "extended";
- if (v === "standard" || v === "low" || v === "medium" || v === "minimal") {
- return "standard";
- }
- return null;
-}
-
-/** Resolve the requested effort for this turn.
- * Order: `providerSpecificData.thinkingEffort` (raw override, takes
- * `standard`/`extended` directly) > `body.reasoning_effort` (top-level OpenAI
- * Chat Completions field) > `body.reasoning.effort` (Responses-API nesting).
- * Returns null when the caller did not request one. */
-export function resolveThinkingEffort(
- body: unknown,
- providerSpecificData: Record<string, unknown> | undefined
-): "standard" | "extended" | null {
- if (providerSpecificData && providerSpecificData.thinkingEffort !== undefined) {
- return normalizeThinkingEffort(providerSpecificData.thinkingEffort);
- }
- const b = (body as Record<string, unknown> | null) ?? null;
- if (!b) return null;
- const top = normalizeThinkingEffort(b.reasoning_effort);
- if (top) return top;
- const nested = (b.reasoning as Record<string, unknown> | undefined)?.effort;
- return normalizeThinkingEffort(nested);
-}
-
-export interface ResolvedChatGptModel {
- slug: string;
- effort: "standard" | "extended" | null;
- isPro: boolean;
-}
-
-export function resolveChatGptModel(
- model: string,
- body: unknown,
- providerSpecificData: Record<string, unknown> | undefined
-): ResolvedChatGptModel {
- const slug = MODEL_MAP[model] ?? model;
- const forcedEffort = MODEL_FORCED_EFFORT[model] ?? null;
- const effort = forcedEffort ?? resolveThinkingEffort(body, providerSpecificData);
- const isPro = slug === "gpt-5-5-pro";
- return { slug, effort, isPro };
-}
diff --git a/open-sse/executors/chatgptWebTools.ts b/open-sse/executors/chatgptWebTools.ts
index 55a1c5be91..4a52506b33 100644
--- a/open-sse/executors/chatgptWebTools.ts
+++ b/open-sse/executors/chatgptWebTools.ts
@@ -1,16 +1,13 @@
-// Tool-call emulation helpers for web-cookie executors (#5240, #5927).
+// Tool-call emulation helpers for the ChatGPT Web executor (#5240).
//
-// Web-cookie providers (chatgpt-web, perplexity-web, ...) have no native
-// function calling. When the OpenAI request carries `tools`, the prompt-side
-// shim (`prepareToolMessages` in ../translator/webTools.ts) injects a `<tool>`
-// contract; on the response side we parse `<tool>{...}</tool>` blocks back
-// into OpenAI `tool_calls`.
+// chatgpt.com has no native function calling. When the OpenAI request carries
+// `tools`, the prompt-side shim (`prepareToolMessages` in
+// ../translator/webTools.ts) injects a `<tool>` contract; on the response side
+// we parse `<tool>{...}</tool>` blocks back into OpenAI `tool_calls` —
+// mirroring the sibling web-session executors (qwen-web, perplexity-web, ...).
//
-// The whole tool-mode orchestration lives here — provider-agnostic — so each
-// (frozen) executor only gains an import + a single delegating call. Despite
-// the filename (kept for git-blame continuity from #5240, the first caller),
-// this module is shared: `buildToolModeResponse()` accepts an `idSeed` so
-// every provider gets its own `tool_calls[].id` prefix.
+// The whole tool-mode orchestration lives here so the (frozen) chatgpt-web.ts
+// only gains an import + a single delegating call.
import { buildToolAwareResult } from "../translator/webTools.ts";
@@ -31,8 +28,7 @@ function sseChunk(data: unknown): string {
*/
async function applyToolCallsToJsonResponse(
response: Response,
- requestedTools: unknown,
- idSeed: string
+ requestedTools: unknown
): Promise<Response> {
const bodyText = await response.text();
try {
@@ -41,7 +37,7 @@ async function applyToolCallsToJsonResponse(
const { content, toolCalls, finishReason } = buildToolAwareResult(
rawContent,
requestedTools,
- idSeed
+ "cgpt"
);
if (toolCalls) {
json.choices[0].message = { role: "assistant", content: null, tool_calls: toolCalls };
@@ -111,13 +107,9 @@ export async function buildToolModeResponse(
bufferedJson: Response,
requestedTools: unknown,
stream: boolean,
- meta: { cid: string; created: number; model: string; idSeed?: string }
+ meta: { cid: string; created: number; model: string }
): Promise<Response> {
- const jsonResponse = await applyToolCallsToJsonResponse(
- bufferedJson,
- requestedTools,
- meta.idSeed ?? "cgpt"
- );
+ const jsonResponse = await applyToolCallsToJsonResponse(bufferedJson, requestedTools);
if (!stream) return jsonResponse;
const completion = await jsonResponse.json();
return new Response(toolCompletionToSseStream(completion, meta.cid, meta.created, meta.model), {
diff --git a/open-sse/executors/claude-web.ts b/open-sse/executors/claude-web.ts
index 599814d072..6c384fcc7a 100644
--- a/open-sse/executors/claude-web.ts
+++ b/open-sse/executors/claude-web.ts
@@ -27,11 +27,6 @@ import { normalizeSessionCookieHeader } from "@/lib/providers/webCookieAuth";
import { randomUUID } from "crypto";
import { sanitizeErrorMessage } from "../utils/error.ts";
import { tryBackedChat } from "../services/browserBackedChat.ts";
-import {
- type ClaudeWebRequestPayload,
- transformToClaude,
- transformFromClaude,
-} from "./claude-web/payload.ts";
// ─── Constants ──────────────────────────────────────────────────────────────
const CLAUDE_WEB_API_BASE = "https://claude.ai/api";
@@ -92,6 +87,74 @@ function readClaudeWebDeviceId(credentials: unknown): string | undefined {
return undefined;
}
+// Default model when not specified
+const DEFAULT_CLAUDE_MODEL = "claude-sonnet-4-6";
+
+// ─── Types ──────────────────────────────────────────────────────────────────
+/**
+ * Extended credentials to include organization and conversation context
+ */
+interface ClaudeWebRequestPayload {
+ prompt: string;
+ model: string;
+ timezone: string;
+ personalized_styles: Array<{
+ type: string;
+ key: string;
+ name: string;
+ nameKey: string;
+ prompt: string;
+ summary: string;
+ summaryKey: string;
+ isDefault: boolean;
+ }>;
+ locale: string;
+ tools: Array<{
+ name?: string;
+ description?: string;
+ input_schema?: Record<string, unknown>;
+ integration_name?: string;
+ is_mcp_app?: boolean;
+ type?: string;
+ }>;
+ turn_message_uuids: {
+ human_message_uuid: string;
+ assistant_message_uuid: string;
+ };
+ attachments: unknown[];
+ effort: string;
+ files: unknown[];
+ sync_sources: unknown[];
+ rendering_mode: string;
+ thinking_mode: string;
+ create_conversation_params: {
+ name: string;
+ model: string;
+ include_conversation_preferences: boolean;
+ paprika_mode: unknown;
+ compass_mode: unknown;
+ is_temporary: boolean;
+ enabled_imagine: boolean;
+ tool_search_mode: string;
+ };
+}
+
+/**
+ * Stream chunk from Claude Web API
+ */
+interface ClaudeWebStreamChunk {
+ type?: string;
+ index?: number;
+ completion?: string;
+ stop_reason?: string | null;
+ model?: string;
+ delta?: {
+ type?: string;
+ text?: string;
+ };
+ [key: string]: unknown;
+}
+
// ─── Helper Functions ───────────────────────────────────────────────────────
/**
@@ -167,6 +230,166 @@ async function normalizeClaudeSessionCookieWithAutoRefresh(
return normalized;
}
+/**
+ * Generate UUIDs for turn message tracking
+ */
+function generateMessageUUIDs() {
+ return {
+ human_message_uuid: randomUUID(),
+ assistant_message_uuid: randomUUID(),
+ };
+}
+
+/**
+ * Get default tool definitions for Claude Web API
+ */
+function getDefaultTools(): ClaudeWebRequestPayload["tools"] {
+ return [
+ {
+ name: "show_widget",
+ description: "Display interactive widgets and visualizations",
+ input_schema: {
+ type: "object",
+ properties: {
+ widget_type: {
+ type: "string",
+ description: "Type of widget to display",
+ },
+ },
+ },
+ integration_name: "visualize",
+ is_mcp_app: true,
+ },
+ {
+ name: "read_me",
+ description: "Read and reference documents",
+ input_schema: {
+ type: "object",
+ properties: {
+ file_path: {
+ type: "string",
+ description: "Path to the file to read",
+ },
+ },
+ },
+ integration_name: "visualize",
+ is_mcp_app: false,
+ },
+ {
+ type: "web_search_v0",
+ name: "web_search",
+ },
+ {
+ type: "artifacts_v0",
+ name: "artifacts",
+ },
+ {
+ type: "repl_v0",
+ name: "repl",
+ },
+ { type: "widget", name: "weather_fetch" },
+ { type: "widget", name: "recipe_display_v0" },
+ { type: "widget", name: "places_map_display_v0" },
+ { type: "widget", name: "message_compose_v1" },
+ { type: "widget", name: "ask_user_input_v0" },
+ { type: "widget", name: "recommend_claude_apps" },
+ { type: "widget", name: "places_search" },
+ { type: "widget", name: "fetch_sports_data" },
+ ];
+}
+
+/**
+ * Get default personalized style
+ */
+function getDefaultPersonalizedStyle(): ClaudeWebRequestPayload["personalized_styles"] {
+ return [
+ {
+ type: "default",
+ key: "Default",
+ name: "Normal",
+ nameKey: "normal_style_name",
+ prompt: "Normal\n",
+ summary: "Default responses from Claude",
+ summaryKey: "normal_style_summary",
+ isDefault: true,
+ },
+ ];
+}
+
+/**
+ * Transform OpenAI format to Claude Web format
+ */
+function transformToClaude(body: Record<string, unknown>, model: string): ClaudeWebRequestPayload {
+ const messages = Array.isArray(body.messages) ? body.messages : [];
+
+ // Extract the last user message as the prompt
+ let prompt = "";
+ for (const msg of messages) {
+ if (typeof msg === "object" && msg !== null) {
+ const message = msg as Record<string, unknown>;
+ if (message.role === "user") {
+ prompt = String(message.content || "");
+ }
+ }
+ }
+
+ if (!prompt.trim()) {
+ throw new Error("No user message found in request");
+ }
+
+ return {
+ prompt,
+ model: model || DEFAULT_CLAUDE_MODEL,
+ timezone: "Asia/Jakarta",
+ personalized_styles: getDefaultPersonalizedStyle(),
+ locale: "en-US",
+ tools: getDefaultTools(),
+ turn_message_uuids: generateMessageUUIDs(),
+ attachments: [],
+ effort: "low",
+ files: [],
+ sync_sources: [],
+ rendering_mode: "messages",
+ thinking_mode: "off",
+ create_conversation_params: {
+ name: "",
+ model: model || DEFAULT_CLAUDE_MODEL,
+ include_conversation_preferences: true,
+ paprika_mode: null,
+ compass_mode: null,
+ is_temporary: false,
+ enabled_imagine: true,
+ tool_search_mode: "auto",
+ },
+ };
+}
+
+/**
+ * Transform Claude Web response to OpenAI format
+ */
+function transformFromClaude(
+ claudeContent: string,
+ model: string,
+ stopReason?: string
+): Record<string, unknown> {
+ return {
+ id: `chatcmpl-${Date.now()}`,
+ object: "chat.completion.chunk",
+ created: Math.floor(Date.now() / 1000),
+ model,
+ choices: [
+ {
+ index: 0,
+ delta: {
+ content: claudeContent,
+ },
+ finish_reason: stopReason === "end_turn" ? "stop" : null,
+ logprobs: null,
+ },
+ ],
+ };
+}
+
/**
* Verify session is still valid by checking if the organizations endpoint
* returns a successful response. Claude's API does not have a /api/auth/session
diff --git a/open-sse/executors/claude-web/payload.ts b/open-sse/executors/claude-web/payload.ts
deleted file mode 100644
index cc0dcc3787..0000000000
--- a/open-sse/executors/claude-web/payload.ts
+++ /dev/null
@@ -1,230 +0,0 @@
-// Pure Claude-web payload construction (types + transforms + default tools/style).
-// Extracted verbatim from claude-web.ts. No host state, no fetch/auth.
-import { randomUUID } from "crypto";
-
-// Default model when not specified
-export const DEFAULT_CLAUDE_MODEL = "claude-sonnet-4-6";
-
-export interface ClaudeWebRequestPayload {
- prompt: string;
- model: string;
- timezone: string;
- personalized_styles: Array<{
- type: string;
- key: string;
- name: string;
- nameKey: string;
- prompt: string;
- summary: string;
- summaryKey: string;
- isDefault: boolean;
- }>;
- locale: string;
- tools: Array<{
- name?: string;
- description?: string;
- input_schema?: Record<string, unknown>;
- integration_name?: string;
- is_mcp_app?: boolean;
- type?: string;
- }>;
- turn_message_uuids: {
- human_message_uuid: string;
- assistant_message_uuid: string;
- };
- attachments: unknown[];
- effort: string;
- files: unknown[];
- sync_sources: unknown[];
- rendering_mode: string;
- thinking_mode: string;
- create_conversation_params: {
- name: string;
- model: string;
- include_conversation_preferences: boolean;
- paprika_mode: unknown;
- compass_mode: unknown;
- is_temporary: boolean;
- enabled_imagine: boolean;
- tool_search_mode: string;
- };
-}
-
-/**
- * Stream chunk from Claude Web API
- */
-export interface ClaudeWebStreamChunk {
- type?: string;
- index?: number;
- completion?: string;
- stop_reason?: string | null;
- model?: string;
- delta?: {
- type?: string;
- text?: string;
- };
- [key: string]: unknown;
-}
-
-/**
- * Generate UUIDs for turn message tracking
- */
-export function generateMessageUUIDs() {
- return {
- human_message_uuid: randomUUID(),
- assistant_message_uuid: randomUUID(),
- };
-}
-
-/**
- * Get default tool definitions for Claude Web API
- */
-export function getDefaultTools(): ClaudeWebRequestPayload["tools"] {
- return [
- {
- name: "show_widget",
- description: "Display interactive widgets and visualizations",
- input_schema: {
- type: "object",
- properties: {
- widget_type: {
- type: "string",
- description: "Type of widget to display",
- },
- },
- },
- integration_name: "visualize",
- is_mcp_app: true,
- },
- {
- name: "read_me",
- description: "Read and reference documents",
- input_schema: {
- type: "object",
- properties: {
- file_path: {
- type: "string",
- description: "Path to the file to read",
- },
- },
- },
- integration_name: "visualize",
- is_mcp_app: false,
- },
- {
- type: "web_search_v0",
- name: "web_search",
- },
- {
- type: "artifacts_v0",
- name: "artifacts",
- },
- {
- type: "repl_v0",
- name: "repl",
- },
- { type: "widget", name: "weather_fetch" },
- { type: "widget", name: "recipe_display_v0" },
- { type: "widget", name: "places_map_display_v0" },
- { type: "widget", name: "message_compose_v1" },
- { type: "widget", name: "ask_user_input_v0" },
- { type: "widget", name: "recommend_claude_apps" },
- { type: "widget", name: "places_search" },
- { type: "widget", name: "fetch_sports_data" },
- ];
-}
-
-/**
- * Get default personalized style
- */
-export function getDefaultPersonalizedStyle(): ClaudeWebRequestPayload["personalized_styles"] {
- return [
- {
- type: "default",
- key: "Default",
- name: "Normal",
- nameKey: "normal_style_name",
- prompt: "Normal\n",
- summary: "Default responses from Claude",
- summaryKey: "normal_style_summary",
- isDefault: true,
- },
- ];
-}
-
-/**
- * Transform OpenAI format to Claude Web format
- */
-export function transformToClaude(
- body: Record<string, unknown>,
- model: string
-): ClaudeWebRequestPayload {
- const messages = Array.isArray(body.messages) ? body.messages : [];
-
- // Extract the last user message as the prompt
- let prompt = "";
- for (const msg of messages) {
- if (typeof msg === "object" && msg !== null) {
- const message = msg as Record<string, unknown>;
- if (message.role === "user") {
- prompt = String(message.content || "");
- }
- }
- }
-
- if (!prompt.trim()) {
- throw new Error("No user message found in request");
- }
-
- return {
- prompt,
- model: model || DEFAULT_CLAUDE_MODEL,
- timezone: "Asia/Jakarta",
- personalized_styles: getDefaultPersonalizedStyle(),
- locale: "en-US",
- tools: getDefaultTools(),
- turn_message_uuids: generateMessageUUIDs(),
- attachments: [],
- effort: "low",
- files: [],
- sync_sources: [],
- rendering_mode: "messages",
- thinking_mode: "off",
- create_conversation_params: {
- name: "",
- model: model || DEFAULT_CLAUDE_MODEL,
- include_conversation_preferences: true,
- paprika_mode: null,
- compass_mode: null,
- is_temporary: false,
- enabled_imagine: true,
- tool_search_mode: "auto",
- },
- };
-}
-
-/**
- * Transform Claude Web response to OpenAI format
- */
-export function transformFromClaude(
- claudeContent: string,
- model: string,
- stopReason?: string
-): Record<string, unknown> {
- return {
- id: `chatcmpl-${Date.now()}`,
- object: "chat.completion.chunk",
- created: Math.floor(Date.now() / 1000),
- model,
- choices: [
- {
- index: 0,
- delta: {
- content: claudeContent,
- },
- finish_reason: stopReason === "end_turn" ? "stop" : null,
- logprobs: null,
- },
- ],
- };
-}
diff --git a/open-sse/executors/cliproxyapi.ts b/open-sse/executors/cliproxyapi.ts
index 07bece15c0..c4b2047f2a 100644
--- a/open-sse/executors/cliproxyapi.ts
+++ b/open-sse/executors/cliproxyapi.ts
@@ -22,7 +22,6 @@ import {
type ProviderCredentials,
} from "./base.ts";
import { HTTP_STATUS, FETCH_TIMEOUT_MS } from "../config/constants.ts";
-import { getProviderPluginManifestHeader } from "../config/providerPluginManifestUrl.ts";
import { cloakThirdPartyToolNames } from "../services/claudeCodeToolRemapper.ts";
import { sanitizeClaudeToolSchemas } from "../translator/helpers/schemaCoercion.ts";
@@ -266,7 +265,6 @@ export class CliproxyapiExecutor extends BaseExecutor {
const headers: Record<string, string> = {
"Content-Type": "application/json",
- ...getProviderPluginManifestHeader(),
};
if (key) {
diff --git a/open-sse/executors/codex.ts b/open-sse/executors/codex.ts
index 6bca470eb5..12af8ae216 100644
--- a/open-sse/executors/codex.ts
+++ b/open-sse/executors/codex.ts
@@ -37,17 +37,6 @@ import { CORS_HEADERS } from "../utils/cors.ts";
import { normalizeCodexResponsesInput } from "../utils/responsesInputNormalization.ts";
import * as prl from "../utils/providerRequestLogging.ts";
import { createRequire } from "module";
-// Quota parsing/scheduling extracted to a pure leaf; re-exported for external
-// importers (handlers/chatCore/codexQuota.ts + tests).
-export {
- type CodexQuotaSnapshot,
- parseCodexQuotaHeaders,
- getCodexResetTime,
- getCodexDualWindowCooldownMs,
-} from "./codex/quota.ts";
-import { isCodexFreePlan, normalizeCodexTools } from "./codex/tools.ts";
-// Re-exported for external importers (tests + provider services).
-export { isCodexFreePlan, normalizeCodexTools } from "./codex/tools.ts";
// ─── wreq-js lazy loader ───────────────────────────────────────────────────
// wreq-js is a Rust-native module that requires platform-specific .node binaries.
@@ -115,6 +104,119 @@ function codexWebSocketUnavailableResponse(): Response {
// Ref: sub2api PR #1129 (feat(openai): split codex spark rate limiting from codex)
export { getCodexModelScope, getCodexRateLimitKey, type CodexQuotaScope };
+/**
+ * T03: Parsed quota snapshot from Codex response headers.
+ * Codex includes per-account usage windows that allow precise reset scheduling.
+ * Ref: sub2api PR #357 (feat(oauth): persist usage snapshots and window cooldown)
+ */
+export interface CodexQuotaSnapshot {
+ usage5h: number; // tokens used in 5h window
+ limit5h: number; // token limit for 5h window
+ resetAt5h: string | null; // ISO timestamp when 5h window resets
+ usage7d: number; // tokens used in 7d window
+ limit7d: number; // token limit for 7d window
+ resetAt7d: string | null; // ISO timestamp when 7d window resets
+}
+
+/**
+ * T03: Parse Codex-specific quota headers from a provider response.
+ * Returns null if none of the relevant headers are present.
+ *
+ * Extracts:
+ * x-codex-5h-usage / x-codex-5h-limit / x-codex-5h-reset-at
+ * x-codex-7d-usage / x-codex-7d-limit / x-codex-7d-reset-at
+ */
+export function parseCodexQuotaHeaders(headers: Record<string, string>): CodexQuotaSnapshot | null {
+ const usage5h = headers["x-codex-5h-usage"] ?? null;
+ const limit5h = headers["x-codex-5h-limit"] ?? null;
+ const resetAt5h = headers["x-codex-5h-reset-at"] ?? null;
+ const usage7d = headers["x-codex-7d-usage"] ?? null;
+ const limit7d = headers["x-codex-7d-limit"] ?? null;
+ const resetAt7d = headers["x-codex-7d-reset-at"] ?? null;
+
+ // Return null if none of the quota headers are present (not a quota-aware response)
+ if (!usage5h && !limit5h && !resetAt5h && !usage7d && !limit7d && !resetAt7d) {
+ return null;
+ }
+
+ return {
+ usage5h: usage5h ? parseFloat(usage5h) : 0,
+ limit5h: limit5h ? parseFloat(limit5h) : Infinity,
+ resetAt5h: resetAt5h ?? null,
+ usage7d: usage7d ? parseFloat(usage7d) : 0,
+ limit7d: limit7d ? parseFloat(limit7d) : Infinity,
+ resetAt7d: resetAt7d ?? null,
+ };
+}
+
+/**
+ * T03: Get the soonest quota reset time from a CodexQuotaSnapshot.
+ * 7d window takes priority (wider window, harder limit) but we use whichever
+ * is further in the future to avoid releasing the block too early.
+ *
+ * @returns Unix timestamp (ms) of the soonest effective reset, or null
+ */
+export function getCodexResetTime(quota: CodexQuotaSnapshot): number | null {
+ const times: number[] = [];
+ if (quota.resetAt7d) {
+ const t = new Date(quota.resetAt7d).getTime();
+ if (!isNaN(t) && t > Date.now()) times.push(t);
+ }
+ if (quota.resetAt5h) {
+ const t = new Date(quota.resetAt5h).getTime();
+ if (!isNaN(t) && t > Date.now()) times.push(t);
+ }
+ if (times.length === 0) return null;
+ return Math.max(...times); // Use furthest-out reset to avoid premature unblock
+}
+
+/**
+ * T03 (Item 3): Compute the minimum-necessary cooldown based on which window
+ * is actually exhausted. Prevents over-blocking the account:
+ *
+ * - If 7d window >= threshold: cooldown until 7d reset (weekly window exhausted)
+ * - If 5h window >= threshold: cooldown until 5h reset only (short-term limit)
+ * - Otherwise: 0 (account is healthy, no cooldown needed)
+ *
+ * Called after parsing quota headers from a successful/429 response to
+ * mark the account accordingly without overly long cooldowns.
+ *
+ * @param quota - Parsed quota snapshot from response headers
+ * @param threshold - Fraction (0-1) that triggers cooldown (default: 0.95)
+ * @returns Cooldown duration in milliseconds (0 = no cooldown needed)
+ */
+export function getCodexDualWindowCooldownMs(
+ quota: CodexQuotaSnapshot,
+ threshold = 0.95
+): { cooldownMs: number; window: "7d" | "5h" | "none" } {
+ const now = Date.now();
+
+ // Compute per-window usage ratios (0..1)
+ const ratio7d =
+ quota.limit7d > 0 && Number.isFinite(quota.limit7d) ? quota.usage7d / quota.limit7d : 0;
+ const ratio5h =
+ quota.limit5h > 0 && Number.isFinite(quota.limit5h) ? quota.usage5h / quota.limit5h : 0;
+
+ // 7d window takes priority — if the weekly budget is near-exhausted,
+ // we must wait until the weekly reset (not just 5h).
+ if (ratio7d >= threshold && quota.resetAt7d) {
+ const resetTime = new Date(quota.resetAt7d).getTime();
+ if (resetTime > now) {
+ return { cooldownMs: resetTime - now, window: "7d" };
+ }
+ }
+
+ // 5h window (primary short-term rate limit)
+ if (ratio5h >= threshold && quota.resetAt5h) {
+ const resetTime = new Date(quota.resetAt5h).getTime();
+ if (resetTime > now) {
+ return { cooldownMs: resetTime - now, window: "5h" };
+ }
+ }
+
+ return { cooldownMs: 0, window: "none" };
+}
+
// Ordered list of effort levels from lowest to highest
const EFFORT_ORDER = ["none", "low", "medium", "high", "xhigh"] as const;
type EffortLevel = (typeof EFFORT_ORDER)[number];
@@ -299,6 +401,169 @@ function repairMissingCodexFunctionCallOutputs(body: Record<string, unknown>): v
}
}
+// Responses-API hosted tool types that OpenAI/Codex executes server-side.
+// These arrive shaped as `{ type, ...params }` with no `function` object and no `name` —
+// e.g. Codex CLI injects `{ type: "image_generation", output_format: "png" }` or
+// `{ type: "namespace", name: "mcp__atlassian__", tools: [...] }` for MCP tool groups.
+// Keep them through `normalizeCodexTools` so upstream can execute them.
+const CODEX_HOSTED_TOOL_TYPES: ReadonlySet<string> = new Set([
+ "tool_search",
+ "image_generation",
+ "web_search",
+ "web_search_preview",
+ "file_search",
+ "computer",
+ "computer_use_preview",
+ "code_interpreter",
+ "mcp",
+]);
+
+// #2980: a free-plan Codex account (workspacePlanType === "free", from the OAuth
+// id_token) cannot run the server-side `image_generation` hosted tool. The Codex
+// CLI injects it into every Responses request regardless of plan, so it must be
+// dropped for free-plan accounts (mirrors CLIProxyAPI's isCodexFreePlanAuth).
+export function isCodexFreePlan(providerSpecificData: unknown): boolean {
+ if (!providerSpecificData || typeof providerSpecificData !== "object") return false;
+ const plan = (providerSpecificData as { workspacePlanType?: unknown }).workspacePlanType;
+ return typeof plan === "string" && plan.trim().toLowerCase() === "free";
+}
+
+export function normalizeCodexTools(
+ body: Record<string, unknown>,
+ options?: { dropImageGeneration?: boolean; preserveCustomTools?: boolean }
+): void {
+ if (!Array.isArray(body.tools)) return;
+
+ const validToolNames = new Set<string>();
+ body.tools = body.tools.filter((toolValue) => {
+ if (!toolValue || typeof toolValue !== "object" || Array.isArray(toolValue)) {
+ return false;
+ }
+
+ const tool = toolValue as Record<string, unknown>;
+ const toolType = typeof tool.type === "string" ? tool.type : "";
+
+ // Preserve namespace tools (MCP tool groups used by Codex/OpenAI Responses API).
+ // Codex API supports them natively; register sub-tool names for tool_choice validation.
+ if (toolType === "namespace") {
+ if (Array.isArray(tool.tools)) {
+ for (const st of tool.tools as unknown[]) {
+ if (st && typeof st === "object" && !Array.isArray(st)) {
+ const subTool = st as Record<string, unknown>;
+ const name = typeof subTool.name === "string" ? subTool.name.trim().slice(0, 128) : "";
+ if (name) validToolNames.add(name);
+ }
+ }
+ }
+ return true;
+ }
+
+ // Native Codex clients send Responses API custom tools such as apply_patch as:
+ // { type: "custom", name, format }. Preserve those only on native passthrough;
+ // translated/non-native requests can still contain provider-specific "custom"
+ // shapes that the Codex backend would reject.
+ if (toolType === "custom" && options?.preserveCustomTools === true) {
+ const name = typeof tool.name === "string" ? tool.name.trim().slice(0, 128) : "";
+ if (!name) return false;
+ tool.name = name;
+ validToolNames.add(name);
+ return true;
+ }
+
+ if (toolType !== "function") {
+ const hasFunctionObject = tool.function && typeof tool.function === "object";
+ const hasName = typeof tool.name === "string";
+ if (!toolType || hasFunctionObject || hasName) {
+ return false;
+ }
+ if (CODEX_HOSTED_TOOL_TYPES.has(toolType)) {
+ // #2980: drop the CLI-injected image_generation tool for free-plan
+ // accounts, which can't run it server-side (upstream 400 otherwise).
+ if (toolType === "image_generation" && options?.dropImageGeneration === true) {
+ return false;
+ }
+ return true;
+ }
+ console.debug(`[Codex] dropping unknown hosted tool type: ${toolType}`);
+ return false;
+ }
+
+ const rawName =
+ typeof tool.name === "string"
+ ? tool.name
+ : tool.function &&
+ typeof tool.function === "object" &&
+ !Array.isArray(tool.function) &&
+ typeof (tool.function as Record<string, unknown>).name === "string"
+ ? ((tool.function as Record<string, unknown>).name as string)
+ : "";
+ const name = rawName.trim();
+ if (!name) {
+ return false;
+ }
+
+ // Codex Responses API requires function tools in flat Responses format:
+ // { type: "function", name, description, parameters }
+ // Some clients/translators send Chat Completions shape:
+ // { type: "function", function: { name, description, parameters } }
+ // which upstream rejects with "Missing required parameter: tools[0].name".
+ // Flatten the nested `function` wrapper into top-level fields (#1914).
+ const functionObject =
+ tool.function && typeof tool.function === "object" && !Array.isArray(tool.function)
+ ? (tool.function as Record<string, unknown>)
+ : null;
+ const description =
+ typeof tool.description === "string"
+ ? tool.description
+ : typeof functionObject?.description === "string"
+ ? functionObject.description
+ : "";
+ const parameters =
+ tool.parameters && typeof tool.parameters === "object" && !Array.isArray(tool.parameters)
+ ? tool.parameters
+ : functionObject?.parameters &&
+ typeof functionObject.parameters === "object" &&
+ !Array.isArray(functionObject.parameters)
+ ? functionObject.parameters
+ : { type: "object", properties: {} };
+ const strict =
+ typeof tool.strict === "boolean"
+ ? tool.strict
+ : typeof functionObject?.strict === "boolean"
+ ? functionObject.strict
+ : undefined;
+
+ // Rewrite in-place to Responses format
+ for (const key of Object.keys(tool)) {
+ delete tool[key];
+ }
+ tool.type = "function";
+ tool.name = name.slice(0, 128);
+ if (description) tool.description = description;
+ tool.parameters = parameters;
+ if (strict !== undefined) tool.strict = strict;
+
+ validToolNames.add(name);
+ return true;
+ });
+
+ if (
+ body.tool_choice &&
+ typeof body.tool_choice === "object" &&
+ !Array.isArray(body.tool_choice)
+ ) {
+ const toolChoice = body.tool_choice as Record<string, unknown>;
+ if (toolChoice.type === "function") {
+ const rawName = typeof toolChoice.name === "string" ? toolChoice.name.trim() : "";
+ if (!rawName || !validToolNames.has(rawName)) {
+ delete body.tool_choice;
+ }
+ } else if (toolChoice.type === "local_shell") {
+ delete body.tool_choice;
+ }
+ }
+}
+
function getResponsesSubpath(endpointPath: unknown): string | null {
let normalizedEndpoint = String(endpointPath || "");
while (normalizedEndpoint.endsWith("/") && normalizedEndpoint.length > 0) {
@@ -894,7 +1159,9 @@ export class CodexExecutor extends BaseExecutor {
headers["chatgpt-account-id"] = workspaceId;
}
const clientIdentity = credentials?.providerSpecificData?.codexClientIdentity as
- CodexClientIdentity | null | undefined;
+ | CodexClientIdentity
+ | null
+ | undefined;
// Originator header — identifies the client type to the Codex backend.
// Ref: openai/codex login/src/auth/default_client.rs DEFAULT_ORIGINATOR = "codex_cli_rs"
@@ -1214,7 +1481,9 @@ export class CodexExecutor extends BaseExecutor {
applyCodexClientMetadata(
body,
credentials?.providerSpecificData?.codexClientIdentity as
- CodexClientIdentity | null | undefined
+ | CodexClientIdentity
+ | null
+ | undefined
);
}
diff --git a/open-sse/executors/codex/quota.ts b/open-sse/executors/codex/quota.ts
deleted file mode 100644
index 977f794dde..0000000000
--- a/open-sse/executors/codex/quota.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-// Codex quota-snapshot parsing + reset/cooldown scheduling (pure). Verbatim from codex.ts.
-
-/**
- * T03: Parsed quota snapshot from Codex response headers.
- * Codex includes per-account usage windows that allow precise reset scheduling.
- * Ref: sub2api PR #357 (feat(oauth): persist usage snapshots and window cooldown)
- */
-export interface CodexQuotaSnapshot {
- usage5h: number; // tokens used in 5h window
- limit5h: number; // token limit for 5h window
- resetAt5h: string | null; // ISO timestamp when 5h window resets
- usage7d: number; // tokens used in 7d window
- limit7d: number; // token limit for 7d window
- resetAt7d: string | null; // ISO timestamp when 7d window resets
-}
-
-/**
- * T03: Parse Codex-specific quota headers from a provider response.
- * Returns null if none of the relevant headers are present.
- *
- * Extracts:
- * x-codex-5h-usage / x-codex-5h-limit / x-codex-5h-reset-at
- * x-codex-7d-usage / x-codex-7d-limit / x-codex-7d-reset-at
- */
-export function parseCodexQuotaHeaders(headers: Record<string, string>): CodexQuotaSnapshot | null {
- const usage5h = headers["x-codex-5h-usage"] ?? null;
- const limit5h = headers["x-codex-5h-limit"] ?? null;
- const resetAt5h = headers["x-codex-5h-reset-at"] ?? null;
- const usage7d = headers["x-codex-7d-usage"] ?? null;
- const limit7d = headers["x-codex-7d-limit"] ?? null;
- const resetAt7d = headers["x-codex-7d-reset-at"] ?? null;
-
- // Return null if none of the quota headers are present (not a quota-aware response)
- if (!usage5h && !limit5h && !resetAt5h && !usage7d && !limit7d && !resetAt7d) {
- return null;
- }
-
- return {
- usage5h: usage5h ? parseFloat(usage5h) : 0,
- limit5h: limit5h ? parseFloat(limit5h) : Infinity,
- resetAt5h: resetAt5h ?? null,
- usage7d: usage7d ? parseFloat(usage7d) : 0,
- limit7d: limit7d ? parseFloat(limit7d) : Infinity,
- resetAt7d: resetAt7d ?? null,
- };
-}
-
-/**
- * T03: Get the soonest quota reset time from a CodexQuotaSnapshot.
- * 7d window takes priority (wider window, harder limit) but we use whichever
- * is further in the future to avoid releasing the block too early.
- *
- * @returns Unix timestamp (ms) of the soonest effective reset, or null
- */
-export function getCodexResetTime(quota: CodexQuotaSnapshot): number | null {
- const times: number[] = [];
- if (quota.resetAt7d) {
- const t = new Date(quota.resetAt7d).getTime();
- if (!isNaN(t) && t > Date.now()) times.push(t);
- }
- if (quota.resetAt5h) {
- const t = new Date(quota.resetAt5h).getTime();
- if (!isNaN(t) && t > Date.now()) times.push(t);
- }
- if (times.length === 0) return null;
- return Math.max(...times); // Use furthest-out reset to avoid premature unblock
-}
-
-/**
- * T03 (Item 3): Compute the minimum-necessary cooldown based on which window
- * is actually exhausted. Prevents over-blocking the account:
- *
- * - If 7d window >= threshold: cooldown until 7d reset (weekly window exhausted)
- * - If 5h window >= threshold: cooldown until 5h reset only (short-term limit)
- * - Otherwise: 0 (account is healthy, no cooldown needed)
- *
- * Called after parsing quota headers from a successful/429 response to
- * mark the account accordingly without overly long cooldowns.
- *
- * @param quota - Parsed quota snapshot from response headers
- * @param threshold - Fraction (0-1) that triggers cooldown (default: 0.95)
- * @returns Cooldown duration in milliseconds (0 = no cooldown needed)
- */
-export function getCodexDualWindowCooldownMs(
- quota: CodexQuotaSnapshot,
- threshold = 0.95
-): { cooldownMs: number; window: "7d" | "5h" | "none" } {
- const now = Date.now();
-
- // Compute per-window usage ratios (0..1)
- const ratio7d =
- quota.limit7d > 0 && Number.isFinite(quota.limit7d) ? quota.usage7d / quota.limit7d : 0;
- const ratio5h =
- quota.limit5h > 0 && Number.isFinite(quota.limit5h) ? quota.usage5h / quota.limit5h : 0;
-
- // 7d window takes priority — if the weekly budget is near-exhausted,
- // we must wait until the weekly reset (not just 5h).
- if (ratio7d >= threshold && quota.resetAt7d) {
- const resetTime = new Date(quota.resetAt7d).getTime();
- if (resetTime > now) {
- return { cooldownMs: resetTime - now, window: "7d" };
- }
- }
-
- // 5h window (primary short-term rate limit)
- if (ratio5h >= threshold && quota.resetAt5h) {
- const resetTime = new Date(quota.resetAt5h).getTime();
- if (resetTime > now) {
- return { cooldownMs: resetTime - now, window: "5h" };
- }
- }
-
- return { cooldownMs: 0, window: "none" };
-}
diff --git a/open-sse/executors/codex/tools.ts b/open-sse/executors/codex/tools.ts
deleted file mode 100644
index 3337000359..0000000000
--- a/open-sse/executors/codex/tools.ts
+++ /dev/null
@@ -1,165 +0,0 @@
-// Codex Responses-API tool normalization (hosted-tool passthrough + free-plan gating).
-// Extracted verbatim from codex.ts. Self-contained (console.debug only).
-
-// Responses-API hosted tool types that OpenAI/Codex executes server-side.
-// These arrive shaped as `{ type, ...params }` with no `function` object and no `name` —
-// e.g. Codex CLI injects `{ type: "image_generation", output_format: "png" }` or
-// `{ type: "namespace", name: "mcp__atlassian__", tools: [...] }` for MCP tool groups.
-// Keep them through `normalizeCodexTools` so upstream can execute them.
-export const CODEX_HOSTED_TOOL_TYPES: ReadonlySet<string> = new Set([
- "tool_search",
- "image_generation",
- "web_search",
- "web_search_preview",
- "file_search",
- "computer",
- "computer_use_preview",
- "code_interpreter",
- "mcp",
-]);
-
-// #2980: a free-plan Codex account (workspacePlanType === "free", from the OAuth
-// id_token) cannot run the server-side `image_generation` hosted tool. The Codex
-// CLI injects it into every Responses request regardless of plan, so it must be
-// dropped for free-plan accounts (mirrors CLIProxyAPI's isCodexFreePlanAuth).
-export function isCodexFreePlan(providerSpecificData: unknown): boolean {
- if (!providerSpecificData || typeof providerSpecificData !== "object") return false;
- const plan = (providerSpecificData as { workspacePlanType?: unknown }).workspacePlanType;
- return typeof plan === "string" && plan.trim().toLowerCase() === "free";
-}
-
-export function normalizeCodexTools(
- body: Record<string, unknown>,
- options?: { dropImageGeneration?: boolean; preserveCustomTools?: boolean }
-): void {
- if (!Array.isArray(body.tools)) return;
-
- const validToolNames = new Set<string>();
- body.tools = body.tools.filter((toolValue) => {
- if (!toolValue || typeof toolValue !== "object" || Array.isArray(toolValue)) {
- return false;
- }
-
- const tool = toolValue as Record<string, unknown>;
- const toolType = typeof tool.type === "string" ? tool.type : "";
-
- // Preserve namespace tools (MCP tool groups used by Codex/OpenAI Responses API).
- // Codex API supports them natively; register sub-tool names for tool_choice validation.
- if (toolType === "namespace") {
- if (Array.isArray(tool.tools)) {
- for (const st of tool.tools as unknown[]) {
- if (st && typeof st === "object" && !Array.isArray(st)) {
- const subTool = st as Record<string, unknown>;
- const name = typeof subTool.name === "string" ? subTool.name.trim().slice(0, 128) : "";
- if (name) validToolNames.add(name);
- }
- }
- }
- return true;
- }
-
- // Native Codex clients send Responses API custom tools such as apply_patch as:
- // { type: "custom", name, format }. Preserve those only on native passthrough;
- // translated/non-native requests can still contain provider-specific "custom"
- // shapes that the Codex backend would reject.
- if (toolType === "custom" && options?.preserveCustomTools === true) {
- const name = typeof tool.name === "string" ? tool.name.trim().slice(0, 128) : "";
- if (!name) return false;
- tool.name = name;
- validToolNames.add(name);
- return true;
- }
-
- if (toolType !== "function") {
- const hasFunctionObject = tool.function && typeof tool.function === "object";
- const hasName = typeof tool.name === "string";
- if (!toolType || hasFunctionObject || hasName) {
- return false;
- }
- if (CODEX_HOSTED_TOOL_TYPES.has(toolType)) {
- // #2980: drop the CLI-injected image_generation tool for free-plan
- // accounts, which can't run it server-side (upstream 400 otherwise).
- if (toolType === "image_generation" && options?.dropImageGeneration === true) {
- return false;
- }
- return true;
- }
- console.debug(`[Codex] dropping unknown hosted tool type: ${toolType}`);
- return false;
- }
-
- const rawName =
- typeof tool.name === "string"
- ? tool.name
- : tool.function &&
- typeof tool.function === "object" &&
- !Array.isArray(tool.function) &&
- typeof (tool.function as Record<string, unknown>).name === "string"
- ? ((tool.function as Record<string, unknown>).name as string)
- : "";
- const name = rawName.trim();
- if (!name) {
- return false;
- }
-
- // Codex Responses API requires function tools in flat Responses format:
- // { type: "function", name, description, parameters }
- // Some clients/translators send Chat Completions shape:
- // { type: "function", function: { name, description, parameters } }
- // which upstream rejects with "Missing required parameter: tools[0].name".
- // Flatten the nested `function` wrapper into top-level fields (#1914).
- const functionObject =
- tool.function && typeof tool.function === "object" && !Array.isArray(tool.function)
- ? (tool.function as Record<string, unknown>)
- : null;
- const description =
- typeof tool.description === "string"
- ? tool.description
- : typeof functionObject?.description === "string"
- ? functionObject.description
- : "";
- const parameters =
- tool.parameters && typeof tool.parameters === "object" && !Array.isArray(tool.parameters)
- ? tool.parameters
- : functionObject?.parameters &&
- typeof functionObject.parameters === "object" &&
- !Array.isArray(functionObject.parameters)
- ? functionObject.parameters
- : { type: "object", properties: {} };
- const strict =
- typeof tool.strict === "boolean"
- ? tool.strict
- : typeof functionObject?.strict === "boolean"
- ? functionObject.strict
- : undefined;
-
- // Rewrite in-place to Responses format
- for (const key of Object.keys(tool)) {
- delete tool[key];
- }
- tool.type = "function";
- tool.name = name.slice(0, 128);
- if (description) tool.description = description;
- tool.parameters = parameters;
- if (strict !== undefined) tool.strict = strict;
-
- validToolNames.add(name);
- return true;
- });
-
- if (
- body.tool_choice &&
- typeof body.tool_choice === "object" &&
- !Array.isArray(body.tool_choice)
- ) {
- const toolChoice = body.tool_choice as Record<string, unknown>;
- if (toolChoice.type === "function") {
- const rawName = typeof toolChoice.name === "string" ? toolChoice.name.trim() : "";
- if (!rawName || !validToolNames.has(rawName)) {
- delete body.tool_choice;
- }
- } else if (toolChoice.type === "local_shell") {
- delete body.tool_choice;
- }
- }
-}
diff --git a/open-sse/executors/cursor.ts b/open-sse/executors/cursor.ts
index ad7a9b68a6..62cf10f348 100644
--- a/open-sse/executors/cursor.ts
+++ b/open-sse/executors/cursor.ts
@@ -38,7 +38,11 @@ import {
type McpToolDefinition,
type OpenAITool,
} from "../utils/cursorAgentProtobuf.ts";
-import { resolveCursorImages, extractImageUrls, CursorImageError } from "../utils/cursorImages.ts";
+import {
+ resolveCursorImages,
+ extractImageUrls,
+ CursorImageError,
+} from "../utils/cursorImages.ts";
import {
estimateInputTokens,
estimateOutputTokens,
@@ -58,18 +62,6 @@ import crypto from "crypto";
import * as fs from "node:fs";
import * as zlib from "node:zlib";
import { promisify } from "node:util";
-import { toolChoiceDirectiveLine, buildCursorOutputConstraints } from "./cursor/prompt.ts";
-import {
- isComposerModel,
- visibleComposerContentFromThinking,
- composerReasoningRemainder,
-} from "./cursor/composer.ts";
-// Composer helpers re-exported for external importers (tests).
-export {
- isComposerModel,
- visibleComposerContentFromThinking,
- composerReasoningRemainder,
-} from "./cursor/composer.ts";
// Reject reason text aligned with kaitranntt/CLIProxyAPIPlus — proven to
// keep cursor's model from retrying the same built-in tool indefinitely.
@@ -97,6 +89,78 @@ const TOOL_COMMIT_DIRECTIVE = [
// non-existent switch_mode tool and measurably LOWERED the tool-call rate in
// live A/B (56% vs 69%), so it is intentionally not ported.
+function isRecordLike(v: unknown): v is Record<string, unknown> {
+ return typeof v === "object" && v !== null;
+}
+
+/**
+ * Translate OpenAI `tool_choice` into an extra directive line — cursor's agent
+ * endpoint has no native equivalent. `"required"` forces some tool; a specific
+ * `{type:"function", function:{name}}` forces that tool. `"auto"`/`"none"`/
+ * absent add nothing here ("none" is handled by dropping tools entirely).
+ * Ported from composer-api (directToolChoiceHint / tool_choice === "required").
+ */
+function toolChoiceDirectiveLine(toolChoice: unknown): string {
+ if (toolChoice === "required") {
+ return "\nYou MUST call at least one of the available tools now; do not answer without calling a tool.";
+ }
+ if (
+ isRecordLike(toolChoice) &&
+ toolChoice.type === "function" &&
+ isRecordLike(toolChoice.function) &&
+ typeof toolChoice.function.name === "string" &&
+ toolChoice.function.name
+ ) {
+ return `\nYou MUST call the \`${toolChoice.function.name}\` tool now and not any other tool.`;
+ }
+ return "";
+}
+
+/**
+ * Build an OUTPUT CONSTRAINTS block from OpenAI request params that cursor's
+ * agent endpoint silently ignores (response_format / max_tokens / stop), so
+ * they're surfaced to the model as prompt instructions instead. Ported from
+ * composer-api (appendChatOptions / appendJsonConstraint / appendStopConstraint).
+ * Returns "" when no constraints apply.
+ */
+function buildCursorOutputConstraints(body: {
+ max_tokens?: unknown;
+ max_completion_tokens?: unknown;
+ stop?: unknown;
+ response_format?: unknown;
+}): string {
+ const constraints: string[] = [];
+
+ const rawMax = body.max_completion_tokens ?? body.max_tokens;
+ const maxTokens = typeof rawMax === "number" && Number.isFinite(rawMax) ? Math.floor(rawMax) : 0;
+ if (maxTokens > 0) {
+ constraints.push(`Keep the answer within about ${maxTokens} output tokens.`);
+ }
+
+ const stop = body.stop;
+ if (typeof stop === "string" && stop) {
+ constraints.push(`Do not include any text at or after this stop sequence: ${stop}`);
+ } else if (Array.isArray(stop) && stop.length) {
+ constraints.push(`Stop before any of these sequences: ${stop.filter(Boolean).join(", ")}`);
+ }
+
+ const fmt = body.response_format;
+ if (isRecordLike(fmt)) {
+ if (fmt.type === "json_object") {
+ constraints.push("Return a single valid JSON object and no surrounding prose or code fences.");
+ } else if (fmt.type === "json_schema") {
+ const js = isRecordLike(fmt.json_schema) ? fmt.json_schema.schema : fmt.schema;
+ constraints.push(
+ `Return only valid JSON (no prose or code fences) matching this schema: ${JSON.stringify(js ?? fmt)}`
+ );
+ }
+ }
+
+ return constraints.length
+ ? `\n\nOUTPUT CONSTRAINTS:\n${constraints.map((c) => `- ${c}`).join("\n")}`
+ : "";
+}
+
/**
* Build the ExecClientMessage frame that responds to a built-in tool request.
* Returns null for the request_context handshake (caller handles separately
@@ -247,6 +311,61 @@ function tryParseJsonError(payload: Buffer): { message: string; status: number }
}
}
+// ─── Composer thinking-as-content decoding ─────────────────────────────────
+//
+// The Cursor `composer-*` family encodes its visible reply inside the
+// `thinking` field, marked off from the (private) chain-of-thought by a
+// final `</think>` sentinel. Everything AFTER the last `</think>` is the
+// user-facing reply; the prefix must stay hidden.
+//
+// Ported from decolua/9router#1310 by Noé Rivera. Same algorithm, adapted
+// to OmniRoute's StreamCtx-based pipeline so streaming + non-streaming
+// share the accumulation path.
+
+const COMPOSER_THINK_END = "</think>";
+
+export function isComposerModel(model: string | undefined | null): boolean {
+ const id = String(model ?? "")
+ .split("/")
+ .pop();
+ return /^composer(?:-|$)/i.test(id ?? "");
+}
+
+// Composer's protobuf sometimes wraps the visible suffix in sentinel tags:
+// `<|final|>` (full-width pipes) or `<|final|>` (ASCII), optionally closed
+// with a matching `<|/final|>` / `<|/final|>`. These are protocol-internal
+// and must never leak to OpenAI-compatible clients (decolua/9router#1316).
+const COMPOSER_OPEN_MARKER = /^\s*<[||]\s*final\s*[||]>\s*/i;
+const COMPOSER_CLOSE_MARKER = /\s*<[||]\s*\/\s*final\s*[||]>\s*$/i;
+const COMPOSER_PARTIAL_OPEN = /^\s*<(?![||/])/;
+const COMPOSER_PARTIAL_OPEN_PIPE = /^\s*<[||][^>]*$/;
+
+export function visibleComposerContentFromThinking(thinking: string): string {
+ if (!thinking) return "";
+ const endIdx = thinking.lastIndexOf(COMPOSER_THINK_END);
+ if (endIdx < 0) return "";
+ let visible = thinking.slice(endIdx + COMPOSER_THINK_END.length).trimStart();
+ if (COMPOSER_OPEN_MARKER.test(visible)) {
+ visible = visible.replace(COMPOSER_OPEN_MARKER, "");
+ } else if (
+ COMPOSER_PARTIAL_OPEN.test(visible) ||
+ COMPOSER_PARTIAL_OPEN_PIPE.test(visible)
+ ) {
+ // A streamed chunk delivered only a partial opening marker (e.g. `<` or
+ // `<|fin`). Hold back everything until more data arrives so the marker
+ // fragment never leaks as content.
+ return "";
+ }
+ return visible.replace(COMPOSER_CLOSE_MARKER, "").trim();
+}
+
+export function composerReasoningRemainder(thinking: string): string {
+ if (!thinking) return "";
+ const endIdx = thinking.lastIndexOf(COMPOSER_THINK_END);
+ if (endIdx < 0) return thinking;
+ return thinking.slice(0, endIdx);
+}
+
// ─── Phase 4: streaming dispatch context ───────────────────────────────────
//
// One StreamCtx flows through a single execute() call. It owns the live
@@ -557,19 +676,11 @@ export function processFrame(
ctx.totalText += parseOut.safeDelta;
emitChunk(ctx, { content: parseOut.safeDelta });
}
- if (
- parseOut.ready &&
- parseOut.toolCalls.length > 0 &&
- !ctx.composerInlineToolCallsEmitted
- ) {
+ if (parseOut.ready && parseOut.toolCalls.length > 0 && !ctx.composerInlineToolCallsEmitted) {
ctx.composerInlineToolCallsEmitted = true;
for (const tc of parseOut.toolCalls) {
const toolCallIndex = ctx.emittedToolCallIndex++;
- ctx.toolCalls.push({
- id: tc.id,
- name: tc.function.name,
- argumentsJson: tc.function.arguments,
- });
+ ctx.toolCalls.push({ id: tc.id, name: tc.function.name, argumentsJson: tc.function.arguments });
emitChunk(ctx, {
tool_calls: [
{
@@ -1324,7 +1435,11 @@ export class CursorExecutor extends BaseExecutor {
// parser state never reached "ready"), try a full non-streaming parse on
// the accumulated visible content so we still emit structured tool_calls
// and don't leak the markers as plain text.
- if (isComposerModel(ctx.model) && !ctx.composerInlineToolCallsEmitted && ctx.totalText) {
+ if (
+ isComposerModel(ctx.model) &&
+ !ctx.composerInlineToolCallsEmitted &&
+ ctx.totalText
+ ) {
const parsed = parseComposerToolCalls(ctx.totalText);
if (parsed.toolCalls.length > 0) {
ctx.composerInlineToolCallsEmitted = true;
@@ -1332,11 +1447,7 @@ export class CursorExecutor extends BaseExecutor {
ctx.totalText = parsed.content;
for (const tc of parsed.toolCalls) {
const toolCallIndex = ctx.emittedToolCallIndex++;
- ctx.toolCalls.push({
- id: tc.id,
- name: tc.function.name,
- argumentsJson: tc.function.arguments,
- });
+ ctx.toolCalls.push({ id: tc.id, name: tc.function.name, argumentsJson: tc.function.arguments });
emitChunk(ctx, {
tool_calls: [
{
@@ -1390,17 +1501,17 @@ export class CursorExecutor extends BaseExecutor {
// Composer DeepSeek inline tool-call fallback (decolua/9router#1335): for
// non-streaming requests, the streaming parser never runs — parse the
// accumulated visible content once here instead.
- if (isComposerModel(ctx.model) && !ctx.composerInlineToolCallsEmitted && ctx.totalText) {
+ if (
+ isComposerModel(ctx.model) &&
+ !ctx.composerInlineToolCallsEmitted &&
+ ctx.totalText
+ ) {
const parsed = parseComposerToolCalls(ctx.totalText);
if (parsed.toolCalls.length > 0) {
ctx.composerInlineToolCallsEmitted = true;
ctx.totalText = parsed.content;
for (const tc of parsed.toolCalls) {
- ctx.toolCalls.push({
- id: tc.id,
- name: tc.function.name,
- argumentsJson: tc.function.arguments,
- });
+ ctx.toolCalls.push({ id: tc.id, name: tc.function.name, argumentsJson: tc.function.arguments });
}
}
}
diff --git a/open-sse/executors/cursor/composer.ts b/open-sse/executors/cursor/composer.ts
deleted file mode 100644
index 73d590992b..0000000000
--- a/open-sse/executors/cursor/composer.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-// Composer thinking-as-content decoding for the Cursor executor (verbatim, no host imports).
-
-// ─── Composer thinking-as-content decoding ─────────────────────────────────
-//
-// The Cursor `composer-*` family encodes its visible reply inside the
-// `thinking` field, marked off from the (private) chain-of-thought by a
-// final `</think>` sentinel. Everything AFTER the last `</think>` is the
-// user-facing reply; the prefix must stay hidden.
-//
-// Ported from decolua/9router#1310 by Noé Rivera. Same algorithm, adapted
-// to OmniRoute's StreamCtx-based pipeline so streaming + non-streaming
-// share the accumulation path.
-
-const COMPOSER_THINK_END = "</think>";
-
-export function isComposerModel(model: string | undefined | null): boolean {
- const id = String(model ?? "")
- .split("/")
- .pop();
- return /^composer(?:-|$)/i.test(id ?? "");
-}
-
-// Composer's protobuf sometimes wraps the visible suffix in sentinel tags:
-// `<|final|>` (full-width pipes) or `<|final|>` (ASCII), optionally closed
-// with a matching `<|/final|>` / `<|/final|>`. These are protocol-internal
-// and must never leak to OpenAI-compatible clients (decolua/9router#1316).
-const COMPOSER_OPEN_MARKER = /^\s*<[||]\s*final\s*[||]>\s*/i;
-const COMPOSER_CLOSE_MARKER = /\s*<[||]\s*\/\s*final\s*[||]>\s*$/i;
-const COMPOSER_PARTIAL_OPEN = /^\s*<(?![||/])/;
-const COMPOSER_PARTIAL_OPEN_PIPE = /^\s*<[||][^>]*$/;
-
-export function visibleComposerContentFromThinking(thinking: string): string {
- if (!thinking) return "";
- const endIdx = thinking.lastIndexOf(COMPOSER_THINK_END);
- if (endIdx < 0) return "";
- let visible = thinking.slice(endIdx + COMPOSER_THINK_END.length).trimStart();
- if (COMPOSER_OPEN_MARKER.test(visible)) {
- visible = visible.replace(COMPOSER_OPEN_MARKER, "");
- } else if (COMPOSER_PARTIAL_OPEN.test(visible) || COMPOSER_PARTIAL_OPEN_PIPE.test(visible)) {
- // A streamed chunk delivered only a partial opening marker (e.g. `<` or
- // `<|fin`). Hold back everything until more data arrives so the marker
- // fragment never leaks as content.
- return "";
- }
- return visible.replace(COMPOSER_CLOSE_MARKER, "").trim();
-}
-
-export function composerReasoningRemainder(thinking: string): string {
- if (!thinking) return "";
- const endIdx = thinking.lastIndexOf(COMPOSER_THINK_END);
- if (endIdx < 0) return thinking;
- return thinking.slice(0, endIdx);
-}
diff --git a/open-sse/executors/cursor/prompt.ts b/open-sse/executors/cursor/prompt.ts
deleted file mode 100644
index ae93452374..0000000000
--- a/open-sse/executors/cursor/prompt.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-// Pure prompt/constraint builders for the Cursor executor (verbatim, no host imports).
-
-export function isRecordLike(v: unknown): v is Record<string, unknown> {
- return typeof v === "object" && v !== null;
-}
-
-/**
- * Translate OpenAI `tool_choice` into an extra directive line — cursor's agent
- * endpoint has no native equivalent. `"required"` forces some tool; a specific
- * `{type:"function", function:{name}}` forces that tool. `"auto"`/`"none"`/
- * absent add nothing here ("none" is handled by dropping tools entirely).
- * Ported from composer-api (directToolChoiceHint / tool_choice === "required").
- */
-export function toolChoiceDirectiveLine(toolChoice: unknown): string {
- if (toolChoice === "required") {
- return "\nYou MUST call at least one of the available tools now; do not answer without calling a tool.";
- }
- if (
- isRecordLike(toolChoice) &&
- toolChoice.type === "function" &&
- isRecordLike(toolChoice.function) &&
- typeof toolChoice.function.name === "string" &&
- toolChoice.function.name
- ) {
- return `\nYou MUST call the \`${toolChoice.function.name}\` tool now and not any other tool.`;
- }
- return "";
-}
-
-/**
- * Build an OUTPUT CONSTRAINTS block from OpenAI request params that cursor's
- * agent endpoint silently ignores (response_format / max_tokens / stop), so
- * they're surfaced to the model as prompt instructions instead. Ported from
- * composer-api (appendChatOptions / appendJsonConstraint / appendStopConstraint).
- * Returns "" when no constraints apply.
- */
-export function buildCursorOutputConstraints(body: {
- max_tokens?: unknown;
- max_completion_tokens?: unknown;
- stop?: unknown;
- response_format?: unknown;
-}): string {
- const constraints: string[] = [];
-
- const rawMax = body.max_completion_tokens ?? body.max_tokens;
- const maxTokens = typeof rawMax === "number" && Number.isFinite(rawMax) ? Math.floor(rawMax) : 0;
- if (maxTokens > 0) {
- constraints.push(`Keep the answer within about ${maxTokens} output tokens.`);
- }
-
- const stop = body.stop;
- if (typeof stop === "string" && stop) {
- constraints.push(`Do not include any text at or after this stop sequence: ${stop}`);
- } else if (Array.isArray(stop) && stop.length) {
- constraints.push(`Stop before any of these sequences: ${stop.filter(Boolean).join(", ")}`);
- }
-
- const fmt = body.response_format;
- if (isRecordLike(fmt)) {
- if (fmt.type === "json_object") {
- constraints.push(
- "Return a single valid JSON object and no surrounding prose or code fences."
- );
- } else if (fmt.type === "json_schema") {
- const js = isRecordLike(fmt.json_schema) ? fmt.json_schema.schema : fmt.schema;
- constraints.push(
- `Return only valid JSON (no prose or code fences) matching this schema: ${JSON.stringify(js ?? fmt)}`
- );
- }
- }
-
- return constraints.length
- ? `\n\nOUTPUT CONSTRAINTS:\n${constraints.map((c) => `- ${c}`).join("\n")}`
- : "";
-}
diff --git a/open-sse/executors/deepseek-web-with-auto-refresh.ts b/open-sse/executors/deepseek-web-with-auto-refresh.ts
index bd65532947..167823902d 100644
--- a/open-sse/executors/deepseek-web-with-auto-refresh.ts
+++ b/open-sse/executors/deepseek-web-with-auto-refresh.ts
@@ -125,53 +125,24 @@ export class DeepSeekWebWithAutoRefreshExecutor extends DeepSeekWebExecutor {
return super.execute(input);
}
- /**
- * Refresh the session once and re-run the base executor. Returns the retried
- * result, or `null` when the refresh itself fails (dead userToken) so the
- * caller surfaces the original failure instead of looping.
- */
- private async refreshAndRetry(
- input: ExecuteInput
- ): Promise<Awaited<ReturnType<typeof this.executeBase>> | null> {
- this.retryCount++;
- try {
- await this.doRefreshSession();
- return await this.executeBase(input);
- } catch (refreshError) {
- console.error(
- `[DeepSeek-WEB] Session refresh failed (attempt ${this.retryCount}/${this.maxRetries}):`,
- refreshError
- );
- return null;
- }
- }
-
private async executeWithRetry(input: ExecuteInput) {
try {
- const result = await this.executeBase(input);
-
- // The base DeepSeekWebExecutor never throws on an upstream auth failure —
- // it converts 401/403 into a returned error Response (and deletes the stale
- // access token). Detect that here so auto-refresh actually fires; relying
- // only on the thrown-error catch below left the retry path dead, so a stale
- // access token surfaced a 401 to the client on every refresh boundary
- // instead of self-healing.
- const status = result?.response?.status;
- if ((status === 401 || status === 403) && this.retryCount < this.maxRetries) {
- const retried = await this.refreshAndRetry(input);
- return retried ?? result;
- }
-
- return result;
+ return await this.executeBase(input);
} catch (error: unknown) {
- // Defensive: keep handling genuinely thrown failures (e.g. a network error
- // that escapes the base) even though the base normally returns Responses.
const msg = error instanceof Error ? error.message : String(error);
const isUnauthorized =
msg.includes("401") || msg.includes("Unauthorized") || msg.includes("expired");
if (isUnauthorized && this.retryCount < this.maxRetries) {
- const retried = await this.refreshAndRetry(input);
- if (retried) return retried;
+ this.retryCount++;
+ try {
+ await this.doRefreshSession();
+ return await this.executeBase(input);
+ } catch (refreshError) {
+ console.error(
+ `[DeepSeek-WEB] Session refresh failed (attempt ${this.retryCount}/${this.maxRetries}):`,
+ refreshError
+ );
+ }
}
if (msg.includes("429") || msg.includes("Rate limit")) {
console.warn("[DeepSeek-WEB] Rate limited:", msg);
diff --git a/open-sse/executors/deepseek-web.ts b/open-sse/executors/deepseek-web.ts
index 7b6e5e0167..bdc6ad1a15 100644
--- a/open-sse/executors/deepseek-web.ts
+++ b/open-sse/executors/deepseek-web.ts
@@ -7,27 +7,11 @@ import {
buildToolConversationPrompt,
} from "../translator/deepseekWebTools.ts";
import { sanitizeErrorMessage } from "../utils/error.ts";
-import {
- isThinkingModel,
- isSearchModel,
- formatStreamContent,
- appendSearchCitations,
- type DeepSeekSearchResult,
-} from "./deepseek-web/stream-format.ts";
export const DEEPSEEK_WEB_BASE = "https://chat.deepseek.com";
const DEEPSEEK_API_BASE = `${DEEPSEEK_WEB_BASE}/api`;
const COMPLETION_URL = `${DEEPSEEK_API_BASE}/v0/chat/completion`;
-// Fingerprint headers the chat.deepseek.com web client sends on every /api/v0/*
-// request. Kept in sync with a real captured completion request (client v2.0.0):
-// the 2.0.0 web build DROPPED the legacy `X-App-Version` build stamp and ADDED
-// `X-Client-Bundle-Id`. Sending the stale `X-App-Version` (and the old 1.8.0
-// version) is itself a bot-detection signal, so match the current client exactly.
-// NOTE: the live client also sends `x-hif-leim`, a signed client-attestation
-// token generated by obfuscated JS. It is intentionally omitted — reproducing it
-// requires porting that JS, and it is not currently enforced by the completion
-// endpoint. Revisit if requests start failing a client-attestation check.
const FAKE_HEADERS: Record<string, string> = {
Accept: "*/*",
"Accept-Encoding": "gzip, deflate, br, zstd",
@@ -36,10 +20,10 @@ const FAKE_HEADERS: Record<string, string> = {
Referer: `${DEEPSEEK_WEB_BASE}/`,
"User-Agent":
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36",
- "X-Client-Bundle-Id": "com.deepseek.chat",
+ "X-App-Version": "20241129.1",
"X-Client-Locale": "en-US",
"X-Client-Platform": "web",
- "X-Client-Version": "2.0.0",
+ "X-Client-Version": "1.8.0",
};
// ── Types ────────────────────────────────────────────────────────────────
@@ -160,6 +144,46 @@ async function solvePow(challenge: PowChallenge): Promise<string> {
// ── SSE Transform (DeepSeek → OpenAI) ───────────────────────────────────
+function isThinkingModel(model: string): boolean {
+ const m = model.toLowerCase();
+ return m.includes("think") || m.includes("r1") || m.includes("reason");
+}
+
+function isSearchModel(model: string): boolean {
+ const m = model.toLowerCase();
+ return m.includes("search") || m.includes("fold");
+}
+
+function cleanDeepSeekToken(text: string): string {
+ return text.replace(/FINISHED/g, "").replace(/^(SEARCH|WEB_SEARCH|SEARCHING)\s*/i, "");
+}
+
+function formatStreamContent(raw: string, model: string): string {
+ let text = cleanDeepSeekToken(raw);
+ if (!isSearchModel(model)) return text;
+ if (model.toLowerCase().includes("search-silent")) {
+ return text.replace(/\[citation:(\d+)\]/g, "");
+ }
+ return text.replace(/\[citation:(\d+)\]/g, "[$1]");
+}
+
+interface DeepSeekSearchResult {
+ cite_index?: number;
+ title?: string;
+ url?: string;
+}
+
+function appendSearchCitations(searchResults: DeepSeekSearchResult[], model: string): string {
+ if (searchResults.length === 0 || model.toLowerCase().includes("search-silent")) {
+ return "";
+ }
+ return searchResults
+ .filter((r) => r.cite_index)
+ .sort((a, b) => (a.cite_index || 0) - (b.cite_index || 0))
+ .map((r) => `[${r.cite_index}]: [${r.title}](${r.url})`)
+ .join("\n");
+}
+
function transformSSE(deepseekStream: ReadableStream, model: string): ReadableStream {
const encoder = new TextEncoder();
const decoder = new TextDecoder();
diff --git a/open-sse/executors/deepseek-web/stream-format.ts b/open-sse/executors/deepseek-web/stream-format.ts
deleted file mode 100644
index 44a4e5232b..0000000000
--- a/open-sse/executors/deepseek-web/stream-format.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-// Pure DeepSeek stream content/citation formatting. Verbatim from deepseek-web.ts.
-
-export function isThinkingModel(model: string): boolean {
- const m = model.toLowerCase();
- return m.includes("think") || m.includes("r1") || m.includes("reason");
-}
-
-export function isSearchModel(model: string): boolean {
- const m = model.toLowerCase();
- return m.includes("search") || m.includes("fold");
-}
-
-export function cleanDeepSeekToken(text: string): string {
- return text.replace(/FINISHED/g, "").replace(/^(SEARCH|WEB_SEARCH|SEARCHING)\s*/i, "");
-}
-
-export function formatStreamContent(raw: string, model: string): string {
- let text = cleanDeepSeekToken(raw);
- if (!isSearchModel(model)) return text;
- if (model.toLowerCase().includes("search-silent")) {
- return text.replace(/\[citation:(\d+)\]/g, "");
- }
- return text.replace(/\[citation:(\d+)\]/g, "[$1]");
-}
-
-export interface DeepSeekSearchResult {
- cite_index?: number;
- title?: string;
- url?: string;
-}
-
-export function appendSearchCitations(
- searchResults: DeepSeekSearchResult[],
- model: string
-): string {
- if (searchResults.length === 0 || model.toLowerCase().includes("search-silent")) {
- return "";
- }
- return searchResults
- .filter((r) => r.cite_index)
- .sort((a, b) => (a.cite_index || 0) - (b.cite_index || 0))
- .map((r) => `[${r.cite_index}]: [${r.title}](${r.url})`)
- .join("\n");
-}
diff --git a/open-sse/executors/default.ts b/open-sse/executors/default.ts
index afabd75645..cbdb8d90bf 100644
--- a/open-sse/executors/default.ts
+++ b/open-sse/executors/default.ts
@@ -24,23 +24,17 @@ import {
isClaudeCodeCompatible,
} from "../services/provider.ts";
import { sanitizeQwenThinkingToolChoice } from "../services/qwenThinking.ts";
-import { getSapResourceGroup } from "../config/sap.ts";
-import {
- normalizeBailianMessagesUrl,
- normalizeDataRobotChatUrl,
- normalizeAzureAiChatUrl,
- normalizeWatsonxChatUrl,
- normalizeOciChatUrl,
- normalizeSapChatUrl,
- normalizeXiaomiMimoChatUrl,
- normalizeOpenAIChatUrl,
- getOpenRouterConnectionPreset,
-} from "./default/urlNormalizers.ts";
+import { buildDataRobotChatUrl } from "../config/datarobot.ts";
+import { buildAzureAiChatUrl } from "../config/azureAi.ts";
+import { buildWatsonxChatUrl } from "../config/watsonx.ts";
+import { buildOciChatUrl } from "../config/oci.ts";
+import { buildSapChatUrl, getSapResourceGroup } from "../config/sap.ts";
import { buildMaritalkChatUrl } from "../config/maritalk.ts";
import { LOCAL_PROVIDERS } from "@/shared/constants/providers";
import { isForbiddenCustomHeaderName } from "@/shared/constants/upstreamHeaders";
import { getClaudeCodeCompatibleRequestDefaults } from "@/lib/providers/requestDefaults";
import { buildClineHeaders } from "@/shared/utils/clineAuth";
+import { normalizeBaseUrl } from "../utils/urlSanitize.ts";
import {
normalizeHerokuChatUrl,
normalizeDatabricksChatUrl,
@@ -93,6 +87,62 @@ function applyCustomHeaders(headers: Record<string, string>, rawCustomHeaders: u
}
}
+function normalizeBailianMessagesUrl(baseUrl) {
+ const normalized = normalizeBaseUrl(baseUrl).replace(/\?beta=true$/, "");
+ const messagesUrl = normalized.endsWith("/messages") ? normalized : `${normalized}/messages`;
+ return messagesUrl;
+}
+
+function normalizeDataRobotChatUrl(baseUrl) {
+ return buildDataRobotChatUrl(baseUrl);
+}
+
+function normalizeAzureAiChatUrl(baseUrl: string, apiType: "chat" | "responses" = "chat") {
+ return buildAzureAiChatUrl(baseUrl, apiType);
+}
+
+function normalizeWatsonxChatUrl(baseUrl: string) {
+ return buildWatsonxChatUrl(baseUrl);
+}
+
+function normalizeOciChatUrl(baseUrl: string, apiType: "chat" | "responses" = "chat") {
+ return buildOciChatUrl(baseUrl, apiType);
+}
+
+function normalizeSapChatUrl(baseUrl) {
+ return buildSapChatUrl(baseUrl);
+}
+
+function normalizeXiaomiMimoChatUrl(baseUrl) {
+ const normalized = normalizeBaseUrl(baseUrl).replace(/\/chat\/completions$/, "");
+ return `${normalized}/chat/completions`;
+}
+
+function normalizeOpenAIChatUrl(baseUrl) {
+ const normalized = normalizeBaseUrl(baseUrl);
+ if (
+ normalized.endsWith("/chat/completions") ||
+ normalized.endsWith("/responses") ||
+ normalized.endsWith("/chat")
+ ) {
+ return normalized;
+ }
+ if (normalized.endsWith("/v1")) {
+ return `${normalized}/chat/completions`;
+ }
+ // Assume OpenAI-compatible /v1/chat/completions path structure
+ // when the base URL is a bare hostname or custom path (e.g. llama.cpp, vLLM, LM Studio).
+ return `${normalized}/v1/chat/completions`;
+}
+
+function getOpenRouterConnectionPreset(
+ providerSpecificData?: Record<string, unknown> | null
+): string | null {
+ const preset =
+ typeof providerSpecificData?.preset === "string" ? providerSpecificData.preset.trim() : "";
+ return preset || null;
+}
+
export class DefaultExecutor extends BaseExecutor {
constructor(provider) {
super(provider, PROVIDERS[provider] || PROVIDERS.openai);
@@ -687,54 +737,9 @@ export class DefaultExecutor extends BaseExecutor {
}
}
- // ClinePass reasoning models burn all of max_tokens on the thinking phase
- // when the budget is too small, leaving content empty (finish_reason:
- // "length"). Bump max_tokens to a safe floor when reasoning is enabled and
- // the budget is undersized. CLINEPASS-GATED — no-op for every other provider.
- if (typeof withDefaults === "object" && withDefaults !== null) {
- this.ensureThinkingBudget(withDefaults as Record<string, unknown>, model);
- }
-
return withDefaults;
}
- // ClinePass / OpenRouter-style thinking models leave content empty when the
- // reasoning budget consumes all of max_tokens. Bump max_tokens to a safe
- // minimum only when reasoning is enabled and the budget is undersized.
- // CLINEPASS-GATED: returns early for every other provider.
- ensureThinkingBudget(body: Record<string, unknown>, model: string): Record<string, unknown> {
- if (!body || this.provider !== "clinepass") return body;
-
- const outboundModel = typeof body.model === "string" ? body.model : model;
- const entry = getRegistryEntry(this.provider);
- const modelEntry = entry?.models?.find((m) => m.id === outboundModel);
- if (!modelEntry?.supportsReasoning) return body;
-
- const extraBody = body.extra_body as Record<string, unknown> | undefined;
- const thinking = extraBody?.thinking as Record<string, unknown> | undefined;
- const effort = body.reasoning_effort;
- const reasoningEnabled =
- thinking?.type === "enabled" ||
- (typeof effort === "string" && effort !== "none" && effort !== "off") ||
- effort === true;
- if (!reasoningEnabled) return body;
-
- const MIN_TOKENS = 4096;
- const maxOutput =
- typeof modelEntry.maxOutputTokens === "number" && modelEntry.maxOutputTokens > 0
- ? modelEntry.maxOutputTokens
- : MIN_TOKENS;
- const target = Math.min(MIN_TOKENS, maxOutput);
- const current = body.max_tokens ?? body.max_completion_tokens;
-
- if (typeof current !== "number" || current <= 0) {
- body.max_tokens = target;
- } else if (current < MIN_TOKENS && current < maxOutput) {
- body.max_tokens = MIN_TOKENS;
- }
- return body;
- }
-
/**
* Refresh credentials via the centralized tokenRefresh service.
* Delegates to getAccessToken() which handles all providers with
diff --git a/open-sse/executors/default/urlNormalizers.ts b/open-sse/executors/default/urlNormalizers.ts
deleted file mode 100644
index a4a5ed4ae5..0000000000
--- a/open-sse/executors/default/urlNormalizers.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-// Pure per-provider chat-URL normalizers + connection-preset reader.
-// Extracted verbatim from default.ts (string transforms only, no host state/this).
-import { buildDataRobotChatUrl } from "../../config/datarobot.ts";
-import { buildAzureAiChatUrl } from "../../config/azureAi.ts";
-import { buildWatsonxChatUrl } from "../../config/watsonx.ts";
-import { buildOciChatUrl } from "../../config/oci.ts";
-import { buildSapChatUrl } from "../../config/sap.ts";
-import { normalizeBaseUrl } from "../../utils/urlSanitize.ts";
-
-export function normalizeBailianMessagesUrl(baseUrl) {
- const normalized = normalizeBaseUrl(baseUrl).replace(/\?beta=true$/, "");
- const messagesUrl = normalized.endsWith("/messages") ? normalized : `${normalized}/messages`;
- return messagesUrl;
-}
-
-export function normalizeDataRobotChatUrl(baseUrl) {
- return buildDataRobotChatUrl(baseUrl);
-}
-
-export function normalizeAzureAiChatUrl(baseUrl: string, apiType: "chat" | "responses" = "chat") {
- return buildAzureAiChatUrl(baseUrl, apiType);
-}
-
-export function normalizeWatsonxChatUrl(baseUrl: string) {
- return buildWatsonxChatUrl(baseUrl);
-}
-
-export function normalizeOciChatUrl(baseUrl: string, apiType: "chat" | "responses" = "chat") {
- return buildOciChatUrl(baseUrl, apiType);
-}
-
-export function normalizeSapChatUrl(baseUrl) {
- return buildSapChatUrl(baseUrl);
-}
-
-export function normalizeXiaomiMimoChatUrl(baseUrl) {
- const normalized = normalizeBaseUrl(baseUrl).replace(/\/chat\/completions$/, "");
- return `${normalized}/chat/completions`;
-}
-
-export function normalizeOpenAIChatUrl(baseUrl) {
- const normalized = normalizeBaseUrl(baseUrl);
- if (
- normalized.endsWith("/chat/completions") ||
- normalized.endsWith("/responses") ||
- normalized.endsWith("/chat")
- ) {
- return normalized;
- }
- if (normalized.endsWith("/v1")) {
- return `${normalized}/chat/completions`;
- }
- // Assume OpenAI-compatible /v1/chat/completions path structure
- // when the base URL is a bare hostname or custom path (e.g. llama.cpp, vLLM, LM Studio).
- return `${normalized}/v1/chat/completions`;
-}
-
-export function getOpenRouterConnectionPreset(
- providerSpecificData?: Record<string, unknown> | null
-): string | null {
- const preset =
- typeof providerSpecificData?.preset === "string" ? providerSpecificData.preset.trim() : "";
- return preset || null;
-}
diff --git a/open-sse/executors/duckduckgo-web.ts b/open-sse/executors/duckduckgo-web.ts
index e9c6053548..05cc4b12cd 100644
--- a/open-sse/executors/duckduckgo-web.ts
+++ b/open-sse/executors/duckduckgo-web.ts
@@ -1,6 +1,6 @@
-import { generateKeyPairSync, randomUUID } from "node:crypto";
+import { createHash, generateKeyPairSync, randomUUID } from "node:crypto";
import vm from "node:vm";
-import { solveDuckDuckGoChallenge, makeDuckDuckGoFeSignals } from "./duckduckgo-web/challenge.ts";
+import { parseFragment, serialize } from "parse5";
import { BaseExecutor, type ExecuteInput } from "./base.ts";
import { FETCH_TIMEOUT_MS } from "../config/constants.ts";
import { prepareToolMessages, buildToolAwareResult } from "../translator/webTools.ts";
@@ -82,6 +82,71 @@ type DuckDuckGoChallengeResult = {
let durablePublicKey: JsonWebKey | null = null;
+const CHALLENGE_STUBS = String.raw`
+var __ua = __DDG_REAL_UA__;
+var __HTML_LOOKUP = __DDG_HTML_LOOKUP__;
+function __makeHtmlElement(tag) {
+ var state = { _innerHTML: '', _qsaCount: 0, _cssText: '' };
+ var el = {
+ tagName: String(tag).toUpperCase(), nodeName: String(tag).toUpperCase(), nodeType: 1,
+ children: [], childNodes: [], classList: [], dataset: {},
+ offsetWidth: 1, offsetHeight: 1, clientWidth: 1, clientHeight: 1, scrollHeight: 1, scrollWidth: 1,
+ getBoundingClientRect: function(){ return { x: 0, y: 0, top: 0, left: 0, right: 1, bottom: 1, width: 1, height: 1, toJSON: function(){ return {}; } }; },
+ setAttribute: function(){}, removeAttribute: function(){},
+ getAttribute: function(a){ if(a==='srcdoc') return state._srcdoc||''; return null; },
+ hasAttribute: function(){ return false; }, appendChild: function(c){ return c; }, removeChild: function(c){ return c; },
+ addEventListener: function(){}, removeEventListener: function(){}, querySelector: function(){ return null; },
+ querySelectorAll: function(s){ if (s === '*') { var arr = []; arr.length = state._qsaCount; return arr; } return []; },
+ cloneNode: function(){ return __makeHtmlElement(tag); }
+ };
+ Object.defineProperty(el, 'style', { value: new Proxy({}, { set: function(t, k, v){ t[k] = v; if (k === 'cssText') state._cssText = String(v); return true; }, get: function(t, k){ if (k === 'cssText') return state._cssText; return t[k] || ''; } }), enumerable: true, configurable: true });
+ Object.defineProperty(el, 'innerHTML', { get: function(){ return state._innerHTML; }, set: function(v){ var key = String(v); var entry = __HTML_LOOKUP && __HTML_LOOKUP[key]; if (entry) { state._innerHTML = String(entry.html); state._qsaCount = entry.count|0; } else { state._innerHTML = key; state._qsaCount = 0; } }, enumerable: true, configurable: true });
+ Object.defineProperty(el, 'outerHTML', { get: function(){ return '<' + tag + '>' + state._innerHTML + '</' + tag + '>'; }, enumerable: true });
+ Object.defineProperty(el, 'srcdoc', { get: function(){ return state._srcdoc||''; }, set: function(v){ state._srcdoc = String(v); }, enumerable: true });
+ Object.defineProperty(el, 'contentWindow', { get: function(){ var w = {}; w.document = __ifDoc; w.Proxy = Proxy; w.self = w; w.top = w; w.parent = w; w.window = w; return w; }, enumerable: true });
+ Object.defineProperty(el, 'contentDocument', { get: function(){ return __ifDoc; }, enumerable: true });
+ return el;
+}
+function __mkObj(name, base) {
+ base = base || {};
+ return new Proxy(base, {
+ get: function(t, k) {
+ if (k in t) return t[k];
+ if (k === Symbol.toPrimitive) return function(){ return ''; };
+ if (k === Symbol.iterator) return undefined;
+ if (k === 'then' || k === 'catch' || k === 'finally') return undefined;
+ if (k === 'constructor') return Object;
+ if (k === 'toString' || k === 'valueOf') return function(){ return '[object ' + name + ']'; };
+ if (k === 'length') return 0;
+ if (k === 'nodeType') return 1;
+ if (k === 'tagName' || k === 'nodeName') return 'DIV';
+ if (k === 'innerHTML' || k === 'outerHTML' || k === 'textContent' || k === 'innerText' || k === 'value') return '';
+ if (k === 'children' || k === 'childNodes' || k === 'classList') return [];
+ // Real numeric layout values for the DDG challenge DOM probes.
+ if (k === 'offsetWidth' || k === 'offsetHeight' || k === 'clientWidth' || k === 'clientHeight' || k === 'scrollHeight' || k === 'scrollWidth') return 1;
+ if (k === 'getBoundingClientRect') return function(){ return { x: 0, y: 0, top: 0, left: 0, right: 1, bottom: 1, width: 1, height: 1, toJSON: function(){ return {}; } }; };
+ if (typeof k === 'string' && (k.indexOf('get') === 0 || k.indexOf('query') === 0 || k.indexOf('find') === 0)) return function(){ return k === 'querySelectorAll' || k === 'getElementsByTagName' || k === 'getElementsByClassName' ? [] : null; };
+ return function(){ return __mkObj(name + '.' + String(k)); };
+ },
+ has: function(t, k){ return k in t; }, set: function(t, k, v){ t[k] = v; return true; }
+ });
+}
+function __parseCssDisplay(cssText){ if(!cssText) return ''; var m = String(cssText).match(/(?:^|;)\\s*display\\s*:\\s*([^;]+)/i); return m ? String(m[1]).trim() : ''; }
+function __getComputedStyle(el){ var cssText = el && el.style && el.style.cssText || ''; var display = __parseCssDisplay(cssText); return { getPropertyValue: function(name){ if(String(name).toLowerCase()==='display') return display; return ''; }, cssText: cssText, display: display }; }
+var __ifMeta = __mkObj('meta', { getAttribute: function(a){ return a==='content' ? "default-src 'none'; script-src 'unsafe-inline';" : null; }, hasAttribute: function(a){ return a==='content'; }, tagName: 'META', nodeName: 'META' });
+var __ifDoc = __mkObj('iframeDoc', { querySelector: function(s){ if (s && s.indexOf('Content-Security-Policy') !== -1) return __ifMeta; if (s === 'meta') return __ifMeta; return null; }, querySelectorAll: function(s){ if (s && s.indexOf('Content-Security-Policy') !== -1) return [__ifMeta]; if (s === 'meta') return [__ifMeta]; return []; }, getElementsByTagName: function(t){ return t && t.toLowerCase()==='meta' ? [__ifMeta] : []; }, body: __mkObj('iframeBody'), head: __mkObj('iframeHead'), documentElement: __mkObj('iframeRoot'), createElement: function(){ return __mkObj('elem', {setAttribute:function(){}, appendChild:function(){}, removeChild:function(){}, getAttribute:function(){return null;}, hasAttribute:function(){return false;}}); }, cookie: '', readyState: 'complete' });
+var __iframeEl = __mkObj('iframe', { contentDocument: __ifDoc, contentWindow: __mkObj('iframeWin', { document: __ifDoc, top: undefined, parent: undefined }), document: __ifDoc, getAttribute: function(a){ if (a==='sandbox') return 'allow-scripts allow-same-origin'; if (a==='srcdoc') return ''; if (a==='id') return 'jsa'; return null; }, hasAttribute: function(a){ return a==='sandbox'||a==='id'; }, tagName: 'IFRAME', nodeName: 'IFRAME', id: 'jsa' });
+var document = __mkObj('document', { querySelector: function(s){ if (s === '#jsa') return __iframeEl; if (s && s.indexOf('Content-Security-Policy') !== -1) return __ifMeta; return null; }, querySelectorAll: function(s){ if (s === '#jsa') return [__iframeEl]; if (s && s.indexOf('Content-Security-Policy') !== -1) return [__ifMeta]; return []; }, getElementById: function(id){ return id==='jsa' ? __iframeEl : null; }, getElementsByTagName: function(t){ if(t&&t.toLowerCase()==='iframe') return [__iframeEl]; return []; }, getElementsByClassName: function(){ return []; }, body: __mkObj('body', {appendChild:function(){}, removeChild:function(){}, querySelector:function(s){return s==='#jsa'?__iframeEl:null;}, querySelectorAll:function(s){return s==='#jsa'?[__iframeEl]:[];}}), head: __mkObj('head'), documentElement: __mkObj('root'), createElement: function(tag){ return __makeHtmlElement(tag||'div'); }, createTextNode: function(t){ return {nodeType:3, nodeValue:String(t||''), textContent:String(t||'')}; }, cookie: '', readyState: 'complete', title: '', addEventListener: function(){}, removeEventListener: function(){} });
+ var window = __mkObj('window', { document: document, __DDG_BE_VERSION__: 1, __DDG_FE_CHAT_HASH__: 1, navigator: __mkObj('navigator', { userAgent: __ua, webdriver: false, language: 'en-US', languages: ['en-US','en'], platform: 'Linux x86_64', vendor: 'Google Inc.', appVersion: '5.0 (X11)', cookieEnabled: true, onLine: true, hardwareConcurrency: 8, deviceMemory: 8 }), innerWidth: 1280, innerHeight: 800, outerWidth: 1280, outerHeight: 800, devicePixelRatio: 1, screen: __mkObj('screen', { width:1920, height:1080, availWidth:1920, availHeight:1080, colorDepth:24, pixelDepth:24 }), location: __mkObj('location', { href:'https://duck.ai/', origin:'https://duck.ai', host:'duck.ai', hostname:'duck.ai', protocol:'https:', pathname:'/' }), performance: __mkObj('perf', { now: function(){ return 0; }, timeOrigin: 0 }), history: __mkObj('history', { length: 1, state: null }), addEventListener: function(){}, removeEventListener: function(){}, dispatchEvent: function(){return true;}, setTimeout: function(fn){ try{fn();}catch(e){} return 0; }, clearTimeout: function(){}, hasOwnProperty: function(k){ if (k==='__DDG_BE_VERSION__'||k==='__DDG_FE_CHAT_HASH__') return true; return Object.prototype.hasOwnProperty.call(this,k); } });
+window.top = window; window.self = window; window.window = window; window.parent = window; window.globalThis = window;
+var top = window, self = window, parent = window, navigator = window.navigator, location = window.location, screen = window.screen, performance = window.performance, history = window.history;
+var __R = null, __E = null;
+function __HTMLClass(name){ var c = function(){}; c.prototype = __mkObj(name+'.proto'); return c; }
+var HTMLElement = __HTMLClass('HTMLElement'), HTMLDivElement = __HTMLClass('HTMLDivElement'), HTMLIFrameElement = __HTMLClass('HTMLIFrameElement'), HTMLDocument = __HTMLClass('HTMLDocument'), Document = __HTMLClass('Document'), Element = __HTMLClass('Element'), Node = __HTMLClass('Node'), Window = __HTMLClass('Window'), Event = __HTMLClass('Event'), MouseEvent = __HTMLClass('MouseEvent'), KeyboardEvent = __HTMLClass('KeyboardEvent'), TouchEvent = __HTMLClass('TouchEvent'), XMLHttpRequest = __HTMLClass('XMLHttpRequest'), WebSocket = __HTMLClass('WebSocket'), Image = __HTMLClass('Image'), FormData = __HTMLClass('FormData'), Blob = __HTMLClass('Blob'), File = __HTMLClass('File'), FileReader = __HTMLClass('FileReader'), URL = __HTMLClass('URL'), URLSearchParams = __HTMLClass('URLSearchParams'), Headers = __HTMLClass('Headers'), Request = __HTMLClass('Request'), Response = __HTMLClass('Response');
+var fetch = function(){ return Promise.resolve(__mkObj('resp', {ok:true, status:200, json:function(){return Promise.resolve({});}, text:function(){return Promise.resolve('');}})); };
+var getComputedStyle = __getComputedStyle;
+`;
+
function extractDuckDuckGoContent(data: unknown): string {
if (!data || typeof data !== "object") return "";
const record = data as Record<string, unknown>;
@@ -182,6 +247,83 @@ function getDuckDuckGoModelCapabilities(model: string): DuckDuckGoModelCapabilit
return { reasoningEffort: null };
}
+function countHtmlElements(node: unknown): number {
+ if (!node || typeof node !== "object") return 0;
+ const record = node as { nodeName?: string; childNodes?: unknown[] };
+ const own = record.nodeName && record.nodeName !== "#document-fragment" ? 1 : 0;
+ let childCount = 0;
+ for (const child of record.childNodes ?? []) {
+ childCount += countHtmlElements(child);
+ }
+ return own + childCount;
+}
+
+function buildHtmlLookup(js: string): Record<string, { html: string; count: number }> {
+ const lookup: Record<string, { html: string; count: number }> = {};
+ const seen = new Set<string>();
+ const pattern = /(['"])(<[^'"]{1,400}?)\1/g;
+ for (const match of js.matchAll(pattern)) {
+ const html = match[2];
+ if (seen.has(html)) continue;
+ seen.add(html);
+ const fragment = parseFragment(html);
+ lookup[html] = {
+ html: serialize(fragment),
+ count: Math.max(0, countHtmlElements(fragment) - 1),
+ };
+ }
+ return lookup;
+}
+
+function sha256Base64(value: string): string {
+ return createHash("sha256").update(value, "utf8").digest("base64");
+}
+
+async function solveDuckDuckGoChallenge(challenge: string, userAgent: string): Promise<string> {
+ // SECURITY NOTE: This function executes base64-decoded JavaScript from duck.ai via vm.runInContext.
+ // The challenge code is upstream-supplied (supply-chain surface). It is sandboxed with a 5s timeout
+ // to limit DoS risk. This is intentional for the DDG challenge solver to work.
+ const js = Buffer.from(challenge, "base64").toString("utf8");
+ const stubs = CHALLENGE_STUBS.replace("__DDG_REAL_UA__", JSON.stringify(userAgent)).replace(
+ "__DDG_HTML_LOOKUP__",
+ JSON.stringify(buildHtmlLookup(js))
+ );
+ const context = vm.createContext({});
+ vm.runInContext(stubs, context, { timeout: 5000 });
+ const result = (await vm.runInContext(js, context, {
+ timeout: 5000,
+ })) as DuckDuckGoChallengeResult;
+ const clientHashes = Array.isArray(result.client_hashes) ? result.client_hashes : [];
+ if (clientHashes.length === 0)
+ throw new Error("DuckDuckGo challenge returned empty client_hashes");
+ clientHashes[0] = userAgent;
+ result.client_hashes = clientHashes.map((hash) => sha256Base64(String(hash)));
+ return Buffer.from(JSON.stringify(result), "utf8").toString("base64");
+}
+
+function makeDuckDuckGoFeSignals(): string {
+ const start = Date.now() - 3000;
+ let delta = 80 + Math.floor(Math.random() * 101);
+ const events: Array<Record<string, unknown>> = [{ name: "onboarding_impression_1", delta }];
+ delta += 120 + Math.floor(Math.random() * 141);
+ events.push({ name: "onboarding_impression_2", delta });
+ delta += 200 + Math.floor(Math.random() * 301);
+ events.push({ name: "startNewChat", delta });
+ const keyEvents = 6 + Math.floor(Math.random() * 13);
+ for (let i = 0; i < keyEvents; i++) {
+ delta += 40 + Math.floor(Math.random() * 141);
+ events.push({ name: "user_input", delta });
+ }
+ delta += 120 + Math.floor(Math.random() * 231);
+ events.push({ name: "user_submit", delta });
+ const payload = {
+ start,
+ events,
+ end: Math.max(delta + 20 + Math.floor(Math.random() * 71), 3000),
+ };
+ return Buffer.from(JSON.stringify(payload), "utf8").toString("base64");
+}
+
function extractDuckDuckGoFeVersion(html: string): string | null {
return html.match(FE_VERSION_PATTERN)?.[0] ?? null;
}
diff --git a/open-sse/executors/duckduckgo-web/challenge.ts b/open-sse/executors/duckduckgo-web/challenge.ts
deleted file mode 100644
index 4c3f3a6132..0000000000
--- a/open-sse/executors/duckduckgo-web/challenge.ts
+++ /dev/null
@@ -1,151 +0,0 @@
-// DuckDuckGo anti-abuse challenge solver + FE signals (pure of module state).
-// SECURITY: solveDuckDuckGoChallenge runs upstream-supplied JS in a vm sandbox with a
-// 5s timeout (see inline note). Extracted verbatim from duckduckgo-web.ts.
-import { createHash } from "node:crypto";
-import vm from "node:vm";
-import { parseFragment, serialize } from "parse5";
-
-export const CHALLENGE_STUBS = String.raw`
-var __ua = __DDG_REAL_UA__;
-var __HTML_LOOKUP = __DDG_HTML_LOOKUP__;
-export function __makeHtmlElement(tag) {
- var state = { _innerHTML: '', _qsaCount: 0, _cssText: '' };
- var el = {
- tagName: String(tag).toUpperCase(), nodeName: String(tag).toUpperCase(), nodeType: 1,
- children: [], childNodes: [], classList: [], dataset: {},
- offsetWidth: 1, offsetHeight: 1, clientWidth: 1, clientHeight: 1, scrollHeight: 1, scrollWidth: 1,
- getBoundingClientRect: function(){ return { x: 0, y: 0, top: 0, left: 0, right: 1, bottom: 1, width: 1, height: 1, toJSON: function(){ return {}; } }; },
- setAttribute: function(){}, removeAttribute: function(){},
- getAttribute: function(a){ if(a==='srcdoc') return state._srcdoc||''; return null; },
- hasAttribute: function(){ return false; }, appendChild: function(c){ return c; }, removeChild: function(c){ return c; },
- addEventListener: function(){}, removeEventListener: function(){}, querySelector: function(){ return null; },
- querySelectorAll: function(s){ if (s === '*') { var arr = []; arr.length = state._qsaCount; return arr; } return []; },
- cloneNode: function(){ return __makeHtmlElement(tag); }
- };
- Object.defineProperty(el, 'style', { value: new Proxy({}, { set: function(t, k, v){ t[k] = v; if (k === 'cssText') state._cssText = String(v); return true; }, get: function(t, k){ if (k === 'cssText') return state._cssText; return t[k] || ''; } }), enumerable: true, configurable: true });
- Object.defineProperty(el, 'innerHTML', { get: function(){ return state._innerHTML; }, set: function(v){ var key = String(v); var entry = __HTML_LOOKUP && __HTML_LOOKUP[key]; if (entry) { state._innerHTML = String(entry.html); state._qsaCount = entry.count|0; } else { state._innerHTML = key; state._qsaCount = 0; } }, enumerable: true, configurable: true });
- Object.defineProperty(el, 'outerHTML', { get: function(){ return '<' + tag + '>' + state._innerHTML + '</' + tag + '>'; }, enumerable: true });
- Object.defineProperty(el, 'srcdoc', { get: function(){ return state._srcdoc||''; }, set: function(v){ state._srcdoc = String(v); }, enumerable: true });
- Object.defineProperty(el, 'contentWindow', { get: function(){ var w = {}; w.document = __ifDoc; w.Proxy = Proxy; w.self = w; w.top = w; w.parent = w; w.window = w; return w; }, enumerable: true });
- Object.defineProperty(el, 'contentDocument', { get: function(){ return __ifDoc; }, enumerable: true });
- return el;
-}
-export function __mkObj(name, base) {
- base = base || {};
- return new Proxy(base, {
- get: function(t, k) {
- if (k in t) return t[k];
- if (k === Symbol.toPrimitive) return function(){ return ''; };
- if (k === Symbol.iterator) return undefined;
- if (k === 'then' || k === 'catch' || k === 'finally') return undefined;
- if (k === 'constructor') return Object;
- if (k === 'toString' || k === 'valueOf') return function(){ return '[object ' + name + ']'; };
- if (k === 'length') return 0;
- if (k === 'nodeType') return 1;
- if (k === 'tagName' || k === 'nodeName') return 'DIV';
- if (k === 'innerHTML' || k === 'outerHTML' || k === 'textContent' || k === 'innerText' || k === 'value') return '';
- if (k === 'children' || k === 'childNodes' || k === 'classList') return [];
- // Real numeric layout values for the DDG challenge DOM probes.
- if (k === 'offsetWidth' || k === 'offsetHeight' || k === 'clientWidth' || k === 'clientHeight' || k === 'scrollHeight' || k === 'scrollWidth') return 1;
- if (k === 'getBoundingClientRect') return function(){ return { x: 0, y: 0, top: 0, left: 0, right: 1, bottom: 1, width: 1, height: 1, toJSON: function(){ return {}; } }; };
- if (typeof k === 'string' && (k.indexOf('get') === 0 || k.indexOf('query') === 0 || k.indexOf('find') === 0)) return function(){ return k === 'querySelectorAll' || k === 'getElementsByTagName' || k === 'getElementsByClassName' ? [] : null; };
- return function(){ return __mkObj(name + '.' + String(k)); };
- },
- has: function(t, k){ return k in t; }, set: function(t, k, v){ t[k] = v; return true; }
- });
-}
-export function __parseCssDisplay(cssText){ if(!cssText) return ''; var m = String(cssText).match(/(?:^|;)\\s*display\\s*:\\s*([^;]+)/i); return m ? String(m[1]).trim() : ''; }
-export function __getComputedStyle(el){ var cssText = el && el.style && el.style.cssText || ''; var display = __parseCssDisplay(cssText); return { getPropertyValue: function(name){ if(String(name).toLowerCase()==='display') return display; return ''; }, cssText: cssText, display: display }; }
-var __ifMeta = __mkObj('meta', { getAttribute: function(a){ return a==='content' ? "default-src 'none'; script-src 'unsafe-inline';" : null; }, hasAttribute: function(a){ return a==='content'; }, tagName: 'META', nodeName: 'META' });
-var __ifDoc = __mkObj('iframeDoc', { querySelector: function(s){ if (s && s.indexOf('Content-Security-Policy') !== -1) return __ifMeta; if (s === 'meta') return __ifMeta; return null; }, querySelectorAll: function(s){ if (s && s.indexOf('Content-Security-Policy') !== -1) return [__ifMeta]; if (s === 'meta') return [__ifMeta]; return []; }, getElementsByTagName: function(t){ return t && t.toLowerCase()==='meta' ? [__ifMeta] : []; }, body: __mkObj('iframeBody'), head: __mkObj('iframeHead'), documentElement: __mkObj('iframeRoot'), createElement: function(){ return __mkObj('elem', {setAttribute:function(){}, appendChild:function(){}, removeChild:function(){}, getAttribute:function(){return null;}, hasAttribute:function(){return false;}}); }, cookie: '', readyState: 'complete' });
-var __iframeEl = __mkObj('iframe', { contentDocument: __ifDoc, contentWindow: __mkObj('iframeWin', { document: __ifDoc, top: undefined, parent: undefined }), document: __ifDoc, getAttribute: function(a){ if (a==='sandbox') return 'allow-scripts allow-same-origin'; if (a==='srcdoc') return ''; if (a==='id') return 'jsa'; return null; }, hasAttribute: function(a){ return a==='sandbox'||a==='id'; }, tagName: 'IFRAME', nodeName: 'IFRAME', id: 'jsa' });
-var document = __mkObj('document', { querySelector: function(s){ if (s === '#jsa') return __iframeEl; if (s && s.indexOf('Content-Security-Policy') !== -1) return __ifMeta; return null; }, querySelectorAll: function(s){ if (s === '#jsa') return [__iframeEl]; if (s && s.indexOf('Content-Security-Policy') !== -1) return [__ifMeta]; return []; }, getElementById: function(id){ return id==='jsa' ? __iframeEl : null; }, getElementsByTagName: function(t){ if(t&&t.toLowerCase()==='iframe') return [__iframeEl]; return []; }, getElementsByClassName: function(){ return []; }, body: __mkObj('body', {appendChild:function(){}, removeChild:function(){}, querySelector:function(s){return s==='#jsa'?__iframeEl:null;}, querySelectorAll:function(s){return s==='#jsa'?[__iframeEl]:[];}}), head: __mkObj('head'), documentElement: __mkObj('root'), createElement: function(tag){ return __makeHtmlElement(tag||'div'); }, createTextNode: function(t){ return {nodeType:3, nodeValue:String(t||''), textContent:String(t||'')}; }, cookie: '', readyState: 'complete', title: '', addEventListener: function(){}, removeEventListener: function(){} });
- var window = __mkObj('window', { document: document, __DDG_BE_VERSION__: 1, __DDG_FE_CHAT_HASH__: 1, navigator: __mkObj('navigator', { userAgent: __ua, webdriver: false, language: 'en-US', languages: ['en-US','en'], platform: 'Linux x86_64', vendor: 'Google Inc.', appVersion: '5.0 (X11)', cookieEnabled: true, onLine: true, hardwareConcurrency: 8, deviceMemory: 8 }), innerWidth: 1280, innerHeight: 800, outerWidth: 1280, outerHeight: 800, devicePixelRatio: 1, screen: __mkObj('screen', { width:1920, height:1080, availWidth:1920, availHeight:1080, colorDepth:24, pixelDepth:24 }), location: __mkObj('location', { href:'https://duck.ai/', origin:'https://duck.ai', host:'duck.ai', hostname:'duck.ai', protocol:'https:', pathname:'/' }), performance: __mkObj('perf', { now: function(){ return 0; }, timeOrigin: 0 }), history: __mkObj('history', { length: 1, state: null }), addEventListener: function(){}, removeEventListener: function(){}, dispatchEvent: function(){return true;}, setTimeout: function(fn){ try{fn();}catch(e){} return 0; }, clearTimeout: function(){}, hasOwnProperty: function(k){ if (k==='__DDG_BE_VERSION__'||k==='__DDG_FE_CHAT_HASH__') return true; return Object.prototype.hasOwnProperty.call(this,k); } });
-window.top = window; window.self = window; window.window = window; window.parent = window; window.globalThis = window;
-var top = window, self = window, parent = window, navigator = window.navigator, location = window.location, screen = window.screen, performance = window.performance, history = window.history;
-var __R = null, __E = null;
-export function __HTMLClass(name){ var c = function(){}; c.prototype = __mkObj(name+'.proto'); return c; }
-var HTMLElement = __HTMLClass('HTMLElement'), HTMLDivElement = __HTMLClass('HTMLDivElement'), HTMLIFrameElement = __HTMLClass('HTMLIFrameElement'), HTMLDocument = __HTMLClass('HTMLDocument'), Document = __HTMLClass('Document'), Element = __HTMLClass('Element'), Node = __HTMLClass('Node'), Window = __HTMLClass('Window'), Event = __HTMLClass('Event'), MouseEvent = __HTMLClass('MouseEvent'), KeyboardEvent = __HTMLClass('KeyboardEvent'), TouchEvent = __HTMLClass('TouchEvent'), XMLHttpRequest = __HTMLClass('XMLHttpRequest'), WebSocket = __HTMLClass('WebSocket'), Image = __HTMLClass('Image'), FormData = __HTMLClass('FormData'), Blob = __HTMLClass('Blob'), File = __HTMLClass('File'), FileReader = __HTMLClass('FileReader'), URL = __HTMLClass('URL'), URLSearchParams = __HTMLClass('URLSearchParams'), Headers = __HTMLClass('Headers'), Request = __HTMLClass('Request'), Response = __HTMLClass('Response');
-var fetch = function(){ return Promise.resolve(__mkObj('resp', {ok:true, status:200, json:function(){return Promise.resolve({});}, text:function(){return Promise.resolve('');}})); };
-var getComputedStyle = __getComputedStyle;
-`;
-
-export function countHtmlElements(node: unknown): number {
- if (!node || typeof node !== "object") return 0;
- const record = node as { nodeName?: string; childNodes?: unknown[] };
- const own = record.nodeName && record.nodeName !== "#document-fragment" ? 1 : 0;
- let childCount = 0;
- for (const child of record.childNodes ?? []) {
- childCount += countHtmlElements(child);
- }
- return own + childCount;
-}
-
-export function buildHtmlLookup(js: string): Record<string, { html: string; count: number }> {
- const lookup: Record<string, { html: string; count: number }> = {};
- const seen = new Set<string>();
- const pattern = /(['"])(<[^'"]{1,400}?)\1/g;
- for (const match of js.matchAll(pattern)) {
- const html = match[2];
- if (seen.has(html)) continue;
- seen.add(html);
- const fragment = parseFragment(html);
- lookup[html] = {
- html: serialize(fragment),
- count: Math.max(0, countHtmlElements(fragment) - 1),
- };
- }
- return lookup;
-}
-
-export function sha256Base64(value: string): string {
- return createHash("sha256").update(value, "utf8").digest("base64");
-}
-
-export async function solveDuckDuckGoChallenge(
- challenge: string,
- userAgent: string
-): Promise<string> {
- // SECURITY NOTE: This function executes base64-decoded JavaScript from duck.ai via vm.runInContext.
- // The challenge code is upstream-supplied (supply-chain surface). It is sandboxed with a 5s timeout
- // to limit DoS risk. This is intentional for the DDG challenge solver to work.
- const js = Buffer.from(challenge, "base64").toString("utf8");
- const stubs = CHALLENGE_STUBS.replace("__DDG_REAL_UA__", JSON.stringify(userAgent)).replace(
- "__DDG_HTML_LOOKUP__",
- JSON.stringify(buildHtmlLookup(js))
- );
- const context = vm.createContext({});
- vm.runInContext(stubs, context, { timeout: 5000 });
- const result = (await vm.runInContext(js, context, {
- timeout: 5000,
- })) as DuckDuckGoChallengeResult;
- const clientHashes = Array.isArray(result.client_hashes) ? result.client_hashes : [];
- if (clientHashes.length === 0)
- throw new Error("DuckDuckGo challenge returned empty client_hashes");
- clientHashes[0] = userAgent;
- result.client_hashes = clientHashes.map((hash) => sha256Base64(String(hash)));
- return Buffer.from(JSON.stringify(result), "utf8").toString("base64");
-}
-
-export function makeDuckDuckGoFeSignals(): string {
- const start = Date.now() - 3000;
- let delta = 80 + Math.floor(Math.random() * 101);
- const events: Array<Record<string, unknown>> = [{ name: "onboarding_impression_1", delta }];
- delta += 120 + Math.floor(Math.random() * 141);
- events.push({ name: "onboarding_impression_2", delta });
- delta += 200 + Math.floor(Math.random() * 301);
- events.push({ name: "startNewChat", delta });
- const keyEvents = 6 + Math.floor(Math.random() * 13);
- for (let i = 0; i < keyEvents; i++) {
- delta += 40 + Math.floor(Math.random() * 141);
- events.push({ name: "user_input", delta });
- }
- delta += 120 + Math.floor(Math.random() * 231);
- events.push({ name: "user_submit", delta });
- const payload = {
- start,
- events,
- end: Math.max(delta + 20 + Math.floor(Math.random() * 71), 3000),
- };
- return Buffer.from(JSON.stringify(payload), "utf8").toString("base64");
-}
diff --git a/open-sse/executors/firecrawl-fetch.ts b/open-sse/executors/firecrawl-fetch.ts
index b2c59386ec..c8ae752466 100644
--- a/open-sse/executors/firecrawl-fetch.ts
+++ b/open-sse/executors/firecrawl-fetch.ts
@@ -6,37 +6,13 @@
*
* Free tier: 500 fetches/month, no credit card required.
* Docs: https://docs.firecrawl.dev/api-reference/endpoint/scrape
- *
- * Self-hosted: set FIRECRAWL_BASE_URL to point at a self-hosted Firecrawl
- * instance (e.g. http://127.0.0.1:3002). The API key is only required against
- * the default cloud base URL — self-hosted instances typically run with no
- * auth in front of them, so credentials.apiKey becomes optional in that case.
*/
import { sanitizeErrorMessage, buildErrorBody } from "../utils/error.ts";
import type { WebFetchResult, WebFetchFormat, WebFetchCredentials } from "../handlers/webFetch.ts";
-const FIRECRAWL_DEFAULT_BASE_URL = "https://api.firecrawl.dev";
-const FIRECRAWL_DEFAULT_TIMEOUT_MS = 30_000;
-
-/** Resolve the configured Firecrawl base URL, falling back to the public cloud API. */
-function getFirecrawlBaseUrl(): string {
- const envBase = process.env.FIRECRAWL_BASE_URL?.trim();
- return envBase ? envBase.replace(/\/+$/, "") : FIRECRAWL_DEFAULT_BASE_URL;
-}
-
-/** Whether the given base URL is the default Firecrawl cloud endpoint. */
-function isDefaultFirecrawlBaseUrl(baseUrl: string): boolean {
- return baseUrl === FIRECRAWL_DEFAULT_BASE_URL;
-}
-
-/** Resolve the configured request timeout, falling back to a sane default. */
-function getFirecrawlTimeoutMs(): number {
- const raw = process.env.FIRECRAWL_TIMEOUT_MS;
- if (!raw) return FIRECRAWL_DEFAULT_TIMEOUT_MS;
- const parsed = Number(raw);
- return Number.isFinite(parsed) && parsed > 0 ? parsed : FIRECRAWL_DEFAULT_TIMEOUT_MS;
-}
+const FIRECRAWL_API_BASE = "https://api.firecrawl.dev/v1";
+const FIRECRAWL_TIMEOUT_MS = 30_000;
function mapFormat(format: WebFetchFormat): string {
switch (format) {
@@ -67,12 +43,7 @@ interface FirecrawlScrapeOptions {
export async function firecrawlFetch(opts: FirecrawlScrapeOptions): Promise<WebFetchResult> {
const { url, format, depth, waitForSelector, includeMetadata, credentials } = opts;
- const baseUrl = getFirecrawlBaseUrl();
- const isDefaultBaseUrl = isDefaultFirecrawlBaseUrl(baseUrl);
-
- // The API key is mandatory for the public Firecrawl cloud API, but optional
- // once a custom (self-hosted) base URL is configured.
- if (isDefaultBaseUrl && !credentials.apiKey) {
+ if (!credentials.apiKey) {
const body = buildErrorBody(401, "Firecrawl API key required");
return { success: false, status: 401, error: body.error.message };
}
@@ -100,17 +71,15 @@ export async function firecrawlFetch(opts: FirecrawlScrapeOptions): Promise<WebF
}
const controller = new AbortController();
- const timeoutId = setTimeout(() => controller.abort(), getFirecrawlTimeoutMs());
+ const timeoutId = setTimeout(() => controller.abort(), FIRECRAWL_TIMEOUT_MS);
try {
- const headers: Record<string, string> = { "Content-Type": "application/json" };
- if (credentials.apiKey) {
- headers.Authorization = `Bearer ${credentials.apiKey}`;
- }
-
- const response = await fetch(`${baseUrl}/v1/scrape`, {
+ const response = await fetch(`${FIRECRAWL_API_BASE}/scrape`, {
method: "POST",
- headers,
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${credentials.apiKey}`,
+ },
body: JSON.stringify(requestBody),
signal: controller.signal,
});
diff --git a/open-sse/executors/gitlab.ts b/open-sse/executors/gitlab.ts
index 888e10b94a..9ccec9a46b 100644
--- a/open-sse/executors/gitlab.ts
+++ b/open-sse/executors/gitlab.ts
@@ -10,13 +10,6 @@ import {
} from "./base.ts";
import { FETCH_TIMEOUT_MS } from "../config/constants.ts";
import { getAccessToken } from "../services/tokenRefresh.ts";
-import { prepareToolMessages, buildToolAwareResult } from "../translator/webTools.ts";
-import {
- buildStreamingResponse,
- buildJsonCompletion,
- buildToolJsonCompletion,
- buildToolStreamingResponse,
-} from "./gitlabResponses.ts";
import {
buildGitLabDirectGatewayUrl,
buildGitLabOAuthEndpoints,
@@ -119,6 +112,101 @@ function toOpenAIError(status: number, message: string): Response {
);
}
+function buildSseChunk(data: unknown): string {
+ return `data: ${JSON.stringify(data)}\n\n`;
+}
+
+function buildStreamingResponse(
+ content: string,
+ model: string,
+ id: string,
+ created: number
+): Response {
+ const encoder = new TextEncoder();
+
+ const body = new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.enqueue(
+ encoder.encode(
+ buildSseChunk({
+ id,
+ object: "chat.completion.chunk",
+ created,
+ model,
+ choices: [{ index: 0, delta: { role: "assistant" }, finish_reason: null }],
+ })
+ )
+ );
+
+ if (content) {
+ controller.enqueue(
+ encoder.encode(
+ buildSseChunk({
+ id,
+ object: "chat.completion.chunk",
+ created,
+ model,
+ choices: [{ index: 0, delta: { content }, finish_reason: null }],
+ })
+ )
+ );
+ }
+
+ controller.enqueue(
+ encoder.encode(
+ buildSseChunk({
+ id,
+ object: "chat.completion.chunk",
+ created,
+ model,
+ choices: [{ index: 0, delta: {}, finish_reason: "stop" }],
+ })
+ )
+ );
+ controller.enqueue(encoder.encode("data: [DONE]\n\n"));
+ controller.close();
+ },
+ });
+
+ return new Response(body, {
+ status: 200,
+ headers: { "Content-Type": "text/event-stream" },
+ });
+}
+
+function buildJsonCompletion(
+ content: string,
+ model: string,
+ id: string,
+ created: number
+): Response {
+ const estimated = Math.max(1, Math.ceil(content.length / 4));
+ return new Response(
+ JSON.stringify({
+ id,
+ object: "chat.completion",
+ created,
+ model,
+ choices: [
+ {
+ index: 0,
+ message: { role: "assistant", content },
+ finish_reason: "stop",
+ },
+ ],
+ usage: {
+ prompt_tokens: estimated,
+ completion_tokens: estimated,
+ total_tokens: estimated * 2,
+ },
+ }),
+ {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }
+ );
+}
+
function mergeCredentials(
current: ProviderCredentials,
patch: Partial<ProviderCredentials> | null | undefined
@@ -484,20 +572,9 @@ export class GitlabExecutor extends BaseExecutor {
}
async execute(input: ExecuteInput) {
- const bodyObj = (input.body as Record<string, unknown>) || {};
- const rawMessages = (bodyObj.messages as OpenAIMessage[]) || [];
-
- // Emulate OpenAI tool calling for GitLab Duo (which has no native function
- // calling). When `tools` are present we serialize the tool contract into the
- // prompt and parse `<tool>{...}</tool>` blocks back out of the completion text
- // into OpenAI `tool_calls` — the same web-tool-emulation idiom used by the
- // qwen-web / duckduckgo-web executors (#6051).
- const { hasTools, requestedTools, effectiveMessages } = prepareToolMessages(
- bodyObj,
- rawMessages as Array<{ role: string; content: unknown }>
+ const prompt = buildPrompt(
+ (input.body as Record<string, unknown>)?.messages as OpenAIMessage[]
);
-
- const prompt = buildPrompt(effectiveMessages as OpenAIMessage[]);
if (!prompt) {
return {
response: toOpenAIError(400, "GitLab Duo requires at least one user message"),
@@ -521,7 +598,7 @@ export class GitlabExecutor extends BaseExecutor {
const transformedBody = this.transformRequest(
input.model,
- { ...bodyObj, messages: effectiveMessages },
+ (input.body as Record<string, unknown>) || {},
false,
activeCredentials
);
@@ -607,24 +684,6 @@ export class GitlabExecutor extends BaseExecutor {
const resolvedModel = resolveResponseModel(payload, input.model);
const responseId = `chatcmpl-gitlab-${randomUUID()}`;
const created = Math.floor(Date.now() / 1000);
-
- if (hasTools) {
- const {
- content: toolContent,
- toolCalls,
- finishReason,
- } = buildToolAwareResult(content, requestedTools, "gitlab");
- const message: Record<string, unknown> = { role: "assistant", content: toolContent };
- if (toolCalls) {
- message.tool_calls = toolCalls;
- message.content = null;
- }
- const response = input.stream
- ? buildToolStreamingResponse(message, finishReason, resolvedModel, responseId, created)
- : buildToolJsonCompletion(message, finishReason, resolvedModel, responseId, created);
- return { response, url: activeTarget.url, headers: requestHeaders, transformedBody };
- }
-
const response = input.stream
? buildStreamingResponse(content, resolvedModel, responseId, created)
: buildJsonCompletion(content, resolvedModel, responseId, created);
diff --git a/open-sse/executors/gitlabResponses.ts b/open-sse/executors/gitlabResponses.ts
deleted file mode 100644
index 0e98bb216c..0000000000
--- a/open-sse/executors/gitlabResponses.ts
+++ /dev/null
@@ -1,191 +0,0 @@
-// OpenAI-shaped response builders for the GitLab Duo executor. Extracted from
-// gitlab.ts (leaf module — must not import from gitlab.ts) so the executor stays
-// under the file-size cap. Covers plain text (streaming + JSON) and the
-// tool_calls emulation variants added for #6051.
-
-function buildSseChunk(data: unknown): string {
- return `data: ${JSON.stringify(data)}\n\n`;
-}
-
-export function buildStreamingResponse(
- content: string,
- model: string,
- id: string,
- created: number
-): Response {
- const encoder = new TextEncoder();
-
- const body = new ReadableStream<Uint8Array>({
- start(controller) {
- controller.enqueue(
- encoder.encode(
- buildSseChunk({
- id,
- object: "chat.completion.chunk",
- created,
- model,
- choices: [{ index: 0, delta: { role: "assistant" }, finish_reason: null }],
- })
- )
- );
-
- if (content) {
- controller.enqueue(
- encoder.encode(
- buildSseChunk({
- id,
- object: "chat.completion.chunk",
- created,
- model,
- choices: [{ index: 0, delta: { content }, finish_reason: null }],
- })
- )
- );
- }
-
- controller.enqueue(
- encoder.encode(
- buildSseChunk({
- id,
- object: "chat.completion.chunk",
- created,
- model,
- choices: [{ index: 0, delta: {}, finish_reason: "stop" }],
- })
- )
- );
- controller.enqueue(encoder.encode("data: [DONE]\n\n"));
- controller.close();
- },
- });
-
- return new Response(body, {
- status: 200,
- headers: { "Content-Type": "text/event-stream" },
- });
-}
-
-export function buildJsonCompletion(
- content: string,
- model: string,
- id: string,
- created: number
-): Response {
- const estimated = Math.max(1, Math.ceil(content.length / 4));
- return new Response(
- JSON.stringify({
- id,
- object: "chat.completion",
- created,
- model,
- choices: [
- {
- index: 0,
- message: { role: "assistant", content },
- finish_reason: "stop",
- },
- ],
- usage: {
- prompt_tokens: estimated,
- completion_tokens: estimated,
- total_tokens: estimated * 2,
- },
- }),
- {
- status: 200,
- headers: { "Content-Type": "application/json" },
- }
- );
-}
-
-export function buildToolJsonCompletion(
- message: Record<string, unknown>,
- finishReason: string,
- model: string,
- id: string,
- created: number
-): Response {
- const contentForEstimate = typeof message.content === "string" ? message.content : "";
- const estimated = Math.max(1, Math.ceil(contentForEstimate.length / 4));
- return new Response(
- JSON.stringify({
- id,
- object: "chat.completion",
- created,
- model,
- choices: [
- {
- index: 0,
- message,
- finish_reason: finishReason,
- },
- ],
- usage: {
- prompt_tokens: estimated,
- completion_tokens: estimated,
- total_tokens: estimated * 2,
- },
- }),
- {
- status: 200,
- headers: { "Content-Type": "application/json" },
- }
- );
-}
-
-export function buildToolStreamingResponse(
- message: Record<string, unknown>,
- finishReason: string,
- model: string,
- id: string,
- created: number
-): Response {
- const encoder = new TextEncoder();
-
- const body = new ReadableStream<Uint8Array>({
- start(controller) {
- controller.enqueue(
- encoder.encode(
- buildSseChunk({
- id,
- object: "chat.completion.chunk",
- created,
- model,
- choices: [{ index: 0, delta: { role: "assistant" }, finish_reason: null }],
- })
- )
- );
-
- controller.enqueue(
- encoder.encode(
- buildSseChunk({
- id,
- object: "chat.completion.chunk",
- created,
- model,
- choices: [{ index: 0, delta: message, finish_reason: null }],
- })
- )
- );
-
- controller.enqueue(
- encoder.encode(
- buildSseChunk({
- id,
- object: "chat.completion.chunk",
- created,
- model,
- choices: [{ index: 0, delta: {}, finish_reason: finishReason }],
- })
- )
- );
- controller.enqueue(encoder.encode("data: [DONE]\n\n"));
- controller.close();
- },
- });
-
- return new Response(body, {
- status: 200,
- headers: { "Content-Type": "text/event-stream" },
- });
-}
diff --git a/open-sse/executors/grok-web.ts b/open-sse/executors/grok-web.ts
index df311699d3..880d95420c 100644
--- a/open-sse/executors/grok-web.ts
+++ b/open-sse/executors/grok-web.ts
@@ -27,22 +27,6 @@ import {
type TlsFetchResult,
} from "../services/grokTlsClient.ts";
import { sanitizeErrorMessage } from "../utils/error.ts";
-import type { GrokStreamEvent } from "./grok-web/types.ts";
-import {
- type OpenAIToolCall,
- type GrokToolRegistry,
- buildGrokToolRegistry,
- buildGrokMessage,
- parseClientToolCallMarkup,
- hasOpenToolCallMarkup,
-} from "./grok-web/tool-bridge.ts";
-import { mapGrokNativeToolToOpenAI } from "./grok-web/native-tools.ts";
-import {
- GrokMarkupFilter,
- cleanGrokContentText,
- cleanGrokThinkingText,
- extractStructuredReasoning,
-} from "./grok-web/text-cleanup.ts";
// ─── Constants ──────────────────────────────────────────────────────────────
@@ -105,6 +89,875 @@ function randomHex(bytes: number): string {
return Array.from(arr, (b) => b.toString(16).padStart(2, "0")).join("");
}
+// ─── OpenAI message → Grok query translation ───────────────────────────────
+
+interface OpenAIToolCall {
+ id: string;
+ type: "function";
+ function: {
+ name: string;
+ arguments: string;
+ };
+}
+
+interface GrokToolRegistry {
+ enabled: boolean;
+ toolsByName: Map<string, GrokFunctionToolSummary>;
+ lastUserText: string;
+ executedToolKeys: Set<string>;
+ completedToolCalls: string[];
+}
+
+interface GrokFunctionToolSummary {
+ name: string;
+ description?: string;
+ parameters: unknown;
+}
+
+type NativeToolIntent = "bash" | "readFile" | "webSearch" | "browsePage";
+
+interface ToolBridgeContext {
+ lastUserText: string;
+}
+
+function stripInjectedRuntimeReminders(text: string): string {
+ return text
+ .replace(/\n?---\s*\n\s*<internal_reminder>[\s\S]*?<\/internal_reminder>/gi, "")
+ .replace(/<internal_reminder>[\s\S]*?<\/internal_reminder>/gi, "")
+ .replace(/\n{3,}/g, "\n\n")
+ .trim();
+}
+
+function extractTextContent(msg: Record<string, unknown>): string {
+ if (typeof msg.content === "string") return stripInjectedRuntimeReminders(msg.content);
+ if (Array.isArray(msg.content)) {
+ return stripInjectedRuntimeReminders(
+ (msg.content as Array<Record<string, unknown>>)
+ .filter((c) => c.type === "text")
+ .map((c) => String(c.text || ""))
+ .join(" ")
+ );
+ }
+ return "";
+}
+
+function getLastUserText(messages: Array<Record<string, unknown>>): string {
+ for (let i = messages.length - 1; i >= 0; i--) {
+ if (String(messages[i].role || "") === "user") return extractTextContent(messages[i]);
+ }
+ return "";
+}
+
+function normalizeToolArgumentObject(value: unknown): Record<string, unknown> {
+ if (!value) return {};
+ if (typeof value === "object") return value as Record<string, unknown>;
+ if (typeof value === "string") {
+ try {
+ const parsed = JSON.parse(value);
+ return parsed && typeof parsed === "object"
+ ? (parsed as Record<string, unknown>)
+ : { input: value };
+ } catch {
+ return { input: value };
+ }
+ }
+ return {};
+}
+
+function stableJson(value: unknown): string {
+ if (!value || typeof value !== "object") return JSON.stringify(value);
+ if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
+ const record = value as Record<string, unknown>;
+ return `{${Object.keys(record)
+ .sort()
+ .map((key) => `${JSON.stringify(key)}:${stableJson(record[key])}`)
+ .join(",")}}`;
+}
+
+function toolCallKey(name: string, args: unknown): string {
+ return `${name}:${stableJson(normalizeToolArgumentObject(args))}`;
+}
+
+function normalizeShellCommand(command: string): string {
+ return command.trim().replace(/\s+/g, " ");
+}
+
+function normalizePathValue(path: string): string {
+ return path.trim().replace(/^['"]|['"]$/g, "");
+}
+
+function normalizeQueryValue(query: string): string {
+ return query.trim().replace(/\s+/g, " ").toLowerCase();
+}
+
+function semanticToolKey(name: string, args: unknown): string {
+ const normalizedName = name.trim();
+ const record = normalizeToolArgumentObject(args);
+ const command = firstString(record.command, record.cmd, record.shell);
+ if (command) return `${normalizedName}:command:${normalizeShellCommand(command)}`;
+
+ const url = firstString(record.url, record.uri);
+ if (url) return `${normalizedName}:url:${normalizePathValue(url)}`;
+
+ const path = firstString(record.filePath, record.file_path, record.path, record.filename);
+ if (path) return `${normalizedName}:path:${normalizePathValue(path)}`;
+
+ const query = firstString(record.query, record.search);
+ if (query) return `${normalizedName}:query:${normalizeQueryValue(query)}`;
+
+ return toolCallKey(normalizedName, record);
+}
+
+function summarizeCompletedToolCall(name: string, args: unknown): string {
+ const record = normalizeToolArgumentObject(args);
+ const command = firstString(record.command, record.cmd, record.shell);
+ if (command) return `${name}(command=${JSON.stringify(normalizeShellCommand(command))})`;
+ const url = firstString(record.url, record.uri);
+ if (url) return `${name}(url=${JSON.stringify(normalizePathValue(url))})`;
+ const path = firstString(record.filePath, record.file_path, record.path, record.filename);
+ if (path) return `${name}(path=${JSON.stringify(normalizePathValue(path))})`;
+ const query = firstString(record.query, record.search);
+ if (query) return `${name}(query=${JSON.stringify(normalizeQueryValue(query))})`;
+ return `${name}(${stableJson(record)})`;
+}
+
+function getExecutedToolState(messages: Array<Record<string, unknown>>): {
+ keys: Set<string>;
+ summaries: string[];
+} {
+ let lastUserIdx = -1;
+ for (let i = messages.length - 1; i >= 0; i--) {
+ if (String(messages[i].role || "") === "user") {
+ lastUserIdx = i;
+ break;
+ }
+ }
+ const callsById = new Map<string, { name: string; args: Record<string, unknown> }>();
+ const executed = new Set<string>();
+ const summaries: string[] = [];
+ for (let i = Math.max(0, lastUserIdx + 1); i < messages.length; i++) {
+ const msg = messages[i];
+ if (String(msg.role || "") === "assistant" && Array.isArray(msg.tool_calls)) {
+ for (const call of msg.tool_calls as Array<Record<string, unknown>>) {
+ const id = typeof call.id === "string" ? call.id : "";
+ const fn = call.function;
+ if (!id || !fn || typeof fn !== "object") continue;
+ const fnRecord = fn as Record<string, unknown>;
+ const name = typeof fnRecord.name === "string" ? fnRecord.name : "";
+ if (!name) continue;
+ callsById.set(id, { name, args: normalizeToolArgumentObject(fnRecord.arguments) });
+ }
+ }
+ if (String(msg.role || "") === "tool") {
+ const id = typeof msg.tool_call_id === "string" ? msg.tool_call_id : "";
+ const call = id ? callsById.get(id) : null;
+ if (call) {
+ const key = semanticToolKey(call.name, call.args);
+ executed.add(key);
+ const summary = summarizeCompletedToolCall(call.name, call.args);
+ if (!summaries.includes(summary)) summaries.push(summary);
+ }
+ }
+ }
+ return { keys: executed, summaries };
+}
+
+function extractFirstUrl(text: string): string | undefined {
+ const match = text.match(/https?:\/\/[^\s)\]}>"']+/i);
+ if (match?.[0]) return match[0].replace(/[.,;:!?]+$/, "");
+ const domain = text.match(/(?:^|\s)((?:[a-z0-9-]+\.)+[a-z]{2,}(?:\/[^\s)\]}>"']*)?)/i)?.[1];
+ return domain ? `https://${domain.replace(/[.,;:!?]+$/, "")}` : undefined;
+}
+
+function wantsUrlFetch(text: string): boolean {
+ return (
+ /\b(webfetch|web_fetch|fetch|browse|open|read|lee|abre|extrae|investiga|analiza|resume|summarize|de qu[eé] va)\b/i.test(
+ text
+ ) && !!extractFirstUrl(text)
+ );
+}
+
+function forcedToolChoiceName(toolChoice: unknown): string | null {
+ if (!toolChoice || typeof toolChoice !== "object") return null;
+ const record = toolChoice as Record<string, unknown>;
+ if (record.type !== "function" || !record.function || typeof record.function !== "object")
+ return null;
+ const name = (record.function as Record<string, unknown>).name;
+ return typeof name === "string" && name.trim() ? name.trim() : null;
+}
+
+function parseOpenAIMessages(
+ messages: Array<Record<string, unknown>>,
+ beforeLatestUser = ""
+): string {
+ const parts: string[] = [];
+ let lastUserIdx = -1;
+ let lastUserSourceIdx = -1;
+
+ for (let i = messages.length - 1; i >= 0; i--) {
+ if (String(messages[i].role || "") === "user") {
+ lastUserSourceIdx = i;
+ break;
+ }
+ }
+
+ // Extract text from each message
+ const extracted: Array<{ role: string; text: string }> = [];
+
+ for (let msgIdx = 0; msgIdx < messages.length; msgIdx++) {
+ const msg = messages[msgIdx];
+ let role = String(msg.role || "user");
+ if (role === "developer") role = "system";
+
+ let content = extractTextContent(msg);
+ if (role === "tool") {
+ if (msgIdx < lastUserSourceIdx) continue;
+ const toolName = typeof msg.name === "string" ? msg.name : "unknown_tool";
+ const toolCallId = typeof msg.tool_call_id === "string" ? msg.tool_call_id : "unknown_call";
+ content = `CLIENT TOOL RESULT from caller runtime for ${toolName} (${toolCallId}). Use this result to answer; do not call the same tool again:\n${content}`;
+ } else if (role === "assistant" && Array.isArray(msg.tool_calls)) {
+ if (msgIdx < lastUserSourceIdx) continue;
+ const calls = (msg.tool_calls as Array<Record<string, unknown>>).map((call) => ({
+ id: call.id,
+ function: call.function,
+ }));
+ content = [content, `Previous assistant tool calls: ${JSON.stringify(calls)}`]
+ .filter(Boolean)
+ .join("\n");
+ }
+ if (!content.trim()) continue;
+ extracted.push({ role, text: content });
+ }
+
+ // Find last user message index
+ for (let i = extracted.length - 1; i >= 0; i--) {
+ if (extracted[i].role === "user") {
+ lastUserIdx = i;
+ break;
+ }
+ }
+
+ // Build combined message — last user message is raw, others are prefixed
+ for (let i = 0; i < extracted.length; i++) {
+ const { role, text } = extracted[i];
+ if (i === lastUserIdx) {
+ parts.push(text);
+ } else {
+ parts.push(`${role}: ${text}`);
+ }
+ }
+
+ if (beforeLatestUser.trim()) {
+ parts.push(beforeLatestUser.trim());
+ }
+
+ return parts.join("\n\n");
+}
+
+function buildGrokToolRegistry(body: Record<string, unknown>): GrokToolRegistry {
+ const tools = Array.isArray(body.tools) ? (body.tools as Array<Record<string, unknown>>) : [];
+ const messages = Array.isArray(body.messages)
+ ? (body.messages as Array<Record<string, unknown>>)
+ : [];
+ const lastUserText = getLastUserText(messages);
+ const executedToolState = getExecutedToolState(messages);
+ const toolChoice = body.tool_choice ?? "auto";
+
+ if (toolChoice === "none") {
+ return {
+ enabled: false,
+ toolsByName: new Map(),
+ lastUserText,
+ executedToolKeys: executedToolState.keys,
+ completedToolCalls: executedToolState.summaries,
+ };
+ }
+
+ const functionTools: GrokFunctionToolSummary[] = tools
+ .map((tool) => {
+ const fn = tool?.function;
+ if (tool?.type !== "function" || !fn || typeof fn !== "object") return null;
+ const record = fn as Record<string, unknown>;
+ const name = typeof record.name === "string" ? record.name.trim() : "";
+ if (!name) return null;
+ return {
+ name,
+ ...(typeof record.description === "string" ? { description: record.description } : {}),
+ parameters: record.parameters || { type: "object", properties: {} },
+ };
+ })
+ .filter((tool): tool is GrokFunctionToolSummary => Boolean(tool));
+ const forcedName = forcedToolChoiceName(toolChoice);
+ const visibleTools = forcedName
+ ? functionTools.filter((tool) => tool.name === forcedName)
+ : functionTools;
+
+ return {
+ enabled: visibleTools.length > 0,
+ toolsByName: new Map(visibleTools.map((tool) => [tool.name, tool])),
+ lastUserText,
+ executedToolKeys: executedToolState.keys,
+ completedToolCalls: executedToolState.summaries,
+ };
+}
+
+function getSchemaProperties(parameters: unknown): Record<string, unknown> {
+ if (!parameters || typeof parameters !== "object") return {};
+ const properties = (parameters as Record<string, unknown>).properties;
+ return properties && typeof properties === "object"
+ ? (properties as Record<string, unknown>)
+ : {};
+}
+
+function getSchemaRequired(parameters: unknown): string[] {
+ if (!parameters || typeof parameters !== "object") return [];
+ const required = (parameters as Record<string, unknown>).required;
+ return Array.isArray(required)
+ ? required.filter((key): key is string => typeof key === "string")
+ : [];
+}
+
+function formatToolArgsSummary(parameters: unknown): string {
+ const properties = getSchemaProperties(parameters);
+ const propNames = Object.keys(properties);
+ const required = getSchemaRequired(parameters);
+ const segments: string[] = [];
+ if (propNames.length > 0) segments.push(`args=${propNames.join(",")}`);
+ if (required.length > 0) segments.push(`required=${required.join(",")}`);
+ return segments.length > 0 ? ` (${segments.join("; ")})` : "";
+}
+
+function toolText(tool: GrokFunctionToolSummary): string {
+ return `${tool.name} ${tool.description || ""}`.toLowerCase();
+}
+
+function hasAnyProperty(tool: GrokFunctionToolSummary, names: string[]): boolean {
+ const properties = getSchemaProperties(tool.parameters);
+ const lowerProps = new Set(Object.keys(properties).map((key) => key.toLowerCase()));
+ return names.some((name) => lowerProps.has(name.toLowerCase()));
+}
+
+function isTerminalTool(tool: GrokFunctionToolSummary): boolean {
+ if (isMetaOrInfrastructureTool(tool)) return false;
+ const text = toolText(tool);
+ const name = tool.name.toLowerCase();
+ const explicitName = /\b(bash|shell|terminal|run_command|execute_command|exec|command)\b/.test(
+ name
+ );
+ const explicitText =
+ /\b(?:run|execute).{0,24}\b(?:shell|bash|terminal|command)\b|\b(?:shell|bash|terminal)\b/.test(
+ text
+ );
+ return explicitName || (hasAnyProperty(tool, ["command", "cmd", "shell"]) && explicitText);
+}
+
+function isFileReadTool(tool: GrokFunctionToolSummary): boolean {
+ const text = toolText(tool);
+ return (
+ hasAnyProperty(tool, ["filePath", "file_path", "path"]) &&
+ /\b(read|file|filesystem|open)\b/.test(text) &&
+ !/\b(write|edit|patch|delete|remove|grep|search|bash|shell|command)\b/.test(text)
+ );
+}
+
+function isUrlFetchTool(tool: GrokFunctionToolSummary): boolean {
+ const text = toolText(tool);
+ const name = tool.name.toLowerCase();
+ const explicitName =
+ /\b(webfetch|web.fetch|fetch_url|url_fetch|read_url|browse_page|browsepage)\b/.test(name);
+ const explicitUrlText =
+ /\b(?:fetch|browse|read).{0,32}\b(?:url|uri|web page|page content)\b|\b(?:url|uri|web page|page content).{0,32}\b(?:fetch|browse|read)\b/.test(
+ text
+ );
+ return (
+ explicitName ||
+ (!isMetaOrInfrastructureTool(tool) && hasAnyProperty(tool, ["url", "uri"]) && explicitUrlText)
+ );
+}
+
+function isWebSearchTool(tool: GrokFunctionToolSummary): boolean {
+ const text = toolText(tool);
+ return (
+ hasAnyProperty(tool, ["query", "search"]) &&
+ /\b(web|internet|exa|browser|browse|serp)\b/.test(text) &&
+ !isMetaOrInfrastructureTool(tool) &&
+ !isContextMemoryTool(tool)
+ );
+}
+
+function isContextMemoryTool(tool: GrokFunctionToolSummary): boolean {
+ const text = toolText(tool);
+ return /\b(ctx_|memory|memories|conversation history|session notes|git commits|project memories|context.db|magic context)\b/.test(
+ text
+ );
+}
+
+function isMetaOrInfrastructureTool(tool: GrokFunctionToolSummary): boolean {
+ const text = toolText(tool);
+ return /\b(mcp|mcpproxy|upstream|registry|registries|quarantine|oauth|cache key|token usage|session notes|conversation transcript|handoff|context management|memory|memories|lsp|language server|plan file|server management|tool discovery|tools? using bm25)\b/.test(
+ text
+ );
+}
+
+function baseToolOrderScore(tool: GrokFunctionToolSummary): number {
+ if (isUrlFetchTool(tool)) return 90;
+ if (isWebSearchTool(tool)) return 85;
+ if (isFileReadTool(tool)) return 75;
+ if (isTerminalTool(tool)) return 70;
+ if (/\b(glob|grep|search files?|file search|content search)\b/.test(toolText(tool))) return 60;
+ if (/\b(edit|write|patch|modify|apply)\b/.test(toolText(tool))) return 50;
+ if (/\b(task|agent|delegate|subagent)\b/.test(toolText(tool))) return 40;
+ if (isMetaOrInfrastructureTool(tool)) return 10;
+ if (isContextMemoryTool(tool)) return 20;
+ return 30;
+}
+
+function latestUserIntentScore(tool: GrokFunctionToolSummary, lastUserText: string): number {
+ const user = lastUserText.toLowerCase();
+ const hasPath = /(?:^|\s|["'`])(?:~|\.?\.?\/|\/)[^\s"'`]+/.test(lastUserText);
+ const hasUrl = !!extractFirstUrl(lastUserText);
+ const asksLineCount = /\b(l[ií]neas?|line count|cu[aá]ntas? l[ií]neas?|wc\s+-l)\b/.test(user);
+ const asksFileContent =
+ /\b(lee|leer|read|archivo|file|json|config|modelo|default|por defecto|de qu[eé] va|consiste|contenido)\b/.test(
+ user
+ ) && hasPath;
+ const asksContext =
+ /\b(contexto|memoria|historial|conversation history|project memories|ctx_|memory|memories|recordabas?)\b/.test(
+ user
+ );
+ const asksWeb =
+ !asksContext &&
+ /\b(web|internet|fuente|oficial|release|versi[oó]n|ubuntu|latest|actual|contrasta|busca|search)\b/.test(
+ user
+ );
+ let score = 0;
+
+ if (asksFileContent && isFileReadTool(tool)) score += 160;
+ if (asksFileContent && isTerminalTool(tool)) score += asksLineCount ? 70 : 20;
+ if (asksLineCount && isTerminalTool(tool)) score += 120;
+ if (asksLineCount && isFileReadTool(tool)) score += asksFileContent ? 90 : 30;
+ if (asksWeb && !hasUrl && isWebSearchTool(tool)) score += 170;
+ if (asksWeb && !hasUrl && isUrlFetchTool(tool)) score += 35;
+ if (asksWeb && isContextMemoryTool(tool)) score -= 120;
+ if (asksContext && isContextMemoryTool(tool)) score += 170;
+ if (asksContext && isWebSearchTool(tool)) score -= 80;
+
+ if (isContextMemoryTool(tool) && (asksFileContent || asksWeb)) score -= 80;
+ return score;
+}
+
+function orderedToolsForManifest(
+ toolRegistry: GrokToolRegistry
+): Array<{ tool: GrokFunctionToolSummary; score: number }> {
+ return [...toolRegistry.toolsByName.values()]
+ .map((tool, index) => ({
+ tool,
+ score: latestUserIntentScore(tool, toolRegistry.lastUserText) + baseToolOrderScore(tool),
+ meta: isMetaOrInfrastructureTool(tool),
+ index,
+ }))
+ .sort((a, b) => b.score - a.score || Number(a.meta) - Number(b.meta) || a.index - b.index)
+ .map(({ tool, score }) => ({ tool, score }));
+}
+
+function formatToolManifestEntry(tool: GrokFunctionToolSummary, rank: number): string {
+ const desc = tool.description ? `\n description: ${tool.description}` : "";
+ const args = formatToolArgsSummary(tool.parameters).trim();
+ return `${rank}. name: ${tool.name}${args ? `\n ${args.slice(1, -1)}` : ""}${desc ? desc.replace(/\n /g, "\n ") : ""}`;
+}
+
+function buildClientToolManifest(toolRegistry: GrokToolRegistry, toolChoice: unknown): string {
+ if (!toolRegistry.enabled) return "";
+ const orderedTools = orderedToolsForManifest(toolRegistry);
+ const lines = [
+ 'CLIENT_TOOLS: use this caller-runtime tool list as the tool interface for this request. To call one, respond only with <tool_call>{"name":"exact_tool_name","arguments":{...}}</tool_call>. After tool results, answer normally.',
+ `tool_choice=${JSON.stringify(toolChoice ?? "auto")}`,
+ ...(toolRegistry.completedToolCalls.length > 0
+ ? [
+ "completed_tool_calls:",
+ ...toolRegistry.completedToolCalls.map((summary) => `- ${summary}`),
+ "Do not repeat completed tool calls unless a different result is required; use their tool results to answer.",
+ ]
+ : []),
+ "tools (priority order for this request):",
+ ...orderedTools.map(({ tool }, index) => formatToolManifestEntry(tool, index + 1)),
+ ];
+ return lines.join("\n");
+}
+
+function buildGrokMessage(
+ messages: Array<Record<string, unknown>>,
+ toolRegistry: GrokToolRegistry,
+ toolChoice: unknown
+): string {
+ const manifest = buildClientToolManifest(toolRegistry, toolChoice);
+ return parseOpenAIMessages(messages, manifest);
+}
+
+function propertyType(properties: Record<string, unknown>, key: string): string | undefined {
+ const prop = properties[key];
+ if (!prop || typeof prop !== "object") return undefined;
+ const type = (prop as Record<string, unknown>).type;
+ return typeof type === "string" ? type : undefined;
+}
+
+function hasValue(value: unknown): boolean {
+ return value !== undefined && value !== null && value !== "";
+}
+
+function firstString(...values: unknown[]): string | undefined {
+ for (const value of values) {
+ if (typeof value === "string" && value.trim()) return value;
+ }
+ return undefined;
+}
+
+function defaultRequiredValue(
+ key: string,
+ type: string | undefined,
+ args: Record<string, unknown>,
+ intent: string
+): unknown {
+ const lower = key.toLowerCase();
+ const command = firstString(args.command, args.cmd, args.shell, args.input);
+ const path = firstString(args.filePath, args.file_path, args.path, args.filename);
+ const query = firstString(args.query, args.search, args.input);
+ const url = firstString(args.url, args.uri);
+
+ if (lower === "command" || lower === "cmd") return command;
+ if (lower === "filepath" || lower === "file_path" || lower === "path") return path;
+ if (lower === "query" || lower === "search") return query;
+ if (lower === "url" || lower === "uri") return url;
+ if (lower === "input") return query || url || command || path;
+ if (lower === "description" || lower === "reason" || lower === "intent_reason") {
+ if (command) return `Execute shell command: ${command}`;
+ if (path) return `Read file: ${path}`;
+ if (url) return `Fetch URL: ${url}`;
+ if (query) return `Search: ${query}`;
+ return `Grok Web ${intent} tool call`;
+ }
+ if (lower === "intent_data_sensitivity") return "private";
+ return undefined;
+}
+
+function extractNumericUserParam(text: string, names: string[]): number | undefined {
+ const escaped = names.map((name) => name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|");
+ const re = new RegExp(`\\b(?:${escaped})\\s*(?:=|:|a|de)?\\s*(\\d+)`, "i");
+ const match = text.match(re);
+ if (!match) return undefined;
+ const value = Number(match[1]);
+ return Number.isFinite(value) ? value : undefined;
+}
+
+function adaptArgumentsToDeclaredTool(
+ toolName: string,
+ args: Record<string, unknown>,
+ toolRegistry: GrokToolRegistry,
+ intent: string,
+ options: { preserveUnknownArgs?: boolean } = { preserveUnknownArgs: true }
+): Record<string, unknown> {
+ const tool = toolRegistry.toolsByName.get(toolName);
+ if (!tool) return args;
+ const properties = getSchemaProperties(tool.parameters);
+ const required = getSchemaRequired(tool.parameters);
+ const out: Record<string, unknown> = { ...args };
+
+ // Normalize common aliases only when the declared schema expects them.
+ if ("filePath" in properties && !hasValue(out.filePath))
+ out.filePath = firstString(args.filePath, args.file_path, args.path);
+ if ("file_path" in properties && !hasValue(out.file_path))
+ out.file_path = firstString(args.file_path, args.filePath, args.path);
+ if ("path" in properties && !hasValue(out.path))
+ out.path = firstString(args.path, args.filePath, args.file_path);
+ if ("query" in properties && !hasValue(out.query))
+ out.query = firstString(args.query, args.search, args.input);
+ if ("url" in properties && !hasValue(out.url)) out.url = firstString(args.url, args.uri);
+ if ("uri" in properties && !hasValue(out.uri)) out.uri = firstString(args.uri, args.url);
+ if ("input" in properties && !hasValue(out.input))
+ out.input = firstString(args.input, args.query, args.command);
+
+ for (const key of required) {
+ if (hasValue(out[key])) continue;
+ const value = defaultRequiredValue(key, propertyType(properties, key), out, intent);
+ if (value !== undefined) out[key] = value;
+ }
+
+ if (options.preserveUnknownArgs !== false || Object.keys(properties).length === 0) return out;
+
+ const filtered: Record<string, unknown> = {};
+ for (const key of Object.keys(properties)) {
+ if (hasValue(out[key])) filtered[key] = out[key];
+ }
+ for (const key of required) {
+ if (hasValue(out[key])) filtered[key] = out[key];
+ }
+ return filtered;
+}
+
+function normalizeArbitraryToolArguments(value: unknown): Record<string, unknown> {
+ if (!value) return {};
+ if (typeof value === "object") return value as Record<string, unknown>;
+ if (typeof value === "string") {
+ try {
+ const parsed = JSON.parse(value);
+ return parsed && typeof parsed === "object" ? (parsed as Record<string, unknown>) : {};
+ } catch {
+ return { input: value };
+ }
+ }
+ return {};
+}
+
+function parseClientToolCallMarkup(
+ text: string,
+ toolRegistry: GrokToolRegistry
+): OpenAIToolCall[] | null {
+ if (!toolRegistry.enabled || !text.includes("<tool_call>")) return null;
+ const calls: OpenAIToolCall[] = [];
+ const re = /<tool_call>\s*([\s\S]*?)\s*<\/tool_call>/g;
+ for (const match of text.matchAll(re)) {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(match[1]);
+ } catch {
+ continue;
+ }
+ if (!parsed || typeof parsed !== "object") continue;
+ const record = parsed as Record<string, unknown>;
+ const name = typeof record.name === "string" ? record.name.trim() : "";
+ if (!name || !toolRegistry.toolsByName.has(name)) continue;
+ const rawArgs = normalizeArbitraryToolArguments(record.arguments);
+ const args = adaptArgumentsToDeclaredTool(name, rawArgs, toolRegistry, "clientTool", {
+ preserveUnknownArgs: true,
+ });
+ if (toolRegistry.executedToolKeys.has(semanticToolKey(name, args))) continue;
+ calls.push({
+ id:
+ typeof record.id === "string" && record.id.trim()
+ ? record.id.trim()
+ : `call_${crypto.randomUUID()}`,
+ type: "function",
+ function: { name, arguments: JSON.stringify(args) },
+ });
+ }
+ return calls.length > 0 ? calls : null;
+}
+
+function hasOpenToolCallMarkup(text: string): boolean {
+ return (
+ /<tool(?:_call)?$|<tool_call[^>]*$/.test(text) ||
+ (text.includes("<tool_call>") && !text.includes("</tool_call>"))
+ );
+}
+
+function toolScore(
+ tool: GrokFunctionToolSummary,
+ intent: NativeToolIntent,
+ context: ToolBridgeContext
+): number {
+ const name = tool.name.toLowerCase();
+ const description = (tool.description || "").toLowerCase();
+ const properties = getSchemaProperties(tool.parameters);
+ const propNames = new Set(Object.keys(properties).map((key) => key.toLowerCase()));
+ const text = `${name} ${description}`;
+ const userText = context.lastUserText.toLowerCase();
+ let score = 0;
+
+ if (intent === "bash") {
+ if (!isTerminalTool(tool)) score -= 80;
+ if (name === "bash") score += 100;
+ if (["shell", "terminal", "run_command", "execute_command", "exec", "command"].includes(name))
+ score += 80;
+ if (propNames.has("command") || propNames.has("cmd")) score += 60;
+ if (/bash|shell|terminal|command|execute|run/.test(text)) score += 25;
+ if (/read|search|grep|web|http|browser|context|note|memory/.test(name)) score -= 50;
+ } else if (intent === "readFile") {
+ if (!isFileReadTool(tool)) score -= 60;
+ if (["read", "read_file", "readfile", "file_read"].includes(name)) score += 100;
+ if (propNames.has("filepath") || propNames.has("file_path") || propNames.has("path"))
+ score += 50;
+ if (/read.*file|file.*read|filesystem/.test(text)) score += 25;
+ if (/write|edit|delete|remove|bash|shell|command/.test(text)) score -= 50;
+ } else if (intent === "webSearch" || intent === "browsePage") {
+ const preferUrlFetch = wantsUrlFetch(userText);
+ if (isContextMemoryTool(tool) || isMetaOrInfrastructureTool(tool)) score -= 180;
+ if (intent === "browsePage" || preferUrlFetch) {
+ if (!isUrlFetchTool(tool)) score -= 60;
+ if (/webfetch|web_fetch|fetch|browse|browse_page|read_url|url_fetch|page/.test(name))
+ score += 140;
+ if (propNames.has("url") || propNames.has("uri")) score += 90;
+ if (/fetch|browse|url|web page|page content|extract.*url|read.*url/.test(text)) score += 55;
+ if (
+ /websearch|web_search|search/.test(name) &&
+ !(propNames.has("url") || propNames.has("uri"))
+ )
+ score -= 80;
+ }
+ if (intent === "webSearch" && !isWebSearchTool(tool)) score -= 60;
+ if (
+ intent === "browsePage" &&
+ /\b(websearch|web_search|search)\b/.test(name) &&
+ !(propNames.has("url") || propNames.has("uri"))
+ )
+ score -= 120;
+ if (["web_search", "websearch", "search"].includes(name)) score += 100;
+ if (propNames.has("query") || propNames.has("search")) score += 50;
+ if (/web.*search|search.*web|internet|browse/.test(text)) score += 25;
+ if (/file|bash|shell|command|write|edit/.test(text)) score -= 50;
+ }
+
+ return score;
+}
+
+function pickDeclaredToolForIntent(
+ intent: NativeToolIntent,
+ toolRegistry: GrokToolRegistry
+): string | null {
+ let best: { name: string; score: number } | null = null;
+ for (const tool of toolRegistry.toolsByName.values()) {
+ const score = toolScore(tool, intent, { lastUserText: toolRegistry.lastUserText });
+ if (score <= 0) continue;
+ if (!best || score > best.score) best = { name: tool.name, score };
+ }
+ return best?.name || null;
+}
+
+function mapGrokNativeToolToOpenAI(
+ resp: GrokStreamResponse,
+ toolRegistry: GrokToolRegistry
+): OpenAIToolCall | null {
+ if (!toolRegistry.enabled || !resp.toolUsageCard) return null;
+ const card = resp.toolUsageCard as Record<string, unknown>;
+ const id = resp.toolUsageCardId || String(card.toolUsageCardId || `call_${crypto.randomUUID()}`);
+
+ const bash = card.bash as { args?: Record<string, unknown> } | undefined;
+ if (bash?.args) {
+ const name = pickDeclaredToolForIntent("bash", toolRegistry);
+ if (name) {
+ const args = adaptArgumentsToDeclaredTool(name, bash.args, toolRegistry, "bash", {
+ preserveUnknownArgs: false,
+ });
+ if (toolRegistry.executedToolKeys.has(semanticToolKey(name, args))) return null;
+ return { id, type: "function", function: { name, arguments: JSON.stringify(args) } };
+ }
+ }
+
+ const readFile = (card.readFile || card.read_file) as
+ | { args?: Record<string, unknown> }
+ | undefined;
+ if (readFile?.args) {
+ const rawPath = readFile.args.filePath || readFile.args.file_path || readFile.args.path;
+ const name = pickDeclaredToolForIntent("readFile", toolRegistry);
+ if (name && typeof rawPath === "string") {
+ const userOffset = extractNumericUserParam(toolRegistry.lastUserText, ["offset"]);
+ const userLimit = extractNumericUserParam(toolRegistry.lastUserText, [
+ "limit",
+ "limite",
+ "límite",
+ ]);
+ const rawArgs = {
+ ...readFile.args,
+ ...(userOffset !== undefined ? { offset: userOffset } : {}),
+ ...(userLimit !== undefined ? { limit: userLimit } : {}),
+ filePath: rawPath,
+ file_path: rawPath,
+ path: rawPath,
+ };
+ const args = adaptArgumentsToDeclaredTool(name, rawArgs, toolRegistry, "readFile", {
+ preserveUnknownArgs: false,
+ });
+ if (toolRegistry.executedToolKeys.has(semanticToolKey(name, args))) return null;
+ return { id, type: "function", function: { name, arguments: JSON.stringify(args) } };
+ }
+ }
+
+ const webSearch = card.webSearch as { args?: Record<string, unknown> } | undefined;
+ if (webSearch?.args) {
+ const name = pickDeclaredToolForIntent("webSearch", toolRegistry);
+ if (name) {
+ const requestedUrl = wantsUrlFetch(toolRegistry.lastUserText)
+ ? extractFirstUrl(toolRegistry.lastUserText)
+ : undefined;
+ const args = adaptArgumentsToDeclaredTool(
+ name,
+ requestedUrl ? { ...webSearch.args, url: requestedUrl, uri: requestedUrl } : webSearch.args,
+ toolRegistry,
+ requestedUrl ? "webFetch" : "webSearch",
+ { preserveUnknownArgs: false }
+ );
+ if (toolRegistry.executedToolKeys.has(semanticToolKey(name, args))) return null;
+ return { id, type: "function", function: { name, arguments: JSON.stringify(args) } };
+ }
+ }
+
+ const browsePage = (card.browsePage || card.browse_page) as
+ | { args?: Record<string, unknown> }
+ | undefined;
+ if (browsePage?.args) {
+ const url = firstString(browsePage.args.url, browsePage.args.uri);
+ const name = pickDeclaredToolForIntent("browsePage", toolRegistry);
+ if (name && url) {
+ const args = adaptArgumentsToDeclaredTool(
+ name,
+ { ...browsePage.args, url, uri: url, input: url },
+ toolRegistry,
+ "browsePage",
+ { preserveUnknownArgs: false }
+ );
+ if (toolRegistry.executedToolKeys.has(semanticToolKey(name, args))) return null;
+ return { id, type: "function", function: { name, arguments: JSON.stringify(args) } };
+ }
+ }
+
+ return null;
+}
+
+// ─── NDJSON stream types ────────────────────────────────────────────────────
+
+interface GrokStreamResponse {
+ token?: string;
+ isThinking?: boolean;
+ reasoning?: string;
+ reasoningContent?: string;
+ reasoning_content?: string;
+ thinking?: string;
+ thought?: string;
+ responseId?: string;
+ messageTag?: string;
+ messageStepId?: number;
+ toolUsageCardId?: string;
+ toolUsageCard?: {
+ toolUsageCardId?: string;
+ bash?: { args?: Record<string, unknown> };
+ readFile?: { args?: Record<string, unknown> };
+ read_file?: { args?: Record<string, unknown> };
+ webSearch?: { args?: Record<string, unknown> };
+ browsePage?: { args?: Record<string, unknown> };
+ browse_page?: { args?: Record<string, unknown> };
+ };
+ webSearchResults?: {
+ results?: Array<Record<string, unknown>>;
+ };
+ llmInfo?: { modelHash?: string };
+ modelResponse?: {
+ message?: string;
+ reasoning?: string;
+ reasoningContent?: string;
+ reasoning_content?: string;
+ thinking?: string;
+ thought?: string;
+ responseId?: string;
+ generatedImageUrls?: string[];
+ metadata?: { llm_info?: { modelHash?: string } };
+ pipelineToken?: string;
+ };
+}
+
+interface GrokStreamEvent {
+ result?: { response?: GrokStreamResponse };
+ error?: { message?: string; code?: string };
+}
+
// ─── NDJSON parsing ─────────────────────────────────────────────────────────
async function* readGrokNdjsonEvents(
@@ -152,6 +1005,141 @@ async function* readGrokNdjsonEvents(
}
}
+// ─── Grok markup cleanup ────────────────────────────────────────────────────
+
+const BLOCKED_GROK_MARKUP = [
+ { start: "<xai:tool_usage_card", end: "</xai:tool_usage_card>" },
+] as const;
+
+const PARTIAL_GROK_MARKER_KEEP = 32;
+
+function stripLooseGrokMarkup(text: string): string {
+ return text
+ .replace(/<\/?xai:[^>]*>/g, "")
+ .replace(/<\/?grok:[^>]*>/g, "")
+ .replace(/<\/?argument\b[^>]*>/g, "")
+ .replace(/<!\[CDATA\[/g, "")
+ .replace(/\]\]>/g, "");
+}
+
+class GrokMarkupFilter {
+ private buffer = "";
+ private suppressedUntil: string | null = null;
+
+ feed(text: string): string {
+ if (!text) return "";
+ this.buffer += text;
+ return this.drain(false);
+ }
+
+ flush(): string {
+ const out = this.drain(true);
+ this.buffer = "";
+ this.suppressedUntil = null;
+ return out;
+ }
+
+ private drain(flush: boolean): string {
+ let out = "";
+
+ while (this.buffer) {
+ if (this.suppressedUntil) {
+ const endIdx = this.buffer.indexOf(this.suppressedUntil);
+ if (endIdx < 0) {
+ this.buffer = this.buffer.slice(this.longestEndPrefixStart(this.suppressedUntil));
+ return out;
+ }
+ this.buffer = this.buffer.slice(endIdx + this.suppressedUntil.length);
+ this.suppressedUntil = null;
+ continue;
+ }
+
+ let nextStart = -1;
+ let nextEnd = "";
+ for (const marker of BLOCKED_GROK_MARKUP) {
+ const idx = this.buffer.indexOf(marker.start);
+ if (idx >= 0 && (nextStart < 0 || idx < nextStart)) {
+ nextStart = idx;
+ nextEnd = marker.end;
+ }
+ }
+
+ if (nextStart < 0) {
+ if (!flush) {
+ const lastLt = this.buffer.lastIndexOf("<");
+ if (lastLt >= 0 && this.buffer.length - lastLt <= PARTIAL_GROK_MARKER_KEEP) {
+ out += stripLooseGrokMarkup(this.buffer.slice(0, lastLt));
+ this.buffer = this.buffer.slice(lastLt);
+ return out;
+ }
+ }
+ out += stripLooseGrokMarkup(this.buffer);
+ this.buffer = "";
+ return out;
+ }
+
+ out += stripLooseGrokMarkup(this.buffer.slice(0, nextStart));
+ this.buffer = this.buffer.slice(nextStart);
+ const endIdx = this.buffer.indexOf(nextEnd);
+ const openTagEndIdx = this.buffer.indexOf(">");
+ if (openTagEndIdx >= 0 && /\/\s*>$/.test(this.buffer.slice(0, openTagEndIdx + 1))) {
+ this.buffer = this.buffer.slice(openTagEndIdx + 1);
+ continue;
+ }
+ if (endIdx < 0) {
+ this.suppressedUntil = nextEnd;
+ this.buffer = this.buffer.slice(this.longestEndPrefixStart(nextEnd));
+ return out;
+ }
+ this.buffer = this.buffer.slice(endIdx + nextEnd.length);
+ }
+
+ return out;
+ }
+
+ private longestEndPrefixStart(end: string): number {
+ const max = Math.min(this.buffer.length, end.length - 1);
+ for (let len = max; len > 0; len--) {
+ if (this.buffer.slice(-len) === end.slice(0, len)) return this.buffer.length - len;
+ }
+ return this.buffer.length;
+ }
+}
+
+function cleanGrokText(text: string): string {
+ const filter = new GrokMarkupFilter();
+ return filter.feed(text) + filter.flush();
+}
+
+function cleanGrokContentText(text: string): string {
+ return cleanGrokText(text);
+}
+
+function cleanGrokThinkingText(resp: GrokStreamResponse): string {
+ const text = resp.token || "";
+ const cleaned = cleanGrokText(text);
+ const trimmed = cleaned.trim();
+ if (!trimmed) return "";
+ const isGenericOpeningHeader =
+ resp.messageTag === "header" &&
+ resp.messageStepId === 0 &&
+ /^(?:\.{3}|thinking(?: about your request)?)$/i.test(trimmed);
+ if (isGenericOpeningHeader) return "";
+ if (resp.messageTag === "header") return `${trimmed}\n`;
+ if (resp.messageTag === "summary") return `${trimmed}\n`;
+ return cleaned;
+}
+
+function extractStructuredReasoning(value: object | undefined): string {
+ if (!value) return "";
+ const record = value as Record<string, unknown>;
+ for (const key of ["reasoning", "reasoningContent", "reasoning_content", "thinking", "thought"]) {
+ const candidate = record[key];
+ if (typeof candidate === "string" && candidate.trim()) return cleanGrokText(candidate);
+ }
+ return "";
+}
+
// ─── Content extraction ─────────────────────────────────────────────────────
interface ContentChunk {
@@ -666,7 +1654,8 @@ export class GrokWebExecutor extends BaseExecutor {
upstreamExtraHeaders,
}: ExecuteInput) {
const messages = (body as Record<string, unknown>).messages as
- Array<Record<string, unknown>> | undefined;
+ | Array<Record<string, unknown>>
+ | undefined;
if (!messages || !Array.isArray(messages) || messages.length === 0) {
const errResp = new Response(
JSON.stringify({
diff --git a/open-sse/executors/grok-web/native-tools.ts b/open-sse/executors/grok-web/native-tools.ts
deleted file mode 100644
index ba003072a6..0000000000
--- a/open-sse/executors/grok-web/native-tools.ts
+++ /dev/null
@@ -1,182 +0,0 @@
-// Grok native-tool selection + native->OpenAI mapping (pure). Verbatim from grok-web.ts.
-import type { GrokStreamResponse } from "./types.ts";
-import {
- type OpenAIToolCall,
- type GrokToolRegistry,
- type GrokFunctionToolSummary,
- type NativeToolIntent,
- type ToolBridgeContext,
- semanticToolKey,
- extractFirstUrl,
- wantsUrlFetch,
- getSchemaProperties,
- isTerminalTool,
- isFileReadTool,
- isUrlFetchTool,
- isWebSearchTool,
- isContextMemoryTool,
- isMetaOrInfrastructureTool,
- firstString,
- extractNumericUserParam,
- adaptArgumentsToDeclaredTool,
-} from "./tool-bridge.ts";
-
-export function toolScore(
- tool: GrokFunctionToolSummary,
- intent: NativeToolIntent,
- context: ToolBridgeContext
-): number {
- const name = tool.name.toLowerCase();
- const description = (tool.description || "").toLowerCase();
- const properties = getSchemaProperties(tool.parameters);
- const propNames = new Set(Object.keys(properties).map((key) => key.toLowerCase()));
- const text = `${name} ${description}`;
- const userText = context.lastUserText.toLowerCase();
- let score = 0;
-
- if (intent === "bash") {
- if (!isTerminalTool(tool)) score -= 80;
- if (name === "bash") score += 100;
- if (["shell", "terminal", "run_command", "execute_command", "exec", "command"].includes(name))
- score += 80;
- if (propNames.has("command") || propNames.has("cmd")) score += 60;
- if (/bash|shell|terminal|command|execute|run/.test(text)) score += 25;
- if (/read|search|grep|web|http|browser|context|note|memory/.test(name)) score -= 50;
- } else if (intent === "readFile") {
- if (!isFileReadTool(tool)) score -= 60;
- if (["read", "read_file", "readfile", "file_read"].includes(name)) score += 100;
- if (propNames.has("filepath") || propNames.has("file_path") || propNames.has("path"))
- score += 50;
- if (/read.*file|file.*read|filesystem/.test(text)) score += 25;
- if (/write|edit|delete|remove|bash|shell|command/.test(text)) score -= 50;
- } else if (intent === "webSearch" || intent === "browsePage") {
- const preferUrlFetch = wantsUrlFetch(userText);
- if (isContextMemoryTool(tool) || isMetaOrInfrastructureTool(tool)) score -= 180;
- if (intent === "browsePage" || preferUrlFetch) {
- if (!isUrlFetchTool(tool)) score -= 60;
- if (/webfetch|web_fetch|fetch|browse|browse_page|read_url|url_fetch|page/.test(name))
- score += 140;
- if (propNames.has("url") || propNames.has("uri")) score += 90;
- if (/fetch|browse|url|web page|page content|extract.*url|read.*url/.test(text)) score += 55;
- if (
- /websearch|web_search|search/.test(name) &&
- !(propNames.has("url") || propNames.has("uri"))
- )
- score -= 80;
- }
- if (intent === "webSearch" && !isWebSearchTool(tool)) score -= 60;
- if (
- intent === "browsePage" &&
- /\b(websearch|web_search|search)\b/.test(name) &&
- !(propNames.has("url") || propNames.has("uri"))
- )
- score -= 120;
- if (["web_search", "websearch", "search"].includes(name)) score += 100;
- if (propNames.has("query") || propNames.has("search")) score += 50;
- if (/web.*search|search.*web|internet|browse/.test(text)) score += 25;
- if (/file|bash|shell|command|write|edit/.test(text)) score -= 50;
- }
-
- return score;
-}
-
-export function pickDeclaredToolForIntent(
- intent: NativeToolIntent,
- toolRegistry: GrokToolRegistry
-): string | null {
- let best: { name: string; score: number } | null = null;
- for (const tool of toolRegistry.toolsByName.values()) {
- const score = toolScore(tool, intent, { lastUserText: toolRegistry.lastUserText });
- if (score <= 0) continue;
- if (!best || score > best.score) best = { name: tool.name, score };
- }
- return best?.name || null;
-}
-
-export function mapGrokNativeToolToOpenAI(
- resp: GrokStreamResponse,
- toolRegistry: GrokToolRegistry
-): OpenAIToolCall | null {
- if (!toolRegistry.enabled || !resp.toolUsageCard) return null;
- const card = resp.toolUsageCard as Record<string, unknown>;
- const id = resp.toolUsageCardId || String(card.toolUsageCardId || `call_${crypto.randomUUID()}`);
-
- const bash = card.bash as { args?: Record<string, unknown> } | undefined;
- if (bash?.args) {
- const name = pickDeclaredToolForIntent("bash", toolRegistry);
- if (name) {
- const args = adaptArgumentsToDeclaredTool(name, bash.args, toolRegistry, "bash", {
- preserveUnknownArgs: false,
- });
- if (toolRegistry.executedToolKeys.has(semanticToolKey(name, args))) return null;
- return { id, type: "function", function: { name, arguments: JSON.stringify(args) } };
- }
- }
-
- const readFile = (card.readFile || card.read_file) as
- { args?: Record<string, unknown> } | undefined;
- if (readFile?.args) {
- const rawPath = readFile.args.filePath || readFile.args.file_path || readFile.args.path;
- const name = pickDeclaredToolForIntent("readFile", toolRegistry);
- if (name && typeof rawPath === "string") {
- const userOffset = extractNumericUserParam(toolRegistry.lastUserText, ["offset"]);
- const userLimit = extractNumericUserParam(toolRegistry.lastUserText, [
- "limit",
- "limite",
- "límite",
- ]);
- const rawArgs = {
- ...readFile.args,
- ...(userOffset !== undefined ? { offset: userOffset } : {}),
- ...(userLimit !== undefined ? { limit: userLimit } : {}),
- filePath: rawPath,
- file_path: rawPath,
- path: rawPath,
- };
- const args = adaptArgumentsToDeclaredTool(name, rawArgs, toolRegistry, "readFile", {
- preserveUnknownArgs: false,
- });
- if (toolRegistry.executedToolKeys.has(semanticToolKey(name, args))) return null;
- return { id, type: "function", function: { name, arguments: JSON.stringify(args) } };
- }
- }
-
- const webSearch = card.webSearch as { args?: Record<string, unknown> } | undefined;
- if (webSearch?.args) {
- const name = pickDeclaredToolForIntent("webSearch", toolRegistry);
- if (name) {
- const requestedUrl = wantsUrlFetch(toolRegistry.lastUserText)
- ? extractFirstUrl(toolRegistry.lastUserText)
- : undefined;
- const args = adaptArgumentsToDeclaredTool(
- name,
- requestedUrl ? { ...webSearch.args, url: requestedUrl, uri: requestedUrl } : webSearch.args,
- toolRegistry,
- requestedUrl ? "webFetch" : "webSearch",
- { preserveUnknownArgs: false }
- );
- if (toolRegistry.executedToolKeys.has(semanticToolKey(name, args))) return null;
- return { id, type: "function", function: { name, arguments: JSON.stringify(args) } };
- }
- }
-
- const browsePage = (card.browsePage || card.browse_page) as
- { args?: Record<string, unknown> } | undefined;
- if (browsePage?.args) {
- const url = firstString(browsePage.args.url, browsePage.args.uri);
- const name = pickDeclaredToolForIntent("browsePage", toolRegistry);
- if (name && url) {
- const args = adaptArgumentsToDeclaredTool(
- name,
- { ...browsePage.args, url, uri: url, input: url },
- toolRegistry,
- "browsePage",
- { preserveUnknownArgs: false }
- );
- if (toolRegistry.executedToolKeys.has(semanticToolKey(name, args))) return null;
- return { id, type: "function", function: { name, arguments: JSON.stringify(args) } };
- }
- }
-
- return null;
-}
diff --git a/open-sse/executors/grok-web/text-cleanup.ts b/open-sse/executors/grok-web/text-cleanup.ts
deleted file mode 100644
index cbca2b623f..0000000000
--- a/open-sse/executors/grok-web/text-cleanup.ts
+++ /dev/null
@@ -1,137 +0,0 @@
-// Grok markup cleanup (pure). Extracted verbatim from grok-web.ts.
-import type { GrokStreamResponse } from "./types.ts";
-
-// ─── Grok markup cleanup ────────────────────────────────────────────────────
-
-export const BLOCKED_GROK_MARKUP = [
- { start: "<xai:tool_usage_card", end: "</xai:tool_usage_card>" },
-] as const;
-
-export const PARTIAL_GROK_MARKER_KEEP = 32;
-
-export function stripLooseGrokMarkup(text: string): string {
- return text
- .replace(/<\/?xai:[^>]*>/g, "")
- .replace(/<\/?grok:[^>]*>/g, "")
- .replace(/<\/?argument\b[^>]*>/g, "")
- .replace(/<!\[CDATA\[/g, "")
- .replace(/\]\]>/g, "");
-}
-
-export class GrokMarkupFilter {
- private buffer = "";
- private suppressedUntil: string | null = null;
-
- feed(text: string): string {
- if (!text) return "";
- this.buffer += text;
- return this.drain(false);
- }
-
- flush(): string {
- const out = this.drain(true);
- this.buffer = "";
- this.suppressedUntil = null;
- return out;
- }
-
- private drain(flush: boolean): string {
- let out = "";
-
- while (this.buffer) {
- if (this.suppressedUntil) {
- const endIdx = this.buffer.indexOf(this.suppressedUntil);
- if (endIdx < 0) {
- this.buffer = this.buffer.slice(this.longestEndPrefixStart(this.suppressedUntil));
- return out;
- }
- this.buffer = this.buffer.slice(endIdx + this.suppressedUntil.length);
- this.suppressedUntil = null;
- continue;
- }
-
- let nextStart = -1;
- let nextEnd = "";
- for (const marker of BLOCKED_GROK_MARKUP) {
- const idx = this.buffer.indexOf(marker.start);
- if (idx >= 0 && (nextStart < 0 || idx < nextStart)) {
- nextStart = idx;
- nextEnd = marker.end;
- }
- }
-
- if (nextStart < 0) {
- if (!flush) {
- const lastLt = this.buffer.lastIndexOf("<");
- if (lastLt >= 0 && this.buffer.length - lastLt <= PARTIAL_GROK_MARKER_KEEP) {
- out += stripLooseGrokMarkup(this.buffer.slice(0, lastLt));
- this.buffer = this.buffer.slice(lastLt);
- return out;
- }
- }
- out += stripLooseGrokMarkup(this.buffer);
- this.buffer = "";
- return out;
- }
-
- out += stripLooseGrokMarkup(this.buffer.slice(0, nextStart));
- this.buffer = this.buffer.slice(nextStart);
- const endIdx = this.buffer.indexOf(nextEnd);
- const openTagEndIdx = this.buffer.indexOf(">");
- if (openTagEndIdx >= 0 && /\/\s*>$/.test(this.buffer.slice(0, openTagEndIdx + 1))) {
- this.buffer = this.buffer.slice(openTagEndIdx + 1);
- continue;
- }
- if (endIdx < 0) {
- this.suppressedUntil = nextEnd;
- this.buffer = this.buffer.slice(this.longestEndPrefixStart(nextEnd));
- return out;
- }
- this.buffer = this.buffer.slice(endIdx + nextEnd.length);
- }
-
- return out;
- }
-
- private longestEndPrefixStart(end: string): number {
- const max = Math.min(this.buffer.length, end.length - 1);
- for (let len = max; len > 0; len--) {
- if (this.buffer.slice(-len) === end.slice(0, len)) return this.buffer.length - len;
- }
- return this.buffer.length;
- }
-}
-
-export function cleanGrokText(text: string): string {
- const filter = new GrokMarkupFilter();
- return filter.feed(text) + filter.flush();
-}
-
-export function cleanGrokContentText(text: string): string {
- return cleanGrokText(text);
-}
-
-export function cleanGrokThinkingText(resp: GrokStreamResponse): string {
- const text = resp.token || "";
- const cleaned = cleanGrokText(text);
- const trimmed = cleaned.trim();
- if (!trimmed) return "";
- const isGenericOpeningHeader =
- resp.messageTag === "header" &&
- resp.messageStepId === 0 &&
- /^(?:\.{3}|thinking(?: about your request)?)$/i.test(trimmed);
- if (isGenericOpeningHeader) return "";
- if (resp.messageTag === "header") return `${trimmed}\n`;
- if (resp.messageTag === "summary") return `${trimmed}\n`;
- return cleaned;
-}
-
-export function extractStructuredReasoning(value: object | undefined): string {
- if (!value) return "";
- const record = value as Record<string, unknown>;
- for (const key of ["reasoning", "reasoningContent", "reasoning_content", "thinking", "thought"]) {
- const candidate = record[key];
- if (typeof candidate === "string" && candidate.trim()) return cleanGrokText(candidate);
- }
- return "";
-}
diff --git a/open-sse/executors/grok-web/tool-bridge.ts b/open-sse/executors/grok-web/tool-bridge.ts
deleted file mode 100644
index 90a059f6e5..0000000000
--- a/open-sse/executors/grok-web/tool-bridge.ts
+++ /dev/null
@@ -1,666 +0,0 @@
-// OpenAI <-> Grok tool-call translation (pure). Extracted verbatim from grok-web.ts.
-import type { GrokStreamResponse } from "./types.ts";
-
-// ─── OpenAI message → Grok query translation ───────────────────────────────
-
-export interface OpenAIToolCall {
- id: string;
- type: "function";
- function: {
- name: string;
- arguments: string;
- };
-}
-
-export interface GrokToolRegistry {
- enabled: boolean;
- toolsByName: Map<string, GrokFunctionToolSummary>;
- lastUserText: string;
- executedToolKeys: Set<string>;
- completedToolCalls: string[];
-}
-
-export interface GrokFunctionToolSummary {
- name: string;
- description?: string;
- parameters: unknown;
-}
-
-export type NativeToolIntent = "bash" | "readFile" | "webSearch" | "browsePage";
-
-export interface ToolBridgeContext {
- lastUserText: string;
-}
-
-export function stripInjectedRuntimeReminders(text: string): string {
- return text
- .replace(/\n?---\s*\n\s*<internal_reminder>[\s\S]*?<\/internal_reminder>/gi, "")
- .replace(/<internal_reminder>[\s\S]*?<\/internal_reminder>/gi, "")
- .replace(/\n{3,}/g, "\n\n")
- .trim();
-}
-
-export function extractTextContent(msg: Record<string, unknown>): string {
- if (typeof msg.content === "string") return stripInjectedRuntimeReminders(msg.content);
- if (Array.isArray(msg.content)) {
- return stripInjectedRuntimeReminders(
- (msg.content as Array<Record<string, unknown>>)
- .filter((c) => c.type === "text")
- .map((c) => String(c.text || ""))
- .join(" ")
- );
- }
- return "";
-}
-
-export function getLastUserText(messages: Array<Record<string, unknown>>): string {
- for (let i = messages.length - 1; i >= 0; i--) {
- if (String(messages[i].role || "") === "user") return extractTextContent(messages[i]);
- }
- return "";
-}
-
-export function normalizeToolArgumentObject(value: unknown): Record<string, unknown> {
- if (!value) return {};
- if (typeof value === "object") return value as Record<string, unknown>;
- if (typeof value === "string") {
- try {
- const parsed = JSON.parse(value);
- return parsed && typeof parsed === "object"
- ? (parsed as Record<string, unknown>)
- : { input: value };
- } catch {
- return { input: value };
- }
- }
- return {};
-}
-
-export function stableJson(value: unknown): string {
- if (!value || typeof value !== "object") return JSON.stringify(value);
- if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
- const record = value as Record<string, unknown>;
- return `{${Object.keys(record)
- .sort()
- .map((key) => `${JSON.stringify(key)}:${stableJson(record[key])}`)
- .join(",")}}`;
-}
-
-export function toolCallKey(name: string, args: unknown): string {
- return `${name}:${stableJson(normalizeToolArgumentObject(args))}`;
-}
-
-export function normalizeShellCommand(command: string): string {
- return command.trim().replace(/\s+/g, " ");
-}
-
-export function normalizePathValue(path: string): string {
- return path.trim().replace(/^['"]|['"]$/g, "");
-}
-
-export function normalizeQueryValue(query: string): string {
- return query.trim().replace(/\s+/g, " ").toLowerCase();
-}
-
-export function semanticToolKey(name: string, args: unknown): string {
- const normalizedName = name.trim();
- const record = normalizeToolArgumentObject(args);
- const command = firstString(record.command, record.cmd, record.shell);
- if (command) return `${normalizedName}:command:${normalizeShellCommand(command)}`;
-
- const url = firstString(record.url, record.uri);
- if (url) return `${normalizedName}:url:${normalizePathValue(url)}`;
-
- const path = firstString(record.filePath, record.file_path, record.path, record.filename);
- if (path) return `${normalizedName}:path:${normalizePathValue(path)}`;
-
- const query = firstString(record.query, record.search);
- if (query) return `${normalizedName}:query:${normalizeQueryValue(query)}`;
-
- return toolCallKey(normalizedName, record);
-}
-
-export function summarizeCompletedToolCall(name: string, args: unknown): string {
- const record = normalizeToolArgumentObject(args);
- const command = firstString(record.command, record.cmd, record.shell);
- if (command) return `${name}(command=${JSON.stringify(normalizeShellCommand(command))})`;
- const url = firstString(record.url, record.uri);
- if (url) return `${name}(url=${JSON.stringify(normalizePathValue(url))})`;
- const path = firstString(record.filePath, record.file_path, record.path, record.filename);
- if (path) return `${name}(path=${JSON.stringify(normalizePathValue(path))})`;
- const query = firstString(record.query, record.search);
- if (query) return `${name}(query=${JSON.stringify(normalizeQueryValue(query))})`;
- return `${name}(${stableJson(record)})`;
-}
-
-export function getExecutedToolState(messages: Array<Record<string, unknown>>): {
- keys: Set<string>;
- summaries: string[];
-} {
- let lastUserIdx = -1;
- for (let i = messages.length - 1; i >= 0; i--) {
- if (String(messages[i].role || "") === "user") {
- lastUserIdx = i;
- break;
- }
- }
- const callsById = new Map<string, { name: string; args: Record<string, unknown> }>();
- const executed = new Set<string>();
- const summaries: string[] = [];
- for (let i = Math.max(0, lastUserIdx + 1); i < messages.length; i++) {
- const msg = messages[i];
- if (String(msg.role || "") === "assistant" && Array.isArray(msg.tool_calls)) {
- for (const call of msg.tool_calls as Array<Record<string, unknown>>) {
- const id = typeof call.id === "string" ? call.id : "";
- const fn = call.function;
- if (!id || !fn || typeof fn !== "object") continue;
- const fnRecord = fn as Record<string, unknown>;
- const name = typeof fnRecord.name === "string" ? fnRecord.name : "";
- if (!name) continue;
- callsById.set(id, { name, args: normalizeToolArgumentObject(fnRecord.arguments) });
- }
- }
- if (String(msg.role || "") === "tool") {
- const id = typeof msg.tool_call_id === "string" ? msg.tool_call_id : "";
- const call = id ? callsById.get(id) : null;
- if (call) {
- const key = semanticToolKey(call.name, call.args);
- executed.add(key);
- const summary = summarizeCompletedToolCall(call.name, call.args);
- if (!summaries.includes(summary)) summaries.push(summary);
- }
- }
- }
- return { keys: executed, summaries };
-}
-
-export function extractFirstUrl(text: string): string | undefined {
- const match = text.match(/https?:\/\/[^\s)\]}>"']+/i);
- if (match?.[0]) return match[0].replace(/[.,;:!?]+$/, "");
- const domain = text.match(/(?:^|\s)((?:[a-z0-9-]+\.)+[a-z]{2,}(?:\/[^\s)\]}>"']*)?)/i)?.[1];
- return domain ? `https://${domain.replace(/[.,;:!?]+$/, "")}` : undefined;
-}
-
-export function wantsUrlFetch(text: string): boolean {
- return (
- /\b(webfetch|web_fetch|fetch|browse|open|read|lee|abre|extrae|investiga|analiza|resume|summarize|de qu[eé] va)\b/i.test(
- text
- ) && !!extractFirstUrl(text)
- );
-}
-
-export function forcedToolChoiceName(toolChoice: unknown): string | null {
- if (!toolChoice || typeof toolChoice !== "object") return null;
- const record = toolChoice as Record<string, unknown>;
- if (record.type !== "function" || !record.function || typeof record.function !== "object")
- return null;
- const name = (record.function as Record<string, unknown>).name;
- return typeof name === "string" && name.trim() ? name.trim() : null;
-}
-
-export function parseOpenAIMessages(
- messages: Array<Record<string, unknown>>,
- beforeLatestUser = ""
-): string {
- const parts: string[] = [];
- let lastUserIdx = -1;
- let lastUserSourceIdx = -1;
-
- for (let i = messages.length - 1; i >= 0; i--) {
- if (String(messages[i].role || "") === "user") {
- lastUserSourceIdx = i;
- break;
- }
- }
-
- // Extract text from each message
- const extracted: Array<{ role: string; text: string }> = [];
-
- for (let msgIdx = 0; msgIdx < messages.length; msgIdx++) {
- const msg = messages[msgIdx];
- let role = String(msg.role || "user");
- if (role === "developer") role = "system";
-
- let content = extractTextContent(msg);
- if (role === "tool") {
- if (msgIdx < lastUserSourceIdx) continue;
- const toolName = typeof msg.name === "string" ? msg.name : "unknown_tool";
- const toolCallId = typeof msg.tool_call_id === "string" ? msg.tool_call_id : "unknown_call";
- content = `CLIENT TOOL RESULT from caller runtime for ${toolName} (${toolCallId}). Use this result to answer; do not call the same tool again:\n${content}`;
- } else if (role === "assistant" && Array.isArray(msg.tool_calls)) {
- if (msgIdx < lastUserSourceIdx) continue;
- const calls = (msg.tool_calls as Array<Record<string, unknown>>).map((call) => ({
- id: call.id,
- function: call.function,
- }));
- content = [content, `Previous assistant tool calls: ${JSON.stringify(calls)}`]
- .filter(Boolean)
- .join("\n");
- }
- if (!content.trim()) continue;
- extracted.push({ role, text: content });
- }
-
- // Find last user message index
- for (let i = extracted.length - 1; i >= 0; i--) {
- if (extracted[i].role === "user") {
- lastUserIdx = i;
- break;
- }
- }
-
- // Build combined message — last user message is raw, others are prefixed
- for (let i = 0; i < extracted.length; i++) {
- const { role, text } = extracted[i];
- if (i === lastUserIdx) {
- parts.push(text);
- } else {
- parts.push(`${role}: ${text}`);
- }
- }
-
- if (beforeLatestUser.trim()) {
- parts.push(beforeLatestUser.trim());
- }
-
- return parts.join("\n\n");
-}
-
-export function buildGrokToolRegistry(body: Record<string, unknown>): GrokToolRegistry {
- const tools = Array.isArray(body.tools) ? (body.tools as Array<Record<string, unknown>>) : [];
- const messages = Array.isArray(body.messages)
- ? (body.messages as Array<Record<string, unknown>>)
- : [];
- const lastUserText = getLastUserText(messages);
- const executedToolState = getExecutedToolState(messages);
- const toolChoice = body.tool_choice ?? "auto";
-
- if (toolChoice === "none") {
- return {
- enabled: false,
- toolsByName: new Map(),
- lastUserText,
- executedToolKeys: executedToolState.keys,
- completedToolCalls: executedToolState.summaries,
- };
- }
-
- const functionTools: GrokFunctionToolSummary[] = tools
- .map((tool) => {
- const fn = tool?.function;
- if (tool?.type !== "function" || !fn || typeof fn !== "object") return null;
- const record = fn as Record<string, unknown>;
- const name = typeof record.name === "string" ? record.name.trim() : "";
- if (!name) return null;
- return {
- name,
- ...(typeof record.description === "string" ? { description: record.description } : {}),
- parameters: record.parameters || { type: "object", properties: {} },
- };
- })
- .filter((tool): tool is GrokFunctionToolSummary => Boolean(tool));
- const forcedName = forcedToolChoiceName(toolChoice);
- const visibleTools = forcedName
- ? functionTools.filter((tool) => tool.name === forcedName)
- : functionTools;
-
- return {
- enabled: visibleTools.length > 0,
- toolsByName: new Map(visibleTools.map((tool) => [tool.name, tool])),
- lastUserText,
- executedToolKeys: executedToolState.keys,
- completedToolCalls: executedToolState.summaries,
- };
-}
-
-export function getSchemaProperties(parameters: unknown): Record<string, unknown> {
- if (!parameters || typeof parameters !== "object") return {};
- const properties = (parameters as Record<string, unknown>).properties;
- return properties && typeof properties === "object"
- ? (properties as Record<string, unknown>)
- : {};
-}
-
-export function getSchemaRequired(parameters: unknown): string[] {
- if (!parameters || typeof parameters !== "object") return [];
- const required = (parameters as Record<string, unknown>).required;
- return Array.isArray(required)
- ? required.filter((key): key is string => typeof key === "string")
- : [];
-}
-
-export function formatToolArgsSummary(parameters: unknown): string {
- const properties = getSchemaProperties(parameters);
- const propNames = Object.keys(properties);
- const required = getSchemaRequired(parameters);
- const segments: string[] = [];
- if (propNames.length > 0) segments.push(`args=${propNames.join(",")}`);
- if (required.length > 0) segments.push(`required=${required.join(",")}`);
- return segments.length > 0 ? ` (${segments.join("; ")})` : "";
-}
-
-export function toolText(tool: GrokFunctionToolSummary): string {
- return `${tool.name} ${tool.description || ""}`.toLowerCase();
-}
-
-export function hasAnyProperty(tool: GrokFunctionToolSummary, names: string[]): boolean {
- const properties = getSchemaProperties(tool.parameters);
- const lowerProps = new Set(Object.keys(properties).map((key) => key.toLowerCase()));
- return names.some((name) => lowerProps.has(name.toLowerCase()));
-}
-
-export function isTerminalTool(tool: GrokFunctionToolSummary): boolean {
- if (isMetaOrInfrastructureTool(tool)) return false;
- const text = toolText(tool);
- const name = tool.name.toLowerCase();
- const explicitName = /\b(bash|shell|terminal|run_command|execute_command|exec|command)\b/.test(
- name
- );
- const explicitText =
- /\b(?:run|execute).{0,24}\b(?:shell|bash|terminal|command)\b|\b(?:shell|bash|terminal)\b/.test(
- text
- );
- return explicitName || (hasAnyProperty(tool, ["command", "cmd", "shell"]) && explicitText);
-}
-
-export function isFileReadTool(tool: GrokFunctionToolSummary): boolean {
- const text = toolText(tool);
- return (
- hasAnyProperty(tool, ["filePath", "file_path", "path"]) &&
- /\b(read|file|filesystem|open)\b/.test(text) &&
- !/\b(write|edit|patch|delete|remove|grep|search|bash|shell|command)\b/.test(text)
- );
-}
-
-export function isUrlFetchTool(tool: GrokFunctionToolSummary): boolean {
- const text = toolText(tool);
- const name = tool.name.toLowerCase();
- const explicitName =
- /\b(webfetch|web.fetch|fetch_url|url_fetch|read_url|browse_page|browsepage)\b/.test(name);
- const explicitUrlText =
- /\b(?:fetch|browse|read).{0,32}\b(?:url|uri|web page|page content)\b|\b(?:url|uri|web page|page content).{0,32}\b(?:fetch|browse|read)\b/.test(
- text
- );
- return (
- explicitName ||
- (!isMetaOrInfrastructureTool(tool) && hasAnyProperty(tool, ["url", "uri"]) && explicitUrlText)
- );
-}
-
-export function isWebSearchTool(tool: GrokFunctionToolSummary): boolean {
- const text = toolText(tool);
- return (
- hasAnyProperty(tool, ["query", "search"]) &&
- /\b(web|internet|exa|browser|browse|serp)\b/.test(text) &&
- !isMetaOrInfrastructureTool(tool) &&
- !isContextMemoryTool(tool)
- );
-}
-
-export function isContextMemoryTool(tool: GrokFunctionToolSummary): boolean {
- const text = toolText(tool);
- return /\b(ctx_|memory|memories|conversation history|session notes|git commits|project memories|context.db|magic context)\b/.test(
- text
- );
-}
-
-export function isMetaOrInfrastructureTool(tool: GrokFunctionToolSummary): boolean {
- const text = toolText(tool);
- return /\b(mcp|mcpproxy|upstream|registry|registries|quarantine|oauth|cache key|token usage|session notes|conversation transcript|handoff|context management|memory|memories|lsp|language server|plan file|server management|tool discovery|tools? using bm25)\b/.test(
- text
- );
-}
-
-export function baseToolOrderScore(tool: GrokFunctionToolSummary): number {
- if (isUrlFetchTool(tool)) return 90;
- if (isWebSearchTool(tool)) return 85;
- if (isFileReadTool(tool)) return 75;
- if (isTerminalTool(tool)) return 70;
- if (/\b(glob|grep|search files?|file search|content search)\b/.test(toolText(tool))) return 60;
- if (/\b(edit|write|patch|modify|apply)\b/.test(toolText(tool))) return 50;
- if (/\b(task|agent|delegate|subagent)\b/.test(toolText(tool))) return 40;
- if (isMetaOrInfrastructureTool(tool)) return 10;
- if (isContextMemoryTool(tool)) return 20;
- return 30;
-}
-
-export function latestUserIntentScore(tool: GrokFunctionToolSummary, lastUserText: string): number {
- const user = lastUserText.toLowerCase();
- const hasPath = /(?:^|\s|["'`])(?:~|\.?\.?\/|\/)[^\s"'`]+/.test(lastUserText);
- const hasUrl = !!extractFirstUrl(lastUserText);
- const asksLineCount = /\b(l[ií]neas?|line count|cu[aá]ntas? l[ií]neas?|wc\s+-l)\b/.test(user);
- const asksFileContent =
- /\b(lee|leer|read|archivo|file|json|config|modelo|default|por defecto|de qu[eé] va|consiste|contenido)\b/.test(
- user
- ) && hasPath;
- const asksContext =
- /\b(contexto|memoria|historial|conversation history|project memories|ctx_|memory|memories|recordabas?)\b/.test(
- user
- );
- const asksWeb =
- !asksContext &&
- /\b(web|internet|fuente|oficial|release|versi[oó]n|ubuntu|latest|actual|contrasta|busca|search)\b/.test(
- user
- );
- let score = 0;
-
- if (asksFileContent && isFileReadTool(tool)) score += 160;
- if (asksFileContent && isTerminalTool(tool)) score += asksLineCount ? 70 : 20;
- if (asksLineCount && isTerminalTool(tool)) score += 120;
- if (asksLineCount && isFileReadTool(tool)) score += asksFileContent ? 90 : 30;
- if (asksWeb && !hasUrl && isWebSearchTool(tool)) score += 170;
- if (asksWeb && !hasUrl && isUrlFetchTool(tool)) score += 35;
- if (asksWeb && isContextMemoryTool(tool)) score -= 120;
- if (asksContext && isContextMemoryTool(tool)) score += 170;
- if (asksContext && isWebSearchTool(tool)) score -= 80;
-
- if (isContextMemoryTool(tool) && (asksFileContent || asksWeb)) score -= 80;
- return score;
-}
-
-export function orderedToolsForManifest(
- toolRegistry: GrokToolRegistry
-): Array<{ tool: GrokFunctionToolSummary; score: number }> {
- return [...toolRegistry.toolsByName.values()]
- .map((tool, index) => ({
- tool,
- score: latestUserIntentScore(tool, toolRegistry.lastUserText) + baseToolOrderScore(tool),
- meta: isMetaOrInfrastructureTool(tool),
- index,
- }))
- .sort((a, b) => b.score - a.score || Number(a.meta) - Number(b.meta) || a.index - b.index)
- .map(({ tool, score }) => ({ tool, score }));
-}
-
-export function formatToolManifestEntry(tool: GrokFunctionToolSummary, rank: number): string {
- const desc = tool.description ? `\n description: ${tool.description}` : "";
- const args = formatToolArgsSummary(tool.parameters).trim();
- return `${rank}. name: ${tool.name}${args ? `\n ${args.slice(1, -1)}` : ""}${desc ? desc.replace(/\n /g, "\n ") : ""}`;
-}
-
-export function buildClientToolManifest(
- toolRegistry: GrokToolRegistry,
- toolChoice: unknown
-): string {
- if (!toolRegistry.enabled) return "";
- const orderedTools = orderedToolsForManifest(toolRegistry);
- const lines = [
- 'CLIENT_TOOLS: use this caller-runtime tool list as the tool interface for this request. To call one, respond only with <tool_call>{"name":"exact_tool_name","arguments":{...}}</tool_call>. After tool results, answer normally.',
- `tool_choice=${JSON.stringify(toolChoice ?? "auto")}`,
- ...(toolRegistry.completedToolCalls.length > 0
- ? [
- "completed_tool_calls:",
- ...toolRegistry.completedToolCalls.map((summary) => `- ${summary}`),
- "Do not repeat completed tool calls unless a different result is required; use their tool results to answer.",
- ]
- : []),
- "tools (priority order for this request):",
- ...orderedTools.map(({ tool }, index) => formatToolManifestEntry(tool, index + 1)),
- ];
- return lines.join("\n");
-}
-
-export function buildGrokMessage(
- messages: Array<Record<string, unknown>>,
- toolRegistry: GrokToolRegistry,
- toolChoice: unknown
-): string {
- const manifest = buildClientToolManifest(toolRegistry, toolChoice);
- return parseOpenAIMessages(messages, manifest);
-}
-
-export function propertyType(properties: Record<string, unknown>, key: string): string | undefined {
- const prop = properties[key];
- if (!prop || typeof prop !== "object") return undefined;
- const type = (prop as Record<string, unknown>).type;
- return typeof type === "string" ? type : undefined;
-}
-
-export function hasValue(value: unknown): boolean {
- return value !== undefined && value !== null && value !== "";
-}
-
-export function firstString(...values: unknown[]): string | undefined {
- for (const value of values) {
- if (typeof value === "string" && value.trim()) return value;
- }
- return undefined;
-}
-
-export function defaultRequiredValue(
- key: string,
- type: string | undefined,
- args: Record<string, unknown>,
- intent: string
-): unknown {
- const lower = key.toLowerCase();
- const command = firstString(args.command, args.cmd, args.shell, args.input);
- const path = firstString(args.filePath, args.file_path, args.path, args.filename);
- const query = firstString(args.query, args.search, args.input);
- const url = firstString(args.url, args.uri);
-
- if (lower === "command" || lower === "cmd") return command;
- if (lower === "filepath" || lower === "file_path" || lower === "path") return path;
- if (lower === "query" || lower === "search") return query;
- if (lower === "url" || lower === "uri") return url;
- if (lower === "input") return query || url || command || path;
- if (lower === "description" || lower === "reason" || lower === "intent_reason") {
- if (command) return `Execute shell command: ${command}`;
- if (path) return `Read file: ${path}`;
- if (url) return `Fetch URL: ${url}`;
- if (query) return `Search: ${query}`;
- return `Grok Web ${intent} tool call`;
- }
- if (lower === "intent_data_sensitivity") return "private";
- return undefined;
-}
-
-export function extractNumericUserParam(text: string, names: string[]): number | undefined {
- const escaped = names.map((name) => name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|");
- const re = new RegExp(`\\b(?:${escaped})\\s*(?:=|:|a|de)?\\s*(\\d+)`, "i");
- const match = text.match(re);
- if (!match) return undefined;
- const value = Number(match[1]);
- return Number.isFinite(value) ? value : undefined;
-}
-
-export function adaptArgumentsToDeclaredTool(
- toolName: string,
- args: Record<string, unknown>,
- toolRegistry: GrokToolRegistry,
- intent: string,
- options: { preserveUnknownArgs?: boolean } = { preserveUnknownArgs: true }
-): Record<string, unknown> {
- const tool = toolRegistry.toolsByName.get(toolName);
- if (!tool) return args;
- const properties = getSchemaProperties(tool.parameters);
- const required = getSchemaRequired(tool.parameters);
- const out: Record<string, unknown> = { ...args };
-
- // Normalize common aliases only when the declared schema expects them.
- if ("filePath" in properties && !hasValue(out.filePath))
- out.filePath = firstString(args.filePath, args.file_path, args.path);
- if ("file_path" in properties && !hasValue(out.file_path))
- out.file_path = firstString(args.file_path, args.filePath, args.path);
- if ("path" in properties && !hasValue(out.path))
- out.path = firstString(args.path, args.filePath, args.file_path);
- if ("query" in properties && !hasValue(out.query))
- out.query = firstString(args.query, args.search, args.input);
- if ("url" in properties && !hasValue(out.url)) out.url = firstString(args.url, args.uri);
- if ("uri" in properties && !hasValue(out.uri)) out.uri = firstString(args.uri, args.url);
- if ("input" in properties && !hasValue(out.input))
- out.input = firstString(args.input, args.query, args.command);
-
- for (const key of required) {
- if (hasValue(out[key])) continue;
- const value = defaultRequiredValue(key, propertyType(properties, key), out, intent);
- if (value !== undefined) out[key] = value;
- }
-
- if (options.preserveUnknownArgs !== false || Object.keys(properties).length === 0) return out;
-
- const filtered: Record<string, unknown> = {};
- for (const key of Object.keys(properties)) {
- if (hasValue(out[key])) filtered[key] = out[key];
- }
- for (const key of required) {
- if (hasValue(out[key])) filtered[key] = out[key];
- }
- return filtered;
-}
-
-export function normalizeArbitraryToolArguments(value: unknown): Record<string, unknown> {
- if (!value) return {};
- if (typeof value === "object") return value as Record<string, unknown>;
- if (typeof value === "string") {
- try {
- const parsed = JSON.parse(value);
- return parsed && typeof parsed === "object" ? (parsed as Record<string, unknown>) : {};
- } catch {
- return { input: value };
- }
- }
- return {};
-}
-
-export function parseClientToolCallMarkup(
- text: string,
- toolRegistry: GrokToolRegistry
-): OpenAIToolCall[] | null {
- if (!toolRegistry.enabled || !text.includes("<tool_call>")) return null;
- const calls: OpenAIToolCall[] = [];
- const re = /<tool_call>\s*([\s\S]*?)\s*<\/tool_call>/g;
- for (const match of text.matchAll(re)) {
- let parsed: unknown;
- try {
- parsed = JSON.parse(match[1]);
- } catch {
- continue;
- }
- if (!parsed || typeof parsed !== "object") continue;
- const record = parsed as Record<string, unknown>;
- const name = typeof record.name === "string" ? record.name.trim() : "";
- if (!name || !toolRegistry.toolsByName.has(name)) continue;
- const rawArgs = normalizeArbitraryToolArguments(record.arguments);
- const args = adaptArgumentsToDeclaredTool(name, rawArgs, toolRegistry, "clientTool", {
- preserveUnknownArgs: true,
- });
- if (toolRegistry.executedToolKeys.has(semanticToolKey(name, args))) continue;
- calls.push({
- id:
- typeof record.id === "string" && record.id.trim()
- ? record.id.trim()
- : `call_${crypto.randomUUID()}`,
- type: "function",
- function: { name, arguments: JSON.stringify(args) },
- });
- }
- return calls.length > 0 ? calls : null;
-}
-
-export function hasOpenToolCallMarkup(text: string): boolean {
- return (
- /<tool(?:_call)?$|<tool_call[^>]*$/.test(text) ||
- (text.includes("<tool_call>") && !text.includes("</tool_call>"))
- );
-}
diff --git a/open-sse/executors/grok-web/types.ts b/open-sse/executors/grok-web/types.ts
deleted file mode 100644
index 20984f6dc3..0000000000
--- a/open-sse/executors/grok-web/types.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-// Grok NDJSON stream response/event types. Extracted verbatim from grok-web.ts.
-
-// ─── NDJSON stream types ────────────────────────────────────────────────────
-
-export interface GrokStreamResponse {
- token?: string;
- isThinking?: boolean;
- reasoning?: string;
- reasoningContent?: string;
- reasoning_content?: string;
- thinking?: string;
- thought?: string;
- responseId?: string;
- messageTag?: string;
- messageStepId?: number;
- toolUsageCardId?: string;
- toolUsageCard?: {
- toolUsageCardId?: string;
- bash?: { args?: Record<string, unknown> };
- readFile?: { args?: Record<string, unknown> };
- read_file?: { args?: Record<string, unknown> };
- webSearch?: { args?: Record<string, unknown> };
- browsePage?: { args?: Record<string, unknown> };
- browse_page?: { args?: Record<string, unknown> };
- };
- webSearchResults?: {
- results?: Array<Record<string, unknown>>;
- };
- llmInfo?: { modelHash?: string };
- modelResponse?: {
- message?: string;
- reasoning?: string;
- reasoningContent?: string;
- reasoning_content?: string;
- thinking?: string;
- thought?: string;
- responseId?: string;
- generatedImageUrls?: string[];
- metadata?: { llm_info?: { modelHash?: string } };
- pipelineToken?: string;
- };
-}
-
-export interface GrokStreamEvent {
- result?: { response?: GrokStreamResponse };
- error?: { message?: string; code?: string };
-}
diff --git a/open-sse/executors/huggingchat.ts b/open-sse/executors/huggingchat.ts
index 7b7557ce02..46db72840e 100644
--- a/open-sse/executors/huggingchat.ts
+++ b/open-sse/executors/huggingchat.ts
@@ -27,7 +27,6 @@ import {
import { FETCH_TIMEOUT_MS } from "../config/constants.ts";
import { buildErrorBody, sanitizeErrorMessage } from "../utils/error.ts";
import { normalizeSessionCookieHeader } from "@/lib/providers/webCookieAuth";
-import { streamJsonlToOpenAi, readJsonlResponse } from "./huggingchat/jsonlStream.ts";
const HUGGINGFACE_BASE = "https://huggingface.co";
const CONVERSATION_URL = `${HUGGINGFACE_BASE}/chat/conversation`;
@@ -109,6 +108,10 @@ function buildConversationPrompt(messages: Array<Record<string, unknown>>): {
};
}
+function sseChunk(data: unknown): string {
+ return `data: ${JSON.stringify(data)}\n\n`;
+}
+
function estimateTokens(text: string): number {
return Math.max(1, Math.ceil((text || "").length / 4));
}
@@ -242,6 +245,222 @@ function mergeCookieHeaderWithSetCookie(cookieHeader: string, setCookieHeaders:
return [...cookieMap.entries()].map(([name, value]) => `${name}=${value}`).join("; ");
}
+function parseJsonlLine(line: string): {
+ token?: string;
+ done?: boolean;
+ error?: string;
+ text?: string;
+} {
+ try {
+ const event = JSON.parse(line);
+
+ if (event.type === "stream" && typeof event.token === "string") {
+ const token = event.token.replace(/\0/g, "");
+ if (token) return { token };
+ }
+
+ if (event.type === "finalAnswer" && typeof event.text === "string") {
+ return { text: event.text, done: true };
+ }
+
+ if (event.type === "status") {
+ if (event.status === "error") {
+ return { error: event.message || "HuggingChat generation error" };
+ }
+ if (event.status === "finished") {
+ return { done: true };
+ }
+ }
+ } catch {
+ // Skip non-JSON lines
+ }
+
+ return {};
+}
+
+async function* streamJsonlToOpenAi(
+ body: ReadableStream<Uint8Array>,
+ model: string,
+ id: string,
+ created: number,
+ signal?: AbortSignal | null
+): AsyncGenerator<string> {
+ const reader = body.getReader();
+ const decoder = new TextDecoder();
+ let buffer = "";
+ let emittedRole = false;
+ let fullText = "";
+ let finished = false;
+
+ try {
+ while (true) {
+ if (signal?.aborted) break;
+
+ const { value, done } = await reader.read();
+ if (done) break;
+
+ buffer += decoder.decode(value, { stream: true });
+
+ const lines = buffer.split("\n");
+ buffer = lines.pop() || "";
+
+ for (const line of lines) {
+ const trimmed = line.trim();
+ if (!trimmed) continue;
+
+ const parsed = parseJsonlLine(trimmed);
+
+ if (parsed.error) {
+ yield sseChunk({
+ id,
+ object: "chat.completion.chunk",
+ created,
+ model,
+ choices: [{ index: 0, delta: {}, finish_reason: "stop" }],
+ });
+ yield "data: [DONE]\n\n";
+ finished = true;
+ return;
+ }
+
+ if (parsed.token) {
+ if (!emittedRole) {
+ emittedRole = true;
+ yield sseChunk({
+ id,
+ object: "chat.completion.chunk",
+ created,
+ model,
+ choices: [{ index: 0, delta: { role: "assistant" }, finish_reason: null }],
+ });
+ }
+
+ fullText += parsed.token;
+ yield sseChunk({
+ id,
+ object: "chat.completion.chunk",
+ created,
+ model,
+ choices: [{ index: 0, delta: { content: parsed.token }, finish_reason: null }],
+ });
+ }
+
+ if (parsed.text) {
+ const remaining = parsed.text.slice(fullText.length);
+ if (remaining) {
+ if (!emittedRole) {
+ emittedRole = true;
+ yield sseChunk({
+ id,
+ object: "chat.completion.chunk",
+ created,
+ model,
+ choices: [{ index: 0, delta: { role: "assistant" }, finish_reason: null }],
+ });
+ }
+ yield sseChunk({
+ id,
+ object: "chat.completion.chunk",
+ created,
+ model,
+ choices: [{ index: 0, delta: { content: remaining }, finish_reason: null }],
+ });
+ }
+ finished = true;
+ break;
+ }
+
+ if (parsed.done) {
+ finished = true;
+ break;
+ }
+ }
+
+ if (finished) break;
+ }
+
+ if (!finished && buffer.trim()) {
+ const parsed = parseJsonlLine(buffer.trim());
+ if (parsed.token && !signal?.aborted) {
+ if (!emittedRole) {
+ emittedRole = true;
+ yield sseChunk({
+ id,
+ object: "chat.completion.chunk",
+ created,
+ model,
+ choices: [{ index: 0, delta: { role: "assistant" }, finish_reason: null }],
+ });
+ }
+ yield sseChunk({
+ id,
+ object: "chat.completion.chunk",
+ created,
+ model,
+ choices: [{ index: 0, delta: { content: parsed.token }, finish_reason: null }],
+ });
+ }
+ }
+ } finally {
+ reader.releaseLock();
+ }
+
+ if (!signal?.aborted) {
+ yield sseChunk({
+ id,
+ object: "chat.completion.chunk",
+ created,
+ model,
+ choices: [{ index: 0, delta: {}, finish_reason: "stop" }],
+ });
+ yield "data: [DONE]\n\n";
+ }
+}
+
+async function readJsonlResponse(
+ body: ReadableStream<Uint8Array>,
+ signal?: AbortSignal | null
+): Promise<string> {
+ const reader = body.getReader();
+ const decoder = new TextDecoder();
+ let buffer = "";
+ let fullText = "";
+
+ try {
+ while (true) {
+ if (signal?.aborted) break;
+
+ const { value, done } = await reader.read();
+ if (done) break;
+
+ buffer += decoder.decode(value, { stream: true });
+
+ const lines = buffer.split("\n");
+ buffer = lines.pop() || "";
+
+ for (const line of lines) {
+ const trimmed = line.trim();
+ if (!trimmed) continue;
+
+ const parsed = parseJsonlLine(trimmed);
+ if (parsed.token) fullText += parsed.token;
+ if (parsed.text) return parsed.text;
+ if (parsed.error) throw new Error(parsed.error);
+ }
+ }
+
+ if (buffer.trim()) {
+ const parsed = parseJsonlLine(buffer.trim());
+ if (parsed.text) return parsed.text;
+ if (parsed.token) fullText += parsed.token;
+ }
+ } finally {
+ reader.releaseLock();
+ }
+
+ return fullText;
+}
+
// -- Executor ----------------------------------------------------------------
export class HuggingChatExecutor extends BaseExecutor {
diff --git a/open-sse/executors/huggingchat/jsonlStream.ts b/open-sse/executors/huggingchat/jsonlStream.ts
deleted file mode 100644
index b09bcb2c30..0000000000
--- a/open-sse/executors/huggingchat/jsonlStream.ts
+++ /dev/null
@@ -1,221 +0,0 @@
-// Pure JSONL stream translation (HuggingChat NDJSON -> OpenAI SSE). Verbatim from huggingchat.ts.
-
-export function sseChunk(data: unknown): string {
- return `data: ${JSON.stringify(data)}\n\n`;
-}
-
-export function parseJsonlLine(line: string): {
- token?: string;
- done?: boolean;
- error?: string;
- text?: string;
-} {
- try {
- const event = JSON.parse(line);
-
- if (event.type === "stream" && typeof event.token === "string") {
- const token = event.token.replace(/\0/g, "");
- if (token) return { token };
- }
-
- if (event.type === "finalAnswer" && typeof event.text === "string") {
- return { text: event.text, done: true };
- }
-
- if (event.type === "status") {
- if (event.status === "error") {
- return { error: event.message || "HuggingChat generation error" };
- }
- if (event.status === "finished") {
- return { done: true };
- }
- }
- } catch {
- // Skip non-JSON lines
- }
-
- return {};
-}
-
-export async function* streamJsonlToOpenAi(
- body: ReadableStream<Uint8Array>,
- model: string,
- id: string,
- created: number,
- signal?: AbortSignal | null
-): AsyncGenerator<string> {
- const reader = body.getReader();
- const decoder = new TextDecoder();
- let buffer = "";
- let emittedRole = false;
- let fullText = "";
- let finished = false;
-
- try {
- while (true) {
- if (signal?.aborted) break;
-
- const { value, done } = await reader.read();
- if (done) break;
-
- buffer += decoder.decode(value, { stream: true });
-
- const lines = buffer.split("\n");
- buffer = lines.pop() || "";
-
- for (const line of lines) {
- const trimmed = line.trim();
- if (!trimmed) continue;
-
- const parsed = parseJsonlLine(trimmed);
-
- if (parsed.error) {
- yield sseChunk({
- id,
- object: "chat.completion.chunk",
- created,
- model,
- choices: [{ index: 0, delta: {}, finish_reason: "stop" }],
- });
- yield "data: [DONE]\n\n";
- finished = true;
- return;
- }
-
- if (parsed.token) {
- if (!emittedRole) {
- emittedRole = true;
- yield sseChunk({
- id,
- object: "chat.completion.chunk",
- created,
- model,
- choices: [{ index: 0, delta: { role: "assistant" }, finish_reason: null }],
- });
- }
-
- fullText += parsed.token;
- yield sseChunk({
- id,
- object: "chat.completion.chunk",
- created,
- model,
- choices: [{ index: 0, delta: { content: parsed.token }, finish_reason: null }],
- });
- }
-
- if (parsed.text) {
- const remaining = parsed.text.slice(fullText.length);
- if (remaining) {
- if (!emittedRole) {
- emittedRole = true;
- yield sseChunk({
- id,
- object: "chat.completion.chunk",
- created,
- model,
- choices: [{ index: 0, delta: { role: "assistant" }, finish_reason: null }],
- });
- }
- yield sseChunk({
- id,
- object: "chat.completion.chunk",
- created,
- model,
- choices: [{ index: 0, delta: { content: remaining }, finish_reason: null }],
- });
- }
- finished = true;
- break;
- }
-
- if (parsed.done) {
- finished = true;
- break;
- }
- }
-
- if (finished) break;
- }
-
- if (!finished && buffer.trim()) {
- const parsed = parseJsonlLine(buffer.trim());
- if (parsed.token && !signal?.aborted) {
- if (!emittedRole) {
- emittedRole = true;
- yield sseChunk({
- id,
- object: "chat.completion.chunk",
- created,
- model,
- choices: [{ index: 0, delta: { role: "assistant" }, finish_reason: null }],
- });
- }
- yield sseChunk({
- id,
- object: "chat.completion.chunk",
- created,
- model,
- choices: [{ index: 0, delta: { content: parsed.token }, finish_reason: null }],
- });
- }
- }
- } finally {
- reader.releaseLock();
- }
-
- if (!signal?.aborted) {
- yield sseChunk({
- id,
- object: "chat.completion.chunk",
- created,
- model,
- choices: [{ index: 0, delta: {}, finish_reason: "stop" }],
- });
- yield "data: [DONE]\n\n";
- }
-}
-
-export async function readJsonlResponse(
- body: ReadableStream<Uint8Array>,
- signal?: AbortSignal | null
-): Promise<string> {
- const reader = body.getReader();
- const decoder = new TextDecoder();
- let buffer = "";
- let fullText = "";
-
- try {
- while (true) {
- if (signal?.aborted) break;
-
- const { value, done } = await reader.read();
- if (done) break;
-
- buffer += decoder.decode(value, { stream: true });
-
- const lines = buffer.split("\n");
- buffer = lines.pop() || "";
-
- for (const line of lines) {
- const trimmed = line.trim();
- if (!trimmed) continue;
-
- const parsed = parseJsonlLine(trimmed);
- if (parsed.token) fullText += parsed.token;
- if (parsed.text) return parsed.text;
- if (parsed.error) throw new Error(parsed.error);
- }
- }
-
- if (buffer.trim()) {
- const parsed = parseJsonlLine(buffer.trim());
- if (parsed.text) return parsed.text;
- if (parsed.token) fullText += parsed.token;
- }
- } finally {
- reader.releaseLock();
- }
-
- return fullText;
-}
diff --git a/open-sse/executors/index.ts b/open-sse/executors/index.ts
index 5984fde2ee..65d09889e3 100644
--- a/open-sse/executors/index.ts
+++ b/open-sse/executors/index.ts
@@ -28,7 +28,6 @@ import { GitlabExecutor } from "./gitlab.ts";
import { NlpCloudExecutor } from "./nlpcloud.ts";
import { WindsurfExecutor } from "./windsurf.ts";
import { DevinCliExecutor } from "./devin-cli.ts";
-import { AuggieExecutor } from "./auggie.ts";
import { DeepSeekWebExecutor } from "./deepseek-web.ts";
import { DeepSeekWebWithAutoRefreshExecutor } from "./deepseek-web-with-auto-refresh.ts";
import { AdaptaWebExecutor } from "./adapta-web.ts";
@@ -55,7 +54,6 @@ import { MimocodeExecutor } from "./mimocode.ts";
import { GrokCliExecutor } from "./grok-cli.ts";
import { CodeBuddyCnExecutor } from "./codebuddy-cn.ts";
import { ZenmuxFreeExecutor } from "./zenmux-free.ts";
-import { XaiExecutor } from "./xai.ts";
const executors = {
antigravity: new AntigravityExecutor(),
@@ -156,8 +154,6 @@ const executors = {
cbcn: new CodeBuddyCnExecutor(), // Alias for codebuddy-cn
"zenmux-free": new ZenmuxFreeExecutor(),
zmf: new ZenmuxFreeExecutor(), // Alias for zenmux-free
- auggie: new AuggieExecutor(),
- xai: new XaiExecutor(),
};
const defaultCache = new Map();
@@ -203,7 +199,6 @@ export { GitlabExecutor } from "./gitlab.ts";
export { NlpCloudExecutor } from "./nlpcloud.ts";
export { WindsurfExecutor } from "./windsurf.ts";
export { DevinCliExecutor } from "./devin-cli.ts";
-export { AuggieExecutor } from "./auggie.ts";
export { CopilotWebExecutor } from "./copilot-web.ts";
export { CopilotM365WebExecutor } from "./copilot-m365-web.ts";
export { VeoAIFreeWebExecutor } from "./veoaifree-web.ts";
@@ -222,4 +217,3 @@ export { MimocodeExecutor } from "./mimocode.ts";
export { GrokCliExecutor } from "./grok-cli.ts";
export { CodeBuddyCnExecutor } from "./codebuddy-cn.ts";
export { ZenmuxFreeExecutor } from "./zenmux-free.ts";
-export { XaiExecutor } from "./xai.ts";
diff --git a/open-sse/executors/kimi-web.ts b/open-sse/executors/kimi-web.ts
index cf4ff4bdbe..f45e9d1072 100644
--- a/open-sse/executors/kimi-web.ts
+++ b/open-sse/executors/kimi-web.ts
@@ -36,24 +36,7 @@ const CHAT_URL = `${BASE_URL}/apiv2/kimi.gateway.chat.v1.ChatService/Chat`;
const USER_AGENT =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36";
-/**
- * Map a Kimi model id (the `key` field from `GetAvailableModels`) to the
- * request shape the upstream expects. Today only the chat-tier `k2d6` family
- * is supported — the agent variants (`k2d6-agent`, `k2d6-agent-ultra`) need
- * a different scenario (`SCENARIO_OK_COMPUTER`) plus `kimiPlusId` /
- * `agentMode` fields that this executor does not shape; users who need
- * agentic Kimi should use the `kimi-coding` (api.kimi.com) provider.
- */
-export interface KimiModelConfig {
- scenario: string;
- thinking: boolean;
-}
-
-export function resolveModelConfig(modelId: string): KimiModelConfig {
- if (modelId === "k2d6-thinking") return { scenario: "SCENARIO_K2D5", thinking: true };
- // `k2d6` (Instant) and any unknown id fall back to the default chat scenario.
- return { scenario: "SCENARIO_K2D5", thinking: false };
-}
+const DEFAULT_SCENARIO = "SCENARIO_K2D5";
/** Wrap a JSON message in the 5-byte Connect streaming envelope (flags + length). */
export function frameConnectMessage(json: string): Uint8Array {
@@ -223,14 +206,14 @@ export class KimiWebExecutor extends BaseExecutor {
return headers;
}
- private buildRequestBody(prompt: string, wantThinking: boolean, scenario: string): string {
+ private buildRequestBody(prompt: string, wantThinking: boolean): string {
return JSON.stringify({
- scenario,
+ scenario: DEFAULT_SCENARIO,
tools: [{ type: "TOOL_TYPE_SEARCH", search: {} }, { type: "TOOL_TYPE_CRON_JOB" }],
message: {
role: "user",
blocks: [{ message_id: "", text: { content: prompt } }],
- scenario,
+ scenario: DEFAULT_SCENARIO,
},
options: { thinking: wantThinking, enable_plugin: true },
});
@@ -253,13 +236,14 @@ export class KimiWebExecutor extends BaseExecutor {
const messages = (bodyObj.messages as Array<{ role: string; content: unknown }>) || [];
const modelId = (bodyObj.model as string) || "kimi-default";
- // Resolve scenario + default thinking flag from the model id (catalog truth),
- // then honour an explicit `reasoning_effort: "none"` override from the caller.
- const modelConfig = resolveModelConfig(modelId);
- const wantThinking = bodyObj.reasoning_effort === "none" ? false : modelConfig.thinking;
+ // Decide thinking intent. A user sending `reasoning_effort: "none"` is
+ // explicit — honour it even when the model id suggests a thinking variant.
+ // Otherwise thinking models (kimi-k2.6 etc.) default to thinking on.
+ const modelWantsThinking = /k2\.6|k2-6|think/i.test(modelId);
+ const wantThinking = bodyObj.reasoning_effort === "none" ? false : modelWantsThinking;
const prompt = foldMessages(messages);
- const reqBody = this.buildRequestBody(prompt, wantThinking, modelConfig.scenario);
+ const reqBody = this.buildRequestBody(prompt, wantThinking);
const reqHeaders = this.buildKimiHeaders(jwt);
// Connect framing wraps the JSON body in a 5-byte envelope. Without it the
diff --git a/open-sse/executors/kiro.ts b/open-sse/executors/kiro.ts
index 26c3135257..614efbaf3b 100644
--- a/open-sse/executors/kiro.ts
+++ b/open-sse/executors/kiro.ts
@@ -8,12 +8,7 @@ import {
import { PROVIDERS } from "../config/constants.ts";
import { v4 as uuidv4 } from "uuid";
import { refreshKiroToken } from "../services/tokenRefresh.ts";
-import {
- splitInlineThinking,
- flushPendingThinking,
- type KiroThinkingState,
-} from "./kiroThinking.ts";
-import { ByteQueue, TEXT_ENCODER, parseEventFrame } from "./kiro/eventstream.ts";
+import { splitInlineThinking, flushPendingThinking, type KiroThinkingState } from "./kiroThinking.ts";
type JsonRecord = Record<string, unknown>;
@@ -46,6 +41,97 @@ type KiroStreamState = {
thinking?: KiroThinkingState;
};
+type EventFrame = {
+ headers: Record<string, string>;
+ payload: JsonRecord | null;
+};
+
+class ByteQueue {
+ private chunks: Uint8Array[] = [];
+ private headOffset = 0;
+ length = 0;
+
+ push(chunk: Uint8Array) {
+ if (!(chunk instanceof Uint8Array) || chunk.length === 0) return;
+ this.chunks.push(chunk);
+ this.length += chunk.length;
+ }
+
+ peekUint32BE(offset = 0): number | null {
+ if (this.length < offset + 4) return null;
+
+ let value = 0;
+ for (let i = 0; i < 4; i++) {
+ value = (value << 8) | this.byteAt(offset + i);
+ }
+ return value >>> 0;
+ }
+
+ read(length: number): Uint8Array | null {
+ if (length < 0 || this.length < length) return null;
+
+ const output = new Uint8Array(length);
+ let written = 0;
+
+ while (written < length) {
+ const head = this.chunks[0];
+ const available = head.length - this.headOffset;
+ const take = Math.min(available, length - written);
+ output.set(head.subarray(this.headOffset, this.headOffset + take), written);
+ written += take;
+ this.headOffset += take;
+ this.length -= take;
+
+ if (this.headOffset >= head.length) {
+ this.chunks.shift();
+ this.headOffset = 0;
+ }
+ }
+
+ return output;
+ }
+
+ private byteAt(offset: number): number {
+ let remaining = offset;
+ for (let i = 0; i < this.chunks.length; i++) {
+ const chunk = this.chunks[i];
+ const start = i === 0 ? this.headOffset : 0;
+ const available = chunk.length - start;
+ if (remaining < available) {
+ return chunk[start + remaining];
+ }
+ remaining -= available;
+ }
+ return 0;
+ }
+}
+
+// ── CRC32 lookup table (IEEE polynomial, no dependency) ──
+const CRC32_TABLE = new Uint32Array(256);
+const TEXT_ENCODER = new TextEncoder();
+const TEXT_DECODER = new TextDecoder();
+for (let i = 0; i < 256; i++) {
+ let c = i;
+ for (let j = 0; j < 8; j++) {
+ c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
+ }
+ CRC32_TABLE[i] = c >>> 0;
+}
+
+// Full per-frame message-CRC validation is O(frame bytes) and runs for EVERY frame of
+// every Kiro response on the main thread. The transport is TLS-protected and the 8-byte
+// prelude CRC already guards framing, so the full-message CRC is redundant overhead that
+// contributes to the CPU-runaway on large/long generations. Keep it opt-in for debugging.
+const KIRO_VERIFY_FULL_CRC = process.env.KIRO_VERIFY_FULL_CRC === "true";
+
+function crc32(buf: Uint8Array) {
+ let crc = 0xffffffff;
+ for (let i = 0; i < buf.length; i++) {
+ crc = CRC32_TABLE[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8);
+ }
+ return (crc ^ 0xffffffff) >>> 0;
+}
+
/**
* Flush buffered tool arguments at finish boundaries.
*
@@ -268,18 +354,16 @@ export class KiroExecutor extends BaseExecutor {
// channel.
const tb = transformedBody as Record<string, unknown>;
const userContent =
- ((
+ (
(
- (tb?.conversationState as Record<string, unknown>)?.currentMessage as Record<
- string,
- unknown
- >
- )?.userInputMessage as Record<string, unknown>
- )?.content as string) || "";
+ (
+ (tb?.conversationState as Record<string, unknown>)
+ ?.currentMessage as Record<string, unknown>
+ )?.userInputMessage as Record<string, unknown>
+ )?.content as string
+ ) || "";
const thinkingExpected = userContent.includes("<thinking_mode>enabled</thinking_mode>");
- const transformedResponse = this.transformEventStreamToSSE(response, model, {
- thinkingExpected,
- });
+ const transformedResponse = this.transformEventStreamToSSE(response, model, { thinkingExpected });
return { response: transformedResponse, url, headers, transformedBody };
}
@@ -410,10 +494,7 @@ export class KiroExecutor extends BaseExecutor {
choices: [
{
index: 0,
- delta:
- chunkIndex === 0
- ? { role: "assistant", content: text }
- : { content: text },
+ delta: chunkIndex === 0 ? { role: "assistant", content: text } : { content: text },
finish_reason: null,
},
],
@@ -762,4 +843,101 @@ export class KiroExecutor extends BaseExecutor {
}
}
+/**
+ * Parse AWS EventStream frame
+ */
+function parseEventFrame(data: Uint8Array): EventFrame | null {
+ try {
+ const view = new DataView(data.buffer, data.byteOffset);
+ const totalLength = view.getUint32(0, false);
+ const headersLength = view.getUint32(4, false);
+
+ // ── CRC32 validation ──
+ // Prelude CRC covers bytes [0..7] (totalLength + headersLength)
+ const preludeCRC = view.getUint32(8, false);
+ const computedPreludeCRC = crc32(data.slice(0, 8));
+ if (preludeCRC !== computedPreludeCRC) {
+ console.warn(
+ `[Kiro] Prelude CRC mismatch: expected ${preludeCRC}, got ${computedPreludeCRC} — skipping corrupted frame`
+ );
+ return null;
+ }
+
+ // Message CRC covers bytes [0..totalLength-5] (everything except the CRC itself).
+ // Skipped by default (O(frame bytes) per frame) — the prelude CRC above already
+ // validates framing and the stream is TLS-protected. Enable KIRO_VERIFY_FULL_CRC=true
+ // to restore full validation for debugging corrupted-stream issues.
+ if (KIRO_VERIFY_FULL_CRC) {
+ const messageCRC = view.getUint32(data.length - 4, false);
+ const computedMessageCRC = crc32(data.slice(0, data.length - 4));
+ if (messageCRC !== computedMessageCRC) {
+ console.warn(
+ `[Kiro] Message CRC mismatch: expected ${messageCRC}, got ${computedMessageCRC} — skipping corrupted frame`
+ );
+ return null;
+ }
+ }
+ // Parse headers
+ const headers: Record<string, string> = {};
+ let offset = 12; // After prelude
+ const headerEnd = 12 + headersLength;
+
+ while (offset < headerEnd && offset < data.length) {
+ const nameLen = data[offset];
+ offset++;
+ if (offset + nameLen > data.length) break;
+
+ const name = TEXT_DECODER.decode(data.subarray(offset, offset + nameLen));
+ offset += nameLen;
+
+ const headerType = data[offset];
+ offset++;
+
+ if (headerType === 7) {
+ // String type
+ const valueLen = (data[offset] << 8) | data[offset + 1];
+ offset += 2;
+ if (offset + valueLen > data.length) break;
+
+ const value = TEXT_DECODER.decode(data.subarray(offset, offset + valueLen));
+ offset += valueLen;
+ headers[name] = value;
+ } else {
+ break;
+ }
+ }
+
+ // Parse payload
+ const payloadStart = 12 + headersLength;
+ const payloadEnd = data.length - 4; // Exclude message CRC
+
+ let payload: JsonRecord | null = null;
+ if (payloadEnd > payloadStart) {
+ const payloadStr = TEXT_DECODER.decode(data.subarray(payloadStart, payloadEnd));
+
+ // Skip empty or whitespace-only payloads
+ if (!payloadStr || !payloadStr.trim()) {
+ return { headers, payload: null };
+ }
+
+ try {
+ payload = JSON.parse(payloadStr);
+ } catch (parseError) {
+ const err = parseError instanceof Error ? parseError : new Error(String(parseError));
+ // Log parse error for debugging
+ console.warn(
+ `[Kiro] Failed to parse payload: ${err.message} | payload: ${payloadStr.substring(0, 100)}`
+ );
+ payload = { raw: payloadStr };
+ }
+ }
+
+ return { headers, payload };
+ } catch (err) {
+ const error = err instanceof Error ? err : new Error(String(err));
+ console.warn(`[Kiro] Frame parse error: ${error.message}`);
+ return null;
+ }
+}
+
export default KiroExecutor;
diff --git a/open-sse/executors/kiro/eventstream.ts b/open-sse/executors/kiro/eventstream.ts
deleted file mode 100644
index 39bb7e02cb..0000000000
--- a/open-sse/executors/kiro/eventstream.ts
+++ /dev/null
@@ -1,192 +0,0 @@
-// Pure AWS EventStream binary framing for Kiro (ByteQueue, CRC32, frame parsing).
-// Extracted verbatim from kiro.ts. Self-contained (local JsonRecord, no host imports).
-
-type JsonRecord = Record<string, unknown>;
-
-export type EventFrame = {
- headers: Record<string, string>;
- payload: JsonRecord | null;
-};
-
-export class ByteQueue {
- private chunks: Uint8Array[] = [];
- private headOffset = 0;
- length = 0;
-
- push(chunk: Uint8Array) {
- if (!(chunk instanceof Uint8Array) || chunk.length === 0) return;
- this.chunks.push(chunk);
- this.length += chunk.length;
- }
-
- peekUint32BE(offset = 0): number | null {
- if (this.length < offset + 4) return null;
-
- let value = 0;
- for (let i = 0; i < 4; i++) {
- value = (value << 8) | this.byteAt(offset + i);
- }
- return value >>> 0;
- }
-
- read(length: number): Uint8Array | null {
- if (length < 0 || this.length < length) return null;
-
- const output = new Uint8Array(length);
- let written = 0;
-
- while (written < length) {
- const head = this.chunks[0];
- const available = head.length - this.headOffset;
- const take = Math.min(available, length - written);
- output.set(head.subarray(this.headOffset, this.headOffset + take), written);
- written += take;
- this.headOffset += take;
- this.length -= take;
-
- if (this.headOffset >= head.length) {
- this.chunks.shift();
- this.headOffset = 0;
- }
- }
-
- return output;
- }
-
- private byteAt(offset: number): number {
- let remaining = offset;
- for (let i = 0; i < this.chunks.length; i++) {
- const chunk = this.chunks[i];
- const start = i === 0 ? this.headOffset : 0;
- const available = chunk.length - start;
- if (remaining < available) {
- return chunk[start + remaining];
- }
- remaining -= available;
- }
- return 0;
- }
-}
-
-// ── CRC32 lookup table (IEEE polynomial, no dependency) ──
-export const CRC32_TABLE = new Uint32Array(256);
-export const TEXT_ENCODER = new TextEncoder();
-export const TEXT_DECODER = new TextDecoder();
-for (let i = 0; i < 256; i++) {
- let c = i;
- for (let j = 0; j < 8; j++) {
- c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
- }
- CRC32_TABLE[i] = c >>> 0;
-}
-
-// Full per-frame message-CRC validation is O(frame bytes) and runs for EVERY frame of
-// every Kiro response on the main thread. The transport is TLS-protected and the 8-byte
-// prelude CRC already guards framing, so the full-message CRC is redundant overhead that
-// contributes to the CPU-runaway on large/long generations. Keep it opt-in for debugging.
-export const KIRO_VERIFY_FULL_CRC = process.env.KIRO_VERIFY_FULL_CRC === "true";
-
-export function crc32(buf: Uint8Array) {
- let crc = 0xffffffff;
- for (let i = 0; i < buf.length; i++) {
- crc = CRC32_TABLE[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8);
- }
- return (crc ^ 0xffffffff) >>> 0;
-}
-
-/**
- * Parse AWS EventStream frame
- */
-export function parseEventFrame(data: Uint8Array): EventFrame | null {
- try {
- const view = new DataView(data.buffer, data.byteOffset);
- const totalLength = view.getUint32(0, false);
- const headersLength = view.getUint32(4, false);
-
- // ── CRC32 validation ──
- // Prelude CRC covers bytes [0..7] (totalLength + headersLength)
- const preludeCRC = view.getUint32(8, false);
- const computedPreludeCRC = crc32(data.slice(0, 8));
- if (preludeCRC !== computedPreludeCRC) {
- console.warn(
- `[Kiro] Prelude CRC mismatch: expected ${preludeCRC}, got ${computedPreludeCRC} — skipping corrupted frame`
- );
- return null;
- }
-
- // Message CRC covers bytes [0..totalLength-5] (everything except the CRC itself).
- // Skipped by default (O(frame bytes) per frame) — the prelude CRC above already
- // validates framing and the stream is TLS-protected. Enable KIRO_VERIFY_FULL_CRC=true
- // to restore full validation for debugging corrupted-stream issues.
- if (KIRO_VERIFY_FULL_CRC) {
- const messageCRC = view.getUint32(data.length - 4, false);
- const computedMessageCRC = crc32(data.slice(0, data.length - 4));
- if (messageCRC !== computedMessageCRC) {
- console.warn(
- `[Kiro] Message CRC mismatch: expected ${messageCRC}, got ${computedMessageCRC} — skipping corrupted frame`
- );
- return null;
- }
- }
- // Parse headers
- const headers: Record<string, string> = {};
- let offset = 12; // After prelude
- const headerEnd = 12 + headersLength;
-
- while (offset < headerEnd && offset < data.length) {
- const nameLen = data[offset];
- offset++;
- if (offset + nameLen > data.length) break;
-
- const name = TEXT_DECODER.decode(data.subarray(offset, offset + nameLen));
- offset += nameLen;
-
- const headerType = data[offset];
- offset++;
-
- if (headerType === 7) {
- // String type
- const valueLen = (data[offset] << 8) | data[offset + 1];
- offset += 2;
- if (offset + valueLen > data.length) break;
-
- const value = TEXT_DECODER.decode(data.subarray(offset, offset + valueLen));
- offset += valueLen;
- headers[name] = value;
- } else {
- break;
- }
- }
-
- // Parse payload
- const payloadStart = 12 + headersLength;
- const payloadEnd = data.length - 4; // Exclude message CRC
-
- let payload: JsonRecord | null = null;
- if (payloadEnd > payloadStart) {
- const payloadStr = TEXT_DECODER.decode(data.subarray(payloadStart, payloadEnd));
-
- // Skip empty or whitespace-only payloads
- if (!payloadStr || !payloadStr.trim()) {
- return { headers, payload: null };
- }
-
- try {
- payload = JSON.parse(payloadStr);
- } catch (parseError) {
- const err = parseError instanceof Error ? parseError : new Error(String(parseError));
- // Log parse error for debugging
- console.warn(
- `[Kiro] Failed to parse payload: ${err.message} | payload: ${payloadStr.substring(0, 100)}`
- );
- payload = { raw: payloadStr };
- }
- }
-
- return { headers, payload };
- } catch (err) {
- const error = err instanceof Error ? err : new Error(String(err));
- console.warn(`[Kiro] Frame parse error: ${error.message}`);
- return null;
- }
-}
diff --git a/open-sse/executors/muse-spark-web.ts b/open-sse/executors/muse-spark-web.ts
index 106c28fb9d..6a7cac1f1d 100644
--- a/open-sse/executors/muse-spark-web.ts
+++ b/open-sse/executors/muse-spark-web.ts
@@ -13,11 +13,6 @@ import {
normalizeSessionCookieHeader,
normalizeSessionCookieHeaders,
} from "@/lib/providers/webCookieAuth";
-import {
- type ParsedMetaAiResponse,
- isRecord,
- parseMetaAiResponseText,
-} from "./muse-spark-web/response-parser.ts";
const META_AI_GRAPHQL_API = "https://www.meta.ai/api/graphql";
// Meta rebranded the chat product from "Abra" to "Ecto"; the session cookie
@@ -53,6 +48,25 @@ const MODEL_MAP: Record<string, MuseSparkModelInfo> = {
"muse-spark-contemplating": { mode: "think_hard", isThinking: true },
};
+type MetaSseFrame = {
+ event: string;
+ data: string;
+};
+
+type ParsedMetaAiResponse = {
+ content: string;
+ deltas: string[];
+ reasoningContent: string;
+ reasoningDeltas: string[];
+ errorCode: string | null;
+ errorMessage: string | null;
+ status: number;
+};
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return !!value && typeof value === "object" && !Array.isArray(value);
+}
+
function extractMessageText(content: unknown): string {
if (typeof content === "string") {
return content.trim();
@@ -373,6 +387,365 @@ function buildMetaAiRequestBody(prompt: string, model: string, conversation: Con
};
}
+function parseMetaSseFrames(text: string): MetaSseFrame[] {
+ const frames: MetaSseFrame[] = [];
+ const lines = text.split(/\r?\n/);
+ let currentEvent = "message";
+ let dataLines: string[] = [];
+
+ const flush = () => {
+ if (dataLines.length === 0 && currentEvent === "message") {
+ return;
+ }
+
+ frames.push({
+ event: currentEvent,
+ data: dataLines.join("\n").trim(),
+ });
+
+ currentEvent = "message";
+ dataLines = [];
+ };
+
+ for (const line of lines) {
+ if (!line) {
+ flush();
+ continue;
+ }
+
+ if (line.startsWith(":")) {
+ continue;
+ }
+
+ if (line.startsWith("event:")) {
+ currentEvent = line.slice("event:".length).trim() || "message";
+ continue;
+ }
+
+ if (line.startsWith("data:")) {
+ dataLines.push(line.slice("data:".length).trimStart());
+ }
+ }
+
+ flush();
+ return frames;
+}
+
+function readMetaJsonPayloads(text: string): Array<Record<string, unknown>> {
+ const trimmed = text.trim();
+ if (trimmed.startsWith("{")) {
+ try {
+ const parsed = JSON.parse(trimmed);
+ return isRecord(parsed) ? [parsed] : [];
+ } catch {
+ return [];
+ }
+ }
+
+ return parseMetaSseFrames(text)
+ .filter((frame) => frame.data)
+ .map((frame) => {
+ try {
+ const parsed = JSON.parse(frame.data);
+ return isRecord(parsed) ? parsed : null;
+ } catch {
+ return null;
+ }
+ })
+ .filter((frame): frame is Record<string, unknown> => !!frame);
+}
+
+const META_AI_REASONING_KEYS = [
+ "reasoning",
+ "reasoningContent",
+ "reasoning_content",
+ "reasoningText",
+ "thinking",
+ "thinkingContent",
+ "thinkingText",
+ "thought",
+ "thoughtText",
+ "thoughts",
+ "internalThoughts",
+ "chainOfThought",
+ "thinkingTrace",
+ "thinking_trace",
+] as const;
+
+const META_AI_NESTED_RENDERER_KEYS = [
+ "contentRenderer",
+ "textContent",
+ "message",
+ "mediaContent",
+ "unified_response",
+ "unifiedResponseContent",
+ "sections",
+ "view_model",
+ "primitive",
+ "primitives",
+ "nested_responses",
+] as const;
+
+function collectRendererTexts(value: unknown, seen: Set<string>, depth = 0): string[] {
+ if (depth > 8) {
+ return [];
+ }
+
+ if (typeof value === "string") {
+ const normalized = value.trim();
+ if (!normalized || seen.has(normalized)) {
+ return [];
+ }
+ seen.add(normalized);
+ return [normalized];
+ }
+
+ if (Array.isArray(value)) {
+ return value.flatMap((item) => collectRendererTexts(item, seen, depth + 1));
+ }
+
+ if (!isRecord(value)) {
+ return [];
+ }
+
+ const parts: string[] = [];
+ if (typeof value.text === "string") {
+ parts.push(...collectRendererTexts(value.text, seen, depth + 1));
+ }
+
+ for (const key of [
+ "contentRenderer",
+ "textContent",
+ "message",
+ "mediaContent",
+ "unified_response",
+ "unifiedResponseContent",
+ "sections",
+ "view_model",
+ "primitive",
+ "primitives",
+ "nested_responses",
+ ]) {
+ if (key in value) {
+ parts.push(...collectRendererTexts(value[key], seen, depth + 1));
+ }
+ }
+
+ return parts;
+}
+
+function collectReasoningTexts(
+ value: unknown,
+ seen: Set<string>,
+ depth = 0,
+ force = false
+): string[] {
+ if (depth > 8) {
+ return [];
+ }
+
+ if (typeof value === "string") {
+ const normalized = value.trim();
+ if (!force || !normalized || seen.has(normalized)) {
+ return [];
+ }
+ seen.add(normalized);
+ return [normalized];
+ }
+
+ if (Array.isArray(value)) {
+ return value.flatMap((item) => collectReasoningTexts(item, seen, depth + 1, force));
+ }
+
+ if (!isRecord(value)) {
+ return [];
+ }
+
+ const typename = typeof value.__typename === "string" ? value.__typename : "";
+ const localForce = force || /reasoning|thinking|thought/i.test(typename);
+ const parts: string[] = [];
+
+ if (typeof value.text === "string" && localForce) {
+ parts.push(...collectReasoningTexts(value.text, seen, depth + 1, true));
+ }
+
+ for (const key of META_AI_REASONING_KEYS) {
+ if (key in value) {
+ parts.push(...collectReasoningTexts(value[key], seen, depth + 1, true));
+ }
+ }
+
+ for (const key of META_AI_NESTED_RENDERER_KEYS) {
+ if (key in value) {
+ parts.push(...collectReasoningTexts(value[key], seen, depth + 1, localForce));
+ }
+ }
+
+ return parts;
+}
+
+function extractAssistantContent(message: Record<string, unknown>): string {
+ if (typeof message.content === "string" && message.content.length > 0) {
+ return message.content;
+ }
+
+ const contentRenderer = isRecord(message.contentRenderer) ? message.contentRenderer : null;
+ if (!contentRenderer) {
+ return "";
+ }
+
+ const parts = collectRendererTexts(contentRenderer, new Set());
+ return parts.join("\n\n").trim();
+}
+
+function extractAssistantReasoning(message: Record<string, unknown>): string {
+ const parts = collectReasoningTexts(message, new Set());
+ return parts.join("\n\n").trim();
+}
+
+function extractAssistantError(message: Record<string, unknown>) {
+ const error = isRecord(message.error) ? message.error : null;
+ const streamingState =
+ typeof message.streamingState === "string" ? message.streamingState.toUpperCase() : null;
+ return {
+ code: typeof error?.code === "string" ? error.code : null,
+ message:
+ typeof error?.message === "string"
+ ? error.message.trim()
+ : streamingState === "ERROR" &&
+ typeof message.content === "string" &&
+ message.content.trim()
+ ? message.content.trim()
+ : null,
+ };
+}
+
+function classifyMetaAiError(errorMessage: string | null, content: string) {
+ const combined = `${errorMessage || ""}\n${content}`.trim();
+ if (!combined) {
+ return null;
+ }
+
+ if (/authentication required to send messages|login is required|sign in/i.test(combined)) {
+ return {
+ status: 401,
+ message: "Meta AI auth failed — your meta.ai ecto_1_sess cookie may be missing or expired.",
+ };
+ }
+
+ if (/limit exceeded|rate limit|too many requests/i.test(combined)) {
+ return {
+ status: 429,
+ message: "Meta AI rate limited the session. Wait a moment and retry.",
+ };
+ }
+
+ if (/blocked by our security system|security system/i.test(combined)) {
+ return {
+ status: 403,
+ message:
+ "Meta AI blocked the request through its web security checks. Refresh the session cookie and retry.",
+ };
+ }
+
+ return null;
+}
+
+function parseMetaAiResponseText(text: string, isThinkingModel: boolean): ParsedMetaAiResponse {
+ let lastContent = "";
+ const deltas: string[] = [];
+ let lastReasoning = "";
+ const reasoningDeltas: string[] = [];
+ let errorCode: string | null = null;
+ let errorMessage: string | null = null;
+
+ for (const payload of readMetaJsonPayloads(text)) {
+ if (Array.isArray(payload.errors) && payload.errors.length > 0) {
+ const firstError = payload.errors.find(
+ (item) => isRecord(item) && typeof item.message === "string"
+ );
+ if (isRecord(firstError) && typeof firstError.message === "string") {
+ errorMessage = firstError.message.trim();
+ }
+ }
+
+ const data = isRecord(payload.data) ? payload.data : null;
+ const sendMessageStream = isRecord(data?.sendMessageStream) ? data?.sendMessageStream : null;
+ if (!sendMessageStream || sendMessageStream.__typename !== "AssistantMessage") {
+ continue;
+ }
+
+ const content = extractAssistantContent(sendMessageStream);
+ if (content && content !== lastContent) {
+ deltas.push(content.startsWith(lastContent) ? content.slice(lastContent.length) : content);
+ lastContent = content;
+ }
+
+ if (isThinkingModel) {
+ const reasoning = extractAssistantReasoning(sendMessageStream);
+ if (reasoning && reasoning !== content && reasoning !== lastReasoning) {
+ reasoningDeltas.push(
+ reasoning.startsWith(lastReasoning) ? reasoning.slice(lastReasoning.length) : reasoning
+ );
+ lastReasoning = reasoning;
+ }
+ }
+
+ const upstreamError = extractAssistantError(sendMessageStream);
+ if (upstreamError.message) {
+ errorMessage = upstreamError.message;
+ errorCode = upstreamError.code;
+ }
+ }
+
+ const classifiedError = classifyMetaAiError(errorMessage, lastContent);
+ if (classifiedError) {
+ return {
+ content: lastContent,
+ deltas,
+ reasoningContent: lastReasoning,
+ reasoningDeltas,
+ errorCode,
+ errorMessage: classifiedError.message,
+ status: classifiedError.status,
+ };
+ }
+
+ if (errorMessage) {
+ return {
+ content: lastContent,
+ deltas,
+ reasoningContent: lastReasoning,
+ reasoningDeltas,
+ errorCode,
+ errorMessage: `Meta AI returned an error: ${errorMessage}`,
+ status: 502,
+ };
+ }
+
+ if (!lastContent) {
+ return {
+ content: "",
+ deltas: [],
+ reasoningContent: lastReasoning,
+ reasoningDeltas,
+ errorCode: null,
+ errorMessage: "Meta AI returned no assistant content",
+ status: 502,
+ };
+ }
+
+ return {
+ content: lastContent,
+ deltas: deltas.filter((delta) => delta.length > 0),
+ reasoningContent: lastReasoning,
+ reasoningDeltas: reasoningDeltas.filter((delta) => delta.length > 0),
+ errorCode: null,
+ errorMessage: null,
+ status: 200,
+ };
+}
+
function sseChunk(data: unknown): string {
return `data: ${JSON.stringify(data)}\n\n`;
}
diff --git a/open-sse/executors/muse-spark-web/response-parser.ts b/open-sse/executors/muse-spark-web/response-parser.ts
deleted file mode 100644
index 2e80a10447..0000000000
--- a/open-sse/executors/muse-spark-web/response-parser.ts
+++ /dev/null
@@ -1,383 +0,0 @@
-// Pure Meta AI SSE/JSON response parsing + content/reasoning/error extraction.
-// Extracted verbatim from muse-spark-web.ts. No host state/fetch/auth.
-
-export type MetaSseFrame = {
- event: string;
- data: string;
-};
-
-export type ParsedMetaAiResponse = {
- content: string;
- deltas: string[];
- reasoningContent: string;
- reasoningDeltas: string[];
- errorCode: string | null;
- errorMessage: string | null;
- status: number;
-};
-
-export function isRecord(value: unknown): value is Record<string, unknown> {
- return !!value && typeof value === "object" && !Array.isArray(value);
-}
-
-export function parseMetaSseFrames(text: string): MetaSseFrame[] {
- const frames: MetaSseFrame[] = [];
- const lines = text.split(/\r?\n/);
- let currentEvent = "message";
- let dataLines: string[] = [];
-
- const flush = () => {
- if (dataLines.length === 0 && currentEvent === "message") {
- return;
- }
-
- frames.push({
- event: currentEvent,
- data: dataLines.join("\n").trim(),
- });
-
- currentEvent = "message";
- dataLines = [];
- };
-
- for (const line of lines) {
- if (!line) {
- flush();
- continue;
- }
-
- if (line.startsWith(":")) {
- continue;
- }
-
- if (line.startsWith("event:")) {
- currentEvent = line.slice("event:".length).trim() || "message";
- continue;
- }
-
- if (line.startsWith("data:")) {
- dataLines.push(line.slice("data:".length).trimStart());
- }
- }
-
- flush();
- return frames;
-}
-
-export function readMetaJsonPayloads(text: string): Array<Record<string, unknown>> {
- const trimmed = text.trim();
- if (trimmed.startsWith("{")) {
- try {
- const parsed = JSON.parse(trimmed);
- return isRecord(parsed) ? [parsed] : [];
- } catch {
- return [];
- }
- }
-
- return parseMetaSseFrames(text)
- .filter((frame) => frame.data)
- .map((frame) => {
- try {
- const parsed = JSON.parse(frame.data);
- return isRecord(parsed) ? parsed : null;
- } catch {
- return null;
- }
- })
- .filter((frame): frame is Record<string, unknown> => !!frame);
-}
-
-export const META_AI_REASONING_KEYS = [
- "reasoning",
- "reasoningContent",
- "reasoning_content",
- "reasoningText",
- "thinking",
- "thinkingContent",
- "thinkingText",
- "thought",
- "thoughtText",
- "thoughts",
- "internalThoughts",
- "chainOfThought",
- "thinkingTrace",
- "thinking_trace",
-] as const;
-
-export const META_AI_NESTED_RENDERER_KEYS = [
- "contentRenderer",
- "textContent",
- "message",
- "mediaContent",
- "unified_response",
- "unifiedResponseContent",
- "sections",
- "view_model",
- "primitive",
- "primitives",
- "nested_responses",
-] as const;
-
-export function collectRendererTexts(value: unknown, seen: Set<string>, depth = 0): string[] {
- if (depth > 8) {
- return [];
- }
-
- if (typeof value === "string") {
- const normalized = value.trim();
- if (!normalized || seen.has(normalized)) {
- return [];
- }
- seen.add(normalized);
- return [normalized];
- }
-
- if (Array.isArray(value)) {
- return value.flatMap((item) => collectRendererTexts(item, seen, depth + 1));
- }
-
- if (!isRecord(value)) {
- return [];
- }
-
- const parts: string[] = [];
- if (typeof value.text === "string") {
- parts.push(...collectRendererTexts(value.text, seen, depth + 1));
- }
-
- for (const key of [
- "contentRenderer",
- "textContent",
- "message",
- "mediaContent",
- "unified_response",
- "unifiedResponseContent",
- "sections",
- "view_model",
- "primitive",
- "primitives",
- "nested_responses",
- ]) {
- if (key in value) {
- parts.push(...collectRendererTexts(value[key], seen, depth + 1));
- }
- }
-
- return parts;
-}
-
-export function collectReasoningTexts(
- value: unknown,
- seen: Set<string>,
- depth = 0,
- force = false
-): string[] {
- if (depth > 8) {
- return [];
- }
-
- if (typeof value === "string") {
- const normalized = value.trim();
- if (!force || !normalized || seen.has(normalized)) {
- return [];
- }
- seen.add(normalized);
- return [normalized];
- }
-
- if (Array.isArray(value)) {
- return value.flatMap((item) => collectReasoningTexts(item, seen, depth + 1, force));
- }
-
- if (!isRecord(value)) {
- return [];
- }
-
- const typename = typeof value.__typename === "string" ? value.__typename : "";
- const localForce = force || /reasoning|thinking|thought/i.test(typename);
- const parts: string[] = [];
-
- if (typeof value.text === "string" && localForce) {
- parts.push(...collectReasoningTexts(value.text, seen, depth + 1, true));
- }
-
- for (const key of META_AI_REASONING_KEYS) {
- if (key in value) {
- parts.push(...collectReasoningTexts(value[key], seen, depth + 1, true));
- }
- }
-
- for (const key of META_AI_NESTED_RENDERER_KEYS) {
- if (key in value) {
- parts.push(...collectReasoningTexts(value[key], seen, depth + 1, localForce));
- }
- }
-
- return parts;
-}
-
-export function extractAssistantContent(message: Record<string, unknown>): string {
- if (typeof message.content === "string" && message.content.length > 0) {
- return message.content;
- }
-
- const contentRenderer = isRecord(message.contentRenderer) ? message.contentRenderer : null;
- if (!contentRenderer) {
- return "";
- }
-
- const parts = collectRendererTexts(contentRenderer, new Set());
- return parts.join("\n\n").trim();
-}
-
-export function extractAssistantReasoning(message: Record<string, unknown>): string {
- const parts = collectReasoningTexts(message, new Set());
- return parts.join("\n\n").trim();
-}
-
-export function extractAssistantError(message: Record<string, unknown>) {
- const error = isRecord(message.error) ? message.error : null;
- const streamingState =
- typeof message.streamingState === "string" ? message.streamingState.toUpperCase() : null;
- return {
- code: typeof error?.code === "string" ? error.code : null,
- message:
- typeof error?.message === "string"
- ? error.message.trim()
- : streamingState === "ERROR" &&
- typeof message.content === "string" &&
- message.content.trim()
- ? message.content.trim()
- : null,
- };
-}
-
-export function classifyMetaAiError(errorMessage: string | null, content: string) {
- const combined = `${errorMessage || ""}\n${content}`.trim();
- if (!combined) {
- return null;
- }
-
- if (/authentication required to send messages|login is required|sign in/i.test(combined)) {
- return {
- status: 401,
- message: "Meta AI auth failed — your meta.ai ecto_1_sess cookie may be missing or expired.",
- };
- }
-
- if (/limit exceeded|rate limit|too many requests/i.test(combined)) {
- return {
- status: 429,
- message: "Meta AI rate limited the session. Wait a moment and retry.",
- };
- }
-
- if (/blocked by our security system|security system/i.test(combined)) {
- return {
- status: 403,
- message:
- "Meta AI blocked the request through its web security checks. Refresh the session cookie and retry.",
- };
- }
-
- return null;
-}
-
-export function parseMetaAiResponseText(
- text: string,
- isThinkingModel: boolean
-): ParsedMetaAiResponse {
- let lastContent = "";
- const deltas: string[] = [];
- let lastReasoning = "";
- const reasoningDeltas: string[] = [];
- let errorCode: string | null = null;
- let errorMessage: string | null = null;
-
- for (const payload of readMetaJsonPayloads(text)) {
- if (Array.isArray(payload.errors) && payload.errors.length > 0) {
- const firstError = payload.errors.find(
- (item) => isRecord(item) && typeof item.message === "string"
- );
- if (isRecord(firstError) && typeof firstError.message === "string") {
- errorMessage = firstError.message.trim();
- }
- }
-
- const data = isRecord(payload.data) ? payload.data : null;
- const sendMessageStream = isRecord(data?.sendMessageStream) ? data?.sendMessageStream : null;
- if (!sendMessageStream || sendMessageStream.__typename !== "AssistantMessage") {
- continue;
- }
-
- const content = extractAssistantContent(sendMessageStream);
- if (content && content !== lastContent) {
- deltas.push(content.startsWith(lastContent) ? content.slice(lastContent.length) : content);
- lastContent = content;
- }
-
- if (isThinkingModel) {
- const reasoning = extractAssistantReasoning(sendMessageStream);
- if (reasoning && reasoning !== content && reasoning !== lastReasoning) {
- reasoningDeltas.push(
- reasoning.startsWith(lastReasoning) ? reasoning.slice(lastReasoning.length) : reasoning
- );
- lastReasoning = reasoning;
- }
- }
-
- const upstreamError = extractAssistantError(sendMessageStream);
- if (upstreamError.message) {
- errorMessage = upstreamError.message;
- errorCode = upstreamError.code;
- }
- }
-
- const classifiedError = classifyMetaAiError(errorMessage, lastContent);
- if (classifiedError) {
- return {
- content: lastContent,
- deltas,
- reasoningContent: lastReasoning,
- reasoningDeltas,
- errorCode,
- errorMessage: classifiedError.message,
- status: classifiedError.status,
- };
- }
-
- if (errorMessage) {
- return {
- content: lastContent,
- deltas,
- reasoningContent: lastReasoning,
- reasoningDeltas,
- errorCode,
- errorMessage: `Meta AI returned an error: ${errorMessage}`,
- status: 502,
- };
- }
-
- if (!lastContent) {
- return {
- content: "",
- deltas: [],
- reasoningContent: lastReasoning,
- reasoningDeltas,
- errorCode: null,
- errorMessage: "Meta AI returned no assistant content",
- status: 502,
- };
- }
-
- return {
- content: lastContent,
- deltas: deltas.filter((delta) => delta.length > 0),
- reasoningContent: lastReasoning,
- reasoningDeltas: reasoningDeltas.filter((delta) => delta.length > 0),
- errorCode: null,
- errorMessage: null,
- status: 200,
- };
-}
diff --git a/open-sse/executors/perplexity-web.ts b/open-sse/executors/perplexity-web.ts
index d5c693cff3..9b4397fae4 100644
--- a/open-sse/executors/perplexity-web.ts
+++ b/open-sse/executors/perplexity-web.ts
@@ -13,21 +13,75 @@ import {
TlsClientUnavailableError,
type TlsFetchResult,
} from "../services/perplexityTlsClient.ts";
-import { prepareToolMessages } from "../translator/webTools.ts";
-import { buildToolModeResponse } from "./chatgptWebTools.ts";
+import { prepareToolMessages, buildToolAwareResult } from "../translator/webTools.ts";
import { sanitizeErrorMessage } from "../utils/error.ts";
-import {
- PPLX_SSE_ENDPOINT,
- PPLX_USER_AGENT,
- MODEL_MAP,
- THINKING_MAP,
- cleanResponse,
- parseOpenAIMessages,
- buildPplxRequestBody,
- buildQuery,
- extractContent,
- sseChunk,
-} from "./perplexity-web/protocol.ts";
+
+const PPLX_SSE_ENDPOINT = "https://www.perplexity.ai/rest/sse/perplexity_ask";
+// Perplexity's current request schema version (sent in params.version). Perplexity rejects
+// stale versions with HTTP 400 — keep this in lockstep with the website's payload.
+const PPLX_API_VERSION = "2.18";
+// Block use-cases the current web client advertises. The schematized API (use_schematized_api)
+// validates the request shape, so this must be present (mirrors the browser request body).
+const PPLX_SUPPORTED_BLOCK_USE_CASES = [
+ "answer_modes",
+ "media_items",
+ "knowledge_cards",
+ "inline_entity_cards",
+ "place_widgets",
+ "finance_widgets",
+ "sports_widgets",
+ "news_widgets",
+ "shopping_widgets",
+ "jobs_widgets",
+ "search_result_widgets",
+ "inline_images",
+ "inline_assets",
+ "placeholder_cards",
+ "diff_blocks",
+ "inline_knowledge_cards",
+ "entity_group_v2",
+ "refinement_filters",
+ "canvas_mode",
+ "maps_preview",
+ "answer_tabs",
+ "price_comparison_widgets",
+ "preserve_latex",
+ "generic_onboarding_widgets",
+ "in_context_suggestions",
+ "pending_followups",
+ "inline_claims",
+ "unified_assets",
+ "workflow_steps",
+ "background_agents",
+];
+// Firefox 148 — must match the `firefox_148` TLS profile used by perplexityTlsClient.
+// A mismatched UA vs TLS fingerprint is itself a Cloudflare bot signal (issue #2459).
+const PPLX_USER_AGENT =
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:148.0) Gecko/20100101 Firefox/148.0";
+
+const MODEL_MAP: Record<string, [string, string]> = {
+ "pplx-auto": ["concise", "pplx_pro"],
+ "pplx-sonar": ["copilot", "experimental"],
+ "pplx-gpt": ["copilot", "gpt54"],
+ "pplx-gemini": ["copilot", "gemini31pro_high"],
+ "pplx-sonnet": ["copilot", "claude46sonnet"],
+ "pplx-opus": ["copilot", "claude46opus"],
+ "pplx-nemotron": ["copilot", "nv_nemotron_3_super"],
+};
+
+const THINKING_MAP: Record<string, string> = {
+ "pplx-gpt": "gpt54_thinking",
+ "pplx-sonnet": "claude46sonnetthinking",
+ "pplx-opus": "claude46opusthinking",
+};
+
+const CITATION_RE = /\[\d+\]/g;
+const GROK_TAG_RE = /<grok:[^>]*>.*?<\/grok:[^>]*>/gs;
+const GROK_SELF_RE = /<grok:[^>]*\/>/g;
+const XML_DECL_RE = /<[?]xml[^?]*[?]>/g;
+const RESPONSE_TAG_RE = /<\/?response\b[^>]*>/gi;
+const MULTI_SPACE = / {2,}/g;
+const MULTI_NL = /\n{3,}/g;
// ─── Session continuity ─────────────────────────────────────────────────────
@@ -90,6 +144,434 @@ function sessionStore(
}
}
+// ─── Helpers ────────────────────────────────────────────────────────────────
+
+function cleanResponse(text: string, strip = true): string {
+ let t = text;
+ t = t.replace(XML_DECL_RE, "");
+ t = t.replace(CITATION_RE, "");
+ t = t.replace(GROK_TAG_RE, "");
+ t = t.replace(GROK_SELF_RE, "");
+ t = t.replace(RESPONSE_TAG_RE, "");
+ if (strip) {
+ t = t.replace(MULTI_SPACE, " ");
+ t = t.replace(MULTI_NL, "\n\n");
+ t = t.trim();
+ }
+ return t;
+}
+
+// ─── SSE types ──────────────────────────────────────────────────────────────
+
+interface PplxDiffPatch {
+ op?: string;
+ path?: string;
+ value?: unknown;
+}
+
+interface PplxBlock {
+ intended_usage?: string;
+ markdown_block?: {
+ answer?: string;
+ chunks?: string[];
+ progress?: string;
+ chunk_starting_offset?: number;
+ };
+ // Schematized API (use_schematized_api) streams block updates as RFC-6902
+ // JSON-patch diffs against a target field (e.g. markdown_block) instead of
+ // sending the whole block each frame. `field` names the block being patched.
+ diff_block?: {
+ field?: string;
+ patches?: PplxDiffPatch[];
+ };
+ web_result_block?: {
+ web_results?: Array<{ url?: string; name?: string; snippet?: string }>;
+ };
+ plan_block?: {
+ steps?: Array<{
+ step_type?: string;
+ search_web_content?: { queries?: Array<{ query?: string }> };
+ read_results_content?: { urls?: string[] };
+ }>;
+ goals?: Array<{ description?: string }>;
+ };
+}
+
+interface PplxStreamEvent {
+ status?: string;
+ final?: boolean;
+ text?: string;
+ blocks?: PplxBlock[];
+ backend_uuid?: string;
+ web_results?: Array<{ url?: string; name?: string }>;
+ error_code?: string;
+ error_message?: string;
+ display_model?: string;
+}
+
+// ─── SSE parsing ────────────────────────────────────────────────────────────
+
+async function* readPplxSseEvents(
+ body: ReadableStream<Uint8Array>,
+ signal?: AbortSignal | null
+): AsyncGenerator<PplxStreamEvent> {
+ const reader = body.getReader();
+ const decoder = new TextDecoder();
+ let buffer = "";
+ let dataLines: string[] = [];
+
+ function flush(): PplxStreamEvent | null | "done" {
+ if (dataLines.length === 0) return null;
+ const payload = dataLines.join("\n");
+ dataLines = [];
+ const trimmed = payload.trim();
+ if (!trimmed || trimmed === "[DONE]") return "done";
+ try {
+ return JSON.parse(trimmed) as PplxStreamEvent;
+ } catch {
+ return null;
+ }
+ }
+
+ try {
+ while (true) {
+ if (signal?.aborted) return;
+ const { value, done } = await reader.read();
+ if (done) break;
+ buffer += decoder.decode(value, { stream: true });
+
+ while (true) {
+ const idx = buffer.indexOf("\n");
+ if (idx < 0) break;
+ const rawLine = buffer.slice(0, idx);
+ buffer = buffer.slice(idx + 1);
+ const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
+
+ if (line === "") {
+ const parsed = flush();
+ if (parsed === "done") return;
+ if (parsed) yield parsed;
+ continue;
+ }
+ if (line.startsWith("data:")) {
+ dataLines.push(line.slice(5).trimStart());
+ }
+ if (line === "event: end_of_stream") {
+ return;
+ }
+ }
+ }
+
+ buffer += decoder.decode();
+ if (buffer.trim().startsWith("data:")) {
+ dataLines.push(buffer.trim().slice(5).trimStart());
+ }
+ const tail = flush();
+ if (tail && tail !== "done") yield tail;
+ } finally {
+ reader.releaseLock();
+ }
+}
+
+// ─── OpenAI → Perplexity translation ────────────────────────────────────────
+
+interface ParsedMessages {
+ systemMsg: string;
+ history: Array<{ role: string; content: string }>;
+ currentMsg: string;
+}
+
+function parseOpenAIMessages(messages: Array<Record<string, unknown>>): ParsedMessages {
+ let systemMsg = "";
+ const history: Array<{ role: string; content: string }> = [];
+
+ for (const msg of messages) {
+ let role = String(msg.role || "user");
+ if (role === "developer") role = "system";
+
+ let content = "";
+ if (typeof msg.content === "string") {
+ content = msg.content;
+ } else if (Array.isArray(msg.content)) {
+ content = (msg.content as Array<Record<string, unknown>>)
+ .filter((c) => c.type === "text")
+ .map((c) => String(c.text || ""))
+ .join(" ");
+ }
+ if (!content.trim()) continue;
+
+ if (role === "system") {
+ systemMsg += content + "\n";
+ } else if (role === "user" || role === "assistant") {
+ history.push({ role, content });
+ }
+ }
+
+ let currentMsg = "";
+ if (history.length > 0 && history[history.length - 1].role === "user") {
+ currentMsg = history.pop()!.content;
+ }
+
+ return { systemMsg, history, currentMsg };
+}
+
+function buildPplxRequestBody(
+ query: string,
+ dslQuery: string,
+ mode: string,
+ modelPref: string,
+ followUpUuid: string | null,
+ requestId: string
+): Record<string, unknown> {
+ const tz = typeof Intl !== "undefined" ? Intl.DateTimeFormat().resolvedOptions().timeZone : "UTC";
+
+ // Mirrors the current www.perplexity.ai/rest/sse/perplexity_ask request body. Perplexity's
+ // schematized API validates this shape; an outdated version or missing required fields → HTTP 400.
+ const params: Record<string, unknown> = {
+ attachments: [],
+ language: "en-US",
+ timezone: tz,
+ search_focus: "internet",
+ sources: ["web"],
+ frontend_uuid: requestId,
+ mode,
+ model_preference: modelPref,
+ is_related_query: false,
+ is_sponsored: false,
+ frontend_context_uuid: crypto.randomUUID(),
+ prompt_source: "user",
+ query_source: "home",
+ is_incognito: true,
+ local_search_enabled: false,
+ use_schematized_api: true,
+ send_back_text_in_streaming_api: false,
+ supported_block_use_cases: PPLX_SUPPORTED_BLOCK_USE_CASES,
+ client_coordinates: null,
+ mentions: [],
+ dsl_query: dslQuery && dslQuery.trim() ? dslQuery : query,
+ skip_search_enabled: true,
+ is_nav_suggestions_disabled: false,
+ source: "default",
+ always_search_override: false,
+ override_no_search: false,
+ client_search_results_cache_key: requestId,
+ should_ask_for_mcp_tool_confirmation: true,
+ browser_agent_allow_once_from_toggle: false,
+ force_enable_browser_agent: false,
+ supported_features: ["browser_agent_permission_banner_v1.1"],
+ extended_context: false,
+ version: PPLX_API_VERSION,
+ rum_session_id: crypto.randomUUID(),
+ };
+
+ // Only present on follow-ups (matches the browser, which omits it for a fresh query).
+ if (followUpUuid) {
+ params.last_backend_uuid = followUpUuid;
+ }
+
+ return {
+ query_str: query,
+ params,
+ };
+}
+
+function buildQuery(parsed: ParsedMessages, followUpUuid: string | null): string {
+ if (followUpUuid) return parsed.currentMsg;
+
+ const obj: Record<string, unknown> = {};
+ if (parsed.systemMsg.trim()) {
+ obj.instructions = [
+ parsed.systemMsg.trim(),
+ "You have built-in web search. Answer questions directly using search results.",
+ ];
+ }
+ if (parsed.history.length > 0) {
+ obj.history = parsed.history;
+ }
+ if (parsed.currentMsg) {
+ obj.query = parsed.currentMsg;
+ } else if (parsed.history.length === 0) {
+ obj.query = "";
+ }
+ const json = JSON.stringify(obj);
+ return json.length > 96000 ? json.slice(-96000) : json;
+}
+
+// ─── Content extraction ─────────────────────────────────────────────────────
+
+interface ContentChunk {
+ delta?: string;
+ answer?: string;
+ backendUuid?: string;
+ thinking?: string;
+ error?: string;
+ done?: boolean;
+}
+
+// The schematized API delivers the answer text in blocks whose `intended_usage`
+// is either the aggregate `ask_text` or per-segment `ask_text_<n>_markdown`
+// (older builds used names merely containing "markdown"). All converge on the
+// same answer, so we lock onto a single primary usage to avoid double-counting.
+function isAnswerTextUsage(usage: string): boolean {
+ return (
+ usage === "ask_text" || /^ask_text_\d+_markdown$/.test(usage) || usage.includes("markdown")
+ );
+}
+
+// Reconstructed state for one answer-text block, built up from diff patches
+// (streaming) or a materialized markdown_block (final COMPLETED frame).
+interface MarkdownAccumulator {
+ chunks: string[];
+}
+
+// Apply a markdown_block diff_block patch set. Perplexity sends an initial
+// `{op:"replace", path:"", value:{chunks:[...]}}` then incremental
+// `{op:"add", path:"/chunks/<n>", value:"..."}` frames. We only need the
+// chunks array; joining it yields the cumulative answer text.
+function applyMarkdownDiff(acc: MarkdownAccumulator, patches: PplxDiffPatch[]): void {
+ for (const patch of patches) {
+ const path = patch.path ?? "";
+ if (path === "") {
+ const value = (patch.value ?? {}) as { chunks?: unknown };
+ acc.chunks = Array.isArray(value.chunks) ? value.chunks.map((c) => String(c)) : [];
+ continue;
+ }
+ const chunkMatch = /^\/chunks\/(\d+)$/.exec(path);
+ if (chunkMatch && typeof patch.value === "string") {
+ const idx = Number.parseInt(chunkMatch[1], 10);
+ acc.chunks[idx] = patch.value;
+ }
+ }
+}
+
+async function* extractContent(
+ eventStream: ReadableStream<Uint8Array>,
+ signal?: AbortSignal | null
+): AsyncGenerator<ContentChunk> {
+ let fullAnswer = "";
+ let backendUuid: string | null = null;
+ let seenLen = 0;
+ const seenThinking = new Set<string>();
+ // Per-usage reconstructed answer-text blocks + the locked primary usage.
+ const mdState = new Map<string, MarkdownAccumulator>();
+ let primaryUsage: string | null = null;
+
+ for await (const event of readPplxSseEvents(eventStream, signal)) {
+ if (event.error_code || event.error_message) {
+ yield {
+ error: event.error_message || `Perplexity error: ${event.error_code}`,
+ done: true,
+ };
+ return;
+ }
+
+ if (event.backend_uuid) backendUuid = event.backend_uuid;
+
+ const blocks = event.blocks ?? [];
+ for (const block of blocks) {
+ const usage = block.intended_usage ?? "";
+
+ // Thinking: search steps
+ if (usage === "pro_search_steps" && block.plan_block?.steps) {
+ for (const step of block.plan_block.steps) {
+ if (step.step_type === "SEARCH_WEB") {
+ for (const q of step.search_web_content?.queries ?? []) {
+ const qr = q.query ?? "";
+ if (qr && !seenThinking.has(qr)) {
+ seenThinking.add(qr);
+ yield { thinking: `Searching: ${qr}`, backendUuid: backendUuid ?? undefined };
+ }
+ }
+ } else if (step.step_type === "READ_RESULTS") {
+ for (const u of (step.read_results_content?.urls ?? []).slice(0, 3)) {
+ if (u && !seenThinking.has(u)) {
+ seenThinking.add(u);
+ yield { thinking: `Reading: ${u}`, backendUuid: backendUuid ?? undefined };
+ }
+ }
+ }
+ }
+ }
+
+ // Thinking: plan goals
+ if (usage === "plan" && block.plan_block?.goals) {
+ for (const goal of block.plan_block.goals) {
+ const desc = goal.description ?? "";
+ if (desc && !seenThinking.has(desc)) {
+ seenThinking.add(desc);
+ yield { thinking: desc, backendUuid: backendUuid ?? undefined };
+ }
+ }
+ }
+
+ // Content: answer-text blocks (schematized diff frames OR materialized
+ // markdown_block on the final COMPLETED frame).
+ if (!isAnswerTextUsage(usage)) continue;
+ let acc = mdState.get(usage);
+ if (!acc) {
+ acc = { chunks: [] };
+ mdState.set(usage, acc);
+ }
+
+ if (block.diff_block && Array.isArray(block.diff_block.patches)) {
+ applyMarkdownDiff(acc, block.diff_block.patches);
+ } else if (block.markdown_block) {
+ const mb = block.markdown_block;
+ if (Array.isArray(mb.chunks) && mb.chunks.length > 0) {
+ acc.chunks = mb.chunks.map((c) => String(c));
+ } else if (typeof mb.answer === "string" && mb.answer.length > 0) {
+ acc.chunks = [mb.answer];
+ }
+ }
+
+ // Prefer the aggregate `ask_text` block; otherwise lock the first seen.
+ if (usage === "ask_text") {
+ primaryUsage = "ask_text";
+ } else if (!primaryUsage) {
+ primaryUsage = usage;
+ }
+ }
+
+ // Emit at most one content delta per event, from the locked primary usage.
+ if (primaryUsage) {
+ const currentAnswer = (mdState.get(primaryUsage)?.chunks ?? []).join("");
+ if (currentAnswer.length > seenLen) {
+ const delta = currentAnswer.slice(seenLen);
+ fullAnswer = currentAnswer;
+ seenLen = currentAnswer.length;
+ yield { delta, answer: fullAnswer, backendUuid: backendUuid ?? undefined };
+ }
+ }
+
+ // Legacy fallback: a plain non-JSON `text` field with no structured blocks.
+ // The schematized API's `text` field is a JSON step-blob (not user-facing),
+ // so only use it when there are no answer-text blocks at all.
+ if (!primaryUsage && blocks.length === 0 && event.text) {
+ const t = event.text.trim();
+ const looksLikeJson = t.startsWith("{") || t.startsWith("[");
+ if (!looksLikeJson && t.length > seenLen) {
+ const delta = t.slice(seenLen);
+ fullAnswer = t;
+ seenLen = t.length;
+ yield { delta, answer: fullAnswer, backendUuid: backendUuid ?? undefined };
+ }
+ }
+
+ // Only stop on the terminal COMPLETED frame. A `final:true` flag can appear
+ // on a still-PENDING frame BEFORE the COMPLETED frame that materializes the
+ // full markdown_block — breaking on `final` there drops the answer.
+ if (event.status === "COMPLETED") break;
+ }
+
+ yield { delta: "", answer: fullAnswer, backendUuid: backendUuid ?? undefined, done: true };
+}
+
+// ─── OpenAI SSE format ──────────────────────────────────────────────────────
+
+function sseChunk(data: unknown): string {
+ return `data: ${JSON.stringify(data)}\n\n`;
+}
+
function buildStreamingResponse(
eventStream: ReadableStream<Uint8Array>,
model: string,
@@ -483,29 +965,8 @@ export class PerplexityWebExecutor extends BaseExecutor {
const cid = `chatcmpl-pplx-${crypto.randomUUID().slice(0, 12)}`;
const created = Math.floor(Date.now() / 1000);
- // Tool mode buffers the full completion (no live token streaming) and
- // converts <tool> text into real tool_calls — even when the caller asked
- // for a streaming response — mirroring chatgpt-web's toolMode (#5240,
- // #5927). Without this, streaming requests (the default for agentic
- // coding clients) never emitted a tool_calls SSE delta.
let finalResponse: Response;
- if (hasTools) {
- const bufferedJson = await buildNonStreamingResponse(
- response.body,
- model,
- cid,
- created,
- parsed.history,
- parsed.currentMsg,
- signal
- );
- finalResponse = await buildToolModeResponse(bufferedJson, requestedTools, stream, {
- cid,
- created,
- model,
- idSeed: "pplx",
- });
- } else if (stream) {
+ if (stream) {
const sseStream = buildStreamingResponse(
response.body,
model,
@@ -535,6 +996,31 @@ export class PerplexityWebExecutor extends BaseExecutor {
);
}
+ if (hasTools && !stream) {
+ const bodyText = await (finalResponse as Response).text();
+ try {
+ const json = JSON.parse(bodyText);
+ const rawContent = json?.choices?.[0]?.message?.content || "";
+ const { content, toolCalls, finishReason } = buildToolAwareResult(
+ rawContent,
+ requestedTools,
+ "pplx"
+ );
+ if (toolCalls) {
+ json.choices[0].message = { role: "assistant", content: null, tool_calls: toolCalls };
+ json.choices[0].finish_reason = finishReason;
+ } else {
+ json.choices[0].message.content = content;
+ }
+ finalResponse = new Response(JSON.stringify(json), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+ } catch {
+ /* keep original response */
+ }
+ }
+
return {
response: finalResponse,
url: PPLX_SSE_ENDPOINT,
diff --git a/open-sse/executors/perplexity-web/protocol.ts b/open-sse/executors/perplexity-web/protocol.ts
deleted file mode 100644
index 102ef3f9b9..0000000000
--- a/open-sse/executors/perplexity-web/protocol.ts
+++ /dev/null
@@ -1,498 +0,0 @@
-// Pure Perplexity wire protocol: consts, types, SSE parsing, request/query building,
-// content extraction. Extracted verbatim from perplexity-web.ts. No host state/fetch/auth.
-import { randomUUID } from "crypto";
-
-export const PPLX_SSE_ENDPOINT = "https://www.perplexity.ai/rest/sse/perplexity_ask";
-// Perplexity's current request schema version (sent in params.version). Perplexity rejects
-// stale versions with HTTP 400 — keep this in lockstep with the website's payload.
-export const PPLX_API_VERSION = "2.18";
-// Block use-cases the current web client advertises. The schematized API (use_schematized_api)
-// validates the request shape, so this must be present (mirrors the browser request body).
-export const PPLX_SUPPORTED_BLOCK_USE_CASES = [
- "answer_modes",
- "media_items",
- "knowledge_cards",
- "inline_entity_cards",
- "place_widgets",
- "finance_widgets",
- "sports_widgets",
- "news_widgets",
- "shopping_widgets",
- "jobs_widgets",
- "search_result_widgets",
- "inline_images",
- "inline_assets",
- "placeholder_cards",
- "diff_blocks",
- "inline_knowledge_cards",
- "entity_group_v2",
- "refinement_filters",
- "canvas_mode",
- "maps_preview",
- "answer_tabs",
- "price_comparison_widgets",
- "preserve_latex",
- "generic_onboarding_widgets",
- "in_context_suggestions",
- "pending_followups",
- "inline_claims",
- "unified_assets",
- "workflow_steps",
- "background_agents",
-];
-// Firefox 148 — must match the `firefox_148` TLS profile used by perplexityTlsClient.
-// A mismatched UA vs TLS fingerprint is itself a Cloudflare bot signal (issue #2459).
-export const PPLX_USER_AGENT =
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:148.0) Gecko/20100101 Firefox/148.0";
-
-export const MODEL_MAP: Record<string, [string, string]> = {
- "pplx-auto": ["concise", "pplx_pro"],
- "pplx-sonar": ["copilot", "experimental"],
- "pplx-gpt": ["copilot", "gpt54"],
- "pplx-gemini": ["copilot", "gemini31pro_high"],
- "pplx-sonnet": ["copilot", "claude46sonnet"],
- "pplx-opus": ["copilot", "claude46opus"],
- "pplx-nemotron": ["copilot", "nv_nemotron_3_super"],
-};
-
-export const THINKING_MAP: Record<string, string> = {
- "pplx-gpt": "gpt54_thinking",
- "pplx-sonnet": "claude46sonnetthinking",
- "pplx-opus": "claude46opusthinking",
-};
-
-export const CITATION_RE = /\[\d+\]/g;
-export const GROK_TAG_RE = /<grok:[^>]*>.*?<\/grok:[^>]*>/gs;
-export const GROK_SELF_RE = /<grok:[^>]*\/>/g;
-export const XML_DECL_RE = /<[?]xml[^?]*[?]>/g;
-export const RESPONSE_TAG_RE = /<\/?response\b[^>]*>/gi;
-export const MULTI_SPACE = / {2,}/g;
-export const MULTI_NL = /\n{3,}/g;
-
-// ─── Helpers ────────────────────────────────────────────────────────────────
-
-export function cleanResponse(text: string, strip = true): string {
- let t = text;
- t = t.replace(XML_DECL_RE, "");
- t = t.replace(CITATION_RE, "");
- t = t.replace(GROK_TAG_RE, "");
- t = t.replace(GROK_SELF_RE, "");
- t = t.replace(RESPONSE_TAG_RE, "");
- if (strip) {
- t = t.replace(MULTI_SPACE, " ");
- t = t.replace(MULTI_NL, "\n\n");
- t = t.trim();
- }
- return t;
-}
-
-// ─── SSE types ──────────────────────────────────────────────────────────────
-
-export interface PplxDiffPatch {
- op?: string;
- path?: string;
- value?: unknown;
-}
-
-export interface PplxBlock {
- intended_usage?: string;
- markdown_block?: {
- answer?: string;
- chunks?: string[];
- progress?: string;
- chunk_starting_offset?: number;
- };
- // Schematized API (use_schematized_api) streams block updates as RFC-6902
- // JSON-patch diffs against a target field (e.g. markdown_block) instead of
- // sending the whole block each frame. `field` names the block being patched.
- diff_block?: {
- field?: string;
- patches?: PplxDiffPatch[];
- };
- web_result_block?: {
- web_results?: Array<{ url?: string; name?: string; snippet?: string }>;
- };
- plan_block?: {
- steps?: Array<{
- step_type?: string;
- search_web_content?: { queries?: Array<{ query?: string }> };
- read_results_content?: { urls?: string[] };
- }>;
- goals?: Array<{ description?: string }>;
- };
-}
-
-export interface PplxStreamEvent {
- status?: string;
- final?: boolean;
- text?: string;
- blocks?: PplxBlock[];
- backend_uuid?: string;
- web_results?: Array<{ url?: string; name?: string }>;
- error_code?: string;
- error_message?: string;
- display_model?: string;
-}
-
-// ─── SSE parsing ────────────────────────────────────────────────────────────
-
-export async function* readPplxSseEvents(
- body: ReadableStream<Uint8Array>,
- signal?: AbortSignal | null
-): AsyncGenerator<PplxStreamEvent> {
- const reader = body.getReader();
- const decoder = new TextDecoder();
- let buffer = "";
- let dataLines: string[] = [];
-
- function flush(): PplxStreamEvent | null | "done" {
- if (dataLines.length === 0) return null;
- const payload = dataLines.join("\n");
- dataLines = [];
- const trimmed = payload.trim();
- if (!trimmed || trimmed === "[DONE]") return "done";
- try {
- return JSON.parse(trimmed) as PplxStreamEvent;
- } catch {
- return null;
- }
- }
-
- try {
- while (true) {
- if (signal?.aborted) return;
- const { value, done } = await reader.read();
- if (done) break;
- buffer += decoder.decode(value, { stream: true });
-
- while (true) {
- const idx = buffer.indexOf("\n");
- if (idx < 0) break;
- const rawLine = buffer.slice(0, idx);
- buffer = buffer.slice(idx + 1);
- const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
-
- if (line === "") {
- const parsed = flush();
- if (parsed === "done") return;
- if (parsed) yield parsed;
- continue;
- }
- if (line.startsWith("data:")) {
- dataLines.push(line.slice(5).trimStart());
- }
- if (line === "event: end_of_stream") {
- return;
- }
- }
- }
-
- buffer += decoder.decode();
- if (buffer.trim().startsWith("data:")) {
- dataLines.push(buffer.trim().slice(5).trimStart());
- }
- const tail = flush();
- if (tail && tail !== "done") yield tail;
- } finally {
- reader.releaseLock();
- }
-}
-
-// ─── OpenAI → Perplexity translation ────────────────────────────────────────
-
-export interface ParsedMessages {
- systemMsg: string;
- history: Array<{ role: string; content: string }>;
- currentMsg: string;
-}
-
-export function parseOpenAIMessages(messages: Array<Record<string, unknown>>): ParsedMessages {
- let systemMsg = "";
- const history: Array<{ role: string; content: string }> = [];
-
- for (const msg of messages) {
- let role = String(msg.role || "user");
- if (role === "developer") role = "system";
-
- let content = "";
- if (typeof msg.content === "string") {
- content = msg.content;
- } else if (Array.isArray(msg.content)) {
- content = (msg.content as Array<Record<string, unknown>>)
- .filter((c) => c.type === "text")
- .map((c) => String(c.text || ""))
- .join(" ");
- }
- if (!content.trim()) continue;
-
- if (role === "system") {
- systemMsg += content + "\n";
- } else if (role === "user" || role === "assistant") {
- history.push({ role, content });
- }
- }
-
- let currentMsg = "";
- if (history.length > 0 && history[history.length - 1].role === "user") {
- currentMsg = history.pop()!.content;
- }
-
- return { systemMsg, history, currentMsg };
-}
-
-export function buildPplxRequestBody(
- query: string,
- dslQuery: string,
- mode: string,
- modelPref: string,
- followUpUuid: string | null,
- requestId: string
-): Record<string, unknown> {
- const tz = typeof Intl !== "undefined" ? Intl.DateTimeFormat().resolvedOptions().timeZone : "UTC";
-
- // Mirrors the current www.perplexity.ai/rest/sse/perplexity_ask request body. Perplexity's
- // schematized API validates this shape; an outdated version or missing required fields → HTTP 400.
- const params: Record<string, unknown> = {
- attachments: [],
- language: "en-US",
- timezone: tz,
- search_focus: "internet",
- sources: ["web"],
- frontend_uuid: requestId,
- mode,
- model_preference: modelPref,
- is_related_query: false,
- is_sponsored: false,
- frontend_context_uuid: crypto.randomUUID(),
- prompt_source: "user",
- query_source: "home",
- is_incognito: true,
- local_search_enabled: false,
- use_schematized_api: true,
- send_back_text_in_streaming_api: false,
- supported_block_use_cases: PPLX_SUPPORTED_BLOCK_USE_CASES,
- client_coordinates: null,
- mentions: [],
- dsl_query: dslQuery && dslQuery.trim() ? dslQuery : query,
- skip_search_enabled: true,
- is_nav_suggestions_disabled: false,
- source: "default",
- always_search_override: false,
- override_no_search: false,
- client_search_results_cache_key: requestId,
- should_ask_for_mcp_tool_confirmation: true,
- browser_agent_allow_once_from_toggle: false,
- force_enable_browser_agent: false,
- supported_features: ["browser_agent_permission_banner_v1.1"],
- extended_context: false,
- version: PPLX_API_VERSION,
- rum_session_id: crypto.randomUUID(),
- };
-
- // Only present on follow-ups (matches the browser, which omits it for a fresh query).
- if (followUpUuid) {
- params.last_backend_uuid = followUpUuid;
- }
-
- return {
- query_str: query,
- params,
- };
-}
-
-export function buildQuery(parsed: ParsedMessages, followUpUuid: string | null): string {
- if (followUpUuid) return parsed.currentMsg;
-
- const obj: Record<string, unknown> = {};
- if (parsed.systemMsg.trim()) {
- obj.instructions = [
- parsed.systemMsg.trim(),
- "You have built-in web search. Answer questions directly using search results.",
- ];
- }
- if (parsed.history.length > 0) {
- obj.history = parsed.history;
- }
- if (parsed.currentMsg) {
- obj.query = parsed.currentMsg;
- } else if (parsed.history.length === 0) {
- obj.query = "";
- }
- const json = JSON.stringify(obj);
- return json.length > 96000 ? json.slice(-96000) : json;
-}
-
-// ─── Content extraction ─────────────────────────────────────────────────────
-
-export interface ContentChunk {
- delta?: string;
- answer?: string;
- backendUuid?: string;
- thinking?: string;
- error?: string;
- done?: boolean;
-}
-
-// The schematized API delivers the answer text in blocks whose `intended_usage`
-// is either the aggregate `ask_text` or per-segment `ask_text_<n>_markdown`
-// (older builds used names merely containing "markdown"). All converge on the
-// same answer, so we lock onto a single primary usage to avoid double-counting.
-export function isAnswerTextUsage(usage: string): boolean {
- return (
- usage === "ask_text" || /^ask_text_\d+_markdown$/.test(usage) || usage.includes("markdown")
- );
-}
-
-// Reconstructed state for one answer-text block, built up from diff patches
-// (streaming) or a materialized markdown_block (final COMPLETED frame).
-export interface MarkdownAccumulator {
- chunks: string[];
-}
-
-// Apply a markdown_block diff_block patch set. Perplexity sends an initial
-// `{op:"replace", path:"", value:{chunks:[...]}}` then incremental
-// `{op:"add", path:"/chunks/<n>", value:"..."}` frames. We only need the
-// chunks array; joining it yields the cumulative answer text.
-export function applyMarkdownDiff(acc: MarkdownAccumulator, patches: PplxDiffPatch[]): void {
- for (const patch of patches) {
- const path = patch.path ?? "";
- if (path === "") {
- const value = (patch.value ?? {}) as { chunks?: unknown };
- acc.chunks = Array.isArray(value.chunks) ? value.chunks.map((c) => String(c)) : [];
- continue;
- }
- const chunkMatch = /^\/chunks\/(\d+)$/.exec(path);
- if (chunkMatch && typeof patch.value === "string") {
- const idx = Number.parseInt(chunkMatch[1], 10);
- acc.chunks[idx] = patch.value;
- }
- }
-}
-
-export async function* extractContent(
- eventStream: ReadableStream<Uint8Array>,
- signal?: AbortSignal | null
-): AsyncGenerator<ContentChunk> {
- let fullAnswer = "";
- let backendUuid: string | null = null;
- let seenLen = 0;
- const seenThinking = new Set<string>();
- // Per-usage reconstructed answer-text blocks + the locked primary usage.
- const mdState = new Map<string, MarkdownAccumulator>();
- let primaryUsage: string | null = null;
-
- for await (const event of readPplxSseEvents(eventStream, signal)) {
- if (event.error_code || event.error_message) {
- yield {
- error: event.error_message || `Perplexity error: ${event.error_code}`,
- done: true,
- };
- return;
- }
-
- if (event.backend_uuid) backendUuid = event.backend_uuid;
-
- const blocks = event.blocks ?? [];
- for (const block of blocks) {
- const usage = block.intended_usage ?? "";
-
- // Thinking: search steps
- if (usage === "pro_search_steps" && block.plan_block?.steps) {
- for (const step of block.plan_block.steps) {
- if (step.step_type === "SEARCH_WEB") {
- for (const q of step.search_web_content?.queries ?? []) {
- const qr = q.query ?? "";
- if (qr && !seenThinking.has(qr)) {
- seenThinking.add(qr);
- yield { thinking: `Searching: ${qr}`, backendUuid: backendUuid ?? undefined };
- }
- }
- } else if (step.step_type === "READ_RESULTS") {
- for (const u of (step.read_results_content?.urls ?? []).slice(0, 3)) {
- if (u && !seenThinking.has(u)) {
- seenThinking.add(u);
- yield { thinking: `Reading: ${u}`, backendUuid: backendUuid ?? undefined };
- }
- }
- }
- }
- }
-
- // Thinking: plan goals
- if (usage === "plan" && block.plan_block?.goals) {
- for (const goal of block.plan_block.goals) {
- const desc = goal.description ?? "";
- if (desc && !seenThinking.has(desc)) {
- seenThinking.add(desc);
- yield { thinking: desc, backendUuid: backendUuid ?? undefined };
- }
- }
- }
-
- // Content: answer-text blocks (schematized diff frames OR materialized
- // markdown_block on the final COMPLETED frame).
- if (!isAnswerTextUsage(usage)) continue;
- let acc = mdState.get(usage);
- if (!acc) {
- acc = { chunks: [] };
- mdState.set(usage, acc);
- }
-
- if (block.diff_block && Array.isArray(block.diff_block.patches)) {
- applyMarkdownDiff(acc, block.diff_block.patches);
- } else if (block.markdown_block) {
- const mb = block.markdown_block;
- if (Array.isArray(mb.chunks) && mb.chunks.length > 0) {
- acc.chunks = mb.chunks.map((c) => String(c));
- } else if (typeof mb.answer === "string" && mb.answer.length > 0) {
- acc.chunks = [mb.answer];
- }
- }
-
- // Prefer the aggregate `ask_text` block; otherwise lock the first seen.
- if (usage === "ask_text") {
- primaryUsage = "ask_text";
- } else if (!primaryUsage) {
- primaryUsage = usage;
- }
- }
-
- // Emit at most one content delta per event, from the locked primary usage.
- if (primaryUsage) {
- const currentAnswer = (mdState.get(primaryUsage)?.chunks ?? []).join("");
- if (currentAnswer.length > seenLen) {
- const delta = currentAnswer.slice(seenLen);
- fullAnswer = currentAnswer;
- seenLen = currentAnswer.length;
- yield { delta, answer: fullAnswer, backendUuid: backendUuid ?? undefined };
- }
- }
-
- // Legacy fallback: a plain non-JSON `text` field with no structured blocks.
- // The schematized API's `text` field is a JSON step-blob (not user-facing),
- // so only use it when there are no answer-text blocks at all.
- if (!primaryUsage && blocks.length === 0 && event.text) {
- const t = event.text.trim();
- const looksLikeJson = t.startsWith("{") || t.startsWith("[");
- if (!looksLikeJson && t.length > seenLen) {
- const delta = t.slice(seenLen);
- fullAnswer = t;
- seenLen = t.length;
- yield { delta, answer: fullAnswer, backendUuid: backendUuid ?? undefined };
- }
- }
-
- // Only stop on the terminal COMPLETED frame. A `final:true` flag can appear
- // on a still-PENDING frame BEFORE the COMPLETED frame that materializes the
- // full markdown_block — breaking on `final` there drops the answer.
- if (event.status === "COMPLETED") break;
- }
-
- yield { delta: "", answer: fullAnswer, backendUuid: backendUuid ?? undefined, done: true };
-}
-
-// ─── OpenAI SSE format ──────────────────────────────────────────────────────
-
-export function sseChunk(data: unknown): string {
- return `data: ${JSON.stringify(data)}\n\n`;
-}
diff --git a/open-sse/executors/qoder.ts b/open-sse/executors/qoder.ts
index 62ac641e90..f52faad70c 100644
--- a/open-sse/executors/qoder.ts
+++ b/open-sse/executors/qoder.ts
@@ -10,17 +10,8 @@ import {
getQoderDashscopeCompatHeaders,
QODER_DEFAULT_USER_AGENT,
} from "../config/providerHeaderProfiles.ts";
-import { randomUUID } from "node:crypto";
import { sanitizeQwenThinkingToolChoice } from "../services/qwenThinking.ts";
-import {
- buildQoderChunk,
- buildQoderCompletionPayload,
- buildQoderPrompt,
- createQoderErrorResponse,
- parseQoderCliFailure,
- parseQoderCliResult,
- runQoderCli,
-} from "../services/qoderCli.ts";
+import { buildCosyHeadersForValidation, resolveQoderJobToken } from "../services/qoderCli.ts";
import { sanitizeErrorMessage } from "../utils/error.ts";
function truncate(text: string, max: number): string {
@@ -28,33 +19,6 @@ function truncate(text: string, max: number): string {
return `${text.slice(0, max)}…`;
}
-/**
- * Wrap a full qodercli reply as an OpenAI-compatible SSE stream (role chunk →
- * content chunk → stop chunk → [DONE]). qodercli's `--print` mode returns the
- * whole answer at once, so there are no incremental deltas to forward.
- */
-function buildQoderCliSseStream(model: string, text: string): ReadableStream<Uint8Array> {
- const id = `chatcmpl-${randomUUID()}`;
- const created = Math.floor(Date.now() / 1000);
- const encoder = new TextEncoder();
- const send = (obj: unknown) => encoder.encode(`data: ${JSON.stringify(obj)}\n\n`);
- return new ReadableStream<Uint8Array>({
- start(controller) {
- controller.enqueue(
- send(buildQoderChunk({ id, model, created, delta: { role: "assistant", content: "" } }))
- );
- if (text) {
- controller.enqueue(send(buildQoderChunk({ id, model, created, delta: { content: text } })));
- }
- controller.enqueue(
- send(buildQoderChunk({ id, model, created, delta: {}, finishReason: "stop" }))
- );
- controller.enqueue(encoder.encode("data: [DONE]\n\n"));
- controller.close();
- },
- });
-}
-
/**
* Peek at the first SSE event from a Qoder response to detect upstream errors
* that Qoder wraps inside an HTTP 200 SSE envelope ({statusCodeValue, body}).
@@ -210,23 +174,22 @@ export class QoderExecutor extends BaseExecutor {
const resolvedModel = model || "qwen3-coder-plus";
- // Detect token type: PAT (Personal Access Token) starts with "pt-".
- // PATs are driven through the local qodercli binary (see executeViaQoderCli);
- // only the qodercli binary can produce the WASM-signed Cosy request the raw
- // HTTP path can no longer replicate.
+ // Detect token type: PAT (Personal Access Token) starts with "pt-"
const isPatToken = token.startsWith("pt-");
- if (isPatToken) {
- return this.executeViaQoderCli({ model: resolvedModel, body, stream, token, signal });
- }
- // Non-PAT tokens (OAuth apiKey / DashScope key) → DashScope OpenAI-compatible API.
let mappedModel = resolvedModel;
- if (resolvedModel === "qwen3.5-plus" || resolvedModel === "qwen3.6-plus") {
- mappedModel = "coder-model";
- } else if (resolvedModel === "vision-model") {
- mappedModel = "qwen3-vl-plus";
+ let endpointUrl: string;
+
+ if (isPatToken) {
+ endpointUrl = "https://api.qoder.com/v1/chat/completions";
+ } else {
+ if (resolvedModel === "qwen3.5-plus" || resolvedModel === "qwen3.6-plus") {
+ mappedModel = "coder-model";
+ } else if (resolvedModel === "vision-model") {
+ mappedModel = "qwen3-vl-plus";
+ }
+ endpointUrl = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";
}
- let endpointUrl = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";
// Check for custom API base via credentials (overrides the default)
let credentialsApiBase: unknown;
@@ -244,23 +207,91 @@ export class QoderExecutor extends BaseExecutor {
const headers: Record<string, string> = {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
- ...getQoderDashscopeCompatHeaders(),
+ ...(isPatToken ? {} : getQoderDashscopeCompatHeaders()),
};
mergeUpstreamExtraHeaders(headers, upstreamExtraHeaders);
- const payload = this.transformRequest(mappedModel, body);
+ const payload = this.transformRequest(mappedModel, body, stream, credentials);
const bodyStr = JSON.stringify(payload);
try {
- const response = await fetch(endpointUrl, {
+ let response = await fetch(endpointUrl, {
method: "POST",
headers,
body: bodyStr,
signal,
});
+ // PAT tokens (pt-*) are not accepted as Bearer tokens by api.qoder.com/v1/chat/completions.
+ // They return 401 TOKEN_INVALID. Fallback to Cosy auth against api1.qoder.sh.
+ if (!response.ok && response.status === 401 && isPatToken) {
+ // #4683: exchange the PAT (pt-*) for a job token (jt-*) before the Cosy call;
+ // Cosy rejects a raw pt-* in security_oauth_token with a generic 500.
+ const cosyToken = await resolveQoderJobToken(token, { signal });
+ const cosyHeaders = buildCosyHeadersForValidation(bodyStr, cosyToken);
+ const cosyEndpoint =
+ "https://api1.qoder.sh/algo/api/v2/service/pro/sse/agent_chat_generation?AgentId=agent_common";
+ const cosyRes = await fetch(cosyEndpoint, {
+ method: "POST",
+ headers: cosyHeaders,
+ body: bodyStr,
+ signal,
+ });
+
+ if (cosyRes.ok || cosyRes.status === 200) {
+ // Cosy SSE response - read full body and parse
+ const rawText = await cosyRes.text();
+ const lines = rawText.split("\n").filter((l) => l.startsWith("data: "));
+ let fullContent = "";
+ for (const line of lines) {
+ try {
+ const jsonData = JSON.parse(line.slice(6));
+ const { extractTextFromQoderEnvelope } = await import("../services/qoderCli.ts");
+ const chunkText = extractTextFromQoderEnvelope(jsonData);
+ if (chunkText) fullContent += chunkText;
+ } catch {
+ // skip unparseable chunks
+ }
+ }
+ const { buildQoderCompletionPayload } = await import("../services/qoderCli.ts");
+ const cosyPayload = buildQoderCompletionPayload({
+ model: mappedModel || resolvedModel,
+ text: fullContent,
+ });
+ return {
+ response: new Response(JSON.stringify(cosyPayload), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }),
+ url: cosyEndpoint,
+ headers: cosyHeaders,
+ transformedBody: payload,
+ };
+ }
+
+ // Cosy also failed - return the original 401 error
+ let errText = await cosyRes.text();
+ return {
+ response: new Response(
+ JSON.stringify({
+ error: {
+ message:
+ `Qoder API (Cosy) failed with status ${cosyRes.status}: ${errText}. Your PAT token may not be valid for the chat API.` +
+ " Try using an OAuth token or a different auth method.",
+ type: "authentication_error",
+ code: "token_invalid",
+ },
+ }),
+ { status: 401, headers: { "Content-Type": "application/json" } }
+ ),
+ url: cosyEndpoint,
+ headers: cosyHeaders,
+ transformedBody: payload,
+ };
+ }
+
if (!response.ok) {
let errText = await response.text();
return {
@@ -310,102 +341,6 @@ export class QoderExecutor extends BaseExecutor {
};
}
}
-
- /**
- * Drive a PAT (`pt-*`) completion through the local qodercli binary. The CLI
- * performs Qoder's WASM-signed Cosy auth internally, so this is the only path
- * that works for PATs now that the pure-HTTP Cosy reimplementation is dead.
- */
- private async executeViaQoderCli({
- model,
- body,
- stream,
- token,
- signal,
- }: {
- model: string;
- body: unknown;
- stream: boolean;
- token: string;
- signal?: AbortSignal | null;
- }): Promise<{
- response: Response;
- url: string;
- headers: Record<string, string>;
- transformedBody: unknown;
- }> {
- const url = "qodercli://stdio";
- const prompt = buildQoderPrompt(body);
-
- const run = await runQoderCli({ token, prompt, stream: false, model, signal });
-
- // Honor client cancellation the same way the HTTP path does.
- if (signal?.aborted) {
- const abortError = new Error("Aborted");
- abortError.name = "AbortError";
- throw abortError;
- }
-
- if (run.error && /enoent|not found|no such file|spawn/i.test(run.error)) {
- return {
- response: createQoderErrorResponse({
- status: 502,
- message:
- `Qoder CLI (qodercli) was not found on the OmniRoute host (${run.error}). ` +
- "Install it from https://qoder.com or set CLI_QODER_BIN to its path.",
- code: "cli_not_found",
- }),
- url,
- headers: {},
- transformedBody: body,
- };
- }
-
- if (!run.ok) {
- return {
- response: createQoderErrorResponse(parseQoderCliFailure(run.stderr, run.stdout)),
- url,
- headers: {},
- transformedBody: body,
- };
- }
-
- const { text, isError, errorMessage } = parseQoderCliResult(run.stdout);
- if (isError) {
- return {
- response: createQoderErrorResponse(parseQoderCliFailure(errorMessage)),
- url,
- headers: {},
- transformedBody: body,
- };
- }
-
- if (stream) {
- return {
- response: new Response(buildQoderCliSseStream(model, text), {
- status: 200,
- headers: {
- "Content-Type": "text/event-stream",
- "Cache-Control": "no-cache",
- Connection: "keep-alive",
- },
- }),
- url,
- headers: {},
- transformedBody: body,
- };
- }
-
- return {
- response: new Response(JSON.stringify(buildQoderCompletionPayload({ model, text })), {
- status: 200,
- headers: { "Content-Type": "application/json" },
- }),
- url,
- headers: {},
- transformedBody: body,
- };
- }
}
export default QoderExecutor;
diff --git a/open-sse/executors/qwen-web.ts b/open-sse/executors/qwen-web.ts
index 485eb93758..a61072d283 100644
--- a/open-sse/executors/qwen-web.ts
+++ b/open-sse/executors/qwen-web.ts
@@ -58,9 +58,7 @@ const MODEL_ALIASES: Record<string, string> = {
"qwen3-plus": "qwen3.7-plus",
"qwen3-max": "qwen3.7-max",
"qwen3-flash": "qwen3.6-plus",
- // Note: `qwen3-coder-plus` is a real upstream model id (Qwen3-Coder) and
- // must NOT be aliased — the previous `"qwen3-coder-plus": "qwen3.7-max"`
- // entry silently rewrote valid coder requests to the wrong model.
+ "qwen3-coder-plus": "qwen3.7-max",
"qwen3-coder-flash": "qwen3.6-plus",
qwen: "qwen3.7-max",
qwen3: "qwen3.7-max",
diff --git a/open-sse/executors/theoldllm.ts b/open-sse/executors/theoldllm.ts
index 64e985b96c..46804cdf77 100644
--- a/open-sse/executors/theoldllm.ts
+++ b/open-sse/executors/theoldllm.ts
@@ -39,44 +39,7 @@ const CLAUDE_NAMES: Record<string, string> = {
"claude haiku 3.5": "CLAUDE_4_5_HAIKU",
};
-// Canonical upstream model IDs served by theoldllm's /api/chatgpt proxy
-// (apiProvider "chatgpt" in the site's model catalog — the free, reachable tier).
-// Source: https://theoldllm.vercel.app model list (reported in #5181).
-// These pass through mapModel() UNCHANGED — critical for non-GPT/Claude models
-// (Gemini, o-series, Grok, DeepSeek, Sonar) which would otherwise fall through
-// to the GPT_5_4 default and silently misroute.
-export const CHATGPT_UPSTREAM_MODELS: ReadonlySet<string> = new Set<string>([
- "GPT_5_4",
- "GPT_5_3",
- "GPT_5_2",
- "GPT_5_1",
- "GPT_5",
- "GPT_o4_mini",
- "GPT_o3_mini",
- "gemini_3_pro",
- "gemini_2_5_pro",
- "gemini_2_0_flash",
- "gemini_1_5_flash",
- "CLAUDE_4_6_OPUS",
- "CLAUDE_4_6_SONNET",
- "CLAUDE_4_5_HAIKU",
- "openrouter_gpt_4_o",
- "openrouter_gpt_4_o_mini",
- "openrouter_gpt_4",
- "openrouter_grok_4",
- "together_deepseek_r1",
- "openrouter_deepseek_r1",
- "together_deepseek_v3",
- "openrouter_deepseek_v3",
- "sonar-deep-research",
- "sonar-pro",
- "openrouter_web_search",
-]);
-
-export function mapModel(model: string): string {
- const trimmed = model.trim();
- // Known upstream IDs (from live discovery / refreshed catalog) route as-is.
- if (CHATGPT_UPSTREAM_MODELS.has(trimmed)) return trimmed;
+function mapModel(model: string): string {
const n = model.toLowerCase().trim();
const gptKey = n.replace(/[_\s]+/g, "-");
if (GPT_MODELS[gptKey]) return GPT_MODELS[gptKey];
diff --git a/open-sse/executors/xai.ts b/open-sse/executors/xai.ts
deleted file mode 100644
index 9f806e2c5a..0000000000
--- a/open-sse/executors/xai.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-import { BaseExecutor, type ProviderCredentials } from "./base.ts";
-import { PROVIDERS } from "../config/constants.ts";
-
-type JsonRecord = Record<string, unknown>;
-
-/**
- * xAI/Grok model ids (open-sse/config/providers/registry/xai/index.ts) that accept
- * a graduated `reasoning_effort`. Kept narrow and reconciled against the REAL
- * catalog rather than upstream's example ids (grok-4/grok-3 do not exist here):
- * - grok-4.3 — current-generation flagship, reasoning-capable.
- * - grok-4.20-0309-reasoning — explicit reasoning variant.
- *
- * grok-4.20-multi-agent-0309 is intentionally left unclassified (neither allow
- * nor deny): its reasoning support is not documented in the local catalog, so
- * we pass it through unchanged rather than guess.
- */
-const REASONING_ALLOWED = ["grok-4.3", "grok-4.20-0309-reasoning"];
-
-/**
- * Model ids that reject `reasoning_effort` outright:
- * - grok-build-0.1 — build/tool-oriented model, no reasoning mode.
- * - grok-4.20-0309-non-reasoning — already encodes "no reasoning" in the id;
- * forwarding reasoning_effort here would be redundant/rejected upstream.
- */
-const REASONING_DENIED = ["grok-build-0.1", "grok-4.20-0309-non-reasoning"];
-
-/** `-{level}` suffixes some clients append to a model id to select reasoning intensity. */
-const EFFORT_SUFFIXES = ["low", "medium", "high", "xhigh"] as const;
-
-function asRecord(value: unknown): JsonRecord | null {
- return value && typeof value === "object" && !Array.isArray(value) ? (value as JsonRecord) : null;
-}
-
-/**
- * xAI/Grok executor (port of decolua/9router#2147).
- *
- * Some Grok clients select reasoning intensity via a `-{low,medium,high,xhigh}`
- * suffix on the model id (e.g. `grok-4.3-high`) rather than a native
- * `reasoning_effort` field — xAI itself does not recognize the suffixed id.
- * This executor:
- * 1. Parses and strips that suffix off the model id before the request
- * reaches xAI, mapping it to `reasoning_effort` for allow-listed models.
- * 2. Strips any `reasoning_effort` for deny-listed models — including ids
- * that already encode their reasoning state in the name (`-reasoning` /
- * `-non-reasoning`), which must not be double-mutated by also stacking a
- * `reasoning_effort` field on top of what the id already declares.
- * 3. Leaves unclassified models and bodies untouched otherwise.
- */
-export class XaiExecutor extends BaseExecutor {
- constructor() {
- super("xai", PROVIDERS.xai);
- }
-
- transformRequest(
- model: string,
- body: unknown,
- stream: boolean,
- credentials: ProviderCredentials
- ): unknown {
- const cleaned = super.transformRequest(model, body, stream, credentials);
- const record = asRecord(cleaned);
- if (!record) return cleaned;
-
- const out: JsonRecord = { ...record };
- let modelId = typeof out.model === "string" ? out.model : model;
-
- let suffixEffort: string | null = null;
- for (const level of EFFORT_SUFFIXES) {
- const suffix = `-${level}`;
- if (modelId.endsWith(suffix)) {
- suffixEffort = level;
- modelId = modelId.slice(0, -suffix.length);
- break;
- }
- }
- if (suffixEffort && typeof out.model === "string") {
- out.model = modelId;
- }
-
- const isDenied = REASONING_DENIED.some((id) => modelId.includes(id));
- const isAllowed = REASONING_ALLOWED.some((id) => modelId.includes(id));
-
- if (isDenied) {
- delete out.reasoning_effort;
- } else if (isAllowed) {
- const effort = suffixEffort || out.reasoning_effort;
- if (effort) out.reasoning_effort = effort;
- }
-
- return out;
- }
-}
-
-export default XaiExecutor;
diff --git a/open-sse/handlers/audioTranslation.ts b/open-sse/handlers/audioTranslation.ts
deleted file mode 100644
index 7269ffb006..0000000000
--- a/open-sse/handlers/audioTranslation.ts
+++ /dev/null
@@ -1,135 +0,0 @@
-/**
- * Audio Translation Handler
- *
- * Handles POST /v1/audio/translations (Whisper translate-to-English API
- * format). Proxies multipart/form-data to upstream providers that expose an
- * OpenAI-Whisper-compatible /audio/translations endpoint.
- *
- * Unlike /v1/audio/transcriptions, translation always outputs English text
- * regardless of the source audio language, so there is no `language` input
- * field — only `model`, `file`, `prompt`, `response_format`, and
- * `temperature` are forwarded upstream.
- */
-
-import {
- getTranslationProvider,
- parseTranslationModel,
- type AudioProvider,
-} from "../config/audioRegistry.ts";
-import { buildAuthHeaders } from "../config/registryUtils.ts";
-import { buildMultipartBody } from "./audioTranscription.ts";
-import { errorResponse } from "../utils/error.ts";
-
-type TranslationCredentials = {
- apiKey?: string;
- accessToken?: string;
-};
-
-/**
- * Extract a readable error message from an upstream provider's error body.
- */
-function extractUpstreamErrorMessage(errText: string, status: number): string {
- try {
- const parsed = JSON.parse(errText);
- const raw =
- parsed?.error?.message ||
- (typeof parsed?.error === "string" ? parsed.error : null) ||
- parsed?.message ||
- null;
- return raw ? String(raw) : errText || `Upstream error (${status})`;
- } catch {
- return errText || `Upstream error (${status})`;
- }
-}
-
-/**
- * Handle audio translation request
- *
- * @param {Object} options
- * @param {FormData} options.formData - Multipart form data with file + model
- * @param {Object} options.credentials - Provider credentials { apiKey }
- * @returns {Response}
- */
-export async function handleAudioTranslation({
- formData,
- credentials,
- resolvedProvider = null,
- resolvedModel = null,
-}: {
- formData: FormData;
- credentials?: TranslationCredentials | null;
- resolvedProvider?: AudioProvider | null;
- resolvedModel?: string | null;
-}): Promise<Response> {
- const model = formData.get("model");
- if (typeof model !== "string" || !model) {
- return errorResponse(400, "model is required");
- }
-
- const fileEntry = formData.get("file");
- if (!(fileEntry instanceof Blob)) {
- return errorResponse(400, "file is required");
- }
- const file = fileEntry as Blob & { name?: unknown };
-
- // Use pre-resolved provider/model from route handler if available.
- let providerConfig = resolvedProvider;
- let modelId = resolvedModel;
- if (!providerConfig) {
- const parsed = parseTranslationModel(model);
- providerConfig = parsed.provider ? getTranslationProvider(parsed.provider) : null;
- modelId = parsed.model;
- }
-
- if (!providerConfig) {
- return errorResponse(
- 400,
- `No translation provider found for model "${model}". Available: openai, groq`
- );
- }
-
- const token =
- providerConfig.authType === "none" ? null : credentials?.apiKey || credentials?.accessToken;
- if (providerConfig.authType !== "none" && !token) {
- return errorResponse(401, `No credentials for translation provider: ${providerConfig.id}`);
- }
-
- // OpenAI Whisper translate-to-English params — no `language`, output is
- // always English regardless of the source audio language.
- const extraFields: Record<string, string> = {};
- for (const key of ["prompt", "response_format", "temperature"]) {
- const val = formData.get(key);
- if (val !== null && val !== undefined) {
- extraFields[key] = String(val);
- }
- }
-
- const { body: multipartBody, contentType: multipartCT } = await buildMultipartBody(file, {
- model: modelId as string,
- ...extraFields,
- });
-
- try {
- const res = await fetch(providerConfig.baseUrl, {
- method: "POST",
- headers: { ...buildAuthHeaders(providerConfig, token), "Content-Type": multipartCT },
- body: multipartBody,
- });
-
- if (!res.ok) {
- const errText = await res.text();
- return errorResponse(res.status, extractUpstreamErrorMessage(errText, res.status));
- }
-
- const data = await res.text();
- const respContentType = res.headers.get("content-type") || "application/json";
-
- return new Response(data, {
- status: 200,
- headers: { "Content-Type": respContentType },
- });
- } catch (err) {
- const error = err instanceof Error ? err : new Error(String(err));
- return errorResponse(500, `Translation request failed: ${error.message}`);
- }
-}
diff --git a/open-sse/handlers/chatCore.ts b/open-sse/handlers/chatCore.ts
index 45a58c3f57..4535402de7 100644
--- a/open-sse/handlers/chatCore.ts
+++ b/open-sse/handlers/chatCore.ts
@@ -5,10 +5,6 @@ import { extractSystemRoleMessages } from "./chatCore/claudeSystemRole.ts";
export { extractSystemRoleMessages } from "./chatCore/claudeSystemRole.ts";
import { checkIdempotencyCache } from "./chatCore/idempotency.ts";
import { checkSemanticCache } from "./chatCore/semanticCache.ts";
-import {
- shouldDefaultAllowClassifier,
- buildDefaultAllowClaudeMessage,
-} from "./chatCore/claudeClassifierCompat.ts";
import { applyClientUsageBuffer } from "./chatCore/clientUsageBuffer.ts";
import { buildPostCallGuardrailContext } from "./chatCore/postCallGuardrailContext.ts";
import { storeSemanticCacheResponse } from "./chatCore/semanticCacheStore.ts";
@@ -26,7 +22,6 @@ import {
isStripReasoningRequested,
} from "./chatCore/headers.ts";
import { markCodexScopeRateLimited } from "./chatCore/codexFailover.ts";
-import { trackDevice, extractIpFromHeaders } from "../services/deviceTracker.ts";
import { getCombosCached } from "./chatCore/comboContextCache.ts";
export { clearCombosCache, clearUpstreamProxyConfigCache } from "./chatCore/comboContextCache.ts";
import {
@@ -217,7 +212,6 @@ import {
type NonStreamingSseTerminalState,
} from "./chatCore/nonStreamingSse.ts";
import { parseNonStreamingResponseBody } from "./chatCore/nonStreamingResponseParse.ts";
-import { unwrapClinepassEnvelope } from "../utils/clinepassEnvelope.ts";
import { recordNonStreamingUsageStats } from "./chatCore/nonStreamingUsageStats.ts";
import {
createBodyTimeoutError,
@@ -252,7 +246,6 @@ import { isCompactResponsesEndpoint } from "../executors/codex.ts";
import { buildCodexQuotaPersistence } from "./chatCore/codexQuota.ts";
import { invalidateCodexQuotaCache } from "../services/codexQuotaFetcher.ts";
import { translateNonStreamingResponse } from "./responseTranslator.ts";
-import { unwrapClineNonStreamingEnvelope } from "./chatCore/clineResponseEnvelope.ts";
import { extractUsageFromResponse } from "./usageExtractor.ts";
import {
sanitizeOpenAIResponse,
@@ -461,15 +454,6 @@ export async function handleChatCore({
if (pluginGate.body) {
body = pluginGate.body;
}
- // Per-API-key device/connection tracking (port of upstream 9router#931,
- // thanks @mugnimaestra). In-memory only, never blocks the request path.
- if (apiKeyInfo?.id) {
- trackDevice(
- apiKeyInfo.id,
- extractIpFromHeaders(clientRawRequest?.headers ?? null),
- userAgent ?? null
- );
- }
const agentGoalPolicy = resolveAgentGoalPolicy(body, clientRawRequest?.headers ?? null);
if (agentGoalPolicy.detected) {
log?.debug?.(
@@ -593,30 +577,6 @@ export async function handleChatCore({
return bypassResponse;
}
- // ── Claude Code auto-mode classifier compat (opt-in, default "off") ──
- // Claude Code's `--permission-mode auto` sends an internal classifier request that
- // requires the response to START with `<block>no</block>`/`<block>yes</block>`.
- // When a combo/fallback route sends that call to a cheap model returning 200 with
- // empty content, Claude Code fails closed on every gated action. Detect the
- // classifier request and short-circuit with a synthetic ALLOW response, WITHOUT
- // calling the upstream provider. See chatCore/claudeClassifierCompat.ts.
- {
- const classifierSettings = cachedSettings ?? (await getCachedSettings());
- if (
- shouldDefaultAllowClassifier(
- sourceFormat,
- body as Record<string, unknown>,
- classifierSettings.claudeClassifierCompat as string | undefined
- )
- ) {
- log?.warn?.(
- "CHAT",
- `classifier compat=${classifierSettings.claudeClassifierCompat} | short-circuit default-allow`
- );
- return buildDefaultAllowClaudeMessage(requestedModel);
- }
- }
-
// Detect source format and get target format
// Model-specific targetFormat takes priority over provider default
@@ -3557,64 +3517,6 @@ export async function handleChatCore({
let responseBody = parsed.responseBody;
let responsePayloadFormat = parsed.responsePayloadFormat;
- // ── ClinePass {success,data} envelope unwrap (before translation) ──────────
- // ClinePass wraps non-streaming JSON in a {success, data} envelope; errors
- // use {success:false, error}. Transient {success:false, error:"empty..."}
- // responses get one 2s retry before surfacing. CLINEPASS-GATED — untouched
- // for every other provider. Envelope errors route through createErrorResult
- // (→ buildErrorBody/sanitizeErrorMessage, Rule #12).
- if (provider === "clinepass") {
- let { body: unwrapped, error: envError } = unwrapClinepassEnvelope(responseBody, provider);
- if (envError && /empty/i.test(envError.message || "")) {
- log?.warn?.("RETRY", "clinepass returned empty content, retrying once after 2s");
- await new Promise((r) => setTimeout(r, 2000));
- try {
- const retryResult = await executeProviderRequest(effectiveModel, false);
- if (retryResult?.response?.ok) {
- const retryParsed = await parseNonStreamingResponseBody({
- providerResponse: retryResult.response,
- upstreamStream: undefined,
- providerHeaders: retryResult.headers,
- finalBody: retryResult.transformedBody,
- targetFormat,
- model,
- log,
- });
- if (retryParsed.kind !== "invalid_sse" && retryParsed.kind !== "invalid_json") {
- providerResponse = retryResult.response;
- providerUrl = retryResult.url;
- providerHeaders = retryResult.headers;
- finalBody = providerRequestCapture.body(retryResult.transformedBody);
- ({ body: unwrapped, error: envError } = unwrapClinepassEnvelope(
- retryParsed.responseBody,
- provider
- ));
- }
- }
- } catch (retryErr) {
- log?.warn?.(
- "RETRY",
- `clinepass retry failed: ${
- retryErr instanceof Error ? retryErr.message : String(retryErr)
- }`
- );
- }
- }
- if (envError) {
- appendRequestLog({
- model,
- provider,
- connectionId,
- status: `FAILED ${HTTP_STATUS.BAD_GATEWAY}`,
- }).catch(() => {});
- persistFailureUsage(HTTP_STATUS.BAD_GATEWAY, "clinepass_envelope_error");
- trackPendingRequest(model, provider, connectionId, false);
- return createErrorResult(HTTP_STATUS.BAD_GATEWAY, envError.message);
- }
- responseBody = unwrapped;
- }
- responseBody = unwrapClineNonStreamingEnvelope(provider, responseBody);
-
// Check for empty content response (fake success) - trigger fallback
if (isEmptyContentResponse(responseBody)) {
appendRequestLog({
diff --git a/open-sse/handlers/chatCore/claudeClassifierCompat.ts b/open-sse/handlers/chatCore/claudeClassifierCompat.ts
deleted file mode 100644
index c524a7a9eb..0000000000
--- a/open-sse/handlers/chatCore/claudeClassifierCompat.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-/**
- * Claude Code auto-mode classifier compat mode (opt-in, default "off").
- *
- * Claude Code's `--permission-mode auto` sends an internal `/v1/messages`
- * security-classifier request and requires the response to START with the literal
- * token `<block>no</block>` (ALLOW) or `<block>yes</block>` (BLOCK) — anything else
- * is unparseable and Claude Code fails closed with "Auto mode could not evaluate
- * this action and is blocking it for safety".
- *
- * When a combo/fallback route sends the classifier call to a cheap model that
- * returns 200 with empty content, the well-formed-but-empty Claude message
- * OmniRoute would normally produce still fails that parser — every gated action
- * (WebFetch, Bash, Edit, …) ends up fail-closed. With `claudeClassifierCompat` set
- * to "auto" or "always", handleChatCore detects the classifier request up front
- * and short-circuits with a synthetic ALLOW response, WITHOUT ever calling the
- * upstream provider. Default is "off": nothing changes unless an operator
- * explicitly opts in (never mutates legitimate traffic by default).
- */
-
-import { FORMATS } from "../../translator/formats.ts";
-
-/** The literal system-prompt marker Claude Code's classifier request carries. */
-const SECURITY_MONITOR_MARKER = "You are a security monitor for autonomous AI coding agents";
-
-export type ClaudeClassifierCompatMode = "off" | "auto" | "always";
-
-function extractSystemTexts(body: Record<string, unknown> | null | undefined): string[] {
- const system = body?.system;
- if (typeof system === "string") return [system];
- if (Array.isArray(system)) {
- return system
- .map((part) => (part && typeof (part as { text?: unknown }).text === "string"
- ? ((part as { text: string }).text)
- : ""))
- .filter(Boolean);
- }
- return [];
-}
-
-/**
- * True when the inbound request should be default-allowed without calling upstream.
- *
- * - `mode === "off"` (default): never short-circuits.
- * - `mode === "always"`: short-circuits every Claude-format request (operator has
- * decided every `/v1/messages` call through this route is the classifier).
- * - `mode === "auto"`: only short-circuits when the request carries the classifier's
- * system-prompt marker OR lists `</block>` as a stop sequence — the two
- * independent signals Claude Code's own classifier request relies on.
- */
-export function shouldDefaultAllowClassifier(
- sourceFormat: string,
- body: Record<string, unknown> | null | undefined,
- mode: ClaudeClassifierCompatMode | string | null | undefined
-): boolean {
- if (mode !== "auto" && mode !== "always") return false;
- if (sourceFormat !== FORMATS.CLAUDE) return false;
- if (mode === "always") return true;
-
- const stopSequences = Array.isArray(body?.stop_sequences)
- ? (body!.stop_sequences as unknown[])
- : [];
- if (stopSequences.includes("</block>")) return true;
-
- return extractSystemTexts(body).some((text) => text.includes(SECURITY_MONITOR_MARKER));
-}
-
-/**
- * Build the synthetic Claude `message` ALLOW response. Always returns a plain JSON
- * body (matching the upstream reference implementation) — Claude Code's classifier
- * reads the assistant text content, not an SSE stream, so a single JSON response
- * satisfies both streaming and non-streaming callers without needing to plumb a
- * synthetic SSE encoding through the streaming/sseToJson/non-streaming handlers.
- */
-export function buildDefaultAllowClaudeMessage(model?: string | null): {
- success: true;
- response: Response;
-} {
- const message = {
- id: `msg_${globalThis.crypto.randomUUID()}`,
- type: "message",
- role: "assistant",
- model: model || "claude-3-5-sonnet-20241022",
- content: [{ type: "text", text: "<block>no</block>" }],
- stop_reason: "end_turn",
- stop_sequence: null,
- usage: { input_tokens: 1, output_tokens: 1 },
- };
-
- return {
- success: true,
- response: new Response(JSON.stringify(message), {
- status: 200,
- headers: {
- "Content-Type": "application/json",
- "anthropic-version": "2023-06-01",
- },
- }),
- };
-}
diff --git a/open-sse/handlers/chatCore/clineResponseEnvelope.ts b/open-sse/handlers/chatCore/clineResponseEnvelope.ts
deleted file mode 100644
index 0882ef3718..0000000000
--- a/open-sse/handlers/chatCore/clineResponseEnvelope.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-type JsonRecord = Record<string, unknown>;
-
-function isRecord(value: unknown): value is JsonRecord {
- return !!value && typeof value === "object" && !Array.isArray(value);
-}
-
-function hasOpenAIChoices(value: unknown): boolean {
- return isRecord(value) && Array.isArray(value.choices);
-}
-
-export function unwrapClineNonStreamingEnvelope(provider: string, responseBody: unknown): unknown {
- if (provider !== "cline" || !isRecord(responseBody)) {
- return responseBody;
- }
-
- const data = responseBody.data;
- if (!hasOpenAIChoices(data)) {
- return responseBody;
- }
-
- return {
- ...data,
- usage: isRecord(data) && data.usage !== undefined ? data.usage : responseBody.usage,
- };
-}
diff --git a/open-sse/handlers/imageGeneration.ts b/open-sse/handlers/imageGeneration.ts
index 2bfc452a0a..1e63e105bd 100644
--- a/open-sse/handlers/imageGeneration.ts
+++ b/open-sse/handlers/imageGeneration.ts
@@ -50,7 +50,6 @@ import { sanitizeErrorMessage, sanitizeUpstreamDetails } from "../utils/error.ts
// are still used by handleImageEdit below, so they are imported (not re-defined).
import { handleSDWebUIImageGeneration } from "./imageGeneration/providers/sdWebUI.ts";
import { handleHyperbolicImageGeneration } from "./imageGeneration/providers/hyperbolic.ts";
-import { handleHuggingFaceImageGeneration } from "./imageGeneration/providers/huggingface.ts";
import { handleComfyUIImageGeneration } from "./imageGeneration/providers/comfyUI.ts";
import { handleImagen3ImageGeneration } from "./imageGeneration/providers/imagen3.ts";
import { handleIdeogramImageGeneration } from "./imageGeneration/providers/ideogram.ts";
@@ -61,7 +60,6 @@ import {
extractMarkdownImageUrls,
CHATGPT_WEB_IMAGE_ID_RE,
} from "./imageGeneration/providers/chatgptWeb.ts";
-import { handleNvidiaNimImageGeneration } from "./imageGeneration/providers/nvidiaNim.ts";
interface KieImageOptions {
@@ -381,17 +379,6 @@ export async function handleImageGeneration({
});
}
- if (providerConfig.format === "huggingface-image") {
- return handleHuggingFaceImageGeneration({
- model,
- provider,
- providerConfig,
- body,
- credentials,
- log,
- });
- }
-
if (providerConfig.format === "fal-ai") {
return handleFalAIImageGeneration({
model,
@@ -524,17 +511,6 @@ export async function handleImageGeneration({
});
}
- if (providerConfig.format === "nvidia-nim") {
- return handleNvidiaNimImageGeneration({
- model,
- provider,
- providerConfig,
- body,
- credentials,
- log,
- });
- }
-
return handleOpenAIImageGeneration({ model, provider, providerConfig, body, credentials, log });
}
diff --git a/open-sse/handlers/imageGeneration/providers/huggingface.ts b/open-sse/handlers/imageGeneration/providers/huggingface.ts
deleted file mode 100644
index 7e5cad8de6..0000000000
--- a/open-sse/handlers/imageGeneration/providers/huggingface.ts
+++ /dev/null
@@ -1,90 +0,0 @@
-// HuggingFace Hub image-generation provider.
-//
-// The HF Inference API text-to-image task returns the generated image as raw
-// binary bytes (e.g. `image/jpeg`), not a JSON envelope — unlike most other
-// image providers wired in this file. Mirrors the shape/error-handling
-// conventions used by ./hyperbolic.ts and ./leonardo.ts.
-
-import { saveCallLog } from "@/lib/usageDb";
-import { sanitizeErrorMessage } from "../../../utils/error.ts";
-
-export async function handleHuggingFaceImageGeneration({
- model,
- provider,
- providerConfig,
- body,
- credentials,
- log,
-}) {
- const startTime = Date.now();
- const token = credentials?.apiKey || credentials?.accessToken || "";
- const prompt = typeof body.prompt === "string" ? body.prompt : String(body.prompt ?? "");
-
- if (log) {
- log.info("IMAGE", `${provider}/${model} (huggingface) | prompt: "${prompt.slice(0, 60)}..."`);
- }
-
- try {
- const response = await fetch(`${providerConfig.baseUrl}/${model}`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- ...(token ? { Authorization: `Bearer ${token}` } : {}),
- },
- body: JSON.stringify({ inputs: prompt }),
- });
-
- if (!response.ok) {
- const errorText = await response.text();
- if (log)
- log.error("IMAGE", `${provider} error ${response.status}: ${errorText.slice(0, 200)}`);
-
- saveCallLog({
- method: "POST",
- path: "/v1/images/generations",
- status: response.status,
- model: `${provider}/${model}`,
- provider,
- duration: Date.now() - startTime,
- error: errorText.slice(0, 500),
- }).catch(() => {});
-
- return { success: false, status: response.status, error: errorText };
- }
-
- const buf = await response.arrayBuffer();
-
- saveCallLog({
- method: "POST",
- path: "/v1/images/generations",
- status: 200,
- model: `${provider}/${model}`,
- provider,
- duration: Date.now() - startTime,
- }).catch(() => {});
-
- return {
- success: true,
- data: {
- created: Math.floor(Date.now() / 1000),
- data: [{ b64_json: Buffer.from(buf).toString("base64"), revised_prompt: prompt }],
- },
- };
- } catch (err) {
- if (log) log.error("IMAGE", `${provider} fetch error: ${err.message}`);
- saveCallLog({
- method: "POST",
- path: "/v1/images/generations",
- status: 502,
- model: `${provider}/${model}`,
- provider,
- duration: Date.now() - startTime,
- error: err.message,
- }).catch(() => {});
- return {
- success: false,
- status: 502,
- error: `Image provider error: ${sanitizeErrorMessage((err as Error).message || err)}`,
- };
- }
-}
diff --git a/open-sse/handlers/imageGeneration/providers/nvidiaNim.ts b/open-sse/handlers/imageGeneration/providers/nvidiaNim.ts
deleted file mode 100644
index 863c20667d..0000000000
--- a/open-sse/handlers/imageGeneration/providers/nvidiaNim.ts
+++ /dev/null
@@ -1,286 +0,0 @@
-// NVIDIA NIM image generation (FLUX models) — ported from upstream 9router#1195.
-// Unlike the NVIDIA *chat* entry (open-sse/config/providers/registry/nvidia/index.ts,
-// host integrate.api.nvidia.com, OpenAI-compatible), NVIDIA NIM *image* generation lives
-// on a different host (ai.api.nvidia.com) with a native per-model NIM body — so it gets
-// its own provider handler rather than reusing the OpenAI-compatible image path.
-//
-// Invoke shape: POST https://ai.api.nvidia.com/v1/genai/<model>
-// Authorization: Bearer <NGC API key>
-// where <model> is the registered model id itself (e.g. "black-forest-labs/flux.1-dev").
-//
-// Response shape varies across the NIM `genai` catalog (SDXL-style `artifacts[].base64`,
-// list-of-strings `images[]`, OpenAI-style `data[].b64_json`, or single-value shorthands)
-// — normalizeNvidiaNimImages() accepts every variant so a NIM response-shape change
-// degrades to "no images" rather than throwing.
-
-import { saveCallLog } from "@/lib/usageDb";
-import { sanitizeErrorMessage } from "../../../utils/error.ts";
-
-const FLUX_1_DEV = "black-forest-labs/flux.1-dev";
-const FLUX_1_KONTEXT_DEV = "black-forest-labs/flux.1-kontext-dev";
-
-function numberFromInput(value: unknown): number | null {
- if (value === undefined || value === null || value === "") return null;
- const num = Number(value);
- return Number.isFinite(num) ? num : null;
-}
-
-function parseSizeString(size: unknown): { width: number; height: number } | null {
- if (typeof size !== "string" || !size || size === "auto") return null;
- const match = /^(\d+)x(\d+)$/.exec(size);
- if (!match) return null;
- return { width: Number(match[1]), height: Number(match[2]) };
-}
-
-function parseDimensions(body: Record<string, unknown>): { width: number; height: number } | null {
- const width = numberFromInput(body.width);
- const height = numberFromInput(body.height);
- if (width !== null && height !== null) return { width, height };
- return parseSizeString(body.size);
-}
-
-function copyIfPresent(
- target: Record<string, unknown>,
- source: Record<string, unknown>,
- key: string
-): void {
- if (source[key] !== undefined && source[key] !== null && source[key] !== "") {
- target[key] = source[key];
- }
-}
-
-function copyNumberIfPresent(
- target: Record<string, unknown>,
- source: Record<string, unknown>,
- key: string,
- options: { greaterThan?: number } = {}
-): void {
- if (source[key] === undefined || source[key] === null || source[key] === "") return;
- const value = Number(source[key]);
- if (!Number.isFinite(value)) return;
- if (options.greaterThan !== undefined && !(value > options.greaterThan)) return;
- target[key] = value;
-}
-
-function normalizeImageArray(image: unknown): unknown[] {
- if (Array.isArray(image)) return image.filter(Boolean);
- return image ? [image] : [];
-}
-
-// FLUX.1 Dev only accepts dimensions in the 768-1344px range, in 64px increments —
-// out-of-range values are silently dropped rather than sent upstream (matches upstream
-// 9router#1195 behavior, verified against build.nvidia.com model page constraints).
-function isFlux1DevDimension(value: number): boolean {
- return Number.isInteger(value) && value >= 768 && value <= 1344 && value % 64 === 0;
-}
-
-/**
- * Build the per-model NIM request body. Each FLUX family member on NIM accepts a
- * slightly different parameter set:
- * - flux.1-dev: mode (base/depth/canny) + cfg_scale (only forwarded if > 1) + strict
- * 768-1344/64px-increment width/height validation; input image only sent for
- * non-"base" modes (depth/canny control image)
- * - flux.1-kontext-dev: image-conditioned edit — requires `image`, uses `aspect_ratio`
- * instead of width/height (the model preserves/derives its own output dimensions)
- * - flux.1-schnell / flux.2-klein-4b: width/height/seed/steps, optional `image` sent as
- * an array when present (edit-style input)
- */
-export function buildNvidiaNimRequestBody(
- model: string,
- body: Record<string, unknown>
-): Record<string, unknown> {
- const req: Record<string, unknown> = { prompt: body.prompt };
- const dimensions = parseDimensions(body);
-
- if (dimensions && model !== FLUX_1_KONTEXT_DEV) {
- if (model !== FLUX_1_DEV || (isFlux1DevDimension(dimensions.width) && isFlux1DevDimension(dimensions.height))) {
- req.width = dimensions.width;
- req.height = dimensions.height;
- }
- }
-
- if (model === FLUX_1_DEV) {
- const mode = body.mode || "base";
- req.mode = mode;
- if (mode !== "base") {
- const images = normalizeImageArray(body.image);
- if (images.length > 0) req.image = images[0];
- }
- } else if (model === FLUX_1_KONTEXT_DEV) {
- const images = normalizeImageArray(body.image);
- if (images.length > 0) req.image = images[0];
- copyIfPresent(req, body, "aspect_ratio");
- } else if (body.image) {
- req.image = normalizeImageArray(body.image);
- }
-
- if (model === FLUX_1_DEV) {
- copyNumberIfPresent(req, body, "cfg_scale", { greaterThan: 1 });
- } else {
- copyIfPresent(req, body, "cfg_scale");
- }
- copyIfPresent(req, body, "seed");
- copyIfPresent(req, body, "steps");
- return req;
-}
-
-function imageItemFromValue(value: unknown): { b64_json?: string; url?: string; finish_reason?: string } | null {
- if (!value) return null;
- if (typeof value === "string") return { b64_json: value };
- if (typeof value !== "object") return null;
- const obj = value as Record<string, unknown>;
- if (typeof obj.url === "string") return { url: obj.url };
- const base64 = obj.base64 || obj.b64_json || obj.image || obj.data;
- if (typeof base64 !== "string") return null;
- const item: { b64_json: string; finish_reason?: string } = { b64_json: base64 };
- const finishReason = obj.finishReason || obj.finish_reason;
- if (typeof finishReason === "string") item.finish_reason = finishReason;
- return item;
-}
-
-/**
- * Normalize the NIM response into `{ created, data: [{ b64_json | url, finish_reason? }] }`.
- * Accepts every response shape seen across the NIM `genai` catalog rather than a single
- * assumed format.
- */
-export function normalizeNvidiaNimImages(responseBody: unknown): {
- created: number;
- data: Array<{ b64_json?: string; url?: string; finish_reason?: string }>;
-} {
- const obj = (responseBody && typeof responseBody === "object" ? responseBody : {}) as Record<
- string,
- unknown
- >;
-
- // Already OpenAI-shaped — pass through.
- if (typeof obj.created === "number" && Array.isArray(obj.data)) {
- return obj as { created: number; data: Array<{ b64_json?: string; url?: string }> };
- }
-
- const candidates: unknown[] = [];
- if (Array.isArray(obj.artifacts)) candidates.push(...obj.artifacts);
- if (Array.isArray(obj.images)) candidates.push(...obj.images);
- if (Array.isArray(obj.data)) candidates.push(...obj.data);
- if (obj.artifact) candidates.push(obj.artifact);
- if (obj.image) candidates.push(obj.image);
- if (obj.base64) candidates.push(obj.base64);
- const result = obj.result as Record<string, unknown> | undefined;
- if (result?.image) candidates.push(result.image);
- if (result && Array.isArray(result.artifacts)) candidates.push(...result.artifacts);
-
- return {
- created: Math.floor(Date.now() / 1000),
- data: candidates.map(imageItemFromValue).filter((item): item is NonNullable<typeof item> => item !== null),
- };
-}
-
-export async function handleNvidiaNimImageGeneration({
- model,
- provider,
- providerConfig,
- body,
- credentials,
- log,
-}: {
- model: string;
- provider: string;
- providerConfig: { baseUrl: string };
- body: Record<string, unknown>;
- credentials?: { apiKey?: string; accessToken?: string } | null;
- log?: {
- info: (scope: string, message: string) => void;
- error: (scope: string, message: string) => void;
- } | null;
-}) {
- const startTime = Date.now();
- const token = credentials?.apiKey || credentials?.accessToken || "";
-
- if (model === FLUX_1_KONTEXT_DEV && !body.image) {
- return {
- success: false,
- status: 400,
- error: "NVIDIA FLUX.1 Kontext Dev requires an input image",
- };
- }
-
- const requestBody = buildNvidiaNimRequestBody(model, body);
-
- if (log) {
- const promptPreview = String(body.prompt ?? "").slice(0, 60);
- log.info("IMAGE", `${provider}/${model} (nvidia-nim) | prompt: "${promptPreview}..."`);
- }
-
- const url = `${providerConfig.baseUrl.replace(/\/$/, "")}/${model}`;
-
- try {
- const response = await fetch(url, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- Accept: "application/json",
- Authorization: `Bearer ${token}`,
- },
- body: JSON.stringify(requestBody),
- });
-
- if (!response.ok) {
- const errorText = await response.text();
- if (log)
- log.error("IMAGE", `${provider} error ${response.status}: ${errorText.slice(0, 200)}`);
- saveCallLog({
- method: "POST",
- path: "/v1/images/generations",
- status: response.status,
- model: `${provider}/${model}`,
- provider,
- duration: Date.now() - startTime,
- error: errorText.slice(0, 500),
- }).catch(() => {});
- return { success: false, status: response.status, error: errorText };
- }
-
- const payload = await response.json();
- const normalized = normalizeNvidiaNimImages(payload);
-
- if (normalized.data.length === 0) {
- saveCallLog({
- method: "POST",
- path: "/v1/images/generations",
- status: 502,
- model: `${provider}/${model}`,
- provider,
- duration: Date.now() - startTime,
- error: "No images returned from NVIDIA NIM",
- }).catch(() => {});
- return { success: false, status: 502, error: "No images returned from NVIDIA NIM" };
- }
-
- saveCallLog({
- method: "POST",
- path: "/v1/images/generations",
- status: 200,
- model: `${provider}/${model}`,
- provider,
- duration: Date.now() - startTime,
- responseBody: { images_count: normalized.data.length },
- }).catch(() => {});
-
- return { success: true, data: normalized };
- } catch (err) {
- if (log) log.error("IMAGE", `${provider} fetch error: ${(err as Error).message}`);
- saveCallLog({
- method: "POST",
- path: "/v1/images/generations",
- status: 502,
- model: `${provider}/${model}`,
- provider,
- duration: Date.now() - startTime,
- error: (err as Error).message,
- }).catch(() => {});
- return {
- success: false,
- status: 502,
- error: `Image provider error: ${sanitizeErrorMessage((err as Error).message || err)}`,
- };
- }
-}
diff --git a/open-sse/handlers/ocr.ts b/open-sse/handlers/ocr.ts
deleted file mode 100644
index bf0c553ff0..0000000000
--- a/open-sse/handlers/ocr.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-import { CORS_HEADERS } from "../utils/cors.ts";
-/**
- * OCR Handler
- *
- * Handles POST /v1/ocr (Mistral OCR API format).
- */
-
-import { getOcrProvider, parseOcrModel } from "../config/ocrRegistry.ts";
-import { errorResponse } from "../utils/error.ts";
-import { attachOmniRouteMetaHeaders } from "@/domain/omnirouteResponseMeta";
-import { generateRequestId } from "@/shared/utils/requestId";
-
-/**
- * Handle OCR request
- *
- * @param {Object} options
- * @param {Object} options.body - JSON body { model, document }
- * @param {Object} options.credentials - Provider credentials { apiKey }
- * @returns {Response}
- */
-/** @returns {Promise<unknown>} */
-export async function handleOcr({ body, credentials }) {
- const startTime = Date.now();
- if (!body.document) {
- return errorResponse(400, "document is required");
- }
-
- // Default to latest OCR model
- const model = body.model || "mistral-ocr-latest";
- const { provider: providerId, model: modelId } = parseOcrModel(model);
- const providerConfig = providerId ? getOcrProvider(providerId) : null;
-
- if (!providerConfig) {
- return errorResponse(400, `No OCR provider found for model "${model}". Available: mistral`);
- }
-
- const token = credentials?.apiKey || credentials?.accessToken;
- if (!token) {
- return errorResponse(401, `No credentials for OCR provider: ${providerId}`);
- }
-
- try {
- const res = await fetch(providerConfig.baseUrl, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- Authorization: `Bearer ${token}`,
- },
- body: JSON.stringify({
- ...body,
- model: modelId,
- }),
- });
-
- if (!res.ok) {
- const errText = await res.text();
- return new Response(errText, {
- status: res.status,
- headers: {
- "Content-Type": "application/json",
- ...CORS_HEADERS,
- },
- });
- }
-
- const data = await res.json();
- const headers = new Headers({ ...CORS_HEADERS, "Content-Type": "application/json" });
- attachOmniRouteMetaHeaders(headers, {
- provider: providerId,
- model: modelId,
- costUsd: 0,
- latencyMs: Date.now() - startTime,
- requestId: generateRequestId(),
- });
- return new Response(JSON.stringify(data), { status: 200, headers });
- } catch (err) {
- return errorResponse(500, `OCR request failed: ${err.message}`);
- }
-}
diff --git a/open-sse/handlers/responseSanitizer/reasoning.ts b/open-sse/handlers/responseSanitizer/reasoning.ts
index 867d455c84..cf15fc2fc6 100644
--- a/open-sse/handlers/responseSanitizer/reasoning.ts
+++ b/open-sse/handlers/responseSanitizer/reasoning.ts
@@ -129,13 +129,7 @@ export function isTextualReasoningTagNativeRoute(providerId: string, modelId: st
return (
/deepseek[-_/]?r1\b/.test(routeId) ||
/r1[-_/]?distill\b/.test(routeId) ||
- /(?:^|[/:_-])qwq(?:[/._:-]|$)/.test(routeId) ||
- // 9router#2231: MiniMax M3 leaks raw <think>...</think> into `content` on its
- // OpenAI-format provider tiers (trae, huggingchat, bazaarlink, ollama-cloud,
- // opencode, cline, opencode-zen, codebuddy-cn). The direct minimax/minimax-cn
- // tiers stay on Anthropic's Messages format (targetFormat: "claude") and
- // already surface reasoning natively, so they are excluded here.
- (providerId !== "minimax" && providerId !== "minimax-cn" && /minimax[-_]?m3\b/.test(routeId))
+ /(?:^|[/:_-])qwq(?:[/._:-]|$)/.test(routeId)
);
}
diff --git a/open-sse/mcp-server/audit.ts b/open-sse/mcp-server/audit.ts
index 40e023212c..259ded1c49 100644
--- a/open-sse/mcp-server/audit.ts
+++ b/open-sse/mcp-server/audit.ts
@@ -206,49 +206,6 @@ function toString(value: unknown): string {
return typeof value === "string" ? value : "";
}
-async function openBetterSqliteAuditDb(dbPath: string): Promise<AuditDatabase> {
- const Database = (await import("better-sqlite3")).default as unknown as new (
- dbPath: string
- ) => AuditDatabase;
- return new Database(dbPath);
-}
-
-function nodeSqliteFallbackAvailable(): boolean {
- const [maj, min] = (process.versions.node ?? "0.0").split(".").map(Number);
- return maj > 22 || (maj === 22 && (min ?? 0) >= 5);
-}
-
-async function openNodeSqliteAuditDb(dbPath: string): Promise<AuditDatabase> {
- const { DatabaseSync } = (await import("node:sqlite")) as {
- DatabaseSync: new (p: string) => NodeSqliteDatabase;
- };
- return createNodeSqliteAuditAdapter(new DatabaseSync(dbPath));
-}
-
-async function openFallbackAuditDb(dbPath: string, nativeMessage: string): Promise<AuditDatabase | null> {
- if (!nodeSqliteFallbackAvailable()) {
- console.error(
- `[MCP Audit] better-sqlite3 native binding unavailable and Node ${process.version} ` +
- "has no built-in sqlite. Audit logging disabled. Fix: run " +
- "`npm rebuild better-sqlite3` in the omniroute install root."
- );
- return null;
- }
-
- try {
- const adapter = await openNodeSqliteAuditDb(dbPath);
- console.warn(
- `[MCP Audit] better-sqlite3 binding unavailable — fell back to node:sqlite ` +
- `(${nativeMessage.split("\n")[0]})`
- );
- return adapter;
- } catch (nodeErr) {
- const nodeMessage = nodeErr instanceof Error ? nodeErr.message : String(nodeErr);
- console.error("[MCP Audit] Failed to connect to database:", nodeMessage);
- return null;
- }
-}
-
/**
* Lazy-load the database connection.
* Uses the same SQLite database as the main OmniRoute app.
@@ -281,19 +238,58 @@ async function getDb(): Promise<AuditDatabase | null> {
return null;
}
+ // Try better-sqlite3 first (matches the main app's default driver).
try {
- const database = await openBetterSqliteAuditDb(dbPath);
+ const Database = (await import("better-sqlite3")).default as unknown as new (
+ dbPath: string
+ ) => AuditDatabase;
+ const database = new Database(dbPath);
setCachedAuditDb(database);
return database;
} catch (nativeErr) {
+ // Declared once at the top of the catch: nativeMessage is read both on
+ // the non-fallback bail-out and in the node:sqlite fallback warning
+ // further down. A block-scoped const inside the `if` below would be out
+ // of scope in the fallback path.
const nativeMessage = nativeErr instanceof Error ? nativeErr.message : String(nativeErr);
+ // Reuse the canonical detection helper from the main app's DB layer
+ // so we cover every ABI/binding failure mode the rest of the codebase
+ // already knows about: missing MODULE_NOT_FOUND, ERR_DLOPEN_FAILED,
+ // "Module did not self-register", "Cannot find module 'better-sqlite3'",
+ // the standard V8 "was compiled against a different Node.js version"
+ // message, and the bindings-loader "Could not locate the bindings file".
+ // Real errors (corrupt db, permission denied) still surface to the operator.
if (!isNativeSqliteLoadError(nativeErr)) {
console.error("[MCP Audit] Failed to connect to database:", nativeMessage);
return null;
}
- const fallbackDb = await openFallbackAuditDb(dbPath, nativeMessage);
- setCachedAuditDb(fallbackDb);
- return fallbackDb;
+ // Fall back to Node's built-in sqlite (Node 22.5+).
+ const [maj, min] = (process.versions.node ?? "0.0").split(".").map(Number);
+ if (maj < 22 || (maj === 22 && (min ?? 0) < 5)) {
+ console.error(
+ `[MCP Audit] better-sqlite3 native binding unavailable and Node ${process.version} ` +
+ "has no built-in sqlite. Audit logging disabled. Fix: run " +
+ "`npm rebuild better-sqlite3` in the omniroute install root."
+ );
+ return null;
+ }
+ try {
+ const { DatabaseSync } = (await import("node:sqlite")) as {
+ DatabaseSync: new (p: string) => NodeSqliteDatabase;
+ };
+ const nodeDb = new DatabaseSync(dbPath);
+ const adapter = createNodeSqliteAuditAdapter(nodeDb);
+ setCachedAuditDb(adapter);
+ console.warn(
+ `[MCP Audit] better-sqlite3 binding unavailable — fell back to node:sqlite ` +
+ `(${nativeMessage.split("\n")[0]})`
+ );
+ return adapter;
+ } catch (nodeErr) {
+ const nodeMessage = nodeErr instanceof Error ? nodeErr.message : String(nodeErr);
+ console.error("[MCP Audit] Failed to connect to database:", nodeMessage);
+ return null;
+ }
}
} catch (err: unknown) {
const message = err instanceof Error ? err.message : String(err);
diff --git a/open-sse/mcp-server/catalog.ts b/open-sse/mcp-server/catalog.ts
deleted file mode 100644
index d06a16f192..0000000000
--- a/open-sse/mcp-server/catalog.ts
+++ /dev/null
@@ -1,290 +0,0 @@
-import { getCodexRequestDefaults } from "../../src/lib/providers/requestDefaults.ts";
-import { getProviderConnections } from "../../src/lib/db/providers.ts";
-import { AI_PROVIDERS, NOAUTH_PROVIDERS } from "../../src/shared/constants/providers.ts";
-
-type JsonRecord = Record<string, unknown>;
-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;
-};
-
-type McpCatalogRequestSpec = {
- provider: string;
- path: string;
- thinkingEffort?: string;
-};
-
-function toRecord(value: unknown): JsonRecord {
- return value && typeof value === "object" && !Array.isArray(value) ? (value as JsonRecord) : {};
-}
-
-function toString(value: unknown, fallback = ""): string {
- return typeof value === "string" ? value : fallback;
-}
-
-function toStringArray(value: unknown, fallback: string[] = []): string[] {
- return Array.isArray(value) ? value.map((item) => String(item)) : fallback;
-}
-
-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,
- };
-}
-
-function activeProviderConnections(
- connections: ProviderConnectionLike[],
- normalizeProviderId: (value: string) => string,
- requestedProvider: string | null
-): ProviderConnectionLike[] {
- return connections.filter((connection) => {
- const provider =
- typeof connection?.provider === "string" ? normalizeProviderId(connection.provider) : null;
- return !!provider && !!connection?.id && connection.isActive !== false &&
- (!requestedProvider || provider === requestedProvider);
- });
-}
-
-function providerModelRequestSpecs(
- connections: ProviderConnectionLike[],
- normalizeProviderId: (value: string) => string
-): McpCatalogRequestSpec[] {
- return connections.map((connection) => ({
- provider: normalizeProviderId(String(connection.provider)),
- path: `/api/providers/${encodeURIComponent(String(connection.id))}/models?excludeHidden=true`,
- thinkingEffort: getConnectionThinkingEffort(connection),
- }));
-}
-
-function noAuthProviderSpec(requestedProvider: string): McpCatalogRequestSpec {
- return {
- provider: requestedProvider,
- path: `/api/v1/providers/${encodeURIComponent(requestedProvider)}/models`,
- thinkingEffort: undefined,
- };
-}
-
-function emptyCatalogForProvider(requestedProvider: string): McpCatalogResponse {
- return {
- models: [],
- source: "provider_connections",
- warning: `No active connections found for provider '${requestedProvider}'.`,
- };
-}
-
-function rawModelsFromCatalog(raw: JsonRecord): unknown[] {
- if (Array.isArray(raw.models)) return raw.models;
- if (Array.isArray(raw.data)) return raw.data;
- return [];
-}
-
-function maybeCatalogModel(
- rawModel: unknown,
- spec: McpCatalogRequestSpec,
- source: string,
- warning: string | undefined,
- requestedCapability: string | null
-): McpCatalogResponse["models"][number] | null {
- const normalized = normalizeProviderModelRecord(rawModel, spec.provider, source, warning);
- if (spec.thinkingEffort && !normalized.thinkingEffort) normalized.thinkingEffort = spec.thinkingEffort;
- if (!normalized.id) return null;
- if (requestedCapability && !normalized.capabilities.includes(requestedCapability)) return null;
- return normalized;
-}
-
-function addCatalogModels(
- raw: JsonRecord,
- spec: McpCatalogRequestSpec,
- source: string,
- warning: string | undefined,
- requestedCapability: string | null,
- collectedModels: Map<string, McpCatalogResponse["models"][number]>
-) {
- for (const rawModel of rawModelsFromCatalog(raw)) {
- const normalized = maybeCatalogModel(rawModel, spec, source, warning, requestedCapability);
- if (normalized) collectedModels.set(`${normalized.provider}:${normalized.id}`, normalized);
- }
-}
-
-async function collectCatalogModels(
- requestSpecs: McpCatalogRequestSpec[],
- fetchJson: (path: string) => Promise<unknown>,
- requestedCapability: string | null
-) {
- 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);
- addCatalogModels(raw, spec, source, warning, requestedCapability, collectedModels);
- }
-
- return { collectedModels, warnings, sources };
-}
-
-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) => import("./server.ts").then((m) => m.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 = activeProviderConnections(
- connections,
- normalizeProviderId,
- requestedProvider
- );
- const requestSpecs = providerModelRequestSpecs(activeConnections, normalizeProviderId);
-
- if (requestedProvider && requestSpecs.length === 0) {
- const isNoAuthProvider = Object.values(NOAUTH_PROVIDERS).some(
- (provider) => provider.id === requestedProvider
- );
- if (isNoAuthProvider) {
- requestSpecs.push(noAuthProviderSpec(requestedProvider));
- } else {
- return emptyCatalogForProvider(requestedProvider);
- }
- }
-
- const { collectedModels, warnings, sources } = await collectCatalogModels(
- requestSpecs,
- fetchJson,
- requestedCapability
- );
-
- return {
- models: [...collectedModels.values()],
- source: sources.size === 1 ? [...sources][0] : "aggregated_provider_models",
- ...(warnings.size > 0 ? { warning: [...warnings].join(" | ") } : {}),
- };
-}
diff --git a/open-sse/mcp-server/httpTransport.ts b/open-sse/mcp-server/httpTransport.ts
index 7b982142d4..67448e15d0 100644
--- a/open-sse/mcp-server/httpTransport.ts
+++ b/open-sse/mcp-server/httpTransport.ts
@@ -173,27 +173,6 @@ async function handleStreamableRequest(request: Request): Promise<Response> {
// terminated/unknown, the server MUST respond with HTTP 404 Not Found so the
// client re-initializes. A 400 here is non-recoverable for spec-compliant
// clients (they only re-init on 404). See issue #5169.
- //
- // Auto-recovery: if the client sends an initialize request with a stale session
- // id (e.g. after a server restart or idle eviction), treat it as a fresh
- // initialization rather than hard-failing with 404. This avoids requiring users
- // to manually restart their MCP client after every server restart.
- if (await isInitializeRequest(request)) {
- const newSession = createStreamableSession();
- try {
- const response = await withMcpHttpAuthContext(request, () =>
- newSession.transport.handleRequest(request)
- );
- return withSessionHeader(response, newSession.sessionId);
- } catch (err) {
- closeStreamableSession(newSession.sessionId);
- console.error("[MCP] Streamable HTTP error during stale-session recovery:", err);
- return new Response(JSON.stringify({ error: "MCP transport error" }), {
- status: 500,
- headers: { "Content-Type": "application/json" },
- });
- }
- }
return errorResponse("Not Found: Unknown Mcp-Session-Id header", -32000, 404);
}
diff --git a/open-sse/mcp-server/schemas/pickFastestModel.ts b/open-sse/mcp-server/schemas/pickFastestModel.ts
deleted file mode 100644
index 3434b02ec6..0000000000
--- a/open-sse/mcp-server/schemas/pickFastestModel.ts
+++ /dev/null
@@ -1,110 +0,0 @@
-import { z } from "zod";
-import type { McpToolDefinition } from "./toolDefinition.ts";
-
-export const pickFastestModelInput = z.object({
- comboId: z
- .string()
- .optional()
- .describe(
- "Optional combo id or name to scope the ranking to. Omit to rank across all enabled combos."
- ),
- includeUnhealthy: z
- .boolean()
- .optional()
- .describe(
- "When true, OPEN-circuit candidates are scored (sorted to the bottom) instead of filtered out."
- ),
- weights: z
- .object({
- ttft: z.number().min(0).optional(),
- tps: z.number().min(0).optional(),
- e2e: z.number().min(0).optional(),
- p95: z.number().min(0).optional(),
- health: z.number().min(0).optional(),
- reliability: z.number().min(0).optional(),
- stability: z.number().min(0).optional(),
- })
- .partial()
- .optional()
- .describe("Optional speed-ranking weight overrides merged onto the defaults."),
- applyToCombo: z
- .boolean()
- .optional()
- .describe("When true + comboId present, switches the combo to auto/latency routing."),
- limit: z.number().int().min(1).max(50).optional().describe("Ranked result limit."),
-});
-
-export const pickFastestModelOutput = z.object({
- fastest: z
- .object({
- provider: z.string(),
- model: z.string(),
- score: z.number(),
- reason: z.string(),
- })
- .nullable(),
- ranked: z.array(
- z.object({
- provider: z.string(),
- model: z.string(),
- score: z.number(),
- factors: z.object({
- ttft: z.number(),
- tps: z.number(),
- e2e: z.number(),
- p95: z.number(),
- health: z.number(),
- reliability: z.number(),
- stability: z.number(),
- }),
- metrics: z.object({
- avgTtftMs: z.number().nullable(),
- avgTokensPerSecond: z.number().nullable(),
- avgE2ELatencyMs: z.number().nullable(),
- p95LatencyMs: z.number().nullable(),
- latencyStdDev: z.number().nullable(),
- failureRate: z.number(),
- circuitBreakerState: z.enum(["CLOSED", "OPEN", "HALF_OPEN"]),
- }),
- reason: z.string(),
- })
- ),
- weights: z.object({
- ttft: z.number(),
- tps: z.number(),
- e2e: z.number(),
- p95: z.number(),
- health: z.number(),
- reliability: z.number(),
- stability: z.number(),
- }),
- comboScope: z.object({ id: z.string(), name: z.string() }).nullable(),
- appliedToCombo: z
- .object({
- id: z.string(),
- name: z.string(),
- strategy: z.string(),
- autoRoutingStrategy: z.string(),
- })
- .nullable(),
-});
-
-export const pickFastestModelTool: McpToolDefinition<
- typeof pickFastestModelInput,
- typeof pickFastestModelOutput
-> = {
- name: "omniroute_pick_fastest_model",
- description:
- "Picks the fastest reliable provider-model pair from live telemetry and can apply latency routing to a combo.",
- inputSchema: pickFastestModelInput,
- outputSchema: pickFastestModelOutput,
- scopes: ["read:combos", "read:health", "read:usage"],
- auditLevel: "basic",
- phase: 2,
- sourceEndpoints: [
- "/api/combos",
- "/api/monitoring/health",
- "/api/usage/quota",
- "/api/usage/analytics",
- ],
-};
diff --git a/open-sse/mcp-server/schemas/tools.ts b/open-sse/mcp-server/schemas/tools.ts
index 85b5c3edd7..b7b0b84090 100644
--- a/open-sse/mcp-server/schemas/tools.ts
+++ b/open-sse/mcp-server/schemas/tools.ts
@@ -1,5 +1,5 @@
/**
- * MCP Tool Schemas — Contracts for all 23 core and advanced OmniRoute MCP tools.
+ * MCP Tool Schemas — Contracts for all 22 core and advanced OmniRoute MCP tools.
*
* Defines input/output Zod schemas, descriptions, scopes, and audit levels
* for both essential (Phase 1) and advanced (Phase 2) MCP tools.
@@ -11,7 +11,6 @@
import { z } from "zod";
import { toolSearchTool } from "./toolSearch.ts";
-import { pickFastestModelTool } from "./pickFastestModel.ts";
import {
AUTO_ROUTING_STRATEGY_VALUES,
ROUTING_STRATEGY_VALUES,
@@ -23,7 +22,6 @@ import {
// Re-exported here for backward compatibility (many modules import them from ./tools.ts).
export type { AuditLevel, McpToolDefinition } from "./toolDefinition.ts";
import type { McpToolDefinition } from "./toolDefinition.ts";
-export { pickFastestModelInput, pickFastestModelOutput } from "./pickFastestModel.ts";
// ============ Phase 1: Essential Tools (8) ============
@@ -1468,7 +1466,6 @@ export const MCP_TOOLS = [
agentSkillsListTool,
agentSkillsGetTool,
agentSkillsCoverageTool,
- pickFastestModelTool,
] as const;
export const MCP_ESSENTIAL_TOOLS = MCP_TOOLS.filter((t) => t.phase === 1);
diff --git a/open-sse/mcp-server/server.ts b/open-sse/mcp-server/server.ts
index cbf95b1956..554f1ab1d8 100644
--- a/open-sse/mcp-server/server.ts
+++ b/open-sse/mcp-server/server.ts
@@ -5,7 +5,9 @@ import {
getComboModelString,
getComboStepTarget,
} from "../../src/lib/combos/steps.ts";
+
import { registerToolSearchTool } from "./toolSearch/register.ts";
+
import {
MCP_TOOLS,
getHealthInput,
@@ -26,7 +28,6 @@ import {
getProviderMetricsInput,
bestComboForTaskInput,
explainRouteInput,
- pickFastestModelInput,
getSessionSnapshotInput,
dbHealthCheckInput,
syncPricingInput,
@@ -37,6 +38,7 @@ import {
oneproxyStatsInput,
} from "./schemas/tools.ts";
import { startMcpHeartbeat } from "./runtimeHeartbeat.ts";
+
import { z } from "zod";
import { closeAuditDb, logToolCall } from "./audit.ts";
import {
@@ -45,6 +47,7 @@ import {
type McpToolExtraLike,
} from "./scopeEnforcement.ts";
import { getMcpHttpAuthHeadersForInternalFetch } from "./httpAuthContext.ts";
+
import {
handleSimulateRoute,
handleSetBudgetGuard,
@@ -63,7 +66,6 @@ import {
handleOneproxyRotate,
handleOneproxyStats,
} from "./tools/advancedTools.ts";
-import { handlePickFastestModel } from "./tools/pickFastestModel.ts";
import { memoryTools } from "./tools/memoryTools.ts";
import { skillTools } from "./tools/skillTools.ts";
import { agentSkillTools } from "./tools/agentSkillTools.ts";
@@ -84,10 +86,11 @@ 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";
-import { getMcpModelsCatalog } from "./catalog.ts";
-export { getMcpModelsCatalog } from "./catalog.ts";
const OMNIROUTE_BASE_URL = resolveOmniRouteBaseUrl();
const MCP_ENFORCE_SCOPES = process.env.OMNIROUTE_MCP_ENFORCE_SCOPES === "true";
@@ -141,6 +144,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) : {};
}
@@ -185,7 +210,7 @@ function getOmniRouteApiKey(): string {
return process.env.OMNIROUTE_API_KEY || "";
}
-export async function omniRouteFetch(path: string, options: RequestInit = {}): Promise<unknown> {
+async function omniRouteFetch(path: string, options: RequestInit = {}): Promise<unknown> {
const url = `${OMNIROUTE_BASE_URL}${path}`;
const apiKey = getOmniRouteApiKey();
const headers: Record<string, string> = {
@@ -208,6 +233,202 @@ export async function omniRouteFetch(path: string, options: RequestInit = {}): P
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>,
@@ -864,8 +1085,6 @@ export function createMcpServer(): McpServer {
)
);
- server.registerTool("omniroute_pick_fastest_model", { description: "Picks the fastest reliable provider-model pair from live telemetry.", inputSchema: pickFastestModelInput }, withScopeEnforcement("omniroute_pick_fastest_model", (args) => handlePickFastestModel(pickFastestModelInput.parse(args))));
-
server.registerTool(
"omniroute_get_session_snapshot",
{
diff --git a/open-sse/mcp-server/tools/pickFastestModel.ts b/open-sse/mcp-server/tools/pickFastestModel.ts
deleted file mode 100644
index 2d22ab9e15..0000000000
--- a/open-sse/mcp-server/tools/pickFastestModel.ts
+++ /dev/null
@@ -1,293 +0,0 @@
-import { logToolCall } from "../audit.ts";
-import { getMcpHttpAuthHeadersForInternalFetch } from "../httpAuthContext.ts";
-import { normalizeQuotaResponse } from "../../../src/shared/contracts/quota.ts";
-import { resolveOmniRouteBaseUrl } from "../../../src/shared/utils/resolveOmniRouteBaseUrl.ts";
-import {
- getComboModelProvider,
- getComboModelString,
- getComboStepTarget,
-} from "../../../src/lib/combos/steps.ts";
-import type { AutoRoutingStrategyValue } from "../../../src/shared/constants/routingStrategies.ts";
-import { rankBySpeed, DEFAULT_SPEED_WEIGHTS } from "../../services/autoCombo/speedRanking.ts";
-import type { SpeedCandidate } from "../../services/autoCombo/speedRanking.ts";
-
-const OMNIROUTE_BASE_URL = resolveOmniRouteBaseUrl();
-const OMNIROUTE_API_KEY = process.env.OMNIROUTE_API_KEY || "";
-
-async function apiFetch(path: string, options: RequestInit = {}): Promise<unknown> {
- const url = `${OMNIROUTE_BASE_URL}${path}`;
- const headers: Record<string, string> = {
- "Content-Type": "application/json",
- ...(OMNIROUTE_API_KEY ? { Authorization: `Bearer ${OMNIROUTE_API_KEY}` } : {}),
- ...getMcpHttpAuthHeadersForInternalFetch(),
- ...((options.headers as Record<string, string>) || {}),
- };
- const response = await fetch(url, { ...options, headers, signal: AbortSignal.timeout(30000) });
- if (!response.ok) {
- const text = await response.text().catch(() => "Unknown error");
- throw new Error(`API [${response.status}]: ${text}`);
- }
- return response.json();
-}
-
-type JsonRecord = Record<string, unknown>;
-interface ComboModel { provider: string; model: string; inputCostPer1M: number; }
-interface PickFastestModelArgs {
- comboId?: string;
- /** When true, OPEN-circuit candidates are still scored (sorted to the bottom). */
- includeUnhealthy?: boolean;
- /** Optional weight overrides; merged onto DEFAULT_SPEED_WEIGHTS. */
- weights?: Partial<{
- ttft: number;
- tps: number;
- e2e: number;
- p95: number;
- health: number;
- reliability: number;
- stability: number;
- }>;
- /** When true + comboId present, sets the combo's autoRoutingStrategy to "latency". */
- applyToCombo?: boolean;
- /** Max number of ranked entries to return (default 10). */
- limit?: number;
-}
-interface TelemetrySources {
- combos: JsonRecord[];
- breakers: JsonRecord[];
- providers: ReturnType<typeof normalizeQuotaResponse>["providers"];
- analyticsByProvider: JsonRecord;
- analyticsTop: JsonRecord;
-}
-
-function isRecord(value: unknown): value is JsonRecord { return !!value && typeof value === "object" && !Array.isArray(value); }
-function toRecord(value: unknown): JsonRecord { return isRecord(value) ? value : {}; }
-function toArrayOfRecords(value: unknown): JsonRecord[] { return Array.isArray(value) ? value.filter(isRecord) : []; }
-function toString(value: unknown, fallback = ""): string { return typeof value === "string" ? value : fallback; }
-function toNumber(value: unknown, fallback = 0): number {
- const parsed = typeof value === "number" ? value : typeof value === "string" && value.trim().length > 0 ? Number(value) : Number.NaN;
- return Number.isFinite(parsed) ? parsed : fallback;
-}
-function getComboModels(combo: JsonRecord): ComboModel[] {
- const directModels = toArrayOfRecords(combo.models);
- const nestedModels = toArrayOfRecords(toRecord(combo.data).models);
- const sourceModels = directModels.length > 0 ? directModels : nestedModels;
- return sourceModels.map((model) => ({
- provider: getComboModelProvider(model) || (getComboModelString(model) ? "unknown" : "combo"),
- model: getComboModelString(model) || getComboStepTarget(model) || "",
- inputCostPer1M: toNumber(model.inputCostPer1M, 3.0),
- }));
-}
-function normalizeCombosResponse(raw: unknown): JsonRecord[] {
- if (Array.isArray(raw)) return raw.filter(isRecord);
- const source = toRecord(raw);
- return Array.isArray(source.combos) ? source.combos.filter(isRecord) : [];
-}
-
-function settledValue(result: PromiseSettledResult<unknown>): unknown {
- return result.status === "fulfilled" ? result.value : undefined;
-}
-
-async function fetchTelemetrySources(): Promise<TelemetrySources> {
- const [combosRaw, healthRaw, quotaRaw, analyticsRaw] = await Promise.allSettled([
- apiFetch("/api/combos"),
- apiFetch("/api/monitoring/health"),
- apiFetch("/api/usage/quota"),
- apiFetch("/api/usage/analytics?period=session"),
- ]);
-
- const analytics = toRecord(settledValue(analyticsRaw));
- return {
- combos: normalizeCombosResponse(settledValue(combosRaw)),
- breakers: toArrayOfRecords(toRecord(settledValue(healthRaw)).circuitBreakers),
- providers: normalizeQuotaResponse(settledValue(quotaRaw) ?? {}).providers,
- analyticsByProvider: toRecord(toRecord(analytics.byProvider)),
- analyticsTop: analytics,
- };
-}
-
-function selectComboScope(combos: JsonRecord[], comboId?: string) {
- const targetCombo = comboId
- ? combos.find((combo) => toString(combo.id) === comboId || toString(combo.name) === comboId)
- : undefined;
- return {
- targetCombo,
- scopedCombos: targetCombo ? [targetCombo] : combos.filter((combo) => combo.enabled !== false),
- };
-}
-
-function noCandidatesResult(error: string) {
- return { content: [{ type: "text" as const, text: JSON.stringify({ error }) }], isError: true };
-}
-
-function providerAnalytics(sources: TelemetrySources, provider: string) {
- const perProvider = toRecord(sources.analyticsByProvider[provider]);
- return perProvider.requests
- ? perProvider
- : toRecord(sources.analyticsTop.byProvider && toRecord(sources.analyticsTop.byProvider)[provider]);
-}
-
-function buildCandidate(model: ComboModel, sources: TelemetrySources): SpeedCandidate {
- const cb = sources.breakers.find((breaker) => toString(breaker.provider) === model.provider);
- const q = sources.providers.find((providerEntry) => providerEntry.provider === model.provider);
- const analytics = providerAnalytics(sources, model.provider);
- const cbState = toString(cb?.state, "CLOSED") as SpeedCandidate["circuitBreakerState"];
- const p95 = toNumber(analytics.p95LatencyMs, NaN);
- const errorRate = toNumber(analytics.errorRate, 0);
-
- return {
- provider: model.provider,
- model: model.model,
- circuitBreakerState: cbState,
- avgE2ELatencyMs: toNumber(analytics.avgLatencyMs, NaN),
- p95LatencyMs: Number.isFinite(p95) ? p95 : 0,
- avgTokensPerSecond: toNumber(analytics.avgTokensPerSecond ?? analytics.tps, NaN),
- avgTtftMs: toNumber(analytics.avgTtftMs ?? analytics.ttftMs, NaN),
- latencyStdDev: toNumber(analytics.latencyStdDev, NaN),
- errorRate: Number.isFinite(errorRate) ? errorRate : 0,
- failureRate: Number.isFinite(errorRate) ? errorRate : 0,
- quotaRemaining: q?.quotaUsed != null && q?.quotaTotal
- ? Math.max(0, 100 - q.quotaUsed / q.quotaTotal * 100)
- : 100,
- quotaTotal: q?.quotaTotal ?? 100,
- costPer1MTokens: model.inputCostPer1M ?? 0,
- };
-}
-
-function buildSpeedCandidates(scopedCombos: JsonRecord[], sources: TelemetrySources): SpeedCandidate[] {
- const speedCandidates: SpeedCandidate[] = [];
- for (const combo of scopedCombos) {
- for (const model of getComboModels(combo)) {
- if (model.provider && model.model) speedCandidates.push(buildCandidate(model, sources));
- }
- }
- return speedCandidates;
-}
-
-function candidateCompletenessScore(candidate: SpeedCandidate): number {
- return (candidate.circuitBreakerState ? 1 : 0) + (candidate.quotaRemaining != null ? 1 : 0);
-}
-
-function dedupeCandidates(candidates: SpeedCandidate[]): SpeedCandidate[] {
- const deduped = new Map<string, SpeedCandidate>();
- for (const candidate of candidates) {
- const key = `${candidate.provider}::${candidate.model}`;
- const existing = deduped.get(key);
- if (!existing || candidateCompletenessScore(candidate) > candidateCompletenessScore(existing)) {
- deduped.set(key, candidate);
- }
- }
- return [...deduped.values()];
-}
-
-async function applyWinnerToCombo(targetCombo: JsonRecord, winner: { provider: string; model: string }) {
- const comboId = toString(targetCombo.id);
- const comboData = toRecord(targetCombo.data);
- const baseConfig = toRecord(targetCombo.config);
- const currentConfig = Object.keys(baseConfig).length > 0 ? baseConfig : toRecord(comboData.config);
- const nextConfig = {
- ...currentConfig,
- auto: {
- ...toRecord(currentConfig.auto),
- routerStrategy: "latency" as AutoRoutingStrategyValue,
- },
- };
- const updatedCombo = toRecord(
- await apiFetch(`/api/combos/${encodeURIComponent(comboId)}`, {
- method: "PUT",
- body: JSON.stringify({ strategy: "auto", config: nextConfig }),
- })
- );
- const updatedConfig = toRecord(updatedCombo.config);
- return {
- id: toString(updatedCombo.id, comboId),
- name: toString(updatedCombo.name, toString(targetCombo.name, comboId)),
- strategy: toString(updatedCombo.strategy, "auto"),
- autoRoutingStrategy: toString(toRecord(updatedConfig.auto).routerStrategy, "latency"),
- };
-}
-
-/**
- * Speed-optimized "pick the fastest reliable provider×model" tool.
- *
- * Composes live telemetry from `/api/combos/metrics` (per-combo per-model
- * avg latency + success rate), `/api/monitoring/health` (circuit-breaker
- * state), `/api/usage/quota` (quota remaining) and `/api/usage/analytics`
- * (per-provider p95 / errorRate) into SpeedCandidates, runs the same
- * `rankBySpeed` engine that drives `LatencyStrategyImpl` and the latency-
- * optimized playground preview, and returns:
- * - the top-ranked (fastest) provider×model pair,
- * - the full ranked list with per-factor scores (ttft / tps / e2e /
- * p95 / health / reliability / stability) so callers can show
- * "why this one wins" in dashboards,
- * - optionally applies the choice to a target combo by flipping its
- * strategy to "auto" + autoRoutingStrategy "latency", so the runtime
- * router will keep using this ranking.
- */
-export async function handlePickFastestModel(args: PickFastestModelArgs) {
- const start = Date.now();
- try {
- const sources = await fetchTelemetrySources();
- const { targetCombo, scopedCombos } = selectComboScope(sources.combos, args.comboId);
-
- if (scopedCombos.length === 0) {
- return noCandidatesResult("No matching combos available");
- }
-
- const finalCandidates = dedupeCandidates(buildSpeedCandidates(scopedCombos, sources));
- if (finalCandidates.length === 0) {
- return noCandidatesResult("No provider×model candidates available to rank");
- }
-
- const weights = args.weights ? { ...DEFAULT_SPEED_WEIGHTS, ...args.weights } : DEFAULT_SPEED_WEIGHTS;
- const ranked = rankBySpeed(finalCandidates, weights, {
- includeUnhealthy: args.includeUnhealthy === true,
- });
-
- const limit = Math.min(Math.max(toNumber(args.limit, 10), 1), 50);
- const trimmed = ranked.slice(0, limit);
- const winner = trimmed[0];
-
- let appliedToCombo: JsonRecord | null = null;
- if (args.applyToCombo && targetCombo && winner) {
- appliedToCombo = await applyWinnerToCombo(targetCombo, winner);
- }
-
- const result = {
- fastest: winner
- ? {
- provider: winner.provider,
- model: winner.model,
- score: winner.score,
- reason: winner.reason,
- }
- : null,
- ranked: trimmed.map((entry) => ({
- provider: entry.provider,
- model: entry.model,
- score: entry.score,
- factors: entry.factors,
- metrics: entry.metrics,
- reason: entry.reason,
- })),
- weights,
- comboScope: targetCombo
- ? { id: toString(targetCombo.id), name: toString(targetCombo.name) }
- : null,
- appliedToCombo,
- };
-
- await logToolCall("omniroute_pick_fastest_model", args, result, Date.now() - start, true);
- return { content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }] };
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- await logToolCall(
- "omniroute_pick_fastest_model",
- args,
- null,
- Date.now() - start,
- false,
- msg
- );
- return { content: [{ type: "text" as const, text: `Error: ${msg}` }], isError: true };
- }
-}
diff --git a/open-sse/package.json b/open-sse/package.json
index f4e9ce4697..1b03c6aeaf 100644
--- a/open-sse/package.json
+++ b/open-sse/package.json
@@ -1,6 +1,6 @@
{
"name": "@omniroute/open-sse",
- "version": "3.8.44",
+ "version": "3.8.43",
"description": "Express SSE sidecar for OmniRoute — handles streaming, protocol translation, and provider orchestration",
"type": "module",
"main": "index.js",
diff --git a/open-sse/services/accountFallback.ts b/open-sse/services/accountFallback.ts
index 1ade866731..0efddc1762 100644
--- a/open-sse/services/accountFallback.ts
+++ b/open-sse/services/accountFallback.ts
@@ -33,7 +33,6 @@ import { resolveUseUpstream429BreakerHints } from "../../src/shared/utils/provid
import { getCodexModelScope } from "../config/codexQuotaScopes.ts";
import { getQuotaScopedModelForProvider } from "./antigravityQuotaFamily.ts";
import { isRpdExhausted, isRpmExhausted } from "./geminiRateLimitTracker.ts";
-import { parseRetryHintFromJsonBody } from "./retryAfterJson.ts";
export type ProviderProfile = {
baseCooldownMs: number;
@@ -1036,15 +1035,22 @@ function parseDelayString(value: unknown): number | null {
return Number.isNaN(num) ? null : num * 1000;
}
-// T07: parse retry time from error text body with combined "XhYmZs" format.
+/**
+ * T07: Parse retry time from error text body with combined "XhYmZs" format.
+ * Examples: "Your quota will reset after 2h30m14s", "reset after 45m", "reset after 30s"
+ * Returns milliseconds or null if not parseable.
+ *
+ * @param {string} errorText - Error message text from response body
+ * @returns {number|null} Retry duration in milliseconds
+ */
export function parseRetryFromErrorText(errorText: unknown): number | null {
if (!errorText || typeof errorText !== "string") return null;
const msg: string = String(errorText);
- const bodyHintMs = parseRetryHintFromJsonBody(msg, MAX_PROVIDER_COOLDOWN_MS);
- if (bodyHintMs !== null) return bodyHintMs;
-
- // Issue #2321: parse embedded absolute ISO retry timestamps.
+ // Issue #2321: Anthropic OAuth occasionally embeds an absolute ISO 8601
+ // timestamp instead of a relative duration (e.g. "Try again at
+ // 2026-05-17T10:00:00Z" or "Please wait until 2026-05-17T10:00:00.000Z").
+ // Convert to a future-duration in milliseconds if it parses.
const isoMatch =
/\b(?:try again at|wait until|reset(?:s)? at|available at|retry after)\s+(\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}(?::\d{2})?(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?)/i.exec(
msg
diff --git a/open-sse/services/autoCombo/__tests__/speedRanking.test.ts b/open-sse/services/autoCombo/__tests__/speedRanking.test.ts
deleted file mode 100644
index 1599e36b82..0000000000
--- a/open-sse/services/autoCombo/__tests__/speedRanking.test.ts
+++ /dev/null
@@ -1,226 +0,0 @@
-/**
- * Unit tests for the speed-optimized provider×model ranking engine.
- *
- * Covers the pure `rankBySpeed` function used by:
- * - the runtime `LatencyStrategyImpl` (routerStrategy.ts)
- * - the `omniroute_pick_fastest_model` MCP tool
- * - the latency-optimized playground preview (via the same shared core)
- */
-
-import { describe, it, expect } from "vitest";
-import {
- rankBySpeed,
- pickFastest,
- DEFAULT_SPEED_WEIGHTS,
-} from "../speedRanking";
-import type { SpeedCandidate } from "../speedRanking";
-
-function candidate(overrides: Partial<SpeedCandidate> = {}): SpeedCandidate {
- return {
- provider: "anthropic",
- model: "claude-sonnet",
- circuitBreakerState: "CLOSED",
- errorRate: 0,
- failureRate: 0,
- quotaRemaining: 100,
- quotaTotal: 100,
- costPer1MTokens: 3,
- p95LatencyMs: 1000,
- latencyStdDev: 100,
- ...overrides,
- };
-}
-
-describe("rankBySpeed — selection", () => {
- it("returns an empty list when the pool is empty", () => {
- expect(rankBySpeed([])).toEqual([]);
- });
-
- it("filters out OPEN circuit-breaker candidates by default", () => {
- const pool: SpeedCandidate[] = [
- candidate({ provider: "broken", model: "x", circuitBreakerState: "OPEN" }),
- candidate({ provider: "ok", model: "y", avgTtftMs: 200 }),
- ];
- const ranked = rankBySpeed(pool);
- expect(ranked).toHaveLength(1);
- expect(ranked[0].provider).toBe("ok");
- });
-
- it("keeps OPEN candidates when includeUnhealthy is set, sorted to the bottom", () => {
- const pool: SpeedCandidate[] = [
- candidate({ provider: "broken", model: "x", circuitBreakerState: "OPEN" }),
- candidate({ provider: "ok", model: "y", avgTtftMs: 200, avgE2ELatencyMs: 1000 }),
- ];
- const ranked = rankBySpeed(pool, DEFAULT_SPEED_WEIGHTS, { includeUnhealthy: true });
- expect(ranked).toHaveLength(2);
- expect(ranked[0].provider).toBe("ok");
- expect(ranked[1].provider).toBe("broken");
- });
-});
-
-describe("rankBySpeed — metric weighting", () => {
- it("picks the lower-TTFT provider×model when TTFT dominates", () => {
- const fast: SpeedCandidate = candidate({
- provider: "fast",
- model: "m",
- avgTtftMs: 120,
- avgE2ELatencyMs: 1000,
- avgTokensPerSecond: 80,
- p95LatencyMs: 1100,
- });
- const slow: SpeedCandidate = candidate({
- provider: "slow",
- model: "m",
- avgTtftMs: 900,
- avgE2ELatencyMs: 6000,
- avgTokensPerSecond: 20,
- p95LatencyMs: 7000,
- });
- const ranked = rankBySpeed([slow, fast]);
- expect(ranked[0].provider).toBe("fast");
- });
-
- it("penalizes high failure rate so a flaky fast provider loses to a steady slower one", () => {
- const flakyFast: SpeedCandidate = candidate({
- provider: "flaky",
- model: "m",
- avgTtftMs: 250,
- avgE2ELatencyMs: 1500,
- avgTokensPerSecond: 90,
- p95LatencyMs: 1700,
- errorRate: 0.3,
- failureRate: 0.3,
- });
- const steadySlow: SpeedCandidate = candidate({
- provider: "steady",
- model: "m",
- avgTtftMs: 400,
- avgE2ELatencyMs: 2200,
- avgTokensPerSecond: 70,
- p95LatencyMs: 2500,
- errorRate: 0.01,
- failureRate: 0.01,
- });
- const ranked = rankBySpeed([flakyFast, steadySlow]);
- expect(ranked[0].provider).toBe("steady");
- });
-
- it("penalizes high latency stdDev so a bursty fast provider loses to a steady slow one", () => {
- const bursty: SpeedCandidate = candidate({
- provider: "bursty",
- model: "m",
- avgTtftMs: 100,
- avgE2ELatencyMs: 900,
- avgTokensPerSecond: 100,
- p95LatencyMs: 950,
- latencyStdDev: 1500,
- });
- const steady: SpeedCandidate = candidate({
- provider: "steady",
- model: "m",
- avgTtftMs: 350,
- avgE2ELatencyMs: 1500,
- avgTokensPerSecond: 60,
- p95LatencyMs: 1600,
- latencyStdDev: 50,
- });
- const ranked = rankBySpeed([bursty, steady]);
- expect(ranked[0].provider).toBe("steady");
- });
-
- it("rewards higher tokens-per-second when everything else ties", () => {
- const base = {
- avgTtftMs: 300,
- avgE2ELatencyMs: 1500,
- p95LatencyMs: 1600,
- };
- const lowTps: SpeedCandidate = candidate({ provider: "low", model: "m", ...base, avgTokensPerSecond: 20 });
- const highTps: SpeedCandidate = candidate({ provider: "high", model: "m", ...base, avgTokensPerSecond: 200 });
- const ranked = rankBySpeed([lowTps, highTps]);
- expect(ranked[0].provider).toBe("high");
- });
-});
-
-describe("rankBySpeed — factor breakdown", () => {
- it("emits per-factor values in [0..1] and an explanation", () => {
- const ranked = rankBySpeed([
- candidate({
- provider: "a",
- model: "m",
- avgTtftMs: 100,
- avgE2ELatencyMs: 1000,
- avgTokensPerSecond: 100,
- p95LatencyMs: 1100,
- latencyStdDev: 50,
- }),
- ]);
- expect(ranked).toHaveLength(1);
- const factors = ranked[0].factors;
- for (const value of Object.values(factors)) {
- expect(value).toBeGreaterThanOrEqual(0);
- expect(value).toBeLessThanOrEqual(1);
- }
- expect(ranked[0].reason).toMatch(/SpeedRanking\[/);
- expect(ranked[0].reason).toMatch(/ttft=100ms/);
- });
-
- it("falls back to 0.5 per missing metric so new providers are not crushed", () => {
- const ranked = rankBySpeed([candidate({ provider: "fresh", model: "m" })]);
- expect(ranked).toHaveLength(1);
- // No telemetry at all → weighted sum lands near 0.5 with reliability multiplier 1
- expect(ranked[0].factors.reliability).toBe(1);
- expect(ranked[0].factors.health).toBe(1);
- expect(ranked[0].factors.ttft).toBe(0.5);
- expect(ranked[0].factors.tps).toBe(0.5);
- });
-});
-
-describe("rankBySpeed — weight overrides", () => {
- it("respects caller weight overrides (e.g. heavy TTFT bias)", () => {
- const fastTtft: SpeedCandidate = candidate({
- provider: "fast",
- model: "m",
- avgTtftMs: 100,
- avgE2ELatencyMs: 5000,
- avgTokensPerSecond: 5,
- p95LatencyMs: 6000,
- });
- const slowTtft: SpeedCandidate = candidate({
- provider: "slow",
- model: "m",
- avgTtftMs: 800,
- avgE2ELatencyMs: 1200,
- avgTokensPerSecond: 120,
- p95LatencyMs: 1300,
- });
-
- const normal = rankBySpeed([fastTtft, slowTtft]);
- // Normal weights still pick slowTtft because TPS/E2E dominate over TTFT gaps.
- expect(normal[0].provider).toBe("slow");
-
- const heavyTtft = rankBySpeed([fastTtft, slowTtft], {
- ...DEFAULT_SPEED_WEIGHTS,
- ttft: 0.7,
- tps: 0.05,
- e2e: 0.05,
- p95: 0.05,
- health: 0.05,
- reliability: 0.05,
- stability: 0.05,
- });
- expect(heavyTtft[0].provider).toBe("fast");
- });
-});
-
-describe("pickFastest", () => {
- it("returns null on an empty pool", () => {
- expect(pickFastest([])).toBeNull();
- });
-
- it("returns the top-ranked candidate", () => {
- const fast = candidate({ provider: "fast", model: "m", avgTtftMs: 100 });
- const slow = candidate({ provider: "slow", model: "m", avgTtftMs: 900 });
- const winner = pickFastest([slow, fast]);
- expect(winner?.provider).toBe("fast");
- });
-});
\ No newline at end of file
diff --git a/open-sse/services/autoCombo/routerStrategy.ts b/open-sse/services/autoCombo/routerStrategy.ts
index b9923fe470..466d815607 100644
--- a/open-sse/services/autoCombo/routerStrategy.ts
+++ b/open-sse/services/autoCombo/routerStrategy.ts
@@ -14,8 +14,6 @@ import type { ProviderCandidate, ScoredProvider } from "./scoring.ts";
import { scorePool } from "./scoring.ts";
import { getTaskFitness } from "./taskFitness.ts";
import { clamp01 } from "../../utils/number.ts";
-import { rankBySpeed } from "./speedRanking.ts";
-import type { SpeedCandidate } from "./speedRanking.ts";
export interface SlaRoutingPolicy {
targetP95Ms?: number;
@@ -51,36 +49,6 @@ export interface RouterStrategy {
// ── RulesStrategy: wraps 6-factor scoring engine ────────────────────────────
-function toSpeedCandidate(c: ProviderCandidate): SpeedCandidate {
- return {
- // Identity
- provider: c.provider,
- model: c.model,
- // Resource state
- quotaRemaining: c.quotaRemaining,
- quotaTotal: c.quotaTotal,
- circuitBreakerState: c.circuitBreakerState,
- // Costs
- costPer1MTokens: c.costPer1MTokens,
- // Latency metrics
- p95LatencyMs: c.p95LatencyMs,
- avgTtftMs: c.avgTtftMs,
- avgE2ELatencyMs: c.avgE2ELatencyMs,
- avgTokensPerSecond: c.avgTokensPerSecond,
- latencyStdDev: c.latencyStdDev,
- // Reliability
- errorRate: c.errorRate,
- failureRate: c.failureRate,
- // Tier signals (forwarded so weights stay available for downstream tuning)
- accountTier: c.accountTier,
- quotaResetIntervalSecs: c.quotaResetIntervalSecs,
- contextAffinity: c.contextAffinity,
- resetWindowAffinity: c.resetWindowAffinity,
- connectionPoolSize: c.connectionPoolSize,
- connectionId: c.connectionId,
- };
-}
-
class RulesStrategyImpl implements RouterStrategy {
readonly name = "rules";
readonly description =
@@ -132,48 +100,105 @@ class CostStrategyImpl implements RouterStrategy {
// ── LatencyStrategy: prioritize low latency + reliability ───────────────────
+function positiveMetric(value: unknown): number | null {
+ const numericValue = Number(value);
+ return Number.isFinite(numericValue) && numericValue > 0 ? numericValue : null;
+}
+
+function boundedRate(value: unknown): number {
+ const numericValue = Number(value);
+ return Number.isFinite(numericValue) && numericValue >= 0 ? Math.min(1, numericValue) : 0;
+}
+
+function maxPositiveMetric(
+ candidates: ProviderCandidate[],
+ readMetric: (candidate: ProviderCandidate) => unknown,
+ fallback = 1
+): number {
+ return Math.max(
+ ...candidates.map((candidate) => positiveMetric(readMetric(candidate)) ?? 0),
+ fallback
+ );
+}
+
+function latencyMetricScore(value: number | null, maxValue: number): number {
+ if (value == null) return 0.5;
+ return inverseNormalized(value, maxValue);
+}
+
+function throughputMetricScore(value: number | null, maxValue: number): number {
+ if (value == null) return 0.5;
+ return clamp01(value / Math.max(maxValue, 0.000_001));
+}
+
class LatencyStrategyImpl implements RouterStrategy {
readonly name = "latency";
readonly description =
"Prioritizes the fastest reliable provider-model pair using TTFT, TPS, E2E latency, health, fail rate, and stability";
select(pool: ProviderCandidate[], context: RoutingContext): RoutingDecision {
- const ranked = rankBySpeed(pool.map(toSpeedCandidate));
- const winner = ranked[0];
- if (!winner) {
- throw new Error("[LatencyStrategy] No candidates available after speed ranking");
- }
+ const healthy = pool.filter((c) => c.circuitBreakerState !== "OPEN");
+ const candidates = healthy.length > 0 ? healthy : pool;
+ if (candidates.length === 0) throw new Error("[LatencyStrategy] No candidates available");
+
+ const maxP95 = maxPositiveMetric(candidates, (candidate) => candidate.p95LatencyMs);
+ const maxTtft = maxPositiveMetric(
+ candidates,
+ (candidate) => candidate.avgTtftMs ?? candidate.p95LatencyMs
+ );
+ const maxE2E = maxPositiveMetric(
+ candidates,
+ (candidate) => candidate.avgE2ELatencyMs ?? candidate.p95LatencyMs
+ );
+ const maxTps = maxPositiveMetric(candidates, (candidate) => candidate.avgTokensPerSecond);
+ const maxStdDev = maxPositiveMetric(candidates, (candidate) => candidate.latencyStdDev, 0.001);
+
+ const scored = candidates
+ .map((candidate) => {
+ const p95 = positiveMetric(candidate.p95LatencyMs);
+ const ttft = positiveMetric(candidate.avgTtftMs) ?? p95;
+ const e2e = positiveMetric(candidate.avgE2ELatencyMs) ?? p95;
+ const tps = positiveMetric(candidate.avgTokensPerSecond);
+ const failureRate = boundedRate(candidate.failureRate ?? candidate.errorRate);
+ const healthScore = getHealthScore(candidate);
+ const p95Score = latencyMetricScore(p95, maxP95);
+ const ttftScore = latencyMetricScore(ttft, maxTtft);
+ const e2eScore = latencyMetricScore(e2e, maxE2E);
+ const throughputScore = throughputMetricScore(tps, maxTps);
+ const reliabilityScore = 1 - failureRate;
+ const stabilityScore = latencyMetricScore(
+ positiveMetric(candidate.latencyStdDev),
+ maxStdDev
+ );
+ const rawScore =
+ ttftScore * 0.25 +
+ throughputScore * 0.2 +
+ e2eScore * 0.18 +
+ p95Score * 0.12 +
+ reliabilityScore * 0.15 +
+ healthScore * 0.05 +
+ stabilityScore * 0.05;
+ const reliabilityMultiplier = Math.max(0.05, reliabilityScore * reliabilityScore);
+ const score = rawScore * reliabilityMultiplier * Math.max(0.25, healthScore);
+
+ return { candidate, score, ttft, e2e, tps, failureRate };
+ })
+ .sort((a, b) => b.score - a.score);
+
+ const best = scored[0];
+ if (!best) throw new Error("[LatencyStrategy] No candidates available");
return {
- provider: winner.provider,
- model: winner.model,
+ provider: best.candidate.provider,
+ model: best.candidate.model,
strategy: this.name,
- reason: latencyDecisionReason(winner),
- candidatesConsidered: ranked.length,
- finalScore: winner.score,
+ reason: `LatencyStrategy: ttft=${best.ttft ?? "n/a"}ms, tps=${best.tps ?? "n/a"}, e2e=${best.e2e ?? "n/a"}ms, p95=${best.candidate.p95LatencyMs}ms, failRate=${(best.failureRate * 100).toFixed(2)}%`,
+ candidatesConsidered: candidates.length,
+ finalScore: best.score,
};
}
}
-function metricString(value: number | null | undefined, digits = 0): string {
- return value == null ? "n/a" : value.toFixed(digits);
-}
-
-function latencyDecisionReason(winner: ReturnType<typeof rankBySpeed>[number]): string {
- const metrics = winner.metrics;
- const e2e = metrics.avgE2ELatencyMs ?? metrics.p95LatencyMs;
- return (
- `LatencyStrategy(score=${winner.score.toFixed(3)}): ` +
- `ttft=${metricString(metrics.avgTtftMs)}ms ` +
- `tps=${metricString(metrics.avgTokensPerSecond, 1)} ` +
- `e2e=${metricString(e2e)}ms ` +
- `p95=${metricString(metrics.p95LatencyMs)}ms ` +
- `failRate=${((metrics.failureRate ?? 0) * 100).toFixed(2)}% ` +
- `stability=${metricString(metrics.latencyStdDev)}ms ` +
- `cb=${metrics.circuitBreakerState ?? "n/a"}`
- );
-}
-
// ── SLAStrategy: favor targets that meet latency/error/cost SLOs ───────────
const DEFAULT_SLA_TARGET_P95_MS = 2_000;
diff --git a/open-sse/services/autoCombo/speedRanking.ts b/open-sse/services/autoCombo/speedRanking.ts
deleted file mode 100644
index 514420a5a0..0000000000
--- a/open-sse/services/autoCombo/speedRanking.ts
+++ /dev/null
@@ -1,327 +0,0 @@
-/**
- * Speed-optimized Provider×Model Ranking
- *
- * Pure, framework-free scoring function that ranks provider×model candidates by
- * the speed/reliability combination most likely to make a request feel "fast":
- *
- * - lower avg Time-To-First-Token (TTFT) — perceived responsiveness
- * - higher avg tokens-per-second (TPS) — generation throughput
- * - lower avg end-to-end (E2E) latency — full completion time
- * - lower p95 latency — tail-risk backup metric
- * - higher circuit-breaker health — must be reachable
- * - lower failure / error rate — speed without flake
- * - lower latency standard deviation (stability)— consistent, not bursty
- *
- * Every metric is optional; missing telemetry is treated as the pool median
- * (i.e. 0.5 in [0..1]) so a brand-new provider/model does not get crushed, but
- * also does not get a free pass on a metric we have no data for. This mirrors
- * the behavior of the existing `LatencyStrategyImpl` and is intentional — the
- * function is the canonical ranking for the "fastest reliable provider-model"
- * UX in the playground + MCP `omniroute_pick_fastest_model` tool, and is
- * reused by the runtime `LatencyStrategyImpl` so the runtime router picks the
- * same winner as the user-facing preview.
- *
- * Optional weights override defaults so callers (tests, dashboards, future
- * `modePacks.speed-first`) can rebalance without duplicating the math.
- */
-
-import type { ProviderCandidate } from "./scoring.ts";
-
-/** Optional per-candidate telemetry surfaced by the ranking. */
-export interface SpeedCandidate extends ProviderCandidate {
- /** Numeric health score [0..1]; computed from circuitBreakerState when missing. */
- health?: number;
- /** Percentage quota remaining in [0..100]. Falls back to quotaRemaining. */
- quotaRemainingPct?: number;
- /** Numeric capacity score [0..1] in case the caller wants to expose it. */
- capacityScore?: number;
- /** Cached cost-per-1k tokens (denormalized from costPer1MTokens). */
- costPer1k?: number;
- /** Optional quality score for the candidate (e.g. eval benchmark). */
- qualityScore?: number;
- /** Optional strategic boost applied for premium/internal models. */
- strategicBoost?: number;
- /** Optional SLO-violation penalty that should be subtracted from the raw score. */
- sloPenalty?: number;
-}
-
-/** Per-factor contribution of a single candidate (each value clamped to [0..1]). */
-export interface SpeedFactors {
- ttft: number;
- tps: number;
- e2e: number;
- p95: number;
- health: number;
- reliability: number;
- stability: number;
-}
-
-/** Result of ranking a pool of candidates. */
-export interface SpeedRankedCandidate {
- provider: string;
- model: string;
- /** Final composite score in [0..1]; higher is faster+more-reliable. */
- score: number;
- factors: SpeedFactors;
- /** Raw telemetry we observed for the candidate (in provider-native units). */
- metrics: {
- avgTtftMs: number | null;
- avgTokensPerSecond: number | null;
- avgE2ELatencyMs: number | null;
- p95LatencyMs?: number | null;
- latencyStdDev: number | null;
- failureRate: number;
- circuitBreakerState: SpeedCandidate["circuitBreakerState"];
- };
- /** Human-readable explanation of why this candidate earned its score. */
- reason: string;
-}
-
-/** Caller-tunable weights; defaults are documented at each property. */
-export interface SpeedRankingWeights {
- /** Weight for TTFT (default 0.25). */
- ttft: number;
- /** Weight for tokens/sec (default 0.20). */
- tps: number;
- /** Weight for end-to-end latency (default 0.18). */
- e2e: number;
- /** Weight for p95 latency fallback (default 0.12). */
- p95: number;
- /** Weight for circuit-breaker health (default 0.05). */
- health: number;
- /** Weight for reliability = 1 - failureRate (default 0.15). */
- reliability: number;
- /** Weight for latency stability / low std-dev (default 0.05). */
- stability: number;
-}
-
-/**
- * Default weights — these sum to 1.0 and bias toward perceived speed (TTFT +
- * TPS together account for 45% of the score) while still penalizing unsafe
- * providers. They are deliberately exported so the playground UI can render
- * the formula and tests can pin it.
- */
-export const DEFAULT_SPEED_WEIGHTS: SpeedRankingWeights = {
- ttft: 0.25,
- tps: 0.2,
- e2e: 0.18,
- p95: 0.12,
- health: 0.05,
- reliability: 0.15,
- stability: 0.05,
-};
-
-/** Human-readable label for each weight key — used in `reason` strings. */
-const FACTOR_LABEL: Record<keyof SpeedRankingWeights, string> = {
- ttft: "ttft",
- tps: "tps",
- e2e: "e2e",
- p95: "p95",
- health: "health",
- reliability: "reliability",
- stability: "stability",
-};
-
-function clamp01(value: number): number {
- if (!Number.isFinite(value)) return 0;
- if (value < 0) return 0;
- if (value > 1) return 1;
- return value;
-}
-
-function positiveFinite(value: number | null | undefined): number | null {
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : null;
-}
-
-function toBoundedRate(value: number | null | undefined): number {
- if (typeof value !== "number" || !Number.isFinite(value) || value < 0) return 0;
- return Math.min(1, value);
-}
-
-/**
- * Pool-relative maximum for "lower is better" metrics. Returns at least
- * `floor` so a candidate with the only positive measurement does not divide
- * by zero.
- */
-function poolMax<T>(
- values: ReadonlyArray<T>,
- readMetric: (value: T) => number | null,
- floor = 1
-): number {
- let max = floor;
- for (const value of values) {
- const v = readMetric(value);
- if (v != null && v > max) max = v;
- }
- return max;
-}
-
-/**
- * Pool-relative maximum for "higher is better" metrics. Returns at least
- * `floor` so a missing metric does not yield Infinity downstream.
- */
-function poolMaxHigherBetter<T>(
- values: ReadonlyArray<T>,
- readMetric: (value: T) => number | null,
- floor = 0.000_001
-): number {
- let max = floor;
- for (const value of values) {
- const v = readMetric(value);
- if (v != null && v > max) max = v;
- }
- return max;
-}
-
-/** 1 - (value / max), clamped to [0..1]. Missing → 0.5 (pool median). */
-function lowerIsBetter(value: number | null | undefined, max: number): number {
- if (value == null) return 0.5;
- if (!Number.isFinite(value) || value < 0) return 0;
- if (!Number.isFinite(max) || max <= 0) return 1;
- return clamp01(1 - value / max);
-}
-
-/** value / max, clamped to [0..1]. Missing → 0.5. */
-function higherIsBetter(value: number | null | undefined, max: number): number {
- if (value == null) return 0.5;
- if (!Number.isFinite(value) || value < 0) return 0;
- if (!Number.isFinite(max) || max <= 0) return 0;
- return clamp01(value / max);
-}
-
-function healthScoreFor(state: SpeedCandidate["circuitBreakerState"]): number {
- if (state === "CLOSED") return 1;
- if (state === "HALF_OPEN") return 0.5;
- return 0; // OPEN — caller is expected to filter these out beforehand, but be defensive.
-}
-
-function speedPoolMaxima(pool: ReadonlyArray<SpeedCandidate>) {
- return {
- ttft: poolMax(pool, (c) => positiveFinite(c.avgTtftMs) ?? positiveFinite(c.p95LatencyMs)),
- e2e: poolMax(pool, (c) => positiveFinite(c.avgE2ELatencyMs) ?? positiveFinite(c.p95LatencyMs)),
- p95: poolMax(pool, (c) => positiveFinite(c.p95LatencyMs)),
- tps: poolMaxHigherBetter(pool, (c) => positiveFinite(c.avgTokensPerSecond)),
- stdDev: poolMax(pool, (c) => positiveFinite(c.latencyStdDev), 0.001),
- };
-}
-
-function speedFactorsFor(
- candidate: SpeedCandidate,
- maxima: ReturnType<typeof speedPoolMaxima>,
- failureRate: number
-): SpeedFactors {
- return {
- ttft: lowerIsBetter(positiveFinite(candidate.avgTtftMs), maxima.ttft),
- tps: higherIsBetter(positiveFinite(candidate.avgTokensPerSecond), maxima.tps),
- e2e: lowerIsBetter(positiveFinite(candidate.avgE2ELatencyMs), maxima.e2e),
- p95: lowerIsBetter(positiveFinite(candidate.p95LatencyMs), maxima.p95),
- health: healthScoreFor(candidate.circuitBreakerState),
- reliability: clamp01(1 - failureRate),
- stability: lowerIsBetter(positiveFinite(candidate.latencyStdDev), maxima.stdDev),
- };
-}
-
-function weightedSpeedScore(factors: SpeedFactors, weights: SpeedRankingWeights): number {
- return (
- factors.ttft * weights.ttft +
- factors.tps * weights.tps +
- factors.e2e * weights.e2e +
- factors.p95 * weights.p95 +
- factors.health * weights.health +
- factors.reliability * weights.reliability +
- factors.stability * weights.stability
- );
-}
-
-function applySpeedPenalties(weightedSum: number, factors: SpeedFactors): number {
- const reliabilityMultiplier = Math.max(0.05, Math.pow(0.25 + 0.75 * factors.reliability, 2));
- const stabilityMultiplier = Math.max(0.05, Math.pow(0.25 + 0.75 * factors.stability, 2));
- return clamp01(weightedSum * reliabilityMultiplier * stabilityMultiplier * Math.max(0.25, factors.health));
-}
-
-function speedReason(candidate: SpeedCandidate, factors: SpeedFactors, metrics: SpeedRankedCandidate["metrics"]): string {
- const reasonParts = [
- `ttft=${metrics.avgTtftMs == null ? "n/a" : `${Math.round(metrics.avgTtftMs)}ms`}`,
- `tps=${metrics.avgTokensPerSecond == null ? "n/a" : metrics.avgTokensPerSecond.toFixed(1)}`,
- `e2e=${metrics.avgE2ELatencyMs == null ? "n/a" : `${Math.round(metrics.avgE2ELatencyMs)}ms`}`,
- `p95=${metrics.p95LatencyMs == null ? "n/a" : `${Math.round(metrics.p95LatencyMs)}ms`}`,
- `failRate=${(metrics.failureRate * 100).toFixed(2)}%`,
- `cb=${candidate.circuitBreakerState}`,
- ];
- return `SpeedRanking[${FACTOR_LABEL.ttft}=${factors.ttft.toFixed(2)}, ${FACTOR_LABEL.tps}=${factors.tps.toFixed(2)}, ${FACTOR_LABEL.e2e}=${factors.e2e.toFixed(2)}, ${FACTOR_LABEL.p95}=${factors.p95.toFixed(2)}, ${FACTOR_LABEL.reliability}=${factors.reliability.toFixed(2)}, ${FACTOR_LABEL.health}=${factors.health.toFixed(2)}, ${FACTOR_LABEL.stability}=${factors.stability.toFixed(2)}] → ${reasonParts.join(", ")}`;
-}
-
-/**
- * Rank candidates for the speed-optimized routing mode.
- *
- * @param candidates Pool of provider×model candidates (typically the candidates
- * inside an auto combo's provider pool, or any list assembled by the
- * playground / MCP tool).
- * @param weights Optional weight overrides — defaults to {@link DEFAULT_SPEED_WEIGHTS}.
- * @param options.includeUnhealthy If false (default), OPEN circuit-breaker
- * candidates are dropped before scoring. If true, they are scored with a
- * health factor of 0 and a reliability factor of 0 so they sort to the
- * bottom without changing the rest of the ranking.
- * @returns The full ranked list, highest score first. The first entry is the
- * "fastest reliable provider-model pair" for this pool.
- */
-export function rankBySpeed(
- candidates: ReadonlyArray<SpeedCandidate>,
- weights: SpeedRankingWeights = DEFAULT_SPEED_WEIGHTS,
- options: { includeUnhealthy?: boolean } = {}
-): SpeedRankedCandidate[] {
- if (candidates.length === 0) return [];
-
- const pool = options.includeUnhealthy
- ? [...candidates]
- : candidates.filter((c) => c.circuitBreakerState !== "OPEN");
- if (pool.length === 0) return [];
-
- const maxima = speedPoolMaxima(pool);
-
- const ranked = pool.map((candidate) => {
- const p95 = positiveFinite(candidate.p95LatencyMs);
- const ttft = positiveFinite(candidate.avgTtftMs);
- const e2e = positiveFinite(candidate.avgE2ELatencyMs);
- const tps = positiveFinite(candidate.avgTokensPerSecond);
- const stdDev = positiveFinite(candidate.latencyStdDev);
- const failureRate = toBoundedRate(
- candidate.failureRate ?? (typeof candidate.errorRate === "number" ? candidate.errorRate : 0)
- );
- const factors = speedFactorsFor(candidate, maxima, failureRate);
- const score = applySpeedPenalties(weightedSpeedScore(factors, weights), factors);
- const metrics = {
- avgTtftMs: ttft,
- avgTokensPerSecond: tps,
- avgE2ELatencyMs: e2e,
- p95LatencyMs: p95,
- latencyStdDev: stdDev,
- failureRate,
- circuitBreakerState: candidate.circuitBreakerState,
- };
-
- return {
- provider: candidate.provider,
- model: candidate.model,
- score,
- factors,
- metrics,
- reason: speedReason(candidate, factors, metrics),
- };
- });
-
- return ranked.sort((a, b) => b.score - a.score);
-}
-
-/**
- * Convenience selector — returns the top-ranked candidate or `null` when the
- * pool is empty. Used by the runtime `LatencyStrategyImpl` and the MCP
- * `omniroute_pick_fastest_model` tool when only the winner is needed.
- */
-export function pickFastest(
- candidates: ReadonlyArray<SpeedCandidate>,
- weights: SpeedRankingWeights = DEFAULT_SPEED_WEIGHTS
-): SpeedRankedCandidate | null {
- const ranked = rankBySpeed(candidates, weights);
- return ranked.length > 0 ? ranked[0] : null;
-}
diff --git a/open-sse/services/claudeCodeCompatible.ts b/open-sse/services/claudeCodeCompatible.ts
index 4fd5f22711..c9fd70f58f 100644
--- a/open-sse/services/claudeCodeCompatible.ts
+++ b/open-sse/services/claudeCodeCompatible.ts
@@ -54,7 +54,6 @@ const CLAUDE_CODE_COMPATIBLE_DEFAULT_SYSTEM_BLOCKS = [
];
const CONTEXT_1M_SUPPORTED_MODELS = [
"claude-fable-5",
- "claude-sonnet-5",
"claude-opus-4-8",
"claude-opus-4-7",
"claude-opus-4-6",
@@ -176,12 +175,13 @@ export function buildClaudeCodeCompatibleHeaders(
sessionId?: string | null,
options: { redactThinking?: boolean } = {}
): Record<string, string> {
+ void stream;
// These headers intentionally mirror Claude Code's wire image closely.
// For CC-compatible relays, passing the upstream's client-gating checks is
// more important than forwarding arbitrary caller-specific header shapes.
return {
"Content-Type": "application/json",
- Accept: stream ? "text/event-stream" : "application/json",
+ Accept: "application/json",
Authorization: `Bearer ${apiKey}`,
"anthropic-version": CLAUDE_CODE_COMPATIBLE_ANTHROPIC_VERSION,
"anthropic-beta": resolveClaudeCodeCompatibleAnthropicBeta({
diff --git a/open-sse/services/clinepassModels.ts b/open-sse/services/clinepassModels.ts
deleted file mode 100644
index ee25f6e8e5..0000000000
--- a/open-sse/services/clinepassModels.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-import { buildClineHeaders } from "@/shared/utils/clineAuth";
-
-// ClinePass live-models resolver. ClinePass is API-key-only (BYOK), but the
-// underlying api.cline.bot host also accepts the OAuth `cline` credential shape,
-// so the resolver reuses buildClineHeaders() (the shared workos:-prefixed Cline
-// header set) for the non-apikey path. Only `cline-pass/*` model ids are kept.
-
-const CLINEPASS_MODELS_ENDPOINT = "https://api.cline.bot/api/v1/models";
-const FETCH_TIMEOUT_MS = 5000;
-
-export interface ClinepassModel {
- id: string;
- name: string;
-}
-
-/**
- * Filter a raw models list down to the ClinePass namespace (`cline-pass/*`).
- * Pure — shared by the live resolver and the discovery-config parseResponse.
- */
-export function filterClinepassModels(rawList: unknown): ClinepassModel[] {
- if (!Array.isArray(rawList)) return [];
- return rawList
- .filter(
- (m): m is { id: string; name?: string } =>
- !!m &&
- typeof (m as { id?: unknown }).id === "string" &&
- (m as { id: string }).id.startsWith("cline-pass/")
- )
- .map((m) => ({ id: m.id, name: m.name || m.id }));
-}
-
-function buildModelListHeaders(token: string, isApiKey: boolean): Record<string, string> {
- if (isApiKey) {
- return {
- Accept: "application/json",
- Authorization: `Bearer ${token}`,
- };
- }
- return buildClineHeaders(token, { Accept: "application/json" });
-}
-
-/**
- * Resolve the live ClinePass model catalogue for a connection. Returns
- * `{ models }` on success or `null` on any failure (missing token, non-2xx,
- * bad shape, timeout) so callers fall back to the static registry catalogue.
- */
-export async function resolveClinepassModels(credentials: {
- apiKey?: string | null;
- accessToken?: string | null;
-}): Promise<{ models: ClinepassModel[] } | null> {
- const isApiKey = Boolean(credentials?.apiKey);
- const token = isApiKey ? credentials.apiKey : credentials?.accessToken;
- if (!token) return null;
-
- const controller = new AbortController();
- const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
-
- try {
- const headers = buildModelListHeaders(token, isApiKey);
- const response = await fetch(CLINEPASS_MODELS_ENDPOINT, {
- method: "GET",
- headers,
- signal: controller.signal,
- });
- if (!response.ok) return null;
-
- const json = await response.json();
- const rawList = Array.isArray(json) ? json : json?.data;
- const models = filterClinepassModels(rawList);
- return models.length ? { models } : null;
- } catch {
- return null;
- } finally {
- clearTimeout(timer);
- }
-}
diff --git a/open-sse/services/codexQuotaFetcher.ts b/open-sse/services/codexQuotaFetcher.ts
index 0cb914e884..8a2ed5e859 100644
--- a/open-sse/services/codexQuotaFetcher.ts
+++ b/open-sse/services/codexQuotaFetcher.ts
@@ -49,13 +49,6 @@ export interface CodexDualWindowQuota extends QuotaInfo {
limitReached: boolean;
/** All known Codex quota windows, including Spark when the upstream exposes it. */
allWindows?: Record<string, { percentUsed: number; resetAt: string | null }>;
- /**
- * Banked reset credits available on the account (display-only, issue #5199).
- * Eligibility-gated: absent for most accounts. Never throws when missing.
- */
- bankedResetCredits?: number;
- /** Which window is currently reported as blocking, when the upstream exposes it. */
- rateLimitReachedType?: string;
}
interface CacheEntry {
@@ -302,26 +295,6 @@ function parseCodexWindow(
return { percentUsed, resetAt: parseWindowReset(window) };
}
-/**
- * Codex "banked reset credits" — same eligibility-gated field parsed in
- * codexUsageQuotas.ts (kept in sync manually; the two parsers read the same
- * /wham/usage payload independently). DISPLAY ONLY, never throws.
- */
-function parseBankedResetCredits(data: Record<string, unknown>): number | undefined {
- const resetCredits = toRecord(data["rate_limit_reset_credits"] ?? data["rateLimitResetCredits"]);
- const availableCount = resetCredits["available_count"] ?? resetCredits["availableCount"];
- const count = toNumber(availableCount, NaN);
- return Number.isFinite(count) ? count : undefined;
-}
-
-function parseRateLimitReachedType(data: Record<string, unknown>): string | undefined {
- const reachedType = data["rate_limit_reached_type"] ?? data["rateLimitReachedType"];
- if (typeof reachedType === "string" && reachedType.trim().length > 0) return reachedType.trim();
- const reachedTypeObj = toRecord(reachedType);
- const type = reachedTypeObj["type"];
- return typeof type === "string" && type.trim().length > 0 ? type.trim() : undefined;
-}
-
function findSparkRateLimit(data: Record<string, unknown>): Record<string, unknown> | null {
const additional = data["additional_rate_limits"] ?? data["additionalRateLimits"];
if (!Array.isArray(additional)) return null;
@@ -430,9 +403,6 @@ function parseCodexUsageResponse(
secondary: CODEX_WINDOW_WEEKLY,
});
- const bankedResetCredits = parseBankedResetCredits(obj);
- const rateLimitReachedType = parseRateLimitReachedType(obj);
-
return {
used: Math.round(worstPercentUsed * 100),
total: 100,
@@ -449,9 +419,6 @@ function parseCodexUsageResponse(
window5h,
window7d,
limitReached,
- // Banked reset credits (display-only, eligibility-gated — issue #5199).
- ...(bankedResetCredits !== undefined ? { bankedResetCredits } : {}),
- ...(rateLimitReachedType !== undefined ? { rateLimitReachedType } : {}),
};
}
diff --git a/open-sse/services/codexUsageQuotas.ts b/open-sse/services/codexUsageQuotas.ts
index 4d0bc0d857..6696daca0b 100644
--- a/open-sse/services/codexUsageQuotas.ts
+++ b/open-sse/services/codexUsageQuotas.ts
@@ -160,43 +160,13 @@ function findCodexReviewRateLimit(data: JsonRecord): JsonRecord {
return {};
}
-/**
- * Codex "banked reset credits" — an eligibility-gated field some ChatGPT plans
- * expose on the /wham/usage payload: a count of extra rate-limit resets the
- * account has banked (available_count), plus an optional descriptor of which
- * window is currently blocking (rate_limit_reached_type). DISPLAY ONLY — this
- * reads the field defensively (many accounts will not have it) and never
- * throws; redemption is an unofficial mutating endpoint and out of scope
- * (issue #5199).
- */
-function parseBankedResetCredits(data: JsonRecord): number | undefined {
- const resetCredits = toRecord(getFieldValue(data, "rate_limit_reset_credits", "rateLimitResetCredits"));
- const availableCount = getFieldValue(resetCredits, "available_count", "availableCount");
- const count = toNumber(availableCount, NaN);
- return Number.isFinite(count) ? count : undefined;
-}
-
-function parseRateLimitReachedType(data: JsonRecord): string | undefined {
- const reachedType = getFieldValue(data, "rate_limit_reached_type", "rateLimitReachedType");
- if (typeof reachedType === "string" && reachedType.trim().length > 0) return reachedType.trim();
- const reachedTypeObj = toRecord(reachedType);
- const type = getFieldValue(reachedTypeObj, "type");
- return typeof type === "string" && type.trim().length > 0 ? type.trim() : undefined;
-}
-
export function buildCodexUsageQuotas(dataValue: unknown): {
rateLimit: JsonRecord;
quotas: Record<string, CodexUsageQuota>;
- /** Banked reset credits available on the account (undefined when absent/not eligible). */
- bankedResetCredits?: number;
- /** Which window is currently reported as blocking, when the upstream exposes it. */
- rateLimitReachedType?: string;
} {
const data = toRecord(dataValue);
const rateLimit = toRecord(getFieldValue(data, "rate_limit", "rateLimit"));
const quotas: Record<string, CodexUsageQuota> = {};
- const bankedResetCredits = parseBankedResetCredits(data);
- const rateLimitReachedType = parseRateLimitReachedType(data);
const primaryWindow = toRecord(getFieldValue(rateLimit, "primary_window", "primaryWindow"));
if (Object.keys(primaryWindow).length > 0) quotas.session = buildPercentageQuota(primaryWindow);
@@ -261,10 +231,5 @@ export function buildCodexUsageQuotas(dataValue: unknown): {
);
}
- return {
- rateLimit,
- quotas,
- ...(bankedResetCredits !== undefined ? { bankedResetCredits } : {}),
- ...(rateLimitReachedType !== undefined ? { rateLimitReachedType } : {}),
- };
+ return { rateLimit, quotas };
}
diff --git a/open-sse/services/codexVerbosity.ts b/open-sse/services/codexVerbosity.ts
index 96cc441faa..8b530038c6 100644
--- a/open-sse/services/codexVerbosity.ts
+++ b/open-sse/services/codexVerbosity.ts
@@ -9,8 +9,9 @@
*
* This helper runs on the translated path (before the allowlist) and folds whichever
* shape arrived into a single, validated `text:{verbosity}`. `text` is then added to
- * the allowlist so the hint survives. Other Responses `text` keys, such as
- * `text.format` for structured output, are preserved.
+ * the allowlist so the hint survives. Non-verbosity `text` keys (e.g. a stray
+ * `text.format`) are intentionally dropped — they were already stripped by the
+ * pre-existing allowlist, so this preserves the status quo while adding verbosity.
*
* Ref: OpenAI GPT-5 docs (text.verbosity), Azure Foundry reasoning guide.
*/
@@ -32,8 +33,8 @@ function normalizeLevel(value: unknown): string | undefined {
/**
* Mutates `body` in place: resolves verbosity from `text.verbosity` (Responses) or
* the top-level `verbosity` (Chat Completions, which takes precedence when both are
- * present), drops the Chat-only top-level field, and preserves any other existing
- * Responses `text` configuration.
+ * present), drops the Chat-only top-level field, and collapses `text` to
+ * `{verbosity}` when valid or removes it otherwise.
*/
export function normalizeCodexVerbosity(body: Record<string, unknown>): void {
const textRecord = asRecord(body.text);
@@ -44,15 +45,8 @@ export function normalizeCodexVerbosity(body: Record<string, unknown>): void {
delete body.verbosity;
- const nextText = textRecord ? { ...textRecord } : {};
if (verbosity) {
- nextText.verbosity = verbosity;
- } else {
- delete nextText.verbosity;
- }
-
- if (Object.keys(nextText).length > 0) {
- body.text = nextText;
+ body.text = { verbosity };
} else {
delete body.text;
}
diff --git a/open-sse/services/combo.ts b/open-sse/services/combo.ts
index 4ce9712934..c99c9bbd1d 100644
--- a/open-sse/services/combo.ts
+++ b/open-sse/services/combo.ts
@@ -18,8 +18,12 @@ import {
selectLockoutCooldownMs,
} from "./accountFallback.ts";
import { errorResponse, unavailableResponse } from "../utils/error.ts";
-import { buildTargetTimeoutRunner } from "./combo/targetTimeoutRunner.ts";
-import { recordComboRequest, recordComboShadowRequest, getComboMetrics } from "./comboMetrics.ts";
+import {
+ recordComboIntent,
+ recordComboRequest,
+ recordComboShadowRequest,
+ getComboMetrics,
+} from "./comboMetrics.ts";
import {
resolveComboConfig,
getDefaultComboConfig,
@@ -41,7 +45,12 @@ import { extractSessionAffinityKey } from "@/sse/services/auth";
import { getHiddenModelsByProvider } from "@/models";
import { resolveModelLockoutSettings } from "../../src/lib/resilience/modelLockoutSettings";
import { fetchCodexQuota } from "./codexQuotaFetcher.ts";
-import { evaluateQuotaCutoff, getQuotaFetcher, type QuotaInfo } from "./quotaPreflight.ts";
+import {
+ evaluateQuotaCutoff,
+ getQuotaFetcher,
+ type PreflightQuotaThresholds,
+ type QuotaInfo,
+} from "./quotaPreflight.ts";
import * as semaphore from "./rateLimitSemaphore.ts";
import { getCircuitBreaker } from "../../src/shared/utils/circuitBreaker";
import { fisherYatesShuffle, getNextFromDeck } from "../../src/shared/utils/shuffleDeck";
@@ -51,18 +60,31 @@ import { phaseComboSetup } from "./combo/comboSetup.ts";
import { checkCredentialGate, logCredentialSkip } from "./credentialGate.ts";
import { emit } from "../../src/lib/events/eventBus";
import { notifyWebhookEvent } from "../../src/lib/webhookDispatcher";
+import { classifyWithConfig } from "./intentClassifier.ts";
+import { selectProvider as selectAutoProvider } from "./autoCombo/engine.ts";
+import { selectWithStrategy } from "./autoCombo/routerStrategy.ts";
import { parseAutoPrefix } from "./autoCombo/autoPrefix.ts";
-import { resolveAutoStrategyOrder } from "./combo/resolveAutoStrategy.ts";
-import { applyStrategyOrdering } from "./combo/applyStrategyOrdering.ts";
import { handlePipelineCombo, buildPipelineResponse } from "./autoCombo/pipelineRouter.ts";
-import { type ProviderCandidate } from "./autoCombo/scoring.ts";
+import {
+ DEFAULT_WEIGHTS,
+ type ProviderCandidate,
+ type ScoringWeights,
+} from "./autoCombo/scoring.ts";
+import { supportsToolCalling } from "./modelCapabilities.ts";
import { estimateTokens } from "./contextManager.ts";
import { getSessionConnection } from "./sessionManager.ts";
import { applySessionStickiness, recordStickyBinding } from "./combo/sessionStickiness.ts";
import { selectQuotaShareTarget } from "./combo/quotaShareStrategy.ts";
-import { makeConnectionConcurrencyResolver, lookupPositiveCap } from "./combo/concurrencyCaps.ts";
+import {
+ resolveMaxConcurrentByConnection,
+ makeConnectionConcurrencyResolver,
+ lookupPositiveCap,
+} from "./combo/concurrencyCaps.ts";
import { acquireQuotaShareConcurrencySlot } from "./combo/quotaShareConcurrency.ts";
import { orderTargetsByEvalScores } from "./evalRouting.ts";
+import { generateRoutingHints } from "./manifestAdapter";
+import type { RoutingHint } from "./manifestAdapter";
+import { buildComplexityRoutingHint } from "./autoCombo/complexityRouter";
import type { CompressionMode } from "./compression/types.ts";
import { getProviderConnections } from "../../src/lib/db/providers";
import {
@@ -127,42 +149,52 @@ import {
} from "./combo/comboPredicates.ts";
import { applyComboTargetExhaustion } from "./combo/targetExhaustion.ts";
import { executeRuntimeUnitCombo } from "./combo/runtimeUnits.ts";
-import { isRecord } from "./combo/comboData.ts";
+import { dedupeTargetsByExecutionKey, isRecord } from "./combo/comboData.ts";
import {
expandProviderWildcardsInCombo,
expandProviderWildcardsInCollection,
} from "./combo/providerWildcard.ts";
import { resolveShadowTargets, scheduleShadowRouting } from "./combo/shadowRouting.ts";
+import {
+ sortTargetsByCost,
+ sortTargetsByUsage,
+ orderTargetsByPowerOfTwoChoices,
+} from "./combo/targetSorters.ts";
import {
filterTargetsByRequestCompatibility,
+ getModelContextLimitForModelString,
resolveComboRuntimeUnits,
resolveComboTargets,
resolveWeightedTargets,
resolveWeightedStepGroups,
+ sortTargetsByContextSize,
} from "./combo/comboStructure.ts";
import {
QUOTA_SOFT_DEPRIORITIZE_FACTOR,
setCandidateQuotaSoftPenalty,
_registerExecutionCandidates,
_unregisterExecutionCandidates,
+ extractPromptForIntent,
+ mapIntentToTaskType,
+ getIntentConfig,
applyRequestTagRouting,
scoreAutoTargets,
expandAutoComboCandidatePool,
} from "./combo/autoStrategy.ts";
import {
resolveResetWindowConfig,
+ resolveSlaRoutingPolicy,
calculateResetWindowAffinity,
type ResetWindowConfig,
} from "./combo/quotaScoring.ts";
import {
fetchResetAwareQuotaWithCache,
preScreenTargets,
+ orderTargetsByResetAwareQuota,
+ orderTargetsByResetWindow,
+ orderTargetsByHeadroom,
type PreScreenResult,
} from "./combo/quotaStrategies.ts";
-import {
- buildAutoQuotaThresholds,
- resolveQuotaExhaustionCutoffForTarget,
-} from "./combo/quotaExhaustionCutoff.ts";
import {
classifyTask,
getConversationCacheKey,
@@ -225,6 +257,55 @@ function clampPercent(value: number): number {
return Math.max(0, Math.min(100, value));
}
+function asThresholdMap(value: unknown): Record<string, number> {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
+ const result: Record<string, number> = {};
+ for (const [key, raw] of Object.entries(value as Record<string, unknown>)) {
+ const numeric = Number(raw);
+ if (key && Number.isFinite(numeric)) result[key] = numeric;
+ }
+ return result;
+}
+
+function quotaWindowLookupNames(provider: string, windowName: string): string[] {
+ const names = [windowName];
+ const lower = windowName.toLowerCase();
+ if (lower !== windowName) names.push(lower);
+ if (provider === "codex") {
+ if (lower.includes("session") || lower === "5h" || lower === "five_hour") names.push("session");
+ if (lower.includes("weekly") || lower === "7d" || lower === "seven_day") names.push("weekly");
+ if (lower.includes("monthly") || lower === "30d") names.push("monthly");
+ }
+ return [...new Set(names)];
+}
+
+function buildAutoQuotaThresholds(
+ provider: string,
+ connection: Record<string, unknown> | undefined,
+ resilienceSettings: ResilienceSettings | null | undefined
+): PreflightQuotaThresholds {
+ const quotaPreflight = (resilienceSettings ?? resolveResilienceSettings(null))?.quotaPreflight;
+ const defaultThresholdPercent = quotaPreflight?.defaultThresholdPercent ?? 2;
+ const warnThresholdPercent = quotaPreflight?.warnThresholdPercent ?? 20;
+ const providerWindowMap = asThresholdMap(quotaPreflight?.providerWindowDefaults?.[provider]);
+ const perConnectionWindowOverrides = asThresholdMap(connection?.quotaWindowThresholds);
+
+ return {
+ resolveMinRemainingPercent: (windowName: string | null): number => {
+ if (windowName !== null) {
+ for (const lookupWindowName of quotaWindowLookupNames(provider, windowName)) {
+ const override = perConnectionWindowOverrides[lookupWindowName];
+ if (typeof override === "number") return override;
+ const providerDefault = providerWindowMap[lookupWindowName];
+ if (typeof providerDefault === "number") return providerDefault;
+ }
+ }
+ return defaultThresholdPercent;
+ },
+ resolveWarnRemainingPercent: () => warnThresholdPercent,
+ };
+}
+
function quotaRemainingPercentFromQuota(quota: unknown): number {
if (!quota || typeof quota !== "object") return 100;
const record = quota as Record<string, unknown>;
@@ -653,11 +734,72 @@ export async function handleComboChat({
} = phaseComboSetup(comboCtx);
body = comboCtx.body;
- const handleSingleModelWithTimeout = buildTargetTimeoutRunner({
- handleSingleModel,
- comboTargetTimeoutMs,
- log,
- });
+ const handleSingleModelWithTimeout = async (
+ b: Record<string, unknown>,
+ modelStr: string,
+ target?: SingleModelTarget
+ ): Promise<Response> => {
+ if (comboTargetTimeoutMs <= 0) {
+ return handleSingleModel(b, modelStr, target).catch((err) =>
+ errorResponse(502, err?.message ?? "Upstream model error")
+ );
+ }
+
+ const timeoutController = new AbortController();
+ let timeoutId: ReturnType<typeof setTimeout> | undefined;
+ let timedOut = false;
+ const timeoutPromise = new Promise<Response>((resolve) => {
+ timeoutId = setTimeout(() => {
+ timedOut = true;
+ log.warn(
+ "COMBO",
+ `Model ${modelStr} exceeded ${comboTargetTimeoutMs}ms timeout — falling back`
+ );
+ timeoutController.abort(new Error("combo-per-model-timeout"));
+ resolve(
+ new Response(JSON.stringify({ error: { message: `Model ${modelStr} timed out` } }), {
+ status: 524,
+ headers: { "Content-Type": "application/json" },
+ })
+ );
+ }, comboTargetTimeoutMs);
+ });
+ const targetWithSignal = {
+ ...(target ?? {}),
+ modelAbortSignal: timeoutController.signal,
+ };
+ const parentHedgeSignal = target?.modelAbortSignal ?? null;
+ let onParentHedgeAbort: (() => void) | null = null;
+ if (parentHedgeSignal) {
+ if (parentHedgeSignal.aborted) {
+ timeoutController.abort(new Error("hedge-cancelled"));
+ } else {
+ onParentHedgeAbort = () => {
+ timeoutController.abort(new Error("hedge-cancelled"));
+ };
+ parentHedgeSignal.addEventListener("abort", onParentHedgeAbort, { once: true });
+ }
+ }
+ try {
+ return await Promise.race([
+ handleSingleModel(b, modelStr, targetWithSignal).catch((err) => {
+ if (timedOut) {
+ // Inner call rejected because we aborted it. The synthetic 524 from
+ // timeoutPromise already wins the race; return an empty response so
+ // the loser branch resolves cleanly without leaking err.message.
+ return new Response(null, { status: 599 });
+ }
+ return errorResponse(502, err?.message ?? "Upstream model error");
+ }),
+ timeoutPromise,
+ ]);
+ } finally {
+ clearTimeout(timeoutId);
+ if (parentHedgeSignal && onParentHedgeAbort) {
+ parentHedgeSignal.removeEventListener("abort", onParentHedgeAbort);
+ }
+ }
+ };
// Route to pinned model if context caching specifies one (Fix #679)
if (pinnedModel) {
@@ -1034,28 +1176,422 @@ export async function handleComboChat({
// the fallback order, never override the router's primary choice.
let autoUsedExplicitRouter = false;
if (strategy === "auto") {
- const autoResult = await resolveAutoStrategyOrder({
+ const requestHasTools = Array.isArray(body?.tools) && body.tools.length > 0;
+ let eligibleTargets = [...orderedTargets];
+
+ if (requestHasTools) {
+ const filtered = eligibleTargets.filter((target) => supportsToolCalling(target.modelStr));
+ if (filtered.length > 0) {
+ eligibleTargets = filtered;
+ } else {
+ log.warn(
+ "COMBO",
+ "Auto strategy: all candidates filtered by tool-calling policy, falling back to full pool"
+ );
+ }
+ }
+
+ // Context-window pre-filter (#1808)
+ // Estimate input tokens once; exclude candidates whose known context limit is too small.
+ // Uses the same 4-chars-per-token heuristic as contextManager.ts::compressContext().
+ // Null/unknown limits are treated as "include" to avoid incorrectly dropping valid targets.
+ const requestMessages = body.messages;
+ const estimatedInputTokens = estimateTokens(
+ typeof requestMessages === "string" ||
+ (requestMessages !== null && typeof requestMessages === "object")
+ ? requestMessages
+ : []
+ );
+ if (estimatedInputTokens > 0) {
+ const filteredByContext = eligibleTargets.filter((target) => {
+ const limit = getModelContextLimitForModelString(target.modelStr);
+ if (limit === null || limit === undefined) return true; // unknown — include to be safe
+ return limit >= estimatedInputTokens;
+ });
+ if (filteredByContext.length > 0) {
+ log.debug?.(
+ "COMBO",
+ `Auto strategy: context-window filter kept ${filteredByContext.length}/${eligibleTargets.length} candidates (est. ${estimatedInputTokens} tokens)`
+ );
+ eligibleTargets = filteredByContext;
+ } else {
+ log.warn(
+ "COMBO",
+ `Auto strategy: all candidates filtered by context-window policy (est. ${estimatedInputTokens} tokens), falling back to full pool`
+ );
+ // eligibleTargets intentionally unchanged — same fallback contract as tool-calling filter
+ }
+
+ eligibleTargets = await expandAutoComboCandidatePool(eligibleTargets, combo);
+ }
+
+ const prompt = extractPromptForIntent(body);
+ const systemPrompt =
+ typeof combo?.system_message === "string" ? combo.system_message : undefined;
+ const intentConfig = getIntentConfig(settings, combo);
+ const intent = classifyWithConfig(prompt, intentConfig, systemPrompt);
+ recordComboIntent(combo.name, intent);
+ const taskType = mapIntentToTaskType(intent);
+
+ const rawAutoConfigSource =
+ combo?.autoConfig ||
+ (isRecord(combo?.config?.auto) ? combo.config.auto : null) ||
+ combo?.config ||
+ {};
+ const autoConfigSource: Record<string, unknown> = isRecord(rawAutoConfigSource)
+ ? rawAutoConfigSource
+ : {};
+ const routingStrategy =
+ typeof autoConfigSource.routerStrategy === "string"
+ ? autoConfigSource.routerStrategy
+ : typeof autoConfigSource.routingStrategy === "string"
+ ? autoConfigSource.routingStrategy
+ : typeof autoConfigSource.strategyName === "string"
+ ? autoConfigSource.strategyName
+ : "rules";
+
+ const candidatePool = Array.isArray(autoConfigSource.candidatePool)
+ ? autoConfigSource.candidatePool
+ : [...new Set(eligibleTargets.map((target) => target.provider))];
+
+ const weights =
+ autoConfigSource.weights && typeof autoConfigSource.weights === "object"
+ ? (autoConfigSource.weights as ScoringWeights)
+ : DEFAULT_WEIGHTS;
+ const explorationRate = Number.isFinite(Number(autoConfigSource.explorationRate))
+ ? Number(autoConfigSource.explorationRate)
+ : 0.05;
+ const budgetCap = Number.isFinite(Number(autoConfigSource.budgetCap))
+ ? Number(autoConfigSource.budgetCap)
+ : undefined;
+ const modePack =
+ typeof autoConfigSource.modePack === "string" ? autoConfigSource.modePack : undefined;
+ const resetWindowConfig = resolveResetWindowConfig(autoConfigSource);
+ const slaPolicy = resolveSlaRoutingPolicy(autoConfigSource);
+
+ let lastKnownGoodProvider: string | undefined;
+ try {
+ const { getLKGP } = await import("../../src/lib/localDb");
+ const lkgp = await getLKGP(combo.name, combo.id || combo.name);
+ if (lkgp) lastKnownGoodProvider = lkgp.provider;
+ } catch (err) {
+ log.warn("COMBO", "Failed to retrieve Last Known Good Provider. This is non-fatal.", { err });
+ }
+
+ const autoCandidateResilienceSettings =
+ relayOptions?.bypassProviderQuotaPolicy === true
+ ? {
+ ...resilienceSettings,
+ quotaPreflight: {
+ ...resilienceSettings.quotaPreflight,
+ enabled: false,
+ },
+ }
+ : resilienceSettings;
+ const candidates = await buildAutoCandidates(
+ eligibleTargets,
+ combo.name,
+ relayOptions?.sessionId,
+ resetWindowConfig,
+ autoCandidateResilienceSettings
+ );
+ const routableCandidates = candidates.filter(
+ (candidate) => candidate.quotaCutoffBlocked !== true
+ );
+ const quotaBlockedCount = candidates.length - routableCandidates.length;
+ if (quotaBlockedCount > 0) {
+ log.info(
+ "COMBO",
+ `Auto strategy: quota cutoff skipped ${quotaBlockedCount}/${candidates.length} account candidates`
+ );
+ }
+ // G2: Register candidates so chatCore can mark quotaSoftPenalty via setCandidateQuotaSoftPenalty.
+ _registerExecutionCandidates(routableCandidates);
+ if (candidates.length > 0 && routableCandidates.length === 0) {
+ return unavailableResponse(
+ 429,
+ "All auto strategy candidates are below configured quota cutoffs"
+ );
+ }
+ if (routableCandidates.length > 0) {
+ let selectedProvider: string | null = null;
+ let selectedModel: string | null = null;
+ let selectionReason = "";
+
+ if (routingStrategy !== "rules") {
+ try {
+ const decision = selectWithStrategy(
+ routableCandidates,
+ {
+ taskType,
+ requestHasTools,
+ lastKnownGoodProvider,
+ estimatedInputTokens,
+ sla: slaPolicy,
+ },
+ routingStrategy
+ );
+ selectedProvider = decision.provider;
+ selectedModel = decision.model;
+ selectionReason = decision.reason;
+ autoUsedExplicitRouter = true;
+ } catch (err) {
+ log.warn(
+ "COMBO",
+ `Auto strategy '${routingStrategy}' failed (${err?.message || "unknown"}), falling back to rules`
+ );
+ }
+ }
+
+ if (!selectedProvider || !selectedModel) {
+ const selection = selectAutoProvider(
+ {
+ id: combo.id || combo.name,
+ name: combo.name,
+ type: "auto",
+ candidatePool,
+ weights,
+ modePack,
+ budgetCap,
+ explorationRate,
+ },
+ routableCandidates,
+ taskType
+ );
+ selectedProvider = selection.provider;
+ selectedModel = selection.model;
+ selectionReason = `score=${selection.score.toFixed(3)}${selection.isExploration ? " (exploration)" : ""}`;
+ }
+
+ // Complexity-aware routing (2026, opt-in): classify the request's
+ // difficulty and feed a tier hint into scoring so tierAffinity /
+ // specificityMatch favor candidates whose tier matches the request.
+ const autoManifestHint: RoutingHint | null =
+ config.complexityAwareRouting === true
+ ? buildComplexityRoutingHint(
+ eligibleTargets.filter((t) => t.kind === "model"),
+ body,
+ log
+ )
+ : null;
+
+ const scoredTargets = scoreAutoTargets(
+ eligibleTargets,
+ routableCandidates,
+ taskType,
+ weights,
+ autoManifestHint
+ );
+ const rankedTargets = scoredTargets.map((entry) => entry.target);
+ const selectedTarget =
+ scoredTargets.find((entry) => {
+ const parsed = parseModel(entry.target.modelStr);
+ const modelId = parsed.model || entry.target.modelStr;
+ return entry.target.provider === selectedProvider && modelId === selectedModel;
+ })?.target ||
+ rankedTargets[0] ||
+ eligibleTargets[0];
+ if (!selectedTarget) {
+ return unavailableResponse(
+ 429,
+ "No auto strategy targets remained after quota cutoff filtering"
+ );
+ }
+
+ // Keep eligibleTargets as the last-resort fallback tail: dedupe drops the
+ // routable ranked ones (and, when the cutoff is OFF, makes this identical to
+ // the pre-cutoff behavior), but a quota-blocked target still survives as a
+ // final fallback instead of vanishing — the hard cutoff only de-prioritizes.
+ orderedTargets = dedupeTargetsByExecutionKey(
+ [selectedTarget, ...rankedTargets, ...eligibleTargets].filter(
+ (entry): entry is ResolvedComboTarget => entry !== undefined && entry !== null
+ )
+ );
+
+ log.info(
+ "COMBO",
+ `Auto selection: ${selectedTarget?.modelStr || `${selectedProvider}/${selectedModel}`} | intent=${intent} task=${taskType} | strategy=${routingStrategy} | ${selectionReason}`
+ );
+ } else {
+ log.warn("COMBO", "Auto strategy has no candidates, keeping default ordering");
+ }
+ } else if (strategy === "lkgp") {
+ try {
+ const { getLKGP } = await import("../../src/lib/localDb");
+ const lkgpProvider = await getLKGP(combo.name, combo.id || combo.name);
+
+ if (lkgpProvider) {
+ const lkgpRecord = lkgpProvider;
+ const providerName = lkgpRecord.provider;
+ const connId = lkgpRecord.connectionId;
+
+ let lkgpIndex = -1;
+ if (connId) {
+ lkgpIndex = orderedTargets.findIndex(
+ (target) => target.provider === providerName && target.connectionId === connId
+ );
+ }
+ if (lkgpIndex < 0) {
+ lkgpIndex = orderedTargets.findIndex(
+ (target) =>
+ target.provider === providerName ||
+ // Issue #2359: Defensive guard. The `target.modelStr` type
+ // annotation is `string`, but malformed combo entries (e.g.,
+ // local-provider rows whose `modelStr` failed to resolve when
+ // the executor catalogue was being rebuilt) have leaked
+ // through and surfaced as `e.startsWith is not a function`
+ // 500s on combo test/dispatch. The fast path stays
+ // unchanged for the common case; this only avoids the
+ // crash when the field is unexpectedly non-string.
+ (typeof target.modelStr === "string" &&
+ target.modelStr.startsWith(`${providerName}/`))
+ );
+ }
+
+ if (lkgpIndex > 0) {
+ const [lkgpTarget] = orderedTargets.splice(lkgpIndex, 1);
+ orderedTargets.unshift(lkgpTarget);
+ log.info(
+ "COMBO",
+ `[LKGP] Prioritizing last known good provider ${providerName}${connId ? ` (account ${connId})` : ""} for combo "${combo.name}"`
+ );
+ } else if (lkgpIndex === 0) {
+ log.debug?.(
+ "COMBO",
+ `[LKGP] Last known good provider ${providerName}${connId ? ` (account ${connId})` : ""} already first for combo "${combo.name}"`
+ );
+ }
+ }
+ } catch (err) {
+ log.warn("COMBO", "Failed to retrieve Last Known Good Provider. This is non-fatal.", { err });
+ }
+ } else if (strategy === "strict-random") {
+ const selectedExecutionKey = await getNextFromDeck(
+ `combo:${combo.name}`,
+ orderedTargets.map((target) => target.executionKey)
+ );
+ const selectedTarget =
+ orderedTargets.find((target) => target.executionKey === selectedExecutionKey) || null;
+ // #3959: shuffle the fallback remainder too. Previously `rest` kept fixed
+ // priority order, so after a failing deck pick the chain always fell through
+ // to the same top-priority model — a persistently-failing model was retried
+ // on essentially every request and fallback load never spread across peers.
+ const rest = fisherYatesShuffle(
+ orderedTargets.filter((target) => target.executionKey !== selectedExecutionKey)
+ );
+ orderedTargets = [selectedTarget, ...rest].filter(
+ (target): target is ResolvedComboTarget => target !== null
+ );
+ log.info(
+ "COMBO",
+ `Strict-random deck: ${selectedExecutionKey} selected (${orderedTargets.length} targets)`
+ );
+ } else if (strategy === "random") {
+ orderedTargets = fisherYatesShuffle([...orderedTargets]);
+ log.info("COMBO", `Random shuffle: ${orderedTargets.length} targets`);
+ } else if (strategy === "fill-first") {
+ log.info(
+ "COMBO",
+ `Fill-first ordering: preserving priority order (${orderedTargets.length} targets)`
+ );
+ } else if (strategy === "p2c") {
+ orderedTargets = orderTargetsByPowerOfTwoChoices(orderedTargets, combo.name);
+ log.info("COMBO", `Power-of-two-choices ordering: selected ${orderedTargets[0]?.modelStr}`);
+ } else if (strategy === "least-used") {
+ orderedTargets = sortTargetsByUsage(orderedTargets, combo.name);
+ log.info("COMBO", `Least-used ordering: ${orderedTargets[0]?.modelStr} has fewest requests`);
+ } else if (strategy === "cost-optimized") {
+ orderedTargets = await sortTargetsByCost(orderedTargets);
+ if (config.manifestRouting === true) {
+ try {
+ const manifestHint = generateRoutingHints(
+ orderedTargets.filter((t) => t.kind === "model"),
+ {
+ messages: Array.isArray(body?.messages)
+ ? (body.messages as Array<{ role?: string; content?: string | unknown }>)
+ : [],
+ tools: Array.isArray(body?.tools)
+ ? (body.tools as Array<{
+ function?: { name: string; description?: string; parameters?: unknown };
+ }>)
+ : undefined,
+ model: typeof body?.model === "string" ? body.model : undefined,
+ }
+ );
+ if (manifestHint.strategyModifier === "require-premium") {
+ const eligible = orderedTargets.filter(
+ (t) =>
+ t.kind !== "model" ||
+ manifestHint.eligibleTargets.some(
+ (e) => e.provider === t.provider && e.modelStr === t.modelStr
+ )
+ );
+ if (eligible.length > 0) orderedTargets = eligible;
+ }
+ log.debug?.(
+ {
+ strategyModifier: manifestHint.strategyModifier,
+ specificityLevel: manifestHint.specificityLevel,
+ score: manifestHint.specificity.score,
+ },
+ "manifest routing applied"
+ );
+ } catch (err) {
+ log.warn({ err }, "manifest routing failed, falling back to standard strategy");
+ }
+ }
+ log.info("COMBO", `Cost-optimized ordering: cheapest first (${orderedTargets[0]?.modelStr})`);
+ } else if (strategy === "reset-aware") {
+ orderedTargets = await orderTargetsByResetAwareQuota(
orderedTargets,
- body,
- combo,
- settings,
+ combo.name,
config,
- relayOptions,
- resilienceSettings,
log,
- buildAutoCandidates,
- });
- if ("earlyResponse" in autoResult) return autoResult.earlyResponse;
- orderedTargets = autoResult.orderedTargets;
- autoUsedExplicitRouter = autoResult.autoUsedExplicitRouter;
- } else {
- orderedTargets = await applyStrategyOrdering(strategy, orderedTargets, {
- combo,
+ apiKeyAllowedConnections
+ );
+ log.info(
+ "COMBO",
+ `Reset-aware ordering: ${orderedTargets[0]?.modelStr}${orderedTargets[0]?.connectionId ? ` (${orderedTargets[0].connectionId})` : ""} first`
+ );
+ } else if (strategy === "reset-window") {
+ orderedTargets = await orderTargetsByResetWindow(
+ orderedTargets,
+ combo.name,
config,
- body,
log,
- apiKeyAllowedConnections,
- });
+ apiKeyAllowedConnections
+ );
+ log.info(
+ "COMBO",
+ `Reset-window ordering: ${orderedTargets[0]?.modelStr}${orderedTargets[0]?.connectionId ? ` (${orderedTargets[0].connectionId})` : ""} first`
+ );
+ } else if (strategy === "context-optimized") {
+ orderedTargets = sortTargetsByContextSize(orderedTargets);
+ log.info("COMBO", `Context-optimized ordering: largest first (${orderedTargets[0]?.modelStr})`);
+ } else if (strategy === "headroom") {
+ orderedTargets = await orderTargetsByHeadroom(
+ orderedTargets,
+ combo.name,
+ log,
+ apiKeyAllowedConnections
+ );
+ log.info(
+ "COMBO",
+ `Headroom ordering: ${orderedTargets[0]?.modelStr}${orderedTargets[0]?.connectionId ? ` (${orderedTargets[0].connectionId})` : ""} has most free capacity`
+ );
+ } else if (strategy === "quota-share") {
+ // Internal quota-share combos (qtSd/): delegate to the dedicated module (DRR +
+ // P2C in-flight + per-model bucket gating + per-connection concurrency gating).
+ const qsModel =
+ typeof body?.model === "string" ? body.model : (orderedTargets[0]?.modelStr ?? "");
+ const qsMaxConcurrent = await resolveMaxConcurrentByConnection(orderedTargets);
+ orderedTargets = selectQuotaShareTarget(orderedTargets, combo.name, qsModel, Date.now(), {
+ maxConcurrentByConnection: qsMaxConcurrent,
+ }).orderedTargets;
+ log.info(
+ "COMBO",
+ `Quota-share ordering: ${orderedTargets[0]?.modelStr}${orderedTargets[0]?.connectionId ? ` (${orderedTargets[0].connectionId})` : ""} selected (DRR+P2C)`
+ );
}
const _sticky = await applySessionStickiness(
orderedTargets,
@@ -1102,12 +1638,6 @@ export async function handleComboChat({
)
: new Map<string, PreScreenResult>();
- // #5923 (Finding #4) — reset-window config for the shared per-target quota-
- // exhaustion cutoff below. The "auto" strategy already applies its own cutoff
- // via buildAutoCandidates/routableCandidates, so this only affects the other
- // 16 strategies (priority, weighted, etc.) that funnel through executeTarget.
- const quotaCutoffResetWindowConfig = resolveResetWindowConfig(config as Record<string, unknown>);
-
if (orderedTargets.length === 0) {
return comboModelNotFoundResponse("Combo has no executable targets");
}
@@ -1260,33 +1790,6 @@ export async function handleComboChat({
return null;
}
- // #5923 (Finding #4) — honor the same opt-in quota-exhaustion cutoff the
- // "auto" strategy already applies (buildAutoCandidates), for every other
- // strategy (priority, weighted, etc.). Strictly scoped per (provider,
- // connectionId): a 0%-remaining connection is skipped here, but sibling
- // connections/models on the same provider are untouched — the provider
- // circuit breaker is never touched by this check. The "auto" strategy is
- // excluded to avoid a redundant duplicate fetch — it already filtered its
- // candidate pool via `routableCandidates` before reaching this loop.
- if (strategy !== "auto" && provider && target.connectionId) {
- const quotaCutoff = await resolveQuotaExhaustionCutoffForTarget(
- provider,
- target.connectionId,
- resilienceSettings,
- quotaCutoffResetWindowConfig,
- combo.name,
- log
- );
- if (quotaCutoff.blocked) {
- log.info(
- "COMBO",
- `Skipping ${modelStr} — quota exhaustion cutoff (${quotaCutoff.reason || "quota_exhausted"})`
- );
- if (i > 0) fallbackCount++;
- return null;
- }
- }
-
// Pre-screen snapshot is NOT used as a permanent skip — availability
// is always re-checked via isModelAvailable below because connection
// cooldowns can expire between setTry retries, making a previously
@@ -1920,15 +2423,6 @@ export async function handleComboChat({
!isTokenLimitBreach &&
[408, 429, 500, 502, 503, 504].includes(result.status);
if (retry < maxRetries && isTransient && !providerExhausted) {
- if (
- provider &&
- rawModel &&
- isModelLocked(provider, targetWithConnection.connectionId || "", rawModel)
- ) {
- log.info("COMBO", `Skipping retry for ${modelStr} — model lockout active`);
- if (i > 0) fallbackCount++;
- return null;
- }
// Record model lockout immediately on the first transient failure —
// once the model is cooling down, retrying it would waste an upstream
// call and extend the cooldown via exponential backoff.
diff --git a/open-sse/services/combo/__tests__/targetExhaustion.test.ts b/open-sse/services/combo/__tests__/targetExhaustion.test.ts
new file mode 100644
index 0000000000..f422aafc6a
--- /dev/null
+++ b/open-sse/services/combo/__tests__/targetExhaustion.test.ts
@@ -0,0 +1,311 @@
+import { describe, it, expect } from "vitest";
+import { applyComboTargetExhaustion, type ComboExhaustionSets } from "../targetExhaustion.ts";
+import type { ResolvedComboTarget, ComboLogger } from "../types.ts";
+
+function makeTarget(overrides: Partial<ResolvedComboTarget> = {}): ResolvedComboTarget {
+ return {
+ kind: "model",
+ stepId: "step-1",
+ executionKey: "key-1",
+ modelStr: "gpt-4",
+ provider: "openai",
+ providerId: "p1",
+ connectionId: "c1",
+ allowedConnectionIds: null,
+ weight: 1,
+ label: null,
+ failoverBeforeRetry: undefined,
+ ...overrides,
+ };
+}
+
+function makeLogger(): ComboLogger {
+ const msgs: string[] = [];
+ return {
+ info: (...args: unknown[]) => { msgs.push(args.join(" ")); },
+ warn: (...args: unknown[]) => { msgs.push(args.join(" ")); },
+ error: (...args: unknown[]) => { msgs.push(args.join(" ")); },
+ debug: (...args: unknown[]) => { msgs.push(args.join(" ")); },
+ _msgs: msgs,
+ } as ComboLogger & { _msgs: string[] };
+}
+
+function makeSets(): ComboExhaustionSets {
+ return {
+ exhaustedProviders: new Set<string>(),
+ exhaustedConnections: new Set<string>(),
+ transientRateLimitedProviders: new Set<string>(),
+ };
+}
+
+describe("applyComboTargetExhaustion", () => {
+ it("marks provider exhausted when isProviderExhaustedReason is true (quota)", () => {
+ const sets = makeSets();
+ const log = makeLogger();
+ const exhausted = applyComboTargetExhaustion(makeTarget(), {
+ result: { status: 429 },
+ // isProviderExhaustedReason reads `reason`/`creditsExhausted`/`dailyQuotaExhausted`
+ // (NOT `error.code`), so signal full-account exhaustion via creditsExhausted.
+ fallbackResult: { creditsExhausted: true },
+ errorText: "",
+ rawModel: "gpt-4",
+ isTokenLimitBreach: false,
+ allAccountsRateLimited: false,
+ sets,
+ log,
+ tag: "COMBO",
+ exhaustedLogLevel: "info",
+ });
+ expect(exhausted).toBe(true);
+ expect(sets.exhaustedProviders.has("openai")).toBe(true);
+ expect(sets.exhaustedProviders.size).toBe(1);
+ expect(sets.transientRateLimitedProviders.has("openai")).toBe(false);
+ });
+
+ it("marks provider exhausted when classifyErrorText returns QUOTA_EXHAUSTED", () => {
+ const sets = makeSets();
+ const log = makeLogger();
+ const exhausted = applyComboTargetExhaustion(makeTarget(), {
+ result: { status: 429 },
+ fallbackResult: {} as any,
+ // classifyErrorText flags "quota exceeded" as QUOTA_EXHAUSTED.
+ errorText: "Quota exceeded — please retry later.",
+ rawModel: "gpt-4",
+ isTokenLimitBreach: false,
+ allAccountsRateLimited: false,
+ sets,
+ log,
+ tag: "COMBO",
+ exhaustedLogLevel: "info",
+ });
+ expect(exhausted).toBe(true);
+ expect(sets.exhaustedProviders.has("openai")).toBe(true);
+ });
+
+ it("marks provider exhausted when allAccountsRateLimited is true", () => {
+ const sets = makeSets();
+ const log = makeLogger();
+ const exhausted = applyComboTargetExhaustion(makeTarget(), {
+ result: { status: 503 },
+ fallbackResult: {} as any,
+ errorText: "Service temporarily unavailable",
+ rawModel: "gpt-4",
+ isTokenLimitBreach: false,
+ allAccountsRateLimited: true,
+ sets,
+ log,
+ tag: "COMBO-RR",
+ exhaustedLogLevel: "info",
+ });
+ expect(exhausted).toBe(true);
+ expect(sets.exhaustedProviders.has("openai")).toBe(true);
+ });
+
+ it("does NOT mark provider exhausted for per-model-quota providers (different model)", () => {
+ const sets = makeSets();
+ const log = makeLogger();
+ // gemini has per-model quotas (hasPerModelQuota === true): a model-scoped quota
+ // 429 must NOT mark the whole provider exhausted — other models may still work.
+ const target = makeTarget({ provider: "gemini" });
+ const exhausted = applyComboTargetExhaustion(target, {
+ result: { status: 429 },
+ fallbackResult: { reason: "quota_exhausted" } as any,
+ errorText: "quota exceeded for model gpt-4",
+ rawModel: "gpt-4",
+ isTokenLimitBreach: false,
+ allAccountsRateLimited: false,
+ sets,
+ log,
+ tag: "COMBO",
+ exhaustedLogLevel: "info",
+ });
+ expect(exhausted).toBe(false);
+ expect(sets.exhaustedProviders.has("gemini")).toBe(false);
+ expect(sets.transientRateLimitedProviders.has("gemini")).toBe(true);
+ });
+
+ it("does NOT mark provider exhausted for unknown providers", () => {
+ const sets = makeSets();
+ const log = makeLogger();
+ const exhausted = applyComboTargetExhaustion(makeTarget({ provider: "unknown" }), {
+ result: { status: 503 },
+ fallbackResult: { error: { code: "quota_exhausted" } },
+ errorText: "quota exhausted",
+ rawModel: "unknown-model",
+ isTokenLimitBreach: false,
+ allAccountsRateLimited: true,
+ sets,
+ log,
+ tag: "COMBO",
+ exhaustedLogLevel: "info",
+ });
+ expect(exhausted).toBe(false);
+ });
+
+ it("does NOT mark provider exhausted for empty provider strings", () => {
+ const sets = makeSets();
+ const log = makeLogger();
+ const exhausted = applyComboTargetExhaustion(makeTarget({ provider: "" }), {
+ result: { status: 503 },
+ fallbackResult: { error: { code: "quota_exhausted" } },
+ errorText: "quota exhausted",
+ rawModel: "model",
+ isTokenLimitBreach: false,
+ allAccountsRateLimited: true,
+ sets,
+ log,
+ tag: "COMBO",
+ exhaustedLogLevel: "info",
+ });
+ expect(exhausted).toBe(false);
+ });
+
+ it("marks transientRateLimited on 429 when NOT token-limit breach and NOT provider-exhausted", () => {
+ const sets = makeSets();
+ const log = makeLogger();
+ const exhausted = applyComboTargetExhaustion(makeTarget(), {
+ result: { status: 429 },
+ fallbackResult: {} as any,
+ errorText: "Rate limited",
+ rawModel: "gpt-4",
+ isTokenLimitBreach: false,
+ allAccountsRateLimited: false,
+ sets,
+ log,
+ tag: "COMBO",
+ exhaustedLogLevel: "info",
+ });
+ expect(exhausted).toBe(false);
+ expect(sets.transientRateLimitedProviders.has("openai")).toBe(true);
+ expect(sets.exhaustedProviders.has("openai")).toBe(false);
+ });
+
+ it("does NOT mark transientRateLimited on 429 when isTokenLimitBreach is true", () => {
+ const sets = makeSets();
+ const log = makeLogger();
+ const exhausted = applyComboTargetExhaustion(makeTarget(), {
+ result: { status: 429 },
+ fallbackResult: {} as any,
+ errorText: "Token limit exceeded",
+ rawModel: "gpt-4",
+ isTokenLimitBreach: true,
+ allAccountsRateLimited: false,
+ sets,
+ log,
+ tag: "COMBO",
+ exhaustedLogLevel: "info",
+ });
+ expect(exhausted).toBe(false);
+ expect(sets.transientRateLimitedProviders.has("openai")).toBe(false);
+ expect(sets.exhaustedProviders.has("openai")).toBe(false);
+ });
+
+ it("marks exhaustedConnections on connection-level error status (502) with connectionId", () => {
+ const sets = makeSets();
+ const log = makeLogger();
+ const exhausted = applyComboTargetExhaustion(
+ makeTarget({ provider: "openai", connectionId: "conn-1" }),
+ {
+ result: { status: 502 },
+ fallbackResult: {} as any,
+ errorText: "Bad Gateway",
+ rawModel: "gpt-4",
+ isTokenLimitBreach: false,
+ allAccountsRateLimited: false,
+ sets,
+ log,
+ tag: "COMBO",
+ exhaustedLogLevel: "info",
+ }
+ );
+ expect(exhausted).toBe(false);
+ expect(sets.exhaustedConnections.has("openai:conn-1")).toBe(true);
+ expect(sets.exhaustedProviders.has("openai")).toBe(false);
+ });
+
+ it("marks exhaustedProviders on connection-level error when NO connectionId", () => {
+ const sets = makeSets();
+ const log = makeLogger();
+ const exhausted = applyComboTargetExhaustion(
+ makeTarget({ provider: "openai", connectionId: null }),
+ {
+ result: { status: 502 },
+ fallbackResult: {} as any,
+ errorText: "Bad Gateway",
+ rawModel: "gpt-4",
+ isTokenLimitBreach: false,
+ allAccountsRateLimited: false,
+ sets,
+ log,
+ tag: "COMBO",
+ exhaustedLogLevel: "info",
+ }
+ );
+ expect(exhausted).toBe(false);
+ expect(sets.exhaustedProviders.has("openai")).toBe(true);
+ expect(sets.exhaustedConnections.size).toBe(0);
+ });
+
+ it("does NOT mark anything for circuit-open (X-OmniRoute-Provider-Breaker header)", () => {
+ const sets = makeSets();
+ const log = makeLogger();
+ const exhausted = applyComboTargetExhaustion(makeTarget(), {
+ result: { status: 503, headers: new Map([["x-omniroute-provider-breaker", "open"]]) as any },
+ fallbackResult: {} as any,
+ errorText: "",
+ rawModel: "gpt-4",
+ isTokenLimitBreach: false,
+ allAccountsRateLimited: false,
+ sets,
+ log,
+ tag: "COMBO",
+ exhaustedLogLevel: "info",
+ });
+ expect(exhausted).toBe(false);
+ expect(sets.exhaustedProviders.has("openai")).toBe(false);
+ expect(sets.exhaustedConnections.has("openai:c1")).toBe(false);
+ expect(sets.transientRateLimitedProviders.has("openai")).toBe(false);
+ });
+
+ it("does NOT mark exhaustion for non-connection-level status codes (400)", () => {
+ const sets = makeSets();
+ const log = makeLogger();
+ const exhausted = applyComboTargetExhaustion(makeTarget(), {
+ result: { status: 400 },
+ fallbackResult: {} as any,
+ errorText: "Bad Request",
+ rawModel: "gpt-4",
+ isTokenLimitBreach: false,
+ allAccountsRateLimited: false,
+ sets,
+ log,
+ tag: "COMBO",
+ exhaustedLogLevel: "info",
+ });
+ expect(exhausted).toBe(false);
+ expect(sets.exhaustedConnections.size).toBe(0);
+ expect(sets.exhaustedProviders.size).toBe(0);
+ expect(sets.transientRateLimitedProviders.size).toBe(0);
+ });
+
+ it("does NOT mark anything for 200 (success)", () => {
+ const sets = makeSets();
+ const log = makeLogger();
+ const exhausted = applyComboTargetExhaustion(makeTarget(), {
+ result: { status: 200 },
+ fallbackResult: {} as any,
+ errorText: "",
+ rawModel: "gpt-4",
+ isTokenLimitBreach: false,
+ allAccountsRateLimited: false,
+ sets,
+ log,
+ tag: "COMBO",
+ exhaustedLogLevel: "info",
+ });
+ expect(exhausted).toBe(false);
+ expect(sets.exhaustedProviders.size).toBe(0);
+ expect(sets.exhaustedConnections.size).toBe(0);
+ expect(sets.transientRateLimitedProviders.size).toBe(0);
+ });
+});
diff --git a/open-sse/services/combo/applyStrategyOrdering.ts b/open-sse/services/combo/applyStrategyOrdering.ts
deleted file mode 100644
index e8cb39ecf8..0000000000
--- a/open-sse/services/combo/applyStrategyOrdering.ts
+++ /dev/null
@@ -1,226 +0,0 @@
-import { fisherYatesShuffle, getNextFromDeck } from "../../../src/shared/utils/shuffleDeck";
-import { generateRoutingHints } from "../manifestAdapter";
-import { resolveMaxConcurrentByConnection } from "./concurrencyCaps.ts";
-import { sortTargetsByContextSize } from "./comboStructure.ts";
-import { selectQuotaShareTarget } from "./quotaShareStrategy.ts";
-import {
- orderTargetsByHeadroom,
- orderTargetsByResetAwareQuota,
- orderTargetsByResetWindow,
-} from "./quotaStrategies.ts";
-import {
- orderTargetsByPowerOfTwoChoices,
- sortTargetsByCost,
- sortTargetsByUsage,
-} from "./targetSorters.ts";
-import type { ComboLike, ComboLogger, ResolvedComboTarget } from "./types.ts";
-
-export interface ApplyStrategyOrderingDeps {
- combo: ComboLike;
- config: Record<string, unknown>;
- body: Record<string, unknown>;
- log: ComboLogger;
- apiKeyAllowedConnections: string[] | null;
-}
-
-/**
- * Apply the target-ordering step for every non-`auto` combo strategy.
- *
- * Extracted verbatim from the `else if (strategy === ...)` chain in
- * handleComboChat (lkgp / strict-random / random / fill-first / p2c /
- * least-used / cost-optimized / reset-aware / reset-window / context-optimized /
- * headroom / quota-share). Each branch only reorders `orderedTargets` — no early
- * returns, no other mutable state — so the extraction returns the reordered list.
- * An unknown strategy falls through with the input order unchanged, matching the
- * previous inline behavior (the chain had no trailing `else`). The `auto` strategy
- * is handled separately by `resolveAutoStrategyOrder` and never reaches here.
- */
-export async function applyStrategyOrdering(
- strategy: string,
- initialOrderedTargets: ResolvedComboTarget[],
- deps: ApplyStrategyOrderingDeps
-): Promise<ResolvedComboTarget[]> {
- const { combo, config, body, log, apiKeyAllowedConnections } = deps;
- let orderedTargets = initialOrderedTargets;
-
- if (strategy === "lkgp") {
- try {
- const { getLKGP } = await import("../../../src/lib/localDb");
- const lkgpProvider = await getLKGP(combo.name, combo.id || combo.name);
-
- if (lkgpProvider) {
- const lkgpRecord = lkgpProvider;
- const providerName = lkgpRecord.provider;
- const connId = lkgpRecord.connectionId;
-
- let lkgpIndex = -1;
- if (connId) {
- lkgpIndex = orderedTargets.findIndex(
- (target) => target.provider === providerName && target.connectionId === connId
- );
- }
- if (lkgpIndex < 0) {
- lkgpIndex = orderedTargets.findIndex(
- (target) =>
- target.provider === providerName ||
- // Issue #2359: Defensive guard. The `target.modelStr` type
- // annotation is `string`, but malformed combo entries (e.g.,
- // local-provider rows whose `modelStr` failed to resolve when
- // the executor catalogue was being rebuilt) have leaked
- // through and surfaced as `e.startsWith is not a function`
- // 500s on combo test/dispatch. The fast path stays
- // unchanged for the common case; this only avoids the
- // crash when the field is unexpectedly non-string.
- (typeof target.modelStr === "string" &&
- target.modelStr.startsWith(`${providerName}/`))
- );
- }
-
- if (lkgpIndex > 0) {
- const [lkgpTarget] = orderedTargets.splice(lkgpIndex, 1);
- orderedTargets.unshift(lkgpTarget);
- log.info(
- "COMBO",
- `[LKGP] Prioritizing last known good provider ${providerName}${connId ? ` (account ${connId})` : ""} for combo "${combo.name}"`
- );
- } else if (lkgpIndex === 0) {
- log.debug?.(
- "COMBO",
- `[LKGP] Last known good provider ${providerName}${connId ? ` (account ${connId})` : ""} already first for combo "${combo.name}"`
- );
- }
- }
- } catch (err) {
- log.warn("COMBO", "Failed to retrieve Last Known Good Provider. This is non-fatal.", { err });
- }
- } else if (strategy === "strict-random") {
- const selectedExecutionKey = await getNextFromDeck(
- `combo:${combo.name}`,
- orderedTargets.map((target) => target.executionKey)
- );
- const selectedTarget =
- orderedTargets.find((target) => target.executionKey === selectedExecutionKey) || null;
- // #3959: shuffle the fallback remainder too. Previously `rest` kept fixed
- // priority order, so after a failing deck pick the chain always fell through
- // to the same top-priority model — a persistently-failing model was retried
- // on essentially every request and fallback load never spread across peers.
- const rest = fisherYatesShuffle(
- orderedTargets.filter((target) => target.executionKey !== selectedExecutionKey)
- );
- orderedTargets = [selectedTarget, ...rest].filter(
- (target): target is ResolvedComboTarget => target !== null
- );
- log.info(
- "COMBO",
- `Strict-random deck: ${selectedExecutionKey} selected (${orderedTargets.length} targets)`
- );
- } else if (strategy === "random") {
- orderedTargets = fisherYatesShuffle([...orderedTargets]);
- log.info("COMBO", `Random shuffle: ${orderedTargets.length} targets`);
- } else if (strategy === "fill-first") {
- log.info(
- "COMBO",
- `Fill-first ordering: preserving priority order (${orderedTargets.length} targets)`
- );
- } else if (strategy === "p2c") {
- orderedTargets = orderTargetsByPowerOfTwoChoices(orderedTargets, combo.name);
- log.info("COMBO", `Power-of-two-choices ordering: selected ${orderedTargets[0]?.modelStr}`);
- } else if (strategy === "least-used") {
- orderedTargets = sortTargetsByUsage(orderedTargets, combo.name);
- log.info("COMBO", `Least-used ordering: ${orderedTargets[0]?.modelStr} has fewest requests`);
- } else if (strategy === "cost-optimized") {
- orderedTargets = await sortTargetsByCost(orderedTargets);
- if (config.manifestRouting === true) {
- try {
- const manifestHint = generateRoutingHints(
- orderedTargets.filter((t) => t.kind === "model"),
- {
- messages: Array.isArray(body?.messages)
- ? (body.messages as Array<{ role?: string; content?: string | unknown }>)
- : [],
- tools: Array.isArray(body?.tools)
- ? (body.tools as Array<{
- function?: { name: string; description?: string; parameters?: unknown };
- }>)
- : undefined,
- model: typeof body?.model === "string" ? body.model : undefined,
- }
- );
- if (manifestHint.strategyModifier === "require-premium") {
- const eligible = orderedTargets.filter(
- (t) =>
- t.kind !== "model" ||
- manifestHint.eligibleTargets.some(
- (e) => e.provider === t.provider && e.modelStr === t.modelStr
- )
- );
- if (eligible.length > 0) orderedTargets = eligible;
- }
- log.debug?.(
- {
- strategyModifier: manifestHint.strategyModifier,
- specificityLevel: manifestHint.specificityLevel,
- score: manifestHint.specificity.score,
- },
- "manifest routing applied"
- );
- } catch (err) {
- log.warn({ err }, "manifest routing failed, falling back to standard strategy");
- }
- }
- log.info("COMBO", `Cost-optimized ordering: cheapest first (${orderedTargets[0]?.modelStr})`);
- } else if (strategy === "reset-aware") {
- orderedTargets = await orderTargetsByResetAwareQuota(
- orderedTargets,
- combo.name,
- config,
- log,
- apiKeyAllowedConnections
- );
- log.info(
- "COMBO",
- `Reset-aware ordering: ${orderedTargets[0]?.modelStr}${orderedTargets[0]?.connectionId ? ` (${orderedTargets[0].connectionId})` : ""} first`
- );
- } else if (strategy === "reset-window") {
- orderedTargets = await orderTargetsByResetWindow(
- orderedTargets,
- combo.name,
- config,
- log,
- apiKeyAllowedConnections
- );
- log.info(
- "COMBO",
- `Reset-window ordering: ${orderedTargets[0]?.modelStr}${orderedTargets[0]?.connectionId ? ` (${orderedTargets[0].connectionId})` : ""} first`
- );
- } else if (strategy === "context-optimized") {
- orderedTargets = sortTargetsByContextSize(orderedTargets);
- log.info("COMBO", `Context-optimized ordering: largest first (${orderedTargets[0]?.modelStr})`);
- } else if (strategy === "headroom") {
- orderedTargets = await orderTargetsByHeadroom(
- orderedTargets,
- combo.name,
- log,
- apiKeyAllowedConnections
- );
- log.info(
- "COMBO",
- `Headroom ordering: ${orderedTargets[0]?.modelStr}${orderedTargets[0]?.connectionId ? ` (${orderedTargets[0].connectionId})` : ""} has most free capacity`
- );
- } else if (strategy === "quota-share") {
- // Internal quota-share combos (qtSd/): delegate to the dedicated module (DRR +
- // P2C in-flight + per-model bucket gating + per-connection concurrency gating).
- const qsModel =
- typeof body?.model === "string" ? body.model : (orderedTargets[0]?.modelStr ?? "");
- const qsMaxConcurrent = await resolveMaxConcurrentByConnection(orderedTargets);
- orderedTargets = selectQuotaShareTarget(orderedTargets, combo.name, qsModel, Date.now(), {
- maxConcurrentByConnection: qsMaxConcurrent,
- }).orderedTargets;
- log.info(
- "COMBO",
- `Quota-share ordering: ${orderedTargets[0]?.modelStr}${orderedTargets[0]?.connectionId ? ` (${orderedTargets[0].connectionId})` : ""} selected (DRR+P2C)`
- );
- }
-
- return orderedTargets;
-}
diff --git a/open-sse/services/combo/autoConfig.ts b/open-sse/services/combo/autoConfig.ts
deleted file mode 100644
index c79c9ad032..0000000000
--- a/open-sse/services/combo/autoConfig.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-import { DEFAULT_WEIGHTS, type ScoringWeights } from "../autoCombo/scoring.ts";
-import { isRecord } from "./comboData.ts";
-import { resolveResetWindowConfig, resolveSlaRoutingPolicy } from "./quotaScoring.ts";
-import type { ComboLike, ResolvedComboTarget } from "./types.ts";
-
-/**
- * Resolve the auto-strategy routing configuration for a combo.
- *
- * Pure function of `(combo, eligibleTargets)`: derives the router strategy name,
- * candidate provider pool, scoring weights, exploration rate, budget cap, mode
- * pack, reset-window config and SLA policy from the combo's `autoConfig`/`config`.
- * No side effects, no early returns — extracted verbatim from `handleComboChat`
- * so its behavior is byte-identical to the previous inline block.
- */
-export function parseAutoConfig(combo: ComboLike, eligibleTargets: ResolvedComboTarget[]) {
- const rawAutoConfigSource =
- combo?.autoConfig ||
- (isRecord(combo?.config?.auto) ? combo.config.auto : null) ||
- combo?.config ||
- {};
- const autoConfigSource: Record<string, unknown> = isRecord(rawAutoConfigSource)
- ? rawAutoConfigSource
- : {};
- const routingStrategy =
- typeof autoConfigSource.routerStrategy === "string"
- ? autoConfigSource.routerStrategy
- : typeof autoConfigSource.routingStrategy === "string"
- ? autoConfigSource.routingStrategy
- : typeof autoConfigSource.strategyName === "string"
- ? autoConfigSource.strategyName
- : "rules";
-
- const candidatePool = Array.isArray(autoConfigSource.candidatePool)
- ? autoConfigSource.candidatePool
- : [...new Set(eligibleTargets.map((target) => target.provider))];
-
- const weights =
- autoConfigSource.weights && typeof autoConfigSource.weights === "object"
- ? (autoConfigSource.weights as ScoringWeights)
- : DEFAULT_WEIGHTS;
- const explorationRate = Number.isFinite(Number(autoConfigSource.explorationRate))
- ? Number(autoConfigSource.explorationRate)
- : 0.05;
- const budgetCap = Number.isFinite(Number(autoConfigSource.budgetCap))
- ? Number(autoConfigSource.budgetCap)
- : undefined;
- const modePack =
- typeof autoConfigSource.modePack === "string" ? autoConfigSource.modePack : undefined;
- const resetWindowConfig = resolveResetWindowConfig(autoConfigSource);
- const slaPolicy = resolveSlaRoutingPolicy(autoConfigSource);
-
- return {
- routingStrategy,
- candidatePool,
- weights,
- explorationRate,
- budgetCap,
- modePack,
- resetWindowConfig,
- slaPolicy,
- };
-}
diff --git a/open-sse/services/combo/quotaExhaustionCutoff.ts b/open-sse/services/combo/quotaExhaustionCutoff.ts
deleted file mode 100644
index e0b75c1873..0000000000
--- a/open-sse/services/combo/quotaExhaustionCutoff.ts
+++ /dev/null
@@ -1,140 +0,0 @@
-/**
- * Quota-exhaustion cutoff helpers for combo routing.
- *
- * Home of the opt-in per-(provider, connection, window) quota-exhaustion cutoff
- * shared by the "auto" strategy candidate builder (`buildAutoQuotaThresholds`,
- * consumed by combo.ts::buildAutoCandidates) and the per-target eligibility loop
- * (`resolveQuotaExhaustionCutoffForTarget`, consumed by combo.ts::handleComboChat
- * for every non-auto strategy). Extracted from combo.ts (#5923 Finding #4) to
- * keep the god-file under its frozen size cap; behavior is byte-identical.
- *
- * Pure leaf: this module never imports from the combo barrel. Threshold math and
- * cutoff evaluation are delegated to ./quotaPreflight.ts; the reset-aware quota
- * fetch/cache is delegated to ./quotaStrategies.ts.
- */
-
-import {
- evaluateQuotaCutoff,
- getQuotaFetcher,
- type PreflightQuotaThresholds,
- type QuotaInfo,
-} from "../quotaPreflight.ts";
-import { getProviderConnectionById } from "../../../src/lib/db/providers";
-import {
- resolveResilienceSettings,
- type ResilienceSettings,
-} from "../../../src/lib/resilience/settings";
-import { fetchResetAwareQuotaWithCache } from "./quotaStrategies.ts";
-import type { ResetWindowConfig } from "./quotaScoring.ts";
-
-function asThresholdMap(value: unknown): Record<string, number> {
- if (!value || typeof value !== "object" || Array.isArray(value)) return {};
- const result: Record<string, number> = {};
- for (const [key, raw] of Object.entries(value as Record<string, unknown>)) {
- const numeric = Number(raw);
- if (key && Number.isFinite(numeric)) result[key] = numeric;
- }
- return result;
-}
-
-function quotaWindowLookupNames(provider: string, windowName: string): string[] {
- const names = [windowName];
- const lower = windowName.toLowerCase();
- if (lower !== windowName) names.push(lower);
- if (provider === "codex") {
- if (lower.includes("session") || lower === "5h" || lower === "five_hour") names.push("session");
- if (lower.includes("weekly") || lower === "7d" || lower === "seven_day") names.push("weekly");
- if (lower.includes("monthly") || lower === "30d") names.push("monthly");
- }
- return [...new Set(names)];
-}
-
-export function buildAutoQuotaThresholds(
- provider: string,
- connection: Record<string, unknown> | undefined,
- resilienceSettings: ResilienceSettings | null | undefined
-): PreflightQuotaThresholds {
- const quotaPreflight = (resilienceSettings ?? resolveResilienceSettings(null))?.quotaPreflight;
- const defaultThresholdPercent = quotaPreflight?.defaultThresholdPercent ?? 2;
- const warnThresholdPercent = quotaPreflight?.warnThresholdPercent ?? 20;
- const providerWindowMap = asThresholdMap(quotaPreflight?.providerWindowDefaults?.[provider]);
- const perConnectionWindowOverrides = asThresholdMap(connection?.quotaWindowThresholds);
-
- return {
- resolveMinRemainingPercent: (windowName: string | null): number => {
- if (windowName !== null) {
- for (const lookupWindowName of quotaWindowLookupNames(provider, windowName)) {
- const override = perConnectionWindowOverrides[lookupWindowName];
- if (typeof override === "number") return override;
- const providerDefault = providerWindowMap[lookupWindowName];
- if (typeof providerDefault === "number") return providerDefault;
- }
- }
- return defaultThresholdPercent;
- },
- resolveWarnRemainingPercent: () => warnThresholdPercent,
- };
-}
-
-/**
- * #5923 (Finding #4) — Shared quota-exhaustion cutoff predicate, scoped strictly
- * per (provider, connectionId, model window). Extracted from the inline logic
- * that `buildAutoCandidates` has always used (fetch via the SAME
- * `fetchResetAwareQuotaWithCache` cache, evaluate via the SAME pure
- * `evaluateQuotaCutoff` + `buildAutoQuotaThresholds`), so priority/weighted/etc.
- * strategies honor the operator's configured quota cutoff instead of only the
- * "auto" strategy.
- *
- * Gated behind the SAME opt-in setting as the auto-strategy cutoff
- * (`resilienceSettings.quotaPreflight.enabled`) — when that setting is off this
- * is a no-op, exactly like the auto path. Never touches the provider circuit
- * breaker; a blocked result only means "skip this one connection", leaving
- * every sibling connection/model for the same provider fully eligible.
- */
-export async function resolveQuotaExhaustionCutoffForTarget(
- provider: string,
- connectionId: string | undefined,
- resilienceSettings: ResilienceSettings | null | undefined,
- resetWindowConfig: ResetWindowConfig,
- comboName: string,
- log: { debug?: (...args: unknown[]) => void; warn?: (...args: unknown[]) => void }
-): Promise<{ blocked: boolean; reason?: string }> {
- const quotaCutoffEnabled =
- (resilienceSettings ?? resolveResilienceSettings(null))?.quotaPreflight?.enabled === true;
- if (!quotaCutoffEnabled || !provider || !connectionId) return { blocked: false };
-
- const fetcher = getQuotaFetcher(provider);
- if (!fetcher) return { blocked: false };
-
- let connection: Record<string, unknown> | undefined;
- try {
- connection = (await getProviderConnectionById(connectionId)) as
- | Record<string, unknown>
- | undefined;
- } catch {
- connection = undefined;
- }
-
- try {
- const quota = await fetchResetAwareQuotaWithCache({
- provider,
- connectionId,
- connection,
- fetcher,
- config: resetWindowConfig,
- log,
- comboName,
- });
- const cutoffDecision = evaluateQuotaCutoff(
- quota as QuotaInfo | null,
- buildAutoQuotaThresholds(provider, connection, resilienceSettings)
- );
- if (!cutoffDecision.proceed) {
- return { blocked: true, reason: cutoffDecision.reason || "quota_exhausted" };
- }
- } catch {
- // Fail-open: never block routing because the preflight fetch itself errored.
- return { blocked: false };
- }
- return { blocked: false };
-}
diff --git a/open-sse/services/combo/resolveAutoStrategy.ts b/open-sse/services/combo/resolveAutoStrategy.ts
deleted file mode 100644
index 980d922b27..0000000000
--- a/open-sse/services/combo/resolveAutoStrategy.ts
+++ /dev/null
@@ -1,306 +0,0 @@
-import { unavailableResponse } from "../../utils/error.ts";
-import { selectProvider as selectAutoProvider } from "../autoCombo/engine.ts";
-import { selectWithStrategy } from "../autoCombo/routerStrategy.ts";
-import { buildComplexityRoutingHint } from "../autoCombo/complexityRouter";
-import { recordComboIntent } from "../comboMetrics.ts";
-import { estimateTokens } from "../contextManager.ts";
-import { classifyWithConfig } from "../intentClassifier.ts";
-import type { RoutingHint } from "../manifestAdapter";
-import { parseModel } from "../model.ts";
-import { supportsToolCalling } from "../modelCapabilities.ts";
-import type { ResilienceSettings } from "../../../src/lib/resilience/settings";
-import { parseAutoConfig } from "./autoConfig.ts";
-import { dedupeTargetsByExecutionKey } from "./comboData.ts";
-import { getModelContextLimitForModelString } from "./comboStructure.ts";
-import type { ResetWindowConfig } from "./quotaScoring.ts";
-import {
- _registerExecutionCandidates,
- expandAutoComboCandidatePool,
- extractPromptForIntent,
- getIntentConfig,
- mapIntentToTaskType,
- scoreAutoTargets,
-} from "./autoStrategy.ts";
-import type {
- AutoProviderCandidate,
- ComboLike,
- ComboLogger,
- ResolvedComboTarget,
-} from "./types.ts";
-
-/**
- * Dependency-injected `buildAutoCandidates` — it lives in `combo.ts` (the host of
- * this leaf), so importing it directly would create an import cycle. Passing it
- * through `deps` keeps this module acyclic (same pattern as `buildTargetTimeoutRunner`).
- */
-type BuildAutoCandidates = (
- targets: ResolvedComboTarget[],
- comboName: string,
- sessionId?: string | null,
- resetWindowConfig?: ResetWindowConfig,
- resilienceSettings?: ResilienceSettings | null
-) => Promise<AutoProviderCandidate[]>;
-
-export interface ResolveAutoStrategyDeps {
- orderedTargets: ResolvedComboTarget[];
- body: Record<string, unknown>;
- combo: ComboLike;
- settings: Record<string, unknown> | null | undefined;
- config: { complexityAwareRouting?: boolean };
- relayOptions?: { bypassProviderQuotaPolicy?: boolean; sessionId?: string | null } | null;
- resilienceSettings: ResilienceSettings;
- log: ComboLogger;
- buildAutoCandidates: BuildAutoCandidates;
-}
-
-export type ResolveAutoStrategyResult =
- | { earlyResponse: Response }
- | { orderedTargets: ResolvedComboTarget[]; autoUsedExplicitRouter: boolean };
-
-/**
- * Resolve target ordering for the `auto` combo strategy.
- *
- * Extracted verbatim from `handleComboChat`'s `if (strategy === "auto")` branch:
- * tool-calling + context-window pre-filters, intent classification, candidate
- * building (quota cutoff), explicit-router vs rules selection, complexity-aware
- * scoring and final dedup ordering. Behavior is byte-identical to the previous
- * inline block; the two `return unavailableResponse(...)` exits become
- * `{ earlyResponse }` so the host can decide to return them, and the mutated
- * `orderedTargets` / `autoUsedExplicitRouter` are returned instead of closed over.
- */
-export async function resolveAutoStrategyOrder(
- deps: ResolveAutoStrategyDeps
-): Promise<ResolveAutoStrategyResult> {
- const {
- body,
- combo,
- settings,
- config,
- relayOptions,
- resilienceSettings,
- log,
- buildAutoCandidates,
- } = deps;
- let orderedTargets = deps.orderedTargets;
- let autoUsedExplicitRouter = false;
-
- const requestHasTools = Array.isArray(body?.tools) && body.tools.length > 0;
- let eligibleTargets = [...orderedTargets];
-
- if (requestHasTools) {
- const filtered = eligibleTargets.filter((target) => supportsToolCalling(target.modelStr));
- if (filtered.length > 0) {
- eligibleTargets = filtered;
- } else {
- log.warn(
- "COMBO",
- "Auto strategy: all candidates filtered by tool-calling policy, falling back to full pool"
- );
- }
- }
-
- // Context-window pre-filter (#1808)
- // Estimate input tokens once; exclude candidates whose known context limit is too small.
- // Uses the same 4-chars-per-token heuristic as contextManager.ts::compressContext().
- // Null/unknown limits are treated as "include" to avoid incorrectly dropping valid targets.
- const requestMessages = body.messages;
- const estimatedInputTokens = estimateTokens(
- typeof requestMessages === "string" ||
- (requestMessages !== null && typeof requestMessages === "object")
- ? requestMessages
- : []
- );
- if (estimatedInputTokens > 0) {
- const filteredByContext = eligibleTargets.filter((target) => {
- const limit = getModelContextLimitForModelString(target.modelStr);
- if (limit === null || limit === undefined) return true; // unknown — include to be safe
- return limit >= estimatedInputTokens;
- });
- if (filteredByContext.length > 0) {
- log.debug?.(
- "COMBO",
- `Auto strategy: context-window filter kept ${filteredByContext.length}/${eligibleTargets.length} candidates (est. ${estimatedInputTokens} tokens)`
- );
- eligibleTargets = filteredByContext;
- } else {
- log.warn(
- "COMBO",
- `Auto strategy: all candidates filtered by context-window policy (est. ${estimatedInputTokens} tokens), falling back to full pool`
- );
- // eligibleTargets intentionally unchanged — same fallback contract as tool-calling filter
- }
-
- eligibleTargets = await expandAutoComboCandidatePool(eligibleTargets, combo);
- }
-
- const prompt = extractPromptForIntent(body);
- const systemPrompt = typeof combo?.system_message === "string" ? combo.system_message : undefined;
- const intentConfig = getIntentConfig(settings, combo);
- const intent = classifyWithConfig(prompt, intentConfig, systemPrompt);
- recordComboIntent(combo.name, intent);
- const taskType = mapIntentToTaskType(intent);
-
- const {
- routingStrategy,
- candidatePool,
- weights,
- explorationRate,
- budgetCap,
- modePack,
- resetWindowConfig,
- slaPolicy,
- } = parseAutoConfig(combo, eligibleTargets);
-
- let lastKnownGoodProvider: string | undefined;
- try {
- const { getLKGP } = await import("../../../src/lib/localDb");
- const lkgp = await getLKGP(combo.name, combo.id || combo.name);
- if (lkgp) lastKnownGoodProvider = lkgp.provider;
- } catch (err) {
- log.warn("COMBO", "Failed to retrieve Last Known Good Provider. This is non-fatal.", { err });
- }
-
- const autoCandidateResilienceSettings =
- relayOptions?.bypassProviderQuotaPolicy === true
- ? {
- ...resilienceSettings,
- quotaPreflight: {
- ...resilienceSettings.quotaPreflight,
- enabled: false,
- },
- }
- : resilienceSettings;
- const candidates = await buildAutoCandidates(
- eligibleTargets,
- combo.name,
- relayOptions?.sessionId,
- resetWindowConfig,
- autoCandidateResilienceSettings
- );
- const routableCandidates = candidates.filter(
- (candidate) => candidate.quotaCutoffBlocked !== true
- );
- const quotaBlockedCount = candidates.length - routableCandidates.length;
- if (quotaBlockedCount > 0) {
- log.info(
- "COMBO",
- `Auto strategy: quota cutoff skipped ${quotaBlockedCount}/${candidates.length} account candidates`
- );
- }
- // G2: Register candidates so chatCore can mark quotaSoftPenalty via setCandidateQuotaSoftPenalty.
- _registerExecutionCandidates(routableCandidates);
- if (candidates.length > 0 && routableCandidates.length === 0) {
- return {
- earlyResponse: unavailableResponse(
- 429,
- "All auto strategy candidates are below configured quota cutoffs"
- ),
- };
- }
- if (routableCandidates.length > 0) {
- let selectedProvider: string | null = null;
- let selectedModel: string | null = null;
- let selectionReason = "";
-
- if (routingStrategy !== "rules") {
- try {
- const decision = selectWithStrategy(
- routableCandidates,
- {
- taskType,
- requestHasTools,
- lastKnownGoodProvider,
- estimatedInputTokens,
- sla: slaPolicy,
- },
- routingStrategy
- );
- selectedProvider = decision.provider;
- selectedModel = decision.model;
- selectionReason = decision.reason;
- autoUsedExplicitRouter = true;
- } catch (err) {
- log.warn(
- "COMBO",
- `Auto strategy '${routingStrategy}' failed (${err?.message || "unknown"}), falling back to rules`
- );
- }
- }
-
- if (!selectedProvider || !selectedModel) {
- const selection = selectAutoProvider(
- {
- id: combo.id || combo.name,
- name: combo.name,
- type: "auto",
- candidatePool,
- weights,
- modePack,
- budgetCap,
- explorationRate,
- },
- routableCandidates,
- taskType
- );
- selectedProvider = selection.provider;
- selectedModel = selection.model;
- selectionReason = `score=${selection.score.toFixed(3)}${selection.isExploration ? " (exploration)" : ""}`;
- }
-
- // Complexity-aware routing (2026, opt-in): classify the request's
- // difficulty and feed a tier hint into scoring so tierAffinity /
- // specificityMatch favor candidates whose tier matches the request.
- const autoManifestHint: RoutingHint | null =
- config.complexityAwareRouting === true
- ? buildComplexityRoutingHint(
- eligibleTargets.filter((t) => t.kind === "model"),
- body,
- log
- )
- : null;
-
- const scoredTargets = scoreAutoTargets(
- eligibleTargets,
- routableCandidates,
- taskType,
- weights,
- autoManifestHint
- );
- const rankedTargets = scoredTargets.map((entry) => entry.target);
- const selectedTarget =
- scoredTargets.find((entry) => {
- const parsed = parseModel(entry.target.modelStr);
- const modelId = parsed.model || entry.target.modelStr;
- return entry.target.provider === selectedProvider && modelId === selectedModel;
- })?.target ||
- rankedTargets[0] ||
- eligibleTargets[0];
- if (!selectedTarget) {
- return {
- earlyResponse: unavailableResponse(
- 429,
- "No auto strategy targets remained after quota cutoff filtering"
- ),
- };
- }
-
- // Keep eligibleTargets as the last-resort fallback tail: dedupe drops the
- // routable ranked ones (and, when the cutoff is OFF, makes this identical to
- // the pre-cutoff behavior), but a quota-blocked target still survives as a
- // final fallback instead of vanishing — the hard cutoff only de-prioritizes.
- orderedTargets = dedupeTargetsByExecutionKey(
- [selectedTarget, ...rankedTargets, ...eligibleTargets].filter(
- (entry): entry is ResolvedComboTarget => entry !== undefined && entry !== null
- )
- );
-
- log.info(
- "COMBO",
- `Auto selection: ${selectedTarget?.modelStr || `${selectedProvider}/${selectedModel}`} | intent=${intent} task=${taskType} | strategy=${routingStrategy} | ${selectionReason}`
- );
- } else {
- log.warn("COMBO", "Auto strategy has no candidates, keeping default ordering");
- }
-
- return { orderedTargets, autoUsedExplicitRouter };
-}
diff --git a/open-sse/services/combo/targetExhaustion.ts b/open-sse/services/combo/targetExhaustion.ts
index 7091b483ef..01f73d58db 100644
--- a/open-sse/services/combo/targetExhaustion.ts
+++ b/open-sse/services/combo/targetExhaustion.ts
@@ -104,7 +104,7 @@ export function applyComboTargetExhaustion(
if (result.status === 429 && !isTokenLimitBreach && provider && provider !== "unknown") {
transientRateLimitedProviders.add(provider);
}
- markConnectionLevelExhaustion(target, { result, errorText, sets, log, tag, rawModel });
+ markConnectionLevelExhaustion(target, { result, errorText, sets, log, tag });
}
return providerExhausted;
@@ -118,12 +118,9 @@ export function applyComboTargetExhaustion(
*/
function markConnectionLevelExhaustion(
target: ResolvedComboTarget,
- opts: Pick<
- ApplyComboTargetExhaustionOptions,
- "result" | "errorText" | "sets" | "log" | "tag" | "rawModel"
- >
+ opts: Pick<ApplyComboTargetExhaustionOptions, "result" | "errorText" | "sets" | "log" | "tag">
): void {
- const { result, errorText, sets, log, tag, rawModel } = opts;
+ const { result, errorText, sets, log, tag } = opts;
const provider = target.provider;
if (
!provider ||
@@ -133,13 +130,7 @@ function markConnectionLevelExhaustion(
// #5085: empty-content 502 is a healthy connection returning no body — model-level, not
// connection-level. Don't exhaust the provider; let the remaining legs (incl. same-provider)
// be tried in-request.
- isEmptyContentFailure(result.status, errorText) ||
- // Per-model-quota providers (gemini, github, passthrough, compatible) multiplex models
- // behind one connection. A model-level 500 (e.g. Gemini "Internal error encountered")
- // must NOT exhaust the connection — other models on the same connection may still succeed.
- // Other connection-level statuses (408/502/503/504/524) indicate the connection itself is
- // bad, so they correctly exhaust even for per-model-quota providers.
- (result.status === 500 && hasPerModelQuota(provider, rawModel))
+ isEmptyContentFailure(result.status, errorText)
) {
return;
}
diff --git a/open-sse/services/combo/targetTimeoutRunner.ts b/open-sse/services/combo/targetTimeoutRunner.ts
deleted file mode 100644
index a1479b8e07..0000000000
--- a/open-sse/services/combo/targetTimeoutRunner.ts
+++ /dev/null
@@ -1,91 +0,0 @@
-/**
- * Wrap a single-model dispatch with a per-target timeout that aborts and falls back.
- *
- * Verbatim extraction of handleComboChat's `handleSingleModelWithTimeout` closure
- * (combo.ts). Behavior is byte-identical; the only change is that the closed-over locals
- * (`handleSingleModel`, `comboTargetTimeoutMs`, `log`) became explicit factory params.
- * The per-model abort signal still comes from the target (`target.modelAbortSignal`), so
- * the outer request signal is intentionally NOT a dependency here.
- *
- * See _tasks/superpowers/plans/2026-07-03-blocoJ-combo-hotpath-decomposition.md (Task 1).
- */
-import { errorResponse } from "../../utils/error.ts";
-import type { HandleSingleModel, SingleModelTarget, ComboLogger } from "./types.ts";
-
-export function buildTargetTimeoutRunner(deps: {
- handleSingleModel: HandleSingleModel;
- comboTargetTimeoutMs: number;
- log: ComboLogger;
-}): (
- b: Record<string, unknown>,
- modelStr: string,
- target?: SingleModelTarget
-) => Promise<Response> {
- const { handleSingleModel, comboTargetTimeoutMs, log } = deps;
- return async (
- b: Record<string, unknown>,
- modelStr: string,
- target?: SingleModelTarget
- ): Promise<Response> => {
- if (comboTargetTimeoutMs <= 0) {
- return handleSingleModel(b, modelStr, target).catch((err) =>
- errorResponse(502, err?.message ?? "Upstream model error")
- );
- }
-
- const timeoutController = new AbortController();
- let timeoutId: ReturnType<typeof setTimeout> | undefined;
- let timedOut = false;
- const timeoutPromise = new Promise<Response>((resolve) => {
- timeoutId = setTimeout(() => {
- timedOut = true;
- log.warn(
- "COMBO",
- `Model ${modelStr} exceeded ${comboTargetTimeoutMs}ms timeout — falling back`
- );
- timeoutController.abort(new Error("combo-per-model-timeout"));
- resolve(
- new Response(JSON.stringify({ error: { message: `Model ${modelStr} timed out` } }), {
- status: 524,
- headers: { "Content-Type": "application/json" },
- })
- );
- }, comboTargetTimeoutMs);
- });
- const targetWithSignal = {
- ...(target ?? {}),
- modelAbortSignal: timeoutController.signal,
- };
- const parentHedgeSignal = target?.modelAbortSignal ?? null;
- let onParentHedgeAbort: (() => void) | null = null;
- if (parentHedgeSignal) {
- if (parentHedgeSignal.aborted) {
- timeoutController.abort(new Error("hedge-cancelled"));
- } else {
- onParentHedgeAbort = () => {
- timeoutController.abort(new Error("hedge-cancelled"));
- };
- parentHedgeSignal.addEventListener("abort", onParentHedgeAbort, { once: true });
- }
- }
- try {
- return await Promise.race([
- handleSingleModel(b, modelStr, targetWithSignal).catch((err) => {
- if (timedOut) {
- // Inner call rejected because we aborted it. The synthetic 524 from
- // timeoutPromise already wins the race; return an empty response so
- // the loser branch resolves cleanly without leaking err.message.
- return new Response(null, { status: 599 });
- }
- return errorResponse(502, err?.message ?? "Upstream model error");
- }),
- timeoutPromise,
- ]);
- } finally {
- clearTimeout(timeoutId);
- if (parentHedgeSignal && onParentHedgeAbort) {
- parentHedgeSignal.removeEventListener("abort", onParentHedgeAbort);
- }
- }
- };
-}
diff --git a/open-sse/services/deviceTracker.ts b/open-sse/services/deviceTracker.ts
deleted file mode 100644
index 84d6985f57..0000000000
--- a/open-sse/services/deviceTracker.ts
+++ /dev/null
@@ -1,307 +0,0 @@
-/**
- * Per-API-Key Device Tracker
- *
- * Tracks unique client "devices" (IP + User-Agent fingerprint) that have used
- * a given API key, so operators can see how many distinct connections are
- * active behind a key — independent of `maxSessions` (which caps concurrent
- * sticky-routing sessions, not device identity; see `sessionManager.ts`).
- *
- * In-memory only, module-scoped Map (same pattern as `sessionManager.ts` —
- * no `global.*` singleton). Records never store the raw IP: it is masked
- * before being written, so even a memory dump or the `/api/keys/[id]/devices`
- * endpoint can't leak a full client IP.
- *
- * Ported from upstream 9router#931 (thanks @mugnimaestra) — original stored
- * a global singleton keyed by the raw API key string; this port keys by
- * `apiKeyInfo.id` (OmniRoute never threads the raw key value down to
- * `chatCore`) and follows the module-Map + `unref()` cleanup-timer pattern
- * used across `open-sse/services/`.
- */
-
-import { createHash } from "node:crypto";
-
-const DEFAULT_TTL_MS = 30 * 60 * 1000;
-const CLEANUP_INTERVAL_MS = 60 * 1000;
-const DEFAULT_MAX_DEVICES_PER_API_KEY = 1000;
-const DEFAULT_MAX_TOTAL_DEVICES = 10000;
-const MAX_STORED_USER_AGENT_LENGTH = 256;
-
-const TTL_ENV_NAME = "DEVICE_TRACKER_TTL_MS";
-const MAX_PER_KEY_ENV_NAME = "DEVICE_TRACKER_MAX_DEVICES_PER_KEY";
-const MAX_TOTAL_ENV_NAME = "DEVICE_TRACKER_MAX_TOTAL_DEVICES";
-
-interface DeviceRecord {
- fingerprint: string;
- /** Already masked — never the raw client IP. */
- ip: string;
- /** Truncated to MAX_STORED_USER_AGENT_LENGTH. */
- userAgent: string;
- lastSeen: number;
-}
-
-export interface DeviceDetail {
- /** Truncated fingerprint (first 12 hex chars) — never the full hash. */
- fingerprint: string;
- ip: string;
- userAgent: string;
- lastSeen: number;
-}
-
-function parseTtlMs(): number {
- const rawValue = process.env[TTL_ENV_NAME];
- if (!rawValue) return DEFAULT_TTL_MS;
- const parsedValue = Number(rawValue);
- if (!Number.isFinite(parsedValue) || parsedValue <= 0) return DEFAULT_TTL_MS;
- return parsedValue;
-}
-
-function parsePositiveIntegerEnv(envName: string, defaultValue: number): number {
- const rawValue = process.env[envName];
- if (!rawValue) return defaultValue;
- const parsedValue = Number(rawValue);
- if (!Number.isInteger(parsedValue) || parsedValue <= 0) return defaultValue;
- return parsedValue;
-}
-
-let ttlMs = parseTtlMs();
-let maxDevicesPerApiKey = parsePositiveIntegerEnv(
- MAX_PER_KEY_ENV_NAME,
- DEFAULT_MAX_DEVICES_PER_API_KEY
-);
-let maxTotalDevices = parsePositiveIntegerEnv(MAX_TOTAL_ENV_NAME, DEFAULT_MAX_TOTAL_DEVICES);
-
-// Module-scoped in-memory store — mirrors the `sessionManager.ts` pattern.
-// key: apiKeyId → Map<fingerprint, DeviceRecord>
-const devicesByApiKey = new Map<string, Map<string, DeviceRecord>>();
-
-let cleanupTimer: ReturnType<typeof setInterval> | null = null;
-
-/**
- * Mask an IP address so the stored/reported value never reveals the full
- * client address. IPv4 keeps the first two octets; IPv6 keeps the first
- * three groups.
- */
-export function maskIp(ip: string | null | undefined): string {
- if (!ip || ip === "unknown") return "unknown";
-
- const ipv4Parts = ip.split(".");
- if (ipv4Parts.length === 4 && ipv4Parts.every((part) => /^\d{1,3}$/.test(part))) {
- return `${ipv4Parts[0]}.${ipv4Parts[1]}.x.x`;
- }
-
- if (ip.includes(":")) {
- const visibleGroups = ip.split(":").filter(Boolean).slice(0, 3).join(":");
- return visibleGroups ? `${visibleGroups}:...` : "unknown";
- }
-
- return "masked";
-}
-
-function truncateUserAgent(userAgent: string): string {
- if (userAgent.length <= MAX_STORED_USER_AGENT_LENGTH) return userAgent;
- return `${userAgent.slice(0, MAX_STORED_USER_AGENT_LENGTH)}...`;
-}
-
-function createFingerprint(ip: string, userAgent: string): string {
- return createHash("sha256").update(`${ip}|${userAgent}`).digest("hex");
-}
-
-function getTotalDeviceCount(): number {
- let count = 0;
- for (const devices of devicesByApiKey.values()) count += devices.size;
- return count;
-}
-
-function deleteDevice(apiKeyId: string, fingerprint: string): boolean {
- const devices = devicesByApiKey.get(apiKeyId);
- if (!devices) return false;
- const deleted = devices.delete(fingerprint);
- if (devices.size === 0) devicesByApiKey.delete(apiKeyId);
- return deleted;
-}
-
-function findOldestDevice(
- apiKeyId: string | null
-): { apiKeyId: string; fingerprint: string; lastSeen: number } | null {
- let oldest: { apiKeyId: string; fingerprint: string; lastSeen: number } | null = null;
- const entries = apiKeyId ? [[apiKeyId, devicesByApiKey.get(apiKeyId)] as const] : devicesByApiKey.entries();
-
- for (const [entryApiKeyId, devices] of entries) {
- if (!devices) continue;
- for (const [fingerprint, record] of devices.entries()) {
- if (!oldest || record.lastSeen < oldest.lastSeen) {
- oldest = { apiKeyId: entryApiKeyId, fingerprint, lastSeen: record.lastSeen };
- }
- }
- }
-
- return oldest;
-}
-
-function evictOldestDevice(apiKeyId: string | null = null): boolean {
- const oldest = findOldestDevice(apiKeyId);
- if (!oldest) return false;
- return deleteDevice(oldest.apiKeyId, oldest.fingerprint);
-}
-
-function enforceDeviceLimits(apiKeyId: string, devices: Map<string, DeviceRecord>): void {
- while (devices.size >= maxDevicesPerApiKey) {
- if (!evictOldestDevice(apiKeyId)) break;
- }
- while (getTotalDeviceCount() >= maxTotalDevices) {
- if (!evictOldestDevice()) break;
- }
-}
-
-/**
- * Remove expired device records. Exported for tests; the cleanup timer
- * calls this on an interval in production.
- */
-export function expireDevices(now: number = Date.now()): number {
- let expiredCount = 0;
-
- for (const [apiKeyId, devices] of devicesByApiKey.entries()) {
- for (const [fingerprint, record] of devices.entries()) {
- if (now - record.lastSeen > ttlMs) {
- devices.delete(fingerprint);
- expiredCount += 1;
- }
- }
- if (devices.size === 0) devicesByApiKey.delete(apiKeyId);
- }
-
- return expiredCount;
-}
-
-function ensureCleanupTimer(): void {
- if (cleanupTimer) return;
- cleanupTimer = setInterval(() => {
- expireDevices();
- }, CLEANUP_INTERVAL_MS);
- cleanupTimer.unref?.();
-}
-
-ensureCleanupTimer();
-
-/**
- * Extract the client IP from a header source. Mirrors the priority order
- * already used across `open-sse/` (`cf-connecting-ip` → `x-real-ip` →
- * `x-forwarded-for`, first hop only). Returns "unknown" when absent.
- */
-export function extractIpFromHeaders(
- headers: Record<string, unknown> | Headers | null | undefined
-): string {
- if (!headers) return "unknown";
-
- const getHeader = (name: string): string | null => {
- if (headers instanceof Headers) return headers.get(name);
- for (const [key, value] of Object.entries(headers)) {
- if (key.toLowerCase() === name && typeof value === "string" && value.trim()) {
- return value.trim();
- }
- }
- return null;
- };
-
- const edgeIp =
- getHeader("cf-connecting-ip") || getHeader("x-real-ip") || getHeader("fastly-client-ip");
- if (edgeIp) return edgeIp;
-
- const forwardedFor = getHeader("x-forwarded-for");
- if (forwardedFor) {
- const firstIp = forwardedFor.split(",")[0]?.trim();
- if (firstIp) return firstIp;
- }
-
- return "unknown";
-}
-
-/**
- * Track a device (IP + User-Agent fingerprint) for an API key. Idempotent —
- * calling it again for the same key + fingerprint just refreshes `lastSeen`.
- * No-ops (returns null) when `apiKeyId` is missing, so callers can call it
- * unconditionally after resolving `apiKeyInfo`.
- */
-export function trackDevice(
- apiKeyId: string | null | undefined,
- ip: string | null | undefined,
- userAgent: string | null | undefined
-): string | null {
- if (!apiKeyId || typeof apiKeyId !== "string") return null;
-
- const now = Date.now();
- expireDevices(now);
-
- const resolvedIp = ip && ip.trim() ? ip.trim() : "unknown";
- const resolvedUserAgent = userAgent && userAgent.trim() ? userAgent.trim() : "unknown";
- const fingerprint = createFingerprint(resolvedIp, resolvedUserAgent);
-
- let devices = devicesByApiKey.get(apiKeyId);
- if (!devices) {
- devices = new Map();
- devicesByApiKey.set(apiKeyId, devices);
- }
-
- const existingRecord = devices.get(fingerprint);
- if (existingRecord) {
- existingRecord.lastSeen = now;
- } else {
- enforceDeviceLimits(apiKeyId, devices);
- if (!devicesByApiKey.has(apiKeyId)) devicesByApiKey.set(apiKeyId, devices);
- devices.set(fingerprint, {
- fingerprint,
- ip: maskIp(resolvedIp),
- userAgent: truncateUserAgent(resolvedUserAgent),
- lastSeen: now,
- });
- }
-
- return fingerprint;
-}
-
-/** Number of distinct devices currently tracked for an API key. */
-export function getDeviceCount(apiKeyId: string | null | undefined): number {
- expireDevices();
- if (!apiKeyId || typeof apiKeyId !== "string") return 0;
- return devicesByApiKey.get(apiKeyId)?.size || 0;
-}
-
-/** Device detail rows for an API key — masked IP, truncated fingerprint. */
-export function getDeviceDetails(apiKeyId: string | null | undefined): DeviceDetail[] {
- expireDevices();
- if (!apiKeyId || typeof apiKeyId !== "string") return [];
-
- const devices = devicesByApiKey.get(apiKeyId);
- if (!devices) return [];
-
- return Array.from(devices.values()).map((record) => ({
- fingerprint: record.fingerprint.slice(0, 12),
- ip: record.ip,
- userAgent: record.userAgent,
- lastSeen: record.lastSeen,
- }));
-}
-
-/** Device counts for every tracked API key. */
-export function getAllDeviceCounts(): Record<string, number> {
- expireDevices();
- const counts: Record<string, number> = {};
- for (const [apiKeyId, devices] of devicesByApiKey.entries()) {
- counts[apiKeyId] = devices.size;
- }
- return counts;
-}
-
-/**
- * Test-only reset — mirrors `sessionManager.ts::clearSessions()`. Also lets
- * tests override the TTL/limit env vars deterministically.
- */
-export function clearDeviceTracker(): void {
- devicesByApiKey.clear();
- ttlMs = parseTtlMs();
- maxDevicesPerApiKey = parsePositiveIntegerEnv(
- MAX_PER_KEY_ENV_NAME,
- DEFAULT_MAX_DEVICES_PER_API_KEY
- );
- maxTotalDevices = parsePositiveIntegerEnv(MAX_TOTAL_ENV_NAME, DEFAULT_MAX_TOTAL_DEVICES);
-}
diff --git a/open-sse/services/hfModelSuggestions.ts b/open-sse/services/hfModelSuggestions.ts
deleted file mode 100644
index 09a273a687..0000000000
--- a/open-sse/services/hfModelSuggestions.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-/**
- * HuggingFace Hub "suggested models" helpers.
- *
- * Pure, unit-testable pieces used by
- * `GET /api/v1/providers/suggested-models` — that route proxies the public
- * HuggingFace Hub models search API (never exposing any HF token
- * client-side) and uses these helpers to map a dashboard media "kind" to an
- * HF `pipeline_tag`, then sort/limit the raw search results.
- */
-
-/** Media kinds (mirrors `RegistryMediaKind` in mediaServiceKinds.ts) that currently
- * have a mapped HF Hub `pipeline_tag`. Extend as more kinds get suggestions. */
-export const SUGGESTED_MODEL_KIND_PIPELINE_TAGS: Readonly<Record<string, string>> = {
- image: "text-to-image",
-};
-
-export type SuggestedModelKind = keyof typeof SUGGESTED_MODEL_KIND_PIPELINE_TAGS;
-
-/**
- * Resolve a dashboard media kind (e.g. "image") to the HuggingFace Hub
- * `pipeline_tag` used to search https://huggingface.co/api/models.
- * Returns null for kinds without a mapped pipeline tag.
- */
-export function resolveHfPipelineTag(kind: string): string | null {
- return SUGGESTED_MODEL_KIND_PIPELINE_TAGS[kind] ?? null;
-}
-
-/** Minimal shape consumed from the HF Hub `/api/models` search response. */
-export interface HfModelSummary {
- id: string;
- likes?: number;
- downloads?: number;
- pipeline_tag?: string;
-}
-
-export type HfSuggestedModelSortBy = "downloads" | "likes";
-
-/**
- * Pure filter/sort over raw HF Hub model search results:
- * - drops entries without a usable string `id`
- * - sorts descending by the requested metric (missing/non-numeric treated as 0)
- * - caps the result to `limit` entries
- *
- * No network access — safe to unit test directly with fixture arrays.
- */
-export function sortHfSuggestedModels(
- models: readonly HfModelSummary[],
- sortBy: HfSuggestedModelSortBy = "downloads",
- limit = 20
-): HfModelSummary[] {
- const valid = (models ?? []).filter(
- (m): m is HfModelSummary => !!m && typeof m.id === "string" && m.id.trim().length > 0
- );
-
- const sorted = [...valid].sort((a, b) => {
- const bVal = Number(b[sortBy]);
- const aVal = Number(a[sortBy]);
- return (Number.isFinite(bVal) ? bVal : 0) - (Number.isFinite(aVal) ? aVal : 0);
- });
-
- const safeLimit = Number.isFinite(limit) && limit > 0 ? Math.floor(limit) : 20;
- return sorted.slice(0, safeLimit);
-}
diff --git a/open-sse/services/model.ts b/open-sse/services/model.ts
index 122247a966..54cc6a3e2c 100644
--- a/open-sse/services/model.ts
+++ b/open-sse/services/model.ts
@@ -32,6 +32,11 @@ for (const [id, alias] of Object.entries(PROVIDER_ID_TO_ALIAS)) {
// or backward-compatible slug changes, not a single provider's display name.
// opencode/ → opencode-zen (the main free/open tier; opencode-go is a separate paid tier)
ALIAS_TO_PROVIDER_ID["opencode"] = "opencode-zen";
+
+// Manual aliases for external compatibility not covered by PROVIDER_ID_TO_ALIAS.
+// OpenCode's Zen provider now uses the "opencode" slug, but OmniRoute registers
+// it as "opencode-zen". This alias ensures `opencode/<model>` resolves correctly.
+ALIAS_TO_PROVIDER_ID["opencode"] = "opencode-zen";
// xiaomi/ is the user-visible prefix for MiMo models; register it so
// parseModel("xiaomi/mimo-v2-flash") resolves provider = "xiaomi-mimo" instead
// of falling through to the identity fallback ("xiaomi").
@@ -142,19 +147,7 @@ interface ProviderConnectionLike {
*/
export function resolveProviderAlias(aliasOrId: string | null | undefined): string | null {
if (typeof aliasOrId !== "string") return null;
- // Follow the alias chain transitively so intermediate aliases
- // (e.g. "oc" -> "opencode" -> "opencode-zen") resolve to the final target.
- // Guarded against infinite loops with both a depth limit and a seen-set.
- let current = aliasOrId;
- const seen = new Set<string>();
- for (let i = 0; i < 10; i++) {
- const next = ALIAS_TO_PROVIDER_ID[current];
- if (!next || next === current) return current;
- if (seen.has(next)) return next;
- seen.add(next);
- current = next;
- }
- return current;
+ return ALIAS_TO_PROVIDER_ID[aliasOrId] || aliasOrId;
}
/**
@@ -553,15 +546,8 @@ async function resolveModelByProviderInference(modelId: string, extendedContext:
};
}
- // Fallback for newly released OpenAI-family model IDs that may not be in the local
- // catalog yet. This must only fire when NO known provider catalogs the model id —
- // otherwise it hijacks cataloged open-weight models like "gpt-oss-120b" (served by
- // fireworks/cerebras/scaleway/byteplus) into provider "openai", which does not carry
- // them (#5852).
- if (
- providers.length === 0 &&
- (/^gpt-/i.test(modelId) || /^o1/i.test(modelId) || /^o3/i.test(modelId))
- ) {
+ // Fallback for newly released OpenAI-family model IDs that may not be in the local catalog yet.
+ if (/^gpt-/i.test(modelId) || /^o1/i.test(modelId) || /^o3/i.test(modelId)) {
return {
provider: "openai",
model: modelId,
diff --git a/open-sse/services/modelFamilyFallback.ts b/open-sse/services/modelFamilyFallback.ts
index 16ef338874..216c2748b7 100644
--- a/open-sse/services/modelFamilyFallback.ts
+++ b/open-sse/services/modelFamilyFallback.ts
@@ -75,20 +75,15 @@ const MODEL_FAMILIES: Record<string, string[]> = {
// Claude Mythos family (Fable 5) — flagship falls to the next-best Opus
// tiers before the cheaper Sonnet, matching the Opus family ordering.
- "claude-fable-5": ["claude-opus-4-8", "claude-opus-4-7", "claude-sonnet-5"],
+ "claude-fable-5": ["claude-opus-4-8", "claude-opus-4-7", "claude-sonnet-4-6"],
// Claude Opus family
- "claude-opus-4-8": ["claude-opus-4-7", "claude-opus-4-6", "claude-sonnet-5"],
- "claude-opus-4-7": ["claude-opus-4-6", "claude-opus-4-5-20251101", "claude-sonnet-5"],
- "claude-opus-4-6": ["claude-opus-4-6-thinking", "claude-opus-4-5-20251101", "claude-sonnet-5"],
+ "claude-opus-4-8": ["claude-opus-4-7", "claude-opus-4-6", "claude-sonnet-4-6"],
+ "claude-opus-4-7": ["claude-opus-4-6", "claude-opus-4-5-20251101", "claude-sonnet-4-6"],
+ "claude-opus-4-6": ["claude-opus-4-6-thinking", "claude-opus-4-5-20251101", "claude-sonnet-4-6"],
"claude-opus-4-6-thinking": ["claude-opus-4-6", "claude-opus-4-5-20251101"],
- // Claude Sonnet family — Sonnet 5 is the newest tier; degrade to 4.6 → 4.5 → 4.
- "claude-sonnet-5": [
- "claude-sonnet-4-6",
- "claude-sonnet-4-5-20250929",
- "claude-sonnet-4-20250514",
- ],
+ // Claude Sonnet family
"claude-sonnet-4-6": ["claude-sonnet-4-5-20250929", "claude-sonnet-4-20250514"],
"claude-sonnet-4-5-20250929": ["claude-sonnet-4-6", "claude-sonnet-4-20250514"],
diff --git a/open-sse/services/providerCostData.ts b/open-sse/services/providerCostData.ts
index b9809dea99..b1be9d0203 100644
--- a/open-sse/services/providerCostData.ts
+++ b/open-sse/services/providerCostData.ts
@@ -15,7 +15,6 @@ export const KNOWN_MODEL_PRICING: Record<string, ModelPricing> = {
"claude-opus-4-8": { inputCostPer1M: 15.0, outputCostPer1M: 75.0, isFree: false },
"claude-opus-4-7": { inputCostPer1M: 15.0, outputCostPer1M: 75.0, isFree: false },
"claude-sonnet-4-6": { inputCostPer1M: 3.0, outputCostPer1M: 15.0, isFree: false },
- "claude-sonnet-5": { inputCostPer1M: 3.0, outputCostPer1M: 15.0, isFree: false },
"claude-haiku-4-5": { inputCostPer1M: 0.8, outputCostPer1M: 4.0, isFree: false },
"gemini-2.5-flash": { inputCostPer1M: 0.15, outputCostPer1M: 0.6, isFree: false },
"gemini-2.5-pro": { inputCostPer1M: 1.25, outputCostPer1M: 5.0, isFree: false },
diff --git a/open-sse/services/qoderCli.ts b/open-sse/services/qoderCli.ts
index 3aa110eee9..b8674483d0 100644
--- a/open-sse/services/qoderCli.ts
+++ b/open-sse/services/qoderCli.ts
@@ -1,17 +1,12 @@
import { spawn } from "child_process";
import crypto from "crypto";
-import fs from "fs";
-import os from "os";
-import path from "path";
const DEFAULT_TIMEOUT_MS = 45_000;
-const DEFAULT_MODELS_TIMEOUT_MS = 20_000;
+const DEFAULT_MAX_TURNS = "1";
const QODER_DEFAULT_MODEL = "qoder-rome-30ba3b";
export const QODER_STATIC_MODELS = [
{ id: "qoder-rome-30ba3b", name: "Qoder ROME" },
- { id: "glm-5.2", name: "GLM-5.2" },
- { id: "minimax-m3", name: "MiniMax M3" },
{ id: "qwen3-coder-plus", name: "Qwen3 Coder Plus" },
{ id: "qwen3-max", name: "Qwen3 Max" },
{ id: "qwen3-vl-plus", name: "Qwen3 Vision Plus" },
@@ -77,361 +72,6 @@ export function getQoderCliWorkspace(): string {
return home || process.cwd();
}
-/**
- * Isolated `--config-dir` for OmniRoute-driven qodercli runs. Keeping it separate
- * from the operator's own `~/.qoder` avoids polluting an interactive qodercli
- * session and lets each PAT authenticate via `QODER_PERSONAL_ACCESS_TOKEN`
- * without clobbering a browser login. Override with `QODER_CLI_CONFIG_DIR`.
- */
-export function getQoderCliConfigDir(): string {
- const explicit = String(process.env.QODER_CLI_CONFIG_DIR || "").trim();
- if (explicit) return explicit;
- const dataDir = String(process.env.DATA_DIR || "").trim();
- const base = dataDir || path.join(os.homedir() || os.tmpdir(), ".omniroute");
- return path.join(base, "qoder-cli");
-}
-
-// Memoized per resolved path so we don't hit synchronous disk I/O
-// (fs.mkdirSync blocks the event loop) on every chat/quota request.
-const ensuredQoderCliConfigDirs = new Set<string>();
-
-/** Ensure the qodercli config dir exists so it is a valid spawn cwd + cache root. */
-function ensureQoderCliConfigDir(): string {
- const dir = getQoderCliConfigDir();
- if (ensuredQoderCliConfigDirs.has(dir)) return dir;
- try {
- fs.mkdirSync(dir, { recursive: true });
- ensuredQoderCliConfigDirs.add(dir);
- } catch {
- /* best-effort — spawn will surface a real failure */
- }
- return dir;
-}
-
-type SpawnQoderCliOptions = {
- args: string[];
- token?: string | null;
- stdin?: string | null;
- signal?: AbortSignal | null;
- timeoutMs?: number;
- command?: string | null;
- cwd?: string | null;
-};
-
-/**
- * Low-level qodercli spawn. The PAT (if any) is passed via the
- * `QODER_PERSONAL_ACCESS_TOKEN` env var — the only env var the official CLI
- * honors for headless PAT auth — and the prompt is piped through stdin so no
- * untrusted value is ever interpolated into a shell command (Hard Rule #13).
- */
-function spawnQoderCli(options: SpawnQoderCliOptions): Promise<QoderCliRunResult> {
- const command = String(options.command || "").trim() || getQoderCliCommand();
- const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
- const env: NodeJS.ProcessEnv = { ...process.env };
- const token = String(options.token || "").trim();
- if (token) env.QODER_PERSONAL_ACCESS_TOKEN = token;
-
- return new Promise<QoderCliRunResult>((resolve) => {
- let stdout = "";
- let stderr = "";
- let settled = false;
- let timedOut = false;
-
- let child: ReturnType<typeof spawn>;
- try {
- child = spawn(command, options.args, {
- env,
- cwd: options.cwd || undefined,
- stdio: ["pipe", "pipe", "pipe"],
- });
- } catch (err) {
- resolve({
- ok: false,
- code: null,
- stdout: "",
- stderr: "",
- timedOut: false,
- error: (err as Error).message,
- });
- return;
- }
-
- const timer = setTimeout(() => {
- timedOut = true;
- try {
- child.kill("SIGKILL");
- } catch {
- /* already gone */
- }
- }, timeoutMs);
- timer.unref?.();
-
- const onAbort = () => {
- try {
- child.kill("SIGKILL");
- } catch {
- /* already gone */
- }
- };
- if (options.signal) {
- if (options.signal.aborted) onAbort();
- else options.signal.addEventListener("abort", onAbort, { once: true });
- }
-
- const finish = (result: QoderCliRunResult) => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- options.signal?.removeEventListener?.("abort", onAbort);
- resolve(result);
- };
-
- child.on("error", (err: Error) => {
- finish({ ok: false, code: null, stdout, stderr, timedOut, error: err.message });
- });
- // If qodercli exits or closes stdin before we finish writing the prompt, the
- // write/end below can emit an ASYNC EPIPE/EINVAL on the stream (not caught by
- // the surrounding try/catch). Without a listener that becomes an unhandled
- // 'error' event that crashes the whole process — attach no-op handlers.
- child.stdin?.on("error", () => {});
- child.stdout?.on("error", () => {});
- child.stderr?.on("error", () => {});
- // Decode with a stateful UTF-8 reader so a multi-byte character (e.g. Chinese,
- // common in Qoder output) split across two chunks is not corrupted — Buffer
- // per-chunk toString() would mangle the boundary bytes.
- child.stdout?.setEncoding("utf8");
- child.stderr?.setEncoding("utf8");
- child.stdout?.on("data", (chunk: string) => {
- stdout += chunk;
- });
- child.stderr?.on("data", (chunk: string) => {
- stderr += chunk;
- });
- child.on("close", (code: number | null) => {
- finish({
- ok: code === 0 && !timedOut,
- code,
- stdout,
- stderr,
- timedOut,
- error: timedOut ? "qodercli timed out" : null,
- });
- });
-
- try {
- if (options.stdin != null) child.stdin?.write(options.stdin);
- child.stdin?.end();
- } catch {
- /* stdin closed early — the child will surface its own error */
- }
- });
-}
-
-/**
- * Run a single non-interactive chat turn through qodercli. Returns the raw
- * process result; use {@link parseQoderCliResult} to extract the reply text.
- */
-export async function runQoderCli(options: QoderCliRunOptions): Promise<QoderCliRunResult> {
- const level = await resolveQoderCliModel(options.model, options.token, {
- command: options.command,
- signal: options.signal,
- });
- const configDir = ensureQoderCliConfigDir();
- const cwd = String(options.workspace || "").trim() || configDir;
- const args = [
- "--print",
- "--output-format",
- "json",
- "--model",
- level,
- // Disable all built-in tools — OmniRoute only wants a plain LM reply, never
- // file-system access or command execution from the proxied CLI.
- "--tools",
- "",
- "--config-dir",
- configDir,
- ];
- return spawnQoderCli({
- args,
- token: options.token,
- stdin: options.prompt,
- signal: options.signal,
- timeoutMs: options.timeoutMs,
- command: options.command,
- cwd,
- });
-}
-
-/**
- * List the models qodercli can reach for the given PAT. Used as a cheap
- * connection/credential check (no chat tokens are consumed).
- */
-export async function listQoderCliModels(
- options: {
- token?: string | null;
- signal?: AbortSignal | null;
- timeoutMs?: number;
- command?: string | null;
- } = {}
-): Promise<QoderCliRunResult> {
- const configDir = ensureQoderCliConfigDir();
- return spawnQoderCli({
- args: ["--list-models", "--config-dir", configDir],
- token: options.token,
- signal: options.signal,
- timeoutMs: options.timeoutMs ?? DEFAULT_MODELS_TIMEOUT_MS,
- command: options.command,
- cwd: configDir,
- });
-}
-
-/** Normalize a model id / display name so "glm-5.2" and "GLM-5.2" compare equal. */
-export function normalizeQoderModelKey(value: unknown): string {
- return String(value || "")
- .toLowerCase()
- .replace(/[^a-z0-9]/g, "");
-}
-
-/** Extract the display names from a `qodercli --list-models` table. */
-export function parseQoderCliModelNames(stdout: string): string[] {
- return String(stdout || "")
- .split("\n")
- .map((line) => line.replace(/\[[0-9;]*m/g, "").trim()) // strip ANSI colors
- .filter(
- (line) =>
- line.length > 0 &&
- line.toLowerCase() !== "model" && // header row
- !/invalid model|not logged in|please run|available model keys/i.test(line)
- );
-}
-
-/**
- * Resolve an OmniRoute model id to the exact value to pass to `qodercli -m`.
- * Pure (no I/O) so it can be unit-tested against a captured model list.
- *
- * Preference order:
- * 1. A live `--list-models` display name (case-insensitive, punctuation-insensitive)
- * — qodercli accepts these directly and they track upstream renames of the
- * opaque internal level keys.
- * 2. The static family map (level keys) — used when the live list is unavailable
- * or has no match.
- * 3. "Auto".
- */
-export function resolveQoderModelName(
- requested: string | null | undefined,
- availableNames: string[]
-): string {
- const normalized = normalizeQoderModelKey(requested);
- if (!normalized) return "auto";
- const match = (availableNames || []).find((name) => normalizeQoderModelKey(name) === normalized);
- if (match) return match;
- return mapQoderModelToLevel(requested) || "auto";
-}
-
-// Per-token cache of the `--list-models` display names (the catalog is stable and
-// per-account); TTL keeps it fresh without a CLI spawn on every request.
-const QODER_MODEL_LIST_TTL_MS = 10 * 60 * 1000;
-type QoderModelNamesCacheEntry = { names: string[]; expiresAt: number };
-const qoderModelNamesCache = new Map<string, QoderModelNamesCacheEntry>();
-const qoderModelNamesPending = new Map<string, Promise<string[]>>();
-
-async function getCachedQoderCliModelNames(
- token?: string | null,
- options: { command?: string | null; signal?: AbortSignal | null; now?: number } = {}
-): Promise<string[]> {
- const key = String(token || "").trim() || "default";
- const now = options.now ?? Date.now();
- const cached = qoderModelNamesCache.get(key);
- if (cached && cached.expiresAt > now) return cached.names;
-
- let pending = qoderModelNamesPending.get(key);
- if (!pending) {
- pending = listQoderCliModels({ token, command: options.command, signal: options.signal })
- .then((run) => {
- const names = run.ok ? parseQoderCliModelNames(run.stdout) : [];
- // Only cache a non-empty success; a failed/empty list should retry next time.
- if (names.length > 0) {
- qoderModelNamesCache.set(key, { names, expiresAt: now + QODER_MODEL_LIST_TTL_MS });
- }
- return names;
- })
- .catch(() => [] as string[])
- .finally(() => qoderModelNamesPending.delete(key));
- qoderModelNamesPending.set(key, pending);
- }
- return pending;
-}
-
-/** Async resolver: matches the request against the live (cached) `--list-models`. */
-export async function resolveQoderCliModel(
- requested: string | null | undefined,
- token?: string | null,
- options: { command?: string | null; signal?: AbortSignal | null } = {}
-): Promise<string> {
- let names: string[] = [];
- try {
- names = await getCachedQoderCliModelNames(token, options);
- } catch {
- names = [];
- }
- return resolveQoderModelName(requested, names);
-}
-
-/** Test-only: drop the cached `--list-models` names so unit tests don't leak state. */
-export function __clearQoderModelNamesCache(): void {
- qoderModelNamesCache.clear();
- qoderModelNamesPending.clear();
-}
-
-/**
- * Parse the `--output-format json` envelope qodercli prints in print mode. The
- * CLI may emit banner/log lines before the JSON, so we fall back to scanning for
- * the last JSON object line. Returns the assistant text plus an error flag.
- */
-export function parseQoderCliResult(stdout: string): {
- text: string;
- isError: boolean;
- errorMessage: string;
-} {
- const trimmed = String(stdout || "").trim();
- if (!trimmed) {
- return { text: "", isError: true, errorMessage: "qodercli produced no output" };
- }
-
- let parsed: JsonRecord | null = null;
- try {
- const whole = JSON.parse(trimmed);
- if (whole && typeof whole === "object") parsed = whole as JsonRecord;
- } catch {
- for (const line of trimmed.split("\n").reverse()) {
- const candidate = line.trim();
- if (!candidate.startsWith("{")) continue;
- try {
- const obj = JSON.parse(candidate);
- if (obj && typeof obj === "object") {
- parsed = obj as JsonRecord;
- break;
- }
- } catch {
- /* keep scanning earlier lines */
- }
- }
- }
-
- if (!parsed) {
- return { text: "", isError: true, errorMessage: trimmed.slice(0, 300) };
- }
-
- const result = getString(parsed.result);
- const isError =
- parsed.is_error === true || getString(parsed.subtype).trim().toLowerCase() === "error";
- return {
- text: result,
- isError,
- errorMessage: isError ? result || "qodercli returned an error" : "",
- };
-}
-
export function normalizeQoderPatProviderData(providerSpecificData: JsonRecord = {}): JsonRecord {
return {
...providerSpecificData,
@@ -452,33 +92,12 @@ export function getStaticQoderModels() {
return QODER_STATIC_MODELS.map((model) => ({ ...model }));
}
-/** qodercli's `-m` accepts these level keys (see `qodercli --list-models`). */
-const QODER_LEVEL_KEYS = new Set([
- "auto",
- "ultimate",
- "performance",
- "efficient",
- "lite",
- "q35model_preview",
- "qmodel_latest",
- "qmodel",
- "gm51model",
- "kmodel",
- "dmodel",
- "dfmodel",
- "mmodel",
-]);
-
export function mapQoderModelToLevel(model: string | null | undefined): string | null {
const normalized = String(model || "")
.trim()
.toLowerCase();
if (!normalized) return null;
- // A caller may pass a qodercli level key directly (e.g. "gm51model") — honor it.
- if (QODER_LEVEL_KEYS.has(normalized)) return normalized;
if (normalized.includes("deepseek-r1")) return "ultimate";
- if (normalized.includes("glm")) return "gm51model"; // GLM-5.2 (`qoder/glm-5.2`)
- if (normalized.includes("minimax")) return "mmodel";
if (normalized.includes("qwen3-max")) return "performance";
if (normalized.includes("kimi-k2")) return "kmodel";
if (normalized.includes("qwen3-coder")) return "qmodel";
@@ -691,13 +310,7 @@ export function parseQoderCliFailure(stderrText: string, stdoutText = ""): Qoder
if (
normalized.includes("invalid api key") ||
normalized.includes("invalid token") ||
- normalized.includes("invalid personal token") ||
normalized.includes("personal access token") ||
- normalized.includes("personal token format") ||
- normalized.includes("exchangejobtoken failed") ||
- normalized.includes("not logged in") ||
- normalized.includes("please run /login") ||
- normalized.includes("login required") ||
(normalized.includes("unauthorized") && normalized.includes("qoder"))
) {
return { status: 401, message: combined, code: "upstream_auth_error" };
@@ -928,61 +541,126 @@ export async function validateQoderCliPat({
};
}
- // Reference providerSpecificData so callers can still pass validation hints
- // (model id, etc.) without a signature change; the CLI resolves models itself.
- void providerSpecificData;
-
- // Validate by asking the local qodercli to list the models reachable for this
- // PAT. The official CLI signs the (WASM-based) Cosy request internally, which
- // the pure-HTTP path can no longer replicate — a raw Cosy call now returns a
- // generic 500 for every token, so it cannot distinguish valid from invalid.
- // `--list-models` authenticates without consuming any chat tokens.
- const run = await listQoderCliModels({ token: resolvedToken });
- const combined = `${run.stdout}\n${run.stderr}`.trim();
- const normalized = combined.toLowerCase();
+ const modelId =
+ getString(providerSpecificData.validationModelId).trim() ||
+ getString(providerSpecificData.modelId).trim() ||
+ QODER_DEFAULT_MODEL;
- if (run.error && /enoent|not found|no such file|spawn/i.test(run.error)) {
+ const bodyStr = JSON.stringify({
+ model: modelId || "coder-model",
+ messages: [{ role: "user", content: "hi" }],
+ stream: false,
+ });
+
+ // Step 1: Connectivity check — verify Qoder API is reachable
+ try {
+ const pingRes = await fetch("https://api1.qoder.sh/algo/api/v1/ping", {
+ method: "GET",
+ // @ts-ignore
+ signal: AbortSignal.timeout(10000),
+ });
+ if (!pingRes.ok) {
+ return {
+ valid: false,
+ error: `Qoder API unreachable (ping returned ${pingRes.status}). Check your network/proxy configuration.`,
+ unsupported: false,
+ };
+ }
+ } catch (pingErr: any) {
return {
valid: false,
error:
- `Qoder CLI (qodercli) was not found on the OmniRoute host (${run.error}). ` +
- "Install it from https://qoder.com or point CLI_QODER_BIN at the binary. " +
- "PAT auth is driven through the local qodercli binary.",
+ `Cannot reach Qoder API (${pingErr.message}). ` +
+ "If behind a proxy, configure HTTPS_PROXY. For Docker, ensure the container has internet access.",
unsupported: false,
};
}
- if (run.timedOut) {
+ // Step 2: Auth validation — exchange the PAT for a job token (#4683), then send a
+ // minimal request with the `jt-*` (Cosy rejects a raw `pt-*` with a generic 500).
+ const cosyToken = await resolveQoderJobToken(resolvedToken);
+ const headers = buildCosyHeadersForValidation(bodyStr, cosyToken);
+ const endpoint =
+ "https://api1.qoder.sh/algo/api/v2/service/pro/sse/agent_chat_generation?AgentId=agent_common";
+
+ try {
+ const res = await fetch(endpoint, {
+ method: "POST",
+ headers,
+ body: bodyStr,
+ // @ts-ignore
+ signal: AbortSignal.timeout(30000),
+ });
+
+ if (res.ok || res.status === 200) {
+ return { valid: true, error: null, unsupported: false };
+ }
+
+ // Parse error body for better diagnostics
+ let errorDetail = "";
+ try {
+ const errBody = await res.text();
+ errorDetail = errBody.slice(0, 300);
+ } catch {}
+
+ if (res.status === 401 || res.status === 403) {
+ return {
+ valid: false,
+ error:
+ `Authentication failed (HTTP ${res.status}). ` +
+ "Make sure you're using a valid Personal Access Token from https://qoder.com/account/integrations. " +
+ "Note: tokens from ~/.qoder/.auth/user are encrypted and cannot be used directly." +
+ (errorDetail ? ` Server: ${errorDetail}` : ""),
+ unsupported: false,
+ };
+ }
+
+ // 4xx other than auth — token was accepted but request had issues (model, format, etc.)
+ if (res.status >= 400 && res.status < 500) {
+ return { valid: true, error: null, unsupported: false };
+ }
+
+ // Treat 5xx as a valid bypass to prevent false negatives from legacy Qoder APIs (#1391).
+ // A Cosy `{"success":false}` 500 is ambiguous: it can be a genuine auth rejection OR a
+ // transient/generic upstream "Internal Server Error". Only mark the PAT invalid when the
+ // body carries an EXPLICIT auth signal — a generic 500 is a server fault, not an auth
+ // verdict, so a working PAT must not be reported as expired (#3247, narrowing #2860).
+ if (res.status >= 500) {
+ const isCosyResponse = /"success"\s*:\s*false/.test(errorDetail);
+ const hasAuthSignal =
+ /(unauthorized|forbidden|expired|revoked|not\s*authorized|permission\s*denied|access\s*denied|invalid\s*(?:token|credential|api[\s_-]*key)|token\s*(?:invalid|expired|revoked))/i.test(
+ errorDetail
+ );
+
+ if (isCosyResponse && hasAuthSignal) {
+ return {
+ valid: false,
+ error:
+ `Authentication failed (HTTP ${res.status}). The Qoder Cosy server rejected the token ` +
+ "as invalid, expired, or not authorized. " +
+ "Please check your token at https://qoder.com/account/integrations." +
+ (errorDetail ? ` Server response: ${errorDetail}` : ""),
+ unsupported: false,
+ };
+ }
+
+ return {
+ valid: true,
+ error: `Validation endpoint returned HTTP ${res.status}${errorDetail ? `: ${errorDetail}` : ""}, treating PAT as valid`,
+ unsupported: false,
+ };
+ }
+
return {
valid: false,
- error:
- "qodercli timed out while validating the token. Check network/proxy access from the OmniRoute host.",
+ error: `Qoder API returned HTTP ${res.status}${errorDetail ? `: ${errorDetail}` : ""}`,
unsupported: false,
};
- }
-
- if (
- /not logged in|please run \/login|login required|unauthorized|forbidden|exchangejobtoken failed|personal token format|invalid[\s\w]{0,40}?(?:token|credential|api[\s_-]*key)/i.test(
- normalized
- )
- ) {
+ } catch (e: any) {
return {
valid: false,
- error:
- "Qoder rejected this Personal Access Token (not authorized). " +
- "Check your token at https://qoder.com/account/integrations.",
+ error: `Qoder validation request failed: ${e.message}`,
unsupported: false,
};
}
-
- // A successful `--list-models` prints the catalog (a table headed by "MODEL").
- if (run.ok && normalized.includes("model")) {
- return { valid: true, error: null, unsupported: false };
- }
-
- return {
- valid: false,
- error: `qodercli validation failed: ${(combined || run.error || "unknown error").slice(0, 300)}`,
- unsupported: false,
- };
}
diff --git a/open-sse/services/retryAfterJson.ts b/open-sse/services/retryAfterJson.ts
deleted file mode 100644
index 1426fc3447..0000000000
--- a/open-sse/services/retryAfterJson.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-type JsonRecord = Record<string, unknown>;
-
-function objectRecord(value: unknown): JsonRecord {
- return value && typeof value === "object" && !Array.isArray(value) ? (value as JsonRecord) : {};
-}
-
-function positiveCappedMs(value: unknown, maxMs: number): number | null {
- return typeof value === "number" && Number.isFinite(value) && value > 0
- ? Math.min(value, maxMs)
- : null;
-}
-
-function futureTimestampMs(value: unknown, maxMs: number): number | null {
- if (typeof value !== "string") return null;
- const parsedTs = Date.parse(value);
- if (!Number.isFinite(parsedTs)) return null;
- const waitMs = parsedTs - Date.now();
- return waitMs > 0 ? Math.min(waitMs, maxMs) : null;
-}
-
-/**
- * Parse Retry-After hints from a 429 JSON response body. Providers use both
- * top-level and nested `error` fields for ISO timestamps and millisecond values.
- */
-export function parseRetryHintFromJsonBody(body: string, maxMs: number): number | null {
- let parsed: unknown;
- try {
- parsed = JSON.parse(body);
- } catch {
- return null;
- }
-
- const root = objectRecord(parsed);
- if (!Object.keys(root).length) return null;
- const errorObj = objectRecord(root.error);
-
- const isoHint = futureTimestampMs(errorObj.retryAfter ?? root.retryAfter, maxMs);
- if (isoHint !== null) return isoHint;
-
- return positiveCappedMs(
- errorObj.retry_after_ms ?? root.retry_after_ms ?? errorObj.retryAfterMs ?? root.retryAfterMs,
- maxMs
- );
-}
diff --git a/open-sse/services/usage.ts b/open-sse/services/usage.ts
index 39f8296082..a65d21daf8 100644
--- a/open-sse/services/usage.ts
+++ b/open-sse/services/usage.ts
@@ -14,7 +14,6 @@ import {
extractCodeAssistSubscriptionTier,
} from "./codeAssistSubscription.ts";
import { sanitizeErrorMessage } from "../utils/error.ts";
-import { resolveQoderJobToken } from "./qoderCli.ts";
import {
toRecord,
toNumber,
@@ -312,43 +311,6 @@ async function getXiaomiMimoUsage(connectionId: string) {
}
}
-/**
- * xAI (Grok) — SELF-TRACKED cumulative usage.
- *
- * xAI has no public per-account quota API (the billing console at console.x.ai
- * requires a session cookie, not an API key), so — exactly like the Xiaomi
- * MiMo self-track pattern above — OmniRoute sums the tokens it itself routed
- * to this connection (from `usage_history`) instead of calling an upstream
- * endpoint. Unlike Xiaomi MiMo, xAI has no fixed monthly cap, so the
- * aggregate is reported as `unlimited: true` with `remaining: 100` — this
- * renders the dashboard's green "100%" badge instead of a meaningless
- * progress bar against a `total: 0`.
- */
-async function getXaiUsage(connectionId: string) {
- if (!connectionId) {
- return { message: "xAI: connection id unavailable for self-tracked usage." };
- }
- try {
- const { getMonthlyProviderTokensForConnection } = await import("@/lib/usage/usageStats");
- const used = getMonthlyProviderTokensForConnection("xai", connectionId);
- return {
- plan: "xAI / Grok (OmniRoute-tracked)",
- quotas: {
- monthly: {
- used,
- total: 0,
- remaining: 100,
- remainingPercentage: 100,
- resetAt: null,
- unlimited: true,
- } as UsageQuota,
- },
- };
- } catch (error) {
- return { message: `xAI self-tracked usage error: ${(error as Error).message}` };
- }
-}
-
/**
* OpenCode Go / OpenCode / OpenCode Zen Usage
* Delegates to the dedicated opencodeQuotaFetcher and shapes the result into
@@ -534,7 +496,6 @@ export const USAGE_FETCHER_PROVIDERS = [
"opencode",
"opencode-zen",
"xiaomi-mimo",
- "xai",
"vertex",
"vertex-partner",
"codebuddy-cn",
@@ -585,9 +546,7 @@ export async function getUsageForProvider(
case "qwen":
return await getQwenUsage(accessToken, providerSpecificData);
case "qoder":
- // Qoder PATs live in `apiKey` (decrypted) or `providerSpecificData.qoderPat`,
- // never in `accessToken`.
- return await getQoderUsage(apiKey, providerSpecificData);
+ return await getQoderUsage(accessToken);
case "glm":
case "glm-cn":
case "zai":
@@ -616,8 +575,6 @@ export async function getUsageForProvider(
return await getOpencodeUsage(id || "", apiKey || "");
case "xiaomi-mimo":
return await getXiaomiMimoUsage(id || "");
- case "xai":
- return await getXaiUsage(id || "");
case "codebuddy-cn":
return await getCodeBuddyCnUsage(accessToken, apiKey, providerSpecificData);
default:
@@ -901,132 +858,19 @@ async function getQwenUsage(accessToken?: string, providerSpecificData?: JsonRec
/**
* Qoder Usage
- *
- * Qoder exposes account plan + quota at `openapi.qoder.sh/api/v3/user/status`,
- * the same endpoint the official qodercli reads for its usage badge. The status
- * call needs a short-lived `jt-*` job token, so we exchange the PAT the same way
- * the chat/validation paths do (see qoderCli.ts::resolveQoderJobToken).
- */
-const QODER_USER_STATUS_URL = "https://openapi.qoder.sh/api/v3/user/status";
-
-/** Human-readable plan label from Qoder's `PLAN_TIER_*` enum / `userTag`. */
-function prettifyQoderPlan(planRaw: string, userTag: string): string {
- const tag = String(userTag || "").trim();
- if (tag) return tag;
- const stripped = String(planRaw || "")
- .trim()
- .replace(/^PLAN_TIER_/i, "");
- return stripped ? toTitleCase(stripped) : "Qoder";
-}
-
-/**
- * Map a Qoder `/user/status` payload into the shared `{ plan, quotas }` shape.
- * Pure (no I/O) so it can be unit-tested against captured payloads.
*/
-export function parseQoderUserStatusUsage(status: JsonRecord): {
- plan: string;
- quotas: Record<string, UsageQuota>;
-} {
- const userType = String(status.userType || "")
- .trim()
- .toLowerCase();
- const planLabel = prettifyQoderPlan(String(status.plan || ""), String(status.userTag || ""));
- const isExceeded = status.isQuotaExceeded === true;
- const quotaNum = toNumber(status.quota, 0);
- const resetAt = parseResetTime(status.nextResetAt);
- // Team/enterprise seats draw from a pooled org quota rather than a per-user
- // counter, so `quota: 0` there means "pooled", not "exhausted".
- const isPooled = userType === "teams" || userType === "enterprise";
-
- const quotas: Record<string, UsageQuota> = {};
- if (isExceeded) {
- // Genuinely out of quota — remainingPercentage 0 lets routing skip it until reset.
- quotas["Quota"] = {
- used: quotaNum,
- total: quotaNum,
- remaining: 0,
- remainingPercentage: 0,
- resetAt,
- unlimited: false,
- displayName: "Quota exceeded",
- };
- } else if (isPooled || quotaNum <= 0) {
- // Pooled/unlimited seat — MUST report 100% remaining. The quota→routing
- // conversion (src/domain/quotaCache.ts) ignores `unlimited` and would treat a
- // `total: 0` window as 0% (i.e. exhausted), wrongly 429-ing every request.
- quotas["Plan"] = {
- used: 0,
- total: 0,
- remaining: 0,
- remainingPercentage: 100,
- resetAt,
- unlimited: true,
- displayName: `${planLabel} plan · pooled quota`,
- };
- } else {
- quotas["Requests"] = {
- used: 0,
- total: quotaNum,
- remaining: quotaNum,
- remainingPercentage: 100,
- resetAt,
- unlimited: false,
- displayName: `${quotaNum} requests left`,
- };
- }
-
- return { plan: planLabel, quotas };
-}
-
-async function getQoderUsage(apiKey?: string, providerSpecificData?: JsonRecord) {
- const token = (apiKey || "").trim() || String(providerSpecificData?.qoderPat || "").trim();
- if (!token) {
- return { message: "Qoder connected. Add a Personal Access Token to view quota." };
- }
-
- let jobToken: string;
- try {
- jobToken = await resolveQoderJobToken(token);
- } catch {
- return { message: "Qoder connected. Unable to resolve a usage token." };
- }
-
- let response: Response;
+async function getQoderUsage(accessToken?: string) {
+ void accessToken;
try {
- response = await fetch(QODER_USER_STATUS_URL, {
- method: "GET",
- headers: { Authorization: `Bearer ${jobToken}`, Accept: "application/json" },
- // @ts-ignore — AbortSignal.timeout is available on the Node runtime
- signal: AbortSignal.timeout(15000),
- });
+ // Qoder may have usage endpoint
+ return { message: "Qoder connected. Usage tracked per request." };
} catch (error) {
- return {
- message: `Qoder connected. Unable to fetch usage: ${sanitizeErrorMessage((error as Error).message)}`,
- };
- }
-
- if (response.status === 401 || response.status === 403) {
- return {
- message: "Qoder connected. The token was rejected by the usage API — re-test the connection.",
- };
+ return { message: "Unable to fetch Qoder usage." };
}
- if (!response.ok) {
- return { message: `Qoder connected. Usage API returned HTTP ${response.status}.` };
- }
-
- let status: JsonRecord;
- try {
- status = toRecord(await response.json());
- } catch {
- return { message: "Qoder connected. Unable to parse the usage response." };
- }
-
- return parseQoderUserStatusUsage(status);
}
export const __testing = {
parseResetTime,
- parseQoderUserStatusUsage,
formatGitHubQuotaSnapshot,
inferGitHubPlanName,
getAntigravityPlanLabel,
@@ -1046,7 +890,6 @@ export const __testing = {
getMiniMaxRemainingPercent,
getMiniMaxUsage,
getXiaomiMimoUsage,
- getXaiUsage,
getVertexUsage,
getMiniMaxAuthErrorMessage,
getMiniMaxErrorSummary,
diff --git a/open-sse/services/usage/codex.ts b/open-sse/services/usage/codex.ts
index 564cbdad9d..b1d0261f03 100644
--- a/open-sse/services/usage/codex.ts
+++ b/open-sse/services/usage/codex.ts
@@ -57,17 +57,12 @@ export async function getCodexUsage(
const data = await response.json();
- const { rateLimit, quotas, bankedResetCredits, rateLimitReachedType } =
- buildCodexUsageQuotas(data);
+ const { rateLimit, quotas } = buildCodexUsageQuotas(data);
return {
plan: String(getFieldValue(data, "plan_type", "planType") || "unknown"),
limitReached: Boolean(getFieldValue(rateLimit, "limit_reached", "limitReached")),
quotas,
- // Banked reset credits (display-only, eligibility-gated — issue #5199).
- // Absent for most accounts; never throws when the upstream omits it.
- ...(bankedResetCredits !== undefined ? { bankedResetCredits } : {}),
- ...(rateLimitReachedType !== undefined ? { rateLimitReachedType } : {}),
};
} catch (error) {
return { message: `Failed to fetch Codex usage: ${(error as Error).message}` };
diff --git a/open-sse/translator/helpers/geminiHelper.ts b/open-sse/translator/helpers/geminiHelper.ts
index 5fd500b2da..515765a2f2 100644
--- a/open-sse/translator/helpers/geminiHelper.ts
+++ b/open-sse/translator/helpers/geminiHelper.ts
@@ -12,10 +12,6 @@ export const GEMINI_UNSUPPORTED_SCHEMA_KEYS = new Set([
"maxLength",
"exclusiveMinimum",
"exclusiveMaximum",
- // `multipleOf` is not part of the Gemini/antigravity OpenAPI 3.0 schema subset;
- // leaving it in function_declarations triggers a hard upstream 400
- // ("Unknown name \"multipleOf\""). `minimum`/`maximum` ARE accepted and kept.
- "multipleOf",
// NOTE: `pattern` is intentionally NOT in this set. Antigravity (Gemini-derived
// surface) accepts `pattern` on string constraints, and glob/grep/file-search
// tools depend on it to express their argument regex. Removing it produced
diff --git a/open-sse/translator/request/antigravity-to-openai.ts b/open-sse/translator/request/antigravity-to-openai.ts
index 032d509127..24d25d4b11 100644
--- a/open-sse/translator/request/antigravity-to-openai.ts
+++ b/open-sse/translator/request/antigravity-to-openai.ts
@@ -1,7 +1,6 @@
import { register } from "../registry.ts";
import { FORMATS } from "../formats.ts";
import { adjustMaxTokens } from "../helpers/maxTokensHelper.ts";
-import { fixToolPairs } from "../../services/contextManager.ts";
type JsonRecord = Record<string, unknown>;
@@ -97,19 +96,6 @@ export function antigravityToOpenAIRequest(model, body, stream) {
}
}
- // Guard against orphan tool_result/tool_use pairs (#6026). Antigravity IDE can ship a
- // truncated history whose first turn is a `functionResponse` with no preceding
- // `functionCall`. Left untouched, that becomes an orphan `role:"tool"` message here and,
- // after the openai→claude step, an orphan `tool_result` block — which Anthropic (Vertex
- // `claude-opus-4.6`) rejects with `unexpected tool_use_id found in tool_result blocks`.
- // `fixToolPairs` strips only genuine orphans and is idempotent on well-formed histories,
- // so paired functionCall/functionResponse turns pass through unchanged. This mirrors the
- // executor-side guard in `executors/base.ts` / `services/claudeCodeCompatible.ts`; the
- // Antigravity MITM path did not run it (no `fixToolPairs` under `src/mitm/`). We do NOT
- // run `fixToolAdjacency` here because this stage still emits OpenAI-format messages and
- // Claude's adjacency rule is enforced downstream per provider.
- result.messages = fixToolPairs(result.messages) as JsonRecord[];
-
return result;
}
@@ -243,17 +229,14 @@ function convertContent(content) {
continue;
}
- // Text with thoughtSignature = regular text after thinking.
- // Skip empty text — Anthropic rejects empty content blocks with a 400.
+ // Text with thoughtSignature = regular text after thinking
if (part.thoughtSignature && part.text !== undefined) {
- if (part.text) {
- textParts.push({ type: "text", text: part.text });
- }
+ textParts.push({ type: "text", text: part.text });
continue;
}
- // Regular text — skip empty strings (Anthropic rejects empty content blocks).
- if (part.text !== undefined && part.text !== "") {
+ // Regular text
+ if (part.text !== undefined) {
textParts.push({ type: "text", text: part.text });
}
@@ -291,26 +274,8 @@ function convertContent(content) {
}
}
- // Function responses may be co-located with function calls / text / reasoning in
- // the same content. Emit the tool messages AND the accompanying assistant message so
- // nothing is dropped (previously only the tool messages survived).
+ // Content with only functionResponses → return array of tool messages
if (toolResults.length > 0) {
- if (toolCalls.length > 0 || textParts.length > 0 || reasoningContent) {
- const assistantMsg: JsonRecord = { role: "assistant" };
- if (textParts.length > 0) {
- assistantMsg.content =
- textParts.length === 1 && textParts[0].type === "text"
- ? textParts[0].text
- : textParts;
- }
- if (reasoningContent) {
- assistantMsg.reasoning_content = reasoningContent;
- }
- if (toolCalls.length > 0) {
- assistantMsg.tool_calls = toolCalls;
- }
- return [...toolResults, assistantMsg];
- }
return toolResults;
}
diff --git a/open-sse/translator/request/openai-responses.ts b/open-sse/translator/request/openai-responses.ts
index 23f32f53d4..a79259bd67 100644
--- a/open-sse/translator/request/openai-responses.ts
+++ b/open-sse/translator/request/openai-responses.ts
@@ -6,28 +6,73 @@
*/
import { isOpenAIResponsesStoreEnabled } from "@/lib/providers/requestDefaults";
import { FORMATS } from "../formats.ts";
+import { generateToolCallId } from "../helpers/toolCallHelper.ts";
import { register } from "../registry.ts";
import { normalizeResponsesInputForChat } from "../../utils/responsesInputNormalization.ts";
-import { openaiToOpenAIResponsesRequest } from "./openai-responses/toResponses.ts";
-import {
- JsonRecord,
- RESPONSES_STORE_MARKER,
- COPILOT_REASONING_SUMMARY_MARKER,
- WEB_SEARCH_TOOL_TYPES,
- TOOL_SEARCH_TOOL_TYPES,
- IMAGE_GENERATION_TOOL_TYPES,
- toRecord,
- toArray,
- toString,
- normalizeVerbosity,
- normalizeResponsesReasoningEffort,
- shouldRequestClaudeSummarizedThinking,
- unsupportedFeature,
-} from "./openai-responses/helpers.ts";
-
-// chat -> Responses direction extracted to a pure leaf; re-exported for external
-// importers (tests). Host imports it back for registration below.
-export { openaiToOpenAIResponsesRequest } from "./openai-responses/toResponses.ts";
+type JsonRecord = Record<string, unknown>;
+const RESPONSES_STORE_MARKER = "_omnirouteResponsesStore";
+const COPILOT_REASONING_SUMMARY_MARKER = "_omnirouteCopilotReasoningSummary";
+
+// Forward-compatible regex: matches web_search, web_search_20250305, and future versioned names.
+const WEB_SEARCH_TOOL_TYPES = /^web_search/;
+// tool_search is a Responses API built-in sent by newer Codex clients; it has no Chat Completions
+// equivalent and must be silently dropped (not rejected with 400).
+const TOOL_SEARCH_TOOL_TYPES = /^tool_search/;
+// image_generation is a Responses API hosted tool that Codex Desktop injects into every request
+// (even text-only ones); it has no Chat Completions equivalent and must be silently dropped (#2950).
+const IMAGE_GENERATION_TOOL_TYPES = /^image_generation/;
+
+// GPT-5 output verbosity: `verbosity` on Chat Completions, `text.verbosity` on the
+// Responses API. Only these three levels are valid upstream; anything else is dropped.
+const VERBOSITY_LEVELS = new Set(["low", "medium", "high"]);
+function normalizeVerbosity(value: unknown): string | undefined {
+ if (typeof value !== "string") return undefined;
+ const level = value.toLowerCase();
+ return VERBOSITY_LEVELS.has(level) ? level : undefined;
+}
+
+function toRecord(value: unknown): JsonRecord {
+ return value && typeof value === "object" && !Array.isArray(value) ? (value as JsonRecord) : {};
+}
+
+// The Responses API rejects call_id values longer than 64 characters (9router#396).
+// Clamp deterministically so a function_call and its matching function_call_output keep
+// the same id and stay paired through the orphaned-output filter below.
+const MAX_CALL_ID_LEN = 64;
+function clampCallId(id: string): string {
+ return id.length > MAX_CALL_ID_LEN ? id.slice(0, MAX_CALL_ID_LEN) : id;
+}
+
+function toArray(value: unknown): unknown[] {
+ return Array.isArray(value) ? value : [];
+}
+
+function toString(value: unknown, fallback = ""): string {
+ return typeof value === "string" ? value : fallback;
+}
+
+function imageUrlToText(value: unknown): string {
+ if (typeof value === "string") return value;
+ const record = toRecord(value);
+ return toString(record.url);
+}
+
+function normalizeResponsesReasoningEffort(value: unknown): string {
+ const effort = toString(value).toLowerCase();
+ return effort === "max" ? "xhigh" : effort;
+}
+
+function shouldRequestClaudeSummarizedThinking(value: unknown): boolean {
+ const summary = toString(value).toLowerCase();
+ return !!summary && summary !== "off" && summary !== "none" && summary !== "disabled";
+}
+
+function unsupportedFeature(message: string): Error & { statusCode: number; errorType: string } {
+ const error = new Error(message) as Error & { statusCode: number; errorType: string };
+ error.statusCode = 400;
+ error.errorType = "unsupported_feature";
+ return error;
+}
/**
* Convert OpenAI Responses API request to OpenAI Chat Completions format
@@ -524,6 +569,326 @@ export function openaiResponsesToOpenAIRequest(
return result;
}
+/**
+ * Convert OpenAI Chat Completions to OpenAI Responses API format
+ */
+export function openaiToOpenAIResponsesRequest(
+ model: unknown,
+ body: unknown,
+ stream: unknown,
+ credentials: unknown
+): unknown {
+ void stream;
+
+ const root = toRecord(body);
+ const credentialRecord = toRecord(credentials);
+ const storeEnabled = isOpenAIResponsesStoreEnabled(credentialRecord.providerSpecificData);
+ const result: JsonRecord = {
+ model,
+ input: [],
+ stream: true,
+ };
+ if (!storeEnabled) {
+ result.store = false;
+ }
+
+ const input = result.input as JsonRecord[];
+
+ // Extract first system message as instructions
+ let hasSystemMessage = false;
+ const messages = toArray(root.messages);
+
+ for (const messageValue of messages) {
+ const msg = toRecord(messageValue);
+ const role = toString(msg.role);
+
+ if (role === "system" || role === "developer") {
+ if (!hasSystemMessage) {
+ result.instructions = typeof msg.content === "string" ? msg.content : "";
+ hasSystemMessage = true;
+ }
+ continue;
+ }
+
+ // Convert user messages
+ if (role === "user") {
+ const content =
+ typeof msg.content === "string"
+ ? [{ type: "input_text", text: msg.content }]
+ : Array.isArray(msg.content)
+ ? msg.content.map((contentValue) => {
+ const contentItem = toRecord(contentValue);
+ if (contentItem.type === "text") {
+ return { type: "input_text", text: toString(contentItem.text) };
+ }
+ if (contentItem.type === "image_url") {
+ const imgUrl = contentItem.image_url as
+ | string
+ | { url?: string; detail?: string };
+ const imgResult: JsonRecord = {
+ type: "input_image",
+ image_url: typeof imgUrl === "string" ? imgUrl : imgUrl?.url || "",
+ };
+ if (typeof imgUrl === "object" && imgUrl?.detail !== undefined) {
+ imgResult.detail = imgUrl.detail;
+ }
+ return imgResult;
+ }
+ if (
+ contentItem.type === "image" &&
+ typeof contentItem.image === "string" &&
+ /^data:([^;]+);base64,(.+)$/.test(contentItem.image)
+ ) {
+ // AI SDK-style image part: { type: "image", image: "data:...;base64,..." } (#1330)
+ const imgResult: JsonRecord = {
+ type: "input_image",
+ image_url: contentItem.image,
+ detail: contentItem.detail !== undefined ? contentItem.detail : "auto",
+ };
+ return imgResult;
+ }
+ if (contentItem.type === "file" || contentItem.type === "document") {
+ // Accept both the OpenAI `file` shape and the Gemini-style `document` shape,
+ // and map the bare `data`/`url` fields too, so a PDF reaches Codex/Responses
+ // regardless of which content-part name the client used (#2515).
+ const file = toRecord(
+ contentItem.type === "document" ? contentItem.document : contentItem.file
+ );
+ const fileResult: JsonRecord = { type: "input_file" };
+ if (file.file_data !== undefined) fileResult.file_data = file.file_data;
+ else if (file.data !== undefined) fileResult.file_data = file.data;
+ if (file.file_id !== undefined) fileResult.file_id = file.file_id;
+ if (file.file_url !== undefined) fileResult.file_url = file.file_url;
+ else if (file.url !== undefined) fileResult.file_url = file.url;
+ if (file.filename !== undefined) fileResult.filename = file.filename;
+ else if (file.name !== undefined) fileResult.filename = file.name;
+ return fileResult;
+ }
+ return contentValue;
+ })
+ : [{ type: "input_text", text: "" }];
+
+ input.push({
+ type: "message",
+ role: "user",
+ content,
+ });
+ }
+
+ // Convert assistant messages
+ if (role === "assistant") {
+ // Skip reasoning_content — OpenAI Responses API requires server-generated
+ // rs_* IDs for reasoning items. Synthesizing client-side IDs (e.g. reasoning_N)
+ // causes 400 errors from Responses-compatible upstreams. (#224)
+
+ // Skip thinking blocks in array content — same rs_* ID constraint applies
+
+ // Build assistant output content
+ const outputContent: unknown[] = [];
+ if (typeof msg.content === "string" && msg.content) {
+ outputContent.push({ type: "output_text", text: msg.content });
+ } else if (Array.isArray(msg.content)) {
+ for (const contentValue of msg.content) {
+ const contentItem = toRecord(contentValue);
+ if (contentItem.type === "text") {
+ outputContent.push({ type: "output_text", text: toString(contentItem.text) });
+ } else if (contentItem.type === "image_url") {
+ const url = imageUrlToText(contentItem.image_url);
+ outputContent.push({ type: "output_text", text: url ? `[Image: ${url}]` : "[Image]" });
+ } else if (contentItem.type === "thinking" || contentItem.type === "redacted_thinking") {
+ // Reasoning already moved above
+ continue;
+ } else {
+ outputContent.push(contentValue);
+ }
+ }
+ }
+
+ // Only add assistant message if content exists
+ if (outputContent.length > 0) {
+ input.push({
+ type: "message",
+ role: "assistant",
+ content: outputContent,
+ });
+ }
+
+ // Convert tool_calls to function_call items
+ if (Array.isArray(msg.tool_calls)) {
+ for (const toolCallValue of msg.tool_calls) {
+ const toolCall = toRecord(toolCallValue);
+ const fn = toRecord(toolCall.function);
+ // Skip tool calls with empty names to avoid infinite placeholder_tool loops
+ const fnName = toString(fn.name).trim();
+ if (!fnName) {
+ continue;
+ }
+ input.push({
+ type: "function_call",
+ call_id: clampCallId(toString(toolCall.id).trim() || generateToolCallId()),
+ name: fnName,
+ arguments: toString(fn.arguments, "{}"),
+ });
+ }
+ }
+
+ // Handle deprecated function_call field (pre-tool_calls API)
+ if (msg.function_call && !msg.tool_calls) {
+ const fc = toRecord(msg.function_call);
+ const fnName = toString(fc.name).trim();
+ if (fnName) {
+ input.push({
+ type: "function_call",
+ call_id: clampCallId(`call_${fnName}`),
+ name: fnName,
+ arguments: toString(fc.arguments, "{}"),
+ });
+ }
+ }
+ }
+
+ // Convert tool results
+ if (role === "tool") {
+ input.push({
+ type: "function_call_output",
+ call_id: clampCallId(toString(msg.tool_call_id)),
+ output:
+ typeof msg.content === "string"
+ ? msg.content
+ : Array.isArray(msg.content)
+ ? msg.content.map((c) => {
+ const part = toRecord(c);
+ if (part.type === "text")
+ return { type: "input_text", text: toString(part.text) };
+ return c;
+ })
+ : String(msg.content ?? ""),
+ });
+ }
+
+ // Handle deprecated function role messages
+ if (role === "function") {
+ input.push({
+ type: "function_call_output",
+ call_id: clampCallId(`call_${toString(msg.name)}`),
+ output: typeof msg.content === "string" ? msg.content : String(msg.content ?? ""),
+ });
+ }
+ }
+
+ // Filter orphaned function_call_output items (no matching function_call)
+ // This happens when Claude Code compaction removes messages but leaves tool results
+ const knownCallIds = new Set(
+ input
+ .filter(
+ (item: { type?: string; call_id?: string }) => item.type === "function_call" && item.call_id
+ )
+ .map((item: { type?: string; call_id?: string }) => item.call_id)
+ );
+ result.input = input.filter((item: { type?: string; call_id?: string }) => {
+ if (item.type === "function_call_output" && item.call_id) {
+ return knownCallIds.has(item.call_id);
+ }
+ return true;
+ });
+
+ // If no system message, keep empty instructions
+ if (!hasSystemMessage) {
+ result.instructions = "";
+ }
+
+ // Convert tools format
+ if (Array.isArray(root.tools)) {
+ result.tools = root.tools.map((toolValue) => {
+ const tool = toRecord(toolValue);
+ if (tool.type === "function") {
+ const fn = toRecord(tool.function);
+ const name = toString(fn.name);
+ return {
+ type: "function",
+ name,
+ description: toString(fn.description),
+ parameters: fn.parameters,
+ strict: fn.strict,
+ };
+ }
+ return toolValue;
+ });
+ }
+
+ // Translate tool_choice: Chat {type,function:{name}} → Responses {type,name}
+ if (root.tool_choice !== undefined) {
+ if (typeof root.tool_choice === "string") {
+ result.tool_choice = root.tool_choice;
+ } else if (typeof root.tool_choice === "object" && !Array.isArray(root.tool_choice)) {
+ const tc = toRecord(root.tool_choice);
+ if (tc.type === "function" && tc.function) {
+ const fn = toRecord(tc.function);
+ result.tool_choice = { type: "function", name: fn.name };
+ } else {
+ result.tool_choice = root.tool_choice;
+ }
+ } else {
+ result.tool_choice = root.tool_choice;
+ }
+ }
+
+ // Pass through relevant fields
+ if (root.previous_response_id !== undefined) {
+ result.previous_response_id = root.previous_response_id;
+ }
+ if (root.prompt_cache_key !== undefined) {
+ result.prompt_cache_key = root.prompt_cache_key;
+ }
+ if (root.session_id !== undefined) {
+ result.session_id = root.session_id;
+ }
+ if (root.conversation_id !== undefined) {
+ result.conversation_id = root.conversation_id;
+ }
+ if (root.service_tier !== undefined) result.service_tier = root.service_tier;
+ if (root.temperature !== undefined) result.temperature = root.temperature;
+ // Translate max_tokens / max_completion_tokens → max_output_tokens for Responses API.
+ // The Responses API does not accept max_tokens or max_completion_tokens; it requires
+ // max_output_tokens. max_completion_tokens takes priority as the newer Chat Completions field.
+ if (root.max_completion_tokens !== undefined) {
+ result.max_output_tokens = root.max_completion_tokens;
+ } else if (root.max_tokens !== undefined) {
+ result.max_output_tokens = root.max_tokens;
+ }
+ if (root.top_p !== undefined) result.top_p = root.top_p;
+ // GPT-5 verbosity: Chat Completions `verbosity` → Responses `text.verbosity`.
+ const chatVerbosity = normalizeVerbosity(root.verbosity);
+ if (chatVerbosity) {
+ result.text = { ...toRecord(result.text), verbosity: chatVerbosity };
+ }
+ if (root.reasoning !== undefined) {
+ result.reasoning = root.reasoning;
+ } else if (root.reasoning_effort !== undefined) {
+ const effort = normalizeResponsesReasoningEffort(root.reasoning_effort);
+ if (effort) {
+ result.reasoning = { effort };
+ }
+ }
+
+ // Propagate Responses-API-only fields when a chat client sent them.
+ // Without this, e.g. `include: ["reasoning.encrypted_content"]` is lost on
+ // the way upstream and Codex returns an empty reasoning summary, so clients
+ // (OpenCode, Cursor, etc.) see no thinking stream.
+ if (Array.isArray(root.include) && root.include.length > 0) {
+ result.include = root.include;
+ }
+ if (storeEnabled) {
+ if (root[RESPONSES_STORE_MARKER] !== undefined) {
+ result.store = root[RESPONSES_STORE_MARKER];
+ } else if (root.store !== undefined) {
+ result.store = root.store;
+ }
+ }
+
+ return result;
+}
+
// Register both directions
register(FORMATS.OPENAI_RESPONSES, FORMATS.OPENAI, openaiResponsesToOpenAIRequest, null);
register(FORMATS.OPENAI, FORMATS.OPENAI_RESPONSES, openaiToOpenAIResponsesRequest, null);
diff --git a/open-sse/translator/request/openai-responses/helpers.ts b/open-sse/translator/request/openai-responses/helpers.ts
deleted file mode 100644
index f50f5132ce..0000000000
--- a/open-sse/translator/request/openai-responses/helpers.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-// Pure shared primitives for the OpenAI Responses <-> Chat Completions request
-// translators. Extracted verbatim from openai-responses.ts (no host imports).
-
-export type JsonRecord = Record<string, unknown>;
-export const RESPONSES_STORE_MARKER = "_omnirouteResponsesStore";
-export const COPILOT_REASONING_SUMMARY_MARKER = "_omnirouteCopilotReasoningSummary";
-
-// Forward-compatible regex: matches web_search, web_search_20250305, and future versioned names.
-export const WEB_SEARCH_TOOL_TYPES = /^web_search/;
-// tool_search is a Responses API built-in sent by newer Codex clients; it has no Chat Completions
-// equivalent and must be silently dropped (not rejected with 400).
-export const TOOL_SEARCH_TOOL_TYPES = /^tool_search/;
-// image_generation is a Responses API hosted tool that Codex Desktop injects into every request
-// (even text-only ones); it has no Chat Completions equivalent and must be silently dropped (#2950).
-export const IMAGE_GENERATION_TOOL_TYPES = /^image_generation/;
-
-// GPT-5 output verbosity: `verbosity` on Chat Completions, `text.verbosity` on the
-// Responses API. Only these three levels are valid upstream; anything else is dropped.
-export const VERBOSITY_LEVELS = new Set(["low", "medium", "high"]);
-export function normalizeVerbosity(value: unknown): string | undefined {
- if (typeof value !== "string") return undefined;
- const level = value.toLowerCase();
- return VERBOSITY_LEVELS.has(level) ? level : undefined;
-}
-
-export function toRecord(value: unknown): JsonRecord {
- return value && typeof value === "object" && !Array.isArray(value) ? (value as JsonRecord) : {};
-}
-
-// The Responses API rejects call_id values longer than 64 characters (9router#396).
-// Clamp deterministically so a function_call and its matching function_call_output keep
-// the same id and stay paired through the orphaned-output filter below.
-export const MAX_CALL_ID_LEN = 64;
-export function clampCallId(id: string): string {
- return id.length > MAX_CALL_ID_LEN ? id.slice(0, MAX_CALL_ID_LEN) : id;
-}
-
-export function toArray(value: unknown): unknown[] {
- return Array.isArray(value) ? value : [];
-}
-
-export function toString(value: unknown, fallback = ""): string {
- return typeof value === "string" ? value : fallback;
-}
-
-export function imageUrlToText(value: unknown): string {
- if (typeof value === "string") return value;
- const record = toRecord(value);
- return toString(record.url);
-}
-
-export function normalizeResponsesReasoningEffort(value: unknown): string {
- const effort = toString(value).toLowerCase();
- return effort === "max" ? "xhigh" : effort;
-}
-
-export function shouldRequestClaudeSummarizedThinking(value: unknown): boolean {
- const summary = toString(value).toLowerCase();
- return !!summary && summary !== "off" && summary !== "none" && summary !== "disabled";
-}
-
-export function unsupportedFeature(
- message: string
-): Error & { statusCode: number; errorType: string } {
- const error = new Error(message) as Error & { statusCode: number; errorType: string };
- error.statusCode = 400;
- error.errorType = "unsupported_feature";
- return error;
-}
diff --git a/open-sse/translator/request/openai-responses/toResponses.ts b/open-sse/translator/request/openai-responses/toResponses.ts
deleted file mode 100644
index d52608496f..0000000000
--- a/open-sse/translator/request/openai-responses/toResponses.ts
+++ /dev/null
@@ -1,357 +0,0 @@
-/**
- * Translator: OpenAI Chat Completions -> OpenAI Responses API
- *
- * Extracted verbatim from openai-responses.ts. Registration stays in the host.
- */
-import { isOpenAIResponsesStoreEnabled } from "@/lib/providers/requestDefaults";
-import { generateToolCallId } from "../../helpers/toolCallHelper.ts";
-import {
- JsonRecord,
- RESPONSES_STORE_MARKER,
- toRecord,
- toArray,
- toString,
- clampCallId,
- imageUrlToText,
- normalizeVerbosity,
- normalizeResponsesReasoningEffort,
-} from "./helpers.ts";
-
-// Chat Completions `response_format: { type: "json_schema" }` → Responses API `text.format`.
-// Merges into any existing `result.text` (e.g. verbosity) so structured-output schemas from
-// Chat clients survive the translation to the Responses/Codex upstream (#5933).
-function mapChatResponseFormatToResponsesText(body: JsonRecord, result: JsonRecord): void {
- const responseFormat = toRecord(body.response_format);
- if (responseFormat.type !== "json_schema") return;
-
- const jsonSchema = toRecord(responseFormat.json_schema);
- if (jsonSchema.schema === undefined) return;
-
- const existingText = toRecord(result.text);
- const format: JsonRecord = {
- type: "json_schema",
- name: toString(jsonSchema.name, "codex_output_schema"),
- schema: jsonSchema.schema,
- };
- if (jsonSchema.description !== undefined) format.description = jsonSchema.description;
- if (jsonSchema.strict !== undefined) format.strict = jsonSchema.strict;
-
- result.text = { ...existingText, format };
-}
-
-export function openaiToOpenAIResponsesRequest(
- model: unknown,
- body: unknown,
- stream: unknown,
- credentials: unknown
-): unknown {
- void stream;
-
- const root = toRecord(body);
- const credentialRecord = toRecord(credentials);
- const storeEnabled = isOpenAIResponsesStoreEnabled(credentialRecord.providerSpecificData);
- const result: JsonRecord = {
- model,
- input: [],
- stream: true,
- };
- if (!storeEnabled) {
- result.store = false;
- }
-
- const input = result.input as JsonRecord[];
-
- // Extract first system message as instructions
- let hasSystemMessage = false;
- const messages = toArray(root.messages);
-
- for (const messageValue of messages) {
- const msg = toRecord(messageValue);
- const role = toString(msg.role);
-
- if (role === "system" || role === "developer") {
- if (!hasSystemMessage) {
- result.instructions = typeof msg.content === "string" ? msg.content : "";
- hasSystemMessage = true;
- }
- continue;
- }
-
- // Convert user messages
- if (role === "user") {
- const content =
- typeof msg.content === "string"
- ? [{ type: "input_text", text: msg.content }]
- : Array.isArray(msg.content)
- ? msg.content.map((contentValue) => {
- const contentItem = toRecord(contentValue);
- if (contentItem.type === "text") {
- return { type: "input_text", text: toString(contentItem.text) };
- }
- if (contentItem.type === "image_url") {
- const imgUrl = contentItem.image_url as
- string | { url?: string; detail?: string };
- const imgResult: JsonRecord = {
- type: "input_image",
- image_url: typeof imgUrl === "string" ? imgUrl : imgUrl?.url || "",
- };
- if (typeof imgUrl === "object" && imgUrl?.detail !== undefined) {
- imgResult.detail = imgUrl.detail;
- }
- return imgResult;
- }
- if (
- contentItem.type === "image" &&
- typeof contentItem.image === "string" &&
- /^data:([^;]+);base64,(.+)$/.test(contentItem.image)
- ) {
- // AI SDK-style image part: { type: "image", image: "data:...;base64,..." } (#1330)
- const imgResult: JsonRecord = {
- type: "input_image",
- image_url: contentItem.image,
- detail: contentItem.detail !== undefined ? contentItem.detail : "auto",
- };
- return imgResult;
- }
- if (contentItem.type === "file" || contentItem.type === "document") {
- // Accept both the OpenAI `file` shape and the Gemini-style `document` shape,
- // and map the bare `data`/`url` fields too, so a PDF reaches Codex/Responses
- // regardless of which content-part name the client used (#2515).
- const file = toRecord(
- contentItem.type === "document" ? contentItem.document : contentItem.file
- );
- const fileResult: JsonRecord = { type: "input_file" };
- if (file.file_data !== undefined) fileResult.file_data = file.file_data;
- else if (file.data !== undefined) fileResult.file_data = file.data;
- if (file.file_id !== undefined) fileResult.file_id = file.file_id;
- if (file.file_url !== undefined) fileResult.file_url = file.file_url;
- else if (file.url !== undefined) fileResult.file_url = file.url;
- if (file.filename !== undefined) fileResult.filename = file.filename;
- else if (file.name !== undefined) fileResult.filename = file.name;
- return fileResult;
- }
- return contentValue;
- })
- : [{ type: "input_text", text: "" }];
-
- input.push({
- type: "message",
- role: "user",
- content,
- });
- }
-
- // Convert assistant messages
- if (role === "assistant") {
- // Skip reasoning_content — OpenAI Responses API requires server-generated
- // rs_* IDs for reasoning items. Synthesizing client-side IDs (e.g. reasoning_N)
- // causes 400 errors from Responses-compatible upstreams. (#224)
-
- // Skip thinking blocks in array content — same rs_* ID constraint applies
-
- // Build assistant output content
- const outputContent: unknown[] = [];
- if (typeof msg.content === "string" && msg.content) {
- outputContent.push({ type: "output_text", text: msg.content });
- } else if (Array.isArray(msg.content)) {
- for (const contentValue of msg.content) {
- const contentItem = toRecord(contentValue);
- if (contentItem.type === "text") {
- outputContent.push({ type: "output_text", text: toString(contentItem.text) });
- } else if (contentItem.type === "image_url") {
- const url = imageUrlToText(contentItem.image_url);
- outputContent.push({ type: "output_text", text: url ? `[Image: ${url}]` : "[Image]" });
- } else if (contentItem.type === "thinking" || contentItem.type === "redacted_thinking") {
- // Reasoning already moved above
- continue;
- } else {
- outputContent.push(contentValue);
- }
- }
- }
-
- // Only add assistant message if content exists
- if (outputContent.length > 0) {
- input.push({
- type: "message",
- role: "assistant",
- content: outputContent,
- });
- }
-
- // Convert tool_calls to function_call items
- if (Array.isArray(msg.tool_calls)) {
- for (const toolCallValue of msg.tool_calls) {
- const toolCall = toRecord(toolCallValue);
- const fn = toRecord(toolCall.function);
- // Skip tool calls with empty names to avoid infinite placeholder_tool loops
- const fnName = toString(fn.name).trim();
- if (!fnName) {
- continue;
- }
- input.push({
- type: "function_call",
- call_id: clampCallId(toString(toolCall.id).trim() || generateToolCallId()),
- name: fnName,
- arguments: toString(fn.arguments, "{}"),
- });
- }
- }
-
- // Handle deprecated function_call field (pre-tool_calls API)
- if (msg.function_call && !msg.tool_calls) {
- const fc = toRecord(msg.function_call);
- const fnName = toString(fc.name).trim();
- if (fnName) {
- input.push({
- type: "function_call",
- call_id: clampCallId(`call_${fnName}`),
- name: fnName,
- arguments: toString(fc.arguments, "{}"),
- });
- }
- }
- }
-
- // Convert tool results
- if (role === "tool") {
- input.push({
- type: "function_call_output",
- call_id: clampCallId(toString(msg.tool_call_id)),
- output:
- typeof msg.content === "string"
- ? msg.content
- : Array.isArray(msg.content)
- ? msg.content.map((c) => {
- const part = toRecord(c);
- if (part.type === "text")
- return { type: "input_text", text: toString(part.text) };
- return c;
- })
- : String(msg.content ?? ""),
- });
- }
-
- // Handle deprecated function role messages
- if (role === "function") {
- input.push({
- type: "function_call_output",
- call_id: clampCallId(`call_${toString(msg.name)}`),
- output: typeof msg.content === "string" ? msg.content : String(msg.content ?? ""),
- });
- }
- }
-
- // Filter orphaned function_call_output items (no matching function_call)
- // This happens when Claude Code compaction removes messages but leaves tool results
- const knownCallIds = new Set(
- input
- .filter(
- (item: { type?: string; call_id?: string }) => item.type === "function_call" && item.call_id
- )
- .map((item: { type?: string; call_id?: string }) => item.call_id)
- );
- result.input = input.filter((item: { type?: string; call_id?: string }) => {
- if (item.type === "function_call_output" && item.call_id) {
- return knownCallIds.has(item.call_id);
- }
- return true;
- });
-
- // If no system message, keep empty instructions
- if (!hasSystemMessage) {
- result.instructions = "";
- }
-
- // Convert tools format
- if (Array.isArray(root.tools)) {
- result.tools = root.tools.map((toolValue) => {
- const tool = toRecord(toolValue);
- if (tool.type === "function") {
- const fn = toRecord(tool.function);
- const name = toString(fn.name);
- return {
- type: "function",
- name,
- description: toString(fn.description),
- parameters: fn.parameters,
- strict: fn.strict,
- };
- }
- return toolValue;
- });
- }
-
- // Translate tool_choice: Chat {type,function:{name}} → Responses {type,name}
- if (root.tool_choice !== undefined) {
- if (typeof root.tool_choice === "string") {
- result.tool_choice = root.tool_choice;
- } else if (typeof root.tool_choice === "object" && !Array.isArray(root.tool_choice)) {
- const tc = toRecord(root.tool_choice);
- if (tc.type === "function" && tc.function) {
- const fn = toRecord(tc.function);
- result.tool_choice = { type: "function", name: fn.name };
- } else {
- result.tool_choice = root.tool_choice;
- }
- } else {
- result.tool_choice = root.tool_choice;
- }
- }
-
- // Pass through relevant fields
- if (root.previous_response_id !== undefined) {
- result.previous_response_id = root.previous_response_id;
- }
- if (root.prompt_cache_key !== undefined) {
- result.prompt_cache_key = root.prompt_cache_key;
- }
- if (root.session_id !== undefined) {
- result.session_id = root.session_id;
- }
- if (root.conversation_id !== undefined) {
- result.conversation_id = root.conversation_id;
- }
- if (root.service_tier !== undefined) result.service_tier = root.service_tier;
- if (root.temperature !== undefined) result.temperature = root.temperature;
- // Translate max_tokens / max_completion_tokens → max_output_tokens for Responses API.
- // The Responses API does not accept max_tokens or max_completion_tokens; it requires
- // max_output_tokens. max_completion_tokens takes priority as the newer Chat Completions field.
- if (root.max_completion_tokens !== undefined) {
- result.max_output_tokens = root.max_completion_tokens;
- } else if (root.max_tokens !== undefined) {
- result.max_output_tokens = root.max_tokens;
- }
- if (root.top_p !== undefined) result.top_p = root.top_p;
- mapChatResponseFormatToResponsesText(root, result);
- // GPT-5 verbosity: Chat Completions `verbosity` → Responses `text.verbosity`.
- const chatVerbosity = normalizeVerbosity(root.verbosity);
- if (chatVerbosity) {
- result.text = { ...toRecord(result.text), verbosity: chatVerbosity };
- }
- if (root.reasoning !== undefined) {
- result.reasoning = root.reasoning;
- } else if (root.reasoning_effort !== undefined) {
- const effort = normalizeResponsesReasoningEffort(root.reasoning_effort);
- if (effort) {
- result.reasoning = { effort };
- }
- }
-
- // Propagate Responses-API-only fields when a chat client sent them.
- // Without this, e.g. `include: ["reasoning.encrypted_content"]` is lost on
- // the way upstream and Codex returns an empty reasoning summary, so clients
- // (OpenCode, Cursor, etc.) see no thinking stream.
- if (Array.isArray(root.include) && root.include.length > 0) {
- result.include = root.include;
- }
- if (storeEnabled) {
- if (root[RESPONSES_STORE_MARKER] !== undefined) {
- result.store = root[RESPONSES_STORE_MARKER];
- } else if (root.store !== undefined) {
- result.store = root.store;
- }
- }
-
- return result;
-}
diff --git a/open-sse/translator/request/openai-to-claude.ts b/open-sse/translator/request/openai-to-claude.ts
index 078d48e94a..2180bef00e 100644
--- a/open-sse/translator/request/openai-to-claude.ts
+++ b/open-sse/translator/request/openai-to-claude.ts
@@ -6,8 +6,8 @@ import { adjustMaxTokens } from "../helpers/maxTokensHelper.ts";
import { sanitizeToolId } from "../helpers/schemaCoercion.ts";
import { safeParseJSON } from "../helpers/jsonUtil.ts";
import { DEFAULT_THINKING_CLAUDE_SIGNATURE } from "../../config/defaultThinkingSignature.ts";
+import { capMaxOutputTokens } from "../../../src/lib/modelCapabilities.ts";
import { isAdaptiveThinkingOnly } from "../../../src/shared/constants/modelSpecs.ts";
-import { fitThinkingToMaxTokens } from "./openai-to-claude/thinkingBudget.ts";
// Reasoning-effort levels Anthropic accepts on `output_config.effort`. Used to steer
// adaptive-only Claude models (Opus 4.7+/Fable 5) without ever emitting a manual budget.
@@ -36,9 +36,93 @@ function applyCopilotSummarizedThinkingDisplay(
};
}
-// Thinking-budget fitting extracted to a pure leaf; re-exported for external
-// importers (tests). Host also uses fitThinkingToMaxTokens internally.
-export { fitThinkingToMaxTokens } from "./openai-to-claude/thinkingBudget.ts";
+// Anthropic constraints for the thinking + max_tokens contract:
+// - thinking.budget_tokens must be >= 1024 when thinking is enabled
+// - max_tokens must be > thinking.budget_tokens (covers thinking + response)
+// - max_tokens must be <= model output cap (e.g. 128000 for Opus 4.7)
+const MIN_CLAUDE_THINKING_BUDGET = 1024;
+const MIN_RESPONSE_ROOM = 1024;
+
+function safeCapMaxOutputTokens(model: string): number | null {
+ try {
+ const cap = capMaxOutputTokens(model);
+ return typeof cap === "number" && cap > 0 ? cap : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Fit Claude thinking budget within the model's max output cap.
+ *
+ * Replaces the previous unconditional `max_tokens = budget + 8192` inflation,
+ * which could exceed the model output cap (e.g. Opus 4.7's 128000 ceiling) and
+ * trigger HTTP 400 from Anthropic ("max_tokens > 128000").
+ *
+ * Strategy (preserves caller intent up to the model cap):
+ * - Preserve caller's max_tokens as response room (floored to MIN_RESPONSE_ROOM)
+ * - Target max_tokens = responseRoom + requestedBudget, capped at modelCap
+ * - fittedBudget = max_tokens - responseRoom (the thinking budget actually used)
+ * - If the cap squeezes fittedBudget below the Anthropic minimum, retry with
+ * responseRoom shrunk to MIN_RESPONSE_ROOM; if still below MIN, disable
+ * thinking entirely (cap too tight for any reasoning).
+ *
+ * Worked example (real-world Opus 4.7 case that previously 400'd):
+ * caller max_tokens = 32000, reasoning_effort=high → budget = 131072,
+ * model cap = 128000.
+ * responseRoom = max(32000, 1024) = 32000
+ * target = min(32000 + 131072, 128000) = 128000
+ * fittedBudget = 128000 - 32000 = 96000 (>= 1024, OK)
+ * → max_tokens=128000, budget_tokens=96000 (vs. the old buggy 139264 / 131072).
+ */
+export function fitThinkingToMaxTokens(
+ model: string,
+ callerMaxTokens: number,
+ thinking: Record<string, unknown> | undefined
+): { maxTokens: number; thinking: Record<string, unknown> | undefined } {
+ const modelCap = safeCapMaxOutputTokens(model);
+ const requestedBudget = Number(thinking?.budget_tokens) || 0;
+
+ // No budgeted thinking — just cap max_tokens to the model output ceiling.
+ if (!thinking || requestedBudget <= 0) {
+ return {
+ maxTokens:
+ modelCap === null
+ ? Math.max(callerMaxTokens, 1)
+ : Math.min(Math.max(callerMaxTokens, 1), modelCap),
+ thinking,
+ };
+ }
+
+ let responseRoom = Math.max(callerMaxTokens, MIN_RESPONSE_ROOM);
+ let target =
+ modelCap === null
+ ? responseRoom + requestedBudget
+ : Math.min(responseRoom + requestedBudget, modelCap);
+ let fittedBudget = target - responseRoom;
+
+ // If the cap squeezed thinking below Anthropic's floor, try shrinking
+ // response room to MIN_RESPONSE_ROOM to recover budget.
+ if (fittedBudget < MIN_CLAUDE_THINKING_BUDGET && responseRoom > MIN_RESPONSE_ROOM) {
+ responseRoom = MIN_RESPONSE_ROOM;
+ target =
+ modelCap === null
+ ? responseRoom + requestedBudget
+ : Math.min(responseRoom + requestedBudget, modelCap);
+ fittedBudget = target - responseRoom;
+ }
+
+ // Cap too tight for any thinking — disable rather than send an invalid request.
+ if (fittedBudget < MIN_CLAUDE_THINKING_BUDGET) {
+ return { maxTokens: modelCap ?? Math.max(callerMaxTokens, 1), thinking: undefined };
+ }
+
+ const adjustedThinking: Record<string, unknown> = { ...thinking };
+ if (fittedBudget < requestedBudget) {
+ adjustedThinking.budget_tokens = fittedBudget;
+ }
+ return { maxTokens: target, thinking: adjustedThinking };
+}
type ClaudeContentBlock = Record<string, unknown>;
type ClaudeMessage = {
@@ -165,97 +249,6 @@ export function openaiToClaudeRequest(model, body, stream) {
result.stop_sequences = Array.isArray(body.stop) ? body.stop : [body.stop];
}
- // Thinking configuration
- // NOTE: computed BEFORE message-block conversion (below) so that
- // `getContentBlocksFromMessage` knows whether the outbound request actually has
- // extended thinking enabled — required to correctly gate the `redacted_thinking`
- // replay-placeholder injection (#5945). This block has no dependency on
- // `result.messages`/`toolNameMap`, so moving it earlier is safe.
- if (body.thinking) {
- result.thinking = {
- type: body.thinking.type || "enabled",
- ...(body.thinking.budget_tokens && { budget_tokens: body.thinking.budget_tokens }),
- ...(body.thinking.max_tokens && { max_tokens: body.thinking.max_tokens }),
- };
- } else if (body.reasoning_effort) {
- // Convert OpenAI reasoning_effort to Claude thinking format (#627)
- // Clients like OpenCode send reasoning_effort via @ai-sdk/openai-compatible
- const requestedEffort = String(body.reasoning_effort).toLowerCase();
- const normalizedEffort =
- requestedEffort === "max" && !supportsClaudeMaxEffort(model)
- ? "high"
- : requestedEffort === "xhigh" && !supportsXHighEffort("claude", model)
- ? "high"
- : requestedEffort;
- if (isAdaptiveThinkingOnly(model)) {
- // Opus 4.7+/Fable 5 removed manual extended thinking: a fixed `budget_tokens`
- // (or `type:"enabled"`) is a hard 400. Steer EVERY level via adaptive +
- // output_config.effort instead of the budget buckets below. Unrecognized levels
- // leave thinking unset so the model keeps its adaptive default rather than 400ing
- // on an invalid effort value.
- if (ADAPTIVE_EFFORT_LEVELS.has(normalizedEffort)) {
- result.thinking = {
- type: "adaptive",
- };
- result.output_config = {
- ...(result.output_config || {}),
- effort: normalizedEffort,
- };
- }
- } else if (normalizedEffort === "max" || normalizedEffort === "xhigh") {
- result.thinking = {
- type: "adaptive",
- };
- result.output_config = {
- ...(result.output_config || {}),
- effort: normalizedEffort,
- };
- } else {
- const effortBudgetMap: Record<string, number> = {
- low: 1024,
- medium: 10240,
- high: 131072,
- max: 131072,
- };
- const budget = effortBudgetMap[normalizedEffort];
- if (budget !== undefined && budget > 0) {
- result.thinking = {
- type: "enabled",
- budget_tokens: budget,
- };
- }
- }
- }
-
- // Fit thinking budget within the model's output cap and ensure
- // max_tokens > budget_tokens for all thinking configurations (#627).
- // Replaces the previous unconditional `budget + 8192` inflation, which
- // could exceed model caps (e.g. Opus 4.7's 128000 ceiling) and trigger
- // HTTP 400 from Anthropic.
- const fitted = fitThinkingToMaxTokens(model, Number(result.max_tokens) || 0, result.thinking);
- result.max_tokens = fitted.maxTokens;
- if (fitted.thinking === undefined) {
- delete result.thinking;
- } else {
- result.thinking = applyCopilotSummarizedThinkingDisplay(fitted.thinking, body);
- }
-
- delete result[COPILOT_REASONING_SUMMARY_MARKER];
-
- // Final guard: Claude rejects `temperature` whenever extended thinking is
- // enabled. If `result.thinking` was set above from `body.thinking` or
- // `body.reasoning_effort` (manual budget or adaptive effort), drop temperature
- // defensively. The model-name strip earlier already covers Claude OAuth's
- // forced-thinking case (claude-opus-4.x / claude-sonnet-4.x).
- if (result.thinking && result.temperature !== undefined) {
- delete result.temperature;
- }
-
- // Whether the OUTBOUND request actually has extended thinking enabled. Anthropic's
- // schema only requires a precursor thinking/redacted_thinking block before a tool_use
- // block when thinking mode is active for THIS request — never unconditionally (#5945).
- const thinkingEnabledForRequest = Boolean(result.thinking) && result.thinking.type !== "disabled";
-
// Messages
const systemParts = [];
@@ -290,12 +283,7 @@ export function openaiToClaudeRequest(model, body, stream) {
for (const msg of nonSystemMessages) {
const newRole = msg.role === "user" || msg.role === "tool" ? "user" : "assistant";
- const blocks = getContentBlocksFromMessage(
- msg,
- toolNameMap,
- disableToolPrefix,
- thinkingEnabledForRequest
- );
+ const blocks = getContentBlocksFromMessage(msg, toolNameMap, disableToolPrefix);
const hasToolUse = blocks.some((b) => b.type === "tool_use");
const hasToolResult = blocks.some((b) => b.type === "tool_result");
@@ -483,6 +471,87 @@ export function openaiToClaudeRequest(model, body, stream) {
: [{ type: "text", text: String(body.system) }];
}
+ // Thinking configuration
+ if (body.thinking) {
+ result.thinking = {
+ type: body.thinking.type || "enabled",
+ ...(body.thinking.budget_tokens && { budget_tokens: body.thinking.budget_tokens }),
+ ...(body.thinking.max_tokens && { max_tokens: body.thinking.max_tokens }),
+ };
+ } else if (body.reasoning_effort) {
+ // Convert OpenAI reasoning_effort to Claude thinking format (#627)
+ // Clients like OpenCode send reasoning_effort via @ai-sdk/openai-compatible
+ const requestedEffort = String(body.reasoning_effort).toLowerCase();
+ const normalizedEffort =
+ requestedEffort === "max" && !supportsClaudeMaxEffort(model)
+ ? "high"
+ : requestedEffort === "xhigh" && !supportsXHighEffort("claude", model)
+ ? "high"
+ : requestedEffort;
+ if (isAdaptiveThinkingOnly(model)) {
+ // Opus 4.7+/Fable 5 removed manual extended thinking: a fixed `budget_tokens`
+ // (or `type:"enabled"`) is a hard 400. Steer EVERY level via adaptive +
+ // output_config.effort instead of the budget buckets below. Unrecognized levels
+ // leave thinking unset so the model keeps its adaptive default rather than 400ing
+ // on an invalid effort value.
+ if (ADAPTIVE_EFFORT_LEVELS.has(normalizedEffort)) {
+ result.thinking = {
+ type: "adaptive",
+ };
+ result.output_config = {
+ ...(result.output_config || {}),
+ effort: normalizedEffort,
+ };
+ }
+ } else if (normalizedEffort === "max" || normalizedEffort === "xhigh") {
+ result.thinking = {
+ type: "adaptive",
+ };
+ result.output_config = {
+ ...(result.output_config || {}),
+ effort: normalizedEffort,
+ };
+ } else {
+ const effortBudgetMap: Record<string, number> = {
+ low: 1024,
+ medium: 10240,
+ high: 131072,
+ max: 131072,
+ };
+ const budget = effortBudgetMap[normalizedEffort];
+ if (budget !== undefined && budget > 0) {
+ result.thinking = {
+ type: "enabled",
+ budget_tokens: budget,
+ };
+ }
+ }
+ }
+
+ // Fit thinking budget within the model's output cap and ensure
+ // max_tokens > budget_tokens for all thinking configurations (#627).
+ // Replaces the previous unconditional `budget + 8192` inflation, which
+ // could exceed model caps (e.g. Opus 4.7's 128000 ceiling) and trigger
+ // HTTP 400 from Anthropic.
+ const fitted = fitThinkingToMaxTokens(model, Number(result.max_tokens) || 0, result.thinking);
+ result.max_tokens = fitted.maxTokens;
+ if (fitted.thinking === undefined) {
+ delete result.thinking;
+ } else {
+ result.thinking = applyCopilotSummarizedThinkingDisplay(fitted.thinking, body);
+ }
+
+ delete result[COPILOT_REASONING_SUMMARY_MARKER];
+
+ // Final guard: Claude rejects `temperature` whenever extended thinking is
+ // enabled. If `result.thinking` was set above from `body.thinking` or
+ // `body.reasoning_effort` (manual budget or adaptive effort), drop temperature
+ // defensively. The model-name strip earlier already covers Claude OAuth's
+ // forced-thinking case (claude-opus-4.x / claude-sonnet-4.x).
+ if (result.thinking && result.temperature !== undefined) {
+ delete result.temperature;
+ }
+
// Attach toolNameMap to result for response translation
if (toolNameMap.size > 0) {
result._toolNameMap = toolNameMap;
@@ -503,12 +572,7 @@ export function openaiToClaudeRequest(model, body, stream) {
}
// Get content blocks from single message
-function getContentBlocksFromMessage(
- msg,
- toolNameMap = new Map(),
- disableToolPrefix = false,
- thinkingEnabledForRequest = false
-) {
+function getContentBlocksFromMessage(msg, toolNameMap = new Map(), disableToolPrefix = false) {
const blocks = [];
if (msg.role === "tool") {
@@ -575,6 +639,22 @@ function getContentBlocksFromMessage(
}
}
} else if (msg.role === "assistant") {
+ // Add reasoning_content as a replay placeholder (OpenAI extended thinking format).
+ // #5312 RC-D: reasoning_content carries NO real Claude signature. Emitting a
+ // `thinking` block with the fabricated DEFAULT signature makes Anthropic reject the
+ // replay with 400 "Invalid signature in thinking block" — and claudeHelper's
+ // latest-assistant guard (prepareClaudeRequest) preserves it verbatim, so the fake
+ // signature leaks upstream. Emit a signature-less redacted_thinking block instead
+ // (the same shape prepareClaudeRequest produces for Anthropic-native replay);
+ // Anthropic accepts it without signature validation and non-Anthropic Claude-shape
+ // upstreams re-hydrate the real text downstream from reasoningCache.
+ if (msg.reasoning_content) {
+ blocks.push({
+ type: "redacted_thinking",
+ data: DEFAULT_THINKING_CLAUDE_SIGNATURE,
+ });
+ }
+
if (Array.isArray(msg.content)) {
for (const part of msg.content) {
if (part.type === "text" && part.text) {
@@ -623,37 +703,6 @@ function getContentBlocksFromMessage(
}
}
}
-
- // Add reasoning_content as a replay placeholder (OpenAI extended thinking format) —
- // ONLY when Anthropic's schema actually requires a precursor thinking block: the
- // outbound request has extended thinking enabled AND this assistant turn contains a
- // tool_use block (Anthropic rejects a tool_use turn without a preceding
- // thinking/redacted_thinking block when thinking is active). #5312 RC-D:
- // reasoning_content carries NO real Claude signature. Emitting a `thinking` block
- // with the fabricated DEFAULT signature makes Anthropic reject the replay with 400
- // "Invalid signature in thinking block" — and claudeHelper's latest-assistant guard
- // (prepareClaudeRequest) preserves it verbatim, so the fake signature leaks
- // upstream. Emit a signature-less redacted_thinking block instead (the same shape
- // prepareClaudeRequest produces for Anthropic-native replay, gated the same way at
- // claudeHelper.ts `thinkingEnabled && !hasThinking && hasToolUse`); Anthropic
- // accepts it without signature validation and non-Anthropic Claude-shape upstreams
- // re-hydrate the real text downstream from reasoningCache.
- // #5945: injecting this unconditionally — for ANY assistant turn carrying
- // reasoning_content, regardless of tool_use or thinking state — fabricates a content
- // block the client never sent. Some upstream clients (reported: Claude Sonnet 5 via
- // the "Pi" harness) detect the extra block and refuse the turn as prompt injection.
- // Drop reasoning_content silently when it is not required by the schema, mirroring
- // how other echo-only fields are dropped (see OPENAI_INCOMPATIBLE_ECHO_FIELDS).
- const hasThinkingBlock = blocks.some(
- (b) => b.type === "thinking" || b.type === "redacted_thinking"
- );
- const hasToolUseBlock = blocks.some((b) => b.type === "tool_use");
- if (msg.reasoning_content && thinkingEnabledForRequest && hasToolUseBlock && !hasThinkingBlock) {
- blocks.unshift({
- type: "redacted_thinking",
- data: DEFAULT_THINKING_CLAUDE_SIGNATURE,
- });
- }
}
return blocks;
diff --git a/open-sse/translator/request/openai-to-claude/thinkingBudget.ts b/open-sse/translator/request/openai-to-claude/thinkingBudget.ts
deleted file mode 100644
index e78275570f..0000000000
--- a/open-sse/translator/request/openai-to-claude/thinkingBudget.ts
+++ /dev/null
@@ -1,89 +0,0 @@
-import { capMaxOutputTokens } from "../../../../src/lib/modelCapabilities.ts";
-
-// Anthropic constraints for the thinking + max_tokens contract:
-// - thinking.budget_tokens must be >= 1024 when thinking is enabled
-// - max_tokens must be > thinking.budget_tokens (covers thinking + response)
-// - max_tokens must be <= model output cap (e.g. 128000 for Opus 4.7)
-const MIN_CLAUDE_THINKING_BUDGET = 1024;
-const MIN_RESPONSE_ROOM = 1024;
-
-function safeCapMaxOutputTokens(model: string): number | null {
- try {
- const cap = capMaxOutputTokens(model);
- return typeof cap === "number" && cap > 0 ? cap : null;
- } catch {
- return null;
- }
-}
-
-/**
- * Fit Claude thinking budget within the model's max output cap.
- *
- * Replaces the previous unconditional `max_tokens = budget + 8192` inflation,
- * which could exceed the model output cap (e.g. Opus 4.7's 128000 ceiling) and
- * trigger HTTP 400 from Anthropic ("max_tokens > 128000").
- *
- * Strategy (preserves caller intent up to the model cap):
- * - Preserve caller's max_tokens as response room (floored to MIN_RESPONSE_ROOM)
- * - Target max_tokens = responseRoom + requestedBudget, capped at modelCap
- * - fittedBudget = max_tokens - responseRoom (the thinking budget actually used)
- * - If the cap squeezes fittedBudget below the Anthropic minimum, retry with
- * responseRoom shrunk to MIN_RESPONSE_ROOM; if still below MIN, disable
- * thinking entirely (cap too tight for any reasoning).
- *
- * Worked example (real-world Opus 4.7 case that previously 400'd):
- * caller max_tokens = 32000, reasoning_effort=high → budget = 131072,
- * model cap = 128000.
- * responseRoom = max(32000, 1024) = 32000
- * target = min(32000 + 131072, 128000) = 128000
- * fittedBudget = 128000 - 32000 = 96000 (>= 1024, OK)
- * → max_tokens=128000, budget_tokens=96000 (vs. the old buggy 139264 / 131072).
- */
-export function fitThinkingToMaxTokens(
- model: string,
- callerMaxTokens: number,
- thinking: Record<string, unknown> | undefined
-): { maxTokens: number; thinking: Record<string, unknown> | undefined } {
- const modelCap = safeCapMaxOutputTokens(model);
- const requestedBudget = Number(thinking?.budget_tokens) || 0;
-
- // No budgeted thinking — just cap max_tokens to the model output ceiling.
- if (!thinking || requestedBudget <= 0) {
- return {
- maxTokens:
- modelCap === null
- ? Math.max(callerMaxTokens, 1)
- : Math.min(Math.max(callerMaxTokens, 1), modelCap),
- thinking,
- };
- }
-
- let responseRoom = Math.max(callerMaxTokens, MIN_RESPONSE_ROOM);
- let target =
- modelCap === null
- ? responseRoom + requestedBudget
- : Math.min(responseRoom + requestedBudget, modelCap);
- let fittedBudget = target - responseRoom;
-
- // If the cap squeezed thinking below Anthropic's floor, try shrinking
- // response room to MIN_RESPONSE_ROOM to recover budget.
- if (fittedBudget < MIN_CLAUDE_THINKING_BUDGET && responseRoom > MIN_RESPONSE_ROOM) {
- responseRoom = MIN_RESPONSE_ROOM;
- target =
- modelCap === null
- ? responseRoom + requestedBudget
- : Math.min(responseRoom + requestedBudget, modelCap);
- fittedBudget = target - responseRoom;
- }
-
- // Cap too tight for any thinking — disable rather than send an invalid request.
- if (fittedBudget < MIN_CLAUDE_THINKING_BUDGET) {
- return { maxTokens: modelCap ?? Math.max(callerMaxTokens, 1), thinking: undefined };
- }
-
- const adjustedThinking: Record<string, unknown> = { ...thinking };
- if (fittedBudget < requestedBudget) {
- adjustedThinking.budget_tokens = fittedBudget;
- }
- return { maxTokens: target, thinking: adjustedThinking };
-}
diff --git a/open-sse/translator/request/openai-to-kiro.ts b/open-sse/translator/request/openai-to-kiro.ts
index fc6d39abfd..7a4c794b0d 100644
--- a/open-sse/translator/request/openai-to-kiro.ts
+++ b/open-sse/translator/request/openai-to-kiro.ts
@@ -5,11 +5,6 @@
import { register } from "../registry.ts";
import { FORMATS } from "../formats.ts";
import { v4 as uuidv4, v5 as uuidv5 } from "uuid";
-import {
- parseToolInput,
- normalizeKiroToolSchema,
- serializeToolResultContent,
-} from "./openai-to-kiro/messageHelpers.ts";
/**
* Anthropic's direct-provider `[1m]` context-1m beta suffix. Kiro is AWS
@@ -28,17 +23,116 @@ export const KIRO_UNSUPPORTED_CONTEXT_1M_MESSAGE =
*/
export function hasUnsupportedKiroContextSuffix(model: unknown): boolean {
return (
- typeof model === "string" && model.toLowerCase().includes(KIRO_UNSUPPORTED_CONTEXT_1M_SUFFIX)
+ typeof model === "string" &&
+ model.toLowerCase().includes(KIRO_UNSUPPORTED_CONTEXT_1M_SUFFIX)
);
}
+function parseToolInput(value: unknown) {
+ if (value && typeof value === "object" && !Array.isArray(value)) {
+ return value;
+ }
+ if (typeof value !== "string") {
+ return {};
+ }
+
+ const trimmed = value.trim();
+ if (!trimmed) {
+ return {};
+ }
+
+ try {
+ const parsed = JSON.parse(trimmed);
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
+ } catch {
+ return {};
+ }
+}
+
/**
- * Wrap system-prompt content in <system-reminder> tags before it is merged into
- * a Kiro user message. Kiro/CodeWhisperer has no `system` role, so without this
- * the system prompt would appear as raw user text (issue #2306).
+ * Recursively sanitize JSON Schema for Kiro API.
+ * Kiro returns 400 "Improperly formed request" if:
+ * - `required` is an empty array []
+ * - `additionalProperties` is present anywhere
*/
-function wrapSystemReminder(text: string): string {
- return `<system-reminder>\n${text}\n</system-reminder>`;
+function normalizeKiroToolSchema(schema: unknown): Record<string, unknown> {
+ if (!schema || typeof schema !== "object" || Array.isArray(schema)) {
+ return { type: "object", properties: {} };
+ }
+
+ const result: Record<string, unknown> = {};
+ const src = schema as Record<string, unknown>;
+
+ for (const [key, value] of Object.entries(src)) {
+ // Skip empty required arrays — Kiro rejects them
+ if (key === "required" && Array.isArray(value) && value.length === 0) {
+ continue;
+ }
+ // Skip additionalProperties — Kiro doesn't support it
+ if (key === "additionalProperties") {
+ continue;
+ }
+ // Recursively process nested objects
+ if (
+ key === "properties" &&
+ typeof value === "object" &&
+ value !== null &&
+ !Array.isArray(value)
+ ) {
+ const sanitizedProps: Record<string, unknown> = {};
+ for (const [propName, propValue] of Object.entries(value as Record<string, unknown>)) {
+ sanitizedProps[propName] = normalizeKiroToolSchema(propValue);
+ }
+ result[key] = sanitizedProps;
+ } else if (typeof value === "object" && value !== null && !Array.isArray(value)) {
+ result[key] = normalizeKiroToolSchema(value);
+ } else if (Array.isArray(value)) {
+ result[key] = value.map((item) =>
+ typeof item === "object" && item !== null && !Array.isArray(item)
+ ? normalizeKiroToolSchema(item)
+ : item
+ );
+ } else {
+ result[key] = value;
+ }
+ }
+
+ return result;
+}
+
+function serializeToolResultContent(content: unknown): string {
+ if (typeof content === "string") {
+ return content || "(no output)";
+ }
+ if (!Array.isArray(content)) {
+ if (content !== null && content !== undefined) {
+ try {
+ return JSON.stringify(content);
+ } catch {
+ return "(no output)";
+ }
+ }
+ return "(no output)";
+ }
+ const parts: string[] = [];
+ for (const block of content as Array<Record<string, unknown>>) {
+ if (!block || typeof block !== "object") continue;
+ if (block.type === "text" && typeof block.text === "string") {
+ if (block.text) parts.push(block.text);
+ } else if (block.type === "image" || block.type === "image_url") {
+ const src = block.source as Record<string, unknown> | undefined;
+ const mediaType = src?.media_type ?? block.media_type ?? "image";
+ parts.push(`[image: ${mediaType}]`);
+ } else {
+ try {
+ const str = JSON.stringify(block);
+ if (str && str !== "{}") parts.push(str);
+ } catch {
+ // skip unserializable block
+ }
+ }
+ }
+ return parts.join("\n") || "(no output)";
}
/**
@@ -247,11 +341,7 @@ function convertMessages(messages, tools, model) {
content: [{ text: toolContent }],
});
} else if (content) {
- // #2306: Kiro/CodeWhisperer has no `system` role, so system messages are
- // normalized to `user`. Wrap their content in <system-reminder> tags so
- // the model can tell the system prompt apart from real user input instead
- // of treating the full Claude Code prompt as something the user typed.
- pendingUserContent.push(msg.role === "system" ? wrapSystemReminder(content) : content);
+ pendingUserContent.push(content);
}
} else if (role === "assistant") {
// Extract text content and tool uses
@@ -716,7 +806,9 @@ export function buildKiroPayload(model, body, stream, credentials) {
// compressContext runs). This keeps conversationId stable even when compression alters content.
// Priority 2: Deterministic hash from first user message in translated history (fallback).
const preCompressionBody = credentials?._preCompressionBody as
- Record<string, unknown> | null | undefined;
+ | Record<string, unknown>
+ | null
+ | undefined;
const preCompressionMessages = Array.isArray(preCompressionBody?.messages)
? preCompressionBody.messages
: null;
diff --git a/open-sse/translator/request/openai-to-kiro/messageHelpers.ts b/open-sse/translator/request/openai-to-kiro/messageHelpers.ts
deleted file mode 100644
index 2102023fa7..0000000000
--- a/open-sse/translator/request/openai-to-kiro/messageHelpers.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-// Pure message/tool helpers for the OpenAI -> Kiro request translator.
-// Extracted verbatim from openai-to-kiro.ts (no host imports).
-
-export function parseToolInput(value: unknown) {
- if (value && typeof value === "object" && !Array.isArray(value)) {
- return value;
- }
- if (typeof value !== "string") {
- return {};
- }
-
- const trimmed = value.trim();
- if (!trimmed) {
- return {};
- }
-
- try {
- const parsed = JSON.parse(trimmed);
- return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
- } catch {
- return {};
- }
-}
-
-/**
- * Recursively sanitize JSON Schema for Kiro API.
- * Kiro returns 400 "Improperly formed request" if:
- * - `required` is an empty array []
- * - `additionalProperties` is present anywhere
- */
-export function normalizeKiroToolSchema(schema: unknown): Record<string, unknown> {
- if (!schema || typeof schema !== "object" || Array.isArray(schema)) {
- return { type: "object", properties: {} };
- }
-
- const result: Record<string, unknown> = {};
- const src = schema as Record<string, unknown>;
-
- for (const [key, value] of Object.entries(src)) {
- // Skip empty required arrays — Kiro rejects them
- if (key === "required" && Array.isArray(value) && value.length === 0) {
- continue;
- }
- // Skip additionalProperties — Kiro doesn't support it
- if (key === "additionalProperties") {
- continue;
- }
- // Recursively process nested objects
- if (
- key === "properties" &&
- typeof value === "object" &&
- value !== null &&
- !Array.isArray(value)
- ) {
- const sanitizedProps: Record<string, unknown> = {};
- for (const [propName, propValue] of Object.entries(value as Record<string, unknown>)) {
- sanitizedProps[propName] = normalizeKiroToolSchema(propValue);
- }
- result[key] = sanitizedProps;
- } else if (typeof value === "object" && value !== null && !Array.isArray(value)) {
- result[key] = normalizeKiroToolSchema(value);
- } else if (Array.isArray(value)) {
- result[key] = value.map((item) =>
- typeof item === "object" && item !== null && !Array.isArray(item)
- ? normalizeKiroToolSchema(item)
- : item
- );
- } else {
- result[key] = value;
- }
- }
-
- return result;
-}
-
-export function serializeToolResultContent(content: unknown): string {
- if (typeof content === "string") {
- return content || "(no output)";
- }
- if (!Array.isArray(content)) {
- if (content !== null && content !== undefined) {
- try {
- return JSON.stringify(content);
- } catch {
- return "(no output)";
- }
- }
- return "(no output)";
- }
- const parts: string[] = [];
- for (const block of content as Array<Record<string, unknown>>) {
- if (!block || typeof block !== "object") continue;
- if (block.type === "text" && typeof block.text === "string") {
- if (block.text) parts.push(block.text);
- } else if (block.type === "image" || block.type === "image_url") {
- const src = block.source as Record<string, unknown> | undefined;
- const mediaType = src?.media_type ?? block.media_type ?? "image";
- parts.push(`[image: ${mediaType}]`);
- } else {
- try {
- const str = JSON.stringify(block);
- if (str && str !== "{}") parts.push(str);
- } catch {
- // skip unserializable block
- }
- }
- }
- return parts.join("\n") || "(no output)";
-}
diff --git a/open-sse/translator/response/gemini-to-openai.ts b/open-sse/translator/response/gemini-to-openai.ts
index 9d8a8629fe..dbf608b148 100644
--- a/open-sse/translator/response/gemini-to-openai.ts
+++ b/open-sse/translator/response/gemini-to-openai.ts
@@ -9,7 +9,6 @@ import {
containsTextualToolCallMarker,
} from "../../utils/textualToolCall.ts";
import { normalizeOpenAICompatibleFinishReasonString } from "../../utils/finishReason.ts";
-import { stripAnsiCodes } from "../../utils/streamHelpers.ts";
type GeminiToOpenAIState = {
functionIndex: number;
@@ -402,10 +401,6 @@ export function geminiToOpenAIResponse(chunk, state) {
// Process parts
if (content?.parts) {
for (const part of content.parts) {
- // Normalize the part text once: strip ANSI/VT100 escape codes that some
- // upstreams (gemini-cli terminal redraws) inject, so the `<thinking>` /
- // `[Tool call:]` textual parsers below never see stray control bytes (#2273).
- const partText = stripAnsiCodes(part.text);
const hasThoughtSig = part.thoughtSignature || part.thought_signature;
const isThought = part.thought === true;
if (hasThoughtSig && typeof hasThoughtSig === "string") {
@@ -414,7 +409,7 @@ export function geminiToOpenAIResponse(chunk, state) {
// Handle thought signature (thinking mode) or native gemini thought flag
if (hasThoughtSig || isThought) {
- const hasTextContent = partText !== undefined && partText !== "";
+ const hasTextContent = part.text !== undefined && part.text !== "";
const hasFunctionCall = !!part.functionCall;
// Gemini/Antigravity can emit thoughtSignature as a standalone part
@@ -438,7 +433,7 @@ export function geminiToOpenAIResponse(chunk, state) {
choices: [
{
index: 0,
- delta: isThought ? { reasoning_content: partText } : { content: partText },
+ delta: isThought ? { reasoning_content: part.text } : { content: part.text },
finish_reason: null,
},
],
@@ -468,10 +463,10 @@ export function geminiToOpenAIResponse(chunk, state) {
// "[Tool call: ...]" block instead of native functionCall. Convert that
// back to a structured OpenAI tool call so clients/tools do not see it as
// assistant prose.
- if (partText !== undefined && partText !== "") {
+ if (part.text !== undefined && part.text !== "") {
const afterReasoning = parseTextualReasoningTags
- ? consumeTextualReasoningTags(partText, state, results)
- : partText;
+ ? consumeTextualReasoningTags(part.text, state, results)
+ : part.text;
if (!afterReasoning) continue;
let accumulated = (state.textualToolCallBuffer || "") + afterReasoning;
diff --git a/open-sse/translator/response/openai-responses.ts b/open-sse/translator/response/openai-responses.ts
index 6e62715f84..3a9a1299da 100644
--- a/open-sse/translator/response/openai-responses.ts
+++ b/open-sse/translator/response/openai-responses.ts
@@ -7,16 +7,38 @@ import { FORMATS } from "../formats.ts";
import { appendToolCallArgumentDelta } from "../../utils/toolCallArguments.ts";
import { fallbackToolCallId } from "../helpers/toolCallHelper.ts";
import { shouldParseTextualReasoningTags } from "../../handlers/responseSanitizer.ts";
-import {
- normalizeToolName,
- stripEmptyOptionalToolArgs,
- normalizeOutputIndex,
- normalizeUpstreamFailure,
- extractResponsesReasoningSummaryText,
-} from "./openai-responses/pureHelpers.ts";
-// normalizeUpstreamFailure is re-exported for external importers (tests).
-export { normalizeUpstreamFailure } from "./openai-responses/pureHelpers.ts";
+function normalizeToolName(value) {
+ return typeof value === "string" ? value.trim() : "";
+}
+
+function stripEmptyOptionalToolArgs(value, toolName) {
+ if (value == null) return value;
+
+ if (typeof value === "string") {
+ // JSON-string cleanup is intentionally scoped to Claude Code's Read tool.
+ // For arbitrary tools, empty strings/arrays may be valid user payloads.
+ if (toolName !== "Read") return value;
+ try {
+ const parsed = JSON.parse(value);
+ if (Array.isArray(parsed) || typeof parsed !== "object" || parsed === null) return value;
+ const cleaned = stripEmptyOptionalToolArgs(parsed, toolName);
+ return JSON.stringify(cleaned ?? {});
+ } catch {
+ return value;
+ }
+ }
+
+ if (Array.isArray(value) || typeof value !== "object") return value;
+
+ const cleaned = { ...value };
+ for (const [key, entry] of Object.entries(cleaned)) {
+ if (entry === "" || (Array.isArray(entry) && entry.length === 0)) {
+ delete cleaned[key];
+ }
+ }
+ return cleaned;
+}
/**
* Translate OpenAI chunk to Responses API events
@@ -170,6 +192,11 @@ export function openaiToOpenAIResponsesResponse(chunk, state) {
}
// Normalize output_index to a non-negative integer (replaces fragile parseInt calls)
+function normalizeOutputIndex(outputIndex) {
+ const normalized = Number(outputIndex);
+ return Number.isInteger(normalized) && normalized >= 0 ? normalized : 0;
+}
+
// Record a finalized item keyed by output_index so buildDenseOutput can sort later
function recordCompletedItem(state, outputIndex, item) {
if (!Array.isArray(state.completedOutputItems)) {
@@ -537,6 +564,50 @@ function flushEvents(state) {
return events;
}
+export function normalizeUpstreamFailure(data, fallbackType = "server_error") {
+ const response = data?.response && typeof data.response === "object" ? data.response : null;
+ const error =
+ response?.error && typeof response.error === "object"
+ ? response.error
+ : data?.error && typeof data.error === "object"
+ ? data.error
+ : null;
+
+ const code = typeof error?.code === "string" ? error.code : "";
+ const message =
+ typeof error?.message === "string"
+ ? error.message
+ : typeof data?.message === "string"
+ ? data.message
+ : "Upstream failure";
+
+ // Preserve upstream error semantics:
+ // - context_length_exceeded → 400 (client can retry with smaller context)
+ // - rate_limit_exceeded → 429 (client should back off)
+ // - Everything else → 502 (upstream failure)
+ const isContextOverflow = code === "context_length_exceeded";
+ const isRateLimit = code === "rate_limit_exceeded" || code === "rate_limited";
+ let status: number;
+ let type: string;
+ if (isRateLimit) {
+ status = 429;
+ type = "rate_limit_error";
+ } else if (isContextOverflow) {
+ status = 400;
+ type = "invalid_request_error";
+ } else {
+ status = 502;
+ type = fallbackType;
+ }
+
+ return {
+ status,
+ type,
+ code: code || (isRateLimit ? "rate_limit_exceeded" : "bad_gateway"),
+ message,
+ };
+}
+
/**
* OpenAI Chat Completions streams announce the assistant role on the FIRST delta
* (e.g. `{ "role": "assistant", "content": "" }` or `{ "role": "assistant",
@@ -609,6 +680,15 @@ function buildResponsesReasoningDeltaChunk(state, text) {
};
}
+function extractResponsesReasoningSummaryText(item) {
+ if (!item || !Array.isArray(item.summary)) return "";
+ return item.summary
+ .map((part) =>
+ part && typeof part === "object" && typeof part.text === "string" ? part.text : ""
+ )
+ .join("");
+}
+
/**
* Translate OpenAI Responses API chunk to OpenAI Chat Completions format
* This is for when Codex returns data and we need to send it to an OpenAI-compatible client
diff --git a/open-sse/translator/response/openai-responses/pureHelpers.ts b/open-sse/translator/response/openai-responses/pureHelpers.ts
deleted file mode 100644
index 3ed559fb55..0000000000
--- a/open-sse/translator/response/openai-responses/pureHelpers.ts
+++ /dev/null
@@ -1,92 +0,0 @@
-// Pure, stateless helpers for the OpenAI Responses <-> Chat response translator.
-// Extracted verbatim from response/openai-responses.ts (no host imports, no stream state).
-
-export function normalizeToolName(value) {
- return typeof value === "string" ? value.trim() : "";
-}
-
-export function stripEmptyOptionalToolArgs(value, toolName) {
- if (value == null) return value;
-
- if (typeof value === "string") {
- // JSON-string cleanup is intentionally scoped to Claude Code's Read tool.
- // For arbitrary tools, empty strings/arrays may be valid user payloads.
- if (toolName !== "Read") return value;
- try {
- const parsed = JSON.parse(value);
- if (Array.isArray(parsed) || typeof parsed !== "object" || parsed === null) return value;
- const cleaned = stripEmptyOptionalToolArgs(parsed, toolName);
- return JSON.stringify(cleaned ?? {});
- } catch {
- return value;
- }
- }
-
- if (Array.isArray(value) || typeof value !== "object") return value;
-
- const cleaned = { ...value };
- for (const [key, entry] of Object.entries(cleaned)) {
- if (entry === "" || (Array.isArray(entry) && entry.length === 0)) {
- delete cleaned[key];
- }
- }
- return cleaned;
-}
-
-export function normalizeOutputIndex(outputIndex) {
- const normalized = Number(outputIndex);
- return Number.isInteger(normalized) && normalized >= 0 ? normalized : 0;
-}
-
-export function normalizeUpstreamFailure(data, fallbackType = "server_error") {
- const response = data?.response && typeof data.response === "object" ? data.response : null;
- const error =
- response?.error && typeof response.error === "object"
- ? response.error
- : data?.error && typeof data.error === "object"
- ? data.error
- : null;
-
- const code = typeof error?.code === "string" ? error.code : "";
- const message =
- typeof error?.message === "string"
- ? error.message
- : typeof data?.message === "string"
- ? data.message
- : "Upstream failure";
-
- // Preserve upstream error semantics:
- // - context_length_exceeded → 400 (client can retry with smaller context)
- // - rate_limit_exceeded → 429 (client should back off)
- // - Everything else → 502 (upstream failure)
- const isContextOverflow = code === "context_length_exceeded";
- const isRateLimit = code === "rate_limit_exceeded" || code === "rate_limited";
- let status: number;
- let type: string;
- if (isRateLimit) {
- status = 429;
- type = "rate_limit_error";
- } else if (isContextOverflow) {
- status = 400;
- type = "invalid_request_error";
- } else {
- status = 502;
- type = fallbackType;
- }
-
- return {
- status,
- type,
- code: code || (isRateLimit ? "rate_limit_exceeded" : "bad_gateway"),
- message,
- };
-}
-
-export function extractResponsesReasoningSummaryText(item) {
- if (!item || !Array.isArray(item.summary)) return "";
- return item.summary
- .map((part) =>
- part && typeof part === "object" && typeof part.text === "string" ? part.text : ""
- )
- .join("");
-}
diff --git a/open-sse/utils/clinepassEnvelope.ts b/open-sse/utils/clinepassEnvelope.ts
deleted file mode 100644
index 925bb4efeb..0000000000
--- a/open-sse/utils/clinepassEnvelope.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-// ClinePass upstream wraps non-streaming JSON responses in a {success, data}
-// envelope (errors use {success: false, error}). Detect and unwrap; pass the
-// payload through untouched for every other provider / shape.
-
-export interface ClinepassEnvelopeError {
- message: string;
- status: number | null;
-}
-
-export interface ClinepassEnvelopeResult {
- body: unknown;
- error: ClinepassEnvelopeError | null;
-}
-
-/**
- * Unwrap a ClinePass {success, data} envelope.
- *
- * - Non-clinepass provider, non-object, array, or object without a `success`
- * key → pass through untouched ({ body, error: null }).
- * - { success: false, ... } → { body: null, error: { message, status } } with
- * the upstream error string extracted (never a local stack — the caller must
- * still route it through sanitizeErrorMessage before emitting a response).
- * - { success: true, data: {...} } → unwrap to `data`.
- */
-export function unwrapClinepassEnvelope(
- body: unknown,
- provider: string | null | undefined
-): ClinepassEnvelopeResult {
- if (provider !== "clinepass") return { body, error: null };
- if (!body || typeof body !== "object" || Array.isArray(body)) return { body, error: null };
-
- const record = body as Record<string, unknown>;
- if (!("success" in record)) return { body, error: null };
-
- if (record.success === false) {
- const rawError = record.error;
- const message =
- typeof rawError === "string"
- ? rawError
- : (rawError && typeof rawError === "object"
- ? ((rawError as Record<string, unknown>).message as string | undefined)
- : undefined) ||
- (typeof record.message === "string" ? record.message : undefined) ||
- "Upstream error";
- const statusCode = typeof record.statusCode === "number" ? record.statusCode : null;
- return { body: null, error: { message, status: statusCode } };
- }
-
- if (
- record.success === true &&
- "data" in record &&
- record.data !== null &&
- typeof record.data === "object"
- ) {
- return { body: record.data, error: null };
- }
-
- return { body, error: null };
-}
diff --git a/open-sse/utils/error.ts b/open-sse/utils/error.ts
index 9afc237715..17bbef99d4 100644
--- a/open-sse/utils/error.ts
+++ b/open-sse/utils/error.ts
@@ -1,5 +1,4 @@
import { CORS_HEADERS } from "./cors.ts";
-import { unwrapClinepassEnvelope } from "./clinepassEnvelope.ts";
import { getDefaultErrorMessage, getErrorInfo } from "../config/errorConfig.ts";
import { normalizePayloadForLog } from "@/lib/logPayloads";
import type { ModelCooldownErrorPayload } from "@/types";
@@ -231,14 +230,7 @@ export async function parseUpstreamError(response: Response, provider: string |
const parsed = JSON.parse(text);
// Handle array responses (e.g., from some Gemini APIs)
const json = (Array.isArray(parsed) && parsed.length > 0 ? parsed[0] : parsed) || {};
- // ClinePass wraps upstream errors in a {success:false, error} envelope.
- // Extract the upstream error string (an upstream JSON field, not a local
- // stack) — still routed through sanitizeErrorMessage/buildErrorBody by
- // every consumer below (Rule #12).
- const { error: clinepassEnvError } = unwrapClinepassEnvelope(json, provider);
- message = clinepassEnvError
- ? clinepassEnvError.message
- : json.error?.message || json.message || json.error || text;
+ message = json.error?.message || json.message || json.error || text;
errorCode = json.error?.code || json.code;
errorType = json.error?.type || json.type;
} catch {
@@ -505,8 +497,7 @@ export function formatProviderError(
const message = error.message || "Unknown error";
// Expose low-level cause (e.g. UND_ERR_SOCKET, ECONNRESET, ETIMEDOUT) for diagnosing fetch failures
const cause = (error as { cause?: unknown }).cause;
- const causeObj =
- cause && typeof cause === "object" ? (cause as Record<string, unknown>) : undefined;
+ const causeObj = cause && typeof cause === "object" ? (cause as Record<string, unknown>) : undefined;
const causeCode = typeof causeObj?.code === "string" ? causeObj.code : undefined;
const causeMsg = typeof causeObj?.message === "string" ? causeObj.message : undefined;
const causeStr =
diff --git a/open-sse/utils/streamHelpers.ts b/open-sse/utils/streamHelpers.ts
index 03e0b66f5c..bfa5a2aad2 100644
--- a/open-sse/utils/streamHelpers.ts
+++ b/open-sse/utils/streamHelpers.ts
@@ -53,31 +53,6 @@ function isRecord(value: unknown): value is Record<string, unknown> {
return !!value && typeof value === "object" && !Array.isArray(value);
}
-/**
- * Matches ANSI/VT100 terminal control sequences plus non-whitespace C0 control
- * codes, while preserving `\t` (0x09), `\n` (0x0a), and `\r` (0x0d).
- *
- * Some upstream CLIs (notably gemini-cli via the `gc/` bridge) prefix SSE frames
- * with cursor-movement escapes such as `\x1b[2K\x1b[1A` to redraw the terminal.
- * Those bytes are not whitespace, so `line.trimStart().startsWith("data:")` fails
- * and the frame is silently dropped, stalling the client SSE parser (issue #2273).
- *
- * The pattern is strictly bounded (no unbounded quantifiers over overlapping
- * alternatives) so it runs in linear time on untrusted input — ReDoS-safe.
- */
-// eslint-disable-next-line no-control-regex
-const ANSI_ESCAPE_RE =
- /\x1b(?:\[[0-9;?]*[A-Za-z]|\][^\x07\x1b]*(?:\x07|\x1b\\)|[A-Z\[\]\\^_`])|[\x00-\x08\x0b\x0c\x0e-\x1f]/g;
-
-/**
- * Strip ANSI/VT100 escape sequences (and stray C0 controls) from a string.
- * Non-string inputs (null/undefined) are returned unchanged. Preserves \t \n \r.
- */
-export function stripAnsiCodes<T>(str: T): T {
- if (typeof str !== "string") return str;
- return str.replace(ANSI_ESCAPE_RE, "") as T;
-}
-
export function parseSSEDataPayload(
data: unknown,
options: SSEPayloadOptions = {}
@@ -113,18 +88,15 @@ export function parseSSEDataLines(
export function parseSSELine(line: string): SSEJsonPayload | null {
if (!line) return null;
- // Trim leading whitespace before checking field name. Also strip ANSI/VT100
- // escape codes so terminal-redraw-prefixed frames (e.g. gemini-cli `\x1b[2K\x1b[1A`)
- // still resolve to a `data:` line instead of being silently dropped (#2273).
+ // Trim leading whitespace before checking field name.
const trimmed = line.trimStart();
- const clean = stripAnsiCodes(trimmed);
- if (!clean.startsWith("data:")) return null;
+ if (!trimmed.startsWith("data:")) return null;
- return parseSSEDataPayload(clean.slice(5));
+ return parseSSEDataPayload(trimmed.slice(5));
}
function extractSseDataLine(line: string): string | null {
- const trimmed = stripAnsiCodes(line.trimStart().replace(/\r$/, ""));
+ const trimmed = line.trimStart().replace(/\r$/, "");
if (!trimmed.startsWith("data:")) return null;
return trimmed.slice(5).trimStart();
}
diff --git a/package-lock.json b/package-lock.json
index 882f93cc12..655662db13 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "omniroute",
- "version": "3.8.44",
+ "version": "3.8.43",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "omniroute",
- "version": "3.8.44",
+ "version": "3.8.43",
"hasInstallScript": true,
"license": "MIT",
"workspaces": [
@@ -22,7 +22,6 @@
"@monaco-editor/react": "^4.7.0",
"@ngrok/ngrok": "^1.7.0",
"@swc/helpers": "0.5.23",
- "@toon-format/toon": "^2.3.0",
"@types/mdx": "^2.0.13",
"@xyflow/react": "^12.11.1",
"axios": "^1.16.1",
@@ -71,7 +70,6 @@
"react-markdown": "^10.1.0",
"react-reconciler": "^0.33.0",
"recharts": "^3.8.1",
- "safe-regex": "^2.1.1",
"selfsigned": "^5.5.0",
"socks": "^2.8.7",
"sql.js": "^1.14.1",
@@ -28673,7 +28671,7 @@
},
"open-sse": {
"name": "@omniroute/open-sse",
- "version": "3.8.44",
+ "version": "3.8.43",
"dependencies": {
"@toon-format/toon": "^2.3.0",
"safe-regex": "^2.1.1"
diff --git a/package.json b/package.json
index 2004895bd4..ce571e997c 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "omniroute",
- "version": "3.8.44",
+ "version": "3.8.43",
"description": "Unified AI router with 160+ providers, RTK+Caveman compression, auto fallback, MCP/A2A, desktop, PWA, and OpenAI-compatible APIs.",
"type": "module",
"bin": {
@@ -95,13 +95,13 @@
"electron:build:mac": "npm run build && cd electron && npm run build:mac",
"electron:build:linux": "npm run build && cd electron && npm run build:linux",
"electron:smoke:packaged": "node scripts/dev/smoke-electron-packaged.mjs",
- "test": "cross-env DISABLE_SQLITE_AUTO_BACKUP=true node --max-old-space-size=8192 --import tsx --import ./open-sse/utils/setupPolyfill.ts --import ./tests/_setup/isolateDataDir.ts --test --test-concurrency=20 tests/unit/*.test.ts \"tests/unit/{api,auth,authz,build,cli,cli-helper,combo,compression,correctness,cors,dashboard,db,db-adapters,docs,executors,gamification,guardrails,lib,mcp,memory,runtime,security,services,settings,shared,ui,usage}/**/*.test.ts\"",
- "test:unit": "cross-env DISABLE_SQLITE_AUTO_BACKUP=true node --max-old-space-size=8192 --import tsx --import ./open-sse/utils/setupPolyfill.ts --import ./tests/_setup/isolateDataDir.ts --test --test-force-exit --test-concurrency=20 tests/unit/*.test.ts \"tests/unit/{api,auth,authz,build,cli,cli-helper,combo,compression,correctness,cors,dashboard,db,db-adapters,docs,executors,gamification,guardrails,lib,mcp,memory,runtime,security,services,settings,shared,ui,usage}/**/*.test.ts\"",
- "test:unit:ci": "cross-env DISABLE_SQLITE_AUTO_BACKUP=true node --max-old-space-size=8192 --import tsx --import ./open-sse/utils/setupPolyfill.ts --import ./tests/_setup/isolateDataDir.ts --test --test-force-exit --test-concurrency=4 tests/unit/*.test.ts \"tests/unit/{api,auth,authz,build,cli,cli-helper,combo,compression,correctness,cors,dashboard,db,db-adapters,docs,executors,gamification,guardrails,lib,mcp,memory,runtime,security,services,settings,shared,ui,usage}/**/*.test.ts\"",
- "test:unit:fast": "cross-env DISABLE_SQLITE_AUTO_BACKUP=true node --max-old-space-size=8192 --import tsx --import ./open-sse/utils/setupPolyfill.ts --import ./tests/_setup/isolateDataDir.ts --test --test-force-exit --test-isolation=none tests/unit/*.test.ts \"tests/unit/{api,auth,authz,build,cli,cli-helper,combo,compression,correctness,cors,dashboard,db,db-adapters,docs,executors,gamification,guardrails,lib,mcp,memory,runtime,security,services,settings,shared,ui,usage}/**/*.test.ts\"",
+ "test": "cross-env DISABLE_SQLITE_AUTO_BACKUP=true node --max-old-space-size=8192 --import tsx --import ./open-sse/utils/setupPolyfill.ts --import ./tests/_setup/isolateDataDir.ts --test --test-concurrency=20 tests/unit/*.test.ts \"tests/unit/{api,auth,authz,build,cli,cli-helper,combo,compression,correctness,cors,dashboard,db,db-adapters,docs,gamification,guardrails,lib,mcp,memory,runtime,security,services,settings,shared,ui,usage}/**/*.test.ts\"",
+ "test:unit": "cross-env DISABLE_SQLITE_AUTO_BACKUP=true node --max-old-space-size=8192 --import tsx --import ./open-sse/utils/setupPolyfill.ts --import ./tests/_setup/isolateDataDir.ts --test --test-force-exit --test-concurrency=20 tests/unit/*.test.ts \"tests/unit/{api,auth,authz,build,cli,cli-helper,combo,compression,correctness,cors,dashboard,db,db-adapters,docs,gamification,guardrails,lib,mcp,memory,runtime,security,services,settings,shared,ui,usage}/**/*.test.ts\"",
+ "test:unit:ci": "cross-env DISABLE_SQLITE_AUTO_BACKUP=true node --max-old-space-size=8192 --import tsx --import ./open-sse/utils/setupPolyfill.ts --import ./tests/_setup/isolateDataDir.ts --test --test-force-exit --test-concurrency=4 tests/unit/*.test.ts \"tests/unit/{api,auth,authz,build,cli,cli-helper,combo,compression,correctness,cors,dashboard,db,db-adapters,docs,gamification,guardrails,lib,mcp,memory,runtime,security,services,settings,shared,ui,usage}/**/*.test.ts\"",
+ "test:unit:fast": "cross-env DISABLE_SQLITE_AUTO_BACKUP=true node --max-old-space-size=8192 --import tsx --import ./open-sse/utils/setupPolyfill.ts --import ./tests/_setup/isolateDataDir.ts --test --test-force-exit --test-isolation=none tests/unit/*.test.ts \"tests/unit/{api,auth,authz,build,cli,cli-helper,combo,compression,correctness,cors,dashboard,db,db-adapters,docs,gamification,guardrails,lib,mcp,memory,runtime,security,services,settings,shared,ui,usage}/**/*.test.ts\"",
"test:unit:shard": "concurrently --kill-others-on-fail -n s1,s2 \"npm:test:unit:shard:1\" \"npm:test:unit:shard:2\"",
- "test:unit:shard:1": "cross-env DISABLE_SQLITE_AUTO_BACKUP=true node --max-old-space-size=8192 --import tsx --import ./open-sse/utils/setupPolyfill.ts --import ./tests/_setup/isolateDataDir.ts --test --test-force-exit --test-concurrency=10 --test-shard=1/2 tests/unit/*.test.ts \"tests/unit/{api,auth,authz,build,cli,cli-helper,combo,compression,correctness,cors,dashboard,db,db-adapters,docs,executors,gamification,guardrails,lib,mcp,memory,runtime,security,services,settings,shared,ui,usage}/**/*.test.ts\"",
- "test:unit:shard:2": "cross-env DISABLE_SQLITE_AUTO_BACKUP=true node --max-old-space-size=8192 --import tsx --import ./open-sse/utils/setupPolyfill.ts --import ./tests/_setup/isolateDataDir.ts --test --test-force-exit --test-concurrency=10 --test-shard=2/2 tests/unit/*.test.ts \"tests/unit/{api,auth,authz,build,cli,cli-helper,combo,compression,correctness,cors,dashboard,db,db-adapters,docs,executors,gamification,guardrails,lib,mcp,memory,runtime,security,services,settings,shared,ui,usage}/**/*.test.ts\"",
+ "test:unit:shard:1": "cross-env DISABLE_SQLITE_AUTO_BACKUP=true node --max-old-space-size=8192 --import tsx --import ./open-sse/utils/setupPolyfill.ts --import ./tests/_setup/isolateDataDir.ts --test --test-force-exit --test-concurrency=10 --test-shard=1/2 tests/unit/*.test.ts \"tests/unit/{api,auth,authz,build,cli,cli-helper,combo,compression,correctness,cors,dashboard,db,db-adapters,docs,gamification,guardrails,lib,mcp,memory,runtime,security,services,settings,shared,ui,usage}/**/*.test.ts\"",
+ "test:unit:shard:2": "cross-env DISABLE_SQLITE_AUTO_BACKUP=true node --max-old-space-size=8192 --import tsx --import ./open-sse/utils/setupPolyfill.ts --import ./tests/_setup/isolateDataDir.ts --test --test-force-exit --test-concurrency=10 --test-shard=2/2 tests/unit/*.test.ts \"tests/unit/{api,auth,authz,build,cli,cli-helper,combo,compression,correctness,cors,dashboard,db,db-adapters,docs,gamification,guardrails,lib,mcp,memory,runtime,security,services,settings,shared,ui,usage}/**/*.test.ts\"",
"test:plan3": "cross-env DISABLE_SQLITE_AUTO_BACKUP=true node --import tsx --import ./open-sse/utils/setupPolyfill.ts --import ./tests/_setup/isolateDataDir.ts --test tests/unit/plan3-p0.test.ts",
"test:fixes": "cross-env DISABLE_SQLITE_AUTO_BACKUP=true node --import tsx --import ./open-sse/utils/setupPolyfill.ts --import ./tests/_setup/isolateDataDir.ts --test tests/unit/fixes-p1.test.ts",
"test:security": "cross-env DISABLE_SQLITE_AUTO_BACKUP=true node --import tsx --import ./open-sse/utils/setupPolyfill.ts --import ./tests/_setup/isolateDataDir.ts --test tests/unit/security-fase01.test.ts",
@@ -191,7 +191,7 @@
"test:mutation": "stryker run",
"test:ecosystem": "node scripts/dev/run-ecosystem-tests.mjs",
"test:system": "cross-env DISABLE_SQLITE_AUTO_BACKUP=true node --import tsx --import ./open-sse/utils/setupPolyfill.ts --import ./tests/_setup/isolateDataDir.ts --test --test-force-exit --test-concurrency=1 tests/e2e/system-failover.test.ts",
- "test:coverage": "cross-env DISABLE_SQLITE_AUTO_BACKUP=true NODE_OPTIONS=--max-old-space-size=8192 c8 --merge-async --output-dir coverage --exclude=tests/** --exclude=**/*.test.* --reporter=text-summary --reporter=html --reporter=json-summary --reporter=lcov --check-coverage --statements 60 --lines 60 --functions 60 --branches 60 node --max-old-space-size=8192 --import tsx --import ./open-sse/utils/setupPolyfill.ts --import ./tests/_setup/isolateDataDir.ts --test --test-force-exit --test-concurrency=8 tests/unit/*.test.ts \"tests/unit/{api,auth,authz,build,cli,cli-helper,combo,compression,correctness,cors,dashboard,db,db-adapters,docs,executors,gamification,guardrails,lib,mcp,memory,runtime,security,services,settings,shared,ui,usage}/**/*.test.ts\"",
+ "test:coverage": "cross-env DISABLE_SQLITE_AUTO_BACKUP=true NODE_OPTIONS=--max-old-space-size=8192 c8 --merge-async --output-dir coverage --exclude=tests/** --exclude=**/*.test.* --reporter=text-summary --reporter=html --reporter=json-summary --reporter=lcov --check-coverage --statements 60 --lines 60 --functions 60 --branches 60 node --max-old-space-size=8192 --import tsx --import ./open-sse/utils/setupPolyfill.ts --import ./tests/_setup/isolateDataDir.ts --test --test-force-exit --test-concurrency=8 tests/unit/*.test.ts \"tests/unit/{api,auth,authz,build,cli,cli-helper,combo,compression,correctness,cors,dashboard,db,db-adapters,docs,gamification,guardrails,lib,mcp,memory,runtime,security,services,settings,shared,ui,usage}/**/*.test.ts\"",
"test:coverage:legacy": "c8 --output-dir coverage --exclude=open-sse --check-coverage --lines 50 --functions 50 --branches 50 node --import tsx --test tests/unit/*.test.ts",
"coverage:report": "cross-env NODE_OPTIONS=--max-old-space-size=8192 c8 report --merge-async --output-dir coverage --exclude=tests/** --exclude=**/*.test.* --reporter=text --reporter=text-summary --reporter=html --reporter=json-summary --reporter=lcov",
"coverage:summary": "node scripts/check/test-report-summary.mjs --input coverage/coverage-summary.json --output coverage/coverage-report.md",
@@ -205,9 +205,7 @@
"uninstall:full": "node scripts/build/uninstall.mjs --full",
"prepare": "husky",
"system-info": "node scripts/dev/system-info.mjs",
- "build:cli-api": "node --import tsx/esm scripts/cli/generate-api-commands.mjs",
- "release:contributors": "node scripts/release/gen-contributors.mjs",
- "release:uncovered": "node scripts/release/list-uncovered-commits.mjs"
+ "build:cli-api": "node --import tsx/esm scripts/cli/generate-api-commands.mjs"
},
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.1073.0",
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
deleted file mode 100644
index 72766ea810..0000000000
--- a/pnpm-workspace.yaml
+++ /dev/null
@@ -1,31 +0,0 @@
-packages:
- - "open-sse"
-allowBuilds:
- "@parcel/watcher": true
- "@swc/core": true
- better-sqlite3: true
- core-js: true
- esbuild: true
- keytar: true
- koffi: true
- libxmljs2: true
- onnxruntime-node: true
- protobufjs: true
- sharp: true
- tls-client-node: true
- unrs-resolver: true
-onlyBuiltDependencies:
- - "@parcel/watcher"
- - "@swc/core"
- - "better-sqlite3"
- - "core-js"
- - "esbuild"
- - "keytar"
- - "koffi"
- - "libxmljs2"
- - "onnxruntime-node"
- - "omniroute"
- - "protobufjs"
- - "sharp"
- - "tls-client-node"
- - "unrs-resolver"
diff --git a/pnpm.json b/pnpm.json
deleted file mode 100644
index b07b72ab41..0000000000
--- a/pnpm.json
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "onlyBuiltDependencies": [
- "@parcel/watcher",
- "@swc/core",
- "better-sqlite3",
- "core-js",
- "esbuild",
- "keytar",
- "koffi",
- "libxmljs2",
- "omniroute",
- "onnxruntime-node",
- "protobufjs",
- "sharp",
- "tls-client-node",
- "unrs-resolver"
- ]
-}
diff --git a/scripts/check/check-known-symbols.ts b/scripts/check/check-known-symbols.ts
index 510d5b1f04..d88320ed85 100644
--- a/scripts/check/check-known-symbols.ts
+++ b/scripts/check/check-known-symbols.ts
@@ -473,16 +473,7 @@ async function main(): Promise<void> {
...(strategiesMod.ROUTING_STRATEGY_VALUES as readonly string[]),
...(strategiesMod.INTERNAL_ROUTING_STRATEGY_VALUES as readonly string[]),
];
- // The combo dispatch was decomposed (Block J): the `strategy === "..."` branches
- // now live across combo.ts + its strategy-ordering leaves, so scan all of them.
- const comboDispatchFiles = [
- "open-sse/services/combo.ts",
- "open-sse/services/combo/applyStrategyOrdering.ts",
- "open-sse/services/combo/resolveAutoStrategy.ts",
- ];
- const comboSource = comboDispatchFiles
- .map((rel) => readFileSync(resolvePath(REPO_ROOT, rel), "utf8"))
- .join("\n");
+ const comboSource = readFileSync(resolvePath(REPO_ROOT, "open-sse/services/combo.ts"), "utf8");
const handled = extractHandledStrategies(comboSource);
// Stale-enforcement (6A.3): IMPLICIT_DEFAULT_STRATEGIES is a suppression allowlist —
diff --git a/scripts/check/check-pr-evidence.mjs b/scripts/check/check-pr-evidence.mjs
index 41f059d67f..f5cbbf8624 100644
--- a/scripts/check/check-pr-evidence.mjs
+++ b/scripts/check/check-pr-evidence.mjs
@@ -231,16 +231,7 @@ if (isMain) {
} else if (result === "pass") {
reportLines.push("Result: PASS", "", reason);
} else {
- reportLines.push(
- "Result: FAIL",
- "",
- reason,
- "",
- "> ℹ️ Editing the PR body to add the evidence does NOT re-run this gate — `ci.yml` " +
- "does not listen to the `edited` event. Add the `## Evidence` block, then **push a " +
- "commit** (or re-run this job) to re-validate. For releases, put the Evidence block in " +
- "the body BEFORE the first push (see the generate-release skill, Phase 0)."
- );
+ reportLines.push("Result: FAIL", "", reason);
}
const report = buildReport(reportLines);
diff --git a/scripts/check/check-test-discovery.mjs b/scripts/check/check-test-discovery.mjs
index 4c0efe5ba8..9ea80e0774 100644
--- a/scripts/check/check-test-discovery.mjs
+++ b/scripts/check/check-test-discovery.mjs
@@ -53,7 +53,7 @@ export const COLLECTORS = [
// "vitest" e explodem no node runner). Subdir novo: adicione aqui E nos scripts
// (o drift-check + o gate de órfãos forçam a manutenção em sincronia).
{
- glob: "tests/unit/{api,auth,authz,build,cli,cli-helper,combo,compression,correctness,cors,dashboard,db,db-adapters,docs,executors,gamification,guardrails,lib,mcp,memory,runtime,security,services,settings,shared,ui,usage}/**/*.test.ts",
+ glob: "tests/unit/{api,auth,authz,build,cli,cli-helper,combo,compression,correctness,cors,dashboard,db,db-adapters,docs,gamification,guardrails,lib,mcp,memory,runtime,security,services,settings,shared,ui,usage}/**/*.test.ts",
sources: ["package.json", ".github/workflows/ci.yml"],
},
// Node native runner — test:integration (top-level only; tests/integration/services/ NÃO roda)
diff --git a/scripts/quality/build-test-impact-map.mjs b/scripts/quality/build-test-impact-map.mjs
index 1704c3a356..5952f51e7b 100644
--- a/scripts/quality/build-test-impact-map.mjs
+++ b/scripts/quality/build-test-impact-map.mjs
@@ -60,7 +60,7 @@ function sourceDepsOf(entry) {
const testFiles = globSync(
[
"tests/unit/*.test.ts",
- "tests/unit/{api,auth,authz,build,cli,cli-helper,combo,compression,correctness,cors,dashboard,db,db-adapters,docs,executors,gamification,guardrails,lib,mcp,runtime,security,services,settings,shared,ui}/**/*.test.ts",
+ "tests/unit/{api,auth,authz,build,cli,cli-helper,combo,compression,correctness,cors,dashboard,db,db-adapters,docs,gamification,guardrails,lib,mcp,runtime,security,services,settings,shared,ui}/**/*.test.ts",
],
{ cwd: ROOT, absolute: true }
);
diff --git a/scripts/quality/validate-release-green.mjs b/scripts/quality/validate-release-green.mjs
index 78091ce8ab..2914db0b50 100644
--- a/scripts/quality/validate-release-green.mjs
+++ b/scripts/quality/validate-release-green.mjs
@@ -146,7 +146,7 @@ function run(cmd, cmdArgs, opts = {}) {
encoding: "utf8",
stdio: ["ignore", "pipe", "pipe"],
maxBuffer: 256 * 1024 * 1024,
- env: { ...process.env, FORCE_COLOR: "0", ...(opts.env || {}) },
+ env: { ...process.env, FORCE_COLOR: "0" },
// A hard ceiling for the long, silent test suites (execFileSync buffers all output until
// exit, so they show no progress while running). undefined = no timeout for fast gates.
...(opts.timeout ? { timeout: opts.timeout } : {}),
@@ -255,27 +255,6 @@ function main() {
});
}
- // test-masking (hard) — a PR-context gate: it only runs on the release PR (PR→main) in CI, so
- // net-assert reductions accrue unseen on release/** and explode on the release PR. Reproduce it
- // here against origin/main so a non-allowlisted reduction surfaces in the pre-flight, not in a
- // ~40-min CI layer (v3.8.43 cost 3 such round-trips). Legitimate reductions get allowlisted in
- // config/quality/test-masking-allowlist.json; tautology/skip/deletion signals are never allowlistable.
- if (!QUICK) {
- announce("Test-masking (weakened-assert guard vs main)");
- // best-effort fetch so the merge-base diff is accurate; ignore fetch failure (offline pre-flight)
- run("git", ["fetch", "--no-tags", "origin", "main", "--depth=200"], { timeout: 60 * 1000 });
- const { code, out } = run(npmCmd, ["run", "check:test-masking"], {
- env: { GITHUB_BASE_REF: "main" },
- });
- record({
- id: "test-masking",
- label: "Test-masking (weakened-assert guard)",
- kind: "hard",
- ok: code === 0,
- detail: code === 0 ? "no weakening" : firstFailureLine(out),
- });
- }
-
// Remaining quality-gate / quality-extended ratchets that the PR→release
// fast-gates skip and that historically surfaced — one at a time, because the
// CI Quality Ratchet job is fail-fast — only on the release PR. Running them all
diff --git a/scripts/release/gen-contributors.mjs b/scripts/release/gen-contributors.mjs
deleted file mode 100644
index 660fbb5893..0000000000
--- a/scripts/release/gen-contributors.mjs
+++ /dev/null
@@ -1,186 +0,0 @@
-#!/usr/bin/env node
-// Generate (or inject) the `### 🙌 Contributors` table for a CHANGELOG version section.
-//
-// WHY: every version's CHANGELOG `## [vX.Y.Z]` section MUST end with a `### 🙌 Contributors`
-// table (the convention across every prior version). v3.8.43 shipped without it (a real miss the
-// owner caught) because it was assembled by hand. This makes it reproducible + accurate.
-//
-// A naive `@handle` scan mis-assigns rollup PRs — a maintenance bullet lists many PRs under one
-// `— thanks @X`, and a flat scan would credit every handle on the line with all of them. This
-// parses each `([#refs] — thanks @X / @Y)` PARENTHETICAL GROUP and assigns that group's refs only
-// to that group's handles (crediting is per-parenthetical, matching how bullets are written).
-//
-// Usage:
-// node scripts/release/gen-contributors.mjs <version> # print the table
-// node scripts/release/gen-contributors.mjs <version> --inject # insert/replace it in CHANGELOG.md
-//
-// Exit codes: 0 ok · 2 version section not found · 3 nothing to inject over.
-
-import fs from "node:fs";
-import path from "node:path";
-import { fileURLToPath } from "node:url";
-
-const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");
-
-// Handles that are package names / code refs / scopes, never people. Extend as needed.
-export const NOISE_HANDLES = new Set([
- "toon-format",
- "dnd-kit",
- "om-usage",
- "anthropic-ai",
- "huggingface",
- "oven",
- "latest",
- "next",
- "types",
-]);
-
-const MAINTAINER = "diegosouzapw";
-
-/** Extract the `## [version]` … up to the next `## [` section body (exclusive of the next header). */
-export function extractVersionSection(changelog, version) {
- const esc = version.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
- const startRe = new RegExp(`^## \\[${esc}\\][^\\n]*$`, "m");
- const sm = changelog.match(startRe);
- if (!sm) return null;
- const bodyStart = sm.index + sm[0].length;
- const rest = changelog.slice(bodyStart);
- const nextIdx = rest.search(/\n## \[/);
- return nextIdx === -1 ? rest : rest.slice(0, nextIdx);
-}
-
-/**
- * Parse contributor → set of ref numbers from a version section body.
- * Rules (in order, per bullet line starting with "- "):
- * 1. Parenthetical groups containing "thanks": refs in the group → handles in the group.
- * 2. A "thanks @X" NOT inside such a group (direct-commit trailing credit): the last ref before
- * it on the line (if any) → the handles.
- * 3. "Extracted from [#N] by [@X]": N → X.
- * Excludes NOISE_HANDLES and the maintainer (returned separately by caller).
- */
-export function parseContributors(sectionText) {
- const agg = new Map(); // handle -> Set(refs)
- const add = (handle, refs) => {
- if (NOISE_HANDLES.has(handle) || handle === MAINTAINER) return;
- if (!agg.has(handle)) agg.set(handle, new Set());
- for (const r of refs) agg.get(handle).add(r);
- };
- const handlesIn = (s) => [...s.matchAll(/@([A-Za-z0-9_-]+)/g)].map((m) => m[1]);
- const refsIn = (s) => [...s.matchAll(/#(\d+)/g)].map((m) => Number(m[1]));
-
- for (const raw of sectionText.split("\n")) {
- if (!raw.startsWith("- ")) continue;
- // Collapse markdown links so parenthetical groups aren't broken by the URL's own parens:
- // [#5720](https://…/pull/5720) → #5720 · [@pizzav-xyz](https://…) → @pizzav-xyz
- const line = raw
- .replace(/\[#(\d+)\]\([^)]*\)/g, "#$1")
- .replace(/\[@([A-Za-z0-9_-]+)\]\([^)]*\)/g, "@$1");
- const usedSpans = [];
-
- // (1) parenthetical groups with "thanks"
- for (const g of line.matchAll(/\(([^()]*thanks[^()]*)\)/g)) {
- const inner = g[1];
- const refs = refsIn(inner);
- for (const th of inner.matchAll(/thanks\s+((?:@[A-Za-z0-9_-]+(?:\s*\/\s*)?)+)/g)) {
- for (const h of handlesIn(th[1])) add(h, refs);
- }
- usedSpans.push([g.index, g.index + g[0].length]);
- }
-
- // (2) trailing "— thanks @X" outside any used parenthetical (direct commits)
- for (const th of line.matchAll(/thanks\s+((?:@[A-Za-z0-9_-]+(?:\s*\/\s*)?)+)/g)) {
- const inGroup = usedSpans.some(([s, e]) => th.index >= s && th.index < e);
- if (inGroup) continue;
- const before = line.slice(0, th.index);
- const refsBefore = refsIn(before);
- const refs = refsBefore.length ? [refsBefore[refsBefore.length - 1]] : [];
- for (const h of handlesIn(th[1])) add(h, refs);
- }
-
- // (3) "Extracted from #N by @X" (links already collapsed by the preprocessing above)
- for (const em of line.matchAll(/[Ee]xtracted from #(\d+)\s+by\s+@([A-Za-z0-9_-]+)/g)) {
- add(em[2], [Number(em[1])]);
- }
- }
- return agg;
-}
-
-export function renderContributors(version, agg, maintainerNote = "maintainer") {
- const fmt = (set) =>
- set.size
- ? [...set]
- .sort((a, b) => a - b)
- .map((n) => `#${n}`)
- .join(", ")
- : "direct commit / report";
- const rows = [...agg.entries()].sort((a, b) =>
- a[0].toLowerCase().localeCompare(b[0].toLowerCase())
- );
- const lines = [
- "### 🙌 Contributors",
- "",
- `Thanks to everyone whose work landed in v${version}:`,
- "",
- "| Contributor | PRs / Issues |",
- "| --- | --- |",
- ];
- for (const [h, refs] of rows) {
- lines.push(`| [@${h}](https://github.com/${h}) | ${fmt(refs)} |`);
- }
- lines.push(`| [@${MAINTAINER}](https://github.com/${MAINTAINER}) | ${maintainerNote} |`);
- return lines.join("\n");
-}
-
-/** Insert or replace the Contributors section inside the version block, before its closing `---`. */
-export function injectContributors(changelog, version, table) {
- const esc = version.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
- const startRe = new RegExp(`^## \\[${esc}\\][^\\n]*$`, "m");
- const sm = changelog.match(startRe);
- if (!sm) return null;
- const headerEnd = sm.index + sm[0].length;
- const rest = changelog.slice(headerEnd);
- const nextIdx = rest.search(/\n## \[/);
- const bodyEnd = nextIdx === -1 ? changelog.length : headerEnd + nextIdx;
- let body = changelog.slice(headerEnd, bodyEnd);
- // strip an existing Contributors section (idempotent re-run)
- body = body.replace(/\n### 🙌 Contributors[\s\S]*?(?=\n---\n|$)/, "\n");
- // insert before the trailing `---` (or append if none)
- const idx = body.lastIndexOf("\n---");
- const insertion = `\n${table}\n`;
- body = idx >= 0 ? body.slice(0, idx) + insertion + body.slice(idx) : `${body}${insertion}\n---\n`;
- return changelog.slice(0, headerEnd) + body + changelog.slice(bodyEnd);
-}
-
-function main(argv) {
- const version = argv[0];
- const inject = argv.includes("--inject");
- if (!version || !/^\d+\.\d+\.\d+$/.test(version)) {
- process.stderr.write("usage: gen-contributors.mjs <version> [--inject]\n");
- process.exit(1);
- }
- const clPath = path.join(ROOT, "CHANGELOG.md");
- const changelog = fs.readFileSync(clPath, "utf8");
- const section = extractVersionSection(changelog, version);
- if (section == null) {
- process.stderr.write(`No [${version}] section in CHANGELOG.md\n`);
- process.exit(2);
- }
- const agg = parseContributors(section);
- const table = renderContributors(version, agg);
- if (!inject) {
- process.stdout.write(table + "\n");
- return;
- }
- const next = injectContributors(changelog, version, table);
- if (next == null) {
- process.stderr.write(`Could not locate [${version}] block for injection\n`);
- process.exit(3);
- }
- fs.writeFileSync(clPath, next);
- process.stderr.write(`✓ Injected ${agg.size} external contributor(s) into [${version}]\n`);
-}
-
-// direct-run guard (importable for tests)
-if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
- main(process.argv.slice(2));
-}
diff --git a/scripts/release/list-uncovered-commits.mjs b/scripts/release/list-uncovered-commits.mjs
deleted file mode 100644
index ba8127c124..0000000000
--- a/scripts/release/list-uncovered-commits.mjs
+++ /dev/null
@@ -1,119 +0,0 @@
-#!/usr/bin/env node
-// Reconciliation helper: list non-merge commits since the last tag whose PR/issue ref is NOT
-// represented in the current version's CHANGELOG section (or [Unreleased]).
-//
-// WHY: during the cycle, PRs merge into release/** and some land WITHOUT a CHANGELOG bullet, so
-// /generate-release reconciliation has to rediscover them by hand (v3.8.43: 123 of 176 commits had
-// no bullet). This surfaces exactly that gap in seconds — maintainer-side, non-blocking, run it at
-// reconciliation (Phase 0a) so the release CHANGELOG is complete before the PR opens.
-//
-// A commit is "covered" iff ANY `#N` in its subject appears anywhere in the CHANGELOG scan window
-// (the version section + [Unreleased]) — matching on issue OR PR number, since a bullet may cite
-// either. Internal commits (chore/ci/test/refactor) are listed under "rollup candidates" so the
-// maintainer can consolidate rather than write one bullet each.
-//
-// Usage: node scripts/release/list-uncovered-commits.mjs [--json]
-// Exit: 0 always (advisory). Prints a report to stdout.
-
-import { execFileSync } from "node:child_process";
-import fs from "node:fs";
-import path from "node:path";
-import { fileURLToPath } from "node:url";
-
-const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");
-const git = (args) => execFileSync("git", args, { cwd: ROOT, encoding: "utf8" }).trim();
-
-const ROLLUP_TYPES = new Set(["chore", "ci", "test", "refactor", "build", "docs", "style"]);
-
-export function refsOf(subject) {
- return [...subject.matchAll(/#(\d+)/g)].map((m) => Number(m[1]));
-}
-
-export function typeOf(subject) {
- const m = subject.match(/^([a-z]+)(\(|:|!)/);
- return m ? m[1] : "other";
-}
-
-/**
- * @param {{hash:string, subject:string}[]} commits
- * @param {Set<number>} changelogRefs every #N present in the CHANGELOG scan window
- * @returns {{covered:number, uncovered:{hash,subject,refs,type,rollup}[]}}
- */
-export function computeUncovered(commits, changelogRefs) {
- const uncovered = [];
- let covered = 0;
- for (const c of commits) {
- const refs = refsOf(c.subject);
- const isCovered = refs.length > 0 && refs.some((r) => changelogRefs.has(r));
- if (isCovered) {
- covered++;
- } else {
- const type = typeOf(c.subject);
- uncovered.push({ ...c, refs, type, rollup: ROLLUP_TYPES.has(type) });
- }
- }
- return { covered, uncovered };
-}
-
-/** Read every #N in the version's CHANGELOG section + the [Unreleased] section. */
-export function changelogRefWindow(changelog, version) {
- const esc = version.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
- // From [Unreleased] up to (but excluding) the version-after-this one.
- const startRe = /^## \[Unreleased\]/m;
- const s = changelog.match(startRe);
- const from = s ? s.index : 0;
- // find the header AFTER the target version
- const verRe = new RegExp(`^## \\[${esc}\\]`, "m");
- const vm = changelog.slice(from).match(verRe);
- const afterVersionStart = vm ? from + vm.index + vm[0].length : from;
- const rest = changelog.slice(afterVersionStart);
- const nextIdx = rest.search(/\n## \[/);
- const to = nextIdx === -1 ? changelog.length : afterVersionStart + nextIdx;
- const window = changelog.slice(from, to);
- return new Set([...window.matchAll(/#(\d+)/g)].map((m) => Number(m[1])));
-}
-
-function main(argv) {
- const jsonOut = argv.includes("--json");
- const lastTag = git(["describe", "--tags", "--abbrev=0"]);
- const version = JSON.parse(fs.readFileSync(path.join(ROOT, "package.json"), "utf8")).version;
- const log = git(["log", "--no-merges", `${lastTag}..HEAD`, "--pretty=format:%h%x09%s"]);
- const commits = log
- ? log.split("\n").map((l) => {
- const [hash, subject] = l.split("\t");
- return { hash, subject };
- })
- : [];
- const changelog = fs.readFileSync(path.join(ROOT, "CHANGELOG.md"), "utf8");
- const refs = changelogRefWindow(changelog, version);
- const { covered, uncovered } = computeUncovered(commits, refs);
-
- if (jsonOut) {
- process.stdout.write(
- JSON.stringify({ version, lastTag, total: commits.length, covered, uncovered }, null, 2) +
- "\n"
- );
- return;
- }
- const bulletsWorthy = uncovered.filter((c) => !c.rollup);
- const rollupCandidates = uncovered.filter((c) => c.rollup);
- process.stdout.write(`# Uncovered-commit reconciliation — v${version} (${lastTag}..HEAD)\n\n`);
- process.stdout.write(
- `Commits: ${commits.length} · covered: ${covered} · uncovered: ${uncovered.length}\n\n`
- );
- process.stdout.write(
- `## Needs a bullet (feat/fix/other — user-facing) — ${bulletsWorthy.length}\n`
- );
- for (const c of bulletsWorthy) process.stdout.write(`- ${c.hash} ${c.subject}\n`);
- process.stdout.write(
- `\n## Rollup candidates (chore/ci/test/refactor/docs) — ${rollupCandidates.length}\n`
- );
- for (const c of rollupCandidates) process.stdout.write(`- ${c.hash} ${c.subject}\n`);
- process.stdout.write(
- `\n> Advisory. Add a bullet for each user-facing item; consolidate rollup candidates into a few Maintenance bullets (list their PR numbers).\n`
- );
-}
-
-if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
- main(process.argv.slice(2));
-}
diff --git a/src/app/(dashboard)/dashboard/HomePageClient.tsx b/src/app/(dashboard)/dashboard/HomePageClient.tsx
index 37db2baa6b..017d14de00 100644
--- a/src/app/(dashboard)/dashboard/HomePageClient.tsx
+++ b/src/app/(dashboard)/dashboard/HomePageClient.tsx
@@ -10,7 +10,6 @@ import { Card, CardSkeleton, Button, Modal } from "@/shared/components";
import ProviderIcon from "@/shared/components/ProviderIcon";
import { AI_PROVIDERS, NOAUTH_PROVIDERS, OAUTH_PROVIDERS } from "@/shared/constants/providers";
import { useNotificationStore } from "@/store/notificationStore";
-import { extractApiErrorMessage } from "@/shared/http/apiErrorMessage";
import { copyToClipboard } from "@/shared/utils/clipboard";
import { getProviderDisplayLabel } from "@/shared/utils/providerDisplayLabel";
import { useIsElectron, useOpenExternal } from "@/shared/hooks/useElectron";
@@ -162,7 +161,13 @@ export default function HomePageClient({ machineId }: HomePageClientProps) {
// Electron internal auto-updater state and listeners
const [electronUpdateStatus, setElectronUpdateStatus] = useState<{
status:
- "idle" | "checking" | "available" | "not-available" | "downloading" | "downloaded" | "error";
+ | "idle"
+ | "checking"
+ | "available"
+ | "not-available"
+ | "downloading"
+ | "downloaded"
+ | "error";
version?: string;
percent?: number;
message?: string;
@@ -680,11 +685,7 @@ export default function HomePageClient({ machineId }: HomePageClientProps) {
if (contentType.includes("application/json")) {
const data = await res.json();
if (!res.ok || !data.success) {
- // #5991: the error envelope is `{ error: { code, message, correlation_id } }`.
- // Passing the raw object to notify.error() rendered it as a React child →
- // "Minified React error #31" crash ("Internal Server Error" screen), e.g. on
- // the 403 from the loopback-only /api/system/version. Extract the string.
- notify.error(extractApiErrorMessage(data, "Failed to start update."));
+ notify.error(data.error || "Failed to start update.");
setUpdating(false);
setUpdatePhase("idle");
return;
@@ -1108,10 +1109,7 @@ export default function HomePageClient({ machineId }: HomePageClientProps) {
<p className="text-text-muted mt-0.5">
{t.rich("step1Desc", {
endpoint: (chunks) => (
- <Link
- href="/dashboard/api-manager"
- className="text-primary hover:underline"
- >
+ <Link href="/dashboard/api-manager" className="text-primary hover:underline">
{chunks}
</Link>
),
diff --git a/src/app/(dashboard)/dashboard/api-manager/ApiManagerPageClient.tsx b/src/app/(dashboard)/dashboard/api-manager/ApiManagerPageClient.tsx
index 3a54c5a74f..362196321d 100644
--- a/src/app/(dashboard)/dashboard/api-manager/ApiManagerPageClient.tsx
+++ b/src/app/(dashboard)/dashboard/api-manager/ApiManagerPageClient.tsx
@@ -222,7 +222,6 @@ export default function ApiManagerPageClient() {
const [isSubmitting, setIsSubmitting] = useState(false);
const [usageStats, setUsageStats] = useState<Record<string, KeyUsageStats>>({});
const [sessionCounts, setSessionCounts] = useState<Record<string, number>>({});
- const [deviceCounts, setDeviceCounts] = useState<Record<string, number>>({});
const [allowKeyReveal, setAllowKeyReveal] = useState(false);
// Per-row API key visibility toggle (eye / eye-off). Keys default to masked.
// Map id -> fully revealed key string fetched on demand from /api/keys/{id}/reveal.
@@ -368,7 +367,6 @@ export default function ApiManagerPageClient() {
// Fetch usage stats after keys are loaded
fetchUsageStats(data.keys || []);
fetchSessionCounts(data.keys || []);
- fetchDeviceCounts(data.keys || []);
}
} catch (error) {
console.log("Error fetching keys:", error);
@@ -449,35 +447,6 @@ export default function ApiManagerPageClient() {
}
};
- // Per-key device/connection counts (port of upstream 9router#931, thanks
- // @mugnimaestra). One lightweight GET per key against
- // /api/keys/[id]/devices — device counts are in-memory + TTL-evicted, so
- // this is a much smaller payload than session data.
- const fetchDeviceCounts = async (apiKeys: ApiKey[]) => {
- if (apiKeys.length === 0) {
- setDeviceCounts({});
- return;
- }
- try {
- const results = await Promise.all(
- apiKeys.map(async (key) => {
- try {
- const res = await fetch(`/api/keys/${encodeURIComponent(key.id)}/devices`);
- if (!res.ok) return [key.id, 0] as const;
- const data = await res.json();
- const count = typeof data?.count === "number" && Number.isFinite(data.count) ? data.count : 0;
- return [key.id, count] as const;
- } catch {
- return [key.id, 0] as const;
- }
- })
- );
- setDeviceCounts(Object.fromEntries(results));
- } catch (error) {
- console.log("Error fetching device counts:", error);
- }
- };
-
const clearPageError = useCallback(() => setPageError(null), []);
const keyCounts = useMemo(() => computeApiKeyCounts(keys), [keys]);
@@ -994,7 +963,6 @@ export default function ApiManagerPageClient() {
const maxSessions = typeof key.maxSessions === "number" ? key.maxSessions : 0;
const hasSessionLimit = maxSessions > 0;
const activeSessions = sessionCounts[key.id] || 0;
- const deviceCount = deviceCounts[key.id] || 0;
const hasSchedule = key.accessSchedule?.enabled === true;
const keyIsQuota = isQuotaKey(key);
const groups = quotaGroupsForKey(key);
@@ -1156,15 +1124,6 @@ export default function ApiManagerPageClient() {
Sessions: {activeSessions}/{maxSessions}
</span>
)}
- {deviceCount > 0 && (
- <span
- className="inline-flex items-center gap-1 px-2 py-0.5 rounded-md bg-cyan-500/10 text-cyan-700 dark:text-cyan-300 text-[11px] font-medium"
- title={t("devicesTooltip", { count: deviceCount })}
- >
- <span className="material-symbols-outlined text-[12px]">devices</span>
- {t("devicesCount", { count: deviceCount })}
- </span>
- )}
{hasThrottle && (
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-md bg-yellow-500/10 text-yellow-700 dark:text-yellow-300 text-[11px] font-medium">
<span className="material-symbols-outlined text-[12px]">speed</span>+
diff --git a/src/app/(dashboard)/dashboard/cli-code/components/ClaudeClassifierCompatToggle.tsx b/src/app/(dashboard)/dashboard/cli-code/components/ClaudeClassifierCompatToggle.tsx
deleted file mode 100644
index e98b7a56fd..0000000000
--- a/src/app/(dashboard)/dashboard/cli-code/components/ClaudeClassifierCompatToggle.tsx
+++ /dev/null
@@ -1,98 +0,0 @@
-"use client";
-
-import { useCallback, useEffect, useState } from "react";
-
-type CompatMode = "off" | "auto" | "always";
-
-const MODES: CompatMode[] = ["off", "auto", "always"];
-
-const MODE_STYLES: Record<CompatMode, string> = {
- off: "bg-black/5 dark:bg-white/5 text-text-muted border-border",
- auto: "bg-yellow-500/10 text-yellow-600 dark:text-yellow-400 border-yellow-500/40",
- always: "bg-green-500/10 text-green-600 dark:text-green-400 border-green-500/40",
-};
-
-function isCompatMode(value: unknown): value is CompatMode {
- return value === "off" || value === "auto" || value === "always";
-}
-
-/**
- * Opt-in toggle (default "off") for Claude Code's auto-permission classifier compat mode.
- *
- * Claude Code's `--permission-mode auto` sends an internal `/v1/messages` security-classifier
- * request that requires the response to START with `<block>no</block>` (ALLOW) / `<block>yes</block>`
- * (BLOCK). When a combo/fallback route sends that call to a cheap model returning empty content,
- * Claude Code fails closed on every gated action. "auto" detects the classifier request and
- * short-circuits with a synthetic ALLOW response without calling upstream; "always" applies it to
- * every Claude-format request. Cycles off → auto → always via the existing /api/settings PATCH.
- */
-export default function ClaudeClassifierCompatToggle() {
- const [mode, setMode] = useState<CompatMode>("off");
- const [loading, setLoading] = useState(true);
- const [saving, setSaving] = useState(false);
- const [error, setError] = useState<string | null>(null);
-
- const load = useCallback(async () => {
- setLoading(true);
- try {
- const res = await fetch("/api/settings");
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- const data = await res.json();
- setMode(isCompatMode(data?.claudeClassifierCompat) ? data.claudeClassifierCompat : "off");
- setError(null);
- } catch (err) {
- setError(err instanceof Error ? err.message : "Failed to load setting");
- } finally {
- setLoading(false);
- }
- }, []);
-
- useEffect(() => {
- load();
- }, [load]);
-
- const cycle = useCallback(async () => {
- const next = MODES[(MODES.indexOf(mode) + 1) % MODES.length];
- const previous = mode;
- setMode(next); // optimistic
- setSaving(true);
- setError(null);
- try {
- const res = await fetch("/api/settings", {
- method: "PATCH",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ claudeClassifierCompat: next }),
- });
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- } catch (err) {
- setMode(previous); // revert on failure
- setError(err instanceof Error ? err.message : "Failed to save");
- } finally {
- setSaving(false);
- }
- }, [mode]);
-
- return (
- <div className="rounded-lg border border-border bg-surface/40 p-3">
- <div className="flex items-center justify-between gap-3">
- <div className="min-w-0">
- <h4 className="text-xs font-semibold text-text-main">Auto-permission classifier compat</h4>
- <p className="text-xs text-text-muted">
- Short-circuit Claude Code&apos;s <code>--permission-mode auto</code> security classifier
- with a synthetic allow, so fallback routes don&apos;t fail closed. Off by default.
- </p>
- </div>
- <button
- type="button"
- onClick={cycle}
- disabled={loading || saving}
- title="Cycle off → auto → always"
- className={`shrink-0 rounded border px-3 py-1.5 text-xs font-medium uppercase tracking-wide transition-colors disabled:opacity-50 ${MODE_STYLES[mode]}`}
- >
- {mode}
- </button>
- </div>
- {error ? <p className="mt-2 text-xs text-red-500">{error}</p> : null}
- </div>
- );
-}
diff --git a/src/app/(dashboard)/dashboard/cli-code/components/ClaudeToolCard.tsx b/src/app/(dashboard)/dashboard/cli-code/components/ClaudeToolCard.tsx
index 66871aaceb..832ff024b2 100644
--- a/src/app/(dashboard)/dashboard/cli-code/components/ClaudeToolCard.tsx
+++ b/src/app/(dashboard)/dashboard/cli-code/components/ClaudeToolCard.tsx
@@ -4,7 +4,6 @@ import { useState, useEffect, useRef } from "react";
import { Card, Button, ModelSelectModal, ManualConfigModal } from "@/shared/components";
import ProviderIcon from "@/shared/components/ProviderIcon";
import CliStatusBadge from "./CliStatusBadge";
-import ClaudeClassifierCompatToggle from "./ClaudeClassifierCompatToggle";
import { useTranslations } from "next-intl";
import {
getStoredClaudeAuthValue,
@@ -493,9 +492,6 @@ export default function ClaudeToolCard({
))}
</div>
- {/* Opt-in (default off): Claude Code auto-permission classifier compat mode. */}
- <ClaudeClassifierCompatToggle />
-
{message && (
<div
className={`flex items-center gap-2 px-2 py-1.5 rounded text-xs ${message.type === "success" ? "bg-green-500/10 text-green-600" : "bg-red-500/10 text-red-600"}`}
diff --git a/src/app/(dashboard)/dashboard/discovery/DiscoveryPageClient.tsx b/src/app/(dashboard)/dashboard/discovery/DiscoveryPageClient.tsx
deleted file mode 100644
index 72187a0ee4..0000000000
--- a/src/app/(dashboard)/dashboard/discovery/DiscoveryPageClient.tsx
+++ /dev/null
@@ -1,329 +0,0 @@
-"use client";
-
-import { useCallback, useEffect, useState } from "react";
-import { useTranslations } from "next-intl";
-import { Card, Button, Input, Badge, EmptyState, Spinner, ConfirmModal } from "@/shared/components";
-
-interface DiscoveryResult {
- id: number;
- providerId: string;
- method: string;
- endpoint?: string | null;
- authType: string;
- models?: string[];
- rateLimit?: string | null;
- feasibility: number;
- riskLevel: string;
- status: string;
- notes?: string | null;
- discoveredAt?: string;
- verifiedAt?: string | null;
-}
-
-type Feedback = { type: "success" | "error"; message: string } | null;
-type Translate = ReturnType<typeof useTranslations>;
-
-type BadgeVariant = "default" | "success" | "warning" | "error";
-
-const RISK_VARIANT: Record<string, BadgeVariant> = {
- none: "success",
- low: "success",
- medium: "warning",
- high: "error",
- critical: "error",
-};
-
-const STATUS_VARIANT: Record<string, BadgeVariant> = {
- verified: "success",
- testing: "warning",
- pending: "default",
- rejected: "error",
-};
-
-/** Run a fetch, surface a localized error via `setFeedback`, and report success. */
-async function callApi(
- fn: () => Promise<Response>,
- t: Translate,
- failKey: string,
- setFeedback: (f: Feedback) => void
-): Promise<boolean> {
- setFeedback(null);
- try {
- const res = await fn();
- const data = await res.json().catch(() => ({}));
- if (!res.ok) throw new Error(data?.error?.message || t(failKey));
- return true;
- } catch (err) {
- setFeedback({ type: "error", message: err instanceof Error ? err.message : t(failKey) });
- return false;
- }
-}
-
-/** Results list + loading + feedback state, plus the reload function. */
-function useDiscoveryResults(t: Translate) {
- const [results, setResults] = useState<DiscoveryResult[]>([]);
- const [loading, setLoading] = useState(true);
- const [feedback, setFeedback] = useState<Feedback>(null);
-
- const load = useCallback(async () => {
- setLoading(true);
- try {
- const res = await fetch("/api/discovery/results");
- const data = await res.json().catch(() => ({}));
- if (!res.ok) throw new Error(data?.error?.message || t("loadFailed"));
- setResults(Array.isArray(data.results) ? data.results : []);
- } catch (err) {
- setFeedback({ type: "error", message: err instanceof Error ? err.message : t("loadFailed") });
- } finally {
- setLoading(false);
- }
- }, [t]);
-
- useEffect(() => {
- void load();
- }, [load]);
-
- return { results, loading, feedback, setFeedback, load };
-}
-
-/** Scan / verify / delete actions and their transient state. */
-function useDiscoveryActions(
- t: Translate,
- load: () => Promise<void>,
- setFeedback: (f: Feedback) => void
-) {
- const [scanTarget, setScanTarget] = useState("");
- const [scanning, setScanning] = useState(false);
- const [busyId, setBusyId] = useState<number | null>(null);
- const [deleteTarget, setDeleteTarget] = useState<DiscoveryResult | null>(null);
-
- const scan = useCallback(async () => {
- const providerId = scanTarget.trim();
- if (!providerId) return;
- setScanning(true);
- const ok = await callApi(
- () =>
- fetch("/api/discovery/scan", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({ providerId }),
- }),
- t,
- "scanFailed",
- setFeedback
- );
- setScanning(false);
- if (ok) {
- setScanTarget("");
- setFeedback({ type: "success", message: t("scanQueued", { provider: providerId }) });
- await load();
- }
- }, [scanTarget, t, load, setFeedback]);
-
- const verify = useCallback(
- async (row: DiscoveryResult) => {
- setBusyId(row.id);
- const ok = await callApi(
- () => fetch(`/api/discovery/verify/${row.id}`, { method: "POST" }),
- t,
- "verifyFailed",
- setFeedback
- );
- setBusyId(null);
- if (ok) await load();
- },
- [t, load, setFeedback]
- );
-
- const remove = useCallback(async () => {
- if (!deleteTarget) return;
- setBusyId(deleteTarget.id);
- const ok = await callApi(
- () => fetch(`/api/discovery/results/${deleteTarget.id}`, { method: "DELETE" }),
- t,
- "deleteFailed",
- setFeedback
- );
- setBusyId(null);
- if (ok) {
- setDeleteTarget(null);
- await load();
- }
- }, [deleteTarget, t, load, setFeedback]);
-
- return {
- scanTarget,
- setScanTarget,
- scanning,
- busyId,
- deleteTarget,
- setDeleteTarget,
- scan,
- verify,
- remove,
- };
-}
-
-/** State + data orchestration for the discovery page, kept out of the view. */
-function useDiscovery() {
- const t = useTranslations("discovery");
- const { results, loading, feedback, setFeedback, load } = useDiscoveryResults(t);
- const actions = useDiscoveryActions(t, load, setFeedback);
- return { t, results, loading, feedback, ...actions };
-}
-
-function DiscoveryScanForm({
- t,
- value,
- onChange,
- onScan,
- scanning,
-}: {
- t: Translate;
- value: string;
- onChange: (v: string) => void;
- onScan: () => void;
- scanning: boolean;
-}) {
- return (
- <Card className="p-4">
- <div className="flex flex-col gap-3 sm:flex-row sm:items-end">
- <div className="flex-1">
- <label className="mb-1 block text-sm font-medium" htmlFor="discovery-scan-target">
- {t("scanLabel")}
- </label>
- <Input
- id="discovery-scan-target"
- value={value}
- placeholder={t("scanPlaceholder")}
- onChange={(e) => onChange(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === "Enter") onScan();
- }}
- />
- </div>
- <Button onClick={onScan} disabled={scanning || !value.trim()}>
- {scanning ? t("scanning") : t("scan")}
- </Button>
- </div>
- <p className="mt-2 text-xs text-muted-foreground">{t("localOnlyNote")}</p>
- </Card>
- );
-}
-
-function DiscoveryResultCard({
- t,
- row,
- busy,
- onVerify,
- onDelete,
-}: {
- t: Translate;
- row: DiscoveryResult;
- busy: boolean;
- onVerify: () => void;
- onDelete: () => void;
-}) {
- return (
- <Card className="p-4">
- <div className="flex flex-wrap items-start justify-between gap-3">
- <div className="space-y-1">
- <div className="flex items-center gap-2">
- <span className="font-medium">{row.providerId}</span>
- <Badge variant={STATUS_VARIANT[row.status] ?? "default"}>{row.status}</Badge>
- <Badge variant={RISK_VARIANT[row.riskLevel] ?? "default"}>
- {t("risk")}: {row.riskLevel}
- </Badge>
- </div>
- <div className="text-xs text-muted-foreground">
- {t("method")}: {row.method} · {t("auth")}: {row.authType} · {t("feasibility")}:{" "}
- {row.feasibility}/5
- </div>
- {row.endpoint && (
- <div className="text-xs text-muted-foreground break-all">{row.endpoint}</div>
- )}
- {row.models && row.models.length > 0 && (
- <div className="text-xs text-muted-foreground">
- {t("models")}: {row.models.join(", ")}
- </div>
- )}
- </div>
- <div className="flex gap-2">
- {row.status !== "verified" && (
- <Button variant="secondary" onClick={onVerify} disabled={busy}>
- {t("verify")}
- </Button>
- )}
- <Button variant="danger" onClick={onDelete} disabled={busy}>
- {t("delete")}
- </Button>
- </div>
- </div>
- </Card>
- );
-}
-
-export function DiscoveryPageClient() {
- const d = useDiscovery();
-
- return (
- <div className="space-y-6">
- <header className="space-y-1">
- <h1 className="text-2xl font-semibold">{d.t("title")}</h1>
- <p className="text-sm text-muted-foreground">{d.t("subtitle")}</p>
- </header>
-
- <DiscoveryScanForm
- t={d.t}
- value={d.scanTarget}
- onChange={d.setScanTarget}
- onScan={() => void d.scan()}
- scanning={d.scanning}
- />
-
- {d.feedback && (
- <div
- role="status"
- className={
- d.feedback.type === "error"
- ? "rounded-md border border-red-300 bg-red-50 px-3 py-2 text-sm text-red-700"
- : "rounded-md border border-green-300 bg-green-50 px-3 py-2 text-sm text-green-700"
- }
- >
- {d.feedback.message}
- </div>
- )}
-
- {d.loading ? (
- <div className="flex justify-center py-10">
- <Spinner />
- </div>
- ) : d.results.length === 0 ? (
- <EmptyState title={d.t("emptyTitle")} description={d.t("emptyDescription")} />
- ) : (
- <ul className="space-y-3">
- {d.results.map((row) => (
- <li key={row.id}>
- <DiscoveryResultCard
- t={d.t}
- row={row}
- busy={d.busyId === row.id}
- onVerify={() => void d.verify(row)}
- onDelete={() => d.setDeleteTarget(row)}
- />
- </li>
- ))}
- </ul>
- )}
-
- <ConfirmModal
- isOpen={d.deleteTarget !== null}
- title={d.t("deleteTitle")}
- message={d.t("deleteConfirm", { provider: d.deleteTarget?.providerId ?? "" })}
- confirmText={d.t("delete")}
- onConfirm={() => void d.remove()}
- onClose={() => d.setDeleteTarget(null)}
- />
- </div>
- );
-}
diff --git a/src/app/(dashboard)/dashboard/discovery/__tests__/DiscoveryPageClient.test.tsx b/src/app/(dashboard)/dashboard/discovery/__tests__/DiscoveryPageClient.test.tsx
deleted file mode 100644
index e5b46427e7..0000000000
--- a/src/app/(dashboard)/dashboard/discovery/__tests__/DiscoveryPageClient.test.tsx
+++ /dev/null
@@ -1,76 +0,0 @@
-// @vitest-environment jsdom
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import { render, screen, waitFor } from "@testing-library/react";
-import React from "react";
-import { DiscoveryPageClient } from "../DiscoveryPageClient";
-
-// Stable `t` reference: useTranslations must return the SAME function across
-// renders, otherwise the `load` useCallback (dep [t]) changes every render and
-// the fetch-on-mount useEffect loops forever.
-const t = (key: string, vars?: Record<string, unknown>) =>
- vars ? `${key}:${JSON.stringify(vars)}` : key;
-
-vi.mock("next-intl", () => ({
- useTranslations: () => t,
-}));
-
-function mockFetchOnce(results: unknown[]) {
- const fetchMock = vi.fn(async () =>
- new Response(JSON.stringify({ results }), {
- status: 200,
- headers: { "content-type": "application/json" },
- })
- );
- vi.stubGlobal("fetch", fetchMock);
- return fetchMock;
-}
-
-describe("DiscoveryPageClient", () => {
- beforeEach(() => {
- vi.restoreAllMocks();
- });
- afterEach(() => {
- vi.unstubAllGlobals();
- });
-
- it("loads and renders discovery results from the API", async () => {
- mockFetchOnce([
- {
- id: 1,
- providerId: "huggingchat",
- method: "free_tier",
- authType: "none",
- feasibility: 5,
- riskLevel: "none",
- status: "verified",
- models: ["mixtral"],
- },
- ]);
-
- render(<DiscoveryPageClient />);
-
- await waitFor(() => {
- expect(screen.getByText("huggingchat")).toBeInTheDocument();
- });
- // status + risk badges render (mocked t returns the key)
- expect(screen.getByText("verified")).toBeInTheDocument();
- });
-
- it("shows the empty state when there are no results", async () => {
- mockFetchOnce([]);
-
- render(<DiscoveryPageClient />);
-
- await waitFor(() => {
- expect(screen.getByText("emptyTitle")).toBeInTheDocument();
- });
- });
-
- it("calls the discovery results endpoint on mount", async () => {
- const fetchMock = mockFetchOnce([]);
- render(<DiscoveryPageClient />);
- await waitFor(() => {
- expect(fetchMock).toHaveBeenCalledWith("/api/discovery/results");
- });
- });
-});
diff --git a/src/app/(dashboard)/dashboard/discovery/page.tsx b/src/app/(dashboard)/dashboard/discovery/page.tsx
deleted file mode 100644
index a89031e19d..0000000000
--- a/src/app/(dashboard)/dashboard/discovery/page.tsx
+++ /dev/null
@@ -1,5 +0,0 @@
-import { DiscoveryPageClient } from "./DiscoveryPageClient";
-
-export default function DiscoveryPage() {
- return <DiscoveryPageClient />;
-}
diff --git a/src/app/(dashboard)/dashboard/media-providers/[kind]/[id]/MediaProviderPageClient.tsx b/src/app/(dashboard)/dashboard/media-providers/[kind]/[id]/MediaProviderPageClient.tsx
index c1eed94d7c..9ca2963b66 100644
--- a/src/app/(dashboard)/dashboard/media-providers/[kind]/[id]/MediaProviderPageClient.tsx
+++ b/src/app/(dashboard)/dashboard/media-providers/[kind]/[id]/MediaProviderPageClient.tsx
@@ -14,7 +14,6 @@ import { WebSearchExampleCard } from "../../components/WebSearchExampleCard";
import { WebFetchExampleCard } from "../../components/WebFetchExampleCard";
import { VideoExampleCard } from "../../components/VideoExampleCard";
import { MusicExampleCard } from "../../components/MusicExampleCard";
-import { OcrExampleCard } from "../../components/OcrExampleCard";
interface Connection {
id: string;
@@ -54,8 +53,6 @@ function renderPlayground(kind: MediaKind, providerId: string) {
return <VideoExampleCard providerId={providerId} />;
case "music":
return <MusicExampleCard providerId={providerId} />;
- case "ocr":
- return <OcrExampleCard providerId={providerId} />;
case "imageToText":
// Endpoint /api/v1/images/understanding does not exist yet — omitted.
return (
diff --git a/src/app/(dashboard)/dashboard/media-providers/components/ImageExampleCard.tsx b/src/app/(dashboard)/dashboard/media-providers/components/ImageExampleCard.tsx
index fea18d1207..2df7e2a28b 100644
--- a/src/app/(dashboard)/dashboard/media-providers/components/ImageExampleCard.tsx
+++ b/src/app/(dashboard)/dashboard/media-providers/components/ImageExampleCard.tsx
@@ -1,54 +1,12 @@
"use client";
-import { useEffect, useState } from "react";
+import { useState } from "react";
import { useTranslations } from "next-intl";
import { useApiKey } from "../../providers/hooks/useApiKey";
import { useProviderModels } from "../../providers/hooks/useProviderModels";
import { buildCurl } from "../../providers/utils/buildCurl";
import { PlaygroundCard } from "./PlaygroundCard";
-interface SuggestedHfModel {
- id: string;
- likes?: number;
- downloads?: number;
-}
-
-/**
- * useHfSuggestedImageModels — fetch suggested HuggingFace Hub image models
- * via GET /api/v1/providers/suggested-models?type=image. Only meaningful for
- * the `huggingface` provider (the only image-kind entry backed by HF Hub);
- * other providers simply never trigger the fetch.
- */
-function useHfSuggestedImageModels(providerId: string): SuggestedHfModel[] {
- // Keep the fetched models tagged with the providerId they were fetched
- // for, and derive the return value below — this avoids ever calling
- // setState synchronously from the effect body (react-hooks/set-state-in-effect)
- // for the "not huggingface" early-return case; switching providers simply
- // stops matching the tag instead of requiring an explicit reset call.
- const [fetched, setFetched] = useState<{ providerId: string; models: SuggestedHfModel[] } | null>(
- null
- );
-
- useEffect(() => {
- if (providerId !== "huggingface") return;
- let cancelled = false;
- fetch("/api/v1/providers/suggested-models?type=image")
- .then((res) => (res.ok ? (res.json() as Promise<{ data?: SuggestedHfModel[] }>) : null))
- .then((data) => {
- if (cancelled || !data) return;
- setFetched({ providerId, models: Array.isArray(data.data) ? data.data : [] });
- })
- .catch(() => {
- // Best-effort suggestions — the static model list still works.
- });
- return () => {
- cancelled = true;
- };
- }, [providerId]);
-
- return fetched && fetched.providerId === providerId ? fetched.models : [];
-}
-
interface Props {
providerId: string;
}
@@ -96,10 +54,8 @@ function ImageResultRenderer(data: unknown) {
export function ImageExampleCard({ providerId }: Props) {
const t = useTranslations("miniPlayground");
- const tMedia = useTranslations("media");
const { apiKey } = useApiKey();
const { models } = useProviderModels(providerId);
- const suggestedModels = useHfSuggestedImageModels(providerId);
const firstModel = models[0]?.id ?? "dall-e-3";
const [model, setModel] = useState<string>("");
@@ -153,10 +109,7 @@ export function ImageExampleCard({ providerId }: Props) {
}
};
- const staticModelOptions = models.length > 0 ? models : [{ id: "dall-e-3" }];
- const knownModelIds = new Set(staticModelOptions.map((m) => m.id));
- const suggestedOnly = suggestedModels.filter((m) => !knownModelIds.has(m.id));
- const modelOptions = [...staticModelOptions, ...suggestedOnly.map((m) => ({ id: m.id }))];
+ const modelOptions = models.length > 0 ? models : [{ id: "dall-e-3" }];
return (
<PlaygroundCard
@@ -184,31 +137,6 @@ export function ImageExampleCard({ providerId }: Props) {
))}
</select>
</div>
- {/* Suggested models from HuggingFace Hub (image kind only) */}
- {suggestedOnly.length > 0 && (
- <div>
- <label className="block text-xs text-text-muted mb-1">
- {tMedia("suggestedModels")}
- </label>
- <div className="flex flex-wrap gap-1.5">
- {suggestedOnly.map((m) => (
- <button
- key={m.id}
- type="button"
- onClick={() => setModel(m.id)}
- aria-pressed={effectiveModel === m.id}
- className={`rounded-full border px-2.5 py-1 text-xs transition-colors ${
- effectiveModel === m.id
- ? "border-primary bg-primary/10 text-primary"
- : "border-border bg-bg-subtle text-text-muted hover:text-text-main"
- }`}
- >
- {m.id}
- </button>
- ))}
- </div>
- </div>
- )}
{/* Size */}
<div>
<label className="block text-xs text-text-muted mb-1">{t("size")}</label>
diff --git a/src/app/(dashboard)/dashboard/media-providers/components/OcrExampleCard.tsx b/src/app/(dashboard)/dashboard/media-providers/components/OcrExampleCard.tsx
deleted file mode 100644
index f5a675b034..0000000000
--- a/src/app/(dashboard)/dashboard/media-providers/components/OcrExampleCard.tsx
+++ /dev/null
@@ -1,126 +0,0 @@
-"use client";
-
-import { useState } from "react";
-import { useTranslations } from "next-intl";
-import { useApiKey } from "../../providers/hooks/useApiKey";
-import { useProviderModels } from "../../providers/hooks/useProviderModels";
-import { buildCurl } from "../../providers/utils/buildCurl";
-import { PlaygroundCard } from "./PlaygroundCard";
-
-interface Props {
- providerId: string;
-}
-
-const ENDPOINT_PATH = "/api/v1/ocr";
-const SAMPLE_DOCUMENT_URL = "https://arxiv.org/pdf/2201.04234";
-
-function extractError(data: unknown): string | null {
- if (!data || typeof data !== "object") return null;
- const d = data as Record<string, unknown>;
- const err = d.error as Record<string, unknown> | undefined;
- if (err?.message) return String(err.message);
- if (typeof d.message === "string") return d.message;
- return null;
-}
-
-export function OcrExampleCard({ providerId }: Props) {
- const t = useTranslations("miniPlayground");
- const { apiKey } = useApiKey();
- const { models } = useProviderModels(providerId);
-
- const firstModel = models[0]?.id ?? "";
- const [model, setModel] = useState<string>("");
- const [documentUrl, setDocumentUrl] = useState<string>(SAMPLE_DOCUMENT_URL);
- const [running, setRunning] = useState<boolean>(false);
- const [result, setResult] = useState<{ data: unknown; latencyMs: number } | undefined>();
- const [error, setError] = useState<string | null>(null);
-
- const effectiveModel = model || firstModel;
-
- const buildBody = () => ({
- model: effectiveModel,
- document: { type: "document_url", document_url: documentUrl },
- });
-
- const curlSnippet = buildCurl({
- endpoint:
- (typeof window !== "undefined" ? window.location.origin : "http://localhost:20128") +
- ENDPOINT_PATH,
- headers: {
- Authorization: `Bearer ${apiKey || "<your-api-key>"}`,
- "Content-Type": "application/json",
- },
- body: buildBody(),
- });
-
- const handleRun = async () => {
- setRunning(true);
- setError(null);
- setResult(undefined);
- const t0 = performance.now();
- try {
- const res = await fetch(ENDPOINT_PATH, {
- method: "POST",
- headers: {
- Authorization: `Bearer ${apiKey}`,
- "Content-Type": "application/json",
- "x-connection-id": providerId,
- },
- body: JSON.stringify(buildBody()),
- });
- const data: unknown = await res.json();
- const latencyMs = performance.now() - t0;
- const errMsg = extractError(data);
- if (!res.ok || errMsg) {
- setError(errMsg ?? `HTTP ${res.status}`);
- } else {
- setResult({ data, latencyMs });
- }
- } catch (err) {
- setError(err instanceof Error ? err.message : "Request failed");
- } finally {
- setRunning(false);
- }
- };
-
- const modelOptions = models.length > 0 ? models : [{ id: "mistral-ocr-latest" }];
-
- return (
- <PlaygroundCard
- kindLabel="OCR"
- apiEndpoint={ENDPOINT_PATH}
- onRun={handleRun}
- curlSnippet={curlSnippet}
- running={running}
- result={result}
- error={error}
- >
- {/* Model select */}
- <div>
- <label className="block text-xs text-text-muted mb-1">{t("model")}</label>
- <select
- value={model || firstModel}
- onChange={(e) => setModel(e.target.value)}
- className="w-full rounded-md border border-border bg-bg-subtle text-sm px-2 py-1.5 text-text-main focus:outline-none focus:ring-1 focus:ring-primary"
- >
- {modelOptions.map((m) => (
- <option key={m.id} value={m.id}>
- {m.id}
- </option>
- ))}
- </select>
- </div>
- {/* Document URL */}
- <div>
- <label className="block text-xs text-text-muted mb-1">Document URL</label>
- <input
- type="text"
- value={documentUrl}
- onChange={(e) => setDocumentUrl(e.target.value)}
- placeholder={SAMPLE_DOCUMENT_URL}
- className="w-full rounded-md border border-border bg-bg-subtle text-sm px-2 py-1.5 text-text-main focus:outline-none focus:ring-1 focus:ring-primary"
- />
- </div>
- </PlaygroundCard>
- );
-}
diff --git a/src/app/(dashboard)/dashboard/media-providers/components/ServiceKindTabs.tsx b/src/app/(dashboard)/dashboard/media-providers/components/ServiceKindTabs.tsx
index 2e54dd4841..bcd50300e4 100644
--- a/src/app/(dashboard)/dashboard/media-providers/components/ServiceKindTabs.tsx
+++ b/src/app/(dashboard)/dashboard/media-providers/components/ServiceKindTabs.tsx
@@ -15,7 +15,6 @@ const KIND_ICON: Record<ServiceKind, string> = {
webFetch: "language",
video: "videocam",
music: "music_note",
- ocr: "document_scanner",
};
interface ServiceKindTabsProps {
diff --git a/src/app/(dashboard)/dashboard/media-providers/components/mediaKinds.ts b/src/app/(dashboard)/dashboard/media-providers/components/mediaKinds.ts
index 05b5586e34..a3ded4173e 100644
--- a/src/app/(dashboard)/dashboard/media-providers/components/mediaKinds.ts
+++ b/src/app/(dashboard)/dashboard/media-providers/components/mediaKinds.ts
@@ -7,8 +7,7 @@ export type MediaKind =
| "webSearch"
| "webFetch"
| "video"
- | "music"
- | "ocr";
+ | "music";
export const MEDIA_KINDS: MediaKind[] = [
"embedding",
@@ -20,5 +19,4 @@ export const MEDIA_KINDS: MediaKind[] = [
"webFetch",
"video",
"music",
- "ocr",
];
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/components/CompatibleNodeCard.tsx b/src/app/(dashboard)/dashboard/providers/[id]/components/CompatibleNodeCard.tsx
index 5347c075a8..1b01f2eb7d 100644
--- a/src/app/(dashboard)/dashboard/providers/[id]/components/CompatibleNodeCard.tsx
+++ b/src/app/(dashboard)/dashboard/providers/[id]/components/CompatibleNodeCard.tsx
@@ -3,7 +3,6 @@
// Phase 1t.2 extraction — Issue #3501
import { useRouter } from "next/navigation";
import { Card, Button } from "@/shared/components";
-import ProviderIcon from "@/shared/components/ProviderIcon";
import { getApiLabel, getApiPath } from "../providerPageHelpers";
import type { ProviderMessageTranslator } from "../providerPageHelpers";
@@ -12,8 +11,6 @@ interface ProviderNode {
apiType?: string;
chatPath?: string;
prefix?: string;
- /** Optional operator-supplied remote icon URL (#2166). */
- iconUrl?: string;
[key: string]: unknown;
}
@@ -45,35 +42,24 @@ export default function CompatibleNodeCard({
return (
<Card>
<div className="mb-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
- <div className="flex items-center gap-3">
- {providerNode.iconUrl && (
- <ProviderIcon
- providerId={providerId}
- src={providerNode.iconUrl}
- size={32}
- className="shrink-0 rounded-lg"
- fallbackText={isCcCompatible ? "CC" : isAnthropicCompatible ? "AC" : "OC"}
- />
- )}
- <div>
- <h2 className="text-lg font-semibold">
- {isCcCompatible
- ? t("ccCompatibleDetailsTitle")
- : isAnthropicCompatible
- ? t("anthropicCompatibleDetails")
- : t("openaiCompatibleDetails")}
- </h2>
- <p className="text-sm text-text-muted">
- {getApiLabel(t, isAnthropicProtocolCompatible, providerNode?.apiType)} ·{" "}
- {(providerNode.baseUrl || "").replace(/\/$/, "")}/
- {getApiPath(
- isCcCompatible,
- isAnthropicCompatible,
- providerNode?.apiType,
- providerNode?.chatPath
- )}
- </p>
- </div>
+ <div>
+ <h2 className="text-lg font-semibold">
+ {isCcCompatible
+ ? t("ccCompatibleDetailsTitle")
+ : isAnthropicCompatible
+ ? t("anthropicCompatibleDetails")
+ : t("openaiCompatibleDetails")}
+ </h2>
+ <p className="text-sm text-text-muted">
+ {getApiLabel(t, isAnthropicProtocolCompatible, providerNode?.apiType)} ·{" "}
+ {(providerNode.baseUrl || "").replace(/\/$/, "")}/
+ {getApiPath(
+ isCcCompatible,
+ isAnthropicCompatible,
+ providerNode?.apiType,
+ providerNode?.chatPath
+ )}
+ </p>
</div>
<div className="flex flex-wrap items-center gap-2">
<Button size="sm" icon="add" onClick={() => gateConnectionFlow(openApiKeyAddFlow)}>
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/components/ProviderPageHeader.tsx b/src/app/(dashboard)/dashboard/providers/[id]/components/ProviderPageHeader.tsx
index fda56087f8..4e3abaebe6 100644
--- a/src/app/(dashboard)/dashboard/providers/[id]/components/ProviderPageHeader.tsx
+++ b/src/app/(dashboard)/dashboard/providers/[id]/components/ProviderPageHeader.tsx
@@ -12,10 +12,6 @@ interface ProviderInfo {
website?: string;
color: string;
apiType?: string;
- /** Optional operator-supplied remote icon URL (#2166) for compatible provider nodes. */
- iconUrl?: string;
- /** Short text-badge fallback (e.g. "OC"/"AC"/"CC") shown if `iconUrl` fails to load. */
- textIcon?: string;
}
interface ProviderPageHeaderProps {
@@ -60,10 +56,6 @@ export default function ProviderPageHeader({
)}
size={48}
type="color"
- src={providerInfo.iconUrl}
- alt={providerInfo.name}
- fallbackText={providerInfo.textIcon}
- fallbackColor={providerInfo.color}
/>
</div>
<div>
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/components/modals/EditCompatibleNodeModal.tsx b/src/app/(dashboard)/dashboard/providers/[id]/components/modals/EditCompatibleNodeModal.tsx
index ec0f1fcdf7..049797e4df 100644
--- a/src/app/(dashboard)/dashboard/providers/[id]/components/modals/EditCompatibleNodeModal.tsx
+++ b/src/app/(dashboard)/dashboard/providers/[id]/components/modals/EditCompatibleNodeModal.tsx
@@ -11,7 +11,6 @@ interface EditCompatibleNodeModalNode {
baseUrl?: string;
chatPath?: string;
modelsPath?: string;
- iconUrl?: string;
}
interface EditCompatibleNodeModalProps {
@@ -39,7 +38,6 @@ export default function EditCompatibleNodeModal({
baseUrl: "https://api.openai.com/v1",
chatPath: "",
modelsPath: "",
- iconUrl: "",
});
const [saving, setSaving] = useState(false);
const [checkKey, setCheckKey] = useState("");
@@ -65,7 +63,6 @@ export default function EditCompatibleNodeModal({
: "https://api.openai.com/v1"),
chatPath: node.chatPath || (isCcCompatible ? CC_COMPATIBLE_DEFAULT_CHAT_PATH : ""),
modelsPath: isCcCompatible ? "" : node.modelsPath || "",
- iconUrl: node.iconUrl || "",
});
setShowAdvanced(
!!(
@@ -96,7 +93,6 @@ export default function EditCompatibleNodeModal({
baseUrl: formData.baseUrl,
chatPath: formData.chatPath || (isCcCompatible ? CC_COMPATIBLE_DEFAULT_CHAT_PATH : ""),
modelsPath: isCcCompatible ? "" : formData.modelsPath,
- iconUrl: formData.iconUrl.trim(),
};
if (!isAnthropic) {
payload.apiType = formData.apiType;
@@ -212,13 +208,6 @@ export default function EditCompatibleNodeModal({
})
}
/>
- <Input
- label={t("iconUrlLabel")}
- value={formData.iconUrl}
- onChange={(e) => setFormData({ ...formData, iconUrl: e.target.value })}
- placeholder="https://example.com/logo.png"
- hint={t("iconUrlHint")}
- />
<button
type="button"
className="text-sm text-text-muted hover:text-text-primary flex items-center gap-1"
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/components/modals/EditConnectionModal.tsx b/src/app/(dashboard)/dashboard/providers/[id]/components/modals/EditConnectionModal.tsx
index d4a7d3ea6c..bb58cc06e7 100644
--- a/src/app/(dashboard)/dashboard/providers/[id]/components/modals/EditConnectionModal.tsx
+++ b/src/app/(dashboard)/dashboard/providers/[id]/components/modals/EditConnectionModal.tsx
@@ -164,7 +164,8 @@ export default function EditConnectionModal({
const setOpenRouterPreset = openRouterPreset.setValue;
const isCodex = provider === "codex";
const isClaude = provider === "claude";
- const isAntigravityFamily = provider === "antigravity" || provider === "agy";
+ const isAntigravity = provider === "antigravity";
+ const supportsGoogleProjectId = isAntigravity;
const localProviderMetadata = getLocalProviderMetadata(provider);
const isLocalSelfHostedProvider = !!localProviderMetadata;
const isGooglePse = provider === "google-pse-search";
@@ -430,7 +431,7 @@ export default function EditConnectionModal({
overrides.maxConcurrent = Number(formData.rateLimitMaxConcurrent);
updates.rateLimitOverrides = Object.keys(overrides).length > 0 ? overrides : null;
- if (isAntigravityFamily) {
+ if (supportsGoogleProjectId) {
updates.projectId = trimmedCloudCodeProjectId || null;
}
@@ -504,7 +505,7 @@ export default function EditConnectionModal({
defaultRegion,
isGlm,
isCloudflare,
- isAntigravityFamily,
+ supportsGoogleProjectId,
trimmedCloudCodeProjectId,
isGooglePse,
isCcCompatible,
@@ -529,11 +530,11 @@ export default function EditConnectionModal({
updates.providerSpecificData.openaiStoreEnabled =
formData.codexOpenaiStoreEnabled === true;
}
- if (isAntigravityFamily) {
+ if (supportsGoogleProjectId) {
updates.providerSpecificData.projectId = trimmedCloudCodeProjectId || null;
}
}
- if (isAntigravityFamily) {
+ if (isAntigravity) {
updates.providerSpecificData = {
...(connection.providerSpecificData || {}),
...(updates.providerSpecificData || {}),
@@ -684,20 +685,22 @@ export default function EditConnectionModal({
t={t}
editMode
/>
- {isAntigravityFamily && (
+ {supportsGoogleProjectId && (
<div className="flex flex-col gap-4 rounded-lg border border-border/50 bg-surface/20 p-4">
- <Select
- label={t("antigravityClientProfileLabel")}
- value={formData.antigravityClientProfile}
- options={ANTIGRAVITY_CLIENT_PROFILE_OPTIONS.map((option) => ({
- value: option.value,
- label: t(option.labelKey),
- }))}
- onChange={(e) =>
- setFormData({ ...formData, antigravityClientProfile: e.target.value })
- }
- hint={t("antigravityClientProfileHint")}
- />
+ {isAntigravity && (
+ <Select
+ label={t("antigravityClientProfileLabel")}
+ value={formData.antigravityClientProfile}
+ options={ANTIGRAVITY_CLIENT_PROFILE_OPTIONS.map((option) => ({
+ value: option.value,
+ label: t(option.labelKey),
+ }))}
+ onChange={(e) =>
+ setFormData({ ...formData, antigravityClientProfile: e.target.value })
+ }
+ hint={t("antigravityClientProfileHint")}
+ />
+ )}
<Input
label={t("antigravityProjectIdLabel")}
value={formData.cloudCodeProjectId}
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/components/modals/connectionProviderSpecificData.ts b/src/app/(dashboard)/dashboard/providers/[id]/components/modals/connectionProviderSpecificData.ts
index 53ea1b7947..654593ed6c 100644
--- a/src/app/(dashboard)/dashboard/providers/[id]/components/modals/connectionProviderSpecificData.ts
+++ b/src/app/(dashboard)/dashboard/providers/[id]/components/modals/connectionProviderSpecificData.ts
@@ -89,7 +89,7 @@ export function assignEditApiKeyProviderSpecificData(options: {
defaultRegion: string;
isGlm: boolean;
isCloudflare: boolean;
- isAntigravityFamily: boolean;
+ supportsGoogleProjectId: boolean;
trimmedCloudCodeProjectId: string;
isGooglePse: boolean;
isCcCompatible: boolean;
@@ -116,7 +116,7 @@ export function assignEditApiKeyProviderSpecificData(options: {
else if (o.isCloudflare && o.formData.accountId.trim()) {
o.target.accountId = o.formData.accountId.trim();
}
- if (o.isAntigravityFamily) o.target.projectId = o.trimmedCloudCodeProjectId || null;
+ if (o.supportsGoogleProjectId) o.target.projectId = o.trimmedCloudCodeProjectId || null;
if (o.isCcCompatible) {
o.target.requestDefaults = mergeCcCompatibleRequestDefaults(
o.target.requestDefaults,
diff --git a/src/app/(dashboard)/dashboard/providers/components/AddCompatibleProviderModal.tsx b/src/app/(dashboard)/dashboard/providers/components/AddCompatibleProviderModal.tsx
index ee107c63b6..5eecba769e 100644
--- a/src/app/(dashboard)/dashboard/providers/components/AddCompatibleProviderModal.tsx
+++ b/src/app/(dashboard)/dashboard/providers/components/AddCompatibleProviderModal.tsx
@@ -4,10 +4,6 @@ import { useEffect, useMemo, useState } from "react";
import { useTranslations } from "next-intl";
import { Badge, Button, Input, Modal, Select } from "@/shared/components";
-import {
- CLIENT_IDENTITY_PROFILE_OPTIONS,
- getClientIdentityProfileHeaders,
-} from "@/shared/constants/clientIdentityProfiles";
type CompatibleMode = "openai" | "anthropic" | "cc";
type CompatibleProviderNode = { id: string } & Record<string, unknown>;
@@ -27,8 +23,6 @@ interface CompatibleFormState {
baseUrl: string;
chatPath: string;
modelsPath: string;
- iconUrl: string;
- clientIdentityProfile: string;
}
const CC_DEFAULT_CHAT_PATH = "/v1/messages?beta=true";
@@ -81,8 +75,6 @@ function createInitialForm(mode: CompatibleMode): CompatibleFormState {
baseUrl: defaults.baseUrl,
chatPath: defaults.chatPath,
modelsPath: "",
- iconUrl: "",
- clientIdentityProfile: "default",
};
}
@@ -189,13 +181,6 @@ export default function AddCompatibleProviderModal({
if (defaults.hasApiType) body.apiType = formData.apiType;
if (defaults.hasModelsPath) body.modelsPath = formData.modelsPath || "";
if (defaults.compatMode) body.compatMode = defaults.compatMode;
- body.iconUrl = formData.iconUrl.trim();
- // Merge the selected identity profile's preset headers into the SAME
- // `customHeaders` field the node already persists (see
- // src/lib/db/providers/nodes.ts + open-sse/executors/default.ts
- // `applyCustomHeaders`) — no separate profile field, no new pipeline.
- const identityHeaders = getClientIdentityProfileHeaders(formData.clientIdentityProfile);
- if (Object.keys(identityHeaders).length > 0) body.customHeaders = identityHeaders;
const res = await fetch("/api/provider-nodes", {
method: "POST",
@@ -291,13 +276,6 @@ export default function AddCompatibleProviderModal({
placeholder={baseUrlPlaceholder}
hint={baseUrlHint}
/>
- <Input
- label={t("iconUrlLabel")}
- value={formData.iconUrl}
- onChange={(e) => setFormData({ ...formData, iconUrl: e.target.value })}
- placeholder="https://example.com/logo.png"
- hint={t("iconUrlHint")}
- />
<button
type="button"
@@ -332,13 +310,6 @@ export default function AddCompatibleProviderModal({
hint={t("modelsPathHint")}
/>
)}
- <Select
- label={t("clientIdentityLabel")}
- options={CLIENT_IDENTITY_PROFILE_OPTIONS.map((option) => ({ ...option }))}
- value={formData.clientIdentityProfile}
- onChange={(e) => setFormData({ ...formData, clientIdentityProfile: e.target.value })}
- hint={t("clientIdentityHint")}
- />
</div>
)}
diff --git a/src/app/(dashboard)/dashboard/providers/components/ProviderCard.tsx b/src/app/(dashboard)/dashboard/providers/components/ProviderCard.tsx
index 23a990abf5..9a9256b9e7 100644
--- a/src/app/(dashboard)/dashboard/providers/components/ProviderCard.tsx
+++ b/src/app/(dashboard)/dashboard/providers/components/ProviderCard.tsx
@@ -56,10 +56,6 @@ interface ProviderCardProps {
subscriptionRisk?: boolean;
/** Declared service kinds — "llm" enables the inline Test button */
serviceKinds?: string[];
- /** Optional operator-supplied remote icon URL (#2166) for compatible provider nodes. */
- iconUrl?: string;
- /** Short text-badge fallback (e.g. "OC"/"AC"/"CC") shown if `iconUrl` fails to load. */
- textIcon?: string;
};
stats: ProviderStats;
authType?: string;
@@ -244,17 +240,7 @@ export default function ProviderCard({
className="size-9 rounded-lg flex items-center justify-center shrink-0"
style={{ backgroundColor: `${provider.color || "#64748b"}15` }}
>
- {provider.iconUrl ? (
- <ProviderIcon
- providerId={provider.id || providerId}
- src={provider.iconUrl}
- alt={provider.name}
- size={26}
- className="max-h-[26px] max-w-[26px] rounded-lg object-contain"
- fallbackText={provider.textIcon}
- fallbackColor={provider.color}
- />
- ) : staticIconPath ? (
+ {staticIconPath ? (
<Image
src={staticIconPath}
alt={provider.name}
diff --git a/src/app/(dashboard)/dashboard/providers/page.tsx b/src/app/(dashboard)/dashboard/providers/page.tsx
index 112e46fa47..466b3e53d3 100644
--- a/src/app/(dashboard)/dashboard/providers/page.tsx
+++ b/src/app/(dashboard)/dashboard/providers/page.tsx
@@ -20,7 +20,6 @@ import { useTranslations } from "next-intl";
import {
buildStaticProviderEntries,
buildCompatibleProviderGroups,
- connectionMatchesProviderCard,
filterConfiguredProviderEntries,
shouldFilterProviderEntriesForDisplayMode,
shouldShowFirstProviderHint,
@@ -327,9 +326,11 @@ export default function ProvidersPage() {
};
const getProviderStats = (providerId, authType) => {
- const providerConnections = connections.filter((c) =>
- connectionMatchesProviderCard(c, providerId, authType)
- );
+ const providerConnections = connections.filter((c) => {
+ if (c.provider !== providerId) return false;
+ if (authType === "free") return true;
+ return c.authType === authType;
+ });
// Helper: check if connection is effectively active (cooldown expired)
const getEffectiveStatus = (conn) => {
@@ -392,7 +393,8 @@ export default function ProvidersPage() {
// Count API keys in "warning" state across all connections
const warning = providerConnections.reduce((warnCount, conn) => {
const health = (conn as any).providerSpecificData?.apiKeyHealth as
- Record<string, { status: string }> | undefined;
+ | Record<string, { status: string }>
+ | undefined;
if (!health) return warnCount;
return warnCount + Object.values(health).filter((h) => h.status === "warning").length;
}, 0);
@@ -412,14 +414,18 @@ export default function ProvidersPage() {
// Toggle all connections for a provider on/off
const handleToggleProvider = async (providerId: string, authType: string, newActive: boolean) => {
- // Mirror getProviderStats: dual-auth providers (qoder, …) toggle BOTH their
- // oauth and apikey/PAT connections from the single OAuth card.
- const matchesToggle = (c: { provider: string; authType?: string }) =>
- connectionMatchesProviderCard(c, providerId, authType as "oauth" | "free" | "apikey");
- const providerConns = connections.filter(matchesToggle);
+ const providerConns = connections.filter((c) => {
+ if (c.provider !== providerId) return false;
+ if (authType === "free") return true;
+ return c.authType === authType;
+ });
// Optimistically update UI
setConnections((prev) =>
- prev.map((c) => (matchesToggle(c) ? { ...c, isActive: newActive } : c))
+ prev.map((c) =>
+ c.provider === providerId && (authType === "free" || c.authType === authType)
+ ? { ...c, isActive: newActive }
+ : c
+ )
);
// Fire API calls in parallel
await Promise.allSettled(
diff --git a/src/app/(dashboard)/dashboard/providers/providerPageUtils.ts b/src/app/(dashboard)/dashboard/providers/providerPageUtils.ts
index f1ea2cc66f..72184b1769 100644
--- a/src/app/(dashboard)/dashboard/providers/providerPageUtils.ts
+++ b/src/app/(dashboard)/dashboard/providers/providerPageUtils.ts
@@ -7,10 +7,7 @@ import {
type ResolvedProviderCatalogEntry,
type StaticProviderCatalogCategory,
} from "@/lib/providers/catalog";
-import {
- isClaudeCodeCompatibleProvider,
- supportsApiKeyOnFreeProvider,
-} from "@/shared/constants/providers";
+import { isClaudeCodeCompatibleProvider } from "@/shared/constants/providers";
import { getModelsByProviderId } from "@/shared/constants/models";
import { providerHasServiceKind } from "@/lib/providers/serviceKindIndex";
import { compareTr, matchesSearch } from "@/shared/utils/turkishText";
@@ -35,8 +32,6 @@ export type CompatibleProviderInfo = {
color: string;
textIcon: string;
apiType?: string;
- /** Optional operator-supplied remote icon URL (#2166). */
- iconUrl?: string;
};
export type CompatibleProviderGroups = {
@@ -70,26 +65,6 @@ export function shouldShowFirstProviderHint(
type ProviderRecord<TProvider = Record<string, unknown>> = Record<string, TProvider>;
-/**
- * Whether a provider connection should be counted on a provider card rendered in
- * the given section. Dual-auth providers (qoder, opencode, codebuddy-cn, …) are
- * OAuth-categorized but also accept a PAT/API key stored as authType "apikey";
- * their single OAuth card must count BOTH, else a working PAT connection shows as
- * "not connected" on the dashboard.
- */
-export function connectionMatchesProviderCard(
- conn: { provider?: string; authType?: string } | null | undefined,
- providerId: string,
- cardAuthType: "oauth" | "free" | "apikey"
-): boolean {
- if (!conn || conn.provider !== providerId) return false;
- if (cardAuthType === "free") return true;
- if (supportsApiKeyOnFreeProvider(providerId)) {
- return conn.authType === "oauth" || conn.authType === "apikey";
- }
- return conn.authType === cardAuthType;
-}
-
type GetProviderStats = (
providerId: string,
authType: "oauth" | "free" | "apikey"
@@ -151,13 +126,7 @@ export function buildStaticProviderEntries(
}
export function buildCompatibleProviderGroups(
- providerNodes: Array<{
- id: string;
- name?: string;
- type?: string;
- apiType?: string;
- iconUrl?: string | null;
- }>,
+ providerNodes: Array<{ id: string; name?: string; type?: string; apiType?: string }>,
labels: {
openaiCompatibleName: string;
anthropicCompatibleName: string;
@@ -176,7 +145,6 @@ export function buildCompatibleProviderGroups(
color: "#10A37F",
textIcon: "OC",
apiType: node.apiType,
- iconUrl: node.iconUrl || undefined,
});
continue;
}
@@ -189,7 +157,6 @@ export function buildCompatibleProviderGroups(
name: node.name || labels.claudeCodeCompatibleName,
color: "#B45309",
textIcon: "CC",
- iconUrl: node.iconUrl || undefined,
});
continue;
}
@@ -199,7 +166,6 @@ export function buildCompatibleProviderGroups(
name: node.name || labels.anthropicCompatibleName,
color: "#D97757",
textIcon: "AC",
- iconUrl: node.iconUrl || undefined,
});
}
diff --git a/src/app/(dashboard)/dashboard/providers/services/page.tsx b/src/app/(dashboard)/dashboard/providers/services/page.tsx
index 8cc5a09443..ab18dad077 100644
--- a/src/app/(dashboard)/dashboard/providers/services/page.tsx
+++ b/src/app/(dashboard)/dashboard/providers/services/page.tsx
@@ -4,16 +4,12 @@ import { useSearchParams, useRouter } from "next/navigation";
import { cn } from "@/shared/utils/cn";
import { CliproxyServiceTab } from "./tabs/CliproxyServiceTab";
import { NinerouterServiceTab } from "./tabs/NinerouterServiceTab";
-import { MuxServiceTab } from "./tabs/MuxServiceTab";
-import { BifrostServiceTab } from "./tabs/BifrostServiceTab";
-type Tab = "cliproxy" | "9router" | "mux" | "bifrost";
+type Tab = "cliproxy" | "9router";
const TABS: { id: Tab; label: string; icon: string }[] = [
{ id: "cliproxy", label: "CLIProxyAPI", icon: "swap_horiz" },
{ id: "9router", label: "9Router", icon: "route" },
- { id: "mux", label: "Mux", icon: "hub" },
- { id: "bifrost", label: "Bifrost", icon: "bolt" },
];
export default function ServicesPage() {
@@ -30,8 +26,7 @@ export default function ServicesPage() {
<header>
<h1 className="text-xl font-semibold text-text-primary">Embedded Services</h1>
<p className="text-sm text-text-muted mt-1">
- External engines managed on demand — CLIProxyAPI, 9Router, Mux, and Bifrost. Accessible on
- loopback only.
+ External engines managed on demand — CLIProxyAPI and 9Router. Accessible on loopback only.
</p>
</header>
@@ -60,8 +55,6 @@ export default function ServicesPage() {
<div>
{active === "cliproxy" && <CliproxyServiceTab />}
{active === "9router" && <NinerouterServiceTab />}
- {active === "mux" && <MuxServiceTab />}
- {active === "bifrost" && <BifrostServiceTab />}
</div>
</div>
);
diff --git a/src/app/(dashboard)/dashboard/providers/services/tabs/BifrostServiceTab.tsx b/src/app/(dashboard)/dashboard/providers/services/tabs/BifrostServiceTab.tsx
deleted file mode 100644
index fd4f474c79..0000000000
--- a/src/app/(dashboard)/dashboard/providers/services/tabs/BifrostServiceTab.tsx
+++ /dev/null
@@ -1,22 +0,0 @@
-"use client";
-
-import { ServiceStatusCard } from "../components/ServiceStatusCard";
-import { ServiceLifecycleButtons } from "../components/ServiceLifecycleButtons";
-import { ServiceLogsPanel } from "../components/ServiceLogsPanel";
-import { AutoStartToggle } from "../components/AutoStartToggle";
-
-const NAME = "bifrost";
-
-export function BifrostServiceTab() {
- return (
- <div className="space-y-4">
- <ServiceStatusCard name={NAME} />
- <ServiceLifecycleButtons name={NAME} />
- <AutoStartToggle
- name={NAME}
- description="Launch Bifrost automatically when OmniRoute starts"
- />
- <ServiceLogsPanel name={NAME} />
- </div>
- );
-}
diff --git a/src/app/(dashboard)/dashboard/providers/services/tabs/MuxServiceTab.tsx b/src/app/(dashboard)/dashboard/providers/services/tabs/MuxServiceTab.tsx
deleted file mode 100644
index a51dc07e81..0000000000
--- a/src/app/(dashboard)/dashboard/providers/services/tabs/MuxServiceTab.tsx
+++ /dev/null
@@ -1,19 +0,0 @@
-"use client";
-
-import { ServiceStatusCard } from "../components/ServiceStatusCard";
-import { ServiceLifecycleButtons } from "../components/ServiceLifecycleButtons";
-import { ServiceLogsPanel } from "../components/ServiceLogsPanel";
-import { AutoStartToggle } from "../components/AutoStartToggle";
-
-const NAME = "mux";
-
-export function MuxServiceTab() {
- return (
- <div className="space-y-4">
- <ServiceStatusCard name={NAME} />
- <ServiceLifecycleButtons name={NAME} />
- <AutoStartToggle name={NAME} description="Launch Mux automatically when OmniRoute starts" />
- <ServiceLogsPanel name={NAME} />
- </div>
- );
-}
diff --git a/src/app/(dashboard)/dashboard/settings/advanced/page.tsx b/src/app/(dashboard)/dashboard/settings/advanced/page.tsx
index 5dfefd170b..803fbfe47c 100644
--- a/src/app/(dashboard)/dashboard/settings/advanced/page.tsx
+++ b/src/app/(dashboard)/dashboard/settings/advanced/page.tsx
@@ -1,7 +1,6 @@
"use client";
import DebugModeCard from "../components/DebugModeCard";
-import LogToolSourcesCard from "../components/LogToolSourcesCard";
import PayloadRulesTab from "../components/PayloadRulesTab";
import RequestLimitsTab from "../components/RequestLimitsTab";
import CliproxyapiSettingsTab from "../components/CliproxyapiSettingsTab";
@@ -10,7 +9,6 @@ export default function SettingsAdvancedPage() {
return (
<div className="space-y-6">
<DebugModeCard />
- <LogToolSourcesCard />
<PayloadRulesTab />
<RequestLimitsTab />
<CliproxyapiSettingsTab />
diff --git a/src/app/(dashboard)/dashboard/settings/components/AuthzSection.tsx b/src/app/(dashboard)/dashboard/settings/components/AuthzSection.tsx
index a77d252c44..1c38ced0a4 100644
--- a/src/app/(dashboard)/dashboard/settings/components/AuthzSection.tsx
+++ b/src/app/(dashboard)/dashboard/settings/components/AuthzSection.tsx
@@ -13,17 +13,11 @@ interface TierEntry {
bypassable: boolean;
}
-interface CorsStatus {
- allowAll: boolean;
- allowedOrigins: string[];
-}
-
interface InventoryPayload {
tiers: TierEntry[];
bypassEnabled: boolean;
bypassPrefixes: string[];
spawnCapablePrefixes: string[];
- cors?: CorsStatus;
}
interface StatusMessage {
@@ -247,24 +241,6 @@ export default function AuthzSection() {
return (
<>
- {/* #5602: persistent wildcard-CORS warning — only visible while
- CORS_ALLOW_ALL=true is live. See docs/security/CORS.md. */}
- {inventory.cors?.allowAll && (
- <div
- data-testid="cors-wildcard-banner"
- role="alert"
- className="flex items-start gap-3 rounded-lg border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-amber-700 dark:text-amber-300"
- >
- <span className="material-symbols-outlined text-[20px] mt-0.5" aria-hidden="true">
- warning
- </span>
- <div className="flex flex-col gap-1">
- <p className="font-semibold">{t("authz.cors.wildcard.title")}</p>
- <p className="text-sm">{t("authz.cors.wildcard.desc")}</p>
- </div>
- </div>
- )}
-
{/* Bypass policy editor */}
<Card>
<div className="flex items-center gap-3 mb-4">
diff --git a/src/app/(dashboard)/dashboard/settings/components/LogToolSourcesCard.tsx b/src/app/(dashboard)/dashboard/settings/components/LogToolSourcesCard.tsx
deleted file mode 100644
index d64575e993..0000000000
--- a/src/app/(dashboard)/dashboard/settings/components/LogToolSourcesCard.tsx
+++ /dev/null
@@ -1,70 +0,0 @@
-"use client";
-
-import { useEffect, useState } from "react";
-import { Card, Toggle } from "@/shared/components";
-import { useTranslations } from "next-intl";
-
-export default function LogToolSourcesCard() {
- const [logToolSources, setLogToolSources] = useState(false);
- const [loading, setLoading] = useState(true);
- const t = useTranslations("settings");
-
- useEffect(() => {
- let mounted = true;
-
- async function loadSettings() {
- setLoading(true);
- try {
- const res = await fetch("/api/settings", { cache: "no-store" });
- if (res.ok && mounted) {
- const data = await res.json();
- setLogToolSources(data.logToolSources === true);
- }
- } catch {
- // Leave the current switch state in place if settings cannot be loaded.
- } finally {
- if (mounted) setLoading(false);
- }
- }
-
- loadSettings();
- return () => {
- mounted = false;
- };
- }, []);
-
- const updateLogToolSources = async (value: boolean) => {
- const previousValue = logToolSources;
- setLogToolSources(value);
- try {
- const res = await fetch("/api/settings", {
- method: "PATCH",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ logToolSources: value }),
- });
- if (!res.ok) setLogToolSources(previousValue);
- } catch (err) {
- setLogToolSources(previousValue);
- console.error("Failed to update logToolSources:", err);
- }
- };
-
- return (
- <Card>
- <div className="flex items-center justify-between gap-4">
- <div className="flex items-center gap-3">
- <div className="p-2 rounded-lg bg-primary/10 text-primary">
- <span className="material-symbols-outlined text-[20px]" aria-hidden="true">
- troubleshoot
- </span>
- </div>
- <div>
- <h3 className="text-lg font-semibold">{t("logToolSourcesToggle")}</h3>
- <p className="text-sm text-muted-foreground">{t("logToolSourcesDescription")}</p>
- </div>
- </div>
- <Toggle checked={logToolSources} onChange={updateLogToolSources} disabled={loading} />
- </div>
- </Card>
- );
-}
diff --git a/src/app/(dashboard)/dashboard/settings/components/ProxyBatchActions.tsx b/src/app/(dashboard)/dashboard/settings/components/ProxyBatchActions.tsx
deleted file mode 100644
index a9e537a884..0000000000
--- a/src/app/(dashboard)/dashboard/settings/components/ProxyBatchActions.tsx
+++ /dev/null
@@ -1,55 +0,0 @@
-"use client";
-
-import { useTranslations } from "next-intl";
-import { Button } from "@/shared/components";
-
-interface ProxyBatchActionsProps {
- selectedCount: number;
- batchDeleting: boolean;
- autoTesting: boolean;
- onBatchDelete: () => void;
- onAutoTestAll: () => void;
-}
-
-export function ProxyBatchActions({
- selectedCount,
- batchDeleting,
- autoTesting,
- onBatchDelete,
- onAutoTestAll,
-}: ProxyBatchActionsProps) {
- const t = useTranslations("proxyRegistry");
-
- return (
- <>
- {selectedCount > 0 && (
- <>
- <span className="text-xs text-text-muted">
- {t("batchSelectedCount", { count: selectedCount })}
- </span>
- <Button
- size="sm"
- variant="secondary"
- icon="delete"
- onClick={onBatchDelete}
- loading={batchDeleting}
- className="!text-red-400 !border-red-500/30"
- data-testid="proxy-registry-batch-delete"
- >
- {t("batchDeleteSelected", { count: selectedCount })}
- </Button>
- </>
- )}
- <Button
- size="sm"
- variant="secondary"
- icon="network_check"
- onClick={onAutoTestAll}
- loading={autoTesting}
- data-testid="proxy-registry-test-all"
- >
- {t("testAll")}
- </Button>
- </>
- );
-}
diff --git a/src/app/(dashboard)/dashboard/settings/components/ProxyBulkImportModal.tsx b/src/app/(dashboard)/dashboard/settings/components/ProxyBulkImportModal.tsx
deleted file mode 100644
index 59e9b8526b..0000000000
--- a/src/app/(dashboard)/dashboard/settings/components/ProxyBulkImportModal.tsx
+++ /dev/null
@@ -1,226 +0,0 @@
-"use client";
-
-import { useState } from "react";
-import { useTranslations } from "next-intl";
-import { Button, Modal } from "@/shared/components";
-
-type ParsedProxyEntry = {
- name: string;
- type: string;
- host: string;
- port: number;
- username?: string;
- region?: string;
- status: string;
-};
-
-type ParseError = { line: number; reason: string };
-
-interface ProxyBulkImportModalProps {
- isOpen: boolean;
- onClose: () => void;
- onImported: () => Promise<void>;
-}
-
-const BULK_IMPORT_TEMPLATE = `# Proxy Bulk Import
-# Format: name | type | host | port | username | region | status
-# Example:
-# My Proxy | http | 1.2.3.4 | 8080 | user | US | active
-`;
-
-function parseBulkImportText(text: string): {
- parsed: ParsedProxyEntry[];
- errors: ParseError[];
- skipped: number;
-} {
- const lines = text.split("\n");
- const parsed: ParsedProxyEntry[] = [];
- const errors: ParseError[] = [];
- let skipped = 0;
-
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i].trim();
- if (!line || line.startsWith("#")) {
- skipped++;
- continue;
- }
- const parts = line.split("|").map((p) => p.trim());
- if (parts.length < 4) {
- errors.push({ line: i + 1, reason: "bulkImportMinFields" });
- continue;
- }
- const [name, type, host, portStr, username, region, status] = parts;
- const port = parseInt(portStr, 10);
- if (!Number.isFinite(port) || port < 1 || port > 65535) {
- errors.push({ line: i + 1, reason: "bulkImportInvalidPort" });
- continue;
- }
- parsed.push({
- name: name || `${host}:${port}`,
- type: ["http", "https", "socks5"].includes(type) ? type : "http",
- host,
- port,
- username: username || undefined,
- region: region || undefined,
- status: status === "inactive" ? "inactive" : "active",
- });
- }
-
- return { parsed, errors, skipped };
-}
-
-export function ProxyBulkImportModal({ isOpen, onClose, onImported }: ProxyBulkImportModalProps) {
- const t = useTranslations("proxyRegistry");
- const [bulkImportText, setBulkImportText] = useState(BULK_IMPORT_TEMPLATE);
- const [bulkImportParsed, setBulkImportParsed] = useState<ParsedProxyEntry[]>([]);
- const [bulkImportErrors, setBulkImportErrors] = useState<ParseError[]>([]);
- const [bulkImportSkipped, setBulkImportSkipped] = useState(0);
- const [bulkImportParsedOnce, setBulkImportParsedOnce] = useState(false);
- const [bulkImporting, setBulkImporting] = useState(false);
- const [bulkImportResult, setBulkImportResult] = useState<{ created: number; updated: number; failed: number } | null>(null);
-
- const handleParse = () => {
- const result = parseBulkImportText(bulkImportText);
- setBulkImportParsed(result.parsed);
- setBulkImportErrors(result.errors);
- setBulkImportSkipped(result.skipped);
- setBulkImportParsedOnce(true);
- setBulkImportResult(null);
- };
-
- const handleExecute = async () => {
- if (bulkImportParsed.length === 0) return;
- setBulkImporting(true);
- try {
- const res = await fetch("/api/settings/proxies/bulk-import", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ items: bulkImportParsed }),
- });
- const data = await res.json().catch(() => ({}));
- if (res.ok) {
- setBulkImportResult(data);
- await onImported();
- }
- } finally {
- setBulkImporting(false);
- }
- };
-
- return (
- <Modal
- isOpen={isOpen}
- onClose={() => {
- if (!bulkImporting) onClose();
- }}
- title={t("bulkImportTitle")}
- maxWidth="xl"
- >
- <div className="flex flex-col gap-4">
- <p className="text-sm text-text-muted">{t("bulkImportDescription")}</p>
-
- <div>
- <textarea
- className="w-full px-3 py-2 rounded bg-bg-subtle border border-border font-mono text-xs leading-relaxed"
- rows={14}
- value={bulkImportText}
- onChange={(e) => {
- setBulkImportText(e.target.value);
- setBulkImportParsedOnce(false);
- setBulkImportResult(null);
- }}
- spellCheck={false}
- />
- </div>
-
- <div className="flex items-center gap-3">
- <Button size="sm" variant="secondary" icon="search" onClick={handleParse}>
- {t("bulkImportParse")}
- </Button>
-
- {bulkImportParsedOnce && (
- <div className="flex items-center gap-3 text-xs">
- <span className="text-emerald-400">{t("bulkImportParsed", { count: bulkImportParsed.length })}</span>
- <span className="text-text-muted">{t("bulkImportSkipped", { count: bulkImportSkipped })}</span>
- {bulkImportErrors.length > 0 && (
- <span className="text-red-400">{t("bulkImportParseErrors", { count: bulkImportErrors.length })}</span>
- )}
- </div>
- )}
- </div>
-
- {bulkImportErrors.length > 0 && (
- <div className="max-h-28 overflow-y-auto rounded border border-red-500/30 bg-red-500/10 p-2">
- {bulkImportErrors.map((err, idx) => (
- <div key={idx} className="text-xs text-red-400">
- {t("bulkImportErrorLine", { line: err.line, reason: t(err.reason as "bulkImportMinFields" | "bulkImportInvalidPort") })}
- </div>
- ))}
- </div>
- )}
-
- {bulkImportParsedOnce && bulkImportParsed.length > 0 && (
- <div className="overflow-x-auto max-h-48 overflow-y-auto rounded border border-border">
- <table className="w-full text-xs">
- <thead>
- <tr className="text-left text-text-muted border-b border-border bg-bg-subtle sticky top-0">
- <th className="py-1.5 px-2">{t("tableName")}</th>
- <th className="py-1.5 px-2">{t("labelType")}</th>
- <th className="py-1.5 px-2">{t("labelHost")}</th>
- <th className="py-1.5 px-2">{t("labelPort")}</th>
- <th className="py-1.5 px-2">{t("labelUsername")}</th>
- <th className="py-1.5 px-2">{t("labelRegion")}</th>
- <th className="py-1.5 px-2">{t("labelStatus")}</th>
- </tr>
- </thead>
- <tbody>
- {bulkImportParsed.map((entry, idx) => (
- <tr key={idx} className="border-b border-border/40">
- <td className="py-1 px-2 font-medium text-text-main">{entry.name}</td>
- <td className="py-1 px-2">
- <span className="px-1.5 py-0.5 rounded bg-bg-subtle border border-border text-[10px]">{entry.type}</span>
- </td>
- <td className="py-1 px-2 font-mono text-text-muted">{entry.host}</td>
- <td className="py-1 px-2 font-mono text-text-muted">{entry.port}</td>
- <td className="py-1 px-2 text-text-muted">{entry.username || "—"}</td>
- <td className="py-1 px-2 text-text-muted">{entry.region || "—"}</td>
- <td className="py-1 px-2">
- <span className={entry.status === "active" ? "text-emerald-400" : "text-text-muted"}>
- {entry.status === "active" ? t("statusActive") : t("statusInactive")}
- </span>
- </td>
- </tr>
- ))}
- </tbody>
- </table>
- </div>
- )}
-
- {bulkImportParsedOnce && bulkImportParsed.length === 0 && bulkImportErrors.length === 0 && (
- <div className="text-sm text-amber-400">{t("bulkImportNoValidEntries")}</div>
- )}
-
- {bulkImportResult && (
- <div className="px-3 py-2 rounded border border-emerald-500/30 bg-emerald-500/10 text-sm text-emerald-400">
- {t("bulkImportSuccess", { created: bulkImportResult.created, updated: bulkImportResult.updated, failed: bulkImportResult.failed })}
- </div>
- )}
-
- <div className="flex items-center justify-end gap-2 pt-2 border-t border-border">
- <Button size="sm" variant="secondary" onClick={onClose}>
- {t("cancel")}
- </Button>
- <Button
- size="sm"
- icon="upload"
- onClick={handleExecute}
- loading={bulkImporting}
- disabled={!bulkImportParsedOnce || bulkImportParsed.length === 0}
- >
- {bulkImporting ? t("bulkImportImporting") : bulkImportParsed.length > 0 ? t("bulkImportImport", { count: bulkImportParsed.length }) : t("bulkImport")}
- </Button>
- </div>
- </div>
- </Modal>
- );
-}
diff --git a/src/app/(dashboard)/dashboard/settings/components/ProxyCheckboxCell.tsx b/src/app/(dashboard)/dashboard/settings/components/ProxyCheckboxCell.tsx
deleted file mode 100644
index 3d20f24331..0000000000
--- a/src/app/(dashboard)/dashboard/settings/components/ProxyCheckboxCell.tsx
+++ /dev/null
@@ -1,21 +0,0 @@
-"use client";
-
-interface ProxyCheckboxCellProps {
- checked: boolean;
- onChange: () => void;
- label: string;
-}
-
-export function ProxyCheckboxCell({ checked, onChange, label }: ProxyCheckboxCellProps) {
- return (
- <td className="py-2 pr-2 w-8">
- <input
- type="checkbox"
- className="accent-blue-500 w-4 h-4 cursor-pointer"
- checked={checked}
- onChange={onChange}
- aria-label={label}
- />
- </td>
- );
-}
diff --git a/src/app/(dashboard)/dashboard/settings/components/ProxyHealthCell.tsx b/src/app/(dashboard)/dashboard/settings/components/ProxyHealthCell.tsx
deleted file mode 100644
index b5908678cc..0000000000
--- a/src/app/(dashboard)/dashboard/settings/components/ProxyHealthCell.tsx
+++ /dev/null
@@ -1,61 +0,0 @@
-"use client";
-
-import { useTranslations } from "next-intl";
-
-interface TestResult {
- success: boolean;
- publicIp?: string;
- latencyMs?: number | null;
- error?: string;
-}
-
-interface HealthInfo {
- successRate?: number;
- avgLatencyMs?: number;
-}
-
-interface ProxyHealthCellProps {
- testResult?: TestResult | null;
- health?: HealthInfo | null;
-}
-
-export function ProxyHealthCell({ testResult, health }: ProxyHealthCellProps) {
- const t = useTranslations("proxyRegistry");
-
- if (testResult) {
- if (testResult.success) {
- return (
- <div className="flex flex-col gap-0.5">
- <span className="text-emerald-400">{t("testPassed")}</span>
- {testResult.latencyMs != null && (
- <span
- className={
- testResult.latencyMs < 1000
- ? "text-emerald-400"
- : testResult.latencyMs < 3000
- ? "text-amber-400"
- : "text-red-400"
- }
- >
- {testResult.latencyMs}ms
- </span>
- )}
- </div>
- );
- }
- return (
- <span className="text-red-400">✗ {testResult.error || t("failed")}</span>
- );
- }
-
- if (health) {
- return (
- <div className="flex flex-col gap-0.5">
- <span>{t("successRate", { rate: health.successRate ?? 0 })}</span>
- <span>{t("avgLatency", { latency: health.avgLatencyMs ?? "-" })}</span>
- </div>
- );
- }
-
- return <span>—</span>;
-}
diff --git a/src/app/(dashboard)/dashboard/settings/components/ProxyRegistryManager.tsx b/src/app/(dashboard)/dashboard/settings/components/ProxyRegistryManager.tsx
index fb6808a2be..8865839d79 100644
--- a/src/app/(dashboard)/dashboard/settings/components/ProxyRegistryManager.tsx
+++ b/src/app/(dashboard)/dashboard/settings/components/ProxyRegistryManager.tsx
@@ -3,11 +3,8 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { useTranslations } from "next-intl";
import { Button, Card, Modal } from "@/shared/components";
-import { useProxyBatchOperations } from "./useProxyBatchOperations";
-import { ProxyStatusBadge } from "./ProxyStatusBadge";
-import { ProxyHealthCell } from "./ProxyHealthCell";
-import { ProxyBatchActions } from "./ProxyBatchActions";
-import { ProxyCheckboxCell } from "./ProxyCheckboxCell";
+import { parseBulkImportText } from "./parseBulkProxyImport.ts";
+import type { ParsedProxyEntry, ParseError } from "./parseBulkProxyImport.ts";
type ProxyItem = {
id: string;
@@ -44,23 +41,6 @@ type TestResult = {
error?: string;
};
-type ParsedProxyEntry = {
- name: string;
- host: string;
- port: number;
- username: string;
- password: string;
- type: string;
- region: string;
- status: string;
- notes: string;
-};
-
-type ParseError = {
- line: number;
- reason: string;
-};
-
const EMPTY_FORM = {
id: "",
name: "",
@@ -76,9 +56,11 @@ const EMPTY_FORM = {
};
const BULK_IMPORT_TEMPLATE = `# Proxy Bulk Import
-# Format: NAME|HOST|PORT|USERNAME|PASSWORD|TYPE|REGION|STATUS|NOTES
-# Required: NAME, HOST, PORT
-# Optional: USERNAME, PASSWORD, TYPE (http|https|socks5, default: socks5), REGION, STATUS (active|inactive, default: active), NOTES
+# Format A (pipe-delimited): NAME|HOST|PORT|USERNAME|PASSWORD|TYPE|REGION|STATUS|NOTES
+# Required: NAME, HOST, PORT
+# Optional: USERNAME, PASSWORD, TYPE (http|https|socks5, default: socks5), REGION, STATUS (active|inactive, default: active), NOTES
+# Format B (auth-less shorthand): HOST:PORT
+# Imports an HTTP proxy without credentials; name is auto-generated.
# Lines starting with # are ignored. Existing proxies (same host+port) will be updated.
#
# SOCKS5 examples:
@@ -88,72 +70,12 @@ const BULK_IMPORT_TEMPLATE = `# Proxy Bulk Import
# HTTP/HTTPS examples:
# http-proxy|10.0.0.50|8080|||http||active|Internal HTTP proxy
# https-proxy|proxy.example.com|443|admin|secret123|https|US|active
+#
+# Auth-less shorthand examples:
+# 127.0.0.1:7897
+# proxy.example.com:3128
`;
-const VALID_TYPES = new Set(["http", "https", "socks5"]);
-const VALID_STATUSES = new Set(["active", "inactive"]);
-
-function parseBulkImportText(text: string): {
- entries: ParsedProxyEntry[];
- errors: ParseError[];
- skipped: number;
-} {
- const lines = text.split("\n");
- const entries: ParsedProxyEntry[] = [];
- const errors: ParseError[] = [];
- let skipped = 0;
-
- for (let i = 0; i < lines.length; i++) {
- const raw = lines[i].trim();
- if (!raw || raw.startsWith("#")) {
- skipped++;
- continue;
- }
-
- const parts = raw.split("|").map((p) => p.trim());
- const [name, host, portStr, username, password, type, region, status, notes] = parts;
- const lineNum = i + 1;
-
- if (!name) {
- errors.push({ line: lineNum, reason: "bulkImportErrorMissingName" });
- continue;
- }
- if (!host) {
- errors.push({ line: lineNum, reason: "bulkImportErrorMissingHost" });
- continue;
- }
- const port = Number(portStr);
- if (!portStr || isNaN(port) || port < 1 || port > 65535) {
- errors.push({ line: lineNum, reason: "bulkImportErrorInvalidPort" });
- continue;
- }
- const normalizedType = (type || "socks5").toLowerCase();
- if (!VALID_TYPES.has(normalizedType)) {
- errors.push({ line: lineNum, reason: "bulkImportErrorInvalidType" });
- continue;
- }
- const normalizedStatus = (status || "active").toLowerCase();
- if (!VALID_STATUSES.has(normalizedStatus)) {
- errors.push({ line: lineNum, reason: "bulkImportErrorInvalidStatus" });
- continue;
- }
-
- entries.push({
- name,
- host,
- port,
- username: username || "",
- password: password || "",
- type: normalizedType,
- region: region || "",
- status: normalizedStatus,
- notes: notes || "",
- });
- }
-
- return { entries, errors, skipped };
-}
-
export default function ProxyRegistryManager() {
const t = useTranslations("proxyRegistry");
const [items, setItems] = useState<ProxyItem[]>([]);
@@ -189,29 +111,6 @@ export default function ProxyRegistryManager() {
failed: number;
} | null>(null);
- const {
- selectedIds,
- setSelectedIds,
- batchDeleting,
- autoTesting,
- toggleSelectAll: hookToggleSelectAll,
- toggleSelect,
- handleBatchDelete: hookHandleBatchDelete,
- handleAutoTestAll: hookHandleAutoTestAll,
- } = useProxyBatchOperations(load);
-
- const allSelected = items.length > 0 && items.every((item) => selectedIds.has(item.id));
-
-
- const handleBatchDelete = useCallback(() => {
- hookHandleBatchDelete(setError);
- }, [hookHandleBatchDelete, setError]);
-
- const handleAutoTestAll = useCallback(() => {
- hookHandleAutoTestAll(setError, setTestById);
- }, [hookHandleAutoTestAll, setError, setTestById]);
-
-
const editingId = useMemo(() => form.id || "", [form.id]);
const loadHealth = useCallback(async () => {
@@ -275,9 +174,8 @@ export default function ProxyRegistryManager() {
const ids = loaded.map((p) => p.id).filter(Boolean);
void loadHealth();
void loadAllUsage(ids);
- } catch (e: unknown) {
- const msg = e instanceof Error ? e.message : String(e);
- setError(msg || t("errorLoadFailed"));
+ } catch (e: any) {
+ setError(e?.message || t("errorLoadFailed"));
setItems([]);
} finally {
setLoading(false);
@@ -288,7 +186,6 @@ export default function ProxyRegistryManager() {
void load();
}, [load]);
-
useEffect(() => {
if (items.length > 0 && !bulkProxyId) {
setBulkProxyId(items[0].id);
@@ -634,13 +531,6 @@ export default function ProxyRegistryManager() {
>
{t("bulkAssign")}
</Button>
- <ProxyBatchActions
- selectedCount={selectedIds.size}
- batchDeleting={batchDeleting}
- autoTesting={autoTesting}
- onBatchDelete={handleBatchDelete}
- onAutoTestAll={handleAutoTestAll}
- />
<Button
size="sm"
icon="add"
@@ -667,19 +557,8 @@ export default function ProxyRegistryManager() {
<table className="w-full text-sm">
<thead>
<tr className="text-left text-text-muted border-b border-border">
- <th className="py-2 pr-2 w-8">
- <input
- type="checkbox"
- className="accent-blue-500 w-4 h-4 cursor-pointer"
- checked={allSelected}
- ref={(el) => {
- if (el) el.indeterminate = !allSelected && items.some((item) => selectedIds.has(item.id));
- }}
- onChange={() => hookToggleSelectAll(allSelected, items)}
- aria-label="Select all proxies"
- />
- </th>
<th className="py-2 pr-3">{t("tableName")}</th>
+ <th className="py-2 pr-3">{t("tableEndpoint")}</th>
<th className="py-2 pr-3">{t("tableStatus")}</th>
<th className="py-2 pr-3">{t("tableHealth")}</th>
<th className="py-2 pr-3">{t("tableUsage")}</th>
@@ -692,11 +571,6 @@ export default function ProxyRegistryManager() {
const health = healthById[item.id];
return (
<tr key={item.id} className="border-b border-border/60">
- <ProxyCheckboxCell
- checked={selectedIds.has(item.id)}
- onChange={() => toggleSelect(item.id)}
- label={`Select ${item.name}`}
- />
<td className="py-2 pr-3">
<div className="font-medium text-text-main">{item.name}</div>
{item.region && (
@@ -707,13 +581,38 @@ export default function ProxyRegistryManager() {
{item.type}://{item.host}:{item.port}
</td>
<td className="py-2 pr-3">
- <ProxyStatusBadge status={item.status} />
+ <span className="text-xs px-2 py-1 rounded border border-border bg-bg-subtle">
+ {item.status === "inactive" ? t("statusInactive") : t("statusActive")}
+ </span>
</td>
<td className="py-2 pr-3 text-xs text-text-muted">
- <ProxyHealthCell
- testResult={testById[item.id] ?? undefined}
- health={health ?? undefined}
- />
+ <div className="flex flex-col gap-0.5">
+ {testById[item.id] ? (
+ testById[item.id]!.success ? (
+ <>
+ <span className="text-emerald-400">
+ ✓ {testById[item.id]!.publicIp}
+ </span>
+ {testById[item.id]!.latencyMs && (
+ <span>{testById[item.id]!.latencyMs}ms</span>
+ )}
+ </>
+ ) : (
+ <span className="text-red-400">
+ ✗ {testById[item.id]!.error || t("failed")}
+ </span>
+ )
+ ) : health ? (
+ <>
+ <span>{t("successRate", { rate: health.successRate ?? 0 })}</span>
+ <span>
+ {t("avgLatency", { latency: health.avgLatencyMs ?? "-" })}
+ </span>
+ </>
+ ) : (
+ <span>—</span>
+ )}
+ </div>
</td>
<td className="py-2 pr-3 text-xs text-text-muted">
{usageById[item.id] != null
diff --git a/src/app/(dashboard)/dashboard/settings/components/ProxyStatusBadge.tsx b/src/app/(dashboard)/dashboard/settings/components/ProxyStatusBadge.tsx
deleted file mode 100644
index 4f1287bf4f..0000000000
--- a/src/app/(dashboard)/dashboard/settings/components/ProxyStatusBadge.tsx
+++ /dev/null
@@ -1,23 +0,0 @@
-"use client";
-
-interface ProxyStatusBadgeProps {
- status?: string;
-}
-
-export function ProxyStatusBadge({ status }: ProxyStatusBadgeProps) {
- const isInactive = status === "inactive";
- return (
- <span
- className={`inline-flex items-center gap-1.5 text-xs px-2 py-1 rounded border ${
- isInactive
- ? "border-red-500/30 bg-red-500/10 text-red-400"
- : "border-emerald-500/30 bg-emerald-500/10 text-emerald-400"
- }`}
- >
- <span
- className={`w-1.5 h-1.5 rounded-full ${isInactive ? "bg-red-400" : "bg-emerald-400"}`}
- />
- {isInactive ? "Inactive" : "Active"}
- </span>
- );
-}
diff --git a/src/app/(dashboard)/dashboard/settings/components/SystemStorageTab.tsx b/src/app/(dashboard)/dashboard/settings/components/SystemStorageTab.tsx
index d73bfe60c0..f113d140e2 100644
--- a/src/app/(dashboard)/dashboard/settings/components/SystemStorageTab.tsx
+++ b/src/app/(dashboard)/dashboard/settings/components/SystemStorageTab.tsx
@@ -1,23 +1,10 @@
"use client";
import { useState, useEffect, useRef } from "react";
-import { Card, Button, Badge, ConfirmModal } from "@/shared/components";
+import { Card, Button, Badge } from "@/shared/components";
import { useLocale, useTranslations } from "next-intl";
import DatabaseBackupRetentionCard from "./DatabaseBackupRetentionCard";
-// Whitelist mirrored from src/lib/db/cleanup.ts::RESET_USAGE_HISTORY_PERIODS.
-const RESET_USAGE_PERIOD_VALUES = [
- "5m",
- "1h",
- "3h",
- "6h",
- "12h",
- "1d",
- "7d",
- "30d",
- "all",
-] as const;
-
export default function SystemStorageTab() {
const [backups, setBackups] = useState([]);
const [backupsLoading, setBackupsLoading] = useState(false);
@@ -51,10 +38,6 @@ export default function SystemStorageTab() {
const [purgeCallLogsStatus, setPurgeCallLogsStatus] = useState({ type: "", message: "" });
const [purgeDetailedLogsLoading, setPurgeDetailedLogsLoading] = useState(false);
const [purgeDetailedLogsStatus, setPurgeDetailedLogsStatus] = useState({ type: "", message: "" });
- const [resetUsageModalOpen, setResetUsageModalOpen] = useState(false);
- const [resetUsagePeriod, setResetUsagePeriod] = useState("all");
- const [resetUsageLoading, setResetUsageLoading] = useState(false);
- const [resetUsageStatus, setResetUsageStatus] = useState({ type: "", message: "" });
const fileInputRef = useRef<HTMLInputElement>(null);
const jsonInputRef = useRef<HTMLInputElement>(null);
const locale = useLocale();
@@ -345,48 +328,6 @@ export default function SystemStorageTab() {
}
};
- const handleResetUsageHistory = async () => {
- setResetUsageLoading(true);
- setResetUsageStatus({ type: "", message: "" });
- try {
- const res = await fetch("/api/settings/purge-usage-history", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ period: resetUsagePeriod }),
- });
- const data = await res.json().catch(() => null);
- if (res.ok) {
- const deleted = data?.deleted ?? 0;
- setResetUsageStatus({
- type: "success",
- message:
- t("resetUsageSuccess", { count: deleted }) ||
- `Usage data reset (${deleted} row(s) deleted).`,
- });
- setResetUsageModalOpen(false);
- } else {
- setResetUsageStatus({
- type: "error",
- message:
- data?.error?.message ||
- (typeof data?.error === "string" ? data.error : null) ||
- t("resetUsageFailed") ||
- "Failed to reset usage data",
- });
- }
- } catch {
- setResetUsageStatus({ type: "error", message: t("errorOccurred") });
- } finally {
- setResetUsageLoading(false);
- }
- };
-
- const openResetUsageModal = () => {
- setResetUsagePeriod("all");
- setResetUsageStatus({ type: "", message: "" });
- setResetUsageModalOpen(true);
- };
-
const handleManualVacuum = async () => {
setManualVacuumLoading(true);
setManualVacuumStatus({ type: "", message: "" });
@@ -1452,17 +1393,6 @@ export default function SystemStorageTab() {
</span>
Purge Detailed Logs
</Button>
- <Button
- variant="danger"
- size="sm"
- loading={resetUsageLoading}
- onClick={openResetUsageModal}
- >
- <span className="material-symbols-outlined text-[14px] mr-1" aria-hidden="true">
- restart_alt
- </span>
- {t("resetUsageData") || "Reset Usage Data"}
- </Button>
</div>
<div className="mt-4 border-t border-border/50 pt-3">
<div className="flex flex-col gap-2">
@@ -1473,7 +1403,6 @@ export default function SystemStorageTab() {
purgeQuotaSnapshotsStatus,
purgeCallLogsStatus,
purgeDetailedLogsStatus,
- resetUsageStatus,
].map(renderStatusAlert)}
</div>
</div>
@@ -1530,37 +1459,6 @@ export default function SystemStorageTab() {
{renderRetentionSettings()}
{renderOptimizationSettings()}
{renderCompressionAggregationSettings()}
-
- <ConfirmModal
- isOpen={resetUsageModalOpen}
- onClose={() => !resetUsageLoading && setResetUsageModalOpen(false)}
- onConfirm={handleResetUsageHistory}
- title={t("resetUsageData") || "Reset Usage Data"}
- message={
- <div className="space-y-3">
- <p className="text-text-muted">
- {t("resetUsageDataDesc") ||
- "Select how far back you want to delete usage data. This action cannot be undone."}
- </p>
- <select
- value={resetUsagePeriod}
- onChange={(e) => setResetUsagePeriod(e.target.value)}
- className="w-full rounded-lg border border-border bg-surface px-3 py-2 text-sm text-text-main focus:outline-none focus:ring-2 focus:ring-red-500/40"
- >
- {RESET_USAGE_PERIOD_VALUES.map((value) => (
- <option key={value} value={value}>
- {t(`resetUsagePeriod_${value}`) || value}
- </option>
- ))}
- </select>
- </div>
- }
- confirmText={
- resetUsageLoading ? t("resetting") || "Resetting..." : t("reset") || "Reset"
- }
- variant="danger"
- loading={resetUsageLoading}
- />
</Card>
);
}
diff --git a/src/app/(dashboard)/dashboard/settings/components/proxy/SourceToggleBar.tsx b/src/app/(dashboard)/dashboard/settings/components/proxy/SourceToggleBar.tsx
index 78152b18bf..74a6a4d976 100644
--- a/src/app/(dashboard)/dashboard/settings/components/proxy/SourceToggleBar.tsx
+++ b/src/app/(dashboard)/dashboard/settings/components/proxy/SourceToggleBar.tsx
@@ -1,8 +1,8 @@
"use client";
-export type SourceId = "1proxy" | "proxifly" | "iplocate" | "webshare";
+export type SourceId = "1proxy" | "proxifly" | "iplocate";
-export const ALL_SOURCE_IDS: SourceId[] = ["1proxy", "proxifly", "iplocate", "webshare"];
+export const ALL_SOURCE_IDS: SourceId[] = ["1proxy", "proxifly", "iplocate"];
export const FREE_POOL_DISABLED_SOURCES_KEY = "freePool.disabledSources";
@@ -32,7 +32,6 @@ const SOURCES: Array<{ id: SourceId; label: string }> = [
{ id: "1proxy", label: "1proxy" },
{ id: "proxifly", label: "Proxifly" },
{ id: "iplocate", label: "IPLocate" },
- { id: "webshare", label: "Webshare" },
];
export default function SourceToggleBar({ disabledSources, onToggle }: SourceToggleBarProps) {
diff --git a/src/app/(dashboard)/dashboard/settings/components/useProxyBatchOperations.ts b/src/app/(dashboard)/dashboard/settings/components/useProxyBatchOperations.ts
deleted file mode 100644
index b336431158..0000000000
--- a/src/app/(dashboard)/dashboard/settings/components/useProxyBatchOperations.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-import { useCallback, useState } from "react";
-
-interface BatchDeleteResult {
- id: string;
- success: boolean;
- error?: string;
-}
-
-interface AutoTestResult {
- proxyId: string;
- host: string;
- port: number;
- alive: boolean;
- latencyMs: number | null;
- error?: string;
-}
-
-export function useProxyBatchOperations(load: () => Promise<void>) {
- const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
- const [batchDeleting, setBatchDeleting] = useState(false);
- const [autoTesting, setAutoTesting] = useState(false);
-
- const toggleSelectAll = useCallback(
- (allSelected: boolean, items: Array<{ id: string }>) => {
- setSelectedIds(allSelected ? new Set() : new Set(items.map((i) => i.id)));
- },
- []
- );
-
- const toggleSelect = useCallback((id: string) => {
- setSelectedIds((prev) => {
- const next = new Set(prev);
- if (next.has(id)) next.delete(id);
- else next.add(id);
- return next;
- });
- }, []);
-
- const handleBatchDelete = useCallback(
- async (setError: (msg: string | null) => void) => {
- if (selectedIds.size === 0) return;
- setBatchDeleting(true);
- try {
- const res = await fetch("/api/settings/proxies/batch-delete", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ ids: Array.from(selectedIds), force: true }),
- });
- const data: { error?: { message?: string }; results?: BatchDeleteResult[] } =
- await res.json().catch(() => ({}));
- if (res.ok) {
- setSelectedIds(new Set());
- await load();
- } else {
- setError(data?.error?.message || "Batch delete failed");
- }
- } catch (e: unknown) {
- setError(e instanceof Error ? e.message : "Batch delete failed");
- } finally {
- setBatchDeleting(false);
- }
- },
- [selectedIds, load]
- );
-
- const handleAutoTestAll = useCallback(
- async (
- setError: (msg: string | null) => void,
- setTestById: React.Dispatch<React.SetStateAction<Record<string, { success: boolean; publicIp?: string; latencyMs?: number | null; error?: string } | null>>>
- ) => {
- setAutoTesting(true);
- try {
- const res = await fetch("/api/settings/proxies/auto-test", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({}),
- });
- const data: { error?: { message?: string }; results?: AutoTestResult[] } =
- await res.json().catch(() => ({}));
- if (res.ok && data?.results) {
- const newTestResults: Record<string, { success: boolean; publicIp?: string; latencyMs?: number | null; error?: string } | null> = {};
- for (const r of data.results) {
- newTestResults[r.proxyId] = {
- success: r.alive,
- publicIp: r.alive ? r.host : undefined,
- latencyMs: r.latencyMs,
- error: r.error,
- };
- }
- setTestById((prev) => ({ ...prev, ...newTestResults }));
- } else if (data?.error?.message) {
- setError(data.error.message);
- }
- await load();
- } catch (e: unknown) {
- setError(e instanceof Error ? e.message : "Auto-test failed");
- } finally {
- setAutoTesting(false);
- }
- },
- [load]
- );
-
- return {
- selectedIds,
- setSelectedIds,
- batchDeleting,
- autoTesting,
- toggleSelectAll,
- toggleSelect,
- handleBatchDelete,
- handleAutoTestAll,
- };
-}
diff --git a/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/parts/QuotaCardExpanded.tsx b/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/parts/QuotaCardExpanded.tsx
index 0457174b36..58b509f078 100644
--- a/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/parts/QuotaCardExpanded.tsx
+++ b/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/parts/QuotaCardExpanded.tsx
@@ -1,6 +1,5 @@
"use client";
-import { useMemo, useState } from "react";
import { useTranslations } from "next-intl";
import {
formatCountdown,
@@ -22,20 +21,6 @@ const CURRENCY_SYMBOLS: Record<string, string> = {
INR: "₹",
};
-const DEFAULT_VISIBLE_ROWS = 3;
-
-/** Pure helper — sorts quotas by remaining percentage, highest first. */
-export function sortQuotasByRemaining(quotas: any[]): any[] {
- return [...quotas].sort(
- (a, b) => getQuotaRemainingPercentage(b) - getQuotaRemainingPercentage(a)
- );
-}
-
-/** Pure helper — slices the sorted quotas down to the visible window. */
-export function getVisibleQuotas(sortedQuotas: any[], expanded: boolean): any[] {
- return expanded ? sortedQuotas : sortedQuotas.slice(0, DEFAULT_VISIBLE_ROWS);
-}
-
interface Props {
quotas: any[];
loading: boolean;
@@ -139,14 +124,6 @@ export default function QuotaCardExpanded({
const tr = (key: string, fallback: string, values?: UsageTranslationValues) =>
translateUsageOrFallback(t, key, fallback, values);
- const [expanded, setExpanded] = useState(false);
- const sortedQuotas = useMemo(() => sortQuotasByRemaining(quotas), [quotas]);
- const visibleQuotas = useMemo(
- () => getVisibleQuotas(sortedQuotas, expanded),
- [sortedQuotas, expanded]
- );
- const hiddenCount = sortedQuotas.length - visibleQuotas.length;
-
const refreshedLabel = refreshedAt
? new Date(refreshedAt).toLocaleTimeString([], {
hour: "2-digit",
@@ -178,30 +155,12 @@ export default function QuotaCardExpanded({
<div className="text-[11px] text-text-muted italic">{t("noQuotaData")}</div>
) : (
<div className="flex flex-col divide-y divide-border/40">
- {visibleQuotas.map((q, i) => (
+ {quotas.map((q, i) => (
<QuotaDetailRow key={`${q.name}-${q.modelKey ?? ""}-${i}`} q={q} />
))}
</div>
)}
- {!loading && !error && sortedQuotas.length > DEFAULT_VISIBLE_ROWS && (
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- setExpanded((prev) => !prev);
- }}
- className="inline-flex items-center justify-center gap-1 text-[11px] font-medium px-2 py-1 rounded-md border border-border bg-bg-subtle hover:bg-black/[0.04] dark:hover:bg-white/[0.04] cursor-pointer"
- >
- <span className="material-symbols-outlined text-[12px]">
- {expanded ? "expand_less" : "expand_more"}
- </span>
- {expanded
- ? tr("showLessQuotas", "Show less")
- : tr("showMoreQuotas", `Show ${hiddenCount} more`, { count: hiddenCount })}
- </button>
- )}
-
<div className="flex items-center justify-between gap-2 pt-1.5 border-t border-border/40">
{refreshedLabel && (
<span
diff --git a/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/quotaParsing.ts b/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/quotaParsing.ts
index 04346f1dc1..5b567b0157 100644
--- a/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/quotaParsing.ts
+++ b/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/quotaParsing.ts
@@ -110,30 +110,13 @@ function parseAntigravity(data: any) {
.filter(Boolean);
}
-/**
- * Codex "banked reset credits" — an eligibility-gated field (issue #5199):
- * a count of extra rate-limit resets the account has banked. DISPLAY ONLY
- * (redemption is an unofficial mutating endpoint, out of scope). Most
- * accounts won't have this field; only render it when the count is positive.
- */
-function buildBankedResetCreditsQuota(count: number) {
- return buildCreditsQuota("banked_reset_credits", count, 100, { currency: "" });
-}
-
function parseCodex(data: any) {
- const quotas = quotaEntries(data).map(([quotaType, quota]) =>
+ return quotaEntries(data).map(([quotaType, quota]) =>
normalizeQuotaEntry(quotaType, quota, {
displayName: quota?.displayName,
isPercentageOnly: true,
})
);
-
- const bankedResetCredits = Number(data?.bankedResetCredits);
- if (Number.isFinite(bankedResetCredits) && bankedResetCredits > 0) {
- quotas.push(buildBankedResetCreditsQuota(bankedResetCredits));
- }
-
- return quotas;
}
function parseClaude(data: any) {
diff --git a/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/utils.tsx b/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/utils.tsx
index f99f0f9c85..e19f8b973b 100644
--- a/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/utils.tsx
+++ b/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/utils.tsx
@@ -33,7 +33,6 @@ const QUOTA_LABEL_MAP: Record<string, string> = {
"Monthly Tools": "Monthly Tools",
tokens: "Tokens",
time_limit: "Time Limit",
- banked_reset_credits: "Banked Reset Credits",
};
function toRecord(value: unknown): Record<string, unknown> {
diff --git a/src/app/api/cli-tools/codewhale-settings/route.ts b/src/app/api/cli-tools/codewhale-settings/route.ts
deleted file mode 100644
index 273c1029ed..0000000000
--- a/src/app/api/cli-tools/codewhale-settings/route.ts
+++ /dev/null
@@ -1,235 +0,0 @@
-"use server";
-
-import { NextResponse } from "next/server";
-import fs from "fs/promises";
-import path from "path";
-import { requireCliToolsAuth } from "@/lib/api/requireCliToolsAuth";
-import {
- ensureCliConfigWriteAllowed,
- getCliPrimaryConfigPath,
- getCliRuntimeStatus,
-} from "@/shared/services/cliRuntime";
-import { createBackup } from "@/shared/services/backupService";
-import { saveCliToolLastConfigured, deleteCliToolLastConfigured } from "@/lib/db/cliToolState";
-import { cliModelConfigSchema } from "@/shared/validation/schemas";
-import { isValidationFailure, validateBody } from "@/shared/validation/helpers";
-import { resolveApiKey } from "@/shared/services/apiKeyResolver";
-import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error.ts";
-
-const TOOL_ID = "codewhale";
-
-/**
- * CodeWhale is the actively-maintained successor to DeepSeek TUI (same
- * author, renamed project — https://github.com/Hmbown/CodeWhale). It reads
- * its config from ~/.codewhale/config.toml. Users upgrading from the old
- * DeepSeek TUI binary may still have ~/.deepseek/config.toml around, so we
- * read/write that path as a legacy fallback.
- */
-const getPrimaryConfigPath = (): string =>
- getCliPrimaryConfigPath(TOOL_ID) ?? path.join(process.env.HOME ?? "~", ".codewhale", "config.toml");
-
-const getLegacyConfigPath = (): string =>
- path.join(process.env.HOME ?? "~", ".deepseek", "config.toml");
-
-const getPrimaryConfigDir = () => path.dirname(getPrimaryConfigPath());
-
-/**
- * Render the OmniRoute config block in CodeWhale TOML format.
- * CodeWhale reads OPENAI_BASE_URL and OPENAI_API_KEY from its config.
- * Reference: https://github.com/Hmbown/CodeWhale
- */
-function renderCodewhaleConfig(baseUrl: string, apiKey: string, model: string): string {
- return [
- "# CodeWhale config — managed by OmniRoute (plan 14)",
- "",
- "[openai]",
- `base_url = "${baseUrl}"`,
- `api_key = "${apiKey}"`,
- `model = "${model}"`,
- "",
- ].join("\n");
-}
-
-/**
- * Check if the config file contains OmniRoute settings.
- */
-const hasOmniRouteConfig = (content: string | null): boolean => {
- if (!content) return false;
- return content.includes("managed by OmniRoute");
-};
-
-// Read current config.toml — prefers the primary ~/.codewhale path, falling
-// back to the legacy ~/.deepseek path for users upgrading from DeepSeek TUI.
-const readConfig = async (): Promise<string | null> => {
- for (const candidate of [getPrimaryConfigPath(), getLegacyConfigPath()]) {
- try {
- return await fs.readFile(candidate, "utf-8");
- } catch (err) {
- if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
- }
- }
- return null;
-};
-
-// GET — check CodeWhale CLI and return current config
-export async function GET(request: Request) {
- const authError = await requireCliToolsAuth(request);
- if (authError) return authError;
-
- try {
- const runtime = await getCliRuntimeStatus(TOOL_ID);
-
- if (!runtime.installed || !runtime.runnable) {
- return NextResponse.json({
- installed: runtime.installed,
- runnable: runtime.runnable,
- command: runtime.command,
- commandPath: runtime.commandPath,
- runtimeMode: runtime.runtimeMode,
- reason: runtime.reason,
- config: null,
- message:
- runtime.installed && !runtime.runnable
- ? "CodeWhale is installed but not runnable"
- : "CodeWhale is not installed",
- });
- }
-
- const config = await readConfig();
-
- return NextResponse.json({
- installed: runtime.installed,
- runnable: runtime.runnable,
- command: runtime.command,
- commandPath: runtime.commandPath,
- runtimeMode: runtime.runtimeMode,
- reason: runtime.reason,
- config,
- hasOmniRoute: hasOmniRouteConfig(config),
- configPath: getPrimaryConfigPath(),
- });
- } catch (err) {
- return NextResponse.json(
- { error: { message: sanitizeErrorMessage(err) } },
- { status: 500 }
- );
- }
-}
-
-// POST — write OmniRoute settings to CodeWhale's config.toml (primary), and
-// keep the legacy ~/.deepseek/config.toml in sync when it already exists so
-// users who have not yet upgraded their CLI binary keep working.
-export async function POST(request: Request) {
- const authError = await requireCliToolsAuth(request);
- if (authError) return authError;
-
- let rawBody;
- try {
- rawBody = await request.json();
- } catch {
- return NextResponse.json(
- { error: { message: "Invalid JSON body" } },
- { status: 400 }
- );
- }
-
- try {
- const writeGuard = ensureCliConfigWriteAllowed();
- if (writeGuard) {
- return NextResponse.json({ error: writeGuard }, { status: 403 });
- }
-
- // Extract keyId BEFORE Zod validation — Zod strips unknown fields
- const keyId = typeof rawBody?.keyId === "string" ? rawBody.keyId.trim() : null;
-
- const validation = validateBody(cliModelConfigSchema, rawBody);
- if (isValidationFailure(validation)) {
- return NextResponse.json({ error: validation.error }, { status: 400 });
- }
- const { baseUrl, model } = validation.data;
- const apiKey = await resolveApiKey(keyId, validation.data.apiKey);
-
- const primaryPath = getPrimaryConfigPath();
- const legacyPath = getLegacyConfigPath();
- const content = renderCodewhaleConfig(baseUrl, apiKey, model);
-
- // Always write the primary (~/.codewhale) config.
- await fs.mkdir(getPrimaryConfigDir(), { recursive: true });
- await createBackup(TOOL_ID, primaryPath);
- await fs.writeFile(primaryPath, content, "utf-8");
-
- // Best-effort: keep the legacy (~/.deepseek) config in sync only if it
- // already exists — never create a fresh legacy directory for new users.
- try {
- await fs.access(legacyPath);
- await createBackup(TOOL_ID, legacyPath);
- await fs.writeFile(legacyPath, content, "utf-8");
- } catch {
- /* legacy config not present — nothing to sync */
- }
-
- // Persist last-configured timestamp
- try {
- saveCliToolLastConfigured(TOOL_ID);
- } catch {
- /* non-critical */
- }
-
- return NextResponse.json({
- success: true,
- message: "CodeWhale settings applied successfully!",
- configPath: primaryPath,
- });
- } catch (err) {
- return NextResponse.json(
- { error: { message: sanitizeErrorMessage(err) } },
- { status: 500 }
- );
- }
-}
-
-// DELETE — remove OmniRoute CodeWhale config (primary + legacy, if present)
-export async function DELETE(request: Request) {
- const authError = await requireCliToolsAuth(request);
- if (authError) return authError;
-
- try {
- const writeGuard = ensureCliConfigWriteAllowed();
- if (writeGuard) {
- return NextResponse.json({ error: writeGuard }, { status: 403 });
- }
-
- const primaryPath = getPrimaryConfigPath();
- const legacyPath = getLegacyConfigPath();
-
- // Backup + remove primary before removing
- await createBackup(TOOL_ID, primaryPath);
- await fs.rm(primaryPath, { force: true });
-
- // Best-effort: remove legacy config too, if present
- try {
- await fs.access(legacyPath);
- await createBackup(TOOL_ID, legacyPath);
- await fs.rm(legacyPath, { force: true });
- } catch {
- /* legacy config not present */
- }
-
- // Clear last-configured timestamp
- try {
- deleteCliToolLastConfigured(TOOL_ID);
- } catch {
- /* non-critical */
- }
-
- return NextResponse.json({
- success: true,
- message: "CodeWhale settings removed successfully",
- });
- } catch (err) {
- return NextResponse.json(
- { error: { message: sanitizeErrorMessage(err) } },
- { status: 500 }
- );
- }
-}
diff --git a/src/app/api/cli-tools/crush-settings/route.ts b/src/app/api/cli-tools/crush-settings/route.ts
deleted file mode 100644
index 123f352c15..0000000000
--- a/src/app/api/cli-tools/crush-settings/route.ts
+++ /dev/null
@@ -1,252 +0,0 @@
-"use server";
-
-import { NextResponse } from "next/server";
-import fs from "fs/promises";
-import path from "path";
-import { requireCliToolsAuth } from "@/lib/api/requireCliToolsAuth";
-import {
- ensureCliConfigWriteAllowed,
- getCliPrimaryConfigPath,
- getCliRuntimeStatus,
-} from "@/shared/services/cliRuntime";
-import { createBackup } from "@/shared/services/backupService";
-import { saveCliToolLastConfigured, deleteCliToolLastConfigured } from "@/lib/db/cliToolState";
-import { cliModelConfigSchema } from "@/shared/validation/schemas";
-import { isValidationFailure, validateBody } from "@/shared/validation/helpers";
-import { resolveApiKey } from "@/shared/services/apiKeyResolver";
-import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error.ts";
-
-const TOOL_ID = "crush";
-
-// Crush (charmbracelet/crush) reads a file-based config, default
-// ~/.config/crush/crush.json — same default `bin/cli/commands/setup-crush.mjs`
-// (resolveCrushTarget / runSetupCrushCommand) writes to, so the dashboard and
-// the `omniroute setup-crush` CLI command agree on one canonical location.
-const getCrushConfigPath = (): string =>
- getCliPrimaryConfigPath(TOOL_ID) ??
- path.join(process.env.HOME ?? "~", ".config", "crush", "crush.json");
-
-const getCrushDir = () => path.dirname(getCrushConfigPath());
-
-/**
- * Crush's config uses a `providers.<id>` map. OmniRoute is registered under
- * the `omniroute` provider id as an `openai-compat` provider — same shape
- * `buildCrushProvider()`/`mergeCrushConfig()` in setup-crush.mjs produce.
- */
-type CrushProvider = {
- type: "openai-compat";
- base_url: string;
- api_key: string;
- models: Array<{ id: string; name: string; context_window: number }>;
-};
-
-const DEFAULT_CONTEXT_WINDOW = 128000;
-
-const ensureV1 = (url: string): string => {
- const s = url.replace(/\/+$/, "");
- return s.endsWith("/v1") ? s : `${s}/v1`;
-};
-
-const hasOmniRouteConfig = (settings: Record<string, unknown> | null): boolean => {
- if (!settings) return false;
- const providers = settings.providers as Record<string, unknown> | undefined;
- const omniroute = providers?.omniroute as Record<string, unknown> | undefined;
- return (
- !!omniroute &&
- omniroute.type === "openai-compat" &&
- typeof omniroute.base_url === "string" &&
- omniroute.base_url.length > 0
- );
-};
-
-// Read current crush.json
-const readConfig = async (): Promise<Record<string, unknown> | null> => {
- try {
- const content = await fs.readFile(getCrushConfigPath(), "utf-8");
- return JSON.parse(content) as Record<string, unknown>;
- } catch (err) {
- if ((err as NodeJS.ErrnoException).code === "ENOENT") return null;
- throw err;
- }
-};
-
-// GET — check crush CLI and return current config
-export async function GET(request: Request) {
- const authError = await requireCliToolsAuth(request);
- if (authError) return authError;
-
- try {
- const runtime = await getCliRuntimeStatus(TOOL_ID);
-
- if (!runtime.installed || !runtime.runnable) {
- return NextResponse.json({
- installed: runtime.installed,
- runnable: runtime.runnable,
- command: runtime.command,
- commandPath: runtime.commandPath,
- runtimeMode: runtime.runtimeMode,
- reason: runtime.reason,
- config: null,
- message:
- runtime.installed && !runtime.runnable
- ? "Crush CLI is installed but not runnable"
- : "Crush CLI is not installed",
- });
- }
-
- const config = await readConfig();
-
- return NextResponse.json({
- installed: runtime.installed,
- runnable: runtime.runnable,
- command: runtime.command,
- commandPath: runtime.commandPath,
- runtimeMode: runtime.runtimeMode,
- reason: runtime.reason,
- config,
- hasOmniRoute: hasOmniRouteConfig(config),
- configPath: getCrushConfigPath(),
- });
- } catch (err) {
- return NextResponse.json({ error: { message: sanitizeErrorMessage(err) } }, { status: 500 });
- }
-}
-
-// POST — write OmniRoute settings to crush.json (providers.omniroute)
-export async function POST(request: Request) {
- const authError = await requireCliToolsAuth(request);
- if (authError) return authError;
-
- let rawBody;
- try {
- rawBody = await request.json();
- } catch {
- return NextResponse.json({ error: { message: "Invalid JSON body" } }, { status: 400 });
- }
-
- try {
- const writeGuard = ensureCliConfigWriteAllowed();
- if (writeGuard) {
- return NextResponse.json({ error: writeGuard }, { status: 403 });
- }
-
- // Extract keyId BEFORE Zod validation — Zod strips unknown fields
- const keyId = typeof rawBody?.keyId === "string" ? rawBody.keyId.trim() : null;
-
- const validation = validateBody(cliModelConfigSchema, rawBody);
- if (isValidationFailure(validation)) {
- return NextResponse.json({ error: validation.error }, { status: 400 });
- }
- const { baseUrl, model } = validation.data;
- const apiKey = await resolveApiKey(keyId, validation.data.apiKey);
-
- const configPath = getCrushConfigPath();
- const crushDir = getCrushDir();
-
- // Ensure directory exists
- await fs.mkdir(crushDir, { recursive: true });
-
- // Backup current config before modifying
- await createBackup(TOOL_ID, configPath);
-
- // Read existing config or start fresh
- let existing: Record<string, unknown> = {};
- try {
- const raw = await fs.readFile(configPath, "utf-8");
- existing = JSON.parse(raw) as Record<string, unknown>;
- } catch {
- /* No existing config */
- }
-
- const normalizedBaseUrl = ensureV1(baseUrl);
- const provider: CrushProvider = {
- type: "openai-compat",
- base_url: normalizedBaseUrl,
- api_key: apiKey,
- models: [{ id: model, name: `OmniRoute: ${model}`, context_window: DEFAULT_CONTEXT_WINDOW }],
- };
-
- const updated: Record<string, unknown> = {
- ...existing,
- providers: {
- ...((existing.providers as Record<string, unknown>) || {}),
- omniroute: provider,
- },
- };
-
- await fs.writeFile(configPath, JSON.stringify(updated, null, 2), "utf-8");
-
- // Persist last-configured timestamp
- try {
- saveCliToolLastConfigured(TOOL_ID);
- } catch {
- /* non-critical */
- }
-
- return NextResponse.json({
- success: true,
- message: "Crush settings applied successfully!",
- configPath,
- });
- } catch (err) {
- return NextResponse.json({ error: { message: sanitizeErrorMessage(err) } }, { status: 500 });
- }
-}
-
-// DELETE — remove OmniRoute provider from Crush config
-export async function DELETE(request: Request) {
- const authError = await requireCliToolsAuth(request);
- if (authError) return authError;
-
- try {
- const writeGuard = ensureCliConfigWriteAllowed();
- if (writeGuard) {
- return NextResponse.json({ error: writeGuard }, { status: 403 });
- }
-
- const configPath = getCrushConfigPath();
-
- // Backup before modifying
- await createBackup(TOOL_ID, configPath);
-
- // Read existing config
- let existing: Record<string, unknown> = {};
- try {
- const raw = await fs.readFile(configPath, "utf-8");
- existing = JSON.parse(raw) as Record<string, unknown>;
- } catch (err) {
- if ((err as NodeJS.ErrnoException).code === "ENOENT") {
- return NextResponse.json({ success: true, message: "No config file to reset" });
- }
- throw err;
- }
-
- // Remove only the OmniRoute-managed provider entry — preserve the rest
- // of the user's providers map (Crush supports multiple providers).
- const providers = { ...((existing.providers as Record<string, unknown>) || {}) };
- delete providers.omniroute;
-
- if (Object.keys(providers).length === 0) {
- delete existing.providers;
- } else {
- existing.providers = providers;
- }
-
- if (Object.keys(existing).length === 0) {
- await fs.rm(configPath, { force: true });
- } else {
- await fs.writeFile(configPath, JSON.stringify(existing, null, 2), "utf-8");
- }
-
- // Clear last-configured timestamp
- try {
- deleteCliToolLastConfigured(TOOL_ID);
- } catch {
- /* non-critical */
- }
-
- return NextResponse.json({ success: true, message: "Crush OmniRoute settings removed" });
- } catch (err) {
- return NextResponse.json({ error: { message: sanitizeErrorMessage(err) } }, { status: 500 });
- }
-}
diff --git a/src/app/api/discovery/results/[id]/route.ts b/src/app/api/discovery/results/[id]/route.ts
deleted file mode 100644
index 4a7a23ab38..0000000000
--- a/src/app/api/discovery/results/[id]/route.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-/**
- * Discovery result by id — GET / DELETE /api/discovery/results/:id
- *
- * Auth: Tier 3 MANAGEMENT + strict local-only (see ../route.ts for the model).
- */
-
-import { requireManagementAuth } from "@/lib/api/requireManagementAuth";
-import { createErrorResponse, createErrorResponseFromUnknown } from "@/lib/api/errorResponse";
-import { getDiscoveryResultById, deleteDiscoveryResult } from "@/lib/db/discoveryResults";
-
-function parseId(raw: string): number | null {
- const id = Number(raw);
- return Number.isInteger(id) && id > 0 ? id : null;
-}
-
-export async function GET(
- request: Request,
- { params }: { params: Promise<{ id: string }> }
-): Promise<Response> {
- const authError = await requireManagementAuth(request);
- if (authError) return authError;
-
- const { id: rawId } = await params;
- const id = parseId(rawId);
- if (id === null) {
- return createErrorResponse({ status: 400, message: "Invalid discovery result id" });
- }
-
- try {
- const result = getDiscoveryResultById(id);
- if (!result) {
- return createErrorResponse({ status: 404, message: "Discovery result not found" });
- }
- return Response.json({ result });
- } catch (error) {
- return createErrorResponseFromUnknown(error, "Failed to read discovery result");
- }
-}
-
-export async function DELETE(
- request: Request,
- { params }: { params: Promise<{ id: string }> }
-): Promise<Response> {
- const authError = await requireManagementAuth(request);
- if (authError) return authError;
-
- const { id: rawId } = await params;
- const id = parseId(rawId);
- if (id === null) {
- return createErrorResponse({ status: 400, message: "Invalid discovery result id" });
- }
-
- try {
- const removed = deleteDiscoveryResult(id);
- if (!removed) {
- return createErrorResponse({ status: 404, message: "Discovery result not found" });
- }
- return Response.json({ deleted: true, id });
- } catch (error) {
- return createErrorResponseFromUnknown(error, "Failed to delete discovery result");
- }
-}
diff --git a/src/app/api/discovery/results/route.ts b/src/app/api/discovery/results/route.ts
deleted file mode 100644
index c7d91f882d..0000000000
--- a/src/app/api/discovery/results/route.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-/**
- * Discovery results — GET /api/discovery/results
- *
- * Lists persisted discovery findings, optionally filtered by `?providerId=`.
- *
- * Auth: Tier 3 MANAGEMENT (requireManagementAuth) + strict local-only. The
- * `/api/discovery/` prefix is in `LOCAL_ONLY_API_PREFIXES` (routeGuard.ts), so
- * the central authz pipeline (src/proxy.ts → runAuthzPipeline → managementPolicy)
- * blocks non-loopback callers with a 403 LOCAL_ONLY before this handler runs.
- * It is NOT in the manage-scope bypass list — strict loopback, no remote bypass.
- */
-
-import { requireManagementAuth } from "@/lib/api/requireManagementAuth";
-import { createErrorResponseFromUnknown } from "@/lib/api/errorResponse";
-import { getDiscoveryResults } from "@/lib/db/discoveryResults";
-
-export async function GET(request: Request): Promise<Response> {
- const authError = await requireManagementAuth(request);
- if (authError) return authError;
-
- try {
- const url = new URL(request.url);
- const providerId = url.searchParams.get("providerId") || undefined;
- const results = getDiscoveryResults(providerId);
- return Response.json({ results });
- } catch (error) {
- return createErrorResponseFromUnknown(error, "Failed to list discovery results");
- }
-}
diff --git a/src/app/api/discovery/scan/route.ts b/src/app/api/discovery/scan/route.ts
deleted file mode 100644
index 3245997664..0000000000
--- a/src/app/api/discovery/scan/route.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-/**
- * Discovery scan — POST /api/discovery/scan
- *
- * Triggers a scan for one provider and persists the findings. Body:
- * `{ "providerId": "<id>" }`.
- *
- * Auth: Tier 3 MANAGEMENT + strict local-only (see ../results/route.ts). The
- * strict-loopback classification matters here specifically: `scanProvider` may
- * probe outbound provider endpoints (SSRF-adjacent), so the surface must never
- * be reachable from a tunnel/remote origin.
- */
-
-import { z } from "zod";
-import { requireManagementAuth } from "@/lib/api/requireManagementAuth";
-import { createErrorResponse, createErrorResponseFromUnknown } from "@/lib/api/errorResponse";
-import { isValidationFailure, validateBody } from "@/shared/validation/helpers";
-import { scanProvider, persistDiscoveryResult } from "@/lib/discovery/index";
-
-const scanRequestSchema = z.object({
- providerId: z.string().min(1).max(200),
-});
-
-export async function POST(request: Request): Promise<Response> {
- const authError = await requireManagementAuth(request);
- if (authError) return authError;
-
- let raw: unknown;
- try {
- raw = await request.json();
- } catch {
- return createErrorResponse({
- status: 400,
- message: "Invalid request",
- details: [{ field: "body", message: "Invalid JSON body" }],
- });
- }
-
- const validation = validateBody(scanRequestSchema, raw);
- if (isValidationFailure(validation)) {
- return createErrorResponse({
- status: 400,
- message: validation.error.message,
- details: validation.error.details,
- });
- }
-
- try {
- const found = await scanProvider(validation.data.providerId);
- const persisted = found.map((result) => persistDiscoveryResult(result));
- return Response.json({ results: persisted });
- } catch (error) {
- return createErrorResponseFromUnknown(error, "Failed to scan provider");
- }
-}
diff --git a/src/app/api/discovery/verify/[id]/route.ts b/src/app/api/discovery/verify/[id]/route.ts
deleted file mode 100644
index 684e622f94..0000000000
--- a/src/app/api/discovery/verify/[id]/route.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-/**
- * Discovery verify — POST /api/discovery/verify/:id
- *
- * Marks a discovery finding as verified (status='verified', stamps verified_at).
- *
- * Auth: Tier 3 MANAGEMENT + strict local-only (see ../../results/route.ts).
- */
-
-import { requireManagementAuth } from "@/lib/api/requireManagementAuth";
-import { createErrorResponse, createErrorResponseFromUnknown } from "@/lib/api/errorResponse";
-import { markVerified } from "@/lib/db/discoveryResults";
-
-export async function POST(
- request: Request,
- { params }: { params: Promise<{ id: string }> }
-): Promise<Response> {
- const authError = await requireManagementAuth(request);
- if (authError) return authError;
-
- const { id: rawId } = await params;
- const id = Number(rawId);
- if (!Number.isInteger(id) || id <= 0) {
- return createErrorResponse({ status: 400, message: "Invalid discovery result id" });
- }
-
- try {
- const result = markVerified(id);
- if (!result) {
- return createErrorResponse({ status: 404, message: "Discovery result not found" });
- }
- return Response.json({ result });
- } catch (error) {
- return createErrorResponseFromUnknown(error, "Failed to verify discovery result");
- }
-}
diff --git a/src/app/api/keys/[id]/devices/route.ts b/src/app/api/keys/[id]/devices/route.ts
deleted file mode 100644
index 584ea52c0a..0000000000
--- a/src/app/api/keys/[id]/devices/route.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-/**
- * Per-API-Key Device List — Read Route
- *
- * Lists the distinct devices (IP + User-Agent fingerprints) tracked for an
- * API key by `open-sse/services/deviceTracker.ts` (in-memory, TTL-evicted).
- * IPs are already masked by the tracker before storage — this route never
- * has access to the raw client IP or the full SHA-256 fingerprint.
- *
- * Ported from upstream 9router#931 (thanks @mugnimaestra) — the original
- * exposed a flat `GET /api/keys/devices` listing every key; this route
- * follows the OmniRoute `[id]` sub-resource convention (see
- * `src/app/api/keys/[id]/usage-limits/route.ts`) and requires management
- * auth like every other `/api/keys/[id]/*` route.
- *
- * @route /api/keys/[id]/devices
- */
-
-import { NextResponse } from "next/server";
-import { requireManagementAuth } from "@/lib/api/requireManagementAuth";
-import { getApiKeyById } from "@/lib/db/apiKeys";
-import { getDeviceCount, getDeviceDetails } from "@omniroute/open-sse/services/deviceTracker.ts";
-import { buildErrorBody, sanitizeErrorMessage } from "@omniroute/open-sse/utils/error.ts";
-import * as log from "@/sse/utils/logger";
-
-export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) {
- const authError = await requireManagementAuth(request);
- if (authError) return authError;
-
- try {
- const { id } = await params;
- const key = await getApiKeyById(id);
- if (!key || typeof key.id !== "string") {
- return NextResponse.json(buildErrorBody(404, "Key not found"), { status: 404 });
- }
-
- return NextResponse.json({
- keyId: key.id,
- name: typeof key.name === "string" ? key.name : "",
- count: getDeviceCount(key.id),
- devices: getDeviceDetails(key.id),
- });
- } catch (error) {
- log.error("keys", "Error fetching API key devices", error);
- return NextResponse.json(buildErrorBody(500, sanitizeErrorMessage(error)), { status: 500 });
- }
-}
diff --git a/src/app/api/oauth/codex/import-token/route.ts b/src/app/api/oauth/codex/import-token/route.ts
deleted file mode 100644
index 6706f2b5a5..0000000000
--- a/src/app/api/oauth/codex/import-token/route.ts
+++ /dev/null
@@ -1,103 +0,0 @@
-import { NextResponse } from "next/server";
-import { z } from "zod";
-import { extractCodexAccountInfo } from "@/lib/oauth/services/codexImport";
-import { createProviderConnection } from "@/models";
-import { isAuthRequired, isAuthenticated } from "@/shared/utils/apiAuth";
-import { buildErrorBody, sanitizeErrorMessage } from "@omniroute/open-sse/utils/error.ts";
-
-/**
- * POST /api/oauth/codex/import-token
- *
- * Import a Codex (ChatGPT/OpenAI) connection from a bare access token — no
- * refresh token required. Covers users who only have a raw ChatGPT website
- * access token (e.g. copied from devtools/session storage) and have no path
- * through the refresh-token-requiring bulk import at /api/oauth/codex/import.
- *
- * The connection is created with authType "access_token": with no refresh
- * token, the executor's refreshCredentials() degrades to returning null on
- * expiry (forcing re-auth) instead of attempting a refresh-token exchange —
- * see open-sse/executors/codex.ts.
- *
- * Body: `{ accessToken: string, name?: string }`
- *
- * Inspired-by: https://github.com/decolua/9router/pull/1290
- */
-
-const bodySchema = z.object({
- accessToken: z.string().trim().min(1, "accessToken is required"),
- name: z.string().trim().min(1).optional(),
-});
-
-async function requireAuth(request: Request): Promise<NextResponse | null> {
- if (!(await isAuthRequired(request))) return null;
- if (await isAuthenticated(request)) return null;
- return NextResponse.json(buildErrorBody(401, "Unauthorized"), { status: 401 });
-}
-
-export async function POST(request: Request) {
- const authResponse = await requireAuth(request);
- if (authResponse) return authResponse;
-
- let rawBody: unknown;
- try {
- rawBody = await request.json();
- } catch {
- return NextResponse.json(buildErrorBody(400, "Invalid or empty JSON body"), { status: 400 });
- }
-
- const parsed = bodySchema.safeParse(rawBody);
- if (!parsed.success) {
- return NextResponse.json(
- buildErrorBody(400, parsed.error.issues[0]?.message ?? "Invalid request body"),
- { status: 400 }
- );
- }
-
- const { accessToken, name } = parsed.data;
- const info = extractCodexAccountInfo(accessToken);
-
- if (!info.email && !info.chatgptAccountId && !name) {
- return NextResponse.json(
- buildErrorBody(
- 400,
- "Could not decode any account info from the access token and no name was provided"
- ),
- { status: 400 }
- );
- }
-
- const providerSpecificData: Record<string, string> = {};
- if (info.chatgptAccountId) providerSpecificData.chatgptAccountId = info.chatgptAccountId;
- if (info.chatgptPlanType) providerSpecificData.chatgptPlanType = info.chatgptPlanType;
-
- try {
- const connection = await createProviderConnection({
- provider: "codex",
- authType: "access_token",
- accessToken,
- email: info.email,
- name: name || info.email,
- testStatus: "active",
- isActive: true,
- ...(Object.keys(providerSpecificData).length > 0 ? { providerSpecificData } : {}),
- });
-
- return NextResponse.json({
- success: true,
- connection: {
- id: connection.id,
- provider: connection.provider,
- email: connection.email,
- name: connection.name,
- },
- });
- } catch (error) {
- return NextResponse.json(
- buildErrorBody(
- 500,
- sanitizeErrorMessage(error instanceof Error ? error.message : String(error))
- ),
- { status: 500 }
- );
- }
-}
diff --git a/src/app/api/provider-nodes/[id]/route.ts b/src/app/api/provider-nodes/[id]/route.ts
index eef4803372..8512a94e19 100644
--- a/src/app/api/provider-nodes/[id]/route.ts
+++ b/src/app/api/provider-nodes/[id]/route.ts
@@ -56,8 +56,7 @@ export async function PUT(request: Request, { params }: { params: Promise<{ id:
if (isValidationFailure(validation)) {
return NextResponse.json({ error: validation.error }, { status: 400 });
}
- const { name, prefix, apiType, baseUrl, chatPath, modelsPath, customHeaders, iconUrl } =
- validation.data;
+ const { name, prefix, apiType, baseUrl, chatPath, modelsPath, customHeaders } = validation.data;
const node: any = await getProviderNodeById(id);
if (!node) {
@@ -94,9 +93,6 @@ export async function PUT(request: Request, { params }: { params: Promise<{ id:
baseUrl: sanitizedBaseUrl,
chatPath: chatPath || null,
modelsPath: isClaudeCodeCompatibleProvider(id) ? null : modelsPath || null,
- // #2166: explicit null (not omission) so an empty submission clears a
- // previously stored custom icon.
- iconUrl: iconUrl?.trim() || null,
customHeaders: customHeaders || null,
};
diff --git a/src/app/api/provider-nodes/route.ts b/src/app/api/provider-nodes/route.ts
index 87bb5330b2..10871381da 100644
--- a/src/app/api/provider-nodes/route.ts
+++ b/src/app/api/provider-nodes/route.ts
@@ -79,7 +79,6 @@ export async function POST(request) {
chatPath,
modelsPath,
customHeaders,
- iconUrl,
} = validation.data;
// Determine type
@@ -99,7 +98,6 @@ export async function POST(request) {
name: name.trim(),
chatPath: chatPath || null,
modelsPath: modelsPath || null,
- iconUrl: iconUrl?.trim() || null,
customHeaders: customHeaders || null,
});
return NextResponse.json({ node }, { status: 201 });
@@ -129,7 +127,6 @@ export async function POST(request) {
name: name.trim(),
chatPath: chatPath || null,
modelsPath: compatMode === "cc" ? null : modelsPath || null,
- iconUrl: iconUrl?.trim() || null,
customHeaders: customHeaders || null,
});
return NextResponse.json({ node }, { status: 201 });
diff --git a/src/app/api/providers/[id]/models/discovery/providerModelsConfig.ts b/src/app/api/providers/[id]/models/discovery/providerModelsConfig.ts
index b7bb1940a8..ab13717427 100644
--- a/src/app/api/providers/[id]/models/discovery/providerModelsConfig.ts
+++ b/src/app/api/providers/[id]/models/discovery/providerModelsConfig.ts
@@ -1,7 +1,6 @@
import { getAntigravityModelsDiscoveryUrls } from "@omniroute/open-sse/config/antigravityUpstream.ts";
import { getAntigravityHeaders } from "@omniroute/open-sse/services/antigravityHeaders.ts";
import { parseGeminiModelsList } from "@/lib/providerModels/geminiModelsParser";
-import { filterClinepassModels } from "@omniroute/open-sse/services/clinepassModels.ts";
import { normalizeOpenAiLikeModelsResponse } from "./normalizers";
export type ProviderModelsConfigEntry = {
@@ -77,35 +76,6 @@ export const PROVIDER_MODELS_CONFIG: Record<string, ProviderModelsConfigEntry> =
.filter((m: any) => m.id);
},
},
- // #5858 follow-up: kimi-web (cookie provider) on the international domain.
- // `GetAvailableModels` returns the model list as a plain JSON envelope
- // (no Connect framing on either request or response — only the chat
- // completion endpoint uses the 5-byte envelope). Auth: Bearer JWT extracted
- // from the `kimi-auth` cookie the user pasted. Agent variants
- // (`k2d6-agent*`) need a different scenario + agent fields this executor
- // doesn't shape, so they're filtered out.
- "kimi-web": {
- url: "https://www.kimi.com/apiv2/kimi.gateway.config.v1.ConfigService/GetAvailableModels",
- method: "GET",
- headers: { accept: "application/json, text/plain, */*", "Content-Type": "application/json" },
- authHeader: "Authorization",
- authPrefix: "Bearer ",
- parseResponse: (data) => {
- const list = (data?.availableModels || []) as Array<{
- key?: string;
- displayName?: string;
- thinking?: boolean;
- }>;
- return list
- .filter((m) => typeof m.key === "string" && !m.key?.includes("agent"))
- .map((m) => ({
- id: m.key as string,
- name: m.displayName || (m.key as string),
- supportsReasoning: !!m.thinking,
- owned_by: "kimi",
- }));
- },
- },
antigravity: {
url: getAntigravityModelsDiscoveryUrls()[0],
method: "POST",
@@ -276,16 +246,6 @@ export const PROVIDER_MODELS_CONFIG: Record<string, ProviderModelsConfigEntry> =
authPrefix: "Bearer ",
parseResponse: (data) => data.data || data.models || [],
},
- // ClinePass (BYOK apikey gateway) — same host as OAuth `cline`, but only the
- // `cline-pass/*` namespace is surfaced (filterClinepassModels).
- clinepass: {
- url: "https://api.cline.bot/api/v1/models",
- method: "GET",
- headers: { "Content-Type": "application/json" },
- authHeader: "Authorization",
- authPrefix: "Bearer ",
- parseResponse: (data) => filterClinepassModels(Array.isArray(data) ? data : data?.data),
- },
cohere: {
url: "https://api.cohere.com/v2/models",
method: "GET",
diff --git a/src/app/api/providers/[id]/models/discovery/providerSets.ts b/src/app/api/providers/[id]/models/discovery/providerSets.ts
index 4bf76ecb19..d98e4325f7 100644
--- a/src/app/api/providers/[id]/models/discovery/providerSets.ts
+++ b/src/app/api/providers/[id]/models/discovery/providerSets.ts
@@ -56,14 +56,6 @@ export const NAMED_OPENAI_STYLE_PROVIDERS = new Set([
// DGrid is an OpenAI-compatible gateway whose default seed is the free auto-router;
// the full model catalog is discovered live from https://api.dgrid.ai/v1/models.
"dgrid",
- // b.ai is an OpenAI-compatible LLM gateway with no static seed — it proxies many
- // upstream models (GPT, Claude, Gemini, MiniMax, Kimi, GLM...) behind one key, so the
- // full catalog is discovered live from https://api.b.ai/v1/models.
- "bai",
- // Qiniu (七牛云 AI inference) is an OpenAI-compatible gateway with no static seed —
- // it proxies many upstream models (DeepSeek, Claude, Kimi...) behind one key, so the
- // full catalog is discovered live from https://api.qnaigc.com/v1/models.
- "qiniu",
]);
export function isNamedOpenAIStyleProvider(provider: string): boolean {
diff --git a/src/app/api/providers/[id]/models/route.ts b/src/app/api/providers/[id]/models/route.ts
index 6d1448d803..c217c45636 100755
--- a/src/app/api/providers/[id]/models/route.ts
+++ b/src/app/api/providers/[id]/models/route.ts
@@ -533,14 +533,7 @@ export async function GET(
base = base.slice(0, -17);
} else if (base.endsWith("/completions")) {
base = base.slice(0, -12);
- }
-
- // Strip trailing /v1 unconditionally so the next step re-adds it exactly once.
- // Without this, baseUrls that embed /v1 (e.g. "https://api.airforce/v1/chat/completions")
- // become "…/v1" after stripping "/chat/completions", and then appending "/v1/models"
- // produces "…/v1/v1/models" — a 308 redirect that blocked model fetch (#5899).
- // Guard against a literal "scheme://v1" authority so we never strip the host itself.
- if (base.endsWith("/v1") && !base.endsWith("://v1")) {
+ } else if (base.endsWith("/v1")) {
base = base.slice(0, -3);
}
@@ -583,11 +576,6 @@ export async function GET(
}
} catch (err: any) {
if (err.message === "auth_failed") break; // Don't try other endpoints if auth failed
-
- if (err?.code === "REDIRECT_BLOCKED") {
- continue; // Try next endpoint
- }
-
const status = getSafeOutboundFetchErrorStatus(err);
if (status) {
throw err;
@@ -1729,11 +1717,7 @@ export async function GET(
base = base.slice(0, -"/chat/completions".length);
} else if (base.endsWith("/completions")) {
base = base.slice(0, -"/completions".length);
- }
- // Strip a trailing /v1 unconditionally (same #5899 double-prefix guard as the
- // discovery path above): a customBaseUrl like ".../v1/chat/completions" would
- // otherwise leave base as ".../v1" and produce ".../v1/v1/models" below.
- if (base.endsWith("/v1") && !base.endsWith("://v1")) {
+ } else if (base.endsWith("/v1")) {
base = base.slice(0, -"/v1".length);
}
url = `${base}/v1/models`;
diff --git a/src/app/api/providers/bulk-web-session/route.ts b/src/app/api/providers/bulk-web-session/route.ts
index 6ef99acb73..48196ab1a5 100644
--- a/src/app/api/providers/bulk-web-session/route.ts
+++ b/src/app/api/providers/bulk-web-session/route.ts
@@ -16,7 +16,6 @@ import {
requiresWebSessionCredential,
getWebSessionCredentialRequirement,
hasUsableWebSessionCredential,
- resolveWebSessionImportApiKey,
} from "@/shared/providers/webSessionCredentials";
export async function POST(request: Request) {
@@ -60,7 +59,10 @@ export async function POST(request: Request) {
for (let i = 0; i < entries.length; i++) {
const entry = entries[i];
try {
- const providerSpecificData = buildProviderSpecificData(requirement, entry.credential);
+ const providerSpecificData = buildProviderSpecificData(
+ requirement,
+ entry.credential
+ );
if (!hasUsableWebSessionCredential(provider, providerSpecificData)) {
throw new Error(
@@ -72,11 +74,7 @@ export async function POST(request: Request) {
provider,
authType: "cookie",
name: entry.name,
- // token-kind providers (deepseek-web, copilot-web, …) are read from apiKey
- // by both the validator and the executor; cookie-kind stays null and is read
- // from providerSpecificData.cookie. Without this, imported token connections
- // were never recognized.
- apiKey: resolveWebSessionImportApiKey(requirement, entry.credential),
+ apiKey: null,
priority: priority || 1,
globalPriority: globalPriority || null,
defaultModel: null,
diff --git a/src/app/api/services/[name]/logs/route.ts b/src/app/api/services/[name]/logs/route.ts
index 697302c63f..c3c3a93a9a 100644
--- a/src/app/api/services/[name]/logs/route.ts
+++ b/src/app/api/services/[name]/logs/route.ts
@@ -37,15 +37,6 @@ async function getOrInitNamedSupervisor(name: string) {
return getOrInitSupervisor();
}
- if (name === "mux") {
- const { getOrInitSupervisor } = await import("../../mux/_lib");
- return getOrInitSupervisor();
- }
- if (name === "bifrost") {
- const { getOrInitSupervisor } = await import("../../bifrost/_lib");
- return getOrInitSupervisor();
- }
-
return null;
}
diff --git a/src/app/api/services/bifrost/_lib.ts b/src/app/api/services/bifrost/_lib.ts
deleted file mode 100644
index 93d3b8ad8d..0000000000
--- a/src/app/api/services/bifrost/_lib.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-/**
- * Shared helpers for /api/services/bifrost/* route handlers.
- * Creates a supervisor on demand if bootstrap hasn't registered one yet.
- */
-
-import { getSupervisor, registerSupervisor } from "@/lib/services/registry";
-import { ServiceSupervisor } from "@/lib/services/ServiceSupervisor";
-import { resolveSpawnArgs, BIFROST_DEFAULT_PORT } from "@/lib/services/installers/bifrost";
-
-const TOOL = "bifrost";
-const PORT = parseInt(process.env.BIFROST_PORT ?? String(BIFROST_DEFAULT_PORT), 10);
-
-export async function getOrInitSupervisor(): Promise<ServiceSupervisor> {
- const existing = getSupervisor(TOOL);
- if (existing) return existing;
-
- const sup = new ServiceSupervisor({
- tool: TOOL,
- port: PORT,
- spawnArgs: () => resolveSpawnArgs(PORT),
- healthUrl: () => `http://127.0.0.1:${PORT}/v1/models`,
- healthIntervalMs: 5_000,
- stopTimeoutMs: 15_000,
- logsBufferBytes: 5_242_880,
- });
-
- registerSupervisor(sup);
- return sup;
-}
diff --git a/src/app/api/services/bifrost/auto-start/route.ts b/src/app/api/services/bifrost/auto-start/route.ts
deleted file mode 100644
index 3123f6cb13..0000000000
--- a/src/app/api/services/bifrost/auto-start/route.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import { z } from "zod";
-import { updateServiceField } from "@/lib/db/versionManager";
-import { createErrorResponse } from "@/lib/api/errorResponse";
-import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error";
-
-const BodySchema = z.object({ enabled: z.boolean() });
-
-export async function POST(request: Request): Promise<Response> {
- let body: unknown;
- try {
- body = await request.json();
- } catch {
- return createErrorResponse({ status: 400, message: "Invalid JSON body" });
- }
-
- const parsed = BodySchema.safeParse(body);
- if (!parsed.success) {
- return createErrorResponse({ status: 400, message: parsed.error.message });
- }
-
- try {
- await updateServiceField("bifrost", "autoStart", parsed.data.enabled);
- return new Response(null, { status: 204 });
- } catch (err) {
- const msg = sanitizeErrorMessage(err instanceof Error ? err.message : String(err));
- return createErrorResponse({ status: 500, message: msg });
- }
-}
diff --git a/src/app/api/services/bifrost/install/route.ts b/src/app/api/services/bifrost/install/route.ts
deleted file mode 100644
index 28e39f5149..0000000000
--- a/src/app/api/services/bifrost/install/route.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import { install } from "@/lib/services/installers/bifrost";
-import { handleServiceInstall } from "@/app/api/services/_shared/installRoute";
-
-export async function POST(request: Request): Promise<Response> {
- return handleServiceInstall(request, install);
-}
diff --git a/src/app/api/services/bifrost/restart/route.ts b/src/app/api/services/bifrost/restart/route.ts
deleted file mode 100644
index acf74b287a..0000000000
--- a/src/app/api/services/bifrost/restart/route.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { getServiceRow } from "@/lib/db/versionManager";
-import { getOrInitSupervisor } from "../_lib";
-import { createErrorResponse } from "@/lib/api/errorResponse";
-import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error";
-
-const TOOL = "bifrost";
-
-export async function POST(): Promise<Response> {
- try {
- const row = await getServiceRow(TOOL);
- if (!row || row.status === "not_installed") {
- return createErrorResponse({ status: 409, message: "Bifrost não está instalado." });
- }
-
- const sup = await getOrInitSupervisor();
- const status = await sup.restart();
- return Response.json(status);
- } catch (err) {
- const msg = sanitizeErrorMessage(err instanceof Error ? err.message : String(err));
- return createErrorResponse({ status: 503, message: msg });
- }
-}
diff --git a/src/app/api/services/bifrost/start/route.ts b/src/app/api/services/bifrost/start/route.ts
deleted file mode 100644
index ad8e0e935a..0000000000
--- a/src/app/api/services/bifrost/start/route.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { getServiceRow } from "@/lib/db/versionManager";
-import { getOrInitSupervisor } from "../_lib";
-import { createErrorResponse } from "@/lib/api/errorResponse";
-import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error";
-
-const TOOL = "bifrost";
-
-export async function POST(): Promise<Response> {
- try {
- const row = await getServiceRow(TOOL);
- if (!row || row.status === "not_installed") {
- return createErrorResponse({ status: 409, message: "Bifrost não está instalado." });
- }
-
- const sup = await getOrInitSupervisor();
- const status = await sup.start();
- return Response.json(status);
- } catch (err) {
- const msg = sanitizeErrorMessage(err instanceof Error ? err.message : String(err));
- return createErrorResponse({ status: 503, message: msg });
- }
-}
diff --git a/src/app/api/services/bifrost/status/route.ts b/src/app/api/services/bifrost/status/route.ts
deleted file mode 100644
index bc6a1631d7..0000000000
--- a/src/app/api/services/bifrost/status/route.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { getSupervisor } from "@/lib/services/registry";
-import { getServiceRow } from "@/lib/db/versionManager";
-import {
- getInstalledVersion,
- getLatestVersion,
- BIFROST_DEFAULT_PORT,
-} from "@/lib/services/installers/bifrost";
-import { createErrorResponse } from "@/lib/api/errorResponse";
-import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error";
-
-const TOOL = "bifrost";
-
-export async function GET(): Promise<Response> {
- try {
- const sup = getSupervisor(TOOL);
- const row = await getServiceRow(TOOL);
-
- const liveStatus = sup?.getStatus() ?? null;
- const installedVersion = await getInstalledVersion();
- const latestVersion = await getLatestVersion();
-
- return Response.json({
- tool: TOOL,
- state: liveStatus?.state ?? row?.status ?? "unknown",
- pid: liveStatus?.pid ?? null,
- port: liveStatus?.port ?? row?.port ?? BIFROST_DEFAULT_PORT,
- health: liveStatus?.health ?? "unknown",
- startedAt: liveStatus?.startedAt ?? null,
- lastError: liveStatus?.lastError ?? row?.errorMessage ?? null,
- installedVersion: installedVersion ?? row?.installedVersion ?? null,
- latestVersion,
- updateAvailable: !!installedVersion && !!latestVersion && installedVersion !== latestVersion,
- autoStart: row?.autoStart ?? false,
- });
- } catch (err) {
- const msg = sanitizeErrorMessage(err instanceof Error ? err.message : String(err));
- return createErrorResponse({ status: 500, message: msg });
- }
-}
diff --git a/src/app/api/services/bifrost/stop/route.ts b/src/app/api/services/bifrost/stop/route.ts
deleted file mode 100644
index b54bfde2e5..0000000000
--- a/src/app/api/services/bifrost/stop/route.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { getSupervisor } from "@/lib/services/registry";
-import { createErrorResponse } from "@/lib/api/errorResponse";
-import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error";
-
-const TOOL = "bifrost";
-
-export async function POST(): Promise<Response> {
- try {
- const sup = getSupervisor(TOOL);
- if (!sup) {
- return Response.json({ tool: TOOL, state: "stopped" });
- }
- const status = await sup.stop();
- return Response.json(status);
- } catch (err) {
- const msg = sanitizeErrorMessage(err instanceof Error ? err.message : String(err));
- return createErrorResponse({ status: 500, message: msg });
- }
-}
diff --git a/src/app/api/services/bifrost/update/route.ts b/src/app/api/services/bifrost/update/route.ts
deleted file mode 100644
index e5abac79af..0000000000
--- a/src/app/api/services/bifrost/update/route.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import { getSupervisor } from "@/lib/services/registry";
-import { getOrInitSupervisor } from "../_lib";
-import {
- getInstalledVersion,
- getLatestVersion,
- update as downloadUpdate,
-} from "@/lib/services/installers/bifrost";
-import { createErrorResponse } from "@/lib/api/errorResponse";
-import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error";
-
-export async function POST(): Promise<Response> {
- try {
- const [installed, latest] = await Promise.all([getInstalledVersion(), getLatestVersion()]);
-
- if (installed && latest && installed === latest) {
- return Response.json({ updated: false, installedVersion: installed, latestVersion: latest });
- }
-
- const sup = getSupervisor("bifrost");
- const wasRunning = sup?.getStatus().state === "running";
-
- if (wasRunning && sup) {
- await sup.stop();
- }
-
- const result = await downloadUpdate();
-
- if (wasRunning) {
- const freshSup = await getOrInitSupervisor();
- await freshSup.start().catch((err: unknown) => {
- const msg = err instanceof Error ? err.message : String(err);
- console.warn("[Services] Could not restart bifrost after update:", msg);
- });
- }
-
- return Response.json({
- updated: true,
- oldVersion: installed ?? null,
- newVersion: result.installedVersion,
- });
- } catch (err) {
- const msg = sanitizeErrorMessage(err instanceof Error ? err.message : String(err));
- return createErrorResponse({ status: 500, message: msg });
- }
-}
diff --git a/src/app/api/services/mux/_lib.ts b/src/app/api/services/mux/_lib.ts
deleted file mode 100644
index 49b1ef672d..0000000000
--- a/src/app/api/services/mux/_lib.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-/**
- * Shared helpers for /api/services/mux/* route handlers.
- * Creates a supervisor on demand if bootstrap hasn't registered one yet.
- */
-
-import { getSupervisor, registerSupervisor } from "@/lib/services/registry";
-import { ServiceSupervisor } from "@/lib/services/ServiceSupervisor";
-import { resolveSpawnArgs, MUX_DEFAULT_PORT } from "@/lib/services/installers/mux";
-import { getOrCreateApiKey } from "@/lib/services/apiKey";
-
-const TOOL = "mux";
-const PORT = parseInt(process.env.MUX_SERVICE_PORT ?? String(MUX_DEFAULT_PORT), 10);
-
-export async function getOrInitSupervisor(): Promise<ServiceSupervisor> {
- const existing = getSupervisor(TOOL);
- if (existing) return existing;
-
- const apiKey = await getOrCreateApiKey(TOOL);
-
- const sup = new ServiceSupervisor({
- tool: TOOL,
- port: PORT,
- spawnArgs: () => resolveSpawnArgs(apiKey, PORT),
- healthUrl: () => `http://127.0.0.1:${PORT}/health`,
- healthIntervalMs: 5_000,
- stopTimeoutMs: 15_000,
- logsBufferBytes: 5_242_880,
- });
-
- registerSupervisor(sup);
- return sup;
-}
diff --git a/src/app/api/services/mux/auto-start/route.ts b/src/app/api/services/mux/auto-start/route.ts
deleted file mode 100644
index 1feb460178..0000000000
--- a/src/app/api/services/mux/auto-start/route.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import { z } from "zod";
-import { updateServiceField } from "@/lib/db/versionManager";
-import { createErrorResponse } from "@/lib/api/errorResponse";
-import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error";
-
-const BodySchema = z.object({ enabled: z.boolean() });
-
-export async function POST(request: Request): Promise<Response> {
- let body: unknown;
- try {
- body = await request.json();
- } catch {
- return createErrorResponse({ status: 400, message: "Invalid JSON body" });
- }
-
- const parsed = BodySchema.safeParse(body);
- if (!parsed.success) {
- return createErrorResponse({ status: 400, message: parsed.error.message });
- }
-
- try {
- await updateServiceField("mux", "autoStart", parsed.data.enabled);
- return new Response(null, { status: 204 });
- } catch (err) {
- const msg = sanitizeErrorMessage(err instanceof Error ? err.message : String(err));
- return createErrorResponse({ status: 500, message: msg });
- }
-}
diff --git a/src/app/api/services/mux/install/route.ts b/src/app/api/services/mux/install/route.ts
deleted file mode 100644
index b895a956f6..0000000000
--- a/src/app/api/services/mux/install/route.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import { install } from "@/lib/services/installers/mux";
-import { handleServiceInstall } from "@/app/api/services/_shared/installRoute";
-
-export async function POST(request: Request): Promise<Response> {
- return handleServiceInstall(request, install);
-}
diff --git a/src/app/api/services/mux/restart/route.ts b/src/app/api/services/mux/restart/route.ts
deleted file mode 100644
index bcfaec3508..0000000000
--- a/src/app/api/services/mux/restart/route.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { getServiceRow } from "@/lib/db/versionManager";
-import { getOrInitSupervisor } from "../_lib";
-import { createErrorResponse } from "@/lib/api/errorResponse";
-import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error";
-
-const TOOL = "mux";
-
-export async function POST(): Promise<Response> {
- try {
- const row = await getServiceRow(TOOL);
- if (!row || row.status === "not_installed") {
- return createErrorResponse({ status: 409, message: "Mux não está instalado." });
- }
-
- const sup = await getOrInitSupervisor();
- const status = await sup.restart();
- return Response.json(status);
- } catch (err) {
- const msg = sanitizeErrorMessage(err instanceof Error ? err.message : String(err));
- return createErrorResponse({ status: 503, message: msg });
- }
-}
diff --git a/src/app/api/services/mux/start/route.ts b/src/app/api/services/mux/start/route.ts
deleted file mode 100644
index 92cfebb6e8..0000000000
--- a/src/app/api/services/mux/start/route.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { getServiceRow } from "@/lib/db/versionManager";
-import { getOrInitSupervisor } from "../_lib";
-import { createErrorResponse } from "@/lib/api/errorResponse";
-import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error";
-
-const TOOL = "mux";
-
-export async function POST(): Promise<Response> {
- try {
- const row = await getServiceRow(TOOL);
- if (!row || row.status === "not_installed") {
- return createErrorResponse({ status: 409, message: "Mux não está instalado." });
- }
-
- const sup = await getOrInitSupervisor();
- const status = await sup.start();
- return Response.json(status);
- } catch (err) {
- const msg = sanitizeErrorMessage(err instanceof Error ? err.message : String(err));
- return createErrorResponse({ status: 503, message: msg });
- }
-}
diff --git a/src/app/api/services/mux/status/route.ts b/src/app/api/services/mux/status/route.ts
deleted file mode 100644
index 512ca97b43..0000000000
--- a/src/app/api/services/mux/status/route.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { getSupervisor } from "@/lib/services/registry";
-import { getServiceRow } from "@/lib/db/versionManager";
-import {
- getInstalledVersion,
- getLatestVersion,
- MUX_DEFAULT_PORT,
-} from "@/lib/services/installers/mux";
-import { createErrorResponse } from "@/lib/api/errorResponse";
-import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error";
-
-const TOOL = "mux";
-
-export async function GET(): Promise<Response> {
- try {
- const sup = getSupervisor(TOOL);
- const row = await getServiceRow(TOOL);
-
- const liveStatus = sup?.getStatus() ?? null;
- const installedVersion = await getInstalledVersion();
- const latestVersion = await getLatestVersion();
-
- return Response.json({
- tool: TOOL,
- state: liveStatus?.state ?? row?.status ?? "unknown",
- pid: liveStatus?.pid ?? null,
- port: liveStatus?.port ?? row?.port ?? MUX_DEFAULT_PORT,
- health: liveStatus?.health ?? "unknown",
- startedAt: liveStatus?.startedAt ?? null,
- lastError: liveStatus?.lastError ?? row?.errorMessage ?? null,
- installedVersion: installedVersion ?? row?.installedVersion ?? null,
- latestVersion,
- updateAvailable: !!installedVersion && !!latestVersion && installedVersion !== latestVersion,
- autoStart: row?.autoStart ?? false,
- });
- } catch (err) {
- const msg = sanitizeErrorMessage(err instanceof Error ? err.message : String(err));
- return createErrorResponse({ status: 500, message: msg });
- }
-}
diff --git a/src/app/api/services/mux/stop/route.ts b/src/app/api/services/mux/stop/route.ts
deleted file mode 100644
index 5c753a3d92..0000000000
--- a/src/app/api/services/mux/stop/route.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { getSupervisor } from "@/lib/services/registry";
-import { createErrorResponse } from "@/lib/api/errorResponse";
-import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error";
-
-const TOOL = "mux";
-
-export async function POST(): Promise<Response> {
- try {
- const sup = getSupervisor(TOOL);
- if (!sup) {
- return Response.json({ tool: TOOL, state: "stopped" });
- }
- const status = await sup.stop();
- return Response.json(status);
- } catch (err) {
- const msg = sanitizeErrorMessage(err instanceof Error ? err.message : String(err));
- return createErrorResponse({ status: 500, message: msg });
- }
-}
diff --git a/src/app/api/services/mux/update/route.ts b/src/app/api/services/mux/update/route.ts
deleted file mode 100644
index 9f25629286..0000000000
--- a/src/app/api/services/mux/update/route.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import { getSupervisor } from "@/lib/services/registry";
-import { getOrInitSupervisor } from "../_lib";
-import {
- getInstalledVersion,
- getLatestVersion,
- update as downloadUpdate,
-} from "@/lib/services/installers/mux";
-import { createErrorResponse } from "@/lib/api/errorResponse";
-import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error";
-
-export async function POST(): Promise<Response> {
- try {
- const [installed, latest] = await Promise.all([getInstalledVersion(), getLatestVersion()]);
-
- if (installed && latest && installed === latest) {
- return Response.json({ updated: false, installedVersion: installed, latestVersion: latest });
- }
-
- const sup = getSupervisor("mux");
- const wasRunning = sup?.getStatus().state === "running";
-
- if (wasRunning && sup) {
- await sup.stop();
- }
-
- const result = await downloadUpdate();
-
- if (wasRunning) {
- const freshSup = await getOrInitSupervisor();
- await freshSup.start().catch((err: unknown) => {
- const msg = err instanceof Error ? err.message : String(err);
- console.warn("[Services] Could not restart mux after update:", msg);
- });
- }
-
- return Response.json({
- updated: true,
- oldVersion: installed ?? null,
- newVersion: result.installedVersion,
- });
- } catch (err) {
- const msg = sanitizeErrorMessage(err instanceof Error ? err.message : String(err));
- return createErrorResponse({ status: 500, message: msg });
- }
-}
diff --git a/src/app/api/settings/authz-inventory/route.ts b/src/app/api/settings/authz-inventory/route.ts
index 4b309a992e..880f1af9cb 100644
--- a/src/app/api/settings/authz-inventory/route.ts
+++ b/src/app/api/settings/authz-inventory/route.ts
@@ -9,7 +9,6 @@ import {
LOCAL_ONLY_MANAGE_SCOPE_BYPASS_PREFIXES,
SPAWN_CAPABLE_PREFIXES,
} from "@/server/authz/routeGuard";
-import { getCorsStatus } from "@/server/cors/origins";
/**
* Static MANAGEMENT-tier example prefixes. Render-only — never consulted by
@@ -154,9 +153,6 @@ export async function GET(request: Request) {
bypassEnabled,
bypassPrefixes,
spawnCapablePrefixes: [...SPAWN_CAPABLE_PREFIXES],
- // #5602: surface the effective CORS allowlist so the dashboard can warn
- // when `CORS_ALLOW_ALL=true` is set (wildcard origins). See docs/security/CORS.md.
- cors: getCorsStatus(),
});
} catch (error) {
console.log("Error loading authz inventory:", error);
diff --git a/src/app/api/settings/proxies/auto-test/route.ts b/src/app/api/settings/proxies/auto-test/route.ts
deleted file mode 100644
index 1f657d3b1f..0000000000
--- a/src/app/api/settings/proxies/auto-test/route.ts
+++ /dev/null
@@ -1,126 +0,0 @@
-import { z } from "zod";
-import { deleteProxyById, listProxies, updateProxy } from "@/lib/localDb";
-import { createErrorResponseFromUnknown } from "@/lib/api/errorResponse";
-import { requireManagementAuth } from "@/lib/api/requireManagementAuth";
-import { createProxyDispatcher } from "@omniroute/open-sse/utils/proxyDispatcher";
-import { fetch as undiciFetch } from "undici";
-import { isValidationFailure, validateBody } from "@/shared/validation/helpers";
-import { createErrorResponse } from "@/lib/api/errorResponse";
-
-const TEST_TIMEOUT_MS = 5000;
-// Reachability probe target. Configurable so operators can point it at an
-// internal/self-hosted endpoint instead of the public default.
-const TEST_URL = process.env.PROXY_HEALTH_TEST_URL || "https://httpbin.org/ip";
-const CONCURRENCY = 10;
-
-const autoTestSchema = z.object({
- ids: z.array(z.string()).optional(),
- autoRemove: z.boolean().optional().default(false),
-});
-
-interface TestResult {
- proxyId: string;
- host: string;
- port: number;
- alive: boolean;
- latencyMs: number | null;
- error?: string;
-}
-
-async function testSingleProxy(proxy: { id: string; type: string; host: string; port: number }): Promise<TestResult> {
- const proxyUrl = `${proxy.type}://${proxy.host}:${proxy.port}`;
- const start = Date.now();
- const controller = new AbortController();
- const timeout = setTimeout(() => controller.abort(), TEST_TIMEOUT_MS);
-
- try {
- const dispatcher = createProxyDispatcher(proxyUrl);
- const resp = await undiciFetch(TEST_URL, {
- method: "HEAD",
- signal: controller.signal,
- dispatcher,
- headers: { "User-Agent": "OmniRoute/1.0" },
- });
- const latencyMs = Date.now() - start;
- const alive = resp.status < 500;
- await updateProxy(proxy.id, { status: alive ? "active" : "inactive" }).catch(() => {});
- return { proxyId: proxy.id, host: proxy.host, port: proxy.port, alive, latencyMs };
- } catch (err) {
- const latencyMs = Date.now() - start;
- await updateProxy(proxy.id, { status: "inactive" }).catch(() => {});
- return {
- proxyId: proxy.id,
- host: proxy.host,
- port: proxy.port,
- alive: false,
- latencyMs,
- error: err instanceof Error ? err.message : "Connection failed",
- };
- } finally {
- clearTimeout(timeout);
- }
-}
-
-/**
- * POST /api/settings/proxies/auto-test
- * Tests proxy reachability. If autoRemove is true, removes dead proxies.
- */
-export async function POST(request: Request) {
- const authError = await requireManagementAuth(request);
- if (authError) return authError;
-
- let rawBody: unknown;
- try {
- rawBody = await request.json();
- } catch {
- rawBody = {};
- }
-
- const validation = validateBody(autoTestSchema, rawBody);
- if (isValidationFailure(validation)) {
- return createErrorResponse({ status: 400, message: validation.error.message, type: "invalid_request" });
- }
-
- const { ids: specificIds, autoRemove } = validation.data;
-
- try {
- const allProxies = await listProxies({ includeSecrets: false });
- const proxiesToTest = specificIds
- ? allProxies.filter((p) => specificIds.includes(p.id))
- : allProxies;
-
- if (proxiesToTest.length === 0) {
- return Response.json({ results: [], removed: [] });
- }
-
- const results: TestResult[] = [];
- for (let i = 0; i < proxiesToTest.length; i += CONCURRENCY) {
- const batch = proxiesToTest.slice(i, i + CONCURRENCY);
- const batchResults = await Promise.allSettled(batch.map((proxy) => testSingleProxy(proxy)));
- for (const result of batchResults) {
- if (result.status === "fulfilled") results.push(result.value);
- }
- }
-
- const removed: string[] = [];
- if (autoRemove) {
- for (const r of results) {
- if (!r.alive) {
- try {
- if (await deleteProxyById(r.proxyId, { force: true })) removed.push(r.proxyId);
- } catch { /* skip */ }
- }
- }
- }
-
- return Response.json({
- tested: results.length,
- alive: results.filter((r) => r.alive).length,
- dead: results.filter((r) => !r.alive).length,
- removed: removed.length,
- results,
- });
- } catch (error) {
- return createErrorResponseFromUnknown(error, "Failed to auto-test proxies");
- }
-}
diff --git a/src/app/api/settings/proxies/batch-delete/route.ts b/src/app/api/settings/proxies/batch-delete/route.ts
deleted file mode 100644
index ac343fb953..0000000000
--- a/src/app/api/settings/proxies/batch-delete/route.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-import { z } from "zod";
-import { deleteProxyById } from "@/lib/localDb";
-import { createErrorResponse, createErrorResponseFromUnknown } from "@/lib/api/errorResponse";
-import { requireManagementAuth } from "@/lib/api/requireManagementAuth";
-import { clearDispatcherCache } from "@omniroute/open-sse/utils/proxyDispatcher";
-import { isValidationFailure, validateBody } from "@/shared/validation/helpers";
-
-const batchDeleteSchema = z.object({
- ids: z.array(z.string()).min(1).max(100),
- force: z.boolean().optional().default(false),
-});
-
-/**
- * POST /api/settings/proxies/batch-delete
- * Deletes multiple proxies in a single request.
- */
-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 createErrorResponse({ status: 400, message: "Invalid JSON body", type: "invalid_request" });
- }
-
- const validation = validateBody(batchDeleteSchema, rawBody);
- if (isValidationFailure(validation)) {
- return createErrorResponse({ status: 400, message: validation.error.message, type: "invalid_request" });
- }
-
- const { ids, force } = validation.data;
-
- try {
- const results: Array<{ id: string; success: boolean; error?: string }> = [];
- let deletedCount = 0;
-
- for (const id of ids) {
- try {
- if (await deleteProxyById(id, { force })) {
- results.push({ id, success: true });
- deletedCount++;
- } else {
- results.push({ id, success: false, error: "Proxy not found" });
- }
- } catch (err) {
- results.push({ id, success: false, error: err instanceof Error ? err.message : "Unknown error" });
- }
- }
-
- if (deletedCount > 0) {
- try { clearDispatcherCache(); } catch { /* non-critical */ }
- }
-
- return Response.json({ success: deletedCount > 0, deleted: deletedCount, failed: ids.length - deletedCount, results });
- } catch (error) {
- return createErrorResponseFromUnknown(error, "Failed to batch delete proxies");
- }
-}
diff --git a/src/app/api/settings/purge-usage-history/route.ts b/src/app/api/settings/purge-usage-history/route.ts
deleted file mode 100644
index 63489833e4..0000000000
--- a/src/app/api/settings/purge-usage-history/route.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import { NextResponse } from "next/server";
-import { z } from "zod";
-import { buildErrorBody } from "@omniroute/open-sse/utils/error";
-import { RESET_USAGE_HISTORY_PERIODS, resetUsageHistory } from "@/lib/db/cleanup";
-import { isAuthenticated } from "@/shared/utils/apiAuth";
-import { isValidationFailure, validateBody } from "@/shared/validation/helpers";
-
-export const runtime = "nodejs";
-
-const resetUsageHistorySchema = z.object({
- period: z.enum(RESET_USAGE_HISTORY_PERIODS),
-});
-
-export async function POST(request: Request) {
- if (!(await isAuthenticated(request))) {
- return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
- }
-
- 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 = validateBody(resetUsageHistorySchema, rawBody);
- if (isValidationFailure(validation)) {
- return NextResponse.json({ error: validation.error }, { status: 400 });
- }
-
- try {
- const result = await resetUsageHistory(validation.data.period);
- return NextResponse.json(
- {
- deleted: result.deleted,
- deletedUsageHistory: result.deletedUsageHistory,
- deletedDailySummary: result.deletedDailySummary,
- deletedHourlySummary: result.deletedHourlySummary,
- errors: result.errors,
- },
- { status: result.errors > 0 ? 500 : 200 }
- );
- } catch {
- return NextResponse.json(buildErrorBody(500, "Failed to reset usage history"), {
- status: 500,
- });
- }
-}
diff --git a/src/app/api/v1/audio/translations/route.ts b/src/app/api/v1/audio/translations/route.ts
deleted file mode 100644
index 11dca26ca4..0000000000
--- a/src/app/api/v1/audio/translations/route.ts
+++ /dev/null
@@ -1,129 +0,0 @@
-// Allow large audio/video file uploads — 5min for processing large files (up to 2GB)
-export const maxDuration = 300;
-import { handleAudioTranslation } from "@omniroute/open-sse/handlers/audioTranslation.ts";
-import { getProviderCredentials, clearRecoveredProviderState } from "@/sse/services/auth";
-import {
- parseTranslationModel,
- getTranslationProvider,
- buildDynamicAudioProvider,
- type ProviderNodeRow,
-} from "@omniroute/open-sse/config/audioRegistry.ts";
-import { errorResponse } from "@omniroute/open-sse/utils/error.ts";
-import { HTTP_STATUS } from "@omniroute/open-sse/config/constants.ts";
-import { enforceApiKeyPolicy } from "@/shared/utils/apiKeyPolicy";
-import { getProviderNodes } from "@/lib/localDb";
-import {
- isAllRateLimitedCredentials,
- rateLimitedProviderResponse,
-} from "@/app/api/v1/_shared/rateLimit";
-import { attachOmniRouteMetaToResponse } from "@/domain/omnirouteResponseMeta";
-import { generateRequestId } from "@/shared/utils/requestId";
-
-/**
- * Handle CORS preflight
- */
-export async function OPTIONS() {
- return new Response(null, {
- headers: {
- "Access-Control-Allow-Methods": "POST, OPTIONS",
- "Access-Control-Allow-Headers": "*",
- },
- });
-}
-
-/**
- * POST /v1/audio/translations — translate audio to English text
- * OpenAI Whisper API compatible (multipart/form-data). Unlike
- * /v1/audio/transcriptions, output is always English regardless of the
- * source audio language.
- */
-export async function POST(request) {
- let formData;
- try {
- formData = await request.formData();
- } catch {
- return errorResponse(HTTP_STATUS.BAD_REQUEST, "Invalid multipart form data");
- }
-
- const startTime = Date.now();
-
- const model = formData.get("model");
- if (!model) {
- return errorResponse(HTTP_STATUS.BAD_REQUEST, "Missing model");
- }
-
- // Enforce API key policies (model restrictions + budget limits)
- const policy = await enforceApiKeyPolicy(request, model as string);
- if (policy.rejection) return policy.rejection;
-
- // Load local provider_nodes for audio routing (only localhost — prevents auth bypass/SSRF)
- let dynamicProviders: ReturnType<typeof buildDynamicAudioProvider>[] = [];
- try {
- const nodes = await getProviderNodes();
- dynamicProviders = (Array.isArray(nodes) ? (nodes as unknown as ProviderNodeRow[]) : [])
- .filter((n: ProviderNodeRow) => {
- if (n.apiType !== "chat" && n.apiType !== "responses") return false;
- try {
- const hostname = new URL(n.baseUrl).hostname;
- // Strictly matching 172.16.0.0/12 (Docker/local) and explicitly blocking ::1 per SSRF hardening
- return (
- hostname === "localhost" ||
- hostname === "127.0.0.1" ||
- /^172\.(1[6-9]|2[0-9]|3[0-1])\.\d{1,3}\.\d{1,3}$/.test(hostname)
- );
- } catch {
- return false;
- }
- })
- .map((n) => buildDynamicAudioProvider(n, "/audio/translations"));
- } catch {
- // DB error — fall back to hardcoded providers only
- }
-
- const { provider, model: resolvedModel } = parseTranslationModel(
- model as string,
- dynamicProviders
- );
- if (!provider) {
- return errorResponse(
- HTTP_STATUS.BAD_REQUEST,
- `Invalid translation model: ${model}. Use format: provider/model`
- );
- }
-
- // Check provider config — hardcoded first, then dynamic
- const providerConfig =
- getTranslationProvider(provider) || dynamicProviders.find((dp) => dp.id === provider) || null;
-
- // Get credentials — skip for local providers (authType: "none")
- let credentials = null;
- if (providerConfig && providerConfig.authType !== "none") {
- credentials = await getProviderCredentials(provider);
- if (!credentials) {
- return errorResponse(HTTP_STATUS.BAD_REQUEST, `No credentials for provider: ${provider}`);
- }
- if (isAllRateLimitedCredentials(credentials)) {
- return rateLimitedProviderResponse(provider, credentials);
- }
- }
-
- let response = await handleAudioTranslation({
- formData,
- credentials,
- resolvedProvider: providerConfig,
- resolvedModel,
- });
- if (response?.ok) {
- await clearRecoveredProviderState(credentials);
- // No text body / playback duration available from the multipart upload, so
- // per-second pricing cannot be applied → cost 0 (ADD-only headers, body intact).
- response = attachOmniRouteMetaToResponse(response, {
- provider,
- model: resolvedModel,
- costUsd: 0,
- latencyMs: Date.now() - startTime,
- requestId: generateRequestId(),
- });
- }
- return response;
-}
diff --git a/src/app/api/v1/ocr/route.ts b/src/app/api/v1/ocr/route.ts
deleted file mode 100644
index 8b717c7a58..0000000000
--- a/src/app/api/v1/ocr/route.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-import { handleOcr } from "@omniroute/open-sse/handlers/ocr.ts";
-import { getProviderCredentials, clearRecoveredProviderState } from "@/sse/services/auth";
-import { withInjectionGuard } from "@/middleware/promptInjectionGuard";
-import { parseOcrModel } from "@omniroute/open-sse/config/ocrRegistry.ts";
-import { errorResponse } from "@omniroute/open-sse/utils/error.ts";
-import { HTTP_STATUS } from "@omniroute/open-sse/config/constants.ts";
-import { enforceApiKeyPolicy } from "@/shared/utils/apiKeyPolicy";
-import { v1OcrSchema } from "@/shared/validation/schemas";
-import { isValidationFailure, validateBody } from "@/shared/validation/helpers";
-import {
- isAllRateLimitedCredentials,
- rateLimitedProviderResponse,
-} from "@/app/api/v1/_shared/rateLimit";
-
-/**
- * Handle CORS preflight
- */
-export async function OPTIONS() {
- return new Response(null, {
- headers: {
- "Access-Control-Allow-Methods": "POST, OPTIONS",
- "Access-Control-Allow-Headers": "*",
- },
- });
-}
-
-/**
- * POST /v1/ocr — document OCR
- * Mistral OCR API compatible.
- */
-async function postHandler(request, context) {
- let rawBody;
- try {
- rawBody = await request.json();
- } catch {
- return errorResponse(HTTP_STATUS.BAD_REQUEST, "Invalid JSON body");
- }
-
- const validation = validateBody(v1OcrSchema, rawBody);
- if (isValidationFailure(validation)) {
- return errorResponse(HTTP_STATUS.BAD_REQUEST, validation.error.message);
- }
- const body = validation.data;
-
- const model = body.model || "mistral-ocr-latest";
-
- // Enforce API key policies (model restrictions + budget limits)
- const policy = await enforceApiKeyPolicy(request, model);
- if (policy.rejection) return policy.rejection;
-
- const { provider } = parseOcrModel(model);
-
- // Default to mistral if no provider prefix
- const resolvedProvider = provider || "mistral";
- const credentials = await getProviderCredentials(resolvedProvider);
- if (!credentials) {
- return errorResponse(
- HTTP_STATUS.BAD_REQUEST,
- `No credentials for provider: ${resolvedProvider}`
- );
- }
- if (isAllRateLimitedCredentials(credentials)) {
- return rateLimitedProviderResponse(resolvedProvider, credentials);
- }
-
- const response = await handleOcr({ body: { ...body, model }, credentials });
- if (response?.ok) {
- await clearRecoveredProviderState(credentials);
- }
- return response;
-}
-
-export const POST = withInjectionGuard(postHandler);
diff --git a/src/app/api/v1/provider-plugin-manifest/route.ts b/src/app/api/v1/provider-plugin-manifest/route.ts
deleted file mode 100644
index 9774b49f53..0000000000
--- a/src/app/api/v1/provider-plugin-manifest/route.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { CORS_HEADERS } from "@/shared/utils/cors";
-import { generateProviderPluginManifest } from "@omniroute/open-sse/config/providerPluginManifestRegistry.ts";
-
-const JSON_HEADERS = {
- ...CORS_HEADERS,
- "Content-Type": "application/json",
- "Cache-Control": "public, max-age=60",
-} as const;
-
-export async function OPTIONS() {
- return new Response(null, {
- headers: {
- ...CORS_HEADERS,
- "Access-Control-Allow-Methods": "GET, OPTIONS",
- "Access-Control-Allow-Headers": "*",
- },
- });
-}
-
-export async function GET() {
- return new Response(JSON.stringify(generateProviderPluginManifest()), {
- headers: JSON_HEADERS,
- });
-}
diff --git a/src/app/api/v1/providers/[provider]/chat/completions/route.ts b/src/app/api/v1/providers/[provider]/chat/completions/route.ts
index d6c336a659..20b2e15c81 100644
--- a/src/app/api/v1/providers/[provider]/chat/completions/route.ts
+++ b/src/app/api/v1/providers/[provider]/chat/completions/route.ts
@@ -3,6 +3,8 @@ import { initTranslators } from "@omniroute/open-sse/translator/index.ts";
import { errorResponse } from "@omniroute/open-sse/utils/error.ts";
import { HTTP_STATUS } from "@omniroute/open-sse/config/constants.ts";
import { getRegistryEntry } from "@omniroute/open-sse/config/providerRegistry.ts";
+import { providerChatCompletionSchema } from "@/shared/validation/schemas";
+import { isValidationFailure, validateBody } from "@/shared/validation/helpers";
let initialized = false;
@@ -28,7 +30,6 @@ export async function OPTIONS() {
/**
* POST /v1/providers/{provider}/chat/completions
* Routes to the specified provider, validating model/provider match.
- * Full body format validation is delegated to handleChat.
*/
export async function POST(request, { params }) {
const { provider: rawProvider } = await params;
@@ -44,25 +45,18 @@ export async function POST(request, { params }) {
await ensureInitialized();
- // Parse body once so this provider-scoped route can normalize the model prefix
- // before delegating full chat-format validation to handleChat.
- let rawBody: unknown;
+ // Clone request with provider-prefixed model
+ let rawBody;
try {
rawBody = await request.json();
} catch {
return errorResponse(HTTP_STATUS.BAD_REQUEST, "Invalid JSON body");
}
-
- if (!rawBody || typeof rawBody !== "object" || Array.isArray(rawBody)) {
- return errorResponse(HTTP_STATUS.BAD_REQUEST, "Request body must be a JSON object");
- }
-
- const body = rawBody as { model?: string; [key: string]: unknown };
-
- // Keep the route-level checks minimal: only guard fields needed for provider prefix handling.
- if (body.model !== undefined && typeof body.model !== "string") {
- return errorResponse(HTTP_STATUS.BAD_REQUEST, "model must be a string");
+ const validation = validateBody(providerChatCompletionSchema, rawBody);
+ if (isValidationFailure(validation)) {
+ return errorResponse(HTTP_STATUS.BAD_REQUEST, validation.error.message);
}
+ const body = validation.data;
// Validate model belongs to this provider
if (body.model) {
diff --git a/src/app/api/v1/providers/suggested-models/route.ts b/src/app/api/v1/providers/suggested-models/route.ts
deleted file mode 100644
index efe9bd1956..0000000000
--- a/src/app/api/v1/providers/suggested-models/route.ts
+++ /dev/null
@@ -1,125 +0,0 @@
-import { NextResponse } from "next/server";
-import { z } from "zod";
-import { CORS_HEADERS, handleCorsOptions } from "@/shared/utils/cors";
-import { isAuthenticated } from "@/shared/utils/apiAuth";
-import { buildErrorBody } from "@omniroute/open-sse/utils/error.ts";
-import {
- resolveHfPipelineTag,
- sortHfSuggestedModels,
- type HfModelSummary,
-} from "@omniroute/open-sse/services/hfModelSuggestions.ts";
-
-/**
- * GET /api/v1/providers/suggested-models?type=image
- *
- * Proxies the public HuggingFace Hub models search API
- * (https://huggingface.co/api/models) server-side so the dashboard can
- * suggest HF Hub models for a media provider kind without a CORS round-trip
- * from the browser and without ever exposing an HF token client-side.
- *
- * This route is a read-only proxy to a public search endpoint — it never
- * spawns a child process, so it does NOT require `isLocalOnlyPath()`
- * classification in `src/server/authz/routeGuard.ts` (Hard Rules #15/#17
- * only apply to routes that spawn processes or reverse-proxy embedded
- * service UIs).
- */
-
-const HF_MODELS_API_URL = "https://huggingface.co/api/models";
-const HF_SEARCH_PAGE_SIZE = 100;
-const HF_FETCH_TIMEOUT_MS = 8000;
-
-const querySchema = z.object({
- type: z.enum(["image"]).default("image"),
- sortBy: z.enum(["downloads", "likes"]).default("downloads"),
- limit: z.coerce.number().int().min(1).max(50).default(20),
-});
-
-export async function OPTIONS() {
- return handleCorsOptions();
-}
-
-export async function GET(request: Request) {
- if (!(await isAuthenticated(request))) {
- return NextResponse.json(buildErrorBody(401, "Authentication required"), {
- status: 401,
- headers: CORS_HEADERS,
- });
- }
-
- const { searchParams } = new URL(request.url);
- const parsed = querySchema.safeParse({
- type: searchParams.get("type") ?? undefined,
- sortBy: searchParams.get("sortBy") ?? undefined,
- limit: searchParams.get("limit") ?? undefined,
- });
-
- if (!parsed.success) {
- return NextResponse.json(
- buildErrorBody(400, parsed.error.issues[0]?.message ?? "Invalid query parameters"),
- { status: 400, headers: CORS_HEADERS }
- );
- }
-
- const { type, sortBy, limit } = parsed.data;
- const pipelineTag = resolveHfPipelineTag(type);
- if (!pipelineTag) {
- return NextResponse.json(
- buildErrorBody(400, `Unsupported suggested-models type: ${type}`),
- { status: 400, headers: CORS_HEADERS }
- );
- }
-
- try {
- const upstreamUrl = new URL(HF_MODELS_API_URL);
- upstreamUrl.searchParams.set("inference_provider", "hf-inference");
- upstreamUrl.searchParams.set("pipeline_tag", pipelineTag);
- upstreamUrl.searchParams.set("limit", String(HF_SEARCH_PAGE_SIZE));
-
- // This project has no dedicated server-side HF Hub search token config
- // (HuggingFace credentials are per-connection, stored encrypted in the
- // DB — see src/lib/db/providers.ts — not a raw env var), and an HF token
- // must never be exposed client-side. The public HF Hub models search
- // endpoint works fine unauthenticated, so this route calls it without
- // credentials.
- const upstream = await fetch(upstreamUrl.toString(), {
- headers: { Accept: "application/json" },
- signal: AbortSignal.timeout(HF_FETCH_TIMEOUT_MS),
- });
-
- if (!upstream.ok) {
- return NextResponse.json(
- buildErrorBody(502, `HuggingFace Hub API responded with status ${upstream.status}`),
- { status: 502, headers: CORS_HEADERS }
- );
- }
-
- const raw: unknown = await upstream.json();
- const models: HfModelSummary[] = Array.isArray(raw)
- ? raw.filter(
- (m): m is HfModelSummary =>
- !!m && typeof m === "object" && typeof (m as { id?: unknown }).id === "string"
- )
- : [];
-
- const suggested = sortHfSuggestedModels(models, sortBy, limit);
-
- return NextResponse.json(
- {
- object: "list",
- type,
- pipeline_tag: pipelineTag,
- data: suggested.map((m) => ({
- id: m.id,
- likes: typeof m.likes === "number" ? m.likes : 0,
- downloads: typeof m.downloads === "number" ? m.downloads : 0,
- })),
- },
- { headers: CORS_HEADERS }
- );
- } catch (err) {
- return NextResponse.json(
- buildErrorBody(502, err instanceof Error ? err.message : String(err)),
- { status: 502, headers: CORS_HEADERS }
- );
- }
-}
diff --git a/src/app/api/v1/relay/chat/completions/bifrost/route.ts b/src/app/api/v1/relay/chat/completions/bifrost/route.ts
index da8722d11c..6d1c29b0a4 100644
--- a/src/app/api/v1/relay/chat/completions/bifrost/route.ts
+++ b/src/app/api/v1/relay/chat/completions/bifrost/route.ts
@@ -32,7 +32,6 @@ import { CORS_HEADERS, handleCorsOptions } from "@/shared/utils/cors";
import { createInjectionGuard } from "@/middleware/promptInjectionGuard";
import { getRelayTokenByHash, checkRateLimit, recordRelayUsage } from "@/lib/db/relayProxies";
import { buildErrorBody } from "@omniroute/open-sse/utils/error";
-import { getProviderPluginManifestHeader } from "@omniroute/open-sse/config/providerPluginManifestUrl.ts";
import { z } from "zod";
import {
checkIpRateLimit,
@@ -258,7 +257,6 @@ export async function POST(request: Request) {
"Content-Type": "application/json",
"x-relay-token-id": token.id,
"x-relay-client-ip": clientIp,
- ...getProviderPluginManifestHeader(new URL(request.url).origin),
};
if (BIFROST_API_KEY) {
upstreamHeaders["Authorization"] = `Bearer ${BIFROST_API_KEY}`;
diff --git a/src/app/api/v1/relay/chat/completions/route.ts b/src/app/api/v1/relay/chat/completions/route.ts
index f674327f62..d8d7afd693 100644
--- a/src/app/api/v1/relay/chat/completions/route.ts
+++ b/src/app/api/v1/relay/chat/completions/route.ts
@@ -22,11 +22,9 @@ import {
getBifrostRoutingConfig,
getRoutingFallbackHeader,
resolveRelayRoutingBackend,
- shouldTryBifrostForRequest,
+ shouldTryBifrost,
type BifrostRoutingConfig,
} from "./routingBackend";
-import { getProviderPluginManifestEntryForModel } from "@omniroute/open-sse/config/providerPluginManifestRegistry.ts";
-import { getProviderPluginManifestHeader } from "@omniroute/open-sse/config/providerPluginManifestUrl.ts";
import { finalizeReadableStream } from "./streamFinalizer";
import {
clearBifrostFailure,
@@ -75,7 +73,6 @@ async function forwardToBifrost(
"Content-Type": "application/json",
"x-relay-token-id": token.id,
"x-relay-client-ip": clientIp,
- ...getProviderPluginManifestHeader(new URL(request.url).origin),
};
if (config.apiKey) {
upstreamHeaders.Authorization = `Bearer ${config.apiKey}`;
@@ -293,16 +290,7 @@ export async function POST(request: Request) {
const backend = resolveRelayRoutingBackend();
const bifrostConfig = getBifrostRoutingConfig();
let bifrostFallbackReason: string | null = null;
- const bifrostDecision = shouldTryBifrostForRequest(
- backend,
- bifrostConfig,
- parsedBody,
- (model) => getProviderPluginManifestEntryForModel(model)?.sidecar ?? null
- );
- if (bifrostDecision.fallbackReason) {
- bifrostFallbackReason = bifrostDecision.fallbackReason;
- }
- if (bifrostDecision.tryBifrost) {
+ if (shouldTryBifrost(backend, bifrostConfig)) {
const cooldown =
backend === "auto" ? getActiveBifrostCooldown(bifrostConfig.baseUrl) : null;
if (cooldown) {
diff --git a/src/app/api/v1/relay/chat/completions/routingBackend.ts b/src/app/api/v1/relay/chat/completions/routingBackend.ts
index ed1459c5d0..8604065c04 100644
--- a/src/app/api/v1/relay/chat/completions/routingBackend.ts
+++ b/src/app/api/v1/relay/chat/completions/routingBackend.ts
@@ -1,5 +1,3 @@
-import { getSupervisor } from "@/lib/services/registry";
-
export type RelayRoutingBackend = "ts" | "bifrost" | "auto";
const VALID_BACKENDS = new Set<RelayRoutingBackend>(["ts", "bifrost", "auto"]);
@@ -12,38 +10,15 @@ export interface BifrostRoutingConfig {
enabled: boolean;
}
-export interface SidecarEligibility {
- eligible: boolean;
- reasons: readonly string[];
-}
-
-export type ProviderSidecarLookup = (model: string | undefined) => SidecarEligibility | null;
-
-export interface BifrostRoutingDecision {
- tryBifrost: boolean;
- fallbackReason?: string;
-}
-
export function getBifrostRoutingConfig(
env: NodeJS.ProcessEnv = process.env
): BifrostRoutingConfig | null {
const baseUrl = env.BIFROST_BASE_URL?.replace(/\/$/, "");
-
- // §4b: if BIFROST_BASE_URL is unset, check if supervised instance is running
- let resolvedBaseUrl = baseUrl;
- if (!resolvedBaseUrl) {
- const sup = getSupervisor("bifrost");
- if (sup?.getStatus().state === "running") {
- resolvedBaseUrl = `http://127.0.0.1:${sup.getStatus().port}`;
- }
- }
-
- if (!resolvedBaseUrl) return null;
-
+ if (!baseUrl) return null;
const timeoutMs = Number.parseInt(env.BIFROST_TIMEOUT_MS || "", 10);
return {
- baseUrl: resolvedBaseUrl,
+ baseUrl,
apiKey: env.BIFROST_API_KEY || env.OMNIROUTE_BIFROST_KEY || undefined,
timeoutMs: Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 30000,
streamingEnabled: env.BIFROST_STREAMING_ENABLED !== "0",
@@ -69,33 +44,6 @@ export function shouldTryBifrost(
return Boolean(config?.enabled && backend !== "ts");
}
-export function shouldTryBifrostForRequest(
- backend: RelayRoutingBackend,
- config: BifrostRoutingConfig | null,
- body: unknown,
- lookupProviderSidecar: ProviderSidecarLookup
-): BifrostRoutingDecision {
- if (!shouldTryBifrost(backend, config)) {
- return { tryBifrost: false };
- }
- if (backend === "bifrost") {
- return { tryBifrost: true };
- }
-
- const model = typeof (body as { model?: unknown } | null)?.model === "string"
- ? (body as { model: string }).model
- : undefined;
- const provider = lookupProviderSidecar(model);
- if (provider?.eligible) {
- return { tryBifrost: true };
- }
-
- return {
- tryBifrost: false,
- fallbackReason: provider ? "bifrost-ineligible" : "bifrost-provider-unknown",
- };
-}
-
export function getRoutingFallbackHeader(
backend: RelayRoutingBackend,
config: BifrostRoutingConfig | null
diff --git a/src/app/layout.tsx b/src/app/layout.tsx
index 8388309570..1e1d6483f8 100644
--- a/src/app/layout.tsx
+++ b/src/app/layout.tsx
@@ -8,7 +8,6 @@ import { normalizeComplianceEventTypes } from "@/i18n/request";
import { getSettings } from "@/lib/db/settings";
import type { Viewport } from "next";
import { PwaRegister } from "@/shared/components/PwaRegister";
-import { LocaleAutoDetect } from "@/shared/components/LocaleAutoDetect";
const inter = Inter({
subsets: ["latin"],
@@ -110,7 +109,6 @@ export default async function RootLayout({ children }) {
</a>
<NextIntlClientProvider locale={locale} messages={messages}>
<PwaRegister />
- <LocaleAutoDetect />
<ThemeProvider>{children}</ThemeProvider>
</NextIntlClientProvider>
</body>
diff --git a/src/domain/quotaCache.ts b/src/domain/quotaCache.ts
index ddbf2c6019..cb03598f90 100644
--- a/src/domain/quotaCache.ts
+++ b/src/domain/quotaCache.ts
@@ -250,20 +250,15 @@ export function setQuotaCache(
}
: null,
});
- // #5923 (Finding #5) — is_exhausted must reflect THIS window's own remaining
- // percentage, not the connection-wide AND-across-all-windows aggregate
- // (`entry.exhausted`). A connection with one 0% window and other non-zero
- // windows previously never flagged that window's row as exhausted.
- const windowExhausted = remainingPercentage <= 0;
// #4438 — only persist on the first observation or a real change.
- if (!quotaSnapshotChanged(prior, windowKey, remainingPercentage, windowExhausted)) continue;
+ if (!quotaSnapshotChanged(prior, windowKey, remainingPercentage, entry.exhausted)) continue;
try {
saveQuotaSnapshot({
provider,
connection_id: connectionId,
window_key: windowKey,
remaining_percentage: remainingPercentage,
- is_exhausted: windowExhausted ? 1 : 0,
+ is_exhausted: entry.exhausted ? 1 : 0,
next_reset_at: quotaInfo.resetAt ?? null,
window_duration_ms: entry.windowDurationMs ?? null,
raw_data: null,
diff --git a/src/i18n/detectBrowserLocale.ts b/src/i18n/detectBrowserLocale.ts
deleted file mode 100644
index 00f8128750..0000000000
--- a/src/i18n/detectBrowserLocale.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-/**
- * Pure browser-language detector used to pick an initial locale on first
- * visit, before the user has made an explicit selection (no cookie set).
- *
- * Matching order:
- * 1. Exact match against `navigator.languages` entries (case-insensitive).
- * 2. `zh-HK` / `zh-MO` are treated as `zh-TW` (Traditional Chinese) since
- * OmniRoute does not ship a dedicated Hong-Kong/Macau locale.
- * 3. Language-prefix match — e.g. `en-US` matches a supported `en` locale.
- * 4. No match → `null` (caller should keep the existing default).
- *
- * Kept dependency-free (no DOM/`navigator` access) so it is trivially unit
- * testable and reusable from both client components and future server code.
- */
-export function detectBrowserLocale(
- languages: readonly string[],
- locales: readonly string[]
-): string | null {
- if (!languages || languages.length === 0 || !locales || locales.length === 0) {
- return null;
- }
-
- const normalizedLocales = locales.map((locale) => locale.toLowerCase());
-
- for (const rawLanguage of languages) {
- if (!rawLanguage) continue;
- const language = rawLanguage.toLowerCase();
-
- // 1. Exact match.
- const exactIndex = normalizedLocales.indexOf(language);
- if (exactIndex !== -1) {
- return locales[exactIndex];
- }
-
- // 2. zh-HK / zh-MO fold to zh-TW when zh-TW is supported.
- if (language === "zh-hk" || language === "zh-mo") {
- const zhTwIndex = normalizedLocales.indexOf("zh-tw");
- if (zhTwIndex !== -1) {
- return locales[zhTwIndex];
- }
- }
-
- // 3. Language-prefix match (e.g. "en-US" -> "en").
- const prefix = language.split("-")[0];
- const prefixIndex = normalizedLocales.indexOf(prefix);
- if (prefixIndex !== -1) {
- return locales[prefixIndex];
- }
- }
-
- return null;
-}
diff --git a/src/i18n/messages/en.json b/src/i18n/messages/en.json
index 8fdd6ac761..8c1d17ae05 100644
--- a/src/i18n/messages/en.json
+++ b/src/i18n/messages/en.json
@@ -1117,9 +1117,7 @@
"dragReorderItem": "Drag to reorder",
"cannotHide": "This item cannot be hidden",
"alwaysVisible": "Always visible",
- "groupSeparatorLabel": "Separator",
- "discovery": "Discovery",
- "discoverySubtitle": "Scan providers for free access"
+ "groupSeparatorLabel": "Separator"
},
"webhooks": {
"title": "Webhooks",
@@ -1763,8 +1761,6 @@
"copyMaskedKey": "Copy masked key",
"keyOnlyAvailableAtCreation": "Full key available only at creation time — copy it when you first create the key",
"modelsCount": "{count, plural, one {# model} other {# models}}",
- "devicesCount": "{count, plural, one {# device} other {# devices}}",
- "devicesTooltip": "{count, plural, one {# distinct IP/User-Agent device seen with this key (last 30 min)} other {# distinct IP/User-Agent devices seen with this key (last 30 min)}}",
"lastUsedOn": "Last: {date}",
"viewCostsFor": "View costs for {name}",
"editPermissions": "Edit permissions",
@@ -1860,16 +1856,14 @@
"webSearch": "Web Search",
"webFetch": "Web Fetch",
"video": "Video",
- "music": "Music",
- "ocr": "OCR"
+ "music": "Music"
},
"noProviders": "No providers configured for this kind yet.",
"addConnection": "Add Connection",
"backToProviders": "Back to Providers",
"connections": "{count} Connections",
"noConnections": "No connections yet — add one from the provider page.",
- "loading": "Loading...",
- "suggestedModels": "Suggested models from provider"
+ "loading": "Loading..."
},
"search": {
"searchQuery": "Search Query",
@@ -4091,8 +4085,6 @@
"prefixHint": "Required. Unique prefix for model names.",
"nameHint": "Required. A friendly label for this node.",
"baseUrlHint": "Required. Provider API base URL.",
- "iconUrlLabel": "Icon URL",
- "iconUrlHint": "Optional. Image URL shown as this provider's icon.",
"anthropicPrefixPlaceholder": "ac-prod",
"openaiPrefixPlaceholder": "oc-prod",
"anthropicBaseUrlPlaceholder": "https://api.anthropic.com/v1",
@@ -4508,8 +4500,6 @@
"modelsPathLabel": "Models Endpoint Path",
"modelsPathPlaceholder": "/models",
"modelsPathHint": "Custom models path for validation (e.g. /v4/models)",
- "clientIdentityLabel": "Client Identity",
- "clientIdentityHint": "Optional. Adds client fingerprint headers (e.g. User-Agent) matching a known CLI for compatible gateways that expect one.",
"statusDeactivated": "Deactivated (Manual)",
"statusBanned": "Banned / Sandbox Violation",
"statusCreditsExhausted": "Insufficient Balance / Quota Exhausted",
@@ -4696,7 +4686,7 @@
"totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}",
"unhideModel": "Unhide Model",
"upstreamProxyProviders": "Upstream Proxy Providers",
- "validationModelIdHint": "Model used to verify the API key. Leave blank to use the provider’s first available model.",
+ "validationModelIdHint": "Model used to verify the API key. Leave blank to use the provider\u2019s first available model.",
"validationModelIdLabel": "Validation Model",
"validationModelIdPlaceholder": "e.g. meta-llama/llama-3.1-8b-instruct",
"vertexServiceAccountPlaceholder": "Paste your Service Account JSON ({\"type\":\"service_account\",\"project_id\":\"…\",\"client_email\":\"…\",\"private_key\":\"…\"}) or an OAuth access_token",
@@ -4997,8 +4987,6 @@
"modelsDevInfoOrder": "User Override → models.dev → LiteLLM → Hardcoded Default",
"systemTheme": "System Theme",
"debugToggle": "Enable Debug Mode",
- "logToolSourcesToggle": "Log Tool Sources",
- "logToolSourcesDescription": "Emit a diagnostic log line per request summarizing tool count and MCP/hosted/client source breakdown.",
"homePinProviderQuotaToHome": "Pin Information to Home Page",
"homeProviderQuotaLimits": "Provider Quota Limits",
"homeProviderQuotaLimitsDesc": "Pin the Provider Quota status container (with Refresh All button) to the top of the Home page.",
@@ -5558,21 +5546,6 @@
"purgeExpiredLogs": "Purge Expired Logs",
"purgeLogsFailed": "Failed to purge logs",
"logsDeleted": "{count, plural, =0 {No expired logs purged} one {Purged # expired log} other {Purged # expired logs}}",
- "resetUsageData": "Reset Usage Data",
- "resetUsageDataDesc": "Select how far back you want to delete usage data. This action cannot be undone.",
- "resetUsagePeriod_5m": "5 minutes",
- "resetUsagePeriod_1h": "1 hour",
- "resetUsagePeriod_3h": "3 hours",
- "resetUsagePeriod_6h": "6 hours",
- "resetUsagePeriod_12h": "12 hours",
- "resetUsagePeriod_1d": "1 day",
- "resetUsagePeriod_7d": "7 days",
- "resetUsagePeriod_30d": "30 days",
- "resetUsagePeriod_all": "All time",
- "resetUsageSuccess": "{count, plural, =0 {No usage data rows deleted} one {Reset usage data (# row deleted)} other {Reset usage data (# rows deleted)}}",
- "resetUsageFailed": "Failed to reset usage data",
- "reset": "Reset",
- "resetting": "Resetting...",
"contextOpt": "Context Optimized",
"contextOptDesc": "Routes based on context window requirements and conversation length",
"priorityDesc": "Sequential fallback - tries provider 1 first, then provider 2, and so on",
@@ -5979,12 +5952,6 @@
"claudeFastModeModelCheckbox": "Enable Fast Mode for {model}",
"claudeFastModeSaveError": "Failed to update Claude Fast Mode setting",
"authz": {
- "cors": {
- "wildcard": {
- "title": "CORS is open to every origin (CORS_ALLOW_ALL=true)",
- "desc": "Any website can call this server's API from a visitor's browser. Use only on trusted networks — set explicit origins in ALLOWED_ORIGINS and disable CORS_ALLOW_ALL in production."
- }
- },
"title": "Authorization Inventory",
"description": "5-tier route classification with live bypass policy. Read shows the full taxonomy; mutations re-prompt for the management password.",
"loading": "Loading inventory…",
@@ -6722,8 +6689,6 @@
"autoRefresh": "Auto-refresh",
"refreshAll": "Refresh All",
"loadingQuotas": "Loading...",
- "showMoreQuotas": "Show {count} more",
- "showLessQuotas": "Show less",
"account": "Account",
"modelQuotas": "Model Quotas",
"lastUsed": "Last Refreshed",
@@ -7926,12 +7891,7 @@
"bulkImportMaxExceeded": "Maximum 100 proxies per import",
"bulkImportPreview": "Preview",
"clearAssignment": "(clear assignment)",
- "bulkProxyAssignment": "Bulk Proxy Assignment",
- "testAll": "Test All",
- "errorTestFailed": "Failed to test proxies",
- "batchSelectedCount": "{count} selected",
- "batchDeleteSelected": "Delete {count} selected",
- "testPassed": "✓ OK"
+ "bulkProxyAssignment": "Bulk Proxy Assignment"
},
"playground": {
"title": "Model Playground",
@@ -9031,30 +8991,5 @@
"colAvgScore": "Avg Score",
"colModels": "Models",
"colType": "Type"
- },
- "discovery": {
- "title": "Provider Discovery",
- "subtitle": "Scan providers for free/unlimited access methods and review findings. Opt-in, local-only.",
- "scanLabel": "Provider to scan",
- "scanPlaceholder": "e.g. huggingchat",
- "scan": "Scan",
- "scanning": "Scanning…",
- "scanQueued": "Scan complete for {provider}.",
- "scanFailed": "Scan failed.",
- "loadFailed": "Failed to load discovery results.",
- "localOnlyNote": "This tool is local-only (loopback). Scans run from this machine and are never reachable remotely.",
- "verify": "Verify",
- "verifyFailed": "Failed to verify finding.",
- "delete": "Delete",
- "deleteFailed": "Failed to delete finding.",
- "deleteTitle": "Delete discovery result",
- "deleteConfirm": "Delete the discovery finding for {provider}? This cannot be undone.",
- "emptyTitle": "No discovery results yet",
- "emptyDescription": "Run a scan above to look for free access methods on a provider.",
- "risk": "Risk",
- "method": "Method",
- "auth": "Auth",
- "feasibility": "Feasibility",
- "models": "Models"
}
}
diff --git a/src/instrumentation-node.ts b/src/instrumentation-node.ts
index 6c005b1c51..bdc202e9e2 100755
--- a/src/instrumentation-node.ts
+++ b/src/instrumentation-node.ts
@@ -151,9 +151,6 @@ export async function registerNodejs(): Promise<void> {
import("@/lib/skills/builtins"),
]);
- // Proxy health scheduler (auto-removes dead proxies on interval)
- await import("@/lib/proxyHealth/scheduler");
-
initGracefulShutdown();
initApiBridgeServer();
startSpendBatchWriter();
diff --git a/src/lib/db/cleanup.ts b/src/lib/db/cleanup.ts
index 40cebb328c..83563f11a2 100644
--- a/src/lib/db/cleanup.ts
+++ b/src/lib/db/cleanup.ts
@@ -351,127 +351,6 @@ export async function purgeDetailedLogs(): Promise<CleanupResult> {
return result;
}
-/**
- * Whitelist of periods accepted by {@link resetUsageHistory}. `"all"` wipes
- * every row; any other value deletes rows strictly older than `now - period`.
- */
-export const RESET_USAGE_HISTORY_PERIODS = [
- "5m",
- "1h",
- "3h",
- "6h",
- "12h",
- "1d",
- "7d",
- "30d",
- "all",
-] as const;
-
-export type ResetUsageHistoryPeriod = (typeof RESET_USAGE_HISTORY_PERIODS)[number];
-
-type TimedResetUsageHistoryPeriod = Exclude<ResetUsageHistoryPeriod, "all">;
-
-const RESET_USAGE_HISTORY_PERIOD_MS: Record<TimedResetUsageHistoryPeriod, number> = {
- "5m": 5 * 60 * 1000,
- "1h": 60 * 60 * 1000,
- "3h": 3 * 60 * 60 * 1000,
- "6h": 6 * 60 * 60 * 1000,
- "12h": 12 * 60 * 60 * 1000,
- "1d": 24 * 60 * 60 * 1000,
- "7d": 7 * 24 * 60 * 60 * 1000,
- "30d": 30 * 24 * 60 * 60 * 1000,
-};
-
-export interface ResetUsageHistoryResult extends CleanupResult {
- deletedUsageHistory: number;
- deletedDailySummary: number;
- deletedHourlySummary: number;
-}
-
-function isResetUsageHistoryPeriod(period: string): period is ResetUsageHistoryPeriod {
- return (RESET_USAGE_HISTORY_PERIODS as readonly string[]).includes(period);
-}
-
-/**
- * On-demand, period-scoped reset of usage analytics data (`usage_history`,
- * `daily_usage_summary`, `hourly_usage_summary`).
- *
- * Unlike {@link cleanupUsageHistory} (retention-based background cleanup,
- * which rolls up rows into `daily_usage_summary` before deleting them), this
- * is a destructive user-triggered reset — it intentionally does NOT roll up
- * first, since the whole point is to wipe the data the user selected.
- *
- * @param period - One of {@link RESET_USAGE_HISTORY_PERIODS}. `"all"` wipes
- * every row in all three tables; any other value deletes rows strictly
- * older than `now - period`. Throws on an invalid period.
- */
-export async function resetUsageHistory(period: string): Promise<ResetUsageHistoryResult> {
- if (!isResetUsageHistoryPeriod(period)) {
- throw new Error(`Invalid reset period: ${period}`);
- }
-
- const db = getDbInstance();
- const result: ResetUsageHistoryResult = {
- deleted: 0,
- deletedUsageHistory: 0,
- deletedDailySummary: 0,
- deletedHourlySummary: 0,
- errors: 0,
- };
-
- try {
- const runReset = db.transaction(() => {
- if (period === "all") {
- const usageHistory = db.prepare("DELETE FROM usage_history").run();
- const dailySummary = db.prepare("DELETE FROM daily_usage_summary").run();
- const hourlySummary = db.prepare("DELETE FROM hourly_usage_summary").run();
- result.deletedUsageHistory = usageHistory.changes;
- result.deletedDailySummary = dailySummary.changes;
- result.deletedHourlySummary = hourlySummary.changes;
- return;
- }
-
- const cutoffMs = Date.now() - RESET_USAGE_HISTORY_PERIOD_MS[period];
- const cutoffIso = new Date(cutoffMs).toISOString();
- // usage_history.timestamp is a full ISO string; daily_usage_summary.date is
- // "YYYY-MM-DD"; hourly_usage_summary.date_hour is "YYYY-MM-DD HH:00:00" (see
- // src/lib/usage/aggregateHistory.ts, which derives both with SQLite's UTC-based
- // DATE()/strftime()). Slicing the UTC ISO cutoff keeps all three comparisons
- // consistent without re-deriving timezone-sensitive date math by hand.
- const cutoffDate = cutoffIso.slice(0, 10);
- const cutoffDateHour = `${cutoffIso.slice(0, 10)} ${cutoffIso.slice(11, 13)}:00:00`;
-
- const usageHistory = db
- .prepare("DELETE FROM usage_history WHERE timestamp < ?")
- .run(cutoffIso);
- const dailySummary = db
- .prepare("DELETE FROM daily_usage_summary WHERE date < ?")
- .run(cutoffDate);
- const hourlySummary = db
- .prepare("DELETE FROM hourly_usage_summary WHERE date_hour < ?")
- .run(cutoffDateHour);
-
- result.deletedUsageHistory = usageHistory.changes;
- result.deletedDailySummary = dailySummary.changes;
- result.deletedHourlySummary = hourlySummary.changes;
- });
-
- runReset();
- result.deleted =
- result.deletedUsageHistory + result.deletedDailySummary + result.deletedHourlySummary;
-
- console.log(
- `[Cleanup] Reset usage data (period=${period}): ${result.deletedUsageHistory} usage_history, ` +
- `${result.deletedDailySummary} daily_usage_summary, ${result.deletedHourlySummary} hourly_usage_summary`
- );
- } catch (err: unknown) {
- console.error("[Cleanup] Error resetting usage history:", err);
- result.errors++;
- }
-
- return result;
-}
-
/**
* Clean up old proxy_logs based on retention settings.
* Uses the same retention period as call_logs (30 days default).
diff --git a/src/lib/db/discoveryResults.ts b/src/lib/db/discoveryResults.ts
deleted file mode 100644
index 085af33d35..0000000000
--- a/src/lib/db/discoveryResults.ts
+++ /dev/null
@@ -1,176 +0,0 @@
-/**
- * Database module: Discovery Results
- *
- * CRUD for the automated provider-discovery tool (opt-in, default off). Rows
- * live in the `discovery_results` table (migration 074). The Discovery service
- * (`src/lib/discovery/`) writes findings here via {@link upsertDiscoveryResult};
- * the `/api/discovery/*` routes read/verify/delete them.
- *
- * See `_tasks/features-v3.8.42/gaps/DISCOVERY_TOOL_DESIGN.md` for the design.
- */
-
-import { getDbInstance } from "./core";
-
-export type DiscoveryMethod =
- | "free_tier"
- | "web_cookie"
- | "auto_register"
- | "trial"
- | "public_api";
-export type DiscoveryAuthType = "none" | "cookie" | "api_key" | "oauth";
-export type DiscoveryRiskLevel = "none" | "low" | "medium" | "high" | "critical";
-export type DiscoveryStatus = "pending" | "testing" | "verified" | "rejected";
-
-export interface DiscoveryResult {
- id?: number;
- providerId: string;
- method: DiscoveryMethod;
- endpoint?: string | null;
- authType: DiscoveryAuthType;
- models?: string[];
- rateLimit?: string | null;
- feasibility: number;
- riskLevel: DiscoveryRiskLevel;
- status: DiscoveryStatus;
- notes?: string | null;
- discoveredAt?: string;
- verifiedAt?: string | null;
-}
-
-interface DiscoveryRow {
- id: number;
- provider_id: string;
- method: string;
- endpoint: string | null;
- auth_type: string | null;
- models: string | null;
- rate_limit: string | null;
- feasibility: number | null;
- risk_level: string | null;
- status: string;
- notes: string | null;
- discovered_at: string;
- verified_at: string | null;
-}
-
-function rowToResult(row: DiscoveryRow): DiscoveryResult {
- let models: string[] | undefined;
- if (row.models) {
- try {
- const parsed = JSON.parse(row.models);
- if (Array.isArray(parsed)) models = parsed.map(String);
- } catch {
- models = undefined;
- }
- }
- return {
- id: row.id,
- providerId: row.provider_id,
- method: row.method as DiscoveryMethod,
- endpoint: row.endpoint,
- authType: (row.auth_type as DiscoveryAuthType) ?? "none",
- models,
- rateLimit: row.rate_limit,
- feasibility: row.feasibility ?? 0,
- riskLevel: (row.risk_level as DiscoveryRiskLevel) ?? "none",
- status: row.status as DiscoveryStatus,
- notes: row.notes,
- discoveredAt: row.discovered_at,
- verifiedAt: row.verified_at,
- };
-}
-
-/**
- * Insert or update a discovery finding. Uniqueness is keyed on
- * `(provider_id, method, endpoint)` (the table's UNIQUE constraint), so
- * re-discovering the same endpoint updates the existing row rather than
- * duplicating it. Returns the persisted row (with its id).
- */
-export function upsertDiscoveryResult(result: DiscoveryResult): DiscoveryResult {
- const db = getDbInstance();
- const models = result.models ? JSON.stringify(result.models) : null;
- db.prepare(
- `INSERT INTO discovery_results
- (provider_id, method, endpoint, auth_type, models, rate_limit, feasibility, risk_level, status, notes)
- VALUES (@provider_id, @method, @endpoint, @auth_type, @models, @rate_limit, @feasibility, @risk_level, @status, @notes)
- ON CONFLICT(provider_id, method, endpoint) DO UPDATE SET
- auth_type = excluded.auth_type,
- models = excluded.models,
- rate_limit = excluded.rate_limit,
- feasibility = excluded.feasibility,
- risk_level = excluded.risk_level,
- status = excluded.status,
- notes = excluded.notes`
- ).run({
- provider_id: result.providerId,
- method: result.method,
- endpoint: result.endpoint ?? null,
- auth_type: result.authType,
- models,
- rate_limit: result.rateLimit ?? null,
- feasibility: result.feasibility,
- risk_level: result.riskLevel,
- status: result.status,
- notes: result.notes ?? null,
- });
-
- const row = db
- .prepare(
- `SELECT * FROM discovery_results
- WHERE provider_id = ? AND method = ? AND ifnull(endpoint, '') = ifnull(?, '')`
- )
- .get(result.providerId, result.method, result.endpoint ?? null) as DiscoveryRow | undefined;
- // The row was just written, so it must exist.
- return rowToResult(row!);
-}
-
-/**
- * List discovery results, optionally filtered to a single provider. Newest
- * findings first.
- */
-export function getDiscoveryResults(providerId?: string): DiscoveryResult[] {
- const db = getDbInstance();
- const rows = providerId
- ? (db
- .prepare(
- "SELECT * FROM discovery_results WHERE provider_id = ? ORDER BY discovered_at DESC, id DESC"
- )
- .all(providerId) as DiscoveryRow[])
- : (db
- .prepare("SELECT * FROM discovery_results ORDER BY discovered_at DESC, id DESC")
- .all() as DiscoveryRow[]);
- return rows.map(rowToResult);
-}
-
-export function getDiscoveryResultById(id: number): DiscoveryResult | null {
- const db = getDbInstance();
- const row = db.prepare("SELECT * FROM discovery_results WHERE id = ?").get(id) as
- | DiscoveryRow
- | undefined;
- return row ? rowToResult(row) : null;
-}
-
-/**
- * Mark a finding as verified, stamping `verified_at`. Returns the updated row,
- * or null if no row with that id exists.
- */
-export function markVerified(id: number): DiscoveryResult | null {
- const db = getDbInstance();
- const info = db
- .prepare(
- "UPDATE discovery_results SET status = 'verified', verified_at = datetime('now') WHERE id = ?"
- )
- .run(id);
- if (info.changes === 0) return null;
- return getDiscoveryResultById(id);
-}
-
-/**
- * Delete a finding. Returns true if a row was removed, false if the id was not
- * found.
- */
-export function deleteDiscoveryResult(id: number): boolean {
- const db = getDbInstance();
- const info = db.prepare("DELETE FROM discovery_results WHERE id = ?").run(id);
- return info.changes > 0;
-}
diff --git a/src/lib/db/freeProxies.ts b/src/lib/db/freeProxies.ts
index c75642d491..57593c98ef 100644
--- a/src/lib/db/freeProxies.ts
+++ b/src/lib/db/freeProxies.ts
@@ -270,34 +270,6 @@ export async function clearFreeProxiesBySource(source: FreeProxySourceId): Promi
return result.changes;
}
-/**
- * Tombstone rows for `source` whose `host:port` is no longer present in the
- * provider's latest list — e.g. Webshare recycles/retires proxy IDs between
- * syncs. Rows already promoted to the pool (`in_pool = 1`) are left alone so
- * runtime resolution of an in-use proxy is never disturbed; only stale,
- * not-yet-pooled candidates are pruned. Returns the number of rows removed.
- */
-export async function pruneStaleFreeProxies(
- source: FreeProxySourceId,
- activeKeys: ReadonlySet<string>
-): Promise<number> {
- const db = getDbInstance();
- const rows = db
- .prepare("SELECT id, host, port FROM free_proxies WHERE source = ? AND in_pool = 0")
- .all(source) as Array<{ id: string; host: string; port: number }>;
-
- const staleIds = rows.filter((r) => !activeKeys.has(`${r.host}:${r.port}`)).map((r) => r.id);
-
- if (staleIds.length === 0) return 0;
-
- const placeholders = staleIds.map(() => "?").join(",");
- const result = db
- .prepare(`DELETE FROM free_proxies WHERE id IN (${placeholders})`)
- .run(...staleIds);
- backupDbFile("pre-write");
- return result.changes;
-}
-
// #4878: the displayed "last sync" used to be derived from MAX(last_validated),
// which only advances when a provider returns at least one new/updated proxy. A
// sync that returns zero rows (or whose providers all fail) left the timestamp
diff --git a/src/lib/db/migrations/113_provider_node_icon_url.sql b/src/lib/db/migrations/113_provider_node_icon_url.sql
deleted file mode 100644
index 51737ca8ee..0000000000
--- a/src/lib/db/migrations/113_provider_node_icon_url.sql
+++ /dev/null
@@ -1,5 +0,0 @@
--- Add icon_url column to provider_nodes
--- Stores an optional operator-supplied remote icon URL for OpenAI-/Anthropic-compatible
--- provider nodes. NULL = no custom icon (falls back to the built-in @lobehub/static resolution).
--- Plain TEXT column (no `_json` suffix) — rowToCamel passes it through as a string as-is.
-ALTER TABLE provider_nodes ADD COLUMN icon_url TEXT;
diff --git a/src/lib/db/migrations/114_mux_service_seed.sql b/src/lib/db/migrations/114_mux_service_seed.sql
deleted file mode 100644
index eabd381f03..0000000000
--- a/src/lib/db/migrations/114_mux_service_seed.sql
+++ /dev/null
@@ -1,12 +0,0 @@
--- Migration 114: Seed the Mux (coder/mux) embedded service row.
---
--- Mux is a local agent-orchestration daemon (npm package `mux`, headless
--- `mux server --port <port>` mode) managed via the ServiceSupervisor
--- framework, same shape as 9Router (071) and CLIProxyAPI (016/017).
--- Seeds a `not_installed` / `auto_start=0` placeholder row so the dashboard
--- tab and /api/services/mux/status have a row to read before install.
-
-INSERT OR IGNORE INTO version_manager
- (tool, status, port, auto_start, auto_update, provider_expose)
-VALUES
- ('mux', 'not_installed', 8322, 0, 0, 0);
diff --git a/src/lib/db/migrations/115_bifrost_service.sql b/src/lib/db/migrations/115_bifrost_service.sql
deleted file mode 100644
index b4a3f1bb02..0000000000
--- a/src/lib/db/migrations/115_bifrost_service.sql
+++ /dev/null
@@ -1,9 +0,0 @@
--- Migration 115: Seed version_manager row for Bifrost embedded service
---
--- Bifrost (npm @maximhq/bifrost) is promoted from env-only relay sidecar
--- to a first-class supervised service (v3.8.43).
--- The row is seeded with status='not_installed' so the bootstrap loop
--- skips it until the user installs via /api/services/bifrost/install.
-
-INSERT OR IGNORE INTO version_manager (tool, status, port, auto_start, auto_update, provider_expose)
-VALUES ('bifrost', 'not_installed', 8080, 0, 1, 1);
diff --git a/src/lib/db/providers.ts b/src/lib/db/providers.ts
index e3eeb5419a..f4ed72524f 100644
--- a/src/lib/db/providers.ts
+++ b/src/lib/db/providers.ts
@@ -231,14 +231,6 @@ export async function createProviderConnection(data: JsonRecord) {
data.name,
normalizedProviderSpecificData
);
- } else if (data.authType === "access_token") {
- // #1290 — bare access-token imports (e.g. a raw ChatGPT website access
- // token with no refresh token) are intentionally never deduped: every
- // import creates a new connection. Unlike oauth (workspace+email) or
- // apikey (key-value) imports, a bare access token has no refresh token
- // and no stable long-lived identity to safely dedup against — matching
- // on email alone here would risk silently overwriting an existing full
- // oauth connection for the same account.
}
if (existing) {
@@ -263,7 +255,7 @@ export async function createProviderConnection(data: JsonRecord) {
// Generate name: prefer explicit name, then email, then a stable short-ID label.
// Avoid sequential "Account N" — it reassigns when accounts are deleted/reordered.
let connectionName = data.name || null;
- if (!connectionName && (data.authType === "oauth" || data.authType === "access_token")) {
+ if (!connectionName && data.authType === "oauth") {
if (data.email) {
connectionName = data.email as string;
} else if (data.displayName) {
diff --git a/src/lib/db/providers/nodes.ts b/src/lib/db/providers/nodes.ts
index 667f00900c..08bcad36f7 100644
--- a/src/lib/db/providers/nodes.ts
+++ b/src/lib/db/providers/nodes.ts
@@ -64,8 +64,6 @@ export async function createProviderNode(data: JsonRecord) {
baseUrl: data.baseUrl || null,
chatPath: data.chatPath || null,
modelsPath: data.modelsPath || null,
- // Optional operator-supplied remote icon URL (#2166) — plain TEXT, no JSON parsing needed.
- iconUrl: data.iconUrl || null,
customHeadersJson,
createdAt: now,
updatedAt: now,
@@ -73,8 +71,8 @@ export async function createProviderNode(data: JsonRecord) {
db.prepare(
`
- INSERT INTO provider_nodes (id, type, name, prefix, api_type, base_url, chat_path, models_path, icon_url, custom_headers_json, created_at, updated_at)
- VALUES (@id, @type, @name, @prefix, @apiType, @baseUrl, @chatPath, @modelsPath, @iconUrl, @customHeadersJson, @createdAt, @updatedAt)
+ INSERT INTO provider_nodes (id, type, name, prefix, api_type, base_url, chat_path, models_path, custom_headers_json, created_at, updated_at)
+ VALUES (@id, @type, @name, @prefix, @apiType, @baseUrl, @chatPath, @modelsPath, @customHeadersJson, @createdAt, @updatedAt)
`
).run(node);
@@ -121,8 +119,7 @@ export async function updateProviderNode(id: string, data: JsonRecord) {
`
UPDATE provider_nodes SET type = @type, name = @name, prefix = @prefix,
api_type = @apiType, base_url = @baseUrl, chat_path = @chatPath,
- models_path = @modelsPath, icon_url = @iconUrl,
- custom_headers_json = @customHeadersJson, updated_at = @updatedAt
+ models_path = @modelsPath, custom_headers_json = @customHeadersJson, updated_at = @updatedAt
WHERE id = @id
`
).run({
@@ -134,9 +131,6 @@ export async function updateProviderNode(id: string, data: JsonRecord) {
baseUrl: merged["baseUrl"] || null,
chatPath: merged["chatPath"] || null,
modelsPath: merged["modelsPath"] || null,
- // #2166: iconUrl is nullable — explicit `null` (not omission) clears a previously
- // stored custom icon when the caller submits an empty value.
- iconUrl: merged["iconUrl"] || null,
customHeadersJson: merged["customHeadersJson"] || null,
updatedAt: merged["updatedAt"],
});
diff --git a/src/lib/db/settings.ts b/src/lib/db/settings.ts
index c6aa4bb832..e99fce7c4e 100644
--- a/src/lib/db/settings.ts
+++ b/src/lib/db/settings.ts
@@ -113,11 +113,6 @@ export async function getSettings() {
preferClaudeCodeForUnprefixedClaudeModels: isTruthyEnvFlag(
process.env.OMNIROUTE_PREFER_CLAUDE_CODE_FOR_UNPREFIXED_CLAUDE_MODELS
),
- // Opt-in (default "off"): short-circuits Claude Code's `--permission-mode auto`
- // internal security-classifier request with a synthetic `<block>no</block>` ALLOW
- // response, without calling the upstream provider. See
- // open-sse/handlers/chatCore/claudeClassifierCompat.ts for the detector + builder.
- claudeClassifierCompat: "off",
autoRefreshProviderQuota: false,
autoRefreshProviderQuotaInterval: 180,
comboConfigMode: "guided",
diff --git a/src/lib/discovery/index.ts b/src/lib/discovery/index.ts
index 0631536704..74b0aba0df 100644
--- a/src/lib/discovery/index.ts
+++ b/src/lib/discovery/index.ts
@@ -11,11 +11,6 @@
*/
import { logger } from "../../../open-sse/utils/logger.ts";
-import {
- upsertDiscoveryResult as dbUpsertDiscoveryResult,
- getDiscoveryResults as dbGetDiscoveryResults,
- type DiscoveryResult as DbDiscoveryResult,
-} from "../db/discoveryResults";
const log = logger("DISCOVERY");
@@ -107,24 +102,13 @@ export async function scanProvider(
];
}
-// ── Results (Reporter — Phase 2) ──
+// ── Results ──
/**
- * Persist a discovery finding to the `discovery_results` table via the DB
- * module. Uniqueness is keyed on `(providerId, method, endpoint)`, so
- * re-discovering the same endpoint updates the existing row. Returns the
- * persisted row (with its id).
+ * Get discovery results. Phase 1 stub — returns empty array.
*/
-export function persistDiscoveryResult(result: DiscoveryResult): DiscoveryResult {
- return dbUpsertDiscoveryResult(result as DbDiscoveryResult) as DiscoveryResult;
-}
-
-/**
- * Get discovery results from the DB, optionally filtered to one provider.
- * Newest findings first.
- */
-export function getDiscoveryResults(providerId?: string): DiscoveryResult[] {
- return dbGetDiscoveryResults(providerId) as DiscoveryResult[];
+export function getDiscoveryResults(_providerId?: string): DiscoveryResult[] {
+ return [];
}
// ── Config ──
diff --git a/src/lib/embeddings/service.ts b/src/lib/embeddings/service.ts
index 49b16f9db2..3c467c066c 100644
--- a/src/lib/embeddings/service.ts
+++ b/src/lib/embeddings/service.ts
@@ -12,8 +12,6 @@ import * as log from "@/sse/utils/logger";
import { toJsonErrorPayload } from "@/shared/utils/upstreamError";
import { getProviderCredentials, clearRecoveredProviderState } from "@/sse/services/auth";
import { getProviderNodes, getComboByName, getCombos, getDatabaseSettings } from "@/lib/localDb";
-import { resolveProxyForConnection } from "@/lib/db/settings";
-import { runWithProxyContext } from "@omniroute/open-sse/utils/proxyFetch.ts";
import { handleComboChat } from "@omniroute/open-sse/services/combo.ts";
import { resolveBareModelToConnectionDefault } from "@omniroute/open-sse/services/model.ts";
import { findEmbeddingComboDimensionConflict } from "./familyGuard";
@@ -222,41 +220,20 @@ export async function createEmbeddingResponse(
connectionDefaultModel
);
- // Resolve the connection-level proxy so the upstream embedding request honors
- // the same per-connection pinning as chat, image generation, and count_tokens
- // (#1904-style behavior). Without this, embeddings silently fall back to the
- // global/env proxy and ignore a connection's pinned proxy. Ported from
- // upstream decolua/9router#1701.
- let proxyInfo: Awaited<ReturnType<typeof resolveProxyForConnection>> | null = null;
- const connectionIdForProxy = (credentials as { connectionId?: string } | null)?.connectionId;
- if (connectionIdForProxy) {
- try {
- proxyInfo = await resolveProxyForConnection(connectionIdForProxy);
- } catch (err) {
- log.error("EMBED", `Failed to resolve proxy for connection ${connectionIdForProxy}: ${err}`);
- }
- }
-
- const runEmbedding = () =>
- handleEmbedding({
- body:
- effectiveModel !== resolvedModel ? { ...body, model: `${provider}/${effectiveModel}` } : body,
- // getProviderCredentials returns a richer connection object; handleEmbedding
- // only reads apiKey/accessToken, both present at runtime. Bridge the wider
- // selection type to the handler's narrow credential shape.
- credentials: credentials as { apiKey?: string; accessToken?: string } | null,
- log,
- resolvedProvider: providerConfig,
- resolvedModel: effectiveModel,
- clientRawRequest: options.clientRawRequest || null,
- apiKeyId: options.apiKeyId || null,
- apiKeyName: options.apiKeyName || null,
- connectionId: options.connectionId || null,
- });
-
- const result = connectionIdForProxy
- ? await runWithProxyContext(proxyInfo?.proxy || null, runEmbedding)
- : await runEmbedding();
+ const result = await handleEmbedding({
+ body: effectiveModel !== resolvedModel ? { ...body, model: `${provider}/${effectiveModel}` } : body,
+ // getProviderCredentials returns a richer connection object; handleEmbedding
+ // only reads apiKey/accessToken, both present at runtime. Bridge the wider
+ // selection type to the handler's narrow credential shape.
+ credentials: credentials as { apiKey?: string; accessToken?: string } | null,
+ log,
+ resolvedProvider: providerConfig,
+ resolvedModel: effectiveModel,
+ clientRawRequest: options.clientRawRequest || null,
+ apiKeyId: options.apiKeyId || null,
+ apiKeyName: options.apiKeyName || null,
+ connectionId: options.connectionId || null,
+ });
const responseHeaders = new Headers(result.headers);
diff --git a/src/lib/freeProxyProviders/index.ts b/src/lib/freeProxyProviders/index.ts
index 3f7115069d..8a29d71eb0 100644
--- a/src/lib/freeProxyProviders/index.ts
+++ b/src/lib/freeProxyProviders/index.ts
@@ -2,13 +2,11 @@ import type { FreeProxyProvider, FreeProxySourceId } from "./types";
import { OneproxyProvider } from "./oneproxy";
import { ProxiflyProvider } from "./proxifly";
import { IplocateProvider } from "./iplocate";
-import { WebshareProvider } from "./webshare";
const ALL_PROVIDERS: FreeProxyProvider[] = [
new OneproxyProvider(),
new ProxiflyProvider(),
new IplocateProvider(),
- new WebshareProvider(),
];
export function getProvider(id: FreeProxySourceId): FreeProxyProvider | undefined {
diff --git a/src/lib/freeProxyProviders/types.ts b/src/lib/freeProxyProviders/types.ts
index e050a36880..81bcf86bac 100644
--- a/src/lib/freeProxyProviders/types.ts
+++ b/src/lib/freeProxyProviders/types.ts
@@ -1,4 +1,4 @@
-export type FreeProxySourceId = "1proxy" | "proxifly" | "iplocate" | "webshare";
+export type FreeProxySourceId = "1proxy" | "proxifly" | "iplocate";
export interface FreeProxyItem {
source: FreeProxySourceId;
diff --git a/src/lib/freeProxyProviders/webshare.ts b/src/lib/freeProxyProviders/webshare.ts
deleted file mode 100644
index 0ca393a680..0000000000
--- a/src/lib/freeProxyProviders/webshare.ts
+++ /dev/null
@@ -1,148 +0,0 @@
-import type { FreeProxyItem, FreeProxySyncResult, FreeProxyProvider } from "./types";
-import { isPrivateHost } from "@/shared/network/outboundUrlGuard";
-
-const DEFAULT_API_URL = "https://proxy.webshare.io/api/v2/proxy/list/";
-const DEFAULT_MAX = 500;
-const DEFAULT_PAGE_SIZE = 100;
-const DEFAULT_TIMEOUT_MS = 15_000;
-const MAX_PAGES = 50; // hard stop so a misbehaving `next` cursor can't loop forever
-
-type WebshareApiProxy = {
- proxy_address?: string;
- port?: number;
- valid?: boolean;
- country_code?: string | null;
- last_verification?: string | null;
-};
-
-type WebshareApiResponse = {
- count?: number;
- next?: string | null;
- previous?: string | null;
- results?: WebshareApiProxy[];
-};
-
-/**
- * Webshare (https://proxy.webshare.io) proxy pool — imports the operator's
- * purchased/rotating proxy list via the account API. Unlike the other
- * free-proxy sources this is a paid, per-account list, so it is gated on an
- * API key rather than a plain on/off flag: `isEnabled()` returns false
- * whenever no key is configured, regardless of `FREE_PROXY_WEBSHARE_ENABLED`.
- */
-export class WebshareProvider implements FreeProxyProvider {
- readonly id = "webshare" as const;
- readonly name = "Webshare";
-
- isEnabled(): boolean {
- if (process.env.FREE_PROXY_WEBSHARE_ENABLED === "false") return false;
- return Boolean(process.env.FREE_PROXY_WEBSHARE_API_KEY);
- }
-
- private getConfig() {
- return {
- apiUrl: process.env.FREE_PROXY_WEBSHARE_API_URL || DEFAULT_API_URL,
- apiKey: process.env.FREE_PROXY_WEBSHARE_API_KEY || "",
- maxProxies: parseInt(process.env.FREE_PROXY_WEBSHARE_MAX || "", 10) || DEFAULT_MAX,
- };
- }
-
- async sync(): Promise<FreeProxySyncResult> {
- if (!this.isEnabled()) {
- return {
- fetched: 0,
- added: 0,
- updated: 0,
- errors: ["Webshare provider disabled (set FREE_PROXY_WEBSHARE_API_KEY to enable)"],
- };
- }
-
- const { upsertFreeProxy } = await import("../db/freeProxies");
- const { pruneStaleFreeProxies } = await import("../db/freeProxies");
- const { apiUrl, apiKey, maxProxies } = this.getConfig();
-
- const errors: string[] = [];
- const activeKeys = new Set<string>();
- let added = 0;
- let updated = 0;
- let fetched = 0;
- let page = 1;
-
- try {
- while (fetched < maxProxies && page <= MAX_PAGES) {
- const url = new URL(apiUrl);
- url.searchParams.set("mode", "direct");
- url.searchParams.set("page", String(page));
- url.searchParams.set("page_size", String(Math.min(DEFAULT_PAGE_SIZE, maxProxies - fetched)));
-
- const res = await fetch(url, {
- signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS),
- headers: { Authorization: `Token ${apiKey}` },
- });
-
- if (!res.ok) {
- // Response bodies never contain the request's own Authorization
- // header, so this is safe to surface verbatim (truncated) without
- // leaking the API key.
- const text = await res.text().catch(() => "");
- errors.push(`HTTP ${res.status}: ${text.slice(0, 100)}`);
- break;
- }
-
- const json = (await res.json()) as WebshareApiResponse;
- const results = Array.isArray(json.results) ? json.results : [];
- if (results.length === 0) break;
-
- for (const p of results) {
- if (!p.proxy_address || !p.port) continue;
- if (isPrivateHost(p.proxy_address)) {
- errors.push(`Webshare: skipped private/loopback host ${p.proxy_address}`);
- continue;
- }
- if (p.valid === false) continue;
-
- activeKeys.add(`${p.proxy_address}:${p.port}`);
-
- const item: FreeProxyItem = {
- source: "webshare",
- host: p.proxy_address,
- port: p.port,
- type: "http",
- countryCode: p.country_code || null,
- qualityScore: null,
- latencyMs: null,
- anonymity: null,
- lastValidated: p.last_verification || new Date().toISOString(),
- };
- const result = await upsertFreeProxy(item);
- if (result.action === "created") added++;
- else updated++;
- fetched++;
- }
-
- if (!json.next) break;
- page++;
- }
-
- // Tombstone rows this account no longer lists (recycled/retired IDs).
- // Only run this when the sync completed without a hard error, so a
- // failed fetch never wipes out a previously-good candidate list.
- if (errors.length === 0 && fetched > 0) {
- await pruneStaleFreeProxies("webshare", activeKeys);
- }
- } catch (err) {
- errors.push(err instanceof Error ? err.message : String(err));
- }
-
- return { fetched, added, updated, errors };
- }
-
- async list(filters: {
- protocol?: string;
- country?: string;
- minQuality?: number;
- limit?: number;
- }): Promise<FreeProxyItem[]> {
- const { listFreeProxiesBySource } = await import("../db/freeProxies");
- return listFreeProxiesBySource("webshare", filters);
- }
-}
diff --git a/src/lib/localDb.ts b/src/lib/localDb.ts
index b22f879d0f..227f56f205 100755
--- a/src/lib/localDb.ts
+++ b/src/lib/localDb.ts
@@ -321,22 +321,6 @@ export {
export type { Webhook, WebhookKind } from "./db/webhooks";
export { insertDelivery, getDeliveries } from "./db/webhookDeliveries";
-
-export {
- upsertDiscoveryResult,
- getDiscoveryResults,
- getDiscoveryResultById,
- markVerified,
- deleteDiscoveryResult,
-} from "./db/discoveryResults";
-
-export type {
- DiscoveryResult,
- DiscoveryMethod,
- DiscoveryAuthType,
- DiscoveryRiskLevel,
- DiscoveryStatus,
-} from "./db/discoveryResults";
export type { WebhookDelivery } from "./db/webhookDeliveries";
export {
@@ -557,7 +541,6 @@ export {
promoteFreeProxyToPool,
deleteFreeProxy,
clearFreeProxiesBySource,
- pruneStaleFreeProxies,
getFreeProxyStats,
recordFreeProxySync,
} from "./db/freeProxies";
diff --git a/src/lib/oauth/services/codexImport.ts b/src/lib/oauth/services/codexImport.ts
index 955584e3c6..5ef19be84f 100644
--- a/src/lib/oauth/services/codexImport.ts
+++ b/src/lib/oauth/services/codexImport.ts
@@ -67,15 +67,7 @@ function decodeJwtPayload(jwt: unknown): Record<string, unknown> | null {
}
}
-/**
- * Decode a Codex JWT (id_token, or a bare ChatGPT access token — both carry
- * the same `https://api.openai.com/auth` custom claim) into account info.
- *
- * Exported so other Codex import paths (e.g. the bare-access-token import at
- * `/api/oauth/codex/import-token`, #1290) can reuse this decode logic instead
- * of duplicating an inline JWT decode.
- */
-export function extractCodexAccountInfo(idToken: string): {
+function extractCodexAccountInfo(idToken: string): {
email?: string;
chatgptAccountId?: string;
chatgptPlanType?: string;
diff --git a/src/lib/providers/catalog.ts b/src/lib/providers/catalog.ts
index 1c9d5e4621..7454acc564 100644
--- a/src/lib/providers/catalog.ts
+++ b/src/lib/providers/catalog.ts
@@ -41,8 +41,6 @@ export interface ProviderCatalogMetadata {
riskNoticeVariant?: RiskNoticeVariant;
apiType?: string;
baseUrl?: string;
- /** Optional operator-supplied remote icon URL (#2166) for compatible provider nodes. */
- iconUrl?: string;
[key: string]: unknown;
}
@@ -61,8 +59,6 @@ export interface CompatibleProviderNodeLike {
type?: string | null;
apiType?: string | null;
baseUrl?: string | null;
- /** Optional operator-supplied remote icon URL (#2166). */
- iconUrl?: string | null;
}
export interface CompatibleProviderLabels {
@@ -222,7 +218,6 @@ export function resolveCompatibleProviderCatalogEntry(
textIcon: isCcCompatible ? "CC" : isAnthropicCompatible ? "AC" : "OC",
apiType: providerNode.apiType || undefined,
baseUrl: providerNode.baseUrl || undefined,
- iconUrl: providerNode.iconUrl || undefined,
type: providerNode.type,
category: "compatible",
displayAuthType: "compatible",
diff --git a/src/lib/providers/staticModels.ts b/src/lib/providers/staticModels.ts
index 8a9d18cb8e..e1b921e7e4 100644
--- a/src/lib/providers/staticModels.ts
+++ b/src/lib/providers/staticModels.ts
@@ -37,7 +37,6 @@ const STATIC_MODEL_PROVIDERS: Record<string, () => Array<{ id: string; name: str
{ id: "claude-opus-4-8", name: "Claude Opus 4.8" },
{ id: "claude-opus-4-7", name: "Claude Opus 4.7" },
{ id: "claude-opus-4-6", name: "Claude Opus 4.6" },
- { id: "claude-sonnet-5", name: "Claude Sonnet 5" },
{ id: "claude-sonnet-4-6", name: "Claude Sonnet 4.6" },
{ id: "claude-opus-4-5-20251101", name: "Claude Opus 4.5 (2025-11-01)" },
{ id: "claude-sonnet-4-5-20250929", name: "Claude Sonnet 4.5 (2025-09-29)" },
diff --git a/src/lib/providers/validation.ts b/src/lib/providers/validation.ts
index 867625ccb6..b8df0801a1 100644
--- a/src/lib/providers/validation.ts
+++ b/src/lib/providers/validation.ts
@@ -264,57 +264,7 @@ export async function validateProviderApiKey({ provider, apiKey, providerSpecifi
// ── Specialty provider validation ──
const SPECIALTY_VALIDATORS = {
- "v0-vercel": async ({ apiKey, providerSpecificData }: any) => {
- try {
- const configuredBaseUrl =
- typeof providerSpecificData?.baseUrl === "string" && providerSpecificData.baseUrl.trim()
- ? providerSpecificData.baseUrl.trim()
- : "https://api.v0.dev";
-
- const root = normalizeBaseUrl(configuredBaseUrl)
- .replace(/\/v1\/chat\/completions$/, "")
- .replace(/\/v1$/, "");
-
- const res = await validationRead(
- `${root}/v1/chats?limit=1`,
- {
- method: "GET",
- headers: buildBearerHeaders(apiKey, providerSpecificData),
- },
- isLocal
- );
-
- if (res.ok) {
- return { valid: true, error: null, method: "v0_platform_chats_list" };
- }
-
- if (res.status === 401 || res.status === 403) {
- return { valid: false, error: "Invalid API key" };
- }
-
- return { valid: false, error: `v0 validation failed: ${res.status}` };
- } catch (error: any) {
- return toValidationErrorResult(error);
- }
- },
jules: validateJulesProvider,
- // auggie is a fully local, credential-less CLI passthrough — there is no API
- // key to check upstream. The only meaningful validation is confirming the
- // `auggie` binary is installed and runnable on this machine.
- auggie: async () => {
- const { checkAuggieCliVersion } = await import(
- "@omniroute/open-sse/executors/auggie.ts"
- );
- const result = await checkAuggieCliVersion();
- if (!result.ok) {
- return {
- valid: false,
- error: result.error || "Auggie CLI not found. Install it and run `auggie login`.",
- unsupported: false,
- };
- }
- return { valid: true, error: null, unsupported: false, method: result.version };
- },
qoder: async ({ apiKey, providerSpecificData }: any) => {
// Bifurcate validation: PAT tokens use Cosy auth against api1.qoder.sh;
// regular API keys validate against dashscope (OpenAI-compatible endpoint).
diff --git a/src/lib/providers/validation/webProvidersA.ts b/src/lib/providers/validation/webProvidersA.ts
index ef8c1fd366..709a7cbe18 100644
--- a/src/lib/providers/validation/webProvidersA.ts
+++ b/src/lib/providers/validation/webProvidersA.ts
@@ -112,12 +112,8 @@ export async function validateDeepSeekWebProvider({ apiKey }: any) {
Referer: "https://chat.deepseek.com/",
"User-Agent":
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36",
- // Match the current chat.deepseek.com web client (v2.0.0): the legacy
- // X-App-Version build stamp was dropped, X-Client-Bundle-Id was added.
- // Keep aligned with FAKE_HEADERS in open-sse/executors/deepseek-web.ts.
- "X-Client-Bundle-Id": "com.deepseek.chat",
+ "X-App-Version": "20241129.1",
"X-Client-Platform": "web",
- "X-Client-Version": "2.0.0",
},
});
if (resp.status === 401 || resp.status === 403) {
diff --git a/src/lib/proxyHealth/scheduler.ts b/src/lib/proxyHealth/scheduler.ts
deleted file mode 100644
index 2e6c291125..0000000000
--- a/src/lib/proxyHealth/scheduler.ts
+++ /dev/null
@@ -1,171 +0,0 @@
-/**
- * Proxy Health Check Scheduler
- *
- * Periodically tests all proxy registry entries and automatically
- * removes proxies that have been failing consecutively.
- *
- * Config via environment:
- * PROXY_HEALTH_INTERVAL_MS — sweep interval (default: 600000 = 10min)
- * PROXY_HEALTH_ENABLED — set "false" to disable
- * PROXY_AUTO_REMOVE — set "true" to auto-remove dead proxies
- * PROXY_AUTO_REMOVE_AFTER — consecutive failures before removal (default: 3)
- */
-
-import { deleteProxyById, listProxies, updateProxy } from "@/lib/localDb";
-import { createProxyDispatcher, clearDispatcherCache } from "@omniroute/open-sse/utils/proxyDispatcher";
-import { fetch as undiciFetch } from "undici";
-
-const TEST_TIMEOUT_MS = 5000;
-// Reachability probe target for proxy health checks. Configurable so operators
-// can point it at an internal/self-hosted endpoint instead of the public default.
-const TEST_URL = process.env.PROXY_HEALTH_TEST_URL || "https://httpbin.org/ip";
-const CONCURRENCY = 10;
-const INITIAL_DELAY_MS = 60_000;
-const DEFAULT_INTERVAL_MS = 600_000;
-const DEFAULT_REMOVE_AFTER = 3;
-const LOG_PREFIX = "[ProxyHealth]";
-
-declare global {
- var __proxyHealthInterval: ReturnType<typeof setInterval> | undefined;
- var __proxyHealthConsecutiveFailures: Map<string, number> | undefined;
-}
-
-function getFailureMap(): Map<string, number> {
- if (!globalThis.__proxyHealthConsecutiveFailures) {
- globalThis.__proxyHealthConsecutiveFailures = new Map();
- }
- return globalThis.__proxyHealthConsecutiveFailures;
-}
-
-function isEnabled(): boolean {
- return process.env.PROXY_HEALTH_ENABLED !== "false";
-}
-
-function getIntervalMs(): number {
- const raw = parseInt(process.env.PROXY_HEALTH_INTERVAL_MS ?? "", 10);
- return Number.isFinite(raw) && raw >= 60_000 ? raw : DEFAULT_INTERVAL_MS;
-}
-
-function isAutoRemoveEnabled(): boolean {
- return process.env.PROXY_AUTO_REMOVE === "true";
-}
-
-function getRemoveAfter(): number {
- const raw = parseInt(process.env.PROXY_AUTO_REMOVE_AFTER ?? "", 10);
- return Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_REMOVE_AFTER;
-}
-
-function isBuildProcess(): boolean {
- return typeof process !== "undefined" && process.env.NEXT_PHASE === "phase-production-build";
-}
-
-function isBackgroundServicesDisabled(): boolean {
- const raw = process.env.OMNIROUTE_DISABLE_BACKGROUND_SERVICES;
- if (!raw) return false;
- return ["1", "true", "yes", "on"].includes(raw.trim().toLowerCase());
-}
-
-async function testOneProxy(proxy: { id: string; type: string; host: string; port: number }): Promise<boolean> {
- const proxyUrl = `${proxy.type}://${proxy.host}:${proxy.port}`;
- const controller = new AbortController();
- const timeout = setTimeout(() => controller.abort(), TEST_TIMEOUT_MS);
- try {
- const dispatcher = createProxyDispatcher(proxyUrl);
- const resp = await undiciFetch(TEST_URL, {
- method: "HEAD",
- signal: controller.signal,
- dispatcher,
- headers: { "User-Agent": "OmniRoute/1.0" },
- });
- return resp.status < 500;
- } catch {
- return false;
- } finally {
- clearTimeout(timeout);
- }
-}
-
-async function sweep(): Promise<void> {
- const proxies = await listProxies({ includeSecrets: false });
- if (proxies.length === 0) return;
-
- const failureMap = getFailureMap();
- const removeAfter = getRemoveAfter();
- const autoRemove = isAutoRemoveEnabled();
-
- let tested = 0;
- let alive = 0;
- let removed = 0;
-
- for (let i = 0; i < proxies.length; i += CONCURRENCY) {
- const batch = proxies.slice(i, i + CONCURRENCY);
- const results = await Promise.allSettled(
- batch.map(async (proxy) => {
- const ok = await testOneProxy(proxy);
- return { id: proxy.id, ok };
- })
- );
-
- for (const result of results) {
- if (result.status !== "fulfilled") continue;
- const { id, ok } = result.value;
- tested++;
-
- if (ok) {
- alive++;
- failureMap.delete(id);
- await updateProxy(id, { status: "active" }).catch(() => {});
- } else {
- const failures = (failureMap.get(id) ?? 0) + 1;
- failureMap.set(id, failures);
- await updateProxy(id, { status: "inactive" }).catch(() => {});
-
- if (autoRemove && failures >= removeAfter) {
- if (await deleteProxyById(id, { force: true }).catch(() => false)) {
- failureMap.delete(id);
- removed++;
- try { clearDispatcherCache(); } catch { /* non-critical */ }
- }
- }
- }
- }
- }
-
- console.log(
- `${LOG_PREFIX} Sweep complete: ${tested} tested, ${alive} alive, ${removed} auto-removed`
- );
-}
-
-function scheduleSweep(): void {
- const interval = getIntervalMs();
- globalThis.__proxyHealthInterval = setInterval(() => {
- void sweep().catch((err) => {
- console.error(`${LOG_PREFIX} Sweep error:`, err);
- });
- }, interval);
-}
-
-export function initProxyHealthCheck(): void {
- if (!isEnabled() || isBuildProcess() || isBackgroundServicesDisabled()) return;
- if (globalThis.__proxyHealthInterval) return;
-
- setTimeout(() => {
- console.log(`${LOG_PREFIX} Starting proxy health scheduler (interval: ${getIntervalMs()}ms)`);
- void sweep().catch(() => {});
- scheduleSweep();
- }, INITIAL_DELAY_MS);
-}
-
-export function stopProxyHealthCheck(): void {
- if (globalThis.__proxyHealthInterval) {
- clearInterval(globalThis.__proxyHealthInterval);
- globalThis.__proxyHealthInterval = undefined;
- }
-}
-
-export async function forceProxyHealthSweep(): Promise<void> {
- await sweep();
-}
-
-// Auto-initialize on first import
-initProxyHealthCheck();
diff --git a/src/lib/services/apiKey.ts b/src/lib/services/apiKey.ts
index 2d58ce1bcb..67ff240332 100644
--- a/src/lib/services/apiKey.ts
+++ b/src/lib/services/apiKey.ts
@@ -28,8 +28,7 @@ export async function getOrCreateApiKey(tool: string): Promise<string> {
// operator-facing signal.
throw new ServiceApiKeyDecryptError(tool);
}
- const prefix = tool === "9router" ? "nr" : tool === "mux" ? "mx" : "cp";
- const key = generateServiceApiKey(prefix);
+ const key = generateServiceApiKey(tool === "9router" ? "nr" : "cp");
await updateServiceField(tool, "apiKey", encrypt(key) ?? key);
return key;
}
diff --git a/src/lib/services/bootstrap.ts b/src/lib/services/bootstrap.ts
index 5dea02e9d4..6aa0030ae3 100644
--- a/src/lib/services/bootstrap.ts
+++ b/src/lib/services/bootstrap.ts
@@ -7,19 +7,12 @@ import {
resolveSpawnArgs as cliproxySpawnArgs,
CLIPROXY_DEFAULT_PORT,
} from "./installers/cliproxy";
-import { resolveSpawnArgs as muxSpawnArgs, MUX_DEFAULT_PORT } from "./installers/mux";
-import {
- resolveSpawnArgs as bifrostSpawnArgs,
- BIFROST_DEFAULT_PORT,
-} from "./installers/bifrost";
import { getOrCreateApiKey } from "./apiKey";
import { scheduleServiceModelSync, stopServiceModelSync } from "./modelSync";
import type { ServiceStatus } from "./types";
const NINEROUTER_PORT = parseInt(process.env.NINEROUTER_PORT ?? "20130", 10);
const CLIPROXY_PORT = parseInt(process.env.CLIPROXYAPI_PORT ?? String(CLIPROXY_DEFAULT_PORT), 10);
-const MUX_PORT = parseInt(process.env.MUX_SERVICE_PORT ?? String(MUX_DEFAULT_PORT), 10);
-const BIFROST_PORT = parseInt(process.env.BIFROST_PORT ?? String(BIFROST_DEFAULT_PORT), 10);
type ServiceEntry = {
tool: string;
@@ -50,24 +43,6 @@ const SERVICES: ServiceEntry[] = [
logsBufferBytes: 5_242_880,
needsApiKey: false,
},
- {
- tool: "mux",
- port: MUX_PORT,
- healthPath: "/health",
- healthIntervalMs: 5_000,
- stopTimeoutMs: 15_000,
- logsBufferBytes: 5_242_880,
- needsApiKey: true,
- },
- {
- tool: "bifrost",
- port: BIFROST_PORT,
- healthPath: "/v1/models",
- healthIntervalMs: 5_000,
- stopTimeoutMs: 15_000,
- logsBufferBytes: 5_242_880,
- needsApiKey: false,
- },
];
function buildSpawnArgsFactory(
@@ -77,12 +52,6 @@ function buildSpawnArgsFactory(
if (cfg.tool === "9router") {
return () => nineRouterSpawnArgs(apiKey, cfg.port);
}
- if (cfg.tool === "mux") {
- return () => muxSpawnArgs(apiKey, cfg.port);
- }
- if (cfg.tool === "bifrost") {
- return () => bifrostSpawnArgs(cfg.port);
- }
return () => cliproxySpawnArgs(cfg.port);
}
diff --git a/src/lib/services/installers/bifrost.ts b/src/lib/services/installers/bifrost.ts
deleted file mode 100644
index a097f6cdc5..0000000000
--- a/src/lib/services/installers/bifrost.ts
+++ /dev/null
@@ -1,145 +0,0 @@
-import fs from "node:fs";
-import path from "node:path";
-import { DATA_DIR } from "@/lib/db/core";
-import { upsertVersionManagerTool } from "@/lib/db/versionManager";
-import { runNpm, InstallError } from "./utils";
-
-export const BIFROST_PACKAGE = "@maximhq/bifrost";
-export const BIFROST_DEFAULT_PORT = 8080;
-export const BIFROST_INSTALL_DIR = path.join(DATA_DIR, "services", "bifrost");
-
-export interface InstallResult {
- installedVersion: string;
- installPath: string;
- durationMs: number;
-}
-
-export interface SpawnArgs {
- command: string;
- args: string[];
- env: NodeJS.ProcessEnv;
- cwd: string;
-}
-
-// In-memory latest-version cache, 1h TTL
-let latestVersionCache: { value: string; expiresAt: number } | null = null;
-const VERSION_CACHE_TTL_MS = 3_600_000;
-
-function getInstalledPkgPath(): string {
- return path.join(BIFROST_INSTALL_DIR, "node_modules", "@maximhq", "bifrost", "package.json");
-}
-
-function getBinPath(): string {
- return path.join(BIFROST_INSTALL_DIR, "node_modules", "@maximhq", "bifrost", "bin.js");
-}
-
-function getInstalledVersionSync(): string | null {
- try {
- const raw = fs.readFileSync(getInstalledPkgPath(), "utf8");
- const parsed = JSON.parse(raw) as { version?: string };
- return typeof parsed.version === "string" ? parsed.version : null;
- } catch {
- return null;
- }
-}
-
-export async function getInstalledVersion(): Promise<string | null> {
- return getInstalledVersionSync();
-}
-
-export async function getLatestVersion(): Promise<string | null> {
- if (latestVersionCache && latestVersionCache.expiresAt > Date.now()) {
- return latestVersionCache.value;
- }
- try {
- const { stdout } = await runNpm(["view", BIFROST_PACKAGE, "version"], { timeoutMs: 30_000 });
- const version = stdout.trim();
- if (version) {
- latestVersionCache = { value: version, expiresAt: Date.now() + VERSION_CACHE_TTL_MS };
- }
- return version || null;
- } catch {
- return null;
- }
-}
-
-export async function install(version = "latest"): Promise<InstallResult> {
- const startMs = Date.now();
-
- // Create install dir + minimal package.json (idempotent)
- fs.mkdirSync(BIFROST_INSTALL_DIR, { recursive: true });
- const hostPkgPath = path.join(BIFROST_INSTALL_DIR, "package.json");
- if (!fs.existsSync(hostPkgPath)) {
- fs.writeFileSync(
- hostPkgPath,
- JSON.stringify(
- { name: "omniroute-bifrost-host", version: "0.0.0", private: true, dependencies: {} },
- null,
- 2
- ),
- "utf8"
- );
- }
-
- await runNpm(
- ["install", `${BIFROST_PACKAGE}@${version}`, "--omit=dev", "--no-audit", "--no-fund"],
- // `--prefix` via `prefix` (→ npm_config_prefix env) so paths with spaces survive Windows shell
- { cwd: BIFROST_INSTALL_DIR, prefix: BIFROST_INSTALL_DIR }
- );
-
- const installedVersion = await getInstalledVersion();
- if (!installedVersion) {
- throw new InstallError(
- "Could not read installed version from node_modules/@maximhq/bifrost/package.json",
- "Bifrost instalado mas versão não pôde ser lida.",
- 500
- );
- }
-
- await upsertVersionManagerTool({
- tool: "bifrost",
- installedVersion,
- binaryPath: getBinPath(),
- status: "stopped",
- port: BIFROST_DEFAULT_PORT,
- });
-
- // Invalidate cache so next getLatestVersion() re-fetches
- latestVersionCache = null;
-
- return {
- installedVersion,
- installPath: BIFROST_INSTALL_DIR,
- durationMs: Date.now() - startMs,
- };
-}
-
-export async function update(): Promise<InstallResult> {
- return install("latest");
-}
-
-export function resolveSpawnArgs(port: number): SpawnArgs {
- const binPath = getBinPath();
- // Pin transport version to the installed npm version for reproducibility (spec §2b)
- const transportVersion = getInstalledVersionSync() ?? "latest";
-
- return {
- command: process.execPath,
- args: [
- binPath,
- "-port",
- String(port),
- "-host",
- "127.0.0.1",
- "-app-dir",
- BIFROST_INSTALL_DIR,
- "-log-level",
- "warn",
- ],
- env: {
- ...process.env,
- BIFROST_TRANSPORT_VERSION: transportVersion,
- },
- cwd: BIFROST_INSTALL_DIR,
- };
-}
diff --git a/src/lib/services/installers/mux.ts b/src/lib/services/installers/mux.ts
deleted file mode 100644
index 2ad880cfc4..0000000000
--- a/src/lib/services/installers/mux.ts
+++ /dev/null
@@ -1,178 +0,0 @@
-/**
- * Mux (coder/mux) installer adapter for the ServiceSupervisor framework.
- *
- * Mux (https://github.com/coder/mux) is a local agent-orchestration daemon
- * ("AI agent orchestration") published on npm as the `mux` package, with a
- * documented headless server mode: `mux server --host <host> --port <port>`.
- * It is installed the same way as 9Router — `npm install` into a
- * DATA_DIR-scoped directory via `runNpm` (Hard Rule #13: no shell
- * interpolation, array args + `env` option only) — never a git-clone+build.
- *
- * Binary location: $DATA_DIR/services/mux/node_modules/mux/dist/cli/index.js
- * Data dir: $DATA_DIR/services/mux/data (MUX_HOME — mux's own state)
- * DB row: version_manager WHERE tool = 'mux'
- */
-
-import fs from "node:fs";
-import path from "node:path";
-import { DATA_DIR } from "@/lib/db/core";
-import { upsertVersionManagerTool } from "@/lib/db/versionManager";
-import { runNpm, InstallError } from "./utils";
-
-export const MUX_PACKAGE = "mux";
-export const MUX_DEFAULT_PORT = 8322;
-export const MUX_INSTALL_DIR = path.join(DATA_DIR, "services", "mux");
-
-export interface InstallResult {
- installedVersion: string;
- installPath: string;
- durationMs: number;
-}
-
-export interface SpawnArgs {
- command: string;
- args: string[];
- env: NodeJS.ProcessEnv;
- cwd: string;
-}
-
-// In-memory latest-version cache, 1h TTL — mirrors ninerouter.ts.
-let latestVersionCache: { value: string; expiresAt: number } | null = null;
-const VERSION_CACHE_TTL_MS = 3_600_000;
-
-function getServerPath(): string {
- return path.join(MUX_INSTALL_DIR, "node_modules", "mux", "dist", "cli", "index.js");
-}
-
-function getInstalledPkgPath(): string {
- return path.join(MUX_INSTALL_DIR, "node_modules", "mux", "package.json");
-}
-
-export async function getInstalledVersion(): Promise<string | null> {
- try {
- const raw = fs.readFileSync(getInstalledPkgPath(), "utf8");
- const parsed = JSON.parse(raw) as { version?: string };
- return typeof parsed.version === "string" ? parsed.version : null;
- } catch {
- return null;
- }
-}
-
-export async function getLatestVersion(): Promise<string | null> {
- if (latestVersionCache && latestVersionCache.expiresAt > Date.now()) {
- return latestVersionCache.value;
- }
- try {
- const { stdout } = await runNpm(["view", MUX_PACKAGE, "version"], { timeoutMs: 30_000 });
- const version = stdout.trim();
- if (version) {
- latestVersionCache = { value: version, expiresAt: Date.now() + VERSION_CACHE_TTL_MS };
- }
- return version || null;
- } catch {
- return null;
- }
-}
-
-/**
- * Download and install Mux from npm.
- * Upserts the version_manager row with tool='mux'.
- */
-export async function install(version = "latest"): Promise<InstallResult> {
- const startMs = Date.now();
-
- // Create install dir + minimal package.json (idempotent) — same shape as ninerouter.ts.
- fs.mkdirSync(MUX_INSTALL_DIR, { recursive: true });
- const hostPkgPath = path.join(MUX_INSTALL_DIR, "package.json");
- if (!fs.existsSync(hostPkgPath)) {
- fs.writeFileSync(
- hostPkgPath,
- JSON.stringify(
- { name: "omniroute-mux-host", version: "0.0.0", private: true, dependencies: {} },
- null,
- 2
- ),
- "utf8"
- );
- }
-
- await runNpm(
- ["install", `${MUX_PACKAGE}@${version}`, "--omit=dev", "--no-audit", "--no-fund"],
- // `--prefix` is passed via `prefix` (→ npm_config_prefix env) instead of an
- // argv path so an install dir with spaces survives the Windows shell (#5379).
- { cwd: MUX_INSTALL_DIR, prefix: MUX_INSTALL_DIR }
- );
-
- const installedVersion = await getInstalledVersion();
- if (!installedVersion) {
- throw new InstallError(
- "Could not read installed version from node_modules/mux/package.json",
- "Mux instalado mas versão não pôde ser lida.",
- 500
- );
- }
-
- await upsertVersionManagerTool({
- tool: "mux",
- installedVersion,
- binaryPath: getServerPath(),
- status: "stopped",
- port: MUX_DEFAULT_PORT,
- });
-
- // Invalidate cache so next getLatestVersion() re-fetches
- latestVersionCache = null;
-
- return {
- installedVersion,
- installPath: MUX_INSTALL_DIR,
- durationMs: Date.now() - startMs,
- };
-}
-
-export async function update(): Promise<InstallResult> {
- return install("latest");
-}
-
-export async function uninstall(): Promise<void> {
- const nmDir = path.join(MUX_INSTALL_DIR, "node_modules");
- if (fs.existsSync(nmDir)) {
- fs.rmSync(nmDir, { recursive: true, force: true });
- }
- await upsertVersionManagerTool({
- tool: "mux",
- status: "not_installed",
- installedVersion: null,
- binaryPath: null,
- });
-}
-
-/**
- * Build spawn args for ServiceSupervisor.start().
- *
- * Mux binds to 127.0.0.1 explicitly (never 0.0.0.0) — the dashboard route is
- * already loopback-gated (Hard Rule #17), and this is defense-in-depth since
- * Mux orchestrates AI agents that can execute shell commands on the host.
- * The bearer token is passed via `MUX_SERVER_AUTH_TOKEN` (mux's documented env
- * form), never as a CLI arg, so it never appears in `ps`/process listings.
- */
-export function resolveSpawnArgs(apiKey: string, port: number): SpawnArgs {
- const serverPath = getServerPath();
- // MUX_ROOT is mux's documented override for its home/config/data directory
- // (defaults to ~/.mux otherwise) — scope it under DATA_DIR like every other
- // embedded service instead of leaking into the OS-user home directory.
- const muxRoot = path.join(MUX_INSTALL_DIR, "data");
- fs.mkdirSync(muxRoot, { recursive: true });
-
- return {
- command: process.execPath,
- args: [serverPath, "server", "--host", "127.0.0.1", "--port", String(port)],
- env: {
- ...process.env,
- NODE_ENV: "production",
- MUX_ROOT: muxRoot,
- MUX_SERVER_AUTH_TOKEN: apiKey,
- },
- cwd: MUX_INSTALL_DIR,
- };
-}
diff --git a/src/lib/usage/providerLimits.ts b/src/lib/usage/providerLimits.ts
index d3de997e75..d089f23483 100644
--- a/src/lib/usage/providerLimits.ts
+++ b/src/lib/usage/providerLimits.ts
@@ -74,9 +74,6 @@ const PROVIDER_LIMITS_APIKEY_PROVIDERS = new Set([
"vertex",
"vertex-partner",
"kimi-coding-apikey",
- // Qoder connections are PAT-based (authType "apikey"); the usage fetcher
- // exchanges the PAT for a job token and reads openapi.qoder.sh/user/status.
- "qoder",
]);
const DEFAULT_PROVIDER_LIMITS_SYNC_INTERVAL_MINUTES = 70;
const PROVIDER_LIMITS_AUTO_SYNC_SETTING_KEY = "provider_limits_auto_sync_last_run";
@@ -173,7 +170,7 @@ function shouldRefreshProviderLimitsCache(
);
}
-export function isSupportedUsageConnection(connection: ProviderConnectionLike | null): boolean {
+function isSupportedUsageConnection(connection: ProviderConnectionLike | null): boolean {
if (
!connection ||
!connection.provider ||
diff --git a/src/server/authz/pipeline.ts b/src/server/authz/pipeline.ts
index 5312974006..247391c179 100644
--- a/src/server/authz/pipeline.ts
+++ b/src/server/authz/pipeline.ts
@@ -148,7 +148,7 @@ async function refreshDashboardSessionIfNeeded(
}
function dashboardLoginRedirect(request: NextRequest, requestId: string): NextResponse {
- const response = NextResponse.redirect(new URL(`${request.nextUrl.basePath}/login`, request.url));
+ const response = NextResponse.redirect(new URL("/login", request.url));
response.cookies.delete("auth_token");
stampRouteResponse(response, requestId, "MANAGEMENT");
applyCorsHeaders(response, request);
@@ -223,9 +223,7 @@ export async function runAuthzPipeline(
const requestId = generateRequestId();
if (pathname === "/") {
- const response = NextResponse.redirect(
- new URL(`${request.nextUrl.basePath}/dashboard`, request.url)
- );
+ const response = NextResponse.redirect(new URL("/dashboard", request.url));
return stampRouteResponse(response, requestId, "MANAGEMENT");
}
diff --git a/src/server/authz/routeGuard.ts b/src/server/authz/routeGuard.ts
index b921eb57cc..8874ed33f7 100644
--- a/src/server/authz/routeGuard.ts
+++ b/src/server/authz/routeGuard.ts
@@ -42,7 +42,6 @@ export const LOCAL_ONLY_API_PREFIXES: ReadonlyArray<string> = [
"/api/headroom/start", // Headroom token-saver proxy lifecycle: spawns headroom-ai python CLI (Hard Rules #15 + #17)
"/api/headroom/stop", // Headroom token-saver proxy lifecycle: sends SIGTERM/SIGKILL to managed PID (Hard Rules #15 + #17)
"/api/oauth/cursor/auto-import", // spawns `execFile("which", ["cursor"])` to verify a local Cursor install before importing creds — RCE-via-tunnel surface (Hard Rules #15 + #17, found by 6A.8 route-guard gate). Specific path only: the rest of /api/oauth/ (browser redirect/callback flows) must stay remote-reachable.
- "/api/discovery/", // Discovery tool (opt-in provider scanner): the scan route makes outbound probes to provider endpoints (SSRF-adjacent) and the whole surface is an admin research tool — strict-loopback only, no manage-scope bypass (NOT in LOCAL_ONLY_MANAGE_SCOPE_BYPASS_PREFIXES). See _tasks/features-v3.8.42/gaps/DISCOVERY_TOOL_DESIGN.md.
];
/**
diff --git a/src/server/cors/origins.ts b/src/server/cors/origins.ts
index f6a748fb6a..139966f85e 100644
--- a/src/server/cors/origins.ts
+++ b/src/server/cors/origins.ts
@@ -96,28 +96,6 @@ export function resolveAllowedOrigin(requestOrigin: string | null | undefined):
return null;
}
-/**
- * Read-only snapshot of the effective CORS allowlist configuration, for
- * dashboards / monitoring (`/api/settings/authz-inventory`). `allowAll` mirrors
- * the `CORS_ALLOW_ALL` opt-in (and the legacy `CORS_ORIGIN=*`); `allowedOrigins`
- * is the merged, normalized, sorted, deduped env + runtime allowlist.
- *
- * A `true` `allowAll` is what the dashboard surfaces as a wildcard-CORS warning.
- * See `docs/security/CORS.md`.
- */
-export interface CorsStatus {
- allowAll: boolean;
- allowedOrigins: string[];
-}
-
-export function getCorsStatus(): CorsStatus {
- const merged = new Set<string>([...envAllowedOrigins(), ...runtimeAllowedOrigins]);
- return {
- allowAll: envAllowAll(),
- allowedOrigins: [...merged].sort(),
- };
-}
-
/**
* Apply CORS headers to a response in-place. Safe to call on any response
* (rejections, preflight, normal `next()` continuations). When the origin
diff --git a/src/shared/components/LanguageSelector.tsx b/src/shared/components/LanguageSelector.tsx
index c136bf7bd7..94d6f70b0c 100644
--- a/src/shared/components/LanguageSelector.tsx
+++ b/src/shared/components/LanguageSelector.tsx
@@ -2,10 +2,19 @@
import { useState, useRef, useEffect } from "react";
import { useRouter } from "next/navigation";
-import { LANGUAGES } from "@/i18n/config";
+import { LANGUAGES, LOCALE_COOKIE } from "@/i18n/config";
import type { Locale } from "@/i18n/config";
import { useLocale } from "next-intl";
-import { persistLocale } from "@/shared/lib/persistLocale";
+
+/** Persist locale preference in cookie + localStorage (outside component scope for ESLint) */
+function persistLocale(code: Locale) {
+ document.cookie = `${LOCALE_COOKIE}=${code};path=/;max-age=${365 * 24 * 60 * 60};samesite=lax`;
+ try {
+ localStorage.setItem(LOCALE_COOKIE, code);
+ } catch {
+ // Ignore
+ }
+}
function CountryFlag({ emoji, alt }: { emoji: string; alt: string }) {
const [error, setError] = useState(false);
diff --git a/src/shared/components/LocaleAutoDetect.tsx b/src/shared/components/LocaleAutoDetect.tsx
deleted file mode 100644
index e84c75bc7a..0000000000
--- a/src/shared/components/LocaleAutoDetect.tsx
+++ /dev/null
@@ -1,39 +0,0 @@
-"use client";
-
-import { useEffect } from "react";
-import { useRouter } from "next/navigation";
-import { LOCALES, LOCALE_COOKIE } from "@/i18n/config";
-import type { Locale } from "@/i18n/config";
-import { detectBrowserLocale } from "@/i18n/detectBrowserLocale";
-import { persistLocale } from "@/shared/lib/persistLocale";
-
-function hasLocaleCookie(): boolean {
- return document.cookie
- .split(";")
- .some((entry) => entry.trim().startsWith(`${LOCALE_COOKIE}=`));
-}
-
-/**
- * Auto-detects the browser language on first visit (no locale cookie set
- * yet) and persists it via the same writer `LanguageSelector` uses for a
- * manual selection, then refreshes the router so the server re-renders with
- * the detected locale. Mounted once in the root layout; renders nothing.
- */
-export function LocaleAutoDetect() {
- const router = useRouter();
-
- useEffect(() => {
- if (typeof navigator === "undefined" || hasLocaleCookie()) return;
-
- const detected = detectBrowserLocale(navigator.languages ?? [navigator.language], LOCALES);
- if (!detected) return;
-
- persistLocale(detected as Locale);
- router.refresh();
- // Run once on mount only — this is a first-visit detection, not a
- // reactive effect that should re-run on router identity changes.
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
-
- return null;
-}
diff --git a/src/shared/components/OAuthModal.tsx b/src/shared/components/OAuthModal.tsx
index 0c01342aef..0766a31f68 100644
--- a/src/shared/components/OAuthModal.tsx
+++ b/src/shared/components/OAuthModal.tsx
@@ -657,26 +657,6 @@ export default function OAuthModal({
await submitCredentialBlob(provider, callbackUrl, reauthConnection, setStep, onSuccess);
return;
}
-
- // Codex: a bare ChatGPT access token (JWT, no refresh token) pasted
- // directly instead of a callback URL/code — mirrors the grok-cli
- // raw-token paste pattern. Routed through the access-token-only import
- // endpoint (#1290) instead of the authorization-code exchange below.
- if (provider === "codex" && /^eyJ/.test(callbackUrl.trim())) {
- const res = await fetch("/api/oauth/codex/import-token", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ accessToken: callbackUrl.trim() }),
- });
- const data = (await parseResponseBody(res)) as Record<string, unknown>;
- if (!res.ok) {
- throw new Error(getErrorMessage(data, res.status, "Failed to import access token"));
- }
- setStep("success");
- onSuccess?.();
- return;
- }
-
if (!authData) {
throw new Error(
"OAuth session not initialized. Restart the connection flow and try again."
diff --git a/src/shared/components/ProviderIcon.tsx b/src/shared/components/ProviderIcon.tsx
index c12fb7ec7c..e3d8486a7d 100644
--- a/src/shared/components/ProviderIcon.tsx
+++ b/src/shared/components/ProviderIcon.tsx
@@ -4,10 +4,6 @@
* ProviderIcon — Renders a provider logo using @lobehub/icons with static asset fallbacks.
*
* Strategy (#529):
- * 0. If `src` is set (operator-supplied remote icon URL, #2166), render it — this always
- * wins over the @lobehub/static resolution below. On load error, falls back to
- * `fallbackText`/`fallbackColor` (a colored text badge) if provided, otherwise falls
- * through to steps 1-4.
* 1. Try @lobehub/icons direct icon components (no @lobehub/ui peer runtime)
* 2. Fall back to /providers/{id}.png (existing static assets)
* 3. Fall back to /providers/{id}.svg (SVG assets)
@@ -16,7 +12,6 @@
* Usage:
* <ProviderIcon providerId="openai" size={24} />
* <ProviderIcon providerId="anthropic" size={28} type="color" />
- * <ProviderIcon providerId="openai-compatible-abc" src={node.iconUrl} fallbackText="OC" />
*/
import { createElement, memo, useState } from "react";
@@ -30,16 +25,6 @@ interface ProviderIconProps {
type?: "mono" | "color";
className?: string;
style?: React.CSSProperties;
- /**
- * Optional operator-supplied remote icon URL (#2166) — e.g. a custom icon set for an
- * OpenAI-/Anthropic-compatible provider node. When set, this always takes priority
- * over the @lobehub/static resolution. On load error, falls back to `fallbackText`
- * (if provided) or the normal resolution chain below.
- */
- src?: string;
- alt?: string;
- fallbackText?: string;
- fallbackColor?: string;
}
function GenericProviderIcon({ size }: { size: number }) {
@@ -137,10 +122,6 @@ const ProviderIcon = memo(function ProviderIcon({
type = "color",
className,
style,
- src,
- alt,
- fallbackText,
- fallbackColor,
}: ProviderIconProps) {
const normalizedId = providerId.toLowerCase();
const lobeIcon = getLobeProviderIcon(normalizedId, type);
@@ -148,55 +129,11 @@ const ProviderIcon = memo(function ProviderIcon({
const hasSvg = KNOWN_SVGS.has(normalizedId);
const [failedAssets, setFailedAssets] = useState<Record<string, true>>({});
- const [remoteSrcFailed, setRemoteSrcFailed] = useState(false);
const pngKey = `${normalizedId}:png`;
const svgKey = `${normalizedId}:svg`;
const usePng = !lobeIcon && hasPng && !failedAssets[pngKey];
const useSvg = !lobeIcon && hasSvg && !failedAssets[svgKey] && (!hasPng || failedAssets[pngKey]);
- const trimmedSrc = typeof src === "string" ? src.trim() : "";
-
- // #2166: a custom remote icon URL always wins over the @lobehub/static resolution
- // below. It is a plain <img> (not next/image) so operators can point at any host
- // without requiring `images.remotePatterns` allow-listing for arbitrary domains.
- if (trimmedSrc && !remoteSrcFailed) {
- return (
- <span className={className} style={{ display: "inline-flex", alignItems: "center", ...style }}>
- {/* eslint-disable-next-line @next/next/no-img-element -- operator-supplied remote URL, not a static/known asset */}
- <img
- src={trimmedSrc}
- alt={alt || providerId}
- width={size}
- height={size}
- style={{ objectFit: "contain", flex: "none" }}
- onError={() => setRemoteSrcFailed(true)}
- />
- </span>
- );
- }
-
- if (trimmedSrc && remoteSrcFailed && fallbackText) {
- return (
- <span
- className={className}
- style={{
- display: "inline-flex",
- alignItems: "center",
- justifyContent: "center",
- width: size,
- height: size,
- fontSize: Math.max(10, Math.round(size * 0.4)),
- fontWeight: 700,
- lineHeight: 1,
- color: fallbackColor || "currentColor",
- ...style,
- }}
- >
- {fallbackText}
- </span>
- );
- }
-
if (lobeIcon) {
return (
<span
diff --git a/src/shared/constants/cliTools.ts b/src/shared/constants/cliTools.ts
index 70245a675b..297d615acc 100644
--- a/src/shared/constants/cliTools.ts
+++ b/src/shared/constants/cliTools.ts
@@ -645,13 +645,7 @@ aider --openai-api-base "{{baseUrl}}" --model "{{model}}"`,
defaultCommand: "jcode",
},
- /**
- * ★ Added by plan 14 (CLI Pages Redesign) — 2026-05-27
- * Kept as a legacy/dual entry after CodeWhale (see below) took over as the
- * actively-maintained successor. Existing users who still have DeepSeek
- * TUI installed keep a working dashboard card; new users are steered to
- * "codewhale" instead.
- */
+ /** ★ Added by plan 14 (CLI Pages Redesign) — 2026-05-27 */
"deepseek-tui": {
id: "deepseek-tui",
name: "DeepSeek TUI",
@@ -667,29 +661,6 @@ aider --openai-api-base "{{baseUrl}}" --model "{{model}}"`,
defaultCommand: "deepseek-tui",
},
- /**
- * ★ Added 2026-07-02 (dual-entry, see deepseek-tui above). CodeWhale is
- * the actively-maintained successor to DeepSeek TUI — same author, new
- * name. Config lives under ~/.codewhale/config.toml; the settings route
- * also keeps ~/.deepseek/config.toml (legacy) in sync for upgrading
- * users. Reference: https://github.com/Hmbown/CodeWhale
- */
- codewhale: {
- id: "codewhale",
- name: "CodeWhale",
- icon: "terminal",
- color: "#4F46E5",
- description:
- "CodeWhale — Rust-based coding agent CLI with OPENAI_BASE_URL support (successor to DeepSeek TUI)",
- docsUrl: "https://github.com/Hmbown/CodeWhale",
- configType: "custom",
- category: "code",
- vendor: "OSS (Hmbown)",
- acpSpawnable: false,
- baseUrlSupport: "full",
- defaultCommand: "codewhale",
- },
-
/** ★ Added by plan 14 (CLI Pages Redesign) — 2026-05-27 */
smelt: {
id: "smelt",
@@ -722,22 +693,6 @@ aider --openai-api-base "{{baseUrl}}" --model "{{model}}"`,
defaultCommand: "pi",
},
- /** Added — ported from upstream decolua/9router#1233 (dashboard catalog entry for Crush). */
- crush: {
- id: "crush",
- name: "Crush",
- icon: "terminal",
- color: "#FB923C",
- description: "Crush coding agent CLI — terminal AI agent by Charm (charmbracelet/crush)",
- docsUrl: "https://github.com/charmbracelet/crush",
- configType: "custom",
- category: "code",
- vendor: "OSS (Charm)",
- acpSpawnable: false,
- baseUrlSupport: "full",
- defaultCommand: "crush",
- },
-
// ── Agent entries ─────────────────────────────────────────────────────────
/** ★ Added by plan 14 (CLI Pages Redesign) — 2026-05-27 */
diff --git a/src/shared/constants/clientIdentityProfiles.ts b/src/shared/constants/clientIdentityProfiles.ts
deleted file mode 100644
index 3b3ef31e5a..0000000000
--- a/src/shared/constants/clientIdentityProfiles.ts
+++ /dev/null
@@ -1,89 +0,0 @@
-/**
- * Named "client identity" header presets for OpenAI-/Anthropic-compatible
- * provider nodes (e.g. mimicking a known CLI's `User-Agent`).
- *
- * This module is intentionally dumb: it only supplies preset header
- * VALUES. It introduces NO new header-merge path — selecting a profile in
- * the compatible-provider UI merges its headers into the SAME
- * `providerSpecificData.customHeaders` field already wired end-to-end
- * (node -> connection -> `DefaultExecutor.buildHeaders()` ->
- * `applyCustomHeaders()` in `open-sse/executors/default.ts`), which already
- * sanitizes via `isForbiddenCustomHeaderName` (`upstreamHeaders.ts`) and is
- * applied AFTER the credential-auth headers are set. Auth/cookie headers
- * therefore always win over anything a profile (or a hand-edited custom
- * header) tries to set — no new precedence logic is needed here.
- */
-
-export interface ClientIdentityProfile {
- readonly id: string;
- readonly label: string;
- readonly headers: Readonly<Record<string, string>>;
-}
-
-const DEFAULT_PROFILE: ClientIdentityProfile = Object.freeze({
- id: "default",
- label: "Default",
- headers: Object.freeze({}),
-});
-
-const CLAUDE_CLI_PROFILE: ClientIdentityProfile = Object.freeze({
- id: "claude-cli",
- label: "Claude CLI",
- headers: Object.freeze({
- "User-Agent": "claude-cli/2.1.195 (external, cli)",
- "X-App": "cli",
- }),
-});
-
-const CODEX_CLI_PROFILE: ClientIdentityProfile = Object.freeze({
- id: "codex-cli",
- label: "Codex CLI",
- headers: Object.freeze({
- "User-Agent": "codex_cli_rs/0.136.0",
- originator: "codex_cli_rs",
- }),
-});
-
-const GEMINI_CLI_PROFILE: ClientIdentityProfile = Object.freeze({
- id: "gemini-cli",
- label: "Gemini CLI",
- headers: Object.freeze({
- "User-Agent": "GeminiCLI/0.1.0 (linux; x64)",
- }),
-});
-
-/** Ordered so `CLIENT_IDENTITY_PROFILE_OPTIONS` renders "Default" first. */
-export const CLIENT_IDENTITY_PROFILES: Readonly<Record<string, ClientIdentityProfile>> =
- Object.freeze({
- default: DEFAULT_PROFILE,
- "claude-cli": CLAUDE_CLI_PROFILE,
- "codex-cli": CODEX_CLI_PROFILE,
- "gemini-cli": GEMINI_CLI_PROFILE,
- });
-
-export const CLIENT_IDENTITY_PROFILE_IDS: readonly string[] = Object.keys(
- CLIENT_IDENTITY_PROFILES
-);
-
-export const CLIENT_IDENTITY_PROFILE_OPTIONS: ReadonlyArray<{ value: string; label: string }> =
- CLIENT_IDENTITY_PROFILE_IDS.map((id) => ({
- value: id,
- label: CLIENT_IDENTITY_PROFILES[id].label,
- }));
-
-export function isClientIdentityProfileId(value: unknown): value is string {
- return typeof value === "string" && Object.prototype.hasOwnProperty.call(CLIENT_IDENTITY_PROFILES, value);
-}
-
-/**
- * Returns a plain (mutable, unfrozen) copy of the preset's headers so callers
- * can safely spread/merge it into `providerSpecificData.customHeaders`
- * without ever needing to sanitize here — that happens downstream in
- * `applyCustomHeaders()` regardless of where the header entries came from.
- */
-export function getClientIdentityProfileHeaders(
- profileId: string | undefined | null
-): Record<string, string> {
- if (!isClientIdentityProfileId(profileId)) return {};
- return { ...CLIENT_IDENTITY_PROFILES[profileId].headers };
-}
diff --git a/src/shared/constants/config.ts b/src/shared/constants/config.ts
index edbd57987b..0b8262fe64 100644
--- a/src/shared/constants/config.ts
+++ b/src/shared/constants/config.ts
@@ -5,8 +5,6 @@ export const PROVIDER_ENDPOINTS = {
agentrouter: "https://agentrouter.org/v1/chat/completions",
openrouter: "https://openrouter.ai/api/v1/chat/completions",
dgrid: "https://api.dgrid.ai/v1/chat/completions",
- bai: "https://api.b.ai/v1/chat/completions",
- qiniu: "https://api.qnaigc.com/v1/chat/completions",
glm: "https://api.z.ai/api/anthropic/v1/messages",
glmt: "https://api.z.ai/api/anthropic/v1/messages",
"bailian-coding-plan": "https://coding-intl.dashscope.aliyuncs.com/apps/anthropic/v1/messages",
@@ -20,8 +18,6 @@ export const PROVIDER_ENDPOINTS = {
openadapter: "https://api.openadapter.in/v1/chat/completions",
dit: "https://api.dit.ai/v1/chat/completions",
tokenrouter: "https://api.tokenrouter.com/v1/chat/completions",
- sumopod: "https://ai.sumopod.com/v1/chat/completions",
- x5lab: "https://api.x5lab.dev/v1/chat/completions",
openai: "https://api.openai.com/v1/chat/completions",
anthropic: "https://api.anthropic.com/v1/messages",
gemini: "https://generativelanguage.googleapis.com/v1beta/models",
diff --git a/src/shared/constants/endpointCategories.ts b/src/shared/constants/endpointCategories.ts
index fd761f9987..509b534282 100644
--- a/src/shared/constants/endpointCategories.ts
+++ b/src/shared/constants/endpointCategories.ts
@@ -22,7 +22,12 @@ export const ENDPOINT_CATEGORIES: readonly EndpointCategory[] = [
id: "chat",
label: "Chat / Messages",
description: "Chat completions, text completions, messages, and responses",
- prefixes: ["/v1/chat/completions", "/v1/completions", "/v1/messages", "/v1/responses"],
+ prefixes: [
+ "/v1/chat/completions",
+ "/v1/completions",
+ "/v1/messages",
+ "/v1/responses",
+ ],
},
{
id: "search",
@@ -78,12 +83,6 @@ export const ENDPOINT_CATEGORIES: readonly EndpointCategory[] = [
description: "Content moderation",
prefixes: ["/v1/moderations"],
},
- {
- id: "ocr",
- label: "OCR",
- description: "Optical character recognition",
- prefixes: ["/v1/ocr"],
- },
{
id: "batches",
label: "Batch Processing",
diff --git a/src/shared/constants/modelSpecs.ts b/src/shared/constants/modelSpecs.ts
index c0a6ff402c..3f9e54eb3b 100644
--- a/src/shared/constants/modelSpecs.ts
+++ b/src/shared/constants/modelSpecs.ts
@@ -198,22 +198,6 @@ export const MODEL_SPECS: Record<string, ModelSpec> = {
aliases: BEDROCK_CLAUDE_ALIASES("claude-sonnet-4-6", "claude-sonnet-4.6"),
},
- // ── Claude Sonnet 5 ─────────────────────────────────────────────
- "claude-sonnet-5": {
- // 1M context, 128K max output. Adaptive-thinking-only (manual
- // budget_tokens / thinking.type:"enabled" return 400; effort-steered);
- // unlike Fable 5 it still accepts thinking.type:"disabled".
- maxOutputTokens: 128000,
- contextWindow: 1000000,
- defaultThinkingBudget: 32000,
- thinkingBudgetCap: 120000,
- supportsThinking: true,
- supportsTools: true,
- supportsVision: true,
- adaptiveThinkingOnly: true,
- aliases: BEDROCK_CLAUDE_ALIASES("claude-sonnet-5"),
- },
-
// ── Claude Opus 4.6 ─────────────────────────────────────────────
"claude-opus-4-6": {
maxOutputTokens: 128000,
diff --git a/src/shared/constants/pricing/frontier-labs.ts b/src/shared/constants/pricing/frontier-labs.ts
index 3c6d4819d3..f8da44774f 100644
--- a/src/shared/constants/pricing/frontier-labs.ts
+++ b/src/shared/constants/pricing/frontier-labs.ts
@@ -9,7 +9,6 @@ import {
CLAUDE_SONNET_4_PRICING,
CLAUDE_OPUS_46_PRICING,
CLAUDE_SONNET_46_PRICING,
- CLAUDE_SONNET_5_PRICING,
} from "./shared-tiers";
export const DEFAULT_PRICING_FRONTIER = {
@@ -206,7 +205,6 @@ export const DEFAULT_PRICING_FRONTIER = {
// Intentional duplicates of dot-notation variants (e.g. claude-opus-4.6)
// to cover hyphen-notation IDs (claude-opus-4-6) used by some clients
"claude-fable-5": CLAUDE_FABLE_5_PRICING,
- "claude-sonnet-5": CLAUDE_SONNET_5_PRICING,
"claude-opus-4.8": CLAUDE_OPUS_4_PRICING,
"claude-opus-4-8": CLAUDE_OPUS_4_PRICING,
"claude-opus-4-7": CLAUDE_OPUS_4_PRICING,
diff --git a/src/shared/constants/pricing/oauth-subscriptions.ts b/src/shared/constants/pricing/oauth-subscriptions.ts
index b5aa770351..3726083ca6 100644
--- a/src/shared/constants/pricing/oauth-subscriptions.ts
+++ b/src/shared/constants/pricing/oauth-subscriptions.ts
@@ -41,13 +41,6 @@ export const DEFAULT_PRICING_OAUTH = {
reasoning: 15.0,
cache_creation: 3.75,
},
- "claude-sonnet-5": {
- input: 3.0,
- output: 15.0,
- cached: 0.3,
- reasoning: 15.0,
- cache_creation: 3.75,
- },
"claude-opus-4-5-20251101": {
input: 5.0,
output: 25.0,
diff --git a/src/shared/constants/pricing/shared-tiers.ts b/src/shared/constants/pricing/shared-tiers.ts
index 1d6cec77e6..768642c5a3 100644
--- a/src/shared/constants/pricing/shared-tiers.ts
+++ b/src/shared/constants/pricing/shared-tiers.ts
@@ -57,16 +57,6 @@ export const CLAUDE_SONNET_46_PRICING = {
cache_creation: 3.0,
};
-// Claude Sonnet 5 — Sonnet-tier ($3/$15/M, same sticker as Sonnet 4.6; intro
-// $2/$10 through 2026-08-31 not encoded — track the standard rate like 4.6).
-export const CLAUDE_SONNET_5_PRICING = {
- input: 3.0,
- output: 15.0,
- cached: 1.5,
- reasoning: 22.5,
- cache_creation: 3.0,
-};
-
export const GLM_PRICING = {
"glm-5.2": {
input: 1.2,
diff --git a/src/shared/constants/providers.ts b/src/shared/constants/providers.ts
index 36f3a535e4..336664da44 100644
--- a/src/shared/constants/providers.ts
+++ b/src/shared/constants/providers.ts
@@ -33,11 +33,6 @@ export const FREE_APIKEY_PROVIDER_IDS = new Set([
// API key (Authorization: Bearer). Admit it through the same managed-provider
// gate so POST /api/providers accepts the dual-auth shape.
"codebuddy-cn",
- // auggie is a fully local, credential-less CLI passthrough (auth handled by
- // `auggie login` outside OmniRoute). Admitted here purely so POST /api/providers
- // accepts an optional connection row for display/priority/testStatus tracking —
- // no apiKey is ever required or sent upstream.
- "auggie",
]);
export function supportsApiKeyOnFreeProvider(providerId: unknown): boolean {
@@ -399,7 +394,6 @@ export const USAGE_SUPPORTED_PROVIDERS = [
"codex",
"claude",
"cursor",
- "qoder",
"kimi-coding",
"kimi-coding-apikey",
"glm",
diff --git a/src/shared/constants/providers/apikey/gateways.ts b/src/shared/constants/providers/apikey/gateways.ts
index 4b0e2e31af..0fca742cb5 100644
--- a/src/shared/constants/providers/apikey/gateways.ts
+++ b/src/shared/constants/providers/apikey/gateways.ts
@@ -3,20 +3,6 @@
* Pure data; merged by apikey/index.ts via spread (god-file decomposition; semantic split).
*/
export const APIKEY_PROVIDERS_GATEWAYS = {
- "charm-hyper": {
- id: "charm-hyper",
- alias: "charm-hyper",
- name: "Charm Hyper",
- icon: "router",
- color: "#7C3AED",
- textIcon: "CH",
- passthroughModels: true,
- website: "https://hyper.charm.land",
- hasFree: true,
- freeNote: "100 free monthly Hypercredits on signup",
- apiHint:
- "Create an API key at https://hyper.charm.land, then paste it here as a Bearer token.",
- },
agentrouter: {
id: "agentrouter",
alias: "agentrouter",
@@ -42,20 +28,6 @@ export const APIKEY_PROVIDERS_GATEWAYS = {
"Use a Command Code API key. Requests are sent to Command Code's /alpha/generate endpoint.",
apiHint: "Create or copy an API key from Command Code, then paste it here as a Bearer token.",
},
- clinepass: {
- id: "clinepass",
- alias: "clinepass",
- name: "ClinePass",
- icon: "vpn_key",
- color: "#5B9BD5",
- textIcon: "CP",
- passthroughModels: true,
- website: "https://cline.bot",
- notice: {
- text: "ClinePass is Cline's paid BYOK gateway ($9.99/mo). Bring your own Cline API key; requests hit api.cline.bot with the cline-pass/* model namespace.",
- apiKeyUrl: "https://app.cline.bot/settings/api-keys",
- },
- },
openrouter: {
id: "openrouter",
alias: "openrouter",
@@ -85,20 +57,6 @@ export const APIKEY_PROVIDERS_GATEWAYS = {
"Create a DGrid API key at https://dgrid.ai, then use https://api.dgrid.ai/v1 " +
"as the OpenAI-compatible base URL.",
},
- qiniu: {
- id: "qiniu",
- alias: "qiniu",
- name: "Qiniu",
- icon: "cloud",
- color: "#1E88E5",
- textIcon: "QN",
- passthroughModels: true,
- website: "https://www.qiniu.com",
- apiHint:
- "Create a Qiniu AI inference API key at https://portal.qiniu.com/ai-inference/api-key, " +
- "then paste it here as a Bearer token. OpenAI-compatible endpoint " +
- "at https://api.qnaigc.com/v1, proxying DeepSeek, Claude, Kimi and more behind one key.",
- },
orcarouter: {
id: "orcarouter",
alias: "orcarouter",
@@ -421,19 +379,6 @@ export const APIKEY_PROVIDERS_GATEWAYS = {
authHint: "Bearer API key for the TheB.AI OpenAI-compatible gateway.",
passthroughModels: true,
},
- bai: {
- id: "bai",
- alias: "bai",
- name: "b.ai",
- icon: "hub",
- color: "#6366F1",
- textIcon: "BA",
- website: "https://b.ai",
- authHint:
- "Bearer API key for the b.ai OpenAI-compatible LLM gateway (distinct from TheB.AI). " +
- "Create a key at https://docs.b.ai, then use https://api.b.ai/v1 as the OpenAI-compatible base URL.",
- passthroughModels: true,
- },
fenayai: {
id: "fenayai",
alias: "fenayai",
@@ -602,32 +547,4 @@ export const APIKEY_PROVIDERS_GATEWAYS = {
apiHint:
"TokenRouter exposes an OpenAI-compatible chat completions endpoint at https://api.tokenrouter.com/v1/chat/completions, plus a working /v1/models catalog. OmniRoute uses the OpenAI protocol.",
},
- sumopod: {
- id: "sumopod",
- alias: "sumopod",
- name: "SumoPod",
- icon: "router",
- color: "#2563EB",
- textIcon: "SP",
- passthroughModels: true,
- website: "https://ai.sumopod.com",
- authHint:
- "Use your SumoPod API key (sk-...) in Authorization: Bearer <key>. Fully OpenAI-compatible. API base URL: https://ai.sumopod.com/v1.",
- apiHint:
- "SumoPod exposes an OpenAI-compatible chat completions endpoint at https://ai.sumopod.com/v1/chat/completions, plus a live /v1/models catalog. OmniRoute uses the OpenAI protocol and lists models via passthrough.",
- },
- x5lab: {
- id: "x5lab",
- alias: "x5lab",
- name: "X5Lab",
- icon: "router",
- color: "#7C3AED",
- textIcon: "X5",
- passthroughModels: true,
- website: "https://x5lab.dev",
- authHint:
- "Use your X5Lab API key (x5-...) in Authorization: Bearer <key>. Fully OpenAI-compatible. API base URL: https://api.x5lab.dev/v1.",
- apiHint:
- "X5Lab exposes an OpenAI-compatible chat completions endpoint at https://api.x5lab.dev/v1/chat/completions, plus a live /v1/models catalog. OmniRoute uses the OpenAI protocol and lists models via passthrough.",
- },
};
diff --git a/src/shared/constants/providers/apikey/inference-hosts.ts b/src/shared/constants/providers/apikey/inference-hosts.ts
index 1fb2b9bb93..f019501590 100644
--- a/src/shared/constants/providers/apikey/inference-hosts.ts
+++ b/src/shared/constants/providers/apikey/inference-hosts.ts
@@ -61,20 +61,6 @@ export const APIKEY_PROVIDERS_INFERENCE = {
hasFree: true,
freeNote: "~$1 trial credits on signup for API testing",
},
- nube: {
- id: "nube",
- alias: "nube",
- name: "Nube.sh",
- icon: "cloud",
- color: "#2563EB",
- textIcon: "NB",
- website: "https://nube.sh",
- hasFree: false,
- notice: {
- text: "OpenAI-compatible gateway (LiteLLM). Bring your own API key — models are resolved live from the account (passthrough).",
- apiKeyUrl: "https://nube.sh/dashboard/api-keys",
- },
- },
siliconflow: {
id: "siliconflow",
alias: "siliconflow",
@@ -279,21 +265,6 @@ export const APIKEY_PROVIDERS_INFERENCE = {
passthroughModels: true,
authHint: "Get API key at monsterapi.ai",
},
- modelscope: {
- id: "modelscope",
- alias: "ms",
- name: "ModelScope",
- icon: "cloud",
- color: "#FF6A00",
- textIcon: "MS",
- website: "https://modelscope.cn",
- hasFree: true,
- // #1764 (upstream 9router): OpenAI-compatible API-Inference. Base URL verified
- // live against ModelScope's own docs — the upstream PR used the `.ai` TLD, but
- // the confirmed production domain is `api-inference.modelscope.cn` (see registry
- // entry + test guard).
- freeNote: "Free tier via ModelScope API-Inference — Alibaba account required.",
- },
byteplus: {
id: "byteplus",
alias: "bpm",
diff --git a/src/shared/constants/providers/apikey/regional.ts b/src/shared/constants/providers/apikey/regional.ts
index 7affe24500..2ad534cfc0 100644
--- a/src/shared/constants/providers/apikey/regional.ts
+++ b/src/shared/constants/providers/apikey/regional.ts
@@ -255,14 +255,6 @@ export const APIKEY_PROVIDERS_REGIONAL = {
freeNote: "Free Step-2 models. Chinese AI company.",
passthroughModels: true,
authHint: "Get API key at platform.stepfun.com",
- // #5462 — this integration calls StepFun's China platform (api.stepfun.com),
- // whose sign-up appears to be phone-based. International users have a separate
- // global platform (platform.stepfun.ai, operated by Sparkling AI Pte Ltd,
- // Singapore) with email/Google/Discord login.
- notice: {
- text: "This connects to StepFun's China platform (platform.stepfun.com), whose sign-up appears to require a Chinese phone number. Users outside mainland China can instead register at the global StepFun Open Platform (platform.stepfun.ai, operated by Sparkling AI Pte. Ltd., Singapore) with email/Google/Discord login.",
- signupUrl: "https://platform.stepfun.ai",
- },
},
coze: {
id: "coze",
@@ -315,13 +307,6 @@ export const APIKEY_PROVIDERS_REGIONAL = {
freeNote: "Free SenseTime models. Computer vision leader.",
passthroughModels: true,
authHint: "Get API key at platform.sensenova.cn",
- // #5462 — SenseNova's console (platform.sensenova.cn) appears to require a
- // Chinese (+86) phone number for SMS-verified registration, with no documented
- // international sign-up path. Warn users outside mainland China up front.
- notice: {
- text: "SenseNova registration appears to require a Chinese (+86) phone number for SMS verification — no international sign-up path is documented, so users outside mainland China may be unable to obtain an API key.",
- signupUrl: "https://platform.sensenova.cn/console",
- },
},
sparkdesk: {
id: "sparkdesk",
diff --git a/src/shared/constants/providers/noauth.ts b/src/shared/constants/providers/noauth.ts
index a33e0d08e4..1375f6cdc5 100644
--- a/src/shared/constants/providers/noauth.ts
+++ b/src/shared/constants/providers/noauth.ts
@@ -100,24 +100,4 @@ export const NOAUTH_PROVIDERS = {
text: "MiMoCode uses Xiaomi's public free AI endpoint with bootstrap-based JWT authentication. No signup needed. Rate limits apply.",
},
},
- auggie: {
- id: "auggie",
- alias: "aug",
- name: "Augment (Auggie CLI)",
- icon: "terminal",
- color: "#7C3AED",
- textIcon: "AU",
- website: "https://augmentcode.com",
- noAuth: true,
- hasFree: false,
- serviceKinds: ["llm"],
- isLocalCli: true,
- freeNote:
- "Local passthrough — runs the Augment CLI (`auggie`) on this machine. Auth is handled by `auggie login`, not OmniRoute.",
- authHint:
- "No API key stored by OmniRoute. Install the Auggie CLI and run `auggie login` on this machine, then OmniRoute spawns it locally for each request.",
- notice: {
- text: "Augment (Auggie CLI) requires the `auggie` binary installed and authenticated locally (`auggie login`). OmniRoute spawns it as a subprocess and never sees or stores your Augment credentials.",
- },
- },
};
diff --git a/src/shared/constants/serviceKinds.ts b/src/shared/constants/serviceKinds.ts
index 7b29a888ad..2121edb1d6 100644
--- a/src/shared/constants/serviceKinds.ts
+++ b/src/shared/constants/serviceKinds.ts
@@ -16,8 +16,7 @@ export type ServiceKind =
| "webSearch"
| "webFetch"
| "video"
- | "music"
- | "ocr";
+ | "music";
export const SERVICE_KIND_VALUES: readonly ServiceKind[] = [
"llm",
@@ -30,5 +29,4 @@ export const SERVICE_KIND_VALUES: readonly ServiceKind[] = [
"webFetch",
"video",
"music",
- "ocr",
];
diff --git a/src/shared/constants/sidebarVisibility/sections.ts b/src/shared/constants/sidebarVisibility/sections.ts
index 043ddf45f4..5574fc0776 100644
--- a/src/shared/constants/sidebarVisibility/sections.ts
+++ b/src/shared/constants/sidebarVisibility/sections.ts
@@ -229,13 +229,6 @@ const TOOLS_GROUP: SidebarItemGroup = {
subtitleKey: "trafficInspectorSubtitle",
icon: "network_check",
},
- {
- id: "discovery",
- href: "/dashboard/discovery",
- i18nKey: "discovery",
- subtitleKey: "discoverySubtitle",
- icon: "travel_explore",
- },
],
};
diff --git a/src/shared/constants/sidebarVisibility/types.ts b/src/shared/constants/sidebarVisibility/types.ts
index ba486b6b0e..a50b727395 100644
--- a/src/shared/constants/sidebarVisibility/types.ts
+++ b/src/shared/constants/sidebarVisibility/types.ts
@@ -29,7 +29,6 @@ export const HIDEABLE_SIDEBAR_ITEM_IDS = [
"cloud-agents",
"agent-bridge",
"traffic-inspector",
- "discovery",
// OmniProxy > Integrations
"api-endpoints",
"webhooks",
diff --git a/src/shared/constants/upstreamHeaders.ts b/src/shared/constants/upstreamHeaders.ts
index f4502aacfa..ba990dfd87 100644
--- a/src/shared/constants/upstreamHeaders.ts
+++ b/src/shared/constants/upstreamHeaders.ts
@@ -28,7 +28,7 @@ export function isForbiddenUpstreamHeaderName(name: string): boolean {
* apply-loop (open-sse/executors/default.ts) cannot drift apart.
*/
const FORBIDDEN_AUTH = new Set(
- ["authorization", "x-api-key", "x-goog-api-key", "api-key", "cookie"].map((s) => s.toLowerCase())
+ ["authorization", "x-api-key", "x-goog-api-key", "api-key"].map((s) => s.toLowerCase())
);
/**
diff --git a/src/shared/lib/persistLocale.ts b/src/shared/lib/persistLocale.ts
deleted file mode 100644
index 51ce4b245d..0000000000
--- a/src/shared/lib/persistLocale.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { LOCALE_COOKIE } from "@/i18n/config";
-import type { Locale } from "@/i18n/config";
-
-/**
- * Persist the locale preference in the cookie `src/i18n/request.ts` reads on
- * the server, plus localStorage as a client-side convenience mirror.
- *
- * Shared by every client-side locale writer (manual selection in
- * `LanguageSelector`, first-visit auto-detection in `LocaleAutoDetect`) so
- * there is a single source of truth for the cookie name/format.
- */
-export function persistLocale(code: Locale): void {
- document.cookie = `${LOCALE_COOKIE}=${code};path=/;max-age=${365 * 24 * 60 * 60};samesite=lax`;
- try {
- localStorage.setItem(LOCALE_COOKIE, code);
- } catch {
- // Ignore (e.g. storage disabled/full)
- }
-}
diff --git a/src/shared/providers/webSessionCredentials.ts b/src/shared/providers/webSessionCredentials.ts
index 04a8ce6928..68064679e0 100644
--- a/src/shared/providers/webSessionCredentials.ts
+++ b/src/shared/providers/webSessionCredentials.ts
@@ -273,28 +273,3 @@ export function hasUsableWebSessionCredential(
const data = providerSpecificData as Record<string, unknown>;
return requirement.storageKeys.some((key) => hasNonEmptyString(data[key]));
}
-
-/**
- * Resolve the value that a web-session import must store in the connection's
- * `apiKey` column.
- *
- * `token`-kind providers (deepseek-web, copilot-web, copilot-m365-web,
- * t3-chat-web, …) are authenticated from `apiKey`: both the connection
- * validator (`validateDeepSeekWebProvider({ apiKey })`) and the executor
- * (`extractUserToken` → `credentials.apiKey`) read the token there — never from
- * `providerSpecificData`. The bulk web-session import used to leave `apiKey`
- * null and stash the token only in `providerSpecificData`, so imported token-kind
- * connections were never recognized. Return the credential for token-kind so the
- * import stores it where those readers look.
- *
- * `cookie`-kind providers keep `apiKey` null — their executors read the full
- * cookie from `providerSpecificData.cookie`.
- */
-export function resolveWebSessionImportApiKey(
- requirement: WebSessionCredentialRequirement | null,
- credential: string
-): string | null {
- if (!requirement || requirement.kind !== "token") return null;
- const trimmed = typeof credential === "string" ? credential.trim() : "";
- return trimmed.length > 0 ? trimmed : null;
-}
diff --git a/src/shared/schemas/cliCatalog.ts b/src/shared/schemas/cliCatalog.ts
index 22ef529ec5..1cd65e5316 100644
--- a/src/shared/schemas/cliCatalog.ts
+++ b/src/shared/schemas/cliCatalog.ts
@@ -47,7 +47,9 @@ export const CliCatalogEntrySchema = z.object({
.optional(),
codeBlock: z.object({ language: z.string(), code: z.string() }).optional(),
notes: z
- .array(z.object({ type: z.enum(["info", "warning", "error", "cloudCheck"]), text: z.string() }))
+ .array(
+ z.object({ type: z.enum(["info", "warning", "error", "cloudCheck"]), text: z.string() })
+ )
.optional(),
requiresCloud: z.boolean().optional(),
modelSelectionMode: z.enum(["single", "multiple"]).optional(),
@@ -59,8 +61,6 @@ export type CliCatalogEntry = z.infer<typeof CliCatalogEntrySchema>;
export const CliCatalogSchema = z.record(CliCatalogEntrySchema);
-/** Cardinalidade obrigatória (Plano §3.1/§3.2 + D15). +1 (crush, decolua/9router#1233). */
-// +1 (2026-07-02): "codewhale" added as a dual entry alongside "deepseek-tui"
-// (CodeWhale is the actively-maintained successor to DeepSeek TUI).
-export const EXPECTED_CODE_COUNT = 20;
+/** Cardinalidade obrigatória (Plano §3.1/§3.2 + D15). */
+export const EXPECTED_CODE_COUNT = 18;
export const EXPECTED_AGENT_COUNT = 6;
diff --git a/src/shared/services/cliRuntime.ts b/src/shared/services/cliRuntime.ts
index d2a37a1f53..c4c3349e1c 100644
--- a/src/shared/services/cliRuntime.ts
+++ b/src/shared/services/cliRuntime.ts
@@ -210,15 +210,6 @@ const CLI_TOOLS: Record<string, any> = {
config: ".config/deepseek-tui/config.toml",
},
},
- codewhale: {
- defaultCommand: "codewhale",
- envBinKey: "CLI_CODEWHALE_BIN",
- requiresBinary: true,
- healthcheckTimeoutMs: 8000,
- paths: {
- config: ".codewhale/config.toml",
- },
- },
smelt: {
defaultCommand: "smelt",
envBinKey: "CLI_SMELT_BIN",
@@ -237,18 +228,6 @@ const CLI_TOOLS: Record<string, any> = {
config: ".pi/config.json",
},
},
- // Config path reconciled with bin/cli/commands/setup-crush.mjs::resolveCrushTarget's
- // default (~/.config/crush/crush.json) so the dashboard and `omniroute setup-crush`
- // agree on one canonical config location.
- crush: {
- defaultCommand: "crush",
- envBinKey: "CLI_CRUSH_BIN",
- requiresBinary: true,
- healthcheckTimeoutMs: 8000,
- paths: {
- config: ".config/crush/crush.json",
- },
- },
};
const isWindows = () => process.platform === "win32";
diff --git a/src/shared/utils/api.ts b/src/shared/utils/api.ts
index 852091b772..f15eff16b3 100644
--- a/src/shared/utils/api.ts
+++ b/src/shared/utils/api.ts
@@ -96,10 +96,10 @@ export function getErrorMessage(
}
async function handleResponse(response: Response) {
- const data = await parseResponseBody(response);
+ const data = await response.json();
if (!response.ok) {
- const error: any = new Error(getErrorMessage(data, response.status, "An error occurred"));
+ const error: any = new Error(data.error || "An error occurred");
error.status = response.status;
error.data = data;
throw error;
diff --git a/src/shared/validation/freeProxySchemas.ts b/src/shared/validation/freeProxySchemas.ts
index 445e9c90c0..ab91b72810 100644
--- a/src/shared/validation/freeProxySchemas.ts
+++ b/src/shared/validation/freeProxySchemas.ts
@@ -1,6 +1,6 @@
import { z } from "zod";
-export const freeProxySourceSchema = z.enum(["1proxy", "proxifly", "iplocate", "webshare"]);
+export const freeProxySourceSchema = z.enum(["1proxy", "proxifly", "iplocate"]);
export const freeProxyListSchema = z.object({
sources: z
diff --git a/src/shared/validation/helpers.ts b/src/shared/validation/helpers.ts
index 577041bada..395388b314 100644
--- a/src/shared/validation/helpers.ts
+++ b/src/shared/validation/helpers.ts
@@ -1,4 +1,3 @@
-import { NextResponse } from "next/server";
import { z } from "zod";
type ValidationErrorDetail = {
@@ -55,63 +54,3 @@ export function isValidationFailure<TData>(
): validation is ValidationFailure {
return validation.success === false;
}
-
-/**
- * Result of attempting to parse and validate a JSON body against a Zod schema.
- *
- * On failure, `response` is a fully-prepared `NextResponse` (with the standard
- * error envelope) that the caller should return directly, so route handlers can
- * do `if (!r.success) return r.response;` without knowing the envelope shape.
- */
-export type ValidatedJsonBodyResult<TData> =
- | { success: true; data: TData }
- | { success: false; response: NextResponse };
-
-/**
- * Parse a request body as JSON and validate it against a Zod schema in one
- * step. Returns the parsed (and type-narrowed) data on success, or a ready-to-
- * return 400 `NextResponse` on failure. Both the malformed-JSON and the failed-
- * validation paths emit the same error envelope
- * (`{ error: { message, details: [{ field, message }] } }`), so a single client
- * parser covers both.
- *
- * Usage:
- *
- * ```ts
- * const result = await validatedJsonBody(request, updateComboSchema);
- * if (!result.success) return result.response;
- * const body = result.data; // typed as z.infer<typeof updateComboSchema>
- * ```
- */
-export async function validatedJsonBody<TSchema extends z.ZodTypeAny>(
- request: Request,
- schema: TSchema
-): Promise<ValidatedJsonBodyResult<z.infer<TSchema>>> {
- let raw: unknown;
- try {
- raw = await request.json();
- } catch {
- return {
- success: false,
- response: NextResponse.json(
- {
- error: {
- message: "Invalid request",
- details: [{ field: "body", message: "Invalid JSON body" }],
- },
- },
- { status: 400 }
- ),
- };
- }
-
- const validation = validateBody(schema, raw);
- if (validation.success) {
- return { success: true, data: validation.data };
- }
-
- return {
- success: false,
- response: NextResponse.json({ error: validation.error }, { status: 400 }),
- };
-}
diff --git a/src/shared/validation/schemas/apiV1.ts b/src/shared/validation/schemas/apiV1.ts
index e29e734ed6..e941a3dc54 100644
--- a/src/shared/validation/schemas/apiV1.ts
+++ b/src/shared/validation/schemas/apiV1.ts
@@ -87,31 +87,6 @@ export const v1ModerationSchema = z
})
.catchall(z.unknown());
-// Mistral OCR: `document` is a { type, document_url | image_url } object.
-// Keep the schema permissive-but-typed — validate model + that a non-empty
-// `document` object (or a document_url/image_url string shorthand) is present.
-export const v1OcrDocumentSchema = z.union([
- z
- .object({
- type: z.string().trim().min(1).optional(),
- document_url: z.string().trim().min(1).optional(),
- image_url: z.union([z.string().trim().min(1), z.record(z.string(), z.unknown())]).optional(),
- })
- .catchall(z.unknown())
- .refine(
- (value) => value.document_url !== undefined || value.image_url !== undefined,
- "document must include document_url or image_url"
- ),
- nonEmptyStringSchema,
-]);
-
-export const v1OcrSchema = z
- .object({
- model: modelIdSchema.optional(),
- document: v1OcrDocumentSchema,
- })
- .catchall(z.unknown());
-
export const v1RerankSchema = z
.object({
model: modelIdSchema,
diff --git a/src/shared/validation/schemas/provider.ts b/src/shared/validation/schemas/provider.ts
index f57bb8124b..3f8f06bd48 100644
--- a/src/shared/validation/schemas/provider.ts
+++ b/src/shared/validation/schemas/provider.ts
@@ -25,22 +25,6 @@ export { validateProviderSpecificData };
// ──── Provider Schemas ────
-// #2166: shared optional remote icon URL for compatible provider nodes. Empty string
-// is accepted as "no custom icon" (clears any previously stored value). Restricted to
-// http(s) — `.url()` alone also accepts syntactically-valid-but-unsafe schemes like
-// `javascript:`/`data:`, which we never want persisted as an <img src>.
-const providerNodeIconUrlSchema = z
- .string()
- .trim()
- .max(2000)
- .refine((value) => value === "" || z.string().url().safeParse(value).success, {
- message: "Icon URL must be a valid URL",
- })
- .refine((value) => value === "" || /^https?:\/\//i.test(value), {
- message: "Icon URL must be a valid http:// or https:// URL",
- })
- .optional();
-
export const createProviderSchema = z
.object({
provider: z.string().min(1).max(100),
@@ -223,11 +207,6 @@ export const createProviderNodeSchema = z
compatMode: z.enum(["cc"]).optional(),
chatPath: z.string().trim().startsWith("/").max(500).optional().or(z.literal("")),
modelsPath: z.string().trim().startsWith("/").max(500).optional().or(z.literal("")),
- // #2166: optional operator-supplied remote icon URL for the provider node. Empty
- // string is accepted so callers can explicitly submit "no custom icon" (falls back
- // to the built-in @lobehub/static resolution). Restricted to http(s) — `.url()` alone
- // also accepts syntactically-valid-but-unsafe schemes like `javascript:`/`data:`.
- iconUrl: providerNodeIconUrlSchema,
customHeaders: customHeadersSchema,
})
.superRefine((value, ctx) => {
@@ -257,9 +236,6 @@ export const updateProviderNodeSchema = z.object({
baseUrl: z.string().trim().min(1, "Base URL is required"),
chatPath: z.string().trim().startsWith("/").max(500).optional().or(z.literal("")),
modelsPath: z.string().trim().startsWith("/").max(500).optional().or(z.literal("")),
- // #2166: same optional remote icon URL as createProviderNodeSchema — empty string
- // clears a previously stored custom icon.
- iconUrl: providerNodeIconUrlSchema,
customHeaders: customHeadersSchema,
});
diff --git a/src/shared/validation/settingsSchemas.ts b/src/shared/validation/settingsSchemas.ts
index de513b621e..3d53665875 100644
--- a/src/shared/validation/settingsSchemas.ts
+++ b/src/shared/validation/settingsSchemas.ts
@@ -112,11 +112,6 @@ export const updateSettingsSchema = z.object({
hideEndpointTailscaleFunnel: z.boolean().optional(),
hideEndpointNgrokTunnel: z.boolean().optional(),
preferClaudeCodeForUnprefixedClaudeModels: z.boolean().optional(),
- // Opt-in (default "off"): short-circuits Claude Code's `--permission-mode auto`
- // internal security-classifier request with a synthetic ALLOW response instead of
- // calling the upstream provider. "auto" only fires on detected classifier requests;
- // "always" applies the short-circuit to every Claude-format request.
- claudeClassifierCompat: z.enum(["off", "auto", "always"]).optional(),
autoRefreshProviderQuota: z.boolean().optional(),
autoRefreshProviderQuotaInterval: z.number().int().min(10).max(3600).optional(),
pinProviderQuotaToHome: z.boolean().optional(),
@@ -149,7 +144,6 @@ export const updateSettingsSchema = z.object({
.optional(),
customBannedSignals: z.array(z.string().max(200)).optional(),
debugMode: z.boolean().optional(),
- logToolSources: z.boolean().optional(),
hiddenSidebarItems: z.array(z.enum(HIDEABLE_SIDEBAR_ITEM_IDS)).optional(),
hiddenSidebarGroupLabels: z.array(z.enum(HIDEABLE_SIDEBAR_GROUP_IDS)).optional(),
sidebarSectionOrder: z
diff --git a/src/sse/services/auth.ts b/src/sse/services/auth.ts
index e14b791a8c..38148e3edd 100644
--- a/src/sse/services/auth.ts
+++ b/src/sse/services/auth.ts
@@ -6,6 +6,10 @@ import {
updateProviderConnection,
getSettings,
getCachedSettings,
+ getSessionAccountAffinity,
+ upsertSessionAccountAffinity,
+ touchSessionAccountAffinity,
+ deleteSessionAccountAffinity,
} from "@/lib/localDb";
import {
DEFAULT_QUOTA_THRESHOLD_PERCENT,
@@ -56,12 +60,6 @@ import {
WEB_COOKIE_PROVIDERS,
} from "@/shared/constants/providers";
import { isModelExcludedByConnection } from "@/domain/connectionModelRules";
-import {
- applySessionAffinityPin,
- formatSessionKeyForLog,
- resolveSessionAffinityTtlMs,
- selectSessionAffinityConnection,
-} from "./sessionAffinityPin";
import { isNoAuthProviderBlockedBySettings } from "./noAuthProviderSettings";
import { resolveAccountProxiesFromRegistry } from "./noAuthProxyResolution";
import * as log from "../utils/logger";
@@ -306,6 +304,10 @@ export function extractSessionAffinityKey(
return `input:sha256:${createHash("sha256").update(inputText.slice(0, 4096)).digest("hex")}`;
}
+function formatSessionKeyForLog(sessionKey: string): string {
+ return `${sessionKey.slice(0, 18)}...`;
+}
+
function getCodexLimitPolicy(providerSpecificData: JsonRecord): {
use5h: boolean;
useWeekly: boolean;
@@ -711,6 +713,69 @@ function compareP2CConnections(
return a.id.localeCompare(b.id);
}
+function compareLruConnections(a: ProviderConnectionView, b: ProviderConnectionView): number {
+ if (!a.lastUsedAt && !b.lastUsedAt) return (a.priority || 999) - (b.priority || 999);
+ if (!a.lastUsedAt) return -1;
+ if (!b.lastUsedAt) return 1;
+ const recencyDelta = new Date(a.lastUsedAt).getTime() - new Date(b.lastUsedAt).getTime();
+ if (recencyDelta !== 0) return recencyDelta;
+ if ((a.consecutiveUseCount || 0) !== (b.consecutiveUseCount || 0)) {
+ return (a.consecutiveUseCount || 0) - (b.consecutiveUseCount || 0);
+ }
+ return (a.priority || 999) - (b.priority || 999);
+}
+
+async function selectSessionAffinityConnection(
+ provider: string,
+ sessionKey: string | null | undefined,
+ connections: ProviderConnectionView[],
+ ttlMs = 0
+): Promise<ProviderConnectionView | null> {
+ if (!sessionKey || connections.length === 0 || ttlMs <= 0) return null;
+
+ const existing = getSessionAccountAffinity(sessionKey, provider, ttlMs);
+ if (existing) {
+ const connection = connections.find((candidate) => candidate.id === existing.connectionId);
+ if (connection) {
+ touchSessionAccountAffinity(sessionKey, provider, Date.now(), ttlMs);
+ await updateProviderConnection(connection.id, {
+ lastUsedAt: new Date().toISOString(),
+ consecutiveUseCount: (connection.consecutiveUseCount || 0) + 1,
+ });
+ log.info(
+ "AUTH",
+ `session_key=${formatSessionKeyForLog(sessionKey)} -> connection ${connection.id.slice(
+ 0,
+ 8
+ )} (affinity)`
+ );
+ return connection;
+ }
+
+ deleteSessionAccountAffinity(sessionKey, provider);
+ log.info(
+ "AUTH",
+ `affinity cleared for session_key=${formatSessionKeyForLog(sessionKey)} provider=${provider}`
+ );
+ }
+
+ const connection = [...connections].sort(compareLruConnections)[0] ?? null;
+ if (!connection) return null;
+
+ upsertSessionAccountAffinity(sessionKey, provider, connection.id, Date.now(), ttlMs);
+ await updateProviderConnection(connection.id, {
+ lastUsedAt: new Date().toISOString(),
+ consecutiveUseCount: 1,
+ });
+ log.info(
+ "AUTH",
+ `new affinity created for session_key=${formatSessionKeyForLog(
+ sessionKey
+ )} -> connection ${connection.id.slice(0, 8)}`
+ );
+ return connection;
+}
+
/**
* Sentinel connection id used for the synthetic credentials of no-auth /
* keyless providers. It is NOT a real DB row, so it
@@ -1018,7 +1083,7 @@ export async function getProviderCredentials(
const allowRateLimitedConnections =
allowSuppressedConnections || options.allowRateLimitedConnections === true;
const bypassQuotaPolicy = options.bypassQuotaPolicy === true;
- let forcedConnectionId =
+ const forcedConnectionId =
typeof options.forcedConnectionId === "string" && options.forcedConnectionId.trim().length > 0
? options.forcedConnectionId.trim()
: null;
@@ -1027,11 +1092,6 @@ export async function getProviderCredentials(
options.excludeConnectionIds
);
- // Fetched early so the session-affinity-pin override (#5903) can consult
- // the TTL before forcedConnectionId narrows the connection pool.
- const settings = await getSettings();
- const sessionAffinityTtlMs = resolveSessionAffinityTtlMs(provider, options, settings);
-
// Fix #922: Check for aliases (nvidia/nvidia_nim) to ensure credentials are found
const providersToSearch = await getProviderSearchPool(provider);
const connectionResults = await Promise.all(
@@ -1046,24 +1106,6 @@ export async function getProviderCredentials(
if (allowedConnections && allowedConnections.length > 0) {
connections = connections.filter((conn) => allowedConnections.includes(conn.id));
}
-
- // #5903: an active session-affinity pin outranks a per-request reset-aware
- // forcedConnectionId (see sessionAffinityPin leaf for the full rationale).
- forcedConnectionId =
- applySessionAffinityPin({
- forcedConnectionId,
- options,
- sessionAffinityTtlMs,
- connections,
- provider,
- requestedModel,
- excludedConnectionIds,
- isTerminalConnectionStatus,
- isCodexScopeUnavailable,
- isQuotaPolicyBlocked: (c) =>
- evaluateQuotaLimitPolicy(provider, c as ProviderConnectionView, requestedModel).blocked,
- }) ?? forcedConnectionId;
-
if (forcedConnectionId) {
connections = connections.filter((conn) => conn.id === forcedConnectionId);
}
@@ -1441,7 +1483,18 @@ export async function getProviderCredentials(
const orderedConnections = withQuota;
+ const settings = await getSettings();
const strategy = settings.fallbackStrategy || "fill-first";
+ const sessionAffinityTtlMs =
+ provider === "codex"
+ ? Number.isFinite(Number(options.sessionAffinityTtlMs)) &&
+ Number(options.sessionAffinityTtlMs) > 0
+ ? Number(options.sessionAffinityTtlMs)
+ : Number.isFinite(Number(settings.codexSessionAffinityTtlMs)) &&
+ Number(settings.codexSessionAffinityTtlMs) > 0
+ ? Number(settings.codexSessionAffinityTtlMs)
+ : 0
+ : 0;
let connection;
const affinityConnection = await selectSessionAffinityConnection(
diff --git a/src/sse/services/sessionAffinityPin.ts b/src/sse/services/sessionAffinityPin.ts
deleted file mode 100644
index f8f4749d48..0000000000
--- a/src/sse/services/sessionAffinityPin.ts
+++ /dev/null
@@ -1,247 +0,0 @@
-/**
- * #5903 — session-affinity-pin resolution + TTL, extracted from auth.ts as a
- * pure leaf so the frozen god-file `auth.ts` does not grow.
- *
- * Problem: reset-aware (and other quota-scoring) combo strategies recompute a
- * "winner" connection on every request and hand it to getProviderCredentials
- * as `forcedConnectionId`. That id narrows the connection pool to exactly one
- * connection BEFORE session affinity is consulted, so an existing pin pointing
- * at a previously-selected account is never found and gets silently
- * deleted/re-pinned to the fresh winner — breaking "same session -> reuse
- * pinned account".
- *
- * Fix: when an active, non-expired affinity pin already exists for this
- * (session, provider) AND the pinned connection is still eligible, the pin wins
- * over the freshly recomputed `forcedConnectionId`. If the pin is ineligible
- * (rate-limited / exhausted / model-locked / etc.) the caller keeps its forced
- * connection, so the existing 429-driven `deleteSessionAccountAffinity`
- * failover still owns rotating away from a pin that stops working.
- *
- * This module stays decoupled from auth.ts internals: the three predicates that
- * live in (or would cause a cycle back into) auth.ts —
- * `isTerminalConnectionStatus`, `isCodexScopeUnavailable`, and the quota-policy
- * check wrapping `evaluateQuotaLimitPolicy` — are injected as callbacks.
- */
-
-import {
- getSessionAccountAffinity,
- upsertSessionAccountAffinity,
- touchSessionAccountAffinity,
- deleteSessionAccountAffinity,
-} from "@/lib/db/sessionAccountAffinity";
-import { updateProviderConnection } from "@/lib/db/providers";
-import { isModelExcludedByConnection } from "@/domain/connectionModelRules";
-import { isAccountQuotaExhausted } from "@/domain/quotaCache";
-import {
- isAccountUnavailable,
- isModelLocked,
-} from "@omniroute/open-sse/services/accountFallback.ts";
-import * as log from "../utils/logger";
-
-/** Minimal structural view of a provider connection this module reads. */
-export interface AffinityPinConnection {
- id: string;
- testStatus?: string | null;
- rateLimitedUntil?: string | null;
- providerSpecificData?: unknown;
-}
-
-/** Fields the LRU tie-break / session-affinity selection reads. */
-export interface SessionAffinityConnection {
- id: string;
- lastUsedAt?: string | null;
- consecutiveUseCount?: number | null;
- priority?: number | null;
-}
-
-export function formatSessionKeyForLog(sessionKey: string): string {
- return `${sessionKey.slice(0, 18)}...`;
-}
-
-function compareLruConnections(a: SessionAffinityConnection, b: SessionAffinityConnection): number {
- if (!a.lastUsedAt && !b.lastUsedAt) return (a.priority || 999) - (b.priority || 999);
- if (!a.lastUsedAt) return -1;
- if (!b.lastUsedAt) return 1;
- const recencyDelta = new Date(a.lastUsedAt).getTime() - new Date(b.lastUsedAt).getTime();
- if (recencyDelta !== 0) return recencyDelta;
- if ((a.consecutiveUseCount || 0) !== (b.consecutiveUseCount || 0)) {
- return (a.consecutiveUseCount || 0) - (b.consecutiveUseCount || 0);
- }
- return (a.priority || 999) - (b.priority || 999);
-}
-
-/**
- * Session-affinity account selection (moved from auth.ts alongside the #5903
- * pin-override so all session-affinity logic lives in one leaf). Reuses an
- * active pin when its connection is in the pool; otherwise picks the LRU
- * connection and creates a fresh pin. Behavior byte-identical to the original.
- */
-export async function selectSessionAffinityConnection<T extends SessionAffinityConnection>(
- provider: string,
- sessionKey: string | null | undefined,
- connections: T[],
- ttlMs = 0
-): Promise<T | null> {
- if (!sessionKey || connections.length === 0 || ttlMs <= 0) return null;
-
- const existing = getSessionAccountAffinity(sessionKey, provider, ttlMs);
- if (existing) {
- const connection = connections.find((candidate) => candidate.id === existing.connectionId);
- if (connection) {
- touchSessionAccountAffinity(sessionKey, provider, Date.now(), ttlMs);
- await updateProviderConnection(connection.id, {
- lastUsedAt: new Date().toISOString(),
- consecutiveUseCount: (connection.consecutiveUseCount || 0) + 1,
- });
- log.info(
- "AUTH",
- `session_key=${formatSessionKeyForLog(sessionKey)} -> connection ${connection.id.slice(
- 0,
- 8
- )} (affinity)`
- );
- return connection;
- }
-
- deleteSessionAccountAffinity(sessionKey, provider);
- log.info(
- "AUTH",
- `affinity cleared for session_key=${formatSessionKeyForLog(sessionKey)} provider=${provider}`
- );
- }
-
- const connection = [...connections].sort(compareLruConnections)[0] ?? null;
- if (!connection) return null;
-
- upsertSessionAccountAffinity(sessionKey, provider, connection.id, Date.now(), ttlMs);
- await updateProviderConnection(connection.id, {
- lastUsedAt: new Date().toISOString(),
- consecutiveUseCount: 1,
- });
- log.info(
- "AUTH",
- `new affinity created for session_key=${formatSessionKeyForLog(
- sessionKey
- )} -> connection ${connection.id.slice(0, 8)}`
- );
- return connection;
-}
-
-/** Subset of credential-selection options the pin resolution consults. */
-export interface AffinityPinOptions {
- sessionKey?: string | null;
- allowSuppressedConnections?: boolean;
- allowRateLimitedConnections?: boolean;
- bypassQuotaPolicy?: boolean;
- sessionAffinityTtlMs?: number | null;
-}
-
-/** Settings subset needed to resolve the codex session-affinity TTL. */
-export interface AffinityPinSettings {
- codexSessionAffinityTtlMs?: number | null;
-}
-
-/**
- * Resolve the effective session-affinity TTL. Only codex opts in today: an
- * explicit per-request override wins, else the persisted codex setting, else 0
- * (disabled). Kept here so auth.ts can reuse it at both the pin-override site
- * and the downstream `selectSessionAffinityConnection` site with one call.
- */
-export function resolveSessionAffinityTtlMs(
- provider: string,
- options: AffinityPinOptions,
- settings: AffinityPinSettings
-): number {
- if (provider !== "codex") return 0;
- const override = Number(options.sessionAffinityTtlMs);
- if (Number.isFinite(override) && override > 0) return override;
- const configured = Number(settings.codexSessionAffinityTtlMs);
- if (Number.isFinite(configured) && configured > 0) return configured;
- return 0;
-}
-
-/**
- * Predicates supplied by the caller because they either live in auth.ts or
- * would introduce a circular import if pulled in directly.
- */
-export interface AffinityPinPredicates {
- /** auth.ts::isTerminalConnectionStatus (banned/expired/credits_exhausted). */
- isTerminalConnectionStatus: (connection: AffinityPinConnection) => boolean;
- /** auth.ts::isCodexScopeUnavailable (codex per-scope cooldown). */
- isCodexScopeUnavailable: (
- connection: AffinityPinConnection,
- requestedModel: string | null
- ) => boolean;
- /** Wraps auth.ts::evaluateQuotaLimitPolicy(...).blocked for one connection. */
- isQuotaPolicyBlocked: (connection: AffinityPinConnection) => boolean;
-}
-
-export interface ApplySessionAffinityPinParams extends AffinityPinPredicates {
- forcedConnectionId: string | null;
- options: AffinityPinOptions;
- sessionAffinityTtlMs: number;
- connections: AffinityPinConnection[];
- provider: string;
- requestedModel: string | null;
- excludedConnectionIds: Set<string>;
-}
-
-/**
- * Mirrors the eligibility predicates applied later in getProviderCredentials
- * (availableConnections filter + quota policy + quota exhaustion) but scoped to
- * a single candidate connection. Pure/read-only.
- */
-function isConnectionEligibleForAffinityPin(
- connection: AffinityPinConnection,
- params: ApplySessionAffinityPinParams
-): boolean {
- const { provider, requestedModel, options } = params;
- const allowSuppressed = options.allowSuppressedConnections === true;
- const allowRateLimited = allowSuppressed || options.allowRateLimitedConnections === true;
- if (params.excludedConnectionIds.has(connection.id)) return false;
- if (
- requestedModel &&
- isModelExcludedByConnection(requestedModel, connection.providerSpecificData)
- ) {
- return false;
- }
- if (!allowSuppressed) {
- if (!allowRateLimited && isAccountUnavailable(connection.rateLimitedUntil)) return false;
- if (params.isTerminalConnectionStatus(connection)) return false;
- if (provider === "codex" && params.isCodexScopeUnavailable(connection, requestedModel)) {
- return false;
- }
- if (requestedModel && isModelLocked(provider, connection.id, requestedModel)) return false;
- }
- if (isAccountQuotaExhausted(connection.id)) return false;
- if (options.bypassQuotaPolicy !== true && params.isQuotaPolicyBlocked(connection)) return false;
- return true;
-}
-
-/**
- * If an active, non-expired affinity pin exists for (sessionKey, provider) and
- * the pinned connection is present-and-eligible in the current pool, returns
- * that pinned connectionId (which should override `forcedConnectionId`) and
- * logs the override. Returns null when the caller should keep its
- * `forcedConnectionId` — no session, TTL disabled, no pin, pin already equals
- * the forced id, pin absent from pool, or pin ineligible.
- */
-export function applySessionAffinityPin(params: ApplySessionAffinityPinParams): string | null {
- const { forcedConnectionId, options, sessionAffinityTtlMs, connections, provider } = params;
- const sessionKey = options.sessionKey;
- if (!forcedConnectionId || !sessionKey || sessionAffinityTtlMs <= 0) return null;
-
- const pinned = getSessionAccountAffinity(sessionKey, provider, sessionAffinityTtlMs);
- if (!pinned || pinned.connectionId === forcedConnectionId) return null;
-
- const pinnedConnection = connections.find((conn) => conn.id === pinned.connectionId);
- if (!pinnedConnection || !isConnectionEligibleForAffinityPin(pinnedConnection, params)) {
- return null;
- }
-
- log.info(
- "AUTH",
- `session affinity pin ${pinned.connectionId.slice(0, 8)}... overrides forcedConnectionId ${forcedConnectionId.slice(0, 8)}... (#5903)`
- );
- return pinned.connectionId;
-}
diff --git a/stryker.conf.json b/stryker.conf.json
index b8dac2b67c..ecbd54a540 100644
--- a/stryker.conf.json
+++ b/stryker.conf.json
@@ -43,7 +43,6 @@
"tap": {
"testFiles": [
"tests/unit/account-fallback-anthropic-quota.test.ts",
- "tests/unit/account-fallback-retry-after-json.test.ts",
"tests/unit/account-fallback-route-restriction-403.test.ts",
"tests/unit/account-fallback-service.test.ts",
"tests/unit/api-key-rotator-health.test.ts",
@@ -92,10 +91,7 @@
"tests/unit/claude-passthrough-stream-boolean.test.ts",
"tests/unit/claude-passthrough-thinking-2454.test.ts",
"tests/unit/cli-simulate.test.ts",
- "tests/unit/cline-response-envelope.test.ts",
- "tests/unit/clinepass-provider.test.ts",
"tests/unit/codex-failover.test.ts",
- "tests/unit/codex-session-affinity-reset-aware-5903.test.ts",
"tests/unit/codex-stream-false.test.ts",
"tests/unit/collect-metrics-module-coverage.test.ts",
"tests/unit/combo-499-abort.test.ts",
@@ -110,11 +106,9 @@
"tests/unit/combo-max-depth-config.test.ts",
"tests/unit/combo-omnimodel-tag-stripping.test.ts",
"tests/unit/combo-prescreen.test.ts",
- "tests/unit/combo-priority-quota-exhaustion-cutoff-5923.test.ts",
"tests/unit/combo-provider-cooldown.test.ts",
"tests/unit/combo-provider-diversity-wiring.test.ts",
"tests/unit/combo-quality-validator-reasoning.test.ts",
- "tests/unit/combo-priority-quota-exhaustion-cutoff-5923.test.ts",
"tests/unit/combo-quota-soft-penalty.test.ts",
"tests/unit/combo-round-robin-streaming-lock-3811.test.ts",
"tests/unit/combo-routing-engine.test.ts",
@@ -190,7 +184,6 @@
"tests/unit/antigravity-429-quota-tdd.test.ts",
"tests/unit/auth-antigravity-account-retry-v2.test.ts",
"tests/unit/middleware-header-strip-5849.test.ts",
- "tests/unit/authz/discovery-routes-local-only.test.ts",
"tests/unit/authz/route-guard-local-prefix.test.ts",
"tests/unit/authz/route-guard-version-get-exemption.test.ts",
"tests/unit/chat-combo-live-test.test.ts",
@@ -200,13 +193,10 @@
"tests/unit/chatcore-upstream-timeouts.test.ts",
"tests/unit/circuit-breaker-registry-cap.test.ts",
"tests/unit/circuit-breaker-stream-controller-4602.test.ts",
- "tests/unit/clinepass-provider.test.ts",
- "tests/unit/codex-session-affinity-reset-aware-5903.test.ts",
"tests/unit/combo-account-allowlist-3266.test.ts",
"tests/unit/combo-headroom-strategy.test.ts",
"tests/unit/combo-model-lockout-honors-reset-1308.test.ts",
"tests/unit/combo-param-validation-fallback-4519.test.ts",
- "tests/unit/combo-priority-quota-exhaustion-cutoff-5923.test.ts",
"tests/unit/combo-quota-share-cooldown-wait.test.ts",
"tests/unit/combo-selected-connection-success.test.ts",
"tests/unit/combo-stream-readiness-fallback.test.ts",
diff --git a/tests/integration/cli-settings-codewhale.test.ts b/tests/integration/cli-settings-codewhale.test.ts
deleted file mode 100644
index 8a98ff547b..0000000000
--- a/tests/integration/cli-settings-codewhale.test.ts
+++ /dev/null
@@ -1,279 +0,0 @@
-/**
- * Integration tests for /api/cli-tools/codewhale-settings
- *
- * CodeWhale (https://github.com/Hmbown/CodeWhale) is the actively-maintained
- * successor to DeepSeek TUI (same author, renamed project). This route mirrors
- * deepseek-tui-settings/route.ts but writes/reads a dual config path:
- * - primary: ~/.codewhale/config.toml
- * - legacy: ~/.deepseek/config.toml (kept in sync when it already exists,
- * so users upgrading their CLI binary keep working)
- */
-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-codewhale-settings-"));
-process.env.DATA_DIR = TEST_DATA_DIR;
-process.env.API_KEY_SECRET = "test-api-key-secret-codewhale";
-process.env.JWT_SECRET = "test-jwt-secret-codewhale";
-
-const core = await import("../../src/lib/db/core.ts");
-const localDb = await import("../../src/lib/localDb.ts");
-
-const { GET, POST, DELETE } = await import("../../src/app/api/cli-tools/codewhale-settings/route.ts");
-
-async function resetStorage() {
- delete process.env.INITIAL_PASSWORD;
- core.resetDbInstance();
- fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
- fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
-}
-
-async function enableAuth() {
- process.env.INITIAL_PASSWORD = "test-bootstrap";
- await localDb.updateSettings({ requireLogin: true, password: "" });
-}
-
-test.beforeEach(async () => {
- await resetStorage();
-});
-
-// ── Test 1: GET without auth → 401 ──────────────────────────────────────────
-
-test("codewhale-settings GET: returns 401 when auth required and no token", async () => {
- await enableAuth();
- const res = await GET(new Request("http://localhost/api/cli-tools/codewhale-settings"));
- assert.equal(res.status, 401, `Expected 401, got ${res.status}`);
-});
-
-// ── Test 2: GET without auth requirement → 200 ───────────────────────────────
-
-test("codewhale-settings GET: returns 200 when auth not required", async () => {
- const res = await GET(new Request("http://localhost/api/cli-tools/codewhale-settings"));
- assert.equal(res.status, 200, `Expected 200, got ${res.status}`);
- const body = await res.json();
- assert.ok(
- "installed" in body || "config" in body,
- "Response should contain installed or config field"
- );
-});
-
-// ── Test 3: POST with invalid body → 400 ─────────────────────────────────────
-
-test("codewhale-settings POST: 400 when baseUrl is missing", async () => {
- const res = await POST(
- new Request("http://localhost/api/cli-tools/codewhale-settings", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({ apiKey: "sk-test", model: "deepseek-v4-pro" }),
- })
- );
- assert.equal(res.status, 400, `Expected 400, got ${res.status}`);
- const body = await res.json();
- assert.ok(body.error !== undefined);
-});
-
-test("codewhale-settings POST: 400 when model is missing", async () => {
- const res = await POST(
- new Request("http://localhost/api/cli-tools/codewhale-settings", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({ baseUrl: "http://localhost:20128", apiKey: "sk-test" }),
- })
- );
- assert.equal(res.status, 400, `Expected 400, got ${res.status}`);
-});
-
-// ── Test 4: POST with valid body → writes PRIMARY config.toml only (no legacy dir) ──
-
-test("codewhale-settings POST: writes primary ~/.codewhale/config.toml for a fresh install", async () => {
- const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "codewhale-home-"));
- const origHome = process.env.HOME;
- process.env.HOME = tmpHome;
-
- try {
- const res = await POST(
- new Request("http://localhost/api/cli-tools/codewhale-settings", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({
- baseUrl: "http://localhost:20128",
- apiKey: "sk-test-codewhale-key",
- model: "deepseek-v4-pro",
- }),
- })
- );
- assert.ok([200, 403, 500].includes(res.status), `Unexpected status ${res.status}`);
- if (res.status === 200) {
- const body = await res.json();
- assert.equal(body.success, true);
-
- const primaryPath = path.join(tmpHome, ".codewhale", "config.toml");
- assert.ok(fs.existsSync(primaryPath), "Primary ~/.codewhale/config.toml must be written");
- const content = fs.readFileSync(primaryPath, "utf-8");
- assert.ok(content.includes("managed by OmniRoute"), "Config should have OmniRoute marker");
- assert.ok(content.includes("http://localhost:20128"), "Config should contain base URL");
- assert.ok(content.includes("[openai]"), "Config should have [openai] section");
-
- // No legacy ~/.deepseek dir existed before the write — must NOT be created.
- const legacyPath = path.join(tmpHome, ".deepseek", "config.toml");
- assert.ok(
- !fs.existsSync(legacyPath),
- "Legacy ~/.deepseek/config.toml must not be created for a fresh install"
- );
- }
- } finally {
- process.env.HOME = origHome;
- fs.rmSync(tmpHome, { recursive: true, force: true });
- }
-});
-
-// ── Test 5: POST keeps an EXISTING legacy ~/.deepseek config in sync ────────
-
-test("codewhale-settings POST: syncs an existing legacy ~/.deepseek/config.toml", async () => {
- const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "codewhale-home-legacy-"));
- const origHome = process.env.HOME;
- process.env.HOME = tmpHome;
-
- try {
- // Simulate an existing DeepSeek TUI install (pre-CodeWhale upgrade).
- const legacyDir = path.join(tmpHome, ".deepseek");
- fs.mkdirSync(legacyDir, { recursive: true });
- fs.writeFileSync(path.join(legacyDir, "config.toml"), 'provider = "deepseek"\n');
-
- const res = await POST(
- new Request("http://localhost/api/cli-tools/codewhale-settings", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({
- baseUrl: "http://localhost:20128",
- apiKey: "sk-test-codewhale-key",
- model: "deepseek-v4-flash",
- }),
- })
- );
- assert.ok([200, 403, 500].includes(res.status), `Unexpected status ${res.status}`);
- if (res.status === 200) {
- const primaryPath = path.join(tmpHome, ".codewhale", "config.toml");
- const legacyPath = path.join(tmpHome, ".deepseek", "config.toml");
-
- assert.ok(fs.existsSync(primaryPath), "Primary config must be written");
- assert.ok(fs.existsSync(legacyPath), "Legacy config must still exist");
-
- const primaryContent = fs.readFileSync(primaryPath, "utf-8");
- const legacyContent = fs.readFileSync(legacyPath, "utf-8");
- assert.ok(primaryContent.includes("http://localhost:20128"));
- assert.ok(
- legacyContent.includes("http://localhost:20128"),
- "Legacy config must be kept in sync with the new base URL"
- );
- assert.equal(primaryContent, legacyContent, "Primary and legacy configs should match");
- }
- } finally {
- process.env.HOME = origHome;
- fs.rmSync(tmpHome, { recursive: true, force: true });
- }
-});
-
-// ── Test 6: GET reads from legacy path when only legacy config exists ───────
-
-test("codewhale-settings GET: falls back to legacy ~/.deepseek/config.toml when primary is absent", async () => {
- const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "codewhale-home-getlegacy-"));
- const origHome = process.env.HOME;
- process.env.HOME = tmpHome;
-
- try {
- const legacyDir = path.join(tmpHome, ".deepseek");
- fs.mkdirSync(legacyDir, { recursive: true });
- fs.writeFileSync(
- path.join(legacyDir, "config.toml"),
- '# managed by OmniRoute (plan 14)\n[openai]\nbase_url = "http://localhost:20128"\n'
- );
-
- const res = await GET(new Request("http://localhost/api/cli-tools/codewhale-settings"));
- assert.equal(res.status, 200);
- const body = await res.json();
- if (body.config) {
- assert.ok(body.config.includes("managed by OmniRoute"));
- assert.equal(body.hasOmniRoute, true);
- }
- } finally {
- process.env.HOME = origHome;
- fs.rmSync(tmpHome, { recursive: true, force: true });
- }
-});
-
-// ── Test 7: DELETE → removes both primary and legacy config files ───────────
-
-test("codewhale-settings DELETE: removes primary and legacy config files", async () => {
- const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "codewhale-home-del-"));
- const origHome = process.env.HOME;
- process.env.HOME = tmpHome;
-
- try {
- const primaryDir = path.join(tmpHome, ".codewhale");
- const legacyDir = path.join(tmpHome, ".deepseek");
- fs.mkdirSync(primaryDir, { recursive: true });
- fs.mkdirSync(legacyDir, { recursive: true });
- fs.writeFileSync(
- path.join(primaryDir, "config.toml"),
- '# managed by OmniRoute (plan 14)\n[openai]\nbase_url = "http://localhost:20128"\n'
- );
- fs.writeFileSync(
- path.join(legacyDir, "config.toml"),
- '# managed by OmniRoute (plan 14)\n[openai]\nbase_url = "http://localhost:20128"\n'
- );
-
- const res = await DELETE(
- new Request("http://localhost/api/cli-tools/codewhale-settings", { method: "DELETE" })
- );
- assert.ok([200, 403, 500].includes(res.status), `Expected 200/403/500, got ${res.status}`);
- if (res.status === 200) {
- const body = await res.json();
- assert.equal(body.success, true);
- assert.ok(!fs.existsSync(path.join(primaryDir, "config.toml")), "Primary config removed");
- assert.ok(!fs.existsSync(path.join(legacyDir, "config.toml")), "Legacy config removed");
- }
- } finally {
- process.env.HOME = origHome;
- fs.rmSync(tmpHome, { recursive: true, force: true });
- }
-});
-
-// ── Test 8: Error sanitization (Hard Rule #12) ───────────────────────────────
-
-test("codewhale-settings: error responses do not leak stack traces", async () => {
- const badReq = new Request("http://localhost/api/cli-tools/codewhale-settings", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: "{ bad json }",
- });
- const res = await POST(badReq);
- const bodyStr = JSON.stringify(await res.json());
- assert.ok(
- !bodyStr.match(/\s+at\s+\/[^\s]/),
- "Error response must not contain absolute-path stack traces"
- );
-});
-
-// ── Test 9: Hard Rule #13 (no exec/spawn) ────────────────────────────────────
-
-test("codewhale-settings route.ts: does not call exec() or spawn() directly", () => {
- const routePath = path.resolve(
- import.meta.dirname,
- "../../src/app/api/cli-tools/codewhale-settings/route.ts"
- );
- const content = fs.readFileSync(routePath, "utf-8");
- assert.ok(!content.match(/\bexec\s*\(/), "Handler must not use exec()");
- assert.ok(!content.match(/\bspawn\s*\(/), "Handler must not use spawn()");
-});
-
-test.after(async () => {
- await resetStorage();
- fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
- delete process.env.DATA_DIR;
- delete process.env.API_KEY_SECRET;
- delete process.env.JWT_SECRET;
-});
diff --git a/tests/integration/services/full-lifecycle.int.test.ts b/tests/integration/services/full-lifecycle.int.test.ts
index 24e8b928cc..bb411d7324 100644
--- a/tests/integration/services/full-lifecycle.int.test.ts
+++ b/tests/integration/services/full-lifecycle.int.test.ts
@@ -13,10 +13,8 @@
* Prerequisites when running for real:
* - npm is in PATH
* - Network access to registry.npmjs.org
- * - Ports 20130 (9router), 8317 (cliproxy), and 8080 (bifrost) are available
+ * - Ports 20130 (9router) and 8317 (cliproxy) are available
* - DATA_DIR is writable
- * - Bifrost lazily downloads its Go binary from downloads.getmaxim.ai on first
- * start, so the bifrost block additionally needs network access to that host.
*/
import { describe, it } from "node:test";
@@ -247,86 +245,6 @@ describe("cliproxy — full lifecycle (opt-in, RUN_SERVICES_INT=1)", () => {
});
});
-// ---------------------------------------------------------------------------
-// bifrost lifecycle
-// ---------------------------------------------------------------------------
-
-describe("bifrost — full lifecycle (opt-in, RUN_SERVICES_INT=1)", () => {
- it("STEP 1: install bifrost (latest)", async (t) => {
- if (maybeSkip(t)) return;
- const { status, body } = await apiPost("/api/services/bifrost/install", {
- version: "latest",
- });
- assert.ok(
- status === 200,
- `Expected 200 from install, got ${status}: ${JSON.stringify(body).slice(0, 300)}`
- );
- const b = body as Record<string, unknown>;
- assert.ok(b.ok === true, "install response must have ok:true");
- assert.ok(
- typeof b.installedVersion === "string",
- "install response must have installedVersion"
- );
- assert.ok(typeof b.durationMs === "number", "install response must have durationMs");
- });
-
- it("STEP 2: verify status is stopped after install", async (t) => {
- if (maybeSkip(t)) return;
- const { status, body } = await apiGet("/api/services/bifrost/status");
- assert.equal(status, 200);
- const b = body as Record<string, unknown>;
- assert.equal(b.state, "stopped", `Expected stopped state after install, got: ${b.state}`);
- assert.ok(
- typeof b.installedVersion === "string",
- "installedVersion should be set after install"
- );
- });
-
- it("STEP 3: start bifrost", async (t) => {
- if (maybeSkip(t)) return;
- const { status, body } = await apiPost("/api/services/bifrost/start");
- assert.ok(
- status === 200,
- `Expected 200 from start, got ${status}: ${JSON.stringify(body).slice(0, 300)}`
- );
- const b = body as Record<string, unknown>;
- assert.ok(
- ["starting", "running"].includes(b.state as string),
- `Expected starting or running, got: ${b.state}`
- );
- });
-
- it("STEP 4: wait for bifrost to become healthy (≤60s — Go binary download on first start)", async (t) => {
- if (maybeSkip(t)) return;
- // First start lazily downloads the Go binary, so allow a longer window than
- // the 9router/cliproxy blocks (30s). Confirms open question §2b/§6 (Windows +
- // headless boot) against a real download.
- const finalStatus = await waitForState("/api/services/bifrost/status", "running", 60_000);
- const b = finalStatus as Record<string, unknown>;
- assert.equal(b.state, "running");
- assert.equal(b.health, "healthy");
- assert.ok(typeof b.pid === "number", "pid must be a number when running");
- assert.equal(b.port, 8080, "bifrost must report its default port 8080");
- });
-
- it("STEP 5: stop bifrost", async (t) => {
- if (maybeSkip(t)) return;
- const { status, body } = await apiPost("/api/services/bifrost/stop");
- assert.equal(status, 200);
- const b = body as Record<string, unknown>;
- assert.ok(
- ["stopping", "stopped"].includes(b.state as string),
- `Expected stopping or stopped, got: ${b.state}`
- );
- });
-
- it("STEP 6: status returns stopped after stop", async (t) => {
- if (maybeSkip(t)) return;
- const final = await waitForState("/api/services/bifrost/status", "stopped", 15_000);
- assert.equal((final as Record<string, unknown>).state, "stopped");
- });
-});
-
// ---------------------------------------------------------------------------
// Security smoke (requires running server)
// ---------------------------------------------------------------------------
diff --git a/tests/integration/services/route-guard-services.int.test.ts b/tests/integration/services/route-guard-services.int.test.ts
index d9e52d899b..0cadfb9ce2 100644
--- a/tests/integration/services/route-guard-services.int.test.ts
+++ b/tests/integration/services/route-guard-services.int.test.ts
@@ -52,18 +52,6 @@ describe("isLocalOnlyPath — /api/services/* and /dashboard/providers/services/
assert.equal(isLocalOnlyPath("/api/services/cliproxy/status"), true);
});
- it("returns true for /api/services/bifrost/start", () => {
- assert.equal(isLocalOnlyPath("/api/services/bifrost/start"), true);
- });
-
- it("returns true for /api/services/bifrost/install", () => {
- assert.equal(isLocalOnlyPath("/api/services/bifrost/install"), true);
- });
-
- it("returns true for /api/services/bifrost/status", () => {
- assert.equal(isLocalOnlyPath("/api/services/bifrost/status"), true);
- });
-
it("returns true for /api/services/ (root prefix)", () => {
assert.equal(isLocalOnlyPath("/api/services/"), true);
});
@@ -122,10 +110,6 @@ describe("isLocalOnlyBypassableByManageScope — /api/services/* is NOT bypassab
it("returns false for /api/services/cliproxy/install", () => {
assert.equal(isLocalOnlyBypassableByManageScope("/api/services/cliproxy/install"), false);
});
-
- it("returns false for /api/services/bifrost/install (spawn-capable)", () => {
- assert.equal(isLocalOnlyBypassableByManageScope("/api/services/bifrost/install"), false);
- });
});
// ---------------------------------------------------------------------------
diff --git a/tests/snapshots/provider/translate-path.json b/tests/snapshots/provider/translate-path.json
index 6fe22b4d39..3dfce0ca56 100644
--- a/tests/snapshots/provider/translate-path.json
+++ b/tests/snapshots/provider/translate-path.json
@@ -33,10 +33,10 @@
"Content-Type": "application/json",
"User-Agent": "claude-cli/2.1.195 (external, cli)",
"X-App": "cli",
- "X-Stainless-Arch": "<ARCH>",
+ "X-Stainless-Arch": "x64",
"X-Stainless-Helper-Method": "stream",
"X-Stainless-Lang": "js",
- "X-Stainless-Os": "<OS>",
+ "X-Stainless-Os": "Linux",
"X-Stainless-Package-Version": "0.94.0",
"X-Stainless-Retry-Count": "0",
"X-Stainless-Runtime": "node",
@@ -51,10 +51,10 @@
"Content-Type": "application/json",
"User-Agent": "claude-cli/2.1.195 (external, cli)",
"X-App": "cli",
- "X-Stainless-Arch": "<ARCH>",
+ "X-Stainless-Arch": "x64",
"X-Stainless-Helper-Method": "stream",
"X-Stainless-Lang": "js",
- "X-Stainless-Os": "<OS>",
+ "X-Stainless-Os": "Linux",
"X-Stainless-Package-Version": "0.94.0",
"X-Stainless-Retry-Count": "0",
"X-Stainless-Runtime": "node",
@@ -70,10 +70,10 @@
"Content-Type": "application/json",
"User-Agent": "claude-cli/2.1.195 (external, cli)",
"X-App": "cli",
- "X-Stainless-Arch": "<ARCH>",
+ "X-Stainless-Arch": "x64",
"X-Stainless-Helper-Method": "stream",
"X-Stainless-Lang": "js",
- "X-Stainless-Os": "<OS>",
+ "X-Stainless-Os": "Linux",
"X-Stainless-Package-Version": "0.94.0",
"X-Stainless-Retry-Count": "0",
"X-Stainless-Runtime": "node",
@@ -94,18 +94,18 @@
"Accept": "text/event-stream",
"Authorization": "Bearer <TOK>",
"Content-Type": "application/json",
- "User-Agent": "Antigravity/4.2.0 (<PLATFORM>) Chrome/142.0.7444.175 Electron/39.2.3"
+ "User-Agent": "Antigravity/4.2.0 (X11; Linux x86_64) Chrome/142.0.7444.175 Electron/39.2.3"
},
"nonStream": {
"Authorization": "Bearer <TOK>",
"Content-Type": "application/json",
- "User-Agent": "Antigravity/4.2.0 (<PLATFORM>) Chrome/142.0.7444.175 Electron/39.2.3"
+ "User-Agent": "Antigravity/4.2.0 (X11; Linux x86_64) Chrome/142.0.7444.175 Electron/39.2.3"
},
"oauth": {
"Accept": "text/event-stream",
"Authorization": "Bearer <TOK>",
"Content-Type": "application/json",
- "User-Agent": "Antigravity/4.2.0 (<PLATFORM>) Chrome/142.0.7444.175 Electron/39.2.3"
+ "User-Agent": "Antigravity/4.2.0 (X11; Linux x86_64) Chrome/142.0.7444.175 Electron/39.2.3"
}
},
"url": {
@@ -241,18 +241,18 @@
"Accept": "text/event-stream",
"Authorization": "Bearer <TOK>",
"Content-Type": "application/json",
- "User-Agent": "Antigravity/4.2.0 (<PLATFORM>) Chrome/142.0.7444.175 Electron/39.2.3"
+ "User-Agent": "Antigravity/4.2.0 (X11; Linux x86_64) Chrome/142.0.7444.175 Electron/39.2.3"
},
"nonStream": {
"Authorization": "Bearer <TOK>",
"Content-Type": "application/json",
- "User-Agent": "Antigravity/4.2.0 (<PLATFORM>) Chrome/142.0.7444.175 Electron/39.2.3"
+ "User-Agent": "Antigravity/4.2.0 (X11; Linux x86_64) Chrome/142.0.7444.175 Electron/39.2.3"
},
"oauth": {
"Accept": "text/event-stream",
"Authorization": "Bearer <TOK>",
"Content-Type": "application/json",
- "User-Agent": "Antigravity/4.2.0 (<PLATFORM>) Chrome/142.0.7444.175 Electron/39.2.3"
+ "User-Agent": "Antigravity/4.2.0 (X11; Linux x86_64) Chrome/142.0.7444.175 Electron/39.2.3"
}
},
"url": {
@@ -289,52 +289,6 @@
"stream": "https://api.airforce/v1/chat/completions"
}
},
- "auggie": {
- "format": "openai",
- "headers": {
- "apiKey": {
- "Accept": "text/event-stream",
- "Authorization": "Bearer <TOK>",
- "Content-Type": "application/json"
- },
- "nonStream": {
- "Authorization": "Bearer <TOK>",
- "Content-Type": "application/json"
- },
- "oauth": {
- "Accept": "text/event-stream",
- "Authorization": "Bearer <TOK>",
- "Content-Type": "application/json"
- }
- },
- "url": {
- "nonStream": "auggie://cli/stdio",
- "stream": "auggie://cli/stdio"
- }
- },
- "bai": {
- "format": "openai",
- "headers": {
- "apiKey": {
- "Accept": "text/event-stream",
- "Authorization": "Bearer <TOK>",
- "Content-Type": "application/json"
- },
- "nonStream": {
- "Authorization": "Bearer <TOK>",
- "Content-Type": "application/json"
- },
- "oauth": {
- "Accept": "text/event-stream",
- "Authorization": "Bearer <TOK>",
- "Content-Type": "application/json"
- }
- },
- "url": {
- "nonStream": "https://api.b.ai/v1/chat/completions",
- "stream": "https://api.b.ai/v1/chat/completions"
- }
- },
"baichuan": {
"format": "openai",
"headers": {
@@ -611,29 +565,6 @@
"stream": "https://api.cerebras.ai/v1/chat/completions"
}
},
- "charm-hyper": {
- "format": "openai",
- "headers": {
- "apiKey": {
- "Accept": "text/event-stream",
- "Authorization": "Bearer <TOK>",
- "Content-Type": "application/json"
- },
- "nonStream": {
- "Authorization": "Bearer <TOK>",
- "Content-Type": "application/json"
- },
- "oauth": {
- "Accept": "text/event-stream",
- "Authorization": "Bearer <TOK>",
- "Content-Type": "application/json"
- }
- },
- "url": {
- "nonStream": "https://hyper.charm.land/v1/chat/completions",
- "stream": "https://hyper.charm.land/v1/chat/completions"
- }
- },
"chatgpt-web": {
"format": "openai",
"headers": {
@@ -714,10 +645,10 @@
"Content-Type": "application/json",
"User-Agent": "claude-cli/2.1.195 (external, cli)",
"X-App": "cli",
- "X-Stainless-Arch": "<ARCH>",
+ "X-Stainless-Arch": "x64",
"X-Stainless-Helper-Method": "stream",
"X-Stainless-Lang": "js",
- "X-Stainless-Os": "<OS>",
+ "X-Stainless-Os": "Linux",
"X-Stainless-Package-Version": "0.94.0",
"X-Stainless-Retry-Count": "0",
"X-Stainless-Runtime": "node",
@@ -732,10 +663,10 @@
"Content-Type": "application/json",
"User-Agent": "claude-cli/2.1.195 (external, cli)",
"X-App": "cli",
- "X-Stainless-Arch": "<ARCH>",
+ "X-Stainless-Arch": "x64",
"X-Stainless-Helper-Method": "stream",
"X-Stainless-Lang": "js",
- "X-Stainless-Os": "<OS>",
+ "X-Stainless-Os": "Linux",
"X-Stainless-Package-Version": "0.94.0",
"X-Stainless-Retry-Count": "0",
"X-Stainless-Runtime": "node",
@@ -751,10 +682,10 @@
"Content-Type": "application/json",
"User-Agent": "claude-cli/2.1.195 (external, cli)",
"X-App": "cli",
- "X-Stainless-Arch": "<ARCH>",
+ "X-Stainless-Arch": "x64",
"X-Stainless-Helper-Method": "stream",
"X-Stainless-Lang": "js",
- "X-Stainless-Os": "<OS>",
+ "X-Stainless-Os": "Linux",
"X-Stainless-Package-Version": "0.94.0",
"X-Stainless-Retry-Count": "0",
"X-Stainless-Runtime": "node",
@@ -841,35 +772,6 @@
"stream": "https://api.cline.bot/api/v1/chat/completions"
}
},
- "clinepass": {
- "format": "openai",
- "headers": {
- "apiKey": {
- "Accept": "text/event-stream",
- "Authorization": "Bearer <TOK>",
- "Content-Type": "application/json",
- "HTTP-Referer": "https://cline.bot",
- "X-Title": "Cline"
- },
- "nonStream": {
- "Authorization": "Bearer <TOK>",
- "Content-Type": "application/json",
- "HTTP-Referer": "https://cline.bot",
- "X-Title": "Cline"
- },
- "oauth": {
- "Accept": "text/event-stream",
- "Authorization": "Bearer <TOK>",
- "Content-Type": "application/json",
- "HTTP-Referer": "https://cline.bot",
- "X-Title": "Cline"
- }
- },
- "url": {
- "nonStream": "https://api.cline.bot/api/v1/chat/completions",
- "stream": "https://api.cline.bot/api/v1/chat/completions"
- }
- },
"cloudflare-ai": {
"format": "openai",
"headers": {
@@ -965,7 +867,7 @@
"Authorization": "Bearer <TOK>",
"Content-Type": "application/json",
"Openai-Beta": "responses=experimental",
- "User-Agent": "codex-cli/0.142.0 (<OS>; <ARCH>)",
+ "User-Agent": "codex-cli/0.142.0 (Windows 10.0.26200; x64)",
"Version": "0.142.0",
"X-Codex-Beta-Features": "responses_websockets"
},
@@ -973,7 +875,7 @@
"Authorization": "Bearer <TOK>",
"Content-Type": "application/json",
"Openai-Beta": "responses=experimental",
- "User-Agent": "codex-cli/0.142.0 (<OS>; <ARCH>)",
+ "User-Agent": "codex-cli/0.142.0 (Windows 10.0.26200; x64)",
"Version": "0.142.0",
"X-Codex-Beta-Features": "responses_websockets"
},
@@ -982,7 +884,7 @@
"Authorization": "Bearer <TOK>",
"Content-Type": "application/json",
"Openai-Beta": "responses=experimental",
- "User-Agent": "codex-cli/0.142.0 (<OS>; <ARCH>)",
+ "User-Agent": "codex-cli/0.142.0 (Windows 10.0.26200; x64)",
"Version": "0.142.0",
"X-Codex-Beta-Features": "responses_websockets"
}
@@ -1754,14 +1656,14 @@
"Authorization": "Bearer <TOK>",
"Content-Type": "application/json",
"HTTP-Referer": "https://github.com/Gitlawb/openclaude",
- "User-Agent": "OpenClaude/1.0 (<OS>; <ARCH>)",
+ "User-Agent": "OpenClaude/1.0 (linux; x86_64)",
"X-Title": "OpenClaude CLI"
},
"nonStream": {
"Authorization": "Bearer <TOK>",
"Content-Type": "application/json",
"HTTP-Referer": "https://github.com/Gitlawb/openclaude",
- "User-Agent": "OpenClaude/1.0 (<OS>; <ARCH>)",
+ "User-Agent": "OpenClaude/1.0 (linux; x86_64)",
"X-Title": "OpenClaude CLI"
},
"oauth": {
@@ -1769,7 +1671,7 @@
"Authorization": "Bearer <TOK>",
"Content-Type": "application/json",
"HTTP-Referer": "https://github.com/Gitlawb/openclaude",
- "User-Agent": "OpenClaude/1.0 (<OS>; <ARCH>)",
+ "User-Agent": "OpenClaude/1.0 (linux; x86_64)",
"X-Title": "OpenClaude CLI"
}
},
@@ -1786,14 +1688,14 @@
"Authorization": "Bearer <TOK>",
"Content-Type": "application/json",
"HTTP-Referer": "https://github.com/Gitlawb/openclaude",
- "User-Agent": "OpenClaude/1.0 (<OS>; <ARCH>)",
+ "User-Agent": "OpenClaude/1.0 (linux; x86_64)",
"X-Title": "OpenClaude CLI"
},
"nonStream": {
"Authorization": "Bearer <TOK>",
"Content-Type": "application/json",
"HTTP-Referer": "https://github.com/Gitlawb/openclaude",
- "User-Agent": "OpenClaude/1.0 (<OS>; <ARCH>)",
+ "User-Agent": "OpenClaude/1.0 (linux; x86_64)",
"X-Title": "OpenClaude CLI"
},
"oauth": {
@@ -1801,7 +1703,7 @@
"Authorization": "Bearer <TOK>",
"Content-Type": "application/json",
"HTTP-Referer": "https://github.com/Gitlawb/openclaude",
- "User-Agent": "OpenClaude/1.0 (<OS>; <ARCH>)",
+ "User-Agent": "OpenClaude/1.0 (linux; x86_64)",
"X-Title": "OpenClaude CLI"
}
},
@@ -2755,29 +2657,6 @@
"stream": "https://api.modal.ai/v1/chat/completions"
}
},
- "modelscope": {
- "format": "openai",
- "headers": {
- "apiKey": {
- "Accept": "text/event-stream",
- "Authorization": "Bearer <TOK>",
- "Content-Type": "application/json"
- },
- "nonStream": {
- "Authorization": "Bearer <TOK>",
- "Content-Type": "application/json"
- },
- "oauth": {
- "Accept": "text/event-stream",
- "Authorization": "Bearer <TOK>",
- "Content-Type": "application/json"
- }
- },
- "url": {
- "nonStream": "https://api-inference.modelscope.cn/v1/chat/completions",
- "stream": "https://api-inference.modelscope.cn/v1/chat/completions"
- }
- },
"monsterapi": {
"format": "openai",
"headers": {
@@ -3008,29 +2887,6 @@
"stream": "https://inference.api.nscale.com/v1/chat/completions"
}
},
- "nube": {
- "format": "openai",
- "headers": {
- "apiKey": {
- "Accept": "text/event-stream",
- "Authorization": "Bearer <TOK>",
- "Content-Type": "application/json"
- },
- "nonStream": {
- "Authorization": "Bearer <TOK>",
- "Content-Type": "application/json"
- },
- "oauth": {
- "Accept": "text/event-stream",
- "Authorization": "Bearer <TOK>",
- "Content-Type": "application/json"
- }
- },
- "url": {
- "nonStream": "https://ai.nube.sh/api/v1/chat/completions",
- "stream": "https://ai.nube.sh/api/v1/chat/completions"
- }
- },
"nvidia": {
"format": "openai",
"headers": {
@@ -3457,29 +3313,6 @@
"stream": "https://qianfan.baidubce.com/v2/chat/completions"
}
},
- "qiniu": {
- "format": "openai",
- "headers": {
- "apiKey": {
- "Accept": "text/event-stream",
- "Authorization": "Bearer <TOK>",
- "Content-Type": "application/json"
- },
- "nonStream": {
- "Authorization": "Bearer <TOK>",
- "Content-Type": "application/json"
- },
- "oauth": {
- "Accept": "text/event-stream",
- "Authorization": "Bearer <TOK>",
- "Content-Type": "application/json"
- }
- },
- "url": {
- "nonStream": "https://api.qnaigc.com/v1/chat/completions",
- "stream": "https://api.qnaigc.com/v1/chat/completions"
- }
- },
"qoder": {
"format": "openai",
"headers": {
@@ -3516,13 +3349,13 @@
"Connection": "keep-alive",
"Content-Type": "application/json",
"Sec-Fetch-Mode": "cors",
- "User-Agent": "QwenCode/0.19.3 (<OS>; <ARCH>)",
+ "User-Agent": "QwenCode/0.19.3 (linux; x64)",
"X-Dashscope-AuthType": "qwen-oauth",
"X-Dashscope-CacheControl": "enable",
- "X-Dashscope-UserAgent": "QwenCode/0.19.3 (<OS>; <ARCH>)",
- "X-Stainless-Arch": "<ARCH>",
+ "X-Dashscope-UserAgent": "QwenCode/0.19.3 (linux; x64)",
+ "X-Stainless-Arch": "x64",
"X-Stainless-Lang": "js",
- "X-Stainless-Os": "<OS>",
+ "X-Stainless-Os": "Linux",
"X-Stainless-Package-Version": "5.11.0",
"X-Stainless-Retry-Count": "1",
"X-Stainless-Runtime": "node",
@@ -3534,13 +3367,13 @@
"Connection": "keep-alive",
"Content-Type": "application/json",
"Sec-Fetch-Mode": "cors",
- "User-Agent": "QwenCode/0.19.3 (<OS>; <ARCH>)",
+ "User-Agent": "QwenCode/0.19.3 (linux; x64)",
"X-Dashscope-AuthType": "qwen-oauth",
"X-Dashscope-CacheControl": "enable",
- "X-Dashscope-UserAgent": "QwenCode/0.19.3 (<OS>; <ARCH>)",
- "X-Stainless-Arch": "<ARCH>",
+ "X-Dashscope-UserAgent": "QwenCode/0.19.3 (linux; x64)",
+ "X-Stainless-Arch": "x64",
"X-Stainless-Lang": "js",
- "X-Stainless-Os": "<OS>",
+ "X-Stainless-Os": "Linux",
"X-Stainless-Package-Version": "5.11.0",
"X-Stainless-Retry-Count": "1",
"X-Stainless-Runtime": "node",
@@ -3553,13 +3386,13 @@
"Connection": "keep-alive",
"Content-Type": "application/json",
"Sec-Fetch-Mode": "cors",
- "User-Agent": "QwenCode/0.19.3 (<OS>; <ARCH>)",
+ "User-Agent": "QwenCode/0.19.3 (linux; x64)",
"X-Dashscope-AuthType": "qwen-oauth",
"X-Dashscope-CacheControl": "enable",
- "X-Dashscope-UserAgent": "QwenCode/0.19.3 (<OS>; <ARCH>)",
- "X-Stainless-Arch": "<ARCH>",
+ "X-Dashscope-UserAgent": "QwenCode/0.19.3 (linux; x64)",
+ "X-Stainless-Arch": "x64",
"X-Stainless-Lang": "js",
- "X-Stainless-Os": "<OS>",
+ "X-Stainless-Os": "Linux",
"X-Stainless-Package-Version": "5.11.0",
"X-Stainless-Retry-Count": "1",
"X-Stainless-Runtime": "node",
@@ -3778,29 +3611,6 @@
"stream": "https://api.stepfun.com/v1/chat/completions"
}
},
- "sumopod": {
- "format": "openai",
- "headers": {
- "apiKey": {
- "Accept": "text/event-stream",
- "Authorization": "Bearer <TOK>",
- "Content-Type": "application/json"
- },
- "nonStream": {
- "Authorization": "Bearer <TOK>",
- "Content-Type": "application/json"
- },
- "oauth": {
- "Accept": "text/event-stream",
- "Authorization": "Bearer <TOK>",
- "Content-Type": "application/json"
- }
- },
- "url": {
- "nonStream": "https://ai.sumopod.com/v1/chat/completions",
- "stream": "https://ai.sumopod.com/v1/chat/completions"
- }
- },
"suno": {
"format": "openai",
"headers": {
@@ -4287,29 +4097,6 @@
"stream": "https://server.self-serve.windsurf.com"
}
},
- "x5lab": {
- "format": "openai",
- "headers": {
- "apiKey": {
- "Accept": "text/event-stream",
- "Authorization": "Bearer <TOK>",
- "Content-Type": "application/json"
- },
- "nonStream": {
- "Authorization": "Bearer <TOK>",
- "Content-Type": "application/json"
- },
- "oauth": {
- "Accept": "text/event-stream",
- "Authorization": "Bearer <TOK>",
- "Content-Type": "application/json"
- }
- },
- "url": {
- "nonStream": "https://api.x5lab.dev/v1/chat/completions",
- "stream": "https://api.x5lab.dev/v1/chat/completions"
- }
- },
"xai": {
"format": "openai",
"headers": {
diff --git a/tests/unit/account-fallback-retry-after-json.test.ts b/tests/unit/account-fallback-retry-after-json.test.ts
deleted file mode 100644
index 515dd46351..0000000000
--- a/tests/unit/account-fallback-retry-after-json.test.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import test from "node:test";
-import assert from "node:assert/strict";
-
-const { parseRetryFromErrorText } = await import("../../open-sse/services/accountFallback.ts");
-
-test("parseRetryFromErrorText reads nested ISO retryAfter from a 429 JSON body", () => {
- const futureIso = new Date(Date.now() + 120_000).toISOString();
- const waitMs = parseRetryFromErrorText(JSON.stringify({ error: { retryAfter: futureIso } }));
- assert.ok(waitMs !== null, "expected a parsed wait time, got null");
- assert.ok(Math.abs((waitMs as number) - 120_000) <= 2_000, `expected ~120000ms, got ${waitMs}`);
-});
-
-test("parseRetryFromErrorText reads top-level retryAfter when nested field is absent", () => {
- const futureIso = new Date(Date.now() + 60_000).toISOString();
- const waitMs = parseRetryFromErrorText(JSON.stringify({ retryAfter: futureIso }));
- assert.ok(waitMs !== null, "expected a parsed wait time, got null");
- assert.ok(Math.abs((waitMs as number) - 60_000) <= 2_000, `expected ~60000ms, got ${waitMs}`);
-});
-
-test("parseRetryFromErrorText reads millisecond retry hints from 429 JSON bodies", () => {
- assert.equal(parseRetryFromErrorText(JSON.stringify({ retry_after_ms: 45_000 })), 45_000);
- assert.equal(
- parseRetryFromErrorText(JSON.stringify({ error: { retry_after_ms: 12_000 } })),
- 12_000
- );
- assert.equal(parseRetryFromErrorText(JSON.stringify({ retryAfterMs: 8_000 })), 8_000);
-});
-
-test("parseRetryFromErrorText ignores past ISO retryAfter values in JSON bodies", () => {
- const pastIso = new Date(Date.now() - 60_000).toISOString();
- assert.equal(parseRetryFromErrorText(JSON.stringify({ error: { retryAfter: pastIso } })), null);
-});
diff --git a/tests/unit/agy-projectid-ui.test.ts b/tests/unit/agy-projectid-ui.test.ts
deleted file mode 100644
index de0c057819..0000000000
--- a/tests/unit/agy-projectid-ui.test.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import { describe, it } from "node:test";
-import assert from "node:assert";
-import { readFileSync } from "node:fs";
-
-const modalPath =
- "src/app/(dashboard)/dashboard/providers/[id]/components/modals/EditConnectionModal.tsx";
-const source = readFileSync(modalPath, "utf8");
-
-describe("agy Project ID UI support", () => {
- it("declares a single Antigravity-family provider gate", () => {
- assert.ok(
- source.includes(
- 'const isAntigravityFamily = provider === "antigravity" || provider === "agy";'
- ),
- "isAntigravityFamily must include antigravity and agy without a separate Google Project ID gate"
- );
- });
-
- it("does not keep the old supportsGoogleProjectId alias", () => {
- assert.equal(source.includes("supportsGoogleProjectId"), false);
- });
-
- it("uses antigravityProjectIdLabel for Antigravity-family providers", () => {
- assert.ok(
- source.includes('label={t("antigravityProjectIdLabel")}'),
- "projectId label must use Antigravity-family copy"
- );
- });
-
- it("uses isAntigravityFamily for antigravityClientProfile UI", () => {
- assert.ok(
- source.includes("{isAntigravityFamily && (\n <div") &&
- source.includes('label={t("antigravityClientProfileLabel")}'),
- "client profile Select must render for isAntigravityFamily"
- );
- });
-
- it("uses isAntigravityFamily for client profile save", () => {
- assert.ok(
- source.includes("if (isAntigravityFamily) {"),
- "client profile save must use isAntigravityFamily"
- );
- });
-});
diff --git a/tests/unit/airforce-v1-double-prefix-5899.test.ts b/tests/unit/airforce-v1-double-prefix-5899.test.ts
deleted file mode 100644
index 288fbd0d03..0000000000
--- a/tests/unit/airforce-v1-double-prefix-5899.test.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-/**
- * Regression for #5899 (PR #5920): the OpenAI-compatible models-discovery URL
- * builder must strip a trailing `/v1` UNCONDITIONALLY before appending
- * `/v1/models`. A gateway baseUrl like ".../v1/chat/completions" was reduced to
- * ".../v1" (the old `else if` skipped the /v1 strip once `/chat/completions`
- * matched) and then produced ".../v1/v1/models" — a 308 redirect that blocked
- * model discovery. The fix converts the `/v1` strip to an independent `if`
- * (guarding against a literal "scheme://v1" authority) in BOTH the general
- * discovery path and the `provider === "openai"` custom-base-URL path.
- */
-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-5899-"));
-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 modelsRoute = await import("../../src/app/api/providers/[id]/models/route.ts");
-
-test.after(() => {
- core.resetDbInstance();
- fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
-});
-
-test("#5899 openai gateway baseUrl ending in /v1/chat/completions never probes /v1/v1/models", async () => {
- const connection = await providersDb.createProviderConnection({
- provider: "openai",
- authType: "apikey",
- name: "airforce-gateway",
- apiKey: "sk-airforce",
- providerSpecificData: { baseUrl: "https://api.airforce/v1/chat/completions" },
- });
-
- const requestedUrls: string[] = [];
- const originalFetch = globalThis.fetch;
- globalThis.fetch = async (url) => {
- const u = String(url);
- requestedUrls.push(u);
- // The correctly-stripped candidate must be the one that serves models.
- if (u === "https://api.airforce/v1/models") {
- return Response.json({ object: "list", data: [{ id: "gpt-4o" }, { id: "gpt-5" }] });
- }
- // The double-prefixed URL upstream answered with a 308 redirect (#5899).
- if (u === "https://api.airforce/v1/v1/models") {
- return new Response(null, { status: 308, headers: { location: u } });
- }
- return new Response("not found", { status: 404 });
- };
-
- try {
- await modelsRoute.GET(
- new Request(`http://localhost/api/providers/${connection.id}/models?refresh=true`),
- { params: { id: connection.id } }
- );
- } finally {
- globalThis.fetch = originalFetch;
- }
-
- assert.ok(
- requestedUrls.includes("https://api.airforce/v1/models"),
- `expected a request to the correctly-stripped /v1/models URL; got: ${JSON.stringify(requestedUrls)}`
- );
- assert.ok(
- !requestedUrls.includes("https://api.airforce/v1/v1/models"),
- `must never probe the double-prefixed /v1/v1/models URL; got: ${JSON.stringify(requestedUrls)}`
- );
-});
diff --git a/tests/unit/antigravity-executor-split.test.ts b/tests/unit/antigravity-executor-split.test.ts
deleted file mode 100644
index c965b803ef..0000000000
--- a/tests/unit/antigravity-executor-split.test.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import { test } from "node:test";
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { fileURLToPath } from "node:url";
-import { dirname, join } from "node:path";
-
-// Split-guard for the antigravity executor SSE-collect extraction.
-// The pure SSE-payload -> collected-stream parser lives in antigravity/sseCollect.ts
-// (no host state, no fetch/auth). Host imports the helpers it uses and re-exports
-// processAntigravitySSEPayload for external importers (tests).
-const HERE = dirname(fileURLToPath(import.meta.url));
-const EXE = join(HERE, "../../open-sse/executors");
-const HOST = join(EXE, "antigravity.ts");
-const LEAF = join(EXE, "antigravity/sseCollect.ts");
-
-test("leaf hosts the SSE-collect helpers and does not import the host", () => {
- const src = readFileSync(LEAF, "utf8");
- for (const sym of [
- "processAntigravitySSEPayload",
- "processAntigravitySSEText",
- "flushAntigravitySSEText",
- "stripZeroWidth",
- ]) {
- assert.match(src, new RegExp(`export (function|type) ${sym}\\b`));
- }
- assert.doesNotMatch(src, /from "\.\.\/antigravity\.ts"/);
-});
-
-test("host re-exports processAntigravitySSEPayload", () => {
- const host = readFileSync(HOST, "utf8");
- assert.match(
- host,
- /export \{ processAntigravitySSEPayload \} from "\.\/antigravity\/sseCollect\.ts"/
- );
- assert.match(host, /from "\.\/antigravity\/sseCollect\.ts"/);
-});
-
-test("SSE-collect helpers are callable and tolerate empty/garbage input", async () => {
- const { processAntigravitySSEPayload, stripZeroWidth } =
- await import("../../open-sse/executors/antigravity/sseCollect.ts");
- assert.equal(typeof processAntigravitySSEPayload, "function");
- // stripZeroWidth removes zero-width markers from strings, passes through non-strings.
- assert.equal(stripZeroWidth("a​b"), "ab");
- assert.deepEqual(stripZeroWidth(42), 42);
- // A malformed payload must not throw (defensive parse).
- const collected = { textContent: "" };
- assert.doesNotThrow(() => processAntigravitySSEPayload("not-json", collected));
-});
diff --git a/tests/unit/antigravity-orphan-toolresult-6026.test.ts b/tests/unit/antigravity-orphan-toolresult-6026.test.ts
deleted file mode 100644
index 1fe8091720..0000000000
--- a/tests/unit/antigravity-orphan-toolresult-6026.test.ts
+++ /dev/null
@@ -1,127 +0,0 @@
-/**
- * Regression test for #6026.
- *
- * Antigravity IDE (via AgentBridge/MITM → `/v1/antigravity` → translator) can ship a
- * truncated history whose FIRST turn is a tool result (`functionResponse`) with no
- * preceding tool call. When that survives the antigravity→openai→claude chain, Anthropic
- * (Vertex `claude-opus-4.6`) rejects it with HTTP 400:
- *
- * messages.0.content.1: unexpected tool_use_id found in tool_result blocks:
- * toolu_vrtx_...: Each tool_result block must have a corresponding tool_use block in
- * the previous message.
- *
- * The fix strips orphan tool_results at the antigravity message-assembly point
- * (`antigravityToOpenAIRequest`) by reusing `fixToolPairs`, so the orphan never reaches
- * the upstream Claude request.
- *
- * PURE-FUNCTION ONLY — this test imports the translator + sanitizer functions directly.
- * It must NEVER start the MITM proxy, bind :443/:80, touch /etc/hosts, or install a CA.
- */
-import test from "node:test";
-import assert from "node:assert/strict";
-
-const { antigravityToOpenAIRequest } = await import(
- "../../open-sse/translator/request/antigravity-to-openai.ts"
-);
-const { fixToolPairs } = await import("../../open-sse/services/contextManager.ts");
-
-test("#6026: antigravityToOpenAIRequest strips an orphan functionResponse (no preceding functionCall)", () => {
- const result = antigravityToOpenAIRequest(
- "ag/claude-opus-4-6",
- {
- request: {
- contents: [
- {
- // First (and only) turn is a tool result with NO preceding tool call.
- role: "user",
- parts: [
- {
- functionResponse: {
- id: "toolu_vrtx_test",
- name: "read_file",
- response: { result: { ok: true } },
- },
- },
- ],
- },
- ],
- },
- },
- false
- );
-
- // The orphan tool message must be gone — otherwise the openai→claude step would emit an
- // orphan tool_result block and Anthropic would 400.
- const orphan = result.messages.find(
- (m: Record<string, unknown>) => m.role === "tool" && m.tool_call_id === "toolu_vrtx_test"
- );
- assert.equal(orphan, undefined, "orphan tool_result message must be stripped");
- assert.equal(
- result.messages.some((m: Record<string, unknown>) => m.role === "tool"),
- false,
- "no orphan tool messages should remain"
- );
-});
-
-test("#6026: well-formed functionCall/functionResponse pair is preserved (no regression)", () => {
- const result = antigravityToOpenAIRequest(
- "ag/claude-opus-4-6",
- {
- request: {
- contents: [
- {
- role: "model",
- parts: [{ functionCall: { id: "toolu_vrtx_ok", name: "read_file", args: {} } }],
- },
- {
- role: "user",
- parts: [
- {
- functionResponse: {
- id: "toolu_vrtx_ok",
- name: "read_file",
- response: { result: { ok: true } },
- },
- },
- ],
- },
- ],
- },
- },
- false
- );
-
- const assistant = result.messages.find(
- (m: Record<string, unknown>) => m.role === "assistant"
- );
- const tool = result.messages.find((m: Record<string, unknown>) => m.role === "tool");
- assert.ok(assistant, "assistant tool_call message must survive");
- assert.ok(tool, "matched tool_result message must survive");
- assert.equal((tool as Record<string, unknown>).tool_call_id, "toolu_vrtx_ok");
-});
-
-test("#6026: fixToolPairs removes the exact Anthropic-shape orphan tool_result block", () => {
- // Mirrors the reporter's failing body: messages[0] is a user message whose content array
- // holds a tool_result block with no matching tool_use anywhere in the request.
- const messages: Record<string, unknown>[] = [
- {
- role: "user",
- content: [
- { type: "text", text: "continue" },
- { type: "tool_result", tool_use_id: "toolu_vrtx_test", content: "stale" },
- ],
- },
- ];
-
- const fixed = fixToolPairs(messages);
-
- const stillHasOrphan = fixed.some(
- (m) =>
- m.role === "user" &&
- Array.isArray(m.content) &&
- (m.content as Record<string, unknown>[]).some(
- (b) => b.type === "tool_result" && b.tool_use_id === "toolu_vrtx_test"
- )
- );
- assert.equal(stillHasOrphan, false, "orphan tool_result block must be stripped");
-});
diff --git a/tests/unit/api-key-provider-quota-bypass-scope.test.ts b/tests/unit/api-key-provider-quota-bypass-scope.test.ts
index 91a29de6d7..c19f773394 100644
--- a/tests/unit/api-key-provider-quota-bypass-scope.test.ts
+++ b/tests/unit/api-key-provider-quota-bypass-scope.test.ts
@@ -27,12 +27,7 @@ test("chat handler maps API key provider quota bypass scope to auth bypass optio
});
test("auto combo disables hard provider quota cutoffs when relay requests bypass", () => {
- // The auto-strategy bypass logic was extracted verbatim from combo.ts into the
- // resolveAutoStrategy leaf (Block J Task 2); the source scan follows the code.
- const source = fs.readFileSync(
- path.join(repoRoot, "open-sse/services/combo/resolveAutoStrategy.ts"),
- "utf8"
- );
+ const source = fs.readFileSync(path.join(repoRoot, "open-sse/services/combo.ts"), "utf8");
assert.match(source, /relayOptions\?\.bypassProviderQuotaPolicy === true/);
assert.match(source, /quotaPreflight:[\s\S]*enabled: false/);
diff --git a/tests/unit/api/authz-inventory.test.ts b/tests/unit/api/authz-inventory.test.ts
index a1363d8026..5d37f44c11 100644
--- a/tests/unit/api/authz-inventory.test.ts
+++ b/tests/unit/api/authz-inventory.test.ts
@@ -19,7 +19,6 @@ process.env.OMNIROUTE_DISABLE_REDIS_AUTH_CACHE = "1";
const ORIGINAL_JWT_SECRET = process.env.JWT_SECRET;
const ORIGINAL_INITIAL_PASSWORD = process.env.INITIAL_PASSWORD;
-const ORIGINAL_CORS_ALLOW_ALL = process.env.CORS_ALLOW_ALL;
const core = await import("../../../src/lib/db/core.ts");
const settingsDb = await import("../../../src/lib/db/settings.ts");
@@ -40,8 +39,6 @@ test.after(() => {
else process.env.JWT_SECRET = ORIGINAL_JWT_SECRET;
if (ORIGINAL_INITIAL_PASSWORD === undefined) delete process.env.INITIAL_PASSWORD;
else process.env.INITIAL_PASSWORD = ORIGINAL_INITIAL_PASSWORD;
- if (ORIGINAL_CORS_ALLOW_ALL === undefined) delete process.env.CORS_ALLOW_ALL;
- else process.env.CORS_ALLOW_ALL = ORIGINAL_CORS_ALLOW_ALL;
});
// ─── AC-1 — shape ─────────────────────────────────────────────────────────
@@ -156,44 +153,6 @@ test("AC-2: bypassPrefixes additions land in the inventory", async () => {
assert.deepEqual(body.bypassPrefixes, ["/api/mcp/", "/api/mcp/v2/"]);
});
-// ─── #5602 — CORS status surfaced for the dashboard wildcard warning ──────
-
-test("#5602: cors.allowAll is false by default (no CORS_ALLOW_ALL)", async () => {
- process.env.JWT_SECRET = "test-jwt-secret-authz-inventory";
- process.env.INITIAL_PASSWORD = "initial-pass-cors-a";
- delete process.env.CORS_ALLOW_ALL;
- await settingsDb.updateSettings({ requireLogin: true });
-
- const response = await inventoryRoute.GET(
- await makeManagementSessionRequest("http://localhost/api/settings/authz-inventory", {
- method: "GET",
- })
- );
- assert.equal(response.status, 200);
- const body = (await response.json()) as {
- cors: { allowAll: boolean; allowedOrigins: string[] };
- };
- assert.ok(body.cors, "response should carry a cors envelope");
- assert.equal(body.cors.allowAll, false);
- assert.deepEqual(body.cors.allowedOrigins, []);
-});
-
-test("#5602: cors.allowAll reflects CORS_ALLOW_ALL=true", async () => {
- process.env.JWT_SECRET = "test-jwt-secret-authz-inventory";
- process.env.INITIAL_PASSWORD = "initial-pass-cors-b";
- process.env.CORS_ALLOW_ALL = "true";
- await settingsDb.updateSettings({ requireLogin: true });
-
- const response = await inventoryRoute.GET(
- await makeManagementSessionRequest("http://localhost/api/settings/authz-inventory", {
- method: "GET",
- })
- );
- assert.equal(response.status, 200);
- const body = (await response.json()) as { cors: { allowAll: boolean } };
- assert.equal(body.cors.allowAll, true);
-});
-
// ─── AC-12 — anonymous request rejected (no inventory leak) ───────────────
test("AC-12: anonymous request (no cookie, no Bearer) → 401", async () => {
diff --git a/tests/unit/api/discovery-routes.test.ts b/tests/unit/api/discovery-routes.test.ts
deleted file mode 100644
index 99dc8dddcc..0000000000
--- a/tests/unit/api/discovery-routes.test.ts
+++ /dev/null
@@ -1,155 +0,0 @@
-import { describe, test, before, after } from "node:test";
-import assert from "node:assert/strict";
-import { mkdtempSync, rmSync } from "node:fs";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-
-// Isolated DB + auth disabled so requireManagementAuth passes (no key configured).
-let tmpDataDir: string;
-let core: typeof import("@/lib/db/core");
-let db: typeof import("@/lib/db/discoveryResults");
-let resultsRoute: typeof import("@/app/api/discovery/results/route");
-let resultByIdRoute: typeof import("@/app/api/discovery/results/[id]/route");
-let scanRoute: typeof import("@/app/api/discovery/scan/route");
-let verifyRoute: typeof import("@/app/api/discovery/verify/[id]/route");
-
-function req(method: string, url: string, body?: unknown): Request {
- return new Request(`http://localhost${url}`, {
- method,
- headers: { "content-type": "application/json" },
- body: body === undefined ? undefined : JSON.stringify(body),
- });
-}
-
-before(async () => {
- tmpDataDir = mkdtempSync(join(tmpdir(), "omniroute-discovery-routes-"));
- process.env.DATA_DIR = tmpDataDir;
- delete process.env.REQUIRE_API_KEY;
- process.env.OMNIROUTE_DISABLE_AUTH = "1";
- core = await import("@/lib/db/core");
- core.resetDbInstance();
- core.getDbInstance();
- db = await import("@/lib/db/discoveryResults");
- resultsRoute = await import("@/app/api/discovery/results/route");
- resultByIdRoute = await import("@/app/api/discovery/results/[id]/route");
- scanRoute = await import("@/app/api/discovery/scan/route");
- verifyRoute = await import("@/app/api/discovery/verify/[id]/route");
-});
-
-after(() => {
- core.resetDbInstance();
- if (tmpDataDir) rmSync(tmpDataDir, { recursive: true, force: true });
-});
-
-describe("discovery API routes", () => {
- test("GET /results lists persisted findings (and filters by providerId)", async () => {
- db.upsertDiscoveryResult({
- providerId: "acme",
- method: "free_tier",
- authType: "none",
- feasibility: 3,
- riskLevel: "none",
- status: "pending",
- });
- const res = await resultsRoute.GET(req("GET", "/api/discovery/results?providerId=acme"));
- assert.equal(res.status, 200);
- const body = await res.json();
- assert.ok(Array.isArray(body.results));
- assert.ok(body.results.some((r: { providerId: string }) => r.providerId === "acme"));
- });
-
- test("GET /results/:id returns the row, 404 when missing, 400 on bad id", async () => {
- const created = db.upsertDiscoveryResult({
- providerId: "beta",
- method: "trial",
- authType: "api_key",
- feasibility: 2,
- riskLevel: "low",
- status: "pending",
- });
- const ok = await resultByIdRoute.GET(req("GET", `/api/discovery/results/${created.id}`), {
- params: Promise.resolve({ id: String(created.id) }),
- });
- assert.equal(ok.status, 200);
-
- const missing = await resultByIdRoute.GET(req("GET", "/api/discovery/results/999999"), {
- params: Promise.resolve({ id: "999999" }),
- });
- assert.equal(missing.status, 404);
-
- const bad = await resultByIdRoute.GET(req("GET", "/api/discovery/results/abc"), {
- params: Promise.resolve({ id: "abc" }),
- });
- assert.equal(bad.status, 400);
- });
-
- test("POST /scan persists findings; rejects an empty providerId with 400", async () => {
- const res = await scanRoute.POST(req("POST", "/api/discovery/scan", { providerId: "gamma" }));
- assert.equal(res.status, 200);
- const body = await res.json();
- assert.ok(Array.isArray(body.results) && body.results.length > 0);
- assert.ok(body.results[0].id > 0);
- // the persisted row is now queryable
- assert.ok(db.getDiscoveryResults("gamma").length > 0);
-
- const invalid = await scanRoute.POST(req("POST", "/api/discovery/scan", { providerId: "" }));
- assert.equal(invalid.status, 400);
-
- const malformed = new Request("http://localhost/api/discovery/scan", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: "{not json",
- });
- const malformedRes = await scanRoute.POST(malformed);
- assert.equal(malformedRes.status, 400);
- });
-
- test("POST /verify/:id marks verified, 404 when missing", async () => {
- const created = db.upsertDiscoveryResult({
- providerId: "delta",
- method: "public_api",
- authType: "api_key",
- feasibility: 5,
- riskLevel: "none",
- status: "pending",
- });
- const res = await verifyRoute.POST(req("POST", `/api/discovery/verify/${created.id}`), {
- params: Promise.resolve({ id: String(created.id) }),
- });
- assert.equal(res.status, 200);
- const body = await res.json();
- assert.equal(body.result.status, "verified");
-
- const missing = await verifyRoute.POST(req("POST", "/api/discovery/verify/999999"), {
- params: Promise.resolve({ id: "999999" }),
- });
- assert.equal(missing.status, 404);
- });
-
- test("DELETE /results/:id removes the row, 404 on second delete", async () => {
- const created = db.upsertDiscoveryResult({
- providerId: "epsilon",
- method: "free_tier",
- authType: "none",
- feasibility: 1,
- riskLevel: "none",
- status: "pending",
- });
- const first = await resultByIdRoute.DELETE(req("DELETE", `/api/discovery/results/${created.id}`), {
- params: Promise.resolve({ id: String(created.id) }),
- });
- assert.equal(first.status, 200);
- const second = await resultByIdRoute.DELETE(req("DELETE", `/api/discovery/results/${created.id}`), {
- params: Promise.resolve({ id: String(created.id) }),
- });
- assert.equal(second.status, 404);
- });
-
- test("error responses do not leak stack traces", async () => {
- const missing = await resultByIdRoute.GET(req("GET", "/api/discovery/results/424242"), {
- params: Promise.resolve({ id: "424242" }),
- });
- const body = await missing.json();
- assert.ok(!String(body.error?.message ?? "").includes("at /"));
- });
-});
diff --git a/tests/unit/api/v1/provider-plugin-manifest-route.test.ts b/tests/unit/api/v1/provider-plugin-manifest-route.test.ts
deleted file mode 100644
index 9af7baa46d..0000000000
--- a/tests/unit/api/v1/provider-plugin-manifest-route.test.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import assert from "node:assert/strict";
-import test from "node:test";
-
-import {
- GET,
- OPTIONS,
-} from "../../../../src/app/api/v1/provider-plugin-manifest/route.ts";
-
-test("provider plugin manifest route returns JSON-safe manifest", async () => {
- const response = await GET();
- const body = await response.json();
-
- assert.equal(response.status, 200);
- assert.equal(response.headers.get("Content-Type"), "application/json");
- assert.equal(body.schemaVersion, 1);
- assert.equal(body.generatedFrom, "open-sse/config/providers");
- assert.ok(body.providers.length > 100);
- assert.ok(body.providers.some((provider: { id: string }) => provider.id === "openai"));
-
- const serialized = JSON.stringify(body);
- assert.equal(serialized.includes("clientSecret"), false);
-});
-
-test("provider plugin manifest route handles CORS preflight", async () => {
- const response = await OPTIONS();
-
- assert.equal(response.status, 200);
- assert.equal(response.headers.get("Access-Control-Allow-Methods"), "GET, OPTIONS");
- assert.equal(response.headers.get("Access-Control-Allow-Headers"), "*");
-});
diff --git a/tests/unit/api/v1/relay-routing-backend.test.ts b/tests/unit/api/v1/relay-routing-backend.test.ts
index 6e8e0e0aad..c30af34b20 100644
--- a/tests/unit/api/v1/relay-routing-backend.test.ts
+++ b/tests/unit/api/v1/relay-routing-backend.test.ts
@@ -5,7 +5,6 @@ import {
getRoutingFallbackHeader,
resolveRelayRoutingBackend,
shouldTryBifrost,
- shouldTryBifrostForRequest,
} from "../../../../src/app/api/v1/relay/chat/completions/routingBackend.ts";
test("relay routing backend defaults to TypeScript without bifrost", () => {
@@ -99,56 +98,3 @@ test("relay routing backend keeps strict bifrost failures out of auto fallback a
assert.equal(getRoutingFallbackHeader("bifrost", config), undefined);
assert.equal(resolveRelayRoutingBackend({ OMNIROUTE_RELAY_BACKEND: "bifrost" }), "bifrost");
});
-
-test("relay routing backend auto mode tries bifrost for manifest-eligible providers", () => {
- const config = getBifrostRoutingConfig({
- BIFROST_BASE_URL: "http://127.0.0.1:8080",
- });
-
- assert.deepEqual(
- shouldTryBifrostForRequest("auto", config, { model: "openai/gpt-4.1" }, () => ({
- eligible: true,
- reasons: [],
- })),
- { tryBifrost: true }
- );
-});
-
-test("relay routing backend auto mode skips bifrost for manifest-ineligible providers", () => {
- const config = getBifrostRoutingConfig({
- BIFROST_BASE_URL: "http://127.0.0.1:8080",
- });
-
- assert.deepEqual(
- shouldTryBifrostForRequest("auto", config, { model: "cw/claude-sonnet-4.6" }, () => ({
- eligible: false,
- reasons: ["custom executor: claude-web"],
- })),
- { tryBifrost: false, fallbackReason: "bifrost-ineligible" }
- );
-});
-
-test("relay routing backend auto mode keeps unknown providers on TS fallback", () => {
- const config = getBifrostRoutingConfig({
- BIFROST_BASE_URL: "http://127.0.0.1:8080",
- });
-
- assert.deepEqual(
- shouldTryBifrostForRequest("auto", config, { model: "unknown/model" }, () => null),
- { tryBifrost: false, fallbackReason: "bifrost-provider-unknown" }
- );
-});
-
-test("relay routing backend strict bifrost bypasses manifest eligibility", () => {
- const config = getBifrostRoutingConfig({
- BIFROST_BASE_URL: "http://127.0.0.1:8080",
- });
-
- assert.deepEqual(
- shouldTryBifrostForRequest("bifrost", config, { model: "cw/claude-sonnet-4.6" }, () => ({
- eligible: false,
- reasons: ["custom executor: claude-web"],
- })),
- { tryBifrost: true }
- );
-});
diff --git a/tests/unit/api/validated-json-body.test.ts b/tests/unit/api/validated-json-body.test.ts
deleted file mode 100644
index f8076dbad0..0000000000
--- a/tests/unit/api/validated-json-body.test.ts
+++ /dev/null
@@ -1,91 +0,0 @@
-import { describe, test } from "node:test";
-import assert from "node:assert/strict";
-import { z } from "zod";
-import { validatedJsonBody } from "@/shared/validation/helpers";
-
-function makeRequest(body: string, contentType = "application/json"): Request {
- return new Request("http://localhost/test", {
- method: "POST",
- headers: { "content-type": contentType },
- body,
- });
-}
-
-describe("validatedJsonBody", () => {
- const schema = z.object({
- name: z.string().min(1),
- count: z.number().int().nonnegative(),
- });
-
- test("returns the parsed and validated data on success", async () => {
- const result = await validatedJsonBody(makeRequest('{"name":"hello","count":3}'), schema);
- assert.equal(result.success, true);
- if (result.success) {
- assert.deepEqual(result.data, { name: "hello", count: 3 });
- }
- });
-
- test("returns a 400 with structured details when the body fails Zod validation", async () => {
- const result = await validatedJsonBody(makeRequest('{"name":"","count":-1}'), schema);
- assert.equal(result.success, false);
- if (!result.success) {
- assert.equal(result.response.status, 400);
- const body = await result.response.json();
- assert.equal(body.error.message, "Invalid request");
- assert.ok(Array.isArray(body.error.details));
- const fields = body.error.details.map((d: { field: string }) => d.field);
- assert.ok(fields.includes("name"));
- assert.ok(fields.includes("count"));
- }
- });
-
- test("returns a 400 with a body-parse failure for malformed JSON", async () => {
- const result = await validatedJsonBody(makeRequest("not json at all"), schema);
- assert.equal(result.success, false);
- if (!result.success) {
- assert.equal(result.response.status, 400);
- const body = await result.response.json();
- assert.deepEqual(body, {
- error: {
- message: "Invalid request",
- details: [{ field: "body", message: "Invalid JSON body" }],
- },
- });
- }
- });
-
- test("returns a 400 for an empty body", async () => {
- const result = await validatedJsonBody(makeRequest(""), schema);
- assert.equal(result.success, false);
- if (!result.success) {
- assert.equal(result.response.status, 400);
- }
- });
-
- test("returns a 400 when required fields are missing entirely", async () => {
- const result = await validatedJsonBody(makeRequest("{}"), schema);
- assert.equal(result.success, false);
- if (!result.success) {
- assert.equal(result.response.status, 400);
- const body = await result.response.json();
- const fields = body.error.details.map((d: { field: string }) => d.field);
- assert.ok(fields.includes("name"));
- assert.ok(fields.includes("count"));
- }
- });
-
- test("preserves the same envelope shape between parse and validate failure", async () => {
- const parseFailure = await validatedJsonBody(makeRequest("nope"), schema);
- const validateFailure = await validatedJsonBody(makeRequest("{}"), schema);
- assert.equal(parseFailure.success, false);
- assert.equal(validateFailure.success, false);
- if (!parseFailure.success && !validateFailure.success) {
- const parseBody = await parseFailure.response.json();
- const validateBody = await validateFailure.response.json();
- assert.equal(typeof parseBody.error.message, "string");
- assert.equal(typeof validateBody.error.message, "string");
- assert.ok(Array.isArray(parseBody.error.details));
- assert.ok(Array.isArray(validateBody.error.details));
- }
- });
-});
diff --git a/tests/unit/audio-translations-route.test.ts b/tests/unit/audio-translations-route.test.ts
deleted file mode 100644
index 42cd481b59..0000000000
--- a/tests/unit/audio-translations-route.test.ts
+++ /dev/null
@@ -1,199 +0,0 @@
-import test from "node:test";
-import assert from "node:assert/strict";
-
-const { handleAudioTranslation } = await import("../../open-sse/handlers/audioTranslation.ts");
-
-function buildFile(contents, name, type) {
- return new File([Buffer.from(contents)], name, { type });
-}
-
-test("handleAudioTranslation requires model", async () => {
- const formData = new FormData();
- formData.append("file", buildFile("abc", "audio.wav", "audio/wav"));
-
- const response = await handleAudioTranslation({ formData, credentials: { apiKey: "x" } });
- const payload = (await response.json()) as any;
-
- assert.equal(response.status, 400);
- assert.equal(payload.error.message, "model is required");
-});
-
-test("handleAudioTranslation requires a file upload", async () => {
- const formData = new FormData();
- formData.append("model", "openai/whisper-1");
-
- const response = await handleAudioTranslation({ formData, credentials: { apiKey: "x" } });
- const payload = (await response.json()) as any;
-
- assert.equal(response.status, 400);
- assert.equal(payload.error.message, "file is required");
-});
-
-test("handleAudioTranslation requires credentials for authenticated providers", async () => {
- const formData = new FormData();
- formData.append("model", "openai/whisper-1");
- formData.append("file", buildFile("abc", "clip.wav", "audio/wav"));
-
- const response = await handleAudioTranslation({ formData, credentials: null });
- const payload = (await response.json()) as any;
-
- assert.equal(response.status, 401);
- assert.equal(payload.error.message, "No credentials for translation provider: openai");
-});
-
-test("handleAudioTranslation rejects unsupported providers", async () => {
- const formData = new FormData();
- formData.append("model", "unknown/provider");
- formData.append("file", buildFile("abc", "clip.wav", "audio/wav"));
-
- const response = await handleAudioTranslation({
- formData,
- credentials: { apiKey: "x" },
- });
- const payload = (await response.json()) as any;
-
- assert.equal(response.status, 400);
- assert.match(payload.error.message, /No translation provider found for model "unknown\/provider"/);
-});
-
-test("handleAudioTranslation dispatches OpenAI-compatible multipart requests and returns { text }", async () => {
- const originalFetch = globalThis.fetch;
- let captured;
-
- globalThis.fetch = async (url, options = {}) => {
- captured = {
- url: String(url),
- headers: options.headers,
- body: options.body,
- };
-
- return new Response(JSON.stringify({ text: "hello world" }), {
- status: 200,
- headers: { "content-type": "application/json" },
- });
- };
-
- try {
- const formData = new FormData();
- formData.append("model", "openai/whisper-1");
- formData.append("file", buildFile("abc", "clip.webm", "audio/webm"));
- formData.append("prompt", "greeting");
- formData.append("response_format", "json");
- formData.append("temperature", "0.2");
- // Translation always outputs English — a caller-supplied `language` must
- // NOT be forwarded upstream (differs from /v1/audio/transcriptions).
- formData.append("language", "pt");
-
- const response = await handleAudioTranslation({
- formData,
- credentials: { apiKey: "openai-key" },
- });
-
- assert.equal(response.status, 200);
- assert.equal(captured.url, "https://api.openai.com/v1/audio/translations");
- assert.equal(captured.headers.Authorization, "Bearer openai-key");
- assert.match(captured.headers["Content-Type"], /^multipart\/form-data; boundary=/);
-
- const bodyText = new TextDecoder().decode(captured.body);
- assert.ok(bodyText.includes('name="model"'));
- assert.ok(bodyText.includes("whisper-1"));
- assert.ok(bodyText.includes('name="prompt"'));
- assert.ok(bodyText.includes("greeting"));
- assert.ok(bodyText.includes('name="response_format"'));
- assert.ok(bodyText.includes('name="temperature"'));
- assert.ok(bodyText.includes("0.2"));
- assert.ok(bodyText.includes('name="file"'));
- assert.ok(bodyText.includes('filename="clip.webm"'));
- assert.ok(!bodyText.includes('name="language"'));
-
- assert.deepEqual(await response.json(), { text: "hello world" });
- } finally {
- globalThis.fetch = originalFetch;
- }
-});
-
-test("handleAudioTranslation dispatches Groq-compatible multipart requests", async () => {
- const originalFetch = globalThis.fetch;
- let captured;
-
- globalThis.fetch = async (url, options = {}) => {
- captured = { url: String(url), headers: options.headers };
- return new Response(JSON.stringify({ text: "bonjour" }), {
- status: 200,
- headers: { "content-type": "application/json" },
- });
- };
-
- try {
- const formData = new FormData();
- formData.append("model", "groq/whisper-large-v3");
- formData.append("file", buildFile("abc", "clip.wav", "audio/wav"));
-
- const response = await handleAudioTranslation({
- formData,
- credentials: { apiKey: "groq-key" },
- });
-
- assert.equal(response.status, 200);
- assert.equal(captured.url, "https://api.groq.com/openai/v1/audio/translations");
- assert.equal(captured.headers.Authorization, "Bearer groq-key");
- assert.deepEqual(await response.json(), { text: "bonjour" });
- } finally {
- globalThis.fetch = originalFetch;
- }
-});
-
-test("handleAudioTranslation surfaces parsed upstream errors without leaking internals", async () => {
- const originalFetch = globalThis.fetch;
-
- globalThis.fetch = async () =>
- new Response(JSON.stringify({ error: { message: "too many requests" } }), {
- status: 429,
- headers: { "content-type": "application/json" },
- });
-
- try {
- const formData = new FormData();
- formData.append("model", "openai/whisper-1");
- formData.append("file", buildFile("abc", "clip.wav", "audio/wav"));
-
- const response = await handleAudioTranslation({
- formData,
- credentials: { apiKey: "openai-key" },
- });
- const payload = (await response.json()) as any;
-
- assert.equal(response.status, 429);
- assert.equal(payload.error.message, "too many requests");
- assert.ok(!payload.error.message.includes("at /"));
- } finally {
- globalThis.fetch = originalFetch;
- }
-});
-
-test("handleAudioTranslation sanitizes stack-trace-shaped messages on fetch failure", async () => {
- const originalFetch = globalThis.fetch;
-
- globalThis.fetch = async () => {
- throw new Error("Fetch failed at /home/user/project/src/secure.ts:10:5");
- };
-
- try {
- const formData = new FormData();
- formData.append("model", "openai/whisper-1");
- formData.append("file", buildFile("abc", "clip.wav", "audio/wav"));
-
- const response = await handleAudioTranslation({
- formData,
- credentials: { apiKey: "openai-key" },
- });
- const payload = (await response.json()) as any;
-
- assert.equal(response.status, 500);
- // Rule: error responses must never leak absolute source paths / stack traces.
- assert.ok(!payload.error.message.includes("at /"));
- assert.ok(!payload.error.message.includes("secure.ts"));
- } finally {
- globalThis.fetch = originalFetch;
- }
-});
diff --git a/tests/unit/auggie-executor.test.ts b/tests/unit/auggie-executor.test.ts
deleted file mode 100644
index c5418ac546..0000000000
--- a/tests/unit/auggie-executor.test.ts
+++ /dev/null
@@ -1,380 +0,0 @@
-/**
- * AuggieExecutor unit tests.
- *
- * Rather than mocking node:child_process (fragile under ESM without
- * --experimental-vm-modules — see tests/unit/dns-config-generic.test.ts for the
- * same tradeoff), these tests point `AUGGIE_BIN` at small real, disposable shell
- * scripts that stand in for the `auggie` CLI. No live `auggie` binary is required
- * or touched — CI never needs the real Augment CLI installed.
- */
-
-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 { AuggieExecutor, buildAuggiePrompt, resolveAuggieBin, resolveAuggieModel } = await import(
- "@omniroute/open-sse/executors/auggie"
-);
-
-const TMP_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-auggie-test-"));
-
-/** Write an executable shell script and return its absolute path. */
-function writeFakeBin(name: string, script: string): string {
- const p = path.join(TMP_DIR, name);
- fs.writeFileSync(p, `#!/bin/sh\n${script}\n`, { mode: 0o755 });
- return p;
-}
-
-
-async function readSseEvents(response: Response): Promise<Record<string, unknown>[]> {
- const text = await response.text();
- const events: Record<string, unknown>[] = [];
- for (const line of text.split("\n")) {
- if (!line.startsWith("data: ")) continue;
- const payload = line.slice("data: ".length).trim();
- if (payload === "[DONE]") continue;
- events.push(JSON.parse(payload));
- }
- return events;
-}
-
-test.after(() => {
- fs.rmSync(TMP_DIR, { recursive: true, force: true });
-});
-
-// ─── buildAuggiePrompt ────────────────────────────────────────────────────
-
-test("buildAuggiePrompt flattens system/user/assistant turns with role tags", () => {
- const prompt = buildAuggiePrompt([
- { role: "system", content: "Be terse." },
- { role: "user", content: "hi" },
- { role: "assistant", content: "hello" },
- { role: "user", content: "how are you?" },
- ]);
- assert.equal(
- prompt,
- "[System]\nBe terse.\n\n[User]\nhi\n\n[Assistant]\nhello\n\n[User]\nhow are you?"
- );
-});
-
-test("buildAuggiePrompt flattens array-shaped content blocks and skips empty turns", () => {
- const prompt = buildAuggiePrompt([
- { role: "user", content: [{ type: "text", text: "part1 " }, { type: "text", text: "part2" }] },
- { role: "user", content: "" },
- { role: "user", content: [] },
- ]);
- assert.equal(prompt, "[User]\npart1 part2");
-});
-
-test("buildAuggiePrompt returns a placeholder for an empty conversation", () => {
- assert.equal(buildAuggiePrompt([]), "(empty)");
-});
-
-// ─── resolveAuggieBin ─────────────────────────────────────────────────────
-
-test("resolveAuggieBin honors AUGGIE_BIN env override", () => {
- const prev = process.env.AUGGIE_BIN;
- try {
- process.env.AUGGIE_BIN = "/custom/path/to/auggie";
- assert.equal(resolveAuggieBin(), "/custom/path/to/auggie");
- } finally {
- if (prev === undefined) delete process.env.AUGGIE_BIN;
- else process.env.AUGGIE_BIN = prev;
- }
-});
-
-// ─── execute(): ENOENT → CLI not found ─────────────────────────────────────
-
-test("execute() surfaces a sanitized 'CLI not found' error on ENOENT (streaming)", async () => {
- const prevBin = process.env.AUGGIE_BIN;
- process.env.AUGGIE_BIN = path.join(TMP_DIR, "does-not-exist-binary");
- try {
- const executor = new AuggieExecutor();
- const { response } = await executor.execute({
- model: "claude-sonnet-4.6",
- body: { messages: [{ role: "user", content: "hi" }] },
- stream: true,
- credentials: {} as never,
- });
- assert.equal(response.headers.get("Content-Type"), "text/event-stream");
- const events = await readSseEvents(response);
- const errorEvent = events.find((e) => (e as any).error);
- assert.ok(errorEvent, "expected an error SSE event");
- const message = String((errorEvent as any).error.message);
- // The configured bin path is intentionally included (actionable for the
- // operator) — sanitizeErrorMessage only strips stack-trace-shaped source
- // paths (`*.ts`/`*.js` + line:col), not arbitrary CLI binary paths.
- assert.match(message, /Auggie CLI not found/);
- assert.equal(message.includes("\n"), false, "message must not contain a stack trace");
- } finally {
- if (prevBin === undefined) delete process.env.AUGGIE_BIN;
- else process.env.AUGGIE_BIN = prevBin;
- }
-});
-
-test("execute() surfaces a sanitized 'CLI not found' error on ENOENT (non-streaming)", async () => {
- const prevBin = process.env.AUGGIE_BIN;
- process.env.AUGGIE_BIN = path.join(TMP_DIR, "does-not-exist-binary-2");
- try {
- const executor = new AuggieExecutor();
- const { response } = await executor.execute({
- model: "claude-sonnet-4.6",
- body: { messages: [{ role: "user", content: "hi" }] },
- stream: false,
- credentials: {} as never,
- });
- assert.equal(response.headers.get("Content-Type"), "application/json");
- assert.equal(response.status, 502);
- const body = await response.json();
- assert.match(String(body.error.message), /Auggie CLI not found/);
- } finally {
- if (prevBin === undefined) delete process.env.AUGGIE_BIN;
- else process.env.AUGGIE_BIN = prevBin;
- }
-});
-
-// ─── execute(): non-zero exit → sanitized error ────────────────────────────
-
-test("execute() surfaces a sanitized error when the CLI exits non-zero (streaming)", async () => {
- const bin = writeFakeBin("fake-auggie-fail.sh", 'echo "boom at /home/attacker/secret.ts:42" 1>&2\nexit 3');
- const prevBin = process.env.AUGGIE_BIN;
- process.env.AUGGIE_BIN = bin;
- try {
- const executor = new AuggieExecutor();
- const { response } = await executor.execute({
- model: "claude-sonnet-4.6",
- body: { messages: [{ role: "user", content: "hi" }] },
- stream: true,
- credentials: {} as never,
- });
- const events = await readSseEvents(response);
- const errorEvent = events.find((e) => (e as any).error);
- assert.ok(errorEvent, "expected an error SSE event");
- const message = String((errorEvent as any).error.message);
- assert.match(message, /exited with code 3/);
- assert.equal(message.includes("/home/attacker/secret.ts"), false, "path must be sanitized");
- } finally {
- if (prevBin === undefined) delete process.env.AUGGIE_BIN;
- else process.env.AUGGIE_BIN = prevBin;
- }
-});
-
-test("execute() surfaces a sanitized error when the CLI exits non-zero (non-streaming)", async () => {
- const bin = writeFakeBin("fake-auggie-fail2.sh", "exit 1");
- const prevBin = process.env.AUGGIE_BIN;
- process.env.AUGGIE_BIN = bin;
- try {
- const executor = new AuggieExecutor();
- const { response } = await executor.execute({
- model: "claude-sonnet-4.6",
- body: { messages: [{ role: "user", content: "hi" }] },
- stream: false,
- credentials: {} as never,
- });
- assert.equal(response.status, 502);
- const body = await response.json();
- assert.match(String(body.error.message), /exited with code 1/);
- } finally {
- if (prevBin === undefined) delete process.env.AUGGIE_BIN;
- else process.env.AUGGIE_BIN = prevBin;
- }
-});
-
-// ─── execute(): stream vs non-stream shape ─────────────────────────────────
-
-test("execute() with stream=true returns SSE deltas + [DONE]", async () => {
- const bin = writeFakeBin("fake-auggie-echo.sh", 'printf "hello world"');
- const prevBin = process.env.AUGGIE_BIN;
- process.env.AUGGIE_BIN = bin;
- try {
- const executor = new AuggieExecutor();
- const { response } = await executor.execute({
- model: "claude-sonnet-4.6",
- body: { messages: [{ role: "user", content: "say hi" }] },
- stream: true,
- credentials: {} as never,
- });
- assert.equal(response.headers.get("Content-Type"), "text/event-stream");
- const events = await readSseEvents(response);
- // First chunk announces the assistant role.
- assert.equal((events[0] as any).choices[0].delta.role, "assistant");
- // Content is streamed as delta chunks that concatenate to the full text.
- const contentDeltas = events
- .map((e) => (e as any).choices?.[0]?.delta?.content)
- .filter((c) => typeof c === "string");
- assert.equal(contentDeltas.join(""), "hello world");
- // Final chunk signals completion.
- const last = events[events.length - 1] as any;
- assert.equal(last.choices[0].finish_reason, "stop");
- } finally {
- if (prevBin === undefined) delete process.env.AUGGIE_BIN;
- else process.env.AUGGIE_BIN = prevBin;
- }
-});
-
-test("execute() with stream=false returns a single chat.completion JSON body", async () => {
- const bin = writeFakeBin("fake-auggie-echo2.sh", 'printf "hello world"');
- const prevBin = process.env.AUGGIE_BIN;
- process.env.AUGGIE_BIN = bin;
- try {
- const executor = new AuggieExecutor();
- const { response } = await executor.execute({
- model: "claude-sonnet-4.6",
- body: { messages: [{ role: "user", content: "say hi" }] },
- stream: false,
- credentials: {} as never,
- });
- assert.equal(response.headers.get("Content-Type"), "application/json");
- assert.equal(response.status, 200);
- const body = await response.json();
- assert.equal(body.object, "chat.completion");
- assert.equal(body.choices[0].message.role, "assistant");
- assert.equal(body.choices[0].message.content, "hello world");
- assert.equal(body.choices[0].finish_reason, "stop");
- assert.ok(body.usage);
- } finally {
- if (prevBin === undefined) delete process.env.AUGGIE_BIN;
- else process.env.AUGGIE_BIN = prevBin;
- }
-});
-
-// ─── resolveAuggieModel ─────────────────────────────────────────────────────
-
-test("resolveAuggieModel defaults to a real allowlisted model when unset", () => {
- const result = resolveAuggieModel(undefined);
- assert.equal(result.ok, true);
- if (result.ok) assert.equal(typeof result.model, "string");
-});
-
-test("resolveAuggieModel accepts a known registry model id verbatim", () => {
- const result = resolveAuggieModel("claude-haiku-4.5");
- assert.deepEqual(result, { ok: true, model: "claude-haiku-4.5" });
-});
-
-// ─── execute(): model allowlist (argument-injection defense) ──────────────
-
-test("execute() rejects a model not in the registry allowlist and never spawns", async () => {
- const marker = path.join(TMP_DIR, "spawned-unknown-model.marker");
- const bin = writeFakeBin("fake-auggie-unknown.sh", `touch "${marker}"\nprintf "hi"`);
- const prevBin = process.env.AUGGIE_BIN;
- process.env.AUGGIE_BIN = bin;
- try {
- const executor = new AuggieExecutor();
- const { response } = await executor.execute({
- model: "totally-not-a-real-model",
- body: { messages: [{ role: "user", content: "hi" }] },
- stream: false,
- credentials: {} as never,
- });
- assert.equal(response.status, 400);
- const body = await response.json();
- assert.match(String(body.error.message), /Unknown Auggie model/);
- assert.equal(fs.existsSync(marker), false, "subprocess must never be spawned");
- } finally {
- if (prevBin === undefined) delete process.env.AUGGIE_BIN;
- else process.env.AUGGIE_BIN = prevBin;
- }
-});
-
-test("execute() rejects a model starting with '-' (flag smuggling) and never spawns (streaming)", async () => {
- const marker = path.join(TMP_DIR, "spawned-flag-smuggle.marker");
- const bin = writeFakeBin("fake-auggie-flag.sh", `touch "${marker}"\nprintf "hi"`);
- const prevBin = process.env.AUGGIE_BIN;
- process.env.AUGGIE_BIN = bin;
- try {
- const executor = new AuggieExecutor();
- const { response } = await executor.execute({
- model: "-rf",
- body: { messages: [{ role: "user", content: "hi" }] },
- stream: true,
- credentials: {} as never,
- });
- assert.equal(response.headers.get("Content-Type"), "text/event-stream");
- const events = await readSseEvents(response);
- const errorEvent = events.find((e) => (e as any).error);
- assert.ok(errorEvent, "expected an error SSE event");
- assert.match(String((errorEvent as any).error.message), /must not start with "-"/);
- assert.equal(fs.existsSync(marker), false, "subprocess must never be spawned");
- } finally {
- if (prevBin === undefined) delete process.env.AUGGIE_BIN;
- else process.env.AUGGIE_BIN = prevBin;
- }
-});
-
-test("execute() spawns with a valid allowlisted model, no shell, and a '--' argv separator", async () => {
- const argvFile = path.join(TMP_DIR, "captured-argv.txt");
- const bin = writeFakeBin(
- "fake-auggie-argv.sh",
- `for a in "$@"; do printf '%s\\n' "$a" >> "${argvFile}"; done\nprintf "ok"`
- );
- const prevBin = process.env.AUGGIE_BIN;
- process.env.AUGGIE_BIN = bin;
- try {
- const executor = new AuggieExecutor();
- const { response } = await executor.execute({
- model: "claude-opus-4.6",
- body: { messages: [{ role: "user", content: "hi" }] },
- stream: false,
- credentials: {} as never,
- });
- assert.equal(response.status, 200);
- const body = await response.json();
- assert.equal(body.choices[0].message.content, "ok");
- const argv = fs.readFileSync(argvFile, "utf8").trim().split("\n");
- assert.deepEqual(argv, ["--print", "--quiet", "--model", "claude-opus-4.6", "--"]);
- } finally {
- if (prevBin === undefined) delete process.env.AUGGIE_BIN;
- else process.env.AUGGIE_BIN = prevBin;
- fs.rmSync(argvFile, { force: true });
- }
-});
-
-// ─── execute(): abort kills the subprocess promptly ────────────────────────
-
-test("execute() aborts a long-running CLI process instead of hanging (streaming)", async () => {
- // Sleeps far longer than the test timeout unless killed on abort.
- const bin = writeFakeBin("fake-auggie-sleep.sh", "sleep 30");
- const prevBin = process.env.AUGGIE_BIN;
- process.env.AUGGIE_BIN = bin;
- try {
- const executor = new AuggieExecutor();
- const controller = new AbortController();
- const { response } = await executor.execute({
- model: "claude-sonnet-4.6",
- body: { messages: [{ role: "user", content: "hi" }] },
- stream: true,
- credentials: {} as never,
- signal: controller.signal,
- });
- // Give the child process a beat to spawn, then abort.
- await new Promise((resolve) => setTimeout(resolve, 100));
- controller.abort();
-
- // Reading the stream must resolve promptly (i.e. the stream closes) rather
- // than hanging for the full 30s sleep.
- const start = Date.now();
- await response.text();
- const elapsed = Date.now() - start;
- assert.ok(elapsed < 5000, `expected abort to close the stream quickly, took ${elapsed}ms`);
- } finally {
- if (prevBin === undefined) delete process.env.AUGGIE_BIN;
- else process.env.AUGGIE_BIN = prevBin;
- }
-});
-
-// ─── refreshCredentials() is a no-op ────────────────────────────────────────
-
-test("refreshCredentials() is a no-op (auggie has no OmniRoute-managed credentials)", async () => {
- const executor = new AuggieExecutor();
- const result = await executor.refreshCredentials({} as never);
- assert.equal(result, null);
-});
-
-test("buildUrl/buildHeaders/transformRequest match the CLI-passthrough shape", () => {
- const executor = new AuggieExecutor();
- assert.equal(executor.buildUrl(), "auggie://cli/stdio");
- assert.deepEqual(executor.buildHeaders(), {});
- assert.equal(executor.transformRequest(), null);
-});
diff --git a/tests/unit/authz/discovery-routes-local-only.test.ts b/tests/unit/authz/discovery-routes-local-only.test.ts
deleted file mode 100644
index ceea7f7dbc..0000000000
--- a/tests/unit/authz/discovery-routes-local-only.test.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { describe, test } from "node:test";
-import assert from "node:assert/strict";
-import {
- isLocalOnlyPath,
- isLocalOnlyBypassableByManageScope,
-} from "@/server/authz/routeGuard";
-
-// Security guard: the discovery surface must be strict-loopback only. If someone
-// removes "/api/discovery/" from LOCAL_ONLY_API_PREFIXES, or adds it to the
-// manage-scope bypass list, these assertions fail — the scan route makes
-// outbound probes (SSRF-adjacent) and must never be tunnel-reachable.
-describe("discovery routes are strict local-only", () => {
- for (const path of [
- "/api/discovery/results",
- "/api/discovery/results/42",
- "/api/discovery/scan",
- "/api/discovery/verify/42",
- ]) {
- test(`isLocalOnlyPath("${path}") === true`, () => {
- assert.equal(isLocalOnlyPath(path), true);
- });
-
- test(`"${path}" is NOT bypassable by manage-scope (strict loopback)`, () => {
- assert.equal(isLocalOnlyBypassableByManageScope(path), false);
- });
- }
-});
diff --git a/tests/unit/authz/pipeline.test.ts b/tests/unit/authz/pipeline.test.ts
index 2b43287911..18d90b12d8 100644
--- a/tests/unit/authz/pipeline.test.ts
+++ b/tests/unit/authz/pipeline.test.ts
@@ -138,50 +138,6 @@ test("runAuthzPipeline redirects unauthenticated /home/* nested paths to login (
assert.equal(response.headers.get("x-omniroute-route-class"), "MANAGEMENT");
});
-// PR #1810 (upstream 9router): reverse-proxy subpath deployment via
-// OMNIROUTE_BASE_PATH. Next.js strips the basePath from nextUrl.pathname
-// before route classification, so the redirect targets must re-add it via
-// request.nextUrl.basePath to stay inside the deployed subpath.
-test("runAuthzPipeline prefixes the root-to-dashboard redirect with basePath when set", async () => {
- await forceAuthRequired();
-
- const req = new NextRequest("http://localhost/omniroute/", {
- nextConfig: { basePath: "/omniroute" },
- });
-
- const response = await pipeline.runAuthzPipeline(req, { enforce: true });
-
- assert.equal(response.status, 307);
- assert.equal(response.headers.get("location"), "http://localhost/omniroute/dashboard");
-});
-
-test("runAuthzPipeline prefixes the dashboard login redirect with basePath when set", async () => {
- await forceAuthRequired();
-
- const req = new NextRequest("http://localhost/omniroute/dashboard", {
- nextConfig: { basePath: "/omniroute" },
- });
-
- const response = await pipeline.runAuthzPipeline(req, { enforce: true });
-
- assert.equal(response.status, 307);
- assert.equal(response.headers.get("location"), "http://localhost/omniroute/login");
- assert.equal(response.headers.get("x-omniroute-route-class"), "MANAGEMENT");
-});
-
-test("runAuthzPipeline leaves redirect targets unprefixed when basePath is empty", async () => {
- await forceAuthRequired();
-
- const req = new NextRequest("http://localhost/dashboard", {
- nextConfig: { basePath: "" },
- });
-
- const response = await pipeline.runAuthzPipeline(req, { enforce: true });
-
- assert.equal(response.status, 307);
- assert.equal(response.headers.get("location"), "http://localhost/login");
-});
-
test("runAuthzPipeline allows onboarding when login is required but no password exists", async () => {
delete process.env.INITIAL_PASSWORD;
await settingsDb.updateSettings({
diff --git a/tests/unit/authz/routeGuard.test.ts b/tests/unit/authz/routeGuard.test.ts
index 2a4fd3799c..5a79bfa2ff 100644
--- a/tests/unit/authz/routeGuard.test.ts
+++ b/tests/unit/authz/routeGuard.test.ts
@@ -189,25 +189,6 @@ test("isLocalOnlyBypassableByManageScope: /api/services/* is NOT bypassable (spa
assert.equal(isLocalOnlyBypassableByManageScope("/api/services/"), false);
});
-// Hard Rule #17 — Mux (coder/mux) embedded service (spawns child processes via
-// runNpm install + node server spawn): every /api/services/mux/* route MUST be
-// classified local-only, same as every other embedded service under this prefix.
-test("isLocalOnlyPath: /api/services/mux/* is local-only (Hard Rule #17)", () => {
- assert.equal(isLocalOnlyPath("/api/services/mux/install"), true);
- assert.equal(isLocalOnlyPath("/api/services/mux/start"), true);
- assert.equal(isLocalOnlyPath("/api/services/mux/stop"), true);
- assert.equal(isLocalOnlyPath("/api/services/mux/restart"), true);
- assert.equal(isLocalOnlyPath("/api/services/mux/update"), true);
- assert.equal(isLocalOnlyPath("/api/services/mux/status"), true);
- assert.equal(isLocalOnlyPath("/api/services/mux/auto-start"), true);
- assert.equal(isLocalOnlyPath("/api/services/mux/logs"), true);
-});
-
-test("isLocalOnlyBypassableByManageScope: /api/services/mux/* is NOT bypassable (spawn-capable)", () => {
- assert.equal(isLocalOnlyBypassableByManageScope("/api/services/mux/start"), false);
- assert.equal(isLocalOnlyBypassableByManageScope("/api/services/mux/install"), false);
-});
-
test("management policy rejects /api/services/ from non-localhost (status 403)", async () => {
const ctx = makeCtx("/api/services/9router/start", { host: "evil.tunnel.io" });
const outcome = await managementPolicy.evaluate(ctx);
diff --git a/tests/unit/bai-provider.test.ts b/tests/unit/bai-provider.test.ts
deleted file mode 100644
index 3669d53998..0000000000
--- a/tests/unit/bai-provider.test.ts
+++ /dev/null
@@ -1,159 +0,0 @@
-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 { APIKEY_PROVIDERS } = await import("../../src/shared/constants/providers.ts");
-const { PROVIDER_ENDPOINTS } = await import("../../src/shared/constants/config.ts");
-const { REGISTRY: providerRegistry } = await import("../../open-sse/config/providerRegistry.ts");
-const { isValidModel } = await import("../../src/shared/constants/models.ts");
-
-const BAI_CHAT_URL = "https://api.b.ai/v1/chat/completions";
-const BAI_MODELS_URL = "https://api.b.ai/v1/models";
-
-test("b.ai is registered as an API-key provider", () => {
- const entry = APIKEY_PROVIDERS.bai;
- assert.ok(entry, "APIKEY_PROVIDERS.bai must be defined");
- assert.equal(entry.id, "bai");
- assert.equal(entry.alias, "bai");
- assert.equal(entry.name, "b.ai");
- assert.equal(entry.website, "https://b.ai");
- assert.equal(entry.passthroughModels, true);
-});
-
-test("b.ai is distinct from the existing thebai (TheB.AI) provider", () => {
- const bai = APIKEY_PROVIDERS.bai;
- const thebai = APIKEY_PROVIDERS.thebai;
- assert.ok(bai, "APIKEY_PROVIDERS.bai must be defined");
- assert.ok(thebai, "APIKEY_PROVIDERS.thebai must be defined");
- assert.notEqual(bai.id, thebai.id);
- assert.notEqual(bai.website, thebai.website);
- assert.equal(bai.website, "https://b.ai");
- assert.equal(thebai.website, "https://theb.ai");
-});
-
-test("b.ai exposes the OpenAI-compatible chat completions endpoint", () => {
- assert.equal(PROVIDER_ENDPOINTS.bai, BAI_CHAT_URL);
-});
-
-test("b.ai registry entry uses OpenAI format with bearer API-key auth", () => {
- const entry = providerRegistry.bai;
- assert.ok(entry, "providerRegistry.bai must be defined");
- assert.equal(entry.id, "bai");
- assert.equal(entry.alias, "bai");
- assert.equal(entry.format, "openai");
- assert.equal(entry.executor, "default");
- assert.equal(entry.authType, "apikey");
- assert.equal(entry.authHeader, "bearer");
- assert.equal(entry.baseUrl, BAI_CHAT_URL);
- assert.equal(entry.modelsUrl, BAI_MODELS_URL);
- assert.equal(entry.passthroughModels, true);
-});
-
-test("b.ai ships no static model seed — relies fully on passthrough + live catalog", () => {
- const models = providerRegistry.bai.models;
- assert.deepEqual(models, []);
-});
-
-test("b.ai accepts any model id via passthrough models (GPT/Claude/Gemini/Kimi/GLM behind one key)", () => {
- assert.equal(isValidModel("bai", "gpt-5.2"), true);
- assert.equal(isValidModel("bai", "claude-opus-4-5"), true);
- assert.equal(isValidModel("bai", "gemini-3-pro"), true);
- assert.equal(isValidModel("bai", "kimi-k2.5"), true);
-});
-
-const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-bai-"));
-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 modelsRoute = await import("../../src/app/api/providers/[id]/models/route.ts");
-
-async function resetStorage() {
- core.resetDbInstance();
- fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
- fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
-}
-
-test.after(() => {
- core.resetDbInstance();
- fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
-});
-
-interface ModelsBody {
- provider: string;
- connectionId: string;
- models: Array<{ id: string }>;
- source?: string;
-}
-
-test("b.ai import fetches the live /v1/models catalog", async () => {
- await resetStorage();
- const connection = await providersDb.createProviderConnection({
- provider: "bai",
- authType: "apikey",
- name: "bai-live",
- apiKey: "bai-key",
- });
-
- let fetched = false;
- const originalFetch = globalThis.fetch;
- globalThis.fetch = async (url) => {
- if (String(url) === BAI_MODELS_URL) {
- fetched = true;
- return Response.json({
- object: "list",
- data: [{ id: "gpt-5.2" }, { id: "claude-opus-4-5" }, { id: "kimi-k2.5" }],
- });
- }
- return new Response("not found", { status: 404 });
- };
-
- try {
- const response = await modelsRoute.GET(
- new Request(`http://localhost/api/providers/${connection.id}/models?refresh=true`),
- { params: { id: connection.id } }
- );
- assert.equal(response.status, 200);
- const body = (await response.json()) as ModelsBody;
- assert.equal(body.provider, "bai");
- assert.equal(body.source, "api", "should serve the live upstream catalog");
- assert.ok(fetched, `should have probed ${BAI_MODELS_URL}`);
- const ids = body.models.map((model) => model.id);
- assert.ok(ids.includes("gpt-5.2"), `live catalog model missing: ${ids.join(",")}`);
- assert.ok(ids.includes("kimi-k2.5"), `live catalog model missing: ${ids.join(",")}`);
- } finally {
- globalThis.fetch = originalFetch;
- }
-});
-
-test("b.ai import falls back to an empty local catalog when live fetch fails", async () => {
- await resetStorage();
- const connection = await providersDb.createProviderConnection({
- provider: "bai",
- authType: "apikey",
- name: "bai-fallback",
- apiKey: "bai-key-2",
- });
-
- const originalFetch = globalThis.fetch;
- globalThis.fetch = async () => new Response("bad gateway", { status: 502 });
-
- try {
- const response = await modelsRoute.GET(
- new Request(`http://localhost/api/providers/${connection.id}/models?refresh=true`),
- { params: { id: connection.id } }
- );
- assert.equal(response.status, 200);
- const body = (await response.json()) as ModelsBody;
- assert.equal(body.provider, "bai");
- assert.equal(body.source, "local_catalog", "import must not break when upstream is down");
- assert.deepEqual(
- body.models.map((model) => model.id),
- []
- );
- } finally {
- globalThis.fetch = originalFetch;
- }
-});
diff --git a/tests/unit/base-headers-split.test.ts b/tests/unit/base-headers-split.test.ts
deleted file mode 100644
index 7fe9106ada..0000000000
--- a/tests/unit/base-headers-split.test.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import { test } from "node:test";
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { fileURLToPath } from "node:url";
-import { dirname, join } from "node:path";
-
-// Split-guard for the base executor header-helper extraction.
-// The pure upstream-header helpers live in base/headers.ts (no host state, no fetch).
-// base.ts re-exports all 6 so the ~18 executors + tests that import them from "./base.ts"
-// keep resolving unchanged.
-const HERE = dirname(fileURLToPath(import.meta.url));
-const EXE = join(HERE, "../../open-sse/executors");
-const HOST = join(EXE, "base.ts");
-const LEAF = join(EXE, "base/headers.ts");
-
-test("leaf hosts the header helpers and does not import the host", () => {
- const src = readFileSync(LEAF, "utf8");
- for (const sym of [
- "mergeUpstreamExtraHeaders",
- "setUserAgentHeader",
- "isOpenAICompatibleEndpoint",
- "stripStainlessHeadersForOpenAICompat",
- ]) {
- assert.match(src, new RegExp(`export function ${sym}\\b`));
- }
- assert.doesNotMatch(src, /from "\.\.\/base\.ts"/);
-});
-
-test("host re-exports all 6 header helpers for external importers", () => {
- const host = readFileSync(HOST, "utf8");
- for (const sym of [
- "mergeUpstreamExtraHeaders",
- "getCustomUserAgent",
- "setUserAgentHeader",
- "applyConfiguredUserAgent",
- "isOpenAICompatibleEndpoint",
- "stripStainlessHeadersForOpenAICompat",
- ]) {
- assert.match(host, new RegExp(`\\b${sym}\\b`));
- }
- assert.match(host, /from "\.\/base\/headers\.ts"/);
-});
-
-test("header helpers behave via base.ts (the public import path)", async () => {
- const mod = await import("../../open-sse/executors/base.ts");
- assert.equal(mod.isOpenAICompatibleEndpoint("openai-compatible-x", "https://x/y"), true);
- const headers: Record<string, string> = { "x-stainless-lang": "js", "User-Agent": "openai-node" };
- const stripped = mod.stripStainlessHeadersForOpenAICompat(
- headers,
- "openai-compatible-x",
- "https://x/v1/chat/completions"
- );
- assert.ok(stripped.includes("x-stainless-lang"));
- assert.equal(headers["x-stainless-lang"], undefined);
-});
diff --git a/tests/unit/base-reasoning-effort-split.test.ts b/tests/unit/base-reasoning-effort-split.test.ts
deleted file mode 100644
index 84ab9e46d8..0000000000
--- a/tests/unit/base-reasoning-effort-split.test.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import { test } from "node:test";
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { fileURLToPath } from "node:url";
-import { dirname, join } from "node:path";
-
-// Split-guard for the base executor reasoning-effort extraction.
-// The provider-aware reasoning_effort sanitation lives in base/reasoningEffort.ts
-// (deps are config/services only — no host import, no cycle). base.ts re-exports it
-// so external importers (mimoThinking + tests) keep the "./base.ts" path.
-const HERE = dirname(fileURLToPath(import.meta.url));
-const EXE = join(HERE, "../../open-sse/executors");
-
-test("leaf hosts sanitizeReasoningEffortForProvider and does not import the host", () => {
- const src = readFileSync(join(EXE, "base/reasoningEffort.ts"), "utf8");
- assert.match(src, /export function sanitizeReasoningEffortForProvider\b/);
- assert.doesNotMatch(src, /from "\.\.\/base\.ts"/);
-});
-
-test("base.ts re-exports it for external importers", () => {
- const host = readFileSync(join(EXE, "base.ts"), "utf8");
- assert.match(
- host,
- /export \{[^}]*sanitizeReasoningEffortForProvider[^}]*\} from "\.\/base\/reasoningEffort\.ts"/s
- );
-});
-
-test("both import paths resolve to the same function", async () => {
- const viaHost = (await import("../../open-sse/executors/base.ts"))
- .sanitizeReasoningEffortForProvider;
- const viaLeaf = (await import("../../open-sse/executors/base/reasoningEffort.ts"))
- .sanitizeReasoningEffortForProvider;
- assert.equal(viaHost, viaLeaf);
-});
diff --git a/tests/unit/bulk-web-session-import.test.ts b/tests/unit/bulk-web-session-import.test.ts
index 1eaea2c049..881828331d 100644
--- a/tests/unit/bulk-web-session-import.test.ts
+++ b/tests/unit/bulk-web-session-import.test.ts
@@ -11,7 +11,6 @@ import {
requiresWebSessionCredential,
getWebSessionCredentialRequirement,
hasUsableWebSessionCredential,
- resolveWebSessionImportApiKey,
} from "../../src/shared/providers/webSessionCredentials.ts";
describe("bulkWebSessionImportSchema", () => {
@@ -150,63 +149,24 @@ describe("web-session credential helpers", () => {
}),
true
);
- assert.equal(hasUsableWebSessionCredential("chatgpt-web", { cookie: "" }), false);
- assert.equal(hasUsableWebSessionCredential("chatgpt-web", {}), false);
- });
-
- it("hasUsableWebSessionCredential validates token data correctly", () => {
- assert.equal(hasUsableWebSessionCredential("deepseek-web", { token: "my-token" }), true);
- assert.equal(hasUsableWebSessionCredential("deepseek-web", { token: " " }), false);
- });
-});
-
-describe("resolveWebSessionImportApiKey (token-kind imports must populate apiKey)", () => {
- // Regression: the bulk web-session import stored token-kind credentials
- // (deepseek-web, copilot-web, t3-chat-web, …) only in providerSpecificData and
- // left apiKey null. Both the connection validator (validateDeepSeekWebProvider)
- // and the executor (extractUserToken → credentials.apiKey) read the token from
- // apiKey, so imported token-kind connections were never recognized. Token-kind
- // must resolve the credential into apiKey; cookie-kind keeps apiKey null (those
- // executors read providerSpecificData.cookie).
- it("returns the credential for a token-kind provider (deepseek-web)", () => {
- const req = getWebSessionCredentialRequirement("deepseek-web");
assert.equal(
- resolveWebSessionImportApiKey(req, "j9CVFGvd8Y/deadbeeftoken"),
- "j9CVFGvd8Y/deadbeeftoken"
+ hasUsableWebSessionCredential("chatgpt-web", { cookie: "" }),
+ false
+ );
+ assert.equal(
+ hasUsableWebSessionCredential("chatgpt-web", {}),
+ false
);
});
- it("preserves a JSON-wrapped userToken verbatim (extractUserToken unwraps it later)", () => {
- const req = getWebSessionCredentialRequirement("deepseek-web");
- const blob = '{"value":"abc123","__version":"0"}';
- assert.equal(resolveWebSessionImportApiKey(req, blob), blob);
- });
-
- it("returns null for cookie-kind providers (they read providerSpecificData.cookie)", () => {
+ it("hasUsableWebSessionCredential validates token data correctly", () => {
assert.equal(
- resolveWebSessionImportApiKey(
- getWebSessionCredentialRequirement("claude-web"),
- "sessionKey=abc"
- ),
- null
+ hasUsableWebSessionCredential("deepseek-web", { token: "my-token" }),
+ true
);
assert.equal(
- resolveWebSessionImportApiKey(
- getWebSessionCredentialRequirement("chatgpt-web"),
- "__Secure-next-auth.session-token=abc"
- ),
- null
+ hasUsableWebSessionCredential("deepseek-web", { token: " " }),
+ false
);
});
-
- it("returns null for a whitespace-only or missing credential", () => {
- const req = getWebSessionCredentialRequirement("deepseek-web");
- assert.equal(resolveWebSessionImportApiKey(req, " "), null);
- assert.equal(resolveWebSessionImportApiKey(null, "anything"), null);
- });
-
- it("trims surrounding whitespace from the stored token", () => {
- const req = getWebSessionCredentialRequirement("copilot-web");
- assert.equal(resolveWebSessionImportApiKey(req, " tok-123 "), "tok-123");
- });
});
diff --git a/tests/unit/catalog-updates-v3x.test.ts b/tests/unit/catalog-updates-v3x.test.ts
index a246171cea..0597b371b1 100644
--- a/tests/unit/catalog-updates-v3x.test.ts
+++ b/tests/unit/catalog-updates-v3x.test.ts
@@ -66,29 +66,6 @@ test("Fable 5 catalog exposes claude-fable-5 in cc and kiro providers with match
assert.ok(kiroPricing["claude-fable-5"], "kiro pricing must include claude-fable-5");
});
-test("Sonnet 5 catalog exposes claude-sonnet-5 across cc/kiro/anthropic/blackbox with Sonnet-tier pricing", () => {
- // Sonnet 5 must be wired everywhere the last flagship (Fable 5) was — but as a
- // Sonnet-tier model: $3/$15 pricing (NOT the Opus/Fable $15/$75), 1M ctx / 128K out.
- for (const providerId of ["cc", "kiro", "anthropic", "blackbox"]) {
- const ids = new Set(getModelsByProviderId(providerId).map((m) => m.id));
- assert.ok(ids.has("claude-sonnet-5"), `${providerId} must expose claude-sonnet-5`);
- }
-
- const kiroSonnet5 = getModelsByProviderId("kiro").find((m) => m.id === "claude-sonnet-5");
- assert.equal(kiroSonnet5?.contextLength, 1000000);
- assert.equal(kiroSonnet5?.maxOutputTokens, 128000);
-
- const ccPricing = (DEFAULT_PRICING as Record<string, Record<string, unknown>>).cc;
- assert.ok(ccPricing["claude-sonnet-5"], "cc pricing must include claude-sonnet-5");
-
- const kiroPricing = (DEFAULT_PRICING as Record<string, Record<string, unknown>>).kiro;
- const kiroSonnet5Price = kiroPricing["claude-sonnet-5"] as { input: number; output: number };
- assert.ok(kiroSonnet5Price, "kiro pricing must include claude-sonnet-5");
- // Sonnet-tier, not Opus-tier — guards against copying Fable 5's $15/$75.
- assert.equal(kiroSonnet5Price.input, 3.0);
- assert.equal(kiroSonnet5Price.output, 15.0);
-});
-
test("Kiro catalog exposes Claude Opus 4.8 alongside 4.7 with matching pricing", () => {
const models = getModelsByProviderId("kiro");
const ids = new Set(models.map((model) => model.id));
diff --git a/tests/unit/cc-compatible-provider.test.ts b/tests/unit/cc-compatible-provider.test.ts
index 43a155a3f5..cf65d924ef 100644
--- a/tests/unit/cc-compatible-provider.test.ts
+++ b/tests/unit/cc-compatible-provider.test.ts
@@ -452,7 +452,7 @@ test("DefaultExecutor uses CC-compatible path and headers", () => {
assert.equal(headers.Authorization, "Bearer sk-test");
assert.equal(headers["x-api-key"], undefined);
assert.equal(headers["X-Claude-Code-Session-Id"], "session-3");
- assert.equal(headers.Accept, "text/event-stream");
+ assert.equal(headers.Accept, "application/json");
});
test("validateProviderApiKey uses CC skeleton request after /models fallback", async () => {
@@ -493,7 +493,7 @@ test("validateProviderApiKey uses CC skeleton request after /models fallback", a
assert.equal(calls[1].body.stream, true);
assert.equal(calls[1].headers.Authorization, "Bearer sk-test");
assert.equal(calls[1].headers["x-api-key"], undefined);
- assert.equal(calls[1].headers.Accept, "text/event-stream");
+ assert.equal(calls[1].headers.Accept, "application/json");
});
test("handleChatCore forces SSE upstream for CC compatible providers while returning JSON to non-stream clients", async () => {
@@ -571,7 +571,7 @@ test("handleChatCore forces SSE upstream for CC compatible providers while retur
assert.equal(result.success, true);
assert.equal(calls.length, 1);
- assert.equal(calls[0].headers.Accept, "text/event-stream");
+ assert.equal(calls[0].headers.Accept, "application/json");
assert.equal(calls[0].body.stream, true);
assert.equal(calls[0].body.stream_options, undefined);
assert.equal(JSON.stringify(calls[0].body).includes('"cache_control"'), false);
diff --git a/tests/unit/charm-hyper-provider.test.ts b/tests/unit/charm-hyper-provider.test.ts
deleted file mode 100644
index ffc25f2256..0000000000
--- a/tests/unit/charm-hyper-provider.test.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import test from "node:test";
-import assert from "node:assert/strict";
-
-const { APIKEY_PROVIDERS } = await import("../../src/shared/constants/providers.ts");
-const { REGISTRY: providerRegistry } = await import("../../open-sse/config/providerRegistry.ts");
-
-const CHARM_HYPER_CHAT_URL = "https://hyper.charm.land/v1/chat/completions";
-const CHARM_HYPER_MODELS_URL = "https://hyper.charm.land/v1/models";
-
-test("Charm Hyper is registered as a free API-key provider", () => {
- const entry = APIKEY_PROVIDERS["charm-hyper"];
- assert.ok(entry, "APIKEY_PROVIDERS['charm-hyper'] must be defined");
- assert.equal(entry.id, "charm-hyper");
- assert.equal(entry.alias, "charm-hyper");
- assert.equal(entry.name, "Charm Hyper");
- assert.equal(entry.website, "https://hyper.charm.land");
- assert.equal(entry.hasFree, true);
- assert.equal(entry.passthroughModels, true);
-});
-
-test("Charm Hyper registry entry uses OpenAI format with bearer API-key auth", () => {
- const entry = providerRegistry["charm-hyper"];
- assert.ok(entry, "providerRegistry['charm-hyper'] must be defined");
- assert.equal(entry.id, "charm-hyper");
- assert.equal(entry.alias, "charm-hyper");
- assert.equal(entry.format, "openai");
- assert.equal(entry.executor, "default");
- assert.equal(entry.authType, "apikey");
- assert.equal(entry.authHeader, "bearer");
- assert.equal(entry.baseUrl, CHARM_HYPER_CHAT_URL);
- assert.equal(entry.modelsUrl, CHARM_HYPER_MODELS_URL);
- assert.equal(entry.passthroughModels, true);
-});
diff --git a/tests/unit/chatcore-translation-paths.test.ts b/tests/unit/chatcore-translation-paths.test.ts
index d59df9815c..c3ada3a628 100644
--- a/tests/unit/chatcore-translation-paths.test.ts
+++ b/tests/unit/chatcore-translation-paths.test.ts
@@ -499,9 +499,7 @@ test("chatCore keeps Responses-native Codex payloads in native passthrough mode"
assert.equal(result.success, true);
assert.match(call.url, /\/responses$/);
- assert.deepEqual(call.body.input, [
- { type: "message", role: "user", content: [{ type: "input_text", text: "ship it" }] },
- ]);
+ assert.deepEqual(call.body.input, [{ type: "message", role: "user", content: [{ type: "input_text", text: "ship it" }] }]);
assert.equal(call.body.instructions, "custom system prompt");
assert.equal(call.body.store, false);
assert.deepEqual(call.body.metadata, { source: "codex-client" });
@@ -673,8 +671,9 @@ test("chatCore builds Claude Code-compatible upstream requests for CC providers"
});
assert.equal(result.success, true);
- assert.equal(call.headers.Accept ?? call.headers.accept, "text/event-stream");
- assert.deepEqual([call.body.stream, call.body.context_management], [true, undefined]);
+ assert.equal(call.headers.Accept ?? call.headers.accept, "application/json");
+ assert.equal(call.body.stream, true);
+ assert.equal(call.body.context_management, undefined);
assert.equal(call.body.system.length, 1);
assert.match(call.body.system[0].text, /Claude Agent SDK/);
assert.equal(typeof call.body.metadata.user_id, "string");
diff --git a/tests/unit/chatgpt-web-models-split.test.ts b/tests/unit/chatgpt-web-models-split.test.ts
deleted file mode 100644
index f25f78556d..0000000000
--- a/tests/unit/chatgpt-web-models-split.test.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import { test } from "node:test";
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { fileURLToPath } from "node:url";
-import { dirname, join } from "node:path";
-
-// Split-guard for the chatgpt-web model-mapping extraction.
-// The static model maps + pure thinking-effort resolvers live in the pure leaf
-// chatgpt-web/models.ts (no module state). Host imports the two it uses back.
-const HERE = dirname(fileURLToPath(import.meta.url));
-const EXE = join(HERE, "../../open-sse/executors");
-const HOST = join(EXE, "chatgpt-web.ts");
-const LEAF = join(EXE, "chatgpt-web/models.ts");
-
-test("leaf hosts the model maps + resolvers and does not import the host", () => {
- const src = readFileSync(LEAF, "utf8");
- for (const sym of ["MODEL_MAP", "resolveChatGptModel", "resolveThinkingEffort"]) {
- assert.match(src, new RegExp(`export (const|function) ${sym}\\b`));
- }
- assert.doesNotMatch(src, /from "\.\.\/chatgpt-web\.ts"/);
-});
-
-test("host imports the resolvers back from the leaf", () => {
- const host = readFileSync(HOST, "utf8");
- assert.match(host, /from "\.\/chatgpt-web\/models\.ts"/);
-});
-
-test("resolveChatGptModel maps a dot-form model id to a chatgpt slug", async () => {
- const { resolveChatGptModel, MODEL_MAP } =
- await import("../../open-sse/executors/chatgpt-web/models.ts");
- const firstKey = Object.keys(MODEL_MAP)[0];
- const resolved = resolveChatGptModel(firstKey);
- assert.equal(typeof resolved.slug, "string");
- assert.ok(resolved.slug.length > 0);
-});
diff --git a/tests/unit/check-pr-evidence.test.ts b/tests/unit/check-pr-evidence.test.ts
deleted file mode 100644
index 3125ac1fe3..0000000000
--- a/tests/unit/check-pr-evidence.test.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import test from "node:test";
-import assert from "node:assert/strict";
-import { execFileSync } from "node:child_process";
-import path from "node:path";
-import { fileURLToPath } from "node:url";
-
-const mod = await import("../../scripts/check/check-pr-evidence.mjs");
-const { evaluatePrBody } = mod;
-const SCRIPT = path.resolve(
- path.dirname(fileURLToPath(import.meta.url)),
- "../../scripts/check/check-pr-evidence.mjs"
-);
-
-function run(body) {
- try {
- const out = execFileSync("node", [SCRIPT], {
- encoding: "utf8",
- env: { ...process.env, PR_BODY: body },
- });
- return { code: 0, out };
- } catch (err) {
- return { code: err.status ?? 1, out: `${err.stdout || ""}${err.stderr || ""}` };
- }
-}
-
-test("evaluatePrBody: no outcome claim → pass (no evidence required)", () => {
- const r = evaluatePrBody("Adds a helper module.");
- assert.equal(r.result, "pass");
- assert.match(r.reason, /no evidence required/i);
-});
-
-test("evaluatePrBody: outcome claim + evidence block → pass", () => {
- const r = evaluatePrBody("Tests pass.\n\n## Evidence\n```\ntests 20 / pass 20 / fail 0\n```");
- assert.equal(r.result, "pass");
-});
-
-test("evaluatePrBody: outcome claim without evidence → fail", () => {
- const r = evaluatePrBody("All 20 tests pass and 0 errors.");
- assert.equal(r.result, "fail");
-});
-
-test("the FAIL report explains that editing the body does not re-run the gate (push instead)", () => {
- const { code, out } = run("All 20 tests pass and 0 errors."); // claim, no evidence
- assert.equal(code, 1, "gate fails on a claim with no evidence");
- assert.match(out, /Result: FAIL/);
- assert.match(out, /does NOT re-run this gate/);
- assert.match(out, /push a commit/i);
-});
-
-test("the hint does NOT appear when the gate passes", () => {
- const { code, out } = run("Tests pass.\n\n## Evidence\n```\ntests 20 / pass 20 / fail 0\n```");
- assert.equal(code, 0);
- assert.match(out, /Result: PASS/);
- assert.doesNotMatch(out, /does NOT re-run this gate/);
-});
diff --git a/tests/unit/claude-classifier-compat.test.ts b/tests/unit/claude-classifier-compat.test.ts
deleted file mode 100644
index 56f1631ec5..0000000000
--- a/tests/unit/claude-classifier-compat.test.ts
+++ /dev/null
@@ -1,178 +0,0 @@
-/**
- * TDD test for the Claude Code auto-mode classifier compat mode (opt-in, default off).
- *
- * Claude Code's `--permission-mode auto` sends an internal `/v1/messages` security-classifier
- * request and requires the response to START with the literal token `<block>no</block>` (ALLOW)
- * or `<block>yes</block>` (BLOCK) — anything else is unparseable and Claude Code fails closed
- * with "Auto mode could not evaluate this action and is blocking it for safety".
- *
- * When a combo/fallback route sends the classifier call to a cheap model that returns 200 with
- * empty content, the well-formed-but-empty Claude message OmniRoute produces still fails that
- * parser. With `claudeClassifierCompat` set to "auto" (or "always"), handleChatCore detects the
- * classifier request and short-circuits with a synthetic ALLOW response — WITHOUT ever calling
- * the upstream provider. Default is "off": nothing changes unless an operator explicitly opts in.
- */
-
-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-claude-classifier-compat-"));
-process.env.DATA_DIR = TEST_DATA_DIR;
-
-const core = await import("../../src/lib/db/core.ts");
-const { updateSettings } = await import("../../src/lib/db/settings.ts");
-const { handleChatCore } = await import("../../open-sse/handlers/chatCore.ts");
-const { shouldDefaultAllowClassifier, buildDefaultAllowClaudeMessage } = await import(
- "../../open-sse/handlers/chatCore/claudeClassifierCompat.ts"
-);
-const { FORMATS } = await import("../../open-sse/translator/formats.ts");
-
-const originalFetch = globalThis.fetch;
-
-function noopLog() {
- return { debug() {}, info() {}, warn() {}, error() {} };
-}
-
-// Shape of the classifier request Claude Code's `--permission-mode auto` sends internally:
-// a Claude Messages request carrying the security-monitor system prompt AND `</block>` as a
-// stop sequence — the two independent signals the compat detector relies on.
-const CLASSIFIER_BODY = {
- model: "claude-3-5-haiku-20241022",
- stream: false,
- system: [
- {
- type: "text",
- text: "You are a security monitor for autonomous AI coding agents. Evaluate the following action and respond with <block>yes</block> or <block>no</block>.",
- },
- ],
- stop_sequences: ["</block>"],
- messages: [
- {
- role: "user",
- content: [{ type: "text", text: "<transcript>WebFetch https://example.com</transcript>" }],
- },
- ],
- max_tokens: 8,
-};
-
-test.after(() => {
- globalThis.fetch = originalFetch;
- core.resetDbInstance();
- fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
-});
-
-// ─── Settings default is opt-in (off) ────────────────────────────────────────
-// Runs FIRST, before any updateSettings() write, so it reads the pristine DB.
-// (DATA_DIR freezes at the first DB open, so a later "fresh dir" swap would still
-// read this same DB — hence assert the default up front.)
-
-test("settings default: claudeClassifierCompat is 'off' (opt-in)", async () => {
- const { getSettings } = await import("../../src/lib/db/settings.ts");
- const settings = await getSettings();
- assert.equal(settings.claudeClassifierCompat, "off", "claudeClassifierCompat defaults to off");
-});
-
-// ─── Pure detector: shouldDefaultAllowClassifier ─────────────────────────────
-
-test("detector: off never short-circuits (pass-through preserved by default)", () => {
- assert.equal(shouldDefaultAllowClassifier(FORMATS.CLAUDE, CLASSIFIER_BODY, "off"), false);
- assert.equal(shouldDefaultAllowClassifier(FORMATS.CLAUDE, CLASSIFIER_BODY, undefined), false);
-});
-
-test("detector: auto fires on the security-monitor system-prompt marker", () => {
- const body = {
- system: [{ type: "text", text: "You are a security monitor for autonomous AI coding agents." }],
- stop_sequences: [],
- };
- assert.equal(shouldDefaultAllowClassifier(FORMATS.CLAUDE, body, "auto"), true);
-});
-
-test("detector: auto fires on the </block> stop_sequence token", () => {
- const body = { system: [{ type: "text", text: "unrelated" }], stop_sequences: ["</block>"] };
- assert.equal(shouldDefaultAllowClassifier(FORMATS.CLAUDE, body, "auto"), true);
-});
-
-test("detector: auto does NOT fire on a regular Claude request (no marker, no </block>)", () => {
- const body = {
- system: [{ type: "text", text: "You are a helpful coding assistant." }],
- stop_sequences: [],
- messages: [{ role: "user", content: "hello" }],
- };
- assert.equal(shouldDefaultAllowClassifier(FORMATS.CLAUDE, body, "auto"), false);
-});
-
-test("detector: never fires for non-Claude source formats even in always mode", () => {
- assert.equal(shouldDefaultAllowClassifier(FORMATS.OPENAI, CLASSIFIER_BODY, "always"), false);
-});
-
-test("detector: always fires for every Claude-format request", () => {
- const plain = { system: [{ type: "text", text: "hi" }], stop_sequences: [] };
- assert.equal(shouldDefaultAllowClassifier(FORMATS.CLAUDE, plain, "always"), true);
-});
-
-// ─── Pure builder: buildDefaultAllowClaudeMessage ────────────────────────────
-
-test("builder: synthetic message text STARTS WITH <block>no</block>", async () => {
- const built = buildDefaultAllowClaudeMessage("claude-3-5-haiku-20241022");
- assert.equal(built.success, true);
- const payload = (await built.response.json()) as {
- type: string;
- role: string;
- stop_reason: string;
- content: Array<{ type: string; text?: string }>;
- };
- assert.equal(payload.type, "message");
- assert.equal(payload.role, "assistant");
- assert.equal(payload.stop_reason, "end_turn");
- const text = payload.content.find((b) => b.type === "text")?.text ?? "";
- assert.ok(
- text.startsWith("<block>no</block>"),
- `expected synthetic text to start with <block>no</block>, got: ${text}`
- );
- assert.ok(!text.includes("<block>yes"), "must not signal BLOCK");
-});
-
-// ─── Handler-level: end-to-end short-circuit through handleChatCore ──────────
-
-test("handler: claudeClassifierCompat=auto short-circuits WITHOUT calling upstream, text starts with <block>no</block>", async () => {
- await updateSettings({ claudeClassifierCompat: "auto" });
-
- let fetchCalls = 0;
- globalThis.fetch = (async () => {
- fetchCalls++;
- throw new Error("upstream fetch should NOT be called when the classifier short-circuits");
- }) as typeof fetch;
-
- try {
- const result = await handleChatCore({
- body: structuredClone(CLASSIFIER_BODY),
- modelInfo: { provider: "openai", model: "gpt-4o-mini", extendedContext: false },
- credentials: { apiKey: "sk-test", providerSpecificData: {} },
- log: noopLog(),
- clientRawRequest: {
- endpoint: "/v1/messages",
- body: structuredClone(CLASSIFIER_BODY),
- headers: new Headers({ accept: "application/json" }),
- },
- userAgent: "unit-test",
- });
-
- assert.equal(fetchCalls, 0, "upstream fetch must NOT be called");
- assert.equal(result.success, true, "handleChatCore must report success");
- const payload = (await (result as { response: Response }).response.json()) as {
- type: string;
- content: Array<{ type: string; text?: string }>;
- };
- assert.equal(payload.type, "message");
- const text = payload.content.find((b) => b.type === "text")?.text ?? "";
- assert.ok(
- text.startsWith("<block>no</block>"),
- `expected classifier response to start with <block>no</block>, got: ${text}`
- );
- } finally {
- globalThis.fetch = originalFetch;
- }
-});
diff --git a/tests/unit/claude-code-compatible-helpers.test.ts b/tests/unit/claude-code-compatible-helpers.test.ts
index eaa944b1cf..13d00fc482 100644
--- a/tests/unit/claude-code-compatible-helpers.test.ts
+++ b/tests/unit/claude-code-compatible-helpers.test.ts
@@ -47,7 +47,7 @@ test("buildClaudeCodeCompatibleHeaders emits bearer auth headers and session id"
const streamHeaders = buildClaudeCodeCompatibleHeaders("sk-demo", true, "session-123");
const jsonHeaders = buildClaudeCodeCompatibleHeaders("sk-demo", false);
- assert.equal(streamHeaders.Accept, "text/event-stream");
+ assert.equal(streamHeaders.Accept, "application/json");
assert.equal(streamHeaders.Authorization, "Bearer sk-demo");
assert.equal(streamHeaders["x-api-key"], undefined);
assert.equal(streamHeaders["X-Claude-Code-Session-Id"], "session-123");
diff --git a/tests/unit/claude-web-executor-split.test.ts b/tests/unit/claude-web-executor-split.test.ts
deleted file mode 100644
index be510e80d4..0000000000
--- a/tests/unit/claude-web-executor-split.test.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-import { test } from "node:test";
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { fileURLToPath } from "node:url";
-import { dirname, join } from "node:path";
-
-// Split-guard for the claude-web executor payload extraction.
-// The pure payload types + transforms + default tools/style live in the leaf
-// claude-web/payload.ts (no host state, no fetch/auth). Host imports back the
-// symbols it uses (ClaudeWebRequestPayload, transformToClaude, transformFromClaude).
-const HERE = dirname(fileURLToPath(import.meta.url));
-const EXE = join(HERE, "../../open-sse/executors");
-const HOST = join(EXE, "claude-web.ts");
-const LEAF = join(EXE, "claude-web/payload.ts");
-
-test("leaf hosts the payload builders/transforms and does not import the host", () => {
- const src = readFileSync(LEAF, "utf8");
- for (const sym of ["transformToClaude", "transformFromClaude", "getDefaultTools"]) {
- assert.match(src, new RegExp(`export function ${sym}\\b`));
- }
- assert.match(src, /export interface ClaudeWebRequestPayload\b/);
- assert.doesNotMatch(src, /from "\.\.\/claude-web\.ts"/);
-});
-
-test("host imports the transforms back from the leaf", () => {
- const host = readFileSync(HOST, "utf8");
- assert.match(host, /from "\.\/claude-web\/payload\.ts"/);
-});
-
-test("transformToClaude builds a Claude-web payload with model + tools", async () => {
- const { transformToClaude } = await import("../../open-sse/executors/claude-web/payload.ts");
- const payload = transformToClaude(
- { messages: [{ role: "user", content: "hi" }] },
- "claude-sonnet-4-6"
- );
- assert.equal(typeof payload, "object");
- assert.ok(Array.isArray(payload.tools));
-});
diff --git a/tests/unit/cli-catalog-acpspawnable.test.ts b/tests/unit/cli-catalog-acpspawnable.test.ts
index 06e79f76ce..d0b6654476 100644
--- a/tests/unit/cli-catalog-acpspawnable.test.ts
+++ b/tests/unit/cli-catalog-acpspawnable.test.ts
@@ -44,7 +44,6 @@ const NOT_ACP_SPAWNABLE_IDS = [
"roo",
"jcode",
"deepseek-tui",
- "codewhale",
"smelt",
"pi",
"hermes-agent",
diff --git a/tests/unit/cli-catalog-counts.test.ts b/tests/unit/cli-catalog-counts.test.ts
index e65516f228..7ad6db8744 100644
--- a/tests/unit/cli-catalog-counts.test.ts
+++ b/tests/unit/cli-catalog-counts.test.ts
@@ -30,7 +30,7 @@ test(`CLI_TOOLS has exactly ${EXPECTED_AGENT_COUNT} agent entries`, () => {
);
});
-test("CLI_TOOLS total code entries (including none) equals 24 (20 visible + 4 none)", () => {
+test("CLI_TOOLS total code entries (including none) equals 22 (18 visible + 4 none)", () => {
// code-none entries: antigravity, kiro, cursor (app), hermes (simple guide)
const codeNone = codeAll.filter((t) => t.baseUrlSupport === "none");
assert.equal(
@@ -38,11 +38,11 @@ test("CLI_TOOLS total code entries (including none) equals 24 (20 visible + 4 no
4,
`Expected 4 code entries with baseUrlSupport='none', got ${codeNone.length}: ${codeNone.map((t) => t.id).join(", ")}`
);
- assert.equal(codeAll.length, 24, `Expected 24 total code entries, got ${codeAll.length}`);
+ assert.equal(codeAll.length, 22, `Expected 22 total code entries, got ${codeAll.length}`);
});
-test("CLI_TOOLS total (code + agent) = 30", () => {
- assert.equal(all.length, 30, `Expected 30 total entries, got ${all.length}`);
+test("CLI_TOOLS total (code + agent) = 28", () => {
+ assert.equal(all.length, 28, `Expected 28 total entries, got ${all.length}`);
});
test("All code-none entries have configType mitm OR are legacy excluded entries", () => {
@@ -66,7 +66,7 @@ test("All agent entries have baseUrlSupport 'full' or 'partial' (no agent is 'no
}
});
-test("The 20 visible code entries match D15 list exactly (+ crush + codewhale)", () => {
+test("The 18 visible code entries match D15 list exactly", () => {
const d15List = new Set([
"claude",
"codex",
@@ -79,7 +79,6 @@ test("The 20 visible code entries match D15 list exactly (+ crush + codewhale)",
"forge",
"jcode",
"deepseek-tui",
- "codewhale",
"opencode",
"droid",
"copilot",
@@ -87,7 +86,6 @@ test("The 20 visible code entries match D15 list exactly (+ crush + codewhale)",
"smelt",
"pi",
"custom",
- "crush",
]);
const visibleIds = new Set(codeVisible.map((t) => t.id));
for (const id of d15List) {
diff --git a/tests/unit/cli-setup-opencode.test.ts b/tests/unit/cli-setup-opencode.test.ts
index ca5425e9d5..714e901db8 100644
--- a/tests/unit/cli-setup-opencode.test.ts
+++ b/tests/unit/cli-setup-opencode.test.ts
@@ -40,27 +40,12 @@ function readConfig() {
return JSON.parse(fs.readFileSync(path.join(CONFIG_DIR, "opencode.json"), "utf8"));
}
-// #5959-class deflake: the command under test prints CLI progress with multi-byte
-// glyphs (printInfo/printSuccess "✔"/printError "✖" via console.log). Under the
-// node:test runner those stdout writes interleave with the child's V8-serialized
-// report frames and can corrupt the stream ("Unable to deserialize cloned data
-// due to invalid or unsupported version"). No test here asserts on stdout, so
-// silence the stdout-writing console methods for the duration of this file
-// (same pattern as tests/unit/cli/setup-claude.test.ts, #6019/#6021).
-const _console = { log: console.log, info: console.info, warn: console.warn };
-
describe("omniroute setup opencode", () => {
before(() => {
- console.log = () => {};
- console.info = () => {};
- console.warn = () => {};
makeFakePluginDist();
});
after(() => {
- console.log = _console.log;
- console.info = _console.info;
- console.warn = _console.warn;
try {
fs.rmSync(FIXTURE_ROOT, { recursive: true, force: true });
} catch {
@@ -87,11 +72,7 @@ describe("omniroute setup opencode", () => {
const [modulePath, options] = cfg.plugin[0];
assert.equal(modulePath, "./plugins/omniroute/dist/index.js");
assert.equal(options.providerId, "omniroute");
- assert.equal(
- options.baseURL,
- "http://10.0.0.5:20128",
- "--base-url flag must reach the registered entry"
- );
+ assert.equal(options.baseURL, "http://10.0.0.5:20128", "--base-url flag must reach the registered entry");
});
it("is idempotent: re-running updates the entry in place instead of duplicating it", async () => {
@@ -104,15 +85,10 @@ describe("omniroute setup opencode", () => {
const cfg = readConfig();
const omniEntries = cfg.plugin.filter(
- (p: unknown) =>
- Array.isArray(p) && (p[1] as { providerId?: string })?.providerId === "omniroute"
+ (p: unknown) => Array.isArray(p) && (p[1] as { providerId?: string })?.providerId === "omniroute"
);
assert.equal(omniEntries.length, 1, "re-run must not duplicate the entry");
- assert.equal(
- omniEntries[0][1].baseURL,
- "http://10.0.0.9:20128",
- "re-run updates baseURL in place"
- );
+ assert.equal(omniEntries[0][1].baseURL, "http://10.0.0.9:20128", "re-run updates baseURL in place");
});
it("removes the legacy opencode-omniroute-auth entry (#3711) and preserves unrelated plugins", async () => {
diff --git a/tests/unit/cli-tools-crush.test.ts b/tests/unit/cli-tools-crush.test.ts
deleted file mode 100644
index a3fca02851..0000000000
--- a/tests/unit/cli-tools-crush.test.ts
+++ /dev/null
@@ -1,233 +0,0 @@
-/**
- * Unit tests for the "Crush" CLI tool dashboard entry (ported from upstream
- * decolua/9router#1233). Mirrors the assertions used for the "pi" tool in
- * tests/unit/cli-tools-schema.test.ts, plus a GET/POST/DELETE round-trip for
- * /api/cli-tools/crush-settings modeled on tests/integration/cli-settings-pi.test.ts.
- */
-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";
-
-// ── Catalog shape ────────────────────────────────────────────────────────────
-
-test("CLI_TOOLS contains a 'crush' entry modeled on 'pi'", async () => {
- const { CLI_TOOLS } = await import("../../src/shared/constants/cliTools.ts");
- const crush = CLI_TOOLS["crush"];
- assert.ok(crush, "crush entry must exist in CLI_TOOLS");
- assert.equal(crush.id, "crush");
- assert.equal(crush.name, "Crush");
- assert.equal(crush.configType, "custom");
- assert.equal(crush.category, "code");
- assert.equal(crush.acpSpawnable, false);
- assert.equal(crush.baseUrlSupport, "full");
- assert.equal(crush.defaultCommand, "crush");
- assert.equal(typeof crush.description, "string");
- assert.ok(crush.description.length > 0);
- assert.equal(typeof crush.docsUrl, "string");
- assert.ok(crush.docsUrl.length > 0);
-});
-
-test("getCliTool('crush') resolves the catalog entry", async () => {
- const { getCliTool } = await import("../../src/shared/constants/cliTools.ts");
- const crush = getCliTool("crush");
- assert.ok(crush);
- assert.equal(crush.id, "crush");
-});
-
-// ── Runtime config path reconciliation with setup-crush.mjs ─────────────────
-
-test("getCliConfigPaths('crush') resolves to ~/.config/crush/crush.json (matches setup-crush.mjs default)", async () => {
- const { getCliConfigPaths } = await import("../../src/shared/services/cliRuntime.ts");
- const paths = getCliConfigPaths("crush");
- assert.ok(paths);
- assert.ok(
- paths.config?.endsWith(path.join(".config", "crush", "crush.json")),
- `Expected config path to end with .config/crush/crush.json, got: ${paths.config}`
- );
-});
-
-// ── /api/cli-tools/crush-settings round-trip ─────────────────────────────────
-
-const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-crush-settings-"));
-process.env.DATA_DIR = TEST_DATA_DIR;
-process.env.API_KEY_SECRET = "test-api-key-secret-crush";
-process.env.JWT_SECRET = "test-jwt-secret-crush";
-
-const core = await import("../../src/lib/db/core.ts");
-const localDb = await import("../../src/lib/localDb.ts");
-
-const { GET, POST, DELETE } = await import("../../src/app/api/cli-tools/crush-settings/route.ts");
-
-async function resetStorage() {
- delete process.env.INITIAL_PASSWORD;
- core.resetDbInstance();
- fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
- fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
-}
-
-async function enableAuth() {
- process.env.INITIAL_PASSWORD = "test-bootstrap";
- await localDb.updateSettings({ requireLogin: true, password: "" });
-}
-
-test.beforeEach(async () => {
- await resetStorage();
-});
-
-test("crush-settings GET: returns 401 when auth required and no token", async () => {
- await enableAuth();
- const res = await GET(new Request("http://localhost/api/cli-tools/crush-settings"));
- assert.equal(res.status, 401, `Expected 401, got ${res.status}`);
-});
-
-test("crush-settings GET: returns 200 when auth not required", async () => {
- const res = await GET(new Request("http://localhost/api/cli-tools/crush-settings"));
- assert.equal(res.status, 200, `Expected 200, got ${res.status}`);
- const body = await res.json();
- assert.ok(
- "installed" in body || "config" in body,
- "Response should contain installed or config field"
- );
-});
-
-test("crush-settings POST: 400 when baseUrl is missing", async () => {
- const res = await POST(
- new Request("http://localhost/api/cli-tools/crush-settings", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({ apiKey: "sk-test", model: "openai/gpt-5" }),
- })
- );
- assert.equal(res.status, 400, `Expected 400, got ${res.status}`);
- const body = await res.json();
- assert.ok(body.error !== undefined);
-});
-
-test("crush-settings POST: 400 when model is missing", async () => {
- const res = await POST(
- new Request("http://localhost/api/cli-tools/crush-settings", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({ baseUrl: "http://localhost:20128", apiKey: "sk-test" }),
- })
- );
- assert.equal(res.status, 400, `Expected 400, got ${res.status}`);
-});
-
-test("crush-settings POST: writes crush.json with an openai-compat providers.omniroute block", async () => {
- const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "crush-home-"));
- const origHome = process.env.HOME;
- process.env.HOME = tmpHome;
-
- try {
- const res = await POST(
- new Request("http://localhost/api/cli-tools/crush-settings", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({
- baseUrl: "http://localhost:20128",
- apiKey: "sk-test-crush-key",
- model: "openai/gpt-5.4-mini",
- }),
- })
- );
- assert.ok([200, 403, 500].includes(res.status), `Unexpected status ${res.status}`);
- if (res.status === 200) {
- const body = await res.json();
- assert.equal(body.success, true);
- const configPath = path.join(tmpHome, ".config", "crush", "crush.json");
- if (fs.existsSync(configPath)) {
- const written = JSON.parse(fs.readFileSync(configPath, "utf-8"));
- const provider = written.providers?.omniroute;
- assert.ok(provider, "providers.omniroute must be written");
- assert.equal(provider.type, "openai-compat");
- assert.ok(provider.base_url.includes("localhost:20128"));
- assert.ok(provider.base_url.endsWith("/v1"));
- assert.ok(Array.isArray(provider.models) && provider.models.length === 1);
- assert.equal(provider.models[0].id, "openai/gpt-5.4-mini");
- }
- }
- } finally {
- process.env.HOME = origHome;
- fs.rmSync(tmpHome, { recursive: true, force: true });
- }
-});
-
-test("crush-settings DELETE: removes only the omniroute provider entry", async () => {
- const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "crush-home-del-"));
- const origHome = process.env.HOME;
- process.env.HOME = tmpHome;
-
- try {
- const crushDir = path.join(tmpHome, ".config", "crush");
- fs.mkdirSync(crushDir, { recursive: true });
- fs.writeFileSync(
- path.join(crushDir, "crush.json"),
- JSON.stringify({
- providers: {
- omniroute: {
- type: "openai-compat",
- base_url: "http://localhost:20128/v1",
- api_key: "sk-test",
- models: [
- { id: "openai/gpt-5", name: "OmniRoute: openai/gpt-5", context_window: 128000 },
- ],
- },
- other: { type: "openai-compat", base_url: "http://example.com/v1" },
- },
- })
- );
-
- const res = await DELETE(
- new Request("http://localhost/api/cli-tools/crush-settings", { method: "DELETE" })
- );
- assert.ok([200, 403, 500].includes(res.status), `Expected 200/403/500, got ${res.status}`);
- if (res.status === 200) {
- const body = await res.json();
- assert.equal(body.success, true);
- const configPath = path.join(crushDir, "crush.json");
- if (fs.existsSync(configPath)) {
- const written = JSON.parse(fs.readFileSync(configPath, "utf-8"));
- assert.equal(written.providers?.omniroute, undefined);
- assert.ok(written.providers?.other, "Unrelated providers must be preserved");
- }
- }
- } finally {
- process.env.HOME = origHome;
- fs.rmSync(tmpHome, { recursive: true, force: true });
- }
-});
-
-test("crush-settings: error responses do not leak stack traces", async () => {
- const badReq = new Request("http://localhost/api/cli-tools/crush-settings", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: "{ bad json }",
- });
- const res = await POST(badReq);
- const bodyStr = JSON.stringify(await res.json());
- assert.ok(
- !bodyStr.match(/\s+at\s+\/[^\s]/),
- "Error response must not contain absolute-path stack traces"
- );
-});
-
-test("crush-settings route.ts: does not call exec() or spawn() directly", () => {
- const routePath = path.resolve(
- import.meta.dirname,
- "../../src/app/api/cli-tools/crush-settings/route.ts"
- );
- const content = fs.readFileSync(routePath, "utf-8");
- assert.ok(!content.match(/\bexec\s*\(/), "Handler must not use exec()");
- assert.ok(!content.match(/\bspawn\s*\(/), "Handler must not use spawn()");
-});
-
-test.after(async () => {
- await resetStorage();
- fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
- delete process.env.DATA_DIR;
- delete process.env.API_KEY_SECRET;
- delete process.env.JWT_SECRET;
-});
diff --git a/tests/unit/cli-tools-schema.test.ts b/tests/unit/cli-tools-schema.test.ts
index b74e274eef..70e6d620f0 100644
--- a/tests/unit/cli-tools-schema.test.ts
+++ b/tests/unit/cli-tools-schema.test.ts
@@ -1,14 +1,11 @@
import test from "node:test";
import assert from "node:assert/strict";
-test("CLI_TOOLS registry contains all expected tools (plan 14 — 30 total + crush + codewhale)", async () => {
+test("CLI_TOOLS registry contains all expected tools (plan 14 — 28 total)", async () => {
const { CLI_TOOLS } = await import("../../src/shared/constants/cliTools.ts");
// windsurf and amp removed per plan 14 D17 (MITM backlog plan 11)
// New entries added: roo, jcode, deepseek-tui, smelt, pi, aider, forge,
// cursor-cli, goose, interpreter, warp, agent-deck (+ hermes-agent already existed)
- // crush added — ported from upstream decolua/9router#1233
- // codewhale added 2026-07-02 as a dual entry alongside deepseek-tui
- // (CodeWhale is the actively-maintained successor to DeepSeek TUI).
const expected = [
"claude",
"codex",
@@ -32,14 +29,12 @@ test("CLI_TOOLS registry contains all expected tools (plan 14 — 30 total + cru
"roo",
"jcode",
"deepseek-tui",
- "codewhale",
"smelt",
"pi",
"goose",
"interpreter",
"warp",
"agent-deck",
- "crush",
];
for (const id of expected) {
assert.ok(id in CLI_TOOLS, `Missing tool: ${id}`);
diff --git a/tests/unit/cli/setup-claude.test.ts b/tests/unit/cli/setup-claude.test.ts
index ed1ca11eca..5dec875335 100644
--- a/tests/unit/cli/setup-claude.test.ts
+++ b/tests/unit/cli/setup-claude.test.ts
@@ -1,4 +1,4 @@
-import { test, before, after } from "node:test";
+import { test } from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs/promises";
import os from "node:os";
@@ -10,27 +10,6 @@ import {
import { buildClaudeEnv, resolveLaunchTarget } from "../../../bin/cli/commands/launch.mjs";
import { categoriseModel } from "../../../bin/cli/commands/setup-codex.mjs";
-// #5959 — deflake: `node --test` runs each file in a child process that streams
-// its report back to the parent as V8-serialized frames on fd 1 (stdout). The CLI
-// helpers under test (`syncClaudeProfilesFromModels`) print progress via
-// `console.log`, and that stdout output interleaves with the serialized frames,
-// corrupting the stream — the parent then throws
-// "Unable to deserialize cloned data due to invalid or unsupported version" at
-// file teardown ~50% of runs (all subtests pass; only the file errors). No test
-// here asserts on stdout, so silence the stdout-writing console methods for the
-// duration of this file. Restored in `after` for good hygiene.
-const _console = { log: console.log, info: console.info, warn: console.warn };
-before(() => {
- console.log = () => {};
- console.info = () => {};
- console.warn = () => {};
-});
-after(() => {
- console.log = _console.log;
- console.info = _console.info;
- console.warn = _console.warn;
-});
-
// ── setup-claude profile generation ──────────────────────────────────────────
test("buildProfileSettings pins the model + base URL + gateway discovery", () => {
@@ -89,30 +68,19 @@ test("syncClaudeProfilesFromModels writes directory-per-profile settings + threa
}
});
-test("syncClaudeProfilesFromModels dry-run writes nothing and reports via the injected log (#5959)", async () => {
+test("syncClaudeProfilesFromModels dry-run writes nothing", async () => {
const claudeHome = await fs.mkdtemp(path.join(os.tmpdir(), "omniroute-claude-dry-"));
- // The collector keeps the dry-run's multi-byte "──" heading OFF this child
- // process's stdout: under the node:test runner that write corrupts the V8
- // serialization stream ~50% of runs (#5959, "Unable to deserialize cloned
- // data due to invalid or unsupported version").
- const lines: string[] = [];
try {
const result = await syncClaudeProfilesFromModels([{ id: "glm/glm-5.2" }], {
claudeHome,
baseUrl: "http://vps:20128",
dryRun: true,
- log: (line: string) => lines.push(line),
});
assert.equal(result.written, 1);
- // Dry-run reports the would-be file + its content through the log sink…
- assert.equal(lines.length, 2);
- const settingsPath = path.join(claudeHome, "profiles", "glm52", "settings.json");
- assert.ok(lines[0].includes(settingsPath));
- const printed = JSON.parse(lines[1]);
- assert.equal(printed.model, "glm/glm-5.2");
- assert.equal(printed.env.ANTHROPIC_BASE_URL, "http://vps:20128");
- // …and writes nothing to disk.
- await assert.rejects(fs.stat(settingsPath), /ENOENT/);
+ await assert.rejects(
+ fs.stat(path.join(claudeHome, "profiles", "glm52", "settings.json")),
+ /ENOENT/
+ );
} finally {
await fs.rm(claudeHome, { recursive: true, force: true });
}
diff --git a/tests/unit/client-identity-profiles.test.ts b/tests/unit/client-identity-profiles.test.ts
deleted file mode 100644
index 119c8a7b2d..0000000000
--- a/tests/unit/client-identity-profiles.test.ts
+++ /dev/null
@@ -1,174 +0,0 @@
-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";
-
-// DefaultExecutor transitively touches the DB layer (provider/key rotation
-// lookups) at import/call time. Point DATA_DIR at an isolated temp dir
-// BEFORE importing it so these tests never read/write the operator's real
-// ~/.omniroute database (see CLAUDE.md "Database Handles in Tests").
-const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-client-identity-"));
-process.env.DATA_DIR = TEST_DATA_DIR;
-
-const {
- CLIENT_IDENTITY_PROFILES,
- CLIENT_IDENTITY_PROFILE_OPTIONS,
- getClientIdentityProfileHeaders,
- isClientIdentityProfileId,
-} = await import("../../src/shared/constants/clientIdentityProfiles.ts");
-const { isForbiddenCustomHeaderName } = await import("../../src/shared/constants/upstreamHeaders.ts");
-const { DefaultExecutor } = await import("../../open-sse/executors/default.ts");
-const core = await import("../../src/lib/db/core.ts");
-
-test.after(async () => {
- core.resetDbInstance();
- fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
-});
-
-test("getClientIdentityProfileHeaders: default profile adds no headers", () => {
- assert.deepEqual(getClientIdentityProfileHeaders("default"), {});
- assert.deepEqual(getClientIdentityProfileHeaders(undefined), {});
- assert.deepEqual(getClientIdentityProfileHeaders(null), {});
-});
-
-test("getClientIdentityProfileHeaders: unknown profile id falls back to no headers", () => {
- assert.deepEqual(getClientIdentityProfileHeaders("not-a-real-profile"), {});
-});
-
-test("getClientIdentityProfileHeaders: known CLI profiles expose their preset headers", () => {
- const claudeCli = getClientIdentityProfileHeaders("claude-cli");
- assert.equal(claudeCli["User-Agent"], "claude-cli/2.1.195 (external, cli)");
- assert.equal(claudeCli["X-App"], "cli");
-
- const codexCli = getClientIdentityProfileHeaders("codex-cli");
- assert.equal(codexCli["User-Agent"], "codex_cli_rs/0.136.0");
- assert.equal(codexCli.originator, "codex_cli_rs");
-
- const geminiCli = getClientIdentityProfileHeaders("gemini-cli");
- assert.equal(geminiCli["User-Agent"], "GeminiCLI/0.1.0 (linux; x64)");
-});
-
-test("getClientIdentityProfileHeaders: returns a fresh mutable copy (catalog stays frozen)", () => {
- const headers = getClientIdentityProfileHeaders("claude-cli");
- headers["User-Agent"] = "tampered";
- assert.equal(
- CLIENT_IDENTITY_PROFILES["claude-cli"].headers["User-Agent"],
- "claude-cli/2.1.195 (external, cli)"
- );
-});
-
-test("isClientIdentityProfileId / CLIENT_IDENTITY_PROFILE_OPTIONS stay in sync with the catalog", () => {
- for (const id of Object.keys(CLIENT_IDENTITY_PROFILES)) {
- assert.equal(isClientIdentityProfileId(id), true);
- }
- assert.equal(isClientIdentityProfileId("bogus"), false);
-
- const optionValues = CLIENT_IDENTITY_PROFILE_OPTIONS.map((o) => o.value);
- assert.deepEqual(optionValues, Object.keys(CLIENT_IDENTITY_PROFILES));
- assert.equal(CLIENT_IDENTITY_PROFILE_OPTIONS[0].value, "default");
-});
-
-test("a selected profile's headers land in providerSpecificData.customHeaders", () => {
- // This is exactly what the compatible-provider modal does when an operator
- // picks a profile from the <Select>: merge the preset onto the existing
- // customHeaders record before persisting the node/connection.
- const profileHeaders = getClientIdentityProfileHeaders("codex-cli");
- const providerSpecificData = {
- baseUrl: "https://proxy.example.com/v1",
- customHeaders: { ...profileHeaders, "X-Operator-Set": "keep-me" },
- };
-
- assert.equal(providerSpecificData.customHeaders["User-Agent"], "codex_cli_rs/0.136.0");
- assert.equal(providerSpecificData.customHeaders.originator, "codex_cli_rs");
- assert.equal(providerSpecificData.customHeaders["X-Operator-Set"], "keep-me");
-});
-
-test("profile headers merged into customHeaders survive applyCustomHeaders sanitization via DefaultExecutor", () => {
- const executor = new DefaultExecutor("openai-compatible-test");
- const profileHeaders = getClientIdentityProfileHeaders("claude-cli");
-
- const headers = executor.buildHeaders(
- {
- apiKey: "test-key",
- providerSpecificData: {
- baseUrl: "https://proxy.example.com/v1",
- customHeaders: profileHeaders,
- },
- },
- true
- ) as Record<string, string>;
-
- assert.equal(headers["User-Agent"], "claude-cli/2.1.195 (external, cli)");
- assert.equal(headers["X-App"], "cli");
- assert.equal(headers["Authorization"], "Bearer test-key");
-});
-
-test("a malicious profile-shaped header set has its auth/cookie entries dropped by applyCustomHeaders", () => {
- const executor = new DefaultExecutor("openai-compatible-test");
-
- // Simulate a compromised/hand-crafted profile that tries to smuggle in
- // credential-owning header names alongside a legitimate identity header.
- // isForbiddenCustomHeaderName is the single source of truth used by both
- // the Zod schema and the executor, so assert against it directly too.
- const maliciousProfileHeaders: Record<string, string> = {
- "User-Agent": "totally-legit-cli/1.0",
- Authorization: "Bearer stolen-token",
- "x-api-key": "stolen-key",
- cookie: "session=stolen",
- };
- assert.equal(isForbiddenCustomHeaderName("Authorization"), true);
- assert.equal(isForbiddenCustomHeaderName("x-api-key"), true);
- assert.equal(isForbiddenCustomHeaderName("cookie"), true);
-
- const headers = executor.buildHeaders(
- {
- apiKey: "real-key",
- providerSpecificData: {
- baseUrl: "https://proxy.example.com/v1",
- customHeaders: maliciousProfileHeaders,
- },
- },
- true
- ) as Record<string, string>;
-
- assert.equal(headers["User-Agent"], "totally-legit-cli/1.0");
- assert.equal(headers["Authorization"], "Bearer real-key");
- assert.notEqual(headers["Authorization"], "Bearer stolen-token");
- assert.equal(headers["x-api-key"], undefined);
- assert.equal(headers["cookie"], undefined);
-});
-
-test("DefaultExecutor.execute sends the selected profile's headers for a compatible-node connection", async () => {
- const executor = new DefaultExecutor("openai-compatible-test");
- const originalFetch = globalThis.fetch;
- let capturedHeaders: Record<string, string> = {};
-
- globalThis.fetch = async (_url: string | URL | Request, init: RequestInit = {}) => {
- capturedHeaders = (init.headers as Record<string, string>) || {};
- return new Response(JSON.stringify({ ok: true }), {
- status: 200,
- headers: { "Content-Type": "application/json" },
- });
- };
-
- try {
- await executor.execute({
- model: "gpt-4.1",
- body: { messages: [{ role: "user", content: "hi" }] },
- stream: false,
- credentials: {
- apiKey: "real-key",
- providerSpecificData: {
- baseUrl: "https://test.proxy.com/v1",
- customHeaders: getClientIdentityProfileHeaders("gemini-cli"),
- },
- },
- });
-
- assert.equal(capturedHeaders["User-Agent"], "GeminiCLI/0.1.0 (linux; x64)");
- assert.equal(capturedHeaders["Authorization"], "Bearer real-key");
- } finally {
- globalThis.fetch = originalFetch;
- }
-});
diff --git a/tests/unit/cline-response-envelope.test.ts b/tests/unit/cline-response-envelope.test.ts
deleted file mode 100644
index f087ad923a..0000000000
--- a/tests/unit/cline-response-envelope.test.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import test from "node:test";
-import assert from "node:assert/strict";
-
-const { unwrapClineNonStreamingEnvelope } = await import(
- "../../open-sse/handlers/chatCore/clineResponseEnvelope.ts"
-);
-
-test("unwrapClineNonStreamingEnvelope extracts Cline wrapped chat completions", () => {
- const wrapped = {
- success: true,
- data: {
- id: "chatcmpl_cline",
- model: "cline/model",
- choices: [{ index: 0, message: { role: "assistant", content: "ok" } }],
- usage: { prompt_tokens: 3, completion_tokens: 2, total_tokens: 5 },
- },
- };
-
- assert.deepEqual(unwrapClineNonStreamingEnvelope("cline", wrapped), wrapped.data);
-});
-
-test("unwrapClineNonStreamingEnvelope keeps non-Cline and malformed envelopes untouched", () => {
- const wrapped = { success: true, data: { message: "missing choices" } };
-
- assert.equal(unwrapClineNonStreamingEnvelope("openai", wrapped), wrapped);
- assert.equal(unwrapClineNonStreamingEnvelope("cline", wrapped), wrapped);
-});
diff --git a/tests/unit/clinepass-provider.test.ts b/tests/unit/clinepass-provider.test.ts
deleted file mode 100644
index 1706e1cc56..0000000000
--- a/tests/unit/clinepass-provider.test.ts
+++ /dev/null
@@ -1,117 +0,0 @@
-import test from "node:test";
-import assert from "node:assert/strict";
-
-const { APIKEY_PROVIDERS } = await import("../../src/shared/constants/providers.ts");
-const { REGISTRY: providerRegistry } = await import("../../open-sse/config/providerRegistry.ts");
-const { unwrapClinepassEnvelope } = await import("../../open-sse/utils/clinepassEnvelope.ts");
-const { filterClinepassModels } = await import("../../open-sse/services/clinepassModels.ts");
-const { parseUpstreamError, buildErrorBody } = await import("../../open-sse/utils/error.ts");
-
-// ── Provider metadata (Zod-validated APIKEY catalog) ─────────────────────────
-test("ClinePass is registered as an API-key provider with the canonical identity", () => {
- const cp = APIKEY_PROVIDERS.clinepass;
- assert.ok(cp, "APIKEY_PROVIDERS.clinepass must be defined");
- assert.equal(cp.id, "clinepass");
- assert.equal(cp.alias, "clinepass");
- assert.equal(cp.name, "ClinePass");
- assert.equal(cp.website, "https://cline.bot");
- assert.equal(
- (cp as { notice?: { apiKeyUrl?: string } }).notice?.apiKeyUrl,
- "https://app.cline.bot/settings/api-keys"
- );
-});
-
-test("ClinePass registry entry uses OpenAI format with bearer apikey auth + Cline headers", () => {
- const entry = providerRegistry.clinepass;
- assert.ok(entry, "providerRegistry.clinepass must be defined");
- assert.equal(entry.id, "clinepass");
- assert.equal(entry.format, "openai");
- assert.equal(entry.executor, "default");
- assert.equal(entry.authType, "apikey");
- assert.equal(entry.authHeader, "bearer");
- assert.equal(entry.baseUrl, "https://api.cline.bot/api/v1/chat/completions");
- assert.equal(entry.extraHeaders?.["HTTP-Referer"], "https://cline.bot");
- assert.equal(entry.extraHeaders?.["X-Title"], "Cline");
-});
-
-test("ClinePass models are cline-pass/* and deepseek entries flag reasoning", () => {
- const models = providerRegistry.clinepass.models;
- const ids = models.map((m: { id: string }) => m.id);
- assert.ok(ids.length >= 8, "expect a non-trivial seed list");
- assert.equal(new Set(ids).size, ids.length, "model ids must be unique");
- for (const id of ids) {
- assert.ok(id.startsWith("cline-pass/"), `${id} must be in the cline-pass/ namespace`);
- }
- const deepseek = models.filter((m: { id: string }) => m.id.includes("deepseek"));
- assert.ok(deepseek.length >= 2, "expect the two DeepSeek V4 entries");
- for (const m of deepseek) {
- assert.equal((m as { supportsReasoning?: boolean }).supportsReasoning, true);
- }
-});
-
-// ── Envelope unwrap ──────────────────────────────────────────────────────────
-test("unwrapClinepassEnvelope: success unwraps to data", () => {
- const inner = { id: "chatcmpl-1", choices: [] };
- const { body, error } = unwrapClinepassEnvelope({ success: true, data: inner }, "clinepass");
- assert.equal(error, null);
- assert.deepEqual(body, inner);
-});
-
-test("unwrapClinepassEnvelope: {success:false} yields an error", () => {
- const { body, error } = unwrapClinepassEnvelope(
- { success: false, error: "empty response content", statusCode: 502 },
- "clinepass"
- );
- assert.equal(body, null);
- assert.ok(error);
- assert.equal(error?.message, "empty response content");
- assert.equal(error?.status, 502);
-});
-
-test("unwrapClinepassEnvelope: nested error.message extracted", () => {
- const { error } = unwrapClinepassEnvelope(
- { success: false, error: { message: "quota exceeded" } },
- "clinepass"
- );
- assert.equal(error?.message, "quota exceeded");
-});
-
-test("unwrapClinepassEnvelope: non-clinepass provider passes through untouched", () => {
- const payload = { success: false, error: "boom" };
- const { body, error } = unwrapClinepassEnvelope(payload, "openai");
- assert.equal(error, null);
- assert.deepEqual(body, payload);
-});
-
-test("unwrapClinepassEnvelope: non-object / array / no-success passthrough", () => {
- assert.deepEqual(unwrapClinepassEnvelope("plain", "clinepass"), { body: "plain", error: null });
- assert.deepEqual(unwrapClinepassEnvelope([1, 2], "clinepass"), { body: [1, 2], error: null });
- const bare = { id: "x" };
- assert.deepEqual(unwrapClinepassEnvelope(bare, "clinepass"), { body: bare, error: null });
-});
-
-// ── Model filter ─────────────────────────────────────────────────────────────
-test("filterClinepassModels keeps only cline-pass/* ids", () => {
- const out = filterClinepassModels([
- { id: "cline-pass/glm-5.2", name: "GLM" },
- { id: "openai/gpt-5.5" },
- { id: "cline-pass/deepseek-v4-pro" },
- { notId: true },
- ]);
- assert.deepEqual(out, [
- { id: "cline-pass/glm-5.2", name: "GLM" },
- { id: "cline-pass/deepseek-v4-pro", name: "cline-pass/deepseek-v4-pro" },
- ]);
- assert.deepEqual(filterClinepassModels("not-array"), []);
-});
-
-// ── Error sanitization (Rule #12 — no stack leak) ────────────────────────────
-test("parseUpstreamError unwraps clinepass envelope error without leaking a stack", async () => {
- const upstream = new Response(
- JSON.stringify({ success: false, error: "upstream at /srv/x.js:1:1 failed" }),
- { status: 502, headers: { "content-type": "application/json" } }
- );
- const parsed = await parseUpstreamError(upstream, "clinepass");
- const body = buildErrorBody(502, parsed.message) as { error: { message: string } };
- assert.ok(!body.error.message.includes("at /"), "sanitized error must not include a stack frame");
-});
diff --git a/tests/unit/clinepass-thinking-budget.test.ts b/tests/unit/clinepass-thinking-budget.test.ts
deleted file mode 100644
index db49bac583..0000000000
--- a/tests/unit/clinepass-thinking-budget.test.ts
+++ /dev/null
@@ -1,77 +0,0 @@
-import test from "node:test";
-import assert from "node:assert/strict";
-
-import { DefaultExecutor } from "../../open-sse/executors/default.ts";
-
-// DefaultExecutor.ensureThinkingBudget — clinepass-gated max_tokens floor for
-// reasoning models (prevents empty content when the budget is undersized).
-
-test("bumps undersized max_tokens to 4096 for a clinepass reasoning model", () => {
- const executor = new DefaultExecutor("clinepass");
- const body = {
- model: "cline-pass/deepseek-v4-pro",
- reasoning_effort: "high",
- max_tokens: 512,
- } as Record<string, unknown>;
-
- executor.ensureThinkingBudget(body, "cline-pass/deepseek-v4-pro");
- assert.equal(body.max_tokens, 4096);
-});
-
-test("sets max_tokens floor when absent for a reasoning model", () => {
- const executor = new DefaultExecutor("clinepass");
- const body = {
- model: "cline-pass/deepseek-v4-flash",
- reasoning_effort: "medium",
- } as Record<string, unknown>;
-
- executor.ensureThinkingBudget(body, "cline-pass/deepseek-v4-flash");
- assert.equal(body.max_tokens, 4096);
-});
-
-test("leaves an already-sufficient budget untouched", () => {
- const executor = new DefaultExecutor("clinepass");
- const body = {
- model: "cline-pass/deepseek-v4-pro",
- reasoning_effort: "high",
- max_tokens: 8000,
- } as Record<string, unknown>;
-
- executor.ensureThinkingBudget(body, "cline-pass/deepseek-v4-pro");
- assert.equal(body.max_tokens, 8000);
-});
-
-test("no-op when reasoning is disabled", () => {
- const executor = new DefaultExecutor("clinepass");
- const body = {
- model: "cline-pass/deepseek-v4-pro",
- max_tokens: 100,
- } as Record<string, unknown>;
-
- executor.ensureThinkingBudget(body, "cline-pass/deepseek-v4-pro");
- assert.equal(body.max_tokens, 100);
-});
-
-test("no-op for a non-reasoning clinepass model", () => {
- const executor = new DefaultExecutor("clinepass");
- const body = {
- model: "cline-pass/glm-5.2",
- reasoning_effort: "high",
- max_tokens: 100,
- } as Record<string, unknown>;
-
- executor.ensureThinkingBudget(body, "cline-pass/glm-5.2");
- assert.equal(body.max_tokens, 100);
-});
-
-test("no-op for a non-clinepass provider (gate)", () => {
- const executor = new DefaultExecutor("openrouter");
- const body = {
- model: "cline-pass/deepseek-v4-pro",
- reasoning_effort: "high",
- max_tokens: 100,
- } as Record<string, unknown>;
-
- executor.ensureThinkingBudget(body, "cline-pass/deepseek-v4-pro");
- assert.equal(body.max_tokens, 100);
-});
diff --git a/tests/unit/codex-banked-reset-credits-5199.test.ts b/tests/unit/codex-banked-reset-credits-5199.test.ts
deleted file mode 100644
index b831956bfd..0000000000
--- a/tests/unit/codex-banked-reset-credits-5199.test.ts
+++ /dev/null
@@ -1,200 +0,0 @@
-/**
- * Regression test for Codex "banked reset credits" (issue #5199).
- *
- * DISPLAY ONLY: OmniRoute already calls the ChatGPT backend
- * `/backend-api/wham/usage` endpoint for quota tracking. Some eligibility-gated
- * accounts additionally expose `rate_limit_reset_credits.available_count` (a
- * count of extra rate-limit resets banked on the account) and, optionally,
- * `rate_limit_reached_type` (which window is currently blocking). This test
- * verifies:
- * 1. The field is parsed and surfaced additively when present, across both
- * independent parsers that read this payload (codexUsageQuotas.ts used by
- * the dashboard usage fetcher, and codexQuotaFetcher.ts used by the
- * preflight/monitor fetcher).
- * 2. Existing quota parsing is completely unaffected when the field is
- * absent (fail-open — no throw, no regression to session/weekly/etc).
- *
- * Redemption of banked reset credits is an unofficial, mutating upstream
- * endpoint and is explicitly OUT OF SCOPE — this only reads and surfaces data
- * already present in the existing usage-fetch response.
- */
-import test from "node:test";
-import assert from "node:assert/strict";
-
-import { buildCodexUsageQuotas } from "../../open-sse/services/codexUsageQuotas.ts";
-import { getCodexUsage } from "../../open-sse/services/usage/codex.ts";
-import {
- fetchCodexQuota,
- invalidateCodexQuotaCache,
- registerCodexConnection,
- unregisterCodexConnection,
-} from "../../open-sse/services/codexQuotaFetcher.ts";
-
-const originalFetch = globalThis.fetch;
-
-test.afterEach(() => {
- globalThis.fetch = originalFetch;
-});
-
-// ─── codexUsageQuotas.ts (dashboard usage-fetch path) ──────────────────────
-
-test("buildCodexUsageQuotas surfaces bankedResetCredits when present", () => {
- const { quotas, bankedResetCredits, rateLimitReachedType } = buildCodexUsageQuotas({
- rate_limit: {
- primary_window: { used_percent: 10 },
- secondary_window: { used_percent: 20 },
- },
- rate_limit_reset_credits: { available_count: 3 },
- rate_limit_reached_type: { type: "secondary_window" },
- });
-
- assert.equal(bankedResetCredits, 3);
- assert.equal(rateLimitReachedType, "secondary_window");
- // Existing quotas remain intact.
- assert.equal(quotas.session?.used, 10);
- assert.equal(quotas.weekly?.used, 20);
-});
-
-test("buildCodexUsageQuotas tolerates camelCase field shape", () => {
- const { bankedResetCredits, rateLimitReachedType } = buildCodexUsageQuotas({
- rateLimit: { primaryWindow: { usedPercent: 5 } },
- rateLimitResetCredits: { availableCount: 7 },
- rateLimitReachedType: "primary_window",
- });
-
- assert.equal(bankedResetCredits, 7);
- assert.equal(rateLimitReachedType, "primary_window");
-});
-
-test("buildCodexUsageQuotas leaves bankedResetCredits undefined when absent (fail-open)", () => {
- const result = buildCodexUsageQuotas({
- rate_limit: {
- primary_window: { used_percent: 10 },
- secondary_window: { used_percent: 20 },
- },
- });
-
- assert.equal(result.bankedResetCredits, undefined);
- assert.equal(result.rateLimitReachedType, undefined);
- // Existing quota parsing is unaffected — no throw, no missing windows.
- assert.equal(result.quotas.session?.used, 10);
- assert.equal(result.quotas.weekly?.used, 20);
-});
-
-test("buildCodexUsageQuotas never throws on a garbage rate_limit_reset_credits shape", () => {
- assert.doesNotThrow(() => {
- const result = buildCodexUsageQuotas({
- rate_limit: { primary_window: { used_percent: 1 } },
- rate_limit_reset_credits: "not-an-object",
- rate_limit_reached_type: 12345,
- });
- assert.equal(result.bankedResetCredits, undefined);
- assert.equal(result.rateLimitReachedType, undefined);
- });
-});
-
-// ─── usage/codex.ts (getCodexUsage — full dashboard fetch) ─────────────────
-
-test("getCodexUsage threads bankedResetCredits through additively", async () => {
- globalThis.fetch = async () =>
- new Response(
- JSON.stringify({
- plan_type: "plus",
- rate_limit: {
- primary_window: { used_percent: 15 },
- secondary_window: { used_percent: 25 },
- },
- rate_limit_reset_credits: { available_count: 2 },
- }),
- { status: 200, headers: { "content-type": "application/json" } }
- );
-
- const usage = await getCodexUsage("token", { workspaceId: "ws-1" });
-
- assert.equal((usage as any).plan, "plus");
- assert.equal((usage as any).bankedResetCredits, 2);
- assert.equal((usage as any).quotas.session.used, 15);
- assert.equal((usage as any).quotas.weekly.used, 25);
-});
-
-test("getCodexUsage omits bankedResetCredits and stays intact when absent", async () => {
- globalThis.fetch = async () =>
- new Response(
- JSON.stringify({
- plan_type: "plus",
- rate_limit: {
- primary_window: { used_percent: 15 },
- secondary_window: { used_percent: 25 },
- },
- }),
- { status: 200, headers: { "content-type": "application/json" } }
- );
-
- const usage = await getCodexUsage("token", { workspaceId: "ws-1" });
-
- assert.equal("bankedResetCredits" in (usage as any), false);
- assert.equal((usage as any).quotas.session.used, 15);
- assert.equal((usage as any).quotas.weekly.used, 25);
-});
-
-// ─── codexQuotaFetcher.ts (preflight/monitor path) ─────────────────────────
-
-test("fetchCodexQuota surfaces bankedResetCredits from the dual-window parser", async () => {
- const connectionId = `codex-banked-${Date.now()}`;
-
- globalThis.fetch = async () =>
- new Response(
- JSON.stringify({
- rate_limit: {
- primary_window: { used_percent: 70, reset_after_seconds: 45 },
- secondary_window: { used_percent: 20, reset_after_seconds: 300 },
- },
- rate_limit_reset_credits: { available_count: 4 },
- rate_limit_reached_type: { type: "primary_window" },
- }),
- { status: 200, headers: { "content-type": "application/json" } }
- );
-
- const quota = await fetchCodexQuota(connectionId, {
- accessToken: "token",
- providerSpecificData: { workspaceId: "ws" },
- });
-
- assert.ok(quota);
- assert.equal(quota?.bankedResetCredits, 4);
- assert.equal(quota?.rateLimitReachedType, "primary_window");
- // Existing dual-window parsing stays intact.
- assert.equal(quota?.window5h.percentUsed, 0.7);
- assert.equal(quota?.window7d.percentUsed, 0.2);
-
- invalidateCodexQuotaCache(connectionId);
- unregisterCodexConnection(connectionId);
-});
-
-test("fetchCodexQuota omits bankedResetCredits when the payload does not have it (fail-open)", async () => {
- const connectionId = `codex-nobanked-${Date.now()}`;
-
- registerCodexConnection(connectionId, { accessToken: "token" });
-
- globalThis.fetch = async () =>
- new Response(
- JSON.stringify({
- rate_limit: {
- primary_window: { used_percent: 30 },
- secondary_window: { used_percent: 10 },
- },
- }),
- { status: 200, headers: { "content-type": "application/json" } }
- );
-
- const quota = await fetchCodexQuota(connectionId);
-
- assert.ok(quota);
- assert.equal(quota?.bankedResetCredits, undefined);
- assert.equal(quota?.rateLimitReachedType, undefined);
- assert.equal(quota?.window5h.percentUsed, 0.3);
- assert.equal(quota?.window7d.percentUsed, 0.1);
-
- invalidateCodexQuotaCache(connectionId);
- unregisterCodexConnection(connectionId);
-});
diff --git a/tests/unit/codex-executor-split.test.ts b/tests/unit/codex-executor-split.test.ts
deleted file mode 100644
index eac6b2eea0..0000000000
--- a/tests/unit/codex-executor-split.test.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import { test } from "node:test";
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { fileURLToPath } from "node:url";
-import { dirname, join } from "node:path";
-
-// Split-guard for the codex executor quota extraction.
-// The pure quota-snapshot parsing + reset/cooldown scheduling lives in codex/quota.ts.
-// Host re-exports the 4 public symbols (chatCore/codexQuota.ts + tests import them).
-const HERE = dirname(fileURLToPath(import.meta.url));
-const EXE = join(HERE, "../../open-sse/executors");
-const HOST = join(EXE, "codex.ts");
-const LEAF = join(EXE, "codex/quota.ts");
-
-test("leaf hosts the quota helpers and does not import the host", () => {
- const src = readFileSync(LEAF, "utf8");
- for (const sym of [
- "parseCodexQuotaHeaders",
- "getCodexResetTime",
- "getCodexDualWindowCooldownMs",
- "CodexQuotaSnapshot",
- ]) {
- assert.match(src, new RegExp(`export (function|interface) ${sym}\\b`));
- }
- assert.doesNotMatch(src, /from "\.\.\/codex\.ts"/);
-});
-
-test("host re-exports the quota symbols for external importers", () => {
- const host = readFileSync(HOST, "utf8");
- assert.match(host, /from "\.\/codex\/quota\.ts"/);
-});
-
-test("parseCodexQuotaHeaders returns null without quota headers", async () => {
- const { parseCodexQuotaHeaders } = await import("../../open-sse/executors/codex/quota.ts");
- assert.equal(parseCodexQuotaHeaders({}), null);
-});
diff --git a/tests/unit/codex-import-token-route.test.ts b/tests/unit/codex-import-token-route.test.ts
deleted file mode 100644
index 83f2c8ad3f..0000000000
--- a/tests/unit/codex-import-token-route.test.ts
+++ /dev/null
@@ -1,143 +0,0 @@
-// Route-wiring tests for /api/oauth/codex/import-token (#1290).
-//
-// Imports a Codex connection from a bare ChatGPT access token — no refresh
-// token required. Auth is disabled via settings (requireLogin:false) so we
-// reach the schema/decode logic rather than a 401. DB handles are released
-// in test.after (CLAUDE.md learning: unreleased SQLite handles hang node:test).
-
-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-import-token-"));
-process.env.DATA_DIR = TEST_DATA_DIR;
-
-const core = await import("../../src/lib/db/core.ts");
-const settingsDb = await import("../../src/lib/db/settings.ts");
-const providersDb = await import("../../src/lib/db/providers.ts");
-const route = await import("../../src/app/api/oauth/codex/import-token/route.ts");
-
-function b64url(obj: unknown): string {
- return Buffer.from(JSON.stringify(obj))
- .toString("base64")
- .replace(/=+$/, "")
- .replace(/\+/g, "-")
- .replace(/\//g, "_");
-}
-
-function makeJwt(payload: Record<string, unknown>): string {
- const header = b64url({ alg: "RS256", typ: "JWT" });
- const body = b64url(payload);
- return `${header}.${body}.signature`;
-}
-
-test.before(async () => {
- await settingsDb.updateSettings({ requireLogin: false });
-});
-
-test.after(async () => {
- core.resetDbInstance();
- fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
-});
-
-async function postImportToken(body: unknown) {
- const request = new Request("http://localhost:20128/api/oauth/codex/import-token", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(body),
- });
- const response = await route.POST(request);
- return { status: response.status, body: await response.json() };
-}
-
-test("import-token: decodes email + workspace claims from the access token and creates a connection", async () => {
- const accessToken = makeJwt({
- email: "[email protected]",
- "https://api.openai.com/auth": {
- chatgpt_account_id: "acct-bare",
- chatgpt_plan_type: "plus",
- },
- });
-
- const { status, body } = await postImportToken({ accessToken });
- assert.equal(status, 200);
- assert.equal(body.success, true);
- assert.equal(body.connection.provider, "codex");
- assert.equal(body.connection.email, "[email protected]");
-
- const rows = await providersDb.getProviderConnections({ provider: "codex" });
- const created = rows.find((r) => r.id === body.connection.id);
- assert.equal(created?.authType, "access_token");
- assert.equal(created?.accessToken, accessToken);
- assert.ok(!created?.refreshToken, "no refresh token should be persisted");
- assert.deepEqual(created?.providerSpecificData, {
- chatgptAccountId: "acct-bare",
- chatgptPlanType: "plus",
- });
-});
-
-test("import-token: falls back to the explicit `name` when the JWT carries no email", async () => {
- const accessToken = makeJwt({
- "https://api.openai.com/auth": { chatgpt_account_id: "acct-noemail" },
- });
-
- const { status, body } = await postImportToken({ accessToken, name: "My Bare Token" });
- assert.equal(status, 200);
- assert.equal(body.connection.name, "My Bare Token");
-});
-
-test("import-token: missing accessToken fails schema validation with 400", async () => {
- const { status, body } = await postImportToken({});
- assert.equal(status, 400);
- assert.ok(typeof body.error.message === "string" && body.error.message.length > 0);
-});
-
-test("import-token: empty-string accessToken fails schema validation with 400", async () => {
- const { status } = await postImportToken({ accessToken: " " });
- assert.equal(status, 400);
-});
-
-test("import-token: undecodable token with no name and no claims is rejected with 400", async () => {
- const { status, body } = await postImportToken({ accessToken: "not-a-jwt" });
- assert.equal(status, 400);
- assert.match(body.error.message, /decode|account info/i);
-});
-
-test("import-token: undecodable token IS accepted when an explicit name is supplied", async () => {
- const { status, body } = await postImportToken({
- accessToken: "not-a-jwt-but-thats-ok",
- name: "Manually Labeled",
- });
- assert.equal(status, 200);
- assert.equal(body.connection.name, "Manually Labeled");
-});
-
-test("import-token: malformed JSON body is rejected with 400", async () => {
- const request = new Request("http://localhost:20128/api/oauth/codex/import-token", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: "{not json",
- });
- const response = await route.POST(request);
- assert.equal(response.status, 400);
-});
-
-test("import-token: repeated imports for the same email never dedup (each is a new connection)", async () => {
- const tokenA = makeJwt({ email: "[email protected]" });
- const tokenB = makeJwt({ email: "[email protected]" });
-
- const first = await postImportToken({ accessToken: tokenA });
- const second = await postImportToken({ accessToken: tokenB });
-
- assert.equal(first.status, 200);
- assert.equal(second.status, 200);
- assert.notEqual(first.body.connection.id, second.body.connection.id);
-});
-
-test("import-token: error responses never leak a stack trace", async () => {
- const { body } = await postImportToken({});
- assert.ok(!JSON.stringify(body).includes("at /"), "must not leak a stack trace");
- assert.ok(!JSON.stringify(body).includes(".ts:"), "must not leak a source location");
-});
diff --git a/tests/unit/codex-session-affinity-reset-aware-5903.test.ts b/tests/unit/codex-session-affinity-reset-aware-5903.test.ts
deleted file mode 100644
index 02f4ef6f1f..0000000000
--- a/tests/unit/codex-session-affinity-reset-aware-5903.test.ts
+++ /dev/null
@@ -1,181 +0,0 @@
-// #5903: Codex session affinity must win over a per-request reset-aware
-// re-scoring. The reset-aware combo strategy (open-sse/services/combo/quotaStrategies.ts)
-// recomputes its "winner" connection on every request and hands it to
-// getProviderCredentials as forcedConnectionId (src/sse/handlers/chat.ts).
-// Before the fix, forcedConnectionId narrowed the connection pool BEFORE
-// session affinity was consulted, so a fresh quota-scoring winner silently
-// evicted the existing pin (deleteSessionAccountAffinity) on every request —
-// breaking "same session -> reuse pinned account".
-//
-// This test drives auth.getProviderCredentials directly (the same call shape
-// chat.ts uses: sessionKey + forcedConnectionId together) to reproduce the
-// bug without needing the full combo/quota-scoring machinery.
-
-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-affinity-5903-"));
-process.env.DATA_DIR = TEST_DATA_DIR;
-process.env.API_KEY_SECRET = process.env.API_KEY_SECRET || "codex-affinity-5903-test-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 affinityDb = await import("../../src/lib/db/sessionAccountAffinity.ts");
-const auth = await import("../../src/sse/services/auth.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: any = {}) {
- return providersDb.createProviderConnection({
- provider,
- authType: overrides.authType || "oauth",
- name: overrides.name || `${provider}-${Math.random().toString(16).slice(2, 8)}`,
- accessToken: overrides.accessToken || `at-${Math.random().toString(16).slice(2, 10)}`,
- refreshToken: overrides.refreshToken,
- isActive: overrides.isActive ?? true,
- testStatus: overrides.testStatus || "active",
- priority: overrides.priority,
- providerSpecificData: overrides.providerSpecificData || {},
- });
-}
-
-test.beforeEach(async () => {
- await resetStorage();
-});
-
-test.after(async () => {
- core.resetDbInstance();
- apiKeysDb.resetApiKeyState();
- fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
-});
-
-test("codex session affinity wins over a per-request reset-aware forcedConnectionId (#5903)", async () => {
- await settingsDb.updateSettings({
- fallbackStrategy: "reset-aware",
- codexSessionAffinityTtlMs: 60_000,
- });
-
- const connectionA = await seedConnection("codex", { name: "codex-reset-aware-a" });
- const connectionB = await seedConnection("codex", { name: "codex-reset-aware-b" });
-
- // Request 1: reset-aware quota scoring picks A as the winner for session S.
- const request1 = await auth.getProviderCredentials("codex", null, null, "gpt-5.5", {
- sessionKey: "session-S",
- forcedConnectionId: connectionA.id,
- });
- assert.equal(request1?.connectionId, connectionA.id, "request 1 should pin to the scored winner A");
- assert.equal(
- affinityDb.getSessionAccountAffinity("session-S", "codex", 60_000)?.connectionId,
- connectionA.id,
- "affinity row must be created for session-S pointing at A"
- );
-
- // Request 2: quota state shifted and reset-aware now scores B higher for
- // the SAME session. Without the fix, forcedConnectionId=B narrows the pool
- // to just B before affinity is checked, evicting the A pin and re-pinning
- // to B. With the fix, the existing active pin (A) must win.
- const request2 = await auth.getProviderCredentials("codex", null, null, "gpt-5.5", {
- sessionKey: "session-S",
- forcedConnectionId: connectionB.id,
- });
- assert.equal(
- request2?.connectionId,
- connectionA.id,
- "request 2 must still use the pinned connection A, not the freshly re-scored B"
- );
- assert.equal(
- affinityDb.getSessionAccountAffinity("session-S", "codex", 60_000)?.connectionId,
- connectionA.id,
- "affinity row for session-S must remain pinned to A after re-scoring"
- );
-
- // A brand-new session (S2) has no existing pin, so the freshly re-scored
- // winner (B) must be honored and a NEW pin created for S2.
- const request3 = await auth.getProviderCredentials("codex", null, null, "gpt-5.5", {
- sessionKey: "session-S2",
- forcedConnectionId: connectionB.id,
- });
- assert.equal(request3?.connectionId, connectionB.id, "a new session must honor the fresh re-scored pick");
- assert.equal(
- affinityDb.getSessionAccountAffinity("session-S2", "codex", 60_000)?.connectionId,
- connectionB.id,
- "a new affinity row for session-S2 must be created pointing at B"
- );
-
- // Session S must remain unaffected by S2's independent pin.
- assert.equal(
- affinityDb.getSessionAccountAffinity("session-S", "codex", 60_000)?.connectionId,
- connectionA.id,
- "session-S pin must stay isolated from session-S2"
- );
-});
-
-test("reset-aware forcedConnectionId is honored when the pinned connection becomes ineligible (#5903)", async () => {
- await settingsDb.updateSettings({
- fallbackStrategy: "reset-aware",
- codexSessionAffinityTtlMs: 60_000,
- });
-
- const connectionA = await seedConnection("codex", { name: "codex-reset-aware-ineligible-a" });
- const connectionB = await seedConnection("codex", { name: "codex-reset-aware-ineligible-b" });
-
- const request1 = await auth.getProviderCredentials("codex", null, null, "gpt-5.5", {
- sessionKey: "session-failover",
- forcedConnectionId: connectionA.id,
- });
- assert.equal(request1?.connectionId, connectionA.id);
-
- // A becomes rate-limited (e.g. 429 handled by markAccountUnavailable in
- // production). Reset-aware re-scores and now forces B. The pin (A) is no
- // longer eligible, so the freshly forced B must be used instead of
- // failing the whole request.
- await providersDb.updateProviderConnection(connectionA.id, {
- rateLimitedUntil: new Date(Date.now() + 60_000).toISOString(),
- });
-
- const request2 = await auth.getProviderCredentials("codex", null, null, "gpt-5.5", {
- sessionKey: "session-failover",
- forcedConnectionId: connectionB.id,
- });
- assert.equal(
- request2?.connectionId,
- connectionB.id,
- "an ineligible pin must fall through to the freshly forced connection"
- );
-});
-
-test("no session affinity configured: reset-aware forcedConnectionId applies exactly as before (#5903)", async () => {
- await settingsDb.updateSettings({
- fallbackStrategy: "reset-aware",
- codexSessionAffinityTtlMs: 0,
- });
-
- const connectionA = await seedConnection("codex", { name: "codex-no-affinity-a" });
- const connectionB = await seedConnection("codex", { name: "codex-no-affinity-b" });
-
- const request1 = await auth.getProviderCredentials("codex", null, null, "gpt-5.5", {
- sessionKey: "session-no-ttl",
- forcedConnectionId: connectionA.id,
- });
- assert.equal(request1?.connectionId, connectionA.id);
-
- const request2 = await auth.getProviderCredentials("codex", null, null, "gpt-5.5", {
- sessionKey: "session-no-ttl",
- forcedConnectionId: connectionB.id,
- });
- assert.equal(
- request2?.connectionId,
- connectionB.id,
- "with affinity disabled (ttl=0) each request must honor the fresh forcedConnectionId"
- );
-});
diff --git a/tests/unit/codex-tools-split.test.ts b/tests/unit/codex-tools-split.test.ts
deleted file mode 100644
index e3cfc467f6..0000000000
--- a/tests/unit/codex-tools-split.test.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import { test } from "node:test";
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { fileURLToPath } from "node:url";
-import { dirname, join } from "node:path";
-
-// Split-guard for the codex executor tool-normalization extraction.
-// The hosted-tool passthrough + free-plan gating live in codex/tools.ts (self-contained,
-// console.debug only). codex.ts re-exports them so external importers keep the path.
-const HERE = dirname(fileURLToPath(import.meta.url));
-const EXE = join(HERE, "../../open-sse/executors");
-
-test("leaf hosts the tool normalizers and does not import the host", () => {
- const src = readFileSync(join(EXE, "codex/tools.ts"), "utf8");
- assert.match(src, /export function normalizeCodexTools\b/);
- assert.match(src, /export function isCodexFreePlan\b/);
- assert.doesNotMatch(src, /from "\.\.\/codex\.ts"/);
-});
-
-test("codex.ts re-exports them for external importers", () => {
- const host = readFileSync(join(EXE, "codex.ts"), "utf8");
- assert.match(host, /export \{[^}]*normalizeCodexTools[^}]*\} from "\.\/codex\/tools\.ts"/s);
-});
-
-test("both import paths resolve to the same function", async () => {
- const viaHost = (await import("../../open-sse/executors/codex.ts")).normalizeCodexTools;
- const viaLeaf = (await import("../../open-sse/executors/codex/tools.ts")).normalizeCodexTools;
- assert.equal(viaHost, viaLeaf);
-});
diff --git a/tests/unit/codex-verbosity.test.ts b/tests/unit/codex-verbosity.test.ts
index 7869f5aea9..b23814c04d 100644
--- a/tests/unit/codex-verbosity.test.ts
+++ b/tests/unit/codex-verbosity.test.ts
@@ -37,19 +37,10 @@ test("invalid verbosity is dropped and text removed", () => {
assert.equal(body.verbosity, undefined);
});
-test("no verbosity + Responses text.format is preserved", () => {
- const format = { type: "json_schema", name: "schema", schema: { type: "object" } };
- const body: Record<string, unknown> = { text: { format }, input: [] };
+test("no verbosity + stray non-verbosity text → text removed (status quo)", () => {
+ const body: Record<string, unknown> = { text: { format: { type: "json" } }, input: [] };
normalizeCodexVerbosity(body);
- assert.deepEqual(body.text, { format });
-});
-
-test("verbosity is merged with existing Responses text.format", () => {
- const format = { type: "json_schema", name: "schema", schema: { type: "object" } };
- const body: Record<string, unknown> = { verbosity: "low", text: { format }, input: [] };
- normalizeCodexVerbosity(body);
- assert.deepEqual(body.text, { format, verbosity: "low" });
- assert.equal(body.verbosity, undefined);
+ assert.equal(body.text, undefined);
});
test("verbosity is normalized case-insensitively", () => {
diff --git a/tests/unit/combo-apply-strategy-ordering-split.test.ts b/tests/unit/combo-apply-strategy-ordering-split.test.ts
deleted file mode 100644
index 858d7ed3fe..0000000000
--- a/tests/unit/combo-apply-strategy-ordering-split.test.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-import { test, after } from "node:test";
-import assert from "node:assert/strict";
-
-import { applyStrategyOrdering } from "@omniroute/open-sse/services/combo/applyStrategyOrdering.ts";
-import { resetDbInstance } from "@/lib/db/core.ts";
-
-// Split guard for Block J Task 3: the non-`auto` strategy-ordering chain
-// (lkgp / strict-random / random / fill-first / p2c / ... / quota-share) was
-// extracted verbatim into applyStrategyOrdering. These tests pin the exits that
-// need no DB/deck state (random / fill-first / unknown); the DB-backed branches
-// (lkgp, reset-*, quota-share) are covered end-to-end by the 47 consumer tests
-// (router-strategies / combo-strategy-fallbacks / rr-session-stickiness).
-
-after(() => {
- // some branches (lkgp/quota-share) may touch the DB singleton; release handles.
- resetDbInstance();
-});
-
-const noopLog = { info() {}, warn() {}, error() {}, debug() {} } as never;
-
-const target = (provider: string, modelStr: string): never =>
- ({
- kind: "model",
- stepId: "s1",
- executionKey: `${provider}>${modelStr}`,
- modelStr,
- provider,
- providerId: null,
- connectionId: null,
- weight: 1,
- label: null,
- }) as never;
-
-const deps = () =>
- ({
- combo: { id: "c1", name: "c1", config: {} },
- config: {},
- body: { messages: [] },
- log: noopLog,
- apiKeyAllowedConnections: null,
- }) as never;
-
-const keys = (arr: Array<{ executionKey: string }>) => arr.map((t) => t.executionKey).sort();
-
-test("exports applyStrategyOrdering", () => {
- assert.equal(typeof applyStrategyOrdering, "function");
-});
-
-test("unknown strategy -> input order unchanged (same reference contents)", async () => {
- const input = [target("openai", "gpt-4o"), target("anthropic", "claude-3")];
- const out = await applyStrategyOrdering("no-such-strategy", input, deps());
- assert.deepEqual(
- out.map((t: { executionKey: string }) => t.executionKey),
- ["openai>gpt-4o", "anthropic>claude-3"]
- );
-});
-
-test("fill-first -> preserves priority order", async () => {
- const input = [target("a", "m1"), target("b", "m2"), target("c", "m3")];
- const out = await applyStrategyOrdering("fill-first", input, deps());
- assert.deepEqual(
- out.map((t: { executionKey: string }) => t.executionKey),
- ["a>m1", "b>m2", "c>m3"]
- );
-});
-
-test("random -> same multiset of targets (a permutation)", async () => {
- const input = [target("a", "m1"), target("b", "m2"), target("c", "m3")];
- const out = await applyStrategyOrdering("random", input, deps());
- assert.equal(out.length, 3);
- assert.deepEqual(keys(out), keys(input));
-});
diff --git a/tests/unit/combo-auto-config-split.test.ts b/tests/unit/combo-auto-config-split.test.ts
deleted file mode 100644
index a833cae0c4..0000000000
--- a/tests/unit/combo-auto-config-split.test.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-import { test } from "node:test";
-import assert from "node:assert/strict";
-
-import { parseAutoConfig } from "@omniroute/open-sse/services/combo/autoConfig.ts";
-import { DEFAULT_WEIGHTS } from "@omniroute/open-sse/services/autoCombo/scoring.ts";
-
-// Split guard for Block J Task 2: parseAutoConfig was extracted verbatim from
-// handleComboChat's inline auto-strategy config block. These assertions pin the
-// pure derivation so the extraction stays behavior-identical.
-
-const target = (provider: string, modelStr: string) =>
- ({ provider, modelStr, executionKey: `${provider}>${modelStr}` }) as never;
-
-test("defaults: rules strategy, provider-derived pool, default weights", () => {
- const cfg = parseAutoConfig({ name: "c", config: {} } as never, [
- target("openai", "gpt-4o"),
- target("anthropic", "claude-3"),
- target("openai", "gpt-4o-mini"),
- ]);
- assert.equal(cfg.routingStrategy, "rules");
- assert.deepEqual(cfg.candidatePool, ["openai", "anthropic"]);
- assert.equal(cfg.weights, DEFAULT_WEIGHTS);
- assert.equal(cfg.explorationRate, 0.05);
- assert.equal(cfg.budgetCap, undefined);
- assert.equal(cfg.modePack, undefined);
-});
-
-test("routerStrategy takes precedence over routingStrategy/strategyName", () => {
- const cfg = parseAutoConfig(
- {
- name: "c",
- autoConfig: {
- routerStrategy: "lkgp",
- routingStrategy: "cost",
- strategyName: "p2c",
- },
- } as never,
- []
- );
- assert.equal(cfg.routingStrategy, "lkgp");
-});
-
-test("explicit candidatePool, weights, exploration and budget are honored", () => {
- const customWeights = { latency: 1 } as never;
- const cfg = parseAutoConfig(
- {
- name: "c",
- autoConfig: {
- candidatePool: ["glm", "openai"],
- weights: customWeights,
- explorationRate: 0.3,
- budgetCap: 5,
- modePack: "coding",
- },
- } as never,
- [target("ignored", "x")]
- );
- assert.deepEqual(cfg.candidatePool, ["glm", "openai"]);
- assert.equal(cfg.weights, customWeights);
- assert.equal(cfg.explorationRate, 0.3);
- assert.equal(cfg.budgetCap, 5);
- assert.equal(cfg.modePack, "coding");
-});
-
-test("config.auto is preferred over top-level config", () => {
- const cfg = parseAutoConfig(
- { name: "c", config: { auto: { routerStrategy: "cost" }, routerStrategy: "rules" } } as never,
- []
- );
- assert.equal(cfg.routingStrategy, "cost");
-});
-
-test("non-finite explorationRate falls back to 0.05", () => {
- const cfg = parseAutoConfig(
- { name: "c", autoConfig: { explorationRate: "not-a-number" } } as never,
- []
- );
- assert.equal(cfg.explorationRate, 0.05);
-});
diff --git a/tests/unit/combo-priority-quota-exhaustion-cutoff-5923.test.ts b/tests/unit/combo-priority-quota-exhaustion-cutoff-5923.test.ts
deleted file mode 100644
index 252c9cef3b..0000000000
--- a/tests/unit/combo-priority-quota-exhaustion-cutoff-5923.test.ts
+++ /dev/null
@@ -1,183 +0,0 @@
-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";
-
-/**
- * #5923 (Finding #4) — the quota-exhaustion preflight cutoff only ran for
- * strategy === "auto" (buildAutoCandidates / routableCandidates in combo.ts).
- * Priority/weighted/etc. strategies funneled through the shared executeTarget
- * per-target loop, which only checked the provider circuit breaker + model
- * lockout — never a per-(provider, connection) quota-exhaustion cutoff. A 0%-
- * remaining connection stayed eligible as the lead leg until it reactively
- * 429'd.
- *
- * Regression guard: with the quota-exhaustion opt-in enabled
- * (`resilienceSettings.quotaPreflight.enabled = true`), a "priority" combo
- * whose first-listed connection is at 0% remaining must skip straight to the
- * sibling connection of the SAME provider — never dispatching to the
- * exhausted connection. This must stay strictly per-connection: it must NOT
- * touch the provider circuit breaker (both connections belong to the same
- * provider, and the healthy one must remain fully eligible).
- */
-const TEST_DATA_DIR = fs.mkdtempSync(
- path.join(os.tmpdir(), "omniroute-quota-cutoff-priority-5923-")
-);
-process.env.DATA_DIR = TEST_DATA_DIR;
-
-const dbCore = await import("../../src/lib/db/core.ts");
-const { handleComboChat } = await import("../../open-sse/services/combo.ts");
-const { registerQuotaFetcher } = await import("../../open-sse/services/quotaPreflight.ts");
-const { getCircuitBreaker } = await import("../../src/shared/utils/circuitBreaker.ts");
-
-test.after(() => {
- dbCore.resetDbInstance();
- fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
-});
-
-function makeLog() {
- return {
- info() {},
- warn() {},
- debug() {},
- error() {},
- };
-}
-
-function okResponse(model: string) {
- return Response.json({ choices: [{ message: { role: "assistant", content: model } }] });
-}
-
-const PROVIDER = "openai";
-const EXHAUSTED_CONNECTION_ID = "conn-exhausted-5923";
-const HEALTHY_CONNECTION_ID = "conn-healthy-5923";
-
-test("#5923 priority combo skips a 0%-remaining lead connection but keeps the sibling connection eligible", async () => {
- registerQuotaFetcher(PROVIDER, async (connectionId: string) => {
- if (connectionId === EXHAUSTED_CONNECTION_ID) {
- return { used: 100, total: 100, percentUsed: 1 };
- }
- return { used: 5, total: 100, percentUsed: 0.05 };
- });
-
- const combo = {
- name: `priority-quota-cutoff-5923-${Date.now()}`,
- strategy: "priority",
- models: [
- {
- kind: "model",
- provider: PROVIDER,
- providerId: PROVIDER,
- model: "gpt-4o-mini",
- connectionId: EXHAUSTED_CONNECTION_ID,
- id: "step-a",
- },
- {
- kind: "model",
- provider: PROVIDER,
- providerId: PROVIDER,
- model: "gpt-4o-mini",
- connectionId: HEALTHY_CONNECTION_ID,
- id: "step-b",
- },
- ],
- };
-
- const calls: Array<string | null> = [];
- const response = await handleComboChat({
- body: { model: combo.name, messages: [{ role: "user", content: "hi" }] },
- combo,
- allCombos: [combo],
- isModelAvailable: undefined,
- relayOptions: undefined,
- signal: undefined,
- settings: {
- resilienceSettings: {
- quotaPreflight: {
- enabled: true,
- defaultThresholdPercent: 2,
- warnThresholdPercent: 20,
- },
- },
- },
- log: makeLog(),
- handleSingleModel: async (
- _body: unknown,
- modelStr: string,
- target?: { connectionId?: string | null }
- ) => {
- calls.push(target?.connectionId ?? null);
- return okResponse(modelStr);
- },
- } as Parameters<typeof handleComboChat>[0]);
-
- assert.equal(response.status, 200);
- assert.ok(calls.length > 0, "expected at least one dispatched target");
- assert.equal(
- calls[0],
- HEALTHY_CONNECTION_ID,
- "the 0%-remaining lead connection must be skipped; the sibling connection must be dispatched instead"
- );
- assert.ok(
- !calls.includes(EXHAUSTED_CONNECTION_ID),
- "the exhausted connection must never be dispatched to"
- );
-
- // Strictly per-connection — the provider circuit breaker must stay CLOSED.
- // Only one connection was skipped; the provider itself never failed.
- assert.equal(
- getCircuitBreaker(PROVIDER).getStatus().state,
- "CLOSED",
- "quota-exhaustion cutoff must never trip the whole-provider circuit breaker"
- );
-});
-
-test("#5923 priority combo does NOT skip a 0%-remaining connection when the cutoff setting is disabled (default)", async () => {
- const provider = "openai";
- const exhaustedConnectionId = "conn-exhausted-disabled-5923";
- registerQuotaFetcher(provider, async () => ({ used: 100, total: 100, percentUsed: 1 }));
-
- const combo = {
- name: `priority-quota-cutoff-disabled-5923-${Date.now()}`,
- strategy: "priority",
- models: [
- {
- kind: "model",
- provider,
- providerId: provider,
- model: "gpt-4o-mini",
- connectionId: exhaustedConnectionId,
- id: "step-a",
- },
- ],
- };
-
- const calls: Array<string | null> = [];
- const response = await handleComboChat({
- body: { model: combo.name, messages: [{ role: "user", content: "hi" }] },
- combo,
- allCombos: [combo],
- isModelAvailable: undefined,
- relayOptions: undefined,
- signal: undefined,
- // No resilienceSettings override → quotaPreflight.enabled defaults to false (opt-in).
- settings: {},
- log: makeLog(),
- handleSingleModel: async (
- _body: unknown,
- modelStr: string,
- target?: { connectionId?: string | null }
- ) => {
- calls.push(target?.connectionId ?? null);
- return okResponse(modelStr);
- },
- } as Parameters<typeof handleComboChat>[0]);
-
- assert.equal(response.status, 200);
- assert.deepEqual(
- calls,
- [exhaustedConnectionId],
- "with the cutoff setting OFF (default), the exhausted connection must still be dispatched to (unchanged auto-off behavior)"
- );
-});
diff --git a/tests/unit/combo-resolve-auto-strategy-split.test.ts b/tests/unit/combo-resolve-auto-strategy-split.test.ts
deleted file mode 100644
index 7ffceeae16..0000000000
--- a/tests/unit/combo-resolve-auto-strategy-split.test.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-import { test, after } from "node:test";
-import assert from "node:assert/strict";
-
-import { resolveAutoStrategyOrder } from "@omniroute/open-sse/services/combo/resolveAutoStrategy.ts";
-import { resetDbInstance } from "@/lib/db/core.ts";
-
-// resolveAutoStrategyOrder loads the LKGP via the DB singleton (dynamic import);
-// release the handle so the node:test runner does not hang on teardown (learning #3).
-after(() => {
- resetDbInstance();
-});
-
-// Split guard for Block J Task 2 (coupled slice): the `if (strategy === "auto")`
-// branch of handleComboChat was extracted verbatim into resolveAutoStrategyOrder,
-// with `buildAutoCandidates` injected (it lives in combo.ts, so a direct import
-// would cycle). These tests pin the DI contract and the two control-flow exits
-// that the host now forwards: an early 429 Response, and the default-ordering
-// pass-through. The routable-selection path is covered end-to-end by the 60
-// consumer tests (router-strategies / auto-combo-engine / combo-strategy-fallbacks).
-
-const noopLog = {
- info() {},
- warn() {},
- error() {},
- debug() {},
-} as never;
-
-const target = (provider: string, modelStr: string): never =>
- ({
- kind: "model",
- stepId: "s1",
- executionKey: `${provider}>${modelStr}`,
- modelStr,
- provider,
- providerId: null,
- connectionId: null,
- weight: 1,
- label: null,
- }) as never;
-
-const baseDeps = (buildAutoCandidates: never) =>
- ({
- orderedTargets: [target("openai", "gpt-4o"), target("anthropic", "claude-3")],
- body: { messages: [{ role: "user", content: "hi" }] },
- combo: { id: "c1", name: "autoc", config: {} },
- settings: null,
- config: {},
- relayOptions: null,
- resilienceSettings: { quotaPreflight: { enabled: false } },
- log: noopLog,
- buildAutoCandidates,
- }) as never;
-
-test("exports resolveAutoStrategyOrder", () => {
- assert.equal(typeof resolveAutoStrategyOrder, "function");
-});
-
-test("no candidates -> keeps default ordering, no explicit router", async () => {
- const build = (async () => []) as never;
- const result = await resolveAutoStrategyOrder(baseDeps(build));
- assert.ok(!("earlyResponse" in result));
- if ("orderedTargets" in result) {
- assert.equal(result.autoUsedExplicitRouter, false);
- // default ordering preserved (both original targets survive)
- assert.equal(result.orderedTargets.length, 2);
- assert.equal(result.orderedTargets[0].provider, "openai");
- }
-});
-
-test("all candidates quota-cutoff-blocked -> early 429 Response", async () => {
- const build = (async () => [
- {
- kind: "model",
- stepId: "s1",
- executionKey: "openai>gpt-4o",
- modelStr: "gpt-4o",
- provider: "openai",
- model: "gpt-4o",
- quotaCutoffBlocked: true,
- },
- ]) as never;
- const result = await resolveAutoStrategyOrder(baseDeps(build));
- assert.ok("earlyResponse" in result);
- if ("earlyResponse" in result) {
- assert.ok(result.earlyResponse instanceof Response);
- assert.equal(result.earlyResponse.status, 429);
- }
-});
diff --git a/tests/unit/combo-target-defensive-modelstr.test.ts b/tests/unit/combo-target-defensive-modelstr.test.ts
index 8201075a4c..f26b86c8cc 100644
--- a/tests/unit/combo-target-defensive-modelstr.test.ts
+++ b/tests/unit/combo-target-defensive-modelstr.test.ts
@@ -14,22 +14,16 @@ import path from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
-// The LKGP fallback (and every non-auto strategy ordering) was extracted verbatim
-// from combo.ts into the applyStrategyOrdering leaf (Block J Task 3); the guard
-// scans follow the code to the leaf that now owns the `target.modelStr` usages.
-const STRATEGY_SRC = path.resolve(
- __dirname,
- "../../open-sse/services/combo/applyStrategyOrdering.ts"
-);
+const COMBO_SRC = path.resolve(__dirname, "../../open-sse/services/combo.ts");
const TEST_ROUTE_SRC = path.resolve(__dirname, "../../src/app/api/combos/test/route.ts");
-test("#2359 LKGP findIndex guards modelStr against non-string", () => {
- const src = fs.readFileSync(STRATEGY_SRC, "utf8");
+test("#2359 combo.ts LKGP findIndex guards modelStr against non-string", () => {
+ const src = fs.readFileSync(COMBO_SRC, "utf8");
// The findIndex on orderedTargets must check `typeof target.modelStr === "string"`
// before calling .startsWith. Anchor on the LKGP fallback branch.
assert.ok(
/typeof target\.modelStr === "string"[\s\S]{0,80}target\.modelStr\.startsWith/.test(src),
- "LKGP fallback must type-check target.modelStr before calling .startsWith"
+ "LKGP fallback in combo.ts must type-check target.modelStr before calling .startsWith"
);
});
@@ -47,8 +41,8 @@ test("#2359 combo test route falls back instead of throwing on missing modelStr"
);
});
-test("#2359 strategy ordering has no remaining unguarded target.modelStr.<method> usages", () => {
- const src = fs.readFileSync(STRATEGY_SRC, "utf8");
+test("#2359 combo.ts has no remaining unguarded target.modelStr.<method> usages", () => {
+ const src = fs.readFileSync(COMBO_SRC, "utf8");
// Strip the line that contains the guard so the regex below only catches
// direct, unguarded method calls.
const stripped = src.replace(/typeof target\.modelStr === "string"[^\n]*\n[^\n]*/g, "");
diff --git a/tests/unit/combo-target-timeout-runner.test.ts b/tests/unit/combo-target-timeout-runner.test.ts
deleted file mode 100644
index 9b89461d42..0000000000
--- a/tests/unit/combo-target-timeout-runner.test.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-import { test } from "node:test";
-import assert from "node:assert/strict";
-import { buildTargetTimeoutRunner } from "../../open-sse/services/combo/targetTimeoutRunner.ts";
-
-const noopLog = { warn() {}, info() {}, error() {}, debug() {} } as any;
-
-test("timeout<=0: passthrough direto (sem timer)", async () => {
- let called = false;
- const runner = buildTargetTimeoutRunner({
- handleSingleModel: async () => {
- called = true;
- return new Response("ok");
- },
- comboTargetTimeoutMs: 0,
- log: noopLog,
- });
- const res = await runner({}, "m");
- assert.equal(called, true);
- assert.equal(await res.text(), "ok");
-});
-
-test("timeout<=0: erro do upstream vira errorResponse 502", async () => {
- const runner = buildTargetTimeoutRunner({
- handleSingleModel: async () => {
- throw new Error("boom");
- },
- comboTargetTimeoutMs: 0,
- log: noopLog,
- });
- const res = await runner({}, "m");
- assert.equal(res.status, 502);
-});
-
-test("excede o limite: aborta e retorna 524 timed out", async () => {
- const runner = buildTargetTimeoutRunner({
- handleSingleModel: (_b, _m, target) =>
- new Promise<Response>((resolve) => {
- // resolve só se abortado (simula um upstream que respeita o signal)
- const sig = (target as any)?.modelAbortSignal as AbortSignal | undefined;
- sig?.addEventListener("abort", () => resolve(new Response(null, { status: 599 })));
- }),
- comboTargetTimeoutMs: 20,
- log: noopLog,
- });
- const res = await runner({}, "slow-model");
- assert.equal(res.status, 524);
- const body = await res.json();
- assert.match(JSON.stringify(body), /timed out/i);
-});
-
-test("sucesso rápido vence a corrida do timeout", async () => {
- const runner = buildTargetTimeoutRunner({
- handleSingleModel: async () => new Response("fast", { status: 200 }),
- comboTargetTimeoutMs: 1000,
- log: noopLog,
- });
- const res = await runner({}, "m");
- assert.equal(res.status, 200);
- assert.equal(await res.text(), "fast");
-});
-
-test("hedge do parent já abortado propaga o abort ao filho", async () => {
- const parent = new AbortController();
- parent.abort(new Error("hedge-cancelled"));
- let sawAbort = false;
- const runner = buildTargetTimeoutRunner({
- handleSingleModel: (_b, _m, target) =>
- new Promise<Response>((resolve) => {
- const sig = (target as any)?.modelAbortSignal as AbortSignal | undefined;
- if (sig?.aborted) sawAbort = true;
- resolve(new Response("ok"));
- }),
- comboTargetTimeoutMs: 1000,
- log: noopLog,
- });
- await runner({}, "m", { modelAbortSignal: parent.signal } as any);
- assert.equal(sawAbort, true);
-});
diff --git a/tests/unit/combo/combo-target-exhaustion.test.ts b/tests/unit/combo/combo-target-exhaustion.test.ts
index c6b0369187..5d28703aa0 100644
--- a/tests/unit/combo/combo-target-exhaustion.test.ts
+++ b/tests/unit/combo/combo-target-exhaustion.test.ts
@@ -166,200 +166,3 @@ test("a 200/benign status with no exhaustion mutates nothing and returns false",
0
);
});
-
-test("does NOT mark provider exhausted for per-model-quota providers (different model)", () => {
- const s = sets();
- const exhausted = applyComboTargetExhaustion(target({ provider: "gemini" }), {
- ...baseOpts,
- result: { status: 429 },
- fallbackResult: { reason: "quota_exhausted" },
- errorText: "quota exceeded for model gpt-4",
- sets: s,
- });
- assert.equal(exhausted, false);
- assert.equal(s.exhaustedProviders.has("gemini"), false);
- assert.ok(s.transientRateLimitedProviders.has("gemini"));
-});
-
-test("does NOT mark provider exhausted for empty provider strings", () => {
- const s = sets();
- const exhausted = applyComboTargetExhaustion(target({ provider: "" }), {
- ...baseOpts,
- result: { status: 503 },
- fallbackResult: { error: { code: "quota_exhausted" } },
- errorText: "quota exhausted",
- allAccountsRateLimited: true,
- sets: s,
- });
- assert.equal(exhausted, false);
-});
-
-test("does NOT mark transientRateLimited on 429 when isTokenLimitBreach is true", () => {
- const s = sets();
- const exhausted = applyComboTargetExhaustion(target(), {
- ...baseOpts,
- result: { status: 429 },
- fallbackResult: {},
- errorText: "Token limit exceeded",
- isTokenLimitBreach: true,
- sets: s,
- });
- assert.equal(exhausted, false);
- assert.equal(s.transientRateLimitedProviders.has("test-dedup-provider"), false);
- assert.equal(s.exhaustedProviders.has("test-dedup-provider"), false);
-});
-
-test("does NOT mark anything for circuit-open (X-OmniRoute-Provider-Breaker header)", () => {
- const s = sets();
- const exhausted = applyComboTargetExhaustion(target(), {
- ...baseOpts,
- result: { status: 503, headers: new Map([["x-omniroute-provider-breaker", "open"]]) },
- fallbackResult: {},
- errorText: "",
- sets: s,
- });
- assert.equal(exhausted, false);
- assert.equal(s.exhaustedProviders.has("test-dedup-provider"), false);
- assert.equal(s.exhaustedConnections.has("test-dedup-provider:conn-1"), false);
- assert.equal(s.transientRateLimitedProviders.has("test-dedup-provider"), false);
-});
-
-test("does NOT mark exhaustion for non-connection-level status codes (400)", () => {
- const s = sets();
- const exhausted = applyComboTargetExhaustion(target(), {
- ...baseOpts,
- result: { status: 400 },
- fallbackResult: {},
- errorText: "Bad Request",
- sets: s,
- });
- assert.equal(exhausted, false);
- assert.equal(s.exhaustedConnections.size, 0);
- assert.equal(s.exhaustedProviders.size, 0);
- assert.equal(s.transientRateLimitedProviders.size, 0);
-});
-
-test("does NOT mark connection exhausted for per-model-quota provider on 500 (gemini model-level error)", () => {
- const s = sets();
- const exhausted = applyComboTargetExhaustion(
- target({ provider: "gemini", connectionId: "gemini-conn-1" }),
- {
- ...baseOpts,
- result: { status: 500 },
- fallbackResult: {},
- errorText: "Internal error encountered.",
- rawModel: "gemma-4-31b-it",
- sets: s,
- }
- );
- assert.equal(exhausted, false);
- assert.equal(s.exhaustedProviders.has("gemini"), false);
- assert.equal(s.exhaustedConnections.has("gemini:gemini-conn-1"), false);
- assert.equal(s.transientRateLimitedProviders.has("gemini"), false);
-});
-
-// Sanitized Gemini 500 response — model-level "Internal error encountered" should NOT exhaust
-// the connection, allowing sibling models on the same provider to be tried.
-test("gemini 500 INTERNAL (sanitized real response) does NOT exhaust connection — sibling retry", () => {
- const s = sets();
- const exhausted = applyComboTargetExhaustion(
- target({ provider: "gemini", connectionId: "gemini-key-abc" }),
- {
- ...baseOpts,
- result: { status: 500 },
- fallbackResult: {},
- errorText: "Internal error encountered.",
- rawModel: "gemma-4-31b-it",
- structuredError: { code: 500, status: "INTERNAL", message: "Internal error encountered." },
- sets: s,
- }
- );
- assert.equal(exhausted, false, "providerExhausted must be false");
- assert.equal(s.exhaustedProviders.has("gemini"), false, "must not exhaust provider");
- assert.equal(
- s.exhaustedConnections.has("gemini:gemini-key-abc"),
- false,
- "must not exhaust connection — sibling model may succeed"
- );
- assert.equal(s.transientRateLimitedProviders.has("gemini"), false);
-});
-
-// Non-500 connection-level errors MUST exhaust the connection even for per-model-quota providers.
-// A 503 (Service Unavailable) means the upstream is down — retrying sibling models wastes calls.
-test("gemini 503 DOES exhaust connection (upstream down, not model-level)", () => {
- const s = sets();
- const exhausted = applyComboTargetExhaustion(
- target({ provider: "gemini", connectionId: "gemini-key-abc" }),
- {
- ...baseOpts,
- result: { status: 503 },
- fallbackResult: {},
- errorText: "The service is currently unavailable.",
- rawModel: "gemma-4-31b-it",
- sets: s,
- }
- );
- assert.equal(exhausted, false, "providerExhausted is false (not quota)");
- assert.equal(
- s.exhaustedConnections.has("gemini:gemini-key-abc"),
- true,
- "503 must exhaust connection — upstream is down"
- );
- assert.equal(s.exhaustedProviders.size, 0);
-});
-
-test("gemini 502 DOES exhaust connection (bad gateway)", () => {
- const s = sets();
- const exhausted = applyComboTargetExhaustion(
- target({ provider: "gemini", connectionId: "gemini-key-abc" }),
- {
- ...baseOpts,
- result: { status: 502 },
- fallbackResult: {},
- errorText: "Bad Gateway",
- rawModel: "gemma-4-31b-it",
- sets: s,
- }
- );
- assert.equal(exhausted, false);
- assert.equal(s.exhaustedConnections.has("gemini:gemini-key-abc"), true);
-});
-
-test("gemini 504 DOES exhaust connection (gateway timeout)", () => {
- const s = sets();
- applyComboTargetExhaustion(target({ provider: "gemini", connectionId: "gemini-key-abc" }), {
- ...baseOpts,
- result: { status: 504 },
- fallbackResult: {},
- errorText: "Gateway Timeout",
- rawModel: "gemini-2.0-flash",
- sets: s,
- });
- assert.equal(s.exhaustedConnections.has("gemini:gemini-key-abc"), true);
-});
-
-test("gemini 408 DOES exhaust connection (request timeout)", () => {
- const s = sets();
- applyComboTargetExhaustion(target({ provider: "gemini", connectionId: "gemini-key-abc" }), {
- ...baseOpts,
- result: { status: 408 },
- fallbackResult: {},
- errorText: "Request Timeout",
- rawModel: "gemini-2.0-flash",
- sets: s,
- });
- assert.equal(s.exhaustedConnections.has("gemini:gemini-key-abc"), true);
-});
-
-test("gemini 524 DOES exhaust connection (cloudflare timeout)", () => {
- const s = sets();
- applyComboTargetExhaustion(target({ provider: "gemini", connectionId: "gemini-key-abc" }), {
- ...baseOpts,
- result: { status: 524 },
- fallbackResult: {},
- errorText: "A Timeout Occurred",
- rawModel: "gemini-2.0-flash",
- sets: s,
- });
- assert.equal(s.exhaustedConnections.has("gemini:gemini-key-abc"), true);
-});
diff --git a/tests/unit/cors/origins.test.ts b/tests/unit/cors/origins.test.ts
index ff1502e02b..d00fcf699d 100644
--- a/tests/unit/cors/origins.test.ts
+++ b/tests/unit/cors/origins.test.ts
@@ -3,7 +3,6 @@ import assert from "node:assert/strict";
import { NextResponse } from "next/server";
import {
applyCorsHeaders,
- getCorsStatus,
resolveAllowedOrigin,
setRuntimeAllowedOrigins,
STATIC_CORS_HEADERS,
@@ -189,48 +188,6 @@ describe("cors/origins.applyCorsHeaders", () => {
});
});
-describe("cors/origins.getCorsStatus", () => {
- let envSnap: Record<string, string | undefined>;
-
- beforeEach(() => {
- envSnap = snapshotEnv();
- for (const key of ENV_KEYS) delete process.env[key];
- setRuntimeAllowedOrigins("");
- });
-
- afterEach(() => {
- restoreEnv(envSnap);
- setRuntimeAllowedOrigins("");
- });
-
- it("default (no env, no runtime) → allowAll false, empty origins", () => {
- assert.deepEqual(getCorsStatus(), { allowAll: false, allowedOrigins: [] });
- });
-
- it("CORS_ALLOW_ALL=true → allowAll true", () => {
- process.env.CORS_ALLOW_ALL = "true";
- assert.equal(getCorsStatus().allowAll, true);
- });
-
- it("legacy CORS_ORIGIN=* → allowAll true", () => {
- process.env.CORS_ORIGIN = "*";
- assert.equal(getCorsStatus().allowAll, true);
- });
-
- it("merges env + runtime allowlists, normalized, sorted, deduped", () => {
- process.env.CORS_ALLOWED_ORIGINS = "https://Env.Example.com/, https://shared.example.com";
- setRuntimeAllowedOrigins("https://runtime.example.com, https://shared.example.com/");
- assert.deepEqual(getCorsStatus(), {
- allowAll: false,
- allowedOrigins: [
- "https://env.example.com",
- "https://runtime.example.com",
- "https://shared.example.com",
- ],
- });
- });
-});
-
describe("cors/origins.STATIC_CORS_HEADERS", () => {
it("never contains Access-Control-Allow-Origin", () => {
assert.equal(
diff --git a/tests/unit/cursor-executor-split.test.ts b/tests/unit/cursor-executor-split.test.ts
deleted file mode 100644
index bcfdecb791..0000000000
--- a/tests/unit/cursor-executor-split.test.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import { test } from "node:test";
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { fileURLToPath } from "node:url";
-import { dirname, join } from "node:path";
-
-// Split-guard for the cursor executor pure-helper extraction.
-// Two pure leaves: cursor/prompt.ts (isRecordLike + toolChoiceDirectiveLine +
-// buildCursorOutputConstraints) and cursor/composer.ts (composer thinking decoding).
-// The host re-exports the 3 composer helpers for external importers (tests).
-const HERE = dirname(fileURLToPath(import.meta.url));
-const EXE = join(HERE, "../../open-sse/executors");
-const HOST = join(EXE, "cursor.ts");
-const PROMPT = join(EXE, "cursor/prompt.ts");
-const COMPOSER = join(EXE, "cursor/composer.ts");
-
-test("leaves are pure and do not import the host", () => {
- const prompt = readFileSync(PROMPT, "utf8");
- const composer = readFileSync(COMPOSER, "utf8");
- assert.match(prompt, /export function toolChoiceDirectiveLine\b/);
- assert.match(prompt, /export function buildCursorOutputConstraints\b/);
- assert.match(composer, /export function isComposerModel\b/);
- assert.doesNotMatch(prompt, /from "\.\.\/cursor\.ts"/);
- assert.doesNotMatch(composer, /from "\.\.\/cursor\.ts"/);
-});
-
-test("host re-exports the composer helpers", () => {
- const host = readFileSync(HOST, "utf8");
- assert.match(host, /from "\.\/cursor\/composer\.ts"/);
- assert.match(host, /from "\.\/cursor\/prompt\.ts"/);
-});
-
-test("composer thinking decoding behaves via the leaf", async () => {
- const { visibleComposerContentFromThinking, composerReasoningRemainder, isComposerModel } =
- await import("../../open-sse/executors/cursor/composer.ts");
- assert.equal(isComposerModel("composer-1"), true);
- assert.equal(isComposerModel("gpt-4"), false);
- assert.equal(visibleComposerContentFromThinking("hidden</think>visible"), "visible");
- assert.equal(composerReasoningRemainder("hidden</think>visible"), "hidden");
-});
-
-test("prompt constraint builder behaves via the leaf", async () => {
- const { toolChoiceDirectiveLine, buildCursorOutputConstraints } =
- await import("../../open-sse/executors/cursor/prompt.ts");
- assert.match(toolChoiceDirectiveLine("required"), /MUST call at least one/);
- assert.equal(toolChoiceDirectiveLine("auto"), "");
- assert.match(buildCursorOutputConstraints({ max_tokens: 100 }), /100 output tokens/);
- assert.equal(buildCursorOutputConstraints({}), "");
-});
diff --git a/tests/unit/dashboard/providers/services/mux-tab.test.ts b/tests/unit/dashboard/providers/services/mux-tab.test.ts
deleted file mode 100644
index 51e72d731c..0000000000
--- a/tests/unit/dashboard/providers/services/mux-tab.test.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-/**
- * MuxServiceTab unit test — verifies module shape only (no DOM renderer wired
- * into the node:test runner for this suite; mirrors CliproxyServiceTab.tsx's
- * module-shape test).
- */
-
-import { describe, it } from "node:test";
-import assert from "node:assert/strict";
-
-describe("MuxServiceTab — module shape", () => {
- it("exports MuxServiceTab function", async () => {
- const mod = await import(
- "../../../../../src/app/(dashboard)/dashboard/providers/services/tabs/MuxServiceTab.tsx"
- );
- assert.equal(typeof mod.MuxServiceTab, "function");
- });
-});
diff --git a/tests/unit/db-providers-access-token-1290.test.ts b/tests/unit/db-providers-access-token-1290.test.ts
deleted file mode 100644
index 85d94ec50f..0000000000
--- a/tests/unit/db-providers-access-token-1290.test.ts
+++ /dev/null
@@ -1,119 +0,0 @@
-// #1290 — bare-access-token Codex import. createProviderConnection must
-// never dedup authType "access_token" rows (each import is intentionally a
-// new connection — a raw access token has no stable long-lived identity to
-// safely match against), and must derive a connection name from email when
-// no explicit name is supplied, mirroring the existing "oauth" behavior.
-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-access-token-1290-"));
-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");
-
-async function resetStorage() {
- core.resetDbInstance();
- for (let attempt = 0; attempt < 10; attempt++) {
- try {
- if (fs.existsSync(TEST_DATA_DIR)) {
- fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
- }
- break;
- } catch (error: unknown) {
- const code = (error as { code?: string } | null)?.code;
- if ((code === "EBUSY" || code === "EPERM") && attempt < 9) {
- await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1)));
- } else {
- throw error;
- }
- }
- }
- fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
-}
-
-test.beforeEach(async () => {
- await resetStorage();
-});
-
-test.after(async () => {
- core.resetDbInstance();
- fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
-});
-
-test("createProviderConnection: authType access_token never dedups — same email creates a new row each time", async () => {
- const first = await providersDb.createProviderConnection({
- provider: "codex",
- authType: "access_token",
- accessToken: "eyJfirst.token.sig",
- email: "[email protected]",
- testStatus: "active",
- });
- const second = await providersDb.createProviderConnection({
- provider: "codex",
- authType: "access_token",
- accessToken: "eyJsecond.token.sig",
- email: "[email protected]",
- testStatus: "active",
- });
-
- assert.notEqual(first.id, second.id);
-
- const rows = await providersDb.getProviderConnections({ provider: "codex" });
- assert.equal(rows.length, 2);
- assert.deepEqual(
- rows.map((r) => r.accessToken).sort(),
- ["eyJfirst.token.sig", "eyJsecond.token.sig"].sort()
- );
-});
-
-test("createProviderConnection: authType access_token falls back to email for the connection name", async () => {
- const conn = await providersDb.createProviderConnection({
- provider: "codex",
- authType: "access_token",
- accessToken: "eyJtoken.sig",
- email: "[email protected]",
- });
-
- assert.equal(conn.name, "[email protected]");
-});
-
-test("createProviderConnection: authType access_token prefers an explicit name over email", async () => {
- const conn = await providersDb.createProviderConnection({
- provider: "codex",
- authType: "access_token",
- accessToken: "eyJtoken.sig",
- email: "[email protected]",
- name: "My Bare Token",
- });
-
- assert.equal(conn.name, "My Bare Token");
-});
-
-test("createProviderConnection: authType access_token does not collide with an existing oauth row for the same email", async () => {
- const oauthConn = await providersDb.createProviderConnection({
- provider: "codex",
- authType: "oauth",
- accessToken: "oauth-access",
- refreshToken: "oauth-refresh",
- email: "[email protected]",
- });
- const tokenConn = await providersDb.createProviderConnection({
- provider: "codex",
- authType: "access_token",
- accessToken: "eyJbare.token.sig",
- email: "[email protected]",
- });
-
- assert.notEqual(oauthConn.id, tokenConn.id);
-
- // The oauth row must be untouched (not silently overwritten by the
- // access_token import).
- const refreshed = await providersDb.getProviderConnections({ provider: "codex" });
- const oauthRow = refreshed.find((r) => r.id === oauthConn.id);
- assert.equal(oauthRow?.authType, "oauth");
- assert.equal(oauthRow?.refreshToken, "oauth-refresh");
-});
diff --git a/tests/unit/db/discovery-results.test.ts b/tests/unit/db/discovery-results.test.ts
deleted file mode 100644
index afc4106ee6..0000000000
--- a/tests/unit/db/discovery-results.test.ts
+++ /dev/null
@@ -1,143 +0,0 @@
-import { describe, test, before, after } from "node:test";
-import assert from "node:assert/strict";
-import { mkdtempSync, rmSync } from "node:fs";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-
-// Isolate the DB into a throwaway DATA_DIR so migrations run against a fresh file.
-let tmpDataDir: string;
-let mod: typeof import("@/lib/db/discoveryResults");
-let core: typeof import("@/lib/db/core");
-
-before(async () => {
- tmpDataDir = mkdtempSync(join(tmpdir(), "omniroute-discovery-"));
- process.env.DATA_DIR = tmpDataDir;
- core = await import("@/lib/db/core");
- core.resetDbInstance();
- // Touch the instance so migrations (incl. 074_discovery_results) apply.
- core.getDbInstance();
- mod = await import("@/lib/db/discoveryResults");
-});
-
-after(() => {
- core.resetDbInstance();
- if (tmpDataDir) rmSync(tmpDataDir, { recursive: true, force: true });
-});
-
-describe("discoveryResults DB module", () => {
- test("upsert inserts a new row and returns it with an id", () => {
- const row = mod.upsertDiscoveryResult({
- providerId: "acme",
- method: "free_tier",
- authType: "none",
- feasibility: 4,
- riskLevel: "low",
- status: "pending",
- models: ["acme-large", "acme-small"],
- endpoint: "https://acme.example/api",
- });
- assert.ok(typeof row.id === "number" && row.id > 0);
- assert.equal(row.providerId, "acme");
- assert.deepEqual(row.models, ["acme-large", "acme-small"]);
- assert.equal(row.status, "pending");
- });
-
- test("upsert on the same (provider, method, endpoint) updates instead of duplicating", () => {
- const first = mod.upsertDiscoveryResult({
- providerId: "beta",
- method: "web_cookie",
- authType: "cookie",
- feasibility: 3,
- riskLevel: "medium",
- status: "pending",
- endpoint: "https://beta.example/chat",
- });
- const second = mod.upsertDiscoveryResult({
- providerId: "beta",
- method: "web_cookie",
- authType: "cookie",
- feasibility: 5,
- riskLevel: "medium",
- status: "testing",
- endpoint: "https://beta.example/chat",
- });
- assert.equal(second.id, first.id);
- assert.equal(second.feasibility, 5);
- assert.equal(second.status, "testing");
- const all = mod.getDiscoveryResults("beta");
- assert.equal(all.length, 1);
- });
-
- test("getDiscoveryResults filters by providerId and returns all when omitted", () => {
- const beta = mod.getDiscoveryResults("beta");
- assert.ok(beta.every((r) => r.providerId === "beta"));
- const all = mod.getDiscoveryResults();
- assert.ok(all.length >= 2);
- });
-
- test("getDiscoveryResultById returns the row or null", () => {
- const created = mod.upsertDiscoveryResult({
- providerId: "gamma",
- method: "trial",
- authType: "api_key",
- feasibility: 2,
- riskLevel: "low",
- status: "pending",
- });
- const found = mod.getDiscoveryResultById(created.id!);
- assert.equal(found?.providerId, "gamma");
- assert.equal(mod.getDiscoveryResultById(999999), null);
- });
-
- test("markVerified sets status=verified and stamps verified_at", () => {
- const created = mod.upsertDiscoveryResult({
- providerId: "delta",
- method: "public_api",
- authType: "api_key",
- feasibility: 5,
- riskLevel: "none",
- status: "pending",
- });
- const updated = mod.markVerified(created.id!);
- assert.equal(updated?.status, "verified");
- assert.ok(updated?.verifiedAt);
- });
-
- test("markVerified on a missing id returns null", () => {
- assert.equal(mod.markVerified(999999), null);
- });
-
- test("deleteDiscoveryResult removes the row and returns true, false if absent", () => {
- const created = mod.upsertDiscoveryResult({
- providerId: "epsilon",
- method: "free_tier",
- authType: "none",
- feasibility: 1,
- riskLevel: "none",
- status: "pending",
- });
- assert.equal(mod.deleteDiscoveryResult(created.id!), true);
- assert.equal(mod.getDiscoveryResultById(created.id!), null);
- assert.equal(mod.deleteDiscoveryResult(created.id!), false);
- });
-});
-
-describe("discovery service reporter delegation", () => {
- test("persistDiscoveryResult writes through and getDiscoveryResults reads it back", async () => {
- const svc = await import("@/lib/discovery/index");
- const saved = svc.persistDiscoveryResult({
- providerId: "zeta",
- method: "public_api",
- authType: "api_key",
- feasibility: 5,
- riskLevel: "none",
- status: "verified",
- models: ["zeta-1"],
- });
- assert.ok(saved.id! > 0);
- const read = svc.getDiscoveryResults("zeta");
- assert.equal(read.length, 1);
- assert.equal(read[0].providerId, "zeta");
- assert.deepEqual(read[0].models, ["zeta-1"]);
- });
-});
diff --git a/tests/unit/deepseek-web-autorefresh-401-response.test.ts b/tests/unit/deepseek-web-autorefresh-401-response.test.ts
deleted file mode 100644
index 8e8b4e855d..0000000000
--- a/tests/unit/deepseek-web-autorefresh-401-response.test.ts
+++ /dev/null
@@ -1,135 +0,0 @@
-import { describe, it, afterEach } from "node:test";
-import assert from "node:assert/strict";
-
-import {
- DeepSeekWebWithAutoRefreshExecutor,
-} from "../../open-sse/executors/deepseek-web-with-auto-refresh.ts";
-import { DeepSeekWebExecutor } from "../../open-sse/executors/deepseek-web.ts";
-
-// Regression: the base DeepSeekWebExecutor.execute() never throws — it converts
-// upstream auth failures (401/403) into a returned error Response. The auto-refresh
-// subclass used to trigger refresh+retry only from its catch block (thrown errors),
-// so the retry path was dead code: a stale access token surfaced a 401 to the client
-// on every refresh boundary instead of self-healing. See executor-deepseek-web-auto-refresh.
-
-const baseProto = DeepSeekWebExecutor.prototype;
-const originalExecute = baseProto.execute;
-
-function makeInput(overrides: Record<string, unknown> = {}) {
- return {
- model: "deepseek-web",
- body: { messages: [{ role: "user", content: "hi" }] },
- stream: false,
- credentials: { apiKey: "user-token-abc" },
- signal: null,
- log: null,
- ...overrides,
- } as any;
-}
-
-afterEach(() => {
- baseProto.execute = originalExecute;
-});
-
-describe("DeepSeekWebWithAutoRefreshExecutor — 401 Response retry (regression)", () => {
- it("refreshes and retries when the base returns a 401 error Response", async () => {
- const executor = new DeepSeekWebWithAutoRefreshExecutor({ autoRefresh: false });
-
- let baseCalls = 0;
- baseProto.execute = async function () {
- baseCalls++;
- if (baseCalls === 1) {
- return {
- response: new Response(
- JSON.stringify({ error: { message: "DeepSeek token expired" } }),
- { status: 401, headers: { "Content-Type": "application/json" } }
- ),
- url: "https://chat.deepseek.com/api/v0/chat/completion",
- headers: {},
- transformedBody: {},
- };
- }
- return {
- response: new Response(
- JSON.stringify({ choices: [{ message: { role: "assistant", content: "ok" } }] }),
- { status: 200, headers: { "Content-Type": "application/json" } }
- ),
- url: "https://chat.deepseek.com/api/v0/chat/completion",
- headers: {},
- transformedBody: {},
- };
- };
-
- let refreshCalls = 0;
- (executor as any).doRefreshSession = async () => {
- refreshCalls++;
- };
-
- const result = await executor.execute(makeInput());
-
- assert.equal(refreshCalls, 1, "auto-refresh should fire exactly once on a 401 Response");
- assert.equal(baseCalls, 2, "base execute should run twice (initial 401 → refreshed retry)");
- assert.equal(result.response.status, 200, "the retried request's success should reach the client");
- });
-
- it("does not refresh/retry on a successful 200 Response", async () => {
- const executor = new DeepSeekWebWithAutoRefreshExecutor({ autoRefresh: false });
-
- let baseCalls = 0;
- baseProto.execute = async function () {
- baseCalls++;
- return {
- response: new Response(JSON.stringify({ choices: [] }), {
- status: 200,
- headers: { "Content-Type": "application/json" },
- }),
- url: "https://chat.deepseek.com/api/v0/chat/completion",
- headers: {},
- transformedBody: {},
- };
- };
-
- let refreshCalls = 0;
- (executor as any).doRefreshSession = async () => {
- refreshCalls++;
- };
-
- const result = await executor.execute(makeInput());
-
- assert.equal(baseCalls, 1, "base execute should run once on success");
- assert.equal(refreshCalls, 0, "no refresh on a 200 Response");
- assert.equal(result.response.status, 200);
- });
-
- it("stops retrying (no loop) when refresh cannot recover a dead userToken", async () => {
- const executor = new DeepSeekWebWithAutoRefreshExecutor({ autoRefresh: false });
-
- let baseCalls = 0;
- baseProto.execute = async function () {
- baseCalls++;
- return {
- response: new Response(JSON.stringify({ error: { message: "expired" } }), {
- status: 401,
- headers: { "Content-Type": "application/json" },
- }),
- url: "https://chat.deepseek.com/api/v0/chat/completion",
- headers: {},
- transformedBody: {},
- };
- };
-
- let refreshCalls = 0;
- (executor as any).doRefreshSession = async () => {
- refreshCalls++;
- throw new Error("Token expired — get a new userToken from DeepSeek localStorage");
- };
-
- const result = await executor.execute(makeInput());
-
- // Refresh is attempted once; when it throws (dead userToken), we surface the
- // original 401 instead of looping forever.
- assert.equal(refreshCalls, 1, "refresh attempted once");
- assert.equal(baseCalls, 1, "no retry when refresh itself fails");
- assert.equal(result.response.status, 401, "original auth failure surfaces to the client");
- });
-});
diff --git a/tests/unit/deepseek-web-executor-split.test.ts b/tests/unit/deepseek-web-executor-split.test.ts
deleted file mode 100644
index 34d5561371..0000000000
--- a/tests/unit/deepseek-web-executor-split.test.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import { test } from "node:test";
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { fileURLToPath } from "node:url";
-import { dirname, join } from "node:path";
-
-// Split-guard for the deepseek-web executor stream-format extraction.
-// The pure content/citation formatters live in deepseek-web/stream-format.ts
-// (module-private; host imports them into transformSSE/collectSSEContent).
-const HERE = dirname(fileURLToPath(import.meta.url));
-const EXE = join(HERE, "../../open-sse/executors");
-const HOST = join(EXE, "deepseek-web.ts");
-const LEAF = join(EXE, "deepseek-web/stream-format.ts");
-
-test("leaf hosts the formatters and does not import the host", () => {
- const src = readFileSync(LEAF, "utf8");
- for (const sym of ["formatStreamContent", "appendSearchCitations", "isThinkingModel"]) {
- assert.match(src, new RegExp(`export function ${sym}\\b`));
- }
- assert.doesNotMatch(src, /from "\.\.\/deepseek-web\.ts"/);
-});
-
-test("host imports the formatters back from the leaf", () => {
- const host = readFileSync(HOST, "utf8");
- assert.match(host, /from "\.\/deepseek-web\/stream-format\.ts"/);
-});
-
-test("formatStreamContent + model classifiers behave", async () => {
- const { isThinkingModel, isSearchModel, formatStreamContent } =
- await import("../../open-sse/executors/deepseek-web/stream-format.ts");
- assert.equal(typeof isThinkingModel("deepseek-reasoner"), "boolean");
- assert.equal(typeof isSearchModel("deepseek-search"), "boolean");
- assert.equal(typeof formatStreamContent("hi", "deepseek-chat"), "string");
-});
diff --git a/tests/unit/deepseek-web.test.ts b/tests/unit/deepseek-web.test.ts
index af1fc82c49..eab5be7703 100644
--- a/tests/unit/deepseek-web.test.ts
+++ b/tests/unit/deepseek-web.test.ts
@@ -311,19 +311,8 @@ test("execute: sends PoW response header", async () => {
"Has Bearer token"
);
assert.ok(compCall.headers["X-Ds-Pow-Response"], "Has PoW header");
- // Header set matches the current chat.deepseek.com web client (v2.0.0):
- // legacy X-App-Version dropped, X-Client-Bundle-Id added, version bumped.
- assert.ok(
- !("X-App-Version" in compCall.headers),
- "Legacy X-App-Version must not be sent (removed in web client 2.0.0)"
- );
- assert.equal(
- compCall.headers["X-Client-Bundle-Id"],
- "com.deepseek.chat",
- "Sends X-Client-Bundle-Id"
- );
- assert.equal(compCall.headers["X-Client-Version"], "2.0.0", "Sends current X-Client-Version");
- assert.equal(compCall.headers["X-Client-Platform"], "web", "Has X-Client-Platform");
+ assert.ok(compCall.headers["X-App-Version"], "Has X-App-Version");
+ assert.ok(compCall.headers["X-Client-Platform"] === "web", "Has X-Client-Platform");
} finally {
mock.restore();
}
diff --git a/tests/unit/default-url-normalizers-split.test.ts b/tests/unit/default-url-normalizers-split.test.ts
deleted file mode 100644
index 87d7f0adc6..0000000000
--- a/tests/unit/default-url-normalizers-split.test.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import { test } from "node:test";
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { fileURLToPath } from "node:url";
-import { dirname, join } from "node:path";
-
-// Split-guard for the default executor URL-normalizer extraction.
-// The pure per-provider chat-URL normalizers live in default/urlNormalizers.ts
-// (string transforms only). Host imports them back into buildUrl/transformRequest.
-const HERE = dirname(fileURLToPath(import.meta.url));
-const EXE = join(HERE, "../../open-sse/executors");
-const HOST = join(EXE, "default.ts");
-const LEAF = join(EXE, "default/urlNormalizers.ts");
-
-test("leaf hosts the normalizers and does not import the host", () => {
- const src = readFileSync(LEAF, "utf8");
- for (const sym of [
- "normalizeOpenAIChatUrl",
- "normalizeSapChatUrl",
- "getOpenRouterConnectionPreset",
- ]) {
- assert.match(src, new RegExp(`export function ${sym}\\b`));
- }
- assert.doesNotMatch(src, /from "\.\.\/default\.ts"/);
-});
-
-test("host imports the normalizers back from the leaf", () => {
- const host = readFileSync(HOST, "utf8");
- assert.match(host, /from "\.\/default\/urlNormalizers\.ts"/);
-});
-
-test("normalizeOpenAIChatUrl appends chat/completions for a bare base URL", async () => {
- const { normalizeOpenAIChatUrl } =
- await import("../../open-sse/executors/default/urlNormalizers.ts");
- assert.match(normalizeOpenAIChatUrl("https://api.example.com"), /\/v1\/chat\/completions$/);
-});
diff --git a/tests/unit/device-tracker.test.ts b/tests/unit/device-tracker.test.ts
deleted file mode 100644
index bbe7682a9a..0000000000
--- a/tests/unit/device-tracker.test.ts
+++ /dev/null
@@ -1,195 +0,0 @@
-import test from "node:test";
-import assert from "node:assert/strict";
-
-const {
- trackDevice,
- getDeviceCount,
- getDeviceDetails,
- getAllDeviceCounts,
- expireDevices,
- extractIpFromHeaders,
- maskIp,
- clearDeviceTracker,
-} = await import("../../open-sse/services/deviceTracker.ts");
-
-test.beforeEach(() => {
- delete process.env.DEVICE_TRACKER_TTL_MS;
- delete process.env.DEVICE_TRACKER_MAX_DEVICES_PER_KEY;
- delete process.env.DEVICE_TRACKER_MAX_TOTAL_DEVICES;
- clearDeviceTracker();
-});
-
-// ─── Fingerprint dedup ──────────────────────────────────────────────────────
-
-test("trackDevice: same IP + UA for a key counts as one device", async () => {
- await trackDevice("key-1", "203.0.113.5", "Mozilla/5.0 test-agent");
- await trackDevice("key-1", "203.0.113.5", "Mozilla/5.0 test-agent");
- await trackDevice("key-1", "203.0.113.5", "Mozilla/5.0 test-agent");
-
- assert.equal(getDeviceCount("key-1"), 1);
-});
-
-test("trackDevice: different User-Agent for same key/IP counts as a new device", async () => {
- await trackDevice("key-1", "203.0.113.5", "curl/8.0");
- await trackDevice("key-1", "203.0.113.5", "python-requests/2.31");
-
- assert.equal(getDeviceCount("key-1"), 2);
-});
-
-test("trackDevice: different IP for same key/UA counts as a new device", async () => {
- await trackDevice("key-1", "203.0.113.5", "curl/8.0");
- await trackDevice("key-1", "198.51.100.9", "curl/8.0");
-
- assert.equal(getDeviceCount("key-1"), 2);
-});
-
-test("trackDevice: repeated tracking refreshes lastSeen instead of duplicating", async () => {
- await trackDevice("key-1", "203.0.113.5", "curl/8.0");
- const [before] = getDeviceDetails("key-1");
- await new Promise((resolve) => setTimeout(resolve, 5));
- await trackDevice("key-1", "203.0.113.5", "curl/8.0");
- const [after] = getDeviceDetails("key-1");
-
- assert.equal(getDeviceCount("key-1"), 1);
- assert.ok(after.lastSeen >= before.lastSeen);
-});
-
-test("trackDevice: no-ops and returns null when apiKeyId is missing", async () => {
- const fingerprint = await trackDevice(null, "203.0.113.5", "curl/8.0");
- assert.equal(fingerprint, null);
- assert.equal(getDeviceCount(null), 0);
-});
-
-// ─── Per-key isolation ──────────────────────────────────────────────────────
-
-test("trackDevice: devices are scoped per API key, not global", async () => {
- await trackDevice("key-1", "203.0.113.5", "curl/8.0");
- await trackDevice("key-2", "203.0.113.5", "curl/8.0"); // same fingerprint, different key
-
- assert.equal(getDeviceCount("key-1"), 1);
- assert.equal(getDeviceCount("key-2"), 1);
-
- const allCounts = getAllDeviceCounts();
- assert.equal(allCounts["key-1"], 1);
- assert.equal(allCounts["key-2"], 1);
-});
-
-// ─── TTL expiry ─────────────────────────────────────────────────────────────
-
-test("expireDevices: evicts devices whose lastSeen exceeds the TTL window", async () => {
- process.env.DEVICE_TRACKER_TTL_MS = "1000";
- clearDeviceTracker();
-
- await trackDevice("key-1", "203.0.113.5", "curl/8.0");
- assert.equal(getDeviceCount("key-1"), 1);
-
- const farFuture = Date.now() + 5000;
- const expiredCount = expireDevices(farFuture);
-
- assert.equal(expiredCount, 1);
- assert.equal(getDeviceCount("key-1"), 0);
-});
-
-test("expireDevices: keeps devices seen within the TTL window", async () => {
- process.env.DEVICE_TRACKER_TTL_MS = "60000";
- clearDeviceTracker();
-
- await trackDevice("key-1", "203.0.113.5", "curl/8.0");
- const soon = Date.now() + 1000;
- const expiredCount = expireDevices(soon);
-
- assert.equal(expiredCount, 0);
- assert.equal(getDeviceCount("key-1"), 1);
-});
-
-// ─── Eviction under caps ────────────────────────────────────────────────────
-
-test("trackDevice: enforces maxDevicesPerApiKey by evicting the oldest device", async () => {
- process.env.DEVICE_TRACKER_MAX_DEVICES_PER_KEY = "2";
- clearDeviceTracker();
-
- await trackDevice("key-1", "203.0.113.1", "ua-1");
- await new Promise((resolve) => setTimeout(resolve, 2));
- await trackDevice("key-1", "203.0.113.2", "ua-2");
- await new Promise((resolve) => setTimeout(resolve, 2));
- // Third distinct device should evict the oldest (203.0.113.1 / ua-1).
- await trackDevice("key-1", "203.0.113.3", "ua-3");
-
- assert.equal(getDeviceCount("key-1"), 2);
- const uaSet = new Set(getDeviceDetails("key-1").map((d) => d.userAgent));
- assert.ok(!uaSet.has("ua-1"), "oldest device should have been evicted");
- assert.ok(uaSet.has("ua-2"));
- assert.ok(uaSet.has("ua-3"));
-});
-
-test("trackDevice: enforces maxTotalDevices globally across all keys", async () => {
- process.env.DEVICE_TRACKER_MAX_TOTAL_DEVICES = "2";
- clearDeviceTracker();
-
- await trackDevice("key-1", "203.0.113.1", "ua-1");
- await new Promise((resolve) => setTimeout(resolve, 2));
- await trackDevice("key-2", "203.0.113.2", "ua-2");
- await new Promise((resolve) => setTimeout(resolve, 2));
- await trackDevice("key-3", "203.0.113.3", "ua-3");
-
- const total = Object.values(getAllDeviceCounts()).reduce((a, b) => a + b, 0);
- assert.equal(total, 2);
- // key-1's device was the oldest globally and should be gone.
- assert.equal(getDeviceCount("key-1"), 0);
-});
-
-// ─── IP masking ─────────────────────────────────────────────────────────────
-
-test("maskIp: masks the last two octets of an IPv4 address", () => {
- assert.equal(maskIp("203.0.113.42"), "203.0.x.x");
-});
-
-test("maskIp: masks an IPv6 address down to its first three groups", () => {
- assert.equal(maskIp("2001:db8:85a3:0:0:8a2e:370:7334"), "2001:db8:85a3:...");
-});
-
-test("maskIp: returns 'unknown' for missing/unknown input", () => {
- assert.equal(maskIp(null), "unknown");
- assert.equal(maskIp(undefined), "unknown");
- assert.equal(maskIp("unknown"), "unknown");
-});
-
-test("trackDevice: never stores the raw IP — only the masked form", async () => {
- await trackDevice("key-1", "203.0.113.42", "curl/8.0");
- const [detail] = getDeviceDetails("key-1");
-
- assert.equal(detail.ip, "203.0.x.x");
- assert.notEqual(detail.ip, "203.0.113.42");
-});
-
-test("getDeviceDetails: truncates the fingerprint instead of exposing the full SHA-256 hash", async () => {
- await trackDevice("key-1", "203.0.113.42", "curl/8.0");
- const [detail] = getDeviceDetails("key-1");
-
- assert.equal(detail.fingerprint.length, 12);
-});
-
-// ─── IP extraction from headers ─────────────────────────────────────────────
-
-test("extractIpFromHeaders: prefers cf-connecting-ip over x-forwarded-for", () => {
- const ip = extractIpFromHeaders({
- "cf-connecting-ip": "203.0.113.5",
- "x-forwarded-for": "198.51.100.9, 10.0.0.1",
- });
- assert.equal(ip, "203.0.113.5");
-});
-
-test("extractIpFromHeaders: falls back to the first hop of x-forwarded-for", () => {
- const ip = extractIpFromHeaders({ "x-forwarded-for": "198.51.100.9, 10.0.0.1" });
- assert.equal(ip, "198.51.100.9");
-});
-
-test("extractIpFromHeaders: works with a real Headers instance", () => {
- const headers = new Headers({ "x-real-ip": "192.0.2.7" });
- assert.equal(extractIpFromHeaders(headers), "192.0.2.7");
-});
-
-test("extractIpFromHeaders: returns 'unknown' when no IP header is present", () => {
- assert.equal(extractIpFromHeaders({}), "unknown");
- assert.equal(extractIpFromHeaders(null), "unknown");
-});
diff --git a/tests/unit/duckduckgo-challenge-split.test.ts b/tests/unit/duckduckgo-challenge-split.test.ts
deleted file mode 100644
index cc4a7bd8a3..0000000000
--- a/tests/unit/duckduckgo-challenge-split.test.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import { test } from "node:test";
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { fileURLToPath } from "node:url";
-import { dirname, join } from "node:path";
-
-// Split-guard for the duckduckgo-web challenge-solver extraction.
-// The anti-abuse challenge solver + FE signals live in duckduckgo-web/challenge.ts
-// (pure of module state; the vm sandbox + 5s timeout are preserved). Host imports back.
-const HERE = dirname(fileURLToPath(import.meta.url));
-const EXE = join(HERE, "../../open-sse/executors");
-const HOST = join(EXE, "duckduckgo-web.ts");
-const LEAF = join(EXE, "duckduckgo-web/challenge.ts");
-
-test("leaf hosts the solver and does not import the host", () => {
- const src = readFileSync(LEAF, "utf8");
- assert.match(src, /export async function solveDuckDuckGoChallenge\b/);
- assert.match(src, /export function makeDuckDuckGoFeSignals\b/);
- assert.doesNotMatch(src, /from "\.\.\/duckduckgo-web\.ts"/);
- // The vm sandbox timeout must survive the move (security invariant).
- assert.match(src, /timeout/);
-});
-
-test("host imports the solver back from the leaf", () => {
- const host = readFileSync(HOST, "utf8");
- assert.match(host, /from "\.\/duckduckgo-web\/challenge\.ts"/);
-});
-
-test("makeDuckDuckGoFeSignals returns a base64 string", async () => {
- const { makeDuckDuckGoFeSignals } =
- await import("../../open-sse/executors/duckduckgo-web/challenge.ts");
- const out = makeDuckDuckGoFeSignals();
- assert.equal(typeof out, "string");
- assert.ok(out.length > 0);
-});
diff --git a/tests/unit/embeddings-proxy-forwarding.test.ts b/tests/unit/embeddings-proxy-forwarding.test.ts
deleted file mode 100644
index 2d93d066bf..0000000000
--- a/tests/unit/embeddings-proxy-forwarding.test.ts
+++ /dev/null
@@ -1,110 +0,0 @@
-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";
-import http from "node:http";
-
-// Isolate the DB to a temp dir BEFORE importing any module that opens it.
-const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-embed-proxy-"));
-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 settingsDb = await import("../../src/lib/db/settings.ts");
-const { createEmbeddingResponse } = await import("../../src/lib/embeddings/service.ts");
-const { resolveProxyForRequest } = await import("../../open-sse/utils/proxyFetch.ts");
-
-test.after(() => {
- core.resetDbInstance();
- fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
-});
-
-async function withHttpServer(handler: http.RequestListener, fn: (baseUrl: string) => Promise<void>) {
- const server = http.createServer(handler);
- await new Promise<void>((resolve, reject) => {
- server.once("error", reject);
- server.listen(0, "127.0.0.1", () => resolve());
- });
- const address = server.address();
- assert.ok(address && typeof address === "object");
- try {
- await fn(`http://127.0.0.1:${(address as { port: number }).port}`);
- } finally {
- await new Promise<void>((resolve, reject) => {
- server.close((err) => (err ? reject(err) : resolve()));
- });
- }
-}
-
-test("embeddings forward the connection-level (key) pinned proxy to the upstream fetch", async () => {
- // T14 Proxy Fast-Fail performs a real TCP reachability check before running
- // the request inside the proxy context, so the "proxy" must be a real,
- // reachable local listener (its actual response body is irrelevant here —
- // the assertion is about which proxy context the upstream fetch observes).
- await withHttpServer(
- (_req, res) => {
- res.writeHead(200);
- res.end("ok");
- },
- async (proxyBaseUrl) => {
- const proxyUrl = new URL(proxyBaseUrl);
-
- const connection = await providersDb.createProviderConnection({
- provider: "mistral",
- authType: "apikey",
- name: "Test Mistral Proxy",
- apiKey: "mistral-test-key",
- });
-
- // Pin a proxy at the connection ("key") level — the most specific level,
- // exactly like a user would configure per-connection in the dashboard.
- await settingsDb.setProxyForLevel("key", (connection as any).id, {
- type: "http",
- host: proxyUrl.hostname,
- port: Number(proxyUrl.port),
- });
-
- let capturedProxySource: string | null = null;
- let capturedProxyUrl: string | null = null;
-
- const originalFetch = globalThis.fetch;
- globalThis.fetch = async (input: RequestInfo | URL) => {
- const targetUrl = typeof input === "string" ? input : (input as URL).toString();
- const resolved = resolveProxyForRequest(targetUrl);
- capturedProxySource = resolved.source;
- capturedProxyUrl = resolved.proxyUrl;
- return new Response(
- JSON.stringify({
- data: [{ object: "embedding", embedding: [0.1, 0.2], index: 0 }],
- usage: { prompt_tokens: 3, total_tokens: 3 },
- }),
- { status: 200, headers: { "content-type": "application/json" } }
- );
- };
-
- try {
- const res = await createEmbeddingResponse({
- model: "mistral/mistral-embed",
- input: "hello world",
- });
- assert.equal(res.status, 200, "embedding request should succeed");
- } finally {
- globalThis.fetch = originalFetch;
- }
-
- // The upstream fetch must have run inside the AsyncLocalStorage proxy
- // context carrying the connection's pinned proxy — not "direct" (no
- // context) and not the env-var proxy fallback.
- assert.equal(
- capturedProxySource,
- "context",
- `expected the embeddings upstream fetch to run inside a proxy context, got source="${capturedProxySource}"`
- );
- assert.ok(
- capturedProxyUrl && capturedProxyUrl.includes(`${proxyUrl.hostname}:${proxyUrl.port}`),
- `expected the connection's pinned proxy to be forwarded, got "${capturedProxyUrl}"`
- );
- }
- );
-});
diff --git a/tests/unit/endpoint-categories.test.ts b/tests/unit/endpoint-categories.test.ts
index b51215300d..b64a63e8a8 100644
--- a/tests/unit/endpoint-categories.test.ts
+++ b/tests/unit/endpoint-categories.test.ts
@@ -80,10 +80,6 @@ test("resolveEndpointCategory: maps /v1/moderations to 'moderations'", () => {
assert.equal(resolveEndpointCategory("/v1/moderations"), "moderations");
});
-test("resolveEndpointCategory: maps /v1/ocr to 'ocr'", () => {
- assert.equal(resolveEndpointCategory("/v1/ocr"), "ocr");
-});
-
test("resolveEndpointCategory: maps /v1/batches to 'batches'", () => {
assert.equal(resolveEndpointCategory("/v1/batches"), "batches");
});
diff --git a/tests/unit/executor-default-base.test.ts b/tests/unit/executor-default-base.test.ts
index 0f0beaca60..001035c0a2 100644
--- a/tests/unit/executor-default-base.test.ts
+++ b/tests/unit/executor-default-base.test.ts
@@ -587,7 +587,7 @@ test("DefaultExecutor.buildHeaders rotates extra API keys and builds Claude Code
assert.equal(ccHeaders["x-api-key"], undefined);
assert.equal(ccHeaders["anthropic-version"], CLAUDE_CODE_COMPATIBLE_ANTHROPIC_VERSION);
assert.equal(ccHeaders["X-Claude-Code-Session-Id"], "session-1");
- assert.equal(ccHeaders.Accept, "text/event-stream");
+ assert.equal(ccHeaders.Accept, "application/json");
assert.equal(ccJsonHeaders.Accept, "application/json");
});
diff --git a/tests/unit/executor-firecrawl-fetch.test.ts b/tests/unit/executor-firecrawl-fetch.test.ts
deleted file mode 100644
index 83376e3125..0000000000
--- a/tests/unit/executor-firecrawl-fetch.test.ts
+++ /dev/null
@@ -1,151 +0,0 @@
-import test from "node:test";
-import assert from "node:assert/strict";
-
-const { firecrawlFetch } = await import("../../open-sse/executors/firecrawl-fetch.ts");
-
-// ── #2253 (decolua/9router): self-hosted Firecrawl support ────────────────────
-// FIRECRAWL_BASE_URL lets operators point the executor at a self-hosted instance.
-// The API key stays required for the default cloud endpoint, but becomes optional
-// once a custom base URL is configured (self-hosted instances usually run with no
-// auth in front of them).
-
-function withEnv(vars: Record<string, string | undefined>, fn: () => Promise<void>) {
- const original: Record<string, string | undefined> = {};
- for (const key of Object.keys(vars)) {
- original[key] = process.env[key];
- }
- for (const [key, value] of Object.entries(vars)) {
- if (value === undefined) delete process.env[key];
- else process.env[key] = value;
- }
- return fn().finally(() => {
- for (const [key, value] of Object.entries(original)) {
- if (value === undefined) delete process.env[key];
- else process.env[key] = value;
- }
- });
-}
-
-test("firecrawlFetch routes to FIRECRAWL_BASE_URL when set", async () => {
- await withEnv({ FIRECRAWL_BASE_URL: "http://127.0.0.1:3002" }, async () => {
- const originalFetch = globalThis.fetch;
- let capturedUrl = "";
-
- globalThis.fetch = async (url) => {
- capturedUrl = String(url);
- return new Response(JSON.stringify({ data: { markdown: "# Self-hosted" } }), {
- status: 200,
- headers: { "content-type": "application/json" },
- });
- };
-
- try {
- const result = await firecrawlFetch({
- url: "https://example.com",
- format: "markdown",
- depth: 0,
- includeMetadata: false,
- credentials: { apiKey: "any-key" },
- });
-
- assert.equal(result.success, true);
- assert.equal(capturedUrl, "http://127.0.0.1:3002/v1/scrape");
- } finally {
- globalThis.fetch = originalFetch;
- }
- });
-});
-
-test("firecrawlFetch allows missing apiKey when FIRECRAWL_BASE_URL is custom", async () => {
- await withEnv({ FIRECRAWL_BASE_URL: "http://127.0.0.1:3002" }, async () => {
- const originalFetch = globalThis.fetch;
- let capturedHeaders: Record<string, string> = {};
-
- globalThis.fetch = async (_url, init = {}) => {
- capturedHeaders = (init as RequestInit).headers as Record<string, string>;
- return new Response(JSON.stringify({ data: { markdown: "# Self-hosted" } }), {
- status: 200,
- headers: { "content-type": "application/json" },
- });
- };
-
- try {
- const result = await firecrawlFetch({
- url: "https://example.com",
- format: "markdown",
- depth: 0,
- includeMetadata: false,
- credentials: {},
- });
-
- assert.equal(result.success, true, "custom base URL must not require an API key");
- assert.equal(
- capturedHeaders["Authorization"],
- undefined,
- "no Authorization header should be sent without an apiKey"
- );
- } finally {
- globalThis.fetch = originalFetch;
- }
- });
-});
-
-test("firecrawlFetch still requires apiKey against the default cloud base URL", async () => {
- await withEnv({ FIRECRAWL_BASE_URL: undefined }, async () => {
- const result = await firecrawlFetch({
- url: "https://example.com",
- format: "markdown",
- depth: 0,
- includeMetadata: false,
- credentials: {},
- });
-
- assert.equal(result.success, false);
- assert.equal(result.status, 401);
- assert.ok(!result.error?.includes("at /"), "error must not contain stack trace");
- });
-});
-
-test("firecrawlFetch honors FIRECRAWL_TIMEOUT_MS override", async () => {
- await withEnv(
- { FIRECRAWL_BASE_URL: "http://127.0.0.1:3002", FIRECRAWL_TIMEOUT_MS: "5" },
- async () => {
- const originalFetch = globalThis.fetch;
-
- globalThis.fetch = async (_url, init = {}) => {
- const signal = (init as RequestInit).signal;
- return new Promise((resolve, reject) => {
- const timer = setTimeout(
- () =>
- resolve(
- new Response(JSON.stringify({ data: { markdown: "late" } }), {
- status: 200,
- headers: { "content-type": "application/json" },
- })
- ),
- 50
- );
- signal?.addEventListener("abort", () => {
- clearTimeout(timer);
- reject(new DOMException("Aborted", "AbortError"));
- });
- });
- };
-
- try {
- const result = await firecrawlFetch({
- url: "https://example.com",
- format: "markdown",
- depth: 0,
- includeMetadata: false,
- credentials: {},
- });
-
- assert.equal(result.success, false);
- assert.equal(result.status, 504);
- } finally {
- globalThis.fetch = originalFetch;
- }
- }
- );
-});
diff --git a/tests/unit/executor-kimi-web.test.ts b/tests/unit/executor-kimi-web.test.ts
index bff69e30d6..05f6e52f34 100644
--- a/tests/unit/executor-kimi-web.test.ts
+++ b/tests/unit/executor-kimi-web.test.ts
@@ -19,7 +19,7 @@ describe("KimiWebExecutor", () => {
it("execute returns a 400 error when no JWT is provided", async () => {
const executor = new mod.KimiWebExecutor();
const result = await executor.execute({
- model: "k2d6",
+ model: "kimi-default",
body: { messages: [{ role: "user", content: "hi" }] },
stream: false,
credentials: { apiKey: "" },
@@ -43,7 +43,7 @@ describe("KimiWebExecutor", () => {
});
}) as typeof fetch;
await executor.execute({
- model: "k2d6",
+ model: "kimi-default",
body: { messages: [{ role: "user", content: "hi" }] },
stream: false,
credentials: { apiKey: "kimi-auth=fake.jwt.token" },
@@ -57,28 +57,6 @@ describe("KimiWebExecutor", () => {
});
});
-describe("resolveModelConfig", () => {
- const { resolveModelConfig } = mod;
-
- it("maps k2d6-thinking to the K2D5 scenario with thinking enabled", () => {
- const cfg = resolveModelConfig("k2d6-thinking");
- assert.equal(cfg.scenario, "SCENARIO_K2D5");
- assert.equal(cfg.thinking, true);
- });
-
- it("maps k2d6 (Instant) to the K2D5 scenario without thinking", () => {
- const cfg = resolveModelConfig("k2d6");
- assert.equal(cfg.scenario, "SCENARIO_K2D5");
- assert.equal(cfg.thinking, false);
- });
-
- it("falls back to K2D5 + no thinking for an unknown model id", () => {
- const cfg = resolveModelConfig("k2d6-agent");
- assert.equal(cfg.scenario, "SCENARIO_K2D5");
- assert.equal(cfg.thinking, false);
- });
-});
-
describe("extractKimiJwt", () => {
const { extractKimiJwt } = mod;
diff --git a/tests/unit/executor-xai.test.ts b/tests/unit/executor-xai.test.ts
deleted file mode 100644
index df5d096ecd..0000000000
--- a/tests/unit/executor-xai.test.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-import test from "node:test";
-import assert from "node:assert/strict";
-
-import { XaiExecutor } from "../../open-sse/executors/xai.ts";
-import { getExecutor, hasSpecializedExecutor } from "../../open-sse/executors/index.ts";
-import { xaiProvider } from "../../open-sse/config/providers/registry/xai/index.ts";
-
-// Real xai catalog ids (open-sse/config/providers/registry/xai/index.ts):
-// grok-4.3 — plain, reasoning-capable
-// grok-build-0.1 — build/tool model, no reasoning mode
-// grok-4.20-multi-agent-0309 — neutral (not in either allow/deny list)
-// grok-4.20-0309-reasoning — already encodes reasoning in the id
-// grok-4.20-0309-non-reasoning — already encodes non-reasoning in the id
-
-const credentials = { apiKey: "test-key" };
-
-test("XaiExecutor is registered under the 'xai' key and set as the registry executor", () => {
- assert.equal(hasSpecializedExecutor("xai"), true);
- assert.ok(getExecutor("xai") instanceof XaiExecutor);
- assert.equal(xaiProvider.executor, "xai");
-});
-
-test("strips a -{level} suffix from an allow-listed model and sets reasoning_effort", () => {
- const executor = new XaiExecutor();
-
- for (const level of ["low", "medium", "high", "xhigh"] as const) {
- const body = { model: `grok-4.3-${level}`, messages: [] };
- const out = executor.transformRequest(`grok-4.3-${level}`, body, false, credentials) as Record<
- string,
- unknown
- >;
- assert.equal(out.model, "grok-4.3", `level=${level} should strip suffix from model id`);
- assert.equal(out.reasoning_effort, level, `level=${level} should set reasoning_effort`);
- }
-});
-
-test("suffix parsing also applies to the explicit -reasoning variant without double-mutating it", () => {
- const executor = new XaiExecutor();
- const body = { model: "grok-4.20-0309-reasoning-high", messages: [] };
- const out = executor.transformRequest(
- "grok-4.20-0309-reasoning-high",
- body,
- false,
- credentials
- ) as Record<string, unknown>;
-
- assert.equal(out.model, "grok-4.20-0309-reasoning");
- assert.equal(out.reasoning_effort, "high");
-});
-
-test("strips reasoning_effort for a deny-listed model (grok-build-0.1)", () => {
- const executor = new XaiExecutor();
- const body = { model: "grok-build-0.1", reasoning_effort: "high", messages: [] };
- const out = executor.transformRequest("grok-build-0.1", body, false, credentials) as Record<
- string,
- unknown
- >;
-
- assert.equal(out.model, "grok-build-0.1");
- assert.equal(out.reasoning_effort, undefined);
-});
-
-test("strips reasoning_effort for the explicit -non-reasoning variant (already encodes reasoning state)", () => {
- const executor = new XaiExecutor();
- const body = {
- model: "grok-4.20-0309-non-reasoning",
- reasoning_effort: "high",
- messages: [],
- };
- const out = executor.transformRequest(
- "grok-4.20-0309-non-reasoning",
- body,
- false,
- credentials
- ) as Record<string, unknown>;
-
- assert.equal(out.model, "grok-4.20-0309-non-reasoning");
- assert.equal(out.reasoning_effort, undefined);
-});
-
-test("leaves a plain, unlisted model id and body unchanged (no suffix, not allow/deny listed)", () => {
- const executor = new XaiExecutor();
- const body = { model: "grok-4.20-multi-agent-0309", messages: [{ role: "user", content: "hi" }] };
- const out = executor.transformRequest(
- "grok-4.20-multi-agent-0309",
- body,
- false,
- credentials
- ) as Record<string, unknown>;
-
- assert.equal(out.model, "grok-4.20-multi-agent-0309");
- assert.equal(out.reasoning_effort, undefined);
- assert.deepEqual(out.messages, body.messages);
-});
diff --git a/tests/unit/free-proxy-providers.test.ts b/tests/unit/free-proxy-providers.test.ts
index 1faa53b9cf..a63d53087c 100644
--- a/tests/unit/free-proxy-providers.test.ts
+++ b/tests/unit/free-proxy-providers.test.ts
@@ -29,14 +29,13 @@ test.after(() => {
// ── Registry ─────────────────────────────────────────────────────────────────
-test("getAllProviders returns exactly 4 providers", () => {
+test("getAllProviders returns exactly 3 providers", () => {
const providers = getAllProviders();
- assert.equal(providers.length, 4);
+ assert.equal(providers.length, 3);
const ids = providers.map((p) => p.id);
assert.ok(ids.includes("1proxy"));
assert.ok(ids.includes("proxifly"));
assert.ok(ids.includes("iplocate"));
- assert.ok(ids.includes("webshare"));
});
test("getProvider returns the correct provider by id", () => {
diff --git a/tests/unit/gemini-cli-ansi-sanitization.test.ts b/tests/unit/gemini-cli-ansi-sanitization.test.ts
deleted file mode 100644
index 0291be48f7..0000000000
--- a/tests/unit/gemini-cli-ansi-sanitization.test.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-import { test } from "node:test";
-import assert from "node:assert/strict";
-
-import { parseSSELine, stripAnsiCodes } from "../../open-sse/utils/streamHelpers.ts";
-
-test("parseSSELine resolves an ANSI/VT100-prefixed data: frame (gemini-cli redraw)", () => {
- // gemini-cli prefixes SSE frames with cursor-redraw escapes (\x1b[2K clears the
- // line, \x1b[1A moves the cursor up). 0x1b is not whitespace, so before the fix
- // trimStart().startsWith("data:") failed and the frame was silently dropped (#2273).
- const line = `\x1b[2K\x1b[1Adata: ${JSON.stringify({
- choices: [{ delta: { content: "hi" } }],
- })}`;
- const r = parseSSELine(line);
- assert.ok(r, "expected a parsed payload, got null (frame was dropped)");
- assert.equal(r?.choices?.[0]?.delta?.content, "hi");
-});
-
-test("parseSSELine returns null for a pure-ANSI line (nothing after stripping)", () => {
- assert.equal(parseSSELine("\x1b[2K\x1b[1A"), null);
-});
-
-test("stripAnsiCodes strips CSI/SGR/OSC/C0 but preserves \\t \\n \\r", () => {
- // CSI cursor moves + SGR color codes
- assert.equal(stripAnsiCodes("\x1b[2K\x1b[1Ahello"), "hello");
- assert.equal(stripAnsiCodes("\x1b[31mred\x1b[0m"), "red");
- // OSC sequence terminated by BEL (\x07)
- assert.equal(stripAnsiCodes("\x1b]0;title\x07text"), "text");
- // OSC sequence terminated by ST (\x1b\\)
- assert.equal(stripAnsiCodes("\x1b]8;;https://x\x1b\\link"), "link");
- // stray C0 control byte
- assert.equal(stripAnsiCodes("a\x00b"), "ab");
- // whitespace preserved
- assert.equal(stripAnsiCodes("a\tb\nc\rd"), "a\tb\nc\rd");
-});
-
-test("stripAnsiCodes passes null/undefined through unchanged", () => {
- assert.equal(stripAnsiCodes(null), null);
- assert.equal(stripAnsiCodes(undefined), undefined);
-});
-
-test("stripAnsiCodes runs in linear time on adversarial input (ReDoS guard)", () => {
- const hostile = "\x1b[" + "0;".repeat(50000) + "m";
- const start = Date.now();
- stripAnsiCodes(hostile);
- assert.ok(Date.now() - start < 1000, "stripAnsiCodes should not backtrack catastrophically");
-});
diff --git a/tests/unit/gemini-multipleof-2309.test.ts b/tests/unit/gemini-multipleof-2309.test.ts
deleted file mode 100644
index 5a4f7f3fc6..0000000000
--- a/tests/unit/gemini-multipleof-2309.test.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-/**
- * #2309 — antigravity/gemini returned [400] "Invalid JSON payload received.
- * Unknown name \"multipleOf\" at 'request.tools[0].function_declarations[...]"
- *
- * Root cause: `multipleOf` (a JSON Schema numeric constraint) was NOT listed in
- * `GEMINI_UNSUPPORTED_SCHEMA_KEYS`, so `cleanJSONSchemaForAntigravity` left it in
- * the function-declaration parameters. The Gemini/antigravity upstream (OpenAPI
- * 3.0 schema subset) rejects `multipleOf` with a hard 400.
- *
- * Fix: add `multipleOf` to the unsupported-keys set so it is stripped at every
- * level (top-level property, nested object, and inside array `items`). Sibling
- * numeric constraints `minimum`/`maximum` ARE accepted by Gemini and must stay.
- */
-import test from "node:test";
-import assert from "node:assert/strict";
-
-import {
- cleanJSONSchemaForAntigravity,
- GEMINI_UNSUPPORTED_SCHEMA_KEYS,
-} from "../../open-sse/translator/helpers/geminiHelper.ts";
-
-test("#2309 multipleOf is stripped at all levels for antigravity/gemini schemas", () => {
- const schema = {
- type: "object",
- properties: {
- count: { type: "integer", multipleOf: 2, minimum: 0 },
- ratio: { type: "number", multipleOf: 0.5 },
- tags: { type: "array", items: { type: "number", multipleOf: 10 } },
- },
- };
-
- const cleaned = JSON.stringify(cleanJSONSchemaForAntigravity(schema));
-
- assert.ok(!cleaned.includes("multipleOf"), "multipleOf must be removed");
- // Gemini DOES support minimum/maximum — those must survive.
- assert.ok(cleaned.includes("minimum"), "minimum must be preserved");
-});
-
-test("#2309 multipleOf is in GEMINI_UNSUPPORTED_SCHEMA_KEYS", () => {
- assert.ok(GEMINI_UNSUPPORTED_SCHEMA_KEYS.has("multipleOf"));
-});
diff --git a/tests/unit/gen-contributors.test.ts b/tests/unit/gen-contributors.test.ts
deleted file mode 100644
index d6ba809f8e..0000000000
--- a/tests/unit/gen-contributors.test.ts
+++ /dev/null
@@ -1,110 +0,0 @@
-import test from "node:test";
-import assert from "node:assert/strict";
-
-const mod = await import("../../scripts/release/gen-contributors.mjs");
-const {
- extractVersionSection,
- parseContributors,
- renderContributors,
- injectContributors,
- NOISE_HANDLES,
-} = mod;
-
-const FIXTURE = `# Changelog
-
-## [Unreleased]
-
----
-
-## [3.9.0] — 2026-08-01
-
-### ✨ New Features
-
-- **feat(a):** thing one. ([#100](https://github.com/x/y/pull/100) — thanks @alice)
-- **feat(b):** uses \`@toon-format/toon\` and \`@dnd-kit\`. ([#101](https://github.com/x/y/pull/101) — thanks @bob)
-
-### 🔧 Bug Fixes
-
-- **fix(c):** direct commit fix. (thanks @carol)
-- **fix(d):** extracted. Extracted from [#102](https://github.com/x/y/pull/102) by [@dave](https://github.com/dave).
-
-### 📝 Maintenance
-
-- **refactor(rollup):** god-file split ([#200](https://github.com/x/y/pull/200), [#201](https://github.com/x/y/pull/201) — thanks @erin); editorconfig ([#202](https://github.com/x/y/pull/202) — thanks @frank). — thanks @diegosouzapw
-
----
-
-## [3.8.99] — 2026-07-31
-
-### 🔧 Bug Fixes
-
-- **fix(z):** other version, must not leak. ([#999](https://github.com/x/y/pull/999) — thanks @zoe)
-
----
-`;
-
-test("extractVersionSection returns only the target version body (not the next section)", () => {
- const sec = extractVersionSection(FIXTURE, "3.9.0");
- assert.ok(sec.includes("thing one"), "includes 3.9.0 content");
- assert.ok(!sec.includes("must not leak"), "excludes 3.8.99 content");
- assert.ok(!sec.includes("#999"), "does not bleed into next version");
-});
-
-test("parseContributors credits per parenthetical group, not a flat scan", () => {
- const agg = parseContributors(extractVersionSection(FIXTURE, "3.9.0"));
- // rollup: erin gets 200+201, frank gets 202 — NOT both getting all three
- assert.deepEqual(
- [...agg.get("erin")].sort((a, b) => a - b),
- [200, 201]
- );
- assert.deepEqual([...agg.get("frank")], [202]);
- // simple bullets
- assert.deepEqual([...agg.get("alice")], [100]);
- // direct-commit credit with no PR ref
- assert.ok(agg.has("carol") && agg.get("carol").size === 0);
- // "Extracted from #N by @X"
- assert.deepEqual([...agg.get("dave")], [102]);
-});
-
-test("noise handles and the maintainer are excluded from the contributor map", () => {
- const agg = parseContributors(extractVersionSection(FIXTURE, "3.9.0"));
- assert.ok(!agg.has("toon-format"), "package scope is not a contributor");
- assert.ok(!agg.has("dnd-kit"), "package scope is not a contributor");
- assert.ok(!agg.has("diegosouzapw"), "maintainer is rendered separately, not in the map");
- assert.ok(NOISE_HANDLES.has("toon-format"));
-});
-
-test("renderContributors emits an alphabetical table with maintainer last", () => {
- const agg = parseContributors(extractVersionSection(FIXTURE, "3.9.0"));
- const table = renderContributors("3.9.0", agg);
- assert.ok(table.startsWith("### 🙌 Contributors"));
- const rows = table.split("\n").filter((l) => l.startsWith("| [@"));
- const handles = rows.map((r) => r.match(/@([A-Za-z0-9_-]+)/)[1]);
- assert.equal(handles[handles.length - 1], "diegosouzapw", "maintainer is last");
- const external = handles.slice(0, -1);
- assert.deepEqual(
- external,
- [...external].sort((a, b) => a.localeCompare(b)),
- "external sorted"
- );
- assert.ok(table.includes("| [@carol](https://github.com/carol) | direct commit / report |"));
-});
-
-test("injectContributors inserts before the closing --- and is idempotent", () => {
- const once = injectContributors(
- FIXTURE,
- "3.9.0",
- renderContributors("3.9.0", parseContributors(extractVersionSection(FIXTURE, "3.9.0")))
- );
- assert.ok(once.includes("### 🙌 Contributors"), "section injected");
- // 3.8.99 untouched
- assert.ok(once.includes("must not leak"));
- // idempotent: injecting again does not duplicate
- const twice = injectContributors(
- once,
- "3.9.0",
- renderContributors("3.9.0", parseContributors(extractVersionSection(once, "3.9.0")))
- );
- const count = (twice.match(/### 🙌 Contributors/g) || []).length;
- assert.equal(count, 1, "no duplicate Contributors section on re-run");
-});
diff --git a/tests/unit/gitlab-duo-toolcalls-6051.test.ts b/tests/unit/gitlab-duo-toolcalls-6051.test.ts
deleted file mode 100644
index 3bf8df51ef..0000000000
--- a/tests/unit/gitlab-duo-toolcalls-6051.test.ts
+++ /dev/null
@@ -1,145 +0,0 @@
-import test from "node:test";
-import assert from "node:assert/strict";
-
-import { GitlabExecutor } from "../../open-sse/executors/gitlab.ts";
-
-function jsonResponse(body: unknown, status = 200) {
- return new Response(JSON.stringify(body), {
- status,
- headers: { "Content-Type": "application/json" },
- });
-}
-
-const WEATHER_TOOL = {
- type: "function",
- function: {
- name: "get_weather",
- description: "Get the current weather for a city",
- parameters: {
- type: "object",
- properties: { city: { type: "string" } },
- required: ["city"],
- },
- },
-};
-
-test("GitlabExecutor emulates OpenAI tool_calls when body.tools is present (#6051)", async () => {
- const executor = new GitlabExecutor();
- const originalFetch = globalThis.fetch;
- const calls: Array<{ url: string; body: Record<string, unknown> }> = [];
-
- // Upstream (GitLab code_suggestions) replies with the tool invocation as raw
- // text, exactly how a web/completion model would when handed the tool contract.
- globalThis.fetch = async (url, init = {}) => {
- calls.push({ url: String(url), body: JSON.parse(String(init.body || "{}")) });
- return jsonResponse({
- model: { name: "code-gecko" },
- choices: [
- {
- text: 'Sure, let me check.\n<tool>{"name": "get_weather", "arguments": {"city": "Paris"}}</tool>',
- },
- ],
- });
- };
-
- try {
- const result = await executor.execute({
- model: "gitlab-duo-code-suggestions",
- body: {
- messages: [{ role: "user", content: "What's the weather in Paris?" }],
- tools: [WEATHER_TOOL],
- tool_choice: "auto",
- },
- stream: false,
- credentials: { apiKey: "glpat-test" },
- signal: AbortSignal.timeout(10_000),
- log: null,
- } as any);
-
- // The serialized tool contract must reach the GitLab prompt.
- assert.equal(calls.length, 1);
- assert.match(
- String((calls[0].body.current_file as any)?.content_above_cursor ?? ""),
- /get_weather/,
- "tool contract must be serialized into the GitLab prompt"
- );
-
- const body = (await result.response.json()) as any;
- const choice = body.choices[0];
- assert.equal(choice.finish_reason, "tool_calls");
- assert.ok(Array.isArray(choice.message.tool_calls), "tool_calls array must be present");
- assert.equal(choice.message.tool_calls.length, 1);
- assert.equal(choice.message.tool_calls[0].type, "function");
- assert.equal(choice.message.tool_calls[0].function.name, "get_weather");
- assert.deepEqual(JSON.parse(choice.message.tool_calls[0].function.arguments), {
- city: "Paris",
- });
- assert.equal(choice.message.content, null);
- } finally {
- globalThis.fetch = originalFetch;
- }
-});
-
-test("GitlabExecutor streams a tool_calls chunk when tools are present (#6051)", async () => {
- const executor = new GitlabExecutor();
- const originalFetch = globalThis.fetch;
-
- globalThis.fetch = async () =>
- jsonResponse({
- model: { name: "code-gecko" },
- choices: [{ text: '<tool>{"name": "get_weather", "arguments": {"city": "Paris"}}</tool>' }],
- });
-
- try {
- const result = await executor.execute({
- model: "gitlab-duo-code-suggestions",
- body: {
- messages: [{ role: "user", content: "weather in Paris?" }],
- tools: [WEATHER_TOOL],
- },
- stream: true,
- credentials: { apiKey: "glpat-test" },
- signal: AbortSignal.timeout(10_000),
- log: null,
- } as any);
-
- assert.equal(result.response.headers.get("Content-Type"), "text/event-stream");
- const text = await result.response.text();
- assert.match(text, /"tool_calls"/, "SSE stream must carry a tool_calls delta");
- assert.match(text, /get_weather/);
- assert.match(text, /"finish_reason":"tool_calls"/);
- assert.match(text, /data: \[DONE\]/);
- } finally {
- globalThis.fetch = originalFetch;
- }
-});
-
-test("GitlabExecutor keeps plain-text finish_reason:stop for non-tool requests (#6051)", async () => {
- const executor = new GitlabExecutor();
- const originalFetch = globalThis.fetch;
-
- globalThis.fetch = async () =>
- jsonResponse({
- model: { name: "code-gecko" },
- choices: [{ text: "def hello():\n return 'world'" }],
- });
-
- try {
- const result = await executor.execute({
- model: "gitlab-duo-code-suggestions",
- body: { messages: [{ role: "user", content: "Write a hello world function" }] },
- stream: false,
- credentials: { apiKey: "glpat-test" },
- signal: AbortSignal.timeout(10_000),
- log: null,
- } as any);
-
- const body = (await result.response.json()) as any;
- const choice = body.choices[0];
- assert.equal(choice.finish_reason, "stop");
- assert.equal(choice.message.tool_calls, undefined);
- assert.match(choice.message.content, /hello/);
- } finally {
- globalThis.fetch = originalFetch;
- }
-});
diff --git a/tests/unit/gptoss-provider-inference-5852.test.ts b/tests/unit/gptoss-provider-inference-5852.test.ts
deleted file mode 100644
index f733afc4f8..0000000000
--- a/tests/unit/gptoss-provider-inference-5852.test.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-import test from "node:test";
-import assert from "node:assert/strict";
-
-import { getModelInfoCore } from "../../open-sse/services/model.ts";
-
-// Bug #5852: resolveModelByProviderInference() in open-sse/services/model.ts had an
-// unconditional `/^gpt-/i` heuristic that fired for ANY model id starting with
-// "gpt-", hijacking open-weight models cataloged under other providers (e.g.
-// "gpt-oss-120b", served by fireworks/cerebras/scaleway/byteplus) into
-// provider "openai", which does not carry them — producing a 404 with no
-// fallback for bare (non-combo) requests.
-//
-// Fix: the fallback must only apply when there are ZERO known catalog
-// candidates for the model id (providers.length === 0).
-
-const KNOWN_GPT_OSS_120B_PROVIDERS = new Set(["fireworks", "cerebras", "scaleway", "byteplus"]);
-
-test("gpt-oss-120b resolves into its cataloged open-weight providers, not openai (#5852)", async () => {
- const info = await getModelInfoCore("gpt-oss-120b", null);
-
- assert.notEqual(
- info.provider,
- "openai",
- "gpt-oss-120b must not be hijacked into the openai-family fallback"
- );
-
- // Multiple providers catalog this open-weight model id, so the resolver correctly
- // reports it as ambiguous (asking the caller to disambiguate with a provider/model
- // prefix) instead of silently defaulting to openai (which doesn't carry it → 404).
- assert.equal(info.errorType, "ambiguous_model");
- assert.ok(Array.isArray(info.candidateProviders) && info.candidateProviders.length > 0);
- assert.ok(
- info.candidateProviders.some((p: string) => KNOWN_GPT_OSS_120B_PROVIDERS.has(p)),
- `expected at least one candidate from ${[...KNOWN_GPT_OSS_120B_PROVIDERS].join(
- ", "
- )}, got ${JSON.stringify(info.candidateProviders)}`
- );
- assert.ok(
- !info.candidateProviders.includes("openai"),
- "openai must not be listed as a candidate for gpt-oss-120b"
- );
-});
-
-test("regression guard: a genuinely-uncataloged openai-family id still falls back to openai (#5852)", async () => {
- const info = await getModelInfoCore("gpt-5.9-imaginary-unreleased", null);
-
- assert.equal(
- info.provider,
- "openai",
- "uncataloged gpt-* ids with zero known candidates must still fall back to openai"
- );
-});
diff --git a/tests/unit/grok-web-executor-split.test.ts b/tests/unit/grok-web-executor-split.test.ts
deleted file mode 100644
index a898b5c910..0000000000
--- a/tests/unit/grok-web-executor-split.test.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import { test } from "node:test";
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { fileURLToPath } from "node:url";
-import { dirname, join } from "node:path";
-
-// Split-guard for the grok-web executor extraction.
-// Pure clusters live in 4 leaves: types.ts (stream types), tool-bridge.ts (OpenAI<->Grok
-// tool translation), native-tools.ts (native-tool selection + mapping), text-cleanup.ts
-// (markup cleanup). All are module-private (no host re-export). No leaf imports the host.
-const HERE = dirname(fileURLToPath(import.meta.url));
-const DIR = join(HERE, "../../open-sse/executors/grok-web");
-const HOST = join(HERE, "../../open-sse/executors/grok-web.ts");
-
-test("leaves are acyclic: none imports the host, layered types<-tool-bridge<-native-tools", () => {
- for (const f of ["types", "tool-bridge", "native-tools", "text-cleanup"]) {
- const src = readFileSync(join(DIR, `${f}.ts`), "utf8");
- assert.doesNotMatch(src, /from "\.\.\/grok-web\.ts"/, `${f} must not import the host`);
- }
- assert.doesNotMatch(readFileSync(join(DIR, "types.ts"), "utf8"), /^import /m);
- assert.match(readFileSync(join(DIR, "native-tools.ts"), "utf8"), /from "\.\/tool-bridge\.ts"/);
-});
-
-test("host imports the tool-bridge + native-tools + text-cleanup helpers", () => {
- const host = readFileSync(HOST, "utf8");
- assert.match(host, /from "\.\/grok-web\/tool-bridge\.ts"/);
- assert.match(host, /from "\.\/grok-web\/native-tools\.ts"/);
- assert.match(host, /from "\.\/grok-web\/text-cleanup\.ts"/);
-});
-
-test("text-cleanup strips Grok markup", async () => {
- const { cleanGrokContentText } =
- await import("../../open-sse/executors/grok-web/text-cleanup.ts");
- assert.equal(typeof cleanGrokContentText, "function");
- assert.equal(typeof cleanGrokContentText("plain text"), "string");
-});
diff --git a/tests/unit/hf-model-suggestions.test.ts b/tests/unit/hf-model-suggestions.test.ts
deleted file mode 100644
index 53b6491867..0000000000
--- a/tests/unit/hf-model-suggestions.test.ts
+++ /dev/null
@@ -1,103 +0,0 @@
-import test from "node:test";
-import assert from "node:assert/strict";
-
-import {
- resolveHfPipelineTag,
- sortHfSuggestedModels,
- type HfModelSummary,
-} from "../../open-sse/services/hfModelSuggestions.ts";
-
-test("resolveHfPipelineTag: maps the 'image' kind to HF's text-to-image pipeline_tag", () => {
- assert.equal(resolveHfPipelineTag("image"), "text-to-image");
-});
-
-test("resolveHfPipelineTag: returns null for an unmapped kind", () => {
- assert.equal(resolveHfPipelineTag("video"), null);
- assert.equal(resolveHfPipelineTag("does-not-exist"), null);
-});
-
-test("sortHfSuggestedModels: sorts descending by downloads (default)", () => {
- const models: HfModelSummary[] = [
- { id: "a/low", downloads: 10, likes: 500 },
- { id: "b/high", downloads: 1000, likes: 1 },
- { id: "c/mid", downloads: 100, likes: 50 },
- ];
-
- const result = sortHfSuggestedModels(models);
- assert.deepEqual(
- result.map((m) => m.id),
- ["b/high", "c/mid", "a/low"]
- );
-});
-
-test("sortHfSuggestedModels: sorts descending by likes when requested", () => {
- const models: HfModelSummary[] = [
- { id: "a/low", downloads: 10, likes: 500 },
- { id: "b/high", downloads: 1000, likes: 1 },
- { id: "c/mid", downloads: 100, likes: 50 },
- ];
-
- const result = sortHfSuggestedModels(models, "likes");
- assert.deepEqual(
- result.map((m) => m.id),
- ["a/low", "c/mid", "b/high"]
- );
-});
-
-test("sortHfSuggestedModels: caps results at the requested limit", () => {
- const models: HfModelSummary[] = Array.from({ length: 30 }, (_, i) => ({
- id: `model/${i}`,
- downloads: i,
- }));
-
- const result = sortHfSuggestedModels(models, "downloads", 5);
- assert.equal(result.length, 5);
- // Highest downloads (29..25) come first
- assert.deepEqual(
- result.map((m) => m.id),
- ["model/29", "model/28", "model/27", "model/26", "model/25"]
- );
-});
-
-test("sortHfSuggestedModels: drops entries without a usable string id", () => {
- const models = [
- { id: "", downloads: 999 },
- { id: " ", downloads: 998 },
- { downloads: 997 },
- { id: "valid/model", downloads: 1 },
- ] as HfModelSummary[];
-
- const result = sortHfSuggestedModels(models);
- assert.deepEqual(
- result.map((m) => m.id),
- ["valid/model"]
- );
-});
-
-test("sortHfSuggestedModels: treats missing/non-numeric metric values as 0 (no throw)", () => {
- const models = [
- { id: "a/no-metric" },
- { id: "b/has-metric", downloads: 5 },
- { id: "c/nan-metric", downloads: Number.NaN },
- ] as HfModelSummary[];
-
- const result = sortHfSuggestedModels(models, "downloads");
- assert.deepEqual(
- result.map((m) => m.id),
- ["b/has-metric", "a/no-metric", "c/nan-metric"]
- );
-});
-
-test("sortHfSuggestedModels: handles an empty input array", () => {
- assert.deepEqual(sortHfSuggestedModels([]), []);
-});
-
-test("sortHfSuggestedModels: falls back to a default limit for an invalid limit value", () => {
- const models: HfModelSummary[] = Array.from({ length: 25 }, (_, i) => ({
- id: `model/${i}`,
- downloads: i,
- }));
-
- const result = sortHfSuggestedModels(models, "downloads", 0);
- assert.equal(result.length, 20);
-});
diff --git a/tests/unit/huggingchat-jsonl-split.test.ts b/tests/unit/huggingchat-jsonl-split.test.ts
deleted file mode 100644
index e6d952683a..0000000000
--- a/tests/unit/huggingchat-jsonl-split.test.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { test } from "node:test";
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { fileURLToPath } from "node:url";
-import { dirname, join } from "node:path";
-
-// Split-guard for the huggingchat executor JSONL-stream extraction.
-// The pure JSONL->OpenAI-SSE translation lives in huggingchat/jsonlStream.ts
-// (consumes a passed-in ReadableStream; no host state/fetch/auth). Host imports it back.
-const HERE = dirname(fileURLToPath(import.meta.url));
-const EXE = join(HERE, "../../open-sse/executors");
-const HOST = join(EXE, "huggingchat.ts");
-const LEAF = join(EXE, "huggingchat/jsonlStream.ts");
-
-test("leaf hosts the jsonl translators and does not import the host", () => {
- const src = readFileSync(LEAF, "utf8");
- assert.match(src, /export async function\* streamJsonlToOpenAi\b/);
- assert.match(src, /export async function readJsonlResponse\b/);
- assert.match(src, /export function (sseChunk|parseJsonlLine)\b/);
- assert.doesNotMatch(src, /from "\.\.\/huggingchat\.ts"/);
-});
-
-test("host imports the jsonl translators back from the leaf", () => {
- const host = readFileSync(HOST, "utf8");
- assert.match(host, /from "\.\/huggingchat\/jsonlStream\.ts"/);
-});
-
-test("parseJsonlLine parses a jsonl data line", async () => {
- const { parseJsonlLine } = await import("../../open-sse/executors/huggingchat/jsonlStream.ts");
- assert.equal(typeof parseJsonlLine, "function");
- assert.doesNotThrow(() => parseJsonlLine("not json"));
-});
diff --git a/tests/unit/i18n-detect-browser-locale.test.ts b/tests/unit/i18n-detect-browser-locale.test.ts
deleted file mode 100644
index d55748fb96..0000000000
--- a/tests/unit/i18n-detect-browser-locale.test.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import { describe, it } from "node:test";
-import assert from "node:assert/strict";
-import { detectBrowserLocale } from "../../src/i18n/detectBrowserLocale";
-
-const SUPPORTED_LOCALES = ["en", "pt-BR", "es", "zh-TW", "fr", "de"] as const;
-
-describe("detectBrowserLocale", () => {
- it("returns the exact match when a browser language equals a supported locale", () => {
- assert.equal(detectBrowserLocale(["pt-BR"], SUPPORTED_LOCALES), "pt-BR");
- });
-
- it("folds zh-HK to zh-TW when zh-TW is supported", () => {
- assert.equal(detectBrowserLocale(["zh-HK"], SUPPORTED_LOCALES), "zh-TW");
- });
-
- it("folds zh-MO to zh-TW when zh-TW is supported", () => {
- assert.equal(detectBrowserLocale(["zh-MO"], SUPPORTED_LOCALES), "zh-TW");
- });
-
- it("falls back to a language-prefix match when no exact match exists", () => {
- assert.equal(detectBrowserLocale(["en-US"], SUPPORTED_LOCALES), "en");
- });
-
- it("returns null when nothing matches", () => {
- assert.equal(detectBrowserLocale(["ja-JP"], SUPPORTED_LOCALES), null);
- });
-
- it("returns null for an empty languages list", () => {
- assert.equal(detectBrowserLocale([], SUPPORTED_LOCALES), null);
- });
-
- it("returns null for an empty locales list", () => {
- assert.equal(detectBrowserLocale(["en-US"], []), null);
- });
-
- it("tries each browser language in order until one matches", () => {
- assert.equal(detectBrowserLocale(["ja-JP", "fr-CA"], SUPPORTED_LOCALES), "fr");
- });
-
- it("is case-insensitive", () => {
- assert.equal(detectBrowserLocale(["PT-br"], SUPPORTED_LOCALES), "pt-BR");
- });
-});
diff --git a/tests/unit/kiro-claude-sonnet-5-2267.test.ts b/tests/unit/kiro-claude-sonnet-5-2267.test.ts
index fef92c14e5..ede4c805cc 100644
--- a/tests/unit/kiro-claude-sonnet-5-2267.test.ts
+++ b/tests/unit/kiro-claude-sonnet-5-2267.test.ts
@@ -3,10 +3,7 @@ import assert from "node:assert/strict";
import { kiroProvider } from "../../open-sse/config/providers/registry/kiro/index.ts";
-const { getNextFamilyFallback } = await import("../../open-sse/services/modelFamilyFallback.ts");
-
-// Regression for the port of decolua/9router#2267 ("claude-sonnet-5 is not supported"),
-// upstream PR diegosouzapw/OmniRoute#5796.
+// Regression for the port of decolua/9router#2267 ("claude-sonnet-5 is not supported").
//
// The Kiro provider's OAuth model catalog lives in `registry/kiro/index.ts` `models[]`.
// That list is both the model selector's source and the fallback for the live
@@ -31,12 +28,3 @@ test("kiro claude-sonnet-5 declares the 1M-context / 128K-output capability", ()
assert.equal(sonnet5.contextLength, 1000000);
assert.equal(sonnet5.maxOutputTokens, 128000);
});
-
-test("claude-sonnet-5 degrades to the Sonnet family, not Opus", () => {
- // Sonnet 5 is Sonnet-tier: its first fallback must be a cheaper Sonnet, never an Opus.
- const next = getNextFamilyFallback("kiro/claude-sonnet-5", new Set(["kiro/claude-sonnet-5"]));
- assert.ok(
- next && /claude-sonnet-4/.test(next),
- `expected claude-sonnet-5 to fall back within the Sonnet family, got: ${next}`
- );
-});
diff --git a/tests/unit/kiro-eventstream-split.test.ts b/tests/unit/kiro-eventstream-split.test.ts
deleted file mode 100644
index 9ba3cd4c32..0000000000
--- a/tests/unit/kiro-eventstream-split.test.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import { test } from "node:test";
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { fileURLToPath } from "node:url";
-import { dirname, join } from "node:path";
-
-// Split-guard for the kiro executor EventStream framing extraction.
-// The pure AWS EventStream binary framing (ByteQueue, CRC32, parseEventFrame) lives in
-// kiro/eventstream.ts (self-contained, no host imports). Host imports back what it uses.
-const HERE = dirname(fileURLToPath(import.meta.url));
-const EXE = join(HERE, "../../open-sse/executors");
-const HOST = join(EXE, "kiro.ts");
-const LEAF = join(EXE, "kiro/eventstream.ts");
-
-test("leaf hosts the framing primitives and does not import the host", () => {
- const src = readFileSync(LEAF, "utf8");
- assert.match(src, /export class ByteQueue\b/);
- assert.match(src, /export function crc32\b/);
- assert.match(src, /export function parseEventFrame\b/);
- assert.doesNotMatch(src, /from "\.\.\/kiro\.ts"/);
-});
-
-test("host imports the framing primitives back from the leaf", () => {
- const host = readFileSync(HOST, "utf8");
- assert.match(host, /from "\.\/kiro\/eventstream\.ts"/);
-});
-
-test("crc32 is deterministic and ByteQueue buffers bytes", async () => {
- const { crc32, ByteQueue } = await import("../../open-sse/executors/kiro/eventstream.ts");
- const a = crc32(new Uint8Array([1, 2, 3]));
- const b = crc32(new Uint8Array([1, 2, 3]));
- assert.equal(a, b);
- const q = new ByteQueue();
- assert.equal(typeof q, "object");
-});
diff --git a/tests/unit/kiro-system-reminder-2306.test.ts b/tests/unit/kiro-system-reminder-2306.test.ts
deleted file mode 100644
index db05743716..0000000000
--- a/tests/unit/kiro-system-reminder-2306.test.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-/**
- * #2306 — When Claude Code routes through the Kiro/CodeWhisperer backend, the
- * `system` message was normalized to `role: user` WITHOUT any wrapper, so the
- * full system prompt (env info, tool defs, memory instructions, etc.) appeared
- * as raw user text — indistinguishable from real user input, polluting context.
- *
- * Fix: wrap system-origin content in `<system-reminder>...</system-reminder>`
- * before it is merged into the Kiro user message. Real user turns stay raw.
- */
-import test from "node:test";
-import assert from "node:assert/strict";
-
-import { buildKiroPayload } from "../../open-sse/translator/request/openai-to-kiro.ts";
-
-test("#2306 system prompt is wrapped in <system-reminder> for Kiro, not raw user text", () => {
- const body = {
- messages: [
- { role: "system", content: "You are Claude Code. ENV: cwd=/tmp. Secret: do not reveal." },
- { role: "user", content: "hello there" },
- ],
- };
-
- const payload = JSON.stringify(buildKiroPayload("claude-sonnet-4-5", body, false, {}));
-
- assert.ok(payload.includes("<system-reminder>"), "system content must be wrapped");
- assert.ok(payload.includes("You are Claude Code"), "system text must still be present");
- // The real user turn must NOT be wrapped.
- assert.ok(payload.includes("hello there"), "user text preserved");
-});
-
-test("#2306 a plain user-only request is never wrapped in <system-reminder>", () => {
- const body = { messages: [{ role: "user", content: "just a normal question" }] };
- const payload = JSON.stringify(buildKiroPayload("claude-sonnet-4-5", body, false, {}));
- assert.ok(!payload.includes("<system-reminder>"), "no system → no wrapper");
-});
diff --git a/tests/unit/list-uncovered-commits.test.ts b/tests/unit/list-uncovered-commits.test.ts
deleted file mode 100644
index a49cbcecfa..0000000000
--- a/tests/unit/list-uncovered-commits.test.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-import test from "node:test";
-import assert from "node:assert/strict";
-
-const mod = await import("../../scripts/release/list-uncovered-commits.mjs");
-const { refsOf, typeOf, computeUncovered, changelogRefWindow } = mod;
-
-test("refsOf extracts every #N from a subject", () => {
- assert.deepEqual(refsOf("fix(x): thing (#5842) (#5901)"), [5842, 5901]);
- assert.deepEqual(refsOf("chore: no refs here"), []);
-});
-
-test("typeOf reads the conventional-commit type", () => {
- assert.equal(typeOf("feat(api): x"), "feat");
- assert.equal(typeOf("fix: y"), "fix");
- assert.equal(typeOf("refactor(db)!: z"), "refactor");
- assert.equal(typeOf("Merge branch main"), "other");
-});
-
-test("computeUncovered: a commit is covered iff ANY of its refs is in the changelog window", () => {
- const commits = [
- { hash: "a1", subject: "fix(x): covered by issue ref (#100)" }, // issue 100 in changelog
- { hash: "b2", subject: "feat(y): uncovered feature (#200)" }, // 200 not in changelog
- { hash: "c3", subject: "refactor(z): internal (#300)" }, // rollup type, uncovered
- { hash: "d4", subject: "chore: no ref at all" }, // no ref → uncovered, rollup
- ];
- const refs = new Set([100]); // only #100 is documented
- const { covered, uncovered } = computeUncovered(commits, refs);
- assert.equal(covered, 1);
- assert.equal(uncovered.length, 3);
- const byHash = Object.fromEntries(uncovered.map((c) => [c.hash, c]));
- assert.equal(byHash.b2.rollup, false, "feat is user-facing, not a rollup candidate");
- assert.equal(byHash.c3.rollup, true, "refactor is a rollup candidate");
- assert.equal(byHash.d4.rollup, true, "chore is a rollup candidate");
-});
-
-test("changelogRefWindow scans [Unreleased] + the version section but not older versions", () => {
- const cl = `# Changelog
-
-## [Unreleased]
-
-- **fix:** something ([#10](u))
-
----
-
-## [3.9.0] — x
-
-### 🔧 Bug Fixes
-
-- **fix(a):** landed ([#20](u))
-
----
-
-## [3.8.99] — y
-
-- **fix(old):** must not count ([#999](u))
-
----
-`;
- const refs = changelogRefWindow(cl, "3.9.0");
- assert.ok(refs.has(10), "picks up [Unreleased] refs");
- assert.ok(refs.has(20), "picks up the target version refs");
- assert.ok(!refs.has(999), "does NOT bleed into the previous version");
-});
diff --git a/tests/unit/mcp-session-sweep.test.ts b/tests/unit/mcp-session-sweep.test.ts
index 95a09c2ea1..8848d60ab3 100644
--- a/tests/unit/mcp-session-sweep.test.ts
+++ b/tests/unit/mcp-session-sweep.test.ts
@@ -347,76 +347,3 @@ test("handleMcpStreamableHTTP keeps 400 for a missing session id (non-initialize
// only the *present-but-unknown* case changed to 404. This must NOT regress.
assert.equal(res.status, 400);
});
-
-test("handleMcpStreamableHTTP auto-recovers when stale session id is sent with initialize", async () => {
- mod.shutdownMcpHttp();
-
- const initReq = new Request("http://localhost/api/mcp/stream", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- Accept: "application/json, text/event-stream",
- },
- body: JSON.stringify({
- jsonrpc: "2.0",
- method: "initialize",
- id: 1,
- params: {
- protocolVersion: "2025-03-26",
- capabilities: {},
- clientInfo: { name: "test-client", version: "1.0.0" },
- },
- }),
- });
-
- const firstRes = await mod.handleMcpStreamableHTTP(initReq);
- const staleSessionId = firstRes.headers.get("mcp-session-id");
- if (!staleSessionId) {
- mod.shutdownMcpHttp();
- return;
- }
-
- mod.shutdownMcpHttp();
- assert.equal(mod.isMcpHttpActive(), false);
-
- const reinitReq = new Request("http://localhost/api/mcp/stream", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- Accept: "application/json, text/event-stream",
- "mcp-session-id": staleSessionId,
- },
- body: JSON.stringify({
- jsonrpc: "2.0",
- method: "initialize",
- id: 2,
- params: {
- protocolVersion: "2025-03-26",
- capabilities: {},
- clientInfo: { name: "test-client", version: "1.0.0" },
- },
- }),
- });
-
- const recoveryRes = await mod.handleMcpStreamableHTTP(reinitReq);
-
- assert.notEqual(
- recoveryRes.status,
- 404,
- "Stale session + initialize must NOT return 404 — server should auto-recover"
- );
- assert.ok(
- recoveryRes.status >= 200 && recoveryRes.status < 300,
- `Expected 2xx response on auto-recovery, got ${recoveryRes.status}`
- );
-
- const newSessionId = recoveryRes.headers.get("mcp-session-id");
- assert.ok(newSessionId, "Server must issue a new mcp-session-id on auto-recovery");
- assert.equal(
- mod.isMcpHttpActive(),
- true,
- "Server must have an active session after auto-recovery"
- );
-
- mod.shutdownMcpHttp();
-});
diff --git a/tests/unit/minimax-media-servicekinds.test.ts b/tests/unit/minimax-media-servicekinds.test.ts
index 6eecb2a1c2..5cb64cb638 100644
--- a/tests/unit/minimax-media-servicekinds.test.ts
+++ b/tests/unit/minimax-media-servicekinds.test.ts
@@ -81,19 +81,6 @@ test("media listing filter surfaces minimax where the old declared-only filter m
assert.ok(oldListFor("tts").length < newListFor("tts").length, "fix surfaces additional tts providers");
});
-test("ocr is a registry-backed media kind and mistral derives it", () => {
- assert.ok(
- (REGISTRY_MEDIA_KINDS as readonly string[]).includes("ocr"),
- "REGISTRY_MEDIA_KINDS should include ocr once the OCR registry is wired"
- );
- assert.ok(
- getRegistryMediaKinds("mistral").includes("ocr" as never),
- "mistral should derive the ocr media kind from OCR_PROVIDERS"
- );
- const merged = resolveProviderServiceKinds("mistral", ["llm"]);
- assert.ok(merged.includes("ocr"), `expected ocr in ${merged.join(",")}`);
-});
-
test("derived kinds are always within the known media-kind set", () => {
for (const id of Object.keys(AI_PROVIDERS)) {
for (const kind of getRegistryMediaKinds(id)) {
diff --git a/tests/unit/modelscope-provider.test.ts b/tests/unit/modelscope-provider.test.ts
deleted file mode 100644
index c4bdbfce73..0000000000
--- a/tests/unit/modelscope-provider.test.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-import test from "node:test";
-import assert from "node:assert/strict";
-
-import { modelscopeProvider } from "../../open-sse/config/providers/registry/modelscope/index.ts";
-import { REGISTRY } from "../../open-sse/config/providerRegistry.ts";
-import { APIKEY_PROVIDERS } from "../../src/shared/constants/providers/apikey/index.ts";
-import { AI_PROVIDERS, getProviderById } from "../../src/shared/constants/providers.ts";
-
-// Upstream 9router PR #1764 (@tn5052) ports ModelScope (Alibaba 魔搭) as an OpenAI-compatible
-// BYOK free-tier provider. The upstream PR hardcoded `https://api-inference.modelscope.ai/...`
-// (`.ai` TLD) — ModelScope's own docs confirm the real production domain is
-// `api-inference.modelscope.cn` (`.cn` TLD). This suite locks in the verified domain and
-// guards against a regression back to the unverified `.ai` domain.
-
-test("providers-shape: modelscope is registered in APIKEY_PROVIDERS metadata", () => {
- assert.ok("modelscope" in APIKEY_PROVIDERS, "modelscope missing from APIKEY_PROVIDERS");
- const meta = (APIKEY_PROVIDERS as Record<string, Record<string, unknown>>).modelscope;
- assert.equal(meta.id, "modelscope");
- assert.equal(meta.alias, "ms");
- assert.equal(meta.name, "ModelScope");
- assert.equal(meta.website, "https://modelscope.cn");
- assert.equal(meta.hasFree, true);
-});
-
-test("providers-shape: modelscope is a canonical AI_PROVIDERS entry resolvable by id", () => {
- assert.ok("modelscope" in AI_PROVIDERS, "modelscope missing from AI_PROVIDERS");
- const provider = getProviderById("modelscope");
- assert.ok(provider, "getProviderById('modelscope') returned nothing");
- assert.equal(provider?.id, "modelscope");
-});
-
-test("registry resolution: modelscope resolves in the provider REGISTRY as OpenAI-compatible", () => {
- assert.ok("modelscope" in REGISTRY, "modelscope missing from REGISTRY");
- const entry = REGISTRY.modelscope;
- assert.equal(entry.format, "openai");
- assert.equal(entry.executor, "default");
- assert.equal(entry.authType, "apikey");
- assert.equal(entry.authHeader, "bearer");
- assert.equal(entry, modelscopeProvider);
-});
-
-test("registry resolution: modelscope uses passthrough models with an empty static seed list", () => {
- assert.equal(modelscopeProvider.passthroughModels, true);
- assert.deepEqual(modelscopeProvider.models, []);
- assert.equal(
- modelscopeProvider.modelsUrl,
- "https://api-inference.modelscope.cn/v1/models",
- "modelsUrl must point at the verified .cn domain"
- );
-});
-
-test("baseUrl guard: modelscope targets the verified api-inference.modelscope.cn domain (not .ai)", () => {
- assert.equal(
- modelscopeProvider.baseUrl,
- "https://api-inference.modelscope.cn/v1/chat/completions"
- );
- assert.ok(
- modelscopeProvider.baseUrl.includes("api-inference.modelscope.cn"),
- `baseUrl must use the verified .cn domain, got: ${modelscopeProvider.baseUrl}`
- );
- assert.ok(
- !modelscopeProvider.baseUrl.includes("modelscope.ai"),
- "baseUrl must not regress to the upstream PR's unverified .ai domain"
- );
-});
diff --git a/tests/unit/moderations-handler.test.ts b/tests/unit/moderations-handler.test.ts
index 68ec32847a..06cff14788 100644
--- a/tests/unit/moderations-handler.test.ts
+++ b/tests/unit/moderations-handler.test.ts
@@ -2,9 +2,6 @@ import test from "node:test";
import assert from "node:assert/strict";
const { handleModeration } = await import("../../open-sse/handlers/moderations.ts");
-const { MODERATION_PROVIDERS, getModerationProvider, parseModerationModel } = await import(
- "../../open-sse/config/moderationRegistry.ts"
-);
const originalFetch = globalThis.fetch;
@@ -12,42 +9,6 @@ test.afterEach(() => {
globalThis.fetch = originalFetch;
});
-test("MODERATION_PROVIDERS registers mistral with the Mistral moderations base URL", () => {
- const provider = getModerationProvider("mistral");
- assert.ok(provider);
- assert.equal(provider.baseUrl, "https://api.mistral.ai/v1/moderations");
- assert.ok(provider.models.some((m: { id: string }) => m.id === "mistral-moderation-latest"));
- assert.ok(MODERATION_PROVIDERS.mistral);
-});
-
-test("parseModerationModel routes mistral moderation models to the mistral provider", () => {
- assert.deepEqual(parseModerationModel("mistral/mistral-moderation-latest"), {
- provider: "mistral",
- model: "mistral-moderation-latest",
- });
- assert.deepEqual(parseModerationModel("mistral-moderation-latest"), {
- provider: "mistral",
- model: "mistral-moderation-latest",
- });
-});
-
-test("handleModeration proxies mistral moderation requests to the mistral endpoint", async () => {
- let captured: any;
- globalThis.fetch = async (url: any, options: any = {}) => {
- captured = { url: String(url), headers: options.headers };
- return Response.json({ id: "modr-mistral", results: [{ flagged: false }] });
- };
-
- const response = await handleModeration({
- body: { model: "mistral/mistral-moderation-latest", input: "check this" },
- credentials: { apiKey: "sk-mistral" },
- });
-
- assert.equal(captured.url, "https://api.mistral.ai/v1/moderations");
- assert.equal(captured.headers.Authorization, "Bearer sk-mistral");
- assert.equal(response.status, 200);
-});
-
test("handleModeration requires input", async () => {
const response = await handleModeration({
body: { model: "openai/omni-moderation-latest" },
diff --git a/tests/unit/muse-spark-response-parser-split.test.ts b/tests/unit/muse-spark-response-parser-split.test.ts
deleted file mode 100644
index 719dcff33e..0000000000
--- a/tests/unit/muse-spark-response-parser-split.test.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import { test } from "node:test";
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { fileURLToPath } from "node:url";
-import { dirname, join } from "node:path";
-
-// Split-guard for the muse-spark-web Meta AI response-parser extraction.
-// The pure SSE/JSON parsing + content/reasoning/error extraction lives in
-// muse-spark-web/response-parser.ts (no host state/fetch/auth). Host imports it back.
-const HERE = dirname(fileURLToPath(import.meta.url));
-const EXE = join(HERE, "../../open-sse/executors");
-const HOST = join(EXE, "muse-spark-web.ts");
-const LEAF = join(EXE, "muse-spark-web/response-parser.ts");
-
-test("leaf hosts the parser and does not import the host", () => {
- const src = readFileSync(LEAF, "utf8");
- for (const sym of ["parseMetaAiResponseText", "parseMetaSseFrames", "isRecord"]) {
- assert.match(src, new RegExp(`export function ${sym}\\b`));
- }
- assert.doesNotMatch(src, /from "\.\.\/muse-spark-web\.ts"/);
-});
-
-test("host imports the parser back from the leaf", () => {
- const host = readFileSync(HOST, "utf8");
- assert.match(host, /from "\.\/muse-spark-web\/response-parser\.ts"/);
-});
-
-test("parseMetaAiResponseText tolerates empty input", async () => {
- const { parseMetaAiResponseText } =
- await import("../../open-sse/executors/muse-spark-web/response-parser.ts");
- const out = parseMetaAiResponseText("", false);
- assert.equal(typeof out, "object");
-});
diff --git a/tests/unit/next-config.test.ts b/tests/unit/next-config.test.ts
index b44e278b51..11ec9ed4bb 100644
--- a/tests/unit/next-config.test.ts
+++ b/tests/unit/next-config.test.ts
@@ -37,15 +37,6 @@ test("next config exposes standalone build settings and canonical rewrites", asy
"fumadocs-ui",
"fumadocs-core",
]);
- // #6062: `ws` and its native masking helpers must stay external so the
- // copilot-m365-web executor keeps a working WebSocket masking path at runtime
- // (bundling ws breaks `bufferutil` → `TypeError: b.mask is not a function`).
- for (const pkg of ["ws", "bufferutil", "utf-8-validate"]) {
- assert.ok(
- nextConfig.serverExternalPackages.includes(pkg),
- `expected serverExternalPackages to externalize "${pkg}" (#6062)`
- );
- }
assert.equal(headers[0].source, "/:path*");
assert.match(securityHeaders["Content-Security-Policy"], /default-src 'self'/);
assert.match(securityHeaders["Content-Security-Policy"], /frame-ancestors 'none'/);
diff --git a/tests/unit/nube-provider.test.ts b/tests/unit/nube-provider.test.ts
deleted file mode 100644
index 181eafbbf0..0000000000
--- a/tests/unit/nube-provider.test.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import test from "node:test";
-import assert from "node:assert/strict";
-
-const { APIKEY_PROVIDERS } = await import("../../src/shared/constants/providers.ts");
-const { REGISTRY: providerRegistry } = await import("../../open-sse/config/providerRegistry.ts");
-
-test("Nube.sh is registered as an API-key provider with the canonical identity", () => {
- const nube = APIKEY_PROVIDERS.nube;
- assert.ok(nube, "APIKEY_PROVIDERS.nube must be defined");
- assert.equal(nube.id, "nube");
- assert.equal(nube.alias, "nube");
- assert.equal(nube.name, "Nube.sh");
- assert.equal(nube.website, "https://nube.sh");
- assert.equal(typeof nube.textIcon, "string");
-});
-
-test("Nube.sh registry entry uses OpenAI format with bearer apikey auth", () => {
- const entry = providerRegistry.nube;
- assert.ok(entry, "providerRegistry.nube must be defined");
- assert.equal(entry.id, "nube");
- assert.equal(entry.format, "openai");
- assert.equal(entry.executor, "default");
- assert.equal(entry.authType, "apikey");
- assert.equal(entry.authHeader, "bearer");
- assert.equal(entry.baseUrl, "https://ai.nube.sh/api/v1/chat/completions");
-});
-
-test("Nube.sh ships no fabricated model IDs and relies on passthrough enumeration", () => {
- const entry = providerRegistry.nube;
- // The live catalog is only reachable with a valid key (401 unauthenticated), so we do
- // NOT hardcode unverifiable model IDs — models pass through and are enumerated live.
- assert.equal(entry.passthroughModels, true);
- assert.deepEqual(entry.models, []);
- assert.equal(entry.modelsUrl, "https://ai.nube.sh/api/v1/models");
-});
diff --git a/tests/unit/nvidia-nim-image.test.ts b/tests/unit/nvidia-nim-image.test.ts
deleted file mode 100644
index 2f07ae325e..0000000000
--- a/tests/unit/nvidia-nim-image.test.ts
+++ /dev/null
@@ -1,314 +0,0 @@
-import test from "node:test";
-import assert from "node:assert/strict";
-
-// Ported from upstream 9router#1195: NVIDIA NIM image generation (FLUX models).
-// NVIDIA already exists as a CHAT provider (integrate.api.nvidia.com,
-// OpenAI-compatible) — image generation is a distinct host (ai.api.nvidia.com)
-// with a native NIM body shape, so it gets its own `nvidia-nim` format/handler
-// (handleNvidiaNimImageGeneration) rather than reusing the OpenAI image path.
-
-import { handleImageGeneration } from "../../open-sse/handlers/imageGeneration.ts";
-import { getImageProvider } from "../../open-sse/config/imageRegistry.ts";
-import {
- buildNvidiaNimRequestBody,
- normalizeNvidiaNimImages,
-} from "../../open-sse/handlers/imageGeneration/providers/nvidiaNim.ts";
-
-test("nvidia is registered as an nvidia-nim image provider with the 4 FLUX models", () => {
- const cfg = getImageProvider("nvidia");
- assert.ok(cfg, "expected an IMAGE_PROVIDERS entry for nvidia");
- assert.equal(cfg.format, "nvidia-nim");
- assert.equal(cfg.baseUrl, "https://ai.api.nvidia.com/v1/genai");
- assert.equal(cfg.authType, "apikey");
- assert.equal(cfg.authHeader, "bearer");
-
- const ids = cfg.models.map((m) => m.id);
- assert.deepEqual(ids, [
- "black-forest-labs/flux.1-dev",
- "black-forest-labs/flux.1-schnell",
- "black-forest-labs/flux.1-kontext-dev",
- "black-forest-labs/flux.2-klein-4b",
- ]);
-});
-
-test("handleImageGeneration(nvidia/flux.1-schnell): URL construction + minimal body shaping", async () => {
- const originalFetch = globalThis.fetch;
- let capturedUrl;
- let capturedOptions;
-
- globalThis.fetch = async (url, options) => {
- capturedUrl = String(url);
- capturedOptions = options;
- return new Response(
- JSON.stringify({ artifacts: [{ base64: "base64nvidia", finishReason: "SUCCESS" }] }),
- { status: 200, headers: { "content-type": "application/json" } }
- );
- };
-
- try {
- const result = await handleImageGeneration({
- body: {
- model: "nvidia/black-forest-labs/flux.1-schnell",
- prompt: "A neon city",
- width: 1344,
- height: 1024,
- seed: 7,
- steps: 4,
- },
- credentials: { apiKey: "nv-token" },
- log: null,
- });
-
- assert.equal(result.success, true);
- assert.equal(capturedUrl, "https://ai.api.nvidia.com/v1/genai/black-forest-labs/flux.1-schnell");
- assert.equal(capturedOptions.method, "POST");
- assert.equal(capturedOptions.headers.Authorization, "Bearer nv-token");
- assert.equal(capturedOptions.headers.Accept, "application/json");
-
- const requestBody = JSON.parse(capturedOptions.body);
- assert.deepEqual(requestBody, {
- prompt: "A neon city",
- width: 1344,
- height: 1024,
- seed: 7,
- steps: 4,
- });
-
- assert.equal(result.data.data[0].b64_json, "base64nvidia");
- assert.equal(result.data.data[0].finish_reason, "SUCCESS");
- } finally {
- globalThis.fetch = originalFetch;
- }
-});
-
-test("handleImageGeneration(nvidia/flux.2-klein-4b): sends edit input image as an array", async () => {
- const originalFetch = globalThis.fetch;
-
- globalThis.fetch = async () =>
- new Response(JSON.stringify({ artifacts: [{ base64: "base64nvidiaedit" }] }), {
- status: 200,
- headers: { "content-type": "application/json" },
- });
-
- try {
- const result = await handleImageGeneration({
- body: {
- model: "nvidia/black-forest-labs/flux.2-klein-4b",
- prompt: "Make the frog wear tiny glasses",
- image: "data:image/png;example_id,0",
- width: 1024,
- height: 1024,
- seed: 0,
- steps: 4,
- },
- credentials: { apiKey: "nv-token" },
- log: null,
- });
-
- assert.equal(result.success, true);
- assert.equal(result.data.data[0].b64_json, "base64nvidiaedit");
- } finally {
- globalThis.fetch = originalFetch;
- }
-});
-
-test("buildNvidiaNimRequestBody(flux.2-klein-4b): image sent as an array, width/height passthrough", () => {
- const req = buildNvidiaNimRequestBody("black-forest-labs/flux.2-klein-4b", {
- prompt: "Make the frog wear tiny glasses",
- image: "data:image/png;example_id,0",
- width: 1024,
- height: 1024,
- seed: 0,
- steps: 4,
- });
- assert.deepEqual(req, {
- prompt: "Make the frog wear tiny glasses",
- width: 1024,
- height: 1024,
- image: ["data:image/png;example_id,0"],
- seed: 0,
- steps: 4,
- });
-});
-
-test("buildNvidiaNimRequestBody(flux.1-dev): omits input image in base mode", () => {
- const req = buildNvidiaNimRequestBody("black-forest-labs/flux.1-dev", {
- prompt: "A simple coffee shop interior",
- mode: "base",
- image: "data:image/png;example_id,0",
- cfg_scale: 1.1,
- width: 768,
- height: 1344,
- seed: 0,
- steps: 50,
- });
- assert.deepEqual(req, {
- prompt: "A simple coffee shop interior",
- mode: "base",
- width: 768,
- height: 1344,
- cfg_scale: 1.1,
- seed: 0,
- steps: 50,
- });
-});
-
-test("buildNvidiaNimRequestBody(flux.1-dev): drops out-of-range dimensions and non-positive cfg_scale", () => {
- const req = buildNvidiaNimRequestBody("black-forest-labs/flux.1-dev", {
- prompt: "A simple coffee shop interior",
- mode: "base",
- image: "data:image/png;example_id,0",
- cfg_scale: 0,
- width: 1792, // out of the 768-1344 range
- height: 1024,
- seed: 0,
- steps: 50,
- });
- assert.deepEqual(req, {
- prompt: "A simple coffee shop interior",
- mode: "base",
- seed: 0,
- steps: 50,
- });
- assert.ok(!("width" in req) && !("height" in req) && !("cfg_scale" in req));
-});
-
-test("buildNvidiaNimRequestBody(flux.1-dev): sends control image as a string for non-base modes", () => {
- const req = buildNvidiaNimRequestBody("black-forest-labs/flux.1-dev", {
- prompt: "A simple coffee shop interior",
- mode: "depth",
- image: "data:image/png;example_id,0",
- cfg_scale: 3.5,
- width: 1024,
- height: 1024,
- seed: 0,
- steps: 50,
- });
- assert.deepEqual(req, {
- prompt: "A simple coffee shop interior",
- width: 1024,
- height: 1024,
- mode: "depth",
- image: "data:image/png;example_id,0",
- cfg_scale: 3.5,
- seed: 0,
- steps: 50,
- });
-});
-
-test("buildNvidiaNimRequestBody(flux.1-kontext-dev): uses aspect_ratio instead of width/height", () => {
- const req = buildNvidiaNimRequestBody("black-forest-labs/flux.1-kontext-dev", {
- prompt: "Now the mouse is holding pizza instead",
- image: "data:image/png;example_id,0",
- aspect_ratio: "match_input_image",
- width: 1024,
- height: 1024,
- steps: 30,
- cfg_scale: 3.5,
- seed: 0,
- });
- assert.deepEqual(req, {
- prompt: "Now the mouse is holding pizza instead",
- image: "data:image/png;example_id,0",
- aspect_ratio: "match_input_image",
- cfg_scale: 3.5,
- seed: 0,
- steps: 30,
- });
-});
-
-test("handleImageGeneration(nvidia/flux.1-kontext-dev): requires an input image, does not fetch", async () => {
- const originalFetch = globalThis.fetch;
- let fetchCalled = false;
- globalThis.fetch = async () => {
- fetchCalled = true;
- throw new Error("fetch should not be called without an input image");
- };
-
- try {
- const result = await handleImageGeneration({
- body: {
- model: "nvidia/black-forest-labs/flux.1-kontext-dev",
- prompt: "Now the mouse is holding pizza instead",
- },
- credentials: { apiKey: "nv-token" },
- log: null,
- });
-
- assert.equal(result.success, false);
- assert.equal(result.status, 400);
- assert.match(result.error, /requires an input image/i);
- assert.equal(fetchCalled, false);
- } finally {
- globalThis.fetch = originalFetch;
- }
-});
-
-test("normalizeNvidiaNimImages: accepts artifacts[], images[], data[], and single-value shapes", () => {
- assert.deepEqual(normalizeNvidiaNimImages({ artifacts: [{ base64: "a1" }] }).data, [
- { b64_json: "a1" },
- ]);
- assert.deepEqual(normalizeNvidiaNimImages({ images: ["b1", "b2"] }).data, [
- { b64_json: "b1" },
- { b64_json: "b2" },
- ]);
- assert.deepEqual(normalizeNvidiaNimImages({ data: [{ b64_json: "c1" }] }).data, [
- { b64_json: "c1" },
- ]);
- assert.deepEqual(normalizeNvidiaNimImages({ image: "d1" }).data, [{ b64_json: "d1" }]);
- assert.deepEqual(normalizeNvidiaNimImages({ result: { image: "e1" } }).data, [
- { b64_json: "e1" },
- ]);
- // Already-OpenAI-shaped responses pass through untouched.
- const passthrough = { created: 123, data: [{ b64_json: "f1" }] };
- assert.deepEqual(normalizeNvidiaNimImages(passthrough), passthrough);
- // Unrecognized shape -> empty data, never throws.
- assert.deepEqual(normalizeNvidiaNimImages({ nonsense: true }).data, []);
-});
-
-test("handleImageGeneration(nvidia): upstream error body never leaks a stack trace", async () => {
- const originalFetch = globalThis.fetch;
- globalThis.fetch = async () => {
- throw new Error(`boom at /home/user/secret/path/imageGeneration.ts:123:45`);
- };
-
- try {
- const result = await handleImageGeneration({
- body: {
- model: "nvidia/black-forest-labs/flux.1-schnell",
- prompt: "test",
- },
- credentials: { apiKey: "nv-token" },
- log: null,
- });
-
- assert.equal(result.success, false);
- assert.equal(result.status, 502);
- assert.ok(!result.error.includes("/home/"), "error must not leak an absolute path/stack");
- assert.ok(!result.error.includes(":123:45"), "error must not leak a stack trace location");
- } finally {
- globalThis.fetch = originalFetch;
- }
-});
-
-test("handleImageGeneration(nvidia): upstream non-2xx response is surfaced with its status", async () => {
- const originalFetch = globalThis.fetch;
- globalThis.fetch = async () =>
- new Response("rate limited", { status: 429, headers: { "content-type": "text/plain" } });
-
- try {
- const result = await handleImageGeneration({
- body: {
- model: "nvidia/black-forest-labs/flux.1-schnell",
- prompt: "test",
- },
- credentials: { apiKey: "nv-token" },
- log: null,
- });
-
- assert.equal(result.success, false);
- assert.equal(result.status, 429);
- } finally {
- globalThis.fetch = originalFetch;
- }
-});
diff --git a/tests/unit/ocr-route.test.ts b/tests/unit/ocr-route.test.ts
deleted file mode 100644
index 5047311c38..0000000000
--- a/tests/unit/ocr-route.test.ts
+++ /dev/null
@@ -1,188 +0,0 @@
-import test from "node:test";
-import assert from "node:assert/strict";
-
-const { POST, OPTIONS } = await import("../../src/app/api/v1/ocr/route.ts");
-const { handleOcr } = await import("../../open-sse/handlers/ocr.ts");
-const { OCR_PROVIDERS, getOcrProvider, parseOcrModel, getAllOcrModels } =
- await import("../../open-sse/config/ocrRegistry.ts");
-const { v1OcrSchema } = await import("../../src/shared/validation/schemas/apiV1.ts");
-
-const originalFetch = globalThis.fetch;
-
-test.afterEach(() => {
- globalThis.fetch = originalFetch;
-});
-
-function ocrRequest(body: string) {
- return new Request("http://localhost/v1/ocr", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body,
- });
-}
-
-// ── Registry ───────────────────────────────────────────────────────────────
-
-test("OCR_PROVIDERS registers mistral with the Mistral OCR base URL", () => {
- assert.equal(OCR_PROVIDERS.mistral.baseUrl, "https://api.mistral.ai/v1/ocr");
- const provider = getOcrProvider("mistral");
- assert.ok(provider);
- assert.equal(provider.authHeader, "bearer");
- assert.ok(provider.models.some((m: { id: string }) => m.id === "mistral-ocr-latest"));
-});
-
-test("parseOcrModel routes bare and prefixed mistral models to the mistral provider", () => {
- assert.deepEqual(parseOcrModel("mistral-ocr-latest"), {
- provider: "mistral",
- model: "mistral-ocr-latest",
- });
- assert.deepEqual(parseOcrModel("mistral/mistral-ocr-latest"), {
- provider: "mistral",
- model: "mistral-ocr-latest",
- });
- // Unknown model → no provider resolved
- assert.deepEqual(parseOcrModel("mystery-model"), {
- provider: null,
- model: "mystery-model",
- });
-});
-
-test("getAllOcrModels exposes the mistral OCR model with a provider prefix", () => {
- const models = getAllOcrModels();
- assert.ok(models.some((m: { id: string }) => m.id === "mistral/mistral-ocr-latest"));
-});
-
-// ── Schema (Zod, Rule #7) ────────────────────────────────────────────────────
-
-test("v1OcrSchema rejects a body without a document", () => {
- const result = v1OcrSchema.safeParse({ model: "mistral-ocr-latest" });
- assert.equal(result.success, false);
-});
-
-test("v1OcrSchema accepts a document_url document object", () => {
- const result = v1OcrSchema.safeParse({
- model: "mistral-ocr-latest",
- document: { type: "document_url", document_url: "https://example.com/a.pdf" },
- });
- assert.equal(result.success, true);
-});
-
-test("v1OcrSchema accepts an image_url document object", () => {
- const result = v1OcrSchema.safeParse({
- document: { type: "image_url", image_url: "https://example.com/a.png" },
- });
- assert.equal(result.success, true);
-});
-
-// ── Route (public /v1/ocr entry point) ───────────────────────────────────────
-
-test("POST /v1/ocr returns 400 for invalid JSON without leaking a stack trace", async () => {
- const response = await POST(ocrRequest("not json at all"));
- const body = (await response.json()) as any;
-
- assert.equal(response.status, 400);
- assert.equal(body.error.message, "Invalid JSON body");
- // Rule #12 — error responses must never leak stack traces.
- assert.ok(!body.error.message.includes("at /"));
-});
-
-test("OPTIONS /v1/ocr answers the CORS preflight", async () => {
- const response = await OPTIONS();
- assert.equal(response.status, 200);
- assert.match(response.headers.get("access-control-allow-methods") || "", /OPTIONS/);
-});
-
-// ── Handler ──────────────────────────────────────────────────────────────────
-
-test("handleOcr requires a document", async () => {
- const response = await handleOcr({
- body: { model: "mistral-ocr-latest" },
- credentials: { apiKey: "sk-test" },
- });
- const payload = (await response.json()) as any;
-
- assert.equal(response.status, 400);
- assert.equal(payload.error.message, "document is required");
-});
-
-test("handleOcr rejects unknown OCR models", async () => {
- const response = await handleOcr({
- body: { model: "mystery/ocr", document: { document_url: "x" } },
- credentials: { apiKey: "sk-test" },
- });
- const payload = (await response.json()) as any;
-
- assert.equal(response.status, 400);
- assert.match(payload.error.message, /No OCR provider found/);
-});
-
-test("handleOcr requires credentials for the resolved provider", async () => {
- const response = await handleOcr({
- body: { document: { document_url: "x" } },
- credentials: null,
- });
- const payload = (await response.json()) as any;
-
- assert.equal(response.status, 401);
- assert.equal(payload.error.message, "No credentials for OCR provider: mistral");
-});
-
-test("handleOcr proxies a successful request to the mistral OCR endpoint", async () => {
- let captured: any;
- globalThis.fetch = async (url: any, options: any = {}) => {
- captured = {
- url: String(url),
- headers: options.headers,
- body: JSON.parse(String(options.body || "{}")),
- };
- return Response.json({ pages: [{ index: 0, markdown: "hello" }] });
- };
-
- const response = await handleOcr({
- body: { document: { type: "document_url", document_url: "https://example.com/a.pdf" } },
- credentials: { apiKey: "sk-mistral" },
- });
-
- assert.equal(captured.url, "https://api.mistral.ai/v1/ocr");
- assert.equal(captured.headers.Authorization, "Bearer sk-mistral");
- // model defaults to mistral-ocr-latest and the document is forwarded upstream.
- assert.equal(captured.body.model, "mistral-ocr-latest");
- assert.deepEqual(captured.body.document, {
- type: "document_url",
- document_url: "https://example.com/a.pdf",
- });
- assert.equal(response.status, 200);
- assert.deepEqual(await response.json(), { pages: [{ index: 0, markdown: "hello" }] });
-});
-
-test("handleOcr passes upstream error payloads through with the upstream status", async () => {
- globalThis.fetch = async () =>
- new Response('{"error":"bad request"}', {
- status: 422,
- headers: { "content-type": "application/json" },
- });
-
- const response = await handleOcr({
- body: { model: "mistral/mistral-ocr-latest", document: { document_url: "x" } },
- credentials: { apiKey: "sk-test" },
- });
-
- assert.equal(response.status, 422);
- assert.equal(await response.text(), '{"error":"bad request"}');
-});
-
-test("handleOcr returns a sanitized 500 when the upstream request throws", async () => {
- globalThis.fetch = async () => {
- throw new Error("socket closed");
- };
-
- const response = await handleOcr({
- body: { model: "mistral-ocr-latest", document: { document_url: "x" } },
- credentials: { apiKey: "sk-test" },
- });
- const payload = (await response.json()) as any;
-
- assert.equal(response.status, 500);
- assert.match(payload.error.message, /OCR request failed: socket closed/);
- assert.ok(!payload.error.message.includes("at /"));
-});
diff --git a/tests/unit/openai-responses-request-split.test.ts b/tests/unit/openai-responses-request-split.test.ts
deleted file mode 100644
index 50699805a6..0000000000
--- a/tests/unit/openai-responses-request-split.test.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import { test } from "node:test";
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { fileURLToPath } from "node:url";
-import { dirname, join } from "node:path";
-
-// Split-guard for the openai-responses request-translator extraction.
-// Pure shared primitives live in `openai-responses/helpers.ts`; the chat->Responses
-// direction (`openaiToOpenAIResponsesRequest`) lives in `openai-responses/toResponses.ts`.
-// The host keeps `openaiResponsesToOpenAIRequest` + both register() calls and re-exports
-// the moved function so external importers (tests) keep working unchanged.
-const HERE = dirname(fileURLToPath(import.meta.url));
-const REQ = join(HERE, "../../open-sse/translator/request");
-const HOST = join(REQ, "openai-responses.ts");
-const HELPERS = join(REQ, "openai-responses/helpers.ts");
-const TO_RESPONSES = join(REQ, "openai-responses/toResponses.ts");
-
-test("helpers leaf is pure (no host import) and exports the shared primitives", () => {
- const src = readFileSync(HELPERS, "utf8");
- assert.doesNotMatch(src, /from "\.\.\/openai-responses\.ts"/);
- for (const sym of ["toRecord", "toString", "clampCallId", "normalizeVerbosity"]) {
- assert.match(src, new RegExp(`export (function|const) ${sym}\\b`));
- }
-});
-
-test("toResponses leaf hosts the chat->Responses direction and imports helpers, not the host", () => {
- const src = readFileSync(TO_RESPONSES, "utf8");
- assert.match(src, /export function openaiToOpenAIResponsesRequest\(/);
- assert.match(src, /from "\.\/helpers\.ts"/);
- assert.doesNotMatch(src, /from "\.\.\/openai-responses\.ts"/);
-});
-
-test("host re-exports the moved function and keeps both register() directions", () => {
- const src = readFileSync(HOST, "utf8");
- assert.match(
- src,
- /export \{ openaiToOpenAIResponsesRequest \} from "\.\/openai-responses\/toResponses\.ts"/
- );
- assert.match(src, /export function openaiResponsesToOpenAIRequest\(/);
- assert.match(src, /register\(FORMATS\.OPENAI_RESPONSES, FORMATS\.OPENAI,/);
- assert.match(src, /register\(FORMATS\.OPENAI, FORMATS\.OPENAI_RESPONSES,/);
-});
-
-test("both directions are callable via the host module", async () => {
- const mod = await import("../../open-sse/translator/request/openai-responses.ts");
- assert.equal(typeof mod.openaiResponsesToOpenAIRequest, "function");
- assert.equal(typeof mod.openaiToOpenAIResponsesRequest, "function");
- // chat->Responses basic shape: wraps into { input: [...], stream: true }.
- const out = mod.openaiToOpenAIResponsesRequest(
- "gpt-4",
- { messages: [{ role: "user", content: "hi" }] },
- true,
- null
- ) as Record<string, unknown>;
- assert.ok(Array.isArray(out.input));
-});
diff --git a/tests/unit/openai-to-claude-redacted-replay-5312.test.ts b/tests/unit/openai-to-claude-redacted-replay-5312.test.ts
index 42c434898e..43764ae00c 100644
--- a/tests/unit/openai-to-claude-redacted-replay-5312.test.ts
+++ b/tests/unit/openai-to-claude-redacted-replay-5312.test.ts
@@ -1,37 +1,14 @@
/**
- * TDD regression for #5312 (FIX D / RC-D) and #5945.
+ * TDD regression for #5312 (FIX D / RC-D): openai-to-claude reconstructed a Claude
+ * `thinking` block from signature-less `reasoning_content` and stamped it with the
+ * fabricated DEFAULT_THINKING_CLAUDE_SIGNATURE. Anthropic validates signatures and
+ * rejects the fake one with 400 "Invalid signature in thinking block" — and
+ * claudeHelper's latest-assistant guard preserves the block verbatim, so the fake
+ * signature leaks upstream.
*
- * #5312 (FIX D / RC-D): openai-to-claude reconstructed a Claude `thinking` block from
- * signature-less `reasoning_content` and stamped it with the fabricated
- * DEFAULT_THINKING_CLAUDE_SIGNATURE. Anthropic validates signatures and rejects the
- * fake one with 400 "Invalid signature in thinking block" — and claudeHelper's
- * latest-assistant guard preserves the block verbatim, so the fake signature leaks
- * upstream.
- *
- * Fix (#5312): when a precursor thinking block IS required by Anthropic's schema
- * (assistant turn has tool_use AND the outbound request has extended thinking
- * enabled), emit a signature-less `redacted_thinking` placeholder (matching what
- * prepareClaudeRequest produces downstream) instead of a fabricated-signature
- * `thinking` block. A REAL part.signature must always be preserved verbatim — never
- * overwritten with the default.
- *
- * #5945 (over-correction of #5312): the original #5312 fix injected the
- * redacted_thinking placeholder UNCONDITIONALLY whenever ANY assistant history
- * message carried non-empty `reasoning_content` — regardless of whether the current
- * outbound request has thinking enabled, and regardless of whether that assistant
- * turn even contains a `tool_use` block (the only case Anthropic's schema actually
- * requires a preceding thinking/redacted_thinking block). This fabricated a content
- * block the client never sent; reported by dev-cj: Claude Sonnet 5 via the "Pi"
- * harness detected the extra block and refused the turn as prompt injection.
- *
- * Fix (#5945): gate the injection on BOTH (a) the assistant turn containing a
- * tool_use block and (b) the outbound request having extended thinking enabled.
- * Otherwise `reasoning_content` is dropped silently — it carries no useful signal
- * for a plain-text replay turn, and the client never asked for it to appear.
- *
- * These two fixes are not in tension: #5312 legitimately fixed a real Anthropic 400
- * for the case the redacted_thinking block IS required; #5945 narrows the trigger to
- * exactly that case instead of firing for every reasoning_content-bearing message.
+ * Fix: emit a signature-less `redacted_thinking` placeholder (matching what
+ * prepareClaudeRequest produces downstream). A REAL part.signature must always be
+ * preserved verbatim — never overwritten with the default.
*/
import test from "node:test";
import assert from "node:assert/strict";
@@ -43,7 +20,7 @@ const { DEFAULT_THINKING_CLAUDE_SIGNATURE } = await import(
"../../open-sse/config/defaultThinkingSignature.ts"
);
-test("#5945: reasoning_content on a plain-text assistant turn (no tool_use, thinking not requested) yields NO redacted_thinking/thinking block", () => {
+test("#5312 RC-D: signature-less reasoning_content yields no fabricated-signature thinking block", () => {
const result = openaiToClaudeRequest(
"claude-opus-4-8",
{
@@ -51,7 +28,6 @@ test("#5945: reasoning_content on a plain-text assistant turn (no tool_use, thin
{ role: "user", content: "hello" },
{ role: "assistant", reasoning_content: "thinking about it", content: "hi there" },
],
- // no body.thinking / body.reasoning_effort — thinking is NOT enabled for this request.
},
false
);
@@ -59,101 +35,24 @@ test("#5945: reasoning_content on a plain-text assistant turn (no tool_use, thin
const assistant = result.messages.find((m) => m.role === "assistant");
assert.ok(assistant, "expected assistant message");
- // No fabricated block at all — reasoning_content must be dropped silently, exactly
- // like OPENAI_INCOMPATIBLE_ECHO_FIELDS drops other echo-only fields.
- assert.equal(
- assistant.content.find((b) => b && (b.type === "thinking" || b.type === "redacted_thinking")),
- undefined,
- "must NOT fabricate a thinking/redacted_thinking block the client never sent"
- );
- assert.deepEqual(
- assistant.content.map((b) => b.type),
- ["text"],
- "assistant content should contain only the real text block"
- );
-});
-
-test("#5945: reasoning_content + tool_use, but thinking NOT enabled on the outbound request, yields NO injection", () => {
- const result = openaiToClaudeRequest(
- "claude-opus-4-8",
- {
- messages: [
- { role: "user", content: "hello" },
- {
- role: "assistant",
- reasoning_content: "thinking about it",
- tool_calls: [
- {
- id: "call_1",
- type: "function",
- function: { name: "get_weather", arguments: "{}" },
- },
- ],
- },
- ],
- // no body.thinking / body.reasoning_effort — thinking is NOT enabled.
- },
- false
- );
-
- const assistant = result.messages.find((m) => m.role === "assistant");
- assert.ok(assistant, "expected assistant message");
- assert.equal(
- assistant.content.find((b) => b && (b.type === "thinking" || b.type === "redacted_thinking")),
- undefined,
- "must NOT inject a precursor thinking block when the request itself has thinking disabled"
- );
- assert.ok(
- assistant.content.some((b) => b.type === "tool_use"),
- "tool_use block must still be present"
- );
-});
-
-test("#5312: reasoning_content + tool_use + thinking ENABLED still gets a signature-less redacted_thinking precursor (the legitimate #5312 400-fix case)", () => {
- const result = openaiToClaudeRequest(
- "claude-opus-4-8",
- {
- thinking: { type: "enabled", budget_tokens: 4096 },
- messages: [
- { role: "user", content: "hello" },
- {
- role: "assistant",
- reasoning_content: "thinking about it",
- tool_calls: [
- {
- id: "call_1",
- type: "function",
- function: { name: "get_weather", arguments: "{}" },
- },
- ],
- },
- ],
- },
- false
- );
-
- const assistant = result.messages.find((m) => m.role === "assistant");
- assert.ok(assistant, "expected assistant message");
-
- // No block may carry the fabricated default signature on a `thinking`-typed block.
+ // No block may carry the fabricated default signature.
const fake = assistant.content.find(
- (b) => b && b.type === "thinking" && b.signature === DEFAULT_THINKING_CLAUDE_SIGNATURE
+ (b) => b && b.signature === DEFAULT_THINKING_CLAUDE_SIGNATURE
);
- assert.equal(fake, undefined, "must NOT emit a `thinking` block with the fabricated signature");
+ assert.equal(fake, undefined, "must NOT emit a thinking block with the fabricated signature");
- // It becomes a redacted_thinking placeholder (Anthropic accepts without sig check),
- // and it must precede the tool_use block.
- assert.equal(assistant.content[0].type, "redacted_thinking", "must be the precursor block");
- assert.equal(assistant.content[0].data, DEFAULT_THINKING_CLAUDE_SIGNATURE);
+ // No `thinking`-typed block at all from signature-less reasoning_content.
assert.equal(
- assistant.content[0].signature,
+ assistant.content.find((b) => b && b.type === "thinking"),
undefined,
- "redacted_thinking must not carry a signature"
- );
- assert.ok(
- assistant.content.some((b) => b.type === "tool_use"),
- "tool_use block must still be present"
+ "signature-less reasoning_content must not produce a `thinking` block"
);
+
+ // It becomes a redacted_thinking placeholder (Anthropic accepts without sig check).
+ const redacted = assistant.content.find((b) => b && b.type === "redacted_thinking");
+ assert.ok(redacted, "expected a redacted_thinking placeholder");
+ assert.equal(redacted.data, DEFAULT_THINKING_CLAUDE_SIGNATURE);
+ assert.equal(redacted.signature, undefined, "redacted_thinking must not carry a signature");
});
test("#5312 RC-D: a REAL thinking signature is preserved verbatim", () => {
diff --git a/tests/unit/openai-to-claude-thinking-budget-split.test.ts b/tests/unit/openai-to-claude-thinking-budget-split.test.ts
deleted file mode 100644
index aa3076cd19..0000000000
--- a/tests/unit/openai-to-claude-thinking-budget-split.test.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-import { test } from "node:test";
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { fileURLToPath } from "node:url";
-import { dirname, join } from "node:path";
-
-// Split-guard for the openai-to-claude thinking-budget extraction.
-// `fitThinkingToMaxTokens` (+ its private helpers safeCapMaxOutputTokens / MIN_*)
-// live in the pure leaf `openai-to-claude/thinkingBudget.ts`; the host re-exports
-// the public symbol so external importers (tests) keep working unchanged.
-const HERE = dirname(fileURLToPath(import.meta.url));
-const REQ = join(HERE, "../../open-sse/translator/request");
-const HOST = join(REQ, "openai-to-claude.ts");
-const LEAF = join(REQ, "openai-to-claude/thinkingBudget.ts");
-
-test("leaf hosts fitThinkingToMaxTokens and does not import the host", () => {
- const leaf = readFileSync(LEAF, "utf8");
- assert.match(leaf, /export function fitThinkingToMaxTokens\(/);
- assert.match(leaf, /function safeCapMaxOutputTokens\(/);
- assert.doesNotMatch(leaf, /from "\.\.\/openai-to-claude\.ts"/);
-});
-
-test("host re-exports fitThinkingToMaxTokens from the leaf", () => {
- const host = readFileSync(HOST, "utf8");
- assert.match(
- host,
- /export \{ fitThinkingToMaxTokens \} from "\.\/openai-to-claude\/thinkingBudget\.ts"/
- );
-});
-
-test("re-exported fitThinkingToMaxTokens is callable via the host module and behaves", async () => {
- const mod = await import("../../open-sse/translator/request/openai-to-claude.ts");
- assert.equal(typeof mod.fitThinkingToMaxTokens, "function");
- // No budgeted thinking → max_tokens floored to >= 1, thinking passed through.
- const out = mod.fitThinkingToMaxTokens("gpt-4o-mini", 0, undefined);
- assert.equal(out.thinking, undefined);
- assert.ok(out.maxTokens >= 1);
-});
diff --git a/tests/unit/openai-to-kiro-helpers-split.test.ts b/tests/unit/openai-to-kiro-helpers-split.test.ts
deleted file mode 100644
index d4e5eec648..0000000000
--- a/tests/unit/openai-to-kiro-helpers-split.test.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import { test } from "node:test";
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { fileURLToPath } from "node:url";
-import { dirname, join } from "node:path";
-
-// Split-guard for the openai-to-kiro message-helper extraction.
-// The pure tool/message helpers (parseToolInput / normalizeKiroToolSchema /
-// serializeToolResultContent) live in the leaf `openai-to-kiro/messageHelpers.ts`;
-// the host imports them back for convertMessages. They were module-private, so the
-// public export set is unchanged (no re-export needed).
-const HERE = dirname(fileURLToPath(import.meta.url));
-const REQ = join(HERE, "../../open-sse/translator/request");
-const HOST = join(REQ, "openai-to-kiro.ts");
-const LEAF = join(REQ, "openai-to-kiro/messageHelpers.ts");
-
-test("leaf hosts the pure helpers and does not import the host", () => {
- const src = readFileSync(LEAF, "utf8");
- for (const sym of ["parseToolInput", "normalizeKiroToolSchema", "serializeToolResultContent"]) {
- assert.match(src, new RegExp(`export function ${sym}\\b`));
- }
- assert.doesNotMatch(src, /from "\.\.\/openai-to-kiro\.ts"/);
-});
-
-test("host imports the helpers back from the leaf", () => {
- const src = readFileSync(HOST, "utf8");
- assert.match(src, /from "\.\/openai-to-kiro\/messageHelpers\.ts"/);
- // buildKiroPayload stays exported on the host module.
- assert.match(src, /export function buildKiroPayload\(/);
-});
-
-test("normalizeKiroToolSchema strips empty required arrays and additionalProperties", async () => {
- const { normalizeKiroToolSchema } =
- await import("../../open-sse/translator/request/openai-to-kiro/messageHelpers.ts");
- const out = normalizeKiroToolSchema({
- type: "object",
- required: [],
- additionalProperties: false,
- properties: { a: { type: "string" } },
- });
- assert.equal("required" in out, false);
- assert.equal("additionalProperties" in out, false);
- assert.deepEqual(out.properties, { a: { type: "string" } });
-});
diff --git a/tests/unit/perplexity-web-executor-split.test.ts b/tests/unit/perplexity-web-executor-split.test.ts
deleted file mode 100644
index 9348704a63..0000000000
--- a/tests/unit/perplexity-web-executor-split.test.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import { test } from "node:test";
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { fileURLToPath } from "node:url";
-import { dirname, join } from "node:path";
-
-// Split-guard for the perplexity-web executor protocol extraction.
-// The pure wire protocol (consts, types, SSE parsing, request/query building, content
-// extraction) lives in perplexity-web/protocol.ts (no host state/fetch/auth). Host imports
-// back the symbols it uses; everything is module-private (no re-export).
-const HERE = dirname(fileURLToPath(import.meta.url));
-const EXE = join(HERE, "../../open-sse/executors");
-const HOST = join(EXE, "perplexity-web.ts");
-const LEAF = join(EXE, "perplexity-web/protocol.ts");
-
-test("leaf hosts the protocol helpers and does not import the host", () => {
- const src = readFileSync(LEAF, "utf8");
- for (const sym of ["cleanResponse", "buildPplxRequestBody", "extractContent", "sseChunk"]) {
- assert.match(src, new RegExp(`export (async function\\*?|function\\*?|const) ${sym}\\b`));
- }
- assert.doesNotMatch(src, /from "\.\.\/perplexity-web\.ts"/);
-});
-
-test("host imports the protocol helpers back from the leaf", () => {
- const host = readFileSync(HOST, "utf8");
- assert.match(host, /from "\.\/perplexity-web\/protocol\.ts"/);
-});
-
-test("cleanResponse strips citations and sseChunk formats a chunk", async () => {
- const { cleanResponse, sseChunk } =
- await import("../../open-sse/executors/perplexity-web/protocol.ts");
- assert.equal(typeof cleanResponse("hello", true), "string");
- assert.match(sseChunk({ a: 1 }), /^data: \{"a":1\}\n\n$/);
-});
diff --git a/tests/unit/perplexity-web-streaming-tools-5927.test.ts b/tests/unit/perplexity-web-streaming-tools-5927.test.ts
deleted file mode 100644
index 8e867e6262..0000000000
--- a/tests/unit/perplexity-web-streaming-tools-5927.test.ts
+++ /dev/null
@@ -1,167 +0,0 @@
-// Tool-call emulation for the Perplexity Web executor in STREAMING mode (#5927).
-//
-// perplexity-web.ts converts <tool>{...}</tool> text into real OpenAI tool_calls
-// only for non-streaming requests (the `hasTools && !stream` gate). Streaming
-// requests — the default for agentic coding clients — got the raw <tool> text
-// as plain delta.content and never emitted a tool_calls SSE delta, so clients
-// could not execute tools. These tests live in a dedicated file mirroring
-// tests/unit/chatgpt-web-tools-5240.test.ts (the reference fix for chatgpt-web).
-
-import test from "node:test";
-import assert from "node:assert/strict";
-
-const { PerplexityWebExecutor } = await import("../../open-sse/executors/perplexity-web.ts");
-const { __setTlsFetchOverrideForTesting } = await import(
- "../../open-sse/services/perplexityTlsClient.ts"
-);
-
-// ─── Helper: Build a mock SSE stream from Perplexity events ─────────────────
-
-function mockPplxStream(events: unknown[]) {
- const encoder = new TextEncoder();
- const chunks: string[] = [];
- for (const evt of events) {
- chunks.push(`event: message\r\ndata: ${JSON.stringify(evt)}\r\n\r\n`);
- }
- chunks.push("event: end_of_stream\r\n\r\n");
- const body = chunks.join("");
- return new ReadableStream({
- start(controller) {
- controller.enqueue(encoder.encode(body));
- controller.close();
- },
- });
-}
-
-function installMockFetch(streamEvents: unknown[]) {
- __setTlsFetchOverrideForTesting(async () => {
- return {
- status: 200,
- headers: new Headers({ "Content-Type": "text/event-stream" }),
- text: null,
- body: mockPplxStream(streamEvents),
- };
- });
- return () => __setTlsFetchOverrideForTesting(null);
-}
-
-const WEATHER_TOOL = {
- type: "function",
- function: {
- name: "write_file",
- description: "Write a file to disk",
- parameters: {
- type: "object",
- properties: { path: { type: "string" }, content: { type: "string" } },
- required: ["path", "content"],
- },
- },
-};
-
-const TOOL_CALL_TEXT =
- '<tool>{"name":"write_file","arguments":{"path":"a.ts","content":"x"}}</tool>';
-
-function toolEvents(text: string) {
- return [
- {
- backend_uuid: "tool-uuid-1",
- blocks: [
- {
- intended_usage: "markdown",
- markdown_block: { chunks: [text], progress: "DONE" },
- },
- ],
- status: "COMPLETED",
- },
- ];
-}
-
-test("Tools stream: <tool> text becomes delta.tool_calls + finish_reason tool_calls, NOT raw <tool> content (#5927)", async () => {
- const restore = installMockFetch(toolEvents(TOOL_CALL_TEXT));
- try {
- const executor = new PerplexityWebExecutor();
- const result = await executor.execute({
- model: "pplx-auto",
- body: {
- messages: [{ role: "user", content: "write a file" }],
- tools: [WEATHER_TOOL],
- stream: true,
- },
- stream: true,
- credentials: { apiKey: "test-cookie" },
- signal: AbortSignal.timeout(10000),
- log: null,
- } as any);
-
- assert.equal(result.response.status, 200);
- assert.equal(result.response.headers.get("Content-Type"), "text/event-stream");
-
- const text = await result.response.text();
- const chunks = text
- .split("\n")
- .filter((l) => l.startsWith("data: ") && !l.includes("[DONE]"))
- .map((l) => JSON.parse(l.slice(6)));
-
- // Must NOT leak raw <tool> text as plain content.
- assert.ok(
- chunks.every((c) => {
- const content = c.choices?.[0]?.delta?.content;
- return typeof content !== "string" || !content.includes("<tool>");
- }),
- "no chunk contains raw <tool> text in delta.content"
- );
-
- const toolChunk = chunks.find((c) => c.choices[0].delta && c.choices[0].delta.tool_calls);
- assert.ok(toolChunk, "a chunk carries delta.tool_calls");
- assert.equal(toolChunk.choices[0].finish_reason, "tool_calls");
- const tc = toolChunk.choices[0].delta.tool_calls;
- assert.ok(Array.isArray(tc) && tc.length === 1);
- assert.equal(tc[0].type, "function");
- assert.equal(tc[0].function.name, "write_file");
- assert.equal(typeof tc[0].function.arguments, "string", "arguments is a JSON string");
- assert.deepEqual(JSON.parse(tc[0].function.arguments), { path: "a.ts", content: "x" });
-
- const lastLine = text.trim().split("\n").filter(Boolean).pop();
- assert.equal(lastLine, "data: [DONE]");
- } finally {
- restore();
- }
-});
-
-test("Tools regression: streaming request with NO tools still streams plain content unchanged (#5927)", async () => {
- const restore = installMockFetch(toolEvents("Just plain text, no tools."));
- try {
- const executor = new PerplexityWebExecutor();
- const result = await executor.execute({
- model: "pplx-auto",
- body: { messages: [{ role: "user", content: "hi" }], stream: true },
- stream: true,
- credentials: { apiKey: "test-cookie" },
- signal: AbortSignal.timeout(10000),
- log: null,
- } as any);
-
- assert.equal(result.response.status, 200);
- const text = await result.response.text();
- const chunks = text
- .split("\n")
- .filter((l) => l.startsWith("data: ") && !l.includes("[DONE]"))
- .map((l) => JSON.parse(l.slice(6)));
-
- let assembled = "";
- for (const c of chunks) {
- const content = c.choices?.[0]?.delta?.content;
- if (content) assembled += content;
- }
- assert.equal(assembled, "Just plain text, no tools.");
-
- assert.ok(
- chunks.every((c) => !(c.choices[0].delta && c.choices[0].delta.tool_calls)),
- "no tool_calls emitted without a tools array"
- );
- const finishChunk = chunks.find((c) => c.choices[0].finish_reason);
- assert.equal(finishChunk.choices[0].finish_reason, "stop");
- } finally {
- restore();
- }
-});
diff --git a/tests/unit/provider-alias-transitive-5918.test.ts b/tests/unit/provider-alias-transitive-5918.test.ts
deleted file mode 100644
index ae8df4cf88..0000000000
--- a/tests/unit/provider-alias-transitive-5918.test.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-/**
- * Regression tests for #5918: resolveProviderAlias must follow the alias chain
- * transitively.
- *
- * Root cause: resolveProviderAlias() did a single-hop lookup
- * (`ALIAS_TO_PROVIDER_ID[alias] || alias`). The registry has genuine two-hop chains:
- * the parent OpenCode provider registers `id: "opencode", alias: "oc"` (so
- * `oc -> opencode`), and a manual override maps `opencode -> opencode-zen` (the
- * main free tier). With single-hop, `resolveProviderAlias("oc")` returned the
- * intermediate `"opencode"` instead of the final `"opencode-zen"`, so `oc/<model>`
- * resolved to the wrong provider.
- *
- * Fix: resolve transitively with a depth limit AND a seen-set so cycles cannot loop.
- * These assertions FAIL on the old single-hop implementation and pass on the fix.
- */
-import test from "node:test";
-import assert from "node:assert/strict";
-
-import { resolveProviderAlias } from "../../open-sse/services/model.ts";
-
-test("resolveProviderAlias follows the oc -> opencode -> opencode-zen chain transitively", () => {
- // The bug: single-hop returned "opencode" (intermediate) instead of "opencode-zen".
- assert.equal(resolveProviderAlias("oc"), "opencode-zen");
-});
-
-test("resolveProviderAlias resolves a direct one-hop alias", () => {
- assert.equal(resolveProviderAlias("opencode"), "opencode-zen");
-});
-
-test("resolveProviderAlias returns a terminal id unchanged (id === alias)", () => {
- // opencode-zen registers id === alias === "opencode-zen"; must not loop or drift.
- assert.equal(resolveProviderAlias("opencode-zen"), "opencode-zen");
-});
-
-test("resolveProviderAlias falls back to identity for an unknown provider/id", () => {
- assert.equal(resolveProviderAlias("gpt-4"), "gpt-4");
- assert.equal(resolveProviderAlias("some-unregistered-provider"), "some-unregistered-provider");
-});
-
-test("resolveProviderAlias returns null for non-string input", () => {
- assert.equal(resolveProviderAlias(null), null);
- assert.equal(resolveProviderAlias(undefined), null);
- // @ts-expect-error — exercising the runtime guard against non-string input
- assert.equal(resolveProviderAlias(123), null);
-});
diff --git a/tests/unit/provider-models-route.test.ts b/tests/unit/provider-models-route.test.ts
index f83c81e5a3..0dd23c0f6e 100644
--- a/tests/unit/provider-models-route.test.ts
+++ b/tests/unit/provider-models-route.test.ts
@@ -320,130 +320,6 @@ test("provider models route discovers SiliconFlow models from configured China b
]);
});
-test("provider models route handles local hostnames named 'v1' correctly", async () => {
- const connection = await seedConnection("openai-compatible-local-v1", {
- apiKey: "sk-local",
- providerSpecificData: {
- baseUrl: "http://v1/chat/completions",
- },
- });
- const seenUrls: string[] = [];
-
- globalThis.fetch = async (url) => {
- seenUrls.push(String(url));
- return Response.json({
- data: [{ id: "local-v1-model", name: "Local v1 Model" }],
- });
- };
-
- const response = await callRoute(connection.id);
- const body = (await response.json()) as any;
-
- assert.equal(response.status, 200);
- assert.equal(body.source, "api");
- assert.deepEqual(seenUrls, ["http://v1/v1/models"]);
-});
-
-test("provider models route correctly strips standard /v1 paths", async () => {
- const connection = await seedConnection("openai-compatible-standard-v1", {
- apiKey: "sk-standard",
- providerSpecificData: {
- baseUrl: "https://api.openai.com/v1",
- },
- });
- const seenUrls: string[] = [];
-
- globalThis.fetch = async (url) => {
- seenUrls.push(String(url));
- return Response.json({
- data: [{ id: "standard-model", name: "Standard Model" }],
- });
- };
-
- const response = await callRoute(connection.id);
- const body = (await response.json()) as any;
-
- assert.equal(response.status, 200);
- assert.equal(body.source, "api");
- assert.deepEqual(seenUrls, ["https://api.openai.com/v1/models"]);
-});
-
-test("provider models route strips /v1 when it precedes /chat/completions (#5899 no double /v1)", async () => {
- // Regression for #5899 (Api Airforce): a baseUrl of the form
- // "https://api.airforce/v1/chat/completions" must probe ".../v1/models" — NOT
- // ".../v1/v1/models". The old `else if` strip chain only removed
- // "/chat/completions", leaving a trailing "/v1" that the endpoint builder then
- // doubled, producing a 308 redirect that aborted discovery.
- const connection = await seedConnection("openai-compatible-airforce-v1", {
- apiKey: "sk-airforce",
- providerSpecificData: {
- baseUrl: "https://api.airforce/v1/chat/completions",
- },
- });
- const seenUrls: string[] = [];
-
- globalThis.fetch = async (url) => {
- seenUrls.push(String(url));
- return Response.json({
- data: [{ id: "airforce-model", name: "Airforce Model" }],
- });
- };
-
- const response = await callRoute(connection.id);
- const body = (await response.json()) as any;
-
- assert.equal(response.status, 200);
- assert.equal(body.source, "api");
- // First probed endpoint must have a single /v1 — no ".../v1/v1/models".
- assert.equal(seenUrls[0], "https://api.airforce/v1/models");
- assert.ok(
- !seenUrls.some((u) => u.includes("/v1/v1/")),
- `no endpoint should contain a doubled /v1: ${JSON.stringify(seenUrls)}`
- );
-});
-
-test("provider models route continues probing past a REDIRECT_BLOCKED endpoint (#5899)", async () => {
- // Regression for #5899: a REDIRECT_BLOCKED error on one candidate endpoint must
- // not abort the whole probe loop — discovery should fall through to the next
- // endpoint instead of surfacing an empty catalog.
- const connection = await seedConnection("openai-compatible-redirect-v1", {
- apiKey: "sk-redirect",
- providerSpecificData: {
- baseUrl: "https://redirect.example",
- },
- });
- const seenUrls: string[] = [];
-
- globalThis.fetch = async (url) => {
- const u = String(url);
- seenUrls.push(u);
- // First candidate ".../v1/models" answers with a real 308 redirect →
- // safeOutboundFetch throws a SafeOutboundFetchError(REDIRECT_BLOCKED). The old
- // code re-threw on it (status 503) and aborted the loop; the fix `continue`s.
- if (u === "https://redirect.example/v1/models") {
- return new Response(null, {
- status: 308,
- headers: { location: "https://redirect.example/models" },
- });
- }
- return Response.json({
- data: [{ id: "redirect-model", name: "Redirect Model" }],
- });
- };
-
- const response = await callRoute(connection.id);
- const body = (await response.json()) as any;
-
- assert.equal(response.status, 200);
- // Without the REDIRECT_BLOCKED `continue`, discovery aborted and fell back to a
- // non-api catalog. The fix lets it reach the next endpoint and return live models.
- assert.equal(body.source, "api");
- assert.ok(
- seenUrls.length >= 2,
- `expected the loop to continue past REDIRECT_BLOCKED: ${JSON.stringify(seenUrls)}`
- );
-});
-
test("provider models route returns static catalog entries for providers with hardcoded models", async () => {
const connection = await seedConnection("bailian-coding-plan", {
apiKey: "bailian-key",
diff --git a/tests/unit/provider-node-icon-url.test.ts b/tests/unit/provider-node-icon-url.test.ts
deleted file mode 100644
index 541781708d..0000000000
--- a/tests/unit/provider-node-icon-url.test.ts
+++ /dev/null
@@ -1,280 +0,0 @@
-// #2166 — custom remote icon URL for OpenAI-/Anthropic-compatible provider nodes.
-// Mirrors the structure of tests/unit/custom-headers-provider-nodes.test.ts.
-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-icon-url-"));
-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 providerNodesRoute = await import("../../src/app/api/provider-nodes/route.ts");
-const providerNodesIdRoute = await import("../../src/app/api/provider-nodes/[id]/route.ts");
-const { OPENAI_COMPATIBLE_PREFIX } = await import("../../src/shared/constants/providers.ts");
-const { createProviderNodeSchema, updateProviderNodeSchema } =
- await import("../../src/shared/validation/schemas.ts");
-
-async function resetStorage() {
- core.resetDbInstance();
- fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
- fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
-}
-
-function makeRequest(body: Record<string, unknown>) {
- return new Request("http://localhost/api/provider-nodes", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify(body),
- });
-}
-
-function makeUpdateRequest(id: string, body: Record<string, unknown>) {
- return new Request(`http://localhost/api/provider-nodes/${id}`, {
- method: "PUT",
- headers: { "content-type": "application/json" },
- body: JSON.stringify(body),
- });
-}
-
-test.beforeEach(async () => {
- await resetStorage();
-});
-
-test.after(async () => {
- await resetStorage();
- fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
-});
-
-test("createProviderNodeSchema accepts a valid iconUrl", () => {
- const result = createProviderNodeSchema.safeParse({
- name: "Test",
- prefix: "test",
- apiType: "chat",
- iconUrl: "https://example.com/logo.png",
- });
- assert.equal(result.success, true);
-});
-
-test("createProviderNodeSchema accepts an empty iconUrl (no custom icon)", () => {
- const result = createProviderNodeSchema.safeParse({
- name: "Test",
- prefix: "test",
- apiType: "chat",
- iconUrl: "",
- });
- assert.equal(result.success, true);
-});
-
-test("createProviderNodeSchema accepts a missing iconUrl", () => {
- const result = createProviderNodeSchema.safeParse({
- name: "Test",
- prefix: "test",
- apiType: "chat",
- });
- assert.equal(result.success, true);
-});
-
-test("createProviderNodeSchema rejects a non-URL or non-http(s) iconUrl", () => {
- // " " is intentionally NOT in this list — it trims to "" (no custom icon),
- // matching the chatPath/modelsPath convention for optional path-like fields.
- const invalidInputs = ["not-a-url", "javascript:alert(1)", "data:text/html,evil", "ftp://broken"];
- for (const iconUrl of invalidInputs) {
- const result = createProviderNodeSchema.safeParse({
- name: "Test",
- prefix: "test",
- apiType: "chat",
- iconUrl,
- });
- assert.equal(result.success, false, `Should reject: ${JSON.stringify(iconUrl)}`);
- }
-});
-
-test("updateProviderNodeSchema accepts a valid iconUrl", () => {
- const result = updateProviderNodeSchema.safeParse({
- name: "Test",
- prefix: "test",
- baseUrl: "https://test.com",
- iconUrl: "https://example.com/logo.png",
- });
- assert.equal(result.success, true);
-});
-
-test("updateProviderNodeSchema rejects a non-URL iconUrl", () => {
- const result = updateProviderNodeSchema.safeParse({
- name: "Test",
- prefix: "test",
- baseUrl: "https://test.com",
- iconUrl: "not-a-url",
- });
- assert.equal(result.success, false);
-});
-
-test("provider nodes route creates an OpenAI-compatible node with iconUrl", async () => {
- const response = await providerNodesRoute.POST(
- makeRequest({
- name: "Icon URL Node",
- prefix: "icon-url",
- apiType: "chat",
- baseUrl: "https://custom.example.com/v1",
- iconUrl: "https://cdn.example.com/icons/custom.png",
- })
- );
- const body = (await response.json()) as any;
-
- assert.equal(response.status, 201);
- assert.match(body.node.id, new RegExp(`^${OPENAI_COMPATIBLE_PREFIX}chat-`));
- assert.equal(body.node.iconUrl, "https://cdn.example.com/icons/custom.png");
-});
-
-test("provider nodes route creates nodes without iconUrl (null)", async () => {
- const response = await providerNodesRoute.POST(
- makeRequest({
- name: "No Icon Node",
- prefix: "no-icon",
- apiType: "chat",
- baseUrl: "https://noicon.example.com/v1",
- })
- );
- const body = (await response.json()) as any;
-
- assert.equal(response.status, 201);
- assert.equal(body.node.iconUrl, null);
-});
-
-test("provider nodes route update modifies iconUrl", async () => {
- const createResponse = await providerNodesRoute.POST(
- makeRequest({
- name: "Original Node",
- prefix: "original-icon",
- apiType: "chat",
- baseUrl: "https://original.example.com/v1",
- })
- );
- const created = (await createResponse.json()) as any;
- const nodeId = created.node.id;
- assert.equal(created.node.iconUrl, null);
-
- const updateResponse = await providerNodesIdRoute.PUT(
- makeUpdateRequest(nodeId, {
- name: "Updated Node",
- prefix: "updated-icon",
- apiType: "chat",
- baseUrl: "https://updated.example.com/v1",
- iconUrl: "https://cdn.example.com/icons/updated.png",
- }),
- { params: Promise.resolve({ id: nodeId }) }
- );
- const updated = (await updateResponse.json()) as any;
-
- assert.equal(updateResponse.status, 200);
- assert.equal(updated.node.iconUrl, "https://cdn.example.com/icons/updated.png");
-});
-
-test("provider nodes route update can clear iconUrl by passing an empty string", async () => {
- const createResponse = await providerNodesRoute.POST(
- makeRequest({
- name: "Node With Icon",
- prefix: "with-icon",
- apiType: "chat",
- baseUrl: "https://withicon.example.com/v1",
- iconUrl: "https://cdn.example.com/icons/keep.png",
- })
- );
- const created = (await createResponse.json()) as any;
- const nodeId = created.node.id;
- assert.equal(created.node.iconUrl, "https://cdn.example.com/icons/keep.png");
-
- const updateResponse = await providerNodesIdRoute.PUT(
- makeUpdateRequest(nodeId, {
- name: "Node Without Icon",
- prefix: "no-clear",
- apiType: "chat",
- baseUrl: "https://noclear.example.com/v1",
- iconUrl: "",
- }),
- { params: Promise.resolve({ id: nodeId }) }
- );
- const updated = (await updateResponse.json()) as any;
-
- assert.equal(updateResponse.status, 200);
- assert.equal(updated.node.iconUrl, null);
-});
-
-test("db: createProviderNode and getProviderNodeById round-trip iconUrl", async () => {
- const node = await providersDb.createProviderNode({
- id: "openai-compatible-chat-icon-url-db",
- type: "openai-compatible",
- name: "DB Icon URL Test",
- prefix: "db-icon",
- apiType: "chat",
- baseUrl: "https://db.example.com/v1",
- iconUrl: "https://cdn.example.com/icons/db.png",
- });
-
- assert.equal(node.iconUrl, "https://cdn.example.com/icons/db.png");
-
- const retrieved = await providersDb.getProviderNodeById("openai-compatible-chat-icon-url-db");
- assert.equal(retrieved.iconUrl, "https://cdn.example.com/icons/db.png");
-});
-
-test("db: createProviderNode without iconUrl stores null", async () => {
- const node = await providersDb.createProviderNode({
- id: "openai-compatible-chat-no-icon-db",
- type: "openai-compatible",
- name: "DB No Icon Test",
- prefix: "db-no-icon",
- apiType: "chat",
- baseUrl: "https://db-no-icon.example.com/v1",
- });
-
- assert.equal(node.iconUrl, null);
-});
-
-test("db: updateProviderNode modifies iconUrl", async () => {
- const node = await providersDb.createProviderNode({
- id: "openai-compatible-chat-update-icon",
- type: "openai-compatible",
- name: "Update Icon Test",
- prefix: "update-icon",
- apiType: "chat",
- baseUrl: "https://update-icon.example.com/v1",
- iconUrl: "https://cdn.example.com/icons/initial.png",
- });
-
- assert.equal(node.iconUrl, "https://cdn.example.com/icons/initial.png");
-
- const updated = await providersDb.updateProviderNode("openai-compatible-chat-update-icon", {
- iconUrl: "https://cdn.example.com/icons/updated.png",
- });
-
- assert.equal(updated.iconUrl, "https://cdn.example.com/icons/updated.png");
-
- const retrieved = await providersDb.getProviderNodeById("openai-compatible-chat-update-icon");
- assert.equal(retrieved.iconUrl, "https://cdn.example.com/icons/updated.png");
-});
-
-test("db: updateProviderNode can clear iconUrl by passing null", async () => {
- const node = await providersDb.createProviderNode({
- id: "openai-compatible-chat-clear-icon",
- type: "openai-compatible",
- name: "Clear Icon Test",
- prefix: "clear-icon",
- apiType: "chat",
- baseUrl: "https://clear-icon.example.com/v1",
- iconUrl: "https://cdn.example.com/icons/clear-me.png",
- });
-
- assert.equal(node.iconUrl, "https://cdn.example.com/icons/clear-me.png");
-
- const updated = await providersDb.updateProviderNode("openai-compatible-chat-clear-icon", {
- iconUrl: null,
- });
-
- assert.equal(updated.iconUrl, null);
-
- const retrieved = await providersDb.getProviderNodeById("openai-compatible-chat-clear-icon");
- assert.equal(retrieved.iconUrl, null);
-});
diff --git a/tests/unit/provider-plugin-manifest-url.test.ts b/tests/unit/provider-plugin-manifest-url.test.ts
deleted file mode 100644
index e2bcbc307a..0000000000
--- a/tests/unit/provider-plugin-manifest-url.test.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import assert from "node:assert/strict";
-import test from "node:test";
-
-import {
- PROVIDER_PLUGIN_MANIFEST_HEADER,
- resolveProviderPluginManifestUrl,
- getProviderPluginManifestHeader,
-} from "../../open-sse/config/providerPluginManifestUrl.ts";
-
-test("provider manifest URL uses explicit env override", () => {
- const previous = process.env.OMNIROUTE_PROVIDER_MANIFEST_URL;
- process.env.OMNIROUTE_PROVIDER_MANIFEST_URL = "http://sidecar.local/manifest.json";
- try {
- assert.equal(
- resolveProviderPluginManifestUrl("http://127.0.0.1:20128"),
- "http://sidecar.local/manifest.json",
- );
- } finally {
- if (previous === undefined) {
- delete process.env.OMNIROUTE_PROVIDER_MANIFEST_URL;
- } else {
- process.env.OMNIROUTE_PROVIDER_MANIFEST_URL = previous;
- }
- }
-});
-
-test("provider manifest URL derives from request origin", () => {
- assert.equal(
- resolveProviderPluginManifestUrl("http://127.0.0.1:20128/"),
- "http://127.0.0.1:20128/api/v1/provider-plugin-manifest",
- );
-});
-
-test("provider manifest header exposes stable header name", () => {
- assert.deepEqual(getProviderPluginManifestHeader("http://localhost:20128"), {
- [PROVIDER_PLUGIN_MANIFEST_HEADER]:
- "http://localhost:20128/api/v1/provider-plugin-manifest",
- });
-});
diff --git a/tests/unit/provider-plugin-manifest.test.ts b/tests/unit/provider-plugin-manifest.test.ts
deleted file mode 100644
index 37ce937b1c..0000000000
--- a/tests/unit/provider-plugin-manifest.test.ts
+++ /dev/null
@@ -1,121 +0,0 @@
-import assert from "node:assert/strict";
-import test from "node:test";
-
-import {
- generateProviderPluginManifestFromRegistry,
- getProviderPluginManifestEntryFromRegistry,
-} from "../../open-sse/config/providerPluginManifest.ts";
-import type { RegistryEntry } from "../../open-sse/config/providers/shared.ts";
-
-const registryFixture: Record<string, RegistryEntry> = {
- openai: {
- id: "openai",
- alias: "openai",
- format: "openai",
- executor: "default",
- baseUrl: "https://api.openai.com/v1/chat/completions",
- authType: "apikey",
- authHeader: "bearer",
- defaultContextLength: 128000,
- models: [
- { id: "gpt-4.1", name: "GPT-4.1", contextLength: 1047576 },
- {
- id: "o3",
- name: "O3",
- contextLength: 200000,
- unsupportedParams: ["temperature", "top_p"],
- },
- ],
- },
- anthropic: {
- id: "anthropic",
- alias: "anthropic",
- format: "claude",
- executor: "default",
- baseUrl: "https://api.anthropic.com/v1/messages",
- authType: "apikey",
- authHeader: "x-api-key",
- headers: {
- "Anthropic-Version": "2023-06-01",
- },
- models: [{ id: "claude-sonnet-4.6", name: "Claude Sonnet 4.6" }],
- },
- "claude-web": {
- id: "claude-web",
- alias: "cw",
- format: "openai",
- executor: "claude-web",
- baseUrl: "https://claude.ai/api/organizations",
- authType: "apikey",
- authHeader: "cookie",
- models: [{ id: "claude-sonnet-4.6", name: "Claude 4.6 Sonnet (web)" }],
- },
- claude: {
- id: "claude",
- alias: "claude",
- format: "claude",
- executor: "default",
- baseUrl: "https://api.anthropic.com/v1/messages",
- authType: "oauth",
- authHeader: "x-api-key",
- oauth: {
- clientIdDefault: "public-client",
- clientSecretDefault: "secret-that-must-not-export",
- tokenUrl: "https://console.anthropic.com/oauth/token",
- },
- models: [{ id: "claude-opus-4.7", name: "Claude Opus 4.7" }],
- },
-};
-
-test("provider plugin manifest is JSON-safe and stable enough for sidecars", () => {
- const manifest = generateProviderPluginManifestFromRegistry(registryFixture);
- const roundTripped = JSON.parse(JSON.stringify(manifest));
-
- assert.equal(roundTripped.schemaVersion, 1);
- assert.equal(roundTripped.generatedFrom, "open-sse/config/providers");
- assert.equal(roundTripped.providers.length, 4);
- assert.deepEqual(
- roundTripped.providers.map((provider: { id: string }) => provider.id),
- [...roundTripped.providers.map((provider: { id: string }) => provider.id)].sort(),
- );
-});
-
-test("manifest exposes API-key default-executor providers as sidecar candidates", () => {
- const openai = getProviderPluginManifestEntryFromRegistry(registryFixture, "openai");
-
- assert.ok(openai);
- assert.equal(openai.sidecar.eligible, true);
- assert.deepEqual(openai.sidecar.reasons, []);
- assert.ok(openai.capabilities.includes("apikey"));
- assert.ok(openai.capabilities.includes("sidecar-candidate"));
- assert.equal(openai.endpoints.baseUrl, "https://api.openai.com/v1/chat/completions");
- assert.ok(openai.models.some((model) => model.id === "gpt-4.1"));
-});
-
-test("manifest keeps custom web executors on the TypeScript fallback path", () => {
- const claudeWeb = getProviderPluginManifestEntryFromRegistry(registryFixture, "cw");
-
- assert.ok(claudeWeb);
- assert.equal(claudeWeb.id, "claude-web");
- assert.equal(claudeWeb.sidecar.eligible, false);
- assert.ok(claudeWeb.capabilities.includes("custom-executor"));
- assert.ok(claudeWeb.sidecar.reasons.some((reason) => reason.includes("claude-web")));
-});
-
-test("manifest does not export OAuth client secrets or dynamic functions", () => {
- const manifest = generateProviderPluginManifestFromRegistry(registryFixture);
- const serialized = JSON.stringify(manifest);
-
- assert.equal(serialized.includes("clientSecret"), false);
- assert.equal(serialized.includes("clientSecretDefault"), false);
- assert.equal(serialized.includes("clientSecretEnv"), false);
-
- const parsed = JSON.parse(serialized);
- for (const provider of parsed.providers) {
- assert.notEqual(typeof provider.endpoints?.urlBuilder, "function");
- assert.equal("oauth" in provider, false);
- assert.equal("headers" in provider, false);
- assert.equal("extraHeaders" in provider, false);
- assert.equal("requestDefaults" in provider, false);
- }
-});
diff --git a/tests/unit/provider-request-failure-pipeline.test.ts b/tests/unit/provider-request-failure-pipeline.test.ts
index 9a95322c72..cedb7e3f16 100644
--- a/tests/unit/provider-request-failure-pipeline.test.ts
+++ b/tests/unit/provider-request-failure-pipeline.test.ts
@@ -485,7 +485,7 @@ test("CC-compatible providerRequest log keeps request beta headers and summarize
assert.ok(providerRequest, "providerRequest must be present on CC-compatible success");
assert.equal(providerRequest.headers["cf-ray"], undefined);
assert.equal(providerRequest.headers.server, undefined);
- assert.equal(providerRequest.headers.Accept, "text/event-stream");
+ assert.equal(providerRequest.headers.Accept, "application/json");
assert.match(providerRequest.headers["anthropic-beta"], new RegExp(CONTEXT_1M_BETA_HEADER));
assert.match(
providerRequest.headers["anthropic-beta"],
diff --git a/tests/unit/provider-scoped-chat-completions-validation.test.ts b/tests/unit/provider-scoped-chat-completions-validation.test.ts
deleted file mode 100644
index 24650b5f23..0000000000
--- a/tests/unit/provider-scoped-chat-completions-validation.test.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-// Regression guard for #5907 — the provider-scoped chat/completions route
-// (`/v1/providers/{provider}/chat/completions`) must NOT re-apply the strict
-// `providerChatCompletionSchema`. Full body-format validation is delegated to
-// handleChat; the route keeps only the minimal guards it needs to normalize the
-// model prefix. This test locks that contract without mocking handleChat (the
-// project's node:test runner does not enable --experimental-test-module-mocks,
-// and the Stryker tap-runner rejects mock.module), by exercising the branches
-// that return BEFORE delegation:
-// - a loosely-valid body (no `messages`, which the removed strict schema would
-// have 400'd) now reaches the model-prefix logic instead of a schema 400;
-// - the minimal route-level guards still reject invalid JSON, non-object
-// bodies, non-string models, and unknown providers.
-import { test, after } from "node:test";
-import assert from "node:assert/strict";
-
-const { POST } =
- await import("../../src/app/api/v1/providers/[provider]/chat/completions/route.ts");
-
-// Importing the route transitively opens the SQLite handle (handleChat's graph).
-// Release it so Node's native test runner does not hang on open handles.
-after(async () => {
- try {
- const core = await import("../../src/lib/db/core.ts");
- core.resetDbInstance();
- } catch {
- // best-effort cleanup — never fail the suite on teardown
- }
-});
-
-function makeRequest(body: string) {
- return new Request("http://localhost/v1/providers/openai/chat/completions", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body,
- });
-}
-
-const params = (provider: string) => ({ params: Promise.resolve({ provider }) });
-
-test("#5907 a loosely-valid body (no messages) is no longer rejected by the removed strict schema", async () => {
- // `{ model: "anthropic/..." }` has NO `messages`. Under the old strict
- // providerChatCompletionSchema this 400'd at the route before any prefix
- // check. The relaxed route must instead run the model-prefix validation and
- // return the *specific* cross-provider error — proving the schema is gone.
- const res = await POST(
- makeRequest(JSON.stringify({ model: "anthropic/claude-3-5-sonnet" })),
- params("openai")
- );
- assert.equal(res.status, 400);
- const body = await res.json();
- assert.match(
- body.error.message,
- /does not belong to provider/i,
- "expected the model-prefix check to run — a schema validation 400 would mean the strict schema is still applied"
- );
-});
-
-test("#5907 rejects invalid JSON with 400", async () => {
- const res = await POST(makeRequest("{not json"), params("openai"));
- assert.equal(res.status, 400);
-});
-
-test("#5907 rejects a non-object body (array) with 400", async () => {
- const res = await POST(makeRequest(JSON.stringify([1, 2, 3])), params("openai"));
- assert.equal(res.status, 400);
- const body = await res.json();
- assert.match(body.error.message, /must be a JSON object/i);
-});
-
-test("#5907 rejects a non-string model with 400", async () => {
- const res = await POST(makeRequest(JSON.stringify({ model: 123 })), params("openai"));
- assert.equal(res.status, 400);
- const body = await res.json();
- assert.match(body.error.message, /model must be a string/i);
-});
-
-test("#5907 rejects an unknown provider with 400", async () => {
- const res = await POST(makeRequest(JSON.stringify({ model: "gpt-4o" })), params("nope-xyz"));
- assert.equal(res.status, 400);
-});
-
-test("#5907 route errors are sanitized (no stack trace leak in body)", async () => {
- const res = await POST(makeRequest("{bad"), params("openai"));
- const body = await res.json();
- assert.ok(!JSON.stringify(body).includes("at /"), "error body must not leak a stack trace");
-});
diff --git a/tests/unit/provider-translate-path-golden.test.ts b/tests/unit/provider-translate-path-golden.test.ts
index 0aecd8e90f..e9eec891b9 100644
--- a/tests/unit/provider-translate-path-golden.test.ts
+++ b/tests/unit/provider-translate-path-golden.test.ts
@@ -48,25 +48,9 @@ function sanitize(headers: Record<string, unknown>): Record<string, unknown> {
out[k] = v;
continue;
}
- if (k === "X-Stainless-Arch") {
- out[k] = "<ARCH>";
- continue;
- }
- if (k === "X-Stainless-Os") {
- out[k] = "<OS>";
- continue;
- }
let s = v
.replace(/Bearer .+/, "Bearer <TOK>")
.replace(/sk-test-APIKEY|tok-test-ACCESS/g, "<CRED>")
- .replace(/\(([A-Za-z0-9_. -]+); (?:arm64|x64|x86_64|amd64|ia32)\)/g, "(<OS>; <ARCH>)")
- // Antigravity's User-Agent embeds an os.platform()-derived platform string
- // (getAntigravityPlatformInfo) that the (OS; arch) rule above does not cover,
- // so normalize the three known values to keep the golden runner-independent.
- .replace(
- /Macintosh; Intel Mac OS X 10_15_7|Windows NT 10\.0; Win64; x64|X11; Linux x86_64/g,
- "<PLATFORM>"
- )
.replace(/kimi-\d{10,}/g, "kimi-<TS>")
.replace(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i, "<UUID>");
if (NODE_VERSION) s = s.split(NODE_VERSION).join("<NODE>");
diff --git a/tests/unit/provider-validation-specialty.test.ts b/tests/unit/provider-validation-specialty.test.ts
index e1afca203e..6a7bbd3d6d 100644
--- a/tests/unit/provider-validation-specialty.test.ts
+++ b/tests/unit/provider-validation-specialty.test.ts
@@ -242,48 +242,6 @@ test("embedding and rerank specialty validators surface auth failures for Voyage
assert.equal(jina.error, "Invalid API key");
});
-test("v0-vercel specialty validator checks the Platform API chats endpoint", async () => {
- globalThis.fetch = async (url, init = {}) => {
- assert.equal(String(url), "https://api.v0.dev/v1/chats?limit=1");
- assert.equal((init.headers as Record<string, string>).Authorization, "Bearer v0-key");
- return new Response(JSON.stringify({ object: "list", data: [] }), { status: 200 });
- };
-
- const result = await validateProviderApiKey({
- provider: "v0-vercel",
- apiKey: "v0-key",
- providerSpecificData: {
- baseUrl: "https://api.v0.dev/v1/chat/completions",
- },
- });
-
- assert.deepEqual(result, {
- valid: true,
- error: null,
- method: "v0_platform_chats_list",
- });
-});
-
-test("v0-vercel specialty validator treats auth failures as invalid API key", async () => {
- globalThis.fetch = async (url, init = {}) => {
- assert.equal(String(url), "https://api.v0.dev/v1/chats?limit=1");
- assert.equal((init.headers as Record<string, string>).Authorization, "Bearer bad-v0-key");
- return new Response(JSON.stringify({ error: { type: "unauthorized_error" } }), {
- status: 401,
- });
- };
-
- const result = await validateProviderApiKey({
- provider: "v0-vercel",
- apiKey: "bad-v0-key",
- providerSpecificData: {
- baseUrl: "https://api.v0.dev/v1",
- },
- });
-
- assert.equal(result.error, "Invalid API key");
-});
-
test("gitlab specialty validator accepts PAT auth on the direct access endpoint", async () => {
globalThis.fetch = async (url, init = {}) => {
assert.equal(String(url), "https://gitlab.com/api/v4/code_suggestions/direct_access");
@@ -2825,14 +2783,12 @@ test("huggingface validator accepts a token whoami-v2 recognizes", async () => {
});
test("huggingface validator treats 401/403 as an invalid token", async () => {
- globalThis.fetch = async () =>
- new Response(JSON.stringify({ error: "Unauthorized" }), { status: 401 });
+ globalThis.fetch = async () => new Response(JSON.stringify({ error: "Unauthorized" }), { status: 401 });
const unauthorized = await validateProviderApiKey({ provider: "huggingface", apiKey: "hf_bad" });
assert.equal(unauthorized.valid, false);
assert.equal(unauthorized.error, "Invalid API key");
- globalThis.fetch = async () =>
- new Response(JSON.stringify({ error: "Forbidden" }), { status: 403 });
+ globalThis.fetch = async () => new Response(JSON.stringify({ error: "Forbidden" }), { status: 403 });
const forbidden = await validateProviderApiKey({ provider: "huggingface", apiKey: "hf_bad" });
assert.equal(forbidden.valid, false);
assert.equal(forbidden.error, "Invalid API key");
@@ -2844,10 +2800,7 @@ test("huggingface validator does NOT mark a fine-grained token invalid on a non-
// non-OK status must surface as a transient error, never "Invalid API key".
globalThis.fetch = async () => new Response("upstream down", { status: 503 });
- const result = await validateProviderApiKey({
- provider: "huggingface",
- apiKey: "hf_finegrained",
- });
+ const result = await validateProviderApiKey({ provider: "huggingface", apiKey: "hf_finegrained" });
assert.equal(result.valid, false);
assert.notEqual(result.error, "Invalid API key");
diff --git a/tests/unit/providers-constants-split.test.ts b/tests/unit/providers-constants-split.test.ts
index 7e187dbbb2..eb4e425673 100644
--- a/tests/unit/providers-constants-split.test.ts
+++ b/tests/unit/providers-constants-split.test.ts
@@ -1,7 +1,7 @@
// Characterization of the providers.ts catalog split (god-file decomposition): the host became a
// barrel that re-exports 10 data catalogs now living under constants/providers/*, and APIKEY is
// merged from 6 semantic family files (apikey/<family>.ts). Locks: the public surface (every catalog
-// + helpers still exported), the spread-merge integrity (166 APIKEY entries, no loss/dup), and that
+// + helpers still exported), the spread-merge integrity (159 APIKEY entries, no loss/dup), and that
// load-time Zod validation still runs. Pure-data move → behavior must be identical.
import { test } from "node:test";
import assert from "node:assert/strict";
@@ -31,12 +31,12 @@ test("barrel still exports every catalog + key helpers", () => {
}
});
-test("APIKEY_PROVIDERS merges the 6 family files into 166 entries (no loss / no dup)", async () => {
+test("APIKEY_PROVIDERS merges the 6 family files into 158 entries (no loss / no dup)", async () => {
const keys = Object.keys((P as Record<string, object>).APIKEY_PROVIDERS);
- assert.equal(keys.length, 166);
- assert.equal(new Set(keys).size, 166, "duplicate keys after spread-merge");
+ assert.equal(keys.length, 158);
+ assert.equal(new Set(keys).size, 158, "duplicate keys after spread-merge");
// the merged object's entry-count equals the sum of the 6 semantic family files; families are a
- // strict partition (every provider in exactly one), so the sum must be exactly 166.
+ // strict partition (every provider in exactly one), so the sum must be exactly 158.
const families: [string, string][] = [
["gateways", "APIKEY_PROVIDERS_GATEWAYS"],
["frontier-labs", "APIKEY_PROVIDERS_FRONTIER"],
@@ -56,7 +56,7 @@ test("APIKEY_PROVIDERS merges the 6 family files into 166 entries (no loss / no
seen.add(k);
}
}
- assert.equal(famTotal, 166, "families must partition all 166 providers");
+ assert.equal(famTotal, 158, "families must partition all 158 providers");
});
test("AI_PROVIDERS Proxy aggregates all sections; lookups resolve", () => {
diff --git a/tests/unit/providers-page-utils.test.ts b/tests/unit/providers-page-utils.test.ts
index 17f30b9038..6b0426ad45 100644
--- a/tests/unit/providers-page-utils.test.ts
+++ b/tests/unit/providers-page-utils.test.ts
@@ -748,7 +748,6 @@ test("compatible catalog entries keep dynamic compatible metadata", () => {
type: "openai-compatible",
apiType: "responses",
baseUrl: "https://example.test",
- iconUrl: "https://cdn.example.com/icons/lab.png",
},
compatibleLabels: {
ccCompatibleName: "CC Compatible",
@@ -763,8 +762,6 @@ test("compatible catalog entries keep dynamic compatible metadata", () => {
assert.equal(compatibleProvider?.toggleAuthType, "apikey");
assert.equal(compatibleProvider?.apiType, "responses");
assert.equal(compatibleProvider?.baseUrl, "https://example.test");
- // #2166: custom remote icon URL passthrough.
- assert.equal(compatibleProvider?.iconUrl, "https://cdn.example.com/icons/lab.png");
});
test("model search filter matches providers by model id", async () => {
@@ -1018,13 +1015,7 @@ test("buildCompatibleProviderGroups partitions nodes by type + claude-code prefi
const groups = providerPageUtils.buildCompatibleProviderGroups(
[
- {
- id: "my-oai",
- name: "My OAI",
- type: "openai-compatible",
- apiType: "responses",
- iconUrl: "https://cdn.example.com/icons/my-oai.png",
- },
+ { id: "my-oai", name: "My OAI", type: "openai-compatible", apiType: "responses" },
{ id: "my-anthropic", name: "My Claude", type: "anthropic-compatible" },
{ id: "anthropic-compatible-cc-acme", name: "Acme CC", type: "anthropic-compatible" },
{ id: "ignored-node", name: "Ignored", type: "unsupported-provider" },
@@ -1046,14 +1037,6 @@ test("buildCompatibleProviderGroups partitions nodes by type + claude-code prefi
"missing name falls back to the openai-compatible label"
);
- // #2166: custom remote icon URL passthrough.
- assert.equal(
- groups.openai[0].iconUrl,
- "https://cdn.example.com/icons/my-oai.png",
- "iconUrl is preserved for nodes that set it"
- );
- assert.equal(groups.openai[1].iconUrl, undefined, "iconUrl is undefined when the node has none");
-
assert.deepEqual(
groups.anthropic.map((p) => p.id),
["my-anthropic"],
@@ -1066,43 +1049,3 @@ test("buildCompatibleProviderGroups partitions nodes by type + claude-code prefi
"anthropic-compatible nodes with the cc- prefix land in the claudeCode bucket"
);
});
-
-test("connectionMatchesProviderCard counts a dual-auth provider's PAT (apikey) connection on its OAuth card", () => {
- const { connectionMatchesProviderCard } = providerPageUtils;
-
- // qoder is OAuth-categorized but its working auth is a PAT (authType "apikey").
- // Regression: the OAuth card must count the PAT connection, else the dashboard
- // shows a connected qoder as "not connected".
- assert.equal(
- connectionMatchesProviderCard({ provider: "qoder", authType: "apikey" }, "qoder", "oauth"),
- true
- );
- assert.equal(
- connectionMatchesProviderCard({ provider: "qoder", authType: "oauth" }, "qoder", "oauth"),
- true
- );
-
- // A normal OAuth-only provider must NOT count an apikey connection on its OAuth card.
- assert.equal(
- connectionMatchesProviderCard({ provider: "claude", authType: "apikey" }, "claude", "oauth"),
- false
- );
- assert.equal(
- connectionMatchesProviderCard({ provider: "claude", authType: "oauth" }, "claude", "oauth"),
- true
- );
-
- // Provider mismatch and the "free" card (counts everything) behave as expected.
- assert.equal(
- connectionMatchesProviderCard({ provider: "openai", authType: "apikey" }, "qoder", "oauth"),
- false
- );
- assert.equal(
- connectionMatchesProviderCard({ provider: "qoder", authType: "apikey" }, "qoder", "free"),
- true
- );
-
- // Defensive: a null/undefined connection must not throw (gemini-code-assist).
- assert.equal(connectionMatchesProviderCard(null, "qoder", "oauth"), false);
- assert.equal(connectionMatchesProviderCard(undefined, "qoder", "oauth"), false);
-});
diff --git a/tests/unit/proxy-batch-routes-5918.test.ts b/tests/unit/proxy-batch-routes-5918.test.ts
deleted file mode 100644
index fafe9f691e..0000000000
--- a/tests/unit/proxy-batch-routes-5918.test.ts
+++ /dev/null
@@ -1,103 +0,0 @@
-/**
- * Route coverage for #5918 proxy management endpoints:
- * POST /api/settings/proxies/batch-delete
- * POST /api/settings/proxies/auto-test
- *
- * DB-backed and network-free: batch-delete is exercised end-to-end against a
- * temp SQLite DB; auto-test is exercised only on its no-proxy early-return path
- * (which returns before any outbound probe), so no real network is touched.
- */
-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-proxy-batch-5918-"));
-process.env.DATA_DIR = TEST_DATA_DIR;
-process.env.API_KEY_SECRET = "test-secret";
-delete process.env.INITIAL_PASSWORD; // auth not required in this test env
-
-const core = await import("../../src/lib/db/core.ts");
-const proxiesDb = await import("../../src/lib/db/proxies.ts");
-const { POST: batchDeletePost } = await import(
- "../../src/app/api/settings/proxies/batch-delete/route.ts"
-);
-const { POST: autoTestPost } = await import(
- "../../src/app/api/settings/proxies/auto-test/route.ts"
-);
-
-function jsonRequest(body: unknown): Request {
- return new Request("http://localhost/api/settings/proxies/batch-delete", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify(body),
- });
-}
-
-async function resetStorage() {
- delete process.env.INITIAL_PASSWORD;
- core.resetDbInstance();
- fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
- fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
-}
-
-test.after(async () => {
- core.resetDbInstance();
- fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
-});
-
-test("batch-delete removes multiple existing proxies in one request", async () => {
- await resetStorage();
- const a = await proxiesDb.createProxy({ name: "A", type: "http", host: "127.0.0.1", port: 8080 });
- const b = await proxiesDb.createProxy({ name: "B", type: "http", host: "127.0.0.1", port: 8081 });
- assert.ok(a?.id && b?.id);
-
- const res = await batchDeletePost(jsonRequest({ ids: [a.id, b.id] }));
- assert.equal(res.status, 200);
- const body = await res.json();
- assert.equal(body.deleted, 2);
- assert.equal(body.failed, 0);
- // Both are actually gone from the store.
- const remaining = await proxiesDb.listProxies({ includeSecrets: false });
- assert.equal(remaining.filter((p) => p.id === a.id || p.id === b.id).length, 0);
-});
-
-test("batch-delete reports non-existent ids as failed without throwing", async () => {
- await resetStorage();
- const res = await batchDeletePost(jsonRequest({ ids: ["does-not-exist"] }));
- assert.equal(res.status, 200);
- const body = await res.json();
- assert.equal(body.deleted, 0);
- assert.equal(body.failed, 1);
-});
-
-test("batch-delete rejects an empty ids array with 400 (validation, pre-DB)", async () => {
- await resetStorage();
- const res = await batchDeletePost(jsonRequest({ ids: [] }));
- assert.equal(res.status, 400);
-});
-
-test("batch-delete rejects invalid JSON with 400", async () => {
- await resetStorage();
- const bad = new Request("http://localhost/x", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: "{ not json",
- });
- const res = await batchDeletePost(bad);
- assert.equal(res.status, 400);
-});
-
-test("auto-test returns an empty result set when there are no proxies (no network probe)", async () => {
- await resetStorage();
- const req = new Request("http://localhost/api/settings/proxies/auto-test", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({}),
- });
- const res = await autoTestPost(req);
- assert.equal(res.status, 200);
- const body = await res.json();
- assert.deepEqual(body.results, []);
-});
diff --git a/tests/unit/qiniu-provider.test.ts b/tests/unit/qiniu-provider.test.ts
deleted file mode 100644
index f98f38623e..0000000000
--- a/tests/unit/qiniu-provider.test.ts
+++ /dev/null
@@ -1,148 +0,0 @@
-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 { APIKEY_PROVIDERS } = await import("../../src/shared/constants/providers.ts");
-const { PROVIDER_ENDPOINTS } = await import("../../src/shared/constants/config.ts");
-const { REGISTRY: providerRegistry } = await import("../../open-sse/config/providerRegistry.ts");
-const { isValidModel } = await import("../../src/shared/constants/models.ts");
-
-const QINIU_CHAT_URL = "https://api.qnaigc.com/v1/chat/completions";
-const QINIU_MODELS_URL = "https://api.qnaigc.com/v1/models";
-
-test("Qiniu is registered as an API-key provider", () => {
- const entry = APIKEY_PROVIDERS.qiniu;
- assert.ok(entry, "APIKEY_PROVIDERS.qiniu must be defined");
- assert.equal(entry.id, "qiniu");
- assert.equal(entry.alias, "qiniu");
- assert.equal(entry.name, "Qiniu");
- assert.equal(entry.website, "https://www.qiniu.com");
- assert.equal(entry.passthroughModels, true);
-});
-
-test("Qiniu exposes the OpenAI-compatible chat completions endpoint", () => {
- assert.equal(PROVIDER_ENDPOINTS.qiniu, QINIU_CHAT_URL);
-});
-
-test("Qiniu registry entry uses OpenAI format with bearer API-key auth", () => {
- const entry = providerRegistry.qiniu;
- assert.ok(entry, "providerRegistry.qiniu must be defined");
- assert.equal(entry.id, "qiniu");
- assert.equal(entry.alias, "qiniu");
- assert.equal(entry.format, "openai");
- assert.equal(entry.executor, "default");
- assert.equal(entry.authType, "apikey");
- assert.equal(entry.authHeader, "bearer");
- assert.equal(entry.baseUrl, QINIU_CHAT_URL);
- assert.equal(entry.modelsUrl, QINIU_MODELS_URL);
- assert.equal(entry.passthroughModels, true);
-});
-
-test("Qiniu ships no static model seed — relies fully on passthrough + live catalog", () => {
- const models = providerRegistry.qiniu.models;
- assert.deepEqual(models, []);
-});
-
-test("Qiniu accepts any model id via passthrough models (DeepSeek/Claude/Kimi behind one key)", () => {
- assert.equal(isValidModel("qiniu", "deepseek-v3"), true);
- assert.equal(isValidModel("qiniu", "deepseek-v3.2"), true);
- assert.equal(isValidModel("qiniu", "claude-sonnet-4-5"), true);
- assert.equal(isValidModel("qiniu", "kimi-k2"), true);
-});
-
-const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-qiniu-"));
-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 modelsRoute = await import("../../src/app/api/providers/[id]/models/route.ts");
-
-async function resetStorage() {
- core.resetDbInstance();
- fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
- fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
-}
-
-test.after(() => {
- core.resetDbInstance();
- fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
-});
-
-interface ModelsBody {
- provider: string;
- connectionId: string;
- models: Array<{ id: string }>;
- source?: string;
-}
-
-test("Qiniu import fetches the live /v1/models catalog", async () => {
- await resetStorage();
- const connection = await providersDb.createProviderConnection({
- provider: "qiniu",
- authType: "apikey",
- name: "qiniu-live",
- apiKey: "qiniu-key",
- });
-
- let fetched = false;
- const originalFetch = globalThis.fetch;
- globalThis.fetch = async (url) => {
- if (String(url) === QINIU_MODELS_URL) {
- fetched = true;
- return Response.json({
- object: "list",
- data: [{ id: "deepseek-v3" }, { id: "deepseek-v4" }, { id: "kimi-k2" }],
- });
- }
- return new Response("not found", { status: 404 });
- };
-
- try {
- const response = await modelsRoute.GET(
- new Request(`http://localhost/api/providers/${connection.id}/models?refresh=true`),
- { params: { id: connection.id } }
- );
- assert.equal(response.status, 200);
- const body = (await response.json()) as ModelsBody;
- assert.equal(body.provider, "qiniu");
- assert.equal(body.source, "api", "should serve the live upstream catalog");
- assert.ok(fetched, `should have probed ${QINIU_MODELS_URL}`);
- const ids = body.models.map((model) => model.id);
- assert.ok(ids.includes("deepseek-v3"), `live catalog model missing: ${ids.join(",")}`);
- assert.ok(ids.includes("kimi-k2"), `live catalog model missing: ${ids.join(",")}`);
- } finally {
- globalThis.fetch = originalFetch;
- }
-});
-
-test("Qiniu import falls back to an empty local catalog when live fetch fails", async () => {
- await resetStorage();
- const connection = await providersDb.createProviderConnection({
- provider: "qiniu",
- authType: "apikey",
- name: "qiniu-fallback",
- apiKey: "qiniu-key-2",
- });
-
- const originalFetch = globalThis.fetch;
- globalThis.fetch = async () => new Response("bad gateway", { status: 502 });
-
- try {
- const response = await modelsRoute.GET(
- new Request(`http://localhost/api/providers/${connection.id}/models?refresh=true`),
- { params: { id: connection.id } }
- );
- assert.equal(response.status, 200);
- const body = (await response.json()) as ModelsBody;
- assert.equal(body.provider, "qiniu");
- assert.equal(body.source, "local_catalog", "import must not break when upstream is down");
- assert.deepEqual(
- body.models.map((model) => model.id),
- []
- );
- } finally {
- globalThis.fetch = originalFetch;
- }
-});
diff --git a/tests/unit/qoder-cli.test.ts b/tests/unit/qoder-cli.test.ts
index 5f781f4baa..0928d72527 100644
--- a/tests/unit/qoder-cli.test.ts
+++ b/tests/unit/qoder-cli.test.ts
@@ -1,47 +1,8 @@
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 qoderCli = await import("../../open-sse/services/qoderCli.ts");
-/**
- * Write a fake `qodercli` binary and point CLI_QODER_BIN at it (see the twin
- * helper in qoder-executor.test.ts). The stub authenticates unless the PAT
- * contains "bad", covering both `--list-models` (validation) and `--print`.
- */
-function withStubQoderCli(fn: () => void | Promise<void>) {
- const prevBin = process.env.CLI_QODER_BIN;
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "qodercli-stub-"));
- const stub = path.join(dir, "qodercli");
- fs.writeFileSync(
- stub,
- [
- "#!/bin/sh",
- 'is_bad() { case "$QODER_PERSONAL_ACCESS_TOKEN" in *bad*) return 0;; *) return 1;; esac; }',
- 'case "$*" in',
- " *--list-models*)",
- ' if is_bad; then echo "Not logged in · Please run /login"; exit 0; fi',
- ' printf "MODEL\\nAuto\\nQwen3-Coder\\n"; exit 0;;',
- " *--print*)",
- " cat >/dev/null;",
- ' if is_bad; then printf \'{"type":"result","subtype":"success","is_error":true,"result":"Not logged in · Please run /login"}\\n\'; exit 0; fi',
- ' printf \'{"type":"result","subtype":"success","is_error":false,"result":"OK from stub"}\\n\'; exit 0;;',
- "esac",
- "exit 0",
- ].join("\n"),
- { mode: 0o755 }
- );
- process.env.CLI_QODER_BIN = stub;
- const restore = () => {
- if (prevBin === undefined) delete process.env.CLI_QODER_BIN;
- else process.env.CLI_QODER_BIN = prevBin;
- fs.rmSync(dir, { recursive: true, force: true });
- };
- return Promise.resolve().then(fn).finally(restore);
-}
-
function withEnv(
overrides: Record<string, string | undefined | null>,
fn: () => void | Promise<void>
@@ -120,9 +81,6 @@ test("qoder cli static models are copied and model-to-level mapping covers major
assert.equal(qoderCli.mapQoderModelToLevel("kimi-k2-0905"), "kmodel");
assert.equal(qoderCli.mapQoderModelToLevel("qwen3-coder-plus"), "qmodel");
assert.equal(qoderCli.mapQoderModelToLevel("qoder-rome-30ba3b"), "qmodel");
- assert.equal(qoderCli.mapQoderModelToLevel("glm-5.2"), "gm51model");
- assert.equal(qoderCli.mapQoderModelToLevel("minimax-m3"), "mmodel");
- assert.equal(qoderCli.mapQoderModelToLevel("gm51model"), "gm51model");
assert.equal(qoderCli.mapQoderModelToLevel("totally-unknown"), "auto");
assert.equal(qoderCli.mapQoderModelToLevel(""), null);
});
@@ -285,208 +243,184 @@ test("qoder cli failure parsing classifies auth, timeout and generic upstream er
});
});
-test("validateQoderCliPat returns valid when qodercli lists models for the PAT", async () => {
- await withStubQoderCli(async () => {
- const result = await qoderCli.validateQoderCliPat({ apiKey: "pt-valid-token" });
- assert.deepEqual(result, { valid: true, error: null, unsupported: false });
- });
-});
+test("validateQoderCliPat builds COSY headers and handles success, HTTP failures and fetch errors", async () => {
+ const originalFetch = globalThis.fetch;
+
+ // Test 1: Success path (ping OK + validation OK)
+ {
+ let callIndex = 0;
+ globalThis.fetch = async (url, options = {}) => {
+ callIndex++;
+ const urlStr = String(url);
+ // Ping request
+ if (urlStr.includes("/ping")) {
+ return new Response("pong", { status: 200 });
+ }
+ // Validation request
+ return new Response("ok", { status: 200 });
+ };
-test("validateQoderCliPat rejects a PAT that qodercli reports as not logged in", async () => {
- await withStubQoderCli(async () => {
- const result = await qoderCli.validateQoderCliPat({ apiKey: "pt-bad-token" });
- assert.equal(result.valid, false);
- assert.match(result.error!, /not authorized|integrations/i);
- });
-});
+ const success = await qoderCli.validateQoderCliPat({
+ apiKey: "pat-token",
+ providerSpecificData: { validationModelId: "kimi-k2" },
+ });
+ assert.equal(success.valid, true);
+ assert.equal(success.error, null);
+ assert.equal(success.unsupported, false);
+ }
-test("validateQoderCliPat rejects an encrypted auth blob without spawning", async () => {
- const blobToken = "x".repeat(600);
- const result = await qoderCli.validateQoderCliPat({ apiKey: blobToken });
- assert.equal(result.valid, false);
- assert.match(result.error!, /encrypted auth blob/i);
-});
+ // Test 2: Auth failure (ping OK + validation 403)
+ {
+ globalThis.fetch = async (url) => {
+ if (String(url).includes("/ping")) {
+ return new Response("pong", { status: 200 });
+ }
+ return new Response("denied", { status: 403 });
+ };
-test("validateQoderCliPat requires a token", async () => {
- const result = await qoderCli.validateQoderCliPat({ apiKey: "" });
- assert.equal(result.valid, false);
- assert.match(result.error!, /No Qoder token/i);
-});
+ const denied = await qoderCli.validateQoderCliPat({
+ apiKey: "pat-token",
+ providerSpecificData: { modelId: "qwen3-max" },
+ });
+ assert.equal(denied.valid, false);
+ assert.match(denied.error!, /Authentication failed/);
+ assert.equal(denied.unsupported, false);
+ }
-test("validateQoderCliPat surfaces a clear error when qodercli is missing", async () => {
- const prevBin = process.env.CLI_QODER_BIN;
- process.env.CLI_QODER_BIN = "/nonexistent/qodercli-please-fail";
- try {
- const result = await qoderCli.validateQoderCliPat({ apiKey: "pt-valid-token" });
- assert.equal(result.valid, false);
- assert.match(result.error!, /qodercli|CLI_QODER_BIN|not found/i);
- } finally {
- if (prevBin === undefined) delete process.env.CLI_QODER_BIN;
- else process.env.CLI_QODER_BIN = prevBin;
+ // Test 3: Network error (ping fails)
+ {
+ globalThis.fetch = async () => {
+ throw new Error("network down");
+ };
+
+ const failed = await qoderCli.validateQoderCliPat({ apiKey: "pat-token" });
+ assert.equal(failed.valid, false);
+ assert.match(failed.error!, /Cannot reach Qoder API/);
+ assert.equal(failed.unsupported, false);
}
-});
-test("runQoderCli drives the stub binary and returns its JSON envelope", async () => {
- await withStubQoderCli(async () => {
- const run = await qoderCli.runQoderCli({
- token: "pt-valid-token",
- prompt: "hello",
- stream: false,
- model: "qwen3-coder-plus",
- });
- assert.equal(run.ok, true);
- const parsed = qoderCli.parseQoderCliResult(run.stdout);
- assert.equal(parsed.isError, false);
- assert.equal(parsed.text, "OK from stub");
- });
-});
+ // Test 4: Non-auth 4xx treated as auth-pass
+ {
+ globalThis.fetch = async (url) => {
+ if (String(url).includes("/ping")) {
+ return new Response("pong", { status: 200 });
+ }
+ return new Response("bad request", { status: 400 });
+ };
-test("parseQoderCliResult extracts text, flags errors and tolerates banner noise", () => {
- assert.deepEqual(
- qoderCli.parseQoderCliResult('{"type":"result","is_error":false,"result":"pong"}'),
- { text: "pong", isError: false, errorMessage: "" }
- );
+ const badRequest = await qoderCli.validateQoderCliPat({ apiKey: "pat-token" });
+ assert.equal(badRequest.valid, true);
+ assert.equal(badRequest.error, null);
+ }
- const errored = qoderCli.parseQoderCliResult(
- '{"type":"result","is_error":true,"result":"Not logged in"}'
- );
- assert.equal(errored.isError, true);
- assert.equal(errored.errorMessage, "Not logged in");
+ // Test 5: Empty token returns clear error
+ {
+ await withEnv({ QODER_PERSONAL_ACCESS_TOKEN: undefined }, async () => {
+ const noToken = await qoderCli.validateQoderCliPat({ apiKey: "" });
+ assert.equal(noToken.valid, false);
+ assert.match(noToken.error!, /No Qoder token provided/);
+ });
+ }
- // Leading banner/log lines before the JSON envelope must still parse.
- const noisy = qoderCli.parseQoderCliResult(
- 'starting qodercli...\nwarming up\n{"type":"result","is_error":false,"result":"hi"}'
- );
- assert.equal(noisy.text, "hi");
- assert.equal(noisy.isError, false);
+ // Test 6: Encrypted blob token is rejected with guidance
+ {
+ const blobToken = "x".repeat(600);
+ const blobResult = await qoderCli.validateQoderCliPat({ apiKey: blobToken });
+ assert.equal(blobResult.valid, false);
+ assert.match(blobResult.error!, /encrypted auth blob/);
+ }
- const empty = qoderCli.parseQoderCliResult(" ");
- assert.equal(empty.isError, true);
+ globalThis.fetch = originalFetch;
});
-test("parseQoderCliFailure classifies qodercli auth output as 401", () => {
- for (const msg of [
- "Not logged in · Please run /login",
- "Failed to fetch model list: auth.exchangeJobToken failed: invalid personal token format",
- ]) {
- const failure = qoderCli.parseQoderCliFailure(msg);
- assert.equal(failure.status, 401, msg);
- assert.equal(failure.code, "upstream_auth_error", msg);
+test("validateQoderCliPat succeeds when the validation endpoint returns OK", async () => {
+ const originalFetch = globalThis.fetch;
+ globalThis.fetch = async (url) => {
+ if (String(url).includes("/ping")) return new Response("pong", { status: 200 });
+ return new Response("ok", { status: 200 });
+ };
+
+ try {
+ const result = await qoderCli.validateQoderCliPat({ apiKey: "valid-pat" });
+ assert.equal(result.valid, true);
+ assert.equal(result.error, null);
+ } finally {
+ globalThis.fetch = originalFetch;
}
});
-test("runQoderCli survives qodercli exiting before it reads a large stdin (async EPIPE)", async () => {
- const prevBin = process.env.CLI_QODER_BIN;
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "qodercli-stub-"));
- const stub = path.join(dir, "qodercli");
- // Exits immediately WITHOUT reading stdin. Writing a >pipe-buffer prompt then
- // races an async EPIPE/EINVAL on the closed stdin; without a stream 'error'
- // listener that crashes the whole process (gemini-code-assist review).
- fs.writeFileSync(stub, "#!/bin/sh\nexit 0\n", { mode: 0o755 });
- process.env.CLI_QODER_BIN = stub;
+test("validateQoderCliPat treats 5xx HTTP failures as valid bypass", async () => {
+ const originalFetch = globalThis.fetch;
+ globalThis.fetch = async (url) => {
+ if (String(url).includes("/ping")) return new Response("pong", { status: 200 });
+ return new Response("server error", { status: 500 });
+ };
+
try {
- const run = await qoderCli.runQoderCli({
- token: "pt-x",
- prompt: "x".repeat(1_000_000),
- stream: false,
- model: "auto",
- });
- // The assertion is simply that we get here — a resolved result, no crash.
- assert.equal(typeof run.ok, "boolean");
+ const result = await qoderCli.validateQoderCliPat({ apiKey: "valid-pat" });
+ assert.equal(result.valid, true);
+ assert.match(result.error!, /HTTP 500.*treating PAT as valid/);
} finally {
- if (prevBin === undefined) delete process.env.CLI_QODER_BIN;
- else process.env.CLI_QODER_BIN = prevBin;
- fs.rmSync(dir, { recursive: true, force: true });
+ globalThis.fetch = originalFetch;
}
});
-test("runQoderCli preserves multi-byte UTF-8 output (Chinese) via stream setEncoding", async () => {
- const prevBin = process.env.CLI_QODER_BIN;
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "qodercli-stub-"));
- const stub = path.join(dir, "qodercli");
- // qodercli commonly returns Chinese; stream chunk boundaries must not corrupt it.
- fs.writeFileSync(
- stub,
- '#!/bin/sh\ncat >/dev/null\nprintf \'{"type":"result","is_error":false,"result":"你好世界,测试"}\\n\'\nexit 0\n',
- { mode: 0o755 }
- );
- process.env.CLI_QODER_BIN = stub;
+// #3247: a generic Cosy 500 (`{"success":false,...,"msgCode":500,"message":"Internal
+// Server Error"}`) is a SERVER fault, not a reliable auth verdict — a PAT that works in
+// the Qoder CLI was being wrongly marked "expired". Per the older #1391 rule, a generic
+// 5xx is now a valid bypass; only an explicit auth signal in the body marks it invalid.
+test("validateQoderCliPat treats a generic Cosy 500 (no auth signal) as a valid bypass (#3247)", async () => {
+ const originalFetch = globalThis.fetch;
+ globalThis.fetch = async (url) => {
+ if (String(url).includes("/ping")) return new Response("pong", { status: 200 });
+ return new Response(
+ '{"success":false,"traceId":"a4e5de61929400b9243b4f6e49756906","msgCode":500,"msgInfo":"Internal Server Error","message":"Internal Server Error"}',
+ { status: 500 }
+ );
+ };
+
try {
- const run = await qoderCli.runQoderCli({
- token: "pt-x",
- prompt: "hi",
- stream: false,
- model: "auto",
- });
- assert.equal(run.ok, true);
- assert.equal(qoderCli.parseQoderCliResult(run.stdout).text, "你好世界,测试");
+ const result = await qoderCli.validateQoderCliPat({ apiKey: "pt-valid-token" });
+ assert.equal(result.valid, true);
+ assert.match(result.error!, /treating PAT as valid/);
} finally {
- if (prevBin === undefined) delete process.env.CLI_QODER_BIN;
- else process.env.CLI_QODER_BIN = prevBin;
- fs.rmSync(dir, { recursive: true, force: true });
+ globalThis.fetch = originalFetch;
}
});
-test("parseQoderCliModelNames extracts display names, dropping header/noise", () => {
- const names = qoderCli.parseQoderCliModelNames(
- "MODEL\nAuto\nGLM-5.2\nKimi-K2.7-Code\n\nDeepSeek-V4-Pro\n"
- );
- assert.deepEqual(names, ["Auto", "GLM-5.2", "Kimi-K2.7-Code", "DeepSeek-V4-Pro"]);
- // Auth/error lines must not be mistaken for model names.
- assert.deepEqual(qoderCli.parseQoderCliModelNames("Not logged in · Please run /login"), []);
-});
+test("validateQoderCliPat treats a generic 'Internal Server Error' 500 as a valid bypass (#3247)", async () => {
+ const originalFetch = globalThis.fetch;
+ globalThis.fetch = async (url) => {
+ if (String(url).includes("/ping")) return new Response("pong", { status: 200 });
+ return new Response(' { "success" : false, "error": "Internal Server Error" } ', {
+ status: 500,
+ });
+ };
-test("resolveQoderModelName prefers a live display name, then static, then Auto", () => {
- const live = ["Auto", "GLM-5.2", "Kimi-K2.7-Code"];
- // punctuation/case-insensitive match against the live list
- assert.equal(qoderCli.resolveQoderModelName("glm-5.2", live), "GLM-5.2");
- assert.equal(qoderCli.resolveQoderModelName("GLM-5.2", live), "GLM-5.2");
- assert.equal(qoderCli.resolveQoderModelName("kimi-k2.7-code", live), "Kimi-K2.7-Code");
- // not in the live list → static family map (level key)
- assert.equal(qoderCli.resolveQoderModelName("qwen3-coder-plus", live), "qmodel");
- // unknown → Auto; empty → Auto
- assert.equal(qoderCli.resolveQoderModelName("totally-unknown", live), "auto");
- assert.equal(qoderCli.resolveQoderModelName("", live), "auto");
- // no live list at all → falls back to the static map
- assert.equal(qoderCli.resolveQoderModelName("glm-5.2", []), "gm51model");
+ try {
+ const result = await qoderCli.validateQoderCliPat({ apiKey: "pt-valid-token" });
+ assert.equal(result.valid, true);
+ assert.match(result.error!, /treating PAT as valid/);
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
});
-test("runQoderCli resolves the request against live --list-models and passes the display name to -m", async () => {
- qoderCli.__clearQoderModelNamesCache();
- const prevBin = process.env.CLI_QODER_BIN;
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "qodercli-stub-"));
- const stub = path.join(dir, "qodercli");
- // --list-models → a live catalog; --print → echo back the -m value it received.
- fs.writeFileSync(
- stub,
- [
- "#!/bin/sh",
- 'case "$*" in',
- ' *--list-models*) printf "MODEL\\nAuto\\nGLM-5.2\\nKimi-K2.7-Code\\n"; exit 0;;',
- "esac",
- 'model=""',
- 'while [ $# -gt 0 ]; do if [ "$1" = "--model" ]; then model="$2"; fi; shift; done',
- "cat >/dev/null",
- 'printf \'{"type":"result","is_error":false,"result":"%s"}\\n\' "$model"',
- "exit 0",
- ].join("\n"),
- { mode: 0o755 }
- );
- process.env.CLI_QODER_BIN = stub;
+test("validateQoderCliPat still rejects a Cosy 500 that carries an explicit auth signal (#2860)", async () => {
+ const originalFetch = globalThis.fetch;
+ globalThis.fetch = async (url) => {
+ if (String(url).includes("/ping")) return new Response("pong", { status: 200 });
+ return new Response(
+ '{"success":false,"msgCode":500,"message":"token invalid or unauthorized"}',
+ { status: 500 }
+ );
+ };
+
try {
- const run = await qoderCli.runQoderCli({
- token: "pt-model-resolve",
- prompt: "hi",
- stream: false,
- model: "glm-5.2",
- });
- assert.equal(run.ok, true);
- // The stub echoed the -m value → proves runQoderCli sent the resolved display name.
- assert.equal(qoderCli.parseQoderCliResult(run.stdout).text, "GLM-5.2");
+ const result = await qoderCli.validateQoderCliPat({ apiKey: "pt-bad-token" });
+ assert.equal(result.valid, false);
+ assert.match(result.error!, /Authentication failed \(HTTP 500\)/);
} finally {
- qoderCli.__clearQoderModelNamesCache();
- if (prevBin === undefined) delete process.env.CLI_QODER_BIN;
- else process.env.CLI_QODER_BIN = prevBin;
- fs.rmSync(dir, { recursive: true, force: true });
+ globalThis.fetch = originalFetch;
}
});
diff --git a/tests/unit/qoder-executor.test.ts b/tests/unit/qoder-executor.test.ts
index bbbdacdb02..18e4a534c4 100644
--- a/tests/unit/qoder-executor.test.ts
+++ b/tests/unit/qoder-executor.test.ts
@@ -1,8 +1,5 @@
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";
import { QoderExecutor } from "../../open-sse/executors/qoder.ts";
import { getQwenCliUserAgent } from "../../open-sse/config/providerHeaderProfiles.ts";
@@ -15,43 +12,6 @@ import {
validateQoderCliPat,
} from "../../open-sse/services/qoderCli.ts";
-/**
- * Write a fake `qodercli` binary and point CLI_QODER_BIN at it. The stub mimics
- * the two invocations OmniRoute makes: `--print --output-format json` (chat) and
- * `--list-models` (validation). It fails auth when the PAT contains "bad" so a
- * single stub covers both the happy and the rejection path. Returns a cleanup fn.
- */
-function withStubQoderCli(fn: () => void | Promise<void>) {
- const prevBin = process.env.CLI_QODER_BIN;
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "qodercli-stub-"));
- const stub = path.join(dir, "qodercli");
- fs.writeFileSync(
- stub,
- [
- "#!/bin/sh",
- 'is_bad() { case "$QODER_PERSONAL_ACCESS_TOKEN" in *bad*) return 0;; *) return 1;; esac; }',
- 'case "$*" in',
- " *--list-models*)",
- ' if is_bad; then echo "Not logged in · Please run /login"; exit 0; fi',
- ' printf "MODEL\\nAuto\\nQwen3-Coder\\n"; exit 0;;',
- " *--print*)",
- " cat >/dev/null;",
- ' if is_bad; then printf \'{"type":"result","subtype":"success","is_error":true,"result":"Not logged in · Please run /login"}\\n\'; exit 0; fi',
- ' printf \'{"type":"result","subtype":"success","is_error":false,"result":"OK from stub"}\\n\'; exit 0;;',
- "esac",
- "exit 0",
- ].join("\n"),
- { mode: 0o755 }
- );
- process.env.CLI_QODER_BIN = stub;
- const restore = () => {
- if (prevBin === undefined) delete process.env.CLI_QODER_BIN;
- else process.env.CLI_QODER_BIN = prevBin;
- fs.rmSync(dir, { recursive: true, force: true });
- };
- return Promise.resolve().then(fn).finally(restore);
-}
-
test("QoderExecutor: constructor sets provider to qoder", () => {
const executor = new QoderExecutor();
assert.equal(executor.getProvider(), "qoder");
@@ -167,32 +127,45 @@ test("parseQoderCliFailure classifies auth, upstream and timeout failures", () =
});
});
-test("validateQoderCliPat succeeds when qodercli lists models for the PAT", async () => {
- await withStubQoderCli(async () => {
- const result = await validateQoderCliPat({ apiKey: "pt-good-token" });
+test("validateQoderCliPat succeeds when the validation endpoint returns OK", async () => {
+ const originalFetch = globalThis.fetch;
+ globalThis.fetch = async (url, options) => {
+ const urlStr = String(url);
+ // Handle ping check
+ if (urlStr.includes("/ping")) {
+ return new Response("pong", { status: 200 });
+ }
+ assert.match(
+ urlStr,
+ /api1\.qoder\.sh\/algo\/api\/v2\/service\/pro\/sse\/agent_chat_generation/
+ );
+ assert.equal(options.method, "POST");
+ assert.match(String(options.headers.Authorization), /^Bearer COSY\./);
+ return new Response("{}", { status: 200 });
+ };
+
+ try {
+ const result = await validateQoderCliPat({ apiKey: "pat_test" });
assert.deepEqual(result, { valid: true, error: null, unsupported: false });
- });
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
});
test("validateQoderCliPat returns auth failures with actionable error", async () => {
- await withStubQoderCli(async () => {
- const result = await validateQoderCliPat({ apiKey: "pt-bad-token" });
- assert.equal(result.valid, false);
- assert.match(result.error, /not authorized|integrations/i);
- assert.equal(result.unsupported, false);
- });
-});
+ const originalFetch = globalThis.fetch;
+ globalThis.fetch = async (url) => {
+ if (String(url).includes("/ping")) return new Response("pong", { status: 200 });
+ return new Response("Invalid API key", { status: 401 });
+ };
-test("validateQoderCliPat reports a clear error when qodercli is missing", async () => {
- const prevBin = process.env.CLI_QODER_BIN;
- process.env.CLI_QODER_BIN = "/nonexistent/qodercli-please-fail";
try {
- const result = await validateQoderCliPat({ apiKey: "pt-good-token" });
+ const result = await validateQoderCliPat({ apiKey: "pat_bad" });
assert.equal(result.valid, false);
- assert.match(result.error, /qodercli|CLI_QODER_BIN|not found/i);
+ assert.match(result.error, /Authentication failed/);
+ assert.equal(result.unsupported, false);
} finally {
- if (prevBin === undefined) delete process.env.CLI_QODER_BIN;
- else process.env.CLI_QODER_BIN = prevBin;
+ globalThis.fetch = originalFetch;
}
});
@@ -211,63 +184,50 @@ test("QoderExecutor: missing tokens return an authentication error response", as
assert.equal(payload.error.code, "token_required");
});
-test("QoderExecutor: non-stream PAT completions route through the local qodercli binary", async () => {
- await withStubQoderCli(async () => {
- const executor = new QoderExecutor();
- const { response, url } = await executor.execute({
- model: "qwen3-coder-plus",
+test("QoderExecutor: non-stream calls target Qoder native API for PAT tokens", async () => {
+ const executor = new QoderExecutor();
+ const originalFetch = globalThis.fetch;
+ globalThis.fetch = async (url, options) => {
+ assert.equal(String(url), "https://api.qoder.com/v1/chat/completions");
+ assert.equal(options.method, "POST");
+ assert.equal(options.headers.Authorization, "Bearer pt-0pUI-test-token");
+ assert.equal(options.headers["x-dashscope-authtype"], undefined);
+ const parsedBody = JSON.parse(String(options.body));
+ assert.equal(parsedBody.model, "qwen3.5-plus");
+ return new Response(
+ JSON.stringify({
+ id: "chatcmpl-qoder",
+ object: "chat.completion",
+ choices: [
+ {
+ index: 0,
+ message: { role: "assistant", content: "OK" },
+ finish_reason: "stop",
+ },
+ ],
+ }),
+ { status: 200, headers: { "Content-Type": "application/json" } }
+ );
+ };
+
+ try {
+ const { response, url, transformedBody } = await executor.execute({
+ model: "qwen3.5-plus",
body: { messages: [{ role: "user", content: "Reply with OK only." }] },
stream: false,
credentials: { apiKey: "pt-0pUI-test-token" },
});
- assert.equal(url, "qodercli://stdio");
+ assert.equal(url, "https://api.qoder.com/v1/chat/completions");
+ assert.equal((transformedBody as any).model, "qwen3.5-plus");
assert.equal(response.status, 200);
- const payload = (await response.json()) as {
- object: string;
- choices: { message: { role: string; content: string } }[];
- };
+ const payload = (await response.json()) as any;
assert.equal(payload.object, "chat.completion");
assert.equal(payload.choices[0].message.role, "assistant");
- assert.equal(payload.choices[0].message.content, "OK from stub");
- });
-});
-
-test("QoderExecutor: streaming PAT completions emit OpenAI-compatible SSE via qodercli", async () => {
- await withStubQoderCli(async () => {
- const executor = new QoderExecutor();
- const { response, url } = await executor.execute({
- model: "qwen3-coder-plus",
- body: { messages: [{ role: "user", content: "Reply with OK only." }] },
- stream: true,
- credentials: { apiKey: "pt-0pUI-test-token" },
- });
-
- assert.equal(url, "qodercli://stdio");
- assert.equal(response.status, 200);
- assert.match(response.headers.get("Content-Type") || "", /text\/event-stream/);
- const body = await response.text();
- assert.match(body, /"content":"OK from stub"/);
- assert.match(body, /"finish_reason":"stop"/);
- assert.match(body, /\[DONE\]/);
- });
-});
-
-test("QoderExecutor: PAT auth failure from qodercli surfaces a 401", async () => {
- await withStubQoderCli(async () => {
- const executor = new QoderExecutor();
- const { response, url } = await executor.execute({
- model: "qwen3-coder-plus",
- body: { messages: [{ role: "user", content: "hi" }] },
- stream: false,
- credentials: { apiKey: "pt-bad-token" },
- });
-
- assert.equal(url, "qodercli://stdio");
- assert.equal(response.status, 401);
- const payload = (await response.json()) as { error: { type: string } };
- assert.equal(payload.error.type, "authentication_error");
- });
+ assert.equal(payload.choices[0].message.content, "OK");
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
});
test("QoderExecutor: non-stream calls target DashScope for non-PAT tokens and map alias models", async () => {
@@ -318,29 +278,63 @@ test("QoderExecutor: non-stream calls target DashScope for non-PAT tokens and ma
}
});
-test("QoderExecutor: PAT completions never touch the (dead) Cosy HTTP endpoints", async () => {
- await withStubQoderCli(async () => {
- const executor = new QoderExecutor();
- const originalFetch = globalThis.fetch;
- let fetchCalls = 0;
- globalThis.fetch = async (...args) => {
- fetchCalls++;
- return originalFetch(...(args as Parameters<typeof fetch>));
- };
- try {
- const { response } = await executor.execute({
- model: "qwen3-coder-plus",
- body: { messages: [{ role: "user", content: "Reply with OK only." }] },
- stream: false,
- credentials: { apiKey: "pt-0pUI-test-token" },
+test("QoderExecutor: PAT token falls back to Cosy auth when Bearer returns 401", async () => {
+ const executor = new QoderExecutor();
+ const originalFetch = globalThis.fetch;
+ let callCount = 0;
+
+ globalThis.fetch = async (url, options) => {
+ callCount++;
+ const u = String(url);
+ if (u === "https://api.qoder.com/v1/chat/completions") {
+ // First call to api.qoder.com returns 401 TOKEN_INVALID
+ assert.equal(options.headers.Authorization, "Bearer pt-0pUI-test-token");
+ return new Response(JSON.stringify({ code: "TOKEN_INVALID", message: "invalid apikey" }), {
+ status: 401,
+ headers: { "Content-Type": "application/json" },
});
- assert.equal(response.status, 200);
- // No HTTP at all: PATs are served entirely by the local qodercli binary.
- assert.equal(fetchCalls, 0);
- } finally {
- globalThis.fetch = originalFetch;
}
- });
+ if (u.includes("/jobToken/exchange")) {
+ // #4683: the PAT is exchanged for a short-lived jt-* job token before the Cosy call.
+ assert.deepEqual(JSON.parse(String(options.body)), { personal_token: "pt-0pUI-test-token" });
+ return new Response(JSON.stringify({ job_token: "jt-from-exchange", expires_in: 86400 }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+ }
+ // Cosy fallback call to api1.qoder.sh returns SSE response
+ assert.ok(u.includes("api1.qoder.sh"));
+ assert.ok(u.includes("agent_chat_generation"));
+ assert.ok(options.headers["Cosy-Key"]);
+ assert.ok(options.headers["Cosy-User"]);
+ assert.ok(options.headers["Cosy-Date"]);
+ assert.ok(options.headers.Authorization.startsWith("Bearer COSY."));
+ return new Response('data: {"message":{"content":"Hello from Cosy"}}\n\ndata: [DONE]\n\n', {
+ status: 200,
+ headers: { "Content-Type": "text/event-stream" },
+ });
+ };
+
+ try {
+ const { response, url } = await executor.execute({
+ model: "qwen3.5-plus",
+ body: { messages: [{ role: "user", content: "Reply with OK only." }] },
+ stream: false,
+ credentials: { apiKey: "pt-0pUI-test-token" },
+ });
+
+ assert.equal(
+ callCount,
+ 3,
+ "Should have made 3 fetch calls (1 Bearer + 1 jobToken exchange + 1 Cosy)"
+ );
+ assert.equal(response.status, 200);
+ const payload = await response.json();
+ assert.equal(payload.object, "chat.completion");
+ assert.equal(payload.choices[0].message.content, "Hello from Cosy");
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
});
test("QoderExecutor: stream calls pass through successful SSE responses", async () => {
diff --git a/tests/unit/qoder-jobtoken-exchange-4683.test.ts b/tests/unit/qoder-jobtoken-exchange-4683.test.ts
index b6468e16cf..c5979807c3 100644
--- a/tests/unit/qoder-jobtoken-exchange-4683.test.ts
+++ b/tests/unit/qoder-jobtoken-exchange-4683.test.ts
@@ -1,8 +1,5 @@
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";
// #4683: Qoder PAT (`pt-*`) chat requests failed with a Cosy 500 because OmniRoute
// injected the raw `pt-*` PAT into the Cosy `security_oauth_token`. The official
@@ -166,39 +163,34 @@ test("#4683 resolveQoderJobToken falls back to the PAT when the exchange fails",
__clearQoderJobTokenCache();
});
-// The jobToken exchange helpers above are retained (and independently unit-tested)
-// but are no longer on the PAT validation path: the Cosy HTTP protocol moved to a
-// WASM-signed envelope that OmniRoute cannot reproduce, so validation now delegates
-// to the local qodercli binary. This test guards that new contract — validation
-// must NOT hit the (dead) jobToken/Cosy HTTP endpoints.
-test("validateQoderCliPat validates via qodercli and makes no Cosy/jobToken HTTP calls", async () => {
+test("#4683 validateQoderCliPat performs the jobToken exchange before the Cosy chat call", async () => {
__clearQoderJobTokenCache();
const originalFetch = globalThis.fetch;
- const prevBin = process.env.CLI_QODER_BIN;
const urls: string[] = [];
// @ts-ignore - test stub
- globalThis.fetch = async (url: string) => {
+ globalThis.fetch = async (url: string, init?: Record<string, unknown>) => {
urls.push(String(url));
- return jsonResponse({ success: true });
+ if (String(url).includes("/ping")) return jsonResponse({ ok: true });
+ if (String(url).includes("/jobToken/exchange")) {
+ assert.deepEqual(JSON.parse(String(init?.body ?? "{}")), { personal_token: "pt-live" });
+ return jsonResponse({ job_token: "jt-live", expires_in: 86400 });
+ }
+ // agent_chat_generation -> accept (valid)
+ return jsonResponse({ success: true }, { ok: true, status: 200 });
};
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "qodercli-stub-"));
- const stub = path.join(dir, "qodercli");
- fs.writeFileSync(stub, '#!/bin/sh\nprintf "MODEL\\nAuto\\n"\nexit 0\n', { mode: 0o755 });
- process.env.CLI_QODER_BIN = stub;
try {
const res = await validateQoderCliPat({ apiKey: "pt-live" });
assert.equal(res.valid, true);
- assert.equal(
- urls.some((u) => u.includes("/jobToken/exchange") || u.includes("agent_chat_generation")),
- false,
- "validation must not call the dead Cosy/jobToken HTTP endpoints"
+ const exchangeIdx = urls.findIndex((u) => u.includes("/jobToken/exchange"));
+ const chatIdx = urls.findIndex((u) => u.includes("agent_chat_generation"));
+ assert.ok(
+ exchangeIdx >= 0,
+ "the PAT->job-token exchange step must run (was skipped before #4683)"
);
+ assert.ok(chatIdx >= 0 && exchangeIdx < chatIdx, "exchange must precede the Cosy chat call");
} finally {
globalThis.fetch = originalFetch;
- if (prevBin === undefined) delete process.env.CLI_QODER_BIN;
- else process.env.CLI_QODER_BIN = prevBin;
- fs.rmSync(dir, { recursive: true, force: true });
__clearQoderJobTokenCache();
}
});
diff --git a/tests/unit/qoder-usage-quota.test.ts b/tests/unit/qoder-usage-quota.test.ts
deleted file mode 100644
index 14666abc11..0000000000
--- a/tests/unit/qoder-usage-quota.test.ts
+++ /dev/null
@@ -1,157 +0,0 @@
-import test from "node:test";
-import assert from "node:assert/strict";
-
-import { USAGE_SUPPORTED_PROVIDERS } from "../../src/shared/constants/providers.ts";
-import { isSupportedUsageConnection } from "../../src/lib/usage/providerLimits.ts";
-import {
- __clearQoderJobTokenCache,
- parseQoderJobTokenResponse,
-} from "../../open-sse/services/qoderCli.ts";
-
-const usageModule = await import("../../open-sse/services/usage.ts");
-const { parseQoderUserStatusUsage } = usageModule.__testing;
-
-// A Teams seat draws from a pooled org quota — `quota: 0` here means "pooled",
-// not "exhausted", so it must render as an unlimited plan entry, not a 0-left one.
-test("parseQoderUserStatusUsage maps a Teams/pooled account to an unlimited plan entry", () => {
- const { plan, quotas } = parseQoderUserStatusUsage({
- userType: "teams",
- userTag: "Teams",
- plan: "PLAN_TIER_TEAM",
- quota: 0,
- isQuotaExceeded: false,
- nextResetAt: 1784736000000,
- });
-
- assert.equal(plan, "Teams");
- assert.deepEqual(Object.keys(quotas), ["Plan"]);
- assert.equal(quotas.Plan.unlimited, true);
- assert.equal(quotas.Plan.remaining, 0);
- assert.match(quotas.Plan.displayName!, /Teams plan · pooled/);
- // nextResetAt (ms) must be surfaced as an ISO reset timestamp.
- assert.equal(quotas.Plan.resetAt, new Date(1784736000000).toISOString());
- // Regression: a pooled/unlimited window MUST report 100% remaining, else the
- // quota→routing conversion (which ignores `unlimited`) treats total:0 as 0%
- // and 429-blocks every request. See src/domain/quotaCache.ts.
- assert.equal(quotas.Plan.remainingPercentage, 100);
-});
-
-test("parseQoderUserStatusUsage maps an individual plan with remaining quota to a Requests entry", () => {
- const { plan, quotas } = parseQoderUserStatusUsage({
- userType: "individual",
- plan: "PLAN_TIER_PRO",
- quota: 42,
- isQuotaExceeded: false,
- nextResetAt: 1784736000000,
- });
-
- // No userTag → prettified from the PLAN_TIER_* enum.
- assert.equal(plan, "Pro");
- assert.deepEqual(Object.keys(quotas), ["Requests"]);
- assert.equal(quotas.Requests.remaining, 42);
- assert.equal(quotas.Requests.total, 42);
- assert.equal(quotas.Requests.unlimited, false);
-});
-
-test("parseQoderUserStatusUsage flags an exceeded quota", () => {
- const { quotas } = parseQoderUserStatusUsage({
- userType: "individual",
- plan: "PLAN_TIER_FREE",
- quota: 100,
- isQuotaExceeded: true,
- nextResetAt: 1784736000000,
- });
-
- assert.deepEqual(Object.keys(quotas), ["Quota"]);
- assert.equal(quotas.Quota.remaining, 0);
- assert.equal(quotas.Quota.unlimited, false);
- assert.match(quotas.Quota.displayName!, /exceeded/i);
-});
-
-test("getUsageForProvider (qoder) exchanges the PAT then reads /user/status", async () => {
- __clearQoderJobTokenCache();
- const originalFetch = globalThis.fetch;
- const calls: string[] = [];
-
- // @ts-ignore — test stub
- globalThis.fetch = async (url: string, init?: Record<string, unknown>) => {
- const u = String(url);
- calls.push(u);
- if (u.includes("/jobToken/exchange")) {
- assert.deepEqual(JSON.parse(String(init?.body ?? "{}")), {
- personal_token: "pt-usage-token",
- });
- return new Response(JSON.stringify({ token: "jt-usage", expires_in: 86400 }), {
- status: 200,
- headers: { "Content-Type": "application/json" },
- });
- }
- // /api/v3/user/status — assert the jt-* is carried, return a Teams payload.
- assert.match(u, /openapi\.qoder\.sh\/api\/v3\/user\/status/);
- assert.equal(
- String((init?.headers as Record<string, string>)?.Authorization),
- "Bearer jt-usage"
- );
- return new Response(
- JSON.stringify({
- userType: "teams",
- userTag: "Teams",
- plan: "PLAN_TIER_TEAM",
- quota: 0,
- isQuotaExceeded: false,
- nextResetAt: 1784736000000,
- }),
- { status: 200, headers: { "Content-Type": "application/json" } }
- );
- };
-
- try {
- const result = (await usageModule.getUsageForProvider({
- provider: "qoder",
- apiKey: "pt-usage-token",
- })) as { plan?: string; quotas?: Record<string, unknown> };
-
- assert.equal(result.plan, "Teams");
- assert.ok(result.quotas && Object.keys(result.quotas).length > 0);
- // The exchange must precede the usage call.
- const exchangeIdx = calls.findIndex((c) => c.includes("/jobToken/exchange"));
- const statusIdx = calls.findIndex((c) => c.includes("/user/status"));
- assert.ok(exchangeIdx >= 0 && statusIdx > exchangeIdx);
- } finally {
- globalThis.fetch = originalFetch;
- __clearQoderJobTokenCache();
- }
-});
-
-test("getUsageForProvider (qoder) without a token returns a friendly message", async () => {
- const result = (await usageModule.getUsageForProvider({ provider: "qoder" })) as {
- message?: string;
- };
- assert.match(result.message ?? "", /Personal Access Token/i);
-});
-
-test("qoder is registered for both the usage fetcher and the quota widget whitelist", () => {
- assert.ok(USAGE_SUPPORTED_PROVIDERS.includes("qoder"));
- assert.ok(usageModule.USAGE_FETCHER_PROVIDERS.includes("qoder"));
-});
-
-// A PAT connection is authType "apikey"; the provider-limits sync only picks up
-// apikey connections whose provider is explicitly allow-listed — guard that qoder
-// is, so the quota widget actually refreshes it (regression for the sync gate).
-test("a qoder PAT (apikey) connection is picked up by the provider-limits sync", () => {
- assert.equal(
- isSupportedUsageConnection({ id: "c1", provider: "qoder", authType: "apikey" }),
- true
- );
- // Sanity: an unrelated apikey provider not on the list is excluded.
- assert.equal(
- isSupportedUsageConnection({ id: "c2", provider: "some-random-provider", authType: "apikey" }),
- false
- );
-});
-
-// Guards the shared exchange contract the usage path relies on.
-test("parseQoderJobTokenResponse reads the exchange token field", () => {
- const parsed = parseQoderJobTokenResponse({ token: "jt-abc", expires_in: 86400 });
- assert.equal(parsed?.jobToken, "jt-abc");
-});
diff --git a/tests/unit/quota-cache-is-exhausted-per-window-5923.test.ts b/tests/unit/quota-cache-is-exhausted-per-window-5923.test.ts
deleted file mode 100644
index e1f1c0cb9b..0000000000
--- a/tests/unit/quota-cache-is-exhausted-per-window-5923.test.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-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";
-
-/**
- * #5923 (Finding #5) — `is_exhausted` on `quota_snapshots` rows was written from
- * the connection-wide aggregate (`entries.every(q => q.remainingPercentage <= 0)`
- * in `isExhausted()`), not from the specific window being persisted.
- *
- * A connection with one window at 0% and another window at 50% never got its
- * 0%-window row flagged `is_exhausted=1`, because the AND-across-all-windows
- * aggregate was false (the 50% window kept it false). The reporter observed
- * ~360 of 274k snapshot rows ever set `is_exhausted=1` in production.
- *
- * Regression guard: `setQuotaCache` must persist `is_exhausted` per-window
- * (`remainingPercentage <= 0` for THAT window), independent of sibling windows
- * on the same connection.
- */
-const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omni-quota-per-window-5923-"));
-process.env.DATA_DIR = TEST_DATA_DIR;
-
-const coreDb = await import("../../src/lib/db/core.ts");
-const quotaSnapshotsDb = await import("../../src/lib/db/quotaSnapshots.ts");
-const quotaCache = await import("../../src/domain/quotaCache.ts");
-
-test.after(() => {
- coreDb.resetDbInstance();
- fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
-});
-
-test("#5923 setQuotaCache writes is_exhausted per-window, not the connection-wide AND aggregate", () => {
- const connectionId = "conn-per-window-5923";
-
- quotaCache.setQuotaCache(connectionId, "anthropic", {
- session: { remainingPercentage: 0, resetAt: null },
- weekly: { remainingPercentage: 50, resetAt: null },
- });
-
- const snapshots = quotaSnapshotsDb.getLatestQuotaSnapshotsForConnection(connectionId);
-
- const sessionRow = snapshots.find((s: any) => (s.windowKey ?? s.window_key) === "session");
- const weeklyRow = snapshots.find((s: any) => (s.windowKey ?? s.window_key) === "weekly");
-
- assert.ok(sessionRow, "expected a persisted row for the session window");
- assert.ok(weeklyRow, "expected a persisted row for the weekly window");
-
- assert.equal(
- (sessionRow as any).isExhausted ?? (sessionRow as any).is_exhausted,
- 1,
- "the 0%-remaining session window must be flagged is_exhausted=1"
- );
- assert.equal(
- (weeklyRow as any).isExhausted ?? (weeklyRow as any).is_exhausted,
- 0,
- "the 50%-remaining weekly window must NOT be flagged is_exhausted (sibling window is exhausted, but this one isn't)"
- );
-});
diff --git a/tests/unit/quota-card-expanded-sort-collapse.test.ts b/tests/unit/quota-card-expanded-sort-collapse.test.ts
deleted file mode 100644
index 823060a304..0000000000
--- a/tests/unit/quota-card-expanded-sort-collapse.test.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-import { test } from "node:test";
-import assert from "node:assert/strict";
-import {
- sortQuotasByRemaining,
- getVisibleQuotas,
-} from "@/app/(dashboard)/dashboard/usage/components/ProviderLimits/parts/QuotaCardExpanded";
-
-function quota(name: string, remainingPercentage: number) {
- return { name, remainingPercentage };
-}
-
-test("sortQuotasByRemaining orders quotas by remaining percentage descending", () => {
- const quotas = [quota("low", 10), quota("high", 90), quota("mid", 50)];
- const sorted = sortQuotasByRemaining(quotas);
- assert.deepEqual(
- sorted.map((q) => q.name),
- ["high", "mid", "low"]
- );
- // original array untouched
- assert.deepEqual(
- quotas.map((q) => q.name),
- ["low", "high", "mid"]
- );
-});
-
-test("sortQuotasByRemaining treats unlimited quotas as 100% remaining", () => {
- const quotas = [quota("capped", 40), { name: "unlimited", unlimited: true }];
- const sorted = sortQuotasByRemaining(quotas);
- assert.equal(sorted[0].name, "unlimited");
-});
-
-test("getVisibleQuotas collapses to the first 3 rows when not expanded", () => {
- const quotas = [1, 2, 3, 4, 5].map((n) => quota(`q${n}`, n));
- const visible = getVisibleQuotas(quotas, false);
- assert.equal(visible.length, 3);
- assert.deepEqual(
- visible.map((q) => q.name),
- ["q1", "q2", "q3"]
- );
-});
-
-test("getVisibleQuotas returns every row when expanded", () => {
- const quotas = [1, 2, 3, 4, 5].map((n) => quota(`q${n}`, n));
- const visible = getVisibleQuotas(quotas, true);
- assert.equal(visible.length, 5);
-});
-
-test("getVisibleQuotas returns all rows unchanged when under the default threshold", () => {
- const quotas = [quota("a", 10), quota("b", 20)];
- const visible = getVisibleQuotas(quotas, false);
- assert.equal(visible.length, 2);
-});
diff --git a/tests/unit/regional-provider-cn-notices-5462.test.ts b/tests/unit/regional-provider-cn-notices-5462.test.ts
deleted file mode 100644
index d9767364d6..0000000000
--- a/tests/unit/regional-provider-cn-notices-5462.test.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import test from "node:test";
-import assert from "node:assert/strict";
-
-// Feature guard for #5462 — geo-restriction notices for CN-registration providers.
-//
-// SenseNova's console appears to require a Chinese (+86) phone number for
-// registration with no documented international path. StepFun's default endpoint
-// (api.stepfun.com) is the China platform, but a genuine Singapore-operated global
-// platform (platform.stepfun.ai) exists — so StepFun's notice must POINT users to
-// the global alternative rather than claim a hard CN-only block.
-const { APIKEY_PROVIDERS_REGIONAL } = await import(
- "../../src/shared/constants/providers/apikey/regional.ts"
-);
-
-function notice(id: string): { text?: string; signupUrl?: string } | undefined {
- const entry = (APIKEY_PROVIDERS_REGIONAL as Record<string, any>)[id];
- assert.ok(entry, `${id} regional provider entry must exist`);
- return entry.notice;
-}
-
-test("#5462 SenseNova carries a CN-phone registration notice with its signup URL", () => {
- const n = notice("sensenova");
- assert.ok(n, "sensenova must have a notice");
- assert.match(n.text ?? "", /\+86|Chinese/i, "notice must mention the Chinese phone requirement");
- assert.equal(n.signupUrl, "https://platform.sensenova.cn/console");
-});
-
-test("#5462 StepFun notice points international users to the global .ai platform", () => {
- const n = notice("stepfun");
- assert.ok(n, "stepfun must have a notice");
- // Must reference the global platform — NOT a blanket CN-only block (a Singapore
- // platform genuinely exists, so a symmetric 'CN-only' warning would be wrong).
- assert.match(n.text ?? "", /stepfun\.ai/i, "notice must point to the global platform");
- assert.equal(n.signupUrl, "https://platform.stepfun.ai");
-});
-
-test("#5462 the notices do not disable the providers (display-only hint)", () => {
- for (const id of ["sensenova", "stepfun"]) {
- const entry = (APIKEY_PROVIDERS_REGIONAL as Record<string, any>)[id];
- assert.equal(entry.hasFree, true, `${id} must stay usable — notice is informational only`);
- assert.equal(entry.id, id);
- }
-});
diff --git a/tests/unit/response-openai-responses-purehelpers-split.test.ts b/tests/unit/response-openai-responses-purehelpers-split.test.ts
deleted file mode 100644
index 7b8485471e..0000000000
--- a/tests/unit/response-openai-responses-purehelpers-split.test.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-import { test } from "node:test";
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { fileURLToPath } from "node:url";
-import { dirname, join } from "node:path";
-
-// Split-guard for the response/openai-responses pure-helper extraction.
-// The stateless helpers (normalizeToolName / stripEmptyOptionalToolArgs /
-// normalizeOutputIndex / normalizeUpstreamFailure / extractResponsesReasoningSummaryText)
-// live in the pure leaf `openai-responses/pureHelpers.ts` (no stream state, no host import).
-// The host imports them back and re-exports normalizeUpstreamFailure for external importers.
-const HERE = dirname(fileURLToPath(import.meta.url));
-const RESP = join(HERE, "../../open-sse/translator/response");
-const HOST = join(RESP, "openai-responses.ts");
-const LEAF = join(RESP, "openai-responses/pureHelpers.ts");
-
-test("leaf hosts the pure helpers, has no stream state and no host import", () => {
- const src = readFileSync(LEAF, "utf8");
- for (const sym of [
- "normalizeToolName",
- "stripEmptyOptionalToolArgs",
- "normalizeOutputIndex",
- "normalizeUpstreamFailure",
- "extractResponsesReasoningSummaryText",
- ]) {
- assert.match(src, new RegExp(`export function ${sym}\\b`));
- }
- assert.doesNotMatch(src, /from "\.\.\/openai-responses\.ts"/);
- // No stream-state parameter leaked into the pure leaf (ignore comments).
- const code = src
- .split("\n")
- .filter((l) => !l.trim().startsWith("//"))
- .join("\n");
- assert.doesNotMatch(code, /\bstate\b/);
-});
-
-test("host imports helpers back and re-exports normalizeUpstreamFailure", () => {
- const src = readFileSync(HOST, "utf8");
- assert.match(src, /from "\.\/openai-responses\/pureHelpers\.ts"/);
- assert.match(
- src,
- /export \{ normalizeUpstreamFailure \} from "\.\/openai-responses\/pureHelpers\.ts"/
- );
-});
-
-test("normalizeUpstreamFailure preserves upstream error semantics", async () => {
- const { normalizeUpstreamFailure } =
- await import("../../open-sse/translator/response/openai-responses/pureHelpers.ts");
- assert.equal(
- normalizeUpstreamFailure({ error: { code: "rate_limit_exceeded", message: "slow down" } })
- .status,
- 429
- );
- assert.equal(
- normalizeUpstreamFailure({ error: { code: "context_length_exceeded", message: "too big" } })
- .status,
- 400
- );
- assert.equal(normalizeUpstreamFailure({ message: "boom" }).status, 502);
-});
diff --git a/tests/unit/responsesanitizer-reasoning-split.test.ts b/tests/unit/responsesanitizer-reasoning-split.test.ts
index 1517d5db3b..3387924dbc 100644
--- a/tests/unit/responsesanitizer-reasoning-split.test.ts
+++ b/tests/unit/responsesanitizer-reasoning-split.test.ts
@@ -22,10 +22,8 @@ import assert from "node:assert/strict";
import {
extractThinkingFromContent,
- isTextualReasoningTagNativeRoute,
shouldParseTextualReasoningTags,
} from "../../open-sse/handlers/responseSanitizer/reasoning.ts";
-import { sanitizeOpenAIResponse } from "../../open-sse/handlers/responseSanitizer.ts";
describe("responseSanitizer/reasoning — extractThinkingFromContent", () => {
it("leaves tag-free content untouched (thinking = null)", () => {
@@ -52,84 +50,6 @@ describe("responseSanitizer/reasoning — shouldParseTextualReasoningTags", () =
});
});
-// ── MiniMax M3 textual reasoning-tag route (9router#2231) ──────────────────────
-//
-// MiniMax M3 leaks raw <think>...</think> into `content` instead of a separate
-// reasoning_content field on the 8 OpenAI-format provider tiers below. The two
-// direct minimax/minimax-cn tiers stay on Anthropic's Messages format
-// (targetFormat: "claude") and already surface reasoning natively — they must
-// stay unaffected.
-describe("responseSanitizer/reasoning — MiniMax M3 textual reasoning-tag route", () => {
- const affectedRoutes: Array<[string, string]> = [
- ["trae", "minimax-m3"],
- ["huggingchat", "minimaxai/minimax-m3"],
- ["bazaarlink", "minimax-m3"],
- ["ollama-cloud", "minimax-m3"],
- ["opencode", "minimax-m3-free"],
- ["cline", "minimax/minimax-m3"],
- ["opencode-zen", "minimax-m3"],
- ["codebuddy-cn", "minimax-m3"],
- ];
-
- for (const [provider, model] of affectedRoutes) {
- it(`isTextualReasoningTagNativeRoute("${provider}", "${model}") === true`, () => {
- assert.equal(isTextualReasoningTagNativeRoute(provider, model), true);
- });
- }
-
- it("shouldParseTextualReasoningTags is true for a mixed-case MiniMax M3 model id (huggingchat)", () => {
- assert.equal(shouldParseTextualReasoningTags("huggingchat", "MiniMaxAI/MiniMax-M3"), true);
- });
-
- it("extracts <think>...</think> from delta.content into reasoning_content on an affected route", () => {
- const chunk = {
- choices: [{ index: 0, delta: { content: "<think>reasoning here</think>final answer" } }],
- };
- const sanitized = sanitizeOpenAIResponse(chunk, {
- parseTextualReasoningTags: shouldParseTextualReasoningTags("trae", "minimax-m3"),
- }) as { choices: Array<{ delta: { content: string; reasoning_content?: string } }> };
-
- const delta = sanitized.choices[0].delta;
- assert.equal(delta.content, "final answer");
- assert.equal(delta.reasoning_content, "reasoning here");
- });
-
- it("leaves <think> tags untouched in content when the route is not tag-native (pre-fix behavior)", () => {
- const chunk = {
- choices: [{ index: 0, delta: { content: "<think>reasoning here</think>final answer" } }],
- };
- const sanitized = sanitizeOpenAIResponse(chunk, {
- parseTextualReasoningTags: shouldParseTextualReasoningTags("openai", "gpt-4"),
- }) as { choices: Array<{ delta: { content: string; reasoning_content?: string } }> };
-
- const delta = sanitized.choices[0].delta;
- assert.equal(delta.content, "<think>reasoning here</think>final answer");
- assert.equal(delta.reasoning_content, undefined);
- });
-});
-
-describe("responseSanitizer/reasoning — MiniMax M3 fix regression guards", () => {
- it("direct minimax tier (claude format) stays unaffected", () => {
- assert.equal(isTextualReasoningTagNativeRoute("minimax", "minimax-m3"), false);
- assert.equal(shouldParseTextualReasoningTags("minimax", "MiniMax-M3"), false);
- });
-
- it("direct minimax-cn tier (claude format) stays unaffected", () => {
- assert.equal(isTextualReasoningTagNativeRoute("minimax-cn", "minimax-m3"), false);
- assert.equal(shouldParseTextualReasoningTags("minimax-cn", "MiniMax-M3"), false);
- });
-
- it("MiniMax M2.x (non-M3) models on OpenAI-format tiers stay unaffected", () => {
- assert.equal(isTextualReasoningTagNativeRoute("trae", "minimax-m2.7"), false);
- });
-
- it("existing deepseek-r1 / qwq textual-reasoning routes are unaffected", () => {
- assert.equal(shouldParseTextualReasoningTags("together", "deepseek-ai/DeepSeek-R1"), true);
- assert.equal(shouldParseTextualReasoningTags("cloudflare-ai", "@cf/qwen/qwq-32b"), true);
- assert.equal(shouldParseTextualReasoningTags("openrouter", "deepseek/deepseek-v4-pro"), false);
- });
-});
-
// ── host public API surface ──────────────────────────────────────────────────
const host = await import("../../open-sse/handlers/responseSanitizer.ts");
diff --git a/tests/unit/route-edge-coverage.test.ts b/tests/unit/route-edge-coverage.test.ts
index 7874aa7941..c66335782c 100644
--- a/tests/unit/route-edge-coverage.test.ts
+++ b/tests/unit/route-edge-coverage.test.ts
@@ -84,13 +84,6 @@ async function seedOpenAIConnection({
errorCode: "refresh_failed",
rateLimitedUntil,
backoffLevel: 2,
- // These embeddings edge-case tests do not exercise proxying. Pin the
- // connection to a direct egress (proxy off) so resolveProxyForConnection
- // returns "direct" regardless of any global/provider proxyConfig the
- // settings-proxy suite left behind in the shared DATA_DIR. Without this,
- // #5975 (embeddings now honor the connection-level proxy) makes the leaked
- // provider.local:8080 fast-fail the upstream with PROXY_UNREACHABLE.
- proxyEnabled: false,
});
}
diff --git a/tests/unit/services/bifrost-route-guard.test.ts b/tests/unit/services/bifrost-route-guard.test.ts
deleted file mode 100644
index 7870f6cf57..0000000000
--- a/tests/unit/services/bifrost-route-guard.test.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import test from "node:test";
-import assert from "node:assert/strict";
-import { isLocalOnlyPath } from "../../../src/server/authz/routeGuard.ts";
-
-test("isLocalOnlyPath: /api/services/bifrost/start is local-only", () => {
- assert.equal(isLocalOnlyPath("/api/services/bifrost/start"), true);
-});
-
-test("isLocalOnlyPath: /api/services/bifrost/install is local-only", () => {
- assert.equal(isLocalOnlyPath("/api/services/bifrost/install"), true);
-});
-
-test("isLocalOnlyPath: /api/services/bifrost/status is local-only", () => {
- assert.equal(isLocalOnlyPath("/api/services/bifrost/status"), true);
-});
-
-test("isLocalOnlyPath: /api/services/bifrost/stop is local-only", () => {
- assert.equal(isLocalOnlyPath("/api/services/bifrost/stop"), true);
-});
-
-test("isLocalOnlyPath: /api/services/bifrost/auto-start is local-only", () => {
- assert.equal(isLocalOnlyPath("/api/services/bifrost/auto-start"), true);
-});
-
-test("isLocalOnlyPath: /api/services/bifrost/logs is local-only", () => {
- assert.equal(isLocalOnlyPath("/api/services/bifrost/logs"), true);
-});
diff --git a/tests/unit/services/bifrost-routing-backend.test.ts b/tests/unit/services/bifrost-routing-backend.test.ts
deleted file mode 100644
index aa5dbe6491..0000000000
--- a/tests/unit/services/bifrost-routing-backend.test.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-/**
- * Unit tests for §4b routing-layer wiring:
- * getBifrostRoutingConfig uses supervised instance port when BIFROST_BASE_URL is unset.
- */
-import test from "node:test";
-import assert from "node:assert/strict";
-import { registerSupervisor, unregisterSupervisor } from "../../../src/lib/services/registry.ts";
-import { ServiceSupervisor } from "../../../src/lib/services/ServiceSupervisor.ts";
-import { getBifrostRoutingConfig } from "../../../src/app/api/v1/relay/chat/completions/routingBackend.ts";
-
-test("getBifrostRoutingConfig: returns null when BIFROST_BASE_URL unset and no supervised service", () => {
- const result = getBifrostRoutingConfig({} as NodeJS.ProcessEnv);
- assert.equal(result, null);
-});
-
-test("getBifrostRoutingConfig: uses BIFROST_BASE_URL when set (explicit env wins)", () => {
- const result = getBifrostRoutingConfig({
- BIFROST_BASE_URL: "http://localhost:9999",
- } as NodeJS.ProcessEnv);
- assert.ok(result !== null);
- assert.equal(result?.baseUrl, "http://localhost:9999");
-});
-
-test("getBifrostRoutingConfig: uses supervised port when BIFROST_BASE_URL unset and bifrost running", () => {
- // Register a stub supervisor whose getStatus() reports running on port 8080
- const stub = {
- getStatus: () => ({
- tool: "bifrost",
- state: "running" as const,
- port: 8080,
- health: "healthy" as const,
- pid: 1234,
- startedAt: new Date().toISOString(),
- lastError: null,
- }),
- } as unknown as ServiceSupervisor;
-
- registerSupervisor(stub);
-
- try {
- const result = getBifrostRoutingConfig({} as NodeJS.ProcessEnv);
- assert.ok(result !== null, "should return config when supervised instance is running");
- assert.equal(result?.baseUrl, "http://127.0.0.1:8080");
- assert.equal(result?.enabled, true);
- } finally {
- unregisterSupervisor("bifrost");
- }
-});
-
-test("getBifrostRoutingConfig: explicit BIFROST_BASE_URL overrides supervised port", () => {
- const stub = {
- getStatus: () => ({
- tool: "bifrost",
- state: "running" as const,
- port: 8080,
- health: "healthy" as const,
- pid: 1234,
- startedAt: new Date().toISOString(),
- lastError: null,
- }),
- } as unknown as ServiceSupervisor;
-
- registerSupervisor(stub);
-
- try {
- const result = getBifrostRoutingConfig({
- BIFROST_BASE_URL: "http://remote-host:9999",
- } as NodeJS.ProcessEnv);
- assert.ok(result !== null);
- // Explicit env wins
- assert.equal(result?.baseUrl, "http://remote-host:9999");
- } finally {
- unregisterSupervisor("bifrost");
- }
-});
-
-test("getBifrostRoutingConfig: stopped supervised instance does NOT provide baseUrl", () => {
- const stub = {
- getStatus: () => ({
- tool: "bifrost",
- state: "stopped" as const,
- port: 8080,
- health: "unknown" as const,
- pid: null,
- startedAt: null,
- lastError: null,
- }),
- } as unknown as ServiceSupervisor;
-
- registerSupervisor(stub);
-
- try {
- const result = getBifrostRoutingConfig({} as NodeJS.ProcessEnv);
- assert.equal(result, null, "stopped supervisor should not yield a baseUrl");
- } finally {
- unregisterSupervisor("bifrost");
- }
-});
diff --git a/tests/unit/services/installers/bifrost.test.ts b/tests/unit/services/installers/bifrost.test.ts
deleted file mode 100644
index 8e20574a68..0000000000
--- a/tests/unit/services/installers/bifrost.test.ts
+++ /dev/null
@@ -1,152 +0,0 @@
-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";
-import { execSync } from "node:child_process";
-
-const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-bifrost-installer-"));
-const FAKE_BIN_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-bifrost-fake-bin-"));
-
-process.env.DATA_DIR = TEST_DATA_DIR;
-process.env.NODE_ENV = "test";
-process.env.DISABLE_SQLITE_AUTO_BACKUP = "true";
-
-const originalPath = process.env.PATH ?? "";
-process.env.PATH = `${FAKE_BIN_DIR}:${originalPath}`;
-
-const INSTALL_DIR = path.join(TEST_DATA_DIR, "services", "bifrost");
-const fakeNpmScript = `#!/bin/sh
-set -e
-CMD="$1"
-shift
-if [ "$CMD" = "install" ]; then
- PREFIX=""
- while [ $# -gt 0 ]; do
- if [ "$1" = "--prefix" ]; then PREFIX="$2"; shift 2; else shift; fi
- done
- if [ -z "$PREFIX" ]; then PREFIX="$npm_config_prefix"; fi
- PKG_DIR="$PREFIX/node_modules/@maximhq/bifrost"
- mkdir -p "$PKG_DIR"
- echo '{"name":"@maximhq/bifrost","version":"1.6.3"}' > "$PKG_DIR/package.json"
- touch "$PKG_DIR/bin.js"
- exit 0
-fi
-if [ "$CMD" = "view" ]; then
- echo "1.6.3"
- exit 0
-fi
-exit 0
-`;
-const fakeNpmPath = path.join(FAKE_BIN_DIR, "npm");
-fs.writeFileSync(fakeNpmPath, fakeNpmScript, { mode: 0o755 });
-
-execSync("which npm", { env: process.env });
-
-// DB bootstrap (must be before bifrost import due to db/core eager init)
-const core = await import("../../../../src/lib/db/core.ts");
-const db = core.getDbInstance();
-db.prepare(
- `INSERT OR IGNORE INTO version_manager (tool, status, port, auto_start, auto_update, provider_expose)
- VALUES ('bifrost', 'not_installed', 8080, 0, 1, 1)`
-).run();
-
-const {
- install,
- update,
- getInstalledVersion,
- getLatestVersion,
- resolveSpawnArgs,
- BIFROST_DEFAULT_PORT,
- BIFROST_INSTALL_DIR,
-} = await import("../../../../src/lib/services/installers/bifrost.ts");
-
-test.after(() => {
- process.env.PATH = originalPath;
- core.resetDbInstance();
- fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
- fs.rmSync(FAKE_BIN_DIR, { recursive: true, force: true });
-});
-
-test("BIFROST_DEFAULT_PORT is 8080", () => {
- assert.equal(BIFROST_DEFAULT_PORT, 8080);
-});
-
-test("install creates host package.json structure", async () => {
- const result = await install("1.6.3");
-
- const hostPkg = path.join(BIFROST_INSTALL_DIR, "package.json");
- assert.ok(fs.existsSync(hostPkg), "host package.json should exist");
- const parsedHost = JSON.parse(fs.readFileSync(hostPkg, "utf8")) as {
- name: string;
- private: boolean;
- };
- assert.equal(parsedHost.name, "omniroute-bifrost-host");
- assert.ok(parsedHost.private);
-
- assert.equal(result.installedVersion, "1.6.3");
- assert.equal(result.installPath, BIFROST_INSTALL_DIR);
- assert.ok(result.durationMs >= 0);
-});
-
-test("getInstalledVersion reads from node_modules/@maximhq/bifrost/package.json", async () => {
- const ver = await getInstalledVersion();
- assert.equal(ver, "1.6.3", "should read version from installed package");
-});
-
-test("update calls npm install with latest (idempotent)", async () => {
- const result = await update();
- assert.equal(result.installedVersion, "1.6.3");
-});
-
-test("getLatestVersion returns version string from npm view", async () => {
- const ver = await getLatestVersion();
- assert.equal(ver, "1.6.3");
-});
-
-test("resolveSpawnArgs shape: command is node, bin.js path, Go single-dash flags", () => {
- const args = resolveSpawnArgs(8080);
-
- assert.equal(args.command, process.execPath, "command must be current node binary");
- assert.ok(args.args[0]?.includes("bin.js"), "args[0] should point to bin.js");
-
- // Go-style single-dash flags
- const portIdx = args.args.indexOf("-port");
- assert.ok(portIdx !== -1, "must have -port flag");
- assert.equal(args.args[portIdx + 1], "8080");
-
- const hostIdx = args.args.indexOf("-host");
- assert.ok(hostIdx !== -1, "must have -host flag");
- assert.equal(args.args[hostIdx + 1], "127.0.0.1");
-
- const appDirIdx = args.args.indexOf("-app-dir");
- assert.ok(appDirIdx !== -1, "must have -app-dir flag");
- assert.ok(args.args[appDirIdx + 1]?.includes("bifrost"), "-app-dir must point into bifrost dir");
-
- const logLevelIdx = args.args.indexOf("-log-level");
- assert.ok(logLevelIdx !== -1, "must have -log-level flag");
- assert.equal(args.args[logLevelIdx + 1], "warn");
-
- // BIFROST_TRANSPORT_VERSION must be set in env
- assert.ok(
- typeof args.env.BIFROST_TRANSPORT_VERSION === "string" &&
- args.env.BIFROST_TRANSPORT_VERSION.length > 0,
- "BIFROST_TRANSPORT_VERSION must be set in env"
- );
-});
-
-test("resolveSpawnArgs with different port passes correct -port value", () => {
- const args = resolveSpawnArgs(9090);
- const portIdx = args.args.indexOf("-port");
- assert.ok(portIdx !== -1);
- assert.equal(args.args[portIdx + 1], "9090");
-});
-
-test("INSTALL_DIR constant points into DATA_DIR/services/bifrost", () => {
- assert.ok(BIFROST_INSTALL_DIR.includes("bifrost"), "install dir must include 'bifrost'");
- assert.ok(
- BIFROST_INSTALL_DIR.startsWith(TEST_DATA_DIR),
- "install dir must be under TEST_DATA_DIR"
- );
- assert.equal(INSTALL_DIR, BIFROST_INSTALL_DIR);
-});
diff --git a/tests/unit/services/installers/mux.test.ts b/tests/unit/services/installers/mux.test.ts
deleted file mode 100644
index 97a2568aa9..0000000000
--- a/tests/unit/services/installers/mux.test.ts
+++ /dev/null
@@ -1,105 +0,0 @@
-/**
- * Mux installer unit tests.
- *
- * All tests are pure-logic: no real file I/O, no network, no DB.
- * resolveSpawnArgs() performs fs.mkdirSync as a side effect (creating
- * MUX_ROOT under DATA_DIR), so — mirroring cliproxy.test.ts — we replicate
- * its pure argument-building contract here instead of invoking the real
- * function, keeping this suite side-effect-free.
- */
-
-import { describe, it } from "node:test";
-import assert from "node:assert/strict";
-import path from "node:path";
-
-// ── exported constants ────────────────────────────────────────────────────────
-
-describe("mux installer — exports", () => {
- it("MUX_DEFAULT_PORT is 8322", async () => {
- const { MUX_DEFAULT_PORT } = await import("../../../../src/lib/services/installers/mux.ts");
- assert.equal(MUX_DEFAULT_PORT, 8322);
- });
-
- it("MUX_PACKAGE is the npm package name 'mux'", async () => {
- const { MUX_PACKAGE } = await import("../../../../src/lib/services/installers/mux.ts");
- assert.equal(MUX_PACKAGE, "mux");
- });
-});
-
-// ── getInstalledVersion ───────────────────────────────────────────────────────
-
-describe("getInstalledVersion", () => {
- it("reads version from node_modules/mux/package.json", () => {
- // Replicates the logic in getInstalledVersion(): reads a JSON file at a
- // DATA_DIR-scoped, non-user-controlled path and pulls out `.version`.
- const fakePkg = JSON.stringify({ name: "mux", version: "0.27.0" });
- const parsed = JSON.parse(fakePkg) as { version?: string };
- assert.equal(parsed.version, "0.27.0");
- });
-});
-
-// ── resolveSpawnArgs (pure argument-building contract) ─────────────────────────
-
-describe("resolveSpawnArgs — argument-building contract", () => {
- const MUX_INSTALL_DIR = path.join("/fake", "services", "mux");
-
- function buildArgs(apiKey: string, port: number) {
- const serverPath = path.join(MUX_INSTALL_DIR, "node_modules", "mux", "dist", "cli", "index.js");
- return {
- command: "node",
- args: [serverPath, "server", "--host", "127.0.0.1", "--port", String(port)],
- env: { MUX_SERVER_AUTH_TOKEN: apiKey },
- cwd: MUX_INSTALL_DIR,
- };
- }
-
- it("binds host to 127.0.0.1 explicitly — never 0.0.0.0", () => {
- const spawnArgs = buildArgs("mx_fake_token", 8322);
- const hostIdx = spawnArgs.args.indexOf("--host");
- assert.ok(hostIdx !== -1);
- assert.equal(spawnArgs.args[hostIdx + 1], "127.0.0.1");
- });
-
- it("passes the port via --port flag as a string", () => {
- const spawnArgs = buildArgs("mx_fake_token", 9001);
- const portIdx = spawnArgs.args.indexOf("--port");
- assert.ok(portIdx !== -1);
- assert.equal(spawnArgs.args[portIdx + 1], "9001");
- });
-
- it("invokes the 'server' subcommand", () => {
- const spawnArgs = buildArgs("mx_fake_token", 8322);
- assert.ok(spawnArgs.args.includes("server"));
- });
-
- it("passes the auth token via MUX_SERVER_AUTH_TOKEN env var, never as an argv entry", () => {
- const token = "mx_super_secret_token_value";
- const spawnArgs = buildArgs(token, 8322);
-
- assert.equal(spawnArgs.env.MUX_SERVER_AUTH_TOKEN, token);
- assert.ok(
- !spawnArgs.args.some((a) => a.includes(token)),
- "token must never appear in argv (would leak via `ps`)"
- );
- });
-
- it("targets the installed server entry point under node_modules/mux/dist/cli", () => {
- const spawnArgs = buildArgs("mx_fake_token", 8322);
- assert.ok(spawnArgs.args[0].endsWith(path.join("dist", "cli", "index.js")));
- assert.ok(spawnArgs.args[0].includes(path.join("node_modules", "mux")));
- });
-});
-
-// ── path safety ───────────────────────────────────────────────────────────────
-
-describe("path safety", () => {
- it("resolveSpawnArgs takes only (apiKey: string, port: number) — no arbitrary path input", () => {
- // resolveSpawnArgs never accepts a user-controlled path; every filesystem
- // path it builds is derived from DATA_DIR + static path segments.
- const port = 8322;
- assert.equal(typeof port, "number", "port must always be a number, not a string");
- const portStr = String(port);
- assert.ok(!portStr.includes("/"), "port string cannot contain path separator");
- assert.ok(!portStr.includes(".."), "port string cannot contain traversal");
- });
-});
diff --git a/tests/unit/settings-ui-layout-static.test.ts b/tests/unit/settings-ui-layout-static.test.ts
index 278b938d12..e9f50ee7a1 100644
--- a/tests/unit/settings-ui-layout-static.test.ts
+++ b/tests/unit/settings-ui-layout-static.test.ts
@@ -59,25 +59,6 @@ test("Debug mode moved to the top of Advanced settings", () => {
assertInOrder(advancedPage, ["<DebugModeCard", "<PayloadRulesTab"]);
});
-test("Log Tool Sources toggle is mounted in Advanced settings next to Debug mode", () => {
- const advancedPage = readSrc("src/app/(dashboard)/dashboard/settings/advanced/page.tsx");
-
- assertInOrder(advancedPage, ["<DebugModeCard", "<LogToolSourcesCard", "<PayloadRulesTab"]);
-
- const card = readSrc(
- "src/app/(dashboard)/dashboard/settings/components/LogToolSourcesCard.tsx"
- );
- assert.match(card, /t\("logToolSourcesToggle"\)/);
- assert.match(card, /t\("logToolSourcesDescription"\)/);
- assert.match(card, /logToolSources: value/);
-
- const schema = readSrc("src/shared/validation/settingsSchemas.ts");
- assert.match(schema, /logToolSources: z\.boolean\(\)\.optional\(\)/);
-
- const en = readSrc("src/i18n/messages/en.json");
- assert.match(en, /"logToolSourcesToggle": "Log Tool Sources"/);
-});
-
test("Proxy Logs table uses the same blue row hover emphasis as Logs", () => {
const proxyLogger = readSrc("src/shared/components/ProxyLogger.tsx");
const requestLogger = readSrc("src/shared/components/RequestLoggerV2.tsx");
diff --git a/tests/unit/shared-api-utils.test.ts b/tests/unit/shared-api-utils.test.ts
index a91e5973cf..56b8f709a0 100644
--- a/tests/unit/shared-api-utils.test.ts
+++ b/tests/unit/shared-api-utils.test.ts
@@ -109,22 +109,3 @@ test("shared api utils throw enriched errors for non-OK responses", async () =>
}
);
});
-
-test("shared api utils throw a clean error for non-JSON non-OK responses", async () => {
- globalThis.fetch = async () =>
- new Response("Bad Gateway", {
- status: 502,
- headers: { "Content-Type": "text/plain" },
- });
-
- await assert.rejects(
- () => get("http://localhost/get"),
- (error) => {
- assert.ok(!(error instanceof SyntaxError), "must not be a raw JSON parse SyntaxError");
- assert.match((error as any).message, /Bad Gateway/);
- assert.equal((error as any).status, 502);
- assert.equal((error as any).data, "Bad Gateway");
- return true;
- }
- );
-});
diff --git a/tests/unit/sidebar-tools-group.test.ts b/tests/unit/sidebar-tools-group.test.ts
index 3a1f145c86..75b66e733b 100644
--- a/tests/unit/sidebar-tools-group.test.ts
+++ b/tests/unit/sidebar-tools-group.test.ts
@@ -25,22 +25,14 @@ function getToolsGroup() {
};
}
-test("TOOLS_GROUP items follow plan 14 order: cli-code → cli-agents → acp-agents → cloud-agents → agent-bridge → traffic-inspector → discovery", () => {
+test("TOOLS_GROUP items follow plan 14 order: cli-code → cli-agents → acp-agents → cloud-agents → agent-bridge → traffic-inspector", () => {
const toolsGroup = getToolsGroup();
const itemIds = toolsGroup.items.map((item) => item.id);
- // cli-code/cli-agents/acp-agents/cloud-agents from plan 14 (#2839); agent-bridge/traffic-inspector from plans 11/12 (#2858); discovery from #5939.
+ // cli-code/cli-agents/acp-agents/cloud-agents from plan 14 (#2839); agent-bridge/traffic-inspector from plans 11/12 (#2858).
assert.deepEqual(
itemIds,
- [
- "cli-code",
- "cli-agents",
- "acp-agents",
- "cloud-agents",
- "agent-bridge",
- "traffic-inspector",
- "discovery",
- ],
- "TOOLS_GROUP items order must be cli-code, cli-agents, acp-agents, cloud-agents, agent-bridge, traffic-inspector, discovery"
+ ["cli-code", "cli-agents", "acp-agents", "cloud-agents", "agent-bridge", "traffic-inspector"],
+ "TOOLS_GROUP items order must be cli-code, cli-agents, acp-agents, cloud-agents, agent-bridge, traffic-inspector"
);
});
diff --git a/tests/unit/sidebar-visibility.test.ts b/tests/unit/sidebar-visibility.test.ts
index 1a5b62c62a..67a40e8170 100644
--- a/tests/unit/sidebar-visibility.test.ts
+++ b/tests/unit/sidebar-visibility.test.ts
@@ -63,7 +63,6 @@ test("primary sidebar items place limits after cache", () => {
"cloud-agents",
"agent-bridge",
"traffic-inspector",
- "discovery",
"api-endpoints",
"webhooks",
"proxy",
diff --git a/tests/unit/suggested-models-route.test.ts b/tests/unit/suggested-models-route.test.ts
deleted file mode 100644
index bca7401838..0000000000
--- a/tests/unit/suggested-models-route.test.ts
+++ /dev/null
@@ -1,169 +0,0 @@
-/**
- * GET /api/v1/providers/suggested-models
- *
- * Behavioral tests: mocks the outbound fetch to the HuggingFace Hub public
- * models API and asserts the route's response shape + error-sanitization
- * behavior (Hard Rule #12 — never leak err.stack/err.message raw).
- */
-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-suggested-models-route-"));
-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 route = await import("../../src/app/api/v1/providers/suggested-models/route.ts");
-
-const originalFetch = globalThis.fetch;
-
-function mockFetchOnce(response: { ok: boolean; status: number; json?: unknown; text?: string }) {
- globalThis.fetch = (async () =>
- ({
- ok: response.ok,
- status: response.status,
- json: async () => response.json,
- text: async () => response.text ?? "",
- }) as unknown as Response) as typeof fetch;
-}
-
-test.afterEach(() => {
- globalThis.fetch = originalFetch;
-});
-
-test.after(() => {
- globalThis.fetch = originalFetch;
- 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("GET suggested-models: returns sorted+shaped suggestions for type=image", async () => {
- mockFetchOnce({
- ok: true,
- status: 200,
- json: [
- { id: "black-forest-labs/FLUX.1-dev", downloads: 50, likes: 900 },
- { id: "stabilityai/stable-diffusion-xl-base-1.0", downloads: 5000, likes: 10 },
- { id: 123 }, // malformed entry — must be dropped, not throw
- ],
- });
-
- const response = await route.GET(
- new Request("http://localhost:20128/api/v1/providers/suggested-models?type=image")
- );
- const body = (await response.json()) as {
- object: string;
- type: string;
- pipeline_tag: string;
- data: Array<{ id: string; downloads: number; likes: number }>;
- };
-
- assert.equal(response.status, 200);
- assert.equal(body.object, "list");
- assert.equal(body.type, "image");
- assert.equal(body.pipeline_tag, "text-to-image");
- assert.equal(body.data.length, 2);
- // sorted descending by downloads (default sortBy)
- assert.equal(body.data[0].id, "stabilityai/stable-diffusion-xl-base-1.0");
- assert.equal(body.data[1].id, "black-forest-labs/FLUX.1-dev");
-});
-
-test("GET suggested-models: respects sortBy=likes and limit", async () => {
- mockFetchOnce({
- ok: true,
- status: 200,
- json: [
- { id: "a/model", downloads: 999, likes: 1 },
- { id: "b/model", downloads: 1, likes: 999 },
- { id: "c/model", downloads: 50, likes: 50 },
- ],
- });
-
- const response = await route.GET(
- new Request(
- "http://localhost:20128/api/v1/providers/suggested-models?type=image&sortBy=likes&limit=2"
- )
- );
- const body = (await response.json()) as { data: Array<{ id: string }> };
-
- assert.equal(response.status, 200);
- assert.equal(body.data.length, 2);
- assert.equal(body.data[0].id, "b/model");
- assert.equal(body.data[1].id, "c/model");
-});
-
-test("GET suggested-models: rejects an unsupported type with a 400 and no stack leak", async () => {
- const response = await route.GET(
- new Request("http://localhost:20128/api/v1/providers/suggested-models?type=video")
- );
- const body = (await response.json()) as { error: { message: string } };
-
- assert.equal(response.status, 400);
- assert.ok(body.error?.message);
- assert.ok(!body.error.message.includes("at "));
- assert.ok(!body.error.message.includes(".ts:"));
-});
-
-test("GET suggested-models: upstream failure surfaces a sanitized 502 (no raw err leak)", async () => {
- mockFetchOnce({ ok: false, status: 503, text: "upstream unavailable" });
-
- const response = await route.GET(
- new Request("http://localhost:20128/api/v1/providers/suggested-models?type=image")
- );
- const body = (await response.json()) as { error: { message: string } };
-
- assert.equal(response.status, 502);
- assert.ok(body.error?.message);
- assert.ok(!body.error.message.includes("at "));
- assert.ok(!body.error.message.includes(process.cwd()));
-});
-
-test("GET suggested-models: a thrown fetch error never leaks err.stack/err.message raw", async () => {
- globalThis.fetch = (async () => {
- const err = new Error(`boom at ${process.cwd()}/secret/internal/path.ts:42:7`);
- throw err;
- }) as typeof fetch;
-
- const response = await route.GET(
- new Request("http://localhost:20128/api/v1/providers/suggested-models?type=image")
- );
- const body = (await response.json()) as { error: { message: string } };
-
- assert.equal(response.status, 502);
- assert.ok(body.error?.message);
- assert.ok(!body.error.message.includes(process.cwd()));
- assert.ok(!body.error.message.includes("<path>".repeat(0)) || true);
- // sanitizeErrorMessage replaces absolute paths with "<path>"
- assert.ok(!/\/secret\/internal\/path\.ts/.test(body.error.message));
-});
-
-test("route source: imports and uses buildErrorBody (Hard Rule #12)", async () => {
- const src = fs.readFileSync(
- path.join(process.cwd(), "src/app/api/v1/providers/suggested-models/route.ts"),
- "utf8"
- );
- assert.match(
- src,
- /import \{[^}]*buildErrorBody[^}]*\} from ["']@omniroute\/open-sse\/utils\/error(\.ts)?["']/,
- "must import buildErrorBody from @omniroute/open-sse/utils/error"
- );
- assert.match(src, /buildErrorBody\s*\(/, "must call buildErrorBody() in error responses");
-
- // Static guard: no raw err.message / err.stack in a response-building line
- const lines = src.split("\n");
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i];
- if (/console\.(error|warn|log|debug|info)/.test(line)) continue;
- if (/err\.stack/.test(line) && /NextResponse\.json|return.*json\(/.test(line)) {
- assert.fail(`line ${i + 1}: raw err.stack found in response body:\n ${line.trim()}`);
- }
- }
-});
diff --git a/tests/unit/sumopod-x5lab-provider.test.ts b/tests/unit/sumopod-x5lab-provider.test.ts
deleted file mode 100644
index e539726273..0000000000
--- a/tests/unit/sumopod-x5lab-provider.test.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import test from "node:test";
-import assert from "node:assert/strict";
-
-const { APIKEY_PROVIDERS } = await import("../../src/shared/constants/providers.ts");
-const { PROVIDER_ENDPOINTS } = await import("../../src/shared/constants/config.ts");
-const { REGISTRY: providerRegistry } = await import("../../open-sse/config/providerRegistry.ts");
-
-const SUMOPOD_CHAT_URL = "https://ai.sumopod.com/v1/chat/completions";
-const SUMOPOD_MODELS_URL = "https://ai.sumopod.com/v1/models";
-
-const X5LAB_CHAT_URL = "https://api.x5lab.dev/v1/chat/completions";
-const X5LAB_MODELS_URL = "https://api.x5lab.dev/v1/models";
-
-test("SumoPod is registered as an OpenAI-compatible API-key gateway", () => {
- const entry = APIKEY_PROVIDERS.sumopod;
- assert.ok(entry, "APIKEY_PROVIDERS.sumopod must be defined");
- assert.equal(entry.id, "sumopod");
- assert.equal(entry.alias, "sumopod");
- assert.equal(entry.name, "SumoPod");
- assert.equal(entry.website, "https://ai.sumopod.com");
- assert.equal(entry.passthroughModels, true);
-});
-
-test("X5Lab is registered as an OpenAI-compatible API-key gateway", () => {
- const entry = APIKEY_PROVIDERS.x5lab;
- assert.ok(entry, "APIKEY_PROVIDERS.x5lab must be defined");
- assert.equal(entry.id, "x5lab");
- assert.equal(entry.alias, "x5lab");
- assert.equal(entry.name, "X5Lab");
- assert.equal(entry.website, "https://x5lab.dev");
- assert.equal(entry.passthroughModels, true);
-});
-
-test("SumoPod exposes the OpenAI-compatible chat completions endpoint", () => {
- assert.equal(PROVIDER_ENDPOINTS.sumopod, SUMOPOD_CHAT_URL);
-});
-
-test("X5Lab exposes the OpenAI-compatible chat completions endpoint", () => {
- assert.equal(PROVIDER_ENDPOINTS.x5lab, X5LAB_CHAT_URL);
-});
-
-test("SumoPod registry entry uses OpenAI format with bearer API-key auth and passthrough models", () => {
- const entry = providerRegistry.sumopod;
- assert.ok(entry, "providerRegistry.sumopod must be defined");
- assert.equal(entry.id, "sumopod");
- assert.equal(entry.alias, "sumopod");
- assert.equal(entry.format, "openai");
- assert.equal(entry.executor, "default");
- assert.equal(entry.authType, "apikey");
- assert.equal(entry.authHeader, "bearer");
- assert.equal(entry.baseUrl, SUMOPOD_CHAT_URL);
- assert.equal(entry.modelsUrl, SUMOPOD_MODELS_URL);
- assert.equal(entry.passthroughModels, true);
- assert.deepEqual(entry.models, [], "SumoPod ships no speculative seeded models — passthrough only");
-});
-
-test("X5Lab registry entry uses OpenAI format with bearer API-key auth and passthrough models", () => {
- const entry = providerRegistry.x5lab;
- assert.ok(entry, "providerRegistry.x5lab must be defined");
- assert.equal(entry.id, "x5lab");
- assert.equal(entry.alias, "x5lab");
- assert.equal(entry.format, "openai");
- assert.equal(entry.executor, "default");
- assert.equal(entry.authType, "apikey");
- assert.equal(entry.authHeader, "bearer");
- assert.equal(entry.baseUrl, X5LAB_CHAT_URL);
- assert.equal(entry.modelsUrl, X5LAB_MODELS_URL);
- assert.equal(entry.passthroughModels, true);
- assert.deepEqual(entry.models, [], "X5Lab ships no speculative seeded models — passthrough only");
-});
diff --git a/tests/unit/theoldllm-model-refresh-5181.test.ts b/tests/unit/theoldllm-model-refresh-5181.test.ts
deleted file mode 100644
index f41003268e..0000000000
--- a/tests/unit/theoldllm-model-refresh-5181.test.ts
+++ /dev/null
@@ -1,90 +0,0 @@
-import test from "node:test";
-import assert from "node:assert/strict";
-
-// Feature guard for #5181 — "Update The Old LLM (Free) model list".
-//
-// Two things this proves, both of which fail on the pre-#5181 code:
-// 1. mapModel() now passes KNOWN upstream IDs through UNCHANGED. Before the fix,
-// any non-GPT/Claude id (Gemini, o-series, Grok, DeepSeek, Sonar) fell through
-// to the `return "GPT_5_4"` default and silently misrouted every request.
-// 2. The registry catalog is refreshed with the current free-tier models while
-// keeping the legacy alias IDs for saved-preference backward compatibility.
-const { mapModel, CHATGPT_UPSTREAM_MODELS } = await import(
- "../../open-sse/executors/theoldllm.ts"
-);
-const { getRegistryEntry } = await import("../../open-sse/config/providerRegistry.ts");
-
-function catalogIds(): string[] {
- const entry = getRegistryEntry("theoldllm");
- assert.ok(entry, "theoldllm registry entry must exist");
- return (entry.models ?? []).map((m) => m.id);
-}
-
-test("#5181 known upstream IDs pass through mapModel unchanged (Gemini no longer misroutes to GPT_5_4)", () => {
- // These are the exact cases the old default clause broke.
- assert.equal(mapModel("gemini_3_pro"), "gemini_3_pro");
- assert.equal(mapModel("gemini_2_5_pro"), "gemini_2_5_pro");
- assert.equal(mapModel("gemini_2_0_flash"), "gemini_2_0_flash");
- assert.equal(mapModel("openrouter_grok_4"), "openrouter_grok_4");
- assert.equal(mapModel("together_deepseek_v3"), "together_deepseek_v3");
- assert.equal(mapModel("sonar-pro"), "sonar-pro");
- assert.equal(mapModel("GPT_o4_mini"), "GPT_o4_mini");
- // Every declared upstream id must round-trip through mapModel unchanged.
- for (const id of CHATGPT_UPSTREAM_MODELS) {
- assert.equal(mapModel(id), id, `${id} must route unchanged`);
- }
-});
-
-test("#5181 legacy alias IDs still map to available upstream models (backward compatibility)", () => {
- assert.equal(mapModel("claude_opus_4"), "CLAUDE_4_6_OPUS");
- assert.equal(mapModel("claude_sonnet_4"), "CLAUDE_4_6_SONNET");
- assert.equal(mapModel("claude_haiku_3_5"), "CLAUDE_4_5_HAIKU");
- assert.equal(mapModel("gpt-5.4"), "GPT_5_4");
- assert.equal(mapModel("gpt-4o"), "GPT_4O");
-});
-
-test("#5181 catalog is refreshed with the current free-tier models", () => {
- const ids = catalogIds();
- for (const id of [
- "GPT_5_3",
- "GPT_5_2",
- "GPT_5_1",
- "GPT_5",
- "GPT_o4_mini",
- "GPT_o3_mini",
- "gemini_2_5_pro",
- "gemini_2_0_flash",
- "gemini_1_5_flash",
- "CLAUDE_4_6_OPUS",
- "CLAUDE_4_6_SONNET",
- "CLAUDE_4_5_HAIKU",
- "openrouter_grok_4",
- "sonar-pro",
- ]) {
- assert.ok(ids.includes(id), `catalog must include refreshed model ${id}`);
- }
-});
-
-test("#5181 legacy catalog entries are preserved (no breaking removal of saved-preference IDs)", () => {
- const ids = catalogIds();
- for (const id of ["GPT_5_4", "GPT_4o", "claude_opus_4", "gemini_3_pro"]) {
- assert.ok(ids.includes(id), `legacy catalog id ${id} must be preserved`);
- }
-});
-
-test("#5181 every refreshed catalog id routes to a valid upstream model", () => {
- // No catalog id may fall through to the GPT_5_4 default unless it is genuinely a
- // GPT-5 alias — Gemini/Grok/DeepSeek/Sonar/Claude entries must resolve to their
- // own upstream id, not silently collapse onto GPT_5_4.
- const nonGptExpectations: Record<string, string> = {
- gemini_2_5_pro: "gemini_2_5_pro",
- gemini_2_0_flash: "gemini_2_0_flash",
- gemini_1_5_flash: "gemini_1_5_flash",
- CLAUDE_4_6_OPUS: "CLAUDE_4_6_OPUS",
- openrouter_grok_4: "openrouter_grok_4",
- "sonar-pro": "sonar-pro",
- };
- for (const [id, expected] of Object.entries(nonGptExpectations)) {
- assert.equal(mapModel(id), expected);
- }
-});
diff --git a/tests/unit/translator-antigravity-to-openai.test.ts b/tests/unit/translator-antigravity-to-openai.test.ts
index 1463538c6d..6012b0bb9a 100644
--- a/tests/unit/translator-antigravity-to-openai.test.ts
+++ b/tests/unit/translator-antigravity-to-openai.test.ts
@@ -121,11 +121,7 @@ test("Antigravity -> OpenAI extracts string system instructions and text-only me
]);
});
-test("Antigravity -> OpenAI strips a lone function response with no matching function call (#6026)", () => {
- // A `functionResponse` with no preceding `functionCall` is an orphan tool_result. Left in
- // place it becomes an orphan `tool_result` block after the openai→claude step, which
- // Anthropic (Vertex claude-opus-4.6) rejects with HTTP 400 (#6026). `fixToolPairs` now
- // strips it at the antigravity assembly point, so the upstream request stays valid.
+test("Antigravity -> OpenAI returns tool messages when content contains only function responses", () => {
const result = antigravityToOpenAIRequest(
"gpt-4o",
{
@@ -149,74 +145,11 @@ test("Antigravity -> OpenAI strips a lone function response with no matching fun
false
);
- assert.deepEqual(result.messages, []);
-});
-
-test("Antigravity -> OpenAI keeps co-located function call and text but strips the orphan function response (#6026)", () => {
- const result = antigravityToOpenAIRequest(
- "gpt-4o",
- {
- request: {
- contents: [
- {
- role: "model",
- parts: [
- { text: "Let me look that up." },
- { functionResponse: { id: "call_9", name: "lookup", response: { result: { ok: true } } } },
- { functionCall: { id: "call_10", name: "lookup", args: { q: "weather" } } },
- ],
- },
- ],
- },
- },
- false
- );
-
- // The accompanying assistant message (text + tool_call) survives, but the co-located
- // function response `call_9` has no matching function call, so it is an orphan tool_result
- // and must be stripped (#6026) — otherwise Anthropic 400s on the openai→claude request.
- const toolMsg = result.messages.find((m) => m.role === "tool");
- const assistantMsg = result.messages.find((m) => m.role === "assistant");
- assert.equal(toolMsg, undefined, "orphan function-response tool message must be stripped");
- assert.ok(assistantMsg, "expected a role:assistant message");
- assert.equal(assistantMsg.content, "Let me look that up.");
- assert.deepEqual(assistantMsg.tool_calls, [
- {
- id: "call_10",
- type: "function",
- function: { name: "lookup", arguments: '{"q":"weather"}' },
- },
- ]);
-});
-
-test("Antigravity -> OpenAI drops empty thoughtSignature text instead of emitting empty content", () => {
- const result = antigravityToOpenAIRequest(
- "gpt-4o",
- {
- request: {
- contents: [
- {
- role: "model",
- parts: [
- { thoughtSignature: "sig", text: "" },
- { functionCall: { id: "call_11", name: "noop", args: {} } },
- ],
- },
- ],
- },
- },
- false
- );
-
- const assistantMsg = result.messages.find((m) => m.role === "assistant");
- assert.ok(assistantMsg, "expected a role:assistant message");
- // No empty content block should be emitted (Anthropic rejects it with a 400).
- assert.equal("content" in assistantMsg, false);
- assert.deepEqual(assistantMsg.tool_calls, [
+ assert.deepEqual(result.messages, [
{
- id: "call_11",
- type: "function",
- function: { name: "noop", arguments: "{}" },
+ role: "tool",
+ tool_call_id: "call_2",
+ content: '{"ok":true}',
},
]);
});
diff --git a/tests/unit/translator-openai-responses-req.test.ts b/tests/unit/translator-openai-responses-req.test.ts
index 87e5c97f43..705ff6c38f 100644
--- a/tests/unit/translator-openai-responses-req.test.ts
+++ b/tests/unit/translator-openai-responses-req.test.ts
@@ -393,81 +393,6 @@ test("Chat -> Responses converts messages, tool calls, tool outputs, tools and p
assert.equal((result as any).top_p, 0.9);
});
-test("Chat -> Responses converts json_schema response_format to text.format", () => {
- const schema = {
- type: "object",
- additionalProperties: false,
- properties: { answer: { type: "string" } },
- required: ["answer"],
- };
-
- const result = openaiToOpenAIResponsesRequest(
- "gpt-5.2-codex",
- {
- messages: [{ role: "user", content: "Return the answer as JSON" }],
- response_format: {
- type: "json_schema",
- json_schema: {
- name: "answer_schema",
- description: "A structured answer",
- strict: true,
- schema,
- },
- },
- },
- false,
- null
- ) as any;
-
- assert.deepEqual(result.text, {
- format: {
- type: "json_schema",
- name: "answer_schema",
- description: "A structured answer",
- strict: true,
- schema,
- },
- });
- assert.equal(result.response_format, undefined);
-});
-
-test("Chat -> Responses uses response_format over nonstandard chat text.format", () => {
- const result = openaiToOpenAIResponsesRequest(
- "gpt-5.2-codex",
- {
- messages: [{ role: "user", content: "Return JSON" }],
- text: {
- format: { type: "json_schema", name: "nonstandard", schema: { type: "object" } },
- verbosity: "low",
- },
- response_format: {
- type: "json_schema",
- json_schema: { name: "chat", schema: { type: "object", properties: {} } },
- },
- },
- false,
- null
- ) as any;
-
- assert.deepEqual(result.text, {
- format: { type: "json_schema", name: "chat", schema: { type: "object", properties: {} } },
- });
-});
-
-test("Chat -> Responses ignores nonstandard chat text.format without response_format", () => {
- const result = openaiToOpenAIResponsesRequest(
- "gpt-5.2-codex",
- {
- messages: [{ role: "user", content: "Return JSON" }],
- text: { format: { type: "json_schema", name: "nonstandard", schema: { type: "object" } } },
- },
- false,
- null
- ) as any;
-
- assert.equal(result.text, undefined);
-});
-
test("Responses round-trip preserves store and previous_response_id when opt-in is enabled", () => {
const credentials = {
providerSpecificData: {
diff --git a/tests/unit/translator-openai-to-claude.test.ts b/tests/unit/translator-openai-to-claude.test.ts
index 70c3f1a4f2..5754707216 100644
--- a/tests/unit/translator-openai-to-claude.test.ts
+++ b/tests/unit/translator-openai-to-claude.test.ts
@@ -114,11 +114,6 @@ test("OpenAI -> Claude converts multimodal content, tool declarations, tool call
const result = openaiToClaudeRequest(
"claude-4-sonnet",
{
- // #5945: the redacted_thinking precursor is only emitted when the outbound
- // request actually has extended thinking enabled (Anthropic's schema
- // requirement). Set it explicitly so this test keeps exercising that
- // legitimate #5312 case alongside the multimodal/tool assertions below.
- thinking: { type: "enabled", budget_tokens: 4096 },
messages: [
{
role: "user",
diff --git a/tests/unit/translator-openai-to-kiro.test.ts b/tests/unit/translator-openai-to-kiro.test.ts
index 9d74a3e20e..9ef079d8a2 100644
--- a/tests/unit/translator-openai-to-kiro.test.ts
+++ b/tests/unit/translator-openai-to-kiro.test.ts
@@ -81,9 +81,7 @@ test("OpenAI -> Kiro preserves prior history, tool uses and accumulated tool res
assert.equal(result.conversationState.history.length, 2);
assert.deepEqual(result.conversationState.history[0], {
userInputMessage: {
- // #2306: the system prompt ("Rules") is wrapped in <system-reminder> before
- // being merged into the Kiro user turn, instead of leaking as raw user text.
- content: "<system-reminder>\nRules\n</system-reminder>\n\nHello",
+ content: "Rules\n\nHello",
modelId: "claude-sonnet-4",
origin: "AI_EDITOR",
},
@@ -235,11 +233,11 @@ test("OpenAI -> Kiro derives a stable conversationId for the same first history
assert.equal(
(first.conversationState as any).history[0].userInputMessage.content,
- "<system-reminder>\nRules\n</system-reminder>\n\nHello"
+ "Rules\n\nHello"
);
assert.equal(
(second as any).conversationState.history[0].userInputMessage.content,
- "<system-reminder>\nRules\n</system-reminder>\n\nHello"
+ "Rules\n\nHello"
);
assert.equal(first.conversationState.conversationId, second.conversationState.conversationId);
});
@@ -293,10 +291,7 @@ test("OpenAI -> Kiro merges adjacent user history turns after role normalization
const firstUser = history[0].userInputMessage;
assert.ok(firstUser, "first history turn should be a user turn");
- assert.equal(
- firstUser.content,
- "<system-reminder>\nSystem rules\n</system-reminder>\n\nFirst question"
- );
+ assert.equal(firstUser.content, "System rules\n\nFirst question");
assert.equal(history[1].assistantResponseMessage?.content, "Answer 1");
});
diff --git a/tests/unit/ui/ClaudeClassifierCompatToggle.test.tsx b/tests/unit/ui/ClaudeClassifierCompatToggle.test.tsx
deleted file mode 100644
index 1ff956d4fd..0000000000
--- a/tests/unit/ui/ClaudeClassifierCompatToggle.test.tsx
+++ /dev/null
@@ -1,87 +0,0 @@
-// @vitest-environment jsdom
-//
-// UI test for the opt-in Claude Code auto-permission classifier compat toggle.
-// Verifies it reads the current mode from GET /api/settings, renders "off" by
-// default, and cycles off → auto → always by PATCHing /api/settings.
-import React from "react";
-import { act } from "react";
-import { createRoot } from "react-dom/client";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-let currentMode = "off";
-const patchBodies: Array<Record<string, unknown>> = [];
-
-beforeEach(() => {
- currentMode = "off";
- patchBodies.length = 0;
- (
- globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }
- ).IS_REACT_ACT_ENVIRONMENT = true;
- globalThis.fetch = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
- const url = typeof input === "string" ? input : input.toString();
- if (url.includes("/api/settings")) {
- if (init?.method === "PATCH") {
- const body = JSON.parse(String(init.body)) as Record<string, unknown>;
- patchBodies.push(body);
- currentMode = String(body.claudeClassifierCompat);
- return new Response(JSON.stringify({ claudeClassifierCompat: currentMode }), {
- status: 200,
- });
- }
- return new Response(JSON.stringify({ claudeClassifierCompat: currentMode }), { status: 200 });
- }
- return new Response("{}", { status: 200 });
- }) as unknown as typeof fetch;
-});
-
-const containers: HTMLElement[] = [];
-
-afterEach(() => {
- while (containers.length > 0) {
- containers.pop()?.remove();
- }
- document.body.innerHTML = "";
- vi.restoreAllMocks();
-});
-
-const { default: ClaudeClassifierCompatToggle } = await import(
- "@/app/(dashboard)/dashboard/cli-code/components/ClaudeClassifierCompatToggle"
-);
-
-async function renderToggle() {
- const container = document.createElement("div");
- document.body.appendChild(container);
- containers.push(container);
- const root = createRoot(container);
- await act(async () => {
- root.render(<ClaudeClassifierCompatToggle />);
- });
- await act(async () => {
- await Promise.resolve();
- await Promise.resolve();
- });
- return container;
-}
-
-describe("ClaudeClassifierCompatToggle", () => {
- it("renders the current mode (off by default)", async () => {
- const container = await renderToggle();
- const btn = container.querySelector("button");
- expect(btn).toBeTruthy();
- expect((btn!.textContent ?? "").trim().toLowerCase()).toBe("off");
- });
-
- it("cycles off → auto on click and PATCHes /api/settings", async () => {
- const container = await renderToggle();
- const btn = container.querySelector("button")!;
- await act(async () => {
- btn.click();
- });
- await act(async () => {
- await Promise.resolve();
- });
- expect(patchBodies).toHaveLength(1);
- expect(patchBodies[0].claudeClassifierCompat).toBe("auto");
- expect((btn.textContent ?? "").trim().toLowerCase()).toBe("auto");
- });
-});
diff --git a/tests/unit/ui/ProviderIcon-icon-url.test.tsx b/tests/unit/ui/ProviderIcon-icon-url.test.tsx
deleted file mode 100644
index 19977c1455..0000000000
--- a/tests/unit/ui/ProviderIcon-icon-url.test.tsx
+++ /dev/null
@@ -1,110 +0,0 @@
-// @vitest-environment jsdom
-// #2166 — ProviderIcon custom remote icon URL (`src` prop) support.
-import React from "react";
-import { act } from "react";
-import { createRoot } from "react-dom/client";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-// ── Mocks ─────────────────────────────────────────────────────────────────────
-
-vi.mock("next/image", () => ({
- default: (props: Record<string, unknown>) => {
- const { onError, alt, ...rest } = props as { onError?: () => void; alt?: string } & Record<
- string,
- unknown
- >;
- // eslint-disable-next-line @next/next/no-img-element -- test double for next/image
- return <img data-testid="next-image" alt={alt || ""} onError={onError} {...rest} />;
- },
-}));
-
-const { default: ProviderIcon } = await import("@/shared/components/ProviderIcon");
-
-// ── Helpers ───────────────────────────────────────────────────────────────────
-
-// Deliberately not registered in @lobehub/icons aliases or the KNOWN_PNGS/KNOWN_SVGS
-// static-asset sets, so tests exercise only the `src` override + generic-icon fallback
-// paths, never the @lobehub/static resolution chain.
-const UNKNOWN_PROVIDER_ID = "openai-compatible-test-node-xyz";
-
-const containers: HTMLElement[] = [];
-
-function renderIcon(props: Record<string, unknown>): HTMLElement {
- const container = document.createElement("div");
- document.body.appendChild(container);
- containers.push(container);
-
- const root = createRoot(container);
- act(() => {
- root.render(<ProviderIcon providerId={UNKNOWN_PROVIDER_ID} {...props} />);
- });
- return container;
-}
-
-function fireImgError(container: HTMLElement) {
- const img = container.querySelector("img");
- if (!img) throw new Error("expected an <img> element to fire error on");
- act(() => {
- img.dispatchEvent(new Event("error"));
- });
-}
-
-beforeEach(() => {
- (globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT =
- true;
-});
-
-afterEach(() => {
- while (containers.length > 0) {
- containers.pop()?.remove();
- }
- document.body.innerHTML = "";
-});
-
-// ── Tests ─────────────────────────────────────────────────────────────────────
-
-describe("ProviderIcon — custom remote icon URL (#2166)", () => {
- it("renders an <img> with the given src when `src` is set", () => {
- const container = renderIcon({ src: "https://example.com/logo.png", size: 32 });
- const img = container.querySelector("img");
- expect(img).not.toBeNull();
- expect(img?.getAttribute("src")).toBe("https://example.com/logo.png");
- });
-
- it("falls back to the generic icon when `src` is unset", () => {
- const container = renderIcon({});
- expect(container.querySelector("img")).toBeNull();
- expect(container.querySelector("svg")).not.toBeNull();
- });
-
- it("falls back to the generic (lobehub/static) icon chain when `src` load fails and no fallbackText is given", () => {
- const container = renderIcon({ src: "https://example.com/broken.png" });
- expect(container.querySelector("img")).not.toBeNull();
-
- fireImgError(container);
-
- expect(container.querySelector("img")).toBeNull();
- expect(container.querySelector("svg")).not.toBeNull();
- });
-
- it("falls back to a text badge when `src` load fails and fallbackText is given", () => {
- const container = renderIcon({
- src: "https://example.com/broken.png",
- fallbackText: "OC",
- fallbackColor: "#10A37F",
- });
- expect(container.querySelector("img")).not.toBeNull();
-
- fireImgError(container);
-
- expect(container.querySelector("img")).toBeNull();
- expect(container.querySelector("svg")).toBeNull();
- expect(container.textContent).toBe("OC");
- });
-
- it("ignores a whitespace-only src and falls back to the generic icon", () => {
- const container = renderIcon({ src: " " });
- expect(container.querySelector("img")).toBeNull();
- expect(container.querySelector("svg")).not.toBeNull();
- });
-});
diff --git a/tests/unit/ui/authz-cors-banner.test.tsx b/tests/unit/ui/authz-cors-banner.test.tsx
deleted file mode 100644
index 8b9b2c2d1f..0000000000
--- a/tests/unit/ui/authz-cors-banner.test.tsx
+++ /dev/null
@@ -1,104 +0,0 @@
-// @vitest-environment jsdom
-/**
- * UI unit test for the AuthzSection wildcard-CORS banner (#5602).
- *
- * The banner must appear when `/api/settings/authz-inventory` reports
- * `cors.allowAll === true` (i.e. `CORS_ALLOW_ALL=true` at runtime) and stay
- * hidden otherwise. It is the only runtime signal a wildcard-CORS
- * misconfiguration is live. See docs/security/CORS.md.
- */
-import React from "react";
-import { act } from "react";
-import { createRoot } from "react-dom/client";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-// Stable identity fn — the real next-intl `t` is memoized per render. A fresh
-// closure each render would flip AuthzSection's `useCallback([t])` dep and loop
-// its mount fetch forever, so we return the SAME reference every call.
-const translate = (key: string) => key;
-vi.mock("next-intl", () => ({
- useTranslations: () => translate,
-}));
-
-// Import the (heavy) dashboard component ONCE at module load rather than inside every
-// render call. The dynamic import pulls the whole settings-page dependency graph through
-// esbuild on first use (~20s cold); doing it per-test made the first test tip over the
-// 30s per-test timeout while the second (warm, cached) passed. Hoisting moves that cost to
-// module-eval time (outside any per-test timeout) and keeps each test body fast.
-const AuthzSection = (
- await import("../../../src/app/(dashboard)/dashboard/settings/components/AuthzSection")
-).default;
-
-const cleanupCallbacks: Array<() => void> = [];
-
-function makeContainer(): HTMLElement {
- const container = document.createElement("div");
- document.body.appendChild(container);
- cleanupCallbacks.push(() => container.remove());
- return container;
-}
-
-function inventoryPayload(cors: { allowAll: boolean; allowedOrigins: string[] }) {
- return {
- tiers: [
- {
- name: "PUBLIC",
- prefixes: ["/api/health"],
- description: "public",
- bypassable: false,
- },
- ],
- bypassEnabled: true,
- bypassPrefixes: ["/api/mcp/"],
- spawnCapablePrefixes: ["/api/cli-tools/runtime/"],
- cors,
- };
-}
-
-function mockInventoryFetch(cors: { allowAll: boolean; allowedOrigins: string[] }) {
- globalThis.fetch = vi.fn().mockResolvedValue({
- ok: true,
- json: () => Promise.resolve(inventoryPayload(cors)),
- } as unknown as Response);
-}
-
-async function renderAuthzSection(): Promise<HTMLElement> {
- const container = makeContainer();
- await act(async () => {
- createRoot(container).render(React.createElement(AuthzSection));
- });
- // Flush the mount-time inventory fetch + resulting state update.
- await act(async () => {
- await Promise.resolve();
- await Promise.resolve();
- });
- return container;
-}
-
-describe("AuthzSection wildcard-CORS banner (#5602)", { timeout: 60000 }, () => {
- beforeEach(() => {
- (
- globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }
- ).IS_REACT_ACT_ENVIRONMENT = true;
- });
-
- afterEach(() => {
- while (cleanupCallbacks.length > 0) cleanupCallbacks.pop()?.();
- document.body.innerHTML = "";
- vi.clearAllMocks();
- });
-
- it("renders the banner when cors.allowAll is true", async () => {
- mockInventoryFetch({ allowAll: true, allowedOrigins: [] });
- await renderAuthzSection();
- const banner = document.querySelector('[data-testid="cors-wildcard-banner"]');
- expect(banner).not.toBeNull();
- });
-
- it("does NOT render the banner when cors.allowAll is false", async () => {
- mockInventoryFetch({ allowAll: false, allowedOrigins: ["https://app.example.com"] });
- await renderAuthzSection();
- const banner = document.querySelector('[data-testid="cors-wildcard-banner"]');
- expect(banner).toBeNull();
- });
-});
diff --git a/tests/unit/ui/home-update-error-render-5991.test.ts b/tests/unit/ui/home-update-error-render-5991.test.ts
deleted file mode 100644
index fc598c0138..0000000000
--- a/tests/unit/ui/home-update-error-render-5991.test.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import { test } from "node:test";
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import { fileURLToPath } from "node:url";
-import { dirname, resolve } from "node:path";
-
-// Regression guard for #5991 — clicking "Update now" showed an "Internal Server
-// Error" screen (Minified React error #31). The handler POSTs /api/system/version
-// (a loopback-only auto-update endpoint) and, on a non-OK JSON response, did:
-// notify.error(data.error || "Failed to start update.");
-// OmniRoute's error envelope is `{ error: { code, message, correlation_id } }`, so
-// `data.error` is an OBJECT. notify.error rendered that object as a React child →
-// React #31 crash. The fix funnels the body through extractApiErrorMessage() (the
-// same helper introduced in #5340) so a string always reaches the toast.
-
-const here = dirname(fileURLToPath(import.meta.url));
-const source = readFileSync(
- resolve(here, "../../../src/app/(dashboard)/dashboard/HomePageClient.tsx"),
- "utf8"
-);
-
-test("HomePageClient imports the safe API error extractor", () => {
- assert.match(
- source,
- /import\s*\{\s*extractApiErrorMessage\s*\}\s*from\s*["']@\/shared\/http\/apiErrorMessage["']/,
- "HomePageClient must import extractApiErrorMessage to render API errors safely (#5991)"
- );
-});
-
-test("the update-error handler funnels the body through extractApiErrorMessage (#5991)", () => {
- // The update failure path must extract a string, not hand the raw envelope object
- // (which triggers React #31) to notify.error.
- assert.match(
- source,
- /notify\.error\(\s*extractApiErrorMessage\(\s*data\s*,/,
- "the update-error notify.error must use extractApiErrorMessage(data, …) (#5991)"
- );
-});
-
-test("the update-error handler never passes the raw error object to notify.error (#5991)", () => {
- // The pre-fix pattern `notify.error(data.error || …)` rendered an object as a React
- // child. It must not come back.
- assert.doesNotMatch(
- source,
- /notify\.error\(\s*data\.error\b/,
- "notify.error(data.error …) renders the error envelope object as a React child → React #31 (#5991)"
- );
-});
diff --git a/tests/unit/ui/quick-start-api-keys-link-5695.test.ts b/tests/unit/ui/quick-start-api-keys-link-5695.test.ts
index c4a3eaaca0..bd14d442a3 100644
--- a/tests/unit/ui/quick-start-api-keys-link-5695.test.ts
+++ b/tests/unit/ui/quick-start-api-keys-link-5695.test.ts
@@ -21,10 +21,7 @@ const messages = JSON.parse(
test("#5695 Quick Start step 1 links to the API Manager (API Keys), not Endpoint", () => {
// The endpoint render-prop Link inside the step1Desc rich block.
- // NB: tolerate Prettier splitting `<Link href=...>` across lines (\s+ between
- // the tag and the attr) — otherwise the regex skips the multi-line step1 Link
- // and wrongly matches the single-line step2 `/dashboard/providers` Link.
- const hrefMatch = source.match(/t\.rich\("step1Desc"[\s\S]*?<Link\s+href="([^"]*)"/);
+ const hrefMatch = source.match(/t\.rich\("step1Desc"[\s\S]*?<Link href="([^"]*)"/);
assert.ok(hrefMatch, "expected to find the step1Desc endpoint Link in HomePageClient.tsx");
assert.equal(
hrefMatch![1],
diff --git a/tests/unit/usage-history-reset.test.ts b/tests/unit/usage-history-reset.test.ts
deleted file mode 100644
index 0050ee90b6..0000000000
--- a/tests/unit/usage-history-reset.test.ts
+++ /dev/null
@@ -1,179 +0,0 @@
-/**
- * TDD regression guard for the on-demand, period-scoped usage-data reset
- * (Settings → Storage → "Reset usage data").
- *
- * Ported from decolua/9router PR #2272 (usage-reset concern only — the
- * connection bulk-delete half of that PR is intentionally not ported;
- * OmniRoute already has a native bulk-delete for connections).
- */
-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";
-
-let tempDir: string;
-let originalDataDir: string | undefined;
-
-function setup() {
- tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-usage-reset-test-"));
- originalDataDir = process.env.DATA_DIR;
- process.env.DATA_DIR = tempDir;
-}
-
-function teardown() {
- try {
- const { resetDbInstance } = require("../../src/lib/db/core.ts");
- resetDbInstance();
- } catch {
- // ignore if import fails
- }
- if (originalDataDir !== undefined) {
- process.env.DATA_DIR = originalDataDir;
- } else {
- delete process.env.DATA_DIR;
- }
- try {
- fs.rmSync(tempDir, { recursive: true, force: true });
- } catch {
- // ignore cleanup errors
- }
-}
-
-function countRows(db: import("better-sqlite3").Database, table: string): number {
- const row = db.prepare(`SELECT COUNT(*) as c FROM ${table}`).get() as { c: number };
- return row.c;
-}
-
-test.after(() => {
- // Belt-and-suspenders: guarantee the DB handle from the last test that ran
- // (if teardown() somehow wasn't reached) is closed so node:test can exit.
- try {
- const { resetDbInstance } = require("../../src/lib/db/core.ts");
- resetDbInstance();
- } catch {
- // ignore
- }
-});
-
-test("resetUsageHistory: 'all' wipes usage_history, daily_usage_summary, and hourly_usage_summary; a period only deletes rows older than the cutoff; an invalid period throws", async () => {
- setup();
- try {
- const { getDbInstance } = await import("../../src/lib/db/core.ts");
- const { resetUsageHistory } = await import("../../src/lib/db/cleanup.ts");
-
- const db = getDbInstance();
-
- const now = Date.now();
- const oldIso = new Date(now - 2 * 24 * 60 * 60 * 1000).toISOString(); // 2 days ago
- const recentIso = new Date(now - 60 * 60 * 1000).toISOString(); // 1 hour ago
- const oldDate = oldIso.slice(0, 10);
- const recentDate = recentIso.slice(0, 10);
- const oldDateHour = `${oldIso.slice(0, 10)} ${oldIso.slice(11, 13)}:00:00`;
- const recentDateHour = `${recentIso.slice(0, 10)} ${recentIso.slice(11, 13)}:00:00`;
-
- function seed() {
- db.prepare(
- "INSERT INTO usage_history (provider, model, timestamp) VALUES (?, ?, ?)"
- ).run("openai", "gpt-test", oldIso);
- db.prepare(
- "INSERT INTO usage_history (provider, model, timestamp) VALUES (?, ?, ?)"
- ).run("openai", "gpt-test", recentIso);
-
- db.prepare(
- "INSERT INTO daily_usage_summary (provider, model, date) VALUES (?, ?, ?)"
- ).run("openai", "gpt-test", oldDate);
- db.prepare(
- "INSERT INTO daily_usage_summary (provider, model, date) VALUES (?, ?, ?)"
- ).run("openai", "gpt-test", recentDate);
-
- db.prepare(
- "INSERT INTO hourly_usage_summary (provider, model, date_hour) VALUES (?, ?, ?)"
- ).run("openai", "gpt-test", oldDateHour);
- db.prepare(
- "INSERT INTO hourly_usage_summary (provider, model, date_hour) VALUES (?, ?, ?)"
- ).run("openai", "gpt-test", recentDateHour);
- }
-
- seed();
-
- assert.equal(countRows(db, "usage_history"), 2, "sanity: 2 usage_history rows seeded");
- assert.equal(
- countRows(db, "daily_usage_summary"),
- 2,
- "sanity: 2 daily_usage_summary rows seeded"
- );
- assert.equal(
- countRows(db, "hourly_usage_summary"),
- 2,
- "sanity: 2 hourly_usage_summary rows seeded"
- );
-
- // 1) A period ("1d") deletes only the row older than the cutoff, keeps the recent one.
- const periodResult = await resetUsageHistory("1d");
-
- assert.equal(periodResult.errors, 0, "period reset should not report errors");
- assert.equal(periodResult.deletedUsageHistory, 1, "should delete only the old usage_history row");
- assert.equal(
- periodResult.deletedDailySummary,
- 1,
- "should delete only the old daily_usage_summary row"
- );
- assert.equal(
- periodResult.deletedHourlySummary,
- 1,
- "should delete only the old hourly_usage_summary row"
- );
- assert.equal(periodResult.deleted, 3, "total deleted should sum the three tables");
-
- assert.equal(countRows(db, "usage_history"), 1, "recent usage_history row should survive");
- assert.equal(
- countRows(db, "daily_usage_summary"),
- 1,
- "recent daily_usage_summary row should survive"
- );
- assert.equal(
- countRows(db, "hourly_usage_summary"),
- 1,
- "recent hourly_usage_summary row should survive"
- );
-
- const survivingTimestamp = db
- .prepare("SELECT timestamp FROM usage_history")
- .get() as { timestamp: string };
- assert.equal(
- survivingTimestamp.timestamp,
- recentIso,
- "the surviving usage_history row should be the recent one"
- );
-
- // 2) "all" wipes everything left (including the row the period reset kept).
- const allResult = await resetUsageHistory("all");
-
- assert.equal(allResult.errors, 0, "'all' reset should not report errors");
- assert.equal(allResult.deletedUsageHistory, 1, "'all' should delete the remaining usage_history row");
- assert.equal(
- allResult.deletedDailySummary,
- 1,
- "'all' should delete the remaining daily_usage_summary row"
- );
- assert.equal(
- allResult.deletedHourlySummary,
- 1,
- "'all' should delete the remaining hourly_usage_summary row"
- );
-
- assert.equal(countRows(db, "usage_history"), 0, "'all' should empty usage_history");
- assert.equal(countRows(db, "daily_usage_summary"), 0, "'all' should empty daily_usage_summary");
- assert.equal(countRows(db, "hourly_usage_summary"), 0, "'all' should empty hourly_usage_summary");
-
- // 3) An invalid period throws instead of silently doing nothing / deleting everything.
- await assert.rejects(
- () => resetUsageHistory("bogus-period"),
- /Invalid reset period/,
- "an invalid period should throw"
- );
- } finally {
- teardown();
- }
-});
diff --git a/tests/unit/usage-service-hardening.test.ts b/tests/unit/usage-service-hardening.test.ts
index 44c4a5fe6a..fab25fcd26 100644
--- a/tests/unit/usage-service-hardening.test.ts
+++ b/tests/unit/usage-service-hardening.test.ts
@@ -893,13 +893,11 @@ test("usage service covers Qwen, Qoder, GLM, Z.AI and GLMT branches", async () =
});
assert.match(qwen.message, /Usage tracked per request/i);
- // Qoder now reads its PAT from `apiKey` (not `accessToken`); with no PAT the
- // usage fetcher returns a friendly prompt instead of hitting the network.
const qoder: any = await usageService.getUsageForProvider({
provider: "qoder",
accessToken: "qoder-token",
});
- assert.match(qoder.message, /Personal Access Token/i);
+ assert.match(qoder.message, /Usage tracked per request/i);
const glmMissingKey: any = await usageService.getUsageForProvider({
provider: "glm",
diff --git a/tests/unit/validate-release-green.test.ts b/tests/unit/validate-release-green.test.ts
index d2d165bd53..b31be512b9 100644
--- a/tests/unit/validate-release-green.test.ts
+++ b/tests/unit/validate-release-green.test.ts
@@ -121,22 +121,3 @@ test("classifyRunError: a kill WITHOUT a configured timeout is not misreported a
assert.equal(r.code, 1);
assert.doesNotMatch(r.out, /ceiling/);
});
-
-test("pre-flight wires the test-masking PR-context gate against origin/main (v3.8.43 gap fix)", async () => {
- const fs = await import("node:fs");
- const src = fs.readFileSync(
- new URL("../../scripts/quality/validate-release-green.mjs", import.meta.url),
- "utf8"
- );
- // The gate must run check:test-masking, pin the base to main, and be classified HARD —
- // it caught a real net-assert reduction that only surfaced on the release PR before.
- assert.match(src, /check:test-masking/, "test-masking gate must be wired into the pre-flight");
- assert.match(src, /GITHUB_BASE_REF:\s*"main"/, "test-masking must diff against origin/main");
- assert.match(
- src,
- /id:\s*"test-masking"[\s\S]*?kind:\s*"hard"/,
- "test-masking must be a HARD gate (non-allowlisted weakening blocks the release)"
- );
- // run() must honor a per-gate env override so GITHUB_BASE_REF actually reaches the child.
- assert.match(src, /\.\.\.\(opts\.env \|\| \{\}\)/, "run() must merge opts.env into the child env");
-});
diff --git a/tests/unit/vercel-ai-gateway-media.test.ts b/tests/unit/vercel-ai-gateway-media.test.ts
deleted file mode 100644
index b223235aea..0000000000
--- a/tests/unit/vercel-ai-gateway-media.test.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import { describe, it } from "node:test";
-import assert from "node:assert/strict";
-import {
- EMBEDDING_PROVIDERS,
- getEmbeddingProvider,
-} from "../../open-sse/config/embeddingRegistry.ts";
-import { IMAGE_PROVIDERS, getImageProvider } from "../../open-sse/config/imageRegistry.ts";
-
-describe("vercel-ai-gateway media registry entries (upstream #1704)", () => {
- describe("embeddingRegistry — vercel-ai-gateway", () => {
- it("is registered in EMBEDDING_PROVIDERS", () => {
- assert.ok(
- EMBEDDING_PROVIDERS["vercel-ai-gateway"],
- "vercel-ai-gateway should be in EMBEDDING_PROVIDERS"
- );
- });
-
- it("resolves vercel-ai-gateway provider config", () => {
- const p = getEmbeddingProvider("vercel-ai-gateway");
- assert.ok(p, "getEmbeddingProvider should resolve vercel-ai-gateway");
- assert.equal(p.id, "vercel-ai-gateway");
- assert.equal(p.baseUrl, "https://ai-gateway.vercel.sh/v1/embeddings");
- assert.equal(p.authType, "apikey");
- assert.equal(p.authHeader, "bearer");
- });
-
- it("has at least one embedding model", () => {
- const p = getEmbeddingProvider("vercel-ai-gateway");
- assert.ok(p.models.length >= 1, `Expected ≥1 models, got ${p.models.length}`);
- });
- });
-
- describe("imageRegistry — vercel-ai-gateway", () => {
- it("is registered in IMAGE_PROVIDERS", () => {
- assert.ok(IMAGE_PROVIDERS["vercel-ai-gateway"], "vercel-ai-gateway should be in IMAGE_PROVIDERS");
- });
-
- it("resolves vercel-ai-gateway image provider config", () => {
- const p = getImageProvider("vercel-ai-gateway");
- assert.ok(p, "getImageProvider should resolve vercel-ai-gateway");
- assert.equal(p.id, "vercel-ai-gateway");
- assert.equal(p.alias, "vag");
- assert.equal(p.baseUrl, "https://ai-gateway.vercel.sh/v1/images/generations");
- assert.equal(p.authType, "apikey");
- assert.equal(p.authHeader, "bearer");
- assert.equal(p.format, "openai");
- });
-
- it("has at least one image model", () => {
- const p = getImageProvider("vercel-ai-gateway");
- assert.ok(p.models.length >= 1, `Expected ≥1 models, got ${p.models.length}`);
- });
- });
-});
diff --git a/tests/unit/web-cookie-providers-new.test.ts b/tests/unit/web-cookie-providers-new.test.ts
index 4390fc33ca..2cc59bcd23 100644
--- a/tests/unit/web-cookie-providers-new.test.ts
+++ b/tests/unit/web-cookie-providers-new.test.ts
@@ -675,7 +675,7 @@ test("Kimi Web: targets www.kimi.com (international)", async () => {
const executor = new KimiWebExecutor();
const result = await executor.execute({
...noopExecuteInput,
- model: "k2d6",
+ model: "kimi-default",
credentials: { apiKey: "kimi-auth=eyJ.eyJzdWI.signature" },
});
assert.ok(result.response instanceof Response);
@@ -695,7 +695,7 @@ test("Kimi Web: missing JWT returns a 400 before fetching", async () => {
const executor = new KimiWebExecutor();
const result = await executor.execute({
...noopExecuteInput,
- model: "k2d6",
+ model: "kimi-default",
credentials: { apiKey: "" },
});
assert.equal(result.response.status, 400);
@@ -707,7 +707,7 @@ test("Kimi Web: error response returns error result", async () => {
const executor = new KimiWebExecutor();
const result = await executor.execute({
...noopExecuteInput,
- model: "k2d6",
+ model: "kimi-default",
credentials: { apiKey: "kimi-auth=eyJ.eyJzdWI.signature" },
});
assert.ok(result.response instanceof Response);
diff --git a/tests/unit/webshare-sync.test.ts b/tests/unit/webshare-sync.test.ts
deleted file mode 100644
index 184641bf08..0000000000
--- a/tests/unit/webshare-sync.test.ts
+++ /dev/null
@@ -1,367 +0,0 @@
-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-webshare-"));
-process.env.DATA_DIR = TEST_DATA_DIR;
-
-// Providers read process.env at call-time, so we can set flags before import.
-// Keep the other free-proxy sources disabled so this file only exercises Webshare.
-process.env.FREE_PROXY_1PROXY_ENABLED = "false";
-process.env.FREE_PROXY_PROXIFLY_ENABLED = "false";
-process.env.FREE_PROXY_IPLOCATE_ENABLED = "false";
-
-const FAKE_API_KEY = "wsk_test_super_secret_token_1234567890";
-
-const core = await import("../../src/lib/db/core.ts");
-const { getProvider } = await import("../../src/lib/freeProxyProviders/index.ts");
-const freeProxiesDb = await import("../../src/lib/db/freeProxies.ts");
-
-async function reset() {
- core.resetDbInstance();
- fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
- fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
-}
-
-test.after(() => {
- core.resetDbInstance();
- fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
-});
-
-function webshareResponse(results: unknown[], next: string | null = null) {
- return new Response(JSON.stringify({ count: results.length, next, previous: null, results }), {
- status: 200,
- headers: { "content-type": "application/json" },
- });
-}
-
-// ── isEnabled ────────────────────────────────────────────────────────────────
-
-test("WebshareProvider.isEnabled is false without an API key", () => {
- const originalKey = process.env.FREE_PROXY_WEBSHARE_API_KEY;
- delete process.env.FREE_PROXY_WEBSHARE_API_KEY;
-
- const p = getProvider("webshare")!;
- assert.equal(p.isEnabled(), false);
-
- if (originalKey !== undefined) process.env.FREE_PROXY_WEBSHARE_API_KEY = originalKey;
-});
-
-test("WebshareProvider.isEnabled is true once an API key is configured", () => {
- const originalKey = process.env.FREE_PROXY_WEBSHARE_API_KEY;
- process.env.FREE_PROXY_WEBSHARE_API_KEY = FAKE_API_KEY;
-
- const p = getProvider("webshare")!;
- assert.equal(p.isEnabled(), true);
-
- process.env.FREE_PROXY_WEBSHARE_API_KEY = originalKey ?? "";
- if (originalKey === undefined) delete process.env.FREE_PROXY_WEBSHARE_API_KEY;
-});
-
-test("WebshareProvider.isEnabled is false when explicitly disabled, even with a key", () => {
- const originalKey = process.env.FREE_PROXY_WEBSHARE_API_KEY;
- const originalEnabled = process.env.FREE_PROXY_WEBSHARE_ENABLED;
- process.env.FREE_PROXY_WEBSHARE_API_KEY = FAKE_API_KEY;
- process.env.FREE_PROXY_WEBSHARE_ENABLED = "false";
-
- const p = getProvider("webshare")!;
- assert.equal(p.isEnabled(), false);
-
- process.env.FREE_PROXY_WEBSHARE_API_KEY = originalKey ?? "";
- if (originalKey === undefined) delete process.env.FREE_PROXY_WEBSHARE_API_KEY;
- process.env.FREE_PROXY_WEBSHARE_ENABLED = originalEnabled ?? "";
- if (originalEnabled === undefined) delete process.env.FREE_PROXY_WEBSHARE_ENABLED;
-});
-
-// ── sync — disabled path ────────────────────────────────────────────────────
-
-test("WebshareProvider.sync returns a disabled error (no key leak) when no API key is set", async () => {
- const originalKey = process.env.FREE_PROXY_WEBSHARE_API_KEY;
- delete process.env.FREE_PROXY_WEBSHARE_API_KEY;
- await reset();
-
- const p = getProvider("webshare")!;
- const result = await p.sync();
-
- assert.equal(result.fetched, 0);
- assert.ok(result.errors.length > 0);
- assert.ok(result.errors[0].includes("disabled"));
-
- if (originalKey !== undefined) process.env.FREE_PROXY_WEBSHARE_API_KEY = originalKey;
-});
-
-// ── sync — pagination + upsert ──────────────────────────────────────────────
-
-test("WebshareProvider.sync paginates via `next` and upserts proxies", async () => {
- await reset();
- const originalKey = process.env.FREE_PROXY_WEBSHARE_API_KEY;
- const originalFetch = globalThis.fetch;
- process.env.FREE_PROXY_WEBSHARE_API_KEY = FAKE_API_KEY;
-
- const seenAuthHeaders: string[] = [];
- const seenPages: string[] = [];
-
- globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
- const url = new URL(String(input));
- seenPages.push(url.searchParams.get("page") || "");
- const headers = new Headers(init?.headers);
- seenAuthHeaders.push(headers.get("authorization") || "");
-
- const page = url.searchParams.get("page");
- if (page === "1") {
- return webshareResponse(
- [
- {
- proxy_address: "45.10.20.1",
- port: 6001,
- valid: true,
- country_code: "US",
- last_verification: "2026-01-01T00:00:00.000Z",
- },
- {
- proxy_address: "45.10.20.2",
- port: 6002,
- valid: true,
- country_code: "DE",
- last_verification: "2026-01-01T00:00:00.000Z",
- },
- ],
- "https://proxy.webshare.io/api/v2/proxy/list/?page=2"
- );
- }
- return webshareResponse(
- [
- {
- proxy_address: "45.10.20.3",
- port: 6003,
- valid: true,
- country_code: "FR",
- last_verification: "2026-01-01T00:00:00.000Z",
- },
- ],
- null
- );
- }) as typeof fetch;
-
- try {
- const p = getProvider("webshare")!;
- const result = await p.sync();
-
- assert.deepEqual(seenPages, ["1", "2"]);
- assert.ok(
- seenAuthHeaders.every((h) => h === `Token ${FAKE_API_KEY}`),
- "every request must carry the Webshare Authorization token"
- );
- assert.equal(result.fetched, 3);
- assert.equal(result.added, 3);
- assert.equal(result.updated, 0);
- assert.deepEqual(result.errors, []);
-
- const items = await p.list({ limit: 10 });
- assert.equal(items.length, 3);
- assert.ok(items.every((item) => item.source === "webshare"));
- assert.ok(items.some((item) => item.host === "45.10.20.1" && item.port === 6001));
- } finally {
- globalThis.fetch = originalFetch;
- process.env.FREE_PROXY_WEBSHARE_API_KEY = originalKey ?? "";
- if (originalKey === undefined) delete process.env.FREE_PROXY_WEBSHARE_API_KEY;
- }
-});
-
-test("WebshareProvider.sync updates existing rows instead of duplicating them", async () => {
- await reset();
- const originalKey = process.env.FREE_PROXY_WEBSHARE_API_KEY;
- const originalFetch = globalThis.fetch;
- process.env.FREE_PROXY_WEBSHARE_API_KEY = FAKE_API_KEY;
-
- let call = 0;
- globalThis.fetch = (async () => {
- call++;
- return webshareResponse([
- {
- proxy_address: "45.10.20.1",
- port: 6001,
- valid: true,
- country_code: "US",
- last_verification: new Date().toISOString(),
- },
- ]);
- }) as typeof fetch;
-
- try {
- const p = getProvider("webshare")!;
- const first = await p.sync();
- const second = await p.sync();
-
- assert.equal(first.added, 1);
- assert.equal(second.added, 0);
- assert.equal(second.updated, 1);
- assert.equal(call, 2);
-
- const items = await p.list({ limit: 10 });
- assert.equal(items.length, 1);
- } finally {
- globalThis.fetch = originalFetch;
- process.env.FREE_PROXY_WEBSHARE_API_KEY = originalKey ?? "";
- if (originalKey === undefined) delete process.env.FREE_PROXY_WEBSHARE_API_KEY;
- }
-});
-
-// ── sync — tombstone ─────────────────────────────────────────────────────────
-
-test("WebshareProvider.sync tombstones proxies no longer returned by the account list", async () => {
- await reset();
- const originalKey = process.env.FREE_PROXY_WEBSHARE_API_KEY;
- const originalFetch = globalThis.fetch;
- process.env.FREE_PROXY_WEBSHARE_API_KEY = FAKE_API_KEY;
-
- let responses: unknown[][] = [
- [
- { proxy_address: "45.10.20.1", port: 6001, valid: true, country_code: "US" },
- { proxy_address: "45.10.20.2", port: 6002, valid: true, country_code: "DE" },
- ],
- ];
- let callIndex = 0;
- globalThis.fetch = (async () => {
- const batch = responses[callIndex] ?? [];
- callIndex++;
- return webshareResponse(batch);
- }) as typeof fetch;
-
- try {
- const p = getProvider("webshare")!;
- await p.sync();
- let items = await p.list({ limit: 10 });
- assert.equal(items.length, 2);
-
- // Second sync: the account list now only has 45.10.20.1 — .2 was retired.
- responses = [[{ proxy_address: "45.10.20.1", port: 6001, valid: true, country_code: "US" }]];
- callIndex = 0;
- await p.sync();
-
- items = await p.list({ limit: 10 });
- assert.equal(items.length, 1);
- assert.equal(items[0].host, "45.10.20.1");
- } finally {
- globalThis.fetch = originalFetch;
- process.env.FREE_PROXY_WEBSHARE_API_KEY = originalKey ?? "";
- if (originalKey === undefined) delete process.env.FREE_PROXY_WEBSHARE_API_KEY;
- }
-});
-
-test("WebshareProvider.sync never tombstones proxies already promoted to the pool", async () => {
- await reset();
- const originalKey = process.env.FREE_PROXY_WEBSHARE_API_KEY;
- const originalFetch = globalThis.fetch;
- process.env.FREE_PROXY_WEBSHARE_API_KEY = FAKE_API_KEY;
-
- globalThis.fetch = (async () =>
- webshareResponse([
- { proxy_address: "45.10.20.1", port: 6001, valid: true, country_code: "US" },
- ])) as typeof fetch;
-
- try {
- const p = getProvider("webshare")!;
- await p.sync();
- const [item] = await freeProxiesDb.listFreeProxies({ sources: ["webshare"] });
- assert.ok(item);
- await freeProxiesDb.markFreeProxyInPool(item.id, "some-registry-id");
-
- // Next sync returns an empty list — if pruning ignored `in_pool`, this row
- // would be deleted even though it's actively in use by the proxy pool.
- globalThis.fetch = (async () => webshareResponse([])) as typeof fetch;
- await p.sync();
-
- const stillThere = await freeProxiesDb.getFreeProxyById(item.id);
- assert.ok(stillThere, "in-pool proxy must survive a sync where it is no longer listed");
- } finally {
- globalThis.fetch = originalFetch;
- process.env.FREE_PROXY_WEBSHARE_API_KEY = originalKey ?? "";
- if (originalKey === undefined) delete process.env.FREE_PROXY_WEBSHARE_API_KEY;
- }
-});
-
-// ── sync — error sanitization / key masking ─────────────────────────────────
-
-test("WebshareProvider.sync never leaks the API key in error messages on an HTTP failure", async () => {
- await reset();
- const originalKey = process.env.FREE_PROXY_WEBSHARE_API_KEY;
- const originalFetch = globalThis.fetch;
- process.env.FREE_PROXY_WEBSHARE_API_KEY = FAKE_API_KEY;
-
- globalThis.fetch = (async () =>
- new Response("Unauthorized", { status: 401 })) as typeof fetch;
-
- try {
- const p = getProvider("webshare")!;
- const result = await p.sync();
-
- assert.equal(result.fetched, 0);
- assert.ok(result.errors.length > 0);
- for (const err of result.errors) {
- assert.ok(!err.includes(FAKE_API_KEY), `error must not leak the API key: ${err}`);
- assert.ok(!err.toLowerCase().includes("authorization"), `error must not leak the auth header: ${err}`);
- }
- } finally {
- globalThis.fetch = originalFetch;
- process.env.FREE_PROXY_WEBSHARE_API_KEY = originalKey ?? "";
- if (originalKey === undefined) delete process.env.FREE_PROXY_WEBSHARE_API_KEY;
- }
-});
-
-test("WebshareProvider.sync never leaks the API key in error messages on a network exception", async () => {
- await reset();
- const originalKey = process.env.FREE_PROXY_WEBSHARE_API_KEY;
- const originalFetch = globalThis.fetch;
- process.env.FREE_PROXY_WEBSHARE_API_KEY = FAKE_API_KEY;
-
- globalThis.fetch = (async () => {
- throw new Error(`connect ECONNREFUSED (key was ${FAKE_API_KEY})`);
- }) as typeof fetch;
-
- try {
- const p = getProvider("webshare")!;
- const result = await p.sync();
-
- // The provider itself must not additionally embed the key; it only
- // forwards err.message. This guards the call site never re-injects the
- // key into a wrapper string.
- assert.equal(result.fetched, 0);
- assert.ok(result.errors.length > 0);
- } finally {
- globalThis.fetch = originalFetch;
- process.env.FREE_PROXY_WEBSHARE_API_KEY = originalKey ?? "";
- if (originalKey === undefined) delete process.env.FREE_PROXY_WEBSHARE_API_KEY;
- }
-});
-
-test("WebshareProvider.sync skips private/loopback hosts", async () => {
- await reset();
- const originalKey = process.env.FREE_PROXY_WEBSHARE_API_KEY;
- const originalFetch = globalThis.fetch;
- process.env.FREE_PROXY_WEBSHARE_API_KEY = FAKE_API_KEY;
-
- globalThis.fetch = (async () =>
- webshareResponse([
- { proxy_address: "127.0.0.1", port: 6001, valid: true, country_code: "US" },
- { proxy_address: "45.10.20.9", port: 6009, valid: true, country_code: "US" },
- ])) as typeof fetch;
-
- try {
- const p = getProvider("webshare")!;
- const result = await p.sync();
-
- assert.equal(result.fetched, 1);
- assert.ok(result.errors.some((e) => e.includes("private/loopback")));
-
- const items = await p.list({ limit: 10 });
- assert.equal(items.length, 1);
- assert.equal(items[0].host, "45.10.20.9");
- } finally {
- globalThis.fetch = originalFetch;
- process.env.FREE_PROXY_WEBSHARE_API_KEY = originalKey ?? "";
- if (originalKey === undefined) delete process.env.FREE_PROXY_WEBSHARE_API_KEY;
- }
-});
diff --git a/tests/unit/xai-usage.test.ts b/tests/unit/xai-usage.test.ts
deleted file mode 100644
index 5e027f3c2d..0000000000
--- a/tests/unit/xai-usage.test.ts
+++ /dev/null
@@ -1,136 +0,0 @@
-/**
- * tests/unit/xai-usage.test.ts
- *
- * xAI (Grok) has no public per-account quota API (the billing console at
- * console.x.ai requires a session cookie, not an API key), so — exactly like
- * the Xiaomi MiMo self-track pattern — OmniRoute self-tracks it: it sums the
- * tokens it routed to the connection from `usage_history` and surfaces them
- * as a cumulative, uncapped ("unlimited") usage figure on the quota
- * dashboard. These tests cover the aggregation helper + the fetcher shape,
- * with a real temp DB, and assert provider + connection scoping (no bleed).
- */
-
-import { describe, it, before, after } from "node:test";
-import assert from "node:assert/strict";
-import os from "node:os";
-import path from "node:path";
-import fs from "node:fs";
-
-// DATA_DIR must be set before any module that opens the DB is imported.
-const TMP = fs.mkdtempSync(path.join(os.tmpdir(), "omni-xai-usage-"));
-process.env.DATA_DIR = TMP;
-
-const core = await import("../../src/lib/db/core.ts");
-const { getMonthlyProviderTokensForConnection } = await import(
- "../../src/lib/usage/usageStats.ts"
-);
-const { __testing, USAGE_FETCHER_PROVIDERS, getUsageForProvider } = await import(
- "../../open-sse/services/usage.ts"
-);
-const { getXaiUsage } = __testing;
-
-function insertUsage(
- connectionId: string,
- provider: string,
- tokensIn: number,
- tokensOut: number,
- timestamp: string
-) {
- const db = core.getDbInstance();
- db.prepare(
- `INSERT INTO usage_history (provider, connection_id, tokens_input, tokens_output, timestamp)
- VALUES (?, ?, ?, ?, ?)`
- ).run(provider, connectionId, tokensIn, tokensOut, timestamp);
-}
-
-describe("xAI self-tracked usage", () => {
- before(() => {
- core.getDbInstance(); // trigger migrations
- const now = new Date();
- const inWindow = now.toISOString();
- const outOfWindow = new Date(
- Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - 1, 15)
- ).toISOString();
- // in-window usage for conn-x: 2.0M + 0.3M
- insertUsage("conn-x", "xai", 2_000_000, 0, inWindow);
- insertUsage("conn-x", "xai", 0, 300_000, inWindow);
- // out-of-window usage must NOT count toward the current aggregate
- insertUsage("conn-x", "xai", 9_000_000, 9_000_000, outOfWindow);
- // a different connection must not bleed in
- insertUsage("conn-y", "xai", 5_000_000, 0, inWindow);
- // a different provider on the same connection must not bleed in
- insertUsage("conn-x", "minimax", 8_000_000, 0, inWindow);
- });
-
- after(() => {
- core.resetDbInstance();
- try {
- fs.rmSync(TMP, { recursive: true, force: true });
- } catch {
- // best-effort temp cleanup
- }
- });
-
- it("registers 'xai' as a usage-fetcher provider", () => {
- assert.ok(
- (USAGE_FETCHER_PROVIDERS as readonly string[]).includes("xai"),
- "xai must be listed in USAGE_FETCHER_PROVIDERS"
- );
- });
-
- it("aggregates only in-window tokens for the given provider+connection", () => {
- // 2.0M + 0.3M = 2.3M; excludes out-of-window, conn-y, and minimax rows.
- assert.equal(getMonthlyProviderTokensForConnection("xai", "conn-x"), 2_300_000);
- });
-
- it("returns 0 for an unknown connection (fail-open, no bleed)", () => {
- assert.equal(getMonthlyProviderTokensForConnection("xai", "conn-none"), 0);
- });
-
- it("getXaiUsage returns a cumulative unlimited quota scoped to the connection", async () => {
- const r = (await getXaiUsage("conn-x")) as {
- plan?: string;
- quotas?: Record<
- string,
- {
- used: number;
- total: number;
- remaining?: number;
- remainingPercentage?: number;
- unlimited: boolean;
- resetAt: string | null;
- }
- >;
- message?: string;
- };
- assert.ok(r.quotas, `expected quotas, got message: ${r.message}`);
- const m = r.quotas!.monthly;
- assert.ok(m, "cumulative window present");
- assert.equal(m.used, 2_300_000);
- assert.equal(m.unlimited, true, "xAI has no fixed monthly cap");
- assert.equal(m.remaining, 100, "unlimited rows report remaining: 100 (matches upstream UX)");
- });
-
- it("getXaiUsage does not bleed a different connection's usage", async () => {
- const r = (await getXaiUsage("conn-y")) as {
- quotas?: { monthly?: { used: number } };
- };
- assert.equal(r.quotas?.monthly?.used, 5_000_000);
- });
-
- it("getXaiUsage returns a message when connection id is missing", async () => {
- const r = (await getXaiUsage("")) as { message?: string; quotas?: unknown };
- assert.ok(r.message && !r.quotas, "no quota without a connection id");
- });
-
- it("getUsageForProvider('xai', ...) delegates to getXaiUsage", async () => {
- const r = (await getUsageForProvider({
- id: "conn-x",
- provider: "xai",
- } as Parameters<typeof getUsageForProvider>[0])) as {
- quotas?: { monthly?: { used: number; unlimited: boolean } };
- };
- assert.equal(r.quotas?.monthly?.used, 2_300_000);
- assert.equal(r.quotas?.monthly?.unlimited, true);
- });
-});
diff --git a/vitest.config.ts b/vitest.config.ts
index 4664608302..d448bdeb6c 100644
--- a/vitest.config.ts
+++ b/vitest.config.ts
@@ -15,7 +15,6 @@ export default defineConfig({
"src/app/**/dashboard/endpoint/__tests__/**/*.test.tsx",
"src/app/**/dashboard/providers/**/__tests__/**/*.test.tsx",
"src/app/**/dashboard/webhooks/__tests__/**/*.test.tsx",
- "src/app/**/dashboard/discovery/__tests__/**/*.test.tsx",
"src/shared/hooks/__tests__/**/*.test.tsx",
"src/lib/memory/__tests__/**/*.test.ts",
"src/lib/skills/__tests__/**/*.test.ts",