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): implement caveman compression engine — Wave 1 complete
oyi77b5f6bea88002
diff --git a/open-sse/services/compression/caveman.ts b/open-sse/services/compression/caveman.tsnew file mode 100644index 0000000000..bdfd5e2beb--- /dev/null+++ b/open-sse/services/compression/caveman.ts@@ -0,0 +1,160 @@+import type { CavemanConfig, CavemanRule, CompressionResult, CompressionStats } from "./types.ts";+import { DEFAULT_CAVEMAN_CONFIG } from "./types.ts";+import { CAVEMAN_RULES, getRulesForContext } from "./cavemanRules.ts";+import { extractPreservedBlocks, restorePreservedBlocks } from "./preservation.ts";+import { createCompressionStats, estimateTokensForStats, trackCompressionStats } from "./stats.ts";++const CHARS_PER_TOKEN = 4;++interface ChatMessage {+ role: string;+ content?: string | Array<{ type: string; text?: string }>;+}++interface ChatRequestBody {+ messages?: ChatMessage[];+ [key: string]: unknown;+}++export function applyRulesToText(+ text: string,+ rules: CavemanRule[]+): { text: string; appliedRules: string[] } {+ let result = text;+ const appliedRules: string[] = [];++ for (const rule of rules) {+ const before = result;+ if (typeof rule.replacement === "function") {+ result = result.replace(rule.pattern, (...args) => {+ const match = args[0];+ return rule.replacement(match, ...args.slice(1, -2));+ });+ } else {+ result = result.replace(rule.pattern, rule.replacement);+ }+ if (result !== before) {+ appliedRules.push(rule.name);+ }+ }++ return { text: result, appliedRules };+}++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+$/, "");+ return result;+}++export function cavemanCompress(+ body: ChatRequestBody,+ options?: Partial<CavemanConfig>+): CompressionResult {+ const startMs = performance.now();+ const config: CavemanConfig = { ...DEFAULT_CAVEMAN_CONFIG, ...options };++ if (!config.enabled) {+ return {+ body,+ compressed: false,+ stats: createCompressionStats(0, 0, "caveman"),+ };+ }++ if (!body.messages || !Array.isArray(body.messages) || body.messages.length === 0) {+ return {+ body,+ compressed: false,+ stats: createCompressionStats(0, 0, "caveman"),+ };+ }++ let totalOriginalTokens = 0;+ let totalCompressedTokens = 0;+ const allAppliedRules: string[] = [];++ const compressedMessages = body.messages.map((msg): ChatMessage => {+ const contentStr =+ typeof msg.content === "string"+ ? msg.content+ : Array.isArray(msg.content)+ ? msg.content+ .map((part) => (part.type === "text" && part.text ? part.text : ""))+ .filter(Boolean)+ .join("\n")+ : "";++ totalOriginalTokens += estimateTokensForStats(contentStr);++ if (!contentStr || contentStr.length < config.minMessageLength) {+ totalCompressedTokens += estimateTokensForStats(contentStr);+ return msg;+ }++ if (!config.compressRoles.includes(msg.role as "user" | "assistant" | "system")) {+ totalCompressedTokens += estimateTokensForStats(contentStr);+ return msg;+ }++ // Step 1: Extract preserved blocks+ const { text: extractedText, blocks } = extractPreservedBlocks(contentStr);++ // Step 2: Apply rules by context+ const rules = getRulesForContext(msg.role).filter(+ (rule) => !config.skipRules.includes(rule.name)+ );+ const { text: rulesApplied, appliedRules } = applyRulesToText(extractedText, rules);+ allAppliedRules.push(...appliedRules);++ // Step 3: Restore preserved blocks+ const restored = restorePreservedBlocks(rulesApplied, blocks);++ // Step 4: Cleanup artifacts+ const cleaned = cleanupArtifacts(restored);++ totalCompressedTokens += estimateTokensForStats(cleaned);++ const newContent =+ typeof msg.content === "string"+ ? cleaned+ : Array.isArray(msg.content)+ ? msg.content.map((part) =>+ part.type === "text" && part.text ? { ...part, text: cleaned } : part+ )+ : msg.content;++ return { ...msg, content: newContent };+ });++ const durationMs = performance.now() - startMs;+ const savingsPercent =+ totalOriginalTokens > 0+ ? Math.round(((totalOriginalTokens - totalCompressedTokens) / totalOriginalTokens) * 100)+ : 0;++ const stats: CompressionStats = {+ mode: "caveman",+ originalTokens: totalOriginalTokens,+ compressedTokens: totalCompressedTokens,+ savingsPercent,+ durationMs: Math.round(durationMs * 100) / 100,+ rulesApplied: [...new Set(allAppliedRules)],+ };++ const compressed = totalCompressedTokens < totalOriginalTokens;++ const result: CompressionResult = {+ body: { ...body, messages: compressedMessages },+ compressed,+ stats,+ };++ trackCompressionStats(stats);++ return result;+}diff --git a/open-sse/services/compression/cavemanRules.ts b/open-sse/services/compression/cavemanRules.tsnew file mode 100644index 0000000000..0f2f90d247--- /dev/null+++ b/open-sse/services/compression/cavemanRules.ts@@ -0,0 +1,263 @@+import type { CavemanRule } from "./types.ts";++const CAVEMAN_RULES: CavemanRule[] = [+ // ── Category 1: Filler Removal (10+ rules) ──────────────────────────++ {+ 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",+ },+ {+ name: "hedging",+ pattern:+ /\b(?:it seems like|it appears that|I think that|I believe that|probably|possibly|maybe it)\b\s*/gi,+ replacement: "",+ context: "all",+ },+ {+ name: "verbose_instructions",+ pattern:+ /\b(?: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": "provide",+ "give me a comprehensive": "give",+ "write an in-depth": "write",+ "create a thorough": "create",+ "explain in detail": "explain",+ };+ const lower = match.toLowerCase();+ return map[lower] ?? match;+ },+ context: "all",+ },+ {+ name: "filler_adverbs",+ pattern: /(?<![a-z])\b(?:basically|essentially|actually|literally|simply)\b\s*/gi,+ replacement: "",+ context: "all",+ },+ {+ name: "filler_phrases",+ pattern: /^(?:I want to|I need to|I'd like to|I'm looking for)\b\s*/gim,+ replacement: "",+ context: "user",+ },+ {+ name: "redundant_openers",+ pattern: /^(?:Hi there|Hello|Good morning|Hey)\s*[,.!?\s]?\s*/gim,+ replacement: "",+ context: "user",+ },+ {+ name: "verbose_requests",+ pattern: /\b(?:I was wondering if you could|Would it be possible to)\b\s*/gi,+ replacement: "",+ context: "user",+ },+ {+ name: "self_reference",+ pattern: /^(?:I am trying to|I am working on|I have been)\b\s*/gim,+ replacement: "",+ context: "user",+ },+ {+ name: "excessive_gratitude",+ pattern: /\b(?:Thank you so much|Thanks in advance|I really appreciate)\b[,.!?\s]*/gi,+ replacement: "",+ context: "all",+ },+ {+ name: "qualifier_removal",+ pattern: /\b(?:a bit|a little|somewhat|kind of|sort of)\b\s*/gi,+ replacement: "",+ context: "all",+ },++ // ── Category 2: Context Condensation (8+ rules) ──────────────────────++ {+ name: "compound_collapse",+ pattern: /\band any potential\b/gi,+ replacement: "",+ context: "all",+ },+ {+ name: "explanatory_prefix",+ pattern:+ /\b(?:The function appears to be handling|The code seems to|The class is|This module is)\b/gi,+ replacement: (match: string): string => {+ const map: Record<string, string> = {+ "the function appears to be handling": "Function:",+ "the code seems to": "Code:",+ "the class is": "Class:",+ "this module is": "Module:",+ };+ return map[match.toLowerCase()] ?? match;+ },+ context: "all",+ },+ {+ name: "question_to_directive",+ pattern:+ /\b(?:Can you explain why|Could you show me how|Would you tell me|Can you tell me)\b\s*/gi,+ replacement: (match: string): string => {+ const map: Record<string, string> = {+ "can you explain why": "Explain why",+ "could you show me how": "Show how",+ "would you tell me": "Tell me",+ "can you tell me": "Tell me",+ };+ return map[match.toLowerCase()] ?? match;+ },+ context: "user",+ },+ {+ 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",+ },+ {+ name: "intent_clarification",+ pattern:+ /\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",+ },+ {+ name: "background_removal",+ pattern: /\b(?:As you may know,?\s*|As we discussed earlier,?\s*)/gi,+ replacement: "",+ context: "all",+ },+ {+ name: "meta_commentary",+ pattern: /^(?:Note that|Keep in mind that|Remember that)\b\s*/gim,+ replacement: "",+ context: "all",+ },+ {+ name: "purpose_statement",+ pattern: /\b(?:for the purpose of|with the goal of|in an effort to)\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",+ };+ return map[match.toLowerCase()] ?? match;+ },+ context: "all",+ },++ // ── Category 3: Structural Compression (7+ rules) ────────────────────++ {+ name: "list_conjunction",+ pattern: /,\s*and also\s+|,\s*as well as\s+/gi,+ replacement: ", ",+ context: "all",+ },+ {+ name: "purpose_phrases",+ pattern: /\b(?:in order to|so as to)\b\s*/gi,+ replacement: "to ",+ context: "all",+ },+ {+ name: "redundant_quantifiers",+ pattern: /\b(?:each and every single|each and every|any and all)\b/gi,+ replacement: (match: string): string => {+ const map: Record<string, string> = {+ "each and every single": "each",+ "each and every": "each",+ "any and all": "all",+ };+ return map[match.toLowerCase()] ?? match;+ },+ context: "all",+ },+ {+ name: "verbose_connectors",+ pattern: /\b(?:furthermore|additionally|moreover|in addition)\b\s*/gi,+ replacement: "also ",+ context: "all",+ },+ {+ name: "transition_removal",+ pattern: /^(?:On the other hand,?\s*|In contrast,?\s*|However,?\s*)/gim,+ replacement: "",+ context: "all",+ },+ {+ name: "emphasis_removal",+ pattern: /\b(?:very|really|extremely|highly|quite)\s+(?=[a-z])/gi,+ replacement: "",+ context: "all",+ },+ {+ name: "passive_voice",+ pattern: /\b(?:is being used|is being called|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",+ "was created": "created",+ "was generated": "generated",+ "was implemented": "implemented",+ };+ return map[match.toLowerCase()] ?? match;+ },+ context: "all",+ },++ // ── Category 4: Multi-Turn Dedup (5+ rules) ─────────────────────────++ {+ name: "repeated_context",+ pattern:+ /\b(?:As we discussed earlier|As mentioned before|As previously stated|As I said before)\b[,.]?\s*/gi,+ replacement: "See above. ",+ context: "all",+ },+ {+ name: "repeated_question",+ pattern:+ /\b(?:Same question as before|I asked this earlier|This is the same question)\b[,.]?\s*/gi,+ replacement: "[same question] ",+ context: "user",+ },+ {+ name: "reestablished_context",+ pattern: /\b(?:Going back to the code above|Referring back to|Returning to)\b\s*/gi,+ replacement: "Re: ",+ context: "all",+ },+ {+ name: "summary_replacement",+ pattern:+ /\b(?:To summarize what we've discussed|In summary of our conversation|To recap)\b[,.]?\s*/gi,+ replacement: "Summary: ",+ context: "assistant",+ },+ {+ name: "turn_marker",+ pattern: /^$/g,+ replacement: "",+ context: "assistant",+ },+];++export function getRulesForContext(context: string): CavemanRule[] {+ return CAVEMAN_RULES.filter((rule) => rule.context === "all" || rule.context === context);+}++export function getRuleByName(name: string): CavemanRule | undefined {+ return CAVEMAN_RULES.find((rule) => rule.name === name);+}++export { CAVEMAN_RULES };diff --git a/open-sse/services/compression/preservation.ts b/open-sse/services/compression/preservation.tsnew file mode 100644index 0000000000..1071ba23f3--- /dev/null+++ b/open-sse/services/compression/preservation.ts@@ -0,0 +1,53 @@+interface PreservedBlock {+ placeholder: string;+ content: string;+}++export function extractPreservedBlocks(text: string): { text: string; blocks: PreservedBlock[] } {+ const blocks: PreservedBlock[] = [];+ let result = text;+ let counter = 0;++ const addBlock = (content: string): string => {+ const placeholder = `[PRESERVED_${counter}]`;+ blocks.push({ placeholder, content });+ counter++;+ return placeholder;+ };++ // Extract fenced code blocks (```lang\n...\n```)+ result = result.replace(/```[a-z]*\n[\s\S]*?\n```/g, (match) => addBlock(match));++ // 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);+ });++ // 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)+ );++ return { text: result, blocks };+}++export function restorePreservedBlocks(text: string, blocks: PreservedBlock[]): string {+ let result = text;+ for (const block of blocks) {+ result = result.replace(block.placeholder, block.content);+ }+ return result;+}++export function shouldPreserve(text: string, preservePatterns: RegExp[]): boolean {+ return preservePatterns.some((pattern) => pattern.test(text));+}diff --git a/open-sse/services/compression/stats.ts b/open-sse/services/compression/stats.tsnew file mode 100644index 0000000000..cd48231462--- /dev/null+++ b/open-sse/services/compression/stats.ts@@ -0,0 +1,49 @@+import {+ type CompressionMode,+ type CompressionStats,+ type CompressionConfig,+ type CompressionResult,+ DEFAULT_CAVEMAN_CONFIG,+} from "./types.ts";++const CHARS_PER_TOKEN = 4;++export function estimateTokensForStats(text: string | object | null | undefined): number {+ if (!text) return 0;+ const str = typeof text === "string" ? text : JSON.stringify(text);+ return Math.ceil(str.length / CHARS_PER_TOKEN);+}++export function createCompressionStats(+ originalTokens: number,+ compressedTokens: number,+ mode: string,+ rulesApplied?: string[]+): CompressionStats {+ const savingsPercent =+ originalTokens > 0+ ? Math.round(((originalTokens - compressedTokens) / originalTokens) * 100)+ : 0;+ return {+ mode,+ originalTokens,+ compressedTokens,+ savingsPercent,+ durationMs: 0,+ ...(rulesApplied ? { rulesApplied } : {}),+ };+}++export function trackCompressionStats(stats: CompressionStats): void {+ if (process.env.COMPRESSION_DEBUG === "1") {+ console.log("[compression]", JSON.stringify(stats));+ }+}++export function getDefaultCompressionConfig(): CompressionConfig {+ return {+ mode: "off",+ enabled: false,+ cavemanConfig: { ...DEFAULT_CAVEMAN_CONFIG },+ };+}diff --git a/open-sse/services/compression/strategySelector.ts b/open-sse/services/compression/strategySelector.tsnew file mode 100644index 0000000000..60d0a440e6--- /dev/null+++ b/open-sse/services/compression/strategySelector.ts@@ -0,0 +1,42 @@+import { type CompressionMode, type CompressionConfig, type CompressionResult } from "./types.ts";+import { createCompressionStats } from "./stats.ts";+import { cavemanCompress } from "./caveman.ts";++export function selectCompressionStrategy(+ config: CompressionConfig | null,+ _body: unknown,+ _tokenCount: number,+ _provider: string+): CompressionMode {+ if (!config || !config.enabled) return "off";+ return config.mode || "caveman";+}++export function applyCompression(+ body: unknown,+ mode: CompressionMode,+ config: CompressionConfig | null+): CompressionResult {+ if (mode === "off" || !config?.enabled) {+ return { body, compressed: false, stats: createCompressionStats(0, 0, "off") };+ }+ if (mode === "caveman" && config.cavemanConfig) {+ return cavemanCompress(body as Parameters<typeof cavemanCompress>[0], config.cavemanConfig);+ }+ return { body, compressed: false, stats: createCompressionStats(0, 0, mode) };+}++export function getEffectiveMode(+ comboOverride: string | null,+ _autoTrigger: boolean,+ defaultMode: string+): CompressionMode {+ if (comboOverride && ["off", "lite", "caveman", "aggressive", "ultra"].includes(comboOverride)) {+ return comboOverride as CompressionMode;+ }+ if (defaultMode === "standard") return "caveman";+ if (["off", "lite", "caveman", "aggressive", "ultra"].includes(defaultMode)) {+ return defaultMode as CompressionMode;+ }+ return "off";+}diff --git a/open-sse/services/compression/types.ts b/open-sse/services/compression/types.tsnew file mode 100644index 0000000000..5bf9e86b45--- /dev/null+++ b/open-sse/services/compression/types.ts@@ -0,0 +1,60 @@+/**+ * Compression Types — Phase 1 + Phase 2 (Caveman)+ *+ * Shared type definitions for the compression pipeline.+ * No implementation logic — types only.+ */++/** Supported compression modes */+export type CompressionMode = "off" | "lite" | "caveman" | "aggressive" | "ultra";++/** A single caveman compression rule */+export interface CavemanRule {+ name: string;+ pattern: RegExp;+ replacement: string | ((match: string, ...groups: string[]) => string);+ context: "all" | "user" | "system" | "assistant";+ preservePatterns?: RegExp[];+}++/** Configuration for the caveman compression engine */+export interface CavemanConfig {+ enabled: boolean;+ compressRoles: ("user" | "assistant" | "system")[];+ skipRules: string[];+ minMessageLength: number;+ preservePatterns: string[];+}++/** Statistics for a single compression operation */+export interface CompressionStats {+ mode: string;+ originalTokens: number;+ compressedTokens: number;+ savingsPercent: number;+ durationMs: number;+ rulesApplied?: string[];+}++/** Result of a compression operation */+export interface CompressionResult {+ body: unknown;+ compressed: boolean;+ stats: CompressionStats;+}++/** Top-level compression configuration */+export interface CompressionConfig {+ mode: CompressionMode;+ enabled: boolean;+ cavemanConfig?: CavemanConfig;+}++/** Default caveman configuration */+export const DEFAULT_CAVEMAN_CONFIG: CavemanConfig = {+ enabled: true,+ compressRoles: ["user"],+ skipRules: [],+ minMessageLength: 50,+ preservePatterns: [],+};diff --git a/src/lib/db/compression.ts b/src/lib/db/compression.tsnew file mode 100644index 0000000000..7e871af780--- /dev/null+++ b/src/lib/db/compression.ts@@ -0,0 +1,63 @@+import { getDbInstance } from "./core.ts";+import { invalidateDbCache } from "./readCache.ts";+import { DEFAULT_CAVEMAN_CONFIG } from "../../open-sse/services/compression/types.ts";+import type { CavemanConfig } from "../../open-sse/services/compression/types.ts";++const NAMESPACE = "compression";++type JsonRecord = Record<string, unknown>;++function toRecord(value: unknown): JsonRecord {+ return value && typeof value === "object" ? (value as JsonRecord) : {};+}++export interface CompressionSettings {+ mode: string;+ enabled: boolean;+ cavemanConfig: CavemanConfig;+}++export function getCompressionSettings(): CompressionSettings {+ const db = getDbInstance();+ const rows = db.prepare("SELECT key, value FROM key_value WHERE namespace = ?").all(NAMESPACE);++ const defaults: CompressionSettings = {+ mode: "off",+ enabled: false,+ cavemanConfig: { ...DEFAULT_CAVEMAN_CONFIG },+ };++ for (const row of rows) {+ const record = toRecord(row);+ const key = typeof record.key === "string" ? record.key : null;+ const rawValue = typeof record.value === "string" ? record.value : null;+ if (!key || !rawValue) continue;+ try {+ const parsed = JSON.parse(rawValue);+ if (key === "mode") defaults.mode = parsed;+ else if (key === "enabled") defaults.enabled = parsed;+ else if (key === "cavemanConfig")+ defaults.cavemanConfig = { ...DEFAULT_CAVEMAN_CONFIG, ...parsed };+ } catch {+ // skip malformed JSON+ }+ }++ return defaults;+}++export function updateCompressionSettings(settings: Record<string, unknown>): void {+ const db = getDbInstance();+ const upsert = db.prepare(+ "INSERT INTO key_value (namespace, key, value) VALUES (?, ?, ?) ON CONFLICT(namespace, key) DO UPDATE SET value = excluded.value"+ );++ const transaction = db.transaction(() => {+ for (const [key, value] of Object.entries(settings)) {+ upsert.run(NAMESPACE, key, JSON.stringify(value));+ }+ });++ transaction();+ invalidateDbCache();+}diff --git a/tests/unit/compression/caveman-engine.test.ts b/tests/unit/compression/caveman-engine.test.tsnew file mode 100644index 0000000000..7249f82c53--- /dev/null+++ b/tests/unit/compression/caveman-engine.test.ts@@ -0,0 +1,228 @@+import { describe, it } from "node:test";+import assert from "node:assert/strict";+import {+ cavemanCompress,+ applyRulesToText,+} from "../../../open-sse/services/compression/caveman.ts";+import { CAVEMAN_RULES } from "../../../open-sse/services/compression/cavemanRules.ts";+import type { CavemanRule } from "../../../open-sse/services/compression/types.ts";++describe("caveman engine", () => {+ it("should compress a verbose user prompt", () => {+ const body = {+ messages: [+ {+ role: "user",+ content:+ "Please could you help me analyze this code? I would like you to provide a detailed explanation of what the function does. Thank you so much for your help!",+ },+ ],+ };+ const result = cavemanCompress(body, {+ enabled: true,+ compressRoles: ["user"],+ skipRules: [],+ minMessageLength: 50,+ preservePatterns: [],+ });+ assert.equal(result.compressed, true);+ assert.ok(+ result.stats.savingsPercent > 0,+ `Expected savings > 0, got ${result.stats.savingsPercent}`+ );+ assert.ok(+ result.stats.rulesApplied && result.stats.rulesApplied.length > 0,+ "Expected rules applied"+ );+ });++ it("should skip messages below minMessageLength", () => {+ const body = { messages: [{ role: "user", content: "Hi" }] };+ const result = cavemanCompress(body, {+ enabled: true,+ compressRoles: ["user"],+ skipRules: [],+ minMessageLength: 50,+ preservePatterns: [],+ });+ assert.equal(result.compressed, false);+ });++ it("should return unchanged body when disabled", () => {+ const body = { messages: [{ role: "user", content: "Please help me with this code" }] };+ const result = cavemanCompress(body, {+ enabled: false,+ compressRoles: ["user"],+ skipRules: [],+ minMessageLength: 50,+ preservePatterns: [],+ });+ assert.equal(result.compressed, false);+ });++ it("should preserve code blocks", () => {+ const codeContent = "const x = 42;\nconsole.log(x);";+ const body = {+ messages: [+ {+ role: "user",+ content: `Please analyze this code:\n\`\`\`typescript\n${codeContent}\n\`\`\`\nThank you so much!`,+ },+ ],+ };+ const result = cavemanCompress(body, {+ enabled: true,+ compressRoles: ["user"],+ skipRules: [],+ minMessageLength: 50,+ preservePatterns: [],+ });+ const text = result.body.messages[0].content as string;+ assert.ok(text.includes(codeContent), `Code block should be preserved exactly`);+ });++ it("should preserve URLs", () => {+ const url = "https://example.com/api/v1/users";+ const body = {+ messages: [+ {+ role: "user",+ content: `Please check ${url} for the API docs. Thank you so much!`,+ },+ ],+ };+ const result = cavemanCompress(body, {+ enabled: true,+ compressRoles: ["user"],+ skipRules: [],+ minMessageLength: 50,+ preservePatterns: [],+ });+ const text = result.body.messages[0].content as string;+ assert.ok(text.includes(url), `URL should be preserved`);+ });++ it("should handle empty messages array", () => {+ const body = { messages: [] };+ const result = cavemanCompress(body, {+ enabled: true,+ compressRoles: ["user"],+ skipRules: [],+ minMessageLength: 50,+ preservePatterns: [],+ });+ assert.equal(result.compressed, false);+ });++ it("should handle messages without content", () => {+ const body = { messages: [{ role: "user" }] };+ const result = cavemanCompress(body, {+ enabled: true,+ compressRoles: ["user"],+ skipRules: [],+ minMessageLength: 50,+ preservePatterns: [],+ });+ assert.equal(result.compressed, false);+ });++ it("should skip rules in skipRules list", () => {+ const body = {+ messages: [{ role: "user", content: "Please help me with this code. Thank you so much!" }],+ };+ const resultWithSkip = cavemanCompress(body, {+ enabled: true,+ compressRoles: ["user"],+ skipRules: ["polite_framing"],+ minMessageLength: 50,+ preservePatterns: [],+ });+ assert.ok(+ !resultWithSkip.stats.rulesApplied?.includes("polite_framing"),+ "polite_framing should be skipped"+ );+ });++ it("should respect compressRoles setting", () => {+ const body = {+ messages: [+ {+ role: "system",+ content:+ "You are a very helpful assistant. Please be extremely detailed in all your responses.",+ },+ {+ role: "user",+ content:+ "Please could you help me with this code problem? I would like you to provide a detailed explanation. Thank you so much!",+ },+ ],+ };+ const result = cavemanCompress(body, {+ enabled: true,+ compressRoles: ["user"],+ skipRules: [],+ minMessageLength: 50,+ preservePatterns: [],+ });+ const systemMsg = result.body.messages[0].content as string;+ const userMsg = result.body.messages[1].content as string;+ assert.ok(+ systemMsg.includes("very"),+ "System message should not be compressed (not in compressRoles)"+ );+ assert.ok(+ !userMsg.includes("Please could you"),+ "User message should have 'Please could you' removed"+ );+ assert.ok(+ !userMsg.includes("Thank you so much"),+ "User message should have 'Thank you so much' removed"+ );+ });++ it("should compute stats accurately", () => {+ const body = {+ messages: [+ { role: "user", content: "Please could you help me with this problem? Thank you so much!" },+ ],+ };+ const result = cavemanCompress(body, {+ enabled: true,+ compressRoles: ["user"],+ skipRules: [],+ minMessageLength: 50,+ preservePatterns: [],+ });+ assert.ok(result.stats.originalTokens > 0);+ assert.ok(result.stats.compressedTokens >= 0);+ assert.ok(result.stats.savingsPercent >= 0);+ assert.ok(result.stats.durationMs >= 0);+ assert.ok(+ result.stats.durationMs < 50,+ `Duration ${result.stats.durationMs}ms should be well under 5ms`+ );+ });++ it("applyRulesToText should track applied rules", () => {+ const { text, appliedRules } = applyRulesToText(+ "Please help me",+ CAVEMAN_RULES.filter((r) => r.context === "all" || r.context === "user")+ );+ assert.ok(appliedRules.length > 0, "Should track applied rules");+ assert.ok(appliedRules.includes("polite_framing"), "polite_framing should be in applied rules");+ });++ it("should complete in under 5ms for 10K token messages", () => {+ const longContent = "Please help me analyze this code. ".repeat(1000);+ const body = { messages: [{ role: "user", content: longContent }] };+ const result = cavemanCompress(body, {+ enabled: true,+ compressRoles: ["user"],+ skipRules: [],+ minMessageLength: 50,+ preservePatterns: [],+ });+ assert.ok(result.stats.durationMs < 5, `Expected <5ms, got ${result.stats.durationMs}ms`);+ });+});diff --git a/tests/unit/compression/caveman-preservation.test.ts b/tests/unit/compression/caveman-preservation.test.tsnew file mode 100644index 0000000000..af33b226a9--- /dev/null+++ b/tests/unit/compression/caveman-preservation.test.ts@@ -0,0 +1,70 @@+import { describe, it } from "node:test";+import assert from "node:assert/strict";+import {+ extractPreservedBlocks,+ restorePreservedBlocks,+ shouldPreserve,+} from "../../../open-sse/services/compression/preservation.ts";++describe("preservation", () => {+ it("should extract and restore code blocks", () => {+ const code = "const x = 42;\nconsole.log(x);";+ const text = `Please fix this:\n\`\`\`js\n${code}\n\`\`\`\nThanks!`;+ const { text: extracted, blocks } = extractPreservedBlocks(text);+ assert.ok(!extracted.includes(code), "Code should be replaced with placeholder");+ assert.ok(blocks.length > 0, "Should have preserved blocks");+ const restored = restorePreservedBlocks(extracted, blocks);+ assert.equal(restored, text, "Should restore to original");+ });++ it("should preserve URLs", () => {+ const url = "https://example.com/api/v1/users";+ const text = `Check ${url} please`;+ const { text: extracted, blocks } = extractPreservedBlocks(text);+ const restored = restorePreservedBlocks(extracted, blocks);+ assert.ok(restored.includes(url), "URL should be preserved");+ });++ it("should preserve file paths", () => {+ const path = "/src/utils/helper.ts";+ const text = `Fix the file ${path} please`;+ const { text: extracted, blocks } = extractPreservedBlocks(text);+ const restored = restorePreservedBlocks(extracted, blocks);+ assert.ok(restored.includes(path), "Path should be preserved");+ });++ it("should preserve error messages", () => {+ const text = "I got TypeError: Cannot read property of undefined";+ const { blocks } = extractPreservedBlocks(text);+ assert.ok(+ blocks.some((b) => b.content.includes("TypeError")),+ "Error should be preserved"+ );+ });++ it("shouldPreserve matches user patterns", () => {+ assert.ok(shouldPreserve("my-secret-key", [/secret/i]));+ assert.ok(!shouldPreserve("hello world", [/secret/i]));+ });++ it("should handle nested code blocks and URLs", () => {+ const text = "See https://docs.example.com for:\n```\nfetch('https://api.example.com')\n```";+ const { text: extracted, blocks } = extractPreservedBlocks(text);+ const restored = restorePreservedBlocks(extracted, blocks);+ assert.ok(restored.includes("https://docs.example.com"));+ assert.ok(restored.includes("fetch('https://api.example.com')"));+ });++ it("should handle empty text", () => {+ const { text, blocks } = extractPreservedBlocks("");+ assert.equal(text, "");+ assert.equal(blocks.length, 0);+ });++ it("should handle text with nothing to preserve", () => {+ const text = "Just regular text here";+ const { text: extracted, blocks } = extractPreservedBlocks(text);+ assert.equal(blocks.length, 0);+ assert.equal(extracted, text);+ });+});diff --git a/tests/unit/compression/caveman-rules.test.ts b/tests/unit/compression/caveman-rules.test.tsnew file mode 100644index 0000000000..a1134c0f53--- /dev/null+++ b/tests/unit/compression/caveman-rules.test.ts@@ -0,0 +1,165 @@+import { describe, it } from "node:test";+import assert from "node:assert/strict";+import {+ CAVEMAN_RULES,+ getRulesForContext,+ getRuleByName,+} from "../../../open-sse/services/compression/cavemanRules.ts";++describe("cavemanRules", () => {+ it("should have 30+ rules", () => {+ assert.ok(CAVEMAN_RULES.length >= 30, `Expected 30+ rules, got ${CAVEMAN_RULES.length}`);+ });++ it("every rule should have a name, pattern, replacement, and context", () => {+ for (const rule of CAVEMAN_RULES) {+ assert.ok(rule.name, "Rule missing name");+ assert.ok(rule.pattern instanceof RegExp, `Rule ${rule.name} missing pattern`);+ assert.ok(rule.replacement !== undefined, `Rule ${rule.name} missing replacement`);+ assert.ok(+ ["all", "user", "system", "assistant"].includes(rule.context),+ `Rule ${rule.name} has invalid context: ${rule.context}`+ );+ }+ });++ it("all regex patterns should compile", () => {+ for (const rule of CAVEMAN_RULES) {+ assert.doesNotThrow(() => rule.pattern.test("test"), `Rule ${rule.name} pattern fails`);+ }+ });++ it("getRulesForContext filters correctly", () => {+ const userRules = getRulesForContext("user");+ const systemRules = getRulesForContext("system");+ const assistantRules = getRulesForContext("assistant");++ assert.ok(userRules.length >= 20, `Expected 20+ user rules, got ${userRules.length}`);+ assert.ok(systemRules.length >= 15, `Expected 15+ system rules, got ${systemRules.length}`);+ assert.ok(+ assistantRules.length >= 15,+ `Expected 15+ assistant rules, got ${assistantRules.length}`+ );++ for (const rule of userRules) {+ assert.ok(+ rule.context === "all" || rule.context === "user",+ `User rules should include ${rule.name}`+ );+ }+ });++ it("getRuleByName returns correct rule", () => {+ const rule = getRuleByName("polite_framing");+ assert.ok(rule);+ assert.equal(rule.name, "polite_framing");++ const missing = getRuleByName("nonexistent_rule");+ assert.equal(missing, undefined);+ });++ it("polite_framing removes 'please'", () => {+ const rule = getRuleByName("polite_framing");+ assert.ok(rule);+ const result = "Please analyze this code".replace(rule.pattern, rule.replacement);+ assert.ok(+ !result.toLowerCase().includes("please"),+ `Expected 'please' removed, got: ${result}`+ );+ });++ it("hedging removes 'it seems like'", () => {+ const rule = getRuleByName("hedging");+ assert.ok(rule);+ const result = "It seems like this works".replace(rule.pattern, rule.replacement);+ assert.ok(+ !result.toLowerCase().includes("it seems like"),+ `Expected hedging removed, got: ${result}`+ );+ });++ it("verbose_instructions compresses", () => {+ const rule = getRuleByName("verbose_instructions");+ assert.ok(rule);+ const result = "provide a detailed explanation".replace(+ rule.pattern,+ typeof rule.replacement === "function"+ ? (...args: string[]) => rule.replacement(args[0], ...args.slice(1))+ : rule.replacement+ );+ assert.ok(result.includes("provide"), `Expected 'provide', got: ${result}`);+ assert.ok(!result.includes("detailed"), `Expected 'detailed' removed, got: ${result}`);+ });++ it("filler_adverbs removes 'basically'", () => {+ const rule = getRuleByName("filler_adverbs");+ assert.ok(rule);+ const result = "This is basically a test".replace(rule.pattern, rule.replacement);+ assert.ok(+ !result.toLowerCase().includes("basically"),+ `Expected 'basically' removed, got: ${result}`+ );+ });++ it("excessive_gratitude removes 'Thank you so much'", () => {+ const rule = getRuleByName("excessive_gratitude");+ assert.ok(rule);+ const result = "Thank you so much for your help!".replace(rule.pattern, rule.replacement);+ assert.ok(+ !result.toLowerCase().includes("thank you so much"),+ `Expected gratitude removed, got: ${result}`+ );+ });++ it("context_setup converts 'Here is my code' to 'Code:'", () => {+ const rule = getRuleByName("context_setup");+ assert.ok(rule);+ const result = "Here is my code for review:".replace(rule.pattern, rule.replacement);+ assert.ok(result.includes("Code:"), `Expected 'Code:', got: ${result}`);+ });++ it("intent_clarification converts intent to 'Goal:'", () => {+ const rule = getRuleByName("intent_clarification");+ assert.ok(rule);+ const result = "What I'm trying to do is fix the bug".replace(rule.pattern, rule.replacement);+ assert.ok(result.startsWith("Goal:"), `Expected 'Goal:', got: ${result}`);+ });++ it("purpose_phrases converts 'in order to' to 'to'", () => {+ const rule = getRuleByName("purpose_phrases");+ assert.ok(rule);+ const result = "in order to fix this".replace(rule.pattern, rule.replacement);+ assert.ok(result.startsWith("to "), `Expected 'to ', got: ${result}`);+ assert.ok(!result.includes("in order"), `Expected 'in order' removed, got: ${result}`);+ });++ it("passive_voice converts 'is being used' to 'uses'", () => {+ const rule = getRuleByName("passive_voice");+ assert.ok(rule);+ const result = "The function is being used".replace(+ rule.pattern,+ typeof rule.replacement === "function"+ ? (...args: string[]) => rule.replacement(args[0])+ : rule.replacement+ );+ assert.ok(result.includes("uses"), `Expected 'uses', got: ${result}`);+ });++ it("repeated_context converts to 'See above'", () => {+ const rule = getRuleByName("repeated_context");+ assert.ok(rule);+ const result = "As we discussed earlier, this needs fixing".replace(+ rule.pattern,+ rule.replacement+ );+ assert.ok(result.includes("See above"), `Expected 'See above', got: ${result}`);+ });++ it("emphasis_removal removes 'very' before adjectives", () => {+ const rule = getRuleByName("emphasis_removal");+ assert.ok(rule);+ const result = "This is very important".replace(rule.pattern, rule.replacement);+ assert.ok(!result.includes("very"), `Expected 'very' removed, got: ${result}`);+ assert.ok(result.includes("important"), `Expected 'important' kept, got: ${result}`);+ });+});