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/src/distiller.py CHANGED
@@ -109,10 +109,13 @@ Rules:
109
109
  return os.environ.get("TOKENSAFE_SELF_HOSTED", "").lower() in ("1", "true", "yes")
110
110
 
111
111
  @classmethod
112
- def _call_cloud_distill(cls, raw_text: str, lic_key: str) -> Optional[str]:
112
+ def _call_cloud_distill(cls, raw_text: str, lic_key: str, mode: str = "") -> Optional[str]:
113
113
  cloud_url = os.environ.get("TOKENSAFE_CLOUD_URL", "https://api.tokensafe.dev").rstrip("/")
114
114
  endpoint = f"{cloud_url}/api/distill"
115
115
  payload = {"prompt": raw_text.strip()}
116
+ if mode:
117
+ payload["mode"] = mode
118
+ timeout = cls.HISTORY_DISTILL_TIMEOUT if mode == "history" else cls.DEFAULT_TIMEOUT
116
119
  req = urllib.request.Request(
117
120
  endpoint,
118
121
  data=json.dumps(payload).encode("utf-8"),
@@ -123,7 +126,7 @@ Rules:
123
126
  }
124
127
  )
125
128
  try:
126
- with urllib.request.urlopen(req, timeout=cls.DEFAULT_TIMEOUT) as resp:
129
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
127
130
  if resp.status == 200:
128
131
  data = json.loads(resp.read().decode("utf-8"))
129
132
  if data.get("success") and data.get("distilled"):
@@ -132,6 +135,42 @@ Rules:
132
135
  return None
133
136
  return None
134
137
 
138
+ HISTORY_DISTILL_TIMEOUT = 8.0
139
+
140
+ @classmethod
141
+ def distill_history(cls, raw_text: str) -> Optional[str]:
142
+ """
143
+ Managed-cloud history summarization for the Tool Result Ledger (v3.0.0):
144
+ compresses an aged tool-result segment into a terse state ledger.
145
+ Paid license required (free tier = hard-off per the distiller contract);
146
+ managed cloud only — self-hosted BYOK keeps the mechanical fold.
147
+ Shares the failure-cooldown breaker with prompt distillation.
148
+ """
149
+ if not raw_text or len(raw_text.strip()) < 50:
150
+ return None
151
+ if cls._cooldown_active():
152
+ return None
153
+ cache_key_text = "HIST:" + raw_text[:4000]
154
+ cached = DistillationCache.get(cache_key_text)
155
+ if cached:
156
+ return cached
157
+ tier, _ = LicenseManager.get_active_license()
158
+ if tier == "free":
159
+ return None
160
+ providers = cls.get_configured_providers()
161
+ if "cloud" not in providers:
162
+ return None # self-hosted BYOK: mechanical fold stays the contract
163
+ lic_key = LicenseManager.get_active_license_key()
164
+ if not lic_key:
165
+ return None
166
+ cloud_res = cls._call_cloud_distill(raw_text, lic_key, mode="history")
167
+ if cloud_res:
168
+ DistillationCache.set(cache_key_text, cloud_res, provider="cloud-managed")
169
+ cls._clear_failure()
170
+ return cloud_res
171
+ cls._record_failure()
172
+ return None
173
+
135
174
  @classmethod
136
175
  def get_configured_providers(cls) -> Dict[str, Dict[str, Any]]:
137
176
  """Scans environment and data/config.json for configured LLM distillation keys."""
package/src/governor.py CHANGED
@@ -8,6 +8,7 @@ into a Consolidated State Ledger.
8
8
 
9
9
  import os
10
10
  import re
11
+ import json
11
12
  from typing import Dict, List, Any, Tuple, Optional
12
13
  from src.tokenizer import count_tokens
13
14
  from src.skeletonizer import Skeletonizer
package/src/guard.py CHANGED
@@ -603,8 +603,3 @@ class TokenSafeGuard:
603
603
  if "/" not in clean_pattern and rel_path.startswith(clean_pattern + "/"):
604
604
  return True
605
605
  return False
606
-
607
- @classmethod
608
- def _is_git_ignored(cls, file_path: str, repo_root: str) -> bool:
609
- """Checks if a file is covered by .gitignore in the repository."""
610
- return cls._matches_gitignore(file_path, repo_root, cls._load_gitignore_patterns(repo_root))
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__)))
@@ -63,6 +64,20 @@ UNIFIED_TOKENSAFE_RULE = (
63
64
  "`⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown>) | Cumulative Total: <total> tokens (≈$<usd> approx)`\n"
64
65
  )
65
66
 
67
+ # Short pointer written into PROJECT-level rule files when the full protocol is
68
+ # already installed at the agent-global level (~/.zcode/AGENTS.md etc.).
69
+ # Keeps every session's meta-context lean: ~110 tokens instead of ~850.
70
+ POINTER_RULE = (
71
+ "## TOKENSAFE GRAPH-FIRST OPTIMIZATION PROTOCOL\n"
72
+ "The full 12-point protocol is installed globally in the agent-level instructions "
73
+ "(~/.zcode/AGENTS.md, ~/.claude/CLAUDE.md, ~/.codex/AGENTS.md) and applies to this project. "
74
+ "Core rules: never raw grep/find or `ls -la` — use `tokensafe:scoped_search`, "
75
+ "`tokensafe:smart_read_file(path, symbol)`, `tokensafe:smart_bundle` and `tokensafe:list_dir`; "
76
+ "sanitize high-output commands via `tokensafe:sanitize_command`; check `tokensafe:context_budget` "
77
+ "before large tasks and compact via `tokensafe:compact_conversation`; never hardcode secret "
78
+ "fallbacks; append the `⚡ TokenSafe Turn Savings` footer on tool-using turns.\n"
79
+ )
80
+
66
81
  AGENTS_REGISTRY = {
67
82
  "antigravity": {
68
83
  "name": "Google Antigravity",
@@ -191,7 +206,7 @@ class AgentInstaller:
191
206
  def install_hooks_config(cls, agent_key: str) -> Tuple[bool, str]:
192
207
  """Registers TokenSafe lifecycle-hook adapters with agents that support them.
193
208
  Claude Code: SessionStart (one-shot directives) + UserPromptSubmit (TOCP
194
- injection) + PreToolUse (shell guard).
209
+ injection) + PreToolUse (shell guard) + PostToolUse (stdout compaction).
195
210
  Cursor: beforeShellExecution / beforeReadFile guards.
196
211
  Codex has no lifecycle hooks (MCP + AGENTS.md remain the integration)."""
197
212
  if agent_key == "codex":
@@ -211,7 +226,9 @@ class AgentInstaller:
211
226
  hooks = data.get("hooks") if isinstance(data.get("hooks"), dict) else {}
212
227
  prompt_entry = {"hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
213
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}]}
214
230
  session_entry = {"hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
231
+ post_bash_entry = {"matcher": "Bash", "hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
215
232
 
216
233
  def _sync_claude_event(event_name: str, default_entry: dict) -> bool:
217
234
  entries = hooks.get(event_name)
@@ -237,12 +254,14 @@ class AgentInstaller:
237
254
  _sync_claude_event("SessionStart", session_entry),
238
255
  _sync_claude_event("UserPromptSubmit", prompt_entry),
239
256
  _sync_claude_event("PreToolUse", bash_entry),
257
+ _sync_claude_event("PreToolUse", write_entry),
258
+ _sync_claude_event("PostToolUse", post_bash_entry),
240
259
  ])
241
260
  if not changed:
242
261
  return True, "TokenSafe Claude Code hooks already registered"
243
262
  data["hooks"] = hooks
244
263
  cls._atomic_write_json(config_file, data)
245
- return True, "hooks registered (SessionStart + UserPromptSubmit + PreToolUse guard)"
264
+ return True, "hooks registered (SessionStart + UserPromptSubmit + PreToolUse guard/write + PostToolUse stdout compact)"
246
265
 
247
266
  # cursor
248
267
  config_file = os.path.join(HOME, ".cursor", "hooks.json")
@@ -282,6 +301,279 @@ class AgentInstaller:
282
301
  cls._atomic_write_json(config_file, data)
283
302
  return True, "guards registered (shell + junk-read + prompt pipeline)"
284
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
+
285
577
  @classmethod
286
578
  def install_mcp_config(cls, agent_key: str) -> Tuple[bool, str]:
287
579
  """Injects TokenSafe MCP config into target agent."""
@@ -593,6 +885,23 @@ class AgentInstaller:
593
885
  skill_src = os.path.join(PROJECT_ROOT, "skills", "token-optimizer")
594
886
  cls._symlink_dir(skill_src, target_path)
595
887
 
888
+ @classmethod
889
+ def _global_rule_installed(cls) -> bool:
890
+ """True if any agent-global rules file already carries the tokensafe block,
891
+ meaning project-level files can reference it instead of duplicating it."""
892
+ for info in AGENTS_REGISTRY.values():
893
+ for key in ("agents_md_path", "rules_path"):
894
+ path = info.get(key)
895
+ if not path or not os.path.isfile(path):
896
+ continue
897
+ try:
898
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
899
+ if "<!-- tokensafe -->" in f.read():
900
+ return True
901
+ except Exception:
902
+ continue
903
+ return False
904
+
596
905
  @classmethod
597
906
  def install_project(
598
907
  cls,
@@ -627,13 +936,17 @@ class AgentInstaller:
627
936
  "---\n\n"
628
937
  )
629
938
 
939
+ # Rules dedup: when the full protocol is already installed globally,
940
+ # project files get the short pointer instead of the ~850-token block.
941
+ project_rule = POINTER_RULE if cls._global_rule_installed() else UNIFIED_TOKENSAFE_RULE
942
+
630
943
  created = []
631
944
  for rf in rule_files:
632
945
  try:
633
946
  if rf.endswith(".mdc"):
634
- cls._write_file_safely(rf, cursor_mdc_header + UNIFIED_TOKENSAFE_RULE)
947
+ cls._write_file_safely(rf, cursor_mdc_header + project_rule)
635
948
  else:
636
- cls._inject_global_rule(rf, UNIFIED_TOKENSAFE_RULE)
949
+ cls._inject_global_rule(rf, project_rule)
637
950
  created.append(os.path.relpath(rf, project_dir))
638
951
  except Exception:
639
952
  pass
@@ -760,6 +1073,7 @@ class AgentInstaller:
760
1073
 
761
1074
  print(f"\n\033[32m\033[1m✅ TokenSafe successfully connected to {installed_count} agent(s)!\033[0m")
762
1075
  print(" Restart your IDE / Agent to start saving tokens automatically.\n")
1076
+ cls.maybe_prompt_proxy_enable(context="install")
763
1077
 
764
1078
  @staticmethod
765
1079
  def _is_tokensafe_mcp_command(cmd: str) -> bool:
@@ -1105,6 +1419,7 @@ class AgentInstaller:
1105
1419
  print(f" Synchronized {synced_count} agent environments with zero-loss AST & God Nodes rules.")
1106
1420
  print(f" Run {BOLD}tokensafe stats{RESET} to view token savings.")
1107
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")
1108
1423
 
1109
1424
  def main():
1110
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 {