{"_id":"@capyup/pi-rtk","name":"@capyup/pi-rtk","dist-tags":{"latest":"0.1.0"},"versions":{"0.1.0":{"name":"@capyup/pi-rtk","version":"0.1.0","description":"pi integration for rtk (Rust Token Killer) — transparently rewrites bash tool calls to rtk equivalents for 60-90% token savings.","type":"module","license":"MIT","author":{"name":"capyup"},"repository":{"type":"git","url":"git+https://github.com/capyup/pi-rtk.git"},"keywords":["pi-package","pi","pi-extension","rtk","token-optimization"],"publishConfig":{"access":"public"},"pi":{"extensions":["./extensions"],"skills":["./skills"]},"peerDependencies":{"@earendil-works/pi-coding-agent":"^0.74.0"},"devDependencies":{"@earendil-works/pi-coding-agent":"^0.74.0","jiti":"^2.6.0"},"scripts":{"test":"node --test --test-reporter=spec 'test/**/*.test.mjs'","test:unit":"node --test --test-reporter=spec 'test/unit/**/*.test.mjs'","test:e2e":"node --test --test-reporter=spec 'test/e2e/**/*.test.mjs'","test:integration":"node --test --test-reporter=spec 'test/integration/**/*.test.mjs'","bench":"node benchmark/run.mjs"},"gitHead":"82d17f388725fbfbda713a8b740cb4125fd5349e","_id":"@capyup/pi-rtk@0.1.0","bugs":{"url":"https://github.com/capyup/pi-rtk/issues"},"homepage":"https://github.com/capyup/pi-rtk#readme","_nodeVersion":"25.9.0","_npmVersion":"11.12.1","dist":{"integrity":"sha512-+rWnesfcr0cM8YTSp/ZVS8D6dBuHgyHS/Q2X60Mwz4b0DgCuVkNTRzJr/c3oEyTfs7k2JShQYzB/R1B1uqZqsw==","shasum":"74abd21fc87d03012db79afbe820688d30f88b5c","tarball":"https://registry.npmjs.org/@capyup/pi-rtk/-/pi-rtk-0.1.0.tgz","fileCount":11,"unpackedSize":46373,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIEZrhmywgN43IEer+sje1tm8m9SlLq+6BvmAZOjfWsAuAiEA8Q/0v8ct3nBtjO2ItsThumqQYHUDZ9UxTAALecPAhs4="}]},"_npmUser":{"name":"capyup","email":"lucas@knowecon.com"},"directories":{},"maintainers":[{"name":"capyup","email":"lucas@knowecon.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/pi-rtk_0.1.0_1778522844534_0.17855805999574392"},"_hasShrinkwrap":false}},"time":{"created":"2026-05-11T18:07:24.465Z","0.1.0":"2026-05-11T18:07:24.720Z","modified":"2026-05-11T18:07:24.912Z"},"maintainers":[{"name":"capyup","email":"lucas@knowecon.com"}],"description":"pi integration for rtk (Rust Token Killer) — transparently rewrites bash tool calls to rtk equivalents for 60-90% token savings.","homepage":"https://github.com/capyup/pi-rtk#readme","keywords":["pi-package","pi","pi-extension","rtk","token-optimization"],"repository":{"type":"git","url":"git+https://github.com/capyup/pi-rtk.git"},"author":{"name":"capyup"},"bugs":{"url":"https://github.com/capyup/pi-rtk/issues"},"license":"MIT","readme":"# pi-rtk\n\n[![test](https://github.com/lulucatdev/pi-rtk/actions/workflows/test.yml/badge.svg)](https://github.com/lulucatdev/pi-rtk/actions/workflows/test.yml)\n\npi integration for [rtk](https://github.com/rtk-ai/rtk) (Rust Token Killer):\ntransparently rewrites `bash` tool calls to their token-optimized `rtk`\nequivalents, mirroring the behavior of rtk's own hooks for Claude Code,\nCursor, Codex, OpenCode, and others.\n\nThe extension hooks pi's `tool_call` event, feeds each bash command through\n`rtk rewrite`, and substitutes the rewritten command in place before\nexecution. Most rewrite decisions are delegated to the rtk binary's registry; pi-rtk also\nships a small local LaTeX fallback that captures verbose TeX transcripts to disk\nand returns a compact build summary. The core integration otherwise keeps the\nsame shape as rtk's official OpenCode plugin.\n\n## Measured effectiveness\n\nThe repository ships an effectiveness benchmark (`npm run bench`) that\nexecutes each task twice per rep — once raw, once through the same\n`rewriteCommand` path the live extension uses — with 5 repetitions per arm,\nstrictly serial and interleaved. The arms are deterministic on a stable\nfixture, so the 5-rep protocol serves as a check that both paths really are\ndeterministic; wall time has genuine variance and is reported separately.\n\nNumbers below are from the committed sample run in\n[`benchmark/results/sample.md`](benchmark/results/sample.md) on `rtk 0.37.2`\n/ `node 25.9.0` / `darwin/arm64`. Re-run locally with `npm run bench` for\nyour own environment.\n\n### Aggregate\n\n| metric | baseline (mean) | rtk (mean) | savings |\n|---|---:|---:|---:|\n| tokens | 117,505 | 5,856 | **95.0%** |\n\n### Per task (5 reps per arm, serial)\n\n| task | baseline tokens (mean ± σ) | rtk tokens (mean ± σ) | savings | baseline ms (median) | rtk ms (median) |\n|---|---:|---:|---:|---:|---:|\n| `git-status-log` — `git status` + `git log --oneline -30` | 112 ± 0 | 67 ± 0 | **40.2%** | 18.2 ms | 228.8 ms |\n| `git-diff` — `git diff HEAD~3 HEAD` | 48,870 ± 0 | 4,288 ± 0 | **91.2%** | 13.2 ms | 125.2 ms |\n| `ls-node-modules` — two `ls -la` subtrees | 2,345 ± 0 | 829 ± 0 | **64.6%** | 13.7 ms | 215.7 ms |\n| `find-dts` — `find node_modules -name '*.d.ts' -type f` | 65,746 ± 0 | 240 ± 0 | **99.6%** | 111.1 ms | 162.4 ms |\n| `grep-function` — `grep -rn 'function' node_modules/jiti/lib` | 432 ± 0 | 432 ± 0 | **0.0%** | 5.8 ms | 111.4 ms |\n\n### How to read this\n\n- **Token savings scale with output volume.** The two large tasks\n  (`git-diff` and `find-dts`) dominate the aggregate. `git-diff` shrinks\n  from 5,302 lines to 532, and `find-dts` collapses 3,802 file paths into\n  13 grouped lines. These are the cases rtk was built for.\n- **A 0% task is not a failure.** `grep-function` produces 20 short\n  matches with no redundancy; rtk has nothing to compress and passes\n  through verbatim. Keeping this task in the benchmark demonstrates\n  that the measurement does not cherry-pick.\n- **Wall-time overhead is ~100-200 ms per command** (rewrite decision\n  plus filter pipeline). On `find-dts` this translates to 54 ms traded\n  for 65,506 saved tokens — a large positive expected value for any\n  LLM-driven workflow, because every saved token is also saved on every\n  subsequent turn's prompt.\n- **σ = 0 for tokens/bytes/lines is expected.** Commands operate on a\n  stable fixture and rtk's filtering is deterministic; the 5-rep\n  protocol checks that, and isolates scheduler / cache / IO noise to\n  the wall-time column (σ = 0.5 to 8 ms on the sample).\n- **Fixture caveat.** `git-diff` and `git-log` reference `HEAD~3 HEAD`\n  and the 30 most recent commits, so absolute numbers drift as new\n  commits land. Order-of-magnitude savings do not change.\n\nFor methodology detail and tuning knobs (`REPS`, `WARMUP`, `BENCH_QUIET`)\nsee [`benchmark/README.md`](benchmark/README.md).\n\n## Requirements\n\n- pi (`@mariozechner/pi-coding-agent`) ≥ 0.69.0\n- `rtk` ≥ 0.23.0 on `PATH` — install via `brew install rtk`,\n  `cargo install --git https://github.com/rtk-ai/rtk`, or the prebuilt\n  binaries on the [rtk releases page](https://github.com/rtk-ai/rtk/releases).\n\n## Installation\n\n```bash\npi install git:github.com/capyup/pi-rtk        # global\npi install -l git:github.com/capyup/pi-rtk     # project-local\npi -e git:github.com/capyup/pi-rtk             # run once without installing\npi update git:github.com/capyup/pi-rtk         # pull the latest\npi remove git:github.com/capyup/pi-rtk         # uninstall\n```\n\n## What the extension does\n\n- **Hook on `tool_call`**: when the LLM calls the built-in `bash` tool,\n  the extension invokes `rtk rewrite <command>` and rewrites\n  `event.input.command` in place when rtk returns a token-optimized\n  equivalent. Same pattern as rtk's official OpenCode plugin.\n- **LaTeX build summaries**: when upstream `rtk rewrite` has no equivalent\n  for `latexmk`, `xelatex`, `pdflatex`, `lualatex`, `tectonic`, `bibtex`,\n  `biber`, `makeindex`, `makeglossaries`, or `xdvipdfmx`, pi-rtk wraps the\n  original shell command in a local runner. The full stdout/stderr transcript\n  is written to `.pi/rtk/latex/*.log`; the agent only sees status, artifact\n  lines, important errors/warnings, overfull boxes above 1pt, and the log path.\n- **System-prompt addition**: appends a short awareness block to every\n  turn's system prompt so the model knows about the bash-only scope and\n  about meta commands (`rtk gain`, `rtk discover`, …) that are not\n  auto-rewritten.\n- **`/rtk` slash command**: `/rtk`, `/rtk gain --history`,\n  `/rtk discover`, `/rtk on`, `/rtk off`, `/rtk clear`, `/rtk status`.\n  Output is shown in a transient widget so it never enters LLM context.\n- **Footer status**: shows `rtk <version>` (or `rtk off` after `/rtk off`).\n- **Skill**: a SKILL.md describing rtk usage that the model can pull in.\n\n## Scope\n\nThe auto-rewrite only fires for the `bash` tool. The built-in `read`,\n`grep`, `glob`, and `list` tools bypass the hook. When token efficiency\nmatters for file inspection or code search, prefer invoking `rtk read`,\n`rtk grep`, or `rtk find` through bash.\n\n## Configuration\n\nAll configuration is via environment variables; no settings file is read.\n\n| Variable                  | Default | Effect                                                             |\n|---------------------------|---------|--------------------------------------------------------------------|\n| `PI_RTK_DISABLED`         | unset   | If `1`, disable the extension entirely                             |\n| `PI_RTK_ASK_MODE`         | `auto`  | `auto` silently applies rtk \"ask\" rewrites; `confirm` prompts      |\n| `PI_RTK_AWARENESS`        | `1`     | Set `0` to skip the system-prompt addition                         |\n| `PI_RTK_TIMEOUT_MS`       | `2000`  | Per-call timeout for `rtk rewrite` (ms)                            |\n| `PI_RTK_QUIET`            | unset   | If `1`, suppress startup notifications                             |\n| `PI_RTK_LATEX`            | `1`     | Set `0` to disable local LaTeX transcript summarization            |\n| `PI_RTK_LATEX_LOG_DIR`    | unset   | Override the default `.pi/rtk/latex` transcript directory          |\n\n`rtk`'s own per-command opt-out also works: prefix a command with\n`RTK_DISABLED=1` (for example `RTK_DISABLED=1 git status`) to bypass the\nrewrite for that one invocation.\n\n## Failure model\n\nIf `rtk` is missing, below the minimum version, or fails for any reason,\nthe extension passes the original command through unchanged. It never\nblocks execution of the LLM's bash calls.\n\nA startup notification appears once per session if rtk is missing or too\nold (suppressible with `PI_RTK_QUIET=1`).\n\n## Relationship to upstream rtk\n\nThis package is independent of rtk and does not require any change to\nthe rtk binary. General rewrite decisions are delegated to `rtk rewrite`,\nwhich is the single source of truth defined in `src/discover/registry.rs`\nof the rtk repository. The only local exception is the LaTeX transcript\nsummarizer, which exists because TeX builds are especially verbose and already\nproduce canonical `.log` files. For non-LaTeX rewrite rules, file a PR against\nrtk itself.\n\n## Development\n\nClone the repo and install dev dependencies:\n\n```bash\ngit clone https://github.com/lulucatdev/pi-rtk.git\ncd pi-rtk\nnpm install\n```\n\n### Correctness tests (102 tests, ~0.8 s local)\n\n```bash\nnpm test                  # all suites\nnpm run test:unit         # unit tests only (57)\nnpm run test:e2e          # e2e tests only (38)\nnpm run test:integration  # requires rtk on PATH (7; auto-skipped otherwise)\n```\n\nThe test layout:\n\n- `test/unit/` — pure-function tests against the `config`, `version`,\n  `rewrite`, and `awareness` modules, using a programmable `pi.exec`\n  stub so no real `rtk` binary is required.\n- `test/e2e/` — drives the extension factory with a fake\n  `ExtensionAPI` + `ExtensionContext`, fires synthetic `session_start`,\n  `before_agent_start`, `tool_call` events, and invokes the `/rtk`\n  command to verify registered handlers end-to-end.\n- `test/integration/` — exercises the real `rtk` binary to protect\n  against drift in the `rtk rewrite` exit-code contract. Skipped\n  automatically when `rtk` is not installed.\n\nTypeScript source modules are loaded via `jiti` (matching how pi itself\nloads extensions), so no build step is needed.\n\nCI runs the full suite plus a benchmark smoke-run on\n`{ubuntu-latest, macos-latest} × Node {22, 24}`.\n\n### Effectiveness benchmark\n\n```bash\nnpm run bench               # default: 5 reps per arm\nREPS=10 npm run bench       # more reps\nWARMUP=0 npm run bench      # skip warmup\nBENCH_QUIET=1 npm run bench # suppress per-rep progress\n```\n\nReports are written to `benchmark/results/<timestamp>.md`. Timestamped\nreports are gitignored; the committed [`benchmark/results/sample.md`](benchmark/results/sample.md)\nshows the expected shape.\n\nSee [`benchmark/README.md`](benchmark/README.md) for full methodology.\n\n## License\n\nMIT.\n\n---\n\n## 中文说明\n\npi 与 [rtk](https://github.com/rtk-ai/rtk)（Rust Token Killer）的集成。\npi-rtk 通过 `tool_call` 事件钩子，在 `bash` 工具被 LLM 调用前把命令透明地\n改写为 `rtk` 等价形式。所有重写决策由 rtk 二进制内部的 `rtk rewrite` 完成，\n本扩展是薄代理，结构与 rtk 官方为 OpenCode 提供的 TypeScript 插件一致。\n\n### 实测效果\n\n仓库内置基准 `npm run bench`：每个任务跑两遍（raw vs 同样走 `rewriteCommand`\n路径），每 arm 重复 5 次，**严格串行**并交错执行（base, rtk, base, rtk, ...）\n以让系统扰动均匀分布。由于 fixture 稳定、rtk 过滤确定，tokens/bytes/lines\n的 σ 恒为 0；5 次重复用于验证\"两路都是确定的\"，wall time 方差单独列出。\n\n下表取自仓库提交的 sample 运行（`rtk 0.37.2` / `node 25.9.0` / `darwin/arm64`），\n本地 `npm run bench` 可复现。\n\n#### 聚合\n\n| 指标 | baseline（均值） | rtk（均值） | 节省 |\n|---|---:|---:|---:|\n| tokens | 117,505 | 5,856 | **95.0%** |\n\n#### 分任务（每 arm 5 次串行）\n\n| 任务 | baseline tokens (均值 ± σ) | rtk tokens (均值 ± σ) | 节省 | baseline ms (中位数) | rtk ms (中位数) |\n|---|---:|---:|---:|---:|---:|\n| `git-status-log` — `git status` + `git log --oneline -30` | 112 ± 0 | 67 ± 0 | **40.2%** | 18.2 ms | 228.8 ms |\n| `git-diff` — `git diff HEAD~3 HEAD` | 48,870 ± 0 | 4,288 ± 0 | **91.2%** | 13.2 ms | 125.2 ms |\n| `ls-node-modules` — 两处 `ls -la` 子树 | 2,345 ± 0 | 829 ± 0 | **64.6%** | 13.7 ms | 215.7 ms |\n| `find-dts` — `find node_modules -name '*.d.ts' -type f` | 65,746 ± 0 | 240 ± 0 | **99.6%** | 111.1 ms | 162.4 ms |\n| `grep-function` — `grep -rn 'function' node_modules/jiti/lib` | 432 ± 0 | 432 ± 0 | **0.0%** | 5.8 ms | 111.4 ms |\n\n#### 解读\n\n- **节省量与输出体积成正比**：`git-diff` 与 `find-dts` 两个大任务贡献了\n  绝大部分节省。`git-diff` 从 5,302 行压到 532 行，`find-dts` 把 3,802\n  条文件路径聚合为 13 行——这就是 rtk 的典型场景。\n- **0% 任务不是失败**：`grep-function` 只有 20 条短匹配，没有冗余可压，\n  rtk 原样透传。保留这个任务恰恰证明基准不是挑 cherry 的。\n- **rtk 时间成本约 100-200 ms / 命令**（重写决策 + 过滤管线）。以 `find-dts`\n  为例：多花 54 ms 换来省下 65,506 tokens；对任何 LLM 工作流这都是高正\n  期望值，因为每一条被省下的 token 在后续每一轮对话中也同样不会出现。\n- **tokens/bytes/lines 的 σ 为 0 是预期结果**：命令在稳定 fixture 上完全\n  确定，rtk 也是确定的；5 次重复用来验证这一点，并把系统噪声隔离到 wall\n  time 一列（sample 上 σ 为 0.5-8 ms）。\n- **Fixture 会漂**：`git-diff` 和 `git-log` 引用 `HEAD~3 HEAD` 与最近 30\n  条提交，绝对数会随提交演进变化；量级不变。\n\n方法学与调节参数（`REPS`、`WARMUP`、`BENCH_QUIET`）详见\n[`benchmark/README.md`](benchmark/README.md)。\n\n### 前置条件\n\n- pi（`@mariozechner/pi-coding-agent`）≥ 0.69.0\n- 系统 `PATH` 中存在 `rtk` ≥ 0.23.0\n  - macOS：`brew install rtk`\n  - 任意平台：`cargo install --git https://github.com/rtk-ai/rtk`\n  - 或下载 [release 二进制](https://github.com/rtk-ai/rtk/releases)\n\n### 安装\n\n```bash\npi install git:github.com/lulucatdev/pi-rtk        # 全局\npi install -l git:github.com/lulucatdev/pi-rtk     # 项目本地\npi -e git:github.com/lulucatdev/pi-rtk             # 临时试用（不安装）\npi update git:github.com/lulucatdev/pi-rtk         # 拉取最新\npi remove git:github.com/lulucatdev/pi-rtk         # 卸载\n```\n\n### 行为\n\n- **bash 工具自动改写**：只拦截 `bash` 工具，`read`/`grep`/`glob`/`list`\n  等 pi 自带工具不受影响。需要时请显式通过 bash 调用 `rtk read`、\n  `rtk grep`、`rtk find`。\n- **system prompt 注入**：每轮在系统提示后追加一段 awareness 文本，告知\n  模型 meta 命令（`rtk gain`、`rtk discover` 等不会被自动改写）。\n- **`/rtk` 斜杠命令**：`/rtk`（默认 `rtk gain`）、`/rtk <args>`、`/rtk on`、\n  `/rtk off`、`/rtk clear`、`/rtk status`。输出渲染在 widget，不进入 LLM\n  上下文。\n- **底栏状态**：显示 `rtk <version>` 或 `rtk off`。\n- **SKILL.md**：作为可被模型加载的技能说明。\n\n### 配置（仅环境变量）\n\n| 变量                      | 默认    | 含义                                                     |\n|---------------------------|--------|---------------------------------------------------------|\n| `PI_RTK_DISABLED`         | 未设   | 设为 `1` 完全停用本扩展                                  |\n| `PI_RTK_ASK_MODE`         | `auto` | rtk ask-rule 命中时：`auto` 静默应用，`confirm` 弹窗确认 |\n| `PI_RTK_AWARENESS`        | `1`    | 设为 `0` 不向系统提示追加 awareness                      |\n| `PI_RTK_TIMEOUT_MS`       | `2000` | `rtk rewrite` 单次超时（毫秒）                            |\n| `PI_RTK_QUIET`            | 未设   | 设为 `1` 抑制启动提示                                    |\n\nrtk 本身支持的单次旁路也仍然可用：在某条命令前加 `RTK_DISABLED=1`，例如\n`RTK_DISABLED=1 git status`，即可让该命令不被改写。\n\n### 错误降级\n\n`rtk` 缺失、版本过低、超时或任何调用失败，本扩展都会原样透传命令，绝不\n阻塞执行。\n\n### 与上游 rtk 的关系\n\n本仓库独立于 rtk，无需对 rtk 二进制做任何修改。所有重写决策都由\n`rtk rewrite` 完成，规则维护在 rtk 仓库的 `src/discover/registry.rs`。\n要新增或调整规则，应向 rtk 上游提 PR。\n\n### 开发\n\n```bash\ngit clone https://github.com/lulucatdev/pi-rtk.git\ncd pi-rtk\nnpm install\n\nnpm test                  # 正确性测试（102 条，本机 ~0.8 s）\nnpm run test:unit         # 仅 unit（57 条）\nnpm run test:e2e          # 仅 e2e（38 条）\nnpm run test:integration  # 依赖真实 rtk，无 rtk 时自动跳过（7 条）\n\nnpm run bench             # 效果基准（5 任务 × 5 次 × 2 arm，本机 ~8 s）\n```\n\nCI 矩阵 `{ubuntu-latest, macos-latest} × Node {22, 24}`，每个 job 完整跑\n正确性测试并烟测 benchmark 脚本。\n\n### 协议\n\nMIT。\n 协议\n\nMIT。\n","readmeFilename":"README.md","_rev":"1-dd967d9570c426ac67ffed229578fd42"}