К основному содержанию
плагин

token-saver — плагин для Claude Code: что делает и как установить

Сжимает длинный вывод терминала в сессиях Claude Code, убирая лишние логи и индикаторы прогресса. Освобождает контекст под код без сетевых запросов.

Установить в Claude Code · Через маркетплейс плагинов Все способы и платформы ↓
/plugin marketplace add anthropics/claude-plugins-community
/plugin install token-saver@claude-community
Открыть на GitHub

Что делает token-saver

Плагин перехватывает вывод утилит вроде git, pytest, npm, docker, terraform и kubectl перед тем, как он попадёт к модели. Обработка выполняется на вашей машине через регулярные выражения и парсинг, исключая повторные вызовы нейросетей или передачу данных на внешние серверы. Плотные логи вроде git status -s или ошибок tsc плагин не трогает, чтобы не повредить точную диагностику.

Внутри работают 36 специализированных процессоров для разных инструментов сборки, тестов и облачных CLI. В версии 3 появилась экспериментальная функция Delta для pytest и ruff: при повторных запусках плагин показывает только свежие или изменившиеся сбои, а повторяющиеся сворачивает в краткий список. Для работы самого инструмента в окружении нужен Python 3.10+.

Какие задачи решает

  • сэкономить контекстное окно при длинных выводах тестов pytest и jest
  • убрать лишние строки прогресса при установке пакетов через npm или pip
  • сжать простыни логов сборки контейнеров docker и шагов cargo
  • отслеживать только новые ошибки тестов между повторными прогонами

Примеры запросов агенту

  • Запусти pytest и покажи упавшие тесты
  • Покажи git diff последних пяти коммитов
  • Запусти сборку проекта через npm install

Как установить token-saver

Через маркетплейс плагинов

/plugin marketplace add anthropics/claude-plugins-community
/plugin install token-saver@claude-community

По шагам, с командами для каждой платформы: Плагины Claude Code: маркетплейсы, установка и как собрать свой

Вопросы о token-saver

Как установить token-saver в Claude Code?

Сначала добавьте каталог плагинов командой /plugin marketplace add anthropics/claude-plugins-community. Затем установите плагин через /plugin install token-saver@claude-community.

Что делает token-saver?

Он локально урезает повторяющийся вывод терминала при вызове команд вроде git diff, docker или pytest. За счёт этого в контекстном окне сессии остаётся больше места под сам код и инструкции.

Отправляет ли плагин вывод команд на внешние серверы?

Нет, сжатие текста происходит локально на машине с помощью регулярных выражений и парсеров. Никаких дополнительных вызовов моделей или сетевых передач не происходит.

Исходный текст

SKILL.md · Apache-2.0
# Token-Saver

[![CI](https://github.com/ppgranger/token-saver/actions/workflows/ci.yml/badge.svg)](https://github.com/ppgranger/token-saver/actions/workflows/ci.yml)
[![Python](https://img.shields.io/badge/python-3.10%2B-blue)](https://python.org)
[![License](https://img.shields.io/badge/license-Apache%202.0-blue)](LICENSE)
[![Avg Savings](docs/assets/badge-savings.svg)](docs/processors/)

**Keep the signal. Stop rereading the same failures.**

Token-Saver compresses the terminal output your AI coding assistant reads —
`git diff`, `pytest`, `npm install`, `terraform plan`, `kubectl`, `docker` — to
leave more room for the code, instructions, and next decision. Compression runs
locally, without another model call or an output upload.

**New in v3: [Delta](#delta-changes-between-runs).** Run your tests,
edit, run again: see which failures are new, changed, or unchanged. Fresh
diagnostics keep their full details; repeated ones can become a short inventory,
with details available on demand. Delta is an experimental, opt-in feature in
3.0.0 for supported pytest and Ruff commands in Claude Code.

**36 specialized processors** cover git, pytest, jest, cargo, go, docker,
kubernetes, terraform, pulumi, helm, ansible, aws, gcloud, and more. Their rules
reduce progress logs and boilerplate, with failure fixtures and optional quality
contracts checking important diagnostics.

Ordinary compression supports **Claude Code** and **Antigravity CLI**. It runs
automatically after installation. Results depend on the command and output;
already concise or unsupported output may stay unchanged.

**Why developers use Token-Saver:**

- 💸 **Less output to process** — many benchmark scenarios save 60-99% of estimated output tokens; billing impact depends on your usage and provider.
- 🔁 **See what changed** — opt-in Delta compares repeated pytest/Ruff runs and keeps retained details one command away.
- 🪟 **Bigger effective context** — fit more real work into the same context window.
- 🎯 **Tested preservation** — failure fixtures check important diagnostics; add quality contracts for your own workflows.
- 🔌 **Install once, forget it** — works automatically in the background, no prompts to change.
- 🛡️ **Local compression** — pure regex/parsing with no network calls in the compression path.

---

## Table of Contents

- [Before & After](#before--after)
- [Quick Start](#quick-start)
- [Why Token-Saver Exists](#why-token-saver-exists)
- [Who It's For](#who-its-for)
- [What Gets Compressed — Real Examples](#what-gets-compressed--real-examples)
- [How It Compares](#how-it-compares)
- [How It Works](#how-it-works)
- [Precision Guarantees](#precision-guarantees)
- [Installation](#installation)
- [CLI Reference](#cli-reference)
- [Delta: Changes Between Runs](#delta-changes-between-runs)
- [Compression Quality Gates](#compression-quality-gates)
- [Processors](#processors)
- [Configuration](#configuration)
- [Tuning Recipes](#tuning-recipes)
- [Custom Processors](#custom-processors)
- [Savings Tracking](#savings-tracking)
- [Security & Privacy](#security--privacy)
- [Performance](#performance)
- [FAQ](#faq)
- [Troubleshooting](#troubleshooting)
- [Known Limitations](#known-limitations)
- [Project Structure](#project-structure)
- [Tests](#tests)
- [Contributing](#contributing)

---

## Before & After

| Command | Raw Output | Compressed | Savings |
|---------|-----------|------------|---------|
| `git diff` (5 files, 20 context lines each) | 2,270 tokens | 546 tokens | **76%** |
| `git diff --stat` (25 files) | 526 tokens | 21 tokens | **96%** |
| `git log --oneline` (50 entries) | 568 tokens | 117 tokens | **79%** |
| `pytest` (500 tests, 2 failures) | 6,744 tokens | 307 tokens | **95%** |
| `pytest` (200 passed, 30 warnings) | 3,543 tokens | 80 tokens | **98%** |
| `jest` (50 suites, all passing) | 570 tokens | 32 tokens | **94%** |
| `npm install` (220 packages) | 3,843 tokens | 4 tokens | **99.9%** |
| `pip install -r requirements.txt` (30 packages) | 1,797 tokens | 88 tokens | **95%** |
| `cargo build` (120 crates) | 934 tokens | 21 tokens | **98%** |
| `docker build` (20 steps) | 1,682 tokens | 207 tokens | **88%** |
| `curl` download (100 progress lines) | 2,122 tokens | 0 tokens | **100%** |
| `ruff check` (110 violations, 4 rules) | 1,475 tokens | 186 tokens | **87%** |
| `eslint` (55 violations, 2 rules) | 1,292 tokens | 144 tokens | **89%** |
| `tree` (350+ lines) | 1,840 tokens | 136 tokens | **93%** |
| `find . -name '*.py'` (205 results) | 1,294 tokens | 217 tokens | **75%** |

These are locked to [`tests/compression_baselines.json`](tests/compression_baselines.json) and gated by CI ([`tests/test_compression_ratchet.py`](tests/test_compression_ratchet.py)) — if a change makes any of them compress worse, the build fails. Run `python3 scripts/audit_compression.py` to see the full scenario set, or `token-saver benchmark '<command>'` to measure savings on your own workloads.

Not every command compresses, and that's deliberate. `cat large_file.py`, `git status -s`, and `tsc` with 7 type errors all sit in the same baseline file at **0%** — they're already dense, or the model needs them verbatim. Token-Saver returns the original bytes rather than shaving a few tokens at the cost of correctness.

## Quick Start

```
/plugin marketplace add ppgranger/token-saver
/plugin install token-saver
```

(Also available on Anthropic's official community marketplace — see [Installation](#installation) for both options.)

That's the whole setup. Ask Claude to run anything — *"run the tests"*, *"show me the diff"*, *"what changed in the last 10 commits"* — and the output is compressed before it reaches the model. Then:

```bash
token-saver stats
```

Want to see it work before installing it?

```bash
git clone https://github.com/ppgranger/token-saver.git && cd token-saver
python3 bin/token-saver benchmark 'git log --oneline -50'
python3 bin/token-saver benchmark 'git diff' --show-removed
python3 bin/token-saver explain 'docker compose logs | grep error'
```

## Why Token-Saver Exists

Verbose tool output competes with your code and instructions for context. A
`pytest` run with 200 passing tests or an install with hundreds of progress
lines often repeats information that can be represented much more compactly.
After an edit, another run can repeat the same failures too.

Token-Saver reduces that repetition using local parsing. Delta extends this to
consecutive runs, while keeping a current diagnostic inventory and retrievable
details. Whether this improves task completion, response time, or billing needs
measurement in the agent workflow that uses it.

There are three common ways to attack this:

1. **Summarize with another LLM.** Accurate-ish, but it costs a second inference per command, adds seconds of latency, and is non-deterministic — the same `pytest` run can be summarized two different ways.
2. **Truncate blindly.** Free and instant, but it's exactly how you lose the one stack-trace line that mattered.
3. **Parse the format you already know.** `git diff` has a grammar. `pytest` has a summary line. `npm install` has a progress phase and a result phase. Format-aware parsing can remove repetitive output while retaining tested diagnostics, deterministically and without another model call.

Token-Saver is the third approach, applied to 36 command families. It sits
between the CLI and your AI assistant, applying format-specific rules whose
preservation behavior you can test against your own captured output.

## Who It's For

- **Developers paying per token** on Claude Code, whether via API credits or a plan with usage limits. Tool output is often the largest single category of input tokens in an agentic session.
- **Teams running agents in CI**, where a long pipeline command (`terraform plan`, `pytest`, `gradle build`) is piped straight into a model.
- **Anyone hitting context limits** mid-task — the "conversation is too long" wall usually arrives right after a big `npm install` or a wide `git diff`.
- **Monorepo and infrastructure work**, where a single `terraform plan` or `kubectl describe` is thousands of tokens of mostly-unchanged resource attributes.
- **Privacy-sensitive environments** that can't route output through a second model or a hosted service. Token-Saver is pure local Python with no network calls in the compression path.

It's probably **not** for you if your agent mostly reads and writes source files and rarely runs shell commands — file reads go through Claude Code's own Read tool, which Token-Saver doesn't intercept.

## What Gets Compressed — Real Examples

Everything below is actual Token-Saver output, produced by the same scenario corpus the CI ratchet uses.

### `pytest` — 533 lines → 26 lines (95%)

Passing tests collapse to a count. Every failure keeps its full traceback, assertion diff, file, and line number.

```
[500 tests passed]
=================================== FAILURES ===================================
__________________________ test_compression_ratio ______________________________

    def test_compression_ratio():
        engine = CompressionEngine()
        result = engine.compress('git status', large_output)
>       assert len(result[0]) < len(large_output) * 0.5
E       AssertionError: assert 1500 < 1000
...
FAILED tests/test_engine.py::test_compression_ratio - AssertionError: assert 1500 < 1000
FAILED tests/test_processors.py::test_diff_context_trim - AssertionError: assert 42 < 10
========================= 2 failed, 510 passed ==
```

### `ruff check` — 111 lines → 18 lines (87%)

Violations are grouped by rule with a count and a couple of concrete examples, so the model learns the *pattern* to fix instead of reading 45 near-identical lines.

```
110 issues across 4 rules:
  E501: 45 occurrences in 45 files
    src/module/e501_00.py:10:5: E501 Line too long
    src/module/e501_01.py:11:6: E501 Line too long
    ... (43 more)
  F401: 30 occurrences in 30 files
    src/module/f401_00.py:10:5: F401 imported but unused
    ... (28 more)
Found 110 errors.
```

### `npm install` — 526 lines → 1 line (99.9%)

```
Build succeeded.
```

Nothing actionable was lost: the raw output was 220 `added <pkg>@<ver>` lines and a progress bar. Had the install failed, the error and the failing package would survive verbatim — see [Precision Guarantees](#precision-guarantees).

### `cargo build` — 122 lines → 2 lines (98%)

```
[121 crates compiled]
    Finished dev [unoptimized + debuginfo] target(s) in 45.23s
```

### `git diff` — context trimmed, changes untouched (76%)

Unified diffs keep every `+`/`-` line and every `@@` hunk header, with surrounding unchanged context trimmed to `max_diff_context_lines` (default 3):

```
diff --git a/src/module_0.py b/src/module_0.py
@@ -10,30 +10,32 @@ def some_function_0():
     # This is context line 9 that hasn't changed and takes up tokens
-    old_value = compute_something(0)
-    return old_value
+    new_value = compute_something_better(0)
+    cached = cache.get(new_value)
+    if cached:
+        return cached
+    return new_value
     # This is trailing context line 0 that is unchanged and wastes tokens
```

### `tree` — 312 lines → 28 lines (93%)

The directory shape is preserved down to the truncation point, with an explicit marker and the original totals, so the model knows what it *isn't* seeing:

```
.
├── src/
│   ├── engine.py
│   ├── config.py
│   ├── processors/
│   │   ├── git.py
...
... (287 lines truncated)
20 directories, 310 files
```

### `env` / `printenv` — secrets redacted before the model sees them

Variables whose names look sensitive (`SECRET`, `PASSWORD`, `CREDENTIAL`, `API_KEY`, `GITHUB_TOKEN`, and bare `KEY`/`TOKEN`/`AUTH`/`PWD` at letter boundaries — so `PATH`, `AUTHOR`, and `MONKEY` are left alone) have their values replaced. Token-Saver returns this redacted output **even when it isn't smaller** than the input: a redacted result is never traded back for the raw one to satisfy a compression threshold.

## How It Compares

| | Token-Saver | LLM summarizer | Blind truncation | Response caching |
|---|---|---|---|---|
| Extra inference cost | None | One call per command | None | None |
| Additional work | Python startup + parsing | Another model call | Truncation | Cache lookup |
| Deterministic | Yes | No | Yes | Yes |
| Diagnostic preservation | Tested fixtures + configurable quality contracts | Depends on prompt/model | No semantic checks | Depends on cached content |
| Works offline | Yes | Needs a model | Yes | Usually not |
| Understands `git diff` | Yes | Sort of | No | N/A |

For a sourced comparison with RTK and Context Mode, including integration caveats, see the [full comparison](docs/comparison.md).

## How It Works

### Architecture

**Built around explicit SOLID boundaries.** Processors parse output, a shared
policy decides command eligibility, adapters execute commands, and dedicated
modules own storage and presentation. Delta comparison and statistics formatting
are pure functions; engine dependencies and telemetry writers can be supplied
independently. The [architecture guide](docs/architecture.md) documents the
contracts, compatibility guarantees, tests, and remaining couplings.

```
CLI command  -->  Specialized processor  -->  Compressed output
                        |
                  36 processors
                  (git, test, cargo, go, build,
                   lint, package_list, python_install,
                   maven_gradle, bun, network, docker,
                   kubectl, terraform, pulumi, cdktf,
                   nix, mise, env, search, system_info,
                   gh, db_query, cloud_cli, ansible,
                   helm, syslog, ssh, jq_yq, just, act,
                   structured_log, file_listing,
                   file_content, generic)
```

The engine (`CompressionEngine`) maintains a priority-ordered chain of processors.
The first processor that can handle the command (`can_handle()`) produces the
compressed output. `GenericProcessor` serves as a fallback and always matches last.

When a specialized processor doesn't achieve the minimum compression ratio,
the engine tries the generic processor as a fallback before returning uncompressed output.

After the specialized processor runs, a lightweight cleanup pass (`clean()`)
strips residual ANSI codes and collapses consecutive blank lines.

### The Compression Pipeline, Step by Step

1. **Eligibility.** The hook first decides whether the command is safe to wrap at all — see [Security & Privacy](#security--privacy). Redirections, `sudo`, editors, unquoted newlines, background `&`, and shell-construct fragments are all left alone.
2. **Size gates.** Output shorter than `min_input_length` is returned untouched. Output longer than `max_output_bytes` (default 10 MB) is hard-capped with an explicit note before compression, so a pathological command can't be held in memory in full.
3. **Routing.** Processors are tried in priority order; the first `can_handle()` match wins.
4. **Failure routing.** If the command exited non-zero and the matched processor hasn't opted into `handles_failure`, the engine deliberately routes to the generic processor instead. A specialized processor's heuristics are tuned for the *success* shape of a tool's output; failure text often isn't recognized, and an unrecognized line is exactly what a loop drops silently.
5. **Chaining.** A processor may declare `chain_to` to hand its result to a second one, bounded by `max_chain_depth`.
6. **Cleanup.** ANSI escape stripping and blank-line collapsing.
7. **Critical-line recovery.** The engine diffs the compressed output against the original for error-shaped lines that vanished, and re-appends up to `recover_critical_lines` of them under an explicit `[token-saver] N error line(s) recovered` marker. This is a backstop covering all 36 processors — and every future one — rather than an audit that has to be repeated per processor.
8. **Ratio gate.** If the result isn't meaningfully smaller, the original is returned. **Exception:** if the processor redacted secrets, the redacted output always wins, regardless of size.
9. **Tracking.** Sizes — never content — go to a local SQLite database.

### Platform Integration

The two platforms use different mechanisms:

**Claude Code** (PreToolUse hook):

```
1. Claude wants to run `git status`
2. PreToolUse hook intercepts the command
3. Rewrites to: python3 wrap.py 'git status'
4. wrap.py executes the original command
5. Compresses the output
6. Claude receives the compressed version
```

Claude Code's PreToolUse hook cannot modify output after execution.
The only way to reduce tokens is to rewrite the command to go through a wrapper
that executes, compresses, and returns the result.

Because that rewrite is a source-to-source shell transformation, the rewritten
command is syntax-checked (`sh -n -c`) before it runs. If the rewrite wouldn't
parse, the **original** command runs uncompressed — a missed saving, never a
broken command.

**Antigravity CLI** (AfterTool hook):

```
1. Antigravity executes the command
2. AfterTool hook receives the raw output
3. Compresses the output
4. Replaces it via {"decision": "deny", "reason": "<compressed output>"}
```

Antigravity CLI allows direct output replacement through the deny/reason mechanism.

### Chained Commands

`git add -A && git commit -m wip && git push` is a single Bash tool call, but three
commands with three different output shapes. Token-Saver splits the chain, validates
each segment independently, injects unique boundary markers, and compresses each
segment with its own processor — so the `git push` output is handled by the git
processor even though it shares a shell with two other commands. If *any* segment is
ineligible, the whole chain runs untouched.

## Precision Guarantees

Compression is aggressive on noise, conservative on signal:

- Tiny outputs are never touched, and a result that doesn't actually get smaller is discarded in favor of the original (both thresholds are configurable — see [Configuration](#configuration))
- Failure fixtures verify specific errors, tracebacks and changed lines; grouping and bounded recovery can omit other details
- Source code files (`cat *.py`, `cat *.ts`, ...) pass through **unchanged** — the model needs exact content
- Secrets in `.env.production`, `.env.local`, and other `.env.*` variants are automatically **redacted** before reaching the model (`.env`, `.env.example`, and `.env.template` pass through unchanged, by design — see the note below)
- Processors remove or group progress bars, passing tests, installation logs, ANSI codes and other repetitive content according to their documented rules
- Generic truncation includes an omission marker; format-specific processors can also summarize or omit lines
- 1300+ tests including precision-specific tests that verify every critical piece of data survives compression, and a compression-ratchet suite that fails CI if a real-world scenario's compression ratio regresses

Two of these are enforced structurally rather than by convention:

- **`TestFailureHandling`** runs a realistic *failing*-command fixture through **every** processor, at **every** exit code (`0`, `1`, and unknown), and asserts the failure reason is still present. A processor that claims `handles_failure = True` has to earn it; one that doesn't gets routed around.
- **Critical-line recovery** (step 7 above) restores recognized error lines within a configurable cap, except after redaction where restoring raw lines could expose secrets.

These are protections on tested output formats, not a universal lossless guarantee.
Use [quality gates](#compression-quality-gates) to assert the exact diagnostics
your workflow requires.

> **Note on `.env`:** `.env`, `.env.example`, and `.env.template` are intentionally left untouched (not redacted, not compressed) — these are the files you're most likely actively editing, where exact values matter. Other `.env.*` variants (`.env.production`, `.env.local`, ...), which you're more likely to be reading than editing, get their values redacted. If you `cat .env` directly, treat that output as sensitive the same way you would without Token-Saver installed.

## Installation

### Prerequisites

- Python 3.10+
- Claude Code and/or Antigravity CLI

No third-party Python packages are required — Token-Saver uses only the standard library.

### Method 1: Claude Code Plugin (recommended)

Two marketplaces carry Token-Saver — pick one.

**Anthropic's official community marketplace** (`claude-community`), no setup beyond adding it once:
```
/plugin marketplace add anthropics/claude-plugins-community
/plugin install token-saver@claude-community --scope project
```
This mirror is a snapshot pinned to a specific commit, refreshed periodically rather than on every push — if you want the exact latest commit on `main`, use the self-hosted marketplace below instead.

**Self-hosted marketplace** (this repo, always current):
```
/plugin marketplace add ppgranger/token-saver
/plugin install token-saver
```

Or test directly from a local clone:
```bash
git clone https://github.com/ppgranger/token-saver.git
claude --plugin-dir ./token-saver
```

### Method 2: Manual installation

```bash
git clone https://github.com/ppgranger/token-saver.git
cd token-saver
python3 install.py --target claude    # Claude Code only
python3 install.py --target antigravity    # Antigravity CLI only
python3 install.py --target both      # Both platforms
```

The manual installer registers token-saver as a native Claude Code plugin
(equivalent to `/plugin install`). It appears in `/plugin` list and hooks,
skills, and commands are managed natively by Claude Code.

The repo/zip can be deleted after installation. Token-Saver copies everything
it needs to `~/.token-saver/` and the platform plugin directories.

### Development Mode

```bash
python3 install.py --target claude --link   # Symlinks instead of copies
```

Changes in the source directory are immediately applied.
Do **not** delete the repo in this mode.

### Uninstall

```bash
python3 install.py --uninstall              # Remove from all platforms
python3 install.py --uninstall --keep-data  # Keep stats DB
```

### Updating

**Plugin install**: Claude Code handles updates automatically when you refresh the marketplace.

**Manual install**: Run `token-saver update` from anywhere, or:
```bash
cd token-saver && git pull && python3 install.py --target claude
```

**GitHub releases**: Both methods check for new releases via the GitHub API. The `token-saver update` CLI command and the SessionStart hook notification work regardless of install method. The remote lookup is cached for 24h and fails open — a network outage or an API rate limit never blocks a session.

### Upgrading from v1.x to v2.0

If you previously installed token-saver v1.x:
```bash
cd token-saver
git pull
python3 install.py --target claude
```
The installer automatically:
- Removes legacy hooks from `~/.claude/settings.json` (no longer needed)
- Removes the old `~/.claude/plugins/token-saver/` directory
- Installs to the plugin cache as a native Claude Code plugin
- Registers in `enabledPlugins` and `installed_plugins.json`

You can also run `token-saver update` from anywhere to auto-upgrade.

### Avoid dual installation

Do NOT install token-saver via BOTH `/plugin install` AND `python3 install.py`
simultaneously — this could register the plugin twice. Use one method or the
other. The same applies across marketplaces: install from either
`claude-community` or the self-hosted `ppgranger/token-saver` marketplace,
not both.

To switch from manual to marketplace:
```bash
python3 install.py --uninstall --target claude
/plugin marketplace add ppgranger/token-saver
/plugin install token-saver
```

### What the Installer Does

1. Copies (or symlinks) files to:
   - Core: `~/.token-saver/` (CLI, updater, shared source)
   - Claude Code: `~/.claude/plugins/cache/token-saver-marketplace/token-saver/`
   - Antigravity CLI: `~/.gemini/antigravity-cli/plugins/token-saver/`
2. Registers as a native Claude Code plugin in `installed_plugins.json` and `enabledPlugins`
3. Installs `token-saver` CLI to `~/.local/bin/`
4. Stamps the current version into plugin manifests
5. Cleans up any legacy `token-saving` or v1.x installation

## CLI Reference

After installation the `token-saver` command is available. If `~/.local/bin` is not on your PATH, the installer prints instructions.

| Command | What it does |
|---|---|
| `token-saver version` | Print the installed version |
| `token-saver stats` | Show session + lifetime savings |
| `token-saver stats --json` | Same, machine-readable |
| `token-saver update` | Check GitHub for a new release and apply it |
| `token-saver benchmark '<cmd>'` | Run a command and report its compression |
| `token-saver benchmark '<cmd>' --dry-run` | Show which processor would match, without executing |
| `token-saver benchmark '<cmd>' --show-removed` | Line/byte breakdown of what compression removed |
| `token-saver benchmark '<cmd>' --stdin` | Compress output piped on stdin instead of executing |
| `token-saver benchmark '<cmd>' --format json` | Machine-readable benchmark |
| `token-saver explain '<cmd>'` | Explain how a command is routed — or why it's excluded |
| `token-saver explain '<cmd>' --format json` | Same, machine-readable |
| `token-saver compress '<cmd>'` | Read UTF-8 stdin and emit compressed text; never execute the command label |
| `token-saver compress '<cmd>' --exit-code 1 --max-tokens 1500` | Apply failure-aware routing and check an estimated output budget |
| `token-saver compress '<cmd>' --format json` | Compressed output plus measurements and budget verdict |
| `token-saver replay quality.json` | Check captured fixtures against preservation and budget contracts |
| `token-saver replay quality.json --format json` | Content-free quality report for CI |
| `token-saver delta show RUN` | Read a retained, sanitized Delta snapshot without rerunning its command |
| `token-saver delta show RUN --diagnostic EXACT_ID` | Read full details for one diagnostic in that snapshot |
| `token-saver delta clear` | Delete all retained Delta snapshots and reset comparisons |

`explain` is the fastest way to answer "why didn't that get compressed?":

```console
$ token-saver explain 'git status'
Token-Saver Explain
========================================
Command:      git status
Compressible: yes
Reason:       matched a compressible processor pattern
Processor:    git

$ token-saver explain 'cat x.py > out.txt'
Command:      cat x.py > out.txt
Compressible: no
Reason:       contains output redirection (>, >>, 2>, &>)
Excluded by:  output redirection
Processor:    file_content
```

And `--stdin` lets you test compression against output you already have, with no re-execution:

```bash
pytest > /tmp/out.txt 2>&1
token-saver benchmark 'pytest' --stdin --show-removed < /tmp/out.txt
```

## Delta: Changes Between Runs

**New in 3.0.0: spend context on the next change.** Delta is experimental and
disabled by default.
Delta compares consecutive `pytest` and `ruff check` results in Claude Code so
the agent can see what changed after an edit. Commands still execute normally.
New or changed diagnostics retain their full details; unchanged diagnostics keep
their identity and summary, with a command to retrieve the details locally.

| In your edit–test loop | What Delta reports |
|---|---|
| First supported run | A baseline with full failure details. |
| Same failures again | `UNCHANGED` with names and summaries when that saves output. |
| An assertion or traceback changes | `CHANGED` with its full current details. |
| A new regression appears | `NEW` with its full current details. |
| A previous failure disappears | `PASSED` only with explicit passing evidence; otherwise `NOT OBSERVED`. |
| You need the original diagnostic | `token-saver delta show RUN --diagnostic EXACT_ID`, without rerunning tests. |

One repeated run from the [real-command fixture benchmark](docs/delta.md#run-the-real-command-benchmark)
returns this instead of 4,079 characters of ordinary compressed output
(`RUN` replaces the generated snapshot identifier):

```text
[token-saver delta] pytest | exit 1
3 failed, 21 passed in 0.02s
UNCHANGED test_fixture.py::test_payload — AssertionError: payload diagnostic
UNCHANGED test_fixture.py::test_status — AssertionError: status diagnostic
UNCHANGED test_fixture.py::test_cache — AssertionError: cache diagnostic

Details: token-saver delta show RUN [--diagnostic ID]
```

The complete five-run fixture sequence saves **32.5% of output characters for
pytest and 8.3% for Ruff**, compared with ordinary compression, **including one
targeted detail retrieval**. These are measured fixture results, not universal
savings or billing figures. A complete snapshot read is more expensive: it
erases the gain in the Ruff scenario. The guide includes every result and the
reproduction command.

Enable it explicitly in your global configuration, or before launching Claude:

```bash
export TOKEN_SAVER_DELTA_ENABLED=true
```

The comparison stays within the same session, working directory, and exact
command. Each Delta response includes the current exit status, totals, and diagnostic
inventory. A missing failure is **`NOT OBSERVED`, not confirmed fixed**; `PASSED`
requires an explicit passing test result in the current output. Use `pytest -v`
to expose those per-test results.

Delta is disabled by default. Enabling it retains sanitized output snapshots
locally for 24 hours and at most 100 runs by default. It currently applies only
to supported single commands through the Claude wrapper, with a host session
identifier. Unsupported or ambiguous output uses ordinary compression.

The first run and new or changed failures can produce **more output than v2**
when preserving full details requires it. For unchanged repeats, Token-Saver uses
ordinary sanitized compression whenever Delta would be as large...

© ppgranger · Apache-2.0 · ppgranger/token-saver

Похожие плагины

Все плагины по теме «Настройка агента: память, контекст, субагенты» →
ponytail DietrichGebert Плагин настраивает агента на короткие решения без лишних абстракций. Сгодится, когда нужно использовать возможности уже имеющегося кода и не усложнять задачу. ★ 177 259звёзд репо impeccable pbakaus Даёт агенту словарь дизайнера: 24 команды вроде polish, audit и bolder, чтобы правки интерфейса не сводились к «сделай красиво». ★ 89 321звёзд репо last-30-days-skill mvanhorn Собирает свежие посты, комментарии и транскрипты по любой теме за последний месяц и укладывает их в один отчёт. ★ 65 596звёзд репо claude-hud jarrodwatts Показывает под строкой ввода, сколько контекста занято, какие инструменты работают и как идут задачи. Пригодится, когда сессия длинная и надо видеть расход. ★ 28 914звёзд репо understand-anything Egonex-AI Плагин сканирует проект и строит интерактивный граф файлов, классов и зависимостей с веб-дашбордом. Пригодится при знакомстве с чужим или крупным кодом. ★ 88 429звёзд репо mem0 mem0ai Подключает долговременную память к Claude Code, сохраняя контекст проектов и привычки между сессиями. ★ 67 869звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой