mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-07-31 12:22:14 +03:00
* chore(release): open v3.8.34 development cycle * chore(quality): release-green pre-flight validator + nightly signal (C+D) (#4622) C — scripts/quality/validate-release-green.mjs (npm run check:release-green): reproduces the release-equivalent validation (typecheck, eslint, db-rules, public-creds, full unit, vitest, ratchets, optional --with-build package-artifact) against the current working tree and classifies each red as HARD (real defect, exit 1) vs DRIFT (ratchet — reported, never affects exit / never blocks). Pure helpers exported + orchestration behind a direct-run guard; unit-tested. D — .github/workflows/nightly-release-green.yml: runs C on the active release branch nightly (and on workflow_dispatch) and opens/updates a single tracking issue on HARD failures. Never a required check, never touches a contributor PR. Closes the gap where the full gate (ci.yml) only ran on the release PR, so reds accrued silently on release/** and surfaced in 40-min layers at release time. Non-blocking by construction; drift is the maintainer's to rebaseline at release. Co-authored-by: Diego Rodrigues de Sa e Souza <diego.souza@cdwasolutions.com.br> * fix(providers): show revealed connection API keys (#4583) Integrated into release/v3.8.34 * fix(resilience): respect upstream retry hint toggle (#4585) Integrated into release/v3.8.34 * feat(settings): expose stream recovery feature flags (#4586) Integrated into release/v3.8.34 * fix(logs): make active request stale sweep configurable (#4599) Integrated into release/v3.8.34 * fix(plugin): auto-prefix providerId with 'opencode-' for OC 1.17.8+ native gate (#4527) Integrated into release/v3.8.34 (supersedes #4445) * fix(models): treat unknown output caps as unset (#4584) Integrated into release/v3.8.34 * fix(executors): strip temperature for GitHub Copilot gpt-5.4 family (#4564) Integrated into release/v3.8.34 (rebuilt onto tip) * fix(oauth): update Qwen OAuth URLs from chat.qwen.ai to qwen.ai (#4561) Integrated into release/v3.8.34 (rebuilt onto tip) * fix(api/settings): prevent cached /api/settings responses (port from 9router#951) (#4566) Integrated into release/v3.8.34 (rebuilt onto tip) * feat(audio): MiniMax T2A v2 TTS dispatch in audioSpeech (port #1043) (#4553) Integrated into release/v3.8.34 (rebuilt onto tip) * fix(dashboard): surface manual config CTA when Open Claw CLI auto-detect fails (#4562) Integrated into release/v3.8.34 (rebuilt onto tip) * feat(providers): optional model ID for custom API-key validation (#4555) Integrated into release/v3.8.34 (rebuilt onto tip) * fix(cli): align data dir and env loading with runtime (#4607) Integrated into release/v3.8.34 (rebuilt onto tip) * fix(quota): expose Bailian quota windows (#4610) Integrated into release/v3.8.34 (rebuilt onto tip) * fix: retain provider cooldowns for configured max window (#4588) Integrated into release/v3.8.34 (rebuilt — bundled commits stripped) * fix: reject invalid provider cooldown bounds (#4589) Integrated into release/v3.8.34 (rebuilt — bundled commits stripped) * fix: preserve production combo metrics on shadow eviction (#4590) Integrated into release/v3.8.34 (rebuilt — bundled commits stripped) * fix(stream): estimate input tokens when upstream reports prompt_tokens=0 (#4615) Integrated into release/v3.8.34 (rebuilt onto tip) * fix(catalog): shorten no-thinking gateway prefix to no-think/ (#4525) Integrated into release/v3.8.34 (rebuilt — kept only the prefix rename, dropped stale-base reverts) * fix(relay): apply IP rate limit to bifrost sidecar (#4593) Integrated into release/v3.8.34 (rebuilt onto tip; merge before #4612) * fix(bifrost): finalize SSE relay usage after stream (#4612) Integrated into release/v3.8.34 (rebuilt + reconciled with #4593) * feat(compression): per-request `x-omniroute-compression` header (Phase 3) (#4645) * docs(compression): Phase 3 per-request header design spec Approved brainstorming output for the x-omniroute-compression header: header-first precedence, name-first combo matching (Decision A), explicit value bypasses auto-trigger (Decision B), DerivedPlan.source, and the X-OmniRoute-Compression response header. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * docs(compression): Phase 3 per-request header implementation plan 4-task TDD plan (resolver header-first + source, parser, chatCore wiring + response header, docs/file-size) with full code and exact commands. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(compression): header-first resolver + plan source (Phase 3 core) Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(compression): resolveCompressionHeader parser (Phase 3) Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(compression): wire x-omniroute-compression header + response header (Phase 3) Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * refactor(compression): extract plan-resolution leaf (planResolution.ts) under size cap (Phase 3) Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * docs(compression): document x-omniroute-compression header (Phase 3) Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(compression): harden named-combo map + trim engine: header id (Phase 3 review) Addresses gemini-code-assist review on #4645: - Extract buildNamedComboLookup (pure) so a blank/whitespace/null combo name contributes only its id key (no '' key, no throw that disables all combos). - Trim the engine:<id> header value so 'engine: rtk' resolves. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Diego Rodrigues de Sa e Souza <diego.souza@cdwasolutions.com.br> Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Co-authored-by: Diego Rodrigues de Sa e Souza <souzamiriamrodrigues790@gmail.com> * fix: exclude exhausted connections from auto scoring (#4592) Integrated into release/v3.8.34 (rebuilt + opt-in gate fix) * fix(dashboard): memoize compatible provider groups (#4613) Integrated into release/v3.8.34 (rebuilt + test added) * fix(dashboard): isolate quota widget refresh clock (#4611) Integrated into release/v3.8.34 (rebuilt + jsdom test) * fix(dashboard): gate topology side effects behind widget visibility (#4606) Integrated into release/v3.8.34 (rebuilt + jsdom test) * fix(dashboard): keep play_arrow spinning on provider Test All buttons (#4563) Integrated into release/v3.8.34 (rebuilt onto tip; UI-cosmetic per owner) * fix(db): schedule retention cleanup + fix cleanup table/column names (extracted from #4428) (#4691) Integrated into release/v3.8.34 (cleanup core extracted from #4428, credit @oyi77) * fix(telemetry): back off live-WS event forwarding when the sidecar is unreachable (#4604) (#4687) Co-authored-by: Diego Rodrigues de Sa e Souza <souzamiriamrodrigues790@gmail.com> * fix(api): serve GET /v1/models/{model} as JSON, not the HTML dashboard (#4674) (#4677) Co-authored-by: Diego Rodrigues de Sa e Souza <souzamiriamrodrigues790@gmail.com> * feat(opencode): add go deepseek reasoning variants (#4647) Integrated into release/v3.8.34 * fix(executors): robust deepseek-web tool-call parsing and agentic context retention (#4644) Integrated into release/v3.8.34 * fix(cli): authenticate `omniroute logs` and honor active context (#4638) Integrated into release/v3.8.34 (authored by Rahul Sharma, AI co-author trailer stripped per project policy) * fix(proxy): apply pipelining:0 + connections cap to the direct dispatcher (#4580) (#4684) Co-authored-by: Diego Rodrigues de Sa e Souza <souzamiriamrodrigues790@gmail.com> * fix(executors): Firecrawl web_fetch 500 with include_metadata=true (#4692) Integrated into release/v3.8.34 * fix(routing): include all noAuth models in auto-combos + add reka-flash + best-free template (#4621) Integrated into release/v3.8.34 (dead getFirstRegistryModelId dropped, rebuilt onto tip) * fix(dashboard): gate home topology live-WS networking (#4596) (#4618) Integrated into release/v3.8.34 (adapted onto #4606's extracted topology section: default-hidden flip + enabled gate on useLiveDashboard) * fix(cli): align `omniroute` env loading with the runtime data dir (#4597) (#4619) Integrated into release/v3.8.34 (data-dir.mjs refactor reconciled with #4607; loadEnvFile aligned to getDefaultDataDir) * chore(quality): reconcile file-size baseline for #4644 (deepseek-web.ts 1117->1125) (#4695) file-size reconcile for #4644 * Support quota scraping for OpenCode Go and Ollama Cloud (#4642) Integrated into release/v3.8.34 (Ollama Cloud + OpenCode Go dashboard quota scraping; rebuilt onto tip, gates green: typecheck/public-creds/file-size/lint/docs-sync + 31 tests) * feat(executors): land M365 Copilot pure framing + connection helpers (#4042) (#4696) Land M365 pure modules ahead of draft #4400 * deps: bump production + development groups; migrate js-yaml to v5 ESM (#4697) Incorporates Dependabot #4667 + #4668 + js-yaml v5 ESM migration into release/v3.8.34 * fix: noAuth provider validation + kimi executor routing (#4699) Integrated into release/v3.8.34 (noAuth in NOAUTH_PROVIDERS dynamic check + remove misrouted kimi web alias; 9 tests) * refactor(imageGeneration): extract 8 provider families to co-located files (#4609) Integrated into release/v3.8.34 (extraction completed: added missing imports/exports per module, main imports handlers locally; 145 image-gen tests pass, typecheck/cycles/file-size green) * chore(release): v3.8.34 — finalize changelog, rebaseline drift, fix release-green reds - Finalize CHANGELOG [3.8.34] (43 bullets, full contributor attribution) + seed i18n mirrors - Rebaseline inherited cycle drift surfaced by release-green pre-flight: eslint warnings 3900->3907, cognitive-complexity 797->801 (release-finalize touches no prod code; all drift is from this cycle's contributor merges) - fix(providers): keep reka-flash-3 as the Reka provider default. #4621 inserted reka-flash at the head of the model list, silently changing the default from reka-flash-3 (the free-tier model) to reka-flash; reorder so reka-flash-3 stays default, reka-flash retained. - test: align provider-models-config / provider-models-route / web-cookie-providers-new with #4621 (reka-flash now in the Reka catalog) and #4699 (the `kimi` API-key provider correctly falls through to DefaultExecutor instead of KimiWebExecutor) - chore(quality): allowlist the COMPRESSION_GUIDE doc name in check-fabricated-docs (false-positive env-var match; docs/compression/COMPRESSION_GUIDE.md exists) * fix(release-green): resolve release-PR full-CI reds for v3.8.34 Surfaced only on the release PR (these gates don't run on PR->release fast-gates): - fix(quota): complete HTML-comment sanitization in opencodeOllamaUsage SSR reset-time parsing — strip any <!--...--> generically instead of the two literal React hydration markers, so no partial "<!--" can survive (CodeQL js/incomplete-multi-character- sanitization, HIGH, introduced by #4642). Regression test added. - test(codex): correct the Codex-fingerprint body key order assertion to match the canonical bodyFieldOrder (prompt_cache_key precedes include); #4584 flipped the two and integration tests don't run on fast-gates so it never executed until the release PR. - chore(quality): rebaseline inherited cycle drift surfaced by full CI — zizmorFindings 152->155 (+3 unpinned-uses in nightly-release-green.yml from #4622, same @vN convention as ci.yml) and openapiCoverage.pct 38.4->37.8 (-0.6, contributor routes added faster than openapi docs). Release-finalize touches no prod routes. * fix(release-green): complete CodeQL sanitization + rebaseline complexity drift - fix(quota): handle unterminated HTML comments in opencodeOllamaUsage SSR reset-time parsing — the `(?:-->|$)` arm consumes a trailing "<!--" with no closing "-->", so no partial "<!--" can survive (CodeQL js/incomplete-multi-character-sanitization persisted with the plain <!--...--> form because an unclosed comment could still leave "<!--"). - chore(quality): rebaseline cyclomatic complexity 1915->1916 (+1) — inherited v3.8.34 cycle drift (contributor feature branches); check:complexity does not run on PR->release fast-gates so it surfaced only on the release PR. Release-finalize adds 0 complexity (measured 1916 with/without the regex tweak). dead-code/cognitive/type-coverage/ compression-budget/codeql ratchets all pass. --------- Co-authored-by: Diego Rodrigues de Sa e Souza <diego.souza@cdwasolutions.com.br> Co-authored-by: Randi <55005611+rdself@users.noreply.github.com> Co-authored-by: Hernan Javier Ardila Sanchez <hjasgr@gmail.com> Co-authored-by: KooshaPari <42529354+KooshaPari@users.noreply.github.com> Co-authored-by: Abhishek Divekar <adivekar@utexas.edu> Co-authored-by: Rahul sharma <sharmaR0810@gmail.com> Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Co-authored-by: Diego Rodrigues de Sa e Souza <souzamiriamrodrigues790@gmail.com> Co-authored-by: Ronald Estacion <DevEstacion@users.noreply.github.com> Co-authored-by: Igor <60442260+BugsBag@users.noreply.github.com> Co-authored-by: Oonishi <275808243+ponkcore@users.noreply.github.com> Co-authored-by: Paijo <14921983+oyi77@users.noreply.github.com> Co-authored-by: Jan Leon <Jan.gaschler@gmail.com>
502 lines
18 KiB
Markdown
502 lines
18 KiB
Markdown
---
|
|
title: "🗜️ Prompt Compression Guide — OmniRoute"
|
|
version: 3.8.2
|
|
lastUpdated: 2026-05-13
|
|
---
|
|
|
|
# 🗜️ Prompt Compression Guide — OmniRoute
|
|
|
|
> 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
|
|
|
|
OmniRoute implements a modular prompt compression pipeline that runs **proactively** before requests hit upstream providers. This means your token savings happen transparently — no changes needed to your workflow.
|
|
|
|
```
|
|
Client Request
|
|
→ Compression Strategy Selector
|
|
→ Combo override? → Use combo setting
|
|
→ Auto-trigger threshold? → Use auto mode
|
|
→ Default mode? → Use global setting
|
|
→ Off? → Skip compression
|
|
→ Selected Compression Mode
|
|
→ Off: No compression
|
|
→ Lite: Safe whitespace/formatting cleanup (~15%)
|
|
→ 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
|
|
```
|
|
|
|
---
|
|
|
|
## Compression Modes
|
|
|
|
### Off
|
|
|
|
No compression applied. All messages pass through unchanged.
|
|
|
|
### Lite Mode (~15% savings, <1ms latency)
|
|
|
|
The safest mode — zero semantic change, only formatting cleanup:
|
|
|
|
| Technique | Description |
|
|
| ------------------------ | ------------------------------------------------- |
|
|
| `collapseWhitespace` | Merge consecutive blank lines and trailing spaces |
|
|
| `dedupSystemPrompt` | Remove duplicate system messages |
|
|
| `compressToolResults` | Compress verbose tool/function outputs |
|
|
| `removeRedundantContent` | Strip repeated instructions |
|
|
| `replaceImageUrls` | Shorten base64 image data URIs |
|
|
|
|
**Best for:** Always-on usage, safety-critical workflows.
|
|
|
|
### Standard Mode (~30% savings)
|
|
|
|
Inspired by [Caveman](https://github.com/JuliusBrussee/caveman) — removes filler words and verbose phrasing while preserving meaning:
|
|
|
|
- Removes filler words ("please", "I think", "basically", "actually")
|
|
- Condenses verbose phrases ("in order to" → "to", "as a result of" → "because")
|
|
- Strips polite hedging ("Would you mind...", "If you could possibly...")
|
|
- 30+ regex rules tuned for coding prompts
|
|
|
|
**Best for:** Daily coding workflows, cost-conscious teams.
|
|
|
|
### Aggressive Mode (~50% savings)
|
|
|
|
Smart history management for long sessions:
|
|
|
|
- **Message Aging** — older messages get progressively compressed
|
|
- **Tool Result Summarization** — long tool outputs replaced with summaries
|
|
- **Structural Integrity Guards** — ensures `tool_use` + `tool_result` pairs stay consistent
|
|
- **Context Window Awareness** — respects per-model token limits
|
|
|
|
**Best for:** Extended debugging sessions, large codebases.
|
|
|
|
### Ultra Mode (~75% savings)
|
|
|
|
Maximum compression for token-critical scenarios:
|
|
|
|
- **Heuristic Pruning** — removes messages below relevance threshold
|
|
- **Code Block Thinning** — compresses repetitive code examples
|
|
- **Binary Search Truncation** — finds optimal cut point for context window
|
|
- All Aggressive mode features included
|
|
|
|
**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
|
|
|
|
```
|
|
Without compression: 47K tokens sent to LLM
|
|
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)
|
|
```
|
|
|
|
---
|
|
|
|
## Configuration
|
|
|
|
### Dashboard
|
|
|
|
Navigate to `Dashboard → Context & Cache`:
|
|
|
|
- **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
|
|
|
|
In `Dashboard → Context & Cache → Compression Combos`, assign a compression combo to a routing
|
|
combo:
|
|
|
|
```txt
|
|
Combo: "free-forever"
|
|
Compression Combo: "coding-agent-stack"
|
|
Pipeline: RTK -> Caveman
|
|
Targets:
|
|
1. gc/gemini-3-flash
|
|
2. if/kimi-k2-thinking
|
|
```
|
|
|
|
This lets you use stacked compression on free/coding providers while keeping lite mode on paid
|
|
subscriptions.
|
|
|
|
### Per-request override
|
|
|
|
Send the `x-omniroute-compression` request header to override the compression plan for a single
|
|
request. It has the highest precedence — it beats the routing-combo override, the active profile,
|
|
auto-trigger, and the panel Default. Unknown values are ignored (the request is never rejected) and
|
|
the global master switch still gates everything: when compression is off globally, the header cannot
|
|
turn it on. Values:
|
|
|
|
| Value | Effect |
|
|
|-------|--------|
|
|
| `off` | No compression for this request. |
|
|
| `default` | The panel-derived Default profile (ignores the active profile). |
|
|
| `engine:<id>` | A single engine when enabled, e.g. `engine:rtk`. |
|
|
| `<combo>` | A named combo, matched by name (case-insensitive) first, then by id. |
|
|
|
|
The applied plan is echoed back in the `X-OmniRoute-Compression: <mode>; source=<source>` response
|
|
header, where `<source>` is one of `request-header`, `routing-override`, `active-profile`,
|
|
`auto-trigger`, `default`, or `off`.
|
|
|
|
### API
|
|
|
|
```bash
|
|
# Get compression settings
|
|
curl http://localhost:20128/api/settings/compression
|
|
|
|
# Update compression settings
|
|
curl -X PUT http://localhost:20128/api/settings/compression \
|
|
-H "Content-Type: application/json" \
|
|
-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"}'
|
|
```
|
|
|
|
---
|
|
|
|
## What Gets Protected
|
|
|
|
The compression engine **always preserves:**
|
|
|
|
- ✅ Code blocks (fenced and inline)
|
|
- ✅ URLs and file paths
|
|
- ✅ JSON structures and structured data
|
|
- ✅ 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
|
|
|
|
Every compressed request includes stats in the server logs:
|
|
|
|
```json
|
|
{
|
|
"originalTokens": 47200,
|
|
"compressedTokens": 40120,
|
|
"savingsPercent": 15.0,
|
|
"techniquesUsed": ["collapseWhitespace", "dedupSystemPrompt"],
|
|
"mode": "lite",
|
|
"engine": "caveman",
|
|
"compressionComboId": "coding-agent-stack",
|
|
"durationMs": 0.8,
|
|
"rtkRawOutputPointers": []
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
## Phase Roadmap
|
|
|
|
| Phase | Modes | Status |
|
|
| ------- | ------------------------------------ | ---------- |
|
|
| Phase 1 | Off, Lite | ✅ Shipped |
|
|
| Phase 2 | Standard, Aggressive, Ultra | ✅ Shipped |
|
|
| 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. 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.
|
|
|
|
---
|
|
|
|
## Advanced Compression Systems
|
|
|
|
Beyond the 7 standard modes, OmniRoute includes several advanced compression
|
|
systems that work automatically based on context.
|
|
|
|
### Cache-Aware Compression
|
|
|
|
Some providers (like Anthropic with prompt caching) support **prompt caching**,
|
|
which lets them cache parts of the prompt to reduce costs and latency. When
|
|
caching is enabled, aggressive compression can actually **hurt** performance
|
|
because it changes the cached tokens, invalidating the cache.
|
|
|
|
The `cachingAware.ts` module solves this by **detecting caching context** and
|
|
**adjusting the compression strategy** accordingly.
|
|
|
|
#### How it works
|
|
|
|
1. **Detect caching context** — Scans the request body for `cache_control` markers
|
|
2. **Identify caching providers** — Checks if the target provider supports caching
|
|
3. **Adjust strategy** — Downgrades `aggressive`/`ultra` to `standard` for caching providers
|
|
4. **Skip system prompt** — System prompts are usually cached, so don't compress them
|
|
5. **Use deterministic transformations** — Only use transformations that produce consistent output
|
|
|
|
#### Code example
|
|
|
|
```ts
|
|
import { detectCachingContext, getCacheAwareStrategy } from "@omniroute/open-sse/services/compression/cachingAware";
|
|
|
|
const body = {
|
|
model: "anthropic/claude-sonnet-4.5",
|
|
messages: [{ role: "user", content: "Hello" }],
|
|
cache_control: { type: "ephemeral" }, // ← Cache marker
|
|
};
|
|
|
|
const ctx = detectCachingContext(body, { provider: "anthropic" });
|
|
// → { hasCacheControl: true, provider: "anthropic", isCachingProvider: true }
|
|
|
|
const strategy = getCacheAwareStrategy("aggressive", ctx);
|
|
// → { strategy: "standard", skipSystemPrompt: true, deterministicOnly: true }
|
|
```
|
|
|
|
#### When to use
|
|
|
|
Cache-aware compression is **always on** — no configuration needed. It only kicks in
|
|
when:
|
|
- The request has `cache_control` markers
|
|
- The target provider supports prompt caching (Anthropic, OpenAI, etc.)
|
|
|
|
### Progressive Aging
|
|
|
|
Long conversations accumulate many message turns, but older turns become less
|
|
relevant. The `progressiveAging.ts` module **degrades messages by turn distance**:
|
|
|
|
- **Recent turns (0-3)**: Kept verbatim (full detail)
|
|
- **Medium turns (4-8)**: Lite compression (whitespace, formatting cleanup)
|
|
- **Old turns (9+)**: Caveman compression (filler removal, summarization)
|
|
- **Very old turns (20+)**: Heavily summarized or dropped
|
|
|
|
#### Code example
|
|
|
|
```ts
|
|
import { applyAging } from "@omniroute/open-sse/services/compression/progressiveAging";
|
|
|
|
const messages = [
|
|
{ role: "system", content: "You are a helpful assistant" },
|
|
{ role: "user", content: "What is 2+2?" },
|
|
{ role: "assistant", content: "4" },
|
|
// ... 50 more turns ...
|
|
];
|
|
|
|
const { messages: aged, saved } = applyAging(messages, {
|
|
verbatim: 3, // First 3 turns: verbatim
|
|
light: 8, // Turns 4-8: lite compression
|
|
moderate: 20, // Turns 9-20: caveman compression
|
|
// Turns 21+: heavy summarization
|
|
});
|
|
|
|
// saved = number of tokens saved
|
|
```
|
|
|
|
#### When to use
|
|
|
|
Progressive aging is **always on** for `aggressive` and `ultra` modes. It's
|
|
particularly effective for:
|
|
- Long-running coding sessions
|
|
- Multi-day conversations
|
|
- Agentic workflows with many tool calls
|
|
|
|
### Caveman Output Mode
|
|
|
|
The `outputMode.ts` module injects **system prompt instructions** to make the
|
|
model itself produce compressed, terse output (a "caveman" style).
|
|
|
|
#### How it works
|
|
|
|
Instead of compressing the input, this mode adds a system prompt like:
|
|
> "Reply in minimal words. Skip pleasantries. Use short sentences."
|
|
|
|
This works particularly well for:
|
|
- Code generation (terser output = fewer tokens)
|
|
- Quick Q&A (no need for elaborate explanations)
|
|
- Batch processing (maximize throughput)
|
|
|
|
#### When to use
|
|
|
|
Caveman output mode is **opt-in** — set it via the combo config:
|
|
```json
|
|
{
|
|
"strategy": "auto",
|
|
"config": {
|
|
"auto": {
|
|
"outputMode": "caveman"
|
|
}
|
|
}
|
|
}
|
|
```
|
|
|
|
### Tool Result Compression
|
|
|
|
The `toolResultCompressor.ts` module provides **5 specialized compression strategies**
|
|
for tool results (function calls, agent outputs, search results, etc.):
|
|
|
|
1. **Search result compression** — Removes redundant results, keeps top-N
|
|
2. **File read compression** — Truncates large files, preserves headers/imports
|
|
3. **Code execution compression** — Keeps only essential stdout/stderr
|
|
4. **Database query compression** — Limits rows, removes verbose metadata
|
|
5. **API response compression** — Strips null fields, condenses arrays
|
|
|
|
#### When to use
|
|
|
|
Tool result compression is **always on** when tool calls are present. No
|
|
configuration needed.
|
|
|
|
### Stacked Pipeline
|
|
|
|
The stacked mode runs **multiple engines in sequence** — usually RTK first
|
|
(60-90% savings on tool output), then Caveman (30% additional savings on the
|
|
remaining text). This achieves **78-95% total savings**.
|
|
|
|
#### How it works
|
|
|
|
```
|
|
Input (1000 tokens)
|
|
→ RTK (command-aware filter) → 200 tokens
|
|
→ Caveman (filler removal) → 140 tokens
|
|
→ Output (140 tokens, 86% savings)
|
|
```
|
|
|
|
#### When to use
|
|
|
|
Use stacked mode for:
|
|
- Tool-heavy workflows (agentic coding, research)
|
|
- Cost-sensitive batch processing
|
|
- When you need maximum token savings
|
|
|
|
Configure via combo:
|
|
```json
|
|
{
|
|
"strategy": "auto",
|
|
"config": {
|
|
"auto": {
|
|
"modePack": "stacked"
|
|
}
|
|
}
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
## Compression Combo Overrides
|
|
|
|
You can override the global compression mode **per combo** to fine-tune behavior
|
|
for different use cases:
|
|
|
|
```json
|
|
{
|
|
"id": "coding-combo",
|
|
"strategy": "priority",
|
|
"config": {
|
|
"auto": {
|
|
"weights": { "taskFit": 0.5 },
|
|
"modePack": "quality-first"
|
|
}
|
|
},
|
|
"compressionOverride": {
|
|
"mode": "aggressive",
|
|
"stackedPipelines": ["rtk", "caveman"],
|
|
"preserveToolDefinitions": true
|
|
}
|
|
}
|
|
```
|
|
|
|
This is useful for:
|
|
- **Coding combos**: Use `aggressive` mode for long sessions
|
|
- **Quick Q&A combos**: Use `lite` mode for fast responses
|
|
- **Tool-heavy combos**: Use `stacked` mode for max savings
|
|
- **Production combos**: Use `cache-aware` mode for caching providers
|
|
|
|
---
|
|
|
|
## See Also
|
|
|
|
- [Environment Config](../reference/ENVIRONMENT.md) — Compression environment variables
|
|
- [Architecture Guide](../architecture/ARCHITECTURE.md) — Compression pipeline internals
|
|
- [User Guide](../guides/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 rules
|