tokensafe 2.9.0 → 3.0.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 CHANGED
@@ -226,6 +226,33 @@ TokenSafe combines two multiplicative savings layers rather than relying on AST
226
226
 
227
227
  > **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)).
228
228
 
229
+ ### Real-Repository Benchmark (measured on live clones)
230
+
231
+ No modeling: five popular repositories cloned at HEAD, scenarios **pre-registered before measurement** ([`src/bench_scenarios.json`](src/bench_scenarios.json)), every token counted on real bytes, and deterministic zero-loss gates that disqualify any scenario they fail:
232
+
233
+ | Repo | Scenario | Baseline tok | TokenSafe tok | Reduction | Gates |
234
+ |---|---|---:|---:|---:|:---|
235
+ | flask | Architecture discovery (hub crawl → map) | 53,237 | **176** | **-99.7%** | PASS |
236
+ | flask | Write egress (output axis, $15/M) | 7,106 | **44** | **-99.4%** | PASS |
237
+ | flask | Multi-turn + repeat reads | 45,336 | 7,628 | **-83.2%** | PASS |
238
+ | flask | Symbol read (AST skeleton) | 18,864 | 5,506 | **-70.8%** | PASS |
239
+ | flask | Raw search → scoped results | 7,967 | 523 | **-93.4%** | PASS |
240
+ | rich | Symbol read (AST skeleton) | 28,675 | 9,444 | **-67.1%** | PASS |
241
+ | rich | Architecture discovery | 76,172 | 158 | **-99.8%** | PASS |
242
+ | fastapi | Symbol read (`routing.py`, 73.7K tok) | 73,721 | 39,420 | **-46.5%** | PASS |
243
+ | fastapi | Multi-turn + repeat reads | 147,442 | 39,420 | **-73.3%** | PASS |
244
+ | httpie | Raw search → scoped results | 9,568 | 462 | **-95.2%** | PASS |
245
+ | flask | Full-suite pytest output | 6,391 | 6,391 | **0.0%** | PASS |
246
+ | fastapi | Git diff churn → slice | 416 | 393 | **-5.5%** | PASS |
247
+
248
+ Aggregate: **~670,000 measured tokens saved** per traced pass over all 5 repositories (input at `$3/M`, output axis at `$15/M`). A clean pytest suite honestly scores **0.0%** — savings are never invented. One scenario is published as **FAIL** with its reason: fastapi's test-output — fastapi's strict warning filters escalate a `pytest-asyncio` configuration deprecation into a pytest `INTERNALERROR`, so the suite cannot be collected in the bench venv; the gate rejects the output and no savings are claimed for it. Full table + raw JSON: [docs/BENCHMARK_REAL.md](docs/BENCHMARK_REAL.md) · live page: <https://tokensafe.dev/bench> · methodology post: <https://tokensafe.dev/blog/real-repo-benchmark-5-repos>. Reproduce:
249
+
250
+ ```bash
251
+ tokensafe bench --real # all 5 pre-registered repos
252
+ tokensafe bench --real --repo=pallets/flask # one repo
253
+ tokensafe bench --real --here # your current repository
254
+ ```
255
+
229
256
  ## Metrics Honesty
230
257
 
231
258
  TokenSafe labels every savings event as one of:
@@ -328,7 +355,8 @@ tokensafe guard audit [path] Recursive source audit for secrets & vulnera
328
355
  tokensafe doctor Audit MCP tool overhead and context token tax
329
356
  tokensafe digest [--send] Compile (and optionally dispatch) the weekly team digest
330
357
  tokensafe mcp list|disable|enable Manage configured MCP servers
331
- tokensafe proxy [port] Local transparent AI proxy (0.0.0.0:8765/v1)
358
+ tokensafe proxy [port] Local transparent AI proxy (127.0.0.1:8765/v1; host via TOKENSAFE_HOST)
359
+ tokensafe proxy on/off/status Daemon + agent wiring with one-command rollback
332
360
  tokensafe install / setup [--all] Configure detected agent environments
333
361
  tokensafe update / check-update Self-update / check for a newer version
334
362
  tokensafe activate <KEY> Activate a Team or Solo license key
@@ -343,6 +371,34 @@ tokensafe --version Print version and exit
343
371
  ```
344
372
  </details>
345
373
 
374
+ ### Proxy mode & agent coverage (v3.0.0)
375
+
376
+ One command wires everything it safely can:
377
+
378
+ ```bash
379
+ tokensafe proxy on # installs a keep-alive daemon (launchd/systemd), wires Claude Code, prints manual steps for the rest
380
+ tokensafe proxy status # health, wiring state, last traffic
381
+ tokensafe proxy off # rollback: unwires agents (previous base URL restored) and removes the daemon
382
+ ```
383
+
384
+ The daemon keeps the proxy alive on `127.0.0.1:8765`, `on` rewires agents only after a verified `/health` answer (a dead proxy never bricks an agent), and every wiring is backed up for `off`. `tokensafe install` and `tokensafe update` ask interactively whether to enable the proxy (skipped in non-TTY/scripted runs); prefer manual? Run `tokensafe proxy` in a terminal and point your agent's base URL at `http://127.0.0.1:8765` yourself:
385
+
386
+ | Agent | Route through proxy? | How |
387
+ |---|---|---|
388
+ | Claude Code | ✅ auto (`tokensafe proxy on`) | `ANTHROPIC_BASE_URL=http://127.0.0.1:8765` — the proxy ingests native Anthropic `/v1/messages` shape |
389
+ | Cline / Roo Code | ✅ manual | API Provider → OpenAI-compatible → Base URL `http://127.0.0.1:8765/v1` |
390
+ | Aider | ✅ manual | `--openai-api-base http://127.0.0.1:8765/v1` |
391
+ | Cursor (custom models) | ✅ manual | Add an OpenAI-compatible model with override base URL |
392
+ | Cursor (built-in models) | ❌ | Routed via Cursor's own backend — hooks only |
393
+ | Antigravity / ZCode | ❌ | Hooks only (lifecycle adapters) |
394
+ | Codex CLI | ❌ | stdio MCP + AGENTS.md (no proxy transport) |
395
+
396
+ What runs where:
397
+
398
+ - **Proxy-only (A/B/D)**: Tool Result Ledger (folds aged tool results in-flight, `TOKENSAFE_TOOL_LEDGER=0` to disable), session-stable cold-tool pruning (opt-in: `TOKENSAFE_TOOL_PRUNING=1`, `TOKENSAFE_TOOL_PRUNE_KEEP`, `TOKENSAFE_TOOL_PRUNE_ALLOWLIST`), managed-cloud history distillation (paid, opt-in: `TOKENSAFE_HISTORY_DISTILL=1`).
399
+ - **Hooks (all agents)**: PostToolUse stdout compaction, PreToolUse shell/secret guards, Output Guard steering full-file writes to surgical edits, prompt compaction, history folding.
400
+ - Folded originals are archived under `~/.tokensafe/data/tool_ledger/` and every fold carries a deterministic re-hydration anchor — nothing is destroyed, and already-folded results are never re-processed (KV-cache stable).
401
+
346
402
  More documentation: [docs/AGENT_SETUP.md](docs/AGENT_SETUP.md) · [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) · [docs/API.md](docs/API.md) · [METRICS.md](METRICS.md) · [BENCHMARK_REPORT.md](BENCHMARK_REPORT.md)
347
403
 
348
404
  ## Development and License
@@ -22,7 +22,7 @@ PROJECT_ROOT = os.path.dirname(HOOK_DIR)
22
22
  if PROJECT_ROOT not in sys.path:
23
23
  sys.path.insert(0, PROJECT_ROOT)
24
24
 
25
- from src.adapter_core import TOKENSAFE_DIRECTIVES, compact_for_injection, guard_command
25
+ from src.adapter_core import TOKENSAFE_DIRECTIVES, compact_for_injection, guard_command, guard_write
26
26
 
27
27
  AGENT = "claude_code"
28
28
 
@@ -170,6 +170,29 @@ def handle(event: str, payload: dict) -> dict:
170
170
  "permissionDecisionReason": verdict["reason"],
171
171
  }
172
172
  }
173
+ elif tool in ("Write", "write_file", "replace_file_content"):
174
+ # Egress economy (v3.0.0): full-file writes over existing files
175
+ # burn expensive output tokens — steer to surgical Edit instead.
176
+ file_path = str(tool_input.get("file_path") or tool_input.get("Path") or tool_input.get("path") or "")
177
+ content = tool_input.get("content") or tool_input.get("Content") or tool_input.get("file_text") or ""
178
+ append = bool(tool_input.get("append") or tool_input.get("Append") or False)
179
+ verdict = guard_write(file_path, str(content or ""), append, AGENT, session_id)
180
+ if verdict["decision"] == "deny":
181
+ return {
182
+ "hookSpecificOutput": {
183
+ "hookEventName": "PreToolUse",
184
+ "permissionDecision": "deny",
185
+ "permissionDecisionReason": verdict["reason"],
186
+ }
187
+ }
188
+ if verdict["decision"] == "ask":
189
+ return {
190
+ "hookSpecificOutput": {
191
+ "hookEventName": "PreToolUse",
192
+ "permissionDecision": "ask",
193
+ "permissionDecisionReason": verdict["reason"],
194
+ }
195
+ }
173
196
  return {}
174
197
 
175
198
  if event == "PostToolUse":
@@ -21,6 +21,7 @@ from src.loop_detector import LoopDetector
21
21
  from src.metrics import MetricsTracker
22
22
  from src.tokenizer import count_tokens
23
23
  from src.license_manager import LicenseManager
24
+ from src.adapter_core import guard_write
24
25
 
25
26
 
26
27
  def _trigger_bg_sync():
@@ -103,43 +104,17 @@ def _handle(payload: dict) -> dict:
103
104
  _trigger_bg_sync()
104
105
  return {"decision": "deny", "reason": f"🛡️ TokenSafe Guard: {guard_res.reason}"}
105
106
 
106
- # 3. Output Guard: Block write_file on large existing files to enforce edit_file
107
+ # 3. Output Guard (shared guard_write, v3.0.0): deny wholesale overwrite of
108
+ # large existing files to enforce edit_file; ask on small-delta writes.
107
109
  if tool_name == "write_file":
108
110
  raw_path = str(args.get("Path") or args.get("path") or "")
109
111
  path = _resolve_hook_path(raw_path, hook_cwd)
110
112
  content = args.get("Content", "")
111
113
  is_append = args.get("Append", False)
112
-
113
- if not is_append and path and os.path.exists(path):
114
- try:
115
- with open(path, "r", encoding="utf-8", errors="replace") as f:
116
- existing_lines = sum(1 for _ in f)
117
- except Exception:
118
- existing_lines = 0
119
-
120
- # If file already has >= 40 lines, block wholesale overwrite to save output tokens
121
- if existing_lines >= 40:
122
- content_tokens = count_tokens(content)
123
- tracker.record_event(
124
- session_id=conversation_id,
125
- event_type="OUTPUT_GUARD",
126
- original_tokens=content_tokens,
127
- optimized_tokens=80, # typical edit_file diff tokens
128
- details={
129
- "target_file": os.path.basename(path),
130
- "existing_lines": existing_lines,
131
- "saved_output_tokens": max(0, content_tokens - 80)
132
- }
133
- )
134
- _trigger_bg_sync()
135
- return {
136
- "decision": "deny",
137
- "reason": (
138
- f"Token Optimizer Output Guard: '{os.path.basename(path)}' already exists with {existing_lines} lines. "
139
- f"Wholesale rewriting via write_file burns expensive output tokens. "
140
- f"Please use 'edit_file' with surgical Target and Replacement blocks instead."
141
- )
142
- }
114
+ verdict = guard_write(path, str(content or ""), bool(is_append), "antigravity", conversation_id)
115
+ if verdict["decision"] in ("deny", "ask"):
116
+ _trigger_bg_sync()
117
+ return {"decision": verdict["decision"], "reason": verdict["reason"]}
143
118
 
144
119
  # 3. read_file Optimization (AST Windowing & Skeletonization).
145
120
  # 'view_file' is the IDE-surface name for the same tool (hooks.md) —
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "2.9.0",
4
+ "version": "3.0.1",
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
  "main": "bin/tokensafe.js",
7
7
  "bin": {
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "displayName": "TokenSafe",
4
- "version": "2.9.0",
4
+ "version": "3.0.1",
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/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": "2.9.0",
6
+ "version": "3.0.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.9.0",
33
+ "version": "3.0.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.9.0",
49
+ "version": "3.0.1",
50
50
  "runtimeHint": "uvx",
51
51
  "transport": {
52
52
  "type": "stdio"
@@ -18,6 +18,8 @@ import re
18
18
  import json
19
19
  from typing import Dict, Any, Optional, Tuple
20
20
 
21
+ from src.tokenizer import count_tokens
22
+
21
23
  PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
22
24
  if PROJECT_ROOT not in sys.path:
23
25
  sys.path.insert(0, PROJECT_ROOT)
@@ -220,3 +222,72 @@ def guard_read(file_path: str, agent: str, session_id: str = "") -> Dict[str, An
220
222
  })
221
223
  return result
222
224
  return result
225
+
226
+
227
+ def guard_write(file_path: str, content: str, append: bool = False, agent: str = "", session_id: str = "") -> Dict[str, Any]:
228
+ """Pre-write egress guard (v3.0.0): full-file Write over an existing file
229
+ burns expensive OUTPUT tokens. Policy:
230
+ - new file / append / no content -> allow
231
+ - wholesale overwrite of a >=40-line file -> deny (parity with the
232
+ Antigravity Output Guard, hooks/pre_tool_use.py)
233
+ - small delta vs the current file (<25% of lines AND <80 lines) -> ask,
234
+ steering the model to a surgical Edit instead (quality untouched).
235
+ Recorded as OUTPUT_GUARD with honest estimated output-token savings."""
236
+ result = {"decision": "allow", "reason": "", "saved_tokens": 0}
237
+ if not file_path or append or not isinstance(content, str) or not content:
238
+ return result
239
+ path = file_path.replace("\\", "/")
240
+ if not os.path.isfile(path):
241
+ return result
242
+ try:
243
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
244
+ existing_text = f.read()
245
+ except Exception:
246
+ return result
247
+ existing_lines = existing_text.splitlines()
248
+ if len(existing_lines) < 40:
249
+ return result
250
+
251
+ new_lines = content.splitlines()
252
+ import difflib
253
+ delta_lines = sum(
254
+ 1 for ln in difflib.unified_diff(existing_lines, new_lines, lineterm="", n=0)
255
+ if ln[:1] in ("+", "-") and ln[:3] not in ("+++", "---")
256
+ )
257
+ content_tokens = max(1, count_tokens(content))
258
+ edit_tokens = max(1, count_tokens("\n".join(new_lines[:80])) // 3)
259
+ tracker = _get_tracker()
260
+
261
+ def _emit(decision: str, reason: str) -> Dict[str, Any]:
262
+ if tracker:
263
+ try:
264
+ tracker.record_event(
265
+ session_id=session_id or f"hook_{agent}",
266
+ event_type="OUTPUT_GUARD",
267
+ original_tokens=content_tokens,
268
+ optimized_tokens=edit_tokens if decision == "ask" else 80,
269
+ details={
270
+ "agent": agent,
271
+ "target_file": os.path.basename(path),
272
+ "existing_lines": len(existing_lines),
273
+ "delta_lines": delta_lines,
274
+ "decision": decision,
275
+ },
276
+ )
277
+ except Exception:
278
+ pass
279
+ return {"decision": decision, "reason": reason, "saved_tokens": max(0, content_tokens - edit_tokens)}
280
+
281
+ if delta_lines < max(1, int(len(existing_lines) * 0.25)) and delta_lines < 80:
282
+ return _emit(
283
+ "ask",
284
+ f"TokenSafe Output Guard: '{os.path.basename(path)}' already exists ({len(existing_lines)} lines) "
285
+ f"and your Write is only a ~{delta_lines}-line delta. Use 'edit_file'/Edit with the exact old block "
286
+ f"instead — wholesale rewrite burns expensive output tokens (~{content_tokens} vs ~{edit_tokens}).",
287
+ )
288
+ return _emit(
289
+ "deny",
290
+ f"TokenSafe Output Guard: '{os.path.basename(path)}' already exists with {len(existing_lines)} lines. "
291
+ f"Wholesale rewriting via write_file burns expensive output tokens. "
292
+ f"Please use 'edit_file' (surgical Edit) with Target and Replacement blocks instead.",
293
+ )