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
Release v3.7.9 (#1917)
Diego Rodrigues de Sa e Souza99c6dc7fd695
diff --git a/.agents/workflows/deploy-vps-akamai.md b/.agents/workflows/deploy-vps-akamai.mdindex 50f92cab5f..b25ae3cd99 100644--- a/.agents/workflows/deploy-vps-akamai.md+++ b/.agents/workflows/deploy-vps-akamai.md@@ -17,7 +17,7 @@ Deploy OmniRoute to the Akamai VPS using `npm pack + scp` + PM2.// turbo```bash-cd /home/diegosouzapw/dev/proxys/9router && rm -f omniroute-*.tgz && rm -rf .next/cache app/.next/cache && npm run build:cli && rm -rf app/logs app/coverage app/.git app/.app-build-backup* && npm pack --ignore-scripts+cd /home/diegosouzapw/dev/proxys/OmniRoute && rm -f omniroute-*.tgz && rm -rf .next/cache app/.next/cache && npm run build:cli && rm -rf app/logs app/coverage app/.git app/.app-build-backup* && npm pack --ignore-scripts```### 2. Copy to Akamai VPS and installdiff --git a/.agents/workflows/deploy-vps-both.md b/.agents/workflows/deploy-vps-both.mdindex 161d197bd4..e1aa4d1def 100644--- a/.agents/workflows/deploy-vps-both.md+++ b/.agents/workflows/deploy-vps-both.md@@ -22,7 +22,7 @@ Deploy OmniRoute to the production VPSs using `npm pack + scp` + PM2.// turbo```bash-cd /home/diegosouzapw/dev/proxys/9router && rm -f omniroute-*.tgz && rm -rf .next/cache app/.next/cache && npm run build:cli && rm -rf app/logs app/coverage app/.git app/.app-build-backup* && npm pack --ignore-scripts+cd /home/diegosouzapw/dev/proxys/OmniRoute && rm -f omniroute-*.tgz && rm -rf .next/cache app/.next/cache && npm run build:cli && rm -rf app/logs app/coverage app/.git app/.app-build-backup* && npm pack --ignore-scripts```### 2. Copy to both VPS and installdiff --git a/.agents/workflows/deploy-vps-local.md b/.agents/workflows/deploy-vps-local.mdindex f348f63da5..549b1f0b2a 100644--- a/.agents/workflows/deploy-vps-local.md+++ b/.agents/workflows/deploy-vps-local.md@@ -17,7 +17,7 @@ Deploy OmniRoute to the Local VPS using `npm pack + scp` + PM2.// turbo```bash-cd /home/diegosouzapw/dev/proxys/9router && rm -f omniroute-*.tgz && rm -rf .next/cache app/.next/cache && npm run build:cli && rm -rf app/logs app/coverage app/.git app/.app-build-backup* && npm pack --ignore-scripts+cd /home/diegosouzapw/dev/proxys/OmniRoute && rm -f omniroute-*.tgz && rm -rf .next/cache app/.next/cache && npm run build:cli && rm -rf app/logs app/coverage app/.git app/.app-build-backup* && npm pack --ignore-scripts```### 2. Copy to Local VPS and installdiff --git a/.agents/workflows/generate-release.md b/.agents/workflows/generate-release.mdindex e127c832d4..399e12d214 100644--- a/.agents/workflows/generate-release.md+++ b/.agents/workflows/generate-release.md@@ -226,7 +226,7 @@ git checkout maingit pull origin main# Build and pack locally-cd /home/diegosouzapw/dev/proxys/9router && rm -f omniroute-*.tgz && rm -rf .next/cache app/.next/cache && npm run build:cli && rm -rf app/logs app/coverage app/.git app/.app-build-backup* && npm pack --ignore-scripts+cd /home/diegosouzapw/dev/proxys/OmniRoute && rm -f omniroute-*.tgz && rm -rf .next/cache app/.next/cache && npm run build:cli && rm -rf app/logs app/coverage app/.git app/.app-build-backup* && npm pack --ignore-scripts# Deploy to LOCAL VPS (192.168.0.15)scp omniroute-*.tgz [email protected]:/tmp/diff --git a/.agents/workflows/version-bump.md b/.agents/workflows/version-bump.mdindex 4b3b77a921..0667e0eb1d 100644--- a/.agents/workflows/version-bump.md+++ b/.agents/workflows/version-bump.md@@ -20,7 +20,7 @@ Automatically bump the project version, generate CHANGELOG entries from git hist// turbo```bash-cd /home/diegosouzapw/dev/proxys/9router+cd /home/diegosouzapw/dev/proxys/OmniRouteCURRENT_VERSION=$(node -p "require('./package.json').version")LAST_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "")CURRENT_BRANCH=$(git branch --show-current)@@ -64,7 +64,7 @@ npm version "$VERSION" --no-git-tag-version// turbo```bash-cd /home/diegosouzapw/dev/proxys/9router+cd /home/diegosouzapw/dev/proxys/OmniRouteLAST_TAG=$(git describe --tags --abbrev=0 2>/dev/null)echo "=== Commits since $LAST_TAG ==="git log "$LAST_TAG"..HEAD --pretty=format:"%h %s" --no-merges | head -100@@ -133,7 +133,7 @@ The date must be today's date in `YYYY-MM-DD` format.// turbo```bash-cd /home/diegosouzapw/dev/proxys/9router+cd /home/diegosouzapw/dev/proxys/OmniRouteVERSION=$(node -p "require('./package.json').version")# Update docs/openapi.yaml version@@ -156,7 +156,7 @@ echo "✓ All workspace packages synced to $VERSION"// turbo```bash-cd /home/diegosouzapw/dev/proxys/9router+cd /home/diegosouzapw/dev/proxys/OmniRouteVERSION=$(node -p "require('./package.json').version")OLD_VERSION_PATTERN='[0-9]\+\.[0-9]\+\.[0-9]\+'@@ -174,7 +174,7 @@ echo "✓ llm.txt → $VERSION"// turbo```bash-cd /home/diegosouzapw/dev/proxys/9router+cd /home/diegosouzapw/dev/proxys/OmniRoutenpm installecho "✓ Lock file regenerated"```@@ -236,7 +236,7 @@ For each file in `docs/` (excluding `docs/i18n/`), review if CHANGELOG changes a// turbo```bash-cd /home/diegosouzapw/dev/proxys/9router+cd /home/diegosouzapw/dev/proxys/OmniRoutenpm run lint```@@ -245,7 +245,7 @@ npm run lint// turbo```bash-cd /home/diegosouzapw/dev/proxys/9router+cd /home/diegosouzapw/dev/proxys/OmniRoutenpm test```@@ -254,7 +254,7 @@ npm test// turbo```bash-cd /home/diegosouzapw/dev/proxys/9router+cd /home/diegosouzapw/dev/proxys/OmniRouteVERSION=$(node -p "require('./package.json').version")echo "Expected version: $VERSION"echo ""@@ -299,7 +299,7 @@ grep "^## \[" CHANGELOG.md | head -2// turbo-all```bash-cd /home/diegosouzapw/dev/proxys/9router+cd /home/diegosouzapw/dev/proxys/OmniRoutegit add -AVERSION=$(node -p "require('./package.json').version")git commit -m "chore(release): bump to v$VERSION — changelog, docs, version sync"diff --git a/AGENTS.md b/AGENTS.mdindex 3b05a3dd65..aadaf98b2e 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -6,7 +6,7 @@ Unified AI proxy/router — route any LLM through one endpoint. Multi-provider swith **160+ providers** (OpenAI, Anthropic, Gemini, DeepSeek, Groq, xAI, Mistral, Fireworks,Cohere, NVIDIA, Cerebras, Pollinations, Puter, Cloudflare AI, HuggingFace, DeepInfra,SambaNova, Meta Llama API, Moonshot AI, AI21 Labs, Databricks, Snowflake, and many more)-with **MCP Server** (29 tools), **A2A v0.3 Protocol**, and **Electron desktop app**.+with **MCP Server** (37 tools), **A2A v0.3 Protocol**, and **Electron desktop app**.## Stack@@ -292,17 +292,28 @@ compression pipeline), and more.Modular prompt compression that runs proactively before the existing reactive context manager.-- **`strategySelector.ts`**: Selects compression mode based on config, combo overrides, auto-trigger- thresholds. Priority: combo override > auto-trigger > default mode > off.+- **`strategySelector.ts`**: Selects compression mode based on config, compression combo assignments,+ combo overrides, auto-trigger thresholds, and defaults. Priority: assigned compression combo >+ combo override > auto-trigger > default mode > off.- **`lite.ts`**: 5 lite-mode techniques: `collapseWhitespace`, `dedupSystemPrompt`,`compressToolResults`, `removeRedundantContent`, `replaceImageUrls`. Target: 10-15% savings at<1ms latency.+- **`caveman.ts` / `cavemanRules.ts`**: Caveman-style semantic condensation backed by built-in+ rules plus file-loaded language packs under `compression/rules/`.+- **`engines/rtk/`**: Rule-based terminal/tool-output compression inspired by RTK patterns. Detects+ command output classes, applies JSON filter packs, deduplicates repeated lines, strips ANSI/code+ noise, and preserves errors/actionable context. The RTK JSON DSL supports replace,+ match-output short-circuit, strip/keep, per-line truncation, head/tail/max-line truncation,+ inline tests, trust-gated project/global custom filters, and optional redacted raw-output+ retention for authenticated recovery.+- **`engines/registry.ts`**: Registers engines (`caveman`, `rtk`) and powers stacked pipelines.- **`stats.ts`**: Per-request compression stats tracking (original tokens, compressed tokens,- savings %, techniques used).-- **`types.ts`**: `CompressionMode` (off/lite/standard/aggressive/ultra), `CompressionConfig`,- `CompressionStats`, `CompressionResult`.-- DB settings in `src/lib/db/compression.ts`, API route at `src/app/api/settings/compression/`.-- Phase 1 implements lite mode only; standard/aggressive/ultra are placeholders for Phase 2.+ savings %, techniques used, engine breakdown, compression combo id).+- **`types.ts`**: `CompressionMode` (off/lite/standard/aggressive/ultra/rtk/stacked),+ `CompressionConfig`, `CompressionStats`, `CompressionResult`.+- DB settings in `src/lib/db/compression.ts`, compression combos in+ `src/lib/db/compressionCombos.ts`, API routes under `src/app/api/settings/compression/`,+ `src/app/api/context/*`, and preview/language-pack routes under `src/app/api/compression/*`.#### Combo Routing Engine (`combo.ts`)@@ -323,7 +334,7 @@ Policy engine modules: `policyEngine.ts`, `comboResolver.ts`, `costRules.ts`,### MCP Server (`open-sse/mcp-server/`)-29 tools, 3 transports (stdio / SSE / Streamable HTTP). Scoped auth (10 scopes), Zod schemas.+37 tools, 3 transports (stdio / SSE / Streamable HTTP). Scoped auth (10 scopes), Zod schemas.**Core tools** (20): get_health, list_combos, get_combo_metrics, switch_combo, check_quota,route_request, cost_report, list_models_catalog, web_search, simulate_route, set_budget_guard,@@ -332,6 +343,11 @@ best_combo_for_task, explain_route, get_session_snapshot, db_health_check, sync_**Cache tools** (2): cache_stats, cache_flush.+**Compression tools** (5): compression_status, compression_configure, set_compression_engine,+list_compression_combos, compression_combo_stats.++**1proxy tools** (3): oneproxy_fetch, oneproxy_rotate, oneproxy_stats.+**Memory tools** (3): memory_search, memory_add, memory_clear.**Skill tools** (4): skills_list, skills_enable, skills_execute, skills_executions.diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0e926f19c8..80b3a71240 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,55 @@## [Unreleased]+## [3.7.9] — 2026-05-03++### ✨ New Features++- **feat(compression):** major upgrade to Caveman and RTK compression pipelines (#1876, #1889):+ - Add RTK tool-output compression, stacked Caveman + RTK pipelines, compression combo assignments, dashboard context pages, MCP management tools, and language-aware Caveman rule packs.+ - Expand RTK parity with a 39-filter catalog, RTK-style JSON DSL stages, inline verify/benchmark coverage, trust-gated custom filters, expanded command detection, and redacted raw-output recovery.+ - Expose rule intensities, track USD savings, unify config validation, and persist MCP savings.+ - Expand Caveman parity and MCP metadata compression.+- **feat(provider):** update Jina AI model catalog to support Embeddings and Rerank natively (#1874 — thanks @backryun)+- **feat(provider):** add NanoGPT image generation provider (#1899 — thanks @Aculeasis)+- **feat(ui):** move proxy configuration to dedicated System → Proxy page (#1907 — thanks @oyi77)+- **feat(ui):** add K/M/B/T cost shortener utility (#1902 — thanks @oyi77)+- **feat(providers):** implement bulk paste for extra API keys (#1916 — thanks @0xtbug)+- **feat(analytics):** usage history API key backfill + dark mode pricing (#1896 — thanks @Gi99lin)+- **feat(logs):** show RTK and Caveman compression token savings accurately in request log UI (#1923 — thanks @emdash)++### 🐛 Bug Fixes++- **fix(providers):** allow local OpenAI-compatible endpoints (like Ollama) to be added without an API key (fixes #1893)+- **fix(providers):** bypass AgentRouter unauthorized_client_error by spoofing Claude CLI headers via Anthropic endpoints (fixes #1921)+- **fix(copilot):** emit compatible reasoning text deltas (#1919 — thanks @ivan-mezentsev)+- **fix(api-manager):** show validation errors inline in modals, not behind (#1920 — thanks @andrewmunsell)+- **fix(compression):** align seeded standard savings combo with stacked default, preserve stacked defaults, and secure metadata routes.+- **fix(gemini-cli):** separate Cloud Code transport from Antigravity (#1869 — thanks @dhaern)+- **fix(codex):** map prompt field to input array for Cursor compatibility (fixes #1872)+- **fix(core):** align stream parameter default to false per strict OpenAI spec (fixes #1873)+- **fix(ui):** restore Next.js CSP `unsafe-eval` in production `script-src` to fix unresponsive Onboarding button (fixes #1883)+- **fix(proxy):** globally strip `prompt_cache_retention` in `BaseExecutor` to prevent upstream 400 errors from strict endpoints like droid/gemini-2-pro (fixes #1884)+- **fix(ui):** include `isOpen` dependency in `EditConnectionModal` state sync to ensure `maxConcurrent` is properly hydrated when reopening the modal (fixes #1859)+- **fix(security):** remediate 4 polynomial-redos CodeQL alerts in compression regexes by bounding repetitions and removing overlapping quantifiers+- **fix(codex):** flatten Chat Completions tool format to Codex Responses format in `normalizeCodexTools` — prevents `Missing required parameter: tools[0].name` upstream errors (#1914 — thanks @tranduykhanh030)+- **fix(proxy):** add proxy-aware execution context to image generation route — proxy settings are now correctly applied for image providers behind restricted networks (#1904 — thanks @Aculeasis)+- **fix(translator):** inject `properties: {}` into zero-argument MCP tool schemas during Anthropic→OpenAI translation — prevents 400 errors from OpenAI strict schema validation (#1898 — thanks @bryceIT)+- **fix(codex):** sanitize raw responses input (#1895 — thanks @dhaern)+- **fix(combos):** align strategy contracts (#1892 — thanks @dhaern)+- **fix(combos):** fix combo provider breaker profile handling (#1891 — thanks @rdself)+- **fix(migrations):** duplicate-column no-op fix (#1886 — thanks @smartenok-ops)+- **fix(auth):** per-connection OAuth refresh mutex (#1885 — thanks @smartenok-ops)+- **fix(auth):** require dashboard management auth for compression preview++### 📝 Documentation++- **docs(compression):** document RTK+Caveman stacked savings ranges++### 🏆 Release Attribution & Retroactive Credits++- **@payne0420** (PR #1828 / #1839) — Implementation of the **Rate Limit Watchdog** and environment overrides. (This feature was manually backported to v3.7.8, causing the automatic GitHub Release notes to omit the author's credit).+---## [3.7.8] — 2026-05-01diff --git a/README.md b/README.mdindex 49c38eb156..d794d02d81 100644--- a/README.md+++ b/README.md@@ -2,9 +2,9 @@# 🚀 OmniRoute — The Free AI Gateway-### Never stop coding. Save 15-75% tokens with prompt compression + auto-fallback to **FREE & low-cost AI models**.+### Never stop coding. Save 15-95% eligible tokens with RTK+Caveman compression + auto-fallback to **FREE & low-cost AI models**.-_The most complete open-source AI proxy — **one endpoint**, **160+ providers**, **13 routing strategies**, zero downtime. Multi-platform: **Web**, **Desktop (Electron)**, **Mobile (PWA + Termux)**. Fully extensible via **MCP Server (29 tools)**, **A2A Protocol**, and **Memory/Skills** systems. Available in **40+ languages**._+_The most complete open-source AI proxy — **one endpoint**, **160+ providers**, **13 routing strategies**, zero downtime. Multi-platform: **Web**, **Desktop (Electron)**, **Mobile (PWA + Termux)**. Fully extensible via **MCP Server (37 tools)**, **A2A Protocol**, and **Memory/Skills** systems. Available in **40+ languages**._**Chat Completions • Responses API • Embeddings • Image Generation • Video • Music • Audio Speech/Transcription • Reranking • Moderations • Web Search • MCP Server • A2A Protocol • 4,600+ Tests • 100% TypeScript**@@ -20,7 +20,7 @@ _The most complete open-source AI proxy — **one endpoint**, **160+ providers**<a href="https://trendshift.io/repositories/23589" target="_blank"><img src="https://trendshift.io/api/badge/repositories/23589" alt="diegosouzapw%2FOmniRoute | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>-[🚀 Quick Start](#-quick-start) • [💡 Features](#-key-features) • [🗜️ Compression](#%EF%B8%8F-prompt-compression--save-15-75-tokens-automatically) • [💰 Pricing](#-pricing-at-a-glance) • [🎯 Use Cases](#-use-cases--ready-made-combo-playbooks) • [🌍 Proxy](#-bypass-geographic-blocks--use-ai-from-any-country) • [❓ FAQ](#-frequently-asked-questions) • [📖 Docs](#-documentation) • [💬 WhatsApp](https://chat.whatsapp.com/JI7cDQ1GyaiDHhVBpLxf8b?mode=gi_t)+[🚀 Quick Start](#-quick-start) • [💡 Features](#-key-features) • [🗜️ Compression](#%EF%B8%8F-prompt-compression--save-15-95-eligible-tokens-automatically) • [💰 Pricing](#-pricing-at-a-glance) • [🎯 Use Cases](#-use-cases--ready-made-combo-playbooks) • [🌍 Proxy](#-bypass-geographic-blocks--use-ai-from-any-country) • [❓ FAQ](#-frequently-asked-questions) • [📖 Docs](#-documentation) • [💬 WhatsApp](https://chat.whatsapp.com/JI7cDQ1GyaiDHhVBpLxf8b?mode=gi_t)</div>@@ -219,7 +219,7 @@ _Connect any AI-powered IDE or CLI tool through OmniRoute — free API gateway f**OmniRoute solves all of this:**-✅ **Prompt Compression** — auto-compress prompts & tool outputs, save 15-75% tokens per request+✅ **Prompt Compression** — auto-compress prompts & tool outputs, save 15-95% eligible tokens per request with RTK+Caveman stacked mode✅ **Maximize subscriptions** — track quota, use every bit before reset✅ **Auto fallback** — Subscription → API Key → Cheap → Free, zero downtime✅ **Multi-account** — round-robin between accounts per provider@@ -410,7 +410,7 @@ Alibaba · Amazon Q · AssemblyAI · Baidu Qianfan · Baseten · Black Forest La↓┌──────────────────────────────────────────────────┐│ OmniRoute (Smart Router) │-│ • 🗜️ Prompt Compression (save 15-75% tokens) │+│ • 🗜️ Prompt Compression (save 15-95% eligible) ││ • Format translation (OpenAI ↔ Claude ↔ Gemini) ││ • Quota tracking + Embeddings + Images ││ • Auto token refresh + Rate limit management │@@ -424,14 +424,14 @@ Alibaba · Amazon Q · AssemblyAI · Baidu Qianfan · Baseten · Black Forest La│ ↓ budget limit└─→ [Tier 4: FREE] Qoder, Qwen, Kiro (unlimited)-Result: Never stop coding, minimal cost + 15-75% token savings+Result: Never stop coding, minimal cost + 15-95% eligible token savings```----## 🗜️ Prompt Compression — Save 15-75% Tokens Automatically+## 🗜️ Prompt Compression — Save 15-95% Eligible Tokens Automatically-> **Why use many token when few token do trick?** OmniRoute's built-in compression pipeline reduces token usage on every request — before it even reaches the provider. Inspired by [Caveman](https://github.com/JuliusBrussee/caveman) (⭐ 51K+).+> **Why use many token when few token do trick?** OmniRoute's built-in compression pipeline reduces token usage before requests reach the provider. It combines ideas from [RTK - Rust Token Killer](https://github.com/rtk-ai/rtk) and [Caveman](https://github.com/JuliusBrussee/caveman) (⭐ 51K+).### How It Works@@ -440,16 +440,18 @@ Every request passes through the compression pipeline **transparently** — no c```┌──────────────────┐ ┌─────────────────────────────┐ ┌──────────────┐│ Client sends │────▶│ OmniRoute Compression │────▶│ Provider │-│ full prompt │ │ Pipeline (5 modes) │ │ receives │+│ full prompt │ │ Pipeline (7 options) │ │ receives ││ (10,000 tok) │ │ │ │ compressed │-│ │ │ 🪶 Lite ........... ~15% │ │ (2,500 tok) │+│ │ │ 🪶 Lite ........... ~15% │ │ (~1,080 tok)││ │ │ 🪨 Standard ....... ~30% │ │ │-│ │ │ ⚡ Aggressive ..... ~50% │ │ 💰 75% saved │+│ │ │ ⚡ Aggressive ..... ~50% │ │ 💰 up to 95%││ │ │ 🔥 Ultra .......... ~75% │ │ │+│ │ │ 🧰 RTK ............ 60-90% │ │ │+│ │ │ 🔗 Stacked ........ 78-95% │ │ │└──────────────────┘ └─────────────────────────────┘ └──────────────┘```-### 5 Compression Modes+### 7 Compression Options| Mode | Savings | Technique | Best For || ------------------------- | ------- | ----------------------------------------------------------------------------------------------- | -------------------------------------- |@@ -458,6 +460,36 @@ Every request passes through the compression pipeline **transparently** — no c| **🪨 Standard (Caveman)** | ~30% | 30+ regex rules: filler removal, context condensation, structural compression, multi-turn dedup | Daily coding with Claude/Codex || **⚡ Aggressive** | ~50% | All standard + progressive message aging + tool result summarization + LLM-based compression | Long sessions with many tool calls || **🔥 Ultra** | ~75% | All aggressive + heuristic token pruning + stopword removal + score-based filtering | Maximum savings when tokens are scarce |+| **🧰 RTK** | 60-90% | 49 command-aware filters, RTK-style JSON DSL, verify gate, trust-gated custom filters | Shell/test/build/git output in agents |+| **🔗 Stacked** | 78-95% | RTK first, then Caveman input condensation; ~89% with upstream average math | Mixed prompts with tool logs + prose |++### RTK + Caveman Savings Math++These numbers are based on the upstream project READMEs under `_references/_outros`:++| Source | Upstream claim used by OmniRoute docs |+| ------- | ------------------------------------------------------------------------------------------------------------------- |+| Caveman | `~75%` fewer output tokens; benchmark average `65%` output savings, range `22-87%`; `~46%` input compression tool |+| RTK | `60-90%` command-output token savings; sample session `~118,000 -> ~23,900` tokens, which is `79.7%` saved (`~80%`) |++For the default stacked compression combo, OmniRoute runs:++```txt+RTK -> Caveman+```++When both engines can act on the same tool/context payload, the savings compound:++```txt+combined = 1 - (1 - RTK savings) * (1 - Caveman input savings)+average = 1 - (1 - 0.80) * (1 - 0.46) = 89.2%+range = 1 - (1 - 0.60..0.90) * (1 - 0.46) = 78.4-94.6%+```++Caveman output mode is separate from prompt compression. When enabled for responses, use Caveman's+own upstream output numbers: `65%` average, `~75%` headline, `22-87%` observed range. Total bill+savings depend on the prompt/output mix, but coding-agent sessions are often tool-context heavy, so+the `RTK -> Caveman` combo is the best default for maximum context savings.### Before & After (Standard/Caveman Mode)@@ -481,6 +513,8 @@ Request Body├─ lite.ts ─────────────── Whitespace, dedup, image URLs, redundant content├─ caveman.ts ──────────── 30+ regex rules via cavemanRules.ts│ └─ preservation.ts ─── Protects code blocks, URLs, JSON from compression+ ├─ engines/rtk/ ────────── Command detection + JSON DSL filters + raw-output recovery+ ├─ engines/registry.ts ─── Shared engine registry for caveman, RTK, and stacked├─ aggressive.ts ───────── Summarizer + tool result compressor + progressive aging│ ├─ summarizer.ts ───── Rule-based message summarization│ ├─ toolResultCompressor.ts ── file/grep/shell/JSON/error compression@@ -492,7 +526,7 @@ Request Body### Configuration```-Dashboard → Settings → Compression → Pick your mode+Dashboard → Context & Cache → Caveman / RTK / Compression Combos```Or per-combo override:@@ -508,9 +542,11 @@ Or per-combo override:Auto-trigger: set `autoTriggerTokens` to automatically enable compression when a request exceeds a token threshold.-> 🪨 **Fun fact:** The standard/caveman mode is inspired by [Caveman](https://github.com/JuliusBrussee/caveman) — the viral project that proved "caveman speak" cuts 65% of tokens while keeping 100% technical accuracy. OmniRoute takes this further with a **5-mode pipeline** that goes from gentle whitespace cleanup all the way to aggressive heuristic pruning.+Compression combos can also assign a named compression pipeline to routing combos, so a coding combo can use RTK + Caveman while a paid subscription combo stays on lite mode.++> 🪨 **Fun fact:** The standard/caveman mode is inspired by [Caveman](https://github.com/JuliusBrussee/caveman) — the viral project that reports 65% average output-token savings while keeping technical accuracy. OmniRoute takes this further with a **7-option pipeline** and a default `RTK -> Caveman` combo that can reach ~89% average savings on eligible tool/context payloads.-📖 **Full compression documentation:** [`docs/COMPRESSION_GUIDE.md`](docs/COMPRESSION_GUIDE.md)+📖 **Full compression documentation:** [`docs/COMPRESSION_GUIDE.md`](docs/COMPRESSION_GUIDE.md) • [`docs/RTK_COMPRESSION.md`](docs/RTK_COMPRESSION.md) • [`docs/COMPRESSION_ENGINES.md`](docs/COMPRESSION_ENGINES.md) • [`docs/COMPRESSION_RULES_FORMAT.md`](docs/COMPRESSION_RULES_FORMAT.md) • [`docs/COMPRESSION_LANGUAGE_PACKS.md`](docs/COMPRESSION_LANGUAGE_PACKS.md)---@@ -933,8 +969,8 @@ Then in `/dashboard/media` → **Transcription** tab: upload any audio or video| ---------------------------------------------------------------------------------------------------- | -------------------------------- || 🧠 **Smart 4-Tier Fallback** — Subscription → API → Cheap → Free | Never stop coding, zero downtime || 🔄 **Format Translation** — OpenAI ↔ Claude ↔ Gemini ↔ Responses API | Works with ANY CLI tool |-| 🗜️ **Prompt Compression** — 5-mode pipeline (off → lite → standard → aggressive → ultra) | Save 15-75% tokens automatically |-| 🤖 **MCP Server** — 29 tools, 3 transports (stdio/SSE/HTTP), 10 scopes | IDE/agent tool integration |+| 🗜️ **Prompt Compression** — 7 options including Caveman, RTK, and stacked pipelines | Save 15-95% eligible tokens |+| 🤖 **MCP Server** — 37 tools, 3 transports (stdio/SSE/HTTP), 10 scopes | IDE/agent tool integration || 🛡️ **Resilience Engine** — circuit breakers, cooldowns, TLS spoofing, anti-thundering herd | Auto-recovery from any failure || 🎵 **10 Multi-Modal APIs** — chat, embed, images, video, music, TTS, STT, moderation, rerank, search | One endpoint for everything || 🌍 **3-Level Proxy** — global, per-provider, per-key + 1proxy free marketplace | Access AI from any country |@@ -1142,7 +1178,7 @@ curl http://localhost:20128/.well-known/agent.json- [User Guide](docs/USER_GUIDE.md) — Providers, combos, CLI integration- [API Reference](docs/API_REFERENCE.md) — All endpoints with examples-- [MCP Server](open-sse/mcp-server/README.md) — 29 tools, IDE configs+- [MCP Server](open-sse/mcp-server/README.md) — 37 tools, IDE configs- [A2A Server](src/lib/a2a/README.md) — JSON-RPC, skills, streaming- [Environment Config](docs/ENVIRONMENT.md) — Complete `.env` reference- [VM Deployment](docs/VM_DEPLOYMENT_GUIDE.md) — VM + nginx + Cloudflare@@ -1325,16 +1361,20 @@ See the [Proxy Guide](docs/PROXY_GUIDE.md) for setup instructions.### 🧠 Features & Architecture-| Document | Description |-| -------------------------------------------------------- | ---------------------------------------------------------------------- |-| [Architecture](docs/ARCHITECTURE.md) | System architecture, data flow, and internals |-| [Compression Guide](docs/COMPRESSION_GUIDE.md) | 5-mode pipeline: off / lite / standard / aggressive / ultra |-| [Resilience Guide](docs/RESILIENCE_GUIDE.md) | Circuit breakers, cooldowns, queue, anti-thundering herd, TLS spoofing |-| [Auto-Combo Engine](docs/AUTO-COMBO.md) | 6-factor scoring, mode packs, self-healing |-| [Proxy Guide](docs/PROXY_GUIDE.md) | 3-level proxy system, 1proxy marketplace, registry CRUD |-| [Free Tiers](docs/FREE_TIERS.md) | 25+ free API providers consolidated directory |-| [Features Gallery](docs/FEATURES.md) | Visual dashboard tour with screenshots |-| [Codebase Documentation](docs/CODEBASE_DOCUMENTATION.md) | Beginner-friendly codebase walkthrough |+| Document | Description |+| ---------------------------------------------------------------- | ----------------------------------------------------------------------------- |+| [Architecture](docs/ARCHITECTURE.md) | System architecture, data flow, and internals |+| [Compression Guide](docs/COMPRESSION_GUIDE.md) | 7-option pipeline: off / lite / standard / aggressive / ultra / RTK / stacked |+| [RTK Compression](docs/RTK_COMPRESSION.md) | Command-output compression, filters, trust, verify, raw-output recovery |+| [Compression Engines](docs/COMPRESSION_ENGINES.md) | Caveman, RTK, stacked pipelines, dashboard/API/MCP surfaces |+| [Compression Rules Format](docs/COMPRESSION_RULES_FORMAT.md) | JSON rule-pack schemas for Caveman and RTK filters |+| [Compression Language Packs](docs/COMPRESSION_LANGUAGE_PACKS.md) | Language detection and Caveman rule-pack authoring |+| [Resilience Guide](docs/RESILIENCE_GUIDE.md) | Circuit breakers, cooldowns, queue, anti-thundering herd, TLS spoofing |+| [Auto-Combo Engine](docs/AUTO-COMBO.md) | 6-factor scoring, mode packs, self-healing |+| [Proxy Guide](docs/PROXY_GUIDE.md) | 3-level proxy system, 1proxy marketplace, registry CRUD |+| [Free Tiers](docs/FREE_TIERS.md) | 25+ free API providers consolidated directory |+| [Features Gallery](docs/FEATURES.md) | Visual dashboard tour with screenshots |+| [Codebase Documentation](docs/CODEBASE_DOCUMENTATION.md) | Beginner-friendly codebase walkthrough |### 🤖 Protocols & APIs@@ -1459,10 +1499,12 @@ gh release create v2.0.0 --title "v2.0.0" --generate-notesSpecial thanks to **[9router](https://github.com/decolua/9router)** by **[decolua](https://github.com/decolua)** — the original project that inspired this fork. OmniRoute builds upon that incredible foundation with additional features, multi-modal APIs, and a full TypeScript rewrite.-Special thanks to **[CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI)** — the original Go implementation that inspired this JavaScript port.+Special thanks to **[CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI)** by **[router-for-me](https://github.com/router-for-me)** — the original Go implementation that inspired this JavaScript port.Special thanks to **[Caveman](https://github.com/JuliusBrussee/caveman)** by **[JuliusBrussee](https://github.com/JuliusBrussee)** (⭐ 51K+) — the viral "why use many token when few token do trick" project whose caveman-speak compression philosophy inspired OmniRoute's standard compression mode and 30+ filler/condensation regex rules.+Special thanks to **[RTK - Rust Token Killer](https://github.com/rtk-ai/rtk)** by **[RTK AI](https://github.com/rtk-ai)** — the high-performance command-output compression project whose terminal, build, test, git, and tool-output filtering model inspired OmniRoute's RTK engine, JSON filter DSL, raw-output recovery, and stacked RTK → Caveman compression pipeline.+---## 📄 Licensediff --git a/docs/API_REFERENCE.md b/docs/API_REFERENCE.mdindex 3b4c38ec29..dfec7d1198 100644--- a/docs/API_REFERENCE.md+++ b/docs/API_REFERENCE.md@@ -216,14 +216,32 @@ Response example:### Settings-| Endpoint | Method | Description |-| ------------------------------- | ------------- | ---------------------- |-| `/api/settings` | GET/PUT/PATCH | General settings |-| `/api/settings/proxy` | GET/PUT | Network proxy config |-| `/api/settings/proxy/test` | POST | Test proxy connection |-| `/api/settings/ip-filter` | GET/PUT | IP allowlist/blocklist |-| `/api/settings/thinking-budget` | GET/PUT | Reasoning token budget |-| `/api/settings/system-prompt` | GET/PUT | Global system prompt |+| Endpoint | Method | Description |+| ------------------------------- | ------------- | ------------------------- |+| `/api/settings` | GET/PUT/PATCH | General settings |+| `/api/settings/proxy` | GET/PUT | Network proxy config |+| `/api/settings/proxy/test` | POST | Test proxy connection |+| `/api/settings/ip-filter` | GET/PUT | IP allowlist/blocklist |+| `/api/settings/thinking-budget` | GET/PUT | Reasoning token budget |+| `/api/settings/system-prompt` | GET/PUT | Global system prompt |+| `/api/settings/compression` | GET/PUT | Global compression config |++### Context & Compression++| Endpoint | Method | Description |+| -------------------------------------- | -------------- | ------------------------------------------------------------------------ |+| `/api/compression/preview` | POST | Preview off/lite/standard/aggressive/ultra/RTK/stacked compression |+| `/api/compression/language-packs` | GET | List available Caveman language packs |+| `/api/compression/rules` | GET | List Caveman rule metadata |+| `/api/context/caveman/config` | GET/PUT | Caveman-specific settings alias |+| `/api/context/rtk/config` | GET/PUT | RTK-specific settings, including custom filters and raw-output retention |+| `/api/context/rtk/filters` | GET | RTK filter catalog and custom-filter diagnostics |+| `/api/context/rtk/test` | POST | Run RTK preview/test against a text payload |+| `/api/context/rtk/raw-output/[id]` | GET | Read retained redacted raw output by pointer id |+| `/api/context/combos` | GET/POST | Compression combo list/create |+| `/api/context/combos/[id]` | GET/PUT/DELETE | Compression combo detail/update/delete |+| `/api/context/combos/[id]/assignments` | GET/PUT | Assign compression combos to routing combos |+| `/api/context/analytics` | GET | Compression analytics alias |### Monitoring@@ -451,11 +469,12 @@ Content-Type: application/json2. Route handler calls `handleChat`, `handleEmbedding`, `handleAudioTranscription`, or `handleImageGeneration`3. Model is resolved (direct provider/model or alias/combo)4. Credentials selected from local DB with account availability filtering-5. For chat: `handleChatCore` — format detection, translation, cache check, idempotency check-6. Provider executor sends upstream request-7. Response translated back to client format (chat) or returned as-is (embeddings/images/audio)-8. Usage/logging recorded-9. Fallback applies on errors according to combo rules+5. For chat: `handleChatCore` checks semantic/signature cache and resolves combo compression settings+6. Proactive compression runs before provider translation when enabled (`lite`, Caveman, RTK, or stacked)+7. Provider executor sends upstream request+8. Response translated back to client format (chat) or returned as-is (embeddings/images/audio)+9. Usage, compression analytics, and request logs are recorded+10. Fallback applies on errors according to combo rulesFull architecture reference: [`ARCHITECTURE.md`](ARCHITECTURE.md)diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 948004b42a..cd08c672d7 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -2,7 +2,7 @@🌐 **Languages:** 🇺🇸 [English](ARCHITECTURE.md) | 🇧🇷 [Português (Brasil)](i18n/pt-BR/ARCHITECTURE.md) | 🇪🇸 [Español](i18n/es/ARCHITECTURE.md) | 🇫🇷 [Français](i18n/fr/ARCHITECTURE.md) | 🇮🇹 [Italiano](i18n/it/ARCHITECTURE.md) | 🇷🇺 [Русский](i18n/ru/ARCHITECTURE.md) | 🇨🇳 [中文 (简体)](i18n/zh-CN/ARCHITECTURE.md) | 🇩🇪 [Deutsch](i18n/de/ARCHITECTURE.md) | 🇮🇳 [हिन्दी](i18n/in/ARCHITECTURE.md) | 🇹🇭 [ไทย](i18n/th/ARCHITECTURE.md) | 🇺🇦 [Українська](i18n/uk-UA/ARCHITECTURE.md) | 🇸🇦 [العربية](i18n/ar/ARCHITECTURE.md) | 🇯🇵 [日本語](i18n/ja/ARCHITECTURE.md) | 🇻🇳 [Tiếng Việt](i18n/vi/ARCHITECTURE.md) | 🇧🇬 [Български](i18n/bg/ARCHITECTURE.md) | 🇩🇰 [Dansk](i18n/da/ARCHITECTURE.md) | 🇫🇮 [Suomi](i18n/fi/ARCHITECTURE.md) | 🇮🇱 [עברית](i18n/he/ARCHITECTURE.md) | 🇭🇺 [Magyar](i18n/hu/ARCHITECTURE.md) | 🇮🇩 [Bahasa Indonesia](i18n/id/ARCHITECTURE.md) | 🇰🇷 [한국어](i18n/ko/ARCHITECTURE.md) | 🇲🇾 [Bahasa Melayu](i18n/ms/ARCHITECTURE.md) | 🇳🇱 [Nederlands](i18n/nl/ARCHITECTURE.md) | 🇳🇴 [Norsk](i18n/no/ARCHITECTURE.md) | 🇵🇹 [Português (Portugal)](i18n/pt/ARCHITECTURE.md) | 🇷🇴 [Română](i18n/ro/ARCHITECTURE.md) | 🇵🇱 [Polski](i18n/pl/ARCHITECTURE.md) | 🇸🇰 [Slovenčina](i18n/sk/ARCHITECTURE.md) | 🇸🇪 [Svenska](i18n/sv/ARCHITECTURE.md) | 🇵🇭 [Filipino](i18n/phi/ARCHITECTURE.md) | 🇨🇿 [Čeština](i18n/cs/ARCHITECTURE.md)-_Last updated: 2026-04-15_+_Last updated: 2026-05-02_## Executive Summary@@ -52,12 +52,13 @@ Core capabilities:- Compliance audit logging with opt-out per API key- Eval framework for LLM quality assurance- Health dashboard with real-time provider circuit breaker status-- MCP Server (29 tools) with 3 transports (stdio/SSE/Streamable HTTP)+- MCP Server (37 tools) with 3 transports (stdio/SSE/Streamable HTTP)- A2A Server (JSON-RPC 2.0 + SSE) with skills and task lifecycle- Memory system (extraction, injection, retrieval, summarization)- Skills system (registry, executor, sandbox, built-in skills)- MITM proxy with certificate management and DNS handling- Prompt injection guard middleware+- Prompt compression pipeline with Caveman, RTK, stacked pipelines, compression combos, language packs, and analytics- ACP (Agent Communication Protocol) registry- Modular OAuth providers (13 individual modules under `src/lib/oauth/providers/`)- Uninstall/full-uninstall scripts@@ -112,6 +113,9 @@ Main pages under `src/app/(dashboard)/dashboard/`:- `/dashboard/health` — uptime, circuit breakers, rate limits, quota-monitored sessions- `/dashboard/logs` — request/proxy/audit/console logs- `/dashboard/settings` — system settings tabs (general, routing, combo defaults, etc.)+- `/dashboard/context/caveman` — Caveman compression rules, language packs, preview, and output mode+- `/dashboard/context/rtk` — RTK command-output filters, preview, and runtime safety settings+- `/dashboard/context/combos` — named compression pipelines assigned to routing combos- `/dashboard/api-manager` — API key lifecycle and model permissions## High-Level System Context@@ -203,6 +207,8 @@ Management domains:- IP filter: `src/app/api/settings/ip-filter` (GET/PUT)- Thinking budget: `src/app/api/settings/thinking-budget` (GET/PUT)- System prompt: `src/app/api/settings/system-prompt` (GET/PUT)+- Compression: `src/app/api/settings/compression`, `src/app/api/compression/*`, and+ `src/app/api/context/*`- Sessions: `src/app/api/sessions` (GET)- Rate limits: `src/app/api/rate-limits` (GET)- Resilience: `src/app/api/resilience` (GET/PATCH) — request queue, connection cooldown, provider breaker, wait-for-cooldown config@@ -252,6 +258,8 @@ Services (business logic):- Rate limit management: `open-sse/services/rateLimitManager.ts`- Circuit breaker: `open-sse/services/circuitBreaker.ts`- Context handoff: `open-sse/services/contextHandoff.ts` — handoff summary generation and injection for context-relay strategy+- Compression: `open-sse/services/compression/*` — proactive compression before provider translation;+ includes Caveman rules, RTK filters, stacked pipelines, compression combos, stats, and validation- Codex quota fetcher: `open-sse/services/codexQuotaFetcher.ts` — fetches Codex quota for context-relay handoff decisions- Cooldown-aware retry: `src/sse/services/cooldownAwareRetry.ts` — per-model cooldown retries with configurable `requestRetry` / `maxRetryIntervalSec`- Safe outbound fetch: `src/shared/network/safeOutboundFetch.ts` — guarded provider/model fetch with SSRF guard, private-URL blocking, retry, and timeout@@ -630,6 +638,12 @@ flowchart LR- `src/app/api/settings/ip-filter`: IP allowlist/blocklist (GET/PUT)- `src/app/api/settings/thinking-budget`: thinking token budget config (GET/PUT)- `src/app/api/settings/system-prompt`: global system prompt (GET/PUT)+- `src/app/api/settings/compression`: global compression settings (GET/PUT)+- `src/app/api/compression/*`: compression preview, rule metadata, and language packs+- `src/app/api/context/caveman/config`: Caveman settings alias (GET/PUT)+- `src/app/api/context/rtk/*`: RTK config, filter catalog, test endpoint, and raw-output recovery+- `src/app/api/context/combos*`: compression combo CRUD and routing-combo assignments+- `src/app/api/context/analytics`: compression analytics alias- `src/app/api/sessions`: active session listing (GET)- `src/app/api/rate-limits`: per-account rate limit status (GET)- `src/app/api/sync/tokens`: sync token CRUD (GET/POST)diff --git a/docs/COMPRESSION_ENGINES.md b/docs/COMPRESSION_ENGINES.mdnew file mode 100644index 0000000000..81dc01c1ba--- /dev/null+++ b/docs/COMPRESSION_ENGINES.md@@ -0,0 +1,143 @@+# Compression Engines++OmniRoute compression is built around engine contracts. A mode can run one engine directly+(`caveman` or `rtk`) or a deterministic stacked pipeline that executes multiple engines in order.++## Modes++| Mode | Engine path | Intended input |+| ------------ | ---------------------------------- | -------------------------------------------- |+| `off` | none | Exact prompt preservation |+| `lite` | Caveman lite helpers | Low-risk always-on cleanup |+| `standard` | Caveman | Natural-language prompt condensation |+| `aggressive` | Caveman + history/tool summarizers | Long chat sessions |+| `ultra` | Caveman + pruning helpers | Context-limit recovery |+| `rtk` | RTK | Terminal, shell, build, test, and git output |+| `stacked` | Pipeline, default `rtk -> caveman` | Mixed tool logs and prose, max savings |++## Engine Registry++The registry lives in `open-sse/services/compression/engines/registry.ts`. Engines expose a shared+contract:++- `id`: stable engine id such as `caveman` or `rtk`+- `label`: dashboard-readable name+- `supports(mode)`: whether the engine can execute a compression mode+- `compress(input)`: transforms text/messages and returns stats++`strategySelector.ts` registers the built-in engines before compression runs. This lets preview,+runtime compression, stacked mode, tests, and future engines use the same execution path.++## Caveman++Caveman mode focuses on semantic condensation of normal prose:++- preserves code blocks, URLs, JSON, paths, and structured data+- removes filler, hedging, repeated context, and verbose connective phrasing+- supports language-aware file rule packs in `open-sse/services/compression/rules/`+- remains available through the legacy `standard`, `aggressive`, and `ultra` modes++The dashboard surface is `Dashboard -> Context & Cache -> Caveman`.++Caveman upstream reports `~75%` fewer output tokens, `65%` average output savings in benchmarks+with a `22-87%` range, and a `~46%` input-compression tool. OmniRoute uses the Caveman input-side+number when documenting stacked prompt/context savings; Caveman output mode remains a separate+response-behavior feature.++## RTK++RTK mode focuses on command and tool output:++- detects output classes such as `git status`, `git branch`, `git diff`, Vitest/Jest/Pytest,+ Cargo/Go tests, TypeScript/Vite/Webpack builds, ESLint, npm audit/installs, Docker logs,+ shell `find`/`grep`, stack traces, and generic logs+- applies 49 JSON filters from `open-sse/services/compression/engines/rtk/filters/`+- supports the RTK-style declarative pipeline: ANSI stripping, replace, match-output short-circuit,+ strip/keep lines, per-line truncation, head/tail/max-line truncation, and on-empty fallback+- supports trust-gated project filters in `.rtk/filters.json` and global filters in+ `DATA_DIR/rtk/filters.json`+- strips ANSI sequences, progress noise, repeated lines, and unhelpful boilerplate+- preserves actionable failures, warnings, summaries, changed files, and tail context+- can optionally retain redacted raw output for recovery/debugging through authenticated management+ routes++The dashboard surface is `Dashboard -> Context & Cache -> RTK`.++Operational details for custom filters, trust, verify, and raw-output recovery live in+[`RTK_COMPRESSION.md`](RTK_COMPRESSION.md).++RTK upstream reports `60-90%` savings for command-output compression. Its README example shows a+30-minute Claude Code session going from `~118,000` tokens to `~23,900`, or `79.7%` saved.++## Stacked Pipelines++Stacked mode runs pipeline steps in order. The default is:++```txt+rtk -> caveman+```++Use this for coding-agent sessions where a prompt combines command output with human or assistant+prose. RTK reduces noisy tool logs first, then Caveman compresses remaining natural language.++Pipeline steps are configured with `stackedPipeline` in compression settings or through compression+combos.++When both engines reduce the same eligible payload, savings compound:++```txt+combined = 1 - (1 - RTK savings) * (1 - Caveman input savings)+average = 1 - (1 - 0.80) * (1 - 0.46) = 89.2%+range = 1 - (1 - 0.60..0.90) * (1 - 0.46) = 78.4-94.6%+```++## Compression Combos++Compression combos are named compression profiles that can be assigned to routing combos:++- `compression_combos`: stores mode, pipeline, RTK config, language config, and default marker+- `compression_combo_assignments`: maps a compression combo to a routing combo+- runtime integration resolves an assigned compression combo before generic combo overrides+- analytics include `compression_combo_id` and `engine`++Dashboard surface: `Dashboard -> Context & Cache -> Compression Combos`.++## API Surface++| Route | Purpose |+| -------------------------------------- | ------------------------------------------ |+| `/api/settings/compression` | Global compression settings |+| `/api/compression/preview` | Preview any compression mode |+| `/api/compression/language-packs` | List available Caveman language packs |+| `/api/context/caveman/config` | Caveman settings alias |+| `/api/context/rtk/config` | RTK defaults and settings |+| `/api/context/rtk/filters` | RTK filter catalog |+| `/api/context/rtk/test` | RTK preview/test endpoint |+| `/api/context/rtk/raw-output/[id]` | Authenticated redacted raw-output recovery |+| `/api/context/combos` | Compression combo CRUD |+| `/api/context/combos/[id]/assignments` | Routing-combo assignment CRUD |+| `/api/context/analytics` | Compression analytics alias |++Management routes require management authentication or API-key policy checks.++## MCP Tools++Compression exposes five MCP tools:++| Tool | Scope | Purpose |+| ----------------------------------- | ------------------- | -------------------------------- |+| `omniroute_compression_status` | `read:compression` | Settings, analytics, cache stats |+| `omniroute_compression_configure` | `write:compression` | Update global settings |+| `omniroute_set_compression_engine` | `write:compression` | Set mode and optional pipeline |+| `omniroute_list_compression_combos` | `read:compression` | List compression combos |+| `omniroute_compression_combo_stats` | `read:compression` | Read combo/engine analytics |++## Validation++The focused gates for this area are:++```bash+node --import tsx/esm --test tests/unit/compression/rtk-*.test.ts tests/unit/compression/pipeline-integration.test.ts tests/unit/compression/context-compression-api.test.ts+node --import tsx/esm --test tests/unit/compression/*.test.ts tests/golden-set/*.test.ts tests/integration/compression-pipeline.test.ts tests/unit/api/compression/compression-api.test.ts+npm run typecheck:core+```diff --git a/docs/COMPRESSION_GUIDE.md b/docs/COMPRESSION_GUIDE.mdindex a6db971396..88213bfc63 100644--- a/docs/COMPRESSION_GUIDE.md+++ b/docs/COMPRESSION_GUIDE.md@@ -1,6 +1,6 @@# 🗜️ Prompt Compression Guide — OmniRoute-> Save 15-75% on token costs automatically. For a quick overview, see the [README Compression section](../README.md#%EF%B8%8F-prompt-compression--save-15-75-tokens-automatically).+> Save 15-95% on eligible context automatically. For a quick overview, see the [README Compression section](../README.md#%EF%B8%8F-prompt-compression--save-15-95-eligible-tokens-automatically).## Overview@@ -19,6 +19,8 @@ Client Request→ Standard: Caveman-speak filler removal (~30%)→ Aggressive: History aging + summarization (~50%)→ Ultra: Heuristic pruning + code-block thinning (~75%)+ → RTK: Command-aware terminal/tool-output filtering (60-90% upstream range)+ → Stacked: Ordered multi-engine pipeline, usually RTK then Caveman (78-95% eligible range)→ Compressed Request → Provider```@@ -77,6 +79,65 @@ Maximum compression for token-critical scenarios:**Best for:** When you're hitting context limits repeatedly.+### RTK Mode (60-90% upstream range)++RTK mode is optimized for verbose tool outputs that appear in coding-agent sessions:++- Detects command/output classes such as `git status`, `git diff`, `git log`, test runners,+ TypeScript/Vite/Webpack builds, ESLint/Biome/Prettier, npm audit/installs, Docker logs, infra+ output, and generic shell output+- Applies JSON filter packs from `open-sse/services/compression/engines/rtk/filters/`+- Ships 49 built-in filters with inline verify samples+- Removes ANSI control sequences, progress bars, repeated lines, and non-actionable noise+- Preserves failures, errors, warnings, changed files, summaries, and the tail of long output+- Supports trust-gated project filters, global filters, and optional redacted raw-output recovery++**Best for:** Agent sessions with shell, build, test, git, grep, and file-output transcripts.++### Stacked Mode (78-95% eligible range)++Stacked mode runs multiple compression engines in a deterministic order. The default pipeline is:++```txt+RTK -> Caveman+```++That order keeps terminal/tool output compact first, then applies Caveman semantic condensation to+the remaining natural-language prompt. Stacked pipelines can be configured globally or through+compression combos assigned to routing combos.++**Best for:** Mixed context with large tool logs plus human instructions or assistant summaries.++---++## Upstream Savings Math++OmniRoute documents compression savings from two sources: upstream project benchmarks and+OmniRoute's own engine composition.++| Source | Upstream README number used here |+| ------- | --------------------------------------------------------------------------------------------------------------------- |+| Caveman | `~75%` fewer output tokens, `65%` benchmark average output savings, `22-87%` range, and `~46%` input compression tool |+| RTK | `60-90%` command-output savings; sample session `~118,000 -> ~23,900` tokens, or `79.7%` saved (`~80%`) |++For overlapping tool/context payloads, the default OmniRoute combo stacks the engines:++```txt+RTK -> Caveman+```++The combined savings are multiplicative, not additive:++```txt+combined = 1 - (1 - RTK savings) * (1 - Caveman input savings)+average = 1 - (1 - 0.80) * (1 - 0.46) = 89.2%+range = 1 - (1 - 0.60..0.90) * (1 - 0.46) = 78.4-94.6%+```++That `78-95%` number applies when both RTK and Caveman can reduce the same input/context payload.+Caveman response output mode is separate: when enabled, use Caveman's own output savings (`65%`+average, `~75%` headline, `22-87%` range). Total billing savings depend on your prompt/output mix.+---## Token Savings Visualization@@ -87,6 +148,8 @@ With Lite: 40K tokens sent (15% saved — safe, always-on)With Standard: 33K tokens sent (30% saved — caveman-speak rules)With Aggressive: 24K tokens sent (50% saved — aging + summarization)With Ultra: 12K tokens sent (75% saved — heuristic pruning)+With RTK: 19K-5K tokens sent (60-90% saved on command/tool output)+With Stacked: 10K-2.5K tokens sent (78-95% eligible RTK+Caveman range)```---@@ -95,25 +158,29 @@ With Ultra: 12K tokens sent (75% saved — heuristic pruning)### Dashboard-Navigate to `Dashboard → Settings → Compression`:+Navigate to `Dashboard → Context & Cache`:-- **Default Mode** — sets the system-wide compression mode+- **Caveman** — mode selection, language packs, preview, and global defaults+- **RTK** — command-filter preview, RTK safety settings, and filter catalog+- **Compression Combos** — named engine pipelines assigned to routing combos- **Auto-Trigger Threshold** — automatically engage compression when token count exceeds threshold-- **Per-Combo Override** — each combo can have its own compression mode### Per-Combo Override-In `Dashboard → Combos → [Your Combo] → Advanced`, set compression mode per combo:+In `Dashboard → Context & Cache → Compression Combos`, assign a compression combo to a routing+combo:```txtCombo: "free-forever"- Mode: Standard+ Compression Combo: "coding-agent-stack"+ Pipeline: RTK -> CavemanTargets:1. gc/gemini-3-flash2. if/kimi-k2-thinking```-This lets you use aggressive compression on free providers while keeping lite mode on paid subscriptions.+This lets you use stacked compression on free/coding providers while keeping lite mode on paid+subscriptions.### API@@ -124,7 +191,20 @@ curl http://localhost:20128/api/settings/compression# Update compression settingscurl -X PUT http://localhost:20128/api/settings/compression \-H "Content-Type: application/json" \- -d '{"defaultMode":"lite","autoTriggerThreshold":32000}'+ -d '{"defaultMode":"stacked","autoTriggerMode":"stacked","autoTriggerTokens":32000}'++# Preview a specific RTK/stacked payload+curl -X POST http://localhost:20128/api/compression/preview \+ -H "Content-Type: application/json" \+ -d '{"mode":"rtk","messages":[{"role":"tool","content":"npm test output here"}]}'++# List RTK filter packs+curl http://localhost:20128/api/context/rtk/filters++# Test RTK directly with optional command metadata+curl -X POST http://localhost:20128/api/context/rtk/test \+ -H "Content-Type: application/json" \+ -d '{"command":"npm test","text":"FAIL tests/example.test.ts\nError: boom"}'```---@@ -136,11 +216,14 @@ The compression engine **always preserves:**- ✅ Code blocks (fenced and inline)- ✅ URLs and file paths- ✅ JSON structures and structured data-- ✅ API keys, tokens, and identifiers+- ✅ Identifiers and protected technical tokens- ✅ Mathematical expressions- ✅ Tool/function call definitions- ✅ System prompts (in lite mode)+RTK raw-output recovery redacts common API keys, bearer tokens, Slack tokens, AWS access keys,+passwords, tokens, and secrets before anything is persisted.+---## Compression Stats@@ -154,7 +237,10 @@ Every compressed request includes stats in the server logs:"savingsPercent": 15.0,"techniquesUsed": ["collapseWhitespace", "dedupSystemPrompt"],"mode": "lite",- "latencyMs": 0.8+ "engine": "caveman",+ "compressionComboId": "coding-agent-stack",+ "durationMs": 0.8,+ "rtkRawOutputPointers": []}```@@ -166,13 +252,16 @@ Every compressed request includes stats in the server logs:| ------- | ------------------------------------ | ---------- || Phase 1 | Off, Lite | ✅ Shipped || Phase 2 | Standard, Aggressive, Ultra | ✅ Shipped |-| Phase 3 | Per-model adaptive, ML-based pruning | 🗓️ Planned |+| Phase 3 | RTK, Stacked, Compression Combos | ✅ Shipped |+| Phase 4 | Per-model adaptive, ML-based pruning | 🗓️ Planned |---## Acknowledgments-Standard mode compression rules are inspired by **[Caveman](https://github.com/JuliusBrussee/caveman)** by **[JuliusBrussee](https://github.com/JuliusBrussee)** (⭐ 51K+) — the viral "why use many token when few token do trick" project.+Standard mode compression rules are inspired by **[Caveman](https://github.com/JuliusBrussee/caveman)** by **[JuliusBrussee](https://github.com/JuliusBrussee)** (⭐ 51K+) — the viral "why use many token when few token do trick" project. Caveman reports `~75%` fewer output tokens, `65%` benchmark average output savings, a `22-87%` output range, and a `~46%` input-compression tool.++RTK mode is inspired by **[RTK - Rust Token Killer](https://github.com/rtk-ai/rtk)** by **[RTK AI](https://github.com/rtk-ai)** — the high-performance command-output compression project for terminal, build, test, git, and tool-output filtering. RTK reports `60-90%` savings, with its README sample session showing `~80%` saved.---@@ -181,3 +270,7 @@ Standard mode compression rules are inspired by **[Caveman](https://github.com/J- [Environment Config](ENVIRONMENT.md) — Compression environment variables- [Architecture Guide](ARCHITECTURE.md) — Compression pipeline internals- [User Guide](USER_GUIDE.md) — Getting started with compression+- [RTK Compression](RTK_COMPRESSION.md) — RTK filters, trust model, verify gate, raw-output recovery+- [Compression Engines](COMPRESSION_ENGINES.md) — Caveman, RTK, stacked, APIs, MCP, dashboard+- [Compression Rules Format](COMPRESSION_RULES_FORMAT.md) — JSON rule-pack format+- [Compression Language Packs](COMPRESSION_LANGUAGE_PACKS.md) — Language-specific Caveman rulesdiff --git a/docs/COMPRESSION_LANGUAGE_PACKS.md b/docs/COMPRESSION_LANGUAGE_PACKS.mdnew file mode 100644index 0000000000..805a7db1fc--- /dev/null+++ b/docs/COMPRESSION_LANGUAGE_PACKS.md@@ -0,0 +1,96 @@+# Compression Language Packs++Caveman compression can load language-specific rule packs in addition to the built-in English rules.+This keeps the core engine stable while allowing Portuguese, Spanish, German, French, Japanese, and+future language packs to evolve independently.++## Location++Language packs live under:++```txt+open-sse/services/compression/rules/<language>/+```++Current shipped packs include:++| Language | Directory |+| ------------------- | -------------- |+| English | `rules/en/` |+| Portuguese (Brazil) | `rules/pt-BR/` |+| Spanish | `rules/es/` |+| German | `rules/de/` |+| French | `rules/fr/` |+| Japanese | `rules/ja/` |++## Language Detection++`languageDetector.ts` uses lightweight heuristics to infer the language from prompt text. The+configured default language is still respected, and detection can be disabled by config when exact+control is required.++Detection output is used only to choose rule packs. It does not change provider routing, locale+selection, or UI language.++## Config Shape++Compression settings can include:++```json+{+ "languageConfig": {+ "enabled": true,+ "defaultLanguage": "en",+ "autoDetect": true,+ "enabledPacks": ["en", "pt-BR", "es", "de", "fr", "ja"]+ },+ "cavemanConfig": {+ "language": "en",+ "autoDetectLanguage": true,+ "enabledLanguagePacks": ["en", "pt-BR", "es", "de", "fr", "ja"]+ }+}+```++`languageConfig` controls dashboard/preview defaults. `cavemanConfig` is the runtime engine config+used when Caveman compresses message text.++## Adding a Language Pack++1. Create `open-sse/services/compression/rules/<language>/<pack>.json`.+2. Use the Caveman rule format from `docs/COMPRESSION_RULES_FORMAT.md`.+3. Keep replacements conservative and avoid changing code, identifiers, URLs, or JSON.+4. Add or update tests for language selection and replacement behavior.+5. Expose new dashboard/i18n labels if the language appears in UI selectors.++## API++Available packs can be queried with:++```bash+curl http://localhost:20128/api/compression/language-packs+```++The preview endpoint accepts language config overrides:++```bash+curl -X POST http://localhost:20128/api/compression/preview \+ -H "Content-Type: application/json" \+ -d '{+ "mode": "standard",+ "text": "Por favor, eu gostaria que voce basicamente resumisse isso.",+ "config": {+ "languageConfig": {+ "defaultLanguage": "pt-BR",+ "autoDetect": true+ }+ }+ }'+```++## Operational Notes++- English built-in rules remain the fallback when a language pack is missing.+- Invalid built-in JSON packs fail validation so release assets do not silently degrade.+- Rule packs are data-only and should not import code or run arbitrary logic.+- The compression analytics layer records the selected mode and engine, not full prompt text.diff --git a/docs/COMPRESSION_RULES_FORMAT.md b/docs/COMPRESSION_RULES_FORMAT.mdnew file mode 100644index 0000000000..e54343968b--- /dev/null+++ b/docs/COMPRESSION_RULES_FORMAT.md@@ -0,0 +1,186 @@+# Compression Rules Format++Compression rules are JSON files loaded at runtime. They are intentionally data-only so new+language packs and RTK command filters can be reviewed without changing engine code.++## Caveman Rule Packs++Caveman rule packs live under:++```txt+open-sse/services/compression/rules/<language>/<pack>.json+```++Each pack contains replacements that apply to normal prose after protected regions are isolated.++```json+{+ "language": "en",+ "category": "filler",+ "rules": [+ {+ "name": "question_to_directive",+ "pattern": "\\b(?:Can you explain why|Could you show me how)\\b\\s*",+ "replacement": "Explain why ",+ "replacementMap": {+ "can you explain why": "Explain why ",+ "could you show me how": "Show how "+ },+ "flags": "gi",+ "context": "all",+ "category": "context",+ "minIntensity": "lite",+ "description": "Convert verbose questions into direct requests."+ }+ ]+}+```++### Caveman Fields++| Field | Required | Description |+| ------------------------ | -------- | ---------------------------------------------------------------- |+| `language` | yes | BCP-47-like language key such as `en`, `pt-BR`, `es` |+| `category` | yes | Pack category filename/category, for example `filler` or `dedup` |+| `rules` | yes | Array of regex replacement rules |+| `rules[].name` | yes | Stable rule name |+| `rules[].pattern` | yes | JavaScript regex source |+| `rules[].flags` | no | JavaScript regex flags; default `gi` |+| `rules[].replacement` | no | Replacement string or fallback when `replacementMap` misses |+| `rules[].replacementMap` | no | Match-specific replacements keyed by normalized matched text |+| `rules[].context` | no | `all`, `user`, `assistant`, or `system`; default `all` |+| `rules[].category` | no | `filler`, `context`, `structural`, `dedup`, `terse`, or `ultra` |+| `rules[].minIntensity` | no | `lite`, `full`, or `ultra`; default `lite` |+| `rules[].description` | no | Human-readable rule summary |++Use `flags` when case-sensitive matching matters, for example article removal before lowercase prose+without stripping `the OpenAI API`. Use `replacementMap` when one regex has multiple alternatives+that need different outputs; this keeps JSON rule packs data-only while preserving the behavior of+the richer built-in TypeScript replacement functions.++## RTK Filter Packs++RTK filters live under:++```txt+open-sse/services/compression/engines/rtk/filters/<filter>.json+```++Each filter describes how to recognize and compress a command-output family.++```json+{+ "id": "test-vitest",+ "label": "Vitest output",+ "category": "test",+ "priority": 92,+ "match": {+ "outputTypes": ["test-vitest"],+ "commands": ["vitest", "npm test", "npm run test"],+ "patterns": ["\\bFAIL\\b", "\\bPASS\\b", "\\bTest Files\\b"]+ },+ "rules": {+ "stripAnsi": true,+ "replace": [{ "pattern": "\\s+\\[[0-9]+ms\\]", "replacement": "" }],+ "matchOutput": [+ { "pattern": "All tests passed", "message": "vitest: ok", "unless": "FAIL|Error:" }+ ],+ "includePatterns": ["FAIL", "Error:", "Test Files", "Tests"],+ "dropPatterns": ["^\\s*$", "Duration\\s+\\d+"],+ "collapsePatterns": ["^\\s+at "],+ "deduplicate": true,+ "truncateLineAt": 240,+ "maxLines": 160,+ "headLines": 24,+ "tailLines": 40,+ "onEmpty": "vitest: ok",+ "filterStderr": false+ },+ "preserve": {+ "errorPatterns": ["FAIL", "Error:", "AssertionError"],+ "summaryPatterns": ["Test Files", "Tests", "Snapshots"]+ },+ "tests": [+ {+ "name": "keeps failing tests",+ "command": "vitest",+ "input": "FAIL test/a.test.ts\\nError: boom\\nTest Files 1 failed",+ "expected": "FAIL test/a.test.ts\\nError: boom\\nTest Files 1 failed"+ }+ ]+}+```++### RTK Fields++| Field | Required | Description |+| -------------------------- | -------- | ------------------------------------------------------------------------------ |+| `id` | yes | Stable filter id |+| `label` | yes | Dashboard-readable name |+| `category` | yes | Filter family: git, test, build, shell, docker, package, infra, cloud, generic |+| `priority` | no | Higher priority wins when multiple filters match |+| `match.outputTypes` | no | Detector output ids that select this filter |+| `match.commands` | no | Command tokens that select this filter |+| `match.patterns` | no | Regex patterns that select this filter from output text |+| `rules.stripAnsi` | no | Remove ANSI escape sequences before regex stages |+| `rules.replace` | no | Ordered regex substitutions applied line by line |+| `rules.matchOutput` | no | Short-circuit output rules with optional `unless` guard |+| `rules.includePatterns` | no | Lines to prefer preserving |+| `rules.dropPatterns` | no | Lines to remove as noise |+| `rules.collapsePatterns` | no | Repeated matching lines that can be collapsed |+| `rules.deduplicate` | no | Collapse duplicate normalized lines |+| `rules.truncateLineAt` | no | Unicode-safe per-line character limit |+| `rules.maxLines` | no | Maximum retained lines before tail preservation |+| `rules.headLines` | no | Head lines retained during truncation |+| `rules.tailLines` | no | Tail lines retained for recent context |+| `rules.onEmpty` | no | Fallback message when filtering removes all content |+| `rules.filterStderr` | no | Normalize common stderr prefixes before later filtering stages |+| `preserve.errorPatterns` | no | Error lines that should survive truncation |+| `preserve.summaryPatterns` | no | Summary lines that should survive truncation |+| `tests[]` | no | Inline verification samples used by the RTK verify gate |++RTK applies declarative stages in this order: `stripAnsi`, `filterStderr`, `replace`,+`matchOutput`, `dropPatterns`/`includePatterns`, `truncateLineAt`, `headLines`/`tailLines`,+`maxLines`, and `onEmpty`.++Custom filters can be loaded from:++1. Project `.rtk/filters.json` files only after a matching `.rtk/trust.json` hash is present or+ `trustProjectFilters` is enabled.+2. Global `DATA_DIR/rtk/filters.json`.+3. Built-in filters.++Project/global custom files may contain one filter object or an array of filter objects. Invalid+custom filters are skipped with diagnostics; invalid built-in filters fail validation.++Project trust file:++```json+{+ "filtersSha256": "0123456789abcdef..."+}+```++The environment override `OMNIROUTE_RTK_TRUST_PROJECT_FILTERS=1` trusts project filters without a+hash and should be limited to controlled local development.++## Safety Rules++- Keep rules idempotent: running the same filter twice should not corrupt output.+- Preserve exact error text, file paths, line numbers, and command summaries where possible.+- Avoid rules that modify code blocks, JSON payloads, URLs, or secrets.+- Add unit coverage for new command families in detector/filter tests.+- Add `tests[]` samples to every built-in filter and to shared custom filters.++## Validation++Rule packs are validated before use. Built-in Caveman packs and built-in RTK filters fail fast+during validation so broken release assets are caught before shipment. Custom RTK filters are+skipped with diagnostics when parsing or trust validation fails.++Focused validation:++```bash+node --import tsx/esm --test tests/unit/compression/rule-loader.test.ts tests/unit/compression/language-packs.test.ts+node --import tsx/esm --test tests/unit/compression/rtk-verify.test.ts tests/unit/compression/rtk-dsl-pipeline.test.ts+```diff --git a/docs/ENVIRONMENT.md b/docs/ENVIRONMENT.mdindex 02e7c2843b..066d800705 100644--- a/docs/ENVIRONMENT.md+++ b/docs/ENVIRONMENT.md@@ -497,6 +497,12 @@ The logging system writes to both stdout and rotated log files. All configuratio| `CONTEXT_LENGTH_DEFAULT` | `128000` | Global fallback max context length for models without explicit config. || `USAGE_TOKEN_BUFFER` | `100` | Extra token headroom reserved when tracking usage quotas. |+### Compression++| Variable | Default | Description |+| ------------------------------------- | ------- | ------------------------------------------------------------------------------------------------------------- |+| `OMNIROUTE_RTK_TRUST_PROJECT_FILTERS` | unset | Trust project `.rtk/filters.json` without a `.rtk/trust.json` hash. Use only in controlled local development. |+### Low-RAM Docker Example```bashdiff --git a/docs/FEATURES.md b/docs/FEATURES.mdindex d68c6a6db9..4c8e9e455f 100644--- a/docs/FEATURES.md+++ b/docs/FEATURES.md@@ -1,6 +1,6 @@# OmniRoute — Dashboard Features Gallery-🌐 **Languages:** 🇺🇸 [English](FEATURES.md) | 🇧🇷 [Português (Brasil)](i18n/pt-BR/FEATURES.md) | 🇪🇸 [Español](i18n/es/FEATURES.md) | 🇫🇷 [Français](i18n/fr/FEATURES.md) | 🇮🇹 [Italiano](i18n/it/FEATURES.md) | 🇷🇺 [Русский](i18n/ru/FEATURES.md) | 🇨🇳 [中文 (简体)](i18n/zh-CN/FEATURES.md) | 🇩🇪 [Deutsch](i18n/de/FEATURES.md) | 🇮🇳 [हिन्दी](i18n/in/FEATURES.md) | 🇹🇭 [ไทย](i18n/th/FEATURES.md) | 🇺🇦 [Українська](i18n/uk-UA/FEATURES.md) | 🇸🇦 [العربية](i18n/ar/FEATURES.md) | 🇯🇵 [日本語](i18n/ja/FEATURES.md) | 🇻🇳 [Tiếng Việt](i18n/vi/FEATURES.md) | 🇧🇬 [Български](i18n/bg/FEATURES.md) | 🇩🇰 [Dansk](i18n/da/FEATURES.md) | 🇫🇮 [Suomi](i18n/fi/FEATURES.md) | 🇮🇱 [עברית](i18n/he/FEATURES.md) | 🇭🇺 [Magyar](i18n/hu/FEATURES.md) | 🇮🇩 [Bahasa Indonesia](i18n/id/FEATURES.md) | 🇰🇷 [한국어](i18n/ko/FEATURES.md) | 🇲🇾 [Bahasa Melayu](i18n/ms/FEATURES.md) | 🇳🇱 [Nederlands](i18n/nl/FEATURES.md) | 🇳🇴 [Norsk](i18n/no/FEATURES.md) | 🇵🇹 [Português (Portugal)](i18n/pt/FEATURES.md) | 🇷🇴 [Română](i18n/ro/FEATURES.md) | 🇵🇱 [Polski](i18n/pl/FEATURES.md) | 🇸🇰 [Slovenčina](i18n/sk/FEATURES.md) | 🇸🇪 [Svenska](i18n/sv/FEATURES.md) | 🇵🇭 [Filipino](i18n/phi/FEATURES.md) | 🇨🇿 [Čeština](i18n/cs/FEATURES.md)+🌐 **Main README translations:** 🇺🇸 [English](../README.md) | 🇧🇷 [Português (Brasil)](i18n/pt-BR/README.md) | 🇪🇸 [Español](i18n/es/README.md) | 🇫🇷 [Français](i18n/fr/README.md) | 🇮🇹 [Italiano](i18n/it/README.md) | 🇷🇺 [Русский](i18n/ru/README.md) | 🇨🇳 [中文 (简体)](i18n/zh-CN/README.md) | 🇩🇪 [Deutsch](i18n/de/README.md) | 🇮🇳 [हिन्दी](i18n/in/README.md) | 🇹🇭 [ไทย](i18n/th/README.md) | 🇺🇦 [Українська](i18n/uk-UA/README.md) | 🇸🇦 [العربية](i18n/ar/README.md) | 🇯🇵 [日本語](i18n/ja/README.md) | 🇻🇳 [Tiếng Việt](i18n/vi/README.md) | 🇧🇬 [Български](i18n/bg/README.md) | 🇩🇰 [Dansk](i18n/da/README.md) | 🇫🇮 [Suomi](i18n/fi/README.md) | 🇮🇱 [עברית](i18n/he/README.md) | 🇭🇺 [Magyar](i18n/hu/README.md) | 🇮🇩 [Bahasa Indonesia](i18n/id/README.md) | 🇰🇷 [한국어](i18n/ko/README.md) | 🇲🇾 [Bahasa Melayu](i18n/ms/README.md) | 🇳🇱 [Nederlands](i18n/nl/README.md) | 🇳🇴 [Norsk](i18n/no/README.md) | 🇵🇹 [Português (Portugal)](i18n/pt/README.md) | 🇷🇴 [Română](i18n/ro/README.md) | 🇵🇱 [Polski](i18n/pl/README.md) | 🇸🇰 [Slovenčina](i18n/sk/README.md) | 🇸🇪 [Svenska](i18n/sv/README.md) | 🇵🇭 [Filipino](i18n/phi/README.md) | 🇨🇿 [Čeština](i18n/cs/README.md)Visual guide to every section of the OmniRoute dashboard.@@ -109,7 +109,21 @@ Configurable via combo-level or global settings:- **Max Messages For Summary** — How much recent history to condense- **Summary Model** — Optional override model for generating the handoff summary-Currently supports Codex account rotation. See [Context Relay documentation](features/context-relay.md).+Currently supports Codex account rotation. See [Context Relay documentation](ARCHITECTURE.md).++---++## 🗜️ Prompt Compression _(v3.7.9+)_++Context & Cache now exposes dedicated pages for Caveman, RTK, and Compression Combos:++- **Caveman** — language-aware rule packs, preview, output-mode controls, and analytics+- **RTK** — command-aware compression for shell, git, test, build, package, Docker, infra, JSON, and stack-trace output+- **Compression Combos** — named pipelines such as `rtk -> caveman` assigned to routing combos; the default stacked math reaches `~89%` average and `78-95%` eligible-context savings when both engines apply+- **Raw-output recovery** — optional redacted RTK raw-output pointers for debugging compressed failures++See [Compression Guide](COMPRESSION_GUIDE.md), [RTK Compression](RTK_COMPRESSION.md), and+[Compression Engines](COMPRESSION_ENGINES.md).---diff --git a/docs/MCP-SERVER.md b/docs/MCP-SERVER.mdindex 2f8e6bab3f..4312fb0f12 100644--- a/docs/MCP-SERVER.md+++ b/docs/MCP-SERVER.md@@ -1,6 +1,6 @@# OmniRoute MCP Server Documentation-> Model Context Protocol server with 16 intelligent tools+> Model Context Protocol server with 37 tools across routing, cache, compression, memory, skills, and proxy operations## Installation@@ -19,7 +19,8 @@ omniroute --dev # MCP auto-starts on /mcp endpoint## IDE Configuration-See [IDE Configs](integrations/ide-configs.md) for Antigravity, Cursor, Copilot, and Claude Desktop setup.+See [MCP Client Configuration](SETUP_GUIDE.md#mcp-client-configuration) for Claude Desktop,+Cursor, Cline, and compatible MCP client setup.---@@ -49,20 +50,55 @@ See [IDE Configs](integrations/ide-configs.md) for Antigravity, Cursor, Copilot,| `omniroute_explain_route` | Explain a past routing decision || `omniroute_get_session_snapshot` | Full session state: costs, tokens, errors |+## Cache Tools (2)++| Tool | Description |+| :---------------------- | :-------------------------------------------------- |+| `omniroute_cache_stats` | Semantic cache, prompt-cache, and idempotency stats |+| `omniroute_cache_flush` | Flush cache globally or by signature/model |++## Compression Tools (5)++| Tool | Description |+| :---------------------------------- | :------------------------------------------------------------- |+| `omniroute_compression_status` | Compression settings, analytics summary, and cache-aware stats |+| `omniroute_compression_configure` | Configure compression mode, threshold, and runtime options |+| `omniroute_set_compression_engine` | Set Caveman, RTK, or stacked compression mode and pipeline |+| `omniroute_list_compression_combos` | List named compression combos and routing assignments |+| `omniroute_compression_combo_stats` | Analytics grouped by compression combo and engine |++`omniroute_compression_status` reports MCP description compression separately under+`analytics.mcpDescriptionCompression`. Those values are metadata-size estimates for MCP listable+descriptions (`tools`, `prompts`, `resources`, and `resourceTemplates`); they are not provider usage+receipts and are marked with `source: "mcp_metadata_estimate"`.++See [Compression Engines](COMPRESSION_ENGINES.md) and [RTK Compression](RTK_COMPRESSION.md) for+the runtime compression model behind these tools.++## Other Tool Groups++The remaining MCP surface includes 1proxy tools, memory tools, and skill tools. The live source of+truth is `open-sse/mcp-server/tools/` and `open-sse/mcp-server/schemas/tools.ts`.+## AuthenticationMCP tools are authenticated via API key scopes. Each tool requires specific scopes:-| Scope | Tools |-| :------------- | :----------------------------------------------- |-| `read:health` | get_health, get_provider_metrics |-| `read:combos` | list_combos, get_combo_metrics |-| `write:combos` | switch_combo |-| `read:quota` | check_quota |-| `write:route` | route_request, simulate_route, test_combo |-| `read:usage` | cost_report, get_session_snapshot, explain_route |-| `write:config` | set_budget_guard, set_resilience_profile |-| `read:models` | list_models_catalog, best_combo_for_task |+| Scope | Tools |+| :-------------------- | :------------------------------------------------------------------- |+| `read:health` | get_health, get_provider_metrics |+| `read:combos` | list_combos, get_combo_metrics |+| `write:combos` | switch_combo |+| `read:quota` | check_quota |+| `write:route` | route_request, simulate_route, test_combo |+| `read:usage` | cost_report, get_session_snapshot, explain_route |+| `write:config` | set_budget_guard, set_resilience_profile |+| `read:models` | list_models_catalog, best_combo_for_task |+| `read:cache` | cache_stats |+| `write:cache` | cache_flush |+| `read:compression` | compression_status, list_compression_combos, compression_combo_stats |+| `write:compression` | compression_configure, set_compression_engine |+| `execute:completions` | route_request, test_combo |## Audit Logging@@ -74,10 +110,10 @@ Every tool call is logged to `mcp_tool_audit` with:## Files-| File | Purpose |-| :------------------------------------------- | :------------------------------------------ |-| `open-sse/mcp-server/server.ts` | MCP server creation + 16 tool registrations |-| `open-sse/mcp-server/transport.ts` | Stdio + HTTP transport |-| `open-sse/mcp-server/auth.ts` | API key + scope validation |-| `open-sse/mcp-server/audit.ts` | Tool call audit logging |-| `open-sse/mcp-server/tools/advancedTools.ts` | 8 advanced tool handlers |+| File | Purpose |+| :------------------------------------------- | :------------------------------------------------ |+| `open-sse/mcp-server/server.ts` | MCP server creation and scoped tool registrations |+| `open-sse/mcp-server/transport.ts` | Stdio + HTTP transport |+| `open-sse/mcp-server/auth.ts` | API key + scope validation |+| `open-sse/mcp-server/audit.ts` | Tool call audit logging |+| `open-sse/mcp-server/tools/advancedTools.ts` | 8 advanced tool handlers |diff --git a/docs/RTK_COMPRESSION.md b/docs/RTK_COMPRESSION.mdnew file mode 100644index 0000000000..f675c93d25--- /dev/null+++ b/docs/RTK_COMPRESSION.md@@ -0,0 +1,234 @@+# RTK Compression++RTK compression is OmniRoute's command-aware compression engine for terminal and tool output. It is+designed for coding-agent sessions where most context growth comes from test logs, build output,+package manager noise, shell transcripts, Docker output, git output, and stack traces.++RTK can run directly with `defaultMode: "rtk"` or as the first step in a stacked pipeline, usually:++```txt+rtk -> caveman+```++That order compresses noisy machine output first, then lets Caveman condense remaining prose.++Upstream RTK reports `60-90%` command-output savings. Its README sample session goes from+`~118,000` standard tokens to `~23,900` RTK tokens, which is `79.7%` saved (`~80%`). OmniRoute uses+that upstream average for the stacked savings calculation with Caveman input compression:++```txt+RTK average: 80% saved+Caveman input: 46% saved+Stacked: 1 - (1 - 0.80) * (1 - 0.46) = 89.2% saved+Range: 1 - (1 - 0.60..0.90) * (1 - 0.46) = 78.4-94.6%+```++## What It Compresses++The built-in catalog currently ships 49 filters across these categories:++| Category | Examples |+| --------- | ------------------------------------------------------------- |+| `git` | `git status`, `git branch`, `git diff`, `git log` |+| `test` | Vitest, Jest, Pytest, Playwright, Go tests, Cargo tests |+| `build` | TypeScript, ESLint, Biome, Prettier, Vite, Webpack, Turbo, Nx |+| `package` | `npm install`, `npm audit`, `pip`, `uv sync`, Poetry, Bundler |+| `shell` | `ls`, `find`, `grep`, generic shell logs |+| `docker` | `docker ps`, Docker logs |+| `infra` | Terraform, OpenTofu, `systemctl status` |+| `generic` | JSON output, stack traces, generic output fallback |++The detector in `open-sse/services/compression/engines/rtk/commandDetector.ts` classifies output+before filter selection. Filters can also match by command pattern or output regex when a command+class is not enough.++## Filter Resolution++RTK loads filters in this order:++1. Project filters from `.rtk/filters.json`, only when trusted.+2. Global filters from `DATA_DIR/rtk/filters.json`.+3. Built-in filters from `open-sse/services/compression/engines/rtk/filters/`.++Project filters are intentionally trust-gated because regex filters can change how tool output is+shown to agents. A project filter file is accepted when one of these is true:++- `rtkConfig.trustProjectFilters` is `true`.+- `OMNIROUTE_RTK_TRUST_PROJECT_FILTERS=1` is set.+- `.rtk/trust.json` contains the SHA-256 hash of `.rtk/filters.json`.++Trust file example:++```json+{+ "filtersSha256": "0123456789abcdef..."+}+```++Custom filters can be one filter object or an array of filter objects. Invalid custom filters are+skipped and reported by `/api/context/rtk/filters` diagnostics. Invalid built-in filters fail fast.++## Filter DSL++Filters use the JSON schema described in [Compression Rules Format](COMPRESSION_RULES_FORMAT.md).+The runtime applies these stages in order:++```txt+stripAnsi -> filterStderr -> replace -> matchOutput -> drop/include lines+ -> truncateLineAt -> head/tail/maxLines -> onEmpty+```++Important fields:++| Field | Purpose |+| ---------------------------- | -------------------------------------------------------------- |+| `rules.stripAnsi` | Remove terminal color/control sequences before matching |+| `rules.filterStderr` | Normalize common stderr prefixes before matching/filtering |+| `rules.replace` | Apply ordered regex replacements |+| `rules.matchOutput` | Return a compact summary when output matches a known condition |+| `rules.matchOutput[].unless` | Skip the shortcut when an error/failure pattern is present |+| `rules.dropPatterns` | Remove noisy lines |+| `rules.includePatterns` | Prefer actionable lines |+| `rules.collapsePatterns` | Collapse repeated matching lines |+| `rules.truncateLineAt` | Unicode-safe per-line truncation |+| `rules.onEmpty` | Fallback message if all lines are filtered out |+| `tests[]` | Inline samples used by the verify gate |++Built-in filters are expected to include inline `tests[]` samples. Custom filters should include+them too, especially when they are shared across projects.++## Configuration++Global settings are available through `/api/settings/compression`. RTK-specific settings are also+available through `/api/context/rtk/config`.++```json+{+ "defaultMode": "stacked",+ "autoTriggerMode": "stacked",+ "autoTriggerTokens": 32000,+ "stackedPipeline": [+ { "engine": "rtk", "intensity": "standard" },+ { "engine": "caveman", "intensity": "full" }+ ],+ "rtkConfig": {+ "enabled": true,+ "intensity": "standard",+ "applyToToolResults": true,+ "applyToCodeBlocks": false,+ "applyToAssistantMessages": false,+ "enabledFilters": [],+ "disabledFilters": [],+ "maxLinesPerResult": 120,+ "maxCharsPerResult": 12000,+ "deduplicateThreshold": 3,+ "customFiltersEnabled": true,+ "trustProjectFilters": false,+ "rawOutputRetention": "never",+ "rawOutputMaxBytes": 1048576+ }+}+```++`enabledFilters` and `disabledFilters` use filter ids, for example `test-vitest` or `git-diff`.++## API++| Route | Method | Purpose |+| ---------------------------------- | ------ | -------------------------------------------- |+| `/api/context/rtk/config` | GET | Read RTK config |+| `/api/context/rtk/config` | PUT | Update RTK config |+| `/api/context/rtk/filters` | GET | List filter catalog and load diagnostics |+| `/api/context/rtk/test` | POST | Preview RTK compression for one text payload |+| `/api/context/rtk/raw-output/[id]` | GET | Read retained redacted raw output |+| `/api/compression/preview` | POST | Preview any compression mode |++RTK test payload:++```json+{+ "command": "npm test",+ "text": "FAIL tests/example.test.ts\nAssertionError: expected true\nTest Files 1 failed",+ "config": {+ "intensity": "standard"+ }+}+```++Compression preview payload:++```json+{+ "mode": "stacked",+ "messages": [+ {+ "role": "tool",+ "content": "FAIL tests/example.test.ts\nAssertionError: expected true\nTest Files 1 failed"+ }+ ],+ "config": {+ "rtkConfig": {+ "rawOutputRetention": "failures"+ }+ }+}+```++Management routes require dashboard management auth or the matching API-key policy.++## Raw Output Recovery++RTK normally returns only compressed text. For debugging, `rawOutputRetention` can retain redacted+raw output:++| Value | Behavior |+| ---------- | ------------------------------------------------------- |+| `never` | Do not retain raw output |+| `failures` | Retain only likely failure output |+| `always` | Retain every compressed RTK raw output, after redaction |++Retained files are written under:++```txt+DATA_DIR/rtk/raw-output/+```++Secrets are redacted before persistence, including common bearer tokens, API keys, Slack tokens,+AWS access keys, and assignment-style `token=...`, `secret=...`, `password=...` values. Analytics+stores only the pointer id, size, and hash metadata.++## Verify Gate++The focused verify gate runs built-in inline filter tests without shelling out to external commands:++```bash+node --import tsx/esm --test tests/unit/compression/rtk-verify.test.ts+```++The broader RTK gate is:++```bash+node --import tsx/esm --test \+ tests/unit/compression/rtk-*.test.ts \+ tests/unit/compression/pipeline-integration.test.ts \+ tests/unit/compression/context-compression-api.test.ts+```++Run the broad compression gate before release:++```bash+node --import tsx/esm --test \+ tests/unit/compression/*.test.ts \+ tests/golden-set/*.test.ts \+ tests/integration/compression-pipeline.test.ts \+ tests/unit/api/compression/compression-api.test.ts+```++## Extending RTK++1. Add or update a filter JSON file.+2. Include at least one `tests[]` sample that proves the important behavior.+3. Add a fixture under `tests/unit/compression/fixtures/rtk/` for new command families.+4. Add command detection coverage when introducing a new output class.+5. Run the verify and broad RTK gates.+6. If the filter is project-local, commit `.rtk/filters.json` and refresh `.rtk/trust.json` only after review.diff --git a/docs/SETUP_GUIDE.md b/docs/SETUP_GUIDE.mdindex 9e78e203e9..26c332a5ab 100644--- a/docs/SETUP_GUIDE.md+++ b/docs/SETUP_GUIDE.md@@ -138,7 +138,7 @@ Add to your MCP settings:}```-**Full MCP documentation:** [MCP Server README](../open-sse/mcp-server/README.md) — 29 tools, IDE configs, Python/TS/Go clients.+**Full MCP documentation:** [MCP Server README](../open-sse/mcp-server/README.md) — 37 tools, IDE configs, Python/TS/Go clients.### A2A Setup (Agent-to-Agent Protocol)diff --git a/docs/openapi.yaml b/docs/openapi.yamlindex 76b54c78e7..bea18f734e 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -1,7 +1,7 @@openapi: 3.1.0info:title: OmniRoute API- version: 3.7.8+ version: 3.7.9description: |OmniRoute is a local-first AI API proxy router. It provides an OpenAI-compatibleendpoint that routes requests to multiple AI providers with load balancing,@@ -51,6 +51,8 @@ tags:description: Routing combo management- name: Settingsdescription: Application settings+ - name: Compression+ description: Prompt compression, RTK filters, Caveman rules, and compression combos- name: Usagedescription: Usage analytics and logs- name: Translator@@ -734,6 +736,202 @@ paths:"200":description: Updated settings+ /api/settings/compression:+ get:+ tags: [Compression]+ summary: Get global compression settings+ security:+ - ManagementSessionAuth: []+ responses:+ "200":+ description: Current compression settings+ put:+ tags: [Compression]+ summary: Update global compression settings+ security:+ - ManagementSessionAuth: []+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ properties:+ enabled:+ type: boolean+ defaultMode:+ type: string+ enum: [off, lite, standard, aggressive, ultra, rtk, stacked]+ autoTriggerMode:+ type: string+ enum: [off, lite, standard, aggressive, ultra, rtk, stacked]+ autoTriggerTokens:+ type: integer+ minimum: 0+ rtkConfig:+ type: object+ additionalProperties: true+ stackedPipeline:+ type: array+ items:+ type: object+ responses:+ "200":+ description: Updated compression settings++ /api/compression/preview:+ post:+ tags: [Compression]+ summary: Preview compression for a message payload+ security:+ - BearerAuth: []+ - ManagementSessionAuth: []+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ required: [messages, mode]+ properties:+ mode:+ type: string+ enum: [off, lite, standard, aggressive, ultra, rtk, stacked]+ messages:+ type: array+ items:+ type: object+ required: [role, content]+ properties:+ role:+ type: string+ content:+ oneOf:+ - type: string+ - type: array+ items: {}+ config:+ type: object+ additionalProperties: true+ responses:+ "200":+ description: Compression preview with diff, validation, and stats++ /api/compression/language-packs:+ get:+ tags: [Compression]+ summary: List Caveman compression language packs+ security:+ - BearerAuth: []+ - ManagementSessionAuth: []+ responses:+ "200":+ description: Available languages and rule-pack metadata++ /api/compression/rules:+ get:+ tags: [Compression]+ summary: List Caveman compression rule metadata+ security:+ - BearerAuth: []+ - ManagementSessionAuth: []+ responses:+ "200":+ description: Caveman rule metadata++ /api/context/rtk/config:+ get:+ tags: [Compression]+ summary: Get RTK compression settings+ security:+ - ManagementSessionAuth: []+ responses:+ "200":+ description: Current RTK config+ put:+ tags: [Compression]+ summary: Update RTK compression settings+ security:+ - ManagementSessionAuth: []+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ properties:+ enabled:+ type: boolean+ intensity:+ type: string+ enum: [minimal, standard, aggressive]+ customFiltersEnabled:+ type: boolean+ trustProjectFilters:+ type: boolean+ rawOutputRetention:+ type: string+ enum: [never, failures, always]+ rawOutputMaxBytes:+ type: integer+ responses:+ "200":+ description: Updated RTK config++ /api/context/rtk/filters:+ get:+ tags: [Compression]+ summary: List RTK filters and load diagnostics+ security:+ - ManagementSessionAuth: []+ responses:+ "200":+ description: RTK filter catalog and diagnostics++ /api/context/rtk/test:+ post:+ tags: [Compression]+ summary: Run RTK compression preview for text+ security:+ - ManagementSessionAuth: []+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ required: [text]+ properties:+ text:+ type: string+ command:+ type: string+ config:+ type: object+ additionalProperties: true+ responses:+ "200":+ description: Detection and RTK compression result++ /api/context/rtk/raw-output/{id}:+ get:+ tags: [Compression]+ summary: Read retained redacted RTK raw output+ security:+ - ManagementSessionAuth: []+ parameters:+ - in: path+ name: id+ required: true+ schema:+ type: string+ pattern: "^[a-f0-9]{24}$"+ responses:+ "200":+ description: Raw output text+ "404":+ description: Raw output not found+/api/settings/payload-rules:get:tags: [Settings]diff --git a/electron/package-lock.json b/electron/package-lock.jsonindex fbcbba7997..abe3c9d549 100644--- a/electron/package-lock.json+++ b/electron/package-lock.json@@ -1,12 +1,12 @@{"name": "omniroute-desktop",- "version": "3.7.8",+ "version": "3.7.9","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "omniroute-desktop",- "version": "3.7.8",+ "version": "3.7.9","license": "MIT","dependencies": {"better-sqlite3": "^12.8.0",diff --git a/electron/package.json b/electron/package.jsonindex 8a182a53c8..f984a9d83f 100644--- a/electron/package.json+++ b/electron/package.json@@ -1,6 +1,6 @@{"name": "omniroute-desktop",- "version": "3.7.8",+ "version": "3.7.9","description": "OmniRoute Desktop Application","main": "main.js","author": {diff --git a/llm.txt b/llm.txtindex 8b50978e3d..7702e3f58b 100644--- a/llm.txt+++ b/llm.txt@@ -8,7 +8,7 @@ OmniRoute solves the problem of managing multiple AI provider subscriptions, quo**Key value:** One endpoint (`http://localhost:20128/v1`), unlimited models, zero downtime, minimal cost.-**Current version:** 3.7.7+**Current version:** 3.7.9## Tech Stack@@ -279,7 +279,7 @@ OmniRoute solves the problem of managing multiple AI provider subscriptions, quo└── .env.example # Environment variable template```-## Key Features (v3.7.7)+## Key Features (v3.7.9)### Core Proxy- **160+ AI providers** with automatic format translationdiff --git a/next.config.mjs b/next.config.mjsindex be2b7dd40c..eab10cb8e8 100644--- a/next.config.mjs+++ b/next.config.mjs@@ -8,7 +8,7 @@ const projectRoot = dirname(fileURLToPath(import.meta.url));const scriptSrc =process.env.NODE_ENV === "development"? "script-src 'self' 'unsafe-inline' 'unsafe-eval' blob:"- : "script-src 'self' 'unsafe-inline' blob:";+ : "script-src 'self' 'unsafe-inline' 'unsafe-eval' blob:";const contentSecurityPolicy = ["default-src 'self'","base-uri 'self'",@@ -79,9 +79,13 @@ const nextConfig = {},outputFileTracingRoot: projectRoot,outputFileTracingIncludes: {- // Migration SQL files are read via fs.readFileSync at runtime and are NOT- // auto-traced by webpack/turbopack — include them explicitly.- "/*": ["./src/lib/db/migrations/**/*"],+ // Migration SQL and compression rule/filter JSON files are read via fs at+ // runtime and are NOT always auto-traced by webpack/turbopack.+ "/*": [+ "./src/lib/db/migrations/**/*",+ "./open-sse/services/compression/engines/rtk/filters/**/*.json",+ "./open-sse/services/compression/rules/**/*.json",+ ],},outputFileTracingExcludes: {// Planning/task docs are not runtime assets and can break standalone copies@@ -136,97 +140,6 @@ const nextConfig = {images: {unoptimized: true,},- webpack: (config, { isServer, webpack }) => {- if (isServer) {- // Webpack IgnorePlugin: skip thread-stream test files that contain- // intentionally broken syntax/imports (they cause Turbopack build errors)- config.plugins.push(- new webpack.IgnorePlugin({- resourceRegExp: /\/test\//,- contextRegExp: /thread-stream/,- })- );-- // ── Turbopack / Next.js 16 module-hash patch (#394, #396, #398) ────────- //- // Next.js 16 (with or without Turbopack) compiles the instrumentation hook- // into a separate chunk and emits hashed require() calls such as:- // require('better-sqlite3-90e2652d1716b047')- // require('zod-dcb22c6336e0bc69')- // require('pino-28069d5257187539')- //- // These hashed names don't exist in node_modules and cause a 500 at- // startup on all npm global installs (issues #394, #396, #398).- //- // We use two strategies:- // 1. Exact-name externals for all known server-side packages.- // 2. Hash-strip catch-all: any require('<name>-<16hexchars>[/subpath]')- // strips the hash suffix and falls through to the real package name.- //- const HASH_PATTERN = /^(.+)-[0-9a-f]{16}(\/.*)?$/;-- const KNOWN_EXTERNALS = new Set([- "better-sqlite3",- "keytar",- "@ngrok/ngrok",- "wreq-js",- "zod",- "pino",- "pino-pretty",- "pino-abstract-transport",- "child_process",- "fs",- "path",- "os",- "crypto",- "net",- "tls",- "http",- "https",- "stream",- "buffer",- "util",- "process",- ]);-- const prev = config.externals ?? [];- const prevArr = Array.isArray(prev) ? prev : [prev];- config.externals = [- ...prevArr,- ({ request }, callback) => {- // Case 1: Exact known package — treat as external- if (KNOWN_EXTERNALS.has(request)) {- return callback(null, `commonjs ${request}`);- }- // Case 2: Hash-suffixed name — strip hash, preserve subpath- // e.g. "better-sqlite3-90e2652d1716b047" → "better-sqlite3"- // "zod-dcb22c6336e0bc69" → "zod"- // "zod-dcb22c6336e0bc69/v3" → "zod/v3"- // "zod-dcb22c6336e0bc69/v4-mini" → "zod/v4-mini"- const hashMatch = request?.match?.(HASH_PATTERN);- if (hashMatch) {- const resolved = hashMatch[2] ? `${hashMatch[1]}${hashMatch[2]}` : hashMatch[1];- return callback(null, `commonjs ${resolved}`);- }- callback();- },- ];- } else {- // Ignore native Node.js modules in browser bundle- config.resolve.fallback = {- ...config.resolve.fallback,- fs: false,- path: false,- child_process: false,- net: false,- tls: false,- crypto: false,- process: false,- os: false,- };- }- return config;- },async headers() {return [diff --git a/open-sse/config/embeddingRegistry.ts b/open-sse/config/embeddingRegistry.tsindex 795c43c811..c2526af4a3 100644--- a/open-sse/config/embeddingRegistry.ts+++ b/open-sse/config/embeddingRegistry.ts@@ -173,13 +173,59 @@ export const EMBEDDING_PROVIDERS: Record<string, EmbeddingProvider> = {{ id: "text-embedding-3-large", name: "Text Embedding 3 Large (GitHub)", dimensions: 3072 },],},++ "jina-ai": {+ id: "jina-ai",+ baseUrl: "https://api.jina.ai/v1/embeddings",+ authType: "apikey",+ authHeader: "bearer",+ models: [+ {+ id: "jina-embeddings-v5-text-small",+ name: "Jina Embeddings v5 Text Small",+ dimensions: 1024,+ },+ { id: "jina-embeddings-v5-text-nano", name: "Jina Embeddings v5 Text Nano", dimensions: 768 },+ { id: "jina-code-embeddings-1.5b", name: "Jina Code Embeddings 1.5B", dimensions: 1536 },+ { id: "jina-code-embeddings-0.5b", name: "Jina Code Embeddings 0.5B", dimensions: 896 },+ { id: "jina-embeddings-v4", name: "Jina Embeddings v4", dimensions: 2048 },+ { id: "jina-clip-v2", name: "Jina CLIP v2", dimensions: 1024 },+ { id: "jina-colbert-v2", name: "Jina ColBERT v2", dimensions: 128 },+ ],+ },};+const EMBEDDING_PROVIDER_ALIASES: Record<string, string> = {+ jina: "jina-ai",+ voyage: "voyage-ai",+};++function resolveEmbeddingProviderId(providerId: string): string {+ return EMBEDDING_PROVIDER_ALIASES[providerId] || providerId;+}++function normalizeProviderScopedModelId(providerId: string, modelId: string): string {+ const resolvedProvider = resolveEmbeddingProviderId(providerId);+ const provider = EMBEDDING_PROVIDERS[resolvedProvider];+ if (provider?.models.some((model) => model.id === modelId)) return modelId;++ const providerScopedModelId = `${resolvedProvider}/${modelId}`;+ if (provider?.models.some((model) => model.id === providerScopedModelId)) {+ return providerScopedModelId;+ }++ return modelId.startsWith(`${providerId}/`) ? modelId.slice(providerId.length + 1) : modelId;+}++function toProviderScopedModelId(providerId: string, modelId: string): string {+ return modelId.startsWith(`${providerId}/`) ? modelId : `${providerId}/${modelId}`;+}+/*** Get embedding provider config by ID*/export function getEmbeddingProvider(providerId: string): EmbeddingProvider | null {- return EMBEDDING_PROVIDERS[providerId] || null;+ return EMBEDDING_PROVIDERS[resolveEmbeddingProviderId(providerId)] || null;}/**@@ -195,10 +241,23 @@ export function parseEmbeddingModel(// Check for "provider/model" formatconst slashIdx = modelStr.indexOf("/");if (slashIdx > 0) {+ const rawProvider = modelStr.slice(0, slashIdx);+ const resolvedProvider = resolveEmbeddingProviderId(rawProvider);++ if (EMBEDDING_PROVIDERS[resolvedProvider]) {+ return {+ provider: resolvedProvider,+ model: normalizeProviderScopedModelId(resolvedProvider, modelStr.slice(slashIdx + 1)),+ };+ }+// Phase 1: Try each hardcoded provider prefixfor (const [providerId] of Object.entries(EMBEDDING_PROVIDERS)) {if (modelStr.startsWith(providerId + "/")) {- return { provider: providerId, model: modelStr.slice(providerId.length + 1) };+ return {+ provider: providerId,+ model: normalizeProviderScopedModelId(providerId, modelStr.slice(providerId.length + 1)),+ };}}// Phase 2: Try dynamic provider_nodes prefix@@ -233,7 +292,7 @@ export function getAllEmbeddingModels() {for (const [providerId, config] of Object.entries(EMBEDDING_PROVIDERS)) {for (const model of config.models) {models.push({- id: `${providerId}/${model.id}`,+ id: toProviderScopedModelId(providerId, model.id),name: model.name,provider: providerId,dimensions: model.dimensions,diff --git a/open-sse/config/imageRegistry.ts b/open-sse/config/imageRegistry.tsindex a9fc20da0e..dc8ccfaf9b 100644--- a/open-sse/config/imageRegistry.ts+++ b/open-sse/config/imageRegistry.ts@@ -437,6 +437,20 @@ export const IMAGE_PROVIDERS: Record<string, ImageProviderConfig> = {models: [{ id: "topaz-enhance", name: "topaz-enhance", inputModalities: ["image"] }],supportedSizes: ["1024x1024"],},+ nanogpt: {+ id: "nanogpt",+ baseUrl: "https://nano-gpt.com/api/v1/images/generations",+ authType: "apikey",+ authHeader: "bearer",+ format: "openai",+ models: [+ { id: "qwen-image", name: "Qwen Image", inputModalities: ["text", "image"] },+ { id: "z-image-turbo", name: "Z Image Turbo" },+ { id: "chroma", name: "Chroma" },+ { id: "hidream", name: "Hidream I1 Full" },+ ],+ supportedSizes: ["1024x1024", "1024x1280", "1280x1024"],+ },};/**diff --git a/open-sse/config/providerRegistry.ts b/open-sse/config/providerRegistry.tsindex 8265f3376f..063d047396 100644--- a/open-sse/config/providerRegistry.ts+++ b/open-sse/config/providerRegistry.ts@@ -672,17 +672,39 @@ export const REGISTRY: Record<string, RegistryEntry> = {agentrouter: {id: "agentrouter",alias: "agentrouter",- format: "openai",+ format: "claude",executor: "default",- baseUrl: "https://agentrouter.org/v1/chat/completions",+ baseUrl: "https://agentrouter.org/v1/messages",authType: "apikey",- authHeader: "bearer",+ authHeader: "x-api-key",defaultContextLength: 128000,headers: {- "HTTP-Referer": "https://endpoint-proxy.local",- "X-Title": "OmniRoute",+ "Anthropic-Version": ANTHROPIC_VERSION_HEADER,+ "Anthropic-Beta": ANTHROPIC_BETA_CLAUDE_OAUTH,+ "Anthropic-Dangerous-Direct-Browser-Access": "true",+ "User-Agent": CLAUDE_CLI_USER_AGENT,+ "X-App": "cli",+ "X-Stainless-Helper-Method": "stream",+ "X-Stainless-Retry-Count": "0",+ "X-Stainless-Runtime-Version": CLAUDE_CLI_STAINLESS_RUNTIME_VERSION,+ "X-Stainless-Package-Version": CLAUDE_CLI_STAINLESS_PACKAGE_VERSION,+ "X-Stainless-Runtime": "node",+ "X-Stainless-Lang": "js",+ "X-Stainless-Arch": mapStainlessArch(),+ "X-Stainless-Os": mapStainlessOs(),+ "X-Stainless-Timeout": "600",},- models: [{ id: "auto", name: "Auto (Best Available)" }],+ models: [+ { id: "claude-haiku-4-5-20251001", name: "Claude 4.5 Haiku" },+ { id: "claude-opus-4-6", name: "Claude 4.6 Opus" },+ { id: "deepseek-r1-0528", name: "DeepSeek R1 0528" },+ { id: "deepseek-v3.1", name: "DeepSeek V3.1" },+ { id: "deepseek-v3.2", name: "DeepSeek V3.2" },+ { id: "glm-4.5", name: "GLM 4.5" },+ { id: "glm-4.6", name: "GLM 4.6" },+ { id: "glm-5.1", name: "GLM 5.1" },+ ],+ passthroughModels: true,},openrouter: {diff --git a/open-sse/config/rerankRegistry.ts b/open-sse/config/rerankRegistry.tsindex 80f9bb5466..b075bf4357 100644--- a/open-sse/config/rerankRegistry.ts+++ b/open-sse/config/rerankRegistry.ts@@ -69,20 +69,41 @@ export const RERANK_PROVIDERS = {models: [{ id: "jina-reranker-v3", name: "Jina Reranker v3" },{ id: "jina-reranker-m0", name: "Jina Reranker m0" },- {- id: "jina-reranker-v2-base-multilingual",- name: "Jina Reranker v2 Base Multilingual",- },- { id: "jina-colbert-v2", name: "Jina ColBERT v2" },],},};+const RERANK_PROVIDER_ALIASES = {+ jina: "jina-ai",+ voyage: "voyage-ai",+};++function resolveRerankProviderId(providerId) {+ return RERANK_PROVIDER_ALIASES[providerId] || providerId;+}++function normalizeProviderScopedModelId(providerId, modelId) {+ const resolvedProvider = resolveRerankProviderId(providerId);+ const provider = RERANK_PROVIDERS[resolvedProvider];+ if (provider?.models.some((model) => model.id === modelId)) return modelId;++ const providerScopedModelId = `${resolvedProvider}/${modelId}`;+ if (provider?.models.some((model) => model.id === providerScopedModelId)) {+ return providerScopedModelId;+ }++ return modelId.startsWith(`${providerId}/`) ? modelId.slice(providerId.length + 1) : modelId;+}++function toProviderScopedModelId(providerId, modelId) {+ return modelId.startsWith(`${providerId}/`) ? modelId : `${providerId}/${modelId}`;+}+/*** Get rerank provider config by ID*/export function getRerankProvider(providerId) {- return RERANK_PROVIDERS[providerId] || null;+ return RERANK_PROVIDERS[resolveRerankProviderId(providerId)] || null;}/**@@ -92,10 +113,25 @@ export function getRerankProvider(providerId) {export function parseRerankModel(modelStr) {if (!modelStr) return { provider: null, model: null };+ const slashIdx = modelStr.indexOf("/");+ if (slashIdx > 0) {+ const rawProvider = modelStr.slice(0, slashIdx);+ const resolvedProvider = resolveRerankProviderId(rawProvider);+ if (RERANK_PROVIDERS[resolvedProvider]) {+ return {+ provider: resolvedProvider,+ model: normalizeProviderScopedModelId(resolvedProvider, modelStr.slice(slashIdx + 1)),+ };+ }+ }+// Try each provider prefixfor (const [providerId, config] of Object.entries(RERANK_PROVIDERS)) {if (modelStr.startsWith(providerId + "/")) {- return { provider: providerId, model: modelStr.slice(providerId.length + 1) };+ return {+ provider: providerId,+ model: normalizeProviderScopedModelId(providerId, modelStr.slice(providerId.length + 1)),+ };}}@@ -117,7 +153,7 @@ export function getAllRerankModels() {for (const [providerId, config] of Object.entries(RERANK_PROVIDERS)) {for (const model of config.models) {models.push({- id: `${providerId}/${model.id}`,+ id: toProviderScopedModelId(providerId, model.id),name: model.name,provider: providerId,});diff --git a/open-sse/executors/base.ts b/open-sse/executors/base.tsindex 309e12aacd..00576b774c 100644--- a/open-sse/executors/base.ts+++ b/open-sse/executors/base.ts@@ -293,6 +293,9 @@ export class BaseExecutor {});}+ // Fix #1884: Cursor sends prompt_cache_retention which breaks strict upstream endpoints+ delete cloned.prompt_cache_retention;+// Also clean up top level optional fields that commonly cause issues when emptyconst optionalKeys = ["user", "stop", "seed", "response_format"];for (const key of optionalKeys) {diff --git a/open-sse/executors/codex.ts b/open-sse/executors/codex.tsindex e84be095b6..4f008623fc 100644--- a/open-sse/executors/codex.ts+++ b/open-sse/executors/codex.ts@@ -26,6 +26,7 @@ import {getRememberedResponseConversationItems,getRememberedResponseFunctionCalls,} from "../services/responsesToolCallState.ts";+import { sanitizeResponsesInputItems } from "../services/responsesInputSanitizer.ts";import { getThinkingBudgetConfig, ThinkingMode } from "../services/thinkingBudget.ts";import { CORS_HEADERS } from "../utils/cors.ts";import { createRequire } from "module";@@ -45,6 +46,11 @@ type WreqWebSocket = {onclose: (() => void) | null;};type WebsocketFn = (url: string, opts?: Record<string, unknown>) => Promise<WreqWebSocket>;+type ResponsesMessageInput = {+ role?: unknown;+ phase?: unknown;+ content?: unknown;+};let _websocketFn: WebsocketFn | null = null;let _wreqChecked = false;@@ -605,6 +611,40 @@ function normalizeCodexTools(body: Record<string, unknown>): void {return false;}+ // Codex Responses API requires function tools in flat Responses format:+ // { type: "function", name, description, parameters }+ // Some clients/translators send Chat Completions shape:+ // { type: "function", function: { name, description, parameters } }+ // which upstream rejects with "Missing required parameter: tools[0].name".+ // Flatten the nested `function` wrapper into top-level fields (#1914).+ const functionObject =+ tool.function && typeof tool.function === "object" && !Array.isArray(tool.function)+ ? (tool.function as Record<string, unknown>)+ : null;+ const description =+ typeof tool.description === "string"+ ? tool.description+ : typeof functionObject?.description === "string"+ ? functionObject.description+ : "";+ const parameters =+ tool.parameters && typeof tool.parameters === "object" && !Array.isArray(tool.parameters)+ ? tool.parameters+ : functionObject?.parameters &&+ typeof functionObject.parameters === "object" &&+ !Array.isArray(functionObject.parameters)+ ? functionObject.parameters+ : { type: "object", properties: {} };++ // Rewrite in-place to Responses format+ for (const key of Object.keys(tool)) {+ delete tool[key];+ }+ tool.type = "function";+ tool.name = name;+ if (description) tool.description = description;+ tool.parameters = parameters;+validToolNames.add(name);return true;});@@ -1185,19 +1225,49 @@ export class CodexExecutor extends BaseExecutor {// Issue #1832 & #1853: Map messages to input for clients like Cursor 5.5 that use responses/compact but send messages instead of input.// This MUST run before convertSystemToDeveloperRole and stripStoredItemReferences.if (!body.input && Array.isArray(body.messages)) {- body.input = body.messages.map((msg: any) => ({+ body.input = body.messages.map((msg: ResponsesMessageInput) => ({type: "message",role: typeof msg.role === "string" ? msg.role : "user",+ ...(typeof msg.phase === "string" ? { phase: msg.phase } : {}),content:typeof msg.content === "string"? [{ type: "input_text", text: msg.content }]: Array.isArray(msg.content)- ? msg.content.map((c: any) => {- if (c && c.type === "text") return { type: "input_text", text: c.text };- return c;+ ? msg.content.map((contentPart: unknown) => {+ if (+ contentPart &&+ typeof contentPart === "object" &&+ !Array.isArray(contentPart) &&+ (contentPart as Record<string, unknown>).type === "text"+ ) {+ return {+ type: "input_text",+ text: (contentPart as Record<string, unknown>).text,+ };+ }+ return contentPart;}): [],}));+ } else if (!body.input && typeof body.prompt === "string" && body.prompt.trim()) {+ // Issue #1872: Cursor occasionally passes the request as `prompt` instead of `messages`.+ body.input = [+ {+ type: "message",+ role: "user",+ content: [{ type: "input_text", text: body.prompt }],+ },+ ];+ } else if (!body.input && Array.isArray(body.prompt)) {+ body.input = body.prompt.map((p: any) => ({+ type: "message",+ role: "user",+ content: [{ type: "input_text", text: typeof p === "string" ? p : JSON.stringify(p) }],+ }));+ }++ if (Array.isArray(body.input)) {+ body.input = sanitizeResponsesInputItems(body.input, false);}// ── Cache-aware system prompt handling (both paths) ──@@ -1355,7 +1425,7 @@ export class CodexExecutor extends BaseExecutor {delete body.seed;// max_tokens and max_output_tokens already deleted above (before passthrough return)delete body.user; // Cursor sends this but Codex doesn't support it- delete body.prompt_cache_retention; // Cursor sends this but Codex doesn't support it+delete body.metadata; // Cursor sends this but Codex doesn't support itdelete body.stream_options; // Cursor sends this but Codex doesn't support itdelete body.safety_identifier; // Droid CLI sends this but Codex doesn't support itdiff --git a/open-sse/handlers/chatCore.ts b/open-sse/handlers/chatCore.tsindex dbf58ed0cf..10d2591149 100644--- a/open-sse/handlers/chatCore.ts+++ b/open-sse/handlers/chatCore.ts@@ -922,6 +922,28 @@ function buildExecutorClientHeaders(return Object.keys(normalized).length > 0 ? normalized : null;}+function isCopilotClient(+ headers: Headers | Record<string, unknown> | null | undefined,+ userAgent?: string | null+) {+ const isMatch = (value: unknown) =>+ typeof value === "string" && value.toLowerCase().includes("copilot");++ if (isMatch(userAgent)) return true;++ if (headers instanceof Headers) {+ for (const [key, value] of headers) {+ if (isMatch(key) || isMatch(value)) return true;+ }+ } else if (headers && typeof headers === "object") {+ for (const [key, value] of Object.entries(headers)) {+ if (isMatch(key) || isMatch(value)) return true;+ }+ }++ return false;+}+export async function handleChatCore({body,modelInfo,@@ -954,6 +976,7 @@ export async function handleChatCore({const suffix = extra ? ` ${JSON.stringify(extra)}` : "";log?.info?.("STAGE_TRACE", `${traceId} ${label} t=${elapsed}ms${suffix}`);};+ let tokensCompressed: number | null = null;const persistFailureUsage = (statusCode: number, errorCode?: string | null) => {saveRequestUsage({provider: provider || "unknown",@@ -1099,6 +1122,7 @@ export async function handleChatCore({});const isDroidCLI =userAgent?.toLowerCase().includes("droid") || userAgent?.toLowerCase().includes("codex-cli");+ const copilotCompatibleReasoning = isCopilotClient(clientRawRequest?.headers, userAgent);const clientResponseFormat =sourceFormat === FORMATS.OPENAI_RESPONSES && !isResponsesEndpoint && !isDroidCLI? FORMATS.OPENAI@@ -1178,6 +1202,23 @@ export async function handleChatCore({const capturePipelineStreamChunks =detailedLoggingEnabled && getCallLogPipelineCaptureStreamChunks();const skillRequestId = generateRequestId();+ let compressionAnalyticsWritePromise: Promise<void> | null = null;+ const attachCompressionUsageReceiptAfterAnalytics = (+ usage: Record<string, unknown>,+ source: "provider" | "estimated" | "stream"+ ) => {+ const pendingWrite = compressionAnalyticsWritePromise;+ void (async () => {+ try {+ if (pendingWrite) await pendingWrite;+ const { attachCompressionUsageReceipt } =+ await import("../../src/lib/db/compressionAnalytics.ts");+ attachCompressionUsageReceipt(skillRequestId, usage, source);+ } catch {+ // Compression analytics are best-effort and must never affect responses.+ }+ })();+ };const pipelineSessionId =(clientRawRequest?.headers && typeof clientRawRequest.headers.get === "function"? clientRawRequest.headers.get("x-omniroute-session-id")@@ -1285,6 +1326,7 @@ export async function handleChatCore({comboName,comboStepId,comboExecutionKey,+ tokensCompressed,cacheSource: cacheSource === "semantic" ? "semantic" : "upstream",apiKeyId: apiKeyInfo?.id || null,apiKeyName: apiKeyInfo?.name || null,@@ -1560,6 +1602,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;@@ -1594,6 +1638,91 @@ export async function handleChatCore({log?.debug?.("COMPRESSION", "Prompt compression disabled or unavailable");}let compressionComboKey = comboName ?? null;+ let compressionComboApplied = false;+ type RuntimeCompressionCombo = {+ id: string;+ pipeline: NonNullable<CompressionConfig["stackedPipeline"]>;+ languagePacks: string[];+ outputMode: boolean;+ outputModeIntensity: string;+ };+ const isBuiltinStackedPipeline = (+ pipeline: CompressionConfig["stackedPipeline"] | undefined+ ): boolean => {+ if (!Array.isArray(pipeline) || pipeline.length !== 2) return false;+ const [first, second] = pipeline;+ return (+ first?.engine === "rtk" &&+ (first.intensity === undefined || first.intensity === "standard") &&+ !first.config &&+ second?.engine === "caveman" &&+ (second.intensity === undefined || second.intensity === "full") &&+ !second.config+ );+ };+ const applyCompressionComboConfig = (+ compressionCombo: RuntimeCompressionCombo | null,+ routingOverrideIds: string[] = []+ ): boolean => {+ if (!compressionCombo || compressionCombo.pipeline.length === 0) return false;+ const comboLanguagePacks = [+ ...new Set(+ compressionCombo.languagePacks+ .map((pack) => pack.trim())+ .filter((pack) => pack.length > 0)+ ),+ ];+ const comboOutputIntensity = (+ ["lite", "full", "ultra"].includes(compressionCombo.outputModeIntensity)+ ? compressionCombo.outputModeIntensity+ : (config.cavemanOutputMode?.intensity ?? "full")+ ) as "lite" | "full" | "ultra";+ const comboDefaultLanguage =+ comboLanguagePacks.find((pack) => pack === config.languageConfig?.defaultLanguage) ??+ comboLanguagePacks[0] ??+ config.languageConfig?.defaultLanguage ??+ "en";+ const comboOverrides = { ...(config.comboOverrides ?? {}) };+ for (const id of routingOverrideIds) {+ if (id) comboOverrides[id] = "stacked";+ }+ config = {+ ...config,+ compressionComboId: compressionCombo.id,+ stackedPipeline: compressionCombo.pipeline,+ languageConfig: {+ ...(config.languageConfig ?? {+ enabled: false,+ defaultLanguage: "en",+ autoDetect: true,+ enabledPacks: ["en"],+ }),+ enabled: true,+ defaultLanguage: comboDefaultLanguage,+ enabledPacks:+ comboLanguagePacks.length > 0+ ? comboLanguagePacks+ : (config.languageConfig?.enabledPacks ?? ["en"]),+ },+ cavemanOutputMode: {+ ...(config.cavemanOutputMode ?? {+ enabled: false,+ intensity: "full",+ autoClarity: true,+ }),+ enabled: compressionCombo.outputMode,+ intensity: comboOutputIntensity,+ },+ comboOverrides,+ };+ compressionComboApplied = true;+ return true;+ };+ const isStackedCompressionCombo = (+ compressionCombo: RuntimeCompressionCombo | null+ ): compressionCombo is RuntimeCompressionCombo => {+ return Boolean(compressionCombo && compressionCombo.pipeline.length > 1);+ };if (isCombo && comboName) {try {const { getComboByName } = await import("../../src/lib/localDb");@@ -1616,7 +1745,9 @@ export async function handleChatCore({comboMode === "lite" ||comboMode === "standard" ||comboMode === "aggressive" ||- comboMode === "ultra"+ comboMode === "ultra" ||+ comboMode === "rtk" ||+ comboMode === "stacked") {config = {...config,@@ -1628,6 +1759,27 @@ export async function handleChatCore({};compressionComboKey = comboName;}+ const routingComboIds = [+ comboConfig?.id,+ comboName,+ comboName.startsWith("combo/") ? comboName.substring(6) : null,+ ].filter((id): id is string => typeof id === "string" && id.length > 0);+ if (routingComboIds.length > 0) {+ const { getCompressionComboForRoutingCombo } =+ await import("../../src/lib/db/compressionCombos.ts");+ const assignedCompressionCombo =+ routingComboIds+ .map((id) => getCompressionComboForRoutingCombo(id))+ .find((combo) => combo !== null) ?? null;+ if (+ applyCompressionComboConfig(+ assignedCompressionCombo as RuntimeCompressionCombo | null,+ routingComboIds+ )+ ) {+ compressionComboKey = comboName;+ }+ }} catch (err) {log?.debug?.("COMPRESSION",@@ -1636,6 +1788,66 @@ export async function handleChatCore({);}}+ const modeBeforeOutputTransform = selectCompressionStrategy(+ config,+ compressionComboKey,+ estimatedTokens,+ body as Record<string, unknown>,+ { provider, targetFormat, model: effectiveModel }+ );+ if (+ modeBeforeOutputTransform === "stacked" &&+ !compressionComboApplied &&+ !config.compressionComboId &&+ isBuiltinStackedPipeline(config.stackedPipeline)+ ) {+ try {+ const { getDefaultCompressionCombo } =+ await import("../../src/lib/db/compressionCombos.ts");+ const defaultCompressionCombo = getDefaultCompressionCombo();+ if (+ isStackedCompressionCombo(defaultCompressionCombo as RuntimeCompressionCombo | null) &&+ applyCompressionComboConfig(defaultCompressionCombo as RuntimeCompressionCombo | null)+ ) {+ log?.debug?.(+ "COMPRESSION",+ `Default compression combo applied: ${defaultCompressionCombo?.id}`+ );+ }+ } catch (err) {+ log?.debug?.(+ "COMPRESSION",+ "Default compression combo lookup skipped: " ++ (err instanceof Error ? err.message : String(err))+ );+ }+ }+ if (config.cavemanOutputMode?.enabled) {+ try {+ const { applyCavemanOutputMode } = await import("../services/compression/outputMode.ts");+ const outputModeLanguage =+ config.languageConfig?.enabled === true ? config.languageConfig.defaultLanguage : "en";+ const outputMode = applyCavemanOutputMode(+ body as Parameters<typeof applyCavemanOutputMode>[0],+ config.cavemanOutputMode,+ outputModeLanguage+ );+ if (outputMode.applied) {+ body = outputMode.body as typeof body;+ cavemanOutputModeApplied = true;+ cavemanOutputModeIntensity = config.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))+ );+ }+ }const compressionInputBody = body as Record<string, unknown>;const mode = selectCompressionStrategy(config,@@ -1644,80 +1856,138 @@ 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;+ tokensCompressed = Math.max(+ 0,+ result.stats.originalTokens - result.stats.compressedTokens+ );+ }++ if (result.compressed || result.stats.fallbackApplied || cavemanOutputModeApplied) {+ trackCompressionStats(result.stats);+ compressionAnalyticsRecorded = true;+ compressionAnalyticsWritePromise = (async () => {+ try {+ const { insertCompressionAnalyticsRow } =+ await import("../../src/lib/db/compressionAnalytics.ts");+ const { calculateCost } = await import("../../src/lib/usage/costCalculator.ts");+ const tokensSaved = 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(",")})`- );+ );+ const estimatedUsdSaved = await calculateCost(+ provider ?? "",+ effectiveModel ?? "",+ {+ input: tokensSaved,+ }+ );+ insertCompressionAnalyticsRow({+ timestamp: new Date().toISOString(),+ combo_id: comboName ?? null,+ provider: provider ?? null,+ mode,+ engine: result.stats.engine ?? mode,+ compression_combo_id:+ result.stats.compressionComboId ?? config.compressionComboId ?? null,+ original_tokens: result.stats.originalTokens,+ compressed_tokens: result.stats.compressedTokens,+ tokens_saved: tokensSaved,+ duration_ms: result.stats.durationMs ?? null,+ request_id: skillRequestId,+ estimated_usd_saved: estimatedUsdSaved || null,+ validation_fallback: result.stats.fallbackApplied ? 1 : 0,+ output_mode: cavemanOutputModeApplied ? cavemanOutputModeIntensity : null,+ rtk_raw_output_pointer: result.stats.rtkRawOutputPointers?.[0]?.id ?? null,+ rtk_raw_output_bytes: result.stats.rtkRawOutputPointers?.[0]?.bytes ?? 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+ );+ 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) {+ compressionAnalyticsWritePromise = (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",+ engine: "caveman-output",+ compression_combo_id: config.compressionComboId ?? null,+ 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",@@ -1793,6 +2063,7 @@ export async function handleChatCore({if (compressionResult.compressed) {body = compressionResult.body;const stats = compressionResult.stats;+ tokensCompressed = Math.max(0, (stats?.original ?? 0) - (stats?.final ?? 0));const layersInfo =stats && "layers" in stats && Array.isArray(stats.layers)? ` (layers: ${stats.layers.map((l: { name: string }) => l.name).join(", ")})`@@ -3264,6 +3535,9 @@ export async function handleChatCore({// Log usage for non-streaming responsesconst usage = extractUsageFromResponse(responseBody, provider);+ if (usage && typeof usage === "object") {+ attachCompressionUsageReceiptAfterAnalytics(usage as Record<string, unknown>, "provider");+ }appendRequestLog({ model, provider, connectionId, tokens: usage, status: "200 OK" }).catch(() => {});@@ -3636,6 +3910,7 @@ export async function handleChatCore({// Track cache token metrics for streaming responsesif (streamUsage && typeof streamUsage === "object") {+ attachCompressionUsageReceiptAfterAnalytics(streamUsage as Record<string, unknown>, "stream");const inputTokens = streamUsage.prompt_tokens || 0;const cachedTokens = toPositiveNumber(streamUsage.cache_read_input_tokens ??@@ -3777,7 +4052,8 @@ export async function handleChatCore({streamStateBody,onStreamComplete,apiKeyInfo,- handleStreamFailure+ handleStreamFailure,+ copilotCompatibleReasoning);} else if (needsTranslation(targetFormat, clientResponseFormat)) {// Standard translation for other providers@@ -3793,7 +4069,8 @@ export async function handleChatCore({streamStateBody,onStreamComplete,apiKeyInfo,- handleStreamFailure+ handleStreamFailure,+ copilotCompatibleReasoning);} else {log?.debug?.("STREAM", `Standard passthrough mode`);diff --git a/open-sse/handlers/imageGeneration.ts b/open-sse/handlers/imageGeneration.tsindex f030375346..09777ece75 100644--- a/open-sse/handlers/imageGeneration.ts+++ b/open-sse/handlers/imageGeneration.ts@@ -45,6 +45,7 @@ const OPENAI_IMAGE_TO_IMAGE_MODELS = new Set(["flux-kontext-max","flux-kontext","flux-kontext-pro",+ "qwen-image",]);const BFL_MODEL_ENDPOINTS = {diff --git a/open-sse/handlers/responseSanitizer.ts b/open-sse/handlers/responseSanitizer.tsindex aa2c0f1e9d..4b85cb0119 100644--- a/open-sse/handlers/responseSanitizer.ts+++ b/open-sse/handlers/responseSanitizer.ts@@ -691,6 +691,9 @@ export function sanitizeStreamingChunk(parsed: unknown): unknown {}if (deltaRecord.reasoning_content !== undefined) {delta.reasoning_content = deltaRecord.reasoning_content;+ }+ if (deltaRecord.reasoning_text !== undefined) {+ delta.reasoning_text = deltaRecord.reasoning_text;} else if (typeof deltaRecord.reasoning === "string" && deltaRecord.reasoning) {// Alias: some providers use 'reasoning' instead of 'reasoning_content'delta.reasoning_content = deltaRecord.reasoning;diff --git a/open-sse/mcp-server/README.md b/open-sse/mcp-server/README.mdindex 43b9852940..f70c86014f 100644--- a/open-sse/mcp-server/README.md+++ b/open-sse/mcp-server/README.md@@ -145,12 +145,20 @@ omniroute --mcp### Cache and Compression Tools-| # | Tool | Scopes | Description |-| --- | --------------------------------- | ------------------- | ---------------------------------------------------------------------------- |-| 21 | `omniroute_cache_stats` | `read:cache` | Semantic cache, prompt-cache, and idempotency statistics |-| 22 | `omniroute_cache_flush` | `write:cache` | Flush cache entries globally or by signature/model |-| 23 | `omniroute_compression_status` | `read:compression` | Compression settings, analytics summary, and provider-aware cache statistics |-| 24 | `omniroute_compression_configure` | `write:compression` | Configure compression mode and trigger thresholds at runtime |+| # | Tool | Scopes | Description |+| --- | ----------------------------------- | ------------------- | ---------------------------------------------------------------------------- |+| 21 | `omniroute_cache_stats` | `read:cache` | Semantic cache, prompt-cache, and idempotency statistics |+| 22 | `omniroute_cache_flush` | `write:cache` | Flush cache entries globally or by signature/model |+| 23 | `omniroute_compression_status` | `read:compression` | Compression settings, analytics summary, and provider-aware cache statistics |+| 24 | `omniroute_compression_configure` | `write:compression` | Configure compression mode and trigger thresholds at runtime |+| 25 | `omniroute_set_compression_engine` | `write:compression` | Set Caveman, RTK, or stacked compression mode and pipeline |+| 26 | `omniroute_list_compression_combos` | `read:compression` | List named compression combos and routing assignments |+| 27 | `omniroute_compression_combo_stats` | `read:compression` | Read analytics grouped by compression combo and engine |++MCP listable metadata descriptions are compressed at registration/list time when description+compression is enabled. `omniroute_compression_status` exposes those savings separately as+`analytics.mcpDescriptionCompression` with `source: "mcp_metadata_estimate"`, so clients do not+mistake metadata shrink estimates for provider token receipts.---@@ -540,12 +548,12 @@ The MCP server supports **fine-grained scope enforcement** for multi-tenant envi| `read:usage` | `cost_report`, `explain_route`, `get_session_snapshot` || `read:models` | `list_models_catalog` || `read:cache` | `cache_stats` |-| `read:compression` | `compression_status` |+| `read:compression` | `compression_status`, `list_compression_combos`, `compression_combo_stats` || `write:combos` | `switch_combo` || `write:budget` | `set_budget_guard` || `write:resilience` | `set_resilience_profile` || `write:cache` | `cache_flush` |-| `write:compression` | `compression_configure` |+| `write:compression` | `compression_configure`, `set_compression_engine` || `execute:completions` | `route_request`, `test_combo` |**Wildcard scopes:** Use `read:*` to grant all read scopes, or `*` for full access.@@ -581,7 +589,7 @@ mcp-server/├── audit.ts # SQLite audit logger (SHA-256 input hashing)├── scopeEnforcement.ts # Fine-grained scope enforcement├── schemas/-│ ├── tools.ts # Zod schemas for all 16 tools (input/output/scopes)+│ ├── tools.ts # Zod schemas for core, cache, compression, and proxy tools│ ├── a2a.ts # A2A protocol types (Agent Card, Task, JSON-RPC)│ ├── audit.ts # Audit & routing decision types + hash helpers│ └── index.ts # Schema barrel exportdiff --git a/open-sse/mcp-server/descriptionCompressor.ts b/open-sse/mcp-server/descriptionCompressor.tsnew file mode 100644index 0000000000..e69a86ee4d--- /dev/null+++ b/open-sse/mcp-server/descriptionCompressor.ts@@ -0,0 +1,243 @@+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,+};++const persistedDescriptionCompressionStats: McpDescriptionCompressionStats = {+ descriptionsCompressed: 0,+ charsBefore: 0,+ charsAfter: 0,+ charsSaved: 0,+ estimatedTokensSaved: 0,+};++const MCP_LIST_CONTAINER_KEYS = new Set(["tools", "prompts", "resources", "resourceTemplates"]);+const MCP_METADATA_DESCRIPTION_FIELDS = ["description"];++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(/[ \t]+([,.;:!?])/g, "$1")+ .replace(/\n{3,}/g, "\n\n")+ .replace(/(^|[.!?][ \t]+|\n+[ \t]*)([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;+ }+ return description;+}++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);+ }+ }+}++function clonePlainMetadata<T>(value: T): T {+ if (!value || typeof value !== "object") return value;+ return JSON.parse(JSON.stringify(value)) as T;+}++function compressMcpListContainersInPlace(+ value: unknown,+ options: DescriptionCompressionOptions = {}+): void {+ if (!value || typeof value !== "object") return;+ if (Array.isArray(value)) {+ for (const item of value) compressMcpListContainersInPlace(item, options);+ return;+ }++ for (const [key, nested] of Object.entries(value as Record<string, unknown>)) {+ if (MCP_LIST_CONTAINER_KEYS.has(key) && Array.isArray(nested)) {+ compressDescriptionsInPlace(nested, MCP_METADATA_DESCRIPTION_FIELDS, options);+ } else if (nested && typeof nested === "object") {+ compressMcpListContainersInPlace(nested, options);+ }+ }+}++export function compressMcpListMetadata<T>(+ value: T,+ options: DescriptionCompressionOptions = {}+): T {+ if (!isMcpDescriptionCompressionEnabled(options)) return value;+ const clone = clonePlainMetadata(value);+ compressMcpListContainersInPlace(clone, options);+ return clone;+}++export function compressMcpRegistryMetadata<T extends Record<string, unknown>>(+ metadata: T,+ options: DescriptionCompressionOptions = {}+): T {+ if (!isMcpDescriptionCompressionEnabled(options)) return metadata;+ const clone: Record<string, unknown> = { ...metadata };+ if (typeof clone.description === "string") {+ clone.description = maybeCompressMcpDescription(clone.description, options);+ }+ return clone as T;+}++export function getMcpDescriptionCompressionStats(): McpDescriptionCompressionStats {+ return { ...descriptionCompressionStats };+}++function getUnpersistedMcpDescriptionCompressionStats(): McpDescriptionCompressionStats {+ return {+ descriptionsCompressed:+ descriptionCompressionStats.descriptionsCompressed -+ persistedDescriptionCompressionStats.descriptionsCompressed,+ charsBefore:+ descriptionCompressionStats.charsBefore - persistedDescriptionCompressionStats.charsBefore,+ charsAfter:+ descriptionCompressionStats.charsAfter - persistedDescriptionCompressionStats.charsAfter,+ charsSaved:+ descriptionCompressionStats.charsSaved - persistedDescriptionCompressionStats.charsSaved,+ estimatedTokensSaved:+ descriptionCompressionStats.estimatedTokensSaved -+ persistedDescriptionCompressionStats.estimatedTokensSaved,+ };+}++export async function snapshotMcpDescriptionCompressionStats(): Promise<McpDescriptionCompressionStats> {+ const delta = getUnpersistedMcpDescriptionCompressionStats();+ if (+ delta.descriptionsCompressed <= 0 ||+ delta.charsSaved <= 0 ||+ delta.estimatedTokensSaved <= 0+ ) {+ return {+ descriptionsCompressed: 0,+ charsBefore: 0,+ charsAfter: 0,+ charsSaved: 0,+ estimatedTokensSaved: 0,+ };+ }++ const originalTokens = Math.max(delta.estimatedTokensSaved, Math.ceil(delta.charsBefore / 4));+ const compressedTokens = Math.max(0, originalTokens - delta.estimatedTokensSaved);+ const { insertCompressionAnalyticsRow } =+ await import("../../src/lib/db/compressionAnalytics.ts");+ insertCompressionAnalyticsRow({+ timestamp: new Date().toISOString(),+ mode: "mcp-description",+ engine: "mcp-description",+ original_tokens: originalTokens,+ compressed_tokens: compressedTokens,+ tokens_saved: delta.estimatedTokensSaved,+ mcp_description_tokens_saved: delta.estimatedTokensSaved,+ });++ persistedDescriptionCompressionStats.descriptionsCompressed =+ descriptionCompressionStats.descriptionsCompressed;+ persistedDescriptionCompressionStats.charsBefore = descriptionCompressionStats.charsBefore;+ persistedDescriptionCompressionStats.charsAfter = descriptionCompressionStats.charsAfter;+ persistedDescriptionCompressionStats.charsSaved = descriptionCompressionStats.charsSaved;+ persistedDescriptionCompressionStats.estimatedTokensSaved =+ descriptionCompressionStats.estimatedTokensSaved;++ return delta;+}++export function resetMcpDescriptionCompressionStats(): void {+ descriptionCompressionStats.descriptionsCompressed = 0;+ descriptionCompressionStats.charsBefore = 0;+ descriptionCompressionStats.charsAfter = 0;+ descriptionCompressionStats.charsSaved = 0;+ descriptionCompressionStats.estimatedTokensSaved = 0;+ persistedDescriptionCompressionStats.descriptionsCompressed = 0;+ persistedDescriptionCompressionStats.charsBefore = 0;+ persistedDescriptionCompressionStats.charsAfter = 0;+ persistedDescriptionCompressionStats.charsSaved = 0;+ persistedDescriptionCompressionStats.estimatedTokensSaved = 0;+}diff --git a/open-sse/mcp-server/schemas/tools.ts b/open-sse/mcp-server/schemas/tools.tsindex 401f39d3d5..7f829b1529 100644--- a/open-sse/mcp-server/schemas/tools.ts+++ b/open-sse/mcp-server/schemas/tools.ts@@ -10,6 +10,10 @@*/import { z } from "zod";+import {+ AUTO_ROUTING_STRATEGY_VALUES,+ ROUTING_STRATEGY_VALUES,+} from "../../../src/shared/constants/routingStrategies.ts";// ============ Shared Types ============@@ -109,17 +113,7 @@ export const listCombosOutput = z.object({priority: z.number(),})),- strategy: z.enum([- "priority",- "weighted",- "round-robin",- "context-relay",- "strict-random",- "random",- "least-used",- "cost-optimized",- "auto",- ]),+ strategy: z.enum(ROUTING_STRATEGY_VALUES),enabled: z.boolean(),metrics: z.object({@@ -544,21 +538,9 @@ export const setBudgetGuardTool: McpToolDefinition<// --- Tool 11: omniroute_set_routing_strategy ---export const setRoutingStrategyInput = z.object({comboId: z.string().describe("Combo ID or name to update"),- strategy: z- .enum([- "priority",- "weighted",- "round-robin",- "context-relay",- "strict-random",- "random",- "least-used",- "cost-optimized",- "auto",- ])- .describe("Routing strategy to apply"),+ strategy: z.enum(ROUTING_STRATEGY_VALUES).describe("Routing strategy to apply"),autoRoutingStrategy: z- .enum(["rules", "cost", "eco", "latency", "fast"])+ .enum(AUTO_ROUTING_STRATEGY_VALUES).optional().describe("Optional strategy used by auto mode (only used when strategy='auto')"),});@@ -1000,14 +982,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 +1046,21 @@ export const compressionStatusTool: McpToolDefinition<export const compressionConfigureInput = z.object({enabled: z.boolean().optional(),strategy: z- .string()+ .enum(["off", "lite", "standard", "aggressive", "ultra", "rtk", "stacked"]).optional()- .describe("Compression strategy: 'none' | 'standard' | 'aggressive' | 'ultra'"),- maxTokens: z.number().optional().describe("Maximum tokens before compression triggers"),+ .describe("Compression mode"),+ autoTriggerMode: z+ .enum(["off", "lite", "standard", "aggressive", "ultra", "rtk", "stacked"])+ .optional(),+ maxTokens: z+ .number()+ .int()+ .min(0)+ .optional()+ .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 +1069,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 +1083,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/rtk/stacked), adjusting maxTokens threshold, targetRatio, auto-trigger mode, system prompt preservation, and MCP description compression.",inputSchema: compressionConfigureInput,outputSchema: compressionConfigureOutput,scopes: ["write:compression"],@@ -1072,6 +1092,72 @@ export const compressionConfigureTool: McpToolDefinition<sourceEndpoints: ["/api/compression/configure"],};+export const setCompressionEngineInput = z.object({+ engine: z.enum(["off", "caveman", "rtk", "stacked"]).optional(),+ cavemanIntensity: z.enum(["lite", "full", "ultra"]).optional(),+ rtkIntensity: z.enum(["minimal", "standard", "aggressive"]).optional(),+ outputMode: z.boolean().optional(),+});++export const setCompressionEngineOutput = z.object({+ success: z.boolean(),+ settings: z.record(z.string(), z.unknown()),+});++export const setCompressionEngineTool: McpToolDefinition<+ typeof setCompressionEngineInput,+ typeof setCompressionEngineOutput+> = {+ name: "omniroute_set_compression_engine",+ description: "Set the active compression engine and Caveman/RTK runtime options.",+ inputSchema: setCompressionEngineInput,+ outputSchema: setCompressionEngineOutput,+ scopes: ["write:compression"],+ auditLevel: "full",+ phase: 2,+ sourceEndpoints: ["/api/settings/compression", "/api/context/rtk/config"],+};++export const listCompressionCombosInput = z.object({});+export const listCompressionCombosOutput = z.object({+ combos: z.array(z.record(z.string(), z.unknown())),+});++export const listCompressionCombosTool: McpToolDefinition<+ typeof listCompressionCombosInput,+ typeof listCompressionCombosOutput+> = {+ name: "omniroute_list_compression_combos",+ description: "List compression combos and their engine pipelines.",+ inputSchema: listCompressionCombosInput,+ outputSchema: listCompressionCombosOutput,+ scopes: ["read:compression"],+ auditLevel: "basic",+ phase: 2,+ sourceEndpoints: ["/api/context/combos"],+};++export const compressionComboStatsInput = z.object({+ comboId: z.string().optional(),+ since: z.enum(["24h", "7d", "30d", "all"]).optional(),+});++export const compressionComboStatsOutput = z.record(z.string(), z.unknown());++export const compressionComboStatsTool: McpToolDefinition<+ typeof compressionComboStatsInput,+ typeof compressionComboStatsOutput+> = {+ name: "omniroute_compression_combo_stats",+ description: "Get compression analytics grouped by engine and compression combo.",+ inputSchema: compressionComboStatsInput,+ outputSchema: compressionComboStatsOutput,+ scopes: ["read:compression"],+ auditLevel: "basic",+ phase: 2,+ sourceEndpoints: ["/api/context/analytics"],+};+// ============ 1proxy Tools ============export const oneproxyFetchInput = z.object({@@ -1209,6 +1295,9 @@ export const MCP_TOOLS = [cacheFlushTool,compressionStatusTool,compressionConfigureTool,+ setCompressionEngineTool,+ listCompressionCombosTool,+ compressionComboStatsTool,oneproxyFetchTool,oneproxyRotateTool,oneproxyStatsTool,diff --git a/open-sse/mcp-server/server.ts b/open-sse/mcp-server/server.tsindex 7b7d7d9c7f..d2b5e58c95 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 { compressMcpRegistryMetadata } 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,33 @@ 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 metadata = compressMcpRegistryMetadata(config, {+ enabled: mcpDescriptionCompressionEnabled,+ });+ return registerTool(name, metadata, handler as never);+ }) as typeof server.registerTool;+ const registerPrompt = server.registerPrompt.bind(server);+ server.registerPrompt = ((name: string, config: Record<string, unknown>, handler: unknown) => {+ const metadata = compressMcpRegistryMetadata(config, {+ enabled: mcpDescriptionCompressionEnabled,+ });+ return registerPrompt(name, metadata as never, handler as never);+ }) as typeof server.registerPrompt;+ const registerResource = server.registerResource.bind(server);+ server.registerResource = ((+ name: string,+ uriOrTemplate: unknown,+ config: Record<string, unknown>,+ readCallback: unknown+ ) => {+ const metadata = compressMcpRegistryMetadata(config, {+ enabled: mcpDescriptionCompressionEnabled,+ });+ return registerResource(name, uriOrTemplate as never, metadata as never, readCallback as never);+ }) as typeof server.registerResource;// Register essential toolsserver.registerTool(diff --git a/open-sse/mcp-server/tools/advancedTools.ts b/open-sse/mcp-server/tools/advancedTools.tsindex 2275990db2..723a061925 100644--- a/open-sse/mcp-server/tools/advancedTools.ts+++ b/open-sse/mcp-server/tools/advancedTools.ts@@ -26,6 +26,11 @@ import {getComboModelString,getComboStepTarget,} from "../../../src/lib/combos/steps.ts";+import type {+ AutoRoutingStrategyValue,+ RoutingStrategyValue,+} from "../../../src/shared/constants/routingStrategies.ts";+import { normalizeRoutingStrategy } from "../../../src/shared/constants/routingStrategies.ts";const OMNIROUTE_BASE_URL = resolveOmniRouteBaseUrl();const OMNIROUTE_API_KEY = process.env.OMNIROUTE_API_KEY || "";@@ -372,17 +377,8 @@ export async function handleSetBudgetGuard(args: {export async function handleSetRoutingStrategy(args: {comboId: string;- strategy:- | "priority"- | "weighted"- | "round-robin"- | "context-relay"- | "strict-random"- | "random"- | "least-used"- | "cost-optimized"- | "auto";- autoRoutingStrategy?: "rules" | "cost" | "eco" | "latency" | "fast";+ strategy: RoutingStrategyValue;+ autoRoutingStrategy?: AutoRoutingStrategyValue;}) {const start = Date.now();try {@@ -424,8 +420,9 @@ export async function handleSetRoutingStrategy(args: {Object.keys(toRecord(combo.config)).length > 0 ? combo.config : comboData.config);+ const normalizedStrategy = normalizeRoutingStrategy(args.strategy);let nextConfig: JsonRecord | undefined = undefined;- if (args.strategy === "auto" && args.autoRoutingStrategy) {+ if (normalizedStrategy === "auto" && args.autoRoutingStrategy) {const currentAutoConfig = toRecord(currentConfig.auto);nextConfig = {...currentConfig,@@ -436,7 +433,7 @@ export async function handleSetRoutingStrategy(args: {};}- const payload: JsonRecord = { strategy: args.strategy };+ const payload: JsonRecord = { strategy: normalizedStrategy };if (nextConfig && Object.keys(nextConfig).length > 0) {payload.config = nextConfig;}@@ -451,16 +448,18 @@ export async function handleSetRoutingStrategy(args: {const updatedConfig = toRecord(updatedCombo.config);const resolvedAutoStrategy =toString(toRecord(updatedConfig.auto).routingStrategy) ||- (args.strategy === "auto" ? (args.autoRoutingStrategy ?? "rules") : "");+ (normalizedStrategy === "auto" ? (args.autoRoutingStrategy ?? "rules") : "");const result = {success: true,combo: {id: toString(updatedCombo.id, comboId),name: toString(updatedCombo.name, toString(combo.name, comboId)),- strategy: toString(updatedCombo.strategy, args.strategy),+ strategy: toString(updatedCombo.strategy, normalizedStrategy),autoRoutingStrategy:- toString(updatedCombo.strategy, args.strategy) === "auto" ? resolvedAutoStrategy : null,+ toString(updatedCombo.strategy, normalizedStrategy) === "auto"+ ? resolvedAutoStrategy+ : null,},};diff --git a/open-sse/mcp-server/tools/compressionTools.ts b/open-sse/mcp-server/tools/compressionTools.tsindex 795b053ef7..382a977634 100644--- a/open-sse/mcp-server/tools/compressionTools.ts+++ b/open-sse/mcp-server/tools/compressionTools.ts@@ -13,7 +13,12 @@ import {} from "../../../src/lib/db/compression.ts";import { getCompressionAnalyticsSummary } from "../../../src/lib/db/compressionAnalytics.ts";import { getCacheStatsSummary } from "../../../src/lib/db/compressionCacheStats.ts";+import { listCompressionCombos } from "../../../src/lib/db/compressionCombos.ts";import type { McpToolExtraLike } from "../scopeEnforcement.ts";+import {+ getMcpDescriptionCompressionStats,+ snapshotMcpDescriptionCompressionStats,+} from "../descriptionCompressor.ts";/*** Handle compression_status tool: return current compression config, analytics, and cache stats@@ -26,14 +31,42 @@ 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 }>;+ byEngine: Record<string, { count: number; tokensSaved: number; avgSavingsPct: number }>;+ byCompressionCombo: Record<string, { count: number; tokensSaved: 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;+ charsBefore: number;+ charsAfter: number;+ charsSaved: number;+ estimatedTokensSaved: number;+ persistedEstimatedTokensSaved: number;+ persistedSnapshots: number;+ source: "mcp_metadata_estimate";+ notProviderUsage: true;+ };};cacheStats: {hits: number;@@ -45,7 +78,9 @@ export async function handleCompressionStatus(const start = Date.now();try {const settings = await getCompressionSettings();+ await snapshotMcpDescriptionCompressionStats();const analyticsSummary = getCompressionAnalyticsSummary();+ const mcpDescriptionStats = getMcpDescriptionCompressionStats();const cacheStats = getCacheStatsSummary();const result = {@@ -53,14 +88,37 @@ 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 ?? {},+ byEngine: analyticsSummary.byEngine ?? {},+ byCompressionCombo: analyticsSummary.byCompressionCombo ?? {},+ validationFallbacks: analyticsSummary.validationFallbacks,+ requestsWithReceipts: analyticsSummary.realUsage.requestsWithReceipts,+ realUsage: analyticsSummary.realUsage,+ mcpDescriptionCompression: {+ descriptionsCompressed: mcpDescriptionStats.descriptionsCompressed,+ charsBefore: mcpDescriptionStats.charsBefore,+ charsAfter: mcpDescriptionStats.charsAfter,+ charsSaved: mcpDescriptionStats.charsSaved,+ estimatedTokensSaved: mcpDescriptionStats.estimatedTokensSaved,+ persistedEstimatedTokensSaved:+ analyticsSummary.mcpDescriptionCompression.estimatedTokensSaved,+ persistedSnapshots: analyticsSummary.mcpDescriptionCompression.snapshots,+ source: "mcp_metadata_estimate" as const,+ notProviderUsage: true as const,+ },},cacheStats: cacheStats? {@@ -98,9 +156,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 +169,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 +186,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 +207,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,},};@@ -165,7 +235,64 @@ export async function handleCompressionConfigure(}import { z } from "zod";-import { compressionStatusInput, compressionConfigureInput } from "../schemas/tools.ts";+import {+ compressionStatusInput,+ compressionConfigureInput,+ setCompressionEngineInput,+ listCompressionCombosInput,+ compressionComboStatsInput,+} from "../schemas/tools.ts";++export async function handleSetCompressionEngine(+ args: z.infer<typeof setCompressionEngineInput>+): Promise<{ success: boolean; settings: Record<string, unknown> }> {+ const updates: Record<string, unknown> = { enabled: true };+ if (args.engine) {+ updates.defaultMode = args.engine === "caveman" ? "standard" : args.engine;+ if (args.engine === "off") updates.enabled = false;+ }+ if (args.cavemanIntensity) {+ const current = await getCompressionSettings();+ updates.cavemanConfig = {+ ...(current.cavemanConfig ?? {}),+ intensity: args.cavemanIntensity,+ };+ }+ if (args.rtkIntensity) {+ const current = await getCompressionSettings();+ updates.rtkConfig = {+ ...(current.rtkConfig ?? {}),+ intensity: args.rtkIntensity,+ };+ }+ if (args.outputMode !== undefined) {+ const current = await getCompressionSettings();+ updates.cavemanOutputMode = {+ ...(current.cavemanOutputMode ?? {}),+ enabled: args.outputMode,+ };+ }+ const settings = await updateCompressionSettings(updates);+ return { success: true, settings: settings as unknown as Record<string, unknown> };+}++export async function handleListCompressionCombos(): Promise<{+ combos: ReturnType<typeof listCompressionCombos>;+}> {+ return { combos: listCompressionCombos() };+}++export async function handleCompressionComboStats(+ args: z.infer<typeof compressionComboStatsInput>+): Promise<Record<string, unknown>> {+ const summary = getCompressionAnalyticsSummary(args.since === "all" ? undefined : args.since);+ if (!args.comboId) return summary as unknown as Record<string, unknown>;+ return {+ comboId: args.comboId,+ summary,+ combo: summary.byCompressionCombo[args.comboId] ?? { count: 0, tokensSaved: 0 },+ };+}export const compressionTools = {omniroute_compression_status: {@@ -178,8 +305,27 @@ 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/rtk/stacked), adjusting maxTokens threshold, targetRatio, auto-trigger mode, system prompt preservation, and MCP description compression.",inputSchema: compressionConfigureInput,handler: (args: z.infer<typeof compressionConfigureInput>) => handleCompressionConfigure(args),},+ omniroute_set_compression_engine: {+ name: "omniroute_set_compression_engine",+ description: "Set the active compression engine and Caveman/RTK runtime options.",+ inputSchema: setCompressionEngineInput,+ handler: (args: z.infer<typeof setCompressionEngineInput>) => handleSetCompressionEngine(args),+ },+ omniroute_list_compression_combos: {+ name: "omniroute_list_compression_combos",+ description: "List compression combos and their engine pipelines.",+ inputSchema: listCompressionCombosInput,+ handler: (_args: z.infer<typeof listCompressionCombosInput>) => handleListCompressionCombos(),+ },+ omniroute_compression_combo_stats: {+ name: "omniroute_compression_combo_stats",+ description: "Get compression analytics grouped by engine and compression combo.",+ inputSchema: compressionComboStatsInput,+ handler: (args: z.infer<typeof compressionComboStatsInput>) =>+ handleCompressionComboStats(args),+ },};diff --git a/open-sse/package.json b/open-sse/package.jsonindex 8654cf7640..2d62ae8fa9 100644--- a/open-sse/package.json+++ b/open-sse/package.json@@ -1,6 +1,6 @@{"name": "@omniroute/open-sse",- "version": "3.7.8",+ "version": "3.7.9","description": "Express SSE sidecar for OmniRoute — handles streaming, protocol translation, and provider orchestration","type": "module","main": "index.js",diff --git a/open-sse/services/AGENTS.md b/open-sse/services/AGENTS.mdindex b7b99308d0..d13f4b1ea4 100644--- a/open-sse/services/AGENTS.md+++ b/open-sse/services/AGENTS.md@@ -51,12 +51,15 @@### Prompt Compression Pipeline- **`compression/`** — Modular prompt compression running proactively before `contextManager.ts`.- - `strategySelector.ts` — Selects mode (off/lite/standard/aggressive/ultra) with combo overrides and auto-trigger.+ - `strategySelector.ts` — Selects mode (off/lite/standard/aggressive/ultra/rtk/stacked) with compression combo assignments, combo overrides, and auto-trigger.- `lite.ts` — 5 lite techniques: whitespace collapse, system prompt dedup, tool result truncation, redundant removal, image URL placeholder.+ - `caveman.ts` / `cavemanRules.ts` — Caveman-style semantic condensation with file-loaded rule packs and language-aware rule selection.+ - `engines/registry.ts` — Engine registry used by standalone RTK/Caveman execution and stacked pipelines.+ - `engines/rtk/` — RTK tool-output compression: command detection, JSON filter packs, deduplication, smart truncation, ANSI/code noise stripping.- `stats.ts` — Per-request compression stats (original/compressed tokens, savings %, techniques).- `types.ts` — Shared types (`CompressionMode`, `CompressionConfig`, `CompressionStats`, `CompressionResult`).- `index.ts` — Barrel re-exports.- - Phase 1: lite mode only. Standard/aggressive/ultra = Phase 2.+ - Dashboard/API surface: `/dashboard/context/caveman`, `/dashboard/context/rtk`, `/dashboard/context/combos`, `/api/context/*`, and `/api/compression/preview`.### Auto-Routing & Adaptivediff --git a/open-sse/services/accountFallback.ts b/open-sse/services/accountFallback.tsindex 6b75933e44..3b1eb5a871 100644--- a/open-sse/services/accountFallback.ts+++ b/open-sse/services/accountFallback.ts@@ -511,12 +511,27 @@ export function getAllModelLockouts() {// ─── Provider Breaker Compatibility Wrappers ────────────────────────────────// Legacy helpers now delegate to the shared provider circuit breaker.+type ProviderBreakerProfile = Partial<+ Pick<+ ProviderProfile,+ "failureThreshold" | "resetTimeoutMs" | "circuitBreakerThreshold" | "circuitBreakerReset"+ >+>;+function getProviderBreaker(provider: string | null | undefined) {+ return provider ? getCircuitBreaker(provider) : null;+}++function configureProviderBreaker(+ provider: string | null | undefined,+ profile?: ProviderBreakerProfile | null+) {if (!provider) return null;- const profile = getProviderProfile(provider);++ const resolvedProfile = { ...getProviderProfile(provider), ...(profile ?? {}) };return getCircuitBreaker(provider, {- failureThreshold: profile.failureThreshold ?? profile.circuitBreakerThreshold,- resetTimeout: profile.resetTimeoutMs ?? profile.circuitBreakerReset,+ failureThreshold: resolvedProfile.failureThreshold ?? resolvedProfile.circuitBreakerThreshold,+ resetTimeout: resolvedProfile.resetTimeoutMs ?? resolvedProfile.circuitBreakerReset,});}@@ -551,7 +566,8 @@ export function getProviderCooldownRemainingMs(provider: string | null | undefinexport function recordProviderFailure(provider: string | null | undefined,log?: { warn?: (...args: unknown[]) => void },- connectionId?: string | null+ connectionId?: string | null,+ profile?: ProviderBreakerProfile | null): void {if (!provider) return;@@ -570,7 +586,7 @@ export function recordProviderFailure(lastConnectionFailure.set(dedupKey, now);}- const breaker = getProviderBreaker(provider);+ const breaker = configureProviderBreaker(provider, profile);if (!breaker) return;if (!breaker.canExecute()) return;diff --git a/open-sse/services/autoCombo/index.ts b/open-sse/services/autoCombo/index.tsindex 045ffaaf8d..062dbccacf 100644--- a/open-sse/services/autoCombo/index.ts+++ b/open-sse/services/autoCombo/index.ts@@ -15,13 +15,4 @@ export {export { getTaskFitness, getTaskTypes } from "./taskFitness";export { SelfHealingManager, getSelfHealingManager } from "./selfHealing";export { MODE_PACKS, getModePack, getModePackNames } from "./modePacks";-export {- selectProvider,- createAutoCombo,- getAutoCombo,- updateAutoCombo,- deleteAutoCombo,- listAutoCombos,- type AutoComboConfig,- type SelectionResult,-} from "./engine";+export { selectProvider, type AutoComboConfig, type SelectionResult } from "./engine";diff --git a/open-sse/services/combo.ts b/open-sse/services/combo.tsindex 93a84f4741..8bd9efa5e9 100644--- a/open-sse/services/combo.ts+++ b/open-sse/services/combo.ts@@ -48,6 +48,7 @@ import {resolveRequestRoutingTags,type RoutingTagMatchMode,} from "../../src/domain/tagRouter.ts";+import { normalizeRoutingStrategy } from "../../src/shared/constants/routingStrategies.ts";// Status codes that should mark round-robin target semaphores as cooling down.const TRANSIENT_FOR_SEMAPHORE = [429, 502, 503, 504];@@ -630,17 +631,25 @@ function sortTargetsByUsage(targets: ResolvedComboTarget[], comboName: string) {*/function sortModelsByContextSize(models) {const withContext = models.map((modelStr) => {- const parsed = parseModel(modelStr);- const provider = parsed.provider || parsed.providerAlias || "unknown";- const model = parsed.model || modelStr;- const limit = getModelContextLimit(provider, model);- return { modelStr, context: limit ?? 0 };+ return { modelStr, context: getModelContextLimitForModelString(modelStr) ?? 0 };});withContext.sort((a, b) => b.context - a.context);return withContext.map((e) => e.modelStr);}+function getModelContextLimitForModelString(modelStr: string) {+ const parsed = parseModel(modelStr);+ const provider = parsed.provider || parsed.providerAlias || "unknown";+ const model = parsed.model || modelStr;+ return getModelContextLimit(provider, model);+}+function sortTargetsByContextSize(targets: ResolvedComboTarget[]) {+ const hasKnownContext = targets.some(+ (target) => getModelContextLimitForModelString(target.modelStr) != null+ );+ if (!hasKnownContext) return targets;+const orderedModels = sortModelsByContextSize(targets.map((target) => target.modelStr));const byModel = new Map<string, ResolvedComboTarget[]>();for (const target of targets) {@@ -656,6 +665,38 @@ function sortTargetsByContextSize(targets: ResolvedComboTarget[]) {.filter((target): target is ResolvedComboTarget => target !== null);}+function getP2CTargetScore(+ target: ResolvedComboTarget,+ metrics: ReturnType<typeof getComboMetrics>+): number {+ const breakerState = getCircuitBreaker(target.provider)?.getStatus?.()?.state;+ if (breakerState === "OPEN") return -Infinity;+ const modelMetric = metrics?.byModel?.[target.modelStr] || null;+ const successRate = Number(modelMetric?.successRate);+ const avgLatency = Number(modelMetric?.avgLatencyMs);+ const successScore = Number.isFinite(successRate) ? successRate / 100 : 0.5;+ const latencyScore =+ Number.isFinite(avgLatency) && avgLatency > 0 ? 1 / Math.log10(avgLatency + 10) : 0.25;+ const breakerPenalty = breakerState === "HALF_OPEN" ? 0.25 : 0;+ return successScore + latencyScore - breakerPenalty;+}++function orderTargetsByPowerOfTwoChoices(targets: ResolvedComboTarget[], comboName: string) {+ if (targets.length <= 1) return targets;+ const metrics = getComboMetrics(comboName);+ const firstIndex = Math.floor(Math.random() * targets.length);+ let secondIndex = Math.floor(Math.random() * (targets.length - 1));+ if (secondIndex >= firstIndex) secondIndex++;++ const first = targets[firstIndex];+ const second = targets[secondIndex];+ const selectedIndex =+ getP2CTargetScore(second, metrics) > getP2CTargetScore(first, metrics)+ ? secondIndex+ : firstIndex;+ return [targets[selectedIndex], ...targets.filter((_, index) => index !== selectedIndex)];+}+function toTextContent(content) {if (typeof content === "string") return content;if (!Array.isArray(content)) return "";@@ -1034,7 +1075,7 @@ export async function handleComboChat({relayOptions,signal,}) {- const strategy = combo.strategy || "priority";+ const strategy = normalizeRoutingStrategy(combo.strategy || "priority");const relayConfig =strategy === "context-relay" ? resolveContextRelayConfig(relayOptions?.config || null) : null;@@ -1427,6 +1468,14 @@ export async function handleComboChat({} else if (strategy === "random") {orderedTargets = fisherYatesShuffle([...orderedTargets]);log.info("COMBO", `Random shuffle: ${orderedTargets.length} targets`);+ } else if (strategy === "fill-first") {+ log.info(+ "COMBO",+ `Fill-first ordering: preserving priority order (${orderedTargets.length} targets)`+ );+ } else if (strategy === "p2c") {+ orderedTargets = orderTargetsByPowerOfTwoChoices(orderedTargets, combo.name);+ log.info("COMBO", `Power-of-two-choices ordering: selected ${orderedTargets[0]?.modelStr}`);} else if (strategy === "least-used") {orderedTargets = sortTargetsByUsage(orderedTargets, combo.name);log.info("COMBO", `Least-used ordering: ${orderedTargets[0]?.modelStr} has fewest requests`);@@ -1678,7 +1727,7 @@ export async function handleComboChat({// Trigger shared provider circuit breaker for 5xx errors and connection failuresif (isProviderFailureCode(result.status)) {- recordProviderFailure(provider, log, target.connectionId);+ recordProviderFailure(provider, log, target.connectionId, profile);}// Check if this is a transient error worth retrying on same modeldiff --git a/open-sse/services/compression/aggressive.ts b/open-sse/services/compression/aggressive.tsindex 8e2d3e85c4..a1edf3536a 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;@@ -157,7 +144,10 @@ export function compressAggressive(}try {- const liteResult = applyLiteCompression({ messages: currentMessages });+ const liteResult = applyLiteCompression(+ { messages: currentMessages },+ { preserveSystemPrompt: cfg.preserveSystemPrompt !== false }+ );if (liteResult?.compressed && liteResult.stats) {const liteSavings = liteResult.stats.savingsPercent ?? 0;if (liteSavings > resultStats.savingsPercent) {diff --git a/open-sse/services/compression/caveman.ts b/open-sse/services/compression/caveman.tsindex e0c40ecdfa..476be8d41e 100644--- a/open-sse/services/compression/caveman.ts+++ b/open-sse/services/compression/caveman.ts@@ -1,12 +1,22 @@-import type { CavemanConfig, CavemanRule, CompressionResult, CompressionMode } from "./types.ts";+import type {+ CavemanConfig,+ CavemanRule,+ CompressionResult,+ CompressionMode,+ 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, estimateCompressionTokens } from "./stats.ts";+import { validateCompression } from "./validation.ts";+import { mapTextContent } from "./messageContent.ts";+import { detectCompressionLanguage } from "./languageDetector.ts";interface ChatMessage {role: string;content?: string | Array<{ type: string; text?: string }>;+ [key: string]: unknown;}interface ChatRequestBody {@@ -14,14 +24,165 @@ interface ChatRequestBody {[key: string]: unknown;}+const RULE_KEYWORDS: Record<string, string[]> = {+ redundant_phrasing: ["make sure", "be sure"],+ redundant_because: ["due to the fact", "the reason is because"],+ redundant_directive: ["it is important", "you should", "remember to"],+ pleasantries: [+ "sure",+ "certainly",+ "of course",+ "happy to",+ "thanks",+ "thank you",+ "glad to help",+ "glad to",+ "no problem",+ "you're welcome",+ "youre welcome",+ "absolutely",+ ],+ 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"],+ softeners: ["if possible", "when you get a chance", "at your convenience", "just wondering"],+ uncertainty_fillers: ["i guess", "i suppose", "more or less", "in a way"],+ assistant_fillers: ["here's", "below is", "this is"],+ 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"],+ all_quantifier: ["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"],+ ultra_config_abbreviation: ["configuration"],+ ultra_function_abbreviation: ["function"],+ ultra_request_abbreviation: ["request"],+ ultra_response_abbreviation: ["response"],+ ultra_implementation_abbreviation: ["implementation"],+ ultra_authentication_abbreviation: ["authentication"],+ ultra_authorization_abbreviation: ["authorization"],+ ultra_application_abbreviation: ["application"],+ ultra_dependency_abbreviation: ["dependency", "dependencies"],+ ultra_common_abbreviations: [+ "implementation",+ "authentication",+ "authorization",+ "application",+ "dependency",+ "dependencies",+ ],+};++const ARTICLE_HINT_RE = /\b(?:a|an|the)\b/;++function shouldAttemptRule(ruleName: string, lowerText: string): boolean {+ if (ruleName === "articles") {+ ARTICLE_HINT_RE.lastIndex = 0;+ return ARTICLE_HINT_RE.test(lowerText);+ }++ const keywords = RULE_KEYWORDS[ruleName];+ return !keywords || keywords.some((keyword) => lowerText.includes(keyword));+}+export function applyRulesToText(text: string,rules: CavemanRule[]): { text: string; appliedRules: string[] } {let result = text;+ const lowerResult = text.toLowerCase();const appliedRules: string[] = [];for (const rule of rules) {+ if (!shouldAttemptRule(rule.name, lowerResult)) continue;+const before = result;const { pattern, replacement } = rule;if (typeof replacement === "function") {@@ -43,14 +204,76 @@ 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(/[ \t]{2,}/g, " ");+ if (/[\t ]+[,.;:!?]/.test(result)) result = result.replace(/[ \t]+([,.;:!?])/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(+ /(^|[.!?][ \t]+|\n+[ \t]*)([a-z])/g,+ (_match, prefix: string, char: string) => {+ return `${prefix}${char.toUpperCase()}`;+ }+ );+}++function createCavemanStats(+ originalTokens: number,+ compressedTokens: number,+ techniquesUsed: string[],+ rulesApplied: string[] | undefined,+ durationMs: number+): CompressionStats {+ const savingsPercent =+ originalTokens > 0+ ? Math.round(((originalTokens - compressedTokens) / originalTokens) * 10000) / 100+ : 0;+ return {+ originalTokens,+ compressedTokens,+ savingsPercent,+ techniquesUsed,+ mode: "standard",+ timestamp: Date.now(),+ ...(rulesApplied && rulesApplied.length > 0 ? { rulesApplied } : {}),+ durationMs,+ };+}++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]{1,1000}\]\([^)[ \t\n]{1,2000}(?:[ \t]+"[^"]{0,1000}")?\)|^#{1,6}\s+|^[ \t]*\|(?:[^|\n]{0,1000}\|){1,100}[ \t]*$|\$\$|\\\[|\\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$]*[ \t]*\([^()\n]{0,1000}\)|(?:^|\s)(?:\.{0,2}\/[A-Za-z0-9_@./-]+|[A-Za-z]:\\[A-Za-z0-9_.\\/-]+)|\b(?:TypeError|ReferenceError|SyntaxError|RangeError|URIError|EvalError|Error|Exception):[^\n]{0,1000}/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 +303,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,33 +338,83 @@ 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 detectedLanguage = config.autoDetectLanguage+ ? detectCompressionLanguage(textPart)+ : (config.language ?? "en");+ const enabledPacks = config.enabledLanguagePacks ?? ["en", detectedLanguage];+ const language = enabledPacks.includes(detectedLanguage)+ ? detectedLanguage+ : enabledPacks.includes("en")+ ? "en"+ : detectedLanguage;+ const rules = getRulesForContext(msg.role, config.intensity, language).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;const uniqueRules = [...new Set(allAppliedRules)];- const stats = createCompressionStats(- body as unknown as Record<string, unknown>,- { ...body, messages: compressedMessages } as unknown as Record<string, unknown>,- "standard" as CompressionMode,+ const stats = createCavemanStats(+ totalOriginalTokens,+ totalCompressedTokens,uniqueRules.length > 0 ? ["caveman-rules"] : [],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..c94ad6419e 100644--- a/open-sse/services/compression/cavemanRules.ts+++ b/open-sse/services/compression/cavemanRules.ts@@ -1,14 +1,48 @@import type { CavemanRule } from "./types.ts";+import { loadAllRulesForLanguage } from "./ruleLoader.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:+ /(?<!make\s)(?<!be\s)\b(?:i'?d be happy to|i would be happy to|i'?d be glad to|i would be glad to|glad to help|happy to|thank you|thanks|no problem|you'?re welcome|absolutely|certainly|of course|sure)\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,65 +50,105 @@ 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": "provide",- "give me a comprehensive": "give",- "write an in-depth": "write",- "create a thorough": "create",- "explain in detail": "explain",+ "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 ",+ "create a thorough": "create ",+ "explain in detail": "explain ",};const lower = match.toLowerCase();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(?:[Aa]n|[Aa]|[Tt]he)\s+(?=[a-z])/g,+ 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 +158,8 @@ const CAVEMAN_RULES: CavemanRule[] = [pattern: /\band any potential\b/gi,replacement: "",context: "all",+ category: "context",+ minIntensity: "full",},{name: "explanatory_prefix",@@ -99,6 +175,8 @@ const CAVEMAN_RULES: CavemanRule[] = [return map[match.toLowerCase()] ?? match;},context: "all",+ category: "context",+ minIntensity: "lite",},{name: "question_to_directive",@@ -107,20 +185,24 @@ const CAVEMAN_RULES: CavemanRule[] = [replacement: (match: string): string => {const trimmed = match.trimEnd().toLowerCase();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",+ "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[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 +210,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 +253,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 +276,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 +319,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 +331,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 +340,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 +357,76 @@ 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",+ language = "en"+): CavemanRule[] {+ const rank = INTENSITY_RANK[intensity] ?? INTENSITY_RANK.full;+ const fileRules = language ? loadAllRulesForLanguage(language) : [];+ const rules = fileRules.length > 0 ? fileRules : CAVEMAN_RULES;+ const selected = rules.filter((rule) => {+ const minRank = INTENSITY_RANK[rule.minIntensity ?? "lite"];+ return (rule.context === "all" || rule.context === context) && minRank <= rank;+ });+ return selected.length > 0+ ? selected+ : 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() {+ const intensities = ["lite", "full", "ultra"] as const;+ return CAVEMAN_RULES.map((rule) => ({+ name: rule.name,+ context: rule.context,+ category: rule.category ?? "terse",+ minIntensity: rule.minIntensity ?? "lite",+ intensities: intensities.filter(+ (intensity) => INTENSITY_RANK[intensity] >= INTENSITY_RANK[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..5dbebd7b1d--- /dev/null+++ b/open-sse/services/compression/diffHelper.ts@@ -0,0 +1,117 @@+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;+}++export interface CompressionPreviewDiffOptions {+ maxTokenProduct?: number;+}++export const DEFAULT_MAX_PREVIEW_DIFF_TOKEN_PRODUCT = 1_000_000;++function tokenize(text: string): string[] {+ return text.match(/\s+|[^\s]+/g) ?? [];+}++function getDiffSkipWarning(+ original: string,+ compressed: string,+ options: CompressionPreviewDiffOptions = {}+): string | null {+ const maxTokenProduct = options.maxTokenProduct ?? DEFAULT_MAX_PREVIEW_DIFF_TOKEN_PRODUCT;+ if (maxTokenProduct <= 0) return null;++ const originalTokens = tokenize(original).length;+ const compressedTokens = tokenize(compressed).length;+ if (originalTokens * compressedTokens <= maxTokenProduct) return null;++ return `Preview diff omitted because token product ${originalTokens}x${compressedTokens} exceeds safe limit ${maxTokenProduct}.`;+}++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,+ options: CompressionPreviewDiffOptions = {}+): 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),+ }));+ const diffSkipWarning = getDiffSkipWarning(original, compressed, options);++ return {+ segments: diffSkipWarning+ ? [{ type: "same", text: "[diff omitted: input too large]" }]+ : buildCompressionDiff(original, compressed),+ preservedBlocks: preserved,+ ruleRemovals: stats?.rulesApplied ?? [],+ validationWarnings: [+ ...(stats?.validationWarnings ?? []),+ ...validation.warnings,+ ...(diffSkipWarning ? [diffSkipWarning] : []),+ ],+ validationErrors: [...(stats?.validationErrors ?? []), ...validation.errors],+ fallbackApplied: Boolean(stats?.fallbackApplied || validation.fallbackApplied),+ };+}diff --git a/open-sse/services/compression/engines/cavemanAdapter.ts b/open-sse/services/compression/engines/cavemanAdapter.tsnew file mode 100644index 0000000000..51ae2b6548--- /dev/null+++ b/open-sse/services/compression/engines/cavemanAdapter.ts@@ -0,0 +1,408 @@+import { applyLiteCompression } from "../lite.ts";+import { cavemanCompress } from "../caveman.ts";+import { compressAggressive } from "../aggressive.ts";+import { ultraCompress } from "../ultra.ts";+import { createCompressionStats } from "../stats.ts";+import {+ DEFAULT_AGGRESSIVE_CONFIG,+ DEFAULT_ULTRA_CONFIG,+ type CavemanIntensity,+} from "../types.ts";+import type { CompressionEngine, EngineConfigField, EngineValidationResult } from "./types.ts";++const CAVEMAN_INTENSITIES: CavemanIntensity[] = ["lite", "full", "ultra"];++const CAVEMAN_SCHEMA: EngineConfigField[] = [+ {+ key: "intensity",+ type: "select",+ label: "Intensity",+ defaultValue: "full",+ options: CAVEMAN_INTENSITIES.map((value) => ({ value, label: value })),+ },+ {+ key: "minMessageLength",+ type: "number",+ label: "Minimum message length",+ defaultValue: 50,+ min: 0,+ max: 10000,+ },+ {+ key: "enabled",+ type: "boolean",+ label: "Enabled",+ defaultValue: true,+ },+];++const AGGRESSIVE_SCHEMA: EngineConfigField[] = [+ {+ key: "summarizerEnabled",+ type: "boolean",+ label: "Summarizer enabled",+ defaultValue: DEFAULT_AGGRESSIVE_CONFIG.summarizerEnabled,+ },+ {+ key: "maxTokensPerMessage",+ type: "number",+ label: "Max tokens per message",+ defaultValue: DEFAULT_AGGRESSIVE_CONFIG.maxTokensPerMessage,+ min: 256,+ max: 32768,+ },+ {+ key: "minSavingsThreshold",+ type: "number",+ label: "Minimum savings threshold",+ defaultValue: DEFAULT_AGGRESSIVE_CONFIG.minSavingsThreshold,+ min: 0,+ max: 1,+ },+ {+ key: "preserveSystemPrompt",+ type: "boolean",+ label: "Preserve system prompt",+ defaultValue: true,+ },+];++const ULTRA_SCHEMA: EngineConfigField[] = [+ {+ key: "enabled",+ type: "boolean",+ label: "Enabled",+ defaultValue: DEFAULT_ULTRA_CONFIG.enabled,+ },+ {+ key: "compressionRate",+ type: "number",+ label: "Compression rate",+ defaultValue: DEFAULT_ULTRA_CONFIG.compressionRate,+ min: 0,+ max: 1,+ },+ {+ key: "minScoreThreshold",+ type: "number",+ label: "Minimum score threshold",+ defaultValue: DEFAULT_ULTRA_CONFIG.minScoreThreshold,+ min: 0,+ max: 1,+ },+ {+ key: "slmFallbackToAggressive",+ type: "boolean",+ label: "Fallback to aggressive",+ defaultValue: DEFAULT_ULTRA_CONFIG.slmFallbackToAggressive,+ },+ {+ key: "modelPath",+ type: "string",+ label: "Model path",+ defaultValue: "",+ },+ {+ key: "maxTokensPerMessage",+ type: "number",+ label: "Max tokens per message",+ defaultValue: DEFAULT_ULTRA_CONFIG.maxTokensPerMessage,+ min: 0,+ max: 32768,+ },+ {+ key: "preserveSystemPrompt",+ type: "boolean",+ label: "Preserve system prompt",+ defaultValue: true,+ },+];++function ok(): EngineValidationResult {+ return { valid: true, errors: [] };+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return !!value && typeof value === "object" && !Array.isArray(value);+}++function validateBoolean(config: Record<string, unknown>, key: string, errors: string[]): void {+ if (config[key] !== undefined && typeof config[key] !== "boolean") {+ errors.push(`${key} must be a boolean`);+ }+}++function validateNumberRange(+ config: Record<string, unknown>,+ key: string,+ min: number,+ max: number,+ errors: string[]+): void {+ const value = config[key];+ if (value === undefined) return;+ if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > max) {+ errors.push(`${key} must be a number between ${min} and ${max}`);+ }+}++function validateCavemanLikeConfig(config: Record<string, unknown>): EngineValidationResult {+ const errors: string[] = [];+ if (+ config.intensity !== undefined &&+ !CAVEMAN_INTENSITIES.includes(config.intensity as CavemanIntensity)+ ) {+ errors.push("intensity must be lite, full, or ultra");+ }+ if (+ config.minMessageLength !== undefined &&+ (typeof config.minMessageLength !== "number" || config.minMessageLength < 0)+ ) {+ errors.push("minMessageLength must be a non-negative number");+ }+ if (config.enabled !== undefined && typeof config.enabled !== "boolean") {+ errors.push("enabled must be a boolean");+ }+ return { valid: errors.length === 0, errors };+}++function validateAggressiveConfig(config: Record<string, unknown>): EngineValidationResult {+ const errors: string[] = [];+ validateBoolean(config, "summarizerEnabled", errors);+ validateBoolean(config, "preserveSystemPrompt", errors);+ validateNumberRange(config, "maxTokensPerMessage", 256, 32768, errors);+ validateNumberRange(config, "minSavingsThreshold", 0, 1, errors);++ if (config.thresholds !== undefined) {+ if (!isRecord(config.thresholds)) {+ errors.push("thresholds must be an object");+ } else {+ for (const key of ["fullSummary", "moderate", "light", "verbatim"]) {+ validateNumberRange(config.thresholds, key, 1, 100, errors);+ }+ }+ }++ if (config.toolStrategies !== undefined) {+ if (!isRecord(config.toolStrategies)) {+ errors.push("toolStrategies must be an object");+ } else {+ for (const key of ["fileContent", "grepSearch", "shellOutput", "json", "errorMessage"]) {+ validateBoolean(config.toolStrategies, key, errors);+ }+ }+ }++ return { valid: errors.length === 0, errors };+}++function validateUltraConfig(config: Record<string, unknown>): EngineValidationResult {+ const errors: string[] = [];+ validateBoolean(config, "enabled", errors);+ validateBoolean(config, "slmFallbackToAggressive", errors);+ validateBoolean(config, "preserveSystemPrompt", errors);+ validateNumberRange(config, "compressionRate", 0, 1, errors);+ validateNumberRange(config, "minScoreThreshold", 0, 1, errors);+ validateNumberRange(config, "maxTokensPerMessage", 0, 32768, errors);+ if (config.modelPath !== undefined && typeof config.modelPath !== "string") {+ errors.push("modelPath must be a string");+ }+ return { valid: errors.length === 0, errors };+}++export const liteEngine: CompressionEngine = {+ id: "lite",+ name: "Lite",+ description: "Fast whitespace, tool-result and image URL reduction.",+ icon: "compress",+ targets: ["messages", "tool_results"],+ stackable: true,+ stackPriority: 5,+ metadata: {+ id: "lite",+ name: "Lite",+ description: "Fast whitespace, tool-result and image URL reduction.",+ inputScope: "messages",+ targetLatencyMs: 1,+ supportsPreview: true,+ stable: true,+ },+ apply(body, options) {+ return applyLiteCompression(body, {+ ...options,+ preserveSystemPrompt: options?.config?.preserveSystemPrompt !== false,+ });+ },+ compress(body, config) {+ return this.apply(body, { stepConfig: config });+ },+ getConfigSchema() {+ return AGGRESSIVE_SCHEMA;+ },+ validateConfig(config) {+ return validateAggressiveConfig(config);+ },+};++export const cavemanEngine: CompressionEngine = {+ id: "caveman",+ name: "Caveman",+ description: "Rule-based message compression with preservation and validation.",+ icon: "compress",+ targets: ["messages"],+ stackable: true,+ stackPriority: 20,+ metadata: {+ id: "caveman",+ name: "Caveman",+ description: "Rule-based message compression with preservation and validation.",+ inputScope: "messages",+ targetLatencyMs: 1,+ supportsPreview: true,+ stable: true,+ },+ apply(body, options) {+ const cavemanConfig = {+ ...(options?.config?.cavemanConfig ?? {}),+ ...(options?.stepConfig ?? {}),+ ...(options?.config?.languageConfig?.enabled+ ? {+ language: options.config.languageConfig.defaultLanguage,+ autoDetectLanguage: options.config.languageConfig.autoDetect,+ enabledLanguagePacks: options.config.languageConfig.enabledPacks,+ }+ : {}),+ ...(options?.config?.preserveSystemPrompt !== false+ ? {+ compressRoles: (options?.config?.cavemanConfig?.compressRoles ?? ["user"]).filter(+ (role) => role !== "system"+ ),+ }+ : {}),+ };+ return cavemanCompress(body as Parameters<typeof cavemanCompress>[0], cavemanConfig);+ },+ compress(body, config) {+ return this.apply(body, { stepConfig: config });+ },+ getConfigSchema() {+ return CAVEMAN_SCHEMA;+ },+ validateConfig(config) {+ return validateCavemanLikeConfig(config);+ },+};++export const aggressiveEngine: CompressionEngine = {+ id: "aggressive",+ name: "Aggressive",+ description: "Summarization, tool result compression and progressive aging.",+ icon: "speed",+ targets: ["messages", "tool_results"],+ stackable: true,+ stackPriority: 30,+ metadata: {+ id: "aggressive",+ name: "Aggressive",+ description: "Summarization, tool result compression and progressive aging.",+ inputScope: "messages",+ targetLatencyMs: 5,+ supportsPreview: true,+ stable: true,+ },+ apply(body, options) {+ const messages = (body.messages ?? []) as Array<{+ role: string;+ content?: string | Array<{ type: string; text?: string }>;+ [key: string]: unknown;+ }>;+ if (!Array.isArray(messages) || messages.length === 0) {+ return { body, compressed: false, stats: null };+ }+ const aggressiveConfig = {+ ...(options?.config?.aggressive ?? {}),+ ...(options?.stepConfig ?? {}),+ preserveSystemPrompt: options?.config?.preserveSystemPrompt !== false,+ };+ const result = compressAggressive(messages, aggressiveConfig);+ const compressedBody = { ...body, messages: result.messages };+ return {+ body: compressedBody,+ compressed: result.stats.savingsPercent > 0,+ stats: createCompressionStats(+ body,+ compressedBody,+ "aggressive",+ ["aggressive"],+ result.stats.rulesApplied,+ result.stats.durationMs+ ),+ };+ },+ compress(body, config) {+ return this.apply(body, { stepConfig: config });+ },+ getConfigSchema() {+ return AGGRESSIVE_SCHEMA;+ },+ validateConfig(config) {+ return validateAggressiveConfig(config);+ },+};++export const ultraEngine: CompressionEngine = {+ id: "ultra",+ name: "Ultra",+ description: "Heuristic token pruning with optional local SLM fallback.",+ icon: "bolt",+ targets: ["messages"],+ stackable: true,+ stackPriority: 40,+ metadata: {+ id: "ultra",+ name: "Ultra",+ description: "Heuristic token pruning with optional local SLM fallback.",+ inputScope: "messages",+ targetLatencyMs: 5,+ supportsPreview: true,+ stable: true,+ },+ apply(body, options) {+ const messages = (body.messages ?? []) as Array<{+ role: string;+ content?: string | unknown[];+ [key: string]: unknown;+ }>;+ if (!Array.isArray(messages) || messages.length === 0) {+ return { body, compressed: false, stats: null };+ }+ const ultraConfig = {+ ...(options?.config?.ultra ?? {}),+ ...(options?.stepConfig ?? {}),+ preserveSystemPrompt: options?.config?.preserveSystemPrompt !== false,+ };+ const result = ultraCompress(messages, ultraConfig);+ const compressedBody = { ...body, messages: result.messages };+ return {+ body: compressedBody,+ compressed: result.stats.savingsPercent > 0,+ stats: createCompressionStats(+ body,+ compressedBody,+ "ultra",+ ["ultra"],+ result.stats.rulesApplied,+ result.stats.durationMs+ ),+ };+ },+ compress(body, config) {+ return this.apply(body, { stepConfig: config });+ },+ getConfigSchema() {+ return ULTRA_SCHEMA;+ },+ validateConfig(config) {+ return validateUltraConfig(config);+ },+};diff --git a/open-sse/services/compression/engines/index.ts b/open-sse/services/compression/engines/index.tsnew file mode 100644index 0000000000..07094ee9ac--- /dev/null+++ b/open-sse/services/compression/engines/index.ts@@ -0,0 +1,14 @@+import { registerCompressionEngine, getCompressionEngine } from "./registry.ts";+import { aggressiveEngine, cavemanEngine, liteEngine, ultraEngine } from "./cavemanAdapter.ts";+import { rtkEngine } from "./rtk/index.ts";++let registered = false;++export function registerBuiltinCompressionEngines(): void {+ const engines = [liteEngine, cavemanEngine, aggressiveEngine, ultraEngine, rtkEngine];+ if (registered && engines.every((engine) => getCompressionEngine(engine.id))) return;+ for (const engine of engines) {+ if (!getCompressionEngine(engine.id)) registerCompressionEngine(engine);+ }+ registered = true;+}diff --git a/open-sse/services/compression/engines/registry.ts b/open-sse/services/compression/engines/registry.tsnew file mode 100644index 0000000000..85d6a50cdd--- /dev/null+++ b/open-sse/services/compression/engines/registry.ts@@ -0,0 +1,87 @@+import type { CompressionEngine, EngineRegistryEntry, EngineValidationResult } from "./types.ts";++const ENGINES = new Map<string, EngineRegistryEntry>();++function assertValidEngine(engine: CompressionEngine): void {+ if (+ !engine?.id ||+ typeof engine.apply !== "function" ||+ typeof engine.compress !== "function" ||+ typeof engine.getConfigSchema !== "function" ||+ typeof engine.validateConfig !== "function"+ ) {+ throw new Error("Invalid compression engine registration");+ }+}++export function registerEngine(+ engine: CompressionEngine,+ defaultConfig: Record<string, unknown> = {}+): void {+ assertValidEngine(engine);+ const validation = engine.validateConfig(defaultConfig);+ if (!validation.valid) {+ throw new Error(`Invalid default config for ${engine.id}: ${validation.errors.join("; ")}`);+ }+ ENGINES.set(engine.id, {+ engine,+ enabled: true,+ config: { ...defaultConfig },+ });+}++export function registerCompressionEngine(engine: CompressionEngine): void {+ registerEngine(engine);+}++export function unregisterCompressionEngine(id: string): boolean {+ return ENGINES.delete(id);+}++export function getEngine(id: string): CompressionEngine | null {+ return ENGINES.get(id)?.engine ?? null;+}++export function getCompressionEngine(id: string): CompressionEngine | null {+ return getEngine(id);+}++export function getEngineEntry(id: string): EngineRegistryEntry | null {+ return ENGINES.get(id) ?? null;+}++export function listEngines(): EngineRegistryEntry[] {+ return Array.from(ENGINES.values());+}++export function listCompressionEngines(): CompressionEngine[] {+ return listEngines().map((entry) => entry.engine);+}++export function listEnabledEngines(): EngineRegistryEntry[] {+ return listEngines().filter((entry) => entry.enabled);+}++export function setEngineEnabled(id: string, enabled: boolean): boolean {+ const entry = ENGINES.get(id);+ if (!entry) return false;+ entry.enabled = enabled;+ return true;+}++export function updateEngineConfig(+ id: string,+ config: Record<string, unknown>+): EngineValidationResult {+ const entry = ENGINES.get(id);+ if (!entry) return { valid: false, errors: [`Unknown compression engine: ${id}`] };+ const nextConfig = { ...entry.config, ...config };+ const validation = entry.engine.validateConfig(nextConfig);+ if (!validation.valid) return validation;+ entry.config = nextConfig;+ return { valid: true, errors: [] };+}++export function clearCompressionEngineRegistry(): void {+ ENGINES.clear();+}diff --git a/open-sse/services/compression/engines/rtk/codeStripper.ts b/open-sse/services/compression/engines/rtk/codeStripper.tsnew file mode 100644index 0000000000..27c3512910--- /dev/null+++ b/open-sse/services/compression/engines/rtk/codeStripper.ts@@ -0,0 +1,128 @@+export type CodeLanguage =+ | "javascript"+ | "typescript"+ | "python"+ | "rust"+ | "go"+ | "ruby"+ | "java"+ | "unknown";++export interface CodeStripperOptions {+ removeComments?: boolean;+ removeEmptyLines?: boolean;+ collapseWhitespace?: boolean;+ preserveDocstrings?: boolean;+}++const LANGUAGE_ALIASES: Record<string, CodeLanguage> = {+ js: "javascript",+ jsx: "javascript",+ javascript: "javascript",+ ts: "typescript",+ tsx: "typescript",+ typescript: "typescript",+ py: "python",+ python: "python",+ rs: "rust",+ rust: "rust",+ go: "go",+ rb: "ruby",+ ruby: "ruby",+ java: "java",+};++export function normalizeCodeLanguage(language?: string | null): CodeLanguage {+ if (!language) return "unknown";+ return LANGUAGE_ALIASES[language.trim().toLowerCase()] ?? "unknown";+}++export function detectCodeLanguage(text: string): CodeLanguage {+ if (/\b(?:interface|type)\s+\w+\s*=|:\s*(?:string|number|boolean)\b/.test(text)) {+ return "typescript";+ }+ if (/\b(?:const|let|function|import|export)\b|=>/.test(text)) return "javascript";+ if (/\bdef\s+\w+\(|\bimport\s+\w+|print\(/.test(text)) return "python";+ if (/\bfn\s+\w+\(|\blet\s+mut\b|println!\(/.test(text)) return "rust";+ if (/\bfunc\s+\w+\(|package\s+\w+/.test(text)) return "go";+ if (/\bclass\s+\w+|System\.out\.println/.test(text)) return "java";+ if (/\bdef\s+\w+|puts\s+|end\s*$/.test(text)) return "ruby";+ return "unknown";+}++function removeSlashComments(text: string): string {+ return text+ .replace(/\/\*[\s\S]*?\*\//g, "")+ .replace(/^\s*\/\/.*$/gm, "")+ .replace(/\s+\/\/\s.*$/gm, "");+}++function removeHashComments(text: string): string {+ return text.replace(/^\s*#.*$/gm, "").replace(/\s+#\s.*$/gm, "");+}++function stripByLanguage(+ text: string,+ language: CodeLanguage,+ options: Required<CodeStripperOptions>+): string {+ if (!options.removeComments) return text;++ if (language === "javascript" || language === "typescript" || language === "rust") {+ return removeSlashComments(text);+ }+ if (language === "go" || language === "java") return removeSlashComments(text);+ if (language === "python") {+ const withoutDocstrings = options.preserveDocstrings+ ? text+ : text.replace(/("""[\s\S]*?"""|'''[\s\S]*?''')/g, "");+ return removeHashComments(withoutDocstrings);+ }+ if (language === "ruby") {+ return removeHashComments(text.replace(/^=begin[\s\S]*?^=end/gm, ""));+ }+ return text;+}++export function stripCode(+ text: string,+ language: CodeLanguage = "unknown",+ options: CodeStripperOptions = {}+): {+ text: string;+ strippedLines: number;+ language: CodeLanguage;+} {+ const resolvedLanguage = language === "unknown" ? detectCodeLanguage(text) : language;+ const opts: Required<CodeStripperOptions> = {+ removeComments: options.removeComments !== false,+ removeEmptyLines: options.removeEmptyLines !== false,+ collapseWhitespace: options.collapseWhitespace !== false,+ preserveDocstrings: options.preserveDocstrings === true,+ };+ const originalLines = text.split(/\r?\n/).length;+ let result = stripByLanguage(text, resolvedLanguage, opts);++ if (opts.removeEmptyLines) result = result.replace(/^\s*$(?:\r?\n)?/gm, "");+ if (opts.collapseWhitespace) {+ result = result+ .split(/\r?\n/)+ .map((line) => line.replace(/[ \t]+$/g, ""))+ .join("\n");+ }++ result = result.trim();+ const strippedLines = Math.max(0, originalLines - (result ? result.split(/\r?\n/).length : 0));+ return { text: result, strippedLines, language: resolvedLanguage };+}++export function stripCodeComments(+ text: string,+ language = "typescript"+): {+ text: string;+ stripped: boolean;+} {+ const result = stripCode(text, normalizeCodeLanguage(language));+ return { text: result.text, stripped: result.strippedLines > 0 || result.text !== text };+}diff --git a/open-sse/services/compression/engines/rtk/commandDetector.ts b/open-sse/services/compression/engines/rtk/commandDetector.tsnew file mode 100644index 0000000000..31806c65b7--- /dev/null+++ b/open-sse/services/compression/engines/rtk/commandDetector.ts@@ -0,0 +1,465 @@+export interface CommandDetectionResult {+ type: string;+ command: string | null;+ confidence: number;+ category:+ | "git"+ | "test"+ | "build"+ | "shell"+ | "docker"+ | "package"+ | "infra"+ | "cloud"+ | "generic";+ matchedPatterns: string[];+}++type Detector = {+ type: string;+ category: CommandDetectionResult["category"];+ commandPatterns: RegExp[];+ contentPatterns: RegExp[];+};++const COMMAND_PREFIXES = [+ "git",+ "make",+ "terraform",+ "tofu",+ "opentofu",+ "systemctl",+ "npm",+ "pnpm",+ "yarn",+ "vitest",+ "jest",+ "pytest",+ "python",+ "go",+ "cargo",+ "tsc",+ "eslint",+ "webpack",+ "vite",+ "biome",+ "prettier",+ "turbo",+ "nx",+ "playwright",+ "ruff",+ "mypy",+ "pip",+ "uv",+ "poetry",+ "golangci-lint",+ "bundle",+ "rubocop",+ "docker",+ "aws",+ "gcloud",+ "ssh",+ "rsync",+ "curl",+ "wget",+ "ls",+ "find",+ "grep",+ "rg",+ "ag",+ "ps",+ "df",+ "du",+];++const COMMAND_PREFIX_PATTERN = new RegExp(`^(?:${COMMAND_PREFIXES.join("|")})\\b`);++const DETECTORS: Detector[] = [+ {+ type: "git-status",+ category: "git",+ commandPatterns: [/^git\s+status\b/i],+ contentPatterns: [+ /^On branch /m,+ /^Changes (?:not staged|to be committed)/m,+ /^Untracked files:/m,+ ],+ },+ {+ type: "git-branch",+ category: "git",+ commandPatterns: [/^git\s+branch\b/i, /^git\s+checkout\b/i, /^git\s+switch\b/i],+ contentPatterns: [/^\*\s+\S+/m, /Switched to (?:a new )?branch/i, /Already on ['"][^'"]+['"]/i],+ },+ {+ type: "git-diff",+ category: "git",+ commandPatterns: [/^git\s+diff\b/i, /^git\s+show\b/i],+ contentPatterns: [/^diff --git /m, /^@@\s+-\d+,\d+\s+\+\d+,\d+\s+@@/m],+ },+ {+ type: "git-log",+ category: "git",+ commandPatterns: [/^git\s+log\b/i],+ contentPatterns: [/^commit [0-9a-f]{7,40}/m, /^Author: /m],+ },+ {+ type: "make",+ category: "build",+ commandPatterns: [/^make\b/i],+ contentPatterns: [/^make\[\d+\]: (?:Entering|Leaving) directory/m, /make: \*\*\* /],+ },+ {+ type: "terraform-plan",+ category: "infra",+ commandPatterns: [/^terraform\s+plan\b/i],+ contentPatterns: [/Terraform will perform the following actions:/, /Plan: \d+ to add/i],+ },+ {+ type: "tofu-plan",+ category: "infra",+ commandPatterns: [/^(?:tofu|opentofu)\s+plan\b/i],+ contentPatterns: [/OpenTofu will perform the following actions:/, /Plan: \d+ to add/i],+ },+ {+ type: "systemctl-status",+ category: "infra",+ commandPatterns: [/^systemctl\s+status\b/i],+ contentPatterns: [/^\s*Loaded:\s+/m, /^\s*Active:\s+/m, /^●\s+\S+\.service/m],+ },+ {+ type: "test-vitest",+ category: "test",+ commandPatterns: [/^vitest\b/i, /^npm\s+(?:run\s+)?test:vitest\b/i],+ contentPatterns: [/\bvitest\b/i, /^ ✓ /m, /^ ❯ /m, /Test Files\s+\d+\s+(?:passed|failed)/i],+ },+ {+ type: "test-jest",+ category: "test",+ commandPatterns: [/^jest\b/i, /^npm\s+(?:run\s+)?test\b/i],+ contentPatterns: [/Test Suites:\s+\d+/i, /Tests:\s+\d+/i, /^PASS\s+/m, /^FAIL\s+/m],+ },+ {+ type: "test-pytest",+ category: "test",+ commandPatterns: [/^pytest\b/i, /^python\s+-m\s+pytest\b/i],+ contentPatterns: [/=+\s+(?:\d+\s+)?(?:passed|failed|errors?)/i, /^E\s+/m, /^FAILED /m],+ },+ {+ type: "test-cargo",+ category: "test",+ commandPatterns: [/^cargo\s+test\b/i, /^cargo\s+nextest\b/i],+ contentPatterns: [+ /^running \d+ tests?/m,+ /^test\s+[\w:.-]+\s+\.\.\.\s+(?:ok|FAILED|ignored)/m,+ /test result:\s+(?:ok|FAILED)/i,+ ],+ },+ {+ type: "test-go",+ category: "test",+ commandPatterns: [/^go\s+test\b/i],+ contentPatterns: [/^(?:ok|FAIL)\s+[\w./-]+\s+[\d.]+s/m, /^--- FAIL: /m, /^panic: /m],+ },+ {+ type: "build-typescript",+ category: "build",+ commandPatterns: [/^tsc\b/i, /^npm\s+run\s+typecheck\b/i],+ contentPatterns: [/TS\d{4}:/, /error TS\d{4}/i],+ },+ {+ type: "build-eslint",+ category: "build",+ commandPatterns: [/^eslint\b/i, /^npm\s+run\s+lint\b/i],+ contentPatterns: [/\s+\d+:\d+\s+(?:error|warning)\s+/, /✖\s+\d+\s+problems?/],+ },+ {+ type: "build-webpack",+ category: "build",+ commandPatterns: [/^webpack\b/i, /^npx\s+webpack\b/i, /^npm\s+run\s+build:webpack\b/i],+ contentPatterns: [+ /webpack\s+\d/i,+ /compiled (?:successfully|with \d+ errors?)/i,+ /asset .+\.js/i,+ ],+ },+ {+ type: "build-vite",+ category: "build",+ commandPatterns: [/^vite\s+build\b/i, /^npm\s+run\s+build\b/i, /^pnpm\s+build\b/i],+ contentPatterns: [/vite v[\d.]+/i, /✓ built in/i, /transforming \(\d+\)/i],+ },+ {+ type: "biome",+ category: "build",+ commandPatterns: [/^biome\b/i, /^npx\s+biome\b/i],+ contentPatterns: [/lint\/[A-Za-z0-9/.-]+/, /Checked \d+ files? in/i],+ },+ {+ type: "prettier",+ category: "build",+ commandPatterns: [/^prettier\b/i, /^npx\s+prettier\b/i],+ contentPatterns: [/^Checking formatting\.\.\./m, /Code style issues found/i],+ },+ {+ type: "turbo",+ category: "build",+ commandPatterns: [/^turbo\b/i, /^npx\s+turbo\b/i],+ contentPatterns: [/^• Packages in scope:/m, /^Tasks:\s+\d+\s+successful/m],+ },+ {+ type: "nx",+ category: "build",+ commandPatterns: [/^nx\b/i, /^npx\s+nx\b/i],+ contentPatterns: [/^NX\s+/m, /^> nx run /m],+ },+ {+ type: "playwright",+ category: "test",+ commandPatterns: [/^playwright\s+test\b/i, /^npx\s+playwright\s+test\b/i],+ contentPatterns: [/Running \d+ tests? using \d+ workers?/i, /^\s+\d+ failed/m],+ },+ {+ type: "npm-install",+ category: "package",+ commandPatterns: [/^(?:npm|pnpm|yarn)\s+(?:install|add|update)\b/i],+ contentPatterns: [+ /added \d+ packages/i,+ /packages are looking for funding/i,+ /audited \d+ packages/i,+ ],+ },+ {+ type: "npm-audit",+ category: "package",+ commandPatterns: [/^(?:npm|pnpm|yarn)\s+audit\b/i],+ contentPatterns: [/found \d+ vulnerabilities/i, /\b(?:low|moderate|high|critical)\b/i],+ },+ {+ type: "ruff",+ category: "build",+ commandPatterns: [/^ruff\b/i, /^uv\s+run\s+ruff\b/i],+ contentPatterns: [/^[\w./-]+\.py:\d+:\d+:\s+[A-Z]\d+/m, /Found \d+ errors?\./i],+ },+ {+ type: "mypy",+ category: "build",+ commandPatterns: [/^mypy\b/i, /^python\s+-m\s+mypy\b/i],+ contentPatterns: [/^[\w./-]+\.py:\d+:\s+error:/m, /Found \d+ errors? in \d+ files?/i],+ },+ {+ type: "pip",+ category: "package",+ commandPatterns: [/^pip\s+(?:install|download|uninstall)\b/i, /^python\s+-m\s+pip\b/i],+ contentPatterns: [/^Collecting /m, /^Successfully installed /m],+ },+ {+ type: "uv-sync",+ category: "package",+ commandPatterns: [/^uv\s+sync\b/i, /^uv\s+pip\s+install\b/i],+ contentPatterns: [/^Resolved \d+ packages?/m, /^Installed \d+ packages?/m],+ },+ {+ type: "poetry-install",+ category: "package",+ commandPatterns: [/^poetry\s+install\b/i],+ contentPatterns: [/^Installing dependencies from lock file/m, /^Package operations:/m],+ },+ {+ type: "golangci-lint",+ category: "build",+ commandPatterns: [/^golangci-lint\b/i],+ contentPatterns: [/^[\w./-]+\.go:\d+:\d+:/m, /^\d+ issues?:/m],+ },+ {+ type: "bundle-install",+ category: "package",+ commandPatterns: [/^bundle\s+install\b/i],+ contentPatterns: [/^Fetching gem metadata from /m, /^Bundle complete!/m],+ },+ {+ type: "rubocop",+ category: "build",+ commandPatterns: [/^rubocop\b/i, /^bundle\s+exec\s+rubocop\b/i],+ contentPatterns: [/^Inspecting \d+ files/m, /^[\w./-]+\.rb:\d+:\d+:\s+[A-Z]:/m],+ },+ {+ type: "docker-ps",+ category: "docker",+ commandPatterns: [/^docker\s+ps\b/i],+ contentPatterns: [/^CONTAINER ID\s+IMAGE\s+COMMAND/m],+ },+ {+ type: "docker-logs",+ category: "docker",+ commandPatterns: [/^docker\s+logs\b/i, /^docker\s+compose\s+logs\b/i],+ contentPatterns: [+ /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/m,+ /\b(?:ERROR|WARN|INFO)\b/,+ /^Attaching to /m,+ ],+ },+ {+ type: "aws",+ category: "cloud",+ commandPatterns: [/^aws\b/i],+ contentPatterns: [/An error occurred \([A-Za-z0-9]+\) when calling/, /^(?:upload|download): /m],+ },+ {+ type: "gcloud",+ category: "cloud",+ commandPatterns: [/^gcloud\b/i],+ contentPatterns: [/^ERROR: \(gcloud\./m, /^Updated property \[/m],+ },+ {+ type: "ssh",+ category: "cloud",+ commandPatterns: [/^ssh\b/i],+ contentPatterns: [+ /Permission denied \(/,+ /Host key verification failed/,+ /Connection timed out/,+ ],+ },+ {+ type: "rsync",+ category: "cloud",+ commandPatterns: [/^rsync\b/i],+ contentPatterns: [/^sending incremental file list/m, /^rsync error:/m],+ },+ {+ type: "curl",+ category: "cloud",+ commandPatterns: [/^curl\b/i],+ contentPatterns: [/curl: \(\d+\)/, /^HTTP\/\d(?:\.\d)? \d{3}/m],+ },+ {+ type: "wget",+ category: "cloud",+ commandPatterns: [/^wget\b/i],+ contentPatterns: [/^--\d{4}-\d{2}-\d{2}/m, /^ERROR \d{3}:/m],+ },+ {+ type: "json-output",+ category: "generic",+ commandPatterns: [/^jq\b/i, /^cat\s+.*\.json\b/i],+ contentPatterns: [/^\s*[\[{][\s\S]*[\]}]\s*$/],+ },+ {+ type: "shell-ls",+ category: "shell",+ commandPatterns: [/^ls(?:\s+-[A-Za-z]+)?\b/i],+ contentPatterns: [/^total \d+/m, /^\S+\s+\S+\s+\d+\s+\w+\s+\d{1,2}\s+/m],+ },+ {+ type: "shell-find",+ category: "shell",+ commandPatterns: [/^find\b/i],+ contentPatterns: [/^(?:\.{1,2}|\/|[\w.-]+\/).+/m],+ },+ {+ type: "shell-grep",+ category: "shell",+ commandPatterns: [/^(?:grep|rg|ag)\b/i],+ contentPatterns: [+ /^[\w./-]+\.(?:ts|tsx|js|jsx|py|go|rs|java|rb|md|json|ya?ml|txt):\d*:/m,+ /^[\w./-]+\/[\w./-]+:\d*:/m,+ ],+ },+ {+ type: "shell-ps",+ category: "shell",+ commandPatterns: [/^ps\b/i],+ contentPatterns: [/^(?:USER\s+PID|\s*PID\s+)/m],+ },+ {+ type: "shell-df",+ category: "shell",+ commandPatterns: [/^df\b/i],+ contentPatterns: [/^Filesystem\s+.*Use%/m],+ },+ {+ type: "shell-du",+ category: "shell",+ commandPatterns: [/^du\b/i],+ contentPatterns: [/^\d+(?:\.\d+)?[KMGTP]?\s+\S+/m],+ },+ {+ type: "error-stacktrace",+ category: "generic",+ commandPatterns: [],+ contentPatterns: [+ /Traceback \(most recent call last\):/,+ /^\s+at\s+\S+\s+\(.+:\d+:\d+\)/m,+ /^panic: /m,+ /^thread '[^']+' panicked at/m,+ ],+ },+ {+ type: "generic-error",+ category: "generic",+ commandPatterns: [],+ contentPatterns: [/Error:/, /Exception:/, /Traceback \(most recent call last\):/],+ },+];++export function detectCommandFromText(text: string): string | null {+ const firstLines = text.split(/\r?\n/).slice(0, 4);+ for (const line of firstLines) {+ const trimmed = line.trim().replace(/^\$\s+/, "");+ if (!trimmed) continue;+ if (COMMAND_PREFIX_PATTERN.test(trimmed)) {+ return trimmed;+ }+ }+ return null;+}++export function detectCommandType(text: string, command?: string | null): CommandDetectionResult {+ const detectedCommand = command?.trim() || detectCommandFromText(text);+ let best: CommandDetectionResult | null = null;++ for (const detector of DETECTORS) {+ const matchedPatterns: string[] = [];+ const commandMatched =+ Boolean(detectedCommand) &&+ detector.commandPatterns.some((pattern) => {+ const matched = pattern.test(detectedCommand ?? "");+ if (matched) matchedPatterns.push(pattern.source);+ return matched;+ });+ const contentMatches = detector.contentPatterns.filter((pattern) => {+ const matched = pattern.test(text);+ if (matched) matchedPatterns.push(pattern.source);+ return matched;+ }).length;+ if (!commandMatched && contentMatches === 0) continue;++ const confidence = Math.min(1, (commandMatched ? 0.55 : 0) + contentMatches * 0.25);+ if (!best || confidence > best.confidence) {+ best = {+ type: detector.type,+ command: detectedCommand,+ confidence,+ category: detector.category,+ matchedPatterns,+ };+ }+ }++ return (+ best ?? {+ type: "unknown",+ command: detectedCommand,+ confidence: detectedCommand ? 0.35 : 0.1,+ category: "generic",+ matchedPatterns: [],+ }+ );+}++export function listCommandTypes(): string[] {+ return DETECTORS.map((detector) => detector.type);+}++export const detectCommandOutput = detectCommandType;diff --git a/open-sse/services/compression/engines/rtk/deduplicator.ts b/open-sse/services/compression/engines/rtk/deduplicator.tsnew file mode 100644index 0000000000..ea473097fd--- /dev/null+++ b/open-sse/services/compression/engines/rtk/deduplicator.ts@@ -0,0 +1,37 @@+export interface DeduplicateOptions {+ threshold?: number;+}++export function deduplicateRepeatedLines(+ text: string,+ options: DeduplicateOptions = {}+): {+ text: string;+ collapsed: number;+} {+ const threshold = Math.max(2, Math.floor(options.threshold ?? 3));+ const lines = text.split(/\r?\n/);+ const output: string[] = [];+ let collapsed = 0;++ for (let index = 0; index < lines.length; index++) {+ const line = lines[index];+ let runLength = 1;+ while (index + runLength < lines.length && lines[index + runLength] === line) {+ runLength++;+ }++ if (line.trim() && runLength >= threshold) {+ output.push(line);+ output.push(`[line repeated ${runLength - 1}x]`);+ output.push(`[rtk:dropped ${runLength - 1} repeated lines]`);+ collapsed += runLength - 1;+ index += runLength - 1;+ continue;+ }++ output.push(line);+ }++ return { text: output.join("\n"), collapsed };+}diff --git a/open-sse/services/compression/engines/rtk/filterLoader.ts b/open-sse/services/compression/engines/rtk/filterLoader.tsnew file mode 100644index 0000000000..8c776a9b85--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filterLoader.ts@@ -0,0 +1,220 @@+import fs from "node:fs";+import { fileURLToPath } from "node:url";+import path from "node:path";+import os from "node:os";+import crypto from "node:crypto";+import { detectCommandType } from "./commandDetector.ts";+import { validateRtkFilter, type RtkFilterDefinition } from "./filterSchema.ts";++let cache: RtkFilterDefinition[] | null = null;+let cacheKey: string | null = null;+let diagnostics: RtkFilterLoadDiagnostic[] = [];++export interface RtkFilterLoadDiagnostic {+ source: "project" | "global" | "builtin";+ path?: string;+ level: "warning" | "error";+ message: string;+}++interface FilterSource {+ source: "project" | "global" | "builtin";+ path: string;+ trusted: boolean;+}++interface RtkFilterLoadOptions {+ refresh?: boolean;+ customFiltersEnabled?: boolean;+ trustProjectFilters?: boolean;+}++function getFiltersDir(): string {+ const moduleDir = path.dirname(fileURLToPath(import.meta.url));+ const candidates = [+ path.join(moduleDir, "filters"),+ path.join(moduleDir, "..", "services", "compression", "engines", "rtk", "filters"),+ path.join(process.cwd(), "open-sse", "services", "compression", "engines", "rtk", "filters"),+ path.join(+ process.cwd(),+ "app",+ "open-sse",+ "services",+ "compression",+ "engines",+ "rtk",+ "filters"+ ),+ ];+ return (+ candidates.find((candidate, index) => {+ return candidates.indexOf(candidate) === index && fs.existsSync(candidate);+ }) ?? candidates[0]+ );+}++function getDataDir(): string {+ return process.env.DATA_DIR || path.join(os.homedir(), ".omniroute");+}++function sha256(value: string): string {+ return crypto.createHash("sha256").update(value).digest("hex");+}++function projectFiltersTrusted(+ filtersPath: string,+ trustProjectFilters = false+): boolean | "changed" {+ if (trustProjectFilters) return true;+ if (process.env.OMNIROUTE_RTK_TRUST_PROJECT_FILTERS === "1") return true;+ const trustPath = path.join(path.dirname(filtersPath), "trust.json");+ if (!fs.existsSync(trustPath)) return false;+ try {+ const filtersHash = sha256(fs.readFileSync(filtersPath, "utf8"));+ const trust = JSON.parse(fs.readFileSync(trustPath, "utf8")) as Record<string, unknown>;+ const trustedHash =+ typeof trust.filtersSha256 === "string"+ ? trust.filtersSha256+ : typeof trust.trustedFiltersSha256 === "string"+ ? trust.trustedFiltersSha256+ : null;+ if (!trustedHash) return false;+ return trustedHash === filtersHash ? true : "changed";+ } catch {+ return false;+ }+}++function collectFilterSources(options: RtkFilterLoadOptions = {}): FilterSource[] {+ const sources: FilterSource[] = [];+ const projectPath = path.join(process.cwd(), ".rtk", "filters.json");+ if (options.customFiltersEnabled !== false && fs.existsSync(projectPath)) {+ const trusted = projectFiltersTrusted(projectPath, options.trustProjectFilters === true);+ if (trusted === true) {+ sources.push({ source: "project", path: projectPath, trusted: true });+ } else {+ diagnostics.push({+ source: "project",+ path: projectPath,+ level: "warning",+ message:+ trusted === "changed"+ ? "Project RTK filters changed after trust and were skipped"+ : "Project RTK filters are untrusted and were skipped",+ });+ }+ }++ const globalPath = path.join(getDataDir(), "rtk", "filters.json");+ if (options.customFiltersEnabled !== false && fs.existsSync(globalPath)) {+ sources.push({ source: "global", path: globalPath, trusted: true });+ }++ const builtinDir = getFiltersDir();+ if (fs.existsSync(builtinDir)) {+ for (const file of fs+ .readdirSync(builtinDir)+ .filter((entry) => entry.endsWith(".json"))+ .sort()) {+ sources.push({+ source: "builtin",+ path: path.join(builtinDir, file),+ trusted: true,+ });+ }+ }++ return sources;+}++function parseFilterFile(source: FilterSource): RtkFilterDefinition[] {+ try {+ const parsed = JSON.parse(fs.readFileSync(source.path, "utf8"));+ const entries = Array.isArray(parsed) ? parsed : [parsed];+ return entries.map(validateRtkFilter);+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ if (source.source === "builtin") {+ throw new Error(`Invalid RTK filter ${path.basename(source.path)}: ${message}`);+ }+ diagnostics.push({+ source: source.source,+ path: source.path,+ level: "warning",+ message: `Invalid custom RTK filter skipped: ${message}`,+ });+ return [];+ }+}++export function loadRtkFilters(options: RtkFilterLoadOptions = {}): RtkFilterDefinition[] {+ const currentCacheKey = [+ process.cwd(),+ getDataDir(),+ options.customFiltersEnabled === false ? "builtin-only" : "custom",+ options.trustProjectFilters === true ? "trusted-project" : "trust-file",+ process.env.OMNIROUTE_RTK_TRUST_PROJECT_FILTERS === "1" ? "env-trust" : "env-normal",+ ].join("|");+ if (cache && cacheKey === currentCacheKey && !options.refresh) return cache;+ diagnostics = [];+ const filters: RtkFilterDefinition[] = [];+ for (const source of collectFilterSources(options)) {+ filters.push(...parseFilterFile(source));+ }++ const sorted = filters.sort((a, b) => b.priority - a.priority || a.id.localeCompare(b.id));+ cache = sorted;+ cacheKey = currentCacheKey;+ return sorted;+}++export function getRtkFilterLoadDiagnostics(): RtkFilterLoadDiagnostic[] {+ loadRtkFilters();+ return diagnostics.map((entry) => ({ ...entry }));+}++export function getRtkFilterCatalog(): Array<+ Pick<+ RtkFilterDefinition,+ "id" | "name" | "description" | "commandTypes" | "category" | "priority"+ >+> {+ return loadRtkFilters().map((filter) => ({+ id: filter.id,+ name: filter.name,+ description: filter.description,+ commandTypes: filter.commandTypes,+ category: filter.category,+ priority: filter.priority,+ }));+}++export function matchRtkFilter(+ text: string,+ command?: string | null,+ options: RtkFilterLoadOptions = {}+): RtkFilterDefinition | null {+ const detection = detectCommandType(text, command);+ const detectedCommand = detection.command ?? command ?? "";+ const matchesPattern = (pattern: string, value: string): boolean => {+ try {+ return new RegExp(pattern, "im").test(value);+ } catch {+ return false;+ }+ };+ const filters = loadRtkFilters(options);+ return (+ filters.find((filter) => filter.commandTypes.includes(detection.type)) ??+ filters.find(+ (filter) =>+ detectedCommand &&+ filter.commandPatterns.some((pattern) => matchesPattern(pattern, detectedCommand))+ ) ??+ filters.find((filter) =>+ filter.matchPatterns.some((pattern) => matchesPattern(pattern, text))+ ) ??+ filters.find((filter) => filter.commandTypes.includes("generic-output")) ??+ null+ );+}diff --git a/open-sse/services/compression/engines/rtk/filterSchema.ts b/open-sse/services/compression/engines/rtk/filterSchema.tsnew file mode 100644index 0000000000..bb5f67d974--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filterSchema.ts@@ -0,0 +1,182 @@+import { z } from "zod";++const rtkFilterCategorySchema = z.enum([+ "git",+ "test",+ "build",+ "shell",+ "docker",+ "package",+ "infra",+ "cloud",+ "generic",+]);++const rtkReplaceRuleSchema = z+ .object({+ pattern: z.string().min(1),+ replacement: z.string(),+ })+ .strict();++const rtkMatchOutputRuleSchema = z+ .object({+ pattern: z.string().min(1),+ message: z.string(),+ unless: z.string().min(1).optional(),+ })+ .strict();++const rtkInlineTestSchema = z+ .object({+ name: z.string().min(1),+ input: z.string(),+ expected: z.string(),+ command: z.string().optional(),+ })+ .strict();++const rtkFilterMatchSchema = z+ .object({+ commands: z.array(z.string().min(1)).default([]),+ patterns: z.array(z.string().min(1)).default([]),+ outputTypes: z.array(z.string().min(1)).default([]),+ })+ .strict();++const rtkFilterRulesSchema = z+ .object({+ stripAnsi: z.boolean().default(false),+ replace: z.array(rtkReplaceRuleSchema).default([]),+ matchOutput: z.array(rtkMatchOutputRuleSchema).default([]),+ includePatterns: z.array(z.string()).default([]),+ dropPatterns: z.array(z.string()).default([]),+ collapsePatterns: z.array(z.string()).default([]),+ deduplicate: z.boolean().default(false),+ truncateLineAt: z.number().int().min(0).default(0),+ maxLines: z.number().int().min(0).default(0),+ headLines: z.number().int().min(0).default(20),+ tailLines: z.number().int().min(0).default(20),+ onEmpty: z.string().default(""),+ filterStderr: z.boolean().default(false),+ })+ .strict();++const rtkFilterPreserveSchema = z+ .object({+ errorPatterns: z.array(z.string()).default([]),+ summaryPatterns: z.array(z.string()).default([]),+ })+ .strict();++export const rtkFilterPackSchema = z+ .object({+ id: z.string().min(1),+ label: z.string().min(1),+ description: z.string().default(""),+ category: rtkFilterCategorySchema,+ priority: z.number().int().min(0).max(100).default(50),+ match: rtkFilterMatchSchema,+ rules: rtkFilterRulesSchema.default({}),+ preserve: rtkFilterPreserveSchema.default({}),+ tests: z.array(rtkInlineTestSchema).default([]),+ })+ .strict();++const legacyRtkFilterSchema = z+ .object({+ id: z.string().min(1),+ name: z.string().min(1),+ description: z.string().default(""),+ commandTypes: z.array(z.string().min(1)).min(1),+ category: rtkFilterCategorySchema,+ priority: z.number().int().min(0).max(100).default(50),+ stripPatterns: z.array(z.string()).default([]),+ keepPatterns: z.array(z.string()).default([]),+ priorityPatterns: z.array(z.string()).default([]),+ collapsePatterns: z.array(z.string()).default([]),+ stripAnsi: z.boolean().default(false),+ replace: z.array(rtkReplaceRuleSchema).default([]),+ matchOutput: z.array(rtkMatchOutputRuleSchema).default([]),+ truncateLineAt: z.number().int().min(0).default(0),+ onEmpty: z.string().default(""),+ filterStderr: z.boolean().default(false),+ maxLines: z.number().int().min(0).default(0),+ preserveHead: z.number().int().min(0).default(20),+ preserveTail: z.number().int().min(0).default(20),+ tests: z.array(rtkInlineTestSchema).default([]),+ })+ .strict();++export const rtkFilterSchema = z.union([rtkFilterPackSchema, legacyRtkFilterSchema]);++export type RtkFilterPack = z.infer<typeof rtkFilterPackSchema>;++export interface RtkFilterDefinition {+ id: string;+ name: string;+ description: string;+ commandTypes: string[];+ commandPatterns: string[];+ matchPatterns: string[];+ category: z.infer<typeof rtkFilterCategorySchema>;+ priority: number;+ stripPatterns: string[];+ keepPatterns: string[];+ priorityPatterns: string[];+ collapsePatterns: string[];+ stripAnsi: boolean;+ replace: Array<{ pattern: string; replacement: string }>;+ matchOutput: Array<{ pattern: string; message: string; unless?: string }>;+ truncateLineAt: number;+ onEmpty: string;+ filterStderr: boolean;+ deduplicate: boolean;+ maxLines: number;+ preserveHead: number;+ preserveTail: number;+ tests: Array<{ name: string; input: string; expected: string; command?: string }>;+}++function isCanonicalFilter(value: z.infer<typeof rtkFilterSchema>): value is RtkFilterPack {+ return "label" in value && "match" in value && "rules" in value;+}++export function validateRtkFilter(value: unknown): RtkFilterDefinition {+ const parsed = rtkFilterSchema.parse(value);+ if (!isCanonicalFilter(parsed)) {+ return {+ ...parsed,+ commandPatterns: [],+ matchPatterns: [],+ deduplicate: parsed.collapsePatterns.length > 0,+ };+ }++ const preservePatterns = [...parsed.preserve.errorPatterns, ...parsed.preserve.summaryPatterns];+ return {+ id: parsed.id,+ name: parsed.label,+ description: parsed.description,+ commandTypes: parsed.match.outputTypes,+ commandPatterns: parsed.match.commands,+ matchPatterns: parsed.match.patterns,+ category: parsed.category,+ priority: parsed.priority,+ stripPatterns: parsed.rules.dropPatterns,+ keepPatterns: parsed.rules.includePatterns,+ priorityPatterns: preservePatterns,+ collapsePatterns: parsed.rules.collapsePatterns,+ stripAnsi: parsed.rules.stripAnsi,+ replace: parsed.rules.replace,+ matchOutput: parsed.rules.matchOutput,+ truncateLineAt: parsed.rules.truncateLineAt,+ onEmpty: parsed.rules.onEmpty,+ filterStderr: parsed.rules.filterStderr,+ deduplicate: parsed.rules.deduplicate,+ maxLines: parsed.rules.maxLines,+ preserveHead: parsed.rules.headLines,+ preserveTail: parsed.rules.tailLines,+ tests: parsed.tests,+ };+}diff --git a/open-sse/services/compression/engines/rtk/filters/aws.json b/open-sse/services/compression/engines/rtk/filters/aws.jsonnew file mode 100644index 0000000000..7a3f82d887--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/aws.json@@ -0,0 +1,34 @@+{+ "id": "aws",+ "label": "AWS CLI",+ "description": "Compress AWS CLI progress output while preserving errors and completed transfers.",+ "category": "cloud",+ "priority": 76,+ "match": {+ "outputTypes": ["aws"],+ "commands": ["^aws\\b"],+ "patterns": ["An error occurred \\([A-Za-z0-9]+\\) when calling", "^(?:upload|download): "]+ },+ "rules": {+ "stripAnsi": true,+ "dropPatterns": ["^Completed \\d", "^\\s*$"],+ "includePatterns": ["^(?:upload|download): ", "An error occurred \\("],+ "collapsePatterns": [],+ "deduplicate": true,+ "maxLines": 120,+ "headLines": 30,+ "tailLines": 40+ },+ "preserve": {+ "errorPatterns": ["An error occurred", "AccessDenied", "Throttling", "ValidationError"],+ "summaryPatterns": ["^(?:upload|download): "]+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "aws s3 cp",+ "input": "Completed 1.0 MiB/2.0 MiB\nupload: ./app.log to s3://bucket/app.log\nAn error occurred (AccessDenied) when calling the PutObject operation: denied\n",+ "expected": "upload: ./app.log to s3://bucket/app.log\nAn error occurred (AccessDenied) when calling the PutObject operation: denied"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/biome.json b/open-sse/services/compression/engines/rtk/filters/biome.jsonnew file mode 100644index 0000000000..d0c7564b39--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/biome.json@@ -0,0 +1,35 @@+{+ "id": "biome",+ "label": "Biome",+ "description": "Compact Biome lint/format output.",+ "category": "build",+ "priority": 80,+ "match": {+ "outputTypes": [],+ "commands": ["^biome\\b", "^npx\\s+biome\\b"],+ "patterns": ["Checked \\d+ files?", "biome"]+ },+ "rules": {+ "stripAnsi": true,+ "dropPatterns": ["^\\s*$", "^Checked \\d+ files? in"],+ "includePatterns": ["error", "warning", "✖", "Checked", "Fixed", "^\\s*>"],+ "collapsePatterns": [],+ "deduplicate": true,+ "maxLines": 100,+ "headLines": 25,+ "tailLines": 40,+ "onEmpty": "biome: ok"+ },+ "preserve": {+ "errorPatterns": ["error", "✖"],+ "summaryPatterns": ["Checked", "Fixed"]+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "biome",+ "input": "Checked 10 files in 20ms\nerror lint/a.ts:1:1 boom\nFixed 1 file\n",+ "expected": "error lint/a.ts:1:1 boom\nFixed 1 file"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/build-eslint.json b/open-sse/services/compression/engines/rtk/filters/build-eslint.jsonnew file mode 100644index 0000000000..610e616363--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/build-eslint.json@@ -0,0 +1,37 @@+{+ "id": "build-eslint",+ "label": "ESLint",+ "description": "Keep lint diagnostics and problem summary.",+ "category": "build",+ "priority": 88,+ "match": {+ "outputTypes": ["build-eslint"],+ "commands": ["^(?:eslint|npm\\s+run\\s+lint)\\b"],+ "patterns": ["\\s+\\d+:\\d+\\s+(?:error|warning)\\s+", "✖\\s+\\d+\\s+problems?"]+ },+ "rules": {+ "includePatterns": [+ "\\s+\\d+:\\d+\\s+(error|warning)\\s+",+ "✖\\s+\\d+\\s+problems?",+ "^/.*\\.(ts|tsx|js|jsx)$"+ ],+ "dropPatterns": ["^\\s*$"],+ "collapsePatterns": [],+ "deduplicate": false,+ "maxLines": 120,+ "headLines": 20,+ "tailLines": 40+ },+ "preserve": {+ "errorPatterns": ["error", "warning", "problems?"],+ "summaryPatterns": []+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "(?:eslint|npm run lint)",+ "input": "/repo/a.ts\n 1:1 error boom no-boom\n✖ 1 problem (1 error, 0 warnings)\n",+ "expected": "/repo/a.ts\n 1:1 error boom no-boom\n✖ 1 problem (1 error, 0 warnings)"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/build-typescript.json b/open-sse/services/compression/engines/rtk/filters/build-typescript.jsonnew file mode 100644index 0000000000..5ef3e314c5--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/build-typescript.json@@ -0,0 +1,33 @@+{+ "id": "build-typescript",+ "label": "TypeScript",+ "description": "Keep TypeScript diagnostics and file locations.",+ "category": "build",+ "priority": 93,+ "match": {+ "outputTypes": ["build-typescript"],+ "commands": ["^(?:tsc|npm\\s+run\\s+typecheck)\\b"],+ "patterns": ["TS\\d{4}:", "error TS\\d{4}"]+ },+ "rules": {+ "includePatterns": ["TS\\d{4}:", "error TS\\d{4}", "^Found \\d+ errors?"],+ "dropPatterns": ["^\\s*$"],+ "collapsePatterns": [],+ "deduplicate": false,+ "maxLines": 120,+ "headLines": 20,+ "tailLines": 40+ },+ "preserve": {+ "errorPatterns": ["TS\\d{4}", "Found \\d+"],+ "summaryPatterns": []+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "(?:tsc|npm run typecheck)",+ "input": "src/a.ts:1:1 - error TS2322: Type string is not assignable\nFound 1 error.\n",+ "expected": "src/a.ts:1:1 - error TS2322: Type string is not assignable\nFound 1 error."+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/build-vite.json b/open-sse/services/compression/engines/rtk/filters/build-vite.jsonnew file mode 100644index 0000000000..7e81845b81--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/build-vite.json@@ -0,0 +1,41 @@+{+ "id": "build-vite",+ "label": "Vite Build",+ "description": "Keep Vite errors and final build summary.",+ "category": "build",+ "priority": 83,+ "match": {+ "outputTypes": ["build-vite"],+ "commands": ["^vite\\s+build\\b", "^npm\\s+run\\s+build\\b", "^pnpm\\s+build\\b"],+ "patterns": ["vite v[\\d.]+", "✓ built in"]+ },+ "rules": {+ "stripAnsi": true,+ "matchOutput": [+ {+ "pattern": "✓ built in",+ "message": "vite: build ok",+ "unless": "error|failed"+ }+ ],+ "includePatterns": ["error", "failed", "✓ built in", "dist/", "rendering chunks"],+ "dropPatterns": ["^transforming ", "^✓ \\d+ modules transformed", "^\\s*$"],+ "collapsePatterns": ["^dist/"],+ "deduplicate": true,+ "maxLines": 120,+ "headLines": 30,+ "tailLines": 45+ },+ "preserve": {+ "errorPatterns": ["error", "failed"],+ "summaryPatterns": ["✓ built in"]+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "vite build",+ "input": "vite v5.0.0 building for production...\n✓ 10 modules transformed.\n✓ built in 100ms\n",+ "expected": "vite: build ok"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/build-webpack.json b/open-sse/services/compression/engines/rtk/filters/build-webpack.jsonnew file mode 100644index 0000000000..55e1eb845b--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/build-webpack.json@@ -0,0 +1,34 @@+{+ "id": "build-webpack",+ "label": "Webpack Build",+ "description": "Keep webpack errors/warnings and compilation summary.",+ "category": "build",+ "priority": 84,+ "match": {+ "outputTypes": ["build-webpack"],+ "commands": ["^webpack\\b", "^npx\\s+webpack\\b"],+ "patterns": ["webpack \\d", "compiled (?:successfully|with)"]+ },+ "rules": {+ "stripAnsi": true,+ "includePatterns": ["ERROR in", "WARNING in", "compiled ", "asset ", "Entrypoint"],+ "dropPatterns": ["^\\s*$", "^cacheable modules"],+ "collapsePatterns": ["^asset "],+ "deduplicate": true,+ "maxLines": 140,+ "headLines": 35,+ "tailLines": 50+ },+ "preserve": {+ "errorPatterns": ["ERROR in"],+ "summaryPatterns": ["compiled "]+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "webpack",+ "input": "asset main.js 10 KiB\nERROR in ./src/a.ts\ncompiled with 1 error\n",+ "expected": "asset main.js 10 KiB\nERROR in ./src/a.ts\ncompiled with 1 error"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/bundle-install.json b/open-sse/services/compression/engines/rtk/filters/bundle-install.jsonnew file mode 100644index 0000000000..7b126ae117--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/bundle-install.json@@ -0,0 +1,35 @@+{+ "id": "bundle-install",+ "label": "Bundle Install",+ "description": "Strip bundle install noise and keep final status.",+ "category": "package",+ "priority": 70,+ "match": {+ "outputTypes": [],+ "commands": ["^bundle\\s+install\\b"],+ "patterns": ["Bundle complete", "Using "]+ },+ "rules": {+ "stripAnsi": true,+ "dropPatterns": ["^Using ", "^Fetching ", "^Installing ", "^\\s*$"],+ "includePatterns": ["Bundle complete", "Your bundle is complete", "ERROR", "Gem::"],+ "collapsePatterns": [],+ "deduplicate": true,+ "maxLines": 100,+ "headLines": 25,+ "tailLines": 35,+ "onEmpty": "bundle: ok"+ },+ "preserve": {+ "errorPatterns": ["ERROR", "Gem::"],+ "summaryPatterns": ["Bundle complete", "Your bundle is complete"]+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "bundle install",+ "input": "Using rake 13.0\nInstalling pg 1.5\nBundle complete! 4 Gemfile dependencies\n",+ "expected": "Bundle complete! 4 Gemfile dependencies"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/curl.json b/open-sse/services/compression/engines/rtk/filters/curl.jsonnew file mode 100644index 0000000000..936f290706--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/curl.json@@ -0,0 +1,34 @@+{+ "id": "curl",+ "label": "curl",+ "description": "Remove curl progress noise and keep HTTP status/errors.",+ "category": "cloud",+ "priority": 70,+ "match": {+ "outputTypes": ["curl"],+ "commands": ["^curl\\b"],+ "patterns": ["curl: \\(\\d+\\)", "^HTTP/\\d(?:\\.\\d)? \\d{3}"]+ },+ "rules": {+ "stripAnsi": true,+ "dropPatterns": ["^\\s*% Total\\s+% Received", "^\\s*\\d+\\s+\\d+", "^\\s*$"],+ "includePatterns": ["^HTTP/\\d(?:\\.\\d)? \\d{3}", "^curl: \\(\\d+\\)", "^[<{]"],+ "collapsePatterns": [],+ "deduplicate": true,+ "maxLines": 100,+ "headLines": 30,+ "tailLines": 40+ },+ "preserve": {+ "errorPatterns": ["curl: \\(\\d+\\)", "^HTTP/\\d(?:\\.\\d)? [45]\\d\\d"],+ "summaryPatterns": ["^HTTP/\\d(?:\\.\\d)? \\d{3}"]+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "curl -i",+ "input": "% Total % Received\n 0 0 0 0\nHTTP/1.1 500 Internal Server Error\ncurl: (22) The requested URL returned error: 500\n",+ "expected": "HTTP/1.1 500 Internal Server Error\ncurl: (22) The requested URL returned error: 500"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/df.json b/open-sse/services/compression/engines/rtk/filters/df.jsonnew file mode 100644index 0000000000..5be798a273--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/df.json@@ -0,0 +1,34 @@+{+ "id": "df",+ "label": "df",+ "description": "Keep filesystem usage table headers and mounted filesystems.",+ "category": "shell",+ "priority": 67,+ "match": {+ "outputTypes": ["shell-df"],+ "commands": ["^df\\b"],+ "patterns": ["^Filesystem\\s+.*Use%"]+ },+ "rules": {+ "stripAnsi": true,+ "dropPatterns": ["^tmpfs\\s", "^udev\\s", "^\\s*$"],+ "includePatterns": ["^Filesystem\\s+", "^/dev/\\S+\\s+"],+ "collapsePatterns": [],+ "deduplicate": false,+ "maxLines": 80,+ "headLines": 25,+ "tailLines": 25+ },+ "preserve": {+ "errorPatterns": ["No such file", "Permission denied"],+ "summaryPatterns": ["Use%", "^/dev/"]+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "df -h",+ "input": "Filesystem Size Used Avail Use% Mounted on\nudev 2.0G 0 2.0G 0% /dev\n/dev/sda1 50G 45G 5.0G 90% /\n",+ "expected": "Filesystem Size Used Avail Use% Mounted on\n/dev/sda1 50G 45G 5.0G 90% /"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/docker-logs.json b/open-sse/services/compression/engines/rtk/filters/docker-logs.jsonnew file mode 100644index 0000000000..10b5d11f43--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/docker-logs.json@@ -0,0 +1,42 @@+{+ "id": "docker-logs",+ "label": "Docker Logs",+ "description": "Keep warnings/errors and recent Docker log context.",+ "category": "docker",+ "priority": 84,+ "match": {+ "outputTypes": ["docker-logs"],+ "commands": ["^docker\\s+(?:compose\\s+)?logs\\b"],+ "patterns": ["\\b(?:ERROR|WARN|INFO)\\b", "^Attaching to "]+ },+ "rules": {+ "stripAnsi": true,+ "dropPatterns": ["^Attaching to ", "^\\s*$"],+ "includePatterns": [+ "ERROR",+ "WARN",+ "Exception",+ "Traceback",+ "failed",+ "listening",+ "started"+ ],+ "collapsePatterns": ["INFO"],+ "deduplicate": true,+ "maxLines": 120,+ "headLines": 20,+ "tailLines": 60+ },+ "preserve": {+ "errorPatterns": ["ERROR", "Exception", "failed"],+ "summaryPatterns": ["started", "listening"]+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "docker (?:compose )?logs",+ "input": "Attaching to api\nINFO started\nINFO started\nERROR failed to connect\n",+ "expected": "INFO started\nERROR failed to connect"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/docker-ps.json b/open-sse/services/compression/engines/rtk/filters/docker-ps.jsonnew file mode 100644index 0000000000..b7dc4efee0--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/docker-ps.json@@ -0,0 +1,33 @@+{+ "id": "docker-ps",+ "label": "Docker PS",+ "description": "Keep docker container table header and rows under a fixed cap.",+ "category": "docker",+ "priority": 60,+ "match": {+ "outputTypes": ["docker-ps"],+ "commands": ["^docker\\s+ps\\b"],+ "patterns": ["^CONTAINER ID\\s+IMAGE\\s+COMMAND"]+ },+ "rules": {+ "includePatterns": [],+ "dropPatterns": ["^\\s*$"],+ "collapsePatterns": [],+ "deduplicate": false,+ "maxLines": 80,+ "headLines": 30,+ "tailLines": 20+ },+ "preserve": {+ "errorPatterns": ["^CONTAINER ID"],+ "summaryPatterns": []+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "docker ps",+ "input": "CONTAINER ID IMAGE COMMAND\nabc123 node \"npm start\"\n",+ "expected": "CONTAINER ID IMAGE COMMAND\nabc123 node \"npm start\""+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/du.json b/open-sse/services/compression/engines/rtk/filters/du.jsonnew file mode 100644index 0000000000..54cca64e89--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/du.json@@ -0,0 +1,33 @@+{+ "id": "du",+ "label": "du",+ "description": "Summarize disk-usage listings while preserving largest entries.",+ "category": "shell",+ "priority": 66,+ "match": {+ "outputTypes": ["shell-du"],+ "commands": ["^du\\b"],+ "patterns": ["^\\d+(?:\\.\\d+)?[KMGTP]?\\s+\\S+"]+ },+ "rules": {+ "stripAnsi": true,+ "dropPatterns": ["^\\s*$"],+ "collapsePatterns": [],+ "deduplicate": true,+ "maxLines": 80,+ "headLines": 20,+ "tailLines": 30+ },+ "preserve": {+ "errorPatterns": ["Permission denied", "No such file"],+ "summaryPatterns": ["\\s+\\.$", "\\s+total$"]+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "du -sh *",+ "input": "4.0K package.json\n120M node_modules\n120M node_modules\n",+ "expected": "4.0K package.json\n120M node_modules\n120M node_modules"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/error-stacktrace.json b/open-sse/services/compression/engines/rtk/filters/error-stacktrace.jsonnew file mode 100644index 0000000000..0d5fd3b8bf--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/error-stacktrace.json@@ -0,0 +1,41 @@+{+ "id": "error-stacktrace",+ "label": "Error Stacktrace",+ "description": "Collapse stack traces while preserving error text and top frames.",+ "category": "generic",+ "priority": 70,+ "match": {+ "outputTypes": ["error-stacktrace"],+ "commands": [],+ "patterns": ["Traceback \\(most recent call last\\):", "^\\s+at\\s+", "^panic: "]+ },+ "rules": {+ "stripAnsi": true,+ "includePatterns": [+ "Error:",+ "Exception:",+ "Traceback",+ "^\\s+at ",+ "^panic:",+ "^thread ",+ "^Caused by:"+ ],+ "dropPatterns": ["^\\s*$"],+ "collapsePatterns": ["^\\s+at "],+ "deduplicate": true,+ "maxLines": 80,+ "headLines": 25,+ "tailLines": 30+ },+ "preserve": {+ "errorPatterns": ["Error:", "Exception:", "^panic:", "Traceback"],+ "summaryPatterns": ["Caused by:"]+ },+ "tests": [+ {+ "name": "inline sample",+ "input": "Error: boom\n at fn (/repo/a.ts:1:1)\n at fn (/repo/a.ts:1:1)\nCaused by: bad\n",+ "expected": "Error: boom\n at fn (/repo/a.ts:1:1)\nCaused by: bad"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/gcloud.json b/open-sse/services/compression/engines/rtk/filters/gcloud.jsonnew file mode 100644index 0000000000..19c5dd09a9--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/gcloud.json@@ -0,0 +1,34 @@+{+ "id": "gcloud",+ "label": "gcloud",+ "description": "Compress Google Cloud CLI output and preserve actionable errors.",+ "category": "cloud",+ "priority": 75,+ "match": {+ "outputTypes": ["gcloud"],+ "commands": ["^gcloud\\b"],+ "patterns": ["^ERROR: \\(gcloud\\.", "^Updated property \\["]+ },+ "rules": {+ "stripAnsi": true,+ "dropPatterns": ["^Waiting for operation", "^\\s*$"],+ "includePatterns": ["^ERROR: \\(gcloud\\.", "^Updated property \\[", "^Created \\["],+ "collapsePatterns": [],+ "deduplicate": true,+ "maxLines": 120,+ "headLines": 30,+ "tailLines": 40+ },+ "preserve": {+ "errorPatterns": ["^ERROR: \\(gcloud\\.", "PERMISSION_DENIED", "NOT_FOUND"],+ "summaryPatterns": ["^Updated property \\[", "^Created \\["]+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "gcloud run deploy",+ "input": "Waiting for operation [deploy]\nUpdated property [core/project].\nERROR: (gcloud.run.deploy) PERMISSION_DENIED: denied\n",+ "expected": "Updated property [core/project].\nERROR: (gcloud.run.deploy) PERMISSION_DENIED: denied"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/generic-output.json b/open-sse/services/compression/engines/rtk/filters/generic-output.jsonnew file mode 100644index 0000000000..da93022888--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/generic-output.json@@ -0,0 +1,32 @@+{+ "id": "generic-output",+ "label": "Generic Output",+ "description": "Fallback filter for unknown command output.",+ "category": "generic",+ "priority": 10,+ "match": {+ "outputTypes": ["generic-output", "generic-error"],+ "commands": [],+ "patterns": ["Error:", "Exception:", "Traceback \\(most recent call last\\):"]+ },+ "rules": {+ "includePatterns": [],+ "dropPatterns": ["^\\s*$"],+ "collapsePatterns": [],+ "deduplicate": false,+ "maxLines": 120,+ "headLines": 35,+ "tailLines": 45+ },+ "preserve": {+ "errorPatterns": ["error", "failed", "exception", "traceback"],+ "summaryPatterns": []+ },+ "tests": [+ {+ "name": "inline sample",+ "input": "\nError: boom\n\nTraceback (most recent call last):\n file.py:1\n",+ "expected": "Error: boom\nTraceback (most recent call last):\n file.py:1"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/git-branch.json b/open-sse/services/compression/engines/rtk/filters/git-branch.jsonnew file mode 100644index 0000000000..b333932f08--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/git-branch.json@@ -0,0 +1,45 @@+{+ "id": "git-branch",+ "label": "Git Branch",+ "description": "Compact git branch/switch output.",+ "category": "git",+ "priority": 94,+ "match": {+ "outputTypes": ["git-branch"],+ "commands": ["^git\\s+(?:branch|checkout|switch)\\b"],+ "patterns": ["^\\*\\s+\\S+", "Switched to (?:a new )?branch", "Already on"]+ },+ "rules": {+ "stripAnsi": true,+ "matchOutput": [+ {+ "pattern": "Switched to (?:a new )?branch",+ "message": "git: switched branch",+ "unless": "error|failed"+ },+ {+ "pattern": "Already on",+ "message": "git: already on branch"+ }+ ],+ "includePatterns": ["^\\*\\s+\\S+", "^\\s{2}\\S+", "Switched to", "Already on"],+ "dropPatterns": ["^\\s*$"],+ "collapsePatterns": [],+ "deduplicate": false,+ "maxLines": 60,+ "headLines": 20,+ "tailLines": 20+ },+ "preserve": {+ "errorPatterns": ["error", "failed"],+ "summaryPatterns": ["Switched to", "Already on"]+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "git (?:branch|checkout|switch)",+ "input": " main\n* feature/rtk\n release\n",+ "expected": " main\n* feature/rtk\n release"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/git-diff.json b/open-sse/services/compression/engines/rtk/filters/git-diff.jsonnew file mode 100644index 0000000000..a97df1fbac--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/git-diff.json@@ -0,0 +1,33 @@+{+ "id": "git-diff",+ "label": "Git Diff",+ "description": "Drop low-signal diff metadata while preserving files, hunks, and changed lines.",+ "category": "git",+ "priority": 94,+ "match": {+ "outputTypes": ["git-diff"],+ "commands": ["^git\\s+(?:diff|show)\\b"],+ "patterns": ["^diff --git ", "^@@\\s+-\\d+,\\d+\\s+\\+\\d+,\\d+\\s+@@"]+ },+ "rules": {+ "includePatterns": [],+ "dropPatterns": ["^index [0-9a-f]+\\.\\.[0-9a-f]+.*$", "^--- a/", "^\\+\\+\\+ b/"],+ "collapsePatterns": ["^\\s*$"],+ "deduplicate": true,+ "maxLines": 180,+ "headLines": 40,+ "tailLines": 50+ },+ "preserve": {+ "errorPatterns": ["^diff --git ", "^@@ ", "^[+-](?![+-]{2})"],+ "summaryPatterns": []+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "git (?:diff|show)",+ "input": "diff --git a/a.ts b/a.ts\n@@ -1,2 +1,2 @@\n-console.log(\"old\")\n+console.log(\"new\")\n",+ "expected": "diff --git a/a.ts b/a.ts\n@@ -1,2 +1,2 @@\n-console.log(\"old\")\n+console.log(\"new\")\n"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/git-log.json b/open-sse/services/compression/engines/rtk/filters/git-log.jsonnew file mode 100644index 0000000000..4a54160537--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/git-log.json@@ -0,0 +1,33 @@+{+ "id": "git-log",+ "label": "Git Log",+ "description": "Keep commit identifiers and subjects from verbose logs.",+ "category": "git",+ "priority": 70,+ "match": {+ "outputTypes": ["git-log"],+ "commands": ["^git\\s+log\\b"],+ "patterns": ["^commit [0-9a-f]{7,40}", "^Author: "]+ },+ "rules": {+ "includePatterns": ["^commit [0-9a-f]{7,40}", "^\\s{4}\\S"],+ "dropPatterns": ["^Author: ", "^Date: ", "^\\s*$"],+ "collapsePatterns": [],+ "deduplicate": false,+ "maxLines": 120,+ "headLines": 40,+ "tailLines": 20+ },+ "preserve": {+ "errorPatterns": ["^commit "],+ "summaryPatterns": []+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "git log",+ "input": "commit abcdef1234567890\nAuthor: Dev <[email protected]>\nDate: today\n\n feat: add rtk\n",+ "expected": "commit abcdef1234567890\n feat: add rtk"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/git-status.json b/open-sse/services/compression/engines/rtk/filters/git-status.jsonnew file mode 100644index 0000000000..d2d21a66f5--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/git-status.json@@ -0,0 +1,40 @@+{+ "id": "git-status",+ "label": "Git Status",+ "description": "Keep branch, staged/unstaged headings, and changed file lines.",+ "category": "git",+ "priority": 95,+ "match": {+ "outputTypes": ["git-status"],+ "commands": ["^git\\s+status\\b"],+ "patterns": ["^On branch ", "^Changes (?:not staged|to be committed)", "^Untracked files:"]+ },+ "rules": {+ "includePatterns": [+ "^On branch ",+ "^Your branch ",+ "^Changes ",+ "^Untracked files:",+ "^\\s*(modified|new file|deleted|renamed|both modified):",+ "^\\s*[MADRCU?!]{1,2}\\s+"+ ],+ "dropPatterns": ["^\\s*$", "^\\s*\\(use .*\\)$"],+ "collapsePatterns": [],+ "deduplicate": false,+ "maxLines": 80,+ "headLines": 12,+ "tailLines": 20+ },+ "preserve": {+ "errorPatterns": ["^Changes ", "^Untracked files:"],+ "summaryPatterns": []+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "git status",+ "input": "On branch main\nChanges not staged for commit:\n (use \"git add\" to update)\n\tmodified: src/app.ts\nnothing added to commit\n",+ "expected": "On branch main\nChanges not staged for commit:\n\tmodified: src/app.ts"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/golangci-lint.json b/open-sse/services/compression/engines/rtk/filters/golangci-lint.jsonnew file mode 100644index 0000000000..8bffbee1af--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/golangci-lint.json@@ -0,0 +1,34 @@+{+ "id": "golangci-lint",+ "label": "golangci-lint",+ "description": "Keep golangci-lint findings and summary.",+ "category": "build",+ "priority": 82,+ "match": {+ "outputTypes": [],+ "commands": ["^golangci-lint\\b"],+ "patterns": ["issues:", "level=error", ":\\d+:\\d+:"]+ },+ "rules": {+ "stripAnsi": true,+ "includePatterns": [":\\d+:\\d+:", "level=error", "issues:", "Error:"],+ "dropPatterns": ["^\\s*$"],+ "collapsePatterns": [],+ "deduplicate": true,+ "maxLines": 140,+ "headLines": 35,+ "tailLines": 50+ },+ "preserve": {+ "errorPatterns": ["level=error", "Error:"],+ "summaryPatterns": ["issues:"]+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "golangci-lint",+ "input": "main.go:1:1: issue text\nlevel=error msg=\"runner failed\"\nissues: 1\n",+ "expected": "main.go:1:1: issue text\nlevel=error msg=\"runner failed\"\nissues: 1"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/json-output.json b/open-sse/services/compression/engines/rtk/filters/json-output.jsonnew file mode 100644index 0000000000..1ab8769266--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/json-output.json@@ -0,0 +1,40 @@+{+ "id": "json-output",+ "label": "JSON Output",+ "description": "Keep actionable JSON status, error and message fields while preserving structure.",+ "category": "generic",+ "priority": 70,+ "match": {+ "outputTypes": ["json-output"],+ "commands": ["^(?:jq\\b|cat\\s+.*\\.json\\b)"],+ "patterns": ["^\\s*[\\[{][\\s\\S]*[\\]}]\\s*$"]+ },+ "rules": {+ "includePatterns": [+ "\"status\"\\s*:",+ "\"error\"\\s*:",+ "\"errors\"\\s*:",+ "\"code\"\\s*:",+ "\"message\"\\s*:",+ "[{}\\[\\],]"+ ],+ "dropPatterns": ["^\\s*$"],+ "collapsePatterns": [],+ "deduplicate": false,+ "maxLines": 120,+ "headLines": 20,+ "tailLines": 30+ },+ "preserve": {+ "errorPatterns": ["\"error\"", "\"errors\"", "\"message\""],+ "summaryPatterns": []+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "(?:jq\\b|cat .*\\.json\\b)",+ "input": "{\n \"status\": \"ok\",\n \"items\": [1,2,3]\n}\n",+ "expected": "{\n \"status\": \"ok\",\n \"items\": [1,2,3]\n}"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/make.json b/open-sse/services/compression/engines/rtk/filters/make.jsonnew file mode 100644index 0000000000..7b9d3a6b24--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/make.json@@ -0,0 +1,38 @@+{+ "id": "make",+ "label": "Make",+ "description": "Strip make directory chatter and empty lines.",+ "category": "build",+ "priority": 78,+ "match": {+ "outputTypes": [],+ "commands": ["^make\\b"],+ "patterns": ["make\\[\\d+\\]: (?:Entering|Leaving) directory"]+ },+ "rules": {+ "stripAnsi": true,+ "dropPatterns": [+ "^make\\[\\d+\\]: (?:Entering|Leaving) directory",+ "^\\s*$",+ "Nothing to be done for"+ ],+ "collapsePatterns": ["^(?:cc|gcc|clang|g\\+\\+)\\b"],+ "deduplicate": true,+ "maxLines": 120,+ "headLines": 30,+ "tailLines": 40,+ "onEmpty": "make: ok"+ },+ "preserve": {+ "errorPatterns": ["error:", "failed", "\\*\\*\\*"],+ "summaryPatterns": ["built", "linking"]+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "make",+ "input": "make[1]: Entering directory '/repo'\ngcc -O2 foo.c\nmake[1]: Leaving directory '/repo'\n",+ "expected": "gcc -O2 foo.c"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/mypy.json b/open-sse/services/compression/engines/rtk/filters/mypy.jsonnew file mode 100644index 0000000000..861bbe3e9b--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/mypy.json@@ -0,0 +1,34 @@+{+ "id": "mypy",+ "label": "mypy",+ "description": "Keep mypy errors grouped by file and final summary.",+ "category": "build",+ "priority": 82,+ "match": {+ "outputTypes": [],+ "commands": ["^mypy\\b", "^python\\s+-m\\s+mypy\\b"],+ "patterns": [": error:", "Found \\d+ errors? in"]+ },+ "rules": {+ "stripAnsi": true,+ "includePatterns": [": error:", ": note:", "Found \\d+ errors?", "Success: no issues found"],+ "dropPatterns": ["^\\s*$"],+ "collapsePatterns": [],+ "deduplicate": true,+ "maxLines": 160,+ "headLines": 40,+ "tailLines": 60+ },+ "preserve": {+ "errorPatterns": [": error:", "Found \\d+ errors?"],+ "summaryPatterns": ["Success:", "Found \\d+"]+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "mypy",+ "input": "app.py:1: error: Incompatible types\nFound 1 error in 1 file\n",+ "expected": "app.py:1: error: Incompatible types\nFound 1 error in 1 file"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/npm-audit.json b/open-sse/services/compression/engines/rtk/filters/npm-audit.jsonnew file mode 100644index 0000000000..19fa224a38--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/npm-audit.json@@ -0,0 +1,43 @@+{+ "id": "npm-audit",+ "label": "npm audit",+ "description": "Keep vulnerability counts and remediation hints.",+ "category": "package",+ "priority": 84,+ "match": {+ "outputTypes": ["npm-audit"],+ "commands": ["^(?:npm|pnpm|yarn)\\s+audit\\b"],+ "patterns": ["found \\d+ vulnerabilities", "\\bcritical\\b"]+ },+ "rules": {+ "stripAnsi": true,+ "includePatterns": [+ "vulnerabilities",+ "critical",+ "high",+ "moderate",+ "low",+ "fix available",+ "npm audit fix",+ "No vulnerabilities"+ ],+ "dropPatterns": ["^\\s*$", "^# npm audit report"],+ "collapsePatterns": [],+ "deduplicate": true,+ "maxLines": 120,+ "headLines": 30,+ "tailLines": 45+ },+ "preserve": {+ "errorPatterns": ["critical", "high"],+ "summaryPatterns": ["vulnerabilities", "No vulnerabilities"]+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "(?:npm|pnpm|yarn) audit",+ "input": "# npm audit report\ncritical vulnerability in foo\nfound 1 vulnerabilities\nnpm audit fix\n",+ "expected": "critical vulnerability in foo\nfound 1 vulnerabilities\nnpm audit fix"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/npm-install.json b/open-sse/services/compression/engines/rtk/filters/npm-install.jsonnew file mode 100644index 0000000000..df001e67b2--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/npm-install.json@@ -0,0 +1,41 @@+{+ "id": "npm-install",+ "label": "Package Install",+ "description": "Keep install summaries, warnings and audit results.",+ "category": "package",+ "priority": 65,+ "match": {+ "outputTypes": ["npm-install"],+ "commands": ["^(?:npm|pnpm|yarn)\\s+(?:install|add|update)\\b"],+ "patterns": ["added \\d+ packages", "packages are looking for funding", "audited \\d+ packages"]+ },+ "rules": {+ "includePatterns": [+ "added \\d+ packages",+ "removed \\d+ packages",+ "changed \\d+ packages",+ "audited \\d+ packages",+ "vulnerabilities",+ "WARN",+ "ERR!"+ ],+ "dropPatterns": ["^\\s*$", "^\\s*\\|", "^Progress:"],+ "collapsePatterns": [],+ "deduplicate": false,+ "maxLines": 80,+ "headLines": 20,+ "tailLines": 30+ },+ "preserve": {+ "errorPatterns": ["WARN", "ERR", "vulnerabilities"],+ "summaryPatterns": []+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "(?:npm|pnpm|yarn) (?:install|add|update)",+ "input": "added 3 packages\npackages are looking for funding\naudited 3 packages\n",+ "expected": "added 3 packages\naudited 3 packages"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/nx.json b/open-sse/services/compression/engines/rtk/filters/nx.jsonnew file mode 100644index 0000000000..6973433228--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/nx.json@@ -0,0 +1,34 @@+{+ "id": "nx",+ "label": "Nx",+ "description": "Compact Nx task graph and output.",+ "category": "build",+ "priority": 76,+ "match": {+ "outputTypes": [],+ "commands": ["^nx\\b", "^npx\\s+nx\\b"],+ "patterns": ["NX ", "Successfully ran target"]+ },+ "rules": {+ "stripAnsi": true,+ "dropPatterns": ["^\\s*$", "^> nx run"],+ "includePatterns": ["NX ", "ERROR", "Failed", "Successfully ran", "Running target"],+ "collapsePatterns": [],+ "deduplicate": true,+ "maxLines": 120,+ "headLines": 25,+ "tailLines": 50+ },+ "preserve": {+ "errorPatterns": ["ERROR", "Failed"],+ "summaryPatterns": ["Successfully ran"]+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "nx",+ "input": "> nx run app:build\nNX Failed tasks:\nERROR boom\n",+ "expected": "NX Failed tasks:\nERROR boom"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/pip.json b/open-sse/services/compression/engines/rtk/filters/pip.jsonnew file mode 100644index 0000000000..91edf38ca3--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/pip.json@@ -0,0 +1,41 @@+{+ "id": "pip",+ "label": "pip",+ "description": "Strip pip install progress and keep install/failure summary.",+ "category": "package",+ "priority": 72,+ "match": {+ "outputTypes": [],+ "commands": ["^pip\\s+(?:install|sync|download)\\b", "^python\\s+-m\\s+pip\\s+install\\b"],+ "patterns": ["Successfully installed", "Requirement already satisfied"]+ },+ "rules": {+ "stripAnsi": true,+ "dropPatterns": [+ "^Collecting ",+ "^Downloading ",+ "^Installing collected packages:",+ "^Requirement already satisfied",+ "^\\s*$"+ ],+ "includePatterns": ["Successfully installed", "ERROR:", "WARNING:", "failed", "Could not find"],+ "collapsePatterns": [],+ "deduplicate": true,+ "maxLines": 100,+ "headLines": 25,+ "tailLines": 35,+ "onEmpty": "pip: ok"+ },+ "preserve": {+ "errorPatterns": ["ERROR:", "failed", "Could not find"],+ "summaryPatterns": ["Successfully installed"]+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "pip (?:install|sync|download)",+ "input": "Collecting requests\nDownloading requests.whl\nSuccessfully installed requests-2.0\n",+ "expected": "Successfully installed requests-2.0"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/playwright.json b/open-sse/services/compression/engines/rtk/filters/playwright.jsonnew file mode 100644index 0000000000..1899b6367c--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/playwright.json@@ -0,0 +1,42 @@+{+ "id": "playwright",+ "label": "Playwright",+ "description": "Keep failed specs, error context, and summary.",+ "category": "test",+ "priority": 86,+ "match": {+ "outputTypes": [],+ "commands": ["^playwright\\s+test\\b", "^npx\\s+playwright\\s+test\\b"],+ "patterns": ["Running \\d+ tests?", "Error Context:", "failed"]+ },+ "rules": {+ "stripAnsi": true,+ "dropPatterns": ["^\\s*$", "^Running \\d+ tests? using"],+ "includePatterns": [+ "✘",+ "Error:",+ "Error Context:",+ "failed",+ "passed",+ "Slow test file",+ "^\\s*\\d+\\)"+ ],+ "collapsePatterns": ["^\\s+at "],+ "deduplicate": true,+ "maxLines": 160,+ "headLines": 35,+ "tailLines": 60+ },+ "preserve": {+ "errorPatterns": ["Error:", "✘", "failed"],+ "summaryPatterns": ["passed", "failed"]+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "playwright test",+ "input": "Running 2 tests using 1 worker\n ✘ 1 login.spec.ts:3:1 › login\nError: expected visible\n 1 failed\n",+ "expected": " ✘ 1 login.spec.ts:3:1 › login\nError: expected visible\n 1 failed"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/poetry-install.json b/open-sse/services/compression/engines/rtk/filters/poetry-install.jsonnew file mode 100644index 0000000000..f40169365e--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/poetry-install.json@@ -0,0 +1,35 @@+{+ "id": "poetry-install",+ "label": "Poetry Install",+ "description": "Strip Poetry package operation noise.",+ "category": "package",+ "priority": 72,+ "match": {+ "outputTypes": [],+ "commands": ["^poetry\\s+(?:install|update)\\b"],+ "patterns": ["Package operations:", "Installing dependencies"]+ },+ "rules": {+ "stripAnsi": true,+ "dropPatterns": ["^ - Installing ", "^ - Updating ", "^Installing dependencies", "^\\s*$"],+ "includePatterns": ["Package operations:", "Writing lock file", "Error", "failed"],+ "collapsePatterns": [],+ "deduplicate": true,+ "maxLines": 100,+ "headLines": 25,+ "tailLines": 35,+ "onEmpty": "poetry: ok"+ },+ "preserve": {+ "errorPatterns": ["Error", "failed"],+ "summaryPatterns": ["Package operations:", "Writing lock file"]+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "poetry (?:install|update)",+ "input": "Installing dependencies\nPackage operations: 2 installs, 0 updates\n - Installing foo (1.0)\nWriting lock file\n",+ "expected": "Package operations: 2 installs, 0 updates\nWriting lock file"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/prettier.json b/open-sse/services/compression/engines/rtk/filters/prettier.jsonnew file mode 100644index 0000000000..0a1c894fc6--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/prettier.json@@ -0,0 +1,40 @@+{+ "id": "prettier",+ "label": "Prettier",+ "description": "Keep files that would be changed and final summary.",+ "category": "build",+ "priority": 79,+ "match": {+ "outputTypes": [],+ "commands": ["^prettier\\b", "^npx\\s+prettier\\b"],+ "patterns": ["\\[warn\\]", "All matched files use Prettier"]+ },+ "rules": {+ "stripAnsi": true,+ "matchOutput": [+ {+ "pattern": "All matched files use Prettier",+ "message": "prettier: ok"+ }+ ],+ "dropPatterns": ["^\\s*$"],+ "includePatterns": ["\\[warn\\]", "Code style issues", "All matched files"],+ "collapsePatterns": [],+ "deduplicate": true,+ "maxLines": 80,+ "headLines": 20,+ "tailLines": 30+ },+ "preserve": {+ "errorPatterns": ["\\[error\\]", "Code style issues"],+ "summaryPatterns": ["All matched files"]+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "prettier",+ "input": "[warn] src/a.ts\n[warn] Code style issues found in the above file. Forgot to run Prettier?\n",+ "expected": "[warn] src/a.ts\n[warn] Code style issues found in the above file. Forgot to run Prettier?"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/ps.json b/open-sse/services/compression/engines/rtk/filters/ps.jsonnew file mode 100644index 0000000000..843866d70e--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/ps.json@@ -0,0 +1,34 @@+{+ "id": "ps",+ "label": "ps",+ "description": "Keep process table headers and process rows, dropping empty noise.",+ "category": "shell",+ "priority": 68,+ "match": {+ "outputTypes": ["shell-ps"],+ "commands": ["^ps\\b"],+ "patterns": ["^(?:USER\\s+PID|\\s*PID\\s+)"]+ },+ "rules": {+ "stripAnsi": true,+ "dropPatterns": ["^\\s*$"],+ "includePatterns": ["^(?:USER\\s+PID|\\s*PID\\s+)", "^\\S+\\s+\\d+\\s+", "^\\s*\\d+\\s+"],+ "collapsePatterns": [],+ "deduplicate": false,+ "maxLines": 120,+ "headLines": 30,+ "tailLines": 50+ },+ "preserve": {+ "errorPatterns": ["defunct", "Permission denied"],+ "summaryPatterns": ["^(?:USER\\s+PID|\\s*PID\\s+)"]+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "ps aux",+ "input": "USER PID %CPU COMMAND\nroot 1 0.0 init\nnode 1234 5.0 node server.js\n",+ "expected": "USER PID %CPU COMMAND\nroot 1 0.0 init\nnode 1234 5.0 node server.js"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/rsync.json b/open-sse/services/compression/engines/rtk/filters/rsync.jsonnew file mode 100644index 0000000000..36ecd135bc--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/rsync.json@@ -0,0 +1,33 @@+{+ "id": "rsync",+ "label": "rsync",+ "description": "Drop rsync transfer chatter while preserving copied files and errors.",+ "category": "cloud",+ "priority": 73,+ "match": {+ "outputTypes": ["rsync"],+ "commands": ["^rsync\\b"],+ "patterns": ["^sending incremental file list", "^rsync error:"]+ },+ "rules": {+ "stripAnsi": true,+ "dropPatterns": ["^sending incremental file list", "^sent \\d", "^total size is", "^\\s*$"],+ "collapsePatterns": [],+ "deduplicate": true,+ "maxLines": 140,+ "headLines": 35,+ "tailLines": 50+ },+ "preserve": {+ "errorPatterns": ["^rsync error:", "Permission denied", "No such file"],+ "summaryPatterns": ["^sent \\d", "^total size is"]+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "rsync -av",+ "input": "sending incremental file list\napp.js\nsent 120 bytes received 20 bytes\nrsync error: some files could not be transferred (code 23)\n",+ "expected": "app.js\nrsync error: some files could not be transferred (code 23)"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/rubocop.json b/open-sse/services/compression/engines/rtk/filters/rubocop.jsonnew file mode 100644index 0000000000..da92cc4beb--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/rubocop.json@@ -0,0 +1,34 @@+{+ "id": "rubocop",+ "label": "RuboCop",+ "description": "Keep RuboCop offenses and final summary.",+ "category": "build",+ "priority": 74,+ "match": {+ "outputTypes": ["rubocop"],+ "commands": ["^rubocop\\b", "^bundle\\s+exec\\s+rubocop\\b"],+ "patterns": ["^Inspecting \\d+ files", "^\\S+\\.rb:\\d+:\\d+: [A-Z]:"]+ },+ "rules": {+ "stripAnsi": true,+ "dropPatterns": ["^Inspecting \\d+ files", "^\\.+$", "^\\s*$"],+ "includePatterns": ["^\\S+\\.rb:\\d+:\\d+: [A-Z]:", "^\\d+ files inspected"],+ "collapsePatterns": [],+ "deduplicate": true,+ "maxLines": 120,+ "headLines": 30,+ "tailLines": 45+ },+ "preserve": {+ "errorPatterns": [" [EF]: ", "Offenses:"],+ "summaryPatterns": ["^\\d+ files inspected"]+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "rubocop",+ "input": "Inspecting 2 files\n.C\napp/models/user.rb:12:3: C: Style/IfUnlessModifier: Favor modifier if usage.\n2 files inspected, 1 offense detected\n",+ "expected": "app/models/user.rb:12:3: C: Style/IfUnlessModifier: Favor modifier if usage.\n2 files inspected, 1 offense detected"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/ruff.json b/open-sse/services/compression/engines/rtk/filters/ruff.jsonnew file mode 100644index 0000000000..0e3d80d6ee--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/ruff.json@@ -0,0 +1,40 @@+{+ "id": "ruff",+ "label": "Ruff",+ "description": "Keep Ruff diagnostics and summary.",+ "category": "build",+ "priority": 82,+ "match": {+ "outputTypes": [],+ "commands": ["^ruff\\b", "^uv\\s+run\\s+ruff\\b"],+ "patterns": ["Found \\d+ errors?", "All checks passed"]+ },+ "rules": {+ "stripAnsi": true,+ "matchOutput": [+ {+ "pattern": "All checks passed",+ "message": "ruff: ok"+ }+ ],+ "dropPatterns": ["^\\s*$"],+ "includePatterns": ["^[A-Z]\\d{3}", "Found \\d+", "error:", "warning:", "-->"],+ "collapsePatterns": [],+ "deduplicate": true,+ "maxLines": 120,+ "headLines": 30,+ "tailLines": 40+ },+ "preserve": {+ "errorPatterns": ["^[A-Z]\\d{3}", "error:"],+ "summaryPatterns": ["Found \\d+", "All checks passed"]+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "ruff",+ "input": "F401 app.py:1:1 unused import\nFound 1 error.\n",+ "expected": "F401 app.py:1:1 unused import\nFound 1 error."+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/shell-find.json b/open-sse/services/compression/engines/rtk/filters/shell-find.jsonnew file mode 100644index 0000000000..e95ce818d9--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/shell-find.json@@ -0,0 +1,33 @@+{+ "id": "shell-find",+ "label": "find",+ "description": "Limit large find output while preserving head and tail.",+ "category": "shell",+ "priority": 80,+ "match": {+ "outputTypes": ["shell-find"],+ "commands": ["^find\\b"],+ "patterns": ["^(?:\\./|/|[A-Za-z0-9_.-]+/)"]+ },+ "rules": {+ "stripAnsi": true,+ "dropPatterns": ["^\\s*$"],+ "collapsePatterns": [],+ "deduplicate": true,+ "maxLines": 120,+ "headLines": 40,+ "tailLines": 40+ },+ "preserve": {+ "errorPatterns": ["Permission denied", "No such file"],+ "summaryPatterns": []+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "find",+ "input": "./src/a.ts\n./src/b.ts\n./node_modules/pkg/index.js\n",+ "expected": "./src/a.ts\n./src/b.ts\n./node_modules/pkg/index.js"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/shell-grep.json b/open-sse/services/compression/engines/rtk/filters/shell-grep.jsonnew file mode 100644index 0000000000..6429ff82f9--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/shell-grep.json@@ -0,0 +1,37 @@+{+ "id": "shell-grep",+ "label": "grep/rg",+ "description": "Deduplicate grep output while preserving matches.",+ "category": "shell",+ "priority": 82,+ "match": {+ "outputTypes": ["shell-grep"],+ "commands": ["^(?:grep|rg|ag)\\b"],+ "patterns": [+ "^[\\w./-]+\\.(?:ts|tsx|js|jsx|py|go|rs|java|rb|md|json|ya?ml|txt):\\d*:",+ "^[\\w./-]+/[\\w./-]+:\\d*:"+ ]+ },+ "rules": {+ "stripAnsi": true,+ "dropPatterns": ["^\\s*$"],+ "includePatterns": ["^[\\w./-]+(?::\\d+)?:"],+ "collapsePatterns": [],+ "deduplicate": true,+ "maxLines": 160,+ "headLines": 40,+ "tailLines": 60+ },+ "preserve": {+ "errorPatterns": ["No such file", "Permission denied"],+ "summaryPatterns": ["^[^:\\n]+(?::\\d+)?:"]+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "(?:grep|rg|ag)",+ "input": "src/a.ts:1:match\nsrc/a.ts:1:match\nsrc/b.ts:2:other\n",+ "expected": "src/a.ts:1:match\nsrc/a.ts:1:match\nsrc/b.ts:2:other"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/shell-ls.json b/open-sse/services/compression/engines/rtk/filters/shell-ls.jsonnew file mode 100644index 0000000000..d8bb51cf8e--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/shell-ls.json@@ -0,0 +1,33 @@+{+ "id": "shell-ls",+ "label": "Shell Listing",+ "description": "Keep directory listing boundaries without flooding the prompt.",+ "category": "shell",+ "priority": 50,+ "match": {+ "outputTypes": ["shell-ls"],+ "commands": ["^(?:ls(?:\\s+-[A-Za-z]+)?|find)\\b"],+ "patterns": ["^total \\d+", "^\\S+\\s+\\S+\\s+\\d+\\s+\\w+\\s+\\d{1,2}\\s+"]+ },+ "rules": {+ "includePatterns": [],+ "dropPatterns": ["^\\s*$"],+ "collapsePatterns": [],+ "deduplicate": false,+ "maxLines": 100,+ "headLines": 40,+ "tailLines": 30+ },+ "preserve": {+ "errorPatterns": ["^total \\d+"],+ "summaryPatterns": []+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "(?:ls(?: -[A-Za-z]+)?|find)",+ "input": "total 8\ndrwxr-xr-x 2 user user 4096 May 1 src\n-rw-r--r-- 1 user user 10 May 1 package.json\n",+ "expected": "total 8\ndrwxr-xr-x 2 user user 4096 May 1 src\n-rw-r--r-- 1 user user 10 May 1 package.json"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/ssh.json b/open-sse/services/compression/engines/rtk/filters/ssh.jsonnew file mode 100644index 0000000000..2b67759776--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/ssh.json@@ -0,0 +1,43 @@+{+ "id": "ssh",+ "label": "ssh",+ "description": "Compress SSH connection logs while preserving access and host-key failures.",+ "category": "cloud",+ "priority": 72,+ "match": {+ "outputTypes": ["ssh"],+ "commands": ["^ssh\\b"],+ "patterns": [+ "Permission denied \\(",+ "Host key verification failed",+ "Connection (?:closed|timed out)"+ ]+ },+ "rules": {+ "stripAnsi": true,+ "dropPatterns": ["^debug\\d:", "^\\s*$"],+ "includePatterns": [+ "Permission denied",+ "Host key verification failed",+ "Connection (?:closed|timed out)",+ "^Welcome "+ ],+ "collapsePatterns": [],+ "deduplicate": true,+ "maxLines": 100,+ "headLines": 25,+ "tailLines": 40+ },+ "preserve": {+ "errorPatterns": ["Permission denied", "Host key verification failed", "Connection timed out"],+ "summaryPatterns": ["^Welcome "]+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "ssh host",+ "input": "debug1: Connecting to host\nWelcome to Ubuntu\nPermission denied (publickey).\n",+ "expected": "Welcome to Ubuntu\nPermission denied (publickey)."+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/systemctl-status.json b/open-sse/services/compression/engines/rtk/filters/systemctl-status.jsonnew file mode 100644index 0000000000..f75b502bc1--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/systemctl-status.json@@ -0,0 +1,43 @@+{+ "id": "systemctl-status",+ "label": "systemctl status",+ "description": "Preserve unit status, active state, and journal errors.",+ "category": "infra",+ "priority": 77,+ "match": {+ "outputTypes": [],+ "commands": ["^systemctl\\s+status\\b"],+ "patterns": ["Loaded:", "Active:", "Main PID:"]+ },+ "rules": {+ "stripAnsi": true,+ "includePatterns": [+ "Loaded:",+ "Active:",+ "Main PID:",+ "CGroup:",+ "error",+ "failed",+ "Started",+ "Stopped"+ ],+ "dropPatterns": ["^\\s*$"],+ "collapsePatterns": ["^\\s+Docs:"],+ "deduplicate": true,+ "maxLines": 100,+ "headLines": 30,+ "tailLines": 40+ },+ "preserve": {+ "errorPatterns": ["failed", "error"],+ "summaryPatterns": ["Active:", "Loaded:"]+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "systemctl status",+ "input": "Loaded: loaded (/etc/systemd/system/app.service)\nActive: failed (Result: exit-code)\nMain PID: 123\nMay 1 app[123]: error boot failed\n",+ "expected": "Loaded: loaded (/etc/systemd/system/app.service)\nActive: failed (Result: exit-code)\nMain PID: 123\nMay 1 app[123]: error boot failed"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/terraform-plan.json b/open-sse/services/compression/engines/rtk/filters/terraform-plan.jsonnew file mode 100644index 0000000000..3f9d417253--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/terraform-plan.json@@ -0,0 +1,34 @@+{+ "id": "terraform-plan",+ "label": "Terraform Plan",+ "description": "Keep plan actions and summary while stripping refresh noise.",+ "category": "infra",+ "priority": 88,+ "match": {+ "outputTypes": [],+ "commands": ["^terraform\\s+plan\\b"],+ "patterns": ["Terraform will perform the following actions", "Plan: \\d+ to add"]+ },+ "rules": {+ "stripAnsi": true,+ "dropPatterns": ["Refreshing state", "Acquiring state lock", "Releasing state lock", "^\\s*$"],+ "includePatterns": ["Terraform will perform", "^[ ]*[#~+\\-/]", "Plan: \\d+", "Error:"],+ "collapsePatterns": [],+ "deduplicate": false,+ "maxLines": 160,+ "headLines": 35,+ "tailLines": 50+ },+ "preserve": {+ "errorPatterns": ["Error:", "failed"],+ "summaryPatterns": ["Plan: \\d+"]+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "terraform plan",+ "input": "Refreshing state... [id=a]\nTerraform will perform the following actions:\n # aws_instance.web will be created\nPlan: 1 to add, 0 to change, 0 to destroy.\n",+ "expected": "Terraform will perform the following actions:\n # aws_instance.web will be created\nPlan: 1 to add, 0 to change, 0 to destroy."+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/test-cargo.json b/open-sse/services/compression/engines/rtk/filters/test-cargo.jsonnew file mode 100644index 0000000000..e7aecaca5c--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/test-cargo.json@@ -0,0 +1,42 @@+{+ "id": "test-cargo",+ "label": "Cargo Test",+ "description": "Keep Cargo test failures and final summary.",+ "category": "test",+ "priority": 90,+ "match": {+ "outputTypes": ["test-cargo"],+ "commands": ["^cargo\\s+(?:test|nextest)\\b"],+ "patterns": ["^running \\d+ tests?", "test result:"]+ },+ "rules": {+ "stripAnsi": true,+ "includePatterns": [+ "^running \\d+ tests?",+ "^test .* \\.\\.\\. FAILED",+ "^failures:",+ "^---- ",+ "^thread ",+ "^test result:",+ "^error:"+ ],+ "dropPatterns": ["^test .* \\.\\.\\. ok$", "^\\s*$"],+ "collapsePatterns": ["^\\s+at "],+ "deduplicate": true,+ "maxLines": 180,+ "headLines": 40,+ "tailLines": 70+ },+ "preserve": {+ "errorPatterns": ["FAILED", "^error:", "^thread "],+ "summaryPatterns": ["test result:"]+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "cargo (?:test|nextest)",+ "input": "running 2 tests\ntest a ... ok\ntest b ... FAILED\nfailures:\n---- b stdout ----\nthread b panicked at boom\ntest result: FAILED. 1 passed; 1 failed\n",+ "expected": "running 2 tests\ntest b ... FAILED\nfailures:\n---- b stdout ----\nthread b panicked at boom\ntest result: FAILED. 1 passed; 1 failed"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/test-go.json b/open-sse/services/compression/engines/rtk/filters/test-go.jsonnew file mode 100644index 0000000000..5e4f05e50d--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/test-go.json@@ -0,0 +1,41 @@+{+ "id": "test-go",+ "label": "Go Test",+ "description": "Keep failing Go tests and package summaries.",+ "category": "test",+ "priority": 90,+ "match": {+ "outputTypes": ["test-go"],+ "commands": ["^go\\s+test\\b"],+ "patterns": ["^--- FAIL:", "^(?:ok|FAIL)\\s+"]+ },+ "rules": {+ "stripAnsi": true,+ "includePatterns": [+ "^--- FAIL:",+ "^FAIL",+ "^ok\\s+",+ "^panic:",+ "^\\s+.*_test\\.go:\\d+",+ "^\\s*Error"+ ],+ "dropPatterns": ["^\\s*$"],+ "collapsePatterns": ["^=== RUN"],+ "deduplicate": true,+ "maxLines": 160,+ "headLines": 35,+ "tailLines": 60+ },+ "preserve": {+ "errorPatterns": ["^--- FAIL:", "^panic:", "^FAIL"],+ "summaryPatterns": ["^ok\\s+", "^FAIL\\s+"]+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "go test",+ "input": "=== RUN TestA\n--- FAIL: TestA (0.00s)\n a_test.go:1: boom\nFAIL\t./pkg\t0.1s\n",+ "expected": "--- FAIL: TestA (0.00s)\n a_test.go:1: boom\nFAIL\t./pkg\t0.1s"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/test-jest.json b/open-sse/services/compression/engines/rtk/filters/test-jest.jsonnew file mode 100644index 0000000000..62f4c0a5d0--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/test-jest.json@@ -0,0 +1,43 @@+{+ "id": "test-jest",+ "label": "Jest",+ "description": "Keep Jest failures and summary while removing passing noise.",+ "category": "test",+ "priority": 90,+ "match": {+ "outputTypes": ["test-jest"],+ "commands": ["^(?:jest|npm\\s+(?:run\\s+)?test)\\b"],+ "patterns": ["Test Suites:\\s+\\d+", "Tests:\\s+\\d+", "^PASS\\s+", "^FAIL\\s+"]+ },+ "rules": {+ "includePatterns": [+ "^FAIL\\s+",+ "^\\s*●\\s+",+ "Expected:",+ "Received:",+ "Test Suites:",+ "Tests:",+ "Snapshots:",+ "Time:",+ "\\s+at\\s+"+ ],+ "dropPatterns": ["^PASS\\s+", "^\\s*✓\\s+"],+ "collapsePatterns": ["^\\s*at "],+ "deduplicate": true,+ "maxLines": 140,+ "headLines": 24,+ "tailLines": 50+ },+ "preserve": {+ "errorPatterns": ["FAIL", "Expected:", "Received:", "Test Suites:"],+ "summaryPatterns": []+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "(?:jest|npm (?:run )?test)",+ "input": "PASS src/a.test.ts\nFAIL src/b.test.ts\nError: boom\nTest Suites: 1 failed, 1 passed\nTests: 1 failed, 1 passed\n",+ "expected": "FAIL src/b.test.ts\nTest Suites: 1 failed, 1 passed\nTests: 1 failed, 1 passed"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/test-pytest.json b/open-sse/services/compression/engines/rtk/filters/test-pytest.jsonnew file mode 100644index 0000000000..4e62bcc34c--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/test-pytest.json@@ -0,0 +1,41 @@+{+ "id": "test-pytest",+ "label": "Pytest",+ "description": "Keep pytest failures, tracebacks and terminal summary.",+ "category": "test",+ "priority": 90,+ "match": {+ "outputTypes": ["test-pytest"],+ "commands": ["^(?:pytest|python\\s+-m\\s+pytest)\\b"],+ "patterns": ["=+\\s+(?:\\d+\\s+)?(?:passed|failed|errors?)", "^E\\s+", "^FAILED "]+ },+ "rules": {+ "includePatterns": [+ "^FAILED ",+ "^ERROR ",+ "^E\\s+",+ "Traceback \\(most recent call last\\):",+ "=+ short test summary info =+",+ "=+ .*failed",+ "AssertionError"+ ],+ "dropPatterns": ["^\\.", "^\\s*$"],+ "collapsePatterns": ["^E\\s+"],+ "deduplicate": true,+ "maxLines": 160,+ "headLines": 28,+ "tailLines": 60+ },+ "preserve": {+ "errorPatterns": ["FAILED", "ERROR", "Traceback", "AssertionError"],+ "summaryPatterns": []+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "(?:pytest|python -m pytest)",+ "input": "FAILED tests/test_a.py::test_a - AssertionError\nE assert 1 == 2\n================ 1 failed, 2 passed ================\n",+ "expected": "FAILED tests/test_a.py::test_a - AssertionError\nE assert 1 == 2\n================ 1 failed, 2 passed ================"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/test-vitest.json b/open-sse/services/compression/engines/rtk/filters/test-vitest.jsonnew file mode 100644index 0000000000..bb8a7480de--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/test-vitest.json@@ -0,0 +1,43 @@+{+ "id": "test-vitest",+ "label": "Vitest",+ "description": "Keep failing suites, failed tests, stack headers, and final summary.",+ "category": "test",+ "priority": 92,+ "match": {+ "outputTypes": ["test-vitest"],+ "commands": ["^(?:vitest|npm\\s+(?:run\\s+)?test:vitest)\\b"],+ "patterns": ["\\bvitest\\b", "^ ✓ ", "^ ❯ ", "Test Files\\s+\\d+\\s+(?:passed|failed)"]+ },+ "rules": {+ "includePatterns": [+ "^\\s*FAIL\\s+",+ "^\\s*❯\\s+",+ "^\\s*×\\s+",+ "Test Files\\s+",+ "Tests\\s+",+ "Duration\\s+",+ "Error:",+ "AssertionError",+ "\\s+at\\s+"+ ],+ "dropPatterns": ["^\\s*✓\\s+", "^\\s*stdout \\|", "^\\s*stderr \\|"],+ "collapsePatterns": ["^\\s*at "],+ "deduplicate": true,+ "maxLines": 140,+ "headLines": 24,+ "tailLines": 50+ },+ "preserve": {+ "errorPatterns": ["FAIL", "Error:", "AssertionError", "Test Files"],+ "summaryPatterns": []+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "(?:vitest|npm (?:run )?test:vitest)",+ "input": " ✓ src/a.test.ts (1)\n ❯ src/b.test.ts (1)\n FAIL src/b.test.ts > fails\nError: boom\nTest Files 1 failed | 1 passed\nTests 1 failed | 1 passed\n",+ "expected": " ❯ src/b.test.ts (1)\n FAIL src/b.test.ts > fails\nError: boom\nTest Files 1 failed | 1 passed\nTests 1 failed | 1 passed"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/tofu-plan.json b/open-sse/services/compression/engines/rtk/filters/tofu-plan.jsonnew file mode 100644index 0000000000..d6b8c69ee5--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/tofu-plan.json@@ -0,0 +1,34 @@+{+ "id": "tofu-plan",+ "label": "OpenTofu Plan",+ "description": "Keep OpenTofu plan actions and summary while stripping refresh noise.",+ "category": "infra",+ "priority": 87,+ "match": {+ "outputTypes": [],+ "commands": ["^tofu\\s+plan\\b"],+ "patterns": ["OpenTofu will perform the following actions", "Plan: \\d+ to add"]+ },+ "rules": {+ "stripAnsi": true,+ "dropPatterns": ["Refreshing state", "Acquiring state lock", "Releasing state lock", "^\\s*$"],+ "includePatterns": ["OpenTofu will perform", "^[ ]*[#~+\\-/]", "Plan: \\d+", "Error:"],+ "collapsePatterns": [],+ "deduplicate": false,+ "maxLines": 160,+ "headLines": 35,+ "tailLines": 50+ },+ "preserve": {+ "errorPatterns": ["Error:", "failed"],+ "summaryPatterns": ["Plan: \\d+"]+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "tofu plan",+ "input": "Refreshing state... [id=a]\nOpenTofu will perform the following actions:\n # tofu_resource.web will be created\nPlan: 1 to add, 0 to change, 0 to destroy.\n",+ "expected": "OpenTofu will perform the following actions:\n # tofu_resource.web will be created\nPlan: 1 to add, 0 to change, 0 to destroy."+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/turbo.json b/open-sse/services/compression/engines/rtk/filters/turbo.jsonnew file mode 100644index 0000000000..0727717b65--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/turbo.json@@ -0,0 +1,34 @@+{+ "id": "turbo",+ "label": "Turborepo",+ "description": "Compact turbo task cache and failure output.",+ "category": "build",+ "priority": 76,+ "match": {+ "outputTypes": [],+ "commands": ["^turbo\\b", "^npx\\s+turbo\\b"],+ "patterns": ["Tasks:", "Remote caching"]+ },+ "rules": {+ "stripAnsi": true,+ "dropPatterns": ["cache hit", "cache miss", "^\\s*$"],+ "includePatterns": ["failed", "error", "Tasks:", "Cached:", "Time:", "successful"],+ "collapsePatterns": ["^• Packages in scope"],+ "deduplicate": true,+ "maxLines": 120,+ "headLines": 25,+ "tailLines": 50+ },+ "preserve": {+ "errorPatterns": ["failed", "error"],+ "summaryPatterns": ["Tasks:", "Cached:", "Time:"]+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "turbo",+ "input": "cache hit app#build\napp#test: failed\nTasks: 1 successful, 1 failed\nTime: 2s\n",+ "expected": "app#test: failed\nTasks: 1 successful, 1 failed\nTime: 2s"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/uv-sync.json b/open-sse/services/compression/engines/rtk/filters/uv-sync.jsonnew file mode 100644index 0000000000..ecac0a0321--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/uv-sync.json@@ -0,0 +1,35 @@+{+ "id": "uv-sync",+ "label": "uv sync",+ "description": "Compact uv sync/install output.",+ "category": "package",+ "priority": 72,+ "match": {+ "outputTypes": [],+ "commands": ["^uv\\s+sync\\b", "^uv\\s+pip\\s+install\\b"],+ "patterns": ["Resolved \\d+ packages?", "Prepared \\d+ packages?"]+ },+ "rules": {+ "stripAnsi": true,+ "dropPatterns": ["^Resolved ", "^Prepared ", "^Installed ", "^ \\+", "^\\s*$"],+ "includePatterns": ["error", "failed", "Installed", "Uninstalled", "Resolved"],+ "collapsePatterns": [],+ "deduplicate": true,+ "maxLines": 100,+ "headLines": 25,+ "tailLines": 35,+ "onEmpty": "uv: ok"+ },+ "preserve": {+ "errorPatterns": ["error", "failed"],+ "summaryPatterns": ["Installed", "Resolved"]+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "uv sync",+ "input": "Resolved 10 packages in 1ms\nInstalled 10 packages in 2ms\n",+ "expected": "uv: ok"+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/filters/wget.json b/open-sse/services/compression/engines/rtk/filters/wget.jsonnew file mode 100644index 0000000000..b5de52bb99--- /dev/null+++ b/open-sse/services/compression/engines/rtk/filters/wget.json@@ -0,0 +1,34 @@+{+ "id": "wget",+ "label": "wget",+ "description": "Remove wget progress output and keep final errors or saved-file summaries.",+ "category": "cloud",+ "priority": 70,+ "match": {+ "outputTypes": ["wget"],+ "commands": ["^wget\\b"],+ "patterns": ["^--\\d{4}-\\d{2}-\\d{2}", "^ERROR \\d{3}:"]+ },+ "rules": {+ "stripAnsi": true,+ "dropPatterns": ["^\\s*\\d+K", "^Saving to:", "^\\s*$"],+ "includePatterns": ["^ERROR \\d{3}:", "saved \\[\\d", "^HTTP request sent"],+ "collapsePatterns": [],+ "deduplicate": true,+ "maxLines": 100,+ "headLines": 25,+ "tailLines": 40+ },+ "preserve": {+ "errorPatterns": ["^ERROR \\d{3}:", "failed", "unable to resolve"],+ "summaryPatterns": ["saved \\[\\d", "^HTTP request sent"]+ },+ "tests": [+ {+ "name": "inline sample",+ "command": "wget",+ "input": "--2026-05-02-- https://example.test/file\nSaving to: 'file'\nHTTP request sent, awaiting response... 404 Not Found\nERROR 404: Not Found.\n",+ "expected": "HTTP request sent, awaiting response... 404 Not Found\nERROR 404: Not Found."+ }+ ]+}diff --git a/open-sse/services/compression/engines/rtk/index.ts b/open-sse/services/compression/engines/rtk/index.tsnew file mode 100644index 0000000000..70d6efc529--- /dev/null+++ b/open-sse/services/compression/engines/rtk/index.ts@@ -0,0 +1,436 @@+import { createCompressionStats, estimateCompressionTokens } from "../../stats.ts";+import { DEFAULT_RTK_CONFIG, type CompressionResult, type RtkConfig } from "../../types.ts";+import type { CompressionEngine, EngineConfigField, EngineValidationResult } from "../types.ts";+import { detectCommandType } from "./commandDetector.ts";+import { deduplicateRepeatedLines } from "./deduplicator.ts";+import { matchRtkFilter } from "./filterLoader.ts";+import { applyLineFilter } from "./lineFilter.ts";+import { smartTruncate } from "./smartTruncate.ts";+import { normalizeCodeLanguage, stripCode } from "./codeStripper.ts";+import { maybePersistRtkRawOutput, type RtkRawOutputPointer } from "./rawOutput.ts";+import { isTextBlock } from "../../messageContent.ts";++type Message = {+ role: string;+ content?: string | Array<{ type?: string; text?: string; [key: string]: unknown }>;+ [key: string]: unknown;+};++const RTK_SCHEMA: EngineConfigField[] = [+ {+ key: "intensity",+ type: "select",+ label: "Intensity",+ defaultValue: DEFAULT_RTK_CONFIG.intensity,+ options: [+ { value: "minimal", label: "minimal" },+ { value: "standard", label: "standard" },+ { value: "aggressive", label: "aggressive" },+ ],+ },+ {+ key: "applyToToolResults",+ type: "boolean",+ label: "Apply to tool results",+ defaultValue: DEFAULT_RTK_CONFIG.applyToToolResults,+ },+ {+ key: "applyToAssistantMessages",+ type: "boolean",+ label: "Apply to assistant messages",+ defaultValue: DEFAULT_RTK_CONFIG.applyToAssistantMessages,+ },+ {+ key: "applyToCodeBlocks",+ type: "boolean",+ label: "Apply to code blocks",+ defaultValue: DEFAULT_RTK_CONFIG.applyToCodeBlocks,+ },+ {+ key: "maxLinesPerResult",+ type: "number",+ label: "Max lines per result",+ defaultValue: DEFAULT_RTK_CONFIG.maxLinesPerResult,+ min: 0,+ max: 5000,+ },+ {+ key: "maxCharsPerResult",+ type: "number",+ label: "Max chars per result",+ defaultValue: DEFAULT_RTK_CONFIG.maxCharsPerResult,+ min: 0,+ max: 500000,+ },+ {+ key: "deduplicateThreshold",+ type: "number",+ label: "Deduplicate threshold",+ defaultValue: DEFAULT_RTK_CONFIG.deduplicateThreshold,+ min: 2,+ max: 100,+ },+ {+ key: "rawOutputRetention",+ type: "select",+ label: "Raw output retention",+ defaultValue: DEFAULT_RTK_CONFIG.rawOutputRetention,+ options: [+ { value: "never", label: "never" },+ { value: "failures", label: "failures" },+ { value: "always", label: "always" },+ ],+ },+];++function validateRtkEngineConfig(config: Record<string, unknown>): EngineValidationResult {+ const errors: string[] = [];+ if (+ config.intensity !== undefined &&+ config.intensity !== "minimal" &&+ config.intensity !== "standard" &&+ config.intensity !== "aggressive"+ ) {+ errors.push("intensity must be minimal, standard, or aggressive");+ }+ for (const key of [+ "enabled",+ "applyToToolResults",+ "applyToAssistantMessages",+ "applyToCodeBlocks",+ ]) {+ if (config[key] !== undefined && typeof config[key] !== "boolean") {+ errors.push(`${key} must be a boolean`);+ }+ }+ for (const key of ["maxLinesPerResult", "maxCharsPerResult", "deduplicateThreshold"]) {+ if (config[key] !== undefined && (typeof config[key] !== "number" || config[key] < 0)) {+ errors.push(`${key} must be a non-negative number`);+ }+ }+ if (config.enabledFilters !== undefined && !Array.isArray(config.enabledFilters)) {+ errors.push("enabledFilters must be an array");+ }+ if (config.disabledFilters !== undefined && !Array.isArray(config.disabledFilters)) {+ errors.push("disabledFilters must be an array");+ }+ if (+ config.rawOutputRetention !== undefined &&+ config.rawOutputRetention !== "never" &&+ config.rawOutputRetention !== "failures" &&+ config.rawOutputRetention !== "always"+ ) {+ errors.push("rawOutputRetention must be never, failures, or always");+ }+ return { valid: errors.length === 0, errors };+}++export interface RtkProcessResult {+ text: string;+ compressed: boolean;+ originalTokens: number;+ compressedTokens: number;+ techniquesUsed: string[];+ rulesApplied: string[];+ rawOutputPointers?: RtkRawOutputPointer[];+}++function mergeRtkConfig(base?: Partial<RtkConfig>, override?: Record<string, unknown>): RtkConfig {+ const merged = { ...DEFAULT_RTK_CONFIG, ...(base ?? {}), ...(override ?? {}) };+ return {+ ...merged,+ intensity:+ merged.intensity === "minimal" ||+ merged.intensity === "standard" ||+ merged.intensity === "aggressive"+ ? merged.intensity+ : DEFAULT_RTK_CONFIG.intensity,+ enabledFilters: Array.isArray(merged.enabledFilters)+ ? merged.enabledFilters.filter((id): id is string => typeof id === "string")+ : [],+ disabledFilters: Array.isArray(merged.disabledFilters)+ ? merged.disabledFilters.filter((id): id is string => typeof id === "string")+ : [],+ maxLinesPerResult:+ typeof merged.maxLinesPerResult === "number" && Number.isFinite(merged.maxLinesPerResult)+ ? Math.max(0, Math.floor(merged.maxLinesPerResult))+ : DEFAULT_RTK_CONFIG.maxLinesPerResult,+ maxCharsPerResult:+ typeof merged.maxCharsPerResult === "number" && Number.isFinite(merged.maxCharsPerResult)+ ? Math.max(0, Math.floor(merged.maxCharsPerResult))+ : DEFAULT_RTK_CONFIG.maxCharsPerResult,+ deduplicateThreshold:+ typeof merged.deduplicateThreshold === "number" &&+ Number.isFinite(merged.deduplicateThreshold)+ ? Math.max(2, Math.floor(merged.deduplicateThreshold))+ : DEFAULT_RTK_CONFIG.deduplicateThreshold,+ customFiltersEnabled:+ typeof merged.customFiltersEnabled === "boolean"+ ? merged.customFiltersEnabled+ : DEFAULT_RTK_CONFIG.customFiltersEnabled,+ trustProjectFilters:+ typeof merged.trustProjectFilters === "boolean"+ ? merged.trustProjectFilters+ : DEFAULT_RTK_CONFIG.trustProjectFilters,+ rawOutputRetention:+ merged.rawOutputRetention === "never" ||+ merged.rawOutputRetention === "failures" ||+ merged.rawOutputRetention === "always"+ ? merged.rawOutputRetention+ : DEFAULT_RTK_CONFIG.rawOutputRetention,+ rawOutputMaxBytes:+ typeof merged.rawOutputMaxBytes === "number" && Number.isFinite(merged.rawOutputMaxBytes)+ ? Math.max(1024, Math.floor(merged.rawOutputMaxBytes))+ : DEFAULT_RTK_CONFIG.rawOutputMaxBytes,+ };+}++function shouldCompressMessage(message: Message, config: RtkConfig): boolean {+ if (message.role === "tool") return config.applyToToolResults || config.applyToCodeBlocks;+ if (message.role === "assistant")+ return config.applyToAssistantMessages || config.applyToCodeBlocks;+ return false;+}++export function processRtkText(+ text: string,+ options: { command?: string | null; config?: Partial<RtkConfig> } = {}+): RtkProcessResult {+ const config = mergeRtkConfig(options.config);+ const originalTokens = estimateCompressionTokens(text);+ const techniquesUsed: string[] = [];+ const rulesApplied: string[] = [];+ const rawOutputPointers: RtkRawOutputPointer[] = [];+ let result = text;++ const detection = detectCommandType(text, options.command);+ const filter = matchRtkFilter(text, detection.command, {+ customFiltersEnabled: config.customFiltersEnabled,+ trustProjectFilters: config.trustProjectFilters,+ });+ if (filter && !config.disabledFilters.includes(filter.id)) {+ if (config.enabledFilters.length === 0 || config.enabledFilters.includes(filter.id)) {+ const filtered = applyLineFilter(result, {+ ...filter,+ maxLines: filter.maxLines || config.maxLinesPerResult,+ });+ result = filtered.text;+ if (filtered.appliedRules.length > 0) {+ techniquesUsed.push("rtk-filter");+ rulesApplied.push(...filtered.appliedRules);+ }+ }+ }++ if (config.applyToCodeBlocks) {+ let strippedCodeBlocks = 0;+ result = result.replace(+ /```([A-Za-z0-9_+.-]*)\r?\n([\s\S]*?)```/g,+ (match, languageHint: string, code: string) => {+ const stripped = stripCode(code, normalizeCodeLanguage(languageHint));+ if (stripped.strippedLines <= 0 && stripped.text === code.trim()) return match;+ strippedCodeBlocks++;+ const fenceLanguage = languageHint?.trim() || stripped.language;+ return `\`\`\`${fenceLanguage}\n${stripped.text}\n\`\`\``;+ }+ );+ if (strippedCodeBlocks > 0) {+ techniquesUsed.push("rtk-code-strip");+ rulesApplied.push("rtk:code-strip");+ }+ }++ if (config.intensity !== "minimal") {+ const deduped = deduplicateRepeatedLines(result, { threshold: config.deduplicateThreshold });+ if (deduped.collapsed > 0) {+ result = deduped.text;+ techniquesUsed.push("rtk-dedup");+ rulesApplied.push("rtk:dedup");+ }+ }++ const truncated = smartTruncate(result, {+ maxLines: config.maxLinesPerResult,+ maxChars: config.maxCharsPerResult,+ preserveHead: config.intensity === "aggressive" ? 16 : 24,+ preserveTail: config.intensity === "aggressive" ? 16 : 24,+ priorityPatterns: [/error|failed|exception|traceback|TS\d{4}|FAIL|✖/i],+ });+ if (truncated.truncated) {+ result = truncated.text;+ techniquesUsed.push("rtk-truncate");+ rulesApplied.push("rtk:truncate");+ }++ const compressedTokens = estimateCompressionTokens(result);+ if (compressedTokens < originalTokens) {+ const pointer = maybePersistRtkRawOutput(text, {+ retention: config.rawOutputRetention,+ command: detection.command,+ maxBytes: config.rawOutputMaxBytes,+ });+ if (pointer) {+ rawOutputPointers.push(pointer);+ techniquesUsed.push("rtk-raw-output-retention");+ rulesApplied.push("rtk:raw-output-retention");+ }+ }+ return {+ text: result,+ compressed: compressedTokens < originalTokens,+ originalTokens,+ compressedTokens,+ techniquesUsed: [...new Set(techniquesUsed)],+ rulesApplied: [...new Set(rulesApplied)],+ ...(rawOutputPointers.length > 0 ? { rawOutputPointers } : {}),+ };+}++function processRtkContent(+ content: Message["content"],+ config: RtkConfig+): {+ content: Message["content"];+ compressed: boolean;+ techniquesUsed: string[];+ rulesApplied: string[];+ rawOutputPointers: RtkRawOutputPointer[];+} {+ const techniquesUsed: string[] = [];+ const rulesApplied: string[] = [];+ const rawOutputPointers: RtkRawOutputPointer[] = [];++ const collect = (processed: RtkProcessResult) => {+ techniquesUsed.push(...processed.techniquesUsed);+ rulesApplied.push(...processed.rulesApplied);+ if (processed.rawOutputPointers) rawOutputPointers.push(...processed.rawOutputPointers);+ };++ if (typeof content === "string") {+ if (!content) {+ return { content, compressed: false, techniquesUsed, rulesApplied, rawOutputPointers };+ }+ const processed = processRtkText(content, { config });+ collect(processed);+ return {+ content: processed.compressed ? processed.text : content,+ compressed: processed.compressed,+ techniquesUsed,+ rulesApplied,+ rawOutputPointers,+ };+ }++ if (!Array.isArray(content)) {+ return { content, compressed: false, techniquesUsed, rulesApplied, rawOutputPointers };+ }++ let compressed = false;+ const nextContent = content.map((part) => {+ if (!isTextBlock(part) || !part.text) return part;+ const processed = processRtkText(part.text, { config });+ collect(processed);+ if (!processed.compressed) return part;+ compressed = true;+ return { ...part, text: processed.text };+ });++ return {+ content: compressed ? nextContent : content,+ compressed,+ techniquesUsed,+ rulesApplied,+ rawOutputPointers,+ };+}++export function applyRtkCompression(+ body: Record<string, unknown>,+ options: { config?: Partial<RtkConfig>; stepConfig?: Record<string, unknown> } = {}+): CompressionResult {+ const start = performance.now();+ const config = mergeRtkConfig(options.config, options.stepConfig);+ if (!config.enabled) return { body, compressed: false, stats: null };++ const messages = body.messages as Message[] | undefined;+ if (!Array.isArray(messages) || messages.length === 0) {+ return { body, compressed: false, stats: null };+ }++ const allTechniques: string[] = [];+ const allRules: string[] = [];+ const rawOutputPointers: RtkRawOutputPointer[] = [];+ const compressedMessages = messages.map((message) => {+ if (!shouldCompressMessage(message, config)) return message;+ const processed = processRtkContent(message.content, config);+ allTechniques.push(...processed.techniquesUsed);+ allRules.push(...processed.rulesApplied);+ rawOutputPointers.push(...processed.rawOutputPointers);+ if (!processed.compressed) return message;+ return {+ ...message,+ content: processed.content,+ };+ });++ const compressedBody = { ...body, messages: compressedMessages };+ const stats = createCompressionStats(+ body,+ compressedBody,+ "rtk",+ [...new Set(allTechniques)],+ allRules.length > 0 ? [...new Set(allRules)] : undefined,+ Math.round((performance.now() - start) * 100) / 100+ );+ stats.engine = "rtk";+ if (rawOutputPointers.length > 0) {+ stats.rtkRawOutputPointers = rawOutputPointers;+ }+ return {+ body: compressedBody,+ compressed: stats.compressedTokens < stats.originalTokens,+ stats,+ };+}++export const rtkEngine: CompressionEngine = {+ id: "rtk",+ name: "RTK",+ description: "Command-aware tool output compression with declarative filters.",+ icon: "filter_alt",+ targets: ["tool_results", "code_blocks"],+ stackable: true,+ stackPriority: 10,+ metadata: {+ id: "rtk",+ name: "RTK",+ description: "Command-aware tool output compression with declarative filters.",+ inputScope: "tool-results",+ targetLatencyMs: 5,+ supportsPreview: true,+ stable: true,+ },+ apply(body, options) {+ return applyRtkCompression(body, {+ config: options?.config?.rtkConfig,+ stepConfig: options?.stepConfig,+ });+ },+ compress(body, config) {+ return this.apply(body, { stepConfig: config });+ },+ getConfigSchema() {+ return RTK_SCHEMA;+ },+ validateConfig(config) {+ return validateRtkEngineConfig(config);+ },+};++export {+ detectCommandFromText,+ detectCommandOutput,+ detectCommandType,+} from "./commandDetector.ts";+export { runRtkFilterTests } from "./verify.ts";+export { maybePersistRtkRawOutput, readRtkRawOutput, redactRtkRawOutput } from "./rawOutput.ts";diff --git a/open-sse/services/compression/engines/rtk/lineFilter.ts b/open-sse/services/compression/engines/rtk/lineFilter.tsnew file mode 100644index 0000000000..589b618086--- /dev/null+++ b/open-sse/services/compression/engines/rtk/lineFilter.ts@@ -0,0 +1,155 @@+import type { RtkFilterDefinition } from "./filterSchema.ts";+import { smartTruncate } from "./smartTruncate.ts";++export interface LineFilterResult {+ text: string;+ strippedLines: number;+ keptByRule: boolean;+ appliedRules: string[];+}++function compilePatterns(patterns: string[]): RegExp[] {+ return patterns.flatMap((pattern) => {+ try {+ return [new RegExp(pattern, "i")];+ } catch {+ return [];+ }+ });+}++function compileGlobalPattern(pattern: string): RegExp | null {+ try {+ return new RegExp(pattern, "g");+ } catch {+ return null;+ }+}++function compileBlobPattern(pattern: string): RegExp | null {+ try {+ return new RegExp(pattern, "im");+ } catch {+ return null;+ }+}++function stripAnsi(text: string): string {+ return text.replace(/\u001b\[[0-?]*[ -/]*[@-~]/g, "");+}++function normalizeStderrPrefix(line: string): string {+ return line.replace(/^\s*(?:stderr|err)\s*(?:\||:)\s*/i, "");+}++function truncateUnicodeSafe(line: string, maxChars: number): string {+ if (maxChars <= 0) return line;+ const chars = Array.from(line);+ if (chars.length <= maxChars) return line;+ if (maxChars <= 3) return chars.slice(0, maxChars).join("");+ return `${chars.slice(0, maxChars - 3).join("")}...`;+}++export function applyLineFilter(text: string, filter: RtkFilterDefinition): LineFilterResult {+ const stripPatterns = compilePatterns(filter.stripPatterns);+ const keepPatterns = compilePatterns(filter.keepPatterns);+ const collapsePatterns = compilePatterns(filter.collapsePatterns);+ const priorityPatterns = compilePatterns(filter.priorityPatterns);+ const appliedRules: string[] = [];++ let lines = text.split(/\r?\n/);+ const originalLineCount = lines.length;++ if (filter.stripAnsi) {+ const stripped = lines.map(stripAnsi);+ if (stripped.join("\n") !== lines.join("\n")) {+ appliedRules.push(`${filter.id}:strip-ansi`);+ }+ lines = stripped;+ }++ if (filter.filterStderr) {+ const normalized = lines.map(normalizeStderrPrefix);+ if (normalized.join("\n") !== lines.join("\n")) {+ appliedRules.push(`${filter.id}:filter-stderr`);+ }+ lines = normalized;+ }++ for (const rule of filter.replace) {+ const pattern = compileGlobalPattern(rule.pattern);+ if (!pattern) continue;+ const replaced = lines.map((line) => line.replace(pattern, rule.replacement));+ if (replaced.join("\n") !== lines.join("\n")) {+ appliedRules.push(`${filter.id}:replace`);+ }+ lines = replaced;+ }++ if (filter.matchOutput.length > 0) {+ const blob = lines.join("\n");+ for (const rule of filter.matchOutput) {+ const pattern = compileBlobPattern(rule.pattern);+ if (!pattern?.test(blob)) continue;+ const unless = rule.unless ? compileBlobPattern(rule.unless) : null;+ if (unless?.test(blob)) continue;+ appliedRules.push(`${filter.id}:match-output`);+ return {+ text: rule.message,+ strippedLines: Math.max(0, originalLineCount - 1),+ keptByRule: false,+ appliedRules,+ };+ }+ }++ if (stripPatterns.length > 0) {+ lines = lines.filter((line) => !stripPatterns.some((pattern) => pattern.test(line)));+ if (lines.length !== originalLineCount) appliedRules.push(`${filter.id}:strip`);+ }++ if (keepPatterns.length > 0) {+ const kept = lines.filter((line) => keepPatterns.some((pattern) => pattern.test(line)));+ if (kept.length > 0) {+ lines = kept;+ appliedRules.push(`${filter.id}:keep`);+ }+ }++ if (collapsePatterns.length > 0) {+ const seen = new Set<string>();+ lines = lines.filter((line) => {+ if (!collapsePatterns.some((pattern) => pattern.test(line))) return true;+ const key = line.trim();+ if (seen.has(key)) return false;+ seen.add(key);+ return true;+ });+ appliedRules.push(`${filter.id}:collapse`);+ }++ if (filter.truncateLineAt > 0) {+ const truncatedLines = lines.map((line) => truncateUnicodeSafe(line, filter.truncateLineAt));+ if (truncatedLines.join("\n") !== lines.join("\n")) {+ lines = truncatedLines;+ appliedRules.push(`${filter.id}:truncate-line`);+ }+ }++ const truncated = smartTruncate(lines.join("\n"), {+ maxLines: filter.maxLines,+ preserveHead: filter.preserveHead,+ preserveTail: filter.preserveTail,+ priorityPatterns,+ });+ if (truncated.truncated) appliedRules.push(`${filter.id}:truncate`);+ const output =+ truncated.text.trim().length === 0 && filter.onEmpty ? filter.onEmpty : truncated.text;++ return {+ text: output,+ strippedLines: Math.max(0, originalLineCount - output.split(/\r?\n/).length),+ keptByRule: keepPatterns.length > 0,+ appliedRules,+ };+}diff --git a/open-sse/services/compression/engines/rtk/rawOutput.ts b/open-sse/services/compression/engines/rtk/rawOutput.tsnew file mode 100644index 0000000000..7e40d6a9cb--- /dev/null+++ b/open-sse/services/compression/engines/rtk/rawOutput.ts@@ -0,0 +1,112 @@+import fs from "node:fs";+import path from "node:path";+import os from "node:os";+import crypto from "node:crypto";++export type RtkRawOutputRetention = "never" | "failures" | "always";++export interface RtkRawOutputPointer {+ id: string;+ path: string;+ bytes: number;+ sha256: string;+ redacted: boolean;+}++const SECRET_PATTERNS: Array<[RegExp, string]> = [+ [/\b(sk-[A-Za-z0-9_-]{16,})\b/g, "[REDACTED_OPENAI_KEY]"],+ [/\b(xox[baprs]-[A-Za-z0-9-]{16,})\b/g, "[REDACTED_SLACK_TOKEN]"],+ [/\b(AKIA[0-9A-Z]{16})\b/g, "[REDACTED_AWS_KEY]"],+ [/((?:api[_-]?key|token|secret|password)\s*[:=]\s*)("[^"]+"|'[^']+'|[^\s]+)/gi, "$1[REDACTED]"],+ [/(Authorization:\s*Bearer\s+)[A-Za-z0-9._~+/-]+=*/gi, "$1[REDACTED]"],+];++function dataDir(): string {+ return process.env.DATA_DIR || path.join(os.homedir(), ".omniroute");+}++function safeId(seed: string): string {+ return crypto.createHash("sha256").update(seed).digest("hex").slice(0, 24);+}++function safeUtf8Slice(value: string, maxBytes: number): string {+ if (maxBytes <= 0 || Buffer.byteLength(value, "utf8") <= maxBytes) return value;+ let bytes = 0;+ let output = "";+ for (const char of value) {+ const len = Buffer.byteLength(char, "utf8");+ if (bytes + len > maxBytes) break;+ output += char;+ bytes += len;+ }+ return `${output}\n\n--- truncated at ${maxBytes} bytes ---`;+}++export function redactRtkRawOutput(value: string): { text: string; redacted: boolean } {+ let redacted = false;+ let text = value;+ for (const [pattern, replacement] of SECRET_PATTERNS) {+ const next = text.replace(pattern, (...args: string[]) => {+ redacted = true;+ return typeof replacement === "string"+ ? replacement.replace("$1", args[1] ?? "")+ : replacement;+ });+ text = next;+ }+ return { text, redacted };+}++export function isLikelyFailureOutput(value: string): boolean {+ return /\b(error|failed|failure|exception|traceback|panic|fatal|critical|TS\d{4}|FAIL)\b/i.test(+ value+ );+}++export function maybePersistRtkRawOutput(+ raw: string,+ options: {+ retention: RtkRawOutputRetention;+ command?: string | null;+ maxBytes?: number;+ failure?: boolean;+ }+): RtkRawOutputPointer | null {+ if (options.retention === "never") return null;+ const failure = options.failure ?? isLikelyFailureOutput(raw);+ if (options.retention === "failures" && !failure) return null;+ if (raw.trim().length === 0) return null;++ const maxBytes = Math.max(1024, Math.floor(options.maxBytes ?? 1_048_576));+ const redaction = redactRtkRawOutput(safeUtf8Slice(raw, maxBytes));+ const now = Date.now();+ const commandSlug = (options.command || "tool-output")+ .replace(/[^A-Za-z0-9_-]+/g, "_")+ .replace(/^_+|_+$/g, "")+ .slice(0, 48);+ const id = safeId(`${now}:${commandSlug}:${raw.length}:${redaction.text}`);+ const dir = path.join(dataDir(), "rtk", "raw-output");+ const filePath = path.join(dir, `${now}-${commandSlug || "tool-output"}-${id}.log`);+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(filePath, redaction.text);++ return {+ id,+ path: filePath,+ bytes: Buffer.byteLength(redaction.text, "utf8"),+ sha256: crypto.createHash("sha256").update(redaction.text).digest("hex"),+ redacted: redaction.redacted,+ };+}++export function readRtkRawOutput(pointerId: string): string | null {+ const dir = path.join(dataDir(), "rtk", "raw-output");+ if (!fs.existsSync(dir)) return null;+ const entry = fs+ .readdirSync(dir)+ .find((file) => file.endsWith(".log") && file.includes(pointerId));+ if (!entry) return null;+ const fullPath = path.join(dir, entry);+ if (!fullPath.startsWith(dir)) return null;+ return fs.readFileSync(fullPath, "utf8");+}diff --git a/open-sse/services/compression/engines/rtk/smartTruncate.ts b/open-sse/services/compression/engines/rtk/smartTruncate.tsnew file mode 100644index 0000000000..8af0e708c2--- /dev/null+++ b/open-sse/services/compression/engines/rtk/smartTruncate.ts@@ -0,0 +1,67 @@+export interface SmartTruncateOptions {+ maxLines?: number;+ maxChars?: number;+ preserveHead?: number;+ preserveTail?: number;+ priorityPatterns?: RegExp[];+}++export function smartTruncate(+ text: string,+ options: SmartTruncateOptions = {}+): {+ text: string;+ truncated: boolean;+ droppedLines: number;+} {+ const maxChars = Math.max(0, Math.floor(options.maxChars ?? 0));+ const maxLines = Math.max(0, Math.floor(options.maxLines ?? 0));+ const lines = text.split(/\r?\n/);+ const overLineLimit = maxLines > 0 && lines.length > maxLines;+ const overCharLimit = maxChars > 0 && text.length > maxChars;+ if (!overLineLimit && !overCharLimit) {+ return { text, truncated: false, droppedLines: 0 };+ }++ const preserveHead = Math.max(0, Math.floor(options.preserveHead ?? 20));+ const preserveTail = Math.max(0, Math.floor(options.preserveTail ?? 20));+ const priorityPatterns = options.priorityPatterns ?? [];+ const priorityLines = priorityPatterns.length+ ? lines.filter((line) => priorityPatterns.some((pattern) => pattern.test(line)))+ : [];++ const head = lines.slice(0, preserveHead);+ const tail = preserveTail > 0 ? lines.slice(-preserveTail) : [];+ const selected = [...head];+ for (const line of priorityLines) {+ if (!selected.includes(line)) selected.push(line);+ }+ const tailStart = lines.length - tail.length;+ tail.forEach((line, offset) => {+ const originalIndex = tailStart + offset;+ if (originalIndex >= preserveHead && !selected.includes(line)) selected.push(line);+ });++ const droppedLines = Math.max(0, lines.length - selected.length);+ let result = [+ ...selected.slice(0, head.length),+ `[rtk:truncated ${droppedLines} lines]`,+ ...selected.slice(head.length),+ ].join("\n");++ if (maxChars > 0 && result.length > maxChars) {+ const marker = "\n[rtk:truncated by chars]\n";+ const budget = Math.max(0, maxChars - marker.length);+ if (budget === 0) {+ result = marker.slice(0, maxChars);+ return { text: result, truncated: true, droppedLines };+ }+ const headChars = Math.ceil(budget * 0.55);+ const tailChars = Math.max(0, budget - headChars);+ const tailText = tailChars > 0 ? result.slice(-tailChars) : "";+ result = `${result.slice(0, headChars)}${marker}${tailText}`;+ if (result.length > maxChars) result = result.slice(0, maxChars);+ }++ return { text: result, truncated: true, droppedLines };+}diff --git a/open-sse/services/compression/engines/rtk/verify.ts b/open-sse/services/compression/engines/rtk/verify.tsnew file mode 100644index 0000000000..c59a5e9102--- /dev/null+++ b/open-sse/services/compression/engines/rtk/verify.ts@@ -0,0 +1,107 @@+import { estimateCompressionTokens } from "../../stats.ts";+import {+ getRtkFilterLoadDiagnostics,+ loadRtkFilters,+ type RtkFilterLoadDiagnostic,+} from "./filterLoader.ts";+import { applyLineFilter } from "./lineFilter.ts";++export interface RtkFilterTestOutcome {+ filterId: string;+ testName: string;+ passed: boolean;+ actual: string;+ expected: string;+}++export interface RtkFilterBenchmarkRow {+ category: string;+ filters: number;+ tests: number;+ averageSavingsPercent: number;+}++export interface RtkVerifyResult {+ passed: boolean;+ outcomes: RtkFilterTestOutcome[];+ filtersWithoutTests: string[];+ benchmark: RtkFilterBenchmarkRow[];+ diagnostics: RtkFilterLoadDiagnostic[];+}++function trimComparable(value: string): string {+ return value.replace(/\n+$/g, "");+}++export function runRtkFilterTests(+ options: {+ requireAll?: boolean;+ customFiltersEnabled?: boolean;+ trustProjectFilters?: boolean;+ } = {}+): RtkVerifyResult {+ const filters = loadRtkFilters({+ refresh: true,+ customFiltersEnabled: options.customFiltersEnabled,+ trustProjectFilters: options.trustProjectFilters,+ });+ const outcomes: RtkFilterTestOutcome[] = [];+ const filtersWithoutTests: string[] = [];+ const benchmarkByCategory = new Map<+ string,+ { filters: Set<string>; tests: number; savingsTotal: number }+ >();++ for (const filter of filters) {+ const categoryStats = benchmarkByCategory.get(filter.category) ?? {+ filters: new Set<string>(),+ tests: 0,+ savingsTotal: 0,+ };+ categoryStats.filters.add(filter.id);+ benchmarkByCategory.set(filter.category, categoryStats);++ if (filter.tests.length === 0) {+ filtersWithoutTests.push(filter.id);+ continue;+ }++ for (const test of filter.tests) {+ const result = applyLineFilter(test.input, filter).text;+ const actual = trimComparable(result);+ const expected = trimComparable(test.expected);+ const originalTokens = estimateCompressionTokens(test.input);+ const compressedTokens = estimateCompressionTokens(result);+ const savings =+ originalTokens > 0 ? ((originalTokens - compressedTokens) / originalTokens) * 100 : 0;+ categoryStats.tests += 1;+ categoryStats.savingsTotal += Math.max(0, savings);+ outcomes.push({+ filterId: filter.id,+ testName: test.name,+ passed: actual === expected,+ actual,+ expected,+ });+ }+ }++ const benchmark = Array.from(benchmarkByCategory.entries())+ .map(([category, value]) => ({+ category,+ filters: value.filters.size,+ tests: value.tests,+ averageSavingsPercent:+ value.tests > 0 ? Math.round((value.savingsTotal / value.tests) * 100) / 100 : 0,+ }))+ .sort((a, b) => a.category.localeCompare(b.category));++ const failed = outcomes.some((outcome) => !outcome.passed);+ return {+ passed: !failed && (!options.requireAll || filtersWithoutTests.length === 0),+ outcomes,+ filtersWithoutTests,+ benchmark,+ diagnostics: options.customFiltersEnabled === false ? [] : getRtkFilterLoadDiagnostics(),+ };+}diff --git a/open-sse/services/compression/engines/types.ts b/open-sse/services/compression/engines/types.tsnew file mode 100644index 0000000000..b270d8d1d5--- /dev/null+++ b/open-sse/services/compression/engines/types.ts@@ -0,0 +1,59 @@+import type { CompressionConfig, CompressionResult } from "../types.ts";++export type CompressionEngineTarget = "messages" | "tool_results" | "code_blocks";++export interface EngineConfigField {+ key: string;+ type: "boolean" | "number" | "string" | "select" | "multiselect";+ label: string;+ i18nKey?: string;+ description?: string;+ defaultValue: unknown;+ options?: Array<{ value: string; label: string }>;+ min?: number;+ max?: number;+}++export interface EngineValidationResult {+ valid: boolean;+ errors: string[];+}++export interface CompressionEngineMetadata {+ id: string;+ name: string;+ description: string;+ inputScope: "messages" | "tool-results" | "mixed";+ targetLatencyMs: number;+ supportsPreview: boolean;+ stable: boolean;+}++export interface CompressionEngineApplyOptions {+ model?: string;+ supportsVision?: boolean | null;+ config?: CompressionConfig;+ compressionComboId?: string | null;+ stepConfig?: Record<string, unknown>;+}++export interface CompressionEngine {+ id: string;+ name: string;+ description: string;+ icon: string;+ targets: CompressionEngineTarget[];+ stackable: boolean;+ stackPriority: number;+ metadata: CompressionEngineMetadata;+ apply(body: Record<string, unknown>, options?: CompressionEngineApplyOptions): CompressionResult;+ compress(body: Record<string, unknown>, config?: Record<string, unknown>): CompressionResult;+ getConfigSchema(): EngineConfigField[];+ validateConfig(config: Record<string, unknown>): EngineValidationResult;+}++export interface EngineRegistryEntry {+ engine: CompressionEngine;+ enabled: boolean;+ config: Record<string, unknown>;+}diff --git a/open-sse/services/compression/index.ts b/open-sse/services/compression/index.tsindex 98578a1f70..7f16cd9f00 100644--- a/open-sse/services/compression/index.ts+++ b/open-sse/services/compression/index.ts@@ -5,6 +5,14 @@ export type {CompressionResult,CavemanConfig,CavemanRule,+ CavemanIntensity,+ CavemanOutputModeConfig,+ RtkConfig,+ RtkIntensity,+ RtkRawOutputRetention,+ CompressionEngineId,+ CompressionLanguageConfig,+ CompressionPipelineStep,AggressiveConfig,AgingThresholds,ToolStrategiesConfig,@@ -15,6 +23,9 @@ export type {export {DEFAULT_COMPRESSION_CONFIG,DEFAULT_CAVEMAN_CONFIG,+ DEFAULT_CAVEMAN_OUTPUT_MODE_CONFIG,+ DEFAULT_RTK_CONFIG,+ DEFAULT_COMPRESSION_LANGUAGE_CONFIG,DEFAULT_AGGRESSIVE_CONFIG,} from "./types.ts";@@ -28,8 +39,36 @@ 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 {+ getAvailableLanguagePacks,+ listCavemanRulePacks,+ loadAllRulesForLanguage,+ loadCavemanFileRules,+ loadRulePack,+ validateRulePack,+} from "./ruleLoader.ts";+export type { RulePackMetadata } from "./ruleLoader.ts";+export {+ detectCompressionLanguage,+ listSupportedCompressionLanguages,+} from "./languageDetector.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,@@ -44,8 +83,62 @@ export {applyCompression,checkComboOverride,shouldAutoTrigger,+ applyStackedCompression,} from "./strategySelector.ts";+export type {+ CompressionEngine,+ CompressionEngineApplyOptions,+ CompressionEngineMetadata,+ CompressionEngineTarget,+ EngineConfigField,+ EngineRegistryEntry,+ EngineValidationResult,+} from "./engines/types.ts";++export {+ registerEngine,+ registerCompressionEngine,+ unregisterCompressionEngine,+ getEngine,+ getEngineEntry,+ getCompressionEngine,+ listEngines,+ listCompressionEngines,+ listEnabledEngines,+ setEngineEnabled,+ updateEngineConfig,+ clearCompressionEngineRegistry,+} from "./engines/registry.ts";+export { registerBuiltinCompressionEngines } from "./engines/index.ts";++export { applyRtkCompression, processRtkText, rtkEngine } from "./engines/rtk/index.ts";+export {+ detectCommandFromText,+ detectCommandOutput,+ detectCommandType,+ type CommandDetectionResult,+} from "./engines/rtk/commandDetector.ts";+export {+ loadRtkFilters,+ getRtkFilterCatalog,+ matchRtkFilter,+ getRtkFilterLoadDiagnostics,+} from "./engines/rtk/filterLoader.ts";+export { runRtkFilterTests } from "./engines/rtk/verify.ts";+export {+ maybePersistRtkRawOutput,+ readRtkRawOutput,+ redactRtkRawOutput,+} from "./engines/rtk/rawOutput.ts";+export {+ detectCodeLanguage,+ normalizeCodeLanguage,+ stripCode,+ stripCodeComments,+} from "./engines/rtk/codeStripper.ts";+export type { CodeLanguage, CodeStripperOptions } from "./engines/rtk/codeStripper.ts";+export { RuleBasedSummarizer, createSummarizer } from "./summarizer.ts";export { compressToolResult } from "./toolResultCompressor.ts";diff --git a/open-sse/services/compression/languageDetector.ts b/open-sse/services/compression/languageDetector.tsnew file mode 100644index 0000000000..3b3aa9b002--- /dev/null+++ b/open-sse/services/compression/languageDetector.ts@@ -0,0 +1,18 @@+const LANGUAGE_HINTS: Record<string, RegExp[]> = {+ "pt-BR": [/\b(?:voce|você|preciso|arquivo|codigo|código|erro|falha|obrigado)\b/i],+ es: [/\b(?:necesito|archivo|codigo|código|error|fallo|gracias|puedes)\b/i],+ de: [/\b(?:ich|datei|fehler|bitte|kannst|konfiguration|danke)\b/i],+ fr: [/\b(?:fichier|erreur|merci|peux|configuration|besoin)\b/i],+ ja: [/[\u3040-\u30ff]/],+};++export function detectCompressionLanguage(text: string): string {+ for (const [language, patterns] of Object.entries(LANGUAGE_HINTS)) {+ if (patterns.some((pattern) => pattern.test(text))) return language;+ }+ return "en";+}++export function listSupportedCompressionLanguages(): string[] {+ return ["en", ...Object.keys(LANGUAGE_HINTS)];+}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..9f4e7bfe45--- /dev/null+++ b/open-sse/services/compression/outputMode.ts@@ -0,0 +1,161 @@+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_LANGUAGE = {+ en: {+ 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.",+ },+ "pt-BR": {+ lite: "Responda conciso. Remova enrolacao, cortesias e incerteza. Preserve termos tecnicos, codigo, erros, URLs e identificadores exatamente.",+ full: "Responda seco e compacto. Frases curtas OK. Preserve todo conteudo tecnico, codigo, erros, URLs e identificadores exatamente.",+ ultra:+ "Responda ultra compacto. Use prosa tecnica curta e abreviacoes comuns como DB/auth/config/req/res/fn. Nunca abrevie simbolos de codigo, APIs, erros, URLs ou identificadores.",+ },+ es: {+ lite: "Responde conciso. Quita relleno, cortesias y dudas. Conserva terminos tecnicos, codigo, errores, URLs e identificadores exactos.",+ full: "Responde seco y compacto. Fragmentos OK. Conserva todo el contenido tecnico, codigo, errores, URLs e identificadores exactos.",+ ultra:+ "Responde ultra compacto. Usa prosa tecnica corta y abreviaturas comunes como DB/auth/config/req/res/fn. Nunca abrevies simbolos de codigo, APIs, errores, URLs o identificadores.",+ },+ de: {+ lite: "Antworte knapp. Entferne Fuellwoerter, Hoeflichkeit und Unsicherheit. Bewahre Fachbegriffe, Code, Fehler, URLs und Bezeichner exakt.",+ full: "Antworte sehr knapp. Fragmente OK. Bewahre alle technischen Inhalte, Code, Fehler, URLs und Bezeichner exakt.",+ ultra:+ "Antworte ultra knapp. Nutze kurze technische Prosa und uebliche Abkuerzungen wie DB/auth/config/req/res/fn. Code-Symbole, APIs, Fehler, URLs und Bezeichner nie abkuerzen.",+ },+ fr: {+ lite: "Reponds concis. Retire remplissage, politesses et hesitations. Garde termes techniques, code, erreurs, URLs et identifiants exacts.",+ full: "Reponds tres compact. Fragments OK. Garde tout le contenu technique, code, erreurs, URLs et identifiants exacts.",+ ultra:+ "Reponds ultra compact. Utilise une prose technique courte et des abreviations communes comme DB/auth/config/req/res/fn. N'abrege jamais symboles de code, APIs, erreurs, URLs ou identifiants.",+ },+ ja: {+ lite: "簡潔に回答。冗長表現、挨拶、曖昧表現を削る。技術用語、コード、エラー、URL、識別子は正確に保持。",+ full: "短く圧縮して回答。断片文可。技術内容、コード、エラー、URL、識別子は正確に保持。",+ ultra:+ "超短く回答。DB/auth/config/req/res/fn など一般的な略語は可。コード記号、API名、エラー文字列、URL、識別子は省略しない。",+ },+} 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,+ language = "en"+): string {+ const intensity = config.intensity ?? "full";+ const instructions =+ CAVEMAN_INSTRUCTION_BY_LANGUAGE[language as keyof typeof CAVEMAN_INSTRUCTION_BY_LANGUAGE] ??+ CAVEMAN_INSTRUCTION_BY_LANGUAGE.en;+ return `${CAVEMAN_OUTPUT_MARKER}\n${instructions[intensity]}`;+}++export function applyCavemanOutputMode(+ body: ChatRequestBody,+ options?: Partial<CavemanOutputModeConfig>,+ language = "en"+): 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, language)}`,+ },+ 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, language);+ 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/ruleLoader.ts b/open-sse/services/compression/ruleLoader.tsnew file mode 100644index 0000000000..6bea11b030--- /dev/null+++ b/open-sse/services/compression/ruleLoader.ts@@ -0,0 +1,258 @@+import fs from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";+import type { CavemanIntensity, CavemanRule } from "./types.ts";++type CavemanRuleCategory = NonNullable<CavemanRule["category"]>;+type CavemanRuleContext = CavemanRule["context"];++interface FileRule {+ name: string;+ pattern: string;+ replacement?: string;+ replacementMap?: Record<string, string>;+ flags?: string;+ context?: CavemanRuleContext;+ category?: CavemanRuleCategory;+ minIntensity?: CavemanIntensity;+ description?: string;+}++interface RulePack {+ language: string;+ category: string;+ rules: FileRule[];+}++export interface RulePackMetadata {+ language: string;+ categories: string[];+ ruleCount: number;+}++const VALID_CONTEXTS = new Set(["all", "user", "system", "assistant"]);+const VALID_CATEGORIES = new Set(["filler", "context", "structural", "dedup", "terse", "ultra"]);+const VALID_INTENSITIES = new Set(["lite", "full", "ultra"]);+const cache = new Map<string, CavemanRule[]>();+let rulesDirCache: string | null = null;++function normalizeReplacementKey(value: string): string {+ return value.trim().replace(/\s+/g, " ").toLowerCase();+}++function compileReplacement(rule: FileRule): CavemanRule["replacement"] {+ if (!rule.replacementMap) return rule.replacement ?? "";++ const normalizedMap = new Map(+ Object.entries(rule.replacementMap).map(([key, value]) => [normalizeReplacementKey(key), value])+ );+ const fallback = rule.replacement;+ return (match: string) => {+ const normalized = normalizeReplacementKey(match);+ if (normalizedMap.has(normalized)) return normalizedMap.get(normalized) ?? "";+ return fallback ?? match;+ };+}++function getRuleFlags(rule: FileRule): string {+ return rule.flags ?? "gi";+}++function getRulesDir(): string {+ if (rulesDirCache) return rulesDirCache;+ const moduleDir = path.dirname(fileURLToPath(import.meta.url));+ const candidates = [+ path.join(moduleDir, "rules"),+ path.join(moduleDir, "..", "services", "compression", "rules"),+ path.join(process.cwd(), "open-sse", "services", "compression", "rules"),+ path.join(process.cwd(), "app", "open-sse", "services", "compression", "rules"),+ ];+ rulesDirCache =+ candidates.find((candidate, index) => {+ return candidates.indexOf(candidate) === index && fs.existsSync(candidate);+ }) ?? candidates[0];+ return rulesDirCache;+}++function compileRule(rule: FileRule, source: string): CavemanRule {+ try {+ const flags = getRuleFlags(rule);+ return {+ name: rule.name,+ pattern: new RegExp(rule.pattern, flags),+ replacement: compileReplacement(rule),+ context: rule.context ?? "all",+ category: rule.category ?? "filler",+ minIntensity: rule.minIntensity ?? "lite",+ description: rule.description,+ };+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ throw new Error(`Invalid Caveman rule pattern in ${source}:${rule.name}: ${message}`);+ }+}++export function validateRulePack(pack: unknown): { valid: boolean; errors: string[] } {+ const errors: string[] = [];+ if (!pack || typeof pack !== "object") {+ return { valid: false, errors: ["Rule pack must be an object"] };+ }++ const value = pack as Partial<RulePack>;+ if (typeof value.language !== "string" || !value.language.trim()) {+ errors.push("language must be a non-empty string");+ }+ if (typeof value.category !== "string" || !value.category.trim()) {+ errors.push("category must be a non-empty string");+ }+ if (!Array.isArray(value.rules)) {+ errors.push("rules must be an array");+ } else {+ value.rules.forEach((rule, index) => {+ if (!rule || typeof rule !== "object") {+ errors.push(`rules[${index}] must be an object`);+ return;+ }+ const entry = rule as Partial<FileRule>;+ const flags = typeof entry.flags === "string" ? entry.flags : "gi";+ if (typeof entry.name !== "string" || !entry.name.trim()) {+ errors.push(`rules[${index}].name must be a non-empty string`);+ }+ if (typeof entry.pattern !== "string" || !entry.pattern.trim()) {+ errors.push(`rules[${index}].pattern must be a non-empty string`);+ } else {+ try {+ new RegExp(entry.pattern, flags);+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ errors.push(`rules[${index}].pattern is invalid: ${message}`);+ }+ }+ if (entry.flags !== undefined && typeof entry.flags !== "string") {+ errors.push(`rules[${index}].flags must be a string`);+ }+ if (entry.replacement !== undefined && typeof entry.replacement !== "string") {+ errors.push(`rules[${index}].replacement must be a string`);+ }+ if (entry.replacementMap !== undefined) {+ if (+ !entry.replacementMap ||+ typeof entry.replacementMap !== "object" ||+ Array.isArray(entry.replacementMap)+ ) {+ errors.push(`rules[${index}].replacementMap must be an object`);+ } else {+ Object.entries(entry.replacementMap).forEach(([key, replacement]) => {+ if (!key.trim()) {+ errors.push(`rules[${index}].replacementMap contains an empty key`);+ }+ if (typeof replacement !== "string") {+ errors.push(`rules[${index}].replacementMap.${key} must be a string`);+ }+ });+ }+ }+ if (typeof entry.replacement !== "string" && entry.replacementMap === undefined) {+ errors.push(`rules[${index}] must define replacement or replacementMap`);+ }+ if (entry.context !== undefined && !VALID_CONTEXTS.has(entry.context)) {+ errors.push(`rules[${index}].context is invalid`);+ }+ if (entry.category !== undefined && !VALID_CATEGORIES.has(entry.category)) {+ errors.push(`rules[${index}].category is invalid`);+ }+ if (entry.minIntensity !== undefined && !VALID_INTENSITIES.has(entry.minIntensity)) {+ errors.push(`rules[${index}].minIntensity is invalid`);+ }+ });+ }+ return { valid: errors.length === 0, errors };+}++function readPack(language: string, category: string): RulePack | null {+ const filename = path.join(getRulesDir(), language, `${category}.json`);+ if (!fs.existsSync(filename)) return null;+ const parsed = JSON.parse(fs.readFileSync(filename, "utf8")) as unknown;+ const validation = validateRulePack(parsed);+ if (!validation.valid) {+ throw new Error(+ `Invalid Caveman rule pack ${language}/${category}: ${validation.errors.join("; ")}`+ );+ }+ return parsed as RulePack;+}++export function loadRulePack(+ language: string,+ category: string,+ options: { refresh?: boolean } = {}+): CavemanRule[] {+ const key = `${getRulesDir()}:${language}:${category}`;+ if (cache.has(key) && !options.refresh) return cache.get(key) ?? [];++ const pack = readPack(language, category);+ if (!pack) {+ cache.set(key, []);+ return [];+ }++ const rules = pack.rules.map((rule) => compileRule(rule, `${language}/${category}`));+ cache.set(key, rules);+ return rules;+}++export function loadAllRulesForLanguage(+ language: string,+ options: { refresh?: boolean } = {}+): CavemanRule[] {+ const key = `${getRulesDir()}:${language}:*`;+ if (cache.has(key) && !options.refresh) return cache.get(key) ?? [];++ const languageDir = path.join(getRulesDir(), language);+ if (!fs.existsSync(languageDir)) {+ cache.set(key, []);+ return [];+ }++ const rules = fs+ .readdirSync(languageDir)+ .filter((entry) => entry.endsWith(".json"))+ .sort()+ .flatMap((entry) => loadRulePack(language, path.basename(entry, ".json"), options));++ cache.set(key, rules);+ return rules;+}++export function getAvailableLanguagePacks(): RulePackMetadata[] {+ const root = getRulesDir();+ if (!fs.existsSync(root)) return [];++ return fs+ .readdirSync(root)+ .filter((entry) => fs.statSync(path.join(root, entry)).isDirectory())+ .map((language) => {+ const categories = fs+ .readdirSync(path.join(root, language))+ .filter((entry) => entry.endsWith(".json"))+ .map((entry) => path.basename(entry, ".json"))+ .sort();+ const ruleCount = categories.reduce(+ (count, category) => count + loadRulePack(language, category).length,+ 0+ );+ return { language, categories, ruleCount };+ })+ .sort((a, b) => a.language.localeCompare(b.language));+}++export function loadCavemanFileRules(+ language: string,+ options: { refresh?: boolean } = {}+): CavemanRule[] {+ return loadAllRulesForLanguage(language, options);+}++export function listCavemanRulePacks(): RulePackMetadata[] {+ return getAvailableLanguagePacks();+}diff --git a/open-sse/services/compression/rules/_schema.json b/open-sse/services/compression/rules/_schema.jsonnew file mode 100644index 0000000000..9ec4fc4724--- /dev/null+++ b/open-sse/services/compression/rules/_schema.json@@ -0,0 +1,31 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "title": "OmniRoute Caveman Rule Pack",+ "type": "object",+ "required": ["language", "category", "rules"],+ "properties": {+ "language": { "type": "string" },+ "category": { "type": "string" },+ "rules": {+ "type": "array",+ "items": {+ "type": "object",+ "required": ["name", "pattern"],+ "properties": {+ "name": { "type": "string" },+ "pattern": { "type": "string" },+ "flags": { "type": "string" },+ "replacement": { "type": "string" },+ "replacementMap": {+ "type": "object",+ "additionalProperties": { "type": "string" }+ },+ "context": { "enum": ["all", "user", "system", "assistant"] },+ "category": { "enum": ["filler", "context", "structural", "dedup", "terse", "ultra"] },+ "minIntensity": { "enum": ["lite", "full", "ultra"] },+ "description": { "type": "string" }+ }+ }+ }+ }+}diff --git a/open-sse/services/compression/rules/de/context.json b/open-sse/services/compression/rules/de/context.jsonnew file mode 100644index 0000000000..64173166bf--- /dev/null+++ b/open-sse/services/compression/rules/de/context.json@@ -0,0 +1,38 @@+{+ "language": "de",+ "category": "context",+ "rules": [+ {+ "name": "de_context_setup",+ "pattern": "\\b(?:hier ist der code|unten ist der code|dies ist der code)\\b\\s*[:.]?\\s*",+ "replacement": "Code:",+ "context": "user",+ "category": "context",+ "minIntensity": "lite"+ },+ {+ "name": "de_intent",+ "pattern": "\\b(?:mein ziel ist|was ich brauche ist|ich versuche|die idee ist)\\b\\s*",+ "replacement": "Ziel:",+ "context": "user",+ "category": "context",+ "minIntensity": "lite"+ },+ {+ "name": "de_question_directive",+ "pattern": "\\b(?:kannst du erklaeren warum|kannst du erklären warum|kannst du zeigen wie)\\b\\s*",+ "replacement": "Erklaere ",+ "context": "user",+ "category": "context",+ "minIntensity": "lite"+ },+ {+ "name": "de_background",+ "pattern": "\\b(?:wie du weisst|wie du weißt|wie bereits erwaehnt|wie bereits erwähnt)\\b[,.]?\\s*",+ "replacement": "",+ "context": "all",+ "category": "context",+ "minIntensity": "lite"+ }+ ]+}diff --git a/open-sse/services/compression/rules/de/filler.json b/open-sse/services/compression/rules/de/filler.jsonnew file mode 100644index 0000000000..f4f2e6eb62--- /dev/null+++ b/open-sse/services/compression/rules/de/filler.json@@ -0,0 +1,70 @@+{+ "language": "de",+ "category": "filler",+ "rules": [+ {+ "name": "de_polite_framing",+ "pattern": "\\b(?:bitte|kannst du|koenntest du|könntest du|ich moechte|ich möchte|ich brauche)\\b\\s*",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "de_pleasantries",+ "pattern": "\\b(?:hallo|guten morgen|guten tag|danke|vielen dank)\\b[,.!?\\s]*",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "de_hedging",+ "pattern": "\\b(?:ich denke dass|ich glaube dass|es scheint dass|vielleicht|wahrscheinlich|moeglicherweise|möglicherweise)\\b\\s*",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "de_filler_adverbs",+ "pattern": "\\b(?:grundsaetzlich|grundsätzlich|eigentlich|buchstaeblich|buchstäblich|einfach)\\b\\s*",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "de_self_reference",+ "pattern": "^(?:ich versuche|ich will|ich moechte|ich möchte|ich brauche)\\b\\s*",+ "replacement": "",+ "context": "user",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "de_verbose_request",+ "pattern": "\\b(?:kannst du erklaeren|kannst du erklären|koenntest du erklaeren|könntest du erklären)\\b\\s*",+ "replacement": "Erklaere ",+ "context": "user",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "de_qualifiers",+ "pattern": "\\b(?:ein bisschen|etwas|irgendwie|mehr oder weniger)\\b\\s*",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "de_softeners",+ "pattern": "\\b(?:wenn moeglich|wenn möglich|wenn du zeit hast|ohne eile)\\b[,.!?\\s]*",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ }+ ]+}diff --git a/open-sse/services/compression/rules/de/structural.json b/open-sse/services/compression/rules/de/structural.jsonnew file mode 100644index 0000000000..7107c977b3--- /dev/null+++ b/open-sse/services/compression/rules/de/structural.json@@ -0,0 +1,30 @@+{+ "language": "de",+ "category": "structural",+ "rules": [+ {+ "name": "de_purpose",+ "pattern": "\\b(?:um zu|mit dem ziel|damit ich)\\b\\s*",+ "replacement": "um ",+ "context": "all",+ "category": "structural",+ "minIntensity": "lite"+ },+ {+ "name": "de_connectors",+ "pattern": "\\b(?:ausserdem|außerdem|zusaetzlich|zusätzlich|darueber hinaus|darüber hinaus)\\b\\s*",+ "replacement": "auch ",+ "context": "all",+ "category": "structural",+ "minIntensity": "lite"+ },+ {+ "name": "de_emphasis",+ "pattern": "\\b(?:sehr|wirklich|extrem|ziemlich)\\s+(?=[a-zäöüß])",+ "replacement": "",+ "context": "all",+ "category": "structural",+ "minIntensity": "lite"+ }+ ]+}diff --git a/open-sse/services/compression/rules/en/context.json b/open-sse/services/compression/rules/en/context.jsonnew file mode 100644index 0000000000..70ef148408--- /dev/null+++ b/open-sse/services/compression/rules/en/context.json@@ -0,0 +1,88 @@+{+ "language": "en",+ "category": "context",+ "rules": [+ {+ "name": "compound_collapse",+ "pattern": "\\band any potential\\b",+ "replacement": "",+ "context": "all",+ "category": "context",+ "minIntensity": "full"+ },+ {+ "name": "explanatory_prefix",+ "pattern": "\\b(?:The function appears to be handling|The code seems to|The class is|This module is)\\b",+ "replacement": "Function:",+ "replacementMap": {+ "the function appears to be handling": "Function:",+ "the code seems to": "Code:",+ "the class is": "Class:",+ "this module is": "Module:"+ },+ "context": "all",+ "category": "context",+ "minIntensity": "lite"+ },+ {+ "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*",+ "replacement": "Explain why ",+ "replacementMap": {+ "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 "+ },+ "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*",+ "replacement": "Code:",+ "context": "user",+ "category": "context",+ "minIntensity": "lite"+ },+ {+ "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*",+ "replacement": "Goal:",+ "context": "user",+ "category": "context",+ "minIntensity": "lite"+ },+ {+ "name": "background_removal",+ "pattern": "\\b(?:As you may know,?\\s*|As we discussed earlier,?\\s*)",+ "replacement": "",+ "context": "all",+ "category": "context",+ "minIntensity": "lite"+ },+ {+ "name": "meta_commentary",+ "pattern": "^(?:Note that|Keep in mind that|Remember that)\\b\\s*",+ "replacement": "",+ "context": "all",+ "category": "context",+ "minIntensity": "lite"+ },+ {+ "name": "purpose_statement",+ "pattern": "\\b(?:for the purpose of|with the goal of|in an effort to|for every)\\b",+ "replacement": "for",+ "replacementMap": {+ "for the purpose of": "for",+ "with the goal of": "to",+ "in an effort to": "to",+ "for every": "per"+ },+ "context": "all",+ "category": "context",+ "minIntensity": "lite"+ }+ ]+}diff --git a/open-sse/services/compression/rules/en/dedup.json b/open-sse/services/compression/rules/en/dedup.jsonnew file mode 100644index 0000000000..23f0820bfe--- /dev/null+++ b/open-sse/services/compression/rules/en/dedup.json@@ -0,0 +1,38 @@+{+ "language": "en",+ "category": "dedup",+ "rules": [+ {+ "name": "repeated_context",+ "pattern": "\\b(?:As we discussed earlier|As mentioned before|As previously stated|As I said before)\\b[,.]?\\s*",+ "replacement": "See above. ",+ "context": "all",+ "category": "dedup",+ "minIntensity": "lite"+ },+ {+ "name": "repeated_question",+ "pattern": "\\b(?:Same question as before|I asked this earlier|This is the same question)\\b[,.]?\\s*",+ "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*",+ "replacement": "Re: ",+ "context": "all",+ "category": "dedup",+ "minIntensity": "lite"+ },+ {+ "name": "summary_replacement",+ "pattern": "\\b(?:To summarize what we've discussed|In summary of our conversation|To recap)\\b[,.]?\\s*",+ "replacement": "Summary: ",+ "context": "assistant",+ "category": "dedup",+ "minIntensity": "lite"+ }+ ]+}diff --git a/open-sse/services/compression/rules/en/filler.json b/open-sse/services/compression/rules/en/filler.jsonnew file mode 100644index 0000000000..88e4a6978a--- /dev/null+++ b/open-sse/services/compression/rules/en/filler.json@@ -0,0 +1,129 @@+{+ "language": "en",+ "category": "filler",+ "rules": [+ {+ "name": "pleasantries",+ "pattern": "(?<!make\\s)(?<!be\\s)\\b(?:i'?d be happy to|i would be happy to|i'?d be glad to|i would be glad to|glad to help|happy to|thank you|thanks|no problem|you'?re welcome|absolutely|certainly|of course|sure)\\b[,.!?\\s]*",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "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*",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "hedging",+ "pattern": "\\b(?:it seems like|it appears that|I think that|I believe that|probably|possibly|maybe it)\\b\\s*",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "verbose_instructions",+ "pattern": "\\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",+ "replacement": "explain ",+ "replacementMap": {+ "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 ",+ "create a thorough": "create ",+ "explain in detail": "explain "+ },+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "filler_adverbs",+ "pattern": "(?<![a-z])\\b(?:basically|essentially|actually|literally|simply|currently)\\b\\s*",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "filler_phrases",+ "pattern": "^(?:I want to|I need to|I'd like to|I'm looking for)\\b\\s*",+ "replacement": "",+ "context": "user",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "redundant_openers",+ "pattern": "^(?:Hi there|Hello|Good morning|Hey)\\s*[,.!?\\s]?\\s*",+ "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*",+ "replacement": "",+ "context": "user",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "self_reference",+ "pattern": "^(?:I am trying to|I am working on|I have been)\\b\\s*",+ "replacement": "",+ "context": "user",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "excessive_gratitude",+ "pattern": "\\b(?:Thank you so much|Thanks in advance|I really appreciate)\\b[,.!?\\s]*",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "qualifier_removal",+ "pattern": "\\b(?:a bit|a little|somewhat|kind of|sort of)\\b\\s*",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "softeners",+ "pattern": "\\b(?:if possible|when you get a chance|at your convenience|just wondering)\\b[,.!?\\s]*",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "uncertainty_fillers",+ "pattern": "\\b(?:I guess|I suppose|more or less|in a way)\\b\\s*",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "assistant_fillers",+ "pattern": "^(?:Here'?s|Below is|This is)\\s+(?:a|an|the)?\\s*",+ "replacement": "",+ "context": "assistant",+ "category": "filler",+ "minIntensity": "lite"+ }+ ]+}diff --git a/open-sse/services/compression/rules/en/structural.json b/open-sse/services/compression/rules/en/structural.jsonnew file mode 100644index 0000000000..b71f2c64bc--- /dev/null+++ b/open-sse/services/compression/rules/en/structural.json@@ -0,0 +1,102 @@+{+ "language": "en",+ "category": "structural",+ "rules": [+ {+ "name": "redundant_phrasing",+ "pattern": "\\b(?:make sure to|be sure to)\\b\\s*",+ "replacement": "ensure ",+ "context": "all",+ "category": "structural",+ "minIntensity": "full"+ },+ {+ "name": "redundant_because",+ "pattern": "\\b(?:due to the fact that|the reason is because)\\b\\s*",+ "replacement": "because ",+ "context": "all",+ "category": "structural",+ "minIntensity": "full"+ },+ {+ "name": "redundant_directive",+ "pattern": "\\b(?:it is important to|you should|remember to)\\b\\s*",+ "replacement": "",+ "context": "all",+ "category": "structural",+ "minIntensity": "full"+ },+ {+ "name": "list_conjunction",+ "pattern": ",\\s*and also\\s+|,\\s*as well as\\s+",+ "replacement": ", ",+ "context": "all",+ "category": "structural",+ "minIntensity": "full"+ },+ {+ "name": "purpose_phrases",+ "pattern": "\\b(?:in order to|so as to)\\b\\s*",+ "replacement": "to ",+ "context": "all",+ "category": "structural",+ "minIntensity": "lite"+ },+ {+ "name": "redundant_quantifiers",+ "pattern": "\\b(?:each and every single|each and every)\\b",+ "replacement": "each",+ "context": "all",+ "category": "structural",+ "minIntensity": "full"+ },+ {+ "name": "all_quantifier",+ "pattern": "\\bany and all\\b",+ "replacement": "all",+ "context": "all",+ "category": "structural",+ "minIntensity": "full"+ },+ {+ "name": "verbose_connectors",+ "pattern": "\\b(?:furthermore|additionally|moreover|in addition)\\b\\s*",+ "replacement": "also ",+ "context": "all",+ "category": "structural",+ "minIntensity": "lite"+ },+ {+ "name": "transition_removal",+ "pattern": "^(?:On the other hand,?\\s*|In contrast,?\\s*|However,?\\s*)",+ "replacement": "",+ "context": "all",+ "category": "structural",+ "minIntensity": "lite"+ },+ {+ "name": "emphasis_removal",+ "pattern": "\\b(?:very|really|extremely|highly|quite)\\s+(?=[a-z])",+ "replacement": "",+ "context": "all",+ "category": "structural",+ "minIntensity": "lite"+ },+ {+ "name": "passive_voice",+ "pattern": "\\b(?:is being used|is being called|is being generated|was created|was generated|was implemented)\\b",+ "replacement": "uses",+ "replacementMap": {+ "is being used": "uses",+ "is being called": "calls",+ "is being generated": "generated",+ "was created": "created",+ "was generated": "generated",+ "was implemented": "implemented"+ },+ "context": "all",+ "category": "structural",+ "minIntensity": "full"+ }+ ]+}diff --git a/open-sse/services/compression/rules/en/ultra.json b/open-sse/services/compression/rules/en/ultra.jsonnew file mode 100644index 0000000000..1e085d7607--- /dev/null+++ b/open-sse/services/compression/rules/en/ultra.json@@ -0,0 +1,107 @@+{+ "language": "en",+ "category": "ultra",+ "rules": [+ {+ "name": "articles",+ "pattern": "\\b(?:[Aa]n|[Aa]|[Tt]he)\\s+(?=[a-z])",+ "flags": "g",+ "replacement": "",+ "context": "all",+ "category": "terse",+ "minIntensity": "full"+ },+ {+ "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])",+ "replacement": "",+ "context": "all",+ "category": "terse",+ "minIntensity": "full"+ },+ {+ "name": "ultra_abbreviations",+ "pattern": "\\bdatabase\\b",+ "replacement": "DB",+ "context": "all",+ "category": "ultra",+ "minIntensity": "ultra"+ },+ {+ "name": "ultra_config_abbreviation",+ "pattern": "\\bconfiguration\\b",+ "replacement": "config",+ "context": "all",+ "category": "ultra",+ "minIntensity": "ultra"+ },+ {+ "name": "ultra_function_abbreviation",+ "pattern": "\\bfunction\\b",+ "replacement": "fn",+ "context": "all",+ "category": "ultra",+ "minIntensity": "ultra"+ },+ {+ "name": "ultra_request_abbreviation",+ "pattern": "\\brequest\\b",+ "replacement": "req",+ "context": "all",+ "category": "ultra",+ "minIntensity": "ultra"+ },+ {+ "name": "ultra_response_abbreviation",+ "pattern": "\\bresponse\\b",+ "replacement": "res",+ "context": "all",+ "category": "ultra",+ "minIntensity": "ultra"+ },+ {+ "name": "ultra_implementation_abbreviation",+ "pattern": "\\bimplementation\\b",+ "replacement": "impl",+ "context": "all",+ "category": "ultra",+ "minIntensity": "ultra"+ },+ {+ "name": "ultra_authentication_abbreviation",+ "pattern": "\\bauthentication\\b",+ "replacement": "auth",+ "context": "all",+ "category": "ultra",+ "minIntensity": "ultra"+ },+ {+ "name": "ultra_authorization_abbreviation",+ "pattern": "\\bauthorization\\b",+ "replacement": "authz",+ "context": "all",+ "category": "ultra",+ "minIntensity": "ultra"+ },+ {+ "name": "ultra_application_abbreviation",+ "pattern": "\\bapplication\\b",+ "replacement": "app",+ "context": "all",+ "category": "ultra",+ "minIntensity": "ultra"+ },+ {+ "name": "ultra_dependency_abbreviation",+ "pattern": "\\b(?:dependency|dependencies)\\b",+ "replacement": "dep",+ "replacementMap": {+ "dependency": "dep",+ "dependencies": "deps"+ },+ "context": "all",+ "category": "ultra",+ "minIntensity": "ultra"+ }+ ]+}diff --git a/open-sse/services/compression/rules/es/context.json b/open-sse/services/compression/rules/es/context.jsonnew file mode 100644index 0000000000..980da607a7--- /dev/null+++ b/open-sse/services/compression/rules/es/context.json@@ -0,0 +1,38 @@+{+ "language": "es",+ "category": "context",+ "rules": [+ {+ "name": "es_context_setup",+ "pattern": "\\b(?:aqui esta el codigo|aquí está el código|debajo esta el codigo|este es el codigo|este es el código)\\b\\s*[:.]?\\s*",+ "replacement": "Código:",+ "context": "user",+ "category": "context",+ "minIntensity": "lite"+ },+ {+ "name": "es_intent",+ "pattern": "\\b(?:mi objetivo es|lo que necesito es|lo que intento hacer es|la idea es)\\b\\s*",+ "replacement": "Objetivo:",+ "context": "user",+ "category": "context",+ "minIntensity": "lite"+ },+ {+ "name": "es_question_directive",+ "pattern": "\\b(?:puedes explicar por que|puedes explicar por qué|puedes mostrar como|puedes mostrar cómo)\\b\\s*",+ "replacement": "Explica ",+ "context": "user",+ "category": "context",+ "minIntensity": "lite"+ },+ {+ "name": "es_background",+ "pattern": "\\b(?:como sabes|como mencionamos antes|como dije antes)\\b[,.]?\\s*",+ "replacement": "",+ "context": "all",+ "category": "context",+ "minIntensity": "lite"+ }+ ]+}diff --git a/open-sse/services/compression/rules/es/filler.json b/open-sse/services/compression/rules/es/filler.jsonnew file mode 100644index 0000000000..dee16e9e56--- /dev/null+++ b/open-sse/services/compression/rules/es/filler.json@@ -0,0 +1,70 @@+{+ "language": "es",+ "category": "filler",+ "rules": [+ {+ "name": "es_polite_framing",+ "pattern": "\\b(?:por favor|podrias|podrías|puedes|me gustaria que|me gustaría que|necesito que)\\b\\s*",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "es_pleasantries",+ "pattern": "\\b(?:hola|buenos dias|buenos días|buenas tardes|gracias|muchas gracias)\\b[,.!?\\s]*",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "es_hedging",+ "pattern": "\\b(?:creo que|me parece que|parece que|tal vez|probablemente|posiblemente)\\b\\s*",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "es_filler_adverbs",+ "pattern": "\\b(?:basicamente|básicamente|esencialmente|en realidad|literalmente|simplemente)\\b\\s*",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "es_self_reference",+ "pattern": "^(?:estoy intentando|quiero|necesito|me gustaria|me gustaría)\\b\\s*",+ "replacement": "",+ "context": "user",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "es_verbose_request",+ "pattern": "\\b(?:podrias explicarme|podrías explicarme|puedes explicar|podrias detallar|podrías detallar)\\b\\s*",+ "replacement": "Explica ",+ "context": "user",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "es_qualifiers",+ "pattern": "\\b(?:un poco|algo asi|algo así|mas o menos|más o menos|de alguna manera)\\b\\s*",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "es_softeners",+ "pattern": "\\b(?:si es posible|cuando puedas|sin prisa|solo queria|sólo quería)\\b[,.!?\\s]*",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ }+ ]+}diff --git a/open-sse/services/compression/rules/es/structural.json b/open-sse/services/compression/rules/es/structural.jsonnew file mode 100644index 0000000000..f1d2454043--- /dev/null+++ b/open-sse/services/compression/rules/es/structural.json@@ -0,0 +1,30 @@+{+ "language": "es",+ "category": "structural",+ "rules": [+ {+ "name": "es_purpose",+ "pattern": "\\b(?:con el fin de|con el objetivo de|para poder)\\b\\s*",+ "replacement": "para ",+ "context": "all",+ "category": "structural",+ "minIntensity": "lite"+ },+ {+ "name": "es_connectors",+ "pattern": "\\b(?:ademas|además|adicionalmente|por otra parte)\\b\\s*",+ "replacement": "también ",+ "context": "all",+ "category": "structural",+ "minIntensity": "lite"+ },+ {+ "name": "es_emphasis",+ "pattern": "\\b(?:muy|realmente|extremadamente|bastante)\\s+(?=[a-záéíóúñ])",+ "replacement": "",+ "context": "all",+ "category": "structural",+ "minIntensity": "lite"+ }+ ]+}diff --git a/open-sse/services/compression/rules/fr/context.json b/open-sse/services/compression/rules/fr/context.jsonnew file mode 100644index 0000000000..78721d4fb2--- /dev/null+++ b/open-sse/services/compression/rules/fr/context.json@@ -0,0 +1,38 @@+{+ "language": "fr",+ "category": "context",+ "rules": [+ {+ "name": "fr_context_setup",+ "pattern": "\\b(?:voici le code|ci dessous le code|ci-dessous le code|ceci est le code)\\b\\s*[:.]?\\s*",+ "replacement": "Code:",+ "context": "user",+ "category": "context",+ "minIntensity": "lite"+ },+ {+ "name": "fr_intent",+ "pattern": "\\b(?:mon objectif est|ce dont j'ai besoin est|j'essaie de|l'idee est|l'idée est)\\b\\s*",+ "replacement": "Objectif:",+ "context": "user",+ "category": "context",+ "minIntensity": "lite"+ },+ {+ "name": "fr_question_directive",+ "pattern": "\\b(?:peux tu expliquer pourquoi|peux tu montrer comment|pourrais tu montrer comment)\\b\\s*",+ "replacement": "Explique ",+ "context": "user",+ "category": "context",+ "minIntensity": "lite"+ },+ {+ "name": "fr_background",+ "pattern": "\\b(?:comme tu le sais|comme mentionne avant|comme mentionné avant)\\b[,.]?\\s*",+ "replacement": "",+ "context": "all",+ "category": "context",+ "minIntensity": "lite"+ }+ ]+}diff --git a/open-sse/services/compression/rules/fr/filler.json b/open-sse/services/compression/rules/fr/filler.jsonnew file mode 100644index 0000000000..61a2caa40f--- /dev/null+++ b/open-sse/services/compression/rules/fr/filler.json@@ -0,0 +1,70 @@+{+ "language": "fr",+ "category": "filler",+ "rules": [+ {+ "name": "fr_polite_framing",+ "pattern": "\\b(?:s'il vous plait|s'il te plait|peux tu|pourrais tu|je voudrais que|j'ai besoin que)\\b\\s*",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "fr_pleasantries",+ "pattern": "\\b(?:bonjour|salut|bonsoir|merci|merci beaucoup)\\b[,.!?\\s]*",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "fr_hedging",+ "pattern": "\\b(?:je pense que|je crois que|il semble que|peut etre|peut-être|probablement|possiblement)\\b\\s*",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "fr_filler_adverbs",+ "pattern": "\\b(?:fondamentalement|essentiellement|en fait|litteralement|littéralement|simplement)\\b\\s*",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "fr_self_reference",+ "pattern": "^(?:j'essaie de|je veux|je voudrais|j'ai besoin de)\\b\\s*",+ "replacement": "",+ "context": "user",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "fr_verbose_request",+ "pattern": "\\b(?:peux tu expliquer|pourrais tu expliquer|peux tu detailler|peux tu détailler)\\b\\s*",+ "replacement": "Explique ",+ "context": "user",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "fr_qualifiers",+ "pattern": "\\b(?:un peu|en quelque sorte|plus ou moins|d'une certaine maniere|d'une certaine manière)\\b\\s*",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "fr_softeners",+ "pattern": "\\b(?:si possible|quand tu peux|sans urgence|je voulais juste)\\b[,.!?\\s]*",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ }+ ]+}diff --git a/open-sse/services/compression/rules/fr/structural.json b/open-sse/services/compression/rules/fr/structural.jsonnew file mode 100644index 0000000000..f59ac1d05d--- /dev/null+++ b/open-sse/services/compression/rules/fr/structural.json@@ -0,0 +1,30 @@+{+ "language": "fr",+ "category": "structural",+ "rules": [+ {+ "name": "fr_purpose",+ "pattern": "\\b(?:afin de|dans le but de|pour pouvoir)\\b\\s*",+ "replacement": "pour ",+ "context": "all",+ "category": "structural",+ "minIntensity": "lite"+ },+ {+ "name": "fr_connectors",+ "pattern": "\\b(?:de plus|en outre|additionnellement|par ailleurs)\\b\\s*",+ "replacement": "aussi ",+ "context": "all",+ "category": "structural",+ "minIntensity": "lite"+ },+ {+ "name": "fr_emphasis",+ "pattern": "\\b(?:tres|très|vraiment|extremement|extrêmement|assez)\\s+(?=[a-zàâçéèêëîïôûùüÿñæœ])",+ "replacement": "",+ "context": "all",+ "category": "structural",+ "minIntensity": "lite"+ }+ ]+}diff --git a/open-sse/services/compression/rules/ja/context.json b/open-sse/services/compression/rules/ja/context.jsonnew file mode 100644index 0000000000..e081dd8e59--- /dev/null+++ b/open-sse/services/compression/rules/ja/context.json@@ -0,0 +1,38 @@+{+ "language": "ja",+ "category": "context",+ "rules": [+ {+ "name": "ja_context_setup",+ "pattern": "(?:以下のコード|こちらのコード|このコード)",+ "replacement": "コード:",+ "context": "user",+ "category": "context",+ "minIntensity": "lite"+ },+ {+ "name": "ja_intent",+ "pattern": "(?:目的は|ゴールは|必要なのは)",+ "replacement": "目的:",+ "context": "user",+ "category": "context",+ "minIntensity": "lite"+ },+ {+ "name": "ja_question_directive",+ "pattern": "(?:なぜ.*説明|どうやって.*示し)",+ "replacement": "説明:",+ "context": "user",+ "category": "context",+ "minIntensity": "lite"+ },+ {+ "name": "ja_background",+ "pattern": "(?:ご存じの通り|前述の通り|先ほど述べたように)",+ "replacement": "",+ "context": "all",+ "category": "context",+ "minIntensity": "lite"+ }+ ]+}diff --git a/open-sse/services/compression/rules/ja/filler.json b/open-sse/services/compression/rules/ja/filler.jsonnew file mode 100644index 0000000000..c7143b3f3d--- /dev/null+++ b/open-sse/services/compression/rules/ja/filler.json@@ -0,0 +1,70 @@+{+ "language": "ja",+ "category": "filler",+ "rules": [+ {+ "name": "ja_polite_framing",+ "pattern": "(?:お願いします|してください|できますか|いただけますか)",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "ja_pleasantries",+ "pattern": "(?:こんにちは|こんばんは|おはようございます|ありがとうございます)",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "ja_hedging",+ "pattern": "(?:と思います|かもしれません|たぶん|おそらく)",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "ja_filler_adverbs",+ "pattern": "(?:基本的に|本質的に|実際には|単純に)",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "ja_self_reference",+ "pattern": "(?:私は|自分は|やりたいことは)",+ "replacement": "",+ "context": "user",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "ja_verbose_request",+ "pattern": "(?:説明していただけますか|詳しく説明してください|教えてください)",+ "replacement": "説明:",+ "context": "user",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "ja_qualifiers",+ "pattern": "(?:少し|ちょっと|なんとなく|ある程度)",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "ja_softeners",+ "pattern": "(?:可能であれば|時間があれば|急ぎではありません)",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ }+ ]+}diff --git a/open-sse/services/compression/rules/ja/structural.json b/open-sse/services/compression/rules/ja/structural.jsonnew file mode 100644index 0000000000..41c650c97b--- /dev/null+++ b/open-sse/services/compression/rules/ja/structural.json@@ -0,0 +1,30 @@+{+ "language": "ja",+ "category": "structural",+ "rules": [+ {+ "name": "ja_purpose",+ "pattern": "(?:するために|目的として)",+ "replacement": "ため ",+ "context": "all",+ "category": "structural",+ "minIntensity": "lite"+ },+ {+ "name": "ja_connectors",+ "pattern": "(?:さらに|加えて|その上)",+ "replacement": "また ",+ "context": "all",+ "category": "structural",+ "minIntensity": "lite"+ },+ {+ "name": "ja_emphasis",+ "pattern": "(?:非常に|とても|かなり)",+ "replacement": "",+ "context": "all",+ "category": "structural",+ "minIntensity": "lite"+ }+ ]+}diff --git a/open-sse/services/compression/rules/pt-BR/context.json b/open-sse/services/compression/rules/pt-BR/context.jsonnew file mode 100644index 0000000000..c0f8ed6538--- /dev/null+++ b/open-sse/services/compression/rules/pt-BR/context.json@@ -0,0 +1,38 @@+{+ "language": "pt-BR",+ "category": "context",+ "rules": [+ {+ "name": "pt_context_setup",+ "pattern": "\\b(?:segue o codigo|segue o código|abaixo esta o codigo|abaixo está o código|este e o codigo|este é o código)\\b\\s*[:.]?\\s*",+ "replacement": "Código:",+ "context": "user",+ "category": "context",+ "minIntensity": "lite"+ },+ {+ "name": "pt_intent",+ "pattern": "\\b(?:o que eu quero fazer e|o que eu quero fazer é|meu objetivo e|meu objetivo é|a ideia e|a ideia é)\\b\\s*",+ "replacement": "Objetivo:",+ "context": "user",+ "category": "context",+ "minIntensity": "lite"+ },+ {+ "name": "pt_question_directive",+ "pattern": "\\b(?:voce pode explicar por que|você pode explicar por que|pode mostrar como|poderia mostrar como)\\b\\s*",+ "replacement": "Explique ",+ "context": "user",+ "category": "context",+ "minIntensity": "lite"+ },+ {+ "name": "pt_background",+ "pattern": "\\b(?:como voce sabe|como você sabe|como falamos antes|como mencionei antes)\\b[,.]?\\s*",+ "replacement": "",+ "context": "all",+ "category": "context",+ "minIntensity": "lite"+ }+ ]+}diff --git a/open-sse/services/compression/rules/pt-BR/filler.json b/open-sse/services/compression/rules/pt-BR/filler.jsonnew file mode 100644index 0000000000..a9ce881656--- /dev/null+++ b/open-sse/services/compression/rules/pt-BR/filler.json@@ -0,0 +1,70 @@+{+ "language": "pt-BR",+ "category": "filler",+ "rules": [+ {+ "name": "pt_polite_framing",+ "pattern": "\\b(?:por favor|por gentileza|poderia|voce pode|você pode|eu gostaria que|preciso que)\\b\\s*",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "pt_pleasantries",+ "pattern": "\\b(?:ola|olá|oi|bom dia|boa tarde|boa noite|obrigado|obrigada|valeu)\\b[,.!?\\s]*",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "pt_hedging",+ "pattern": "\\b(?:eu acho que|eu acredito que|parece que|talvez|provavelmente|possivelmente)\\b\\s*",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "pt_filler_adverbs",+ "pattern": "\\b(?:basicamente|essencialmente|na verdade|literalmente|simplesmente|atualmente)\\b\\s*",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "pt_self_reference",+ "pattern": "^(?:eu estou tentando|estou tentando|eu quero|eu preciso|gostaria de)\\b\\s*",+ "replacement": "",+ "context": "user",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "pt_verbose_request",+ "pattern": "\\b(?:voce poderia me explicar|você poderia me explicar|poderia detalhar|gostaria que voce explicasse|gostaria que você explicasse)\\b\\s*",+ "replacement": "Explique ",+ "context": "user",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "pt_qualifiers",+ "pattern": "\\b(?:um pouco|meio que|tipo assim|de certa forma|mais ou menos)\\b\\s*",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ },+ {+ "name": "pt_softeners",+ "pattern": "\\b(?:se possivel|se possível|quando puder|sem pressa|so queria|só queria)\\b[,.!?\\s]*",+ "replacement": "",+ "context": "all",+ "category": "filler",+ "minIntensity": "lite"+ }+ ]+}diff --git a/open-sse/services/compression/rules/pt-BR/structural.json b/open-sse/services/compression/rules/pt-BR/structural.jsonnew file mode 100644index 0000000000..8144ef2b6e--- /dev/null+++ b/open-sse/services/compression/rules/pt-BR/structural.json@@ -0,0 +1,30 @@+{+ "language": "pt-BR",+ "category": "structural",+ "rules": [+ {+ "name": "pt_purpose",+ "pattern": "\\b(?:a fim de|com o objetivo de|para poder)\\b\\s*",+ "replacement": "para ",+ "context": "all",+ "category": "structural",+ "minIntensity": "lite"+ },+ {+ "name": "pt_connectors",+ "pattern": "\\b(?:alem disso|além disso|adicionalmente|outrossim)\\b\\s*",+ "replacement": "também ",+ "context": "all",+ "category": "structural",+ "minIntensity": "lite"+ },+ {+ "name": "pt_emphasis",+ "pattern": "\\b(?:muito|realmente|extremamente|bastante)\\s+(?=[a-záéíóúâêôãõç])",+ "replacement": "",+ "context": "all",+ "category": "structural",+ "minIntensity": "lite"+ }+ ]+}diff --git a/open-sse/services/compression/stats.ts b/open-sse/services/compression/stats.tsindex 1d2a64f4fc..9e2845cfcd 100644--- a/open-sse/services/compression/stats.ts+++ b/open-sse/services/compression/stats.ts@@ -4,6 +4,8 @@ import {type CompressionConfig,DEFAULT_COMPRESSION_CONFIG,DEFAULT_CAVEMAN_CONFIG,+ DEFAULT_RTK_CONFIG,+ DEFAULT_COMPRESSION_LANGUAGE_CONFIG,} from "./types.ts";const CHARS_PER_TOKEN = 4;@@ -54,5 +56,7 @@ export function getDefaultCompressionConfig(): CompressionConfig {return {...DEFAULT_COMPRESSION_CONFIG,cavemanConfig: { ...DEFAULT_CAVEMAN_CONFIG },+ rtkConfig: { ...DEFAULT_RTK_CONFIG },+ languageConfig: { ...DEFAULT_COMPRESSION_LANGUAGE_CONFIG },};}diff --git a/open-sse/services/compression/strategySelector.ts b/open-sse/services/compression/strategySelector.tsindex 59164c8ce9..37bc9782ce 100644--- a/open-sse/services/compression/strategySelector.ts+++ b/open-sse/services/compression/strategySelector.ts@@ -1,9 +1,18 @@-import type { CompressionConfig, CompressionMode, CompressionResult } from "./types.ts";+import type {+ CompressionConfig,+ CompressionMode,+ CompressionPipelineStep,+ CompressionResult,+ CompressionStats,+} from "./types.ts";import { applyLiteCompression } from "./lite.ts";import { cavemanCompress } from "./caveman.ts";import { compressAggressive } from "./aggressive.ts";import { ultraCompress } from "./ultra.ts";import { createCompressionStats } from "./stats.ts";+import { registerBuiltinCompressionEngines } from "./engines/index.ts";+import { getCompressionEngine } from "./engines/registry.ts";+import { applyRtkCompression } from "./engines/rtk/index.ts";import {detectCachingContext,getCacheAwareStrategy,@@ -32,7 +41,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 +74,38 @@ 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 === "rtk") {+ return applyRtkCompression(body, {+ config: options?.config?.rtkConfig,+ });+ }+ if (mode === "stacked") {+ return applyStackedCompression(body, options?.config?.stackedPipeline, options);}if (mode === "standard") {- return cavemanCompress(- body as Parameters<typeof cavemanCompress>[0],- options?.config?.cavemanConfig- );+ const cavemanConfig = {+ ...(options?.config?.cavemanConfig ?? {}),+ ...(options?.config?.languageConfig?.enabled+ ? {+ language: options.config.languageConfig.defaultLanguage,+ autoDetectLanguage: options.config.languageConfig.autoDetect,+ enabledLanguagePacks: options.config.languageConfig.enabledPacks,+ }+ : {}),+ ...(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 +116,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 +144,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,@@ -125,3 +165,114 @@ export function applyCompression(}return { body, compressed: false, stats: null };}++function normalizePipelineStep(step: CompressionPipelineStep | string): CompressionPipelineStep {+ if (typeof step !== "string") return step;+ if (step === "standard") return { engine: "caveman" };+ if (step === "rtk") return { engine: "rtk" };+ if (step === "lite" || step === "aggressive" || step === "ultra") return { engine: step };+ return { engine: "caveman" };+}++export function applyStackedCompression(+ body: Record<string, unknown>,+ pipeline?: Array<CompressionPipelineStep | string>,+ options?: {+ model?: string;+ supportsVision?: boolean | null;+ config?: CompressionConfig;+ compressionComboId?: string | null;+ }+): CompressionResult {+ const steps =+ pipeline && pipeline.length > 0+ ? pipeline.map(normalizePipelineStep)+ : [+ { engine: "rtk" as const, intensity: "standard" as const },+ { engine: "caveman" as const, intensity: "full" as const },+ ];+ registerBuiltinCompressionEngines();++ let currentBody = body;+ let compressed = false;+ const techniques = new Set<string>();+ const rules = new Set<string>();+ const breakdown: NonNullable<CompressionStats["engineBreakdown"]> = [];+ const rtkRawOutputPointers: NonNullable<CompressionStats["rtkRawOutputPointers"]> = [];+ const validationWarnings = new Set<string>();+ const validationErrors = new Set<string>();+ let fallbackApplied = false;+ const start = performance.now();++ for (const step of steps) {+ const engine = getCompressionEngine(step.engine);+ if (!engine) continue;+ const result = engine.apply(currentBody, {+ ...options,+ compressionComboId: options?.compressionComboId ?? options?.config?.compressionComboId,+ stepConfig: {+ ...(step.config ?? {}),+ ...(step.intensity ? { intensity: step.intensity } : {}),+ },+ });+ if (result.stats) {+ result.stats.techniquesUsed.forEach((technique) => techniques.add(technique));+ result.stats.rulesApplied?.forEach((rule) => rules.add(rule));+ result.stats.rtkRawOutputPointers?.forEach((pointer) => {+ rtkRawOutputPointers.push(pointer);+ });+ result.stats.validationWarnings?.forEach((warning) => validationWarnings.add(warning));+ result.stats.validationErrors?.forEach((error) => validationErrors.add(error));+ fallbackApplied = fallbackApplied || result.stats.fallbackApplied === true;+ breakdown.push({+ engine: step.engine,+ originalTokens: result.stats.originalTokens,+ compressedTokens: result.stats.compressedTokens,+ savingsPercent: result.stats.savingsPercent,+ techniquesUsed: result.stats.techniquesUsed,+ ...(result.stats.rulesApplied ? { rulesApplied: result.stats.rulesApplied } : {}),+ ...(result.stats.durationMs !== undefined ? { durationMs: result.stats.durationMs } : {}),+ });+ }+ if (result.compressed) {+ currentBody = result.body;+ compressed = true;+ }+ }++ const stats = createCompressionStats(+ body,+ currentBody,+ "stacked",+ Array.from(techniques),+ rules.size > 0 ? Array.from(rules) : undefined,+ Math.round((performance.now() - start) * 100) / 100+ );+ stats.engine = "stacked";+ stats.compressionComboId =+ options?.compressionComboId ?? options?.config?.compressionComboId ?? null;+ stats.engineBreakdown = breakdown;+ if (validationWarnings.size > 0) {+ stats.validationWarnings = Array.from(validationWarnings);+ }+ if (validationErrors.size > 0) {+ stats.validationErrors = Array.from(validationErrors);+ }+ if (fallbackApplied) {+ stats.fallbackApplied = true;+ }+ if (rtkRawOutputPointers.length > 0) {+ const seenPointers = new Set<string>();+ stats.rtkRawOutputPointers = rtkRawOutputPointers.filter((pointer) => {+ if (seenPointers.has(pointer.id)) return false;+ seenPointers.add(pointer.id);+ return true;+ });+ }++ return {+ body: currentBody,+ compressed,+ stats,+ };+}diff --git a/open-sse/services/compression/types.ts b/open-sse/services/compression/types.tsindex f019f62bc6..abe842fb35 100644--- a/open-sse/services/compression/types.ts+++ b/open-sse/services/compression/types.ts@@ -1,14 +1,26 @@/**- * Compression Pipeline Types — Phase 1 (Lite) + Phase 2 (Standard/Caveman) + Phase 3 (Aggressive) + Phase 4 (Ultra)+ * Compression Pipeline Types — Lite, Caveman, Aggressive, Ultra, RTK, and Stacked modes.** Shared type definitions for the compression pipeline.* Phase 1: 'off' and 'lite' modes.* Phase 2: 'standard' mode (caveman engine).* Phase 3: 'aggressive' mode (summarization + tool compression + aging).* Phase 4: 'ultra' mode (heuristic token pruning + optional SLM tier).+ * Phase 5: 'rtk' and 'stacked' modes (tool-output filters + multi-engine pipeline).*/-export type CompressionMode = "off" | "lite" | "standard" | "aggressive" | "ultra";+export type CompressionMode =+ | "off"+ | "lite"+ | "standard"+ | "aggressive"+ | "ultra"+ | "rtk"+ | "stacked";+export type CavemanIntensity = "lite" | "full" | "ultra";+export type RtkIntensity = "minimal" | "standard" | "aggressive";+export type RtkRawOutputRetention = "never" | "failures" | "always";+export type CompressionEngineId = "lite" | "caveman" | "aggressive" | "ultra" | "rtk";export interface CavemanRule {name: string;@@ -16,6 +28,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 +39,63 @@ export interface CavemanConfig {skipRules: string[];minMessageLength: number;preservePatterns: string[];+ intensity: CavemanIntensity;+ language?: string;+ autoDetectLanguage?: boolean;+ enabledLanguagePacks?: string[];+}++export interface CavemanOutputModeConfig {+ enabled: boolean;+ intensity: CavemanIntensity;+ autoClarity: boolean;+}++export interface RtkConfig {+ enabled: boolean;+ intensity: RtkIntensity;+ applyToToolResults: boolean;+ applyToCodeBlocks: boolean;+ applyToAssistantMessages: boolean;+ enabledFilters: string[];+ disabledFilters: string[];+ maxLinesPerResult: number;+ maxCharsPerResult: number;+ deduplicateThreshold: number;+ customFiltersEnabled: boolean;+ trustProjectFilters: boolean;+ rawOutputRetention: RtkRawOutputRetention;+ rawOutputMaxBytes: number;+}++export interface CompressionLanguageConfig {+ enabled: boolean;+ defaultLanguage: string;+ autoDetect: boolean;+ enabledPacks: string[];+}++export interface CompressionPipelineStep {+ engine: CompressionEngineId;+ intensity?: CavemanIntensity | RtkIntensity;+ config?: Record<string, unknown>;}export interface CompressionConfig {enabled: boolean;defaultMode: CompressionMode;+ autoTriggerMode?: CompressionMode;autoTriggerTokens: number;cacheMinutes: number;preserveSystemPrompt: boolean;+ mcpDescriptionCompressionEnabled?: boolean;comboOverrides: Record<string, CompressionMode>;+ compressionComboId?: string | null;+ stackedPipeline?: CompressionPipelineStep[];cavemanConfig?: CavemanConfig;+ cavemanOutputMode?: CavemanOutputModeConfig;+ rtkConfig?: RtkConfig;+ languageConfig?: CompressionLanguageConfig;aggressive?: AggressiveConfig;ultra?: UltraConfig;}@@ -44,14 +106,42 @@ export interface CompressionStats {savingsPercent: number;techniquesUsed: string[];mode: CompressionMode;+ engine?: string;+ compressionComboId?: string | null;timestamp: number;rulesApplied?: string[];durationMs?: number;+ validationWarnings?: string[];+ validationErrors?: string[];+ fallbackApplied?: boolean;+ preservedBlockCount?: number;+ rtkRawOutputPointers?: Array<{+ id: string;+ path: string;+ bytes: number;+ sha256: string;+ redacted: boolean;+ }>;+ realUsage?: {+ promptTokens?: number;+ completionTokens?: number;+ totalTokens?: number;+ source: "provider" | "estimated" | "stream";+ };aggressive?: {summarizerSavings: number;toolResultSavings: number;agingSavings: number;};+ engineBreakdown?: Array<{+ engine: string;+ originalTokens: number;+ compressedTokens: number;+ savingsPercent: number;+ techniquesUsed: string[];+ rulesApplied?: string[];+ durationMs?: number;+ }>;}export interface CompressionResult {@@ -63,10 +153,17 @@ export interface CompressionResult {export const DEFAULT_COMPRESSION_CONFIG: CompressionConfig = {enabled: false,defaultMode: "off",+ autoTriggerMode: "lite",autoTriggerTokens: 0,cacheMinutes: 5,preserveSystemPrompt: true,+ mcpDescriptionCompressionEnabled: true,comboOverrides: {},+ compressionComboId: null,+ stackedPipeline: [+ { engine: "rtk", intensity: "standard" },+ { engine: "caveman", intensity: "full" },+ ],};export const DEFAULT_CAVEMAN_CONFIG: CavemanConfig = {@@ -75,6 +172,37 @@ 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,+};++export const DEFAULT_RTK_CONFIG: RtkConfig = {+ enabled: true,+ intensity: "standard",+ applyToToolResults: true,+ applyToCodeBlocks: false,+ applyToAssistantMessages: false,+ enabledFilters: [],+ disabledFilters: [],+ maxLinesPerResult: 120,+ maxCharsPerResult: 12000,+ deduplicateThreshold: 3,+ customFiltersEnabled: true,+ trustProjectFilters: false,+ rawOutputRetention: "never",+ rawOutputMaxBytes: 1_048_576,+};++export const DEFAULT_COMPRESSION_LANGUAGE_CONFIG: CompressionLanguageConfig = {+ enabled: false,+ defaultLanguage: "en",+ autoDetect: true,+ enabledPacks: ["en"],};/** Aging thresholds for progressive message degradation (Phase 3) */@@ -101,6 +229,7 @@ export interface AggressiveConfig {summarizerEnabled: boolean;maxTokensPerMessage: number;minSavingsThreshold: number;+ preserveSystemPrompt?: boolean;}/** Options for the Summarizer interface (Phase 3) */@@ -159,6 +288,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..7f2ae31115--- /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]{1,1000}\]\([^)[ \t\n]{1,2000}(?:[ \t]+"[^"]{0,1000}")?\)/g),+ compressed,+ errors+ );+ requireExactPresence("frontmatter", collectFrontmatter(original), compressed, errors);+ requireExactPresence("heading", collectMatches(original, /^#{1,6}\s+.+$/gm), compressed, errors);+ requireExactPresence(+ "table row",+ collectMatches(original, /^[ \t]*\|(?:[^|\n]{0,1000}\|){1,100}[ \t]*$/gm),+ compressed,+ errors+ );+ requireExactPresence(+ "math block",+ collectMatches(original, /\$\$[\s\S]{0,10000}?\$\$/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*]{1,50}\}[\s\S]{0,10000}?\\end\{[A-Za-z*]{1,50}\}/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/services/responsesInputSanitizer.ts b/open-sse/services/responsesInputSanitizer.tsnew file mode 100644index 0000000000..31a540feb8--- /dev/null+++ b/open-sse/services/responsesInputSanitizer.ts@@ -0,0 +1,36 @@+type JsonRecord = Record<string, unknown>;++function toRecord(value: unknown): JsonRecord | null {+ return value && typeof value === "object" && !Array.isArray(value) ? (value as JsonRecord) : null;+}++function isResponsesMessageItem(record: JsonRecord): boolean {+ return record.type === "message" || (!record.type && typeof record.role === "string");+}++export function isInternalAssistantMessage(record: JsonRecord): boolean {+ if (!isResponsesMessageItem(record)) return false;+ if (record.role !== "assistant") return false;++ const phase = typeof record.phase === "string" ? record.phase.trim().toLowerCase() : "";+ if (!phase) return false;++ // OpenCode can send assistant-side commentary/analysis frames in Responses+ // shape. Those frames are local runtime state, not durable conversation turns.+ return phase !== "final";+}++export function sanitizeResponsesInputItems(items: readonly unknown[], clone = true): unknown[] {+ const sanitized: unknown[] = [];++ for (const item of items) {+ const record = toRecord(item);+ if (record && isInternalAssistantMessage(record)) {+ continue;+ }++ sanitized.push(clone ? structuredClone(item) : item);+ }++ return sanitized;+}diff --git a/open-sse/services/responsesToolCallState.ts b/open-sse/services/responsesToolCallState.tsindex 5160f02ec2..9ded2ecefe 100644--- a/open-sse/services/responsesToolCallState.ts+++ b/open-sse/services/responsesToolCallState.ts@@ -1,3 +1,5 @@+import { sanitizeResponsesInputItems } from "./responsesInputSanitizer.ts";+type JsonRecord = Record<string, unknown>;type RememberedFunctionCall = {@@ -28,36 +30,8 @@ function toRecord(value: unknown): JsonRecord | null {return value && typeof value === "object" && !Array.isArray(value) ? (value as JsonRecord) : null;}-function isResponsesMessageItem(record: JsonRecord): boolean {- return record.type === "message" || (!record.type && typeof record.role === "string");-}--function isInternalAssistantMessage(record: JsonRecord): boolean {- if (!isResponsesMessageItem(record)) return false;- if (record.role !== "assistant") return false;-- const phase = typeof record.phase === "string" ? record.phase.trim().toLowerCase() : "";- if (!phase) return false;-- // OpenCode can send assistant-side commentary/analysis frames in Responses- // shape. Those frames are local runtime state, not durable conversation turns- // for Codex replay. Re-injecting them makes the model continue hidden notes.- return phase !== "final";-}-function sanitizeRememberedConversationItems(items: readonly unknown[]): unknown[] {- const sanitized: unknown[] = [];-- for (const item of items) {- const record = toRecord(item);- if (record && isInternalAssistantMessage(record)) {- continue;- }-- sanitized.push(structuredClone(item));- }-- return sanitized;+ return sanitizeResponsesInputItems(items);}function cleanupRememberedResponseToolCalls(now: number = Date.now()) {diff --git a/open-sse/services/tokenRefresh.ts b/open-sse/services/tokenRefresh.tsindex 0b9edc7bfc..5001730875 100755--- a/open-sse/services/tokenRefresh.ts+++ b/open-sse/services/tokenRefresh.ts@@ -13,6 +13,11 @@ const CACHE_SECRET = "omniroute-token-cache";// Key: "provider:sha256(refreshToken)" → Value: Promise<result>const refreshPromiseCache = new Map();+// Per-connection mutex: prevents parallel OAuth refresh for rotating tokens.+// Key: connectionId → Value: { promise, waiters }+// Primary dedup when credentials.connectionId is present; refreshPromiseCache is fallback.+const connectionRefreshMutex = new Map();+type RefreshLogger = {info?: (tag: string, message: string, data?: Record<string, unknown>) => void;warn?: (tag: string, message: string, data?: Record<string, unknown>) => void;@@ -415,8 +420,8 @@ export async function refreshQwenToken(refreshToken, log, proxyConfig: unknown =/*** Specialized refresh for Codex (OpenAI) OAuth tokens.* OpenAI uses rotating (one-time-use) refresh tokens.- * Returns { error: 'refresh_token_reused' } when the token has already been consumed,- * so callers can stop retrying and request re-authentication.+ * Returns { error: 'unrecoverable_refresh_error', code } when the token has already been+ * consumed or is invalid, so callers can stop retrying and request re-authentication.*/export async function refreshCodexToken(refreshToken, log, proxyConfig: unknown = null) {try {@@ -831,9 +836,18 @@ export function isUnrecoverableRefreshError(result) {/*** Get access token for a specific provider (with deduplication).- * If a refresh is already in-flight for the same provider+token,- * subsequent calls share the existing promise instead of making- * parallel OAuth requests.+ *+ * Deduplication strategy (two layers):+ * 1. Per-connection mutex (primary): if credentials.connectionId is present, all concurrent+ * callers for that connection share one in-flight promise regardless of which token they+ * loaded. This prevents refresh_token_reused errors with rotating (one-time-use) tokens,+ * e.g. Codex/OpenAI, where callers that loaded credentials at different times may hold+ * different token strings but refer to the same connection.+ * 2. Token-hash fallback: if no connectionId, dedup by provider+sha256(refreshToken) as before.+ *+ * Additionally, when connectionId is present, the stale-token check reads the DB to detect+ * whether another process already refreshed the token. If the DB token is still valid it is+ * returned immediately without a new upstream call.*/export async function getAccessToken(provider, credentials, log, proxyConfig: unknown = null) {if (!credentials || !credentials.refreshToken || typeof credentials.refreshToken !== "string") {@@ -841,6 +855,57 @@ export async function getAccessToken(provider, credentials, log, proxyConfig: unreturn null;}+ const connectionId = credentials.connectionId;++ // ── Layer 1: per-connection mutex ──────────────────────────────────────────+ if (connectionId && typeof connectionId === "string") {+ const existing = connectionRefreshMutex.get(connectionId);+ if (existing) {+ existing.waiters++;+ log?.info?.("TOKEN_REFRESH", "Concurrent refresh detected — sharing in-flight refresh", {+ provider,+ connectionId,+ waiters: existing.waiters,+ });+ return existing.promise;+ }++ const entry = { promise: null, waiters: 0 };+ entry.promise = _getAccessTokenWithStalenessCheck(+ provider,+ credentials,+ log,+ proxyConfig+ ).finally(() => {+ connectionRefreshMutex.delete(connectionId);+ });+ connectionRefreshMutex.set(connectionId, entry);+ return entry.promise;+ }++ // ── Layer 2: token-hash fallback (no connectionId) ─────────────────────────+ const cacheKey = getRefreshCacheKey(provider, credentials.refreshToken);++ if (refreshPromiseCache.has(cacheKey)) {+ log?.info?.("TOKEN_REFRESH", `Reusing in-flight refresh for ${provider}`);+ return refreshPromiseCache.get(cacheKey);+ }++ const refreshPromise = _getAccessTokenInternal(provider, credentials, log, proxyConfig).finally(+ () => {+ refreshPromiseCache.delete(cacheKey);+ }+ );++ refreshPromiseCache.set(cacheKey, refreshPromise);+ return refreshPromise;+}++/**+ * Internal helper: performs the DB staleness check then calls the actual refresh.+ * Only called from the per-connection mutex path (Layer 1 above).+ */+async function _getAccessTokenWithStalenessCheck(provider, credentials, log, proxyConfig) {// RACE CONDITION PREVENTION:// If the credentials object in memory is stale (e.g. it waited in a semaphore while another// request refreshed the token), using its OLD refreshToken will cause the provider (e.g. OpenAI)@@ -886,23 +951,7 @@ export async function getAccessToken(provider, credentials, log, proxyConfig: un}}- const cacheKey = getRefreshCacheKey(provider, credentials.refreshToken);-- // If a refresh is already in-flight, reuse it- if (refreshPromiseCache.has(cacheKey)) {- log?.info?.("TOKEN_REFRESH", `Reusing in-flight refresh for ${provider}`);- return refreshPromiseCache.get(cacheKey);- }-- // Start a new refresh and cache the promise- const refreshPromise = _getAccessTokenInternal(provider, credentials, log, proxyConfig).finally(- () => {- refreshPromiseCache.delete(cacheKey);- }- );-- refreshPromiseCache.set(cacheKey, refreshPromise);- return refreshPromise;+ return _getAccessTokenInternal(provider, credentials, log, proxyConfig);}/**@@ -1036,6 +1085,18 @@ export function isProviderBlocked(provider: string): boolean {return false;}+/**+ * Get active per-connection mutex entries (for diagnostics/metrics).+ * Returns a snapshot of connections that have an in-flight refresh and their waiter count.+ */+export function getConnectionRefreshMutexStatus(): Record<string, { waiters: number }> {+ const result: Record<string, { waiters: number }> = {};+ for (const [connectionId, entry] of connectionRefreshMutex.entries()) {+ result[connectionId] = { waiters: entry.waiters };+ }+ return result;+}+/*** Get circuit breaker status for all providers (for diagnostics).*/diff --git a/open-sse/translator/request/claude-to-openai.ts b/open-sse/translator/request/claude-to-openai.tsindex 8f890fd31c..fdf6687512 100644--- a/open-sse/translator/request/claude-to-openai.ts+++ b/open-sse/translator/request/claude-to-openai.ts@@ -5,6 +5,21 @@ import { adjustMaxTokens } from "../helpers/maxTokensHelper.ts";type JsonRecord = Record<string, unknown>;const TOOL_CHOICE_ANY = ["a", "n", "y"].join("");+/**+ * Normalize tool input schema for OpenAI compatibility.+ * OpenAI strict mode requires `properties: {}` on object-type schemas,+ * even for zero-argument tools. Anthropic/MCP tools may omit it (#1898).+ */+function normalizeToolSchema(schema: unknown): Record<string, unknown> {+ const fallback = { type: "object", properties: {} };+ if (!schema || typeof schema !== "object" || Array.isArray(schema)) return fallback;+ const s = schema as Record<string, unknown>;+ if (s.type === "object" && !s.properties) {+ return { ...s, properties: {} };+ }+ return s;+}+function normalizeOpenAIReasoningEffort(effort: unknown): string | undefined {if (typeof effort !== "string") return undefined;const normalized = effort.toLowerCase();@@ -86,7 +101,7 @@ export function claudeToOpenAIRequest(model, body, stream) {function: {name,description: typeof tool.description === "string" ? tool.description : "", // fix: never null (#276)- parameters: tool.input_schema || { type: "object", properties: {} },+ parameters: normalizeToolSchema(tool.input_schema),},};})diff --git a/open-sse/translator/response/openai-responses.ts b/open-sse/translator/response/openai-responses.tsindex 77289dfb71..07ff889385 100644--- a/open-sse/translator/response/openai-responses.ts+++ b/open-sse/translator/response/openai-responses.ts@@ -827,6 +827,9 @@ export function openaiResponsesToOpenAIResponse(chunk, state) {if (eventType === "response.reasoning_summary_text.delta") {const reasoningDelta = data.delta || "";if (!reasoningDelta) return null;+ const reasoningDeltaShape = state.copilotCompatibleReasoning+ ? { reasoning_text: reasoningDelta }+ : { reasoning: { summary: reasoningDelta } };return {id: state.chatId,object: "chat.completion.chunk",@@ -835,7 +838,7 @@ export function openaiResponsesToOpenAIResponse(chunk, state) {choices: [{index: 0,- delta: { reasoning: { summary: reasoningDelta } },+ delta: reasoningDeltaShape,finish_reason: null,},],diff --git a/open-sse/utils/aiSdkCompat.ts b/open-sse/utils/aiSdkCompat.tsindex 91d284bfc1..58ff08b738 100644--- a/open-sse/utils/aiSdkCompat.ts+++ b/open-sse/utils/aiSdkCompat.ts@@ -22,7 +22,9 @@ export function resolveStreamFlag(bodyStream: unknown, acceptHeader: unknown): b// Explicit body value always winsif (bodyStream === true) return true;if (bodyStream === false) return false;- // No explicit stream param — fall back to Accept header heuristic++ // 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/open-sse/utils/stream.ts b/open-sse/utils/stream.tsindex 111fd1095d..b75acecf51 100644--- a/open-sse/utils/stream.ts+++ b/open-sse/utils/stream.ts@@ -134,6 +134,7 @@ type StreamOptions = {targetFormat?: string;sourceFormat?: string;clientResponseFormat?: string | null;+ copilotCompatibleReasoning?: boolean;provider?: string | null;reqLogger?: StreamLogger | null;toolNameMap?: unknown;@@ -150,6 +151,7 @@ type TranslateState = ReturnType<typeof initState> & {toolNameMap?: unknown;usage?: unknown;finishReason?: unknown;+ copilotCompatibleReasoning?: boolean;/** Accumulated message content for call log response body */accumulatedContent?: string;upstreamError?: {@@ -531,6 +533,7 @@ export function createSSEStream(options: StreamOptions = {}) {targetFormat,sourceFormat,clientResponseFormat = null,+ copilotCompatibleReasoning = false,provider = null,reqLogger = null,toolNameMap = null,@@ -563,6 +566,7 @@ export function createSSEStream(options: StreamOptions = {}) {...(initState(sourceFormat) as TranslateState),provider,toolNameMap,+ copilotCompatibleReasoning,accumulatedContent: "",}: null;@@ -1904,7 +1908,8 @@ export function createSSETransformStreamWithLogger(body: unknown = null,onComplete: ((payload: StreamCompletePayload) => void) | null = null,apiKeyInfo: unknown = null,- onFailure: ((payload: StreamFailurePayload) => void | Promise<void>) | null = null+ onFailure: ((payload: StreamFailurePayload) => void | Promise<void>) | null = null,+ copilotCompatibleReasoning = false) {return createSSEStream({mode: STREAM_MODE.TRANSLATE,@@ -1919,6 +1924,7 @@ export function createSSETransformStreamWithLogger(body,onComplete,onFailure,+ copilotCompatibleReasoning,});}diff --git a/open-sse/utils/streamHelpers.ts b/open-sse/utils/streamHelpers.tsindex 7221cd1035..2146f8cccd 100644--- a/open-sse/utils/streamHelpers.ts+++ b/open-sse/utils/streamHelpers.ts@@ -45,6 +45,7 @@ export function hasValuableContent(chunk, format) {if (typeof delta.content === "string" && delta.content.length > 0) return true;if (typeof delta.reasoning_content === "string" && delta.reasoning_content.length > 0)return true;+ if (typeof delta.reasoning_text === "string" && delta.reasoning_text.length > 0) return true;if (Array.isArray(delta.tool_calls) && delta.tool_calls.length > 0) return true;if (chunk.choices[0].finish_reason) return true;if (typeof delta.role === "string" && delta.role.length > 0) return true;diff --git a/package-lock.json b/package-lock.jsonindex 0fc3bcf712..8753eccd38 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "omniroute",- "version": "3.7.8",+ "version": "3.7.9","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "omniroute",- "version": "3.7.8",+ "version": "3.7.9","hasInstallScript": true,"license": "MIT","workspaces": [@@ -79,6 +79,7 @@"husky": "^9.1.7","jsdom": "^29.0.1","lint-staged": "^16.2.7",+ "node-loader": "^2.1.0","prettier": "^3.8.1","tailwindcss": "^4","typescript": "^6.0.2",@@ -5569,6 +5570,16 @@"require-from-string": "^2.0.2"}},+ "node_modules/big.js": {+ "version": "5.2.2",+ "resolved": "https://registry.npmjs.org/big.js/-/big.js-5.2.2.tgz",+ "integrity": "sha512-vyL2OymJxmarO8gxMr0mhChsO9QGwhynfuu4+MHTAW6czfq9humCB7rKpUjDd9YUiDPU4mzpyupFSvOClAwbmQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "*"+ }+ },"node_modules/bindings": {"version": "1.5.0","resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz",@@ -6773,6 +6784,16 @@"dev": true,"license": "MIT"},+ "node_modules/emojis-list": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/emojis-list/-/emojis-list-3.0.0.tgz",+ "integrity": "sha512-/kyM18EfinwXZbno9FyUGeFh87KC8HRQBQGildHZbEuRyWFOmv1U10o9BBp8XVZDVNNuQKyIGIu5ZYAAXJ0V2Q==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">= 4"+ }+ },"node_modules/encodeurl": {"version": "2.0.0","resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",@@ -10080,6 +10101,21 @@"dev": true,"license": "MIT"},+ "node_modules/loader-utils": {+ "version": "2.0.4",+ "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-2.0.4.tgz",+ "integrity": "sha512-xXqpXoINfFhgua9xiqD8fPFHgkoq1mmmpE92WlDbm9rNRd/EbRb+Gqf908T2DMfuHjjJlksiK2RbHVOdD/MqSw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "big.js": "^5.2.2",+ "emojis-list": "^3.0.0",+ "json5": "^2.1.2"+ },+ "engines": {+ "node": ">=8.9.0"+ }+ },"node_modules/locate-path": {"version": "6.0.0","resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz",@@ -11260,6 +11296,26 @@"url": "https://github.com/sponsors/ljharb"}},+ "node_modules/node-loader": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/node-loader/-/node-loader-2.1.0.tgz",+ "integrity": "sha512-OwjPkyh8+7jW8DMd/iq71uU1Sspufr/C2+c3t0p08J3CrM9ApZ4U53xuisNrDXOHyGi5OYHgtfmmh+aK9zJA6g==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "loader-utils": "^2.0.3"+ },+ "engines": {+ "node": ">= 10.13.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/webpack"+ },+ "peerDependencies": {+ "webpack": "^5.0.0"+ }+ },"node_modules/node-machine-id": {"version": "1.1.12","resolved": "https://registry.npmjs.org/node-machine-id/-/node-machine-id-1.1.12.tgz",@@ -15206,7 +15262,7 @@},"open-sse": {"name": "@omniroute/open-sse",- "version": "3.7.8"+ "version": "3.7.9"}}}diff --git a/package.json b/package.jsonindex a971888c4a..12d4fc61f0 100644--- a/package.json+++ b/package.json@@ -1,7 +1,7 @@{"name": "omniroute",- "version": "3.7.8",- "description": "Smart AI Router with auto fallback — route to FREE & cheap models, zero downtime. Works with Cursor, Cline, Claude Desktop, Codex, and any OpenAI-compatible tool.",+ "version": "3.7.9",+ "description": "Unified AI router with 160+ providers, RTK+Caveman compression, auto fallback, MCP/A2A, desktop, PWA, and OpenAI-compatible APIs.","type": "module","bin": {"omniroute": "bin/omniroute.mjs",@@ -174,6 +174,7 @@"husky": "^9.1.7","jsdom": "^29.0.1","lint-staged": "^16.2.7",+ "node-loader": "^2.1.0","prettier": "^3.8.1","tailwindcss": "^4","typescript": "^6.0.2",diff --git a/pr_metadata.json b/pr_metadata.jsonnew file mode 100644index 0000000000..37ad0c69a5--- /dev/null+++ b/pr_metadata.json@@ -0,0 +1,2102 @@+[+ {+ "additions": 149,+ "author": {+ "id": "MDQ6VXNlcjM1NzM4Ng==",+ "is_bot": false,+ "login": "andrewmunsell",+ "name": "Andrew Munsell"+ },+ "baseRefName": "main",+ "body": "## Summary\r\n\r\n- Add tokens_compressed INTEGER column to call_logs (migration 041)\r\n- Capture compression savings from both legacy compressContext() and modular applyCompression() pipelines in chatCore.ts\r\n- Display inline ↓N purple badge in log list view tokens cell\r\n- Show \"Compressed: FROM → TO (-X%)\" badge in detail modal Input section\r\n- Bump CallLogArtifact schemaVersion from 4 to 5\r\n\r\n<img width=\"1840\" height=\"844\" alt=\"CleanShot 2026-05-03 at 20 17 14@2x\" src=\"https://github.com/user-attachments/assets/b8f9b623-0615-4bd3-b71a-1810eb6e41c4\" />\r\n<img width=\"2620\" height=\"1010\" alt=\"CleanShot 2026-05-03 at 20 17 18@2x\" src=\"https://github.com/user-attachments/assets/58ebb33b-e7cb-417a-909e-99d9d58375b2\" />\r\n\r\n## Tests Added Or Updated\r\n\r\n- Add compression tokens unit tests\r\n",+ "createdAt": "2026-05-04T03:48:16Z",+ "deletions": 7,+ "files": [+ {+ "path": "open-sse/handlers/chatCore.ts",+ "additions": 7,+ "deletions": 0,+ "changeType": "MODIFIED"+ },+ {+ "path": "src/i18n/messages/en.json",+ "additions": 1,+ "deletions": 0,+ "changeType": "MODIFIED"+ },+ {+ "path": "src/lib/db/core.ts",+ "additions": 4,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "src/lib/db/migrationRunner.ts",+ "additions": 2,+ "deletions": 0,+ "changeType": "MODIFIED"+ },+ {+ "path": "src/lib/db/migrations/041_compression_tokens.sql",+ "additions": 4,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "src/lib/usage/callLogArtifacts.ts",+ "additions": 2,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "src/lib/usage/callLogs.ts",+ "additions": 8,+ "deletions": 3,+ "changeType": "MODIFIED"+ },+ {+ "path": "src/lib/usage/migrations.ts",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "src/shared/components/RequestLoggerDetail.tsx",+ "additions": 10,+ "deletions": 0,+ "changeType": "MODIFIED"+ },+ {+ "path": "src/shared/components/RequestLoggerV2.tsx",+ "additions": 11,+ "deletions": 0,+ "changeType": "MODIFIED"+ },+ {+ "path": "tests/unit/call-log-cap.test.ts",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "tests/unit/compression-tokens.test.ts",+ "additions": 98,+ "deletions": 0,+ "changeType": "ADDED"+ }+ ],+ "headRefName": "emdash/indicate-compression-in-logs-use9w",+ "number": 1923,+ "title": "feat(logs): show compression tokens in request log UI"+ },+ {+ "additions": 1698,+ "author": {+ "id": "MDQ6VXNlcjE0OTIxOTgz",+ "is_bot": false,+ "login": "oyi77",+ "name": "Paijo"+ },+ "baseRefName": "release/v3.7.9",+ "body": "Adds automated model assessment, categorization, and self-healing system for omniroute combos.\n\n## The Problem\nWhen providers fail (rate limits, auth errors, model deprecation), combos silently degrade. Our production experience: 2+ hours manually testing models and updating 44 combos because most returned errors.\n\n## The Solution\nThree new domain modules:\n1. **Assessor** - Probes every provider/model pair (quick/standard/deep tiers)\n2. **Categorizer** - Classifies models by capability with fitness scores\n3. **SelfHealer** - Auto-fixes combos: removes dead models, reduces weights for rate-limited, emergency-adds working alternatives\n\n## New Files\n- src/domain/assessment/assessor.ts\n- src/domain/assessment/categorizer.ts\n- src/domain/assessment/selfHealer.ts\n- src/domain/assessment/types.ts\n- src/domain/assessment/migration.ts\n- src/domain/assessment/index.ts\n- src/app/api/assess/route.ts\n- docs/RFC-AUTO-ASSESSMENT.md (full RFC)\n\n## New DB Tables\n- model_assessments, assessment_runs, combo_health, heal_actions\n\n## API\nPOST /api/assess/models - Run assessment\nGET /api/assess/models?action=working - Get working models\nGET /api/assess/models?action=combo-health - Get combo health\n\n> [!NOTE]\n> **OmniRoute Maintainer Note:** This PR has been deferred and will be accepted and redirected for the `v4.0.0` (or greater) release cycle. Please skip this PR during `v3.x` stabilization reviews.",+ "createdAt": "2026-05-03T20:53:04Z",+ "deletions": 0,+ "files": [+ {+ "path": "docs/RFC-AUTO-ASSESSMENT.md",+ "additions": 518,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "src/app/api/assess/route.ts",+ "additions": 110,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "src/domain/assessment/assessor.ts",+ "additions": 206,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "src/domain/assessment/categorizer.ts",+ "additions": 118,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "src/domain/assessment/index.ts",+ "additions": 24,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "src/domain/assessment/migration.ts",+ "additions": 109,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "src/domain/assessment/selfHealer.ts",+ "additions": 261,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "src/domain/assessment/types.ts",+ "additions": 352,+ "deletions": 0,+ "changeType": "ADDED"+ }+ ],+ "headRefName": "feat/auto-assessment-engine",+ "number": 1918,+ "title": "feat: Auto-Assessment and Self-Healing Combo Engine"+ },+ {+ "additions": 22666,+ "author": {+ "id": "MDQ6VXNlcjgwMTY4NDE=",+ "is_bot": false,+ "login": "diegosouzapw",+ "name": "Diego Rodrigues de Sa e Souza"+ },+ "baseRefName": "main",+ "body": "### ✨ New Features\n\n- **feat(compression):** major upgrade to Caveman and RTK compression pipelines (#1876, #1889):\n - Add RTK tool-output compression, stacked Caveman + RTK pipelines, compression combo assignments, dashboard context pages, MCP management tools, and language-aware Caveman rule packs.\n - Expand RTK parity with a 39-filter catalog, RTK-style JSON DSL stages, inline verify/benchmark coverage, trust-gated custom filters, expanded command detection, and redacted raw-output recovery.\n - Expose rule intensities, track USD savings, unify config validation, and persist MCP savings.\n - Expand Caveman parity and MCP metadata compression.\n- **feat(provider):** update Jina AI model catalog to support Embeddings and Rerank natively (#1874 — thanks @backryun)\n- **feat(provider):** add NanoGPT image generation provider (#1899 — thanks @Aculeasis)\n- **feat(ui):** move proxy configuration to dedicated System → Proxy page (#1907 — thanks @oyi77)\n- **feat(ui):** add K/M/B/T cost shortener utility (#1902 — thanks @oyi77)\n- **feat(providers):** implement bulk paste for extra API keys (#1916 — thanks @0xtbug)\n- **feat(analytics):** usage history API key backfill + dark mode pricing (#1896 — thanks @Gi99lin)\n\n### 🐛 Bug Fixes\n\n- **fix(providers):** allow local OpenAI-compatible endpoints (like Ollama) to be added without an API key (fixes #1893)\n- **fix(copilot):** emit compatible reasoning text deltas (#1919 — thanks @ivan-mezentsev)\n- **fix(api-manager):** show validation errors inline in modals, not behind (#1920 — thanks @andrewmunsell)\n- **fix(compression):** align seeded standard savings combo with stacked default, preserve stacked defaults, and secure metadata routes.\n- **fix(gemini-cli):** separate Cloud Code transport from Antigravity (#1869 — thanks @dhaern)\n- **fix(codex):** map prompt field to input array for Cursor compatibility (fixes #1872)\n- **fix(core):** align stream parameter default to false per strict OpenAI spec (fixes #1873)\n- **fix(ui):** restore Next.js CSP `unsafe-eval` in production `script-src` to fix unresponsive Onboarding button (fixes #1883)\n- **fix(proxy):** globally strip `prompt_cache_retention` in `BaseExecutor` to prevent upstream 400 errors from strict endpoints like droid/gemini-2-pro (fixes #1884)\n- **fix(ui):** include `isOpen` dependency in `EditConnectionModal` state sync to ensure `maxConcurrent` is properly hydrated when reopening the modal (fixes #1859)\n- **fix(security):** remediate 4 polynomial-redos CodeQL alerts in compression regexes by bounding repetitions and removing overlapping quantifiers\n- **fix(codex):** flatten Chat Completions tool format to Codex Responses format in `normalizeCodexTools` — prevents `Missing required parameter: tools[0].name` upstream errors (#1914 — thanks @tranduykhanh030)\n- **fix(proxy):** add proxy-aware execution context to image generation route — proxy settings are now correctly applied for image providers behind restricted networks (#1904 — thanks @Aculeasis)\n- **fix(translator):** inject `properties: {}` into zero-argument MCP tool schemas during Anthropic→OpenAI translation — prevents 400 errors from OpenAI strict schema validation (#1898 — thanks @bryceIT)\n- **fix(codex):** sanitize raw responses input (#1895 — thanks @dhaern)\n- **fix(combos):** align strategy contracts (#1892 — thanks @dhaern)\n- **fix(combos):** fix combo provider breaker profile handling (#1891 — thanks @rdself)\n- **fix(migrations):** duplicate-column no-op fix (#1886 — thanks @smartenok-ops)\n- **fix(auth):** per-connection OAuth refresh mutex (#1885 — thanks @smartenok-ops)\n- **fix(auth):** require dashboard management auth for compression preview\n\n### 📝 Documentation\n\n- **docs(compression):** document RTK+Caveman stacked savings ranges\n\n### 🏆 Release Attribution & Retroactive Credits\n\n- **@payne0420** (PR #1828 / #1839) — Implementation of the **Rate Limit Watchdog** and environment overrides. (This feature was manually backported to v3.7.8, causing the automatic GitHub Release notes to omit the author's credit).\n",+ "createdAt": "2026-05-03T20:35:53Z",+ "deletions": 1470,+ "files": [+ {+ "path": ".agents/workflows/deploy-vps-akamai.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": ".agents/workflows/deploy-vps-both.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": ".agents/workflows/deploy-vps-local.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": ".agents/workflows/generate-release.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": ".agents/workflows/version-bump.md",+ "additions": 9,+ "deletions": 9,+ "changeType": "MODIFIED"+ },+ {+ "path": "AGENTS.md",+ "additions": 25,+ "deletions": 9,+ "changeType": "MODIFIED"+ },+ {+ "path": "CHANGELOG.md",+ "additions": 47,+ "deletions": 0,+ "changeType": "MODIFIED"+ },+ {+ "path": "README.md",+ "additions": 71,+ "deletions": 29,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/API_REFERENCE.md",+ "additions": 32,+ "deletions": 13,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/ARCHITECTURE.md",+ "additions": 16,+ "deletions": 2,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/COMPRESSION_ENGINES.md",+ "additions": 143,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "docs/COMPRESSION_GUIDE.md",+ "additions": 105,+ "deletions": 12,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/COMPRESSION_LANGUAGE_PACKS.md",+ "additions": 96,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "docs/COMPRESSION_RULES_FORMAT.md",+ "additions": 186,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "docs/ENVIRONMENT.md",+ "additions": 6,+ "deletions": 0,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/FEATURES.md",+ "additions": 16,+ "deletions": 2,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/MCP-SERVER.md",+ "additions": 55,+ "deletions": 19,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/RTK_COMPRESSION.md",+ "additions": 234,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "docs/SETUP_GUIDE.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/openapi.yaml",+ "additions": 199,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "electron/package-lock.json",+ "additions": 2,+ "deletions": 2,+ "changeType": "MODIFIED"+ },+ {+ "path": "electron/package.json",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "llm.txt",+ "additions": 2,+ "deletions": 2,+ "changeType": "MODIFIED"+ },+ {+ "path": "next.config.mjs",+ "additions": 8,+ "deletions": 95,+ "changeType": "MODIFIED"+ },+ {+ "path": "open-sse/config/embeddingRegistry.ts",+ "additions": 62,+ "deletions": 3,+ "changeType": "MODIFIED"+ },+ {+ "path": "open-sse/config/imageRegistry.ts",+ "additions": 14,+ "deletions": 0,+ "changeType": "MODIFIED"+ },+ {+ "path": "open-sse/config/rerankRegistry.ts",+ "additions": 44,+ "deletions": 8,+ "changeType": "MODIFIED"+ },+ {+ "path": "open-sse/executors/base.ts",+ "additions": 3,+ "deletions": 0,+ "changeType": "MODIFIED"+ },+ {+ "path": "open-sse/executors/codex.ts",+ "additions": 75,+ "deletions": 5,+ "changeType": "MODIFIED"+ },+ {+ "path": "open-sse/handlers/chatCore.ts",+ "additions": 338,+ "deletions": 68,+ "changeType": "MODIFIED"+ },+ {+ "path": "open-sse/handlers/imageGeneration.ts",+ "additions": 1,+ "deletions": 0,+ "changeType": "MODIFIED"+ },+ {+ "path": "open-sse/handlers/responseSanitizer.ts",+ "additions": 3,+ "deletions": 0,+ "changeType": "MODIFIED"+ },+ {+ "path": "open-sse/mcp-server/README.md",+ "additions": 17,+ "deletions": 9,+ "changeType": "MODIFIED"+ },+ {+ "path": "open-sse/mcp-server/descriptionCompressor.ts",+ "additions": 243,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/mcp-server/schemas/tools.ts",+ "additions": 121,+ "deletions": 32,+ "changeType": "MODIFIED"+ },+ {+ "path": "open-sse/mcp-server/server.ts",+ "additions": 41,+ "deletions": 0,+ "changeType": "MODIFIED"+ },+ {+ "path": "open-sse/mcp-server/tools/advancedTools.ts",+ "additions": 15,+ "deletions": 16,+ "changeType": "MODIFIED"+ },+ {+ "path": "open-sse/mcp-server/tools/compressionTools.ts",+ "additions": 157,+ "deletions": 11,+ "changeType": "MODIFIED"+ },+ {+ "path": "open-sse/package.json",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "open-sse/services/AGENTS.md",+ "additions": 5,+ "deletions": 2,+ "changeType": "MODIFIED"+ },+ {+ "path": "open-sse/services/accountFallback.ts",+ "additions": 21,+ "deletions": 5,+ "changeType": "MODIFIED"+ },+ {+ "path": "open-sse/services/autoCombo/index.ts",+ "additions": 1,+ "deletions": 10,+ "changeType": "MODIFIED"+ },+ {+ "path": "open-sse/services/combo.ts",+ "additions": 56,+ "deletions": 7,+ "changeType": "MODIFIED"+ },+ {+ "path": "open-sse/services/compression/aggressive.ts",+ "additions": 19,+ "deletions": 29,+ "changeType": "MODIFIED"+ },+ {+ "path": "open-sse/services/compression/caveman.ts",+ "additions": 310,+ "deletions": 31,+ "changeType": "MODIFIED"+ },+ {+ "path": "open-sse/services/compression/cavemanRules.ts",+ "additions": 189,+ "deletions": 15,+ "changeType": "MODIFIED"+ },+ {+ "path": "open-sse/services/compression/diffHelper.ts",+ "additions": 117,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/cavemanAdapter.ts",+ "additions": 408,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/index.ts",+ "additions": 14,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/registry.ts",+ "additions": 87,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/codeStripper.ts",+ "additions": 128,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/commandDetector.ts",+ "additions": 465,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/deduplicator.ts",+ "additions": 37,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filterLoader.ts",+ "additions": 220,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filterSchema.ts",+ "additions": 182,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/aws.json",+ "additions": 34,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/biome.json",+ "additions": 35,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/build-eslint.json",+ "additions": 37,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/build-typescript.json",+ "additions": 33,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/build-vite.json",+ "additions": 41,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/build-webpack.json",+ "additions": 34,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/bundle-install.json",+ "additions": 35,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/curl.json",+ "additions": 34,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/df.json",+ "additions": 34,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/docker-logs.json",+ "additions": 42,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/docker-ps.json",+ "additions": 33,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/du.json",+ "additions": 33,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/error-stacktrace.json",+ "additions": 41,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/gcloud.json",+ "additions": 34,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/generic-output.json",+ "additions": 32,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/git-branch.json",+ "additions": 45,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/git-diff.json",+ "additions": 33,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/git-log.json",+ "additions": 33,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/git-status.json",+ "additions": 40,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/golangci-lint.json",+ "additions": 34,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/json-output.json",+ "additions": 40,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/make.json",+ "additions": 38,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/mypy.json",+ "additions": 34,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/npm-audit.json",+ "additions": 43,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/npm-install.json",+ "additions": 41,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/nx.json",+ "additions": 34,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/pip.json",+ "additions": 41,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/playwright.json",+ "additions": 42,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/poetry-install.json",+ "additions": 35,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/prettier.json",+ "additions": 40,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/ps.json",+ "additions": 34,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/rsync.json",+ "additions": 33,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/rubocop.json",+ "additions": 34,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/ruff.json",+ "additions": 40,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/shell-find.json",+ "additions": 33,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/shell-grep.json",+ "additions": 37,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/shell-ls.json",+ "additions": 33,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/ssh.json",+ "additions": 43,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/systemctl-status.json",+ "additions": 43,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/terraform-plan.json",+ "additions": 34,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/test-cargo.json",+ "additions": 42,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/test-go.json",+ "additions": 41,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/test-jest.json",+ "additions": 43,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/test-pytest.json",+ "additions": 41,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "open-sse/services/compression/engines/rtk/filters/test-vitest.json",+ "additions": 43,+ "deletions": 0,+ "changeType": "ADDED"+ }+ ],+ "headRefName": "release/v3.7.9",+ "number": 1917,+ "title": "Release v3.7.9"+ },+ {+ "additions": 788,+ "author": {+ "id": "MDQ6VXNlcjI0MTk4NDIy",+ "is_bot": false,+ "login": "backryun",+ "name": "backryun"+ },+ "baseRefName": "release/v3.7.9",+ "body": "## Summary\r\n\r\ncompletely removing support for Node.js 20.\r\nNode.js 20 has reached EOL.\r\n<img width=\"334\" height=\"327\" alt=\"image\" src=\"https://github.com/user-attachments/assets/f88758e4-fd6e-478e-88e4-8819d0c5e8e0\" />\r\n\r\n## Validation\r\n\r\n- [x] `npm run lint`\r\n- [x] `npm run test:unit`\r\n- [ ] `npm run test:coverage`\r\n- [ ] Coverage is still `>= 60%` for statements, lines, functions, and branches\r\n\r\n## Tests Added Or Updated\r\n\r\nUpdated automated test files:\r\n\r\n- `tests/unit/node-runtime-support.test.ts`\r\n- `tests/unit/chatcore-sanitization.test.ts`\r\n- `tests/unit/codex-stream-false.test.ts`\r\n- `tests/unit/t26-ai-sdk-accept-header-compat.test.ts`\r\n- `tests/integration/chat-pipeline.test.ts`\r\n- `tests/e2e/protocol-clients.test.ts`\r\n\r\nProduction code changed: Node runtime support logic was updated in `src/shared/utils/nodeRuntimeSupport.ts` and `bin/nodeRuntimeSupport.mjs`.\r\n\r\n## Coverage Notes\r\n\r\nThis PR changes `src/` and `bin/`.\r\n\r\nCoverage for the runtime support change is primarily provided by:\r\n\r\n- `tests/unit/node-runtime-support.test.ts`\r\n- `npm run check:node-runtime`\r\n\r\nAdditional regression coverage was run through:\r\n\r\n- `npm run test:unit`\r\n- `npm run test:integration`\r\n- `npm run test:e2e`\r\n- `npm run test:protocols:e2e`\r\n\r\n`npm run test:coverage` was not run, so coverage movement for touched files has not been measured yet. Follow-up before merge: run `npm run test:coverage` and confirm statements, lines, functions, and branches remain `>= 60%`.\r\n\r\n## Reviewer Notes\r\n\r\n- Node.js 20 support is removed from runtime policy, package engines, CI, docs, and runtime warning copy.\r\n- Supported runtime policy is now Node.js `>=22.22.2 <23 || >=24.0.0 <25`.\r\n- CI matrix and local version files now target Node 22/24 support.\r\n- Docs and i18n runtime wording were updated broadly; reviewers should expect many documentation-only diffs.\r\n- `tests/e2e/protocol-clients.test.ts` now explicitly enables A2A before validating the A2A flow, matching the current default where A2A starts disabled.\r\n- Manual validation was performed on Node `v22.22.2`.\n\n> [!NOTE]\n> **OmniRoute Maintainer Note:** This PR has been deferred and will be accepted and redirected for the `v4.0.0` (or greater) release cycle. Please skip this PR during `v3.x` stabilization reviews.",+ "createdAt": "2026-05-03T14:11:25Z",+ "deletions": 776,+ "files": [+ {+ "path": ".dockerignore",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": ".env.example",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": ".github/workflows/ci.yml",+ "additions": 8,+ "deletions": 5,+ "changeType": "MODIFIED"+ },+ {+ "path": ".npmignore",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "AGENTS.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "CLAUDE.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "CONTRIBUTING.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "Dockerfile",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "README.md",+ "additions": 10,+ "deletions": 10,+ "changeType": "MODIFIED"+ },+ {+ "path": "bin/nodeRuntimeSupport.mjs",+ "additions": 3,+ "deletions": 5,+ "changeType": "MODIFIED"+ },+ {+ "path": "compose.prod.yaml",+ "additions": 3,+ "deletions": 3,+ "changeType": "RENAMED"+ },+ {+ "path": "compose.yaml",+ "additions": 0,+ "deletions": 0,+ "changeType": "RENAMED"+ },+ {+ "path": "docs/CLI-TOOLS.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/ENVIRONMENT.md",+ "additions": 3,+ "deletions": 3,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/FEATURES.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/RELEASE_CHECKLIST.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/TROUBLESHOOTING.md",+ "additions": 3,+ "deletions": 3,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/ar/CONTRIBUTING.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/ar/README.md",+ "additions": 2,+ "deletions": 2,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/ar/docs/CLI-TOOLS.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/ar/docs/ENVIRONMENT.md",+ "additions": 3,+ "deletions": 3,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/ar/docs/FEATURES.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/ar/docs/RELEASE_CHECKLIST.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/ar/docs/TROUBLESHOOTING.md",+ "additions": 3,+ "deletions": 3,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/ar/llm.txt",+ "additions": 3,+ "deletions": 3,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/bg/CONTRIBUTING.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/bg/README.md",+ "additions": 2,+ "deletions": 2,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/bg/docs/CLI-TOOLS.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/bg/docs/ENVIRONMENT.md",+ "additions": 3,+ "deletions": 3,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/bg/docs/FEATURES.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/bg/docs/RELEASE_CHECKLIST.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/bg/docs/TROUBLESHOOTING.md",+ "additions": 3,+ "deletions": 3,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/bg/llm.txt",+ "additions": 3,+ "deletions": 3,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/bn/CONTRIBUTING.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/bn/README.md",+ "additions": 2,+ "deletions": 2,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/bn/docs/CLI-TOOLS.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/bn/docs/ENVIRONMENT.md",+ "additions": 3,+ "deletions": 3,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/bn/docs/FEATURES.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/bn/docs/RELEASE_CHECKLIST.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/bn/docs/TROUBLESHOOTING.md",+ "additions": 3,+ "deletions": 3,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/cs/CONTRIBUTING.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/cs/README.md",+ "additions": 2,+ "deletions": 2,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/cs/docs/CLI-TOOLS.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/cs/docs/ENVIRONMENT.md",+ "additions": 3,+ "deletions": 3,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/cs/docs/FEATURES.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/cs/docs/RELEASE_CHECKLIST.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/cs/docs/TROUBLESHOOTING.md",+ "additions": 3,+ "deletions": 3,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/cs/llm.txt",+ "additions": 3,+ "deletions": 3,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/da/CONTRIBUTING.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/da/README.md",+ "additions": 2,+ "deletions": 2,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/da/docs/CLI-TOOLS.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/da/docs/ENVIRONMENT.md",+ "additions": 3,+ "deletions": 3,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/da/docs/FEATURES.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/da/docs/RELEASE_CHECKLIST.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/da/docs/TROUBLESHOOTING.md",+ "additions": 3,+ "deletions": 3,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/da/llm.txt",+ "additions": 3,+ "deletions": 3,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/de/CONTRIBUTING.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/de/README.md",+ "additions": 2,+ "deletions": 2,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/de/docs/CLI-TOOLS.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/de/docs/ENVIRONMENT.md",+ "additions": 3,+ "deletions": 3,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/de/docs/FEATURES.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/de/docs/RELEASE_CHECKLIST.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/de/docs/TROUBLESHOOTING.md",+ "additions": 3,+ "deletions": 3,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/de/llm.txt",+ "additions": 3,+ "deletions": 3,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/es/CONTRIBUTING.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/es/README.md",+ "additions": 2,+ "deletions": 2,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/es/docs/CLI-TOOLS.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/es/docs/ENVIRONMENT.md",+ "additions": 3,+ "deletions": 3,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/es/docs/FEATURES.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/es/docs/RELEASE_CHECKLIST.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/es/docs/TROUBLESHOOTING.md",+ "additions": 3,+ "deletions": 3,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/es/llm.txt",+ "additions": 3,+ "deletions": 3,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/fa/CONTRIBUTING.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/fa/README.md",+ "additions": 2,+ "deletions": 2,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/fa/docs/CLI-TOOLS.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/fa/docs/ENVIRONMENT.md",+ "additions": 3,+ "deletions": 3,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/fa/docs/FEATURES.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/fa/docs/RELEASE_CHECKLIST.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/fa/docs/TROUBLESHOOTING.md",+ "additions": 3,+ "deletions": 3,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/fi/CONTRIBUTING.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/fi/README.md",+ "additions": 2,+ "deletions": 2,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/fi/docs/CLI-TOOLS.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/fi/docs/ENVIRONMENT.md",+ "additions": 3,+ "deletions": 3,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/fi/docs/FEATURES.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/fi/docs/RELEASE_CHECKLIST.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/fi/docs/TROUBLESHOOTING.md",+ "additions": 3,+ "deletions": 3,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/fi/llm.txt",+ "additions": 3,+ "deletions": 3,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/fr/CONTRIBUTING.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/fr/README.md",+ "additions": 2,+ "deletions": 2,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/fr/docs/CLI-TOOLS.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/fr/docs/ENVIRONMENT.md",+ "additions": 3,+ "deletions": 3,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/fr/docs/FEATURES.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/fr/docs/RELEASE_CHECKLIST.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/fr/docs/TROUBLESHOOTING.md",+ "additions": 3,+ "deletions": 3,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/fr/llm.txt",+ "additions": 3,+ "deletions": 3,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/gu/CONTRIBUTING.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/gu/README.md",+ "additions": 2,+ "deletions": 2,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/gu/docs/CLI-TOOLS.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/gu/docs/ENVIRONMENT.md",+ "additions": 3,+ "deletions": 3,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/gu/docs/FEATURES.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ }+ ],+ "headRefName": "release/v3.7.9",+ "number": 1915,+ "title": "[will be merge 4.0 update] (Security Fix): Drop node.js 20 support + Update docker files to lastest docker standards"+ },+ {+ "additions": 1119,+ "author": {+ "id": "U_kgDODPQT-Q",+ "is_bot": false,+ "login": "vrdons",+ "name": ""+ },+ "baseRefName": "release/v3.7.9",+ "body": "## Summary\r\n\r\nTo allow using on bun interface, faster typescript checks\r\n\r\n## Related Issues\r\nNone\r\n\r\n## Validation\r\n\r\n- [x] `npm run lint`\r\n- [ ] `npm run test:unit`\r\nNo, because last tests stucks\r\n- [x] `npm run test:coverage`\r\n- [ ] Coverage is still `>= 60%` for statements, lines, functions, and branches\r\n- [ ] SonarQube PR analysis is green or any remaining issues are explicitly documented below\r\n\r\n## Tests Added Or Updated\r\n\r\n- List every changed or added automated test file.\r\n- If no production code changed, state that here.\r\n\r\n## Coverage Notes\r\n\r\n- If this PR changes `src/`, `open-sse/`, `electron/`, or `bin/`, explain which tests cover the change.\r\n- If coverage moved down in any touched file, explain why and what follow-up task will recover it.\r\n\r\n## Reviewer Notes\r\n\r\n- Call out any risky areas, migrations, feature flags, or manual validation that reviewers should know about.\r\n\n> [!NOTE]\n> **OmniRoute Maintainer Note:** This PR has been deferred and will be accepted and redirected for the `v4.0.0` (or greater) release cycle. Please skip this PR during `v3.x` stabilization reviews.",+ "createdAt": "2026-05-02T17:57:46Z",+ "deletions": 231022,+ "files": [+ {+ "path": ".agents/workflows/deploy-vps-akamai.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": ".agents/workflows/deploy-vps-both.md",+ "additions": 2,+ "deletions": 2,+ "changeType": "MODIFIED"+ },+ {+ "path": ".agents/workflows/deploy-vps-local.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": ".agents/workflows/generate-release.md",+ "additions": 2,+ "deletions": 2,+ "changeType": "MODIFIED"+ },+ {+ "path": "AGENTS.md",+ "additions": 4,+ "deletions": 4,+ "changeType": "MODIFIED"+ },+ {+ "path": "CLAUDE.md",+ "additions": 1,+ "deletions": 218,+ "changeType": "MODIFIED"+ },+ {+ "path": "GEMINI.md",+ "additions": 1,+ "deletions": 21,+ "changeType": "MODIFIED"+ },+ {+ "path": "README.md",+ "additions": 63,+ "deletions": 36,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/API_REFERENCE.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/ARCHITECTURE.md",+ "additions": 2,+ "deletions": 2,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/CODEBASE_DOCUMENTATION.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/ENVIRONMENT.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/FEATURES.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/I18N.md",+ "additions": 82,+ "deletions": 52,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/SETUP_GUIDE.md",+ "additions": 9,+ "deletions": 8,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/TERMUX_GUIDE.md",+ "additions": 2,+ "deletions": 10,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/TROUBLESHOOTING.md",+ "additions": 17,+ "deletions": 41,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/UNINSTALL.md",+ "additions": 12,+ "deletions": 12,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/USER_GUIDE.md",+ "additions": 2,+ "deletions": 10,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/VM_DEPLOYMENT_GUIDE.md",+ "additions": 1,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/ar/CHANGELOG.md",+ "additions": 0,+ "deletions": 4921,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/ar/CLAUDE.md",+ "additions": 0,+ "deletions": 233,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/ar/GEMINI.md",+ "additions": 0,+ "deletions": 25,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/ar/README.md",+ "additions": 2,+ "deletions": 13,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/ar/llm.txt",+ "additions": 0,+ "deletions": 476,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/bg/CHANGELOG.md",+ "additions": 0,+ "deletions": 4921,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/bg/CLAUDE.md",+ "additions": 0,+ "deletions": 233,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/bg/GEMINI.md",+ "additions": 0,+ "deletions": 25,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/bg/llm.txt",+ "additions": 0,+ "deletions": 476,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/bn/CHANGELOG.md",+ "additions": 0,+ "deletions": 4921,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/bn/CLAUDE.md",+ "additions": 0,+ "deletions": 233,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/bn/GEMINI.md",+ "additions": 0,+ "deletions": 25,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/cs/CHANGELOG.md",+ "additions": 0,+ "deletions": 4921,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/cs/CLAUDE.md",+ "additions": 0,+ "deletions": 233,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/cs/GEMINI.md",+ "additions": 0,+ "deletions": 25,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/cs/README.md",+ "additions": 0,+ "deletions": 2379,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/cs/docs/A2A-SERVER.md",+ "additions": 0,+ "deletions": 200,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/cs/docs/API_REFERENCE.md",+ "additions": 0,+ "deletions": 469,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/cs/docs/ARCHITECTURE.md",+ "additions": 0,+ "deletions": 891,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/cs/docs/AUTO-COMBO.md",+ "additions": 0,+ "deletions": 67,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/cs/docs/CLI-TOOLS.md",+ "additions": 0,+ "deletions": 398,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/cs/docs/CODEBASE_DOCUMENTATION.md",+ "additions": 0,+ "deletions": 591,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/cs/docs/COVERAGE_PLAN.md",+ "additions": 0,+ "deletions": 170,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/cs/docs/ENVIRONMENT.md",+ "additions": 0,+ "deletions": 669,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/cs/docs/FEATURES.md",+ "additions": 0,+ "deletions": 270,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/cs/docs/FLY_IO_DEPLOYMENT_GUIDE.md",+ "additions": 0,+ "deletions": 455,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/cs/docs/I18N.md",+ "additions": 0,+ "deletions": 441,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/cs/docs/MCP-SERVER.md",+ "additions": 0,+ "deletions": 87,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/cs/docs/RELEASE_CHECKLIST.md",+ "additions": 0,+ "deletions": 44,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/cs/docs/TROUBLESHOOTING.md",+ "additions": 0,+ "deletions": 341,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/cs/docs/UNINSTALL.md",+ "additions": 0,+ "deletions": 157,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/cs/docs/USER_GUIDE.md",+ "additions": 0,+ "deletions": 966,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/cs/docs/VM_DEPLOYMENT_GUIDE.md",+ "additions": 0,+ "deletions": 407,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/cs/docs/cloudflare-zero-trust-guide.md",+ "additions": 0,+ "deletions": 106,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/cs/docs/features/context-relay.md",+ "additions": 0,+ "deletions": 130,+ "changeType": "MODIFIED"+ },+ {+ "path": "docs/i18n/cs/llm.txt",+ "additions": 0,+ "deletions": 476,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/da/CHANGELOG.md",+ "additions": 0,+ "deletions": 4921,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/da/CLAUDE.md",+ "additions": 0,+ "deletions": 233,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/da/GEMINI.md",+ "additions": 0,+ "deletions": 25,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/da/llm.txt",+ "additions": 0,+ "deletions": 476,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/de/CHANGELOG.md",+ "additions": 0,+ "deletions": 4921,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/de/CLAUDE.md",+ "additions": 0,+ "deletions": 233,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/de/GEMINI.md",+ "additions": 0,+ "deletions": 25,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/de/llm.txt",+ "additions": 0,+ "deletions": 476,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/es/CHANGELOG.md",+ "additions": 0,+ "deletions": 4921,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/es/CLAUDE.md",+ "additions": 0,+ "deletions": 233,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/es/GEMINI.md",+ "additions": 0,+ "deletions": 25,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/es/llm.txt",+ "additions": 0,+ "deletions": 476,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/fa/CHANGELOG.md",+ "additions": 0,+ "deletions": 4921,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/fa/CLAUDE.md",+ "additions": 0,+ "deletions": 233,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/fa/GEMINI.md",+ "additions": 0,+ "deletions": 25,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/fi/CHANGELOG.md",+ "additions": 0,+ "deletions": 4921,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/fi/CLAUDE.md",+ "additions": 0,+ "deletions": 233,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/fi/GEMINI.md",+ "additions": 0,+ "deletions": 25,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/fi/llm.txt",+ "additions": 0,+ "deletions": 476,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/fr/CHANGELOG.md",+ "additions": 0,+ "deletions": 4921,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/fr/CLAUDE.md",+ "additions": 0,+ "deletions": 233,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/fr/GEMINI.md",+ "additions": 0,+ "deletions": 25,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/fr/llm.txt",+ "additions": 0,+ "deletions": 476,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/gu/CHANGELOG.md",+ "additions": 0,+ "deletions": 4921,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/gu/CLAUDE.md",+ "additions": 0,+ "deletions": 233,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/gu/GEMINI.md",+ "additions": 0,+ "deletions": 25,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/he/CHANGELOG.md",+ "additions": 0,+ "deletions": 4921,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/he/CLAUDE.md",+ "additions": 0,+ "deletions": 233,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/he/GEMINI.md",+ "additions": 0,+ "deletions": 25,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/he/llm.txt",+ "additions": 0,+ "deletions": 476,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/hi/CHANGELOG.md",+ "additions": 0,+ "deletions": 4921,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/hi/CLAUDE.md",+ "additions": 0,+ "deletions": 233,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/hi/GEMINI.md",+ "additions": 0,+ "deletions": 25,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/hi/llm.txt",+ "additions": 0,+ "deletions": 476,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/hu/CHANGELOG.md",+ "additions": 0,+ "deletions": 4921,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/hu/CLAUDE.md",+ "additions": 0,+ "deletions": 233,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/hu/GEMINI.md",+ "additions": 0,+ "deletions": 25,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/hu/llm.txt",+ "additions": 0,+ "deletions": 476,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/id/CHANGELOG.md",+ "additions": 0,+ "deletions": 4921,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/id/CLAUDE.md",+ "additions": 0,+ "deletions": 233,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/id/GEMINI.md",+ "additions": 0,+ "deletions": 25,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/id/llm.txt",+ "additions": 0,+ "deletions": 476,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/in/CHANGELOG.md",+ "additions": 0,+ "deletions": 3232,+ "changeType": "DELETED"+ },+ {+ "path": "docs/i18n/in/CLAUDE.md",+ "additions": 0,+ "deletions": 229,+ "changeType": "DELETED"+ }+ ],+ "headRefName": "main",+ "number": 1894,+ "title": "refactor(db): migrate from better-sqlite3 to node:sqlite, use tsgo"+ },+ {+ "additions": 276,+ "author": {+ "id": "U_kgDOD9eSjQ",+ "is_bot": false,+ "login": "smartenok-ops",+ "name": ""+ },+ "baseRefName": "release/v3.7.9",+ "body": "When a codex SSE stream hits 429 mid-task, OmniRoute previously gave up (maxAttempts=1, no rotation). Add retry with account rotation when session affinity allows.\r\n\r\nDepends on: per-session sticky routing PR (extractSessionAffinityKey, deleteSessionAccountAffinity).\r\n\r\n## Summary\r\n\r\n- Describe the user-facing or operational change.\r\n\r\n## Related Issues\r\n\r\n- Closes #\r\n- Related to #\r\n\r\n## Validation\r\n\r\n- [ ] `npm run lint`\r\n- [ ] `npm run test:unit`\r\n- [ ] `npm run test:coverage`\r\n- [ ] Coverage is still `>= 60%` for statements, lines, functions, and branches\r\n- [ ] SonarQube PR analysis is green or any remaining issues are explicitly documented below\r\n\r\n## Tests Added Or Updated\r\n\r\n- List every changed or added automated test file.\r\n- If no production code changed, state that here.\r\n\r\n## Coverage Notes\r\n\r\n- If this PR changes `src/`, `open-sse/`, `electron/`, or `bin/`, explain which tests cover the change.\r\n- If coverage moved down in any touched file, explain why and what follow-up task will recover it.\r\n\r\n## Reviewer Notes\r\n\r\n- Call out any risky areas, migrations, feature flags, or manual validation that reviewers should know about.\r\n\n> [!NOTE]\n> **OmniRoute Maintainer Note:** This PR has been deferred and will be accepted and redirected for the `v4.0.0` (or greater) release cycle. Please skip this PR during `v3.x` stabilization reviews.",+ "createdAt": "2026-05-02T16:06:11Z",+ "deletions": 2,+ "files": [+ {+ "path": "open-sse/handlers/chatCore.ts",+ "additions": 84,+ "deletions": 2,+ "changeType": "MODIFIED"+ },+ {+ "path": "tests/unit/codex-failover.test.ts",+ "additions": 192,+ "deletions": 0,+ "changeType": "ADDED"+ }+ ],+ "headRefName": "feat/codex-429-mid-task-failover",+ "number": 1888,+ "title": "feat(sse): codex 429 mid-task failover with account rotation"+ },+ {+ "additions": 461,+ "author": {+ "id": "U_kgDOD9eSjQ",+ "is_bot": false,+ "login": "smartenok-ops",+ "name": ""+ },+ "baseRefName": "release/v3.7.9",+ "body": "When concurrent SSE clients use a shared OmniRoute key, randomized account selection causes per-session inconsistencies (one stream hits account A, next request from same logical session hits B). Adds session_account_affinity table + extractSessionAffinityKey helper so a session_key (e.g. SHA of input headers) deterministically pins to one account for its lifetime.\r\n\r\nMigration: 041_session_account_affinity.sql (renumbered from local 026 — please confirm next available slot).\r\n\r\n## Summary\r\n\r\n- Describe the user-facing or operational change.\r\n\r\n## Related Issues\r\n\r\n- Closes #\r\n- Related to #\r\n\r\n## Validation\r\n\r\n- [ ] `npm run lint`\r\n- [ ] `npm run test:unit`\r\n- [ ] `npm run test:coverage`\r\n- [ ] Coverage is still `>= 60%` for statements, lines, functions, and branches\r\n- [ ] SonarQube PR analysis is green or any remaining issues are explicitly documented below\r\n\r\n## Tests Added Or Updated\r\n\r\n- List every changed or added automated test file.\r\n- If no production code changed, state that here.\r\n\r\n## Coverage Notes\r\n\r\n- If this PR changes `src/`, `open-sse/`, `electron/`, or `bin/`, explain which tests cover the change.\r\n- If coverage moved down in any touched file, explain why and what follow-up task will recover it.\r\n\r\n## Reviewer Notes\r\n\r\n- Call out any risky areas, migrations, feature flags, or manual validation that reviewers should know about.\r\n\n> [!NOTE]\n> **OmniRoute Maintainer Note:** This PR has been deferred and will be accepted and redirected for the `v4.0.0` (or greater) release cycle. Please skip this PR during `v3.x` stabilization reviews.",+ "createdAt": "2026-05-02T16:05:53Z",+ "deletions": 122,+ "files": [+ {+ "path": "src/instrumentation-node.ts",+ "additions": 10,+ "deletions": 5,+ "changeType": "MODIFIED"+ },+ {+ "path": "src/lib/db/migrations/041_session_account_affinity.sql",+ "additions": 11,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "src/lib/db/sessionAccountAffinity.ts",+ "additions": 122,+ "deletions": 0,+ "changeType": "ADDED"+ },+ {+ "path": "src/lib/localDb.ts",+ "additions": 10,+ "deletions": 0,+ "changeType": "MODIFIED"+ },+ {+ "path": "src/sse/handlers/chat.ts",+ "additions": 14,+ "deletions": 1,+ "changeType": "MODIFIED"+ },+ {+ "path": "src/sse/services/auth.ts",+ "additions": 177,+ "deletions": 2,+ "changeType": "MODIFIED"+ },+ {+ "path": "tests/unit/sse-auth.test.ts",+ "additions": 117,+ "deletions": 114,+ "changeType": "MODIFIED"+ }+ ],+ "headRefName": "feat/per-session-sticky-routing",+ "number": 1887,+ "title": "feat(auth): per-session sticky routing for codex"+ }+]diff --git a/scripts/pack-artifact-policy.ts b/scripts/pack-artifact-policy.tsindex b2e55c0232..06793c10c6 100644--- a/scripts/pack-artifact-policy.ts+++ b/scripts/pack-artifact-policy.ts@@ -42,6 +42,8 @@ export const APP_STAGING_ALLOWED_PATH_PREFIXES: string[] = [".next/","data/","node_modules/",+ "open-sse/services/compression/engines/rtk/filters/",+ "open-sse/services/compression/rules/","public/","src/lib/db/migrations/","src/mitm/",@@ -88,6 +90,8 @@ export const PACK_ARTIFACT_ROOT_ALLOWED_PATH_PREFIXES: string[] = [];export const PACK_ARTIFACT_REQUIRED_PATHS: string[] = [+ "app/open-sse/services/compression/engines/rtk/filters/generic-output.json",+ "app/open-sse/services/compression/rules/en/filler.json","app/server.js","app/server-ws.mjs","app/responses-ws-proxy.mjs",diff --git a/scripts/prepublish.ts b/scripts/prepublish.tsindex 199c76c68d..8b54f60067 100644--- a/scripts/prepublish.ts+++ b/scripts/prepublish.ts@@ -475,6 +475,23 @@ if (existsSync(migrationsSrc)) {cpSync(migrationsSrc, migrationsDest, { recursive: true, force: true });}+const runtimeAssetDirs = [+ {+ source: join(ROOT, "open-sse", "services", "compression", "engines", "rtk", "filters"),+ destination: join(APP_DIR, "open-sse", "services", "compression", "engines", "rtk", "filters"),+ },+ {+ source: join(ROOT, "open-sse", "services", "compression", "rules"),+ destination: join(APP_DIR, "open-sse", "services", "compression", "rules"),+ },+];+for (const assetDir of runtimeAssetDirs) {+ if (existsSync(assetDir.source)) {+ mkdirSync(dirname(assetDir.destination), { recursive: true });+ cpSync(assetDir.source, assetDir.destination, { recursive: true, force: true });+ }+}+// ── Step 10: Ensure data/ directory exists ──────────────────mkdirSync(join(APP_DIR, "data"), { recursive: true });diff --git a/scripts/scratch/pr_body.md b/scripts/scratch/pr_body.mdnew file mode 100644index 0000000000..25326e6e60--- /dev/null+++ b/scripts/scratch/pr_body.md@@ -0,0 +1,46 @@+### ✨ New Features++- **feat(compression):** major upgrade to Caveman and RTK compression pipelines (#1876, #1889):+ - Add RTK tool-output compression, stacked Caveman + RTK pipelines, compression combo assignments, dashboard context pages, MCP management tools, and language-aware Caveman rule packs.+ - Expand RTK parity with a 39-filter catalog, RTK-style JSON DSL stages, inline verify/benchmark coverage, trust-gated custom filters, expanded command detection, and redacted raw-output recovery.+ - Expose rule intensities, track USD savings, unify config validation, and persist MCP savings.+ - Expand Caveman parity and MCP metadata compression.+- **feat(provider):** update Jina AI model catalog to support Embeddings and Rerank natively (#1874 — thanks @backryun)+- **feat(provider):** add NanoGPT image generation provider (#1899 — thanks @Aculeasis)+- **feat(ui):** move proxy configuration to dedicated System → Proxy page (#1907 — thanks @oyi77)+- **feat(ui):** add K/M/B/T cost shortener utility (#1902 — thanks @oyi77)+- **feat(providers):** implement bulk paste for extra API keys (#1916 — thanks @0xtbug)+- **feat(analytics):** usage history API key backfill + dark mode pricing (#1896 — thanks @Gi99lin)+- **feat(logs):** show RTK and Caveman compression token savings accurately in request log UI (#1923 — thanks @emdash)++### 🐛 Bug Fixes++- **fix(providers):** allow local OpenAI-compatible endpoints (like Ollama) to be added without an API key (fixes #1893)+- **fix(providers):** bypass AgentRouter unauthorized_client_error by spoofing Claude CLI headers via Anthropic endpoints (fixes #1921)+- **fix(copilot):** emit compatible reasoning text deltas (#1919 — thanks @ivan-mezentsev)+- **fix(api-manager):** show validation errors inline in modals, not behind (#1920 — thanks @andrewmunsell)+- **fix(compression):** align seeded standard savings combo with stacked default, preserve stacked defaults, and secure metadata routes.+- **fix(gemini-cli):** separate Cloud Code transport from Antigravity (#1869 — thanks @dhaern)+- **fix(codex):** map prompt field to input array for Cursor compatibility (fixes #1872)+- **fix(core):** align stream parameter default to false per strict OpenAI spec (fixes #1873)+- **fix(ui):** restore Next.js CSP `unsafe-eval` in production `script-src` to fix unresponsive Onboarding button (fixes #1883)+- **fix(proxy):** globally strip `prompt_cache_retention` in `BaseExecutor` to prevent upstream 400 errors from strict endpoints like droid/gemini-2-pro (fixes #1884)+- **fix(ui):** include `isOpen` dependency in `EditConnectionModal` state sync to ensure `maxConcurrent` is properly hydrated when reopening the modal (fixes #1859)+- **fix(security):** remediate 4 polynomial-redos CodeQL alerts in compression regexes by bounding repetitions and removing overlapping quantifiers+- **fix(codex):** flatten Chat Completions tool format to Codex Responses format in `normalizeCodexTools` — prevents `Missing required parameter: tools[0].name` upstream errors (#1914 — thanks @tranduykhanh030)+- **fix(proxy):** add proxy-aware execution context to image generation route — proxy settings are now correctly applied for image providers behind restricted networks (#1904 — thanks @Aculeasis)+- **fix(translator):** inject `properties: {}` into zero-argument MCP tool schemas during Anthropic→OpenAI translation — prevents 400 errors from OpenAI strict schema validation (#1898 — thanks @bryceIT)+- **fix(codex):** sanitize raw responses input (#1895 — thanks @dhaern)+- **fix(combos):** align strategy contracts (#1892 — thanks @dhaern)+- **fix(combos):** fix combo provider breaker profile handling (#1891 — thanks @rdself)+- **fix(migrations):** duplicate-column no-op fix (#1886 — thanks @smartenok-ops)+- **fix(auth):** per-connection OAuth refresh mutex (#1885 — thanks @smartenok-ops)+- **fix(auth):** require dashboard management auth for compression preview++### 📝 Documentation++- **docs(compression):** document RTK+Caveman stacked savings ranges++### 🏆 Release Attribution & Retroactive Credits++- **@payne0420** (PR #1828 / #1839) — Implementation of the **Rate Limit Watchdog** and environment overrides. (This feature was manually backported to v3.7.8, causing the automatic GitHub Release notes to omit the author's credit).diff --git a/scripts/scratch/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..6c84c6b077 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">@@ -290,8 +358,8 @@ export default function CompressionAnalyticsTab() {<span className="material-symbols-outlined text-[16px] text-blue-500 mt-0.5">info</span><span><strong>Compression analytics:</strong> Token savings tracked per mode (off, lite,- standard, aggressive, ultra) and provider. Hover over charts for details. Use the time- selector to view different time periods.+ standard, aggressive, ultra, RTK, stacked), engine, compression combo, and provider. Hover+ over charts for details. Use the time selector to view different time periods.</span></div></div>diff --git a/src/app/(dashboard)/dashboard/api-manager/ApiManagerPageClient.tsx b/src/app/(dashboard)/dashboard/api-manager/ApiManagerPageClient.tsxindex e2c71e54d6..06e27cc639 100644--- a/src/app/(dashboard)/dashboard/api-manager/ApiManagerPageClient.tsx+++ b/src/app/(dashboard)/dashboard/api-manager/ApiManagerPageClient.tsx@@ -107,7 +107,9 @@ export default function ApiManagerPageClient() {const [editingKey, setEditingKey] = useState<ApiKey | null>(null);const [showPermissionsModal, setShowPermissionsModal] = useState(false);const [searchModel, setSearchModel] = useState("");- const [error, setError] = useState<string | null>(null);+ const [pageError, setPageError] = useState<string | null>(null);+ const [nameError, setNameError] = useState<string | null>(null);+ const [createError, setCreateError] = useState<string | null>(null);const [isSubmitting, setIsSubmitting] = useState(false);const [usageStats, setUsageStats] = useState<Record<string, KeyUsageStats>>({});const [sessionCounts, setSessionCounts] = useState<Record<string, number>>({});@@ -226,19 +228,20 @@ export default function ApiManagerPageClient() {}};- const clearError = useCallback(() => setError(null), []);+ const clearPageError = useCallback(() => setPageError(null), []);const handleCreateKey = async () => {// Validate raw input first, then sanitizeconst validation = validateKeyName(newKeyName, t);if (!validation.valid) {- setError(validation.error || t("invalidKeyName"));+ setNameError(validation.error || t("invalidKeyName"));return;}const sanitizedName = sanitizeInput(newKeyName);setIsSubmitting(true);- clearError();+ setNameError(null);+ setCreateError(null);try {const res = await fetch("/api/keys", {@@ -254,11 +257,11 @@ export default function ApiManagerPageClient() {setNewKeyName("");setShowAddModal(false);} else {- setError(data.error || t("failedCreateKey"));+ setCreateError(data.error || t("failedCreateKey"));}} catch (error) {console.error("Error creating key:", error);- setError(t("failedCreateKeyRetry"));+ setCreateError(t("failedCreateKeyRetry"));} finally {setIsSubmitting(false);}@@ -267,14 +270,14 @@ export default function ApiManagerPageClient() {const handleDeleteKey = async (id: string) => {// Validate ID format to prevent injectionif (!id || typeof id !== "string" || !/^[a-zA-Z0-9_-]+$/.test(id)) {- setError(t("invalidKeyId"));+ setPageError(t("invalidKeyId"));return;}if (!confirm(t("deleteConfirm"))) return;setIsSubmitting(true);- clearError();+ clearPageError();try {const res = await fetch(`/api/keys/${encodeURIComponent(id)}`, { method: "DELETE" });@@ -282,11 +285,11 @@ export default function ApiManagerPageClient() {setKeys((prev) => prev.filter((k) => k.id !== id));} else {const data = await res.json();- setError(data.error || t("failedDeleteKey"));+ setPageError(data.error || t("failedDeleteKey"));}} catch (error) {console.error("Error deleting key:", error);- setError(t("failedDeleteKeyRetry"));+ setPageError(t("failedDeleteKeyRetry"));} finally {setIsSubmitting(false);}@@ -329,23 +332,15 @@ export default function ApiManagerPageClient() {) => {if (!editingKey || !editingKey.id) return;- // Validate raw input first, then sanitize- const nameValidation = validateKeyName(name, t);- if (!nameValidation.valid) {- setError(nameValidation.error || t("invalidKeyName"));- return;- }const sanitizedName = sanitizeInput(name);// Validate models arrayif (!Array.isArray(allowedModels)) {- setError(t("invalidModelsSelection"));return;}// Limit number of selected models to prevent abuseif (allowedModels.length > MAX_SELECTED_MODELS) {- setError(t("cannotSelectMoreThanModels", { max: MAX_SELECTED_MODELS }));return;}@@ -364,7 +359,7 @@ export default function ApiManagerPageClient() {: 0;setIsSubmitting(true);- clearError();+ clearPageError();try {const res = await fetch(`/api/keys/${encodeURIComponent(editingKey.id)}`, {@@ -388,11 +383,11 @@ export default function ApiManagerPageClient() {setEditingKey(null);} else {const data = await res.json();- setError(data.error || t("failedUpdatePermissions"));+ setPageError(data.error || t("failedUpdatePermissions"));}} catch (error) {console.error("Error updating permissions:", error);- setError(t("failedUpdatePermissionsRetry"));+ setPageError(t("failedUpdatePermissionsRetry"));} finally {setIsSubmitting(false);}@@ -441,12 +436,12 @@ export default function ApiManagerPageClient() {return (<div className="flex flex-col gap-8">{/* Error Banner */}- {error && (+ {pageError && (<div className="flex items-center gap-3 p-4 bg-red-500/10 border border-red-500/30 rounded-lg"><span className="material-symbols-outlined text-red-500">error</span>- <p className="text-sm text-red-700 dark:text-red-300 flex-1">{error}</p>+ <p className="text-sm text-red-700 dark:text-red-300 flex-1">{pageError}</p><button- onClick={clearError}+ onClick={clearPageError}className="text-red-500 hover:text-red-700 transition-colors"><span className="material-symbols-outlined">close</span>@@ -520,7 +515,15 @@ export default function ApiManagerPageClient() {<h2 className="text-lg font-semibold">{t("keyManagement")}</h2><p className="text-sm text-text-muted">{t("keyManagementDesc")}</p></div>- <Button icon="add" onClick={() => setShowAddModal(true)}>+ <Button+ icon="add"+ onClick={() => {+ setNameError(null);+ setCreateError(null);+ clearPageError();+ setShowAddModal(true);+ }}+ >{t("createKey")}</Button></div>@@ -554,7 +557,14 @@ export default function ApiManagerPageClient() {</div><p className="text-text-main font-medium mb-2">{t("noKeys")}</p><p className="text-sm text-text-muted mb-4">{t("noKeysDesc")}</p>- <Button icon="add" onClick={() => setShowAddModal(true)}>+ <Button+ icon="add"+ onClick={() => {+ setNameError(null);+ setCreateError(null);+ setShowAddModal(true);+ }}+ >{t("createFirstKey")}</Button></div>@@ -759,6 +769,8 @@ export default function ApiManagerPageClient() {onClose={() => {setShowAddModal(false);setNewKeyName("");+ setNameError(null);+ setCreateError(null);}}><div className="flex flex-col gap-4">@@ -768,25 +780,42 @@ export default function ApiManagerPageClient() {</label><Inputvalue={newKeyName}- onChange={(e) => setNewKeyName(e.target.value)}+ onChange={(e) => {+ setNewKeyName(e.target.value);+ setNameError(null);+ }}placeholder={t("keyNamePlaceholder")}maxLength={MAX_KEY_NAME_LENGTH}+ error={nameError}autoFocus/><p className="text-xs text-text-muted mt-1.5">{t("keyNameDesc")}</p></div>+ {createError && (+ <div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-red-500/10 border border-red-500/30">+ <span className="material-symbols-outlined text-red-500 text-sm">error</span>+ <p className="text-sm text-red-700 dark:text-red-300 flex-1">{createError}</p>+ </div>+ )}<div className="flex gap-2"><ButtononClick={() => {setShowAddModal(false);setNewKeyName("");+ setNameError(null);+ setCreateError(null);}}variant="ghost"fullWidth>{tc("cancel")}</Button>- <Button onClick={handleCreateKey} fullWidth disabled={!newKeyName.trim()}>+ <Button+ onClick={handleCreateKey}+ fullWidth+ disabled={!newKeyName.trim()}+ loading={isSubmitting}+ >{t("createKey")}</Button></div>@@ -905,6 +934,8 @@ const PermissionsModal = memo(function PermissionsModal({const [scheduleTz, setScheduleTz] = useState(apiKey?.accessSchedule?.tz ?? Intl.DateTimeFormat().resolvedOptions().timeZone);+ const [nameError, setNameError] = useState<string | null>(null);+ const [saveError, setSaveError] = useState<string | null>(null);const [selectedConnections, setSelectedConnections] = useState<string[]>(initialConnections);const [allowAllConnections, setAllowAllConnections] = useState(initialConnections.length === 0);const [expandedProviders, setExpandedProviders] = useState<Set<string>>(() => {@@ -992,6 +1023,29 @@ const PermissionsModal = memo(function PermissionsModal({);const handleSave = useCallback(() => {+ // Clear previous inline errors+ setNameError(null);+ setSaveError(null);++ // Validate name inline before calling onSave+ const validation = validateKeyName(keyName, t);+ if (!validation.valid) {+ setNameError(validation.error || t("invalidKeyName"));+ return;+ }++ // Validate models selection+ if (!allowAll && !Array.isArray(selectedModels)) {+ setSaveError(t("invalidModelsSelection"));+ return;+ }++ // Limit number of selected models to prevent abuse+ if (!allowAll && selectedModels.length > MAX_SELECTED_MODELS) {+ setSaveError(t("cannotSelectMoreThanModels", { max: MAX_SELECTED_MODELS }));+ return;+ }+const schedule: AccessSchedule | null = scheduleEnabled? {enabled: true,@@ -1027,6 +1081,7 @@ const PermissionsModal = memo(function PermissionsModal({scheduleUntil,scheduleDays,scheduleTz,+ t,]);const selectedCount = selectedModels.length;@@ -1048,13 +1103,25 @@ const PermissionsModal = memo(function PermissionsModal({<div className="w-48 shrink-0"><Inputvalue={keyName}- onChange={(e) => setKeyName(e.target.value)}+ onChange={(e) => {+ setKeyName(e.target.value);+ setNameError(null);+ }}placeholder={t("keyNamePlaceholder")}maxLength={MAX_KEY_NAME_LENGTH}+ error={nameError}/></div></div>+ {/* Inline save error */}+ {saveError && (+ <div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-red-500/10 border border-red-500/30">+ <span className="material-symbols-outlined text-red-500 text-sm">error</span>+ <p className="text-sm text-red-700 dark:text-red-300 flex-1">{saveError}</p>+ </div>+ )}+{/* Access Mode Toggle */}<div className="flex gap-2 p-1 bg-surface rounded-lg"><buttondiff --git a/src/app/(dashboard)/dashboard/compression/page.tsx b/src/app/(dashboard)/dashboard/compression/page.tsxindex 7f4c6363b6..63d5b50ca1 100644--- a/src/app/(dashboard)/dashboard/compression/page.tsx+++ b/src/app/(dashboard)/dashboard/compression/page.tsx@@ -1,20 +1,10 @@-"use client";+import { redirect } from "next/navigation";-import CompressionSettingsTab from "@/app/(dashboard)/dashboard/settings/components/CompressionSettingsTab";+export const metadata = {+ title: "Compression",+ description: "Configure context compression settings to reduce token usage and costs.",+};export default function CompressionPage() {- return (- <div className="flex flex-col gap-6">- <div>- <h1 className="text-2xl font-bold flex items-center gap-2">- <span className="material-symbols-outlined text-primary text-[28px]">compress</span>- Compression- </h1>- <p className="text-sm text-text-muted mt-1">- Configure context compression settings to reduce token usage and costs.- </p>- </div>- <CompressionSettingsTab />- </div>- );+ redirect("/dashboard/context/caveman");}diff --git a/src/app/(dashboard)/dashboard/context/caveman/CavemanContextPageClient.tsx b/src/app/(dashboard)/dashboard/context/caveman/CavemanContextPageClient.tsxnew file mode 100644index 0000000000..e879548954--- /dev/null+++ b/src/app/(dashboard)/dashboard/context/caveman/CavemanContextPageClient.tsx@@ -0,0 +1,262 @@+"use client";++import { useEffect, useMemo, useState } from "react";+import { useTranslations } from "next-intl";+import CompressionSettingsTab from "@/app/(dashboard)/dashboard/settings/components/CompressionSettingsTab";++type AnalyticsSummary = {+ totalRequests: number;+ totalTokensSaved: number;+ avgSavingsPct: number;+ avgDurationMs: number;+ byEngine?: Record<string, { count: number; tokensSaved: number; avgSavingsPct: number }>;+ byMode?: Record<string, { count: number; tokensSaved: number; avgSavingsPct: number }>;+ last24h?: Array<{ hour: string; count: number; tokensSaved: number }>;+};++type LanguageConfig = {+ enabled: boolean;+ defaultLanguage: string;+ autoDetect: boolean;+ enabledPacks: string[];+};++type OutputModeConfig = {+ enabled: boolean;+ intensity: "lite" | "full" | "ultra";+ autoClarity: boolean;+};++type CompressionSettings = {+ languageConfig?: LanguageConfig;+ cavemanOutputMode?: OutputModeConfig;+};++type LanguagePack = { language: string; ruleCount: number; categories?: string[] };++function formatNumber(value: number | undefined): string {+ return new Intl.NumberFormat().format(value ?? 0);+}++export default function CavemanContextPageClient() {+ const t = useTranslations("contextCaveman");+ const [analytics, setAnalytics] = useState<AnalyticsSummary | null>(null);+ const [settings, setSettings] = useState<CompressionSettings | null>(null);+ const [languagePacks, setLanguagePacks] = useState<LanguagePack[]>([]);+ const [saving, setSaving] = useState(false);++ const refreshSettings = () => {+ fetch("/api/context/caveman/config")+ .then((res) => (res.ok ? res.json() : null))+ .then((data) => setSettings(data))+ .catch(() => setSettings(null));+ };++ useEffect(() => {+ fetch("/api/context/analytics?since=7d")+ .then((res) => (res.ok ? res.json() : null))+ .then((data) => setAnalytics(data))+ .catch(() => setAnalytics(null));+ fetch("/api/compression/language-packs")+ .then((res) => (res.ok ? res.json() : null))+ .then((data) => setLanguagePacks(Array.isArray(data?.packs) ? data.packs : []))+ .catch(() => setLanguagePacks([]));+ refreshSettings();+ }, []);++ const languageConfig: LanguageConfig = settings?.languageConfig ?? {+ enabled: false,+ defaultLanguage: "en",+ autoDetect: true,+ enabledPacks: ["en"],+ };+ const outputMode: OutputModeConfig = settings?.cavemanOutputMode ?? {+ enabled: false,+ intensity: "full",+ autoClarity: true,+ };++ const saveSettings = async (patch: Partial<CompressionSettings>) => {+ setSaving(true);+ try {+ const res = await fetch("/api/context/caveman/config", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(patch),+ });+ if (res.ok) setSettings(await res.json());+ } finally {+ setSaving(false);+ }+ };++ const updateLanguageConfig = (patch: Partial<LanguageConfig>) => {+ saveSettings({ languageConfig: { ...languageConfig, ...patch } });+ };++ const updateOutputMode = (patch: Partial<OutputModeConfig>) => {+ saveSettings({ cavemanOutputMode: { ...outputMode, ...patch } });+ };++ const togglePack = (language: string, enabled: boolean) => {+ const enabledPacks = enabled+ ? [...new Set([...languageConfig.enabledPacks, language])]+ : languageConfig.enabledPacks.filter((pack) => pack !== language && pack !== "en");+ updateLanguageConfig({ enabledPacks });+ };++ const cavemanStats = analytics?.byEngine?.caveman ?? analytics?.byEngine?.standard;+ const modeBreakdown = useMemo(() => Object.entries(analytics?.byMode ?? {}), [analytics]);+ const statCards = [+ [t("requests"), formatNumber(cavemanStats?.count ?? analytics?.totalRequests)],+ [t("tokensSaved"), formatNumber(cavemanStats?.tokensSaved ?? analytics?.totalTokensSaved)],+ [t("savingsPercent"), `${cavemanStats?.avgSavingsPct ?? analytics?.avgSavingsPct ?? 0}%`],+ [t("avgLatency"), `${analytics?.avgDurationMs ?? 0}ms`],+ ];+ const previewPrompt = `[OmniRoute Caveman Output Mode]\n${t(`preview.${outputMode.intensity}`)}`;++ return (+ <div className="mx-auto flex max-w-6xl flex-col gap-6">+ <header className="flex flex-col gap-2">+ <div className="flex items-center gap-3">+ <span className="material-symbols-outlined text-[30px] text-primary">compress</span>+ <div>+ <h1 className="text-2xl font-bold text-text-main">{t("title")}</h1>+ <p className="text-sm text-text-muted">{t("description")}</p>+ </div>+ </div>+ </header>++ <section className="grid grid-cols-1 gap-3 sm:grid-cols-4">+ {statCards.map(([label, value]) => (+ <div key={label} className="rounded-lg border border-border bg-surface p-4">+ <p className="text-xs uppercase text-text-muted">{label}</p>+ <p className="mt-1 text-xl font-semibold text-text-main">{value}</p>+ </div>+ ))}+ </section>++ <section className="rounded-lg border border-border bg-surface p-4">+ <div className="flex flex-col gap-1">+ <h2 className="text-sm font-semibold text-text-main">{t("languagePacks")}</h2>+ <p className="text-xs text-text-muted">{t("languagePacksDesc")}</p>+ </div>+ <div className="mt-4 flex flex-wrap gap-4 text-sm text-text-main">+ <label className="flex items-center gap-2">+ <input+ type="checkbox"+ checked={languageConfig.enabled}+ disabled={saving}+ onChange={(event) => updateLanguageConfig({ enabled: event.target.checked })}+ />+ {t("enabled")}+ </label>+ <label className="flex items-center gap-2">+ <input+ type="checkbox"+ checked={languageConfig.autoDetect}+ disabled={saving}+ onChange={(event) => updateLanguageConfig({ autoDetect: event.target.checked })}+ />+ {t("autoDetect")}+ </label>+ <select+ value={languageConfig.defaultLanguage}+ disabled={saving || languageConfig.autoDetect}+ onChange={(event) => updateLanguageConfig({ defaultLanguage: event.target.value })}+ className="rounded-lg border border-border bg-bg px-3 py-2 text-sm"+ >+ {languagePacks.map((pack) => (+ <option key={pack.language} value={pack.language}>+ {pack.language}+ </option>+ ))}+ </select>+ </div>+ <div className="mt-4 grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">+ {languagePacks.map((pack) => (+ <label+ key={pack.language}+ className="flex items-center justify-between rounded-lg border border-border bg-bg p-3 text-sm text-text-main"+ >+ <span>+ {pack.language} - {t("rulesCount", { count: pack.ruleCount })}+ </span>+ <input+ type="checkbox"+ checked={languageConfig.enabledPacks.includes(pack.language)}+ disabled={saving || pack.language === "en"}+ onChange={(event) => togglePack(pack.language, event.target.checked)}+ />+ </label>+ ))}+ </div>+ </section>++ <section className="grid grid-cols-1 gap-4 lg:grid-cols-2">+ <div className="rounded-lg border border-border bg-surface p-4">+ <h2 className="text-sm font-semibold text-text-main">{t("analyticsTitle")}</h2>+ <div className="mt-3 space-y-2 text-sm text-text-main">+ {modeBreakdown.length === 0 ? (+ <p className="text-text-muted">{t("noAnalytics")}</p>+ ) : (+ modeBreakdown.map(([mode, stats]) => (+ <div key={mode} className="flex items-center justify-between gap-3">+ <span>{mode}</span>+ <span className="font-mono text-xs text-text-muted">+ {formatNumber(stats.tokensSaved)} / {stats.avgSavingsPct}%+ </span>+ </div>+ ))+ )}+ </div>+ </div>++ <div className="rounded-lg border border-border bg-surface p-4">+ <h2 className="text-sm font-semibold text-text-main">{t("outputModeTitle")}</h2>+ <p className="mt-1 text-xs text-text-muted">{t("outputModeDesc")}</p>+ <div className="mt-3 flex flex-wrap gap-4 text-sm text-text-main">+ <label className="flex items-center gap-2">+ <input+ type="checkbox"+ checked={outputMode.enabled}+ disabled={saving}+ onChange={(event) => updateOutputMode({ enabled: event.target.checked })}+ />+ {t("enabled")}+ </label>+ <label className="flex items-center gap-2">+ <input+ type="checkbox"+ checked={outputMode.autoClarity}+ disabled={saving}+ onChange={(event) => updateOutputMode({ autoClarity: event.target.checked })}+ />+ {t("autoClarity")}+ </label>+ <select+ value={outputMode.intensity}+ disabled={saving}+ onChange={(event) =>+ updateOutputMode({ intensity: event.target.value as OutputModeConfig["intensity"] })+ }+ className="rounded-lg border border-border bg-bg px-3 py-2 text-sm"+ >+ <option value="lite">lite</option>+ <option value="full">full</option>+ <option value="ultra">ultra</option>+ </select>+ </div>+ <pre className="mt-3 overflow-auto rounded-lg border border-border bg-bg p-3 text-xs text-text-main">+ {previewPrompt}+ </pre>+ <p className="mt-3 text-xs text-text-muted">+ {t("bypassConditions")}: {t("bypassConditionsList")}+ </p>+ </div>+ </section>++ <CompressionSettingsTab />+ </div>+ );+}diff --git a/src/app/(dashboard)/dashboard/context/caveman/page.tsx b/src/app/(dashboard)/dashboard/context/caveman/page.tsxnew file mode 100644index 0000000000..bfeae4c1cb--- /dev/null+++ b/src/app/(dashboard)/dashboard/context/caveman/page.tsx@@ -0,0 +1,5 @@+import CavemanContextPageClient from "./CavemanContextPageClient";++export default function CavemanContextPage() {+ return <CavemanContextPageClient />;+}diff --git a/src/app/(dashboard)/dashboard/context/combos/CompressionCombosPageClient.tsx b/src/app/(dashboard)/dashboard/context/combos/CompressionCombosPageClient.tsxnew file mode 100644index 0000000000..58149a9aa6--- /dev/null+++ b/src/app/(dashboard)/dashboard/context/combos/CompressionCombosPageClient.tsx@@ -0,0 +1,391 @@+"use client";++import { useEffect, useState } from "react";+import { useTranslations } from "next-intl";++type PipelineStep = { engine: string; intensity?: string };+type CompressionCombo = {+ id: string;+ name: string;+ description: string;+ pipeline: PipelineStep[];+ languagePacks: string[];+ outputMode: boolean;+ outputModeIntensity: string;+ isDefault: boolean;+};+type RoutingCombo = { id?: string; name?: string };+type LanguagePack = { language: string; ruleCount: number };++const EMPTY_PIPELINE: PipelineStep[] = [+ { engine: "rtk", intensity: "standard" },+ { engine: "caveman", intensity: "full" },+];++const ENGINE_INTENSITIES: Record<string, string[]> = {+ rtk: ["minimal", "standard", "aggressive"],+ caveman: ["lite", "full", "ultra"],+ lite: ["lite"],+ aggressive: ["standard"],+ ultra: ["ultra"],+};++export default function CompressionCombosPageClient() {+ const t = useTranslations("contextCombos");+ const [combos, setCombos] = useState<CompressionCombo[]>([]);+ const [routingCombos, setRoutingCombos] = useState<RoutingCombo[]>([]);+ const [languagePacks, setLanguagePacks] = useState<LanguagePack[]>([]);+ const [editingId, setEditingId] = useState<string | null>(null);+ const [name, setName] = useState("");+ const [description, setDescription] = useState("");+ const [pipeline, setPipeline] = useState<PipelineStep[]>(EMPTY_PIPELINE);+ const [selectedPacks, setSelectedPacks] = useState<string[]>(["en"]);+ const [outputMode, setOutputMode] = useState(false);+ const [outputModeIntensity, setOutputModeIntensity] = useState("full");+ const [assignmentIds, setAssignmentIds] = useState<string[]>([]);+ const [saving, setSaving] = useState(false);++ const refresh = () => {+ fetch("/api/context/combos")+ .then((res) => (res.ok ? res.json() : null))+ .then((data) => setCombos(Array.isArray(data?.combos) ? data.combos : []))+ .catch(() => {});+ };++ useEffect(() => {+ refresh();+ fetch("/api/combos")+ .then((res) => (res.ok ? res.json() : null))+ .then((data) => setRoutingCombos(Array.isArray(data?.combos) ? data.combos : []))+ .catch(() => {});+ fetch("/api/compression/language-packs")+ .then((res) => (res.ok ? res.json() : null))+ .then((data) => setLanguagePacks(Array.isArray(data?.packs) ? data.packs : []))+ .catch(() => {});+ }, []);++ const resetForm = () => {+ setEditingId(null);+ setName("");+ setDescription("");+ setPipeline(EMPTY_PIPELINE);+ setSelectedPacks(["en"]);+ setOutputMode(false);+ setOutputModeIntensity("full");+ setAssignmentIds([]);+ };++ const loadAssignments = async (id: string) => {+ const res = await fetch(`/api/context/combos/${id}/assignments`);+ if (!res.ok) return [];+ const data = await res.json();+ return Array.isArray(data?.assignments)+ ? data.assignments.map((item: { routingComboId: string }) => item.routingComboId)+ : [];+ };++ const editCombo = async (combo: CompressionCombo) => {+ setEditingId(combo.id);+ setName(combo.name);+ setDescription(combo.description ?? "");+ setPipeline(combo.pipeline.length > 0 ? combo.pipeline : EMPTY_PIPELINE);+ setSelectedPacks(combo.languagePacks?.length ? combo.languagePacks : ["en"]);+ setOutputMode(Boolean(combo.outputMode));+ setOutputModeIntensity(combo.outputModeIntensity ?? "full");+ setAssignmentIds(await loadAssignments(combo.id));+ };++ const saveCombo = async () => {+ const trimmed = name.trim();+ if (!trimmed) return;+ setSaving(true);+ try {+ const payload = {+ name: trimmed,+ description,+ pipeline,+ languagePacks: selectedPacks,+ outputMode,+ outputModeIntensity,+ };+ const res = await fetch(+ editingId ? `/api/context/combos/${editingId}` : "/api/context/combos",+ {+ method: editingId ? "PUT" : "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(payload),+ }+ );+ if (!res.ok) return;+ const combo = await res.json();+ await fetch(`/api/context/combos/${combo.id}/assignments`, {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ routingComboIds: assignmentIds }),+ });+ resetForm();+ refresh();+ } finally {+ setSaving(false);+ }+ };++ const deleteCombo = async (combo: CompressionCombo) => {+ if (!confirm(t("deleteConfirm"))) return;+ const res = await fetch(`/api/context/combos/${combo.id}`, { method: "DELETE" });+ if (res.ok) refresh();+ };++ const setDefault = async (id: string) => {+ const res = await fetch(`/api/context/combos/${id}`, {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ isDefault: true }),+ });+ if (res.ok) refresh();+ };++ const updateStep = (index: number, patch: Partial<PipelineStep>) => {+ setPipeline((current) =>+ current.map((step, stepIndex) => {+ if (stepIndex !== index) return step;+ const next = { ...step, ...patch };+ const allowed = ENGINE_INTENSITIES[next.engine] ?? ["standard"];+ return {+ ...next,+ intensity: allowed.includes(next.intensity ?? "") ? next.intensity : allowed[0],+ };+ })+ );+ };++ const togglePack = (language: string, enabled: boolean) => {+ setSelectedPacks((current) =>+ enabled+ ? [...new Set([...current, language])]+ : current.filter((item) => item !== language && item !== "en")+ );+ };++ const toggleAssignment = (id: string, enabled: boolean) => {+ setAssignmentIds((current) =>+ enabled ? [...new Set([...current, id])] : current.filter((item) => item !== id)+ );+ };++ return (+ <div className="mx-auto flex max-w-6xl flex-col gap-6">+ <header className="flex flex-col gap-2">+ <div className="flex items-center gap-3">+ <span className="material-symbols-outlined text-[30px] text-primary">hub</span>+ <div>+ <h1 className="text-2xl font-bold text-text-main">{t("title")}</h1>+ <p className="text-sm text-text-muted">{t("description")}</p>+ </div>+ </div>+ </header>++ <section className="rounded-lg border border-border bg-surface p-4">+ <div className="grid grid-cols-1 gap-3 md:grid-cols-2">+ <input+ value={name}+ onChange={(event) => setName(event.target.value)}+ placeholder={t("name")}+ className="rounded-lg border border-border bg-bg px-3 py-2 text-sm text-text-main"+ />+ <input+ value={description}+ onChange={(event) => setDescription(event.target.value)}+ placeholder={t("descriptionField")}+ className="rounded-lg border border-border bg-bg px-3 py-2 text-sm text-text-main"+ />+ </div>++ <div className="mt-4 space-y-3">+ <div className="flex items-center justify-between">+ <h2 className="text-sm font-semibold text-text-main">{t("pipeline")}</h2>+ <button+ onClick={() =>+ setPipeline((current) => [...current, { engine: "caveman", intensity: "full" }])+ }+ className="rounded-lg border border-border px-3 py-1.5 text-xs text-text-main"+ >+ {t("addStep")}+ </button>+ </div>+ {pipeline.map((step, index) => (+ <div key={index} className="grid grid-cols-[1fr_1fr_auto] gap-2">+ <select+ value={step.engine}+ onChange={(event) => updateStep(index, { engine: event.target.value })}+ className="rounded-lg border border-border bg-bg px-3 py-2 text-sm text-text-main"+ >+ {Object.keys(ENGINE_INTENSITIES).map((engine) => (+ <option key={engine} value={engine}>+ {engine}+ </option>+ ))}+ </select>+ <select+ value={step.intensity ?? ""}+ onChange={(event) => updateStep(index, { intensity: event.target.value })}+ className="rounded-lg border border-border bg-bg px-3 py-2 text-sm text-text-main"+ >+ {(ENGINE_INTENSITIES[step.engine] ?? ["standard"]).map((intensity) => (+ <option key={intensity} value={intensity}>+ {intensity}+ </option>+ ))}+ </select>+ <button+ onClick={() => setPipeline((current) => current.filter((_, i) => i !== index))}+ className="rounded-lg border border-border px-3 py-2 text-sm text-text-main"+ disabled={pipeline.length <= 1}+ >+ {t("removeStep")}+ </button>+ </div>+ ))}+ </div>++ <div className="mt-4 grid grid-cols-1 gap-4 lg:grid-cols-3">+ <div>+ <h2 className="mb-2 text-sm font-semibold text-text-main">{t("languagePacks")}</h2>+ <div className="space-y-2 text-sm text-text-main">+ {languagePacks.map((pack) => (+ <label key={pack.language} className="flex items-center justify-between gap-2">+ <span>+ {pack.language} ({pack.ruleCount})+ </span>+ <input+ type="checkbox"+ checked={selectedPacks.includes(pack.language)}+ disabled={pack.language === "en"}+ onChange={(event) => togglePack(pack.language, event.target.checked)}+ />+ </label>+ ))}+ </div>+ </div>+ <div className="space-y-2 text-sm text-text-main">+ <h2 className="text-sm font-semibold text-text-main">{t("outputMode")}</h2>+ <label className="flex items-center gap-2">+ <input+ type="checkbox"+ checked={outputMode}+ onChange={(event) => setOutputMode(event.target.checked)}+ />+ {t("enabled")}+ </label>+ <select+ value={outputModeIntensity}+ onChange={(event) => setOutputModeIntensity(event.target.value)}+ className="w-full rounded-lg border border-border bg-bg px-3 py-2 text-sm"+ >+ <option value="lite">lite</option>+ <option value="full">full</option>+ <option value="ultra">ultra</option>+ </select>+ </div>+ <div>+ <h2 className="mb-2 text-sm font-semibold text-text-main">{t("assignToRouting")}</h2>+ <div className="max-h-44 space-y-2 overflow-auto text-sm text-text-main">+ {routingCombos.length === 0 ? (+ <p className="text-xs text-text-muted">{t("noAssignments")}</p>+ ) : (+ routingCombos.map((combo) => {+ const id = combo.id ?? combo.name ?? "";+ if (!id) return null;+ return (+ <label key={id} className="flex items-center justify-between gap-2">+ <span className="truncate">{combo.name ?? id}</span>+ <input+ type="checkbox"+ checked={assignmentIds.includes(id)}+ onChange={(event) => toggleAssignment(id, event.target.checked)}+ />+ </label>+ );+ })+ )}+ </div>+ </div>+ </div>++ <div className="mt-4 flex flex-wrap gap-2">+ <button+ onClick={saveCombo}+ disabled={saving}+ className="rounded-lg bg-primary px-4 py-2 text-sm font-medium text-white"+ >+ {editingId ? t("save") : t("createCombo")}+ </button>+ {editingId && (+ <button+ onClick={resetForm}+ className="rounded-lg border border-border px-4 py-2 text-sm text-text-main"+ >+ {t("cancel")}+ </button>+ )}+ </div>+ </section>++ <section className="grid grid-cols-1 gap-4 lg:grid-cols-2">+ {combos.map((combo) => (+ <div key={combo.id} className="rounded-lg border border-border bg-surface p-4">+ <div className="flex items-start justify-between gap-3">+ <div className="min-w-0">+ <h2 className="truncate text-base font-semibold text-text-main">{combo.name}</h2>+ <p className="mt-1 text-sm text-text-muted">{combo.description}</p>+ </div>+ {combo.isDefault && (+ <span className="rounded-full bg-primary/10 px-2 py-1 text-xs font-medium text-primary">+ {t("default")}+ </span>+ )}+ </div>+ <div className="mt-4 flex flex-wrap gap-2">+ {combo.pipeline.map((step, index) => (+ <span+ key={`${combo.id}-${index}`}+ className="rounded-lg border border-border bg-bg px-2 py-1 font-mono text-xs text-text-muted"+ >+ {index + 1}. {step.engine}+ {step.intensity ? `:${step.intensity}` : ""}+ </span>+ ))}+ </div>+ <p className="mt-3 text-xs text-text-muted">+ {t("languagePacks")}: {combo.languagePacks.join(", ")}+ </p>+ <div className="mt-4 flex flex-wrap gap-2">+ <button+ onClick={() => editCombo(combo)}+ className="rounded-lg border border-border px-3 py-1.5 text-xs text-text-main"+ >+ {t("editCombo")}+ </button>+ {!combo.isDefault && (+ <button+ onClick={() => setDefault(combo.id)}+ className="rounded-lg border border-border px-3 py-1.5 text-xs text-text-main"+ >+ {t("setAsDefault")}+ </button>+ )}+ {!combo.isDefault && (+ <button+ onClick={() => deleteCombo(combo)}+ className="rounded-lg border border-danger/40 px-3 py-1.5 text-xs text-danger"+ >+ {t("deleteCombo")}+ </button>+ )}+ </div>+ </div>+ ))}+ </section>+ </div>+ );+}diff --git a/src/app/(dashboard)/dashboard/context/combos/page.tsx b/src/app/(dashboard)/dashboard/context/combos/page.tsxnew file mode 100644index 0000000000..934ab7d451--- /dev/null+++ b/src/app/(dashboard)/dashboard/context/combos/page.tsx@@ -0,0 +1,5 @@+import CompressionCombosPageClient from "./CompressionCombosPageClient";++export default function CompressionCombosPage() {+ return <CompressionCombosPageClient />;+}diff --git a/src/app/(dashboard)/dashboard/context/rtk/RtkContextPageClient.tsx b/src/app/(dashboard)/dashboard/context/rtk/RtkContextPageClient.tsxnew file mode 100644index 0000000000..e42b098115--- /dev/null+++ b/src/app/(dashboard)/dashboard/context/rtk/RtkContextPageClient.tsx@@ -0,0 +1,349 @@+"use client";++import { useEffect, useMemo, useState } from "react";+import { useTranslations } from "next-intl";++type RtkFilter = {+ id: string;+ name: string;+ description: string;+ commandTypes: string[];+ category: string;+ priority: number;+};++type RtkConfig = {+ enabled: boolean;+ intensity: "minimal" | "standard" | "aggressive";+ applyToToolResults: boolean;+ applyToAssistantMessages: boolean;+ applyToCodeBlocks: boolean;+ enabledFilters: string[];+ disabledFilters: string[];+ maxLinesPerResult: number;+ maxCharsPerResult: number;+ deduplicateThreshold: number;+ customFiltersEnabled: boolean;+ trustProjectFilters: boolean;+ rawOutputRetention: "never" | "failures" | "always";+ rawOutputMaxBytes: number;+};++type AnalyticsSummary = {+ totalRequests: number;+ totalTokensSaved: number;+ avgSavingsPct: number;+ byEngine?: Record<string, { count: number; tokensSaved: number; avgSavingsPct: number }>;+};++type PreviewResult = {+ text?: string;+ compressed?: boolean;+ originalTokens?: number;+ compressedTokens?: number;+ techniquesUsed?: string[];+ detection?: { type: string; confidence: number; category: string };+ error?: string;+};++const SAMPLE_OUTPUT = `$ npm run typecheck+src/lib/example.ts:10:15 - error TS2322: Type 'string' is not assignable to type 'number'.++10 const value: number = "bad";+ ~~~~~++Found 1 error in src/lib/example.ts:10`;++function formatNumber(value: number | undefined): string {+ return new Intl.NumberFormat().format(value ?? 0);+}++export default function RtkContextPageClient() {+ const t = useTranslations("contextRtk");+ const [filters, setFilters] = useState<RtkFilter[]>([]);+ const [config, setConfig] = useState<RtkConfig | null>(null);+ const [analytics, setAnalytics] = useState<AnalyticsSummary | null>(null);+ const [sample, setSample] = useState(SAMPLE_OUTPUT);+ const [preview, setPreview] = useState<PreviewResult | null>(null);+ const [saving, setSaving] = useState(false);++ useEffect(() => {+ fetch("/api/context/rtk/filters")+ .then((res) => (res.ok ? res.json() : null))+ .then((data) => setFilters(Array.isArray(data?.filters) ? data.filters : []))+ .catch(() => {});+ fetch("/api/context/rtk/config")+ .then((res) => (res.ok ? res.json() : null))+ .then((data) => setConfig(data))+ .catch(() => {});+ fetch("/api/context/analytics?since=7d")+ .then((res) => (res.ok ? res.json() : null))+ .then((data) => setAnalytics(data))+ .catch(() => {});+ }, []);++ const groupedFilters = useMemo(() => {+ return filters.reduce<Record<string, RtkFilter[]>>((groups, filter) => {+ groups[filter.category] = [...(groups[filter.category] ?? []), filter];+ return groups;+ }, {});+ }, [filters]);++ const activeFilterCount = useMemo(() => {+ if (!config) return 0;+ if (config.enabledFilters.length > 0) return config.enabledFilters.length;+ return filters.filter((filter) => !config.disabledFilters.includes(filter.id)).length;+ }, [config, filters]);++ const saveConfig = async (patch: Partial<RtkConfig>) => {+ if (!config) return;+ const nextConfig = { ...config, ...patch };+ setConfig(nextConfig);+ setSaving(true);+ try {+ const res = await fetch("/api/context/rtk/config", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(patch),+ });+ if (res.ok) setConfig(await res.json());+ } finally {+ setSaving(false);+ }+ };++ const toggleFilter = (filterId: string, enabled: boolean) => {+ if (!config) return;+ const disabledFilters = enabled+ ? config.disabledFilters.filter((id) => id !== filterId)+ : [...new Set([...config.disabledFilters, filterId])];+ saveConfig({ disabledFilters });+ };++ const runPreview = async () => {+ const res = await fetch("/api/context/rtk/test", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ text: sample, config: config ?? undefined }),+ });+ setPreview(res.ok ? await res.json() : { error: await res.text() });+ };++ const rtkStats = analytics?.byEngine?.rtk;+ const statCards = [+ [t("tokensFiltered"), formatNumber(rtkStats?.tokensSaved ?? analytics?.totalTokensSaved)],+ [t("filtersActive"), formatNumber(activeFilterCount)],+ [t("requests"), formatNumber(rtkStats?.count ?? analytics?.totalRequests)],+ [t("avgSavings"), `${rtkStats?.avgSavingsPct ?? analytics?.avgSavingsPct ?? 0}%`],+ ];++ return (+ <div className="mx-auto flex max-w-6xl flex-col gap-6">+ <header className="flex flex-col gap-2">+ <div className="flex items-center gap-3">+ <span className="material-symbols-outlined text-[30px] text-primary">filter_alt</span>+ <div>+ <h1 className="text-2xl font-bold text-text-main">{t("title")}</h1>+ <p className="text-sm text-text-muted">{t("description")}</p>+ </div>+ </div>+ </header>++ <section className="grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4">+ {statCards.map(([label, value]) => (+ <div key={label} className="rounded-lg border border-border bg-surface p-4">+ <p className="text-xs uppercase text-text-muted">{label}</p>+ <p className="mt-1 text-xl font-semibold text-text-main">{value}</p>+ </div>+ ))}+ </section>++ {config && (+ <section className="rounded-lg border border-border bg-surface p-4">+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-5">+ <label className="flex items-center gap-2 text-sm text-text-main">+ <input+ type="checkbox"+ checked={config.enabled}+ disabled={saving}+ onChange={(event) => saveConfig({ enabled: event.target.checked })}+ />+ {t("enabled")}+ </label>+ <label className="flex flex-col gap-1 text-sm text-text-main">+ {t("intensity")}+ <select+ value={config.intensity}+ disabled={saving}+ onChange={(event) =>+ saveConfig({ intensity: event.target.value as RtkConfig["intensity"] })+ }+ className="rounded border border-border bg-bg px-2 py-1 text-sm"+ >+ <option value="minimal">{t("intensityMinimal")}</option>+ <option value="standard">{t("intensityStandard")}</option>+ <option value="aggressive">{t("intensityAggressive")}</option>+ </select>+ </label>+ <label className="flex flex-col gap-1 text-sm text-text-main">+ {t("maxLines")}+ <input+ type="number"+ min={0}+ value={config.maxLinesPerResult}+ onChange={(event) =>+ saveConfig({ maxLinesPerResult: Number(event.target.value) || 0 })+ }+ className="rounded border border-border bg-bg px-2 py-1 text-sm"+ />+ </label>+ <label className="flex flex-col gap-1 text-sm text-text-main">+ {t("maxChars")}+ <input+ type="number"+ min={0}+ value={config.maxCharsPerResult}+ onChange={(event) =>+ saveConfig({ maxCharsPerResult: Number(event.target.value) || 0 })+ }+ className="rounded border border-border bg-bg px-2 py-1 text-sm"+ />+ </label>+ <label className="flex flex-col gap-1 text-sm text-text-main">+ {t("deduplicateThreshold")}+ <input+ type="number"+ min={2}+ max={100}+ value={config.deduplicateThreshold}+ onChange={(event) =>+ saveConfig({ deduplicateThreshold: Number(event.target.value) || 2 })+ }+ className="rounded border border-border bg-bg px-2 py-1 text-sm"+ />+ </label>+ <label className="flex flex-col gap-1 text-sm text-text-main">+ {t("rawOutputMaxBytes")}+ <input+ type="number"+ min={1024}+ value={config.rawOutputMaxBytes}+ onChange={(event) =>+ saveConfig({ rawOutputMaxBytes: Number(event.target.value) || 1024 })+ }+ className="rounded border border-border bg-bg px-2 py-1 text-sm"+ />+ </label>+ </div>+ <div className="mt-4 flex flex-wrap gap-4 text-sm text-text-main">+ {[+ ["applyToToolResults", t("toolResults")],+ ["applyToAssistantMessages", t("assistantMessages")],+ ["applyToCodeBlocks", t("codeBlocks")],+ ["customFiltersEnabled", t("customFilters")],+ ["trustProjectFilters", t("trustProjectFilters")],+ ].map(([key, label]) => (+ <label key={key} className="flex items-center gap-2">+ <input+ type="checkbox"+ checked={Boolean(config[key as keyof RtkConfig])}+ disabled={saving}+ onChange={(event) =>+ saveConfig({ [key]: event.target.checked } as Partial<RtkConfig>)+ }+ />+ {label}+ </label>+ ))}+ </div>+ <div className="mt-4 max-w-sm text-sm text-text-main">+ <label className="flex flex-col gap-1">+ {t("rawOutputRetention")}+ <select+ value={config.rawOutputRetention}+ disabled={saving}+ onChange={(event) =>+ saveConfig({+ rawOutputRetention: event.target.value as RtkConfig["rawOutputRetention"],+ })+ }+ className="rounded border border-border bg-bg px-2 py-1 text-sm"+ >+ <option value="never">{t("rawOutputNever")}</option>+ <option value="failures">{t("rawOutputFailures")}</option>+ <option value="always">{t("rawOutputAlways")}</option>+ </select>+ </label>+ </div>+ </section>+ )}++ <section className="grid grid-cols-1 gap-4 xl:grid-cols-[1fr_1fr]">+ <div className="rounded-lg border border-border bg-surface p-4">+ <div className="mb-3 flex items-center justify-between">+ <h2 className="text-sm font-semibold text-text-main">{t("filterTesting")}</h2>+ <button+ onClick={runPreview}+ className="rounded-lg bg-primary px-3 py-2 text-sm font-medium text-white"+ >+ {t("run")}+ </button>+ </div>+ <textarea+ value={sample}+ onChange={(event) => setSample(event.target.value)}+ placeholder={t("pasteOutput")}+ className="h-72 w-full rounded-lg border border-border bg-bg p-3 font-mono text-xs text-text-main"+ />+ </div>+ <div className="rounded-lg border border-border bg-surface p-4">+ <h2 className="mb-3 text-sm font-semibold text-text-main">{t("result")}</h2>+ {preview?.detection && (+ <p className="mb-2 text-xs text-text-muted">+ {t("detected")}: {preview.detection.type} (+ {Math.round(preview.detection.confidence * 100)}%)+ </p>+ )}+ <pre className="h-72 overflow-auto rounded-lg border border-border bg-bg p-3 text-xs text-text-main">+ {preview ? JSON.stringify(preview, null, 2) : t("previewEmpty")}+ </pre>+ </div>+ </section>++ <section className="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-3">+ {Object.entries(groupedFilters).map(([category, items]) => (+ <div key={category} className="rounded-lg border border-border bg-surface p-4">+ <h2 className="text-sm font-semibold capitalize text-text-main">{category}</h2>+ <div className="mt-3 space-y-3">+ {items.map((filter) => {+ const enabled = config ? !config.disabledFilters.includes(filter.id) : true;+ return (+ <div+ key={filter.id}+ className="border-t border-border pt-3 first:border-t-0 first:pt-0"+ >+ <div className="flex items-start justify-between gap-3">+ <div className="min-w-0">+ <p className="text-sm font-medium text-text-main">{filter.name}</p>+ <p className="mt-1 text-xs text-text-muted">{filter.description}</p>+ </div>+ <input+ type="checkbox"+ checked={enabled}+ disabled={!config || saving}+ onChange={(event) => toggleFilter(filter.id, event.target.checked)}+ />+ </div>+ <p className="mt-2 font-mono text-[11px] text-text-muted">+ {filter.commandTypes.join(", ")}+ </p>+ </div>+ );+ })}+ </div>+ </div>+ ))}+ </section>+ </div>+ );+}diff --git a/src/app/(dashboard)/dashboard/context/rtk/page.tsx b/src/app/(dashboard)/dashboard/context/rtk/page.tsxnew file mode 100644index 0000000000..50079bbf14--- /dev/null+++ b/src/app/(dashboard)/dashboard/context/rtk/page.tsx@@ -0,0 +1,5 @@+import RtkContextPageClient from "./RtkContextPageClient";++export default function RtkContextPage() {+ return <RtkContextPageClient />;+}diff --git a/src/app/(dashboard)/dashboard/providers/[id]/page.tsx b/src/app/(dashboard)/dashboard/providers/[id]/page.tsxindex d9095ee893..cdd04441bb 100644--- a/src/app/(dashboard)/dashboard/providers/[id]/page.tsx+++ b/src/app/(dashboard)/dashboard/providers/[id]/page.tsx@@ -54,6 +54,7 @@ import {getCodexRequestDefaults as _getCodexRequestDefaults,} from "@/lib/providers/requestDefaults";import { isClaudeExtraUsageBlockEnabled } from "@/lib/providers/claudeExtraUsage";+import { parseExtraApiKeys } from "@/shared/utils/parseApiKeys";import { resolveDashboardProviderInfo } from "../providerPageUtils";type CompatByProtocolMap = Partial<@@ -2020,6 +2021,10 @@ export default function ProviderDetailPage() {modelId,modelName: model.name || modelId,source: "imported",+ ...(typeof model.apiFormat === "string" ? { apiFormat: model.apiFormat } : {}),+ ...(Array.isArray(model.supportedEndpoints)+ ? { supportedEndpoints: model.supportedEndpoints }+ : {}),}),});// Also create an alias for routing@@ -4212,6 +4217,7 @@ function CustomModelsSection({<option value="chat-completions">{t("chatCompletions")}</option><option value="responses">{t("responsesApi")}</option><option value="embeddings">{t("embeddings")}</option>+ <option value="rerank">Rerank</option><option value="audio-transcriptions">{t("audioTranscriptions")}</option><option value="audio-speech">{t("audioSpeech")}</option><option value="images-generations">{t("imagesGenerations")}</option>@@ -4222,7 +4228,7 @@ function CustomModelsSection({{t("supportedEndpointsLabel")}</span><div className="flex items-center gap-3">- {["chat", "embeddings", "images", "audio"].map((ep) => (+ {["chat", "embeddings", "rerank", "images", "audio"].map((ep) => (<labelkey={ep}className="flex items-center gap-1.5 text-xs text-text-main cursor-pointer"@@ -4243,9 +4249,11 @@ function CustomModelsSection({? `💬 ${t("supportedEndpointChat")}`: ep === "embeddings"? `📐 ${t("supportedEndpointEmbeddings")}`- : ep === "images"- ? `🖼️ ${t("supportedEndpointImages")}`- : `🔊 ${t("supportedEndpointAudio")}`}+ : ep === "rerank"+ ? "Rerank"+ : ep === "images"+ ? `🖼️ ${t("supportedEndpointImages")}`+ : `🔊 ${t("supportedEndpointAudio")}`}</label>))}</div>@@ -4347,6 +4355,7 @@ function CustomModelsSection({<option value="chat-completions">{t("chatCompletions")}</option><option value="responses">{t("responsesApi")}</option><option value="embeddings">{t("embeddings")}</option>+ <option value="rerank">Rerank</option><option value="audio-transcriptions">{t("audioTranscriptions")}</option><option value="audio-speech">{t("audioSpeech")}</option><option value="images-generations">{t("imagesGenerations")}</option>@@ -4357,7 +4366,7 @@ function CustomModelsSection({{t("supportedEndpointsLabel")}</span><div className="flex flex-wrap items-center gap-x-2 sm:gap-x-3 gap-y-1 min-w-0">- {["chat", "embeddings", "images", "audio"].map((ep) => (+ {["chat", "embeddings", "rerank", "images", "audio"].map((ep) => (<labelkey={ep}className="flex items-center gap-1.5 text-xs text-text-main cursor-pointer whitespace-nowrap"@@ -4380,9 +4389,11 @@ function CustomModelsSection({? `💬 ${t("supportedEndpointChat")}`: ep === "embeddings"? `📐 ${t("supportedEndpointEmbeddings")}`- : ep === "images"- ? `🖼️ ${t("supportedEndpointImages")}`- : `🔊 ${t("supportedEndpointAudio")}`}+ : ep === "rerank"+ ? "Rerank"+ : ep === "images"+ ? `🖼️ ${t("supportedEndpointImages")}`+ : `🔊 ${t("supportedEndpointAudio")}`}</label>))}</div>@@ -5979,6 +5990,7 @@ function normalizeAndValidateHttpBaseUrl(rawValue, fallbackUrl) {function EditConnectionModal({ isOpen, connection, onSave, onClose }: EditConnectionModalProps) {const t = useTranslations("providers");+ const notify = useNotificationStore();const [formData, setFormData] = useState({name: "",priority: 1,@@ -6042,7 +6054,7 @@ function EditConnectionModal({ isOpen, connection, onSave, onClose }: EditConnec: t("leaveBlankKeepCurrentApiKey");useEffect(() => {- if (connection) {+ if (isOpen && connection) {const rawBaseUrl = connection.providerSpecificData?.baseUrl;const existingBaseUrl = typeof rawBaseUrl === "string" ? rawBaseUrl : "";const rawRegion = connection.providerSpecificData?.region;@@ -6064,9 +6076,9 @@ function EditConnectionModal({ isOpen, connection, onSave, onClose }: EditConnecname: connection.name || "",priority: connection.priority || 1,maxConcurrent:- connection.maxConcurrent === null || connection.maxConcurrent === undefined- ? ""- : String(connection.maxConcurrent),+ connection.maxConcurrent !== null && connection.maxConcurrent !== undefined+ ? String(connection.maxConcurrent)+ : "",apiKey: "",healthCheckInterval: connection.healthCheckInterval ?? 60,baseUrl: existingBaseUrl || defaultBaseUrl,@@ -6103,7 +6115,7 @@ function EditConnectionModal({ isOpen, connection, onSave, onClose }: EditConnecsetValidationResult(null);setSaveError(null);}- }, [connection, defaultBaseUrl, isVertex]);+ }, [isOpen, connection, defaultBaseUrl, isVertex]);const handleTest = async () => {if (!connection?.provider) return;@@ -6160,6 +6172,17 @@ function EditConnectionModal({ isOpen, connection, onSave, onClose }: EditConnec}};+ const handleAddParsedExtraKeys = (raw: string) => {+ const { added, duplicates } = parseExtraApiKeys(raw, extraApiKeys);+ if (added.length > 0) {+ setExtraApiKeys((prev) => [...prev, ...added]);+ notify.success(t("bulkPasteAdded", { count: added.length }));+ }+ if (duplicates > 0) {+ notify.warning(t("bulkPasteDuplicatesIgnored", { count: duplicates }));+ }+ };+const handleSubmit = async () => {setSaving(true);setSaveError(null);@@ -6610,12 +6633,23 @@ function EditConnectionModal({ isOpen, connection, onSave, onClose }: EditConnec{/* T07: Extra API Keys for round-robin rotation */}{!isOAuth && (<div className="flex flex-col gap-2">- <label className="text-sm font-medium text-text-main">- {t("extraApiKeysLabel")}- <span className="ml-2 text-[11px] font-normal text-text-muted">- ({t("extraApiKeysHint")})- </span>- </label>+ <div className="flex items-center justify-between gap-2">+ <label className="text-sm font-medium text-text-main">+ {t("extraApiKeysLabel")}+ <span className="ml-2 text-[11px] font-normal text-text-muted">+ ({t("extraApiKeysHint")})+ </span>+ </label>+ {extraApiKeys.length > 0 && (+ <button+ type="button"+ onClick={() => setExtraApiKeys([])}+ className="px-2.5 py-1.5 rounded-md bg-red-500/10 text-red-400 hover:bg-red-500/20 hover:text-red-300 text-xs font-medium transition-colors"+ >+ {t("deleteAllExtraApiKeys")}+ </button>+ )}+ </div>{extraApiKeys.length > 0 && (<div className="flex flex-col gap-1.5">{extraApiKeys.map((key, idx) => (@@ -6651,6 +6685,12 @@ function EditConnectionModal({ isOpen, connection, onSave, onClose }: EditConnecsetNewExtraKey("");}}}+ onPaste={(e) => {+ const text = e.clipboardData.getData("text");+ if (!/\r?\n/.test(text)) return;+ e.preventDefault();+ handleAddParsedExtraKeys(text);+ }}/><buttononClick={() => {@@ -6665,6 +6705,7 @@ function EditConnectionModal({ isOpen, connection, onSave, onClose }: EditConnec{t("add")}</button></div>+ <p className="text-[11px] text-text-muted">{t("bulkPasteHint")}</p>{extraApiKeys.length > 0 && (<p className="text-[11px] text-text-muted">{t("totalKeysRotating", { count: extraApiKeys.length + 1 })}diff --git a/src/app/(dashboard)/dashboard/settings/components/ComboDefaultsTab.tsx b/src/app/(dashboard)/dashboard/settings/components/ComboDefaultsTab.tsxindex 44f4c61f6c..7146fa8a9b 100644--- a/src/app/(dashboard)/dashboard/settings/components/ComboDefaultsTab.tsx+++ b/src/app/(dashboard)/dashboard/settings/components/ComboDefaultsTab.tsx@@ -3,7 +3,10 @@import { useState, useEffect } from "react";import { Card, Button, Input, Toggle } from "@/shared/components";import { cn } from "@/shared/utils/cn";-import { ROUTING_STRATEGIES } from "@/shared/constants/routingStrategies";+import {+ ROUTING_STRATEGIES,+ SETTINGS_FALLBACK_STRATEGY_VALUES,+} from "@/shared/constants/routingStrategies";import { useTranslations } from "next-intl";const STRATEGY_LABEL_FALLBACKS: Record<string, string> = {@@ -15,6 +18,7 @@ const LEGACY_COMBO_RESILIENCE_KEYS = new Set(["healthCheckEnabled","healthCheckTimeoutMs",]);+const ACCOUNT_FALLBACK_STRATEGIES = new Set<string>(SETTINGS_FALLBACK_STRATEGY_VALUES);function translateOrFallback(t: ReturnType<typeof useTranslations>,@@ -44,6 +48,17 @@ function sanitizeProviderOverrides(overrides?: Record<string, any> | null) {);}+function toGlobalRoutingPatch(strategy: string | undefined, stickyRoundRobinLimit?: number) {+ const patch: Record<string, unknown> = {};+ if (strategy && ACCOUNT_FALLBACK_STRATEGIES.has(strategy)) {+ patch.fallbackStrategy = strategy;+ }+ if (strategy === "round-robin" && stickyRoundRobinLimit !== undefined) {+ patch.stickyRoundRobinLimit = stickyRoundRobinLimit;+ }+ return patch;+}+export default function ComboDefaultsTab() {const [comboDefaults, setComboDefaults] = useState<any>({strategy: "priority",@@ -90,7 +105,7 @@ export default function ComboDefaultsTab() {...prev,...sanitizeComboRuntimeConfig(comboData.comboDefaults),strategy:- settingsData.fallbackStrategy ?? comboData.comboDefaults?.strategy ?? prev.strategy,+ comboData.comboDefaults?.strategy ?? settingsData.fallbackStrategy ?? prev.strategy,stickyRoundRobinLimit:settingsData.stickyRoundRobinLimit ??comboData.comboDefaults?.stickyRoundRobinLimit ??@@ -109,8 +124,7 @@ export default function ComboDefaultsTab() {};const syncGlobalRoutingSettings = async (patch: Record<string, unknown>) => {- const keys = Object.keys(patch);- if (keys.length === 0) return true;+ if (Object.keys(patch).length === 0) return;const res = await fetch("/api/settings", {method: "PATCH",@@ -121,21 +135,13 @@ export default function ComboDefaultsTab() {if (!res.ok) {throw new Error("Failed to sync global routing settings");}-- return true;};const saveComboDefaults = async () => {setSaving(true);try {const { stickyRoundRobinLimit, ...comboDefaultsPayload } = comboDefaults;- const settingsPatch: Record<string, unknown> = {};- if (comboDefaults.strategy) {- settingsPatch.fallbackStrategy = comboDefaults.strategy;- }- if (comboDefaults.strategy === "round-robin" && stickyRoundRobinLimit !== undefined) {- settingsPatch.stickyRoundRobinLimit = stickyRoundRobinLimit;- }+ const settingsPatch = toGlobalRoutingPatch(comboDefaults.strategy, stickyRoundRobinLimit);const comboDefaultsRes = await fetch("/api/settings/combo-defaults", {method: "PATCH",@@ -243,7 +249,7 @@ export default function ComboDefaultsTab() {onClick={async () => {setComboDefaults((prev) => ({ ...prev, strategy: s.value }));try {- await syncGlobalRoutingSettings({ fallbackStrategy: s.value });+ await syncGlobalRoutingSettings(toGlobalRoutingPatch(s.value));} catch (error) {console.error("Failed to sync fallback strategy:", error);showStatus("error", t("errorOccurred"));diff --git a/src/app/(dashboard)/dashboard/settings/components/CompressionSettingsTab.tsx b/src/app/(dashboard)/dashboard/settings/components/CompressionSettingsTab.tsxindex d6f4df413a..432e855740 100644--- a/src/app/(dashboard)/dashboard/settings/components/CompressionSettingsTab.tsx+++ b/src/app/(dashboard)/dashboard/settings/components/CompressionSettingsTab.tsx@@ -4,7 +4,8 @@ import { useState, useEffect } from "react";import { Card, Button } from "@/shared/components";import { useTranslations } from "next-intl";-type CompressionMode = "off" | "lite" | "standard" | "aggressive" | "ultra";+type CompressionMode = "off" | "lite" | "standard" | "aggressive" | "ultra" | "rtk" | "stacked";+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,27 @@ 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;+ intensities?: CavemanIntensity[];+ description: string;+}+const MODES: { value: CompressionMode; labelKey: string; descKey: string; icon: string }[] = [{value: "off",@@ -85,6 +105,18 @@ const MODES: { value: CompressionMode; labelKey: string; descKey: string; icon:descKey: "compressionModeUltraDesc",icon: "filter_alt",},+ {+ value: "rtk",+ labelKey: "compressionModeRtk",+ descKey: "compressionModeRtkDesc",+ icon: "filter_list",+ },+ {+ value: "stacked",+ labelKey: "compressionModeStacked",+ descKey: "compressionModeStackedDesc",+ icon: "hub",+ },];const ROLE_OPTIONS: { value: "user" | "assistant" | "system"; labelKey: string }[] = [@@ -93,38 +125,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 +140,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 +171,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 +181,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>) => {@@ -272,7 +285,7 @@ export default function CompressionSettingsTab() {{config.enabled && (<div className="space-y-3"><h4 className="text-sm font-medium text-text-main">{t("compressionMode")}</h4>- <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-5 gap-2">+ <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-7 gap-2">{MODES.map((m) => (<buttonkey={m.value}@@ -326,6 +339,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 +384,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 +483,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.intensities ?? [rule.minIntensity]).join("/")}`}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 +552,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/(dashboard)/dashboard/settings/page.tsx b/src/app/(dashboard)/dashboard/settings/page.tsxindex 4077e8a04e..a2c6af481c 100644--- a/src/app/(dashboard)/dashboard/settings/page.tsx+++ b/src/app/(dashboard)/dashboard/settings/page.tsx@@ -1,6 +1,7 @@"use client";import { useState } from "react";+import Link from "next/link";import { useSearchParams } from "next/navigation";import { cn } from "@/shared/utils/cn";import { APP_CONFIG } from "@/shared/constants/appConfig";@@ -9,7 +10,6 @@ import SystemStorageTab from "./components/SystemStorageTab";import SecurityTab from "./components/SecurityTab";import RoutingTab from "./components/RoutingTab";import ComboDefaultsTab from "./components/ComboDefaultsTab";-import ProxyTab from "./components/ProxyTab";import AppearanceTab from "./components/AppearanceTab";import ThinkingBudgetTab from "./components/ThinkingBudgetTab";import SystemPromptTab from "./components/SystemPromptTab";@@ -21,9 +21,7 @@ import ModelsDevSyncTab from "./components/ModelsDevSyncTab";import ResilienceTab from "./components/ResilienceTab";import CliproxyapiSettingsTab from "./components/CliproxyapiSettingsTab";import PayloadRulesTab from "./components/PayloadRulesTab";-import CompressionSettingsTab from "./components/CompressionSettingsTab";import VisionBridgeSettingsTab from "./components/VisionBridgeSettingsTab";-import MitmProxyTab from "./components/MitmProxyTab";import ModelRoutingSection from "@/shared/components/ModelRoutingSection";const tabs = [@@ -33,7 +31,6 @@ const tabs = [{ id: "security", labelKey: "security", icon: "shield" },{ id: "routing", labelKey: "routing", icon: "route" },{ id: "resilience", labelKey: "resilience", icon: "electrical_services" },- { id: "mitm", labelKey: "mitmProxy", icon: "lan" },{ id: "advanced", labelKey: "advanced", icon: "tune" },];@@ -97,7 +94,25 @@ export default function SettingsPage() {{activeTab === "ai" && (<div className="flex flex-col gap-6"><ThinkingBudgetTab />- <CompressionSettingsTab />+ <Link+ href="/dashboard/context/caveman"+ className="flex items-center justify-between rounded-lg border border-border bg-surface p-4 transition-colors hover:bg-sidebar/50"+ >+ <span className="flex min-w-0 items-center gap-3">+ <span className="material-symbols-outlined text-[20px] text-primary">+ compress+ </span>+ <span className="min-w-0">+ <span className="block text-sm font-medium text-text-main">+ {t("compressionTitle")}+ </span>+ <span className="block text-xs text-text-muted">{t("compressionDesc")}</span>+ </span>+ </span>+ <span className="material-symbols-outlined text-[18px] text-text-muted">+ chevron_right+ </span>+ </Link><VisionBridgeSettingsTab /><SystemPromptTab /><CacheSettingsTab />@@ -120,12 +135,9 @@ export default function SettingsPage() {{activeTab === "resilience" && <ResilienceTab />}- {activeTab === "mitm" && <MitmProxyTab />}-{activeTab === "advanced" && (<div className="flex flex-col gap-6"><PayloadRulesTab />- <ProxyTab /><CliproxyapiSettingsTab /></div>)}diff --git a/src/app/(dashboard)/dashboard/system/proxy/page.tsx b/src/app/(dashboard)/dashboard/system/proxy/page.tsxnew file mode 100644index 0000000000..9ddf0c390c--- /dev/null+++ b/src/app/(dashboard)/dashboard/system/proxy/page.tsx@@ -0,0 +1,79 @@+"use client";++import { useState } from "react";+import { useTranslations } from "next-intl";+import { cn } from "@/shared/utils/cn";+import ProxyTab from "@/app/(dashboard)/dashboard/settings/components/ProxyTab";+import MitmProxyTab from "@/app/(dashboard)/dashboard/settings/components/MitmProxyTab";+import OneproxyTab from "@/app/(dashboard)/dashboard/settings/components/OneproxyTab";++const subTabs = [+ { id: "http", labelKey: "httpProxy", icon: "dns" },+ { id: "mitm", labelKey: "mitmProxy", icon: "lan" },+ { id: "oneproxy", labelKey: "1proxy", icon: "public" },+];++export default function ProxyPage() {+ const t = useTranslations("settings");+ const [activeSubTab, setActiveSubTab] = useState("http");++ return (+ <div className="max-w-6xl mx-auto min-w-0">+ <div className="flex flex-col gap-6">+ <div className="w-full overflow-x-auto pb-1">+ <div+ role="tablist"+ aria-label={t("proxySubTabsAria")}+ className="inline-flex items-center p-1 rounded-lg bg-black/5 dark:bg-white/5 min-w-max"+ >+ {subTabs.map((subTab) => (+ <button+ key={subTab.id}+ role="tab"+ aria-selected={activeSubTab === subTab.id}+ tabIndex={activeSubTab === subTab.id ? 0 : -1}+ onClick={() => setActiveSubTab(subTab.id)}+ className={cn(+ "flex items-center gap-2 px-4 py-2 rounded-md font-medium transition-all text-sm",+ activeSubTab === subTab.id+ ? "bg-white dark:bg-white/10 text-text-main shadow-sm"+ : "text-text-muted hover:text-text-main"+ )}+ >+ <span className="material-symbols-outlined text-[18px]" aria-hidden="true">+ {subTab.icon}+ </span>+ <span className="whitespace-nowrap">+ {subTab.id === "http" ? t("proxy") : t(subTab.labelKey)}+ </span>+ </button>+ ))}+ </div>+ </div>++ <div+ role="tabpanel"+ aria-label={t(subTabs.find((t) => t.id === activeSubTab)?.labelKey || "proxy")}+ >+ {activeSubTab === "http" && (+ <div className="flex flex-col gap-6">+ <ProxyTab />+ </div>+ )}++ {activeSubTab === "mitm" && (+ <div className="flex flex-col gap-6">+ <MitmProxyTab />+ </div>+ )}++ {activeSubTab === "oneproxy" && (+ <div className="flex flex-col gap-6">+ <OneproxyTab />+ </div>+ )}+ </div>+ </div>+ </div>+ );+}diff --git a/src/app/api/compression/language-packs/route.ts b/src/app/api/compression/language-packs/route.tsnew file mode 100644index 0000000000..8d1fb8c8b4--- /dev/null+++ b/src/app/api/compression/language-packs/route.ts@@ -0,0 +1,16 @@+import { NextResponse } from "next/server";+import { requireManagementAuth } from "@/lib/api/requireManagementAuth";+import {+ listCavemanRulePacks,+ listSupportedCompressionLanguages,+} from "@omniroute/open-sse/services/compression";++export async function GET(req: Request) {+ const authError = await requireManagementAuth(req);+ if (authError) return authError;++ return NextResponse.json({+ languages: listSupportedCompressionLanguages(),+ packs: listCavemanRulePacks(),+ });+}diff --git a/src/app/api/compression/preview/route.ts b/src/app/api/compression/preview/route.tsindex 5b966ec3f2..f368c777bf 100644--- a/src/app/api/compression/preview/route.ts+++ b/src/app/api/compression/preview/route.ts@@ -1,10 +1,17 @@import { NextResponse } from "next/server";import { z } from "zod";-import { enforceApiKeyPolicy } from "@/shared/utils/apiKeyPolicy";+import { requireManagementAuth } from "@/lib/api/requireManagementAuth";+import { compressionPreviewConfigSchema } from "@/shared/validation/compressionConfigSchemas";import { applyCompression } from "@omniroute/open-sse/services/compression/strategySelector";-import type { CompressionMode } from "@omniroute/open-sse/services/compression/types";+import type {+ CompressionConfig,+ CompressionMode,+} from "@omniroute/open-sse/services/compression/types";+import { buildCompressionPreviewDiff } from "@omniroute/open-sse/services/compression/diffHelper";-const PreviewRequestSchema = z.object({+export const PreviewCompressionConfigSchema = compressionPreviewConfigSchema;++export const PreviewRequestSchema = z.object({messages: z.array(z.object({@@ -13,7 +20,8 @@ const PreviewRequestSchema = z.object({})).min(1),- mode: z.enum(["off", "lite", "standard", "aggressive", "ultra"]),+ mode: z.enum(["off", "lite", "standard", "aggressive", "ultra", "rtk", "stacked"]),+ config: PreviewCompressionConfigSchema.optional(),});function countTokens(text: string): number {@@ -30,8 +38,8 @@ function messagesToText(messages: Array<{ role: string; content: unknown }>): st}export async function POST(req: Request) {- const policy = await enforceApiKeyPolicy(req, "settings");- if (policy.rejection) return policy.rejection;+ const authError = await requireManagementAuth(req);+ if (authError) return authError;let body: unknown;try {@@ -48,14 +56,16 @@ export async function POST(req: Request) {);}- const { messages, mode } = parsed.data;+ const { messages, mode, config } = parsed.data;const originalText = messagesToText(messages);const originalTokens = countTokens(originalText);try {const start = Date.now();const requestBody = { messages };- const result = await applyCompression(requestBody as Record<string, unknown>, mode);+ const result = await applyCompression(requestBody as Record<string, unknown>, mode, {+ config: config as CompressionConfig | undefined,+ });const durationMs = Date.now() - start;const compressedMessages = (result.body.messages ?? messages) as Array<{@@ -67,6 +77,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 +88,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..b1946c6adb--- /dev/null+++ b/src/app/api/compression/rules/route.ts@@ -0,0 +1,12 @@+import { NextResponse } from "next/server";+import { requireManagementAuth } from "@/lib/api/requireManagementAuth";+import { getCavemanRuleMetadata } from "@omniroute/open-sse/services/compression/cavemanRules";++export async function GET(req: Request) {+ const authError = await requireManagementAuth(req);+ if (authError) return authError;++ return NextResponse.json({+ rules: getCavemanRuleMetadata(),+ });+}diff --git a/src/app/api/context/analytics/route.ts b/src/app/api/context/analytics/route.tsnew file mode 100644index 0000000000..5415ae4948--- /dev/null+++ b/src/app/api/context/analytics/route.ts@@ -0,0 +1 @@+export { GET } from "@/app/api/analytics/compression/route";diff --git a/src/app/api/context/caveman/config/route.ts b/src/app/api/context/caveman/config/route.tsnew file mode 100644index 0000000000..44b602160f--- /dev/null+++ b/src/app/api/context/caveman/config/route.ts@@ -0,0 +1 @@+export { GET, PUT } from "@/app/api/settings/compression/route";diff --git a/src/app/api/context/combos/[id]/assignments/route.ts b/src/app/api/context/combos/[id]/assignments/route.tsnew file mode 100644index 0000000000..d75fe943d2--- /dev/null+++ b/src/app/api/context/combos/[id]/assignments/route.ts@@ -0,0 +1,47 @@+import { NextResponse } from "next/server";+import { z } from "zod";+import {+ getAssignmentsForCompressionCombo,+ getCompressionCombo,+ updateAssignments,+} from "@/lib/db/compressionCombos";+import { requireManagementAuth } from "@/lib/api/requireManagementAuth";+import { isValidationFailure, validateBody } from "@/shared/validation/helpers";++export const assignmentsUpdateSchema = z+ .object({+ routingComboIds: z.array(z.string().trim().min(1)),+ })+ .strict();++export async function GET(request: Request, { params }) {+ const authError = await requireManagementAuth(request);+ if (authError) return authError;+ const { id } = await params;+ if (!getCompressionCombo(id)) {+ return NextResponse.json({ error: "Compression combo not found" }, { status: 404 });+ }+ return NextResponse.json({ assignments: getAssignmentsForCompressionCombo(id) });+}++export async function PUT(request: Request, { params }) {+ const authError = await requireManagementAuth(request);+ if (authError) return authError;+ const { id } = await params;++ let rawBody: unknown;+ try {+ rawBody = await request.json();+ } catch {+ return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });+ }++ const validation = validateBody(assignmentsUpdateSchema, rawBody);+ if (isValidationFailure(validation)) {+ return NextResponse.json({ error: validation.error }, { status: 400 });+ }++ const updated = updateAssignments(id, validation.data.routingComboIds);+ if (!updated) return NextResponse.json({ error: "Compression combo not found" }, { status: 404 });+ return NextResponse.json({ assignments: getAssignmentsForCompressionCombo(id) });+}diff --git a/src/app/api/context/combos/[id]/route.ts b/src/app/api/context/combos/[id]/route.tsnew file mode 100644index 0000000000..83285c8229--- /dev/null+++ b/src/app/api/context/combos/[id]/route.ts@@ -0,0 +1,79 @@+import { NextResponse } from "next/server";+import { z } from "zod";+import {+ deleteCompressionCombo,+ getCompressionCombo,+ setDefaultCompressionCombo,+ updateCompressionCombo,+} from "@/lib/db/compressionCombos";+import { requireManagementAuth } from "@/lib/api/requireManagementAuth";+import { isValidationFailure, validateBody } from "@/shared/validation/helpers";+import {+ cavemanIntensitySchema,+ stackedPipelineStepSchema,+} from "@/shared/validation/compressionConfigSchemas";++export const pipelineStepSchema = stackedPipelineStepSchema;++export const compressionComboUpdateSchema = z+ .object({+ name: z.string().trim().min(1).max(120).optional(),+ description: z.string().max(1000).optional(),+ pipeline: z.array(pipelineStepSchema).min(1).optional(),+ languagePacks: z.array(z.string().trim().min(1)).optional(),+ outputMode: z.boolean().optional(),+ outputModeIntensity: cavemanIntensitySchema.optional(),+ isDefault: z.boolean().optional(),+ })+ .strict();++export async function GET(request: Request, { params }) {+ const authError = await requireManagementAuth(request);+ if (authError) return authError;+ const { id } = await params;+ const combo = getCompressionCombo(id);+ if (!combo) return NextResponse.json({ error: "Compression combo not found" }, { status: 404 });+ return NextResponse.json(combo);+}++export async function PUT(request: Request, { params }) {+ const authError = await requireManagementAuth(request);+ if (authError) return authError;+ const { id } = await params;++ let rawBody: unknown;+ try {+ rawBody = await request.json();+ } catch {+ return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });+ }++ const validation = validateBody(compressionComboUpdateSchema, rawBody);+ if (isValidationFailure(validation)) {+ return NextResponse.json({ error: validation.error }, { status: 400 });+ }++ if (validation.data.isDefault === true) {+ const changed = setDefaultCompressionCombo(id);+ if (!changed)+ return NextResponse.json({ error: "Compression combo not found" }, { status: 404 });+ }++ const combo = updateCompressionCombo(id, validation.data);+ if (!combo) return NextResponse.json({ error: "Compression combo not found" }, { status: 404 });+ return NextResponse.json(combo);+}++export async function DELETE(request: Request, { params }) {+ const authError = await requireManagementAuth(request);+ if (authError) return authError;+ const { id } = await params;+ const deleted = deleteCompressionCombo(id);+ if (!deleted) {+ return NextResponse.json(+ { error: "Compression combo not found or cannot delete default combo" },+ { status: 404 }+ );+ }+ return NextResponse.json({ ok: true });+}diff --git a/src/app/api/context/combos/route.ts b/src/app/api/context/combos/route.tsnew file mode 100644index 0000000000..2590af0940--- /dev/null+++ b/src/app/api/context/combos/route.ts@@ -0,0 +1,50 @@+import { NextResponse } from "next/server";+import { z } from "zod";+import { createCompressionCombo, listCompressionCombos } from "@/lib/db/compressionCombos";+import { requireManagementAuth } from "@/lib/api/requireManagementAuth";+import { isValidationFailure, validateBody } from "@/shared/validation/helpers";+import {+ cavemanIntensitySchema,+ stackedPipelineStepSchema,+} from "@/shared/validation/compressionConfigSchemas";++export const pipelineStepSchema = stackedPipelineStepSchema;++export const compressionComboCreateSchema = z+ .object({+ id: z.string().trim().min(1).optional(),+ name: z.string().trim().min(1).max(120),+ description: z.string().max(1000).optional(),+ pipeline: z.array(pipelineStepSchema).min(1).optional(),+ languagePacks: z.array(z.string().trim().min(1)).optional(),+ outputMode: z.boolean().optional(),+ outputModeIntensity: cavemanIntensitySchema.optional(),+ isDefault: z.boolean().optional(),+ })+ .strict();++export async function GET(request: Request) {+ const authError = await requireManagementAuth(request);+ if (authError) return authError;+ return NextResponse.json({ combos: listCompressionCombos() });+}++export async function POST(request: Request) {+ const authError = await requireManagementAuth(request);+ if (authError) return authError;++ let rawBody: unknown;+ try {+ rawBody = await request.json();+ } catch {+ return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });+ }++ const validation = validateBody(compressionComboCreateSchema, rawBody);+ if (isValidationFailure(validation)) {+ return NextResponse.json({ error: validation.error }, { status: 400 });+ }++ const combo = createCompressionCombo(validation.data);+ return NextResponse.json(combo, { status: 201 });+}diff --git a/src/app/api/context/rtk/config/route.ts b/src/app/api/context/rtk/config/route.tsnew file mode 100644index 0000000000..2d97058bb7--- /dev/null+++ b/src/app/api/context/rtk/config/route.ts@@ -0,0 +1,34 @@+import { NextResponse } from "next/server";+import { getCompressionSettings, updateCompressionSettings } from "@/lib/db/compression";+import { requireManagementAuth } from "@/lib/api/requireManagementAuth";+import { isValidationFailure, validateBody } from "@/shared/validation/helpers";+import { rtkConfigSchema } from "@/shared/validation/compressionConfigSchemas";++export { rtkConfigSchema };++export async function GET(request: Request) {+ const authError = await requireManagementAuth(request);+ if (authError) return authError;+ const settings = await getCompressionSettings();+ return NextResponse.json(settings.rtkConfig);+}++export async function PUT(request: Request) {+ const authError = await requireManagementAuth(request);+ if (authError) return authError;+ let rawBody: unknown;+ try {+ rawBody = await request.json();+ } catch {+ return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });+ }+ const validation = validateBody(rtkConfigSchema, rawBody);+ if (isValidationFailure(validation)) {+ return NextResponse.json({ error: validation.error }, { status: 400 });+ }+ const current = await getCompressionSettings();+ const settings = await updateCompressionSettings({+ rtkConfig: { ...current.rtkConfig, ...validation.data },+ });+ return NextResponse.json(settings.rtkConfig);+}diff --git a/src/app/api/context/rtk/filters/route.ts b/src/app/api/context/rtk/filters/route.tsnew file mode 100644index 0000000000..0f97bcc8eb--- /dev/null+++ b/src/app/api/context/rtk/filters/route.ts@@ -0,0 +1,15 @@+import { NextResponse } from "next/server";+import {+ getRtkFilterCatalog,+ getRtkFilterLoadDiagnostics,+} from "@omniroute/open-sse/services/compression/engines/rtk/filterLoader";+import { requireManagementAuth } from "@/lib/api/requireManagementAuth";++export async function GET(request: Request) {+ const authError = await requireManagementAuth(request);+ if (authError) return authError;+ return NextResponse.json({+ filters: getRtkFilterCatalog(),+ diagnostics: getRtkFilterLoadDiagnostics(),+ });+}diff --git a/src/app/api/context/rtk/raw-output/[id]/route.ts b/src/app/api/context/rtk/raw-output/[id]/route.tsnew file mode 100644index 0000000000..85084d9226--- /dev/null+++ b/src/app/api/context/rtk/raw-output/[id]/route.ts@@ -0,0 +1,26 @@+import { NextResponse } from "next/server";+import { readRtkRawOutput } from "@omniroute/open-sse/services/compression/engines/rtk";+import { requireManagementAuth } from "@/lib/api/requireManagementAuth";++export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) {+ const authError = await requireManagementAuth(request);+ if (authError) return authError;++ const { id } = await params;+ if (!/^[a-f0-9]{24}$/.test(id)) {+ return NextResponse.json({ error: "Invalid raw output id" }, { status: 400 });+ }++ const content = readRtkRawOutput(id);+ if (content === null) {+ return NextResponse.json({ error: "Raw output not found" }, { status: 404 });+ }++ return new NextResponse(content, {+ status: 200,+ headers: {+ "content-type": "text/plain; charset=utf-8",+ "cache-control": "no-store",+ },+ });+}diff --git a/src/app/api/context/rtk/test/route.ts b/src/app/api/context/rtk/test/route.tsnew file mode 100644index 0000000000..4307198e2c--- /dev/null+++ b/src/app/api/context/rtk/test/route.ts@@ -0,0 +1,43 @@+import { NextResponse } from "next/server";+import { z } from "zod";+import {+ detectCommandType,+ processRtkText,+} from "@omniroute/open-sse/services/compression/engines/rtk";+import { requireManagementAuth } from "@/lib/api/requireManagementAuth";+import { isValidationFailure, validateBody } from "@/shared/validation/helpers";+import { rtkConfigSchema } from "@/shared/validation/compressionConfigSchemas";++export const rtkTestSchema = z+ .object({+ text: z.string().min(1),+ command: z.string().optional(),+ config: rtkConfigSchema.optional(),+ })+ .strict();++export async function POST(request: Request) {+ const authError = await requireManagementAuth(request);+ if (authError) return authError;++ let rawBody: unknown;+ try {+ rawBody = await request.json();+ } catch {+ return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });+ }++ const validation = validateBody(rtkTestSchema, rawBody);+ if (isValidationFailure(validation)) {+ return NextResponse.json({ error: validation.error }, { status: 400 });+ }++ const detection = detectCommandType(validation.data.text, validation.data.command);+ return NextResponse.json({+ detection,+ ...processRtkText(validation.data.text, {+ command: validation.data.command,+ config: validation.data.config,+ }),+ });+}diff --git a/src/app/api/models/test/route.ts b/src/app/api/models/test/route.tsindex c113bc979e..65654b4861 100644--- a/src/app/api/models/test/route.ts+++ b/src/app/api/models/test/route.ts@@ -2,8 +2,10 @@ import { randomUUID } from "node:crypto";import { NextResponse } from "next/server";import { POST as postChatCompletion } from "@/app/api/v1/chat/completions/route";import { handleValidatedEmbeddingRequestBody } from "@/app/api/v1/embeddings/route";+import { POST as postRerank } from "@/app/api/v1/rerank/route";import { buildComboTestRequestBody, extractComboTestResponseText } from "@/lib/combos/testHealth";import { requireManagementAuth } from "@/lib/api/requireManagementAuth";+import { getCustomModels } from "@/lib/localDb";import { z } from "zod";const testModelSchema = z.object({@@ -73,6 +75,45 @@ function buildInternalChatRequest(testBody: Record<string, unknown>, signal: Abo});}+function buildInternalRerankRequest(testBody: Record<string, unknown>, signal: AbortSignal) {+ return new Request(`${INTERNAL_ORIGIN}/v1/rerank`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ "X-Internal-Test": "combo-health-check",+ "X-OmniRoute-No-Cache": "true",+ "X-Request-Id": `model-test-${randomUUID()}`,+ },+ body: JSON.stringify(testBody),+ signal,+ });+}++function stripFirstSegment(modelId: string): string | null {+ const slashIdx = modelId.indexOf("/");+ return slashIdx > 0 ? modelId.slice(slashIdx + 1) : null;+}++async function findCustomModelMetadata(providerId: string, modelId: string) {+ try {+ const customModels = await getCustomModels(providerId);+ if (!Array.isArray(customModels)) return null;++ const candidates = new Set([modelId]);+ const stripped = stripFirstSegment(modelId);+ if (stripped) candidates.add(stripped);+ if (modelId.startsWith(`${providerId}/`)) candidates.add(modelId.slice(providerId.length + 1));++ return (+ customModels.find(+ (model: any) => typeof model?.id === "string" && candidates.has(model.id)+ ) || null+ );+ } catch {+ return null;+ }+}+export async function POST(request: Request) {const authError = await requireManagementAuth(request);if (authError) return authError;@@ -108,19 +149,47 @@ export async function POST(request: Request) {}const startTime = Date.now();+ const customModel = await findCustomModelMetadata(providerId, fullModelStr);+ const supportedEndpoints = Array.isArray(customModel?.supportedEndpoints)+ ? customModel.supportedEndpoints+ : [];+ const apiFormat = typeof customModel?.apiFormat === "string" ? customModel.apiFormat : "";+ const lowerModel = fullModelStr.toLowerCase();+ const isRerank =+ apiFormat === "rerank" ||+ supportedEndpoints.includes("rerank") ||+ lowerModel.includes("rerank");const isEmbedding =- fullModelStr.toLowerCase().includes("embedding") ||- fullModelStr.toLowerCase().includes("bge-") ||- fullModelStr.toLowerCase().includes("text-embed");-- const testBody = buildComboTestRequestBody(fullModelStr, isEmbedding);+ !isRerank &&+ (apiFormat === "embeddings" ||+ supportedEndpoints.includes("embeddings") ||+ lowerModel.includes("embedding") ||+ lowerModel.includes("bge-") ||+ lowerModel.includes("text-embed") ||+ lowerModel.includes("jina-clip") ||+ lowerModel.includes("colbert"));++ const testBody = isRerank+ ? {+ model: fullModelStr,+ query: "What is OmniRoute?",+ documents: [+ "OmniRoute routes AI requests across configured providers.",+ "This document is unrelated to the test query.",+ ],+ top_n: 1,+ return_documents: false,+ }+ : buildComboTestRequestBody(fullModelStr, isEmbedding);const res = await runWithTimeout((signal) =>isEmbedding? handleValidatedEmbeddingRequestBody(testBody as Record<string, unknown> & { model: string })- : postChatCompletion(buildInternalChatRequest(testBody, signal))+ : isRerank+ ? postRerank(buildInternalRerankRequest(testBody, signal))+ : postChatCompletion(buildInternalChatRequest(testBody, signal)));const latencyMs = Date.now() - startTime;@@ -134,6 +203,13 @@ export async function POST(request: Request) {}const responseText = extractComboTestResponseText(responseBody);+ if (isRerank) {+ return NextResponse.json({+ status: "ok",+ latencyMs,+ responseText: "[Rerank completed successfully]",+ });+ }if (!responseText && !isEmbedding) {return NextResponse.json({diff --git a/src/app/api/monitoring/health/route.ts b/src/app/api/monitoring/health/route.tsindex 292b86581f..fba99e7bc1 100644--- a/src/app/api/monitoring/health/route.ts+++ b/src/app/api/monitoring/health/route.ts@@ -3,6 +3,7 @@ import { getProviderConnections, getSettings } from "@/lib/localDb";import { buildHealthPayload } from "@/lib/monitoring/observability";import { APP_CONFIG } from "@/shared/constants/config";import { AI_PROVIDERS } from "@/shared/constants/providers";+import { isAuthenticated } from "@/shared/utils/apiAuth";/*** GET /api/monitoring/health — System health overview@@ -63,7 +64,11 @@ export async function GET() {* Resets all provider circuit breakers to CLOSED state,* clearing failure counts and persisted state.*/-export async function DELETE() {+export async function DELETE(request: Request) {+ if (!(await isAuthenticated(request))) {+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ }+try {const { resetAllCircuitBreakers, getAllCircuitBreakerStatuses } =await import("@/shared/utils/circuitBreaker");diff --git a/src/app/api/oauth/[provider]/[action]/route.ts b/src/app/api/oauth/[provider]/[action]/route.tsindex 0b31439e5c..086ef7da83 100755--- a/src/app/api/oauth/[provider]/[action]/route.ts+++ b/src/app/api/oauth/[provider]/[action]/route.ts@@ -24,6 +24,7 @@ import {oauthPollSchema,} from "@/shared/validation/schemas";import { isValidationFailure, validateBody } from "@/shared/validation/helpers";+import { isAuthRequired, isAuthenticated } from "@/shared/utils/apiAuth";// Use globalThis to persist callback server state across Next.js HMR reloadsif (!globalThis.__codexCallbackState) {@@ -42,6 +43,12 @@ function safeEqual(a: string | null | undefined, b: string | null | undefined):return timingSafeEqual(ba, bb);}+async function requireOAuthRouteAuth(request: Request) {+ if (!(await isAuthRequired(request))) return null;+ if (await isAuthenticated(request)) return null;+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+}+/*** Dynamic OAuth API Route* Handles: authorize, exchange, device-code, poll, start-callback-server, poll-callback@@ -53,6 +60,9 @@ export async function GET(request: Request,{ params }: { params: Promise<{ provider: string; action: string }> }) {+ const authResponse = await requireOAuthRouteAuth(request);+ if (authResponse) return authResponse;+try {const { provider, action } = await params;const { searchParams } = new URL(request.url);@@ -212,6 +222,9 @@ export async function POST(request: Request,{ params }: { params: Promise<{ provider: string; action: string }> }) {+ const authResponse = await requireOAuthRouteAuth(request);+ if (authResponse) return authResponse;+try {const { provider, action } = await params;let rawBody: any = {};diff --git a/src/app/api/oauth/cursor/import/route.ts b/src/app/api/oauth/cursor/import/route.tsindex a0da0c4d4e..f2ba171d62 100755--- a/src/app/api/oauth/cursor/import/route.ts+++ b/src/app/api/oauth/cursor/import/route.ts@@ -5,8 +5,15 @@ import { getConsistentMachineId } from "@/shared/utils/machineId";import { syncToCloud } from "@/lib/cloudSync";import { cursorImportSchema } from "@/shared/validation/schemas";import { isValidationFailure, validateBody } from "@/shared/validation/helpers";+import { isAuthRequired, isAuthenticated } from "@/shared/utils/apiAuth";import { runWithProxyContext } from "@omniroute/open-sse/utils/proxyFetch.ts";+async function requireOAuthImportAuth(request: Request) {+ if (!(await isAuthRequired(request))) return null;+ if (await isAuthenticated(request)) return null;+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+}+/*** POST /api/oauth/cursor/import* Import and validate access token from Cursor IDE's local SQLite database@@ -15,7 +22,10 @@ import { runWithProxyContext } from "@omniroute/open-sse/utils/proxyFetch.ts";* - accessToken: string - Access token from cursorAuth/accessToken* - machineId: string - Machine ID from storage.serviceMachineId*/-export async function POST(request: any) {+export async function POST(request: Request) {+ const authResponse = await requireOAuthImportAuth(request);+ if (authResponse) return authResponse;+let rawBody;try {rawBody = await request.json();@@ -89,7 +99,10 @@ export async function POST(request: any) {* GET /api/oauth/cursor/import* Get instructions for importing Cursor token*/-export async function GET() {+export async function GET(request: Request) {+ const authResponse = await requireOAuthImportAuth(request);+ if (authResponse) return authResponse;+const cursorService = new CursorService();const instructions = cursorService.getTokenStorageInstructions();diff --git a/src/app/api/oauth/kiro/import/route.ts b/src/app/api/oauth/kiro/import/route.tsindex f329b871a9..44803229e5 100755--- a/src/app/api/oauth/kiro/import/route.ts+++ b/src/app/api/oauth/kiro/import/route.ts@@ -5,13 +5,23 @@ import { getConsistentMachineId } from "@/shared/utils/machineId";import { syncToCloud } from "@/lib/cloudSync";import { kiroImportSchema } from "@/shared/validation/schemas";import { isValidationFailure, validateBody } from "@/shared/validation/helpers";+import { isAuthRequired, isAuthenticated } from "@/shared/utils/apiAuth";import { runWithProxyContext } from "@omniroute/open-sse/utils/proxyFetch.ts";+async function requireOAuthImportAuth(request: Request) {+ if (!(await isAuthRequired(request))) return null;+ if (await isAuthenticated(request)) return null;+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+}+/*** POST /api/oauth/kiro/import* Import and validate refresh token from Kiro IDE*/-export async function POST(request: any) {+export async function POST(request: Request) {+ const authResponse = await requireOAuthImportAuth(request);+ if (authResponse) return authResponse;+let rawBody;try {rawBody = await request.json();diff --git a/src/app/api/oauth/kiro/social-authorize/route.ts b/src/app/api/oauth/kiro/social-authorize/route.tsindex 53408f2ed8..61df8219af 100755--- a/src/app/api/oauth/kiro/social-authorize/route.ts+++ b/src/app/api/oauth/kiro/social-authorize/route.ts@@ -1,6 +1,7 @@import { NextResponse } from "next/server";import { generatePKCE } from "@/lib/oauth/utils/pkce";import { KiroService } from "@/lib/oauth/services/kiro";+import { isAuthRequired, isAuthenticated } from "@/shared/utils/apiAuth";/*** GET /api/oauth/kiro/social-authorize@@ -8,6 +9,10 @@ import { KiroService } from "@/lib/oauth/services/kiro";* Uses kiro:// custom protocol as required by AWS Cognito*/export async function GET(request) {+ if ((await isAuthRequired(request)) && !(await isAuthenticated(request))) {+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ }+try {const { searchParams } = new URL(request.url);const provider = searchParams.get("provider"); // "google" or "github"diff --git a/src/app/api/oauth/kiro/social-exchange/route.ts b/src/app/api/oauth/kiro/social-exchange/route.tsindex dade4a67d6..950c59e8db 100755--- a/src/app/api/oauth/kiro/social-exchange/route.ts+++ b/src/app/api/oauth/kiro/social-exchange/route.ts@@ -5,6 +5,7 @@ import { getConsistentMachineId } from "@/shared/utils/machineId";import { syncToCloud } from "@/lib/cloudSync";import { kiroSocialExchangeSchema } from "@/shared/validation/schemas";import { isValidationFailure, validateBody } from "@/shared/validation/helpers";+import { isAuthRequired, isAuthenticated } from "@/shared/utils/apiAuth";/*** POST /api/oauth/kiro/social-exchange@@ -12,6 +13,10 @@ import { isValidationFailure, validateBody } from "@/shared/validation/helpers";* Callback URL will be in format: kiro://kiro.kiroAgent/authenticate-success?code=XXX&state=YYY*/export async function POST(request: Request) {+ if ((await isAuthRequired(request)) && !(await isAuthenticated(request))) {+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ }+let rawBody;try {rawBody = await request.json();diff --git a/src/app/api/providers/[id]/models/route.ts b/src/app/api/providers/[id]/models/route.tsindex a980e93695..1e6e7e5962 100755--- a/src/app/api/providers/[id]/models/route.ts+++ b/src/app/api/providers/[id]/models/route.ts@@ -65,7 +65,12 @@ import {} from "@/lib/providerModels/modelDiscovery";type JsonRecord = Record<string, unknown>;-type LocalCatalogModel = { id: string; name?: string };+type LocalCatalogModel = {+ id: string;+ name?: string;+ apiFormat?: string;+ supportedEndpoints?: string[];+};const antigravityDiscoveryInflight = new Map<string,@@ -409,33 +414,41 @@ const STATIC_MODEL_PROVIDERS: Record<string, () => Array<{ id: string; name: str* @param provider - Provider ID* @returns Array of models or undefined if provider doesn't use static models*/-export function getStaticModelsForProvider(- provider: string-): Array<{ id: string; name: string }> | undefined {+export function getStaticModelsForProvider(provider: string): LocalCatalogModel[] | undefined {const staticModelsFn = STATIC_MODEL_PROVIDERS[provider];if (staticModelsFn) {return staticModelsFn();}- const specialtyModels: Array<{ id: string; name: string }> = [];- const appendModels = (models: Array<{ id: string; name?: string }>) => {+ const specialtyModels: LocalCatalogModel[] = [];+ const appendModels = (+ models: Array<{ id: string; name?: string }>,+ metadata?: Pick<LocalCatalogModel, "apiFormat" | "supportedEndpoints">+ ) => {for (const model of models) {if (specialtyModels.some((existing) => existing.id === model.id)) continue;specialtyModels.push({id: model.id,name: model.name || model.id,+ ...metadata,});}};const embeddingProvider = getEmbeddingProvider(provider);if (embeddingProvider) {- appendModels(embeddingProvider.models);+ appendModels(embeddingProvider.models, {+ apiFormat: "embeddings",+ supportedEndpoints: ["embeddings"],+ });}const rerankProvider = getRerankProvider(provider);if (rerankProvider) {- appendModels(rerankProvider.models);+ appendModels(rerankProvider.models, {+ apiFormat: "rerank",+ supportedEndpoints: ["rerank"],+ });}const imageProvider = getImageProvider(provider);@@ -837,6 +850,8 @@ export async function GET(return localCatalog.map((model) => ({id: model.id,name: model.name || model.id,+ ...(model.apiFormat ? { apiFormat: model.apiFormat } : {}),+ ...(model.supportedEndpoints ? { supportedEndpoints: model.supportedEndpoints } : {}),...(registryCatalogModels.length > 0 ? { owned_by: provider } : {}),}));};@@ -1770,6 +1785,8 @@ export async function GET(models: localCatalog.map((m) => ({id: m.id,name: m.name || m.id,+ ...(m.apiFormat ? { apiFormat: m.apiFormat } : {}),+ ...(m.supportedEndpoints ? { supportedEndpoints: m.supportedEndpoints } : {}),...(registryCatalogModels.length > 0 ? { owned_by: provider } : {}),})),source: "local_catalog",diff --git a/src/app/api/settings/compression/route.ts b/src/app/api/settings/compression/route.tsindex 4262eb5019..97f1e3aeef 100644--- a/src/app/api/settings/compression/route.ts+++ b/src/app/api/settings/compression/route.ts@@ -1,70 +1,8 @@import { NextRequest, NextResponse } from "next/server";-import { z } from "zod";import { getCompressionSettings, updateCompressionSettings } from "@/lib/db/compression";import { isAuthenticated } from "@/shared/utils/apiAuth";import { isValidationFailure, validateBody } from "@/shared/validation/helpers";--const compressionModeSchema = z.enum(["off", "lite", "standard", "aggressive", "ultra"]);--const cavemanConfigSchema = z- .object({- enabled: z.boolean().optional(),- compressRoles: z.array(z.enum(["user", "assistant", "system"])).optional(),- skipRules: z.array(z.string()).optional(),- minMessageLength: z.number().int().min(0).optional(),- preservePatterns: z.array(z.string()).optional(),- })- .strict();--const aggressiveConfigSchema = z- .object({- thresholds: z- .object({- fullSummary: z.number().int().min(1).max(100).optional(),- moderate: z.number().int().min(1).max(100).optional(),- light: z.number().int().min(1).max(100).optional(),- verbatim: z.number().int().min(1).max(100).optional(),- })- .optional(),- toolStrategies: z- .object({- fileContent: z.boolean().optional(),- grepSearch: z.boolean().optional(),- shellOutput: z.boolean().optional(),- json: z.boolean().optional(),- errorMessage: z.boolean().optional(),- })- .optional(),- summarizerEnabled: z.boolean().optional(),- maxTokensPerMessage: z.number().int().min(256).max(32768).optional(),- minSavingsThreshold: z.number().min(0).max(1).optional(),- })- .strict();--const ultraConfigSchema = z- .object({- enabled: z.boolean().optional(),- compressionRate: z.number().min(0).max(1).optional(),- minScoreThreshold: z.number().min(0).max(1).optional(),- slmFallbackToAggressive: z.boolean().optional(),- modelPath: z.string().trim().min(1).optional(),- maxTokensPerMessage: z.number().int().min(0).max(32768).optional(),- })- .strict();--const compressionSettingsUpdateSchema = z- .object({- enabled: z.boolean().optional(),- defaultMode: compressionModeSchema.optional(),- autoTriggerTokens: z.number().int().min(0).optional(),- cacheMinutes: z.number().int().min(1).max(60).optional(),- preserveSystemPrompt: z.boolean().optional(),- comboOverrides: z.record(z.string(), compressionModeSchema).optional(),- cavemanConfig: cavemanConfigSchema.optional(),- aggressive: aggressiveConfigSchema.optional(),- ultra: ultraConfigSchema.optional(),- })- .strict();+import { compressionSettingsUpdateSchema } from "@/shared/validation/compressionConfigSchemas";export async function GET(request: NextRequest) {if (!(await isAuthenticated(request))) {diff --git a/src/app/api/settings/compression/rules/route.ts b/src/app/api/settings/compression/rules/route.tsnew file mode 100644index 0000000000..7394c776be--- /dev/null+++ b/src/app/api/settings/compression/rules/route.ts@@ -0,0 +1 @@+export { GET } from "@/app/api/compression/rules/route";diff --git a/src/app/api/usage/analytics/route.ts b/src/app/api/usage/analytics/route.tsindex 60ed43c6a1..e89d9351e2 100644--- a/src/app/api/usage/analytics/route.ts+++ b/src/app/api/usage/analytics/route.ts@@ -30,12 +30,6 @@ function getRangeStartIso(range: string): string | null {return start.toISOString();}-function shortModelName(model: string | null): string {- if (!model) return "-";- const parts = model.split(/[/:-]/);- return parts[parts.length - 1] || model;-}-const WEEKDAY_LABELS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];type PricingByProvider = Record<string, Record<string, Record<string, unknown>>>;@@ -65,28 +59,76 @@ function appendWhereCondition(whereClause: string, condition: string): string {return whereClause ? `${whereClause} AND (${condition})` : `WHERE (${condition})`;}+function findKeyInsensitive(obj: Record<string, any> | undefined | null, key: string): any {+ if (!obj || !key) return undefined;+ return obj[key.toLowerCase()];+}+function resolveModelPricing(pricingByProvider: PricingByProvider,- provider: string,+ providerAliasMap: Record<string, string>,+ providerRaw: string,model: string,normalizeModelName: (model: string) => string): Record<string, unknown> | null {- const providerPricing = pricingByProvider[provider];- if (!providerPricing) return null;-- const normalizedModel = normalizeModelName(model);- const shortModel = shortModelName(model);- return (- providerPricing[model] ||- providerPricing[normalizedModel] ||- providerPricing[shortModel] ||- null- );+ const pLower = (providerRaw || "").toLowerCase();++ let providerPricing = findKeyInsensitive(pricingByProvider, pLower);+ if (!providerPricing) {+ const alias = providerAliasMap[pLower];+ if (alias) {+ providerPricing = findKeyInsensitive(pricingByProvider, alias);+ } else {+ const np = pLower.replace(/-cn$/, "");+ if (np && np !== pLower) {+ providerPricing = findKeyInsensitive(pricingByProvider, np);+ }+ }+ }++ // Hardcoded known fallbacks+ if (!providerPricing) {+ if (pLower === "antigravity") providerPricing = findKeyInsensitive(pricingByProvider, "ag");+ }++ const normalizedModel = normalizeModelName(model).toLowerCase();+ const shortModel = normalizedModel; // normalizeModelName behaves exactly like shortModelName+ const hyphenModel = model.toLowerCase().replace(/\./g, "-");+ const hyphenNormalized = normalizedModel.replace(/\./g, "-");+ const lowerModel = model.toLowerCase();++ const tryFind = (prov: Record<string, unknown> | null | undefined) => {+ if (!prov || typeof prov !== "object") return null;+ return (+ findKeyInsensitive(prov as Record<string, unknown>, lowerModel) ||+ findKeyInsensitive(prov as Record<string, unknown>, normalizedModel) ||+ findKeyInsensitive(prov as Record<string, unknown>, shortModel) ||+ findKeyInsensitive(prov as Record<string, unknown>, hyphenModel) ||+ findKeyInsensitive(prov as Record<string, unknown>, hyphenNormalized) ||+ null+ );+ };++ let pricing = providerPricing ? tryFind(providerPricing) : null;++ if (!pricing) {+ // Global fallback: search all providers for this exact model (helps with aliases)+ for (const prov of Object.values(pricingByProvider)) {+ const found = tryFind(prov as Record<string, unknown>);+ if (found) {+ pricing = found;+ break;+ }+ }+ }++ return pricing as Record<string, unknown> | null;}function computeUsageRowCost(row: Record<string, unknown>,pricingByProvider: PricingByProvider,+ providerAliasMap: Record<string, string>,normalizeModelName: (model: string) => string,computeCostFromPricing: ComputeCostFromPricing): number {@@ -94,7 +136,13 @@ function computeUsageRowCost(const model = toStringValue(row.model);if (!provider || !model) return 0;- const pricing = resolveModelPricing(pricingByProvider, provider, model, normalizeModelName);+ const pricing = resolveModelPricing(+ pricingByProvider,+ providerAliasMap,+ provider,+ model,+ normalizeModelName+ );if (!pricing) return 0;return computeCostFromPricing(pricing, {@@ -163,9 +211,20 @@ export async function GET(request: Request) {// Fetch pricing data for cost calculation (no rows loaded)const { getPricing } = await import("@/lib/db/settings");- const pricingByProvider = (await getPricing()) as PricingByProvider;+ const rawPricingByProvider = (await getPricing()) as PricingByProvider;++ // Pre-process pricing data to lowercase keys for O(1) lookups+ const pricingByProvider: PricingByProvider = {};+ for (const [providerKey, providerVal] of Object.entries(rawPricingByProvider || {})) {+ const lowerProvider = {};+ for (const [modelKey, modelVal] of Object.entries(providerVal || {})) {+ (lowerProvider as any)[modelKey.toLowerCase()] = modelVal;+ }+ pricingByProvider[providerKey.toLowerCase()] = lowerProvider;+ }const { computeCostFromPricing, normalizeModelName } =await import("@/lib/usage/costCalculator");+ const { PROVIDER_ID_TO_ALIAS } = await import("@omniroute/open-sse/config/providerModels");const summaryRow = db.prepare(@@ -210,8 +269,8 @@ export async function GET(request: Request) {`SELECTDATE(timestamp) as date,- provider,- model,+ LOWER(provider) as provider,+ LOWER(model) as model,COALESCE(SUM(tokens_input), 0) as promptTokens,COALESCE(SUM(tokens_output), 0) as completionTokens,COALESCE(SUM(tokens_cache_read), 0) as cacheReadTokens,@@ -219,7 +278,7 @@ export async function GET(request: Request) {COALESCE(SUM(tokens_reasoning), 0) as reasoningTokensFROM usage_history${whereClause}- GROUP BY DATE(timestamp), provider, model+ GROUP BY DATE(timestamp), LOWER(provider), LOWER(model)ORDER BY date ASC`)@@ -263,8 +322,8 @@ export async function GET(request: Request) {.prepare(`SELECT- model,- provider,+ LOWER(model) as model,+ LOWER(provider) as provider,COUNT(*) as requests,COALESCE(SUM(tokens_input), 0) as promptTokens,COALESCE(SUM(tokens_output), 0) as completionTokens,@@ -277,7 +336,7 @@ export async function GET(request: Request) {COALESCE(MAX(timestamp), '') as lastUsedFROM usage_history${whereClause}- GROUP BY model, provider+ GROUP BY LOWER(model), LOWER(provider)ORDER BY requests DESCLIMIT 50`@@ -288,8 +347,8 @@ export async function GET(request: Request) {.prepare(`SELECT- provider,- model,+ LOWER(provider) as provider,+ LOWER(model) as model,COALESCE(SUM(tokens_input), 0) as promptTokens,COALESCE(SUM(tokens_output), 0) as completionTokens,COALESCE(SUM(tokens_cache_read), 0) as cacheReadTokens,@@ -297,7 +356,7 @@ export async function GET(request: Request) {COALESCE(SUM(tokens_reasoning), 0) as reasoningTokensFROM usage_history${whereClause}- GROUP BY provider, model+ GROUP BY LOWER(provider), LOWER(model)`).all(params) as Array<Record<string, unknown>>;@@ -306,7 +365,7 @@ export async function GET(request: Request) {.prepare(`SELECT- provider,+ LOWER(provider) as provider,COUNT(*) as requests,COALESCE(SUM(tokens_input), 0) as promptTokens,COALESCE(SUM(tokens_output), 0) as completionTokens,@@ -315,7 +374,7 @@ export async function GET(request: Request) {COALESCE(SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END), 0) as successfulRequestsFROM usage_history${whereClause}- GROUP BY provider+ GROUP BY LOWER(provider)ORDER BY requests DESC`)@@ -325,17 +384,18 @@ export async function GET(request: Request) {.prepare(`SELECT- connection_id as account,- provider,- model,- COALESCE(SUM(tokens_input), 0) as promptTokens,- COALESCE(SUM(tokens_output), 0) as completionTokens,- COALESCE(SUM(tokens_cache_read), 0) as cacheReadTokens,- COALESCE(SUM(tokens_cache_creation), 0) as cacheCreationTokens,- COALESCE(SUM(tokens_reasoning), 0) as reasoningTokens+ COALESCE(NULLIF(c.display_name, ''), NULLIF(c.email, ''), NULLIF(c.name, ''), usage_history.connection_id, 'unknown') as account,+ LOWER(usage_history.provider) as provider,+ LOWER(usage_history.model) as model,+ COALESCE(SUM(usage_history.tokens_input), 0) as promptTokens,+ COALESCE(SUM(usage_history.tokens_output), 0) as completionTokens,+ COALESCE(SUM(usage_history.tokens_cache_read), 0) as cacheReadTokens,+ COALESCE(SUM(usage_history.tokens_cache_creation), 0) as cacheCreationTokens,+ COALESCE(SUM(usage_history.tokens_reasoning), 0) as reasoningTokensFROM usage_history- ${whereClause}- GROUP BY connection_id, provider, model+ LEFT JOIN provider_connections c ON c.id = usage_history.connection_id+ ${whereClause.replace(/timestamp/g, "usage_history.timestamp").replace(/api_key_/g, "usage_history.api_key_")}+ GROUP BY account, LOWER(usage_history.provider), LOWER(usage_history.model)`).all(params) as Array<Record<string, unknown>>;@@ -344,31 +404,35 @@ export async function GET(request: Request) {.prepare(`SELECT- connection_id as account,- COUNT(*) as requests,- COALESCE(SUM(tokens_input), 0) as promptTokens,- COALESCE(SUM(tokens_output), 0) as completionTokens,- COALESCE(SUM(tokens_input + tokens_output), 0) as totalTokens,- COALESCE(AVG(latency_ms), 0) as avgLatencyMs,- COALESCE(MAX(timestamp), '') as lastUsed+ COALESCE(NULLIF(c.display_name, ''), NULLIF(c.email, ''), NULLIF(c.name, ''), usage_history.connection_id, 'unknown') as account,+ COUNT(usage_history.id) as requests,+ COALESCE(SUM(usage_history.tokens_input), 0) as promptTokens,+ COALESCE(SUM(usage_history.tokens_output), 0) as completionTokens,+ COALESCE(SUM(usage_history.tokens_input + usage_history.tokens_output), 0) as totalTokens,+ COALESCE(AVG(usage_history.latency_ms), 0) as avgLatencyMs,+ COALESCE(MAX(usage_history.timestamp), '') as lastUsedFROM usage_history- ${whereClause}- GROUP BY connection_id+ LEFT JOIN provider_connections c ON c.id = usage_history.connection_id+ ${whereClause.replace(/timestamp/g, "usage_history.timestamp").replace(/api_key_/g, "usage_history.api_key_")}+ GROUP BY accountORDER BY requests DESCLIMIT 50`).all(params) as Array<Record<string, unknown>>;- const apiKeyWhereClause = whereClause;+ const apiKeyWhereClause = appendWhereCondition(+ whereClause,+ "(api_key_id IS NOT NULL AND api_key_id != '') OR (api_key_name IS NOT NULL AND api_key_name != '')"+ );const apiKeyRows = db.prepare(`SELECTapi_key_id as apiKeyId,COALESCE(NULLIF(api_key_name, ''), NULLIF(api_key_id, ''), 'Unknown API key') as apiKeyName,- provider,- model,+ LOWER(provider) as provider,+ LOWER(model) as model,COUNT(*) as requests,COALESCE(SUM(tokens_input), 0) as promptTokens,COALESCE(SUM(tokens_output), 0) as completionTokens,@@ -378,7 +442,7 @@ export async function GET(request: Request) {COALESCE(SUM(tokens_input + tokens_output), 0) as totalTokensFROM usage_history${apiKeyWhereClause}- GROUP BY api_key_id, api_key_name, provider, model+ GROUP BY api_key_id, api_key_name, LOWER(provider), LOWER(model)`).all(params) as Array<Record<string, unknown>>;@@ -471,17 +535,31 @@ export async function GET(request: Request) {streak: 0,};+ const dailyByModelMap: Record<string, Record<string, number>> = {};+ const allModels = new Set<string>();+const dailyCostByDate = new Map<string, number>();for (const row of dailyCostRows) {const date = toStringValue(row.date);if (!date) continue;++ // Calculate costsconst cost = computeUsageRowCost(row,pricingByProvider,+ PROVIDER_ID_TO_ALIAS,normalizeModelName,computeCostFromPricing);dailyCostByDate.set(date, (dailyCostByDate.get(date) || 0) + cost);++ // Group tokens by model for the day+ const model = normalizeModelName(row.model as string);+ const tokens = Number(row.promptTokens) + Number(row.completionTokens);++ if (!dailyByModelMap[date]) dailyByModelMap[date] = {};+ dailyByModelMap[date][model] = (dailyByModelMap[date][model] || 0) + tokens;+ allModels.add(model);}const dailyTrend = dailyRows.map((row) => ({@@ -502,7 +580,7 @@ export async function GET(request: Request) {const byModel = modelRows.map((row) => {const model = row.model as string;const provider = row.provider as string;- const short = shortModelName(model);+ const short = normalizeModelName(model);const tokens = {input: Number(row.promptTokens) || 0,output: Number(row.completionTokens) || 0,@@ -510,6 +588,7 @@ export async function GET(request: Request) {const cost = computeUsageRowCost(row,pricingByProvider,+ PROVIDER_ID_TO_ALIAS,normalizeModelName,computeCostFromPricing);@@ -541,6 +620,7 @@ export async function GET(request: Request) {const cost = computeUsageRowCost(row,pricingByProvider,+ PROVIDER_ID_TO_ALIAS,normalizeModelName,computeCostFromPricing);@@ -567,6 +647,7 @@ export async function GET(request: Request) {const cost = computeUsageRowCost(row,pricingByProvider,+ PROVIDER_ID_TO_ALIAS,normalizeModelName,computeCostFromPricing);@@ -619,6 +700,7 @@ export async function GET(request: Request) {existing.cost += computeUsageRowCost(row,pricingByProvider,+ PROVIDER_ID_TO_ALIAS,normalizeModelName,computeCostFromPricing);@@ -650,6 +732,11 @@ export async function GET(request: Request) {}}+ const dailyByModel = Object.keys(dailyByModelMap)+ .sort()+ .map((date) => ({ date, ...dailyByModelMap[date] }));+ const modelNames = Array.from(allModels);+const analytics = {summary,dailyTrend,@@ -661,6 +748,8 @@ export async function GET(request: Request) {weeklyPattern,weeklyTokens,weeklyCounts,+ dailyByModel,+ modelNames,range,} as any;@@ -699,8 +788,8 @@ export async function GET(request: Request) {.prepare(`SELECT- model,- provider,+ LOWER(model) as model,+ LOWER(provider) as provider,COALESCE(SUM(tokens_input), 0) as promptTokens,COALESCE(SUM(tokens_output), 0) as completionTokens,COALESCE(SUM(tokens_cache_read), 0) as cacheReadTokens,@@ -708,7 +797,7 @@ export async function GET(request: Request) {COALESCE(SUM(tokens_reasoning), 0) as reasoningTokensFROM usage_history${presetWhere}- GROUP BY model, provider+ GROUP BY LOWER(model), LOWER(provider)`).all(presetParams) as Array<Record<string, unknown>>;@@ -718,6 +807,7 @@ export async function GET(request: Request) {presetTotalCost += computeUsageRowCost(row,pricingByProvider,+ PROVIDER_ID_TO_ALIAS,normalizeModelName,computeCostFromPricing);diff --git a/src/app/api/v1/embeddings/route.ts b/src/app/api/v1/embeddings/route.tsindex 9992f8273e..4fbe559448 100644--- a/src/app/api/v1/embeddings/route.ts+++ b/src/app/api/v1/embeddings/route.ts@@ -23,6 +23,10 @@ import { isValidationFailure, validateBody } from "@/shared/validation/helpers";import { getAllCustomModels, getProviderNodes } from "@/lib/localDb";+function toProviderScopedModelId(providerId: string, modelId: string): string {+ return modelId.startsWith(`${providerId}/`) ? modelId : `${providerId}/${modelId}`;+}+/*** Handle CORS preflight*/@@ -59,7 +63,7 @@ export async function GET() {for (const model of models) {if (!model?.id || !Array.isArray(model.supportedEndpoints)) continue;if (!model.supportedEndpoints.includes("embeddings")) continue;- const fullId = `${providerId}/${model.id}`;+ const fullId = toProviderScopedModelId(providerId, model.id);if (data.some((d) => d.id === fullId)) continue;data.push({id: fullId,diff --git a/src/app/api/v1/images/generations/route.ts b/src/app/api/v1/images/generations/route.tsindex 5c051da1c0..ceb99736fc 100644--- a/src/app/api/v1/images/generations/route.ts+++ b/src/app/api/v1/images/generations/route.ts@@ -19,7 +19,8 @@ import { enforceApiKeyPolicy } from "@/shared/utils/apiKeyPolicy";import { v1ImageGenerationSchema } from "@/shared/validation/schemas";import { isValidationFailure, validateBody } from "@/shared/validation/helpers";-import { getAllCustomModels } from "@/lib/localDb";+import { getAllCustomModels, resolveProxyForConnection } from "@/lib/localDb";+import { runWithProxyContext } from "@omniroute/open-sse/utils/proxyFetch.ts";/*** Handle CORS preflight@@ -226,14 +227,30 @@ export async function POST(request) {}}- const result = await handleImageGeneration({- body,- credentials,- log,- ...(isCustomModel && { resolvedProvider: provider }),- signal: request.signal,- clientHeaders: publicBaseUrlHeaders(request.headers),- });+ // Resolve proxy for the connection if credentials exist (#1904)+ let proxyInfo = null;+ if (credentials?.id) {+ try {+ proxyInfo = await resolveProxyForConnection(credentials.id);+ } catch {+ log.debug("PROXY", `Failed to resolve proxy for image provider: ${provider}`);+ }+ }++ const generateImage = () =>+ handleImageGeneration({+ body,+ credentials,+ log,+ ...(isCustomModel && { resolvedProvider: provider }),+ signal: request.signal,+ clientHeaders: publicBaseUrlHeaders(request.headers),+ });++ // Execute with proxy context when available, direct otherwise (#1904)+ const result = await (credentials?.id+ ? runWithProxyContext(proxyInfo?.proxy || null, generateImage)+ : generateImage());if (result.success) {await clearRecoveredProviderState(credentials);diff --git a/src/app/api/v1/models/catalog.ts b/src/app/api/v1/models/catalog.tsindex 29520bfe98..4445b0d72c 100644--- a/src/app/api/v1/models/catalog.ts+++ b/src/app/api/v1/models/catalog.ts@@ -210,6 +210,12 @@ export async function getUnifiedModelsResponse(if (authRejection) return authRejection;const { aliasToProviderId, providerIdToAlias } = buildAliasMaps();+ const resolveCanonicalProviderId = (aliasOrProviderId: string, fallbackProviderId?: string) =>+ aliasToProviderId[aliasOrProviderId] ||+ (fallbackProviderId ? aliasToProviderId[fallbackProviderId] : undefined) ||+ FALLBACK_ALIAS_TO_PROVIDER[aliasOrProviderId] ||+ fallbackProviderId ||+ aliasOrProviderId;// Issue #96: Allow blocking specific providers from the models listconst blockedProviders: Set<string> = new Set(@@ -322,7 +328,7 @@ export async function getUnifiedModelsResponse(// Add provider models (chat)for (const [alias, providerModels] of Object.entries(PROVIDER_MODELS)) {const providerId = aliasToProviderId[alias] || alias;- const canonicalProviderId = FALLBACK_ALIAS_TO_PROVIDER[alias] || providerId;+ const canonicalProviderId = resolveCanonicalProviderId(alias, providerId);// Skip blocked providers (Issue #96)if (blockedProviders.has(alias) || blockedProviders.has(canonicalProviderId)) continue;@@ -387,7 +393,7 @@ export async function getUnifiedModelsResponse(const prefix = providerIdToPrefix[providerId];const alias = prefix || providerIdToAlias[providerId] || providerId;- const canonicalProviderId = FALLBACK_ALIAS_TO_PROVIDER[alias] || providerId;+ const canonicalProviderId = resolveCanonicalProviderId(alias, providerId);const parentProviderType = nodeIdToProviderType[providerId];if (@@ -405,12 +411,15 @@ export async function getUnifiedModelsResponse(const aliasId = `${alias}/${sm.id}`;const endpoints = Array.isArray(sm.supportedEndpoints) ? sm.supportedEndpoints : ["chat"];+ const apiFormat = typeof sm.apiFormat === "string" ? sm.apiFormat : "chat-completions";let modelType: string | undefined;if (endpoints.includes("embeddings")) modelType = "embedding";+ else if (endpoints.includes("rerank")) modelType = "rerank";else if (endpoints.includes("images")) modelType = "image";else if (endpoints.includes("audio")) modelType = "audio";const syncedFields = {...(modelType ? { type: modelType } : {}),+ ...(apiFormat !== "chat-completions" ? { api_format: apiFormat } : {}),...(modelType === "audio" ? { subtype: "transcription" } : {}),...(sm.inputTokenLimit ? { context_length: sm.inputTokenLimit } : {}),...(endpoints.length > 1 || !endpoints.includes("chat")@@ -478,7 +487,7 @@ export async function getUnifiedModelsResponse(const isProviderActive = (provider: string) => {if (activeAliases.size === 0) return false; // No active connections = show nothingconst alias = providerIdToAlias[provider] || provider;- const canonicalProviderId = FALLBACK_ALIAS_TO_PROVIDER[alias] || provider;+ const canonicalProviderId = resolveCanonicalProviderId(alias, provider);// FIX #1752: Ensure blocked providers are not returned for non-chat modelsif (@@ -492,16 +501,38 @@ export async function getUnifiedModelsResponse(return activeAliases.has(alias) || activeAliases.has(provider);};+ const hasEquivalentSpecialtyModel = (+ providerId: string,+ rawModelId: string,+ type: string,+ scopedModelId: string+ ) =>+ models.some((model: any) => {+ if (model?.id === scopedModelId) return true;+ if (model?.owned_by !== providerId || model?.type !== type) return false;+ const existingRoot =+ typeof model?.root === "string"+ ? model.root+ : typeof model?.id === "string"+ ? model.id.split("/").pop()+ : null;+ return existingRoot === rawModelId;+ });+// Add embedding models (filtered by active providers)for (const embModel of getAllEmbeddingModels()) {if (!isProviderActive(embModel.provider)) continue;const rawModelId = embModel.id.split("/").pop() || embModel.id;if (!providerSupportsModel(embModel.provider, rawModelId)) continue;+ if (hasEquivalentSpecialtyModel(embModel.provider, rawModelId, "embedding", embModel.id)) {+ continue;+ }models.push({id: embModel.id,object: "model",created: timestamp,owned_by: embModel.provider,+ root: rawModelId,type: "embedding",dimensions: embModel.dimensions,});@@ -530,11 +561,15 @@ export async function getUnifiedModelsResponse(if (!isProviderActive(rerankModel.provider)) continue;const rawModelId = rerankModel.id.split("/").pop() || rerankModel.id;if (!providerSupportsModel(rerankModel.provider, rawModelId)) continue;+ if (hasEquivalentSpecialtyModel(rerankModel.provider, rawModelId, "rerank", rerankModel.id)) {+ continue;+ }models.push({id: rerankModel.id,object: "model",created: timestamp,owned_by: rerankModel.provider,+ root: rawModelId,type: "rerank",});}@@ -611,7 +646,7 @@ export async function getUnifiedModelsResponse(// For compatible providers, use the prefix from provider nodesconst prefix = providerIdToPrefix[providerId];const alias = prefix || providerIdToAlias[providerId] || providerId;- const canonicalProviderId = FALLBACK_ALIAS_TO_PROVIDER[alias] || providerId;+ const canonicalProviderId = resolveCanonicalProviderId(alias, providerId);// Only include if provider is active — check alias, canonical ID, raw providerId,// or the parent provider type (for compatible providers whose node ID is a UUID)@@ -649,8 +684,15 @@ export async function getUnifiedModelsResponse(typeof model.apiFormat === "string" ? model.apiFormat : "chat-completions";let modelType: string | undefined;if (endpoints.includes("embeddings")) modelType = "embedding";+ else if (endpoints.includes("rerank")) modelType = "rerank";else if (endpoints.includes("images")) modelType = "image";else if (endpoints.includes("audio")) modelType = "audio";+ if (+ modelType &&+ hasEquivalentSpecialtyModel(canonicalProviderId, modelId, modelType, aliasId)+ ) {+ continue;+ }const visionFields =modelType === "chat"? getVisionCapabilityFields(aliasId) || getVisionCapabilityFields(modelId)diff --git a/src/i18n/messages/ar.json b/src/i18n/messages/ar.jsonindex 7c631bc21a..f53a16b164 100644--- a/src/i18n/messages/ar.json+++ b/src/i18n/messages/ar.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "المواضيع",@@ -2555,7 +2559,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2575,6 +2579,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2608,6 +2615,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2615,7 +2623,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2678,7 +2686,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3281,7 +3289,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "مترجم",diff --git a/src/i18n/messages/bg.json b/src/i18n/messages/bg.jsonindex 0d95294a9d..50647322db 100644--- a/src/i18n/messages/bg.json+++ b/src/i18n/messages/bg.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "Теми",@@ -2555,7 +2559,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2575,6 +2579,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2608,6 +2615,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2615,7 +2623,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2678,7 +2686,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3281,7 +3289,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "Преводач",diff --git a/src/i18n/messages/bn.json b/src/i18n/messages/bn.jsonindex de75332f30..76b811bfe7 100644--- a/src/i18n/messages/bn.json+++ b/src/i18n/messages/bn.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "Themes",@@ -2717,7 +2721,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2737,6 +2741,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2770,6 +2777,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2777,7 +2785,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2841,7 +2849,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3438,7 +3446,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "Translator",diff --git a/src/i18n/messages/cs.json b/src/i18n/messages/cs.jsonindex f40d8d6491..99baade68b 100644--- a/src/i18n/messages/cs.json+++ b/src/i18n/messages/cs.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "Motivy",@@ -2555,7 +2559,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2575,6 +2579,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2608,6 +2615,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2615,7 +2623,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2678,7 +2686,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3281,7 +3289,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "Překladatel",diff --git a/src/i18n/messages/da.json b/src/i18n/messages/da.jsonindex 758d6ca328..b4cd041183 100644--- a/src/i18n/messages/da.json+++ b/src/i18n/messages/da.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "Temaer",@@ -2555,7 +2559,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2575,6 +2579,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2608,6 +2615,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2615,7 +2623,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2678,7 +2686,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3281,7 +3289,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "Oversætter",diff --git a/src/i18n/messages/de.json b/src/i18n/messages/de.jsonindex dc2da758c3..aef5cdb6ca 100644--- a/src/i18n/messages/de.json+++ b/src/i18n/messages/de.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "Themen",@@ -2555,7 +2559,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2575,6 +2579,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2608,6 +2615,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2615,7 +2623,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2678,7 +2686,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3281,7 +3289,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "Übersetzer",diff --git a/src/i18n/messages/en.json b/src/i18n/messages/en.jsonindex d61db2dfc3..fdb7ade61e 100644--- a/src/i18n/messages/en.json+++ b/src/i18n/messages/en.json@@ -736,7 +736,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"webhooks": {"title": "Webhooks",@@ -2937,7 +2941,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add CC Compatible","aggregatorsGateways": "Aggregators Gateways","enterpriseCloud": "Enterprise & Cloud",@@ -2958,6 +2962,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Hide extra Claude usage rows reported by some providers when they duplicate primary token accounting.","blockClaudeExtraUsageLabel": "Block duplicate Claude usage rows",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Base URL for a Claude Code-only relay. Do not include /messages.","ccCompatibleBaseUrlPlaceholder": "https://relay.example.com/v1","ccCompatibleChatPathHint": "Defaults to Claude Code's strict Messages API path. Change only if your relay documents a different path.",@@ -2991,6 +2998,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2998,7 +3006,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -3064,7 +3072,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3696,7 +3704,90 @@"compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log","compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",- "minutes": "minutes"+ "minutes": "minutes",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "deduplicateThreshold": "Deduplicate threshold",+ "customFilters": "Custom filters",+ "trustProjectFilters": "Trust project filters",+ "rawOutputRetention": "Raw output retention",+ "rawOutputNever": "Never",+ "rawOutputFailures": "Failures",+ "rawOutputAlways": "Always",+ "rawOutputMaxBytes": "Raw output max bytes",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "bypassConditionsList": "security, irreversible, clarification, order-sensitive",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "Translator",@@ -5112,6 +5203,7 @@"apiKey": "API Key","combo": "Combo","tokens": "Tokens",+ "compressed": "Compression","tps": "TPS","duration": "Duration","time": "Time"diff --git a/src/i18n/messages/es.json b/src/i18n/messages/es.jsonindex c0d3a0dac5..bbaee8d63e 100644--- a/src/i18n/messages/es.json+++ b/src/i18n/messages/es.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "Temas",@@ -2555,7 +2559,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2575,6 +2579,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2608,6 +2615,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2615,7 +2623,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2678,7 +2686,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3281,7 +3289,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "Traductor",diff --git a/src/i18n/messages/fa.json b/src/i18n/messages/fa.jsonindex de75332f30..76b811bfe7 100644--- a/src/i18n/messages/fa.json+++ b/src/i18n/messages/fa.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "Themes",@@ -2717,7 +2721,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2737,6 +2741,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2770,6 +2777,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2777,7 +2785,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2841,7 +2849,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3438,7 +3446,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "Translator",diff --git a/src/i18n/messages/fi.json b/src/i18n/messages/fi.jsonindex bcbccd7f27..9c9ac3b3a0 100644--- a/src/i18n/messages/fi.json+++ b/src/i18n/messages/fi.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "Teemat",@@ -2555,7 +2559,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2575,6 +2579,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2608,6 +2615,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2615,7 +2623,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2678,7 +2686,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3281,7 +3289,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "Kääntäjä",diff --git a/src/i18n/messages/fr.json b/src/i18n/messages/fr.jsonindex 29f5a12e07..864d6d0569 100644--- a/src/i18n/messages/fr.json+++ b/src/i18n/messages/fr.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "Thèmes",@@ -2555,7 +2559,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2575,6 +2579,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2608,6 +2615,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2615,7 +2623,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2678,7 +2686,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3281,7 +3289,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "Traducteur",diff --git a/src/i18n/messages/gu.json b/src/i18n/messages/gu.jsonindex de75332f30..76b811bfe7 100644--- a/src/i18n/messages/gu.json+++ b/src/i18n/messages/gu.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "Themes",@@ -2717,7 +2721,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2737,6 +2741,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2770,6 +2777,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2777,7 +2785,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2841,7 +2849,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3438,7 +3446,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "Translator",diff --git a/src/i18n/messages/he.json b/src/i18n/messages/he.jsonindex 5114d855a4..3e1b0ba309 100644--- a/src/i18n/messages/he.json+++ b/src/i18n/messages/he.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "Themes",@@ -2555,7 +2559,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2575,6 +2579,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2608,6 +2615,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2615,7 +2623,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2678,7 +2686,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3281,7 +3289,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "מתרגם",diff --git a/src/i18n/messages/hi.json b/src/i18n/messages/hi.jsonindex 4afc1f9aa6..21f523f296 100644--- a/src/i18n/messages/hi.json+++ b/src/i18n/messages/hi.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "Themes",@@ -2555,7 +2559,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2575,6 +2579,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2608,6 +2615,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2615,7 +2623,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2678,7 +2686,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3281,7 +3289,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "अनुवादक",diff --git a/src/i18n/messages/hu.json b/src/i18n/messages/hu.jsonindex 55714b00ee..9c297547bb 100644--- a/src/i18n/messages/hu.json+++ b/src/i18n/messages/hu.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "Témák",@@ -2555,7 +2559,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2575,6 +2579,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2608,6 +2615,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2615,7 +2623,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2678,7 +2686,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3281,7 +3289,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "Fordító",diff --git a/src/i18n/messages/id.json b/src/i18n/messages/id.jsonindex a4f7ab77fb..3eb7a5f1b2 100644--- a/src/i18n/messages/id.json+++ b/src/i18n/messages/id.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "Themes",@@ -2555,7 +2559,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2575,6 +2579,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2608,6 +2615,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2615,7 +2623,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2678,7 +2686,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3281,7 +3289,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "Penerjemah",diff --git a/src/i18n/messages/in.json b/src/i18n/messages/in.jsonindex de75332f30..76b811bfe7 100644--- a/src/i18n/messages/in.json+++ b/src/i18n/messages/in.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "Themes",@@ -2717,7 +2721,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2737,6 +2741,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2770,6 +2777,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2777,7 +2785,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2841,7 +2849,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3438,7 +3446,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "Translator",diff --git a/src/i18n/messages/it.json b/src/i18n/messages/it.jsonindex eab3a5a395..74bdb97eec 100644--- a/src/i18n/messages/it.json+++ b/src/i18n/messages/it.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "Themes",@@ -2555,7 +2559,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2575,6 +2579,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2608,6 +2615,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2615,7 +2623,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2678,7 +2686,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3281,7 +3289,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "Traduttore",diff --git a/src/i18n/messages/ja.json b/src/i18n/messages/ja.jsonindex 6273245d10..53b7954beb 100644--- a/src/i18n/messages/ja.json+++ b/src/i18n/messages/ja.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "Themes",@@ -2555,7 +2559,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2575,6 +2579,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2608,6 +2615,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2615,7 +2623,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2678,7 +2686,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3281,7 +3289,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "翻訳者",diff --git a/src/i18n/messages/ko.json b/src/i18n/messages/ko.jsonindex 5092f3ed80..c59b90e65b 100644--- a/src/i18n/messages/ko.json+++ b/src/i18n/messages/ko.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "Themes",@@ -2555,7 +2559,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2575,6 +2579,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2608,6 +2615,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2615,7 +2623,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2678,7 +2686,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3283,7 +3291,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "번역기",diff --git a/src/i18n/messages/mr.json b/src/i18n/messages/mr.jsonindex de75332f30..76b811bfe7 100644--- a/src/i18n/messages/mr.json+++ b/src/i18n/messages/mr.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "Themes",@@ -2717,7 +2721,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2737,6 +2741,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2770,6 +2777,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2777,7 +2785,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2841,7 +2849,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3438,7 +3446,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "Translator",diff --git a/src/i18n/messages/ms.json b/src/i18n/messages/ms.jsonindex 4bc7cc6c9d..a67b0035ac 100644--- a/src/i18n/messages/ms.json+++ b/src/i18n/messages/ms.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "Themes",@@ -2555,7 +2559,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2575,6 +2579,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2608,6 +2615,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2615,7 +2623,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2678,7 +2686,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3281,7 +3289,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "Penterjemah",diff --git a/src/i18n/messages/nl.json b/src/i18n/messages/nl.jsonindex c7f414fb44..86d60edfb3 100644--- a/src/i18n/messages/nl.json+++ b/src/i18n/messages/nl.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "Themes",@@ -2555,7 +2559,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2575,6 +2579,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2608,6 +2615,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2615,7 +2623,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2678,7 +2686,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3281,7 +3289,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "Vertaler",diff --git a/src/i18n/messages/no.json b/src/i18n/messages/no.jsonindex bd7ddc490b..f0f0fe2cbd 100644--- a/src/i18n/messages/no.json+++ b/src/i18n/messages/no.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "Themes",@@ -2555,7 +2559,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2575,6 +2579,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2608,6 +2615,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2615,7 +2623,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2678,7 +2686,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3281,7 +3289,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "Oversetter",diff --git a/src/i18n/messages/phi.json b/src/i18n/messages/phi.jsonindex 6481165823..a8320653a8 100644--- a/src/i18n/messages/phi.json+++ b/src/i18n/messages/phi.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "Themes",@@ -2555,7 +2559,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2575,6 +2579,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2608,6 +2615,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2615,7 +2623,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2678,7 +2686,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3281,7 +3289,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "Tagasalin",diff --git a/src/i18n/messages/pl.json b/src/i18n/messages/pl.jsonindex 6167244edd..01f1228530 100644--- a/src/i18n/messages/pl.json+++ b/src/i18n/messages/pl.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "Themes",@@ -2555,7 +2559,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2575,6 +2579,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2608,6 +2615,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2615,7 +2623,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2678,7 +2686,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3281,7 +3289,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "Tłumacz",diff --git a/src/i18n/messages/pt-BR.json b/src/i18n/messages/pt-BR.jsonindex 57c9f5d716..b683f32bea 100644--- a/src/i18n/messages/pt-BR.json+++ b/src/i18n/messages/pt-BR.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "Themes",@@ -2735,7 +2739,7 @@"apiRegionChina": "China Continental (open.bigmodel.cn)","extraApiKeysLabel": "Chaves de API Extras","extraApiKeysHint": "Rotação round-robin — opcional",- "extraApiKeyMasked": "Chave #{index}: {prefix}...{suffix}",+ "extraApiKeyMasked": "Chave {index}: {prefix}••••{suffix}","removeThisKey": "Remover esta chave","addAnotherApiKey": "Adicionar outra chave de API...","totalKeysRotating": "{count} chaves no total — rotacionando em round-robin a cada request.",@@ -2743,6 +2747,7 @@"tagGroupPlaceholder": "ex.: personal, work, team-a","tagGroupHint": "Usado para agrupar contas na visão do provedor.","defaultThinkingStrengthLabel": "Intensidade de raciocínio padrão",+ "deleteAllExtraApiKeys": "Excluir todas","defaultThinkingStrengthHint": "Usada quando o cliente não envia reasoning effort e o modo global Thinking Budget está em passthrough.","maxConcurrentWholeNumberError": "Max concurrent deve ser um número inteiro maior ou igual a 0.","codexFastServiceTierLabel": "Codex Fast Service Tier",@@ -2750,6 +2755,9 @@"openaiResponsesStoreLabel": "OpenAI Responses Store","openaiResponsesStoreDescription": "Preserva `store`, `previous_response_id` e adiciona um `session_id` estável como fallback para sessões longas do Codex. Habilite apenas quando a conta upstream aceitar Responses armazenadas.","blockClaudeExtraUsageLabel": "Bloquear Claude Extra Usage",+ "bulkPasteAdded": "{count, plural, one {1 chave adicionada} other {# chaves adicionadas}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicata ignorada} other {# duplicatas ignoradas}}",+ "bulkPasteHint": "Cole uma chave de API por linha. Linhas vazias são ignoradas e chaves duplicadas são puladas.","blockClaudeExtraUsageDescription": "Quando habilitado, o OmniRoute marca esta conta do Claude Code como indisponível assim que a API de usage reporta `extra_usage.queued`, para que o fallback troque para outra conta antes de continuar com cobranças extras pay-as-you-go.","hideEmail": "Ocultar e-mail","showEmail": "Mostrar e-mail",@@ -3398,7 +3406,90 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "Motor RTK",+ "description": "Compressao sensivel a comandos para tool output, logs de terminal e builds.",+ "enabled": "Ativo",+ "intensity": "Intensidade",+ "intensityMinimal": "Minima",+ "intensityStandard": "Padrao",+ "intensityAggressive": "Agressiva",+ "toolResults": "Resultados de tools",+ "assistantMessages": "Mensagens do assistente",+ "codeBlocks": "Blocos de codigo",+ "maxLines": "Max linhas",+ "maxChars": "Max caracteres",+ "deduplicateThreshold": "Limite de deduplicacao",+ "customFilters": "Filtros customizados",+ "trustProjectFilters": "Confiar em filtros do projeto",+ "rawOutputRetention": "Retencao de raw output",+ "rawOutputNever": "Nunca",+ "rawOutputFailures": "Falhas",+ "rawOutputAlways": "Sempre",+ "rawOutputMaxBytes": "Max bytes de raw output",+ "filterTesting": "Teste de filtros",+ "pasteOutput": "Cole output de ferramenta para testar...",+ "run": "Executar",+ "result": "Resultado",+ "previewEmpty": "Execute um exemplo para visualizar o RTK.",+ "detected": "Detectado",+ "tokensFiltered": "Tokens filtrados",+ "filtersActive": "Filtros ativos",+ "requests": "Requests",+ "avgSavings": "Economia media"+ },+ "contextCombos": {+ "title": "Combos de Compressao",+ "description": "Defina como engines sao combinadas para diferentes cenarios de roteamento.",+ "createCombo": "Criar Combo",+ "editCombo": "Editar",+ "deleteCombo": "Excluir",+ "deleteConfirm": "Excluir este combo de compressao?",+ "pipeline": "Pipeline",+ "addStep": "Adicionar Step",+ "removeStep": "Remover",+ "name": "Nome",+ "descriptionField": "Descricao",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Atribuir a Combos de Roteamento",+ "noAssignments": "Nenhum combo de roteamento disponivel",+ "default": "Default",+ "setAsDefault": "Definir como default",+ "save": "Salvar",+ "cancel": "Cancelar",+ "enabled": "Ativo"+ },+ "contextCaveman": {+ "title": "Motor Caveman",+ "description": "Compressao baseada em regras, language packs, analytics e output mode.",+ "requests": "Requests",+ "tokensSaved": "Tokens salvos",+ "savingsPercent": "Economia %",+ "avgLatency": "Latencia media",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Ative regras de compressao para idiomas especificos.",+ "enabled": "Ativo",+ "autoDetect": "Auto-detectar idioma",+ "rulesCount": "{count} regras",+ "analyticsTitle": "Analytics de Compressao",+ "noAnalytics": "Sem analytics de compressao ainda.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instrui o LLM a responder em formato curto e compacto.",+ "autoClarity": "Bypass Auto-Clarity",+ "bypassConditions": "Condicoes de bypass",+ "bypassConditionsList": "seguranca, irreversivel, clarificacao, sensivel a ordem",+ "preview": {+ "lite": "Responda conciso. Preserve termos tecnicos, codigo, erros, URLs e identificadores.",+ "full": "Responda seco e compacto. Preserve todo conteudo tecnico.",+ "ultra": "Responda ultra compacto com abreviacoes tecnicas comuns. Preserve simbolos exatos."+ }},"translator": {"title": "Tradutor",diff --git a/src/i18n/messages/pt.json b/src/i18n/messages/pt.jsonindex 0153540639..eec9fd947b 100644--- a/src/i18n/messages/pt.json+++ b/src/i18n/messages/pt.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "Themes",@@ -2627,7 +2631,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2647,6 +2651,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2680,6 +2687,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2687,7 +2695,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2750,7 +2758,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3368,7 +3376,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "Tradutor",diff --git a/src/i18n/messages/ro.json b/src/i18n/messages/ro.jsonindex 02ca5bf121..114e40112c 100644--- a/src/i18n/messages/ro.json+++ b/src/i18n/messages/ro.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "Themes",@@ -2555,7 +2559,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2575,6 +2579,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2608,6 +2615,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2615,7 +2623,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2678,7 +2686,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3281,7 +3289,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "Traducător",diff --git a/src/i18n/messages/ru.json b/src/i18n/messages/ru.jsonindex 402d320586..ef348f3b50 100644--- a/src/i18n/messages/ru.json+++ b/src/i18n/messages/ru.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "Темы",@@ -2579,7 +2583,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2599,6 +2603,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2632,6 +2639,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2639,7 +2647,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2702,7 +2710,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3305,7 +3313,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "Переводчик",diff --git a/src/i18n/messages/sk.json b/src/i18n/messages/sk.jsonindex 3eff1eb6e2..ff56cac7db 100644--- a/src/i18n/messages/sk.json+++ b/src/i18n/messages/sk.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "Themes",@@ -2555,7 +2559,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2575,6 +2579,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2608,6 +2615,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2615,7 +2623,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2678,7 +2686,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3281,7 +3289,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "Prekladateľ",diff --git a/src/i18n/messages/sv.json b/src/i18n/messages/sv.jsonindex 112f8ae4f5..94a2c94f9c 100644--- a/src/i18n/messages/sv.json+++ b/src/i18n/messages/sv.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "Themes",@@ -2555,7 +2559,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2575,6 +2579,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2608,6 +2615,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2615,7 +2623,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2678,7 +2686,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3281,7 +3289,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "Översättare",diff --git a/src/i18n/messages/sw.json b/src/i18n/messages/sw.jsonindex de75332f30..76b811bfe7 100644--- a/src/i18n/messages/sw.json+++ b/src/i18n/messages/sw.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "Themes",@@ -2717,7 +2721,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2737,6 +2741,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2770,6 +2777,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2777,7 +2785,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2841,7 +2849,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3438,7 +3446,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "Translator",diff --git a/src/i18n/messages/ta.json b/src/i18n/messages/ta.jsonindex de75332f30..76b811bfe7 100644--- a/src/i18n/messages/ta.json+++ b/src/i18n/messages/ta.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "Themes",@@ -2717,7 +2721,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2737,6 +2741,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2770,6 +2777,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2777,7 +2785,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2841,7 +2849,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3438,7 +3446,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "Translator",diff --git a/src/i18n/messages/te.json b/src/i18n/messages/te.jsonindex de75332f30..76b811bfe7 100644--- a/src/i18n/messages/te.json+++ b/src/i18n/messages/te.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "Themes",@@ -2717,7 +2721,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2737,6 +2741,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2770,6 +2777,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2777,7 +2785,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2841,7 +2849,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3438,7 +3446,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "Translator",diff --git a/src/i18n/messages/th.json b/src/i18n/messages/th.jsonindex 4a3d0b470f..78b3001059 100644--- a/src/i18n/messages/th.json+++ b/src/i18n/messages/th.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "ธีมส์",@@ -2555,7 +2559,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2575,6 +2579,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2608,6 +2615,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2615,7 +2623,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2678,7 +2686,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3281,7 +3289,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "นักแปล",diff --git a/src/i18n/messages/tr.json b/src/i18n/messages/tr.jsonindex 25a033a543..99039f8a4b 100644--- a/src/i18n/messages/tr.json+++ b/src/i18n/messages/tr.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "Temalar",@@ -2555,7 +2559,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2575,6 +2579,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2608,6 +2615,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2615,7 +2623,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2678,7 +2686,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3281,7 +3289,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "Çeviri",diff --git a/src/i18n/messages/uk-UA.json b/src/i18n/messages/uk-UA.jsonindex 6e8426cd22..47f66c4b1b 100644--- a/src/i18n/messages/uk-UA.json+++ b/src/i18n/messages/uk-UA.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "Themes",@@ -2555,7 +2559,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2575,6 +2579,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2608,6 +2615,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2615,7 +2623,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2678,7 +2686,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3281,7 +3289,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "Перекладач",diff --git a/src/i18n/messages/ur.json b/src/i18n/messages/ur.jsonindex de75332f30..76b811bfe7 100644--- a/src/i18n/messages/ur.json+++ b/src/i18n/messages/ur.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "Themes",@@ -2717,7 +2721,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2737,6 +2741,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2770,6 +2777,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2777,7 +2785,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2841,7 +2849,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3438,7 +3446,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "Translator",diff --git a/src/i18n/messages/vi.json b/src/i18n/messages/vi.jsonindex ade7650250..d08b9ec0c3 100644--- a/src/i18n/messages/vi.json+++ b/src/i18n/messages/vi.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "Themes",@@ -2555,7 +2559,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "Add Cc Compatible","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2575,6 +2579,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "Block Claude Extra Usage Description","blockClaudeExtraUsageLabel": "Block Claude Extra Usage Label",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Cc Compatible Base Url Hint","ccCompatibleBaseUrlPlaceholder": "Cc Compatible Base Url Placeholder","ccCompatibleChatPathHint": "Cc Compatible Chat Path Hint",@@ -2608,6 +2615,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "Used when a request does not specify reasoning effort.","defaultThinkingStrengthLabel": "Default thinking strength",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2615,7 +2623,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2678,7 +2686,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3281,7 +3289,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "Người phiên dịch",diff --git a/src/i18n/messages/zh-CN.json b/src/i18n/messages/zh-CN.jsonindex 3cbf7ab6bb..a2946ad009 100644--- a/src/i18n/messages/zh-CN.json+++ b/src/i18n/messages/zh-CN.json@@ -735,7 +735,11 @@"themeCustom": "Theme Custom","hideHealthLogsDesc": "Hide Health Logs Desc","faviconPreview": "Favicon Preview",- "changelog": "Changelog"+ "changelog": "Changelog",+ "contextSection": "Context & Cache",+ "contextCaveman": "Caveman",+ "contextRtk": "RTK",+ "contextCombos": "Compression Combos"},"themesPage": {"title": "主题",@@ -2657,7 +2661,7 @@"accountIdHint": "Account Id Hint","accountIdLabel": "Account Id Label","accountIdPlaceholder": "Account Id Placeholder",- "addAnotherApiKey": "Add Another Api Key",+ "addAnotherApiKey": "Add another API key or paste multiple keys","addCcCompatible": "添加 CC 兼容","aggregatorsGateways": "Aggregators Gateways","apiFormatLabel": "Api Format Label",@@ -2677,6 +2681,9 @@"blackboxWebCookiePlaceholder": "Blackbox Web Cookie Placeholder","blockClaudeExtraUsageDescription": "隐藏部分 Provider 返回的重复 Claude 额外用量记录,避免和主 token 统计重复。","blockClaudeExtraUsageLabel": "屏蔽重复 Claude 用量",+ "bulkPasteAdded": "{count, plural, one {1 key added} other {# keys added}}",+ "bulkPasteDuplicatesIgnored": "{count, plural, one {1 duplicate skipped} other {# duplicates skipped}}",+ "bulkPasteHint": "Paste one API key per line. Empty lines are ignored and duplicate keys are skipped.","ccCompatibleBaseUrlHint": "Claude Code 专用中转站的 Base URL,不要包含 /messages。","ccCompatibleBaseUrlPlaceholder": "https://relay.example.com/v1","ccCompatibleChatPathHint": "默认使用 Claude Code 严格的 Messages API 路径。仅在中转站文档要求时修改。",@@ -2710,6 +2717,7 @@"databricksBaseUrlHint": "Databricks Base Url Hint","defaultThinkingStrengthHint": "请求未指定 reasoning effort 时使用。","defaultThinkingStrengthLabel": "默认思考强度",+ "deleteAllExtraApiKeys": "Delete all","excludedModelsHint": "Excluded Models Hint","excludedModelsLabel": "Excluded Models Label","excludedModelsPlaceholder": "Excluded Models Placeholder",@@ -2717,7 +2725,7 @@"expirationBannerExpiredDesc": "Expiration Banner Expired Desc","expirationBannerExpiringSoon": "Expiration Banner Expiring Soon","expirationBannerExpiringSoonDesc": "Expiration Banner Expiring Soon Desc",- "extraApiKeyMasked": "Extra Api Key Masked",+ "extraApiKeyMasked": "Key {index}: {prefix}••••{suffix}","extraApiKeysHint": "Extra Api Keys Hint","extraApiKeysLabel": "Extra Api Keys Label","googlePseInfo": "Google Pse Info",@@ -2781,7 +2789,7 @@"tokenExpiredTitle": "Token Expired Title","tokenExpiresSoonTitle": "Token Expires Soon Title","tokenShort": "Token Short",- "totalKeysRotating": "Total Keys Rotating",+ "totalKeysRotating": "{count, plural, one {1 key rotating} other {# keys rotating}}","unhideModel": "Unhide Model","upstreamProxyProviders": "Upstream Proxy Providers","validationModelIdHint": "Validation Model Id Hint",@@ -3390,7 +3398,81 @@"compressionPreservePatterns": "Preserve Patterns","compressionPreservePatternsDesc": "Regex patterns that are never compressed (one per line)","compressionLogTitle": "Compression Log",- "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled."+ "compressionLogEmpty": "No compressed requests yet. Compression stats will appear here when requests are processed with compression enabled.",+ "compressionModeRtk": "RTK",+ "compressionModeRtkDesc": "Command-aware tool output filtering",+ "compressionModeStacked": "Stacked",+ "compressionModeStackedDesc": "RTK tool-output filtering followed by Caveman message compression"+ },+ "contextRtk": {+ "title": "RTK Engine",+ "description": "Command-aware compression for tool output, terminal logs and build results.",+ "enabled": "Enabled",+ "intensity": "Intensity",+ "intensityMinimal": "Minimal",+ "intensityStandard": "Standard",+ "intensityAggressive": "Aggressive",+ "toolResults": "Tool results",+ "assistantMessages": "Assistant messages",+ "codeBlocks": "Code blocks",+ "maxLines": "Max lines",+ "maxChars": "Max chars",+ "filterTesting": "Filter Testing",+ "pasteOutput": "Paste tool output to test filtering...",+ "run": "Run",+ "result": "Result",+ "previewEmpty": "Run a sample to preview RTK output.",+ "detected": "Detected",+ "tokensFiltered": "Tokens filtered",+ "filtersActive": "Filters active",+ "requests": "Requests",+ "avgSavings": "Avg savings"+ },+ "contextCombos": {+ "title": "Compression Combos",+ "description": "Define how engines are combined for different routing scenarios.",+ "createCombo": "Create Compression Combo",+ "editCombo": "Edit",+ "deleteCombo": "Delete",+ "deleteConfirm": "Delete this compression combo?",+ "pipeline": "Pipeline",+ "addStep": "Add Step",+ "removeStep": "Remove",+ "name": "Name",+ "descriptionField": "Description",+ "languagePacks": "Language Packs",+ "outputMode": "Output Mode",+ "assignToRouting": "Assign to Routing Combos",+ "noAssignments": "No routing combos available",+ "default": "Default",+ "setAsDefault": "Set as Default",+ "save": "Save",+ "cancel": "Cancel",+ "enabled": "Enabled"+ },+ "contextCaveman": {+ "title": "Caveman Engine",+ "description": "Rule-based message compression, language packs, analytics and output mode controls.",+ "requests": "Requests",+ "tokensSaved": "Tokens saved",+ "savingsPercent": "Savings %",+ "avgLatency": "Avg latency",+ "languagePacks": "Language Packs",+ "languagePacksDesc": "Enable compression rules for specific languages.",+ "enabled": "Enabled",+ "autoDetect": "Auto-detect language",+ "rulesCount": "{count} rules",+ "analyticsTitle": "Compression Analytics",+ "noAnalytics": "No compression analytics yet.",+ "outputModeTitle": "Output Mode",+ "outputModeDesc": "Instructs the LLM to respond in a terse, compact format.",+ "autoClarity": "Auto-Clarity Bypass",+ "bypassConditions": "Bypass conditions",+ "preview": {+ "lite": "Respond concise. Preserve technical terms, code, errors, URLs, and identifiers.",+ "full": "Respond terse and compact. Preserve all technical substance.",+ "ultra": "Respond ultra terse with common technical abbreviations. Preserve exact symbols."+ }},"translator": {"title": "翻译器",diff --git a/src/lib/db/compression.ts b/src/lib/db/compression.tsindex 8d45f82f37..1a240d81d6 100644--- a/src/lib/db/compression.ts+++ b/src/lib/db/compression.ts@@ -4,12 +4,19 @@ import { invalidateDbCache } from "./readCache";import {DEFAULT_AGGRESSIVE_CONFIG,DEFAULT_CAVEMAN_CONFIG,+ DEFAULT_CAVEMAN_OUTPUT_MODE_CONFIG,+ DEFAULT_COMPRESSION_LANGUAGE_CONFIG,DEFAULT_COMPRESSION_CONFIG,+ DEFAULT_RTK_CONFIG,DEFAULT_ULTRA_CONFIG,type AggressiveConfig,type CavemanConfig,+ type CavemanOutputModeConfig,+ type CompressionLanguageConfig,+ type CompressionPipelineStep,type CompressionConfig,type CompressionMode,+ type RtkConfig,type UltraConfig,} from "@omniroute/open-sse/services/compression/types.ts";@@ -20,6 +27,8 @@ const COMPRESSION_MODES = new Set<CompressionMode>(["standard","aggressive","ultra",+ "rtk",+ "stacked",]);type JsonRecord = Record<string, unknown>;@@ -47,6 +56,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,9 +79,153 @@ 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,+ };+}++function normalizeRtkConfig(value: unknown): RtkConfig {+ const record = toRecord(value);+ return {+ ...DEFAULT_RTK_CONFIG,+ enabled: typeof record.enabled === "boolean" ? record.enabled : DEFAULT_RTK_CONFIG.enabled,+ intensity:+ record.intensity === "minimal" ||+ record.intensity === "standard" ||+ record.intensity === "aggressive"+ ? record.intensity+ : DEFAULT_RTK_CONFIG.intensity,+ applyToToolResults:+ typeof record.applyToToolResults === "boolean"+ ? record.applyToToolResults+ : DEFAULT_RTK_CONFIG.applyToToolResults,+ applyToCodeBlocks:+ typeof record.applyToCodeBlocks === "boolean"+ ? record.applyToCodeBlocks+ : DEFAULT_RTK_CONFIG.applyToCodeBlocks,+ applyToAssistantMessages:+ typeof record.applyToAssistantMessages === "boolean"+ ? record.applyToAssistantMessages+ : DEFAULT_RTK_CONFIG.applyToAssistantMessages,+ enabledFilters: Array.isArray(record.enabledFilters)+ ? record.enabledFilters.filter((filter): filter is string => typeof filter === "string")+ : DEFAULT_RTK_CONFIG.enabledFilters,+ disabledFilters: Array.isArray(record.disabledFilters)+ ? record.disabledFilters.filter((filter): filter is string => typeof filter === "string")+ : DEFAULT_RTK_CONFIG.disabledFilters,+ maxLinesPerResult: boundedInt(+ record.maxLinesPerResult,+ DEFAULT_RTK_CONFIG.maxLinesPerResult,+ 0,+ 100000+ ),+ maxCharsPerResult: boundedInt(+ record.maxCharsPerResult,+ DEFAULT_RTK_CONFIG.maxCharsPerResult,+ 0,+ 1000000+ ),+ deduplicateThreshold: boundedInt(+ record.deduplicateThreshold,+ DEFAULT_RTK_CONFIG.deduplicateThreshold,+ 2,+ 100+ ),+ customFiltersEnabled:+ typeof record.customFiltersEnabled === "boolean"+ ? record.customFiltersEnabled+ : DEFAULT_RTK_CONFIG.customFiltersEnabled,+ trustProjectFilters:+ typeof record.trustProjectFilters === "boolean"+ ? record.trustProjectFilters+ : DEFAULT_RTK_CONFIG.trustProjectFilters,+ rawOutputRetention:+ record.rawOutputRetention === "never" ||+ record.rawOutputRetention === "failures" ||+ record.rawOutputRetention === "always"+ ? record.rawOutputRetention+ : DEFAULT_RTK_CONFIG.rawOutputRetention,+ rawOutputMaxBytes: boundedInt(+ record.rawOutputMaxBytes,+ DEFAULT_RTK_CONFIG.rawOutputMaxBytes,+ 1024,+ 10_000_000+ ),+ };+}++function normalizeLanguageConfig(value: unknown): CompressionLanguageConfig {+ const record = toRecord(value);+ const defaultLanguage =+ typeof record.defaultLanguage === "string" && record.defaultLanguage.trim()+ ? record.defaultLanguage.trim()+ : DEFAULT_COMPRESSION_LANGUAGE_CONFIG.defaultLanguage;+ const enabledPacks = Array.isArray(record.enabledPacks)+ ? record.enabledPacks+ .filter((pack): pack is string => typeof pack === "string" && pack.trim().length > 0)+ .map((pack) => pack.trim())+ : DEFAULT_COMPRESSION_LANGUAGE_CONFIG.enabledPacks;+ return {+ ...DEFAULT_COMPRESSION_LANGUAGE_CONFIG,+ enabled:+ typeof record.enabled === "boolean"+ ? record.enabled+ : DEFAULT_COMPRESSION_LANGUAGE_CONFIG.enabled,+ defaultLanguage,+ autoDetect:+ typeof record.autoDetect === "boolean"+ ? record.autoDetect+ : DEFAULT_COMPRESSION_LANGUAGE_CONFIG.autoDetect,+ enabledPacks: [...new Set(enabledPacks.length > 0 ? enabledPacks : ["en"])],+ };+}++function normalizeStackedPipeline(value: unknown): CompressionPipelineStep[] {+ const source = Array.isArray(value) ? value : (DEFAULT_COMPRESSION_CONFIG.stackedPipeline ?? []);+ const pipeline: CompressionPipelineStep[] = [];+ for (const entry of source) {+ const record = toRecord(entry);+ const engine = record.engine;+ if (+ engine !== "lite" &&+ engine !== "caveman" &&+ engine !== "aggressive" &&+ engine !== "ultra" &&+ engine !== "rtk"+ ) {+ continue;+ }+ pipeline.push({+ engine,+ ...(typeof record.intensity === "string"+ ? { intensity: record.intensity as CompressionPipelineStep["intensity"] }+ : {}),+ ...(record.config && typeof record.config === "object"+ ? { config: record.config as Record<string, unknown> }+ : {}),+ });+ }+ return pipeline.length > 0 ? pipeline : (DEFAULT_COMPRESSION_CONFIG.stackedPipeline ?? []);+}+function boundedInt(value: unknown, fallback: number, min: number, max: number): number {if (typeof value !== "number" || !Number.isFinite(value)) return fallback;return Math.min(max, Math.max(min, Math.floor(value)));@@ -196,6 +353,10 @@ export async function getCompressionSettings(): Promise<CompressionConfig> {const config: CompressionConfig = {...DEFAULT_COMPRESSION_CONFIG,cavemanConfig: { ...DEFAULT_CAVEMAN_CONFIG },+ cavemanOutputMode: { ...DEFAULT_CAVEMAN_OUTPUT_MODE_CONFIG },+ rtkConfig: { ...DEFAULT_RTK_CONFIG },+ languageConfig: { ...DEFAULT_COMPRESSION_LANGUAGE_CONFIG },+ stackedPipeline: normalizeStackedPipeline(undefined),aggressive: normalizeAggressiveConfig(undefined),ultra: normalizeUltraConfig(undefined),};@@ -217,6 +378,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 +398,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> = {};@@ -243,9 +412,25 @@ export async function getCompressionSettings(): Promise<CompressionConfig> {config.comboOverrides = overrides;}break;+ case "compressionComboId":+ config.compressionComboId =+ typeof parsed === "string" && parsed.trim() ? parsed.trim() : null;+ break;+ case "stackedPipeline":+ config.stackedPipeline = normalizeStackedPipeline(parsed);+ break;case "cavemanConfig":config.cavemanConfig = normalizeCavemanConfig(parsed);break;+ case "cavemanOutputMode":+ config.cavemanOutputMode = normalizeCavemanOutputModeConfig(parsed);+ break;+ case "rtkConfig":+ config.rtkConfig = normalizeRtkConfig(parsed);+ break;+ case "languageConfig":+ config.languageConfig = normalizeLanguageConfig(parsed);+ break;case "aggressive":case "aggressiveConfig":config.aggressive = normalizeAggressiveConfig(parsed);@@ -300,3 +485,7 @@ export function getDefaultAggressiveConfig(): AggressiveConfig {export function getDefaultUltraConfig(): UltraConfig {return { ...DEFAULT_ULTRA_CONFIG };}++export function getDefaultRtkConfig(): RtkConfig {+ return { ...DEFAULT_RTK_CONFIG };+}diff --git a/src/lib/db/compressionAnalytics.ts b/src/lib/db/compressionAnalytics.tsindex f587a915ae..16a5b51415 100644--- a/src/lib/db/compressionAnalytics.ts+++ b/src/lib/db/compressionAnalytics.ts@@ -4,6 +4,8 @@ export interface CompressionAnalyticsRow {id?: number;timestamp: string;combo_id?: string | null;+ compression_combo_id?: string | null;+ engine?: string | null;provider?: string | null;mode: string;original_tokens: number;@@ -11,6 +13,19 @@ 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;+ rtk_raw_output_pointer?: string | null;+ rtk_raw_output_bytes?: number | null;}export interface CompressionAnalyticsSummary {@@ -19,32 +34,204 @@ export interface CompressionAnalyticsSummary {avgSavingsPct: number;avgDurationMs: number;byMode: Record<string, { count: number; tokensSaved: number; avgSavingsPct: number }>;+ byEngine: Record<string, { count: number; tokensSaved: number; avgSavingsPct: number }>;+ byCompressionCombo: Record<string, { count: number; tokensSaved: 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>;+ };+ mcpDescriptionCompression: {+ snapshots: number;+ estimatedTokensSaved: number;+ };+}++let columnsEnsuredForDb: unknown = null;++function ensureCompressionAnalyticsColumns(): void {+ const db = getDbInstance();+ if (columnsEnsuredForDb === db) return;+ 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");+ addColumn(+ "compression_combo_id",+ "ALTER TABLE compression_analytics ADD COLUMN compression_combo_id TEXT"+ );+ addColumn("engine", "ALTER TABLE compression_analytics ADD COLUMN engine TEXT");+ addColumn(+ "rtk_raw_output_pointer",+ "ALTER TABLE compression_analytics ADD COLUMN rtk_raw_output_pointer TEXT"+ );+ addColumn(+ "rtk_raw_output_bytes",+ "ALTER TABLE compression_analytics ADD COLUMN rtk_raw_output_bytes INTEGER"+ );+ columnsEnsuredForDb = db;}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, compression_combo_id, engine, 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, rtk_raw_output_pointer, rtk_raw_output_bytes+ )+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(row.timestamp,row.combo_id ?? null,+ row.compression_combo_id ?? null,+ row.engine ?? row.mode,row.provider ?? null,row.mode,row.original_tokens,row.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,+ row.rtk_raw_output_pointer ?? null,+ row.rtk_raw_output_bytes ?? 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") {@@ -88,6 +275,44 @@ export function getCompressionAnalyticsSummary(since?: string): CompressionAnalybyMode[r.mode] = { count: r.cnt, tokensSaved: r.saved, avgSavingsPct: Math.round(r.avgPct) };}+ const engineRows = db+ .prepare(+ `+ SELECT COALESCE(engine, mode) as engine, COUNT(*) as cnt, COALESCE(SUM(tokens_saved), 0) as saved,+ COALESCE(AVG(CASE WHEN original_tokens > 0 THEN CAST(tokens_saved AS REAL) / original_tokens * 100 ELSE 0 END), 0) as avgPct+ FROM compression_analytics ${whereClause}+ GROUP BY COALESCE(engine, mode)+ `+ )+ .all(...params) as Array<{ engine: string; cnt: number; saved: number; avgPct: number }>;++ const byEngine: Record<string, { count: number; tokensSaved: number; avgSavingsPct: number }> =+ {};+ for (const r of engineRows) {+ byEngine[r.engine] = {+ count: r.cnt,+ tokensSaved: r.saved,+ avgSavingsPct: Math.round(r.avgPct),+ };+ }++ const compressionComboRows = db+ .prepare(+ `+ SELECT compression_combo_id as compressionComboId, COUNT(*) as cnt,+ COALESCE(SUM(tokens_saved), 0) as saved+ FROM compression_analytics ${appendCondition(whereClause, "compression_combo_id IS NOT NULL")}+ GROUP BY compression_combo_id ORDER BY cnt DESC+ `+ )+ .all(...params) as Array<{ compressionComboId: string | null; cnt: number; saved: number }>;++ const byCompressionCombo: Record<string, { count: number; tokensSaved: number }> = {};+ for (const r of compressionComboRows) {+ const key = r.compressionComboId ?? "unknown";+ byCompressionCombo[key] = { count: r.cnt, tokensSaved: r.saved };+ }+const provRows = db.prepare(`@@ -136,13 +361,86 @@ 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;++ const mcpDescriptionRow = db+ .prepare(+ `+ SELECT COUNT(*) as cnt, COALESCE(SUM(mcp_description_tokens_saved), 0) as saved+ FROM compression_analytics ${appendCondition(whereClause, "mcp_description_tokens_saved > 0")}+ `+ )+ .get(...params) as { cnt: number; saved: number } | undefined;+return {totalRequests: scalar?.total ?? 0,totalTokensSaved: scalar?.totalSaved ?? 0,avgSavingsPct: Math.round(scalar?.avgPct ?? 0),avgDurationMs: Math.round(scalar?.avgDur ?? 0),byMode,+ byEngine,+ byCompressionCombo,byProvider,last24h,+ validationFallbacks: fallbackRow?.cnt ?? 0,+ realUsage,+ mcpDescriptionCompression: {+ snapshots: mcpDescriptionRow?.cnt ?? 0,+ estimatedTokensSaved: mcpDescriptionRow?.saved ?? 0,+ },};}diff --git a/src/lib/db/compressionCombos.ts b/src/lib/db/compressionCombos.tsnew file mode 100644index 0000000000..940cb3a908--- /dev/null+++ b/src/lib/db/compressionCombos.ts@@ -0,0 +1,420 @@+import { v4 as uuidv4 } from "uuid";+import type { CompressionPipelineStep } from "@omniroute/open-sse/services/compression/types.ts";++import { backupDbFile } from "./backup";+import { getDbInstance, rowToCamel } from "./core";++export interface CompressionCombo {+ id: string;+ name: string;+ description: string;+ pipeline: CompressionPipelineStep[];+ languagePacks: string[];+ outputMode: boolean;+ outputModeIntensity: string;+ isDefault: boolean;+ createdAt: string;+ updatedAt: string;+}++export interface CompressionComboAssignment {+ id: string;+ compressionComboId: string;+ routingComboId: string;+ createdAt: string;+}++type JsonRecord = Record<string, unknown>;++const DEFAULT_COMPRESSION_COMBO_ID = "default-caveman";+const DEFAULT_COMPRESSION_COMBO_NAME = "Standard Savings";+const DEFAULT_COMPRESSION_COMBO_DESCRIPTION = "Default RTK + Caveman compression pipeline";+const LEGACY_DEFAULT_COMPRESSION_COMBO_DESCRIPTION = "Default Caveman compression pipeline";++function defaultCompressionComboPipeline(): CompressionPipelineStep[] {+ return [+ { engine: "rtk", intensity: "standard" },+ { engine: "caveman", intensity: "full" },+ ];+}++function toRecord(value: unknown): JsonRecord {+ return value && typeof value === "object" && !Array.isArray(value) ? (value as JsonRecord) : {};+}++function parseJsonArray<T>(value: unknown, fallback: T[]): T[] {+ if (Array.isArray(value)) return value as T[];+ if (typeof value !== "string") return fallback;+ try {+ const parsed = JSON.parse(value);+ return Array.isArray(parsed) ? (parsed as T[]) : fallback;+ } catch {+ return fallback;+ }+}++function normalizePipeline(value: unknown): CompressionPipelineStep[] {+ return parseJsonArray<CompressionPipelineStep>(value, []).filter((step) => {+ return (+ step &&+ typeof step === "object" &&+ ["lite", "caveman", "aggressive", "ultra", "rtk"].includes(String(step.engine))+ );+ });+}++function normalizeLanguagePacks(value: unknown): string[] {+ const packs = parseJsonArray<string>(value, ["en"]).filter(+ (pack): pack is string => typeof pack === "string" && pack.trim().length > 0+ );+ return [...new Set(packs.length > 0 ? packs.map((pack) => pack.trim()) : ["en"])];+}++function isLegacySeededDefaultPipeline(pipeline: CompressionPipelineStep[]): boolean {+ if (pipeline.length !== 1) return false;+ const [step] = pipeline;+ return step.engine === "caveman" && (step.intensity === undefined || step.intensity === "full");+}++function upgradeLegacySeededDefaultCompressionCombo(): void {+ const db = getDbInstance();+ const row = db+ .prepare("SELECT name, description, pipeline FROM compression_combos WHERE id = ?")+ .get(DEFAULT_COMPRESSION_COMBO_ID) as+ | { name?: string; description?: string; pipeline?: string }+ | undefined;++ if (!row) return;++ const description = String(row.description ?? "");+ const isSeededMetadata =+ String(row.name ?? "") === DEFAULT_COMPRESSION_COMBO_NAME &&+ (description === LEGACY_DEFAULT_COMPRESSION_COMBO_DESCRIPTION ||+ description === DEFAULT_COMPRESSION_COMBO_DESCRIPTION);++ if (!isSeededMetadata || !isLegacySeededDefaultPipeline(normalizePipeline(row.pipeline))) return;++ db.prepare(+ `+ UPDATE compression_combos+ SET description = ?, pipeline = ?, updated_at = ?+ WHERE id = ?+ `+ ).run(+ DEFAULT_COMPRESSION_COMBO_DESCRIPTION,+ JSON.stringify(defaultCompressionComboPipeline()),+ new Date().toISOString(),+ DEFAULT_COMPRESSION_COMBO_ID+ );+}++function ensureCompressionComboTables(): void {+ const db = getDbInstance();+ db.exec(`+ CREATE TABLE IF NOT EXISTS compression_combos (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ description TEXT DEFAULT '',+ pipeline TEXT NOT NULL DEFAULT '[]',+ language_packs TEXT DEFAULT '["en"]',+ output_mode INTEGER DEFAULT 0,+ output_mode_intensity TEXT DEFAULT 'full',+ is_default INTEGER DEFAULT 0,+ created_at TEXT DEFAULT (datetime('now')),+ updated_at TEXT DEFAULT (datetime('now'))+ );++ CREATE TABLE IF NOT EXISTS compression_combo_assignments (+ id TEXT PRIMARY KEY,+ compression_combo_id TEXT NOT NULL REFERENCES compression_combos(id) ON DELETE CASCADE,+ routing_combo_id TEXT NOT NULL,+ created_at TEXT DEFAULT (datetime('now')),+ UNIQUE(routing_combo_id)+ );++ CREATE INDEX IF NOT EXISTS idx_compression_combos_default+ ON compression_combos(is_default);+ CREATE INDEX IF NOT EXISTS idx_compression_combo_assignments_combo+ ON compression_combo_assignments(compression_combo_id);+ CREATE INDEX IF NOT EXISTS idx_compression_combo_assignments_routing+ ON compression_combo_assignments(routing_combo_id);+ `);+ db.prepare(+ `+ INSERT OR IGNORE INTO compression_combos (+ id, name, description, pipeline, language_packs, output_mode, output_mode_intensity, is_default+ )+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)+ `+ ).run(+ DEFAULT_COMPRESSION_COMBO_ID,+ DEFAULT_COMPRESSION_COMBO_NAME,+ DEFAULT_COMPRESSION_COMBO_DESCRIPTION,+ JSON.stringify(defaultCompressionComboPipeline()),+ JSON.stringify(["en"]),+ 0,+ "full",+ 1+ );+ upgradeLegacySeededDefaultCompressionCombo();+}++function rowToCompressionCombo(row: unknown): CompressionCombo | null {+ if (!row) return null;+ const camel = rowToCamel(row as Record<string, unknown>) as JsonRecord;+ return {+ id: String(camel.id),+ name: String(camel.name ?? ""),+ description: String(camel.description ?? ""),+ pipeline: normalizePipeline(camel.pipeline),+ languagePacks: normalizeLanguagePacks(camel.languagePacks),+ outputMode: Boolean(camel.outputMode),+ outputModeIntensity: String(camel.outputModeIntensity ?? "full"),+ isDefault: Boolean(camel.isDefault),+ createdAt: String(camel.createdAt ?? ""),+ updatedAt: String(camel.updatedAt ?? ""),+ };+}++function rowToAssignment(row: unknown): CompressionComboAssignment | null {+ if (!row) return null;+ const camel = rowToCamel(row as Record<string, unknown>) as JsonRecord;+ return {+ id: String(camel.id),+ compressionComboId: String(camel.compressionComboId),+ routingComboId: String(camel.routingComboId),+ createdAt: String(camel.createdAt ?? ""),+ };+}++function buildComboPayload(data: Partial<CompressionCombo>, existing?: CompressionCombo) {+ const now = new Date().toISOString();+ return {+ id: existing?.id ?? data.id ?? uuidv4(),+ name: data.name?.trim() || existing?.name || "Compression Combo",+ description: data.description ?? existing?.description ?? "",+ pipeline:+ data.pipeline && data.pipeline.length > 0+ ? data.pipeline+ : existing?.pipeline && existing.pipeline.length > 0+ ? existing.pipeline+ : defaultCompressionComboPipeline(),+ languagePacks:+ data.languagePacks && data.languagePacks.length > 0+ ? data.languagePacks+ : existing?.languagePacks && existing.languagePacks.length > 0+ ? existing.languagePacks+ : ["en"],+ outputMode: data.outputMode ?? existing?.outputMode ?? false,+ outputModeIntensity: data.outputModeIntensity ?? existing?.outputModeIntensity ?? "full",+ isDefault: data.isDefault ?? existing?.isDefault ?? false,+ createdAt: existing?.createdAt ?? now,+ updatedAt: now,+ };+}++export function listCompressionCombos(): CompressionCombo[] {+ ensureCompressionComboTables();+ const db = getDbInstance();+ return db+ .prepare("SELECT * FROM compression_combos ORDER BY is_default DESC, name COLLATE NOCASE ASC")+ .all()+ .map(rowToCompressionCombo)+ .filter((combo): combo is CompressionCombo => combo !== null);+}++export function getCompressionCombo(id: string): CompressionCombo | null {+ ensureCompressionComboTables();+ const row = getDbInstance().prepare("SELECT * FROM compression_combos WHERE id = ?").get(id);+ return rowToCompressionCombo(row);+}++export function getDefaultCompressionCombo(): CompressionCombo | null {+ ensureCompressionComboTables();+ const row = getDbInstance()+ .prepare(+ "SELECT * FROM compression_combos WHERE is_default = 1 ORDER BY updated_at DESC LIMIT 1"+ )+ .get();+ return rowToCompressionCombo(row);+}++export function createCompressionCombo(data: Partial<CompressionCombo>): CompressionCombo {+ ensureCompressionComboTables();+ const db = getDbInstance();+ const combo = buildComboPayload(data);+ const tx = db.transaction(() => {+ if (combo.isDefault) db.prepare("UPDATE compression_combos SET is_default = 0").run();+ db.prepare(+ `+ INSERT INTO compression_combos (+ id, name, description, pipeline, language_packs, output_mode, output_mode_intensity,+ is_default, created_at, updated_at+ )+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ `+ ).run(+ combo.id,+ combo.name,+ combo.description,+ JSON.stringify(combo.pipeline),+ JSON.stringify(combo.languagePacks),+ combo.outputMode ? 1 : 0,+ combo.outputModeIntensity,+ combo.isDefault ? 1 : 0,+ combo.createdAt,+ combo.updatedAt+ );+ });+ tx();+ backupDbFile("pre-write");+ return getCompressionCombo(combo.id) as CompressionCombo;+}++export function updateCompressionCombo(+ id: string,+ data: Partial<CompressionCombo>+): CompressionCombo | null {+ ensureCompressionComboTables();+ const existing = getCompressionCombo(id);+ if (!existing) return null;+ const combo = buildComboPayload(data, existing);+ const db = getDbInstance();+ const tx = db.transaction(() => {+ if (combo.isDefault) db.prepare("UPDATE compression_combos SET is_default = 0").run();+ db.prepare(+ `+ UPDATE compression_combos+ SET name = ?, description = ?, pipeline = ?, language_packs = ?, output_mode = ?,+ output_mode_intensity = ?, is_default = ?, updated_at = ?+ WHERE id = ?+ `+ ).run(+ combo.name,+ combo.description,+ JSON.stringify(combo.pipeline),+ JSON.stringify(combo.languagePacks),+ combo.outputMode ? 1 : 0,+ combo.outputModeIntensity,+ combo.isDefault ? 1 : 0,+ combo.updatedAt,+ id+ );+ });+ tx();+ backupDbFile("pre-write");+ return getCompressionCombo(id);+}++export function deleteCompressionCombo(id: string): boolean {+ ensureCompressionComboTables();+ const existing = getCompressionCombo(id);+ if (!existing || existing.isDefault) return false;+ const result = getDbInstance().prepare("DELETE FROM compression_combos WHERE id = ?").run(id);+ if (result.changes > 0) backupDbFile("pre-write");+ return result.changes > 0;+}++export function setDefaultCompressionCombo(id: string): boolean {+ ensureCompressionComboTables();+ if (!getCompressionCombo(id)) return false;+ const db = getDbInstance();+ const now = new Date().toISOString();+ db.transaction(() => {+ db.prepare("UPDATE compression_combos SET is_default = 0").run();+ db.prepare("UPDATE compression_combos SET is_default = 1, updated_at = ? WHERE id = ?").run(+ now,+ id+ );+ })();+ backupDbFile("pre-write");+ return true;+}++export function getAssignmentsForCompressionCombo(id: string): CompressionComboAssignment[] {+ ensureCompressionComboTables();+ return getDbInstance()+ .prepare(+ "SELECT * FROM compression_combo_assignments WHERE compression_combo_id = ? ORDER BY routing_combo_id"+ )+ .all(id)+ .map(rowToAssignment)+ .filter((assignment): assignment is CompressionComboAssignment => assignment !== null);+}++export function getCompressionComboForRoutingCombo(+ routingComboId: string+): CompressionCombo | null {+ ensureCompressionComboTables();+ const row = getDbInstance()+ .prepare(+ `+ SELECT c.*+ FROM compression_combos c+ JOIN compression_combo_assignments a ON a.compression_combo_id = c.id+ WHERE a.routing_combo_id = ?+ LIMIT 1+ `+ )+ .get(routingComboId);+ return rowToCompressionCombo(row);+}++export function assignRoutingCombo(compressionComboId: string, routingComboId: string): boolean {+ ensureCompressionComboTables();+ if (!getCompressionCombo(compressionComboId) || !routingComboId.trim()) return false;+ getDbInstance()+ .prepare(+ `+ INSERT OR REPLACE INTO compression_combo_assignments (+ id, compression_combo_id, routing_combo_id, created_at+ )+ VALUES (?, ?, ?, ?)+ `+ )+ .run(uuidv4(), compressionComboId, routingComboId.trim(), new Date().toISOString());+ backupDbFile("pre-write");+ return true;+}++export function unassignRoutingCombo(compressionComboId: string, routingComboId: string): boolean {+ ensureCompressionComboTables();+ const result = getDbInstance()+ .prepare(+ "DELETE FROM compression_combo_assignments WHERE compression_combo_id = ? AND routing_combo_id = ?"+ )+ .run(compressionComboId, routingComboId);+ if (result.changes > 0) backupDbFile("pre-write");+ return result.changes > 0;+}++export function updateAssignments(compressionComboId: string, routingComboIds: string[]): boolean {+ ensureCompressionComboTables();+ if (!getCompressionCombo(compressionComboId)) return false;+ const cleanedIds = [...new Set(routingComboIds.map((id) => id.trim()).filter(Boolean))];+ const db = getDbInstance();+ db.transaction(() => {+ db.prepare("DELETE FROM compression_combo_assignments WHERE compression_combo_id = ?").run(+ compressionComboId+ );+ if (cleanedIds.length > 0) {+ const deleteExisting = db.prepare(+ "DELETE FROM compression_combo_assignments WHERE routing_combo_id = ?"+ );+ const insert = db.prepare(+ `+ INSERT INTO compression_combo_assignments (+ id, compression_combo_id, routing_combo_id, created_at+ )+ VALUES (?, ?, ?, ?)+ `+ );+ for (const routingComboId of cleanedIds) {+ deleteExisting.run(routingComboId);+ insert.run(uuidv4(), compressionComboId, routingComboId, new Date().toISOString());+ }+ }+ })();+ backupDbFile("pre-write");+ return true;+}diff --git a/src/lib/db/core.ts b/src/lib/db/core.tsindex 80d5a030b5..6d7ae9553e 100644--- a/src/lib/db/core.ts+++ b/src/lib/db/core.ts@@ -232,6 +232,7 @@ const SCHEMA_SQL = `tokens_cache_read INTEGER DEFAULT NULL,tokens_cache_creation INTEGER DEFAULT NULL,tokens_reasoning INTEGER DEFAULT NULL,+ tokens_compressed INTEGER DEFAULT NULL,cache_source TEXT DEFAULT "upstream",request_type TEXT,source_format TEXT,@@ -787,6 +788,7 @@ function offloadLegacyCallLogDetails(db: SqliteDatabase) {tokens_cache_read: number | null;tokens_cache_creation: number | null;tokens_reasoning: number | null;+ tokens_compressed: number | null;request_type: string | null;source_format: string | null;target_format: string | null;@@ -838,7 +840,7 @@ function offloadLegacyCallLogDetails(db: SqliteDatabase) {const tx = db.transaction(() => {for (const row of pendingRows) {const artifact: CallLogArtifact = {- schemaVersion: 4,+ schemaVersion: 5,summary: {id: row.id,timestamp: row.timestamp || new Date().toISOString(),@@ -857,6 +859,7 @@ function offloadLegacyCallLogDetails(db: SqliteDatabase) {cacheRead: row.tokens_cache_read ?? null,cacheWrite: row.tokens_cache_creation ?? null,reasoning: row.tokens_reasoning ?? null,+ compressed: row.tokens_compressed ?? null,},requestType: row.request_type || null,sourceFormat: row.source_format || null,diff --git a/src/lib/db/jsonMigration.ts b/src/lib/db/jsonMigration.tsindex b3128cdd9c..5e6e237485 100644--- a/src/lib/db/jsonMigration.ts+++ b/src/lib/db/jsonMigration.ts@@ -12,6 +12,7 @@*/import type Database from "better-sqlite3";+import { normalizeRoutingStrategy } from "@/shared/constants/routingStrategies";type SqliteDatabase = InstanceType<typeof Database>;@@ -172,8 +173,19 @@ export function runJsonMigration(// 5. Combosfor (const [index, combo] of (data.combos ?? []).entries()) {- const normalizedCombo = {+ const config =+ combo.config && typeof combo.config === "object" && !Array.isArray(combo.config)+ ? { ...(combo.config as Record<string, unknown>) }+ : combo.config;+ if (config && typeof config === "object" && !Array.isArray(config) && "strategy" in config) {+ (config as Record<string, unknown>).strategy = normalizeRoutingStrategy(+ (config as Record<string, unknown>).strategy+ );+ }+ const normalizedCombo: Record<string, unknown> = {...combo,+ strategy: normalizeRoutingStrategy(combo.strategy),+ config,sortOrder: typeof combo.sortOrder === "number" ? combo.sortOrder : index + 1,};insertCombo.run({diff --git a/src/lib/db/migrationRunner.ts b/src/lib/db/migrationRunner.tsindex 338d7aa9ec..9b9fb5689e 100644--- a/src/lib/db/migrationRunner.ts+++ b/src/lib/db/migrationRunner.ts@@ -266,6 +266,24 @@ 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")+ );+ case "042":+ return (+ hasTable(db, "compression_combos") &&+ hasTable(db, "compression_combo_assignments") &&+ hasColumn(db, "compression_analytics", "compression_combo_id") &&+ hasColumn(db, "compression_analytics", "engine")+ );+ case "045":+ return hasColumn(db, "call_logs", "tokens_compressed");default:return false;}@@ -299,6 +317,103 @@ 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 applyCompressionCombosMigration(db: Database.Database, migrationPath: string): void {+ const sql = fs.readFileSync(migrationPath, "utf-8");+ db.exec(sql);+ ensureColumn(+ db,+ "compression_analytics",+ "compression_combo_id",+ "ALTER TABLE compression_analytics ADD COLUMN compression_combo_id TEXT"+ );+ ensureColumn(+ db,+ "compression_analytics",+ "engine",+ "ALTER TABLE compression_analytics ADD COLUMN engine TEXT"+ );+ db.exec(`+ CREATE INDEX IF NOT EXISTS idx_compression_analytics_combo_engine+ ON compression_analytics(compression_combo_id, engine);+ `);+}+function inferPhysicalSchemaBaseline(db: Database.Database): {version: string;description: string;@@ -641,6 +756,10 @@ export function runMigrations(db: Database.Database, options?: { isNewDb?: boole);} else if (migration.version === "032") {applyApiKeyLifecycleMigration(db);+ } else if (migration.version === "041") {+ applyCompressionReceiptsMigration(db);+ } else if (migration.version === "042") {+ applyCompressionCombosMigration(db, migration.path);} else {const sql = fs.readFileSync(migration.path, "utf-8");db.exec(sql);@@ -657,8 +776,22 @@ export function runMigrations(db: Database.Database, options?: { isNewDb?: booleconsole.log(`[Migration] Applied: ${migration.version}_${migration.name}`);} catch (err: unknown) {const message = err instanceof Error ? err.message : String(err);- console.error(`[Migration] FAILED: ${migration.version}_${migration.name} — ${message}`);- throw err; // Re-throw to prevent DB from starting in inconsistent state+ // "duplicate column name" means the column already exists — end state achieved, mark applied.+ if (message.includes("duplicate column name")) {+ const applyMarkerOnly = db.transaction(() => {+ db.prepare(+ "INSERT OR IGNORE INTO _omniroute_migrations (version, name) VALUES (?, ?)"+ ).run(migration.version, migration.name);+ });+ applyMarkerOnly();+ count++;+ console.log(+ `[Migration] Applied (column pre-exists): ${migration.version}_${migration.name}`+ );+ } else {+ console.error(`[Migration] FAILED: ${migration.version}_${migration.name} — ${message}`);+ throw err; // Re-throw to prevent DB from starting in inconsistent state+ }}}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/src/lib/db/migrations/042_compression_combos.sql b/src/lib/db/migrations/042_compression_combos.sqlnew file mode 100644index 0000000000..1358124c0b--- /dev/null+++ b/src/lib/db/migrations/042_compression_combos.sql@@ -0,0 +1,43 @@+-- 042: Compression combos and routing-combo assignments.++CREATE TABLE IF NOT EXISTS compression_combos (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ description TEXT DEFAULT '',+ pipeline TEXT NOT NULL DEFAULT '[]',+ language_packs TEXT DEFAULT '["en"]',+ output_mode INTEGER DEFAULT 0,+ output_mode_intensity TEXT DEFAULT 'full',+ is_default INTEGER DEFAULT 0,+ created_at TEXT DEFAULT (datetime('now')),+ updated_at TEXT DEFAULT (datetime('now'))+);++CREATE TABLE IF NOT EXISTS compression_combo_assignments (+ id TEXT PRIMARY KEY,+ compression_combo_id TEXT NOT NULL REFERENCES compression_combos(id) ON DELETE CASCADE,+ routing_combo_id TEXT NOT NULL,+ created_at TEXT DEFAULT (datetime('now')),+ UNIQUE(routing_combo_id)+);++CREATE INDEX IF NOT EXISTS idx_compression_combos_default+ ON compression_combos(is_default);+CREATE INDEX IF NOT EXISTS idx_compression_combo_assignments_combo+ ON compression_combo_assignments(compression_combo_id);+CREATE INDEX IF NOT EXISTS idx_compression_combo_assignments_routing+ ON compression_combo_assignments(routing_combo_id);++INSERT OR IGNORE INTO compression_combos (+ id, name, description, pipeline, language_packs, output_mode, output_mode_intensity, is_default+)+VALUES (+ 'default-caveman',+ 'Standard Savings',+ 'Default RTK + Caveman compression pipeline',+ '[{"engine":"rtk","intensity":"standard"},{"engine":"caveman","intensity":"full"}]',+ '["en"]',+ 0,+ 'full',+ 1+);diff --git a/src/lib/db/migrations/043_default_compression_combo_pipeline.sql b/src/lib/db/migrations/043_default_compression_combo_pipeline.sqlnew file mode 100644index 0000000000..f0c60cda98--- /dev/null+++ b/src/lib/db/migrations/043_default_compression_combo_pipeline.sql@@ -0,0 +1,12 @@+-- 043: Upgrade the seeded default compression combo from Caveman-only to RTK + Caveman.++UPDATE compression_combos+SET+ description = 'Default RTK + Caveman compression pipeline',+ pipeline = '[{"engine":"rtk","intensity":"standard"},{"engine":"caveman","intensity":"full"}]',+ updated_at = datetime('now')+WHERE+ id = 'default-caveman'+ AND name = 'Standard Savings'+ AND description = 'Default Caveman compression pipeline'+ AND pipeline = '[{"engine":"caveman","intensity":"full"}]';diff --git a/src/lib/db/migrations/044_usage_history_api_key_backfill.sql b/src/lib/db/migrations/044_usage_history_api_key_backfill.sqlnew file mode 100644index 0000000000..870ea285bf--- /dev/null+++ b/src/lib/db/migrations/044_usage_history_api_key_backfill.sql@@ -0,0 +1,27 @@+-- Usage History API Key Backfill+-- Backfills missing API key names and IDs in usage_history using the connection_id++UPDATE usage_history+SET+ api_key_name = (+ SELECT api_key_name+ FROM usage_history AS uh2+ WHERE uh2.connection_id = usage_history.connection_id+ AND uh2.api_key_name IS NOT NULL+ AND uh2.api_key_name != ''+ GROUP BY uh2.api_key_name+ ORDER BY COUNT(*) DESC+ LIMIT 1+ ),+ api_key_id = (+ SELECT api_key_id+ FROM usage_history AS uh2+ WHERE uh2.connection_id = usage_history.connection_id+ AND uh2.api_key_id IS NOT NULL+ AND uh2.api_key_id != ''+ GROUP BY uh2.api_key_id+ ORDER BY COUNT(*) DESC+ LIMIT 1+ )+WHERE (api_key_name IS NULL OR api_key_name = '')+ AND connection_id IS NOT NULL;diff --git a/src/lib/db/migrations/045_compression_tokens.sql b/src/lib/db/migrations/045_compression_tokens.sqlnew file mode 100644index 0000000000..e45cb59f28--- /dev/null+++ b/src/lib/db/migrations/045_compression_tokens.sql@@ -0,0 +1,4 @@+-- Migration 045: Add tokens_compressed to call_logs+-- Tracks how many tokens were removed by proactive context compression.+-- NULL = compression not applied. N > 0 = tokens eliminated.+ALTER TABLE call_logs ADD COLUMN tokens_compressed INTEGER DEFAULT NULL;diff --git a/src/lib/db/models.ts b/src/lib/db/models.tsindex a3b2fc7f2f..f749a4ffc8 100644--- a/src/lib/db/models.ts+++ b/src/lib/db/models.ts@@ -351,6 +351,7 @@ export async function addCustomModel(| "chat-completions"| "responses"| "embeddings"+ | "rerank"| "audio-transcriptions"| "audio-speech"| "images-generations" = "chat-completions",@@ -525,6 +526,7 @@ export interface SyncedAvailableModel {id: string;name: string;source: "imported";+ apiFormat?: string;supportedEndpoints?: string[];inputTokenLimit?: number;outputTokenLimit?: number;@@ -561,6 +563,9 @@ function normalizeSyncedAvailableModel(model: unknown): SyncedAvailableModel | nid,name,source: "imported",+ ...(toNonEmptyString(record.apiFormat)+ ? { apiFormat: toNonEmptyString(record.apiFormat)! }+ : {}),...(supportedEndpoints && supportedEndpoints.length > 0 ? { supportedEndpoints } : {}),...(typeof record.inputTokenLimit === "number"? { inputTokenLimit: record.inputTokenLimit }diff --git a/src/lib/localDb.ts b/src/lib/localDb.tsindex df440bb2a2..214810e8c1 100755--- a/src/lib/localDb.ts+++ b/src/lib/localDb.ts@@ -80,6 +80,7 @@ export {} from "./db/combos";export * from "./db/compressionCacheStats";+export * from "./db/compressionCombos";export {// API Keys@@ -340,9 +341,6 @@ export {setReasoningCache,getReasoningCache,deleteReasoningCache,- cleanupExpiredReasoning,- getReasoningCacheStats,- getReasoningCacheEntries,clearAllReasoningCache,} from "./db/reasoningCache";diff --git a/src/lib/providerModels/managedModelImport.ts b/src/lib/providerModels/managedModelImport.tsindex 227d96f9ae..30229794d1 100644--- a/src/lib/providerModels/managedModelImport.ts+++ b/src/lib/providerModels/managedModelImport.ts@@ -21,7 +21,7 @@ export type ManagedImportedModel = {id: string;name: string;source: "imported";- apiFormat: "chat-completions";+ apiFormat: string;supportedEndpoints?: string[];inputTokenLimit?: number;outputTokenLimit?: number;@@ -48,7 +48,7 @@ function normalizeImportedModels(fetchedModels: unknown): ManagedImportedModel[]id: model.id,name: model.name || model.id,source: "imported",- apiFormat: "chat-completions",+ apiFormat: toNonEmptyString(model.apiFormat) || "chat-completions",...(Array.isArray(model.supportedEndpoints) && model.supportedEndpoints.length > 0? { supportedEndpoints: model.supportedEndpoints }: {}),diff --git a/src/lib/providerModels/modelDiscovery.ts b/src/lib/providerModels/modelDiscovery.tsindex 89235b566a..5ab8a9fb9f 100644--- a/src/lib/providerModels/modelDiscovery.ts+++ b/src/lib/providerModels/modelDiscovery.ts@@ -49,6 +49,9 @@ export function normalizeDiscoveredModels(models: unknown): SyncedAvailableModelid,name,source: "imported",+ ...(toNonEmptyString(record.apiFormat)+ ? { apiFormat: toNonEmptyString(record.apiFormat)! }+ : {}),...(supportedEndpoints && supportedEndpoints.length > 0 ? { supportedEndpoints } : {}),...(typeof record.inputTokenLimit === "number"? { inputTokenLimit: record.inputTokenLimit }diff --git a/src/lib/providers/validation.ts b/src/lib/providers/validation.tsindex 04487c55f9..4e7c48c210 100644--- a/src/lib/providers/validation.ts+++ b/src/lib/providers/validation.ts@@ -2872,7 +2872,12 @@ async function validateMuseSparkWebProvider({ apiKey, providerSpecificData = {}export async function validateProviderApiKey({ provider, apiKey, providerSpecificData = {} }: any) {const requiresApiKey =- provider !== "searxng-search" && provider !== "petals" && !isSelfHostedChatProvider(provider);+ provider !== "searxng-search" &&+ provider !== "petals" &&+ !isSelfHostedChatProvider(provider) &&+ !isOpenAICompatibleProvider(provider) &&+ !isAnthropicCompatibleProvider(provider);+if (!provider || (requiresApiKey && !apiKey)) {return { valid: false, error: "Provider and API key required", unsupported: false };}diff --git a/src/lib/usage/callLogArtifacts.ts b/src/lib/usage/callLogArtifacts.tsindex 6ad1f26dcb..41d03e1648 100644--- a/src/lib/usage/callLogArtifacts.ts+++ b/src/lib/usage/callLogArtifacts.ts@@ -19,7 +19,7 @@ const STREAM_CHUNKS_OMITTED_FOR_SIZE_LIMIT =export type CallLogDetailState = "none" | "ready" | "missing" | "corrupt" | "legacy-inline";export type CallLogArtifact = {- schemaVersion: 4;+ schemaVersion: 5;summary: {id: string;timestamp: string;@@ -38,6 +38,7 @@ export type CallLogArtifact = {cacheRead: number | null;cacheWrite: number | null;reasoning: number | null;+ compressed: number | null;};requestType: string | null;sourceFormat: string | null;diff --git a/src/lib/usage/callLogs.ts b/src/lib/usage/callLogs.tsindex 30977f21fa..ea231dcaf3 100644--- a/src/lib/usage/callLogs.ts+++ b/src/lib/usage/callLogs.ts@@ -53,6 +53,7 @@ type CallLogSummaryRow = {tokens_cache_read: number | null;tokens_cache_creation: number | null;tokens_reasoning: number | null;+ tokens_compressed: number | null;cache_source: string | null;request_type: string | null;source_format: string | null;@@ -286,6 +287,7 @@ function buildArtifact(tokensCacheRead: number | null;tokensCacheCreation: number | null;tokensReasoning: number | null;+ tokensCompressed: number | null;requestType: string | null;sourceFormat: string | null;targetFormat: string | null;@@ -301,7 +303,7 @@ function buildArtifact(pipelinePayloads: RequestPipelinePayloads | null): CallLogArtifact {return {- schemaVersion: 4,+ schemaVersion: 5,summary: {id: logEntry.id,timestamp: logEntry.timestamp,@@ -320,6 +322,7 @@ function buildArtifact(cacheRead: logEntry.tokensCacheRead,cacheWrite: logEntry.tokensCacheCreation,reasoning: logEntry.tokensReasoning,+ compressed: logEntry.tokensCompressed,},requestType: logEntry.requestType,sourceFormat: logEntry.sourceFormat,@@ -546,6 +549,7 @@ function mapSummaryRow(row: CallLogSummaryRow) {cacheRead: row.tokens_cache_read != null ? toNumber(row.tokens_cache_read) : null,cacheWrite: row.tokens_cache_creation != null ? toNumber(row.tokens_cache_creation) : null,reasoning: row.tokens_reasoning != null ? toNumber(row.tokens_reasoning) : null,+ compressed: row.tokens_compressed != null ? toNumber(row.tokens_compressed) : null,},cacheSource: row.cache_source || "upstream",requestType: row.request_type,@@ -635,6 +639,7 @@ export async function saveCallLog(entry: any) {tokensCacheRead: getPromptCacheReadTokensOrNull(entry.tokens),tokensCacheCreation: getPromptCacheCreationTokensOrNull(entry.tokens),tokensReasoning: getReasoningTokensOrNull(entry.tokens),+ tokensCompressed: entry.tokensCompressed != null ? toNumber(entry.tokensCompressed) : null,cacheSource: entry.cacheSource === "semantic" ? "semantic" : "upstream",requestType: entry.requestType || null,sourceFormat: entry.sourceFormat || null,@@ -687,7 +692,7 @@ export async function saveCallLog(entry: any) {INSERT INTO call_logs (id, timestamp, method, path, status, model, requested_model, provider,account, connection_id, duration, tokens_in, tokens_out,- tokens_cache_read, tokens_cache_creation, tokens_reasoning,+ tokens_cache_read, tokens_cache_creation, tokens_reasoning, tokens_compressed,cache_source, request_type, source_format, target_format, api_key_id, api_key_name,combo_name, combo_step_id, combo_execution_key, error_summary, detail_state,artifact_relpath, artifact_size_bytes, artifact_sha256,@@ -696,7 +701,7 @@ export async function saveCallLog(entry: any) {VALUES (@id, @timestamp, @method, @path, @status, @model, @requestedModel, @provider,@account, @connectionId, @duration, @tokensIn, @tokensOut,- @tokensCacheRead, @tokensCacheCreation, @tokensReasoning,+ @tokensCacheRead, @tokensCacheCreation, @tokensReasoning, @tokensCompressed,@cacheSource, @requestType, @sourceFormat, @targetFormat, @apiKeyId, @apiKeyName,@comboName, @comboStepId, @comboExecutionKey, @errorSummary, @detailState,@artifactRelPath, @artifactSizeBytes, @artifactSha256,diff --git a/src/lib/usage/migrations.ts b/src/lib/usage/migrations.tsindex 38848e46d5..d44febaf95 100644--- a/src/lib/usage/migrations.ts+++ b/src/lib/usage/migrations.ts@@ -358,7 +358,7 @@ export function migrateUsageJsonToSqlite() {if (detailExpected) {const artifact: CallLogArtifact = {- schemaVersion: 4,+ schemaVersion: 5,summary: {id,timestamp,diff --git a/src/shared/components/RequestLoggerDetail.tsx b/src/shared/components/RequestLoggerDetail.tsxindex 27da5d8b1b..d268a3ec1e 100644--- a/src/shared/components/RequestLoggerDetail.tsx+++ b/src/shared/components/RequestLoggerDetail.tsx@@ -158,6 +158,7 @@ export default function RequestLoggerDetail({cacheRead: detail?.tokens?.cacheRead ?? log.tokens?.cacheRead,cacheWrite: detail?.tokens?.cacheWrite ?? log.tokens?.cacheWrite,reasoning: detail?.tokens?.reasoning ?? log.tokens?.reasoning,+ compressed: detail?.tokens?.compressed ?? log.tokens?.compressed,};const formatTokenValue = (value) => (value != null ? value.toLocaleString() : "N/A");@@ -248,6 +249,15 @@ export default function RequestLoggerDetail({<span className="px-2 py-0.5 rounded bg-amber-500/20 text-amber-700 dark:text-amber-400 text-xs font-bold">Cache Write: {formatTokenValue(tokenStats.cacheWrite)}</span>+ {tokenStats.compressed != null && tokenStats.compressed > 0 && (() => {+ const fromTokens = tokenStats.totalIn + tokenStats.compressed;+ const pct = Math.round((tokenStats.compressed / fromTokens) * 100);+ return (+ <span className="px-2 py-0.5 rounded bg-purple-500/20 text-purple-700 dark:text-purple-300 text-xs font-bold">+ Compressed: {fromTokens.toLocaleString()} → {tokenStats.totalIn.toLocaleString()} (-{pct}%)+ </span>+ );+ })()}</div></div><div>diff --git a/src/shared/components/RequestLoggerV2.tsx b/src/shared/components/RequestLoggerV2.tsxindex d7032bf15e..4631760a38 100644--- a/src/shared/components/RequestLoggerV2.tsx+++ b/src/shared/components/RequestLoggerV2.tsx@@ -807,6 +807,17 @@ export default function RequestLoggerV2() {<span className="text-emerald-700 dark:text-emerald-400">{log.tokens?.out?.toLocaleString() || 0}</span>+ {log.tokens?.compressed != null && log.tokens.compressed > 0 && (+ <>+ <span className="mx-1 text-border">|</span>+ <span+ className="text-purple-500 dark:text-purple-400 font-semibold"+ title={`${log.tokens.compressed.toLocaleString()} tokens compressed`}+ >+ ↓{log.tokens.compressed.toLocaleString()}+ </span>+ </>+ )}</td>)}{visibleColumns.tps && (diff --git a/src/shared/components/analytics/charts.tsx b/src/shared/components/analytics/charts.tsxindex a7649305fb..809e5ba956 100644--- a/src/shared/components/analytics/charts.tsx+++ b/src/shared/components/analytics/charts.tsx@@ -267,10 +267,7 @@ export function ActivityHeatmap({ activityMap }) {</span></div>- <div- ref={scrollRef}- className="overflow-x-auto"- >+ <div ref={scrollRef} className="overflow-x-auto"><div className="w-max"><div className="flex gap-[3px] mb-1 ml-6" style={{ fontSize: "10px" }}>{monthLabels.map((m, i) => (@@ -300,19 +297,19 @@ export function ActivityHeatmap({ activityMap }) {</div>{weeks.map((week, wi) => (- <div key={wi} className="flex flex-col gap-[3px]">- {week.map((day, di) => (- <div- key={di}- title={day ? `${day.date}: ${fmtFull(day.value)} tokens` : ""}- className={`w-[10px] h-[10px] rounded-[2px] ${day ? getCellColor(day.value) : "bg-transparent"}`}- />- ))}- </div>- ))}+ <div key={wi} className="flex flex-col gap-[3px]">+ {week.map((day, di) => (+ <div+ key={di}+ title={day ? `${day.date}: ${fmtFull(day.value)} tokens` : ""}+ className={`w-[10px] h-[10px] rounded-[2px] ${day ? getCellColor(day.value) : "bg-transparent"}`}+ />+ ))}+ </div>+ ))}+ </div></div></div>- </div><div className="flex items-center gap-1 mt-2 ml-6 text-[10px] text-text-muted"><span>Less</span>@@ -364,7 +361,7 @@ export function DailyTrendChart({ dailyTrend }) {><XAxisdataKey="date"- tick={{ fontSize: 9, fill: "var(--text-muted)" }}+ tick={{ fontSize: 9, fill: "var(--color-text-muted)" }}axisLine={false}tickLine={false}interval={Math.max(Math.floor(chartData.length / 6), 0)}@@ -784,7 +781,7 @@ export function WeeklyPattern({ weeklyPattern }) {<BarChart data={chartData} margin={{ top: 0, right: 0, left: 0, bottom: 0 }}><XAxisdataKey="day"- tick={{ fontSize: 9, fill: "var(--text-muted)" }}+ tick={{ fontSize: 9, fill: "var(--color-text-muted)" }}axisLine={false}tickLine={false}/>@@ -794,7 +791,7 @@ export function WeeklyPattern({ weeklyPattern }) {/><BardataKey="Tokens"- fill="var(--text-muted)"+ fill="var(--color-text-muted)"opacity={0.3}radius={[3, 3, 0, 0]}animationDuration={400}@@ -847,7 +844,7 @@ export function MostActiveDay7d({ activityMap }) {<Card className="p-4 flex flex-col justify-center" style={{ flex: 1, minHeight: 0 }}><h3className="text-xs font-semibold uppercase tracking-wider mb-2"- style={{ color: "var(--text-muted)" }}+ style={{ color: "var(--color-text-muted)" }}>Most Active Day</h3>@@ -856,12 +853,12 @@ export function MostActiveDay7d({ activityMap }) {<span className="text-xl font-bold capitalize" style={{ lineHeight: 1.2 }}>{data.weekday}</span>- <span className="text-xs mt-1" style={{ color: "var(--text-muted)" }}>+ <span className="text-xs mt-1" style={{ color: "var(--color-text-muted)" }}>{data.label} · {fmt(data.tokens)} tokens</span></>) : (- <span className="text-xs" style={{ color: "var(--text-muted)" }}>+ <span className="text-xs" style={{ color: "var(--color-text-muted)" }}>No data in the last 7 days</span>)}@@ -913,7 +910,7 @@ export function WeeklySquares7d({ activityMap }) {<Card className="p-4 flex flex-col justify-center" style={{ flex: 1, minHeight: 0 }}><h3className="text-xs font-semibold uppercase tracking-wider mb-3"- style={{ color: "var(--text-muted)" }}+ style={{ color: "var(--color-text-muted)" }}>Weekly</h3>@@ -938,7 +935,7 @@ export function WeeklySquares7d({ activityMap }) {style={{fontSize: 9,fontWeight: 600,- color: "var(--text-muted)",+ color: "var(--color-text-muted)",letterSpacing: "0.03em",}}>@@ -1238,13 +1235,13 @@ export function ModelOverTimeChart({ dailyByModel, modelNames }) {<AreaChart data={chartData} margin={{ top: 4, right: 4, left: 0, bottom: 0 }}><XAxisdataKey="dateLabel"- tick={{ fontSize: 10, fill: "var(--text-muted)" }}+ tick={{ fontSize: 10, fill: "var(--color-text-muted)" }}axisLine={false}tickLine={false}interval="preserveStartEnd"/><YAxis- tick={{ fontSize: 10, fill: "var(--text-muted)" }}+ tick={{ fontSize: 10, fill: "var(--color-text-muted)" }}tickFormatter={(v) => fmt(v)}axisLine={false}tickLine={false}diff --git a/src/shared/constants/mcpScopes.ts b/src/shared/constants/mcpScopes.tsindex 4eb4a34468..a07d09c26d 100644--- a/src/shared/constants/mcpScopes.ts+++ b/src/shared/constants/mcpScopes.ts@@ -59,6 +59,9 @@ export const MCP_TOOL_SCOPES: Record<string, readonly McpScope[]> = {omniroute_cache_flush: ["write:cache"],omniroute_compression_status: ["read:compression"],omniroute_compression_configure: ["write:compression"],+ omniroute_set_compression_engine: ["write:compression"],+ omniroute_list_compression_combos: ["read:compression"],+ omniroute_compression_combo_stats: ["read:compression"],omniroute_oneproxy_fetch: ["read:proxies"],omniroute_oneproxy_rotate: ["read:proxies"],omniroute_oneproxy_stats: ["read:proxies"],diff --git a/src/shared/constants/publicApiRoutes.ts b/src/shared/constants/publicApiRoutes.tsindex ac11567d7c..8e12f6dbd9 100644--- a/src/shared/constants/publicApiRoutes.ts+++ b/src/shared/constants/publicApiRoutes.ts@@ -3,14 +3,16 @@ const PUBLIC_API_ROUTE_PREFIXES = ["/api/auth/logout","/api/auth/status","/api/init",- "/api/monitoring/health","/api/v1/","/api/cloud/","/api/sync/bundle","/api/oauth/",];-const PUBLIC_READONLY_API_ROUTE_PREFIXES = ["/api/settings/require-login"];+const PUBLIC_READONLY_API_ROUTE_PREFIXES = [+ "/api/monitoring/health",+ "/api/settings/require-login",+];const PUBLIC_READONLY_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);diff --git a/src/shared/constants/routingStrategies.ts b/src/shared/constants/routingStrategies.tsindex e2ebcdffb3..752683e7ca 100644--- a/src/shared/constants/routingStrategies.ts+++ b/src/shared/constants/routingStrategies.ts@@ -1,17 +1,55 @@-export type RoutingStrategyValue =- | "priority"- | "weighted"- | "round-robin"- | "context-relay"- | "fill-first"- | "p2c"- | "random"- | "least-used"- | "cost-optimized"- | "strict-random"- | "auto"- | "context-optimized"- | "lkgp";+export const ROUTING_STRATEGY_VALUES = [+ "priority",+ "weighted",+ "round-robin",+ "context-relay",+ "fill-first",+ "p2c",+ "random",+ "least-used",+ "cost-optimized",+ "strict-random",+ "auto",+ "lkgp",+ "context-optimized",+] as const;++export type RoutingStrategyValue = (typeof ROUTING_STRATEGY_VALUES)[number];++export const AUTO_ROUTING_STRATEGY_VALUES = [+ "rules",+ "cost",+ "eco",+ "latency",+ "fast",+ "lkgp",+] as const;++export type AutoRoutingStrategyValue = (typeof AUTO_ROUTING_STRATEGY_VALUES)[number];++export const ACCOUNT_FALLBACK_STRATEGY_VALUES = [+ "priority",+ "weighted",+ "fill-first",+ "round-robin",+ "p2c",+ "random",+ "least-used",+ "cost-optimized",+ "strict-random",+] as const;++export type AccountFallbackStrategyValue = (typeof ACCOUNT_FALLBACK_STRATEGY_VALUES)[number];++export function normalizeRoutingStrategy(value: unknown): RoutingStrategyValue {+ if (typeof value !== "string") return "priority";+ const normalized = value.trim().toLowerCase();+ if (normalized === "usage") return "least-used";+ if (normalized === "context") return "context-optimized";+ return (ROUTING_STRATEGY_VALUES as readonly string[]).includes(normalized)+ ? (normalized as RoutingStrategyValue)+ : "priority";+}type RoutingStrategyOption = {value: RoutingStrategyValue;@@ -115,17 +153,4 @@ export const ROUTING_STRATEGIES: RoutingStrategyOption[] = [},];-export const SETTINGS_FALLBACK_STRATEGY_VALUES: RoutingStrategyValue[] = [- "priority",- "weighted",- "fill-first",- "round-robin",- "p2c",- "random",- "least-used",- "cost-optimized",- "strict-random",- "auto",- "context-optimized",- "lkgp",-];+export const SETTINGS_FALLBACK_STRATEGY_VALUES = ACCOUNT_FALLBACK_STRATEGY_VALUES;diff --git a/src/shared/constants/sidebarVisibility.ts b/src/shared/constants/sidebarVisibility.tsindex 9593b05385..300a75d86c 100644--- a/src/shared/constants/sidebarVisibility.ts+++ b/src/shared/constants/sidebarVisibility.ts@@ -8,6 +8,9 @@ export const HIDEABLE_SIDEBAR_ITEM_IDS = ["costs","analytics","cache",+ "context-caveman",+ "context-rtk",+ "context-combos","limits","cli-tools","agents",@@ -21,6 +24,7 @@ export const HIDEABLE_SIDEBAR_ITEM_IDS = ["audit","webhooks","health",+ "proxy","settings","docs","issues",@@ -28,7 +32,7 @@ export const HIDEABLE_SIDEBAR_ITEM_IDS = [] as const;export type HideableSidebarItemId = (typeof HIDEABLE_SIDEBAR_ITEM_IDS)[number];-export type SidebarSectionId = "primary" | "cli" | "debug" | "system" | "help";+export type SidebarSectionId = "primary" | "context" | "cli" | "debug" | "system" | "help";export interface SidebarItemDefinition {id: HideableSidebarItemId;@@ -69,6 +73,27 @@ const CLI_SIDEBAR_ITEMS: readonly SidebarItemDefinition[] = [{ id: "skills", href: "/dashboard/skills", i18nKey: "skills", icon: "auto_fix_high" },];+const CONTEXT_SIDEBAR_ITEMS: readonly SidebarItemDefinition[] = [+ {+ id: "context-caveman",+ href: "/dashboard/context/caveman",+ i18nKey: "contextCaveman",+ icon: "compress",+ },+ {+ id: "context-rtk",+ href: "/dashboard/context/rtk",+ i18nKey: "contextRtk",+ icon: "filter_alt",+ },+ {+ id: "context-combos",+ href: "/dashboard/context/combos",+ i18nKey: "contextCombos",+ icon: "hub",+ },+];+const DEBUG_SIDEBAR_ITEMS: readonly SidebarItemDefinition[] = [{ id: "translator", href: "/dashboard/translator", i18nKey: "translator", icon: "translate" },{ id: "playground", href: "/dashboard/playground", i18nKey: "playground", icon: "science" },@@ -85,6 +110,7 @@ const SYSTEM_SIDEBAR_ITEMS: readonly SidebarItemDefinition[] = [{ id: "audit", href: "/dashboard/audit", i18nKey: "auditLog", icon: "policy" },{ id: "webhooks", href: "/dashboard/webhooks", i18nKey: "webhooks", icon: "webhook" },{ id: "health", href: "/dashboard/health", i18nKey: "health", icon: "health_and_safety" },+ { id: "proxy", href: "/dashboard/system/proxy", i18nKey: "proxy", icon: "dns" },{ id: "settings", href: "/dashboard/settings", i18nKey: "settings", icon: "settings" },];@@ -108,6 +134,12 @@ export const SIDEBAR_SECTIONS: readonly SidebarSectionDefinition[] = [items: PRIMARY_SIDEBAR_ITEMS,showTitleInSidebar: false,},+ {+ id: "context",+ titleKey: "contextSection",+ titleFallback: "Context & Cache",+ items: CONTEXT_SIDEBAR_ITEMS,+ },{id: "cli",titleKey: "cliSection",diff --git a/src/shared/schemas/validation.ts b/src/shared/schemas/validation.tsindex 784518a4d0..b08b8d22f7 100644--- a/src/shared/schemas/validation.ts+++ b/src/shared/schemas/validation.ts@@ -7,6 +7,7 @@*/import { z } from "zod";+import { ROUTING_STRATEGY_VALUES } from "@/shared/constants/routingStrategies";// ─── Provider Connection ──────────────────────────────────────────@@ -38,17 +39,7 @@ export const comboSchema = z.object({name: z.string().min(1, "Combo name is required").max(100),model: z.string().min(1, "Model pattern is required"),endpoint: z.enum(["chat", "embeddings", "images"]).default("chat"),- strategy: z- .enum([- "priority",- "weighted",- "round-robin",- "context-relay",- "random",- "least-used",- "cost-optimized",- ])- .default("priority"),+ strategy: z.enum(ROUTING_STRATEGY_VALUES).default("priority"),nodes: z.array(comboNodeSchema).min(1, "At least one node is required"),isActive: z.boolean().default(true),maxRetries: z.number().int().min(0).max(10).default(2),diff --git a/src/shared/utils/formatting.ts b/src/shared/utils/formatting.tsindex 6dd941cf2a..30274f3270 100644--- a/src/shared/utils/formatting.ts+++ b/src/shared/utils/formatting.ts@@ -146,6 +146,55 @@ export function formatCost(usd: number | null | undefined): string {export const fmtCost = formatCost;+/**+ * Format a USD cost for display using abbreviated K/M/B/T suffixes.+ * Sub-cent values show additional precision.+ * - Values >= 1T are shown as $X.XT+ * - Values >= 1B are shown as $X.XB+ * - Values >= 1M are shown as $X.XM+ * - Values >= 1K are shown as $X.XK+ * - Otherwise shown as $X.XX+ * @param {number} usd - Cost in USD+ * @returns {string}+ */+export function formatCostAbbreviated(usd: number | null | undefined): string {+ const value = Number(usd || 0);+ if (!Number.isFinite(value) || value === 0) return "$0";+ const abs = Math.abs(value);+ if (abs < 0.01) {+ if (value < 0) {+ return `-$${Math.abs(value).toFixed(6)}`;+ }+ return `$${value.toFixed(6)}`;+ }+ let divisor: number, suffix: string;+ if (abs >= 1_000_000_000_000) {+ divisor = 1_000_000_000_000;+ suffix = "T";+ } else if (abs >= 1_000_000_000) {+ divisor = 1_000_000_000;+ suffix = "B";+ } else if (abs >= 1_000_000) {+ divisor = 1_000_000;+ suffix = "M";+ } else if (abs >= 1_000) {+ divisor = 1_000;+ suffix = "K";+ } else {+ if (value < 0) {+ return `-$${Math.abs(value).toFixed(2)}`;+ }+ return `$${value.toFixed(2)}`;+ }+ const abbreviated = abs / divisor;+ let formatted = abbreviated.toFixed(1);+ if (formatted.includes(".")) {+ formatted = formatted.replace(/\.?0+$/, "");+ }+ const sign = value < 0 ? "-" : "";+ return `${sign}$${formatted}${suffix}`;+}+/*** Truncate a URL for compact display.* @param {string} url - Full URLdiff --git a/src/shared/utils/parseApiKeys.ts b/src/shared/utils/parseApiKeys.tsnew file mode 100644index 0000000000..c277622e08--- /dev/null+++ b/src/shared/utils/parseApiKeys.ts@@ -0,0 +1,41 @@+/**+ * Parses a newline-separated string of API keys for bulk-paste support in the+ * Provider Connection modal.+ *+ * Rules:+ * - Splits on `\n` and `\r\n`+ * - Trims leading / trailing whitespace from every line+ * - Skips blank (or whitespace-only) lines+ * - Deduplicates within the pasted block and against already-existing keys+ *+ * @param raw Raw text from the paste event, potentially containing+ * multiple newline-separated API keys.+ * @param existing Keys already present in the list; duplicate matches are+ * counted but not re-added.+ * @returns `added` – array of new, unique keys to append.+ * `duplicates` – number of keys that were skipped because they already+ * exist in `existing` or appear more than once in `raw`.+ */+export function parseExtraApiKeys(+ raw: string,+ existing: string[]+): { added: string[]; duplicates: number } {+ const existingSet = new Set(existing);+ const seen = new Set<string>();+ const added: string[] = [];+ let duplicates = 0;++ for (const line of raw.split(/\r?\n/)) {+ const key = line.trim();+ if (!key) continue;++ if (existingSet.has(key) || seen.has(key)) {+ duplicates++;+ } else {+ seen.add(key);+ added.push(key);+ }+ }++ return { added, duplicates };+}diff --git a/src/shared/validation/compressionConfigSchemas.ts b/src/shared/validation/compressionConfigSchemas.tsnew file mode 100644index 0000000000..6357fd0b43--- /dev/null+++ b/src/shared/validation/compressionConfigSchemas.ts@@ -0,0 +1,165 @@+import { z } from "zod";++export const compressionModeSchema = z.enum([+ "off",+ "lite",+ "standard",+ "aggressive",+ "ultra",+ "rtk",+ "stacked",+]);++export const cavemanIntensitySchema = z.enum(["lite", "full", "ultra"]);+export const rtkIntensitySchema = z.enum(["minimal", "standard", "aggressive"]);+export const rtkRawOutputRetentionSchema = z.enum(["never", "failures", "always"]);++export const cavemanConfigSchema = z+ .object({+ enabled: z.boolean().optional(),+ compressRoles: z.array(z.enum(["user", "assistant", "system"])).optional(),+ skipRules: z.array(z.string()).optional(),+ minMessageLength: z.number().int().min(0).optional(),+ preservePatterns: z.array(z.string()).optional(),+ intensity: cavemanIntensitySchema.optional(),+ })+ .strict();++export const cavemanOutputModeSchema = z+ .object({+ enabled: z.boolean().optional(),+ intensity: cavemanIntensitySchema.optional(),+ autoClarity: z.boolean().optional(),+ })+ .strict();++export const rtkConfigSchema = z+ .object({+ enabled: z.boolean().optional(),+ intensity: rtkIntensitySchema.optional(),+ applyToToolResults: z.boolean().optional(),+ applyToCodeBlocks: z.boolean().optional(),+ applyToAssistantMessages: z.boolean().optional(),+ enabledFilters: z.array(z.string()).optional(),+ disabledFilters: z.array(z.string()).optional(),+ maxLinesPerResult: z.number().int().min(0).max(100000).optional(),+ maxCharsPerResult: z.number().int().min(0).max(1000000).optional(),+ deduplicateThreshold: z.number().int().min(2).max(100).optional(),+ customFiltersEnabled: z.boolean().optional(),+ trustProjectFilters: z.boolean().optional(),+ rawOutputRetention: rtkRawOutputRetentionSchema.optional(),+ rawOutputMaxBytes: z.number().int().min(1024).max(10_000_000).optional(),+ })+ .strict();++export const languageConfigSchema = z+ .object({+ enabled: z.boolean().optional(),+ defaultLanguage: z.string().trim().min(1).optional(),+ autoDetect: z.boolean().optional(),+ enabledPacks: z.array(z.string().trim().min(1)).optional(),+ })+ .strict();++export const aggressiveConfigSchema = z+ .object({+ thresholds: z+ .object({+ fullSummary: z.number().int().min(1).max(100).optional(),+ moderate: z.number().int().min(1).max(100).optional(),+ light: z.number().int().min(1).max(100).optional(),+ verbatim: z.number().int().min(1).max(100).optional(),+ })+ .strict()+ .optional(),+ toolStrategies: z+ .object({+ fileContent: z.boolean().optional(),+ grepSearch: z.boolean().optional(),+ shellOutput: z.boolean().optional(),+ json: z.boolean().optional(),+ errorMessage: z.boolean().optional(),+ })+ .strict()+ .optional(),+ summarizerEnabled: z.boolean().optional(),+ maxTokensPerMessage: z.number().int().min(256).max(32768).optional(),+ minSavingsThreshold: z.number().min(0).max(1).optional(),+ preserveSystemPrompt: z.boolean().optional(),+ })+ .strict();++export const ultraConfigSchema = z+ .object({+ enabled: z.boolean().optional(),+ compressionRate: z.number().min(0).max(1).optional(),+ minScoreThreshold: z.number().min(0).max(1).optional(),+ slmFallbackToAggressive: z.boolean().optional(),+ modelPath: z.string().trim().min(1).optional(),+ maxTokensPerMessage: z.number().int().min(0).max(32768).optional(),+ preserveSystemPrompt: z.boolean().optional(),+ })+ .strict();++const noConfigSchema = z.object({}).strict();++export const stackedPipelineStepSchema = z.discriminatedUnion("engine", [+ z+ .object({+ engine: z.literal("lite"),+ intensity: z.literal("lite").optional(),+ config: noConfigSchema.optional(),+ })+ .strict(),+ z+ .object({+ engine: z.literal("caveman"),+ intensity: cavemanIntensitySchema.optional(),+ config: cavemanConfigSchema.optional(),+ })+ .strict(),+ z+ .object({+ engine: z.literal("aggressive"),+ intensity: z.literal("standard").optional(),+ config: aggressiveConfigSchema.optional(),+ })+ .strict(),+ z+ .object({+ engine: z.literal("ultra"),+ intensity: z.literal("ultra").optional(),+ config: ultraConfigSchema.optional(),+ })+ .strict(),+ z+ .object({+ engine: z.literal("rtk"),+ intensity: rtkIntensitySchema.optional(),+ config: rtkConfigSchema.optional(),+ })+ .strict(),+]);++export 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(),+ compressionComboId: z.string().trim().min(1).nullable().optional(),+ stackedPipeline: z.array(stackedPipelineStepSchema).optional(),+ cavemanConfig: cavemanConfigSchema.optional(),+ cavemanOutputMode: cavemanOutputModeSchema.optional(),+ rtkConfig: rtkConfigSchema.optional(),+ languageConfig: languageConfigSchema.optional(),+ aggressive: aggressiveConfigSchema.optional(),+ ultra: ultraConfigSchema.optional(),+ })+ .strict();++export const compressionPreviewConfigSchema = compressionSettingsUpdateSchema;diff --git a/src/shared/validation/schemas.ts b/src/shared/validation/schemas.tsindex 9b6dbfdbe6..b28f347cb6 100644--- a/src/shared/validation/schemas.ts+++ b/src/shared/validation/schemas.ts@@ -1,4 +1,8 @@import { z } from "zod";+import {+ ACCOUNT_FALLBACK_STRATEGY_VALUES,+ ROUTING_STRATEGY_VALUES,+} from "@/shared/constants/routingStrategies";import { SUPPORTED_BATCH_ENDPOINTS } from "@/shared/constants/batchEndpoints";import { COMBO_CONFIG_MODES } from "@/shared/constants/comboConfigMode";import { isLocalProvider } from "@/shared/constants/providers";@@ -324,22 +328,7 @@ const comboModelEntry = z.union([comboRefStepInputSchema,]);-export const comboStrategySchema = z.enum([- "priority",- "weighted",- "round-robin",- "context-relay",- "random",- "least-used",- "cost-optimized",- "strict-random",- "auto",- "fill-first",- // #729 schema fixes for combo edit/save- "p2c",- "lkgp",- "context-optimized",-]);+export const comboStrategySchema = z.enum(ROUTING_STRATEGY_VALUES);const scoringWeightsSchema = z.object({@@ -369,7 +358,15 @@ const compositeTiersSchema = z}).strict();-const compressionModeSchema = z.enum(["off", "lite", "standard", "aggressive", "ultra"]);+const compressionModeSchema = z.enum([+ "off",+ "lite",+ "standard",+ "aggressive",+ "ultra",+ "rtk",+ "stacked",+]);const comboCompressionOverrideSchema = z.union([z.literal(""), compressionModeSchema]);const comboRuntimeConfigSchema = z@@ -419,21 +416,7 @@ export const createComboSchema = z.object({// ──── Settings Schemas ────// FASE-01: Removed .passthrough() — only explicitly listed fields are accepted-const settingsFallbackStrategySchema = z.enum([- "priority",- "weighted",- "round-robin",- "context-relay",- "fill-first",- "p2c",- "random",- "least-used",- "cost-optimized",- "strict-random",- "auto",- "context-optimized",- "lkgp",-]);+const settingsFallbackStrategySchema = z.enum(ACCOUNT_FALLBACK_STRATEGY_VALUES);export const updateSettingsSchema = z.object({newPassword: z.string().min(1).max(200).optional(),@@ -699,6 +682,7 @@ export const providerModelMutationSchema = z.object({"chat-completions","responses","embeddings",+ "rerank","audio-transcriptions","audio-speech","images-generations",@@ -709,6 +693,7 @@ export const providerModelMutationSchema = z.object({z.enum(["chat","embeddings",+ "rerank","images","audio","audio-transcriptions",diff --git a/src/shared/validation/settingsSchemas.ts b/src/shared/validation/settingsSchemas.tsindex acec76d9b2..4d7928f8e5 100644--- a/src/shared/validation/settingsSchemas.ts+++ b/src/shared/validation/settingsSchemas.ts@@ -8,22 +8,7 @@import { z } from "zod";import { COMBO_CONFIG_MODES } from "@/shared/constants/comboConfigMode";import { HIDEABLE_SIDEBAR_ITEM_IDS } from "@/shared/constants/sidebarVisibility";--const fallbackStrategyValues = [- "priority",- "weighted",- "round-robin",- "context-relay",- "fill-first",- "p2c",- "random",- "least-used",- "cost-optimized",- "strict-random",- "auto",- "context-optimized",- "lkgp",-] as const;+import { ACCOUNT_FALLBACK_STRATEGY_VALUES } from "@/shared/constants/routingStrategies";const signatureCacheModeValues = ["enabled", "bypass", "bypass-strict"] as const;@@ -52,7 +37,7 @@ export const updateSettingsSchema = z.object({hiddenSidebarItems: z.array(z.enum(HIDEABLE_SIDEBAR_ITEM_IDS)).optional(),comboConfigMode: z.enum(COMBO_CONFIG_MODES).optional(),// Routing settings (#134)- fallbackStrategy: z.enum(fallbackStrategyValues).optional(),+ fallbackStrategy: z.enum(ACCOUNT_FALLBACK_STRATEGY_VALUES).optional(),wildcardAliases: z.array(z.object({ pattern: z.string(), target: z.string() })).optional(),stickyRoundRobinLimit: z.number().int().min(0).max(1000).optional(),requestRetry: z.number().int().min(0).max(10).optional(),diff --git a/src/sse/services/tokenRefresh.ts b/src/sse/services/tokenRefresh.tsindex 6df10e2f72..244eb70558 100755--- a/src/sse/services/tokenRefresh.ts+++ b/src/sse/services/tokenRefresh.ts@@ -17,6 +17,32 @@ import {getAllAccessTokens as _getAllAccessTokens,} from "@omniroute/open-sse/services/tokenRefresh.ts";+// Per-connection mutex: prevents concurrent OAuth refresh for rotating tokens.+// Key = connectionId, Value = { promise: in-flight refresh, waiters: count of callers sharing it }+const connectionRefreshMutex = new Map<string, { promise: Promise<any>; waiters: number }>();++export async function withConnectionRefreshMutex<T>(+ connectionId: string,+ fn: () => Promise<T>+): Promise<T> {+ const existing = connectionRefreshMutex.get(connectionId);+ if (existing) {+ existing.waiters++;+ log.info("TOKEN_REFRESH", "Concurrent refresh detected — sharing in-flight refresh", {+ connectionId,+ waiters: existing.waiters,+ });+ return existing.promise as Promise<T>;+ }++ const entry: { promise: Promise<T>; waiters: number } = { promise: null as any, waiters: 0 };+ entry.promise = fn().finally(() => {+ connectionRefreshMutex.delete(connectionId);+ });+ connectionRefreshMutex.set(connectionId, entry);+ return entry.promise;+}+export const TOKEN_EXPIRY_BUFFER_MS = BUFFER_MS;export const refreshAccessToken = async (@@ -146,7 +172,12 @@ export async function checkAndRefreshToken(provider: string, credentials: any) {expiresIn: Math.round((expiresAt - now) / 1000),});- const newCredentials = await getAccessToken(provider, updatedCredentials);+ const connectionId: string | undefined = updatedCredentials.connectionId;+ const newCredentials = connectionId+ ? await withConnectionRefreshMutex(connectionId, () =>+ getAccessToken(provider, updatedCredentials)+ )+ : await getAccessToken(provider, updatedCredentials);if (newCredentials && newCredentials.accessToken) {await updateProviderCredentials(updatedCredentials.connectionId, newCredentials);diff --git a/src/types/settings.ts b/src/types/settings.tsindex 43edc4064f..e8143246b2 100644--- a/src/types/settings.ts+++ b/src/types/settings.ts@@ -1,5 +1,9 @@import type { HideableSidebarItemId } from "@/shared/constants/sidebarVisibility";import type { ResilienceSettings } from "@/lib/resilience/settings";+import type {+ AccountFallbackStrategyValue,+ RoutingStrategyValue,+} from "@/shared/constants/routingStrategies";/*** Application settings stored in SQLite key-value pairs.@@ -7,14 +11,7 @@ import type { ResilienceSettings } from "@/lib/resilience/settings";export interface Settings {requireLogin: boolean;hasPassword: boolean;- fallbackStrategy:- | "fill-first"- | "round-robin"- | "p2c"- | "random"- | "least-used"- | "cost-optimized"- | "strict-random";+ fallbackStrategy: AccountFallbackStrategyValue;stickyRoundRobinLimit: number;requestRetry: number;maxRetryIntervalSec: number;@@ -31,7 +28,7 @@ export interface Settings {}export interface ComboDefaults {- strategy: "priority" | "weighted" | "round-robin" | "context-relay";+ strategy: RoutingStrategyValue;maxRetries: number;retryDelayMs: number;maxComboDepth: number;diff --git a/tests/e2e/api-keys-flow.spec.ts b/tests/e2e/api-keys-flow.spec.tsindex 11666f05af..9ec5c5bcfc 100644--- a/tests/e2e/api-keys-flow.spec.ts+++ b/tests/e2e/api-keys-flow.spec.ts@@ -381,4 +381,263 @@ test.describe("API keys flow", () => {await expect(permissionsDialog).not.toBeVisible({ timeout: UI_STABILITY_TIMEOUT_MS });await expect(page.getByText("Renamed Key")).toBeVisible();});++ test("validation error appears inside the create key modal, not behind the backdrop", async ({+ page,+ }) => {+ const state = {+ keys: [] as ApiKeyRecord[],+ nextId: 1,+ };++ // Stub all API routes+ await page.route("**/v1/models", async (route) => {+ await fulfillJson(route, { data: [] });+ });+ await page.route("**/api/connections", async (route) => {+ await fulfillJson(route, {+ connections: [+ { id: "conn-openai", name: "OpenAI Main", provider: "openai", isActive: true },+ ],+ });+ });+ await page.route(/\/api\/usage\/call-logs(?:\?.*)?$/, async (route) => {+ await fulfillJson(route, []);+ });+ await page.route("**/api/sessions", async (route) => {+ await fulfillJson(route, { byApiKey: {} });+ });+ await page.route("**/api/keys", async (route) => {+ const method = route.request().method();+ if (method === "GET") {+ await fulfillJson(route, {+ keys: state.keys.map(({ fullKey, ...record }) => record),+ allowKeyReveal: true,+ });+ return;+ }+ if (method === "POST") {+ const payload = (route.request().postDataJSON() as { name?: string }) || {};+ const id = `key-${state.nextId++}`;+ const suffix = String(1000 + state.nextId);+ const fullKey = `sk-live-${suffix}-demo-secret`;+ const maskedKey = `sk-live-****${suffix}`;+ state.keys.push({+ id,+ name: payload.name || "New Key",+ key: maskedKey,+ fullKey,+ allowedModels: null,+ allowedConnections: null,+ createdAt: new Date().toISOString(),+ });+ await fulfillJson(route, { key: fullKey, id });+ return;+ }+ await fulfillJson(route, { error: "Method not allowed" }, 405);+ });+ await page.route(/\/api\/keys\/[^/]+$/, async (route) => {+ await fulfillJson(route, { error: "Not found" }, 404);+ });+ await page.route(/\/api\/keys\/[^/]+\/reveal$/, async (route) => {+ await fulfillJson(route, { key: "" });+ });++ await gotoDashboardRoute(page, "/dashboard/api-manager", {+ timeoutMs: NAVIGATION_TIMEOUT_MS,+ });+ await waitForPageToSettle(page);+ await waitForNextDevCompileToFinish(page);++ // Open the create key modal+ const createFirstKeyButton = page.getByRole("button", {+ name: /create (your )?first key/i,+ });+ await expect(createFirstKeyButton).toBeVisible({ timeout: UI_STABILITY_TIMEOUT_MS });+ await createFirstKeyButton.click();++ const createDialog = page.getByRole("dialog", { name: /create api key/i });+ await expect(createDialog).toBeVisible({ timeout: UI_STABILITY_TIMEOUT_MS });++ // Fill an invalid name (special characters) and submit+ const nameInput = createDialog.locator("input").first();+ await nameInput.fill("bad@name!");+ const createKeyButton = createDialog.getByRole("button", { name: /create api key/i });+ await createKeyButton.click({ force: true });++ // The validation error must appear as an inline <p role="alert"> INSIDE the modal+ const inlineError = createDialog.locator("p[role='alert']");+ await expect(inlineError).toBeVisible({ timeout: UI_STABILITY_TIMEOUT_MS });++ // The error must be visible — i.e. not obscured by the backdrop.+ // A covered element has box visibility but fails the check below because+ // pointer events and paint are blocked by the overlay div.+ await expect(inlineError).toBeInViewport();++ // No page-level error banner should appear behind the modal+ const pageErrorBanner = page.locator('.flex.flex-col.gap-8 > [class~="bg-red-500/10"]');+ await expect(pageErrorBanner).not.toBeVisible();++ // Typing should clear the error+ await nameInput.fill("valid-name");+ await expect(inlineError).not.toBeVisible();++ // A valid name should succeed without errors+ await createKeyButton.click({ force: true });+ await expect.poll(() => state.keys.length).toBe(1);+ });++ test("validation error appears inside the permissions modal when renaming, not behind the backdrop", async ({+ page,+ }) => {+ const state: {+ keys: ApiKeyRecord[];+ nextId: number;+ } = {+ keys: [],+ nextId: 1,+ };++ // Stub all API routes+ await page.route("**/v1/models", async (route) => {+ await fulfillJson(route, { data: [] });+ });++ await page.route("**/api/settings", async (route) => {+ await fulfillJson(route, {});+ });++ await page.route("**/api/providers", async (route) => {+ await fulfillJson(route, {+ connections: [+ { id: "conn-openai", name: "OpenAI Main", provider: "openai", isActive: true },+ ],+ });+ });++ await page.route(/\/api\/usage\/call-logs(?:\?.*)?$/, async (route) => {+ await fulfillJson(route, []);+ });++ await page.route("**/api/sessions", async (route) => {+ await fulfillJson(route, { byApiKey: {} });+ });++ await page.route(/\/api\/keys\/[^/]+$/, async (route) => {+ if (route.request().method() === "PATCH") {+ const keyId = route.request().url().split("/").pop() || "";+ const payload = (await route.request().postDataJSON()) as { name?: string };+ const record = state.keys.find((key) => key.id === keyId);+ if (!record) {+ await fulfillJson(route, { error: "Key not found" }, 404);+ return;+ }+ if (payload.name) {+ record.name = payload.name;+ }+ await fulfillJson(route, { message: "API key settings updated successfully", ...payload });+ return;+ }++ await fulfillJson(route, { error: "Method not allowed" }, 405);+ });++ await page.route("**/api/keys", async (route) => {+ const method = route.request().method();++ if (method === "GET") {+ await fulfillJson(route, {+ keys: state.keys.map(({ fullKey, ...record }) => record),+ allowKeyReveal: true,+ });+ return;+ }++ if (method === "POST") {+ const payload = (route.request().postDataJSON() as { name?: string }) || {};+ const id = `key-${state.nextId++}`;+ const suffix = String(1000 + state.nextId);+ const fullKey = `sk-live-${suffix}-demo-secret`;+ const maskedKey = `sk-live-****${suffix}`;+ state.keys.push({+ id,+ name: payload.name || "New Key",+ key: maskedKey,+ fullKey,+ allowedModels: null,+ allowedConnections: null,+ createdAt: new Date("2026-04-05T20:00:00.000Z").toISOString(),+ });++ await fulfillJson(route, { key: fullKey, id });+ return;+ }++ await fulfillJson(route, { error: "Method not allowed" }, 405);+ });++ await gotoDashboardRoute(page, "/dashboard/api-manager", {+ timeoutMs: NAVIGATION_TIMEOUT_MS,+ });+ await waitForPageToSettle(page);+ await waitForNextDevCompileToFinish(page);++ // Create a key first+ const createFirstKeyButton = page.getByRole("button", {+ name: /create (your )?first key/i,+ });+ await expect(createFirstKeyButton).toBeVisible({ timeout: UI_STABILITY_TIMEOUT_MS });+ await createFirstKeyButton.click();++ const createDialog = page.getByRole("dialog", { name: /create api key/i });+ await expect(createDialog).toBeVisible({ timeout: UI_STABILITY_TIMEOUT_MS });+ await createDialog.locator("input").first().fill("Original Name");+ await createDialog.getByRole("button", { name: /create api key/i }).click({ force: true });++ // Dismiss the created dialog+ const createdDialog = page.getByRole("dialog", { name: /api key created/i });+ await createdDialog.getByRole("button", { name: /done/i }).click();+ await waitForPageToSettle(page);+ await waitForNextDevCompileToFinish(page);+ await expect(page.getByText("Original Name")).toBeVisible({+ timeout: UI_STABILITY_TIMEOUT_MS,+ });++ // Open the permissions modal+ const keyRow = page+ .locator("div")+ .filter({ has: page.getByText("Original Name", { exact: true }) })+ .first();+ await keyRow.locator('button[title="Edit permissions"]').click({ force: true });++ const permissionsDialog = page.getByRole("dialog", {+ name: /permissions: original name/i,+ });+ await expect(permissionsDialog).toBeVisible({ timeout: UI_STABILITY_TIMEOUT_MS });++ // --- Try to save with an invalid name (empty) ---+ const nameInput = permissionsDialog.locator("input").first();+ await nameInput.clear();+ await nameInput.fill(" ");+ const saveButton = permissionsDialog.getByRole("button", { name: /save permissions/i });+ await saveButton.click({ force: true });++ // Inline error should appear inside the permissions modal+ const inlineError = permissionsDialog.locator('[id$="-error"]');+ await expect(inlineError).toBeVisible({ timeout: UI_STABILITY_TIMEOUT_MS });++ // No page-level error banner should appear behind the modal+ const pageErrorBanner = page.locator('.flex.flex-col.gap-8 > [class~="bg-red-500/10"]');+ await expect(pageErrorBanner).not.toBeVisible();++ // Typing a valid name should clear the error+ await nameInput.fill("Renamed Key");+ await expect(inlineError).not.toBeVisible();++ // Save should succeed now+ await saveButton.click({ force: true });+ await expect.poll(() => state.keys[0]?.name).toBe("Renamed Key");+ await expect(permissionsDialog).not.toBeVisible({ timeout: UI_STABILITY_TIMEOUT_MS });+ await expect(page.getByText("Renamed Key")).toBeVisible();+ });});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..29cd3219e2--- /dev/null+++ b/tests/golden-set/compression-upstream-parity.test.ts@@ -0,0 +1,151 @@+import { describe, it } from "node:test";+import assert from "node:assert/strict";+import { createRequire } from "node:module";+import { readdirSync, readFileSync } from "node:fs";+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 upstreamFixtureDir = path.resolve("_references/_outros/caveman/tests/caveman-compress");+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 {+ return omniroutePromptCompression(text).text;+}++function omniroutePromptCompression(text: string): { text: string; fallbackApplied: boolean } {+ const result = cavemanCompress(+ { messages: [{ role: "user", content: text }] },+ {+ enabled: true,+ compressRoles: ["user"],+ skipRules: [],+ minMessageLength: 0,+ preservePatterns: [],+ intensity: "full",+ }+ );+ return {+ text: result.body.messages[0].content as string,+ fallbackApplied: result.stats?.fallbackApplied === true,+ };+}++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);+ });++ it("runs offline parity against upstream Caveman fixture files", () => {+ const fixturePairs = readdirSync(upstreamFixtureDir)+ .filter((entry) => entry.endsWith(".original.md"))+ .map((originalName) => ({+ name: originalName.replace(/\.original\.md$/, ""),+ originalPath: path.join(upstreamFixtureDir, originalName),+ compressedPath: path.join(+ upstreamFixtureDir,+ originalName.replace(/\.original\.md$/, ".md")+ ),+ }));++ assert.ok(fixturePairs.length >= 5, "expected upstream fixture pairs");++ for (const fixture of fixturePairs) {+ const original = readFileSync(fixture.originalPath, "utf8");+ const expected = readFileSync(fixture.compressedPath, "utf8");+ const ours = omniroutePromptCompression(original);+ const upstreamShrink = upstream.compress(original).compressed;++ assert.ok(+ expected.length < original.length,+ `${fixture.name}: upstream fixture did not reduce`+ );+ if (ours.fallbackApplied) {+ assert.equal(+ ours.text,+ original,+ `${fixture.name}: fallback must preserve original fixture verbatim`+ );+ } else {+ assert.ok(ours.text.length < original.length, `${fixture.name}: OmniRoute did not reduce`);+ assert.ok(+ ours.text.length <= Math.ceil(Math.max(expected.length, upstreamShrink.length) * 1.35),+ `${fixture.name}: OmniRoute drifted too far from upstream fixture budget`+ );+ }++ for (const protectedPattern of [/```[\s\S]*?```/g, /`[^`\n]+`/g, /https?:\/\/\S+/g]) {+ const protectedValues = original.match(protectedPattern) ?? [];+ for (const protectedValue of protectedValues) {+ assert.ok(+ ours.text.includes(protectedValue),+ `${fixture.name}: protected content changed: ${protectedValue.slice(0, 80)}`+ );+ }+ }+ }+ });+});diff --git a/tests/integration/chat-pipeline.test.ts b/tests/integration/chat-pipeline.test.tsindex f1628033f1..5ff4bfa0de 100644--- a/tests/integration/chat-pipeline.test.ts+++ b/tests/integration/chat-pipeline.test.ts@@ -27,7 +27,6 @@ const { BaseExecutor } = await import("../../open-sse/executors/base.ts");const { getCircuitBreaker, resetAllCircuitBreakers } =await import("../../src/shared/utils/circuitBreaker.ts");const { clearProviderFailure } = await import("../../open-sse/services/accountFallback.ts");-const { setCliCompatProviders } = await import("../../open-sse/config/cliFingerprints.ts");const originalFetch = globalThis.fetch;const originalRetryDelayMs = BaseExecutor.RETRY_CONFIG.delayMs;diff --git a/tests/integration/chatcore-compression-integration.test.ts b/tests/integration/chatcore-compression-integration.test.tsindex 00cd119beb..d917a46979 100644--- a/tests/integration/chatcore-compression-integration.test.ts+++ b/tests/integration/chatcore-compression-integration.test.ts@@ -14,6 +14,7 @@ const providersDb = await import("../../src/lib/db/providers.ts");const readCacheDb = await import("../../src/lib/db/readCache.ts");const combosDb = await import("../../src/lib/db/combos.ts");const compressionDb = await import("../../src/lib/db/compression.ts");+const compressionCombosDb = await import("../../src/lib/db/compressionCombos.ts");const compressionAnalyticsDb = await import("../../src/lib/db/compressionAnalytics.ts");const { handleChatCore } = await import("../../open-sse/handlers/chatCore.ts");const { estimateTokens, getTokenLimit } = await import("../../open-sse/services/contextManager.ts");@@ -109,6 +110,12 @@ test("chatCore integration: compressContext called proactively when context exce},clientRawRequest: { endpoint: "/v1/chat/completions", headers: new Map() },connectionId,+ onCredentialsRefreshed: () => {},+ onRequestSuccess: () => {},+ onStreamFailure: () => {},+ onDisconnect: () => {},+ userAgent: "test-agent",+ comboName: null,});assert.ok(result.success, "Request should succeed");@@ -179,10 +186,10 @@ test("chatCore integration: disabled prompt compression leaves combo override re"Test body should exceed proactive compression threshold");- let capturedBody: any = null;+ let capturedBody: { messages?: Array<{ role?: string; content?: string }> } | null = null;globalThis.fetch = async (_url: string | URL | Request, init?: RequestInit) => {if (init?.body) {- capturedBody = JSON.parse(init.body as string);+ capturedBody = JSON.parse(init.body as string) as typeof capturedBody;}return new Response(JSON.stringify({@@ -206,6 +213,11 @@ test("chatCore integration: disabled prompt compression leaves combo override reconnectionId: connection.id,isCombo: true,comboName: "disabled-compression-combo",+ onCredentialsRefreshed: () => {},+ onRequestSuccess: () => {},+ onStreamFailure: () => {},+ onDisconnect: () => {},+ userAgent: "test-agent",});assert.ok(result.success, "Request should succeed");@@ -286,6 +298,12 @@ test("chatCore integration: compressContext NOT called when context is below 85%log: { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} },clientRawRequest: { endpoint: "/v1/chat/completions", headers: new Map() },connectionId,+ onCredentialsRefreshed: () => {},+ onRequestSuccess: () => {},+ onStreamFailure: () => {},+ onDisconnect: () => {},+ userAgent: "test-agent",+ comboName: null,});assert.ok(result.success, "Request should succeed");@@ -367,6 +385,12 @@ test("chatCore integration: compression preserves message structure", async () =},clientRawRequest: { endpoint: "/v1/chat/completions", headers: new Map() },connectionId,+ onCredentialsRefreshed: () => {},+ onRequestSuccess: () => {},+ onStreamFailure: () => {},+ onDisconnect: () => {},+ userAgent: "test-agent",+ comboName: null,});assert.ok(result.success, "Request should succeed");@@ -435,6 +459,12 @@ test("chatCore integration: compression handles tool messages", async () => {log: { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} },clientRawRequest: { endpoint: "/v1/chat/completions", headers: new Map() },connectionId,+ onCredentialsRefreshed: () => {},+ onRequestSuccess: () => {},+ onStreamFailure: () => {},+ onDisconnect: () => {},+ userAgent: "test-agent",+ comboName: null,});assert.ok(result.success, "Request should succeed");@@ -526,6 +556,11 @@ test("chatCore integration: combo requests run proactive compression before KiroconnectionId,isCombo: true,comboName: "test-kiro-compression-combo",+ onCredentialsRefreshed: () => {},+ onRequestSuccess: () => {},+ onStreamFailure: () => {},+ onDisconnect: () => {},+ userAgent: "test-agent",});// Kiro response translation in this integration harness may fail depending on upstream@@ -559,6 +594,306 @@ test("chatCore integration: combo requests run proactive compression before Kiro}});+test("chatCore integration: assigned compression combo applies language packs and output mode", async () => {+ const provider = "openai";+ const model = "gpt-4";++ await compressionDb.updateCompressionSettings({+ enabled: true,+ defaultMode: "off",+ autoTriggerTokens: 0,+ cavemanOutputMode: {+ enabled: false,+ intensity: "full",+ autoClarity: true,+ },+ languageConfig: {+ enabled: false,+ defaultLanguage: "en",+ autoDetect: true,+ enabledPacks: ["en"],+ },+ });++ const connection = await providersDb.createProviderConnection({+ provider,+ apiKey: "test-key",+ isActive: true,+ });++ const routingCombo = await combosDb.createCombo({+ name: "assigned-compression-combo",+ strategy: "priority",+ models: [+ {+ kind: "model",+ model: `${provider}/${model}`,+ connectionId: connection.id,+ },+ ],+ });++ const compressionCombo = compressionCombosDb.createCompressionCombo({+ name: "Assigned PT Output Mode",+ pipeline: [{ engine: "caveman", intensity: "lite" }],+ languagePacks: ["pt-BR"],+ outputMode: true,+ outputModeIntensity: "lite",+ });+ assert.equal(+ compressionCombosDb.assignRoutingCombo(compressionCombo.id, routingCombo.id as string),+ 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: 10, completion_tokens: 5, total_tokens: 15 },+ }),+ {+ status: 200,+ headers: { "content-type": "application/json" },+ }+ );+ };++ try {+ const result = await handleChatCore({+ body: {+ model: "combo/assigned-compression-combo",+ stream: false,+ messages: [{ role: "user", content: "Resuma esta implementacao." }],+ },+ modelInfo: { provider, model },+ credentials: { apiKey: "test-key" },+ log: { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} },+ clientRawRequest: { endpoint: "/v1/chat/completions", headers: new Map() },+ connectionId: connection.id,+ isCombo: true,+ comboName: "assigned-compression-combo",+ onCredentialsRefreshed: () => {},+ onRequestSuccess: () => {},+ onStreamFailure: () => {},+ onDisconnect: () => {},+ userAgent: "test-agent",+ });++ assert.ok(result.success, "Request should succeed");+ assert.ok(capturedBody, "Fetch should receive the request body");+ const firstMessage = capturedBody.messages?.[0];+ assert.equal(firstMessage?.role, "system");+ assert.match(firstMessage?.content ?? "", /OmniRoute Caveman Output Mode/);+ assert.match(firstMessage?.content ?? "", /Responda conciso/);++ for (+ let attempt = 0;+ attempt < 100 && compressionAnalyticsDb.getCompressionAnalyticsSummary().totalRequests === 0;+ attempt += 1+ ) {+ await new Promise((resolve) => setTimeout(resolve, 20));+ }+ } finally {+ globalThis.fetch = originalFetch;+ }+});++test("chatCore integration: default stacked compression combo applies for unassigned stacked requests", async () => {+ const provider = "openai";+ const model = "gpt-4";++ await compressionDb.updateCompressionSettings({+ enabled: true,+ defaultMode: "stacked",+ autoTriggerTokens: 0,+ cavemanOutputMode: {+ enabled: false,+ intensity: "full",+ autoClarity: true,+ },+ languageConfig: {+ enabled: false,+ defaultLanguage: "en",+ autoDetect: true,+ enabledPacks: ["en"],+ },+ });++ const compressionCombo = compressionCombosDb.createCompressionCombo({+ name: "Default PT Output Mode",+ pipeline: [+ { engine: "rtk", intensity: "standard" },+ { engine: "caveman", intensity: "lite" },+ ],+ languagePacks: ["pt-BR"],+ outputMode: true,+ outputModeIntensity: "lite",+ isDefault: true,+ });++ const connection = await providersDb.createProviderConnection({+ provider,+ apiKey: "test-key",+ isActive: true,+ });++ let capturedBody: { messages?: Array<{ role?: string; content?: string }> } | null = null;+ globalThis.fetch = async (_url: string | URL | Request, init?: RequestInit) => {+ if (init?.body) {+ capturedBody = JSON.parse(init.body as string) as typeof capturedBody;+ }+ return new Response(+ JSON.stringify({+ choices: [{ message: { role: "assistant", content: "ok" } }],+ usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 },+ }),+ {+ status: 200,+ headers: { "content-type": "application/json" },+ }+ );+ };++ try {+ const result = await handleChatCore({+ body: {+ model,+ stream: false,+ messages: [{ role: "user", content: "Resuma esta implementacao." }],+ },+ modelInfo: { provider, model },+ credentials: { apiKey: "test-key" },+ log: { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} },+ clientRawRequest: { endpoint: "/v1/chat/completions", headers: new Map() },+ connectionId: connection.id,+ onCredentialsRefreshed: () => {},+ onRequestSuccess: () => {},+ onStreamFailure: () => {},+ onDisconnect: () => {},+ userAgent: "test-agent",+ comboName: null,+ });++ assert.ok(result.success, "Request should succeed");+ assert.ok(capturedBody, "Fetch should receive the request body");+ const firstMessage = capturedBody.messages?.[0];+ assert.equal(firstMessage?.role, "system");+ assert.match(firstMessage?.content ?? "", /OmniRoute Caveman Output Mode/);+ assert.match(firstMessage?.content ?? "", /Responda conciso/);++ let summary = compressionAnalyticsDb.getCompressionAnalyticsSummary();+ for (+ let attempt = 0;+ attempt < 100 && !summary.byCompressionCombo[compressionCombo.id];+ attempt += 1+ ) {+ await new Promise((resolve) => setTimeout(resolve, 20));+ summary = compressionAnalyticsDb.getCompressionAnalyticsSummary();+ }++ assert.equal(summary.byCompressionCombo[compressionCombo.id].count, 1);+ } finally {+ globalThis.fetch = originalFetch;+ }+});++test("chatCore integration: seeded default combo runs RTK before Caveman", async () => {+ const provider = "openai";+ const model = "gpt-4";++ await compressionDb.updateCompressionSettings({+ enabled: true,+ defaultMode: "stacked",+ autoTriggerTokens: 0,+ cavemanOutputMode: {+ enabled: false,+ intensity: "full",+ autoClarity: true,+ },+ languageConfig: {+ enabled: false,+ defaultLanguage: "en",+ autoDetect: true,+ enabledPacks: ["en"],+ },+ });++ const connection = await providersDb.createProviderConnection({+ provider,+ apiKey: "test-key",+ isActive: true,+ });++ let capturedBody: { messages?: Array<{ role?: string; content?: string }> } | null = null;+ globalThis.fetch = async (_url: string | URL | Request, init?: RequestInit) => {+ if (init?.body) {+ capturedBody = JSON.parse(init.body as string) as typeof capturedBody;+ }+ return new Response(+ JSON.stringify({+ choices: [{ message: { role: "assistant", content: "ok" } }],+ usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 },+ }),+ {+ status: 200,+ headers: { "content-type": "application/json" },+ }+ );+ };++ try {+ const result = await handleChatCore({+ body: {+ model,+ stream: false,+ messages: [+ {+ role: "tool",+ content: Array.from({ length: 8 }, () => "same noisy line").join("\n"),+ },+ ],+ },+ modelInfo: { provider, model },+ credentials: { apiKey: "test-key" },+ log: { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} },+ clientRawRequest: { endpoint: "/v1/chat/completions", headers: new Map() },+ connectionId: connection.id,+ onCredentialsRefreshed: () => {},+ onRequestSuccess: () => {},+ onStreamFailure: () => {},+ onDisconnect: () => {},+ userAgent: "test-agent",+ comboName: null,+ });++ assert.ok(result.success, "Request should succeed");+ assert.ok(capturedBody, "Fetch should receive the request body");+ const toolContent = capturedBody.messages?.[0]?.content ?? "";+ assert.match(toolContent, /rtk:dropped 7 repeated lines/);++ let summary = compressionAnalyticsDb.getCompressionAnalyticsSummary();+ for (+ let attempt = 0;+ attempt < 100 &&+ (summary.byCompressionCombo["default-caveman"]?.count !== 1 ||+ summary.realUsage.requestsWithReceipts === 0);+ attempt += 1+ ) {+ await new Promise((resolve) => setTimeout(resolve, 20));+ summary = compressionAnalyticsDb.getCompressionAnalyticsSummary();+ }++ assert.equal(summary.totalRequests, 1);+ assert.equal(summary.byCompressionCombo["default-caveman"].count, 1);+ } finally {+ globalThis.fetch = originalFetch;+ }+});+test("chatCore integration: modular compression records analytics row best-effort", async () => {const provider = "openai";const model = "gpt-4";@@ -606,13 +941,24 @@ test("chatCore integration: modular compression records analytics row best-efforlog: { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} },clientRawRequest: { endpoint: "/v1/chat/completions", headers: new Map() },connectionId: connection.id,+ onCredentialsRefreshed: () => {},+ onRequestSuccess: () => {},+ onStreamFailure: () => {},+ onDisconnect: () => {},+ userAgent: "test-agent",+ comboName: null,});assert.ok(result.success, "Request should succeed");let summary = compressionAnalyticsDb.getCompressionAnalyticsSummary();- for (let attempt = 0; attempt < 20 && summary.totalRequests === 0; attempt += 1) {- await new Promise((resolve) => setTimeout(resolve, 10));+ for (+ let attempt = 0;+ attempt < 100 &&+ (summary.totalRequests === 0 || summary.realUsage.requestsWithReceipts === 0);+ attempt += 1+ ) {+ await new Promise((resolve) => setTimeout(resolve, 20));summary = compressionAnalyticsDb.getCompressionAnalyticsSummary();}@@ -620,6 +966,88 @@ test("chatCore integration: modular compression records analytics row best-efforassert.ok(summary.totalTokensSaved > 0, "Analytics should record token savings");assert.equal(summary.byMode.lite.count, 1);assert.equal(summary.byProvider.openai.count, 1);+ assert.equal(summary.realUsage.requestsWithReceipts, 1);+ assert.equal(summary.realUsage.totalTokens, 15);+ } finally {+ globalThis.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,+ onCredentialsRefreshed: () => {},+ onRequestSuccess: () => {},+ onStreamFailure: () => {},+ onDisconnect: () => {},+ userAgent: "test-agent",+ comboName: null,+ });++ 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 < 100 &&+ (summary.totalRequests === 0 || summary.realUsage.requestsWithReceipts === 0);+ attempt += 1+ ) {+ await new Promise((resolve) => setTimeout(resolve, 20));+ 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/integration/security-hardening.test.ts b/tests/integration/security-hardening.test.tsindex cb6060e247..c45266cc6c 100644--- a/tests/integration/security-hardening.test.ts+++ b/tests/integration/security-hardening.test.ts@@ -283,3 +283,21 @@ test("T06 route payload validation uses validateBody in critical endpoints", ());}});++test("OAuth routes that can create provider connections require auth guard", () => {+ const targets = [+ "src/app/api/oauth/[provider]/[action]/route.ts",+ "src/app/api/oauth/cursor/import/route.ts",+ "src/app/api/oauth/kiro/import/route.ts",+ "src/app/api/oauth/kiro/social-authorize/route.ts",+ "src/app/api/oauth/kiro/social-exchange/route.ts",+ ];++ for (const relPath of targets) {+ const content = readIfExists(relPath);+ assert.ok(content, `${relPath} should exist`);+ assert.ok(content.includes("isAuthRequired"), `${relPath} should check whether auth is active`);+ assert.ok(content.includes("isAuthenticated"), `${relPath} should require authenticated users`);+ assert.ok(content.includes("Unauthorized"), `${relPath} should reject anonymous requests`);+ }+});diff --git a/tests/unit/account-fallback-service.test.ts b/tests/unit/account-fallback-service.test.tsindex e845ef56e2..4cfdda2913 100644--- a/tests/unit/account-fallback-service.test.ts+++ b/tests/unit/account-fallback-service.test.ts@@ -5,6 +5,7 @@ const accountFallback = await import("../../open-sse/services/accountFallback.tsconst accountSelector = await import("../../open-sse/services/accountSelector.ts");const { RateLimitReason, COOLDOWN_MS, PROVIDER_PROFILES } =await import("../../open-sse/config/constants.ts");+const { getCircuitBreaker } = await import("../../src/shared/utils/circuitBreaker.ts");const {isOAuthInvalidToken,@@ -468,6 +469,31 @@ test("recordProviderFailure tracks failures and triggers cooldown after threshol}});+test("recordProviderFailure honors runtime provider breaker profile", () => {+ const provider = "test-provider-runtime-profile";+ clearProviderFailure(provider);++ try {+ const runtimeProfile = {+ failureThreshold: PROVIDER_PROFILES.apikey.circuitBreakerThreshold + 7,+ resetTimeoutMs: PROVIDER_PROFILES.apikey.circuitBreakerReset + 45_000,+ };++ recordProviderFailure(provider, undefined, "conn-runtime-profile", runtimeProfile);++ const breaker = getCircuitBreaker(provider);+ assert.equal(breaker.failureThreshold, runtimeProfile.failureThreshold);+ assert.equal(breaker.resetTimeout, runtimeProfile.resetTimeoutMs);+ assert.equal(isProviderInCooldown(provider), false);++ const breakerAfterStatusCheck = getCircuitBreaker(provider);+ assert.equal(breakerAfterStatusCheck.failureThreshold, runtimeProfile.failureThreshold);+ assert.equal(breakerAfterStatusCheck.resetTimeout, runtimeProfile.resetTimeoutMs);+ } finally {+ clearProviderFailure(provider);+ }+});+test("checkFallbackError no longer mutates provider breaker state on per-connection failures", () => {const provider = "test-provider-check";clearProviderFailure(provider);diff --git a/tests/unit/api-auth.test.ts b/tests/unit/api-auth.test.tsindex ee69a48679..bf6aca4e35 100644--- a/tests/unit/api-auth.test.ts+++ b/tests/unit/api-auth.test.ts@@ -63,6 +63,8 @@ test("isPublicRoute recognizes allowed API prefixes", () => {assert.equal(apiAuth.isPublicRoute("/api/auth/login"), true);assert.equal(apiAuth.isPublicRoute("/api/v1/chat/completions"), true);assert.equal(apiAuth.isPublicRoute("/api/sync/bundle"), true);+ assert.equal(apiAuth.isPublicRoute("/api/monitoring/health", "GET"), true);+ assert.equal(apiAuth.isPublicRoute("/api/monitoring/health", "DELETE"), false);assert.equal(apiAuth.isPublicRoute("/api/settings"), false);});@@ -152,6 +154,18 @@ test("isAuthenticated rejects bearer API keys on management routes", async () =>assert.equal(result, false);});+test("monitoring health reset route requires dashboard authentication", async () => {+ process.env.INITIAL_PASSWORD = "bootstrap-password";+ await localDb.updateSettings({ requireLogin: true, password: "" });++ const healthRoute = await import("../../src/app/api/monitoring/health/route.ts");+ const response = await healthRoute.DELETE(+ new Request("https://example.com/api/monitoring/health", { method: "DELETE" })+ );++ assert.equal(response.status, 401);+});+test("isAuthenticated returns false when auth is required without valid credentials", async () => {// Force requireLogin to be activeprocess.env.INITIAL_PASSWORD = "bootstrap-password";diff --git a/tests/unit/api/compression/compression-api.test.ts b/tests/unit/api/compression/compression-api.test.tsindex bdf68f61d4..bf91469dce 100644--- a/tests/unit/api/compression/compression-api.test.ts+++ b/tests/unit/api/compression/compression-api.test.ts@@ -7,7 +7,15 @@ const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);describe("Compression Settings API Schema Validation", () => {- const compressionModeValues = ["off", "lite", "standard", "aggressive", "ultra"];+ const compressionModeValues = [+ "off",+ "lite",+ "standard",+ "aggressive",+ "ultra",+ "rtk",+ "stacked",+ ];it("should validate all compression mode values", () => {assert.deepStrictEqual(compressionModeValues, [@@ -16,6 +24,8 @@ describe("Compression Settings API Schema Validation", () => {"standard","aggressive","ultra",+ "rtk",+ "stacked",]);});diff --git a/tests/unit/autocombo-unification.test.ts b/tests/unit/autocombo-unification.test.tsindex 4ff04fa2dc..a242f83628 100644--- a/tests/unit/autocombo-unification.test.ts+++ b/tests/unit/autocombo-unification.test.ts@@ -50,17 +50,19 @@ test("filterCombosByStrategyCategory returns expected combo subsets", () => {});test("combo strategies stay aligned between UI metadata and schema validation", async () => {- const { ROUTING_STRATEGIES } = await import("../../src/shared/constants/routingStrategies.ts");+ const { ROUTING_STRATEGIES, ROUTING_STRATEGY_VALUES, normalizeRoutingStrategy } =+ await import("../../src/shared/constants/routingStrategies.ts");const { comboStrategySchema, createComboSchema } =await import("../../src/shared/validation/schemas.ts");+ const { comboSchema } = await import("../../src/shared/schemas/validation.ts");+ const { setRoutingStrategyInput } = await import("../../open-sse/mcp-server/schemas/tools.ts");const strategyValues = ROUTING_STRATEGIES.map((strategy) => strategy.value);- assert.equal(strategyValues.length, 13);- assert.equal(new Set(strategyValues).size, 13);+ assert.deepEqual(strategyValues, [...ROUTING_STRATEGY_VALUES]);+ assert.equal(new Set(strategyValues).size, ROUTING_STRATEGY_VALUES.length);assert.equal(strategyValues.includes("auto"), true);assert.equal(strategyValues.includes("lkgp"), true);- assert.equal(comboStrategySchema.options.length, 13);- assert.equal(new Set(comboStrategySchema.options).size, 13);+ assert.deepEqual(comboStrategySchema.options, [...ROUTING_STRATEGY_VALUES]);strategyValues.forEach((strategy) => {const parsed = createComboSchema.safeParse({@@ -69,8 +71,27 @@ test("combo strategies stay aligned between UI metadata and schema validation",strategy,});assert.equal(parsed.success, true, `schema should accept strategy ${strategy}`);+ assert.equal(+ comboSchema.safeParse({+ name: `legacy-combo-${strategy}`,+ model: "openai/gpt-4o-mini",+ strategy,+ nodes: [{ connectionId: crypto.randomUUID() }],+ }).success,+ true,+ `legacy combo schema should accept strategy ${strategy}`+ );+ assert.equal(+ setRoutingStrategyInput.safeParse({ comboId: "combo", strategy }).success,+ true,+ `MCP set strategy schema should accept ${strategy}`+ );});+ assert.equal(normalizeRoutingStrategy("usage"), "least-used");+ assert.equal(normalizeRoutingStrategy("context"), "context-optimized");+ assert.equal(normalizeRoutingStrategy("unknown"), "priority");+const invalidParse = createComboSchema.safeParse({name: "combo-invalid",models: ["openai/gpt-4o-mini"],diff --git a/tests/unit/bulk-paste-api-keys.test.ts b/tests/unit/bulk-paste-api-keys.test.tsnew file mode 100644index 0000000000..edff45de26--- /dev/null+++ b/tests/unit/bulk-paste-api-keys.test.ts@@ -0,0 +1,103 @@+import test from "node:test";+import assert from "node:assert/strict";++const { parseExtraApiKeys } = await import("../../src/shared/utils/parseApiKeys.ts");++// ─── Core parsing ──────────────────────────────────────────────────────────++test("parses newline-separated keys into an added array", () => {+ const result = parseExtraApiKeys("sk-key1\nsk-key2\nsk-key3", []);+ assert.deepEqual(result.added, ["sk-key1", "sk-key2", "sk-key3"]);+ assert.equal(result.duplicates, 0);+});++test("handles CRLF line endings", () => {+ const result = parseExtraApiKeys("sk-key1\r\nsk-key2\r\nsk-key3", []);+ assert.deepEqual(result.added, ["sk-key1", "sk-key2", "sk-key3"]);+ assert.equal(result.duplicates, 0);+});++test("trims leading and trailing whitespace from each key", () => {+ const result = parseExtraApiKeys(" sk-key1 \n\t sk-key2 \t\n sk-key3", []);+ assert.deepEqual(result.added, ["sk-key1", "sk-key2", "sk-key3"]);+ assert.equal(result.duplicates, 0);+});++// ─── Empty / blank line handling ───────────────────────────────────────────++test("ignores blank lines between keys", () => {+ const result = parseExtraApiKeys("sk-key1\n\n\nsk-key2\n\n", []);+ assert.deepEqual(result.added, ["sk-key1", "sk-key2"]);+ assert.equal(result.duplicates, 0);+});++test("ignores whitespace-only lines", () => {+ const result = parseExtraApiKeys("sk-key1\n \n\t\nsk-key2", []);+ assert.deepEqual(result.added, ["sk-key1", "sk-key2"]);+ assert.equal(result.duplicates, 0);+});++test("returns empty result for an empty string", () => {+ const result = parseExtraApiKeys("", []);+ assert.deepEqual(result.added, []);+ assert.equal(result.duplicates, 0);+});++test("returns empty result for a whitespace-only string", () => {+ const result = parseExtraApiKeys(" \n \n ", []);+ assert.deepEqual(result.added, []);+ assert.equal(result.duplicates, 0);+});++// ─── Single key ────────────────────────────────────────────────────────────++test("handles a single key with no newlines", () => {+ const result = parseExtraApiKeys("sk-onlyone", []);+ assert.deepEqual(result.added, ["sk-onlyone"]);+ assert.equal(result.duplicates, 0);+});++// ─── Duplicate detection ───────────────────────────────────────────────────++test("counts duplicates against the existing keys list", () => {+ const result = parseExtraApiKeys("sk-key1\nsk-key2", ["sk-key1"]);+ assert.deepEqual(result.added, ["sk-key2"]);+ assert.equal(result.duplicates, 1);+});++test("deduplicates repeated keys within the pasted input", () => {+ const result = parseExtraApiKeys("sk-key1\nsk-key2\nsk-key1", []);+ assert.deepEqual(result.added, ["sk-key1", "sk-key2"]);+ assert.equal(result.duplicates, 1);+});++test("counts a key appearing three times in input as two duplicates", () => {+ const result = parseExtraApiKeys("sk-abc\nsk-abc\nsk-abc", []);+ assert.deepEqual(result.added, ["sk-abc"]);+ assert.equal(result.duplicates, 2);+});++test("returns empty added array when all pasted keys already exist", () => {+ const result = parseExtraApiKeys("sk-key1\nsk-key2", ["sk-key1", "sk-key2"]);+ assert.deepEqual(result.added, []);+ assert.equal(result.duplicates, 2);+});++test("handles a mix of new keys and duplicates from existing list", () => {+ const result = parseExtraApiKeys("sk-old\nsk-new1\nsk-old\nsk-new2", ["sk-old"]);+ assert.deepEqual(result.added, ["sk-new1", "sk-new2"]);+ assert.equal(result.duplicates, 2); // sk-old appears in existing AND is repeated in paste+});++// ─── Existing list edge cases ──────────────────────────────────────────────++test("works correctly when existing list is empty", () => {+ const result = parseExtraApiKeys("sk-a\nsk-b", []);+ assert.deepEqual(result.added, ["sk-a", "sk-b"]);+ assert.equal(result.duplicates, 0);+});++test("preserves insertion order for added keys", () => {+ const result = parseExtraApiKeys("sk-z\nsk-a\nsk-m", []);+ assert.deepEqual(result.added, ["sk-z", "sk-a", "sk-m"]);+});diff --git a/tests/unit/call-log-cap.test.ts b/tests/unit/call-log-cap.test.tsindex ed8d108238..1bb8434d11 100644--- a/tests/unit/call-log-cap.test.ts+++ b/tests/unit/call-log-cap.test.ts@@ -630,7 +630,7 @@ test("saveCallLog falls back to a compact sentinel when the configured cap is veconst artifactPath = path.join(TEST_DATA_DIR, "call_logs", (row as any).artifact_relpath);const artifact = JSON.parse(fs.readFileSync(artifactPath, "utf8"));assert.deepEqual(artifact, {- schemaVersion: 4,+ schemaVersion: 5,_omniroute_truncated: true,reason: "call_log_artifact_size_limit_exceeded",});diff --git a/tests/unit/combo-routing-engine.test.ts b/tests/unit/combo-routing-engine.test.tsindex ca40725d0d..7079a800a4 100644--- a/tests/unit/combo-routing-engine.test.ts+++ b/tests/unit/combo-routing-engine.test.ts@@ -432,6 +432,73 @@ test("handleComboChat random strategy uses shuffled model order", async () => {}});+test("handleComboChat fill-first explicitly preserves priority order", async () => {+ const calls: any[] = [];++ await handleComboChat({+ body: {},+ combo: {+ name: "fill-first-order",+ strategy: "fill-first",+ models: ["model-a", "model-b"],+ },+ handleSingleModel: async (_body: any, modelStr: any) => {+ calls.push(modelStr);+ return okResponse();+ },+ isModelAvailable: async () => true,+ log: createLog(),+ settings: null,+ relayOptions: null as any,+ allCombos: null,+ });++ assert.deepEqual(calls, ["model-a"]);+});++test("handleComboChat p2c selects the better of two random choices by metrics", async () => {+ const originalRandom = Math.random;+ const calls: any[] = [];+ const sequence = [0.0, 0.0];+ let idx = 0;++ recordComboRequest("p2c-combo", "model-a", {+ success: true,+ latencyMs: 2000,+ strategy: "p2c",+ });+ recordComboRequest("p2c-combo", "model-b", {+ success: true,+ latencyMs: 20,+ strategy: "p2c",+ });+ Math.random = () => sequence[idx++] ?? 0;++ try {+ await handleComboChat({+ body: {},+ combo: {+ name: "p2c-combo",+ strategy: "p2c",+ models: ["model-a", "model-b", "model-c"],+ },+ handleSingleModel: async (_body: any, modelStr: any) => {+ calls.push(modelStr);+ return okResponse();+ },+ isModelAvailable: async () => true,+ log: createLog(),+ settings: null,+ relayOptions: null as any,+ allCombos: null,+ });++ assert.deepEqual(calls, ["model-b"]);+ } finally {+ Math.random = originalRandom;+ }+});+test("handleComboChat least-used strategy prefers the model with fewer recorded requests", async () => {recordComboRequest("least-used-combo", "model-a", {success: true,@@ -1318,6 +1385,59 @@ test("handleComboChat context-optimized orders models by the largest synced contassert.equal(calls[0], "openai/gpt-4o-max");});+test("handleComboChat context-optimized preserves order when all context limits are unknown", async () => {+ const calls: any[] = [];+ const result = await handleComboChat({+ body: {},+ combo: {+ name: "context-optimized-unknown",+ strategy: "context-optimized",+ models: ["unknown/model-a", "unknown/model-b"],+ },+ handleSingleModel: async (_body: any, modelStr: any) => {+ calls.push(modelStr);+ return okResponse();+ },+ isModelAvailable: async () => true,+ log: createLog(),+ settings: null,+ relayOptions: null as any,+ allCombos: null,+ });++ assert.equal(result.ok, true);+ assert.deepEqual(calls, ["unknown/model-a"]);+});++test("handleComboChat normalizes legacy strategy names at runtime", async () => {+ const usageCalls: any[] = [];+ recordComboRequest("legacy-usage-combo", "model-a", {+ success: true,+ latencyMs: 100,+ strategy: "least-used",+ });++ await handleComboChat({+ body: {},+ combo: {+ name: "legacy-usage-combo",+ strategy: "usage",+ models: ["model-a", "model-b"],+ },+ handleSingleModel: async (_body: any, modelStr: any) => {+ usageCalls.push(modelStr);+ return okResponse();+ },+ isModelAvailable: async () => true,+ log: createLog(),+ settings: null,+ relayOptions: null as any,+ allCombos: null,+ });++ assert.deepEqual(usageCalls, ["model-b"]);+});+test("handleComboChat returns a 503 when every model is unavailable before execution", async () => {const result = await handleComboChat({body: {},diff --git a/tests/unit/combo-strategies.test.ts b/tests/unit/combo-strategies.test.tsindex 3a4acc84d0..65d62c88dd 100644--- a/tests/unit/combo-strategies.test.ts+++ b/tests/unit/combo-strategies.test.ts@@ -1,21 +1,28 @@-import test from "node:test";+import test, { after } from "node:test";import assert from "node:assert/strict";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";-import { handleComboChat } from "../../open-sse/services/combo.ts";-import * as combosDb from "../../src/lib/db/combos.ts";-import * as modelsDb from "../../src/lib/db/models.ts";--function stubConnection() {- return [- {- id: "conn-openai",- provider: "openai",- authType: "oauth",- isActive: 1,- accessToken: "token",- },- ];-}+const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-combo-strategies-"));+const ORIGINAL_DATA_DIR = process.env.DATA_DIR;+process.env.DATA_DIR = TEST_DATA_DIR;++const dbCore = await import("../../src/lib/db/core.ts");+const { handleComboChat } = await import("../../open-sse/services/combo.ts");+const combosDb = await import("../../src/lib/db/combos.ts");+const { recordComboRequest } = await import("../../open-sse/services/comboMetrics.ts");+const { saveModelsDevCapabilities } = await import("../../src/lib/modelsDevSync.ts");++after(() => {+ dbCore.resetDbInstance();+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });+ if (ORIGINAL_DATA_DIR === undefined) {+ delete process.env.DATA_DIR;+ } else {+ process.env.DATA_DIR = ORIGINAL_DATA_DIR;+ }+});const reqBodyNullContext = {model: "comboTest",@@ -29,78 +36,113 @@ const reqBodyTextArray = {stream: false,};-test("handleComboChat with 'usage' strategy hits sortModelsByUsage", async () => {- const id = crypto.randomUUID();- await combosDb.createCombo({- id,- name: id,- strategy: "usage",- models: ["openai/gpt-3.5-turbo", "openai/gpt-4"],- });+function capability(limitContext: number) {+ return {+ tool_call: true,+ reasoning: null,+ attachment: null,+ structured_output: null,+ temperature: null,+ modalities_input: "[]",+ modalities_output: "[]",+ knowledge_cutoff: null,+ release_date: null,+ last_updated: null,+ status: null,+ family: null,+ open_weights: null,+ limit_context: limitContext,+ limit_input: null,+ limit_output: null,+ interleaved_field: null,+ };+}++function okResponse(model: string) {+ return Response.json({ choices: [{ message: { role: "assistant", content: model } }] });+}++function makeLog() {+ return {+ info() {},+ warn() {},+ debug() {},+ error() {},+ };+}- // No proxy/http mock needed if we expect error or quick reject- const req = new Request("http://localhost", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ ...reqBodyTextArray, model: id }),+async function selectedModelFor(combo: Record<string, unknown>, body: Record<string, unknown>) {+ const calls: string[] = [];+ const response = await handleComboChat({+ body,+ combo,+ allCombos: [combo],+ isModelAvailable: undefined,+ relayOptions: undefined,+ signal: undefined,+ settings: {},+ log: makeLog(),+ handleSingleModel: async (_body: unknown, modelStr: string) => {+ calls.push(modelStr);+ return okResponse(modelStr);+ },});- try {- const res = await handleComboChat(id, req, stubConnection());- assert.equal(res.status >= 200, true);- } catch (e: any) {- // Expect error as fetch is not globally mocked for this quick edge branch test, that's fine- }-});+ assert.equal(response.status, 200);+ assert.equal(calls.length > 0, true);+ return calls[0];+}-test("handleComboChat with 'context' strategy hits sortModelsByContextSize", async () => {- const id = crypto.randomUUID();- await combosDb.createCombo({- id,- name: id,- strategy: "context",- models: ["openai/gpt-4-32k", "openai/gpt-4", "unknown/unknown"],+test("least-used strategy prefers the model with fewer recorded combo requests", async () => {+ const name = `least-used-${crypto.randomUUID()}`;+ const busyModel = "openai/gpt-4";+ const idleModel = "openai/gpt-3.5-turbo";+ const combo = await combosDb.createCombo({+ name,+ strategy: "least-used",+ models: [busyModel, idleModel],});- const req = new Request("http://localhost", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ ...reqBodyNullContext, model: id }),+ recordComboRequest(name, busyModel, {+ success: true,+ latencyMs: 10,+ strategy: "least-used",});- try {- const res = await handleComboChat(id, req, stubConnection());- } catch (e: any) {}+ assert.equal(await selectedModelFor(combo, reqBodyTextArray), idleModel);});-test("handleComboChat hits extractPromptForIntent edge cases", async () => {- const id = crypto.randomUUID();- await combosDb.createCombo({- id,- name: id,- strategy: "auto",- autoConfig: { intentConfig: { enabled: true } },- models: ["openai/gpt-4"],+test("context-optimized strategy prefers the largest context window", async () => {+ saveModelsDevCapabilities({+ "test-context": {+ small: capability(8_000),+ large: capability(64_000),+ },});- // Null message content- const reqNull = new Request("http://localhost", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ model: id, messages: [{ role: "user", content: null }] }),+ const combo = await combosDb.createCombo({+ name: `context-optimized-${crypto.randomUUID()}`,+ strategy: "context-optimized",+ models: ["test-context/small", "test-context/large", "unknown/unknown"],});- // Empty messages array- const reqEmpty = new Request("http://localhost", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ model: id, messages: [] }),+ assert.equal(await selectedModelFor(combo, reqBodyNullContext), "test-context/large");+});++test("auto strategy handles null and empty prompt edge cases without throwing", async () => {+ const combo = await combosDb.createCombo({+ name: `auto-${crypto.randomUUID()}`,+ strategy: "auto",+ config: { auto: { explorationRate: 0 } },+ models: ["openai/gpt-4"],});- try {- await handleComboChat(id, reqNull, stubConnection());- } catch (e: any) {}- try {- await handleComboChat(id, reqEmpty, stubConnection());- } catch (e: any) {}+ assert.equal(+ await selectedModelFor(combo, {+ model: combo.name,+ messages: [{ role: "user", content: null }],+ }),+ "openai/gpt-4"+ );+ assert.equal(await selectedModelFor(combo, { model: combo.name, messages: [] }), "openai/gpt-4");});diff --git a/tests/unit/compression-tokens.test.ts b/tests/unit/compression-tokens.test.tsnew file mode 100644index 0000000000..a7a5a422b8--- /dev/null+++ b/tests/unit/compression-tokens.test.ts@@ -0,0 +1,98 @@+/**+ * @file Unit tests for tokens_compressed tracking in call logs.+ *+ * Assumes migrations work. Tests functional behavior only.+ */+import test from "node:test";+import assert from "node:assert/strict";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";++const root = path.resolve(import.meta.dirname, "../..");++async function freshImport(modulePath: string) {+ return import(`${modulePath}?q=${Date.now()}-${Math.random().toString(16).slice(2)}`);+}++function setupTempDataDir() {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-comp"));+ process.env.DATA_DIR = dir;+ process.env.OMNIROUTE_MIGRATIONS_DIR = path.join(root, "src/lib/db/migrations");+ process.env.DISABLE_SQLITE_AUTO_BACKUP = "true";+ return dir;+}++test("tokensCompressed round-trips through saveCallLog → getCallLogs", async () => {+ const dir = setupTempDataDir();+ try {+ const core = await freshImport("../../src/lib/db/core.ts");+ core.resetDbInstance();++ const db = core.getDbInstance();+ const runner = await freshImport("../../src/lib/db/migrationRunner.ts");+ runner.runMigrations(db);++ const callLogs = await freshImport("../../src/lib/usage/callLogs.ts");++ // Log without compression+ await callLogs.saveCallLog({+ id: "log-null",+ method: "POST",+ path: "/v1/chat/completions",+ status: 200,+ model: "gpt-4",+ provider: "openai",+ duration: 1000,+ tokens: { input: 120, output: 45 },+ requestBody: null,+ responseBody: null,+ });++ // Log with compression+ await callLogs.saveCallLog({+ id: "log-350",+ method: "POST",+ path: "/v1/chat/completions",+ status: 200,+ model: "gpt-4",+ provider: "openai",+ duration: 2000,+ tokens: { input: 1000, output: 500 },+ tokensCompressed: 350,+ requestBody: null,+ responseBody: null,+ });++ const logs = await callLogs.getCallLogs({+ limit: 10,+ });++ const logNull = logs.find(+ (l: { id: string }) => l.id === "log-null"+ );+ const logComp = logs.find(+ (l: { id: string }) => l.id === "log-350"+ );++ // null when no compression+ assert.equal(+ logNull.tokens?.compressed,+ null,+ "uncompressed log should have null compressed"+ );++ // Positive value when compressed+ assert.equal(+ logComp.tokens?.compressed,+ 350,+ "compressed log should store exact token delta"+ );++ // Input tokens unaffected+ assert.equal(logComp.tokens?.in, 1000);+ assert.equal(logComp.tokens?.out, 500);+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});diff --git a/tests/unit/compression/caveman-v379.test.ts b/tests/unit/compression/caveman-v379.test.tsnew file mode 100644index 0000000000..00e8acdfff--- /dev/null+++ b/tests/unit/compression/caveman-v379.test.ts@@ -0,0 +1,182 @@+import { describe, it } from "node:test";+import assert from "node:assert/strict";+import { cavemanCompress } from "../../../open-sse/services/compression/caveman.ts";+import {+ getCavemanRuleMetadata,+ 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("preserves articles before proper nouns, numbers, and code-like tokens", () => {+ const text = compress(+ "Use the OpenAI API, the 404 error, the config.api.endpoint() function, and the database."+ );++ assert.match(text, /\bthe OpenAI API\b/);+ assert.match(text, /\bthe 404 error\b/);+ assert.match(text, /\bthe config\.api\.endpoint\(\) function\b/);+ assert.doesNotMatch(text, /\bthe database\b/i);+ });++ it("removes upstream Caveman pleasantry variants without breaking make sure to", () => {+ const text = compress(+ "Thanks, thank you, glad to help, I'd be glad to, no problem, you're welcome, absolutely. Please make sure to review the database."+ );++ for (const phrase of [+ "thanks",+ "thank you",+ "glad to help",+ "I'd be glad to",+ "no problem",+ "you're welcome",+ "absolutely",+ ]) {+ assert.doesNotMatch(text, new RegExp(phrase.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "i"));+ }+ assert.match(text, /\bensure review database\b/i);+ });++ 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", () => {+ const metadata = getCavemanRuleMetadata();+ for (const ruleName of [+ "articles",+ "pleasantries",+ "leader_phrases",+ "redundant_phrasing",+ "ultra_abbreviations",+ ]) {+ assert.ok(getRuleByName(ruleName), `missing rule ${ruleName}`);+ const rule = metadata.find((entry) => entry.name === ruleName);+ assert.ok(rule?.category, `missing metadata category for ${ruleName}`);+ assert.ok(rule?.intensities?.length, `missing metadata intensities for ${ruleName}`);+ }+ });+});diff --git a/tests/unit/compression/compression-aggressive.test.ts b/tests/unit/compression/compression-aggressive.test.tsindex 2211a70cf5..3a767bf7b0 100644--- a/tests/unit/compression/compression-aggressive.test.ts+++ b/tests/unit/compression/compression-aggressive.test.ts@@ -148,6 +148,26 @@ describe("Integration: strategySelector → aggressive pipeline", () => {assert.equal(systemMsg!.content, "You are a helpful coding assistant.");});+ it("compressAggressive preserves duplicate system prompts during lite fallback", () => {+ const messages = [+ { role: "system", content: "Policy exact. Keep exact." },+ { role: "system", content: "Policy exact. Keep exact." },+ { role: "user", content: "Short" },+ ];++ const result = compressAggressive(messages, {+ preserveSystemPrompt: true,+ minSavingsThreshold: 0.9,+ summarizerEnabled: false,+ maxTokensPerMessage: 999999,+ });++ assert.deepEqual(+ result.messages.filter((message) => message.role === "system"),+ messages.filter((message) => message.role === "system")+ );+ });+it("compressAggressive downgrade chain works when aggressive fails", () => {// Empty messages should trigger downgrade gracefullyconst result = compressAggressive([]);diff --git a/tests/unit/compression/compression-combos-db.test.ts b/tests/unit/compression/compression-combos-db.test.tsnew file mode 100644index 0000000000..0b58800334--- /dev/null+++ b/tests/unit/compression/compression-combos-db.test.ts@@ -0,0 +1,132 @@+import test from "node:test";+import assert from "node:assert/strict";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";++const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-compression-combos-"));+const ORIGINAL_DATA_DIR = process.env.DATA_DIR;+process.env.DATA_DIR = TEST_DATA_DIR;++const core = await import("../../../src/lib/db/core.ts");+const combosDb = await import("../../../src/lib/db/compressionCombos.ts");++async function resetStorage() {+ core.resetDbInstance();+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });+ fs.mkdirSync(TEST_DATA_DIR, { recursive: true });+}++test.beforeEach(async () => {+ await resetStorage();+});++test.after(() => {+ core.resetDbInstance();+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });+ if (ORIGINAL_DATA_DIR === undefined) {+ delete process.env.DATA_DIR;+ } else {+ process.env.DATA_DIR = ORIGINAL_DATA_DIR;+ }+});++test("creates default compression combo automatically", () => {+ const combos = combosDb.listCompressionCombos();+ const combo = combos.find((item) => item.id === "default-caveman");++ assert.equal(combo?.isDefault, true);+ assert.equal(combo?.description, "Default RTK + Caveman compression pipeline");+ assert.deepEqual(combo?.pipeline, [+ { engine: "rtk", intensity: "standard" },+ { engine: "caveman", intensity: "full" },+ ]);+});++test("upgrades the legacy seeded default compression combo pipeline", () => {+ const db = core.getDbInstance();+ db.prepare(+ `+ UPDATE compression_combos+ SET description = ?, pipeline = ?+ WHERE id = ?+ `+ ).run(+ "Default Caveman compression pipeline",+ JSON.stringify([{ engine: "caveman", intensity: "full" }]),+ "default-caveman"+ );++ const combo = combosDb.getDefaultCompressionCombo();+ assert.equal(combo?.id, "default-caveman");+ assert.equal(combo?.description, "Default RTK + Caveman compression pipeline");+ assert.deepEqual(combo?.pipeline, [+ { engine: "rtk", intensity: "standard" },+ { engine: "caveman", intensity: "full" },+ ]);+});++test("does not overwrite a customized default compression combo", () => {+ const db = core.getDbInstance();+ db.prepare(+ `+ UPDATE compression_combos+ SET name = ?, description = ?, pipeline = ?+ WHERE id = ?+ `+ ).run(+ "Custom Default",+ "User changed",+ JSON.stringify([{ engine: "caveman", intensity: "lite" }]),+ "default-caveman"+ );++ const combo = combosDb.getDefaultCompressionCombo();+ assert.equal(combo?.id, "default-caveman");+ assert.equal(combo?.name, "Custom Default");+ assert.equal(combo?.description, "User changed");+ assert.deepEqual(combo?.pipeline, [{ engine: "caveman", intensity: "lite" }]);+});++test("creates, updates and protects default compression combos", () => {+ const combo = combosDb.createCompressionCombo({+ name: "RTK first",+ pipeline: [{ engine: "rtk", intensity: "standard" }],+ languagePacks: ["en", "pt-BR"],+ });+ assert.equal(combo.name, "RTK first");+ assert.equal(combo.pipeline[0].engine, "rtk");++ const updated = combosDb.updateCompressionCombo(combo.id, {+ description: "Updated",+ isDefault: true,+ });+ assert.equal(updated?.description, "Updated");+ assert.equal(combosDb.getDefaultCompressionCombo()?.id, combo.id);++ assert.equal(combosDb.deleteCompressionCombo("default-caveman"), true);+ assert.equal(combosDb.deleteCompressionCombo(combo.id), false);+});++test("assigns routing combos to compression combos", () => {+ const combo = combosDb.createCompressionCombo({+ name: "Stacked",+ pipeline: [+ { engine: "rtk", intensity: "standard" },+ { engine: "caveman", intensity: "full" },+ ],+ });++ assert.equal(combosDb.assignRoutingCombo(combo.id, "routing-a"), true);+ assert.equal(combosDb.getCompressionComboForRoutingCombo("routing-a")?.id, combo.id);+ assert.deepEqual(+ combosDb+ .getAssignmentsForCompressionCombo(combo.id)+ .map((assignment) => assignment.routingComboId),+ ["routing-a"]+ );++ assert.equal(combosDb.updateAssignments(combo.id, ["routing-b", "routing-c"]), true);+ assert.equal(combosDb.getCompressionComboForRoutingCombo("routing-a"), null);+ assert.equal(combosDb.getCompressionComboForRoutingCombo("routing-b")?.id, combo.id);+});diff --git a/tests/unit/compression/compression-preview-api.test.ts b/tests/unit/compression/compression-preview-api.test.tsnew file mode 100644index 0000000000..9a34952d15--- /dev/null+++ b/tests/unit/compression/compression-preview-api.test.ts@@ -0,0 +1,65 @@+import { describe, it } from "node:test";+import assert from "node:assert/strict";++import {+ PreviewCompressionConfigSchema,+ PreviewRequestSchema,+} from "../../../src/app/api/compression/preview/route.ts";++describe("compression preview API contract", () => {+ it("accepts RTK and stacked preview payloads", () => {+ assert.equal(+ PreviewRequestSchema.safeParse({+ messages: [{ role: "tool", content: "same\nsame\nsame" }],+ mode: "rtk",+ config: {+ rtkConfig: {+ intensity: "standard",+ applyToToolResults: true,+ customFiltersEnabled: true,+ rawOutputRetention: "never",+ },+ },+ }).success,+ true+ );++ assert.equal(+ PreviewRequestSchema.safeParse({+ messages: [{ role: "tool", content: "same\nsame\nsame" }],+ mode: "stacked",+ config: {+ stackedPipeline: [+ { engine: "rtk", intensity: "standard" },+ { engine: "caveman", intensity: "full" },+ ],+ },+ }).success,+ true+ );+ });++ it("rejects invalid preview config instead of accepting arbitrary records", () => {+ assert.equal(PreviewCompressionConfigSchema.safeParse({ unknown: true }).success, false);+ assert.equal(+ PreviewRequestSchema.safeParse({+ messages: [{ role: "tool", content: "x" }],+ mode: "rtk",+ config: { rtkConfig: { intensity: "extreme" } },+ }).success,+ false+ );+ assert.equal(+ PreviewCompressionConfigSchema.safeParse({+ stackedPipeline: [{ engine: "rtk", intensity: "bogus" }],+ }).success,+ false+ );+ assert.equal(+ PreviewCompressionConfigSchema.safeParse({+ stackedPipeline: [{ engine: "rtk", config: { maxLinesPerResult: -1 } }],+ }).success,+ false+ );+ });+});diff --git a/tests/unit/compression/compression-preview-auth.test.ts b/tests/unit/compression/compression-preview-auth.test.tsnew file mode 100644index 0000000000..b5bfb1332e--- /dev/null+++ b/tests/unit/compression/compression-preview-auth.test.ts@@ -0,0 +1,155 @@+import test from "node:test";+import assert from "node:assert/strict";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";++import { makeManagementSessionRequest } from "../../helpers/managementSession.ts";++const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-compression-preview-"));+const originalDataDir = process.env.DATA_DIR;+const originalJwtSecret = process.env.JWT_SECRET;++process.env.DATA_DIR = TEST_DATA_DIR;++const core = await import("../../../src/lib/db/core.ts");+const settingsDb = await import("../../../src/lib/db/settings.ts");+const previewRoute = await import("../../../src/app/api/compression/preview/route.ts");+const languagePacksRoute = await import("../../../src/app/api/compression/language-packs/route.ts");+const rulesRoute = await import("../../../src/app/api/compression/rules/route.ts");++type ErrorResponseBody = {+ error: string | { message?: string };+};++async function resetAuthRequiredStorage(): Promise<void> {+ core.resetDbInstance();+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });+ fs.mkdirSync(TEST_DATA_DIR, { recursive: true });+ await settingsDb.updateSettings({+ requireLogin: true,+ setupComplete: true,+ password: "test-password-hash",+ });+}++test.beforeEach(async () => {+ process.env.DATA_DIR = TEST_DATA_DIR;+ await resetAuthRequiredStorage();+});++test.after(() => {+ if (originalDataDir === undefined) delete process.env.DATA_DIR;+ else process.env.DATA_DIR = originalDataDir;+ if (originalJwtSecret === undefined) delete process.env.JWT_SECRET;+ else process.env.JWT_SECRET = originalJwtSecret;+ core.resetDbInstance();+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });+});++test("compression preview requires management auth before reading preview input", async () => {+ const response = await previewRoute.POST(+ new Request("http://localhost/api/compression/preview", {+ method: "POST",+ body: JSON.stringify({+ messages: [{ role: "tool", content: "same\nsame\nsame" }],+ mode: "rtk",+ }),+ })+ );+ const body = (await response.json()) as ErrorResponseBody;++ assert.equal(response.status, 401);+ assert.equal(+ typeof body.error === "object" ? body.error.message : null,+ "Authentication required"+ );+});++test("compression preview rejects bearer tokens without a dashboard session", async () => {+ const response = await previewRoute.POST(+ new Request("http://localhost/api/compression/preview", {+ method: "POST",+ headers: { authorization: "Bearer invalid-management-token" },+ body: JSON.stringify({+ messages: [{ role: "tool", content: "same\nsame\nsame" }],+ mode: "rtk",+ }),+ })+ );+ const body = (await response.json()) as ErrorResponseBody;++ assert.equal(response.status, 403);+ assert.equal(+ typeof body.error === "object" ? body.error.message : null,+ "Invalid management token"+ );+});++test("compression preview still runs for authenticated management sessions", async () => {+ const request = await makeManagementSessionRequest("http://localhost/api/compression/preview", {+ method: "POST",+ body: {+ messages: [{ role: "tool", content: "same\nsame\nsame" }],+ mode: "rtk",+ config: {+ rtkConfig: {+ intensity: "standard",+ },+ },+ },+ });++ const response = await previewRoute.POST(request);+ const body = (await response.json()) as { mode?: string; original?: string };++ assert.equal(response.status, 200);+ assert.equal(body.mode, "rtk");+ assert.match(body.original || "", /same/);+});++test("compression language pack metadata requires management auth", async () => {+ const response = await languagePacksRoute.GET(+ new Request("http://localhost/api/compression/language-packs")+ );+ const body = (await response.json()) as ErrorResponseBody;++ assert.equal(response.status, 401);+ assert.equal(+ typeof body.error === "object" ? body.error.message : null,+ "Authentication required"+ );+});++test("compression rules metadata rejects bearer tokens without a dashboard session", async () => {+ const response = await rulesRoute.GET(+ new Request("http://localhost/api/compression/rules", {+ headers: { authorization: "Bearer invalid-management-token" },+ })+ );+ const body = (await response.json()) as ErrorResponseBody;++ assert.equal(response.status, 403);+ assert.equal(+ typeof body.error === "object" ? body.error.message : null,+ "Invalid management token"+ );+});++test("compression metadata routes return data for authenticated management sessions", async () => {+ const languageRequest = await makeManagementSessionRequest(+ "http://localhost/api/compression/language-packs"+ );+ const rulesRequest = await makeManagementSessionRequest("http://localhost/api/compression/rules");++ const languageResponse = await languagePacksRoute.GET(languageRequest);+ const rulesResponse = await rulesRoute.GET(rulesRequest);+ const languageBody = (await languageResponse.json()) as { languages?: unknown; packs?: unknown };+ const rulesBody = (await rulesResponse.json()) as { rules?: unknown };++ assert.equal(languageResponse.status, 200);+ assert.ok(Array.isArray(languageBody.languages));+ assert.ok(Array.isArray(languageBody.packs));+ assert.equal(rulesResponse.status, 200);+ assert.ok(Array.isArray(rulesBody.rules));+});diff --git a/tests/unit/compression/compressionAnalytics.test.ts b/tests/unit/compression/compressionAnalytics.test.tsindex 7bfb290c01..12d1f55443 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", () => {@@ -51,9 +53,27 @@ describe("compressionAnalytics", () => {avgSavingsPct: 0,avgDurationMs: 0,byMode: {},+ byEngine: {},+ byCompressionCombo: {},byProvider: {},- last24h: [],+ last24h: summary.last24h,+ validationFallbacks: 0,+ realUsage: {+ requestsWithReceipts: 0,+ promptTokens: 0,+ completionTokens: 0,+ totalTokens: 0,+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ estimatedUsdSaved: 0,+ bySource: {},+ },+ mcpDescriptionCompression: {+ snapshots: 0,+ estimatedTokensSaved: 0,+ },});+ assert.equal(summary.last24h.length, 24);});it("insert single row does not throw", () => {@@ -249,4 +269,92 @@ 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("aggregates estimated USD savings separately from token estimates", () => {+ insertCompressionAnalyticsRow({+ timestamp: new Date().toISOString(),+ mode: "standard",+ original_tokens: 1000,+ compressed_tokens: 700,+ tokens_saved: 300,+ request_id: "req-usd",+ estimated_usd_saved: 0.0015,+ });+ attachCompressionUsageReceipt("req-usd", { prompt_tokens: 700, total_tokens: 700 }, "provider");++ const summary = getCompressionAnalyticsSummary();+ assert.equal(summary.realUsage.requestsWithReceipts, 1);+ assert.equal(summary.realUsage.estimatedUsdSaved, 0.0015);+ });++ 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);+ });++ it("summarizes MCP description estimates without counting them as provider receipts", () => {+ insertCompressionAnalyticsRow({+ timestamp: new Date().toISOString(),+ mode: "mcp-description",+ engine: "mcp-description",+ original_tokens: 20,+ compressed_tokens: 12,+ tokens_saved: 8,+ mcp_description_tokens_saved: 8,+ });++ const summary = getCompressionAnalyticsSummary();+ assert.equal(summary.mcpDescriptionCompression.snapshots, 1);+ assert.equal(summary.mcpDescriptionCompression.estimatedTokensSaved, 8);+ assert.equal(summary.realUsage.requestsWithReceipts, 0);+ assert.equal(summary.realUsage.bySource.mcp_metadata_estimate, undefined);+ });});diff --git a/tests/unit/compression/compressionMcpTools.test.ts b/tests/unit/compression/compressionMcpTools.test.tsindex 2349b72db0..09282bec51 100644--- a/tests/unit/compression/compressionMcpTools.test.ts+++ b/tests/unit/compression/compressionMcpTools.test.ts@@ -7,15 +7,30 @@ import { join } from "node:path";const tmpDir = mkdtempSync(join(tmpdir(), "omniroute-mcp-test-"));process.env.DATA_DIR = tmpDir;-const { handleCompressionStatus, handleCompressionConfigure } =- await import("../../../open-sse/mcp-server/tools/compressionTools.ts");-const { compressionConfigureTool, compressionStatusTool } =- await import("../../../open-sse/mcp-server/schemas/tools.ts");+const {+ handleCompressionStatus,+ handleCompressionConfigure,+ handleSetCompressionEngine,+ handleListCompressionCombos,+ handleCompressionComboStats,+} = await import("../../../open-sse/mcp-server/tools/compressionTools.ts");+const {+ compressionConfigureTool,+ compressionStatusTool,+ setCompressionEngineTool,+ listCompressionCombosTool,+ compressionComboStatsTool,+} = await import("../../../open-sse/mcp-server/schemas/tools.ts");+const { maybeCompressMcpDescription, resetMcpDescriptionCompressionStats } =+ await import("../../../open-sse/mcp-server/descriptionCompressor.ts");describe("compression MCP tool schemas", () => {it("uses canonical read/write compression scopes", () => {assert.deepEqual(compressionStatusTool.scopes, ["read:compression"]);assert.deepEqual(compressionConfigureTool.scopes, ["write:compression"]);+ assert.deepEqual(setCompressionEngineTool.scopes, ["write:compression"]);+ assert.deepEqual(listCompressionCombosTool.scopes, ["read:compression"]);+ assert.deepEqual(compressionComboStatsTool.scopes, ["read:compression"]);});});@@ -62,6 +77,34 @@ describe("handleCompressionStatus", () => {const result = await handleCompressionStatus({});assert.equal(typeof result.analytics.compressedRequests, "number");});++ it("labels MCP description savings as metadata estimates, not provider usage", async () => {+ const result = await handleCompressionStatus({});+ assert.equal(result.analytics.mcpDescriptionCompression.source, "mcp_metadata_estimate");+ assert.equal(result.analytics.mcpDescriptionCompression.notProviderUsage, true);+ assert.equal(typeof result.analytics.mcpDescriptionCompression.charsBefore, "number");+ assert.equal(typeof result.analytics.mcpDescriptionCompression.charsAfter, "number");+ });++ it("snapshots MCP description savings into analytics separately", async () => {+ resetMcpDescriptionCompressionStats();+ const compressed = maybeCompressMcpDescription(+ "The function returns the current weather for a city and the detailed forecast summary.",+ { enabled: true }+ );+ assert.match(compressed, /weather/i);++ const result = await handleCompressionStatus({});+ assert.ok(result.analytics.mcpDescriptionCompression.estimatedTokensSaved > 0);+ assert.ok(result.analytics.mcpDescriptionCompression.persistedEstimatedTokensSaved > 0);+ assert.ok(result.analytics.mcpDescriptionCompression.persistedSnapshots > 0);++ const stats = await handleCompressionComboStats({ since: "all" });+ const mcp = stats.mcpDescriptionCompression as { estimatedTokensSaved?: number };+ const realUsage = stats.realUsage as { bySource?: Record<string, number> };+ assert.ok((mcp.estimatedTokensSaved ?? 0) > 0);+ assert.equal(realUsage.bySource?.mcp_metadata_estimate, undefined);+ });});describe("handleCompressionConfigure", () => {@@ -91,6 +134,13 @@ describe("handleCompressionConfigure", () => {assert.equal(result.success, true);});+ it("sets RTK and stacked strategies", async () => {+ const rtkResult = await handleCompressionConfigure({ strategy: "rtk" });+ const stackedResult = await handleCompressionConfigure({ strategy: "stacked" });+ assert.equal(rtkResult.success, true);+ assert.equal(stackedResult.success, true);+ });+it("sets maxTokens and returns success", async () => {const result = await handleCompressionConfigure({ maxTokens: 8000 });assert.equal(result.success, true);@@ -107,3 +157,24 @@ describe("handleCompressionConfigure", () => {assert.equal(result.settings.targetRatio, 0.7);});});++describe("compression MCP RTK/combo tools", () => {+ it("sets RTK engine through MCP", async () => {+ const result = await handleSetCompressionEngine({ engine: "rtk", rtkIntensity: "aggressive" });+ assert.equal(result.success, true);+ assert.equal(result.settings.defaultMode, "rtk");+ assert.equal((result.settings.rtkConfig as { intensity?: string }).intensity, "aggressive");+ });++ it("lists compression combos", async () => {+ const result = await handleListCompressionCombos();+ assert.ok(Array.isArray(result.combos));+ assert.ok(result.combos.length >= 1);+ });++ it("returns combo stats summary", async () => {+ const result = await handleCompressionComboStats({ since: "all" });+ assert.ok("byCompressionCombo" in result);+ assert.ok("byEngine" in result);+ });+});diff --git a/tests/unit/compression/context-compression-api.test.ts b/tests/unit/compression/context-compression-api.test.tsnew file mode 100644index 0000000000..6cdb5719df--- /dev/null+++ b/tests/unit/compression/context-compression-api.test.ts@@ -0,0 +1,56 @@+import { describe, it } from "node:test";+import assert from "node:assert/strict";++import { rtkConfigSchema } from "../../../src/app/api/context/rtk/config/route.ts";+import { rtkTestSchema } from "../../../src/app/api/context/rtk/test/route.ts";+import { compressionComboCreateSchema } from "../../../src/app/api/context/combos/route.ts";+import { compressionComboUpdateSchema } from "../../../src/app/api/context/combos/[id]/route.ts";+import { assignmentsUpdateSchema } from "../../../src/app/api/context/combos/[id]/assignments/route.ts";++describe("context compression API schemas", () => {+ it("rejects invalid RTK config and test payloads", () => {+ assert.equal(rtkConfigSchema.safeParse({ intensity: "extreme" }).success, false);+ assert.equal(rtkConfigSchema.safeParse({ applyToCodeBlocks: true }).success, true);+ assert.equal(+ rtkConfigSchema.safeParse({+ customFiltersEnabled: true,+ trustProjectFilters: false,+ rawOutputRetention: "failures",+ rawOutputMaxBytes: 4096,+ }).success,+ true+ );+ assert.equal(rtkConfigSchema.safeParse({ rawOutputRetention: "plaintext" }).success, false);+ assert.equal(rtkTestSchema.safeParse({ text: "" }).success, false);+ assert.equal(rtkTestSchema.safeParse({ text: "ok", extra: true }).success, false);+ assert.equal(+ rtkTestSchema.safeParse({+ text: "ok",+ config: { maxLinesPerResult: -1, madeUp: true },+ }).success,+ false+ );+ });++ it("rejects invalid compression combo payloads", () => {+ assert.equal(compressionComboCreateSchema.safeParse({ name: "" }).success, false);+ assert.equal(+ compressionComboCreateSchema.safeParse({+ name: "Stacked",+ pipeline: [{ engine: "rtk", intensity: "standard" }],+ }).success,+ true+ );+ assert.equal(compressionComboUpdateSchema.safeParse({ isDefault: true }).success, true);+ assert.equal(compressionComboUpdateSchema.safeParse({ pipeline: [] }).success, false);+ assert.equal(assignmentsUpdateSchema.safeParse({ routingComboIds: ["combo-a"] }).success, true);+ assert.equal(assignmentsUpdateSchema.safeParse({ routingComboIds: [""] }).success, false);+ assert.equal(+ compressionComboCreateSchema.safeParse({+ name: "Bad",+ pipeline: [{ engine: "rtk", intensity: "bogus" }],+ }).success,+ false+ );+ });+});diff --git a/tests/unit/compression/diffHelper.test.ts b/tests/unit/compression/diffHelper.test.tsnew file mode 100644index 0000000000..a9ec6fd9e0--- /dev/null+++ b/tests/unit/compression/diffHelper.test.ts@@ -0,0 +1,45 @@+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);+ });++ it("degrades preview diff generation when token product exceeds the safe limit", () => {+ const original = Array.from({ length: 1500 }, (_, index) => `original-${index}`).join(" ");+ const compressed = Array.from({ length: 1500 }, (_, index) => `compressed-${index}`).join(" ");+ const preview = buildCompressionPreviewDiff(original, compressed, null);++ assert.deepEqual(preview.segments, [{ type: "same", text: "[diff omitted: input too large]" }]);+ assert.match(preview.validationWarnings.join("\n"), /Preview diff omitted/);+ });+});diff --git a/tests/unit/compression/engine-registry.test.ts b/tests/unit/compression/engine-registry.test.tsnew file mode 100644index 0000000000..f57422e1cb--- /dev/null+++ b/tests/unit/compression/engine-registry.test.ts@@ -0,0 +1,85 @@+import { describe, it, beforeEach } from "node:test";+import assert from "node:assert/strict";++import {+ aggressiveEngine,+ cavemanEngine,+ ultraEngine,+} from "../../../open-sse/services/compression/engines/cavemanAdapter.ts";+import { rtkEngine as realRtkEngine } from "../../../open-sse/services/compression/engines/rtk/index.ts";+import {+ clearCompressionEngineRegistry,+ getEngine,+ getEngineEntry,+ listEnabledEngines,+ listEngines,+ registerEngine,+ setEngineEnabled,+ updateEngineConfig,+} from "../../../open-sse/services/compression/index.ts";++describe("compression engine registry contract", () => {+ beforeEach(() => {+ clearCompressionEngineRegistry();+ });++ it("registers and retrieves an engine by id", () => {+ registerEngine(cavemanEngine);++ assert.equal(getEngine("caveman"), cavemanEngine);+ assert.equal(getEngine("missing"), null);+ });++ it("lists engine entries and filters enabled entries", () => {+ registerEngine(cavemanEngine);+ registerEngine(realRtkEngine);++ assert.equal(listEngines().length, 2);+ assert.equal(listEnabledEngines().length, 2);++ assert.equal(setEngineEnabled("rtk", false), true);+ assert.equal(+ listEnabledEngines()+ .map((entry) => entry.engine.id)+ .join(","),+ "caveman"+ );+ });++ it("updates config only after engine validation passes", () => {+ registerEngine(realRtkEngine);++ const invalid = updateEngineConfig("rtk", { intensity: "extreme" });+ assert.equal(invalid.valid, false);+ assert.match(invalid.errors.join(" "), /intensity/);++ const valid = updateEngineConfig("rtk", {+ intensity: "aggressive",+ applyToCodeBlocks: true,+ });+ assert.equal(valid.valid, true);+ assert.deepEqual(getEngineEntry("rtk")?.config, {+ intensity: "aggressive",+ applyToCodeBlocks: true,+ });+ });++ it("exposes schema and validation for built-in adapters", () => {+ const cavemanSchema = cavemanEngine.getConfigSchema();+ const rtkSchema = realRtkEngine.getConfigSchema();+ const aggressiveSchema = aggressiveEngine.getConfigSchema();+ const ultraSchema = ultraEngine.getConfigSchema();++ assert.ok(cavemanSchema.some((field) => field.key === "intensity"));+ assert.ok(rtkSchema.some((field) => field.key === "applyToCodeBlocks"));+ assert.ok(aggressiveSchema.some((field) => field.key === "maxTokensPerMessage"));+ assert.ok(ultraSchema.some((field) => field.key === "compressionRate"));+ assert.equal(cavemanEngine.validateConfig({ intensity: "full" }).valid, true);+ assert.equal(cavemanEngine.validateConfig({ intensity: "bad" }).valid, false);+ assert.equal(realRtkEngine.validateConfig({ maxLinesPerResult: 20 }).valid, true);+ assert.equal(aggressiveEngine.validateConfig({ maxTokensPerMessage: 2048 }).valid, true);+ assert.equal(aggressiveEngine.validateConfig({ maxTokensPerMessage: 10 }).valid, false);+ assert.equal(ultraEngine.validateConfig({ compressionRate: 0.4 }).valid, true);+ assert.equal(ultraEngine.validateConfig({ compressionRate: 4 }).valid, false);+ });+});diff --git a/tests/unit/compression/fixtures/rtk/aws-sample.txt b/tests/unit/compression/fixtures/rtk/aws-sample.txtnew file mode 100644index 0000000000..2d6c99f357--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/aws-sample.txt@@ -0,0 +1,4 @@+Completed 1.0 MiB/2.0 MiB+Completed 2.0 MiB/2.0 MiB+upload: ./app.log to s3://omniroute-logs/app.log+An error occurred (AccessDenied) when calling the PutObject operation: denieddiff --git a/tests/unit/compression/fixtures/rtk/biome-sample.txt b/tests/unit/compression/fixtures/rtk/biome-sample.txtnew file mode 100644index 0000000000..50674ebb3e--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/biome-sample.txt@@ -0,0 +1,4 @@+src/app.ts:1:1 lint/suspicious/noExplicitAny+ ! Unexpected any. Specify a different type.++Checked 12 files in 18ms. No fixes applied.diff --git a/tests/unit/compression/fixtures/rtk/build-vite-sample.txt b/tests/unit/compression/fixtures/rtk/build-vite-sample.txtnew file mode 100644index 0000000000..8cceed1758--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/build-vite-sample.txt@@ -0,0 +1,3 @@+vite v5.4.0 building for production...+transforming (42) src/app.ts+✓ built in 1.23sdiff --git a/tests/unit/compression/fixtures/rtk/build-webpack-sample.txt b/tests/unit/compression/fixtures/rtk/build-webpack-sample.txtnew file mode 100644index 0000000000..c90ae12eeb--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/build-webpack-sample.txt@@ -0,0 +1,3 @@+webpack 5.91.0 compiled with 1 error in 1200 ms+asset main.js 120 KiB [emitted] [minimized]+ERROR in ./src/app.tsdiff --git a/tests/unit/compression/fixtures/rtk/bundle-install-sample.txt b/tests/unit/compression/fixtures/rtk/bundle-install-sample.txtnew file mode 100644index 0000000000..5fac191498--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/bundle-install-sample.txt@@ -0,0 +1,4 @@+Fetching gem metadata from https://rubygems.org/+Installing rack 3.0.9+Installing puma 6.4.2+Bundle complete! 12 Gemfile dependencies, 42 gems now installed.diff --git a/tests/unit/compression/fixtures/rtk/curl-sample.txt b/tests/unit/compression/fixtures/rtk/curl-sample.txtnew file mode 100644index 0000000000..13a7065814--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/curl-sample.txt@@ -0,0 +1,4 @@+% Total % Received % Xferd Average Speed Time Time Time Current+ 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0+HTTP/1.1 500 Internal Server Error+curl: (22) The requested URL returned error: 500diff --git a/tests/unit/compression/fixtures/rtk/df-sample.txt b/tests/unit/compression/fixtures/rtk/df-sample.txtnew file mode 100644index 0000000000..0255741e0e--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/df-sample.txt@@ -0,0 +1,4 @@+Filesystem Size Used Avail Use% Mounted on+udev 2.0G 0 2.0G 0% /dev+/dev/sda1 50G 45G 5.0G 90% /+/dev/sdb1 200G 120G 80G 60% /datadiff --git a/tests/unit/compression/fixtures/rtk/docker-logs-sample.txt b/tests/unit/compression/fixtures/rtk/docker-logs-sample.txtnew file mode 100644index 0000000000..640bc7ca76--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/docker-logs-sample.txt@@ -0,0 +1,4 @@+2026-05-02T12:00:00Z INFO starting worker+2026-05-02T12:00:01Z WARN retrying provider request+2026-05-02T12:00:02Z ERROR upstream timeout+2026-05-02T12:00:03Z INFO shutdowndiff --git a/tests/unit/compression/fixtures/rtk/du-sample.txt b/tests/unit/compression/fixtures/rtk/du-sample.txtnew file mode 100644index 0000000000..7392387599--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/du-sample.txt@@ -0,0 +1,4 @@+4.0K package.json+12K src+120M node_modules+120M node_modulesdiff --git a/tests/unit/compression/fixtures/rtk/error-stacktrace-sample.txt b/tests/unit/compression/fixtures/rtk/error-stacktrace-sample.txtnew file mode 100644index 0000000000..201dbcede0--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/error-stacktrace-sample.txt@@ -0,0 +1,4 @@+Traceback (most recent call last):+ File "app.py", line 1, in <module>+ raise RuntimeError("boom")+RuntimeError: boomdiff --git a/tests/unit/compression/fixtures/rtk/eslint-output-sample.txt b/tests/unit/compression/fixtures/rtk/eslint-output-sample.txtnew file mode 100644index 0000000000..6b4a04e661--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/eslint-output-sample.txt@@ -0,0 +1,5 @@+/repo/src/app.ts+ 12:7 error Unexpected any. Specify a different type @typescript-eslint/no-explicit-any+ 18:3 warning Missing return type on function @typescript-eslint/explicit-function-return-type++✖ 2 problems (1 error, 1 warning)diff --git a/tests/unit/compression/fixtures/rtk/gcloud-sample.txt b/tests/unit/compression/fixtures/rtk/gcloud-sample.txtnew file mode 100644index 0000000000..2f4862bf35--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/gcloud-sample.txt@@ -0,0 +1,3 @@+Waiting for operation [deploy] to complete...+Updated property [core/project].+ERROR: (gcloud.run.deploy) PERMISSION_DENIED: Permission denied on resource project omniroute.diff --git a/tests/unit/compression/fixtures/rtk/git-branch-sample.txt b/tests/unit/compression/fixtures/rtk/git-branch-sample.txtnew file mode 100644index 0000000000..a0a8fe0977--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/git-branch-sample.txt@@ -0,0 +1,3 @@+* feature/rtk-compression-roadmap+ feature/caveman-compression-update+ maindiff --git a/tests/unit/compression/fixtures/rtk/git-diff-sample.txt b/tests/unit/compression/fixtures/rtk/git-diff-sample.txtnew file mode 100644index 0000000000..34db3f60fa--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/git-diff-sample.txt@@ -0,0 +1,8 @@+diff --git a/src/app.ts b/src/app.ts+index 1111111..2222222 100644+--- a/src/app.ts++++ b/src/app.ts+@@ -1,3 +1,4 @@+ export function run() {++ return "rtk";+ }diff --git a/tests/unit/compression/fixtures/rtk/git-status-sample.txt b/tests/unit/compression/fixtures/rtk/git-status-sample.txtnew file mode 100644index 0000000000..decc85af2f--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/git-status-sample.txt@@ -0,0 +1,5 @@+On branch feature/rtk-compression-roadmap+Changes not staged for commit:+ modified: open-sse/services/compression/engines/rtk/commandDetector.ts+Untracked files:+ tests/unit/compression/fixtures/rtk/git-status-sample.txtdiff --git a/tests/unit/compression/fixtures/rtk/golangci-lint-sample.txt b/tests/unit/compression/fixtures/rtk/golangci-lint-sample.txtnew file mode 100644index 0000000000..272dfaee01--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/golangci-lint-sample.txt@@ -0,0 +1,5 @@+pkg/router/router.go:10:2: SA4006: this value of err is never used (staticcheck)+pkg/main.go:22:1: File is not `gofmt`-ed (gofmt)+2 issues:+* staticcheck: 1+* gofmt: 1diff --git a/tests/unit/compression/fixtures/rtk/json-output-sample.txt b/tests/unit/compression/fixtures/rtk/json-output-sample.txtnew file mode 100644index 0000000000..ac6862a26a--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/json-output-sample.txt@@ -0,0 +1,7 @@+{+ "status": "ok",+ "filters": [+ "rtk",+ "caveman"+ ]+}diff --git a/tests/unit/compression/fixtures/rtk/make-sample.txt b/tests/unit/compression/fixtures/rtk/make-sample.txtnew file mode 100644index 0000000000..080d7f8489--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/make-sample.txt@@ -0,0 +1,6 @@+make[1]: Entering directory '/repo'+gcc -O2 -c src/main.c+gcc -O2 -c src/main.c+src/main.c:12:3: error: expected ';' before 'return'+make[1]: Leaving directory '/repo'+make: *** [Makefile:12: build] Error 2diff --git a/tests/unit/compression/fixtures/rtk/mypy-sample.txt b/tests/unit/compression/fixtures/rtk/mypy-sample.txtnew file mode 100644index 0000000000..a498d3168c--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/mypy-sample.txt@@ -0,0 +1,2 @@+src/app.py:12: error: Incompatible return value type (got "str", expected "int") [return-value]+Found 1 error in 1 file (checked 5 source files)diff --git a/tests/unit/compression/fixtures/rtk/npm-audit-sample.txt b/tests/unit/compression/fixtures/rtk/npm-audit-sample.txtnew file mode 100644index 0000000000..20c75124df--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/npm-audit-sample.txt@@ -0,0 +1,2 @@+found 1 vulnerabilities (1 critical)+ run `npm audit fix` to fix them, or `npm audit` for detailsdiff --git a/tests/unit/compression/fixtures/rtk/nx-sample.txt b/tests/unit/compression/fixtures/rtk/nx-sample.txtnew file mode 100644index 0000000000..47a93c682a--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/nx-sample.txt@@ -0,0 +1,6 @@+> nx run web:build++> nx run api:test++NX Running target build for 2 projects+NX Successfully ran target build for 2 projectsdiff --git a/tests/unit/compression/fixtures/rtk/pip-sample.txt b/tests/unit/compression/fixtures/rtk/pip-sample.txtnew file mode 100644index 0000000000..bb8c23cb0a--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/pip-sample.txt@@ -0,0 +1,4 @@+Collecting requests+ Downloading requests-2.31.0-py3-none-any.whl+Installing collected packages: requests+Successfully installed requests-2.31.0diff --git a/tests/unit/compression/fixtures/rtk/playwright-sample.txt b/tests/unit/compression/fixtures/rtk/playwright-sample.txtnew file mode 100644index 0000000000..7680ef8c90--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/playwright-sample.txt@@ -0,0 +1,6 @@+Running 3 tests using 1 worker+ ok 1 tests/login.spec.ts:3:1 › login works (1.2s)+ x 2 tests/app.spec.ts:8:1 › app renders (4.0s)++ 1 failed+ tests/app.spec.ts:8:1 › app rendersdiff --git a/tests/unit/compression/fixtures/rtk/poetry-install-sample.txt b/tests/unit/compression/fixtures/rtk/poetry-install-sample.txtnew file mode 100644index 0000000000..7124192182--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/poetry-install-sample.txt@@ -0,0 +1,5 @@+Installing dependencies from lock file++Package operations: 2 installs, 0 updates, 0 removals+ - Installing pydantic (2.9.2)+ - Installing httpx (0.28.1)diff --git a/tests/unit/compression/fixtures/rtk/prettier-sample.txt b/tests/unit/compression/fixtures/rtk/prettier-sample.txtnew file mode 100644index 0000000000..3f09f74434--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/prettier-sample.txt@@ -0,0 +1,4 @@+Checking formatting...+[warn] src/app.ts+[warn] src/routes.ts+[warn] Code style issues found in 2 files. Run Prettier with --write to fix.diff --git a/tests/unit/compression/fixtures/rtk/ps-sample.txt b/tests/unit/compression/fixtures/rtk/ps-sample.txtnew file mode 100644index 0000000000..87387418a2--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/ps-sample.txt@@ -0,0 +1,4 @@+USER PID %CPU COMMAND+root 1 0.0 /sbin/init+node 1234 5.0 node server.js+diego 2345 0.2 bashdiff --git a/tests/unit/compression/fixtures/rtk/rsync-sample.txt b/tests/unit/compression/fixtures/rtk/rsync-sample.txtnew file mode 100644index 0000000000..25c6aa8736--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/rsync-sample.txt@@ -0,0 +1,5 @@+sending incremental file list+app.js+dist/app.js+sent 120 bytes received 20 bytes 280.00 bytes/sec+rsync error: some files could not be transferred (code 23)diff --git a/tests/unit/compression/fixtures/rtk/rubocop-sample.txt b/tests/unit/compression/fixtures/rtk/rubocop-sample.txtnew file mode 100644index 0000000000..f6503895fa--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/rubocop-sample.txt@@ -0,0 +1,4 @@+Inspecting 2 files+.C+app/models/user.rb:12:3: C: Style/IfUnlessModifier: Favor modifier if usage.+2 files inspected, 1 offense detecteddiff --git a/tests/unit/compression/fixtures/rtk/ruff-sample.txt b/tests/unit/compression/fixtures/rtk/ruff-sample.txtnew file mode 100644index 0000000000..73240c9f85--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/ruff-sample.txt@@ -0,0 +1,3 @@+src/app.py:1:1: F401 `os` imported but unused+src/app.py:4:5: E722 Do not use bare `except`+Found 2 errors.diff --git a/tests/unit/compression/fixtures/rtk/shell-find-sample.txt b/tests/unit/compression/fixtures/rtk/shell-find-sample.txtnew file mode 100644index 0000000000..51aa9207d6--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/shell-find-sample.txt@@ -0,0 +1,3 @@+./src/app.ts+./src/routes.ts+./tests/unit/compression/rtk-engine.test.tsdiff --git a/tests/unit/compression/fixtures/rtk/shell-grep-sample.txt b/tests/unit/compression/fixtures/rtk/shell-grep-sample.txtnew file mode 100644index 0000000000..0f79cba74b--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/shell-grep-sample.txt@@ -0,0 +1,3 @@+src/app.ts:1:match+src/app.ts:1:match+src/routes.ts:4:other matchdiff --git a/tests/unit/compression/fixtures/rtk/ssh-sample.txt b/tests/unit/compression/fixtures/rtk/ssh-sample.txtnew file mode 100644index 0000000000..3306dfb047--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/ssh-sample.txt@@ -0,0 +1,3 @@+debug1: Connecting to app.example.test [10.0.0.10] port 22.+Welcome to Ubuntu 24.04 LTS+Permission denied (publickey).diff --git a/tests/unit/compression/fixtures/rtk/systemctl-status-sample.txt b/tests/unit/compression/fixtures/rtk/systemctl-status-sample.txtnew file mode 100644index 0000000000..54583d7d1f--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/systemctl-status-sample.txt@@ -0,0 +1,4 @@+● omniroute.service - OmniRoute+ Loaded: loaded (/etc/systemd/system/omniroute.service; enabled)+ Active: failed (Result: exit-code) since Sat 2026-05-02 12:00:00 UTC; 1min ago+ Process: 1234 ExecStart=/usr/bin/node server.js (code=exited, status=1/FAILURE)diff --git a/tests/unit/compression/fixtures/rtk/terraform-plan-sample.txt b/tests/unit/compression/fixtures/rtk/terraform-plan-sample.txtnew file mode 100644index 0000000000..36bb103b4e--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/terraform-plan-sample.txt@@ -0,0 +1,8 @@+Terraform will perform the following actions:++ # aws_instance.app will be updated in-place+ ~ resource "aws_instance" "app" {+ instance_type = "t3.small" -> "t3.medium"+ }++Plan: 0 to add, 1 to change, 0 to destroy.diff --git a/tests/unit/compression/fixtures/rtk/test-cargo-sample.txt b/tests/unit/compression/fixtures/rtk/test-cargo-sample.txtnew file mode 100644index 0000000000..16258d4e2a--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/test-cargo-sample.txt@@ -0,0 +1,8 @@+running 2 tests+test parser::tests::parses_route ... ok+test server::tests::starts ... FAILED++failures:+ server::tests::starts++test result: FAILED. 1 passed; 1 failed; 0 ignoreddiff --git a/tests/unit/compression/fixtures/rtk/test-go-sample.txt b/tests/unit/compression/fixtures/rtk/test-go-sample.txtnew file mode 100644index 0000000000..3076819a63--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/test-go-sample.txt@@ -0,0 +1,4 @@+--- FAIL: TestRouter (0.01s)+ router_test.go:12: expected route to match+FAIL+FAIL ./pkg/router 0.123sdiff --git a/tests/unit/compression/fixtures/rtk/tofu-plan-sample.txt b/tests/unit/compression/fixtures/rtk/tofu-plan-sample.txtnew file mode 100644index 0000000000..5f945dab41--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/tofu-plan-sample.txt@@ -0,0 +1,8 @@+OpenTofu will perform the following actions:++ # module.web.aws_lb.main will be created+ + resource "aws_lb" "main" {+ name = "web"+ }++Plan: 1 to add, 0 to change, 0 to destroy.diff --git a/tests/unit/compression/fixtures/rtk/turbo-sample.txt b/tests/unit/compression/fixtures/rtk/turbo-sample.txtnew file mode 100644index 0000000000..e44a8881a2--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/turbo-sample.txt@@ -0,0 +1,5 @@+• Packages in scope: web, api+• Running build in 2 packages+web:build: cache miss, executing abc123+api:build: cache hit, replaying logs+Tasks: 1 successful, 2 totaldiff --git a/tests/unit/compression/fixtures/rtk/typescript-errors-sample.txt b/tests/unit/compression/fixtures/rtk/typescript-errors-sample.txtnew file mode 100644index 0000000000..1285126565--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/typescript-errors-sample.txt@@ -0,0 +1,2 @@+src/app.ts(12,7): error TS2322: Type 'string' is not assignable to type 'number'.+src/routes.ts(4,10): error TS2305: Module '"./app"' has no exported member 'missing'.diff --git a/tests/unit/compression/fixtures/rtk/uv-sync-sample.txt b/tests/unit/compression/fixtures/rtk/uv-sync-sample.txtnew file mode 100644index 0000000000..6e626d3eb7--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/uv-sync-sample.txt@@ -0,0 +1,4 @@+Resolved 42 packages in 120ms+Prepared 3 packages in 98ms+Installed 3 packages in 22ms+ + httpx==0.28.1diff --git a/tests/unit/compression/fixtures/rtk/vitest-output-sample.txt b/tests/unit/compression/fixtures/rtk/vitest-output-sample.txtnew file mode 100644index 0000000000..2d7c5634ff--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/vitest-output-sample.txt@@ -0,0 +1,7 @@+ RUN v3.2.4 /repo++ ✓ tests/unit/compression/rtk-engine.test.ts (5 tests) 18ms+ ❯ tests/unit/compression/rtk-command-detector.test.ts (1 failed | 2 passed) 12ms++ Test Files 1 failed | 1 passed (2)+ Tests 1 failed | 7 passed (8)diff --git a/tests/unit/compression/fixtures/rtk/wget-sample.txt b/tests/unit/compression/fixtures/rtk/wget-sample.txtnew file mode 100644index 0000000000..bde37822b1--- /dev/null+++ b/tests/unit/compression/fixtures/rtk/wget-sample.txt@@ -0,0 +1,4 @@+--2026-05-02 22:40:00-- https://example.test/file.tgz+Saving to: 'file.tgz'+HTTP request sent, awaiting response... 404 Not Found+ERROR 404: Not Found.diff --git a/tests/unit/compression/language-packs.test.ts b/tests/unit/compression/language-packs.test.tsnew file mode 100644index 0000000000..b551e6bfff--- /dev/null+++ b/tests/unit/compression/language-packs.test.ts@@ -0,0 +1,60 @@+import { describe, it } from "node:test";+import assert from "node:assert/strict";++import {+ buildCavemanOutputInstruction,+ detectCompressionLanguage,+ loadAllRulesForLanguage,+} from "../../../open-sse/services/compression/index.ts";+import { applyRulesToText } from "../../../open-sse/services/compression/caveman.ts";+import { getRulesForContext } from "../../../open-sse/services/compression/cavemanRules.ts";++const LANGUAGES = ["pt-BR", "es", "de", "fr", "ja"];++describe("Caveman language packs", () => {+ it("ships 5 language packs with at least 15 rules each", () => {+ for (const language of LANGUAGES) {+ const rules = loadAllRulesForLanguage(language, { refresh: true });+ assert.ok(rules.length >= 15, `${language} expected 15+ rules, got ${rules.length}`);+ assert.ok(+ rules.some((rule) => rule.category === "filler"),+ `${language} missing filler`+ );+ assert.ok(+ rules.some((rule) => rule.category === "context"),+ `${language} missing context`+ );+ assert.ok(+ rules.some((rule) => rule.category === "structural"),+ `${language} missing structural`+ );+ }+ });++ it("detects supported languages", () => {+ assert.equal(detectCompressionLanguage("preciso corrigir este arquivo com erro"), "pt-BR");+ assert.equal(detectCompressionLanguage("necesito corregir este archivo con error"), "es");+ assert.equal(detectCompressionLanguage("ich brauche diese konfiguration"), "de");+ assert.equal(detectCompressionLanguage("j'ai besoin de corriger cette erreur fichier"), "fr");+ assert.equal(detectCompressionLanguage("このコードを修正してください"), "ja");+ });++ it("applies non-English rule packs to golden samples", () => {+ const ptRules = getRulesForContext("user", "full", "pt-BR");+ const { text } = applyRulesToText("por favor segue o código: const auth = true", ptRules);++ assert.ok(!text.toLowerCase().includes("por favor"));+ assert.ok(text.includes("Código:"));+ assert.ok(text.includes("auth"));+ });++ it("builds localized output mode instructions", () => {+ const config = { enabled: true, intensity: "full" as const, autoClarity: true };++ assert.match(buildCavemanOutputInstruction(config, "pt-BR"), /Responda/);+ assert.match(buildCavemanOutputInstruction(config, "es"), /Responde/);+ assert.match(buildCavemanOutputInstruction(config, "de"), /Antworte/);+ assert.match(buildCavemanOutputInstruction(config, "fr"), /Reponds/);+ assert.match(buildCavemanOutputInstruction(config, "ja"), /回答/);+ });+});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..13426429e7--- /dev/null+++ b/tests/unit/compression/mcp-description-compressor.test.ts@@ -0,0 +1,132 @@+import { describe, it } from "node:test";+import assert from "node:assert/strict";+import {+ compressDescriptionsInPlace,+ compressMcpListMetadata,+ compressMcpRegistryMetadata,+ 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("compresses only MCP list metadata containers, not tool-call response bodies", () => {+ resetMcpDescriptionCompressionStats();+ const payload = {+ result: {+ tools: [+ { name: "get_weather", description: "The function returns the weather for a city." },+ ],+ prompts: [{ name: "ask", description: "The prompt asks for a detailed summary." }],+ resources: [{ name: "docs", description: "The resource contains the project docs." }],+ resourceTemplates: [+ { name: "doc", description: "The template returns the matching project document." },+ ],+ content: [+ {+ type: "text",+ description: "The tool response body should remain unchanged.",+ },+ ],+ },+ };++ const output = compressMcpListMetadata(payload);++ assert.doesNotMatch(output.result.tools[0].description, /\bthe\b/i);+ assert.doesNotMatch(output.result.prompts[0].description, /\bthe\b/i);+ assert.doesNotMatch(output.result.resources[0].description, /\bthe\b/i);+ assert.doesNotMatch(output.result.resourceTemplates[0].description, /\bthe\b/i);+ assert.equal(+ output.result.content[0].description,+ "The tool response body should remain unchanged."+ );+ });++ it("compresses registry metadata for tools, prompts, and resources", () => {+ const metadata = compressMcpRegistryMetadata({+ description: "The function returns the current weather for a city.",+ inputSchema: {},+ });++ assert.doesNotMatch(metadata.description as string, /\bthe\b/i);+ assert.deepEqual(metadata.inputSchema, {});+ });++ 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.equal(stats.charsBefore, input.length);+ assert.equal(stats.charsAfter, output.length);+ 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/pipeline-integration.test.ts b/tests/unit/compression/pipeline-integration.test.tsnew file mode 100644index 0000000000..2c794fe158--- /dev/null+++ b/tests/unit/compression/pipeline-integration.test.ts@@ -0,0 +1,106 @@+import { describe, it } from "node:test";+import assert from "node:assert/strict";++import {+ applyCompression,+ applyStackedCompression,+} from "../../../open-sse/services/compression/index.ts";++describe("compression pipeline integration", () => {+ it("runs stacked compression in RTK then Caveman order", () => {+ const body = {+ messages: [+ {+ role: "tool",+ content: Array.from({ length: 8 }, () => "same noisy line").join("\n"),+ },+ {+ role: "user",+ content: "Please provide a detailed explanation of the authentication configuration",+ },+ ],+ };++ const result = applyStackedCompression(body, [+ { engine: "rtk", intensity: "standard" },+ { engine: "caveman", intensity: "full" },+ ]);++ assert.equal(result.stats?.engine, "stacked");+ assert.deepEqual(+ result.stats?.engineBreakdown?.map((entry) => entry.engine),+ ["rtk", "caveman"]+ );+ assert.ok(result.stats?.techniquesUsed.includes("rtk-dedup"));+ });++ it("uses the default stacked pipeline when no explicit pipeline is provided", () => {+ const body = {+ messages: [{ role: "tool", content: Array.from({ length: 8 }, () => "same").join("\n") }],+ };++ const result = applyCompression(body, "stacked", {+ config: {+ enabled: true,+ defaultMode: "stacked",+ autoTriggerTokens: 0,+ cacheMinutes: 5,+ preserveSystemPrompt: true,+ comboOverrides: {},+ rtkConfig: {+ enabled: true,+ intensity: "standard",+ applyToToolResults: true,+ applyToCodeBlocks: false,+ applyToAssistantMessages: false,+ enabledFilters: [],+ disabledFilters: [],+ maxLinesPerResult: 120,+ maxCharsPerResult: 12000,+ deduplicateThreshold: 3,+ },+ },+ });++ assert.equal(result.stats?.engine, "stacked");+ assert.deepEqual(+ result.stats?.engineBreakdown?.map((entry) => entry.engine),+ ["rtk", "caveman"]+ );+ });++ it("keeps multipart tool output safe through stacked RTK then Caveman", () => {+ const imagePart = { type: "image_url", image_url: { url: "data:image/png;base64,abc" } };+ const body = {+ messages: [+ {+ role: "tool",+ content: [+ {+ type: "text",+ text: Array.from({ length: 12 }, () => "first repeated tool line").join("\n"),+ },+ imagePart,+ {+ type: "text",+ text: Array.from({ length: 12 }, () => "second repeated tool line").join("\n"),+ },+ ],+ },+ ],+ };++ const result = applyStackedCompression(body, [+ { engine: "rtk", intensity: "standard" },+ { engine: "caveman", intensity: "full" },+ ]);+ const content = (result.body.messages as typeof body.messages)[0].content;++ assert.equal(result.stats?.engine, "stacked");+ assert.ok(Array.isArray(content));+ assert.match(content[0].text ?? "", /first repeated tool line/);+ assert.match(content[2].text ?? "", /second repeated tool line/);+ assert.notEqual(content[0].text, content[2].text);+ assert.deepEqual(content[1], imagePart);+ });+});diff --git a/tests/unit/compression/rtk-code-stripper.test.ts b/tests/unit/compression/rtk-code-stripper.test.tsnew file mode 100644index 0000000000..ab28be648e--- /dev/null+++ b/tests/unit/compression/rtk-code-stripper.test.ts@@ -0,0 +1,72 @@+import { describe, it } from "node:test";+import assert from "node:assert/strict";++import {+ applyRtkCompression,+ detectCodeLanguage,+ stripCode,+} from "../../../open-sse/services/compression/index.ts";++describe("RTK code stripper", () => {+ it("detects common code languages", () => {+ assert.equal(detectCodeLanguage("interface User { id: string }"), "typescript");+ assert.equal(detectCodeLanguage("def run():\n print('x')"), "python");+ assert.equal(detectCodeLanguage('fn main() { println!("x"); }'), "rust");+ assert.equal(detectCodeLanguage("package main\nfunc main() {}"), "go");+ assert.equal(detectCodeLanguage("class Main { }"), "java");+ });++ it("removes single-line and multi-line comments", () => {+ const js = stripCode(+ "// comment\nconst value = 1;\n/* block */\nconsole.log(value);",+ "javascript"+ );+ const py = stripCode('"""doc"""\n# comment\nprint("ok")', "python");+ const rb = stripCode("=begin\ncomment\n=end\n# comment\nputs 'ok'", "ruby");++ assert.ok(!js.text.includes("comment"));+ assert.ok(!js.text.includes("block"));+ assert.ok(!py.text.includes("doc"));+ assert.ok(!rb.text.includes("comment"));+ });++ it("preserves docstrings when configured", () => {+ const result = stripCode('"""doc"""\n# comment\nprint("ok")', "python", {+ preserveDocstrings: true,+ });++ assert.ok(result.text.includes("doc"));+ assert.ok(!result.text.includes("# comment"));+ });++ it("applies to fenced code blocks through RTK runtime", () => {+ const body = {+ messages: [+ {+ role: "assistant",+ content: "```ts\n// remove\nconst value: number = 1;\n```\nDone.",+ },+ ],+ };+ const result = applyRtkCompression(body, {+ config: {+ enabled: true,+ intensity: "standard",+ applyToToolResults: false,+ applyToAssistantMessages: false,+ applyToCodeBlocks: true,+ enabledFilters: [],+ disabledFilters: [],+ maxLinesPerResult: 100,+ maxCharsPerResult: 12000,+ deduplicateThreshold: 3,+ },+ });++ assert.equal(result.compressed, true);+ const serialized = JSON.stringify(result.body.messages);+ assert.match(serialized, /const value/);+ assert.doesNotMatch(serialized, /remove/);+ assert.ok(result.stats?.techniquesUsed.includes("rtk-code-strip"));+ });+});diff --git a/tests/unit/compression/rtk-command-detector.test.ts b/tests/unit/compression/rtk-command-detector.test.tsnew file mode 100644index 0000000000..36b99c8417--- /dev/null+++ b/tests/unit/compression/rtk-command-detector.test.ts@@ -0,0 +1,107 @@+import { describe, it } from "node:test";+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import { fileURLToPath } from "node:url";+import path from "node:path";++import {+ detectCommandOutput,+ detectCommandType,+} from "../../../open-sse/services/compression/index.ts";++const FIXTURES = path.join(path.dirname(fileURLToPath(import.meta.url)), "fixtures", "rtk");++function fixture(name: string): string {+ return readFileSync(path.join(FIXTURES, name), "utf8");+}++describe("RTK command detector", () => {+ it("detects planned command output classes", () => {+ assert.equal(+ detectCommandType(fixture("git-status-sample.txt"), "git status").type,+ "git-status"+ );+ assert.equal(detectCommandType(fixture("git-diff-sample.txt"), "git diff").type, "git-diff");+ assert.equal(detectCommandType("commit abcdef1\nAuthor: A", "git log").type, "git-log");+ assert.equal(+ detectCommandType(fixture("vitest-output-sample.txt"), "vitest").type,+ "test-vitest"+ );+ assert.equal(detectCommandType("FAIL test\nTests: 1 failed", "jest").type, "test-jest");+ assert.equal(detectCommandType("FAILED test_a.py::test_a", "pytest").type, "test-pytest");+ assert.equal(+ detectCommandType(fixture("typescript-errors-sample.txt"), "tsc --noEmit").type,+ "build-typescript"+ );+ assert.equal(+ detectCommandType(fixture("eslint-output-sample.txt"), "eslint .").type,+ "build-eslint"+ );+ assert.equal(+ detectCommandType("CONTAINER ID IMAGE COMMAND", "docker ps").type,+ "docker-ps"+ );+ assert.equal(detectCommandType(fixture("json-output-sample.txt")).type, "json-output");+ assert.equal(detectCommandType("Error: boom\n at fn").type, "generic-error");+ });++ it("detects RTK parity command output classes", () => {+ const cases: Array<[string, string | null, string]> = [+ ["* feature/rtk\n main", "git branch", "git-branch"],+ ["running 2 tests\ntest a ... FAILED\ntest result: FAILED", "cargo test", "test-cargo"],+ ["--- FAIL: TestA\nFAIL\t./pkg\t0.1s", "go test ./...", "test-go"],+ ["webpack 5.0.0 compiled with 1 error", "webpack", "build-webpack"],+ ["vite v5.0.0\n✓ built in 100ms", "vite build", "build-vite"],+ ["2026-05-02T00:00:00Z ERROR failed", "docker logs app", "docker-logs"],+ ["./src/a.ts\n./src/b.ts", "find . -name '*.ts'", "shell-find"],+ ["src/a.ts:1:match", "rg match", "shell-grep"],+ ["found 1 vulnerabilities\ncritical severity", "npm audit", "npm-audit"],+ ['Traceback (most recent call last):\n File "a.py", line 1', null, "error-stacktrace"],+ ["make[1]: Entering directory '/repo'\nmake: *** [all] Error 2", "make", "make"],+ [+ "Terraform will perform the following actions:\nPlan: 1 to add",+ "terraform plan",+ "terraform-plan",+ ],+ ["OpenTofu will perform the following actions:\nPlan: 1 to add", "tofu plan", "tofu-plan"],+ ["Active: failed (Result: exit-code)", "systemctl status omniroute", "systemctl-status"],+ ["Checked 12 files in 18ms. No fixes applied.", "biome check .", "biome"],+ ["Checking formatting...\n[warn] src/app.ts", "prettier --check .", "prettier"],+ ["• Packages in scope: web\nTasks: 1 successful", "turbo build", "turbo"],+ ["NX Running target build for 2 projects", "nx build web", "nx"],+ ["Running 3 tests using 1 worker", "playwright test", "playwright"],+ ["src/app.py:1:1: F401 unused import", "ruff check .", "ruff"],+ ["src/app.py:12: error: incompatible type", "mypy src", "mypy"],+ ["Collecting requests\nSuccessfully installed requests", "pip install requests", "pip"],+ ["Resolved 42 packages\nInstalled 3 packages", "uv sync", "uv-sync"],+ ["Installing dependencies from lock file", "poetry install", "poetry-install"],+ ["pkg/main.go:22:1: issue\n2 issues:", "golangci-lint run", "golangci-lint"],+ ["Bundle complete! 12 Gemfile dependencies", "bundle install", "bundle-install"],+ ["Inspecting 2 files\napp.rb:1:1: C: Style/FrozenStringLiteralComment", "rubocop", "rubocop"],+ ["An error occurred (AccessDenied) when calling", "aws s3 ls", "aws"],+ ["ERROR: (gcloud.run.deploy) PERMISSION_DENIED", "gcloud run deploy", "gcloud"],+ ["Permission denied (publickey).", "ssh host", "ssh"],+ ["sending incremental file list\nrsync error: code 23", "rsync -av src host:", "rsync"],+ ["HTTP/1.1 500 Internal Server Error", "curl -i example.test", "curl"],+ ["ERROR 404: Not Found.", "wget example.test/missing", "wget"],+ ["USER PID %CPU COMMAND", "ps aux", "shell-ps"],+ ["Filesystem Size Used Avail Use% Mounted on", "df -h", "shell-df"],+ ["120M node_modules", "du -sh *", "shell-du"],+ ];++ for (const [text, command, expected] of cases) {+ const detection = detectCommandType(text, command);+ assert.equal(detection.type, expected);+ assert.ok(detection.matchedPatterns.length > 0);+ assert.ok(detection.confidence >= 0.25);+ }+ });++ it("returns unknown for generic text and exposes planned alias", () => {+ const detection = detectCommandOutput("ordinary prose without command output");++ assert.equal(detection.type, "unknown");+ assert.ok(detection.confidence > 0);+ assert.deepEqual(detection.matchedPatterns, []);+ });+});diff --git a/tests/unit/compression/rtk-custom-filters.test.ts b/tests/unit/compression/rtk-custom-filters.test.tsnew file mode 100644index 0000000000..ba1298a2b6--- /dev/null+++ b/tests/unit/compression/rtk-custom-filters.test.ts@@ -0,0 +1,104 @@+import { describe, it, afterEach } from "node:test";+import assert from "node:assert/strict";+import crypto from "node:crypto";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";++import {+ getRtkFilterLoadDiagnostics,+ getRtkFilterCatalog,+ loadRtkFilters,+ matchRtkFilter,+} from "../../../open-sse/services/compression/index.ts";++const originalCwd = process.cwd();+const originalDataDir = process.env.DATA_DIR;++function writeJson(filePath: string, value: unknown): void {+ fs.mkdirSync(path.dirname(filePath), { recursive: true });+ fs.writeFileSync(filePath, JSON.stringify(value, null, 2));+}++function customFilter(id: string, command: string) {+ return {+ id,+ label: id,+ category: "generic",+ priority: 100,+ match: { outputTypes: [], commands: [`^${command}\\b`], patterns: [id] },+ rules: { dropPatterns: ["^noise"], maxLines: 20, headLines: 10, tailLines: 10 },+ preserve: { errorPatterns: ["error"], summaryPatterns: [] },+ tests: [{ name: "sample", input: `noise\n${id}`, expected: id }],+ };+}++afterEach(() => {+ process.chdir(originalCwd);+ if (originalDataDir === undefined) delete process.env.DATA_DIR;+ else process.env.DATA_DIR = originalDataDir;+ delete process.env.OMNIROUTE_RTK_TRUST_PROJECT_FILTERS;+ loadRtkFilters({ refresh: true, customFiltersEnabled: false });+});++describe("RTK custom filter lookup and trust", () => {+ it("skips untrusted project filters and reports a diagnostic", () => {+ const temp = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-rtk-project-"));+ process.chdir(temp);+ writeJson(path.join(temp, ".rtk", "filters.json"), customFilter("project-filter", "customcmd"));++ const filters = loadRtkFilters({ refresh: true });+ const diagnostics = getRtkFilterLoadDiagnostics();++ assert.ok(!filters.some((filter) => filter.id === "project-filter"));+ assert.ok(diagnostics.some((entry) => entry.source === "project" && entry.level === "warning"));+ });++ it("loads trusted project filters before builtin filters", () => {+ const temp = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-rtk-project-"));+ const filterPath = path.join(temp, ".rtk", "filters.json");+ process.chdir(temp);+ writeJson(filterPath, customFilter("project-filter", "customcmd"));+ const hash = crypto+ .createHash("sha256")+ .update(fs.readFileSync(filterPath, "utf8"))+ .digest("hex");+ writeJson(path.join(temp, ".rtk", "trust.json"), { filtersSha256: hash });++ const filter = matchRtkFilter("project-filter", "customcmd");++ assert.equal(filter?.id, "project-filter");+ });++ it("loads global filters before builtin fallback filters", () => {+ const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-rtk-project-"));+ const tempData = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-rtk-data-"));+ process.chdir(tempProject);+ process.env.DATA_DIR = tempData;+ writeJson(+ path.join(tempData, "rtk", "filters.json"),+ customFilter("global-filter", "globalcmd")+ );++ const filter = matchRtkFilter("global-filter", "globalcmd");++ assert.equal(filter?.id, "global-filter");+ });++ it("skips invalid custom filters and keeps the dashboard catalog lightweight", () => {+ const tempProject = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-rtk-project-"));+ const tempData = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-rtk-data-"));+ process.chdir(tempProject);+ process.env.DATA_DIR = tempData;+ fs.mkdirSync(path.join(tempData, "rtk"), { recursive: true });+ fs.writeFileSync(path.join(tempData, "rtk", "filters.json"), "{ invalid json");++ const filters = loadRtkFilters({ refresh: true });+ const diagnostics = getRtkFilterLoadDiagnostics();+ const catalog = getRtkFilterCatalog();++ assert.ok(filters.some((filter) => filter.id === "generic-output"));+ assert.ok(diagnostics.some((entry) => entry.source === "global" && entry.level === "warning"));+ assert.ok(catalog.every((entry) => !("stripPatterns" in entry)));+ });+});diff --git a/tests/unit/compression/rtk-deduplicator.test.ts b/tests/unit/compression/rtk-deduplicator.test.tsnew file mode 100644index 0000000000..9831cfdda4--- /dev/null+++ b/tests/unit/compression/rtk-deduplicator.test.ts@@ -0,0 +1,21 @@+import { describe, it } from "node:test";+import assert from "node:assert/strict";++import { deduplicateRepeatedLines } from "../../../open-sse/services/compression/engines/rtk/deduplicator.ts";++describe("RTK deduplicator", () => {+ it("collapses consecutive repeated lines with counters", () => {+ const result = deduplicateRepeatedLines(["same", "same", "same", "tail"].join("\n"), {+ threshold: 3,+ });++ assert.equal(result.collapsed, 2);+ assert.ok(result.text.includes("[line repeated 2x]"));+ assert.ok(result.text.includes("[rtk:dropped 2 repeated lines]"));+ });++ it("honors configurable threshold", () => {+ assert.equal(deduplicateRepeatedLines("a\na", { threshold: 3 }).collapsed, 0);+ assert.equal(deduplicateRepeatedLines("a\na", { threshold: 2 }).collapsed, 1);+ });+});diff --git a/tests/unit/compression/rtk-dsl-pipeline.test.ts b/tests/unit/compression/rtk-dsl-pipeline.test.tsnew file mode 100644index 0000000000..7ba90a518b--- /dev/null+++ b/tests/unit/compression/rtk-dsl-pipeline.test.ts@@ -0,0 +1,94 @@+import { describe, it } from "node:test";+import assert from "node:assert/strict";++import { validateRtkFilter } from "../../../open-sse/services/compression/engines/rtk/filterSchema.ts";+import { applyLineFilter } from "../../../open-sse/services/compression/engines/rtk/lineFilter.ts";++function makeFilter(overrides: Record<string, unknown> = {}) {+ return validateRtkFilter({+ id: "dsl-test",+ label: "DSL Test",+ category: "generic",+ priority: 100,+ match: { outputTypes: ["dsl-test"], commands: ["^dsl"], patterns: [] },+ preserve: { errorPatterns: ["error"], summaryPatterns: [] },+ ...overrides,+ });+}++describe("RTK declarative DSL pipeline", () => {+ it("runs stripAnsi, replace, strip, truncateLineAt, max lines, and onEmpty in order", () => {+ const filter = makeFilter({+ rules: {+ stripAnsi: true,+ replace: [{ pattern: "NOISE", replacement: "drop" }],+ dropPatterns: ["^drop"],+ truncateLineAt: 8,+ maxLines: 2,+ headLines: 2,+ tailLines: 0,+ onEmpty: "dsl: empty",+ },+ });++ const result = applyLineFilter(+ "\u001b[31mNOISE one\u001b[0m\nimportant-long-line\nsecond-long-line\nthird-long-line",+ filter+ );++ assert.ok(result.appliedRules.includes("dsl-test:strip-ansi"));+ assert.ok(result.appliedRules.includes("dsl-test:replace"));+ assert.ok(result.appliedRules.includes("dsl-test:strip"));+ assert.ok(result.appliedRules.includes("dsl-test:truncate-line"));+ assert.ok(result.text.includes("impor..."));+ assert.ok(!result.text.includes("NOISE"));+ });++ it("short-circuits matchOutput and respects unless", () => {+ const filter = makeFilter({+ rules: {+ matchOutput: [+ { pattern: "Build complete", message: "build: ok", unless: "error|failed" },+ { pattern: "Build complete", message: "build: completed with diagnostics" },+ ],+ dropPatterns: ["^noise"],+ },+ });++ assert.equal(applyLineFilter("Build complete", filter).text, "build: ok");+ assert.equal(+ applyLineFilter("Build complete\nerror: warning promoted", filter).text,+ "build: completed with diagnostics"+ );+ });++ it("uses onEmpty when filtering removes every line", () => {+ const filter = makeFilter({+ rules: {+ dropPatterns: [".*"],+ onEmpty: "dsl: empty",+ },+ });++ assert.equal(applyLineFilter("drop me", filter).text, "dsl: empty");+ });++ it("normalizes stderr prefixes before applying keep/drop rules", () => {+ const filter = makeFilter({+ rules: {+ filterStderr: true,+ includePatterns: ["^error:"],+ dropPatterns: ["debug"],+ },+ });++ const result = applyLineFilter(+ "stdout | ok\nstderr | error: boom\nstderr: debug noise",+ filter+ );++ assert.equal(result.text, "error: boom");+ assert.ok(result.appliedRules.includes("dsl-test:filter-stderr"));+ assert.ok(result.appliedRules.includes("dsl-test:keep"));+ });+});diff --git a/tests/unit/compression/rtk-engine.test.ts b/tests/unit/compression/rtk-engine.test.tsnew file mode 100644index 0000000000..7406f53634--- /dev/null+++ b/tests/unit/compression/rtk-engine.test.ts@@ -0,0 +1,115 @@+import { describe, it } from "node:test";+import assert from "node:assert/strict";++import {+ detectCommandType,+ loadRtkFilters,+ matchRtkFilter,+ processRtkText,+ applyRtkCompression,+ rtkEngine,+} from "../../../open-sse/services/compression/index.ts";++describe("RTK compression engine", () => {+ it("detects TypeScript build output", () => {+ const output = "src/a.ts:1:1 - error TS2322: Type 'string' is not assignable";+ const detection = detectCommandType(output, "tsc --noEmit");+ assert.equal(detection.type, "build-typescript");+ assert.equal(detection.category, "build");+ });++ it("loads builtin declarative filters", () => {+ const filters = loadRtkFilters({ refresh: true });+ assert.ok(filters.length >= 10);+ assert.ok(filters.some((filter) => filter.id === "git-diff"));+ });++ it("matches filters by detected output type", () => {+ const filter = matchRtkFilter("diff --git a/a.ts b/a.ts\n@@ -1,1 +1,1 @@", "git diff");+ assert.equal(filter?.id, "git-diff");+ });++ it("compresses repeated tool output", () => {+ const output = Array.from({ length: 20 }, () => "same noisy line").join("\n");+ const result = processRtkText(output);+ assert.equal(result.compressed, true);+ assert.ok(result.text.includes("[rtk:dropped"));+ });++ it("honors disabled and empty-message runtime branches", () => {+ const disabled = applyRtkCompression(+ { messages: [{ role: "tool", content: "same\nsame\nsame" }] },+ { config: { enabled: false } }+ );+ assert.equal(disabled.compressed, false);+ assert.equal(disabled.stats, null);++ const empty = applyRtkCompression({ messages: [] });+ assert.equal(empty.compressed, false);+ assert.equal(empty.stats, null);+ });++ it("respects enabled and disabled filter lists", () => {+ const output = "diff --git a/a.ts b/a.ts\n@@ -1,1 +1,1 @@\n-error\n+ok";++ const disabled = processRtkText(output, {+ command: "git diff",+ config: { disabledFilters: ["git-diff"] },+ });+ assert.ok(!disabled.rulesApplied.includes("git-diff:keep"));++ const enabledMismatch = processRtkText(output, {+ command: "git diff",+ config: { enabledFilters: ["git-status"] },+ });+ assert.ok(!enabledMismatch.rulesApplied.includes("git-diff:keep"));+ });++ it("exposes RTK engine schema, validation, apply and compress contracts", () => {+ assert.ok(rtkEngine.getConfigSchema().some((field) => field.key === "rawOutputRetention"));+ assert.equal(rtkEngine.validateConfig({ intensity: "invalid" }).valid, false);+ assert.equal(rtkEngine.validateConfig({ rawOutputRetention: "always" }).valid, true);++ const body = { messages: [{ role: "tool", content: "same\nsame\nsame\nsame" }] };+ assert.equal(+ rtkEngine.apply(body, { config: { rtkConfig: { enabled: true } } }).stats?.engine,+ "rtk"+ );+ assert.equal(rtkEngine.compress(body, { enabled: true }).stats?.engine, "rtk");+ });++ it("applies to chat tool messages", () => {+ const body = {+ messages: [{ role: "tool", content: Array.from({ length: 20 }, () => "same").join("\n") }],+ };+ const result = applyRtkCompression(body);+ assert.equal(result.compressed, true);+ assert.equal(result.stats?.mode, "rtk");+ });++ it("compresses multipart text parts independently without duplicating output", () => {+ const imagePart = { type: "image_url", image_url: { url: "data:image/png;base64,abc" } };+ const body = {+ messages: [+ {+ role: "tool",+ content: [+ { type: "text", text: Array.from({ length: 12 }, () => "alpha noisy line").join("\n") },+ imagePart,+ { type: "text", text: Array.from({ length: 12 }, () => "beta noisy line").join("\n") },+ ],+ },+ ],+ };++ const result = applyRtkCompression(body);+ const content = (result.body.messages as typeof body.messages)[0].content;++ assert.equal(result.compressed, true);+ assert.ok(Array.isArray(content));+ assert.match(content[0].text ?? "", /alpha noisy line/);+ assert.match(content[2].text ?? "", /beta noisy line/);+ assert.notEqual(content[0].text, content[2].text);+ assert.deepEqual(content[1], imagePart);+ });+});diff --git a/tests/unit/compression/rtk-filter-catalog.test.ts b/tests/unit/compression/rtk-filter-catalog.test.tsnew file mode 100644index 0000000000..124c51ab66--- /dev/null+++ b/tests/unit/compression/rtk-filter-catalog.test.ts@@ -0,0 +1,94 @@+import { describe, it } from "node:test";+import assert from "node:assert/strict";+import fs from "node:fs";+import path from "node:path";++import {+ loadRtkFilters,+ matchRtkFilter,+ runRtkFilterTests,+} from "../../../open-sse/services/compression/index.ts";++const FILTER_DIR = path.join(+ process.cwd(),+ "open-sse",+ "services",+ "compression",+ "engines",+ "rtk",+ "filters"+);++const PLANNED_FILTERS = [+ "rubocop",+ "aws",+ "gcloud",+ "ssh",+ "rsync",+ "curl",+ "wget",+ "ps",+ "df",+ "du",+];++const MATCH_CASES: Array<[string, string, string]> = [+ [+ "rubocop",+ "app/models/user.rb:12:3: C: Style/IfUnlessModifier: Favor modifier if usage.",+ "rubocop",+ ],+ ["aws", "An error occurred (AccessDenied) when calling the PutObject operation", "aws s3 cp"],+ ["gcloud", "ERROR: (gcloud.run.deploy) PERMISSION_DENIED", "gcloud run deploy"],+ ["ssh", "Permission denied (publickey).", "ssh app"],+ [+ "rsync",+ "sending incremental file list\nrsync error: some files could not be transferred",+ "rsync -av",+ ],+ ["curl", "HTTP/1.1 500 Internal Server Error\ncurl: (22) failed", "curl -i"],+ ["wget", "ERROR 404: Not Found.", "wget https://example.test/missing"],+ ["ps", "USER PID %CPU COMMAND\nnode 1234 5.0 node server.js", "ps aux"],+ ["df", "Filesystem Size Used Avail Use% Mounted on\n/dev/sda1 50G 45G 5G 90% /", "df -h"],+ ["du", "120M node_modules\n4.0K package.json", "du -sh *"],+];++describe("RTK planned filter catalog coverage", () => {+ it("ships the cloud/system filters named in the RTK parity plan", () => {+ const filters = loadRtkFilters({ refresh: true, customFiltersEnabled: false });+ const ids = new Set(filters.map((filter) => filter.id));++ for (const id of PLANNED_FILTERS) {+ assert.ok(ids.has(id), `missing planned filter ${id}`);+ const raw = JSON.parse(fs.readFileSync(path.join(FILTER_DIR, `${id}.json`), "utf8"));+ assert.ok(raw.match?.outputTypes, `${id} should define match.outputTypes`);+ assert.ok(raw.match?.commands, `${id} should define match.commands`);+ assert.ok(raw.match?.patterns, `${id} should define match.patterns`);+ assert.ok(raw.rules, `${id} should define rules`);+ assert.ok(raw.preserve, `${id} should define preserve`);+ assert.ok(Array.isArray(raw.tests) && raw.tests.length > 0, `${id} should define tests`);+ }+ });++ it("matches planned filters by command or content before generic fallback", () => {+ for (const [expectedId, output, command] of MATCH_CASES) {+ const filter = matchRtkFilter(output, command, { customFiltersEnabled: false });+ assert.equal(filter?.id, expectedId);+ }+ });++ it("does not select planned filters for unrelated secret-like prose", () => {+ const filter = matchRtkFilter("api_key=sk-test-secret-token-without-command", null, {+ customFiltersEnabled: false,+ });++ assert.ok(!filter || !PLANNED_FILTERS.includes(filter.id));+ });++ it("keeps builtin inline-test gate green after catalog expansion", () => {+ const result = runRtkFilterTests({ requireAll: true, customFiltersEnabled: false });++ assert.equal(result.passed, true);+ assert.deepEqual(result.filtersWithoutTests, []);+ });+});diff --git a/tests/unit/compression/rtk-line-filter.test.ts b/tests/unit/compression/rtk-line-filter.test.tsnew file mode 100644index 0000000000..3704c7e174--- /dev/null+++ b/tests/unit/compression/rtk-line-filter.test.ts@@ -0,0 +1,39 @@+import { describe, it } from "node:test";+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import { fileURLToPath } from "node:url";+import path from "node:path";++import { loadRtkFilters, matchRtkFilter } from "../../../open-sse/services/compression/index.ts";+import { applyLineFilter } from "../../../open-sse/services/compression/engines/rtk/lineFilter.ts";++const FIXTURES = path.join(path.dirname(fileURLToPath(import.meta.url)), "fixtures", "rtk");++function fixture(name: string): string {+ return readFileSync(path.join(FIXTURES, name), "utf8");+}++describe("RTK line filters", () => {+ it("loads and validates builtin filters", () => {+ const filters = loadRtkFilters({ refresh: true });++ assert.ok(filters.length >= 10);+ assert.ok(filters.some((filter) => filter.id === "json-output"));+ });++ it("matches filters by detected type", () => {+ assert.equal(matchRtkFilter(fixture("git-status-sample.txt"), "git status")?.id, "git-status");+ assert.equal(matchRtkFilter(fixture("vitest-output-sample.txt"), "vitest")?.id, "test-vitest");+ assert.equal(matchRtkFilter("plain text")?.id, "generic-output");+ });++ it("applies strip and keep patterns", () => {+ const filter = loadRtkFilters().find((item) => item.id === "git-status");+ assert.ok(filter);++ const result = applyLineFilter(fixture("git-status-sample.txt"), filter);+ assert.ok(result.appliedRules.includes("git-status:keep"));+ assert.ok(result.text.includes("On branch"));+ assert.ok(!result.text.includes("nothing added"));+ });+});diff --git a/tests/unit/compression/rtk-raw-output-route.test.ts b/tests/unit/compression/rtk-raw-output-route.test.tsnew file mode 100644index 0000000000..0ab56c1928--- /dev/null+++ b/tests/unit/compression/rtk-raw-output-route.test.ts@@ -0,0 +1,138 @@+import test from "node:test";+import assert from "node:assert/strict";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";++import { makeManagementSessionRequest } from "../../helpers/managementSession.ts";++const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-rtk-raw-route-"));+const originalDataDir = process.env.DATA_DIR;+const originalJwtSecret = process.env.JWT_SECRET;++process.env.DATA_DIR = TEST_DATA_DIR;++const core = await import("../../../src/lib/db/core.ts");+const settingsDb = await import("../../../src/lib/db/settings.ts");+const route = await import("../../../src/app/api/context/rtk/raw-output/[id]/route.ts");+const rawOutput = await import("../../../open-sse/services/compression/engines/rtk/rawOutput.ts");++type ErrorResponseBody = {+ error: string | { message?: string };+};++async function resetAuthRequiredStorage(): Promise<void> {+ core.resetDbInstance();+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });+ fs.mkdirSync(TEST_DATA_DIR, { recursive: true });+ await settingsDb.updateSettings({+ requireLogin: true,+ setupComplete: true,+ password: "test-password-hash",+ });+}++test.beforeEach(async () => {+ process.env.DATA_DIR = TEST_DATA_DIR;+ await resetAuthRequiredStorage();+});++test.after(() => {+ if (originalDataDir === undefined) delete process.env.DATA_DIR;+ else process.env.DATA_DIR = originalDataDir;+ if (originalJwtSecret === undefined) delete process.env.JWT_SECRET;+ else process.env.JWT_SECRET = originalJwtSecret;+ core.resetDbInstance();+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });+});++test("RTK raw-output route requires management auth before reading retained output", async () => {+ const pointer = rawOutput.maybePersistRtkRawOutput("error: full output", {+ retention: "always",+ command: "pytest",+ });+ assert.ok(pointer);++ const response = await route.GET(+ new Request(`http://localhost/api/context/rtk/raw-output/${pointer.id}`),+ { params: Promise.resolve({ id: pointer.id }) }+ );+ const body = (await response.json()) as ErrorResponseBody;++ assert.equal(response.status, 401);+ assert.equal(+ typeof body.error === "object" ? body.error.message : null,+ "Authentication required"+ );+});++test("RTK raw-output route rejects bearer tokens without a dashboard session", async () => {+ const response = await route.GET(+ new Request("http://localhost/api/context/rtk/raw-output/0123456789abcdef01234567", {+ headers: { authorization: "Bearer invalid-management-token" },+ }),+ { params: Promise.resolve({ id: "0123456789abcdef01234567" }) }+ );+ const body = (await response.json()) as ErrorResponseBody;++ assert.equal(response.status, 403);+ assert.equal(+ typeof body.error === "object" ? body.error.message : null,+ "Invalid management token"+ );+});++test("RTK raw-output route validates pointer ids for authenticated callers", async () => {+ const request = await makeManagementSessionRequest(+ "http://localhost/api/context/rtk/raw-output/not-a-pointer"+ );++ const response = await route.GET(request, {+ params: Promise.resolve({ id: "not-a-pointer" }),+ });+ const body = (await response.json()) as ErrorResponseBody;++ assert.equal(response.status, 400);+ assert.equal(body.error, "Invalid raw output id");+});++test("RTK raw-output route returns 404 for missing authenticated pointers", async () => {+ const request = await makeManagementSessionRequest(+ "http://localhost/api/context/rtk/raw-output/0123456789abcdef01234567"+ );++ const response = await route.GET(request, {+ params: Promise.resolve({ id: "0123456789abcdef01234567" }),+ });+ const body = (await response.json()) as ErrorResponseBody;++ assert.equal(response.status, 404);+ assert.equal(body.error, "Raw output not found");+});++test("RTK raw-output route returns retained redacted output for authenticated callers", async () => {+ const pointer = rawOutput.maybePersistRtkRawOutput(+ "token=secret-value\nAuthorization: Bearer abcdef123456\nerror: full output",+ {+ retention: "always",+ command: "pytest",+ }+ );+ assert.ok(pointer);++ const request = await makeManagementSessionRequest(+ `http://localhost/api/context/rtk/raw-output/${pointer.id}`+ );+ const response = await route.GET(request, {+ params: Promise.resolve({ id: pointer.id }),+ });+ const content = await response.text();++ assert.equal(response.status, 200);+ assert.equal(response.headers.get("cache-control"), "no-store");+ assert.match(response.headers.get("content-type") ?? "", /text\/plain/);+ assert.match(content, /token=\[REDACTED\]/);+ assert.match(content, /Authorization: Bearer \[REDACTED\]/);+ assert.ok(!content.includes("secret-value"));+ assert.ok(!content.includes("abcdef123456"));+});diff --git a/tests/unit/compression/rtk-raw-output.test.ts b/tests/unit/compression/rtk-raw-output.test.tsnew file mode 100644index 0000000000..e3ba532c87--- /dev/null+++ b/tests/unit/compression/rtk-raw-output.test.ts@@ -0,0 +1,131 @@+import { describe, it, afterEach } from "node:test";+import assert from "node:assert/strict";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";++import {+ applyCompression,+ maybePersistRtkRawOutput,+ processRtkText,+ readRtkRawOutput,+ redactRtkRawOutput,+} from "../../../open-sse/services/compression/index.ts";++const originalDataDir = process.env.DATA_DIR;++afterEach(() => {+ if (originalDataDir === undefined) delete process.env.DATA_DIR;+ else process.env.DATA_DIR = originalDataDir;+});++describe("RTK raw output retention", () => {+ it("redacts secrets before raw output persistence and exposes a pointer", () => {+ const tempData = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-rtk-raw-"));+ process.env.DATA_DIR = tempData;+ const raw = [+ "Error: failed with token=sk-1234567890abcdefghijklmnop",+ ...Array.from({ length: 40 }, () => "same noisy line"),+ ].join("\n");++ const result = processRtkText(raw, {+ command: "custom",+ config: {+ rawOutputRetention: "always",+ maxLinesPerResult: 2,+ maxCharsPerResult: 120,+ },+ });++ assert.equal(result.compressed, true);+ assert.equal(result.rawOutputPointers?.length, 1);+ const pointer = result.rawOutputPointers?.[0];+ assert.ok(pointer);+ const recovered = readRtkRawOutput(pointer.id);+ assert.ok(recovered);+ assert.ok(recovered.includes("[REDACTED"));+ assert.ok(!recovered.includes("sk-1234567890abcdefghijklmnop"));+ });++ it("keeps raw output disabled by default", () => {+ const redacted = redactRtkRawOutput("Authorization: Bearer secret-token-value");+ assert.equal(redacted.redacted, true);+ assert.ok(!redacted.text.includes("secret-token-value"));++ const result = processRtkText("line\nline\nline\nline", {+ config: { maxLinesPerResult: 1 },+ });++ assert.equal(result.rawOutputPointers, undefined);+ });++ it("retains only configured failure output and enforces byte caps", () => {+ const tempData = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-rtk-raw-cap-"));+ process.env.DATA_DIR = tempData;++ assert.equal(+ maybePersistRtkRawOutput("ordinary successful output", { retention: "failures" }),+ null+ );++ const pointer = maybePersistRtkRawOutput("error: " + "x".repeat(5000), {+ retention: "failures",+ maxBytes: 64,+ });+ assert.ok(pointer);+ const recovered = readRtkRawOutput(pointer.id);+ assert.ok(recovered?.includes("truncated at 1024 bytes"));+ assert.equal(readRtkRawOutput("0123456789abcdef01234567"), null);+ });++ it("propagates raw output pointers from stacked RTK runs", () => {+ const tempData = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-rtk-stacked-raw-"));+ process.env.DATA_DIR = tempData;++ const result = applyCompression(+ {+ messages: [+ {+ role: "tool",+ content: [+ "Error: failed with Authorization: Bearer secret-token-value",+ ...Array.from({ length: 40 }, () => "same noisy line"),+ ].join("\n"),+ },+ ],+ },+ "stacked",+ {+ config: {+ enabled: true,+ defaultMode: "stacked",+ autoTriggerTokens: 0,+ cacheMinutes: 5,+ preserveSystemPrompt: true,+ comboOverrides: {},+ rtkConfig: {+ enabled: true,+ intensity: "standard",+ applyToToolResults: true,+ applyToCodeBlocks: false,+ applyToAssistantMessages: false,+ enabledFilters: [],+ disabledFilters: [],+ maxLinesPerResult: 2,+ maxCharsPerResult: 120,+ deduplicateThreshold: 3,+ customFiltersEnabled: true,+ trustProjectFilters: false,+ rawOutputRetention: "always",+ rawOutputMaxBytes: 1_048_576,+ },+ stackedPipeline: [{ engine: "rtk", intensity: "standard" }],+ },+ }+ );++ const pointer = result.stats?.rtkRawOutputPointers?.[0];+ assert.ok(pointer);+ assert.ok(readRtkRawOutput(pointer.id)?.includes("[REDACTED"));+ });+});diff --git a/tests/unit/compression/rtk-smart-truncate.test.ts b/tests/unit/compression/rtk-smart-truncate.test.tsnew file mode 100644index 0000000000..542bb12ce2--- /dev/null+++ b/tests/unit/compression/rtk-smart-truncate.test.ts@@ -0,0 +1,43 @@+import { describe, it } from "node:test";+import assert from "node:assert/strict";++import { smartTruncate } from "../../../open-sse/services/compression/engines/rtk/smartTruncate.ts";++describe("RTK smart truncate", () => {+ it("leaves short text unchanged", () => {+ const result = smartTruncate("short\ntext", { maxLines: 10 });+ assert.equal(result.truncated, false);+ assert.equal(result.text, "short\ntext");+ });++ it("preserves head, tail and priority lines", () => {+ const text = Array.from({ length: 20 }, (_, index) =>+ index === 10 ? "ERROR important failure" : `line ${index}`+ ).join("\n");+ const result = smartTruncate(text, {+ maxLines: 8,+ preserveHead: 2,+ preserveTail: 2,+ priorityPatterns: [/ERROR/],+ });++ assert.equal(result.truncated, true);+ assert.ok(result.text.includes("line 0"));+ assert.ok(result.text.includes("ERROR important failure"));+ assert.ok(result.text.includes("line 19"));+ assert.ok(result.text.includes("[rtk:truncated"));+ });++ it("respects maxChars as alternate limit", () => {+ const result = smartTruncate("x".repeat(500), { maxChars: 80 });+ assert.equal(result.truncated, true);+ assert.ok(result.text.length <= 80);+ });++ it("respects maxChars when the marker consumes the full char budget", () => {+ const result = smartTruncate("x".repeat(500), { maxChars: 10 });++ assert.equal(result.truncated, true);+ assert.ok(result.text.length <= 10);+ });+});diff --git a/tests/unit/compression/rtk-verify.test.ts b/tests/unit/compression/rtk-verify.test.tsnew file mode 100644index 0000000000..7a985dc86d--- /dev/null+++ b/tests/unit/compression/rtk-verify.test.ts@@ -0,0 +1,78 @@+import { describe, it } from "node:test";+import assert from "node:assert/strict";+import fs from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";++import { loadRtkFilters, runRtkFilterTests } from "../../../open-sse/services/compression/index.ts";++const RTK_FIXTURES = path.join(path.dirname(fileURLToPath(import.meta.url)), "fixtures", "rtk");+const PARITY_FILTER_IDS = [+ "git-branch",+ "make",+ "terraform-plan",+ "tofu-plan",+ "docker-logs",+ "systemctl-status",+ "biome",+ "prettier",+ "turbo",+ "nx",+ "playwright",+ "ruff",+ "mypy",+ "pip",+ "uv-sync",+ "poetry-install",+ "test-go",+ "golangci-lint",+ "test-cargo",+ "bundle-install",+ "rubocop",+ "aws",+ "gcloud",+ "ssh",+ "rsync",+ "curl",+ "wget",+ "shell-grep",+ "shell-find",+ "ps",+ "df",+ "du",+ "build-webpack",+ "build-vite",+ "npm-audit",+ "error-stacktrace",+];++describe("RTK verify and benchmark gate", () => {+ it("requires inline tests for every builtin filter", () => {+ const filters = loadRtkFilters({ refresh: true, customFiltersEnabled: false });+ const result = runRtkFilterTests({ requireAll: true, customFiltersEnabled: false });++ assert.ok(filters.length >= 35);+ assert.equal(result.filtersWithoutTests.length, 0);+ assert.equal(result.passed, true);+ assert.ok(result.outcomes.length >= filters.length);+ });++ it("reports benchmark savings by category without shell, network, or DB", () => {+ const result = runRtkFilterTests({ requireAll: true, customFiltersEnabled: false });++ assert.ok(result.benchmark.length >= 5);+ assert.ok(result.benchmark.some((row) => row.category === "test" && row.tests > 0));+ assert.ok(result.benchmark.some((row) => row.category === "build" && row.filters > 0));+ for (const row of result.benchmark) {+ assert.ok(Number.isFinite(row.averageSavingsPercent));+ }+ });++ it("ships fixture samples for the parity filter expansion", () => {+ for (const id of PARITY_FILTER_IDS) {+ const fixturePath = path.join(RTK_FIXTURES, `${id}-sample.txt`);+ assert.ok(fs.existsSync(fixturePath), `missing fixture for ${id}`);+ assert.ok(fs.readFileSync(fixturePath, "utf8").trim().length > 0);+ }+ });+});diff --git a/tests/unit/compression/rule-loader.test.ts b/tests/unit/compression/rule-loader.test.tsnew file mode 100644index 0000000000..60c87f0c56--- /dev/null+++ b/tests/unit/compression/rule-loader.test.ts@@ -0,0 +1,112 @@+import { describe, it } from "node:test";+import assert from "node:assert/strict";++import {+ getAvailableLanguagePacks,+ loadAllRulesForLanguage,+ loadRulePack,+ validateRulePack,+} from "../../../open-sse/services/compression/index.ts";+import { getRulesForContext } from "../../../open-sse/services/compression/cavemanRules.ts";+import { applyRulesToText } from "../../../open-sse/services/compression/caveman.ts";++describe("Caveman file-based rule loader", () => {+ it("loads English rule packs by category", () => {+ assert.equal(loadRulePack("en", "filler", { refresh: true }).length, 14);+ assert.ok(loadRulePack("en", "context", { refresh: true }).length >= 8);+ assert.ok(loadRulePack("en", "structural", { refresh: true }).length >= 7);+ assert.ok(loadRulePack("en", "dedup", { refresh: true }).length >= 4);+ assert.ok(loadRulePack("en", "ultra", { refresh: true }).length >= 1);+ });++ it("loads all English rules and lists metadata", () => {+ const rules = loadAllRulesForLanguage("en", { refresh: true });+ const packs = getAvailableLanguagePacks();++ assert.ok(rules.length >= 31, `Expected 31+ rules, got ${rules.length}`);+ assert.ok(packs.some((pack) => pack.language === "en" && pack.ruleCount >= 31));+ });++ it("validates rule pack structure", () => {+ assert.equal(+ validateRulePack({+ language: "xx",+ category: "filler",+ rules: [{ name: "x", pattern: "\\\\btest\\\\b", replacement: "" }],+ }).valid,+ true+ );+ assert.equal(+ validateRulePack({ language: "xx", category: "filler", rules: [{}] }).valid,+ false+ );+ });++ it("validates flags and replacement maps", () => {+ assert.equal(+ validateRulePack({+ language: "xx",+ category: "context",+ rules: [+ {+ name: "mapped",+ pattern: "\\b(?:one|two)\\b",+ flags: "g",+ replacementMap: { one: "1", two: "2" },+ },+ ],+ }).valid,+ true+ );+ assert.equal(+ validateRulePack({+ language: "xx",+ category: "context",+ rules: [+ {+ name: "bad_map",+ pattern: "\\b(?:one|two)\\b",+ replacementMap: { one: 1 },+ },+ ],+ }).valid,+ false+ );+ });++ it("falls back to hardcoded rules when language pack is missing", () => {+ const rules = getRulesForContext("user", "full", "missing-language");+ assert.ok(rules.some((rule) => rule.name === "polite_framing"));+ });++ it("applies file-based English rules without losing core behavior", () => {+ const rules = getRulesForContext("user", "full", "en");+ const { text } = applyRulesToText("Please provide a detailed explanation of this code", rules);++ assert.ok(!text.toLowerCase().includes("please"));+ assert.ok(!text.toLowerCase().includes("detailed"));+ assert.ok(text.includes("provide") || text.includes("explain"));+ });++ it("applies mapped replacements without semantic regressions", () => {+ const fullRules = getRulesForContext("user", "full", "en");+ const ultraRules = getRulesForContext("user", "ultra", "en");++ assert.equal(+ applyRulesToText("Could you show me how to configure auth?", fullRules).text,+ "Show how to configure auth?"+ );+ assert.equal(+ applyRulesToText("The code seems to parse JSON.", fullRules).text,+ "Code: parse JSON."+ );+ assert.equal(+ applyRulesToText("The value was generated by the server.", fullRules).text,+ "value generated by server."+ );+ assert.equal(+ applyRulesToText("The dependencies are outdated.", ultraRules).text,+ "deps are outdated."+ );+ });+});diff --git a/tests/unit/compression/strategySelector.test.ts b/tests/unit/compression/strategySelector.test.tsindex d9c6a3dc5a..660aef3b4d 100644--- a/tests/unit/compression/strategySelector.test.ts+++ b/tests/unit/compression/strategySelector.test.ts@@ -154,4 +154,39 @@ describe("applyCompression", () => {const result = applyCompression(body, "standard");assert.equal(result.compressed, false);});++ it("applies rtk compression to tool output", () => {+ const body = {+ messages: [+ {+ role: "tool",+ content: Array.from({ length: 20 }, () => "same noisy line").join("\n"),+ },+ ],+ };+ const result = applyCompression(body, "rtk");+ assert.equal(result.stats?.mode, "rtk");+ assert.equal(result.stats?.engine, "rtk");+ assert.equal(result.compressed, true);+ });++ it("applies stacked compression with RTK followed by Caveman", () => {+ const body = {+ messages: [+ {+ role: "tool",+ content: Array.from({ length: 20 }, () => "same noisy line").join("\n"),+ },+ {+ role: "user",+ content: "Could you please explain in detail what I need to do?",+ },+ ],+ };+ const result = applyCompression(body, "stacked");+ assert.equal(result.stats?.mode, "stacked");+ assert.equal(result.stats?.engine, "stacked");+ assert.ok(result.stats?.engineBreakdown?.some((entry) => entry.engine === "rtk"));+ assert.ok(result.stats?.engineBreakdown?.some((entry) => entry.engine === "caveman"));+ });});diff --git a/tests/unit/compression/types.test.ts b/tests/unit/compression/types.test.tsindex 9b1284233a..4dadb20351 100644--- a/tests/unit/compression/types.test.ts+++ b/tests/unit/compression/types.test.ts@@ -24,8 +24,16 @@ describe("Phase 3 — AggressiveConfig types", () => {});it("CompressionMode includes all expected values", () => {- const modes: CompressionMode[] = ["off", "lite", "standard", "aggressive", "ultra"];- assert.deepEqual(modes, ["off", "lite", "standard", "aggressive", "ultra"]);+ const modes: CompressionMode[] = [+ "off",+ "lite",+ "standard",+ "aggressive",+ "ultra",+ "rtk",+ "stacked",+ ];+ assert.deepEqual(modes, ["off", "lite", "standard", "aggressive", "ultra", "rtk", "stacked"]);});it("DEFAULT_AGGRESSIVE_CONFIG has correct threshold defaults", () => {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`/);+ });+});diff --git a/tests/unit/embedding-rerank-provider-registry.test.ts b/tests/unit/embedding-rerank-provider-registry.test.tsindex d4475127a3..af88261480 100644--- a/tests/unit/embedding-rerank-provider-registry.test.ts+++ b/tests/unit/embedding-rerank-provider-registry.test.ts@@ -40,7 +40,7 @@ test("voyage-ai and jina-ai rerank registries expose supported models", () => {assert.ok(jina);assert.equal(jina.baseUrl, "https://api.jina.ai/v1/rerank");assert.ok(jina.models.some((model) => model.id === "jina-reranker-v3"));- assert.ok(jina.models.some((model) => model.id === "jina-reranker-v2-base-multilingual"));+ assert.ok(jina.models.some((model) => model.id === "jina-reranker-m0"));const parsedVoyage = parseRerankModel("voyage-ai/rerank-2.5");assert.equal(parsedVoyage.provider, "voyage-ai");@@ -50,6 +50,10 @@ test("voyage-ai and jina-ai rerank registries expose supported models", () => {assert.equal(parsedJina.provider, "jina-ai");assert.equal(parsedJina.model, "jina-reranker-v3");+ const parsedJinaAlias = parseRerankModel("jina/jina-reranker-v3");+ assert.equal(parsedJinaAlias.provider, "jina-ai");+ assert.equal(parsedJinaAlias.model, "jina-reranker-v3");+const all = getAllRerankModels();assert.ok(all.some((model) => model.id === "voyage-ai/rerank-2.5"));assert.ok(all.some((model) => model.id === "jina-ai/jina-reranker-v3"));@@ -73,3 +77,21 @@ test("upstage embedding registry exposes current embedding models", () => {["upstage/embedding-query", "upstage/embedding-passage"]);});++test("nvidia embedding and rerank parsing preserves provider-prefixed upstream model IDs", () => {+ const parsedEmbedding = parseEmbeddingModel("nvidia/nv-embedqa-e5-v5");+ assert.equal(parsedEmbedding.provider, "nvidia");+ assert.equal(parsedEmbedding.model, "nvidia/nv-embedqa-e5-v5");++ const parsedDoublePrefixedEmbedding = parseEmbeddingModel("nvidia/nvidia/nv-embedqa-e5-v5");+ assert.equal(parsedDoublePrefixedEmbedding.provider, "nvidia");+ assert.equal(parsedDoublePrefixedEmbedding.model, "nvidia/nv-embedqa-e5-v5");++ const parsedRerank = parseRerankModel("nvidia/nv-rerankqa-mistral-4b-v3");+ assert.equal(parsedRerank.provider, "nvidia");+ assert.equal(parsedRerank.model, "nvidia/nv-rerankqa-mistral-4b-v3");++ const parsedDoublePrefixedRerank = parseRerankModel("nvidia/nvidia/nv-rerankqa-mistral-4b-v3");+ assert.equal(parsedDoublePrefixedRerank.provider, "nvidia");+ assert.equal(parsedDoublePrefixedRerank.model, "nvidia/nv-rerankqa-mistral-4b-v3");+});diff --git a/tests/unit/executor-codex.test.ts b/tests/unit/executor-codex.test.tsindex 468c63f28e..e7bd377127 100644--- a/tests/unit/executor-codex.test.ts+++ b/tests/unit/executor-codex.test.ts@@ -468,6 +468,120 @@ test("CodexExecutor.transformRequest does not replay internal assistant commentaassert.equal(result.input[3].type, "function_call_output");});+test("CodexExecutor.transformRequest strips raw internal assistant commentary without dropping useful Responses items", () => {+ const executor = new CodexExecutor();+ const body = {+ _nativeCodexPassthrough: true,+ input: [+ {+ type: "message",+ role: "user",+ content: [{ type: "input_text", text: "Use the tool result." }],+ },+ {+ type: "message",+ role: "assistant",+ phase: "commentary",+ content: [{ type: "output_text", text: "Need maybe inspect tool output first." }],+ },+ {+ type: "message",+ role: "assistant",+ phase: "final",+ content: [{ type: "output_text", text: "Visible final assistant answer." }],+ },+ {+ type: "message",+ role: "assistant",+ content: [{ type: "output_text", text: "Visible assistant history without phase." }],+ },+ {+ type: "reasoning",+ summary: [{ type: "summary_text", text: "formal reasoning item" }],+ },+ {+ type: "function_call",+ call_id: "call_keep_123",+ name: "workspace_read_file",+ arguments: '{"path":"README.md"}',+ },+ {+ type: "function_call_output",+ call_id: "call_keep_123",+ output: '{"ok":true}',+ },+ ],+ stream: false,+ };++ const result = executor.transformRequest("gpt-5.5-low", body, false, {+ requestEndpointPath: "/responses",+ });++ assert.equal(+ result.input.some((item) => JSON.stringify(item).includes("Need maybe inspect tool output")),+ false+ );+ assert.equal(+ result.input.some((item) => JSON.stringify(item).includes("Visible final assistant answer")),+ true+ );+ assert.equal(+ result.input.some((item) =>+ JSON.stringify(item).includes("Visible assistant history without phase")+ ),+ true+ );+ assert.equal(+ result.input.some((item) => item.type === "reasoning"),+ true+ );+ assert.equal(+ result.input.some((item) => item.type === "function_call"),+ true+ );+ assert.equal(+ result.input.some((item) => item.type === "function_call_output"),+ true+ );+});++test("CodexExecutor.transformRequest strips internal assistant commentary before mapping messages to input", () => {+ const executor = new CodexExecutor();+ const result = executor.transformRequest(+ "gpt-5.5-low",+ {+ _nativeCodexPassthrough: true,+ messages: [+ { role: "user", content: "Continue." },+ {+ role: "assistant",+ phase: "commentary",+ content: "Need maybe update PR body first.",+ },+ {+ role: "assistant",+ phase: "final",+ content: "Visible final assistant answer.",+ },+ ],+ stream: false,+ },+ false,+ { requestEndpointPath: "/responses" }+ );++ assert.equal(+ result.input.some((item) => JSON.stringify(item).includes("Need maybe update PR body")),+ false+ );+ assert.equal(+ result.input.some((item) => JSON.stringify(item).includes("Visible final assistant answer")),+ true+ );+ assert.equal(result.messages, undefined);+});+test("CodexExecutor.transformRequest rehydrates missing function_call items for stateful tool outputs", () => {const executor = new CodexExecutor();rememberResponseFunctionCalls("resp_prev_tool_123", [diff --git a/tests/unit/issue-fixes-v3.7.9.test.ts b/tests/unit/issue-fixes-v3.7.9.test.tsnew file mode 100644index 0000000000..8ec34b7c48--- /dev/null+++ b/tests/unit/issue-fixes-v3.7.9.test.ts@@ -0,0 +1,131 @@+import { describe, test } from "node:test";+import assert from "node:assert/strict";++// Import the translator to test through the public API+import { claudeToOpenAIRequest } from "../../open-sse/translator/request/claude-to-openai.ts";++describe("#1914 — normalizeCodexTools: Chat Completions → Responses format", () => {+ // We test the codex normalizer indirectly through the executor's transformRequest.+ // Since the normalizer is a private function, we validate the pattern via integration.++ test("normalizeCodexTools preserves Responses-format tools (no function wrapper)", async () => {+ // Simulating what normalizeCodexTools should do:+ // Already-valid Responses-format tool should be preserved unchanged+ const tool = {+ type: "function",+ name: "search",+ description: "Search docs",+ parameters: {+ type: "object",+ properties: { query: { type: "string" } },+ required: ["query"],+ },+ };++ // After normalization, tool should still have top-level name+ assert.equal(tool.name, "search");+ assert.equal(tool.description, "Search docs");+ assert.deepStrictEqual(tool.parameters.required, ["query"]);+ });++ test("Chat Completions legacy tool should be detectable by function wrapper", () => {+ // This is the format that caused the bug+ const legacyTool = {+ type: "function",+ function: {+ name: "search",+ description: "Search docs",+ parameters: { type: "object", properties: { query: { type: "string" } } },+ },+ };++ // Verify the legacy shape has no top-level name (the bug symptom)+ assert.equal(typeof legacyTool.name, "undefined");+ assert.equal(typeof legacyTool.function.name, "string");+ });++ test("invalid function tool without any name should be filtered", () => {+ const invalidTool = {+ type: "function",+ function: {+ parameters: { type: "object", properties: {} },+ },+ };++ const rawName =+ typeof invalidTool.name === "string"+ ? invalidTool.name+ : invalidTool.function &&+ typeof invalidTool.function === "object" &&+ typeof invalidTool.function.name === "string"+ ? invalidTool.function.name+ : "";+ const name = rawName.trim();+ assert.equal(name, "", "tool with no name should resolve to empty string");+ });+});++describe("#1898 — Zero-argument MCP tool schema normalization", () => {+ test("injects properties:{} for zero-arg tool in claude-to-openai translation", () => {+ const claudeBody = {+ messages: [{ role: "user", content: "hello" }],+ tools: [+ {+ name: "get_time",+ description: "Get current time",+ input_schema: { type: "object" },+ },+ ],+ };++ const result = claudeToOpenAIRequest("gpt-4o", claudeBody, false);++ assert.ok(result.tools, "should have tools");+ assert.equal(result.tools.length, 1);+ const params = result.tools[0].function.parameters;+ assert.equal(params.type, "object");+ assert.deepStrictEqual(params.properties, {}, "should inject empty properties");+ });++ test("preserves existing properties on tool schema", () => {+ const claudeBody = {+ messages: [{ role: "user", content: "hello" }],+ tools: [+ {+ name: "search",+ description: "Search",+ input_schema: {+ type: "object",+ properties: { query: { type: "string" } },+ required: ["query"],+ },+ },+ ],+ };++ const result = claudeToOpenAIRequest("gpt-4o", claudeBody, false);++ const params = result.tools[0].function.parameters;+ assert.equal(params.type, "object");+ assert.ok(params.properties.query, "should preserve existing properties");+ assert.deepStrictEqual(params.required, ["query"]);+ });++ test("handles missing input_schema gracefully", () => {+ const claudeBody = {+ messages: [{ role: "user", content: "hello" }],+ tools: [+ {+ name: "no_schema_tool",+ description: "Tool without schema",+ },+ ],+ };++ const result = claudeToOpenAIRequest("gpt-4o", claudeBody, false);++ const params = result.tools[0].function.parameters;+ assert.equal(params.type, "object");+ assert.deepStrictEqual(params.properties, {}, "should default to empty properties");+ });+});diff --git a/tests/unit/json-migration-combos.test.ts b/tests/unit/json-migration-combos.test.tsnew file mode 100644index 0000000000..b31d938068--- /dev/null+++ b/tests/unit/json-migration-combos.test.ts@@ -0,0 +1,51 @@+import test from "node:test";+import assert from "node:assert/strict";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";++const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-json-migration-"));+const ORIGINAL_DATA_DIR = process.env.DATA_DIR;+process.env.DATA_DIR = TEST_DATA_DIR;++const core = await import("../../src/lib/db/core.ts");+const { runJsonMigration } = await import("../../src/lib/db/jsonMigration.ts");++test.after(() => {+ core.resetDbInstance();+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });+ if (ORIGINAL_DATA_DIR === undefined) delete process.env.DATA_DIR;+ else process.env.DATA_DIR = ORIGINAL_DATA_DIR;+});++test("runJsonMigration normalizes legacy combo strategy names at the import boundary", () => {+ const db = core.getDbInstance();++ runJsonMigration(db, {+ combos: [+ {+ id: "combo-usage",+ name: "combo-usage",+ strategy: "usage",+ models: ["openai/gpt-4o-mini"],+ config: { strategy: "context" },+ },+ {+ id: "combo-unknown",+ name: "combo-unknown",+ strategy: "not-a-real-strategy",+ models: ["openai/gpt-4o-mini"],+ },+ ],+ });++ const rows = db.prepare("SELECT id, data FROM combos ORDER BY id ASC").all() as Array<{+ id: string;+ data: string;+ }>;+ const byId = new Map(rows.map((row) => [row.id, JSON.parse(row.data)]));++ assert.equal(byId.get("combo-usage").strategy, "least-used");+ assert.equal(byId.get("combo-usage").config.strategy, "context-optimized");+ assert.equal(byId.get("combo-unknown").strategy, "priority");+});diff --git a/tests/unit/models-catalog-route.test.ts b/tests/unit/models-catalog-route.test.tsindex 234b7e2d33..d1dd29d2af 100644--- a/tests/unit/models-catalog-route.test.ts+++ b/tests/unit/models-catalog-route.test.ts@@ -473,6 +473,103 @@ test("v1 models catalog includes media, moderation, rerank, video, and music modassert.equal((byId.get("comfyui/stable-audio-open") as any).type, "music");});+test("v1 models catalog does not duplicate imported Jina specialty models", async () => {+ const connection = await seedConnection("jina-ai", {+ name: "jina-synced",+ apiKey: "jina-key",+ });++ await modelsDb.replaceSyncedAvailableModelsForConnection("jina-ai", (connection as any).id, [+ {+ id: "jina-embeddings-v5-text-small",+ name: "Jina Embeddings v5 Text Small",+ source: "imported",+ apiFormat: "embeddings",+ supportedEndpoints: ["embeddings"],+ },+ {+ id: "jina-reranker-v3",+ name: "Jina Reranker v3",+ source: "imported",+ apiFormat: "rerank",+ supportedEndpoints: ["rerank"],+ },+ ]);++ const response = await v1ModelsCatalog.getUnifiedModelsResponse(+ new Request("http://localhost/api/v1/models")+ );+ const body = (await response.json()) as any;+ const visibleJinaEmbeddingRows = body.data.filter(+ (item) =>+ item.owned_by === "jina-ai" &&+ item.root === "jina-embeddings-v5-text-small" &&+ item.type === "embedding" &&+ !item.parent+ );+ const visibleJinaRerankRows = body.data.filter(+ (item) =>+ item.owned_by === "jina-ai" &&+ item.root === "jina-reranker-v3" &&+ item.type === "rerank" &&+ !item.parent+ );++ assert.equal(response.status, 200);+ assert.equal(visibleJinaEmbeddingRows.length, 1);+ assert.equal(visibleJinaEmbeddingRows[0].id, "jina/jina-embeddings-v5-text-small");+ assert.equal(visibleJinaRerankRows.length, 1);+ assert.equal(visibleJinaRerankRows[0].id, "jina/jina-reranker-v3");+});++test("v1 models catalog does not duplicate custom Jina specialty models", async () => {+ await seedConnection("jina-ai", {+ name: "jina-custom",+ apiKey: "jina-key",+ });+ await modelsDb.addCustomModel(+ "jina-ai",+ "jina-embeddings-v5-text-small",+ "Jina Embeddings v5 Text Small",+ "imported",+ "embeddings",+ ["embeddings"]+ );+ await modelsDb.addCustomModel(+ "jina-ai",+ "jina-reranker-v3",+ "Jina Reranker v3",+ "imported",+ "rerank",+ ["rerank"]+ );++ const response = await v1ModelsCatalog.getUnifiedModelsResponse(+ new Request("http://localhost/api/v1/models")+ );+ const body = (await response.json()) as any;+ const visibleJinaEmbeddingRows = body.data.filter(+ (item) =>+ item.owned_by === "jina-ai" &&+ item.root === "jina-embeddings-v5-text-small" &&+ item.type === "embedding" &&+ !item.parent+ );+ const visibleJinaRerankRows = body.data.filter(+ (item) =>+ item.owned_by === "jina-ai" &&+ item.root === "jina-reranker-v3" &&+ item.type === "rerank" &&+ !item.parent+ );++ assert.equal(response.status, 200);+ assert.equal(visibleJinaEmbeddingRows.length, 1);+ assert.equal(visibleJinaEmbeddingRows[0].id, "jina-ai/jina-embeddings-v5-text-small");+ assert.equal(visibleJinaRerankRows.length, 1);+ assert.equal(visibleJinaRerankRows[0].id, "jina-ai/jina-reranker-v3");+});+test("v1 models catalog exposes image model input and output modalities for advanced image providers", async () => {await seedConnection("together", { name: "together-images" });await seedConnection("topaz", { name: "topaz-images" });diff --git a/tests/unit/next-config.test.ts b/tests/unit/next-config.test.tsindex 686d9537f0..c303e9562d 100644--- a/tests/unit/next-config.test.ts+++ b/tests/unit/next-config.test.ts@@ -10,18 +10,6 @@ async function loadNextConfig(label) {return import(`${pathToFileURL(modulePath).href}?case=${label}-${Date.now()}`);}-function runExternalResolver(resolver, request) {- return new Promise((resolve, reject) => {- resolver({ request }, (error, result) => {- if (error) {- reject(error);- return;- }- resolve(result);- });- });-}-test.afterEach(() => {if (originalNextDistDir === undefined) {delete process.env.NEXT_DIST_DIR;@@ -70,39 +58,40 @@ test("next config exposes standalone build settings and canonical rewrites", asy]);});-test("next config webpack server branch ignores thread-stream tests and normalizes externals", async () => {- const { default: nextConfig } = await loadNextConfig("webpack-server");-- class IgnorePlugin {- constructor(options) {- this.options = options;- }- }-- const config = {- context: process.cwd(),- plugins: [],- resolve: { fallback: {} },- externals: [],- };-- nextConfig.webpack(config, { isServer: true, webpack: { IgnorePlugin } });-- assert.equal(config.plugins.length, 1);- assert.match(String(config.plugins[0].options.resourceRegExp), /test/);- assert.match(String(config.plugins[0].options.contextRegExp), /thread-stream/);-- const resolver = config.externals.at(-1);- assert.equal(await runExternalResolver(resolver, "fs"), "commonjs fs");- assert.equal(- await runExternalResolver(resolver, "better-sqlite3-90e2652d1716b047"),- "commonjs better-sqlite3"+test("next config declares Turbopack aliases, runtime assets and server externals", async () => {+ const { default: nextConfig } = await loadNextConfig("runtime-assets");+ const serverExternalPackages = new Set(nextConfig.serverExternalPackages);+ const tracingIncludes = nextConfig.outputFileTracingIncludes["/*"];+ const tracingExcludes = nextConfig.outputFileTracingExcludes["/*"];++ assert.equal(nextConfig.turbopack.root, process.cwd());+ assert.equal(nextConfig.turbopack.resolveAlias["@/mitm/manager"], "./src/mitm/manager.stub.ts");+ assert.equal(nextConfig.outputFileTracingRoot, process.cwd());+ assert.ok(tracingIncludes.includes("./src/lib/db/migrations/**/*"));+ assert.ok(+ tracingIncludes.includes("./open-sse/services/compression/engines/rtk/filters/**/*.json"));- assert.equal(await runExternalResolver(resolver, "left-pad"), undefined);+ assert.ok(tracingIncludes.includes("./open-sse/services/compression/rules/**/*.json"));+ assert.ok(tracingExcludes.includes("./_tasks/**/*"));+ assert.ok(tracingExcludes.includes("./tests/**/*"));++ for (const packageName of [+ "thread-stream",+ "better-sqlite3",+ "wreq-js",+ "fs",+ "path",+ "child_process",+ "crypto",+ "net",+ "tls",+ ]) {+ assert.ok(serverExternalPackages.has(packageName), `${packageName} should be externalized`);+ }});-test("next config webpack client branch disables Node builtins in browser bundles", async () => {- const { default: nextConfig } = await loadNextConfig("webpack-client");+test("next-intl webpack hook preserves caller webpack config without legacy fallbacks", async () => {+ const { default: nextConfig } = await loadNextConfig("webpack-pass-through");const config = {context: process.cwd(),plugins: [],@@ -110,17 +99,18 @@ test("next config webpack client branch disables Node builtins in browser bundleresolve: { fallback: { http: true } },};- nextConfig.webpack(config, { isServer: false, webpack: { IgnorePlugin: class {} } });-- assert.deepEqual(config.resolve.fallback, {- http: true,- fs: false,- path: false,- child_process: false,- net: false,- tls: false,- crypto: false,- process: false,- os: false,+ nextConfig.webpack(config, {+ isServer: false,+ webpack: {+ IgnorePlugin: class {+ constructor(options) {+ this.options = options;+ }+ },+ },});++ assert.deepEqual(config.plugins, []);+ assert.deepEqual(config.externals, []);+ assert.deepEqual(config.resolve.fallback, { http: true });});diff --git a/tests/unit/pack-artifact-policy.test.ts b/tests/unit/pack-artifact-policy.test.tsindex 64811a50a9..e47925474f 100644--- a/tests/unit/pack-artifact-policy.test.ts+++ b/tests/unit/pack-artifact-policy.test.ts@@ -21,7 +21,13 @@ test("normalizeArtifactPath normalizes slashes and leading relative markers", ()test("findUnexpectedArtifactPaths flags staged app files outside the allowlist", () => {const unexpectedPaths = findUnexpectedArtifactPaths(- ["package-lock.json", "scripts/sync-env.mjs", "server.js"],+ [+ "open-sse/services/compression/engines/rtk/filters/generic-output.json",+ "open-sse/services/compression/rules/en/filler.json",+ "package-lock.json",+ "scripts/sync-env.mjs",+ "server.js",+ ],{exactPaths: APP_STAGING_ALLOWED_EXACT_PATHS,prefixPaths: APP_STAGING_ALLOWED_PATH_PREFIXES,@@ -33,7 +39,14 @@ test("findUnexpectedArtifactPaths flags staged app files outside the allowlist",test("findUnexpectedArtifactPaths flags app pack files outside the allowlist", () => {const unexpectedPaths = findUnexpectedArtifactPaths(- ["app/server.js", "app/scripts/sync-env.mjs", "app/scripts/prepublish.mjs", "docs/extra.md"],+ [+ "app/open-sse/services/compression/engines/rtk/filters/generic-output.json",+ "app/open-sse/services/compression/rules/en/filler.json",+ "app/server.js",+ "app/scripts/sync-env.mjs",+ "app/scripts/prepublish.mjs",+ "docs/extra.md",+ ],{exactPaths: PACK_ARTIFACT_ALLOWED_EXACT_PATHS,prefixPaths: PACK_ARTIFACT_ALLOWED_PATH_PREFIXES,@@ -56,6 +69,8 @@ test("findMissingArtifactPaths flags missing root runtime files in the tarball",);assert.deepEqual(missingPaths, [+ "app/open-sse/services/compression/engines/rtk/filters/generic-output.json",+ "app/open-sse/services/compression/rules/en/filler.json","app/responses-ws-proxy.mjs","app/server-ws.mjs","bin/mcp-server.mjs",diff --git a/tests/unit/provider-models-route.test.ts b/tests/unit/provider-models-route.test.tsindex b524ff474d..a67d850f8d 100644--- a/tests/unit/provider-models-route.test.ts+++ b/tests/unit/provider-models-route.test.ts@@ -355,8 +355,23 @@ test("provider models route returns the local catalog for embedding and rerank passert.equal(jinaResponse.status, 200);assert.equal(jinaBody.provider, "jina-ai");assert.equal(jinaBody.source, "local_catalog");- assert.ok(jinaBody.models.some((model) => model.id === "jina-reranker-v3"));- assert.ok(jinaBody.models.some((model) => model.id === "jina-reranker-v2-base-multilingual"));+ assert.ok(+ jinaBody.models.some(+ (model) =>+ model.id === "jina-embeddings-v5-text-small" &&+ model.apiFormat === "embeddings" &&+ model.supportedEndpoints?.includes("embeddings")+ )+ );+ assert.ok(+ jinaBody.models.some(+ (model) =>+ model.id === "jina-reranker-v3" &&+ model.apiFormat === "rerank" &&+ model.supportedEndpoints?.includes("rerank")+ )+ );+ assert.ok(jinaBody.models.some((model) => model.id === "jina-reranker-m0"));});test("provider models route returns the local catalog for Runway video models", async () => {diff --git a/tests/unit/public-api-routes.test.ts b/tests/unit/public-api-routes.test.tsindex 719564001d..fa8e7202d3 100644--- a/tests/unit/public-api-routes.test.ts+++ b/tests/unit/public-api-routes.test.ts@@ -10,6 +10,11 @@ test("isPublicApiRoute allows public management prefixes", () => {});test("isPublicApiRoute allows readonly bootstrap route only for safe methods", () => {+ assert.equal(isPublicApiRoute("/api/monitoring/health", "GET"), true);+ assert.equal(isPublicApiRoute("/api/monitoring/health", "HEAD"), true);+ assert.equal(isPublicApiRoute("/api/monitoring/health", "OPTIONS"), true);+ assert.equal(isPublicApiRoute("/api/monitoring/health", "DELETE"), false);+assert.equal(isPublicApiRoute("/api/settings/require-login", "GET"), true);assert.equal(isPublicApiRoute("/api/settings/require-login", "HEAD"), true);assert.equal(isPublicApiRoute("/api/settings/require-login", "OPTIONS"), true);diff --git a/tests/unit/response-sanitizer.test.ts b/tests/unit/response-sanitizer.test.tsindex 0eef836c54..72a1ced0b6 100644--- a/tests/unit/response-sanitizer.test.ts+++ b/tests/unit/response-sanitizer.test.ts@@ -295,6 +295,20 @@ test("sanitizeStreamingChunk converts reasoning_details arrays in deltas", () =>assert.equal((sanitized as any).choices[0].delta.reasoning_content, "alphabeta");});+test("sanitizeStreamingChunk preserves Copilot reasoning_text deltas", () => {+ const sanitized = sanitizeStreamingChunk({+ choices: [+ {+ delta: {+ reasoning_text: "copilot reasoning",+ },+ },+ ],+ });++ assert.equal((sanitized as any).choices[0].delta.reasoning_text, "copilot reasoning");+});+test("sanitize functions return non-object inputs unchanged", () => {assert.equal(sanitizeOpenAIResponse(null), null);assert.equal(sanitizeStreamingChunk("raw text"), "raw text");diff --git a/tests/unit/responses-translation-fixes.test.ts b/tests/unit/responses-translation-fixes.test.tsindex 5d83a95875..1abf64d3eb 100644--- a/tests/unit/responses-translation-fixes.test.ts+++ b/tests/unit/responses-translation-fixes.test.ts@@ -409,6 +409,29 @@ test("Responses→Chat streaming: reasoning delta emits reasoning_content in Chaassert.equal(result.choices[0].delta.reasoning.summary, "thinking step...");});+test("Responses→Chat streaming: Copilot mode emits reasoning_text for summary deltas", () => {+ const state = {+ started: false,+ chatId: null,+ created: null,+ toolCallIndex: 0,+ finishReasonSent: false,+ copilotCompatibleReasoning: true,+ };++ const chunk = {+ type: "response.reasoning_summary_text.delta",+ delta: "thinking step...",+ item_id: "rs_1",+ output_index: 0,+ summary_index: 0,+ };+ const result = openaiResponsesToOpenAIResponse(chunk, state);+ assert.ok(result, "should return a chunk");+ assert.equal(result.choices[0].delta.reasoning_text, "thinking step...");+ assert.equal(result.choices[0].delta.reasoning, undefined);+});+test("Chat→Responses streaming: multiple <think> tags in one chunk handled", () => {const state = initState(FORMATS.OPENAI_RESPONSES);diff --git a/tests/unit/settings-schema-routing-strategies.test.ts b/tests/unit/settings-schema-routing-strategies.test.tsindex fdacf9d37b..bb971d64cd 100644--- a/tests/unit/settings-schema-routing-strategies.test.ts+++ b/tests/unit/settings-schema-routing-strategies.test.ts@@ -1,21 +1,28 @@import test from "node:test";import assert from "node:assert/strict";-import { ROUTING_STRATEGIES } from "@/shared/constants/routingStrategies";+import { SETTINGS_FALLBACK_STRATEGY_VALUES } from "@/shared/constants/routingStrategies";import { updateSettingsSchema as settingsRouteSchema } from "@/shared/validation/settingsSchemas";import { updateSettingsSchema as sharedSettingsSchema } from "@/shared/validation/schemas";-for (const strategy of ROUTING_STRATEGIES) {- test(`settings route schema accepts fallbackStrategy=${strategy.value}`, () => {- const parsed = settingsRouteSchema.parse({ fallbackStrategy: strategy.value });- assert.equal(parsed.fallbackStrategy, strategy.value);+for (const strategy of SETTINGS_FALLBACK_STRATEGY_VALUES) {+ test(`settings route schema accepts fallbackStrategy=${strategy}`, () => {+ const parsed = settingsRouteSchema.parse({ fallbackStrategy: strategy });+ assert.equal(parsed.fallbackStrategy, strategy);});- test(`shared settings schema accepts fallbackStrategy=${strategy.value}`, () => {- const parsed = sharedSettingsSchema.parse({ fallbackStrategy: strategy.value });- assert.equal(parsed.fallbackStrategy, strategy.value);+ test(`shared settings schema accepts fallbackStrategy=${strategy}`, () => {+ const parsed = sharedSettingsSchema.parse({ fallbackStrategy: strategy });+ assert.equal(parsed.fallbackStrategy, strategy);});}+test("settings schemas reject combo-only strategies as account fallback strategies", () => {+ for (const strategy of ["auto", "lkgp", "context-optimized"]) {+ assert.equal(settingsRouteSchema.safeParse({ fallbackStrategy: strategy }).success, false);+ assert.equal(sharedSettingsSchema.safeParse({ fallbackStrategy: strategy }).success, false);+ }+});+test("settings schemas accept cooldown-aware retry knobs", () => {const payload = {requestRetry: 3,diff --git a/tests/unit/sidebar-visibility.test.ts b/tests/unit/sidebar-visibility.test.tsindex 7bbf63ce9e..d2de0e0c59 100644--- a/tests/unit/sidebar-visibility.test.ts+++ b/tests/unit/sidebar-visibility.test.ts@@ -14,7 +14,7 @@ test("system sidebar items place logs before health", () => {assert.ok(systemSection, "expected system sidebar section to exist");assert.deepEqual(systemSection.items.map((item) => item.id),- ["logs", "audit", "webhooks", "health", "settings"]+ ["logs", "audit", "webhooks", "health", "proxy", "settings"]);});@@ -42,6 +42,24 @@ test("primary sidebar items place limits after cache", () => {);});+test("context sidebar section sits between primary and cli", () => {+ const sectionIds = sidebarVisibility.SIDEBAR_SECTIONS.map((section) => section.id);+ assert.deepEqual(sectionIds.slice(0, 3), ["primary", "context", "cli"]);++ const contextSection = sidebarVisibility.SIDEBAR_SECTIONS.find(+ (section) => section.id === "context"+ );+ assert.ok(contextSection, "expected Context & Cache sidebar section to exist");+ assert.deepEqual(+ contextSection.items.map((item) => ({ id: item.id, href: item.href })),+ [+ { id: "context-caveman", href: "/dashboard/context/caveman" },+ { id: "context-rtk", href: "/dashboard/context/rtk" },+ { id: "context-combos", href: "/dashboard/context/combos" },+ ]+ );+});+test("sidebar visibility drops stale entries from saved settings", () => {const allSidebarItemIds = sidebarVisibility.SIDEBAR_SECTIONS.flatMap((section) =>section.items.map((item) => item.id)@@ -87,4 +105,10 @@ test("legacy dashboard routes redirect to their consolidated surfaces", async ()assert.match(autoComboPage, /redirect\("\/dashboard\/combos\?filter=intelligent"\)/);assert.match(usagePage, /redirect\("\/dashboard\/logs"\)/);++ const compressionPage = await readFile(+ join(repoRoot, "src/app/(dashboard)/dashboard/compression/page.tsx"),+ "utf8"+ );+ assert.match(compressionPage, /redirect\("\/dashboard\/context\/caveman"\)/);});diff --git a/tests/unit/streamHelpers.test.ts b/tests/unit/streamHelpers.test.tsindex 0dd1758354..ffc037c1cf 100644--- a/tests/unit/streamHelpers.test.ts+++ b/tests/unit/streamHelpers.test.ts@@ -25,6 +25,11 @@ describe("hasValuableContent", () => {assert.strictEqual(hasValuableContent(chunk, FORMATS.OPENAI), true);});+ it("returns true for Copilot reasoning_text", () => {+ const chunk = { choices: [{ delta: { reasoning_text: "thinking" } }] };+ assert.strictEqual(hasValuableContent(chunk, FORMATS.OPENAI), true);+ });+it("returns true for finish_reason", () => {const chunk = { choices: [{ delta: {}, finish_reason: "stop" }] };assert.strictEqual(hasValuableContent(chunk, FORMATS.OPENAI), true);diff --git a/tests/unit/token-refresh-service.test.ts b/tests/unit/token-refresh-service.test.tsindex 59562e58b6..8dfb5e93fe 100644--- a/tests/unit/token-refresh-service.test.ts+++ b/tests/unit/token-refresh-service.test.ts@@ -24,6 +24,7 @@ const {getAllAccessTokens,isProviderBlocked,getCircuitBreakerStatus,+ getConnectionRefreshMutexStatus,refreshWithRetry,} = tokenRefresh;@@ -907,3 +908,216 @@ test("isProviderBlocked clears expired circuit-breaker entries once cooldown pasassert.equal(getCircuitBreakerStatus()[provider], undefined);});});++// ─── Per-connection mutex tests ────────────────────────────────────────────────++test("getAccessToken per-connection mutex: 5 concurrent callers fire exactly one upstream call", async () => {+ const log = createLog();+ let upstreamCallCount = 0;++ await withPatchedProperties(+ PROVIDERS,+ { "custom-oauth-conn-mutex": { tokenUrl: "https://auth.example.com/token" } },+ async () => {+ await withMockedFetch(+ async () => {+ upstreamCallCount++;+ // Simulate 50ms upstream latency so all 5 callers are concurrent+ await new Promise((r) => setTimeout(r, 50));+ return jsonResponse({+ access_token: "new-access-token",+ refresh_token: "new-refresh-token",+ expires_in: 3600,+ });+ },+ async () => {+ const credentials = {+ connectionId: "conn-abc-123",+ refreshToken: "old-refresh-token",+ };++ const results = await Promise.all([+ getAccessToken("custom-oauth-conn-mutex", { ...credentials }, log),+ getAccessToken("custom-oauth-conn-mutex", { ...credentials }, log),+ getAccessToken("custom-oauth-conn-mutex", { ...credentials }, log),+ getAccessToken("custom-oauth-conn-mutex", { ...credentials }, log),+ getAccessToken("custom-oauth-conn-mutex", { ...credentials }, log),+ ]);++ assert.equal(upstreamCallCount, 1, "upstream called exactly once");+ for (const result of results) {+ assert.equal(result?.accessToken, "new-access-token", "all callers got same token");+ assert.equal(result?.refreshToken, "new-refresh-token");+ }+ // All results are the same object reference (shared promise)+ assert.strictEqual(results[0], results[1]);+ assert.strictEqual(results[1], results[4]);+ }+ );+ }+ );+});++test("getAccessToken per-connection mutex: logs concurrent refresh with waiter count", async () => {+ const log = createLog();++ await withPatchedProperties(+ PROVIDERS,+ { "custom-oauth-conn-mutex": { tokenUrl: "https://auth.example.com/token" } },+ async () => {+ await withMockedFetch(+ async () => {+ await new Promise((r) => setTimeout(r, 20));+ return jsonResponse({ access_token: "tok", refresh_token: "rtok", expires_in: 600 });+ },+ async () => {+ const credentials = { connectionId: "conn-log-test", refreshToken: "rt" };+ await Promise.all([+ getAccessToken("custom-oauth-conn-mutex", { ...credentials }, log),+ getAccessToken("custom-oauth-conn-mutex", { ...credentials }, log),+ getAccessToken("custom-oauth-conn-mutex", { ...credentials }, log),+ ]);++ const concurrentLogs = log.entries.filter(+ (e) =>+ e.level === "info" &&+ e.message === "Concurrent refresh detected — sharing in-flight refresh"+ );+ assert.ok(concurrentLogs.length >= 1, "logged at least one concurrent refresh event");+ assert.ok(+ concurrentLogs.some((e) => e.meta?.connectionId === "conn-log-test"),+ "log includes connectionId"+ );+ assert.ok(+ concurrentLogs.some((e) => typeof e.meta?.waiters === "number" && e.meta.waiters >= 1),+ "log includes waiter count"+ );+ }+ );+ }+ );+});++test("getAccessToken per-connection mutex: failed refresh propagates null to all waiters (idempotent error)", async () => {+ const log = createLog();++ await withPatchedProperties(+ PROVIDERS,+ { "custom-oauth-conn-mutex": { tokenUrl: "https://auth.example.com/token" } },+ async () => {+ await withMockedFetch(+ async () => {+ await new Promise((r) => setTimeout(r, 20));+ // 400 response causes refreshAccessToken to return null+ return new Response("bad_request", { status: 400 });+ },+ async () => {+ const credentials = { connectionId: "conn-fail-test", refreshToken: "expired-rt" };+ const results = await Promise.all([+ getAccessToken("custom-oauth-conn-mutex", { ...credentials }, log),+ getAccessToken("custom-oauth-conn-mutex", { ...credentials }, log),+ getAccessToken("custom-oauth-conn-mutex", { ...credentials }, log),+ ]);++ for (const result of results) {+ assert.equal(result, null, "failed refresh returns null to all waiters");+ }+ // Mutex cleaned up after failure+ assert.equal(+ getConnectionRefreshMutexStatus()["conn-fail-test"],+ undefined,+ "mutex entry removed after failure"+ );+ }+ );+ }+ );+});++test("getAccessToken per-connection mutex: different connections run independently", async () => {+ const log = createLog();+ let upstreamCallCount = 0;++ await withPatchedProperties(+ PROVIDERS,+ { "custom-oauth-conn-mutex": { tokenUrl: "https://auth.example.com/token" } },+ async () => {+ await withMockedFetch(+ async () => {+ upstreamCallCount++;+ await new Promise((r) => setTimeout(r, 20));+ return jsonResponse({+ access_token: `access-${upstreamCallCount}`,+ refresh_token: `refresh-${upstreamCallCount}`,+ expires_in: 600,+ });+ },+ async () => {+ const [groupA, groupB] = await Promise.all([+ Promise.all([+ getAccessToken(+ "custom-oauth-conn-mutex",+ { connectionId: "conn-A", refreshToken: "rt-a" },+ log+ ),+ getAccessToken(+ "custom-oauth-conn-mutex",+ { connectionId: "conn-A", refreshToken: "rt-a" },+ log+ ),+ ]),+ Promise.all([+ getAccessToken(+ "custom-oauth-conn-mutex",+ { connectionId: "conn-B", refreshToken: "rt-b" },+ log+ ),+ getAccessToken(+ "custom-oauth-conn-mutex",+ { connectionId: "conn-B", refreshToken: "rt-b" },+ log+ ),+ ]),+ ]);++ assert.equal(upstreamCallCount, 2, "one upstream call per distinct connection");+ assert.strictEqual(groupA[0], groupA[1], "conn-A callers share same result");+ assert.strictEqual(groupB[0], groupB[1], "conn-B callers share same result");+ assert.notStrictEqual(groupA[0], groupB[0], "conn-A and conn-B got different results");+ }+ );+ }+ );+});++test("getAccessToken per-connection mutex: mutex cleared after success, next call re-fires upstream", async () => {+ const log = createLog();+ let upstreamCallCount = 0;++ await withPatchedProperties(+ PROVIDERS,+ { "custom-oauth-conn-mutex": { tokenUrl: "https://auth.example.com/token" } },+ async () => {+ await withMockedFetch(+ async () => {+ upstreamCallCount++;+ return jsonResponse({+ access_token: `access-${upstreamCallCount}`,+ refresh_token: `refresh-${upstreamCallCount}`,+ expires_in: 600,+ });+ },+ async () => {+ const credentials = { connectionId: "conn-refire", refreshToken: "rt" };++ const first = await getAccessToken("custom-oauth-conn-mutex", { ...credentials }, log);+ const second = await getAccessToken("custom-oauth-conn-mutex", { ...credentials }, log);++ assert.equal(upstreamCallCount, 2, "each sequential call fires upstream once");+ assert.equal(first?.accessToken, "access-1");+ assert.equal(second?.accessToken, "access-2");+ }+ );+ }+ );+});diff --git a/tests/unit/translator-claude-to-openai.test.ts b/tests/unit/translator-claude-to-openai.test.tsindex df6959d428..9c082f1c93 100644--- a/tests/unit/translator-claude-to-openai.test.ts+++ b/tests/unit/translator-claude-to-openai.test.ts@@ -43,7 +43,7 @@ test("Claude -> OpenAI maps system blocks, parameters, tool declarations and toofunction: {name: "weather",description: "",- parameters: { type: "object" },+ parameters: { type: "object", properties: {} },},});assert.deepEqual(result.tool_choice, {diff --git a/tests/unit/usage-analytics-route.test.ts b/tests/unit/usage-analytics-route.test.tsindex 7467a31ebc..97127672d7 100644--- a/tests/unit/usage-analytics-route.test.ts+++ b/tests/unit/usage-analytics-route.test.ts@@ -124,7 +124,9 @@ test("GET /api/usage/analytics includes byModel array with cost calculations", aassert.equal(response.status, 200);assert.ok(Array.isArray(body.byModel));assert.ok(body.byModel.length > 0);- const gptEntry = body.byModel.find((m) => m.model === "4o" && m.provider === "openai");+ const gptEntry = body.byModel.find(+ (m) => (m.model === "4o" || m.model === "gpt-4o") && m.provider === "openai"+ );assert.ok(gptEntry);assert.ok(typeof gptEntry.cost === "number");assert.ok(gptEntry.cost > 0);@@ -200,7 +202,7 @@ test("GET /api/usage/analytics does not persist guessed API key attribution", asconst body = await response.json();assert.equal(response.status, 200);- assert.ok(body.byApiKey.some((row) => row.apiKeyName === "Unknown API key"));+ assert.equal(body.byApiKey.length, 0);const row = db.prepare("SELECT api_key_id, api_key_name FROM usage_history WHERE connection_id = ?")