RTK (Rust Token Killer) 完整教學
一句話:在 LLM agent 跑 shell 命令前先過濾、分群、去重、截斷輸出,把 token 消耗砍 60–90%。
1. 專案定位
RTK (Rust Token Killer; Rust token 殺手) 是 Rust 寫的 CLI proxy,定位是「AI agent 與 shell 之間的壓縮層」。和其他類似工具比較:
| 維度 | RTK | LiteLLM proxy | promptfoo | 自寫 hook |
|---|---|---|---|---|
| 目標 | 砍 shell command 輸出 token | LLM API 路由 | Prompt 評估 | DIY |
| 部署 | 單 Rust binary,零依賴 | Python container | Node | 自負責 |
| Overhead | <10ms | 數十 ms | N/A | 視實作 |
| 整合形式 | PreToolUse hook 自動 rewrite | API gateway | 評估框架 | 手寫 |
| 範圍 | shell 命令層(git status → rtk git status) | 整 LLM API | 整 prompt | 任意 |
| 模型成本 | 不省 API 費,省 token in context | 多模型路由 | 不省 | 任意 |
| 多 agent 支援 | 13+ tools 原生整合 | API 統一介面 | 部分 | 自寫 |
主要使用情境:
- Claude Code / Copilot / Cursor 重度使用者降低 token 用量、防 context 爆掉
- pay-per-token plan 上的工程師降低帳單
- 大型 codebase 跑 grep / find / test 想拿到「人眼可讀但 token 少」摘要
- CI / 自動化流程節省 LLM cost
- 個人 dotfiles 加進去當常駐 alias
核心優勢:
- 單 Rust binary:~5 MB,零依賴,跨平台
- <10ms overhead:感受不到
- 100+ commands / 10+ 生態:JS / Rust / Cloud / Ruby / Git / System / JVM / .NET / Python / Go
- 13+ AI tools 原生整合:自動安裝 hook,agent 無感
- GDPR-compliant:telemetry opt-in only
2. 安裝指南
2.1 系統需求
- OS:macOS / Linux / Windows(Windows 建議 WSL2)
- 磁碟空間:~5 MB(binary)
- AI tool:任一支援的(見 §3.4)
2.2 三種安裝方式
1# 1) Homebrew(macOS / Linux,推薦)
2brew install rtk
3
4# 2) Curl 一鍵 install(會裝到 ~/.local/bin)
5curl -fsSL https://raw.githubusercontent.com/rtk-ai/rtk/refs/heads/master/install.sh | sh
6
7# 3) Cargo(從原始碼編譯,最新版本)
8cargo install --git https://github.com/rtk-ai/rtk
9
10# 確認
11rtk --version
12rtk gain # 顯示 token 省了多少 dashboard
⚠️ 重名警告:crates.io 上有另一個
rtk(Rust Type Kit)。如果rtk gain失敗,代表裝錯包。改用cargo install --git上面那條。
2.3 為 AI tool 啟用 hook
1# Claude Code / Copilot(預設)
2rtk init -g
3
4# Gemini CLI
5rtk init -g --gemini
6
7# Codex (OpenAI)
8rtk init -g --codex
9
10# Cursor
11rtk init -g --agent cursor
12
13# Windsurf / Cline / Kilocode / Antigravity / Hermes
14rtk init --agent <name>
15
16# 安裝後 **務必重啟 AI tool**
2.4 安裝流程圖
flowchart TD
A["決定平台"] --> B{OS?}
B -- "macOS / Linux" --> C1["brew install rtk
或 curl install.sh"]
B -- "Windows" --> C2{"WSL2?"}
C2 -- "是" --> C1
C2 -- "否(原生)" --> C3["下載 zip 解壓
加 PATH
退化到 CLAUDE.md injection"]
C1 --> D["rtk --version 驗證"]
C3 --> D
D --> E{"使用哪個 agent?"}
E -- "Claude Code / Copilot" --> F1["rtk init -g"]
E -- "Gemini" --> F2["rtk init -g --gemini"]
E -- "Codex" --> F3["rtk init -g --codex"]
E -- "Cursor" --> F4["rtk init -g --agent cursor"]
E -- "其他 (Windsurf/Cline/...)" --> F5["rtk init --agent "]
F1 --> G["**重啟 AI tool**"]
F2 --> G
F3 --> G
F4 --> G
F5 --> G
G --> H["跑 git status 驗證自動 rewrite"]
3. 核心架構解析
3.1 整體運作流程
flowchart LR
Agent["AI Agent
(Claude Code / Copilot / ...)"] -->|"git status"| Hook["PreToolUse Hook
(rtk-rewrite.sh)"]
Hook -->|"rtk git status"| RTK["RTK binary"]
RTK -->|執行 raw 命令| Shell["shell"]
Shell --> Raw["raw output
(2,000 tokens)"]
Raw --> Filter["RTK Filters
1. Smart Filtering
2. Grouping
3. Truncation
4. Deduplication"]
Filter --> Compact["compact output
(200 tokens)"]
Compact -.-> Agent
RTK -.失敗時.-> Tee["raw 存到
~/.local/share/rtk/tee/"]
3.2 四種壓縮策略
- Smart Filtering:移除噪音(comments、whitespace、boilerplate、emoji、ANSI escape codes)
- Grouping:相似項聚合(同目錄檔案、同類型 errors)
- Truncation:保留 head/tail,截掉中段重複;含 tail-hint 提示去 tee 看完整輸出
- Deduplication:重複 log 行 collapse 成
count × pattern格式
3.3 模組結構
1src/
2├── main.rs # CLI entry
3├── core/ # 核心 abstractions
4│ ├── tee.rs # 失敗時存原始輸出
5│ ├── stream.rs # 串流處理
6│ └── ...
7├── filters/ # 四大策略實作
8├── hooks/ # PreToolUse hook 生成器
9├── cmds/ # 100+ 命令的對應 filter
10│ ├── git/ # git status / log / diff / push / ...
11│ ├── rust/ # cargo test / clippy / build
12│ ├── js/ # npm / pnpm / yarn / bun / vitest / jest
13│ ├── python/ # pytest / ruff / mypy / pip
14│ ├── go/ # go test / build / vet / golangci-lint
15│ ├── jvm/ # gradlew / mvn / kotlin
16│ ├── dotnet/ # dotnet build / test / format
17│ ├── ruby/ # rspec / rake / bundle
18│ ├── system/ # ls / find / grep / cat / docker / kubectl
19│ └── cloud/ # aws / gcloud / az
20├── learn/ # 自學新命令的 fallback
21├── discover/ # rtk discover:掃 session history 找 missed opportunities
22├── parser/ # 各種輸出格式 parser
23└── analytics/ # token-savings 統計 (gain command)
3.4 13+ AI tool 整合矩陣
| Tool | Install | Hook 機制 |
|---|---|---|
| Claude Code | rtk init -g | PreToolUse hook (bash) |
| GitHub Copilot (VS Code) | rtk init -g --copilot | PreToolUse 透明 rewrite |
| Copilot CLI | rtk init -g --copilot | deny-with-suggestion |
| Cursor | rtk init -g --agent cursor | preToolUse hook |
| Gemini CLI | rtk init -g --gemini | BeforeTool hook |
| Codex (OpenAI) | rtk init -g --codex | AGENTS.md + RTK.md |
| Windsurf | rtk init --agent windsurf | .windsurfrules |
| Cline / Roo Code | rtk init --agent cline | .clinerules |
| OpenCode | rtk init -g --opencode | TS plugin (tool.execute.before) |
| OpenClaw | openclaw plugins install ./openclaw | TS plugin (before_tool_call) |
| Hermes | rtk init --agent hermes | Python plugin adapter |
| Mistral Vibe | 規劃中 (#800) | blocked upstream |
| Kilo Code | rtk init --agent kilocode | .kilocode/rules/rtk-rules.md |
| Google Antigravity | rtk init --agent antigravity | .agents/rules/*.md |
3.5 Token 節省 benchmark(30-min Claude Code session)
| Operation | Freq | Standard | RTK | 節省 |
|---|---|---|---|---|
| ls / tree | 10× | 2,000 | 400 | -80% |
| cat / read | 20× | 40,000 | 12,000 | -70% |
| grep / rg | 8× | 16,000 | 3,200 | -80% |
| git status | 10× | 3,000 | 600 | -80% |
| git diff | 5× | 10,000 | 2,500 | -75% |
| git log | 5× | 2,500 | 500 | -80% |
| git add/commit/push | 8× | 1,600 | 120 | -92% |
| cargo test / npm test | 5× | 25,000 | 2,500 | -90% |
| ruff check | 3× | 3,000 | 600 | -80% |
| pytest | 4× | 8,000 | 800 | -90% |
| go test | 3× | 6,000 | 600 | -90% |
| docker ps | 3× | 900 | 180 | -80% |
| Total | ~118,000 | ~23,900 | -80% |
4. Helper Scripts 詳細用法
4.1 Files 系列
1rtk ls . # token-optimized 樹狀
2rtk read file.rs # smart 檔案讀取
3rtk read file.rs -l aggressive # 只 signatures(去 body)
4rtk smart file.rs # 2-line heuristic 摘要
5rtk find "*.rs" . # compact find
6rtk grep "pattern" . # grouped 結果
7rtk diff file1 file2 # 縮短 diff
4.2 Git 系列
1rtk git status # compact
2rtk git log -n 10 # one-line commits
3rtk git diff # 縮短 diff
4rtk git add # → "ok"
5rtk git commit -m "msg" # → "ok abc1234"
6rtk git push # → "ok main"
7rtk git pull # → "ok"
4.3 Test / Lint 系列
1rtk test cargo test # 只回失敗 + 計數
2rtk cargo clippy --all-targets # 只回 warning/error
3rtk pytest # FAILED 列表
4rtk ruff check # cap 50 違規
5rtk go test ./... # FAIL summary
6rtk gradlew build # 只 errors
7rtk dotnet test # FAIL list
4.4 Cloud / Container
1rtk docker ps # compact
2rtk docker compose ps # 同上
3rtk kubectl get pods # alias-aware
4rtk aws s3 ls # 壓縮列
5rtk gcloud compute instances list
4.5 Analytics 命令(meta)
1rtk gain # 看你省了多少 tokens
2rtk gain --history # 歷史每命令的節省
3rtk discover # 掃 session history 找 missed opportunities
4rtk proxy <cmd> # 跑 raw 但仍記錄
5rtk telemetry status # 看 telemetry 狀態
6rtk telemetry enable / disable # 啟用 / 停用
4.6 Hook 管理
1rtk init -g # 裝 hook + RTK.md(推薦)
2rtk init -g --opencode # 改裝 OpenCode plugin
3rtk init -g --auto-patch # 非互動式(CI/CD)
4rtk init -g --hook-only # 只 hook,不寫 RTK.md
5rtk init --show # 顯示安裝狀態
6rtk init -g --uninstall # 移除 hook + RTK.md + settings
4.7 Global flags
1-u, --ultra-compact # ASCII 圖示,inline 格式(更省)
2-v, --verbose # 詳細 (-v, -vv, -vvv)
4.8 Config 檔
~/.config/rtk/config.toml(macOS: ~/Library/Application Support/rtk/config.toml):
1[hooks]
2exclude_commands = ["curl", "playwright"] # 不 rewrite
3
4[tee]
5enabled = true # 失敗時存原始
6mode = "failures" # "failures" / "always" / "never"
失敗時自動存原始輸出供 LLM 後續查:
1FAILED: 2/15 tests
2[full output: ~/.local/share/rtk/tee/1707753600_cargo_test.log]
5. 應用場景
5.1 場景一:Claude Code 重度使用者降低帳單
1brew install rtk
2rtk init -g
3# 重啟 Claude Code
4# 之後跑任何 bash 命令都會自動 rewrite
5# 一天下來 rtk gain 看省了多少
5.2 場景二:大型 monorepo 跑 grep 不爆 context
1# 傳統:grep -r "TODO" . → 5000+ 行直接送 LLM
2# RTK:rtk grep -r "TODO" .
3# → 「Grouped: 32 TODOs across 12 files」+ 前 10 範例
5.3 場景三:CI / 自動化省 LLM cost
1# GitHub Actions
2- run: |
3 brew install rtk
4 rtk init -g --auto-patch
5 rtk cargo test # token-optimized output 送 LLM bot
5.4 場景四:個人 alias / dotfiles 永久啟用
1# ~/.zshrc 或 ~/.bashrc
2alias g='rtk git'
3alias ll='rtk ls -la'
4alias t='rtk test cargo test'
5.5 場景五:探索新命令的 RTK 化機會
1rtk discover
2# 掃過去 session 歷史,列出「沒用 rtk 但本來可以省」的命令
3# 譬如 jq / yq / pnpm 等如果用很頻繁,會建議補 filter
6. 資安掃描報告
掃描範圍:
src/Rust +install.sh+SECURITY.md+.semgrep.yml+ telemetry policy
🟡 整體:中等注意事項(MEDIUM)
RTK 是 production-grade tool with explicit security tooling(有 SECURITY.md、.semgrep.yml、.github/docs-pipeline-contract.md)。主要關注點在 (a) curl-pipe-sh 安裝模式,(b) hook 寫入使用者 ~/.claude 等,(c) telemetry opt-in 機制。
| 類別 | 結果 | 說明 |
|---|---|---|
| Rust unsafe | 🟢 安全 | grep unsafe { 結果均在 stream.rs 內,限內部使用,已測試覆蓋 |
| Command::new | 🟢 安全 | 全部 process::Command 都在 stream.rs / cmds/* 內呼叫使用者明確指定的命令,無 shell injection |
| eval / 動態執行 | 🟢 安全 | Rust 本身無 eval;無 format! → exec 模式 |
| 硬編 secret | 🟢 安全 | 全程無命中 |
| Telemetry | 🟢 GDPR-compliant | opt-in only(GDPR Art. 6, 7);24h 1 次;salted SHA-256 device hash(不可反推);明列每個欄位用途 |
| install.sh | 🟡 注意 | 經典 curl ... | sh 模式;建議先 curl > install.sh && cat install.sh 審閱再 sh install.sh |
| Hook 寫入 | 🟡 注意 | rtk init -g 會寫入 ~/.claude/settings.json / ~/.cursor/hooks.json 等;無 SHA / signature 驗證 |
~/.local/share/rtk/tee/ | 🟡 注意 | 失敗命令的 raw 輸出存本機,可能含敏感資料(譬如 cat /etc/passwd 被 LLM rewrite 跑過)— 預設模式 failures 只在失敗時存 |
| Dependencies | 🟢 透明 | Cargo.toml + Cargo.lock 版本鎖;發行用 dependabot 自動更新 |
| Semgrep CI | 🟢 正面 | .semgrep.yml 內建靜態掃描規則,PR 通過 semgrep check |
| Apache-2.0 vs MIT | 🟡 標示不一致 | GitHub repo metadata 顯示 Apache-2.0,Cargo.toml 寫 MIT;以 LICENSE 檔內容為準(Apache 2.0) |
🟡 中等注意事項詳述
curl ... | sh安裝:經典 supply chain 風險。雖然 GitHub raw 來源相對可信,但攻擊者只要拿到masterpush 權就能 ship 惡意 install script。- 緩解:(a) Homebrew
brew install rtk走 tap 簽章;(b) Cargo--git編原始碼;(c) 先curl ... > install.sh; cat install.sh審閱再跑。
- 緩解:(a) Homebrew
Hook 寫入 agent 設定:
rtk init -g修改~/.claude/settings.json等。Hook 內容是「呼叫 rtk binary」,但理論上若 binary 被換掉就會出問題。- 緩解:Homebrew 安裝 + 不要把
~/.local/bin開放給 untrusted user。
- 緩解:Homebrew 安裝 + 不要把
Tee 暫存原始輸出:失敗命令的完整輸出存
~/.local/share/rtk/tee/,若你跑過cat .env之類,會留在那邊。- 緩解:
rtk tee --clear定期清;或 config[tee] mode = "never"。
- 緩解:
Telemetry 雖然 opt-in,欄位仍是敏感:command 類別分佈、AI agent hook type、安裝方法,可被用來 profile 使用者。
- 緩解:預設關閉(README 明寫);要關掉
rtk telemetry disable。
- 緩解:預設關閉(README 明寫);要關掉
develop為 default branch:與多數 repo 慣用main/master不同;上游 fast-moving,pin 特定 release tag 較穩。- 緩解:production 用
brew install rtk拿穩定版,或cargo install --git ... --rev <pinned-sha>。
- 緩解:production 用
🟢 正面訊號
- 有完整
SECURITY.md(Reporting / Review Process / Critical Files / Dangerous Patterns / Disclosure Timeline) - 內建
.semgrep.yml(CI 必跑) - 內建
docs-pipeline-contract.md(規範 docs 流程) - Telemetry GDPR-compliant(opt-in only,列出每個欄位 + 為什麼)
- Apache 2.0 license(OSI 認可)
- 50k+ stars、3k+ forks、活躍維護(每天多次 rc release)
DISCLAIMER.md明列限制與保證範圍- 跨平台跨 agent(13+ tools 內建支援)
結論:日常 dev 使用安全。Enterprise 場景:(a) 用 Homebrew 或 Cargo 而非 curl-pipe-sh,(b) pin 特定 release,(c) 關掉 tee 或定期清,(d) telemetry 不啟用。
7. FAQ
Q1:RTK 會省「API 費」嗎?
不會直接省 API 費(API 費以 input + output token 數計算,rtk 只壓 shell command 輸出)。但因為 input context 變小,間接省 input token 費,且 model 不會因 context 爆掉斷話。
Q2:和 LiteLLM proxy 差在哪?
LiteLLM 是 LLM API 路由 + multi-model 統一介面,跟 RTK 完全不同層。RTK 是「shell command 層的輸出壓縮」,可與 LiteLLM 並用。
Q3:可以自己加新命令支援嗎?
可以。src/cmds/<生態>/ 內新增 module,實作 Filter trait,加 fixture (tests/fixtures/) 跟測試。rtk discover 也會自動掃 session 找潛在新命令。
Q4:Windows 原生支援?
部分。filter 都跑得起來,但 auto-rewrite hook 需要 Unix shell;原生 Windows 會退化到 CLAUDE.md injection mode(agent 看到提示但不會自動 rewrite)。建議用 WSL2。
Q5:移除?
1rtk init -g --uninstall # 移除 hook + RTK.md + settings
2cargo uninstall rtk # 或
3brew uninstall rtk
Q6:跟 Cursor / Windsurf 整合方式不同?
是。Claude Code / Gemini / Cursor / Copilot 是 hook-based(命令被 intercept);Windsurf / Cline / Kilocode / Antigravity 是 rule-based(寫 .windsurfrules 等專案規範,agent 自己讀)。後者效果依 agent 對規則的服從度而定。
Q7:跟 rtk (Rust Type Kit) 重名怎麼辦?
crates.io 上有另一個 rtk (Rust Type Kit)。cargo install rtk 會裝到那個。必須用 cargo install --git https://github.com/rtk-ai/rtk。Homebrew 沒這問題。
8. 進階技巧
8.1 Ultra-compact 模式
1rtk -u git status # ASCII icons, inline format
2# 對「自動 hook」場景:
3# ~/.config/rtk/config.toml
4# [output]
5# default_format = "ultra-compact"
8.2 自訂 exclude
1# ~/.config/rtk/config.toml
2[hooks]
3exclude_commands = ["curl", "playwright", "my-custom-tool"]
8.3 每專案 filter 覆寫
1# .rtk/filters.toml (project root)
2[git.diff]
3max_lines = 100 # 該專案 git diff 截 100 行(覆寫 global)
8.4 觀察 token saving 趨勢
1rtk gain --history --json | jq '.daily_totals'
2# 接 Grafana / 自訂 dashboard
8.5 OpenClaw / Hermes 自架整合
1# OpenClaw
2cd your-openclaw-workspace
3openclaw plugins install /path/to/rtk/openclaw
4
5# Hermes
6rtk init --agent hermes
7# 會寫 ~/.hermes/plugins/rtk-rewrite/
8.6 Tee log 整理
1# 清 30 天前 tee log
2find ~/.local/share/rtk/tee -mtime +30 -delete
3
4# 或關掉 tee
5# config.toml: [tee] enabled = false
9. 整合進其他工作流
9.1 與本 template 的 gh-tutorial-qd 串接
1# 安裝後跑教學流程會省 token
2brew install rtk
3rtk init -g
4# 之後跑 gh-tutorial-qd: <url> 流程,agent 內部 shell 操作自動壓縮
9.2 與 GBrain 並用
GBrain 是 agent 記憶 / brain;RTK 是 agent 跟 shell 之間的 token 壓縮。互補:
1# 都裝
2brew install rtk
3bun install -g github:garrytan/gbrain
4rtk init -g
5gbrain init --pglite
9.3 CI / GitHub Actions
1- name: Install RTK
2 run: curl -fsSL https://raw.githubusercontent.com/rtk-ai/rtk/refs/heads/master/install.sh | sh
3- name: Run tests via RTK
4 run: ~/.local/bin/rtk cargo test
9.4 與 Cursor / Windsurf rule-based 工具
RTK init 後會在 .windsurfrules / .kilocode/rules/ 等寫入規範,agent 依規範 prefer rtk 命令。效果依 agent 對規則的服從度。
10. 重點摘要 Checklist
- 確認 OS(macOS / Linux / WSL2 推薦;原生 Windows 限定 fallback)
-
brew install rtk(或 cargo install –git) -
rtk --version驗證 -
rtk init -g為 agent 裝 hook - 重啟 AI tool(必要)
- 跑
git status確認被自動 rewrite -
rtk gain看 token 省了多少 - 資安:用 Homebrew 而非
curl ... | sh - 資安:機密命令避免跑(會留 tee log);或關 tee
- 資安:telemetry 預設關閉,不需操作
- 進階:自訂
.rtk/filters.toml專案級 filter - 進階:CI 內整合(
--auto-patch)
11. 進一步閱讀
- 官方 README:https://github.com/rtk-ai/rtk/blob/master/README.md
- 繁中 README:https://github.com/rtk-ai/rtk/blob/master/README_zh.md
- Website / 完整 guide:https://www.rtk-ai.app/guide
- INSTALL.md:https://github.com/rtk-ai/rtk/blob/master/INSTALL.md
- 架構設計:
docs/contributing/ARCHITECTURE.md - 安全政策:
SECURITY.md - Telemetry 政策:
docs/TELEMETRY.md - Discord 社群:https://discord.gg/RySmvNF5kF
- Contributing:
CONTRIBUTING.md - Disclaimer:
DISCLAIMER.md - Reciprocal Rank Fusion (RRF; 倒數排名融合)、context engineering 相關背景閱讀(不直接由 rtk 文件提供)
- 相關專案:LiteLLM(LLM API 路由)、promptfoo(prompt 評估)
Comments