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

chore(scripts): remove scratch one-shot scripts archive

diegosouzapwca6916a86742
diff --git a/scripts/scratch.mjs b/scripts/scratch.mjs
deleted file mode 100644
index 274e16520e..0000000000
--- a/scripts/scratch.mjs
+++ /dev/null
@@ -1,12 +0,0 @@
-import { test } from "node:test";
-import assert from "node:assert";
-import { providerNodesValidateRoute } from "./src/app/api/provider-nodes/validate/route.js";
-
-const req = new Request("http://localhost/api/provider-nodes/validate", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ baseUrl: "", apiKey: "" }),
-});
-const res = await providerNodesValidateRoute.POST(req);
-const data = await res.json();
-console.dir(data, { depth: null });
diff --git a/scripts/scratch/categorize_ideas.py b/scripts/scratch/categorize_ideas.py
deleted file mode 100644
index 943939d630..0000000000
--- a/scripts/scratch/categorize_ideas.py
+++ /dev/null
@@ -1,39 +0,0 @@
-import os
-import shutil
-import subprocess
-
-categories = {
- "viable": [1718, 1731, 1764],
- "need_details": [1765, 1679, 1594, 1584],
- "defer": [1845, 1833, 1814, 1786, 1737, 1736, 1735, 1716, 1591, 1590, 1589, 1588, 1587],
- "notfit": [1826, 1788, 1529, 1586] # 1586 is already exists, goes to notfit
-}
-
-# Create dirs
-os.makedirs("_ideia/viable/need_details", exist_ok=True)
-os.makedirs("_ideia/defer", exist_ok=True)
-os.makedirs("_ideia/notfit", exist_ok=True)
-
-files = os.listdir("_ideia")
-
-for f in files:
- if not f.endswith(".md"): continue
- num_str = f.split('-')[0]
- if not num_str.isdigit(): continue
- num = int(num_str)
-
- src = os.path.join("_ideia", f)
-
- if num in categories["viable"]:
- dst = os.path.join("_ideia/viable", f)
- elif num in categories["need_details"]:
- dst = os.path.join("_ideia/viable/need_details", f)
- elif num in categories["defer"]:
- dst = os.path.join("_ideia/defer", f)
- elif num in categories["notfit"]:
- dst = os.path.join("_ideia/notfit", f)
- else:
- continue
-
- shutil.move(src, dst)
- print(f"Moved {f} to {dst}")
diff --git a/scripts/scratch/check_usage.js b/scripts/scratch/check_usage.js
deleted file mode 100644
index 9360bab904..0000000000
--- a/scripts/scratch/check_usage.js
+++ /dev/null
@@ -1,41 +0,0 @@
-import Database from "better-sqlite3";
-import path from "path";
-import os from "os";
-
-const SQLITE_FILE = path.join(process.cwd(), "data", "storage.sqlite");
-
-console.log("Checking database at:", SQLITE_FILE);
-
-const db = new Database(SQLITE_FILE, { readonly: true });
-
-try {
- const rows = db
- .prepare(
- `
- SELECT api_key_id, api_key_name, COUNT(*) as count, MAX(timestamp) as last_used
- FROM usage_history
- GROUP BY api_key_id, api_key_name
- ORDER BY count DESC
- `
- )
- .all();
-
- console.log("Top Usage Entries:");
- console.table(rows);
-
- const keys = db
- .prepare(
- `
- SELECT id, name, key_prefix, machine_id
- FROM api_keys
- `
- )
- .all();
-
- console.log("All API Keys:");
- console.table(keys);
-} catch (err) {
- console.error("Error:", err.message);
-} finally {
- db.close();
-}
diff --git a/scripts/scratch/debug-handles.mjs b/scripts/scratch/debug-handles.mjs
deleted file mode 100644
index 3f224f6b1a..0000000000
--- a/scripts/scratch/debug-handles.mjs
+++ /dev/null
@@ -1,17 +0,0 @@
-import process from "node:process";
-import fs from "node:fs";
-
-setTimeout(() => {
- const activeHandles = process._getActiveHandles();
- console.log("ACTIVE HANDLES: " + activeHandles.length);
- activeHandles.forEach((handle, i) => {
- console.log(`Handle ${i}:`, handle?.constructor?.name);
- // if it's a timer or socket, let's see more
- if (handle?.constructor?.name === "Timeout") {
- console.log(" Timer wrapper:", handle?._onTimeout?.toString().slice(0, 50));
- }
- });
- process.exit(1);
-}, 2000);
-
-await import("./tests/integration/chat-pipeline.test.mjs");
diff --git a/scripts/scratch/debug-sockets.mjs b/scripts/scratch/debug-sockets.mjs
deleted file mode 100644
index 345213ebb5..0000000000
--- a/scripts/scratch/debug-sockets.mjs
+++ /dev/null
@@ -1,14 +0,0 @@
-import process from "node:process";
-import("./tests/integration/chat-pipeline.test.mjs").then((mod) => {
- setTimeout(() => {
- const activeHandles = process._getActiveHandles();
- console.log("ACTIVE HANDLES: " + activeHandles.length);
- activeHandles.forEach((handle, i) => {
- console.log(`Handle ${i}:`, handle?.constructor?.name);
- if (handle?.constructor?.name === "Socket") {
- console.log("Socket ports:", handle?.localPort, handle?.remotePort);
- }
- });
- process.exit(1);
- }, 15000);
-});
diff --git a/scripts/scratch/delete_iflow.cjs b/scripts/scratch/delete_iflow.cjs
deleted file mode 100644
index 2d80bbf4db..0000000000
--- a/scripts/scratch/delete_iflow.cjs
+++ /dev/null
@@ -1,7 +0,0 @@
-const Database = require('better-sqlite3');
-const db = new Database(process.env.HOME + '/.omniroute/storage.sqlite');
-
-console.log("Deleting iflow connections...");
-const stmt = db.prepare("DELETE FROM provider_connections WHERE provider = 'iflow'");
-const info = stmt.run();
-console.log(`Deleted ${info.changes} rows.`);
diff --git a/scripts/scratch/dump-auth-groups.ts b/scripts/scratch/dump-auth-groups.ts
deleted file mode 100644
index f598461d4f..0000000000
--- a/scripts/scratch/dump-auth-groups.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import {
- APIKEY_PROVIDERS,
- SEARCH_PROVIDERS,
- AUDIO_ONLY_PROVIDERS,
- WEB_COOKIE_PROVIDERS,
-} from "./src/shared/constants/providers";
-
-console.log("SEARCH_PROVIDERS", !!SEARCH_PROVIDERS, Object.keys(SEARCH_PROVIDERS || {}));
-console.log("AUDIO_ONLY", !!AUDIO_ONLY_PROVIDERS);
-console.log("WEB_COOKIE", !!WEB_COOKIE_PROVIDERS);
-
-// Determine auth type group for a provider id
-function getAuthGroup(providerId: string) {
- if (WEB_COOKIE_PROVIDERS && WEB_COOKIE_PROVIDERS[providerId]) return "web-cookie";
- if (SEARCH_PROVIDERS && SEARCH_PROVIDERS[providerId]) return "search";
- if (AUDIO_ONLY_PROVIDERS && AUDIO_ONLY_PROVIDERS[providerId]) return "audio";
- if (APIKEY_PROVIDERS && APIKEY_PROVIDERS[providerId]) return "apikey";
- return "apikey";
-}
-
-console.log("grok-web returns:", getAuthGroup("grok-web"));
-console.log("perplexity-search returns:", getAuthGroup("perplexity-search"));
-console.log("openai returns:", getAuthGroup("openai"));
diff --git a/scripts/scratch/fix-tests.js b/scripts/scratch/fix-tests.js
deleted file mode 100644
index f6ac99e1ff..0000000000
--- a/scripts/scratch/fix-tests.js
+++ /dev/null
@@ -1,30 +0,0 @@
-const fs = require("fs");
-
-function addAnyCast(filePath) {
- let content = fs.readFileSync(filePath, "utf8");
- // Match "const varname = await func({...});" and make it "const varname: any = await func({...});"
- content = content.replace(
- /(const\s+\w+)\s*=\s*(await\s+(?:usageService|usageFetcher)\.getUsageForProvider\()/g,
- "$1: any = $2"
- );
- fs.writeFileSync(filePath, content);
-}
-
-addAnyCast("tests/unit/usage-service-hardening.test.ts");
-addAnyCast("tests/unit/usage-fetcher-antigravity.test.ts");
-
-let bailian = fs.readFileSync("tests/unit/bailian-quota-fetcher.test.ts", "utf8");
-// Fix missing window properties in test typing
-bailian = bailian.replace(/const quota = /g, "const quota: any = ");
-fs.writeFileSync("tests/unit/bailian-quota-fetcher.test.ts", bailian);
-
-let routeTest = fs.readFileSync("tests/unit/token-refresh-route-service.test.ts", "utf8");
-// Fix provider mocks typing
-routeTest = routeTest.replace(/github: \{/g, '"github": {'); // Fix github
-routeTest = routeTest.replace(
- /(refreshWithRetry|log\.entries).*?(toBe|equal).*?;/g,
- (match) => match
-); // just ignore
-fs.writeFileSync("tests/unit/token-refresh-route-service.test.ts", routeTest);
-
-console.log("Fixes applied.");
diff --git a/scripts/scratch/fix-types.mjs b/scripts/scratch/fix-types.mjs
deleted file mode 100644
index 2001c2b810..0000000000
--- a/scripts/scratch/fix-types.mjs
+++ /dev/null
@@ -1,52 +0,0 @@
-import fs from "fs";
-
-let content = fs.readFileSync("tests/unit/token-refresh-service.test.ts", "utf-8");
-
-// Fix jsonResponse
-content = content.replace(
- /function jsonResponse\(body, status = 200\)/g,
- "function jsonResponse(body: any, status = 200)"
-);
-
-// Fix textResponse
-content = content.replace(
- /function textResponse\(text, status = 400\)/g,
- "function textResponse(text: any, status = 400)"
-);
-
-// Fix calls = []
-content = content.replace(/const calls = \[\];/g, "const calls: any[] = [];");
-
-// Fix result is possibly null
-content = content.replace(/result\.accessToken/g, "result?.accessToken");
-content = content.replace(/result\.refreshToken/g, "result?.refreshToken");
-content = content.replace(/result\.expiresIn/g, "result?.expiresIn");
-
-fs.writeFileSync("tests/unit/token-refresh-service.test.ts", content);
-
-let claudeContent = fs.readFileSync("tests/unit/translator-claude-to-gemini.test.ts", "utf-8");
-claudeContent = claudeContent.replace(/result\.tools/g, "(result as any).tools");
-claudeContent = claudeContent.replace(/result\._toolNameMap/g, "(result as any)._toolNameMap");
-claudeContent = claudeContent.replace(/result\[0\]/g, "(result as any)[0]");
-fs.writeFileSync("tests/unit/translator-claude-to-gemini.test.ts", claudeContent);
-
-let openaiContent = fs.readFileSync("tests/unit/translator-openai-to-gemini.test.ts", "utf-8");
-openaiContent = openaiContent.replace(
- /result\.systemInstruction/g,
- "(result as any).systemInstruction"
-);
-openaiContent = openaiContent.replace(/result\.tools/g, "(result as any).tools");
-openaiContent = openaiContent.replace(
- /result\.generationConfig/g,
- "(result as any).generationConfig"
-);
-openaiContent = openaiContent.replace(/result\._toolNameMap/g, "(result as any)._toolNameMap");
-openaiContent = openaiContent.replace(
- /result\.request\.systemInstruction/g,
- "(result as any).request?.systemInstruction"
-);
-openaiContent = openaiContent.replace(/result\.request\.tools/g, "(result as any).request?.tools");
-openaiContent = openaiContent.replace(/null\)/g, "null as any)");
-fs.writeFileSync("tests/unit/translator-openai-to-gemini.test.ts", openaiContent);
-
-console.log("Fixed typings");
diff --git a/scripts/scratch/fix_route.ts b/scripts/scratch/fix_route.ts
deleted file mode 100644
index 186ae89e1d..0000000000
--- a/scripts/scratch/fix_route.ts
+++ /dev/null
@@ -1,708 +0,0 @@
-import fs from "fs";
-
-const content = fs.readFileSync("src/app/api/usage/analytics/route.ts", "utf8");
-
-// We'll replace the GET function entirely
-const getFnStart = content.indexOf("export async function GET(request: Request) {");
-const beforeGet = content.slice(0, getFnStart);
-
-const newGetFn = `export async function GET(request: Request) {
- try {
- const { searchParams } = new URL(request.url);
- const range = searchParams.get("range") || "30d";
- const startDate = searchParams.get("startDate") || undefined;
- const endDate = searchParams.get("endDate") || undefined;
- const apiKeyIdsParam = searchParams.get("apiKeyIds") || "";
- const apiKeyIds = apiKeyIdsParam ? apiKeyIdsParam.split(",").filter(Boolean) : [];
-
- const sinceIso = startDate || getRangeStartIso(range);
- const untilIso = endDate || null;
- const presetsParam = searchParams.get("presets");
-
- const db = getDbInstance();
-
- // ── Enrich entries with missing apiKeyName ──────────────────────────
- try {
- // Only run enrichment if there are actually NULL entries
- const hasNull = db.prepare("SELECT 1 FROM usage_history WHERE (api_key_name IS NULL OR api_key_name = '') AND connection_id IS NOT NULL LIMIT 1").get();
- if (hasNull) {
- // Step 1: dominant key per connectionId from existing usage data
- db.prepare(\`
- UPDATE usage_history
- SET
- api_key_name = (
- SELECT uh2.api_key_name
- FROM usage_history AS uh2
- WHERE uh2.connection_id = usage_history.connection_id
- AND uh2.api_key_name IS NOT NULL AND uh2.api_key_name != ''
- GROUP BY uh2.api_key_name
- ORDER BY COUNT(*) DESC
- LIMIT 1
- ),
- api_key_id = COALESCE(api_key_id, (
- SELECT uh2.api_key_id
- FROM usage_history AS uh2
- WHERE uh2.connection_id = usage_history.connection_id
- AND uh2.api_key_name IS NOT NULL AND uh2.api_key_name != ''
- GROUP BY uh2.api_key_name
- ORDER BY COUNT(*) DESC
- LIMIT 1
- ))
- WHERE (api_key_name IS NULL OR api_key_name = '')
- AND connection_id IS NOT NULL
- AND EXISTS (
- SELECT 1 FROM usage_history AS uh3
- WHERE uh3.connection_id = usage_history.connection_id
- AND uh3.api_key_name IS NOT NULL AND uh3.api_key_name != ''
- )
- \`).run();
-
- // Step 2 & 3: For still unresolved connections, check apiKeys config
- const stillNull = db.prepare("SELECT DISTINCT connection_id FROM usage_history WHERE (api_key_name IS NULL OR api_key_name = '') AND connection_id IS NOT NULL").all();
- if (stillNull.length > 0) {
- const { getApiKeys } = await import("@/lib/localDb");
- const apiKeys = (await getApiKeys()) as any[];
-
- const updateStmt = db.prepare("UPDATE usage_history SET api_key_name = ?, api_key_id = ? WHERE connection_id = ? AND (api_key_name IS NULL OR api_key_name = '')");
- const updateMany = db.transaction((updates: any[]) => {
- for (const u of updates) updateStmt.run(u.name, u.id, u.cid);
- });
-
- const updates = [];
- const orphanIds = new Set(stillNull.map((r: any) => r.connection_id));
-
- for (const ak of apiKeys) {
- const allowed = Array.isArray(ak.allowedConnections) ? ak.allowedConnections : [];
- const keyName = ak.name || ak.id;
- const keyId = ak.id || null;
- for (const cid of allowed) {
- if (typeof cid === "string" && orphanIds.has(cid)) {
- updates.push({ name: keyName, id: keyId, cid });
- orphanIds.delete(cid);
- }
- }
- }
-
- if (orphanIds.size > 0) {
- const unrestrictedKeys = apiKeys.filter(
- (ak: any) => !Array.isArray(ak.allowedConnections) || ak.allowedConnections.length === 0
- );
- if (unrestrictedKeys.length > 0) {
- let bestKey = unrestrictedKeys[0];
- let bestCount = -1;
- for (const uk of unrestrictedKeys) {
- const countRow = db.prepare("SELECT COUNT(*) as c FROM usage_history WHERE api_key_name = ?").get(uk.name || uk.id) as any;
- if (countRow.c > bestCount) { bestCount = countRow.c; bestKey = uk; }
- }
- const fallbackName = bestKey.name || bestKey.id;
- const fallbackId = bestKey.id || null;
- for (const cid of orphanIds) {
- updates.push({ name: fallbackName, id: fallbackId, cid });
- }
- }
- }
-
- if (updates.length > 0) updateMany(updates);
- }
- }
- } catch(e) {
- console.error("Failed to backfill missing api_key_name:", e);
- }
-
- const conditions = [];
- const params: Record<string, string> = {};
-
- if (sinceIso) {
- conditions.push("timestamp >= @since");
- params.since = sinceIso;
- }
- if (untilIso) {
- conditions.push("timestamp <= @until");
- params.until = untilIso;
- }
-
- let apiKeyWhere = "";
- if (apiKeyIds.length > 0) {
- const placeholders = apiKeyIds.map((_, i) => \`@apiKey\${i}\`);
- apiKeyIds.forEach((key, i) => {
- params[\`apiKey\${i}\`] = key;
- });
- apiKeyWhere = \`(api_key_name IN (\${placeholders.join(",")}) OR api_key_id IN (\${placeholders.join(",")}))\`;
- conditions.push(apiKeyWhere);
- }
-
- const whereClause = conditions.length > 0 ? \`WHERE \${conditions.join(" AND ")}\` : "";
-
- // Fetch pricing data for cost calculation (no rows loaded)
- const { getPricing } = await import("@/lib/db/settings");
- const pricingByProvider = (await getPricing()) as PricingByProvider;
- const { computeCostFromPricing, normalizeModelName } =
- await import("@/lib/usage/costCalculator");
-
- const summaryRow = db
- .prepare(
- \`
- SELECT
- COUNT(*) as totalRequests,
- COALESCE(SUM(tokens_input), 0) as promptTokens,
- COALESCE(SUM(tokens_output), 0) as completionTokens,
- COALESCE(SUM(tokens_input + tokens_output), 0) as totalTokens,
- COUNT(DISTINCT model) as uniqueModels,
- COUNT(DISTINCT connection_id) as uniqueAccounts,
- COUNT(DISTINCT api_key_id) as uniqueApiKeys,
- COALESCE(SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END), 0) as successfulRequests,
- COALESCE(AVG(latency_ms), 0) as avgLatencyMs,
- COALESCE(MIN(timestamp), '') as firstRequest,
- COALESCE(MAX(timestamp), '') as lastRequest
- FROM usage_history
- \${whereClause}
- \`
- )
- .get(params) as Record<string, unknown>;
-
- const dailyRows = db
- .prepare(
- \`
- SELECT
- DATE(timestamp) as date,
- COUNT(*) as requests,
- COALESCE(SUM(tokens_input), 0) as promptTokens,
- COALESCE(SUM(tokens_output), 0) as completionTokens,
- COALESCE(SUM(tokens_input + tokens_output), 0) as totalTokens
- FROM usage_history
- \${whereClause}
- GROUP BY DATE(timestamp)
- ORDER BY date ASC
- \`
- )
- .all(params) as Array<Record<string, unknown>>;
-
- const dailyCostRows = db
- .prepare(
- \`
- SELECT
- DATE(timestamp) as date,
- provider,
- model,
- COALESCE(SUM(tokens_input), 0) as promptTokens,
- COALESCE(SUM(tokens_output), 0) as completionTokens,
- COALESCE(SUM(tokens_cache_read), 0) as cacheReadTokens,
- COALESCE(SUM(tokens_cache_creation), 0) as cacheCreationTokens,
- COALESCE(SUM(tokens_reasoning), 0) as reasoningTokens
- FROM usage_history
- \${whereClause}
- GROUP BY DATE(timestamp), provider, model
- ORDER BY date ASC
- \`
- )
- .all(params) as Array<Record<string, unknown>>;
-
- const heatmapStart = new Date();
- heatmapStart.setUTCDate(heatmapStart.getUTCDate() - 364);
- // Custom date range might need a wider heatmap window
- if (startDate) {
- const customStart = new Date(startDate);
- if (customStart.getTime() < heatmapStart.getTime()) {
- heatmapStart.setTime(customStart.getTime());
- }
- }
-
- // Heatmap needs its own whereClause if api keys are filtered
- const heatmapConditions = ["timestamp >= @heatmapStart"];
- if (apiKeyWhere) heatmapConditions.push(apiKeyWhere);
- const heatmapParams: Record<string, string> = { heatmapStart: heatmapStart.toISOString() };
- if (apiKeyIds.length > 0) {
- apiKeyIds.forEach((key, i) => { heatmapParams[\`apiKey\${i}\`] = key; });
- }
-
- const heatmapRows = db
- .prepare(
- \`
- SELECT
- DATE(timestamp) as date,
- COALESCE(SUM(tokens_input + tokens_output), 0) as totalTokens
- FROM usage_history
- WHERE \${heatmapConditions.join(" AND ")}
- GROUP BY DATE(timestamp)
- ORDER BY date ASC
- \`
- )
- .all(heatmapParams) as Array<Record<string, unknown>>;
-
- const modelRows = db
- .prepare(
- \`
- SELECT
- model,
- provider,
- COUNT(*) as requests,
- COALESCE(SUM(tokens_input), 0) as promptTokens,
- COALESCE(SUM(tokens_output), 0) as completionTokens,
- COALESCE(SUM(tokens_cache_read), 0) as cacheReadTokens,
- COALESCE(SUM(tokens_cache_creation), 0) as cacheCreationTokens,
- COALESCE(SUM(tokens_reasoning), 0) as reasoningTokens,
- COALESCE(SUM(tokens_input + tokens_output), 0) as totalTokens,
- COALESCE(AVG(latency_ms), 0) as avgLatencyMs,
- COALESCE(SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END), 0) as successfulRequests,
- COALESCE(MAX(timestamp), '') as lastUsed
- FROM usage_history
- \${whereClause}
- GROUP BY model, provider
- ORDER BY requests DESC
- LIMIT 50
- \`
- )
- .all(params) as Array<Record<string, unknown>>;
-
- const providerCostRows = db
- .prepare(
- \`
- SELECT
- provider,
- model,
- COALESCE(SUM(tokens_input), 0) as promptTokens,
- COALESCE(SUM(tokens_output), 0) as completionTokens,
- COALESCE(SUM(tokens_cache_read), 0) as cacheReadTokens,
- COALESCE(SUM(tokens_cache_creation), 0) as cacheCreationTokens,
- COALESCE(SUM(tokens_reasoning), 0) as reasoningTokens
- FROM usage_history
- \${whereClause}
- GROUP BY provider, model
- \`
- )
- .all(params) as Array<Record<string, unknown>>;
-
- const providerRows = db
- .prepare(
- \`
- SELECT
- provider,
- COUNT(*) as requests,
- COALESCE(SUM(tokens_input), 0) as promptTokens,
- COALESCE(SUM(tokens_output), 0) as completionTokens,
- COALESCE(SUM(tokens_input + tokens_output), 0) as totalTokens,
- COALESCE(AVG(latency_ms), 0) as avgLatencyMs,
- COALESCE(SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END), 0) as successfulRequests
- FROM usage_history
- \${whereClause}
- GROUP BY provider
- ORDER BY requests DESC
- \`
- )
- .all(params) as Array<Record<string, unknown>>;
-
- const accountCostRows = db
- .prepare(
- \`
- SELECT
- connection_id as account,
- provider,
- model,
- COALESCE(SUM(tokens_input), 0) as promptTokens,
- COALESCE(SUM(tokens_output), 0) as completionTokens,
- COALESCE(SUM(tokens_cache_read), 0) as cacheReadTokens,
- COALESCE(SUM(tokens_cache_creation), 0) as cacheCreationTokens,
- COALESCE(SUM(tokens_reasoning), 0) as reasoningTokens
- FROM usage_history
- \${whereClause}
- GROUP BY connection_id, provider, model
- \`
- )
- .all(params) as Array<Record<string, unknown>>;
-
- const accountRows = db
- .prepare(
- \`
- SELECT
- connection_id as account,
- COUNT(*) as requests,
- COALESCE(SUM(tokens_input), 0) as promptTokens,
- COALESCE(SUM(tokens_output), 0) as completionTokens,
- COALESCE(SUM(tokens_input + tokens_output), 0) as totalTokens,
- COALESCE(AVG(latency_ms), 0) as avgLatencyMs,
- COALESCE(MAX(timestamp), '') as lastUsed
- FROM usage_history
- \${whereClause}
- GROUP BY connection_id
- ORDER BY requests DESC
- LIMIT 50
- \`
- )
- .all(params) as Array<Record<string, unknown>>;
-
- const apiKeyWhereClause = appendWhereCondition(
- whereClause,
- "(api_key_id IS NOT NULL AND api_key_id != '') OR (api_key_name IS NOT NULL AND api_key_name != '')"
- );
- const apiKeyRows = db
- .prepare(
- \`
- SELECT
- api_key_id as apiKeyId,
- COALESCE(NULLIF(api_key_name, ''), NULLIF(api_key_id, ''), 'Unknown API key') as apiKeyName,
- provider,
- model,
- COUNT(*) as requests,
- COALESCE(SUM(tokens_input), 0) as promptTokens,
- COALESCE(SUM(tokens_output), 0) as completionTokens,
- COALESCE(SUM(tokens_cache_read), 0) as cacheReadTokens,
- COALESCE(SUM(tokens_cache_creation), 0) as cacheCreationTokens,
- COALESCE(SUM(tokens_reasoning), 0) as reasoningTokens,
- COALESCE(SUM(tokens_input + tokens_output), 0) as totalTokens
- FROM usage_history
- \${apiKeyWhereClause}
- GROUP BY api_key_id, api_key_name, provider, model
- \`
- )
- .all(params) as Array<Record<string, unknown>>;
-
- const weeklyRows = db
- .prepare(
- \`
- SELECT
- dayOfWeek,
- COUNT(*) as days,
- COALESCE(SUM(requests), 0) as requests,
- COALESCE(SUM(totalTokens), 0) as totalTokens
- FROM (
- SELECT
- DATE(timestamp) as date,
- strftime('%w', timestamp) as dayOfWeek,
- COUNT(*) as requests,
- COALESCE(SUM(tokens_input + tokens_output), 0) as totalTokens
- FROM usage_history
- \${whereClause}
- GROUP BY DATE(timestamp), strftime('%w', timestamp)
- )
- GROUP BY dayOfWeek
- ORDER BY dayOfWeek ASC
- \`
- )
- .all(params) as Array<Record<string, unknown>>;
-
- const fallbackRow = db
- .prepare(
- \`
- SELECT
- COUNT(*) as total,
- SUM(CASE WHEN requested_model IS NOT NULL AND requested_model != '' THEN 1 ELSE 0 END) as with_requested,
- SUM(CASE
- WHEN requested_model IS NOT NULL
- AND requested_model != ''
- AND model IS NOT NULL
- AND requested_model != model
- THEN 1 ELSE 0 END
- ) as fallbacks
- FROM call_logs
- \${whereClause}
- \`
- )
- .get(params) as Record<string, unknown>;
-
- const summary = {
- totalRequests: Number(summaryRow?.totalRequests || 0),
- promptTokens: Number(summaryRow?.promptTokens || 0),
- completionTokens: Number(summaryRow?.completionTokens || 0),
- totalTokens: Number(summaryRow?.totalTokens || 0),
- uniqueModels: Number(summaryRow?.uniqueModels || 0),
- uniqueAccounts: Number(summaryRow?.uniqueAccounts || 0),
- uniqueApiKeys: Number(summaryRow?.uniqueApiKeys || 0),
- successfulRequests: Number(summaryRow?.successfulRequests || 0),
- successRatePct:
- Number(summaryRow?.totalRequests || 0) > 0
- ? Number(
- (
- (Number(summaryRow?.successfulRequests || 0) /
- Number(summaryRow?.totalRequests || 1)) *
- 100
- ).toFixed(2)
- )
- : 0,
- avgLatencyMs: Math.round(Number(summaryRow?.avgLatencyMs || 0)),
- totalCost: 0,
- firstRequest: summaryRow?.firstRequest || "",
- lastRequest: summaryRow?.lastRequest || "",
- fallbackCount: Number(fallbackRow?.fallbacks || 0),
- fallbackRatePct:
- Number(fallbackRow?.with_requested || 0) > 0
- ? Number(
- (
- (Number(fallbackRow?.fallbacks || 0) / Number(fallbackRow?.with_requested || 1)) *
- 100
- ).toFixed(2)
- )
- : 0,
- requestedModelCoveragePct:
- Number(fallbackRow?.total || 0) > 0
- ? Number(
- (
- (Number(fallbackRow?.with_requested || 0) / Number(fallbackRow?.total || 1)) *
- 100
- ).toFixed(2)
- )
- : 0,
- streak: 0,
- };
-
- const dailyCostByDate = new Map<string, number>();
- for (const row of dailyCostRows) {
- const date = toStringValue(row.date);
- if (!date) continue;
- const cost = computeUsageRowCost(
- row,
- pricingByProvider,
- normalizeModelName,
- computeCostFromPricing
- );
- dailyCostByDate.set(date, (dailyCostByDate.get(date) || 0) + cost);
- }
-
- const dailyTrend = dailyRows.map((row) => ({
- date: row.date,
- requests: Number(row.requests),
- promptTokens: Number(row.promptTokens),
- completionTokens: Number(row.completionTokens),
- totalTokens: Number(row.totalTokens),
- cost: roundCost(dailyCostByDate.get(toStringValue(row.date)) || 0),
- }));
-
- const activityMap: Record<string, number> = {};
- for (const row of heatmapRows) {
- activityMap[row.date as string] = Number(row.totalTokens);
- }
- summary.streak = computeActivityStreak(activityMap);
-
- const byModel = modelRows.map((row) => {
- const model = row.model as string;
- const provider = row.provider as string;
- const short = shortModelName(model);
- const tokens = {
- input: Number(row.promptTokens) || 0,
- output: Number(row.completionTokens) || 0,
- };
- const cost = computeUsageRowCost(
- row,
- pricingByProvider,
- normalizeModelName,
- computeCostFromPricing
- );
- return {
- model: short,
- provider,
- rawModel: model,
- requests: Number(row.requests),
- promptTokens: tokens.input,
- completionTokens: tokens.output,
- totalTokens: Number(row.totalTokens),
- avgLatencyMs: Math.round(Number(row.avgLatencyMs)),
- successRatePct:
- Number(row.requests) > 0
- ? Number((Number(row.successfulRequests) / Number(row.requests)) * 100).toFixed(2)
- : 0,
- lastUsed: row.lastUsed,
- cost: roundCost(cost),
- };
- });
-
- const totalCost = Array.from(dailyCostByDate.values()).reduce((sum, cost) => sum + cost, 0);
- summary.totalCost = roundCost(totalCost);
-
- const providerCostByProvider = new Map<string, number>();
- for (const row of providerCostRows) {
- const provider = toStringValue(row.provider);
- if (!provider) continue;
- const cost = computeUsageRowCost(
- row,
- pricingByProvider,
- normalizeModelName,
- computeCostFromPricing
- );
- providerCostByProvider.set(provider, (providerCostByProvider.get(provider) || 0) + cost);
- }
-
- const byProvider = providerRows.map((row) => ({
- provider: row.provider,
- requests: Number(row.requests),
- promptTokens: Number(row.promptTokens),
- completionTokens: Number(row.completionTokens),
- totalTokens: Number(row.totalTokens),
- avgLatencyMs: Math.round(Number(row.avgLatencyMs)),
- successRatePct:
- Number(row.requests) > 0
- ? Number((Number(row.successfulRequests) / Number(row.requests)) * 100).toFixed(2)
- : 0,
- cost: roundCost(providerCostByProvider.get(toStringValue(row.provider)) || 0),
- }));
-
- const accountCostByAccount = new Map<string, number>();
- for (const row of accountCostRows) {
- const account = toStringValue(row.account, "unknown");
- const cost = computeUsageRowCost(
- row,
- pricingByProvider,
- normalizeModelName,
- computeCostFromPricing
- );
- accountCostByAccount.set(account, (accountCostByAccount.get(account) || 0) + cost);
- }
-
- const byAccount = accountRows.map((row) => ({
- account: toStringValue(row.account, "unknown"),
- requests: Number(row.requests),
- promptTokens: Number(row.promptTokens),
- completionTokens: Number(row.completionTokens),
- totalTokens: Number(row.totalTokens),
- avgLatencyMs: Math.round(Number(row.avgLatencyMs)),
- lastUsed: row.lastUsed,
- cost: roundCost(accountCostByAccount.get(toStringValue(row.account, "unknown")) || 0),
- }));
-
- const apiKeyMap = new Map<
- string,
- {
- apiKey: string;
- apiKeyId: string | null;
- apiKeyName: string;
- requests: number;
- promptTokens: number;
- completionTokens: number;
- totalTokens: number;
- cost: number;
- }
- >();
- for (const row of apiKeyRows) {
- const apiKeyId = toStringValue(row.apiKeyId);
- const apiKeyName = toStringValue(row.apiKeyName, apiKeyId || "Unknown API key");
- const key = \`\${apiKeyId || "unknown"}::\${apiKeyName}\`;
- const existing = apiKeyMap.get(key) || {
- apiKey: apiKeyId && apiKeyName !== apiKeyId ? \`\${apiKeyName} (\${apiKeyId})\` : apiKeyName,
- apiKeyId: apiKeyId || null,
- apiKeyName,
- requests: 0,
- promptTokens: 0,
- completionTokens: 0,
- totalTokens: 0,
- cost: 0,
- };
-
- existing.requests += Number(row.requests);
- existing.promptTokens += Number(row.promptTokens);
- existing.completionTokens += Number(row.completionTokens);
- existing.totalTokens += Number(row.totalTokens);
- existing.cost += computeUsageRowCost(
- row,
- pricingByProvider,
- normalizeModelName,
- computeCostFromPricing
- );
- apiKeyMap.set(key, existing);
- }
- const byApiKey = Array.from(apiKeyMap.values())
- .map((row) => ({ ...row, cost: roundCost(row.cost) }))
- .sort((left, right) => right.cost - left.cost);
-
- const weeklyTokens = [0, 0, 0, 0, 0, 0, 0];
- const weeklyCounts = [0, 0, 0, 0, 0, 0, 0];
- const weeklyPattern = WEEKDAY_LABELS.map((day) => ({
- day,
- avgTokens: 0,
- totalTokens: 0,
- }));
- for (const row of weeklyRows) {
- const dayIdx = Number(row.dayOfWeek);
- if (dayIdx >= 0 && dayIdx <= 6) {
- const totalTokens = Number(row.totalTokens);
- const days = Number(row.days);
- weeklyTokens[dayIdx] = totalTokens;
- weeklyCounts[dayIdx] = Number(row.requests);
- weeklyPattern[dayIdx] = {
- day: WEEKDAY_LABELS[dayIdx],
- avgTokens: days > 0 ? Math.round(totalTokens / days) : 0,
- totalTokens,
- };
- }
- }
-
- const analytics = {
- summary,
- dailyTrend,
- activityMap,
- byModel,
- byProvider,
- byApiKey,
- byAccount,
- weeklyPattern,
- weeklyTokens,
- weeklyCounts,
- range,
- } as any;
-
- if (presetsParam) {
- const allowedRanges = new Set(["1d", "7d", "30d", "90d", "ytd", "all"]);
- const presetRanges = presetsParam
- .split(",")
- .map((preset) => preset.trim())
- .filter((preset) => allowedRanges.has(preset));
- const presetSummaries: Record<string, { totalCost: number }> = {};
-
- for (const presetRange of presetRanges) {
- if (presetRange === range) {
- presetSummaries[presetRange] = {
- totalCost: Number(analytics.summary?.totalCost || 0),
- };
- continue;
- }
-
- const presetSinceIso = getRangeStartIso(presetRange);
- const presetConditions = [];
- const presetParams: Record<string, string> = {};
- if (presetSinceIso) { presetConditions.push("timestamp >= @presetSince"); presetParams.presetSince = presetSinceIso; }
- if (apiKeyWhere) { presetConditions.push(apiKeyWhere); Object.assign(presetParams, params); }
-
- const presetWhere = presetConditions.length > 0 ? \`WHERE \${presetConditions.join(" AND ")}\` : "";
-
- const presetModelRows = db
- .prepare(
- \`
- SELECT
- model,
- provider,
- COALESCE(SUM(tokens_input), 0) as promptTokens,
- COALESCE(SUM(tokens_output), 0) as completionTokens,
- COALESCE(SUM(tokens_cache_read), 0) as cacheReadTokens,
- COALESCE(SUM(tokens_cache_creation), 0) as cacheCreationTokens,
- COALESCE(SUM(tokens_reasoning), 0) as reasoningTokens
- FROM usage_history
- \${presetWhere}
- GROUP BY model, provider
- \`
- )
- .all(presetParams) as Array<Record<string, unknown>>;
-
- let presetTotalCost = 0;
- for (const row of presetModelRows) {
- presetTotalCost += computeUsageRowCost(
- row,
- pricingByProvider,
- normalizeModelName,
- computeCostFromPricing
- );
- }
-
- presetSummaries[presetRange] = {
- totalCost: roundCost(presetTotalCost),
- };
- }
-
- analytics.presetSummaries = presetSummaries;
- }
-
- return NextResponse.json(analytics);
- } catch (error) {
- console.error("Error computing analytics:", error);
- return NextResponse.json({ error: "Failed to compute analytics" }, { status: 500 });
- }
-}
-`;
-
-fs.writeFileSync("src/app/api/usage/analytics/route.ts", beforeGet + newGetFn, "utf8");
diff --git a/scripts/scratch/harvest_issues.py b/scripts/scratch/harvest_issues.py
deleted file mode 100644
index 649e75f511..0000000000
--- a/scripts/scratch/harvest_issues.py
+++ /dev/null
@@ -1,96 +0,0 @@
-import json
-import os
-import subprocess
-import re
-
-issues = [1845, 1833, 1826, 1814, 1788, 1786, 1765, 1764, 1737, 1736, 1735, 1731, 1718, 1716, 1679, 1594, 1591, 1590, 1589, 1588, 1587, 1586, 1584, 1529]
-
-os.makedirs('_ideia', exist_ok=True)
-
-def slugify(value):
- value = re.sub(r'\[Feature\]', '', value, flags=re.IGNORECASE)
- value = re.sub(r'[^\w\s-]', '', value).strip().lower()
- return re.sub(r'[-\s]+', '-', value)
-
-for num in issues:
- print(f"Processing #{num}...")
- try:
- res = subprocess.run(
- ['gh', 'issue', 'view', str(num), '--repo', 'diegosouzapw/OmniRoute', '--json', 'number,title,labels,body,comments,createdAt,author,assignees'],
- capture_output=True, text=True, check=True
- )
- data = json.loads(res.stdout)
-
- slug = slugify(data['title'])
- filename = f"_ideia/{data['number']}-{slug}.md"
-
- author = data['author']['login']
- created_at = data['createdAt']
- body = data['body']
- comments = data['comments']
-
- participants = set([author])
- comments_str = ""
- if comments:
- for c in comments:
- c_author = c['author']['login']
- participants.add(c_author)
- comments_str += f"**@{c_author}** ({c['createdAt']}):\n{c['body']}\n---\n"
- else:
- comments_str = "*No comments.*"
-
- participants_list = "\n".join([f"- @{p}" for p in participants])
-
- content = f"""# Feature: {data['title']}
-
-> GitHub Issue: #{data['number']} — opened by @{author} on {created_at}
-> Status: 📋 Cataloged | Priority: TBD
-
-## 📝 Original Request
-
-{body}
-
-## 💬 Community Discussion
-
-{comments_str}
-
-### Participants
-
-{participants_list}
-
-### Key Points
-
-- Needs detailed analysis
-
-## 🎯 Refined Feature Description
-
-Feature needs manual refinement and interpretation to fill logical gaps and outline high-level technical scope.
-
-### What it solves
-
-- TBD
-
-### How it should work (high level)
-
-1. TBD
-2. TBD
-
-### Affected areas
-
-- TBD
-
-## 📎 Attachments & References
-
-- Check issue body for references
-
-## 🔗 Related Ideas
-
-- None yet
-"""
- with open(filename, 'w', encoding='utf-8') as f:
- f.write(content)
-
- except Exception as e:
- print(f"Error processing {num}: {e}")
-
-print("Done.")
diff --git a/scripts/scratch/overlap.js b/scripts/scratch/overlap.js
deleted file mode 100644
index 93ac1df151..0000000000
--- a/scripts/scratch/overlap.js
+++ /dev/null
@@ -1,21 +0,0 @@
-import {
- APIKEY_PROVIDERS,
- SEARCH_PROVIDERS,
- AUDIO_ONLY_PROVIDERS,
- WEB_COOKIE_PROVIDERS,
-} from "./src/shared/constants/providers.ts";
-
-const apiKeys = Object.keys(APIKEY_PROVIDERS);
-console.log("Searching overlap in APIKEY_PROVIDERS:");
-console.log(
- "Search overlap:",
- Object.keys(SEARCH_PROVIDERS).filter((k) => apiKeys.includes(k))
-);
-console.log(
- "Audio overlap:",
- Object.keys(AUDIO_ONLY_PROVIDERS).filter((k) => apiKeys.includes(k))
-);
-console.log(
- "Web Cookie overlap:",
- Object.keys(WEB_COOKIE_PROVIDERS).filter((k) => apiKeys.includes(k))
-);
diff --git a/scripts/scratch/overlap.ts b/scripts/scratch/overlap.ts
deleted file mode 100644
index ceb10a0aad..0000000000
--- a/scripts/scratch/overlap.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { APIKEY_PROVIDERS, SEARCH_PROVIDERS } from "./src/shared/constants/providers.ts";
-
-const apiKeys = Object.keys(APIKEY_PROVIDERS);
-console.log(
- "Overlap:",
- Object.keys(SEARCH_PROVIDERS).filter((k) => apiKeys.includes(k))
-);
-console.log("Is perplexity-search in APIKEY?", "perplexity-search" in APIKEY_PROVIDERS);
diff --git a/scripts/scratch/pr_body.md b/scripts/scratch/pr_body.md
deleted file mode 100644
index 25326e6e60..0000000000
--- a/scripts/scratch/pr_body.md
+++ /dev/null
@@ -1,46 +0,0 @@
-### ✨ New Features
-
-- **feat(compression):** major upgrade to Caveman and RTK compression pipelines (#1876, #1889):
- - Add RTK tool-output compression, stacked Caveman + RTK pipelines, compression combo assignments, dashboard context pages, MCP management tools, and language-aware Caveman rule packs.
- - Expand RTK parity with a 39-filter catalog, RTK-style JSON DSL stages, inline verify/benchmark coverage, trust-gated custom filters, expanded command detection, and redacted raw-output recovery.
- - Expose rule intensities, track USD savings, unify config validation, and persist MCP savings.
- - Expand Caveman parity and MCP metadata compression.
-- **feat(provider):** update Jina AI model catalog to support Embeddings and Rerank natively (#1874 — thanks @backryun)
-- **feat(provider):** add NanoGPT image generation provider (#1899 — thanks @Aculeasis)
-- **feat(ui):** move proxy configuration to dedicated System → Proxy page (#1907 — thanks @oyi77)
-- **feat(ui):** add K/M/B/T cost shortener utility (#1902 — thanks @oyi77)
-- **feat(providers):** implement bulk paste for extra API keys (#1916 — thanks @0xtbug)
-- **feat(analytics):** usage history API key backfill + dark mode pricing (#1896 — thanks @Gi99lin)
-- **feat(logs):** show RTK and Caveman compression token savings accurately in request log UI (#1923 — thanks @emdash)
-
-### 🐛 Bug Fixes
-
-- **fix(providers):** allow local OpenAI-compatible endpoints (like Ollama) to be added without an API key (fixes #1893)
-- **fix(providers):** bypass AgentRouter unauthorized_client_error by spoofing Claude CLI headers via Anthropic endpoints (fixes #1921)
-- **fix(copilot):** emit compatible reasoning text deltas (#1919 — thanks @ivan-mezentsev)
-- **fix(api-manager):** show validation errors inline in modals, not behind (#1920 — thanks @andrewmunsell)
-- **fix(compression):** align seeded standard savings combo with stacked default, preserve stacked defaults, and secure metadata routes.
-- **fix(gemini-cli):** separate Cloud Code transport from Antigravity (#1869 — thanks @dhaern)
-- **fix(codex):** map prompt field to input array for Cursor compatibility (fixes #1872)
-- **fix(core):** align stream parameter default to false per strict OpenAI spec (fixes #1873)
-- **fix(ui):** restore Next.js CSP `unsafe-eval` in production `script-src` to fix unresponsive Onboarding button (fixes #1883)
-- **fix(proxy):** globally strip `prompt_cache_retention` in `BaseExecutor` to prevent upstream 400 errors from strict endpoints like droid/gemini-2-pro (fixes #1884)
-- **fix(ui):** include `isOpen` dependency in `EditConnectionModal` state sync to ensure `maxConcurrent` is properly hydrated when reopening the modal (fixes #1859)
-- **fix(security):** remediate 4 polynomial-redos CodeQL alerts in compression regexes by bounding repetitions and removing overlapping quantifiers
-- **fix(codex):** flatten Chat Completions tool format to Codex Responses format in `normalizeCodexTools` — prevents `Missing required parameter: tools[0].name` upstream errors (#1914 — thanks @tranduykhanh030)
-- **fix(proxy):** add proxy-aware execution context to image generation route — proxy settings are now correctly applied for image providers behind restricted networks (#1904 — thanks @Aculeasis)
-- **fix(translator):** inject `properties: {}` into zero-argument MCP tool schemas during Anthropic→OpenAI translation — prevents 400 errors from OpenAI strict schema validation (#1898 — thanks @bryceIT)
-- **fix(codex):** sanitize raw responses input (#1895 — thanks @dhaern)
-- **fix(combos):** align strategy contracts (#1892 — thanks @dhaern)
-- **fix(combos):** fix combo provider breaker profile handling (#1891 — thanks @rdself)
-- **fix(migrations):** duplicate-column no-op fix (#1886 — thanks @smartenok-ops)
-- **fix(auth):** per-connection OAuth refresh mutex (#1885 — thanks @smartenok-ops)
-- **fix(auth):** require dashboard management auth for compression preview
-
-### 📝 Documentation
-
-- **docs(compression):** document RTK+Caveman stacked savings ranges
-
-### 🏆 Release Attribution & Retroactive Credits
-
-- **@payne0420** (PR #1828 / #1839) — Implementation of the **Rate Limit Watchdog** and environment overrides. (This feature was manually backported to v3.7.8, causing the automatic GitHub Release notes to omit the author's credit).
diff --git a/scripts/scratch/query_db.js b/scripts/scratch/query_db.js
deleted file mode 100644
index 7f94c56e1c..0000000000
--- a/scripts/scratch/query_db.js
+++ /dev/null
@@ -1,10 +0,0 @@
-const Database = require("better-sqlite3");
-const db = new Database(process.env.HOME + "/.omniroute/storage.sqlite");
-console.log("=== provider_connections containing iflow ===");
-console.log(
- db
- .prepare(
- "SELECT id, provider_id, alias, account_id FROM provider_connections WHERE provider_id LIKE '%iflow%' OR alias LIKE '%iflow%' OR account_id LIKE '%iflow%'"
- )
- .all()
-);
diff --git a/scripts/scratch/refine_viable.py b/scripts/scratch/refine_viable.py
deleted file mode 100644
index abdf86ed5d..0000000000
--- a/scripts/scratch/refine_viable.py
+++ /dev/null
@@ -1,91 +0,0 @@
-import os
-
-viable_data = {
- 1718: {
- "title": "expose upstream error details in client-facing error responses",
- "solves": "Debugging upstream errors is difficult because they are hidden behind generic '[400] Error from provider' wrappers.",
- "how": "1. Modify `buildErrorBody` to accept `upstream_details`.\n2. In `BaseExecutor` or specific handlers, parse the raw upstream response on failure.\n3. Propagate the parsed body to the client response inside `upstream_details`.",
- "areas": "open-sse/executors/base.ts, open-sse/utils/errors.ts, src/app/api/v1/chat/completions/route.ts",
- "req_summary": "Expose the upstream error body (e.g. context_length_exceeded) directly in the error response under an `upstream_details` key, without breaking OpenAI compatibility.",
- "req_approach": "Modify the central error generation functions (like `buildErrorBody`) to optionally accept an `upstreamDetails` object. Update the request executors to pass the JSON parsed error from the upstream response into this new parameter when a request fails.",
- "req_files": "| File | Changes |\n|---|---|\n| `open-sse/utils/errors.ts` | Update `buildErrorBody` to include `upstream_details`. |\n| `open-sse/executors/base.ts` | Extract response body on failure and pass to error builder. |",
- "req_effort": "Low. A few files changed. No breaking changes."
- },
- 1731: {
- "title": "(combo): provider-level exhaustion tracking to skip same-provider targets",
- "solves": "Combo routing wastes significant time retrying multiple targets from the same provider when the entire provider is rate-limited or quota-exhausted.",
- "how": "1. Track 429 quota exhaustion errors at the provider level.\n2. In `combo.ts`, before attempting a target, check if its provider is currently marked as exhausted.\n3. If exhausted, skip the target and move to the next provider.",
- "areas": "open-sse/services/combo.ts, open-sse/services/accountFallback.ts",
- "req_summary": "Implement provider-level 429 exhaustion tracking in the combo router so it skips remaining targets of a provider if a 429 quota exhaustion occurs.",
- "req_approach": "Add a temporary exclusion set in `handleComboChat` that tracks providers that have returned a hard 429. Before evaluating the next target in the combo, check if its provider is in the exclusion set and skip it if true.",
- "req_files": "| File | Changes |\n|---|---|\n| `open-sse/services/combo.ts` | Add logic to track provider failures and skip matching targets. |\n| `open-sse/services/accountFallback.ts` | Properly bubble up the 429 status. |",
- "req_effort": "Medium. Needs careful state tracking across the combo loop. No breaking changes."
- },
- 1764: {
- "title": "Make installation script detect termux",
- "solves": "OmniRoute fails to start or install properly on Termux because `wreq-js` attempts to load a native `libgcc` arm64 module which is incompatible.",
- "how": "1. Update the `postinstall` script to check `process.env.PREFIX` for termux.\n2. If termux is detected, gracefully skip or patch the wreq-js installation/loading.",
- "areas": "scripts/postinstall.mjs, open-sse/executors/wreq.ts",
- "req_summary": "Detect termux environments during installation or runtime and gracefully handle the `wreq-js` native module failure, allowing the rest of OmniRoute to function.",
- "req_approach": "Modify `scripts/postinstall.mjs` or the wreq-js loader logic. If `process.env.PREFIX && process.env.PREFIX.includes('termux')` is true, avoid hard crashing on wreq-js load failures.",
- "req_files": "| File | Changes |\n|---|---|\n| `scripts/postinstall.mjs` | Add termux detection and warning. |\n| `open-sse/utils/env.ts` (or similar) | Graceful downgrade. |",
- "req_effort": "Low. Very localized fix."
- }
-}
-
-for root, _, files in os.walk("_ideia/viable"):
- for f in files:
- if not f.endswith(".md") or "requirements" in f: continue
- num = int(f.split('-')[0])
- if num in viable_data:
- path = os.path.join(root, f)
- with open(path, 'r') as file:
- content = file.read()
-
- d = viable_data[num]
-
- # replace TBDs
- content = content.replace("### What it solves\n\n- TBD", f"### What it solves\n\n- {d['solves']}")
- content = content.replace("### How it should work (high level)\n\n1. TBD\n2. TBD", f"### How it should work (high level)\n\n{d['how']}")
- content = content.replace("### Affected areas\n\n- TBD", f"### Affected areas\n\n- {d['areas']}")
- content = content.replace("Feature needs manual refinement and interpretation to fill logical gaps and outline high-level technical scope.", "Refined and scoped for implementation.")
-
- with open(path, 'w') as file:
- file.write(content)
-
- req_content = f"""# Requirements: {d['title']}
-
-> Feature Idea: [#{num}](./{f})
-> Research Date: 2026-05-01
-> Verdict: ✅ VIABLE
-
-## 🔍 Research Summary
-
-{d['req_summary']}
-
-## 📚 Reference Implementations
-
-| # | Repository | Stars | Last Updated | Approach | Relevance |
-| --- | ---------------- | ----- | ------------ | -------- | ------------ |
-| 1 | OmniRoute Source | - | 2026-05-01 | Internal | High |
-
-## 📐 Proposed Solution Architecture
-
-### Approach
-
-{d['req_approach']}
-
-### Modified Files
-
-{d['req_files']}
-
-## ⚙️ Implementation Effort
-
-- **Estimated complexity**: {d['req_effort']}
-- **Breaking changes**: No
-"""
- req_path = os.path.join(root, f.replace(".md", ".requirements.md"))
- with open(req_path, 'w') as req_file:
- req_file.write(req_content)
-
- print(f"Refined {num} and created requirements.")
diff --git a/scripts/scratch/test-cherry.js b/scripts/scratch/test-cherry.js
deleted file mode 100644
index 07fb46df26..0000000000
--- a/scripts/scratch/test-cherry.js
+++ /dev/null
@@ -1,2 +0,0 @@
-const { convertOpenAIContentToParts } = require("./open-sse/translator/helpers/geminiHelper.ts");
-// since it's typescript/ESM, we might need a ts-node or vitest
diff --git a/scripts/scratch/test-executor.ts b/scripts/scratch/test-executor.ts
deleted file mode 100644
index 754b6f5414..0000000000
--- a/scripts/scratch/test-executor.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-import { QoderExecutor } from "./open-sse/executors/qoder.ts";
-import fs from "fs";
-import os from "os";
-
-async function run() {
- const credsPath = os.homedir() + "/.qwen/oauth_creds.json";
- const creds = JSON.parse(fs.readFileSync(credsPath, "utf8"));
-
- const executor = new QoderExecutor();
- const result = await executor.execute({
- model: "coder-model",
- body: {
- messages: [{ role: "user", content: "hello test" }],
- stream: true,
- max_tokens: 10,
- },
- credentials: {
- accessToken: creds.access_token,
- resourceUrl: creds.resource_url,
- },
- signal: new AbortController().signal,
- });
-
- console.log("Status:", result.response.status);
-
- if (result.response.body) {
- // If it's a web stream, readable stream
- const reader = result.response.body.getReader();
- const decoder = new TextDecoder("utf-8");
- while (true) {
- const { done, value } = await reader.read();
- if (done) break;
- console.log(decoder.decode(value));
- }
- }
-}
-
-run().catch(console.error);
diff --git a/scripts/scratch/test-math-regex.js b/scripts/scratch/test-math-regex.js
deleted file mode 100644
index e42a210ec8..0000000000
--- a/scripts/scratch/test-math-regex.js
+++ /dev/null
@@ -1,3 +0,0 @@
-const re = /\$\$[^$]*(?:\$(?!\$)[^$]*)*\$\$/g;
-const txt = "some text $$ a + b = c $$ more text $$ x + $y$ = z $$ end";
-console.log(txt.match(re));
diff --git a/scripts/scratch/test-migrations.ts b/scripts/scratch/test-migrations.ts
deleted file mode 100644
index f21ca16ca8..0000000000
--- a/scripts/scratch/test-migrations.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import Database from "better-sqlite3";
-import { runMigrations, getMigrationStatus } from "../../src/lib/db/migrationRunner.js";
-
-const db = new Database("/tmp/test-migrations.sqlite");
-db.exec(
- "CREATE TABLE _omniroute_migrations (version TEXT PRIMARY KEY, name TEXT NOT NULL, applied_at TEXT NOT NULL DEFAULT (datetime('now')))"
-);
-
-const fakeApplied = [
- "001",
- "002",
- "003",
- "004",
- "005",
- "006",
- "007",
- "008",
- "009",
- "010",
- "011",
- "012",
- "013",
- "014",
- "015",
- "016",
- "017",
- "018",
- "019",
- "020",
- "021",
-];
-for (const v of fakeApplied) {
- db.prepare("INSERT INTO _omniroute_migrations (version, name) VALUES (?, ?)").run(v, "fake_" + v);
-}
-db.prepare("INSERT INTO _omniroute_migrations (version, name) VALUES (?, ?)").run(
- "026",
- "call_logs_cache_source"
-);
-db.prepare("INSERT INTO _omniroute_migrations (version, name) VALUES (?, ?)").run(
- "029",
- "provider_connection_max_concurrent"
-);
-
-console.log(
- "Status before:",
- getMigrationStatus(db).pending.map((p) => p.version)
-);
-try {
- runMigrations(db, { isNewDb: false });
-} catch (e: any) {
- console.error("Error:", e.message);
-}
-console.log(
- "Status after:",
- getMigrationStatus(db).pending.map((p) => p.version)
-);
diff --git a/scripts/scratch/test-regex.js b/scripts/scratch/test-regex.js
deleted file mode 100644
index deba62356e..0000000000
--- a/scripts/scratch/test-regex.js
+++ /dev/null
@@ -1,5 +0,0 @@
-const text = "hello world. this is a test\n\nnew line. another.";
-const re1 = /(^|[.!?][ \t]+|\n+[ \t]*)([a-z])/g;
-const re2 = /(^|[.!?]\s+)([a-z])/gm;
-console.log(text.replace(re1, (m, p, c) => p + c.toUpperCase()));
-console.log(text.replace(re2, (m, p, c) => p + c.toUpperCase()));
diff --git a/scripts/scratch/test-regex2.js b/scripts/scratch/test-regex2.js
deleted file mode 100644
index c6eeb518a6..0000000000
--- a/scripts/scratch/test-regex2.js
+++ /dev/null
@@ -1,5 +0,0 @@
-const text = "hello\n world";
-const re1 = /(^|[.!?][ \t]+|\n+[ \t]*)([a-z])/g;
-const re3 = /(^|[.!?]\s+|^\s+)([a-z])/gm;
-console.log(text.replace(re1, (m, p, c) => p + c.toUpperCase()));
-console.log(text.replace(re3, (m, p, c) => p + c.toUpperCase()));
diff --git a/scripts/scratch/test_gemini.mjs b/scripts/scratch/test_gemini.mjs
deleted file mode 100644
index f875cf3316..0000000000
--- a/scripts/scratch/test_gemini.mjs
+++ /dev/null
@@ -1,9 +0,0 @@
-import { convertOpenAIContentToParts } from "./open-sse/translator/helpers/geminiHelper.ts";
-
-const cherryMsg = [
- { type: "text", text: "What runs on this?" },
- { type: "file", file: { data: "ABCDEFG", type: "application/pdf" } },
- { type: "file", file_url: { url: "data:application/pdf;base64,ABCDEFG" } },
-];
-
-console.log(convertOpenAIContentToParts(cherryMsg));
diff --git a/scripts/scratch/update_ui.cjs b/scripts/scratch/update_ui.cjs
deleted file mode 100644
index 98e083adca..0000000000
--- a/scripts/scratch/update_ui.cjs
+++ /dev/null
@@ -1,170 +0,0 @@
-const fs = require('fs');
-
-const path = 'src/app/(dashboard)/dashboard/providers/[id]/page.tsx';
-let content = fs.readFileSync(path, 'utf8');
-
-// 1. Add ModelRowProps fields
-content = content.replace(
- ' togglingHidden?: boolean;\n}',
- ' togglingHidden?: boolean;\n onTestModel?: (modelId: string, fullModel: string) => Promise<void>;\n testStatus?: "ok" | "error" | null;\n testingModel?: boolean;\n}'
-);
-
-// 2. Add PassthroughModelRowProps fields
-content = content.replace(
- ' togglingHidden?: boolean;\n}',
- ' togglingHidden?: boolean;\n onTestModel?: (modelId: string, fullModel: string) => Promise<void>;\n testStatus?: "ok" | "error" | null;\n testingModel?: boolean;\n}'
-);
-
-// 3. Add PassthroughModelsSectionProps fields
-content = content.replace(
- ' togglingModelId?: string | null;\n}',
- ' togglingModelId?: string | null;\n onTestModel?: (modelId: string, fullModel: string) => Promise<void>;\n modelTestStatus?: Record<string, "ok" | "error" | null>;\n testingModelId?: string | null;\n}'
-);
-
-// 4. Add CompatibleModelsSectionProps fields
-content = content.replace(
- ' togglingModelId?: string | null;\n}',
- ' togglingModelId?: string | null;\n onTestModel?: (modelId: string, fullModel: string) => Promise<void>;\n modelTestStatus?: Record<string, "ok" | "error" | null>;\n testingModelId?: string | null;\n}'
-);
-
-// 5. Update ModelRow
-content = content.replace(
- ' compatDisabled,\n onToggleHidden,\n togglingHidden,\n}: ModelRowProps) {',
- ' compatDisabled,\n onToggleHidden,\n togglingHidden,\n onTestModel,\n testStatus,\n testingModel,\n}: ModelRowProps) {'
-);
-content = content.replace(
- ' <div className="flex shrink-0 items-center gap-1">',
- ` <div className="flex shrink-0 items-center gap-1">
- {onTestModel && (
- <button
- onClick={() => onTestModel(model.id, fullModel)}
- disabled={testingModel}
- className={\`rounded p-0.5 hover:bg-sidebar transition-colors disabled:opacity-40 disabled:cursor-not-allowed \${testStatus === "ok" ? "text-green-500" : testStatus === "error" ? "text-red-500" : "text-text-muted hover:text-primary"}\`}
- title={testingModel ? t("testingModel", "Testing...") : testStatus === "ok" ? "OK" : testStatus === "error" ? "Error" : t("testModel", "Test Model")}
- >
- {testingModel ? (
- <span className="material-symbols-outlined text-sm animate-spin">progress_activity</span>
- ) : testStatus === "ok" ? (
- <span className="material-symbols-outlined text-sm">check_circle</span>
- ) : testStatus === "error" ? (
- <span className="material-symbols-outlined text-sm">error</span>
- ) : (
- <span className="material-symbols-outlined text-sm">play_circle</span>
- )}
- </button>
- )}`
-);
-
-// 6. Update PassthroughModelRow
-content = content.replace(
- ' compatDisabled,\n onToggleHidden,\n togglingHidden,\n}: PassthroughModelRowProps) {',
- ' compatDisabled,\n onToggleHidden,\n togglingHidden,\n onTestModel,\n testStatus,\n testingModel,\n}: PassthroughModelRowProps) {'
-);
-content = content.replace(
- ' <div className="flex shrink-0 items-center gap-1 self-start">',
- ` <div className="flex shrink-0 items-center gap-1 self-start">
- {onTestModel && (
- <button
- onClick={() => onTestModel(modelId, fullModel)}
- disabled={testingModel}
- className={\`rounded p-0.5 hover:bg-sidebar transition-colors disabled:opacity-40 disabled:cursor-not-allowed \${testStatus === "ok" ? "text-green-500" : testStatus === "error" ? "text-red-500" : "text-text-muted hover:text-primary"}\`}
- title={testingModel ? t("testingModel", "Testing...") : testStatus === "ok" ? "OK" : testStatus === "error" ? "Error" : t("testModel", "Test Model")}
- >
- {testingModel ? (
- <span className="material-symbols-outlined text-sm animate-spin">progress_activity</span>
- ) : testStatus === "ok" ? (
- <span className="material-symbols-outlined text-sm">check_circle</span>
- ) : testStatus === "error" ? (
- <span className="material-symbols-outlined text-sm">error</span>
- ) : (
- <span className="material-symbols-outlined text-sm">play_circle</span>
- )}
- </button>
- )}`
-);
-
-// 7. Update PassthroughModelsSection component passing props down
-content = content.replace(
- ' togglingModelId,\n}: PassthroughModelsSectionProps)',
- ' togglingModelId,\n onTestModel,\n modelTestStatus,\n testingModelId,\n}: PassthroughModelsSectionProps)'
-);
-content = content.replace(
- ' saveModelCompatFlags={saveModelCompatFlags}\n compatDisabled={compatSavingModelId === cm.id}',
- ' saveModelCompatFlags={saveModelCompatFlags}\n compatDisabled={compatSavingModelId === cm.id}\n onTestModel={onTestModel}\n testStatus={modelTestStatus?.[cm.id] || null}\n testingModel={testingModelId === cm.id}'
-);
-content = content.replace(
- ' compatDisabled={compatSavingModelId === alias}\n onToggleHidden={onToggleHidden}',
- ' compatDisabled={compatSavingModelId === alias}\n onToggleHidden={onToggleHidden}\n onTestModel={onTestModel}\n testStatus={modelTestStatus?.[alias] || null}\n testingModel={testingModelId === alias}'
-);
-
-// 8. Update CompatibleModelsSection component passing props down
-content = content.replace(
- ' togglingModelId,\n}: CompatibleModelsSectionProps) {',
- ' togglingModelId,\n onTestModel,\n modelTestStatus,\n testingModelId,\n}: CompatibleModelsSectionProps) {'
-);
-content = content.replace(
- ' saveModelCompatFlags={saveModelCompatFlags}\n compatDisabled={compatSavingModelId === cm.id}',
- ' saveModelCompatFlags={saveModelCompatFlags}\n compatDisabled={compatSavingModelId === cm.id}\n onTestModel={onTestModel}\n testStatus={modelTestStatus?.[cm.id] || null}\n testingModel={testingModelId === cm.id}'
-);
-content = content.replace(
- ' compatDisabled={compatSavingModelId === model.id}\n onToggleHidden={(modelId, hidden)',
- ' compatDisabled={compatSavingModelId === model.id}\n onTestModel={onTestModel}\n testStatus={modelTestStatus?.[model.id] || null}\n testingModel={testingModelId === model.id}\n onToggleHidden={(modelId, hidden)'
-);
-
-// 9. Update ProviderDetailPage
-content = content.replace(
- ' const [togglingModelId, setTogglingModelId] = useState<string | null>(null);',
- ' const [togglingModelId, setTogglingModelId] = useState<string | null>(null);\n const [testingModelId, setTestingModelId] = useState<string | null>(null);\n const [modelTestStatus, setModelTestStatus] = useState<Record<string, "ok" | "error">>({});'
-);
-
-// Add the onTestModel function
-content = content.replace(
- ' const handleSetAlias = async (modelId, alias, providerAliasOverride = providerAlias) => {',
- ` const onTestModel = async (modelId: string, fullModel: string) => {
- setTestingModelId(modelId);
- setModelTestStatus(prev => ({ ...prev, [modelId]: undefined }));
- try {
- const res = await fetch("/api/models/test", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ providerId: selectedConnection?.provider || providerNode?.id || providerId, modelId: fullModel })
- });
- const data = await res.json();
- if (res.ok && data.status === "ok") {
- notify.success(providerText(t, "testModelSuccess", \`Model \${modelId} is working. Latency: \${data.latencyMs}ms\`, { modelId, latencyMs: data.latencyMs }));
- setModelTestStatus(prev => ({ ...prev, [modelId]: "ok" }));
- } else {
- notify.error(data.error || "Model test failed");
- setModelTestStatus(prev => ({ ...prev, [modelId]: "error" }));
- }
- } catch (err) {
- notify.error("Network error testing model");
- setModelTestStatus(prev => ({ ...prev, [modelId]: "error" }));
- } finally {
- setTestingModelId(null);
- }
- };
-
- const handleSetAlias = async (modelId, alias, providerAliasOverride = providerAlias) => {`
-);
-
-// Pass to PassthroughModelsSection in ProviderDetailPage
-content = content.replace(
- ' togglingModelId={togglingModelId}\n />',
- ' togglingModelId={togglingModelId}\n onTestModel={onTestModel}\n modelTestStatus={modelTestStatus}\n testingModelId={testingModelId}\n />'
-);
-
-// Pass to CompatibleModelsSection in ProviderDetailPage
-content = content.replace(
- ' togglingModelId={togglingModelId}\n />',
- ' togglingModelId={togglingModelId}\n onTestModel={onTestModel}\n modelTestStatus={modelTestStatus}\n testingModelId={testingModelId}\n />'
-);
-
-// Pass to ModelRow in ProviderDetailPage (fallback/normal models list)
-content = content.replace(
- ' togglingHidden={togglingModelId === model.id}\n />',
- ' togglingHidden={togglingModelId === model.id}\n onTestModel={onTestModel}\n testStatus={modelTestStatus[model.id] || null}\n testingModel={testingModelId === model.id}\n />'
-);
-
-fs.writeFileSync(path, content);
-console.log("Successfully updated page.tsx");