tokensafe 2.6.1 → 2.7.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.
Files changed (45) hide show
  1. package/bin/tokensafe +1 -1
  2. package/extensions/cursor-tokensafe/extension.js +21 -8
  3. package/hooks/claude_code_hook.py +13 -5
  4. package/hooks/cursor_hook.py +7 -4
  5. package/hooks/post_tool_use.py +24 -6
  6. package/hooks/pre_invocation.py +40 -27
  7. package/hooks/pre_tool_use.py +85 -83
  8. package/hooks/session_start.py +8 -4
  9. package/hooks/stop_hook.py +7 -4
  10. package/package.json +1 -1
  11. package/plugin.json +1 -1
  12. package/server.json +3 -3
  13. package/src/agent_firewall.py +38 -21
  14. package/src/cache_normalizer.py +39 -10
  15. package/src/cli.py +144 -91
  16. package/src/command_sanitizer.py +248 -136
  17. package/src/compactor.py +55 -25
  18. package/src/dashboard.py +17 -10
  19. package/src/deepseek_distiller.py +26 -17
  20. package/src/dependency_prefetcher.py +66 -41
  21. package/src/diff_slicer.py +23 -17
  22. package/src/distiller.py +45 -17
  23. package/src/distiller_cache.py +74 -47
  24. package/src/environment_auditor.py +34 -12
  25. package/src/governor.py +83 -26
  26. package/src/graph_engine.py +653 -140
  27. package/src/guard.py +316 -132
  28. package/src/history_compactor.py +57 -26
  29. package/src/installer.py +174 -131
  30. package/src/license_manager.py +12 -9
  31. package/src/loop_detector.py +68 -29
  32. package/src/mcp_server.py +200 -60
  33. package/src/metrics.py +141 -54
  34. package/src/paths.py +32 -6
  35. package/src/proxy.py +121 -52
  36. package/src/scoped_search.py +18 -6
  37. package/src/secret_redactor.py +78 -59
  38. package/src/skeletonizer.py +68 -13
  39. package/src/slicer.py +25 -7
  40. package/src/team_cache.py +10 -3
  41. package/src/telemetry_sync.py +110 -39
  42. package/src/tokenizer.py +24 -13
  43. package/src/treesitter_backend.py +539 -0
  44. package/src/version_checker.py +67 -32
  45. package/src/weekly_digest.py +6 -3
@@ -9,6 +9,7 @@ import sys
9
9
  import json
10
10
  import time
11
11
  import re
12
+ import shlex
12
13
  import subprocess
13
14
  import threading
14
15
  import urllib.parse
@@ -16,7 +17,7 @@ import urllib.request
16
17
  import urllib.error
17
18
  from typing import Dict, Any, Optional, Tuple
18
19
 
19
- CURRENT_VERSION = "2.6.1"
20
+ CURRENT_VERSION = "2.7.1"
20
21
  CACHE_TTL = 86400 # 24 hours
21
22
  # When the cloud is unreachable we must NOT cache the synthesized "up to date"
22
23
  # answer for a full day — otherwise an update released right after an outage
@@ -38,6 +39,8 @@ from src.paths import resolve_data_dir
38
39
 
39
40
  DATA_DIR = resolve_data_dir()
40
41
  CACHE_FILE = os.path.join(DATA_DIR, "version_cache.json")
42
+ _DEFAULT_DATA_DIR = DATA_DIR
43
+ _DEFAULT_CACHE_FILE = CACHE_FILE
41
44
  CLOUD_CHECK_URL = os.environ.get("TOKENSAFE_VERSION_URL", "https://api.tokensafe.dev/api/version/check")
42
45
 
43
46
  # ANSI color codes
@@ -66,10 +69,21 @@ def semver_tuple(v_str: str) -> Tuple[int, ...]:
66
69
  class VersionChecker:
67
70
  """Manages cached client-side version discovery and CLI banners."""
68
71
 
72
+ @classmethod
73
+ def _effective_data_dir(cls) -> str:
74
+ if DATA_DIR != _DEFAULT_DATA_DIR:
75
+ return DATA_DIR
76
+ return resolve_data_dir()
77
+
69
78
  @classmethod
70
79
  def get_cache_path(cls) -> str:
71
- os.makedirs(DATA_DIR, exist_ok=True)
72
- return CACHE_FILE
80
+ if CACHE_FILE != _DEFAULT_CACHE_FILE:
81
+ parent = os.path.dirname(CACHE_FILE) or "."
82
+ os.makedirs(parent, exist_ok=True)
83
+ return CACHE_FILE
84
+ dd = cls._effective_data_dir()
85
+ os.makedirs(dd, exist_ok=True)
86
+ return os.path.join(dd, "version_cache.json")
73
87
 
74
88
  @classmethod
75
89
  def load_cache(cls) -> Optional[Dict[str, Any]]:
@@ -78,7 +92,8 @@ class VersionChecker:
78
92
  return None
79
93
  try:
80
94
  with open(cache_path, "r", encoding="utf-8") as f:
81
- return json.load(f)
95
+ data = json.load(f)
96
+ return data if isinstance(data, dict) else None
82
97
  except Exception:
83
98
  return None
84
99
 
@@ -86,8 +101,10 @@ class VersionChecker:
86
101
  def save_cache(cls, data: Dict[str, Any]):
87
102
  cache_path = cls.get_cache_path()
88
103
  try:
89
- with open(cache_path, "w", encoding="utf-8") as f:
104
+ tmp = f"{cache_path}.tmp.{os.getpid()}.{threading.get_ident()}"
105
+ with open(tmp, "w", encoding="utf-8") as f:
90
106
  json.dump(data, f, indent=2)
107
+ os.replace(tmp, cache_path)
91
108
  except Exception:
92
109
  pass
93
110
 
@@ -178,12 +195,24 @@ class VersionChecker:
178
195
  return payload
179
196
 
180
197
  @classmethod
181
- def get_banner(cls, current_version: str = CURRENT_VERSION, license_key: str = "") -> Optional[str]:
198
+ def get_banner(
199
+ cls,
200
+ current_version: str = CURRENT_VERSION,
201
+ license_key: str = "",
202
+ cache_only: bool = False,
203
+ ) -> Optional[str]:
182
204
  """
183
205
  Returns a styled ANSI banner string if an update is available or required,
184
- or None if up to date.
206
+ or None if up to date. When cache_only=True, reads cached version state
207
+ without blocking on network roundtrips.
185
208
  """
186
- info = cls.check_version(current_version=current_version, license_key=license_key)
209
+ if cache_only:
210
+ cached = cls.load_cache()
211
+ if not cls._cache_matches_version(cached, current_version):
212
+ return None
213
+ info = cached or {}
214
+ else:
215
+ info = cls.check_version(current_version=current_version, license_key=license_key)
187
216
  force_update = info.get("force_update", False)
188
217
  update_available = info.get("update_available", False)
189
218
  latest = info.get("latest_version", current_version)
@@ -294,11 +323,12 @@ class VersionChecker:
294
323
 
295
324
  def _zenity_wait():
296
325
  if p.wait() == 0:
326
+ cmd_argv = shlex.split(update_command) or [update_command]
297
327
  for term in (
298
- ["x-terminal-emulator", "-e", update_command],
299
- ["gnome-terminal", "--", update_command],
300
- ["konsole", "-e", update_command],
301
- ["xterm", "-e", update_command]
328
+ ["x-terminal-emulator", "-e", *cmd_argv],
329
+ ["gnome-terminal", "--", *cmd_argv],
330
+ ["konsole", "-e", *cmd_argv],
331
+ ["xterm", "-e", *cmd_argv],
302
332
  ):
303
333
  try:
304
334
  subprocess.Popen(term)
@@ -344,42 +374,39 @@ class VersionChecker:
344
374
  if not update_available and not force:
345
375
  return False
346
376
 
347
- cached = cls.load_cache() or {}
377
+ # Cross-process claim BEFORE checking/updating last_os_notify_at so two concurrent
378
+ # processes never both pass the 24h guard and show duplicate dialogs.
379
+ dd = cls._effective_data_dir()
380
+ os.makedirs(dd, exist_ok=True)
381
+ claim_path = os.path.join(dd, ".update_dialog.claim")
348
382
  now = int(time.time())
349
- last_notified_ver = cached.get("last_os_notify_version", "")
350
- last_notified_at = cached.get("last_os_notify_at", 0)
351
-
352
- if not force and last_notified_ver == latest and (now - last_notified_at) < CACHE_TTL:
353
- return False
354
-
355
- # Cross-process claim: several agent hook processes can pass the 24h
356
- # cache check simultaneously (Antigravity + ZCode + adapters), which
357
- # rendered the update dialog TWICE. Only the process that wins the
358
- # O_EXCL claim shows the dialog; the claim self-expires.
359
- claim_path = os.path.join(DATA_DIR, ".update_dialog.claim")
360
383
  try:
361
384
  if os.path.exists(claim_path):
362
385
  if (now - os.path.getmtime(claim_path)) < 60:
363
386
  return False
364
- os.remove(claim_path) # stale claim: safe to reclaim (O_EXCL guards the race)
387
+ os.remove(claim_path)
365
388
  fd = os.open(claim_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
366
389
  os.write(fd, str(os.getpid()).encode("utf-8"))
367
390
  os.close(fd)
368
391
  except FileExistsError:
369
392
  return False
370
393
  except OSError:
371
- pass # claim is best-effort; never block the dialog entirely on fs errors
394
+ pass
372
395
 
373
396
  try:
397
+ # Re-read cache inside the lock/claim so stale or concurrent updates are visible
398
+ cached = cls.load_cache() or dict(info)
399
+ last_notified_ver = cached.get("last_os_notify_version", "")
400
+ last_notified_at = cached.get("last_os_notify_at", 0)
401
+ if not force and last_notified_ver == latest and (now - last_notified_at) < CACHE_TTL:
402
+ return False
403
+
374
404
  dispatched = cls.show_os_dialog(
375
405
  current_version=current_version,
376
406
  latest_version=latest,
377
407
  update_command=cmd
378
408
  )
379
409
  if dispatched:
380
- # Mark "notified" only after the dialog actually dispatched.
381
- # Writing it earlier let a silently TCC-blocked osascript buy
382
- # 24h of dialog silence without the user ever seeing anything.
383
410
  try:
384
411
  cached["last_os_notify_version"] = latest
385
412
  cached["last_os_notify_at"] = now
@@ -388,7 +415,6 @@ class VersionChecker:
388
415
  pass
389
416
  return dispatched
390
417
  finally:
391
- # Release the dialog claim so a future version can notify again.
392
418
  try:
393
419
  os.remove(claim_path)
394
420
  except OSError:
@@ -429,12 +455,16 @@ class VersionChecker:
429
455
  if os.name == "nt":
430
456
  flags = subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.DETACHED_PROCESS
431
457
  script_path = os.path.abspath(__file__)
432
- cmd = [sys.executable, script_path, "--check-bg"]
458
+ cmd = [sys.executable, script_path, "--check-bg", f"--current-version={current_version}"]
433
459
  if force:
434
460
  cmd.append("--force")
461
+ child_env = dict(os.environ)
462
+ if license_key:
463
+ child_env["TOKENSAFE_BG_LICENSE_KEY"] = license_key
435
464
  subprocess.Popen(
436
465
  cmd,
437
466
  cwd=PROJECT_ROOT,
467
+ env=child_env,
438
468
  stdout=subprocess.DEVNULL,
439
469
  stderr=subprocess.DEVNULL,
440
470
  stdin=subprocess.DEVNULL,
@@ -449,6 +479,11 @@ if __name__ == "__main__":
449
479
  if "--check-bg" in sys.argv:
450
480
  try:
451
481
  is_force = "--force" in sys.argv
452
- VersionChecker.notify_os_update(force=is_force)
482
+ bg_ver = CURRENT_VERSION
483
+ for a in sys.argv[1:]:
484
+ if a.startswith("--current-version="):
485
+ bg_ver = a.split("=", 1)[1].strip() or CURRENT_VERSION
486
+ bg_key = os.environ.get("TOKENSAFE_BG_LICENSE_KEY", "")
487
+ VersionChecker.notify_os_update(current_version=bg_ver, license_key=bg_key, force=is_force)
453
488
  except Exception:
454
489
  pass
@@ -145,13 +145,16 @@ class WeeklyDigestGenerator:
145
145
  team_emails.add(str(lic["customer_email"]).strip().lower())
146
146
 
147
147
  placeholders = ",".join(["?"] * len(team_emails))
148
- params = list(team_emails) + [seven_days_ago]
148
+ params = list(team_emails) + [seven_days_ago, now]
149
149
 
150
- # 3. Aggregate 7-day telemetry
150
+ # 3. Aggregate 7-day telemetry (bounded [seven_days_ago, now], excluding synthetic ROLLUP_LIFETIME)
151
151
  events = conn.execute(
152
152
  f"""
153
153
  SELECT * FROM telemetry
154
- WHERE customer_email IN ({placeholders}) AND timestamp >= ?
154
+ WHERE customer_email IN ({placeholders})
155
+ AND timestamp >= ?
156
+ AND timestamp <= ?
157
+ AND COALESCE(event_type, '') != 'ROLLUP_LIFETIME'
155
158
  ORDER BY timestamp DESC;
156
159
  """,
157
160
  params,