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

Merge release/v3.7.7 into compression phase 4

Antigravity Assistant7b21e0460402
diff --cc open-sse/services/compression/strategySelector.ts
index 7d4634a58a,c0092355a3..4e23bdcd96
--- a/open-sse/services/compression/strategySelector.ts
+++ b/open-sse/services/compression/strategySelector.ts
@@@ -69,43 -66,10 +68,43 @@@ export function applyCompression
}
const aggressiveConfig = options?.config?.aggressive;
const result = compressAggressive(messages, aggressiveConfig);
+ const compressedBody = { ...body, messages: result.messages };
return {
- body: { ...body, messages: result.messages },
+ body: compressedBody,
compressed: result.stats.savingsPercent > 0,
- stats: result.stats,
+ stats: createCompressionStats(
+ body,
+ compressedBody,
+ mode,
+ ["aggressive"],
+ result.stats.rulesApplied,
+ result.stats.durationMs
+ ),
+ };
+ }
+ if (mode === "ultra") {
+ const messages = (body.messages ?? []) as Array<{
+ role: string;
+ content?: string | unknown[];
+ [key: string]: unknown;
+ }>;
+ if (!Array.isArray(messages) || messages.length === 0) {
+ return { body, compressed: false, stats: null };
+ }
+ const ultraConfig = options?.config?.ultra;
- const result = await ultraCompress(messages, ultraConfig ?? {});
++ const result = ultraCompress(messages, ultraConfig ?? {});
+ const compressedBody = { ...body, messages: result.messages };
+ return {
+ body: compressedBody,
+ compressed: result.stats.savingsPercent > 0,
+ stats: createCompressionStats(
+ body,
+ compressedBody,
+ mode,
+ ["ultra"],
+ result.stats.rulesApplied,
+ result.stats.durationMs
+ ),
};
}
return { body, compressed: false, stats: null };
diff --cc open-sse/services/compression/types.ts
index 95b82b6f35,64007a0b5c..f019f62bc6
--- a/open-sse/services/compression/types.ts
+++ b/open-sse/services/compression/types.ts
@@@ -5,13 -5,10 +5,11 @@@
* Phase 1: 'off' and 'lite' modes.
* Phase 2: 'standard' mode (caveman engine).
* Phase 3: 'aggressive' mode (summarization + tool compression + aging).
+ * Phase 4: 'ultra' mode (heuristic token pruning + optional SLM tier).
*/
- /** Compression mode levels */
export type CompressionMode = "off" | "lite" | "standard" | "aggressive" | "ultra";
- /** A single caveman compression rule (Phase 2) */
export interface CavemanRule {
name: string;
pattern: RegExp;
@@@ -29,7 -25,17 +26,18 @@@ export interface CavemanConfig
preservePatterns: string[];
}
- /** Per-request compression statistics */
+ export interface CompressionConfig {
+ enabled: boolean;
+ defaultMode: CompressionMode;
+ autoTriggerTokens: number;
+ cacheMinutes: number;
+ preserveSystemPrompt: boolean;
+ comboOverrides: Record<string, CompressionMode>;
+ cavemanConfig?: CavemanConfig;
+ aggressive?: AggressiveConfig;
++ ultra?: UltraConfig;
+ }
+
export interface CompressionStats {
originalTokens: number;
compressedTokens: number;
diff --cc open-sse/services/compression/ultra.ts
index d24ee37302,0000000000..0c1dd8d219
mode 100644,000000..100644
--- a/open-sse/services/compression/ultra.ts
+++ b/open-sse/services/compression/ultra.ts
@@@ -1,89 -1,0 +1,95 @@@
+import { pruneByScore } from "./ultraHeuristic.ts";
++import { DEFAULT_ULTRA_CONFIG } from "./types.ts";
+import type { UltraConfig, CompressionStats, CompressionMode } from "./types.ts";
+
+const COMPRESSED_PREFIX = "[COMPRESSED:";
+
+export interface SLMInterface {
+ compress(text: string, rate: number): Promise<string>;
+}
+
+export function createSLMStub(): SLMInterface {
+ return {
+ async compress(text: string, rate: number): Promise<string> {
+ return pruneByScore(text, rate);
+ },
+ };
+}
+
+export interface UltraCompressResult {
+ messages: Array<{ role: string; content?: string | unknown[]; [key: string]: unknown }>;
+ stats: CompressionStats;
+}
+
+type Message = { role: string; content?: string | unknown[]; [key: string]: unknown };
+
+function extractText(content: string | unknown[] | undefined): string {
+ if (!content) return "";
+ if (typeof content === "string") return content;
+ return (content as Array<{ type?: string; text?: string }>)
+ .filter((b) => b.type === "text" && b.text)
+ .map((b) => b.text as string)
+ .join("\n");
+}
+
+function applyTextToContent(
+ original: string | unknown[] | undefined,
+ compressed: string
+): string | unknown[] {
+ if (!original || typeof original === "string") return compressed;
+ return (original as Array<{ type?: string; text?: string; [k: string]: unknown }>).map((b) =>
+ b.type === "text" ? { ...b, text: compressed } : b
+ );
+}
+
- export async function ultraCompress(
++export function ultraCompress(
+ messages: Message[],
- config: UltraConfig
- ): Promise<UltraCompressResult> {
++ config: Partial<UltraConfig> = {}
++): UltraCompressResult {
+ const start = Date.now();
- const { compressionRate, minScoreThreshold } = config;
++ const effectiveConfig: UltraConfig = {
++ ...DEFAULT_ULTRA_CONFIG,
++ ...config,
++ };
++ const { compressionRate, minScoreThreshold, maxTokensPerMessage } = effectiveConfig;
+
+ let originalChars = 0;
+ let compressedChars = 0;
+
- const compressed = await Promise.all(
- messages.map(async (msg) => {
- const text = extractText(msg.content);
- if (!text) return msg;
- if (text.startsWith(COMPRESSED_PREFIX)) return msg;
++ const compressed = messages.map((msg) => {
++ const text = extractText(msg.content);
++ if (!text) return msg;
++ if (text.startsWith(COMPRESSED_PREFIX)) return msg;
++ if (maxTokensPerMessage > 0 && Math.ceil(text.length / 4) <= maxTokensPerMessage) {
++ return msg;
++ }
+
- originalChars += text.length;
- const pruned = pruneByScore(text, compressionRate, minScoreThreshold);
- compressedChars += pruned.length;
++ originalChars += text.length;
++ const pruned = pruneByScore(text, compressionRate, minScoreThreshold);
++ compressedChars += pruned.length;
+
- return {
- ...msg,
- content: applyTextToContent(msg.content, pruned),
- };
- })
- );
++ return {
++ ...msg,
++ content: applyTextToContent(msg.content, pruned),
++ };
++ });
+
+ const originalTokens = Math.ceil(originalChars / 4);
+ const compressedTokens = Math.ceil(compressedChars / 4);
+ const savingsPercent =
+ originalTokens > 0
+ ? Math.round(((originalTokens - compressedTokens) / originalTokens) * 100 * 10) / 10
+ : 0;
+
+ const stats: CompressionStats = {
+ originalTokens,
+ compressedTokens,
+ savingsPercent,
+ techniquesUsed: ["ultra-heuristic-pruning"],
+ mode: "ultra" as CompressionMode,
+ timestamp: Date.now(),
+ durationMs: Date.now() - start,
+ };
+
+ return { messages: compressed, stats };
+}
diff --cc scripts/scratch/fix_route.ts
index 0000000000,61df5e3b2f..186ae89e1d
mode 000000,100644..100644
--- a/scripts/scratch/fix_route.ts
+++ b/scripts/scratch/fix_route.ts
@@@ -1,0 -1,708 +1,708 @@@
+ 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
++ 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,
++ 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 --cc src/app/(dashboard)/dashboard/settings/components/CompressionSettingsTab.tsx
index 4618708e2c,4618708e2c..d6f4df413a
--- a/src/app/(dashboard)/dashboard/settings/components/CompressionSettingsTab.tsx
+++ b/src/app/(dashboard)/dashboard/settings/components/CompressionSettingsTab.tsx
@@@ -33,6 -33,6 +33,15 @@@ interface AggressiveConfig
minSavingsThreshold: number;
}
++interface UltraConfig {
++ enabled: boolean;
++ compressionRate: number;
++ minScoreThreshold: number;
++ slmFallbackToAggressive: boolean;
++ modelPath?: string;
++ maxTokensPerMessage: number;
++}
++
interface CompressionConfig {
enabled: boolean;
defaultMode: CompressionMode;
@@@ -42,6 -42,6 +51,7 @@@
comboOverrides: Record<string, CompressionMode>;
cavemanConfig?: CavemanConfig;
aggressive?: AggressiveConfig;
++ ultra?: UltraConfig;
}
const MODES: { value: CompressionMode; labelKey: string; descKey: string; icon: string }[] = [
@@@ -69,6 -69,6 +79,12 @@@
descKey: "compressionModeAggressiveDesc",
icon: "bolt",
},
++ {
++ value: "ultra",
++ labelKey: "compressionModeUltra",
++ descKey: "compressionModeUltraDesc",
++ icon: "filter_alt",
++ },
];
const ROLE_OPTIONS: { value: "user" | "assistant" | "system"; labelKey: string }[] = [
@@@ -138,6 -138,6 +154,13 @@@ export default function CompressionSett
maxTokensPerMessage: 2048,
minSavingsThreshold: 0.05,
},
++ ultra: {
++ enabled: false,
++ compressionRate: 0.5,
++ minScoreThreshold: 0.3,
++ slmFallbackToAggressive: true,
++ maxTokensPerMessage: 0,
++ },
});
const [saving, setSaving] = useState(false);
const [loading, setLoading] = useState(true);
@@@ -249,7 -249,7 +272,7 @@@
{config.enabled && (
<div className="space-y-3">
<h4 className="text-sm font-medium text-text-main">{t("compressionMode")}</h4>
-- <div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
++ <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-5 gap-2">
{MODES.map((m) => (
<button
key={m.value}
@@@ -610,6 -610,6 +633,141 @@@
</div>
</div>
)}
++
++ {config.enabled && config.defaultMode === "ultra" && config.ultra && (
++ <div className="space-y-3 pt-4 border-t border-border/30">
++ <div>
++ <h4 className="text-sm font-medium text-text-main">{t("compressionUltraConfig")}</h4>
++ <p className="text-xs text-text-muted mt-0.5">{t("compressionUltraConfigDesc")}</p>
++ </div>
++
++ <label className="flex items-center justify-between">
++ <span className="text-sm text-text-muted">{t("enabled")}</span>
++ <button
++ onClick={() =>
++ save({
++ ultra: {
++ ...config.ultra!,
++ enabled: !config.ultra!.enabled,
++ },
++ })
++ }
++ className={`relative w-10 h-5 rounded-full transition-colors ${
++ config.ultra.enabled ? "bg-green-500" : "bg-border"
++ }`}
++ >
++ <span
++ className={`absolute top-0.5 w-4 h-4 rounded-full bg-white transition-transform ${
++ config.ultra.enabled ? "left-5" : "left-0.5"
++ }`}
++ />
++ </button>
++ </label>
++
++ <label className="flex items-center justify-between">
++ <span className="text-sm text-text-muted">{t("compressionUltraRate")}</span>
++ <input
++ type="number"
++ min={0}
++ max={1}
++ step={0.05}
++ value={config.ultra.compressionRate}
++ onChange={(e) =>
++ save({
++ ultra: {
++ ...config.ultra!,
++ compressionRate: parseFloat(e.target.value) || 0,
++ },
++ })
++ }
++ className="w-24 px-2 py-1 text-sm rounded border border-border bg-surface text-text-main"
++ />
++ </label>
++
++ <label className="flex items-center justify-between">
++ <span className="text-sm text-text-muted">{t("compressionUltraMinScore")}</span>
++ <input
++ type="number"
++ min={0}
++ max={1}
++ step={0.05}
++ value={config.ultra.minScoreThreshold}
++ onChange={(e) =>
++ save({
++ ultra: {
++ ...config.ultra!,
++ minScoreThreshold: parseFloat(e.target.value) || 0,
++ },
++ })
++ }
++ className="w-24 px-2 py-1 text-sm rounded border border-border bg-surface text-text-main"
++ />
++ </label>
++
++ <label className="flex items-center justify-between">
++ <span className="text-sm text-text-muted">{t("compressionMaxTokensPerMessage")}</span>
++ <div className="flex items-center gap-2">
++ <input
++ type="number"
++ min={0}
++ max={32768}
++ value={config.ultra.maxTokensPerMessage}
++ onChange={(e) =>
++ save({
++ ultra: {
++ ...config.ultra!,
++ maxTokensPerMessage: parseInt(e.target.value) || 0,
++ },
++ })
++ }
++ className="w-24 px-2 py-1 text-sm rounded border border-border bg-surface text-text-main"
++ />
++ <span className="text-xs text-text-muted">{t("tokens")}</span>
++ </div>
++ </label>
++
++ <label className="flex items-center justify-between">
++ <span className="text-sm text-text-muted">{t("compressionUltraSlmFallback")}</span>
++ <button
++ onClick={() =>
++ save({
++ ultra: {
++ ...config.ultra!,
++ slmFallbackToAggressive: !config.ultra!.slmFallbackToAggressive,
++ },
++ })
++ }
++ className={`relative w-10 h-5 rounded-full transition-colors ${
++ config.ultra.slmFallbackToAggressive ? "bg-green-500" : "bg-border"
++ }`}
++ >
++ <span
++ className={`absolute top-0.5 w-4 h-4 rounded-full bg-white transition-transform ${
++ config.ultra.slmFallbackToAggressive ? "left-5" : "left-0.5"
++ }`}
++ />
++ </button>
++ </label>
++
++ <label className="block space-y-1">
++ <span className="text-sm text-text-muted">{t("compressionUltraModelPath")}</span>
++ <input
++ type="text"
++ value={config.ultra.modelPath ?? ""}
++ onChange={(e) =>
++ save({
++ ultra: {
++ ...config.ultra!,
++ modelPath: e.target.value.trim() || undefined,
++ },
++ })
++ }
++ placeholder="/path/to/model.onnx"
++ className="w-full px-2 py-1 text-sm rounded border border-border bg-surface text-text-main font-mono"
++ />
++ </label>
++ </div>
++ )}
</div>
</Card>
);
diff --cc src/app/api/settings/compression/route.ts
index da40c7028f,aac876c355..4262eb5019
--- a/src/app/api/settings/compression/route.ts
+++ b/src/app/api/settings/compression/route.ts
@@@ -36,26 -39,31 +39,43 @@@ const aggressiveConfigSchema =
maxTokensPerMessage: z.number().int().min(256).max(32768).optional(),
minSavingsThreshold: z.number().min(0).max(1).optional(),
})
- .optional();
+ .strict();
+
++const ultraConfigSchema = z
++ .object({
++ enabled: z.boolean().optional(),
++ compressionRate: z.number().min(0).max(1).optional(),
++ minScoreThreshold: z.number().min(0).max(1).optional(),
++ slmFallbackToAggressive: z.boolean().optional(),
++ modelPath: z.string().trim().min(1).optional(),
++ maxTokensPerMessage: z.number().int().min(0).max(32768).optional(),
++ })
++ .strict();
++
+ const compressionSettingsUpdateSchema = z
+ .object({
+ enabled: z.boolean().optional(),
+ defaultMode: compressionModeSchema.optional(),
+ autoTriggerTokens: z.number().int().min(0).optional(),
+ cacheMinutes: z.number().int().min(1).max(60).optional(),
+ preserveSystemPrompt: z.boolean().optional(),
+ comboOverrides: z.record(z.string(), compressionModeSchema).optional(),
+ cavemanConfig: cavemanConfigSchema.optional(),
+ aggressive: aggressiveConfigSchema.optional(),
++ ultra: ultraConfigSchema.optional(),
+ })
+ .strict();
- const updateCompressionSchema = z.object({
- enabled: z.boolean().optional(),
- defaultMode: z.enum(compressionModeValues).optional(),
- autoTriggerTokens: z.number().min(0).optional(),
- cacheMinutes: z.number().min(0).optional(),
- preserveSystemPrompt: z.boolean().optional(),
- comboOverrides: z.record(z.string(), z.enum(compressionModeValues)).optional(),
- cavemanConfig: cavemanConfigSchema.optional(),
- aggressive: aggressiveConfigSchema,
- });
+ export async function GET(request: NextRequest) {
+ if (!(await isAuthenticated(request))) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
- export async function GET() {
try {
- const config = getCompressionSettings();
- return NextResponse.json(config);
+ const settings = await getCompressionSettings();
+ return NextResponse.json(settings);
} catch (error) {
- console.error("Error reading compression config:", error);
- return NextResponse.json({ error: "Failed to read compression config" }, { status: 500 });
+ return NextResponse.json({ error: String(error) }, { status: 500 });
}
}
diff --cc src/app/api/usage/analytics/route.ts
index 57b2aeb69c,2057c7bf43..f696050a24
--- a/src/app/api/usage/analytics/route.ts
+++ b/src/app/api/usage/analytics/route.ts
@@@ -36,79 -126,718 +126,718 @@@ export async function GET(request: Requ
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");
- // Cap history load to last 365 days — the heatmap never looks beyond that,
- // and all named ranges (1d/7d/30d/90d/ytd) fall within this window.
- const heatmapSince = new Date();
- heatmapSince.setDate(heatmapSince.getDate() - 365);
- const db = await getUsageDb(heatmapSince.toISOString());
- const history = db.data.history || [];
+ const db = getDbInstance();
- // Build connection map for account names
- const { getProviderConnections } = await import("@/lib/localDb");
- const connectionMap: Record<string, string> = {};
+ // ── Enrich entries with missing apiKeyName ──────────────────────────
try {
- const connections = await getProviderConnections();
- for (const connRaw of connections as unknown[]) {
- const conn =
- connRaw && typeof connRaw === "object" && !Array.isArray(connRaw)
- ? (connRaw as Record<string, unknown>)
- : {};
- const connectionId =
- typeof conn.id === "string" && conn.id.trim().length > 0 ? conn.id : null;
- if (!connectionId) continue;
-
- const name =
- (typeof conn.name === "string" && conn.name.trim()) ||
- (typeof conn.email === "string" && conn.email.trim()) ||
- connectionId;
- connectionMap[connectionId] = name;
+ // 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
++ 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 {
- /* ignore */
+ } catch (e) {
+ console.error("Failed to backfill missing api_key_name:", e);
}
- const analytics: any = await computeAnalytics(history, range, connectionMap);
+ const conditions = [];
+ const params: Record<string, string> = {};
- // T01: fallback transparency metrics from call_logs (requested_model vs routed model).
- try {
- const db = getDbInstance();
- const sinceIso = getRangeStartIso(range);
- const whereClause = sinceIso ? "WHERE timestamp >= @since" : "";
- const row = db
- .prepare(
- `
+ 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
- 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
+ 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)
)
- .get(sinceIso ? { since: sinceIso } : {}) as
- | { total?: number; with_requested?: number; fallbacks?: number }
- | undefined;
-
- const total = Number(row?.total || 0);
- const withRequested = Number(row?.with_requested || 0);
- const fallbackCount = Number(row?.fallbacks || 0);
-
- analytics.summary.fallbackCount = fallbackCount;
- analytics.summary.fallbackRatePct =
- withRequested > 0 ? Number(((fallbackCount / withRequested) * 100).toFixed(2)) : 0;
- analytics.summary.requestedModelCoveragePct =
- total > 0 ? Number(((withRequested / total) * 100).toFixed(2)) : 0;
- } catch {
- analytics.summary.fallbackCount = 0;
- analytics.summary.fallbackRatePct = 0;
- analytics.summary.requestedModelCoveragePct = 0;
+ 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);
diff --cc src/i18n/messages/en.json
index eeb72a2047,1810fbc73a..d5e1aae288
--- a/src/i18n/messages/en.json
+++ b/src/i18n/messages/en.json
@@@ -2476,8 -3660,8 +3660,16 @@@
"compressionModeStandardDesc": "Rule-based compression with 30+ patterns, preserves code blocks and URLs",
"compressionModeAggressive": "Aggressive",
"compressionModeAggressiveDesc": "Summarization + tool result compression + progressive aging for maximum savings",
++ "compressionModeUltra": "Ultra",
++ "compressionModeUltraDesc": "Heuristic token pruning with optional local SLM fallback",
"compressionAggressiveConfig": "Aggressive Engine Configuration",
"compressionAggressiveConfigDesc": "Fine-tune summarization, tool compression, and aging thresholds",
++ "compressionUltraConfig": "Ultra Engine Configuration",
++ "compressionUltraConfigDesc": "Fine-tune heuristic pruning, SLM fallback, and per-message thresholds",
++ "compressionUltraRate": "Keep Rate",
++ "compressionUltraMinScore": "Minimum Score Threshold",
++ "compressionUltraSlmFallback": "Fallback to Aggressive",
++ "compressionUltraModelPath": "SLM Model Path",
"compressionSummarizerEnabled": "Enable Summarizer",
"compressionMaxTokensPerMessage": "Max Tokens Per Message",
"compressionMinSavings": "Min Savings Threshold",
diff --cc src/i18n/messages/pt-BR.json
index 9825e4ecae,c624098e50..8dc4da1f11
--- a/src/i18n/messages/pt-BR.json
+++ b/src/i18n/messages/pt-BR.json
@@@ -2474,6 -3361,6 +3361,25 @@@
"compressionModeLiteDesc": "Whitespace and blank line reduction",
"compressionModeStandard": "Standard (Caveman)",
"compressionModeStandardDesc": "Rule-based compression with 30+ patterns, preserves code blocks and URLs",
++ "compressionModeAggressive": "Aggressive",
++ "compressionModeAggressiveDesc": "Summarization + tool result compression + progressive aging for maximum savings",
++ "compressionModeUltra": "Ultra",
++ "compressionModeUltraDesc": "Heuristic token pruning with optional local SLM fallback",
++ "compressionAggressiveConfig": "Aggressive Engine Configuration",
++ "compressionAggressiveConfigDesc": "Fine-tune summarization, tool compression, and aging thresholds",
++ "compressionUltraConfig": "Ultra Engine Configuration",
++ "compressionUltraConfigDesc": "Fine-tune heuristic pruning, SLM fallback, and per-message thresholds",
++ "compressionUltraRate": "Keep Rate",
++ "compressionUltraMinScore": "Minimum Score Threshold",
++ "compressionUltraSlmFallback": "Fallback to Aggressive",
++ "compressionUltraModelPath": "SLM Model Path",
++ "compressionSummarizerEnabled": "Enable Summarizer",
++ "compressionMaxTokensPerMessage": "Max Tokens Per Message",
++ "compressionMinSavings": "Min Savings Threshold",
++ "compressionAgingThresholds": "Aging Thresholds",
++ "compressionAgingThresholdsDesc": "Number of recent messages kept at each aging tier (higher = more preserved)",
++ "compressionToolStrategies": "Tool Result Strategies",
++ "compressionToolStrategiesDesc": "Toggle compression strategies for different tool result types",
"compressionGeneral": "General Settings",
"compressionAutoTrigger": "Auto-Trigger Threshold",
"compressionCacheTTL": "Cache TTL",
diff --cc src/i18n/messages/pt.json
index 4d07810cfd,d2fad2682a..7a43f66c1c
--- a/src/i18n/messages/pt.json
+++ b/src/i18n/messages/pt.json
@@@ -2474,6 -3331,6 +3331,25 @@@
"compressionModeLiteDesc": "Whitespace and blank line reduction",
"compressionModeStandard": "Standard (Caveman)",
"compressionModeStandardDesc": "Rule-based compression with 30+ patterns, preserves code blocks and URLs",
++ "compressionModeAggressive": "Aggressive",
++ "compressionModeAggressiveDesc": "Summarization + tool result compression + progressive aging for maximum savings",
++ "compressionModeUltra": "Ultra",
++ "compressionModeUltraDesc": "Heuristic token pruning with optional local SLM fallback",
++ "compressionAggressiveConfig": "Aggressive Engine Configuration",
++ "compressionAggressiveConfigDesc": "Fine-tune summarization, tool compression, and aging thresholds",
++ "compressionUltraConfig": "Ultra Engine Configuration",
++ "compressionUltraConfigDesc": "Fine-tune heuristic pruning, SLM fallback, and per-message thresholds",
++ "compressionUltraRate": "Keep Rate",
++ "compressionUltraMinScore": "Minimum Score Threshold",
++ "compressionUltraSlmFallback": "Fallback to Aggressive",
++ "compressionUltraModelPath": "SLM Model Path",
++ "compressionSummarizerEnabled": "Enable Summarizer",
++ "compressionMaxTokensPerMessage": "Max Tokens Per Message",
++ "compressionMinSavings": "Min Savings Threshold",
++ "compressionAgingThresholds": "Aging Thresholds",
++ "compressionAgingThresholdsDesc": "Number of recent messages kept at each aging tier (higher = more preserved)",
++ "compressionToolStrategies": "Tool Result Strategies",
++ "compressionToolStrategiesDesc": "Toggle compression strategies for different tool result types",
"compressionGeneral": "General Settings",
"compressionAutoTrigger": "Auto-Trigger Threshold",
"compressionCacheTTL": "Cache TTL",
diff --cc src/lib/db/compression.ts
index c0463a9a15,8c4baa24ad..8d45f82f37
--- a/src/lib/db/compression.ts
+++ b/src/lib/db/compression.ts
@@@ -1,25 -1,26 +1,36 @@@
- import { getDbInstance } from "./core.ts";
- import { invalidateDbCache } from "./readCache.ts";
+ import { backupDbFile } from "./backup";
+ import { getDbInstance } from "./core";
+ import { invalidateDbCache } from "./readCache";
import {
- DEFAULT_COMPRESSION_CONFIG,
-- DEFAULT_CAVEMAN_CONFIG,
DEFAULT_AGGRESSIVE_CONFIG,
++ DEFAULT_CAVEMAN_CONFIG,
+ DEFAULT_COMPRESSION_CONFIG,
+ DEFAULT_ULTRA_CONFIG,
- } from "../../../open-sse/services/compression/types.ts";
- import type {
- CompressionConfig,
- CavemanConfig,
- CompressionMode,
- AggressiveConfig,
- UltraConfig,
- } from "../../../open-sse/services/compression/types.ts";
+ type AggressiveConfig,
+ type CavemanConfig,
+ type CompressionConfig,
+ type CompressionMode,
++ type UltraConfig,
+ } from "@omniroute/open-sse/services/compression/types.ts";
const NAMESPACE = "compression";
+ const COMPRESSION_MODES = new Set<CompressionMode>([
+ "off",
+ "lite",
+ "standard",
+ "aggressive",
+ "ultra",
+ ]);
type JsonRecord = Record<string, unknown>;
++type DbInstance = ReturnType<typeof getDbInstance>;
+
+// TTL cache for compression settings (5s)
- let compressionSettingsCache: { value: CompressionConfig; expiresAt: number } | null = null;
++let compressionSettingsCache: {
++ value: CompressionConfig;
++ expiresAt: number;
++ db: DbInstance;
++} | null = null;
function toRecord(value: unknown): JsonRecord {
return value && typeof value === "object" ? (value as JsonRecord) : {};
@@@ -34,18 -35,117 +45,159 @@@ function parseJsonSafe(raw: string | nu
}
}
- export function getCompressionSettings(): CompressionConfig {
- // Check TTL cache
- if (compressionSettingsCache && Date.now() < compressionSettingsCache.expiresAt) {
+ function normalizeCavemanConfig(value: unknown): CavemanConfig {
+ const record = toRecord(value);
+ return {
+ ...DEFAULT_CAVEMAN_CONFIG,
+ ...record,
+ compressRoles: Array.isArray(record.compressRoles)
+ ? record.compressRoles.filter(
+ (role): role is "user" | "assistant" | "system" =>
+ role === "user" || role === "assistant" || role === "system"
+ )
+ : DEFAULT_CAVEMAN_CONFIG.compressRoles,
+ skipRules: Array.isArray(record.skipRules)
+ ? record.skipRules.filter((rule): rule is string => typeof rule === "string")
+ : DEFAULT_CAVEMAN_CONFIG.skipRules,
+ minMessageLength:
+ typeof record.minMessageLength === "number" && Number.isFinite(record.minMessageLength)
+ ? Math.max(0, Math.floor(record.minMessageLength))
+ : DEFAULT_CAVEMAN_CONFIG.minMessageLength,
+ preservePatterns: Array.isArray(record.preservePatterns)
+ ? record.preservePatterns.filter((pattern): pattern is string => typeof pattern === "string")
+ : DEFAULT_CAVEMAN_CONFIG.preservePatterns,
+ };
+ }
+
+ function boundedInt(value: unknown, fallback: number, min: number, max: number): number {
+ if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
+ return Math.min(max, Math.max(min, Math.floor(value)));
+ }
+
+ function boundedNumber(value: unknown, fallback: number, min: number, max: number): number {
+ if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
+ return Math.min(max, Math.max(min, value));
+ }
+
+ function normalizeAggressiveConfig(value: unknown): AggressiveConfig {
+ const record = toRecord(value);
+ const thresholds = toRecord(record.thresholds);
+ const toolStrategies = toRecord(record.toolStrategies);
+
+ return {
+ ...DEFAULT_AGGRESSIVE_CONFIG,
+ thresholds: {
+ fullSummary: boundedInt(
+ thresholds.fullSummary,
+ DEFAULT_AGGRESSIVE_CONFIG.thresholds.fullSummary,
+ 1,
+ 100
+ ),
+ moderate: boundedInt(
+ thresholds.moderate,
+ DEFAULT_AGGRESSIVE_CONFIG.thresholds.moderate,
+ 1,
+ 100
+ ),
+ light: boundedInt(thresholds.light, DEFAULT_AGGRESSIVE_CONFIG.thresholds.light, 1, 100),
+ verbatim: boundedInt(
+ thresholds.verbatim,
+ DEFAULT_AGGRESSIVE_CONFIG.thresholds.verbatim,
+ 1,
+ 100
+ ),
+ },
+ toolStrategies: {
+ fileContent:
+ typeof toolStrategies.fileContent === "boolean"
+ ? toolStrategies.fileContent
+ : DEFAULT_AGGRESSIVE_CONFIG.toolStrategies.fileContent,
+ grepSearch:
+ typeof toolStrategies.grepSearch === "boolean"
+ ? toolStrategies.grepSearch
+ : DEFAULT_AGGRESSIVE_CONFIG.toolStrategies.grepSearch,
+ shellOutput:
+ typeof toolStrategies.shellOutput === "boolean"
+ ? toolStrategies.shellOutput
+ : DEFAULT_AGGRESSIVE_CONFIG.toolStrategies.shellOutput,
+ json:
+ typeof toolStrategies.json === "boolean"
+ ? toolStrategies.json
+ : DEFAULT_AGGRESSIVE_CONFIG.toolStrategies.json,
+ errorMessage:
+ typeof toolStrategies.errorMessage === "boolean"
+ ? toolStrategies.errorMessage
+ : DEFAULT_AGGRESSIVE_CONFIG.toolStrategies.errorMessage,
+ },
+ summarizerEnabled:
+ typeof record.summarizerEnabled === "boolean"
+ ? record.summarizerEnabled
+ : DEFAULT_AGGRESSIVE_CONFIG.summarizerEnabled,
+ maxTokensPerMessage: boundedInt(
+ record.maxTokensPerMessage,
+ DEFAULT_AGGRESSIVE_CONFIG.maxTokensPerMessage,
+ 256,
+ 32768
+ ),
+ minSavingsThreshold: boundedNumber(
+ record.minSavingsThreshold,
+ DEFAULT_AGGRESSIVE_CONFIG.minSavingsThreshold,
+ 0,
+ 1
+ ),
+ };
+ }
+
++function normalizeUltraConfig(value: unknown): UltraConfig {
++ const record = toRecord(value);
++ const modelPath = typeof record.modelPath === "string" ? record.modelPath.trim() : "";
++
++ return {
++ ...DEFAULT_ULTRA_CONFIG,
++ enabled: typeof record.enabled === "boolean" ? record.enabled : DEFAULT_ULTRA_CONFIG.enabled,
++ compressionRate: boundedNumber(
++ record.compressionRate,
++ DEFAULT_ULTRA_CONFIG.compressionRate,
++ 0,
++ 1
++ ),
++ minScoreThreshold: boundedNumber(
++ record.minScoreThreshold,
++ DEFAULT_ULTRA_CONFIG.minScoreThreshold,
++ 0,
++ 1
++ ),
++ slmFallbackToAggressive:
++ typeof record.slmFallbackToAggressive === "boolean"
++ ? record.slmFallbackToAggressive
++ : DEFAULT_ULTRA_CONFIG.slmFallbackToAggressive,
++ ...(modelPath ? { modelPath } : {}),
++ maxTokensPerMessage: boundedInt(
++ record.maxTokensPerMessage,
++ DEFAULT_ULTRA_CONFIG.maxTokensPerMessage,
++ 0,
++ 32768
++ ),
++ };
++}
++
+ export async function getCompressionSettings(): Promise<CompressionConfig> {
+ const db = getDbInstance();
++ if (
++ compressionSettingsCache &&
++ compressionSettingsCache.db === db &&
++ Date.now() < compressionSettingsCache.expiresAt
++ ) {
+ return compressionSettingsCache.value;
+ }
+
- const db = getDbInstance();
const rows = db.prepare("SELECT key, value FROM key_value WHERE namespace = ?").all(NAMESPACE);
const config: CompressionConfig = {
...DEFAULT_COMPRESSION_CONFIG,
cavemanConfig: { ...DEFAULT_CAVEMAN_CONFIG },
+ aggressive: normalizeAggressiveConfig(undefined),
++ ultra: normalizeUltraConfig(undefined),
};
for (const row of rows) {
@@@ -80,50 -192,15 +244,26 @@@
}
break;
case "cavemanConfig":
- if (typeof parsed === "object" && parsed !== null) {
- config.cavemanConfig = {
- ...DEFAULT_CAVEMAN_CONFIG,
- ...(parsed as Partial<CavemanConfig>),
- };
- }
+ config.cavemanConfig = normalizeCavemanConfig(parsed);
break;
+ case "aggressive":
case "aggressiveConfig":
- if (typeof parsed === "object" && parsed !== null) {
- config.aggressive = {
- ...DEFAULT_AGGRESSIVE_CONFIG,
- ...(parsed as Partial<AggressiveConfig>),
- thresholds: {
- ...DEFAULT_AGGRESSIVE_CONFIG.thresholds,
- ...(((parsed as Record<string, unknown>).thresholds as Partial<
- typeof DEFAULT_AGGRESSIVE_CONFIG.thresholds
- >) ?? {}),
- },
- toolStrategies: {
- ...DEFAULT_AGGRESSIVE_CONFIG.toolStrategies,
- ...(((parsed as Record<string, unknown>).toolStrategies as Partial<
- typeof DEFAULT_AGGRESSIVE_CONFIG.toolStrategies
- >) ?? {}),
- },
- };
- }
+ config.aggressive = normalizeAggressiveConfig(parsed);
break;
++ case "ultra":
+ case "ultraConfig":
- if (typeof parsed === "object" && parsed !== null) {
- config.ultra = {
- ...DEFAULT_ULTRA_CONFIG,
- ...(parsed as Partial<UltraConfig>),
- };
- }
++ config.ultra = normalizeUltraConfig(parsed);
+ break;
}
}
+ // Store in TTL cache (5s expiry)
+ compressionSettingsCache = {
+ value: config,
+ expiresAt: Date.now() + 5000,
++ db,
+ };
+
return config;
}
@@@ -139,10 -219,10 +282,11 @@@ export async function updateCompression
}
});
- transaction();
- // Clear TTL cache on update
+ tx();
+ backupDbFile("pre-write");
+ compressionSettingsCache = null;
invalidateDbCache();
+ return getCompressionSettings();
}
export function getDefaultAggressiveConfig(): AggressiveConfig {
diff --cc src/lib/db/migrations/037_ultra_compression.sql
index 0000000000,0000000000..b8ce4dfa17
new file mode 100644
--- /dev/null
+++ b/src/lib/db/migrations/037_ultra_compression.sql
@@@ -1,0 -1,0 +1,6 @@@
++-- 037: Ultra compression configuration
++--
++-- Ultra compression settings are stored in key_value under namespace='compression',
++-- key='ultra'. No schema change is required; this migration reserves the version.
++
++SELECT 1;
diff --cc src/lib/db/quotaSnapshots.ts
index c1d9bb6721,7e40070b11..000fe50b77
--- a/src/lib/db/quotaSnapshots.ts
+++ b/src/lib/db/quotaSnapshots.ts
@@@ -19,22 -19,32 +19,32 @@@ export function saveQuotaSnapshot(snaps
const db = getDbInstance() as unknown as DbLike;
const now = new Date().toISOString();
- db.prepare(
- `INSERT INTO quota_snapshots
- (provider, connection_id, window_key, remaining_percentage, is_exhausted,
- next_reset_at, window_duration_ms, raw_data, created_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`
- ).run(
- snapshot.provider,
- snapshot.connection_id,
- snapshot.window_key,
- snapshot.remaining_percentage,
- snapshot.is_exhausted,
- snapshot.next_reset_at,
- snapshot.window_duration_ms,
- snapshot.raw_data,
- now
- );
+ try {
+ db.prepare(
- `INSERT INTO quota_snapshots
- (provider, connection_id, window_key, remaining_percentage, is_exhausted,
- next_reset_at, window_duration_ms, raw_data, created_at)
++ `INSERT INTO quota_snapshots
++ (provider, connection_id, window_key, remaining_percentage, is_exhausted,
++ next_reset_at, window_duration_ms, raw_data, created_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`
+ ).run(
+ snapshot.provider,
+ snapshot.connection_id,
+ snapshot.window_key,
+ snapshot.remaining_percentage,
+ snapshot.is_exhausted,
+ snapshot.next_reset_at,
+ snapshot.window_duration_ms,
+ snapshot.raw_data,
+ now
+ );
+ } catch (err: any) {
+ if (err?.message?.includes("no such table")) {
+ console.warn(
+ "[QuotaSnapshots] Skipping save: quota_snapshots table not found. Awaiting migration."
+ );
+ return;
+ }
+ throw err;
+ }
}
export function getQuotaSnapshots(opts: {
@@@ -100,34 -117,41 +117,41 @@@ export function getAggregatedSnapshots(
const selectKey =
opts.aggregateBy === "connection" ? "provider || ':' || connection_id as provider" : "provider";
- const sql = `
- SELECT
- datetime((strftime('%s', created_at) / ${bucketSeconds}) * ${bucketSeconds}, 'unixepoch') as bucket,
- ${selectKey},
- AVG(remaining_percentage) as remainingPct,
- MAX(is_exhausted) as isExhausted,
- window_key
- FROM quota_snapshots
- WHERE ${conditions.join(" AND ")}
- GROUP BY ${groupFields}
- ORDER BY bucket ASC
- `;
-
- const rows = db.prepare(sql).all(...params) as Array<{
- bucket: string;
- provider: string;
- remainingPct: number | null;
- isExhausted: number;
- windowKey: string;
- }>;
-
- return rows.map((r) => ({
- timestamp: r.bucket,
- provider: r.provider,
- remainingPct: r.remainingPct ?? 0,
- isExhausted: r.isExhausted === 1,
- windowKey: r.windowKey,
- }));
+ try {
+ const sql = `
- SELECT
++ SELECT
+ datetime((strftime('%s', created_at) / ${bucketSeconds}) * ${bucketSeconds}, 'unixepoch') as bucket,
+ ${selectKey},
+ AVG(remaining_percentage) as remainingPct,
+ MAX(is_exhausted) as isExhausted,
+ window_key
- FROM quota_snapshots
++ FROM quota_snapshots
+ WHERE ${conditions.join(" AND ")}
+ GROUP BY ${groupFields}
+ ORDER BY bucket ASC
+ `;
+
+ const rows = db.prepare(sql).all(...params) as Array<{
+ bucket: string;
+ provider: string;
+ remainingPct: number | null;
+ isExhausted: number;
+ windowKey: string;
+ }>;
+
+ return rows.map((r) => ({
+ timestamp: r.bucket,
+ provider: r.provider,
+ remainingPct: r.remainingPct ?? 0,
+ isExhausted: r.isExhausted === 1,
+ windowKey: r.windowKey,
+ }));
+ } catch (err: any) {
+ if (err?.message?.includes("no such table")) {
+ return [];
+ }
+ throw err;
+ }
}
export function cleanupOldSnapshots(retentionDays = 90): number {
diff --cc tests/unit/api/compression/compression-api.test.ts
index e4636be8fa,e4636be8fa..bdf68f61d4
--- a/tests/unit/api/compression/compression-api.test.ts
+++ b/tests/unit/api/compression/compression-api.test.ts
@@@ -50,6 -50,6 +50,13 @@@ describe("Compression Settings API Sche
minMessageLength: 50,
preservePatterns: [],
},
++ ultra: {
++ enabled: false,
++ compressionRate: 0.5,
++ minScoreThreshold: 0.3,
++ slmFallbackToAggressive: true,
++ maxTokensPerMessage: 0,
++ },
};
assert.equal(defaultConfig.enabled, false);
@@@ -59,6 -59,6 +66,8 @@@
assert.equal(typeof defaultConfig.preserveSystemPrompt, "boolean");
assert.equal(typeof defaultConfig.comboOverrides, "object");
assert.equal(typeof defaultConfig.cavemanConfig, "object");
++ assert.equal(typeof defaultConfig.ultra, "object");
++ assert.equal(defaultConfig.ultra.compressionRate, 0.5);
});
it("should validate all caveman compression rules are defined", async () => {
diff --cc tests/unit/compression/db.test.ts
index 0000000000,4d78a929c3..9da322eb97
mode 000000,100644..100644
--- a/tests/unit/compression/db.test.ts
+++ b/tests/unit/compression/db.test.ts
@@@ -1,0 -1,113 +1,142 @@@
+ import { describe, it, beforeEach, afterEach, after } from "node:test";
+ import assert from "node:assert/strict";
+ import fs from "node:fs";
+ import os from "node:os";
+ import path from "node:path";
+
+ const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-compression-db-"));
+ const ORIGINAL_DATA_DIR = process.env.DATA_DIR;
+ process.env.DATA_DIR = TEST_DATA_DIR;
+
+ const core = await import("../../../src/lib/db/core.ts");
+ const { getCompressionSettings, updateCompressionSettings } =
+ await import("../../../src/lib/db/compression.ts");
+
+ beforeEach(() => {
+ core.resetDbInstance();
+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
+ fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
+ });
+
+ afterEach(() => {
+ core.resetDbInstance();
+ });
+
+ after(() => {
+ core.resetDbInstance();
+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
+ if (ORIGINAL_DATA_DIR === undefined) {
+ delete process.env.DATA_DIR;
+ } else {
+ process.env.DATA_DIR = ORIGINAL_DATA_DIR;
+ }
+ });
+
+ describe("getCompressionSettings", () => {
+ it("returns default settings structure", async () => {
+ const settings = await getCompressionSettings();
+ assert.equal(typeof settings.enabled, "boolean");
+ assert.equal(typeof settings.defaultMode, "string");
+ assert.equal(typeof settings.autoTriggerTokens, "number");
+ assert.equal(typeof settings.cacheMinutes, "number");
+ assert.equal(typeof settings.preserveSystemPrompt, "boolean");
+ assert.equal(typeof settings.comboOverrides, "object");
++ assert.equal(typeof settings.ultra, "object");
+ });
+
+ it("has correct default values", async () => {
+ const settings = await getCompressionSettings();
+ assert.equal(settings.enabled, false);
+ assert.equal(settings.defaultMode, "off");
+ assert.equal(settings.autoTriggerTokens, 0);
+ assert.equal(settings.cacheMinutes, 5);
+ assert.equal(settings.preserveSystemPrompt, true);
+ assert.deepEqual(settings.comboOverrides, {});
++ assert.equal(settings.ultra?.enabled, false);
++ assert.equal(settings.ultra?.compressionRate, 0.5);
++ assert.equal(settings.ultra?.minScoreThreshold, 0.3);
++ assert.equal(settings.ultra?.slmFallbackToAggressive, true);
++ assert.equal(settings.ultra?.maxTokensPerMessage, 0);
+ });
+ });
+
+ describe("updateCompressionSettings", () => {
+ it("updates enabled flag", async () => {
+ await updateCompressionSettings({ enabled: true } as any);
+ const settings = await getCompressionSettings();
+ assert.equal(settings.enabled, true);
+ // Reset
+ await updateCompressionSettings({ enabled: false } as any);
+ });
+
+ it("updates defaultMode", async () => {
+ await updateCompressionSettings({ defaultMode: "lite" } as any);
+ const settings = await getCompressionSettings();
+ assert.equal(settings.defaultMode, "lite");
+ // Reset
+ await updateCompressionSettings({ defaultMode: "off" } as any);
+ });
+
+ it("updates autoTriggerTokens", async () => {
+ await updateCompressionSettings({ autoTriggerTokens: 5000 } as any);
+ const settings = await getCompressionSettings();
+ assert.equal(settings.autoTriggerTokens, 5000);
+ // Reset
+ await updateCompressionSettings({ autoTriggerTokens: 0 } as any);
+ });
+
+ it("updates multiple settings at once", async () => {
+ await updateCompressionSettings({
+ enabled: true,
+ defaultMode: "lite",
+ autoTriggerTokens: 1000,
+ cacheMinutes: 10,
+ } as any);
+ const settings = await getCompressionSettings();
+ assert.equal(settings.enabled, true);
+ assert.equal(settings.defaultMode, "lite");
+ assert.equal(settings.autoTriggerTokens, 1000);
+ assert.equal(settings.cacheMinutes, 10);
+ // Reset all
+ await updateCompressionSettings({
+ enabled: false,
+ defaultMode: "off",
+ autoTriggerTokens: 0,
+ cacheMinutes: 5,
+ } as any);
+ });
+
+ it("preserves unmodified settings", async () => {
+ const before = await getCompressionSettings();
+ await updateCompressionSettings({ enabled: true } as any);
+ const after = await getCompressionSettings();
+ assert.equal(after.enabled, true);
+ assert.equal(after.defaultMode, before.defaultMode);
+ assert.equal(after.cacheMinutes, before.cacheMinutes);
+ // Reset
+ await updateCompressionSettings({ enabled: false } as any);
+ });
++
++ it("updates and normalizes ultra config", async () => {
++ await updateCompressionSettings({
++ defaultMode: "ultra",
++ ultra: {
++ enabled: true,
++ compressionRate: 0.25,
++ minScoreThreshold: 0.4,
++ slmFallbackToAggressive: false,
++ modelPath: " /tmp/model.onnx ",
++ maxTokensPerMessage: 512,
++ },
++ } as any);
++
++ const settings = await getCompressionSettings();
++ assert.equal(settings.defaultMode, "ultra");
++ assert.equal(settings.ultra?.enabled, true);
++ assert.equal(settings.ultra?.compressionRate, 0.25);
++ assert.equal(settings.ultra?.minScoreThreshold, 0.4);
++ assert.equal(settings.ultra?.slmFallbackToAggressive, false);
++ assert.equal(settings.ultra?.modelPath, "/tmp/model.onnx");
++ assert.equal(settings.ultra?.maxTokensPerMessage, 512);
++ });
+ });
diff --cc tests/unit/compression/types.test.ts
index f9a4e6b685,f9a4e6b685..9b1284233a
--- a/tests/unit/compression/types.test.ts
+++ b/tests/unit/compression/types.test.ts
@@@ -3,6 -3,6 +3,7 @@@ import assert from "node:assert/strict"
import {
DEFAULT_AGGRESSIVE_CONFIG,
DEFAULT_COMPRESSION_CONFIG,
++ DEFAULT_ULTRA_CONFIG,
} from "../../../open-sse/services/compression/types.ts";
import type {
AggressiveConfig,
@@@ -13,6 -13,6 +14,7 @@@
CompressionMode,
CompressionStats,
CompressionConfig,
++ UltraConfig,
} from "../../../open-sse/services/compression/types.ts";
describe("Phase 3 — AggressiveConfig types", () => {
@@@ -61,6 -61,6 +63,26 @@@
assert.equal(config.aggressive, undefined);
});
++ it("DEFAULT_ULTRA_CONFIG has correct defaults", () => {
++ assert.equal(DEFAULT_ULTRA_CONFIG.enabled, false);
++ assert.equal(DEFAULT_ULTRA_CONFIG.compressionRate, 0.5);
++ assert.equal(DEFAULT_ULTRA_CONFIG.minScoreThreshold, 0.3);
++ assert.equal(DEFAULT_ULTRA_CONFIG.slmFallbackToAggressive, true);
++ assert.equal(DEFAULT_ULTRA_CONFIG.maxTokensPerMessage, 0);
++ });
++
++ it("CompressionConfig accepts ultra field", () => {
++ const ultra: UltraConfig = {
++ ...DEFAULT_ULTRA_CONFIG,
++ enabled: true,
++ };
++ const config: CompressionConfig = {
++ ...DEFAULT_COMPRESSION_CONFIG,
++ ultra,
++ };
++ assert.deepEqual(config.ultra, ultra);
++ });
++
it("CompressionStats accepts aggressive breakdown", () => {
const stats: CompressionStats = {
originalTokens: 10000,