tokensafe 2.9.0 → 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/src/installer.py CHANGED
@@ -27,6 +27,7 @@ GREEN = "\033[32m"
27
27
  CYAN = "\033[36m"
28
28
  YELLOW = "\033[33m"
29
29
  RED = "\033[31m"
30
+ DIM = "\033[2m"
30
31
 
31
32
  HOME = os.path.expanduser("~")
32
33
  PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
@@ -225,6 +226,7 @@ class AgentInstaller:
225
226
  hooks = data.get("hooks") if isinstance(data.get("hooks"), dict) else {}
226
227
  prompt_entry = {"hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
227
228
  bash_entry = {"matcher": "Bash", "hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
229
+ write_entry = {"matcher": "Write", "hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
228
230
  session_entry = {"hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
229
231
  post_bash_entry = {"matcher": "Bash", "hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
230
232
 
@@ -252,13 +254,14 @@ class AgentInstaller:
252
254
  _sync_claude_event("SessionStart", session_entry),
253
255
  _sync_claude_event("UserPromptSubmit", prompt_entry),
254
256
  _sync_claude_event("PreToolUse", bash_entry),
257
+ _sync_claude_event("PreToolUse", write_entry),
255
258
  _sync_claude_event("PostToolUse", post_bash_entry),
256
259
  ])
257
260
  if not changed:
258
261
  return True, "TokenSafe Claude Code hooks already registered"
259
262
  data["hooks"] = hooks
260
263
  cls._atomic_write_json(config_file, data)
261
- return True, "hooks registered (SessionStart + UserPromptSubmit + PreToolUse guard + PostToolUse stdout compact)"
264
+ return True, "hooks registered (SessionStart + UserPromptSubmit + PreToolUse guard/write + PostToolUse stdout compact)"
262
265
 
263
266
  # cursor
264
267
  config_file = os.path.join(HOME, ".cursor", "hooks.json")
@@ -298,6 +301,279 @@ class AgentInstaller:
298
301
  cls._atomic_write_json(config_file, data)
299
302
  return True, "guards registered (shell + junk-read + prompt pipeline)"
300
303
 
304
+ # ------------------------------------------------------------------
305
+ # Proxy auto-wiring (v3.0.0): daemon + per-agent base URL override with
306
+ # one-command rollback. Only agents that CAN be wired programmatically
307
+ # are touched (Claude Code via settings.json env); everything else gets
308
+ # printed manual steps instead of silent failure.
309
+ # ------------------------------------------------------------------
310
+
311
+ PROXY_PORT = 8765
312
+ PROXY_BASE_URL = f"http://127.0.0.1:{PROXY_PORT}"
313
+ PROXY_ENV_KEY = "ANTHROPIC_BASE_URL"
314
+ _PLIST_LABEL = "dev.tokensafe.proxy"
315
+ _SERVICE_NAME = "tokensafe-proxy"
316
+ _WIRING_BACKUP = "proxy_wiring_backup.json"
317
+
318
+ @classmethod
319
+ def proxy_health(cls, timeout: float = 1.5) -> bool:
320
+ """True when the local proxy answers /health."""
321
+ try:
322
+ import urllib.request
323
+ with urllib.request.urlopen(f"{cls.PROXY_BASE_URL}/health", timeout=timeout) as resp:
324
+ return resp.status == 200
325
+ except Exception:
326
+ return False
327
+
328
+ @classmethod
329
+ def _wiring_backup_path(cls) -> str:
330
+ return os.path.join(HOME, ".tokensafe", "data", cls._WIRING_BACKUP)
331
+
332
+ @classmethod
333
+ def wire_proxy_config(cls) -> Tuple[bool, str]:
334
+ """Points Claude Code at the local proxy via settings.json env.
335
+ Backs up the previous value for `tokensafe proxy off`."""
336
+ if not cls.proxy_health():
337
+ return False, "proxy is not running on 127.0.0.1:8765 — start it first (`tokensafe proxy on` installs a daemon)"
338
+ config_file = os.path.join(HOME, ".claude", "settings.json")
339
+ os.makedirs(os.path.dirname(config_file), exist_ok=True)
340
+ data, err = cls._load_json_with_backup(config_file)
341
+ if err or data is None:
342
+ return False, err or f"Failed to parse {config_file}"
343
+ env = data.get("env") if isinstance(data.get("env"), dict) else {}
344
+ previous = env.get(cls.PROXY_ENV_KEY)
345
+ if previous == cls.PROXY_BASE_URL:
346
+ return True, "Claude Code already points at the local proxy"
347
+ # Persist rollback info before mutating user config
348
+ try:
349
+ backup_path = cls._wiring_backup_path()
350
+ os.makedirs(os.path.dirname(backup_path), exist_ok=True)
351
+ backup = {}
352
+ if os.path.exists(backup_path):
353
+ try:
354
+ with open(backup_path, "r", encoding="utf-8") as f:
355
+ backup = json.load(f)
356
+ except Exception:
357
+ backup = {}
358
+ backup.setdefault("claude_code", {})["ANTHROPIC_BASE_URL"] = previous
359
+ with open(backup_path, "w", encoding="utf-8") as f:
360
+ json.dump(backup, f)
361
+ except Exception:
362
+ pass
363
+ env[cls.PROXY_ENV_KEY] = cls.PROXY_BASE_URL
364
+ data["env"] = env
365
+ cls._atomic_write_json(config_file, data)
366
+ return True, "Claude Code wired: ANTHROPIC_BASE_URL=http://127.0.0.1:8765 (rollback: tokensafe proxy off)"
367
+
368
+ @classmethod
369
+ def unwire_proxy_config(cls) -> Tuple[bool, str]:
370
+ """Removes the proxy override and restores the pre-wiring value."""
371
+ config_file = os.path.join(HOME, ".claude", "settings.json")
372
+ if not os.path.exists(config_file):
373
+ return True, "nothing to unwire"
374
+ data, err = cls._load_json_with_backup(config_file)
375
+ if err or data is None:
376
+ return False, err or f"Failed to parse {config_file}"
377
+ env = data.get("env") if isinstance(data.get("env"), dict) else {}
378
+ if env.get(cls.PROXY_ENV_KEY) != cls.PROXY_BASE_URL:
379
+ return True, "Claude Code was not wired to the proxy"
380
+ restored = None
381
+ try:
382
+ backup_path = cls._wiring_backup_path()
383
+ if os.path.exists(backup_path):
384
+ with open(backup_path, "r", encoding="utf-8") as f:
385
+ backup = json.load(f)
386
+ restored = (backup.get("claude_code") or {}).get("ANTHROPIC_BASE_URL")
387
+ except Exception:
388
+ restored = None
389
+ if restored:
390
+ env[cls.PROXY_ENV_KEY] = restored
391
+ else:
392
+ env.pop(cls.PROXY_ENV_KEY, None)
393
+ if env:
394
+ data["env"] = env
395
+ else:
396
+ data.pop("env", None)
397
+ cls._atomic_write_json(config_file, data)
398
+ return True, "Claude Code unwired (previous base URL restored)"
399
+
400
+ @classmethod
401
+ def install_proxy_daemon(cls) -> Tuple[bool, str]:
402
+ """Keeps `tokensafe proxy` running: launchd (macOS) / systemd user unit (Linux)."""
403
+ python_bin = sys.executable or PYTHON_BIN
404
+ if sys.platform == "darwin":
405
+ launch_dir = os.path.join(HOME, "Library", "LaunchAgents")
406
+ os.makedirs(launch_dir, exist_ok=True)
407
+ plist_path = os.path.join(launch_dir, f"{cls._PLIST_LABEL}.plist")
408
+ log_path = os.path.join(HOME, ".tokensafe", "data", "proxy.log")
409
+ os.makedirs(os.path.dirname(log_path), exist_ok=True)
410
+ plist = f"""<?xml version="1.0" encoding="UTF-8"?>
411
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
412
+ <plist version="1.0">
413
+ <dict>
414
+ <key>Label</key><string>{cls._PLIST_LABEL}</string>
415
+ <key>ProgramArguments</key>
416
+ <array>
417
+ <string>{python_bin}</string>
418
+ <string>-m</string>
419
+ <string>src.proxy</string>
420
+ <string>{cls.PROXY_PORT}</string>
421
+ </array>
422
+ <key>WorkingDirectory</key><string>{PROJECT_ROOT}</string>
423
+ <key>RunAtLoad</key><true/>
424
+ <key>KeepAlive</key><true/>
425
+ <key>StandardOutPath</key><string>{log_path}</string>
426
+ <key>StandardErrorPath</key><string>{log_path}</string>
427
+ </dict>
428
+ </plist>
429
+ """
430
+ with open(plist_path, "w", encoding="utf-8") as f:
431
+ f.write(plist)
432
+ subprocess.run(["launchctl", "unload", plist_path], capture_output=True)
433
+ res = subprocess.run(["launchctl", "load", "-w", plist_path], capture_output=True, text=True)
434
+ if res.returncode != 0:
435
+ return False, f"launchctl load failed: {(res.stderr or '').strip()[:160]}"
436
+ return True, f"launchd daemon installed ({plist_path})"
437
+ if sys.platform.startswith("linux"):
438
+ unit_dir = os.path.join(HOME, ".config", "systemd", "user")
439
+ os.makedirs(unit_dir, exist_ok=True)
440
+ unit_path = os.path.join(unit_dir, f"{cls._SERVICE_NAME}.service")
441
+ unit = f"""[Unit]
442
+ Description=TokenSafe Local AI Proxy
443
+ After=network.target
444
+
445
+ [Service]
446
+ ExecStart={python_bin} -m src.proxy {cls.PROXY_PORT}
447
+ WorkingDirectory={PROJECT_ROOT}
448
+ Restart=always
449
+ RestartSec=3
450
+
451
+ [Install]
452
+ WantedBy=default.target
453
+ """
454
+ with open(unit_path, "w", encoding="utf-8") as f:
455
+ f.write(unit)
456
+ for cmd in (["systemctl", "--user", "daemon-reload"], ["systemctl", "--user", "enable", "--now", cls._SERVICE_NAME]):
457
+ res = subprocess.run(cmd, capture_output=True, text=True)
458
+ if res.returncode != 0:
459
+ return False, f"systemctl failed: {(res.stderr or '').strip()[:160]}"
460
+ return True, f"systemd user service installed ({unit_path})"
461
+ return False, "no daemon support on this OS — run `tokensafe proxy` manually in a terminal"
462
+
463
+ @classmethod
464
+ def remove_proxy_daemon(cls) -> Tuple[bool, str]:
465
+ if sys.platform == "darwin":
466
+ plist_path = os.path.join(HOME, "Library", "LaunchAgents", f"{cls._PLIST_LABEL}.plist")
467
+ if not os.path.exists(plist_path):
468
+ return True, "no daemon installed"
469
+ subprocess.run(["launchctl", "unload", plist_path], capture_output=True)
470
+ os.remove(plist_path)
471
+ return True, "launchd daemon removed"
472
+ if sys.platform.startswith("linux"):
473
+ unit_path = os.path.join(HOME, ".config", "systemd", "user", f"{cls._SERVICE_NAME}.service")
474
+ if not os.path.exists(unit_path):
475
+ return True, "no daemon installed"
476
+ subprocess.run(["systemctl", "--user", "disable", "--now", cls._SERVICE_NAME], capture_output=True)
477
+ os.remove(unit_path)
478
+ subprocess.run(["systemctl", "--user", "daemon-reload"], capture_output=True)
479
+ return True, "systemd user service removed"
480
+ return True, "no daemon support on this OS"
481
+
482
+ @classmethod
483
+ def proxy_on(cls) -> Dict[str, Any]:
484
+ """One command: daemon + wiring. Returns a structured report."""
485
+ report: Dict[str, Any] = {"daemon": None, "wiring": None, "health": False, "manual_steps": []}
486
+ d_ok, d_msg = cls.install_proxy_daemon()
487
+ report["daemon"] = {"ok": d_ok, "message": d_msg}
488
+ # Give the daemon a moment to boot before wiring agents to it.
489
+ for _ in range(6):
490
+ if cls.proxy_health():
491
+ break
492
+ time.sleep(0.8)
493
+ report["health"] = cls.proxy_health()
494
+ if d_ok and not report["health"]:
495
+ report["wiring"] = {"ok": False, "message": "daemon installed but /health did not answer — check ~/.tokensafe/data/proxy.log; agents NOT rewired"}
496
+ return report
497
+ if report["health"]:
498
+ w_ok, w_msg = cls.wire_proxy_config()
499
+ report["wiring"] = {"ok": w_ok, "message": w_msg}
500
+ else:
501
+ report["wiring"] = {"ok": False, "message": "proxy not reachable; agents NOT rewired"}
502
+ report["manual_steps"] = [
503
+ "Cursor: Settings → Models → add OpenAI-compatible model with base URL http://127.0.0.1:8765/v1",
504
+ "Cline/Aider: set OpenAI-compatible base URL to http://127.0.0.1:8765/v1",
505
+ ]
506
+ return report
507
+
508
+ @classmethod
509
+ def proxy_off(cls) -> Dict[str, Any]:
510
+ report: Dict[str, Any] = {}
511
+ u_ok, u_msg = cls.unwire_proxy_config()
512
+ report["unwired"] = {"ok": u_ok, "message": u_msg}
513
+ r_ok, r_msg = cls.remove_proxy_daemon()
514
+ report["daemon"] = {"ok": r_ok, "message": r_msg}
515
+ return report
516
+
517
+ @classmethod
518
+ def proxy_status(cls) -> Dict[str, Any]:
519
+ env_present = None
520
+ settings_path = os.path.join(HOME, ".claude", "settings.json")
521
+ try:
522
+ if os.path.exists(settings_path):
523
+ with open(settings_path, "r", encoding="utf-8") as f:
524
+ env = (json.load(f) or {}).get("env") or {}
525
+ env_present = env.get(cls.PROXY_ENV_KEY)
526
+ except Exception:
527
+ pass
528
+ heartbeat_age = None
529
+ try:
530
+ from src.paths import resolve_data_dir
531
+ marker = os.path.join(resolve_data_dir(), ".proxy_active")
532
+ if os.path.exists(marker):
533
+ with open(marker, "r", encoding="utf-8") as f:
534
+ heartbeat_age = int(time.time()) - int(f.read().strip() or 0)
535
+ except Exception:
536
+ pass
537
+ return {
538
+ "health": cls.proxy_health(),
539
+ "claude_code_wired": env_present == cls.PROXY_BASE_URL,
540
+ "claude_code_env_value": env_present,
541
+ "heartbeat_age_seconds": heartbeat_age,
542
+ "daemon": sys.platform,
543
+ }
544
+
545
+ @classmethod
546
+ def maybe_prompt_proxy_enable(cls, context: str = "install") -> None:
547
+ """Interactive opt-in prompt shown at the end of install/update flows.
548
+ Strictly fail-open and non-nagging: skipped entirely for non-TTY runs
549
+ (scripts, CI, background updaters) and when the proxy is already wired."""
550
+ try:
551
+ if not (sys.stdin.isatty() and sys.stdout.isatty()):
552
+ return
553
+ if os.environ.get("TOKENSAFE_NONINTERACTIVE", "").strip() in ("1", "true", "yes"):
554
+ return
555
+ st = cls.proxy_status()
556
+ if st.get("claude_code_wired"):
557
+ return # already wired — never nag
558
+ print(f"\n {BOLD}?{RESET} Enable the local AI proxy now? [y/N] ", end="", flush=True)
559
+ answer = input().strip().lower()
560
+ if answer not in ("y", "yes"):
561
+ print(f" {DIM}Skipped — enable anytime with:{RESET} {BOLD}tokensafe proxy on{RESET}")
562
+ return
563
+ report = cls.proxy_on()
564
+ d, w = report["daemon"], report["wiring"]
565
+ print(f" Daemon: {'✔ ' + d['message'] if d['ok'] else '✖ ' + d['message']}")
566
+ print(f" Health: {'✔ 127.0.0.1:8765 answering' if report['health'] else '✖ not reachable — agents NOT rewired'}")
567
+ print(f" Wiring: {'✔ ' + w['message'] if w['ok'] else '✖ ' + w['message']}")
568
+ for step in report.get("manual_steps") or []:
569
+ print(f" Manual: {step}")
570
+ print(f" Rollback: {BOLD}tokensafe proxy off{RESET}")
571
+ except (EOFError, KeyboardInterrupt):
572
+ print()
573
+ return
574
+ except Exception:
575
+ return # fail-open: a prompt problem never breaks install/update
576
+
301
577
  @classmethod
302
578
  def install_mcp_config(cls, agent_key: str) -> Tuple[bool, str]:
303
579
  """Injects TokenSafe MCP config into target agent."""
@@ -797,6 +1073,7 @@ class AgentInstaller:
797
1073
 
798
1074
  print(f"\n\033[32m\033[1m✅ TokenSafe successfully connected to {installed_count} agent(s)!\033[0m")
799
1075
  print(" Restart your IDE / Agent to start saving tokens automatically.\n")
1076
+ cls.maybe_prompt_proxy_enable(context="install")
800
1077
 
801
1078
  @staticmethod
802
1079
  def _is_tokensafe_mcp_command(cmd: str) -> bool:
@@ -1142,6 +1419,7 @@ class AgentInstaller:
1142
1419
  print(f" Synchronized {synced_count} agent environments with zero-loss AST & God Nodes rules.")
1143
1420
  print(f" Run {BOLD}tokensafe stats{RESET} to view token savings.")
1144
1421
  print(f" {CYAN}ℹ{RESET} If your terminal still shows the old version, open a new window or run {BOLD}hash -r{RESET}.")
1422
+ cls.maybe_prompt_proxy_enable(context="update")
1145
1423
 
1146
1424
  def main():
1147
1425
  args = sys.argv[1:]
@@ -96,10 +96,30 @@ class LicenseManager:
96
96
  return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:32]
97
97
 
98
98
  @classmethod
99
- def ensure_community_license(cls) -> Dict[str, Any]:
99
+ def detect_agent(cls) -> str:
100
+ """Best-effort agent attribution for adoption analytics: explicit
101
+ TOKENSAFE_AGENT env wins, then well-known agent env markers, then the
102
+ historic default (mirrors MetricsTracker._infer_agent conventions)."""
103
+ explicit = os.environ.get("TOKENSAFE_AGENT", "").strip()
104
+ if explicit:
105
+ return explicit[:32]
106
+ for env_key, tag in (
107
+ ("CLAUDECODE", "claude-code"),
108
+ ("CURSOR_TRACE_ID", "cursor"),
109
+ ("CODEX_HOME", "codex"),
110
+ ("GEMINI_CLI", "gemini-cli"),
111
+ ):
112
+ if os.environ.get(env_key):
113
+ return tag
114
+ return "antigravity"
115
+
116
+ @classmethod
117
+ def ensure_community_license(cls, agent: str = "") -> Dict[str, Any]:
100
118
  """
101
119
  Fetches a signed Community Edition license (tier 'free') bound to this
102
120
  machine's anonymized fingerprint. Zero-config: no keys, no user action.
121
+ `agent` (or TOKENSAFE_AGENT env / detect_agent() markers) attributes the
122
+ machine in server-side adoption analytics.
103
123
 
104
124
  Contract:
105
125
  - Skipped when any real license is already active (any tier).
@@ -133,6 +153,13 @@ class LicenseManager:
133
153
  plugin_version = str(json.load(mf).get("version", "") or "")
134
154
  except Exception:
135
155
  plugin_version = ""
156
+ if not plugin_version:
157
+ # PyPI/npm installs ship without plugin.json next to the package
158
+ try:
159
+ from importlib.metadata import version as _pkg_version
160
+ plugin_version = str(_pkg_version("tokensafe"))
161
+ except Exception:
162
+ plugin_version = ""
136
163
 
137
164
  import urllib.request
138
165
 
@@ -143,7 +170,7 @@ class LicenseManager:
143
170
  "machine_fp": cls.get_machine_fingerprint(),
144
171
  "platform": platform.system()[:32],
145
172
  "arch": platform.machine()[:32],
146
- "agent": os.environ.get("TOKENSAFE_AGENT", "")[:32],
173
+ "agent": str(agent or cls.detect_agent())[:32],
147
174
  "version": plugin_version[:32],
148
175
  }).encode("utf-8"),
149
176
  headers={"Content-Type": "application/json", "User-Agent": "TokenSafe/Community-License"},
@@ -542,13 +569,13 @@ class LicenseManager:
542
569
  f"({monthly_saved:,}/{max_tokens:,} measured tokens saved this month). "
543
570
  f"Graph/signature AST slicing, pointer dedup, history compaction & KV-cache prefix locking are paused "
544
571
  f"(Security Guard stays active). Upgrade to Solo ($9/mo) or 7-Day Team Trial: "
545
- f"`tokensafe activate <key>` or visit https://tokensafe.dev/#pricing"
572
+ f"`tokensafe activate <key>` or create your account at https://tokensafe.dev/signup"
546
573
  )
547
574
  elif monthly_saved >= int(max_tokens * 0.85):
548
575
  warning = (
549
576
  f"⚡ **TokenSafe Quota Notice**: Community Edition is at {int(monthly_saved / max_tokens * 100)}% of monthly limit "
550
577
  f"({monthly_saved:,}/{max_tokens:,} measured tokens). "
551
- f"Upgrade to Solo for unlimited optimization: `tokensafe activate <key>` or https://tokensafe.dev/#pricing"
578
+ f"Upgrade to Solo for unlimited optimization: `tokensafe activate <key>` or https://tokensafe.dev/signup"
552
579
  )
553
580
 
554
581
  return {
package/src/mcp_server.py CHANGED
@@ -42,7 +42,7 @@ from src.paths import get_active_workspace, is_plugin_or_system_dir
42
42
 
43
43
  SERVER_INFO = {
44
44
  "name": "tokensafe-mcp",
45
- "version": "2.9.0"
45
+ "version": "3.0.0"
46
46
  }
47
47
 
48
48
  # MCP client attribution: the initialize handshake carries clientInfo, which
package/src/metrics.py CHANGED
@@ -516,6 +516,31 @@ class MetricsTracker:
516
516
  # Largest contributor first
517
517
  return dict(sorted(by_agent.items(), key=lambda kv: kv[1]["saved_tokens"], reverse=True))
518
518
 
519
+ def get_weekly_saved(self, days: int = 7) -> Dict[str, Any]:
520
+ """Rolling-window savings totals for the quick `tokensafe status` view.
521
+ Reads raw events only (lifetime rollups have no timestamp and are
522
+ deliberately excluded — this is the recent-activity signal)."""
523
+ days = max(1, int(days))
524
+ cutoff = (datetime.now() - timedelta(days=days)).isoformat()
525
+ try:
526
+ with self._get_connection() as conn:
527
+ row = conn.cursor().execute(
528
+ """
529
+ SELECT COUNT(*) AS events,
530
+ COALESCE(SUM(saved_tokens), 0) AS saved_tokens,
531
+ COALESCE(SUM(est_usd_saved), 0.0) AS usd_saved
532
+ FROM events
533
+ WHERE timestamp >= ? AND saved_tokens > 0
534
+ """, (cutoff,)
535
+ ).fetchone()
536
+ return {
537
+ "events": int(row["events"] or 0),
538
+ "saved_tokens": int(row["saved_tokens"] or 0),
539
+ "usd_saved": round(float(row["usd_saved"] or 0.0), 4),
540
+ }
541
+ except Exception:
542
+ return {"events": 0, "saved_tokens": 0, "usd_saved": 0.0}
543
+
519
544
  def get_summary(self) -> Dict[str, Any]:
520
545
  """Returns cumulative statistics across all sessions, including lifetime rollups."""
521
546
  with self._get_connection() as conn: