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

fix(auth): require management auth for agent and cooldown APIs

diegosouzapwc89663d7745b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f739ca8b7b..6540496ffc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,38 +2,13 @@
## [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(oauth):** complete Windsurf and Devin CLI OAuth + API-token flows — WindsurfExecutor (gRPC-web/protobuf), DevinCliExecutor (ACP JSON-RPC 2.0 over stdio), model alias map, OAuth provider config (#2168 — thanks @Zhaba1337228)
-- **feat(search):** add Ollama Search as a web search provider with registry integration and validation (#2176 — thanks @andrewmunsell)
-- **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(cliproxyapi):** detect Anthropic-shaped request bodies and route to `/v1/messages`, strip Capy extras, and round-trip `mcp_*` tool name rewrites to `Mcp_*` (#2165 — thanks @Brkic-Nikola)
-- **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(responses):** degrade `background: true` to synchronous execution with a warning instead of throwing `unsupportedFeature` (#2164 — thanks @Yosee11)
-- **fix(cloudflare):** add state file write serialization lock to prevent race conditions in `cloudflaredTunnel.ts` (#2156 — thanks @bypanghu)
-
-### 🔧 Improvements
-
-- **feat(api):** aggregate combo model metadata in catalog endpoint — `buildComboCatalogMetadata()` inlines contextLength, strategy, and target count for combo entries (#2166 — thanks @faisalill)
-- **feat(resilience):** `useUpstream429BreakerHints` tri-state PATCH field — `true`/`false` persists, `null` resets to undefined (omitted from JSON) (#2146 tests — thanks @rafacpti23)
-- **chore(registry):** refresh `contextLength` and `maxOutputTokens` for claude, kiro, github, kimi-coding, xiaomi-mimo, codex/gpt-5.5 models (#2163 — thanks @brucevoin)
-- **refactor(executor):** `sanitizeReasoningEffortForProvider()` hook in `BaseExecutor.execute()` — downgrades `xhigh`→`high` for unsupporting providers, strips effort for mistral/devstral and github claude models (#2162 — thanks @hachimed)
-- **refactor(translator):** remove redundant provider guard from Claude thinking placeholder injection — applies to all `targetFormat === FORMATS.CLAUDE` bodies (#2161 — thanks @JohnDoe-oss)
-- **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(providers):** add Command Code provider (#2199 — thanks @ddarkr)
+- **feat(providers):** add ModelScope provider-specific 429 handling and retry logic (#2202 — thanks @InkshadeWoods)
+- **feat(providers):** update Gemini CLI provider models catalog (#2196 — thanks @nickwizard)
- **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
@@ -41,6 +16,7 @@
- **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(cursor):** surface Cursor Pro plan usage on provider-limits dashboard (#2128 — thanks @payne0420)
- **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)
@@ -48,21 +24,27 @@
- **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(combo):** add `fallbackDelayMs` to combo configuration and related settings
- **feat(chat):** dynamic tool limit detection with proactive truncation (#2061)
+- **feat(chat):** add `STREAM_READINESS_TIMEOUT_MS` and integrate into chat handling
+- **feat(chat):** enhance error handling for semaphore capacity with fallback logic
- **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(api):** aggregate combo model metadata in catalog endpoint — `buildComboCatalogMetadata()` inlines contextLength, strategy, and target count for combo entries (#2166 — thanks @faisalill)
- **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(oauth):** complete Windsurf and Devin CLI OAuth + API-token flows — WindsurfExecutor (gRPC-web/protobuf), DevinCliExecutor (ACP JSON-RPC 2.0 over stdio), model alias map, OAuth provider config (#2168 — thanks @Zhaba1337228)
- **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):** add model cooldowns dashboard card with real-time list, individual/bulk re-enable, and auto-refresh (#2146 — thanks @rafacpti23)
- **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(search):** add Ollama Search as a web search provider with registry integration and validation (#2176 — thanks @andrewmunsell)
+- **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)
+- **feat(responses):** degrade `background: true` to synchronous execution with a warning instead of throwing `unsupportedFeature` (#2164 — thanks @Yosee11)
- **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
@@ -112,14 +94,34 @@
- **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(authz):** classify `/dashboard/onboarding` as PUBLIC to unblock setup wizard (#2127)
+- **fix(chatcore):** stop leaking provider credentials in response headers
+- **fix(analytics):** precise SQL matching for `auto/` prefix models
- **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):** restore cloud agent provider exports and logger import (#2138 — thanks @backryun)
- **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)
+- **fix(cliproxyapi):** probe `/v1/models` for health when CPA 6.x has no `/health` endpoint (#2189 — thanks @Brkic-Nikola)
+- **fix(cliproxyapi):** detect Anthropic-shaped request bodies and route to `/v1/messages`, strip Capy extras, and round-trip `mcp_*` tool name rewrites to `Mcp_*` (#2165 — thanks @Brkic-Nikola)
+- **fix(cliproxyapi):** detect Anthropic shape on minimal Capy bodies (#2192 — thanks @Brkic-Nikola)
+- **fix(stream):** skip `[DONE]` terminator for Claude SSE clients (#2190 — thanks @Brkic-Nikola)
+- **fix(claudeHelper):** emit `data` field on `redacted_thinking`, drop bogus signature (#2191 — thanks @Brkic-Nikola)
+- **fix(modelSpecs):** cap thinking budget for Claude Opus 4.6 / 4.7 / Sonnet 4.6 (#2197 — thanks @Brkic-Nikola)
+- **fix(reasoning-cache):** include xiaomi-mimo in replay provider/model detection (#2198 — thanks @Brkic-Nikola)
+- **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)
+- **fix(providers):** allow optional-key providers to pass connection test (#2169 — thanks @andrewmunsell)
+- **fix(providers):** correct pollinations requests and provider dashboard state
+- **fix(api):** validate model cooldown delete payload
+- **fix(ci):** run coverage gate serially, align resilience and thinking checks, align cloud code thinking and model catalog tests
### 🔒 Security
@@ -133,53 +135,71 @@
- **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)
+- **docs:** add Brazilian WhatsApp group link to README (#2201 — thanks @rafacpti23)
+
+### 🔧 Improvements
+
+- **refactor(executor):** `sanitizeReasoningEffortForProvider()` hook in `BaseExecutor.execute()` — downgrades `xhigh`→`high` for unsupporting providers, strips effort for mistral/devstral and github claude models (#2162 — thanks @hachimed)
+- **refactor(translator):** remove redundant provider guard from Claude thinking placeholder injection — applies to all `targetFormat === FORMATS.CLAUDE` bodies (#2161 — thanks @JohnDoe-oss)
+- **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)
+- **feat(resilience):** `useUpstream429BreakerHints` tri-state PATCH field — `true`/`false` persists, `null` resets to undefined (omitted from JSON) (#2146 tests — thanks @rafacpti23)
### 🧹 Chores & Maintenance
- **chore(providers):** prune redundant local provider icon assets in favor of `@lobehub/icons` web fonts (#1992)
- **chore(providers):** remove deprecated models (#2033)
+- **chore(providers):** improve BazaarLink and Completions.me support (#2177 — thanks @backryun)
+- **chore(registry):** refresh `contextLength` and `maxOutputTokens` for claude, kiro, github, kimi-coding, xiaomi-mimo, codex/gpt-5.5 models (#2163 — thanks @brucevoin)
+- **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):** resolve npm audit moderate vulnerability (hono)
+- **chore(deps):** move `gray-matter` from devDependencies to dependencies (runtime requirement) (#2156 — thanks @bypanghu)
- **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)
+- **deps:** bump `hono` from 4.12.14 to 4.12.18 (#2065, #2079)
+- **deps:** bump the development group with 6 updates (#2184)
+- **deps:** bump `electron-builder` from 26.9.1 to 26.10.0 (#2183)
+- **ci:** update build-fork workflow to build from main branch (#2055)
- **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! 🎉
+Thank you to all **50+ community contributors** who made v3.8.0 possible! 🎉
| 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 |
+| [@backryun](https://github.com/backryun) | 8 | #1992, #2033, #2088, #2123, #2138, #2141, #2150, #2177 |
+| [@Brkic-Nikola](https://github.com/Brkic-Nikola) | 6 | #2165, #2189, #2190, #2191, #2192 |
+| [@Gioxaa](https://github.com/Gioxaa) | 5 | #2105, #2149, #2153, #2154, #2159 |
| [@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 |
+| [@herjarsa](https://github.com/herjarsa) | 3 | #2030, #2136, #2152 |
+| [@hartmark](https://github.com/hartmark) | 2 | #2045, #2137 |
+| [@payne0420](https://github.com/payne0420) | 2 | #2082, #2128 |
+| [@nickwizard](https://github.com/nickwizard) | 2 | #1991, #2196 |
+| [@bypanghu](https://github.com/bypanghu) | 2 | #2027, #2156 |
+| [@ddarkr](https://github.com/ddarkr) | 2 | #2047, #2199 |
+| [@eleata](https://github.com/eleata) | 2 | #2116, #2133 |
+| [@rafacpti23](https://github.com/rafacpti23) | 2 | #2086, #2146, #2201 |
+| [@andrewmunsell](https://github.com/andrewmunsell) | 2 | #2169, #2176 |
| [@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 |
@@ -188,6 +208,13 @@ Thank you to all **40 community contributors** who made v3.8.0 possible! 🎉
| [@flyingmongoose](https://github.com/flyingmongoose) | 1 | #2134 |
| [@05dunski](https://github.com/05dunski) | 1 | #1978 (cherry-picked) |
| [@DavyMassoneto](https://github.com/DavyMassoneto) | 1 | #2140 |
+| [@Zhaba1337228](https://github.com/Zhaba1337228) | 1 | #2168 |
+| [@faisalill](https://github.com/faisalill) | 1 | #2166 |
+| [@Yosee11](https://github.com/Yosee11) | 1 | #2164 |
+| [@hachimed](https://github.com/hachimed) | 1 | #2162 |
+| [@JohnDoe-oss](https://github.com/JohnDoe-oss) | 1 | #2161 |
+| [@brucevoin](https://github.com/brucevoin) | 1 | #2163 |
+| [@InkshadeWoods](https://github.com/InkshadeWoods) | 1 | #2202 |
## [3.7.9] — 2026-05-03
diff --git a/bin/cli-commands.mjs b/bin/cli-commands.mjs
index 9a9896a9d1..9402eeeb96 100644
--- a/bin/cli-commands.mjs
+++ b/bin/cli-commands.mjs
@@ -27,7 +27,13 @@ import { join, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { homedir, platform, release } from "node:os";
import { execSync, spawn } from "node:child_process";
-import { randomUUID } from "node:crypto";
+import { resolveStoragePath } from "./cli/data-dir.mjs";
+import {
+ ensureProviderSchema,
+ getProviderApiKey,
+ listProviderConnections,
+ upsertApiKeyProviderConnection,
+} from "./cli/provider-store.mjs";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
@@ -1357,8 +1363,7 @@ async function runKeysAdd(args) {
}
// Direct DB fallback
- const dataDir = resolveConfigPath(".omniroute");
- const dbPath = join(dataDir, "storage.sqlite");
+ const dbPath = resolveStoragePath();
if (!existsSync(dbPath)) {
log("Database not found. Start server first.", "red");
@@ -1371,25 +1376,29 @@ async function runKeysAdd(args) {
const require = createRequire(import.meta.url);
const Database = require("better-sqlite3");
const db = new Database(dbPath);
+ ensureProviderSchema(db);
- // Check if connection exists
const existing = db
- .prepare("SELECT id FROM provider_connections WHERE provider = ?")
+ .prepare(
+ "SELECT id, name FROM provider_connections WHERE provider = ? AND auth_type = 'apikey' ORDER BY priority ASC, updated_at DESC LIMIT 1"
+ )
.get(providerLower);
-
- if (existing) {
- db.prepare("UPDATE provider_connections SET api_key = ? WHERE provider = ?").run(
- apiKey,
- providerLower
+ const connectionName = existing?.name || providerLower;
+ if (existing && !existing.name) {
+ db.prepare("UPDATE provider_connections SET name = ? WHERE id = ?").run(
+ connectionName,
+ existing.id
);
- log(`API key for ${provider} updated`, "green");
- } else {
- db.prepare(
- "INSERT INTO provider_connections (id, provider, api_key, name, is_active) VALUES (?, ?, ?, ?, 1)"
- ).run(randomUUID(), providerLower, apiKey, provider);
- log(`API key for ${provider} added`, "green");
}
+ upsertApiKeyProviderConnection(db, {
+ provider: providerLower,
+ name: connectionName,
+ apiKey,
+ });
+
+ log(`API key for ${provider} ${existing ? "updated" : "added"}`, "green");
+
db.close();
} catch (err) {
log(`Failed to save key: ${err.message}`, "red");
@@ -1401,8 +1410,7 @@ async function runKeysAdd(args) {
async function runKeysList(args) {
logSection("Configured API Keys");
- const dataDir = resolveConfigPath(".omniroute");
- const dbPath = join(dataDir, "storage.sqlite");
+ const dbPath = resolveStoragePath();
if (!existsSync(dbPath)) {
log("Database not found. Start server first.", "yellow");
@@ -1415,16 +1423,11 @@ async function runKeysList(args) {
const require = createRequire(import.meta.url);
const Database = require("better-sqlite3");
const db = new Database(dbPath);
+ ensureProviderSchema(db);
- const keys = db
- .prepare(
- `
- SELECT provider_id, api_key, enabled
- FROM provider_connections
- WHERE api_key IS NOT NULL AND api_key != ''
- `
- )
- .all();
+ const keys = listProviderConnections(db).filter(
+ (connection) => connection.authType === "apikey" && connection.apiKey
+ );
db.close();
@@ -1432,14 +1435,20 @@ async function runKeysList(args) {
log("No API keys configured", "yellow");
} else {
for (const key of keys) {
+ let rawApiKey = "";
+ try {
+ rawApiKey = getProviderApiKey(key);
+ } catch {
+ rawApiKey = key.apiKey || "";
+ }
const masked =
- key.api_key && key.api_key.length > 8
- ? key.api_key.slice(0, 6) + "***" + key.api_key.slice(-4)
+ rawApiKey && rawApiKey.length > 8
+ ? rawApiKey.slice(0, 6) + "***" + rawApiKey.slice(-4)
: "***";
- const status = key.enabled
+ const status = key.isActive
? colorize("● enabled", "green")
: colorize("○ disabled", "yellow");
- log(` ${key.provider_id.padEnd(20)} ${masked.padEnd(20)} ${status}`);
+ log(` ${key.provider.padEnd(20)} ${masked.padEnd(20)} ${status}`);
}
}
} catch (err) {
@@ -1459,8 +1468,7 @@ async function runKeysRemove(args) {
logSection(`Removing API Key for ${provider}`);
- const dataDir = resolveConfigPath(".omniroute");
- const dbPath = join(dataDir, "storage.sqlite");
+ const dbPath = resolveStoragePath();
if (!existsSync(dbPath)) {
log("Database not found. Start server first.", "red");
@@ -1473,9 +1481,12 @@ async function runKeysRemove(args) {
const require = createRequire(import.meta.url);
const Database = require("better-sqlite3");
const db = new Database(dbPath);
+ ensureProviderSchema(db);
const result = db
- .prepare("DELETE FROM provider_connections WHERE provider_id = ?")
+ .prepare(
+ "DELETE FROM provider_connections WHERE provider = ? AND (auth_type = 'apikey' OR (api_key IS NOT NULL AND api_key != ''))"
+ )
.run(provider.toLowerCase());
if (result.changes > 0) {
diff --git a/open-sse/services/autoCombo/virtualFactory.ts b/open-sse/services/autoCombo/virtualFactory.ts
index d8777fd6f5..0392ddc64f 100644
--- a/open-sse/services/autoCombo/virtualFactory.ts
+++ b/open-sse/services/autoCombo/virtualFactory.ts
@@ -1,4 +1,4 @@
-import { AutoComboConfig, SelectionResult } from "./engine";
+import { AutoComboConfig } from "./engine";
import { MODE_PACKS } from "./modePacks";
import { DEFAULT_WEIGHTS, ScoringWeights } from "./scoring";
import { AutoVariant } from "./autoPrefix";
@@ -12,7 +12,10 @@ interface VirtualFactoryConn extends ConnectionFields {
id: string;
provider: string;
defaultModel?: string;
- oauthExpiresAt?: number | string; // timestamp or ISO string
+ expiresAt?: number | string | null;
+ tokenExpiresAt?: number | string | null;
+ oauthToken?: string | null;
+ oauthExpiresAt?: number | string | null; // legacy timestamp or ISO string
}
export interface VirtualAutoComboCandidate {
@@ -23,38 +26,108 @@ export interface VirtualAutoComboCandidate {
costPer1MTokens: number; // from providerRegistry
}
+type VirtualAutoCombo = AutoComboConfig & {
+ strategy: "auto";
+ models: Array<{
+ id: string;
+ kind: "model";
+ model: string;
+ providerId: string;
+ connectionId: string;
+ weight: number;
+ label: string;
+ }>;
+ autoConfig: {
+ candidatePool: string[];
+ weights: ScoringWeights;
+ explorationRate: number;
+ routingStrategy: string;
+ };
+ config: {
+ auto: {
+ candidatePool: string[];
+ weights: ScoringWeights;
+ explorationRate: number;
+ routingStrategy: string;
+ };
+ };
+};
+
+function toExpiryMs(value: unknown): number | null {
+ if (value === null || value === undefined || value === "") return null;
+
+ const parsed =
+ typeof value === "number"
+ ? value
+ : typeof value === "string" && value.trim().length > 0
+ ? Number(value)
+ : Number.NaN;
+
+ if (Number.isFinite(parsed) && parsed > 0) {
+ return parsed < 1_000_000_000_000 ? parsed * 1000 : parsed;
+ }
+
+ if (typeof value === "string") {
+ const timestamp = new Date(value).getTime();
+ return Number.isFinite(timestamp) ? timestamp : null;
+ }
+
+ return null;
+}
+
+function hasUsableOAuthToken(conn: VirtualFactoryConn): boolean {
+ const token =
+ typeof conn.accessToken === "string" && conn.accessToken.trim().length > 0
+ ? conn.accessToken
+ : typeof conn.oauthToken === "string" && conn.oauthToken.trim().length > 0
+ ? conn.oauthToken
+ : null;
+
+ if (!token) return false;
+
+ const expiryMs =
+ toExpiryMs(conn.tokenExpiresAt) ??
+ toExpiryMs(conn.expiresAt) ??
+ toExpiryMs(conn.oauthExpiresAt);
+
+ return expiryMs === null || expiryMs > Date.now();
+}
+
/**
* Creates a virtual AutoCombo configuration dynamically based on connected providers and a specified variant.
* This combo is not persisted in the DB.
*/
export async function createVirtualAutoCombo(
variant: AutoVariant | undefined
-): Promise<AutoComboConfig> {
+): Promise<VirtualAutoCombo> {
const connections = (await getProviderConnections({ isActive: true })) as VirtualFactoryConn[];
const validConnections = connections.filter((conn) => {
- const hasApiKey = !!conn.apiKey;
- let expiresAt: number;
- if (typeof conn.oauthExpiresAt === "string") {
- expiresAt = new Date(conn.oauthExpiresAt).getTime();
- } else {
- expiresAt = Number(conn.oauthExpiresAt) || 0;
- }
- const hasOAuthToken = !!conn.oauthToken && new Date(expiresAt) > new Date();
- return hasApiKey || hasOAuthToken;
+ const hasApiKey = typeof conn.apiKey === "string" && conn.apiKey.trim().length > 0;
+ return hasApiKey || hasUsableOAuthToken(conn);
});
if (validConnections.length === 0) {
log.warn("AUTO", "No connected providers with valid credentials for virtual auto-combo");
const emptyPool: string[] = [];
+ const autoConfig = {
+ candidatePool: emptyPool,
+ weights: { ...DEFAULT_WEIGHTS },
+ explorationRate: 0.05,
+ routingStrategy: "lkgp",
+ };
return {
id: `virtual-auto-${variant || "default"}`,
name: `Auto ${variant || "Default"}`,
type: "auto" as const,
+ strategy: "auto",
+ models: [],
candidatePool: emptyPool,
- weights: { ...DEFAULT_WEIGHTS },
- explorationRate: 0.05,
- routerStrategy: "lkgp",
+ weights: autoConfig.weights,
+ explorationRate: autoConfig.explorationRate,
+ routerStrategy: autoConfig.routingStrategy,
+ autoConfig,
+ config: { auto: autoConfig },
};
}
@@ -109,15 +182,34 @@ export async function createVirtualAutoCombo(
break;
}
- const pool = candidatePool.map((c) => c.modelStr);
+ const providerPool = [...new Set(candidatePool.map((c) => c.provider))];
+ const models = candidatePool.map((candidate, index) => ({
+ id: `virtual-auto-${variant || "default"}-${index + 1}-${candidate.provider}`,
+ kind: "model" as const,
+ model: candidate.modelStr,
+ providerId: candidate.provider,
+ connectionId: candidate.connectionId,
+ weight: 1,
+ label: candidate.provider,
+ }));
+ const autoConfig = {
+ candidatePool: providerPool,
+ weights,
+ explorationRate,
+ routingStrategy: routerStrategy,
+ };
return {
id: `virtual-auto-${variant || "default"}`,
name: `Auto ${variant || "Default"}`,
type: "auto",
- candidatePool: pool,
- weights: weights,
- explorationRate: explorationRate,
- routerStrategy: routerStrategy,
+ strategy: "auto",
+ models,
+ candidatePool: providerPool,
+ weights,
+ explorationRate,
+ routerStrategy,
+ autoConfig,
+ config: { auto: autoConfig },
};
}
diff --git a/src/app/(dashboard)/dashboard/cloud-agents/page.tsx b/src/app/(dashboard)/dashboard/cloud-agents/page.tsx
index ff803e4a0a..c86aa56235 100644
--- a/src/app/(dashboard)/dashboard/cloud-agents/page.tsx
+++ b/src/app/(dashboard)/dashboard/cloud-agents/page.tsx
@@ -6,15 +6,24 @@ import { useTranslations } from "next-intl";
interface CloudAgentTask {
id: string;
- provider: string;
- status: "pending" | "running" | "waiting_approval" | "completed" | "failed" | "cancelled";
- description: string;
+ providerId: string;
+ status: "queued" | "running" | "awaiting_approval" | "completed" | "failed" | "cancelled";
+ prompt: string;
+ source: {
+ repoName?: string;
+ repoUrl?: string;
+ branch?: string;
+ };
createdAt: string;
updatedAt: string;
- result?: string;
+ result?: Record<string, unknown> | null;
error?: string;
- plan?: string;
- messages: Array<{ role: string; content: string; timestamp: string }>;
+ activities: Array<{
+ id: string;
+ type: "plan" | "command" | "code_change" | "message" | "error" | "completion";
+ content: string;
+ timestamp: string;
+ }>;
}
const CLOUD_AGENTS = [
@@ -50,18 +59,32 @@ export default function CloudAgentsPage() {
const [creating, setCreating] = useState(false);
const [selectedTask, setSelectedTask] = useState<CloudAgentTask | null>(null);
const [newTask, setNewTask] = useState({
- provider: "jules",
- description: "",
+ providerId: "jules",
+ prompt: "",
+ repoName: "",
+ repoUrl: "",
+ branch: "main",
+ autoCreatePr: true,
});
const [messageInput, setMessageInput] = useState("");
const t = useTranslations("cloudAgents");
+ const upsertTask = useCallback((task: CloudAgentTask) => {
+ setTasks((prev) => {
+ const exists = prev.some((current) => current.id === task.id);
+ return exists
+ ? prev.map((current) => (current.id === task.id ? task : current))
+ : [task, ...prev];
+ });
+ setSelectedTask((current) => (current?.id === task.id ? task : current));
+ }, []);
+
const fetchTasks = useCallback(async () => {
try {
const res = await fetch("/api/v1/agents/tasks");
if (res.ok) {
const data = await res.json();
- setTasks(data.tasks || []);
+ setTasks(Array.isArray(data.data) ? data.data : []);
}
} catch (err) {
console.error("Failed to fetch tasks:", err);
@@ -78,18 +101,34 @@ export default function CloudAgentsPage() {
e.preventDefault();
setCreating(true);
try {
+ const source = {
+ repoName: newTask.repoName.trim(),
+ repoUrl: newTask.repoUrl.trim(),
+ ...(newTask.branch.trim() ? { branch: newTask.branch.trim() } : {}),
+ };
const res = await fetch("/api/v1/agents/tasks", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
- provider: newTask.provider,
- description: newTask.description,
+ providerId: newTask.providerId,
+ prompt: newTask.prompt,
+ source,
+ options: {
+ autoCreatePr: newTask.autoCreatePr,
+ },
}),
});
if (res.ok) {
const data = await res.json();
- setTasks((prev) => [data.task, ...prev]);
- setNewTask({ provider: "jules", description: "" });
+ if (data.data) upsertTask(data.data);
+ setNewTask({
+ providerId: "jules",
+ prompt: "",
+ repoName: "",
+ repoUrl: "",
+ branch: "main",
+ autoCreatePr: true,
+ });
}
} catch (err) {
console.error("Failed to create task:", err);
@@ -111,8 +150,7 @@ export default function CloudAgentsPage() {
});
if (res.ok) {
const data = await res.json();
- setSelectedTask(data.task);
- setTasks((prev) => prev.map((task) => (task.id === selectedTask.id ? data.task : task)));
+ if (data.data) upsertTask(data.data);
setMessageInput("");
}
} catch (err) {
@@ -130,8 +168,7 @@ export default function CloudAgentsPage() {
});
if (res.ok) {
const data = await res.json();
- setSelectedTask(data.task);
- setTasks((prev) => prev.map((t) => (t.id === selectedTask.id ? data.task : t)));
+ if (data.data) upsertTask(data.data);
}
} catch (err) {
console.error("Failed to approve plan:", err);
@@ -147,10 +184,7 @@ export default function CloudAgentsPage() {
});
if (res.ok) {
const data = await res.json();
- setTasks((prev) => prev.map((t) => (t.id === taskId ? data.task : t)));
- if (selectedTask?.id === taskId) {
- setSelectedTask(data.task);
- }
+ if (data.data) upsertTask(data.data);
}
} catch (err) {
console.error("Failed to cancel task:", err);
@@ -175,9 +209,9 @@ export default function CloudAgentsPage() {
const getStatusBadge = (status: string) => {
const statusMap: Record<string, { color: string; label: string }> = {
- pending: { color: "bg-zinc-500/10 text-zinc-500", label: t("statusPending") },
+ queued: { color: "bg-zinc-500/10 text-zinc-500", label: t("statusPending") },
running: { color: "bg-blue-500/10 text-blue-500", label: t("statusRunning") },
- waiting_approval: {
+ awaiting_approval: {
color: "bg-amber-500/10 text-amber-600",
label: t("statusWaitingApproval"),
},
@@ -185,7 +219,7 @@ export default function CloudAgentsPage() {
failed: { color: "bg-red-500/10 text-red-500", label: t("statusFailed") },
cancelled: { color: "bg-zinc-500/10 text-zinc-400", label: t("statusCancelled") },
};
- const s = statusMap[status] || statusMap.pending;
+ const s = statusMap[status] || statusMap.queued;
return (
<span
className={`inline-flex items-center gap-1 text-xs px-2 py-0.5 rounded-full font-medium ${s.color}`}
@@ -200,6 +234,16 @@ export default function CloudAgentsPage() {
return CLOUD_AGENTS.find((a) => a.id === providerId) || CLOUD_AGENTS[0];
};
+ const getPlanText = (task: CloudAgentTask) => {
+ return task.activities.find((activity) => activity.type === "plan")?.content || "";
+ };
+
+ const formatResult = (result: CloudAgentTask["result"]) => {
+ if (!result) return "";
+ if (typeof result === "string") return result;
+ return JSON.stringify(result, null, 2);
+ };
+
if (loading) {
return (
<div className="flex flex-col items-center justify-center min-h-[400px] gap-3">
@@ -265,8 +309,8 @@ export default function CloudAgentsPage() {
{t("selectAgent")}
</label>
<select
- value={newTask.provider}
- onChange={(e) => setNewTask({ ...newTask, provider: e.target.value })}
+ value={newTask.providerId}
+ onChange={(e) => setNewTask({ ...newTask, providerId: e.target.value })}
className="w-full rounded-lg border border-border/50 bg-card px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
>
{CLOUD_AGENTS.map((agent) => (
@@ -278,13 +322,49 @@ export default function CloudAgentsPage() {
</div>
</div>
<div>
- <Input
- label={t("taskDescription")}
+ <label className="text-xs font-medium text-text-muted mb-1.5 block">
+ {t("taskDescription")}
+ </label>
+ <textarea
placeholder={t("taskDescriptionPlaceholder")}
- value={newTask.description}
- onChange={(e) => setNewTask({ ...newTask, description: e.target.value })}
+ value={newTask.prompt}
+ onChange={(e) => setNewTask({ ...newTask, prompt: e.target.value })}
+ className="min-h-24 w-full rounded-lg border border-border/50 bg-card px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
+ required
+ />
+ </div>
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
+ <Input
+ label="Repository name"
+ placeholder="omniroute"
+ value={newTask.repoName}
+ onChange={(e) => setNewTask({ ...newTask, repoName: e.target.value })}
required
/>
+ <Input
+ label="Repository URL"
+ placeholder="https://github.com/owner/repo"
+ value={newTask.repoUrl}
+ onChange={(e) => setNewTask({ ...newTask, repoUrl: e.target.value })}
+ required
+ />
+ </div>
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
+ <Input
+ label="Branch"
+ placeholder="main"
+ value={newTask.branch}
+ onChange={(e) => setNewTask({ ...newTask, branch: e.target.value })}
+ />
+ <label className="flex items-center gap-2 text-sm text-text-muted pt-7">
+ <input
+ type="checkbox"
+ checked={newTask.autoCreatePr}
+ onChange={(e) => setNewTask({ ...newTask, autoCreatePr: e.target.checked })}
+ className="h-4 w-4 rounded border-border/60"
+ />
+ Auto-create PR
+ </label>
</div>
<div className="flex justify-end">
<Button type="submit" variant="primary" loading={creating}>
@@ -305,7 +385,7 @@ export default function CloudAgentsPage() {
</div>
) : (
tasks.map((task) => {
- const agent = getAgentInfo(task.provider);
+ const agent = getAgentInfo(task.providerId);
return (
<Card
key={task.id}
@@ -319,7 +399,7 @@ export default function CloudAgentsPage() {
<span className="text-lg">{agent.icon}</span>
<div>
<p className="text-sm font-medium text-text-main line-clamp-1">
- {task.description || t("untitledTask")}
+ {task.prompt || t("untitledTask")}
</p>
<p className="text-xs text-text-muted">
{agent.name} • {new Date(task.createdAt).toLocaleString()}
@@ -340,9 +420,9 @@ export default function CloudAgentsPage() {
<Card className="flex flex-col gap-4">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
- <span className="text-lg">{getAgentInfo(selectedTask.provider).icon}</span>
+ <span className="text-lg">{getAgentInfo(selectedTask.providerId).icon}</span>
<div>
- <p className="font-medium">{getAgentInfo(selectedTask.provider).name}</p>
+ <p className="font-medium">{getAgentInfo(selectedTask.providerId).name}</p>
<p className="text-xs text-text-muted">
{t("created")}: {new Date(selectedTask.createdAt).toLocaleString()}
</p>
@@ -351,7 +431,7 @@ export default function CloudAgentsPage() {
{getStatusBadge(selectedTask.status)}
</div>
- {selectedTask.status === "waiting_approval" && selectedTask.plan && (
+ {selectedTask.status === "awaiting_approval" && getPlanText(selectedTask) && (
<div className="rounded-lg border border-amber-500/20 bg-amber-500/5 p-3">
<div className="flex items-center gap-2 mb-2">
<span className="material-symbols-outlined text-[16px] text-amber-600">
@@ -362,7 +442,7 @@ export default function CloudAgentsPage() {
</span>
</div>
<pre className="text-xs text-text-muted whitespace-pre-wrap bg-black/5 dark:bg-white/5 rounded p-2 max-h-32 overflow-auto">
- {selectedTask.plan}
+ {getPlanText(selectedTask)}
</pre>
<div className="flex gap-2 mt-2">
<Button variant="primary" size="sm" onClick={handleApprovePlan}>
@@ -380,21 +460,21 @@ export default function CloudAgentsPage() {
</div>
)}
- {selectedTask.messages.length > 0 && (
+ {selectedTask.activities.length > 0 && (
<div className="flex flex-col gap-2">
<p className="text-sm font-medium">{t("conversation")}</p>
<div className="flex flex-col gap-2 max-h-64 overflow-auto">
- {selectedTask.messages.map((msg, i) => (
+ {selectedTask.activities.map((activity) => (
<div
- key={i}
+ key={activity.id}
className={`p-2 rounded-lg text-xs ${
- msg.role === "assistant"
+ activity.type === "message" || activity.type === "completion"
? "bg-purple-500/10 text-text-main"
: "bg-surface/40 text-text-main"
}`}
>
- <span className="font-medium capitalize">{msg.role}: </span>
- {msg.content}
+ <span className="font-medium capitalize">{activity.type}: </span>
+ {activity.content}
</div>
))}
</div>
@@ -412,7 +492,7 @@ export default function CloudAgentsPage() {
</span>
</div>
<pre className="text-xs text-text-muted whitespace-pre-wrap">
- {selectedTask.result}
+ {formatResult(selectedTask.result)}
</pre>
</div>
)}
diff --git a/src/app/api/resilience/model-cooldowns/route.ts b/src/app/api/resilience/model-cooldowns/route.ts
index 52fa92da76..df5d3b7b06 100644
--- a/src/app/api/resilience/model-cooldowns/route.ts
+++ b/src/app/api/resilience/model-cooldowns/route.ts
@@ -5,6 +5,7 @@ import {
getAvailabilityReport,
resetAllAvailability,
} from "@/domain/modelAvailability";
+import { requireManagementAuth } from "@/lib/api/requireManagementAuth";
import { validateBody } from "@/shared/validation/helpers";
const deleteCooldownSchema = z
@@ -19,7 +20,10 @@ function getErrorMessage(error: unknown, fallback: string): string {
return error instanceof Error && error.message ? error.message : fallback;
}
-export async function GET() {
+export async function GET(request: Request) {
+ const authError = await requireManagementAuth(request);
+ if (authError) return authError;
+
try {
const items = getAvailabilityReport().sort((a, b) => b.remainingMs - a.remainingMs);
return NextResponse.json({ items });
@@ -33,6 +37,9 @@ export async function GET() {
}
export async function DELETE(request: Request) {
+ const authError = await requireManagementAuth(request);
+ if (authError) return authError;
+
try {
const rawBody = await request.json().catch(() => ({}));
const validation = validateBody(deleteCooldownSchema, rawBody);
diff --git a/src/app/api/v1/agents/tasks/[id]/route.ts b/src/app/api/v1/agents/tasks/[id]/route.ts
index 78ef7dedf0..d81271254c 100644
--- a/src/app/api/v1/agents/tasks/[id]/route.ts
+++ b/src/app/api/v1/agents/tasks/[id]/route.ts
@@ -1,26 +1,24 @@
import { NextRequest, NextResponse } from "next/server";
-import { extractApiKey } from "@/sse/services/auth";
import { getAgent } from "@/lib/cloudAgent/registry";
import {
createCloudAgentTaskTable,
getCloudAgentTaskById,
updateCloudAgentTask,
+ deleteCloudAgentTask,
} from "@/lib/cloudAgent/db";
+import {
+ getCloudAgentCorsHeaders,
+ getCloudAgentCredentials,
+ requireCloudAgentManagementAuth,
+ serializeCloudAgentTask,
+} from "@/lib/cloudAgent/api";
import { z } from "zod";
import pino from "pino";
const logger = pino({ name: "cloud-agents-api" });
-function getCorsHeaders() {
- return {
- "Access-Control-Allow-Origin": "*",
- "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
- "Access-Control-Allow-Headers": "Content-Type, Authorization",
- };
-}
-
export async function OPTIONS() {
- return new NextResponse(null, { headers: getCorsHeaders() });
+ return new NextResponse(null, { headers: getCloudAgentCorsHeaders() });
}
const ApproveSchema = z.object({
@@ -42,25 +40,17 @@ const TaskActionSchema = z.discriminatedUnion("action", [
CancelSchema,
]);
-function apiKeyRequiredResponse() {
+function cloudAgentCredentialsRequiredResponse(providerId: string) {
return NextResponse.json(
- { error: "API key required" },
- { status: 401, headers: getCorsHeaders() }
+ { error: `No active credentials configured for cloud agent provider: ${providerId}` },
+ { status: 400, headers: getCloudAgentCorsHeaders() }
);
}
-function getRequiredApiKey(request: NextRequest) {
- const apiKey = extractApiKey(request);
- if (!apiKey) {
- return { apiKey: null, response: apiKeyRequiredResponse() };
- }
- return { apiKey, response: null };
-}
-
export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
try {
- const auth = getRequiredApiKey(request);
- if (auth.response) return auth.response;
+ const authError = await requireCloudAgentManagementAuth(request);
+ if (authError) return authError;
createCloudAgentTaskTable();
@@ -70,25 +60,28 @@ export async function GET(request: NextRequest, { params }: { params: Promise<{
if (!task) {
return NextResponse.json(
{ error: "Task not found" },
- { status: 404, headers: getCorsHeaders() }
+ { status: 404, headers: getCloudAgentCorsHeaders() }
);
}
const agent = getAgent(task.provider_id);
if (agent && task.external_id) {
try {
- const statusResult = await agent.getStatus(task.external_id, { apiKey: auth.apiKey });
-
- updateCloudAgentTask(id, {
- status: statusResult.status,
- result: statusResult.result ? JSON.stringify(statusResult.result) : null,
- activities: JSON.stringify(statusResult.activities),
- error: statusResult.error || null,
- completed_at:
- statusResult.status === "completed" || statusResult.status === "failed"
- ? new Date().toISOString()
- : null,
- });
+ const credentials = await getCloudAgentCredentials(task.provider_id);
+ if (credentials) {
+ const statusResult = await agent.getStatus(task.external_id, credentials);
+
+ updateCloudAgentTask(id, {
+ status: statusResult.status,
+ result: statusResult.result ? JSON.stringify(statusResult.result) : null,
+ activities: JSON.stringify(statusResult.activities),
+ error: statusResult.error || null,
+ completed_at:
+ statusResult.status === "completed" || statusResult.status === "failed"
+ ? new Date().toISOString()
+ : null,
+ });
+ }
} catch (err) {
console.error("Failed to sync task status:", err);
}
@@ -98,36 +91,22 @@ export async function GET(request: NextRequest, { params }: { params: Promise<{
return NextResponse.json(
{
- data: {
- id: updatedTask!.id,
- providerId: updatedTask!.provider_id,
- externalId: updatedTask!.external_id,
- status: updatedTask!.status,
- prompt: updatedTask!.prompt,
- source: JSON.parse(updatedTask!.source),
- options: JSON.parse(updatedTask!.options),
- result: updatedTask!.result ? JSON.parse(updatedTask!.result) : null,
- activities: JSON.parse(updatedTask!.activities),
- error: updatedTask!.error,
- createdAt: updatedTask!.created_at,
- updatedAt: updatedTask!.updated_at,
- completedAt: updatedTask!.completed_at,
- },
+ data: serializeCloudAgentTask(updatedTask!),
},
- { headers: getCorsHeaders() }
+ { headers: getCloudAgentCorsHeaders() }
);
} catch (error) {
return NextResponse.json(
{ error: error instanceof Error ? error.message : "Unknown error" },
- { status: 500, headers: getCorsHeaders() }
+ { status: 500, headers: getCloudAgentCorsHeaders() }
);
}
}
export async function POST(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
try {
- const auth = getRequiredApiKey(request);
- if (auth.response) return auth.response;
+ const authError = await requireCloudAgentManagementAuth(request);
+ if (authError) return authError;
const { id } = await params;
const body = await request.json();
@@ -135,7 +114,7 @@ export async function POST(request: NextRequest, { params }: { params: Promise<{
if (!validation.success) {
return NextResponse.json(
{ error: "Validation failed", details: validation.error.issues },
- { status: 400, headers: getCorsHeaders() }
+ { status: 400, headers: getCloudAgentCorsHeaders() }
);
}
@@ -145,7 +124,7 @@ export async function POST(request: NextRequest, { params }: { params: Promise<{
if (!task) {
return NextResponse.json(
{ error: "Task not found" },
- { status: 404, headers: getCorsHeaders() }
+ { status: 404, headers: getCloudAgentCorsHeaders() }
);
}
@@ -155,7 +134,7 @@ export async function POST(request: NextRequest, { params }: { params: Promise<{
if (!agent) {
return NextResponse.json(
{ error: "Agent not found" },
- { status: 500, headers: getCorsHeaders() }
+ { status: 500, headers: getCloudAgentCorsHeaders() }
);
}
@@ -163,34 +142,69 @@ export async function POST(request: NextRequest, { params }: { params: Promise<{
if (!task.external_id) {
return NextResponse.json(
{ error: "No external task to approve" },
- { status: 400, headers: getCorsHeaders() }
+ { status: 400, headers: getCloudAgentCorsHeaders() }
);
}
- await agent.approvePlan(task.external_id, { apiKey: auth.apiKey });
+ const credentials = await getCloudAgentCredentials(task.provider_id);
+ if (!credentials) return cloudAgentCredentialsRequiredResponse(task.provider_id);
+ await agent.approvePlan(task.external_id, credentials);
updateCloudAgentTask(id, { status: "running" });
} else if (validated.action === "message") {
if (!task.external_id) {
return NextResponse.json(
{ error: "No external task to message" },
- { status: 400, headers: getCorsHeaders() }
+ { status: 400, headers: getCloudAgentCorsHeaders() }
);
}
- const activity = await agent.sendMessage(task.external_id, validated.message, {
- apiKey: auth.apiKey,
- });
- const activities = JSON.parse(task.activities);
+ const credentials = await getCloudAgentCredentials(task.provider_id);
+ if (!credentials) return cloudAgentCredentialsRequiredResponse(task.provider_id);
+ const activity = await agent.sendMessage(task.external_id, validated.message, credentials);
+ const activities: unknown[] = serializeCloudAgentTask(task).activities;
activities.push(activity);
updateCloudAgentTask(id, { activities: JSON.stringify(activities) });
} else if (validated.action === "cancel") {
updateCloudAgentTask(id, { status: "cancelled" });
}
- return NextResponse.json({ success: true }, { headers: getCorsHeaders() });
+ const updatedTask = getCloudAgentTaskById(id);
+ return NextResponse.json(
+ { success: true, data: updatedTask ? serializeCloudAgentTask(updatedTask) : null },
+ { headers: getCloudAgentCorsHeaders() }
+ );
} catch (error) {
logger.error({ err: error }, "Failed to process task action");
return NextResponse.json(
{ error: error instanceof Error ? error.message : "Unknown error" },
- { status: 500, headers: getCorsHeaders() }
+ { status: 500, headers: getCloudAgentCorsHeaders() }
+ );
+ }
+}
+
+export async function DELETE(
+ request: NextRequest,
+ { params }: { params: Promise<{ id: string }> }
+) {
+ try {
+ const authError = await requireCloudAgentManagementAuth(request);
+ if (authError) return authError;
+
+ createCloudAgentTaskTable();
+
+ const { id } = await params;
+ const task = getCloudAgentTaskById(id);
+ if (!task) {
+ return NextResponse.json(
+ { error: "Task not found" },
+ { status: 404, headers: getCloudAgentCorsHeaders() }
+ );
+ }
+
+ deleteCloudAgentTask(id);
+ return NextResponse.json({ success: true }, { headers: getCloudAgentCorsHeaders() });
+ } catch (error) {
+ return NextResponse.json(
+ { error: error instanceof Error ? error.message : "Unknown error" },
+ { status: 500, headers: getCloudAgentCorsHeaders() }
);
}
}
diff --git a/src/app/api/v1/agents/tasks/route.ts b/src/app/api/v1/agents/tasks/route.ts
index 260edc8a97..614c5b649f 100644
--- a/src/app/api/v1/agents/tasks/route.ts
+++ b/src/app/api/v1/agents/tasks/route.ts
@@ -1,5 +1,4 @@
import { NextRequest, NextResponse } from "next/server";
-import { extractApiKey } from "@/sse/services/auth";
import { getAgent } from "@/lib/cloudAgent/registry";
import {
createCloudAgentTaskTable,
@@ -9,49 +8,38 @@ import {
getCloudAgentTasksByStatus,
deleteCloudAgentTask,
} from "@/lib/cloudAgent/db";
+import {
+ getCloudAgentCorsHeaders,
+ getCloudAgentCredentials,
+ requireCloudAgentManagementAuth,
+ serializeCloudAgentTask,
+} from "@/lib/cloudAgent/api";
import { CreateCloudAgentTaskSchema } from "@/lib/cloudAgent/types";
import pino from "pino";
const logger = pino({ name: "cloud-agents-api" });
-function getCorsHeaders() {
- return {
- "Access-Control-Allow-Origin": "*",
- "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
- "Access-Control-Allow-Headers": "Content-Type, Authorization",
- };
-}
-
-function apiKeyRequiredResponse() {
- return NextResponse.json(
- { error: "API key required" },
- { status: 401, headers: getCorsHeaders() }
- );
-}
-
-function getRequiredApiKey(request: NextRequest) {
- const apiKey = extractApiKey(request);
- if (!apiKey) {
- return { apiKey: null, response: apiKeyRequiredResponse() };
- }
- return { apiKey, response: null };
+function getLimit(value: string | null): number {
+ const parsed = Number.parseInt(value || "50", 10);
+ if (!Number.isFinite(parsed)) return 50;
+ return Math.max(1, Math.min(parsed, 500));
}
export async function OPTIONS() {
- return new NextResponse(null, { headers: getCorsHeaders() });
+ return new NextResponse(null, { headers: getCloudAgentCorsHeaders() });
}
export async function GET(request: NextRequest) {
try {
- const auth = getRequiredApiKey(request);
- if (auth.response) return auth.response;
+ const authError = await requireCloudAgentManagementAuth(request);
+ if (authError) return authError;
createCloudAgentTaskTable();
const { searchParams } = new URL(request.url);
const providerId = searchParams.get("provider");
const status = searchParams.get("status");
- const limit = parseInt(searchParams.get("limit") || "50", 10);
+ const limit = getLimit(searchParams.get("limit"));
let tasks;
if (providerId) {
@@ -64,43 +52,29 @@ export async function GET(request: NextRequest) {
return NextResponse.json(
{
- data: tasks.map((t) => ({
- id: t.id,
- providerId: t.provider_id,
- externalId: t.external_id,
- status: t.status,
- prompt: t.prompt,
- source: JSON.parse(t.source),
- options: JSON.parse(t.options),
- result: t.result ? JSON.parse(t.result) : null,
- activities: JSON.parse(t.activities),
- error: t.error,
- createdAt: t.created_at,
- updatedAt: t.updated_at,
- completedAt: t.completed_at,
- })),
+ data: tasks.map(serializeCloudAgentTask),
},
- { headers: getCorsHeaders() }
+ { headers: getCloudAgentCorsHeaders() }
);
} catch (error) {
return NextResponse.json(
{ error: error instanceof Error ? error.message : "Unknown error" },
- { status: 500, headers: getCorsHeaders() }
+ { status: 500, headers: getCloudAgentCorsHeaders() }
);
}
}
export async function POST(request: NextRequest) {
try {
- const auth = getRequiredApiKey(request);
- if (auth.response) return auth.response;
+ const authError = await requireCloudAgentManagementAuth(request);
+ if (authError) return authError;
const body = await request.json();
const validation = CreateCloudAgentTaskSchema.safeParse(body);
if (!validation.success) {
return NextResponse.json(
{ error: "Validation failed", details: validation.error.issues },
- { status: 400, headers: getCorsHeaders() }
+ { status: 400, headers: getCloudAgentCorsHeaders() }
);
}
@@ -110,7 +84,17 @@ export async function POST(request: NextRequest) {
if (!agent) {
return NextResponse.json(
{ error: `Unknown provider: ${validated.providerId}` },
- { status: 400, headers: getCorsHeaders() }
+ { status: 400, headers: getCloudAgentCorsHeaders() }
+ );
+ }
+
+ const credentials = await getCloudAgentCredentials(validated.providerId);
+ if (!credentials) {
+ return NextResponse.json(
+ {
+ error: `No active credentials configured for cloud agent provider: ${validated.providerId}`,
+ },
+ { status: 400, headers: getCloudAgentCorsHeaders() }
);
}
@@ -120,7 +104,7 @@ export async function POST(request: NextRequest) {
source: validated.source,
options: validated.options || {},
},
- { apiKey: auth.apiKey }
+ credentials
);
createCloudAgentTaskTable();
@@ -153,21 +137,21 @@ export async function POST(request: NextRequest) {
createdAt: task.createdAt,
},
},
- { status: 201, headers: getCorsHeaders() }
+ { status: 201, headers: getCloudAgentCorsHeaders() }
);
} catch (error) {
logger.error({ err: error }, "Failed to create cloud agent task");
return NextResponse.json(
{ error: error instanceof Error ? error.message : "Unknown error" },
- { status: 500, headers: getCorsHeaders() }
+ { status: 500, headers: getCloudAgentCorsHeaders() }
);
}
}
export async function DELETE(request: NextRequest) {
try {
- const auth = getRequiredApiKey(request);
- if (auth.response) return auth.response;
+ const authError = await requireCloudAgentManagementAuth(request);
+ if (authError) return authError;
createCloudAgentTaskTable();
@@ -177,17 +161,17 @@ export async function DELETE(request: NextRequest) {
if (!taskId) {
return NextResponse.json(
{ error: "Task ID required" },
- { status: 400, headers: getCorsHeaders() }
+ { status: 400, headers: getCloudAgentCorsHeaders() }
);
}
deleteCloudAgentTask(taskId);
- return NextResponse.json({ success: true }, { headers: getCorsHeaders() });
+ return NextResponse.json({ success: true }, { headers: getCloudAgentCorsHeaders() });
} catch (error) {
return NextResponse.json(
{ error: error instanceof Error ? error.message : "Unknown error" },
- { status: 500, headers: getCorsHeaders() }
+ { status: 500, headers: getCloudAgentCorsHeaders() }
);
}
}
diff --git a/src/lib/cloudAgent/api.ts b/src/lib/cloudAgent/api.ts
new file mode 100644
index 0000000000..01ca2cd8d7
--- /dev/null
+++ b/src/lib/cloudAgent/api.ts
@@ -0,0 +1,84 @@
+import { requireManagementAuth } from "@/lib/api/requireManagementAuth";
+import { getProviderConnections } from "@/lib/db/providers";
+import type { AgentCredentials } from "./baseAgent.ts";
+import type { CloudAgentTaskRow } from "./db.ts";
+
+type JsonRecord = Record<string, unknown>;
+
+export function getCloudAgentCorsHeaders() {
+ return {
+ "Access-Control-Allow-Origin": "*",
+ "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
+ "Access-Control-Allow-Headers": "Content-Type, Authorization",
+ };
+}
+
+export function withCloudAgentCors(response: Response): Response {
+ const headers = new Headers(response.headers);
+ for (const [key, value] of Object.entries(getCloudAgentCorsHeaders())) {
+ headers.set(key, value);
+ }
+
+ return new Response(response.body, {
+ status: response.status,
+ statusText: response.statusText,
+ headers,
+ });
+}
+
+export async function requireCloudAgentManagementAuth(request: Request): Promise<Response | null> {
+ const authError = await requireManagementAuth(request);
+ return authError ? withCloudAgentCors(authError) : null;
+}
+
+function parseJson<T>(value: string | null | undefined, fallback: T): T {
+ if (!value) return fallback;
+ try {
+ return JSON.parse(value) as T;
+ } catch {
+ return fallback;
+ }
+}
+
+export function serializeCloudAgentTask(task: CloudAgentTaskRow) {
+ return {
+ id: task.id,
+ providerId: task.provider_id,
+ externalId: task.external_id,
+ status: task.status,
+ prompt: task.prompt,
+ source: parseJson<JsonRecord>(task.source, {}),
+ options: parseJson<JsonRecord>(task.options, {}),
+ result: task.result ? parseJson<JsonRecord>(task.result, {}) : null,
+ activities: parseJson<JsonRecord[]>(task.activities, []),
+ error: task.error,
+ createdAt: task.created_at,
+ updatedAt: task.updated_at,
+ completedAt: task.completed_at,
+ };
+}
+
+function getConnectionToken(connection: JsonRecord): string | null {
+ const apiKey = typeof connection.apiKey === "string" ? connection.apiKey.trim() : "";
+ if (apiKey) return apiKey;
+
+ const accessToken =
+ typeof connection.accessToken === "string" ? connection.accessToken.trim() : "";
+ return accessToken || null;
+}
+
+export async function getCloudAgentCredentials(
+ providerId: string
+): Promise<AgentCredentials | null> {
+ const connections = (await getProviderConnections({
+ provider: providerId,
+ isActive: true,
+ })) as JsonRecord[];
+
+ for (const connection of connections) {
+ const token = getConnectionToken(connection);
+ if (token) return { apiKey: token };
+ }
+
+ return null;
+}
diff --git a/tests/unit/cli-keys-command.test.ts b/tests/unit/cli-keys-command.test.ts
new file mode 100644
index 0000000000..c1b08bc284
--- /dev/null
+++ b/tests/unit/cli-keys-command.test.ts
@@ -0,0 +1,92 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import Database from "better-sqlite3";
+
+const ORIGINAL_DATA_DIR = process.env.DATA_DIR;
+const ORIGINAL_STORAGE_ENCRYPTION_KEY = process.env.STORAGE_ENCRYPTION_KEY;
+const ORIGINAL_FETCH = globalThis.fetch;
+
+interface ProviderConnectionRow {
+ provider: string;
+ auth_type: string;
+ name: string;
+ api_key: string;
+ is_active: number;
+ created_at: string;
+ updated_at: string;
+}
+
+interface CountRow {
+ count: number;
+}
+
+function createTempDataDir() {
+ return fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-cli-keys-"));
+}
+
+async function withCliKeysEnv(fn: (dataDir: string, dbPath: string) => Promise<void>) {
+ const dataDir = createTempDataDir();
+ const dbPath = path.join(dataDir, "storage.sqlite");
+ process.env.DATA_DIR = dataDir;
+ delete process.env.STORAGE_ENCRYPTION_KEY;
+ globalThis.fetch = (async () => {
+ throw new Error("server offline");
+ }) as typeof fetch;
+
+ const originalLog = console.log;
+ console.log = () => {};
+
+ try {
+ new Database(dbPath).close();
+ await fn(dataDir, dbPath);
+ } finally {
+ console.log = originalLog;
+ globalThis.fetch = ORIGINAL_FETCH;
+ fs.rmSync(dataDir, { recursive: true, force: true });
+
+ if (ORIGINAL_DATA_DIR === undefined) delete process.env.DATA_DIR;
+ else process.env.DATA_DIR = ORIGINAL_DATA_DIR;
+
+ if (ORIGINAL_STORAGE_ENCRYPTION_KEY === undefined) delete process.env.STORAGE_ENCRYPTION_KEY;
+ else process.env.STORAGE_ENCRYPTION_KEY = ORIGINAL_STORAGE_ENCRYPTION_KEY;
+ }
+}
+
+test("legacy keys command writes and removes provider_connections with the real schema", async () => {
+ await withCliKeysEnv(async (_dataDir, dbPath) => {
+ const { runSubcommand } = await import("../../bin/cli-commands.mjs");
+
+ await runSubcommand("keys", ["add", "openai", "sk-test-cli-key"]);
+
+ let db = new Database(dbPath);
+ let row = db
+ .prepare(
+ "SELECT provider, auth_type, name, api_key, is_active, created_at, updated_at FROM provider_connections WHERE provider = ?"
+ )
+ .get("openai") as ProviderConnectionRow | undefined;
+ db.close();
+
+ assert.ok(row);
+ assert.equal(row.provider, "openai");
+ assert.equal(row.auth_type, "apikey");
+ assert.equal(row.name, "openai");
+ assert.equal(row.api_key, "sk-test-cli-key");
+ assert.equal(row.is_active, 1);
+ assert.ok(row.created_at);
+ assert.ok(row.updated_at);
+
+ await runSubcommand("keys", ["list"]);
+ await runSubcommand("keys", ["remove", "openai"]);
+
+ db = new Database(dbPath);
+ const countRow = db
+ .prepare("SELECT COUNT(*) AS count FROM provider_connections WHERE provider = ?")
+ .get("openai") as CountRow;
+ db.close();
+
+ assert.equal(countRow.count, 0);
+ });
+});
diff --git a/tests/unit/cloud-agent-tasks-route-auth.test.ts b/tests/unit/cloud-agent-tasks-route-auth.test.ts
new file mode 100644
index 0000000000..c23fe9366b
--- /dev/null
+++ b/tests/unit/cloud-agent-tasks-route-auth.test.ts
@@ -0,0 +1,77 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { makeManagementSessionRequest } from "../helpers/managementSession.ts";
+
+const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-cloud-agent-auth-"));
+const ORIGINAL_DATA_DIR = process.env.DATA_DIR;
+const ORIGINAL_INITIAL_PASSWORD = process.env.INITIAL_PASSWORD;
+const ORIGINAL_JWT_SECRET = process.env.JWT_SECRET;
+
+process.env.DATA_DIR = TEST_DATA_DIR;
+
+const core = await import("../../src/lib/db/core.ts");
+const settingsDb = await import("../../src/lib/db/settings.ts");
+const route = await import("../../src/app/api/v1/agents/tasks/route.ts");
+
+type TasksGetRequest = Parameters<typeof route.GET>[0];
+type ErrorBody = { error: { message: string } };
+
+async function resetStorage() {
+ core.resetDbInstance();
+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
+ fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
+}
+
+async function enableManagementAuth() {
+ process.env.INITIAL_PASSWORD = "cloud-agent-password";
+ await settingsDb.updateSettings({ requireLogin: true, password: "" });
+}
+
+test.beforeEach(async () => {
+ await resetStorage();
+ await enableManagementAuth();
+});
+
+test.after(async () => {
+ await resetStorage();
+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
+
+ if (ORIGINAL_DATA_DIR === undefined) delete process.env.DATA_DIR;
+ else process.env.DATA_DIR = ORIGINAL_DATA_DIR;
+
+ if (ORIGINAL_INITIAL_PASSWORD === undefined) delete process.env.INITIAL_PASSWORD;
+ else process.env.INITIAL_PASSWORD = ORIGINAL_INITIAL_PASSWORD;
+
+ if (ORIGINAL_JWT_SECRET === undefined) delete process.env.JWT_SECRET;
+ else process.env.JWT_SECRET = ORIGINAL_JWT_SECRET;
+});
+
+test("cloud agent task list requires management auth when auth is enabled", async () => {
+ const unauthenticated = await route.GET(
+ new Request("http://localhost/api/v1/agents/tasks") as TasksGetRequest
+ );
+ const invalidToken = await route.GET(
+ new Request("http://localhost/api/v1/agents/tasks", {
+ headers: { authorization: "Bearer anything" },
+ }) as TasksGetRequest
+ );
+ const authenticated = await route.GET(
+ (await makeManagementSessionRequest("http://localhost/api/v1/agents/tasks")) as TasksGetRequest
+ );
+
+ assert.equal(unauthenticated.status, 401);
+ assert.equal(
+ ((await unauthenticated.json()) as ErrorBody).error.message,
+ "Authentication required"
+ );
+ assert.equal(invalidToken.status, 403);
+ assert.equal(
+ ((await invalidToken.json()) as ErrorBody).error.message,
+ "Invalid management token"
+ );
+ assert.equal(authenticated.status, 200);
+ assert.deepEqual(await authenticated.json(), { data: [] });
+});
diff --git a/tests/unit/model-cooldowns-route-auth.test.ts b/tests/unit/model-cooldowns-route-auth.test.ts
new file mode 100644
index 0000000000..77ebf02ea4
--- /dev/null
+++ b/tests/unit/model-cooldowns-route-auth.test.ts
@@ -0,0 +1,94 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { makeManagementSessionRequest } from "../helpers/managementSession.ts";
+
+const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-cooldown-auth-"));
+const ORIGINAL_DATA_DIR = process.env.DATA_DIR;
+const ORIGINAL_INITIAL_PASSWORD = process.env.INITIAL_PASSWORD;
+const ORIGINAL_JWT_SECRET = process.env.JWT_SECRET;
+
+process.env.DATA_DIR = TEST_DATA_DIR;
+
+const core = await import("../../src/lib/db/core.ts");
+const settingsDb = await import("../../src/lib/db/settings.ts");
+const route = await import("../../src/app/api/resilience/model-cooldowns/route.ts");
+const modelAvailability = await import("../../src/domain/modelAvailability.ts");
+const accountFallback = await import("@omniroute/open-sse/services/accountFallback");
+
+const { getAvailabilityReport } = modelAvailability;
+const { clearModelLock, lockModel } = accountFallback;
+
+async function resetStorage() {
+ core.resetDbInstance();
+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
+ fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
+}
+
+async function enableManagementAuth() {
+ process.env.INITIAL_PASSWORD = "cooldown-password";
+ await settingsDb.updateSettings({ requireLogin: true, password: "" });
+}
+
+test.beforeEach(async () => {
+ clearModelLock("cooldown-auth-provider", "cooldown-auth-conn", "cooldown-auth-model");
+ await resetStorage();
+ await enableManagementAuth();
+});
+
+test.after(async () => {
+ clearModelLock("cooldown-auth-provider", "cooldown-auth-conn", "cooldown-auth-model");
+ await resetStorage();
+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
+
+ if (ORIGINAL_DATA_DIR === undefined) delete process.env.DATA_DIR;
+ else process.env.DATA_DIR = ORIGINAL_DATA_DIR;
+
+ if (ORIGINAL_INITIAL_PASSWORD === undefined) delete process.env.INITIAL_PASSWORD;
+ else process.env.INITIAL_PASSWORD = ORIGINAL_INITIAL_PASSWORD;
+
+ if (ORIGINAL_JWT_SECRET === undefined) delete process.env.JWT_SECRET;
+ else process.env.JWT_SECRET = ORIGINAL_JWT_SECRET;
+});
+
+test("model cooldown reset requires management auth", async () => {
+ lockModel(
+ "cooldown-auth-provider",
+ "cooldown-auth-conn",
+ "cooldown-auth-model",
+ "quota_exhausted",
+ 60_000,
+ {}
+ );
+
+ const unauthenticated = await route.DELETE(
+ new Request("http://localhost/api/resilience/model-cooldowns", {
+ method: "DELETE",
+ body: JSON.stringify({ all: true }),
+ })
+ );
+
+ assert.equal(unauthenticated.status, 401);
+ assert.ok(
+ getAvailabilityReport().some(
+ (entry) =>
+ entry.provider === "cooldown-auth-provider" && entry.model === "cooldown-auth-model"
+ )
+ );
+
+ const authenticated = await route.DELETE(
+ await makeManagementSessionRequest("http://localhost/api/resilience/model-cooldowns", {
+ method: "DELETE",
+ body: { all: true },
+ })
+ );
+
+ assert.equal(authenticated.status, 200);
+ assert.deepEqual(await authenticated.json(), { ok: true, clearedAll: true });
+ assert.equal(
+ getAvailabilityReport().some((entry) => entry.provider === "cooldown-auth-provider"),
+ false
+ );
+});
diff --git a/tests/unit/virtual-auto-combo.test.ts b/tests/unit/virtual-auto-combo.test.ts
new file mode 100644
index 0000000000..e98c392843
--- /dev/null
+++ b/tests/unit/virtual-auto-combo.test.ts
@@ -0,0 +1,75 @@
+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-virtual-auto-"));
+const ORIGINAL_DATA_DIR = process.env.DATA_DIR;
+
+process.env.DATA_DIR = TEST_DATA_DIR;
+
+const core = await import("../../src/lib/db/core.ts");
+const providersDb = await import("../../src/lib/db/providers.ts");
+const virtualFactory = await import("../../open-sse/services/autoCombo/virtualFactory.ts");
+
+type VirtualComboResult = Awaited<ReturnType<typeof virtualFactory.createVirtualAutoCombo>>;
+
+async function resetStorage() {
+ core.resetDbInstance();
+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
+ fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
+}
+
+test.beforeEach(async () => {
+ await resetStorage();
+});
+
+test.after(async () => {
+ await resetStorage();
+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
+
+ if (ORIGINAL_DATA_DIR === undefined) {
+ delete process.env.DATA_DIR;
+ } else {
+ process.env.DATA_DIR = ORIGINAL_DATA_DIR;
+ }
+});
+
+test("createVirtualAutoCombo returns an executable auto combo for API-key connections", async () => {
+ await providersDb.createProviderConnection({
+ provider: "openai",
+ authType: "apikey",
+ name: "OpenAI",
+ apiKey: "sk-test-openai",
+ defaultModel: "gpt-4o-mini",
+ });
+
+ const combo: VirtualComboResult = await virtualFactory.createVirtualAutoCombo("fast");
+
+ assert.equal(combo.strategy, "auto");
+ assert.equal(combo.models.length, 1);
+ assert.equal(combo.models[0].kind, "model");
+ assert.equal(combo.models[0].model, "openai/gpt-4o-mini");
+ assert.equal(combo.models[0].providerId, "openai");
+ assert.equal(combo.autoConfig.routingStrategy, "lkgp");
+ assert.deepEqual(combo.autoConfig.candidatePool, ["openai"]);
+});
+
+test("createVirtualAutoCombo includes OAuth accessToken connections with real expiry fields", async () => {
+ await providersDb.createProviderConnection({
+ provider: "anthropic",
+ authType: "oauth",
+ email: "[email protected]",
+ accessToken: "oauth-access-token",
+ tokenExpiresAt: new Date(Date.now() + 60_000).toISOString(),
+ defaultModel: "claude-sonnet-4-5",
+ });
+
+ const combo: VirtualComboResult = await virtualFactory.createVirtualAutoCombo("coding");
+
+ assert.equal(combo.strategy, "auto");
+ assert.equal(combo.models.length, 1);
+ assert.equal(combo.models[0].model, "anthropic/claude-sonnet-4-5");
+ assert.deepEqual(combo.autoConfig.candidatePool, ["anthropic"]);
+});