tokensafe 2.4.3 → 2.5.1
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 +36 -16
- package/hooks/claude_code_hook.py +42 -7
- package/hooks/pre_invocation.py +57 -39
- package/hooks/pre_tool_use.py +5 -4
- package/package.json +2 -2
- package/plugin.json +2 -2
- package/rules/AGENTS.md +1 -1
- package/server.json +4 -4
- package/skills/token-optimizer/SKILL.md +15 -3
- package/skills/token-optimizer/references/mcp-tools.md +3 -3
- package/src/adapter_core.py +3 -1
- package/src/agent_firewall.py +82 -40
- package/src/benchmark.py +479 -124
- package/src/cache_normalizer.py +165 -46
- package/src/cli.py +6 -2
- package/src/dashboard.py +10 -4
- package/src/distiller_cache.py +177 -13
- package/src/governor.py +165 -104
- package/src/graph_engine.py +45 -8
- package/src/installer.py +3 -2
- package/src/license_manager.py +90 -26
- package/src/mcp_server.py +218 -39
- package/src/metrics.py +145 -15
- package/src/proxy.py +96 -50
- package/src/skeletonizer.py +70 -3
- package/src/telemetry_sync.py +36 -14
- package/src/version_checker.py +1 -1
package/README.md
CHANGED
|
@@ -6,10 +6,10 @@
|
|
|
6
6
|
<!-- mcp-name: dev.tokensafe/tokensafe -->
|
|
7
7
|
|
|
8
8
|
<p align="center">
|
|
9
|
-
<b>Local-First
|
|
10
|
-
Reduce your AI bills by up to
|
|
11
|
-
|
|
12
|
-
|
|
9
|
+
<b>Local-First Context Control, Prompt Caching & Secret Guardrails for Coding Agents</b><br>
|
|
10
|
+
Reduce your AI bills by up to 99%. Let your team ship clean code faster and cheaper.<br>
|
|
11
|
+
Your coding agents read only the code each task needs and keep prompt caches intact across turns. Everything runs locally on your machine, so your team fixes fewer broken edits and keeps secrets out of git.<br>
|
|
12
|
+
Works with <b>Cursor, Claude Code, Codex, Windsurf, Google Antigravity, Gemini CLI, and ChatGPT</b>.
|
|
13
13
|
</p>
|
|
14
14
|
|
|
15
15
|
<p align="center">
|
|
@@ -186,22 +186,42 @@ Deeper mechanics (language matrix, context tax math, cache tiers, governor) live
|
|
|
186
186
|
|
|
187
187
|
## Benchmarks
|
|
188
188
|
|
|
189
|
-
Reference run across
|
|
189
|
+
Reference run across 10 production engineering scenarios (`169,761` baseline tokens down to `8,173` tokens, **`-95.2%`** net context reduction, **`-99.4%`** peak single-scenario reduction, `+30.6%` turn latency speedup with `100%` accuracy retention):
|
|
190
190
|
|
|
191
|
-
>
|
|
191
|
+
> Prompt compaction, graph topology (`SWE-06`), `dep_mode="signature"` slicing (`SWE-07`), repeat-read pointer dedup (`SWE-09`), and parametric slot cache hits (`SWE-10`) are **measured live** (`1,368` optimized tokens) while baselines (`169,761`), turn counts, and output estimates (`6,805` tokens) are modeled constants. See [METRICS.md](METRICS.md) and [BENCHMARK_REPORT.md](BENCHMARK_REPORT.md).
|
|
192
192
|
|
|
193
193
|
| Benchmark Scenario | Task Complexity | Baseline Tokens | TokenSafe Tokens | Reduction | Turn Speedup | Accuracy |
|
|
194
194
|
|---|---|---|---|---|---|---|
|
|
195
|
-
| **Zero-Token Architecture Discovery** |
|
|
196
|
-
| **
|
|
197
|
-
| **Monorepo Lockfile
|
|
198
|
-
| **
|
|
199
|
-
| **
|
|
200
|
-
| **
|
|
201
|
-
| **
|
|
202
|
-
| **
|
|
203
|
-
|
|
204
|
-
|
|
195
|
+
| **SWE-06: Zero-Token Architecture Discovery** | God Node indexing vs. crawl | 49,716 | **312** | **-99.4%** | **6 → 1 turns (+83%)** | 100% Pass |
|
|
196
|
+
| **SWE-09: Repeat-Read Pointer Dedup** | `AgentFirewall` unchanged pointer | 17,388 | **208** | **-98.8%** | **2 → 1 turns (+50%)** | 100% Pass |
|
|
197
|
+
| **SWE-03: Monorepo Lockfile Git Diff** | Monorepo branch diff | 18,911 | **761** | **-96.0%** | 2 turns | 100% Pass |
|
|
198
|
+
| **SWE-07: Graph-Guided AST Symbol Slicing** | `dep_mode="signature"` + collapsed imports | 26,023 | **1,194** | **-95.4%** | **4 → 2 turns (+50%)** | 100% Pass |
|
|
199
|
+
| **SWE-10: Parametric Distillation Slot Cache** | Slot template hit (`0` LLM tokens) | 2,814 | **133** | **-95.3%** | **2 → 1 turns (+50%)** | 100% Pass |
|
|
200
|
+
| **SWE-08: Monorepo Lockfile Grep Leak** | `git grep` across lockfiles | 10,111 | **491** | **-95.1%** | 2 turns | 100% Pass |
|
|
201
|
+
| **SWE-01: Race Condition / Distributed Lock** | AST query & Redis redlock | 5,046 | **414** | **-91.8%** | **4 → 3 turns (+25%)** | 100% Pass |
|
|
202
|
+
| **SWE-05: Multi-Turn History Compaction** | 8-turn session history fold | 31,010 | **3,130** | **-89.9%** | 8 turns | 100% Pass |
|
|
203
|
+
| **SWE-02: OAuth JWT Expiration Triage** | Controller bug investigation | 3,733 | **403** | **-89.2%** | **3 → 2 turns (+33%)** | 100% Pass |
|
|
204
|
+
| **SWE-04: CI Test Failure Extraction** | Full test log & stack trace | 5,009 | **1,127** | **-77.5%** | 3 turns | 100% Pass |
|
|
205
|
+
|
|
206
|
+
### Why "Up to 99%" (Multiplicative Math & Honest Boundaries)
|
|
207
|
+
|
|
208
|
+
TokenSafe combines two multiplicative savings layers rather than relying on AST compression alone:
|
|
209
|
+
|
|
210
|
+
1. **Context Token Reduction (-85% to -99.4%):** Graph-guided `dep_mode="signature"` keeps only the edited symbol body intact while collapsing imports and 1-hop dependency implementations into signatures (`-95.4%` in `SWE-07`), Architecture Discovery maps repos in `< 350` tokens vs. full crawls (`-99.4%` in `SWE-06`), and repeat reads resolve to ~75-token integrity pointers (`-98.8%` in `SWE-09`, or `-99.56%` on raw file re-reads).
|
|
211
|
+
2. **KV-Cache Prefix Locking (`90.8%` hit rate at `0.10x` cached-read rate):** The Append-Only Epoch Governor (`ContextGovernor`) freezes history prefixes monotonically up to 80% of the model context window while `PromptCacheNormalizer` strips volatile metadata, sorts tool schemas, and injects provider `cache_control` breakpoints / `prompt_cache_key`. In a live 20-turn replay over `src/*.py` (`BENCHMARK_REPORT.md`):
|
|
212
|
+
|
|
213
|
+
| Multi-Turn 20-Turn Replay Metric | Value | Comparison |
|
|
214
|
+
|---|---|---|
|
|
215
|
+
| **Byte-Identical KV-Cache Prefix Hit Rate** | **`90.8%`** | `535,491 / 589,846` input tokens |
|
|
216
|
+
| **20-Turn Context Input Tokens** | **`-84.6%`** | `3,837,648` ➔ `589,846` |
|
|
217
|
+
| **Claude Sonnet 4.5 Input Bill (vs. Uncached)** | **`-96.8%`** | Cached input reads @ `$0.30/M` (`0.10x`) |
|
|
218
|
+
| **Claude Sonnet 4.5 Total Bill (vs. Uncached)** | **`-96.6%`** | `$11.6779` ➔ `$0.4005` (includes uncached `$15/M` outputs) |
|
|
219
|
+
| **Claude Sonnet 4.5 Total Bill (vs. Naive Mid-Trim Cache)** | **`-84.6%`** | `$2.5984` ➔ `$0.4005` |
|
|
220
|
+
| **DeepSeek V3 Total Bill (vs. Uncached)** | **`-96.9%`** | Cached reads `$0.028/M` (`0.10x`), outputs `$1.10/M` |
|
|
221
|
+
|
|
222
|
+
**Honest bounds:** When `~85–95%` fewer context tokens combine with a `90%+` KV-cache hit rate billed at `0.10x`, cached input spend approaches **1–2% of uncached cost (up to ~99% savings)** on graph-first, repeat-read, and cache-warm workflows. Total session invoices typically fall **80–97%** because newly generated output tokens and first-turn cache writes are never discounted by KV-caching.
|
|
223
|
+
|
|
224
|
+
> **How to read these numbers:** this benchmark is a **simulated** harness. Compression ratios and 20-turn KV-prefix byte matches are computed live from real files, while baselines and turn speedups are modeled. Production events in TokenSafe are explicitly labeled `measured` or `estimated` (see [METRICS.md](METRICS.md)).
|
|
205
225
|
|
|
206
226
|
## Metrics Honesty
|
|
207
227
|
|
|
@@ -40,16 +40,51 @@ def handle(event: str, payload: dict) -> dict:
|
|
|
40
40
|
VersionChecker.notify_os_update_background()
|
|
41
41
|
except Exception:
|
|
42
42
|
pass
|
|
43
|
+
extra = TOKENSAFE_DIRECTIVES
|
|
44
|
+
try:
|
|
45
|
+
from src.metrics import MetricsTracker
|
|
46
|
+
from src.license_manager import LicenseManager
|
|
47
|
+
quota = LicenseManager.check_quota(MetricsTracker())
|
|
48
|
+
if quota.get("warning"):
|
|
49
|
+
extra = f"{extra}\n\n{quota['warning']}"
|
|
50
|
+
except Exception:
|
|
51
|
+
pass
|
|
43
52
|
return {
|
|
44
53
|
"hookSpecificOutput": {
|
|
45
54
|
"hookEventName": "SessionStart",
|
|
46
|
-
"additionalContext":
|
|
55
|
+
"additionalContext": extra,
|
|
47
56
|
}
|
|
48
57
|
}
|
|
49
58
|
|
|
50
59
|
if event == "UserPromptSubmit":
|
|
51
60
|
prompt = str(payload.get("prompt") or "")
|
|
52
61
|
parts = []
|
|
62
|
+
quota = {"is_quota_exceeded": False, "warning": None}
|
|
63
|
+
tracker = None
|
|
64
|
+
try:
|
|
65
|
+
from src.metrics import MetricsTracker
|
|
66
|
+
from src.license_manager import LicenseManager
|
|
67
|
+
tracker = MetricsTracker()
|
|
68
|
+
quota = LicenseManager.check_quota(tracker)
|
|
69
|
+
except Exception:
|
|
70
|
+
pass
|
|
71
|
+
|
|
72
|
+
if quota.get("is_quota_exceeded"):
|
|
73
|
+
try:
|
|
74
|
+
from src.license_manager import LicenseManager
|
|
75
|
+
if LicenseManager.should_emit_quota_banner(tracker, session_id, every_n_turns=5) and quota.get("warning"):
|
|
76
|
+
parts.append(quota["warning"])
|
|
77
|
+
except Exception:
|
|
78
|
+
pass
|
|
79
|
+
if parts:
|
|
80
|
+
return {
|
|
81
|
+
"hookSpecificOutput": {
|
|
82
|
+
"hookEventName": "UserPromptSubmit",
|
|
83
|
+
"additionalContext": "\n\n".join(parts),
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return {}
|
|
87
|
+
|
|
53
88
|
context, meta = compact_for_injection(prompt, AGENT, session_id)
|
|
54
89
|
if context and meta.get("compacted"):
|
|
55
90
|
parts.append(
|
|
@@ -92,12 +127,12 @@ def handle(event: str, payload: dict) -> dict:
|
|
|
92
127
|
optimized_tokens=folded_tok,
|
|
93
128
|
details={"turns": turn, "total_accum_orig": orig_hist, "agent": AGENT},
|
|
94
129
|
)
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
130
|
+
parts.append(
|
|
131
|
+
f"{folded}\n"
|
|
132
|
+
f"(TokenSafe History Compactor: stabilized {orig_hist:,} tokens "
|
|
133
|
+
f"of previous turns — saved {stats['saved_tokens']:,}. "
|
|
134
|
+
f"Estimated per METRICS.md.)"
|
|
135
|
+
)
|
|
101
136
|
except Exception:
|
|
102
137
|
pass
|
|
103
138
|
|
package/hooks/pre_invocation.py
CHANGED
|
@@ -85,11 +85,21 @@ def main():
|
|
|
85
85
|
# once per session by session_start.py, not on every turn here.
|
|
86
86
|
quota = LicenseManager.check_quota(tracker)
|
|
87
87
|
|
|
88
|
-
# 2. Prompt Compaction (
|
|
88
|
+
# 2. Prompt Compaction (Paused completely once 500k Community measured quota is reached).
|
|
89
89
|
# Skipped while the proxy is in the loop: it already replaced the prompt.
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
90
|
+
is_quota_exceeded = bool(quota.get("is_quota_exceeded", False))
|
|
91
|
+
if is_quota_exceeded:
|
|
92
|
+
if LicenseManager.should_emit_quota_banner(tracker, conversation_id, every_n_turns=5) and quota.get("warning"):
|
|
93
|
+
inject_steps.append({
|
|
94
|
+
"systemMessage": {
|
|
95
|
+
"systemMessage": "",
|
|
96
|
+
"metadata": {
|
|
97
|
+
"user_markdown": quota["warning"]
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
})
|
|
101
|
+
elif last_user_input and len(last_user_input.strip()) >= 5 and not _proxy_is_active():
|
|
102
|
+
compaction = PromptCompactor.compact(last_user_input, enable_deepseek=True)
|
|
93
103
|
saved_tokens = compaction["saved_tokens"]
|
|
94
104
|
reduction_pct = compaction["reduction_pct"]
|
|
95
105
|
|
|
@@ -110,16 +120,10 @@ def main():
|
|
|
110
120
|
}
|
|
111
121
|
)
|
|
112
122
|
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
)
|
|
118
|
-
else:
|
|
119
|
-
badge_markdown = (
|
|
120
|
-
f"⚡ **Token Optimizer:** Compaction active ({tier}) — saved **{saved_tokens} tokens** "
|
|
121
|
-
f"(-{reduction_pct}%) on this prompt."
|
|
122
|
-
)
|
|
123
|
+
badge_markdown = (
|
|
124
|
+
f"⚡ **Token Optimizer:** Compaction active ({tier}) — saved **{saved_tokens} tokens** "
|
|
125
|
+
f"(-{reduction_pct}%) on this prompt."
|
|
126
|
+
)
|
|
123
127
|
|
|
124
128
|
inject_steps.append({
|
|
125
129
|
"systemMessage": {
|
|
@@ -131,7 +135,11 @@ def main():
|
|
|
131
135
|
})
|
|
132
136
|
|
|
133
137
|
# 3. Multi-turn History Compaction (Paused when community quota is exceeded)
|
|
138
|
+
# Only inject into context on first fold or >= 1500 token delta so
|
|
139
|
+
# intermediate turns do not churn prefix tokens unnecessarily.
|
|
134
140
|
folded_text = None
|
|
141
|
+
fresh_fold = False
|
|
142
|
+
orig_hist_tokens = 0
|
|
135
143
|
if not quota.get("is_quota_exceeded", False) and invocation_num >= 3 and transcript_path:
|
|
136
144
|
folded_text, orig_hist_tokens, folded_tokens, stats = HistoryCompactor.fold_transcript(
|
|
137
145
|
transcript_path, invocation_num
|
|
@@ -144,10 +152,9 @@ def main():
|
|
|
144
152
|
prev_orig = prev_event["details"].get("total_accum_orig", 0) or prev_event.get("original_tokens", 0)
|
|
145
153
|
|
|
146
154
|
delta_orig = max(0, orig_hist_tokens - prev_orig)
|
|
147
|
-
# Record first fold or incremental accumulation when delta >= 1500 tokens
|
|
148
155
|
if prev_event is None or delta_orig >= 1500:
|
|
156
|
+
fresh_fold = True
|
|
149
157
|
inc_orig = orig_hist_tokens if prev_event is None else delta_orig
|
|
150
|
-
inc_saved = max(0, inc_orig - folded_tokens)
|
|
151
158
|
tracker.record_event(
|
|
152
159
|
session_id=conversation_id,
|
|
153
160
|
event_type="HISTORY_FOLD",
|
|
@@ -162,23 +169,21 @@ def main():
|
|
|
162
169
|
}
|
|
163
170
|
)
|
|
164
171
|
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
172
|
+
hist_badge = (
|
|
173
|
+
f"⚡ **History Compactor:** Stabilized {orig_hist_tokens:,} tokens of previous turns — "
|
|
174
|
+
f"saved **{stats['saved_tokens']:,} tokens**."
|
|
175
|
+
)
|
|
169
176
|
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
177
|
+
inject_steps.append({
|
|
178
|
+
"systemMessage": {
|
|
179
|
+
"systemMessage": folded_text,
|
|
180
|
+
"metadata": {
|
|
181
|
+
"user_markdown": hist_badge
|
|
182
|
+
}
|
|
175
183
|
}
|
|
176
|
-
}
|
|
177
|
-
})
|
|
184
|
+
})
|
|
178
185
|
|
|
179
|
-
# 3b. Real history mass for the Context Budget HUD
|
|
180
|
-
# measured it when active; on early turns probe the transcript lightly
|
|
181
|
-
# so the estimate reflects the history that genuinely sits in context.
|
|
186
|
+
# 3b. Real history mass for the Context Budget HUD
|
|
182
187
|
history_mass = 0
|
|
183
188
|
if folded_text is not None:
|
|
184
189
|
history_mass = orig_hist_tokens
|
|
@@ -188,22 +193,35 @@ def main():
|
|
|
188
193
|
except Exception:
|
|
189
194
|
history_mass = 0
|
|
190
195
|
|
|
191
|
-
# 4. Adaptive Protocol Enforcement Reminder (Guard-triggered only)
|
|
192
|
-
# Full directives are injected once per session by session_start.py as a
|
|
193
|
-
# persistent systemMessage; here they are re-shown only when the guard
|
|
194
|
-
# just fired or fresh history was folded.
|
|
196
|
+
# 4. Adaptive Protocol Enforcement Reminder (Guard-triggered or fresh fold only)
|
|
195
197
|
recent_guard = tracker.get_last_event(conversation_id, "GUARD_RAW_CODE_SEARCH")
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
198
|
+
guard_unreminded = False
|
|
199
|
+
if isinstance(recent_guard, dict):
|
|
200
|
+
last_remind = tracker.get_last_event(conversation_id, "PROTOCOL_REMINDER")
|
|
201
|
+
is_valid_remind = isinstance(last_remind, dict) and last_remind.get("event_type") == "PROTOCOL_REMINDER"
|
|
202
|
+
if not is_valid_remind:
|
|
203
|
+
guard_unreminded = True
|
|
204
|
+
else:
|
|
205
|
+
reminded_id = int((last_remind.get("details") or {}).get("guard_id", 0))
|
|
206
|
+
guard_unreminded = int(recent_guard.get("id", 0)) > reminded_id
|
|
207
|
+
if fresh_fold or guard_unreminded:
|
|
201
208
|
inject_steps.append({
|
|
202
209
|
"systemMessage": {
|
|
203
210
|
"systemMessage": PROTOCOL_DIRECTIVES,
|
|
204
211
|
"metadata": {}
|
|
205
212
|
}
|
|
206
213
|
})
|
|
214
|
+
if guard_unreminded and recent_guard.get("id") is not None:
|
|
215
|
+
try:
|
|
216
|
+
tracker.record_event(
|
|
217
|
+
session_id=conversation_id,
|
|
218
|
+
event_type="PROTOCOL_REMINDER",
|
|
219
|
+
original_tokens=0,
|
|
220
|
+
optimized_tokens=0,
|
|
221
|
+
details={"guard_id": int(recent_guard["id"])},
|
|
222
|
+
)
|
|
223
|
+
except Exception:
|
|
224
|
+
pass
|
|
207
225
|
|
|
208
226
|
# 5. Context Budget HUD warning: inject once per session when the
|
|
209
227
|
# context crosses 80% of the estimated window. history_mass upgrades
|
package/hooks/pre_tool_use.py
CHANGED
|
@@ -149,6 +149,8 @@ def main():
|
|
|
149
149
|
|
|
150
150
|
if is_quota_exceeded:
|
|
151
151
|
# Free tier quota reached: pass through raw read_file without AST skeletonization
|
|
152
|
+
if LicenseManager.should_emit_quota_banner(tracker, conversation_id, every_n_turns=5) and quota.get("warning"):
|
|
153
|
+
response["reason"] = quota["warning"]
|
|
152
154
|
print(json.dumps(response))
|
|
153
155
|
return
|
|
154
156
|
|
|
@@ -259,10 +261,9 @@ def main():
|
|
|
259
261
|
response["reason"] = f"⚠️ TokenSafe Guard Warning: {guard_res.reason}"
|
|
260
262
|
|
|
261
263
|
if is_quota_exceeded:
|
|
262
|
-
# Free tier quota reached:
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
response["overwrite"] = {"CommandLine": new_cmd}
|
|
264
|
+
# Free tier quota reached: skip Pro diff/command optimization while Security Guards remain active
|
|
265
|
+
if LicenseManager.should_emit_quota_banner(tracker, conversation_id, every_n_turns=5) and quota.get("warning"):
|
|
266
|
+
response["reason"] = response.get("reason") or quota["warning"]
|
|
266
267
|
print(json.dumps(response))
|
|
267
268
|
return
|
|
268
269
|
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"mcpName": "dev.tokensafe/tokensafe",
|
|
4
|
-
"version": "2.
|
|
5
|
-
"description": "
|
|
4
|
+
"version": "2.5.1",
|
|
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
|
"main": "bin/tokensafe.js",
|
|
7
7
|
"bin": {
|
|
8
8
|
"tokensafe": "bin/tokensafe.js"
|
package/plugin.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"displayName": "TokenSafe",
|
|
4
|
-
"version": "2.
|
|
5
|
-
"description": "
|
|
4
|
+
"version": "2.5.1",
|
|
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": {
|
|
8
8
|
"name": "Oleg Savelev",
|
package/rules/AGENTS.md
CHANGED
|
@@ -27,7 +27,7 @@ Execute the specified action directly based on these extracted parameters.
|
|
|
27
27
|
|
|
28
28
|
### 3. Architecture & Code Navigation Directives (Graph-Guided)
|
|
29
29
|
1. **Zero Raw Terminal Grep/Find (Blocked)**: 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.
|
|
30
|
-
2. **Mandatory Symbol & Component Inspection**: Whenever locating or reading a function, class, component, or method, ALWAYS call `tokensafe:smart_read_file` with `path` and `symbol`.
|
|
30
|
+
2. **Mandatory Symbol & Component Inspection**: Whenever locating or reading a function, class, component, or method, ALWAYS call `tokensafe:smart_read_file` with `path` 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.
|
|
31
31
|
3. **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.
|
|
32
32
|
4. **API Surface Map**: Use `tokensafe:get_api_surface(project_path)` to get all exported classes, types, and interfaces in a single markdown map.
|
|
33
33
|
5. **Bounded Reads**: Never call `read_file` without `StartLine`/`EndLine` on files > 100 lines unless inspecting a skeleton.
|
package/server.json
CHANGED
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
|
|
3
3
|
"name": "dev.tokensafe/tokensafe",
|
|
4
4
|
"title": "TokenSafe",
|
|
5
|
-
"description": "
|
|
6
|
-
"version": "2.
|
|
5
|
+
"description": "Reduce your AI bills by up to 99% locally: focused code, warm prompt caches & zero secret leaks.",
|
|
6
|
+
"version": "2.5.1",
|
|
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": "2.
|
|
33
|
+
"version": "2.5.1",
|
|
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": "2.
|
|
49
|
+
"version": "2.5.1",
|
|
50
50
|
"runtimeHint": "uvx",
|
|
51
51
|
"transport": {
|
|
52
52
|
"type": "stdio"
|
|
@@ -24,8 +24,9 @@ folds multi-turn conversation history, slices verbose tool outputs, and guards a
|
|
|
24
24
|
|
|
25
25
|
2. **SYMBOL & COMPONENT EXTRACTION (`smart_read_file`)**:
|
|
26
26
|
- When locating or reading any function, component, class, or handler (e.g. `<LuckyWheelTab>`, `areSectorEqual`, `useWallet`), ALWAYS call `tokensafe:smart_read_file` with `path` and `symbol`.
|
|
27
|
-
- **1-Hop
|
|
28
|
-
- **
|
|
27
|
+
- **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.
|
|
28
|
+
- **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.
|
|
29
|
+
- **Result**: Preserves the exact target definition while folding surrounding inert code into clean 1-line signatures without docstrings (-85% to -98% tokens).
|
|
29
30
|
|
|
30
31
|
3. **ARCHITECTURE SURVEY BEFORE BROWSING (`get_architecture_graph`)**:
|
|
31
32
|
- Before multi-file exploration or asking where things are located, ALWAYS call `tokensafe:get_architecture_graph(project_path)`.
|
|
@@ -72,7 +73,7 @@ For long-running autonomous sessions, TokenSafe actively manages context bloat:
|
|
|
72
73
|
- Preserves active file paths, modified symbols, and pending tasks while discarding transient tool output noise.
|
|
73
74
|
- **Manual trigger**: call `tokensafe:compact_conversation` with the session's `transcript_path` any time you need to shed context between subtasks — it returns the ledger JSON plus exact original/folded token counts.
|
|
74
75
|
2. **Subagent Deduplication Firewall**:
|
|
75
|
-
- Caches file reads across subagents
|
|
76
|
+
- Caches file reads across subagents and sessions using SHA-256 content hashes. Interactive MCP clients receive self-healing pointer hits on unchanged repeat reads inside the same session; fresh subagents or post-compaction callers recover automatically with `force_full=true`.
|
|
76
77
|
3. **Loop Guard**:
|
|
77
78
|
- Detects repeated identical tool calls and triggers `force_ask` to prevent runaway infinite agent loops.
|
|
78
79
|
4. **Output Token Guard**:
|
|
@@ -80,6 +81,17 @@ For long-running autonomous sessions, TokenSafe actively manages context bloat:
|
|
|
80
81
|
|
|
81
82
|
---
|
|
82
83
|
|
|
84
|
+
## LLM Prompt Cache Optimization
|
|
85
|
+
|
|
86
|
+
TokenSafe actively maximizes provider KV-cache hit rates alongside token compression:
|
|
87
|
+
|
|
88
|
+
1. **Append-Only Epoch Architecture**: In proxy mode, past messages (`messages[0..N-2]`) are never retroactively mutated within an epoch, preserving prefix cache hits. When cumulative context reaches **80% of the model's window**, an atomic Epoch Rollover consolidates deep history into a State Ledger.
|
|
89
|
+
2. **Multi-Breakpoint Cache Control**: `PromptCacheNormalizer` sorts `tools` deterministically and places Anthropic `cache_control: {"type": "ephemeral"}` across tools, static system instructions, and the penultimate completed turn; OpenAI requests receive deterministic `prompt_cache_key`.
|
|
90
|
+
3. **Deterministic Prefix Normalization**: Ephemeral timestamps, hit counters, and session IDs are stripped from static prefixes, and `AgentFirewall` headers remain byte-deterministic across hits.
|
|
91
|
+
4. **Parametric Prompt Template Caching**: `DistillationCache` extracts file paths and symbols into positional slots (`<FILE_0>`, `<SYM_0>`) so structurally identical prompts hit L1/L2/L3 caches with 0 LLM roundtrips.
|
|
92
|
+
|
|
93
|
+
---
|
|
94
|
+
|
|
83
95
|
## Proof-of-Savings Turn Footer (always in English)
|
|
84
96
|
|
|
85
97
|
At the end of any response where tools were executed, files were inspected, commands were sanitized, or prompts were compacted, append a compact 1-line footer in English:
|
|
@@ -4,7 +4,7 @@ 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
|
|
7
|
+
| `tokensafe:smart_read_file` | Graph-guided AST reader with `symbol` body retention, `dep_mode` (`signature` default / `full`), and session pointer dedup (`force_full`). | **-90% to -98%** token reduction |
|
|
8
8
|
| `tokensafe:scoped_search` | Safe, token-bounded keyword, symbol, or config search across the codebase (supports `path`, 4s safety timeout, system root protection). | **-90% to -95%** vs raw grep/find |
|
|
9
9
|
| `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` |
|
|
10
10
|
| `tokensafe:get_architecture_graph` | Computes dependency topology, hub centrality, and identifies top God Nodes for `project_path`. | **~200 tokens** (replaces 50k crawl) |
|
|
@@ -68,11 +68,11 @@ All tools are exposed via Model Context Protocol (stdio JSON-RPC 2.0).
|
|
|
68
68
|
"Arguments": {
|
|
69
69
|
"path": "/Users/.../projects/my-app/src/views/StatsView.tsx",
|
|
70
70
|
"symbol": "LuckyWheelTab",
|
|
71
|
-
"
|
|
71
|
+
"dep_mode": "signature"
|
|
72
72
|
}
|
|
73
73
|
}
|
|
74
74
|
```
|
|
75
|
-
*Extracts
|
|
75
|
+
*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.*
|
|
76
76
|
|
|
77
77
|
### 3. Public API Map Workflow
|
|
78
78
|
```json
|
package/src/adapter_core.py
CHANGED
|
@@ -29,7 +29,9 @@ TOKENSAFE_DIRECTIVES = (
|
|
|
29
29
|
"[TokenSafe Mandatory Directives]:\n"
|
|
30
30
|
"• Terminal code searches (grep/rg/find on source files) are BLOCKED by TokenSafe Guard.\n"
|
|
31
31
|
"• To search keywords, symbols, or configs: call 'tokensafe:scoped_search(query, scope)'.\n"
|
|
32
|
-
"• To inspect component or function definitions: call 'tokensafe:smart_read_file(path, symbol)'
|
|
32
|
+
"• To inspect component or function definitions: call 'tokensafe:smart_read_file(path, symbol)' "
|
|
33
|
+
"(1-hop deps default to compact signatures via dep_mode='signature'; pass dep_mode='full' only when "
|
|
34
|
+
"dependency bodies are needed, or force_full=true if a cache pointer references content missing from context).\n"
|
|
33
35
|
"• To locate dependencies & God Nodes: call 'tokensafe:get_architecture_graph(project_path)'.\n"
|
|
34
36
|
"• To inspect all exported types/interfaces: call 'tokensafe:get_api_surface(project_path)'.\n"
|
|
35
37
|
"• Before large multi-step tasks: call 'tokensafe:context_budget(model=...)' to check the context window budget.\n"
|