agentnativedev.medium.com 8 min read Original Source

Agent-agnostic token optimization: Save up to 90% reduction with compression, routing and filtering

They print progress bars, successful tests, repeated file paths, package metadata, ANSI formatting, verbose stack traces, and pages of output that are useful for debugging but rarely useful for an agent’s next decision.

When a coding agent runs those same tools, much of that output gets pushed directly into the model’s context.

Run enough commands and the waste compounds.

  • Test suite prints 2,000 lines when three failures matter.
  • git diff repeats structural metadata around every change.
  • Linter reports the same rule across dozens of files.
  • Package manager streams progress the model will never use.

The agent still has to read all of it.

This makes command output one of the most practical places to optimize an agentic system.

Instead of letting raw terminal output flow directly into the conversation, we can:

  • Intercept it first
  • Parse it according to the command that produced it.
  • Remove noise
  • Group repeated information.
  • Preserve failures and relevant state
  • Then return a much smaller representation to the agent

As support expands across Git, test runners, linters, compilers, containers, cloud CLIs, and file operations, the optimization starts covering a meaningful portion of an agent’s working loop.

The idea goes beyond saving tokens.

Tool output can become a data plane between software and the LLM, with its own normalization, filtering, compression, measurement, and routing layer.

We expect this boundary to become a standard part of serious agent infrastructure.

Train for the skills top AI roles actually demand, then find the role that fits you across thousands of recent openings. Join the Agent Foundry.

The Expensive Part Is Often Between the Tool and the Model

Picture a test run with 900 passing tests and two failures.

To decide what to do next, the agent usually needs the names of the failing tests, the relevant assertion output, a trimmed traceback, and the exit status.

Hundreds of success lines add almost nothing to that decision.

We can ship command-specific filters for exactly these cases:

  • git status: compact state grouped by file status
  • git diff: reduced diff context with the useful headers kept
  • cargo test, npm test, pytest, go test: failures plus a compact summary
  • grep, rg, ast-grep: matches grouped together, with long lines truncated
  • ruff, sqlfluff, and other linters: violations grouped by rule and file
  • ls, tree, find: structural summaries in place of repetitive listings
  • read and cat workflows: signatures and structure when aggressive filtering is requested

The project we introduce today is RTK, which leverages four recurring techniques: filtering, grouping, truncation, and deduplication.

It also provides strategies like state-machine parsing for pytest, NDJSON aggregation for Go tests, JSON-first parsing for linters, tree compression for file listings, and failure-focused test output.

The design principle here carries over to any agent: the reducer should understand the tool whose output it compresses. One generic summarizer bolted on after the fact will always know less.

A deterministic parser knows that a failing test name, a file path, a line number, and an exit code carry more operational value than a progress bar.

It also saves you from paying another model to summarize output that a parser can reduce cheaply and reproducibly.

RTK Sits in the Shell Execution Path

The basic flow is simple.

  • Without RTK, the agent issues a shell command and gets raw stdout and stderr back.
  • With RTK initialized for a supported coding agent, a pre-tool hook rewrites eligible shell commands before they run.

The agent can still issue:

cargo test
cargo test

The hook rewrites the execution to:

rtk cargo test
rtk cargo test

RTK runs the underlying tool, parses its output, preserves the command’s result, and sends the compact version back into the conversation.

Nobody has to teach the agent to type rtk on every call.

RTK currently supports most popular harnesses.

One boundary is worth knowing early.

The automatic hook fires on shell tool calls, and agent-native Read, Grep, and Glob tools do not pass through a Bash hook.

To cover them, you can use shell equivalents such as cat, rg, and find, call rtk read, rtk grep, and rtk find directly, or opt into the newer post-tool pipeline covered later in this article.

Quick Start

Install RTK through one of the paths the repository supports:

# macOS / Linux
brew install rtk-ai/tap/rtk

# Windows
winget install rtk-ai.rtk

# macOS / Linux installer
curl -fsSL https://raw.githubusercontent.com/rtk-ai/rtk/master/install.sh | sh
# macOS / Linux
brew install rtk-ai/tap/rtk

# Windows
winget install rtk-ai.rtk

# macOS / Linux installer
curl -fsSL https://raw.githubusercontent.com/rtk-ai/rtk/master/install.sh | sh

There is an unrelated Rust project ships a binary with the same name, so verify the install:

rtk --version
rtk gain
rtk --version
rtk gain

rtk gain should open the RTK savings view.

Next, initialize the integration for your agent:

rtk init -g                     # Claude Code
rtk init -g --gemini            # Gemini CLI
rtk init -g --codex             # Codex
rtk init -g --agent cursor      # Cursor
rtk init -g --agent windsurf    # Windsurf
rtk init --agent cline          # Cline / Roo Code
rtk init -g                     # Claude Code
rtk init -g --gemini            # Gemini CLI
rtk init -g --codex             # Codex
rtk init -g --agent cursor      # Cursor
rtk init -g --agent windsurf    # Windsurf
rtk init --agent cline          # Cline / Roo Code

For a safer rollout, preview the file and settings changes first:

rtk init --global --dry-run
rtk init --global --dry-run -v
rtk init --global --dry-run
rtk init --global --dry-run -v

Restart the coding agent after initialization and use it as usual.

While testing filters, you can also call RTK explicitly:

rtk git status
rtk git diff
rtk cargo test
rtk pytest
rtk grep -R "payment_failed" src/
rtk read src/payments/service.rs --max-lines 120
rtk git status
rtk git diff
rtk cargo test
rtk pytest
rtk grep -R "payment_failed" src/
rtk read src/payments/service.rs --max-lines 120

When you want untouched output for a single command:

<button data-code="rtk bypass ” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-1/2 -translate-y-1/2 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

rtk bypass <command>
rtk bypass <command>

Keep that escape hatch in mind when you evaluate any output-shaping layer.

Turning compression off should be easy at the smallest useful scope.

The Smallest Piece of Code Explains the Engineering Philosophy

Token optimization tools can fail in an embarrassing way: the formatted or summarized output ends up longer than what the command originally printed.

RTK guards against that case in src/core/guard.rs:

<button data-code="pub fn never_worse(raw: &'a str, filtered: &'a str) -> &'a str {
if estimate_tokens(filtered) > estimate_tokens(raw) {
raw
} else {
filtered
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

pub fn never_worse<'a>(raw: &'a str, filtered: &'a str) -> &'a str {
    if estimate_tokens(filtered) > estimate_tokens(raw) {
        raw
    } else {
        filtered
    }
}
pub fn never_worse<'a>(raw: &'a str, filtered: &'a str) -> &'a str {
    if estimate_tokens(filtered) > estimate_tokens(raw) {
        raw
    } else {
        filtered
    }
}

This is a strong production invariant.

A filter can be as sophisticated as it likes internally, yet its output still has to pass a simple budget check.

Tiny command outputs stay tiny, and any compression method that accidentally expands its input loses to the raw result.

The token estimator is deliberately simple, the shared text crate assumes roughly four bytes per token:

usize {
(len as f64 / 4.0).ceil() as usize
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-1/2 -translate-y-1/2 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

pub fn estimate_tokens_from_len(len: usize) -> usize {
    (len as f64 / 4.0).ceil() as usize
}
pub fn estimate_tokens_from_len(len: usize) -> usize {
    (len as f64 / 4.0).ceil() as usize
}

RTK applies the same approximation to both the raw and the filtered output.

The absolute token count is an estimate, while the reduction ratio remains a fair comparison between the two byte streams.

You should keep this in mind when you read cost claims.

90% reduction in one command’s Bash output does not mean a 90% cheaper agent session. Provider billing also covers system instructions, user prompts, conversation history, cached context, and model output.

Measure the Integration Before You Trust It

A transparent hook is convenient, but invisible infrastructure needs observability.

RTK ships three commands, and each one answers a different question:

rtk gain
rtk discover
rtk session
rtk gain
rtk discover
rtk session

rtk gain reports what RTK processed and how much command output it removed.

You can inspect history and daily breakdowns, or export the data:

rtk gain --history
rtk gain --daily
rtk gain --graph
rtk gain --all --format json
rtk gain --history
rtk gain --daily
rtk gain --graph
rtk gain --all --format json

rtk discover finds commands that ran without RTK and estimates the compression you missed:

rtk discover
rtk discover --all --since 7
rtk discover
rtk discover --all --since 7

rtk session reports adoption across recent sessions, which helps you catch a broken hook, a disabled environment variable, or a subagent path that skips the integration.

The analytics layer can also attribute savings by method, rule, layer, and pipeline.

RTK tracks recall efficiency too.

When an agent repeatedly asks for information a filter removed, those requests are counted and become a concrete signal for tuning that filter.

For agent infrastructure, this feedback loop is worth more than any static compression percentage.

You want to know how much you removed, where you removed it, and how often the agent needed the missing detail later.

RTK 1.0 Turns the Filter Into a Pipeline

RTK started as a command-output compressor.

Version 1.0 adds a broader engine for composing behavior across the hook and proxy layers.

The simplest opt-in file in the repository is only a few lines:

schema_version = 1

[pipeline]
extends = ["rtk:posthook", "rtk:proxy"]
schema_version = 1

[pipeline]
extends = ["rtk:posthook", "rtk:proxy"]

Save a user pipeline at:

~/.config/rtk/pipeline.toml
~/.config/rtk/pipeline.toml

rtk:posthook adds output processing after tool calls wherever the harness exposes the required hook. rtk:proxy enables the request-side proxy pipeline.

RTK also supports named overrides.

The repository includes this example, which changes one inherited threshold and leaves the rest of the rule intact:

schema_version = 1

[pipeline]
extends = ["rtk:posthook", "rtk:delegate-reads"]

[override.shunt-large-read]
when.file_lines_gt = 500
schema_version = 1

[pipeline]
extends = ["rtk:posthook", "rtk:delegate-reads"]

[override.shunt-large-read]
when.file_lines_gt = 500

If you are building agent platforms, this is the most relevant part of the release.

Context policy no longer has to be hard-coded inside every tool adapter.

You can define a policy layer around tool execution, with rules that decide when to compress, when to keep output verbatim, when to delegate a read, and which processing chain applies at each point in the agent lifecycle.

The project ships built-in reference pipelines including rtk:default, rtk:posthook, rtk:proxy, rtk:delegate-reads, rtk:verbatim-diffs, and rtk:terse.

You can inspect and validate the resolved policy before trusting it:

rtk pipeline show rtk:default
rtk pipeline show rtk:posthook
rtk pipeline validate
rtk pipeline show rtk:default
rtk pipeline show rtk:posthook
rtk pipeline validate

The Optional Proxy Moves One Layer Higher

RTK’s command filters sit between CLI tools and the agent.

The optional rtk-proxy daemon sits between the agent and its model provider.

For Claude, the repo currently documents a launcher path:

rtk claude
rtk llm-proxy status
rtk gain
rtk claude
rtk llm-proxy status
rtk gain

The proxy can normalize request content, run cache-stable compression rules, align cache breakpoints when configured, and record usage into the same analytics surface.

This layer needs stricter invariants.

Provider caching depends on stable prefixes, so a request transform cannot rewrite older conversation blocks differently from one turn to the next.

RTK’s proxy explicitly limits proxy rules to cache-stable methods and conditions, which is worth copying into any agent middleware.

Once transformed context takes part in caching, deterministic behavior becomes part of your cost model.

What I Would Copy Into an Agent Platform

RTK is useful as a tool, and several of its implementation choices generalize well beyond coding agents:

  1. Put context shaping at the tool boundary. Tool output is structured enough to compress deterministically before it pollutes conversation history.
  2. Preserve execution semantics. Exit codes, error lines, paths, identifiers, and line numbers should survive even aggressive formatting.
  3. Use command-aware reducers. A test runner, a linter, a Git command, a search command, and a file reader each carry different signal.
  4. Fail open. RTK’s architecture calls for a raw-output fallback when filtering fails, and the never_worse guard blocks simple expansion regressions.
  5. Keep an escape hatch. rtk bypass gives a developer raw behavior back for a single command.
  6. Measure recalls. Compression without recovery telemetry can quietly degrade agent performance.
  7. Separate policy from integrations. A pipeline lets one context policy span several harnesses, so it never gets buried inside a single agent-specific hook.

The broader agent ecosystem is pouring engineering effort into better reasoning models, larger context windows, and smarter retrieval.

Tool-output hygiene deserves the same attention.

A bigger context window makes waste easier to tolerate, and you still pay for every wasted token.

Bonus Articles