Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

Merge branch 'release/v3.8.0' into feat/combo-model-metadata-catalog

diegosouzapw0ffbbd631e86
diff --cc CHANGELOG.md
index bb34a7aef6,17c9ec1261..0ce5714d4c
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -2,6 -2,185 +2,184 @@@
## [Unreleased]
+ ### ✨ New Features
+
+ - **feat(resilience):** add model cooldowns dashboard card with real-time list, individual/bulk re-enable, and auto-refresh (#2146 — thanks @rafacpti23)
+ - **feat(debug):** configurable chat log truncation limits via environment variables (`CHAT_LOG_TEXT_LIMIT`, `CHAT_LOG_ARRAY_TAIL_ITEMS`, `CHAT_LOG_MAX_DEPTH`, `CHAT_LOG_MAX_OBJECT_KEYS`) and `CHAT_DEBUG_FILE` mode for untruncated JSON payloads (#2156 — thanks @bypanghu)
+
+ ### 🐛 Bug Fixes
+
+ - **fix(kiro):** synthesize minimal tools schema when `body.tools` is omitted but message history contains `tool_calls`, preventing 400 errors from Claude Code and OpenCode (#2149 — thanks @Gioxaa)
+ - **fix(kiro):** avoid treating high-traffic 429s as quota exhaustion — use `classify429FromError` to prevent premature account deactivation (#2153 — thanks @Gioxaa)
+ - **fix(responses):** propagate `include` array (e.g. `reasoning.encrypted_content`) during Chat→Responses API translation, fixing broken thinking panel in Codex/OpenCode (#2154 — thanks @Gioxaa)
+ - **fix(responses):** emit reasoning summary as `delta.reasoning_content` (flat) instead of `delta.reasoning.summary` (nested) for Chat Completions client compatibility (#2159 — thanks @Gioxaa)
+ - **fix(cloudflare):** add state file write serialization lock to prevent race conditions in `cloudflaredTunnel.ts` (#2156 — thanks @bypanghu)
+
+ ### 🔧 Improvements
+
+ - **refactor(catalog):** remove 11 `.ts` extension imports, eliminate all `as any` casts, add `CustomModelEntry` interface and `ComboModelStep` type predicate, normalize alias resolution with `resolveCanonicalProviderId()` (#2152 — thanks @herjarsa)
+ - **chore(models):** tidy up Alibaba Coding Plan base URL, reorganize Cursor model list by family, fix `gpt-4o` model ID, update OpenCode Zen model (#2150 — thanks @backryun)
+ - **chore(deps):** move `gray-matter` from devDependencies to dependencies (runtime requirement) (#2156 — thanks @bypanghu)
+
+ ## [3.8.0] — 2026-05-06
+
+ ### ✨ New Features
+
+ - **feat(antigravity):** integrate Antigravity provider with dynamic `maxOutputTokens` calculation, identity fingerprinting overhaul, and Cloud Code envelope payload sanitization (#2055, #2063)
+ - **feat(gemini-cli):** add custom projectId support for Gemini CLI transport (UI, DB, executor) (#1991)
+ - **feat(providers):** add KIE media provider support with dynamic polling, text models, and expanded video models catalog
+ - **feat(providers):** add Z.AI provider support with GLM quota handling and new quota labels
+ - **feat(providers):** add 9 new free AI providers — LLM7, Lepton, Kluster, UncloseAI, BazaarLink, Completions, Enally, FreeTheAi (#2096)
+ - **feat(providers):** batch delete provider connections via checkbox multi-select (#2094)
+ - **feat(cursor):** full OpenAI parity — tool calls, streaming, and session management (#2082)
+ - **feat(cli):** comprehensive CLI enhancement suite with 20+ new commands including `omniroute providers`, `omniroute combos`, `omniroute doctor` (#2074)
+ - **feat(cli):** add modular CLI setup and provider management commands (#2046)
+ - **feat(mcp):** add DeepSeek quota and limit monitoring feature (#2089)
+ - **feat(circuit-breaker):** classify 429 errors and apply per-kind cooldowns (#2116)
+ - **feat(multi):** manifest-aware tier routing — W1-W4 complete (#2014)
+ - **feat(combos):** add reset-aware routing strategy for quota-based providers
+ - **feat(combo):** add context_length input field to combo edit form (#2047)
+ - **feat(chat):** dynamic tool limit detection with proactive truncation (#2061)
+ - **feat(sse):** refresh Claude OAuth wire image to claude-cli/2.1.131 (#2011)
+ - **feat(github):** add `targetFormat: openai-responses` to all GitHub models (#2122)
+ - **feat(api):** allow configuration via API calls — open management routes to Bearer keys with manage scope (#2103)
+ - **feat(api):** update API bridge proxy timeout to 600,000ms (#2019)
+ - **feat(usage):** add service tier breakdown, codex fast service tier analytics, and account for fast tier
+ - **feat(chat):** add `STREAM_READINESS_TIMEOUT_MS` and integrate into chat handling
+ - **feat(combo):** add `fallbackDelayMs` to combo configuration and related settings
+ - **feat(chat):** enhance error handling for semaphore capacity with fallback logic
+ - **feat(qdrant):** embedding model discovery (#2086)
+ - **feat(auth):** per-session sticky routing for Codex (#1887)
+ - **feat(inworld):** enhance Inworld TTS support (#2123)
+ - **feat(kiro):** headless auth via kiro-cli SQLite, image support, tool overflow handling, and model list sync (#2129 — thanks @christlau)
+ - **feat(auto):** zero-config auto-routing with `auto/` prefix — dynamic virtual combo from connected providers with 6 variant profiles (coding, fast, cheap, offline, smart, lkgp), analytics tab, and settings UI (#2131 — thanks @oyi77)
+ - **feat(resilience):** `useUpstream429BreakerHints` toggle — per-provider default policy for upstream 429 hint trust at the circuit-breaker cooldown layer with tri-state PATCH semantics (#2133 — thanks @eleata)
+ - **feat(mitm):** dynamic Linux certificate path detection for multi-distro MITM cert trust (Debian, Arch/CachyOS, Fedora/RHEL, openSUSE) with NSS browser database injection (#2134 — thanks @flyingmongoose)
+
+ ### 🐛 Bug Fixes
+
+ - **fix(pricing):** make `getPricingForModel` fully case-insensitive to ensure custom prices correctly reflect in new incoming requests cost calculations
+ - **fix(gemini):** prevent `functionDeclarations` from being dropped by the sanitizer when `googleSearch` tool is present (#2077)
+ - **fix(pollinations):** add `jsonMode: true` flag in the request transformation to enforce correct JSON structure from Pollinations API (#2109)
+ - **fix(docker):** update Dockerfile to copy `/docs` directory during build ensuring API catalog availability at runtime (#2083)
+ - **fix(docker):** include OpenAPI spec in runtime image (#2007)
+ - **fix(providers):** strip OpenAI-specific fields in Kiro translator to prevent 400 errors (#2037)
+ - **fix(kiro):** normalize tool-use payloads to prevent 400 errors from agents (#2104)
+ - **fix(kiro):** merge adjacent user history turns after role normalization (#2105)
+ - **fix(ui):** resolve text contrast issues for zero-config warning banner in light mode (#2050)
+ - **fix(core):** inject global system prompt correctly into downstream chat completions pipeline (#2080)
+ - **fix(core):** restore Claude Code adaptive thinking defaults and resolve audio transcription CORS regression
+ - **fix(routing):** add missing v1beta rewrites to next.config to resolve 404 on Gemini models endpoint (#2102)
+ - **fix(routing):** fix bare GPT-5.5 routing for Codex-only installations (#2054)
+ - **fix(routing):** add fuzzy auto-combo routing for `auto/*` model prefix (#2010)
+ - **fix(cache):** optimize cache_control preservation logic and explicitly align tool schema with upstream Claude Code expectations
+ - **fix(db):** preserve legacy SQLite database path on Windows to prevent data loss (#1973)
+ - **fix(db):** reduce hot-path persistence overhead (#2039)
+ - **fix(db):** resolve migration conflict by renumbering overlapping migration entries (#2041)
+ - **fix(settings):** resolve model alias persistence double stringification preventing UI updates (#2018)
+ - **fix(routing):** dynamically filter bare model auto-resolution by active provider connections to prevent dead-routing (#2029)
+ - **fix(embeddings):** add Google Gemini embeddings compatibility via OpenAI-compatible endpoint mapping (#2006)
+ - **fix(sse):** prevent Claude OAuth multi-account correlation via metadata.user_id (#2053)
+ - **fix(sse):** prevent Claude Code identity cloak overrides and fix fallback resilience (#2053)
+ - **fix(sse):** classify hour quota errors as QUOTA_EXHAUSTED (#2119)
+ - **fix(sse):** fix CC-compatible streaming bridge (#2118)
+ - **fix(antigravity):** sanitize Claude Cloud Code payloads (#2090)
+ - **fix(antigravity):** add duplex half for streaming bodies
+ - **fix(antigravity):** align identity protocol and behavior with official AM
+ - **fix(chatgpt-web):** plumb proxy through to native tls-client (#2022, #2023)
+ - **fix(codex):** expose native model IDs in catalog (#2012)
+ - **fix(glm):** add dedicated coding transport (#2087)
+ - **fix(compression):** support Responses input and expand Spanish compression rules (#2028)
+ - **fix(catalog):** auto-calculate combo context_length from target model limits (#2030)
+ - **fix(api):** fix usage analytics and API key identity (#2008, #2092)
+ - **fix(api-key):** allow Unicode letters in API key name validation (#1996)
+ - **fix(auth):** allow bootstrap without password (#2048)
+ - **fix(proxy):** clean up proxy page redundancy and fix 1proxy sync empty body error (#2052)
+ - **fix(dashboard):** resolve Unknown plan display in Provider Limits
+ - **fix(usage):** add extensible CURRENCY_SYMBOLS mapping for deepseek currencies
+ - **fix(runtime):** harden timer handling and model pricing fallback
+ - **fix(i18n):** complete Simplified Chinese translations (#2115)
+ - **fix(mitm):** add Linux cert install and skip sudo password when root (#1999)
+ - **fix(mitm):** prevent stub from loading at runtime via bypass module
+ - **fix:** remove Anthropic-Beta header from non-Anthropic providers to fix identity contamination (#1989)
+ - **fix(cli):** resolve .env loading failure for global npm installations
+ - **fix(export):** exclude telemetry/usage-history tables from JSON config backups by default to prevent unbounded file growth (#2125)
+ - **fix(translator):** preserve `body.system` in openai→claude translator when Claude Code sends native Anthropic system array through /chat/completions — fixes v3.7.9 regression where system prompt was silently dropped, triggering Anthropic 429 (#2130)
+ - **fix(sanitizer):** preserve `reasoning_content` on assistant messages with `tool_calls` or `function_call` — fixes Kimi and other thinking-enabled providers returning 400 errors when reasoning_content was incorrectly stripped (#2140 — thanks @DavyMassoneto)
+ - **fix(catalog):** ensure individual (non-combo) models expose `context_length` via `getTokenLimit()` fallback chain — prevents OpenCode and other clients from falling back to conservative ~4000 token limit (#2136 — thanks @herjarsa)
+ - **fix(docker):** remove docs directory from `.dockerignore` so API catalog documentation is available at runtime inside containers (#2137, #2120 — thanks @hartmark)
+ - **fix(types):** systematic `any` type elimination across 8 core files — `antigravity.ts`, `accountFallback.ts`, `usage.ts`, `geminiHelper.ts`, `error.ts`, `apiKeys.ts`, `settings.ts`, `logger.ts` (#2137 — thanks @hartmark)
+ - **fix(providers):** remove duplicate `CLOUD_AGENT_PROVIDERS` declaration, move Kiro dash→dot Claude model aliases to `PROVIDER_MODEL_ALIASES`, and trim deprecated Kiro registry entries (#2141 — thanks @backryun)
+ - **fix:** Follow OpenAI specification, handle throttling in batch and fix UI (#2045)
+
+ ### 🔒 Security
+
+ - **fix(security):** remediate CodeQL vulnerabilities (ReDoS, cryptographic bias, stack trace exposure, and weak password hashing) (#216, #215, #211, #208, #206, #210)
+ - **fix(security):** remediate regex validation backtracking path in core compression cleanup (#1990)
+ - **fix(core):** harden input handling and stabilization for prompt compression edge cases
+
+ ### 📝 Documentation
+
+ - **docs:** add competitive marketing tables and SEO/AEO optimizations to README (#2091)
+ - **docs:** refresh providers, model catalogs, and docs for v3.8.0 (#2088)
+ - **docs:** update Claude MD and update GLM-CN max context to 200k (#2027)
+ - **docs(env):** add `GITLAB_DUO_OAUTH_CLIENT_ID` to `.env.example` (#2031)
+
+ ### 🧹 Chores & Maintenance
+
+ - **chore(providers):** prune redundant local provider icon assets in favor of `@lobehub/icons` web fonts (#1992)
+ - **chore(providers):** remove deprecated models (#2033)
+ - **deps:** bump `fast-uri` from 3.1.0 to 3.1.2 (#2078)
+ - **deps:** bump `hono` from 4.12.14 to 4.12.18 (#2079)
+ - **ci:** skip SonarCloud scan on main pushes to optimize CI time
+ - **test:** stabilize cooldown abort coverage case in integration testing
+
+ ### 🏆 v3.8.0 Community Contributors
+
+ Thank you to all **40 community contributors** who made v3.8.0 possible! 🎉
+
-| Contributor | PRs | Contributions |
-| :--------------------------------------------------------- | :-: | :------------------------------------------------------------ |
++| Contributor | PRs | Contributions |
++| :--------------------------------------------------------- | :-: | :------------------------------------------------------------------- |
+ | [@oyi77](https://github.com/oyi77) | 8 | #2010, #2014, #2041, #2052, #2061, #2074, #2091, #2094, #2096, #2131 |
-| [@backryun](https://github.com/backryun) | 6 | #1992, #2033, #2088, #2123, #2138, #2141 |
-| [@dhaern](https://github.com/dhaern) | 4 | #2028, #2039, #2087, #2090 |
-| [@Tentoxa](https://github.com/Tentoxa) | 2 | #2011, #2053 |
-| [@wauputr4](https://github.com/wauputr4) | 2 | #2009, #2046 |
-| [@payne0420](https://github.com/payne0420) | 1 | #2082 |
-| [@Tr0sT](https://github.com/Tr0sT) | 1 | #2012 |
-| [@AveryanAlex](https://github.com/AveryanAlex) | 1 | #2008 |
-| [@nickwizard](https://github.com/nickwizard) | 1 | #1991 |
-| [@rodrigogbbr-stack](https://github.com/rodrigogbbr-stack) | 1 | #1996 |
-| [@NekoMonci12](https://github.com/NekoMonci12) | 1 | #1999 |
-| [@congvc-dev](https://github.com/congvc-dev) | 1 | #2004 |
-| [@tatsster](https://github.com/tatsster) | 1 | #2007 |
-| [@xssdem](https://github.com/xssdem) | 1 | #2023 |
-| [@bypanghu](https://github.com/bypanghu) | 1 | #2027 |
-| [@herjarsa](https://github.com/herjarsa) | 2 | #2030, #2136 |
-| [@wucm667](https://github.com/wucm667) | 1 | #2031 |
-| [@hartmark](https://github.com/hartmark) | 2 | #2045, #2137 |
-| [@ddarkr](https://github.com/ddarkr) | 1 | #2047 |
-| [@tces1](https://github.com/tces1) | 1 | #2048 |
-| [@guanbear](https://github.com/guanbear) | 1 | #2054 |
-| [@Gi99lin](https://github.com/Gi99lin) | 1 | #2055 |
-| [@ivan-mezentsev](https://github.com/ivan-mezentsev) | 1 | #2063 |
-| [@JxnLexn](https://github.com/JxnLexn) | 1 | #2019 |
-| [@yoviarpauzi](https://github.com/yoviarpauzi) | 1 | #2092 |
-| [@rafacpti23](https://github.com/rafacpti23) | 1 | #2086 |
-| [@gleber](https://github.com/gleber) | 1 | #2103 |
-| [@rilham97](https://github.com/rilham97) | 1 | #2104 |
-| [@Gioxaa](https://github.com/Gioxaa) | 1 | #2105 |
-| [@boa-z](https://github.com/boa-z) | 1 | #2115 |
-| [@eleata](https://github.com/eleata) | 2 | #2116, #2133 |
-| [@rdself](https://github.com/rdself) | 1 | #2118 |
-| [@clousky2020](https://github.com/clousky2020) | 1 | #2119 |
-| [@abhinavjnu](https://github.com/abhinavjnu) | 1 | #2122 |
-| [@HoaPham98](https://github.com/HoaPham98) | 1 | #2089 |
-| [@christlau](https://github.com/christlau) | 1 | #2129 |
-| [@flyingmongoose](https://github.com/flyingmongoose) | 1 | #2134 |
-| [@05dunski](https://github.com/05dunski) | 1 | #1978 (cherry-picked) |
-| [@DavyMassoneto](https://github.com/DavyMassoneto) | 1 | #2140 |
-
++| [@backryun](https://github.com/backryun) | 6 | #1992, #2033, #2088, #2123, #2138, #2141 |
++| [@dhaern](https://github.com/dhaern) | 4 | #2028, #2039, #2087, #2090 |
++| [@Tentoxa](https://github.com/Tentoxa) | 2 | #2011, #2053 |
++| [@wauputr4](https://github.com/wauputr4) | 2 | #2009, #2046 |
++| [@payne0420](https://github.com/payne0420) | 1 | #2082 |
++| [@Tr0sT](https://github.com/Tr0sT) | 1 | #2012 |
++| [@AveryanAlex](https://github.com/AveryanAlex) | 1 | #2008 |
++| [@nickwizard](https://github.com/nickwizard) | 1 | #1991 |
++| [@rodrigogbbr-stack](https://github.com/rodrigogbbr-stack) | 1 | #1996 |
++| [@NekoMonci12](https://github.com/NekoMonci12) | 1 | #1999 |
++| [@congvc-dev](https://github.com/congvc-dev) | 1 | #2004 |
++| [@tatsster](https://github.com/tatsster) | 1 | #2007 |
++| [@xssdem](https://github.com/xssdem) | 1 | #2023 |
++| [@bypanghu](https://github.com/bypanghu) | 1 | #2027 |
++| [@herjarsa](https://github.com/herjarsa) | 2 | #2030, #2136 |
++| [@wucm667](https://github.com/wucm667) | 1 | #2031 |
++| [@hartmark](https://github.com/hartmark) | 2 | #2045, #2137 |
++| [@ddarkr](https://github.com/ddarkr) | 1 | #2047 |
++| [@tces1](https://github.com/tces1) | 1 | #2048 |
++| [@guanbear](https://github.com/guanbear) | 1 | #2054 |
++| [@Gi99lin](https://github.com/Gi99lin) | 1 | #2055 |
++| [@ivan-mezentsev](https://github.com/ivan-mezentsev) | 1 | #2063 |
++| [@JxnLexn](https://github.com/JxnLexn) | 1 | #2019 |
++| [@yoviarpauzi](https://github.com/yoviarpauzi) | 1 | #2092 |
++| [@rafacpti23](https://github.com/rafacpti23) | 1 | #2086 |
++| [@gleber](https://github.com/gleber) | 1 | #2103 |
++| [@rilham97](https://github.com/rilham97) | 1 | #2104 |
++| [@Gioxaa](https://github.com/Gioxaa) | 1 | #2105 |
++| [@boa-z](https://github.com/boa-z) | 1 | #2115 |
++| [@eleata](https://github.com/eleata) | 2 | #2116, #2133 |
++| [@rdself](https://github.com/rdself) | 1 | #2118 |
++| [@clousky2020](https://github.com/clousky2020) | 1 | #2119 |
++| [@abhinavjnu](https://github.com/abhinavjnu) | 1 | #2122 |
++| [@HoaPham98](https://github.com/HoaPham98) | 1 | #2089 |
++| [@christlau](https://github.com/christlau) | 1 | #2129 |
++| [@flyingmongoose](https://github.com/flyingmongoose) | 1 | #2134 |
++| [@05dunski](https://github.com/05dunski) | 1 | #1978 (cherry-picked) |
++| [@DavyMassoneto](https://github.com/DavyMassoneto) | 1 | #2140 |
+
## [3.7.9] — 2026-05-03
### ✨ New Features
diff --cc open-sse/config/providerRegistry.ts
index 33efd7cf3c,8d55e95c57..7853ed71de
--- a/open-sse/config/providerRegistry.ts
+++ b/open-sse/config/providerRegistry.ts
@@@ -128,13 -130,21 +130,26 @@@ const KIMI_CODING_SHARED =
executor: "default",
baseUrl: "https://api.kimi.com/coding/v1/messages",
authHeader: "x-api-key",
+ // Kimi K2.6 native context per Moonshot platform docs and cross-provider
+ // catalog (openrouter, moonshot, ali, deepinfra, etc. all advertise 262144).
+ // Without this, contextManager.ts:getTokenLimit falls back to
+ // DEFAULT_LIMITS.default = 128000 because the Kimi Code OAuth product is
+ // not synced via models.dev. The under-reported value cascades into
+ // /v1/models advertised context_length=128000 and downstream client
+ // assumptions about prompt budget (e.g. Capy computing
+ // prompt_cap = context_length - request.max_tokens).
+ defaultContextLength: 262144,
headers: {
"Anthropic-Version": ANTHROPIC_VERSION_HEADER,
- "Anthropic-Beta": ANTHROPIC_BETA_API_KEY,
},
models: [
- { id: "kimi-k2.6", name: "Kimi K2.6" },
- { id: "kimi-k2.6-thinking", name: "Kimi K2.6 Thinking" },
- { id: "kimi-k2.6", name: "Kimi K2.6", contextLength: 262144, maxOutputTokens: 262144 },
- { id: "kimi-k2.6-thinking", name: "Kimi K2.6 Thinking", contextLength: 262144, maxOutputTokens: 262144 },
++ { id: "kimi-k2.6", name: "Kimi K2.6", contextLength: 262144, maxOutputTokens: 262144 },
++ {
++ id: "kimi-k2.6-thinking",
++ name: "Kimi K2.6 Thinking",
++ contextLength: 262144,
++ maxOutputTokens: 262144,
++ },
] as RegistryModel[],
} as const;
@@@ -229,7 -281,12 +286,12 @@@ const CHAT_OPENAI_COMPAT_MODELS: Record
codestral: buildModels(["codestral-2405", "codestral-latest"]),
upstage: buildModels(["solar-pro3", "solar-mini"]),
maritalk: buildModels(["sabia-4", "sabia-3.1", "sabiazinho-4", "sabiazinho-3"]),
- "xiaomi-mimo": buildModels(["mimo-v2.5-pro", "mimo-v2.5", "mimo-v2-omni", "mimo-v2-flash"]),
+ "xiaomi-mimo": [
+ { id: "mimo-v2.5-pro", name: "MiMo-V2.5-Pro", contextLength: 1048576, maxOutputTokens: 131072 },
- { id: "mimo-v2.5", name: "MiMo-V2.5", contextLength: 1048576, maxOutputTokens: 131072 },
- { id: "mimo-v2-omni", name: "MiMo-V2-Omni", contextLength: 262144, maxOutputTokens: 131072 },
- { id: "mimo-v2-flash", name: "MiMo-V2-Flash", contextLength: 262144, maxOutputTokens: 65536 },
++ { id: "mimo-v2.5", name: "MiMo-V2.5", contextLength: 1048576, maxOutputTokens: 131072 },
++ { id: "mimo-v2-omni", name: "MiMo-V2-Omni", contextLength: 262144, maxOutputTokens: 131072 },
++ { id: "mimo-v2-flash", name: "MiMo-V2-Flash", contextLength: 262144, maxOutputTokens: 65536 },
+ ],
"inference-net": buildModels([
"meta-llama/Llama-3.3-70B-Instruct",
"deepseek-ai/DeepSeek-R1",
@@@ -306,11 -384,12 +389,48 @@@ export const REGISTRY: Record<string, R
tokenUrl: "https://console.anthropic.com/v1/oauth/token",
},
models: [
- { id: "claude-opus-4-7", name: "Claude Opus 4.7", supportsXHighEffort: true },
- { id: "claude-opus-4-6", name: "Claude Opus 4.6", supportsXHighEffort: false },
- { id: "claude-sonnet-4-6", name: "Claude 4.6 Sonnet", supportsXHighEffort: false },
- { id: "claude-sonnet-4-5-20250929", name: "Claude 4.5 Sonnet", supportsXHighEffort: false },
- { id: "claude-haiku-4-5-20251001", name: "Claude 4.5 Haiku", supportsXHighEffort: false },
- { id: "claude-opus-4-7", name: "Claude Opus 4.7", supportsXHighEffort: true, contextLength: 1000000, maxOutputTokens: 128000 },
- { id: "claude-opus-4-6", name: "Claude Opus 4.6", supportsXHighEffort: false, contextLength: 1000000, maxOutputTokens: 128000 },
- { id: "claude-opus-4-5-20251101", name: "Claude Opus 4.5", supportsXHighEffort: false, contextLength: 200000, maxOutputTokens: 64000 },
- { id: "claude-sonnet-4-6", name: "Claude 4.6 Sonnet", supportsXHighEffort: false, contextLength: 200000, maxOutputTokens: 64000 },
- { id: "claude-sonnet-4-5-20250929", name: "Claude 4.5 Sonnet", supportsXHighEffort: false, contextLength: 200000, maxOutputTokens: 64000 },
- { id: "claude-haiku-4-5-20251001", name: "Claude 4.5 Haiku", supportsXHighEffort: false, contextLength: 200000, maxOutputTokens: 64000 },
++ {
++ id: "claude-opus-4-7",
++ name: "Claude Opus 4.7",
++ supportsXHighEffort: true,
++ contextLength: 1000000,
++ maxOutputTokens: 128000,
++ },
++ {
++ id: "claude-opus-4-6",
++ name: "Claude Opus 4.6",
++ supportsXHighEffort: false,
++ contextLength: 1000000,
++ maxOutputTokens: 128000,
++ },
++ {
++ id: "claude-opus-4-5-20251101",
++ name: "Claude Opus 4.5",
++ supportsXHighEffort: false,
++ contextLength: 200000,
++ maxOutputTokens: 64000,
++ },
++ {
++ id: "claude-sonnet-4-6",
++ name: "Claude 4.6 Sonnet",
++ supportsXHighEffort: false,
++ contextLength: 200000,
++ maxOutputTokens: 64000,
++ },
++ {
++ id: "claude-sonnet-4-5-20250929",
++ name: "Claude 4.5 Sonnet",
++ supportsXHighEffort: false,
++ contextLength: 200000,
++ maxOutputTokens: 64000,
++ },
++ {
++ id: "claude-haiku-4-5-20251001",
++ name: "Claude 4.5 Haiku",
++ supportsXHighEffort: false,
++ contextLength: 200000,
++ maxOutputTokens: 64000,
++ },
],
},
@@@ -383,10 -462,15 +503,45 @@@
tokenUrl: "https://auth.openai.com/oauth/token",
},
models: [
- { id: "gpt-5.5-xhigh", name: "GPT 5.5 (xHigh)", ...GPT_5_5_CODEX_CAPABILITIES },
- { id: "gpt-5.5-high", name: "GPT 5.5 (High)", ...GPT_5_5_CODEX_CAPABILITIES },
- { id: "gpt-5.5-medium", name: "GPT 5.5 (Medium)", ...GPT_5_5_CODEX_CAPABILITIES },
- { id: "gpt-5.5-low", name: "GPT 5.5 (Low)", ...GPT_5_5_CODEX_CAPABILITIES },
+ // gpt-5.5 codex OAuth backend caps context at 400K (not the public-API
+ // 1.05M). Public refs : openai/codex#19208, #19319, #19464 ;
+ // opencode#24171. max_output_tokens is stripped server-side
+ // (litellm#21193, codex#4138) so 128K is informational only.
- { id: "gpt-5.5", name: "GPT 5.5", ...GPT_5_5_CODEX_CAPABILITIES, contextLength: 400000, maxOutputTokens: 128000 },
- { id: "gpt-5.5-xhigh", name: "GPT 5.5 (xHigh)", ...GPT_5_5_CODEX_CAPABILITIES, contextLength: 400000, maxOutputTokens: 128000 },
- { id: "gpt-5.5-high", name: "GPT 5.5 (High)", ...GPT_5_5_CODEX_CAPABILITIES, contextLength: 400000, maxOutputTokens: 128000 },
- { id: "gpt-5.5-medium", name: "GPT 5.5 (Medium)", ...GPT_5_5_CODEX_CAPABILITIES, contextLength: 400000, maxOutputTokens: 128000 },
- { id: "gpt-5.5-low", name: "GPT 5.5 (Low)", ...GPT_5_5_CODEX_CAPABILITIES, contextLength: 400000, maxOutputTokens: 128000 },
++ {
++ id: "gpt-5.5",
++ name: "GPT 5.5",
++ ...GPT_5_5_CODEX_CAPABILITIES,
++ contextLength: 400000,
++ maxOutputTokens: 128000,
++ },
++ {
++ id: "gpt-5.5-xhigh",
++ name: "GPT 5.5 (xHigh)",
++ ...GPT_5_5_CODEX_CAPABILITIES,
++ contextLength: 400000,
++ maxOutputTokens: 128000,
++ },
++ {
++ id: "gpt-5.5-high",
++ name: "GPT 5.5 (High)",
++ ...GPT_5_5_CODEX_CAPABILITIES,
++ contextLength: 400000,
++ maxOutputTokens: 128000,
++ },
++ {
++ id: "gpt-5.5-medium",
++ name: "GPT 5.5 (Medium)",
++ ...GPT_5_5_CODEX_CAPABILITIES,
++ contextLength: 400000,
++ maxOutputTokens: 128000,
++ },
++ {
++ id: "gpt-5.5-low",
++ name: "GPT 5.5 (Low)",
++ ...GPT_5_5_CODEX_CAPABILITIES,
++ contextLength: 400000,
++ maxOutputTokens: 128000,
++ },
{ id: "gpt-5.4", name: "GPT 5.4", targetFormat: "openai-responses" },
{ id: "gpt-5.4-mini", name: "GPT 5.4 Mini", targetFormat: "openai-responses" },
{ id: "gpt-5.3-codex-spark", name: "GPT 5.3 Codex Spark" },
@@@ -494,16 -577,15 +648,51 @@@
{ id: "gpt-5.4-mini", name: "GPT-5.4 Mini", targetFormat: "openai-responses" },
{ id: "gpt-5.4", name: "GPT-5.4", targetFormat: "openai-responses" },
{ id: "gpt-5.5", name: "GPT-5.5", ...GPT_5_5_CODEX_CAPABILITIES },
- { id: "claude-haiku-4.5", name: "Claude Haiku 4.5" },
- { id: "claude-sonnet-4.5", name: "Claude Sonnet 4.5" },
- { id: "claude-sonnet-4.6", name: "Claude Sonnet 4.6" },
- { id: "claude-opus-4-5-20251101", name: "Claude Opus 4.5 (Full ID)" },
- { id: "claude-opus-4.6", name: "Claude Opus 4.6" },
- { id: "claude-opus-4.7", name: "Claude Opus 4.7" },
- { id: "gemini-3.1-pro-preview", name: "Gemini 3.1 Pro" },
- { id: "gemini-3-flash-preview", name: "Gemini 3 Flash" },
- { id: "grok-code-fast-1", name: "Grok Code Fast 1" },
- { id: "oswe-vscode-prime", name: "Raptor Mini" },
- { id: "claude-haiku-4.5", name: "Claude Haiku 4.5", targetFormat: "openai-responses", contextLength: 200000, maxOutputTokens: 64000 },
- { id: "claude-sonnet-4.5", name: "Claude Sonnet 4.5", targetFormat: "openai-responses", contextLength: 200000, maxOutputTokens: 64000 },
- { id: "claude-sonnet-4.6", name: "Claude Sonnet 4.6", targetFormat: "openai-responses", contextLength: 200000, maxOutputTokens: 64000 },
- { id: "claude-opus-4-5-20251101", name: "Claude Opus 4.5 (Full ID)", targetFormat: "openai-responses", contextLength: 200000, maxOutputTokens: 64000 },
- { id: "claude-opus-4.6", name: "Claude Opus 4.6", targetFormat: "openai-responses", contextLength: 1000000, maxOutputTokens: 128000 },
- { id: "claude-opus-4.7", name: "Claude Opus 4.7", targetFormat: "openai-responses", contextLength: 1000000, maxOutputTokens: 128000 },
++ {
++ id: "claude-haiku-4.5",
++ name: "Claude Haiku 4.5",
++ targetFormat: "openai-responses",
++ contextLength: 200000,
++ maxOutputTokens: 64000,
++ },
++ {
++ id: "claude-sonnet-4.5",
++ name: "Claude Sonnet 4.5",
++ targetFormat: "openai-responses",
++ contextLength: 200000,
++ maxOutputTokens: 64000,
++ },
++ {
++ id: "claude-sonnet-4.6",
++ name: "Claude Sonnet 4.6",
++ targetFormat: "openai-responses",
++ contextLength: 200000,
++ maxOutputTokens: 64000,
++ },
++ {
++ id: "claude-opus-4-5-20251101",
++ name: "Claude Opus 4.5 (Full ID)",
++ targetFormat: "openai-responses",
++ contextLength: 200000,
++ maxOutputTokens: 64000,
++ },
++ {
++ id: "claude-opus-4.6",
++ name: "Claude Opus 4.6",
++ targetFormat: "openai-responses",
++ contextLength: 1000000,
++ maxOutputTokens: 128000,
++ },
++ {
++ id: "claude-opus-4.7",
++ name: "Claude Opus 4.7",
++ targetFormat: "openai-responses",
++ contextLength: 1000000,
++ maxOutputTokens: 128000,
++ },
+ { id: "gemini-3.1-pro-preview", name: "Gemini 3.1 Pro", targetFormat: "openai-responses" },
+ { id: "gemini-3-flash-preview", name: "Gemini 3 Flash", targetFormat: "openai-responses" },
+ { id: "oswe-vscode-prime", name: "Raptor Mini", targetFormat: "openai-responses" },
//{ id: "?", name: "Goldeneye" },
],
},
@@@ -523,14 -605,18 +712,43 @@@
authUrl: "https://prod.us-east-1.auth.desktop.kiro.dev",
},
models: [
- { id: "claude-opus-4.7", name: "Claude Opus 4.7" },
- { id: "claude-opus-4.6", name: "Claude Opus 4.6" },
- { id: "claude-sonnet-4.6", name: "Claude Sonnet 4.6" },
- { id: "claude-sonnet-4.5", name: "Claude Sonnet 4.5" },
- { id: "claude-haiku-4.5", name: "Claude Haiku 4.5" },
- //{ id: "?", name: "DeepSeek V3.2" },
- //{ id: "?", name: "MiniMax M2.5" },
- //{ id: "?", name: "GLM-5" },
+ { id: "auto-kiro", name: "Auto (Kiro picks best model)" },
- { id: "claude-opus-4.7", name: "Claude Opus 4.7", contextLength: 1000000, maxOutputTokens: 128000 },
- { id: "claude-opus-4.6", name: "Claude Opus 4.6", contextLength: 1000000, maxOutputTokens: 128000 },
- { id: "claude-sonnet-4.6", name: "Claude Sonnet 4.6", contextLength: 200000, maxOutputTokens: 64000 },
++ {
++ id: "claude-opus-4.7",
++ name: "Claude Opus 4.7",
++ contextLength: 1000000,
++ maxOutputTokens: 128000,
++ },
++ {
++ id: "claude-opus-4.6",
++ name: "Claude Opus 4.6",
++ contextLength: 1000000,
++ maxOutputTokens: 128000,
++ },
++ {
++ id: "claude-sonnet-4.6",
++ name: "Claude Sonnet 4.6",
++ contextLength: 200000,
++ maxOutputTokens: 64000,
++ },
+ // models for kiro free tier
- { id: "claude-sonnet-4.5", name: "Claude Sonnet 4.5", contextLength: 200000, maxOutputTokens: 64000 },
- { id: "claude-haiku-4.5", name: "Claude Haiku 4.5", contextLength: 200000, maxOutputTokens: 64000 },
++ {
++ id: "claude-sonnet-4.5",
++ name: "Claude Sonnet 4.5",
++ contextLength: 200000,
++ maxOutputTokens: 64000,
++ },
++ {
++ id: "claude-haiku-4.5",
++ name: "Claude Haiku 4.5",
++ contextLength: 200000,
++ maxOutputTokens: 64000,
++ },
+ { id: "deepseek-3.2", name: "DeepSeek V3.2" },
+ { id: "minimax-m2.5", name: "MiniMax M2.5" },
+ { id: "minimax-m2.1", name: "MiniMax M2.1" },
+ { id: "glm-5", name: "GLM-5" },
+ { id: "qwen3-coder-next", name: "Qwen3 Coder Next" },
],
},
diff --cc scripts/scratch/check_usage.js
index 0000000000,15e6cab603..9360bab904
mode 000000,100644..100644
--- a/scripts/scratch/check_usage.js
+++ b/scripts/scratch/check_usage.js
@@@ -1,0 -1,34 +1,41 @@@
-import Database from 'better-sqlite3';
-import path from 'path';
-import os from 'os';
++import Database from "better-sqlite3";
++import path from "path";
++import os from "os";
+
-const SQLITE_FILE = path.join(process.cwd(), 'data', 'storage.sqlite');
++const SQLITE_FILE = path.join(process.cwd(), "data", "storage.sqlite");
+
-console.log('Checking database at:', SQLITE_FILE);
++console.log("Checking database at:", SQLITE_FILE);
+
+ const db = new Database(SQLITE_FILE, { readonly: true });
+
+ try {
- const rows = db.prepare(`
++ const rows = db
++ .prepare(
++ `
+ SELECT api_key_id, api_key_name, COUNT(*) as count, MAX(timestamp) as last_used
+ FROM usage_history
+ GROUP BY api_key_id, api_key_name
+ ORDER BY count DESC
- `).all();
++ `
++ )
++ .all();
+
- console.log('Top Usage Entries:');
- console.table(rows);
++ console.log("Top Usage Entries:");
++ console.table(rows);
+
- const keys = db.prepare(`
++ const keys = db
++ .prepare(
++ `
+ SELECT id, name, key_prefix, machine_id
+ FROM api_keys
- `).all();
-
- console.log('All API Keys:');
- console.table(keys);
++ `
++ )
++ .all();
+
++ console.log("All API Keys:");
++ console.table(keys);
+ } catch (err) {
- console.error('Error:', err.message);
++ console.error("Error:", err.message);
+ } finally {
- db.close();
++ db.close();
+ }
diff --cc src/app/api/v1/models/catalog.ts
index f77c668f1e,3d3f94cd77..5ffcfaf5f9
--- a/src/app/api/v1/models/catalog.ts
+++ b/src/app/api/v1/models/catalog.ts
@@@ -8,27 -8,37 +8,41 @@@ import
getProviderNodes,
getModelIsHidden,
} from "@/lib/localDb";
- import { getAllEmbeddingModels } from "@omniroute/open-sse/config/embeddingRegistry.ts";
- import { getAllImageModels } from "@omniroute/open-sse/config/imageRegistry.ts";
- import { getAllRerankModels } from "@omniroute/open-sse/config/rerankRegistry.ts";
- import { getAllAudioModels } from "@omniroute/open-sse/config/audioRegistry.ts";
- import { getAllModerationModels } from "@omniroute/open-sse/config/moderationRegistry.ts";
- import { getAllVideoModels } from "@omniroute/open-sse/config/videoRegistry.ts";
- import { getAllMusicModels } from "@omniroute/open-sse/config/musicRegistry.ts";
- import { REGISTRY } from "@omniroute/open-sse/config/providerRegistry.ts";
- import { resolveNestedComboTargets } from "@omniroute/open-sse/services/combo.ts";
+ import { getAllEmbeddingModels } from "@omniroute/open-sse/config/embeddingRegistry";
+ import { getAllImageModels } from "@omniroute/open-sse/config/imageRegistry";
+ import { getAllRerankModels } from "@omniroute/open-sse/config/rerankRegistry";
+ import { getAllAudioModels } from "@omniroute/open-sse/config/audioRegistry";
+ import { getAllModerationModels } from "@omniroute/open-sse/config/moderationRegistry";
+ import { getAllVideoModels } from "@omniroute/open-sse/config/videoRegistry";
+ import { getAllMusicModels } from "@omniroute/open-sse/config/musicRegistry";
+ import { REGISTRY } from "@omniroute/open-sse/config/providerRegistry";
+ import { CODEX_NATIVE_UNPREFIXED_MODELS } from "@omniroute/open-sse/services/model";
++import { resolveNestedComboTargets } from "@omniroute/open-sse/services/combo";
import { getAllSyncedAvailableModels } from "@/lib/db/models";
import { getCompatibleFallbackModels } from "@/lib/providers/managedAvailableModels";
import { hasEligibleConnectionForModel } from "@/domain/connectionModelRules";
import {
INTERNAL_PROXY_ERROR,
enrichCatalogModelEntry,
+ getCanonicalModelMetadata,
getCatalogDiagnosticsHeaders,
} from "@/lib/modelMetadataRegistry";
+import { getSyncedCapability } from "@/lib/modelsDevSync";
+import { getModelSpec } from "@/shared/constants/modelSpecs";
import { isAuthRequired, isDashboardSessionAuthenticated } from "@/shared/utils/apiAuth";
+ import { parseModel } from "@omniroute/open-sse/services/model";
+ import { getTokenLimit } from "@omniroute/open-sse/services/contextManager";
+ import type { ComboModelStep } from "@/lib/combos/steps";
+
+ interface CustomModelEntry {
+ id?: string;
+ name?: string;
+ source?: string;
+ apiFormat?: string;
+ supportedEndpoints?: string[];
+ inputTokenLimit?: number;
+ isHidden?: boolean;
+ }
const FALLBACK_ALIAS_TO_PROVIDER = {
ag: "antigravity",
@@@ -567,7 -327,31 +581,8 @@@ export async function getUnifiedModelsR
// Add combos first (they appear at the top) — only active ones
for (const combo of combos) {
if (combo.isActive === false || combo.isHidden === true) continue;
-
- // Calculate combo context length from its model targets.
- // OpenCode and other clients read context_length from the catalog; without it
- // they fall back to a conservative ~4000 token limit, causing truncation.
- const comboContextLength = Array.isArray(combo.models)
- ? combo.models
- .filter((step): step is ComboModelStep => step?.kind === "model" && Boolean(step.model))
- .map((step) => {
- const parsed = parseModel(step.model);
- const rawProvider = parsed.provider || step.providerId || "unknown";
- const provider = resolveCanonicalProviderId(rawProvider);
- const model = parsed.model || step.model;
- return getTokenLimit(provider, model);
- })
- .filter((limit): limit is number => typeof limit === "number" && limit > 0)
- .reduce((min, limit) => Math.min(min, limit), Infinity)
- : undefined;
-
- const effectiveContextLength =
- typeof combo.context_length === "number" && combo.context_length > 0
- ? combo.context_length
- : comboContextLength !== undefined && comboContextLength !== Infinity
- ? comboContextLength
- : undefined;
+ const comboMetadata = buildComboCatalogMetadata(combo, combos);
+
models.push({
id: combo.name,
object: "model",
diff --cc src/i18n/messages/bg.json
index bcb9fa6050,615b046d2f..12d911c36c
--- a/src/i18n/messages/bg.json
+++ b/src/i18n/messages/bg.json
@@@ -4607,5 -4650,12 +4650,12 @@@
"noProxyLogs": "No proxy logs yet. Configure proxies and make API calls to see them here.",
"noMatchingLogs": "No logs match the current filters.",
"tlsFingerprint": "Chrome 124 TLS Fingerprint"
+ },
+ "agentFeatures": {
+ "agentFeaturesContextLength": "Context length",
+ "agentFeaturesContextLengthPlaceholder": "e.g. 128000",
+ "agentFeaturesContextLengthHint": "Defines the context window for this combo in /v1/models.",
+ "agentFeaturesContextLengthErrorInteger": "Context length must be a valid integer",
+ "agentFeaturesContextLengthErrorRange": "Context length must be between 1000 and 2000000"
}
-}
+}
diff --cc src/i18n/messages/bn.json
index c7d76a36e7,f710c34764..cbb45ce673
--- a/src/i18n/messages/bn.json
+++ b/src/i18n/messages/bn.json
@@@ -4900,5 -4943,12 +4943,12 @@@
"noProxyLogs": "No proxy logs yet. Configure proxies and make API calls to see them here.",
"noMatchingLogs": "No logs match the current filters.",
"tlsFingerprint": "Chrome 124 TLS Fingerprint"
+ },
+ "agentFeatures": {
+ "agentFeaturesContextLength": "Context length",
+ "agentFeaturesContextLengthPlaceholder": "e.g. 128000",
+ "agentFeaturesContextLengthHint": "Defines the context window for this combo in /v1/models.",
+ "agentFeaturesContextLengthErrorInteger": "Context length must be a valid integer",
+ "agentFeaturesContextLengthErrorRange": "Context length must be between 1000 and 2000000"
}
-}
+}
diff --cc src/i18n/messages/cs.json
index 1253886043,7017c186e9..ea7664394c
--- a/src/i18n/messages/cs.json
+++ b/src/i18n/messages/cs.json
@@@ -4607,5 -4650,12 +4650,12 @@@
"noProxyLogs": "No proxy logs yet. Configure proxies and make API calls to see them here.",
"noMatchingLogs": "No logs match the current filters.",
"tlsFingerprint": "Chrome 124 TLS Fingerprint"
+ },
+ "agentFeatures": {
+ "agentFeaturesContextLength": "Context length",
+ "agentFeaturesContextLengthPlaceholder": "e.g. 128000",
+ "agentFeaturesContextLengthHint": "Defines the context window for this combo in /v1/models.",
+ "agentFeaturesContextLengthErrorInteger": "Context length must be a valid integer",
+ "agentFeaturesContextLengthErrorRange": "Context length must be between 1000 and 2000000"
}
-}
+}
diff --cc src/i18n/messages/da.json
index 5419e633db,5336c71495..1394d2f8c8
--- a/src/i18n/messages/da.json
+++ b/src/i18n/messages/da.json
@@@ -4607,5 -4650,12 +4650,12 @@@
"noProxyLogs": "No proxy logs yet. Configure proxies and make API calls to see them here.",
"noMatchingLogs": "No logs match the current filters.",
"tlsFingerprint": "Chrome 124 TLS Fingerprint"
+ },
+ "agentFeatures": {
+ "agentFeaturesContextLength": "Context length",
+ "agentFeaturesContextLengthPlaceholder": "e.g. 128000",
+ "agentFeaturesContextLengthHint": "Defines the context window for this combo in /v1/models.",
+ "agentFeaturesContextLengthErrorInteger": "Context length must be a valid integer",
+ "agentFeaturesContextLengthErrorRange": "Context length must be between 1000 and 2000000"
}
-}
+}
diff --cc src/i18n/messages/de.json
index 5daaaa212d,0639d215b7..5e0a11e72e
--- a/src/i18n/messages/de.json
+++ b/src/i18n/messages/de.json
@@@ -4607,5 -4666,12 +4666,12 @@@
"noProxyLogs": "No proxy logs yet. Configure proxies and make API calls to see them here.",
"noMatchingLogs": "No logs match the current filters.",
"tlsFingerprint": "Chrome 124 TLS Fingerprint"
+ },
+ "agentFeatures": {
+ "agentFeaturesContextLength": "Context length",
+ "agentFeaturesContextLengthPlaceholder": "e.g. 128000",
+ "agentFeaturesContextLengthHint": "Defines the context window for this combo in /v1/models.",
+ "agentFeaturesContextLengthErrorInteger": "Context length must be a valid integer",
+ "agentFeaturesContextLengthErrorRange": "Context length must be between 1000 and 2000000"
}
-}
+}
diff --cc src/i18n/messages/es.json
index 84ebe91b16,7ca0ac2d41..6acb1bf214
--- a/src/i18n/messages/es.json
+++ b/src/i18n/messages/es.json
@@@ -4607,5 -4650,12 +4650,12 @@@
"noProxyLogs": "No proxy logs yet. Configure proxies and make API calls to see them here.",
"noMatchingLogs": "No logs match the current filters.",
"tlsFingerprint": "Chrome 124 TLS Fingerprint"
+ },
+ "agentFeatures": {
+ "agentFeaturesContextLength": "Context length",
+ "agentFeaturesContextLengthPlaceholder": "e.g. 128000",
+ "agentFeaturesContextLengthHint": "Defines the context window for this combo in /v1/models.",
+ "agentFeaturesContextLengthErrorInteger": "Context length must be a valid integer",
+ "agentFeaturesContextLengthErrorRange": "Context length must be between 1000 and 2000000"
}
-}
+}
diff --cc src/i18n/messages/fa.json
index 3a15e48922,7360b369ea..1aae9ab357
--- a/src/i18n/messages/fa.json
+++ b/src/i18n/messages/fa.json
@@@ -4900,5 -4943,12 +4943,12 @@@
"noProxyLogs": "No proxy logs yet. Configure proxies and make API calls to see them here.",
"noMatchingLogs": "No logs match the current filters.",
"tlsFingerprint": "Chrome 124 TLS Fingerprint"
+ },
+ "agentFeatures": {
+ "agentFeaturesContextLength": "Context length",
+ "agentFeaturesContextLengthPlaceholder": "e.g. 128000",
+ "agentFeaturesContextLengthHint": "Defines the context window for this combo in /v1/models.",
+ "agentFeaturesContextLengthErrorInteger": "Context length must be a valid integer",
+ "agentFeaturesContextLengthErrorRange": "Context length must be between 1000 and 2000000"
}
-}
+}
diff --cc src/i18n/messages/fi.json
index af2b333bb2,4e75a03fbf..de451a629a
--- a/src/i18n/messages/fi.json
+++ b/src/i18n/messages/fi.json
@@@ -4607,5 -4650,12 +4650,12 @@@
"noProxyLogs": "No proxy logs yet. Configure proxies and make API calls to see them here.",
"noMatchingLogs": "No logs match the current filters.",
"tlsFingerprint": "Chrome 124 TLS Fingerprint"
+ },
+ "agentFeatures": {
+ "agentFeaturesContextLength": "Context length",
+ "agentFeaturesContextLengthPlaceholder": "e.g. 128000",
+ "agentFeaturesContextLengthHint": "Defines the context window for this combo in /v1/models.",
+ "agentFeaturesContextLengthErrorInteger": "Context length must be a valid integer",
+ "agentFeaturesContextLengthErrorRange": "Context length must be between 1000 and 2000000"
}
-}
+}
diff --cc src/i18n/messages/fr.json
index 652f2add5e,44326e348d..61f8cf673e
--- a/src/i18n/messages/fr.json
+++ b/src/i18n/messages/fr.json
@@@ -4607,5 -4650,12 +4650,12 @@@
"noProxyLogs": "No proxy logs yet. Configure proxies and make API calls to see them here.",
"noMatchingLogs": "No logs match the current filters.",
"tlsFingerprint": "Chrome 124 TLS Fingerprint"
+ },
+ "agentFeatures": {
+ "agentFeaturesContextLength": "Context length",
+ "agentFeaturesContextLengthPlaceholder": "e.g. 128000",
+ "agentFeaturesContextLengthHint": "Defines the context window for this combo in /v1/models.",
+ "agentFeaturesContextLengthErrorInteger": "Context length must be a valid integer",
+ "agentFeaturesContextLengthErrorRange": "Context length must be between 1000 and 2000000"
}
-}
+}
diff --cc src/i18n/messages/gu.json
index 1e8450a550,1204fe8a7f..6f6877fa45
--- a/src/i18n/messages/gu.json
+++ b/src/i18n/messages/gu.json
@@@ -4900,5 -4943,12 +4943,12 @@@
"noProxyLogs": "No proxy logs yet. Configure proxies and make API calls to see them here.",
"noMatchingLogs": "No logs match the current filters.",
"tlsFingerprint": "Chrome 124 TLS Fingerprint"
+ },
+ "agentFeatures": {
+ "agentFeaturesContextLength": "Context length",
+ "agentFeaturesContextLengthPlaceholder": "e.g. 128000",
+ "agentFeaturesContextLengthHint": "Defines the context window for this combo in /v1/models.",
+ "agentFeaturesContextLengthErrorInteger": "Context length must be a valid integer",
+ "agentFeaturesContextLengthErrorRange": "Context length must be between 1000 and 2000000"
}
-}
+}
diff --cc src/i18n/messages/he.json
index a91b77250b,e733ca551a..50fe996e44
--- a/src/i18n/messages/he.json
+++ b/src/i18n/messages/he.json
@@@ -4607,5 -4650,12 +4650,12 @@@
"noProxyLogs": "No proxy logs yet. Configure proxies and make API calls to see them here.",
"noMatchingLogs": "No logs match the current filters.",
"tlsFingerprint": "Chrome 124 TLS Fingerprint"
+ },
+ "agentFeatures": {
+ "agentFeaturesContextLength": "Context length",
+ "agentFeaturesContextLengthPlaceholder": "e.g. 128000",
+ "agentFeaturesContextLengthHint": "Defines the context window for this combo in /v1/models.",
+ "agentFeaturesContextLengthErrorInteger": "Context length must be a valid integer",
+ "agentFeaturesContextLengthErrorRange": "Context length must be between 1000 and 2000000"
}
-}
+}
diff --cc src/i18n/messages/hi.json
index 0cb3b55b9e,6213615420..a3030feb32
--- a/src/i18n/messages/hi.json
+++ b/src/i18n/messages/hi.json
@@@ -4607,5 -4650,12 +4650,12 @@@
"noProxyLogs": "No proxy logs yet. Configure proxies and make API calls to see them here.",
"noMatchingLogs": "No logs match the current filters.",
"tlsFingerprint": "Chrome 124 TLS Fingerprint"
+ },
+ "agentFeatures": {
+ "agentFeaturesContextLength": "Context length",
+ "agentFeaturesContextLengthPlaceholder": "e.g. 128000",
+ "agentFeaturesContextLengthHint": "Defines the context window for this combo in /v1/models.",
+ "agentFeaturesContextLengthErrorInteger": "Context length must be a valid integer",
+ "agentFeaturesContextLengthErrorRange": "Context length must be between 1000 and 2000000"
}
-}
+}
diff --cc src/i18n/messages/hu.json
index 75d4714f9b,0695fbfa9d..dde4b75d0a
--- a/src/i18n/messages/hu.json
+++ b/src/i18n/messages/hu.json
@@@ -4607,5 -4650,12 +4650,12 @@@
"noProxyLogs": "No proxy logs yet. Configure proxies and make API calls to see them here.",
"noMatchingLogs": "No logs match the current filters.",
"tlsFingerprint": "Chrome 124 TLS Fingerprint"
+ },
+ "agentFeatures": {
+ "agentFeaturesContextLength": "Context length",
+ "agentFeaturesContextLengthPlaceholder": "e.g. 128000",
+ "agentFeaturesContextLengthHint": "Defines the context window for this combo in /v1/models.",
+ "agentFeaturesContextLengthErrorInteger": "Context length must be a valid integer",
+ "agentFeaturesContextLengthErrorRange": "Context length must be between 1000 and 2000000"
}
-}
+}
diff --cc src/i18n/messages/id.json
index a7f0f928a3,2b554d7928..78d6edc506
--- a/src/i18n/messages/id.json
+++ b/src/i18n/messages/id.json
@@@ -4607,5 -4654,12 +4654,12 @@@
"noProxyLogs": "No proxy logs yet. Configure proxies and make API calls to see them here.",
"noMatchingLogs": "No logs match the current filters.",
"tlsFingerprint": "Chrome 124 TLS Fingerprint"
+ },
+ "agentFeatures": {
+ "agentFeaturesContextLength": "Context length",
+ "agentFeaturesContextLengthPlaceholder": "e.g. 128000",
+ "agentFeaturesContextLengthHint": "Defines the context window for this combo in /v1/models.",
+ "agentFeaturesContextLengthErrorInteger": "Context length must be a valid integer",
+ "agentFeaturesContextLengthErrorRange": "Context length must be between 1000 and 2000000"
}
-}
+}
diff --cc src/i18n/messages/in.json
index 68de27273f,001d49628d..93d1f02fc4
--- a/src/i18n/messages/in.json
+++ b/src/i18n/messages/in.json
@@@ -4900,5 -4943,12 +4943,12 @@@
"noProxyLogs": "No proxy logs yet. Configure proxies and make API calls to see them here.",
"noMatchingLogs": "No logs match the current filters.",
"tlsFingerprint": "Chrome 124 TLS Fingerprint"
+ },
+ "agentFeatures": {
+ "agentFeaturesContextLength": "Context length",
+ "agentFeaturesContextLengthPlaceholder": "e.g. 128000",
+ "agentFeaturesContextLengthHint": "Defines the context window for this combo in /v1/models.",
+ "agentFeaturesContextLengthErrorInteger": "Context length must be a valid integer",
+ "agentFeaturesContextLengthErrorRange": "Context length must be between 1000 and 2000000"
}
-}
+}
diff --cc src/i18n/messages/it.json
index d5951e5591,bdeb16216a..b13bbd59ef
--- a/src/i18n/messages/it.json
+++ b/src/i18n/messages/it.json
@@@ -4607,5 -4650,12 +4650,12 @@@
"noProxyLogs": "No proxy logs yet. Configure proxies and make API calls to see them here.",
"noMatchingLogs": "No logs match the current filters.",
"tlsFingerprint": "Chrome 124 TLS Fingerprint"
+ },
+ "agentFeatures": {
+ "agentFeaturesContextLength": "Context length",
+ "agentFeaturesContextLengthPlaceholder": "e.g. 128000",
+ "agentFeaturesContextLengthHint": "Defines the context window for this combo in /v1/models.",
+ "agentFeaturesContextLengthErrorInteger": "Context length must be a valid integer",
+ "agentFeaturesContextLengthErrorRange": "Context length must be between 1000 and 2000000"
}
-}
+}
diff --cc src/i18n/messages/ja.json
index 7d7ab409e3,6f20f605ad..9245ca8f5b
--- a/src/i18n/messages/ja.json
+++ b/src/i18n/messages/ja.json
@@@ -4607,5 -4650,12 +4650,12 @@@
"noProxyLogs": "No proxy logs yet. Configure proxies and make API calls to see them here.",
"noMatchingLogs": "No logs match the current filters.",
"tlsFingerprint": "Chrome 124 TLS Fingerprint"
+ },
+ "agentFeatures": {
+ "agentFeaturesContextLength": "Context length",
+ "agentFeaturesContextLengthPlaceholder": "e.g. 128000",
+ "agentFeaturesContextLengthHint": "Defines the context window for this combo in /v1/models.",
+ "agentFeaturesContextLengthErrorInteger": "Context length must be a valid integer",
+ "agentFeaturesContextLengthErrorRange": "Context length must be between 1000 and 2000000"
}
-}
+}
diff --cc src/i18n/messages/ko.json
index 0c92c7fd0e,b0200c0c6f..0dea5885de
--- a/src/i18n/messages/ko.json
+++ b/src/i18n/messages/ko.json
@@@ -4609,5 -4652,12 +4652,12 @@@
"noProxyLogs": "No proxy logs yet. Configure proxies and make API calls to see them here.",
"noMatchingLogs": "No logs match the current filters.",
"tlsFingerprint": "Chrome 124 TLS Fingerprint"
+ },
+ "agentFeatures": {
+ "agentFeaturesContextLength": "Context length",
+ "agentFeaturesContextLengthPlaceholder": "e.g. 128000",
+ "agentFeaturesContextLengthHint": "Defines the context window for this combo in /v1/models.",
+ "agentFeaturesContextLengthErrorInteger": "Context length must be a valid integer",
+ "agentFeaturesContextLengthErrorRange": "Context length must be between 1000 and 2000000"
}
-}
+}
diff --cc src/i18n/messages/mr.json
index 230af1fa18,a05d8fc744..1e5ce32f75
--- a/src/i18n/messages/mr.json
+++ b/src/i18n/messages/mr.json
@@@ -4900,5 -4943,12 +4943,12 @@@
"noProxyLogs": "No proxy logs yet. Configure proxies and make API calls to see them here.",
"noMatchingLogs": "No logs match the current filters.",
"tlsFingerprint": "Chrome 124 TLS Fingerprint"
+ },
+ "agentFeatures": {
+ "agentFeaturesContextLength": "Context length",
+ "agentFeaturesContextLengthPlaceholder": "e.g. 128000",
+ "agentFeaturesContextLengthHint": "Defines the context window for this combo in /v1/models.",
+ "agentFeaturesContextLengthErrorInteger": "Context length must be a valid integer",
+ "agentFeaturesContextLengthErrorRange": "Context length must be between 1000 and 2000000"
}
-}
+}
diff --cc src/i18n/messages/ms.json
index 3022f9b12b,2745bbf818..33cc008f9b
--- a/src/i18n/messages/ms.json
+++ b/src/i18n/messages/ms.json
@@@ -4607,5 -4650,12 +4650,12 @@@
"noProxyLogs": "No proxy logs yet. Configure proxies and make API calls to see them here.",
"noMatchingLogs": "No logs match the current filters.",
"tlsFingerprint": "Chrome 124 TLS Fingerprint"
+ },
+ "agentFeatures": {
+ "agentFeaturesContextLength": "Context length",
+ "agentFeaturesContextLengthPlaceholder": "e.g. 128000",
+ "agentFeaturesContextLengthHint": "Defines the context window for this combo in /v1/models.",
+ "agentFeaturesContextLengthErrorInteger": "Context length must be a valid integer",
+ "agentFeaturesContextLengthErrorRange": "Context length must be between 1000 and 2000000"
}
-}
+}
diff --cc src/i18n/messages/nl.json
index 045d8022f0,a72d112ff3..a9b77a8144
--- a/src/i18n/messages/nl.json
+++ b/src/i18n/messages/nl.json
@@@ -4607,5 -4650,12 +4650,12 @@@
"noProxyLogs": "No proxy logs yet. Configure proxies and make API calls to see them here.",
"noMatchingLogs": "No logs match the current filters.",
"tlsFingerprint": "Chrome 124 TLS Fingerprint"
+ },
+ "agentFeatures": {
+ "agentFeaturesContextLength": "Context length",
+ "agentFeaturesContextLengthPlaceholder": "e.g. 128000",
+ "agentFeaturesContextLengthHint": "Defines the context window for this combo in /v1/models.",
+ "agentFeaturesContextLengthErrorInteger": "Context length must be a valid integer",
+ "agentFeaturesContextLengthErrorRange": "Context length must be between 1000 and 2000000"
}
-}
+}
diff --cc src/i18n/messages/no.json
index e63f57edd8,5b5a755318..b86e81d080
--- a/src/i18n/messages/no.json
+++ b/src/i18n/messages/no.json
@@@ -4607,5 -4650,12 +4650,12 @@@
"noProxyLogs": "No proxy logs yet. Configure proxies and make API calls to see them here.",
"noMatchingLogs": "No logs match the current filters.",
"tlsFingerprint": "Chrome 124 TLS Fingerprint"
+ },
+ "agentFeatures": {
+ "agentFeaturesContextLength": "Context length",
+ "agentFeaturesContextLengthPlaceholder": "e.g. 128000",
+ "agentFeaturesContextLengthHint": "Defines the context window for this combo in /v1/models.",
+ "agentFeaturesContextLengthErrorInteger": "Context length must be a valid integer",
+ "agentFeaturesContextLengthErrorRange": "Context length must be between 1000 and 2000000"
}
-}
+}
diff --cc src/i18n/messages/phi.json
index 6daab89dad,35e1d22574..55f87b9e7a
--- a/src/i18n/messages/phi.json
+++ b/src/i18n/messages/phi.json
@@@ -4607,5 -4650,12 +4650,12 @@@
"noProxyLogs": "No proxy logs yet. Configure proxies and make API calls to see them here.",
"noMatchingLogs": "No logs match the current filters.",
"tlsFingerprint": "Chrome 124 TLS Fingerprint"
+ },
+ "agentFeatures": {
+ "agentFeaturesContextLength": "Context length",
+ "agentFeaturesContextLengthPlaceholder": "e.g. 128000",
+ "agentFeaturesContextLengthHint": "Defines the context window for this combo in /v1/models.",
+ "agentFeaturesContextLengthErrorInteger": "Context length must be a valid integer",
+ "agentFeaturesContextLengthErrorRange": "Context length must be between 1000 and 2000000"
}
-}
+}
diff --cc src/lib/db/providers.ts
index fcf6b79fb8,f87953903a..9a023f40e2
--- a/src/lib/db/providers.ts
+++ b/src/lib/db/providers.ts
@@@ -435,6 -435,24 +435,24 @@@ export async function deleteProviderCon
return true;
}
+ export async function deleteProviderConnections(ids: string[]): Promise<number> {
+ if (ids.length === 0) return 0;
+ const db = getDbInstance();
+
+ const deletedCount = db.transaction(() => {
+ const placeholders = ids.map(() => "?").join(",");
+ db.prepare(`DELETE FROM quota_snapshots WHERE connection_id IN (${placeholders})`).run(...ids);
- const result = db.prepare(
- `DELETE FROM provider_connections WHERE id IN (${placeholders})`
- ).run(...ids);
++ const result = db
++ .prepare(`DELETE FROM provider_connections WHERE id IN (${placeholders})`)
++ .run(...ids);
+ return result.changes ?? 0;
+ })();
+
+ backupDbFile("pre-write");
+ invalidateDbCache("connections");
+ return deletedCount;
+ }
+
export async function deleteProviderConnectionsByProvider(providerId: string) {
const db = getDbInstance() as unknown as DbLike;
const connectionIds = db
diff --cc src/shared/components/AutoRoutingBanner.tsx
index 0000000000,062de5c001..9aedb528ce
mode 000000,100644..100644
--- a/src/shared/components/AutoRoutingBanner.tsx
+++ b/src/shared/components/AutoRoutingBanner.tsx
@@@ -1,0 -1,79 +1,79 @@@
+ "use client";
+
+ import { useEffect, useState } from "react";
+
+ const AUTO_ROUTING_DISMISSED_KEY = "auto-routing-banner-dismissed";
+
+ export default function AutoRoutingBanner() {
+ const [isDismissed, setIsDismissed] = useState(false);
+
+ useEffect(() => {
+ try {
+ const dismissed = localStorage.getItem(AUTO_ROUTING_DISMISSED_KEY);
+ if (dismissed === "true") {
+ // eslint-disable-next-line react-hooks/set-state-in-effect
+ setIsDismissed(true);
+ }
+ } catch {
+ // localStorage unavailable (SSR or private mode) — do nothing
+ }
+ }, []);
+
+ const handleDismiss = () => {
+ try {
+ localStorage.setItem(AUTO_ROUTING_DISMISSED_KEY, "true");
+ } catch {
+ // ignore localStorage errors (private mode, quotas)
+ }
-
++
+ setIsDismissed(true);
+ };
+
+ if (isDismissed) return null;
+
+ return (
+ <div
+ role="banner"
+ aria-label="Auto-routing mode active"
+ className="relative overflow-hidden rounded-lg border-l-4 border-blue-500 bg-blue-50/50 p-4 my-4 dark:bg-blue-950/30 transition-colors"
+ >
+ <div className="flex items-start gap-3">
+ <div className="flex items-center gap-2">
+ <span className="inline-flex h-2 w-2 animate-pulse rounded-full bg-blue-500" />
+ <span className="font-semibold text-sm text-blue-700 dark:text-blue-300">
+ Auto-Routing Active
+ </span>
+ </div>
+ <div className="text-sm leading-relaxed text-text-muted">
+ OmniRoute is automatically routing requests using combo-based strategies.
+ <span className="block sm:inline sm:ml-1">
+ View or change your routing configuration on the{" "}
+ <a
+ href="/dashboard/combos"
+ className="text-blue-600 hover:text-blue-800 underline dark:text-blue-400 dark:hover:text-blue-300"
+ >
+ Combos page
+ </a>
+ .
+ </span>
+ </div>
+ <button
+ type="button"
+ onClick={handleDismiss}
+ aria-label="Dismiss auto-routing banner"
+ className="ml-auto flex-shrink-0 rounded-md p-1 text-text-muted hover:bg-blue-100 hover:text-blue-700 dark:hover:bg-blue-900/50 dark:hover:text-blue-300 transition-colors"
+ >
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 20 20"
+ fill="currentColor"
+ className="h-5 w-5"
+ aria-hidden="true"
+ >
+ <path d="M6.28 5.22a.75.75 0 00-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 101.06 1.06L10 11.06l3.72 3.72a.75.75 0 101.06-1.06L11.06 10l3.72-3.72a.75.75 0 00-1.06-1.06L10 8.94 6.28 5.22z" />
+ </svg>
+ </button>
+ </div>
+ </div>
+ );
+ }
diff --cc src/shared/utils/apiKeyPolicy.ts
index 211a074ee9,5909d6b37f..c750f93361
--- a/src/shared/utils/apiKeyPolicy.ts
+++ b/src/shared/utils/apiKeyPolicy.ts
@@@ -14,6 -14,13 +14,13 @@@ import { checkBudget } from "@/domain/c
import { errorResponse } from "@omniroute/open-sse/utils/error.ts";
import { HTTP_STATUS } from "@omniroute/open-sse/config/constants.ts";
import * as log from "@/sse/utils/logger";
+ import { checkRateLimit, RateLimitRule } from "./rateLimiter";
+
+ const DEFAULT_RATE_LIMITS: RateLimitRule[] = [
- { limit: 1000, window: 86400 }, // 1000 per day
- { limit: 5000, window: 604800 }, // 5000 per week
- { limit: 20000, window: 2592000 } // 20000 per month
++ { limit: 1000, window: 86400 }, // 1000 per day
++ { limit: 5000, window: 604800 }, // 5000 per week
++ { limit: 20000, window: 2592000 }, // 20000 per month
+ ];
interface AccessSchedule {
enabled: boolean;
@@@ -230,6 -183,25 +183,28 @@@ export async function enforceApiKeyPoli
rejection: errorResponse(HTTP_STATUS.FORBIDDEN, "This API key is disabled"),
};
}
+ if (apiKeyInfo.isBanned === true) {
+ return {
+ apiKey,
+ apiKeyInfo,
- rejection: errorResponse(HTTP_STATUS.FORBIDDEN, "This API key is banned due to policy violations"),
++ rejection: errorResponse(
++ HTTP_STATUS.FORBIDDEN,
++ "This API key is banned due to policy violations"
++ ),
+ };
+ }
+
+ // ── Check 1.5: expires_at ──
+ if (apiKeyInfo.expiresAt) {
+ const expiry = new Date(apiKeyInfo.expiresAt).getTime();
+ if (Date.now() > expiry) {
+ return {
+ apiKey,
+ apiKeyInfo,
+ rejection: errorResponse(HTTP_STATUS.FORBIDDEN, "This API key has expired"),
+ };
+ }
+ }
// ── Check 2: access_schedule — time-based access window ──
if (apiKeyInfo.accessSchedule && apiKeyInfo.accessSchedule.enabled) {
@@@ -286,18 -258,31 +261,35 @@@
}
}
- // ── Check 5: Request-count limits (#452) ──
- if (apiKeyInfo.id && (apiKeyInfo.maxRequestsPerDay || apiKeyInfo.maxRequestsPerMinute)) {
- const limitError = checkRequestCountLimits(
- apiKeyInfo.id,
- apiKeyInfo.maxRequestsPerDay,
- apiKeyInfo.maxRequestsPerMinute
- );
- if (limitError) {
+ // ── Check 5: Generic Multi-Window Rate Limits ──
+ if (apiKeyInfo.id) {
- const rulesToApply = (apiKeyInfo.rateLimits && apiKeyInfo.rateLimits.length > 0)
- ? [...apiKeyInfo.rateLimits]
- : [...DEFAULT_RATE_LIMITS];
++ const rulesToApply =
++ apiKeyInfo.rateLimits && apiKeyInfo.rateLimits.length > 0
++ ? [...apiKeyInfo.rateLimits]
++ : [...DEFAULT_RATE_LIMITS];
+
+ // Combine with legacy limits if they exist and custom rate limits aren't set
+ if (!apiKeyInfo.rateLimits || apiKeyInfo.rateLimits.length === 0) {
+ if (apiKeyInfo.maxRequestsPerDay) {
+ rulesToApply.push({ limit: apiKeyInfo.maxRequestsPerDay, window: 86400 });
+ }
+ if (apiKeyInfo.maxRequestsPerMinute) {
+ rulesToApply.push({ limit: apiKeyInfo.maxRequestsPerMinute, window: 60 });
+ }
+ }
+
+ const rateLimitResult = await checkRateLimit(apiKeyInfo.id, rulesToApply);
+ if (!rateLimitResult.allowed) {
- const failedWindowStr = rateLimitResult.failedWindow
- ? ` (${rateLimitResult.failedWindow}s window)`
++ const failedWindowStr = rateLimitResult.failedWindow
++ ? ` (${rateLimitResult.failedWindow}s window)`
+ : "";
return {
apiKey,
apiKeyInfo,
- rejection: errorResponse(HTTP_STATUS.RATE_LIMITED, limitError),
- rejection: errorResponse(HTTP_STATUS.RATE_LIMITED, `Request limit exceeded${failedWindowStr}. Please try again later.`),
++ rejection: errorResponse(
++ HTTP_STATUS.RATE_LIMITED,
++ `Request limit exceeded${failedWindowStr}. Please try again later.`
++ ),
};
}
}
diff --cc src/shared/utils/rateLimiter.ts
index 0000000000,14fc5a89fe..e736c3b414
mode 000000,100644..100644
--- a/src/shared/utils/rateLimiter.ts
+++ b/src/shared/utils/rateLimiter.ts
@@@ -1,0 -1,142 +1,142 @@@
+ import Redis from "ioredis";
+
+ // Reuse existing REDIS_URL if set, or local redis via default docker-compose
+ // Use REDIS_URL from env (Docker/Production) or fallback to local redis
+ const REDIS_URL = process.env.REDIS_URL || "redis://localhost:6379";
-if (process.env.NODE_ENV === 'production' && !process.env.REDIS_URL) {
- console.warn('[REDIS] REDIS_URL is not set in production. Falling back to default.');
++if (process.env.NODE_ENV === "production" && !process.env.REDIS_URL) {
++ console.warn("[REDIS] REDIS_URL is not set in production. Falling back to default.");
+ }
+
-
+ let redisClient: Redis | null = null;
+
+ export function getRedisClient() {
+ if (!redisClient) {
+ redisClient = new Redis(REDIS_URL, {
+ maxRetriesPerRequest: 3,
+ enableReadyCheck: false,
+ retryStrategy(times) {
+ return Math.min(times * 50, 2000); // Exponential backoff
- }
++ },
+ });
- redisClient.on('error', (err) => console.error('[REDIS] Error:', err.message));
++ redisClient.on("error", (err) => console.error("[REDIS] Error:", err.message));
+ }
+ return redisClient;
+ }
+
+ export interface RateLimitRule {
+ limit: number;
+ window: number; // in seconds
+ }
+
+ export interface RateLimitResult {
+ allowed: boolean;
+ failedWindow?: number;
+ }
+
+ /**
+ * Atomic Lua script for multi-rule rate limiting using fixed window.
+ * Returns {1, 0} if allowed, or {0, failedWindow} if rejected.
+ */
+ const RATE_LIMIT_SCRIPT = `
+ local key_prefix = KEYS[1]
+ local current_time = tonumber(ARGV[1])
+
+ local rules = {}
+ for i = 2, #ARGV, 2 do
+ table.insert(rules, {
+ limit = tonumber(ARGV[i]),
+ window = tonumber(ARGV[i+1])
+ })
+ end
+
+ -- First pass: check if any limit is exceeded
+ for i, rule in ipairs(rules) do
+ local current_window = math.floor(current_time / rule.window)
+ local window_key = key_prefix .. ":" .. rule.window .. ":" .. current_window
+
+ local count = tonumber(redis.call("GET", window_key) or "0")
+ if count >= rule.limit then
+ return { 0, rule.window } -- Reject, return which window failed
+ end
+ end
+
+ -- Second pass: increment all rules
+ for i, rule in ipairs(rules) do
+ local current_window = math.floor(current_time / rule.window)
+ local window_key = key_prefix .. ":" .. rule.window .. ":" .. current_window
+
+ local count = redis.call("INCR", window_key)
+ if count == 1 then
+ -- TTL is twice the window size to ensure it covers the current window safely
+ redis.call("EXPIRE", window_key, rule.window * 2)
+ end
+ end
+
+ return { 1, 0 } -- Accepted
+ `;
+
+ const TEST_MEMORY_STORE = new Map<string, number>();
+ let explicitTestMode = false;
+
+ export function setRateLimiterTestMode(enabled: boolean) {
+ explicitTestMode = enabled;
+ if (enabled) TEST_MEMORY_STORE.clear();
+ }
+
+ /**
+ * Checks multi-window rate limits for an API key atomically via Redis.
+ */
+ export async function checkRateLimit(
- keyId: string,
++ keyId: string,
+ rules: RateLimitRule[]
+ ): Promise<RateLimitResult> {
+ if (!rules || rules.length === 0) return { allowed: true };
+
+ // ── In-memory mock for unit tests ──
- const isTestMode = explicitTestMode || process.env.NODE_ENV === "test" || process.env.DISABLE_SQLITE_AUTO_BACKUP === "true";
-
++ const isTestMode =
++ explicitTestMode ||
++ process.env.NODE_ENV === "test" ||
++ process.env.DISABLE_SQLITE_AUTO_BACKUP === "true";
++
+ if (isTestMode) {
+ const now = Math.floor(Date.now() / 1000);
+ for (const rule of rules) {
+ const currentWindow = Math.floor(now / rule.window);
+ const windowKey = `rl:api_key:${keyId}:${rule.window}:${currentWindow}`;
+ const count = TEST_MEMORY_STORE.get(windowKey) || 0;
+ if (count >= rule.limit) {
+ return { allowed: false, failedWindow: rule.window };
+ }
+ }
+ for (const rule of rules) {
+ const currentWindow = Math.floor(now / rule.window);
+ const windowKey = `rl:api_key:${keyId}:${rule.window}:${currentWindow}`;
+ TEST_MEMORY_STORE.set(windowKey, (TEST_MEMORY_STORE.get(windowKey) || 0) + 1);
+ }
+ return { allowed: true };
+ }
+
+ const redis = getRedisClient();
+ const args: (string | number)[] = [Math.floor(Date.now() / 1000)];
-
++
+ for (const rule of rules) {
+ args.push(rule.limit, rule.window);
+ }
+
+ try {
- const result = await redis.eval(
- RATE_LIMIT_SCRIPT,
- 1,
- `rl:api_key:${keyId}`,
- ...args
- ) as [number, number];
++ const result = (await redis.eval(RATE_LIMIT_SCRIPT, 1, `rl:api_key:${keyId}`, ...args)) as [
++ number,
++ number,
++ ];
+
+ if (result[0] === 0) {
+ return { allowed: false, failedWindow: result[1] };
+ }
-
++
+ return { allowed: true };
+ } catch (error) {
+ // Fail-open strategy if Redis goes down to prevent complete API outage
+ console.error("[RATE_LIMITER] Redis eval failed, bypassing rate limit:", error);
- return { allowed: true };
++ return { allowed: true };
+ }
+ }
diff --cc tests/unit/api-key-regeneration.test.ts
index 0000000000,d7624811ca..a492424498
mode 000000,100644..100644
--- a/tests/unit/api-key-regeneration.test.ts
+++ b/tests/unit/api-key-regeneration.test.ts
@@@ -1,0 -1,62 +1,62 @@@
+ 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(), "omr-apikey-regen-"));
+ process.env.DATA_DIR = TEST_DATA_DIR;
+ process.env.API_KEY_SECRET = "test-secret-regen";
+
+ const core = await import("../../src/lib/db/core.ts");
+ const apiKeysDb = await import("../../src/lib/db/apiKeys.ts");
+
+ function reset() {
+ core.resetDbInstance();
+ apiKeysDb.resetApiKeyState();
+ if (fs.existsSync(TEST_DATA_DIR)) {
+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
+ }
+ fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
+ }
+
+ test.beforeEach(() => {
+ reset();
+ });
+
+ test.after(() => {
+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
+ });
+
+ test("regenerateApiKey creates a new key and invalidates the old one", async () => {
+ const machineId = "test-machine-regen";
+ const created = await apiKeysDb.createApiKey("Regen Test", machineId);
+ const oldKey = created.key;
+ const oldId = created.id;
+
+ assert.ok(oldKey);
+ assert.equal(await apiKeysDb.validateApiKey(oldKey), true);
+
+ // Regenerate
+ const result = await apiKeysDb.regenerateApiKey(oldId);
+ assert.ok(result?.key);
+ const regenerated = result!.key;
-
++
+ assert.notEqual(regenerated, oldKey);
-
++
+ // New key should be valid
+ assert.equal(await apiKeysDb.validateApiKey(regenerated), true);
-
++
+ // Old key should be invalid
+ assert.equal(await apiKeysDb.validateApiKey(oldKey), false);
-
++
+ // Name and machineId should persist
+ const md = await apiKeysDb.getApiKeyMetadata(regenerated);
+ assert.equal(md?.name, "Regen Test");
+ assert.ok(regenerated.startsWith(`sk-${machineId}-`));
+ });
+
+ test("regenerateApiKey returns null for non-existent ID", async () => {
+ const result = await apiKeysDb.regenerateApiKey("00000000-0000-0000-0000-000000000000");
+ assert.equal(result, null);
+ });
diff --cc tests/unit/base-executor-sanitize-effort.test.ts
index 0000000000,af9b2f3b08..e07958f47c
mode 000000,100644..100644
--- a/tests/unit/base-executor-sanitize-effort.test.ts
+++ b/tests/unit/base-executor-sanitize-effort.test.ts
@@@ -1,0 -1,132 +1,125 @@@
+ import test from "node:test";
+ import assert from "node:assert/strict";
+
-const { sanitizeReasoningEffortForProvider } = await import(
- "../../open-sse/executors/base.ts"
-);
++const { sanitizeReasoningEffortForProvider } = await import("../../open-sse/executors/base.ts");
+
+ function makeLog() {
+ const messages: Array<[string, string]> = [];
+ return {
+ info: (tag: string, msg: string) => messages.push([tag, msg]),
+ messages,
+ };
+ }
+
+ test("sanitizeReasoningEffortForProvider: xiaomi-mimo downgrades xhigh → high", () => {
+ const log = makeLog();
+ const body = {
+ model: "mimo-v2.5-pro",
+ reasoning_effort: "xhigh",
+ messages: [{ role: "user", content: "hi" }],
+ };
- const result = sanitizeReasoningEffortForProvider(
- body,
- "xiaomi-mimo",
- "mimo-v2.5-pro",
- log
- );
++ const result = sanitizeReasoningEffortForProvider(body, "xiaomi-mimo", "mimo-v2.5-pro", log);
+ assert.notEqual(result, body, "must return a new object when mutating");
+ assert.equal((result as any).reasoning_effort, "high");
+ assert.equal((result as any).model, "mimo-v2.5-pro", "other fields preserved");
+ assert.ok(
+ log.messages.some(([tag, m]) => tag === "REASONING_SANITIZE" && /xhigh → high/.test(m)),
+ "logs the downgrade"
+ );
+ });
+
+ test("sanitizeReasoningEffortForProvider: xiaomi-mimo downgrades xhigh in nested reasoning.effort", () => {
+ const body = {
+ model: "mimo-v2.5-pro",
+ reasoning: { effort: "xhigh", summary: "auto" },
+ messages: [],
+ };
+ const result = sanitizeReasoningEffortForProvider(body, "xiaomi-mimo", "mimo-v2.5-pro", null);
+ assert.equal((result as any).reasoning.effort, "high");
+ assert.equal((result as any).reasoning.summary, "auto", "other reasoning fields preserved");
+ });
+
+ test("sanitizeReasoningEffortForProvider: mistral/devstral strips reasoning_effort entirely", () => {
+ const log = makeLog();
+ const body = {
+ model: "devstral-2512",
+ reasoning_effort: "medium",
+ messages: [],
+ };
+ const result = sanitizeReasoningEffortForProvider(body, "mistral", "devstral-2512", log);
+ assert.equal((result as any).reasoning_effort, undefined, "reasoning_effort must be stripped");
+ assert.ok(
+ log.messages.some(([tag, m]) => tag === "REASONING_SANITIZE" && /removed/.test(m)),
+ "logs the removal"
+ );
+ });
+
+ test("sanitizeReasoningEffortForProvider: github/claude-opus strips reasoning_effort entirely", () => {
+ const body = {
+ model: "claude-opus-4-6",
+ reasoning_effort: "high",
+ messages: [],
+ };
+ const result = sanitizeReasoningEffortForProvider(body, "github", "claude-opus-4-6", null);
+ assert.equal((result as any).reasoning_effort, undefined);
+ });
+
+ test("sanitizeReasoningEffortForProvider: mistral/devstral strips reasoning object when only effort present", () => {
+ const body = {
+ model: "devstral-2512",
+ reasoning: { effort: "medium" },
+ messages: [],
+ };
+ const result = sanitizeReasoningEffortForProvider(body, "mistral", "devstral-2512", null);
+ assert.equal((result as any).reasoning, undefined, "reasoning object dropped when emptied");
+ });
+
+ test("sanitizeReasoningEffortForProvider: mistral/devstral preserves reasoning when other fields remain", () => {
+ const body = {
+ model: "devstral-2512",
+ reasoning: { effort: "medium", summary: "auto" },
+ messages: [],
+ };
+ const result = sanitizeReasoningEffortForProvider(body, "mistral", "devstral-2512", null);
+ assert.deepEqual((result as any).reasoning, { summary: "auto" });
+ });
+
+ test("sanitizeReasoningEffortForProvider: codex with xhigh passes through unchanged when model supports it", () => {
+ // codex/gpt-5.5-xhigh and related Claude opus models are flagged
+ // supportsXHighEffort:true in providerRegistry. They must not be downgraded.
+ const body = {
+ model: "gpt-5.5-xhigh",
+ reasoning_effort: "xhigh",
+ messages: [],
+ };
+ const result = sanitizeReasoningEffortForProvider(body, "codex", "gpt-5.5-xhigh", null);
+ // Either passes through unchanged (supportsXHighEffort=true)
+ // or the registry doesn't flag it — in which case downgrade is acceptable.
+ // We assert no error and that some reasoning_effort is present.
+ assert.ok(
+ (result as any).reasoning_effort === "xhigh" || (result as any).reasoning_effort === "high",
+ "either preserved (xhigh) or downgraded (high)"
+ );
+ });
+
+ test("sanitizeReasoningEffortForProvider: no-op when reasoning_effort absent", () => {
+ const body = { model: "mimo-v2.5-pro", messages: [] };
+ const result = sanitizeReasoningEffortForProvider(body, "xiaomi-mimo", "mimo-v2.5-pro", null);
+ assert.equal(result, body, "returns original body unchanged");
+ });
+
+ test("sanitizeReasoningEffortForProvider: handles unknown providers as pass-through", () => {
+ const body = { model: "some-model", reasoning_effort: "xhigh", messages: [] };
+ const result = sanitizeReasoningEffortForProvider(body, "unknown-provider", "some-model", null);
+ // unknown provider + xhigh + model not in registry → supportsXHighEffort returns false → downgrade
+ // OR unknown provider isn't in the strip list → returns xhigh
+ // Both are acceptable behavior; we just assert no exception thrown.
+ assert.ok(result !== undefined);
+ });
+
+ test("sanitizeReasoningEffortForProvider: non-object body returns unchanged", () => {
+ assert.equal(sanitizeReasoningEffortForProvider(null, "xiaomi-mimo", "x", null), null);
+ assert.equal(sanitizeReasoningEffortForProvider("string", "xiaomi-mimo", "x", null), "string");
+ const arr: unknown[] = [];
+ assert.equal(sanitizeReasoningEffortForProvider(arr, "xiaomi-mimo", "x", null), arr);
+ });
diff --cc tests/unit/models-catalog-route.test.ts
index a81477276b,495b730abf..e0e33cdf52
--- a/tests/unit/models-catalog-route.test.ts
+++ b/tests/unit/models-catalog-route.test.ts
@@@ -24,16 -24,19 +24,16 @@@ async function resetStorage()
fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
}
- async function seedConnection(provider, overrides = {}) {
-async function seedConnection(
- provider: string,
- overrides: Record<string, unknown> = {}
-) {
++async function seedConnection(provider: string, overrides: Record<string, unknown> = {}) {
return providersDb.createProviderConnection({
provider,
- authType: overrides.authType || "apikey",
- name: overrides.name || `${provider}-${Math.random().toString(16).slice(2, 8)}`,
- apiKey: overrides.apiKey || "sk-test",
- accessToken: overrides.accessToken,
- isActive: overrides.isActive ?? true,
- testStatus: overrides.testStatus || "active",
- providerSpecificData: overrides.providerSpecificData || {},
+ authType: (overrides.authType as string) || "apikey",
+ name: (overrides.name as string) || `${provider}-${Math.random().toString(16).slice(2, 8)}`,
+ apiKey: (overrides.apiKey as string) || "sk-test",
+ accessToken: overrides.accessToken as string | undefined,
+ isActive: (overrides.isActive as boolean) ?? true,
+ testStatus: (overrides.testStatus as string) || "active",
+ providerSpecificData: (overrides.providerSpecificData as Record<string, unknown>) || {},
});
}
@@@ -1172,3 -925,115 +1202,114 @@@ test("v1 models catalog adds managed fa
assert.ok(ids.has("ccdemo/claude-opus-4-6"));
assert.equal(ids.has("ccdemo/claude-sonnet-4-6"), false);
});
+
+ test("v1 models catalog auto-calculates combo context_length from targets when not set manually", async () => {
+ await seedConnection("openai", { name: "openai-auto-context" });
+ await seedConnection("claude", {
+ authType: "oauth",
+ name: "claude-auto-context",
+ apiKey: null,
+ accessToken: "claude-access",
+ });
+
+ // Create a combo with targets having different context limits.
+ // openai/gpt-4o context = 128000, claude/claude-sonnet-4-6 = 200000.
+ // The combo should expose context_length = min = 128000.
+ const combo = await combosDb.createCombo({
+ name: "auto-context-combo",
+ strategy: "priority",
+ models: ["openai/gpt-4o", "claude/claude-sonnet-4-6"],
+ });
+
+ const response = await v1ModelsCatalog.getUnifiedModelsResponse(
+ new Request("http://localhost/api/v1/models")
+ );
+ const body = (await response.json()) as any;
+ const comboModel = body.data.find((item) => item.id === "auto-context-combo");
+
+ assert.equal(response.status, 200);
+ assert.ok(comboModel);
+ assert.equal(
+ comboModel.context_length,
+ 128000,
+ "combo context_length should be the MIN of all target model limits"
+ );
+ });
+
+ test("v1 models catalog includes context_length for individual chat models", async () => {
+ await seedConnection("openai", { name: "openai-context" });
+ await seedConnection("claude", {
+ authType: "oauth",
+ name: "claude-context",
+ apiKey: null,
+ accessToken: "claude-access",
+ });
+
+ const response = await v1ModelsCatalog.getUnifiedModelsResponse(
+ new Request("http://localhost/api/v1/models")
+ );
+ const body = (await response.json()) as any;
+ const chatModels = body.data.filter((item) => !item.type || item.type === "chat");
+
+ assert.equal(response.status, 200);
+ assert.ok(chatModels.length > 0, "should have at least one chat model");
+
+ for (const model of chatModels) {
+ assert.ok(
+ typeof model.context_length === "number" && model.context_length > 0,
+ `chat model ${model.id} should have a positive context_length, got ${model.context_length}`
+ );
+ }
+ });
+
+ test("v1 models catalog falls back to getTokenLimit for models without registry defaultContextLength", async () => {
+ // opencode-go has defaultContextLength in REGISTRY, but we test the fallback
+ // path by verifying models from the synced path still get context_length
+ const connection = await seedConnection("opencode-go", {
+ name: "opencode-go-context-fallback",
+ apiKey: "go-key",
+ });
+
+ await modelsDb.replaceSyncedAvailableModelsForConnection("opencode-go", (connection as any).id, [
+ {
+ id: "test-model-no-context",
+ name: "Test Model No Context",
+ source: "imported",
+ supportedEndpoints: ["chat"],
+ },
+ ]);
+
+ const response = await v1ModelsCatalog.getUnifiedModelsResponse(
+ new Request("http://localhost/api/v1/models")
+ );
+ const body = (await response.json()) as any;
+ const model = body.data.find((item) => item.id === "opencode-go/test-model-no-context");
+
+ assert.equal(response.status, 200);
+ assert.ok(model, "synced model should appear");
+ assert.ok(
+ typeof model.context_length === "number" && model.context_length > 0,
+ `synced model without inputTokenLimit should get context_length via getTokenLimit fallback, got ${model.context_length}`
+ );
+ });
+
-
+ test("v1 models catalog prefers manual combo context_length over auto-calculated", async () => {
+ await seedConnection("openai", { name: "openai-manual-context" });
+
+ const combo = await combosDb.createCombo({
+ name: "manual-context-combo",
+ strategy: "priority",
+ models: ["openai/gpt-4o"],
+ });
+ await combosDb.updateCombo((combo as any).id, { context_length: 64000 });
+
+ const response = await v1ModelsCatalog.getUnifiedModelsResponse(
+ new Request("http://localhost/api/v1/models")
+ );
+ const body = (await response.json()) as any;
+ const comboModel = body.data.find((item) => item.id === "manual-context-combo");
+
+ assert.equal(response.status, 200);
+ assert.ok(comboModel);
+ assert.equal(comboModel.context_length, 64000, "manual context_length should override auto-calc");
+ });
diff --cc tests/unit/proxy-connection-test.test.ts
index 3d07ad1c99,358c715847..4f5c0f9a49
--- a/tests/unit/proxy-connection-test.test.ts
+++ b/tests/unit/proxy-connection-test.test.ts
@@@ -1,5 -1,6 +1,9 @@@
import test from "node:test";
import assert from "node:assert/strict";
-import { providerAllowsOptionalApiKey, SELF_HOSTED_CHAT_PROVIDER_IDS } from "@/shared/constants/providers";
++import {
++ providerAllowsOptionalApiKey,
++ SELF_HOSTED_CHAT_PROVIDER_IDS,
++} from "@/shared/constants/providers";
// ── Import test targets from connection test route ──────────────────────────
diff --cc tests/unit/translator-claude-helper-thinking.test.ts
index 0000000000,ca153a44d1..5c2f460f45
mode 000000,100644..100644
--- a/tests/unit/translator-claude-helper-thinking.test.ts
+++ b/tests/unit/translator-claude-helper-thinking.test.ts
@@@ -1,0 -1,128 +1,115 @@@
+ import test from "node:test";
+ import assert from "node:assert/strict";
+
-const { prepareClaudeRequest } = await import(
- "../../open-sse/translator/helpers/claudeHelper.ts"
-);
-const { DEFAULT_THINKING_CLAUDE_SIGNATURE } = await import(
- "../../open-sse/config/defaultThinkingSignature.ts"
-);
++const { prepareClaudeRequest } = await import("../../open-sse/translator/helpers/claudeHelper.ts");
++const { DEFAULT_THINKING_CLAUDE_SIGNATURE } =
++ await import("../../open-sse/config/defaultThinkingSignature.ts");
+
+ function multiTurnBodyWithoutThinkingBlock() {
+ return {
+ thinking: { type: "enabled", budget_tokens: 4096 },
+ messages: [
+ { role: "user", content: [{ type: "text", text: "hi" }] },
+ {
+ role: "assistant",
- content: [
- { type: "tool_use", id: "call_x", name: "ls", input: { path: "." } },
- ],
++ content: [{ type: "tool_use", id: "call_x", name: "ls", input: { path: "." } }],
+ },
+ {
+ role: "user",
+ content: [
+ {
+ type: "tool_result",
+ tool_use_id: "call_x",
+ content: "README.md\npackage.json",
+ },
+ ],
+ },
+ ],
+ };
+ }
+
+ test("prepareClaudeRequest: claude provider — injects thinking before tool_use (regression)", () => {
+ const body = multiTurnBodyWithoutThinkingBlock();
+ const result = prepareClaudeRequest(body as any, "claude");
+ const assistantContent = (result as any).messages[1].content;
+ assert.equal(assistantContent.length, 2, "thinking + tool_use");
+ assert.equal(assistantContent[0].type, "thinking");
+ assert.equal(assistantContent[0].thinking, ".");
+ assert.equal(assistantContent[0].signature, DEFAULT_THINKING_CLAUDE_SIGNATURE);
+ assert.equal(assistantContent[1].type, "tool_use");
+ });
+
+ test("prepareClaudeRequest: kimi-coding provider — injects thinking before tool_use (new behavior)", () => {
+ // Previously: kimi-coding was excluded by the provider gate and the assistant
+ // turn shipped to api.kimi.com/coding/v1/messages without a thinking
+ // precursor, triggering 400 "thinking is enabled but reasoning_content is
+ // missing in assistant tool call message at index N".
+ const body = multiTurnBodyWithoutThinkingBlock();
+ const result = prepareClaudeRequest(body as any, "kimi-coding");
+ const assistantContent = (result as any).messages[1].content;
+ assert.equal(assistantContent.length, 2, "thinking + tool_use");
+ assert.equal(assistantContent[0].type, "thinking");
+ assert.equal(assistantContent[0].thinking, ".");
+ assert.equal(assistantContent[0].signature, DEFAULT_THINKING_CLAUDE_SIGNATURE);
+ });
+
+ test("prepareClaudeRequest: existing thinking block — redacted, signature replaced, no double-inject", () => {
+ const body = {
+ thinking: { type: "enabled", budget_tokens: 4096 },
+ messages: [
+ { role: "user", content: [{ type: "text", text: "hi" }] },
+ {
+ role: "assistant",
+ content: [
+ { type: "thinking", thinking: "reasoning here", signature: "old-sig" },
+ { type: "tool_use", id: "call_y", name: "ls", input: {} },
+ ],
+ },
+ {
+ role: "user",
- content: [
- { type: "tool_result", tool_use_id: "call_y", content: "ok" },
- ],
++ content: [{ type: "tool_result", tool_use_id: "call_y", content: "ok" }],
+ },
+ ],
+ };
+ const result = prepareClaudeRequest(body as any, "kimi-coding");
+ const assistantContent = (result as any).messages[1].content;
+ assert.equal(assistantContent.length, 2, "no double-inject — exactly 2 blocks");
+ assert.equal(assistantContent[0].type, "redacted_thinking", "thinking → redacted_thinking");
+ assert.equal(assistantContent[0].signature, DEFAULT_THINKING_CLAUDE_SIGNATURE);
+ assert.equal(assistantContent[0].thinking, undefined, "thinking field stripped");
+ assert.equal(assistantContent[1].type, "tool_use");
+ });
+
+ test("prepareClaudeRequest: thinking disabled — no inject regardless of tool_use presence", () => {
+ const body = {
+ thinking: { type: "disabled" },
+ messages: [
+ { role: "user", content: [{ type: "text", text: "hi" }] },
+ {
+ role: "assistant",
- content: [
- { type: "tool_use", id: "call_z", name: "ls", input: {} },
- ],
++ content: [{ type: "tool_use", id: "call_z", name: "ls", input: {} }],
+ },
+ {
+ role: "user",
- content: [
- { type: "tool_result", tool_use_id: "call_z", content: "ok" },
- ],
++ content: [{ type: "tool_result", tool_use_id: "call_z", content: "ok" }],
+ },
+ ],
+ };
+ const result = prepareClaudeRequest(body as any, "kimi-coding");
+ const assistantContent = (result as any).messages[1].content;
+ assert.equal(assistantContent.length, 1, "no thinking injected when thinking is disabled");
+ assert.equal(assistantContent[0].type, "tool_use");
+ });
+
+ test("prepareClaudeRequest: thinking enabled + no tool_use — no inject (single-turn text)", () => {
+ const body = {
+ thinking: { type: "enabled", budget_tokens: 4096 },
- messages: [
- { role: "user", content: [{ type: "text", text: "hi" }] },
- ],
++ messages: [{ role: "user", content: [{ type: "text", text: "hi" }] }],
+ };
+ const result = prepareClaudeRequest(body as any, "kimi-coding");
+ const userContent = (result as any).messages[0].content;
+ assert.ok(Array.isArray(userContent));
+ assert.equal(userContent[0].type, "text");
+ // No new thinking block prepended on user messages
+ assert.equal(userContent.length, 1);
+ });