tokensafe 1.4.13 → 1.4.14

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.
@@ -5,7 +5,9 @@ and triggers confirmation to prevent infinite token drain loops.
5
5
 
6
6
  import os
7
7
  import json
8
+ import time
8
9
  import hashlib
10
+ from contextlib import contextmanager
9
11
  from typing import Dict, Any, Tuple
10
12
 
11
13
  class LoopDetector:
@@ -13,6 +15,7 @@ class LoopDetector:
13
15
 
14
16
  STATE_FILE = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "data", "loop_state.json")
15
17
  MAX_IDENTICAL_REPEATS = 3
18
+ SESSION_TTL_SECONDS = 48 * 3600 # prune sessions idle for more than 2 days
16
19
 
17
20
  @classmethod
18
21
  def _get_call_signature(cls, tool_name: str, args: Dict[str, Any]) -> str:
@@ -20,6 +23,54 @@ class LoopDetector:
20
23
  args_str = json.dumps(args, sort_keys=True, default=str)
21
24
  return hashlib.sha256(f"{tool_name}:{args_str}".encode("utf-8")).hexdigest()[:16]
22
25
 
26
+ @classmethod
27
+ @contextmanager
28
+ def _locked_state(cls):
29
+ """
30
+ Exclusive read-modify-write guard for the shared state file.
31
+ Hooks for parallel tool calls run as concurrent processes; without the lock
32
+ their increments overwrote each other and identical calls went undetected.
33
+ Uses fcntl on POSIX and degrades to lock-free (best effort) elsewhere.
34
+ """
35
+ os.makedirs(os.path.dirname(cls.STATE_FILE), exist_ok=True)
36
+ lock_path = cls.STATE_FILE + ".lock"
37
+ handle = open(lock_path, "w")
38
+ locked = False
39
+ try:
40
+ try:
41
+ import fcntl
42
+ fcntl.flock(handle.fileno(), fcntl.LOCK_EX)
43
+ locked = True
44
+ except ImportError:
45
+ pass
46
+ yield
47
+ finally:
48
+ try:
49
+ if locked:
50
+ import fcntl
51
+ fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
52
+ except Exception:
53
+ pass
54
+ handle.close()
55
+
56
+ @classmethod
57
+ def _load_state(cls) -> Dict[str, Any]:
58
+ if os.path.exists(cls.STATE_FILE):
59
+ try:
60
+ with open(cls.STATE_FILE, "r", encoding="utf-8") as f:
61
+ return json.load(f)
62
+ except Exception:
63
+ return {}
64
+ return {}
65
+
66
+ @classmethod
67
+ def _save_state(cls, state: Dict[str, Any]):
68
+ try:
69
+ with open(cls.STATE_FILE, "w", encoding="utf-8") as f:
70
+ json.dump(state, f)
71
+ except Exception:
72
+ pass
73
+
23
74
  @classmethod
24
75
  def check_loop(cls, conversation_id: str, tool_name: str, args: Dict[str, Any]) -> Tuple[bool, int, str]:
25
76
  """
@@ -30,37 +81,33 @@ class LoopDetector:
30
81
  return False, 0, ""
31
82
 
32
83
  signature = cls._get_call_signature(tool_name, args)
33
- state = {}
34
84
 
35
- if os.path.exists(cls.STATE_FILE):
36
- try:
37
- with open(cls.STATE_FILE, "r", encoding="utf-8") as f:
38
- state = json.load(f)
39
- except Exception:
40
- state = {}
85
+ with cls._locked_state():
86
+ state = cls._load_state()
41
87
 
42
- session_state = state.get(conversation_id, {
43
- "last_sig": "",
44
- "repeat_count": 0,
45
- "tool_name": ""
46
- })
88
+ # Prune stale sessions so the state file cannot grow unboundedly
89
+ now = time.time()
90
+ stale = [cid for cid, s in state.items()
91
+ if not isinstance(s, dict) or (now - float(s.get("updated", 0))) > cls.SESSION_TTL_SECONDS]
92
+ for cid in stale:
93
+ state.pop(cid, None)
47
94
 
48
- if session_state.get("last_sig") == signature:
49
- session_state["repeat_count"] = session_state.get("repeat_count", 0) + 1
50
- else:
51
- session_state["last_sig"] = signature
52
- session_state["repeat_count"] = 1
53
- session_state["tool_name"] = tool_name
95
+ session_state = state.get(conversation_id, {
96
+ "last_sig": "",
97
+ "repeat_count": 0,
98
+ "tool_name": ""
99
+ })
54
100
 
55
- state[conversation_id] = session_state
101
+ if session_state.get("last_sig") == signature:
102
+ session_state["repeat_count"] = session_state.get("repeat_count", 0) + 1
103
+ else:
104
+ session_state["last_sig"] = signature
105
+ session_state["repeat_count"] = 1
106
+ session_state["tool_name"] = tool_name
107
+ session_state["updated"] = now
56
108
 
57
- # Save state
58
- try:
59
- os.makedirs(os.path.dirname(cls.STATE_FILE), exist_ok=True)
60
- with open(cls.STATE_FILE, "w", encoding="utf-8") as f:
61
- json.dump(state, f)
62
- except Exception:
63
- pass
109
+ state[conversation_id] = session_state
110
+ cls._save_state(state)
64
111
 
65
112
  repeats = session_state["repeat_count"]
66
113
  if repeats >= cls.MAX_IDENTICAL_REPEATS:
package/src/mcp_server.py CHANGED
@@ -12,7 +12,7 @@ import json
12
12
  import threading
13
13
  import traceback
14
14
  import fnmatch
15
- from typing import Tuple, Optional
15
+ from typing import List, Tuple, Optional
16
16
 
17
17
  # Ensure project root in sys.path
18
18
  BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@@ -35,7 +35,7 @@ from src.scoped_search import ScopedSearch
35
35
 
36
36
  SERVER_INFO = {
37
37
  "name": "tokensafe-mcp",
38
- "version": "1.4.13"
38
+ "version": "1.4.14"
39
39
  }
40
40
 
41
41
  TOOLS = [
@@ -382,7 +382,24 @@ def handle_tool_call(name: str, args: dict) -> dict:
382
382
  if args is None or not isinstance(args, dict):
383
383
  args = {}
384
384
  try:
385
- return _dispatch_tool_call(name, args)
385
+ result = _dispatch_tool_call(name, args)
386
+ # Populate the Subagent Firewall dedup cache with what we actually returned,
387
+ # so repeated reads of the same file within a session can be served from cache.
388
+ if name == "smart_read_file" and isinstance(result, dict) and not result.get("isError"):
389
+ content_parts = result.get("content") or []
390
+ text_out = "".join(p.get("text", "") for p in content_parts if isinstance(p, dict))
391
+ if text_out:
392
+ try:
393
+ AgentFirewall.record_cache(
394
+ session_id="mcp_session",
395
+ file_path=args.get("path", ""),
396
+ content=text_out,
397
+ symbol=(args.get("symbol") or "").strip(),
398
+ tracker=_get_safe_tracker()
399
+ )
400
+ except Exception:
401
+ pass
402
+ return result
386
403
  except Exception as e:
387
404
  return _fallback_error(name, f"{type(e).__name__}: {str(e)}")
388
405
 
@@ -395,6 +412,15 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
395
412
  symbol = args.get("symbol", "")
396
413
  start_line = args.get("start_line")
397
414
  end_line = args.get("end_line")
415
+ # Clamp explicit line ranges to sane bounds so bad indices can never produce
416
+ # empty output or negative-index slicing artifacts.
417
+ try:
418
+ if start_line is not None:
419
+ start_line = max(1, int(start_line))
420
+ if end_line is not None:
421
+ end_line = int(end_line)
422
+ except (TypeError, ValueError):
423
+ return _fallback_error("smart_read_file", "start_line/end_line must be integers")
398
424
 
399
425
  if not path or not os.path.exists(path):
400
426
  return {"isError": True, "content": [{"type": "text", "text": f"File not found: {path}"}]}
@@ -421,6 +447,9 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
421
447
  if start_line is not None and end_line is not None:
422
448
  with open(path, "r", encoding="utf-8", errors="replace") as f:
423
449
  lines = f.readlines()
450
+ end_line = min(end_line, len(lines))
451
+ if start_line > end_line:
452
+ return _fallback_error("smart_read_file", f"start_line {start_line} is beyond end of file ({len(lines)} lines)")
424
453
  content = "".join(lines[start_line - 1 : end_line])
425
454
  return {"content": [{"type": "text", "text": (prefetch_block or "") + content}]}
426
455
 
@@ -738,8 +767,27 @@ def _execute_with_timeout(tool_name: str, tool_args: dict, timeout: float = MCP_
738
767
  return box["result"]
739
768
 
740
769
 
770
+ def _get_watched_mtimes() -> Tuple[Optional[float], ...]:
771
+ """Returns mtimes for core server/package files and the update reload marker."""
772
+ watched_paths = (
773
+ os.path.abspath(__file__),
774
+ os.path.join(BASE_DIR, "package.json"),
775
+ os.path.join(BASE_DIR, "data", ".mcp_reload"),
776
+ )
777
+ mtimes: List[Optional[float]] = []
778
+ for p in watched_paths:
779
+ try:
780
+ mtimes.append(os.path.getmtime(p))
781
+ except OSError:
782
+ mtimes.append(None)
783
+ return tuple(mtimes)
784
+
785
+
741
786
  def run_mcp_server():
742
- """Runs stdio JSON-RPC 2.0 loop with per-call timeout & resilient error recovery."""
787
+ """Runs stdio JSON-RPC 2.0 loop with per-call timeout, resilient recovery & auto-reload on upgrade."""
788
+ initial_mtimes = _get_watched_mtimes()
789
+ auto_reload = os.environ.get("TOKENSAFE_MCP_AUTORELOAD", "1").strip().lower() not in ("0", "false", "no")
790
+
743
791
  while True:
744
792
  try:
745
793
  line = sys.stdin.readline()
@@ -801,6 +849,12 @@ def run_mcp_server():
801
849
  except Exception:
802
850
  break
803
851
 
852
+ # Safeguard: if TokenSafe files were upgraded on disk while running, exit cleanly
853
+ # immediately after sending the response so the host IDE respawns the new version.
854
+ if auto_reload and method == "tools/call":
855
+ if _get_watched_mtimes() != initial_mtimes:
856
+ break
857
+
804
858
  def main():
805
859
  run_mcp_server()
806
860
 
package/src/metrics.py CHANGED
@@ -6,6 +6,7 @@ Uses SQLite for persistent, fast, zero-dependency storage.
6
6
 
7
7
  import os
8
8
  import json
9
+ import time
9
10
  import sqlite3
10
11
  import threading
11
12
  from contextlib import contextmanager
@@ -15,6 +16,10 @@ from typing import Dict, List, Optional, Any, Generator
15
16
  USD_PER_TOKEN = 1.50 / 1_000_000.0
16
17
  _METRICS_INIT_LOCK = threading.Lock()
17
18
  _INITIALIZED_METRICS_DBS: set = set()
19
+ # Retention / telemetry cadence is wall-clock based (marker file) rather than
20
+ # instance-based counters: lifecycle hooks construct a fresh MetricsTracker per
21
+ # invocation, so per-instance counters never reached the threshold in production.
22
+ _AUTOPRUNE_INTERVAL = float(os.environ.get("TOKENSAFE_AUTOPRUNE_INTERVAL", "3600"))
18
23
 
19
24
 
20
25
  class MetricsTracker:
@@ -49,6 +54,42 @@ class MetricsTracker:
49
54
  finally:
50
55
  conn.close()
51
56
 
57
+ @classmethod
58
+ def _maybe_autoprune(cls, db_path: str):
59
+ """
60
+ Wall-clock-gated retention + telemetry trigger, safe across short-lived
61
+ hook processes. A marker file records the last run; an O_EXCL claim file
62
+ prevents stampedes when several hooks fire concurrently.
63
+ """
64
+ marker = os.path.join(os.path.dirname(db_path) or ".", ".metrics_last_prune")
65
+ claim = marker + ".claim"
66
+ try:
67
+ if os.path.exists(marker) and (time.time() - os.path.getmtime(marker)) < _AUTOPRUNE_INTERVAL:
68
+ return
69
+ try:
70
+ fd = os.open(claim, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
71
+ os.close(fd)
72
+ except FileExistsError:
73
+ return # another process is pruning right now
74
+ try:
75
+ tracker = cls(db_path)
76
+ tracker.prune(days=tracker.retention_days, max_events=tracker.max_events, vacuum=False)
77
+ try:
78
+ from src.telemetry_sync import TelemetrySync
79
+ TelemetrySync.sync_background()
80
+ except Exception:
81
+ pass
82
+ finally:
83
+ try:
84
+ with open(marker, "w", encoding="utf-8") as f:
85
+ f.write(str(int(time.time())))
86
+ if os.path.exists(claim):
87
+ os.unlink(claim)
88
+ except Exception:
89
+ pass
90
+ except Exception:
91
+ pass
92
+
52
93
  def _init_db(self):
53
94
  with _METRICS_INIT_LOCK:
54
95
  if self.db_path in _INITIALIZED_METRICS_DBS and os.path.exists(self.db_path) and os.path.getsize(self.db_path) > 0:
@@ -146,20 +187,8 @@ class MetricsTracker:
146
187
  """, (session_id, now_iso, now_iso, original_tokens,
147
188
  optimized_tokens, saved_tokens, est_usd))
148
189
 
149
- # Periodic amortized auto-retention check (every 100 events)
150
- self._event_counter += 1
151
- if self._event_counter % 20 == 0:
152
- try:
153
- from src.telemetry_sync import TelemetrySync
154
- TelemetrySync.sync_background()
155
- except Exception:
156
- pass
157
- if self._event_counter >= 100:
158
- self._event_counter = 0
159
- try:
160
- self.prune(days=self.retention_days, max_events=self.max_events, vacuum=False)
161
- except Exception:
162
- pass
190
+ # Wall-clock auto-retention (marker-file gated, cross-process safe)
191
+ self._maybe_autoprune(self.db_path)
163
192
 
164
193
  return {
165
194
  "saved_tokens": saved_tokens,
@@ -234,7 +263,9 @@ class MetricsTracker:
234
263
 
235
264
  def get_monthly_saved_tokens(self) -> int:
236
265
  """Returns total tokens saved in the trailing 30 days for quota calculations."""
237
- thirty_days_ago = (datetime.utcnow() - timedelta(days=30)).isoformat()
266
+ # Events are written with local-time now(); compute the cutoff the same way
267
+ # (previously utcnow vs now mixed naive clocks and skewed the quota window).
268
+ thirty_days_ago = (datetime.now() - timedelta(days=30)).isoformat()
238
269
  with self._get_connection() as conn:
239
270
  cursor = conn.cursor()
240
271
  cursor.execute("""
@@ -110,6 +110,64 @@ class BraceLexer:
110
110
  class Skeletonizer:
111
111
  """Generates structural AST skeletons without LLMs with incremental mtime caching."""
112
112
 
113
+ # Design-token selectors matched on word boundaries so class names like
114
+ # `.html-widget` or identifiers like `innerHTML` no longer masquerade as tokens.
115
+ TOKEN_SELECTOR_REGEX = re.compile(r'(?<![\w.#-])(?::root|@theme|html|body)(?![\w-])')
116
+
117
+ @staticmethod
118
+ def _find_unescaped(s: str, ch: str, start: int) -> int:
119
+ """Index of the next occurrence of ch not preceded by a backslash escape."""
120
+ i = start
121
+ while True:
122
+ i = s.find(ch, i)
123
+ if i == -1:
124
+ return -1
125
+ bs = 0
126
+ j = i - 1
127
+ while j >= 0 and s[j] == "\\":
128
+ bs += 1
129
+ j -= 1
130
+ if bs % 2 == 0:
131
+ return i
132
+ i += 1
133
+
134
+ @classmethod
135
+ def blank_template_literals(cls, lines):
136
+ """
137
+ Returns per-line copies with multi-line template-literal content blanked
138
+ (single-line `...` pairs collapse to ``). Stateless over the whole buffer, so
139
+ braces inside template strings can never corrupt the brace-depth tracker —
140
+ unlike per-line state, this composes safely with the lexer being invoked
141
+ more than once per line by the folding state machine.
142
+ """
143
+ out = []
144
+ in_tmpl = False
145
+ for line in lines:
146
+ if in_tmpl:
147
+ end = cls._find_unescaped(line, "`", 0)
148
+ if end == -1:
149
+ out.append("")
150
+ continue
151
+ in_tmpl = False
152
+ line = line[end + 1:]
153
+ res = []
154
+ pos = 0
155
+ while True:
156
+ start = cls._find_unescaped(line, "`", pos)
157
+ if start == -1:
158
+ res.append(line[pos:])
159
+ break
160
+ end = cls._find_unescaped(line, "`", start + 1)
161
+ if end == -1:
162
+ res.append(line[pos:start])
163
+ in_tmpl = True
164
+ break
165
+ res.append(line[pos:start])
166
+ res.append("``")
167
+ pos = end + 1
168
+ out.append("".join(res))
169
+ return out
170
+
113
171
  CACHE_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "data", "skeletons")
114
172
 
115
173
  @classmethod
@@ -212,6 +270,9 @@ class Skeletonizer:
212
270
  5. Multi-line comment & string immunity for brace depth tracking.
213
271
  """
214
272
  lines = code.splitlines()
273
+ # Pre-blank multi-line template literals once per buffer (stateless) so braces
274
+ # inside them cannot skew the folding depth tracker.
275
+ count_src_lines = cls.blank_template_literals(lines)
215
276
  out = []
216
277
 
217
278
  lexer = BraceLexer()
@@ -226,13 +287,12 @@ class Skeletonizer:
226
287
 
227
288
  comment_token = "/* ... */" if ext != ".py" else "..."
228
289
 
229
- for line in lines:
230
- raw_line = line
231
- clean_line = lexer.clean_line(line).strip()
290
+ for raw_line, count_src in zip(lines, count_src_lines):
291
+ clean_line = lexer.clean_line(count_src).strip()
232
292
 
233
293
  # 1. If currently skipping a folded function body
234
294
  if in_folding:
235
- open_b, close_b = lexer.count_braces(raw_line)
295
+ open_b, close_b = lexer.count_braces(count_src)
236
296
  current_depth += open_b - close_b
237
297
  if current_depth <= fold_depth:
238
298
  in_folding = False
@@ -388,7 +448,7 @@ class Skeletonizer:
388
448
 
389
449
  if "{" in raw_line:
390
450
  should_keep = keep_symbols is not None and name in keep_symbols
391
- open_b, close_b = lexer.count_braces(raw_line)
451
+ open_b, close_b = lexer.count_braces(count_src)
392
452
 
393
453
  if should_keep:
394
454
  out.append(raw_line)
@@ -398,7 +458,8 @@ class Skeletonizer:
398
458
  if raw_line.rstrip().endswith(";"):
399
459
  folded_line += ";"
400
460
  out.append(folded_line)
401
- open_b_head, _ = lexer.count_braces(raw_line[:raw_line.find("{") + 1])
461
+ head_src = count_src[:count_src.find("{") + 1] if "{" in count_src else count_src
462
+ open_b_head, _ = lexer.count_braces(head_src)
402
463
  fold_depth = current_depth + open_b_head - 1
403
464
  current_depth += open_b - close_b
404
465
  if current_depth > fold_depth:
@@ -407,7 +468,7 @@ class Skeletonizer:
407
468
 
408
469
  # 4. Normal line
409
470
  out.append(raw_line)
410
- open_b, close_b = lexer.count_braces(raw_line)
471
+ open_b, close_b = lexer.count_braces(count_src)
411
472
  current_depth += open_b - close_b
412
473
 
413
474
  return "\n".join(out)
@@ -458,7 +519,7 @@ class Skeletonizer:
458
519
  full_sel = " ".join(s.strip() for s in pending_sel)
459
520
  brace_idx = raw_line.find("{")
460
521
  is_container = any(full_sel.strip().startswith(c) for c in CONTAINER_RULES)
461
- is_token = any(ts in full_sel for ts in TOKEN_SELECTORS)
522
+ is_token = bool(cls.TOKEN_SELECTOR_REGEX.search(full_sel))
462
523
 
463
524
  matched_symbol = False
464
525
  if keep_symbols:
@@ -497,7 +558,7 @@ class Skeletonizer:
497
558
 
498
559
  if "{" in clean_line:
499
560
  is_container = any(clean_line.startswith(c) for c in CONTAINER_RULES)
500
- is_token = any(ts in clean_line for ts in TOKEN_SELECTORS)
561
+ is_token = bool(cls.TOKEN_SELECTOR_REGEX.search(clean_line))
501
562
 
502
563
  matched_symbol = False
503
564
  if keep_symbols:
@@ -573,7 +634,8 @@ class Skeletonizer:
573
634
  try:
574
635
  with open(meta_path, "r", encoding="utf-8") as mf:
575
636
  meta = json.load(mf)
576
- if meta.get("mtime") == current_mtime:
637
+ # mtime alone can miss a same-tick rewrite; size guards against it
638
+ if meta.get("mtime") == current_mtime and meta.get("size") == file_size:
577
639
  # Cache hit! Return immediately in 0.05ms
578
640
  return skeleton_path, meta.get("orig_tokens", 0), meta.get("skel_tokens", 0)
579
641
  except Exception:
@@ -638,6 +700,7 @@ class Skeletonizer:
638
700
  with open(meta_path, "w", encoding="utf-8") as mf:
639
701
  json.dump({
640
702
  "mtime": current_mtime,
703
+ "size": file_size,
641
704
  "orig_tokens": orig_tokens,
642
705
  "skel_tokens": skel_tokens,
643
706
  "lines_count": lines_count
package/src/slicer.py CHANGED
@@ -53,15 +53,25 @@ class ToolSlicer:
53
53
  words = re.findall(r'\b[a-zA-Z_][a-zA-Z0-9_]{2,}\b', context_hint)
54
54
  ignore_set = {"function", "method", "class", "async", "const", "return", "optimize", "refactor", "debug", "test", "check", "please", "code", "file"}
55
55
  candidates = [w for w in words if w.lower() not in ignore_set]
56
- for candidate in candidates:
57
- sym_regex = re.compile(r'\b(def|function|class|const|let|var|type|interface)\s+' + re.escape(candidate) + r'\b')
56
+ if candidates:
57
+ # Single pass over the file for ALL candidates (previously O(words x lines)
58
+ # regex scans per read_file hook call on large files).
59
+ unique_candidates = list(dict.fromkeys(candidates))
60
+ combined = re.compile(
61
+ r'\b(?:def|function|class|const|let|var|type|interface)\s+('
62
+ + "|".join(re.escape(c) for c in unique_candidates) + r')\b'
63
+ )
64
+ first_hit: Dict[str, int] = {}
58
65
  for idx, line in enumerate(lines, 1):
59
- if sym_regex.search(line):
60
- found_line = idx
66
+ m = combined.search(line)
67
+ if m and m.group(1) not in first_hit:
68
+ first_hit[m.group(1)] = idx
69
+ # Preserve original semantics: highest-priority candidate that has a match
70
+ for candidate in candidates:
71
+ if candidate in first_hit:
61
72
  target_symbol = candidate
73
+ found_line = first_hit[candidate]
62
74
  break
63
- if found_line:
64
- break
65
75
 
66
76
  new_start = 1
67
77
  new_end = total_lines
@@ -43,6 +43,11 @@ def _get_cloud_url() -> str:
43
43
  return base.rstrip("/")
44
44
 
45
45
 
46
+ def _telemetry_disabled() -> bool:
47
+ """TOKENSAFE_TELEMETRY_DISABLED=1 fully turns off cloud telemetry (privacy / offline / CI)."""
48
+ return os.environ.get("TOKENSAFE_TELEMETRY_DISABLED", "").strip().lower() in ("1", "true", "yes")
49
+
50
+
46
51
  class TelemetrySync:
47
52
  """Manages secure telemetry synchronization between local metrics and cloud dashboard."""
48
53
 
@@ -123,6 +128,13 @@ class TelemetrySync:
123
128
  Synchronizes all un-synced events from data/metrics.db to the TokenSafe cloud server.
124
129
  Returns a dict with sync results and totals.
125
130
  """
131
+ if _telemetry_disabled():
132
+ return {
133
+ "success": True,
134
+ "synced_events": 0,
135
+ "total_synced": 0,
136
+ "message": "Telemetry disabled via TOKENSAFE_TELEMETRY_DISABLED."
137
+ }
126
138
  with cls._sync_lock:
127
139
  base_url = (cloud_url or _get_cloud_url()).rstrip("/")
128
140
  target_url = f"{base_url}/api/telemetry/sync"
@@ -237,7 +249,7 @@ class TelemetrySync:
237
249
  rollup_synced = bool(state.get("lifetime_rollup_synced", False))
238
250
  headers = {
239
251
  "Content-Type": "application/json",
240
- "User-Agent": "TokenSafe-Sync/1.4.13"
252
+ "User-Agent": "TokenSafe-Sync/1.4.14"
241
253
  }
242
254
  if active_key:
243
255
  headers["Authorization"] = f"Bearer {active_key}"
@@ -309,6 +321,8 @@ class TelemetrySync:
309
321
  using persistent state from sync_state.json.
310
322
  Detached from parent process group so it survives the termination of short-lived CLI lifecycle hooks.
311
323
  """
324
+ if _telemetry_disabled():
325
+ return
312
326
  now = time.time()
313
327
  state = cls.get_state()
314
328
  last_synced = max(state.get("last_synced_at", 0), state.get("last_attempt_at", 0))
@@ -319,16 +333,32 @@ class TelemetrySync:
319
333
  if status.get("pending_events", 0) == 0:
320
334
  return
321
335
 
322
- # Prevent overlapping sync runs via PID lock file
323
- if os.path.exists(SYNC_LOCK_PATH):
336
+ # Prevent overlapping sync runs via PID lock file.
337
+ # Atomic O_EXCL claim closes the check-then-write race where two hook
338
+ # processes could both pass the liveness check and spawn duplicate syncs.
339
+ lock_claimed = False
340
+ for _ in range(2):
324
341
  try:
325
- with open(SYNC_LOCK_PATH, "r", encoding="utf-8") as f:
326
- pid = int(f.read().strip())
327
- # Check if PID is still alive
328
- os.kill(pid, 0)
329
- return
330
- except (ValueError, OSError, ProcessLookupError):
331
- pass
342
+ fd = os.open(SYNC_LOCK_PATH, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
343
+ os.write(fd, str(os.getpid()).encode("utf-8"))
344
+ os.close(fd)
345
+ lock_claimed = True
346
+ break
347
+ except FileExistsError:
348
+ try:
349
+ with open(SYNC_LOCK_PATH, "r", encoding="utf-8") as f:
350
+ pid = int(f.read().strip())
351
+ # Check if PID is still alive
352
+ os.kill(pid, 0)
353
+ return # an active sync owns the lock
354
+ except (ValueError, OSError, ProcessLookupError):
355
+ # Stale lock from a dead process: reclaim it once
356
+ try:
357
+ os.unlink(SYNC_LOCK_PATH)
358
+ except OSError:
359
+ return
360
+ if not lock_claimed:
361
+ return
332
362
 
333
363
  try:
334
364
  flags = 0
@@ -351,9 +381,29 @@ class TelemetrySync:
351
381
  if __name__ == "__main__":
352
382
  is_bg = "--background" in sys.argv
353
383
  os.makedirs(DATA_DIR, exist_ok=True)
384
+ # Claim the lock atomically; if another live process owns it, exit without syncing.
385
+ try:
386
+ fd = os.open(SYNC_LOCK_PATH, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
387
+ os.write(fd, str(os.getpid()).encode("utf-8"))
388
+ os.close(fd)
389
+ except FileExistsError:
390
+ try:
391
+ with open(SYNC_LOCK_PATH, "r", encoding="utf-8") as f:
392
+ pid = int(f.read().strip())
393
+ os.kill(pid, 0)
394
+ sys.exit(0) # live owner is syncing already
395
+ except (ValueError, OSError, ProcessLookupError):
396
+ try:
397
+ os.unlink(SYNC_LOCK_PATH)
398
+ except OSError:
399
+ sys.exit(0)
400
+ try:
401
+ fd = os.open(SYNC_LOCK_PATH, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
402
+ os.write(fd, str(os.getpid()).encode("utf-8"))
403
+ os.close(fd)
404
+ except FileExistsError:
405
+ sys.exit(0)
354
406
  try:
355
- with open(SYNC_LOCK_PATH, "w", encoding="utf-8") as f:
356
- f.write(str(os.getpid()))
357
407
  res = TelemetrySync.sync(timeout=10.0, verbose=not is_bg)
358
408
  if not is_bg:
359
409
  print(json.dumps(res, indent=2))
package/src/tokenizer.py CHANGED
@@ -17,9 +17,12 @@ except Exception:
17
17
  class TokenCounter:
18
18
  """Estimates or calculates token counts across languages and code structures."""
19
19
 
20
- # Robust regex splitting on words, contractions, numbers, punctuation, whitespace
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.
21
24
  _WORD_REGEX = re.compile(
22
- r"""'s|'t|'re|'ve|'m|'ll|'d|[a-zA-Zа-яА-ЯёЁ_]+|\d{1,3}|[^\w\s]|\s+"""
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+"""
23
26
  )
24
27
 
25
28
  @classmethod
@@ -69,7 +72,13 @@ class TokenCounter:
69
72
 
70
73
  # Alphabetic words: Check script
71
74
  is_cyrillic = any('\u0400' <= char <= '\u04FF' for char in chunk)
72
- is_cjk = any('\u4E00' <= char <= '\u9FFF' for char in chunk)
75
+ is_cjk = any(
76
+ '\u4E00' <= char <= '\u9FFF' # CJK Unified Ideographs
77
+ or '\u3400' <= char <= '\u4DBF' # CJK Extension A
78
+ or '\u3040' <= char <= '\u30FF' # Hiragana / Katakana
79
+ or '\uAC00' <= char <= '\uD7AF' # Hangul syllables
80
+ for char in chunk
81
+ )
73
82
 
74
83
  if is_cjk:
75
84
  # CJK: typically ~1.8 tokens per character