tokensafe 2.7.0 → 2.7.2

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 (44) 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 +139 -83
  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 +65 -40
  21. package/src/diff_slicer.py +23 -17
  22. package/src/distiller.py +45 -17
  23. package/src/distiller_cache.py +80 -48
  24. package/src/environment_auditor.py +34 -12
  25. package/src/governor.py +83 -26
  26. package/src/graph_engine.py +1 -1
  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 +206 -65
  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/slicer.py +15 -3
  39. package/src/team_cache.py +89 -16
  40. package/src/telemetry_sync.py +110 -39
  41. package/src/tokenizer.py +24 -13
  42. package/src/treesitter_backend.py +1 -0
  43. package/src/version_checker.py +67 -32
  44. package/src/weekly_digest.py +6 -3
@@ -35,9 +35,40 @@ from src.metrics import resolve_measurement
35
35
  from src.paths import resolve_data_dir
36
36
 
37
37
  DATA_DIR = resolve_data_dir()
38
- METRICS_DB_PATH = os.path.join(DATA_DIR, "metrics.db")
38
+ METRICS_DB_PATH = os.environ.get("TOKENSAFE_DB_PATH") or os.path.join(DATA_DIR, "metrics.db")
39
39
  SYNC_STATE_PATH = os.path.join(DATA_DIR, "sync_state.json")
40
40
  SYNC_LOCK_PATH = os.path.join(DATA_DIR, ".sync.lock")
41
+ _DEFAULT_DATA_DIR = DATA_DIR
42
+ _DEFAULT_METRICS_DB_PATH = METRICS_DB_PATH
43
+ _DEFAULT_SYNC_STATE_PATH = SYNC_STATE_PATH
44
+ _DEFAULT_SYNC_LOCK_PATH = SYNC_LOCK_PATH
45
+
46
+
47
+ def _data_dir() -> str:
48
+ if DATA_DIR != _DEFAULT_DATA_DIR:
49
+ return DATA_DIR
50
+ return resolve_data_dir()
51
+
52
+
53
+ def _metrics_db_path() -> str:
54
+ if METRICS_DB_PATH != _DEFAULT_METRICS_DB_PATH:
55
+ return METRICS_DB_PATH
56
+ explicit = os.environ.get("TOKENSAFE_DB_PATH", "").strip()
57
+ if explicit:
58
+ return explicit
59
+ return os.path.join(_data_dir(), "metrics.db")
60
+
61
+
62
+ def _sync_state_path() -> str:
63
+ if SYNC_STATE_PATH != _DEFAULT_SYNC_STATE_PATH:
64
+ return SYNC_STATE_PATH
65
+ return os.path.join(_data_dir(), "sync_state.json")
66
+
67
+
68
+ def _sync_lock_path() -> str:
69
+ if SYNC_LOCK_PATH != _DEFAULT_SYNC_LOCK_PATH:
70
+ return SYNC_LOCK_PATH
71
+ return os.path.join(_data_dir(), ".sync.lock")
41
72
 
42
73
 
43
74
  def _get_cloud_url() -> str:
@@ -61,7 +92,8 @@ class TelemetrySync:
61
92
  @classmethod
62
93
  def get_state(cls) -> Dict[str, Any]:
63
94
  """Loads sync cursor state from persistent JSON."""
64
- if not os.path.exists(SYNC_STATE_PATH):
95
+ state_path = _sync_state_path()
96
+ if not os.path.exists(state_path):
65
97
  return {
66
98
  "last_synced_event_id": 0,
67
99
  "last_synced_at": 0,
@@ -69,8 +101,14 @@ class TelemetrySync:
69
101
  "lifetime_rollup_synced": False
70
102
  }
71
103
  try:
72
- with open(SYNC_STATE_PATH, "r", encoding="utf-8") as f:
73
- return json.load(f)
104
+ with open(state_path, "r", encoding="utf-8") as f:
105
+ data = json.load(f)
106
+ return data if isinstance(data, dict) else {
107
+ "last_synced_event_id": 0,
108
+ "last_synced_at": 0,
109
+ "total_synced_events": 0,
110
+ "lifetime_rollup_synced": False
111
+ }
74
112
  except Exception:
75
113
  return {
76
114
  "last_synced_event_id": 0,
@@ -81,11 +119,14 @@ class TelemetrySync:
81
119
 
82
120
  @classmethod
83
121
  def save_state(cls, state: Dict[str, Any]):
84
- """Persists sync cursor state."""
85
- os.makedirs(DATA_DIR, exist_ok=True)
122
+ """Persists sync cursor state atomically."""
123
+ state_path = _sync_state_path()
124
+ os.makedirs(os.path.dirname(state_path) or ".", exist_ok=True)
86
125
  try:
87
- with open(SYNC_STATE_PATH, "w", encoding="utf-8") as f:
126
+ tmp_path = f"{state_path}.tmp.{os.getpid()}.{threading.get_ident()}"
127
+ with open(tmp_path, "w", encoding="utf-8") as f:
88
128
  json.dump(state, f, indent=2)
129
+ os.replace(tmp_path, state_path)
89
130
  except Exception:
90
131
  pass
91
132
 
@@ -97,9 +138,10 @@ class TelemetrySync:
97
138
 
98
139
  total_local = 0
99
140
  pending = 0
100
- if os.path.exists(METRICS_DB_PATH):
141
+ db_path = _metrics_db_path()
142
+ if os.path.exists(db_path):
101
143
  try:
102
- conn = sqlite3.connect(METRICS_DB_PATH)
144
+ conn = sqlite3.connect(db_path)
103
145
  c = conn.cursor()
104
146
  row = c.execute("SELECT COUNT(*) FROM events").fetchone()
105
147
  total_local = row[0] if row else 0
@@ -145,17 +187,24 @@ class TelemetrySync:
145
187
  active_key = license_key or LicenseManager.get_active_license_key()
146
188
 
147
189
  target_email = (email or "").strip().lower()
148
- if not target_email and active_key:
149
- _, payload, _ = LicenseManager.validate_license(active_key)
150
- target_email = payload.get("email", "").strip().lower()
151
-
152
- # Community fallback: unauthenticated users participate in global token savings
190
+ if active_key and not active_key.startswith("ts_live_"):
191
+ is_valid, payload, _ = LicenseManager.validate_license(active_key)
192
+ if not is_valid:
193
+ # Expired/revoked license must downgrade to Community sync instead of getting 401 forever
194
+ active_key = ""
195
+ if not target_email:
196
+ target_email = ""
197
+ elif not target_email:
198
+ target_email = str(payload.get("email", "")).strip().lower()
199
+
200
+ # Community fallback: unauthenticated or expired users participate in global community sync
153
201
  if not target_email:
154
202
  target_email = "community@tokensafe.dev"
155
203
  if not active_key:
156
204
  active_key = "community"
157
205
 
158
- if not os.path.exists(METRICS_DB_PATH):
206
+ db_path = _metrics_db_path()
207
+ if not os.path.exists(db_path):
159
208
  return {
160
209
  "success": True,
161
210
  "synced_events": 0,
@@ -168,7 +217,7 @@ class TelemetrySync:
168
217
 
169
218
  try:
170
219
  from src.metrics import MetricsTracker
171
- local_monthly_measured = MetricsTracker(db_path=METRICS_DB_PATH).get_monthly_saved_tokens(measured_only=True)
220
+ local_monthly_measured = MetricsTracker(db_path=db_path).get_monthly_saved_tokens(measured_only=True)
172
221
  except Exception:
173
222
  local_monthly_measured = 0
174
223
  machine_fp = "" if os.environ.get("TOKENSAFE_TELEMETRY_DISABLED") in ("1", "true", "yes") else LicenseManager.get_machine_fingerprint()
@@ -179,7 +228,7 @@ class TelemetrySync:
179
228
  current_last_id = last_id
180
229
  headers = {
181
230
  "Content-Type": "application/json",
182
- "User-Agent": "TokenSafe-Sync/2.7.0"
231
+ "User-Agent": "TokenSafe-Sync/2.7.2"
183
232
  }
184
233
  if active_key:
185
234
  headers["Authorization"] = f"Bearer {active_key}"
@@ -189,6 +238,8 @@ class TelemetrySync:
189
238
  "last_synced_event_id": current_last_id,
190
239
  "last_synced_at": state.get("last_synced_at", 0) if total_sent == 0 else int(time.time()),
191
240
  "last_attempt_at": int(time.time()),
241
+ "last_quota_sync_at": state.get("last_quota_sync_at", 0),
242
+ "consecutive_failures": int(state.get("consecutive_failures", 0) or 0) + 1,
192
243
  "total_synced_events": cumulative_synced,
193
244
  "lifetime_rollup_synced": rollup_synced
194
245
  }
@@ -203,7 +254,7 @@ class TelemetrySync:
203
254
  max_pages = 25
204
255
  for page_idx in range(max_pages):
205
256
  try:
206
- conn = sqlite3.connect(METRICS_DB_PATH)
257
+ conn = sqlite3.connect(db_path)
207
258
  conn.row_factory = sqlite3.Row
208
259
  cur = conn.cursor()
209
260
 
@@ -327,7 +378,7 @@ class TelemetrySync:
327
378
  srv_measured = int(resp_body.get("server_monthly_measured_saved") or 0)
328
379
  if srv_measured > 0:
329
380
  from src.metrics import MetricsTracker
330
- MetricsTracker(db_path=METRICS_DB_PATH).record_server_quota_floor(srv_measured)
381
+ MetricsTracker(db_path=db_path).record_server_quota_floor(srv_measured)
331
382
  except Exception:
332
383
  pass
333
384
  total_sent += len(chunk)
@@ -344,6 +395,7 @@ class TelemetrySync:
344
395
  "last_synced_at": int(time.time()),
345
396
  "last_attempt_at": int(time.time()),
346
397
  "last_quota_sync_at": int(time.time()),
398
+ "consecutive_failures": 0,
347
399
  "total_synced_events": cumulative_synced,
348
400
  "lifetime_rollup_synced": rollup_synced
349
401
  })
@@ -368,6 +420,22 @@ class TelemetrySync:
368
420
  def _is_pid_alive(pid: int) -> bool:
369
421
  if pid <= 0:
370
422
  return False
423
+ if os.name == "nt":
424
+ try:
425
+ import ctypes
426
+ SYNCHRONIZE = 0x00100000
427
+ PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
428
+ handle = ctypes.windll.kernel32.OpenProcess(SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, False, int(pid))
429
+ if not handle:
430
+ return False
431
+ try:
432
+ code = ctypes.c_ulong()
433
+ ok = ctypes.windll.kernel32.GetExitCodeProcess(handle, ctypes.byref(code))
434
+ return bool(ok and code.value == 259) # STILL_ACTIVE
435
+ finally:
436
+ ctypes.windll.kernel32.CloseHandle(handle)
437
+ except Exception:
438
+ return False
371
439
  try:
372
440
  os.kill(pid, 0)
373
441
  return True
@@ -414,23 +482,25 @@ class TelemetrySync:
414
482
  now = time.time()
415
483
  state = cls.get_state()
416
484
  last_synced = max(state.get("last_synced_at", 0), state.get("last_attempt_at", 0))
417
- if not force and (now - last_synced) < throttle_seconds:
485
+ failures = int(state.get("consecutive_failures", 0) or 0)
486
+ eff_throttle = throttle_seconds
487
+ if not force and failures > 0:
488
+ eff_throttle = min(300.0, max(throttle_seconds, throttle_seconds * (2 ** min(failures, 4))))
489
+ if not force and (now - last_synced) < eff_throttle:
418
490
  return
419
491
 
420
492
  status = cls.get_sync_status()
421
493
  if status.get("pending_events", 0) == 0:
422
494
  return
423
495
 
424
- os.makedirs(DATA_DIR, exist_ok=True)
425
- # Claim a short-lived spawn handoff token atomically so concurrent hooks
426
- # don't spawn duplicate workers, while the spawned child replaces the
427
- # lock with its own `worker:<pid>` instead of deadlocking on parent PID.
496
+ lock_path = _sync_lock_path()
497
+ os.makedirs(os.path.dirname(lock_path) or ".", exist_ok=True)
428
498
  claim_token = secrets.token_hex(8)
429
499
  spawn_marker = f"spawn:{claim_token}:{now:.3f}"
430
500
  lock_claimed = False
431
501
  for _ in range(2):
432
502
  try:
433
- fd = os.open(SYNC_LOCK_PATH, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
503
+ fd = os.open(lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
434
504
  try:
435
505
  os.write(fd, spawn_marker.encode("utf-8"))
436
506
  finally:
@@ -439,15 +509,14 @@ class TelemetrySync:
439
509
  break
440
510
  except FileExistsError:
441
511
  try:
442
- with open(SYNC_LOCK_PATH, "r", encoding="utf-8") as f:
512
+ with open(lock_path, "r", encoding="utf-8") as f:
443
513
  existing = f.read()
444
514
  if cls._lock_is_active(existing, allow_legacy_self=False):
445
515
  return
446
516
  except OSError:
447
517
  return
448
- # Stale spawn/dead-worker/legacy-self lock: reclaim it once
449
518
  try:
450
- os.unlink(SYNC_LOCK_PATH)
519
+ os.unlink(lock_path)
451
520
  except OSError:
452
521
  return
453
522
  if not lock_claimed:
@@ -469,19 +538,20 @@ class TelemetrySync:
469
538
  )
470
539
  except Exception:
471
540
  try:
472
- with open(SYNC_LOCK_PATH, "r", encoding="utf-8") as f:
541
+ with open(lock_path, "r", encoding="utf-8") as f:
473
542
  if f.read().strip() == spawn_marker:
474
- os.unlink(SYNC_LOCK_PATH)
543
+ os.unlink(lock_path)
475
544
  except OSError:
476
545
  pass
477
546
 
478
547
 
479
548
  def _claim_worker_lock(claim_token: str) -> bool:
480
549
  """Claims or takes over .sync.lock for the current sync worker process."""
550
+ lock_path = _sync_lock_path()
481
551
  worker_marker = f"worker:{os.getpid()}"
482
552
  for _ in range(2):
483
553
  try:
484
- fd = os.open(SYNC_LOCK_PATH, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
554
+ fd = os.open(lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
485
555
  try:
486
556
  os.write(fd, worker_marker.encode("utf-8"))
487
557
  finally:
@@ -489,20 +559,20 @@ def _claim_worker_lock(claim_token: str) -> bool:
489
559
  return True
490
560
  except FileExistsError:
491
561
  try:
492
- with open(SYNC_LOCK_PATH, "r", encoding="utf-8") as f:
562
+ with open(lock_path, "r", encoding="utf-8") as f:
493
563
  existing = f.read().strip()
494
564
  except OSError:
495
565
  return False
496
566
 
497
567
  if claim_token and existing.startswith(f"spawn:{claim_token}:"):
498
- tmp_path = f"{SYNC_LOCK_PATH}.{os.getpid()}.tmp"
568
+ tmp_path = f"{lock_path}.{os.getpid()}.tmp"
499
569
  try:
500
570
  fd = os.open(tmp_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
501
571
  try:
502
572
  os.write(fd, worker_marker.encode("utf-8"))
503
573
  finally:
504
574
  os.close(fd)
505
- os.replace(tmp_path, SYNC_LOCK_PATH)
575
+ os.replace(tmp_path, lock_path)
506
576
  return True
507
577
  except OSError:
508
578
  try:
@@ -516,7 +586,7 @@ def _claim_worker_lock(claim_token: str) -> bool:
516
586
  return False
517
587
 
518
588
  try:
519
- os.unlink(SYNC_LOCK_PATH)
589
+ os.unlink(lock_path)
520
590
  except OSError:
521
591
  return False
522
592
  return False
@@ -529,19 +599,20 @@ if __name__ == "__main__":
529
599
  if arg.startswith("--claim-token="):
530
600
  claim_token = arg.split("=", 1)[1].strip()
531
601
 
532
- os.makedirs(DATA_DIR, exist_ok=True)
602
+ lock_path = _sync_lock_path()
603
+ os.makedirs(os.path.dirname(lock_path) or ".", exist_ok=True)
533
604
  if not _claim_worker_lock(claim_token):
534
605
  sys.exit(0)
535
606
 
536
607
  worker_marker = f"worker:{os.getpid()}"
537
608
  try:
538
- res = TelemetrySync.sync(timeout=10.0, verbose=not is_bg)
609
+ res = TelemetrySync.sync(timeout=2.5 if is_bg else 10.0, verbose=not is_bg)
539
610
  if not is_bg:
540
611
  print(json.dumps(res, indent=2))
541
612
  finally:
542
613
  try:
543
- with open(SYNC_LOCK_PATH, "r", encoding="utf-8") as f:
614
+ with open(lock_path, "r", encoding="utf-8") as f:
544
615
  if f.read().strip() == worker_marker:
545
- os.remove(SYNC_LOCK_PATH)
616
+ os.remove(lock_path)
546
617
  except Exception:
547
618
  pass
package/src/tokenizer.py CHANGED
@@ -7,22 +7,30 @@ Supports English, Cyrillic, CJK, and code-heavy payloads.
7
7
  import re
8
8
  from typing import Optional
9
9
 
10
- try:
11
- import tiktoken # type: ignore
12
- _TIKTOKEN_ENCODING = tiktoken.get_encoding("cl100k_base")
13
- except Exception:
14
- _TIKTOKEN_ENCODING = None
10
+ _TIKTOKEN_ENCODING = None
11
+ _TIKTOKEN_PROBED = False
12
+
13
+
14
+ def _get_tiktoken_encoding():
15
+ global _TIKTOKEN_ENCODING, _TIKTOKEN_PROBED
16
+ if _TIKTOKEN_PROBED:
17
+ return _TIKTOKEN_ENCODING
18
+ _TIKTOKEN_PROBED = True
19
+ try:
20
+ import tiktoken # type: ignore
21
+ _TIKTOKEN_ENCODING = tiktoken.get_encoding("cl100k_base")
22
+ except Exception:
23
+ _TIKTOKEN_ENCODING = None
24
+ return _TIKTOKEN_ENCODING
15
25
 
16
26
 
17
27
  class TokenCounter:
18
28
  """Estimates or calculates token counts across languages and code structures."""
19
29
 
20
- # Robust regex splitting on words, contractions, numbers, punctuation, whitespace.
21
- # CJK ideographs / kana / hangul are matched explicitly: they are Unicode word
22
- # characters (\w) so the [^\w\s] branch never captures them, and without an
23
- # explicit branch they silently disappeared from token counts entirely.
30
+ # Robust regex splitting on words (incl. extended Latin & Cyrillic), contractions,
31
+ # numbers, punctuation runs, CJK, and whitespace.
24
32
  _WORD_REGEX = re.compile(
25
- r"""'s|'t|'re|'ve|'m|'ll|'d|[a-zA-Zа-яА-ЯёЁ_]+|\d{1,3}|[\u3400-\u4DBF\u4E00-\u9FFF\uF900-\uFAFF\u3040-\u30FF\u31F0-\u31FF\uAC00-\uD7AF]+|[^\w\s]|\s+"""
33
+ r"""'s|'t|'re|'ve|'m|'ll|'d|[a-zA-Z\u00C0-\u024F\u0400-\u04FF_]+|\d{1,3}|[\u3400-\u4DBF\u4E00-\u9FFF\uF900-\uFAFF\u3040-\u30FF\u31F0-\u31FF\uAC00-\uD7AF]+|[^\w\s]+|\s+"""
26
34
  )
27
35
 
28
36
  @classmethod
@@ -31,10 +39,11 @@ class TokenCounter:
31
39
  if not text:
32
40
  return 0
33
41
 
34
- # If tiktoken is installed, use exact OpenAI BPE cl100k
35
- if _TIKTOKEN_ENCODING is not None:
42
+ # If tiktoken is installed, use exact OpenAI BPE cl100k (allowing literal special tokens)
43
+ enc = _get_tiktoken_encoding()
44
+ if enc is not None:
36
45
  try:
37
- return len(_TIKTOKEN_ENCODING.encode(text))
46
+ return len(enc.encode(text, disallowed_special=()))
38
47
  except Exception:
39
48
  pass
40
49
 
@@ -75,7 +84,9 @@ class TokenCounter:
75
84
  is_cjk = any(
76
85
  '\u4E00' <= char <= '\u9FFF' # CJK Unified Ideographs
77
86
  or '\u3400' <= char <= '\u4DBF' # CJK Extension A
87
+ or '\uF900' <= char <= '\uFAFF' # CJK Compatibility Ideographs
78
88
  or '\u3040' <= char <= '\u30FF' # Hiragana / Katakana
89
+ or '\u31F0' <= char <= '\u31FF' # Katakana Phonetic Extensions
79
90
  or '\uAC00' <= char <= '\uD7AF' # Hangul syllables
80
91
  for char in chunk
81
92
  )
@@ -48,6 +48,7 @@ _CONTAINER_NODE_TYPES = {
48
48
  "trait_item",
49
49
  "trait_declaration",
50
50
  "interface_declaration",
51
+ "type_alias_declaration",
51
52
  "record_declaration",
52
53
  "enum_declaration",
53
54
  "enum_item",
@@ -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.7.0"
20
+ CURRENT_VERSION = "2.7.2"
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,