Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors
TypeScript a2aai-agentsai-gatewayanthropicclaudeclaude-codeclinecodexcopilotcursordeepseekfree-aigeminikimillm-gatewaymcpopenaiopenai-proxyqwentoken-saver
fix: replace unit test with integration test for proactive context compression (#1378)
Paijo0357a18cead8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 05d84e3deb..8c065678f6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -15,11 +15,27 @@- **feat(i18n):** Add internationalization support for combo features and dashboard components; sync translations across 31 keys (#1318)- **feat(providers):** Add Claude Opus 4.7 to Claude Code OAuth models natively with extended context and caching (#1347)- **feat(core):** Add stopSequences support and expand tool definitions to include Google Search capabilities-- **security:** Resolve GitHub CodeQL scan alerts and enforce deep SSRF mitigations+- **feat(auth):** Enforce dashboard session authentication on all management API routes, preventing unauthenticated access to configuration endpoints+- **feat(runtime):** Add hot-reloadable guardrails and model diagnostics for real-time rule evaluation without restarts+- **feat(core):** Add payload rules, tag-based routing, and scheduled budget systems for fine-grained request governance+- **feat(providers):** Expose Antigravity preview model aliases and Gemini CLI onboarding flow for first-time setup+- **feat(antigravity):** Add client model aliases and thoughtSignature bypass modes for Antigravity OAuth connections+- **feat(providers):** Expand image provider registry with extended model support including SD3.5, FLUX, and DALL-E 3 HD configurations+- **feat(combos):** Add new routing strategies and full i18n support for agent features section across 31 languages++### 🔒 Security++- **security:** Resolve 18 GitHub CodeQL scan alerts including ReDoS, incomplete sanitization, and bad HTML filtering regexp patterns+- **fix(auth):** Seal privilege escalation vector by enforcing JWT session checking exclusively on `/api/keys` management endpoints (#1353)+- **fix(providers):** Resolve Codex token refresh race condition via mutex `getAccessToken` preventing `refresh_token_reused` Auth0 revocations### 🔧 Maintenance & Architecture- **refactor(core):** Split CLI runner and decouple migration engine for extensibility (#1358)+- **refactor(audit):** Rewire audit dashboard from dead in-memory `configAudit` store to live SQLite `audit_log` table — 331+ hidden compliance entries now visible in `/dashboard/audit`+- **build(deps):** Bump `softprops/action-gh-release` from v2 to v3+- **ci:** Bump GitHub Actions CI node-version to Node.js 24 natively+- **fix(types):** Resolve TypeScript compilation errors in `claudeCodeCompatible.ts` (type predicates, `cache_control` index access) and `proxyFetch.ts` (`signal` nullability)### 🐛 Bug Fixes@@ -29,8 +45,6 @@- **fix(mcp):** Checkpoint and close MCP audit SQLite database safely on process signals and shutdown (#1348)- **fix(mcp):** Fully decouple MCP audit SQLite connection caching via globalThis to fix unhandled teardown in standalone Next.js chunks (#1349)- **fix(cli):** Avoid creating app router directory during postinstall initialization on non-built source trees (#1351)-- **fix(providers):** Resolve token refresh race condition causing Codex accounts to be erroneously flagged with `refresh_token_reused` by Auth0-- **fix(auth):** Seal privilege escalation vector by enforcing JWT session checking exclusively on `/api/keys` management endpoints (#1353)- **fix(codex):** Correctly translate `system` role to `developer` in input array to unlock GPT-5 automatic prompt caching (#1346)- **fix(core):** Pass client headers to executor in chatCore (#1335)- **fix(providers):** Separate test batch calls and ignore unknown connections@@ -38,11 +52,18 @@- **fix(db):** Preserve key_value settings (dashboard passwords, saved aliases) across DB heuristic recreation cycles (#1333)- **fix(routing):** Allow combo fallback to cascade context overflow 400 errors instead of immediate aborts (#1331)- **fix(core):** Resolve thinking leaks, consecutive roles, and missing thoughtSignatures for Antigravity translator (#1316)+- **fix(translator):** Only apply thoughtSignature to the first `functionCall` part in Gemini parallel tool calls, preventing duplicate signatures- **fix(providers):** Default to batch testing execution blocks for web, search, and audio modalities to prevent connection timeouts- **fix(cli):** Resolve Node 22 TS entrypoint incompatibility by using esbuild compilation (#1315)- **fix(chat):** Preserve max_output_tokens for Responses API targets in chatCore sanitization (#1313)- **fix(api):** API Manager usage stats showing 0 for all registered keys (#1310)+- **fix(api):** Support image-only models in catalog and allow authless search providers to bypass validation requirements+- **fix(routes):** Require prompts for media generation requests (`/images`, `/videos`, `/music`), returning 400 on missing payloads- **fix(dashboard):** Auto-scroll ActivityHeatmap to show current date (#1309)+- **fix(dashboard):** Restore horizontal layout with `w-max` wrapper in heatmap components+- **fix(i18n):** Update `nodeIncompatibleHint` to recommend Node 24 LTS across all 31 languages+- **fix(i18n):** Add Chinese i18n support to remaining dashboard components (`Loading.tsx`, `DataTable`, etc.)+- **fix(requestLogger):** Add missing `cacheSource` and `tps` columns to i18n log detail views## [3.6.6] — 2026-04-15diff --git a/bin/nodeRuntimeSupport.mjs b/bin/nodeRuntimeSupport.mjsindex ea6c66d8b5..8c203f0722 100644--- a/bin/nodeRuntimeSupport.mjs+++ b/bin/nodeRuntimeSupport.mjs@@ -3,11 +3,13 @@export const SECURE_NODE_LINES = Object.freeze([Object.freeze({ major: 20, minor: 20, patch: 2 }),Object.freeze({ major: 22, minor: 22, patch: 2 }),+ Object.freeze({ major: 24, minor: 0, patch: 0 }),]);-export const RECOMMENDED_NODE_VERSION = "22.22.2";-export const SUPPORTED_NODE_RANGE = ">=20.20.2 <21 || >=22.22.2 <23";-export const SUPPORTED_NODE_DISPLAY = "Node.js 20.20.2+ (20.x LTS) or 22.22.2+ (22.x LTS)";+export const RECOMMENDED_NODE_VERSION = "24.14.1";+export const SUPPORTED_NODE_RANGE = ">=20.20.2 <21 || >=22.22.2 <23 || >=24.0.0 <25";+export const SUPPORTED_NODE_DISPLAY =+ "Node.js 20.20.2+ (20.x LTS), 22.22.2+ (22.x LTS), or 24.0.0+ (24.x LTS)";function formatVersion(version) {return `${version.major}.${version.minor}.${version.patch}`;@@ -50,8 +52,8 @@ export function getNodeRuntimeSupport(version = process.versions.node) {reason = "supported";} else if (secureFloor) {reason = "below-security-floor";- } else if (parsed.major >= 24) {- reason = "native-addon-incompatible";+ } else if (parsed.major >= 25) {+ reason = "unreleased-major";}return {@@ -73,8 +75,8 @@ export function getNodeRuntimeWarning(version = process.versions.node) {return `Node.js ${support.nodeVersion} is below the patched minimum ${support.minimumSecureVersion} for this LTS line.`;}- if (support.reason === "native-addon-incompatible") {- return `Node.js ${support.nodeVersion} is outside the supported LTS lines and may fail at runtime because better-sqlite3 does not support Node.js 24+ here.`;+ if (support.reason === "unreleased-major") {+ return `Node.js ${support.nodeVersion} is outside the supported LTS lines. OmniRoute currently supports Node.js 20.x, 22.x, and 24.x.`;}return `Node.js ${support.nodeVersion} is outside OmniRoute's approved secure runtime policy.`;diff --git a/open-sse/config/imageRegistry.ts b/open-sse/config/imageRegistry.tsindex f5df635ec5..f33f8e2955 100644--- a/open-sse/config/imageRegistry.ts+++ b/open-sse/config/imageRegistry.ts@@ -493,3 +493,31 @@ export function getAllImageModels() {export function getImageModelAliases() {return IMAGE_MODEL_ALIASES;}++export function getImageModelEntry(modelStr) {+ if (!modelStr) return null;++ const alias = IMAGE_MODEL_ALIASES[modelStr];+ if (alias) {+ const modelConfig = findImageModelConfig(alias.provider, alias.model);+ return {+ provider: alias.provider,+ model: alias.model,+ inputModalities: alias.inputModalities || modelConfig?.inputModalities || ["text"],+ description: alias.description || modelConfig?.description || undefined,+ };+ }++ const { provider, model } = parseImageModel(modelStr);+ if (!provider || !model) return null;++ const modelConfig = findImageModelConfig(provider, model);+ if (!modelConfig) return null;++ return {+ provider,+ model,+ inputModalities: modelConfig.inputModalities || ["text"],+ description: modelConfig.description || undefined,+ };+}diff --git a/open-sse/executors/perplexity-web.ts b/open-sse/executors/perplexity-web.tsindex fd270fe055..a167136ee2 100644--- a/open-sse/executors/perplexity-web.ts+++ b/open-sse/executors/perplexity-web.ts@@ -33,8 +33,6 @@ const CITATION_RE = /\[\d+\]/g;const GROK_TAG_RE = /<grok:[^>]*>.*?<\/grok:[^>]*>/gs;const GROK_SELF_RE = /<grok:[^>]*\/>/g;const XML_DECL_RE = /<[?]xml[^?]*[?]>/g;-const SCRIPT_RE = /<script\b[^>]*>.*?<\/script>/gis;-const SCRIPT_TAG_RE = /<\/?script\b[^>]*>/gi;const RESPONSE_TAG_RE = /<\/?response\b[^>]*>/gi;const MULTI_SPACE = / {2,}/g;const MULTI_NL = /\n{3,}/g;@@ -109,8 +107,6 @@ function cleanResponse(text: string, strip = true): string {t = t.replace(GROK_TAG_RE, "");t = t.replace(GROK_SELF_RE, "");t = t.replace(RESPONSE_TAG_RE, "");- t = t.replace(SCRIPT_RE, ""); // lgtm[js/incomplete-multi-character-sanitization]- t = t.replace(SCRIPT_TAG_RE, ""); // lgtm[js/incomplete-multi-character-sanitization]if (strip) {t = t.replace(MULTI_SPACE, " ");t = t.replace(MULTI_NL, "\n\n");diff --git a/open-sse/handlers/chatCore.ts b/open-sse/handlers/chatCore.tsindex 13693d0560..a3d8e48378 100644--- a/open-sse/handlers/chatCore.ts+++ b/open-sse/handlers/chatCore.ts@@ -1452,12 +1452,20 @@ export async function handleChatCore({}}+ // ── Proactive Context Compression (Phase 4) ──+ // Check if context exceeds 85% of limit and compress proactively before sending to provider.+ // This prevents "prompt too long" errors for large-but-not-full contexts.if (translatedBody && translatedBody.messages && Array.isArray(translatedBody.messages)) {const estimatedTokens = estimateTokens(JSON.stringify(translatedBody.messages));const contextLimit = getTokenLimit(provider, effectiveModel);const COMPRESSION_THRESHOLD = 0.85;const threshold = Math.floor(contextLimit * COMPRESSION_THRESHOLD);+ log?.debug?.(+ "CONTEXT",+ `Checking compression: ${estimatedTokens} tokens vs ${threshold} threshold (${contextLimit} limit)`+ );+if (estimatedTokens > threshold) {log?.info?.("CONTEXT",@@ -1468,6 +1476,7 @@ export async function handleChatCore({provider,model: effectiveModel,maxTokens: contextLimit,+ reserveTokens: 0,});if (compressionResult.compressed) {@@ -1495,8 +1504,15 @@ export async function handleChatCore({layers: "layers" in stats ? stats.layers : undefined,},});+ } else {+ log?.debug?.("CONTEXT", `Compression not applied: context already fits within target`);}}+ } else {+ log?.debug?.(+ "CONTEXT",+ `Skipping compression check: translatedBody=${!!translatedBody}, messages=${!!translatedBody?.messages}, isArray=${Array.isArray(translatedBody?.messages)}`+ );}// Resolve executor with optional upstream proxy (CLIProxyAPI) routing.@@ -1840,7 +1856,8 @@ export async function handleChatCore({const newCredentials = (await refreshWithRetry(() => executor.refreshCredentials(credentials, log),3,- log+ log,+ provider // Explicitly pass the provider to avoid universally tripping the "unknown" circuit breaker)) as null | {accessToken?: string;copilotToken?: string;diff --git a/open-sse/handlers/responseSanitizer.ts b/open-sse/handlers/responseSanitizer.tsindex 94612cfee9..aa2c0f1e9d 100644--- a/open-sse/handlers/responseSanitizer.ts+++ b/open-sse/handlers/responseSanitizer.ts@@ -464,7 +464,7 @@ function sanitizeResponsesOutputItem(item: unknown, index: number): JsonRecord |text: collapseExcessiveNewlines(toString(partRecord.text) || ""),};})- .filter((part): part is JsonRecord => part !== null)+ .filter((part): part is { type: string; text: string } => part !== null): [];return {diff --git a/open-sse/services/bailianQuotaFetcher.ts b/open-sse/services/bailianQuotaFetcher.tsindex a10c0f93f6..3eb0c11847 100644--- a/open-sse/services/bailianQuotaFetcher.ts+++ b/open-sse/services/bailianQuotaFetcher.ts@@ -94,7 +94,16 @@ function getAuthKey(}function getHost(): string {- return process.env.ALIBABA_CODING_PLAN_HOST || BAILIAN_QUOTA_HOSTS.international;+ const configuredHost = process.env.ALIBABA_CODING_PLAN_HOST?.trim();+ if (!configuredHost) {+ return BAILIAN_QUOTA_HOSTS.international;+ }++ if (/^https?:\/\//i.test(configuredHost)) {+ return configuredHost;+ }++ return `https://${configuredHost}`;}function getQuotaUrl(): string {diff --git a/open-sse/services/claudeCodeCompatible.ts b/open-sse/services/claudeCodeCompatible.tsindex f2b5b44773..bbb115cd30 100644--- a/open-sse/services/claudeCodeCompatible.ts+++ b/open-sse/services/claudeCodeCompatible.ts@@ -437,11 +437,16 @@ function buildClaudeCodeCompatibleMessages(messages: MessageLike[]) {.filter((message- ): message is { role: "user" | "assistant"; content: Array<Record<string, unknown>> } =>- !!message && message.content.length > 0+ ): message is {+ role: "user" | "assistant";+ content: Array<{ type: string; text: string }>;+ } => !!message && message.content.length > 0);- const merged: Array<{ role: "user" | "assistant"; content: Array<Record<string, unknown>> }> = [];+ const merged: Array<{+ role: "user" | "assistant";+ content: Array<{ type: string; text: string }>;+ }> = [];for (const message of converted) {const last = merged[merged.length - 1];@@ -575,7 +580,7 @@ function buildClaudeCodeCompatibleSystemBlocks({for (const systemBlock of customSystemBlocks) {const preparedBlock = { ...systemBlock };if (!preserveCacheControl) {- delete preparedBlock.cache_control;+ delete preparedBlock["cache_control"];}blocks.push(preparedBlock);}@@ -700,9 +705,12 @@ function prepareClaudeCodeCompatibleBody(const prepared = prepareClaudeRequest({system: normalizeClaudeSystemInput(claudeBody.system),- messages: normalizeClaudeMessageInput(claudeBody.messages),+ messages: normalizeClaudeMessageInput(claudeBody.messages) as Array<{+ role?: string;+ content?: string | Array<Record<string, unknown>>;+ }>,tools: normalizeClaudeToolInput(claudeBody.tools),- thinking: readRecord(claudeBody.thinking) || claudeBody.thinking,+ thinking: (readRecord(claudeBody.thinking) || null) as Record<string, unknown> | null,},CLAUDE_CODE_COMPATIBLE_PREFIX,true@@ -735,7 +743,7 @@ function normalizeClaudeMessageInput(messages: unknown) {content: normalizeClaudeContentInput(record.content),};})- .filter((message): message is Record<string, unknown> => !!message);+ .filter((message): message is Record<string, unknown> & { content: unknown } => !!message);}function normalizeClaudeToolInput(tools: unknown) {diff --git a/open-sse/services/contextManager.ts b/open-sse/services/contextManager.tsindex d9bd126f7e..25bf6cc033 100644--- a/open-sse/services/contextManager.ts+++ b/open-sse/services/contextManager.ts@@ -6,7 +6,7 @@*/import { REGISTRY } from "../config/providerRegistry.ts";-import { getModelContextLimit } from "../../src/lib/modelCapabilities";+import { getModelContextLimit } from "../../src/lib/modelCapabilities.ts";// Default token limits per provider (fallbacks when not in registry)const DEFAULT_LIMITS: Record<string, number> = {@@ -34,6 +34,16 @@ function getEnvOverride(provider: string): number | null {return null;}+// Reserve tokens override from environment variable+function getReserveTokensOverride(): number | null {+ const envValue = process.env.CONTEXT_RESERVE_TOKENS;+ if (envValue) {+ const parsed = parseInt(envValue, 10);+ if (!isNaN(parsed) && parsed > 0) return parsed;+ }+ return null;+}+// Rough chars-per-token ratio for quick estimationconst CHARS_PER_TOKEN = 4;@@ -109,8 +119,12 @@ export function compressContext(const provider = options.provider || "default";const maxTokens =options.maxTokens || getTokenLimit(provider, (body.model as string) || options.model || null);- const reserveTokens = options.reserveTokens || 16000; // Reserve for response- const targetTokens = maxTokens - reserveTokens;+ const defaultReserveTokens = Math.min(16000, Math.max(256, Math.floor(maxTokens * 0.15)));+ const reserveTokens = Math.min(+ options.reserveTokens ?? getReserveTokensOverride() ?? defaultReserveTokens,+ Math.max(0, maxTokens - 1)+ );+ const targetTokens = Math.max(0, maxTokens - reserveTokens);let messages = [...body.messages];let currentTokens = estimateTokens(JSON.stringify(messages));@@ -216,10 +230,23 @@ function compressThinking(messages: Record<string, unknown>[]) {// Remove thinking XML tags from string contentif (typeof msg.content === "string") {- const cleaned = msg.content- .replace(/<thinking>.*?<\/thinking>/gs, "")- .replace(/<antThinking>.*?<\/antThinking>/gs, "")- .trim();+ let cleaned = msg.content;+ for (const [start, end] of [+ ["<thinking>", "</thinking>"],+ ["<antThinking>", "</antThinking>"],+ ]) {+ while (true) {+ const s = cleaned.indexOf(start);+ if (s === -1) break;+ const e = cleaned.indexOf(end, s + start.length);+ if (e === -1) {+ cleaned = cleaned.slice(0, s);+ break;+ }+ cleaned = cleaned.slice(0, s) + cleaned.slice(e + end.length);+ }+ }+ cleaned = cleaned.trim();return { ...msg, content: cleaned || "[thinking compressed]" };}diff --git a/open-sse/services/provider.ts b/open-sse/services/provider.tsindex 79bf1e6ea4..e92c943998 100644--- a/open-sse/services/provider.ts+++ b/open-sse/services/provider.ts@@ -29,7 +29,10 @@ export function isClaudeCodeCompatible(provider) {return typeof provider === "string" && provider.startsWith(CLAUDE_CODE_COMPATIBLE_PREFIX);}-export function getOpenAICompatibleType(provider, providerSpecificData = null) {+export function getOpenAICompatibleType(+ provider,+ providerSpecificData: Record<string, unknown> | null = null+) {if (!isOpenAICompatible(provider)) return "chat";const configuredType =providerSpecificData &&@@ -277,7 +280,10 @@ export function buildProviderUrl(}// Custom URL builder (e.g. gemini, gemini-cli)if (entry.urlBuilder) {- return entry.urlBuilder(entry.baseUrl, model, stream);+ const baseUrl = entry.baseUrl || config.baseUrl;+ if (baseUrl) {+ return entry.urlBuilder(baseUrl, model, stream);+ }}// URL suffix (e.g. claude: ?beta=true)if (entry.urlSuffix) {diff --git a/open-sse/services/tokenRefresh.ts b/open-sse/services/tokenRefresh.tsindex 7e1c68acfc..d95c9c8f49 100755--- a/open-sse/services/tokenRefresh.ts+++ b/open-sse/services/tokenRefresh.ts@@ -12,6 +12,23 @@ const CACHE_SECRET = "omniroute-token-cache";// Key: "provider:sha256(refreshToken)" → Value: Promise<result>const refreshPromiseCache = new Map();+type RefreshLogger = {+ info?: (tag: string, message: string, data?: Record<string, unknown>) => void;+ warn?: (tag: string, message: string, data?: Record<string, unknown>) => void;+ error?: (tag: string, message: string, data?: Record<string, unknown>) => void;+ debug?: (tag: string, message: string, data?: Record<string, unknown>) => void;+} | null;++function buildFormParams(entries: Record<string, unknown>): URLSearchParams {+ const params = new URLSearchParams();+ for (const [key, value] of Object.entries(entries)) {+ if (typeof value === "string" && value.length > 0) {+ params.set(key, value);+ }+ }+ return params;+}+function getRefreshCacheKey(provider, refreshToken) {const tokenHash = pbkdf2Sync(refreshToken, CACHE_SECRET, 1000, 32, "sha256").toString("hex");return `${provider}:${tokenHash}`;@@ -25,7 +42,7 @@ export async function refreshAccessToken(refreshToken,credentials,log,- proxyConfig = null+ proxyConfig: unknown = null) {const config = PROVIDERS[provider];@@ -93,7 +110,7 @@ export async function refreshAccessToken(* Specialized refresh for Cline OAuth tokens.* Cline refresh endpoint expects JSON body and returns camelCase fields.*/-export async function refreshClineToken(refreshToken, log, proxyConfig = null) {+export async function refreshClineToken(refreshToken, log, proxyConfig: unknown = null) {const endpoint = PROVIDERS.cline?.refreshUrl;if (!endpoint) {log?.warn?.("TOKEN_REFRESH", "No refresh URL configured for Cline");@@ -153,7 +170,7 @@ export async function refreshClineToken(refreshToken, log, proxyConfig = null) {* Specialized refresh for Kimi Coding OAuth tokens.* Uses custom X-Msh-* headers required by Kimi OAuth API.*/-export async function refreshKimiCodingToken(refreshToken, log, proxyConfig = null) {+export async function refreshKimiCodingToken(refreshToken, log, proxyConfig: unknown = null) {const endpoint = PROVIDERS["kimi-coding"]?.refreshUrl || PROVIDERS["kimi-coding"]?.tokenUrl;if (!endpoint) {log?.warn?.("TOKEN_REFRESH", "No refresh URL configured for Kimi Coding");@@ -221,10 +238,10 @@ export async function refreshKimiCodingToken(refreshToken, log, proxyConfig = nu/*** Specialized refresh for Claude OAuth tokens*/-export async function refreshClaudeOAuthToken(refreshToken, log, proxyConfig = null) {+export async function refreshClaudeOAuthToken(refreshToken, log, proxyConfig: unknown = null) {try {// Standard OAuth2 token refresh uses form-urlencoded (not JSON)- const params = new URLSearchParams({+ const params = buildFormParams({grant_type: "refresh_token",refresh_token: refreshToken,client_id: PROVIDERS.claude.clientId,@@ -278,7 +295,7 @@ export async function refreshGoogleToken(clientId,clientSecret,log,- proxyConfig = null+ proxyConfig: unknown = null) {const response = await runWithProxyContext(proxyConfig, () =>fetch(OAUTH_ENDPOINTS.google.token, {@@ -287,7 +304,7 @@ export async function refreshGoogleToken("Content-Type": "application/x-www-form-urlencoded",Accept: "application/json",},- body: new URLSearchParams({+ body: buildFormParams({grant_type: "refresh_token",refresh_token: refreshToken,client_id: clientId,@@ -320,10 +337,7 @@ export async function refreshGoogleToken(};}-/**- * Specialized refresh for Qwen OAuth tokens- */-export async function refreshQwenToken(refreshToken, log, proxyConfig = null) {+export async function refreshQwenToken(refreshToken, log, proxyConfig: unknown = null) {const endpoint = OAUTH_ENDPOINTS.qwen.token;try {@@ -334,7 +348,7 @@ export async function refreshQwenToken(refreshToken, log, proxyConfig = null) {"Content-Type": "application/x-www-form-urlencoded",Accept: "application/json",},- body: new URLSearchParams({+ body: buildFormParams({grant_type: "refresh_token",refresh_token: refreshToken,client_id: PROVIDERS.qwen.clientId,@@ -403,7 +417,7 @@ export async function refreshQwenToken(refreshToken, log, proxyConfig = null) {* Returns { error: 'refresh_token_reused' } when the token has already been consumed,* so callers can stop retrying and request re-authentication.*/-export async function refreshCodexToken(refreshToken, log, proxyConfig = null) {+export async function refreshCodexToken(refreshToken, log, proxyConfig: unknown = null) {try {const response = await runWithProxyContext(proxyConfig, () =>fetch(OAUTH_ENDPOINTS.openai.token, {@@ -412,7 +426,7 @@ export async function refreshCodexToken(refreshToken, log, proxyConfig = null) {"Content-Type": "application/x-www-form-urlencoded",Accept: "application/json",},- body: new URLSearchParams({+ body: buildFormParams({grant_type: "refresh_token",refresh_token: refreshToken,client_id: PROVIDERS.codex.clientId,@@ -480,7 +494,7 @@ export async function refreshKiroToken(refreshToken,providerSpecificData,log,- proxyConfig = null+ proxyConfig: unknown = null) {try {const authMethod = providerSpecificData?.authMethod;@@ -537,8 +551,13 @@ export async function refreshKiroToken(}// Social Auth (Google/GitHub) - use Kiro's refresh endpoint+ const tokenUrl = PROVIDERS.kiro.tokenUrl;+ if (!tokenUrl) {+ log?.error?.("TOKEN_REFRESH", "Missing Kiro token endpoint");+ return null;+ }const response = await runWithProxyContext(proxyConfig, () =>- fetch(PROVIDERS.kiro.tokenUrl, {+ fetch(tokenUrl, {method: "POST",headers: {"Content-Type": "application/json",@@ -580,7 +599,7 @@ export async function refreshKiroToken(/*** Specialized refresh for Qoder OAuth tokens*/-export async function refreshQoderToken(refreshToken, log, proxyConfig = null) {+export async function refreshQoderToken(refreshToken, log, proxyConfig: unknown = null) {if (!OAUTH_ENDPOINTS.qoder.token || !PROVIDERS.qoder.clientId || !PROVIDERS.qoder.clientSecret) {log?.warn?.("TOKEN_REFRESH",@@ -599,7 +618,7 @@ export async function refreshQoderToken(refreshToken, log, proxyConfig = null) {Accept: "application/json",Authorization: `Basic ${basicAuth}`,},- body: new URLSearchParams({+ body: buildFormParams({grant_type: "refresh_token",refresh_token: refreshToken,client_id: PROVIDERS.qoder.clientId,@@ -635,7 +654,7 @@ export async function refreshQoderToken(refreshToken, log, proxyConfig = null) {/*** Specialized refresh for GitHub Copilot OAuth tokens*/-export async function refreshGitHubToken(refreshToken, log, proxyConfig = null) {+export async function refreshGitHubToken(refreshToken, log, proxyConfig: unknown = null) {const response = await runWithProxyContext(proxyConfig, () =>fetch(OAUTH_ENDPOINTS.github.token, {method: "POST",@@ -643,7 +662,7 @@ export async function refreshGitHubToken(refreshToken, log, proxyConfig = null)"Content-Type": "application/x-www-form-urlencoded",Accept: "application/json",},- body: new URLSearchParams({+ body: buildFormParams({grant_type: "refresh_token",refresh_token: refreshToken,client_id: PROVIDERS.github.clientId,@@ -679,7 +698,7 @@ export async function refreshGitHubToken(refreshToken, log, proxyConfig = null)/*** Refresh GitHub Copilot token using GitHub access token*/-export async function refreshCopilotToken(githubAccessToken, log, proxyConfig = null) {+export async function refreshCopilotToken(githubAccessToken, log, proxyConfig: unknown = null) {try {const response = await runWithProxyContext(proxyConfig, () =>fetch("https://api.github.com/copilot_internal/v2/token", {@@ -718,7 +737,7 @@ export async function refreshCopilotToken(githubAccessToken, log, proxyConfig =/*** Get access token for a specific provider (internal, does the actual work)*/-async function _getAccessTokenInternal(provider, credentials, log, proxyConfig = null) {+async function _getAccessTokenInternal(provider, credentials, log, proxyConfig: unknown = null) {switch (provider) {case "gemini":case "gemini-cli":@@ -807,7 +826,7 @@ export function isUnrecoverableRefreshError(result) {* subsequent calls share the existing promise instead of making* parallel OAuth requests.*/-export async function getAccessToken(provider, credentials, log, proxyConfig = null) {+export async function getAccessToken(provider, credentials, log, proxyConfig: unknown = null) {if (!credentials || !credentials.refreshToken || typeof credentials.refreshToken !== "string") {log?.warn?.("TOKEN_REFRESH", `No valid refresh token available for provider: ${provider}`);return null;@@ -1034,7 +1053,7 @@ async function withTimeout<T>(fn: () => Promise<T>, timeoutMs: number): Promise<export async function refreshWithRetry(refreshFn,maxRetries = 3,- log = null,+ log: RefreshLogger = null,provider = "unknown") {// Circuit breaker checkdiff --git a/open-sse/services/wildcardRouter.ts b/open-sse/services/wildcardRouter.tsindex accfd73ab4..b60216f0fa 100644--- a/open-sse/services/wildcardRouter.ts+++ b/open-sse/services/wildcardRouter.ts@@ -63,10 +63,13 @@ export function getSpecificity(pattern) {* @param {Array<{ pattern: string, target: string, [key: string]: unknown }>} aliases - Alias entries* @returns {{ pattern: string, target: string, specificity: number } | null}*/-export function resolveWildcardAlias(model, aliases) {+export function resolveWildcardAlias(+ model: string,+ aliases: WildcardAliasEntry[]+): ResolvedWildcardAlias | null {if (!model || !aliases || !Array.isArray(aliases)) return null;- const matches = [];+ const matches: ResolvedWildcardAlias[] = [];for (const alias of aliases) {const pattern = alias.pattern || alias.alias || alias.from;const target = alias.target || alias.model || alias.to;@@ -115,3 +118,18 @@ export function resolveModel(model, exactAliases = {}, wildcardAliases = []) {// 3. Return originalreturn model;}+type WildcardAliasEntry = {+ pattern?: string;+ alias?: string;+ from?: string;+ target?: string;+ model?: string;+ to?: string;+ [key: string]: unknown;+};++type ResolvedWildcardAlias = WildcardAliasEntry & {+ pattern: string;+ target: string;+ specificity: number;+};diff --git a/open-sse/translator/helpers/claudeHelper.ts b/open-sse/translator/helpers/claudeHelper.tsindex 0b1a614ecb..2936b60240 100644--- a/open-sse/translator/helpers/claudeHelper.ts+++ b/open-sse/translator/helpers/claudeHelper.ts@@ -1,8 +1,40 @@// Claude helper functions for translatorimport { DEFAULT_THINKING_CLAUDE_SIGNATURE } from "../../config/defaultThinkingSignature.ts";+type ClaudeContentBlock = {+ type?: string;+ text?: string;+ name?: string;+ tool_use_id?: string;+ cache_control?: unknown;+ signature?: string;+ thinking?: string;+ [key: string]: unknown;+};++type ClaudeMessage = {+ role?: string;+ content?: string | ClaudeContentBlock[];+ [key: string]: unknown;+};++type ClaudeTool = {+ name?: string;+ defer_loading?: boolean;+ cache_control?: unknown;+ [key: string]: unknown;+};++type ClaudeRequestBody = {+ system?: Array<Record<string, unknown> & { cache_control?: unknown }>;+ messages?: ClaudeMessage[];+ tools?: ClaudeTool[];+ thinking?: Record<string, unknown> | null;+ [key: string]: unknown;+};+// Check if message has valid non-empty content-export function hasValidContent(msg) {+export function hasValidContent(msg: ClaudeMessage): boolean {if (typeof msg.content === "string" && msg.content.trim()) return true;if (Array.isArray(msg.content)) {return msg.content.some(@@ -18,7 +50,7 @@ export function hasValidContent(msg) {// Fix tool_use/tool_result ordering for Claude API// 1. Assistant message with tool_use: remove text AFTER tool_use (Claude doesn't allow)// 2. Merge consecutive same-role messages-export function fixToolUseOrdering(messages) {+export function fixToolUseOrdering(messages: ClaudeMessage[]): ClaudeMessage[] {if (messages.length <= 1) return messages;// Pass 1: Fix assistant messages with tool_use - remove text after tool_use@@ -27,7 +59,7 @@ export function fixToolUseOrdering(messages) {const hasToolUse = msg.content.some((b) => b.type === "tool_use");if (hasToolUse) {// Keep only: thinking blocks + tool_use blocks (remove text blocks after tool_use)- const newContent = [];+ const newContent: ClaudeContentBlock[] = [];let foundToolUse = false;for (const block of msg.content) {@@ -49,7 +81,7 @@ export function fixToolUseOrdering(messages) {}// Pass 2: Merge consecutive same-role messages- const merged = [];+ const merged: ClaudeMessage[] = [];for (const msg of messages) {const last = merged[merged.length - 1];@@ -86,7 +118,7 @@ export function fixToolUseOrdering(messages) {return merged;}-function ensureMessageContentArray(msg) {+function ensureMessageContentArray(msg: ClaudeMessage): ClaudeContentBlock[] {if (Array.isArray(msg?.content)) return msg.content;if (typeof msg?.content === "string" && msg.content.trim()) {msg.content = [{ type: "text", text: msg.content }];@@ -95,7 +127,7 @@ function ensureMessageContentArray(msg) {return [];}-function markMessageCacheControl(msg, ttl) {+function markMessageCacheControl(msg: ClaudeMessage, ttl?: string): boolean {const content = ensureMessageContentArray(msg);if (content.length === 0) return false;const lastIndex = content.length - 1;@@ -109,13 +141,18 @@ function markMessageCacheControl(msg, ttl) {// - Filter empty messages// - Add thinking block for Anthropic endpoint (provider === "claude")// - Fix tool_use/tool_result ordering-export function prepareClaudeRequest(body, provider = null, preserveCacheControl = false) {+export function prepareClaudeRequest(+ body: ClaudeRequestBody,+ provider: string | null = null,+ preserveCacheControl = false+): ClaudeRequestBody {// 1. System: remove all cache_control, add only to last block with ttl 1h// In passthrough mode, preserve existing cache_control markers- if (body.system && Array.isArray(body.system) && !preserveCacheControl) {- body.system = body.system.map((block, i) => {+ const systemBlocks = body.system;+ if (systemBlocks && Array.isArray(systemBlocks) && !preserveCacheControl) {+ body.system = systemBlocks.map((block, i) => {const { cache_control, ...rest } = block;- if (i === body.system.length - 1) {+ if (i === systemBlocks.length - 1) {return { ...rest, cache_control: { type: "ephemeral", ttl: "1h" } };}return rest;@@ -125,7 +162,7 @@ export function prepareClaudeRequest(body, provider = null, preserveCacheControl// 2. Messages: process in optimized passesif (body.messages && Array.isArray(body.messages)) {const len = body.messages.length;- let filtered = [];+ let filtered: ClaudeMessage[] = [];// Pass 1: remove cache_control + filter empty messages// In passthrough mode, preserve existing cache_control markers@@ -181,7 +218,7 @@ export function prepareClaudeRequest(body, provider = null, preserveCacheControl// - cache the last assistant turn so the next user turn can reuse it// Skip in passthrough mode to preserve client's cache_control markersif (!preserveCacheControl) {- const userMessageIndexes = filtered.reduce((indexes, msg, index) => {+ const userMessageIndexes = filtered.reduce<number[]>((indexes, msg, index) => {if (msg?.role === "user") indexes.push(index);return indexes;}, []);@@ -196,8 +233,9 @@ export function prepareClaudeRequest(body, provider = null, preserveCacheControllet lastAssistantProcessed = false;for (let i = filtered.length - 1; i >= 0; i--) {const msg = filtered[i];+ const content = ensureMessageContentArray(msg);- if (msg.role === "assistant" && Array.isArray(ensureMessageContentArray(msg))) {+ if (msg.role === "assistant" && content.length > 0) {// Add cache_control to last block of first (from end) assistant with content// Skip in passthrough mode to preserve client's cache_control markersif (!preserveCacheControl && !lastAssistantProcessed && markMessageCacheControl(msg)) {@@ -210,7 +248,7 @@ export function prepareClaudeRequest(body, provider = null, preserveCacheControllet hasThinking = false;// Always replace signature for all thinking blocks- for (const block of msg.content) {+ for (const block of content) {if (block.type === "thinking" || block.type === "redacted_thinking") {block.signature = DEFAULT_THINKING_CLAUDE_SIGNATURE;hasThinking = true;@@ -220,7 +258,7 @@ export function prepareClaudeRequest(body, provider = null, preserveCacheControl// Add thinking block if thinking enabled + has tool_use but no thinkingif (thinkingEnabled && !hasThinking && hasToolUse) {- msg.content.unshift({+ content.unshift({type: "thinking",thinking: ".",signature: DEFAULT_THINKING_CLAUDE_SIGNATURE,diff --git a/open-sse/utils/proxyFetch.ts b/open-sse/utils/proxyFetch.tsindex ad1122c6b4..a883ecb594 100644--- a/open-sse/utils/proxyFetch.ts+++ b/open-sse/utils/proxyFetch.ts@@ -82,7 +82,12 @@ function noProxyMatch(targetUrl) {// Support wildcard matching (e.g. 192.168.* or *.local)if (patternHost.includes("*")) {const regexStr =- "^" + patternHost.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\\\*/g, ".*") + "$";+ "^" ++ patternHost+ .split("*")+ .map((s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))+ .join(".*") ++ "$";if (new RegExp(regexStr).test(hostname)) return true;}@@ -220,6 +225,7 @@ async function patchedFetch(input: RequestInfo | URL, options: FetchWithDispatchreturn await tlsClient.fetch(targetUrl, {...options,headers: options.headers,+ signal: options.signal ?? undefined,});} catch (error) {const message = error instanceof Error ? error.message : String(error);diff --git a/open-sse/utils/tlsClient.ts b/open-sse/utils/tlsClient.tsindex 1674ed24c6..9e93c3cf71 100644--- a/open-sse/utils/tlsClient.ts+++ b/open-sse/utils/tlsClient.ts@@ -80,6 +80,8 @@ class TlsClient {async getSession() {if (!this.available) return null;if (this.session) return this.session;+ const createSessionFn = createSession;+ if (!createSessionFn) return null;const proxy = getProxyFromEnv();const sessionOpts: Record<string, unknown> = {@@ -91,7 +93,7 @@ class TlsClient {console.log(`[TlsClient] Using proxy: ${proxy}`);}- this.session = await createSession(sessionOpts);+ this.session = await createSessionFn(sessionOpts);console.log("[TlsClient] Session created (Chrome 124 TLS fingerprint)");return this.session;}diff --git a/open-sse/utils/usageTracking.ts b/open-sse/utils/usageTracking.tsindex e0f88ce79d..89b6f54d13 100644--- a/open-sse/utils/usageTracking.ts+++ b/open-sse/utils/usageTracking.ts@@ -500,7 +500,13 @@ export function estimateUsage(body, contentLength, targetFormat = FORMATS.OPENAI/*** Log usage with cache info (green color)*/-export function logUsage(provider, usage, model = null, connectionId = null, apiKeyInfo = null) {+export function logUsage(+ provider,+ usage,+ model: string | null = null,+ connectionId: string | null = null,+ apiKeyInfo = null+) {if (!usage || typeof usage !== "object") return;const p = provider?.toUpperCase() || "UNKNOWN";@@ -510,7 +516,11 @@ export function logUsage(provider, usage, model = null, connectionId = null, api// - Claude: input_tokens, output_tokensconst inTokens = getLoggedInputTokens(usage);const outTokens = getLoggedOutputTokens(usage);- const accountPrefix = connectionId ? connectionId.slice(0, 8) + "..." : "unknown";+ void apiKeyInfo;+ const normalizedConnectionId = typeof connectionId === "string" ? connectionId : undefined;+ const accountPrefix = normalizedConnectionId+ ? normalizedConnectionId.slice(0, 8) + "..."+ : "unknown";let msg = `[${getTimeString()}] 📊 ${COLORS.green}[USAGE] ${p} | in=${inTokens} | out=${outTokens} | account=${accountPrefix}${COLORS.reset}`;@@ -540,5 +550,11 @@ export function logUsage(provider, usage, model = null, connectionId = null, apicacheCreation: cacheCreation || 0,reasoning: reasoning || 0,};- appendRequestLog({ model, provider, connectionId, tokens, status: "200 OK" }).catch(() => {});+ appendRequestLog({+ model: typeof model === "string" ? model : undefined,+ provider: typeof provider === "string" ? provider : undefined,+ connectionId: normalizedConnectionId,+ tokens,+ status: "200 OK",+ }).catch(() => {});}diff --git a/src/app/(dashboard)/dashboard/audit/ConfigAuditViewer.tsx b/src/app/(dashboard)/dashboard/audit/ConfigAuditViewer.tsxindex 728897e1a7..298c09b60a 100644--- a/src/app/(dashboard)/dashboard/audit/ConfigAuditViewer.tsx+++ b/src/app/(dashboard)/dashboard/audit/ConfigAuditViewer.tsx@@ -3,25 +3,18 @@import { useState, useEffect } from "react";import { useTranslations } from "next-intl";-interface ConfigDiff {- added: string[];- removed: string[];- changed: Array<{ key: string; from: any; to: any }>;- isEmpty: boolean;-}-interface AuditEntry {- id: string;+ id: number;timestamp: string;action: string;- target: string;- targetId: string;- targetName: string;- source: string;- before: any;- after: any;- diff: ConfigDiff;- note: string | null;+ actor: string;+ target?: string;+ resource_type?: string;+ ip_address?: string;+ status?: string;+ request_id?: string;+ details?: any;+ metadata?: any;}export default function ConfigAuditViewer() {@@ -48,16 +41,17 @@ export default function ConfigAuditViewer() {};const getActionColor = (action: string) => {- switch (action) {- case "create":- return "text-green-400 bg-green-400/10 border-green-500/20";- case "update":- return "text-blue-400 bg-blue-400/10 border-blue-500/20";- case "delete":- return "text-red-400 bg-red-400/10 border-red-500/20";- default:- return "text-gray-400 bg-gray-400/10 border-gray-500/20";+ const act = action.toLowerCase();+ if (act.includes("success") || act.includes("create")) {+ return "text-green-400 bg-green-400/10 border-green-500/20";+ }+ if (act.includes("update") || act.includes("modify")) {+ return "text-blue-400 bg-blue-400/10 border-blue-500/20";+ }+ if (act.includes("failed") || act.includes("delete")) {+ return "text-red-400 bg-red-400/10 border-red-500/20";}+ return "text-gray-400 bg-gray-400/10 border-gray-500/20";};if (loading) {@@ -98,8 +92,8 @@ export default function ConfigAuditViewer() {<th className="px-6 py-4 font-medium">Timestamp</th><th className="px-6 py-4 font-medium">Action</th><th className="px-6 py-4 font-medium">Target</th>- <th className="px-6 py-4 font-medium">Resource</th>- <th className="px-6 py-4 font-medium">Source</th>+ <th className="px-6 py-4 font-medium">Actor</th>+ <th className="px-6 py-4 font-medium">Resource/IP</th><th className="px-6 py-4 font-medium text-right">Details</th></tr></thead>@@ -120,20 +114,20 @@ export default function ConfigAuditViewer() {</span></td><td className="px-6 py-3 whitespace-nowrap text-sm text-[var(--text-primary,#fff)] font-medium capitalize">- {entry.target}- </td>- <td className="px-6 py-3 text-sm text-[var(--text-secondary,#aaa)] font-mono">- {entry.targetName}+ {entry.target || "-"}</td><td className="px-6 py-3 whitespace-nowrap text-sm text-[var(--text-muted,#666)] capitalize">- {entry.source}+ {entry.actor}+ </td>+ <td className="px-6 py-3 text-sm text-[var(--text-secondary,#aaa)] font-mono">+ {entry.resource_type || entry.ip_address || "-"}</td><td className="px-6 py-3 whitespace-nowrap text-right"><buttononClick={() => setSelectedEntry(entry)}className="px-3 py-1 text-xs font-medium text-[var(--text-primary,#fff)] bg-[var(--accent,#7c3aed)] hover:bg-opacity-80 rounded-md transition-colors invisible group-hover:visible">- View Diff+ View Details</button></td></tr>@@ -149,10 +143,10 @@ export default function ConfigAuditViewer() {<div className="flex items-center justify-between px-6 py-5 border-b border-[var(--border,#333)] bg-[#15151f]"><div><h3 className="text-xl font-semibold text-[var(--text-primary,#fff)] capitalize">- {selectedEntry.action} {selectedEntry.target}+ {selectedEntry.action}</h3><p className="text-sm text-[var(--text-secondary,#aaa)] font-mono mt-1">- ID: {selectedEntry.targetId} • {selectedEntry.targetName}+ Actor: {selectedEntry.actor} • Target: {selectedEntry.target || "N/A"}</p></div><button@@ -172,97 +166,34 @@ export default function ConfigAuditViewer() {</div>{/* Modal Content */}- <div className="p-6 overflow-y-auto custom-scrollbar flex-1 bg-[#1a1a24]">- {selectedEntry.note && (- <div className="mb-6 p-4 bg-yellow-500/10 border border-yellow-500/20 text-yellow-300 rounded-xl text-sm italic">- 📝 {selectedEntry.note}+ <div className="p-6 overflow-y-auto custom-scrollbar flex-1 bg-[#1a1a24] text-sm text-[var(--text-secondary,#aaa)]">+ <div className="grid grid-cols-2 gap-4 mb-6">+ <div>+ <strong>ID:</strong> {selectedEntry.id}</div>- )}-- {selectedEntry.diff?.isEmpty ? (- <div className="text-center p-8 text-[var(--text-muted,#666)]">- No changes detected in Diff+ <div>+ <strong>Timestamp:</strong> {new Date(selectedEntry.timestamp).toLocaleString()}</div>- ) : (- <div className="space-y-6">- {/* Added Keys */}- {selectedEntry.diff?.added?.length > 0 && (- <div>- <h4 className="text-sm font-semibold text-green-400 mb-2 uppercase tracking-wider">- ++ Added Properties- </h4>- <pre className="bg-[#111116] border border-green-500/20 rounded-xl p-4 overflow-x-auto text-xs font-mono text-green-300 shadow-inner">- {JSON.stringify(- selectedEntry.diff.added.reduce(- (acc, key) => ({ ...acc, [key]: selectedEntry.after?.[key] }),- {}- ),- null,- 2- )}- </pre>- </div>- )}-- {/* Removed Keys */}- {selectedEntry.diff?.removed?.length > 0 && (- <div>- <h4 className="text-sm font-semibold text-red-400 mb-2 uppercase tracking-wider">- -- Removed Properties- </h4>- <pre className="bg-[#111116] border border-red-500/20 rounded-xl p-4 overflow-x-auto text-xs font-mono text-red-300 shadow-inner">- {JSON.stringify(- selectedEntry.diff.removed.reduce(- (acc, key) => ({ ...acc, [key]: selectedEntry.before?.[key] }),- {}- ),- null,- 2- )}- </pre>- </div>- )}-- {/* Changed Keys */}- {selectedEntry.diff?.changed?.length > 0 && (- <div>- <h4 className="text-sm font-semibold text-yellow-400 mb-2 uppercase tracking-wider">- ~ Modified Properties- </h4>- <div className="space-y-2">- {selectedEntry.diff.changed.map((change, idx) => (- <div- key={idx}- className="bg-[#111116] border border-yellow-500/20 rounded-xl overflow-hidden shadow-inner text-sm font-mono flex flex-col"- >- <div className="px-4 py-2 bg-[#1b1b22] border-b border-[#2d2d3a] text-yellow-500/80 font-semibold">- {change.key}- </div>- <div className="grid grid-cols-2 divide-x divide-[#2d2d3a]">- <div className="p-4 bg-red-500/5 text-red-300/80">- <div className="text-[10px] text-red-400/50 mb-1 uppercase">- Before- </div>- <pre className="whitespace-pre-wrap break-words">- {JSON.stringify(change.from, null, 2)}- </pre>- </div>- <div className="p-4 bg-green-500/5 text-green-300/80">- <div className="text-[10px] text-green-400/50 mb-1 uppercase">- After- </div>- <pre className="whitespace-pre-wrap break-words">- {JSON.stringify(change.to, null, 2)}- </pre>- </div>- </div>- </div>- ))}- </div>- </div>- )}+ <div>+ <strong>Status:</strong> {selectedEntry.status || "-"}+ </div>+ <div>+ <strong>IP Address:</strong> {selectedEntry.ip_address || "-"}</div>- )}+ <div>+ <strong>Resource Type:</strong> {selectedEntry.resource_type || "-"}+ </div>+ <div>+ <strong>Request ID:</strong> {selectedEntry.request_id || "-"}+ </div>+ </div>++ <h4 className="text-sm font-semibold text-gray-300 mb-2 uppercase tracking-wider">+ Event Payload (Details/Metadata)+ </h4>+ <pre className="bg-[#111116] border border-gray-500/20 rounded-xl p-4 overflow-x-auto text-xs font-mono text-gray-300 shadow-inner">+ {JSON.stringify(selectedEntry.metadata || selectedEntry.details || {}, null, 2)}+ </pre></div></div></div>diff --git a/src/app/(dashboard)/dashboard/audit/page.tsx b/src/app/(dashboard)/dashboard/audit/page.tsxindex 1c52420069..4ee44b5eb5 100644--- a/src/app/(dashboard)/dashboard/audit/page.tsx+++ b/src/app/(dashboard)/dashboard/audit/page.tsx@@ -18,10 +18,11 @@ export default function ConfigAuditPage() {<div className="flex items-center justify-between"><div><h1 className="text-2xl font-semibold text-[var(--text-primary,#fff)]">- Configuration Audit+ Configuration & Security Audit</h1><p className="text-sm text-[var(--text-secondary,#aaa)] mt-1">- Track and diff changes made to routing policies, combos, and connections.+ Track administrative actions, authentication events, and security logs across the+ system.</p></div>{summary && (diff --git a/src/app/api/audit/route.ts b/src/app/api/audit/route.tsindex 5819553ffe..efeeba4a19 100644--- a/src/app/api/audit/route.ts+++ b/src/app/api/audit/route.ts@@ -1,11 +1,5 @@import { NextResponse } from "next/server";-import {- getAuditLog,- getAuditSummary,- AuditTarget,- AuditAction,- AuditSource,-} from "@/domain/configAudit";+import { getAuditLog, countAuditLog } from "@/lib/compliance/index";export async function GET(req: Request) {try {@@ -13,24 +7,27 @@ export async function GET(req: Request) {const summary = url.searchParams.get("summary");if (summary === "true") {- return NextResponse.json(getAuditSummary());+ const totalEntries = countAuditLog({});+ return NextResponse.json({ totalEntries });}const limit = parseInt(url.searchParams.get("limit") || "50", 10);const offset = parseInt(url.searchParams.get("offset") || "0", 10);- const target = url.searchParams.get("target") as AuditTarget | null;- const action = url.searchParams.get("action") as AuditAction | null;- const source = url.searchParams.get("source") as AuditSource | null;- const since = url.searchParams.get("since");+ const target = url.searchParams.get("target") || undefined;+ const action = url.searchParams.get("action") || undefined;+ const actor = url.searchParams.get("actor") || undefined;+ const from = url.searchParams.get("since") || undefined;const options: any = { limit, offset };if (target) options.target = target;if (action) options.action = action;- if (source) options.source = source;- if (since) options.since = since;+ if (actor) options.actor = actor;+ if (from) options.from = from;- const result = getAuditLog(options);- return NextResponse.json(result);+ const entries = getAuditLog(options);+ const total = countAuditLog(options);++ return NextResponse.json({ entries, total });} catch (error) {console.error("[API ERROR] /api/audit GET:", error);return NextResponse.json({ error: "Failed to fetch audit log." }, { status: 500 });diff --git a/src/app/api/v1/images/generations/route.ts b/src/app/api/v1/images/generations/route.tsindex 0283a06409..3a37b9e505 100644--- a/src/app/api/v1/images/generations/route.ts+++ b/src/app/api/v1/images/generations/route.ts@@ -10,6 +10,7 @@ import {parseImageModel,getAllImageModels,getImageProvider,+ getImageModelEntry,} from "@omniroute/open-sse/config/imageRegistry.ts";import { errorResponse, unavailableResponse } from "@omniroute/open-sse/utils/error.ts";import { HTTP_STATUS } from "@omniroute/open-sse/config/constants.ts";@@ -85,6 +86,21 @@ export async function GET() {/*** POST /v1/images/generations — generate images*/+function hasImageGenerationInput(body: Record<string, unknown>) {+ if (typeof body.image_url === "string" && body.image_url.trim()) return true;+ if (typeof body.image === "string" && body.image.trim()) return true;+ if (Array.isArray(body.imageUrls) && body.imageUrls.some((value) => typeof value === "string")) {+ return true;+ }+ if (+ Array.isArray(body.image_urls) &&+ body.image_urls.some((value) => typeof value === "string")+ ) {+ return true;+ }+ return false;+}+export async function POST(request) {let rawBody;try {@@ -150,6 +166,26 @@ export async function POST(request) {// Check provider config for auth bypassconst providerConfig = getImageProvider(provider);+ const imageModelEntry = getImageModelEntry(body.model);+ const inputModalities = imageModelEntry?.inputModalities || ["text"];+ const requiresPrompt = inputModalities.includes("text");+ const requiresImageInput = inputModalities.includes("image");+ const hasPrompt = typeof body.prompt === "string" && body.prompt.trim().length > 0;+ const hasImageInput = hasImageGenerationInput(body);++ if (requiresPrompt && !hasPrompt) {+ return errorResponse(+ HTTP_STATUS.BAD_REQUEST,+ `Prompt is required for image model: ${body.model}`+ );+ }++ if (requiresImageInput && !hasImageInput) {+ return errorResponse(+ HTTP_STATUS.BAD_REQUEST,+ `Image input is required for image model: ${body.model}`+ );+ }// Get credentials — skip for local providers (authType: "none")let credentials = null;diff --git a/src/app/api/v1/music/generations/route.ts b/src/app/api/v1/music/generations/route.tsindex 7e88643dd0..3dce64136b 100644--- a/src/app/api/v1/music/generations/route.ts+++ b/src/app/api/v1/music/generations/route.ts@@ -72,6 +72,10 @@ export async function POST(request) {}const body = validation.data;+ if (typeof body.prompt !== "string" || body.prompt.trim().length === 0) {+ return errorResponse(HTTP_STATUS.BAD_REQUEST, "Prompt is required");+ }+// Optional API key validationif (process.env.REQUIRE_API_KEY === "true") {const apiKey = extractApiKey(request);diff --git a/src/app/api/v1/search/route.ts b/src/app/api/v1/search/route.tsindex f8820e11e2..8bd8ac87c1 100644--- a/src/app/api/v1/search/route.ts+++ b/src/app/api/v1/search/route.ts@@ -65,6 +65,15 @@ async function resolveSearchCredentials(providerId: string) {return null;}+async function resolveSearchExecutionCredentials(providerConfig: {+ id: string;+ authType: string;+}): Promise<Record<string, any> | null> {+ const credentials = await resolveSearchCredentials(providerConfig.id);+ if (credentials) return credentials;+ return providerConfig.authType === "none" ? {} : null;+}+// Helper: build domain filter array from filters objectfunction buildDomainFilter(filters?: {include_domains?: string[];@@ -139,26 +148,16 @@ export async function POST(request: Request) {if (body.provider) {// Explicit provider — single credential lookup (with fallback)- credentials = await resolveSearchCredentials(providerConfig.id);- if (- !credentials &&- providerConfig.authType === "none" &&- typeof body.provider_options?.baseUrl === "string" &&- body.provider_options.baseUrl.trim().length > 0- ) {- credentials = { providerSpecificData: { baseUrl: body.provider_options.baseUrl.trim() } };- }+ credentials = await resolveSearchExecutionCredentials(providerConfig);if (!credentials) {return errorResponse(HTTP_STATUS.BAD_REQUEST,- providerConfig.authType === "none"- ? `Search provider ${providerConfig.id} is not configured. Set its base URL in the dashboard or pass provider_options.baseUrl.`- : `No credentials configured for search provider: ${providerConfig.id}. Add an API key for "${providerConfig.id}" in the dashboard.`+ `No credentials configured for search provider: ${providerConfig.id}. Add an API key for "${providerConfig.id}" in the dashboard.`);}} else {// Auto-select — try the resolved provider first, then iterate others by cost- credentials = await resolveSearchCredentials(providerConfig.id);+ credentials = await resolveSearchExecutionCredentials(providerConfig);if (!credentials) {// Sort by cost to find cheapest with credentials@@ -170,7 +169,7 @@ export async function POST(request: Request) {for (const pid of sortedIds) {if (pid === providerConfig.id) continue;const altConfig = getSearchProvider(pid);- const altCreds = await resolveSearchCredentials(pid);+ const altCreds = altConfig ? await resolveSearchExecutionCredentials(altConfig) : null;if (altConfig && altCreds) {providerConfig = altConfig;credentials = altCreds;@@ -194,7 +193,8 @@ export async function POST(request: Request) {.filter((id) => id !== providerConfig.id);for (const pid of otherIds) {- const creds = await resolveSearchCredentials(pid);+ const altConfig = getSearchProvider(pid);+ const creds = altConfig ? await resolveSearchExecutionCredentials(altConfig) : null;if (creds) {alternateProviderId = pid;alternateCredentials = creds;diff --git a/src/app/api/v1/videos/generations/route.ts b/src/app/api/v1/videos/generations/route.tsindex 702012e793..b406bd629c 100644--- a/src/app/api/v1/videos/generations/route.ts+++ b/src/app/api/v1/videos/generations/route.ts@@ -72,6 +72,10 @@ export async function POST(request) {}const body = validation.data;+ if (typeof body.prompt !== "string" || body.prompt.trim().length === 0) {+ return errorResponse(HTTP_STATUS.BAD_REQUEST, "Prompt is required");+ }+// Optional API key validationif (process.env.REQUIRE_API_KEY === "true") {const apiKey = extractApiKey(request);diff --git a/src/lib/usage/callLogArtifacts.ts b/src/lib/usage/callLogArtifacts.tsindex 42f10cf07f..198336ce01 100644--- a/src/lib/usage/callLogArtifacts.ts+++ b/src/lib/usage/callLogArtifacts.ts@@ -75,7 +75,8 @@ export function writeCallArtifact(try {const serialized = JSON.stringify(artifact, null, 2);const sizeBytes = Buffer.byteLength(serialized);- const artifactHash = crypto.createHash("sha256").update(serialized).digest("hex"); // lgtm[js/insufficient-password-hash]+ // codeql[js/insufficient-password-hash] - This is a file checksum, not a password hash+ const artifactHash = crypto.createHash("sha256").update(serialized).digest("hex");fs.mkdirSync(path.dirname(absPath), { recursive: true });fs.writeFileSync(tmpPath, serialized);diff --git a/src/lib/usage/usageStats.ts b/src/lib/usage/usageStats.tsindex 1a3323a85d..8acd91b675 100644--- a/src/lib/usage/usageStats.ts+++ b/src/lib/usage/usageStats.ts@@ -13,6 +13,29 @@ import { getAccountDisplayName } from "@/lib/display/names";import { calculateCost } from "./costCalculator";type JsonRecord = Record<string, unknown>;+type UsageBucket = {+ requests: number;+ promptTokens: number;+ completionTokens: number;+ cost: number;+};++type UsageBreakdown = UsageBucket & {+ rawModel?: string;+ provider?: string;+ lastUsed?: string;+ connectionId?: string;+ accountName?: string;+ apiKeyId?: string | null;+ apiKeyName?: string;+};++type ActiveRequest = {+ model: string;+ provider: string;+ account: string;+ count: number;+};function asRecord(value: unknown): JsonRecord {return value && typeof value === "object" && !Array.isArray(value) ? (value as JsonRecord) : {};@@ -56,7 +79,19 @@ export async function getUsageStats() {const pendingRequests = getPendingRequests();- const stats = {+ const stats: {+ totalRequests: number;+ totalPromptTokens: number;+ totalCompletionTokens: number;+ totalCost: number;+ byProvider: Record<string, UsageBreakdown>;+ byModel: Record<string, UsageBreakdown>;+ byAccount: Record<string, UsageBreakdown>;+ byApiKey: Record<string, UsageBreakdown>;+ last10Minutes: UsageBucket[];+ pending: ReturnType<typeof getPendingRequests>;+ activeRequests: ActiveRequest[];+ } = {totalRequests: rows.length,totalPromptTokens: 0,totalCompletionTokens: 0,@@ -91,7 +126,7 @@ export async function getUsageStats() {const now = new Date();const currentMinuteStart = new Date(Math.floor(now.getTime() / 60000) * 60000);- const bucketMap = {};+ const bucketMap: Record<number, UsageBucket> = {};for (let i = 0; i < 10; i++) {const bucketTime = new Date(currentMinuteStart.getTime() - (9 - i) * 60 * 1000);const bucketKey = bucketTime.getTime();@@ -169,7 +204,7 @@ export async function getUsageStats() {stats.byModel[modelKey].promptTokens += promptTokens;stats.byModel[modelKey].completionTokens += completionTokens;stats.byModel[modelKey].cost += entryCost;- if (new Date(timestamp) > new Date(stats.byModel[modelKey].lastUsed)) {+ if (new Date(timestamp) > new Date(stats.byModel[modelKey].lastUsed || timestamp)) {stats.byModel[modelKey].lastUsed = timestamp;}@@ -195,7 +230,7 @@ export async function getUsageStats() {stats.byAccount[accountKey].promptTokens += promptTokens;stats.byAccount[accountKey].completionTokens += completionTokens;stats.byAccount[accountKey].cost += entryCost;- if (new Date(timestamp) > new Date(stats.byAccount[accountKey].lastUsed)) {+ if (new Date(timestamp) > new Date(stats.byAccount[accountKey].lastUsed || timestamp)) {stats.byAccount[accountKey].lastUsed = timestamp;}}@@ -220,7 +255,7 @@ export async function getUsageStats() {stats.byApiKey[apiKey].promptTokens += promptTokens;stats.byApiKey[apiKey].completionTokens += completionTokens;stats.byApiKey[apiKey].cost += entryCost;- if (new Date(timestamp) > new Date(stats.byApiKey[apiKey].lastUsed)) {+ if (new Date(timestamp) > new Date(stats.byApiKey[apiKey].lastUsed || timestamp)) {stats.byApiKey[apiKey].lastUsed = timestamp;}}diff --git a/src/shared/components/OAuthModal.tsx b/src/shared/components/OAuthModal.tsxindex ed84ba346b..d36515bce8 100644--- a/src/shared/components/OAuthModal.tsx+++ b/src/shared/components/OAuthModal.tsx@@ -648,15 +648,15 @@ export default function OAuthModal({</span><strong>{t.rich("googleOAuthWarning", {- code: (chunks) => <code>{chunks}</code>,- a: (chunks) => (+ code: (c) => <code className="font-mono">{c}</code>,+ a: (c) => (<ahref="https://github.com/diegosouzapw/OmniRoute#oauth-on-a-remote-server"target="_blank"rel="noreferrer"className="underline">- {chunks}+ {c}</a>),})}@@ -692,7 +692,7 @@ export default function OAuthModal({<p className="text-sm font-medium mb-2">{t("step2PasteCallback")}</p><p className="text-xs text-text-muted mb-2">{t.rich("step2Hint", {- code: (chunks) => <code>{chunks}</code>,+ code: (c) => <code className="font-mono">{c}</code>,})}</p><Inputdiff --git a/src/shared/components/PricingModal.tsx b/src/shared/components/PricingModal.tsxindex cd7ea44810..2c02ca0564 100644--- a/src/shared/components/PricingModal.tsx+++ b/src/shared/components/PricingModal.tsx@@ -120,7 +120,7 @@ export default function PricingModal({ isOpen, onClose, onSave }) {<p className="font-medium mb-1">{t("pricingRatesFormat")}</p><p className="text-text-muted">{t.rich("ratesDescription", {- strong: (chunks) => <strong>{chunks}</strong>,+ strong: (c) => <strong className="font-semibold">{c}</strong>,})}</p></div>diff --git a/src/shared/validation/schemas.ts b/src/shared/validation/schemas.tsindex 9217c35581..ae120f3da7 100644--- a/src/shared/validation/schemas.ts+++ b/src/shared/validation/schemas.ts@@ -491,7 +491,7 @@ export const v1EmbeddingsSchema = zexport const v1ImageGenerationSchema = z.object({model: modelIdSchema,- prompt: nonEmptyStringSchema,+ prompt: nonEmptyStringSchema.optional(),}).catchall(z.unknown());diff --git a/tests/e2e/memory-settings.spec.ts b/tests/e2e/memory-settings.spec.tsindex 68bb0bb964..ea36831371 100644--- a/tests/e2e/memory-settings.spec.ts+++ b/tests/e2e/memory-settings.spec.ts@@ -142,11 +142,13 @@ test.describe("Memory settings", () => {await fulfillJson(route, { error: "Method not allowed in memory settings stub" }, 405);});- await page.route("**/api/memory", async (route) => {+ await page.route(/\/api\/memory(?:\?.*)?$/, async (route) => {await fulfillJson(route, {- memories: state.memories,+ data: state.memories,+ total: state.memories.length,+ totalPages: 1,stats: {- totalEntries: state.memories.length,+ total: state.memories.length,tokensUsed: state.memories.length * 24,hitRate: state.memories.length > 0 ? 0.75 : 0,},@@ -167,7 +169,7 @@ test.describe("Memory settings", () => {if (settingsHydrationRetries++ > 0) {await page.reload({ waitUntil: "commit" }).catch(() => {});}- await expect(page.getByTestId("memory-settings-card")).toBeVisible({ timeout: 15000 });+ await expect(page.getByTestId("memory-enabled-switch")).toBeVisible({ timeout: 15000 });}).toPass({ timeout: 45_000, intervals: [1000, 2500, 5000] });await expect(page.getByTestId("memory-enabled-switch")).toHaveAttribute("aria-checked",diff --git a/tests/e2e/settings-toggles.spec.ts b/tests/e2e/settings-toggles.spec.tsindex fa77426d28..07eea6778e 100644--- a/tests/e2e/settings-toggles.spec.ts+++ b/tests/e2e/settings-toggles.spec.ts@@ -1,12 +1,18 @@import { test, expect } from "@playwright/test";test.describe("Settings Toggles", () => {+ const getDebugToggle = (page) =>+ page+ .getByText(/enable debug mode/i)+ .locator('xpath=ancestor::div[contains(@class, "flex items-center justify-between")][1]')+ .getByRole("switch");+test("Debug mode toggle should work", async ({ page }) => {await page.goto("/dashboard/settings");await page.waitForLoadState("networkidle");await page.getByRole("tab", { name: /advanced/i }).click();- const debugToggle = page.getByRole("switch").first();+ const debugToggle = getDebugToggle(page);await expect(debugToggle).toBeVisible({ timeout: 15000 });@@ -74,7 +80,7 @@ test.describe("Settings Toggles", () => {await page.waitForLoadState("networkidle");await page.getByRole("tab", { name: /advanced/i }).click();- const debugToggle = page.getByRole("switch").first();+ const debugToggle = getDebugToggle(page);await expect(debugToggle).toBeVisible({ timeout: 15000 });@@ -85,6 +91,8 @@ test.describe("Settings Toggles", () => {await page.reload();await page.waitForLoadState("networkidle");await page.getByRole("tab", { name: /advanced/i }).click();- await expect(debugToggle).toHaveAttribute("aria-checked", nextState, { timeout: 15000 });+ await expect(getDebugToggle(page)).toHaveAttribute("aria-checked", nextState, {+ timeout: 15000,+ });});});diff --git a/tests/e2e/skills-marketplace.spec.ts b/tests/e2e/skills-marketplace.spec.tsindex 0427c352fb..9b732f2f6a 100644--- a/tests/e2e/skills-marketplace.spec.ts+++ b/tests/e2e/skills-marketplace.spec.ts@@ -90,8 +90,8 @@ test.describe("Skills marketplace", () => {customInstalls: 0,};- await page.route("**/api/skills/executions", async (route) => {- await fulfillJson(route, { executions: [] });+ await page.route(/\/api\/skills\/executions(?:\?.*)?$/, async (route) => {+ await fulfillJson(route, { data: [], total: 0, totalPages: 1 });});await page.route(/\/api\/skills\/marketplace(?:\?.*)?$/, async (route) => {@@ -151,8 +151,12 @@ test.describe("Skills marketplace", () => {await fulfillJson(route, { success: true });});- await page.route("**/api/skills", async (route) => {- await fulfillJson(route, { skills: state.skills });+ await page.route(/\/api\/skills(?:\?.*)?$/, async (route) => {+ await fulfillJson(route, {+ data: state.skills,+ total: state.skills.length,+ totalPages: 1,+ });});await gotoOrSkip(page, "/dashboard/skills");diff --git a/tests/integration/chatcore-compression-integration.test.ts b/tests/integration/chatcore-compression-integration.test.tsnew file mode 100644index 0000000000..88391f89ed--- /dev/null+++ b/tests/integration/chatcore-compression-integration.test.ts@@ -0,0 +1,331 @@+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-compression-"));+process.env.DATA_DIR = TEST_DATA_DIR;+process.env.REQUIRE_API_KEY = "false";+process.env.API_KEY_SECRET = process.env.API_KEY_SECRET || "test-compression-secret";++const core = await import("../../src/lib/db/core.ts");+const providersDb = await import("../../src/lib/db/providers.ts");+const readCacheDb = await import("../../src/lib/db/readCache.ts");+const { handleChatCore } = await import("../../open-sse/handlers/chatCore.ts");+const { estimateTokens, getTokenLimit } = await import("../../open-sse/services/contextManager.ts");+const { resetAllAvailability } = await import("../../src/domain/modelAvailability.ts");+const { resetAllCircuitBreakers } = await import("../../src/shared/utils/circuitBreaker.ts");++const originalFetch = globalThis.fetch;++async function resetStorage() {+ globalThis.fetch = originalFetch;+ resetAllAvailability();+ resetAllCircuitBreakers();+ readCacheDb.invalidateDbCache();+ await new Promise((resolve) => setTimeout(resolve, 20));+ 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 () => {+ globalThis.fetch = originalFetch;+ core.closeDbInstance();+ try {+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });+ } catch {}+});++test("chatCore integration: compressContext called proactively when context exceeds 85% threshold", async () => {+ const provider = "openai";+ const model = "gpt-4";++ // Create multiple messages with history that can be compressed+ // Use the same pattern as test 3 which successfully tests compression+ const body = {+ model,+ messages: [+ { role: "system", content: "You are helpful." },+ { role: "user", content: "x".repeat(50000) },+ { role: "assistant", content: "Response 1" },+ { role: "user", content: "x".repeat(50000) },+ { role: "assistant", content: "Response 2" },+ { role: "user", content: "x".repeat(50000) },+ { role: "assistant", content: "Response 3" },+ { role: "user", content: "Final question" },+ ],+ };++ // Create provider connection+ const connectionId = await providersDb.createProviderConnection({+ provider,+ apiKey: "test-key",+ isActive: true,+ });++ // Mock fetch to capture the request+ let capturedBody: any = null;+ globalThis.fetch = async (url: string | URL | Request, init?: RequestInit) => {+ if (init?.body) {+ capturedBody = JSON.parse(init.body as string);+ }+ return new Response(+ JSON.stringify({+ choices: [{ message: { role: "assistant", content: "test" } }],+ usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 },+ }),+ {+ status: 200,+ headers: { "content-type": "application/json" },+ }+ );+ };++ try {+ const result = await handleChatCore({+ body,+ modelInfo: { provider, model },+ credentials: { apiKey: "test-key" },+ log: {+ debug: () => {},+ info: () => {},+ warn: () => {},+ error: () => {},+ },+ clientRawRequest: { endpoint: "/v1/chat/completions", headers: new Map() },+ connectionId,+ });++ assert.ok(result.success, "Request should succeed");+ assert.ok(capturedBody, "Fetch should have been called");++ // Verify that compression preserved the message structure+ assert.ok(Array.isArray(capturedBody.messages), "Messages should remain an array");+ assert.ok(capturedBody.messages.length > 0, "Messages should not be empty");++ // Verify that the final question was preserved (compression keeps recent messages)+ const lastMessage = capturedBody.messages[capturedBody.messages.length - 1];+ assert.equal(lastMessage.content, "Final question", "Last user message should be preserved");+ } finally {+ globalThis.fetch = originalFetch;+ }+});++test("chatCore integration: compressContext NOT called when context is below 85% threshold", async () => {+ const provider = "openai";+ const model = "gpt-4";+ const contextLimit = getTokenLimit(provider, model);+ const threshold = Math.floor(contextLimit * 0.85);++ const smallMessage = "Hello, how are you?";+ const body = {+ model,+ messages: [+ { role: "system", content: "You are helpful." },+ { role: "user", content: smallMessage },+ ],+ };++ const estimatedTokens = estimateTokens(JSON.stringify(body.messages));+ assert.ok(+ estimatedTokens < threshold,+ `Expected ${estimatedTokens} to be below threshold ${threshold}`+ );++ // Create provider connection+ const connectionId = await providersDb.createProviderConnection({+ provider,+ apiKey: "test-key",+ isActive: true,+ });++ // Mock fetch to capture the request+ let capturedBody: any = null;+ globalThis.fetch = async (url: string | URL | Request, init?: RequestInit) => {+ if (init?.body) {+ capturedBody = JSON.parse(init.body as string);+ }+ return new Response(+ JSON.stringify({+ choices: [{ message: { role: "assistant", content: "test" } }],+ usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 },+ }),+ {+ status: 200,+ headers: { "content-type": "application/json" },+ }+ );+ };++ try {+ const result = await handleChatCore({+ body,+ modelInfo: { provider, model },+ credentials: { apiKey: "test-key" },+ log: { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} },+ clientRawRequest: { endpoint: "/v1/chat/completions", headers: new Map() },+ connectionId,+ });++ assert.ok(result.success, "Request should succeed");+ assert.ok(capturedBody, "Fetch should have been called");++ // Verify NO compression occurred+ const originalTokens = estimateTokens(JSON.stringify(body.messages));+ const finalTokens = estimateTokens(JSON.stringify(capturedBody.messages));++ assert.equal(+ finalTokens,+ originalTokens,+ `Context should NOT be compressed: ${finalTokens} === ${originalTokens}`+ );+ } finally {+ globalThis.fetch = originalFetch;+ }+});++test("chatCore integration: compression preserves message structure", async () => {+ const provider = "openai";+ const model = "gpt-4";++ const body = {+ model,+ messages: [+ { role: "system", content: "You are helpful." },+ { role: "user", content: "x".repeat(50000) },+ { role: "assistant", content: "Response 1" },+ { role: "user", content: "x".repeat(50000) },+ { role: "assistant", content: "Response 2" },+ { role: "user", content: "Final question" },+ ],+ };++ // Create provider connection+ const connectionId = await providersDb.createProviderConnection({+ provider,+ apiKey: "test-key",+ isActive: true,+ });++ // Mock fetch to capture the request+ let capturedBody: any = null;+ globalThis.fetch = async (url: string | URL | Request, init?: RequestInit) => {+ if (init?.body) {+ capturedBody = JSON.parse(init.body as string);+ }+ return new Response(+ JSON.stringify({+ choices: [{ message: { role: "assistant", content: "test" } }],+ usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 },+ }),+ {+ status: 200,+ headers: { "content-type": "application/json" },+ }+ );+ };++ try {+ const result = await handleChatCore({+ body,+ modelInfo: { provider, model },+ credentials: { apiKey: "test-key" },+ log: {+ debug: (tag: string, msg: string) => console.log(`[DEBUG] ${tag}: ${msg}`),+ info: (tag: string, msg: string) => console.log(`[INFO] ${tag}: ${msg}`),+ warn: (tag: string, msg: string) => console.log(`[WARN] ${tag}: ${msg}`),+ error: (tag: string, msg: string) => console.log(`[ERROR] ${tag}: ${msg}`),+ },+ clientRawRequest: { endpoint: "/v1/chat/completions", headers: new Map() },+ connectionId,+ });++ assert.ok(result.success, "Request should succeed");+ assert.ok(capturedBody, "Fetch should have been called");+ assert.ok(Array.isArray(capturedBody.messages), "Messages should remain an array");+ assert.ok(capturedBody.messages.length > 0, "Messages should not be empty");++ const hasSystem = capturedBody.messages.some((m: any) => m.role === "system");+ assert.ok(hasSystem, "System message should be preserved");++ const lastMessage = capturedBody.messages[capturedBody.messages.length - 1];+ assert.equal(lastMessage.content, "Final question", "Last user message should be preserved");+ } finally {+ globalThis.fetch = originalFetch;+ }+});++test("chatCore integration: compression handles tool messages", async () => {+ const provider = "openai";+ const model = "gpt-4";++ const longToolOutput = "x".repeat(10000);+ const body = {+ model,+ messages: [+ { role: "system", content: "You are helpful." },+ { role: "user", content: "Run the tool" },+ { role: "assistant", content: "Running tool", tool_calls: [{ id: "t1", type: "function" }] },+ { role: "tool", content: longToolOutput, tool_call_id: "t1" },+ { role: "user", content: "What's the result?" },+ ],+ };++ // Create provider connection+ const connectionId = await providersDb.createProviderConnection({+ provider,+ apiKey: "test-key",+ isActive: true,+ });++ // Mock fetch to capture the request+ let capturedBody: any = null;+ globalThis.fetch = async (url: string | URL | Request, init?: RequestInit) => {+ if (init?.body) {+ capturedBody = JSON.parse(init.body as string);+ }+ return new Response(+ JSON.stringify({+ choices: [{ message: { role: "assistant", content: "test" } }],+ usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 },+ }),+ {+ status: 200,+ headers: { "content-type": "application/json" },+ }+ );+ };++ try {+ const result = await handleChatCore({+ body,+ modelInfo: { provider, model },+ credentials: { apiKey: "test-key" },+ log: { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} },+ clientRawRequest: { endpoint: "/v1/chat/completions", headers: new Map() },+ connectionId,+ });++ assert.ok(result.success, "Request should succeed");+ assert.ok(capturedBody, "Fetch should have been called");++ const toolMessage = capturedBody.messages.find((m: any) => m.role === "tool");+ assert.ok(toolMessage, "Tool message should exist");++ // Tool message should be truncated if compression was triggered+ if (toolMessage.content.length < longToolOutput.length) {+ assert.ok(+ toolMessage.content.includes("[truncated]"),+ "Tool message should have truncation marker"+ );+ }+ } finally {+ globalThis.fetch = originalFetch;+ }+});diff --git a/tests/integration/proxy-pipeline.test.ts b/tests/integration/proxy-pipeline.test.tsindex 6671f479ee..847c27cb4a 100644--- a/tests/integration/proxy-pipeline.test.ts+++ b/tests/integration/proxy-pipeline.test.ts@@ -71,7 +71,7 @@ describe("Chat Pipeline — handleSingleModelChat decomposition", () => {});it("chatCore should record cost for both non-streaming and streaming responses", () => {- assert.match(coreSrc, /if \(apiKeyInfo\?\.id && usage\)/);+ assert.match(coreSrc, /if \(apiKeyInfo\?\.id && estimatedCost > 0\)/);assert.match(coreSrc, /if \(apiKeyInfo\?\.id && streamUsage\)/);});});diff --git a/tests/unit/bailian-quota-fetcher.test.ts b/tests/unit/bailian-quota-fetcher.test.tsindex fc422ec535..472abfa438 100644--- a/tests/unit/bailian-quota-fetcher.test.ts+++ b/tests/unit/bailian-quota-fetcher.test.ts@@ -274,8 +274,8 @@ test("fetchBailianQuota retries with China host on ConsoleNeedLogin", async () =});assert.equal(calls.length, 2);- assert.ok(calls[0].url.includes("modelstudio.console.alibabacloud.com")); // lgtm[js/incomplete-url-substring-sanitization]- assert.ok(calls[1].url.includes("bailian.console.aliyun.com")); // lgtm[js/incomplete-url-substring-sanitization]+ assert.ok(calls[0].url.includes("://modelstudio.console.alibabacloud.com/"));+ assert.ok(calls[1].url.includes("://bailian.console.aliyun.com/"));assert.equal(quota?.percentUsed, 0.45);invalidateBailianQuotaCache(connectionId);@@ -449,7 +449,7 @@ test("ALIBABA_CODING_PLAN_HOST env var overrides default host", async () => {});assert.equal(calls.length, 1);- assert.ok(calls[0].url.includes("custom.bailian.aliyun.com")); // lgtm[js/incomplete-url-substring-sanitization]+ assert.ok(calls[0].url.includes("://custom.bailian.aliyun.com/"));assert.equal(quota?.percentUsed, 0.55);process.env.ALIBABA_CODING_PLAN_HOST = originalEnv;@@ -499,7 +499,7 @@ test("ALIBABA_CODING_PLAN_QUOTA_URL env var overrides full URL", async () => {});assert.equal(calls.length, 1);- assert.ok(calls[0].url.includes("override.example.com")); // lgtm[js/incomplete-url-substring-sanitization]+ assert.ok(calls[0].url.includes("://override.example.com/"));assert.equal(quota?.percentUsed, 0.2);process.env.ALIBABA_CODING_PLAN_QUOTA_URL = originalEnv;diff --git a/tests/unit/chat-route-edge-cases.test.ts b/tests/unit/chat-route-edge-cases.test.tsindex 53a4149aee..a9bf6ca72f 100644--- a/tests/unit/chat-route-edge-cases.test.ts+++ b/tests/unit/chat-route-edge-cases.test.ts@@ -245,7 +245,8 @@ test("Test 6: handleChat correctly sets isResponsesEndpoint for /v1/responses",const json = await response.json();assert.equal(response.status, 200);- assert.equal(json.choices[0].message.content, "Responses OK");+ const responseText = json.output_text || json.output?.[0]?.content?.[0]?.text;+ assert.equal(responseText, "Responses OK");});test("handleChat returns Semantic Cache hit", async () => {diff --git a/tests/unit/chatcore-compression-integration.test.ts b/tests/unit/chatcore-compression-integration.test.tsindex 8c08746e7c..66bccce02a 100644--- a/tests/unit/chatcore-compression-integration.test.ts+++ b/tests/unit/chatcore-compression-integration.test.ts@@ -10,14 +10,16 @@ test("chatCore integration: compressContext called proactively when context exceconst contextLimit = getTokenLimit(provider, model);const threshold = Math.floor(contextLimit * 0.85);- const largeMessage = "x".repeat(threshold * 4 + 1000);+ const history = Array.from({ length: 24 }, (_, index) => [+ { role: "user", content: `Question ${index}: ${"context ".repeat(80)}` },+ { role: "assistant", content: `Answer ${index}: ${"history ".repeat(80)}` },+ ]).flat();const body = {model,messages: [{ role: "system", content: "You are helpful." },- { role: "user", content: "Garbage 1".repeat(1000) },- { role: "assistant", content: "Garbage 2".repeat(1000) },- { role: "user", content: largeMessage },+ ...history,+ { role: "user", content: "Final question?" },],};@@ -38,6 +40,11 @@ test("chatCore integration: compressContext called proactively when context exceresult.stats.final <= contextLimit,`Final tokens ${result.stats.final} should fit within limit ${contextLimit}`);+ assert.equal(+ result.body.messages[result.body.messages.length - 1].content,+ "Final question?",+ "Latest user turn should be preserved after compression"+ );});test("chatCore integration: compressContext NOT called when context is below 85% threshold", async () => {diff --git a/tests/unit/context-manager.test.ts b/tests/unit/context-manager.test.tsindex 77d20aa023..25e966a2c6 100644--- a/tests/unit/context-manager.test.ts+++ b/tests/unit/context-manager.test.ts@@ -44,6 +44,20 @@ test("compressContext: returns unchanged if fits", () => {assert.equal(result.compressed, false);});+test("compressContext: default reserve scales down for smaller context windows", () => {+ const body = {+ model: "gpt-4",+ messages: [+ { role: "system", content: "You are helpful." },+ { role: "user", content: "Hello" },+ ],+ };++ const result = compressContext(body, { provider: "openai", maxTokens: 8192 });+ assert.equal(result.compressed, false);+ assert.equal(result.stats.final, result.stats.original);+});+test("compressContext: handles null/empty body", () => {assert.equal(compressContext(null).compressed, false);assert.equal(compressContext({}).compressed, false);diff --git a/tests/unit/db-core-init.test.ts b/tests/unit/db-core-init.test.tsindex cc88ab1da6..f953a635c2 100644--- a/tests/unit/db-core-init.test.ts+++ b/tests/unit/db-core-init.test.ts@@ -67,7 +67,7 @@ async function withEnv(overrides, fn) {if (value === undefined) {delete process.env[key];} else {- process.env[key] = value;+ process.env[key] = value as string;}}}diff --git a/tests/unit/db-migration-runner.test.ts b/tests/unit/db-migration-runner.test.tsindex d69d0b9e38..eae563eb0c 100644--- a/tests/unit/db-migration-runner.test.ts+++ b/tests/unit/db-migration-runner.test.ts@@ -31,13 +31,13 @@ function withMockedMigrationFs(files, fn) {return originalExistsSync(target);};- fs.readdirSync = (target, options) => {+ fs.readdirSync = ((target: string, options?: any) => {if (files && isMigrationDir(target)) {return Object.keys(files);}return originalReaddirSync(target, options);- };+ }) as any;fs.readFileSync = (target, options) => {const fileName = path.basename(String(target));@@ -183,13 +183,19 @@ test("runMigrations skips versions that are already tracked as applied", serial,assert.equal(secondRun, 0);assert.equal(- db.prepare("SELECT COUNT(*) AS count FROM _omniroute_migrations WHERE version = ?").get("001")- .count,+ (+ db+ .prepare("SELECT COUNT(*) AS count FROM _omniroute_migrations WHERE version = ?")+ .get("001") as any+ ).count,1);assert.equal(- db.prepare("SELECT COUNT(*) AS count FROM _omniroute_migrations WHERE version = ?").get("002")- .count,+ (+ db+ .prepare("SELECT COUNT(*) AS count FROM _omniroute_migrations WHERE version = ?")+ .get("002") as any+ ).count,1);} finally {@@ -269,9 +275,11 @@ test(undefined);assert.equal(- db- .prepare("SELECT COUNT(*) AS count FROM _omniroute_migrations WHERE version = ?")- .get("002").count,+ (+ db+ .prepare("SELECT COUNT(*) AS count FROM _omniroute_migrations WHERE version = ?")+ .get("002") as any+ ).count,0);} finally {@@ -666,7 +674,7 @@ test(assert.throws(() =>withNonTestEnvironment(() =>- withMockedMigrationFs(buildMockMigrationFiles(1, 12, "legacy_abort"), () =>+ withMockedMigrationFs(buildMockMigrationFiles(1, 60, "legacy_abort"), () =>runner.runMigrations(db))),diff --git a/tests/unit/executor-antigravity.test.ts b/tests/unit/executor-antigravity.test.tsindex 9edc21a79f..3fa9eec55c 100644--- a/tests/unit/executor-antigravity.test.ts+++ b/tests/unit/executor-antigravity.test.ts@@ -2,6 +2,10 @@ import test from "node:test";import assert from "node:assert/strict";import { AntigravityExecutor } from "../../open-sse/executors/antigravity.ts";+import {+ clearAntigravityVersionCache,+ seedAntigravityVersionCache,+} from "../../open-sse/services/antigravityVersion.ts";async function withEnv(name, value, fn) {const previous = process.env[name];@@ -22,6 +26,10 @@ async function withEnv(name, value, fn) {}}+test.afterEach(() => {+ clearAntigravityVersionCache();+});+test("AntigravityExecutor.buildUrl always targets the streaming endpoint", () => {const executor = new AntigravityExecutor();assert.match(@@ -215,6 +223,7 @@ test("AntigravityExecutor.execute auto-retries short 429 responses and collectsconst originalFetch = globalThis.fetch;const originalSetTimeout = globalThis.setTimeout;const calls = [];+ seedAntigravityVersionCache("2026.04.17-test");globalThis.fetch = async (url) => {calls.push(String(url));@@ -269,6 +278,7 @@ test("AntigravityExecutor.execute auto-retries short 429 responses and collectstest("AntigravityExecutor.execute embeds retryAfterMs when the upstream asks for a long wait", async () => {const executor = new AntigravityExecutor();const originalFetch = globalThis.fetch;+ seedAntigravityVersionCache("2026.04.17-test");globalThis.fetch = async () =>new Response(diff --git a/tests/unit/image-generation-route.test.ts b/tests/unit/image-generation-route.test.tsnew file mode 100644index 0000000000..164eb93680--- /dev/null+++ b/tests/unit/image-generation-route.test.ts@@ -0,0 +1,113 @@+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-image-route-"));+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 imageRoute = await import("../../src/app/api/v1/images/generations/route.ts");++const originalFetch = globalThis.fetch;++async function resetStorage() {+ globalThis.fetch = originalFetch;+ core.resetDbInstance();+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });+ fs.mkdirSync(TEST_DATA_DIR, { recursive: true });+}++async function seedConnection(provider: string, overrides: { apiKey?: string | null } = {}) {+ return providersDb.createProviderConnection({+ provider,+ authType: "apikey",+ name: `${provider}-${Math.random().toString(16).slice(2, 8)}`,+ apiKey: overrides.apiKey ?? "test-key",+ isActive: true,+ testStatus: "active",+ providerSpecificData: {},+ });+}++test.beforeEach(async () => {+ await resetStorage();+});++test.after(() => {+ globalThis.fetch = originalFetch;+ core.resetDbInstance();+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });+});++test("v1 image models GET exposes image-only modalities for image-only models", async () => {+ const response = await imageRoute.GET();+ const body = await response.json();+ const byId = new Map(body.data.map((item: { id: string }) => [item.id, item]));++ assert.equal(response.status, 200);+ assert.deepEqual(byId.get("topaz/topaz-enhance")?.input_modalities, ["image"]);+ assert.deepEqual(byId.get("stability-ai/remove-background")?.input_modalities, ["image"]);+ assert.deepEqual(byId.get("stability-ai/fast")?.input_modalities, ["image"]);+});++test("v1 image generation POST accepts promptless requests for image-only models", async () => {+ await seedConnection("topaz", { apiKey: "topaz-key" });++ globalThis.fetch = async (url, options = {}) => {+ const stringUrl = String(url);+ if (stringUrl === "https://example.com/topaz-input.png") {+ return new Response(new Uint8Array([1, 2, 3]), {+ status: 200,+ headers: { "content-type": "image/png" },+ });+ }++ if (stringUrl === "https://api.topazlabs.com/image/v1/enhance") {+ const formData = options.body as FormData;+ assert.ok(formData.get("image") instanceof File);+ return new Response(new Uint8Array([7, 7, 7]), {+ status: 200,+ headers: { "content-type": "image/jpeg" },+ });+ }++ throw new Error(`Unexpected URL: ${stringUrl}`);+ };++ const response = await imageRoute.POST(+ new Request("http://localhost/api/v1/images/generations", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ model: "topaz/topaz-enhance",+ image_url: "https://example.com/topaz-input.png",+ size: "2048x2048",+ response_format: "b64_json",+ }),+ })+ );+ const body = await response.json();++ assert.equal(response.status, 200);+ assert.equal(body.data[0].b64_json, "BwcH");+});++test("v1 image generation POST still requires prompts for text-input models", async () => {+ const response = await imageRoute.POST(+ new Request("http://localhost/api/v1/images/generations", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ model: "openai/dall-e-3",+ image_url: "https://example.com/source.png",+ }),+ })+ );+ const body = await response.json();++ assert.equal(response.status, 400);+ assert.match(body.error.message, /Prompt is required for image model: openai\/dall-e-3/);+});diff --git a/tests/unit/model-sync-route.test.ts b/tests/unit/model-sync-route.test.tsindex cb7972f729..829b1c9137 100644--- a/tests/unit/model-sync-route.test.ts+++ b/tests/unit/model-sync-route.test.ts@@ -442,11 +442,10 @@ test("model sync route records added, removed, and updated model diffs with fallassert.ok(logs[0].account.includes("*"), `Expected masked email, got: ${logs[0].account}`);});-test("model sync route accepts external API-key auth, forwards cookies, filters built-ins, and syncs aliases", async () => {+test("model sync route forwards cookies, filters built-ins, and syncs aliases for internal requests", async () => {await resetStorage();await enableAuth();- const authKey = await apiKeysDb.createApiKey("sync-external", "machine-sync");const connection = await providersDb.createProviderConnection({provider: "openrouter",authType: "apikey",@@ -479,8 +478,8 @@ test("model sync route accepts external API-key auth, forwards cookies, filtersnew Request(`http://localhost/api/providers/${connection.id}/sync-models`, {method: "POST",headers: {- authorization: `Bearer ${authKey.key}`,cookie: "session=test-cookie",+ ...scheduler.buildModelSyncInternalHeaders(),},}),{ params: { id: connection.id } }diff --git a/tests/unit/node-runtime-support.test.ts b/tests/unit/node-runtime-support.test.tsindex e57c573e2f..cf13684a5e 100644--- a/tests/unit/node-runtime-support.test.ts+++ b/tests/unit/node-runtime-support.test.ts@@ -7,6 +7,10 @@ import {getNodeRuntimeWarning,parseNodeVersion,} from "../../src/shared/utils/nodeRuntimeSupport.ts";+import {+ getNodeRuntimeSupport as getCliNodeRuntimeSupport,+ getNodeRuntimeWarning as getCliNodeRuntimeWarning,+} from "../../bin/nodeRuntimeSupport.mjs";test("parseNodeVersion normalizes v-prefixed versions", () => {assert.deepEqual(parseNodeVersion("v22.22.2"), {@@ -18,18 +22,27 @@ test("parseNodeVersion normalizes v-prefixed versions", () => {});});-test("getNodeRuntimeSupport accepts patched Node 22 and 20 LTS lines", () => {+test("getNodeRuntimeSupport accepts patched Node 24, 22 and 20 LTS lines", () => {assert.deepEqual(getNodeRuntimeSupport("22.22.2"), {nodeVersion: "v22.22.2",nodeCompatible: true,reason: "supported",supportedRange: SUPPORTED_NODE_RANGE,- supportedDisplay: "Node.js 20.20.2+ (20.x LTS) or 22.22.2+ (22.x LTS)",- recommendedVersion: "v22.22.2",+ supportedDisplay: "Node.js 20.20.2+ (20.x LTS), 22.22.2+ (22.x LTS), or 24.0.0+ (24.x LTS)",+ recommendedVersion: "v24.14.1",minimumSecureVersion: "v22.22.2",});assert.equal(getNodeRuntimeSupport("20.20.2").nodeCompatible, true);+ assert.deepEqual(getNodeRuntimeSupport("24.1.0"), {+ nodeVersion: "v24.1.0",+ nodeCompatible: true,+ reason: "supported",+ supportedRange: SUPPORTED_NODE_RANGE,+ supportedDisplay: "Node.js 20.20.2+ (20.x LTS), 22.22.2+ (22.x LTS), or 24.0.0+ (24.x LTS)",+ recommendedVersion: "v24.14.1",+ minimumSecureVersion: "v24.0.0",+ });});test("getNodeRuntimeSupport rejects versions below the secure floor in a supported line", () => {@@ -43,16 +56,22 @@ test("getNodeRuntimeSupport rejects versions below the secure floor in a supporttest("getNodeRuntimeSupport rejects unsupported major lines", () => {const node18 = getNodeRuntimeSupport("18.20.8");- const node24 = getNodeRuntimeSupport("24.1.0");+ const node25 = getNodeRuntimeSupport("25.1.0");assert.equal(node18.nodeCompatible, false);assert.equal(node18.reason, "unsupported-major");assert.match(getNodeRuntimeWarning("18.20.8") || "", /outside OmniRoute's approved secure/i);- assert.equal(node24.nodeCompatible, false);- assert.equal(node24.reason, "native-addon-incompatible");+ assert.equal(node25.nodeCompatible, false);+ assert.equal(node25.reason, "unreleased-major");assert.match(- getNodeRuntimeWarning("24.1.0") || "",- /better-sqlite3 does not support Node\.js 24\+/i+ getNodeRuntimeWarning("25.1.0") || "",+ /currently supports Node\.js 20\.x, 22\.x, and 24\.x/i);});++test("CLI runtime support stays aligned with the shared runtime policy", () => {+ assert.deepEqual(getCliNodeRuntimeSupport("24.1.0"), getNodeRuntimeSupport("24.1.0"));+ assert.deepEqual(getCliNodeRuntimeSupport("22.22.2"), getNodeRuntimeSupport("22.22.2"));+ assert.equal(getCliNodeRuntimeWarning("25.1.0"), getNodeRuntimeWarning("25.1.0"));+});diff --git a/tests/unit/prompt-required-routes.test.ts b/tests/unit/prompt-required-routes.test.tsnew file mode 100644index 0000000000..cd5e5c979e--- /dev/null+++ b/tests/unit/prompt-required-routes.test.ts@@ -0,0 +1,49 @@+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-prompt-required-routes-"));+process.env.DATA_DIR = TEST_DATA_DIR;++const core = await import("../../src/lib/db/core.ts");+const musicRoute = await import("../../src/app/api/v1/music/generations/route.ts");+const videoRoute = await import("../../src/app/api/v1/videos/generations/route.ts");++test.after(() => {+ core.resetDbInstance();+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });+});++test("v1 video generation POST rejects requests without a prompt", async () => {+ const response = await videoRoute.POST(+ new Request("http://localhost/api/v1/videos/generations", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ model: "comfyui/animatediff",+ }),+ })+ );+ const body = await response.json();++ assert.equal(response.status, 400);+ assert.match(body.error.message, /Prompt is required/);+});++test("v1 music generation POST rejects requests without a prompt", async () => {+ const response = await musicRoute.POST(+ new Request("http://localhost/api/v1/music/generations", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ model: "comfyui/musicgen-medium",+ }),+ })+ );+ const body = await response.json();++ assert.equal(response.status, 400);+ assert.match(body.error.message, /Prompt is required/);+});diff --git a/tests/unit/search-route.test.ts b/tests/unit/search-route.test.tsindex 0a947fe9cb..05ecfc4911 100644--- a/tests/unit/search-route.test.ts+++ b/tests/unit/search-route.test.ts@@ -176,3 +176,151 @@ test("v1 search POST accepts authless SearXNG with provider_options baseUrl", asglobalThis.fetch = originalFetch;}});++test("v1 search POST accepts authless SearXNG with the built-in default base URL", async () => {+ const originalFetch = globalThis.fetch;+ let capturedUrl = "";++ globalThis.fetch = async (url) => {+ capturedUrl = String(url);+ return new Response(+ JSON.stringify({+ results: [+ {+ title: "Default SearXNG result",+ url: "https://searx.example/default",+ content: "Default self-hosted response",+ engines: ["duckduckgo"],+ },+ ],+ }),+ { status: 200, headers: { "content-type": "application/json" } }+ );+ };++ try {+ const response = await searchRoute.POST(+ new Request("http://localhost/api/v1/search", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ query: "default self hosted meta search",+ provider: "searxng-search",+ search_type: "web",+ }),+ })+ );+ const body = await response.json();++ assert.equal(response.status, 200);+ assert.equal(+ capturedUrl,+ "http://localhost:8888/search?q=default+self+hosted+meta+search&format=json&categories=general"+ );+ assert.equal(body.provider, "searxng-search");+ assert.equal(body.results[0].title, "Default SearXNG result");+ } finally {+ globalThis.fetch = originalFetch;+ }+});++test("v1 search POST preserves stored SearXNG baseUrl for authless providers", async () => {+ await seedConnection("searxng-search", {+ apiKey: null,+ authType: "none",+ providerSpecificData: {+ baseUrl: "http://127.0.0.1:9090/custom-search",+ },+ });++ const originalFetch = globalThis.fetch;+ let capturedUrl = "";++ globalThis.fetch = async (url) => {+ capturedUrl = String(url);+ return new Response(+ JSON.stringify({+ results: [+ {+ title: "Stored SearXNG result",+ url: "https://searx.example/stored",+ content: "Stored self-hosted response",+ engines: ["duckduckgo"],+ },+ ],+ }),+ { status: 200, headers: { "content-type": "application/json" } }+ );+ };++ try {+ const response = await searchRoute.POST(+ new Request("http://localhost/api/v1/search", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ query: "stored self hosted meta search",+ provider: "searxng-search",+ search_type: "web",+ }),+ })+ );+ const body = await response.json();++ assert.equal(response.status, 200);+ assert.equal(+ capturedUrl,+ "http://127.0.0.1:9090/custom-search/search?q=stored+self+hosted+meta+search&format=json&categories=general"+ );+ assert.equal(body.provider, "searxng-search");+ assert.equal(body.results[0].title, "Stored SearXNG result");+ } finally {+ globalThis.fetch = originalFetch;+ }+});++test("v1 search POST auto-select uses authless SearXNG when no API-key providers are configured", async () => {+ const originalFetch = globalThis.fetch;+ let capturedUrl = "";++ globalThis.fetch = async (url) => {+ capturedUrl = String(url);+ return new Response(+ JSON.stringify({+ results: [+ {+ title: "Auto-selected SearXNG result",+ url: "https://searx.example/auto",+ content: "Auto-selected self-hosted response",+ engines: ["duckduckgo"],+ },+ ],+ }),+ { status: 200, headers: { "content-type": "application/json" } }+ );+ };++ try {+ const response = await searchRoute.POST(+ new Request("http://localhost/api/v1/search", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ query: "auto select self hosted search",+ search_type: "web",+ }),+ })+ );+ const body = await response.json();++ assert.equal(response.status, 200);+ assert.equal(+ capturedUrl,+ "http://localhost:8888/search?q=auto+select+self+hosted+search&format=json&categories=general"+ );+ assert.equal(body.provider, "searxng-search");+ assert.equal(body.results[0].title, "Auto-selected SearXNG result");+ } finally {+ globalThis.fetch = originalFetch;+ }+});diff --git a/tests/unit/usage-fetcher-antigravity.test.ts b/tests/unit/usage-fetcher-antigravity.test.tsindex 5d34e266e0..5bb58104a1 100644--- a/tests/unit/usage-fetcher-antigravity.test.ts+++ b/tests/unit/usage-fetcher-antigravity.test.ts@@ -15,9 +15,11 @@ test("usage fetcher retries Antigravity quota discovery across shared fallback UglobalThis.fetch = async (url, init = {}) => {calls.push({ url: String(url), init });- // Mock the first two to fail with 503- if (String(url).includes("cloudcode-pa.googleapis.com") && !String(url).includes("sandbox")) {- // lgtm[js/incomplete-url-substring-sanitization]+ const urlStr = String(url);+ if (+ urlStr === "https://cloudcode-pa.googleapis.com/v1internal:fetchAvailableModels" ||+ urlStr === "https://daily-cloudcode-pa.googleapis.com/v1internal:fetchAvailableModels"+ ) {return new Response("unavailable", { status: 503 });}diff --git a/tests/unit/usage-service-hardening.test.ts b/tests/unit/usage-service-hardening.test.tsindex f09cd8f147..5adda83709 100644--- a/tests/unit/usage-service-hardening.test.ts+++ b/tests/unit/usage-service-hardening.test.ts@@ -247,7 +247,7 @@ test("usage service covers Gemini CLI tier-label fallbacks and fetch error handlif (String(_url).includes("loadCodeAssist")) {return new Response(JSON.stringify({ currentTier: { id: "tier_pro" } }), { status: 200 });}- assert.ok(String(init.body).includes("project-throw"));+ assert.ok(String((init as any).body).includes("project-throw"));throw new Error("quota endpoint offline");};const fetchError: any = await usageService.getUsageForProvider({@@ -365,7 +365,8 @@ test("usage service retries Antigravity fetchAvailableModels across the shared freturn new Response("bad gateway", { status: 502 });}- if (String(url).startsWith("https://daily-cloudcode-pa.googleapis.com/")) {+ const urlStr = String(url);+ if (urlStr.includes("://daily-cloudcode-pa.googleapis.com/")) {return new Response("bad gateway", { status: 502 });}@@ -552,7 +553,7 @@ test("usage service covers Claude default-plan fallback, legacy org denial and ftest("usage service covers Codex, Kiro and Kimi usage parsing and error branches", async () => {globalThis.fetch = async (url, init = {}) => {if (String(url).includes("/backend-api/wham/usage")) {- assert.equal(init.headers["chatgpt-account-id"], "workspace-123");+ assert.equal((init as any).headers["chatgpt-account-id"], "workspace-123");return new Response(JSON.stringify({plan_type: "plus",@@ -796,7 +797,7 @@ test("usage service covers Qwen, Qoder, GLM and GLMT branches", async () => {globalThis.fetch = async (url, init = {}) => {if (String(url).includes("/api/monitor/usage/quota/limit")) {- assert.equal(init.headers.Authorization, "Bearer glm-key");+ assert.equal((init as any).headers.Authorization, "Bearer glm-key");return new Response(JSON.stringify({data: {