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
feat(skills): add workspace-scoped builtins with sandbox execution
diegosouzapw354725828277
diff --git a/open-sse/config/providerRegistry.ts b/open-sse/config/providerRegistry.tsindex f983bced60..bc8044a3cf 100644--- a/open-sse/config/providerRegistry.ts+++ b/open-sse/config/providerRegistry.ts@@ -962,37 +962,6 @@ export const REGISTRY: Record<string, RegistryEntry> = {],},- crof: {- id: "crof",- alias: "crof",- format: "openai",- executor: "default",- baseUrl: "https://crof.ai/v1/chat/completions",- authType: "apikey",- authHeader: "bearer",- // Seed list — runtime /v1/models discovery keeps this fresh.- // Source: GET https://crof.ai/v1/models (2026-04-25).- models: [- { id: "deepseek-v4-pro", name: "DeepSeek V4 Pro" },- { id: "deepseek-v3.2", name: "DeepSeek V3.2" },- { id: "kimi-k2.6", name: "Kimi K2.6" },- { id: "kimi-k2.6-precision", name: "Kimi K2.6 (Precision)" },- { id: "kimi-k2.5", name: "Kimi K2.5" },- { id: "kimi-k2.5-lightning", name: "Kimi K2.5 (Lightning)" },- { id: "glm-5.1", name: "GLM 5.1" },- { id: "glm-5.1-precision", name: "GLM 5.1 (Precision)" },- { id: "glm-5", name: "GLM 5" },- { id: "glm-4.7", name: "GLM 4.7" },- { id: "glm-4.7-flash", name: "GLM 4.7 Flash" },- { id: "gemma-4-31b-it", name: "Gemma 4 31B" },- { id: "minimax-m2.5", name: "MiniMax M2.5" },- { id: "qwen3.6-27b", name: "Qwen3.6 27B" },- { id: "qwen3.5-397b-a17b", name: "Qwen3.5 397B A17B" },- { id: "qwen3.5-9b", name: "Qwen3.5 9B" },- { id: "qwen3.5-9b-chat", name: "Qwen3.5 9B (Chat)" },- ],- },-alicode: {id: "alicode",alias: "alicode",diff --git a/src/app/(dashboard)/dashboard/HomePageClient.tsx b/src/app/(dashboard)/dashboard/HomePageClient.tsxindex 3c79de9de2..adf7b079e2 100644--- a/src/app/(dashboard)/dashboard/HomePageClient.tsx+++ b/src/app/(dashboard)/dashboard/HomePageClient.tsx@@ -636,7 +636,7 @@ export default function HomePageClient({ machineId }) {<p className="text-text-muted mt-0.5">{t.rich("step4Desc", {logs: (chunks) => (- <Link href="/dashboard/usage" className="text-primary hover:underline">+ <Link href="/dashboard/logs" className="text-primary hover:underline">{chunks}</Link>),diff --git a/src/app/(dashboard)/dashboard/settings/components/MemorySkillsTab.tsx b/src/app/(dashboard)/dashboard/settings/components/MemorySkillsTab.tsxindex 5c0468f6f1..7b2dc38b8c 100644--- a/src/app/(dashboard)/dashboard/settings/components/MemorySkillsTab.tsx+++ b/src/app/(dashboard)/dashboard/settings/components/MemorySkillsTab.tsx@@ -280,7 +280,6 @@ export default function MemorySkillsTab() {)}</Card>- {/* Skills Settings (placeholder) */}<Card data-testid="skills-settings-card"><div className="flex items-center gap-3 mb-5"><div className="p-2 rounded-lg bg-amber-500/10 text-amber-500">diff --git a/src/app/(dashboard)/dashboard/usage/page.tsx b/src/app/(dashboard)/dashboard/usage/page.tsxnew file mode 100644index 0000000000..f4517e5f9e--- /dev/null+++ b/src/app/(dashboard)/dashboard/usage/page.tsx@@ -0,0 +1,5 @@+import { redirect } from "next/navigation";++export default function UsageRedirectPage() {+ redirect("/dashboard/logs");+}diff --git a/src/lib/skills/builtin/browser.ts b/src/lib/skills/builtin/browser.tsindex 57b73cee33..560018f2a5 100644--- a/src/lib/skills/builtin/browser.ts+++ b/src/lib/skills/builtin/browser.ts@@ -1,33 +1,20 @@import { SkillHandler } from "../types";export const browserSkill: SkillHandler = async (input, context) => {- const { action, ...params } = input as {+ const { action } = input as {action: "navigate" | "click" | "type" | "screenshot" | "extract";url?: string;selector?: string;text?: string;};- switch (action) {- case "navigate":- return { success: true, action: "navigate", url: params.url, stub: true };- case "click":- return { success: true, action: "click", selector: params.selector, stub: true };- case "type":- return {- success: true,- action: "type",- selector: params.selector,- text: params.text,- stub: true,- };- case "screenshot":- return { success: true, action: "screenshot", stub: true };- case "extract":- return { success: true, action: "extract", selector: params.selector, data: {}, stub: true };- default:- throw new Error(`Unknown action: ${action}`);+ if (!["navigate", "click", "type", "screenshot", "extract"].includes(action)) {+ throw new Error(`Unknown action: ${action}`);}++ throw new Error(+ "Browser automation skill is disabled. Configure a Playwright-backed browser runtime before enabling this skill."+ );};export function registerBrowserSkill(executor: any): void {diff --git a/src/lib/skills/builtins.ts b/src/lib/skills/builtins.tsindex 08eb50ba8b..d602c05c77 100644--- a/src/lib/skills/builtins.ts+++ b/src/lib/skills/builtins.ts@@ -1,29 +1,316 @@import { SkillHandler } from "./types";import { executeWebSearch } from "@/lib/search/executeWebSearch";+import { resolveDataDir } from "@/lib/dataPaths";+import { safeOutboundFetch } from "@/shared/network/safeOutboundFetch";+import { sandboxRunner, type SandboxConfig } from "./sandbox";+import { createHash } from "crypto";+import fs from "fs/promises";+import path from "path";++const MAX_FILE_BYTES = Number.parseInt(process.env.SKILLS_MAX_FILE_BYTES || "", 10) || 1_048_576;+const MAX_HTTP_RESPONSE_BYTES =+ Number.parseInt(process.env.SKILLS_MAX_HTTP_RESPONSE_BYTES || "", 10) || 256_000;+const MAX_SANDBOX_OUTPUT_CHARS =+ Number.parseInt(process.env.SKILLS_MAX_SANDBOX_OUTPUT_CHARS || "", 10) || 100_000;+const DEFAULT_SANDBOX_TIMEOUT_MS =+ Number.parseInt(process.env.SKILLS_SANDBOX_TIMEOUT_MS || "", 10) || 10_000;+const SANDBOX_NETWORK_ENABLED =+ process.env.SKILLS_SANDBOX_NETWORK_ENABLED === "1" ||+ process.env.SKILLS_SANDBOX_NETWORK_ENABLED === "true";+const DEFAULT_COMMAND_IMAGE = "alpine:3.20";+const DEFAULT_JS_IMAGE = "node:22-alpine";+const DEFAULT_PYTHON_IMAGE = "python:3.12-alpine";+const ALLOWED_SANDBOX_IMAGES = new Set(+ (process.env.SKILLS_ALLOWED_SANDBOX_IMAGES || "")+ .split(",")+ .map((value) => value.trim())+ .filter(Boolean)+);++for (const image of [DEFAULT_COMMAND_IMAGE, DEFAULT_JS_IMAGE, DEFAULT_PYTHON_IMAGE]) {+ ALLOWED_SANDBOX_IMAGES.add(image);+}++const FORBIDDEN_PATH_SEGMENTS = new Set([+ ".env",+ ".git",+ ".ssh",+ ".omniroute",+ ".codex",+ "secrets",+]);+const ALLOWED_HTTP_METHODS = new Set(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"]);+const BLOCKED_REQUEST_HEADERS = new Set([+ "host",+ "connection",+ "content-length",+ "cookie",+ "set-cookie",+ "authorization",+ "proxy-authorization",+]);++function getContextId(context: { apiKeyId: string }) {+ return createHash("sha256")+ .update(context.apiKeyId || "anonymous")+ .digest("hex")+ .slice(0, 24);+}++function getWorkspaceRoot(context: { apiKeyId: string }) {+ return path.join(resolveDataDir(), "skills", "workspaces", getContextId(context));+}++function resolveWorkspacePath(inputPath: string, context: { apiKeyId: string }) {+ if (path.isAbsolute(inputPath)) {+ throw new Error("Skill file paths must be relative to the skill workspace");+ }++ const segments = inputPath.split(/[\\/]+/).filter(Boolean);+ if (segments.some((segment) => FORBIDDEN_PATH_SEGMENTS.has(segment.toLowerCase()))) {+ throw new Error("Skill file path contains a restricted segment");+ }++ const root = path.resolve(getWorkspaceRoot(context));+ const resolved = path.resolve(root, inputPath);+ const relative = path.relative(root, resolved);+ if (!relative || relative.startsWith("..") || path.isAbsolute(relative)) {+ throw new Error("Skill file path escapes the skill workspace");+ }++ return { root, resolved, relative };+}++function normalizePositiveInteger(value: unknown, fallback: number, max: number) {+ if (value === undefined || value === null) return fallback;+ const parsed = Number(value);+ if (!Number.isInteger(parsed) || parsed <= 0) return fallback;+ return Math.min(parsed, max);+}++function sanitizeHeaders(headers: unknown) {+ if (!headers || typeof headers !== "object" || Array.isArray(headers)) return undefined;++ const sanitized: Record<string, string> = {};+ for (const [key, value] of Object.entries(headers as Record<string, unknown>)) {+ const normalizedKey = key.trim();+ if (!normalizedKey || BLOCKED_REQUEST_HEADERS.has(normalizedKey.toLowerCase())) continue;+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {+ sanitized[normalizedKey] = String(value);+ }+ }++ return Object.keys(sanitized).length > 0 ? sanitized : undefined;+}++async function readResponseText(response: Response, maxBytes: number) {+ const reader = response.body?.getReader();+ if (!reader) return { body: "", truncated: false };++ const decoder = new TextDecoder();+ const chunks: Uint8Array[] = [];+ let bytesRead = 0;+ let truncated = false;++ while (true) {+ const { value, done } = await reader.read();+ if (done) break;+ if (!value) continue;++ const remaining = maxBytes - bytesRead;+ if (remaining <= 0) {+ truncated = true;+ await reader.cancel();+ break;+ }++ const chunk = value.byteLength > remaining ? value.slice(0, remaining) : value;+ chunks.push(chunk);+ bytesRead += chunk.byteLength;++ if (value.byteLength > remaining) {+ truncated = true;+ await reader.cancel();+ break;+ }+ }++ return {+ body:+ chunks.map((chunk) => decoder.decode(chunk, { stream: true })).join("") + decoder.decode(),+ truncated,+ };+}++function normalizeBody(body: unknown, headers?: Record<string, string>) {+ if (body === undefined || body === null) return undefined;+ if (typeof body === "string") return body;+ if (body instanceof Uint8Array) return body;+ if (typeof body === "object") {+ if (headers && !Object.keys(headers).some((key) => key.toLowerCase() === "content-type")) {+ headers["Content-Type"] = "application/json";+ }+ return JSON.stringify(body);+ }+ return String(body);+}++function normalizeImage(image: unknown, fallback: string) {+ const selected = typeof image === "string" && image.trim() ? image.trim() : fallback;+ if (!ALLOWED_SANDBOX_IMAGES.has(selected)) {+ throw new Error(`Sandbox image is not allowed: ${selected}`);+ }+ return selected;+}++function sandboxConfig(input: {+ timeoutMs?: unknown;+ networkEnabled?: unknown;+}): Partial<SandboxConfig> {+ const requestedNetwork = input.networkEnabled === true;+ return {+ timeout: normalizePositiveInteger(input.timeoutMs, DEFAULT_SANDBOX_TIMEOUT_MS, 60_000),+ networkEnabled: requestedNetwork && SANDBOX_NETWORK_ENABLED,+ readOnly: true,+ };+}++function truncateOutput(value: string) {+ if (value.length <= MAX_SANDBOX_OUTPUT_CHARS) return { value, truncated: false };+ return { value: value.slice(0, MAX_SANDBOX_OUTPUT_CHARS), truncated: true };+}++function normalizeArgs(args: unknown): string[] {+ if (args === undefined) return [];+ if (!Array.isArray(args)) throw new Error("Field args must be an array");+ return args.map((arg) => {+ if (typeof arg !== "string" && typeof arg !== "number" && typeof arg !== "boolean") {+ throw new Error("Command arguments must be strings, numbers, or booleans");+ }+ return String(arg);+ });+}export const builtinSkills: Record<string, SkillHandler> = {file_read: async (input, context) => {- const { path } = input as { path: string };- if (!path || typeof path !== "string") {+ const { path: inputPath, encoding = "utf8" } = input as {+ path: string;+ encoding?: BufferEncoding;+ };+ if (!inputPath || typeof inputPath !== "string") {throw new Error("Missing required field: path");}- return { success: true, path, content: "[File read stub]", context: context.apiKeyId };+ if (encoding !== "utf8" && encoding !== "base64") {+ throw new Error("Unsupported encoding. Use utf8 or base64.");+ }++ const { resolved, relative } = resolveWorkspacePath(inputPath, context);+ const stat = await fs.stat(resolved);+ if (!stat.isFile()) throw new Error("Skill file path must point to a file");+ if (stat.size > MAX_FILE_BYTES) {+ throw new Error(`Skill file exceeds the ${MAX_FILE_BYTES} byte read limit`);+ }++ return {+ success: true,+ path: relative,+ content: await fs.readFile(resolved, encoding),+ bytesRead: stat.size,+ encoding,+ context: context.apiKeyId,+ };},file_write: async (input, context) => {- const { path, content } = input as { path: string; content: string };- if (!path || !content) {+ const {+ path: inputPath,+ content,+ append = false,+ overwrite = true,+ } = input as {+ path: string;+ content: string;+ append?: boolean;+ overwrite?: boolean;+ };+ if (!inputPath || typeof inputPath !== "string" || typeof content !== "string") {throw new Error("Missing required fields: path, content");}- return { success: true, path, bytesWritten: content.length, context: context.apiKeyId };++ const bytesWritten = Buffer.byteLength(content, "utf8");+ if (bytesWritten > MAX_FILE_BYTES) {+ throw new Error(`Skill file write exceeds the ${MAX_FILE_BYTES} byte limit`);+ }++ const { resolved, relative } = resolveWorkspacePath(inputPath, context);+ await fs.mkdir(path.dirname(resolved), { recursive: true });+ await fs.writeFile(resolved, content, {+ encoding: "utf8",+ flag: append ? "a" : overwrite ? "w" : "wx",+ });++ return { success: true, path: relative, bytesWritten, context: context.apiKeyId };},http_request: async (input, context) => {- const { url, method = "GET" } = input as { url: string; method?: string };- if (!url) {+ const {+ url,+ method = "GET",+ headers: rawHeaders,+ body,+ timeoutMs,+ maxBytes,+ } = input as {+ url: string;+ method?: string;+ headers?: Record<string, unknown>;+ body?: unknown;+ timeoutMs?: number;+ maxBytes?: number;+ };+ if (!url || typeof url !== "string") {throw new Error("Missing required field: url");}- return { success: true, url, method, status: 200, context: context.apiKeyId };++ const normalizedMethod = method.toUpperCase();+ if (!ALLOWED_HTTP_METHODS.has(normalizedMethod)) {+ throw new Error(`Unsupported HTTP method: ${method}`);+ }++ const headers = sanitizeHeaders(rawHeaders);+ const response = await safeOutboundFetch(url, {+ method: normalizedMethod,+ headers,+ body:+ normalizedMethod === "GET" || normalizedMethod === "HEAD"+ ? undefined+ : normalizeBody(body, headers),+ timeoutMs: normalizePositiveInteger(timeoutMs, 10_000, 60_000),+ allowRedirect: false,+ retry: false,+ guard: "public-only",+ });+ const limit = normalizePositiveInteger(+ maxBytes,+ MAX_HTTP_RESPONSE_BYTES,+ MAX_HTTP_RESPONSE_BYTES+ );+ const responseBody =+ normalizedMethod === "HEAD"+ ? { body: "", truncated: false }+ : await readResponseText(response, limit);++ return {+ success: response.ok,+ url,+ method: normalizedMethod,+ status: response.status,+ statusText: response.statusText,+ headers: Object.fromEntries(response.headers.entries()),+ body: responseBody.body,+ truncated: responseBody.truncated,+ context: context.apiKeyId,+ };},web_search: async (input, context) => {@@ -98,23 +385,100 @@ export const builtinSkills: Record<string, SkillHandler> = {},eval_code: async (input, context) => {- const { code, language = "javascript" } = input as { code: string; language?: string };- if (!code) {+ const {+ code,+ language = "javascript",+ image,+ timeoutMs,+ networkEnabled,+ } = input as {+ code: string;+ language?: string;+ image?: string;+ timeoutMs?: number;+ networkEnabled?: boolean;+ };+ if (!code || typeof code !== "string") {throw new Error("Missing required field: code");}- return { success: true, language, output: "[Code execution stub]", context: context.apiKeyId };++ const normalizedLanguage = language.toLowerCase();+ let selectedImage: string;+ let command: string[];+ if (normalizedLanguage === "javascript" || normalizedLanguage === "js") {+ selectedImage = normalizeImage(image, DEFAULT_JS_IMAGE);+ command = ["node", "--eval", code];+ } else if (normalizedLanguage === "python" || normalizedLanguage === "py") {+ selectedImage = normalizeImage(image, DEFAULT_PYTHON_IMAGE);+ command = ["python", "-c", code];+ } else {+ throw new Error(`Unsupported code language: ${language}`);+ }++ const result = await sandboxRunner.run(+ selectedImage,+ command,+ {},+ sandboxConfig({ timeoutMs, networkEnabled })+ );+ const stdout = truncateOutput(result.stdout);+ const stderr = truncateOutput(result.stderr);+ return {+ success: result.exitCode === 0,+ language: normalizedLanguage,+ image: selectedImage,+ exitCode: result.exitCode,+ stdout: stdout.value,+ stderr: stderr.value,+ output: stdout.value,+ truncated: stdout.truncated || stderr.truncated,+ durationMs: result.duration,+ killed: result.killed,+ context: context.apiKeyId,+ };},execute_command: async (input, context) => {- const { command, args = [] } = input as { command: string; args?: string[] };- if (!command) {+ const {+ command,+ args = [],+ image,+ timeoutMs,+ networkEnabled,+ } = input as {+ command: string;+ args?: unknown[];+ image?: string;+ timeoutMs?: number;+ networkEnabled?: boolean;+ };+ if (!command || typeof command !== "string") {throw new Error("Missing required field: command");}++ const normalizedArgs = normalizeArgs(args);+ const selectedImage = normalizeImage(image, DEFAULT_COMMAND_IMAGE);+ const result = await sandboxRunner.run(+ selectedImage,+ [command, ...normalizedArgs],+ {},+ sandboxConfig({ timeoutMs, networkEnabled })+ );+ const stdout = truncateOutput(result.stdout);+ const stderr = truncateOutput(result.stderr);+return {- success: true,+ success: result.exitCode === 0,command,- args,- output: "[Command execution stub]",+ args: normalizedArgs,+ image: selectedImage,+ exitCode: result.exitCode,+ stdout: stdout.value,+ stderr: stderr.value,+ output: stdout.value,+ truncated: stdout.truncated || stderr.truncated,+ durationMs: result.duration,+ killed: result.killed,context: context.apiKeyId,};},diff --git a/src/lib/skills/sandbox.ts b/src/lib/skills/sandbox.tsindex 3abefb8924..820d58c80c 100644--- a/src/lib/skills/sandbox.ts+++ b/src/lib/skills/sandbox.ts@@ -1,6 +1,10 @@-import { spawn, ChildProcess } from "child_process";+import { createRequire } from "module";+import type { ChildProcess } from "child_process";import { randomUUID } from "crypto";+const require = createRequire(import.meta.url);+const childProcess = require("child_process") as typeof import("child_process");+interface SandboxConfig {cpuLimit: number;memoryLimit: number;@@ -49,10 +53,12 @@ class SandboxRunner {async run(image: string,command: string[],- env: Record<string, string> = {}+ env: Record<string, string> = {},+ configOverride: Partial<SandboxConfig> = {}): Promise<SandboxResult> {const sandboxId = randomUUID();const startTime = Date.now();+ const config = { ...this.config, ...configOverride };const dockerArgs = ["run",@@ -60,23 +66,33 @@ class SandboxRunner {"--name",`omniroute-sandbox-${sandboxId}`,"--cpus",- `${this.config.cpuLimit / 1000}`,+ `${config.cpuLimit / 1000}`,"--memory",- `${this.config.memoryLimit}m`,+ `${config.memoryLimit}m`,"--network",- this.config.networkEnabled ? "bridge" : "none",- "--read-only",- this.config.readOnly.toString(),- "--cap-add",- "SYS_TIME",+ config.networkEnabled ? "bridge" : "none",+ "--cap-drop",+ "ALL",+ "--security-opt",+ "no-new-privileges","--pids-limit","100",- image,- ...command,+ "--tmpfs",+ "/tmp:rw,noexec,nosuid,size=64m",+ "--tmpfs",+ "/workspace:rw,noexec,nosuid,size=64m",+ "--workdir",+ "/workspace",];+ if (config.readOnly) {+ dockerArgs.push("--read-only");+ }++ dockerArgs.push(image, ...command);+return new Promise((resolve) => {- const proc = spawn("docker", dockerArgs, {+ const proc = childProcess.spawn("docker", dockerArgs, {env: { ...process.env, ...env },stdio: ["ignore", "pipe", "pipe"],});@@ -96,7 +112,7 @@ class SandboxRunner {const timeoutId = setTimeout(() => {this.kill(sandboxId);- }, this.config.timeout);+ }, config.timeout);proc.on("close", (code) => {clearTimeout(timeoutId);@@ -133,7 +149,9 @@ class SandboxRunner {if (proc) {proc.kill("SIGTERM");this.runningContainers.delete(sandboxId);- spawn("docker", ["kill", `omniroute-sandbox-${sandboxId}`], { stdio: "ignore" });+ childProcess.spawn("docker", ["kill", `omniroute-sandbox-${sandboxId}`], {+ stdio: "ignore",+ });return true;}return false;@@ -142,7 +160,7 @@ class SandboxRunner {killAll(): void {for (const [id, proc] of this.runningContainers) {proc.kill("SIGTERM");- spawn("docker", ["kill", `omniroute-sandbox-${id}`], { stdio: "ignore" });+ childProcess.spawn("docker", ["kill", `omniroute-sandbox-${id}`], { stdio: "ignore" });}this.runningContainers.clear();}diff --git a/src/server-init.ts b/src/server-init.tsindex 4b00b7733c..d13679cda8 100644--- a/src/server-init.ts+++ b/src/server-init.ts@@ -13,6 +13,13 @@ import { registerDefaultGuardrails } from "./lib/guardrails";import { ensurePersistentManagementPasswordHash } from "./lib/auth/managementPassword";import { skillExecutor } from "./lib/skills/executor";import { registerBuiltinSkills } from "./lib/skills/builtins";+import { createLogger } from "./shared/utils/logger";++const startupLog = createLogger("server-init");++function getErrorMessage(error: unknown) {+ return error instanceof Error ? error.message : String(error);+}async function startServer() {// Trigger request-log layout migration during startup, before serving requests.@@ -28,9 +35,9 @@ async function startServer() {// Compliance: Initialize audit_log tabletry {initAuditLog();- console.log("[COMPLIANCE] Audit log table initialized");+ startupLog.info("Audit log table initialized");} catch (err) {- console.warn("[COMPLIANCE] Could not initialize audit log:", err.message);+ startupLog.warn({ err }, "Could not initialize audit log");}// Compliance: One-time cleanup of expired logs@@ -44,28 +51,27 @@ async function startServer() {cleanup.deletedAuditLogs ||cleanup.deletedMcpAuditLogs) {- console.log("[COMPLIANCE] Expired log cleanup:", cleanup);+ startupLog.info({ cleanup }, "Expired log cleanup completed");}} catch (err) {- console.warn("[COMPLIANCE] Log cleanup failed:", err.message);+ startupLog.warn({ err }, "Log cleanup failed");}- console.log("Starting server with cloud sync...");+ startupLog.info("Starting server with cloud sync");try {let settings = await getSettings();const passwordState = await ensurePersistentManagementPasswordHash({- logger: console,+ logger: { log: (message: string) => startupLog.info(message) },settings,source: "startup",});settings = passwordState.settings;const runtimeChanges = await applyRuntimeSettings(settings, { force: true, source: "startup" });if (runtimeChanges.length > 0) {- console.log(- `[STARTUP] Runtime settings hydrated: ${runtimeChanges- .map((entry) => entry.section)- .join(", ")}`+ startupLog.info(+ { sections: runtimeChanges.map((entry) => entry.section) },+ "Runtime settings hydrated");}@@ -73,13 +79,13 @@ async function startServer() {startSpendBatchWriter();registerDefaultGuardrails();registerBuiltinSkills(skillExecutor);- console.log("[STARTUP] Spend batch writer started");- console.log("[STARTUP] Guardrail registry initialized");- console.log("[STARTUP] Builtin skill handlers registered");+ startupLog.info("Spend batch writer started");+ startupLog.info("Guardrail registry initialized");+ startupLog.info("Builtin skill handlers registered");await initializeCloudSync();startBudgetResetJob();startRuntimeConfigHotReload();- console.log("Server started with cloud sync initialized");+ startupLog.info("Server started with cloud sync initialized");// Log server start event to audit loglogAuditEvent({@@ -91,7 +97,7 @@ async function startServer() {details: { timestamp: new Date().toISOString() },});} catch (error) {- console.error("[FATAL] Error initializing cloud sync:", error);+ startupLog.error({ err: error }, "Error initializing cloud sync");process.exit(1);}@@ -101,17 +107,14 @@ async function startServer() {const { initPricingSync } = await import("./lib/pricingSync");await initPricingSync();} catch (err) {- console.warn(- "[PRICING_SYNC] Could not initialize:",- err instanceof Error ? err.message : err- );+ startupLog.warn({ error: getErrorMessage(err) }, "Pricing sync could not initialize");}}}// Start the server initializationstartServer().catch((err) => {- console.error("[FATAL] Server initialization failed:", err);+ startupLog.error({ err }, "Server initialization failed");process.exit(1);});diff --git a/src/shared/constants/sidebarVisibility.ts b/src/shared/constants/sidebarVisibility.tsindex 1d071ef65b..a08967a904 100644--- a/src/shared/constants/sidebarVisibility.ts+++ b/src/shared/constants/sidebarVisibility.ts@@ -19,7 +19,6 @@ export const HIDEABLE_SIDEBAR_ITEM_IDS = ["search-tools","logs","health",- "audit","settings","docs","issues",diff --git a/src/sse/services/auth.ts.orig b/src/sse/services/auth.ts.origdeleted file mode 100644index 76e5ee1aa9..0000000000--- a/src/sse/services/auth.ts.orig+++ /dev/null@@ -1,989 +0,0 @@-import {- getProviderConnections,- validateApiKey,- updateProviderConnection,- getSettings,- getCachedSettings,-} from "@/lib/localDb";-import { getQuotaWindowStatus, isAccountQuotaExhausted } from "@/domain/quotaCache";-import {- isAccountUnavailable,- getUnavailableUntil,- getEarliestRateLimitedUntil,- formatRetryAfter,- checkFallbackError,- isModelLocked,- lockModel,- hasPerModelQuota,-} from "@omniroute/open-sse/services/accountFallback.ts";-import { isLocalProvider, getPassthroughProviders } from "@omniroute/open-sse/config/providerRegistry.ts";-import { COOLDOWN_MS } from "@omniroute/open-sse/config/constants.ts";-import { getCodexModelScope } from "@omniroute/open-sse/executors/codex.ts";-import * as log from "../utils/logger";-import { fisherYatesShuffle, getNextFromDeckSync } from "@/shared/utils/shuffleDeck";--type JsonRecord = Record<string, unknown>;--interface ProviderConnectionView {- id: string;- isActive: boolean;- rateLimitedUntil: string | null;- testStatus: string | null;- apiKey: string | null;- accessToken: string | null;- refreshToken: string | null;- tokenExpiresAt: string | null;- expiresAt: string | null;- projectId: string | null;- providerSpecificData: JsonRecord;- lastUsedAt: string | null;- consecutiveUseCount: number;- priority: number;- lastError: string | null;- lastErrorType: string | null;- lastErrorSource: string | null;- errorCode: string | number | null;- backoffLevel: number;-}--interface RecoverableConnectionState {- connectionId: string;- testStatus?: string | null;- lastError?: string | null;- rateLimitedUntil?: string | null;- errorCode?: string | number | null;- lastErrorType?: string | null;- lastErrorSource?: string | null;-}--interface CredentialSelectionOptions {- allowSuppressedConnections?: boolean;- bypassQuotaPolicy?: boolean;-}--const CODEX_QUOTA_THRESHOLD_PERCENT = 90;-const MIN_QUOTA_THRESHOLD_PERCENT = 1;-const MAX_QUOTA_THRESHOLD_PERCENT = 100;--function asRecord(value: unknown): JsonRecord {- return value && typeof value === "object" && !Array.isArray(value) ? (value as JsonRecord) : {};-}--function toStringOrNull(value: unknown): string | null {- return typeof value === "string" && value.trim().length > 0 ? value : null;-}--function toNumber(value: unknown, fallback = 0): number {- if (typeof value === "number" && Number.isFinite(value)) return value;- if (typeof value === "string" && value.trim().length > 0) {- const parsed = Number(value);- return Number.isFinite(parsed) ? parsed : fallback;- }- return fallback;-}--function toProviderConnection(value: unknown): ProviderConnectionView {- const row = asRecord(value);- return {- id: toStringOrNull(row.id) || "",- isActive: row.isActive === true,- rateLimitedUntil: toStringOrNull(row.rateLimitedUntil),- testStatus: toStringOrNull(row.testStatus),- apiKey: toStringOrNull(row.apiKey),- accessToken: toStringOrNull(row.accessToken),- refreshToken: toStringOrNull(row.refreshToken),- tokenExpiresAt: toStringOrNull(row.tokenExpiresAt),- expiresAt: toStringOrNull(row.expiresAt),- projectId: toStringOrNull(row.projectId),- providerSpecificData: asRecord(row.providerSpecificData),- lastUsedAt: toStringOrNull(row.lastUsedAt),- consecutiveUseCount: toNumber(row.consecutiveUseCount, 0),- priority: toNumber(row.priority, 999),- lastError: toStringOrNull(row.lastError),- lastErrorType: toStringOrNull(row.lastErrorType),- lastErrorSource: toStringOrNull(row.lastErrorSource),- errorCode:- typeof row.errorCode === "string" || typeof row.errorCode === "number" ? row.errorCode : null,- backoffLevel: toNumber(row.backoffLevel, 0),- };-}--function toBooleanOrDefault(value: unknown, fallback: boolean): boolean {- return typeof value === "boolean" ? value : fallback;-}--function getCodexLimitPolicy(providerSpecificData: JsonRecord): {- use5h: boolean;- useWeekly: boolean;-} {- const policy = asRecord(providerSpecificData.codexLimitPolicy);- return {- use5h: toBooleanOrDefault(policy.use5h, true),- useWeekly: toBooleanOrDefault(policy.useWeekly, true),- };-}--interface QuotaLimitPolicy {- enabled: boolean;- thresholdPercent: number;- windows: string[];-}--function normalizeQuotaThreshold(value: unknown, fallback = CODEX_QUOTA_THRESHOLD_PERCENT): number {- const parsed = toNumber(value, fallback);- return Math.min(MAX_QUOTA_THRESHOLD_PERCENT, Math.max(MIN_QUOTA_THRESHOLD_PERCENT, parsed));-}--function normalizeWindowName(windowName: unknown): string | null {- if (typeof windowName !== "string") return null;- const normalized = windowName.trim().toLowerCase();- return normalized.length > 0 ? normalized : null;-}--function uniqueWindows(windows: string[]): string[] {- return [...new Set(windows)];-}--function normalizeCodexWindowName(windowName: unknown): string | null {- if (typeof windowName !== "string") return null;- const normalized = windowName.trim().toLowerCase();- if (normalized === "session (5h)" || normalized === "5h" || normalized === "five_hour") {- return "session";- }- if (normalized === "weekly (7d)" || normalized === "7d" || normalized === "seven_day") {- return "weekly";- }- return normalized;-}--function applyCodexWindowPolicy(rawWindows: string[], providerSpecificData: JsonRecord): string[] {- const codexPolicy = getCodexLimitPolicy(providerSpecificData);- const normalizedRaw = rawWindows.map(normalizeCodexWindowName).filter(Boolean) as string[];-- // Preserve explicitly configured custom windows, but enforce canonical Codex windows- // from toggles so weekly exhaustion is never skipped when useWeekly=true.- let windows = [...normalizedRaw];- windows = windows.filter((windowName) => {- if (windowName === "session") return codexPolicy.use5h;- if (windowName === "weekly") return codexPolicy.useWeekly;- return true;- });- if (codexPolicy.use5h) windows.push("session");- if (codexPolicy.useWeekly) windows.push("weekly");-- return uniqueWindows(windows);-}--function getCodexScopeRateLimitedUntil(- providerSpecificData: JsonRecord,- model: string | null-): string | null {- if (!model) return null;- const scope = getCodexModelScope(model);- const scopeMap = asRecord(providerSpecificData.codexScopeRateLimitedUntil);- const value = scopeMap[scope];- return typeof value === "string" && value.trim().length > 0 ? value : null;-}--function isCodexScopeUnavailable(- connection: ProviderConnectionView,- model: string | null-): boolean {- const until = getCodexScopeRateLimitedUntil(connection.providerSpecificData, model);- if (!until) return false;- return new Date(until).getTime() > Date.now();-}--function getEarliestCodexScopeRateLimitedUntil(- connections: ProviderConnectionView[],- model: string | null-): string | null {- let earliest: string | null = null;- let earliestMs = Infinity;-- for (const conn of connections) {- const until = getCodexScopeRateLimitedUntil(conn.providerSpecificData, model);- if (!until) continue;- const ms = new Date(until).getTime();- if (!Number.isFinite(ms) || ms <= Date.now()) continue;- if (ms < earliestMs) {- earliest = until;- earliestMs = ms;- }- }-- return earliest;-}--function normalizeStatus(value: string | null): string {- return (value || "").trim().toLowerCase();-}--function isTerminalConnectionStatus(connection: ProviderConnectionView): boolean {- const status = normalizeStatus(connection.testStatus);- return status === "credits_exhausted" || status === "banned" || status === "expired";-}--export function resolveQuotaLimitPolicy(- provider: string,- providerSpecificData: JsonRecord-): QuotaLimitPolicy {- const rawPolicy = asRecord(providerSpecificData.limitPolicy);- const rawWindows = Array.isArray(rawPolicy.windows) ? rawPolicy.windows : [];- const windows = rawWindows.map(normalizeWindowName).filter(Boolean) as string[];-- if (provider === "codex") {- const defaultWindows = applyCodexWindowPolicy(windows, providerSpecificData);- const enabled = toBooleanOrDefault(rawPolicy.enabled, defaultWindows.length > 0);-- return {- enabled,- thresholdPercent: normalizeQuotaThreshold(rawPolicy.thresholdPercent),- windows: defaultWindows,- };- }-- return {- enabled: toBooleanOrDefault(rawPolicy.enabled, false),- thresholdPercent: normalizeQuotaThreshold(rawPolicy.thresholdPercent),- windows,- };-}--export function evaluateQuotaLimitPolicy(- provider: string,- connection: ProviderConnectionView-): { blocked: boolean; reasons: string[]; resetAt: string | null } {- const policy = resolveQuotaLimitPolicy(provider, connection.providerSpecificData);- if (!policy.enabled || policy.windows.length === 0) {- return { blocked: false, reasons: [], resetAt: null };- }-- const reasons: string[] = [];- const resetCandidates: Array<string | null> = [];-- for (const windowName of policy.windows) {- const status = getQuotaWindowStatus(connection.id, windowName, policy.thresholdPercent);- if (!status?.reachedThreshold) continue;- reasons.push(`${windowName} usage ${Math.round(status.usedPercentage)}%`);- resetCandidates.push(status.resetAt);- }-- return {- blocked: reasons.length > 0,- reasons,- resetAt: getEarliestFutureDate(resetCandidates),- };-}--function parseFutureDateMs(value: string | null): number | null {- if (!value) return null;- const ms = new Date(value).getTime();- if (!Number.isFinite(ms) || ms <= Date.now()) return null;- return ms;-}--function getEarliestFutureDate(candidates: Array<string | null>): string | null {- return (- candidates- .map((candidate) => ({- raw: candidate,- ms: parseFutureDateMs(candidate),- }))- .filter((entry) => entry.ms !== null)- .sort((a, b) => (a.ms as number) - (b.ms as number))[0]?.raw || null- );-}--// Mutex to prevent race conditions during account selection-let selectionMutex = Promise.resolve();--// ─── Anti-Thundering Herd: per-connection mutex for markAccountUnavailable ───-// Prevents multiple concurrent requests from marking the same connection-// unavailable in parallel, which was the root cause of cascading 502 lockouts.-const markMutexes = new Map<string, Promise<void>>();--// Strict-Random shuffle deck moved to src/shared/utils/shuffleDeck.ts-// auth.ts uses getNextFromDeckSync (already inside selectionMutex).-// Re-export for backwards compat with existing test imports.-export { fisherYatesShuffle, getNextFromDeckSync as getNextFromDeck };--/**- * Get provider credentials from localDb- * Filters out unavailable accounts and returns the selected account based on strategy- * @param {string} provider - Provider name- * @param {string|null} excludeConnectionId - Connection ID to exclude (for retry with next account)- */-export async function getProviderCredentials(- provider: string,- excludeConnectionId: string | null = null,- allowedConnections: string[] | null = null,- requestedModel: string | null = null,- options: CredentialSelectionOptions = {}-) {- // Acquire mutex to prevent race conditions- const currentMutex = selectionMutex;- let resolveMutex: (() => void) | undefined;- selectionMutex = new Promise((resolve) => {- resolveMutex = resolve;- });-- try {- await currentMutex;-- const allowSuppressedConnections = options.allowSuppressedConnections === true;- const bypassQuotaPolicy = options.bypassQuotaPolicy === true;-- const connectionsRaw = await getProviderConnections({ provider, isActive: true });- let connections = (Array.isArray(connectionsRaw) ? connectionsRaw : [])- .map(toProviderConnection)- .filter((conn) => conn.id.length > 0);- // allowedConnections: restrict to specific connection IDs (from API key policy, #363)- if (allowedConnections && allowedConnections.length > 0) {- connections = connections.filter((conn) => allowedConnections.includes(conn.id));- }- log.debug(- "AUTH",- `${provider} | total connections: ${connections.length}, excludeId: ${excludeConnectionId || "none"}`- );-- if (connections.length === 0) {- // Check all connections (including inactive) to see if rate limited- const allConnectionsRaw = await getProviderConnections({ provider });- const allConnections = (Array.isArray(allConnectionsRaw) ? allConnectionsRaw : [])- .map(toProviderConnection)- .filter((conn) => conn.id.length > 0);- log.debug("AUTH", `${provider} | all connections (incl inactive): ${allConnections.length}`);- if (allConnections.length > 0) {- const earliest = getEarliestRateLimitedUntil(allConnections);- if (earliest) {- log.warn(- "AUTH",- `${provider} | all ${allConnections.length} accounts rate limited (${formatRetryAfter(earliest)})`- );- return {- allRateLimited: true,- retryAfter: earliest,- retryAfterHuman: formatRetryAfter(earliest),- };- }- log.warn("AUTH", `${provider} | ${allConnections.length} accounts found but none active`);- allConnections.forEach((c) => {- log.debug(- "AUTH",- ` → ${c.id?.slice(0, 8)} | isActive=${c.isActive} | rateLimitedUntil=${c.rateLimitedUntil || "none"} | testStatus=${c.testStatus}`- );- });- }- log.warn("AUTH", `No credentials for ${provider}`);- return null;- }-- // Auto-decay backoffLevel for accounts whose rateLimitedUntil has passed.- // Without this, high backoffLevel permanently deprioritizes accounts even- // after the rate limit window expires, creating a deadlock where the account- // needs a successful request to reset but never gets selected.- for (const c of connections) {- if (- c.backoffLevel > 0 &&- !isTerminalConnectionStatus(c) &&- !isAccountUnavailable(c.rateLimitedUntil)- ) {- c.backoffLevel = 0;- updateProviderConnection(c.id, {- backoffLevel: 0,- testStatus: "active",- lastError: null,- lastErrorAt: null,- lastErrorType: null,- lastErrorSource: null,- errorCode: null,- }).catch(() => {});- }- }-- // Filter out unavailable accounts and excluded connection- const availableConnections = connections.filter((c) => {- if (excludeConnectionId && c.id === excludeConnectionId) return false;- if (!allowSuppressedConnections) {- if (isAccountUnavailable(c.rateLimitedUntil)) return false;- if (isTerminalConnectionStatus(c)) return false;- if (provider === "codex" && isCodexScopeUnavailable(c, requestedModel)) return false;- // Per-model lockout: if this specific model is locked on this connection, skip it- if (requestedModel && isModelLocked(provider, c.id, requestedModel)) return false;- }- return true;- });-- log.debug(- "AUTH",- `${provider} | available: ${availableConnections.length}/${connections.length}`- );- connections.forEach((c) => {- const excluded = excludeConnectionId && c.id === excludeConnectionId;- const rateLimited = isAccountUnavailable(c.rateLimitedUntil);- const terminalStatus = isTerminalConnectionStatus(c);- const codexScopeLimited = provider === "codex" && isCodexScopeUnavailable(c, requestedModel);- if (excluded || rateLimited) {- log.debug(- "AUTH",- ` → ${c.id?.slice(0, 8)} | ${excluded ? "excluded" : ""} ${rateLimited ? `rateLimited until ${c.rateLimitedUntil}` : ""}${allowSuppressedConnections && rateLimited ? " (retained for combo live test)" : ""}`- );- } else if (terminalStatus) {- log.debug(- "AUTH",- allowSuppressedConnections- ? ` → ${c.id?.slice(0, 8)} | retained terminal status=${c.testStatus} for combo live test`- : ` → ${c.id?.slice(0, 8)} | skipped terminal status=${c.testStatus}`- );- } else if (codexScopeLimited) {- const scopeUntil = getCodexScopeRateLimitedUntil(c.providerSpecificData, requestedModel);- log.debug(- "AUTH",- allowSuppressedConnections- ? ` → ${c.id?.slice(0, 8)} | retained codex scope-limited account until ${scopeUntil} for combo live test`- : ` → ${c.id?.slice(0, 8)} | codex scope-limited until ${scopeUntil}`- );- }- });-- if (availableConnections.length === 0) {- const earliest =- getEarliestRateLimitedUntil(connections) ||- (provider === "codex"- ? getEarliestCodexScopeRateLimitedUntil(connections, requestedModel)- : null);- if (earliest) {- // Find the connection with the earliest rateLimitedUntil to get its error info- const rateLimitedConns = connections.filter(- (c) => c.rateLimitedUntil && new Date(c.rateLimitedUntil).getTime() > Date.now()- );- const earliestConn = rateLimitedConns.sort(- (a, b) =>- new Date(a.rateLimitedUntil || 0).getTime() -- new Date(b.rateLimitedUntil || 0).getTime()- )[0];- log.warn(- "AUTH",- `${provider} | all ${connections.length} active accounts rate limited (${formatRetryAfter(earliest)}) | lastErrorCode=${earliestConn?.errorCode}, lastError=${earliestConn?.lastError?.slice(0, 50)}`- );- return {- allRateLimited: true,- retryAfter: earliest,- retryAfterHuman: formatRetryAfter(earliest),- lastError: earliestConn?.lastError || null,- lastErrorCode: earliestConn?.errorCode || null,- };- }- log.warn("AUTH", `${provider} | all ${connections.length} accounts unavailable`);- return null;- }-- let policyEligibleConnections = availableConnections;- const blockedByPolicy: Array<{- id: string;- reasons: string[];- resetAt: string | null;- }> = [];-- if (!bypassQuotaPolicy) {- policyEligibleConnections = availableConnections.filter((connection) => {- const evaluation = evaluateQuotaLimitPolicy(provider, connection);- if (!evaluation.blocked) return true;-- blockedByPolicy.push({- id: connection.id,- reasons: evaluation.reasons,- resetAt: evaluation.resetAt,- });- return false;- });- } else if (availableConnections.length > 0) {- log.debug("AUTH", `${provider} | bypassing quota policy for combo live test`);- }-- if (blockedByPolicy.length > 0) {- log.info(- "AUTH",- `${provider} | quota policy filtered ${blockedByPolicy.length} account(s): ${blockedByPolicy- .map((entry) => `${entry.id.slice(0, 8)}(${entry.reasons.join(", ")})`)- .join("; ")}`- );- }-- if (policyEligibleConnections.length === 0 && availableConnections.length > 0) {- const earliestResetAt = getEarliestFutureDate(blockedByPolicy.map((entry) => entry.resetAt));- const earliestResetMs = parseFutureDateMs(earliestResetAt);-- const retryAfter = earliestResetMs- ? new Date(earliestResetMs).toISOString()- : new Date(Date.now() + 5 * 60 * 1000).toISOString();-- return {- allRateLimited: true,- retryAfter,- retryAfterHuman: formatRetryAfter(retryAfter),- lastError: `All ${provider} accounts reached configured quota threshold`,- lastErrorCode: 429,- };- }-- // Quota-aware: prioritize accounts with available quota- const withQuota = policyEligibleConnections.filter((c) => !isAccountQuotaExhausted(c.id));- const exhaustedQuota = policyEligibleConnections.filter((c) => isAccountQuotaExhausted(c.id));- const orderedConnections =- withQuota.length > 0 ? [...withQuota, ...exhaustedQuota] : policyEligibleConnections;-- if (exhaustedQuota.length > 0) {- log.debug(- "AUTH",- `${provider} | quota-aware: ${withQuota.length} with quota, ${exhaustedQuota.length} exhausted`- );- }-- const settings = await getSettings();- const strategy = settings.fallbackStrategy || "fill-first";-- let connection;- if (strategy === "round-robin") {- const stickyLimit = toNumber((settings as Record<string, unknown>).stickyRoundRobinLimit, 3);-- // If excluding an account (fallback scenario), skip sticky logic and go straight to LRU- // This prevents the system from getting stuck on a failed account- const isFallbackScenario = excludeConnectionId !== null;-- if (!isFallbackScenario) {- // Sort by lastUsed (most recent first) to find current candidate- const byRecency = [...orderedConnections].sort((a: any, b: any) => {- if (!a.lastUsedAt && !b.lastUsedAt) return (a.priority || 999) - (b.priority || 999);- if (!a.lastUsedAt) return 1;- if (!b.lastUsedAt) return -1;- return new Date(b.lastUsedAt).getTime() - new Date(a.lastUsedAt).getTime();- });-- const current = byRecency[0];- const currentCount = current?.consecutiveUseCount || 0;-- if (current && current.lastUsedAt && currentCount < stickyLimit) {- // Stay with current account- connection = current;- log.debug(- "AUTH",- `${provider} round-robin: staying with ${current.id?.slice(0, 8)}... (count=${currentCount}/${stickyLimit})`- );- // Update lastUsedAt and increment count (await to ensure persistence)- await updateProviderConnection(connection.id, {- lastUsedAt: new Date().toISOString(),- consecutiveUseCount: (connection.consecutiveUseCount || 0) + 1,- });- } else {- // Pick the least recently used (excluding current if possible)- // Also penalize accounts with high backoffLevel (previously rate-limited)- // so they don't get immediately re-selected after cooldown (#340)- const sortedByOldest = [...orderedConnections].sort((a: any, b: any) => {- // Penalize previously rate-limited accounts (backoffLevel > 0)- const aBackoff = a.backoffLevel || 0;- const bBackoff = b.backoffLevel || 0;- if (aBackoff !== bBackoff) return aBackoff - bBackoff; // lower backoff first- if (!a.lastUsedAt && !b.lastUsedAt) return (a.priority || 999) - (b.priority || 999);- if (!a.lastUsedAt) return -1;- if (!b.lastUsedAt) return 1;- return new Date(a.lastUsedAt).getTime() - new Date(b.lastUsedAt).getTime();- });-- connection = sortedByOldest[0];- log.debug(- "AUTH",- `${provider} round-robin: switching to LRU ${connection.id?.slice(0, 8)}... (current count=${currentCount} >= limit=${stickyLimit} or no lastUsedAt)`- );-- // Update lastUsedAt and reset count to 1 (await to ensure persistence)- await updateProviderConnection(connection.id, {- lastUsedAt: new Date().toISOString(),- consecutiveUseCount: 1,- });- }- } else {- // Fallback scenario: excluded an account due to failure- // Always pick the least recently used to ensure proper cycling- // Also penalize accounts with high backoffLevel (#340)- const sortedByOldest = [...orderedConnections].sort((a: any, b: any) => {- const aBackoff = a.backoffLevel || 0;- const bBackoff = b.backoffLevel || 0;- if (aBackoff !== bBackoff) return aBackoff - bBackoff;- if (!a.lastUsedAt && !b.lastUsedAt) return (a.priority || 999) - (b.priority || 999);- if (!a.lastUsedAt) return -1;- if (!b.lastUsedAt) return 1;- return new Date(a.lastUsedAt).getTime() - new Date(b.lastUsedAt).getTime();- });-- connection = sortedByOldest[0];- log.info(- "AUTH",- `${provider} round-robin: FALLBACK MODE - excluded ${excludeConnectionId?.slice(0, 8)}..., picked LRU ${connection.id?.slice(0, 8)}...`- );-- // Update lastUsedAt and reset count to 1 (await to ensure persistence)- await updateProviderConnection(connection.id, {- lastUsedAt: new Date().toISOString(),- consecutiveUseCount: 1,- });- }- } else if (strategy === "p2c") {- // Power of Two Choices: pick 2 random, choose the one with fewer failures- if (orderedConnections.length <= 2) {- connection = orderedConnections[0];- } else {- const i = Math.floor(Math.random() * orderedConnections.length);- let j = Math.floor(Math.random() * (orderedConnections.length - 1));- if (j >= i) j++;- const a = orderedConnections[i];- const b = orderedConnections[j];- // Prefer the one with fewer consecutive uses / better health- const scoreA = (a.consecutiveUseCount || 0) + (a.lastError ? 10 : 0);- const scoreB = (b.consecutiveUseCount || 0) + (b.lastError ? 10 : 0);- connection = scoreA <= scoreB ? a : b;- }- } else if (strategy === "random") {- // Random: Fisher-Yates-inspired random pick- const idx = Math.floor(Math.random() * orderedConnections.length);- connection = orderedConnections[idx];- } else if (strategy === "least-used") {- // Least Used: pick the one with oldest lastUsedAt- const sorted = [...orderedConnections].sort((a, b) => {- if (!a.lastUsedAt && !b.lastUsedAt) return (a.priority || 999) - (b.priority || 999);- if (!a.lastUsedAt) return -1;- if (!b.lastUsedAt) return 1;- return new Date(a.lastUsedAt).getTime() - new Date(b.lastUsedAt).getTime();- });- connection = sorted[0];- } else if (strategy === "cost-optimized") {- // Cost Optimized: sort by priority ascending (lower = cheaper/preferred)- // Future: can be enhanced with actual cost data per provider- const sorted = [...orderedConnections].sort(- (a, b) => (a.priority || 999) - (b.priority || 999)- );- connection = sorted[0];- } else if (strategy === "strict-random") {- // Strict Random: shuffle deck — uses each account once before reshuffling- const ids = orderedConnections.map((c) => c.id);- const selectedId = getNextFromDeckSync(`conn:${provider}`, ids);- connection = orderedConnections.find((c) => c.id === selectedId) || orderedConnections[0];- } else {- // Default: fill-first (already sorted by priority in getProviderConnections)- connection = orderedConnections[0];- }-- return {- apiKey: connection.apiKey,- accessToken: connection.accessToken,- refreshToken: connection.refreshToken,- expiresAt: connection.tokenExpiresAt || connection.expiresAt || null,- projectId: connection.projectId,- copilotToken:- typeof connection.providerSpecificData.copilotToken === "string"- ? connection.providerSpecificData.copilotToken- : null,- providerSpecificData: connection.providerSpecificData,- connectionId: connection.id,- // Include current status for optimization check- testStatus: connection.testStatus,- lastError: connection.lastError,- lastErrorType: connection.lastErrorType,- lastErrorSource: connection.lastErrorSource,- errorCode: connection.errorCode,- rateLimitedUntil: connection.rateLimitedUntil,- };- } finally {- if (resolveMutex) resolveMutex();- }-}--/**- * Mark account as unavailable — reads backoffLevel from DB, calculates cooldown with exponential backoff, saves new level- * @param {string} connectionId- * @param {number} status - HTTP status code- * @param {string} errorText - Error message- * @param {string|null} provider- * @param {string|null} model - Model name for per-model lockout- * @returns {{ shouldFallback: boolean, cooldownMs: number }}- */-export async function markAccountUnavailable(- connectionId: string,- status: number,- errorText: string,- provider: string | null = null,- model: string | null = null-) {- const currentMutex = markMutexes.get(connectionId) || Promise.resolve();- let resolveMutex: (() => void) | undefined;- markMutexes.set(- connectionId,- new Promise((resolve) => {- resolveMutex = resolve;- })- );-- try {- await currentMutex;-- // ── Per-model lockout for providers with independent model quotas ──- // Providers like Gemini AI Studio have per-model quotas. A 429/404 on one- // model must NOT lock out other models on the same API key.- if (hasPerModelQuota(provider) && model && (status === 429 || status === 404)) {- const reason = status === 404 ? "not_found" : "rate_limited";- const cooldown = status === 404- ? COOLDOWN_MS.notFoundLocal- : COOLDOWN_MS.rateLimit;- lockModel(provider, connectionId, model, reason, cooldown);- // Update last error for observability (without changing terminal status)- updateProviderConnection(connectionId, {- lastErrorType: reason,- lastError: `Model ${model} ${reason}`,- lastErrorAt: new Date().toISOString(),- errorCode: status,- }).catch(() => {});- log.info(- "AUTH",- `Model-only lockout for ${provider}:${model} — ${status} ${reason} ${Math.ceil(cooldown / 1000)}s (connection stays active)`- );- return { shouldFallback: true, cooldownMs: cooldown };- }-- // Read current connection to get backoffLevel- const connectionsRaw = await getProviderConnections({ provider });- const connections = (Array.isArray(connectionsRaw) ? connectionsRaw : [])- .map(toProviderConnection)- .filter((connection) => connection.id.length > 0);- const conn = connections.find((connection) => connection.id === connectionId);- const backoffLevel = conn?.backoffLevel || 0;-- // T06/T10/T36: terminal statuses should not be overwritten by transient cooldown state.- if (conn && isTerminalConnectionStatus(conn)) {- log.info(- "AUTH",- `${connectionId.slice(0, 8)} terminal status=${conn.testStatus}, skipping cooldown overwrite`- );- return { shouldFallback: true, cooldownMs: 0 };- }-- // ─── Anti-Thundering Herd Guard ─────────────────────────────────- // If this connection was ALREADY marked unavailable by a prior concurrent- // request (within the mutex window), skip re-marking to avoid resetting- // the cooldown timer or double-incrementing the backoff level.- if (conn?.rateLimitedUntil && new Date(conn.rateLimitedUntil).getTime() > Date.now()) {- log.info(- "AUTH",- `${connectionId.slice(0, 8)} already marked unavailable (until ${conn.rateLimitedUntil}), skipping duplicate mark`- );- return {- shouldFallback: true,- cooldownMs: new Date(conn.rateLimitedUntil).getTime() - Date.now(),- };- }-- // T09: Codex scope-aware lockout guard (codex vs spark independent pools).- if (provider === "codex" && model) {- const scopeRateLimitedUntil = getCodexScopeRateLimitedUntil(- conn?.providerSpecificData || {},- model- );- if (scopeRateLimitedUntil && new Date(scopeRateLimitedUntil).getTime() > Date.now()) {- log.info(- "AUTH",- `${connectionId.slice(0, 8)} already scope-limited for ${getCodexModelScope(model)} (until ${scopeRateLimitedUntil}), skipping duplicate mark`- );- return {- shouldFallback: true,- cooldownMs: new Date(scopeRateLimitedUntil).getTime() - Date.now(),- };- }- }-- const result = checkFallbackError(- status,- errorText,- backoffLevel,- model,- provider // ← Now passes provider for profile-aware cooldowns- );- const { shouldFallback, cooldownMs, newBackoffLevel, reason } = result;- if (!shouldFallback) return { shouldFallback: false, cooldownMs: 0 };-- // ── 404 model-only lockout: connection stays active ──- // For local providers (detected by URL) and cloud providers with passthrough models- // (like Antigravity), a 404 means the specific model doesn't exist or isn't available- // for this account — it should NOT lock out the entire connection.- const connBaseUrl = (conn?.providerSpecificData as Record<string, unknown>)?.baseUrl as- | string- | undefined;-- const isPassthroughProvider = provider && getPassthroughProviders().has(provider);- const isPerModelQuotaProvider = hasPerModelQuota(provider);- if ((isLocalProvider(connBaseUrl) || isPerModelQuotaProvider) && status === 404 && provider && model) {- const localCooldown = COOLDOWN_MS.notFoundLocal;- lockModel(provider, connectionId, model, "not_found", localCooldown);- log.info(- "AUTH",- `Model-only lockout for ${model} — 404 lockout ${localCooldown / 1000}s (connection stays active)`- );- return { shouldFallback: true, cooldownMs: localCooldown };- }-- // ── 429 model-only lockout for per-model quota providers ──- // For providers where each model has independent quota (passthrough providers,- // Gemini AI Studio), a 429 on one model should NOT lock out the entire connection- // — other models may still have quota available. Use lockModel() instead of- // connection-wide rateLimitedUntil.- if (isPerModelQuotaProvider && status === 429 && provider && model) {- const modelCooldown = cooldownMs || COOLDOWN_MS.rateLimit;- lockModel(provider, connectionId, model, reason || "rate_limited", modelCooldown);- log.info(- "AUTH",- `Model-only lockout for ${model} — 429 rate limit ${Math.ceil(modelCooldown / 1000)}s (connection stays active)`- );- return { shouldFallback: true, cooldownMs: modelCooldown };- }-- const rateLimitedUntil = getUnavailableUntil(cooldownMs);- const errorMsg = typeof errorText === "string" ? errorText.slice(0, 100) : "Provider error";-- // T09: Codex per-scope lockout (do not block the whole account globally).- if (provider === "codex" && status === 429 && model && conn) {- const scope = getCodexModelScope(model);- const existingScopeMap = asRecord(conn.providerSpecificData.codexScopeRateLimitedUntil);- const persistedScopeUntil = getCodexScopeRateLimitedUntil(conn.providerSpecificData, model);- const scopeRateLimitedUntil = persistedScopeUntil || rateLimitedUntil;- const scopeCooldownMs = Math.max(new Date(scopeRateLimitedUntil).getTime() - Date.now(), 0);-- await updateProviderConnection(connectionId, {- testStatus: "unavailable",- lastError: errorMsg,- errorCode: status,- lastErrorAt: new Date().toISOString(),- backoffLevel: newBackoffLevel ?? backoffLevel,- providerSpecificData: {- ...conn.providerSpecificData,- codexScopeRateLimitedUntil: {- ...existingScopeMap,- [scope]: scopeRateLimitedUntil,- },- },- });-- if (scopeCooldownMs > 0) {- lockModel(provider, connectionId, model, reason || "unknown", scopeCooldownMs);- }-- if (status && errorMsg) {- console.error(`❌ ${provider} [${status}] (${scope}): ${errorMsg}`);- }-- return { shouldFallback: true, cooldownMs: scopeCooldownMs };- }-- await updateProviderConnection(connectionId, {- rateLimitedUntil,- testStatus: "unavailable",- lastError: errorMsg,- errorCode: status,- lastErrorAt: new Date().toISOString(),- backoffLevel: newBackoffLevel ?? backoffLevel,- });-- // T-AUTODISABLE: If auto-disable setting is enabled and error is permanent/terminal,- // mark account as inactive so it is never retried again.- // Uses getCachedSettings() to avoid DB overhead on hot error path.- // NOTE: For permanent bans we disable immediately — no threshold needed,- // because a permanent ban (403 "Verify your account" / ToS violation) will- // NEVER recover, so retrying is pointless regardless of attempt count.- if (result.permanent) {- try {- const settings = await getCachedSettings();- const autoDisableEnabled = settings.autoDisableBannedAccounts ?? false;- if (autoDisableEnabled) {- await updateProviderConnection(connectionId, { isActive: false });- log.info(- "AUTH",- `Auto-disabled ${connectionId.slice(0, 8)} — permanent ban detected (autoDisableBannedAccounts=true)`- );- }- } catch (e) {- log.info("AUTH", `Auto-disable check failed (non-fatal): ${e}`);- }- }-- // Per-model lockout: lock the specific model if known- if (provider && model && cooldownMs > 0) {- lockModel(provider, connectionId, model, reason || "unknown", cooldownMs);- }-- if (provider && status && errorMsg) {- console.error(`❌ ${provider} [${status}]: ${errorMsg}`);- }-- return { shouldFallback: true, cooldownMs };- } finally {- if (resolveMutex) resolveMutex();- // Cleanup stale mutex entries (avoid memory leak)- markMutexes.delete(connectionId);- }-}--/**- * Clear account error status (only if currently has error)- * Optimized to avoid unnecessary DB updates- */-export async function clearAccountError(- connectionId: string,- currentConnection: Partial<RecoverableConnectionState>-) {- // Only update if currently has error status- const hasError =- (currentConnection.testStatus && currentConnection.testStatus !== "active") ||- currentConnection.lastError ||- currentConnection.rateLimitedUntil ||- currentConnection.errorCode ||- currentConnection.lastErrorType ||- currentConnection.lastErrorSource;-- if (!hasError) return; // Skip if already clean-- await updateProviderConnection(connectionId, {- testStatus: "active",- lastError: null,- lastErrorAt: null,- lastErrorType: null,- lastErrorSource: null,- errorCode: null,- rateLimitedUntil: null,- backoffLevel: 0,- });- log.info("AUTH", `Account ${connectionId.slice(0, 8)} error cleared`);-}--export async function clearRecoveredProviderState(- credentials: Partial<RecoverableConnectionState> | null-) {- if (!credentials?.connectionId) return;- await clearAccountError(credentials.connectionId, credentials);-}--/**- * Extract API key from request headers- */-export function extractApiKey(request: Request) {- const authHeader = request.headers.get("Authorization");- if (authHeader?.startsWith("Bearer ")) {- return authHeader.slice(7);- }- return null;-}--/**- * Validate API key (optional - for local use can skip)- */-export async function isValidApiKey(apiKey: string) {- if (!apiKey) return false;- return await validateApiKey(apiKey);-}diff --git a/src/sse/utils/logger.ts b/src/sse/utils/logger.tsindex c3caf39cfc..4674953ca6 100644--- a/src/sse/utils/logger.ts+++ b/src/sse/utils/logger.ts@@ -2,7 +2,7 @@* SSE Logger — Thin wrapper around the shared Pino logger* for backward compatibility with existing SSE code.*- * Migrated from console.log to structured Pino logging.+ * Migrated from direct console logging to structured Pino logging.*/import { createLogger, logger as rootLogger } from "@/shared/utils/logger";diff --git a/tests/integration/integration-wiring.test.ts b/tests/integration/integration-wiring.test.tsindex 4ecd2da607..a539642a5f 100644--- a/tests/integration/integration-wiring.test.ts+++ b/tests/integration/integration-wiring.test.ts@@ -7,7 +7,7 @@import { describe, it } from "node:test";import assert from "node:assert/strict";-import { readFileSync, existsSync } from "node:fs";+import { readFileSync, existsSync, readdirSync } from "node:fs";import { join, dirname } from "node:path";import { fileURLToPath } from "node:url";@@ -34,6 +34,17 @@ function assertRouteMethods(relPath, methods) {}}+function listProjectFiles(relPath) {+ const full = join(ROOT, relPath);+ if (!existsSync(full)) return [];++ return readdirSync(full, { withFileTypes: true }).flatMap((entry) => {+ const childRelPath = `${relPath}/${entry.name}`;+ if (entry.isDirectory()) return listProjectFiles(childRelPath);+ return childRelPath;+ });+}+// ─── Pipeline Wiring ─────────────────────────────────describe("Pipeline Wiring — server-init.ts", () => {@@ -59,6 +70,11 @@ describe("Pipeline Wiring — server-init.ts", () => {it("should log server.start audit event", () => {assert.match(src, /server\.start/);});++ it("should use the structured startup logger instead of direct console calls", () => {+ assert.match(src, /createLogger\("server-init"\)/);+ assert.doesNotMatch(src, /console\.(log|warn|error|info|debug)\(/);+ });});describe("Pipeline Wiring — instrumentation-node.ts", () => {@@ -101,6 +117,14 @@ describe("Pipeline Wiring — sse chat handler", () => {assert.match(coreSrc, /calculateCost/);assert.match(coreSrc, /recordCost/);});++ it("should not track backup artifacts in the active src/sse shim", () => {+ const trackedArtifactNames = listProjectFiles("src/sse").filter((file) =>+ /\.(orig|bak|backup)$/i.test(file)+ );++ assert.deepEqual(trackedArtifactNames, []);+ });});describe("Pipeline Wiring — middleware proxy", () => {@@ -184,6 +208,86 @@ describe("API Routes — export HTTP methods", () => {});});+describe("API Routes — dashboard and tool consumers", () => {+ it("keeps model-combo mapping APIs wired through routing settings", () => {+ const settingsPage = readProjectFile("src/app/(dashboard)/dashboard/settings/page.tsx");+ const modelRoutingSection = readProjectFile("src/shared/components/ModelRoutingSection.tsx");++ assert.ok(settingsPage, "settings page should exist");+ assert.ok(modelRoutingSection, "ModelRoutingSection should exist");+ assert.match(settingsPage, /ModelRoutingSection/);+ assert.match(modelRoutingSection, /fetch\("\/api\/model-combo-mappings"\)/);+ assert.match(modelRoutingSection, /fetch\(`\/api\/model-combo-mappings\/\$\{editingId\}`/);+ assert.match(modelRoutingSection, /method:\s*"DELETE"/);+ assertRouteMethods("src/app/api/model-combo-mappings/route.ts", ["GET", "POST"]);+ assertRouteMethods("src/app/api/model-combo-mappings/[id]/route.ts", ["GET", "PUT", "DELETE"]);+ });++ it("keeps log APIs wired through the consolidated logs dashboard", () => {+ const logsPage = readProjectFile("src/app/(dashboard)/dashboard/logs/page.tsx");+ const requestLogger = readProjectFile("src/shared/components/RequestLoggerV2.tsx");+ const proxyLogger = readProjectFile("src/shared/components/ProxyLogger.tsx");+ const consoleLogger = readProjectFile("src/shared/components/ConsoleLogViewer.tsx");+ const activeRequests = readProjectFile("src/shared/components/ActiveRequestsPanel.tsx");++ assert.ok(logsPage, "logs page should exist");+ assert.ok(requestLogger, "RequestLoggerV2 should exist");+ assert.ok(proxyLogger, "ProxyLogger should exist");+ assert.ok(consoleLogger, "ConsoleLogViewer should exist");+ assert.ok(activeRequests, "ActiveRequestsPanel should exist");+ assert.match(logsPage, /RequestLoggerV2/);+ assert.match(logsPage, /ProxyLogger/);+ assert.match(logsPage, /ConsoleLogViewer/);+ assert.match(logsPage, /ActiveRequestsPanel/);+ assert.match(logsPage, /AuditLogTab/);+ assert.match(logsPage, /\/api\/logs\/export/);+ assert.match(requestLogger, /\/api\/usage\/call-logs/);+ assert.match(requestLogger, /\/api\/logs\/detail/);+ assert.match(proxyLogger, /\/api\/usage\/proxy-logs/);+ assert.match(consoleLogger, /\/api\/logs\/console/);+ assert.match(activeRequests, /\/api\/logs\/active/);+ assertRouteMethods("src/app/api/logs/active/route.ts", ["GET"]);+ assertRouteMethods("src/app/api/logs/console/route.ts", ["GET"]);+ assertRouteMethods("src/app/api/logs/detail/route.ts", ["GET", "POST"]);+ assertRouteMethods("src/app/api/logs/export/route.ts", ["GET"]);+ assertRouteMethods("src/app/api/usage/proxy-logs/route.ts", ["GET", "DELETE"]);+ assertRouteMethods("src/app/api/usage/call-logs/route.ts", ["GET"]);+ assertRouteMethods("src/app/api/usage/call-logs/[id]/route.ts", ["GET"]);+ });++ it("keeps usage quota wired through A2A and MCP tools", () => {+ const quotaSkill = readProjectFile("src/lib/a2a/skills/quotaManagement.ts");+ const mcpAdvancedTools = readProjectFile("open-sse/mcp-server/tools/advancedTools.ts");+ const mcpServer = readProjectFile("open-sse/mcp-server/server.ts");++ assert.ok(quotaSkill, "quotaManagement skill should exist");+ assert.ok(mcpAdvancedTools, "advanced MCP tools should exist");+ assert.ok(mcpServer, "MCP server should exist");+ assert.match(quotaSkill, /\/api\/usage\/quota/);+ assert.match(mcpAdvancedTools, /\/api\/usage\/quota/);+ assert.match(mcpServer, /\/api\/usage\/quota/);+ assertRouteMethods("src/app/api/usage/quota/route.ts", ["GET"]);+ });++ it("keeps legacy usage history and raw request-log APIs explicitly classified", () => {+ const usageStats = readProjectFile("src/shared/components/UsageStats.tsx");+ const apiReference = readProjectFile("docs/API_REFERENCE.md");+ const openApi = readProjectFile("docs/openapi.yaml");++ assert.ok(usageStats, "UsageStats compatibility component should exist");+ assert.ok(apiReference, "API reference should exist");+ assert.ok(openApi, "OpenAPI document should exist");+ assert.match(usageStats, /\/api\/usage\/history/);+ assert.match(apiReference, /\/api\/usage\/history/);+ assert.match(apiReference, /\/api\/usage\/request-logs/);+ assert.match(openApi, /\/api\/usage\/history:/);+ assert.match(openApi, /\/api\/usage\/request-logs:/);+ assertRouteMethods("src/app/api/usage/history/route.ts", ["GET"]);+ assertRouteMethods("src/app/api/usage/request-logs/route.ts", ["GET"]);+ assertRouteMethods("src/app/api/usage/logs/route.ts", ["GET"]);+ });+});+describe("API Routes — T09 /v1 catalog consistency", () => {const v1RouteSrc = readProjectFile("src/app/api/v1/route.ts");const v1ModelsRouteSrc = readProjectFile("src/app/api/v1/models/route.ts");@@ -313,11 +417,19 @@ describe("Page Integration — logs page wiring", () => {describe("Page Integration — settings page wiring", () => {const src = readProjectFile("src/app/(dashboard)/dashboard/settings/page.tsx");+ const memorySkillsTab = readProjectFile(+ "src/app/(dashboard)/dashboard/settings/components/MemorySkillsTab.tsx"+ );it("should include resilience tab in advanced settings", () => {assert.ok(src, "src/app/(dashboard)/dashboard/settings/page.tsx should exist");assert.match(src, /ResilienceTab/);});++ it("should not label the active skills settings card as a placeholder", () => {+ assert.ok(memorySkillsTab, "MemorySkillsTab should exist");+ assert.doesNotMatch(memorySkillsTab, /Skills Settings \(placeholder\)/);+ });});describe("Page Integration — cache page wiring", () => {diff --git a/tests/unit/sidebar-visibility.test.ts b/tests/unit/sidebar-visibility.test.tsindex 9b899d645a..547159e17a 100644--- a/tests/unit/sidebar-visibility.test.ts+++ b/tests/unit/sidebar-visibility.test.ts@@ -1,7 +1,10 @@import test from "node:test";import assert from "node:assert/strict";+import { readFile } from "node:fs/promises";+import { join } from "node:path";const sidebarVisibility = await import("../../src/shared/constants/sidebarVisibility.ts");+const repoRoot = join(import.meta.dirname, "../..");test("system sidebar items place logs before health", () => {const systemSection = sidebarVisibility.SIDEBAR_SECTIONS.find(@@ -38,3 +41,32 @@ test("primary sidebar items place limits after cache", () => {]);});++test("sidebar visibility drops stale audit entries from saved settings", () => {+ const allSidebarItemIds = sidebarVisibility.SIDEBAR_SECTIONS.flatMap((section) =>+ section.items.map((item) => item.id)+ );++ assert.equal(sidebarVisibility.HIDEABLE_SIDEBAR_ITEM_IDS.includes("audit"), false);+ assert.equal(allSidebarItemIds.includes("audit"), false);+ assert.deepEqual(sidebarVisibility.normalizeHiddenSidebarItems(["audit", "logs"]), ["logs"]);+});++test("legacy dashboard routes redirect to their consolidated surfaces", async () => {+ const autoComboPage = await readFile(+ join(repoRoot, "src/app/(dashboard)/dashboard/auto-combo/page.tsx"),+ "utf8"+ );+ const auditPage = await readFile(+ join(repoRoot, "src/app/(dashboard)/dashboard/audit/page.tsx"),+ "utf8"+ );+ const usagePage = await readFile(+ join(repoRoot, "src/app/(dashboard)/dashboard/usage/page.tsx"),+ "utf8"+ );++ assert.match(autoComboPage, /redirect\("\/dashboard\/combos\?filter=intelligent"\)/);+ assert.match(auditPage, /redirect\("\/dashboard\/logs\?tab=audit-logs"\)/);+ assert.match(usagePage, /redirect\("\/dashboard\/logs"\)/);+});diff --git a/tests/unit/skills-builtins-sandbox.test.ts b/tests/unit/skills-builtins-sandbox.test.tsindex 277ec16a73..9f70ea219e 100644--- a/tests/unit/skills-builtins-sandbox.test.ts+++ b/tests/unit/skills-builtins-sandbox.test.ts@@ -2,11 +2,45 @@ import test from "node:test";import assert from "node:assert/strict";import { EventEmitter } from "node:events";import { createRequire } from "node:module";--import { builtinSkills, registerBuiltinSkills } from "../../src/lib/skills/builtins.ts";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { pathToFileURL } from "node:url";const require = createRequire(import.meta.url);const childProcess = require("child_process");+const originalDataDir = process.env.DATA_DIR;+const originalFetch = globalThis.fetch;++function makeTempDir(prefix) {+ return fs.mkdtempSync(path.join(os.tmpdir(), prefix));+}++function removePath(targetPath) {+ fs.rmSync(targetPath, { recursive: true, force: true });+}++async function importFresh(modulePath) {+ const url = pathToFileURL(path.resolve(modulePath)).href;+ return import(`${url}?test=${Date.now()}-${Math.random().toString(16).slice(2)}`);+}++async function withDataDir(dataDir, fn) {+ process.env.DATA_DIR = dataDir;+ try {+ return await fn();+ } finally {+ if (originalDataDir === undefined) {+ delete process.env.DATA_DIR;+ } else {+ process.env.DATA_DIR = originalDataDir;+ }+ }+}++test.afterEach(() => {+ globalThis.fetch = originalFetch;+});function createFakeProcess({ onKill } = {}) {const proc = new EventEmitter();@@ -34,56 +68,178 @@ async function withSandboxModule(fakeSpawn, fn) {}}-test("builtin skill handlers validate required fields and return contextual stubs", async () => {+test("builtin skill handlers validate required fields and perform real sandboxed work", async () => {+ const dataDir = makeTempDir("omniroute-skills-builtins-");const context = { apiKeyId: "key-123", sessionId: "session-123" };- await assert.rejects(() => builtinSkills.file_read({}, context), /Missing required field: path/);- await assert.rejects(- () => builtinSkills.file_write({ path: "/tmp/file.txt" }, context),- /Missing required fields/- );- await assert.rejects(- () => builtinSkills.http_request({}, context),- /Missing required field: url/- );- await assert.rejects(- () => builtinSkills.web_search({}, context),- /Missing required field: query/- );- await assert.rejects(() => builtinSkills.eval_code({}, context), /Missing required field: code/);- await assert.rejects(- () => builtinSkills.execute_command({}, context),- /Missing required field: command/- );+ try {+ await withDataDir(dataDir, async () => {+ const { builtinSkills } = await importFresh("src/lib/skills/builtins.ts");- assert.deepEqual(await builtinSkills.file_read({ path: "/tmp/demo.txt" }, context), {- success: true,- path: "/tmp/demo.txt",- content: "[File read stub]",- context: "key-123",- });- assert.deepEqual(- await builtinSkills.file_write({ path: "/tmp/demo.txt", content: "hello world" }, context),- {- success: true,- path: "/tmp/demo.txt",- bytesWritten: 11,- context: "key-123",- }- );- assert.deepEqual(- await builtinSkills.execute_command({ command: "echo", args: ["hello"] }, context),- {- success: true,- command: "echo",- args: ["hello"],- output: "[Command execution stub]",- context: "key-123",- }+ await assert.rejects(+ () => builtinSkills.file_read({}, context),+ /Missing required field: path/+ );+ await assert.rejects(+ () => builtinSkills.file_write({ path: "demo.txt" }, context),+ /Missing required fields/+ );+ await assert.rejects(+ () => builtinSkills.http_request({}, context),+ /Missing required field: url/+ );+ await assert.rejects(+ () => builtinSkills.web_search({}, context),+ /Missing required field: query/+ );+ await assert.rejects(+ () => builtinSkills.eval_code({}, context),+ /Missing required field: code/+ );+ await assert.rejects(+ () => builtinSkills.execute_command({}, context),+ /Missing required field: command/+ );++ assert.deepEqual(+ await builtinSkills.file_write({ path: "notes/demo.txt", content: "hello world" }, context),+ {+ success: true,+ path: "notes/demo.txt",+ bytesWritten: 11,+ context: "key-123",+ }+ );++ assert.deepEqual(await builtinSkills.file_read({ path: "notes/demo.txt" }, context), {+ success: true,+ path: "notes/demo.txt",+ content: "hello world",+ bytesRead: 11,+ encoding: "utf8",+ context: "key-123",+ });++ await assert.rejects(+ () => builtinSkills.file_read({ path: "../outside.txt" }, context),+ /escapes the skill workspace/+ );+ await assert.rejects(+ () => builtinSkills.file_write({ path: ".env", content: "secret" }, context),+ /restricted segment/+ );++ globalThis.fetch = async (url, init) => {+ assert.equal(String(url), "https://example.com/api");+ assert.equal(init.method, "POST");+ assert.equal(init.headers.Accept, "application/json");+ assert.equal(init.headers.Authorization, undefined);+ assert.equal(init.body, JSON.stringify({ ok: true }));+ return new Response("created", {+ status: 201,+ statusText: "Created",+ headers: { "Content-Type": "text/plain" },+ });+ };++ const httpResult = await builtinSkills.http_request(+ {+ url: "https://example.com/api",+ method: "POST",+ headers: { Accept: "application/json", Authorization: "Bearer secret" },+ body: { ok: true },+ },+ context+ );++ assert.equal(httpResult.success, true);+ assert.equal(httpResult.status, 201);+ assert.equal(httpResult.body, "created");+ assert.equal(httpResult.headers["content-type"], "text/plain");++ await assert.rejects(+ () => builtinSkills.http_request({ url: "http://127.0.0.1:9000" }, context),+ /Blocked private or local provider URL/+ );+ });+ } finally {+ removePath(dataDir);+ }+});++test("builtin command and code skills execute through the Docker sandbox", async () => {+ const context = { apiKeyId: "key-123", sessionId: "session-123" };+ const calls = [];+ const originalSpawn = childProcess.spawn;++ childProcess.spawn = (_command, args, options) => {+ calls.push({ args, options });+ const proc = createFakeProcess();+ setImmediate(() => {+ proc.stdout.emit("data", Buffer.from("hello sandbox\n"));+ proc.stderr.emit("data", Buffer.from("warning stream\n"));+ proc.emit("close", 0);+ });+ return proc;+ };++ try {+ const { builtinSkills } = await importFresh("src/lib/skills/builtins.ts");++ const commandResult = await builtinSkills.execute_command(+ { command: "echo", args: ["hello"] },+ context+ );+ assert.equal(commandResult.success, true);+ assert.equal(commandResult.exitCode, 0);+ assert.equal(commandResult.output, "hello sandbox\n");+ assert.equal(commandResult.stderr, "warning stream\n");++ const codeResult = await builtinSkills.eval_code(+ { code: "console.log('hello sandbox')", language: "javascript" },+ context+ );+ assert.equal(codeResult.success, true);+ assert.equal(codeResult.image, "node:22-alpine");++ const dockerArgs = calls[0].args;+ assert.equal(dockerArgs[0], "run");+ assert.ok(dockerArgs.includes("--network"));+ assert.ok(dockerArgs.includes("none"));+ assert.ok(dockerArgs.includes("--cap-drop"));+ assert.ok(dockerArgs.includes("ALL"));+ assert.ok(dockerArgs.includes("--security-opt"));+ assert.ok(dockerArgs.includes("no-new-privileges"));+ assert.ok(dockerArgs.includes("--read-only"));+ assert.ok(dockerArgs.includes("/workspace:rw,noexec,nosuid,size=64m"));+ assert.equal(dockerArgs.includes("SYS_TIME"), false);++ await assert.rejects(+ () =>+ builtinSkills.execute_command(+ { command: "echo", image: "ubuntu:latest", args: ["hello"] },+ context+ ),+ /Sandbox image is not allowed/+ );+ } finally {+ childProcess.spawn = originalSpawn;+ }+});++test("browser skill fails explicitly instead of returning a fake success", async () => {+ const { browserSkill } = await importFresh("src/lib/skills/builtin/browser.ts");+ const context = { apiKeyId: "key-123", sessionId: "session-123" };++ await assert.rejects(+ () => browserSkill({ action: "navigate", url: "https://example.com" }, context),+ /Browser automation skill is disabled/);+ await assert.rejects(() => browserSkill({ action: "launch" }, context), /Unknown action: launch/);});-test("registerBuiltinSkills registers every builtin handler with the executor", () => {+test("registerBuiltinSkills registers every builtin handler with the executor", async () => {+ const { builtinSkills, registerBuiltinSkills } = await importFresh("src/lib/skills/builtins.ts");const registered = [];const executor = {registerHandler(name, handler) {diff --git a/tests/unit/sse-shim-contract.test.ts b/tests/unit/sse-shim-contract.test.tsnew file mode 100644index 0000000000..fa4717e20f--- /dev/null+++ b/tests/unit/sse-shim-contract.test.ts@@ -0,0 +1,66 @@+import test from "node:test";+import assert from "node:assert/strict";+import { existsSync, readdirSync, readFileSync } from "node:fs";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++const TEST_DATA_DIR = mkdtempSync(join(tmpdir(), "omniroute-sse-shim-"));+process.env.DATA_DIR = TEST_DATA_DIR;++const repoRoot = join(import.meta.dirname, "../..");++function readProjectFile(relativePath: string): string {+ return readFileSync(join(repoRoot, relativePath), "utf8");+}++function listProjectFiles(relativePath: string): string[] {+ const fullPath = join(repoRoot, relativePath);+ if (!existsSync(fullPath)) return [];++ return readdirSync(fullPath, { withFileTypes: true }).flatMap((entry) => {+ const childPath = `${relativePath}/${entry.name}`;+ if (entry.isDirectory()) return listProjectFiles(childPath);+ return childPath;+ });+}++test.after(() => {+ rmSync(TEST_DATA_DIR, { recursive: true, force: true });+});++test("src/sse model shim keeps parseModel behavior aligned with open-sse core", async () => {+ const srcModel = await import("../../src/sse/services/model.ts");+ const coreModel = await import("../../open-sse/services/model.ts");+ const samples = [+ "openai/gpt-4o-mini",+ "claude-sonnet-4-6[1m]",+ "gemini-3-pro-preview",+ "anthropic/claude-opus-4.5",+ "gpt-oss:120b",+ "../bad-model",+ ];++ for (const sample of samples) {+ assert.deepEqual(srcModel.parseModel(sample), coreModel.parseModel(sample));+ }+});++test("src/sse service wrappers delegate to open-sse and shared infrastructure", () => {+ const tokenRefreshSource = readProjectFile("src/sse/services/tokenRefresh.ts");+ const modelSource = readProjectFile("src/sse/services/model.ts");+ const loggerSource = readProjectFile("src/sse/utils/logger.ts");++ assert.match(tokenRefreshSource, /@omniroute\/open-sse\/services\/tokenRefresh\.ts/);+ assert.match(modelSource, /@omniroute\/open-sse\/services\/model\.ts/);+ assert.match(loggerSource, /@\/shared\/utils\/logger/);+ assert.doesNotMatch(loggerSource, /console\.(log|warn|error|info|debug)/);+});++test("src/sse does not contain tracked backup artifacts", () => {+ const artifacts = listProjectFiles("src/sse").filter((file) =>+ /\.(orig|bak|backup)$/i.test(file)+ );++ assert.deepEqual(artifacts, []);+});