tokensafe 4.5.0 → 4.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/bin/agy-tokens +10 -1
  3. package/bin/tokensafe.js +2 -1
  4. package/hooks/claude_code_hook.py +38 -126
  5. package/hooks/cursor_hook.py +45 -1
  6. package/hooks/kimi_hook.py +46 -90
  7. package/hooks/pre_invocation.py +23 -4
  8. package/hooks/pre_tool_use.py +40 -22
  9. package/hooks/session_start.py +28 -10
  10. package/hooks/zcode_hook.py +95 -0
  11. package/hooks.json +1 -1
  12. package/kimi.plugin.json +17 -1
  13. package/mcp_config.json +10 -4
  14. package/package.json +1 -1
  15. package/plugin.json +1 -1
  16. package/rules/AGENTS.md +24 -24
  17. package/server.json +3 -3
  18. package/skills/token-optimizer/SKILL.md +61 -86
  19. package/skills/token-optimizer/references/mcp-tools.md +32 -132
  20. package/src/adapter_core.py +231 -7
  21. package/src/batch_editor.py +73 -22
  22. package/src/batch_search.py +31 -11
  23. package/src/burn_monitor.py +581 -0
  24. package/src/cache_normalizer.py +2 -0
  25. package/src/cli.py +34 -4
  26. package/src/compactor.py +1 -1
  27. package/src/dashboard.py +17 -9
  28. package/src/diff_slicer.py +1 -1
  29. package/src/distiller.py +11 -1
  30. package/src/environment_auditor.py +30 -6
  31. package/src/format_parsers/ansi.py +1 -1
  32. package/src/format_parsers/lockfiles.py +22 -17
  33. package/src/format_parsers/tabular.py +6 -3
  34. package/src/fts_index.py +26 -20
  35. package/src/governor.py +2 -2
  36. package/src/graph_engine.py +31 -9
  37. package/src/guard.py +3 -3
  38. package/src/image_downscale.py +26 -0
  39. package/src/installer.py +61 -48
  40. package/src/license_manager.py +49 -16
  41. package/src/live_relay.py +9 -8
  42. package/src/mcp_server.py +487 -48
  43. package/src/metrics.py +78 -13
  44. package/src/mistakes.py +4 -2
  45. package/src/paths.py +4 -1
  46. package/src/proxy.py +302 -123
  47. package/src/result_ledger.py +39 -1
  48. package/src/schema_slicer.py +40 -18
  49. package/src/scoped_search.py +66 -23
  50. package/src/skeletonizer.py +22 -11
  51. package/src/slicer.py +6 -4
  52. package/src/stash.py +37 -7
  53. package/src/superseded.py +42 -23
  54. package/src/syntax_guard.py +2 -0
  55. package/src/team_cache.py +3 -0
  56. package/src/telemetry_sync.py +96 -54
  57. package/src/thinking_fold.py +50 -12
  58. package/src/transcript_analyzer.py +270 -68
  59. package/src/treesitter_backend.py +2 -0
  60. package/src/type_slicer.py +60 -18
  61. package/src/version_checker.py +1 -1
  62. package/src/web_reader.py +55 -22
@@ -20,88 +20,63 @@ folds multi-turn conversation history, guards against secret leaks, and standard
20
20
 
21
21
  1. **ZERO RAW TERMINAL GREP / FIND (HARD-BLOCKED & REPLACED BY `scoped_search`)**:
22
22
  - Strictly NEVER run `grep`, `egrep`, `ripgrep`, or `find` in `run_command` on source code files (`.ts`, `.tsx`, `.py`, `.js`, `src/`, `views/`, `components/`).
23
- - Raw code searches via bash burn thousands of context tokens and are blocked by **TokenSafe Guard** (`decision: deny`).
24
- - **Mandatory Search Tool (`scoped_search`)**: ALWAYS call `tokensafe:scoped_search(query, path=".", scope="code")` to search for text, identifiers, or symbol definitions across unknown files (-90% tokens). The `path` parameter specifies the search directory or project root (e.g. `"."`, `"./src"`). The `scope` parameter filters files (`"code"`, `"config"`, `"all"`), a file extension (`"go"`, `"ts"`), or a subfolder path (`"internal/promo"`).
25
-
26
- 2. **SYMBOL & COMPONENT EXTRACTION (`smart_read_file`)**:
27
- - When locating or reading any function, component, class, or handler (e.g. `<LuckyWheelTab>`, `areSectorEqual`, `useWallet`), ALWAYS call `tokensafe:smart_read_file` with `path` (supports relative paths, e.g. `"src/service.ts"`) and `symbol`.
28
- - **1-Hop Dependency Modes (`dep_mode` & `include_deps`)**: By default (`dep_mode="signature"`), `smart_read_file` returns the full target implementation plus compact 1-line 1-hop dependency signatures and collapsed imports (-95%+ tokens). Pass `"dep_mode": "full"` when full 1-hop dependency bodies are required, or `"include_deps": false` for 0-hop surgical isolation.
29
- - **Cache Pointer Recovery (`force_full`)**: When repeating an unchanged read in the same MCP session, `smart_read_file` may return a compact pointer referencing the prior output. Reuse that earlier output; only pass `"force_full": true` if your context was compacted or you are a fresh subagent lacking prior turns.
30
- - **Multi-Symbol Bundles (`smart_bundle`)**: When you need 3+ related symbols across several files, call `tokensafe:smart_bundle(targets=[{path, symbol}])` ONCE instead of chained `smart_read_file` calls (max 8 targets). It merges per-file skeletons, deduplicates shared import/type lines into one block, and unifies 1-hop dependency signatures — one roundtrip instead of many.
31
- - **Schema Auto-Slicing**: OpenAPI/Swagger, Prisma, GraphQL and SQL files bypass AST skeletonization. Pass the spec path (`/users/{id}`), Prisma model, GraphQL type, or SQL table as `symbol` for a targeted slice with 1-hop references; an empty `symbol` returns a compact overview (paths/models/types/tables index) instead of a 20k-50k token dump.
32
- - **Result**: Preserves the exact target definition while folding surrounding inert code into clean 1-line signatures without docstrings (-85% to -98% tokens).
33
-
34
- 3. **MANDATORY ARCHITECTURE GRAPH & GOD NODES FIRST (`get_architecture_graph`)**:
35
- - For ANY codebase inquiry, feature design, refactoring, or multi-component investigation, your FIRST tool call MUST be `tokensafe:get_architecture_graph(project_path)` before diving into individual files or running searches. Always pass the target project's absolute path (e.g. `"/path/to/repo"`) when working across multiple workspaces or outside CWD.
36
- - **Result**: Returns top architectural God Nodes, dependency hubs, and centrality rankings in < 250 tokens without file crawling.
37
-
38
- 4. **API SURFACE INSPECTION (`get_api_surface`)**:
39
- - Call `tokensafe:get_api_surface(project_path=".")` (`project_path` defaults to active workspace) to get all exported classes, types, interfaces, and function signatures in a single compact markdown map.
40
-
41
- 5. **DIRECTORY NAVIGATION (`list_dir`)**:
42
- - NEVER run `ls -la` or `ls -l` in terminal.
43
- - Call `tokensafe:list_dir(path=".", depth=2)` for clean directory trees without permissions, timestamps, or lockfiles (-90% tokens). Supports relative subfolders (`path="src"`).
44
-
45
- 6. **SURGICAL FILE EDITS (`edit_file`) & IN-PLACE STREAM MUTATION GUARD (`sed -i` HARD-BLOCKED)**:
46
- - On existing files with >= 40 lines, wholesale rewrites via `write_file` are blocked by **Output Guard**. Always use `edit_file` with precise `Target` and `Replacement` blocks.
47
- - Strictly NEVER run `sed -i`, `perl -i`, `awk -i`, or terminal stream editors on source files (`.ts`, `.tsx`, `.py`, `.js`, etc.) or with numeric line ranges (`'10,20d'`). Blind numeric editing causes line-drift and catastrophic accidental code deletion. These commands are hard-blocked by **TokenSafe Guard** (`decision: deny`).
48
- - NEVER suppress errors with `2>/dev/null` or `&>/dev/null` on file modifications or build commands; failures must fail fast and loud.
49
-
50
- 7. **SECRET LEAK PREVENTION (ZERO HARDCODED FALLBACKS)**:
51
- - Never provide real private keys, API secrets, or credentials as fallback values in `os.environ.get()` or `process.env`. Real credentials must exist strictly in environment variables.
52
-
53
- 8. **CONTEXT BUDGET & HEALTH SCORE (`context_budget` → `compact_conversation`)**:
54
- - Before large multi-step tasks, call `tokensafe:context_budget(model=...)` to check the window budget and Context Quality Score (Grade S/A/B/C/F, tools/history/prompts breakdown, 50/80/95% thresholds).
55
- - When it reports `warning`, `critical`, or Grade C/F, call `tokensafe:compact_conversation(transcript_path=...)` to fold past turns into a Consolidated State Ledger with a 3-line Post-Compaction Orientation Digest (Active Goal, Last State, Next Focus) before continuing — resuming flow immediately without post-compaction disorientation.
56
-
57
- 9. **REPEAT READ DEDUPLICATION & CACHE POINTERS**:
58
- - Never repeatedly re-read the same file or symbol within an active session.
59
- - When `smart_read_file` returns a pointer hit (`// [TokenSafe: Pointer Hit for ...]`), reuse earlier context; pass `"force_full": true` only if your context was compacted or you are a fresh subagent lacking prior turns.
60
-
61
- 10. **ZERO-FLUFF EGRESS & SURGICAL DIFFS**:
62
- - Eliminate conversational preambles, courtesy fillers, and trailing sign-offs.
63
- - Never reprint full unmodified files or lengthy boilerplate; cite line ranges and provide targeted diffs.
64
-
65
- 11. **COMPACT TEST EXECUTION & PIPELINE SANITIZATION**:
66
- - Run unit tests with concise flags or via `tokensafe wrap '<cmd>'` or `tokensafe tests [cmd]`. Native support for `bun test`, `pytest`, `python -m unittest`, `vitest`, `jest`, `cargo test`, and `go test` collapses passing test suites into a single-line summary (`✓ PASS: ...`) rather than flooding `Messages` history with hundreds of verbose log lines. Full traceback is strictly preserved on failure.
67
- - Commands like `git push` automatically strip interactive object-counting progress spam (`--no-progress`), and `git commit` is wrapped when pre-commit/husky hooks exist.
68
-
69
- 12. **MULTIMODAL ISOLATION (PROMPT CACHE PROTECTION)**:
70
- - Loading screenshots or images into a long (>150k-token) coding conversation triggers full KV-cache invalidation and a 3-7x TTFT cliff (40-97s/turn).
71
- - ALWAYS delegate visual inspection of screenshots/mockups to a subagent that returns a concise text-only summary of findings (selectors, coordinates, values, errors); NEVER load raw images into the main coding session.
72
-
73
- 13. **BATCH EDITS & SEARCH ACCELERATION (`apply_edits` & `batch_search`)**:
74
- - When editing >=2 hunks/files or running an edit + verify loop, call `tokensafe:apply_edits(edits=[...], verify="npm test")` to consolidate operations into 1 turn instead of serial turns.
75
- - When running >=2 searches or combining code search with git inspection, call `tokensafe:batch_search(queries=[...])` for concurrent execution in <70ms.
23
+ - **Mandatory Search Tool (`scoped_search`)**: Call `tokensafe:scoped_search(query, path=".", scope="code")` for single searches (`mode="auto|text|regex|glob|fuzzy|git"`), or pass `queries=[{pattern, type, path, glob}]` for up to 20 concurrent queries in <70ms.
24
+
25
+ 2. **SYMBOL, BUNDLE & EXTERNAL TYPE EXTRACTION (`smart_read_file`)**:
26
+ - Call `tokensafe:smart_read_file` with `path` and `symbol` (`dep_mode="signature"` default, `"full"` for dependency bodies, `"include_deps": false` for 0-hop isolation, `"force_full": true` only after compaction or as a fresh subagent).
27
+ - **Multi-Symbol Bundles**: Pass `targets=[{path, symbol}]` (up to 8 targets) to merge skeletons and deduplicate shared imports in ONE call.
28
+ - **External `.d.ts` Types**: Pass `package_name` + `symbol` to slice 3rd-party TypeScript definitions from `node_modules` (-95% tokens).
29
+ - **Schema Auto-Slicing**: OpenAPI/Prisma/GraphQL/SQL files auto-slice via `symbol` (empty `symbol` returns an overview).
30
+
31
+ 3. **ARCHITECTURE GRAPH, API SURFACE & DIRECTORY TREE (`repo_map`)**:
32
+ - First call `tokensafe:repo_map(view="graph", project_path=...)` to inspect God Nodes and dependency hubs (<250 tokens) before reading files.
33
+ - Use `view="api"` for exported classes/types/interfaces, and `view="tree"` (depth=2) instead of `ls -la`.
34
+
35
+ 4. **SURGICAL FILE EDITS (`apply_edits` / `edit_file`) & STREAM GUARD (`sed -i` BLOCKED)**:
36
+ - Use `tokensafe:apply_edits(edits=[...], verify="npm test")` for >=2 hunks/files or edit + verify loops.
37
+ - On existing files with >= 40 lines, wholesale rewrites via `write_file` are blocked by **Output Guard**. Use `edit_file` or `apply_edits`.
38
+ - NEVER run `sed -i`, `perl -i`, `awk -i` on source code or suppress errors (`2>/dev/null`).
39
+
40
+ 5. **SECRET LEAK PREVENTION (ZERO HARDCODED FALLBACKS)**:
41
+ - Never hardcode real private keys, API secrets, or credentials as fallback values in `os.environ.get()` or `process.env`.
42
+
43
+ 6. **SESSION & CONTEXT HYGIENE (`session_context`)**:
44
+ - `action="budget"` (`model=...`, `transcript_path=...`): check window usage and Context Quality Score (Grade S–F).
45
+ - `action="compact"` (`transcript_path=...`): fold past turns into a Consolidated State Ledger with a 3-line Post-Compaction Orientation Digest.
46
+ - `action="prune"` (`transcript_path=...`): drop superseded intermediate file reads.
47
+ - `action="mistakes"` (`project_root=...`): query anti-stuck memory of prior dead-ends and reverts.
48
+ - `action="metrics"`: cumulative savings analytics.
49
+
50
+ 7. **UTILITIES (`run_helper`)**:
51
+ - `action="expand"` (`hash`): restore full original text of a folded `#hash` block.
52
+ - `action="web"` (`url`): fetch docs/pages as clean Markdown (L1/L2/L3 cached).
53
+ - `action="deps"` (`package_name`, `lockfile_path`): point lockfile lookup in <50 tokens.
54
+ - `action="sanitize"` (`command`, `cwd`): rewrite noisy shell/test commands.
55
+ - `action="guard"` (`command`/`code`, `file_path`): pre-flight security/hygiene audit.
56
+ - `action="diff"` (`diff`): slice unified diffs.
57
+ - `action="image"` (`image_path`, `max_edge=1024`): downscale oversized screenshots (-50-75% vision tokens).
58
+ - `action="compress"` (`prompt`): TOCP S-expression prompt compression.
59
+
60
+ 8. **COMPACT TEST EXECUTION & MULTIMODAL ISOLATION**:
61
+ - Run unit tests via `tokensafe tests [cmd]` or `tokensafe wrap '<cmd>'` (1-line summary on pass, full traceback on failure).
62
+ - Never load raw screenshots into long (>150k) sessions; delegate visual inspection to a subagent returning text-only findings.
76
63
 
77
64
  ---
78
65
 
79
- ## Core MCP Tools (`tokensafe`)
80
-
81
- The full tool table with efficiency impact, JSON workflow examples, the Guard check matrix, and the CLI reference live in `references/` — read only the file you need:
66
+ ## Core MCP Tools (`tokensafe` — 7 Consolidated Tools)
82
67
 
83
- - [`references/mcp-tools.md`](references/mcp-tools.md) — Core MCP Tools table + Agent Workflow JSON examples
84
- - [`references/guard-checks.md`](references/guard-checks.md) — Security & Hygiene Guard check matrix (deny/ask per operation)
68
+ - [`references/mcp-tools.md`](references/mcp-tools.md) — Core MCP Tools table + JSON workflow examples
69
+ - [`references/guard-checks.md`](references/guard-checks.md) — Security & Hygiene Guard check matrix
85
70
  - [`references/cli-reference.md`](references/cli-reference.md) — `tokensafe` CLI command reference
86
71
 
87
- Quick pointers:
88
-
89
- - Batch Edits + Verify: `tokensafe:apply_edits(edits=[...], best_effort=true, verify="npm test")` — atomic/best-effort multi-file edits + inline test/typecheck in 1 turn.
90
- - Batch Search: `tokensafe:batch_search(queries=[{pattern, type}])` — up to 20 concurrent text, regex, glob, fuzzy, or read-only git queries in 1 call.
91
- - Search: `tokensafe:scoped_search(query, path=".", scope="code")` — safe keyword & symbol search, never raw grep.
92
- - Inspect: `tokensafe:smart_read_file(path, symbol)` — definition + 1-hop deps. Auto-slices lockfiles, CSV/TSV, SQL dumps.
93
- - External Types: `tokensafe:slice_external_type(package_name, type_name)` — extracts 3rd-party TypeScript definitions from `node_modules` without file crawling (-95% tokens, L1/L2/L3 synced).
94
- - Query Dependencies: `tokensafe:query_dependency(lockfile_path, package_name)` — point lookups in npm/bun/pnpm/cargo/poetry lockfiles in <50 tokens.
95
- - Expand Stash: `tokensafe:expand_ref(hash)` — restore full raw content of any folded block by its 8-char hash (e.g. 'a1b2c3d4').
96
- - Web Reading: `tokensafe:read_web_page(url, force_refresh=false)` — fetch documentation/articles as clean Markdown without HTML/script junk, backed by 3-tier L1/L2/L3 team cache.
97
- - Bundle: `tokensafe:smart_bundle(targets=[{path, symbol}])` — 3-8 related symbols across files in one call, shared imports deduplicated.
98
- - Navigate: `tokensafe:get_architecture_graph(project_path)` / `tokensafe:get_api_surface(project_path)`.
99
- - Directory: `tokensafe:list_dir(path, depth=2)` — clean tree, never verbose `ls -la`.
100
- - Terminal: `tokensafe:sanitize_command(command, cwd)` or run via `tokensafe wrap '<cmd>'` — rewrites git push (--no-progress), wraps git commit hooks, and folds test suites (bun, python unittest/pytest, vitest, jest, cargo, go) to 1-line summaries.
101
- - Context: `tokensafe:compact_conversation(transcript_path)` / `tokensafe:context_budget`.
102
- - Vision: `tokensafe:optimize_image(image_path, max_edge=1024)` — downscale images >1024px (-50-75% vision tokens).
103
- - Prune Reads: `tokensafe:prune_superseded(transcript_path)` — drops obsolete intermediate file reads (-30-40% context).
104
- - Anti-Stuck: `tokensafe:get_mistakes(project_root)` — persistent memory of prior dead-ends and git reverts, backed by 2-tier hybrid escalation (>2 identical failures in 30m = `force_ask`, else advisory) and team broadcast.
72
+ Quick reference:
73
+ - `tokensafe:smart_read_file(path, symbol)` / `(targets=[...])` / `(package_name, symbol)`
74
+ - `tokensafe:scoped_search(query, path=".", scope="code")` / `(queries=[...])`
75
+ - `tokensafe:apply_edits(edits=[...], verify="...")`
76
+ - `tokensafe:repo_map(view="graph"|"api"|"tree", project_path=".")`
77
+ - `tokensafe:session_context(action="budget"|"compact"|"prune"|"mistakes"|"metrics", ...)`
78
+ - `tokensafe:oumv(action="status"|"observe"|"understand"|"verify"|"mutate"|"graph", ...)`
79
+ - `tokensafe:run_helper(action="sanitize"|"guard"|"diff"|"deps"|"web"|"expand"|"image"|"compress", ...)`
105
80
 
106
81
  ---
107
82
 
@@ -137,10 +112,10 @@ TokenSafe actively maximizes provider KV-cache hit rates alongside token compres
137
112
 
138
113
  TokenSafe integrates the **Universal Agent-Runtime Protocol (UARP / OUMV)** to inspect, reason about, edit, and verify running Frontend (`tokensafe-ui`, React 18/19 with Zustand/Redux/Context/useReducer, Vue 3) and Backend (FastAPI, Go, Node.js) services in real time without heavy headless browsers or unconstrained shell curls:
139
114
 
140
- 1. **LIVE RUNTIME HEALTH (`oumv_status`)**:
141
- - Call `tokensafe:oumv_status()` to inspect connection status and capabilities of running DevServers (Frontend ports 5173/3000, Backend ports 8080/8000).
115
+ 1. **LIVE RUNTIME HEALTH (`oumv(action="status")`)**:
116
+ - Call `tokensafe:oumv(action="status")` to inspect connection status and capabilities of running DevServers (Frontend ports 5173/3000, Backend ports 8080/8000).
142
117
 
143
- 2. **PROGRESSIVE CONTEXT OBSERVATION (`oumv_observe`)**:
118
+ 2. **PROGRESSIVE CONTEXT OBSERVATION (`oumv(action="observe")`)**:
144
119
  - Never dump raw HTML or giant JSON payloads. Observe progressively across native components, React, Vue, or backend APIs:
145
120
  - **L0 (Page Pulse ~20 tokens)**: Status, active route, mounted components/roots, error counts (`level="L0"`).
146
121
  - **L1 (Surface ~150 tokens)**: Interactive map of endpoints, models, buttons, and ARIA roles (`level="L1"`).
@@ -148,18 +123,18 @@ TokenSafe integrates the **Universal Agent-Runtime Protocol (UARP / OUMV)** to i
148
123
  - **L3 (Source)**: Targeted symbol source with line mapping and OCC version hash token.
149
124
  - **L4 (Traces)**: Event stream, signal mutations, store subscriptions (Zustand/Redux/Context updates), and state snapshot diffs.
150
125
 
151
- 3. **RUNTIME CAUSALITY & WHY-STATE (`oumv_understand`)**:
126
+ 3. **RUNTIME CAUSALITY & WHY-STATE (`oumv(action="understand")`)**:
152
127
  - Never guess state flows or assume dependencies.
153
- - Call `tokensafe:oumv_understand(query="causality", target="POST /api/orders")` to query live dependencies:
128
+ - Call `tokensafe:oumv(action="understand", query="causality", target="POST /api/orders")` to query live dependencies:
154
129
  `Route ➔ Handler ➔ ValidatesWith ➔ Model ➔ DB Table` or `Signal ➔ Computed ➔ Effect ➔ DOM Binding`.
155
- - Call `tokensafe:oumv_understand(query="impact", target="cart")` before refactoring to know exactly what breaks.
130
+ - Call `tokensafe:oumv(action="understand", query="impact", target="cart")` before refactoring to know exactly what breaks. Use `action="graph"` for the cross-stack graph.
156
131
 
157
- 4. **SANDBOXED ACTION VERIFICATION (`oumv_verify`)**:
132
+ 4. **SANDBOXED ACTION VERIFICATION (`oumv(action="verify")`)**:
158
133
  - Sub-millisecond to low-millisecond local action verification inside transactional sandbox.
159
- - **For backend endpoints**: call `tokensafe:oumv_verify(target="POST /api/products", payload={...})` — executes the request in-memory with automatic database rollback (`rolledBack: true`) and returns structured state diffs (`diff`) and HTTP status code.
160
- - **For frontend UI**: call `tokensafe:oumv_verify(target="cart", action="addItem", payload={...})` — executes synthetic events, component actions, Zustand/Redux actions, or reducer dispatches in memory, returning structured `stateDiff` and `surfaceDiff` without spawning heavy browser automation.
134
+ - **For backend endpoints**: call `tokensafe:oumv(action="verify", target="POST /api/products", payload={...})` — executes in-memory with automatic DB rollback (`rolledBack: true`).
135
+ - **For frontend UI**: call `tokensafe:oumv(action="verify", target="cart", verify_action="addItem", payload={...})` — executes synthetic events/store actions in memory without browser automation.
161
136
 
162
- 5. **OPTIMISTIC CONCURRENCY MUTATIONS (`oumv_mutate`)**:
137
+ 5. **OPTIMISTIC CONCURRENCY MUTATIONS (`oumv(action="mutate")`)**:
163
138
  - Submits surgical edits verified against `expectedVersion` with built-in Babel AST TSX/JSX syntax guards and security leak prevention.
164
139
 
165
140
  ---
@@ -1,167 +1,67 @@
1
1
  # Core MCP Tools Reference (`tokensafe`)
2
2
 
3
- All tools are exposed via Model Context Protocol (stdio JSON-RPC 2.0).
3
+ Exposed via Model Context Protocol (stdio JSON-RPC 2.0) as **7 consolidated tools** (all 28 legacy tool names remain supported as aliases).
4
4
 
5
- | MCP Tool | Description | Efficiency Impact |
5
+ | MCP Tool | Modes / Actions | Efficiency Impact |
6
6
  |---|---|---|
7
- | `tokensafe:smart_read_file` | Graph-guided AST reader with `symbol` body retention, `dep_mode` (`signature` default / `full`), and session pointer dedup (`force_full`). OpenAPI/Swagger, Prisma, GraphQL and SQL files are auto-sliced: `symbol` = spec path/model/type/table; empty `symbol` returns a compact overview. Lockfiles (`package-lock.json`, `Cargo.lock`) and tabular data (`.csv`, `.tsv`, `.sql`, `.har`) auto-reduce with reversible hash anchors. | **-90% to -98%** token reduction |
8
- | `tokensafe:expand_ref` | Expands a previously folded or stashed tool/command/file result by its 8-character hex hash anchor (e.g. `'a1b2c3d4'`). Returns the full original text that TokenSafe folded without re-running tools. | **Zero Data Loss** recovery |
9
- | `tokensafe:read_web_page` | Fetches a web page URL and converts it to clean, readable Markdown, stripping scripts, styles, navbars, and ads. | **-80% to -95%** vs raw HTML fetches |
10
- | `tokensafe:smart_bundle` | Multi-symbol context bundle: up to 8 `{path, symbol}` targets in ONE call — per-file skeletons with shared import lines deduplicated and merged 1-hop dependency signatures. Replaces 3+ chained `smart_read_file` calls. | **-85% to -95%** + one roundtrip instead of many |
11
- | `tokensafe:scoped_search` | Safe, token-bounded keyword, symbol, or config search across the codebase. Accelerated by native SQLite FTS5 trigram index with BM25 relevance ranking (<1ms) and seamless regex fallback (supports `path='.'`, `scope='code'`/`'config'`/`'all'`/file extension/subfolder). | **-90% to -95%** vs raw grep/find |
12
- | `tokensafe:list_dir` | Token-efficient directory tree without lockfiles, timestamps, or ignored folders (node_modules, .git, dist, .env). Replaces `ls -la`. | **-90%** vs verbose `ls` |
13
- | `tokensafe:get_architecture_graph` | Computes dependency topology, hub centrality, and identifies top God Nodes for `project_path`. | **~200 tokens** (replaces 50k crawl) |
14
- | `tokensafe:get_api_surface` | Generates a compact markdown map of all exported types, interfaces, and classes. | **~500 tokens** for entire project |
15
- | `tokensafe:sanitize_command` | Per-stage command rewrites: lockfile diffs, unbounded `git log`/`git show`/`git blame`/`rg`, docker/kubectl log caps, quiet npm/pip installs, bounded `cat`/`curl` output, `git push` object-counting strip (`--no-progress`), and `git commit` hook wrapping. Compound commands (`a && b ; c`) are optimized per stage. Test commands (`bun test`, `pytest`, `python -m unittest`, `vitest`, `jest`) are wrapped or forced into run-once mode (`CI=true`, `--watch=false`, `--forceExit`) so passing suites emit a clean 1-line summary and agents never hang on watch mode. Pass optional `cwd` to identify runners behind opaque `yarn/npm test` scripts. | Saves **10k-50k tokens** per run |
16
- | `tokensafe:slice_diff` | Slices unified git diffs, eliminating lockfiles and minimizing hunk context lines. | **-50% to -80%** diff size |
17
- | `tokensafe:compress_prompt` | Compresses verbose user instructions into lean TOCP S-expressions via DeepSeek/Regex. | **-40% to -65%** prompt tokens |
18
- | `tokensafe:compact_conversation` | On-demand context compaction: folds a long JSONL session transcript into a lean Consolidated State Ledger with a 3-line Post-Compaction Orientation Digest (`transcript_path`, optional `invocation_num`). Preserves flow instantly without post-compaction amnesia. | **-80% to -95%** history tokens |
19
- | `tokensafe:context_budget` | Context Budget HUD & Context Quality Score (Grade S/A/B/C/F): estimated window usage and unified health grade (tools/history/prompts breakdown, static tool/skill tax, headroom %). Call before deciding to compact. | Floor estimate, always labeled estimated |
20
- | `tokensafe:guard_inspect` | Pre-flight security & hygiene audit: denies literal secrets/destructive commands in shell lines (secrets, TLS, SQLi, raw grep); advisory for never-terminating streams (`tail -f`, `watch`, `docker attach`) and TLS bypasses. | **Zero-Risk** pre-flight gate |
21
- | `tokensafe:optimize_image` | Downscales oversized screenshots/diagrams (>1024px) before LLM vision ingestion while preserving original disk files and aspect ratios. | **-50% to -75%** vision tokens |
22
- | `tokensafe:prune_superseded` | Prunes obsolete intermediate tool read outputs in long transcripts that were superseded by subsequent edits or re-reads. | **-30% to -40%** context mass |
23
- | `tokensafe:get_mistakes` | Anti-stuck persistent ledger: retrieves past dead-ends, loop guard trips, and git reverts to prevent cycling through failed solutions. | **Anti-loop / Zero Repetition** |
24
- | `tokensafe:get_token_savings_metrics` | Returns cumulative analytics: tokens saved (measured/estimated split), context ratio, ≈USD value (derived), and optimization source breakdown. | Persistent SQLite analytics |
7
+ | `tokensafe:smart_read_file` | Single `path+symbol` (`dep_mode`: `signature`\|`full`, `force_full`); `targets=[{path,symbol}]` bundle (2–8 symbols); `package_name+symbol` (`.d.ts`). Auto-slices OpenAPI/Prisma/GraphQL/SQL/lockfiles. | **-90% to -98%** token reduction |
8
+ | `tokensafe:scoped_search` | Single `query+scope` (`mode`: `auto`\|`text`\|`regex`\|`glob`\|`fuzzy`\|`git`); or `queries=[...]` batch (up to 20 concurrent queries in <70ms). | **-90% to -95%** vs grep/find |
9
+ | `tokensafe:apply_edits` | `edits=[...]` (up to 50 files, `best_effort`, `dry_run`) + optional `verify` command in 1 turn. | Replaces serial edit/test loops |
10
+ | `tokensafe:repo_map` | `view="graph"` (God Nodes & deps), `"api"` (exported types/classes), `"tree"` (clean dir tree). | **~200–500 tokens** vs 50k crawl |
11
+ | `tokensafe:session_context` | `action="budget"` (Grade S–F), `"compact"` (State Ledger), `"prune"` (superseded reads), `"mistakes"` (anti-stuck), `"metrics"`. | **-80% to -95%** history mass |
12
+ | `tokensafe:oumv` | `action="status"`\|`"observe"` (`L0–L4`)\|`"understand"`\|`"verify"` (sandbox)\|`"mutate"` (OCC)\|`"graph"`. | Sub-ms live runtime verification |
13
+ | `tokensafe:run_helper` | `action="sanitize"`\|`"guard"`\|`"diff"`\|`"deps"`\|`"web"`\|`"expand"`\|`"image"`\|`"compress"`. | Unified utility surface |
25
14
 
26
15
  ---
27
16
 
28
17
  ## Agent Workflows
29
18
 
30
- ### 1. Architecture Exploration Workflow
19
+ ### 1. Architecture, API Map & Directory Tree (`repo_map`)
31
20
  ```json
32
- {
33
- "ServerName": "tokensafe",
34
- "ToolName": "get_architecture_graph",
35
- "Arguments": {
36
- "project_path": "/Users/.../projects/my-app"
37
- }
38
- }
21
+ {"tool": "repo_map", "arguments": {"view": "graph", "project_path": "/path/to/repo"}}
39
22
  ```
40
- *Identifies core architectural hubs and dependency weights before inspecting files.*
23
+ *Use `"view": "api"` for exported interfaces/types and `"view": "tree"` (`depth=2`) instead of `ls -la`.*
41
24
 
42
- ### 2. Scoped Code & Config Search Workflow
25
+ ### 2. Single & Batch Code Search (`scoped_search`)
43
26
  ```json
44
- {
45
- "ServerName": "tokensafe",
46
- "ToolName": "scoped_search",
47
- "Arguments": {
48
- "query": "HARDCODED_VERSION",
49
- "path": "./src",
50
- "scope": "code"
51
- }
52
- }
27
+ {"tool": "scoped_search", "arguments": {"query": "HARDCODED_VERSION", "path": "./src", "scope": "code"}}
53
28
  ```
54
- *Locates exact occurrences with file and line references in < 100 tokens. Always pass `path` (defaults to active project root, e.g. ".") and optional `scope` ('code', 'config', 'all', file extension like 'go', or subfolder like 'internal/promo'). Auto-guarded against system roots.*
55
-
56
- ### 2b. Directory Navigation Workflow (`list_dir`)
57
29
  ```json
58
- {
59
- "ServerName": "tokensafe",
60
- "ToolName": "list_dir",
61
- "Arguments": {
62
- "path": "/Users/.../projects/my-app/src",
63
- "depth": 2
64
- }
65
- }
30
+ {"tool": "scoped_search", "arguments": {"queries": [{"pattern": "auth", "type": "text"}, {"pattern": "status --short", "type": "git"}]}}
66
31
  ```
67
- *Renders a clean directory tree without permissions, timestamps, lockfiles, or heavy directories (`node_modules`, `.git`, `dist`).*
68
32
 
69
- ### 3. Targeted Symbol Inspection Workflow
33
+ ### 3. Symbol, Bundle & External `.d.ts` Reads (`smart_read_file`)
70
34
  ```json
71
- {
72
- "ServerName": "tokensafe",
73
- "ToolName": "smart_read_file",
74
- "Arguments": {
75
- "path": "/Users/.../projects/my-app/src/views/StatsView.tsx",
76
- "symbol": "LuckyWheelTab",
77
- "dep_mode": "signature"
78
- }
79
- }
35
+ {"tool": "smart_read_file", "arguments": {"path": "src/views/StatsView.tsx", "symbol": "LuckyWheelTab", "dep_mode": "signature"}}
80
36
  ```
81
- *Extracts the targeted `LuckyWheelTab` implementation plus compact 1-line signatures for 1-hop dependencies with inert code and imports folded. Pass `"dep_mode": "full"` for full dependency bodies, `"include_deps": false` for 0-hop isolation, or `"force_full": true` to bypass a session pointer hit.*
82
-
83
- ### 4. Public API Map Workflow
84
37
  ```json
85
- {
86
- "ServerName": "tokensafe",
87
- "ToolName": "get_api_surface",
88
- "Arguments": {
89
- "project_path": "/Users/.../projects/my-app"
90
- }
91
- }
38
+ {"tool": "smart_read_file", "arguments": {"targets": [{"path": "src/a.ts", "symbol": "fnA"}, {"path": "src/b.ts", "symbol": "fnB"}]}}
92
39
  ```
93
- *Returns all exported interfaces and types without reading hundreds of module files.*
94
-
95
- ### 5. Pre-flight Security & Hygiene Audit
96
40
  ```json
97
- {
98
- "ServerName": "tokensafe",
99
- "ToolName": "guard_inspect",
100
- "Arguments": {
101
- "command": "git add .env",
102
- "file_path": "src/auth.ts"
103
- }
104
- }
41
+ {"tool": "smart_read_file", "arguments": {"package_name": "zod", "symbol": "ZodSchema"}}
105
42
  ```
106
- *Validates commands and code snippets before execution; returns structured pass/block verdict with check_name.*
107
43
 
108
- ### 6. Context Budget → Smart Compact Workflow
44
+ ### 4. Session & Context Hygiene (`session_context`)
109
45
  ```json
110
- {
111
- "ServerName": "tokensafe",
112
- "ToolName": "context_budget",
113
- "Arguments": {
114
- "model": "claude-x"
115
- }
116
- }
46
+ {"tool": "session_context", "arguments": {"action": "budget", "model": "claude-sonnet-4", "transcript_path": "/path/to/transcript.jsonl"}}
117
47
  ```
118
- *Run before large multi-step tasks. When the response reports `threshold: "warning"` or `"critical"`, immediately chain the compact call:*
119
-
120
48
  ```json
121
- {
122
- "ServerName": "tokensafe",
123
- "ToolName": "compact_conversation",
124
- "Arguments": {
125
- "transcript_path": "/Users/.../.claude/projects/<session>/transcript.jsonl",
126
- "invocation_num": 12
127
- }
128
- }
49
+ {"tool": "session_context", "arguments": {"action": "compact", "transcript_path": "/path/to/transcript.jsonl", "invocation_num": 12}}
129
50
  ```
130
- *Folds past turns into a Consolidated State Ledger (-80% to -95% history tokens) so long sessions never degrade into context starvation. The transcript path is provided by the host session (hook payload `transcript_path` / session start context).*
131
51
 
132
- ### 7. Vision Image Optimizer (`optimize_image`)
52
+ ### 5. Rare Utilities (`run_helper`)
133
53
  ```json
134
- {
135
- "ServerName": "tokensafe",
136
- "ToolName": "optimize_image",
137
- "Arguments": {
138
- "image_path": "/path/to/screenshot.png",
139
- "max_edge": 1024
140
- }
141
- }
54
+ {"tool": "run_helper", "arguments": {"action": "web", "url": "https://docs.example.com/api"}}
142
55
  ```
143
- *Downscales oversized 2K/4K screenshots to max 1024px, saving 50-75% vision tokens while keeping original files intact on disk.*
144
-
145
- ### 8. Superseded Tool Output Pruning (`prune_superseded`)
146
56
  ```json
147
- {
148
- "ServerName": "tokensafe",
149
- "ToolName": "prune_superseded",
150
- "Arguments": {
151
- "transcript_path": "/path/to/transcript.jsonl"
152
- }
153
- }
57
+ {"tool": "run_helper", "arguments": {"action": "expand", "hash": "a1b2c3d4"}}
58
+ ```
59
+ ```json
60
+ {"tool": "run_helper", "arguments": {"action": "deps", "package_name": "zod"}}
61
+ ```
62
+ ```json
63
+ {"tool": "run_helper", "arguments": {"action": "guard", "command": "git add .env"}}
154
64
  ```
155
- *Replaces outdated intermediate file reads with reversible 1-line stashed tombstones (-30-40% context mass in multi-turn sessions).*
156
-
157
- ### 9. Anti-Stuck Mistakes Memory (`get_mistakes`)
158
65
  ```json
159
- {
160
- "ServerName": "tokensafe",
161
- "ToolName": "get_mistakes",
162
- "Arguments": {
163
- "project_root": "."
164
- }
165
- }
66
+ {"tool": "run_helper", "arguments": {"action": "image", "image_path": "/path/to/screenshot.png", "max_edge": 1024}}
166
67
  ```
167
- *Retrieves active dead-ends, failed hypotheses, and git reverts to prevent agents from attempting known failing solutions.*