Skip to content

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

fix(core): resolve runtime edge cases and TypeScript regressions

diegosouzapwfceb9d414574
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 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-15
diff --git a/open-sse/handlers/responseSanitizer.ts b/open-sse/handlers/responseSanitizer.ts
index 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.ts
index 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.ts
index df9e4e0a9d..bbb115cd30 100644
--- a/open-sse/services/claudeCodeCompatible.ts
+++ b/open-sse/services/claudeCodeCompatible.ts
@@ -705,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
diff --git a/open-sse/services/provider.ts b/open-sse/services/provider.ts
index 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.ts
index 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 check
diff --git a/open-sse/services/wildcardRouter.ts b/open-sse/services/wildcardRouter.ts
index 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 original
return 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.ts
index 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 translator
import { 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 passes
if (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 markers
if (!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, preserveCacheControl
let 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 markers
if (!preserveCacheControl && !lastAssistantProcessed && markMessageCacheControl(msg)) {
@@ -210,7 +248,7 @@ export function prepareClaudeRequest(body, provider = null, preserveCacheControl
let 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 thinking
if (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.ts
index 86adc6a639..a883ecb594 100644
--- a/open-sse/utils/proxyFetch.ts
+++ b/open-sse/utils/proxyFetch.ts
@@ -225,6 +225,7 @@ async function patchedFetch(input: RequestInfo | URL, options: FetchWithDispatch
return 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.ts
index 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.ts
index 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_tokens
const 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, api
cacheCreation: 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/lib/dataPaths.js b/src/lib/dataPaths.js
index 5078bbe9e6..6f9b0b626f 100644
--- a/src/lib/dataPaths.js
+++ b/src/lib/dataPaths.js
@@ -1,66 +1,69 @@
-"use strict";
-var __importDefault =
- (this && this.__importDefault) ||
- function (mod) {
- return mod && mod.__esModule ? mod : { default: mod };
- };
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.APP_NAME = void 0;
-exports.getLegacyDotDataDir = getLegacyDotDataDir;
-exports.getDefaultDataDir = getDefaultDataDir;
-exports.resolveDataDir = resolveDataDir;
-exports.isSamePath = isSamePath;
-const path_1 = __importDefault(require("path"));
-const os_1 = __importDefault(require("os"));
-exports.APP_NAME = "omniroute";
+import os from "os";
+import path from "path";
+
+export const APP_NAME = "omniroute";
+
function fallbackHomeDir() {
const envHome = process.env.HOME || process.env.USERPROFILE;
if (typeof envHome === "string" && envHome.trim().length > 0) {
- return path_1.default.resolve(envHome);
+ return path.resolve(envHome);
}
- return os_1.default.tmpdir();
+
+ return os.tmpdir();
}
+
function safeHomeDir() {
try {
- return os_1.default.homedir();
+ return os.homedir();
} catch {
return fallbackHomeDir();
}
}
+
function normalizeConfiguredPath(dir) {
if (typeof dir !== "string") return null;
const trimmed = dir.trim();
if (!trimmed) return null;
- return path_1.default.resolve(trimmed);
+ return path.resolve(trimmed);
}
-function getLegacyDotDataDir() {
- return path_1.default.join(safeHomeDir(), `.${exports.APP_NAME}`);
+
+export function getLegacyDotDataDir() {
+ return path.join(safeHomeDir(), `.${APP_NAME}`);
}
-function getDefaultDataDir() {
+
+export function getDefaultDataDir() {
const homeDir = safeHomeDir();
+
if (process.platform === "win32") {
- const appData = process.env.APPDATA || path_1.default.join(homeDir, "AppData", "Roaming");
- return path_1.default.join(appData, exports.APP_NAME);
+ const appData = process.env.APPDATA || path.join(homeDir, "AppData", "Roaming");
+ return path.join(appData, APP_NAME);
}
- // Support XDG on Linux/macOS when explicitly configured.
+
const xdgConfigHome = normalizeConfiguredPath(process.env.XDG_CONFIG_HOME);
if (xdgConfigHome) {
- return path_1.default.join(xdgConfigHome, exports.APP_NAME);
+ return path.join(xdgConfigHome, APP_NAME);
}
+
return getLegacyDotDataDir();
}
-function resolveDataDir({ isCloud = false } = {}) {
+
+export function resolveDataDir({ isCloud = false } = {}) {
if (isCloud) return "/tmp";
+
const configured = normalizeConfiguredPath(process.env.DATA_DIR);
if (configured) return configured;
+
return getDefaultDataDir();
}
-function isSamePath(a, b) {
+
+export function isSamePath(a, b) {
if (!a || !b) return false;
- const normalizedA = path_1.default.resolve(a);
- const normalizedB = path_1.default.resolve(b);
+ const normalizedA = path.resolve(a);
+ const normalizedB = path.resolve(b);
+
if (process.platform === "win32") {
return normalizedA.toLowerCase() === normalizedB.toLowerCase();
}
+
return normalizedA === normalizedB;
}
diff --git a/src/lib/usage/usageStats.ts b/src/lib/usage/usageStats.ts
index 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/tests/e2e/memory-settings.spec.ts b/tests/e2e/memory-settings.spec.ts
index 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.ts
index 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.ts
index 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/proxy-pipeline.test.ts b/tests/integration/proxy-pipeline.test.ts
index 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/chat-route-edge-cases.test.ts b/tests/unit/chat-route-edge-cases.test.ts
index 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/db-migration-runner.test.ts b/tests/unit/db-migration-runner.test.ts
index 3e171051af..eae563eb0c 100644
--- a/tests/unit/db-migration-runner.test.ts
+++ b/tests/unit/db-migration-runner.test.ts
@@ -674,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.ts
index 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 collects
const 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 collects
test("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/model-sync-route.test.ts b/tests/unit/model-sync-route.test.ts
index 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 fall
assert.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, filters
new 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 } }