tokensafe 2.8.4 → 3.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 CHANGED
@@ -328,7 +328,8 @@ tokensafe guard audit [path] Recursive source audit for secrets & vulnera
328
328
  tokensafe doctor Audit MCP tool overhead and context token tax
329
329
  tokensafe digest [--send] Compile (and optionally dispatch) the weekly team digest
330
330
  tokensafe mcp list|disable|enable Manage configured MCP servers
331
- tokensafe proxy [port] Local transparent AI proxy (0.0.0.0:8765/v1)
331
+ tokensafe proxy [port] Local transparent AI proxy (127.0.0.1:8765/v1; host via TOKENSAFE_HOST)
332
+ tokensafe proxy on/off/status Daemon + agent wiring with one-command rollback
332
333
  tokensafe install / setup [--all] Configure detected agent environments
333
334
  tokensafe update / check-update Self-update / check for a newer version
334
335
  tokensafe activate <KEY> Activate a Team or Solo license key
@@ -343,6 +344,34 @@ tokensafe --version Print version and exit
343
344
  ```
344
345
  </details>
345
346
 
347
+ ### Proxy mode & agent coverage (v3.0.0)
348
+
349
+ One command wires everything it safely can:
350
+
351
+ ```bash
352
+ tokensafe proxy on # installs a keep-alive daemon (launchd/systemd), wires Claude Code, prints manual steps for the rest
353
+ tokensafe proxy status # health, wiring state, last traffic
354
+ tokensafe proxy off # rollback: unwires agents (previous base URL restored) and removes the daemon
355
+ ```
356
+
357
+ 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:
358
+
359
+ | Agent | Route through proxy? | How |
360
+ |---|---|---|
361
+ | Claude Code | ✅ auto (`tokensafe proxy on`) | `ANTHROPIC_BASE_URL=http://127.0.0.1:8765` — the proxy ingests native Anthropic `/v1/messages` shape |
362
+ | Cline / Roo Code | ✅ manual | API Provider → OpenAI-compatible → Base URL `http://127.0.0.1:8765/v1` |
363
+ | Aider | ✅ manual | `--openai-api-base http://127.0.0.1:8765/v1` |
364
+ | Cursor (custom models) | ✅ manual | Add an OpenAI-compatible model with override base URL |
365
+ | Cursor (built-in models) | ❌ | Routed via Cursor's own backend — hooks only |
366
+ | Antigravity / ZCode | ❌ | Hooks only (lifecycle adapters) |
367
+ | Codex CLI | ❌ | stdio MCP + AGENTS.md (no proxy transport) |
368
+
369
+ What runs where:
370
+
371
+ - **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`).
372
+ - **Hooks (all agents)**: PostToolUse stdout compaction, PreToolUse shell/secret guards, Output Guard steering full-file writes to surgical edits, prompt compaction, history folding.
373
+ - 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).
374
+
346
375
  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
376
 
348
377
  ## 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,64 @@ 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
+ }
196
+ return {}
197
+
198
+ if event == "PostToolUse":
199
+ # Auto-mute noisy stdout of successful shell commands (tests/linters/builds):
200
+ # feed the model a compact summary instead of letting it parse the full dump.
201
+ # Fail-open: {} leaves the raw output untouched.
202
+ tool = str(payload.get("tool_name") or "")
203
+ compacted, orig, new = None, 0, 0
204
+ try:
205
+ from src.command_sanitizer import CommandSanitizer
206
+ res = CommandSanitizer.compact_tool_output(tool, payload.get("tool_response"))
207
+ if res:
208
+ compacted, orig, new = res
209
+ except Exception:
210
+ compacted = None
211
+ if compacted:
212
+ try:
213
+ from src.metrics import MetricsTracker
214
+ from src.tokenizer import count_tokens
215
+ MetricsTracker().record_event(
216
+ session_id=session_id,
217
+ event_type="TOOL_OUTPUT_COMPACT",
218
+ original_tokens=count_tokens(str(payload.get("tool_response") or "")),
219
+ optimized_tokens=count_tokens(compacted),
220
+ details={"agent": AGENT, "tool": tool, "chars": f"{orig}->{new}"},
221
+ )
222
+ except Exception:
223
+ pass
224
+ return {
225
+ "decision": "block",
226
+ "reason": (
227
+ f"[TokenSafe] {tool} succeeded (exit 0) — verbose stdout auto-compacted "
228
+ f"({orig:,} → {new:,} chars). Command already completed; do not retry. Summary:\n{compacted}"
229
+ ),
230
+ }
173
231
  return {}
174
232
 
175
233
  return {}
@@ -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.8.4",
4
+ "version": "3.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
  "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.8.4",
4
+ "version": "3.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/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.8.4",
6
+ "version": "3.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": "2.8.4",
33
+ "version": "3.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": "2.8.4",
49
+ "version": "3.0.0",
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
+ )
package/src/cli.py CHANGED
@@ -97,6 +97,7 @@ def _print_help():
97
97
  print("TokenSafe CLI — usage: tokensafe <command> [args]\n")
98
98
  print("Commands:")
99
99
  print(" stats / markdown / html Savings analytics (terminal / .md report / dashboard)")
100
+ print(" status One-screen health check: hooks, weekly savings, tier, sync")
100
101
  print(" benchmark Zero-context-loss benchmark suite (simulated SWE-bench harness)")
101
102
  print(" graph / map / skeleton Architecture graph / API surface / AST skeleton of a file")
102
103
  print(" test <prompt> Preview TOCP S-expression prompt compaction")
@@ -140,7 +141,67 @@ def main():
140
141
  VersionChecker.notify_os_update(force=True)
141
142
  return
142
143
 
143
- if command in ("stats", "dashboard"):
144
+ if command in ("status", "health"):
145
+ from src.installer import AgentInstaller
146
+ from src.license_manager import LicenseManager
147
+ from src.telemetry_sync import TelemetrySync
148
+ tracker = MetricsTracker()
149
+ print("\n\033[1m\033[36m⚡ TOKENSAFE STATUS ⚡\033[0m\n")
150
+ # Hooks wiring (best-effort scan of agent config files and plugin dirs)
151
+ active_agents = []
152
+ for key, info in AgentInstaller.detect_available_agents().items():
153
+ hit = any(info.get(pk) and os.path.exists(info[pk]) for pk in
154
+ ("target_path", "plugin_path", "skills_path", "agents_md_path", "rules_path", "extension_path"))
155
+ cfg = info.get("config_path")
156
+ if not hit and cfg and os.path.exists(cfg):
157
+ try:
158
+ with open(cfg, "r", encoding="utf-8", errors="replace") as f:
159
+ hit = "tokensafe" in f.read().lower()
160
+ except Exception:
161
+ pass
162
+ if hit:
163
+ active_agents.append(key)
164
+ if active_agents:
165
+ print(f" Hooks: \033[32m✔ active\033[0m in {len(active_agents)} agent(s): {', '.join(active_agents)}")
166
+ else:
167
+ print(" Hooks: \033[33m○ not detected\033[0m — run \033[1mtokensafe install\033[0m to configure your agents")
168
+ # The value moment: recent measured savings
169
+ weekly = tracker.get_weekly_saved()
170
+ print(f" This Week: \033[32m\033[1m{weekly['saved_tokens']:,} tokens saved\033[0m across {weekly['events']:,} events (≈${weekly['usd_saved']:.2f})")
171
+ # Tier + quota state
172
+ tier, payload = LicenseManager.get_active_license()
173
+ quota = LicenseManager.check_quota(tracker)
174
+ if tier == "free":
175
+ q_saved = int(quota.get("monthly_saved", 0))
176
+ q_limit = int(quota.get("monthly_limit") or 500_000)
177
+ q_pct = min(100, int(q_saved / q_limit * 100)) if q_limit else 0
178
+ q_state = "\033[31mQUOTA REACHED — Pro optimizations paused\033[0m" if quota.get("is_quota_exceeded") else f"{q_pct}% of monthly measured quota"
179
+ print(f" Tier: \033[33mCOMMUNITY (Free)\033[0m — {q_saved:,} / {q_limit:,} tokens ({q_state})")
180
+ print(" Upgrade: \033[36mhttps://tokensafe.dev/signup\033[0m ($9/mo Solo · 7-Day Team Trial)")
181
+ else:
182
+ print(f" Tier: \033[32m{tier.upper()}\033[0m (Unlimited)")
183
+ # Cloud heartbeat (non-blocking; keeps the machine visible server-side)
184
+ try:
185
+ TelemetrySync.sync_background()
186
+ pending = int(TelemetrySync.get_sync_status().get("pending_events", 0) or 0)
187
+ if pending:
188
+ print(f" Cloud: {pending:,} events queued for telemetry sync (background)")
189
+ else:
190
+ print(" Cloud: \033[32m✔ telemetry up to date\033[0m")
191
+ except Exception:
192
+ pass
193
+ # Distillation cache visibility (get_stats existed but was never surfaced anywhere)
194
+ try:
195
+ from src.distiller_cache import DistillationCache
196
+ cstats = DistillationCache.get_stats()
197
+ lookups = cstats["hits"] + cstats["misses"]
198
+ if lookups:
199
+ print(f" Cache: \033[32m{cstats['hit_ratio_pct']}% distillation cache hit ratio\033[0m ({cstats['hits']:,}/{lookups:,} lookups · {cstats['persistent_entries']:,} entries on disk)")
200
+ except Exception:
201
+ pass
202
+ print()
203
+
204
+ elif command in ("stats", "dashboard"):
144
205
  tracker = MetricsTracker()
145
206
  dashboard = Dashboard(tracker)
146
207
  try:
@@ -195,6 +256,7 @@ def main():
195
256
  status = "\033[32m✔\033[0m" if r["success"] else "\033[31m✖\033[0m"
196
257
  print(f" {status} \033[1m{r['name']:<28}\033[0m: {r['message']}")
197
258
  print(f"\n\033[32m✔ Universal project rules injected into: {', '.join(res['project_rules'])}\033[0m\n")
259
+ AgentInstaller.maybe_prompt_proxy_enable(context="install")
198
260
  elif "--project" in args:
199
261
  agents_plugin = None
200
262
  if "--agents-plugin" in args:
@@ -307,8 +369,41 @@ def main():
307
369
 
308
370
  elif command == "proxy":
309
371
  from src.proxy import run_proxy
310
- if len(args) > 1 and args[1] in ("--help", "-h", "help"):
311
- print("Usage: tokensafe proxy [port] (default: 8765)")
372
+ sub = args[1] if len(args) > 1 else ""
373
+ if sub in ("--help", "-h", "help"):
374
+ print("Usage: tokensafe proxy [port] Run in foreground (default: 8765)")
375
+ print(" tokensafe proxy on Install daemon + wire agents (one command)")
376
+ print(" tokensafe proxy off Unwire agents + remove daemon (rollback)")
377
+ print(" tokensafe proxy status Health, wiring state, heartbeat")
378
+ return
379
+ if sub == "on":
380
+ from src.installer import AgentInstaller
381
+ report = AgentInstaller.proxy_on()
382
+ d, w = report["daemon"], report["wiring"]
383
+ print(f"\n\033[1m\033[36m⚡ TOKENSAFE PROXY SETUP ⚡\033[0m\n")
384
+ print(f" Daemon: {'✔ ' + d['message'] if d['ok'] else '✖ ' + d['message']}")
385
+ print(f" Health: {'✔ proxy answering on 127.0.0.1:8765' if report['health'] else '✖ not reachable'}")
386
+ print(f" Wiring: {'✔ ' + w['message'] if w['ok'] else '✖ ' + w['message']}")
387
+ if report["manual_steps"]:
388
+ print(" Manual (not auto-wirable):")
389
+ for step in report["manual_steps"]:
390
+ print(f" • {step}")
391
+ print(f"\n Rollback anytime: \033[1mtokensafe proxy off\033[0m\n")
392
+ return
393
+ if sub == "off":
394
+ from src.installer import AgentInstaller
395
+ report = AgentInstaller.proxy_off()
396
+ u, d = report["unwired"], report["daemon"]
397
+ print(f"\n Unwired: {'✔ ' + u['message'] if u['ok'] else '✖ ' + u['message']}")
398
+ print(f" Daemon: {'✔ ' + d['message'] if d['ok'] else '✖ ' + d['message']}\n")
399
+ return
400
+ if sub == "status":
401
+ from src.installer import AgentInstaller
402
+ st = AgentInstaller.proxy_status()
403
+ print(f"\n Health: {'✔ running on 127.0.0.1:8765' if st['health'] else '✖ not running'}")
404
+ print(f" Claude Code wired: {'✔ ' + str(st['claude_code_env_value']) if st['claude_code_wired'] else '○ not wired'}")
405
+ hb = st.get("heartbeat_age_seconds")
406
+ print(f" Last traffic: {f'{hb}s ago' if hb is not None else 'no heartbeat yet'}\n")
312
407
  return
313
408
  port = 8765
314
409
  if len(args) > 1:
@@ -460,7 +555,7 @@ def main():
460
555
  q_limit = int(quota.get("monthly_limit") or 500_000)
461
556
  q_state = "\033[31mQUOTA REACHED (Pro optimizations paused)\033[0m" if quota.get("is_quota_exceeded") else "\033[32mActive\033[0m"
462
557
  print(f" Status: Free Tier ({q_saved:,} / {q_limit:,} measured tokens this month · {q_state})")
463
- print(" Upgrade: https://tokensafe.dev/#pricing ($9/mo Solo with 7-Day Free Trial)\n")
558
+ print(" Upgrade: https://tokensafe.dev/signup ($9/mo Solo with 7-Day Free Trial)\n")
464
559
  print()
465
560
 
466
561
  elif command in ("providers", "models", "keys"):
@@ -584,8 +679,11 @@ def main():
584
679
  t = MetricsTracker()
585
680
  b_before = (os.path.getsize(t.db_path) if os.path.exists(t.db_path) else 0) / 1024.0
586
681
  t.vacuum()
682
+ # Repair pass: rebuild session aggregates straight from events (guards
683
+ # against sessions/events drift after crashes or manual DB edits).
684
+ t.recalculate_sessions()
587
685
  b_after = (os.path.getsize(t.db_path) if os.path.exists(t.db_path) else 0) / 1024.0
588
- print(f"\033[32m✔ Database compacted. Size: {b_before:.1f} KB ➔ {b_after:.1f} KB\033[0m\n")
686
+ print(f"\033[32m✔ Database compacted + session aggregates rebuilt. Size: {b_before:.1f} KB ➔ {b_after:.1f} KB\033[0m\n")
589
687
 
590
688
  elif command in ("digest", "weekly-digest"):
591
689
  from src.weekly_digest import WeeklyDigestGenerator
@@ -660,7 +758,7 @@ def main():
660
758
 
661
759
  else:
662
760
  print(f"Unknown command: {command}")
663
- print("Available commands: stats, sync, html, test, tests, doctor, providers, mcp, benchmark, proxy, graph, map, skeleton, guard, vacuum, prune, digest, activate, license, markdown, install, setup, update, check-update, reset. Run 'tokensafe help' for details.")
761
+ print("Available commands: stats, status, sync, html, test, tests, doctor, providers, mcp, benchmark, proxy, graph, map, skeleton, guard, vacuum, prune, digest, activate, license, markdown, install, setup, update, check-update, reset. Run 'tokensafe help' for details.")
664
762
  sys.exit(1)
665
763
 
666
764
  if __name__ == "__main__":
@@ -190,32 +190,6 @@ class CommandSanitizer:
190
190
  out += f" {op} {stage}"
191
191
  return out
192
192
 
193
- @staticmethod
194
- def _split_pipeline_stages(cmd: str) -> List[str]:
195
- """
196
- Splits a shell command on single '|' pipe operators while respecting
197
- quoting ('...', "...", `...`) and '||' logical OR, so regex patterns like
198
- grep "foo|bar" are never torn apart mid-string.
199
- """
200
- pairs = CommandSanitizer.split_stages(cmd)
201
- # Legacy contract: only pipe boundaries split; '&&'/';'/'||' stay inside stages.
202
- stages: List[str] = []
203
- pipe_open = False
204
- for op, stage in pairs:
205
- if op in ("", "|"):
206
- if pipe_open and stages:
207
- stages[-1] = f"{stages[-1]} | {stage}"
208
- else:
209
- stages.append(stage)
210
- pipe_open = op == "|"
211
- else:
212
- # Non-pipe operator: glue operator + stage back into current stage
213
- if stages:
214
- stages[-1] = f"{stages[-1]} {op} {stage}"
215
- else:
216
- stages.append(stage)
217
- return [s for s in (st.strip() for st in stages) if s]
218
-
219
193
  @classmethod
220
194
  def _has_redirect(cls, stage: str) -> bool:
221
195
  """True if the stage redirects stdout to a file/stream (ignoring 2>&1 merges and quoted '>')."""
@@ -651,3 +625,70 @@ class CommandSanitizer:
651
625
  return f"PASS: {lines[0]} ... {lines[-1]} (exit code 0)"
652
626
 
653
627
  return raw
628
+
629
+ # PostToolUse shell tools whose stdout can be compacted (hook payload tool_name)
630
+ SHELL_TOOL_NAMES = {
631
+ "Bash", "bash", "Shell", "shell", "sh",
632
+ "run_command", "RunCommand", "execute_command", "ExecuteCommand", "terminal", "Terminal",
633
+ }
634
+
635
+ @staticmethod
636
+ def _extract_tool_stdout(response: Any) -> Tuple[str, Optional[int]]:
637
+ """Extracts (stdout_text, exit_code_or_None) from a PostToolUse tool_response payload.
638
+ Handles plain strings, {stdout|output|content|text|result} dicts, content-block lists,
639
+ and common exit-code keys (exit_code/exitCode/returncode/code, success booleans)."""
640
+ if isinstance(response, str):
641
+ return response, None
642
+ if isinstance(response, dict):
643
+ stdout = ""
644
+ for key in ("stdout", "output", "content", "text", "result"):
645
+ val = response.get(key)
646
+ if isinstance(val, str) and val:
647
+ stdout = val
648
+ break
649
+ if not stdout:
650
+ blocks = response.get("content")
651
+ if isinstance(blocks, list):
652
+ texts = [
653
+ b.get("text", "") for b in blocks
654
+ if isinstance(b, dict) and isinstance(b.get("text"), str)
655
+ ]
656
+ stdout = "\n".join(t for t in texts if t)
657
+ exit_code = None
658
+ for key in ("exit_code", "exitCode", "returncode", "return_code", "code"):
659
+ val = response.get(key)
660
+ if isinstance(val, (int, float)) and not isinstance(val, bool):
661
+ exit_code = int(val)
662
+ break
663
+ if exit_code is None:
664
+ if response.get("success") is True:
665
+ exit_code = 0
666
+ elif response.get("success") is False or response.get("error"):
667
+ exit_code = 1
668
+ return stdout, exit_code
669
+ return "", None
670
+
671
+ @classmethod
672
+ def compact_tool_output(cls, tool_name: str, tool_response: Any) -> Optional[Tuple[str, int, int]]:
673
+ """
674
+ PostToolUse helper: compacts verbose successful shell output before the model reads it.
675
+ Returns (compacted_text, original_chars, compacted_chars), or None when not applicable:
676
+ non-shell tool, short output, failed command, or when compaction saves too little.
677
+ Fail-open by design — callers must degrade to the raw output on None.
678
+ """
679
+ if str(tool_name or "") not in cls.SHELL_TOOL_NAMES:
680
+ return None
681
+ raw, resolved_exit = cls._extract_tool_stdout(tool_response)
682
+ if not raw or len(raw) < 400:
683
+ return None
684
+ if resolved_exit is None:
685
+ # Unknown exit status: refuse to mute anything that looks like a failure
686
+ if re.search(r"Traceback|AssertionError|\bERROR\b|FAILED|exit code [1-9]", raw):
687
+ return None
688
+ resolved_exit = 0
689
+ elif resolved_exit != 0:
690
+ return None
691
+ compacted = cls.compact_test_output(raw, resolved_exit)
692
+ if compacted is raw or len(compacted) >= len(raw) * 0.6:
693
+ return None
694
+ return compacted, len(raw), len(compacted)
package/src/dashboard.py CHANGED
@@ -48,7 +48,12 @@ EVENT_NAMES = {
48
48
  "OUTPUT_GUARD": "Output Token Guard (write_file)",
49
49
  "LOOP_GUARD": "Anti-Stuck Loop Guard",
50
50
  "HISTORY_FOLD": "Multi-turn History Fold",
51
- "COMMAND_OUTPUT": "Terminal Log Sanitizer"
51
+ "COMMAND_OUTPUT": "Terminal Log Sanitizer",
52
+ "TOOL_OUTPUT_COMPACT": "PostToolUse Stdout Compact",
53
+ "TOOL_LEDGER": "Tool Result Ledger (proxy)",
54
+ "TOOL_PRUNE": "Cold Tool Pruning (proxy)",
55
+ "TOOL_PRUNE_MISS": "Tool Prune Miss (quality watch)",
56
+ "EPOCH_ROLLOVER": "Epoch Rollover (80% window)"
52
57
  }
53
58
 
54
59
  class Dashboard:
@@ -83,10 +88,10 @@ class Dashboard:
83
88
  q_pct = min(100.0, (monthly_saved / limit * 100.0))
84
89
  if monthly_saved >= limit:
85
90
  out.append(f" {BOLD}Subscription Tier:{RESET} {YELLOW}COMMUNITY (Free){RESET} • {RED}{BOLD}500k Monthly Measured Quota Reached ({monthly_saved:,}/{limit:,}){RESET}")
86
- out.append(f" {BOLD}Quota Usage:{RESET} {RED}{render_bar(q_pct)}{RESET} (Pro optimizations paused · Upgrade: tokensafe activate <key> | {CYAN}https://tokensafe.dev/#pricing{RESET})")
91
+ out.append(f" {BOLD}Quota Usage:{RESET} {RED}{render_bar(q_pct)}{RESET} (Pro optimizations paused · Upgrade: tokensafe activate <key> | {CYAN}https://tokensafe.dev/signup{RESET})")
87
92
  else:
88
93
  out.append(f" {BOLD}Subscription Tier:{RESET} {YELLOW}COMMUNITY (Free){RESET} • {monthly_saved:,} / {limit:,} measured tokens this month")
89
- out.append(f" {BOLD}Quota Usage:{RESET} {YELLOW}{render_bar(q_pct)}{RESET} (Upgrade to Solo for Unlimited)")
94
+ out.append(f" {BOLD}Quota Usage:{RESET} {YELLOW}{render_bar(q_pct)}{RESET} (Upgrade to Solo for Unlimited · {CYAN}https://tokensafe.dev/signup{RESET})")
90
95
  else:
91
96
  email_info = f" ({payload.get('email', '')})" if payload.get('email') else ""
92
97
  out.append(f" {BOLD}Subscription Tier:{RESET} {GREEN}{BOLD}{tier_upper} (Unlimited){RESET}{email_info}")
@@ -95,6 +100,8 @@ class Dashboard:
95
100
  out.append(f" {BOLD}Total Tokens Saved:{RESET} {GREEN}{BOLD}{total_saved:,}{RESET} tokens")
96
101
  out.append(f" {BOLD}Efficiency Gain:{RESET} {YELLOW}{BOLD}{render_bar(pct)}{RESET}")
97
102
  out.append(f" {BOLD}Estimated Savings:{RESET} {GREEN}≈${usd:.4f} USD{RESET} {DIM}(derived: tokens × $1.5/M — approximation, not a bill){RESET}")
103
+ weekly = self.tracker.get_weekly_saved()
104
+ out.append(f" {BOLD}This Week:{RESET} {GREEN}{BOLD}{weekly['saved_tokens']:,}{RESET} tokens saved across {weekly['events']:,} events (≈${weekly['usd_saved']:.2f})")
98
105
 
99
106
  # Per-agent breakdown (honest Cumulative Total across ALL agents)
100
107
  by_agent = summary.get("by_agent") or {}
@@ -109,6 +116,21 @@ class Dashboard:
109
116
  out.append("")
110
117
  out.append(f" {BOLD}Context Traffic:{RESET} {orig:,} raw ➔ {opt:,} optimized ({events_count} events)\n")
111
118
 
119
+ # Egress economy (v3.0.0): output tokens cost ~4x input — surfaced apart
120
+ breakdown_early = summary.get("breakdown", {})
121
+ og = breakdown_early.get("OUTPUT_GUARD") or {}
122
+ tl = breakdown_early.get("TOOL_LEDGER") or {}
123
+ tp = breakdown_early.get("TOOL_PRUNE") or {}
124
+ if og.get("count") or tl.get("count") or tp.get("count"):
125
+ out.append(f"{BOLD}── Egress Economy (output ≈4× input price) ──────────────────────────{RESET}")
126
+ if og.get("count"):
127
+ out.append(f" • {BOLD}{'Full-file writes steered to Edit':<34}{RESET} : {GREEN}{og['saved']:,} output tokens{RESET} ({og['count']} events)")
128
+ if tl.get("count"):
129
+ out.append(f" • {BOLD}{'Aged tool results folded (proxy)':<34}{RESET} : {GREEN}{tl['saved']:,} input tokens{RESET} ({tl['count']} events)")
130
+ if tp.get("count"):
131
+ out.append(f" • {BOLD}{'Cold MCP tools pruned (proxy)':<34}{RESET} : {GREEN}{tp['saved']:,} floor tokens{RESET} ({tp['count']} events)")
132
+ out.append("")
133
+
112
134
  # Breakdown by category
113
135
  out.append(f"{BOLD}── Breakdown by Source ──────────────────────────────────────────────{RESET}")
114
136
  breakdown = summary.get("breakdown", {})
@@ -255,7 +277,7 @@ class Dashboard:
255
277
  <div>
256
278
  <strong style="color: #eab308;">⚡ Community Edition:</strong> {monthly_saved:,} / {limit:,} free measured tokens saved this month ({q_pct}%).
257
279
  </div>
258
- <a href="https://tokensafe.dev/#pricing" target="_blank" style="background: #10b981; color: #090a0f; font-weight: 700; padding: 6px 14px; border-radius: 8px; text-decoration: none; font-size: 12px;">Upgrade to Solo (Unlimited)</a>
280
+ <a href="https://tokensafe.dev/signup" target="_blank" style="background: #10b981; color: #090a0f; font-weight: 700; padding: 6px 14px; border-radius: 8px; text-decoration: none; font-size: 12px;">Upgrade to Solo (Unlimited)</a>
259
281
  </div>
260
282
  """
261
283
  else: