{
  "markdown": "# Token Pilot\n\n**Token-efficient AI coding, enforced.** Cuts context consumption in AI coding assistants by up to **90%** without changing the way you work.\n\n> **Why it matters more now:** as frontier models move up in price, the tokens you *don't* spend reading code are worth more, not less. The savings are in tokens; the value is in tokens × price. Token Pilot keeps the expensive main thread lean so the premium model spends its budget on reasoning, not on re-reading files.\n\nThree layers, each useful on its own, stronger together:\n\n1. **MCP tools** — structural reads (`smart_read`, `read_symbol`, `read_for_edit`, …). Ask for an outline or load one function by name instead of the whole file.\n2. **PreToolUse hooks** — intercept heavy native tool calls (`Read` on large files, recursive `Grep`, unbounded `git diff`) and redirect to token-efficient alternatives.\n3. **`tp-*` subagents** — Claude Code delegates with MCP-first behaviour and tight response budgets.\n\n## How It Works\n\n```\nTraditional:  Read(\"user-service.ts\")  →  500 lines  →  ~3000 tokens\nToken Pilot:  smart_read(\"user-service.ts\")  →  15-line outline  →  ~200 tokens\n              read_symbol(\"UserService.updateUser\")  →  45 lines  →  ~350 tokens\n              After edit: read_diff(\"user-service.ts\")  →  ~20 tokens\n```\n\nFiles under 200 lines are returned in full — zero overhead for small files.\n\n### Benchmarks\n\nMeasured on public open-source repos. Files ≥50 lines only:\n\n| Repo | Files | Raw Tokens | Outline Tokens | Savings |\n|------|------:|----------:|--------------:|--------:|\n| [token-pilot](https://github.com/Digital-Threads/token-pilot) (TS) | 55 | 102,086 | 8,992 | **91%** |\n| [express](https://github.com/expressjs/express) (JS) | 6 | 14,421 | 193 | **99%** |\n| [fastify](https://github.com/fastify/fastify) (JS) | 23 | 50,000 | 3,161 | **94%** |\n| [flask](https://github.com/pallets/flask) (Python) | 20 | 78,236 | 7,418 | **91%** |\n| **Total** | **104** | **244,743** | **19,764** | **92%** |\n\n> `smart_read` outline savings only. Real sessions additionally benefit from session cache, `read_symbol`, and `read_for_edit`. Reproduce: `npx tsx scripts/benchmark.ts`.\n\n## Quick Start\n\n```bash\nnpx -y token-pilot init\n```\n\nCreates (or merges into) `.mcp.json` with `token-pilot` + [`context-mode`](https://github.com/mksglu/claude-context-mode), then prompts to install `tp-*` subagents. Restart your AI assistant to activate.\n\n## What You Get\n\n- **25 MCP tools** — structural reads, symbol search, git analysis, module routing, session analytics → [tools reference](docs/tools.md)\n- **PreToolUse hooks** — block heavy `Grep`/`Bash`/`Read` calls; redirect to efficient alternatives → [hooks & modes](docs/hooks.md)\n- **25 `tp-*` subagents** (Claude Code only) — MCP-first delegates with haiku/sonnet model tiers and budget enforcement → [agents reference](docs/agents.md)\n- **Tool profiles** — trim advertised `tools/list` to save ~2 k tokens per session → [profiles & config](docs/configuration.md)\n\n## Client Support Matrix\n\n| Client | MCP tools | PreToolUse hooks | `tp-*` subagents |\n|--------|:---------:|:----------------:|:----------------:|\n| Claude Code | ✅ | ✅ | ✅ |\n| Cursor | ✅ | ✅ | ❌ |\n| Codex CLI | ✅ | ✅ | ❌ |\n| Gemini CLI | ✅ | ✅ | ❌ |\n| Cline (VS Code) | ✅ | ✅ | ❌ |\n| Antigravity | ✅ | ✅ | ❌ |\n\nManual config snippets for each client → [installation guide](docs/installation.md)\n\n## Enforcement Mode\n\n`TOKEN_PILOT_MODE` controls how aggressively Token Pilot redirects heavy native tool calls:\n\n| Value | Behaviour |\n|-------|-----------|\n| `advisory` | Allow all — hooks pass through, advisory notes only |\n| `deny` *(default)* | Block heavy `Grep`/`Bash` patterns; intercept large `Read` calls |\n| `strict` | Deny + auto-cap MCP output (`smart_read` ≤ 2 000 tokens, `find_usages` → list mode, `smart_log` → 20 commits) |\n\n```bash\nTOKEN_PILOT_MODE=strict npx token-pilot\n```\n\n→ [Full hook & mode docs](docs/hooks.md)\n\n## Ecosystem\n\nToken Pilot owns **input** tokens — the stuff Claude reads from files, git, search. The other half of a session (what Claude *writes* back, how it executes code, how it remembers state across days) is owned by separate tools. They compose cleanly:\n\n| Tool | Owns | Typical savings |\n|------|------|----------------:|\n| **Token Pilot** | code reads, git, search | 60-90% input |\n| **[caveman](https://github.com/JuliusBrussee/caveman)** | Claude's response prose (terse-speak skill) | ~75% output |\n| **[ast-index](https://github.com/defendend/Claude-ast-index-search)** | the structural indexer Token Pilot rides on | foundation |\n| **[context-mode](https://github.com/mksglu/claude-context-mode)** | sandboxed shell / python / js execution | 90%+ on big stdout |\n\nA session that pairs `token-pilot` + `caveman` typically hits **~85-90% total reduction** — each cuts a different half, no overlap. Install what you need; none of them assume the others are present.\n\n→ [full ecosystem map](docs/ecosystem.md)\n\nRules of thumb: read code → `smart_read`/`read_symbol`; execute code with big output → context-mode `execute`; bash-only agent → `ast-index` CLI. Never copy the whole stack into `CLAUDE.md` — Token Pilot's `doctor` warns when `CLAUDE.md` exceeds 60 lines.\n\n## Supported Languages\n\nTypeScript, JavaScript, Python, Go, Rust, Java, Kotlin, C#, C/C++, PHP, Ruby. Non-code (JSON/YAML/Markdown/TOML) gets structural summaries. Regex fallback handles most other languages.\n\n## Update / New Machine\n\n**Claude Code (plugin — recommended):**\n```bash\n# Install on a new machine:\nclaude plugin marketplace add https://github.com/Digital-Threads/token-pilot\nclaude plugin install token-pilot@token-pilot\n\n# Update to latest:\nclaude plugin update token-pilot\n```\n\n**Other clients (Cursor, Codex, Cline, …):**\n```bash\n# Install on a new machine:\nnpx -y token-pilot init\n\n# Update to latest — npx always pulls fresh, just restart your client.\n# Or if installed globally:\nnpm i -g token-pilot@latest\nnpx token-pilot install-hook\nnpx token-pilot install-agents --scope=user --force\n```\n\n## Tips for Claude Code 2.1.139+\n\nThe May 2026 Claude Code update changed a few things that affect how\ntoken-pilot is invoked. Nothing breaks on older versions — these are\nquality-of-life notes for the newer ones.\n\n- **Run a tp-\\* agent directly without the `plugin:` prefix.**\n  `claude --agent tp-debugger \"fix the stack trace\"` now works the same\n  as `--agent token-pilot:tp-debugger`. The Task tool dispatcher\n  resolves the short name automatically.\n\n- **Cold ast-index calls — raise `MCP_TOOL_TIMEOUT`.**\n  The first `find_usages` / `outline` / `read_symbol` on a large repo\n  triggers an index build. Default per-MCP-tool timeout (60 s) is\n  enough for ~50k-file repos; bigger ones benefit from\n  `MCP_TOOL_TIMEOUT=120000` in `~/.claude/settings.json`. Subsequent\n  calls hit the cache and return in ~50 ms.\n\n- **Background sessions with `--mcp-config`.**\n  Dispatching a worker via `claude agents` or `--bg` with\n  `--mcp-config /path/to/other.json` swaps the MCP set for that\n  session. If `token-pilot` is not in the override config, MCP tools\n  (`smart_read`, `find_usages`, …) are unavailable in that worker\n  even though the hooks (Read / Edit / Bash / Grep / Task) still\n  fire — hooks are project-level, MCP tools are session-level. Add\n  `token-pilot` to the override config or skip `--mcp-config`.\n\n- **`claude plugin details token-pilot`.**\n  Shows the projected per-turn token cost, the hook event names, and\n  the MCP server entry. The skill list, the agent list, and the LSP\n  list are all auto-discovered from the canonical sub-folders.\n\n## Power-user — undocumented Claude Code features that pair with token-pilot\n\nThese fields come from reverse-engineering `@anthropic-ai/claude-code@2.1.87`\nsource (see the May 2026 Habr write-up). They work today but are\nnot in the official Claude Code docs, so use at your own risk.\n\n### Persistent agent memory (`memory: project`)\n\nEvery relevant tp-\\* agent (onboard, debugger, pr-reviewer,\nhistory-explorer, audit-scanner) now ships with `memory: project`\nin its frontmatter. Claude Code persists the agent's working notes\nin the project so the agent gets faster on repeat invocations —\n`tp-onboard` remembers your layout, `tp-pr-reviewer` remembers your\nflagged patterns, etc. v0.35.0+.\n\n### Required MCP gating (`requiredMcpServers`)\n\nEvery tp-\\* agent declares `requiredMcpServers: [\"token-pilot\"]`.\nClaude Code refuses to load the agent when the MCP server isn't\nconfigured, so a stale install never produces a \"tools not found\"\nloop. v0.35.0+.\n\n### Bootstrap-once hook (`once: true`)\n\nThe plugin ships a SessionStart hook flagged `once: true` —\nClaude Code runs it once per project then auto-removes the entry.\nIt surfaces friendly hints when `install-agents` or\n`install-ast-index` hasn't been run yet. v0.35.0+.\n\n### Async telemetry (`async: true`)\n\nPostToolUse hooks (Bash, Task) are marked `async: true` so they\nno longer add wall-clock to the hot path — telemetry writes fire\nin the background.\n\n### Auto-mode permissions (user-side)\n\nIf you want full auto-approval for safe commands, the YOLO\nclassifier reads natural-language environment descriptions:\n\n```json\n{\n  \"autoMode\": {\n    \"allow\": [\"Bash(git status)\", \"Bash(npm test)\", \"Read\", \"Grep\"],\n    \"soft_deny\": [\"Bash(git push *)\", \"Bash(rm *)\", \"Write(.env)\"],\n    \"environmentDescription\":\n      \"This is a development laptop. Read-only ops are safe; deny anything touching credentials or production.\"\n  }\n}\n```\n\ntoken-pilot's enforcement still runs on top (raw Read on large files\nis denied first, regardless of autoMode).\n\n### Permission rule syntax cheat-sheet\n\n```\nBash(npm *)                       # wildcard after \"npm \"\nBash(git commit *)                # specific subcommand\nRead(*.ts)                        # extension\nRead(src/**/*.ts)                 # recursive + extension\nWrite(src/**)                     # recursive all files\nmcp__token-pilot                  # all token-pilot MCP tools\nmcp__token-pilot__smart_read      # one specific MCP tool\n```\n\n`*` matches inside word boundaries (shell-glob); `**` is recursive.\nThe `if` field on hooks uses the same syntax.\n\n### Experimental: transparent Read rewrite\n\nSet `TOKEN_PILOT_HOOK_REWRITE=1` to swap the \"deny + suggest\" Read\nhook behaviour for an `updatedInput` rewrite — Claude Code's\nundocumented field that silently bounds the Read to its first 200\nlines instead of bouncing the call. The structural summary still\nrides along in `additionalContext`. Default OFF because the field\nis undocumented and may change.\n\n### Experimental: SubagentStop budget feedback (CC 2.1.163+)\n\nEvery subagent completion already lands a task-telemetry row via the\n`SubagentStop` hook (that's how `stats --tasks` knows what you\ndispatched). With `TOKEN_PILOT_SUBAGENT_FEEDBACK=1` the same hook also\nreturns `additionalContext` — when a `token-pilot workflow` fan-out is\nat ≥90 % of its token ceiling, each completing agent gets a wind-down\nnote so a hundred-agent `/workflow` run stops before blowing the\nbudget.\n\n**Requires Claude Code 2.1.163+.** Returning `additionalContext` from\n`SubagentStop` is only honoured there; older Claude Code labels it a\nhook error. Default OFF for that reason — enable only once\n`claude --version` reports 2.1.163 or later.\n\n## What's new for Claude Code 2.1.151+\n\nThese notes are about behaviour you'll see automatically once you\nupdate both Claude Code and `token-pilot@latest`. No extra\nconfiguration required.\n\n### Session title badge (`[TP] Nk saved`)\n\nThe SessionStart hook now sets the window/tab title to the cumulative\ntoken savings for the current project, using Claude Code 2.1.152's\n`hookSpecificOutput.sessionTitle` field. You'll see a badge like\n`[TP] 1.2M saved` in the title bar so you can confirm at a glance\nthat the plugin is doing its job.\n\n### Hardened skills (`disallowed-tools`)\n\nThe three bundled skills (`guide`, `install`, `stats`) declare\n`disallowed-tools` (Claude Code 2.1.152+) so a runaway model can't\nissue `Write` / `Edit` / `Task` while the skill is on display. The\ninstall skill keeps `Bash` because it has to run\n`npx token-pilot install-ast-index`; the other two have Bash\ndisallowed too.\n\n### Auto mode on third-party providers\n\nClaude Code 2.1.158 opened auto mode to Bedrock / Vertex / Foundry\non Opus 4.7 + 4.8. If you're on one of those, opt in with\n`CLAUDE_CODE_ENABLE_AUTO_MODE=1`. token-pilot's deny-Read /\ndeny-Bash gates still run on top — auto mode never bypasses them.\n\n### Opus 4.8 as fast-mode default\n\nClaude Code 2.1.154 made Opus 4.8 the default for high effort. The\ntp-* agents that already declared `model: haiku` keep their cheaper\ntier (90 %+ of the agent roster); the few sonnet/opus-tier ones\nride the upgrade automatically.\n\n## Fleet workflows (v0.38.0)\n\nWhen you fan a task across many subagents — via Claude Code's\n`/workflow`, the Agent tool, or your own orchestration — token-pilot\ncan treat the whole run as one budgeted, telemetry-tagged unit.\n\ntoken-pilot **owns** the workflow boundary, so this works regardless\nof whether Claude Code propagates a workflow id. You wrap the batch:\n\n```bash\n# Start a workflow — prints an export line you eval into your shell\neval \"$(token-pilot workflow start \"review every PR from last sprint\" --budget=2000000)\"\n\n# ...now run your fan-out work. Every hook event is tagged with the\n#    workflow id automatically (TOKEN_PILOT_WORKFLOW_ID is set).\n\ntoken-pilot workflow status      # live budget + task counts\ntoken-pilot workflow list        # all recorded workflows\ntoken-pilot workflow end         # stamp it finished + print summary\n```\n\nWhile a workflow is active:\n\n- Every `event:\"task\"` / `denied` / `diagnostic` row in\n  `hook-events.jsonl` carries `workflow_id`, so you can slice one\n  fan-out run out of the global log.\n- The PreToolUse:Task hook watches the token ceiling. At ≥90 % it\n  appends a wind-down note to its routing advice (\"finish in-flight\n  work rather than starting new branches\") and logs a\n  `workflow_near_budget` diagnostic — visible in `workflow status`.\n  Dispatch is never hard-blocked on budget (a half-finished fan-out\n  is worse than a small overrun).\n- The window title switches to `[TP] wf · N tasks · X%` so a long run\n  shows live progress.\n\nClaude Code's own `/workflow` (2.1.154+) does **not** expose a\nper-workflow id env var to subagents (verified against the 2.1.161\nbundle — it has only a `CLAUDE_CODE_WORKFLOWS` feature flag). So\ntoken-pilot's workflows are independent: they rely on our own\n`TOKEN_PILOT_WORKFLOW_ID`. If CC adds a per-workflow env var later,\n`activeWorkflowId()` already probes for it — no config change needed.\n\n## Troubleshooting\n\n```bash\nnpx token-pilot doctor          # diagnose: ast-index, config, upstream drift\n# \"ast-index not found\"  →  npx token-pilot install-ast-index\n# \"hooks not firing\"     →  restart your AI assistant\n```\n\n## Credits\n\nBuilt on [ast-index](https://github.com/defendend/ast-index) · [@ast-grep/cli](https://ast-grep.github.io/) · [MCP SDK](https://github.com/modelcontextprotocol/typescript-sdk) · [chokidar](https://github.com/paulmillr/chokidar)\n\n## License\n\nMIT\n",
  "bytes": 15102,
  "sha": "1a8b8ceede20a2521bf3776f353b119ad5d3ea86a53900edc387aab79c6e2e0a",
  "repo_slug": "digital-threads/token-pilot",
  "fonte": "repo",
  "truncated": false,
  "api": "https://agentalog.com/api/listings/mcp_io_github_digital_threads_token_pilot_87739947/readme"
}