Repository: rtk-ai/rtk
Stars: 28436
CLAUDE.md
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
Project Overview
rtk (Rust Token Killer) is a high-performance CLI proxy that minimizes LLM token consumption by filtering and compressing command outputs. It achieves 60-90% token savings on common development operations through smart filtering, grouping, truncation, and deduplication.
This is a fork with critical fixes for git argument parsing and modern JavaScript stack support (pnpm, vitest, Next.js, TypeScript, Playwright, Prisma).
Name Collision Warning
Two different "rtk" projects exist:
- This project: Rust Token Killer (rtk-ai/rtk)
- reachingforthejack/rtk: Rust Type Kit (DIFFERENT - generates Rust types)
Verify correct installation:
rtk --version # Should show "rtk 0.28.2" (or newer)
rtk gain # Should show token savings stats (NOT "command not found")If rtk gain fails, you have the wrong package installed.
Development Commands
Note: If rtk is installed, prefer rtk <cmd> over raw commands for token-optimized output.All commands work with passthrough support even for subcommands rtk doesn't specifically handle.
Build & Run
cargo build # raw
rtk cargo build # preferred (token-optimized)
cargo build --release # release build (optimized)
cargo run -- <command> # run directly
cargo install --path . # install locallyTesting
cargo test # all tests
rtk cargo test # preferred (token-optimized)
cargo test <test_name> # specific test
cargo test <module_name>:: # module tests
cargo test -- --nocapture # with stdout
bash scripts/test-all.sh # smoke tests (installed binary required)Linting & Quality
cargo check # check without building
cargo fmt # format code
cargo clippy --all-targets # all clippy lints
rtk cargo clippy --all-targets # preferredPre-commit Gate
cargo fmt --all && cargo clippy --all-targets && cargo test --allPackage Building
cargo deb # DEB package (needs cargo-deb)
cargo generate-rpm # RPM package (needs cargo-generate-rpm, after release build)Architecture
rtk uses a command proxy architecture: main.rs routes CLI commands via a Clap Commands enum to specialized filter modules in src/cmds/*/, each of which executes the underlying command and compresses its output. Token savings are tracked in SQLite via src/core/tracking.rs.
For the full architecture, component details, and module development patterns, see:
- ARCHITECTURE.md β System design, module organization, filtering strategies, error handling
- docs/contributing/TECHNICAL.md β End-to-end flow, folder map, hook system, filter pipeline
Module responsibilities are documented in each folder's README.md and each file's //! doc header. Browse src/cmds/*/ to discover available filters.
Supported ecosystems: git/gh/gt, cargo, go/golangci-lint, npm/pnpm/npx, ruff/pytest/pip/mypy, rspec/rubocop/rake, dotnet, playwright/vitest/jest, docker/kubectl/aws.
Proxy Mode
Purpose: Execute commands without filtering but track usage for metrics.
Usage: rtk proxy <command> [args...]
Benefits:
- Bypass RTK filtering: Workaround bugs or get full unfiltered output
- Track usage metrics: Measure which commands Claude uses most (visible in rtk gain --history)
- Guaranteed compatibility: Always works even if RTK doesn't implement the command
Examples:
rtk proxy git log --oneline -20 # Full git log output (no truncation)
rtk proxy npm install express # Raw npm output (no filtering)
rtk proxy curl https://api.example.com/data # Any command worksAll proxy commands appear in rtk gain --history with 0% savings (input = output).
Coding Rules
Rust patterns, error handling, and anti-patterns are defined in .claude/rules/rust-patterns.md (auto-loaded into context). Key points:
- anyhow::Result everywhere, always .context("description")?
- No unwrap() in production code
- lazy_static! for all regex (never compile inside a function)
- Fallback pattern: if filter fails, execute raw command unchanged
- No async: single-threaded by design (startup <10ms)
- Exit code propagation: std::process::exit(code) on child failure
Testing strategy and performance targets are defined in .claude/rules/cli-testing.md (auto-loaded). Key targets: <10ms startup, <5MB memory, 60-90% token savings.
For contribution workflow and design philosophy, see CONTRIBUTING.md. For the step-by-step filter implementation checklist, see src/cmds/README.md.
Build Verification (Mandatory)
CRITICAL: After ANY Rust file edits, ALWAYS run the full quality check pipeline before committing:
cargo fmt --all && cargo clippy --all-targets && cargo test --allRules:
- Never commit code that hasn't passed all 3 checks
- Fix ALL clippy warnings before moving on (zero tolerance)
- If build fails, fix it immediately before continuing to next task
Performance verification (for filter changes):
hyperfine 'rtk git log -10' --warmup 3 # before
cargo build --release
hyperfine 'target/release/rtk git log -10' --warmup 3 # after (should be <10ms)Working Directory Confirmation
ALWAYS confirm working directory before starting any work:
pwd # Verify you're in the rtk project root
git branch # Verify correct branch (main, feature/*, etc.)Never assume which project to work in. Always verify before file operations.
Avoiding Rabbit Holes
Stay focused on the task. Do not make excessive operations to verify external APIs, documentation, or edge cases unless explicitly asked.
Rule: If verification requires more than 3-4 exploratory commands, STOP and ask the user whether to continue or trust available info.
Examples of rabbit holes to avoid:
- Excessive regex pattern testing (trust snapshot tests, don't manually verify 20 edge cases)
- Deep diving into external command documentation (use fixtures, don't research git/cargo internals)
- Over-testing cross-platform behavior (test macOS + Linux, trust CI for Windows)
- Verifying API signatures across multiple crate versions (use docs.rs if needed, don't clone repos)
When to stop and ask:
- "Should I research X external API behavior?" β ASK if it requires >3 commands
- "Should I test Y edge case?" β ASK if not mentioned in requirements
- "Should I verify Z across N platforms?" β ASK if N > 2
Plan Execution Protocol
When user provides a numbered plan (QW1-QW4, Phase 1-5, sprint tasks, etc.):
1. Execute sequentially: Follow plan order unless explicitly told otherwise
2. Commit after each logical step: One commit per completed phase/task
3. Never skip or reorder: If a step is blocked, report it and ask before proceeding
4. Track progress: Use task list (TaskCreate/TaskUpdate) for plans with 3+ steps
5. Validate assumptions: Before starting, verify all referenced file paths exist and working directory is correct
README.md
<p align="center">
<img src="https://avatars.githubusercontent.com/u/258253854?v=4" alt="RTK - Rust Token Killer" width="500">
</p>
<p align="center">
<strong>High-performance CLI proxy that reduces LLM token consumption by 60-90%</strong>
</p>
<p align="center">
<a href="https://github.com/rtk-ai/rtk/actions"><img src="https://github.com/rtk-ai/rtk/workflows/Security%20Check/badge.svg" alt="CI"></a>
<a href="https://github.com/rtk-ai/rtk/releases"><img src="https://img.shields.io/github/v/release/rtk-ai/rtk" alt="Release"></a>
<a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License: MIT"></a>
<a href="https://discord.gg/RySmvNF5kF"><img src="https://img.shields.io/discord/1470188214710046894?label=Discord&logo=discord" alt="Discord"></a>
<a href="https://formulae.brew.sh/formula/rtk"><img src="https://img.shields.io/homebrew/v/rtk" alt="Homebrew"></a>
</p>
<p align="center">
<a href="https://www.rtk-ai.app">Website</a> •
<a href="#installation">Install</a> •
<a href="https://www.rtk-ai.app/guide/troubleshooting">Troubleshooting</a> •
<a href="ARCHITECTURE.md">Architecture</a> •
<a href="https://discord.gg/RySmvNF5kF">Discord</a>
</p>
<p align="center">
<a href="README.md">English</a> •
<a href="README_fr.md">Francais</a> •
<a href="README_zh.md">δΈζ</a> •
<a href="README_ja.md">ζ₯ζ¬θͺ</a> •
<a href="README_ko.md">νκ΅μ΄</a> •
<a href="README_es.md">Espanol</a>
</p>
---
rtk filters and compresses command outputs before they reach your LLM context. Single Rust binary, 100+ supported commands, <10ms overhead.
Token Savings (30-min Claude Code Session)
| Operation | Frequency | Standard | rtk | Savings |
|-----------|-----------|----------|-----|---------|
| ls / tree | 10x | 2,000 | 400 | -80% |
| cat / read | 20x | 40,000 | 12,000 | -70% |
| grep / rg | 8x | 16,000 | 3,200 | -80% |
| git status | 10x | 3,000 | 600 | -80% |
| git diff | 5x | 10,000 | 2,500 | -75% |
| git log | 5x | 2,500 | 500 | -80% |
| git add/commit/push | 8x | 1,600 | 120 | -92% |
| cargo test / npm test | 5x | 25,000 | 2,500 | -90% |
| ruff check | 3x | 3,000 | 600 | -80% |
| pytest | 4x | 8,000 | 800 | -90% |
| go test | 3x | 6,000 | 600 | -90% |
| docker ps | 3x | 900 | 180 | -80% |
| Total | | ~118,000 | ~23,900 | -80% |
Estimates based on medium-sized TypeScript/Rust projects. Actual savings vary by project size.
Installation
Homebrew (recommended)
brew install rtkQuick Install (Linux/macOS)
curl -fsSL https://raw.githubusercontent.com/rtk-ai/rtk/refs/heads/master/install.sh | shInstalls to ~/.local/bin. Add to PATH if needed:``bashecho 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc # or ~/.zshrc
`Cargo
cargo install --git https://github.com/rtk-ai/rtkPre-built Binaries
Download from releases:
- macOS: rtk-x86_64-apple-darwin.tar.gz / rtk-aarch64-apple-darwin.tar.gzrtk-x86_64-unknown-linux-musl.tar.gz
- Linux: / rtk-aarch64-unknown-linux-gnu.tar.gzrtk-x86_64-pc-windows-msvc.zip
- Windows:
Windows users: Extract the zip and place rtk.exesomewhere in your PATH (e.g.C:\Users\<you>\.local\bin). Run RTK from Command Prompt, PowerShell, or Windows Terminal β do not double-click the.exe(it will flash and close). For the best experience, use WSL where the full hook system works natively. See Windows setup below for details.
Verify Installation
rtk --version # Should show "rtk 0.28.2"
rtk gain # Should show token savings statsName collision warning: Another project named "rtk" (Rust Type Kit) exists on crates.io. If rtk gainfails, you have the wrong package. Usecargo install --gitabove instead.
Quick Start
1. Install for your AI tool
rtk init -g # Claude Code / Copilot (default)
rtk init -g --gemini # Gemini CLI
rtk init -g --codex # Codex (OpenAI)
rtk init -g --agent cursor # Cursor
rtk init --agent windsurf # Windsurf
rtk init --agent cline # Cline / Roo Code
rtk init --agent kilocode # Kilo Code
rtk init --agent antigravity # Google Antigravity2. Restart your AI tool, then test
git status # Automatically rewritten to rtk git statusThe hook transparently rewrites Bash commands (e.g., git status -> rtk git status) before execution. Claude never sees the rewrite, it just gets compressed output.
Important: the hook only runs on Bash tool calls. Claude Code built-in tools like Read, Grep, and Glob do not pass through the Bash hook, so they are not auto-rewritten. To get RTK's compact output for those workflows, use shell commands (cat/head/tail, rg/grep, find) or call rtk read, rtk grep, or rtk find directly.
How It Works
Without rtk: With rtk: Claude --git status--> shell --> git Claude --git status--> RTK --> git
^ | ^ | |
| ~2,000 tokens (raw) | | ~200 tokens | filter |
+-----------------------------------+ +------- (filtered) ---+----------+
Four strategies applied per command type:
1. Smart Filtering - Removes noise (comments, whitespace, boilerplate)
2. Grouping - Aggregates similar items (files by directory, errors by type)
3. Truncation - Keeps relevant context, cuts redundancy
4. Deduplication - Collapses repeated log lines with counts
Commands
Files
rtk ls . # Token-optimized directory tree
rtk read file.rs # Smart file reading
rtk read file.rs -l aggressive # Signatures only (strips bodies)
rtk smart file.rs # 2-line heuristic code summary
rtk find "*.rs" . # Compact find results
rtk grep "pattern" . # Grouped search results
rtk diff file1 file2 # Condensed diffGit
rtk git status # Compact status
rtk git log -n 10 # One-line commits
rtk git diff # Condensed diff
rtk git add # -> "ok"
rtk git commit -m "msg" # -> "ok abc1234"
rtk git push # -> "ok main"
rtk git pull # -> "ok 3 files +10 -2"GitHub CLI
rtk gh pr list # Compact PR listing
rtk gh pr view 42 # PR details + checks
rtk gh issue list # Compact issue listing
rtk gh run list # Workflow run statusTest Runners
rtk jest # Jest compact (failures only)
rtk vitest # Vitest compact (failures only)
rtk playwright test # E2E results (failures only)
rtk pytest # Python tests (-90%)
rtk go test # Go tests (NDJSON, -90%)
rtk cargo test # Cargo tests (-90%)
rtk rake test # Ruby minitest (-90%)
rtk rspec # RSpec tests (JSON, -60%+)
rtk err <cmd> # Filter errors only from any command
rtk test <cmd> # Generic test wrapper - failures only (-90%)Build & Lint
rtk lint # ESLint grouped by rule/file
rtk lint biome # Supports other linters
rtk tsc # TypeScript errors grouped by file
rtk next build # Next.js build compact
rtk prettier --check . # Files needing formatting
rtk cargo build # Cargo build (-80%)
rtk cargo clippy # Cargo clippy (-80%)
rtk ruff check # Python linting (JSON, -80%)
rtk golangci-lint run # Go linting (JSON, -85%)
rtk rubocop # Ruby linting (JSON, -60%+)Package Managers
rtk pnpm list # Compact dependency tree
rtk pip list # Python packages (auto-detect uv)
rtk pip outdated # Outdated packages
rtk bundle install # Ruby gems (strip Using lines)
rtk prisma generate # Schema generation (no ASCII art)AWS
rtk aws sts get-caller-identity # One-line identity
rtk aws ec2 describe-instances # Compact instance list
rtk aws lambda list-functions # Name/runtime/memory (strips secrets)
rtk aws logs get-log-events # Timestamped messages only
rtk aws cloudformation describe-stack-events # Failures first
rtk aws dynamodb scan # Unwraps type annotations
rtk aws iam list-roles # Strips policy documents
rtk aws s3 ls # Truncated with tee recoveryContainers
rtk docker ps # Compact container list
rtk docker images # Compact image list
rtk docker logs <container> # Deduplicated logs
rtk docker compose ps # Compose services
rtk kubectl pods # Compact pod list
rtk kubectl logs <pod> # Deduplicated logs
rtk kubectl services # Compact service listData & Analytics
rtk json config.json # Structure without values
rtk deps # Dependencies summary
rtk env -f AWS # Filtered env vars
rtk log app.log # Deduplicated logs
rtk curl <url> # Auto-detect JSON + schema
rtk wget <url> # Download, strip progress bars
rtk summary <long command> # Heuristic summary
rtk proxy <command> # Raw passthrough + trackingToken Savings Analytics
rtk gain # Summary stats
rtk gain --graph # ASCII graph (last 30 days)
rtk gain --history # Recent command history
rtk gain --daily # Day-by-day breakdown
rtk gain --all --format json # JSON export for dashboardsrtk discover # Find missed savings opportunities
rtk discover --all --since 7 # All projects, last 7 days
rtk session # Show RTK adoption across recent sessions
Global Flags
-u, --ultra-compact # ASCII icons, inline format (extra token savings)
-v, --verbose # Increase verbosity (-v, -vv, -vvv)Examples
Directory listing:
ls -la (45 lines, ~800 tokens) # rtk ls (12 lines, ~150 tokens)
drwxr-xr-x 15 user staff 480 ... my-project/
-rw-r--r-- 1 user staff 1234 ... +-- src/ (8 files)
... | +-- main.rs
+-- Cargo.tomlGit operations:
git push (15 lines, ~200 tokens) # rtk git push (1 line, ~10 tokens)
Enumerating objects: 5, done. ok main
Counting objects: 100% (5/5), done.
Delta compression using up to 8 threads
...Test output:
cargo test (200+ lines on failure) # rtk test cargo test (~20 lines)
running 15 tests FAILED: 2/15 tests
test utils::test_parse ... ok test_edge_case: assertion failed
test utils::test_format ... ok test_overflow: panic at utils.rs:18
...Auto-Rewrite Hook
The most effective way to use rtk. The hook transparently intercepts Bash commands and rewrites them to rtk equivalents before execution.
Result: 100% rtk adoption across all conversations and subagents, zero token overhead.
Scope note: this only applies to Bash tool calls. Claude Code built-in tools such as Read, Grep, and Glob bypass the hook, so use shell commands or explicit rtk commands when you want RTK filtering there.
Setup
rtk init -g # Install hook + RTK.md (recommended)
rtk init -g --opencode # OpenCode plugin (instead of Claude Code)
rtk init -g --auto-patch # Non-interactive (CI/CD)
rtk init -g --hook-only # Hook only, no RTK.md
rtk init --show # Verify installationAfter install, restart Claude Code.
Windows
RTK works on Windows with some limitations. The auto-rewrite hook (rtk-rewrite.sh) requires a Unix shell, so on native Windows RTK falls back to CLAUDE.md injection mode β your AI assistant receives RTK instructions but commands are not rewritten automatically.
Recommended: WSL (full support)
For the best experience, use WSL (Windows Subsystem for Linux). Inside WSL, RTK works exactly like Linux β full hook support, auto-rewrite, everything:
Inside WSL
curl -fsSL https://raw.githubusercontent.com/rtk-ai/rtk/refs/heads/master/install.sh | sh
rtk init -gNative Windows (limited support)
On native Windows (cmd.exe / PowerShell), RTK filters work but the hook does not auto-rewrite commands:
1. Download and extract rtk-x86_64-pc-windows-msvc.zip from releases
2. Add rtk.exe to your PATH
3. Initialize (falls back to CLAUDE.md injection)
rtk init -g
4. Use rtk explicitly
rtk cargo test
rtk git statusImportant: Do not double-click rtk.exe β it is a CLI tool that prints usage and exits immediately. Always run it from a terminal (Command Prompt, PowerShell, or Windows Terminal).
| Feature | WSL | Native Windows |
|---------|-----|----------------|
| Filters (cargo, git, etc.) | Full | Full |
| Auto-rewrite hook | Yes | No (CLAUDE.md fallback) |
| rtk init -g | Hook mode | CLAUDE.md mode |rtk gain
| / analytics | Full | Full |
Supported AI Tools
RTK supports 12 AI coding tools. Each integration transparently rewrites shell commands to rtk equivalents for 60-90% token savings.
| Tool | Install | Method |
|------|---------|--------|
| Claude Code | rtk init -g | PreToolUse hook (bash) |rtk init -g --copilot
| GitHub Copilot (VS Code) | | PreToolUse hook β transparent rewrite |rtk init -g --copilot
| GitHub Copilot CLI | | PreToolUse deny-with-suggestion (CLI limitation) |rtk init -g --agent cursor
| Cursor | | preToolUse hook (hooks.json) |rtk init -g --gemini
| Gemini CLI | | BeforeTool hook |rtk init -g --codex
| Codex | | AGENTS.md + RTK.md instructions |rtk init --agent windsurf
| Windsurf | | .windsurfrules (project-scoped) |rtk init --agent cline
| Cline / Roo Code | | .clinerules (project-scoped) |rtk init -g --opencode
| OpenCode | | Plugin TS (tool.execute.before) |openclaw plugins install ./openclaw
| OpenClaw | | Plugin TS (before_tool_call) |rtk init --agent kilocode
| Mistral Vibe | Planned (#800) | Blocked on upstream |
| Kilo Code | | .kilocode/rules/rtk-rules.md (project-scoped) |rtk init --agent antigravity
| Google Antigravity | | .agents/rules/antigravity-rtk-rules.md (project-scoped) |
For per-agent setup details, override controls, and graceful degradation, see the Supported Agents guide.
Configuration
~/.config/rtk/config.toml (macOS: ~/Library/Application Support/rtk/config.toml):
[hooks]
exclude_commands = ["curl", "playwright"] # skip rewrite for these[tee]
enabled = true # save raw output on failure (default: true)
mode = "failures" # "failures", "always", or "never"
When a command fails, RTK saves the full unfiltered output so the LLM can read it without re-executing:
FAILED: 2/15 tests
[full output: ~/.local/share/rtk/tee/1707753600_cargo_test.log]For the full config reference (all sections, env vars, per-project filters), see the Configuration guide.
Uninstall
rtk init -g --uninstall # Remove hook, RTK.md, settings.json entry
cargo uninstall rtk # Remove binary
brew uninstall rtk # If installed via HomebrewDocumentation
- rtk-ai.app/guide β full user guide (installation, supported agents, what gets optimized, analytics, configuration, troubleshooting)
- INSTALL.md β detailed installation reference
- ARCHITECTURE.md β system design and technical decisions
- CONTRIBUTING.md β contribution guide
- SECURITY.md β security policy
Privacy & Telemetry
RTK can collect anonymous, aggregate usage metrics once per day. Telemetry is disabled by default and requires explicit opt-in consent (GDPR Art. 6, 7) during rtk init or via rtk telemetry enable`. This data helps us build a better product: identifying which commands need filters, which filters need improvement, and how much value RTK delivers. For the full list of fields, data handling, and contributor guidelines, see docs/TELEMETRY.md.
What is collected and why:
| Category | Data | Why |
|----------|------|-----|
| Identity | Salted device hash (SHA-256, not reversible) | Count unique installations without tracking individuals |
| Environment | RTK version, OS, architecture, install method | Know which platforms to support and test |
| Usage volume | Command count (24h), total commands, tokens saved (24h/30d/total) | Measure adoption and value delivered |
| Quality | Top 5 passthrough commands (0% savings), parse failure count, commands with <30% savings | Identify missing filters and weak ones to improve |
| Ecosystem | Command category distribution (e.g. git 45%, cargo 20%, js 15%) | Prioritize filter development for popular ecosystems |
| Retention | Days since first use, active days in last 30 | Understand engagement and detect churn |
| Adoption | AI agent hook type (claude/gemini/codex), custom TOML filter count | Track integration coverage and DSL adoption |
| Configuration | Whether config.toml exists, number of excluded commands, project count | Understand user maturity and customization patterns |
| Features | Usage counts for meta-commands (gain, discover, proxy, verify) | Know which RTK features are valued vs unused |
| Economics | Estimated USD savings (based on API token pricing) | Quantify the value RTK provides to users |
All data is aggregate counts or anonymized command names (first 3 words, no arguments). Top commands report only tool names (e.g. "git", "cargo"), never full command lines.
What is NOT collected: source code, file paths, command arguments, secrets, environment variables, personal data, or repository contents.
Manage telemetry:
rtk telemetry status # Check current consent state
rtk telemetry enable # Give consent (interactive prompt)
rtk telemetry disable # Withdraw consent β stops all collection immediately
rtk telemetry forget # Withdraw consent + delete all local data + request server-side erasureOverride via environment:
export RTK_TELEMETRY_DISABLED=1 # Blocks telemetry regardless of consentStar History
<a href="https://www.star-history.com/?repos=rtk-ai%2Frtk&type=date&legend=top-left">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=rtk-ai/rtk&type=date&theme=dark&legend=top-left" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=rtk-ai/rtk&type=date&legend=top-left" />
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=rtk-ai/rtk&type=date&legend=top-left" />
</picture>
</a>
StarMapper
<a href="https://starmapper.bruniaux.com/rtk-ai/rtk">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://starmapper.bruniaux.com/api/map-image/rtk-ai/rtk?theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://starmapper.bruniaux.com/api/map-image/rtk-ai/rtk?theme=light" />
<img alt="StarMapper" src="https://starmapper.bruniaux.com/api/map-image/rtk-ai/rtk" />
</picture>
</a>
Contributing
Contributions welcome! Please open an issue or PR on GitHub.
Join the community on Discord.
License
MIT License - see LICENSE for details.
Disclaimer
See DISCLAIMER.md.