Files
OmniRoute/docs/RTK_COMPRESSION.md
Diego Rodrigues de Sa e Souza 99c6dc7fd6 Release v3.7.9 (#1917)
* chore(release): v3.7.9 — gemini-cli cloud code separation

* chore(provider): Update Jina AI model catalog (#1874)

Integrated into release/v3.7.9

* docs: update CHANGELOG for PR 1874 and retroactive credits

* fix: resolve stream defaults and codex prompt mapping (#1873, #1872)

* chore(compression): start caveman compression update

* feat(compression): expand caveman compression and analytics pipeline

Add caveman intensity levels, output mode instructions, validation, and
preview diffs across the compression pipeline.

Extend MCP and dashboard settings to support auto-trigger mode, system
prompt preservation, MCP description compression, and caveman rule
metadata. Record richer compression analytics with receipt fields,
validation fallbacks, output mode data, and add the related database
migration.

Improve preservation handling for code, URLs, markdown, math, and other
protected content while adding broad unit, integration, and golden-set
coverage for caveman parity and compression behavior.

* feat(compression): expose rule intensities and track usd savings

Add estimated USD savings to compression analytics so saved tokens can
be reported in cost terms alongside existing token metrics.

Expose caveman rule intensity metadata for settings consumers and add a
settings API route alias for rule lookup. Also preserve system prompts
when aggressive compression falls back to lite mode.

* feat(compression): RTK compression roadmap (#1889)

* chore(rtk): initialize compression roadmap branch

* feat(compression): add RTK engine and compression combos

Introduce RTK command-aware tool-output compression alongside
stacked RTK -> Caveman pipelines for mixed prompt contexts.

Add engine registration, declarative RTK filter packs, language-aware
Caveman rule loading, compression combo persistence and assignments,
analytics grouped by engine/combo, and new MCP/API endpoints for
configuration, previews, filters, and combo management.

Expose the new capabilities in the dashboard with dedicated Context &
Cache pages for Caveman, RTK, and compression combos, and update docs,
i18n strings, migrations, and tests to cover the expanded compression
surface.

* feat(compression): expand RTK DSL, filter catalog, and recovery APIs

Add RTK parity features across the compression pipeline, dashboard,
and management APIs. This expands the built-in filter catalog, adds
trust-gated custom filter loading, inline filter verification, code
stripping, smarter detection, and optional redacted raw-output
retention for authenticated recovery.

Also extend Caveman with file-based multilingual rule packs, localized
output-mode instructions, stricter preview/config schemas, engine
registry metadata, analytics fields, and broad unit test coverage for
RTK, rule loading, and stacked compression behavior.

* fix(auth): protect oauth routes and health reset operations

Require authenticated dashboard access for OAuth endpoints that can
create or import provider connections when login enforcement is
enabled.

Move `/api/monitoring/health` to the readonly public route list so
safe methods remain public while DELETE now returns 401 for anonymous
requests.

Also update Next.js native `.node` handling to avoid webpack parse
failures from external packages such as ngrok and keytar, and add
coverage for the new auth behavior.

* build(compression): ship RTK rule and filter assets with app bundles

Include compression JSON assets in Next output tracing, prepublish copies,
and pack artifact policy checks so standalone and packaged builds can
load RTK filters and caveman rule packs at runtime.

Also harden compression runtime behavior by resolving alternate asset
directories, scoping rule cache entries by source path, carrying RTK raw
output pointers through stacked runs, degrading oversized preview diffs,
and applying combo language/output mode defaults during chat routing.

Add coverage for packaging rules, provider-scoped model parsing, smart
truncate edge cases, raw output retention, and combo-driven compression
behavior.

* docs(workflows): update local repo paths to OmniRoute

Replace outdated `/home/diegosouzapw/dev/proxys/9router` references
with the current `OmniRoute` directory across deploy, release, and
version bump workflow guides so local command examples match the
renamed repository layout

* feat(compression): complete RTK parity coverage

* test(build): align next config assertions

---------

Co-authored-by: diegosouzapw <diego.souza.pw@gmail.com>

* feat(compression): expand caveman parity and MCP metadata compression

Compress MCP registry and list metadata descriptions for tools, prompts,
resources, and resource templates while keeping tool-response bodies
unchanged. Expose those savings in compression status as
`mcp_metadata_estimate` metadata rather than provider usage.

Add Caveman rule-pack support for custom regex flags and match-specific
replacement maps, update English rules for upstream parity, and tighten
article and pleasantry handling. Also process RTK multipart text blocks
independently so mixed media content compresses safely without
duplicating output.

* feat(compression): unify config validation and persist MCP savings

Centralize compression config schemas across settings, preview, RTK,
and combo APIs to enforce consistent validation for stacked pipelines
and engine-specific options.

Expand caveman and stacked compression behavior by applying default
combos at runtime, surfacing validation and fallback metadata, and
exposing aggressive and ultra adapter schemas for configuration UI and
tests.

Persist MCP description compression snapshots into analytics without
counting them as provider usage, and extend the dashboard with the new
RTK controls and localized labels.

* fix(auth): require dashboard management auth for compression preview

Block preview requests unless they come from a valid management session
token so protected settings cannot be probed through the preview API.

Add unit coverage for unauthenticated requests, invalid bearer tokens,
and successful authenticated preview execution.

* fix(compression): preserve stacked defaults and secure metadata routes

Only apply saved default compression combos when they contain a stacked
pipeline so seeded Caveman-only defaults do not replace the builtin
stacked behavior.

Also require management auth for compression language pack and rules
metadata endpoints, and defer usage receipt attachment until compression
analytics writes have completed to keep analytics records consistent.

* fix(compression): align seeded standard savings combo with stacked default

Update the seeded default compression combo to use the RTK then
Caveman pipeline in both fresh installs and upgraded databases.

Add a targeted migration and runtime guard that only rewrites the
legacy seeded record when its original metadata and single-step
pipeline still match, preserving user-customized default combos.
Refresh docs and tests to reflect the stacked default and expanded
RTK filter catalog.

* docs(compression): document RTK+Caveman stacked savings ranges

Refresh the compression docs and README to describe the default
stacked pipeline in terms of eligible-context savings instead of the
older generic token-saving range.

Add upstream RTK and Caveman benchmark references, explain the
multiplicative savings math behind the stacked default, and update
feature summaries plus package metadata to match the revised
positioning.

* feat(image-gen): add NanoGPT image generation provider (#1899)

Integrated into release/v3.7.9

* fix(codex): sanitize raw responses input (#1895)

Integrated into release/v3.7.9

* Fix combo provider breaker profile handling (#1891)

Integrated into release/v3.7.9

* fix(combos): align strategy contracts (#1892)

Integrated into release/v3.7.9

* feat(proxy): move proxy configuration to dedicated System → Proxy page (#1907)

Integrated into release/v3.7.9

* feat: add K/M/B/T cost shortener to prevent UI overflow (#1902)

Integrated into release/v3.7.9

* feat(providers): implement bulk paste for extra API keys (#1916)

Integrated into release/v3.7.9

* fix(migrations): treat duplicate-column ALTER as no-op (#1886)

Integrated into release/v3.7.9

* fix(analytics): robust model pricing resolution, dark mode charts and SQL aggregation fixes (#1896)

Integrated into release/v3.7.9 (migration renumbered to 044)

* fix(oauth): per-connection mutex for rotating refresh tokens (#1885)

Integrated into release/v3.7.9

* fix: resolve 3 bugs — Codex tool normalization (#1914), image gen proxy (#1904), zero-arg MCP tools (#1898)

- fix(codex): flatten Chat Completions tool format to Responses format in
  normalizeCodexTools. Prevents 'Missing required parameter: tools[0].name'
  upstream errors when clients send {type:'function', function:{name,...}}
  instead of {type:'function', name,...}.

- fix(proxy): add proxy-aware execution context to image generation route.
  Image requests now correctly use proxy settings from the connection's
  ProxyRegistry assignment, matching the pattern used by chat pipeline.

- fix(translator): inject properties:{} into zero-argument MCP tool schemas
  during Anthropic→OpenAI translation. OpenAI strict mode requires explicit
  properties even for empty object schemas.

Closes #1914, Closes #1904, Closes #1898

* chore(release): v3.7.9 — all changes in ONE commit

* fix: allow local ollama provider connections (#1893)

* fix(copilot): emit compatible reasoning text deltas (#1919)

Integrated into release/v3.7.9

* fix(api-manager): show validation errors inline in modals, not behind backdrop (#1920)

Integrated into release/v3.7.9

* docs: update changelog and pr body with merged prs

* fix(providers): route agentrouter through anthropic endpoint headers

Update the AgentRouter provider registry to use the Claude-compatible
messages API and required Anthropic-style authentication headers. This
bypasses unauthorized_client_error responses and exposes the supported
model list through passthrough configuration.

Also update the changelog and release PR notes to document the fix for
#1921

* feat(logs): show compression tokens in request log UI (#1923)

* docs: add PR #1923 to changelog

---------

Co-authored-by: diegosouzapw <diego.souza.pw@gmail.com>
Co-authored-by: backryun <bakryun0718@proton.me>
Co-authored-by: Aculeasis <42580940+Aculeasis@users.noreply.github.com>
Co-authored-by: Raxxoor <manker_lol@hotmail.com>
Co-authored-by: Randi <55005611+rdself@users.noreply.github.com>
Co-authored-by: Paijo <14921983+oyi77@users.noreply.github.com>
Co-authored-by: Tubagus <54710482+0xtbug@users.noreply.github.com>
Co-authored-by: smartenok-ops <smartenok@gmail.com>
Co-authored-by: Gi99lin <74502520+Gi99lin@users.noreply.github.com>
Co-authored-by: ivan-mezentsev <ivan@mezentsev.me>
Co-authored-by: Andrew Munsell <andrew@wizardapps.net>
2026-05-04 01:36:53 -03:00

8.8 KiB

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:

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:

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:

{
  "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. The runtime applies these stages in order:

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.

{
  "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:

{
  "command": "npm test",
  "text": "FAIL tests/example.test.ts\nAssertionError: expected true\nTest Files 1 failed",
  "config": {
    "intensity": "standard"
  }
}

Compression preview payload:

{
  "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:

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:

node --import tsx/esm --test tests/unit/compression/rtk-verify.test.ts

The broader RTK gate is:

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:

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.