Spaces:
Runtime error
Runtime error
File size: 20,304 Bytes
cd8bd0a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 | ---
title: "Extending the Compression Pipeline"
version: 3.8.16
lastUpdated: 2026-06-08
---
# Extending the Compression Pipeline
> **TL;DR**: OmniRoute's compression engine is **pluggable** โ you can register custom engines, ship language packs for new languages, and compose stacked pipelines. This guide shows how.
**Related guides:**
- [COMPRESSION_GUIDE.md](./COMPRESSION_GUIDE.md) โ Full pipeline overview
- [COMPRESSION_ENGINES.md](./COMPRESSION_ENGINES.md) โ Engine registry and built-in engines
- [RTK_COMPRESSION.md](./RTK_COMPRESSION.md) โ RTK engine and custom filters
- [COMPRESSION_RULES_FORMAT.md](./COMPRESSION_RULES_FORMAT.md) โ Rule pack format reference
---
## Overview
The compression system has **3 extension points**:
| Extension point | Use case | Difficulty |
|-----------------|----------|------------|
| **Custom engine** | Add a brand-new compression algorithm (e.g., domain-specific summarizer) | Advanced |
| **Language pack** | Add support for a new natural language (e.g., Hindi, Arabic) | Medium |
| **Stacked pipeline** | Compose existing engines in a custom order | Beginner |
```
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Compression Strategy โ
โ โ
โ Input messages โโโถ getEffectiveMode() โโโถ mode โ
โ โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโ โ
โ โ โ โ โ โ โ
โ โผ โผ โผ โผ โ โ
โ "rtk" "lite" "standard" "stacked" โ
โ โ โ โ โ โ โ
โ โผ โผ โผ โผ โ โ
โ RTK Lite Caveman engines[] โ
โ engine engine engine chained โ
โ โ โ โ โ โ โ
โ โโโโโโโโโโโดโโโโโโโโโโดโโโโโโโโโโ โ โ
โ โ โ
โ โผ โ
โ Compressed output โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The strategy selector is MODE-BASED: each request selects ONE mode
(rtk / lite / standard / aggressive / ultra / stacked / off).
Only mode "stacked" chains multiple engines in sequence.
Default auto-trigger mode is "lite" (not a 3-tier priority chain).
```
---
## Writing a Custom Compression Engine
The engine interface (`open-sse/services/compression/engines/types.ts`) is the contract every engine must satisfy. It has 5 required methods.
### The `CompressionEngine` Interface
```ts
interface CompressionEngine {
id: string; // Unique engine ID
name: string; // Display name
description: string; // Short description
icon: string; // Icon (emoji or URL)
targets: CompressionEngineTarget[]; // ["messages", "tool_results", "code_blocks"]
stackable: boolean; // Can be used in a stacked pipeline
stackPriority: number; // Order in stacked pipelines (lower = earlier)
metadata: CompressionEngineMetadata;
apply(body, options?): CompressionResult;
compress(body, config?): CompressionResult;
getConfigSchema(): EngineConfigField[];
validateConfig(config): EngineValidationResult;
}
```
### Minimal Example: Whitespace Engine
The simplest possible engine โ strip extra whitespace from messages.
```ts
import type { CompressionEngine } from "omniroute/compression/engines/types";
import { registerCompressionEngine } from "omniroute/compression/engines/registry";
function preserveCodeBlocks(text: string): string {
// Split by code block markers and preserve whitespace inside them
const parts = text.split(/(```[\s\S]*?```)/);
return parts
.map((part) => {
if (part.startsWith("```")) {
return part; // Don't modify code blocks
}
return part.replace(/\n{3,}/g, "\n\n"); // Only apply to prose
})
.join("");
}
const whitespaceEngine: CompressionEngine = {
id: "whitespace",
name: "Whitespace Stripper",
description: "Removes extra whitespace and blank lines",
icon: "๐",
targets: ["messages", "tool_results"],
stackable: true,
stackPriority: 100, // Run AFTER caveman/rtk
metadata: {
id: "whitespace",
name: "Whitespace Stripper",
description: "Removes extra whitespace and blank lines",
inputScope: "messages",
targetLatencyMs: 5,
supportsPreview: true,
stable: true,
},
apply(body, options) {
return this.compress(body, options?.config);
},
compress(body, config = {}) {
let originalLength = 0;
let compressedLength = 0;
// Traverse message array โ handle both string and multipart content
const compressedBody = (body.messages || []).map((msg) => {
if (typeof msg.content === "string") {
originalLength += msg.content.length;
let compressed = msg.content
.replace(/[ \t]+/g, " ")
.replace(/\n{3,}/g, "\n\n")
.replace(/^\s+|\s+$/gm, "");
compressedLength += compressed.length;
return { ...msg, content: compressed };
}
// Multipart content: traverse parts, compress text parts only
if (Array.isArray(msg.content)) {
const newParts = msg.content.map((part) => {
if (part.type === "text" && typeof part.text === "string") {
originalLength += part.text.length;
let compressed = part.text
.replace(/[ \t]+/g, " ")
.replace(/\n{3,}/g, "\n\n")
.replace(/^\s+|\s+$/gm, "");
compressedLength += compressed.length;
return { ...part, text: compressed };
}
return part; // preserve image_url, tool_use, etc.
});
return { ...msg, content: newParts };
}
return msg;
});
return {
body: { ...body, messages: compressedBody },
stats: {
originalTokens: Math.ceil(originalLength / 4),
compressedTokens: Math.ceil(compressedLength / 4),
savingsPercent: originalLength > 0 ? 100 * (1 - compressedLength / originalLength) : 0,
techniques: ["whitespace-collapse"],
engineId: "whitespace",
},
};
},
getConfigSchema() {
return [
{
key: "preserveCodeBlocks",
type: "boolean",
label: "Preserve code blocks",
defaultValue: true,
description: "Don't touch whitespace inside ```code``` blocks",
},
];
},
validateConfig(config) {
if (config.preserveCodeBlocks !== undefined && typeof config.preserveCodeBlocks !== "boolean") {
return { valid: false, errors: ["preserveCodeBlocks must be a boolean"] };
}
return { valid: true, errors: [] };
},
};
// Register globally
registerCompressionEngine(whitespaceEngine);
```
### Where to Place Custom Engines
```
~/.omniroute/compression/engines/my-engine.ts # User-level
<project>/compression-engines/my-engine.ts # Project-level (loaded on startup)
```
Or load programmatically from a plugin:
```ts
// In your plugin
import { registerCompressionEngine, unregisterCompressionEngine } from "@omniroute/open-sse/services/compression/engines/registry";
import { myEngine } from "./engines/my-engine";
export default definePlugin({
name: "my-compression-plugin",
// The plugin SDK exposes onRequest / onResponse / onError hooks. Register the
// engine when the plugin module loads (or on first onRequest); unregister it
// from your own teardown path.
onRequest: async (ctx) => {
registerCompressionEngine(myEngine);
},
});
// On teardown:
// unregisterCompressionEngine("my-engine");
```
### Testing Your Engine
Register your engine in a plugin or startup function. Once registered, the engine will be available
in the strategy selector via its `id`. Test integration by composing it in a stacked pipeline:
---
## Creating Language Packs
Caveman-style compression uses **language-specific rule packs** to handle fillers, hedging, and verbose patterns in each natural language. OmniRoute ships with **6 language packs**: `en`, `es`, `fr`, `de`, `ja`, `pt-BR`.
### Pack Structure
A language pack is a directory of **JSON files** under `open-sse/services/compression/rules/<language>/`:
```
open-sse/services/compression/rules/
โโโ en/
โ โโโ filler.json # Pleasantries, hedging, politeness
โ โโโ context.json # Context-reducing rules
โ โโโ dedup.json # Deduplication rules
โ โโโ structural.json # Punctuation, formatting
โ โโโ ultra.json # Aggressive compression rules
โโโ es/ (same structure)
โโโ fr/ (same structure)
โโโ de/ (same structure)
โโโ ja/ (same structure)
โโโ pt-BR/ (same structure)
```
### Rule Anatomy
Each rule has this shape (from `open-sse/services/compression/ruleLoader.ts`):
```ts
interface FileRule {
name: string; // Human-readable name (kebab-case)
pattern: string; // JavaScript regex pattern
replacement?: string; // What to replace the match with
replacementMap?: Record<string, string>; // OR a keyโreplacement map
flags?: string; // Regex flags ("gi" typically)
context?: "all" | "user" | "system" | "assistant";
category?: "filler" | "context" | "structural" | "dedup" | "terse" | "ultra";
minIntensity?: "lite" | "full" | "ultra"; // Skip below this intensity
description?: string; // Documentation
}
```
### Example: Adding Hindi Filler Rules
```json
{
"language": "hi",
"category": "filler",
"rules": [
{
"name": "polite_opener",
"pattern": "\\b(?:เคจเคฎเคธเฅเคคเฅ|เคจเคฎเคธเฅเคเคพเคฐ|เคเคฆเคฐเคฃเฅเคฏ)\\b[,!\\s]*",
"replacement": "",
"context": "all",
"category": "filler",
"minIntensity": "lite",
"description": "Strip polite openers like 'เคจเคฎเคธเฅเคคเฅ'"
},
{
"name": "filler_actually",
"pattern": "\\b(?:เค
เคธเคฒ เคฎเฅเค|เคตเคพเคธเฅเคคเคต เคฎเฅเค|เคฆเคฐเค
เคธเคฒ)\\b\\s*",
"replacement": "",
"context": "all",
"category": "filler",
"minIntensity": "lite",
"description": "Strip 'actually' fillers"
},
{
"name": "verbose_plea",
"pattern": "\\b(?:เคเฅเคชเคฏเคพ|เคเฅเคชเคฏเคพ เคเคช|เค
เคจเฅเคฐเฅเคง เคนเฅ เคเคฟ เคเคช)\\b\\s*",
"replacement": "",
"context": "all",
"category": "filler",
"minIntensity": "full",
"description": "Strip 'please' in Hindi"
}
]
}
```
### Validation
Rule packs are validated against `_schema.json` on load. A pack with bad structure will fail to load and log an error:
```
RULE_LOADER: pack "hi/filler.json" failed validation:
- rules.0.pattern: Invalid regex
- rules.1.context: must be one of [all, user, system, assistant]
```
Validation runs automatically when a pack is loaded (against `_schema.json`); an
invalid pack is rejected and the error above is logged. There is no separate
`npm run` script for pack validation โ load the pack (e.g. start the server or
exercise the compression path) and watch the logs.
### Loading a Custom Language Pack
```ts
import { loadRulePack } from "omniroute/compression/ruleLoader";
await loadRulePack("./my-custom-rules/hi/filler.json");
```
Or place in a recognized location:
```
~/.omniroute/compression/rules/hi/filler.json # User-level
<project>/.compression/rules/hi/filler.json # Project-level
```
### Best Practices for Language Packs
1. **Start with `filler`** โ these are the highest-impact rules
2. **Use `minIntensity`** to gate aggressive rules โ protects against over-compression
3. **Include test cases** โ add `tests[]` array in the JSON to verify behavior
4. **Order matters** โ earlier rules apply first; place high-impact rules first
5. **Be conservative with `replacement`** โ empty string is usually correct; never introduce new content
### Translation Strategy
When localizing rule packs to a new language:
1. **Translate the rule names** โ they appear in debug output
2. **Adapt the regex patterns** โ direct translation often fails (word boundaries differ)
3. **Test against real conversations** โ the pack should be safe on actual input
4. **Match cultural conventions** โ Japanese packs, for instance, have more honorific fillers than English
---
## Stacked Pipelines
A **stacked pipeline** runs multiple engines in sequence, with each engine's output feeding the next. This is how `mode: stacked` works internally.
### How Stacking Works
```
Input (10,000 tokens)
โ
โผ
โโโโโโโโโโโโ
โ Engine โ priority 10
โ A โ โโโถ output: 6,000 tokens (-40%)
โโโโโโฌโโโโโโ
โผ
โโโโโโโโโโโโ
โ Engine โ priority 50
โ B โ โโโถ output: 2,400 tokens (-60%)
โโโโโโฌโโโโโโ
โผ
โโโโโโโโโโโโ
โ Engine โ priority 100
โ C โ โโโถ output: 1,200 tokens (-80%)
โโโโโโฌโโโโโโ
โ
โผ
Final output (1,200 tokens, ~88% savings combined)
```
When `mode: "stacked"` is selected, engines execute sequentially in the order specified in the `pipeline` array.
The output of engine N becomes the input of engine N+1.
### Compression Modes
OmniRoute selects **ONE mode per request** based on configuration, auto-trigger thresholds, and combo overrides.
The available modes are defined in `open-sse/services/compression/types.ts` (type `CompressionMode`):
| Mode | Engines | Use case |
|------|---------|----------|
| `off` | None | Disable all compression |
| `rtk` | RTK only | Command-output heavy sessions (80%+ savings) |
| `lite` | Lite only | Conservative compression (fast, safe) |
| `standard` | Caveman | Prose compression with language packs |
| `aggressive` | Caveman + Aggressive | Aggressive prose + aggressive final pass |
| `ultra` | Ultra | Maximum compression (lossy, last resort) |
| `stacked` | Custom pipeline | Compose engines in any order (see below) |
Mode selection is determined by `getEffectiveMode()` in `open-sse/services/compression/strategySelector.ts`:
1. If compression is disabled: `"off"`
2. If a combo override exists: use the override
3. If auto-trigger threshold is exceeded: use `autoTriggerMode` (default: `"lite"`)
4. Otherwise: use `defaultMode`
### The Default Stacked Pipeline
When `mode: "stacked"` is explicitly configured, the default pipeline composes:
1. **RTK** โ strip command output noise (~80% savings on terminal output)
2. **Caveman** โ remove fillers, terse-ify prose (~46% on remaining text)
3. **Lite** โ final whitespace + dedup pass
This composition achieves **78-95% savings** on tool-heavy sessions.
### Configuring Stacked Pipelines
In combo config:
```json
{
"compression": {
"mode": "stacked",
"pipeline": [
{ "engine": "rtk", "config": { "intensity": "aggressive" } },
{ "engine": "caveman", "config": { "intensity": "full" } },
{ "engine": "lite", "config": {} }
]
}
}
```
You can omit engines, add custom ones, or reorder them.
### State Passing
Engines can read metadata from the request context (in `options`):
```ts
compress(body, config) {
// Read metadata from previous engines
const original = options?.compressionComboId; // "my-coding-combo"
// ...
}
```
The metadata is **read-only** โ engines cannot mutate the request context, only their own body output.
### Execution Order Gotchas
| Engine order | Effect |
|--------------|--------|
| RTK โ Caveman โ Lite | **Recommended** (strips noise first, then language, then whitespace) |
| Lite โ RTK โ Caveman | Bad โ Lite strips whitespace from raw output, making RTK pattern matching fail |
| Caveman โ RTK | Bad โ Caveman may rewrite text in ways that RTK doesn't recognize |
| Any order with `tool_results` first | Better โ tool output is the noisiest content |
### When NOT to Stack
Stacking isn't always better:
- **Simple messages** (no tool output) โ single Caveman or Lite is enough
- **Cost-sensitive** โ each engine adds ~5-50ms latency
- **Specific tools** โ RTK alone is usually sufficient for shell output
### Building a Custom Pipeline
There is no named-pipeline registry. A stacked pipeline is just an **inline array
of steps** passed to `applyStackedCompression()` (exported from
`@omniroute/open-sse/services/compression/strategySelector`):
```ts
import { applyStackedCompression } from "@omniroute/open-sse/services/compression/strategySelector";
const result = applyStackedCompression(body, [
{ engine: "rtk", intensity: "aggressive" },
{ engine: "caveman", intensity: "full" },
]);
```
When you don't pass a pipeline, it defaults to `rtk(standard) โ caveman(full)`.
To drive it from config, set `mode: "stacked"` and provide the step array under
`stackedPipeline` (read from `config.stackedPipeline`):
```json
{
"compression": {
"mode": "stacked",
"stackedPipeline": [
{ "engine": "rtk", "intensity": "aggressive" },
{ "engine": "caveman", "intensity": "full" }
]
}
}
```
---
## Best Practices
### Engine Development
1. **Always implement `validateConfig`** โ engines without validation cause silent failures
2. **Set realistic `targetLatencyMs`** โ used by the strategy selector to choose engines
3. **Use `getConfigSchema` for the dashboard** โ never hide config from users
4. **Support `stackable: true` if your engine is pure** โ engines with side effects shouldn't stack
5. **Write inline tests** โ engines should be verifiable in <1s
### Language Pack Development
1. **Start with `lite` intensity** โ your rules should be safe at the lowest setting
2. **Use `context` to scope rules** โ `user` only rules can't accidentally affect system prompts
3. **Avoid capturing JSON keys** โ `\\bword\\b` can match inside JSON, breaking structured data
4. **Test with edge cases** โ empty input, unicode, RTL text, emojis
5. **Use existing packs as templates** โ `en/filler.json` is the most-developed example
### Pipeline Design
1. **Profile before optimizing** โ measure with `compression_stats` first
2. **Prefer composition over reimplementation** โ extend Caveman rules before writing a new engine
3. **Document the order rationale** โ comment why engine A before engine B
4. **Test at all 3 intensity levels** โ `lite` is fast but lossy, `ultra` is slow but precise
---
## Reference: Built-in Engines
| Engine ID | Stackable | Default stackPriority | Targets |
|-----------|-----------|-----------------------|---------|
| `lite` | Yes | 5 | messages, tool_results |
| `rtk` | Yes | 10 | tool_results |
| `standard` (caveman) | Yes | 20 | messages, tool_results, code_blocks |
| `aggressive` | Yes | 30 | messages |
| `ultra` | Yes | 40 | messages, code_blocks |
### See Also
- [COMPRESSION_GUIDE.md](./COMPRESSION_GUIDE.md) โ Pipeline overview
- [COMPRESSION_ENGINES.md](./COMPRESSION_ENGINES.md) โ Engine registry reference
- [COMPRESSION_RULES_FORMAT.md](./COMPRESSION_RULES_FORMAT.md) โ Rule format spec
- [COMPRESSION_LANGUAGE_PACKS.md](./COMPRESSION_LANGUAGE_PACKS.md) โ Language pack details
- [RTK_COMPRESSION.md](./RTK_COMPRESSION.md) โ RTK engine and custom filters
- Source: `open-sse/services/compression/` (117 files, ~250KB)
|