Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors
TypeScript a2aai-agentsai-gatewayanthropicclaudeclaude-codeclinecodexcopilotcursordeepseekfree-aigeminikimillm-gatewaymcpopenaiopenai-proxyqwentoken-saver
Release v3.8.10 (#3140)
Diego Rodrigues de Sa e Souza68d5a0ab273f
diff --git a/.antigravitycli/0db0ca8e-3c51-48d9-83e2-da62c6f0a02b.json b/.antigravitycli/0db0ca8e-3c51-48d9-83e2-da62c6f0a02b.jsondeleted file mode 120000index 263f1a6d6e..0000000000--- a/.antigravitycli/0db0ca8e-3c51-48d9-83e2-da62c6f0a02b.json+++ /dev/null@@ -1 +0,0 @@-/home/diegosouzapw/.gemini/config/projects/0db0ca8e-3c51-48d9-83e2-da62c6f0a02b.json\ No newline at end of filediff --git a/.env.example b/.env.exampleindex 16a61c2444..252ee8d853 100644--- a/.env.example+++ b/.env.example@@ -6,7 +6,6 @@# │ Reference: docs/ENVIRONMENT.md for full details and usage scenarios. │# └─────────────────────────────────────────────────────────────────────────────┘-# ═══════════════════════════════════════════════════════════════════════════════# 1. REQUIRED SECRETS — Must be set before first run!# ═══════════════════════════════════════════════════════════════════════════════@@ -62,7 +61,6 @@ DISABLE_SQLITE_AUTO_BACKUP=false# Default: redis://localhost:6379 (or redis://redis:6379 in Docker)REDIS_URL=redis://localhost:6379-# ═══════════════════════════════════════════════════════════════════════════════# 3. NETWORK & PORTS# ═══════════════════════════════════════════════════════════════════════════════@@ -159,6 +157,11 @@ OMNIROUTE_USE_TURBOPACK=1# Values: production | development | Default: productionNODE_ENV=production+# Container runtime — controls startup script behavior (permissions, advice).+# Values: docker | podman | Default: docker+# Set to "podman" when running under rootless Podman so the entrypoint+# gives the correct fix instructions (podman unshare chown vs sudo chown).+CONTAINER_HOST=docker# ═══════════════════════════════════════════════════════════════════════════════# 4. SECURITY & AUTHENTICATION@@ -238,7 +241,6 @@ ALLOW_API_KEY_REVEAL=false# When unset, OmniRoute uses the per-feature defaults. Set to "false"/"0" to disable.# OUTBOUND_SSRF_GUARD_ENABLED=true-# ═══════════════════════════════════════════════════════════════════════════════# 5. INPUT SANITIZATION & PII PROTECTION (FASE-01)# ═══════════════════════════════════════════════════════════════════════════════@@ -271,7 +273,6 @@ ALLOW_API_KEY_REVEAL=false# PII_RESPONSE_SANITIZATION=false# PII_RESPONSE_SANITIZATION_MODE=redact # redact = mask PII | warn = log only | block = drop response-# ═══════════════════════════════════════════════════════════════════════════════# 6. TOOL & ROUTING POLICIES# ═══════════════════════════════════════════════════════════════════════════════@@ -291,7 +292,6 @@ ALLOW_API_KEY_REVEAL=false# Default: 5000 | Minimum: 1000# OMNIROUTE_PAYLOAD_RULES_RELOAD_MS=5000-# ═══════════════════════════════════════════════════════════════════════════════# 7. URLS & CLOUD SYNC# ═══════════════════════════════════════════════════════════════════════════════@@ -365,7 +365,6 @@ NEXT_PUBLIC_CLOUD_URL=#OMNIROUTE_OPENCODE_QUOTA_URL=https://opencode.ai/zen/go/v1/quota#OMNIROUTE_OPENCODE_GO_QUOTA_URL=https://api.z.ai/api/monitor/usage/quota/limit-# ═══════════════════════════════════════════════════════════════════════════════# 8. OUTBOUND PROXY (Upstream Provider Calls)# ═══════════════════════════════════════════════════════════════════════════════@@ -393,7 +392,6 @@ NEXT_PUBLIC_ENABLE_SOCKS5_PROXY=true# Used by: open-sse/services/claudeTurnstileSolver.ts# OMNIROUTE_TURNSTILE_IGNORE_TLS_ERRORS=false-# ═══════════════════════════════════════════════════════════════════════════════# 9. CLI TOOL INTEGRATION# ═══════════════════════════════════════════════════════════════════════════════@@ -423,7 +421,6 @@ NEXT_PUBLIC_ENABLE_SOCKS5_PROXY=true# CLI_QODER_BIN=qoder# CLI_QWEN_BIN=qwen-# ═══════════════════════════════════════════════════════════════════════════════# 10. INTERNAL AGENT & MCP INTEGRATIONS# ═══════════════════════════════════════════════════════════════════════════════@@ -473,6 +470,12 @@ NEXT_PUBLIC_ENABLE_SOCKS5_PROXY=true# Default: 70PROVIDER_LIMITS_SYNC_INTERVAL_MINUTES=70+# Gap (ms) between consecutive OAuth quota fetches in a bulk provider-limits sync.+# OAuth providers are fetched one at a time with this spacing so a single host+# never bursts simultaneous usage/refresh requests to the same upstream. Set to 0+# to opt out (restores fully concurrent fetches). Default: 1500+PROVIDER_LIMITS_SYNC_SPACING_MS=1500+# Disable all background services (sync, pricing, model refresh).# Used by: src/instrumentation-node.ts, src/lib/initCloudSync.ts# Useful for: CI builds, test environments, or resource-constrained containers.@@ -554,7 +557,6 @@ PROVIDER_LIMITS_SYNC_INTERVAL_MINUTES=70# Default: ~/.gemini/antigravity-cli/antigravity-oauth-token#AGY_TOKEN_FILE=-# ═══════════════════════════════════════════════════════════════════════════════# 11. OAUTH PROVIDER CREDENTIALS# ═══════════════════════════════════════════════════════════════════════════════@@ -701,7 +703,6 @@ GITHUB_OAUTH_CLIENT_ID=Iv1.b507a08c87ecfe98# CLI_USER_ID= # legacy alias for OMNIROUTE_USER_ID# SERVER_URL= # legacy alias for OMNIROUTE_SERVER-# ═══════════════════════════════════════════════════════════════════════════════# 12. PROVIDER USER-AGENT OVERRIDES# ═══════════════════════════════════════════════════════════════════════════════@@ -737,7 +738,6 @@ GEMINI_CLI_USER_AGENT="google-api-nodejs-client/10.3.0"# CODEX_USER_AGENT string. Used by: open-sse/config/codexClient.ts.# CODEX_CLIENT_VERSION=0.132.0-# ═══════════════════════════════════════════════════════════════════════════════# 13. CLI FINGERPRINT COMPATIBILITY (Anti-Detection)# ═══════════════════════════════════════════════════════════════════════════════@@ -766,7 +766,6 @@ GEMINI_CLI_USER_AGENT="google-api-nodejs-client/10.3.0"#KIMI_CLI_VERSION=1.36.0#KIMI_CODING_DEVICE_ID=-# ═══════════════════════════════════════════════════════════════════════════════# 14. API KEY PROVIDERS# ═══════════════════════════════════════════════════════════════════════════════@@ -789,7 +788,6 @@ GEMINI_CLI_USER_AGENT="google-api-nodejs-client/10.3.0"# OpenAI/Mistral/Together/Fireworks/NVIDIA configured via Dashboard → Providers# also work for embeddings.-# ═══════════════════════════════════════════════════════════════════════════════# 15. TIMEOUT SETTINGS# ═══════════════════════════════════════════════════════════════════════════════@@ -868,7 +866,6 @@ GEMINI_CLI_USER_AGENT="google-api-nodejs-client/10.3.0"# Default: 30000 (30 seconds)# SHUTDOWN_TIMEOUT_MS=30000-# ═══════════════════════════════════════════════════════════════════════════════# 16. LOGGING# ═══════════════════════════════════════════════════════════════════════════════@@ -942,7 +939,6 @@ APP_LOG_TO_FILE=true# Default: 100000# PROXY_LOGS_TABLE_MAX_ROWS=100000-# ═══════════════════════════════════════════════════════════════════════════════# 17. MEMORY OPTIMIZATION (Low-RAM / Docker)# ═══════════════════════════════════════════════════════════════════════════════@@ -1022,7 +1018,6 @@ APP_LOG_TO_FILE=true# Used by: open-sse/utils/usageTracking.ts# USAGE_TOKEN_BUFFER=100-# ═══════════════════════════════════════════════════════════════════════════════# 18. PRICING SYNC# ═══════════════════════════════════════════════════════════════════════════════@@ -1038,7 +1033,6 @@ APP_LOG_TO_FILE=true# Comma-separated data sources. Default: litellm# PRICING_SYNC_SOURCES=litellm-# ═══════════════════════════════════════════════════════════════════════════════# 19. MODEL SYNC (Dev)# ═══════════════════════════════════════════════════════════════════════════════@@ -1047,7 +1041,6 @@ APP_LOG_TO_FILE=true# Default: 86400 (24 hours)# MODELS_DEV_SYNC_INTERVAL=86400-# ═══════════════════════════════════════════════════════════════════════════════# 20. PROVIDER-SPECIFIC SETTINGS# ═══════════════════════════════════════════════════════════════════════════════@@ -1128,7 +1121,6 @@ APP_LOG_TO_FILE=true# Used by: open-sse/config/providerRegistry.ts — allows Docker service names.# LOCAL_HOSTNAMES=omlx,mlx-audio-# ═══════════════════════════════════════════════════════════════════════════════# 21. PROXY HEALTH# ═══════════════════════════════════════════════════════════════════════════════@@ -1154,7 +1146,6 @@ APP_LOG_TO_FILE=true# Used by: src/lib/tokenHealthCheck.ts. Default: 3000.# HEALTHCHECK_STAGGER_MS=3000-# ═══════════════════════════════════════════════════════════════════════════════# 22. DEBUGGING# ═══════════════════════════════════════════════════════════════════════════════@@ -1214,7 +1205,6 @@ APP_LOG_TO_FILE=true# Enable E2E test mode — relaxes auth and enables test harness hooks.# NEXT_PUBLIC_OMNIROUTE_E2E_MODE=true-# ═══════════════════════════════════════════════════════════════════════════════# 23. GITHUB INTEGRATION (Issue Reporting)# ═══════════════════════════════════════════════════════════════════════════════@@ -1232,7 +1222,6 @@ APP_LOG_TO_FILE=true# GITHUB_ISSUES_TOKEN when unset.# GITHUB_TOKEN=-# ═══════════════════════════════════════════════════════════════════════════════# 24. PROVIDER QUOTAS, TUNNELS & SANDBOXED SKILLS# ═══════════════════════════════════════════════════════════════════════════════@@ -1337,7 +1326,6 @@ APP_LOG_TO_FILE=true# SKILLS_SANDBOX_NETWORK_ENABLED=0# SKILLS_ALLOWED_SANDBOX_IMAGES=-# ═══════════════════════════════════════════════════════════════════════════════# 25. TEST & E2E# ═══════════════════════════════════════════════════════════════════════════════@@ -1359,6 +1347,12 @@ APP_LOG_TO_FILE=true# Disable the OAuth token healthcheck loop during tests (default: true).# OMNIROUTE_DISABLE_TOKEN_HEALTHCHECK=true+# Exclude specific providers from the PROACTIVE token-refresh sweep (comma-separated,+# case-insensitive). Targeted alternative to OMNIROUTE_DISABLE_TOKEN_HEALTHCHECK: keeps+# rotating-cascade providers (Codex/OpenAI share one Auth0 family) on the reactive 401+# path only, while short-TTL providers like Kimi-coding keep being refreshed proactively.+# OMNIROUTE_HEALTHCHECK_SKIP_PROVIDERS=codex,openai+# Silence healthcheck noise in Playwright stdout (default: true).# OMNIROUTE_HIDE_HEALTHCHECK_LOGS=true@@ -1448,8 +1442,8 @@ INSPECTOR_MASK_SECRETS=trueINSPECTOR_LLM_HOSTS_EXTRA=INSPECTOR_INTERNAL_INGEST_TOKEN=# Quota Sharing (Group B — planos 16+22)-QUOTA_STORE_DRIVER=sqlite # sqlite | redis-# QUOTA_STORE_REDIS_URL= # ex.: redis://localhost:6379 (apenas quando driver=redis)-# QUOTA_SATURATION_THRESHOLD=0.5 # 0..1; >= threshold ativa modo strict (sem empréstimo)-# QUOTA_SOFT_DEPRIORITIZE_FACTOR=0.7 # 0..1; multiplicador do score quando soft policy ativa-# QUOTA_CONSUMPTION_RETENTION_DAYS=14 # GC de buckets quota_consumption.updated_at antigos+QUOTA_STORE_DRIVER=sqlite # sqlite | redis+# QUOTA_STORE_REDIS_URL= # ex.: redis://localhost:6379 (apenas quando driver=redis)+# QUOTA_SATURATION_THRESHOLD=0.5 # 0..1; >= threshold ativa modo strict (sem empréstimo)+# QUOTA_SOFT_DEPRIORITIZE_FACTOR=0.7 # 0..1; multiplicador do score quando soft policy ativa+# QUOTA_CONSUMPTION_RETENTION_DAYS=14 # GC de buckets quota_consumption.updated_at antigosdiff --git a/.gitignore b/.gitignoreindex a0142644e0..6f31e0d47e 100644--- a/.gitignore+++ b/.gitignore@@ -9,6 +9,18 @@ _ideia/_mono_repo/_references/_tasks/+.agents/**+.claude/**+.gemini/**+.config/**+.data/**+.logs/**+.tests/**+.coverage/**+.dist/**+.next/**+.build/**+.out/**# Memory Bank and Cursor rules (local-only AI agent context)diff --git a/.i18n-state.json b/.i18n-state.jsondeleted file mode 100644index b544343cf4..0000000000--- a/.i18n-state.json+++ /dev/null@@ -1,219 +0,0 @@-{- "sources": {- "CLAUDE.md": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "locales": {- "pt-BR": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "301b997e936b1d476e6094042666b96b33f42a4372fd2d9ccf904aacbfd7f023",- "updated_at": "2026-05-22T20:13:39.165Z"- },- "az": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "c26844ec50b2abfbb002767fb5c6c9c3982ec65789435bbc134bf1a7b50bf84a",- "updated_at": "2026-05-22T20:13:39.166Z"- },- "bn": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "0b1416ec3b5af8cc6415d12a9ff12ce078acca4a7bb52a7422ebde3b6ae22832",- "updated_at": "2026-05-22T20:13:39.166Z"- },- "ar": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "bc747c5ea2a387dd37dea9dc1337d9734f2ec0da38a7134573d9743e3f4d2aef",- "updated_at": "2026-05-22T20:13:39.167Z"- },- "cs": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "e37dce45820b53be9d3d5ead08cadb8d13e4c77597b3009bb0be4e485917f5c6",- "updated_at": "2026-05-22T20:13:39.167Z"- },- "da": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "645c382bebe0931eaad6747e33667fd094b92b3f4042549b953db798de6b1f46",- "updated_at": "2026-05-22T20:13:39.168Z"- },- "de": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "b6558f82eb67676baf4d78946a8d1e1b808f7763e5ebaf9f57948cbd1641dc0f",- "updated_at": "2026-05-22T20:13:39.168Z"- },- "es": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "afb2a2dfa74a74c3105b0ac70181d33f5eefd201efe7edb6aba0740864639fe5",- "updated_at": "2026-05-22T20:13:39.169Z"- },- "fa": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "58966769aeb71d23c55cf4aeb452f2bbe32036df8fba1d7596f3e861897d507b",- "updated_at": "2026-05-22T20:13:39.169Z"- },- "fi": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "04cf72a3b370edcb3d54361c6cc250b3af227ba183376827006c7998839740aa",- "updated_at": "2026-05-22T20:13:39.169Z"- },- "fr": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "8dca6de87c88e04396f1139ac8b6328d188defaa5abc99eeb4026f53de772ba1",- "updated_at": "2026-05-22T20:13:39.170Z"- },- "he": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "0308a2c8c5a6b6261474a76c160f3c0658c75f56a633a57bd7300b83ccb32c9d",- "updated_at": "2026-05-22T20:13:39.170Z"- },- "hi": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "a3e902c3b1812a41ccb14c9f16d2cf2e42b8c005a5d557043e582d48eda024c4",- "updated_at": "2026-05-22T20:13:39.170Z"- },- "gu": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "1bc2419db39c7c7960b065222a3e3990e9e53c4d3427ec02422e3e506aa53733",- "updated_at": "2026-05-22T20:13:39.171Z"- },- "hu": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "ec30f54810f8b5b84e3ac8bf7bc8d05acc8616d71801b672ec02f0bc225cf607",- "updated_at": "2026-05-22T20:13:39.171Z"- },- "id": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "aebd8fdad7ec4857aa1b958cda37f59681846525207d71d98d729775031afb94",- "updated_at": "2026-05-22T20:13:39.172Z"- },- "in": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "ac70a1282877f8c4f792e9235f7a6fbce3cbec4a424ce4947074bb210fe12d67",- "updated_at": "2026-05-22T20:13:39.172Z"- },- "it": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "260f10dd121441d08e15a8d511789d8f8f7a788995305ab5e8dc6d0c1a3db06e",- "updated_at": "2026-05-22T20:13:39.173Z"- },- "ja": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "83871c13e99d13d7928409b2aef182f55fe36fbb2425f8fa4bd0df0466afed28",- "updated_at": "2026-05-22T20:13:39.173Z"- },- "mr": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "0c35c5261dd3b6c6b729d14653f95cc112f3ed9829d2d41b61e5a960abc68556",- "updated_at": "2026-05-22T20:13:39.173Z"- },- "ko": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "4ea4079b37d90e90e9a32d0da290e04e38bcd6426512b50ca7be7139354bc329",- "updated_at": "2026-05-22T20:13:39.174Z"- },- "ms": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "0e8031cd987766a69afc7aaf7c3560a57736d37e7238ddccfb848d6fbeb3f212",- "updated_at": "2026-05-22T20:13:39.174Z"- },- "nl": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "27e554c3a9b86db1f04539fcac18d3e75e6599d4de9f5ac0cf789a136b5737d4",- "updated_at": "2026-05-22T20:13:39.174Z"- },- "phi": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "f955af44cc0e8e87a2a7b12313f0dfad9aae1a50d7855e74c8155df3601279ad",- "updated_at": "2026-05-22T20:13:39.175Z"- },- "no": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "de4e3d940ae485c85da13db4471fcc68926ec53e660d92633f01293c5db0a04d",- "updated_at": "2026-05-22T20:13:39.175Z"- },- "pl": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "de5be8961e5184431404d0021e31c3ef0857f7439fbd1c71ddc0c6828bed86bb",- "updated_at": "2026-05-22T20:13:39.175Z"- },- "ro": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "19d98b22bc77c1870b749fad6e62a41c6ef53f3cad303d1c471fba4bf7012797",- "updated_at": "2026-05-22T20:13:39.175Z"- },- "ru": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "25e0c70ec25bd24b073b9d693299c3c3d32d66a410569362719e9c9ecacd759d",- "updated_at": "2026-05-22T20:13:39.176Z"- },- "pt": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "0d31647b21af967d8d4e9ecbcfc4901a66db377a6853d7b59296a2d73f0cab12",- "updated_at": "2026-05-22T20:13:39.176Z"- },- "sk": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "9d5d0ce1c51da4959d1c306969bff0bf36d3a3492ccdbdbd82e4f4d951f32c8b",- "updated_at": "2026-05-22T20:13:39.176Z"- },- "sw": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "11cd3dc7a605eebddf4a34c13de66c713d67adb32e4242962a65c71e5a034c7e",- "updated_at": "2026-05-22T20:13:39.177Z"- },- "sv": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "93b679feb6415315ab96e08298217e66be84265a277e267ecefd25b2cef04026",- "updated_at": "2026-05-22T20:13:39.177Z"- },- "ta": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "55f3df128513a1b4a8cc3f58eb84769814589d80e1c8b8f03ab0635750a76d2d",- "updated_at": "2026-05-22T20:13:39.177Z"- },- "te": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "81019604dd1fb38dfda55c1b8cf5cf8243347be08221a5e1eb11e8c76e095fab",- "updated_at": "2026-05-22T20:13:39.178Z"- },- "tr": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "b67efd07b179be016b388dff4b8979597c0a7b2db602629cef539dbec14913ab",- "updated_at": "2026-05-22T20:13:39.178Z"- },- "th": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "a793a12dc0cba5e3641cd544f63ab23e9cfe1b80568a08770a81ffd890287eda",- "updated_at": "2026-05-22T20:13:39.179Z"- },- "ur": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "6c03049aee6d85b6fd4a3bf9b89a6204e461d3f05e9cb767e36c80af796452df",- "updated_at": "2026-05-22T20:13:39.179Z"- },- "vi": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "4d35c6898f98913a02551dcfbf4d3748b2461e2d8206d292f292acacf0fc7133",- "updated_at": "2026-05-22T20:13:39.180Z"- },- "zh-CN": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "d3f574c244d157c1fe1b9fc86192d1565df2dc6343ac9ef63c0fd3f91d97f492",- "updated_at": "2026-05-22T20:13:39.180Z"- },- "uk-UA": {- "source_hash": "c808d01e42e9aaaede590048dc327347c9e814b152c6f45f54be6df64f4f19df",- "target_hash": "ffe6357e38d56ba2595e8fb8e21db4ae91bf03d10fca50a2b722e0d0bb6c01d9",- "updated_at": "2026-05-22T20:13:39.181Z"- }- }- },- "docs/architecture/ARCHITECTURE.md": {- "source_hash": "f9b4f17a1b0331fb5500768943438411ed88a38278381680caacc37c90bfb869",- "locales": {- "pt-BR": {- "source_hash": "f9b4f17a1b0331fb5500768943438411ed88a38278381680caacc37c90bfb869",- "target_hash": "e320c6172a88a0f3b698ba1a2e9e938424ece66625765395837bcf55cc29454e",- "updated_at": "2026-05-22T20:13:39.183Z"- }- }- }- }-}diff --git a/.vscode/launch.json b/.vscode/launch.jsondeleted file mode 100644index caa4ab6868..0000000000--- a/.vscode/launch.json+++ /dev/null@@ -1,31 +0,0 @@-{- "version": "0.2.0",- "configurations": [- {- "name": "Debug Dev Server",- "type": "node",- "request": "launch",- "runtimeExecutable": "${env:HOME}/.nvm/versions/node/v22.22.2/bin/node",- "program": "${workspaceFolder}/scripts/run-next.mjs",- "args": ["dev"],- "console": "integratedTerminal",- "skipFiles": ["<node_internals>/**", "node_modules/**"]- },- {- "name": "Debug Prod Server",- "type": "node",- "request": "launch",- "program": "${workspaceFolder}/scripts/run-next.mjs",- "args": ["start"],- "console": "integratedTerminal",- "skipFiles": ["<node_internals>/**", "node_modules/**"]- },- {- "name": "Attach to Running Server",- "type": "node",- "request": "attach",- "port": 9229,- "skipFiles": ["<node_internals>/**", "node_modules/**"]- }- ]-}diff --git a/.vscode/settings.json b/.vscode/settings.jsonindex b5113dde4d..c6b72dd90d 100644--- a/.vscode/settings.json+++ b/.vscode/settings.json@@ -36,7 +36,18 @@"**/node_modules/**": true,"**/.next/**": true,"**/coverage/**": true,- "**/_tasks/**": true+ "**/_tasks/**": true,+ "**/.git/objects/**": true,+ "**/dist/**": true,+ "**/build/**": true,+ "**/out/**": true,+ "**/.cache/**": true,+ "**/.turbo/**": true,+ "**/OmniRoute-*/**": true,+ "**/*-merge-*/**": true,+ "**/*-worktree-*/**": true,+ "**/*-issues-*/**": true,+ "**/*-reorg*/**": true},"search.exclude": {"**/_references": true,@@ -45,6 +56,14 @@"**/node_modules": true,"**/.next": true,"**/coverage": true,- "**/_tasks": true+ "**/_tasks": true,+ "**/dist": true,+ "**/build": true,+ "**/out": true,+ "**/OmniRoute-*": true,+ "**/*-merge-*": true,+ "**/*-worktree-*": true,+ "**/*-issues-*": true,+ "**/*-reorg*": true}}diff --git a/@omniroute/opencode-plugin/src/index.ts b/@omniroute/opencode-plugin/src/index.tsindex 3b1f496ef4..c6cc851058 100644--- a/@omniroute/opencode-plugin/src/index.ts+++ b/@omniroute/opencode-plugin/src/index.ts@@ -595,7 +595,7 @@ export function mapRawModelToModelV2(video: outMods.has("video"),pdf: outMods.has("pdf"),},- interleaved: false,+ interleaved: Boolean(caps.thinking),},cost: {input: 0,@@ -845,7 +845,7 @@ export function mapComboToModelV2(video: modalityAllHave(memberOutMods, "video"),pdf: modalityAllHave(memberOutMods, "pdf"),},- interleaved: false,+ interleaved: hasMembers && members.every((m) => Boolean(m.capabilities?.thinking)),};return {diff --git a/CHANGELOG.md b/CHANGELOG.mdindex eb83657aba..56b4b2d113 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,49 @@---+## [3.8.10] — 2026-06-04++OAuth resilience & observability release: spaced/sequential quota sync for OAuth accounts, a per-provider proactive-refresh skip list to keep short-TTL providers (Kimi) alive without re-exposing the Codex Auth0 cascade, token-expiry visibility on the provider cards, a new provider-stats dashboard, plus a wide batch of provider fixes (DeepSeek-web tool calls, Antigravity, Qoder, MiniMax, GitHub Copilot, Fireworks, llama.cpp, t3.chat-web, Kiro, Kilocode) and Podman deployment support.++### ✨ New Features++- **dashboard:** new Provider Stats page + `/api/provider-stats` endpoint — per-provider and per-model aggregates from `call_logs` plus live combo/telemetry/tool-latency overlays. (#3175 — thanks @pizzav-xyz / @diegosouzapw)+- **metrics:** cross-request TTFT and gap-after-tool-call latency tracking, aggregated per provider. (#3173 — thanks @pizzav-xyz / @diegosouzapw)+- **quota:** show the OAuth token expiry on provider cards (small, blue, informative — "Token expires in …" / "Token expired"). (#3178 — thanks @diegosouzapw)+- **responses:** strip `previous_response_id` for stateless Responses upstreams, with an auto/strip/preserve setting + UI so stateless clients (e.g. VS Code Custom Endpoint) keep context. (#3143 — thanks @JxnLexn)+- **deploy:** Podman/rootless deployment support (contrib units + `CONTAINER_HOST` hint) and larger upload body-size limits for `/v1/files`. (#3128 — thanks @hartmark)++### 🔧 Bug Fixes++- **usage:** sequential + spaced OAuth quota sync (`PROVIDER_LIMITS_SYNC_SPACING_MS`) so a host no longer bursts simultaneous usage/refresh requests; reactive forced re-mint after a 401 on the per-card refresh (recovers imported accounts); a genuine 401 now surfaces a re-authenticate hint. (#3156 — thanks @diegosouzapw)+- **healthcheck:** per-provider proactive-refresh skip list (`OMNIROUTE_HEALTHCHECK_SKIP_PROVIDERS`) — keep rotating-cascade providers (Codex/OpenAI) reactive-only while short-TTL providers (Kimi-coding) keep refreshing proactively. (#3159 — thanks @diegosouzapw)+- **providers:** on `?refresh=true` with no remote models, don't resurface the just-cleared synced cache into the local-catalog fallback. (#3181 — thanks @diegosouzapw)+- **providers:** use synced models as the authoritative local catalog across all providers (even on connections that didn't run the sync). (#3148 — thanks @herjarsa)+- **web-tools:** parse bare-JSON tool calls for DeepSeek-web with fuzzy tool-name matching scoped to the requested tools. (#3157 — thanks @wilsonicdev)+- **responses:** normalize `image_url` parts across every Responses input path (message content, replayed output items, `function_call_output`) to avoid upstream 400s. (#3150 — thanks @wilsonicdev)+- **antigravity:** dynamic upstream model resolution via the MITM alias table (server-only executor), with a guard against corrupted alias values. (#3144 — thanks @herjarsa)+- **qoder:** bifurcate validation by token type — PAT (`pt-`) → Cosy, regular API key → dashscope — matching the executor's routing. (#3149 — thanks @herjarsa)+- **api-manager:** preserve API key expiration in local time (the `datetime-local` input no longer silently shifts to UTC) + a clear button. (#3146 — thanks @xz-dev)+- **opencode-plugin:** map `caps.thinking → ModelV2.capabilities.interleaved` for single models and combos. (#3138 — thanks @mrmm)+- **kiro:** optional `targetProvider` on the social-OAuth exchange so Kiro-based providers can reuse the social login flow. (#3176 — thanks @pizzav-xyz)+- **misc:** broaden the DeepSeek reasoning-replay regex (`-free` / `zen/deepseek-v4`), export `ProviderProfile`, and guard a non-string directory entry in the binary manager. (#3177 — thanks @pizzav-xyz)+- **providerRegistry:** point kilocode at the OpenAI format + default executor (matching its sibling `kilo-gateway`). (#3166 — thanks @androw)+- **fireworks:** preserve fully-qualified router/model IDs so Fire Pass router IDs (`accounts/fireworks/routers/...`) are no longer double-prefixed into an upstream 404. (#3133 — thanks @KooshaPari)+- **llama-cpp:** route requests to the configured local baseUrl instead of OpenAI's API (which returned an OpenAI-worded 401). (#3136 — thanks @tjengbudi)+- **t3-chat-web:** parse cookies + convexSessionId from the single stored credential so t3.chat web connections work (the executor previously read fields the credential pipeline never produced). (#3007 — thanks @minhtran162)+- **minimax:** stop capping MiniMax-M3 / MiniMax-M2.7 `max_tokens` at the 8192 default — add the M3 model spec (512K output) and make model-spec lookups case-insensitive. (#3141 — thanks @totaltube)+- **github-copilot:** discover the model catalog live from `api.githubcopilot.com/models` so Import Models refreshes and only entitled models are listed (with fallback to the static catalog). (#3120, #3121 — thanks @gabrielmoreira)+- **combo:** invalidate the nested-combo cache on combo edits so removed targets/models stop being served within the 10s window; log the resolved DATA_DIR at startup to diagnose multi-replica volume mismatches. (#3147 — thanks @ViFigueiredo)+- **providers:** resolve web-provider alias collisions. (thanks @diegosouzapw)++### 📝 Maintenance++- **deps:** bump hono from 4.12.18 to 4.12.23. (#3179 — thanks @dependabot)+- **ci(electron):** make the macOS-arm64 smoke step best-effort (headless GPU crash). (#3137 — thanks @diegosouzapw)+- **chore(release):** open the v3.8.10 development cycle. (thanks @diegosouzapw)++---+## [3.8.9] — 2026-06-03### ✨ New Featuresdiff --git a/ONBOARDING.md b/ONBOARDING.mddeleted file mode 100644index e0cba2070d..0000000000--- a/ONBOARDING.md+++ /dev/null@@ -1,72 +0,0 @@-# Welcome to OmniRoute--## How We Use Claude--Based on diegosouzapw's usage over the last 30 days:--Work Type Breakdown:-Build Feature ████████████████████ 50%-Plan Design ██████████░░░░░░░░░░ 25%-Improve Quality ██████░░░░░░░░░░░░░░ 15%-Write Docs ████░░░░░░░░░░░░░░░░ 10%--Top Skills & Commands:-_no slash commands captured in this window_--Top MCP Servers:-_no MCP usage captured in this window_--## Your Setup Checklist--### Codebases--- [ ] omniroute — https://github.com/diegosouzapw/omniroute-- [ ] OpenCode_Ecosystem (fork) — https://github.com/diegosouzapw/OpenCode_Ecosystem-- [ ] OpenCode_Ecosystem (upstream) — https://github.com/MarceloClaro/OpenCode_Ecosystem--### MCP Servers to Activate--- [ ] _none required from current usage. If you'll be working on OmniRoute itself, ask the team about the project's own embedded MCP server at `/api/mcp/stream`._--### Skills to Know About--- _no skills surfaced from usage data. The team's workflow leaned heavily on direct file edits, git/gh CLI, and subagent dispatch for parallel work — Claude figures these out from context._--## Team Tips--- **Read `CLAUDE.md` first.** It has hard rules that override defaults — e.g. never write raw SQL in routes (use `src/lib/db/` modules), never add `Co-Authored-By: Claude` to commits, error responses must go through `buildErrorBody()` / `sanitizeErrorMessage()`.-- **Subagents for parallel work.** When tasks are independent, dispatch multiple sonnet subagents in one message instead of doing them yourself. Always audit `git diff` after a subagent finishes — its summary describes intent, not necessarily the result.-- **Conventional Commits** for everything: `feat(scope):`, `fix(scope):`, `chore(scope):`, `docs:`. Scopes used here include `db`, `sse`, `oauth`, `dashboard`, `api`, `agents`, `plugin`, `skills`, `commands`.-- **Run the full validation suite before declaring done** — `npm run check` (lint + tests) at minimum; `npm run test:coverage` if you changed production code. Hard gate: 75/75/75/70 (statements/lines/functions/branches).-- **Husky pre-push runs unit tests.** Don't `--no-verify` past it without explicit approval — the project documents this as a hard rule.--## Get Started--- Clone the repo and run `npm install` (auto-generates `.env` from `.env.example`).-- Generate secrets: `openssl rand -base64 48` for `JWT_SECRET`, `openssl rand -hex 32` for `API_KEY_SECRET`. Paste into `.env`.-- `npm run dev` → dashboard at `http://localhost:20128`.-- Read `docs/architecture/REPOSITORY_MAP.md` for the file layout, then `docs/architecture/ARCHITECTURE.md` for how requests flow.-- For a first PR: pick something from `_tasks/` if there's a backlog, or grep for `// TODO` and pick a small one. Run `npm run check` before opening the PR.--<!-- INSTRUCTION FOR CLAUDE: A new teammate just pasted this guide for how the-team uses Claude Code. You're their onboarding buddy — warm, conversational,-not lecture-y.--Open with a warm welcome — include the team name from the title. Then: "Your-teammate uses Claude Code for Build Feature, Plan Design, Improve Quality, and-Write Docs work. Let's get you started."--Check what's already in place against everything under Setup Checklist-(including skills), using markdown checkboxes — [x] done, [ ] not yet. Lead-with what they already have. One sentence per item, all in one message.--Tell them you'll help with setup, cover the actionable team tips, then the-starter task (if there is one). Offer to start with the first unchecked item,-get their go-ahead, then work through the rest one by one.--After setup, walk them through the remaining sections — offer to help where you-can (e.g. link to channels), and just surface the purely informational bits.--Don't invent sections or summaries that aren't in the guide. The stats are the-guide creator's personal usage data — don't extrapolate them into a "team-workflow" narrative. -->diff --git a/README.md b/README.mdindex ab938f7545..5bfa7ec184 100644--- a/README.md+++ b/README.md@@ -540,6 +540,22 @@ devbox run npm run dev📖 [Docker Guide](docs/guides/DOCKER_GUIDE.md) — Compose profiles, Caddy HTTPS, Cloudflare tunnels.+**🦭 Podman**++```bash+# 1. Build the image+podman build --target runner-base -t omniroute:base .++# 2. Fix data directory permissions for rootless Podman+mkdir -p data && podman unshare chown 1000:1000 ./data++# 3. Set runtime in .env, then run (see contrib/podman/ for Quadlet)+echo "CONTAINER_HOST=podman" >> .env+podman compose --profile base up -d+```++📖 [Podman Guide](contrib/podman/README.md) — Quadlet setup, podman-compose, Quadlet.+</details><br/>@@ -779,6 +795,7 @@ Compression: aggressive (~50%) → double your free quota · Cost: $0/mo| Document | Description || ---------------------------------------------------- | -------------------------------------------------------------- || [Docker Guide](docs/guides/DOCKER_GUIDE.md) | Docker run, Compose profiles, Caddy HTTPS, tunnels, image tags |+| [Podman Guide](contrib/podman/README.md) | Quadlet systemd integration, podman-compose, SELinux || [VM Deployment](docs/ops/VM_DEPLOYMENT_GUIDE.md) | Complete guide: VM + nginx + Cloudflare setup || [Fly.io Deployment](docs/ops/FLY_IO_DEPLOYMENT_GUIDE.md) | Deploy to Fly.io with persistent storage || [Termux Guide](docs/guides/TERMUX_GUIDE.md) | Run OmniRoute on Android via Termux |diff --git a/contrib/podman/README.md b/contrib/podman/README.mdnew file mode 100644index 0000000000..7ebc6fc9b0--- /dev/null+++ b/contrib/podman/README.md@@ -0,0 +1,128 @@+# Podman Deployment++Run OmniRoute with Podman via **Quadlet** (systemd integration) or **podman compose**.++---++## Option A: Quadlet (recommended)++### 1. Build the image++```bash+cd /path/to/omniroute+podman build --target runner-base -t omniroute:base .+# For web-cookie providers (gemini-web, claude-web, claude-turnstile):+podman build --target runner-web -t omniroute:web .+# For CLI tool support:+podman build --target runner-cli -t omniroute:cli .+```++### 2. Copy Quadlet files to the systemd directory++```bash+mkdir -p ~/.config/containers/systemd/omniroute+cp contrib/podman/*.container ~/.config/containers/systemd/omniroute/+cp contrib/podman/*.network ~/.config/containers/systemd/omniroute/+cp contrib/podman/*.volume ~/.config/containers/systemd/omniroute/+```++### 3. Mount the project .env for secrets++Edit `~/.config/containers/systemd/omniroute/omniroute.container` and+uncomment/replace the `EnvironmentFile` line with the absolute path to+your project `.env`:++```+EnvironmentFile=/home/USER/code/docker/OmniRoute/.env+```++Make sure `CONTAINER_HOST=podman` is set in that `.env`.++Alternatively, edit the env vars directly in the `.container` file.++### 4. Reload systemd and start++```bash+systemctl --user daemon-reload+systemctl --user start omniroute-redis+systemctl --user start omniroute+```++### 5. Verify++```bash+systemctl --user status omniroute+curl http://localhost:20128/v1/models+```++To follow logs:++```bash+journalctl --user -u omniroute -f+```++### 6. Enable on boot++```bash+systemctl --user enable omniroute-redis+systemctl --user enable omniroute+```++---++## Option B: podman compose++The project's `docker-compose.yml` now works with both Docker and Podman.+Just set `CONTAINER_HOST=podman` in `.env` before starting.++### 1. Prepare the data directory++Rootless Podman maps container UIDs into a subordinate range. The+`node` user (UID 1000) inside the container maps to a different UID+on the host, so it cannot write to `./data` owned by your host user.++Fix the ownership **before** starting:++```bash+mkdir -p data+podman unshare chown 1000:1000 ./data+```++### 2. Set the runtime in `.env`++Make sure `.env` contains:++```env+CONTAINER_HOST=podman+```++### 3. Start++```bash+podman compose --profile base up -d+```++### Profiles++Same profiles as `docker compose`:++| Profile | Command |+| ------------------------------ | ---------------------------------------------------- |+| `base` (no CLIs) | `podman compose --profile base up -d` |+| `web` (+Chromium/Playwright) | `podman compose --profile web up -d` |+| `cli` (+CLI tools) | `podman compose --profile cli up -d` |+| `host` (host-mounted binaries) | `podman compose --profile host up -d` |+| `cliproxyapi` (sidecar) | `podman compose --profile cliproxyapi up -d` |++---++## How it works++The `docker-compose.yml` uses fully-qualified image names+(`docker.io/library/redis:7-alpine`) and flat variable expansions so it+works with both Docker and Podman without a separate compose file.++The entrypoint script (`check-permissions.sh`) reads `CONTAINER_HOST`+from `.env` to give the correct fix instructions:+- **docker**: `sudo chown -R ... ./data`+- **podman**: `podman unshare chown 1000:1000 ./data`diff --git a/contrib/podman/omniroute-redis.container b/contrib/podman/omniroute-redis.containernew file mode 100644index 0000000000..326ac92559--- /dev/null+++ b/contrib/podman/omniroute-redis.container@@ -0,0 +1,26 @@+[Unit]+Description=OmniRoute Redis (rate-limiter backend)+After=network-online.target+Wants=network-online.target++[Container]+Image=docker.io/redis:7-alpine+ContainerName=omniroute-redis++Network=omniroute.network+NetworkAlias=redis++Volume=omniroute-redis.volume:/data++Exec=redis-server --save 60 1 --loglevel warning++HealthCmd=/bin/sh -c "redis-cli ping | grep -q PONG"+HealthInterval=10s+HealthRetries=3+HealthTimeout=5s++[Service]+Restart=always++[Install]+WantedBy=default.targetdiff --git a/contrib/podman/omniroute-redis.volume b/contrib/podman/omniroute-redis.volumenew file mode 100644index 0000000000..e14c448891--- /dev/null+++ b/contrib/podman/omniroute-redis.volume@@ -0,0 +1,3 @@+# Persistent Redis data+[Volume]+Label=omniroutediff --git a/contrib/podman/omniroute.container b/contrib/podman/omniroute.containernew file mode 100644index 0000000000..846e681a27--- /dev/null+++ b/contrib/podman/omniroute.container@@ -0,0 +1,50 @@+[Unit]+Description=OmniRoute — Unified AI Proxy+After=network-online.target+Wants=network-online.target+Requires=omniroute-redis.service+After=omniroute-redis.service++[Container]+# Use this image if your building locally+Image=localhost/omniroute:base+# Use this image if you are pulling from Docker Hub+# Image=diegosouzapw/omniroute:base++ContainerName=omniroute++Network=omniroute.network+PublishPort=20128:20128+PublishPort=20129:20129++Volume=omniroute.volume:/app/data:Z++# Use a bind mount if you need direct host access to the data:+# Volume=/home/USER/code/docker/OmniRoute/data:/app/data:Z++Environment=DATA_DIR=/app/data+Environment=PORT=20128+Environment=DASHBOARD_PORT=20128+Environment=API_PORT=20129+Environment=API_HOST=0.0.0.0+Environment=REDIS_URL=redis://redis:6379+Environment=JWT_SECRET=change-me-to-a-random-base64-string+Environment=API_KEY_SECRET=change-me-to-a-random-base64-string+Environment=INITIAL_PASSWORD=change-me-to-a-random-hex-string+Environment=NODE_ENV=production+Environment=REQUIRE_API_KEY=true++# Load additional secrets (API keys, OAuth creds) from the project .env:+# EnvironmentFile=%h/code/docker/OmniRoute/.env++HealthCmd=node /app/healthcheck.mjs+HealthInterval=30s+HealthRetries=3+HealthTimeout=5s+HealthStartPeriod=15s++[Service]+Restart=always++[Install]+WantedBy=default.targetdiff --git a/contrib/podman/omniroute.network b/contrib/podman/omniroute.networknew file mode 100644index 0000000000..4f618e9943--- /dev/null+++ b/contrib/podman/omniroute.network@@ -0,0 +1,2 @@+[Network]+Label=omniroutediff --git a/contrib/podman/omniroute.volume b/contrib/podman/omniroute.volumenew file mode 100644index 0000000000..d0d3ae8cbc--- /dev/null+++ b/contrib/podman/omniroute.volume@@ -0,0 +1,3 @@+# OmniRoute persistent data (SQLite DB, logs, backups)+[Volume]+Label=omniroutediff --git a/devbox.json b/devbox.jsondeleted file mode 100644index 87fd4a2357..0000000000--- a/devbox.json+++ /dev/null@@ -1,17 +0,0 @@-{- "$schema": "https://json-schema.org/draft/2020-12/schema",- "name": "omniroute",- "version": "3.8.2",- "description": "Unified AI router with 160+ providers, RTK+Caveman compression, auto fallback, MCP/A2A, desktop, PWA, and OpenAI-compatible APIs.",- "packages": [- "nodejs_22",- ],- "shell": {- "init_hook": [- "echo 'Welcome to OmniRoute dev environment'",- ],- "hooks": {- "on_create": "npm install"- }- }-}diff --git a/devbox.lock b/devbox.lockdeleted file mode 100644index ae5d932cd6..0000000000--- a/devbox.lock+++ /dev/null@@ -1,26 +0,0 @@-{- "lockfile_version": "1",- "packages": {- "eslint": {- "resolved": "github:NixOS/nixpkgs/6dedf69f94d03cbe7bdde106f2d4c23ae2a853bf#eslint",- "source": "nixpkg"- },- "github:NixOS/nixpkgs/nixpkgs-unstable": {- "last_modified": "2026-05-22T01:51:30Z",- "resolved": "github:NixOS/nixpkgs/6dedf69f94d03cbe7bdde106f2d4c23ae2a853bf?lastModified=1779414690"- },- "nodejs_22": {- "plugin_version": "0.0.2",- "resolved": "github:NixOS/nixpkgs/6dedf69f94d03cbe7bdde106f2d4c23ae2a853bf#nodejs_22",- "source": "nixpkg"- },- "pnpm": {- "resolved": "github:NixOS/nixpkgs/6dedf69f94d03cbe7bdde106f2d4c23ae2a853bf#pnpm",- "source": "nixpkg"- },- "typescript": {- "resolved": "github:NixOS/nixpkgs/6dedf69f94d03cbe7bdde106f2d4c23ae2a853bf#typescript",- "source": "nixpkg"- }- }-}diff --git a/docker-compose.yml b/docker-compose.ymlindex 8a249e335f..e30f4c0d2a 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -27,7 +27,7 @@ x-common: &commonenvironment:- DATA_DIR=/app/data # Must match the volume mount below- PORT=${PORT:-20128}- - DASHBOARD_PORT=${DASHBOARD_PORT:-${PORT:-20128}}+ - DASHBOARD_PORT=${DASHBOARD_PORT:-20128}- API_PORT=${API_PORT:-20129}- API_HOST=${API_HOST:-0.0.0.0}- REDIS_URL=${REDIS_URL:-redis://redis:6379}@@ -43,7 +43,7 @@ x-common: &commonservices:# ── Redis (Rate Limiter Backend) ──────────────────────────────────redis:- image: redis:7-alpine+ image: docker.io/library/redis:7-alpinecontainer_name: omniroute-redisrestart: unless-stoppedports:@@ -66,7 +66,7 @@ services:target: runner-baseimage: omniroute:baseports:- - "${DASHBOARD_PORT:-${PORT:-20128}}:${DASHBOARD_PORT:-${PORT:-20128}}"+ - "${DASHBOARD_PORT:-20128}:${DASHBOARD_PORT:-20128}"- "${API_PORT:-20129}:${API_PORT:-20129}"profiles:- base@@ -83,7 +83,7 @@ services:target: runner-webimage: omniroute:webports:- - "${DASHBOARD_PORT:-${PORT:-20128}}:${DASHBOARD_PORT:-${PORT:-20128}}"+ - "${DASHBOARD_PORT:-20128}:${DASHBOARD_PORT:-20128}"- "${API_PORT:-20129}:${API_PORT:-20129}"profiles:- web@@ -97,7 +97,7 @@ services:target: runner-cliimage: omniroute:cliports:- - "${DASHBOARD_PORT:-${PORT:-20128}}:${DASHBOARD_PORT:-${PORT:-20128}}"+ - "${DASHBOARD_PORT:-20128}:${DASHBOARD_PORT:-20128}"- "${API_PORT:-20129}:${API_PORT:-20129}"volumes:- ./data:/app/data@@ -116,12 +116,12 @@ services:target: runner-baseimage: omniroute:baseports:- - "${DASHBOARD_PORT:-${PORT:-20128}}:${DASHBOARD_PORT:-${PORT:-20128}}"+ - "${DASHBOARD_PORT:-20128}:${DASHBOARD_PORT:-20128}"- "${API_PORT:-20129}:${API_PORT:-20129}"environment:- DATA_DIR=/app/data- PORT=${PORT:-20128}- - DASHBOARD_PORT=${DASHBOARD_PORT:-${PORT:-20128}}+ - DASHBOARD_PORT=${DASHBOARD_PORT:-20128}- API_PORT=${API_PORT:-20129}- API_HOST=${API_HOST:-0.0.0.0}- CLI_MODE=hostdiff --git a/docs/i18n/ar/CHANGELOG.md b/docs/i18n/ar/CHANGELOG.mdindex 8d813ea526..89f7968ef9 100644--- a/docs/i18n/ar/CHANGELOG.md+++ b/docs/i18n/ar/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/az/CHANGELOG.md b/docs/i18n/az/CHANGELOG.mdindex 73d9da67fd..3461875e4d 100644--- a/docs/i18n/az/CHANGELOG.md+++ b/docs/i18n/az/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/bg/CHANGELOG.md b/docs/i18n/bg/CHANGELOG.mdindex 73d9da67fd..3461875e4d 100644--- a/docs/i18n/bg/CHANGELOG.md+++ b/docs/i18n/bg/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/bn/CHANGELOG.md b/docs/i18n/bn/CHANGELOG.mdindex 5ddd912d40..9242a74359 100644--- a/docs/i18n/bn/CHANGELOG.md+++ b/docs/i18n/bn/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/cs/CHANGELOG.md b/docs/i18n/cs/CHANGELOG.mdindex 483d32503d..325e28e7a6 100644--- a/docs/i18n/cs/CHANGELOG.md+++ b/docs/i18n/cs/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/da/CHANGELOG.md b/docs/i18n/da/CHANGELOG.mdindex dc8e62974c..1a8e491c17 100644--- a/docs/i18n/da/CHANGELOG.md+++ b/docs/i18n/da/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/de/CHANGELOG.md b/docs/i18n/de/CHANGELOG.mdindex 2fa62b0e48..90445e09a7 100644--- a/docs/i18n/de/CHANGELOG.md+++ b/docs/i18n/de/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/es/CHANGELOG.md b/docs/i18n/es/CHANGELOG.mdindex 9290d2fc5d..f4f5d27807 100644--- a/docs/i18n/es/CHANGELOG.md+++ b/docs/i18n/es/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/fa/CHANGELOG.md b/docs/i18n/fa/CHANGELOG.mdindex b3c02ef5ec..0f93651755 100644--- a/docs/i18n/fa/CHANGELOG.md+++ b/docs/i18n/fa/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/fi/CHANGELOG.md b/docs/i18n/fi/CHANGELOG.mdindex 0316fffb8e..6f26b40958 100644--- a/docs/i18n/fi/CHANGELOG.md+++ b/docs/i18n/fi/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/fr/CHANGELOG.md b/docs/i18n/fr/CHANGELOG.mdindex 941023cbd2..8e54d78c42 100644--- a/docs/i18n/fr/CHANGELOG.md+++ b/docs/i18n/fr/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/gu/CHANGELOG.md b/docs/i18n/gu/CHANGELOG.mdindex 1def3ed544..a6caf3e7f9 100644--- a/docs/i18n/gu/CHANGELOG.md+++ b/docs/i18n/gu/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/he/CHANGELOG.md b/docs/i18n/he/CHANGELOG.mdindex bd1bf55274..4447f1a274 100644--- a/docs/i18n/he/CHANGELOG.md+++ b/docs/i18n/he/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/hi/CHANGELOG.md b/docs/i18n/hi/CHANGELOG.mdindex 677dcce598..1e78f828b3 100644--- a/docs/i18n/hi/CHANGELOG.md+++ b/docs/i18n/hi/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/hu/CHANGELOG.md b/docs/i18n/hu/CHANGELOG.mdindex 8612e6d80a..b005468f67 100644--- a/docs/i18n/hu/CHANGELOG.md+++ b/docs/i18n/hu/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/id/CHANGELOG.md b/docs/i18n/id/CHANGELOG.mdindex e1a9c1ae77..dca5461e8b 100644--- a/docs/i18n/id/CHANGELOG.md+++ b/docs/i18n/id/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/in/CHANGELOG.md b/docs/i18n/in/CHANGELOG.mdindex d9f79c90cb..605a8895b7 100644--- a/docs/i18n/in/CHANGELOG.md+++ b/docs/i18n/in/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/it/CHANGELOG.md b/docs/i18n/it/CHANGELOG.mdindex c1ef920607..17703c984f 100644--- a/docs/i18n/it/CHANGELOG.md+++ b/docs/i18n/it/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/ja/CHANGELOG.md b/docs/i18n/ja/CHANGELOG.mdindex 8e770461ee..8bf9c38366 100644--- a/docs/i18n/ja/CHANGELOG.md+++ b/docs/i18n/ja/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/ko/CHANGELOG.md b/docs/i18n/ko/CHANGELOG.mdindex 3c6407f541..0ba8b00b7c 100644--- a/docs/i18n/ko/CHANGELOG.md+++ b/docs/i18n/ko/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/mr/CHANGELOG.md b/docs/i18n/mr/CHANGELOG.mdindex af8e27de0f..71e9564821 100644--- a/docs/i18n/mr/CHANGELOG.md+++ b/docs/i18n/mr/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/ms/CHANGELOG.md b/docs/i18n/ms/CHANGELOG.mdindex e58a6e0cd4..d8f8cb2ed4 100644--- a/docs/i18n/ms/CHANGELOG.md+++ b/docs/i18n/ms/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/nl/CHANGELOG.md b/docs/i18n/nl/CHANGELOG.mdindex f6e37359fb..04fb8e7692 100644--- a/docs/i18n/nl/CHANGELOG.md+++ b/docs/i18n/nl/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/no/CHANGELOG.md b/docs/i18n/no/CHANGELOG.mdindex 2e2b5b04f1..73b7bc4f5f 100644--- a/docs/i18n/no/CHANGELOG.md+++ b/docs/i18n/no/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/phi/CHANGELOG.md b/docs/i18n/phi/CHANGELOG.mdindex 2e28617805..97a0b4e6ea 100644--- a/docs/i18n/phi/CHANGELOG.md+++ b/docs/i18n/phi/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/pl/CHANGELOG.md b/docs/i18n/pl/CHANGELOG.mdindex 1f66b35766..947a301e05 100644--- a/docs/i18n/pl/CHANGELOG.md+++ b/docs/i18n/pl/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/pt-BR/CHANGELOG.md b/docs/i18n/pt-BR/CHANGELOG.mdindex bebdacc5c2..5cb2163a4e 100644--- a/docs/i18n/pt-BR/CHANGELOG.md+++ b/docs/i18n/pt-BR/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/pt/CHANGELOG.md b/docs/i18n/pt/CHANGELOG.mdindex 0592522bfe..e22a033244 100644--- a/docs/i18n/pt/CHANGELOG.md+++ b/docs/i18n/pt/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/ro/CHANGELOG.md b/docs/i18n/ro/CHANGELOG.mdindex 6387aa3f5d..5823515864 100644--- a/docs/i18n/ro/CHANGELOG.md+++ b/docs/i18n/ro/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/ru/CHANGELOG.md b/docs/i18n/ru/CHANGELOG.mdindex 5b6368d1cb..9bfb7479a8 100644--- a/docs/i18n/ru/CHANGELOG.md+++ b/docs/i18n/ru/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/sk/CHANGELOG.md b/docs/i18n/sk/CHANGELOG.mdindex 45e56f92e2..264c15d459 100644--- a/docs/i18n/sk/CHANGELOG.md+++ b/docs/i18n/sk/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/sv/CHANGELOG.md b/docs/i18n/sv/CHANGELOG.mdindex 010a5181be..ba65e04af0 100644--- a/docs/i18n/sv/CHANGELOG.md+++ b/docs/i18n/sv/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/sw/CHANGELOG.md b/docs/i18n/sw/CHANGELOG.mdindex 7fc8f13f92..8f926685ab 100644--- a/docs/i18n/sw/CHANGELOG.md+++ b/docs/i18n/sw/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/ta/CHANGELOG.md b/docs/i18n/ta/CHANGELOG.mdindex 0654f98f37..a3c681eb05 100644--- a/docs/i18n/ta/CHANGELOG.md+++ b/docs/i18n/ta/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/te/CHANGELOG.md b/docs/i18n/te/CHANGELOG.mdindex 7b769d11a3..fc4413b994 100644--- a/docs/i18n/te/CHANGELOG.md+++ b/docs/i18n/te/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/th/CHANGELOG.md b/docs/i18n/th/CHANGELOG.mdindex 0915802f7e..9304df4180 100644--- a/docs/i18n/th/CHANGELOG.md+++ b/docs/i18n/th/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/tr/CHANGELOG.md b/docs/i18n/tr/CHANGELOG.mdindex f392b89bdc..d6cb2a0ccf 100644--- a/docs/i18n/tr/CHANGELOG.md+++ b/docs/i18n/tr/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/uk-UA/CHANGELOG.md b/docs/i18n/uk-UA/CHANGELOG.mdindex 9c5c8858e9..89e8526c08 100644--- a/docs/i18n/uk-UA/CHANGELOG.md+++ b/docs/i18n/uk-UA/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/ur/CHANGELOG.md b/docs/i18n/ur/CHANGELOG.mdindex 222b46f47b..22b814a53d 100644--- a/docs/i18n/ur/CHANGELOG.md+++ b/docs/i18n/ur/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/vi/CHANGELOG.md b/docs/i18n/vi/CHANGELOG.mdindex 2144352d09..eefcd9ee09 100644--- a/docs/i18n/vi/CHANGELOG.md+++ b/docs/i18n/vi/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/i18n/zh-CN/CHANGELOG.md b/docs/i18n/zh-CN/CHANGELOG.mdindex d79a366b57..730f389926 100644--- a/docs/i18n/zh-CN/CHANGELOG.md+++ b/docs/i18n/zh-CN/CHANGELOG.md@@ -4,6 +4,10 @@---+## [3.8.10] — Unreleased++---+## [3.8.9] — Unreleased---diff --git a/docs/reference/ENVIRONMENT.md b/docs/reference/ENVIRONMENT.mdindex c3be99fc53..67e2b6156a 100644--- a/docs/reference/ENVIRONMENT.md+++ b/docs/reference/ENVIRONMENT.md@@ -350,6 +350,7 @@ detection above).| `OMNIROUTE_MCP_DESCRIPTION_COMPRESSION` | `rtk` | `open-sse/mcp-server/descriptionCompressor.ts` | Compression algorithm/profile. Disable values: `0`, `false`, `off`. || `MODEL_SYNC_INTERVAL_HOURS` | `24` | `src/shared/services/modelSyncScheduler.ts` | Model catalog sync interval in hours. || `PROVIDER_LIMITS_SYNC_INTERVAL_MINUTES` | `70` | `src/server-init.ts` | Provider rate-limit and quota polling interval. |+| `PROVIDER_LIMITS_SYNC_SPACING_MS` | `1500` | `src/lib/usage/providerLimits.ts` | Gap (ms) between consecutive OAuth quota fetches in a bulk sync; OAuth connections are fetched one at a time to avoid bursting an upstream. `0` opts out (concurrent). || `OMNIROUTE_DISABLE_BACKGROUND_SERVICES` | `false` | `src/instrumentation-node.ts` | Disable all background services (sync, pricing, model refresh). Useful for CI/test. || `OMNIROUTE_ENABLE_RUNTIME_BACKGROUND_TASKS` | _(unset)_ | `src/lib/config/runtimeSettings.ts` | Force background tasks on under automated test detection. Set `1` to override the test heuristic. || `OMNIROUTE_BUDGET_RESET_JOB_INTERVAL_MS` | `600000` | `src/lib/jobs/budgetResetJob.ts` | Budget reset check cadence (ms). Floor `10000`. |@@ -877,6 +878,7 @@ Provider quota endpoints, network tunnels (Tailscale, Ngrok, MITM debug proxy),| `DB_BACKUP_MAX_FILES` | `20` | `src/lib/db/backup.ts` | Maximum SQLite backup files retained on disk. || `DB_BACKUP_RETENTION_DAYS` | `0` | `src/lib/db/backup.ts` | Maximum age (days) of retained backups. `0` disables age-based pruning. || `OMNIROUTE_TLS_PROXY_URL` | _(unset)_ | `open-sse/services/chatgptTlsClient.ts` | Override the TLS sidecar URL for tests. Production should leave unset. |+| `CONTAINER_HOST` | `docker` | `scripts/check-permissions.sh` | Container runtime hint for the entrypoint permission check. Set to `podman` under rootless Podman so the fix instructions use `podman unshare chown` instead of `sudo chown`. || `QUOTA_STORE_DRIVER` | `sqlite` | `src/lib/quota/storeFactory.ts` | Quota-share consumption store backend: `sqlite` (default) or `redis`. || `QUOTA_STORE_REDIS_URL` | _(unset)_ | `src/lib/quota/storeFactory.ts` | Redis connection string used when `QUOTA_STORE_DRIVER=redis` (e.g. `redis://localhost:6379`). || `QUOTA_SATURATION_THRESHOLD` | `0.5` | `src/lib/quota/enforce.ts` | Pool saturation ratio (0..1); at/above it the pool enters strict mode (no borrowing). |@@ -909,6 +911,7 @@ value below unset in production deployments.| `OMNIROUTE_E2E_PASSWORD` | falls back to `INITIAL_PASSWORD` | `scripts/dev/run-next-playwright.mjs` | Admin password injected into the Playwright environment. || `OMNIROUTE_DISABLE_LOCAL_HEALTHCHECK` | `true` | `scripts/dev/run-next-playwright.mjs` | Disable the local healthcheck poll during Playwright runs. || `OMNIROUTE_DISABLE_TOKEN_HEALTHCHECK` | `true` | `scripts/dev/run-next-playwright.mjs` | Disable the OAuth token healthcheck loop during tests. |+| `OMNIROUTE_HEALTHCHECK_SKIP_PROVIDERS` | _(unset)_ | `src/lib/tokenHealthCheck.ts` | Comma-separated providers excluded from the proactive token-refresh sweep (e.g. `codex,openai`). Targeted alternative to fully disabling the healthcheck — short-TTL providers keep refreshing while cascade providers stay reactive-only. || `OMNIROUTE_HIDE_HEALTHCHECK_LOGS` | `true` | `scripts/dev/run-next-playwright.mjs` | Silence healthcheck noise in Playwright stdout. || `OMNIROUTE_PLAYWRIGHT_SKIP_BUILD` | `0` | `scripts/dev/run-next-playwright.mjs` | Skip the Next.js production build before Playwright starts (CI optimization). || `OMNIROUTE_SKIP_UNINSTALL_HOOK` | `0` | `scripts/build/uninstall.mjs` | Skip the OmniRoute uninstall hook (used by CI to keep `node_modules` intact). |diff --git a/docs/reference/openapi.yaml b/docs/reference/openapi.yamlindex c67478f664..38341c8d90 100644--- a/docs/reference/openapi.yaml+++ b/docs/reference/openapi.yaml@@ -1,7 +1,7 @@openapi: 3.1.0info:title: OmniRoute API- version: 3.8.9+ version: 3.8.10description: |OmniRoute is a local-first AI API proxy router. It provides an OpenAI-compatibleendpoint that routes requests to multiple AI providers with load balancing,diff --git a/electron/package.json b/electron/package.jsonindex 660a4760e8..a8da362d8e 100644--- a/electron/package.json+++ b/electron/package.json@@ -1,6 +1,6 @@{"name": "omniroute-desktop",- "version": "3.8.9",+ "version": "3.8.10","description": "OmniRoute Desktop Application","main": "main.js","author": {diff --git a/next.config.mjs b/next.config.mjsindex ce4252d2bf..1dc08a6dcf 100644--- a/next.config.mjs+++ b/next.config.mjs@@ -104,6 +104,10 @@ const nextConfig = {serverActions: {bodySizeLimit: process.env.OMNIROUTE_SERVER_ACTIONS_BODY_LIMIT || "50mb",},+ // Next.js proxy (middleware) has a default 10MB body clone limit. File+ // uploads (OpenAI-compatible /v1/files) routinely exceed this. Match the+ // 512 MB server-side cap; tune via env if needed.+ proxyClientMaxBodySize: process.env.NEXT_PROXY_BODY_LIMIT || "512mb",},outputFileTracingRoot: projectRoot,outputFileTracingIncludes: {diff --git a/open-sse/config/providerRegistry.ts b/open-sse/config/providerRegistry.tsindex fb304d7964..c0a89b8e6a 100644--- a/open-sse/config/providerRegistry.ts+++ b/open-sse/config/providerRegistry.ts@@ -112,6 +112,12 @@ export interface RegistryEntry {modelsUrl?: string;/** Prefix to prepend to model IDs before upstream API calls (e.g. "accounts/fireworks/models/") */modelIdPrefix?: string;+ /**+ * Additional already-qualified model ID prefixes that must NOT receive `modelIdPrefix`+ * (e.g. Fireworks router IDs "accounts/fireworks/routers/"). Prevents double-prefixing+ * fully-qualified IDs that legitimately differ from `modelIdPrefix`. See issue #3133.+ */+ acceptedModelIdPrefixes?: string[];chatPath?: string;clientVersion?: string;timeoutMs?: number;@@ -1861,8 +1867,8 @@ const _REGISTRY_EAGER: Record<string, RegistryEntry> = {kilocode: {id: "kilocode",alias: "kc",- format: "openrouter",- executor: "openrouter",+ format: "openai",+ executor: "default",baseUrl: "https://api.kilo.ai/api/openrouter/chat/completions",modelsUrl: "https://api.kilo.ai/api/openrouter/models",authType: "oauth",@@ -2437,7 +2443,9 @@ const _REGISTRY_EAGER: Record<string, RegistryEntry> = {huggingchat: {id: "huggingchat",- alias: "hc",+ // Distinct alias: "hc" belongs to the hackclub provider; huggingchat is+ // addressed by its own id to avoid the alias collision.+ alias: "huggingchat",format: "openai",executor: "huggingchat",baseUrl: "https://huggingface.co/chat/conversation",@@ -3035,6 +3043,7 @@ const _REGISTRY_EAGER: Record<string, RegistryEntry> = {modelsUrl:"https://api.fireworks.ai/v1/accounts/fireworks/models?filter=supports_serverless=true",modelIdPrefix: "accounts/fireworks/models/",+ acceptedModelIdPrefixes: ["accounts/fireworks/models/", "accounts/fireworks/routers/"],authType: "apikey",authHeader: "bearer",models: [@@ -3863,7 +3872,9 @@ const _REGISTRY_EAGER: Record<string, RegistryEntry> = {"kimi-web": {id: "kimi-web",- alias: "kimi",+ // Distinct alias: the primary "kimi" provider (dedicated KimiExecutor) keeps+ // the short "kimi" alias; this web/cookie variant is addressed by its own id.+ alias: "kimi-web",format: "openai",executor: "kimi-web",baseUrl: "https://kimi.moonshot.cn/api/chat",@@ -3891,7 +3902,9 @@ const _REGISTRY_EAGER: Record<string, RegistryEntry> = {"qwen-web": {id: "qwen-web",- alias: "qw",+ // Distinct alias: the primary "qwen" provider keeps the short "qw" alias;+ // this web/cookie variant is addressed by its own id.+ alias: "qwen-web",format: "openai",executor: "qwen-web",baseUrl: "https://chat.qwen.ai/api/chat/completions",diff --git a/open-sse/executors/antigravity.ts b/open-sse/executors/antigravity.tsindex 791e8cc273..d4e588b95e 100644--- a/open-sse/executors/antigravity.ts+++ b/open-sse/executors/antigravity.ts@@ -29,6 +29,7 @@ import {handleCreditsFailure,} from "../services/antigravityCredits.ts";import { persistCreditBalance, getAllPersistedCreditBalances } from "@/lib/db/creditBalance";+import { getMitmAlias } from "@/lib/db/models";import { obfuscateSensitiveWords } from "../services/antigravityObfuscation.ts";import { resolveAntigravityVersion } from "../services/antigravityVersion.ts";import { ensureAntigravityProjectAssigned } from "../services/antigravityProjectBootstrap.ts";@@ -401,12 +402,38 @@ function flushAntigravitySSEText(* Strip provider prefixes (e.g. "antigravity/model" → "model").* Ensures the model name sent to the upstream API never contains a routing prefix.*/-function cleanModelName(model: string): string {+async function cleanModelName(model: string): Promise<string> {if (!model) return model;- let clean = model.includes("/") ? model.split("/").pop()! : model;- clean = resolveAntigravityModelId(clean);- // Normalize bare Pro IDs to the Low tier (matching OpenClaw convention).- // The upstream API requires an explicit tier suffix; bare IDs cause errors.+ const stripped = model.includes("/") ? model.split("/").pop()! : model;+ let clean = stripped;++ // 1. Check dynamic MITM aliases first (authoritative after first sync).+ // Built during model sync — contains ONLY currently-available models.+ // Obsolete/removed models are automatically excluded.+ try {+ const mitmAliases = await getMitmAlias("antigravity");+ if (mitmAliases && typeof mitmAliases === "object") {+ const aliases = mitmAliases as Record<string, unknown>;+ const raw = aliases[stripped];+ // Only honor string aliases; corrupted/non-string DB values fall through+ // to the static alias resolution below (never return undefined here).+ if (typeof raw === "string" && raw) {+ // Strip the "antigravity/" prefix if present; use the raw model ID otherwise.+ const PREFIX = "antigravity/";+ clean = raw.startsWith(PREFIX) ? raw.slice(PREFIX.length) : raw;+ }+ }+ } catch {+ // DB not available (build phase, transient error) — fall through to static aliases+ }++ // 2. Fall back to static aliases if MITM didn't resolve+ if (clean === stripped) {+ clean = resolveAntigravityModelId(clean);+ }++ // 3. Normalize bare Pro IDs to the Low tier (matching OpenClaw convention).+ // The upstream API requires an explicit tier suffix; bare IDs cause errors.if (BARE_PRO_IDS.has(clean)) {clean = `${clean}-low`;}@@ -610,7 +637,7 @@ export class AntigravityExecutor extends BaseExecutor {return resp as unknown as never;}- const upstreamModel = cleanModelName(model);+ const upstreamModel = await cleanModelName(model);const isClaude = upstreamModel.toLowerCase().includes("claude");const baseBody = bodyRecord;const normalizedBody = shouldStripCloudCodeThinking(this.provider, upstreamModel)diff --git a/open-sse/executors/deepseek-web.ts b/open-sse/executors/deepseek-web.tsindex 2cb4bd9423..55b10aa2da 100644--- a/open-sse/executors/deepseek-web.ts+++ b/open-sse/executors/deepseek-web.ts@@ -1031,7 +1031,8 @@ export class DeepSeekWebExecutor extends BaseExecutor {await cleanupFn();const { content: cleanedContent, toolCalls } = parseToolCallsFromText(content,- `call-${Date.now()}`+ `call-${Date.now()}`,+ requestedTools);return buildToolAwareResult({stream: stream !== false,diff --git a/open-sse/executors/default.ts b/open-sse/executors/default.tsindex 8595e82d39..0d0e9989b0 100644--- a/open-sse/executors/default.ts+++ b/open-sse/executors/default.ts@@ -205,6 +205,7 @@ export class DefaultExecutor extends BaseExecutor {const baseUrl = credentials?.providerSpecificData?.baseUrl || this.config.baseUrl;return normalizeOpenAIChatUrl(baseUrl);}+ case "llama-cpp":case "lm-studio":case "modal":case "reka":@@ -510,8 +511,16 @@ export class DefaultExecutor extends BaseExecutor {const entry = getRegistryEntry(this.provider);if (entry?.modelIdPrefix) {const body = withDefaults as Record<string, unknown>;- if (typeof body.model === "string" && !body.model.startsWith(entry.modelIdPrefix)) {- body.model = `${entry.modelIdPrefix}${body.model}`;+ if (typeof body.model === "string") {+ // Skip prepending when the model already carries the canonical prefix OR any+ // other accepted fully-qualified prefix (e.g. Fireworks router IDs). #3133.+ const acceptedPrefixes = [entry.modelIdPrefix, ...(entry.acceptedModelIdPrefixes ?? [])];+ const alreadyQualified = acceptedPrefixes.some((prefix) =>+ (body.model as string).startsWith(prefix)+ );+ if (!alreadyQualified) {+ body.model = `${entry.modelIdPrefix}${body.model}`;+ }}}}diff --git a/open-sse/executors/t3-chat-web.ts b/open-sse/executors/t3-chat-web.tsindex 610d3cf647..027e5e75d5 100644--- a/open-sse/executors/t3-chat-web.ts+++ b/open-sse/executors/t3-chat-web.ts@@ -32,6 +32,9 @@ const TSS_ACCEPT = "application/x-tss-framed, application/x-ndjson, application/// ─── Types ───────────────────────────────────────────────────────────────────export interface T3ChatCredentials {+ /** Parsed Cookie header value, guaranteed to include convex-session-id when present. */+ cookieHeader: string;+ /** Raw cookies portion (without the synthesized convex-session-id suffix). */cookies: string;/** convex-session-id — stored as a cookie by t3.chat, sent in the Cookie header */convexSessionId: string;@@ -39,13 +42,69 @@ export interface T3ChatCredentials {// ─── Helpers ─────────────────────────────────────────────────────────────────-function validateCredentials(creds: unknown): creds is T3ChatCredentials {- const raw = typeof creds === "object" && creds !== null ? (creds as Record<string, unknown>) : {};+/**+ * Parse the single stored credential into a structured t3.chat cookie object.+ *+ * The credential pipeline (`src/sse/services/auth.ts`) stores the single pasted+ * string as `credentials.apiKey` (fallback `accessToken`) — it never produces+ * `cookies`/`convexSessionId` fields. So we parse the raw string here, mirroring+ * the validator in `src/lib/providers/validation.ts` (#3007).+ *+ * Accepted forms:+ * (a) "convex-session-id=abc; sessionToken=xyz" — plain Cookie header+ * (b) full Cookie header already containing convex-session-id=...+ * (c) "cookies=<Cookie header>\nconvexSessionId=<id>" — structured form+ */+export function parseT3Credentials(creds: unknown): T3ChatCredentials {+ const rawCreds =+ typeof creds === "object" && creds !== null ? (creds as Record<string, unknown>) : {};+ const raw = String(rawCreds.apiKey ?? rawCreds.accessToken ?? "").trim();+ if (!raw) {+ return { cookieHeader: "", cookies: "", convexSessionId: "" };+ }++ let cookieHeader = raw;+ let convexSessionId = "";++ if (raw.includes("convexSessionId") || raw.includes("convex-session-id")) {+ // Structured / multi-part format: split on separators and pull out the id.+ const parts = raw.split(/[,;\n]/).map((s) => s.trim());+ const cookieParts: string[] = [];+ for (const part of parts) {+ if (part.startsWith("convexSessionId=") || part.startsWith("convex-session-id=")) {+ convexSessionId = part.split("=").slice(1).join("=");+ } else if (part.startsWith("cookies=")) {+ cookieParts.push(part.slice("cookies=".length));+ } else if (part.includes("=")) {+ cookieParts.push(part);+ }+ }+ if (cookieParts.length) cookieHeader = cookieParts.join("; ");+ }++ // Synthesize the final Cookie header, appending convex-session-id only when it+ // was provided separately and isn't already embedded in the header.+ const finalCookie =+ convexSessionId && !cookieHeader.includes("convex-session-id")+ ? `${cookieHeader}; convex-session-id=${convexSessionId}`+ : cookieHeader;++ // Derive convexSessionId from an embedded header form (b) for validation.+ if (!convexSessionId) {+ const m = finalCookie.match(/convex-session-id=([^;]+)/);+ if (m) convexSessionId = m[1].trim();+ }++ return { cookieHeader: finalCookie, cookies: cookieHeader, convexSessionId };+}++export function validateT3Credentials(creds: T3ChatCredentials | null | undefined): boolean {+ if (!creds) return false;return (- typeof raw.cookies === "string" &&- raw.cookies.length > 0 &&- typeof raw.convexSessionId === "string" &&- raw.convexSessionId.length > 0+ typeof creds.cookieHeader === "string" &&+ creds.cookieHeader.length > 0 &&+ typeof creds.convexSessionId === "string" &&+ creds.convexSessionId.length > 0);}@@ -62,17 +121,6 @@ function buildErrorResponse(status: number, message: string): Response {);}-/**- * Build Cookie header value. Includes the convex-session-id as a cookie- * (confirmed from live capture: t3.chat sets convex-session-id as a cookie,- * not as a separate header).- */-function buildCookieHeader(cookies: string, convexSessionId: string): string {- const base = cookies.trim();- if (base.includes("convex-session-id")) return base;- return `${base}; convex-session-id=${convexSessionId}`;-}-/*** Build standard TanStack Start headers matching live captured traffic.* The x-deployment-id header is optional but helps CDN routing.@@ -275,7 +323,8 @@ export class T3ChatWebExecutor extends BaseExecutor {signal?: AbortSignal): Promise<boolean> {try {- if (!validateCredentials(credentials)) return false;+ const parsed = parseT3Credentials(credentials);+ if (!validateT3Credentials(parsed)) return false;// Probe: HEAD to t3.chat base — confirms site reachable and cookies accepted.// 200/302/404 all indicate reachability; 5xx = down.@@ -283,7 +332,7 @@ export class T3ChatWebExecutor extends BaseExecutor {method: "HEAD",headers: {"User-Agent": USER_AGENT,- Cookie: buildCookieHeader(credentials.cookies, credentials.convexSessionId),+ Cookie: parsed.cookieHeader,},signal,});@@ -299,19 +348,15 @@ export class T3ChatWebExecutor extends BaseExecutor {role: string;content: string | unknown;}>;- const rawCreds = credentials as unknown as Record<string, unknown>;-- // 1. Validate credentials- if (!validateCredentials(rawCreds)) {- const missing = !rawCreds.cookies- ? "cookies"- : !rawCreds.convexSessionId- ? "convexSessionId"- : "both fields";+ // 1. Parse + validate credentials. The credential pipeline stores the single+ // pasted string as `apiKey` (fallback `accessToken`); parse out the Cookie+ // header + convex-session-id (#3007) instead of expecting pre-structured fields.+ const parsed = parseT3Credentials(credentials);+ if (!validateT3Credentials(parsed)) {return {response: buildErrorResponse(400,- `t3.chat credentials invalid: missing or empty ${missing}. Both 'cookies' and 'convexSessionId' are required.`+ "t3.chat credentials invalid: paste your full Cookie header (including convex-session-id) from t3.chat."),url: `${SERVER_FN_PREFIX}...`,headers: {},@@ -319,10 +364,7 @@ export class T3ChatWebExecutor extends BaseExecutor {};}- const cookieHeader = buildCookieHeader(- rawCreds.cookies as string,- rawCreds.convexSessionId as string- );+ const cookieHeader = parsed.cookieHeader;const headers = buildServerFnHeaders(cookieHeader);try {diff --git a/open-sse/handlers/chatCore.ts b/open-sse/handlers/chatCore.tsindex 1d8e449434..dc0286ff50 100644--- a/open-sse/handlers/chatCore.ts+++ b/open-sse/handlers/chatCore.ts@@ -24,6 +24,7 @@ import {runWithOnPersist,} from "../services/tokenRefresh.ts";import { createRequestLogger } from "../utils/requestLogger.ts";+import { applyResponsesPreviousResponseIdPolicy } from "../utils/responsesStatePolicy.ts";import { getModelTargetFormat, PROVIDER_ID_TO_ALIAS } from "../config/providerModels.ts";import { DEFAULT_THINKING_CLAUDE_SIGNATURE } from "../config/defaultThinkingSignature.ts";import {@@ -1373,24 +1374,33 @@ const PROXY_CONFIG_CACHE_TTL = 10_000;*/let _combosPromise: Promise<unknown[]> | null = null;let _combosCacheTs = 0;+let _combosCacheVersionSnapshot = -1;const COMBOS_CACHE_TTL = 10_000;async function getCombosCached(): Promise<unknown[]> {const now = Date.now();+ const { getCombos, getCombosCacheVersion } = await import("@/lib/localDb");+ const version = getCombosCacheVersion();+ // A combo write (create/update/delete/reorder) bumps the shared version via+ // invalidateDbCache("combos"); when it no longer matches our snapshot we drop+ // the cached promise so the nested-combo expansion stops serving removed+ // targets/models within the 10s TTL window (#3147).+ if (version !== _combosCacheVersionSnapshot) {+ clearCombosCache();+ }if (_combosPromise && now - _combosCacheTs < COMBOS_CACHE_TTL) {return _combosPromise;}_combosCacheTs = now;- _combosPromise = (async () => {- const { getCombos } = await import("@/lib/localDb");- return getCombos();- })();+ _combosCacheVersionSnapshot = version;+ _combosPromise = getCombos();return _combosPromise;}export function clearCombosCache() {_combosPromise = null;_combosCacheTs = 0;+ _combosCacheVersionSnapshot = -1;}export function clearUpstreamProxyConfigCache(providerId?: string) {@@ -3512,6 +3522,14 @@ export async function handleChatCore({}translatedBody.model = finalModelToUpstream;+ const previousResponseIdPolicy = applyResponsesPreviousResponseIdPolicy(translatedBody, {+ mode: settings.responsesPreviousResponseIdMode,+ sourceFormat,+ targetFormat,+ credentials,+ });+ translatedBody = previousResponseIdPolicy.body as typeof translatedBody;+// #1789: Prevent output_config.effort from overriding effort encoded in model name (Codex)if (provider === "codex" || provider?.startsWith("codex")) {const hasEffortSuffix = finalModelToUpstream.match(/-(low|medium|high|xhigh)$/i);diff --git a/open-sse/package.json b/open-sse/package.jsonindex d847eff1f0..d3d67c1c43 100644--- a/open-sse/package.json+++ b/open-sse/package.json@@ -1,6 +1,6 @@{"name": "@omniroute/open-sse",- "version": "3.8.9",+ "version": "3.8.10","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.tsindex 69e069efde..140317964a 100644--- a/open-sse/services/accountFallback.ts+++ b/open-sse/services/accountFallback.ts@@ -29,7 +29,7 @@ import {} from "../../src/shared/utils/classify429";import { resolveUseUpstream429BreakerHints } from "../../src/shared/utils/providerHints";-type ProviderProfile = {+export type ProviderProfile = {baseCooldownMs: number;useUpstreamRetryHints: boolean;/** Issue #2100 follow-up. Stored override; undefined → per-provider default. */diff --git a/open-sse/services/githubCopilotModels.ts b/open-sse/services/githubCopilotModels.tsnew file mode 100644index 0000000000..b24a57c3e8--- /dev/null+++ b/open-sse/services/githubCopilotModels.ts@@ -0,0 +1,134 @@+/**+ * GitHub Copilot live model discovery (#3120, #3121).+ *+ * The `github` (Copilot) provider previously shipped a STATIC hardcoded model+ * catalog in `providerRegistry.ts` and had no discovery source, so "Import+ * Models" could never refresh the list (#3120) and advertised models the+ * account is not entitled to (e.g. gemini previews), which fail upstream with+ * `400 ... not supported` when tested (#3121).+ *+ * Copilot exposes its per-account catalog at `https://api.githubcopilot.com/models`,+ * authenticated with the Copilot bearer token + the standard Copilot chat+ * headers. The response shape is `{ data: [{ id, name, model_picker_enabled,+ * policy, capabilities, ... }] }`. We map `data[].id` into managed models. Only+ * entitled models appear in the live response, so parsing it directly gives the+ * entitlement filtering #3121 needs.+ *+ * A safe fallback to the existing static catalog is preserved for+ * offline/unauthed/failed refresh so the import flow never breaks.+ */+import { getGitHubCopilotChatHeaders } from "../config/providerHeaderProfiles.ts";++export const GITHUB_COPILOT_MODELS_URL = "https://api.githubcopilot.com/models";++export type GitHubCopilotModel = {+ id: string;+ name: string;+ owned_by: string;+};++type RawRecord = Record<string, unknown>;++function asRecord(value: unknown): RawRecord {+ return value && typeof value === "object" && !Array.isArray(value) ? (value as RawRecord) : {};+}++function toNonEmptyString(value: unknown): string | null {+ if (typeof value !== "string") return null;+ const trimmed = value.trim();+ return trimmed.length > 0 ? trimmed : null;+}++/**+ * Parse a Copilot `/models` response into managed model rows. Only ids present+ * in the live response are returned, which is exactly the entitlement filter+ * #3121 requires.+ */+export function parseGitHubCopilotModels(data: unknown): GitHubCopilotModel[] {+ const payload = asRecord(data);+ const items = Array.isArray(payload.data)+ ? (payload.data as unknown[])+ : Array.isArray(payload.models)+ ? (payload.models as unknown[])+ : [];++ const seen = new Set<string>();+ const models: GitHubCopilotModel[] = [];++ for (const value of items) {+ const item = asRecord(value);+ const id = toNonEmptyString(item.id) || toNonEmptyString(item.model);+ if (!id || seen.has(id)) continue;+ seen.add(id);+ const name = toNonEmptyString(item.name) || toNonEmptyString(item.display_name) || id;+ models.push({ id, name, owned_by: "github" });+ }++ return models;+}++export type FetchGitHubCopilotModelsOptions = {+ /** Copilot bearer token (copilotToken; falls back to GitHub accessToken upstream). */+ token: string | null | undefined;+ /** Injectable fetch (defaults to global fetch). */+ fetchImpl?: typeof fetch;+ /** Static catalog to fall back to when live discovery is unavailable. */+ fallbackModels?: Array<{ id: string; name?: string }>;+};++export type GitHubCopilotModelsResult = {+ models: GitHubCopilotModel[];+ /** "api" = live discovery; "fallback" = static catalog (offline/unauthed/error). */+ source: "api" | "fallback";+};++function toFallbackResult(+ fallbackModels: Array<{ id: string; name?: string }> | undefined+): GitHubCopilotModelsResult {+ const models = (fallbackModels || [])+ .map((model) => {+ const id = toNonEmptyString(model.id);+ if (!id) return null;+ return { id, name: toNonEmptyString(model.name) || id, owned_by: "github" };+ })+ .filter((model): model is GitHubCopilotModel => Boolean(model));+ return { models, source: "fallback" };+}++/**+ * Discover the Copilot model catalog live, falling back to the static catalog+ * when no token is available or the upstream request fails.+ */+export async function fetchGitHubCopilotModels(+ options: FetchGitHubCopilotModelsOptions+): Promise<GitHubCopilotModelsResult> {+ const { token, fetchImpl = fetch, fallbackModels } = options;++ if (!toNonEmptyString(token)) {+ return toFallbackResult(fallbackModels);+ }++ try {+ const response = await fetchImpl(GITHUB_COPILOT_MODELS_URL, {+ method: "GET",+ headers: {+ ...getGitHubCopilotChatHeaders("application/json"),+ Authorization: `Bearer ${token}`,+ },+ });++ if (!response.ok) {+ return toFallbackResult(fallbackModels);+ }++ const data = await response.json();+ const models = parseGitHubCopilotModels(data);+ if (models.length === 0) {+ return toFallbackResult(fallbackModels);+ }+ return { models, source: "api" };+ } catch {+ // Network/parse failure — never break the import flow.+ return toFallbackResult(fallbackModels);+ }+}diff --git a/open-sse/services/reasoningCache.ts b/open-sse/services/reasoningCache.tsindex 7bdabbf6da..fee766ec65 100644--- a/open-sse/services/reasoningCache.ts+++ b/open-sse/services/reasoningCache.ts@@ -45,7 +45,8 @@ const REASONING_REPLAY_MODEL_PATTERNS = [/deepseek-r1/i,/deepseek-reasoner/i,/deepseek-chat/i,- /deepseek[-/]v4[-.](flash|pro)/i,+ /deepseek[-/]v4[-.](flash|pro)(-free)?/i,+ /zen\/deepseek-v4/i,/kimi-k2/i,/qwq/i,/qwen.*think/i,diff --git a/open-sse/services/responsesInputSanitizer.ts b/open-sse/services/responsesInputSanitizer.tsindex 679345c656..c1f938a38b 100644--- a/open-sse/services/responsesInputSanitizer.ts+++ b/open-sse/services/responsesInputSanitizer.ts@@ -55,11 +55,64 @@ function sanitizeInputItemId(record: JsonRecord): JsonRecord {return next;}+function imageUrlToText(value: unknown): string {+ if (typeof value === "string") return value;+ const record = toRecord(value);+ return typeof record?.url === "string" ? record.url : "";+}++function sanitizeContentPart(part: unknown, role: string): unknown {+ const record = toRecord(part);+ if (!record) return part;++ if (record.type === "image_url") {+ const url = imageUrlToText(record.image_url);+ if (role === "user") {+ const next: JsonRecord = { type: "input_image", image_url: url };+ const image = toRecord(record.image_url);+ if (image?.detail !== undefined) next.detail = image.detail;+ return next;+ }+ return { type: "output_text", text: url ? `[Image: ${url}]` : "[Image]" };+ }++ if (role === "assistant" && record.type === "input_image") {+ const url = imageUrlToText(record.image_url);+ return { type: "output_text", text: url ? `[Image: ${url}]` : "[Image]" };+ }++ return part;+}++function sanitizeMessageContent(record: JsonRecord): JsonRecord {+ if (!Array.isArray(record.content)) return record;++ const role = typeof record.role === "string" ? record.role.toLowerCase() : "";+ const content = record.content.map((part) => sanitizeContentPart(part, role));+ return { ...record, content };+}++function sanitizeOutputContent(record: JsonRecord): JsonRecord {+ if (!Array.isArray(record.output)) return record;++ // Some clients replay previous Responses output items inside the next+ // Responses input. In that shape OpenAI validates `input[n].output[m].type`+ // against output content part types, so legacy Chat-style `image_url` parts+ // must be normalized here too, not only in message.content.+ const role = record.type === "function_call_output" ? "user" : "assistant";+ const output = record.output.map((part) => sanitizeContentPart(part, role));+ return { ...record, output };+}+function sanitizeInputItem(item: unknown): unknown {const record = toRecord(item);if (!record) return item;let next = sanitizeInputItemId(record);+ if (isResponsesMessageItem(next)) {+ next = sanitizeMessageContent(next);+ }+ next = sanitizeOutputContent(next);if ((next.type === "function_call" || next.type === "function_call_output") &&typeof next.name === "string" &&diff --git a/open-sse/services/sessionManager.ts b/open-sse/services/sessionManager.tsindex 6452cae763..28612f6c56 100644--- a/open-sse/services/sessionManager.ts+++ b/open-sse/services/sessionManager.ts@@ -12,6 +12,8 @@ interface SessionEntry {lastActive: number;requestCount: number;connectionId: string | null;+ /** Timestamp when the last tool_calls finish_reason was emitted (cross-request TTFT tracking) */+ lastToolFinishAt?: number;}interface SessionFingerprintOptions {@@ -162,6 +164,29 @@ export function touchSession(sessionId: string | null, connectionId: string | nu}}+/**+ * Persist the tool-finish timestamp so Request 2 (the follow-up after tool execution)+ * can measure cross-request TTFT.+ */+export function markToolFinish(sessionId: string | null): void {+ if (!sessionId) return;+ const session = sessions.get(sessionId);+ if (session) session.lastToolFinishAt = Date.now();+}++/**+ * Consume the previously persisted tool-finish timestamp (one-shot: clears after read).+ * Returns null if no pending timestamp or session not found.+ */+export function consumeToolFinishTime(sessionId: string | null): number | null {+ if (!sessionId) return null;+ const session = sessions.get(sessionId);+ if (!session?.lastToolFinishAt) return null;+ const ts = session.lastToolFinishAt;+ session.lastToolFinishAt = undefined;+ return ts;+}+/*** Get session info (for sticky routing decisions)*/diff --git a/open-sse/services/toolLatencyTracker.ts b/open-sse/services/toolLatencyTracker.tsnew file mode 100644index 0000000000..85af5fa918--- /dev/null+++ b/open-sse/services/toolLatencyTracker.ts@@ -0,0 +1,89 @@+/**+ * Tracks per-provider tool call latency metrics.+ * Resets on server restart.+ */++interface ToolLatencyEntry {+ totalRequests: number;+ ttftAfterToolSum: number;+ gapAfterToolSum: number;+ ttftCount: number;+ gapCount: number;+}++const metrics = new Map<string, ToolLatencyEntry>();++export function recordToolLatency(+ provider: string,+ ttftAfterToolMs: number | null,+ gapAfterToolMs: number | null+): void {+ if (!provider) return;++ if (!metrics.has(provider)) {+ metrics.set(provider, {+ totalRequests: 0,+ ttftAfterToolSum: 0,+ gapAfterToolSum: 0,+ ttftCount: 0,+ gapCount: 0,+ });+ }++ const entry = metrics.get(provider)!;+ entry.totalRequests++;++ if (ttftAfterToolMs != null && ttftAfterToolMs >= 0) {+ entry.ttftAfterToolSum += ttftAfterToolMs;+ entry.ttftCount++;+ }++ if (gapAfterToolMs != null && gapAfterToolMs >= 0) {+ entry.gapAfterToolSum += gapAfterToolMs;+ entry.gapCount++;+ }+}++export function getToolLatencyByProvider(): Record<+ string,+ {+ avgTtftAfterToolMs: number;+ avgGapAfterToolMs: number;+ measurementCount: number;+ }+> {+ const result: Record<string, any> = {};+ for (const [provider, entry] of metrics) {+ result[provider] = {+ avgTtftAfterToolMs:+ entry.ttftCount > 0 ? Math.round(entry.ttftAfterToolSum / entry.ttftCount) : 0,+ avgGapAfterToolMs:+ entry.gapCount > 0 ? Math.round(entry.gapAfterToolSum / entry.gapCount) : 0,+ measurementCount: entry.totalRequests,+ };+ }+ return result;+}++export function recordToolTtft(provider: string, ttftMs: number): void {+ if (!provider || ttftMs < 0) return;++ if (!metrics.has(provider)) {+ metrics.set(provider, {+ totalRequests: 0,+ ttftAfterToolSum: 0,+ gapAfterToolSum: 0,+ ttftCount: 0,+ gapCount: 0,+ });+ }++ const entry = metrics.get(provider)!;+ entry.totalRequests++;+ entry.ttftAfterToolSum += ttftMs;+ entry.ttftCount++;+}++export function resetToolLatency(): void {+ metrics.clear();+}diff --git a/open-sse/translator/request/openai-responses.ts b/open-sse/translator/request/openai-responses.tsindex 4129d3a808..a4b099492b 100644--- a/open-sse/translator/request/openai-responses.ts+++ b/open-sse/translator/request/openai-responses.ts@@ -13,7 +13,7 @@ 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 any future versioned names.+// 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).@@ -34,6 +34,12 @@ 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;@@ -492,6 +498,9 @@ export function openaiToOpenAIResponsesRequest(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 abovecontinue;diff --git a/open-sse/translator/webTools.ts b/open-sse/translator/webTools.tsindex 78caf326c7..406ddaa490 100644--- a/open-sse/translator/webTools.ts+++ b/open-sse/translator/webTools.ts@@ -23,6 +23,306 @@ interface OpenAIToolDef {const TOOL_BLOCK_RE = /<tool>\s*([\s\S]*?)\s*<\/tool>/g;+interface ToolParseCandidate {+ raw: string;+ start: number;+ end: number;+ requireRequestedTool: boolean;+}++interface RequestedToolName {+ original: string;+ normalized: string;+}++function toRecord(value: unknown): Record<string, unknown> | null {+ return value && typeof value === "object" && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : null;+}++function getRequestedToolNames(tools: unknown): RequestedToolName[] {+ if (!Array.isArray(tools)) return [];+ const names: RequestedToolName[] = [];+ const seen = new Set<string>();+ for (const tool of tools) {+ const record = toRecord(tool);+ const fn = toRecord(record?.function);+ const name = typeof fn?.name === "string" ? fn.name.trim() : "";+ if (!name || seen.has(name)) continue;+ seen.add(name);+ names.push({ original: name, normalized: normalizeToolName(name) });+ }+ return names;+}++function normalizeToolName(name: string): string {+ return name.toLowerCase().replace(/[^a-z0-9]/g, "");+}++function levenshteinDistance(a: string, b: string): number {+ if (a === b) return 0;+ if (!a) return b.length;+ if (!b) return a.length;+ let previous = Array.from({ length: b.length + 1 }, (_, i) => i);+ let current = Array<number>(b.length + 1);+ for (let i = 1; i <= a.length; i += 1) {+ current[0] = i;+ for (let j = 1; j <= b.length; j += 1) {+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;+ current[j] = Math.min(current[j - 1] + 1, previous[j] + 1, previous[j - 1] + cost);+ }+ const temp = previous;+ previous = current;+ current = temp;+ }+ return previous[b.length];+}++function scoreToolName(emitted: string, requested: RequestedToolName): number {+ if (emitted === requested.original) return 1;+ const normalized = normalizeToolName(emitted);+ if (!normalized || !requested.normalized) return 0;+ if (normalized === requested.normalized) return 0.98;++ const shorter = Math.min(normalized.length, requested.normalized.length);+ const longer = Math.max(normalized.length, requested.normalized.length);+ if (shorter >= 4) {+ if (normalized.includes(requested.normalized) || requested.normalized.includes(normalized)) {+ return 0.86 - (longer - shorter) / Math.max(longer, 1) / 4;+ }+ }++ const distance = levenshteinDistance(normalized, requested.normalized);+ const similarity = 1 - distance / Math.max(longer, 1);+ return similarity >= 0.72 ? similarity : 0;+}++function resolveRequestedToolName(emitted: string, requestedTools: RequestedToolName[]): string | null {+ if (requestedTools.length === 0) return emitted;++ let best: { name: string; score: number } | null = null;+ let secondBest = 0;+ for (const requested of requestedTools) {+ const score = scoreToolName(emitted, requested);+ if (!best || score > best.score) {+ secondBest = best?.score ?? 0;+ best = { name: requested.original, score };+ } else if (score > secondBest) {+ secondBest = score;+ }+ }++ if (!best || best.score < 0.72) return null;+ // Avoid correcting to an arbitrary tool when the fuzzy match is ambiguous.+ if (best.score < 0.98 && best.score - secondBest < 0.08) return null;+ return best.name;+}++function stripCodeFence(value: string): string {+ return value+ .trim()+ .replace(/^```(?:json|javascript|js|python)?\s*/i, "")+ .replace(/\s*```$/i, "")+ .trim();+}++function convertSingleQuotedStrings(value: string): string {+ let result = "";+ let inSingle = false;+ let inDouble = false;+ let escaped = false;++ for (const ch of value) {+ if (escaped) {+ result += ch === '"' && inSingle ? '\\"' : ch;+ escaped = false;+ continue;+ }++ if (ch === "\\") {+ result += ch;+ escaped = true;+ continue;+ }++ if (ch === '"') {+ if (inSingle) {+ result += '\\"';+ } else {+ inDouble = !inDouble;+ result += ch;+ }+ continue;+ }++ if (ch === "'" && !inDouble) {+ inSingle = !inSingle;+ result += '"';+ continue;+ }++ result += ch;+ }++ return result;+}++function replacePythonLiterals(value: string): string {+ let result = "";+ let inString = false;+ let escaped = false;+ let token = "";++ const flushToken = () => {+ if (token === "True") result += "true";+ else if (token === "False") result += "false";+ else if (token === "None") result += "null";+ else result += token;+ token = "";+ };++ for (const ch of value) {+ if (escaped) {+ if (token) flushToken();+ result += ch;+ escaped = false;+ continue;+ }++ if (ch === "\\") {+ if (token) flushToken();+ result += ch;+ escaped = inString;+ continue;+ }++ if (ch === '"') {+ if (token) flushToken();+ inString = !inString;+ result += ch;+ continue;+ }++ if (!inString && /[A-Za-z]/.test(ch)) {+ token += ch;+ continue;+ }++ if (token) flushToken();+ result += ch;+ }++ if (token) flushToken();+ return result;+}++function normalizeLooseJson(value: string): string {+ return replacePythonLiterals(convertSingleQuotedStrings(value))+ .replace(/([{,]\s*)([A-Za-z_][A-Za-z0-9_-]*)(\s*:)/g, '$1"$2"$3')+ .replace(/,\s*([}\]])/g, "$1");+}++function parseLooseJsonObject(raw: string): Record<string, unknown> | null {+ const trimmed = stripCodeFence(raw);+ for (const candidate of [trimmed, normalizeLooseJson(trimmed)]) {+ try {+ return toRecord(JSON.parse(candidate));+ } catch {+ // Try the next, more permissive form.+ }+ }+ return null;+}++function findBareJsonCandidates(text: string): ToolParseCandidate[] {+ const candidates: ToolParseCandidate[] = [];+ let start = -1;+ let depth = 0;+ let quote: '"' | "'" | "" = "";+ let escaped = false;++ for (let i = 0; i < text.length; i += 1) {+ const ch = text[i];++ if (depth === 0 && ch !== "{") {+ continue;+ }++ if (escaped) {+ escaped = false;+ continue;+ }++ if (quote) {+ if (ch === "\\") {+ escaped = true;+ } else if (ch === quote) {+ quote = "";+ }+ continue;+ }++ if (ch === '"' || ch === "'") {+ quote = ch;+ continue;+ }++ if (ch === "{") {+ if (depth === 0) start = i;+ depth += 1;+ continue;+ }++ if (ch === "}" && depth > 0) {+ depth -= 1;+ if (depth === 0 && start >= 0) {+ const raw = text.slice(start, i + 1);+ if (/[{,]\s*["']?(name|command)["']?\s*:/i.test(raw) && /[{,]\s*["']?arguments["']?\s*:/i.test(raw)) {+ candidates.push({ raw, start, end: i + 1, requireRequestedTool: true });+ }+ start = -1;+ }+ }+ }++ return candidates;+}++function rangesOverlap(a: { start: number; end: number }, b: { start: number; end: number }): boolean {+ return a.start < b.end && b.start < a.end;+}++function stripRanges(text: string, ranges: Array<{ start: number; end: number }>): string {+ let content = text;+ const sorted = [...ranges].sort((a, b) => b.start - a.start);+ for (const range of sorted) {+ const lineStart = content.lastIndexOf("\n", range.start - 1) + 1;+ const nextLineBreak = content.indexOf("\n", range.end);+ const lineEnd = nextLineBreak === -1 ? content.length : nextLineBreak;+ const beforeOnLine = content.slice(lineStart, range.start);+ const afterOnLine = content.slice(range.end, lineEnd);+ const removeWholeLine = beforeOnLine.trim() === "" && afterOnLine.trim() === "";+ const start = removeWholeLine ? lineStart : range.start;+ const end = removeWholeLine && nextLineBreak !== -1 ? nextLineBreak + 1 : removeWholeLine ? lineEnd : range.end;+ content = `${content.slice(0, start)}${content.slice(end)}`;+ }+ return content.replace(/\n{3,}/g, "\n\n").trim();+}++function toArgumentsString(value: unknown): string {+ if (value === undefined) return "{}";+ if (typeof value === "string") {+ const parsed = parseLooseJsonObject(value);+ return parsed ? JSON.stringify(parsed) : value;+ }+ try {+ return JSON.stringify(value);+ } catch {+ return "{}";+ }+}+/*** Serialize an OpenAI `tools` array into a system-prompt block that instructs the* web UI model how to invoke a tool (emit a `<tool>{...}</tool>` block). Returns an@@ -59,6 +359,8 @@ export function serializeToolsToPrompt(tools: unknown): string {/*** Parse `<tool>{...}</tool>` blocks out of upstream text into OpenAI `tool_calls`.+ * When a requested `tools[]` set is provided, also accepts bare JSON tool-call+ * objects emitted by web models that ignored the `<tool>` wrapper contract.* Returns the content with the blocks stripped, plus the tool calls (or null when* there are none). `arguments` is always a JSON *string*, matching the OpenAI API.*@@ -67,43 +369,69 @@ export function serializeToolsToPrompt(tools: unknown): string {*/export function parseToolCallsFromText(text: string,- idSeed = "call"+ idSeed = "call",+ requestedTools?: unknown): { content: string; toolCalls: OpenAIToolCall[] | null } {- if (typeof text !== "string" || !text.includes("<tool>")) {+ const requestedToolNames = getRequestedToolNames(requestedTools);+ const canParseBareJson = requestedToolNames.length > 0;+ if (typeof text !== "string" || (!text.includes("<tool>") && !canParseBareJson)) {return { content: text ?? "", toolCalls: null };}- const toolCalls: OpenAIToolCall[] = [];- let match: RegExpExecArray | null;+ const candidates: ToolParseCandidate[] = [];+ const toolBlockRanges: Array<{ start: number; end: number }> = [];++ let blockMatch: RegExpExecArray | null;TOOL_BLOCK_RE.lastIndex = 0;- while ((match = TOOL_BLOCK_RE.exec(text)) !== null) {- const raw = match[1].trim();- let parsed: { name?: unknown; arguments?: unknown } | null = null;- try {- parsed = JSON.parse(raw);- } catch {- parsed = null;- }- const name = parsed && typeof parsed.name === "string" ? parsed.name : null;- if (!name) continue;- let args = "{}";- if (parsed && parsed.arguments !== undefined) {- args =- typeof parsed.arguments === "string"- ? parsed.arguments- : JSON.stringify(parsed.arguments);+ while ((blockMatch = TOOL_BLOCK_RE.exec(text)) !== null) {+ const range = { start: blockMatch.index, end: TOOL_BLOCK_RE.lastIndex };+ toolBlockRanges.push(range);+ candidates.push({+ raw: blockMatch[1].trim(),+ start: range.start,+ end: range.end,+ requireRequestedTool: false,+ });+ }++ if (canParseBareJson) {+ for (const candidate of findBareJsonCandidates(text)) {+ if (!toolBlockRanges.some((range) => rangesOverlap(range, candidate))) {+ candidates.push(candidate);+ }}+ }++ candidates.sort((a, b) => a.start - b.start);++ const toolCalls: OpenAIToolCall[] = [];+ const acceptedRanges: Array<{ start: number; end: number }> = [];+ for (const candidate of candidates) {+ const parsed = parseLooseJsonObject(candidate.raw);+ const emittedName =+ parsed && typeof parsed.name === "string"+ ? parsed.name+ : parsed && typeof parsed.command === "string"+ ? parsed.command+ : null;+ if (!emittedName) continue;+ const name =+ resolveRequestedToolName(emittedName, requestedToolNames) ||+ (candidate.requireRequestedTool ? null : emittedName);+ if (!name || (candidate.requireRequestedTool && requestedToolNames.length === 0)) continue;+ const args = toArgumentsString(parsed?.arguments);toolCalls.push({id: `${idSeed}_${toolCalls.length}`,type: "function",function: { name, arguments: args },});+ acceptedRanges.push({ start: candidate.start, end: candidate.end });}if (toolCalls.length === 0) {return { content: text, toolCalls: null };}- const content = text.replace(TOOL_BLOCK_RE, "").replace(/\n{3,}/g, "\n\n").trim();+ const content = stripRanges(text, acceptedRanges);return { content, toolCalls };}diff --git a/open-sse/utils/responsesStatePolicy.ts b/open-sse/utils/responsesStatePolicy.tsnew file mode 100644index 0000000000..2e073c387f--- /dev/null+++ b/open-sse/utils/responsesStatePolicy.ts@@ -0,0 +1,75 @@+import { isOpenAIResponsesStoreEnabled } from "@/lib/providers/requestDefaults";+import {+ DEFAULT_RESPONSES_PREVIOUS_RESPONSE_ID_MODE,+ RESPONSES_PREVIOUS_RESPONSE_ID_MODES,+ type ResponsesPreviousResponseIdMode,+} from "@/shared/constants/responsesPreviousResponseId";+import { FORMATS } from "../translator/formats.ts";++type JsonRecord = Record<string, unknown>;++type ApplyResponsesPreviousResponseIdPolicyOptions = {+ mode: unknown;+ sourceFormat?: unknown;+ targetFormat?: unknown;+ credentials?: unknown;+};++const MODE_SET = new Set<string>(RESPONSES_PREVIOUS_RESPONSE_ID_MODES);++function toRecord(value: unknown): JsonRecord {+ return value && typeof value === "object" && !Array.isArray(value) ? (value as JsonRecord) : {};+}++export function normalizeResponsesPreviousResponseIdMode(+ value: unknown+): ResponsesPreviousResponseIdMode {+ if (typeof value === "string" && MODE_SET.has(value)) {+ return value as ResponsesPreviousResponseIdMode;+ }+ return DEFAULT_RESPONSES_PREVIOUS_RESPONSE_ID_MODE;+}++export function shouldStripPreviousResponseId({+ mode,+ sourceFormat,+ targetFormat,+ credentials,+}: ApplyResponsesPreviousResponseIdPolicyOptions): boolean {+ const normalizedMode = normalizeResponsesPreviousResponseIdMode(mode);+ if (normalizedMode === "preserve") return false;+ if (normalizedMode === "strip") return true;++ const isResponsesSource = sourceFormat === FORMATS.OPENAI_RESPONSES;+ const isResponsesTarget = targetFormat === FORMATS.OPENAI_RESPONSES;+ if (!isResponsesSource && !isResponsesTarget) return false;++ // `previous_response_id` is only safe when the upstream actually keeps+ // Responses state. OmniRoute defaults to stateless upstream calls, so auto+ // strips unless the connection explicitly opts into OpenAI Responses storage.+ const providerSpecificData = toRecord(toRecord(credentials).providerSpecificData);+ return !isOpenAIResponsesStoreEnabled(providerSpecificData);+}++export function applyResponsesPreviousResponseIdPolicy(+ body: unknown,+ options: ApplyResponsesPreviousResponseIdPolicyOptions+): { body: unknown; stripped: boolean; mode: ResponsesPreviousResponseIdMode } {+ const mode = normalizeResponsesPreviousResponseIdMode(options.mode);+ if (!body || typeof body !== "object" || Array.isArray(body)) {+ return { body, stripped: false, mode };+ }++ const record = body as JsonRecord;+ if (!Object.hasOwn(record, "previous_response_id")) {+ return { body, stripped: false, mode };+ }++ if (!shouldStripPreviousResponseId({ ...options, mode })) {+ return { body, stripped: false, mode };+ }++ const next = { ...record };+ delete next.previous_response_id;+ return { body: next, stripped: true, mode };+}diff --git a/open-sse/utils/stream.ts b/open-sse/utils/stream.tsindex 42d226c684..407b0600f1 100644--- a/open-sse/utils/stream.ts+++ b/open-sse/utils/stream.ts@@ -29,6 +29,12 @@ import {extractThinkingFromContent,} from "../handlers/responseSanitizer.ts";import { buildErrorBody } from "./error.ts";+import { recordToolLatency } from "../services/toolLatencyTracker.ts";+import {+ generateSessionId,+ markToolFinish,+ consumeToolFinishTime,+} from "../services/sessionManager.ts";/*** Race a response body read against a timeout.@@ -796,6 +802,21 @@ export function createSSEStream(options: StreamOptions = {}) {const passthroughResponsesReasoningSummarySeen = new Set<string>();const streamStartedAt = Date.now();+ let lastToolCallChunkTime: number | null = null;+ let toolFinishTime: number | null = null;+ let contentAfterToolSeen = false;++ // Cross-request tool latency: fingerprint the session from the request body+ // so Request 2 can pick up the tool-finish timestamp left by Request 1.+ const sessionId = generateSessionId(body as Parameters<typeof generateSessionId>[0], {+ provider: provider ?? undefined,+ connectionId: connectionId ?? undefined,+ });+ let pendingToolFinishTime: number | null = null;+ try {+ pendingToolFinishTime = consumeToolFinishTime(sessionId);+ } catch {}+// Guard against duplicate [DONE] events — ensures exactly one per streamlet doneSent = false;const providerPayloadCollector = createStructuredSSECollector({@@ -1637,6 +1658,7 @@ export function createSSEStream(options: StreamOptions = {}) {// T18: Track if we saw tool calls & accumulate for call logif (delta?.tool_calls && delta.tool_calls.length > 0) {passthroughHasToolCalls = true;+ lastToolCallChunkTime = Date.now();for (const tc of delta.tool_calls) {// Key by index first — id only appears on the first delta in OpenAI streaminglet key: string;@@ -1670,8 +1692,25 @@ export function createSSEStream(options: StreamOptions = {}) {}const content = delta?.content || delta?.reasoning_content;- if (content && typeof content === "string") {+ if (typeof content === "string") {totalContentLength += content.length;++ if (!contentAfterToolSeen) {+ const toolTs = toolFinishTime || pendingToolFinishTime;+ const lastChunkTs = lastToolCallChunkTime;+ if (toolTs || lastChunkTs) {+ contentAfterToolSeen = true;+ const now = Date.now();+ try {+ recordToolLatency(+ provider || "unknown",+ toolTs ? now - toolTs : null,+ lastChunkTs ? now - lastChunkTs : null+ );+ } catch {}+ pendingToolFinishTime = null;+ }+ }}{const guarded = applyTextualToolCallStreamingGuard(@@ -1693,6 +1732,13 @@ export function createSSEStream(options: StreamOptions = {}) {const isFinishChunk = parsed.choices?.[0]?.finish_reason;+ if (isFinishChunk && passthroughHasToolCalls) {+ toolFinishTime = Date.now();+ try {+ markToolFinish(sessionId);+ } catch {}+ }+// T18: Normalize finish_reason to 'tool_calls' if tool calls were usedif (isFinishChunk &&@@ -1785,6 +1831,16 @@ export function createSSEStream(options: StreamOptions = {}) {continue;}+ if (parsed.choices?.[0]?.delta?.tool_calls) {+ lastToolCallChunkTime = Date.now();+ }+ if (parsed.choices?.[0]?.finish_reason === "tool_calls") {+ toolFinishTime = Date.now();+ try {+ markToolFinish(sessionId);+ } catch {}+ }+// Track content length and accumulate for call log (from raw provider chunk, so content is never missed)// Do this before translation so we capture content regardless of translator output shape@@ -1882,6 +1938,27 @@ export function createSSEStream(options: StreamOptions = {}) {}}+ const translateHasContent =+ typeof parsed.delta?.text === "string" ||+ typeof parsed.choices?.[0]?.delta?.content === "string" ||+ typeof parsed.choices?.[0]?.delta?.reasoning_content === "string";+ if (translateHasContent && !contentAfterToolSeen) {+ const toolTs = toolFinishTime || pendingToolFinishTime;+ const lastChunkTs = lastToolCallChunkTime;+ if (toolTs || lastChunkTs) {+ contentAfterToolSeen = true;+ const now = Date.now();+ try {+ recordToolLatency(+ provider || "unknown",+ toolTs ? now - toolTs : null,+ lastChunkTs ? now - lastChunkTs : null+ );+ } catch {}+ pendingToolFinishTime = null;+ }+ }+// Extract usageconst extracted = extractUsage(parsed);if (extracted) state.usage = extracted; // Keep original usage for loggingdiff --git a/package-lock.json b/package-lock.jsonindex a759f45d45..1f73572364 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "omniroute",- "version": "3.8.9",+ "version": "3.8.10","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "omniroute",- "version": "3.8.9",+ "version": "3.8.10","hasInstallScript": true,"license": "MIT","workspaces": [@@ -12409,9 +12409,9 @@"license": "MIT"},"node_modules/hono": {- "version": "4.12.18",- "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.18.tgz",- "integrity": "sha512-RWzP96k/yv0PQfyXnWjs6zot20TqfpfsNXhOnev8d1InAxubW93L11/oNUc3tQqn2G0bSdAOBpX+2uDFHV7kdQ==",+ "version": "4.12.23",+ "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.23.tgz",+ "integrity": "sha512-eIaZ9qDgu7XV0pxOCrg7/WhnQ6Ivm22UcxhXx/A3dcbqbbYgBEkc6e/J/s7j2tS96zoB0S9VBdLwQNCWwUo4LA==","license": "MIT","engines": {"node": ">=16.9.0"diff --git a/package.json b/package.jsonindex 03c72b2184..4a69df2325 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "omniroute",- "version": "3.8.9",+ "version": "3.8.10","description": "Unified AI router with 160+ providers, RTK+Caveman compression, auto fallback, MCP/A2A, desktop, PWA, and OpenAI-compatible APIs.","type": "module","bin": {diff --git a/recent_issues.jsonl b/recent_issues.jsonldeleted file mode 100644index 5f339d1f8d..0000000000--- a/recent_issues.jsonl+++ /dev/null@@ -1,10 +0,0 @@-{"author":{"id":"MDQ6VXNlcjE0OTIxOTgz","is_bot":false,"login":"oyi77","name":"Paijo"},"body":"# Comprehensive Documentation Site Overhaul\n\n## 🎯 Objective\nTransform OmniRoute's scattered documentation into a comprehensive, structured documentation site with interactive features, advanced search, and professional organization inspired by industry best practices.\n\n## 📋 Problem Statement\nCurrent documentation system limitations:\n- **Scattered Organization**: Markdown files spread across repository with limited navigation\n- **No Dedicated Site**: Lack of professional documentation portal\n- **Limited Discoverability**: Poor search and feature discovery\n- **Static Content**: No interactive elements or API testing\n- **Inconsistent Quality**: Varied formatting and structure\n\n## ✨ Proposed Solution\n\n### New Documentation Structure\n\n\n### Key Features\n- **Interactive API Documentation**: Swagger/OpenAPI with try-it-now functionality\n- **Advanced Search**: Algolia/DocSearch with autocomplete and filtering\n- **Versioned Content**: Clear version tags and migration guides\n- **Code Examples**: Runnable examples with copy-to-clipboard\n- **Visual Aids**: Interactive Mermaid diagrams and architecture visualizations\n- **Responsive Design**: Mobile-friendly with dark mode support\n- **Analytics**: Usage tracking and feedback system\n\n### Technology Stack\n- **Framework**: Next.js (consistent with OmniRoute dashboard)\n- **Content**: MDX (Markdown + React components)\n- **Styling**: Tailwind CSS (matches OmniRoute UI)\n- **Search**: Algolia DocSearch or Fuse.js\n- **Deployment**: Vercel with preview deployments\n\n## 📈 Expected Benefits\n- **50% increase** in documentation page views\n- **30% reduction** in support requests for basic questions\n- **40% increase** in time spent on documentation pages\n- **90% positive** feedback on documentation quality\n- **25% increase** in community contributions\n\n## 🔧 Implementation Plan\n\n### Phase 1: Foundation (2 weeks)\n- Set up Next.js documentation framework\n- Design component library with OmniRoute theme\n- Implement MDX processing pipeline\n- Set up CI/CD pipeline with preview deployments\n\n### Phase 2: Content Migration (4 weeks)\n- Audit and categorize existing documentation\n- Create automated migration tools\n- Migrate core content with quality validation\n- Implement redirects from old URLs\n\n### Phase 3: Advanced Features (3 weeks)\n- Implement search functionality with Algolia\n- Add interactive API documentation\n- Create versioning system\n- Implement analytics and feedback\n\n### Phase 4: Testing & Launch (2 weeks)\n- Comprehensive testing (unit, integration, E2E)\n- Performance optimization\n- Accessibility validation\n- Final review and official launch\n\n## 📊 Success Metrics\n- All content successfully migrated and validated\n- Search functionality achieves ≥90% relevance in test queries\n- Accessibility compliance (WCAG 2.1 AA) verified\n- Performance metrics meet targets (Lighthouse ≥90)\n- 50% increase in documentation engagement\n\n## 🎯 Definition of Done\n- Complete content migration with validation\n- All interactive features fully functional\n- Search system operational with ≥90% relevance\n- Accessibility compliance verified\n- Performance targets achieved\n- Analytics and feedback system implemented\n- Comprehensive documentation completed\n\n## 📝 Additional Context\nThis overhaul will create a professional documentation portal that improves user onboarding, feature discovery, and overall satisfaction while maintaining consistency with OmniRoute's brand and technical stack. The new site will serve as the primary resource for users, developers, and contributors.","comments":[],"createdAt":"2026-05-04T20:54:55Z","labels":[],"number":1958,"title":"feat: Comprehensive Documentation Site Overhaul"}-{"author":{"id":"MDQ6VXNlcjE0OTIxOTgz","is_bot":false,"login":"oyi77","name":"Paijo"},"body":"# Manifest Routing Integration - Tier Resolution & Specificity Detection\n\n## 🎯 Objective\nEnhance OmniRoute's combo routing system by integrating Manifest's sophisticated tier resolution and specificity detection logic to create a more intelligent, context-aware routing engine that optimizes for both performance and cost.\n\n## 📋 Problem Statement\nThe current combo routing system, while functional with 13 strategies, lacks:\n- **Tier Resolution**: Provider classification based on performance, cost, and capabilities\n- **Specificity Detection**: Content complexity analysis for optimal route selection\n- **Adaptive Strategies**: Dynamic adjustment based on real-time metrics and query requirements\n\n## ✨ Proposed Solution\n\n### Core Components\n1. **Tier Resolution System**\n - 3-level classification: static rules → heuristics → specificity-based\n - Dynamic tier assignment based on real-time provider metrics\n - Integration with existing provider health monitoring\n\n2. **Specificity Detection**\n - Query complexity scoring (0-100 scale)\n - Content-type analysis for optimal provider matching\n - Historical performance data integration\n\n3. **Adaptive Combo Strategies**\n - New auto-optimized strategy with dynamic adjustment\n - Tier-aware fallback logic\n - Cost-performance balancing algorithms\n\n### Integration Points\n- **PR #1918 Auto-Assessment**: Leverage existing health monitoring and performance data\n- **Existing Combo System**: Maintain backward compatibility with current strategies\n- **Metrics Pipeline**: Feed routing decisions into analytics for continuous improvement\n\n## 📈 Expected Benefits\n- **15-25%** improvement in routing success rates for complex queries\n- **10-20%** reduction in API costs through optimal provider utilization\n- **30% faster** routing decisions via optimized tier selection\n- **Enhanced reliability** with smarter, context-aware fallback logic\n\n## 🔧 Implementation Plan\n\n### Phase 1: Foundation (2-3 weeks)\n- Research Manifest's tier resolution algorithms\n- Design system architecture with integration points\n- Implement basic tier classification framework\n- Set up test infrastructure and benchmarks\n\n### Phase 2: Core Implementation (4-5 weeks)\n- Implement 3-tier resolution system (static/heuristic/specificity)\n- Develop specificity scoring algorithm\n- Create adaptive combo strategies\n- Integrate with PR #1918 auto-assessment system\n\n### Phase 3: Optimization & Testing (3 weeks)\n- Performance tuning and benchmarking\n- Comprehensive test suite (unit, integration, e2e)\n- Documentation and examples\n- Gradual rollout and monitoring\n\n## 📊 Success Metrics\n- Routing success rate improvement (A/B testing)\n- Cost reduction verified through usage analytics\n- Performance benchmarks showing latency improvements\n- User satisfaction surveys on routing reliability\n\n## 🔍 Related Work\n- PR #1918: Auto-Assessment and Self-Healing Combo Engine\n- Manifest routing engine analysis\n- Current combo strategies documentation\n\n## 🎯 Definition of Done\n- Tier resolution achieves ≥95% accuracy in classification\n- Specificity detection shows ≥90% correlation with manual scoring\n- Adaptive strategies demonstrate ≥15% improvement in benchmarks\n- Integration with auto-assessment system verified\n- All performance benchmarks meet targets\n- Comprehensive documentation completed\n\n## 📝 Additional Context\nThis enhancement builds upon PR #1918's auto-assessment capabilities, adding intelligent tier-based routing and query-specific optimization to create a sophisticated, cost-effective routing system that maintains OmniRoute's commitment to performance and reliability.","comments":[],"createdAt":"2026-05-04T20:54:10Z","labels":[],"number":1957,"title":"feat: Manifest Routing Integration - Tier Resolution & Specificity Detection"}-{"author":{"id":"U_kgDODmAPNQ","is_bot":false,"login":"akatylutir","name":""},"body":"### OmniRoute Version\n\n3.7.8\n\n### Installation Method\n\nnpm (global)\n\n### Operating System\n\nWindows\n\n### OS Version\n\nwindows 11 pro, 24H2\n\n### Node.js Version\n\nv22.22.2\n\n### Provider(s) Involved\n\n_No response_\n\n### Model(s) Involved\n\n_No response_\n\n### Client Tool\n\n_No response_\n\n### Description\n\nHi! I want to use OmniRoute, but red button not working. What can I do? Thi is log: https://pastebin.com/jKcS8CSy , and this is video: https://youtu.be/DB40dkfnGf4\n\n### Steps to Reproduce\n\nHi! I want to use OmniRoute, but red button not working. What can I do? Thi is log: https://pastebin.com/jKcS8CSy , and this is video: https://youtu.be/DB40dkfnGf4\n\n### Expected Behavior\n\nHi! I want to use OmniRoute, but red button not working. What can I do? Thi is log: https://pastebin.com/jKcS8CSy , and this is video: https://youtu.be/DB40dkfnGf4\n\n### Actual Behavior\n\nHi! I want to use OmniRoute, but red button not working. What can I do? Thi is log: https://pastebin.com/jKcS8CSy , and this is video: https://youtu.be/DB40dkfnGf4\n\n### Test Impact\n\nNeeds a new unit test\n\n### Error Logs / Output\n\n```shell\nHi! I want to use OmniRoute, but red button not working. What can I do? Thi is log: https://pastebin.com/jKcS8CSy , and this is video: https://youtu.be/DB40dkfnGf4\n```\n\n### Screenshots\n\nHi! I want to use OmniRoute, but red button not working. What can I do? Thi is log: https://pastebin.com/jKcS8CSy , and this is video: https://youtu.be/DB40dkfnGf4\n\n### Additional Context\n\nHi! I want to use OmniRoute, but red button not working. What can I do? Thi is log: https://pastebin.com/jKcS8CSy , and this is video: https://youtu.be/DB40dkfnGf4\n\n### Validation Plan\n\nHi! I want to use OmniRoute, but red button not working. What can I do? Thi is log: https://pastebin.com/jKcS8CSy , and this is video: https://youtu.be/DB40dkfnGf4","comments":[{"id":"IC_kwDORPf6ys8AAAABBKraWA","author":{"login":"kilo-code-bot"},"authorAssociation":"NONE","body":"This issue appears to be a duplicate of https://github.com/diegosouzapw/OmniRoute/issues/1883.\n\n> **\\[BUG\\] Onboarding button unresponsive after upgrade from 2.x to 3.x — CSP blocks eval** (#1883)\n\nSimilarity score: 90%\n\n*This comment was generated by Kilo Auto-Triage.*","createdAt":"2026-05-04T18:00:58Z","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/diegosouzapw/OmniRoute/issues/1955#issuecomment-4373273176","viewerDidAuthor":false},{"id":"IC_kwDORPf6ys8AAAABBK1BzA","author":{"login":"vladislavsartakov90-svg"},"authorAssociation":"NONE","body":"I solved the problem, install version 3.7.5","createdAt":"2026-05-04T18:24:23Z","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/diegosouzapw/OmniRoute/issues/1955#issuecomment-4373430732","viewerDidAuthor":false}],"createdAt":"2026-05-04T18:00:51Z","labels":[{"id":"LA_kwDORPf6ys8AAAACYAlrFQ","name":"bug","description":"Something isn't working","color":"d73a4a"},{"id":"LA_kwDORPf6ys8AAAACZXajUw","name":"kilo-triaged","description":"Auto-generated label by Kilo","color":"faf74f"},{"id":"LA_kwDORPf6ys8AAAACZ7FLsw","name":"kilo-duplicate","description":"Auto-generated label by Kilo","color":"faf74f"}],"number":1955,"title":"[BUG] Button Start Onboarding not working"}-{"author":{"id":"U_kgDOEMaoiA","is_bot":false,"login":"vladislavsartakov90-svg","name":""},"body":"### OmniRoute Version\n\n3.7.8\n\n### Installation Method\n\nnpm (global)\n\n### Operating System\n\nWindows\n\n### OS Version\n\nwindows 10 \n\n### Node.js Version\n\nv24.15.0\n\n### Provider(s) Involved\n\nall\n\n### Model(s) Involved\n\nall\n\n### Client Tool\n\nall\n\n### Description\n\nI launched omniroute in cmd, the website opens, but the button doesn't work. I tried changing ports, but that didn't help. I also tried using AI, but that didn't help either.\n\n### Steps to Reproduce\n\na\n\n### Expected Behavior\n\na\n\n### Actual Behavior\n\na\n\n### Test Impact\n\nNeeds a new unit test\n\n### Error Logs / Output\n\n```shell\na\n```\n\n### Screenshots\n\n<img width=\"978\" height=\"506\" alt=\"Image\" src=\"https://github.com/user-attachments/assets/440cdbfb-1a2e-42bf-a95e-9dc25b9fcb00\" />\n\n<img width=\"983\" height=\"436\" alt=\"Image\" src=\"https://github.com/user-attachments/assets/50ea65d5-67ca-4b65-9849-c49f5ee1a526\" />\n\n<img width=\"535\" height=\"188\" alt=\"Image\" src=\"https://github.com/user-attachments/assets/b8a74f6b-63f6-4973-9812-2e2146a793a0\" />\n\n### Additional Context\n\na\n\n### Validation Plan\n\na","comments":[{"id":"IC_kwDORPf6ys8AAAABBKpIzA","author":{"login":"kilo-code-bot"},"authorAssociation":"NONE","body":"This issue appears to be a duplicate of https://github.com/diegosouzapw/OmniRoute/issues/1703.\n\n> **\\[BUG\\]** (#1703)\n\nSimilarity score: 93%\n\n*This comment was generated by Kilo Auto-Triage.*","createdAt":"2026-05-04T17:54:38Z","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/diegosouzapw/OmniRoute/issues/1954#issuecomment-4373235916","viewerDidAuthor":false},{"id":"IC_kwDORPf6ys8AAAABBKtw3g","author":{"login":"vladislavsartakov90-svg"},"authorAssociation":"NONE","body":"node 22.22.2 not work\n","createdAt":"2026-05-04T18:06:24Z","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/diegosouzapw/OmniRoute/issues/1954#issuecomment-4373311710","viewerDidAuthor":false}],"createdAt":"2026-05-04T17:54:31Z","labels":[{"id":"LA_kwDORPf6ys8AAAACYAlrFQ","name":"bug","description":"Something isn't working","color":"d73a4a"},{"id":"LA_kwDORPf6ys8AAAACZXajUw","name":"kilo-triaged","description":"Auto-generated label by Kilo","color":"faf74f"},{"id":"LA_kwDORPf6ys8AAAACZ7FLsw","name":"kilo-duplicate","description":"Auto-generated label by Kilo","color":"faf74f"}],"number":1954,"title":"[BUG]"}-{"author":{"id":"MDQ6VXNlcjM3Nzc3MjYx","is_bot":false,"login":"uwuclxdy","name":"cloudy"},"body":"### Problem / Use Case\n\nOmniRoute currently tries all accounts from lets say Codex provider, even though some of them have no more usage available.\n\n### Proposed Solution\n\nMake the already existing buttons \"track 5-hour quota\" and \"track weekly quota\" on `/dashboard/providers/codex` page would make OmniRoute check the quota of the account before attempting to send a query and skip it if on 0%. This could work for other providers like Claude Code in the same way.\n\n### Alternatives Considered\n\n_No response_\n\n### Acceptance Criteria\n\nHave accounts without any usage left skipped automatically when quota tracking is turned on.\n\n### Area\n\nProxy / Routing\n\n### Related Provider(s)\n\nCodex, Claude Code...\n\n### Additional Context\n\n_No response_\n\n### Expected Test Plan\n\n_No response_","comments":[],"createdAt":"2026-05-04T17:21:30Z","labels":[{"id":"LA_kwDORPf6ys8AAAACYAlrLw","name":"enhancement","description":"New feature or request","color":"a2eeef"}],"number":1952,"title":"[Feature] Skip (Codex) accounts that have the weekly or 5h quota exhausted"}-{"author":{"id":"MDQ6VXNlcjU5MzM0MTUz","is_bot":false,"login":"hoangchung0701","name":""},"body":"### Problem / Use Case\n\nCould please show how much quota on model like:\n- Sesssion: x/y request remain\n- Weekly: x/y request remain\n\n### Proposed Solution\n\nNo\n\n### Alternatives Considered\n\n_No response_\n\n### Acceptance Criteria\n\nno\n\n### Area\n\nAnalytics / Usage Tracking\n\n### Related Provider(s)\n\n_No response_\n\n### Additional Context\n\n_No response_\n\n### Expected Test Plan\n\n_No response_","comments":[],"createdAt":"2026-05-04T17:12:44Z","labels":[{"id":"LA_kwDORPf6ys8AAAACYAlrLw","name":"enhancement","description":"New feature or request","color":"a2eeef"}],"number":1951,"title":"[Feature] Show more detail about quota"}-{"author":{"id":"U_kgDODGQfGw","is_bot":false,"login":"Destruction13","name":""},"body":"### Problem / Use Case\n\nOmniRoute supports a very large provider ecosystem, but Devin AI is not currently available as a built-in provider.\n\nThis matters because Devin is a strong coding-focused agent for longer-running engineering tasks, and OmniRoute already positions itself as a universal gateway for coding agents and model providers. Right now, users who want to evaluate or route work to Devin cannot do that from the same OmniRoute endpoint or include Devin in combos/fallback chains.\n\n## Why the current custom-provider path is not enough\n\nAs far as I understand, OmniRoute's generic custom provider support is for OpenAI-compatible and Anthropic-compatible endpoints.\n\nDevin does expose an official API, but it is session-based and organization-scoped rather than a drop-in `/chat/completions`-compatible endpoint. Because of that, Devin likely needs a first-class provider adapter instead of a generic custom endpoint configuration.\n\n## Use cases\n\n- Route repo-level coding, debugging, and refactor tasks to Devin from the same OmniRoute setup used for Codex, Claude Code, Gemini CLI, etc.\n- Use Devin as a higher-latency but higher-capability fallback for complex implementation tasks.\n- Compare Devin against other coding-oriented providers inside the same OmniRoute combo/routing policy.\n- Evaluate Devin inside OmniRoute without reconfiguring clients every time.\n\n### Proposed Solution\n\n## Proposed solution\n\nAdd Devin as a built-in provider with a custom executor.\n\nHigh-level implementation sketch:\n\n1. Register a new `devin` provider in `src/shared/constants/providers.ts`.\n2. Add Devin provider/model metadata in `open-sse/config/providerRegistry.ts`.\n3. Implement a custom executor in `open-sse/executors/` that:\n - authenticates with Devin service-user credentials\n - targets the organization API under `https://api.devin.ai/v3/organizations/{org_id}`\n - creates a new Devin session for a fresh OmniRoute request\n - sends follow-up messages to an existing Devin session when conversation continuity is available\n - polls session state and/or session messages until a stable assistant result is available\n - maps the final Devin output back into OmniRoute's OpenAI-compatible response shape\n4. Add dashboard/provider settings for:\n - `DEVIN_API_KEY` (service-user credential)\n - `DEVIN_ORG_ID`\n - optional defaults such as session tags, repo selection, or ACU limits\n5. Make the provider eligible for direct selection and combo routing.\n\n### Alternatives Considered\n\n_No response_\n\n### Acceptance Criteria\n\n## Acceptance criteria\n\n- Devin appears in the Providers UI as a connectable provider.\n- A user can store Devin credentials and validate the connection.\n- OmniRoute can send a basic text request to Devin and return a usable assistant response through `/v1/chat/completions` and/or `/v1/responses`.\n- Follow-up prompts can either reuse a Devin session or the limitation is explicitly documented for MVP behavior.\n- Devin can be targeted directly in combos.\n- Common Devin session states/errors (for example approval-needed, quota/usage exhaustion, or suspended sessions) are surfaced as clear OmniRoute errors.\n- Documentation explains setup, limitations, and expected latency/behavior differences versus normal token-streaming LLM providers.\n\n## Suggested MVP scope\n\nMVP can be text-only and non-streaming/polling-based if needed.\n\nNot required for the first version:\n- embeddings\n- image/audio endpoints\n- tool-calling parity\n- full real-time streaming parity with standard LLM providers\n\n### Area\n\nProvider Support\n\n### Related Provider(s)\n\n_No response_\n\n### Additional Context\n\n## Additional context\n\nThis would also be useful for users who want to evaluate Devin during onboarding or trial access without changing their entire client setup.\n\n### Expected Test Plan\n\n_No response_","comments":[],"createdAt":"2026-05-04T17:00:59Z","labels":[{"id":"LA_kwDORPf6ys8AAAACYAlrLw","name":"enhancement","description":"New feature or request","color":"a2eeef"}],"number":1950,"title":"[Feature] devin.ai"}-{"author":{"id":"MDQ6VXNlcjc1MzQ1NDc=","is_bot":false,"login":"chbndrhnns","name":"Johannes Rueschel"},"body":"### OmniRoute Version\n\n3.7.8\n\n### Installation Method\n\nnpm (global)\n\n### Operating System\n\nmacOS\n\n### OS Version\n\n26.4.1\n\n### Node.js Version\n\n24.15.0\n\n### Provider(s) Involved\n\n-\n\n### Model(s) Involved\n\n-\n\n### Client Tool\n\n-\n\n### Description\n\n\n```\n❯ pnpm upgrade -g omniroute\nDownloading @ngrok/[email protected]: 7.97 MB/7.97 MB, done\nDownloading @swc/[email protected]: 9.16 MB/9.16 MB, done\n WARN 2 deprecated subdependencies found: [email protected], [email protected]\nDownloading [email protected]: 50.87 MB/50.87 MB, done\nPackages: +29 -25\n+++++++++++++++++++++++++++++-------------------------\nProgress: resolved 988, reused 873, downloaded 27, added 29, done\n WARN Issues with peer dependencies found\n.\n└─┬ @lobehub/ui 5.10.0\n └─┬ @emoji-mart/react 1.1.1\n └── ✕ unmet peer react@\"^16.8 || ^17 || ^18\": found 19.2.5\n\n/Users/jo/Library/pnpm/global/5:\n- omniroute 3.7.4\n+ omniroute 3.7.8\n\n╭ Warning ──────────────────────────────────────────────────────────────────────────────────────╮\n│ │\n│ Ignored build scripts: @swc/[email protected], [email protected]. │\n│ Run \"pnpm approve-builds -g\" to pick which dependencies should be allowed to run scripts. │\n│ │\n╰───────────────────────────────────────────────────────────────────────────────────────────────╯\nDone in 58.1s using pnpm v10.33.0\n❯ pnpm approve-builds -g\n✔ Choose which packages to build (Press <space> to select, <a> to toggle all, <i> to invert selection) · @swc/core, omniroute\n✔ The next packages will now be built: @swc/core, omniroute.\nDo you approve? (y/N) · true\n.pnpm/@[email protected]_@[email protected]/node_modules/@swc/core: Running postinstall script, done in 45ms\n.pnpm/[email protected]_@[email protected]_@[email protected][email protected][email protected]_rea_81be994467029f641d72db51e6e26349/node_modules/omniroute: Running postinstall script...\n.pnpm/[email protected]_@[email protected]_@[email protected][email protected][email protected]_rea_81be994467029f641d72db51e6e26349/node_modules/omniroute: Running postinstall script, done in 772ms\n❯\n❯ omniroute\n\n ____ _ ____ _\n / __ \\\\ (_) __ \\\\ | |\n | | | |_ __ ___ _ __ _| |__) |___ _ _| |_ ___\n | | | | '_ ` _ \\\\| '_ \\\\ | _ // _ \\\\| | | | __/ _ \\\\\n | |__| | | | | | | | | | | | \\\\ \\\\ (_) | |_| | || __/\n \\\\____/|_| |_| |_|_| |_|_|_| \\\\_\\\\___/ \\\\__,_|\\\\__\\\\___|\n\n ⏳ Starting server...\n\n▲ Next.js 16.2.4\n- Local: http://localhost:20128\n- Network: http://0.0.0.0:20128\n✓ Ready in 0ms\n\n ✔ OmniRoute is running!\n\n Dashboard: http://localhost:20128\n API Base: http://localhost:20128/v1\n\n Point your CLI tool (Cursor, Cline, Codex) to:\n http://localhost:20128/v1\n\n Press Ctrl+C to stop\n\n[CREDENTIALS] No external credentials file found, using defaults.\n[DB] Could not preserve critical DB state before recreation: Could not locate the bindings file. Tried:\n → /Users/jo/Library/pnpm/global/5/.pnpm/[email protected]_@[email protected]_@[email protected][email protected][email protected]_rea_81be994467029f641d72db51e6e26349/node_modules/omniroute/app/node_modules/better-sqlite3/build/better_sqlite3.node\n```\n\n### Steps to Reproduce\n\n1. `pnpm upgrade -g omniroute`\n2. `pnpm approve-builds -g`\n3. `omniroute`\n\n### Expected Behavior\n\nCan upgrade without manual installation procedure\n\n### Actual Behavior\n\nNeed to go to /Users/jo/Library/pnpm/global/5/.pnpm/[email protected]_@[email protected]_@[email protected][email protected][email protected]_rea_81be994467029f641d72db51e6e26349/node_modules/omniroute/app\n\nNeed to run `npm install [email protected] [email protected] --no-save`\n\n### Test Impact\n\nNeeds a new e2e test\n\n### Error Logs / Output\n\n```shell\n\n```\n\n### Screenshots\n\n_No response_\n\n### Additional Context\n\n_No response_\n\n### Validation Plan\n\n_No response_","comments":[],"createdAt":"2026-05-04T11:52:34Z","labels":[{"id":"LA_kwDORPf6ys8AAAACYAlrFQ","name":"bug","description":"Something isn't working","color":"d73a4a"}],"number":1943,"title":"[BUG] pnpm install still requires manual better-sqlite3 installation"}-{"author":{"id":"MDQ6VXNlcjE0OTIxOTgz","is_bot":false,"login":"oyi77","name":"Paijo"},"body":"## Summary\n\nOmniRoute v3.7.8 contains **two different encryption key derivation implementations** in the same package that produce incompatible ciphertexts. The health-check/token-refresh thread uses the old dynamic-salt derivation while the main API uses the new static-salt derivation, causing:\n\n1. **Persistent decrypt failures** — tokens encrypted by the health-check thread cannot be decrypted by the main API\n2. **Re-encryption loop** — the health-check thread continuously re-encrypts tokens with a dynamic salt, undoing any fix applied with the static salt\n3. **CPU spike during crash-loop** — when tokens are encrypted with dynamic salt, the main API fails to decrypt them, causing a cascade of errors and 50% CPU usage\n\n## Root Cause\n\nTwo different key derivation functions exist in the built package:\n\n### Old code (chunk 42476) — Dynamic Salt\n```javascript\nfunction k() {\n if (null !== i) return i;\n let a = process.env.STORAGE_ENCRYPTION_KEY;\n let b = (0, f.createHash)(\"sha256\").update(a).digest().slice(0, 16);\n // ^^^^^^^^^^^^^ DYNAMIC — derived from the key itself\n try { i = (0, f.scryptSync)(a, b, 32); }\n // ...\n}\n```\n\n### New code (chunk 56197) — Static Salt\n```javascript\nfunction l() {\n if (null !== j) return j;\n let a = process.env.STORAGE_ENCRYPTION_KEY;\n let b = \"omniroute-field-encryption-v1\";\n // ^^^^^^^^^^^^^^^^^^^^^^^^^^^ STATIC — hardcoded string\n try { j = (0, g.scryptSync)(a, b, 32); }\n // ...\n}\n```\n\nThese produce **different derived keys** from the same `STORAGE_ENCRYPTION_KEY`, making ciphertexts from one undecryptable by the other.\n\nThe decrypt function in `42476.js` has a fallback that tries the static-salt key when the dynamic-salt key fails, but the **encrypt function** only uses the dynamic-salt key. So the health-check thread encrypts with dynamic salt, the main API tries to decrypt with the dynamic-salt key (different derivation → fails), then falls back to static salt (also fails for newly-encrypted tokens).\n\n## Impact\n\n- **Severity: HIGH** — Causes production outages when tokens become undecryptable\n- **CPU**: 50% CPU usage during crash-loop (from repeated decrypt failures triggering health-check)\n- **Data**: All encrypted tokens become unreadable until manually fixed\n- **Recovery**: Requires manual database fix script to re-encrypt all tokens with static salt\n\n## Reproduction\n\n1. Set `STORAGE_ENCRYPTION_KEY` in server.env\n2. Add OAuth providers — tokens get encrypted with static salt\n3. Health-check thread runs — re-encrypts tokens with dynamic salt\n4. Main API attempts to decrypt — fails (dynamic-salt ciphertext produces different derived key)\n5. Error cascade: decrypt failures → health-check triggers → re-encrypts with dynamic salt → more failures\n6. CPU spikes to 50%, API responses fail for encrypted fields\n\n## Evidence\n\n```bash\n# Check encryption status of active tokens\nnode -e \"\nconst db = require('better-sqlite3')('/home/openclaw/.omniroute/storage.sqlite');\nconst rows = db.prepare('SELECT id, access_token, refresh_token FROM provider_connections WHERE is_active = 1').all();\nlet static = 0, dynamic = 0;\nfor (const row of rows) {\n for (const col of ['access_token', 'refresh_token']) {\n const val = row[col];\n if (!val || val === 'revoked') continue;\n try {\n const buf = Buffer.from(val, 'base64');\n const saltLen = buf.readUInt8(0);\n const salt = buf.slice(1, 1 + saltLen).toString('utf8');\n if (salt === 'omniroute-field-encryption-v1') static++;\n else dynamic++;\n } catch(e) {}\n }\n}\nconsole.log('Static salt:', static, '| Dynamic salt:', dynamic);\ndb.close();\n\"\n\n# Output after health-check thread runs:\n# Static: 0 | Dynamic: 205 (= ALL tokens re-encrypted with dynamic salt)\n\n# Output after running fix-encryption-static.cjs:\n# Static: 539 | Dynamic: 0 (= ALL tokens fixed back to static salt)\n```\n\n## Workaround\n\nWe created a script (`fix-encryption-static.cjs`) that:\n1. Reads all encrypted tokens from the database\n2. Decrypts them using the static-salt key (falling back to dynamic-salt key if static fails)\n3. Re-encrypts them with the static-salt key\n4. Writes the updated tokens back to the database\n\nThis script runs via cron every 5 minutes to counteract the health-check thread re-encryption.\n\n## Suggested Fix\n\n1. **Unify key derivation**: Remove the old dynamic-salt code path and use only the static-salt derivation (`\"omniroute-field-encryption-v1\"`) everywhere\n2. **Add migration**: On startup, scan for tokens encrypted with the dynamic salt and re-encrypt them with the static salt\n3. **Remove the fallback**: The current fallback in the decrypt function (try dynamic, then try static) masks the issue. After migration, only the static salt key should exist.\n\n## Environment\n\n- OmniRoute v3.7.8\n- Node v22.22.1\n- Ubuntu 22.04\n- 1,239 models configured\n- 306 active provider connections\n- STORAGE_ENCRYPTION_KEY set via server.env","comments":[{"id":"IC_kwDORPf6ys8AAAABBLxsAA","author":{"login":"soyelmismo"},"authorAssociation":"NONE","body":"how can i disable the encryption its so annoying.\n","createdAt":"2026-05-04T20:56:21Z","includesCreatedEdit":false,"isMinimized":false,"minimizedReason":"","reactionGroups":[],"url":"https://github.com/diegosouzapw/OmniRoute/issues/1941#issuecomment-4374424576","viewerDidAuthor":false}],"createdAt":"2026-05-04T11:47:27Z","labels":[],"number":1941,"title":"[BUG] Dual encryption key derivation (dynamic vs static salt) causes persistent decrypt failures and 50% CPU"}-{"author":{"id":"MDQ6VXNlcjEwODk3NDc4","is_bot":false,"login":"JxnLexn","name":"Jan Leon"},"body":"### OmniRoute Version\n\n3.7.8\n\n### Installation Method\n\nDocker / Docker Compose\n\n### Operating System\n\nLinux\n\n### OS Version\n\n_No response_\n\n### Node.js Version\n\n_No response_\n\n### Provider(s) Involved\n\nCodex\n\n### Model(s) Involved\n\nGPT-5.5\n\n### Client Tool\n\nVisual Studio Code (Github Copilot Chat)\n\n### Description\n\nThe costs and the analytics page show costs of $0.00 even though many tokens are being used and the prices per token are set. It was working before, but for the past few days it has stopped working. I am using a combo, but it has worked before using a combo. \nOn the costs page it also shows a fallback rate of 100%, even tough there was never a fallback to another model.\n\n### Steps to Reproduce\n\n1. Use a model/tokens\n2. Go to cost or analytics\n3. See $0.00 altough prices are set\n\n### Expected Behavior\n\nShow estimated costs\n\n### Actual Behavior\n\nDid not show estimated costs, instead $0.00\n\n### Test Impact\n\nUnsure\n\n### Error Logs / Output\n\n```shell\n\n```\n\n### Screenshots\n\n**Costs:**\n<img width=\"1336\" height=\"770\" alt=\"Image\" src=\"https://github.com/user-attachments/assets/1c58e896-5bec-4c01-af33-2071cf3196dc\" />\n\n**Analytics:**\n<img width=\"1333\" height=\"647\" alt=\"Image\" src=\"https://github.com/user-attachments/assets/441a5ebb-3b1f-44af-af1b-de7b2dfa2ba1\" />\n\n**Fallback Rate:**\n<img width=\"1314\" height=\"215\" alt=\"Image\" src=\"https://github.com/user-attachments/assets/67109ec7-496f-4add-980f-a65e8582ffe2\" />\n\n**Provider Breakdown:**\n<img width=\"1313\" height=\"217\" alt=\"Image\" src=\"https://github.com/user-attachments/assets/08ce8268-0dfd-4885-b9af-eb4b48f0319b\" />\n\n**Model Breakdown:**\n<img width=\"1319\" height=\"216\" alt=\"Image\" src=\"https://github.com/user-attachments/assets/d6d02c11-0d1e-4482-8346-3ac13a30d107\" />\n\n**Costs Pricing:**\n<img width=\"1310\" height=\"773\" alt=\"Image\" src=\"https://github.com/user-attachments/assets/f1e05848-c196-4816-a6b8-0dcd57444bd4\" />\n\n\n### Additional Context\n\n_No response_\n\n### Validation Plan\n\n_No response_","comments":[],"createdAt":"2026-05-04T09:57:53Z","labels":[{"id":"LA_kwDORPf6ys8AAAACYAlrFQ","name":"bug","description":"Something isn't working","color":"d73a4a"}],"number":1934,"title":"[BUG] Est. Cost $0.00"}diff --git a/scripts/check-permissions.sh b/scripts/check-permissions.shindex a58d046351..0c25116673 100755--- a/scripts/check-permissions.sh+++ b/scripts/check-permissions.sh@@ -8,11 +8,18 @@ if [ -n "$OMNIROUTE_MEMORY_MB" ]; thenexport NODE_OPTIONS="${NODE_OPTIONS:-} --max-old-space-size=${OMNIROUTE_MEMORY_MB}"fi-if [ -d "/app/data" ] && [ ! -w "/app/data" ]; then- echo "WARNING: /app/data is not writable by the current user (UID $(id -u))."- echo "Run this on the Docker host to fix:"- echo " sudo chown -R $(id -u):$(id -g) /app/data"- echo " chmod -R u+rwX ./data"+DATA_PATH="${DATA_DIR:-/app/data}"+if [ -d "$DATA_PATH" ] && [ ! -w "$DATA_PATH" ]; then+ echo "WARNING: $DATA_PATH is not writable by the current user (UID $(id -u))."+ if [ "${CONTAINER_HOST:-}" = "podman" ]; then+ echo "Rootless Podman maps container UIDs into a subordinate range."+ echo "Run this on the host to fix (using the host-side bind-mount path):"+ echo " podman unshare chown -R $(id -u):$(id -g) <host-data-dir>"+ else+ echo "Run this on the Docker host to fix (using the host-side bind-mount path):"+ echo " sudo chown -R $(id -u):$(id -g) <host-data-dir>"+ echo " chmod -R u+rwX <host-data-dir>"+ fifiexec "$@"diff --git a/src/app/(dashboard)/dashboard/api-manager/ApiManagerPageClient.tsx b/src/app/(dashboard)/dashboard/api-manager/ApiManagerPageClient.tsxindex 8b155975cf..43da508ffb 100644--- a/src/app/(dashboard)/dashboard/api-manager/ApiManagerPageClient.tsx+++ b/src/app/(dashboard)/dashboard/api-manager/ApiManagerPageClient.tsx@@ -30,6 +30,16 @@ import {const MAX_KEY_NAME_LENGTH = 200;const MAX_SELECTED_MODELS = 500;+function toLocalDateTimeInputValue(value: string | null | undefined): string {+ if (!value) return "";+ const date = new Date(value);+ if (Number.isNaN(date.getTime())) return "";+ const pad = (n: number) => String(n).padStart(2, "0");+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(+ date.getHours()+ )}:${pad(date.getMinutes())}`;+}+// Debounce hook for search optimizationfunction useDebouncedValue<T>(value: T, delay: number): T {const [debouncedValue, setDebouncedValue] = useState(value);@@ -2128,15 +2138,32 @@ const PermissionsModal = memo(function PermissionsModal({Key will automatically stop working after this date.</p></div>- <input- type="datetime-local"- value={expiresAt ? expiresAt.slice(0, 16) : ""}- onChange={(e) => {- const val = e.target.value;- setExpiresAt(val ? new Date(val).toISOString() : "");- }}- className="w-full px-2 py-1.5 text-sm border border-border rounded-md bg-background text-text-main"- />+ <div className="flex gap-2">+ <input+ type="datetime-local"+ value={toLocalDateTimeInputValue(expiresAt)}+ onChange={(e) => {+ const val = e.target.value;+ if (!val) {+ setExpiresAt("");+ return;+ }+ const date = new Date(val);+ if (!Number.isNaN(date.getTime())) {+ setExpiresAt(date.toISOString());+ }+ }}+ className="min-w-0 flex-1 px-2 py-1.5 text-sm border border-border rounded-md bg-background text-text-main"+ />+ <button+ type="button"+ onClick={() => setExpiresAt("")}+ disabled={!expiresAt}+ className="shrink-0 px-3 py-1.5 text-sm font-medium border border-border rounded-md text-text-muted hover:text-text-main hover:bg-black/5 dark:hover:bg-white/5 disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:bg-transparent"+ >+ {tc("clear")}+ </button>+ </div></div>{/* Management Access */}<div className="flex flex-col gap-2 p-3 rounded-lg border border-border bg-surface/40">diff --git a/src/app/(dashboard)/dashboard/provider-stats/page.tsx b/src/app/(dashboard)/dashboard/provider-stats/page.tsxnew file mode 100644index 0000000000..9be2cb0a5a--- /dev/null+++ b/src/app/(dashboard)/dashboard/provider-stats/page.tsx@@ -0,0 +1,499 @@+"use client";++/**+ * Provider Stats Dashboard+ *+ * Shows per-provider and per-model statistics aggregated from call_logs,+ * plus in-memory combo metrics and telemetry data.+ */++import { useState, useEffect, useCallback, Fragment } from "react";+import { Card } from "@/shared/components";++interface ProviderStat {+ provider: string;+ totalRequests: number;+ successfulRequests: number;+ avgLatencyMs: number;+ totalTokensIn: number;+ totalTokensOut: number;+}++interface ModelStat {+ provider: string;+ model: string;+ requests: number;+ avgLatencyMs: number;+ successfulRequests: number;+}++interface ToolLatencyStat {+ avgTtftAfterToolMs: number;+ avgGapAfterToolMs: number;+ measurementCount: number;+}++type SortKey = "totalRequests" | "successfulRequests" | "avgLatencyMs" | "totalTokensIn" | "totalTokensOut" | "avgTtftAfterToolMs" | "avgGapAfterToolMs";+type SortDir = "asc" | "desc";++function formatNumber(n: number | null): string {+ if (n == null) return "0";+ if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;+ if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`;+ return n.toString();+}++function formatLatency(ms: number | null): string {+ if (ms == null) return "—";+ if (ms >= 1000) return `${(ms / 1000).toFixed(1)}s`;+ return `${Math.round(ms)}ms`;+}++function successRate(successful: number, total: number): string {+ if (total === 0) return "—";+ return `${((successful / total) * 100).toFixed(1)}%`;+}++export default function ProviderStatsPage() {+ const [data, setData] = useState<{+ providers: ProviderStat[];+ models: ModelStat[];+ comboMetrics: Record<string, unknown>;+ telemetry: Record<string, unknown>;+ toolLatency: Record<string, ToolLatencyStat>;+ } | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [lastRefresh, setLastRefresh] = useState<Date | null>(null);+ const [sortKey, setSortKey] = useState<SortKey>("totalRequests");+ const [sortDir, setSortDir] = useState<SortDir>("desc");+ const [expandedProvider, setExpandedProvider] = useState<string | null>(null);++ const fetchData = useCallback(async () => {+ try {+ const res = await fetch("/api/provider-stats");+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ const json = await res.json();+ setData(json);+ setError(null);+ setLastRefresh(new Date());+ } catch (err) {+ setError(err instanceof Error ? err.message : "Unknown error");+ }+ }, []);++ useEffect(() => {+ fetchData();+ const interval = setInterval(fetchData, 30000);+ return () => clearInterval(interval);+ }, [fetchData]);++ const handleSort = (key: SortKey) => {+ if (sortKey === key) {+ setSortDir(sortDir === "desc" ? "asc" : "desc");+ } else {+ setSortKey(key);+ setSortDir("desc");+ }+ };++ // Compute summary stats+ const totalRequests = data?.providers.reduce((s, p) => s + (p.totalRequests || 0), 0) ?? 0;+ const totalSuccessful = data?.providers.reduce((s, p) => s + (p.successfulRequests || 0), 0) ?? 0;+ const avgLatency =+ data?.providers.length+ ? Math.round(+ data.providers.reduce((s, p) => s + (p.avgLatencyMs || 0), 0) / data.providers.length+ )+ : 0;+ const activeProviders = data?.providers.length ?? 0;++ // Sorted providers+ const sortedProviders = [...(data?.providers ?? [])].sort((a, b) => {+ if (sortKey === "avgTtftAfterToolMs" || sortKey === "avgGapAfterToolMs") {+ const aLatency = data?.toolLatency?.[a.provider] ?? null;+ const bLatency = data?.toolLatency?.[b.provider] ?? null;+ const va = aLatency ? (aLatency[sortKey] as number) ?? 0 : 0;+ const vb = bLatency ? (bLatency[sortKey] as number) ?? 0 : 0;+ return sortDir === "desc" ? vb - va : va - vb;+ }+ const va = (a[sortKey] as number) ?? 0;+ const vb = (b[sortKey] as number) ?? 0;+ return sortDir === "desc" ? vb - va : va - vb;+ });++ // Group models by provider+ const modelsByProvider = new Map<string, ModelStat[]>();+ for (const m of data?.models ?? []) {+ if (!modelsByProvider.has(m.provider)) modelsByProvider.set(m.provider, []);+ modelsByProvider.get(m.provider)!.push(m);+ }++ // Sort helper icon+ const SortIcon = ({ column }: { column: SortKey }) => {+ if (sortKey !== column) return null;+ return (+ <span className="material-symbols-outlined text-[14px] ml-1 align-middle text-primary">+ {sortDir === "desc" ? "arrow_downward" : "arrow_upward"}+ </span>+ );+ };++ if (!data && !error) {+ return (+ <div className="flex items-center justify-center min-h-[400px]">+ <div className="text-center">+ <div className="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />+ <p className="text-text-muted mt-4">Loading provider stats...</p>+ </div>+ </div>+ );+ }++ if (error && !data) {+ return (+ <div>+ <div className="bg-red-500/10 border border-red-500/30 rounded-xl p-6 text-center">+ <span className="material-symbols-outlined text-red-500 text-[32px] mb-2">error</span>+ <p className="text-red-400">Failed to load provider stats: {error}</p>+ <button+ onClick={fetchData}+ className="mt-4 px-4 py-2 rounded-lg bg-primary/10 text-primary text-sm hover:bg-primary/20 transition-colors"+ >+ Retry+ </button>+ </div>+ </div>+ );+ }++ return (+ <div className="space-y-6">+ {/* Header */}+ <div className="flex items-center justify-end gap-3">+ {lastRefresh && (+ <span className="text-xs text-text-muted">+ Updated {lastRefresh.toLocaleTimeString()}+ </span>+ )}+ <button+ onClick={fetchData}+ className="p-2 rounded-lg bg-surface hover:bg-surface/80 text-text-muted hover:text-text-main transition-colors"+ title="Refresh"+ >+ <span className="material-symbols-outlined text-[18px]">refresh</span>+ </button>+ </div>++ {/* Summary Cards */}+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">+ <Card className="p-4">+ <div className="flex items-center gap-3 mb-2">+ <div className="flex items-center justify-center size-8 rounded-lg bg-primary/10 text-primary">+ <span className="material-symbols-outlined text-[18px]">analytics</span>+ </div>+ <span className="text-sm text-text-muted">Total Requests</span>+ </div>+ <p className="text-xl font-semibold text-text-main">{formatNumber(totalRequests)}</p>+ </Card>++ <Card className="p-4">+ <div className="flex items-center gap-3 mb-2">+ <div className="flex items-center justify-center size-8 rounded-lg bg-blue-500/10 text-blue-500">+ <span className="material-symbols-outlined text-[18px]">timer</span>+ </div>+ <span className="text-sm text-text-muted">Avg Latency</span>+ </div>+ <p className="text-xl font-semibold text-text-main">{formatLatency(avgLatency)}</p>+ </Card>++ <Card className="p-4">+ <div className="flex items-center gap-3 mb-2">+ <div className="flex items-center justify-center size-8 rounded-lg bg-green-500/10 text-green-500">+ <span className="material-symbols-outlined text-[18px]">check_circle</span>+ </div>+ <span className="text-sm text-text-muted">Success Rate</span>+ </div>+ <p className="text-xl font-semibold text-text-main">+ {successRate(totalSuccessful, totalRequests)}+ </p>+ </Card>++ <Card className="p-4">+ <div className="flex items-center gap-3 mb-2">+ <div className="flex items-center justify-center size-8 rounded-lg bg-purple-500/10 text-purple-500">+ <span className="material-symbols-outlined text-[18px]">dns</span>+ </div>+ <span className="text-sm text-text-muted">Active Providers</span>+ </div>+ <p className="text-xl font-semibold text-text-main">{activeProviders}</p>+ </Card>+ </div>++ {/* Provider Table */}+ <Card className="p-5">+ <div className="flex items-center justify-between mb-4">+ <h2 className="text-lg font-semibold text-text-main flex items-center gap-2">+ <span className="material-symbols-outlined text-[20px] text-primary">table_chart</span>+ Provider Breakdown+ </h2>+ <span className="text-xs text-text-muted">{activeProviders} providers</span>+ </div>++ <div className="overflow-x-auto">+ <table className="w-full text-sm">+ <thead>+ <tr className="border-b border-border">+ <th className="text-left py-2 px-3 text-text-muted font-medium">Provider</th>+ <th+ className="text-right py-2 px-3 text-text-muted font-medium cursor-pointer hover:text-text-main transition-colors select-none"+ onClick={() => handleSort("totalRequests")}+ >+ Requests <SortIcon column="totalRequests" />+ </th>+ <th+ className="text-right py-2 px-3 text-text-muted font-medium cursor-pointer hover:text-text-main transition-colors select-none"+ onClick={() => handleSort("successfulRequests")}+ >+ Success <SortIcon column="successfulRequests" />+ </th>+ <th className="text-right py-2 px-3 text-text-muted font-medium">Rate</th>+ <th+ className="text-right py-2 px-3 text-text-muted font-medium cursor-pointer hover:text-text-main transition-colors select-none"+ onClick={() => handleSort("avgLatencyMs")}+ >+ Avg Latency <SortIcon column="avgLatencyMs" />+ </th>+ <th+ className="text-right py-2 px-3 text-text-muted font-medium cursor-pointer hover:text-text-main transition-colors select-none"+ onClick={() => handleSort("totalTokensIn")}+ >+ Tokens In <SortIcon column="totalTokensIn" />+ </th>+ <th+ className="text-right py-2 px-3 text-text-muted font-medium cursor-pointer hover:text-text-main transition-colors select-none"+ onClick={() => handleSort("totalTokensOut")}+ >+ Tokens Out <SortIcon column="totalTokensOut" />+ </th>+ <th+ className="text-right py-2 px-3 text-text-muted font-medium cursor-pointer hover:text-text-main transition-colors select-none"+ onClick={() => handleSort("avgTtftAfterToolMs")}+ >+ TTFT After Tool <SortIcon column="avgTtftAfterToolMs" />+ </th>+ <th+ className="text-right py-2 px-3 text-text-muted font-medium cursor-pointer hover:text-text-main transition-colors select-none"+ onClick={() => handleSort("avgGapAfterToolMs")}+ >+ Gap After Tool <SortIcon column="avgGapAfterToolMs" />+ </th>+ <th className="py-2 px-3 w-8" />+ </tr>+ </thead>+ <tbody>+ {sortedProviders.map((p) => {+ const isExpanded = expandedProvider === p.provider;+ const models = modelsByProvider.get(p.provider) ?? [];+ const rate = p.totalRequests > 0 ? (p.successfulRequests / p.totalRequests) * 100 : 0;+ return (+ <Fragment key={p.provider}>+ <tr+ className="border-b border-border/50 hover:bg-surface/50 transition-colors cursor-pointer"+ onClick={() =>+ setExpandedProvider(isExpanded ? null : models.length > 0 ? p.provider : null)+ }+ >+ <td className="py-2.5 px-3 font-medium text-text-main">+ {p.provider}+ </td>+ <td className="py-2.5 px-3 text-right tabular-nums text-text-main">+ {formatNumber(p.totalRequests)}+ </td>+ <td className="py-2.5 px-3 text-right tabular-nums text-text-main">+ {formatNumber(p.successfulRequests)}+ </td>+ <td className="py-2.5 px-3 text-right tabular-nums">+ <span+ className={+ rate >= 99+ ? "text-green-500"+ : rate >= 95+ ? "text-amber-500"+ : "text-red-500"+ }+ >+ {rate.toFixed(1)}%+ </span>+ </td>+ <td className="py-2.5 px-3 text-right tabular-nums text-text-main">+ {formatLatency(p.avgLatencyMs)}+ </td>+ <td className="py-2.5 px-3 text-right tabular-nums text-text-muted">+ {formatNumber(p.totalTokensIn)}+ </td>+ <td className="py-2.5 px-3 text-right tabular-nums text-text-muted">+ {formatNumber(p.totalTokensOut)}+ </td>+ <td className="py-2.5 px-3 text-right tabular-nums text-text-main">+ {formatLatency(data?.toolLatency?.[p.provider]?.avgTtftAfterToolMs ?? null)}+ </td>+ <td className="py-2.5 px-3 text-right tabular-nums text-text-main">+ {formatLatency(data?.toolLatency?.[p.provider]?.avgGapAfterToolMs ?? null)}+ </td>+ <td className="py-2.5 px-3 text-center">+ {models.length > 0 && (+ <span+ className={`material-symbols-outlined text-[16px] text-text-muted transition-transform ${+ isExpanded ? "rotate-90" : ""+ }`}+ >+ chevron_right+ </span>+ )}+ </td>+ </tr>+ {isExpanded && models.length > 0 && (+ <tr key={`${p.provider}-models`}>+ <td colSpan={10} className="p-0">+ <div className="bg-black/[0.02] dark:bg-white/[0.02] border-b border-border/30">+ <table className="w-full text-xs">+ <thead>+ <tr className="text-text-muted">+ <th className="text-left py-1.5 px-6 pl-12 font-medium">Model</th>+ <th className="text-right py-1.5 px-3 font-medium">Requests</th>+ <th className="text-right py-1.5 px-3 font-medium">Success</th>+ <th className="text-right py-1.5 px-3 font-medium">Rate</th>+ <th className="text-right py-1.5 px-3 font-medium">Avg Latency</th>+ <th className="px-3 w-8" />+ </tr>+ </thead>+ <tbody>+ {models.map((m) => {+ const mRate =+ m.requests > 0 ? (m.successfulRequests / m.requests) * 100 : 0;+ return (+ <tr key={m.model} className="border-t border-border/20">+ <td className="py-1.5 px-6 pl-12 font-mono text-text-main">+ {m.model}+ </td>+ <td className="py-1.5 px-3 text-right tabular-nums text-text-main">+ {formatNumber(m.requests)}+ </td>+ <td className="py-1.5 px-3 text-right tabular-nums text-text-main">+ {formatNumber(m.successfulRequests)}+ </td>+ <td className="py-1.5 px-3 text-right tabular-nums">+ <span+ className={+ mRate >= 99+ ? "text-green-500"+ : mRate >= 95+ ? "text-amber-500"+ : "text-red-500"+ }+ >+ {mRate.toFixed(1)}%+ </span>+ </td>+ <td className="py-1.5 px-3 text-right tabular-nums text-text-main">+ {formatLatency(m.avgLatencyMs)}+ </td>+ <td className="px-3 w-8" />+ </tr>+ );+ })}+ </tbody>+ </table>+ </div>+ </td>+ </tr>+ )}+ </Fragment>+ );+ })}+ {sortedProviders.length === 0 && (+ <tr>+ <td colSpan={10} className="py-8 text-center text-text-muted">+ No provider data recorded yet.+ </td>+ </tr>+ )}+ </tbody>+ </table>+ </div>+ </Card>++ {/* In-Memory Metrics */}+ {data?.comboMetrics && Object.keys(data.comboMetrics).length > 0 && (+ <Card+ title="Combo Metrics"+ subtitle="Per-combo latency and throughput from streaming"+ icon="speed"+ className="p-5"+ >+ <div className="overflow-x-auto">+ <table className="w-full text-sm">+ <thead>+ <tr className="border-b border-border">+ <th className="text-left py-2 px-3 text-text-muted font-medium">Combo</th>+ <th className="text-right py-2 px-3 text-text-muted font-medium">Requests</th>+ <th className="text-right py-2 px-3 text-text-muted font-medium">Avg TTFT</th>+ <th className="text-right py-2 px-3 text-text-muted font-medium">Avg Total</th>+ <th className="text-right py-2 px-3 text-text-muted font-medium">Success</th>+ </tr>+ </thead>+ <tbody>+ {Object.entries(data.comboMetrics).map(([name, m]: [string, any]) => (+ <tr key={name} className="border-b border-border/50 hover:bg-surface/50 transition-colors">+ <td className="py-2 px-3 font-medium text-text-main">{name}</td>+ <td className="py-2 px-3 text-right tabular-nums text-text-main">+ {formatNumber(m.requestCount ?? m.totalRequests ?? 0)}+ </td>+ <td className="py-2 px-3 text-right tabular-nums text-text-main">+ {formatLatency(m.avgTtft ?? m.ttftMs ?? null)}+ </td>+ <td className="py-2 px-3 text-right tabular-nums text-text-main">+ {formatLatency(m.avgLatency ?? m.avgTotalMs ?? null)}+ </td>+ <td className="py-2 px-3 text-right tabular-nums">+ {typeof m.successRate === "number" ? `${(m.successRate * 100).toFixed(1)}%` : "—"}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ </Card>+ )}++ {/* Telemetry Phase Breakdown */}+ {data?.telemetry && Object.keys(data.telemetry).length > 0 && (+ <Card+ title="Request Telemetry"+ subtitle="7-phase pipeline breakdown (last 5 minutes)"+ icon="route"+ className="p-5"+ >+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">+ {Object.entries(data.telemetry).map(([key, val]: [string, any]) => {+ if (val == null || typeof val === "object") return null;+ return (+ <div+ key={key}+ className="rounded-lg border border-border/40 bg-surface/30 p-3"+ >+ <p className="text-xs text-text-muted uppercase tracking-wide">+ {key.replace(/([A-Z])/g, " $1").replace(/_/g, " ")}+ </p>+ <p className="text-lg font-semibold text-text-main mt-1 tabular-nums">+ {typeof val === "number" ? formatNumber(val) : String(val)}+ </p>+ </div>+ );+ })}+ </div>+ </Card>+ )}+ </div>+ );+}diff --git a/src/app/(dashboard)/dashboard/settings/ai/page.tsx b/src/app/(dashboard)/dashboard/settings/ai/page.tsxindex 0770715dda..21b16f5de3 100644--- a/src/app/(dashboard)/dashboard/settings/ai/page.tsx+++ b/src/app/(dashboard)/dashboard/settings/ai/page.tsx@@ -4,6 +4,7 @@ import { useTranslations } from "next-intl";import ThinkingBudgetTab from "../components/ThinkingBudgetTab";import VisionBridgeSettingsTab from "../components/VisionBridgeSettingsTab";import SystemPromptTab from "../components/SystemPromptTab";+import ResponsesStatePolicyTab from "../components/ResponsesStatePolicyTab";import CodexFastTierTab from "../components/CodexFastTierTab";import ClaudeFastModeTab from "../components/ClaudeFastModeTab";import MemorySkillsTab from "../components/MemorySkillsTab";@@ -17,6 +18,7 @@ export default function SettingsAiPage() {<ThinkingBudgetTab /><VisionBridgeSettingsTab /><SystemPromptTab />+ <ResponsesStatePolicyTab /><CodexFastTierTab /><ClaudeFastModeTab /><MemorySkillsTab />diff --git a/src/app/(dashboard)/dashboard/settings/components/ResponsesStatePolicyTab.tsx b/src/app/(dashboard)/dashboard/settings/components/ResponsesStatePolicyTab.tsxnew file mode 100644index 0000000000..3494631920--- /dev/null+++ b/src/app/(dashboard)/dashboard/settings/components/ResponsesStatePolicyTab.tsx@@ -0,0 +1,120 @@+"use client";++import { useEffect, useState, useRef } from "react";+import { useTranslations } from "next-intl";+import { Card, Select } from "@/shared/components";+import {+ DEFAULT_RESPONSES_PREVIOUS_RESPONSE_ID_MODE,+ RESPONSES_PREVIOUS_RESPONSE_ID_MODES,+ type ResponsesPreviousResponseIdMode,+} from "@/shared/constants/responsesPreviousResponseId";++const MODE_SET = new Set<string>(RESPONSES_PREVIOUS_RESPONSE_ID_MODES);++function normalizeMode(value: unknown): ResponsesPreviousResponseIdMode {+ return typeof value === "string" && MODE_SET.has(value)+ ? (value as ResponsesPreviousResponseIdMode)+ : DEFAULT_RESPONSES_PREVIOUS_RESPONSE_ID_MODE;+}++export default function ResponsesStatePolicyTab() {+ const [mode, setMode] = useState<ResponsesPreviousResponseIdMode>(+ DEFAULT_RESPONSES_PREVIOUS_RESPONSE_ID_MODE+ );+ const [loading, setLoading] = useState(true);+ const [saving, setSaving] = useState(false);+ const [status, setStatus] = useState<"" | "saved" | "error">("");+ const t = useTranslations("settings");++ useEffect(() => {+ let cancelled = false;+ fetch("/api/settings")+ .then((res) => res.json())+ .then((data) => {+ if (cancelled) return;+ setMode(normalizeMode(data?.responsesPreviousResponseIdMode));+ setLoading(false);+ })+ .catch(() => {+ if (!cancelled) setLoading(false);+ });+ return () => {+ cancelled = true;+ };+ }, []);++ const save = async (nextMode: ResponsesPreviousResponseIdMode) => {+ if (saving || loading || nextMode === mode) return;+ const previousMode = mode;+ setMode(nextMode);+ setSaving(true);+ setStatus("");++ try {+ const res = await fetch("/api/settings", {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ responsesPreviousResponseIdMode: nextMode }),+ });+ if (!res.ok) {+ setMode(previousMode);+ setStatus("error");+ return;+ }+ setStatus("saved");+ setTimeout(() => setStatus(""), 2000);+ } catch {+ setMode(previousMode);+ setStatus("error");+ } finally {+ setSaving(false);+ }+ };++ return (+ <Card>+ <div className="flex items-center gap-3 mb-3">+ <div className="p-2 rounded-lg bg-emerald-500/10 text-emerald-500">+ <span className="material-symbols-outlined text-[20px]" aria-hidden="true">+ account_tree+ </span>+ </div>+ <div className="flex-1">+ <h3 className="text-lg font-semibold">{t("responsesStateTitle")}</h3>+ <p className="text-sm text-text-muted">{t("responsesStateDesc")}</p>+ </div>+ <div className="min-w-[7rem] flex justify-end">+ {status === "saved" && (+ <span className="text-xs font-medium text-emerald-500 flex items-center gap-1">+ <span className="material-symbols-outlined text-[14px]">check_circle</span>{" "}+ {t("saved")}+ </span>+ )}+ {status === "error" && (+ <span className="text-xs font-medium text-rose-500 flex items-center gap-1">+ <span className="material-symbols-outlined text-[14px]">error</span>{" "}+ {t("responsesStateSaveError")}+ </span>+ )}+ </div>+ </div>++ <Select+ label={t("responsesStateModeLabel")}+ value={mode}+ disabled={loading || saving}+ onChange={(e) => save(normalizeMode(e.target.value))}+ options={[+ { value: "auto", label: t("responsesStateModeAuto") },+ { value: "strip", label: t("responsesStateModeStrip") },+ { value: "preserve", label: t("responsesStateModePreserve") },+ ]}+ />++ <p className="mt-4 text-xs text-text-muted/80 flex items-start gap-1.5 leading-relaxed">+ <span className="material-symbols-outlined text-[14px] mt-0.5">info</span>+ <span>{t("responsesStateHint")}</span>+ </p>+ </Card>+ );+}diff --git a/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/index.tsx b/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/index.tsxindex 64a009d665..7653c1a16f 100644--- a/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/index.tsx+++ b/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/index.tsx@@ -363,10 +363,17 @@ export default function ProviderLimits({const errorMsg = errorData.error || response.statusText;if (response.status === 404) return;if (response.status === 401) {+ // The on-demand path already attempts a forced, serialized re-mint+ // before surfacing a 401, so a 401 here means the token is genuinely+ // dead — make that actionable instead of a silent empty card.+ const reauthMsg = /re-?authenticat|sign in|log in/i.test(errorMsg)+ ? errorMsg+ : `${errorMsg} — re-authenticate this account.`;setQuotaData((prev) => ({...prev,- [connectionId]: { quotas: [], message: errorMsg },+ [connectionId]: { quotas: [], message: reauthMsg },}));+ setErrors((prev) => ({ ...prev, [connectionId]: reauthMsg }));return;}throw new Error(`HTTP ${response.status}: ${errorMsg}`);diff --git a/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/parts/QuotaCardHeader.tsx b/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/parts/QuotaCardHeader.tsxindex 855c2b8579..2b3cf96acb 100644--- a/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/parts/QuotaCardHeader.tsx+++ b/src/app/(dashboard)/dashboard/usage/components/ProviderLimits/parts/QuotaCardHeader.tsx@@ -4,7 +4,8 @@ import { useTranslations } from "next-intl";import Badge from "@/shared/components/Badge";import ProviderIcon from "@/shared/components/ProviderIcon";import { pickDisplayValue } from "@/shared/utils/maskEmail";-import { STATUS_EMOJI, type CardStatus } from "../utils";+import { STATUS_EMOJI, formatCountdown, type CardStatus } from "../utils";+import { translateUsageOrFallback } from "../i18nFallback";interface Props {connection: any;@@ -41,6 +42,27 @@ export default function QuotaCardHeader({connection.provider);+ // OAuth token expiry — informative only. Shown small/blue for connections that+ // expose a concrete token expiry (e.g. Codex), so an operator can see at a+ // glance when the access token rotates. Hidden for API-key / no-expiry connections.+ const tokenExpiryIso =+ connection.authType === "oauth"+ ? connection.tokenExpiresAt || connection.expiresAt || null+ : null;+ const tokenExpiryMs = tokenExpiryIso ? new Date(tokenExpiryIso).getTime() : NaN;+ const hasTokenExpiry = Number.isFinite(tokenExpiryMs);+ const tokenCountdown = hasTokenExpiry ? formatCountdown(tokenExpiryIso) : null;+ const tokenExpiryLabel = !hasTokenExpiry+ ? null+ : tokenCountdown+ ? translateUsageOrFallback(t, "tokenExpiresIn", `Token expires in ${tokenCountdown}`, {+ time: tokenCountdown,+ })+ : translateUsageOrFallback(t, "tokenExpired", "Token expired");+ const tokenExpiryTitle = hasTokenExpiry+ ? new Date(tokenExpiryMs).toLocaleString()+ : undefined;+return (<div className="flex items-start justify-between gap-2 px-3 pt-2.5 pb-1.5"><div className="flex items-start gap-2 min-w-0 flex-1">@@ -85,6 +107,14 @@ export default function QuotaCardHeader({<span className="text-[11px] text-text-muted truncate" title={accountName ?? ""}>{accountName}</span>+ {tokenExpiryLabel && (+ <span+ className={`text-[10px] truncate ${tokenCountdown ? "text-sky-500" : "text-rose-500"}`}+ title={tokenExpiryTitle}+ >+ {tokenExpiryLabel}+ </span>+ )}</div></div><div className="flex items-center gap-0.5 shrink-0">diff --git a/src/app/api/oauth/kiro/social-exchange/route.ts b/src/app/api/oauth/kiro/social-exchange/route.tsindex f97ac7dd06..d668ed02eb 100755--- a/src/app/api/oauth/kiro/social-exchange/route.ts+++ b/src/app/api/oauth/kiro/social-exchange/route.ts@@ -11,6 +11,7 @@ import { KIRO_CONFIG } from "@/lib/oauth/constants/oauth";const socialExchangeSchema = z.object({deviceCode: z.string().min(1, "Missing deviceCode or provider"),provider: z.string().min(1, "Missing deviceCode or provider"),+ targetProvider: z.string().optional(),});/**@@ -47,7 +48,7 @@ export async function POST(request: Request) {}try {- const { deviceCode, provider } = validation.data;+ const { deviceCode, provider, targetProvider } = validation.data;const response = await fetch(KIRO_CONFIG.socialDevicePollUrl, {method: "POST",@@ -84,7 +85,7 @@ export async function POST(request: Request) {}const connection: any = await createProviderConnection({- provider: "kiro",+ provider: targetProvider || "kiro",authType: "oauth",accessToken: data.accessToken,refreshToken: data.refreshToken,diff --git a/src/app/api/provider-stats/route.ts b/src/app/api/provider-stats/route.tsnew file mode 100644index 0000000000..738b9f4747--- /dev/null+++ b/src/app/api/provider-stats/route.ts@@ -0,0 +1,54 @@+import { NextResponse } from "next/server";+import { getProviderCallStats, getModelCallStats } from "@/lib/db/providerStats";+import { AI_PROVIDERS } from "@/shared/constants/providers";++export async function GET() {+ try {+ // Hard Rule #5: SQL lives in src/lib/db/providerStats.ts, not inline here.+ const providerStats = getProviderCallStats();+ const modelStats = getModelCallStats();++ let comboMetrics: Record<string, unknown> = {};+ try {+ const { getAllComboMetrics } = await import(+ "@omniroute/open-sse/services/comboMetrics.ts"+ );+ comboMetrics = getAllComboMetrics() as Record<string, unknown>;+ } catch {}++ let telemetry: Record<string, unknown> = {};+ try {+ const { getTelemetrySummary } = await import("@/shared/utils/requestTelemetry");+ telemetry = getTelemetrySummary(300000) as Record<string, unknown>;+ } catch {}++ let toolLatency: Record<string, unknown> = {};+ try {+ const { getToolLatencyByProvider } = await import(+ "@omniroute/open-sse/services/toolLatencyTracker"+ );+ toolLatency = getToolLatencyByProvider() as Record<string, unknown>;+ } catch {}++ const resolveName = (provider: string, nodeName: string | null) => {+ if (nodeName?.trim()) return nodeName.trim();+ const info = AI_PROVIDERS[provider as keyof typeof AI_PROVIDERS];+ return info?.name || provider;+ };++ const providers = providerStats.map((p: any) => ({+ ...p,+ provider: resolveName(p.provider, p.nodeName),+ }));++ const models = modelStats.map((m: any) => ({+ ...m,+ provider: resolveName(m.provider, m.nodeName),+ }));++ return NextResponse.json({ providers, models, comboMetrics, telemetry, toolLatency });+ } catch (error) {+ console.error("Error fetching provider stats:", error);+ return NextResponse.json({ error: "Failed to fetch provider stats" }, { status: 500 });+ }+}diff --git a/src/app/api/providers/[id]/models/route.ts b/src/app/api/providers/[id]/models/route.tsindex 37e73375c3..f2d4bcb2dc 100755--- a/src/app/api/providers/[id]/models/route.ts+++ b/src/app/api/providers/[id]/models/route.ts@@ -23,6 +23,7 @@ import {import { getProviderOutboundGuard } from "@/shared/network/outboundUrlGuard";import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error";import { getStaticQoderModels } from "@omniroute/open-sse/services/qoderCli.ts";+import { fetchGitHubCopilotModels } from "@omniroute/open-sse/services/githubCopilotModels.ts";import { getAntigravityHeaders } from "@omniroute/open-sse/services/antigravityHeaders.ts";import { ensureAntigravityProjectAssigned } from "@omniroute/open-sse/services/antigravityProjectBootstrap.ts";import {@@ -76,6 +77,7 @@ import {isAutoFetchModelsEnabled,persistDiscoveredModels,} from "@/lib/providerModels/modelDiscovery";+import { getSyncedAvailableModels } from "@/lib/db/models";import { fetchCursorAgentModels } from "@/lib/providerModels/cursorAgent";type JsonRecord = Record<string, unknown>;@@ -794,8 +796,32 @@ export async function GET(const accessToken = typeof connection.accessToken === "string" ? connection.accessToken : "";const autoFetchModels = isAutoFetchModelsEnabled(connection.providerSpecificData);const cachedDiscoveryModels = await getCachedDiscoveredModels(provider, connectionId);- const registryCatalogModels = getModelsByProviderId(provider) || [];- const specialtyCatalogModels = getStaticModelsForProvider(provider) || [];++ // Check for synced models from ANY connection of this provider.+ // When sync has been performed (even on a different connection),+ // use the synced list as the authoritative source instead of static models.+ let providerSyncedModels: Array<{+ id: string;+ name: string;+ apiFormat?: string;+ supportedEndpoints?: string[];+ }> | null = null;+ try {+ const allSynced = await getSyncedAvailableModels(provider);+ if (Array.isArray(allSynced) && allSynced.length > 0) {+ providerSyncedModels = allSynced.map((m) => ({+ id: m.id,+ name: m.name || m.id,+ ...(m.apiFormat ? { apiFormat: m.apiFormat } : {}),+ ...(m.supportedEndpoints ? { supportedEndpoints: m.supportedEndpoints } : {}),+ }));+ }+ } catch {+ // DB unavailable — fall through to static catalog+ }++ const registryCatalogModels = providerSyncedModels ?? (getModelsByProviderId(provider) || []);+ const specialtyCatalogModels = providerSyncedModels ? [] : (getStaticModelsForProvider(provider) || []);const toLocalCatalogModels = () => {const localCatalog = mergeLocalCatalogModels(registryCatalogModels, specialtyCatalogModels);@@ -897,10 +923,52 @@ export async function GET(});}- const fallback = buildLocalCatalogResponse(- "No remote models discovered — using local catalog"- );- if (fallback) return fallback;+ // Empty discovery just cleared THIS connection's synced cache (via+ // persistDiscoveredModels([])). `providerSyncedModels` was read at the top+ // of the handler and is now stale, so it must not leak the just-cleared+ // models back into the response (#3148 made synced authoritative for the+ // normal path; here we re-read the current state instead). Re-derive the+ // local catalog from the provider's remaining synced models (union across+ // its other connections) or the static catalog when none remain.+ let freshSynced: Awaited<ReturnType<typeof getSyncedAvailableModels>> = [];+ try {+ freshSynced = await getSyncedAvailableModels(provider);+ } catch {+ /* DB unavailable — fall through to static catalog */+ }+ const freshRegistry = freshSynced.length+ ? freshSynced.map((m) => ({+ id: m.id,+ name: m.name || m.id,+ ...(m.apiFormat ? { apiFormat: m.apiFormat } : {}),+ ...(m.supportedEndpoints ? { supportedEndpoints: m.supportedEndpoints } : {}),+ }))+ : getModelsByProviderId(provider) || [];+ const freshSpecialty = freshSynced.length ? [] : getStaticModelsForProvider(provider) || [];+ const freshLocal = mergeLocalCatalogModels(freshRegistry, freshSpecialty).map((model) => ({+ id: model.id,+ name: model.name || model.id,+ ...((model as Record<string, unknown>).apiFormat+ ? { apiFormat: (model as Record<string, unknown>).apiFormat as string | undefined }+ : {}),+ ...((model as Record<string, unknown>).supportedEndpoints+ ? {+ supportedEndpoints: (model as Record<string, unknown>).supportedEndpoints as+ | string[]+ | undefined,+ }+ : {}),+ ...(freshRegistry.length > 0 ? { owned_by: provider } : {}),+ }));+ if (freshLocal.length > 0) {+ return buildResponse({+ provider,+ connectionId,+ models: freshLocal,+ source: "local_catalog",+ warning: "No remote models discovered — using local catalog",+ });+ }return buildResponse({provider,@@ -1901,6 +1969,56 @@ export async function GET(});}+ if (provider === "github") {+ // #3120/#3121 — GitHub Copilot's catalog is per-account and dynamic. The+ // registry static list never refreshes and advertises non-entitled models+ // (e.g. gemini previews) that fail upstream when tested. Discover the live+ // catalog from api.githubcopilot.com/models with the Copilot bearer ++ // Copilot chat headers; fall back to the static registry catalog when the+ // live fetch is unavailable (offline/unauthed/error) so import never breaks.+ const cachedResponse = maybeReturnCachedDiscovery();+ if (cachedResponse) return cachedResponse;++ const autoFetchDisabledResponse = maybeReturnAutoFetchDisabled();+ if (autoFetchDisabledResponse) return autoFetchDisabledResponse;++ const psd = asRecord(connection.providerSpecificData);+ // The /models endpoint requires the short-lived Copilot token (same as the+ // chat executor), not the raw GitHub OAuth access token.+ const copilotToken =+ toNonEmptyString(psd.copilotToken) || toNonEmptyString(accessToken) || null;++ const discovery = await fetchGitHubCopilotModels({+ token: copilotToken,+ fetchImpl: (url, init) =>+ safeOutboundFetch(url as string, {+ ...SAFE_OUTBOUND_FETCH_PRESETS.modelsDiscovery,+ guard: getProviderOutboundGuard(),+ proxyConfig: proxy,+ ...(init as Record<string, unknown>),+ }),+ fallbackModels: toLocalCatalogModels(),+ });++ if (discovery.source === "api") {+ return buildApiDiscoveryResponse(discovery.models);+ }++ // Live discovery unavailable — preserve cached/static catalog behavior.+ const fallback = buildDiscoveryFallbackResponse({+ cacheWarning: "Copilot models API unavailable — using cached catalog",+ localWarning: "Copilot models API unavailable — using local catalog",+ });+ if (fallback) return fallback;+ return buildResponse({+ provider,+ connectionId,+ models: discovery.models,+ source: "local_catalog",+ warning: "Copilot models API unavailable — using local catalog",+ });+ }+if (isAnthropicCompatibleProvider(provider)) {const cachedResponse = maybeReturnCachedDiscovery();if (cachedResponse) return cachedResponse;diff --git a/src/i18n/messages/de.json b/src/i18n/messages/de.jsonindex a781691d01..4a350398b8 100644--- a/src/i18n/messages/de.json+++ b/src/i18n/messages/de.json@@ -5350,6 +5350,14 @@"maxResponseTokensDesc": "__MISSING__:Maximum total tokens allowed in a single response.","modelCooldownsTitle": "Modelle in der Abklingzeit","modelCooldownsEmpty": "Im Moment befinden sich keine Modelle in der Abklingzeit.",+ "responsesStateTitle": "Responses-State",+ "responsesStateDesc": "Steuert, wie OmniRoute previous_response_id weiterleitet.",+ "responsesStateModeLabel": "previous_response_id behandeln",+ "responsesStateModeAuto": "Auto",+ "responsesStateModeStrip": "Entfernen",+ "responsesStateModePreserve": "Beibehalten",+ "responsesStateHint": "Auto entfernt previous_response_id, außer eine Verbindung aktiviert explizit OpenAI Responses Storage. Entfernen ist am sichersten für zustandslose Clients wie VS Code Custom Endpoint; der Kontext hängt dann davon ab, dass der Client die vollständige Historie sendet.",+ "responsesStateSaveError": "Responses-State-Einstellung konnte nicht aktualisiert werden","codexFastTierTitle": "Codex Fast Tier","codexFastTierDesc": "service_tier=priority global für OpenAI Codex-Anfragen einfügen.","codexFastTierHint": "Wenn aktiviert, fügt OmniRoute ausgehenden Codex-Anfragen service_tier=priority hinzu, sofern für die Verbindung noch kein Tier festgelegt ist. Der Priority-Tier erfordert einen OpenAI Enterprise API-Schlüssel oder den ChatGPT-Auth-Codex-Pfad; andere Schlüsseltypen erhalten von OpenAI einen tier-bezogenen Fehler. Pro-Verbindung-Einstellungen auf der Codex-Provider-Seite haben Vorrang.",diff --git a/src/i18n/messages/en.json b/src/i18n/messages/en.jsonindex fe7e77c8c7..5bcc85bd2a 100644--- a/src/i18n/messages/en.json+++ b/src/i18n/messages/en.json@@ -1027,6 +1027,8 @@"analyticsCompressionSubtitle": "Token savings stats","analyticsSearchSubtitle": "Search tool analytics","analyticsEvalsSubtitle": "Eval suite results",+ "providerStats": "Provider Stats",+ "providerStatsSubtitle": "Latency and performance metrics","logsSubtitle": "Application logs","logsProxySubtitle": "Proxy traffic logs","consoleLogsSubtitle": "Console output",@@ -5582,6 +5584,14 @@"maxResponseTokensDesc": "Maximum total tokens allowed in a single response.","modelCooldownsTitle": "Models in cooldown","modelCooldownsEmpty": "No models in cooldown right now.",+ "responsesStateTitle": "Responses State",+ "responsesStateDesc": "Control how OmniRoute forwards previous_response_id.",+ "responsesStateModeLabel": "previous_response_id handling",+ "responsesStateModeAuto": "Auto",+ "responsesStateModeStrip": "Strip",+ "responsesStateModePreserve": "Preserve",+ "responsesStateHint": "Auto strips previous_response_id unless a connection explicitly enables OpenAI Responses storage. Strip is safest for stateless clients such as VS Code Custom Endpoint; context then depends on the client sending full history.",+ "responsesStateSaveError": "Failed to update Responses state setting","codexFastTierTitle": "Codex Fast Tier","codexFastTierDesc": "Globally inject service_tier=priority for OpenAI Codex requests.","codexFastTierHint": "When enabled, OmniRoute adds service_tier=priority to outbound Codex requests for connections that don't already specify a tier. Priority tier requires an OpenAI Enterprise API key or the ChatGPT-auth Codex path; other key types will receive a tier-related error from OpenAI. Per-connection settings on the Codex provider page take precedence.",@@ -6279,6 +6289,8 @@"notApplicable": "N/A","rawPlanWithValue": "Raw plan: {plan}","noPlanFromProvider": "No plan from provider",+ "tokenExpiresIn": "Token expires in {time}",+ "tokenExpired": "Token expired","noQuotaData": "No quota data","cardExpand": "Expand","cardCollapse": "Collapse",diff --git a/src/i18n/messages/pt-BR.json b/src/i18n/messages/pt-BR.jsonindex 948f2f2d39..f7566516da 100644--- a/src/i18n/messages/pt-BR.json+++ b/src/i18n/messages/pt-BR.json@@ -7611,6 +7611,8 @@"notApplicable": "N/D","rawPlanWithValue": "Plano bruto: {plan}","noPlanFromProvider": "Sem plano do provedor",+ "tokenExpiresIn": "Token expira em {time}",+ "tokenExpired": "Token expirado","noQuotaData": "Sem dados de cota","cardExpand": "Expandir","cardCollapse": "Recolher",diff --git a/src/lib/db/combos.ts b/src/lib/db/combos.tsindex 980d9cee44..2695756e0d 100644--- a/src/lib/db/combos.ts+++ b/src/lib/db/combos.ts@@ -5,6 +5,7 @@import { v4 as uuidv4 } from "uuid";import { getDbInstance } from "./core";import { backupDbFile } from "./backup";+import { invalidateDbCache } from "./readCache";import { normalizeComboRecord } from "@/lib/combos/steps";type JsonRecord = Record<string, unknown>;@@ -138,6 +139,7 @@ export async function createCombo(data: JsonRecord) {"INSERT INTO combos (id, name, data, sort_order, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)").run(combo.id, combo.name, JSON.stringify(combo), sortOrder, now, now);+ invalidateDbCache("combos");backupDbFile("pre-write");return combo;}@@ -178,6 +180,7 @@ export async function updateCombo(id: string, data: JsonRecord) {"UPDATE combos SET name = ?, data = ?, sort_order = ?, updated_at = ? WHERE id = ?").run(nextName, JSON.stringify(normalizedMerged), sortOrder, normalizedMerged.updatedAt, id);+ invalidateDbCache("combos");backupDbFile("pre-write");return normalizedMerged;}@@ -249,6 +252,7 @@ export async function reorderCombos(comboIds: string[]) {});reorderTransaction();+ invalidateDbCache("combos");backupDbFile("pre-write");return getCombos();}@@ -257,6 +261,7 @@ export async function deleteCombo(id: string) {const db = getDbInstance();const result = db.prepare("DELETE FROM combos WHERE id = ?").run(id);if (result.changes === 0) return false;+ invalidateDbCache("combos");backupDbFile("pre-write");return true;}diff --git a/src/lib/db/core.ts b/src/lib/db/core.tsindex 2e93076c2d..efeaf78ccd 100644--- a/src/lib/db/core.ts+++ b/src/lib/db/core.ts@@ -1368,7 +1368,14 @@ export function getDbInstance(): SqliteDatabase {}startDbHealthCheckScheduler(db);- console.log(`[DB] SQLite database ready: ${sqliteFile}`);+ // Log the resolved absolute DATA_DIR + SQLITE_FILE once at init so a+ // multi-replica / Docker volume-topology mismatch (each replica opening a+ // different on-disk DB → "phantom"/missing combos & connections) is+ // diagnosable straight from the logs. (#3147)+ console.log(+ `[DB] SQLite database ready: ${sqliteFile} ` ++ `(DATA_DIR=${path.resolve(DATA_DIR)}, SQLITE_FILE=${path.resolve(sqliteFile)})`+ );return db;}diff --git a/src/lib/db/providerStats.ts b/src/lib/db/providerStats.tsnew file mode 100644index 0000000000..65d7dc8a4c--- /dev/null+++ b/src/lib/db/providerStats.ts@@ -0,0 +1,68 @@+import { getDbInstance } from "./core";++/**+ * Provider/model call statistics aggregated from `call_logs`.+ *+ * Hard Rule #5: routes must not embed raw SQL — these queries live here so the+ * /api/provider-stats route can delegate. Read-only aggregation; no writes.+ */++export interface ProviderCallStat {+ provider: string;+ nodeName: string | null;+ totalRequests: number;+ successfulRequests: number;+ avgLatencyMs: number | null;+ totalTokensIn: number | null;+ totalTokensOut: number | null;+}++export interface ModelCallStat {+ provider: string;+ nodeName: string | null;+ model: string;+ requests: number;+ avgLatencyMs: number | null;+ successfulRequests: number;+}++export function getProviderCallStats(): ProviderCallStat[] {+ const db = getDbInstance();+ return db+ .prepare(+ `SELECT+ c.provider,+ pn.name AS nodeName,+ COUNT(*) AS totalRequests,+ SUM(CASE WHEN c.status >= 200 AND c.status < 400 THEN 1 ELSE 0 END) AS successfulRequests,+ ROUND(AVG(c.duration)) AS avgLatencyMs,+ SUM(c.tokens_in) AS totalTokensIn,+ SUM(c.tokens_out) AS totalTokensOut+ FROM call_logs c+ LEFT JOIN provider_nodes pn ON pn.id = c.provider+ WHERE c.provider IS NOT NULL AND c.provider != '-'+ GROUP BY c.provider+ ORDER BY totalRequests DESC`+ )+ .all() as ProviderCallStat[];+}++export function getModelCallStats(): ModelCallStat[] {+ const db = getDbInstance();+ return db+ .prepare(+ `SELECT+ c.provider,+ pn.name AS nodeName,+ c.model,+ COUNT(*) AS requests,+ ROUND(AVG(c.duration)) AS avgLatencyMs,+ SUM(CASE WHEN c.status >= 200 AND c.status < 400 THEN 1 ELSE 0 END) AS successfulRequests+ FROM call_logs c+ LEFT JOIN provider_nodes pn ON pn.id = c.provider+ WHERE c.provider IS NOT NULL AND c.model IS NOT NULL+ GROUP BY c.provider, c.model+ ORDER BY c.provider, requests DESC`+ )+ .all() as ModelCallStat[];+}diff --git a/src/lib/db/readCache.ts b/src/lib/db/readCache.tsindex fd5e7e6076..7c8b75521d 100644--- a/src/lib/db/readCache.ts+++ b/src/lib/db/readCache.ts@@ -142,11 +142,37 @@ export async function setCachedLKGP(lkgpCache.invalidate(`lkgp:${comboName}:${modelId}`);}+// ──────────────── Combo Cache Invalidation Signal ────────────────+//+// The nested-combo expansion caches live in request handlers+// (`src/sse/handlers/chat.ts` getCombosCachedForChat and+// `open-sse/handlers/chatCore.ts` getCombosCached), each with a 10s TTL. A db+// module must NOT import a request handler (that would create an import cycle),+// so instead those caches consult this monotonically-incrementing version.+// Combo writes call `invalidateDbCache("combos")`, which bumps the version;+// the handlers compare the version they were populated at against the current+// one and treat a mismatch as a cache miss — so combo edits take effect+// immediately instead of after the 10s window (#3147).+let combosCacheVersion = 0;++/**+ * Current combo-cache version. Cache layers snapshot this when they populate+ * and re-read it on every access; a change means the underlying combos were+ * written and the cached expansion must be refreshed.+ */+export function getCombosCacheVersion(): number {+ return combosCacheVersion;+}+/**- * Invalidate all caches (call after writes to any of: settings, pricing, connections).+ * Invalidate all caches (call after writes to any of: settings, pricing,+ * connections, combos).*/-export function invalidateDbCache(scope?: "settings" | "pricing" | "connections"): void {+export function invalidateDbCache(+ scope?: "settings" | "pricing" | "connections" | "combos"+): void {if (!scope || scope === "settings") settingsCache.invalidate();if (!scope || scope === "pricing") pricingCache.invalidate();if (!scope || scope === "connections") connectionsCache.invalidate();+ if (!scope || scope === "combos") combosCacheVersion++;}diff --git a/src/lib/db/settings.ts b/src/lib/db/settings.tsindex 8dcd735648..738645274a 100644--- a/src/lib/db/settings.ts+++ b/src/lib/db/settings.ts@@ -9,6 +9,7 @@ import { invalidateDbCache } from "./readCache";import { getProxyRegistryGeneration, resolveProxyForScopeFromRegistry } from "./proxies";import { getComboModelProvider as getComboEntryProvider } from "@/lib/combos/steps";import { requestBodyLimitMbFromEnv } from "@/shared/constants/bodySize";+import { DEFAULT_RESPONSES_PREVIOUS_RESPONSE_ID_MODE } from "@/shared/constants/responsesPreviousResponseId";type JsonRecord = Record<string, unknown>;type PricingModels = Record<string, JsonRecord>;@@ -108,6 +109,7 @@ export async function getSettings() {supportedModels: ["claude-opus-4-8", "claude-opus-4-7", "claude-opus-4-6"],},codexSessionAffinityTtlMs: 0,+ responsesPreviousResponseIdMode: DEFAULT_RESPONSES_PREVIOUS_RESPONSE_ID_MODE,alwaysPreserveClientCache: "auto",idempotencyWindowMs: 5000,wsAuth: false,diff --git a/src/lib/localDb.ts b/src/lib/localDb.tsindex a34ad6fd3b..533d642624 100755--- a/src/lib/localDb.ts+++ b/src/lib/localDb.ts@@ -207,6 +207,7 @@ export {getCachedLKGP,setCachedLKGP,invalidateDbCache,+ getCombosCacheVersion,} from "./db/readCache";export {diff --git a/src/lib/providers/validation.ts b/src/lib/providers/validation.tsindex e4ea04e0f4..d451dc60f5 100644--- a/src/lib/providers/validation.ts+++ b/src/lib/providers/validation.ts@@ -3718,8 +3718,43 @@ export async function validateProviderApiKey({ provider, apiKey, providerSpecifi// ── Specialty provider validation ──const SPECIALTY_VALIDATORS = {jules: validateJulesProvider,- qoder: ({ apiKey, providerSpecificData }: any) =>- validateQoderCliPat({ apiKey, providerSpecificData }),+ 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).+ const key = (apiKey || "").trim();+ if (key.startsWith("pt-")) {+ return validateQoderCliPat({ apiKey: key, providerSpecificData });+ }+ // Non-PAT token → validate against dashscope (Alibaba Cloud).+ // The executor routes these tokens to dashscope.aliyuncs.com, so the+ // validation must test against dashscope, NOT the Cosy PAT endpoint.+ try {+ const dashscopeUrl =+ "https://dashscope.aliyuncs.com/compatible-mode/v1/models";+ const res = await validationRead(+ dashscopeUrl,+ {+ headers: {+ Authorization: `Bearer ${key}`,+ },+ },+ false+ );+ if (res.ok) return { valid: true, error: null };+ if (res.status === 401 || res.status === 403) {+ return {+ valid: false,+ error:+ "Invalid Qoder API key. Make sure you're using a valid API key from Qoder / Alibaba Cloud Dashscope.",+ };+ }+ // 4xx/5xx other than auth — treat as valid bypass to prevent false+ // negatives from transient dashscope issues (consistent with PAT path).+ return { valid: true, error: null };+ } catch (err: unknown) {+ return toValidationErrorResult(err);+ }+ },"command-code": validateCommandCodeProvider,deepgram: validateDeepgramProvider,assemblyai: validateAssemblyAIProvider,diff --git a/src/lib/tokenHealthCheck.ts b/src/lib/tokenHealthCheck.tsindex d06aefcdae..1166238f04 100644--- a/src/lib/tokenHealthCheck.ts+++ b/src/lib/tokenHealthCheck.ts@@ -109,6 +109,25 @@ function isHealthCheckDisabled(): boolean {);}+/**+ * Providers excluded from the PROACTIVE refresh sweep, comma-separated and+ * case-insensitive (e.g. "codex,openai"). A targeted alternative to the blunt+ * OMNIROUTE_DISABLE_TOKEN_HEALTHCHECK switch: it lets an operator keep the+ * rotating-token cascade providers (Codex/OpenAI share one Auth0 family) off the+ * proactive sweep — leaving their refresh to the reactive, serialized 401 path —+ * WITHOUT also starving short-TTL providers like Kimi-coding, whose tokens expire+ * while idle when the whole sweep is disabled.+ */+function getHealthCheckSkipProviders(): Set<string> {+ const raw = process.env.OMNIROUTE_HEALTHCHECK_SKIP_PROVIDERS || "";+ return new Set(+ raw+ .split(",")+ .map((s) => s.trim().toLowerCase())+ .filter(Boolean)+ );+}+// ── Logging helper ───────────────────────────────────────────────────────────let cachedHideLogs: boolean | null = null;let cacheTimestamp = 0;@@ -265,6 +284,13 @@ export async function checkConnection(conn) {const latestConnection = (await getProviderConnectionById(conn.id)) || conn;conn = latestConnection;+ // Per-provider opt-out of proactive refresh (e.g. Codex/OpenAI cascade+ // providers) — their token stays on the reactive, serialized 401 path while+ // other providers keep being refreshed proactively.+ if (getHealthCheckSkipProviders().has(String(conn.provider || "").toLowerCase())) {+ return;+ }+// Determine interval (0 = disabled)const intervalMin = conn.healthCheckInterval ?? DEFAULT_HEALTH_CHECK_INTERVAL_MIN;if (intervalMin <= 0) return;diff --git a/src/lib/usage/providerLimits.ts b/src/lib/usage/providerLimits.tsindex 973e9ef2f7..fa139381ce 100644--- a/src/lib/usage/providerLimits.ts+++ b/src/lib/usage/providerLimits.ts@@ -135,7 +135,7 @@ export function shouldAttemptRotatingRefresh(export async function refreshAndUpdateCredentials(connection: ProviderConnectionLike,- opts: { allowRotatingRefresh?: boolean } = {}+ opts: { allowRotatingRefresh?: boolean; force?: boolean } = {}) {if (!shouldAttemptRotatingRefresh(connection.provider, opts.allowRotatingRefresh)) {return { connection, refreshed: false };@@ -151,7 +151,12 @@ export async function refreshAndUpdateCredentials(copilotTokenExpiresAt: connection.providerSpecificData?.copilotTokenExpiresAt,};- if (!executor.needsRefresh(credentials)) {+ // `force` is used ONLY on the reactive 401 recovery path (a usage fetch came+ // back unauthorized) — it bypasses the proactive `needsRefresh` heuristic so+ // imported accounts (expiresAt=null, where needsRefresh is always false) can+ // still re-mint. The mint stays serialized per rotation group; this never+ // refreshes proactively from the bulk path (#3019 guard above is unchanged).+ if (!opts.force && !executor.needsRefresh(credentials)) {return { connection, refreshed: false };}@@ -211,6 +216,19 @@ export async function refreshAndUpdateCredentials(};}+function isUsageAuthError(message: unknown): boolean {+ if (typeof message !== "string") return false;+ const m = message.toLowerCase();+ return (+ m.includes("token expired") ||+ m.includes("unauthorized") ||+ m.includes("re-authenticate") ||+ m.includes("access denied") ||+ m.includes("invalidated") ||+ m.includes("401")+ );+}+function isNetworkFailureMessage(message: unknown): boolean {if (typeof message !== "string") return false;return (@@ -384,6 +402,29 @@ export function getProviderLimitsSyncIntervalMs(): number {return getProviderLimitsSyncIntervalMinutes() * 60 * 1000;}+/** Default gap (ms) inserted between two consecutive OAuth quota fetches. */+const DEFAULT_PROVIDER_LIMITS_SYNC_SPACING_MS = 1500;++/**+ * Spacing (ms) between consecutive OAuth provider-limits fetches in a bulk sync.+ *+ * OAuth providers (Codex/Claude/Kimi-coding/…) are fetched ONE AT A TIME with+ * this gap so a single host never bursts several simultaneous usage/refresh+ * requests to the same upstream — bursts read as automated traffic and+ * contribute to session termination / anomaly flags (and, for rotating-token+ * providers, to the Auth0 family-revocation race). Stateless API-key providers+ * keep the fast concurrent path. Tunable via `PROVIDER_LIMITS_SYNC_SPACING_MS`;+ * set to `"0"` to opt out.+ */+export function getProviderLimitsSyncSpacingMs(): number {+ const rawEnv = process.env.PROVIDER_LIMITS_SYNC_SPACING_MS;+ if (rawEnv === undefined || rawEnv === "") return DEFAULT_PROVIDER_LIMITS_SYNC_SPACING_MS;+ const raw = Number(rawEnv);+ return Number.isFinite(raw) && raw >= 0 ? raw : DEFAULT_PROVIDER_LIMITS_SYNC_SPACING_MS;+}++const syncDelay = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));+export async function getLastProviderLimitsAutoSyncTime(): Promise<string | null> {try {const settings = await getSettings();@@ -456,7 +497,25 @@ async function fetchLiveProviderLimitsWithOptions(await syncToCloudIfEnabled();}- const usageData = (await getUsageForProvider(conn, options)) as JsonRecord;+ let usageData = (await getUsageForProvider(conn, options)) as JsonRecord;++ // Reactive 401 recovery (on-demand/force path only): an unauthorized usage+ // response means the access token is actually dead. Force ONE serialized+ // re-mint and retry once. This recovers imported accounts (expiresAt=null,+ // where the proactive needsRefresh heuristic never fires) without ever+ // refreshing proactively from the bulk path.+ if (options.allowRotatingRefresh && !wasRefreshed && isUsageAuthError(usageData?.message)) {+ const forced = await refreshAndUpdateCredentials(conn, {+ allowRotatingRefresh: true,+ force: true,+ });+ if (forced.refreshed) {+ conn = forced.connection;+ await syncToCloudIfEnabled();+ usageData = (await getUsageForProvider(conn, options)) as JsonRecord;+ }+ }+connection = conn;return { usage: usageData };});@@ -595,42 +654,62 @@ export async function syncAllProviderLimits(const caches: Record<string, ProviderLimitsCacheEntry> = {};const errors: Record<string, string> = {};- for (let i = 0; i < connections.length; i += concurrency) {- const chunk = connections.slice(i, i + concurrency);- const results = await Promise.allSettled(- chunk.map(async (connection) => {- const { usage } = await fetchLiveProviderLimitsWithOptions(connection.id, {- forceRefresh: source === "manual",- });- const cache = toProviderLimitsCacheEntry(usage, source);- return { connectionId: connection.id, cache };- })- );-- results.forEach((result, index) => {- const connectionId = chunk[index]?.id;- if (!connectionId) return;-- if (result.status === "fulfilled") {- const { cache } = result.value;- // Don't persist error-only entries; show prior cache or pass through.- if (!cache.quotas && cache.message) {- const previous = getProviderLimitsCache(connectionId);- if (previous?.quotas && Object.keys(previous.quotas).length > 0) {- caches[connectionId] = previous;- } else {- caches[connectionId] = cache;- }- return;+ const recordResult = (+ connectionId: string,+ result: PromiseSettledResult<{ connectionId: string; cache: ProviderLimitsCacheEntry }>+ ) => {+ if (result.status === "fulfilled") {+ const { cache } = result.value;+ // Don't persist error-only entries; show prior cache or pass through.+ if (!cache.quotas && cache.message) {+ const previous = getProviderLimitsCache(connectionId);+ if (previous?.quotas && Object.keys(previous.quotas).length > 0) {+ caches[connectionId] = previous;+ } else {+ caches[connectionId] = cache;}- cacheEntries.push({ connectionId, entry: cache });- caches[connectionId] = cache;return;}+ cacheEntries.push({ connectionId, entry: cache });+ caches[connectionId] = cache;+ return;+ }+ const reason = result.reason as { message?: string } | undefined;+ errors[connectionId] = reason?.message || "Failed to refresh provider limits";+ };- const reason = result.reason as { message?: string } | undefined;- errors[connectionId] = reason?.message || "Failed to refresh provider limits";+ const fetchOne = async (connection: ProviderConnectionLike) => {+ const { usage } = await fetchLiveProviderLimitsWithOptions(connection.id, {+ forceRefresh: source === "manual",});+ const cache = toProviderLimitsCacheEntry(usage, source);+ return { connectionId: connection.id, cache };+ };++ // OAuth connections are processed STRICTLY SEQUENTIALLY with a spacing gap so a+ // single host never bursts simultaneous usage/refresh requests to the same+ // upstream (anomaly/session-termination guard; see getProviderLimitsSyncSpacingMs).+ // Stateless API-key connections keep the fast chunked-concurrent path.+ const oauthConnections = connections.filter((c) => c.authType === "oauth");+ const otherConnections = connections.filter((c) => c.authType !== "oauth");+ const spacingMs = getProviderLimitsSyncSpacingMs();++ for (let i = 0; i < otherConnections.length; i += concurrency) {+ const chunk = otherConnections.slice(i, i + concurrency);+ const results = await Promise.allSettled(chunk.map(fetchOne));+ results.forEach((result, index) => {+ const connectionId = chunk[index]?.id;+ if (connectionId) recordResult(connectionId, result);+ });+ }++ for (let i = 0; i < oauthConnections.length; i++) {+ const connection = oauthConnections[i];+ const [result] = await Promise.allSettled([fetchOne(connection)]);+ recordResult(connection.id, result);+ if (spacingMs > 0 && i < oauthConnections.length - 1) {+ await syncDelay(spacingMs);+ }}if (cacheEntries.length > 0) {diff --git a/src/lib/versionManager/binaryManager.ts b/src/lib/versionManager/binaryManager.tsindex 1b4b86c6de..2a2d0bf709 100644--- a/src/lib/versionManager/binaryManager.ts+++ b/src/lib/versionManager/binaryManager.ts@@ -162,6 +162,7 @@ export async function getInstalledVersions(dataDir?: string): Promise<string[]>return entries.filter((e) =>+ typeof e === "string" &&e.startsWith("cliproxyapi-") &&fsSync.statSync(path.join(/* turbopackIgnore: true */ binDir, e)).isDirectory())diff --git a/src/shared/components/KiroOAuthWrapper.tsx b/src/shared/components/KiroOAuthWrapper.tsxindex fdfbfba4cc..aff30c2bdd 100644--- a/src/shared/components/KiroOAuthWrapper.tsx+++ b/src/shared/components/KiroOAuthWrapper.tsx@@ -104,6 +104,7 @@ export default function KiroOAuthWrapper({<KiroSocialOAuthModalisOpen={isOpen}provider={socialProvider}+ targetProvider={oauthProviderId}providerLabel={providerLabel}onSuccess={handleSocialSuccess}onClose={handleBack}diff --git a/src/shared/components/KiroSocialOAuthModal.tsx b/src/shared/components/KiroSocialOAuthModal.tsxindex ae31b6d1f7..cd8ce56475 100644--- a/src/shared/components/KiroSocialOAuthModal.tsx+++ b/src/shared/components/KiroSocialOAuthModal.tsx@@ -8,6 +8,7 @@ import { copyToClipboard } from "@/shared/utils/clipboard";type KiroSocialOAuthModalProps = {isOpen: boolean;provider: "google" | "github";+ targetProvider?: string;providerLabel?: string;onSuccess?: () => void;onClose: () => void;@@ -16,6 +17,7 @@ type KiroSocialOAuthModalProps = {export default function KiroSocialOAuthModal({isOpen,provider,+ targetProvider,providerLabel = "Kiro",onSuccess,onClose,@@ -51,7 +53,7 @@ export default function KiroSocialOAuthModal({const pollRes = await fetch("/api/oauth/kiro/social-exchange", {method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ deviceCode: data.deviceCode, provider }),+ body: JSON.stringify({ deviceCode: data.deviceCode, provider, targetProvider }),});const pollData = await pollRes.json();diff --git a/src/shared/constants/modelSpecs.ts b/src/shared/constants/modelSpecs.tsindex ff766f2431..273bc7190e 100644--- a/src/shared/constants/modelSpecs.ts+++ b/src/shared/constants/modelSpecs.ts@@ -310,12 +310,24 @@ export const MODEL_SPECS: Record<string, ModelSpec> = {supportsTools: true,},+ // ── MiniMax M3 (1M context, 512K max output) ─────────────────────+ // max output verified against MiniMax docs / OpenRouter / Artificial+ // Analysis (Nov 2025 launch): 1,048,576-token context, up to 512K output.+ "minimax-m3": {+ maxOutputTokens: 512000,+ contextWindow: 1048576,+ supportsThinking: true,+ supportsTools: true,+ aliases: ["MiniMax-M3", "MiniMaxAI/MiniMax-M3"],+ },+// ── MiniMax M2.x (200K context family) ───────────────────────────"minimax-m2.7": {maxOutputTokens: 131072,contextWindow: 204800,supportsThinking: true,supportsTools: true,+ aliases: ["MiniMax-M2.7", "MiniMaxAI/MiniMax-M2.7"],},"minimax-m2.5": {maxOutputTokens: 131072,@@ -356,14 +368,23 @@ export const MODEL_SPECS: Record<string, ModelSpec> = {export function getModelSpec(modelId: string): ModelSpec | undefined {if (MODEL_SPECS[modelId]) return MODEL_SPECS[modelId];- // Buscas por alias+ // Case-insensitive lookups: upstream model ids are often capitalized+ // (e.g. "MiniMax-M2.7") while specs/aliases use lowercase ids (#3141).+ const lower = modelId.toLowerCase();++ // Exact match (case-insensitive)for (const [canonical, spec] of Object.entries(MODEL_SPECS)) {- if (spec.aliases?.includes(modelId)) return spec;+ if (canonical.toLowerCase() === lower) return spec;+ }++ // Buscas por alias (case-insensitive)+ for (const [, spec] of Object.entries(MODEL_SPECS)) {+ if (spec.aliases?.some((alias) => alias.toLowerCase() === lower)) return spec;}- // Prefix matching+ // Prefix matching (case-insensitive)for (const [key, spec] of Object.entries(MODEL_SPECS)) {- if (key !== "__default__" && modelId.startsWith(key)) return spec;+ if (key !== "__default__" && lower.startsWith(key.toLowerCase())) return spec;}return undefined;diff --git a/src/shared/constants/providers.ts b/src/shared/constants/providers.tsindex ec515b5857..80827dd199 100644--- a/src/shared/constants/providers.ts+++ b/src/shared/constants/providers.ts@@ -435,7 +435,8 @@ export const WEB_COOKIE_PROVIDERS = {},huggingchat: {id: "huggingchat",- alias: "hc",+ // "hc" belongs to the hackclub provider; huggingchat uses its own id as alias.+ alias: "huggingchat",name: "HuggingChat (Free)",icon: "auto_awesome",color: "#FFD21E",@@ -497,7 +498,8 @@ export const WEB_COOKIE_PROVIDERS = {},"kimi-web": {id: "kimi-web",- alias: "kimi",+ // Primary "kimi" provider keeps the short alias; web variant uses its own id.+ alias: "kimi-web",name: "Kimi Web (Moonshot AI)",icon: "auto_awesome",color: "#2563EB",@@ -521,7 +523,8 @@ export const WEB_COOKIE_PROVIDERS = {},"qwen-web": {id: "qwen-web",- alias: "qw",+ // Primary "qwen" provider keeps the short alias; web variant uses its own id.+ alias: "qwen-web",name: "Qwen Web (Free)",icon: "auto_awesome",color: "#10B981",diff --git a/src/shared/constants/responsesPreviousResponseId.ts b/src/shared/constants/responsesPreviousResponseId.tsnew file mode 100644index 0000000000..9a285ef4c5--- /dev/null+++ b/src/shared/constants/responsesPreviousResponseId.ts@@ -0,0 +1,5 @@+export const RESPONSES_PREVIOUS_RESPONSE_ID_MODES = ["auto", "strip", "preserve"] as const;++export type ResponsesPreviousResponseIdMode = (typeof RESPONSES_PREVIOUS_RESPONSE_ID_MODES)[number];++export const DEFAULT_RESPONSES_PREVIOUS_RESPONSE_ID_MODE: ResponsesPreviousResponseIdMode = "auto";diff --git a/src/shared/constants/sidebarVisibility.ts b/src/shared/constants/sidebarVisibility.tsindex 42aed0cfdc..5dd9d328e4 100644--- a/src/shared/constants/sidebarVisibility.ts+++ b/src/shared/constants/sidebarVisibility.ts@@ -35,6 +35,7 @@ export const HIDEABLE_SIDEBAR_ITEM_IDS = ["analytics-compression","analytics-search","analytics-evals",+ "provider-stats",// Monitoring — flat"activity","logs",@@ -374,6 +375,13 @@ const ANALYTICS_ITEMS: readonly SidebarItemDefinition[] = [subtitleKey: "analyticsEvalsSubtitle",icon: "labs",},+ {+ id: "provider-stats",+ href: "/dashboard/provider-stats",+ i18nKey: "providerStats",+ subtitleKey: "providerStatsSubtitle",+ icon: "speed",+ },];const MONITORING_ITEMS: readonly SidebarItemDefinition[] = [diff --git a/src/shared/middleware/bodySizeGuard.ts b/src/shared/middleware/bodySizeGuard.tsindex d9ef26fce3..eefd2b23d2 100644--- a/src/shared/middleware/bodySizeGuard.ts+++ b/src/shared/middleware/bodySizeGuard.ts@@ -26,6 +26,9 @@ export const MAX_BODY_BYTES_IMPORT = 100 * 1024 * 1024;/** Larger limit for audio transcription uploads: 100 MB */export const MAX_BODY_BYTES_AUDIO = 100 * 1024 * 1024;+/** Larger limit for file uploads: 500 MB */+export const MAX_BODY_BYTES_FILE = 500 * 1024 * 1024;+/** Configured limit — reads from env or falls back to 10 MB */export const MAX_BODY_BYTES = parseRequestBodyLimitBytes(process.env.MAX_BODY_SIZE_BYTES);@@ -34,6 +37,7 @@ type BodySizeRule = { prefix: string; limit: number };const ROUTE_LIMITS: BodySizeRule[] = [{ prefix: "/api/db-backups/import", limit: MAX_BODY_BYTES_IMPORT },{ prefix: "/api/v1/audio/transcriptions", limit: MAX_BODY_BYTES_AUDIO },+ { prefix: "/api/v1/files", limit: MAX_BODY_BYTES_FILE },];export function getDefaultRequestBodyLimitMb(): number {@@ -62,7 +66,7 @@ export function checkBodySize(request: Request, limit: number = MAX_BODY_BYTES):const contentLength = request.headers.get("content-length");if (contentLength) {- const bytes = parseInt(contentLength, 10);+ const bytes = Number.parseInt(contentLength, 10);if (!Number.isNaN(bytes) && bytes > limit) {return new Response(JSON.stringify({diff --git a/src/shared/validation/settingsSchemas.ts b/src/shared/validation/settingsSchemas.tsindex 90c2efad0c..86504d5241 100644--- a/src/shared/validation/settingsSchemas.ts+++ b/src/shared/validation/settingsSchemas.ts@@ -10,6 +10,7 @@ import { COMBO_CONFIG_MODES } from "@/shared/constants/comboConfigMode";import { MAX_REQUEST_BODY_LIMIT_MB, MIN_REQUEST_BODY_LIMIT_MB } from "@/shared/constants/bodySize";import { HIDEABLE_SIDEBAR_ITEM_IDS, SIDEBAR_SECTIONS } from "@/shared/constants/sidebarVisibility";import { ACCOUNT_FALLBACK_STRATEGY_VALUES } from "@/shared/constants/routingStrategies";+import { RESPONSES_PREVIOUS_RESPONSE_ID_MODES } from "@/shared/constants/responsesPreviousResponseId";const signatureCacheModeValues = ["enabled", "bypass", "bypass-strict"] as const;@@ -69,6 +70,7 @@ export const updateSettingsSchema = z.object({}).optional(),codexSessionAffinityTtlMs: z.number().int().min(0).max(86_400_000).optional(),+ responsesPreviousResponseIdMode: z.enum(RESPONSES_PREVIOUS_RESPONSE_ID_MODES).optional(),// Routing settings (#134)fallbackStrategy: z.enum(ACCOUNT_FALLBACK_STRATEGY_VALUES).optional(),wildcardAliases: z.array(z.object({ pattern: z.string(), target: z.string() })).optional(),diff --git a/src/sse/handlers/chat.ts b/src/sse/handlers/chat.tsindex 266f8297de..2e5efb681a 100644--- a/src/sse/handlers/chat.ts+++ b/src/sse/handlers/chat.ts@@ -37,6 +37,7 @@ import {deleteSessionAccountAffinity,getCachedSettings,getCombos,+ getCombosCacheVersion,getSessionAccountAffinity,} from "@/lib/localDb";import {@@ -129,17 +130,26 @@ registerOpencodeQuotaFetcher();registerGenericQuotaFetchers();let combosCachePromise: Promise<unknown[]> | null = null;let combosCacheTs = 0;+let combosCacheVersionSnapshot = -1;const COMBOS_CACHE_TTL_MS = 10_000;async function getCombosCachedForChat(): Promise<unknown[]> {const now = Date.now();// Explicit non-null check: we intentionally cache and return the Promise// itself (to dedupe concurrent callers), so this is not a forgotten await.- if (combosCachePromise !== null && now - combosCacheTs < COMBOS_CACHE_TTL_MS) {+ // The version check makes combo edits (create/update/delete/reorder) take+ // effect immediately instead of after the 10s TTL — otherwise a removed+ // target/model could keep being served as a "phantom" for up to 10s (#3147).+ if (+ combosCachePromise !== null &&+ now - combosCacheTs < COMBOS_CACHE_TTL_MS &&+ combosCacheVersionSnapshot === getCombosCacheVersion()+ ) {return combosCachePromise;}combosCacheTs = now;+ combosCacheVersionSnapshot = getCombosCacheVersion();combosCachePromise = getCombos().catch(() => []);return combosCachePromise;}@@ -1009,7 +1019,7 @@ async function handleSingleModelChat(refreshedCredentials);}- const proxyInfo = await safeResolveProxy(credentials.connectionId);+ const proxyInfo = await safeResolveProxy(credentials.connectionId, apiKeyInfo?.id);const proxyStartTime = Date.now();// 4. Execute chat via core after breaker gate checks (with optional TLS tracking)diff --git a/src/sse/handlers/chatHelpers.ts b/src/sse/handlers/chatHelpers.tsindex ebaa542927..a4ca816374 100644--- a/src/sse/handlers/chatHelpers.ts+++ b/src/sse/handlers/chatHelpers.ts@@ -198,7 +198,8 @@ export async function resolveModelOrError(const { getCombos } = await import("@/lib/localDb");const all = await getCombos();for (const c of all) {- if (c.name?.startsWith("auto/")) available.push(c.name);+ const name = typeof c === "object" && c !== null ? (c as Record<string, unknown>).name : undefined;+ if (typeof name === "string" && name.startsWith("auto/")) available.push(name);}} catch {/* DB unavailable */@@ -578,9 +579,9 @@ export function handleNoCredentials();}-export async function safeResolveProxy(connectionId: string) {+export async function safeResolveProxy(connectionId: string, apiKeyId?: string) {try {- return await resolveProxyForConnection(connectionId);+ return await resolveProxyForConnection(connectionId, apiKeyId);} catch (proxyErr: any) {log.debug("PROXY", `Failed to resolve proxy: ${proxyErr.message}`);return null;diff --git a/tests/integration/chat-pipeline.test.ts b/tests/integration/chat-pipeline.test.tsindex 2773023a11..46178d3ecf 100644--- a/tests/integration/chat-pipeline.test.ts+++ b/tests/integration/chat-pipeline.test.ts@@ -728,6 +728,85 @@ test("chat pipeline applies Codex CLI fingerprint to OAuth responses requests",);});+test("chat pipeline strips previous_response_id from stateless Codex responses by default", async () => {+ await seedConnection("codex", {+ apiKey: "sk-codex-stateless-responses",+ providerSpecificData: { openaiStoreEnabled: false },+ });+ const fetchCalls = [];++ globalThis.fetch = async (url, init: RequestInit = {}) => {+ fetchCalls.push({+ url: String(url),+ headers: toPlainHeaders(init.headers),+ body: init.body ? JSON.parse(String(init.body)) : null,+ });+ return buildOpenAIResponsesSSE({ text: "stateless responses ok", model: "gpt-5.5" });+ };++ const response = await handleChat(+ buildRequest({+ url: "http://localhost/v1/responses",+ body: {+ model: "codex/gpt-5.5",+ stream: false,+ previous_response_id: "resp_vs_code_prev",+ input: [+ {+ type: "message",+ role: "user",+ content: [{ type: "input_text", text: "Second VS Code turn" }],+ },+ ],+ },+ })+ );++ await response.json();++ assert.equal(response.status, 200);+ assert.equal(fetchCalls.length, 1);+ assert.match(fetchCalls[0].url, /\/responses$/);+ assert.equal(fetchCalls[0].body.previous_response_id, undefined);+ assert.equal(fetchCalls[0].body.store, false);+});++test("chat pipeline preserve mode forwards previous_response_id for responses requests", async () => {+ await settingsDb.updateSettings({ responsesPreviousResponseIdMode: "preserve" });+ await seedConnection("codex", {+ apiKey: "sk-codex-preserve-responses",+ providerSpecificData: { openaiStoreEnabled: false },+ });+ const fetchCalls = [];++ globalThis.fetch = async (url, init: RequestInit = {}) => {+ fetchCalls.push({+ url: String(url),+ headers: toPlainHeaders(init.headers),+ body: init.body ? JSON.parse(String(init.body)) : null,+ });+ return buildOpenAIResponsesSSE({ text: "preserve responses ok", model: "gpt-5.5" });+ };++ const response = await handleChat(+ buildRequest({+ url: "http://localhost/v1/responses",+ body: {+ model: "codex/gpt-5.5",+ stream: false,+ previous_response_id: "resp_preserved_prev",+ input: "Second stateful turn",+ },+ })+ );++ await response.json();++ assert.equal(response.status, 200);+ assert.equal(fetchCalls.length, 1);+ assert.equal(fetchCalls[0].body.previous_response_id, "resp_preserved_prev");+});+test("chat pipeline treats Codex /responses/compact as non-streaming JSON", async () => {await seedConnection("codex", { apiKey: "sk-codex-compact" });const fetchCalls = [];diff --git a/tests/unit/antigravity-mitm-model-resolution.test.ts b/tests/unit/antigravity-mitm-model-resolution.test.tsnew file mode 100644index 0000000000..86a06718a2--- /dev/null+++ b/tests/unit/antigravity-mitm-model-resolution.test.ts@@ -0,0 +1,63 @@+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-antigravity-mitm-"));+process.env.DATA_DIR = TEST_DATA_DIR;++const core = await import("../../src/lib/db/core.ts");+const modelsDb = await import("../../src/lib/db/models.ts");+const { AntigravityExecutor } = await import("../../open-sse/executors/antigravity.ts");++test.beforeEach(() => {+ core.resetDbInstance();+});++test.after(() => {+ core.resetDbInstance();+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });+});++// #3144: the executor resolves the upstream model through the dynamic MITM alias+// table (populated by model sync) before falling back to the static alias map.+test("transformRequest resolves the upstream model via the dynamic MITM alias table (#3144)", async () => {+ await modelsDb.setMitmAliasAll("antigravity", {+ "gemini-dynamic": "antigravity/gemini-3.1-pro-low",+ });++ const executor = new AntigravityExecutor();+ const result = await executor.transformRequest(+ "antigravity/gemini-dynamic",+ { request: { contents: [] } },+ true,+ { projectId: "project-mitm" }+ );++ if (result instanceof Response) throw new Error("Unexpected Response from transformRequest");+ // The MITM alias wins and the "antigravity/" prefix is stripped.+ assert.equal(result.model, "gemini-3.1-pro-low");+});++// #3144 regression: a corrupted (non-string) MITM alias value must NOT short-circuit+// cleanModelName into returning undefined — it has to fall through to the static+// resolution and still produce a valid string model (the pre-fix code returned+// undefined here, which then threw on `upstreamModel.toLowerCase()`).+test("transformRequest tolerates a corrupted non-string MITM alias value (#3144)", async () => {+ await modelsDb.setMitmAliasAll("antigravity", {+ "gemini-3.1-pro": { unexpected: "object" },+ });++ const executor = new AntigravityExecutor();+ const result = await executor.transformRequest(+ "antigravity/gemini-3.1-pro",+ { request: { contents: [] } },+ true,+ { projectId: "project-mitm" }+ );++ if (result instanceof Response) throw new Error("Unexpected Response from transformRequest");+ assert.equal(typeof result.model, "string");+ assert.equal(result.model, "gemini-3.1-pro");+});diff --git a/tests/unit/api-manager-page-static.test.ts b/tests/unit/api-manager-page-static.test.tsindex 43a2cc2f33..29d920e82f 100644--- a/tests/unit/api-manager-page-static.test.ts+++ b/tests/unit/api-manager-page-static.test.ts@@ -35,6 +35,21 @@ test("permissions modal uses i18n for management access description", () => {assert.doesNotMatch(managementBlock, /Allow this API key to manage OmniRoute configuration\./);});+test("permissions modal converts API key expiration ISO timestamps to local datetime input values", () => {+ const source = readApiManagerPage();+ const expirationBlock = source.slice(+ source.indexOf("{/* Expiration Date */}", source.indexOf("const PermissionsModal")),+ source.indexOf("{/* Management Access */}", source.indexOf("const PermissionsModal"))+ );++ assert.match(expirationBlock, /value=\{toLocalDateTimeInputValue\(expiresAt\)\}/);+ assert.match(expirationBlock, /const date = new Date\(val\)/);+ assert.match(expirationBlock, /setExpiresAt\(date\.toISOString\(\)\)/);+ assert.match(expirationBlock, /onClick=\{\(\) => setExpiresAt\(""\)\}/);+ assert.match(expirationBlock, /\{tc\("clear"\)\}/);+ assert.doesNotMatch(expirationBlock, /expiresAt\.slice\(0, 16\)/);+});+test("permissions modal switch buttons declare button type", () => {const source = readApiManagerPage();const modalStart = source.indexOf("const PermissionsModal");diff --git a/tests/unit/batch-processor-expiration.test.ts b/tests/unit/batch-processor-expiration.test.tsindex ec884b5f1f..4c8281ce98 100644--- a/tests/unit/batch-processor-expiration.test.ts+++ b/tests/unit/batch-processor-expiration.test.ts@@ -1,6 +1,5 @@-import { afterEach, describe, it } from "node:test";+import { describe, it } from "node:test";import assert from "node:assert";-import { deleteFile, listFiles } from "@/lib/localDb";// Helper functions from batchProcessor.tsfunction parseBatchWindowSeconds(window: string | null | undefined): number {@@ -18,15 +17,6 @@ function parseBatchWindowSeconds(window: string | null | undefined): number {}describe("Batch Processor - File Expiration", () => {- afterEach(() => {- const allFiles = listFiles({ limit: 1000 });- for (const f of allFiles) {- if (f.filename?.includes("test-batch-")) {- deleteFile(f.id);- }- }- });-describe("getBatchOutputExpiresAt logic", () => {it("should calculate output expiration as 30 days from batch completion", () => {const completedAt = Math.floor(Date.now() / 1000) - 5 * 24 * 60 * 60; // 5 days agodiff --git a/tests/unit/body-size-guard.test.ts b/tests/unit/body-size-guard.test.tsindex 2f5b967ea2..fd877c7223 100644--- a/tests/unit/body-size-guard.test.ts+++ b/tests/unit/body-size-guard.test.ts@@ -2,6 +2,7 @@ import test from "node:test";import assert from "node:assert/strict";import {MAX_BODY_BYTES_AUDIO,+ MAX_BODY_BYTES_FILE,getBodySizeLimit,checkBodySize,} from "../../src/shared/middleware/bodySizeGuard.ts";@@ -40,3 +41,39 @@ test("checkBodySize reports the configured request limit in 413 responses", asynassert.equal(body.error.code, "PAYLOAD_TOO_LARGE");assert.match(body.error.message, /100 MB/);});++test("/api/v1/files route has 512 MB dedicated limit floor", () => {+ const limit = getBodySizeLimit("/api/v1/files", { maxBodySizeMb: 1 });+ assert.equal(limit, MAX_BODY_BYTES_FILE);+});++test("/api/v1/files route guard allows 500 MB file upload", () => {+ const thirtyMb = 500 * 1024 * 1024;+ const request = new Request("http://localhost/api/v1/files", {+ method: "POST",+ headers: { "content-length": String(thirtyMb) },+ });+ assert.equal(checkBodySize(request, getBodySizeLimit("/api/v1/files", { maxBodySizeMb: 10 })), null);+});++test("/api/v1/files route guard rejects >512 MB file upload", async () => {+ const tooBig = 600 * 1024 * 1024;+ const request = new Request("http://localhost/api/v1/files", {+ method: "POST",+ headers: { "content-length": String(tooBig) },+ });+ const response = checkBodySize(request, getBodySizeLimit("/api/v1/files", { maxBodySizeMb: 10 }));+ assert.ok(response);+ assert.equal(response.status, 413);+ const body = await response.json();+ assert.equal(body.error.code, "PAYLOAD_TOO_LARGE");+});++test("/api/v1/files route guard allows 15 MB (10 MB+ real-world scenario)", () => {+ const fifteenMb = 15 * 1024 * 1024;+ const request = new Request("http://localhost/api/v1/files", {+ method: "POST",+ headers: { "content-length": String(fifteenMb) },+ });+ assert.equal(checkBodySize(request, getBodySizeLimit("/api/v1/files")), null);+});diff --git a/tests/unit/chatcore-translation-paths.test.ts b/tests/unit/chatcore-translation-paths.test.tsindex 9b71494dd3..ffd4137a53 100644--- a/tests/unit/chatcore-translation-paths.test.ts+++ b/tests/unit/chatcore-translation-paths.test.ts@@ -427,7 +427,7 @@ test("chatCore times out upstream execution before provider response headers", aconst pendingDetail = (await waitFor(() =>Object.values(getPendingRequests().details[connectionId] || {}).find(- (detail: any) => detail?.providerRequest+ (detail: any) => detail?.providerRequest?.model === "gpt-4o-mini"))) as any;assert.equal(pendingDetail?.providerRequest?.model, "gpt-4o-mini");diff --git a/tests/unit/combo-cache-invalidation.test.ts b/tests/unit/combo-cache-invalidation.test.tsnew file mode 100644index 0000000000..30b1b8ffb6--- /dev/null+++ b/tests/unit/combo-cache-invalidation.test.ts@@ -0,0 +1,151 @@+/**+ * #3147 — Editing a combo must invalidate the 10s nested-combo expansion caches+ * (src/sse/handlers/chat.ts getCombosCachedForChat + open-sse/handlers/chatCore.ts+ * getCombosCached) so a parent combo's nested expansion stops serving removed+ * targets/models ("phantom models") within the TTL window.+ *+ * Both cache layers consult a shared monotonic version exposed by readCache+ * (getCombosCacheVersion). Combo writes call invalidateDbCache("combos"), which+ * bumps that version. This test drives the real write path and asserts:+ * 1. each combo write bumps the version (the invalidation hook fires), and+ * 2. the chat-layer cache-validity predicate (which is what gates staleness)+ * flips from "valid" to "stale" immediately after a write — i.e. without+ * waiting for the 10s TTL.+ *+ * On current code (no invalidation) the version never changes, so the predicate+ * stays "valid" for the full 10s window → the test FAILS. After the fix it+ * PASSES.+ */+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-combo-cache-"));+process.env.DATA_DIR = TEST_DATA_DIR;++const core = await import("../../src/lib/db/core.ts");+const combosDb = await import("../../src/lib/db/combos.ts");+const readCache = await import("../../src/lib/db/readCache.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: any) {+ if ((error?.code === "EBUSY" || error?.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 });+});++// Mirror the cache-validity predicate used by the handler cache layers+// (getCombosCachedForChat / getCombosCached): a cached entry is only reused+// while it is within the TTL AND the combo version it was populated at still+// matches the current version. We freeze "now" so the TTL never expires on its+// own — the ONLY thing that can make the cache stale here is the version bump.+const COMBOS_CACHE_TTL_MS = 10_000;+function cacheStillValid(populatedAtTs: number, populatedAtVersion: number): boolean {+ const now = populatedAtTs; // same instant → TTL has not elapsed+ return (+ now - populatedAtTs < COMBOS_CACHE_TTL_MS &&+ populatedAtVersion === readCache.getCombosCacheVersion()+ );+}++test("createCombo bumps the combos cache version (invalidation hook fires)", async () => {+ const before = readCache.getCombosCacheVersion();+ await combosDb.createCombo({+ name: "Alpha",+ models: [{ provider: "openai", model: "gpt-4.1" }],+ });+ assert.notEqual(+ readCache.getCombosCacheVersion(),+ before,+ "createCombo must invalidate the combos cache"+ );+});++test("editing a combo invalidates the nested-expansion cache within the 10s window", async () => {+ // Warm the cache: snapshot version + timestamp as the handler layers do.+ const populatedAtTs = Date.now();+ const populatedAtVersion = readCache.getCombosCacheVersion();+ await combosDb.createCombo({+ name: "Child",+ models: [{ provider: "openai", model: "gpt-4o-mini" }],+ });+ const parent = await combosDb.createCombo({+ name: "Parent",+ models: ["Child", { model: "anthropic/claude-sonnet-4", weight: 2 }],+ });++ // A write happened → the cache populated before it must now be considered+ // stale even though the (frozen) TTL has not elapsed.+ assert.equal(+ cacheStillValid(populatedAtTs, populatedAtVersion),+ false,+ "cache populated before the combo writes must be invalidated immediately"+ );++ // Re-warm against the post-write state, then mutate again and confirm the+ // edit (update) is also picked up within the window.+ const freshTs = Date.now();+ const freshVersion = readCache.getCombosCacheVersion();+ assert.equal(cacheStillValid(freshTs, freshVersion), true);++ await combosDb.updateCombo((parent as any).id, { strategy: "round-robin" });+ assert.equal(+ cacheStillValid(freshTs, freshVersion),+ false,+ "updateCombo must invalidate the cache without waiting for the TTL"+ );+});++test("deleteCombo and reorderCombos also invalidate the cache", async () => {+ const a = await combosDb.createCombo({+ name: "A",+ models: [{ provider: "openai", model: "gpt-4.1" }],+ });+ const b = await combosDb.createCombo({+ name: "B",+ models: [{ provider: "anthropic", model: "claude-3-7-sonnet" }],+ });++ let ts = Date.now();+ let version = readCache.getCombosCacheVersion();+ await combosDb.reorderCombos([(b as any).id, (a as any).id]);+ assert.equal(+ cacheStillValid(ts, version),+ false,+ "reorderCombos must invalidate the cache"+ );++ ts = Date.now();+ version = readCache.getCombosCacheVersion();+ await combosDb.deleteCombo((a as any).id);+ assert.equal(+ cacheStillValid(ts, version),+ false,+ "deleteCombo must invalidate the cache"+ );+});diff --git a/tests/unit/console-log-levels.test.ts b/tests/unit/console-log-levels.test.tsindex 119da1f1ff..a691d7e3bd 100644--- a/tests/unit/console-log-levels.test.ts+++ b/tests/unit/console-log-levels.test.ts@@ -8,7 +8,13 @@ import { updateSettings } from "../../src/lib/db/settings";const TEST_LOG_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-console-log-levels-"));const TEST_LOG_PATH = path.join(TEST_LOG_DIR, "app.log");-process.once("exit", () => fs.rmSync(TEST_LOG_DIR, { recursive: true, force: true }));+process.once("exit", () => {+ try {+ fs.rmSync(TEST_LOG_DIR, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 });+ } catch {+ // Best-effort cleanup only; tmpdir residue must not fail otherwise-passing tests.+ }+});const originalLogFilePath = process.env.APP_LOG_FILE_PATH;process.env.APP_LOG_FILE_PATH = TEST_LOG_PATH;diff --git a/tests/unit/db-provider-stats.test.ts b/tests/unit/db-provider-stats.test.tsnew file mode 100644index 0000000000..398351084a--- /dev/null+++ b/tests/unit/db-provider-stats.test.ts@@ -0,0 +1,104 @@+/**+ * #3175 — provider/model call statistics aggregated from call_logs.+ * Guards the SQL extracted out of the /api/provider-stats route (Hard Rule #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";++const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omni-db-provider-stats-"));+process.env.DATA_DIR = TEST_DATA_DIR;++const core = await import("../../src/lib/db/core.ts");+const stats = await import("../../src/lib/db/providerStats.ts");++function insertCallLog(row: Record<string, unknown>) {+ const db = core.getDbInstance();+ const full = {+ method: "POST",+ path: "/v1/chat/completions",+ status: 200,+ model: "openai/gpt-4.1",+ requested_model: null,+ provider: "openai",+ account: null,+ connection_id: null,+ duration: 100,+ tokens_in: 10,+ tokens_out: 20,+ cache_source: "upstream",+ source_format: null,+ target_format: null,+ api_key_id: null,+ api_key_name: null,+ combo_name: null,+ combo_step_id: null,+ combo_execution_key: null,+ error_summary: null,+ detail_state: "none",+ artifact_relpath: null,+ artifact_size_bytes: null,+ artifact_sha256: null,+ has_request_body: 0,+ has_response_body: 0,+ has_pipeline_details: 0,+ request_summary: null,+ ...row,+ id: row.id ?? `log-${Math.random().toString(16).slice(2)}`,+ timestamp: row.timestamp ?? new Date().toISOString(),+ };+ db.prepare(+ `INSERT INTO call_logs (+ id, timestamp, method, path, status, model, requested_model, provider, account,+ connection_id, duration, tokens_in, tokens_out, cache_source, source_format, target_format,+ api_key_id, api_key_name, combo_name, combo_step_id, combo_execution_key,+ error_summary, detail_state, artifact_relpath, artifact_size_bytes, artifact_sha256,+ has_request_body, has_response_body, has_pipeline_details, request_summary+ ) VALUES (+ @id, @timestamp, @method, @path, @status, @model, @requested_model, @provider, @account,+ @connection_id, @duration, @tokens_in, @tokens_out, @cache_source, @source_format, @target_format,+ @api_key_id, @api_key_name, @combo_name, @combo_step_id, @combo_execution_key,+ @error_summary, @detail_state, @artifact_relpath, @artifact_size_bytes, @artifact_sha256,+ @has_request_body, @has_response_body, @has_pipeline_details, @request_summary+ )`+ ).run(full);+}++test.before(() => {+ core.resetDbInstance();+});++test.after(() => {+ core.resetDbInstance();+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });+});++test("#3175 getProviderCallStats aggregates totals, success and latency per provider", () => {+ insertCallLog({ provider: "openai", status: 200, duration: 100, tokens_in: 10, tokens_out: 20 });+ insertCallLog({ provider: "openai", status: 500, duration: 300, tokens_in: 5, tokens_out: 0 });+ insertCallLog({ provider: "anthropic", status: 200, duration: 50, tokens_in: 1, tokens_out: 2 });+ // excluded: provider '-' / null+ insertCallLog({ provider: "-", status: 200 });++ const rows = stats.getProviderCallStats();+ const openai = rows.find((r) => r.provider === "openai");+ assert.ok(openai, "openai stats present");+ assert.equal(openai.totalRequests, 2);+ assert.equal(openai.successfulRequests, 1); // only the 200+ assert.equal(openai.avgLatencyMs, 200); // (100+300)/2+ assert.equal(openai.totalTokensIn, 15);+ assert.equal(openai.totalTokensOut, 20);+ assert.ok(!rows.some((r) => r.provider === "-"), "provider '-' is excluded");+ // ordered by totalRequests desc → openai (2) before anthropic (1)+ assert.equal(rows[0].provider, "openai");+});++test("#3175 getModelCallStats groups by provider+model", () => {+ const rows = stats.getModelCallStats();+ const m = rows.find((r) => r.model === "openai/gpt-4.1" && r.provider === "openai");+ assert.ok(m, "model row present");+ assert.equal(m.requests, 2);+ assert.equal(m.successfulRequests, 1);+});diff --git a/tests/unit/deepseek-web-tools-execute-2820.test.ts b/tests/unit/deepseek-web-tools-execute-2820.test.tsindex 079fb1777a..49c01497d1 100644--- a/tests/unit/deepseek-web-tools-execute-2820.test.ts+++ b/tests/unit/deepseek-web-tools-execute-2820.test.ts@@ -142,6 +142,30 @@ test("execute (non-stream) parses <tool> reply into OpenAI tool_calls", async ()}});+test("execute (non-stream) parses bare JSON reply into OpenAI tool_calls", async () => {+ const mock = installMock('{"name":"getWeather","arguments":{"city":"Paris"}}');+ try {+ const executor = new DeepSeekWebExecutor();+ const result = await executor.execute({+ model: "default",+ body: { messages: [{ role: "user", content: "weather?" }], tools: TOOLS },+ stream: false,+ credentials: { apiKey: "tkn-tools-bare-json" },+ signal: AbortSignal.timeout(10000),+ });+ assert.ok(result.response.ok);+ const json = JSON.parse(await result.response.text());+ const choice = json.choices[0];+ assert.equal(choice.finish_reason, "tool_calls");+ assert.equal(choice.message.tool_calls.length, 1);+ 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, "bare JSON tool call is stripped from content");+ } finally {+ mock.restore();+ }+});+test("execute (stream) emits tool_calls + finish_reason tool_calls in the SSE", async () => {const mock = installMock(TOOL_REPLY);try {diff --git a/tests/unit/fireworks-model-id-prefix.test.ts b/tests/unit/fireworks-model-id-prefix.test.tsindex c16203b9cd..24acb2afee 100644--- a/tests/unit/fireworks-model-id-prefix.test.ts+++ b/tests/unit/fireworks-model-id-prefix.test.ts@@ -27,6 +27,26 @@ test("DefaultExecutor.transformRequest does not double-prepend modelIdPrefix", (assert.equal((result as Record<string, unknown>).model, "accounts/fireworks/models/kimi-k2p6");});+test("DefaultExecutor.transformRequest preserves fully-qualified fireworks router IDs (#3133)", () => {+ const executor = new DefaultExecutor("fireworks");+ const body = {+ model: "accounts/fireworks/routers/kimi-k2p6-turbo",+ messages: [{ role: "user", content: "hi" }],+ };++ const result = executor.transformRequest(+ "accounts/fireworks/routers/kimi-k2p6-turbo",+ body,+ false,+ {}+ );++ assert.equal(+ (result as Record<string, unknown>).model,+ "accounts/fireworks/routers/kimi-k2p6-turbo"+ );+});+test("DefaultExecutor.transformRequest does not modify model for providers without modelIdPrefix", () => {const executor = new DefaultExecutor("openai");const body = { model: "gpt-4.1", messages: [{ role: "user", content: "hi" }] };diff --git a/tests/unit/github-copilot-model-discovery.test.ts b/tests/unit/github-copilot-model-discovery.test.tsnew file mode 100644index 0000000000..d925631dda--- /dev/null+++ b/tests/unit/github-copilot-model-discovery.test.ts@@ -0,0 +1,143 @@+/**+ * Issues #3120 / #3121 — GitHub Copilot model discovery (thanks @gabrielmoreira).+ *+ * #3120: "Import Models" never refreshes the Copilot model list because the+ * `github` (Copilot) provider had a STATIC hardcoded catalog and no live+ * discovery source.+ * #3121: That static catalog advertised models (e.g. gemini previews) that the+ * account is not entitled to, so testing them returned upstream 400s.+ *+ * Fix: discover the catalog live from https://api.githubcopilot.com/models using+ * the Copilot bearer + Copilot chat headers, parse `data[].id` into managed+ * models, and fall back to the static catalog only when the live fetch fails.+ *+ * These tests target the discovery helper directly (injected fetch) so they need+ * no HTTP server or DB.+ */+import test from "node:test";+import assert from "node:assert/strict";++const {+ GITHUB_COPILOT_MODELS_URL,+ parseGitHubCopilotModels,+ fetchGitHubCopilotModels,+} = await import("../../open-sse/services/githubCopilotModels.ts");++// A representative slice of a real Copilot /models response. Crucially it+// includes models the account IS entitled to, and OMITS gemini previews to+// prove non-entitled models are not advertised (#3121).+const MOCK_COPILOT_MODELS_RESPONSE = {+ data: [+ {+ id: "gpt-5.4",+ name: "GPT-5.4",+ model_picker_enabled: true,+ policy: { state: "enabled" },+ capabilities: { type: "chat", limits: { max_context_window_tokens: 128000 } },+ },+ {+ id: "claude-sonnet-4.5",+ name: "Claude Sonnet 4.5",+ model_picker_enabled: true,+ capabilities: { type: "chat" },+ },+ {+ // embeddings model — not a chat model; discovery should still surface the id+ id: "text-embedding-3-small",+ name: "Embedding V3 small",+ capabilities: { type: "embeddings" },+ },+ ],+};++test("#3120 parseGitHubCopilotModels maps data[].id into managed models", () => {+ const models = parseGitHubCopilotModels(MOCK_COPILOT_MODELS_RESPONSE);+ const ids = models.map((m) => m.id);+ assert.ok(ids.includes("gpt-5.4"), "gpt-5.4 must be discovered");+ assert.ok(ids.includes("claude-sonnet-4.5"), "claude-sonnet-4.5 must be discovered");+ const gpt = models.find((m) => m.id === "gpt-5.4");+ assert.ok(gpt, "gpt-5.4 entry present");+ assert.equal(gpt.name, "GPT-5.4");+ assert.equal(gpt.owned_by, "github");+});++test("#3121 a model NOT in the live response is not advertised (entitlement filtering)", () => {+ const models = parseGitHubCopilotModels(MOCK_COPILOT_MODELS_RESPONSE);+ const ids = models.map((m) => m.id);+ // gemini-3.1-pro-preview is in the OLD static catalog but NOT entitled here.+ assert.ok(+ !ids.includes("gemini-3.1-pro-preview"),+ "non-entitled gemini preview must NOT be advertised"+ );+});++test("#3120 fetchGitHubCopilotModels does a live fetch and returns parsed models", async () => {+ let capturedUrl = "";+ let capturedHeaders: Record<string, string> = {};+ const fakeFetch = (async (url: string, init: RequestInit) => {+ capturedUrl = String(url);+ capturedHeaders = (init?.headers as Record<string, string>) || {};+ return new Response(JSON.stringify(MOCK_COPILOT_MODELS_RESPONSE), {+ status: 200,+ headers: { "content-type": "application/json" },+ });+ }) as unknown as typeof fetch;++ const result = await fetchGitHubCopilotModels({+ token: "copilot-tok-abc",+ fetchImpl: fakeFetch,+ });++ assert.equal(capturedUrl, GITHUB_COPILOT_MODELS_URL);+ assert.equal(+ capturedHeaders.Authorization,+ "Bearer copilot-tok-abc",+ "must authenticate with the Copilot bearer token"+ );+ // Copilot chat headers must be present (e.g. copilot-integration-id).+ assert.ok(capturedHeaders["copilot-integration-id"], "must send Copilot integration header");+ assert.equal(result.source, "api");+ const ids = result.models.map((m) => m.id);+ assert.ok(ids.includes("gpt-5.4"));+ assert.ok(!ids.includes("gemini-3.1-pro-preview"));+});++test("#3120/#3121 fetch falls back to static catalog when the live fetch fails", async () => {+ const fakeFetch = (async () =>+ new Response("nope", { status: 503 })) as unknown as typeof fetch;+ const fallback = [+ { id: "gpt-5.4", name: "GPT-5.4" },+ { id: "gemini-3.1-pro-preview", name: "Gemini 3.1 Pro" },+ ];++ const result = await fetchGitHubCopilotModels({+ token: "copilot-tok-abc",+ fetchImpl: fakeFetch,+ fallbackModels: fallback,+ });++ assert.equal(result.source, "fallback");+ assert.deepEqual(+ result.models.map((m) => m.id),+ ["gpt-5.4", "gemini-3.1-pro-preview"],+ "offline/failed discovery must preserve the static catalog"+ );+});++test("fetch falls back when no token is provided (unauthed refresh stays safe)", async () => {+ let called = false;+ const fakeFetch = (async () => {+ called = true;+ return new Response("{}", { status: 200 });+ }) as unknown as typeof fetch;++ const result = await fetchGitHubCopilotModels({+ token: "",+ fetchImpl: fakeFetch,+ fallbackModels: [{ id: "gpt-5.4", name: "GPT-5.4" }],+ });++ assert.equal(called, false, "must not fetch without a token");+ assert.equal(result.source, "fallback");+ assert.deepEqual(result.models.map((m) => m.id), ["gpt-5.4"]);+});diff --git a/tests/unit/llama-cpp-local-url.test.ts b/tests/unit/llama-cpp-local-url.test.tsnew file mode 100644index 0000000000..234bea1ae9--- /dev/null+++ b/tests/unit/llama-cpp-local-url.test.ts@@ -0,0 +1,20 @@+import { test } from "node:test";+import assert from "node:assert/strict";++import { DefaultExecutor } from "@omniroute/open-sse/executors/default.ts";++// Regression for issue #3136: a `llama-cpp` local provider connection must send+// requests to the user's configured local baseUrl, not OpenAI's API. Before the+// fix, `llama-cpp` was missing from the local-provider case group in buildUrl(),+// so it fell through to the registry/default path and (because llama-cpp is not+// in the registry → DefaultExecutor falls back to PROVIDERS.openai) resolved to+// https://api.openai.com/v1/... — producing OpenAI-worded 401 "no api key" errors.+test("llama-cpp buildUrl routes to the configured local baseUrl, not OpenAI", () => {+ const executor = new DefaultExecutor("llama-cpp");+ const url = executor.buildUrl("some-model", true, 0, {+ providerSpecificData: { baseUrl: "http://127.0.0.1:8080/v1" },+ });++ assert.equal(url, "http://127.0.0.1:8080/v1/chat/completions");+ assert.ok(!url.includes("api.openai.com"), `expected local URL, got ${url}`);+});diff --git a/tests/unit/minimax-m3-maxtokens.test.ts b/tests/unit/minimax-m3-maxtokens.test.tsnew file mode 100644index 0000000000..93a63d9b40--- /dev/null+++ b/tests/unit/minimax-m3-maxtokens.test.ts@@ -0,0 +1,80 @@+/**+ * tests/unit/minimax-m3-maxtokens.test.ts+ *+ * Regression for issue #3141 — "Omniroute sets max_tokens = 8192 for+ * minimax/MiniMax-M3" (reporter @totaltube).+ *+ * minimax-coding / minimax route through the Claude translator, which calls+ * fitThinkingToMaxTokens(model, callerMaxTokens, …) → capMaxOutputTokens().+ * The caller's larger max_tokens was silently capped to the 8192+ * MODEL_SPECS.__default__ ceiling because:+ * (a) MiniMax-M3 had no MODEL_SPECS entry at all, and the registry models+ * declare no maxOutputTokens, so resolution fell through to __default__;+ * (b) MiniMax-M2.7 (the upstream, capitalized id) never matched its existing+ * lowercase "minimax-m2.7" spec because getModelSpec was case-SENSITIVE.+ *+ * Both lookups must now resolve to the real family ceiling (well above 8192).+ */++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-minimax-m3-"));+process.env.DATA_DIR = TEST_DATA_DIR;++const core = await import("../../src/lib/db/core.ts");+const modelCapabilities = await import("../../src/lib/modelCapabilities.ts");+const { getModelSpec } = await import("../../src/shared/constants/modelSpecs.ts");++test.after(() => {+ core.resetDbInstance();+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });+});++const DEFAULT_CAP = 8192;++test("#3141 MiniMax-M3 max_tokens is not capped to the 8192 default", () => {+ const cap = modelCapabilities.capMaxOutputTokens({ provider: "minimax", model: "MiniMax-M3" });+ assert.ok(+ cap > DEFAULT_CAP,+ `expected MiniMax-M3 maxOutputTokens > ${DEFAULT_CAP}, got ${cap}`+ );+});++test("#3141 MiniMaxAI/MiniMax-M3 (prefixed id) resolves above the 8192 default", () => {+ const cap = modelCapabilities.capMaxOutputTokens({+ provider: "minimax",+ model: "MiniMaxAI/MiniMax-M3",+ });+ assert.ok(+ cap > DEFAULT_CAP,+ `expected MiniMaxAI/MiniMax-M3 maxOutputTokens > ${DEFAULT_CAP}, got ${cap}`+ );+});++test("#3141 capitalized MiniMax-M2.7 resolves to its lowercase spec (case-insensitive)", () => {+ const cap = modelCapabilities.capMaxOutputTokens({ provider: "minimax", model: "MiniMax-M2.7" });+ assert.ok(+ cap > DEFAULT_CAP,+ `expected MiniMax-M2.7 maxOutputTokens > ${DEFAULT_CAP}, got ${cap}`+ );+});++test("#3141 lowercase minimax-m2.7 spec is unchanged", () => {+ const cap = modelCapabilities.capMaxOutputTokens({ provider: "minimax", model: "minimax-m2.7" });+ assert.ok(+ cap > DEFAULT_CAP,+ `expected minimax-m2.7 maxOutputTokens > ${DEFAULT_CAP}, got ${cap}`+ );+});++test("#3141 getModelSpec resolves MiniMax-M3 and capitalized M2.7 to family specs", () => {+ assert.ok(getModelSpec("MiniMax-M3"), "MiniMax-M3 should have a spec");+ assert.ok(+ getModelSpec("MiniMax-M2.7"),+ "capitalized MiniMax-M2.7 should resolve to the minimax-m2.7 spec"+ );+});diff --git a/tests/unit/provider-alias-uniqueness.test.ts b/tests/unit/provider-alias-uniqueness.test.tsnew file mode 100644index 0000000000..7aeb68bdae--- /dev/null+++ b/tests/unit/provider-alias-uniqueness.test.ts@@ -0,0 +1,64 @@+/**+ * Provider alias uniqueness — no two provider IDs may share the same short alias.+ *+ * Before this guard, three aliases collided in the registry and the LAST entry in+ * iteration order silently won, emitting a startup warning and shadowing a real+ * provider:+ * - "qw" → qwen-web (shadowed qwen)+ * - "kimi" → kimi-web (shadowed the kimi provider that gained a dedicated executor)+ * - "hc" → hackclub (shadowed huggingchat)+ *+ * The decision: the primary provider keeps the short alias; the web/secondary+ * variant takes its own id as alias. This test pins both the global uniqueness+ * invariant (so future additions can't silently re-collide) and the specific+ * resolutions for the six affected providers, across BOTH alias sources+ * (open-sse registry + src/shared providers map).+ */+import test from "node:test";+import assert from "node:assert/strict";++import { PROVIDER_ID_TO_ALIAS } from "../../open-sse/config/providerModels.ts";+import { resolveProviderId, getProviderAlias } from "../../src/shared/constants/providers.ts";++test("no two provider IDs share the same alias in the open-sse registry", () => {+ const aliasToIds = new Map<string, string[]>();+ for (const [id, alias] of Object.entries(PROVIDER_ID_TO_ALIAS)) {+ const ids = aliasToIds.get(alias) ?? [];+ ids.push(id);+ aliasToIds.set(alias, ids);+ }++ const collisions = [...aliasToIds.entries()].filter(([, ids]) => ids.length > 1);+ assert.deepEqual(+ collisions,+ [],+ `Alias collisions detected (each alias must map to exactly one provider id): ${collisions+ .map(([alias, ids]) => `"${alias}" → ${ids.join(", ")}`)+ .join("; ")}`+ );+});++test("primary providers keep the short alias; web/secondary variants use their own id", () => {+ // open-sse registry (source of the startup warning + chat routing)+ assert.equal(PROVIDER_ID_TO_ALIAS.qwen, "qw");+ assert.equal(PROVIDER_ID_TO_ALIAS["qwen-web"], "qwen-web");+ assert.equal(PROVIDER_ID_TO_ALIAS.kimi, "kimi");+ assert.equal(PROVIDER_ID_TO_ALIAS["kimi-web"], "kimi-web");+ assert.equal(PROVIDER_ID_TO_ALIAS.hackclub, "hc");+ assert.equal(PROVIDER_ID_TO_ALIAS.huggingchat, "huggingchat");+});++test("src/shared providers map resolves the same aliases unambiguously", () => {+ // alias → id+ assert.equal(resolveProviderId("qw"), "qwen");+ assert.equal(resolveProviderId("kimi"), "kimi");+ assert.equal(resolveProviderId("hc"), "hackclub");+ // id used as alias for the secondary variants+ assert.equal(resolveProviderId("qwen-web"), "qwen-web");+ assert.equal(resolveProviderId("kimi-web"), "kimi-web");+ assert.equal(resolveProviderId("huggingchat"), "huggingchat");+ // id → alias+ assert.equal(getProviderAlias("qwen"), "qw");+ assert.equal(getProviderAlias("kimi"), "kimi");+ assert.equal(getProviderAlias("hackclub"), "hc");+});diff --git a/tests/unit/provider-limits-401-reauth-hint.test.ts b/tests/unit/provider-limits-401-reauth-hint.test.tsnew file mode 100644index 0000000000..b66fff2ac0--- /dev/null+++ b/tests/unit/provider-limits-401-reauth-hint.test.ts@@ -0,0 +1,28 @@+/**+ * (C) The quota page must make a genuine 401 actionable.+ *+ * After the on-demand path attempts a forced serialized re-mint (B), a 401 that+ * still reaches the client means the token is genuinely dead. The card must show+ * a re-authenticate hint and flag the connection as errored — not render a+ * silent empty card (which read as "force revalidate does nothing").+ */+import test from "node:test";+import assert from "node:assert/strict";+import fs from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";++const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");+const indexPath = path.join(+ repoRoot,+ "src/app/(dashboard)/dashboard/usage/components/ProviderLimits/index.tsx"+);+const source = fs.readFileSync(indexPath, "utf8");++test("ProviderLimits surfaces a re-authenticate hint and error state on 401", () => {+ const start = source.indexOf("if (response.status === 401)");+ const block = source.slice(start, source.indexOf("throw new Error(`HTTP", start));+ assert.ok(block.length > 0, "expected to find the 401 handling block");+ assert.match(block, /re-?authenticate this account/i, "401 must add a re-authenticate hint");+ assert.match(block, /setErrors\(/, "401 must flag the connection as errored, not just a message");+});diff --git a/tests/unit/provider-limits-force-refresh-imported.test.ts b/tests/unit/provider-limits-force-refresh-imported.test.tsnew file mode 100644index 0000000000..7e3717503f--- /dev/null+++ b/tests/unit/provider-limits-force-refresh-imported.test.ts@@ -0,0 +1,88 @@+/**+ * (#3019 reactive-recovery follow-up) Force-refresh on the on-demand path.+ *+ * Imported Codex accounts have no `expiresAt` (token pasted, not minted here),+ * so `needsRefresh` is always false — the per-card "force revalidate" could+ * never re-mint them, leaving an expired imported token stuck. The on-demand+ * path now passes `{ force: true }` AFTER an observed 401 to bypass the+ * proactive `needsRefresh` heuristic (still serialized per rotation group).+ *+ * Critically, `force` must NOT override the bulk #3019 guard: without+ * `allowRotatingRefresh`, a rotating provider is still never refreshed.+ */+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";++process.env.DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-force-refresh-imported-"));++const { getExecutor } = await import("../../open-sse/executors/index.ts");+const { refreshAndUpdateCredentials } = await import("../../src/lib/usage/providerLimits.ts");++function importedCodexConnection() {+ return {+ id: "codex-imported-1",+ provider: "codex",+ accessToken: "imported-access-token",+ refreshToken: "imported-refresh-token",+ tokenExpiresAt: null, // imported: no known expiry → needsRefresh is always false+ providerSpecificData: {},+ };+}++test("force re-mints an imported rotating account that needsRefresh would skip (#3019 reactive)", async () => {+ const exec = getExecutor("codex");+ const origNeeds = exec.needsRefresh;+ const origRefresh = exec.refreshCredentials;+ let refreshCalls = 0;+ exec.needsRefresh = () => false; // imported account: heuristic never fires+ exec.refreshCredentials = async () => {+ refreshCalls++;+ return { accessToken: "freshly-minted-token", expiresIn: 3600 };+ };+ try {+ // Baseline: on-demand path WITHOUT force respects needsRefresh → no mint.+ const noForce = await refreshAndUpdateCredentials(importedCodexConnection(), {+ allowRotatingRefresh: true,+ });+ assert.equal(noForce.refreshed, false, "without force, needsRefresh=false → no mint");+ assert.equal(refreshCalls, 0);++ // Reactive recovery: force bypasses needsRefresh and re-mints.+ const forced = await refreshAndUpdateCredentials(importedCodexConnection(), {+ allowRotatingRefresh: true,+ force: true,+ });+ assert.equal(forced.refreshed, true, "force must re-mint the imported account");+ assert.equal(refreshCalls, 1, "refreshCredentials must be invoked once under force");+ assert.equal(forced.connection.accessToken, "freshly-minted-token");+ } finally {+ exec.needsRefresh = origNeeds;+ exec.refreshCredentials = origRefresh;+ }+});++test("force does NOT override the bulk #3019 guard (no allowRotatingRefresh → no mint)", async () => {+ const exec = getExecutor("codex");+ const origNeeds = exec.needsRefresh;+ const origRefresh = exec.refreshCredentials;+ let refreshCalls = 0;+ exec.needsRefresh = () => true;+ exec.refreshCredentials = async () => {+ refreshCalls++;+ return { accessToken: "should-not-happen", expiresIn: 3600 };+ };+ try {+ const result = await refreshAndUpdateCredentials(importedCodexConnection(), {+ // allowRotatingRefresh omitted → bulk/scheduled semantics+ force: true,+ });+ assert.equal(result.refreshed, false, "bulk path must never refresh a rotating provider");+ assert.equal(refreshCalls, 0, "force must not break the #3019 bulk guard");+ } finally {+ exec.needsRefresh = origNeeds;+ exec.refreshCredentials = origRefresh;+ }+});diff --git a/tests/unit/provider-limits-oauth-sequential-sync.test.ts b/tests/unit/provider-limits-oauth-sequential-sync.test.tsnew file mode 100644index 0000000000..d1c99ca088--- /dev/null+++ b/tests/unit/provider-limits-oauth-sequential-sync.test.ts@@ -0,0 +1,139 @@+/**+ * OAuth provider-limits sync must be SEQUENTIAL + SPACED.+ *+ * `syncAllProviderLimits` historically fetched every connection in chunks of 5+ * CONCURRENT. For OAuth providers (Codex/Claude/Kimi-coding/…) that means up to+ * 5 simultaneous usage/refresh requests to the same upstream from one host —+ * which looks like burst/automated traffic and contributes to session+ * termination / anomaly flags. OAuth connections must instead be processed one+ * at a time with a spacing gap between them. Non-OAuth (stateless API-key)+ * connections keep the fast concurrent 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-oauth-seq-sync-"));+process.env.DATA_DIR = TEST_DATA_DIR;+process.env.API_KEY_SECRET = "test-oauth-seq-sync-secret";+process.env.PROVIDER_LIMITS_SYNC_SPACING_MS = "60";++const core = await import("../../src/lib/db/core.ts");+const providersDb = await import("../../src/lib/db/providers.ts");+const providerLimits = await import("../../src/lib/usage/providerLimits.ts");++const originalFetch = globalThis.fetch;++test.beforeEach(() => {+ globalThis.fetch = originalFetch;+ core.resetDbInstance();+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });+ fs.mkdirSync(TEST_DATA_DIR, { recursive: true });+});++test.after(() => {+ globalThis.fetch = originalFetch;+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });+});++async function createClaudeOAuth(i: number) {+ return providersDb.createProviderConnection({+ provider: "claude",+ authType: "oauth",+ name: `Claude Seq ${i}`,+ email: `claude-seq-${i}@example.test`,+ accessToken: `claude-access-${i}`,+ refreshToken: `claude-refresh-${i}`,+ // Future expiry → scheduled sync never mints; it only fetches usage.+ expiresAt: new Date(Date.now() + 60 * 60 * 1000).toISOString(),+ });+}++function claudeUsageResponse() {+ return new Response(+ JSON.stringify({+ tier: "pro",+ five_hour: { utilization: 10, resets_at: new Date(Date.now() + 3600000).toISOString() },+ seven_day: { utilization: 20, resets_at: new Date(Date.now() + 86400000).toISOString() },+ }),+ { status: 200, headers: { "content-type": "application/json" } }+ );+}++function claudeBootstrapResponse() {+ return new Response(+ JSON.stringify({+ oauth_account: {+ account_uuid: "acc-uuid",+ account_email: "[email protected]",+ organization_uuid: "org-uuid",+ organization_name: "Org",+ organization_type: "pro",+ organization_rate_limit_tier: "pro",+ },+ }),+ { status: 200, headers: { "content-type": "application/json" } }+ );+}++test("syncAllProviderLimits processes OAuth connections sequentially with spacing", async () => {+ for (let i = 0; i < 3; i++) await createClaudeOAuth(i);++ // Track concurrency PER CONNECTION (by access token) — intra-connection+ // parallel fetches (usage + bootstrap) are fine; what must never happen is two+ // *different* OAuth connections being fetched at the same time.+ const inFlightConns = new Set<string>();+ let maxDistinctConns = 0;+ const connFirstStart: Record<string, number> = {};++ const tokenOf = (init: RequestInit | undefined): string => {+ const headers = new Headers((init?.headers as HeadersInit) || {});+ for (const [, v] of headers.entries()) {+ const m = /claude-access-(\d+)/.exec(String(v));+ if (m) return m[1];+ }+ return "unknown";+ };++ globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(+ typeof input === "string" ? input : input instanceof URL ? input.href : (input as Request).url+ );+ const conn = tokenOf(init);+ if (connFirstStart[conn] === undefined) connFirstStart[conn] = Date.now();+ inFlightConns.add(conn);+ maxDistinctConns = Math.max(maxDistinctConns, inFlightConns.size);+ // Hold the request open so two concurrent connections would overlap.+ await new Promise((r) => setTimeout(r, 30));+ try {+ if (url.includes("/bootstrap") || url.includes("oauth_account")) {+ return claudeBootstrapResponse();+ }+ return claudeUsageResponse();+ } finally {+ // Only clear once this connection has no further in-flight fetch. Since+ // intra-connection fetches are sequential, clearing here is correct.+ inFlightConns.delete(conn);+ }+ }) as typeof fetch;++ await providerLimits.syncAllProviderLimits({ source: "scheduled" });++ assert.equal(+ maxDistinctConns,+ 1,+ `Two different OAuth connections must never be fetched concurrently, observed ${maxDistinctConns}`+ );++ // The spacing gap must separate consecutive connections' first fetches.+ const starts = Object.values(connFirstStart).sort((a, b) => a - b);+ assert.ok(starts.length >= 2, "expected fetches from at least two connections");+ const gaps: number[] = [];+ for (let i = 1; i < starts.length; i++) gaps.push(starts[i] - starts[i - 1]);+ assert.ok(+ gaps.every((g) => g >= 50),+ `every inter-connection gap must be >= configured spacing (~60ms), gaps=${gaps.join(",")}`+ );+});diff --git a/tests/unit/provider-models-route.test.ts b/tests/unit/provider-models-route.test.tsindex 87b662dbae..d86ee3c2e0 100644--- a/tests/unit/provider-models-route.test.ts+++ b/tests/unit/provider-models-route.test.ts@@ -640,6 +640,47 @@ test("provider models route honors autoFetchModels=false and skips remote discovassert.ok(body.models.some((model) => model.id === "glm-5"));});+test("provider models route uses synced models as the authoritative local catalog (#3148)", async () => {+ // A connection that resolves to the local catalog (auto-fetch off, no remote+ // discovery). Once a sync has populated the synced-models table for this+ // provider, the route must surface the synced list — even on a connection+ // that never ran the sync itself — instead of the static catalog.+ const connection = await seedConnection("opencode-go", {+ apiKey: "opencode-go-key",+ providerSpecificData: {+ autoFetchModels: false,+ },+ });++ await modelsDb.replaceSyncedAvailableModelsForConnection("opencode-go", "synced-conn", [+ { id: "synced-only-model", name: "Synced Only Model" },+ ]);++ let called = false;+ globalThis.fetch = async () => {+ called = true;+ return Response.json({ data: [] });+ };++ const response = await callRoute(connection.id);+ const body = (await response.json()) as any;++ assert.equal(response.status, 200);+ assert.equal(body.source, "local_catalog");+ assert.equal(called, false);+ // Synced models become the catalog…+ assert.ok(+ body.models.some((model) => model.id === "synced-only-model"),+ "synced model should be present in the local catalog"+ );+ // …and the static catalog entries are no longer surfaced for this provider.+ assert.equal(+ body.models.some((model) => model.id === "glm-5"),+ false,+ "static catalog should be superseded by the synced list"+ );+});+test("provider models route validates Gemini CLI credentials before fetching quota buckets", async () => {const missingToken = await seedConnection("gemini-cli", {authType: "oauth",diff --git a/tests/unit/provider-registry-kilocode-format.test.ts b/tests/unit/provider-registry-kilocode-format.test.tsnew file mode 100644index 0000000000..0cf9bbaced--- /dev/null+++ b/tests/unit/provider-registry-kilocode-format.test.ts@@ -0,0 +1,33 @@+/**+ * #3166 — kilocode must use the OpenAI-compatible format + default executor.+ *+ * kilocode hits an `api.kilo.ai` endpoint (`/api/openrouter/chat/completions`)+ * that returns the OpenAI chat-completions shape — the same family as its+ * sibling `kilo-gateway`. It was previously registered with+ * `format/executor: "openrouter"`, which applied OpenRouter-specific handling+ * the endpoint does not expect. Align it with `kilo-gateway` (format "openai",+ * executor "default").+ */+import test from "node:test";+import assert from "node:assert/strict";++const { REGISTRY } = await import("../../open-sse/config/providerRegistry.ts");++test("#3166 kilocode uses the OpenAI format + default executor (matches kilo-gateway)", () => {+ const reg = REGISTRY as Record<string, Record<string, unknown>>;+ const kilocode = reg.kilocode;+ assert.ok(kilocode, "kilocode should be present in the executor registry");+ assert.equal(kilocode.format, "openai");+ assert.equal(kilocode.executor, "default");++ // Consistency with the sibling api.kilo.ai provider.+ const gateway = reg["kilo-gateway"];+ if (gateway) {+ assert.equal(kilocode.format, gateway.format, "kilocode format must match kilo-gateway");+ assert.equal(+ kilocode.executor,+ gateway.executor,+ "kilocode executor must match kilo-gateway"+ );+ }+});diff --git a/tests/unit/provider-validation-hardening.test.ts b/tests/unit/provider-validation-hardening.test.tsindex 9bbeba99e9..839826679a 100644--- a/tests/unit/provider-validation-hardening.test.ts+++ b/tests/unit/provider-validation-hardening.test.ts@@ -188,3 +188,43 @@ test("#2545 gemini validation does not produce /models/models", async () => {`outbound URL must hit a single /models segment — got ${calls.join(", ")}`);});++test("qoder regular API key validates against dashscope, not the Cosy PAT endpoint (#3149)", async () => {+ const calls: string[] = [];+ globalThis.fetch = async (url: any, init: any) => {+ calls.push(String(url));+ const auth = new Headers(init?.headers as HeadersInit | undefined).get("authorization");+ assert.equal(auth, "Bearer sk-qoder-regular", "dashscope probe must forward the API key");+ return new Response(JSON.stringify({ data: [] }), { status: 200 });+ };++ const result = await validateProviderApiKey({+ provider: "qoder",+ apiKey: "sk-qoder-regular",+ providerSpecificData: {},+ });++ assert.equal(result.valid, true);+ assert.ok(+ calls.some((u) => u.includes("dashscope.aliyuncs.com/compatible-mode/v1/models")),+ `regular qoder key must validate against dashscope — got ${calls.join(", ")}`+ );+ assert.ok(+ !calls.some((u) => u.includes("api1.qoder.sh")),+ "regular (non-PAT) key must not hit the Cosy PAT endpoint"+ );+});++test("qoder regular API key surfaces an auth error when dashscope rejects it (#3149)", async () => {+ globalThis.fetch = async () =>+ new Response(JSON.stringify({ error: { message: "invalid api key" } }), { status: 401 });++ const result = await validateProviderApiKey({+ provider: "qoder",+ apiKey: "sk-qoder-bad",+ providerSpecificData: {},+ });++ assert.equal(result.valid, false);+ assert.match(result.error, /Qoder|Dashscope|API key/i);+});diff --git a/tests/unit/quota-token-expiry-display.test.ts b/tests/unit/quota-token-expiry-display.test.tsnew file mode 100644index 0000000000..32c4616634--- /dev/null+++ b/tests/unit/quota-token-expiry-display.test.ts@@ -0,0 +1,49 @@+/**+ * The quota card shows an informative (small, blue) OAuth token-expiry line for+ * connections that expose a concrete token expiry (e.g. Codex), and an expired+ * marker otherwise. API-key / no-expiry connections show nothing.+ */+import test from "node:test";+import assert from "node:assert/strict";+import fs from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";++const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");+const headerPath = path.join(+ repoRoot,+ "src/app/(dashboard)/dashboard/usage/components/ProviderLimits/parts/QuotaCardHeader.tsx"+);+const source = fs.readFileSync(headerPath, "utf8");++test("QuotaCardHeader derives token expiry only for OAuth connections with a known expiry", () => {+ assert.match(source, /connection\.authType === "oauth"/, "must gate on oauth auth type");+ assert.match(+ source,+ /connection\.tokenExpiresAt \|\| connection\.expiresAt/,+ "must read tokenExpiresAt with expiresAt fallback"+ );+ assert.match(source, /formatCountdown\(/, "must format the countdown");+});++test("QuotaCardHeader renders the expiry as a small blue (sky) informative line", () => {+ assert.match(source, /text-\[10px\]/, "expiry line must be small (10px)");+ assert.match(source, /text-sky-500/, "active expiry must be blue (sky-500)");+ assert.match(source, /tokenExpiresIn/, "must use the tokenExpiresIn i18n key");+ assert.match(source, /tokenExpired/, "must use the tokenExpired i18n key");+});++test("token expiry i18n keys exist in en and pt-BR", () => {+ for (const locale of ["en", "pt-BR"]) {+ const msgs = JSON.parse(+ fs.readFileSync(path.join(repoRoot, `src/i18n/messages/${locale}.json`), "utf8")+ );+ assert.ok(msgs.usage?.tokenExpiresIn, `${locale}: usage.tokenExpiresIn must exist`);+ assert.ok(msgs.usage?.tokenExpired, `${locale}: usage.tokenExpired must exist`);+ assert.match(+ msgs.usage.tokenExpiresIn,+ /\{time\}/,+ `${locale}: tokenExpiresIn must interpolate {time}`+ );+ }+});diff --git a/tests/unit/responses-handler.test.ts b/tests/unit/responses-handler.test.tsindex c98ca88f01..cdcd6676da 100644--- a/tests/unit/responses-handler.test.ts+++ b/tests/unit/responses-handler.test.ts@@ -165,7 +165,7 @@ test("handleResponsesCore converts Responses API input, instructions, tools, metassert.equal("store" in call.body, false);});-test("handleResponsesCore preserves previous_response_id and handles empty input arrays", async () => {+test("handleResponsesCore strips previous_response_id by default and handles empty input arrays", async () => {const { call, result } = await invokeResponsesCore({body: {model: "gpt-4o-mini",@@ -176,7 +176,7 @@ test("handleResponsesCore preserves previous_response_id and handles empty input});assert.equal(result.success, true);- assert.equal(call.body.previous_response_id, "resp_prev_123");+ assert.equal(call.body.previous_response_id, undefined);assert.equal(call.body.metadata, undefined);assert.deepEqual(call.body.messages, []);assert.equal(call.body.stream, true);diff --git a/tests/unit/responses-input-sanitizer-name.test.ts b/tests/unit/responses-input-sanitizer-name.test.tsindex 84f6972d15..6ab5cb2006 100644--- a/tests/unit/responses-input-sanitizer-name.test.ts+++ b/tests/unit/responses-input-sanitizer-name.test.ts@@ -72,3 +72,75 @@ test("keeps valid server reasoning item ids", () => {const result = sanitizeResponsesInputItems(items) as Array<Record<string, unknown>>;assert.equal(result[0].id, "rs_123");});++test("normalizes user image_url content parts to input_image", () => {+ const items = [+ {+ type: "message",+ role: "user",+ content: [{ type: "image_url", image_url: { url: "https://example.com/u.png", detail: "high" } }],+ },+ ];+ const result = sanitizeResponsesInputItems(items) as Array<Record<string, unknown>>;+ assert.deepEqual((result[0].content as unknown[])[0], {+ type: "input_image",+ image_url: "https://example.com/u.png",+ detail: "high",+ });+});++test("normalizes assistant image content parts to output_text", () => {+ const items = [+ {+ type: "message",+ role: "assistant",+ content: [+ { type: "image_url", image_url: { url: "https://example.com/a.png" } },+ { type: "input_image", image_url: "https://example.com/b.png" },+ ],+ },+ ];+ const result = sanitizeResponsesInputItems(items) as Array<Record<string, unknown>>;+ assert.deepEqual(result[0], {+ type: "message",+ role: "assistant",+ content: [+ { type: "output_text", text: "[Image: https://example.com/a.png]" },+ { type: "output_text", text: "[Image: https://example.com/b.png]" },+ ],+ });+});++test("normalizes replayed Responses output image parts to output_text", () => {+ const items = [+ {+ type: "message",+ role: "assistant",+ output: [{ type: "image_url", image_url: { url: "https://example.com/output.png" } }],+ },+ ];+ const result = sanitizeResponsesInputItems(items) as Array<Record<string, unknown>>;+ assert.deepEqual(result[0], {+ type: "message",+ role: "assistant",+ output: [{ type: "output_text", text: "[Image: https://example.com/output.png]" }],+ });+ assert.equal(JSON.stringify(result).includes('"image_url"'), false);+});++test("normalizes function_call_output image output parts to input_image", () => {+ const items = [+ {+ type: "function_call_output",+ call_id: "call_1",+ output: [{ type: "image_url", image_url: { url: "https://example.com/tool.png" } }],+ },+ ];+ const result = sanitizeResponsesInputItems(items) as Array<Record<string, unknown>>;+ assert.deepEqual(result[0], {+ type: "function_call_output",+ call_id: "call_1",+ output: [{ type: "input_image", image_url: "https://example.com/tool.png" }],+ });+ assert.equal(JSON.stringify(result).includes('"type":"image_url"'), false);+});diff --git a/tests/unit/responses-state-policy.test.ts b/tests/unit/responses-state-policy.test.tsnew file mode 100644index 0000000000..46b50f9fb7--- /dev/null+++ b/tests/unit/responses-state-policy.test.ts@@ -0,0 +1,71 @@+import test from "node:test";+import assert from "node:assert/strict";++import {+ applyResponsesPreviousResponseIdPolicy,+ normalizeResponsesPreviousResponseIdMode,+ shouldStripPreviousResponseId,+} from "../../open-sse/utils/responsesStatePolicy.ts";++test("responses previous_response_id policy defaults to auto", () => {+ assert.equal(normalizeResponsesPreviousResponseIdMode(undefined), "auto");+ assert.equal(normalizeResponsesPreviousResponseIdMode("invalid"), "auto");+ assert.equal(normalizeResponsesPreviousResponseIdMode("strip"), "strip");+ assert.equal(normalizeResponsesPreviousResponseIdMode("preserve"), "preserve");+});++test("auto strips previous_response_id for stateless Responses upstreams", () => {+ const result = applyResponsesPreviousResponseIdPolicy(+ { model: "gpt-5.5", previous_response_id: "resp_prev_123", input: [] },+ { mode: "auto", sourceFormat: "openai-responses", targetFormat: "openai-responses" }+ );++ assert.equal(result.stripped, true);+ assert.equal((result.body as Record<string, unknown>).previous_response_id, undefined);+});++test("auto preserves previous_response_id when Responses storage is explicitly enabled", () => {+ const result = applyResponsesPreviousResponseIdPolicy(+ { model: "gpt-5.5", previous_response_id: "resp_prev_123", input: [] },+ {+ mode: "auto",+ sourceFormat: "openai-responses",+ targetFormat: "openai-responses",+ credentials: { providerSpecificData: { openaiStoreEnabled: true } },+ }+ );++ assert.equal(result.stripped, false);+ assert.equal((result.body as Record<string, unknown>).previous_response_id, "resp_prev_123");+});++test("strip and preserve modes override auto detection", () => {+ assert.equal(+ shouldStripPreviousResponseId({+ mode: "strip",+ sourceFormat: "openai",+ targetFormat: "openai",+ }),+ true+ );+ assert.equal(+ shouldStripPreviousResponseId({+ mode: "preserve",+ sourceFormat: "openai-responses",+ targetFormat: "openai-responses",+ }),+ false+ );+});++test("auto leaves unrelated non-Responses requests untouched", () => {+ const body = { model: "gpt-4o-mini", previous_response_id: "client-extra-field" };+ const result = applyResponsesPreviousResponseIdPolicy(body, {+ mode: "auto",+ sourceFormat: "openai",+ targetFormat: "openai",+ });++ assert.equal(result.body, body);+ assert.equal(result.stripped, false);+});diff --git a/tests/unit/settings-api.test.ts b/tests/unit/settings-api.test.tsindex 743a300a1a..4d8d5904ed 100644--- a/tests/unit/settings-api.test.ts+++ b/tests/unit/settings-api.test.ts@@ -59,6 +59,11 @@ after(() => {});describe("Settings API - persisted preferences", () => {+ test("getSettings defaults Responses previous_response_id handling to auto", async () => {+ const settings = await harness.getSettings();+ assert.strictEqual(settings.responsesPreviousResponseIdMode, "auto");+ });+describe("debugMode", () => {test("updateSettings with debugMode=true succeeds", async () => {const result = await harness.updateSettings({ debugMode: true });@@ -158,6 +163,22 @@ describe("Settings API - persisted preferences", () => {assert.equal(settings.hideEndpointNgrokTunnel, true);});+ test("PATCH /api/settings persists Responses previous_response_id handling", async () => {+ const response = await harness.settingsRoute.PATCH(+ await makeManagementSessionRequest("http://localhost/api/settings", {+ method: "PATCH",+ body: { responsesPreviousResponseIdMode: "strip" },+ })+ );+ const body = (await response.json()) as Record<string, unknown>;++ assert.equal(response.status, 200);+ assert.equal(body.responsesPreviousResponseIdMode, "strip");++ const settings = await harness.getSettings();+ assert.equal(settings.responsesPreviousResponseIdMode, "strip");+ });+test("PUT /api/settings reuses the PATCH update flow", async () => {const response = await harness.settingsRoute.PUT(await makeManagementSessionRequest("http://localhost/api/settings", {diff --git a/tests/unit/t3-chat-web-credentials.test.ts b/tests/unit/t3-chat-web-credentials.test.tsnew file mode 100644index 0000000000..2cb0754d68--- /dev/null+++ b/tests/unit/t3-chat-web-credentials.test.ts@@ -0,0 +1,84 @@+import { test } from "node:test";+import assert from "node:assert/strict";++import {+ parseT3Credentials,+ validateT3Credentials,+ T3ChatWebExecutor,+} from "@omniroute/open-sse/executors/t3-chat-web.ts";++// Issue #3007: t3.chat web cookie providers not working.+// The credential pipeline stores the single pasted string as `credentials.apiKey`+// (fallback `accessToken`), but the executor used to read `credentials.cookies`+// and `credentials.convexSessionId` directly — fields nothing ever produces — so+// validation always failed with 400 "missing or empty cookies".+// These tests feed the three valid forms via `apiKey` and assert the parser/+// validator accept them and produce a Cookie header carrying convex-session-id.++test("parseT3Credentials: form (a) — convex-session-id=...; sessionToken=...", () => {+ const creds = { apiKey: "convex-session-id=abc; sessionToken=xyz" };+ const parsed = parseT3Credentials(creds);+ assert.ok(parsed, "parser should produce credentials");+ assert.ok(validateT3Credentials(parsed), "credentials should be valid");+ assert.match(parsed.cookieHeader, /convex-session-id=/);+ assert.match(parsed.cookieHeader, /sessionToken=xyz/);+});++test("parseT3Credentials: form (b) — full Cookie header already containing convex-session-id", () => {+ const creds = {+ apiKey:+ "__Secure-better-auth.session_token=foo; convex-session-id=session-123; theme=dark",+ };+ const parsed = parseT3Credentials(creds);+ assert.ok(parsed);+ assert.ok(validateT3Credentials(parsed));+ assert.match(parsed.cookieHeader, /convex-session-id=session-123/);+ // No duplication of convex-session-id+ assert.equal(+ parsed.cookieHeader.match(/convex-session-id=/g)?.length,+ 1,+ "convex-session-id must appear exactly once"+ );+});++test("parseT3Credentials: form (c) — structured cookies=...\\nconvexSessionId=...", () => {+ const creds = {+ apiKey: "cookies=__Secure-session=foo; theme=dark\nconvexSessionId=conv-789",+ };+ const parsed = parseT3Credentials(creds);+ assert.ok(parsed);+ assert.ok(validateT3Credentials(parsed));+ assert.match(parsed.cookieHeader, /convex-session-id=conv-789/);+ assert.match(parsed.cookieHeader, /__Secure-session=foo/);+});++test("parseT3Credentials: reads accessToken fallback when apiKey is absent", () => {+ const creds = { accessToken: "convex-session-id=tok; sessionToken=zzz" };+ const parsed = parseT3Credentials(creds);+ assert.ok(parsed);+ assert.ok(validateT3Credentials(parsed));+ assert.match(parsed.cookieHeader, /convex-session-id=tok/);+});++test("validateT3Credentials: empty apiKey fails (negative case)", () => {+ const parsed = parseT3Credentials({ apiKey: "" });+ assert.equal(validateT3Credentials(parsed), false);+});++test("validateT3Credentials: undefined credentials fail", () => {+ const parsed = parseT3Credentials(undefined);+ assert.equal(validateT3Credentials(parsed), false);+});++test("execute(): empty apiKey still returns a 400 error response", async () => {+ const executor = new T3ChatWebExecutor();+ const result = await executor.execute({+ model: "gpt-4",+ body: { messages: [{ role: "user", content: "hi" }] },+ stream: false,+ credentials: { apiKey: "" } as never,+ } as never);+ assert.equal(result.response.status, 400);+ const body = await result.response.json();+ assert.equal(body.error.code, "HTTP_400");+});diff --git a/tests/unit/t3-chat-web.test.ts b/tests/unit/t3-chat-web.test.tsindex a84ec71b50..c0d28ac49f 100644--- a/tests/unit/t3-chat-web.test.ts+++ b/tests/unit/t3-chat-web.test.ts@@ -50,13 +50,16 @@ test("execute returns 400 with empty credentials", async () => {assert.ok(body.error?.message, "Should have error message");});-test("execute returns 400 with cookies present but convexSessionId missing", async () => {+// #3007: credentials arrive as the single pasted string under `apiKey`+// (fallback `accessToken`) — the old `cookies`/`convexSessionId` object shape+// was never produced by the credential pipeline, so it must be rejected.+test("execute returns 400 with legacy cookies/convexSessionId object shape (no apiKey)", async () => {const executor = new T3ChatWebExecutor();const result = await executor.execute({model: "gpt-4o",body: { messages: [{ role: "user", content: "hi" }] },stream: true,- credentials: { cookies: "some-cookie=value" },+ credentials: { cookies: "some-cookie=value", convexSessionId: "abc" },signal: AbortSignal.timeout(5000),});assert.equal(result.response.status, 400);@@ -64,13 +67,13 @@ test("execute returns 400 with cookies present but convexSessionId missing", asyassert.ok(body.error?.message?.length > 0, "Should have error message");});-test("execute returns 400 with convexSessionId present but cookies missing", async () => {+test("execute returns 400 with apiKey that has no convex-session-id", async () => {const executor = new T3ChatWebExecutor();const result = await executor.execute({model: "gpt-4o",body: { messages: [{ role: "user", content: "hi" }] },stream: true,- credentials: { convexSessionId: "session-abc-123" },+ credentials: { apiKey: "sessionToken=value; theme=dark" },signal: AbortSignal.timeout(5000),});assert.equal(result.response.status, 400);@@ -78,13 +81,13 @@ test("execute returns 400 with convexSessionId present but cookies missing", asyassert.ok(body.error?.message?.length > 0, "Should have error message");});-test("execute returns 400 with both fields as empty strings", async () => {+test("execute returns 400 with empty apiKey string", async () => {const executor = new T3ChatWebExecutor();const result = await executor.execute({model: "gpt-4o",body: { messages: [{ role: "user", content: "hi" }] },stream: true,- credentials: { cookies: "", convexSessionId: "" },+ credentials: { apiKey: "" },signal: AbortSignal.timeout(5000),});assert.equal(result.response.status, 400);@@ -98,18 +101,18 @@ test("testConnection returns false with empty credentials", async () => {assert.equal(result, false);});-test("testConnection returns false when convexSessionId is missing", async () => {+test("testConnection returns false when convex-session-id is missing from apiKey", async () => {const executor = new T3ChatWebExecutor();- const result = await executor.testConnection({ cookies: "some-cookie=value" });+ const result = await executor.testConnection({ apiKey: "some-cookie=value" });assert.equal(result, false);});// ─── API flow helpers ─────────────────────────────────────────────────────function makeValidCreds() {+ // The credential pipeline stores the single pasted string under `apiKey`.return {- cookies: "t3-auth=session-token-xyz; other=value",- convexSessionId: "convex-session-id-abc123",+ apiKey: "t3-auth=session-token-xyz; other=value; convex-session-id=convex-abc123",};}diff --git a/tests/unit/token-health-check.test.ts b/tests/unit/token-health-check.test.tsindex 8f7cb92fcd..cb0b912d42 100644--- a/tests/unit/token-health-check.test.ts+++ b/tests/unit/token-health-check.test.ts@@ -398,3 +398,74 @@ test("checkConnection skips interval refresh when token expiry is known and stil});});++test("checkConnection skips providers listed in OMNIROUTE_HEALTHCHECK_SKIP_PROVIDERS (#kimi-15)", async () => {+ await resetStorage();++ const providerId = "custom-oauth-skip-list";+ const refreshRequests: string[] = [];+ const prevSkip = process.env.OMNIROUTE_HEALTHCHECK_SKIP_PROVIDERS;++ await withHttpServer(+ (req, res) => {+ let body = "";+ req.setEncoding("utf8");+ req.on("data", (chunk) => {+ body += chunk;+ });+ req.on("end", () => {+ refreshRequests.push(body);+ res.writeHead(200, { "Content-Type": "application/json" });+ res.end(+ JSON.stringify({+ access_token: "should-not-be-fetched",+ refresh_token: "should-not-be-fetched",+ expires_in: 3600,+ })+ );+ });+ },+ async (tokenServer) => {+ await withPatchedProvider(+ providerId,+ {+ tokenUrl: `${tokenServer.url}/token`,+ clientId: "skip-client-id",+ clientSecret: "skip-client-secret",+ },+ async () => {+ const connection = await providersDb.createProviderConnection({+ provider: providerId,+ authType: "oauth",+ name: "Skip-list Account",+ email: "[email protected]",+ accessToken: "stale-access-token",+ refreshToken: "refresh-token-skip",+ isActive: true,+ });++ // The connection is due for refresh (no known expiry, never checked).+ // With the provider listed, the proactive sweep must skip it entirely —+ // NO refresh request is made.+ process.env.OMNIROUTE_HEALTHCHECK_SKIP_PROVIDERS = `foo, ${providerId} ,bar`;+ await tokenHealthCheck.checkConnection(connection);+ assert.equal(+ refreshRequests.length,+ 0,+ "listed provider must NOT trigger a proactive refresh"+ );++ // Control: with the provider no longer listed, the same due connection+ // IS refreshed — proving the skip (not token freshness) gated it.+ process.env.OMNIROUTE_HEALTHCHECK_SKIP_PROVIDERS = "some-other-provider";+ const stillStale = await providersDb.getProviderConnectionById((connection as any).id);+ await tokenHealthCheck.checkConnection(stillStale);+ assert.equal(refreshRequests.length, 1, "non-listed provider must refresh");+ }+ );+ }+ );++ if (prevSkip === undefined) delete process.env.OMNIROUTE_HEALTHCHECK_SKIP_PROVIDERS;+ else process.env.OMNIROUTE_HEALTHCHECK_SKIP_PROVIDERS = prevSkip;+});diff --git a/tests/unit/tool-latency-tracker.test.ts b/tests/unit/tool-latency-tracker.test.tsnew file mode 100644index 0000000000..5c0378e565--- /dev/null+++ b/tests/unit/tool-latency-tracker.test.ts@@ -0,0 +1,61 @@+/**+ * #3173 — cross-request tool latency metrics.+ *+ * toolLatencyTracker aggregates per-provider TTFT/gap after tool calls;+ * sessionManager persists a one-shot tool-finish timestamp so the follow-up+ * request (Request 2) can measure cross-request TTFT.+ */+import test from "node:test";+import assert from "node:assert/strict";++const {+ recordToolLatency,+ getToolLatencyByProvider,+ recordToolTtft,+ resetToolLatency,+} = await import("../../open-sse/services/toolLatencyTracker.ts");+const { markToolFinish, consumeToolFinishTime } = await import(+ "../../open-sse/services/sessionManager.ts"+);++test("recordToolLatency averages TTFT/gap per provider and counts requests", () => {+ resetToolLatency();+ recordToolLatency("openai", 100, 40);+ recordToolLatency("openai", 300, 60);+ recordToolLatency("anthropic", 200, null);++ const m = getToolLatencyByProvider();+ assert.equal(m.openai.avgTtftAfterToolMs, 200); // (100+300)/2+ assert.equal(m.openai.avgGapAfterToolMs, 50); // (40+60)/2+ assert.equal(m.openai.measurementCount, 2);+ assert.equal(m.anthropic.avgTtftAfterToolMs, 200);+ assert.equal(m.anthropic.avgGapAfterToolMs, 0); // no gap samples+ assert.equal(m.anthropic.measurementCount, 1);+});++test("recordToolLatency ignores null/negative samples but still counts the request", () => {+ resetToolLatency();+ recordToolLatency("glm", null, null);+ recordToolLatency("glm", -5, -5);+ const m = getToolLatencyByProvider();+ assert.equal(m.glm.measurementCount, 2);+ assert.equal(m.glm.avgTtftAfterToolMs, 0);+ assert.equal(m.glm.avgGapAfterToolMs, 0);+});++test("recordToolTtft accumulates and resetToolLatency clears", () => {+ resetToolLatency();+ recordToolTtft("codex", 120);+ recordToolTtft("codex", 80);+ assert.equal(getToolLatencyByProvider().codex.avgTtftAfterToolMs, 100);+ resetToolLatency();+ assert.deepEqual(getToolLatencyByProvider(), {});+});++test("markToolFinish/consumeToolFinishTime is a one-shot per session", () => {+ // null session is a no-op / null+ markToolFinish(null);+ assert.equal(consumeToolFinishTime(null), null);+ // unknown session (never touched) → null+ assert.equal(consumeToolFinishTime("sess-never-seen-xyz"), null);+});diff --git a/tests/unit/translator-openai-responses-req.test.ts b/tests/unit/translator-openai-responses-req.test.tsindex 6ac89dbeb3..642acf522a 100644--- a/tests/unit/translator-openai-responses-req.test.ts+++ b/tests/unit/translator-openai-responses-req.test.ts@@ -356,6 +356,37 @@ test("Responses round-trip preserves store and previous_response_id when opt-inassert.equal((result as any).instructions, "Rules");});+test("Chat -> Responses converts assistant image_url history parts to output_text", () => {+ const result = openaiToOpenAIResponsesRequest(+ "gpt-4o",+ {+ messages: [+ {+ role: "assistant",+ content: [+ { type: "text", text: "I inspected the screenshot." },+ { type: "image_url", image_url: { url: "https://example.com/scope.png" } },+ ],+ },+ ],+ },+ true,+ null+ );++ assert.deepEqual((result as any).input, [+ {+ type: "message",+ role: "assistant",+ content: [+ { type: "output_text", text: "I inspected the screenshot." },+ { type: "output_text", text: "[Image: https://example.com/scope.png]" },+ ],+ },+ ]);+ assert.equal(JSON.stringify(result).includes('"image_url"'), false);+});+test("Chat -> Responses preserves prompt_cache_key and session affinity fields", () => {const result = openaiToOpenAIResponsesRequest("gpt-5.3-codex",diff --git a/tests/unit/web-tools-translation-2820.test.ts b/tests/unit/web-tools-translation-2820.test.tsindex d8d152a3d7..20ee1a048c 100644--- a/tests/unit/web-tools-translation-2820.test.ts+++ b/tests/unit/web-tools-translation-2820.test.ts@@ -58,6 +58,70 @@ test("parseToolCallsFromText returns null toolCalls when there is no tool block"assert.equal(content, "just a normal answer");});+test("parseToolCallsFromText detects bare JSON tool calls when requested tools are present", () => {+ const text = '{"name":"get_weather","arguments":{"city":"Paris"}}';+ const { content, toolCalls } = parseToolCallsFromText(text, "call", TOOLS);++ assert.equal(content, "");+ assert.equal(toolCalls?.length, 1);+ assert.equal(toolCalls?.[0].function.name, "get_weather");+ assert.deepEqual(JSON.parse(toolCalls?.[0].function.arguments || "{}"), { city: "Paris" });+});++test("parseToolCallsFromText does not parse bare JSON without requested tools", () => {+ const text = '{"name":"get_weather","arguments":{"city":"Paris"}}';+ const { content, toolCalls } = parseToolCallsFromText(text);++ assert.equal(toolCalls, null);+ assert.equal(content, text);+});++test("parseToolCallsFromText tolerates Python-dict-ish bare tool JSON", () => {+ const text = "{'command': 'get_weather', 'arguments': {'city': 'Paris', 'units': 'metric', 'fresh': True}}";+ const { toolCalls } = parseToolCallsFromText(text, "call", TOOLS);++ assert.equal(toolCalls?.length, 1);+ assert.equal(toolCalls?.[0].function.name, "get_weather");+ assert.deepEqual(JSON.parse(toolCalls?.[0].function.arguments || "{}"), {+ city: "Paris",+ units: "metric",+ fresh: true,+ });+});++test("parseToolCallsFromText escapes double quotes inside single-quoted strings", () => {+ const text = "{'command': 'get_weather', 'arguments': {'city': 'Paris \"City\"'}}";+ const { toolCalls } = parseToolCallsFromText(text, "call", TOOLS);++ assert.equal(toolCalls?.length, 1);+ assert.deepEqual(JSON.parse(toolCalls?.[0].function.arguments || "{}"), { city: 'Paris "City"' });+});++test("parseToolCallsFromText fuzzy-matches emitted tool names to requested tools", () => {+ const text = '{"name":"getWeather","arguments":{"city":"Paris"}}';+ const { toolCalls } = parseToolCallsFromText(text, "call", TOOLS);++ assert.equal(toolCalls?.length, 1);+ assert.equal(toolCalls?.[0].function.name, "get_weather");+});++test("parseToolCallsFromText strips bare JSON while preserving surrounding text", () => {+ const text = 'I will check now.\n{"name":"get_weather","arguments":"{\\"city\\":\\"Paris\\"}"}\nDone.';+ const { content, toolCalls } = parseToolCallsFromText(text, "call", TOOLS);++ assert.equal(toolCalls?.length, 1);+ assert.deepEqual(JSON.parse(toolCalls?.[0].function.arguments || "{}"), { city: "Paris" });+ assert.equal(content, "I will check now.\nDone.");+});++test("parseToolCallsFromText ignores bare JSON whose tool is not requested", () => {+ const text = '{"name":"delete_everything","arguments":{"force":true}}';+ const { content, toolCalls } = parseToolCallsFromText(text, "call", TOOLS);++ assert.equal(toolCalls, null);+ assert.equal(content, text);+});+test("parseToolCallsFromText parses multiple tool calls", () => {const text ='<tool>{"name": "a", "arguments": {"x": 1}}</tool>\n<tool>{"name": "b", "arguments": {}}</tool>';