Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors
TypeScript a2aai-agentsai-gatewayanthropicclaudeclaude-codeclinecodexcopilotcursordeepseekfree-aigeminikimillm-gatewaymcpopenaiopenai-proxyqwentoken-saver
feat(compression): expand caveman compression and analytics pipeline
diegosouzapw0f35c148ead1
diff --git a/open-sse/handlers/chatCore.ts b/open-sse/handlers/chatCore.tsindex dbf58ed0cf..2f1773bcb4 100644--- a/open-sse/handlers/chatCore.ts+++ b/open-sse/handlers/chatCore.ts@@ -1560,6 +1560,8 @@ export async function handleChatCore({// This prevents "prompt too long" errors for large-but-not-full contexts.const allMessages =body?.messages || body?.input || body?.contents || body?.request?.contents || [];+ let cavemanOutputModeApplied = false;+ let cavemanOutputModeIntensity: string | null = null;if (body && Array.isArray(allMessages) && allMessages.length > 0) {let estimatedTokens = estimateTokens(JSON.stringify(allMessages));let promptCompressionEnabled = false;@@ -1576,6 +1578,30 @@ export async function handleChatCore({);}+ if (compressionSettings?.cavemanOutputMode?.enabled) {+ try {+ const { applyCavemanOutputMode } = await import("../services/compression/outputMode.ts");+ const outputMode = applyCavemanOutputMode(+ body as Parameters<typeof applyCavemanOutputMode>[0],+ compressionSettings.cavemanOutputMode+ );+ if (outputMode.applied) {+ body = outputMode.body as typeof body;+ cavemanOutputModeApplied = true;+ cavemanOutputModeIntensity = compressionSettings.cavemanOutputMode.intensity;+ estimatedTokens = estimateTokens(JSON.stringify(body?.messages ?? body?.input ?? []));+ log?.debug?.("COMPRESSION", "Caveman output mode instruction applied");+ } else if (outputMode.skippedReason && outputMode.skippedReason !== "disabled") {+ log?.debug?.("COMPRESSION", `Caveman output mode skipped: ${outputMode.skippedReason}`);+ }+ } catch (err) {+ log?.debug?.(+ "COMPRESSION",+ "Caveman output mode skipped: " + (err instanceof Error ? err.message : String(err))+ );+ }+ }+// --- Modular Compression Pipeline (Phase 1 Lite + Phase 2 Standard/Caveman + Phase 3 Aggressive) ---// Runs BEFORE the existing reactive compressContext() to proactively reduce tokens.try {@@ -1644,80 +1670,117 @@ export async function handleChatCore({compressionInputBody,{ provider, targetFormat, model: effectiveModel });+ let compressionAnalyticsRecorded = false;if (mode !== "off") {const result = applyCompression(compressionInputBody, mode, {model: effectiveModel,config,});- if (result.compressed && result.stats) {- body = result.body as typeof body;- estimatedTokens = result.stats.compressedTokens;- trackCompressionStats(result.stats);- void (async () => {- try {- const { insertCompressionAnalyticsRow } =- await import("../../src/lib/db/compressionAnalytics.ts");- insertCompressionAnalyticsRow({- timestamp: new Date().toISOString(),- combo_id: comboName ?? null,- provider: provider ?? null,- mode,- original_tokens: result.stats.originalTokens,- compressed_tokens: result.stats.compressedTokens,- tokens_saved: Math.max(+ if (result.stats) {+ if (result.compressed) {+ body = result.body as typeof body;+ estimatedTokens = result.stats.compressedTokens;+ }++ if (result.compressed || result.stats.fallbackApplied || cavemanOutputModeApplied) {+ trackCompressionStats(result.stats);+ compressionAnalyticsRecorded = true;+ void (async () => {+ try {+ const { insertCompressionAnalyticsRow } =+ await import("../../src/lib/db/compressionAnalytics.ts");+ insertCompressionAnalyticsRow({+ timestamp: new Date().toISOString(),+ combo_id: comboName ?? null,+ provider: provider ?? null,+ mode,+ original_tokens: result.stats.originalTokens,+ compressed_tokens: result.stats.compressedTokens,+ tokens_saved: Math.max(+ 0,+ result.stats.originalTokens - result.stats.compressedTokens+ ),+ duration_ms: result.stats.durationMs ?? null,+ request_id: skillRequestId,+ validation_fallback: result.stats.fallbackApplied ? 1 : 0,+ output_mode: cavemanOutputModeApplied ? cavemanOutputModeIntensity : null,+ });+ } catch (err) {+ log?.debug?.(+ "COMPRESSION",+ "Compression analytics write skipped: " ++ (err instanceof Error ? err.message : String(err))+ );+ }+ })();+ }++ if (result.compressed) {+ void (async () => {+ try {+ const { detectCachingContext } =+ await import("../services/compression/cachingAware.ts");+ const { recordCacheStats } =+ await import("../../src/lib/db/compressionCacheStats.ts");+ const cacheContext = detectCachingContext(compressionInputBody, {+ provider,+ targetFormat,+ model: effectiveModel,+ });+ const tokensSavedCompression = Math.max(0,result.stats.originalTokens - result.stats.compressedTokens- ),- duration_ms: result.stats.durationMs ?? null,- request_id: skillRequestId,- });- } catch (err) {- log?.debug?.(- "COMPRESSION",- "Compression analytics write skipped: " +- (err instanceof Error ? err.message : String(err))- );- }- })();- void (async () => {- try {- const { detectCachingContext } =- await import("../services/compression/cachingAware.ts");- const { recordCacheStats } =- await import("../../src/lib/db/compressionCacheStats.ts");- const cacheContext = detectCachingContext(compressionInputBody, {- provider,- targetFormat,- model: effectiveModel,- });- const tokensSavedCompression = Math.max(- 0,- result.stats.originalTokens - result.stats.compressedTokens- );- recordCacheStats({- provider: cacheContext.provider ?? provider ?? "unknown",- model: effectiveModel ?? "",- compressionMode: mode,- cacheControlPresent: cacheContext.hasCacheControl,- estimatedCacheHit: cacheContext.hasCacheControl && cacheContext.isCachingProvider,- tokensSavedCompression,- tokensSavedCaching: 0,- netSavings: tokensSavedCompression,- });- } catch (err) {- log?.debug?.(- "COMPRESSION",- "Compression cache stats write skipped: " +- (err instanceof Error ? err.message : String(err))- );- }- })();- log?.info?.(- "COMPRESSION",- `Prompt compressed (${mode}): ${result.stats.originalTokens} -> ${result.stats.compressedTokens} tokens (${result.stats.savingsPercent}% saved, techniques: ${result.stats.techniquesUsed.join(",")})`- );+ );+ recordCacheStats({+ provider: cacheContext.provider ?? provider ?? "unknown",+ model: effectiveModel ?? "",+ compressionMode: mode,+ cacheControlPresent: cacheContext.hasCacheControl,+ estimatedCacheHit: cacheContext.hasCacheControl && cacheContext.isCachingProvider,+ tokensSavedCompression,+ tokensSavedCaching: 0,+ netSavings: tokensSavedCompression,+ });+ } catch (err) {+ log?.debug?.(+ "COMPRESSION",+ "Compression cache stats write skipped: " ++ (err instanceof Error ? err.message : String(err))+ );+ }+ })();+ log?.info?.(+ "COMPRESSION",+ `Prompt compressed (${mode}): ${result.stats.originalTokens} -> ${result.stats.compressedTokens} tokens (${result.stats.savingsPercent}% saved, techniques: ${result.stats.techniquesUsed.join(",")})`+ );+ }}}+ if (cavemanOutputModeApplied && !compressionAnalyticsRecorded) {+ void (async () => {+ try {+ const { insertCompressionAnalyticsRow } =+ await import("../../src/lib/db/compressionAnalytics.ts");+ insertCompressionAnalyticsRow({+ timestamp: new Date().toISOString(),+ combo_id: comboName ?? null,+ provider: provider ?? null,+ mode: "output-caveman",+ original_tokens: estimatedTokens,+ compressed_tokens: estimatedTokens,+ tokens_saved: 0,+ request_id: skillRequestId,+ output_mode: cavemanOutputModeIntensity,+ });+ } catch (err) {+ log?.debug?.(+ "COMPRESSION",+ "Caveman output analytics write skipped: " ++ (err instanceof Error ? err.message : String(err))+ );+ }+ })();+ }} catch (err) {log?.warn?.("COMPRESSION",@@ -3264,6 +3327,13 @@ export async function handleChatCore({// Log usage for non-streaming responsesconst usage = extractUsageFromResponse(responseBody, provider);+ if (usage && typeof usage === "object") {+ void import("../../src/lib/db/compressionAnalytics.ts")+ .then(({ attachCompressionUsageReceipt }) => {+ attachCompressionUsageReceipt(skillRequestId, usage, "provider");+ })+ .catch(() => {});+ }appendRequestLog({ model, provider, connectionId, tokens: usage, status: "200 OK" }).catch(() => {});@@ -3636,6 +3706,11 @@ export async function handleChatCore({// Track cache token metrics for streaming responsesif (streamUsage && typeof streamUsage === "object") {+ void import("../../src/lib/db/compressionAnalytics.ts")+ .then(({ attachCompressionUsageReceipt }) => {+ attachCompressionUsageReceipt(skillRequestId, streamUsage, "stream");+ })+ .catch(() => {});const inputTokens = streamUsage.prompt_tokens || 0;const cachedTokens = toPositiveNumber(streamUsage.cache_read_input_tokens ??diff --git a/open-sse/mcp-server/descriptionCompressor.ts b/open-sse/mcp-server/descriptionCompressor.tsnew file mode 100644index 0000000000..b18a5ea976--- /dev/null+++ b/open-sse/mcp-server/descriptionCompressor.ts@@ -0,0 +1,122 @@+import { applyRulesToText } from "../services/compression/caveman.ts";+import { getRulesForContext } from "../services/compression/cavemanRules.ts";+import {+ extractPreservedBlocks,+ restorePreservedBlocks,+} from "../services/compression/preservation.ts";++export interface DescriptionCompressionResult {+ compressed: string;+ before: number;+ after: number;+ changed: boolean;+}++export interface DescriptionCompressionOptions {+ enabled?: boolean;+}++export interface McpDescriptionCompressionStats {+ descriptionsCompressed: number;+ charsBefore: number;+ charsAfter: number;+ charsSaved: number;+ estimatedTokensSaved: number;+}++const descriptionCompressionStats: McpDescriptionCompressionStats = {+ descriptionsCompressed: 0,+ charsBefore: 0,+ charsAfter: 0,+ charsSaved: 0,+ estimatedTokensSaved: 0,+};++function isDisabledEnvValue(value: string | undefined): boolean {+ return !!value && ["0", "false", "off", "no"].includes(value.trim().toLowerCase());+}++export function isMcpDescriptionCompressionEnabled(+ options: DescriptionCompressionOptions = {}+): boolean {+ if (isDisabledEnvValue(process.env.OMNIROUTE_MCP_COMPRESS_DESCRIPTIONS)) return false;+ if (isDisabledEnvValue(process.env.OMNIROUTE_MCP_DESCRIPTION_COMPRESSION)) return false;+ return options.enabled !== false;+}++export function compressMcpDescription(description: string): DescriptionCompressionResult {+ if (!description) {+ return { compressed: description, before: 0, after: 0, changed: false };+ }++ const { text, blocks } = extractPreservedBlocks(description);+ const rules = getRulesForContext("all", "full");+ const applied = applyRulesToText(text, rules).text;+ const normalized = applied+ .replace(/[ \t]{2,}/g, " ")+ .replace(/\s+([,.;:!?])/g, "$1")+ .replace(/\n{3,}/g, "\n\n")+ .replace(/(^|[.!?]\s+)([a-z])/g, (_match, prefix: string, char: string) => {+ return `${prefix}${char.toUpperCase()}`;+ })+ .trim();+ const compressed = restorePreservedBlocks(normalized, blocks);++ return {+ compressed,+ before: description.length,+ after: compressed.length,+ changed: compressed !== description,+ };+}++export function maybeCompressMcpDescription(+ description: string,+ options: DescriptionCompressionOptions = {}+): string {+ if (!isMcpDescriptionCompressionEnabled(options)) return description;+ const result = compressMcpDescription(description);+ if (result.changed && result.after < result.before) {+ descriptionCompressionStats.descriptionsCompressed += 1;+ descriptionCompressionStats.charsBefore += result.before;+ descriptionCompressionStats.charsAfter += result.after;+ descriptionCompressionStats.charsSaved += result.before - result.after;+ descriptionCompressionStats.estimatedTokensSaved += Math.ceil(+ (result.before - result.after) / 4+ );+ }+ return result.compressed;+}++export function compressDescriptionsInPlace(+ value: unknown,+ fieldNames: string[] = ["description"],+ options: DescriptionCompressionOptions = {}+): void {+ if (!value || typeof value !== "object") return;+ const fields = new Set(fieldNames);+ if (Array.isArray(value)) {+ for (const item of value) compressDescriptionsInPlace(item, fieldNames, options);+ return;+ }++ for (const [key, nested] of Object.entries(value as Record<string, unknown>)) {+ if (fields.has(key) && typeof nested === "string") {+ (value as Record<string, unknown>)[key] = maybeCompressMcpDescription(nested, options);+ } else if (nested && typeof nested === "object") {+ compressDescriptionsInPlace(nested, fieldNames, options);+ }+ }+}++export function getMcpDescriptionCompressionStats(): McpDescriptionCompressionStats {+ return { ...descriptionCompressionStats };+}++export function resetMcpDescriptionCompressionStats(): void {+ descriptionCompressionStats.descriptionsCompressed = 0;+ descriptionCompressionStats.charsBefore = 0;+ descriptionCompressionStats.charsAfter = 0;+ descriptionCompressionStats.charsSaved = 0;+ descriptionCompressionStats.estimatedTokensSaved = 0;+}diff --git a/open-sse/mcp-server/schemas/tools.ts b/open-sse/mcp-server/schemas/tools.tsindex 401f39d3d5..fc9d0deef9 100644--- a/open-sse/mcp-server/schemas/tools.ts+++ b/open-sse/mcp-server/schemas/tools.ts@@ -1000,14 +1000,41 @@ export const compressionStatusOutput = z.object({strategy: z.string(),settings: z.object({maxTokens: z.number(),+ autoTriggerMode: z.string(),targetRatio: z.number(),- aggressiveness: z.string(),+ preserveSystemPrompt: z.boolean(),+ mcpDescriptionCompressionEnabled: z.boolean(),}),analytics: z.object({totalRequests: z.number(),compressedRequests: z.number(),tokensSaved: z.number(),avgCompressionRatio: z.number(),+ byMode: z.record(+ z.string(),+ z.object({+ count: z.number(),+ tokensSaved: z.number(),+ avgSavingsPct: z.number(),+ })+ ),+ validationFallbacks: z.number(),+ requestsWithReceipts: z.number(),+ realUsage: z.object({+ requestsWithReceipts: z.number(),+ promptTokens: z.number(),+ completionTokens: z.number(),+ totalTokens: z.number(),+ cacheReadTokens: z.number(),+ cacheWriteTokens: z.number(),+ estimatedUsdSaved: z.number(),+ bySource: z.record(z.string(), z.number()),+ }),+ mcpDescriptionCompression: z.object({+ descriptionsCompressed: z.number(),+ charsSaved: z.number(),+ estimatedTokensSaved: z.number(),+ }),}),cacheStats: z.object({@@ -1037,12 +1064,19 @@ export const compressionStatusTool: McpToolDefinition<export const compressionConfigureInput = z.object({enabled: z.boolean().optional(),strategy: z- .string()+ .enum(["off", "lite", "standard", "aggressive", "ultra"])+ .optional()+ .describe("Compression mode"),+ autoTriggerMode: z.enum(["off", "lite", "standard", "aggressive", "ultra"]).optional(),+ maxTokens: z+ .number()+ .int()+ .min(0).optional()- .describe("Compression strategy: 'none' | 'standard' | 'aggressive' | 'ultra'"),- maxTokens: z.number().optional().describe("Maximum tokens before compression triggers"),+ .describe("Maximum tokens before compression triggers"),targetRatio: z.number().optional().describe("Target compression ratio (0.0–1.0)"),- aggressiveness: z.string().optional().describe("Aggressiveness level: 'low' | 'medium' | 'high'"),+ preserveSystemPrompt: z.boolean().optional(),+ mcpDescriptionCompressionEnabled: z.boolean().optional(),});export const compressionConfigureOutput = z.object({@@ -1051,9 +1085,11 @@ export const compressionConfigureOutput = z.object({settings: z.object({enabled: z.boolean(),strategy: z.string(),+ autoTriggerMode: z.string(),maxTokens: z.number(),targetRatio: z.number(),- aggressiveness: z.string(),+ preserveSystemPrompt: z.boolean(),+ mcpDescriptionCompressionEnabled: z.boolean(),}),});@@ -1063,7 +1099,7 @@ export const compressionConfigureTool: McpToolDefinition<> = {name: "omniroute_compression_configure",description:- "Configure compression settings at runtime. Supports enabling/disabling compression, changing strategy (none/standard/aggressive/ultra), adjusting maxTokens threshold, targetRatio, and aggressiveness level.",+ "Configure compression settings at runtime. Supports enabling/disabling compression, changing strategy (off/lite/standard/aggressive/ultra), adjusting maxTokens threshold, targetRatio, auto-trigger mode, system prompt preservation, and MCP description compression.",inputSchema: compressionConfigureInput,outputSchema: compressionConfigureOutput,scopes: ["write:compression"],diff --git a/open-sse/mcp-server/server.ts b/open-sse/mcp-server/server.tsindex 7b7d7d9c7f..0a50fbbcd5 100644--- a/open-sse/mcp-server/server.ts+++ b/open-sse/mcp-server/server.ts@@ -76,6 +76,8 @@ import {import { memoryTools } from "./tools/memoryTools.ts";import { skillTools } from "./tools/skillTools.ts";import { compressionTools } from "./tools/compressionTools.ts";+import { maybeCompressMcpDescription } from "./descriptionCompressor.ts";+import { getDbInstance } from "../../src/lib/db/core.ts";import { normalizeQuotaResponse } from "../../src/shared/contracts/quota.ts";import { resolveOmniRouteBaseUrl } from "../../src/shared/utils/resolveOmniRouteBaseUrl.ts";@@ -95,6 +97,18 @@ const TOTAL_MCP_TOOL_COUNT =type JsonRecord = Record<string, unknown>;+function readMcpDescriptionCompressionEnabled(): boolean {+ try {+ const row = getDbInstance()+ .prepare("SELECT value FROM key_value WHERE namespace = ? AND key = ?")+ .get("compression", "mcpDescriptionCompressionEnabled") as { value?: string } | undefined;+ if (!row?.value) return true;+ return JSON.parse(row.value) !== false;+ } catch {+ return true;+ }+}+type TextToolResult = {content: Array<{ type: "text"; text: string }>;isError?: boolean;@@ -577,6 +591,17 @@ export function createMcpServer(): McpServer {name: "omniroute",version: process.env.npm_package_version || "1.8.1",});+ const mcpDescriptionCompressionEnabled = readMcpDescriptionCompressionEnabled();+ const registerTool = server.registerTool.bind(server);+ server.registerTool = ((name: string, config: Record<string, unknown>, handler: unknown) => {+ const description =+ typeof config.description === "string"+ ? maybeCompressMcpDescription(config.description, {+ enabled: mcpDescriptionCompressionEnabled,+ })+ : config.description;+ return registerTool(name, { ...config, description }, handler as never);+ }) as typeof server.registerTool;// Register essential toolsserver.registerTool(diff --git a/open-sse/mcp-server/tools/compressionTools.ts b/open-sse/mcp-server/tools/compressionTools.tsindex 795b053ef7..8732d09376 100644--- a/open-sse/mcp-server/tools/compressionTools.ts+++ b/open-sse/mcp-server/tools/compressionTools.ts@@ -14,6 +14,7 @@ import {import { getCompressionAnalyticsSummary } from "../../../src/lib/db/compressionAnalytics.ts";import { getCacheStatsSummary } from "../../../src/lib/db/compressionCacheStats.ts";import type { McpToolExtraLike } from "../scopeEnforcement.ts";+import { getMcpDescriptionCompressionStats } from "../descriptionCompressor.ts";/*** Handle compression_status tool: return current compression config, analytics, and cache stats@@ -26,14 +27,34 @@ export async function handleCompressionStatus(strategy: string;settings: {maxTokens: number;+ autoTriggerMode: string;targetRatio: number;- aggressiveness: string;+ preserveSystemPrompt: boolean;+ mcpDescriptionCompressionEnabled: boolean;};analytics: {totalRequests: number;compressedRequests: number;tokensSaved: number;avgCompressionRatio: number;+ byMode: Record<string, { count: number; tokensSaved: number; avgSavingsPct: number }>;+ validationFallbacks: number;+ requestsWithReceipts: number;+ realUsage: {+ requestsWithReceipts: number;+ promptTokens: number;+ completionTokens: number;+ totalTokens: number;+ cacheReadTokens: number;+ cacheWriteTokens: number;+ estimatedUsdSaved: number;+ bySource: Record<string, number>;+ };+ mcpDescriptionCompression: {+ descriptionsCompressed: number;+ charsSaved: number;+ estimatedTokensSaved: number;+ };};cacheStats: {hits: number;@@ -46,6 +67,7 @@ export async function handleCompressionStatus(try {const settings = await getCompressionSettings();const analyticsSummary = getCompressionAnalyticsSummary();+ const mcpDescriptionStats = getMcpDescriptionCompressionStats();const cacheStats = getCacheStatsSummary();const result = {@@ -53,14 +75,28 @@ export async function handleCompressionStatus(strategy: settings.defaultMode || "standard",settings: {maxTokens: settings.autoTriggerTokens,+ autoTriggerMode: settings.autoTriggerMode ?? "lite",targetRatio: 0.7, // Default target ratio- aggressiveness: settings.defaultMode || "standard",+ preserveSystemPrompt: settings.preserveSystemPrompt,+ mcpDescriptionCompressionEnabled: settings.mcpDescriptionCompressionEnabled !== false,},analytics: {totalRequests: analyticsSummary.totalRequests,- compressedRequests: analyticsSummary.byMode?.standard?.count || 0,+ compressedRequests: Object.values(analyticsSummary.byMode ?? {}).reduce(+ (sum, mode) => sum + mode.count,+ 0+ ),tokensSaved: analyticsSummary.totalTokensSaved,- avgCompressionRatio: analyticsSummary.byMode?.standard?.avgSavingsPct || 0,+ avgCompressionRatio: analyticsSummary.avgSavingsPct,+ byMode: analyticsSummary.byMode ?? {},+ validationFallbacks: analyticsSummary.validationFallbacks,+ requestsWithReceipts: analyticsSummary.realUsage.requestsWithReceipts,+ realUsage: analyticsSummary.realUsage,+ mcpDescriptionCompression: {+ descriptionsCompressed: mcpDescriptionStats.descriptionsCompressed,+ charsSaved: mcpDescriptionStats.charsSaved,+ estimatedTokensSaved: mcpDescriptionStats.estimatedTokensSaved,+ },},cacheStats: cacheStats? {@@ -98,9 +134,11 @@ export async function handleCompressionConfigure(args: {enabled?: boolean;strategy?: string;+ autoTriggerMode?: string;maxTokens?: number;targetRatio?: number;- aggressiveness?: string;+ preserveSystemPrompt?: boolean;+ mcpDescriptionCompressionEnabled?: boolean;},extra?: McpToolExtraLike): Promise<{@@ -109,9 +147,11 @@ export async function handleCompressionConfigure(settings: {enabled: boolean;strategy: string;+ autoTriggerMode: string;maxTokens: number;targetRatio: number;- aggressiveness: string;+ preserveSystemPrompt: boolean;+ mcpDescriptionCompressionEnabled: boolean;};}> {const start = Date.now();@@ -124,11 +164,17 @@ export async function handleCompressionConfigure(if (args.strategy !== undefined) {updates.defaultMode = args.strategy;}+ if (args.autoTriggerMode !== undefined) {+ updates.autoTriggerMode = args.autoTriggerMode;+ }if (args.maxTokens !== undefined) {updates.autoTriggerTokens = args.maxTokens;}- if (args.aggressiveness !== undefined) {- updates.defaultMode = args.aggressiveness;+ if (args.preserveSystemPrompt !== undefined) {+ updates.preserveSystemPrompt = args.preserveSystemPrompt;+ }+ if (args.mcpDescriptionCompressionEnabled !== undefined) {+ updates.mcpDescriptionCompressionEnabled = args.mcpDescriptionCompressionEnabled;}const settings = await updateCompressionSettings(updates);@@ -139,9 +185,11 @@ export async function handleCompressionConfigure(settings: {enabled: settings.enabled,strategy: settings.defaultMode || "standard",+ autoTriggerMode: settings.autoTriggerMode ?? "lite",maxTokens: settings.autoTriggerTokens,targetRatio: 0.7, // Default target ratio- aggressiveness: settings.defaultMode || "standard",+ preserveSystemPrompt: settings.preserveSystemPrompt,+ mcpDescriptionCompressionEnabled: settings.mcpDescriptionCompressionEnabled !== false,},};@@ -178,7 +226,7 @@ export const compressionTools = {omniroute_compression_configure: {name: "omniroute_compression_configure",description:- "Configure compression settings at runtime. Supports enabling/disabling compression, changing strategy (none/standard/aggressive/ultra), adjusting maxTokens threshold, targetRatio, and aggressiveness level.",+ "Configure compression settings at runtime. Supports enabling/disabling compression, changing strategy (off/lite/standard/aggressive/ultra), adjusting maxTokens threshold, targetRatio, auto-trigger mode, system prompt preservation, and MCP description compression.",inputSchema: compressionConfigureInput,handler: (args: z.infer<typeof compressionConfigureInput>) => handleCompressionConfigure(args),},diff --git a/open-sse/services/compression/aggressive.ts b/open-sse/services/compression/aggressive.tsindex 8e2d3e85c4..83c1acb86c 100644--- a/open-sse/services/compression/aggressive.ts+++ b/open-sse/services/compression/aggressive.ts@@ -5,39 +5,19 @@ import { applyAging } from "./progressiveAging.ts";import { RuleBasedSummarizer } from "./summarizer.ts";import { cavemanCompress } from "./caveman.ts";import { applyLiteCompression } from "./lite.ts";+import { extractTextContent, replaceTextContent, type ChatMessageLike } from "./messageContent.ts";const COMPRESSED_MARKER_RE = /^\[COMPRESSED:/;-interface ChatMessage {- role: string;- content?: string | Array<{ type: string; text?: string }>;- [key: string]: unknown;-}+type ChatMessage = ChatMessageLike;interface AggressiveCompressionResult {messages: ChatMessage[];stats: CompressionStats;}-function extractText(content?: string | Array<{ type: string; text?: string }>): string {- if (typeof content === "string") return content;- if (Array.isArray(content)) {- return content- .filter(- (p): p is { type: string; text?: string } =>- typeof p === "object" && p !== null && "text" in p- )- .map((p) => p.text ?? "")- .join("\n");- }- return "";-}-function setContent(msg: ChatMessage, newContent: string): ChatMessage {- if (typeof msg.content === "string") {- return { ...msg, content: newContent };- }- return { ...msg, content: [{ type: "text", text: newContent }] };+ return replaceTextContent(msg, newContent) as ChatMessage;}function estimateTokens(text: string): number {@@ -71,7 +51,7 @@ export function compressAggressive(};const originalTokens = messages.reduce(- (sum, m) => sum + estimateTokens(extractText(m.content)),+ (sum, m) => sum + estimateTokens(extractTextContent(m.content)),0);resultStats.originalTokens = originalTokens;@@ -84,8 +64,9 @@ export function compressAggressive(// Step 1: Tool-result compressiontry {const afterToolResult = currentMessages.map((msg) => {+ if (cfg.preserveSystemPrompt !== false && msg.role === "system") return msg;if (msg.role !== "tool" && msg.role !== "function") return msg;- const text = extractText(msg.content);+ const text = extractTextContent(msg.content);if (!text || COMPRESSED_MARKER_RE.test(text)) return msg;const result = compressToolResult(text, cfg.toolStrategies);@@ -101,7 +82,12 @@ export function compressAggressive(// Step 2: Progressive agingtry {- const agingResult = applyAging(currentMessages, cfg.thresholds, summarizer);+ const agingResult = applyAging(+ currentMessages,+ cfg.thresholds,+ summarizer,+ cfg.preserveSystemPrompt !== false+ );agingSavings = agingResult.saved;currentMessages = agingResult.messages as ChatMessage[];} catch (err) {@@ -112,7 +98,8 @@ export function compressAggressive(if (cfg.summarizerEnabled) {try {currentMessages = currentMessages.map((msg) => {- const text = extractText(msg.content);+ if (cfg.preserveSystemPrompt !== false && msg.role === "system") return msg;+ const text = extractTextContent(msg.content);if (!text || COMPRESSED_MARKER_RE.test(text)) return msg;if (text.length <= cfg.maxTokensPerMessage * 4) return msg;@@ -133,7 +120,7 @@ export function compressAggressive(// Downgrade chain: if total savings < threshold, try caveman then liteconst compressedTokens = currentMessages.reduce(- (sum, m) => sum + estimateTokens(extractText(m.content)),+ (sum, m) => sum + estimateTokens(extractTextContent(m.content)),0);resultStats.compressedTokens = compressedTokens;diff --git a/open-sse/services/compression/caveman.ts b/open-sse/services/compression/caveman.tsindex e0c40ecdfa..464a6ac3a8 100644--- a/open-sse/services/compression/caveman.ts+++ b/open-sse/services/compression/caveman.ts@@ -3,10 +3,13 @@ import { DEFAULT_CAVEMAN_CONFIG } from "./types.ts";import { CAVEMAN_RULES, getRulesForContext } from "./cavemanRules.ts";import { extractPreservedBlocks, restorePreservedBlocks } from "./preservation.ts";import { createCompressionStats, estimateCompressionTokens } from "./stats.ts";+import { validateCompression } from "./validation.ts";+import { mapTextContent } from "./messageContent.ts";interface ChatMessage {role: string;content?: string | Array<{ type: string; text?: string }>;+ [key: string]: unknown;}interface ChatRequestBody {@@ -14,14 +17,168 @@ interface ChatRequestBody {[key: string]: unknown;}+const RULE_KEYWORDS: Record<string, string[]> = {+ redundant_phrasing: [+ "make sure",+ "be sure",+ "due to the fact",+ "the reason is because",+ "it is important",+ "you should",+ "remember to",+ ],+ pleasantries: ["sure", "certainly", "of course", "happy to"],+ polite_framing: [+ "please",+ "kindly",+ "could you please",+ "would you please",+ "can you please",+ "i would like you",+ "i want you",+ "i need you",+ ],+ hedging: [+ "it seems like",+ "it appears that",+ "i think that",+ "i believe that",+ "probably",+ "possibly",+ "maybe it",+ ],+ verbose_instructions: [+ "provide a detailed",+ "give me a comprehensive",+ "write an in-depth",+ "create a thorough",+ "explain in detail",+ ],+ filler_adverbs: ["basically", "essentially", "actually", "literally", "simply", "currently"],+ filler_phrases: ["i want to", "i need to", "i'd like to", "i'm looking for"],+ redundant_openers: ["hi there", "hello", "good morning", "hey"],+ verbose_requests: ["i was wondering", "would it be possible"],+ leader_phrases: [+ "i'll",+ "i will",+ "i can",+ "i'd",+ "let me",+ "you can",+ "we will",+ "we can",+ "let's",+ ],+ self_reference: ["i am trying to", "i am working on", "i have been"],+ excessive_gratitude: ["thank you so much", "thanks in advance", "i really appreciate"],+ qualifier_removal: ["a bit", "a little", "somewhat", "kind of", "sort of"],+ compound_collapse: ["and any potential"],+ explanatory_prefix: [+ "the function appears to be handling",+ "the code seems to",+ "the class is",+ "this module is",+ ],+ question_to_directive: [+ "can you explain why",+ "could you show me how",+ "would you tell me",+ "can you tell me",+ ],+ context_setup: ["i have the following code", "here is my code", "below is the code"],+ intent_clarification: [+ "what i'm trying to do",+ "my objective is to",+ "what i need is",+ "i'm aiming to",+ ],+ background_removal: ["as you may know", "as we discussed earlier"],+ meta_commentary: ["note that", "keep in mind", "remember that"],+ purpose_statement: ["for the purpose of", "with the goal of", "in an effort to", "for every"],+ list_conjunction: ["and also", "as well as"],+ purpose_phrases: ["in order to", "so as to"],+ redundant_quantifiers: ["each and every", "any and all"],+ verbose_connectors: ["furthermore", "additionally", "moreover", "in addition"],+ transition_removal: ["on the other hand", "in contrast", "however"],+ emphasis_removal: ["very", "really", "extremely", "highly", "quite"],+ passive_voice: [+ "is being used",+ "is being called",+ "is being generated",+ "was created",+ "was generated",+ "was implemented",+ ],+ repeated_context: [+ "as we discussed earlier",+ "as mentioned before",+ "as previously stated",+ "as i said before",+ ],+ repeated_question: [+ "same question as before",+ "i asked this earlier",+ "this is the same question",+ ],+ reestablished_context: ["going back to the code above", "referring back to", "returning to"],+ summary_replacement: ["to summarize", "in summary of our conversation", "to recap"],+ ultra_abbreviations: [+ "database",+ "configuration",+ "function",+ "request",+ "response",+ "implementation",+ "authentication",+ "authorization",+ "application",+ "dependency",+ ],+};++const KEYWORD_WORDS = new Map<string, string[]>();++function extractLowerWords(lowerText: string): Set<string> {+ return new Set(lowerText.match(/[a-z]+(?:'[a-z]+)?/g) ?? []);+}++function getKeywordWords(keyword: string): string[] {+ const cached = KEYWORD_WORDS.get(keyword);+ if (cached) return cached;+ const words = keyword.match(/[a-z]+(?:'[a-z]+)?/g) ?? [];+ KEYWORD_WORDS.set(keyword, words);+ return words;+}++function hasKeywordHint(keyword: string, words: Set<string>): boolean {+ const keywordWords = getKeywordWords(keyword);+ return keywordWords.length === 0 || keywordWords.every((word) => words.has(word));+}++function shouldAttemptRule(ruleName: string, lowerText: string, words: Set<string>): boolean {+ if (ruleName === "articles") {+ return words.has("a") || words.has("an") || words.has("the");+ }++ const keywords = RULE_KEYWORDS[ruleName];+ return (+ !keywords ||+ keywords.some((keyword) => hasKeywordHint(keyword, words) && lowerText.includes(keyword))+ );+}+export function applyRulesToText(text: string,rules: CavemanRule[]): { text: string; appliedRules: string[] } {let result = text;+ const lowerResult = text.toLowerCase();+ const lowerWords = extractLowerWords(lowerResult);const appliedRules: string[] = [];for (const rule of rules) {+ if (!shouldAttemptRule(rule.name, lowerResult, lowerWords)) continue;+const before = result;const { pattern, replacement } = rule;if (typeof replacement === "function") {@@ -43,14 +200,50 @@ export function applyRulesToText(function cleanupArtifacts(text: string): string {let result = text;- result = result.replace(/ +/g, " ");- result = result.replace(/ +$/gm, "");- result = result.replace(/\n{3,}/g, "\n\n");- result = result.replace(/^\n+/, "");- result = result.replace(/\n+$/, "");+ if (result.includes(" ")) result = result.replace(/ +/g, " ");+ if (/[\t ]+[,.;:!?]/.test(result)) result = result.replace(/\s+([,.;:!?])/g, "$1");+ if (/[.!?]{2,}/.test(result)) result = result.replace(/([.!?]){2,}/g, "$1");+ if (/[ \t]\n/.test(result)) result = result.replace(/[ \t]+$/gm, "");+ if (result.endsWith(" ") || result.endsWith("\t")) result = result.trimEnd();+ if (result.includes("\n\n\n")) result = result.replace(/\n{3,}/g, "\n\n");+ if (result.startsWith("\n")) result = result.replace(/^\n+/, "");+ if (result.endsWith("\n")) result = result.replace(/\n+$/, "");return result;}+function recapitalizeSentences(text: string): string {+ return text.replace(/(^|[.!?]\s+|\n+\s*)([a-z])/g, (_match, prefix: string, char: string) => {+ return `${prefix}${char.toUpperCase()}`;+ });+}++function compileUserPreservePatterns(patterns: string[]): {+ patterns: RegExp[];+ warnings: string[];+} {+ const compiled: RegExp[] = [];+ const warnings: string[] = [];+ for (const pattern of patterns) {+ try {+ compiled.push(new RegExp(pattern, "g"));+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ warnings.push(`Invalid preservePatterns regex ignored: ${pattern} (${message})`);+ }+ }+ return { patterns: compiled, warnings };+}++const PROTECTED_STRUCTURE_RE =+ /```|~~~|`|https?:\/\/|\[[^\]\n]+\]\([^) \n]+(?:\s+"[^"]*")?\)|^#{1,6}\s+|^\s*\|.*\|\s*$|\$\$|\\\[|\\begin\{|^\s*#(?:set|show|let|import|include)\b|\b[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+\b|\bprocess\.env\.[A-Za-z_][A-Za-z0-9_]*\b|\$[A-Z_][A-Z0-9_]*\b|\b\d+(?:\.\d+){1,3}(?:[-+][A-Za-z0-9.-]+)?\b|\b[a-zA-Z_$][\w$]*(?:\.[a-zA-Z_$][\w$]*)+\(\)?|\b[A-Za-z_$][\w$]*\s*\([^()\n]*\)|(?:^|\s)(?:\.{0,2}\/[A-Za-z0-9_@./-]+|[A-Za-z]:\\[A-Za-z0-9_.\\/-]+)|\b(?:TypeError|ReferenceError|SyntaxError|RangeError|URIError|EvalError|Error|Exception):[^\n]+/im;+const PROTECTED_STRUCTURE_PREFILTER_RE = /[`~\[\]\|$#\\/:_()0-9]/;++function hasProtectedStructure(text: string): boolean {+ if (!PROTECTED_STRUCTURE_PREFILTER_RE.test(text)) return false;+ PROTECTED_STRUCTURE_RE.lastIndex = 0;+ return PROTECTED_STRUCTURE_RE.test(text);+}+export function cavemanCompress(body: ChatRequestBody,options?: Partial<CavemanConfig>@@ -80,23 +273,29 @@ export function cavemanCompress(let totalOriginalTokens = 0;let totalCompressedTokens = 0;const allAppliedRules: string[] = [];+ const validationWarnings: string[] = [];+ const validationErrors: string[] = [];+ let fallbackApplied = false;+ let preservedBlockCount = 0;+ const customPreservation = compileUserPreservePatterns(config.preservePatterns ?? []);+ validationWarnings.push(...customPreservation.warnings);const compressedMessages = body.messages.map((msg): ChatMessage => {- // Only compress simple string content — multi-part messages (arrays)- // would duplicate compressed text across all text parts if naively handled- if (typeof msg.content !== "string") {- const contentStr = Array.isArray(msg.content)- ? msg.content- .map((part) => (part.type === "text" && part.text ? part.text : ""))- .filter(Boolean)- .join("\n")- : "";- totalOriginalTokens += estimateCompressionTokens(contentStr);- totalCompressedTokens += estimateCompressionTokens(contentStr);+ if (typeof msg.content !== "string" && !Array.isArray(msg.content)) {return msg;}- const contentStr = msg.content;+ const contentStr =+ typeof msg.content === "string"+ ? msg.content+ : msg.content+ .map((part) =>+ part && typeof part === "object" && "text" in part && typeof part.text === "string"+ ? part.text+ : ""+ )+ .filter(Boolean)+ .join("\n");totalOriginalTokens += estimateCompressionTokens(contentStr);if (!contentStr || contentStr.length < config.minMessageLength) {@@ -109,21 +308,59 @@ export function cavemanCompress(return msg;}- const { text: extractedText, blocks } = extractPreservedBlocks(contentStr);+ const compressTextPart = (textPart: string): string => {+ if (!textPart || textPart.length < config.minMessageLength) return textPart;++ const shouldPreserve =+ customPreservation.patterns.length > 0 || hasProtectedStructure(textPart);+ const { text: extractedText, blocks } = shouldPreserve+ ? extractPreservedBlocks(textPart, {+ preservePatterns: customPreservation.patterns,+ })+ : { text: textPart, blocks: [] };+ preservedBlockCount += blocks.length;- const rules = getRulesForContext(msg.role).filter(- (rule) => !config.skipRules.includes(rule.name)- );- const { text: rulesApplied, appliedRules } = applyRulesToText(extractedText, rules);- allAppliedRules.push(...appliedRules);+ const rules = getRulesForContext(msg.role, config.intensity).filter(+ (rule) => !config.skipRules.includes(rule.name)+ );+ const { text: rulesApplied, appliedRules } = applyRulesToText(extractedText, rules);+ allAppliedRules.push(...appliedRules);- const restored = restorePreservedBlocks(rulesApplied, blocks);+ const normalized = cleanupArtifacts(recapitalizeSentences(rulesApplied));+ const cleaned =+ blocks.length > 0+ ? cleanupArtifacts(restorePreservedBlocks(normalized, blocks))+ : normalized;+ if (shouldPreserve || blocks.length > 0) {+ const validation = validateCompression(textPart, cleaned);+ validationWarnings.push(...validation.warnings);+ if (!validation.valid) {+ validationErrors.push(...validation.errors);+ fallbackApplied = true;+ return textPart;+ }+ }- const cleaned = cleanupArtifacts(restored);+ return cleaned;+ };+ const compressedMessage = mapTextContent(msg, compressTextPart) as ChatMessage;+ const cleaned =+ typeof compressedMessage.content === "string"+ ? compressedMessage.content+ : Array.isArray(compressedMessage.content)+ ? compressedMessage.content+ .map((part) =>+ part && typeof part === "object" && "text" in part && typeof part.text === "string"+ ? part.text+ : ""+ )+ .filter(Boolean)+ .join("\n")+ : contentStr;totalCompressedTokens += estimateCompressionTokens(cleaned);- return { ...msg, content: cleaned };+ return compressedMessage;});const durationMs = performance.now() - startMs;@@ -136,6 +373,10 @@ export function cavemanCompress(uniqueRules.length > 0 ? uniqueRules : undefined,Math.round(durationMs * 100) / 100);+ if (validationWarnings.length > 0) stats.validationWarnings = [...new Set(validationWarnings)];+ if (validationErrors.length > 0) stats.validationErrors = [...new Set(validationErrors)];+ if (fallbackApplied) stats.fallbackApplied = true;+ if (preservedBlockCount > 0) stats.preservedBlockCount = preservedBlockCount;const compressed = totalCompressedTokens < totalOriginalTokens;diff --git a/open-sse/services/compression/cavemanRules.ts b/open-sse/services/compression/cavemanRules.tsindex 51e9958d04..7050372ef3 100644--- a/open-sse/services/compression/cavemanRules.ts+++ b/open-sse/services/compression/cavemanRules.ts@@ -3,12 +3,45 @@ import type { CavemanRule } from "./types.ts";const CAVEMAN_RULES: CavemanRule[] = [// ── Category 1: Filler Removal (10+ rules) ──────────────────────────+ {+ name: "redundant_phrasing",+ pattern:+ /\b(?:make sure to|be sure to|due to the fact that|the reason is because|it is important to|you should|remember to)\b\s*/gi,+ replacement: (match: string): string => {+ const map: Record<string, string> = {+ "make sure to": "ensure ",+ "be sure to": "ensure ",+ "due to the fact that": "because ",+ "the reason is because": "because ",+ "it is important to": "",+ "you should": "",+ "remember to": "",+ };+ return map[match.trim().toLowerCase()] ?? "";+ },+ context: "all",+ category: "structural",+ minIntensity: "full",+ description: "Replace verbose stock phrases with shorter equivalents.",+ },+ {+ name: "pleasantries",+ pattern:+ /\b(?:sure|certainly|of course|happy to|i'?d be happy to|i would be happy to)\b[,.!?\s]*/gi,+ replacement: "",+ context: "all",+ category: "filler",+ minIntensity: "lite",+ description: "Drop conversational acknowledgements that do not change request meaning.",+ },{name: "polite_framing",pattern:/\b(?:please|kindly|could you please|would you please|can you please|I would like you to|I want you to|I need you to)\b\s*/gi,replacement: "",context: "all",+ category: "filler",+ minIntensity: "lite",},{name: "hedging",@@ -16,13 +49,19 @@ const CAVEMAN_RULES: CavemanRule[] = [/\b(?:it seems like|it appears that|I think that|I believe that|probably|possibly|maybe it)\b\s*/gi,replacement: "",context: "all",+ category: "filler",+ minIntensity: "lite",},{name: "verbose_instructions",pattern:- /\b(?:provide a detailed|give me a comprehensive|write an in-depth|create a thorough|explain in detail)\b/gi,+ /\b(?:provide a detailed explanation of|give me a comprehensive explanation of|write an in-depth explanation of|create a thorough explanation of|provide a detailed|give me a comprehensive|write an in-depth|create a thorough|explain in detail)\b/gi,replacement: (match: string): string => {const map: Record<string, string> = {+ "provide a detailed explanation of": "explain",+ "give me a comprehensive explanation of": "explain",+ "write an in-depth explanation of": "explain",+ "create a thorough explanation of": "explain","provide a detailed": "provide","give me a comprehensive": "give","write an in-depth": "write",@@ -33,48 +72,82 @@ const CAVEMAN_RULES: CavemanRule[] = [return map[lower] ?? match;},context: "all",+ category: "filler",+ minIntensity: "lite",},{name: "filler_adverbs",- pattern: /(?<![a-z])\b(?:basically|essentially|actually|literally|simply)\b\s*/gi,+ pattern: /(?<![a-z])\b(?:basically|essentially|actually|literally|simply|currently)\b\s*/gi,replacement: "",context: "all",+ category: "filler",+ minIntensity: "lite",+ },+ {+ name: "articles",+ pattern: /\b(?:a|an|the)\s+(?=[a-z])/gi,+ replacement: "",+ context: "all",+ category: "terse",+ minIntensity: "full",+ description: "Remove English articles from prose while protected technical tokens stay intact.",},{name: "filler_phrases",pattern: /^(?:I want to|I need to|I'd like to|I'm looking for)\b\s*/gim,replacement: "",context: "user",+ category: "filler",+ minIntensity: "lite",},{name: "redundant_openers",pattern: /^(?:Hi there|Hello|Good morning|Hey)\s*[,.!?\s]?\s*/gim,replacement: "",context: "user",+ category: "filler",+ minIntensity: "lite",},{name: "verbose_requests",pattern: /\b(?:I was wondering if you could|Would it be possible to)\b\s*/gi,replacement: "",context: "user",+ category: "filler",+ minIntensity: "lite",+ },+ {+ name: "leader_phrases",+ pattern: /^(?:i'?ll|i will|i can|i'?d|let me|you can|we will|we can|let'?s)\s+(?=[a-z])/gim,+ replacement: "",+ context: "all",+ category: "terse",+ minIntensity: "full",+ description: "Remove leading helper phrases before the actual instruction or answer.",},{name: "self_reference",pattern: /^(?:I am trying to|I am working on|I have been)\b\s*/gim,replacement: "",context: "user",+ category: "filler",+ minIntensity: "lite",},{name: "excessive_gratitude",pattern: /\b(?:Thank you so much|Thanks in advance|I really appreciate)\b[,.!?\s]*/gi,replacement: "",context: "all",+ category: "filler",+ minIntensity: "lite",},{name: "qualifier_removal",pattern: /\b(?:a bit|a little|somewhat|kind of|sort of)\b\s*/gi,replacement: "",context: "all",+ category: "filler",+ minIntensity: "lite",},// ── Category 2: Context Condensation (8+ rules) ──────────────────────@@ -84,6 +157,8 @@ const CAVEMAN_RULES: CavemanRule[] = [pattern: /\band any potential\b/gi,replacement: "",context: "all",+ category: "context",+ minIntensity: "full",},{name: "explanatory_prefix",@@ -99,6 +174,8 @@ const CAVEMAN_RULES: CavemanRule[] = [return map[match.toLowerCase()] ?? match;},context: "all",+ category: "context",+ minIntensity: "lite",},{name: "question_to_directive",@@ -115,12 +192,16 @@ const CAVEMAN_RULES: CavemanRule[] = [return map[trimmed] ?? match;},context: "user",+ category: "context",+ minIntensity: "lite",},{name: "context_setup",pattern: /\b(?:I have the following code|Here is my code|Below is the code)\b\s*[:.]?\s*/gi,replacement: "Code:",context: "user",+ category: "context",+ minIntensity: "lite",},{name: "intent_clarification",@@ -128,31 +209,40 @@ const CAVEMAN_RULES: CavemanRule[] = [/\b(?:What I'm trying to do is|My objective is to|What I need is|I'm aiming to)\b\s*/gi,replacement: "Goal:",context: "user",+ category: "context",+ minIntensity: "lite",},{name: "background_removal",pattern: /\b(?:As you may know,?\s*|As we discussed earlier,?\s*)/gi,replacement: "",context: "all",+ category: "context",+ minIntensity: "lite",},{name: "meta_commentary",pattern: /^(?:Note that|Keep in mind that|Remember that)\b\s*/gim,replacement: "",context: "all",+ category: "context",+ minIntensity: "lite",},{name: "purpose_statement",- pattern: /\b(?:for the purpose of|with the goal of|in an effort to)\b/gi,+ pattern: /\b(?:for the purpose of|with the goal of|in an effort to|for every)\b/gi,replacement: (match: string): string => {const map: Record<string, string> = {"for the purpose of": "for","with the goal of": "to","in an effort to": "to",+ "for every": "per",};return map[match.toLowerCase()] ?? match;},context: "all",+ category: "context",+ minIntensity: "lite",},// ── Category 3: Structural Compression (7+ rules) ────────────────────@@ -162,12 +252,16 @@ const CAVEMAN_RULES: CavemanRule[] = [pattern: /,\s*and also\s+|,\s*as well as\s+/gi,replacement: ", ",context: "all",+ category: "structural",+ minIntensity: "full",},{name: "purpose_phrases",pattern: /\b(?:in order to|so as to)\b\s*/gi,replacement: "to ",context: "all",+ category: "structural",+ minIntensity: "lite",},{name: "redundant_quantifiers",@@ -181,32 +275,42 @@ const CAVEMAN_RULES: CavemanRule[] = [return map[match.toLowerCase()] ?? match;},context: "all",+ category: "structural",+ minIntensity: "full",},{name: "verbose_connectors",pattern: /\b(?:furthermore|additionally|moreover|in addition)\b\s*/gi,replacement: "also ",context: "all",+ category: "structural",+ minIntensity: "lite",},{name: "transition_removal",pattern: /^(?:On the other hand,?\s*|In contrast,?\s*|However,?\s*)/gim,replacement: "",context: "all",+ category: "structural",+ minIntensity: "lite",},{name: "emphasis_removal",pattern: /\b(?:very|really|extremely|highly|quite)\s+(?=[a-z])/gi,replacement: "",context: "all",+ category: "structural",+ minIntensity: "lite",},{name: "passive_voice",- pattern: /\b(?:is being used|is being called|was created|was generated|was implemented)\b/gi,+ pattern:+ /\b(?:is being used|is being called|is being generated|was created|was generated|was implemented)\b/gi,replacement: (match: string): string => {const map: Record<string, string> = {"is being used": "uses","is being called": "calls",+ "is being generated": "generated","was created": "created","was generated": "generated","was implemented": "implemented",@@ -214,6 +318,8 @@ const CAVEMAN_RULES: CavemanRule[] = [return map[match.toLowerCase()] ?? match;},context: "all",+ category: "structural",+ minIntensity: "full",},// ── Category 4: Multi-Turn Dedup (5+ rules) ─────────────────────────@@ -224,6 +330,8 @@ const CAVEMAN_RULES: CavemanRule[] = [/\b(?:As we discussed earlier|As mentioned before|As previously stated|As I said before)\b[,.]?\s*/gi,replacement: "See above. ",context: "all",+ category: "dedup",+ minIntensity: "lite",},{name: "repeated_question",@@ -231,12 +339,16 @@ const CAVEMAN_RULES: CavemanRule[] = [/\b(?:Same question as before|I asked this earlier|This is the same question)\b[,.]?\s*/gi,replacement: "[same question] ",context: "user",+ category: "dedup",+ minIntensity: "lite",},{name: "reestablished_context",pattern: /\b(?:Going back to the code above|Referring back to|Returning to)\b\s*/gi,replacement: "Re: ",context: "all",+ category: "dedup",+ minIntensity: "lite",},{name: "summary_replacement",@@ -244,15 +356,63 @@ const CAVEMAN_RULES: CavemanRule[] = [/\b(?:To summarize what we've discussed|In summary of our conversation|To recap)\b[,.]?\s*/gi,replacement: "Summary: ",context: "assistant",+ category: "dedup",+ minIntensity: "lite",+ },++ // ── Category 5: Ultra Abbreviations ─────────────────────────────────++ {+ name: "ultra_abbreviations",+ pattern:+ /\b(?:database|configuration|function|request|response|implementation|authentication|authorization|application|dependency|dependencies)\b/gi,+ replacement: (match: string): string => {+ const map: Record<string, string> = {+ database: "DB",+ configuration: "config",+ function: "fn",+ request: "req",+ response: "res",+ implementation: "impl",+ authentication: "auth",+ authorization: "authz",+ application: "app",+ dependency: "dep",+ dependencies: "deps",+ };+ return map[match.toLowerCase()] ?? match;+ },+ context: "all",+ category: "ultra",+ minIntensity: "ultra",},];-export function getRulesForContext(context: string): CavemanRule[] {- return CAVEMAN_RULES.filter((rule) => rule.context === "all" || rule.context === context);+const INTENSITY_RANK = { lite: 0, full: 1, ultra: 2 } as const;++export function getRulesForContext(+ context: string,+ intensity: "lite" | "full" | "ultra" = "full"+): CavemanRule[] {+ const rank = INTENSITY_RANK[intensity] ?? INTENSITY_RANK.full;+ return CAVEMAN_RULES.filter((rule) => {+ const minRank = INTENSITY_RANK[rule.minIntensity ?? "lite"];+ return (rule.context === "all" || rule.context === context) && minRank <= rank;+ });}export function getRuleByName(name: string): CavemanRule | undefined {return CAVEMAN_RULES.find((rule) => rule.name === name);}+export function getCavemanRuleMetadata() {+ return CAVEMAN_RULES.map((rule) => ({+ name: rule.name,+ context: rule.context,+ category: rule.category ?? "terse",+ minIntensity: rule.minIntensity ?? "lite",+ description: rule.description ?? rule.name.replace(/_/g, " "),+ }));+}+export { CAVEMAN_RULES };diff --git a/open-sse/services/compression/diffHelper.ts b/open-sse/services/compression/diffHelper.tsnew file mode 100644index 0000000000..80632c7e51--- /dev/null+++ b/open-sse/services/compression/diffHelper.ts@@ -0,0 +1,88 @@+import type { CompressionStats } from "./types.ts";+import { extractPreservedBlocks } from "./preservation.ts";+import { validateCompression } from "./validation.ts";++export interface CompressionDiffSegment {+ type: "same" | "removed" | "added";+ text: string;+}++export interface CompressionPreviewDiff {+ segments: CompressionDiffSegment[];+ preservedBlocks: Array<{ kind: string; preview: string }>;+ ruleRemovals: string[];+ validationWarnings: string[];+ validationErrors: string[];+ fallbackApplied: boolean;+}++function tokenize(text: string): string[] {+ return text.match(/\s+|[^\s]+/g) ?? [];+}++export function buildCompressionDiff(+ original: string,+ compressed: string+): CompressionDiffSegment[] {+ const a = tokenize(original);+ const b = tokenize(compressed);+ const dp = Array.from({ length: a.length + 1 }, () => Array<number>(b.length + 1).fill(0));++ for (let i = a.length - 1; i >= 0; i--) {+ for (let j = b.length - 1; j >= 0; j--) {+ dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);+ }+ }++ const segments: CompressionDiffSegment[] = [];+ const push = (type: CompressionDiffSegment["type"], text: string) => {+ if (!text) return;+ const last = segments[segments.length - 1];+ if (last?.type === type) {+ last.text += text;+ } else {+ segments.push({ type, text });+ }+ };++ let i = 0;+ let j = 0;+ while (i < a.length && j < b.length) {+ if (a[i] === b[j]) {+ push("same", a[i]);+ i++;+ j++;+ } else if (dp[i + 1][j] >= dp[i][j + 1]) {+ push("removed", a[i]);+ i++;+ } else {+ push("added", b[j]);+ j++;+ }+ }+ while (i < a.length) push("removed", a[i++]);+ while (j < b.length) push("added", b[j++]);++ return segments;+}++export function buildCompressionPreviewDiff(+ original: string,+ compressed: string,+ stats: CompressionStats | null | undefined+): CompressionPreviewDiff {+ const validation = validateCompression(original, compressed);+ const preserved = extractPreservedBlocks(original).blocks.map((block) => ({+ kind: block.kind,+ preview: block.content.replace(/\s+/g, " ").slice(0, 120),+ }));++ return {+ segments: buildCompressionDiff(original, compressed),+ preservedBlocks: preserved,+ ruleRemovals: stats?.rulesApplied ?? [],+ validationWarnings: [...(stats?.validationWarnings ?? []), ...validation.warnings],+ validationErrors: [...(stats?.validationErrors ?? []), ...validation.errors],+ fallbackApplied: Boolean(stats?.fallbackApplied || validation.fallbackApplied),+ };+}diff --git a/open-sse/services/compression/index.ts b/open-sse/services/compression/index.tsindex 98578a1f70..efc5b4ddb6 100644--- a/open-sse/services/compression/index.ts+++ b/open-sse/services/compression/index.ts@@ -5,6 +5,8 @@ export type {CompressionResult,CavemanConfig,CavemanRule,+ CavemanIntensity,+ CavemanOutputModeConfig,AggressiveConfig,AgingThresholds,ToolStrategiesConfig,@@ -15,6 +17,7 @@ export type {export {DEFAULT_COMPRESSION_CONFIG,DEFAULT_CAVEMAN_CONFIG,+ DEFAULT_CAVEMAN_OUTPUT_MODE_CONFIG,DEFAULT_AGGRESSIVE_CONFIG,} from "./types.ts";@@ -28,8 +31,23 @@ export {} from "./lite.ts";export { cavemanCompress, applyRulesToText } from "./caveman.ts";-export { getRulesForContext, CAVEMAN_RULES } from "./cavemanRules.ts";-export { extractPreservedBlocks, restorePreservedBlocks } from "./preservation.ts";+export { getRulesForContext, getCavemanRuleMetadata, CAVEMAN_RULES } from "./cavemanRules.ts";+export {+ extractPreservedBlocks,+ restorePreservedBlocks,+ findFencedCodeBlocks,+} from "./preservation.ts";+export type { PreservedBlock, PreservationOptions } from "./preservation.ts";+export { validateCompression } from "./validation.ts";+export type { ValidationResult } from "./validation.ts";+export {+ applyCavemanOutputMode,+ buildCavemanOutputInstruction,+ shouldBypassCavemanOutputMode,+} from "./outputMode.ts";+export type { CavemanOutputModeResult } from "./outputMode.ts";+export { buildCompressionDiff, buildCompressionPreviewDiff } from "./diffHelper.ts";+export type { CompressionDiffSegment, CompressionPreviewDiff } from "./diffHelper.ts";export {estimateCompressionTokens,diff --git a/open-sse/services/compression/lite.ts b/open-sse/services/compression/lite.tsindex 5e530e74f5..fba65badbe 100644--- a/open-sse/services/compression/lite.ts+++ b/open-sse/services/compression/lite.ts@@ -15,6 +15,7 @@ interface ChatBody {interface LiteCompressionOptions {model?: string;supportsVision?: boolean | null;+ preserveSystemPrompt?: boolean;}function trimTrailingHorizontalWhitespace(line: string): string {@@ -62,13 +63,17 @@ function modelSupportsVision(model: string): boolean {);}-export function collapseWhitespace(body: ChatBody): {+export function collapseWhitespace(+ body: ChatBody,+ options: LiteCompressionOptions = {}+): {body: ChatBody;applied: boolean;} {if (!body.messages) return { body, applied: false };let applied = false;const messages = body.messages.map((msg) => {+ if (options.preserveSystemPrompt === true && msg.role === "system") return msg;if (typeof msg.content !== "string") return msg;const normalized = normalizeMessageWhitespace(msg.content);if (normalized !== msg.content) applied = true;@@ -77,11 +82,15 @@ export function collapseWhitespace(body: ChatBody): {return { body: { ...body, messages }, applied };}-export function dedupSystemPrompt(body: ChatBody): {+export function dedupSystemPrompt(+ body: ChatBody,+ options: LiteCompressionOptions = {}+): {body: ChatBody;applied: boolean;} {if (!body.messages) return { body, applied: false };+ if (options.preserveSystemPrompt === true) return { body, applied: false };const seen = new Set<string>();let applied = false;const messages = body.messages.filter((msg) => {@@ -116,7 +125,10 @@ export function compressToolResults(body: ChatBody): {return { body: { ...body, messages }, applied };}-export function removeRedundantContent(body: ChatBody): {+export function removeRedundantContent(+ body: ChatBody,+ options: LiteCompressionOptions = {}+): {body: ChatBody;applied: boolean;} {@@ -125,6 +137,10 @@ export function removeRedundantContent(body: ChatBody): {const messages: Message[] = [];for (let i = 0; i < body.messages.length; i++) {const msg = body.messages[i];+ if (options.preserveSystemPrompt === true && msg.role === "system") {+ messages.push(msg);+ continue;+ }const contentStr = typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content);if (i > 0 &&@@ -188,11 +204,11 @@ export function applyLiteCompression(let current = body as ChatBody;const techniquesApplied: string[] = [];- const r1 = collapseWhitespace(current);+ const r1 = collapseWhitespace(current, options);current = r1.body;if (r1.applied) techniquesApplied.push("whitespace");- const r2 = dedupSystemPrompt(current);+ const r2 = dedupSystemPrompt(current, options);current = r2.body;if (r2.applied) techniquesApplied.push("system-dedup");@@ -200,7 +216,7 @@ export function applyLiteCompression(current = r3.body;if (r3.applied) techniquesApplied.push("tool-compress");- const r4 = removeRedundantContent(current);+ const r4 = removeRedundantContent(current, options);current = r4.body;if (r4.applied) techniquesApplied.push("redundant-remove");diff --git a/open-sse/services/compression/messageContent.ts b/open-sse/services/compression/messageContent.tsnew file mode 100644index 0000000000..7bd414d924--- /dev/null+++ b/open-sse/services/compression/messageContent.ts@@ -0,0 +1,79 @@+export interface TextBlock {+ type?: string;+ text?: string;+ [key: string]: unknown;+}++export interface ChatMessageLike {+ role: string;+ content?: string | TextBlock[] | unknown[];+ [key: string]: unknown;+}++export function isTextBlock(value: unknown): value is TextBlock {+ return (+ !!value &&+ typeof value === "object" &&+ "text" in value &&+ typeof (value as TextBlock).text === "string" &&+ ((value as TextBlock).type === undefined ||+ (value as TextBlock).type === "text" ||+ (value as TextBlock).type === "input_text")+ );+}++export function extractTextContent(content: ChatMessageLike["content"]): string {+ if (typeof content === "string") return content;+ if (!Array.isArray(content)) return "";++ const textParts: string[] = [];+ for (const part of content) {+ if (isTextBlock(part) && part.text) {+ textParts.push(part.text);+ }+ }+ return textParts.join("\n");+}++export function mapTextContent(+ msg: ChatMessageLike,+ transform: (text: string, index: number) => string+): ChatMessageLike {+ if (typeof msg.content === "string") {+ return { ...msg, content: transform(msg.content, 0) };+ }+ if (!Array.isArray(msg.content)) return msg;++ let textIndex = 0;+ let changed = false;+ const content = msg.content.map((part) => {+ if (!isTextBlock(part)) return part;+ const nextText = transform(part.text ?? "", textIndex);+ textIndex++;+ if (nextText === part.text) return part;+ changed = true;+ return { ...part, text: nextText };+ });++ return changed ? { ...msg, content } : msg;+}++export function replaceTextContent(msg: ChatMessageLike, newText: string): ChatMessageLike {+ if (typeof msg.content === "string" || !Array.isArray(msg.content)) {+ return { ...msg, content: newText };+ }++ let replaced = false;+ const content = msg.content.flatMap((part) => {+ if (!isTextBlock(part)) return [part];+ if (replaced) return [];+ replaced = true;+ return [{ ...part, text: newText }];+ });++ if (!replaced) {+ return { ...msg, content: [{ type: "text", text: newText }, ...msg.content] };+ }++ return { ...msg, content };+}diff --git a/open-sse/services/compression/outputMode.ts b/open-sse/services/compression/outputMode.tsnew file mode 100644index 0000000000..478ae863f2--- /dev/null+++ b/open-sse/services/compression/outputMode.ts@@ -0,0 +1,122 @@+import { DEFAULT_CAVEMAN_OUTPUT_MODE_CONFIG, type CavemanOutputModeConfig } from "./types.ts";+import { extractTextContent } from "./messageContent.ts";++interface ChatMessage {+ role: string;+ content?: string | unknown[];+ [key: string]: unknown;+}++interface ChatRequestBody {+ messages?: ChatMessage[];+ instructions?: string;+ [key: string]: unknown;+}++export interface CavemanOutputModeResult {+ body: ChatRequestBody;+ applied: boolean;+ skippedReason?: string;+}++const CAVEMAN_INSTRUCTION_BY_INTENSITY = {+ lite: "Respond concise. Drop filler, pleasantries, hedging. Keep full sentences, technical terms, code, errors, URLs, and identifiers exact.",+ full: "Respond terse like smart caveman. Drop articles, filler, pleasantries, hedging. Fragments OK. Keep all technical substance, code, errors, URLs, identifiers exact.",+ ultra:+ "Respond ultra terse. Use short technical prose, arrows for causality, common abbreviations like DB/auth/config/req/res/fn. Never abbreviate code symbols, API names, error strings, URLs, or identifiers.",+} as const;++const CAVEMAN_OUTPUT_MARKER = "[OmniRoute Caveman Output Mode]";++export function shouldBypassCavemanOutputMode(messages: ChatMessage[]): string | null {+ const text = messages+ .slice(-3)+ .map((message) => extractTextContent(message.content).toLowerCase())+ .join("\n");++ if (!text.trim()) return null;+ if (+ /\b(security|vulnerability|exploit|credential leak|secret leak|malware|phishing)\b/.test(text)+ ) {+ return "security_warning";+ }+ if (/\b(delete|drop table|truncate|destroy|wipe|irreversible|permanently remove)\b/.test(text)) {+ return "irreversible_action";+ }+ if (+ /\b(clarify|explain in detail|more detail|step by step|why exactly|what do you mean)\b/.test(+ text+ )+ ) {+ return "clarification_requested";+ }+ if (+ /\b(first|then|after that|before|rollback|backup)\b[\s\S]{0,240}\b(delete|drop|migrate|deploy|release)\b/.test(+ text+ )+ ) {+ return "order_sensitive_sequence";+ }+ return null;+}++export function buildCavemanOutputInstruction(config: CavemanOutputModeConfig): string {+ const intensity = config.intensity ?? "full";+ return `${CAVEMAN_OUTPUT_MARKER}\n${CAVEMAN_INSTRUCTION_BY_INTENSITY[intensity]}`;+}++export function applyCavemanOutputMode(+ body: ChatRequestBody,+ options?: Partial<CavemanOutputModeConfig>+): CavemanOutputModeResult {+ const config: CavemanOutputModeConfig = {+ ...DEFAULT_CAVEMAN_OUTPUT_MODE_CONFIG,+ ...options,+ };+ if (!config.enabled) return { body, applied: false, skippedReason: "disabled" };++ const messages = Array.isArray(body.messages) ? body.messages : null;+ if (!messages || messages.length === 0) {+ if (typeof body.instructions === "string") {+ if (body.instructions.includes(CAVEMAN_OUTPUT_MARKER)) {+ return { body, applied: false, skippedReason: "already_applied" };+ }+ return {+ body: {+ ...body,+ instructions: `${body.instructions.trim()}\n\n${buildCavemanOutputInstruction(config)}`,+ },+ applied: true,+ };+ }+ return { body, applied: false, skippedReason: "no_messages" };+ }++ if (config.autoClarity !== false) {+ const bypass = shouldBypassCavemanOutputMode(messages);+ if (bypass) return { body, applied: false, skippedReason: bypass };+ }++ const alreadyApplied = messages.some(+ (message) =>+ message.role === "system" &&+ typeof message.content === "string" &&+ message.content.includes(CAVEMAN_OUTPUT_MARKER)+ );+ if (alreadyApplied) return { body, applied: false, skippedReason: "already_applied" };++ const instruction = buildCavemanOutputInstruction(config);+ const nextMessages = [...messages];+ const first = nextMessages[0];++ if (first?.role === "system" && typeof first.content === "string") {+ nextMessages[0] = {+ ...first,+ content: `${first.content.trim()}\n\n${instruction}`,+ };+ } else {+ nextMessages.unshift({ role: "system", content: instruction });+ }++ return { body: { ...body, messages: nextMessages }, applied: true };+}diff --git a/open-sse/services/compression/preservation.ts b/open-sse/services/compression/preservation.tsindex d65edbd84b..dcd382b92a 100644--- a/open-sse/services/compression/preservation.ts+++ b/open-sse/services/compression/preservation.ts@@ -1,72 +1,183 @@-interface PreservedBlock {+export interface PreservedBlock {placeholder: string;content: string;+ kind: string;}-export function extractPreservedBlocks(text: string): { text: string; blocks: PreservedBlock[] } {+export interface PreservationOptions {+ preservePatterns?: Array<string | RegExp>;+}++interface CompiledPattern {+ pattern: RegExp;+ kind: string;+}++const SENTINEL_PREFIX = "\u0000OMNI_CAVEMAN";++function randomSentinelSeed(): string {+ const bytes = new Uint8Array(8);+ const cryptoLike = globalThis.crypto;+ if (cryptoLike?.getRandomValues) {+ cryptoLike.getRandomValues(bytes);+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");+ }+ return Math.random().toString(36).slice(2);+}++function ensureGlobal(pattern: RegExp): RegExp {+ const flags = pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`;+ return new RegExp(pattern.source, flags);+}++function compileUserPatterns(patterns: Array<string | RegExp> | undefined): CompiledPattern[] {+ if (!patterns?.length) return [];+ const compiled: CompiledPattern[] = [];+ for (const pattern of patterns) {+ try {+ compiled.push({+ pattern: typeof pattern === "string" ? new RegExp(pattern, "g") : ensureGlobal(pattern),+ kind: "custom",+ });+ } catch {+ // Invalid user regexes are ignored by the hot path. Validation/preview exposes warnings.+ }+ }+ return compiled;+}++function replacePattern(+ text: string,+ pattern: RegExp,+ kind: string,+ addBlock: (content: string, kind: string) => string+): string {+ pattern.lastIndex = 0;+ return text.replace(pattern, (match) => {+ if (!match) return match;+ if (match.includes(SENTINEL_PREFIX)) return match;+ return addBlock(match, kind);+ });+}++export function findFencedCodeBlocks(text: string): string[] {+ const blocks: string[] = [];+ extractFencedCodeBlocks(text, (content) => {+ blocks.push(content);+ return content;+ });+ return blocks;+}++export function extractPreservedBlocks(+ text: string,+ options: PreservationOptions = {}+): { text: string; blocks: PreservedBlock[] } {const blocks: PreservedBlock[] = [];- let result = text;+ const seed = randomSentinelSeed();let counter = 0;- const addBlock = (content: string): string => {- const placeholder = `[PRESERVED_${counter}]`;- blocks.push({ placeholder, content });+ const addBlock = (content: string, kind: string): string => {+ const placeholder = `${SENTINEL_PREFIX}_${seed}_${counter}\u0000`;+ blocks.push({ placeholder, content, kind });counter++;return placeholder;};- // Extract fenced code blocks with a linear scan to avoid ReDoS-prone patterns.- result = extractFencedCodeBlocks(result, addBlock);-- // Extract inline code (`...`)- result = result.replace(/`[^`\n]+`/g, (match) => addBlock(match));-- // Extract URLs- result = result.replace(/https?:\/\/[^\s)\]"'>]+/g, (match) => addBlock(match));-- // Extract file paths (Unix and Windows)- result = result.replace(/(?:\/[a-zA-Z0-9_./-]+|[a-zA-Z]:\\[a-zA-Z0-9_.\\/-]+)/g, (match) => {- if (match.length < 3) return match;- if (match.startsWith("[PRESERVED_")) return match;- return addBlock(match);- });+ let result = text;- // Extract error-like patterns (TypeError:, Error:, 404, etc.)- result = result.replace(- /\b(?:TypeError|ReferenceError|SyntaxError|RangeError|URIError|EvalError|Error):\s*[^\s,;)]+/g,- (match) => addBlock(match)- );+ result = extractFrontmatter(result, addBlock);+ result = extractFencedCodeBlocks(result, (content) => addBlock(content, "fenced_code"));++ const builtIns: CompiledPattern[] = [+ { pattern: /\$\$[\s\S]*?\$\$/g, kind: "math_block" },+ { pattern: /\\\[[\s\S]*?\\\]/g, kind: "math_block" },+ { pattern: /(?<!\$)\$(?![\s$\d])(?:\\.|[^$\n]){1,160}?(?<!\s)\$(?!\$)/g, kind: "math_inline" },+ { pattern: /\\begin\{[A-Za-z*]+\}[\s\S]*?\\end\{[A-Za-z*]+\}/g, kind: "latex_block" },+ { pattern: /^#{1,6}\s+.+$/gm, kind: "markdown_heading" },+ { pattern: /^\s*\|.*\|\s*$/gm, kind: "markdown_table" },+ { pattern: /^\s*\|?\s*:?-{3,}:?\s*(?:\|\s*:?-{3,}:?\s*)+\|?\s*$/gm, kind: "markdown_table" },+ { pattern: /^\s*#(?:set|show|let|import|include)\b.+$/gm, kind: "typst_directive" },+ { pattern: /`[^`\n]+`/g, kind: "inline_code" },+ { pattern: /\[[^\]\n]+\]\([^) \n]+(?:\s+"[^"]*")?\)/g, kind: "markdown_link" },+ { pattern: /\bhttps?:\/\/[^\s)\]"'>]+/gi, kind: "url" },+ { pattern: /\b[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+\b/g, kind: "const_case" },+ { pattern: /\bprocess\.env\.[A-Za-z_][A-Za-z0-9_]*\b/g, kind: "env_var" },+ { pattern: /\$[A-Z_][A-Z0-9_]*\b/g, kind: "env_var" },+ { pattern: /\b\d+(?:\.\d+){1,3}(?:[-+][A-Za-z0-9.-]+)?\b/g, kind: "version" },+ { pattern: /\b[a-zA-Z_$][\w$]*(?:\.[a-zA-Z_$][\w$]*)+\(\)?/g, kind: "dotted_identifier" },+ { pattern: /\b[A-Za-z_$][\w$]*\s*\([^()\n]*\)/g, kind: "function_call" },+ {+ pattern: /(?:^|\s)(?:\.{0,2}\/[A-Za-z0-9_@./-]+|[A-Za-z]:\\[A-Za-z0-9_.\\/-]+)/g,+ kind: "file_path",+ },+ {+ pattern:+ /\b(?:TypeError|ReferenceError|SyntaxError|RangeError|URIError|EvalError|Error|Exception):[^\n]+/g,+ kind: "error_message",+ },+ ];++ for (const { pattern, kind } of [...builtIns, ...compileUserPatterns(options.preservePatterns)]) {+ result = replacePattern(result, ensureGlobal(pattern), kind, addBlock);+ }return { text: result, blocks };}+function extractFrontmatter(+ text: string,+ addBlock: (content: string, kind: string) => string+): string {+ if (!text.startsWith("---\n")) return text;+ const close = text.indexOf("\n---", 4);+ if (close === -1) return text;+ const closeEnd = text.indexOf("\n", close + 4);+ const end = closeEnd === -1 ? text.length : closeEnd + 1;+ return `${addBlock(text.slice(0, end), "frontmatter")}${text.slice(end)}`;+}+function extractFencedCodeBlocks(text: string, addBlock: (content: string) => string): string {+ const lines = text.match(/[^\n]*(?:\n|$)/g) ?? [text];let output = "";- let cursor = 0;-- while (cursor < text.length) {- const start = text.indexOf("```", cursor);- if (start === -1) {- output += text.slice(cursor);- break;+ let i = 0;++ while (i < lines.length) {+ const line = lines[i];+ if (line === "" && i === lines.length - 1) break;+ const opening = line.match(/^([ \t]{0,3})(`{3,}|~{3,})[^\n]*(?:\n|$)/);+ if (!opening) {+ output += line;+ i++;+ continue;}- const openingLineEnd = text.indexOf("\n", start + 3);- if (openingLineEnd === -1) {- output += text.slice(cursor);- break;+ const fence = opening[2];+ const fenceChar = fence[0];+ const minLen = fence.length;+ let block = line;+ let j = i + 1;+ let closed = false;++ while (j < lines.length) {+ const candidate = lines[j];+ block += candidate;+ const closeMatch = candidate.match(/^([ \t]{0,3})(`{3,}|~{3,})\s*(?:\n|$)/);+ if (closeMatch && closeMatch[2][0] === fenceChar && closeMatch[2].length >= minLen) {+ closed = true;+ break;+ }+ j++;}- const closeStart = text.indexOf("\n```", openingLineEnd + 1);- if (closeStart === -1) {- output += text.slice(cursor);- break;+ if (!closed) {+ output += line;+ i++;+ continue;}- const closeEnd = closeStart + 4;- output += text.slice(cursor, start);- output += addBlock(text.slice(start, closeEnd));- cursor = closeEnd;+ output += addBlock(block);+ i = j + 1;}return output;@@ -75,11 +186,14 @@ function extractFencedCodeBlocks(text: string, addBlock: (content: string) => stexport function restorePreservedBlocks(text: string, blocks: PreservedBlock[]): string {let result = text;for (const block of blocks) {- result = result.replace(block.placeholder, () => block.content);+ result = result.split(block.placeholder).join(block.content);}return result;}export function shouldPreserve(text: string, preservePatterns: RegExp[]): boolean {- return preservePatterns.some((pattern) => pattern.test(text));+ return preservePatterns.some((pattern) => {+ pattern.lastIndex = 0;+ return pattern.test(text);+ });}diff --git a/open-sse/services/compression/progressiveAging.ts b/open-sse/services/compression/progressiveAging.tsindex 2b742ecf9f..f9f5399a60 100644--- a/open-sse/services/compression/progressiveAging.ts+++ b/open-sse/services/compression/progressiveAging.ts@@ -2,6 +2,7 @@ import type { AgingThresholds, Summarizer } from "./types.ts";import { DEFAULT_AGGRESSIVE_CONFIG } from "./types.ts";import { applyLiteCompression } from "./lite.ts";import { cavemanCompress } from "./caveman.ts";+import { extractTextContent, replaceTextContent, type ChatMessageLike } from "./messageContent.ts";const COMPRESSED_MARKER_RE = /^\[COMPRESSED:/;@@ -9,43 +10,24 @@ function estimateTokens(text: string): number {return Math.ceil(text.length / 4);}-interface ChatMessage {- role: string;- content?: string | Array<{ type: string; text?: string }>;-}--function extractText(content?: string | Array<{ type: string; text?: string }>): string {- if (typeof content === "string") return content;- if (Array.isArray(content)) {- return content- .filter(- (p): p is { type: string; text?: string } =>- typeof p === "object" && p !== null && "text" in p- )- .map((p) => p.text ?? "")- .join("\n");- }- return "";-}+type ChatMessage = ChatMessageLike;function setContent(msg: ChatMessage, newContent: string): ChatMessage {- if (typeof msg.content === "string") {- return { ...msg, content: newContent };- }- return { ...msg, content: [{ type: "text", text: newContent }] };+ return replaceTextContent(msg, newContent) as ChatMessage;}export function applyAging(messages: unknown[],thresholds?: AgingThresholds,- summarizer?: Summarizer+ summarizer?: Summarizer,+ preserveSystemPrompt = true): { messages: unknown[]; saved: number } {const t = thresholds ?? DEFAULT_AGGRESSIVE_CONFIG.thresholds;const sum = summarizer ?? {summarize: (msgs: unknown[]) => {const typed = msgs as ChatMessage[];const last = typed.filter((m) => m.role === "assistant").pop();- return last ? extractText(last.content).slice(0, 200) : "";+ return last ? extractTextContent(last.content).slice(0, 200) : "";},};@@ -58,9 +40,9 @@ export function applyAging(for (let i = 0; i < typed.length; i++) {const msg = typed[i];- const text = extractText(msg.content);+ const text = extractTextContent(msg.content);- if (COMPRESSED_MARKER_RE.test(text)) {+ if ((preserveSystemPrompt && msg.role === "system") || COMPRESSED_MARKER_RE.test(text)) {result.push(msg);continue;}@@ -75,7 +57,7 @@ export function applyAging(const newContent =typeof compressed.body.messages[0].content === "string"? compressed.body.messages[0].content- : extractText(compressed.body.messages[0].content);+ : extractTextContent(compressed.body.messages[0].content);const tagged = `[COMPRESSED:aging:light] ${newContent}`;saved += estimateTokens(text) - estimateTokens(tagged);result.push(setContent(msg, tagged));@@ -88,7 +70,7 @@ export function applyAging(const newContent =typeof compressed.body.messages[0].content === "string"? compressed.body.messages[0].content- : extractText(compressed.body.messages[0].content);+ : extractTextContent(compressed.body.messages[0].content);const tagged = `[COMPRESSED:aging:moderate] ${newContent}`;saved += estimateTokens(text) - estimateTokens(tagged);result.push(setContent(msg, tagged));diff --git a/open-sse/services/compression/strategySelector.ts b/open-sse/services/compression/strategySelector.tsindex 59164c8ce9..7419f4d538 100644--- a/open-sse/services/compression/strategySelector.ts+++ b/open-sse/services/compression/strategySelector.ts@@ -32,7 +32,7 @@ export function getEffectiveMode(const comboMode = checkComboOverride(config, comboId);if (comboMode) return comboMode;- if (shouldAutoTrigger(config, estimatedTokens)) return "lite";+ if (shouldAutoTrigger(config, estimatedTokens)) return config.autoTriggerMode ?? "lite";return config.defaultMode;}@@ -65,13 +65,23 @@ export function applyCompression(return { body, compressed: false, stats: null };}if (mode === "lite") {- return applyLiteCompression(body, options);+ return applyLiteCompression(body, {+ ...options,+ preserveSystemPrompt: options?.config?.preserveSystemPrompt !== false,+ });}if (mode === "standard") {- return cavemanCompress(- body as Parameters<typeof cavemanCompress>[0],- options?.config?.cavemanConfig- );+ const cavemanConfig = {+ ...(options?.config?.cavemanConfig ?? {}),+ ...(options?.config?.preserveSystemPrompt !== false+ ? {+ compressRoles: (options?.config?.cavemanConfig?.compressRoles ?? ["user"]).filter(+ (role) => role !== "system"+ ),+ }+ : {}),+ };+ return cavemanCompress(body as Parameters<typeof cavemanCompress>[0], cavemanConfig);}if (mode === "aggressive") {const messages = (body.messages ?? []) as Array<{@@ -82,7 +92,10 @@ export function applyCompression(if (!Array.isArray(messages) || messages.length === 0) {return { body, compressed: false, stats: null };}- const aggressiveConfig = options?.config?.aggressive;+ const aggressiveConfig = {+ ...(options?.config?.aggressive ?? {}),+ preserveSystemPrompt: options?.config?.preserveSystemPrompt !== false,+ };const result = compressAggressive(messages, aggressiveConfig);const compressedBody = { ...body, messages: result.messages };return {@@ -107,8 +120,11 @@ export function applyCompression(if (!Array.isArray(messages) || messages.length === 0) {return { body, compressed: false, stats: null };}- const ultraConfig = options?.config?.ultra;- const result = ultraCompress(messages, ultraConfig ?? {});+ const ultraConfig = {+ ...(options?.config?.ultra ?? {}),+ preserveSystemPrompt: options?.config?.preserveSystemPrompt !== false,+ };+ const result = ultraCompress(messages, ultraConfig);const compressedBody = { ...body, messages: result.messages };return {body: compressedBody,diff --git a/open-sse/services/compression/types.ts b/open-sse/services/compression/types.tsindex f019f62bc6..443cc93fdf 100644--- a/open-sse/services/compression/types.ts+++ b/open-sse/services/compression/types.ts@@ -9,6 +9,7 @@*/export type CompressionMode = "off" | "lite" | "standard" | "aggressive" | "ultra";+export type CavemanIntensity = "lite" | "full" | "ultra";export interface CavemanRule {name: string;@@ -16,6 +17,9 @@ export interface CavemanRule {replacement: string | ((match: string, ...groups: string[]) => string);context: "all" | "user" | "system" | "assistant";preservePatterns?: RegExp[];+ category?: "filler" | "context" | "structural" | "dedup" | "terse" | "ultra";+ description?: string;+ minIntensity?: CavemanIntensity;}export interface CavemanConfig {@@ -24,16 +28,26 @@ export interface CavemanConfig {skipRules: string[];minMessageLength: number;preservePatterns: string[];+ intensity: CavemanIntensity;+}++export interface CavemanOutputModeConfig {+ enabled: boolean;+ intensity: CavemanIntensity;+ autoClarity: boolean;}export interface CompressionConfig {enabled: boolean;defaultMode: CompressionMode;+ autoTriggerMode?: CompressionMode;autoTriggerTokens: number;cacheMinutes: number;preserveSystemPrompt: boolean;+ mcpDescriptionCompressionEnabled?: boolean;comboOverrides: Record<string, CompressionMode>;cavemanConfig?: CavemanConfig;+ cavemanOutputMode?: CavemanOutputModeConfig;aggressive?: AggressiveConfig;ultra?: UltraConfig;}@@ -47,6 +61,16 @@ export interface CompressionStats {timestamp: number;rulesApplied?: string[];durationMs?: number;+ validationWarnings?: string[];+ validationErrors?: string[];+ fallbackApplied?: boolean;+ preservedBlockCount?: number;+ realUsage?: {+ promptTokens?: number;+ completionTokens?: number;+ totalTokens?: number;+ source: "provider" | "estimated" | "stream";+ };aggressive?: {summarizerSavings: number;toolResultSavings: number;@@ -63,9 +87,11 @@ export interface CompressionResult {export const DEFAULT_COMPRESSION_CONFIG: CompressionConfig = {enabled: false,defaultMode: "off",+ autoTriggerMode: "lite",autoTriggerTokens: 0,cacheMinutes: 5,preserveSystemPrompt: true,+ mcpDescriptionCompressionEnabled: true,comboOverrides: {},};@@ -75,6 +101,13 @@ export const DEFAULT_CAVEMAN_CONFIG: CavemanConfig = {skipRules: [],minMessageLength: 50,preservePatterns: [],+ intensity: "full",+};++export const DEFAULT_CAVEMAN_OUTPUT_MODE_CONFIG: CavemanOutputModeConfig = {+ enabled: false,+ intensity: "full",+ autoClarity: true,};/** Aging thresholds for progressive message degradation (Phase 3) */@@ -101,6 +134,7 @@ export interface AggressiveConfig {summarizerEnabled: boolean;maxTokensPerMessage: number;minSavingsThreshold: number;+ preserveSystemPrompt?: boolean;}/** Options for the Summarizer interface (Phase 3) */@@ -159,6 +193,7 @@ export interface UltraConfig {* 0 = always apply when mode is "ultra".*/maxTokensPerMessage: number;+ preserveSystemPrompt?: boolean;}export const DEFAULT_ULTRA_CONFIG: UltraConfig = {diff --git a/open-sse/services/compression/ultra.ts b/open-sse/services/compression/ultra.tsindex 0c1dd8d219..1fc3cc0fc2 100644--- a/open-sse/services/compression/ultra.ts+++ b/open-sse/services/compression/ultra.ts@@ -1,6 +1,7 @@import { pruneByScore } from "./ultraHeuristic.ts";import { DEFAULT_ULTRA_CONFIG } from "./types.ts";import type { UltraConfig, CompressionStats, CompressionMode } from "./types.ts";+import { extractTextContent, mapTextContent, type ChatMessageLike } from "./messageContent.ts";const COMPRESSED_PREFIX = "[COMPRESSED:";@@ -21,26 +22,7 @@ export interface UltraCompressResult {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- );-}+type Message = ChatMessageLike;export function ultraCompress(messages: Message[],@@ -57,21 +39,26 @@ export function ultraCompress(let compressedChars = 0;const compressed = messages.map((msg) => {- const text = extractText(msg.content);+ if (effectiveConfig.preserveSystemPrompt !== false && msg.role === "system") return msg;+ const text = extractTextContent(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;-- return {- ...msg,- content: applyTextToContent(msg.content, pruned),- };+ let messageOriginalChars = 0;+ let messageCompressedChars = 0;+ const next = mapTextContent(msg, (textPart) => {+ if (!textPart || textPart.startsWith(COMPRESSED_PREFIX)) return textPart;+ messageOriginalChars += textPart.length;+ const pruned = pruneByScore(textPart, compressionRate, minScoreThreshold);+ messageCompressedChars += pruned.length;+ return pruned;+ }) as Message;+ originalChars += messageOriginalChars;+ compressedChars += messageCompressedChars;+ return next;});const originalTokens = Math.ceil(originalChars / 4);diff --git a/open-sse/services/compression/validation.ts b/open-sse/services/compression/validation.tsnew file mode 100644index 0000000000..cd4c75629e--- /dev/null+++ b/open-sse/services/compression/validation.ts@@ -0,0 +1,132 @@+import { findFencedCodeBlocks } from "./preservation.ts";++export interface ValidationResult {+ valid: boolean;+ errors: string[];+ warnings: string[];+ fallbackApplied: boolean;+}++function collectMatches(text: string, pattern: RegExp): string[] {+ const matches: string[] = [];+ pattern.lastIndex = 0;+ let match: RegExpExecArray | null;+ while ((match = pattern.exec(text)) !== null) {+ if (match[0]) matches.push(match[0]);+ if (match.index === pattern.lastIndex) pattern.lastIndex++;+ }+ return matches;+}++function requireExactPresence(+ label: string,+ originalItems: string[],+ compressed: string,+ errors: string[]+) {+ for (const item of originalItems) {+ if (!compressed.includes(item)) {+ const preview = item.replace(/\s+/g, " ").slice(0, 80);+ errors.push(`${label} changed or missing: ${preview}`);+ }+ }+}++export function validateCompression(original: string, compressed: string): ValidationResult {+ const errors: string[] = [];+ const warnings: string[] = [];++ if (typeof original !== "string" || typeof compressed !== "string") {+ return {+ valid: false,+ errors: ["validation received non-string input"],+ warnings,+ fallbackApplied: true,+ };+ }++ if (original.length > 0 && compressed.trim().length === 0) {+ errors.push("compressed text is empty");+ }++ requireExactPresence("fenced code block", findFencedCodeBlocks(original), compressed, errors);+ requireExactPresence("inline code", collectMatches(original, /`[^`\n]+`/g), compressed, errors);+ requireExactPresence(+ "URL",+ collectMatches(original, /\bhttps?:\/\/[^\s)\]"'>]+/gi),+ compressed,+ errors+ );+ requireExactPresence(+ "markdown link",+ collectMatches(original, /\[[^\]\n]+\]\([^) \n]+(?:\s+"[^"]*")?\)/g),+ compressed,+ errors+ );+ requireExactPresence("frontmatter", collectFrontmatter(original), compressed, errors);+ requireExactPresence("heading", collectMatches(original, /^#{1,6}\s+.+$/gm), compressed, errors);+ requireExactPresence(+ "table row",+ collectMatches(original, /^\s*\|.*\|\s*$/gm),+ compressed,+ errors+ );+ requireExactPresence(+ "math block",+ collectMatches(original, /\$\$[\s\S]*?\$\$/g),+ compressed,+ errors+ );+ requireExactPresence(+ "inline math",+ collectMatches(original, /(?<!\$)\$(?![\s$\d])(?:\\.|[^$\n]){1,160}?(?<!\s)\$(?!\$)/g),+ compressed,+ errors+ );+ requireExactPresence(+ "LaTeX block",+ collectMatches(original, /\\begin\{[A-Za-z*]+\}[\s\S]*?\\end\{[A-Za-z*]+\}/g),+ compressed,+ errors+ );+ requireExactPresence(+ "version",+ collectMatches(original, /\b\d+(?:\.\d+){1,3}(?:[-+][A-Za-z0-9.-]+)?\b/g),+ compressed,+ errors+ );+ requireExactPresence(+ "CONST_CASE",+ collectMatches(original, /\b[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+\b/g),+ compressed,+ errors+ );++ const originalFenceCount = findFencedCodeBlocks(original).length;+ const compressedFenceCount = findFencedCodeBlocks(compressed).length;+ if (compressedFenceCount < originalFenceCount) {+ errors.push(+ `fenced code block count dropped: ${originalFenceCount} -> ${compressedFenceCount}`+ );+ }++ if (compressed.length > original.length) {+ warnings.push("compressed text is longer than original");+ }++ return {+ valid: errors.length === 0,+ errors,+ warnings,+ fallbackApplied: errors.length > 0,+ };+}++function collectFrontmatter(text: string): string[] {+ if (!text.startsWith("---\n")) return [];+ const close = text.indexOf("\n---", 4);+ if (close === -1) return [];+ const closeEnd = text.indexOf("\n", close + 4);+ const end = closeEnd === -1 ? text.length : closeEnd + 1;+ return [text.slice(0, end)];+}diff --git a/open-sse/utils/aiSdkCompat.ts b/open-sse/utils/aiSdkCompat.tsindex 5f0100b08f..58ff08b738 100644--- a/open-sse/utils/aiSdkCompat.ts+++ b/open-sse/utils/aiSdkCompat.ts@@ -23,9 +23,9 @@ export function resolveStreamFlag(bodyStream: unknown, acceptHeader: unknown): bif (bodyStream === true) return true;if (bodyStream === false) return false;- // No explicit stream param — default to false per OpenAI spec- // (Fixes #1873 - previously relied on Accept header heuristic)- return false;+ // No explicit stream param — preserve OmniRoute's streaming default unless+ // the client explicitly asks for JSON and does not also accept SSE.+ return !clientWantsJsonResponse(acceptHeader);}/**diff --git a/scripts/scratch/test-migrations.ts b/scripts/scratch/test-migrations.tsindex d908738b1d..f21ca16ca8 100644--- a/scripts/scratch/test-migrations.ts+++ b/scripts/scratch/test-migrations.ts@@ -1,47 +1,56 @@import Database from "better-sqlite3";-import fs from "fs";-import path from "path";+import { runMigrations, getMigrationStatus } from "../../src/lib/db/migrationRunner.js";-import { runMigrations, getMigrationStatus } from "../../src/lib/db/migrationRunner.ts";+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 db = new Database(":memory:");-db.exec(`- CREATE TABLE IF NOT EXISTS _omniroute_migrations (- version TEXT PRIMARY KEY,- name TEXT NOT NULL,- applied_at TEXT NOT NULL DEFAULT (datetime('now'))- );- INSERT INTO _omniroute_migrations (version, name) VALUES ('001', 'initial_schema');- INSERT INTO _omniroute_migrations (version, name) VALUES ('002', 'mcp_a2a_tables');- INSERT INTO _omniroute_migrations (version, name) VALUES ('003', 'provider_node_custom_paths');- INSERT INTO _omniroute_migrations (version, name) VALUES ('004', 'proxy_registry');- INSERT INTO _omniroute_migrations (version, name) VALUES ('005', 'combo_agent_fields');- INSERT INTO _omniroute_migrations (version, name) VALUES ('006', 'detailed_request_logs');- INSERT INTO _omniroute_migrations (version, name) VALUES ('007', 'search_request_type');- INSERT INTO _omniroute_migrations (version, name) VALUES ('008', 'registered_keys');- INSERT INTO _omniroute_migrations (version, name) VALUES ('009', 'requested_model');- INSERT INTO _omniroute_migrations (version, name) VALUES ('010', 'model_combo_mappings');- INSERT INTO _omniroute_migrations (version, name) VALUES ('011', 'webhooks');- INSERT INTO _omniroute_migrations (version, name) VALUES ('012', 'fix_token_input_cache_tokens');- INSERT INTO _omniroute_migrations (version, name) VALUES ('013', 'quota_snapshots');- INSERT INTO _omniroute_migrations (version, name) VALUES ('014', 'unified_log_artifacts');- INSERT INTO _omniroute_migrations (version, name) VALUES ('015', 'create_memories');- INSERT INTO _omniroute_migrations (version, name) VALUES ('016', 'create_skills');- INSERT INTO _omniroute_migrations (version, name) VALUES ('017', 'version_manager_upstream_proxy');- INSERT INTO _omniroute_migrations (version, name) VALUES ('018', 'call_logs_detailed_tokens');- INSERT INTO _omniroute_migrations (version, name) VALUES ('019', 'context_handoffs');- INSERT INTO _omniroute_migrations (version, name) VALUES ('020', 'combo_sort_order');- INSERT INTO _omniroute_migrations (version, name) VALUES ('021', 'combo_call_log_targets');- INSERT INTO _omniroute_migrations (version, name) VALUES ('026', 'call_logs_cache_source');- INSERT INTO _omniroute_migrations (version, name) VALUES ('029', 'provider_connection_max_concurrent');-`);--console.log("Status before:", getMigrationStatus(db));+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) {- console.error("Migration threw error:", e);+} catch (e: any) {+ console.error("Error:", e.message);}--console.log("Status after:", getMigrationStatus(db));+console.log(+ "Status after:",+ getMigrationStatus(db).pending.map((p) => p.version)+);diff --git a/src/app/(dashboard)/dashboard/analytics/CompressionAnalyticsTab.tsx b/src/app/(dashboard)/dashboard/analytics/CompressionAnalyticsTab.tsxindex 184eb936db..c0d08da196 100644--- a/src/app/(dashboard)/dashboard/analytics/CompressionAnalyticsTab.tsx+++ b/src/app/(dashboard)/dashboard/analytics/CompressionAnalyticsTab.tsx@@ -17,6 +17,17 @@ interface CompressionAnalyticsSummary {byMode: Record<string, { count: number; tokensSaved: number; avgSavingsPct: number }>;byProvider: Record<string, { count: number; tokensSaved: number }>;last24h: Array<{ hour: string; count: number; tokensSaved: number }>;+ validationFallbacks: number;+ realUsage: {+ requestsWithReceipts: number;+ promptTokens: number;+ completionTokens: number;+ totalTokens: number;+ cacheReadTokens: number;+ cacheWriteTokens: number;+ estimatedUsdSaved: number;+ bySource: Record<string, number>;+ };}function StatCard({@@ -178,7 +189,7 @@ export default function CompressionAnalyticsTab() {</div>{/* KPI Cards */}- <div className="grid grid-cols-2 md:grid-cols-4 gap-4">+ <div className="grid grid-cols-2 md:grid-cols-6 gap-4"><StatCardicon="compress"label="Total Requests"@@ -191,8 +202,65 @@ export default function CompressionAnalyticsTab() {/><StatCard icon="percent" label="Avg Savings" value={`${stats.avgSavingsPct}%`} /><StatCard icon="timer" label="Avg Duration" value={`${stats.avgDurationMs}ms`} />+ <StatCard+ icon="receipt_long"+ label="Receipts"+ value={stats.realUsage.requestsWithReceipts.toLocaleString()}+ sub={`${stats.realUsage.totalTokens.toLocaleString()} real tokens`}+ />+ <StatCard+ icon="verified"+ label="Fallbacks"+ value={stats.validationFallbacks.toLocaleString()}+ sub="validation restores"+ /></div>+ {stats.realUsage.requestsWithReceipts > 0 && (+ <div className="card p-5">+ <h3 className="font-semibold text-text mb-4 flex items-center gap-2">+ <span className="material-symbols-outlined text-primary text-[20px]">receipt_long</span>+ Real Usage Receipts+ </h3>+ <div className="grid grid-cols-1 md:grid-cols-5 gap-4 text-sm">+ <div>+ <div className="text-text-muted">Prompt tokens</div>+ <div className="text-lg font-semibold text-text">+ {stats.realUsage.promptTokens.toLocaleString()}+ </div>+ </div>+ <div>+ <div className="text-text-muted">Completion tokens</div>+ <div className="text-lg font-semibold text-text">+ {stats.realUsage.completionTokens.toLocaleString()}+ </div>+ </div>+ <div>+ <div className="text-text-muted">Total tokens</div>+ <div className="text-lg font-semibold text-text">+ {stats.realUsage.totalTokens.toLocaleString()}+ </div>+ </div>+ <div>+ <div className="text-text-muted">Cache tokens</div>+ <div className="text-lg font-semibold text-text">+ {(+ (stats.realUsage.cacheReadTokens ?? 0) + (stats.realUsage.cacheWriteTokens ?? 0)+ ).toLocaleString()}+ </div>+ </div>+ <div>+ <div className="text-text-muted">Sources</div>+ <div className="text-lg font-semibold text-text">+ {Object.entries(stats.realUsage.bySource)+ .map(([source, count]) => `${source}: ${count}`)+ .join(", ")}+ </div>+ </div>+ </div>+ </div>+ )}+{/* Mode Breakdown */}{modes.length > 0 && (<div className="card p-5">diff --git a/src/app/(dashboard)/dashboard/settings/components/CompressionSettingsTab.tsx b/src/app/(dashboard)/dashboard/settings/components/CompressionSettingsTab.tsxindex d6f4df413a..c072e37acf 100644--- a/src/app/(dashboard)/dashboard/settings/components/CompressionSettingsTab.tsx+++ b/src/app/(dashboard)/dashboard/settings/components/CompressionSettingsTab.tsx@@ -5,6 +5,7 @@ import { Card, Button } from "@/shared/components";import { useTranslations } from "next-intl";type CompressionMode = "off" | "lite" | "standard" | "aggressive" | "ultra";+type CavemanIntensity = "lite" | "full" | "ultra";interface CavemanConfig {enabled: boolean;@@ -12,6 +13,13 @@ interface CavemanConfig {skipRules: string[];minMessageLength: number;preservePatterns: string[];+ intensity: CavemanIntensity;+}++interface CavemanOutputModeConfig {+ enabled: boolean;+ intensity: CavemanIntensity;+ autoClarity: boolean;}interface AggressiveConfig {@@ -45,15 +53,26 @@ interface UltraConfig {interface CompressionConfig {enabled: boolean;defaultMode: CompressionMode;+ autoTriggerMode?: CompressionMode;autoTriggerTokens: number;cacheMinutes: number;preserveSystemPrompt: boolean;+ mcpDescriptionCompressionEnabled?: boolean;comboOverrides: Record<string, CompressionMode>;cavemanConfig?: CavemanConfig;+ cavemanOutputMode?: CavemanOutputModeConfig;aggressive?: AggressiveConfig;ultra?: UltraConfig;}+interface RuleMetadata {+ name: string;+ category: string;+ context: string;+ minIntensity: CavemanIntensity;+ description: string;+}+const MODES: { value: CompressionMode; labelKey: string; descKey: string; icon: string }[] = [{value: "off",@@ -93,38 +112,6 @@ const ROLE_OPTIONS: { value: "user" | "assistant" | "system"; labelKey: string }{ value: "system", labelKey: "compressionRoleSystem" },];-const ALL_CAVEMAN_RULES = [- "polite_framing",- "hedging",- "verbose_instructions",- "filler_adverbs",- "filler_phrases",- "redundant_openers",- "verbose_requests",- "self_reference",- "excessive_gratitude",- "qualifier_removal",- "compound_collapse",- "explanatory_prefix",- "question_to_directive",- "context_setup",- "intent_clarification",- "background_removal",- "meta_commentary",- "purpose_statement",- "list_conjunction",- "purpose_phrases",- "redundant_quantifiers",- "verbose_connectors",- "transition_removal",- "emphasis_removal",- "passive_voice",- "repeated_context",- "repeated_question",- "reestablished_context",- "summary_replacement",-];-export default function CompressionSettingsTab() {const t = useTranslations("settings");const [config, setConfig] = useState<CompressionConfig>({@@ -140,6 +127,12 @@ export default function CompressionSettingsTab() {skipRules: [],minMessageLength: 50,preservePatterns: [],+ intensity: "full",+ },+ cavemanOutputMode: {+ enabled: false,+ intensity: "full",+ autoClarity: true,},aggressive: {thresholds: { fullSummary: 5, moderate: 3, light: 2, verbatim: 2 },@@ -165,6 +158,7 @@ export default function CompressionSettingsTab() {const [saving, setSaving] = useState(false);const [loading, setLoading] = useState(true);const [status, setStatus] = useState<"" | "saved" | "error">("");+ const [ruleMetadata, setRuleMetadata] = useState<RuleMetadata[]>([]);useEffect(() => {fetch("/api/settings/compression")@@ -174,6 +168,12 @@ export default function CompressionSettingsTab() {}).catch(() => {}).finally(() => setLoading(false));+ fetch("/api/compression/rules")+ .then((r) => (r.ok ? r.json() : null))+ .then((data) => {+ if (Array.isArray(data?.rules)) setRuleMetadata(data.rules);+ })+ .catch(() => {});}, []);const save = async (updates: Partial<CompressionConfig>) => {@@ -326,6 +326,21 @@ export default function CompressionSettingsTab() {</div></label>+ <label className="flex items-center justify-between">+ <span className="text-sm text-text-muted">Auto trigger mode</span>+ <select+ value={config.autoTriggerMode ?? "lite"}+ onChange={(e) => save({ autoTriggerMode: e.target.value as CompressionMode })}+ className="w-36 px-2 py-1 text-sm rounded border border-border bg-surface text-text-main"+ >+ {MODES.filter((mode) => mode.value !== "off").map((mode) => (+ <option key={mode.value} value={mode.value}>+ {mode.value}+ </option>+ ))}+ </select>+ </label>+<label className="flex items-center justify-between"><span className="text-sm text-text-muted">{t("compressionCacheTTL")}</span><div className="flex items-center gap-2">@@ -356,6 +371,27 @@ export default function CompressionSettingsTab() {/></button></label>++ <label className="flex items-center justify-between">+ <span className="text-sm text-text-muted">MCP description compression</span>+ <button+ onClick={() =>+ save({+ mcpDescriptionCompressionEnabled:+ config.mcpDescriptionCompressionEnabled === false,+ })+ }+ className={`relative w-10 h-5 rounded-full transition-colors ${+ config.mcpDescriptionCompressionEnabled !== false ? "bg-green-500" : "bg-border"+ }`}+ >+ <span+ className={`absolute top-0.5 w-4 h-4 rounded-full bg-white transition-transform ${+ config.mcpDescriptionCompressionEnabled !== false ? "left-5" : "left-0.5"+ }`}+ />+ </button>+ </label></div>)}@@ -434,21 +470,42 @@ export default function CompressionSettingsTab() {/></label>+ <label className="flex items-center justify-between">+ <span className="text-sm text-text-muted">Caveman intensity</span>+ <select+ value={config.cavemanConfig.intensity}+ onChange={(e) =>+ save({+ cavemanConfig: {+ ...config.cavemanConfig!,+ intensity: e.target.value as CavemanIntensity,+ },+ })+ }+ className="w-28 px-2 py-1 text-sm rounded border border-border bg-surface text-text-main"+ >+ <option value="lite">lite</option>+ <option value="full">full</option>+ <option value="ultra">ultra</option>+ </select>+ </label>+<div className="space-y-2"><p className="text-sm text-text-muted">{t("compressionSkipRules")}</p><p className="text-xs text-text-muted">{t("compressionSkipRulesDesc")}</p><div className="grid grid-cols-2 sm:grid-cols-3 gap-1.5">- {ALL_CAVEMAN_RULES.map((rule) => (+ {ruleMetadata.map((rule) => (<button- key={rule}- onClick={() => toggleCavemanRule(rule)}+ key={rule.name}+ onClick={() => toggleCavemanRule(rule.name)}+ title={`${rule.category} · ${rule.context} · ${rule.minIntensity}`}className={`px-2 py-1 rounded text-xs border transition-all ${- config.cavemanConfig!.skipRules.includes(rule)+ config.cavemanConfig!.skipRules.includes(rule.name)? "border-red-500/50 bg-red-500/10 text-red-400 line-through": "border-border/50 text-text-muted hover:border-border"}`}>- {rule.replace(/_/g, " ")}+ {rule.name.replace(/_/g, " ")}</button>))}</div>@@ -482,6 +539,81 @@ export default function CompressionSettingsTab() {</div>)}+ {config.enabled && config.cavemanOutputMode && (+ <div className="space-y-3 pt-4 border-t border-border/30">+ <div className="flex items-center justify-between">+ <div>+ <h4 className="text-sm font-medium text-text-main">Caveman output mode</h4>+ <p className="text-xs text-text-muted mt-0.5">+ Injects terse response instructions without rewriting provider output.+ </p>+ </div>+ <button+ onClick={() =>+ save({+ cavemanOutputMode: {+ ...config.cavemanOutputMode!,+ enabled: !config.cavemanOutputMode!.enabled,+ },+ })+ }+ className={`relative w-10 h-5 rounded-full transition-colors ${+ config.cavemanOutputMode.enabled ? "bg-green-500" : "bg-border"+ }`}+ >+ <span+ className={`absolute top-0.5 w-4 h-4 rounded-full bg-white transition-transform ${+ config.cavemanOutputMode.enabled ? "left-5" : "left-0.5"+ }`}+ />+ </button>+ </div>++ <label className="flex items-center justify-between">+ <span className="text-sm text-text-muted">Output intensity</span>+ <select+ value={config.cavemanOutputMode.intensity}+ onChange={(e) =>+ save({+ cavemanOutputMode: {+ ...config.cavemanOutputMode!,+ intensity: e.target.value as CavemanIntensity,+ },+ })+ }+ className="w-28 px-2 py-1 text-sm rounded border border-border bg-surface text-text-main"+ >+ <option value="lite">lite</option>+ <option value="full">full</option>+ <option value="ultra">ultra</option>+ </select>+ </label>++ <label className="flex items-center justify-between">+ <span className="text-sm text-text-muted">Auto clarity bypass</span>+ <button+ onClick={() =>+ save({+ cavemanOutputMode: {+ ...config.cavemanOutputMode!,+ autoClarity: !config.cavemanOutputMode!.autoClarity,+ },+ })+ }+ className={`relative w-10 h-5 rounded-full transition-colors ${+ config.cavemanOutputMode.autoClarity ? "bg-green-500" : "bg-border"+ }`}+ >+ <span+ className={`absolute top-0.5 w-4 h-4 rounded-full bg-white transition-transform ${+ config.cavemanOutputMode.autoClarity ? "left-5" : "left-0.5"+ }`}+ />+ </button>+ </label>+ </div>+ )}+{config.enabled && config.defaultMode === "aggressive" && config.aggressive && (<div className="space-y-3 pt-4 border-t border-border/30"><div className="flex items-center justify-between">diff --git a/src/app/api/compression/preview/route.ts b/src/app/api/compression/preview/route.tsindex 5b966ec3f2..a4bd60a685 100644--- a/src/app/api/compression/preview/route.ts+++ b/src/app/api/compression/preview/route.ts@@ -3,6 +3,7 @@ import { z } from "zod";import { enforceApiKeyPolicy } from "@/shared/utils/apiKeyPolicy";import { applyCompression } from "@omniroute/open-sse/services/compression/strategySelector";import type { CompressionMode } from "@omniroute/open-sse/services/compression/types";+import { buildCompressionPreviewDiff } from "@omniroute/open-sse/services/compression/diffHelper";const PreviewRequestSchema = z.object({messages: z@@ -67,6 +68,7 @@ export async function POST(req: Request) {const tokensSaved = Math.max(0, originalTokens - compressedTokens);const savingsPct = originalTokens > 0 ? Math.round((tokensSaved / originalTokens) * 100) : 0;const techniquesUsed: string[] = result.stats?.techniquesUsed ?? [];+ const diff = buildCompressionPreviewDiff(originalText, compressedText, result.stats);return NextResponse.json({original: originalText,@@ -77,6 +79,23 @@ export async function POST(req: Request) {savingsPct,techniquesUsed,durationMs,+ mode,+ intensity: null,+ outputMode: null,+ skippedReasons: [],+ diff: diff.segments,+ preservedBlocks: diff.preservedBlocks,+ ruleRemovals: diff.ruleRemovals,+ rulesApplied: diff.ruleRemovals,+ validation: {+ valid: diff.validationErrors.length === 0,+ errors: diff.validationErrors,+ warnings: diff.validationWarnings,+ fallbackApplied: diff.fallbackApplied,+ },+ validationWarnings: diff.validationWarnings,+ validationErrors: diff.validationErrors,+ fallbackApplied: diff.fallbackApplied,});} catch (err: unknown) {const msg = err instanceof Error ? err.message : String(err);diff --git a/src/app/api/compression/rules/route.ts b/src/app/api/compression/rules/route.tsnew file mode 100644index 0000000000..e00093c8fa--- /dev/null+++ b/src/app/api/compression/rules/route.ts@@ -0,0 +1,12 @@+import { NextResponse } from "next/server";+import { enforceApiKeyPolicy } from "@/shared/utils/apiKeyPolicy";+import { getCavemanRuleMetadata } from "@omniroute/open-sse/services/compression/cavemanRules";++export async function GET(req: Request) {+ const policy = await enforceApiKeyPolicy(req, "settings");+ if (policy.rejection) return policy.rejection;++ return NextResponse.json({+ rules: getCavemanRuleMetadata(),+ });+}diff --git a/src/app/api/settings/compression/route.ts b/src/app/api/settings/compression/route.tsindex 4262eb5019..c6400cdea2 100644--- a/src/app/api/settings/compression/route.ts+++ b/src/app/api/settings/compression/route.ts@@ -5,6 +5,7 @@ import { isAuthenticated } from "@/shared/utils/apiAuth";import { isValidationFailure, validateBody } from "@/shared/validation/helpers";const compressionModeSchema = z.enum(["off", "lite", "standard", "aggressive", "ultra"]);+const cavemanIntensitySchema = z.enum(["lite", "full", "ultra"]);const cavemanConfigSchema = z.object({@@ -13,6 +14,15 @@ const cavemanConfigSchema = zskipRules: z.array(z.string()).optional(),minMessageLength: z.number().int().min(0).optional(),preservePatterns: z.array(z.string()).optional(),+ intensity: cavemanIntensitySchema.optional(),+ })+ .strict();++const cavemanOutputModeSchema = z+ .object({+ enabled: z.boolean().optional(),+ intensity: cavemanIntensitySchema.optional(),+ autoClarity: z.boolean().optional(),}).strict();@@ -56,11 +66,14 @@ const compressionSettingsUpdateSchema = z.object({enabled: z.boolean().optional(),defaultMode: compressionModeSchema.optional(),+ autoTriggerMode: compressionModeSchema.optional(),autoTriggerTokens: z.number().int().min(0).optional(),cacheMinutes: z.number().int().min(1).max(60).optional(),preserveSystemPrompt: z.boolean().optional(),+ mcpDescriptionCompressionEnabled: z.boolean().optional(),comboOverrides: z.record(z.string(), compressionModeSchema).optional(),cavemanConfig: cavemanConfigSchema.optional(),+ cavemanOutputMode: cavemanOutputModeSchema.optional(),aggressive: aggressiveConfigSchema.optional(),ultra: ultraConfigSchema.optional(),})diff --git a/src/lib/db/compression.ts b/src/lib/db/compression.tsindex 8d45f82f37..abbc8b1eb6 100644--- a/src/lib/db/compression.ts+++ b/src/lib/db/compression.ts@@ -4,10 +4,12 @@ import { invalidateDbCache } from "./readCache";import {DEFAULT_AGGRESSIVE_CONFIG,DEFAULT_CAVEMAN_CONFIG,+ DEFAULT_CAVEMAN_OUTPUT_MODE_CONFIG,DEFAULT_COMPRESSION_CONFIG,DEFAULT_ULTRA_CONFIG,type AggressiveConfig,type CavemanConfig,+ type CavemanOutputModeConfig,type CompressionConfig,type CompressionMode,type UltraConfig,@@ -47,6 +49,10 @@ function parseJsonSafe(raw: string | null): unknown {function normalizeCavemanConfig(value: unknown): CavemanConfig {const record = toRecord(value);+ const intensity =+ record.intensity === "lite" || record.intensity === "full" || record.intensity === "ultra"+ ? record.intensity+ : DEFAULT_CAVEMAN_CONFIG.intensity;return {...DEFAULT_CAVEMAN_CONFIG,...record,@@ -66,6 +72,26 @@ function normalizeCavemanConfig(value: unknown): CavemanConfig {preservePatterns: Array.isArray(record.preservePatterns)? record.preservePatterns.filter((pattern): pattern is string => typeof pattern === "string"): DEFAULT_CAVEMAN_CONFIG.preservePatterns,+ intensity,+ };+}++function normalizeCavemanOutputModeConfig(value: unknown): CavemanOutputModeConfig {+ const record = toRecord(value);+ return {+ ...DEFAULT_CAVEMAN_OUTPUT_MODE_CONFIG,+ enabled:+ typeof record.enabled === "boolean"+ ? record.enabled+ : DEFAULT_CAVEMAN_OUTPUT_MODE_CONFIG.enabled,+ intensity:+ record.intensity === "lite" || record.intensity === "full" || record.intensity === "ultra"+ ? record.intensity+ : DEFAULT_CAVEMAN_OUTPUT_MODE_CONFIG.intensity,+ autoClarity:+ typeof record.autoClarity === "boolean"+ ? record.autoClarity+ : DEFAULT_CAVEMAN_OUTPUT_MODE_CONFIG.autoClarity,};}@@ -196,6 +222,7 @@ export async function getCompressionSettings(): Promise<CompressionConfig> {const config: CompressionConfig = {...DEFAULT_COMPRESSION_CONFIG,cavemanConfig: { ...DEFAULT_CAVEMAN_CONFIG },+ cavemanOutputMode: { ...DEFAULT_CAVEMAN_OUTPUT_MODE_CONFIG },aggressive: normalizeAggressiveConfig(undefined),ultra: normalizeUltraConfig(undefined),};@@ -217,6 +244,11 @@ export async function getCompressionSettings(): Promise<CompressionConfig> {config.defaultMode = parsed as CompressionMode;}break;+ case "autoTriggerMode":+ if (typeof parsed === "string" && COMPRESSION_MODES.has(parsed as CompressionMode)) {+ config.autoTriggerMode = parsed as CompressionMode;+ }+ break;case "autoTriggerTokens":config.autoTriggerTokens =typeof parsed === "number" && Number.isFinite(parsed)@@ -232,6 +264,9 @@ export async function getCompressionSettings(): Promise<CompressionConfig> {case "preserveSystemPrompt":config.preserveSystemPrompt = parsed !== false;break;+ case "mcpDescriptionCompressionEnabled":+ config.mcpDescriptionCompressionEnabled = parsed !== false;+ break;case "comboOverrides":if (parsed && typeof parsed === "object") {const overrides: Record<string, CompressionMode> = {};@@ -246,6 +281,9 @@ export async function getCompressionSettings(): Promise<CompressionConfig> {case "cavemanConfig":config.cavemanConfig = normalizeCavemanConfig(parsed);break;+ case "cavemanOutputMode":+ config.cavemanOutputMode = normalizeCavemanOutputModeConfig(parsed);+ break;case "aggressive":case "aggressiveConfig":config.aggressive = normalizeAggressiveConfig(parsed);diff --git a/src/lib/db/compressionAnalytics.ts b/src/lib/db/compressionAnalytics.tsindex f587a915ae..950c18cd39 100644--- a/src/lib/db/compressionAnalytics.ts+++ b/src/lib/db/compressionAnalytics.ts@@ -11,6 +11,17 @@ export interface CompressionAnalyticsRow {tokens_saved: number;duration_ms?: number | null;request_id?: string | null;+ actual_prompt_tokens?: number | null;+ actual_completion_tokens?: number | null;+ actual_total_tokens?: number | null;+ actual_cache_read_tokens?: number | null;+ actual_cache_write_tokens?: number | null;+ estimated_usd_saved?: number | null;+ mcp_description_tokens_saved?: number | null;+ multimodal_skip_count?: number | null;+ receipt_source?: string | null;+ validation_fallback?: boolean | number | null;+ output_mode?: string | null;}export interface CompressionAnalyticsSummary {@@ -21,14 +32,85 @@ export interface CompressionAnalyticsSummary {byMode: Record<string, { count: number; tokensSaved: number; avgSavingsPct: number }>;byProvider: Record<string, { count: number; tokensSaved: number }>;last24h: Array<{ hour: string; count: number; tokensSaved: number }>;+ validationFallbacks: number;+ realUsage: {+ requestsWithReceipts: number;+ promptTokens: number;+ completionTokens: number;+ totalTokens: number;+ cacheReadTokens: number;+ cacheWriteTokens: number;+ estimatedUsdSaved: number;+ bySource: Record<string, number>;+ };+}++let columnsEnsured = false;++function ensureCompressionAnalyticsColumns(): void {+ if (columnsEnsured) return;+ const db = getDbInstance();+ const rows = db.prepare("PRAGMA table_info(compression_analytics)").all() as Array<{+ name: string;+ }>;+ const columns = new Set(rows.map((row) => row.name));+ const addColumn = (name: string, sql: string) => {+ if (!columns.has(name)) db.exec(sql);+ };+ addColumn(+ "actual_prompt_tokens",+ "ALTER TABLE compression_analytics ADD COLUMN actual_prompt_tokens INTEGER"+ );+ addColumn(+ "actual_completion_tokens",+ "ALTER TABLE compression_analytics ADD COLUMN actual_completion_tokens INTEGER"+ );+ addColumn(+ "actual_total_tokens",+ "ALTER TABLE compression_analytics ADD COLUMN actual_total_tokens INTEGER"+ );+ addColumn(+ "actual_cache_read_tokens",+ "ALTER TABLE compression_analytics ADD COLUMN actual_cache_read_tokens INTEGER"+ );+ addColumn(+ "actual_cache_write_tokens",+ "ALTER TABLE compression_analytics ADD COLUMN actual_cache_write_tokens INTEGER"+ );+ addColumn(+ "estimated_usd_saved",+ "ALTER TABLE compression_analytics ADD COLUMN estimated_usd_saved REAL"+ );+ addColumn(+ "mcp_description_tokens_saved",+ "ALTER TABLE compression_analytics ADD COLUMN mcp_description_tokens_saved INTEGER DEFAULT 0"+ );+ addColumn(+ "multimodal_skip_count",+ "ALTER TABLE compression_analytics ADD COLUMN multimodal_skip_count INTEGER DEFAULT 0"+ );+ addColumn("receipt_source", "ALTER TABLE compression_analytics ADD COLUMN receipt_source TEXT");+ addColumn(+ "validation_fallback",+ "ALTER TABLE compression_analytics ADD COLUMN validation_fallback INTEGER DEFAULT 0"+ );+ addColumn("output_mode", "ALTER TABLE compression_analytics ADD COLUMN output_mode TEXT");+ columnsEnsured = true;}export function insertCompressionAnalyticsRow(row: CompressionAnalyticsRow): void {const db = getDbInstance();+ ensureCompressionAnalyticsColumns();db.prepare(`- INSERT INTO compression_analytics (timestamp, combo_id, provider, mode, original_tokens, compressed_tokens, tokens_saved, duration_ms, request_id)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)+ INSERT INTO compression_analytics (+ timestamp, combo_id, provider, mode, original_tokens, compressed_tokens, tokens_saved,+ duration_ms, request_id, actual_prompt_tokens, actual_completion_tokens,+ actual_total_tokens, actual_cache_read_tokens, actual_cache_write_tokens,+ estimated_usd_saved, mcp_description_tokens_saved, multimodal_skip_count,+ receipt_source, validation_fallback, output_mode+ )+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(row.timestamp,@@ -39,12 +121,90 @@ export function insertCompressionAnalyticsRow(row: CompressionAnalyticsRow): voirow.compressed_tokens,row.tokens_saved,row.duration_ms ?? null,- row.request_id ?? null+ row.request_id ?? null,+ row.actual_prompt_tokens ?? null,+ row.actual_completion_tokens ?? null,+ row.actual_total_tokens ?? null,+ row.actual_cache_read_tokens ?? null,+ row.actual_cache_write_tokens ?? null,+ row.estimated_usd_saved ?? null,+ row.mcp_description_tokens_saved ?? 0,+ row.multimodal_skip_count ?? 0,+ row.receipt_source ?? null,+ row.validation_fallback ? 1 : 0,+ row.output_mode ?? null+ );+}++export function attachCompressionUsageReceipt(+ requestId: string | null | undefined,+ usage: Record<string, unknown> | null | undefined,+ source: "provider" | "estimated" | "stream" = "provider"+): void {+ if (!requestId || !usage || typeof usage !== "object") return;+ const promptTokens = toFiniteInt(usage.prompt_tokens);+ const completionTokens = toFiniteInt(usage.completion_tokens);+ const totalTokens =+ toFiniteInt(usage.total_tokens) ?? (promptTokens ?? 0) + (completionTokens ?? 0);+ const promptDetails =+ usage.prompt_tokens_details && typeof usage.prompt_tokens_details === "object"+ ? (usage.prompt_tokens_details as Record<string, unknown>)+ : {};+ const cacheReadTokens = toFiniteInt(+ usage.cache_read_input_tokens ?? usage.cached_tokens ?? promptDetails.cached_tokens+ );+ const cacheWriteTokens = toFiniteInt(+ usage.cache_creation_input_tokens ?? promptDetails.cache_creation_tokens+ );+ if (promptTokens === null && completionTokens === null && totalTokens <= 0) return;++ const db = getDbInstance();+ ensureCompressionAnalyticsColumns();+ db.prepare(+ `+ UPDATE compression_analytics+ SET actual_prompt_tokens = ?,+ actual_completion_tokens = ?,+ actual_total_tokens = ?,+ actual_cache_read_tokens = ?,+ actual_cache_write_tokens = ?,+ receipt_source = ?+ WHERE request_id = ?+ AND id = (+ SELECT id FROM compression_analytics+ WHERE request_id = ?+ ORDER BY id DESC+ LIMIT 1+ )+ `+ ).run(+ promptTokens,+ completionTokens,+ totalTokens,+ cacheReadTokens,+ cacheWriteTokens,+ source,+ requestId,+ requestId);}+function toFiniteInt(value: unknown): number | null {+ if (typeof value === "number" && Number.isFinite(value)) return Math.max(0, Math.floor(value));+ if (typeof value === "string" && value.trim()) {+ const parsed = Number(value);+ if (Number.isFinite(parsed)) return Math.max(0, Math.floor(parsed));+ }+ return null;+}++function appendCondition(whereClause: string, condition: string): string {+ return whereClause ? `${whereClause} AND ${condition}` : `WHERE ${condition}`;+}+export function getCompressionAnalyticsSummary(since?: string): CompressionAnalyticsSummary {const db = getDbInstance();+ ensureCompressionAnalyticsColumns();let cutoff: string | null = null;if (since === "24h") {@@ -136,6 +296,62 @@ export function getCompressionAnalyticsSummary(since?: string): CompressionAnalyconst last24h = Array.from(last24hMap.values());+ const receiptRows = db+ .prepare(+ `+ SELECT receipt_source as source, COUNT(*) as cnt,+ COALESCE(SUM(actual_prompt_tokens), 0) as prompt,+ COALESCE(SUM(actual_completion_tokens), 0) as completion,+ COALESCE(SUM(actual_total_tokens), 0) as total,+ COALESCE(SUM(actual_cache_read_tokens), 0) as cacheRead,+ COALESCE(SUM(actual_cache_write_tokens), 0) as cacheWrite,+ COALESCE(SUM(estimated_usd_saved), 0) as usdSaved+ FROM compression_analytics ${appendCondition(whereClause, "receipt_source IS NOT NULL")}+ GROUP BY receipt_source+ `+ )+ .all(...params) as Array<{+ source: string | null;+ cnt: number;+ prompt: number;+ completion: number;+ total: number;+ cacheRead: number;+ cacheWrite: number;+ usdSaved: number;+ }>;++ const realUsage = {+ requestsWithReceipts: 0,+ promptTokens: 0,+ completionTokens: 0,+ totalTokens: 0,+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ estimatedUsdSaved: 0,+ bySource: {} as Record<string, number>,+ };+ for (const row of receiptRows) {+ const source = row.source ?? "unknown";+ realUsage.requestsWithReceipts += row.cnt;+ realUsage.promptTokens += row.prompt;+ realUsage.completionTokens += row.completion;+ realUsage.totalTokens += row.total;+ realUsage.cacheReadTokens += row.cacheRead;+ realUsage.cacheWriteTokens += row.cacheWrite;+ realUsage.estimatedUsdSaved += row.usdSaved;+ realUsage.bySource[source] = row.cnt;+ }++ const fallbackRow = db+ .prepare(+ `+ SELECT COUNT(*) as cnt+ FROM compression_analytics ${appendCondition(whereClause, "validation_fallback = 1")}+ `+ )+ .get(...params) as { cnt: number } | undefined;+return {totalRequests: scalar?.total ?? 0,totalTokensSaved: scalar?.totalSaved ?? 0,@@ -144,5 +360,7 @@ export function getCompressionAnalyticsSummary(since?: string): CompressionAnalybyMode,byProvider,last24h,+ validationFallbacks: fallbackRow?.cnt ?? 0,+ realUsage,};}diff --git a/src/lib/db/migrationRunner.ts b/src/lib/db/migrationRunner.tsindex 338d7aa9ec..307eb4e03b 100644--- a/src/lib/db/migrationRunner.ts+++ b/src/lib/db/migrationRunner.ts@@ -266,6 +266,15 @@ function isSchemaAlreadyApplied(return hasColumn(db, "provider_connections", "max_concurrent");case "040":return hasColumn(db, "proxy_registry", "source");+ case "041":+ return (+ hasColumn(db, "compression_analytics", "actual_prompt_tokens") &&+ hasColumn(db, "compression_analytics", "actual_completion_tokens") &&+ hasColumn(db, "compression_analytics", "actual_total_tokens") &&+ hasColumn(db, "compression_analytics", "receipt_source") &&+ hasColumn(db, "compression_analytics", "validation_fallback") &&+ hasColumn(db, "compression_analytics", "output_mode")+ );default:return false;}@@ -299,6 +308,82 @@ function applySearchRequestTypeMigration(db: Database.Database): void {db.exec("CREATE INDEX IF NOT EXISTS idx_call_logs_request_type ON call_logs(request_type);");}+function applyCompressionReceiptsMigration(db: Database.Database): void {+ ensureColumn(+ db,+ "compression_analytics",+ "actual_prompt_tokens",+ "ALTER TABLE compression_analytics ADD COLUMN actual_prompt_tokens INTEGER"+ );+ ensureColumn(+ db,+ "compression_analytics",+ "actual_completion_tokens",+ "ALTER TABLE compression_analytics ADD COLUMN actual_completion_tokens INTEGER"+ );+ ensureColumn(+ db,+ "compression_analytics",+ "actual_total_tokens",+ "ALTER TABLE compression_analytics ADD COLUMN actual_total_tokens INTEGER"+ );+ ensureColumn(+ db,+ "compression_analytics",+ "actual_cache_read_tokens",+ "ALTER TABLE compression_analytics ADD COLUMN actual_cache_read_tokens INTEGER"+ );+ ensureColumn(+ db,+ "compression_analytics",+ "actual_cache_write_tokens",+ "ALTER TABLE compression_analytics ADD COLUMN actual_cache_write_tokens INTEGER"+ );+ ensureColumn(+ db,+ "compression_analytics",+ "estimated_usd_saved",+ "ALTER TABLE compression_analytics ADD COLUMN estimated_usd_saved REAL"+ );+ ensureColumn(+ db,+ "compression_analytics",+ "mcp_description_tokens_saved",+ "ALTER TABLE compression_analytics ADD COLUMN mcp_description_tokens_saved INTEGER DEFAULT 0"+ );+ ensureColumn(+ db,+ "compression_analytics",+ "multimodal_skip_count",+ "ALTER TABLE compression_analytics ADD COLUMN multimodal_skip_count INTEGER DEFAULT 0"+ );+ ensureColumn(+ db,+ "compression_analytics",+ "receipt_source",+ "ALTER TABLE compression_analytics ADD COLUMN receipt_source TEXT"+ );+ ensureColumn(+ db,+ "compression_analytics",+ "validation_fallback",+ "ALTER TABLE compression_analytics ADD COLUMN validation_fallback INTEGER DEFAULT 0"+ );+ ensureColumn(+ db,+ "compression_analytics",+ "output_mode",+ "ALTER TABLE compression_analytics ADD COLUMN output_mode TEXT"+ );++ db.exec(`+ CREATE INDEX IF NOT EXISTS idx_compression_analytics_request_id+ ON compression_analytics(request_id);+ CREATE INDEX IF NOT EXISTS idx_compression_analytics_receipt_source+ ON compression_analytics(receipt_source);+ `);+}+function inferPhysicalSchemaBaseline(db: Database.Database): {version: string;description: string;@@ -641,6 +726,8 @@ export function runMigrations(db: Database.Database, options?: { isNewDb?: boole);} else if (migration.version === "032") {applyApiKeyLifecycleMigration(db);+ } else if (migration.version === "041") {+ applyCompressionReceiptsMigration(db);} else {const sql = fs.readFileSync(migration.path, "utf-8");db.exec(sql);diff --git a/src/lib/db/migrations/041_compression_receipts.sql b/src/lib/db/migrations/041_compression_receipts.sqlnew file mode 100644index 0000000000..5e4c4a9ee3--- /dev/null+++ b/src/lib/db/migrations/041_compression_receipts.sql@@ -0,0 +1,18 @@+-- 041: Add real usage receipt fields to compression analytics.++ALTER TABLE compression_analytics ADD COLUMN actual_prompt_tokens INTEGER;+ALTER TABLE compression_analytics ADD COLUMN actual_completion_tokens INTEGER;+ALTER TABLE compression_analytics ADD COLUMN actual_total_tokens INTEGER;+ALTER TABLE compression_analytics ADD COLUMN actual_cache_read_tokens INTEGER;+ALTER TABLE compression_analytics ADD COLUMN actual_cache_write_tokens INTEGER;+ALTER TABLE compression_analytics ADD COLUMN estimated_usd_saved REAL;+ALTER TABLE compression_analytics ADD COLUMN mcp_description_tokens_saved INTEGER DEFAULT 0;+ALTER TABLE compression_analytics ADD COLUMN multimodal_skip_count INTEGER DEFAULT 0;+ALTER TABLE compression_analytics ADD COLUMN receipt_source TEXT;+ALTER TABLE compression_analytics ADD COLUMN validation_fallback INTEGER DEFAULT 0;+ALTER TABLE compression_analytics ADD COLUMN output_mode TEXT;++CREATE INDEX IF NOT EXISTS idx_compression_analytics_request_id+ ON compression_analytics(request_id);+CREATE INDEX IF NOT EXISTS idx_compression_analytics_receipt_source+ ON compression_analytics(receipt_source);diff --git a/tests/golden-set/compression-caveman-v2.test.ts b/tests/golden-set/compression-caveman-v2.test.tsnew file mode 100644index 0000000000..2256093162--- /dev/null+++ b/tests/golden-set/compression-caveman-v2.test.ts@@ -0,0 +1,85 @@+import { describe, it } from "node:test";+import assert from "node:assert/strict";+import { cavemanCompress } from "../../open-sse/services/compression/caveman.ts";+import { estimateCompressionTokens } from "../../open-sse/services/compression/stats.ts";++function compressText(text: string, intensity: "lite" | "full" | "ultra" = "full"): string {+ const result = cavemanCompress(+ { messages: [{ role: "user", content: text }] },+ {+ enabled: true,+ compressRoles: ["user"],+ skipRules: [],+ minMessageLength: 0,+ preservePatterns: [],+ intensity,+ }+ );+ return (result.body.messages[0].content as string) ?? text;+}++const verbosePrompts = [+ "Sure, I will make sure to provide a detailed explanation of the database connection issue because the application is currently creating a new connection for every request.",+ "Of course, I would be happy to help. You should make sure to validate the request body before the handler calls the downstream API.",+ "The reason is because the authentication middleware is being used before the token refresh function, and this creates a race condition.",+ "I was wondering if you could explain why the response object is actually being generated twice in the implementation.",+];++describe("Caveman v3.7.9 golden set", () => {+ it("compresses verbose model-style responses while preserving technical substance", () => {+ const compressed = compressText(verbosePrompts[0]);+ assert.doesNotMatch(compressed, /\bSure\b/i);+ assert.doesNotMatch(compressed, /\bI will\b/i);+ assert.match(compressed, /database connection issue/i);+ assert.match(compressed, /new connection/i);+ assert.match(compressed, /request/i);+ });++ it("preserves code blocks, URLs, paths, versions, and CONST_CASE", () => {+ const input = [+ "Please make sure to review the following code.",+ "```ts",+ "const API_KEY_VALUE = process.env.API_KEY_VALUE;",+ "```",+ "See https://example.com/the/api and /src/the/file.ts for version 3.7.9.",+ ].join("\n");+ const compressed = compressText(input);+ assert.match(compressed, /```ts\nconst API_KEY_VALUE = process\.env\.API_KEY_VALUE;\n```/);+ assert.match(compressed, /https:\/\/example\.com\/the\/api/);+ assert.match(compressed, /\/src\/the\/file\.ts/);+ assert.match(compressed, /3\.7\.9/);+ });++ it("preserves document structures, inline math, and multimodal text boundaries", () => {+ const input = [+ "---",+ "title: The Report",+ "---",+ "# The Heading",+ "Please make sure to keep $the value$ exact.",+ "| The Key | The Value |",+ "| --- | --- |",+ "| The row | The value |",+ ].join("\n");+ const compressed = compressText(input);+ assert.match(compressed, /^---\ntitle: The Report\n---/);+ assert.match(compressed, /^# The Heading/m);+ assert.match(compressed, /\$the value\$/);+ assert.match(compressed, /^\| The Key \| The Value \|/m);+ });++ it("achieves >35% average savings on verbose Caveman prompts", () => {+ const savings = verbosePrompts.map((prompt) => {+ const compressed = compressText(prompt);+ const before = estimateCompressionTokens(prompt);+ const after = estimateCompressionTokens(compressed);+ return ((before - after) / before) * 100;+ });+ const avg = savings.reduce((sum, value) => sum + value, 0) / savings.length;+ assert.ok(avg > 35, `Expected >35% average savings, got ${avg.toFixed(1)}%`);+ });++ it("keeps short clean messages readable", () => {+ assert.equal(compressText("Fix auth bug."), "Fix auth bug.");+ });+});diff --git a/tests/golden-set/compression-upstream-parity.test.ts b/tests/golden-set/compression-upstream-parity.test.tsnew file mode 100644index 0000000000..45b3e26209--- /dev/null+++ b/tests/golden-set/compression-upstream-parity.test.ts@@ -0,0 +1,92 @@+import { describe, it } from "node:test";+import assert from "node:assert/strict";+import { createRequire } from "node:module";+import path from "node:path";+import { cavemanCompress } from "../../open-sse/services/compression/caveman.ts";+import {+ compressDescriptionsInPlace,+ getMcpDescriptionCompressionStats,+ resetMcpDescriptionCompressionStats,+} from "../../open-sse/mcp-server/descriptionCompressor.ts";++const require = createRequire(import.meta.url);+const upstream = require(+ path.resolve("_references/_outros/caveman/mcp-servers/caveman-shrink/compress.js")+) as {+ compress(text: string): { compressed: string; before: number; after: number };+};++function omnirouteCompress(text: string): string {+ const result = cavemanCompress(+ { messages: [{ role: "user", content: text }] },+ {+ enabled: true,+ compressRoles: ["user"],+ skipRules: [],+ minMessageLength: 0,+ preservePatterns: [],+ intensity: "full",+ }+ );+ return result.body.messages[0].content as string;+}++const parityCases = [+ "The user is the owner of an account and should make sure to configure the database.",+ "Sure, this just basically returns the value from config.api.endpoint().",+ "I will perhaps connect to the database using API_KEY_VALUE and version 3.7.9.",+ "Read just the file at /tmp/the/just/file.txt and see https://example.com/the/api.",+];++describe("upstream Caveman parity benchmark", () => {+ it("matches core upstream shrink protections and savings direction", () => {+ for (const input of parityCases) {+ const ours = omnirouteCompress(input);+ const theirs = upstream.compress(input).compressed;+ assert.ok(ours.length <= input.length, `OmniRoute did not reduce: ${input}`);+ assert.ok(theirs.length <= input.length, `Upstream did not reduce: ${input}`);+ for (const protectedToken of [+ "config.api.endpoint()",+ "API_KEY_VALUE",+ "3.7.9",+ "/tmp/the/just/file.txt",+ "https://example.com/the/api",+ ]) {+ if (input.includes(protectedToken)) {+ assert.match(ours, new RegExp(protectedToken.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")));+ }+ }+ }+ });++ it("stays within upstream token budget on representative prose", () => {+ const input =+ "Sure, I will make sure to return the current weather for a given location and the temperature in Fahrenheit.";+ const ours = omnirouteCompress(input);+ const theirs = upstream.compress(input).compressed;+ assert.ok(+ ours.length <= Math.ceil(theirs.length * 1.2),+ `Expected OmniRoute within 20% of upstream shrink length. ours=${ours.length}, upstream=${theirs.length}`+ );+ });++ it("tracks MCP description shrink parity separately from prompt compression", () => {+ resetMcpDescriptionCompressionStats();+ const originalDescription =+ "The tool returns the current weather for a given location and the temperature in Fahrenheit.";+ const payload = {+ tools: [+ {+ name: "get_weather",+ description: originalDescription,+ },+ ],+ };++ compressDescriptionsInPlace(payload);+ const stats = getMcpDescriptionCompressionStats();+ assert.ok(payload.tools[0].description.length < originalDescription.length);+ assert.equal(stats.descriptionsCompressed, 1);+ assert.ok(stats.estimatedTokensSaved > 0);+ });+});diff --git a/tests/integration/chatcore-compression-integration.test.ts b/tests/integration/chatcore-compression-integration.test.tsindex 00cd119beb..8dc36291a9 100644--- a/tests/integration/chatcore-compression-integration.test.ts+++ b/tests/integration/chatcore-compression-integration.test.ts@@ -624,3 +624,76 @@ test("chatCore integration: modular compression records analytics row best-efforglobalThis.fetch = originalFetch;}});++test("chatCore integration: caveman output mode records analytics and receipts without prompt compression", async () => {+ const provider = "openai";+ const model = "gpt-4";++ await compressionDb.updateCompressionSettings({+ enabled: false,+ defaultMode: "off",+ autoTriggerTokens: 0,+ cavemanOutputMode: {+ enabled: true,+ intensity: "full",+ autoClarity: true,+ },+ });++ const connection = await providersDb.createProviderConnection({+ provider,+ apiKey: "test-key",+ isActive: true,+ });++ let capturedBody: any = null;+ globalThis.fetch = async (_url: string | URL | Request, init?: RequestInit) => {+ if (init?.body) {+ capturedBody = JSON.parse(init.body as string);+ }+ return new Response(+ JSON.stringify({+ choices: [{ message: { role: "assistant", content: "ok" } }],+ usage: { prompt_tokens: 20, completion_tokens: 4, total_tokens: 24 },+ }),+ {+ status: 200,+ headers: { "content-type": "application/json" },+ }+ );+ };++ try {+ const result = await handleChatCore({+ body: {+ model,+ stream: false,+ messages: [{ role: "user", content: "Summarize this implementation." }],+ },+ modelInfo: { provider, model },+ credentials: { apiKey: "test-key" },+ log: { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} },+ clientRawRequest: { endpoint: "/v1/chat/completions", headers: new Map() },+ connectionId: connection.id,+ });++ assert.ok(result.success, "Request should succeed");+ assert.match(capturedBody.messages[0].content, /Caveman Output Mode/);++ let summary = compressionAnalyticsDb.getCompressionAnalyticsSummary();+ for (+ let attempt = 0;+ attempt < 20 && (summary.totalRequests === 0 || summary.realUsage.requestsWithReceipts === 0);+ attempt += 1+ ) {+ await new Promise((resolve) => setTimeout(resolve, 10));+ summary = compressionAnalyticsDb.getCompressionAnalyticsSummary();+ }++ assert.equal(summary.byMode["output-caveman"].count, 1);+ assert.equal(summary.realUsage.requestsWithReceipts, 1);+ assert.equal(summary.realUsage.totalTokens, 24);+ } finally {+ globalThis.fetch = originalFetch;+ }+});diff --git a/tests/unit/compression/caveman-v379.test.ts b/tests/unit/compression/caveman-v379.test.tsnew file mode 100644index 0000000000..a5f04c3ceb--- /dev/null+++ b/tests/unit/compression/caveman-v379.test.ts@@ -0,0 +1,145 @@+import { describe, it } from "node:test";+import assert from "node:assert/strict";+import { cavemanCompress } from "../../../open-sse/services/compression/caveman.ts";+import { getRuleByName } from "../../../open-sse/services/compression/cavemanRules.ts";+import { applyCompression } from "../../../open-sse/services/compression/strategySelector.ts";++function compress(content: string, options = {}) {+ const result = cavemanCompress(+ { messages: [{ role: "user", content }] },+ {+ enabled: true,+ compressRoles: ["user"],+ skipRules: [],+ minMessageLength: 0,+ preservePatterns: [],+ intensity: "full",+ ...options,+ }+ );+ return result.body.messages[0].content as string;+}++describe("Caveman v3.7.9 rule parity", () => {+ it("removes articles, pleasantries, leader phrases, and redundant phrasing", () => {+ const text = compress(+ "Sure, I will make sure to explain the reason is because the function uses a database."+ );+ assert.doesNotMatch(text, /\bSure\b/i);+ assert.doesNotMatch(text, /^I will\b/i);+ assert.doesNotMatch(text, /\bmake sure to\b/i);+ assert.doesNotMatch(text, /\bthe reason is because\b/i);+ assert.doesNotMatch(text, /\bthe function\b/i);+ assert.match(text, /\bensure\b/i);+ assert.match(text, /\bbecause\b/i);+ assert.match(text, /\bdatabase\b/i);+ });++ it("recapitalizes sentence starts after removals", () => {+ const text = compress("Sure, the database connection fails. of course the fix is simple.");+ assert.match(text, /^Database/);+ assert.match(text, /\. Fix/);+ });++ it("supports intensity sub-levels for standard mode", () => {+ const lite = compress("The database request uses the response object.", { intensity: "lite" });+ const full = compress("The database request uses the response object.", { intensity: "full" });+ const ultra = compress("The database request uses the response object.", {+ intensity: "ultra",+ });++ assert.match(lite, /\bThe\b/);+ assert.doesNotMatch(full, /\bThe\b/);+ assert.match(ultra, /\bDB\b/);+ assert.match(ultra, /\breq\b/);+ assert.match(ultra, /\bres\b/);+ });++ it("keeps system prompts unchanged when preserveSystemPrompt is enabled", () => {+ const body = {+ messages: [+ {+ role: "system",+ content: "The assistant should make sure to preserve the detailed policy.",+ },+ {+ role: "user",+ content: "Please make sure to summarize the database response.",+ },+ ],+ };+ const result = applyCompression(body, "standard", {+ config: {+ enabled: true,+ defaultMode: "standard",+ autoTriggerMode: "standard",+ autoTriggerTokens: 0,+ cacheMinutes: 5,+ preserveSystemPrompt: true,+ comboOverrides: {},+ cavemanConfig: {+ enabled: true,+ compressRoles: ["system", "user"],+ skipRules: [],+ minMessageLength: 0,+ preservePatterns: [],+ intensity: "full",+ },+ },+ });++ const messages = result.body.messages as Array<{ role: string; content: string }>;+ assert.equal(messages[0].content, body.messages[0].content);+ assert.doesNotMatch(messages[1].content, /\bPlease\b/i);+ });++ it("preserves multimodal non-text parts in aggressive and ultra modes", () => {+ const body = {+ messages: [+ {+ role: "user",+ content: [+ { type: "text", text: "Please make sure to explain the database response.".repeat(20) },+ { type: "image_url", image_url: { url: "data:image/png;base64,abc" } },+ ],+ },+ ],+ };++ for (const mode of ["aggressive", "ultra"] as const) {+ const result = applyCompression(body, mode, {+ config: {+ enabled: true,+ defaultMode: mode,+ autoTriggerTokens: 0,+ cacheMinutes: 5,+ preserveSystemPrompt: true,+ comboOverrides: {},+ aggressive: undefined,+ ultra: {+ enabled: true,+ compressionRate: 0.5,+ minScoreThreshold: 0.3,+ slmFallbackToAggressive: true,+ maxTokensPerMessage: 0,+ },+ },+ });+ const content = (result.body.messages as typeof body.messages)[0].content;+ assert.ok(Array.isArray(content));+ assert.deepEqual(content[1], body.messages[0].content[1]);+ }+ });++ it("exposes metadata for new rule names", () => {+ for (const ruleName of [+ "articles",+ "pleasantries",+ "leader_phrases",+ "redundant_phrasing",+ "ultra_abbreviations",+ ]) {+ assert.ok(getRuleByName(ruleName), `missing rule ${ruleName}`);+ }+ });+});diff --git a/tests/unit/compression/compressionAnalytics.test.ts b/tests/unit/compression/compressionAnalytics.test.tsindex 7bfb290c01..0490ad8326 100644--- a/tests/unit/compression/compressionAnalytics.test.ts+++ b/tests/unit/compression/compressionAnalytics.test.ts@@ -11,6 +11,8 @@ const core = await import("../../../src/lib/db/core.ts");core.resetDbInstance();const { insertCompressionAnalyticsRow, getCompressionAnalyticsSummary } =await import("../../../src/lib/db/compressionAnalytics.ts");+const { attachCompressionUsageReceipt } =+ await import("../../../src/lib/db/compressionAnalytics.ts");const { getDbInstance } = core;describe("compressionAnalytics", () => {@@ -52,8 +54,20 @@ describe("compressionAnalytics", () => {avgDurationMs: 0,byMode: {},byProvider: {},- last24h: [],+ last24h: summary.last24h,+ validationFallbacks: 0,+ realUsage: {+ requestsWithReceipts: 0,+ promptTokens: 0,+ completionTokens: 0,+ totalTokens: 0,+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ estimatedUsdSaved: 0,+ bySource: {},+ },});+ assert.equal(summary.last24h.length, 24);});it("insert single row does not throw", () => {@@ -249,4 +263,57 @@ describe("compressionAnalytics", () => {assert(typeof bucket.tokensSaved === "number");});});++ it("attaches real usage receipts to the latest compression row", () => {+ insertCompressionAnalyticsRow({+ timestamp: new Date().toISOString(),+ mode: "standard",+ original_tokens: 1000,+ compressed_tokens: 700,+ tokens_saved: 300,+ request_id: "req-receipt",+ });+ attachCompressionUsageReceipt(+ "req-receipt",+ {+ prompt_tokens: 710,+ completion_tokens: 42,+ total_tokens: 752,+ prompt_tokens_details: { cached_tokens: 100, cache_creation_tokens: 12 },+ },+ "provider"+ );+ const summary = getCompressionAnalyticsSummary();+ assert.equal(summary.realUsage.requestsWithReceipts, 1);+ assert.equal(summary.realUsage.promptTokens, 710);+ assert.equal(summary.realUsage.completionTokens, 42);+ assert.equal(summary.realUsage.totalTokens, 752);+ assert.equal(summary.realUsage.cacheReadTokens, 100);+ assert.equal(summary.realUsage.cacheWriteTokens, 12);+ assert.equal(summary.realUsage.bySource.provider, 1);+ });++ it("summarizes validation fallback and output mode rows", () => {+ insertCompressionAnalyticsRow({+ timestamp: new Date().toISOString(),+ mode: "output-caveman",+ original_tokens: 900,+ compressed_tokens: 900,+ tokens_saved: 0,+ request_id: "req-output",+ validation_fallback: true,+ output_mode: "full",+ });+ attachCompressionUsageReceipt(+ "req-output",+ { prompt_tokens: 900, completion_tokens: 120, total_tokens: 1020 },+ "provider"+ );++ const summary = getCompressionAnalyticsSummary();+ assert.equal(summary.validationFallbacks, 1);+ assert.equal(summary.byMode["output-caveman"].count, 1);+ assert.equal(summary.realUsage.requestsWithReceipts, 1);+ assert.equal(summary.realUsage.totalTokens, 1020);+ });});diff --git a/tests/unit/compression/diffHelper.test.ts b/tests/unit/compression/diffHelper.test.tsnew file mode 100644index 0000000000..cbb424d838--- /dev/null+++ b/tests/unit/compression/diffHelper.test.ts@@ -0,0 +1,36 @@+import { describe, it } from "node:test";+import assert from "node:assert/strict";+import { buildCompressionPreviewDiff } from "../../../open-sse/services/compression/diffHelper.ts";++describe("compression preview diff", () => {+ it("reports diff segments, preserved blocks, rules, validation warnings, and fallback status", () => {+ const original = "Please use `exact_token` and the API.";+ const compressed = "Use `exact_token` and API.";+ const preview = buildCompressionPreviewDiff(original, compressed, {+ originalTokens: 10,+ compressedTokens: 6,+ savingsPercent: 40,+ techniquesUsed: ["caveman-rules"],+ mode: "standard",+ timestamp: Date.now(),+ rulesApplied: ["polite_framing", "articles"],+ validationWarnings: ["sample warning"],+ });++ assert.ok(preview.segments.some((segment) => segment.type === "removed"));+ assert.ok(preview.preservedBlocks.some((block) => block.kind === "inline_code"));+ assert.deepEqual(preview.ruleRemovals, ["polite_framing", "articles"]);+ assert.match(preview.validationWarnings.join("\n"), /sample warning/);+ assert.equal(preview.fallbackApplied, false);+ });++ it("reports validation errors for protected content loss", () => {+ const preview = buildCompressionPreviewDiff(+ "Use `exact_token` and https://example.com.",+ "Use token.",+ null+ );+ assert.equal(preview.fallbackApplied, true);+ assert.ok(preview.validationErrors.length >= 2);+ });+});diff --git a/tests/unit/compression/lite.test.ts b/tests/unit/compression/lite.test.tsindex c3119f2c5e..6070f7ea2d 100644--- a/tests/unit/compression/lite.test.ts+++ b/tests/unit/compression/lite.test.ts@@ -8,6 +8,7 @@ import {removeRedundantContent,replaceImageUrls,} from "../../../open-sse/services/compression/lite.ts";+import { applyCompression } from "../../../open-sse/services/compression/strategySelector.ts";describe("collapseWhitespace", () => {it("collapses 3+ newlines to 2", () => {@@ -192,6 +193,28 @@ describe("applyLiteCompression", () => {assert.ok(result.stats.savingsPercent > 0);});+ it("preserves system prompt text when preserveSystemPrompt is enabled", () => {+ const body = {+ messages: [+ { role: "system", content: "Policy. Keep exact.\n\n\nDo not change." },+ { role: "user", content: "Please normalize this.\n\n\nThanks." },+ ],+ };+ const result = applyCompression(body, "lite", {+ config: {+ enabled: true,+ defaultMode: "lite",+ autoTriggerTokens: 0,+ cacheMinutes: 5,+ preserveSystemPrompt: true,+ comboOverrides: {},+ },+ });+ const messages = result.body.messages as typeof body.messages;+ assert.equal(messages[0].content, body.messages[0].content);+ assert.notEqual(messages[1].content, body.messages[1].content);+ });+it("returns no compression for clean input", () => {const body = {messages: [{ role: "user", content: "clean message" }],diff --git a/tests/unit/compression/mcp-description-compressor.test.ts b/tests/unit/compression/mcp-description-compressor.test.tsnew file mode 100644index 0000000000..f9915b6748--- /dev/null+++ b/tests/unit/compression/mcp-description-compressor.test.ts@@ -0,0 +1,85 @@+import { describe, it } from "node:test";+import assert from "node:assert/strict";+import {+ compressDescriptionsInPlace,+ compressMcpDescription,+ getMcpDescriptionCompressionStats,+ maybeCompressMcpDescription,+ resetMcpDescriptionCompressionStats,+} from "../../../open-sse/mcp-server/descriptionCompressor.ts";++describe("MCP description compression", () => {+ it("compresses MCP-style descriptions while preserving substance", () => {+ const input =+ "Get the current weather for a given location. Returns the temperature in Fahrenheit. Please make sure to provide the location as a city name.";+ const result = compressMcpDescription(input);+ assert.ok(result.after < result.before);+ assert.match(result.compressed, /weather/i);+ assert.match(result.compressed, /Fahrenheit/i);+ assert.match(result.compressed, /city name/i);+ assert.doesNotMatch(result.compressed, /\bthe\b/i);+ });++ it("preserves code, URLs, paths, identifiers, and versions", () => {+ const input =+ "Call config.api.endpoint() with API_KEY_VALUE from /tmp/the/file.txt. See https://example.com/the/api for version 3.7.9.";+ const result = compressMcpDescription(input).compressed;+ assert.match(result, /config\.api\.endpoint\(\)/);+ assert.match(result, /API_KEY_VALUE/);+ assert.match(result, /\/tmp\/the\/file\.txt/);+ assert.match(result, /https:\/\/example\.com\/the\/api/);+ assert.match(result, /3\.7\.9/);+ });++ it("walks nested list metadata and skips non-string fields", () => {+ const payload = {+ result: {+ tools: [+ { name: "get_weather", description: "The function returns the weather for a city." },+ { name: "nested", inputSchema: { description: { not: "string" } } },+ ],+ },+ };+ compressDescriptionsInPlace(payload.result);+ assert.doesNotMatch(payload.result.tools[0].description, /\bthe\b/i);+ assert.deepEqual(payload.result.tools[1].inputSchema.description, { not: "string" });+ });++ it("honors settings and environment kill switches", () => {+ const originalEnv = process.env.OMNIROUTE_MCP_DESCRIPTION_COMPRESSION;+ const originalAliasEnv = process.env.OMNIROUTE_MCP_COMPRESS_DESCRIPTIONS;+ try {+ delete process.env.OMNIROUTE_MCP_DESCRIPTION_COMPRESSION;+ delete process.env.OMNIROUTE_MCP_COMPRESS_DESCRIPTIONS;+ const input = "The function returns the weather for a city.";+ assert.equal(maybeCompressMcpDescription(input, { enabled: false }), input);++ process.env.OMNIROUTE_MCP_COMPRESS_DESCRIPTIONS = "off";+ assert.equal(maybeCompressMcpDescription(input, { enabled: true }), input);+ } finally {+ if (originalEnv === undefined) {+ delete process.env.OMNIROUTE_MCP_DESCRIPTION_COMPRESSION;+ } else {+ process.env.OMNIROUTE_MCP_DESCRIPTION_COMPRESSION = originalEnv;+ }+ if (originalAliasEnv === undefined) {+ delete process.env.OMNIROUTE_MCP_COMPRESS_DESCRIPTIONS;+ } else {+ process.env.OMNIROUTE_MCP_COMPRESS_DESCRIPTIONS = originalAliasEnv;+ }+ }+ });++ it("records MCP description savings separately", () => {+ resetMcpDescriptionCompressionStats();+ const input =+ "The function returns the current weather for a city and the detailed forecast summary.";+ const output = maybeCompressMcpDescription(input, { enabled: true });+ const stats = getMcpDescriptionCompressionStats();++ assert.notEqual(output, input);+ assert.equal(stats.descriptionsCompressed, 1);+ assert.ok(stats.charsSaved > 0);+ assert.ok(stats.estimatedTokensSaved > 0);+ });+});diff --git a/tests/unit/compression/outputMode.test.ts b/tests/unit/compression/outputMode.test.tsnew file mode 100644index 0000000000..33de29d05e--- /dev/null+++ b/tests/unit/compression/outputMode.test.ts@@ -0,0 +1,89 @@+import { describe, it } from "node:test";+import assert from "node:assert/strict";+import {+ applyCavemanOutputMode,+ buildCavemanOutputInstruction,+ shouldBypassCavemanOutputMode,+} from "../../../open-sse/services/compression/outputMode.ts";++describe("Caveman output mode", () => {+ it("injects a system instruction without post-processing output", () => {+ const result = applyCavemanOutputMode(+ { messages: [{ role: "user", content: "Summarize this API response." }] },+ { enabled: true, intensity: "full", autoClarity: true }+ );+ assert.equal(result.applied, true);+ assert.equal(result.body.messages?.[0]?.role, "system");+ assert.match(String(result.body.messages?.[0]?.content), /Caveman Output Mode/);+ });++ it("appends to an existing system prompt", () => {+ const result = applyCavemanOutputMode(+ {+ messages: [+ { role: "system", content: "Follow tenant policy." },+ { role: "user", content: "Summarize logs." },+ ],+ },+ { enabled: true, intensity: "lite", autoClarity: true }+ );+ assert.equal(result.applied, true);+ assert.match(String(result.body.messages?.[0]?.content), /Follow tenant policy/);+ assert.match(String(result.body.messages?.[0]?.content), /Drop filler/);+ });++ it("does not inject the Caveman instruction twice", () => {+ const body = {+ messages: [+ { role: "system", content: "Follow tenant policy." },+ { role: "user", content: "Summarize logs." },+ ],+ };+ const once = applyCavemanOutputMode(body, {+ enabled: true,+ intensity: "full",+ autoClarity: true,+ }).body;+ const twice = applyCavemanOutputMode(once, {+ enabled: true,+ intensity: "full",+ autoClarity: true,+ });++ assert.equal(twice.applied, false);+ assert.equal(twice.skippedReason, "already_applied");+ const markerCount = String(twice.body.messages?.[0]?.content).match(+ /OmniRoute Caveman Output Mode/g+ )?.length;+ assert.equal(markerCount, 1);+ });++ it("does not modify user content", () => {+ const body = { messages: [{ role: "user", content: "Please explain this response." }] };+ const result = applyCavemanOutputMode(body, {+ enabled: true,+ intensity: "full",+ autoClarity: true,+ });+ assert.equal(result.body.messages?.at(-1)?.content, body.messages[0].content);+ });++ it("bypasses security, destructive, clarification, and order-sensitive prompts", () => {+ const cases = [+ "Explain this security vulnerability in detail.",+ "Delete all rows after backup confirmation.",+ "Can you clarify what this means?",+ "First backup then drop table during migration.",+ ];+ for (const content of cases) {+ assert.ok(shouldBypassCavemanOutputMode([{ role: "user", content }]), content);+ }+ });++ it("builds intensity-specific instructions", () => {+ assert.match(+ buildCavemanOutputInstruction({ enabled: true, intensity: "ultra", autoClarity: true }),+ /ultra terse/i+ );+ });+});diff --git a/tests/unit/compression/validation.test.ts b/tests/unit/compression/validation.test.tsnew file mode 100644index 0000000000..f20d8862e2--- /dev/null+++ b/tests/unit/compression/validation.test.ts@@ -0,0 +1,136 @@+import { describe, it } from "node:test";+import assert from "node:assert/strict";+import { validateCompression } from "../../../open-sse/services/compression/validation.ts";+import {+ extractPreservedBlocks,+ restorePreservedBlocks,+} from "../../../open-sse/services/compression/preservation.ts";+import { cavemanCompress } from "../../../open-sse/services/compression/caveman.ts";++describe("compression preservation and validation", () => {+ it("parses backtick and tilde fences with nested shorter fences", () => {+ const input = [+ "Before",+ "````markdown",+ "```js",+ "const theValue = 1;",+ "```",+ "````",+ "~~~ts",+ "const x = `the`;",+ "~~~",+ "After",+ ].join("\n");+ const { text, blocks } = extractPreservedBlocks(input);+ assert.equal(blocks.filter((block) => block.kind === "fenced_code").length, 2);+ assert.equal(restorePreservedBlocks(text, blocks), input);+ });++ it("uses collision-resistant sentinels instead of predictable placeholders", () => {+ const input = "User literal [PRESERVED_0] and `inline code` stay separate.";+ const { text, blocks } = extractPreservedBlocks(input);+ assert.ok(blocks.length > 0);+ assert.doesNotMatch(text, /\[PRESERVED_0\]/);+ assert.equal(restorePreservedBlocks(text, blocks), input);+ });++ it("preserves caveman-shrink protected identifiers and versions", () => {+ const input =+ "Set API_KEY_VALUE in process.env.API_KEY_VALUE before calling config.api.endpoint() on 3.7.9.";+ const output = cavemanCompress(+ { messages: [{ role: "user", content: input }] },+ {+ enabled: true,+ compressRoles: ["user"],+ skipRules: [],+ minMessageLength: 0,+ preservePatterns: [],+ intensity: "full",+ }+ ).body.messages[0].content as string;++ assert.match(output, /API_KEY_VALUE/);+ assert.match(output, /process\.env\.API_KEY_VALUE/);+ assert.match(output, /config\.api\.endpoint\(\)/);+ assert.match(output, /3\.7\.9/);+ });++ it("preserves Typst, LaTeX, frontmatter, headings, and markdown tables", () => {+ const input = [+ "---",+ "title: The Test",+ "---",+ "# The Heading",+ "| Column | Value |",+ "| --- | --- |",+ "| The key | The value |",+ "$$",+ "E = mc^2",+ "$$",+ "\\begin{align}a &= b\\end{align}",+ "#set text(size: 12pt)",+ "Please make sure to explain the document.",+ ].join("\n");+ const output = cavemanCompress(+ { messages: [{ role: "user", content: input }] },+ {+ enabled: true,+ compressRoles: ["user"],+ skipRules: [],+ minMessageLength: 0,+ preservePatterns: [],+ intensity: "full",+ }+ ).body.messages[0].content as string;++ assert.match(output, /^---\ntitle: The Test\n---/);+ assert.match(output, /^# The Heading/m);+ assert.match(output, /^\| Column \| Value \|/m);+ assert.match(output, /\$\$\nE = mc\^2\n\$\$/);+ assert.match(output, /\\begin\{align\}a &= b\\end\{align\}/);+ assert.match(output, /^#set text\(size: 12pt\)/m);+ });++ it("preserves inline math and ignores normal dollar amounts", () => {+ const input = "Please make sure to keep $the value$ exact and the cost as $10.";+ const output = cavemanCompress(+ { messages: [{ role: "user", content: input }] },+ {+ enabled: true,+ compressRoles: ["user"],+ skipRules: [],+ minMessageLength: 0,+ preservePatterns: [],+ intensity: "full",+ }+ ).body.messages[0].content as string;++ assert.match(output, /\$the value\$/);+ assert.match(output, /\$10/);+ });++ it("reports validation failure when protected content is lost", () => {+ const original = "Use `exact_token` and https://example.com/the/path.";+ const validation = validateCompression(original, "Use token.");+ assert.equal(validation.valid, false);+ assert.equal(validation.fallbackApplied, true);+ assert.ok(validation.errors.length >= 2);+ });++ it("falls back to original when validation detects structural loss", () => {+ const original = "Please make sure to use `the exact token` in the request.";+ const result = cavemanCompress(+ { messages: [{ role: "user", content: original }] },+ {+ enabled: true,+ compressRoles: ["user"],+ skipRules: [],+ minMessageLength: 0,+ preservePatterns: ["`[^`]+"],+ intensity: "full",+ }+ );+ const output = result.body.messages[0].content as string;+ assert.match(output, /`the exact token`/);+ });+});