blog.dopana

Quay lại

AI coding agent không tốn token vì suy luận. Nó tốn vì output cargo test, spam git status, và đọc cùng một file năm lần.

Đó là bài toán sqz ↗ giải. Một binary Rust duy nhất nén tool output trước khi vào context của model. Không gọi LLM, chạy offline hoàn toàn, khôi phục byte-exact bằng sqz expand.

Số liệu thật từ repo: 3.003 lần nén, tiết kiệm 178.442 token, giảm trung bình 24.7%, lên tới 92-96% với output model đã có.

Vì sao quan trọng#

Mỗi turn agent gửi lại toàn bộ history. Log test 1.200 token không trả một lần — trả mọi turn sau đó cho tới khi compaction. Thêm prompt caching thì bài toán tiền bạc tinh tế hơn, nhưng hướng rõ: output ồn ào làm ngắn session, tăng chi phí, đẩy reasoning hữu ích ra khỏi cửa sổ context.

[!NOTE] Giảm token ≠ giảm bill 1:1. Với prompt caching, context lặp lại chỉ bill ~10%. sqz stats --cost mô hình hóa điều này một cách trung thực.

Giải thích như bạn 10 tuổi (ELI5): agent xếp vali (context window) mỗi chuyến đi. Hiện tại nó nhồi cả đồ bẩn — test pass đầy đủ, git status không đổi, file đọc lặp. sqz là người bạn gấp gọn, bỏ đồ trùng, dán giấy nhớ: “áo xanh đã có trong vali, xem ngăn 3”.

git, cargo, pytest, docker...lệnh lạcó, còn trong contextchưacókhôngAgent gọi tool: git status, cargotest, cat filesqz PreToolUse hookFormatter riêng cho lệnh?Giữ failure, assertion, file:line.Bỏ nhiễuPipeline chung: gộp dòng lặp,gọn bảngThấy trước đây? Tra SHA-256Trả về §ref:HASH§ 13 tokenStack trace / secret / migration?Safe mode: 0% nén,passthroughOutput đã nén tới model

Cái gì nén, cái gì không#

Nén:

  • Shell output — 45+ formatter cho 12 hệ sinh thái: git, cargo, npm/pnpm/yarn/bun, pytest, ruff, mypy, go test (kể cả stream -json), docker/podman, kubectl, aws, terraform, gcloud, gradle, maven, xcodebuild, adb logcat, dotnet, gh, grep/rg, tree, curl…
  • JSON — strip null, bỏ field debug, flatten, gộp mảng, mã hóa TOON
  • Log — gộp dòng lặp (max_repeated_lines = 3 mặc định)
  • Test output — chỉ giữ failure qua state-machine parser cho Rust, Go, Python, JS, JVM

Không bao giờ đụng:

  • Source code, stack trace, error message, secret → safe mode, nén 0%
  • Prompt của bạn và response của AI → thuộc về agent framework, không phải sqz

[!TIP] Mọi kết quả nén đều khôi phục byte-exact được: sqz expand <ref>.

Con số#

Nén đơn lệnh (cargo test -p sqz-engine benchmarks):

Nội dungTrướcSauTiết kiệm
Dòng log lặp1486258%
Mảng JSON lớn25914245%
JSON API response645317%
Git diff615412%
Văn bản/docs1241212%
Stack trace (safe mode)82820%

Mức session với dedup (nơi sqz thắng lớn):

Lặp lạiKhông sqzCó sqzTiết kiệm
Chạy lại git status không đổi1551392%
Dòng 41-80 của file 200 dòng đã đọc3051695%
Cùng output cargo test, không gì đổi3031396%

Ví dụ từ README:

cat auth.py (500 dòng):    4.000 token     4.000 token  (source giữ nguyên)
cargo test (1 fail):       1.200 token       120 token  (failure + assertion + file:line)
sed -n '40,80p' auth.py:     330 token        18 token  (§ref:…:L40-80§)
git status, không đổi:       160 token        13 token  (§ref:…§)
─────────────────────────────────────      ─────────────
Tổng:                      5.690 token     4.151 token  (tiết kiệm 27%, không mất gì)
text

Điểm tinh tế tác giả nêu: đọc lại nguyên file hiếm hơn lời đồn (1/542 lần đọc trong 92 session của một user). Lặp lại thật là output lệnh không đổi, đoạn dòng, và đọc lại sau sửa nhỏ — mỗi loại có kiểu reference riêng.

Cài trong 2 phút#

install.sh
# macOS / Linux (prebuilt, không cần compiler)
curl -fsSL https://raw.githubusercontent.com/ojuschugh1/sqz/main/install.sh | sh

# Mọi nền tảng qua npm
npm install -g sqz-cli

# macOS qua Homebrew
brew tap ojuschugh1/sqz
brew install sqz

# Từ source
cargo install sqz-cli sqz-mcp
bash

Rồi:

init
sqz init --global   # mọi project (~/.claude/settings.json merge)
# hoặc
sqz init            # chỉ project hiện tại
sqz init --only opencode,codex  # giới hạn client
sqz init --skip cursor,windsurf # trừ các client này
sqz doctor          # kiểm tra chuỗi: binary, DB, hook, lần nén gần nhất
bash

[!WARNING] sqz init parse opencode.jsonc qua JSON parser nên mất comment. Muốn giữ comment, cài tay: sqz print-opencode-plugin > ~/.config/opencode/plugins/sqz.ts, rồi thêm entry sqz-mcp bằng tay.

Thử trước khi gắn hook: replay counterfactual#

Đã dùng Claude Code hay Kiro? Replay transcript có sẵn cục bộ, không upload:

discover
sqz discover --replay
# Sessions replayed: 24
# Tool outputs: 43
# Tokens (original): 116,598 → compressed: 92,560
# Estimated avoidable: 24,038 tokens (20.6%)
bash

Mỗi session replay trên cache trắng riêng, nên dedup liên session không bao giờ thổi phồng số.

CLI cheat sheet#

cli
sqz compress "text"            # hoặc pipe stdin
sqz compress --no-cache        # bỏ dedup, output đầy đủ
sqz expand a1b2c3d4            # prefix match, hoặc dán full §ref:…§
sqz gain                       # bar chart theo ngày, 7 ngày gần nhất
sqz gain --days 30 --project . # 30 ngày, project hiện tại
sqz stats                      # tích lũy + tín hiệu regret
sqz stats --cost               # $ theo mô hình prompt-cached billing
sqz stats --breakdown          # top lệnh ngốn token
sqz recall "connection refused" # tìm FTS5 trên mọi thứ đã nén
sqz resume                     # bơm lại context sau compaction
sqz compact                    # trục xuất chủ động: --strategy keep_recent|keep_relevant|keep_errors
sqz vizit                      # dashboard live kiểu htop
sqz discover                   # lệnh nào nén kém nhất
bash

Thoát hiểm dedup (vài model như GLM 5.1 loop với §ref§):

dedup-off
echo "..." | sqz compress --no-cache
export SQZ_NO_DEDUP=1          # tắt toàn cục
export SQZ_REF_TTL_SECS=300    # rút ngắn cửa sổ ref (mặc định 1800, 0 = tắt)
bash

Cơ chế nén: 6 tầng#

  1. Formatter riêng từng lệnh — cargo test giữ test fail + assertion + file:line. git status thành summary gọn. Lệnh lạ rơi xuống pipeline chung — không output nào bị bỏ sót.
  2. Table compactor — gộp padding trong ps aux, netstat, DB CLI thành separator 2-space. Detector nghiêm: dòng indent, code, YAML, JSON không bao giờ match.
  3. Structural summary — code → import + signature + call graph (~giảm 70%). Model thấy kiến trúc, không thấy nhiễu implementation.
  4. Dedup cache — hash SHA-256, lưu SQLite. Giống byte → §ref:HASH§ 13 token. Đoạn dòng của file đã biết → §ref:HASH:L40-80§. Đọc lại sau sửa nhỏ → chỉ dòng đổi. Ref sống 30 phút (SQZ_REF_TTL_SECS), reset khi compaction.
  5. JSON pipeline — strip null → bỏ field debug → flatten → gộp mảng → TOON (format gọn lossless).
  6. Safe mode — phân tích entropy phát hiện stack trace, secret, migration → nén 0%, passthrough.

Độ trễ sub-millisecond (p99 < 5ms tới 100KB), lookup SQLite ~0.1ms. Không đáng kể so với inference LLM.

Tool hỗ trợ#

ToolTích hợpCài
Claude Code / Cursor / Windsurf / ClinePreToolUse hook (trong suốt)sqz init
Gemini CLIBeforeTool hooksqz init
KiroSteering + MCPsqz init
OpenCodeTypeScript pluginsqz init
Codex / ZedAGENTS.md + MCPsqz init
Copilot CLIpreToolUse hooksqz init
Copilot coding agent (CI)repo hook, tự bootstrapsqz init --ci + commit
Mọi MCP serversqz-mcp proxy -- <server>nén tool result + tools/list
VS Code / JetBrains / Chrome / FirefoxExtensionMarketplace

Ví dụ MCP proxy — bọc mọi stdio server:

mcp.json
{
  "mcpServers": {
    "github": {
      "command": "sqz-mcp",
      "args": ["proxy", "--", "npx", "-y", "@modelcontextprotocol/server-github"]
    }
  }
}
json

Flag: --lazy-tools (mô tả một câu + sqz_tool_help theo nhu cầu — vài server đốt 10-40k token chỉ cho tools/list), --no-desc, --no-cache. Proxy chèn tool sqz_expand để agent khôi phục gốc byte-exact.

Kế toán trung thực: cost và regret#

Hai tín hiệu tool nén khác thường lờ đi:

  • sqz stats --cost — đô la theo billing prompt-cached (cache write ×1.25 một lần, cache read ×0.10 mỗi turn). Giả định in ra hết, override được qua --price-in, --reread-turns, --cache-write-mult, --cache-read-mult. Cố tình保守 (conservative).
  • Regret signal trong sqz stats — re-run nhanh (output giống byte trong 2 phút = lần lặp chẳng mua được gì) và ref expand (§ref§ phải hồi về byte = model cần full content). Lệnh nào hiện hoài thì formatter cần sửa — file issue.

Thiết kế tránh failure mode đã đo trong arXiv:2607.12161 ↗: deterministic + query-agnostic (không invalidate provider prompt cache), chỉ đụng tool output mới (history không viết lại), lệnh pipe/redirect không intercept, cổng net-win 16 token bỏ qua nén không đáng.

Ví dụ thực tế: gắn vào session#

session
# 1. xem đáng ra tiết kiệm bao nhiêu
sqz discover --replay

# 2. cài global
sqz init --global
sqz doctor

# 3. làm việc bình thường, rồi đo
sqz gain
sqz stats --breakdown

# 4. recall nhanh hơn chạy lại
sqz recall "Failed to connect"
sqz expand 3f9a1c05e2d84b17
bash

Isolation DB theo project với direnv:

.envrc
export SQZ_DB_PATH="$PWD/.sqz/sessions.db"
bash

Mọi mặt đều tôn trọng: shell hook, stats/gain/expand, MCP server (env trong config MCP). Thư mục cha tự tạo mode 0700.

Cấu hình#

~/.sqz/presets/default.toml
[preset]
name = "default"
version = "1.0"

[compression.condense]
enabled = true
max_repeated_lines = 3

[compression.strip_nulls]
enabled = true

[budget]
warning_threshold = 0.70
default_window_size = 200000
toml

Riêng tư#

Zero telemetry, không crash report, offline hoàn toàn, chạy được air-gap. Stat trong ~/.sqz/sessions.db (SQLite FTS5). Không gì rời máy.

Khi nào không nên dùng sqz#

  • Cần log verbatim để audit — dùng --no-cache hoặc đường safe-mode, hoặc expand sau.
  • Model không parse được token §ref§ — tắt dedup (SQZ_NO_DEDUP=1).
  • Output tí hon dưới cổng net-win — sqz đã tự bỏ qua (ngưỡng 16 token).

Kết luận#

sqz đứng đúng biên: lúc tool thực thi, không phải viết lại prompt, không adapter riêng từng model. Một sqz init bao mọi agent framework, core Rust deterministic giữ p99 dưới 5ms, dedup biến lặp lại thành ref 13 token.

Bắt đầu bằng sqz discover --replay — nếu transcript của chính bạn hiện 20%+ token tránh được, hãy gắn hook.

Tài liệu tham khảo#