tokensafe 3.2.0 โ 4.0.0
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.
- package/README.md +60 -28
- package/bin/tokensafe.js +25 -9
- package/hooks/claude_code_hook.py +7 -0
- package/hooks/pre_tool_use.py +24 -0
- package/hooks/session_start.py +8 -0
- package/package.json +2 -2
- package/plugin.json +1 -1
- package/rules/AGENTS.md +13 -7
- package/server.json +3 -3
- package/skills/token-optimizer/SKILL.md +7 -2
- package/skills/token-optimizer/references/cli-reference.md +11 -1
- package/skills/token-optimizer/references/mcp-tools.md +44 -2
- package/src/bench_scenarios.json +376 -0
- package/src/cache_normalizer.py +21 -0
- package/src/cli.py +234 -2
- package/src/command_sanitizer.py +2 -0
- package/src/competitors.py +179 -0
- package/src/environment_auditor.py +110 -1
- package/src/format_parsers/__init__.py +20 -0
- package/src/format_parsers/ansi.py +41 -0
- package/src/format_parsers/compiler_errors.py +159 -0
- package/src/format_parsers/docker_k8s.py +95 -0
- package/src/format_parsers/json_log.py +89 -0
- package/src/format_parsers/lockfiles.py +157 -0
- package/src/format_parsers/tabular.py +175 -0
- package/src/fts_index.py +296 -0
- package/src/graph_engine.py +395 -48
- package/src/image_downscale.py +228 -0
- package/src/loop_detector.py +5 -0
- package/src/mcp_config_manager.py +197 -0
- package/src/mcp_proxy.py +154 -0
- package/src/mcp_server.py +215 -1
- package/src/mistakes.py +203 -0
- package/src/result_ledger.py +8 -1
- package/src/scoped_search.py +32 -0
- package/src/stash.py +199 -0
- package/src/superseded.py +220 -0
- package/src/telemetry_sync.py +1 -1
- package/src/test_parsers.py +271 -0
- package/src/version_checker.py +1 -1
- package/src/web_reader.py +202 -0
package/README.md
CHANGED
|
@@ -25,6 +25,7 @@
|
|
|
25
25
|
<p align="center">
|
|
26
26
|
<a href="#install--agents">Install</a> •
|
|
27
27
|
<a href="#cli-quickstart">Quickstart</a> •
|
|
28
|
+
<a href="#whats-new-in-v40">What's New in v4.0</a> •
|
|
28
29
|
<a href="#why-tokensafe">Why TokenSafe</a> •
|
|
29
30
|
<a href="#benchmarks">Benchmarks</a> •
|
|
30
31
|
<a href="#pricing-and-7-day-team-trial">Pricing</a> •
|
|
@@ -35,6 +36,22 @@
|
|
|
35
36
|
|
|
36
37
|
---
|
|
37
38
|
|
|
39
|
+
## What's New in v4.0
|
|
40
|
+
|
|
41
|
+
TokenSafe 4.0 is a major architecture release designed for **Zero Mid-Day Lockouts, 3-Second Turn Latency, Exact Code Context (Zero Loss), and Developer Flow**:
|
|
42
|
+
|
|
43
|
+
- **โก SQLite FTS5 BM25 Code Indexer & Search (`scoped_search`, `tokensafe search`)**: Native SQLite full-text search with trigram tokenization and BM25 relevance ranking (<1ms) across the repository. Replaces raw terminal grep entirely with zero-token-waste search.
|
|
44
|
+
- **๐ SQLite Graph Cache & Cross-Boundary Route Linking**: Persistent SQLite caching (`.tokensafe/cache/graph.db`) with bidirectional semantic linking between frontend client endpoints (`fetch`, `axios`, `apiClient`) and backend HTTP routes (`FastAPI`, `Express`, `Flask`, `Next.js`).
|
|
45
|
+
- **๐ผ๏ธ Vision Image Downscaler (`optimize_image`, `tokensafe optimize-image`)**: Automatically scales down oversized screenshots, architecture diagrams, and mockups (>1024px) via Pillow or macOS `sips`, saving 50โ75% vision tokens while keeping original files intact.
|
|
46
|
+
- **๐ง Anti-Stuck Dead-Ends Ledger (`get_mistakes`, `tokensafe mistakes`)**: Persistent project memory tracking failed hypotheses, loop guard trips, and git reverts to prevent agents from cycling through already-failed solutions.
|
|
47
|
+
- **๐งน Transcript Superseded Output Pruning (`prune_superseded`, `tokensafe prune-superseded`)**: Prunes obsolete intermediate tool reads that were superseded by subsequent edits or re-reads in long agent transcripts (-30-40% context).
|
|
48
|
+
- **๐งผ ANSI Escape Sequence Stripper**: Cleans all ANSI/VT100 escape codes from tool outputs, test runners, and proxy streams before they enter model context.
|
|
49
|
+
- **๐ป Ghost Tokens Auditor (`tokensafe doctor`)**: Detects and cleans redundant multi-IDE configuration files (`.cursorrules`, `CLAUDE.md`, `.windsurfrules`, `.clinerules`) and oversized rule files, saving 2,000โ5,000 wasted ghost tokens on every turn.
|
|
50
|
+
- **๐ก๏ธ Exact Code Context & Reversible Stash (`expand_ref`)**: 100% byte-exact target symbol preservation with reversible 8-char hash anchors (`#a1b2c3d4`) to instantly recover any folded block.
|
|
51
|
+
- **๐ฒ C# Tree-sitter Support**: Native AST slicing and God Nodes detection for C# (`tree-sitter-c-sharp`) alongside TypeScript, JavaScript, Python, Go, Rust, Java, Kotlin, and PHP.
|
|
52
|
+
|
|
53
|
+
---
|
|
54
|
+
|
|
38
55
|
## Install & Agents
|
|
39
56
|
|
|
40
57
|
Connect TokenSafe to the AI coding agents on your workstation in one command:
|
|
@@ -312,18 +329,23 @@ All hook adapters fail open: an internal error never stalls your agent. Failures
|
|
|
312
329
|
## Reference
|
|
313
330
|
|
|
314
331
|
<details>
|
|
315
|
-
<summary><b>Local MCP tools (
|
|
332
|
+
<summary><b>Local MCP tools (18)</b></summary>
|
|
316
333
|
|
|
317
334
|
| Tool | What it does |
|
|
318
335
|
|---|---|
|
|
319
|
-
| `get_architecture_graph` | Architectural hotspots
|
|
336
|
+
| `get_architecture_graph` | Architectural hotspots, dependency topology, and God Nodes detection before multi-file reading (persisted in SQLite cache) |
|
|
320
337
|
| `get_api_surface` | Compact markdown map of all exported interfaces, classes, and types |
|
|
321
|
-
| `smart_read_file` | AST-skeletonized file read preserving a target symbol and 1-hop dependencies; OpenAPI/Prisma/GraphQL/SQL
|
|
338
|
+
| `smart_read_file` | AST-skeletonized file read preserving a target symbol and 1-hop dependencies; OpenAPI/Prisma/GraphQL/SQL auto-slice; lockfiles/CSV/TSV/SQL dump auto-reduction with reversible stash |
|
|
322
339
|
| `smart_bundle` | 3โ8 related symbols across files in one call: merged skeletons, deduplicated shared imports, unified 1-hop signatures |
|
|
323
|
-
| `scoped_search` |
|
|
340
|
+
| `scoped_search` | Sub-millisecond keyword and symbol search powered by native SQLite FTS5 trigram index with BM25 relevance ranking (<1ms) |
|
|
341
|
+
| `expand_ref` | Reversible stash expansion: recovers original un-truncated content by its 8-char hex hash anchor (`#a1b2c3d4`) without re-running tools |
|
|
342
|
+
| `read_web_page` | Web reader & HTML-to-Markdown compactor: strips scripts, styles, navbars, and cookie banners (-80% to -95% tokens) |
|
|
343
|
+
| `optimize_image` | Downscales oversized visual assets (>1024px) via Pillow or macOS `sips`, saving 50โ75% vision tokens |
|
|
344
|
+
| `prune_superseded` | Prunes obsolete intermediate tool reads that were superseded by subsequent edits or re-reads in long agent transcripts (-30-40% context) |
|
|
345
|
+
| `get_mistakes` | Anti-stuck persistent ledger: retrieves past dead-ends, loop guard trips, and git reverts to prevent repeating failed paths |
|
|
324
346
|
| `list_dir` | Clean directory tree without permissions, timestamps, or lockfiles |
|
|
325
347
|
| `slice_diff` | Unified diff slicing omitting lockfiles and minimizing context lines |
|
|
326
|
-
| `sanitize_command` | Per-stage shell command rewrites with bounded output |
|
|
348
|
+
| `sanitize_command` | Per-stage shell command rewrites with bounded output and ANSI escape sequence stripping |
|
|
327
349
|
| `guard_inspect` | Pre-flight security and hygiene audit for commands or code snippets |
|
|
328
350
|
| `context_budget` | Context window usage estimate with thresholds and recommendations |
|
|
329
351
|
| `compress_prompt` | Compiles a verbose developer prompt into a compact S-expression |
|
|
@@ -354,31 +376,41 @@ Endpoint: `https://api.tokensafe.dev/mcp`, auth `Authorization: Bearer <TS1./TS2
|
|
|
354
376
|
</details>
|
|
355
377
|
|
|
356
378
|
<details>
|
|
357
|
-
<summary><b>Full CLI reference (
|
|
379
|
+
<summary><b>Full CLI reference (30 commands)</b></summary>
|
|
358
380
|
|
|
359
381
|
```text
|
|
360
|
-
tokensafe stats / markdown / html
|
|
361
|
-
tokensafe
|
|
362
|
-
tokensafe
|
|
363
|
-
tokensafe
|
|
364
|
-
tokensafe
|
|
365
|
-
tokensafe
|
|
366
|
-
tokensafe
|
|
367
|
-
tokensafe
|
|
368
|
-
tokensafe
|
|
369
|
-
tokensafe
|
|
370
|
-
tokensafe
|
|
371
|
-
tokensafe
|
|
372
|
-
tokensafe
|
|
373
|
-
tokensafe
|
|
374
|
-
tokensafe
|
|
375
|
-
tokensafe
|
|
376
|
-
tokensafe
|
|
377
|
-
tokensafe
|
|
378
|
-
tokensafe
|
|
379
|
-
tokensafe
|
|
380
|
-
tokensafe
|
|
381
|
-
tokensafe
|
|
382
|
+
tokensafe stats / markdown / html Savings analytics (terminal / .md report / dashboard)
|
|
383
|
+
tokensafe search <query> [--path <p>] Fast SQLite FTS5 BM25 code search (<1ms)
|
|
384
|
+
tokensafe index [dir] [--clear] Index repository into SQLite FTS5 trigram database
|
|
385
|
+
tokensafe expand-ref <hash8> Restore folded tool/command/file result by its 8-char hash
|
|
386
|
+
tokensafe optimize-image <path> Downscale image >1024px via Pillow or macOS sips
|
|
387
|
+
tokensafe prune-superseded <path> Prune obsolete intermediate tool reads from transcript
|
|
388
|
+
tokensafe mistakes [list|record|clear] Anti-stuck dead-ends ledger & prompt guard
|
|
389
|
+
tokensafe web <url> Fetch web page/docs and print clean compact Markdown
|
|
390
|
+
tokensafe wrap <command> Run command with compact output folding & ANSI stripping
|
|
391
|
+
tokensafe doctor [--cleanup] Audit MCP tool overhead, ghost tokens & conflicts
|
|
392
|
+
tokensafe benchmark Zero-context-loss benchmark suite (simulated harness)
|
|
393
|
+
tokensafe bench --real Measured benchmark on real repos (zero-loss gates)
|
|
394
|
+
tokensafe graph / map / skeleton Architecture graph / API surface / AST skeleton of a file
|
|
395
|
+
tokensafe test "<prompt>" Preview prompt compaction on custom input
|
|
396
|
+
tokensafe guard "<command>" Pre-flight safety check for a shell command
|
|
397
|
+
tokensafe guard audit [path] Recursive source audit for secrets & vulnerabilities
|
|
398
|
+
tokensafe digest [--send] Compile (and optionally dispatch) the weekly team digest
|
|
399
|
+
tokensafe mcp list|disable|enable Manage configured MCP servers
|
|
400
|
+
tokensafe proxy [port] Local transparent AI proxy (127.0.0.1:8765/v1)
|
|
401
|
+
tokensafe proxy on/off/status Daemon + agent wiring with one-command rollback
|
|
402
|
+
tokensafe install / setup [--all] Configure detected agent environments
|
|
403
|
+
tokensafe update / check-update Self-update / check for a newer version
|
|
404
|
+
tokensafe activate <KEY> Activate a Team or Solo license key
|
|
405
|
+
tokensafe login / logout Authorize or unlink this device via browser
|
|
406
|
+
tokensafe license Show active tier and trial state
|
|
407
|
+
tokensafe providers List distillation providers and active mode
|
|
408
|
+
tokensafe sync Sync local telemetry with the cloud dashboard
|
|
409
|
+
tokensafe prune [--days N] Compact metrics database (roll old events)
|
|
410
|
+
tokensafe vacuum Reclaim SQLite disk space
|
|
411
|
+
tokensafe tests [pytest] Run the unit test suite (compact failure report)
|
|
412
|
+
tokensafe reset Reset all local token metrics
|
|
413
|
+
tokensafe --version Print version and exit
|
|
382
414
|
```
|
|
383
415
|
</details>
|
|
384
416
|
|
package/bin/tokensafe.js
CHANGED
|
@@ -13,6 +13,19 @@ const os = require('os');
|
|
|
13
13
|
const ROOT_DIR = path.resolve(__dirname, '..');
|
|
14
14
|
const args = process.argv.slice(2);
|
|
15
15
|
const VENV_DIR = path.join(os.homedir(), '.tokensafe', 'venv');
|
|
16
|
+
const CORE_DEPS = [
|
|
17
|
+
'cryptography>=42.0',
|
|
18
|
+
'tree-sitter>=0.23',
|
|
19
|
+
'tree-sitter-python',
|
|
20
|
+
'tree-sitter-javascript',
|
|
21
|
+
'tree-sitter-typescript',
|
|
22
|
+
'tree-sitter-go',
|
|
23
|
+
'tree-sitter-rust',
|
|
24
|
+
'tree-sitter-java',
|
|
25
|
+
'tree-sitter-php',
|
|
26
|
+
'tree-sitter-kotlin',
|
|
27
|
+
'tree-sitter-c-sharp'
|
|
28
|
+
];
|
|
16
29
|
|
|
17
30
|
function checkPython(cmd, requireCrypto) {
|
|
18
31
|
const probe = requireCrypto
|
|
@@ -26,12 +39,12 @@ function checkPython(cmd, requireCrypto) {
|
|
|
26
39
|
}
|
|
27
40
|
}
|
|
28
41
|
|
|
29
|
-
function
|
|
30
|
-
console.error('โก Installing
|
|
42
|
+
function bootstrapDependencies(basePython) {
|
|
43
|
+
console.error('โก Installing TokenSafe dependencies (cryptography & tree-sitter AST grammars)...');
|
|
31
44
|
// 1. Try user-site pip first (respects normal user environments)
|
|
32
45
|
const userPip = spawnSync(
|
|
33
46
|
basePython,
|
|
34
|
-
['-m', 'pip', 'install', '--user', '--quiet', '--disable-pip-version-check',
|
|
47
|
+
['-m', 'pip', 'install', '--user', '--quiet', '--disable-pip-version-check', ...CORE_DEPS],
|
|
35
48
|
{ encoding: 'utf-8', stdio: 'pipe' }
|
|
36
49
|
);
|
|
37
50
|
if (userPip.status === 0 && checkPython(basePython, true)) {
|
|
@@ -50,7 +63,7 @@ function bootstrapCryptography(basePython) {
|
|
|
50
63
|
}
|
|
51
64
|
const venvPip = spawnSync(
|
|
52
65
|
venvPy,
|
|
53
|
-
['-m', 'pip', 'install', '--quiet', '--disable-pip-version-check',
|
|
66
|
+
['-m', 'pip', 'install', '--quiet', '--disable-pip-version-check', ...CORE_DEPS],
|
|
54
67
|
{ encoding: 'utf-8', stdio: 'pipe' }
|
|
55
68
|
);
|
|
56
69
|
if (venvPip.status === 0 && checkPython(venvPy, true)) {
|
|
@@ -59,7 +72,7 @@ function bootstrapCryptography(basePython) {
|
|
|
59
72
|
return null;
|
|
60
73
|
}
|
|
61
74
|
|
|
62
|
-
// Locate Python 3.10+ interpreter with required
|
|
75
|
+
// Locate Python 3.10+ interpreter with required dependencies
|
|
63
76
|
function findPython() {
|
|
64
77
|
const venvPy = process.platform === 'win32'
|
|
65
78
|
? path.join(VENV_DIR, 'Scripts', 'python.exe')
|
|
@@ -74,11 +87,11 @@ function findPython() {
|
|
|
74
87
|
for (const cmd of candidates) {
|
|
75
88
|
if (cmd === venvPy && !fs.existsSync(venvPy)) continue;
|
|
76
89
|
if (checkPython(cmd, false)) {
|
|
77
|
-
const bootstrapped =
|
|
90
|
+
const bootstrapped = bootstrapDependencies(cmd);
|
|
78
91
|
if (bootstrapped) return bootstrapped;
|
|
79
|
-
console.error("\nโ TokenSafe requires
|
|
80
|
-
console.error("Install
|
|
81
|
-
console.error(" pip install 'cryptography>=42.0'\n");
|
|
92
|
+
console.error("\nโ TokenSafe requires Python 3.10+ and 'cryptography>=42.0'.");
|
|
93
|
+
console.error("Install dependencies manually via:");
|
|
94
|
+
console.error(" pip install 'cryptography>=42.0' 'tree-sitter>=0.23' 'tree-sitter-python'\n");
|
|
82
95
|
process.exit(1);
|
|
83
96
|
}
|
|
84
97
|
}
|
|
@@ -100,6 +113,9 @@ Commands:
|
|
|
100
113
|
tokensafe sync Synchronize local token metrics with Cloud Dashboard
|
|
101
114
|
tokensafe html Generate and open interactive browser dashboard
|
|
102
115
|
tokensafe test "<prompt>" Test prompt compression on custom input
|
|
116
|
+
tokensafe expand-ref <hash> Restore folded tool/command/file result by its 8-char hash
|
|
117
|
+
tokensafe wrap <command> Run command with compact output folding (e.g. tests/logs)
|
|
118
|
+
tokensafe web <url> Fetch web page/docs and print clean compact Markdown
|
|
103
119
|
tokensafe doctor Audit MCP servers & skills context token tax
|
|
104
120
|
tokensafe providers List active LLM distillation models & keys
|
|
105
121
|
tokensafe benchmark Run zero-loss verification benchmark suite
|
|
@@ -49,6 +49,13 @@ def handle(event: str, payload: dict) -> dict:
|
|
|
49
49
|
extra = f"{extra}\n\n{quota['warning']}"
|
|
50
50
|
except Exception:
|
|
51
51
|
pass
|
|
52
|
+
try:
|
|
53
|
+
from src.mistakes import MistakesLedger
|
|
54
|
+
guard = MistakesLedger.get_guard_prompt(project_root=str(payload.get("cwd") or os.getcwd()))
|
|
55
|
+
if guard:
|
|
56
|
+
extra = f"{extra}\n\n{guard}"
|
|
57
|
+
except Exception:
|
|
58
|
+
pass
|
|
52
59
|
return {
|
|
53
60
|
"hookSpecificOutput": {
|
|
54
61
|
"hookEventName": "SessionStart",
|
package/hooks/pre_tool_use.py
CHANGED
|
@@ -144,6 +144,30 @@ def _handle(payload: dict) -> dict:
|
|
|
144
144
|
response["reason"] = quota["warning"]
|
|
145
145
|
return response
|
|
146
146
|
|
|
147
|
+
# Step 3-Image: Downscale oversized vision images (>1024px)
|
|
148
|
+
if path and os.path.exists(path) and path.lower().endswith((".png", ".jpg", ".jpeg", ".webp")):
|
|
149
|
+
try:
|
|
150
|
+
from src.image_downscale import ImageDownscaler
|
|
151
|
+
opt_res = ImageDownscaler.optimize(path, max_edge=1024)
|
|
152
|
+
if opt_res.get("success") and opt_res.get("was_downscaled"):
|
|
153
|
+
response["overwrite"] = {path_key: opt_res["optimized_path"]}
|
|
154
|
+
response["reason"] = f"Token Optimizer: Downscaled image to {opt_res['new_dimensions']} (Saved ~{opt_res['saved_tokens']} vision tokens)"
|
|
155
|
+
tracker.record_event(
|
|
156
|
+
session_id=conversation_id,
|
|
157
|
+
event_type="IMAGE_DOWNSCALE",
|
|
158
|
+
original_tokens=opt_res.get("saved_tokens", 0) + 300,
|
|
159
|
+
optimized_tokens=300,
|
|
160
|
+
details={
|
|
161
|
+
"target_file": os.path.basename(path),
|
|
162
|
+
"orig_dim": opt_res.get("orig_dimensions"),
|
|
163
|
+
"new_dim": opt_res.get("new_dimensions"),
|
|
164
|
+
"saved_tokens": opt_res.get("saved_tokens")
|
|
165
|
+
}
|
|
166
|
+
)
|
|
167
|
+
return response
|
|
168
|
+
except Exception:
|
|
169
|
+
pass
|
|
170
|
+
|
|
147
171
|
# Step 3A: If model explicitly specified line range, respect it
|
|
148
172
|
if start_line is not None and end_line is not None:
|
|
149
173
|
return response
|
package/hooks/session_start.py
CHANGED
|
@@ -97,6 +97,14 @@ def main():
|
|
|
97
97
|
except Exception:
|
|
98
98
|
pass
|
|
99
99
|
|
|
100
|
+
try:
|
|
101
|
+
from src.mistakes import MistakesLedger
|
|
102
|
+
mistake_guard = MistakesLedger.get_guard_prompt(project_root=workspace_root)
|
|
103
|
+
if mistake_guard:
|
|
104
|
+
inject_steps.append({"systemMessage": {"systemMessage": mistake_guard, "metadata": {}}})
|
|
105
|
+
except Exception:
|
|
106
|
+
pass
|
|
107
|
+
|
|
100
108
|
print(json.dumps({"injectSteps": inject_steps}))
|
|
101
109
|
|
|
102
110
|
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"mcpName": "dev.tokensafe/tokensafe",
|
|
4
|
-
"version": "
|
|
4
|
+
"version": "4.0.0",
|
|
5
5
|
"description": "Make AI coding agents 3x faster without burning team quotas. Exact code context. Fewer tokens. Safer changes.",
|
|
6
6
|
"main": "bin/tokensafe.js",
|
|
7
7
|
"bin": {
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
"bin/tokensafe.js",
|
|
12
12
|
"bin/tokensafe",
|
|
13
13
|
"bin/agy-tokens",
|
|
14
|
-
"src
|
|
14
|
+
"src/",
|
|
15
15
|
"!src/cloud_backend.py",
|
|
16
16
|
"!src/mailer.py",
|
|
17
17
|
"!**/__pycache__/**",
|
package/plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"displayName": "TokenSafe",
|
|
4
|
-
"version": "
|
|
4
|
+
"version": "4.0.0",
|
|
5
5
|
"description": "Reduce your AI bills by up to 99% locally. Your agents read only needed code, keep prompt caches intact across turns, and keep secrets out of git.",
|
|
6
6
|
"logo": "assets/logo.svg",
|
|
7
7
|
"author": {
|
package/rules/AGENTS.md
CHANGED
|
@@ -29,13 +29,19 @@ Execute the specified action directly based on these extracted parameters.
|
|
|
29
29
|
|
|
30
30
|
### 3. Architecture & Code Navigation Directives (Graph-Guided)
|
|
31
31
|
1. **Zero Raw Terminal Grep/Find (Blocked & Replaced by `scoped_search`)**: Strictly NEVER execute terminal `grep`, `egrep`, `ripgrep`, or `find` on source code files or directories (`src/`, `views/`, `components/`, `.ts`, `.tsx`, `.py`, `.js`). These commands are hard-blocked by TokenSafe Guard. To search for text, symbols, or functions across unknown files, ALWAYS call `tokensafe:scoped_search(query, path=".", scope="code")`. The `path` parameter accepts the project root or subfolder (`"."`, `"./src"`), and `scope` accepts file categories (`"code"`, `"config"`, `"all"`), file extensions (`"go"`, `"ts"`), or subfolders (`"internal/promo"`).
|
|
32
|
-
2. **Mandatory Symbol & Component Inspection**: Whenever locating or reading a function, class, component, or method, ALWAYS call `tokensafe:smart_read_file` with `path` (relative e.g. `"src/service.ts"` or absolute) and `symbol`. By default (`dep_mode="signature"`), it preserves the full executable target and compact 1-line 1-hop dependency signatures while folding inert code (-95%+ tokens). Pass `dep_mode="full"` only when dependency bodies are needed, or `force_full=true` if a cache pointer references content missing from your context. When you need 3+ related symbols across several files, call `tokensafe:smart_bundle(targets=[{path, symbol}])` ONCE instead of repeated `smart_read_file` calls โ it merges the skeletons and deduplicates shared imports/types in a single roundtrip. For OpenAPI/Prisma/GraphQL/SQL schema files `smart_read_file` auto-slices: pass the spec path/model/type/table as `symbol` (empty `symbol` returns a compact overview).
|
|
33
|
-
3. **
|
|
34
|
-
4. **
|
|
35
|
-
5. **
|
|
36
|
-
6. **
|
|
37
|
-
7. **
|
|
38
|
-
8. **
|
|
32
|
+
2. **Mandatory Symbol & Component Inspection**: Whenever locating or reading a function, class, component, or method, ALWAYS call `tokensafe:smart_read_file` with `path` (relative e.g. `"src/service.ts"` or absolute) and `symbol`. By default (`dep_mode="signature"`), it preserves the full executable target and compact 1-line 1-hop dependency signatures while folding inert code (-95%+ tokens). Pass `dep_mode="full"` only when dependency bodies are needed, or `force_full=true` if a cache pointer references content missing from your context. When you need 3+ related symbols across several files, call `tokensafe:smart_bundle(targets=[{path, symbol}])` ONCE instead of repeated `smart_read_file` calls โ it merges the skeletons and deduplicates shared imports/types in a single roundtrip. For OpenAPI/Prisma/GraphQL/SQL schema files `smart_read_file` auto-slices: pass the spec path/model/type/table as `symbol` (empty `symbol` returns a compact overview). Lockfiles (`package-lock.json`, `Cargo.lock`) and tabular data (`.csv`, `.tsv`, `.sql`, `.har`) auto-reduce to compact schemas with reversible hash anchors.
|
|
33
|
+
3. **Reversible Hash Stashing (`expand_ref`)**: Whenever TokenSafe folds a long command output, test log, file, or MCP payload, it tags it with an 8-character hash `[TokenSafe folded: #a1b2c3d4 ...]`. If full raw content is ever needed, ALWAYS call `tokensafe:expand_ref(hash="a1b2c3d4")` or run `tokensafe expand-ref a1b2c3d4` to retrieve the exact original bytes without re-running.
|
|
34
|
+
4. **Web & Documentation Reading (`read_web_page`)**: To read web pages, documentation, or API references, ALWAYS call `tokensafe:read_web_page(url)` or run `tokensafe web <url>` instead of raw HTML fetches โ it strips scripts, styles, navbars, and cookie banners (-80-95% tokens).
|
|
35
|
+
5. **Architecture Discovery**: Before executing multi-file exploration, ALWAYS call `tokensafe:get_architecture_graph(project_path=".")` to locate God Nodes and dependency topology in < 250 tokens without file crawling (`project_path` defaults to active workspace).
|
|
36
|
+
6. **API Surface Map**: Use `tokensafe:get_api_surface(project_path=".")` to get all exported classes, types, and interfaces in a single markdown map without crawling files.
|
|
37
|
+
7. **Bounded Reads**: Never call `read_file` without `StartLine`/`EndLine` on files > 100 lines unless inspecting a skeleton.
|
|
38
|
+
8. **Directory Navigation**: Never run verbose `ls -la` or `ls -l`; use `tokensafe:list_dir(path=".", depth=2)` to inspect directory trees without permissions, timestamps, or lockfiles (-90% tokens). Supports relative subfolders (`path="src"`).
|
|
39
|
+
9. **Style & Design Tokens**: When inspecting CSS/SCSS/LESS/Tailwind, `tokensafe:smart_read_file` automatically preserves all design tokens (`:root`, `@theme`, CSS variables) in full while folding component selectors.
|
|
40
|
+
10. **Command Output Wrapping & Test Execution**: Run noisy commands and test suites via `tokensafe wrap '<command>'` or `tokensafe tests [cmd]`. Passing tests return a 1-line summary (`โ PASS: ...`), and failures return focused failure blocks with full tracebacks preserved in stash.
|
|
41
|
+
11. **Context Budget & Smart Compaction**: Before large multi-step tasks, call `tokensafe:context_budget(model=...)` to check window usage (tools/history/prompts breakdown, 50/80/95% thresholds). When it reports `warning` or `critical`, call `tokensafe:compact_conversation(transcript_path=...)` to fold past turns into a State Ledger instead of letting code quality degrade.
|
|
42
|
+
12. **Vision Image Optimization (`optimize_image`)**: When handling screenshots or visual diagrams, call `tokensafe:optimize_image` or run `tokensafe optimize-image <file>` to downscale images exceeding 1024px (-50-75% vision tokens) while preserving original disk files.
|
|
43
|
+
13. **Superseded Output Pruning (`prune_superseded`)**: In long multi-turn sessions, prune obsolete intermediate file reads via `tokensafe:prune_superseded(transcript_path)` to free up context without losing history.
|
|
44
|
+
14. **Anti-Stuck Revert Memory (`get_mistakes`)**: Consult `tokensafe:get_mistakes` to retrieve persistent records of prior dead-ends, loop guard trips, and git reverts to avoid attempting previously failed solutions.
|
|
39
45
|
|
|
40
46
|
### 4. Turn Token Savings Footer (Proof-of-Savings โ always in English)
|
|
41
47
|
At the end of your response for any turn where tools were executed, files were inspected, commands were sanitized, or prompts were compacted, append a compact 1-line footer:
|
package/server.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "dev.tokensafe/tokensafe",
|
|
4
4
|
"title": "TokenSafe",
|
|
5
5
|
"description": "Reduce your AI bills by up to 99% locally: focused code, warm prompt caches & zero secret leaks.",
|
|
6
|
-
"version": "
|
|
6
|
+
"version": "4.0.0",
|
|
7
7
|
"websiteUrl": "https://tokensafe.dev",
|
|
8
8
|
"repository": {
|
|
9
9
|
"url": "https://github.com/tokensafe-dev/tokensafe",
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
"registryType": "npm",
|
|
31
31
|
"registryBaseUrl": "https://registry.npmjs.org",
|
|
32
32
|
"identifier": "tokensafe",
|
|
33
|
-
"version": "
|
|
33
|
+
"version": "4.0.0",
|
|
34
34
|
"runtimeHint": "npx",
|
|
35
35
|
"transport": {
|
|
36
36
|
"type": "stdio"
|
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
"registryType": "pypi",
|
|
47
47
|
"registryBaseUrl": "https://pypi.org",
|
|
48
48
|
"identifier": "tokensafe",
|
|
49
|
-
"version": "
|
|
49
|
+
"version": "4.0.0",
|
|
50
50
|
"runtimeHint": "uvx",
|
|
51
51
|
"transport": {
|
|
52
52
|
"type": "stdio"
|
|
@@ -76,12 +76,17 @@ The full tool table with efficiency impact, JSON workflow examples, the Guard ch
|
|
|
76
76
|
Quick pointers:
|
|
77
77
|
|
|
78
78
|
- Search: `tokensafe:scoped_search(query, path=".", scope="code")` โ safe keyword & symbol search, never raw grep.
|
|
79
|
-
- Inspect: `tokensafe:smart_read_file(path, symbol)` โ definition + 1-hop deps.
|
|
79
|
+
- Inspect: `tokensafe:smart_read_file(path, symbol)` โ definition + 1-hop deps. Auto-slices lockfiles, CSV/TSV, SQL dumps.
|
|
80
|
+
- Expand Stash: `tokensafe:expand_ref(hash)` โ restore full raw content of any folded block by its 8-char hash (e.g. 'a1b2c3d4').
|
|
81
|
+
- Web Reading: `tokensafe:read_web_page(url)` โ fetch documentation/articles as clean Markdown without HTML/script junk.
|
|
80
82
|
- Bundle: `tokensafe:smart_bundle(targets=[{path, symbol}])` โ 3-8 related symbols across files in one call, shared imports deduplicated.
|
|
81
83
|
- Navigate: `tokensafe:get_architecture_graph(project_path)` / `tokensafe:get_api_surface(project_path)`.
|
|
82
84
|
- Directory: `tokensafe:list_dir(path, depth=2)` โ clean tree, never verbose `ls -la`.
|
|
83
|
-
- Terminal: `tokensafe:sanitize_command(command, cwd)`
|
|
85
|
+
- Terminal: `tokensafe:sanitize_command(command, cwd)` or run via `tokensafe wrap '<cmd>'`.
|
|
84
86
|
- Context: `tokensafe:compact_conversation(transcript_path)` / `tokensafe:context_budget`.
|
|
87
|
+
- Vision: `tokensafe:optimize_image(image_path, max_edge=1024)` โ downscale images >1024px (-50-75% vision tokens).
|
|
88
|
+
- Prune Reads: `tokensafe:prune_superseded(transcript_path)` โ drops obsolete intermediate file reads (-30-40% context).
|
|
89
|
+
- Anti-Stuck: `tokensafe:get_mistakes(project_root)` โ persistent memory of prior dead-ends and git reverts.
|
|
85
90
|
|
|
86
91
|
---
|
|
87
92
|
|
|
@@ -15,6 +15,8 @@ tokensafe tests [pytest] # Run the unit test suite (compact failure report;
|
|
|
15
15
|
tokensafe graph [path] # Inspect God Nodes and centrality ranking
|
|
16
16
|
tokensafe map [path] # Generate tokensafe-out/API_SURFACE.md
|
|
17
17
|
tokensafe skeleton <file> # View AST skeleton for a specific file
|
|
18
|
+
tokensafe search "<query>" # Sub-millisecond SQLite FTS5 BM25-ranked code search
|
|
19
|
+
tokensafe index [path] # Build/update incremental FTS5 trigram full-text index
|
|
18
20
|
|
|
19
21
|
# Multi-Agent Ecosystem Management
|
|
20
22
|
tokensafe install # Interactive agent installer (Cursor, Windsurf, Claude, etc.)
|
|
@@ -24,7 +26,15 @@ tokensafe update # One-click self-update & multi-agent re-synchroni
|
|
|
24
26
|
# System Health & Hygiene
|
|
25
27
|
tokensafe guard "<command>" # Pre-flight check command safety (rm, secrets, grep)
|
|
26
28
|
tokensafe guard audit [path] # Recursively audit project files for security violations
|
|
27
|
-
tokensafe doctor
|
|
29
|
+
tokensafe doctor [--cleanup] # Audit MCP tool overhead, token tax & clean competitor conflicts
|
|
30
|
+
tokensafe expand-ref <hash> # Restore original raw content of any folded block by its 8-char hash
|
|
31
|
+
tokensafe wrap "<cmd>" # Run noisy command with compact output folding (e.g. tests, tsc, builds)
|
|
32
|
+
tokensafe web <url> # Fetch web page/docs and print clean compact Markdown
|
|
33
|
+
tokensafe optimize-image <img># Downscale oversized screenshot to max 1024px (-50-75% vision tokens)
|
|
34
|
+
tokensafe prune-superseded <t># Prune outdated intermediate reads from conversation transcript
|
|
35
|
+
tokensafe mistakes [list] # Inspect persistent dead-ends, git reverts & anti-stuck prompt guard
|
|
36
|
+
tokensafe mcp wrap [--all] # Wrap third-party MCP servers behind tokensafe mcp-proxy
|
|
37
|
+
tokensafe mcp unwrap [--all] # Restore third-party MCP servers to direct execution
|
|
28
38
|
tokensafe prune # Compact metrics database and prune old events
|
|
29
39
|
tokensafe vacuum # Reclaim SQLite database disk space
|
|
30
40
|
tokensafe test "<prompt>" # Test TOCP S-expression prompt compaction
|
|
@@ -4,9 +4,11 @@ All tools are exposed via Model Context Protocol (stdio JSON-RPC 2.0).
|
|
|
4
4
|
|
|
5
5
|
| MCP Tool | Description | 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. | **-90% to -98%** token reduction |
|
|
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 |
|
|
8
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 |
|
|
9
|
-
| `tokensafe:scoped_search` | Safe, token-bounded keyword, symbol, or config search across the codebase (supports `path='.'`, `scope='code'`/`'config'`/`'all'`/file extension/subfolder
|
|
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 |
|
|
10
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` |
|
|
11
13
|
| `tokensafe:get_architecture_graph` | Computes dependency topology, hub centrality, and identifies top God Nodes for `project_path`. | **~200 tokens** (replaces 50k crawl) |
|
|
12
14
|
| `tokensafe:get_api_surface` | Generates a compact markdown map of all exported types, interfaces, and classes. | **~500 tokens** for entire project |
|
|
@@ -16,6 +18,9 @@ All tools are exposed via Model Context Protocol (stdio JSON-RPC 2.0).
|
|
|
16
18
|
| `tokensafe:compact_conversation` | On-demand context compaction: folds a long JSONL session transcript into a lean Consolidated State Ledger (`transcript_path`, optional `invocation_num`). Call when the context window feels heavy or before a new subtask. | **-80% to -95%** history tokens |
|
|
17
19
|
| `tokensafe:context_budget` | Context Budget HUD: estimated window usage (`model`/`window_tokens`/`session_id`) with tools/history/prompts breakdown and 50/80/95% thresholds. Call before deciding to compact. | Floor estimate, always labeled estimated |
|
|
18
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** |
|
|
19
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 |
|
|
20
25
|
|
|
21
26
|
---
|
|
@@ -123,3 +128,40 @@ All tools are exposed via Model Context Protocol (stdio JSON-RPC 2.0).
|
|
|
123
128
|
}
|
|
124
129
|
```
|
|
125
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
|
+
|
|
132
|
+
### 7. Vision Image Optimizer (`optimize_image`)
|
|
133
|
+
```json
|
|
134
|
+
{
|
|
135
|
+
"ServerName": "tokensafe",
|
|
136
|
+
"ToolName": "optimize_image",
|
|
137
|
+
"Arguments": {
|
|
138
|
+
"image_path": "/path/to/screenshot.png",
|
|
139
|
+
"max_edge": 1024
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
```
|
|
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
|
+
```json
|
|
147
|
+
{
|
|
148
|
+
"ServerName": "tokensafe",
|
|
149
|
+
"ToolName": "prune_superseded",
|
|
150
|
+
"Arguments": {
|
|
151
|
+
"transcript_path": "/path/to/transcript.jsonl"
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
```
|
|
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
|
+
```json
|
|
159
|
+
{
|
|
160
|
+
"ServerName": "tokensafe",
|
|
161
|
+
"ToolName": "get_mistakes",
|
|
162
|
+
"Arguments": {
|
|
163
|
+
"project_root": "."
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
```
|
|
167
|
+
*Retrieves active dead-ends, failed hypotheses, and git reverts to prevent agents from attempting known failing solutions.*
|