tokensafe 2.5.2 → 2.6.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.
package/README.md CHANGED
@@ -343,7 +343,7 @@ More documentation: [docs/AGENT_SETUP.md](docs/AGENT_SETUP.md) · [docs/ARCHITEC
343
343
 
344
344
  ## Development and License
345
345
 
346
- The client runs on standard Python 3.10+ with zero mandatory runtime dependencies. An optional `cryptography` package accelerates license verification ([details](docs/AGENT_SETUP.md#6-optional-dependency-cryptography)).
346
+ The client runs on Python 3.10+ with `cryptography>=42.0` as its sole runtime dependency for Ed25519 license checks; all AST slicing, SQLite metrics, MCP tooling, and guardrails run on the standard library ([details](docs/AGENT_SETUP.md#6-runtime-dependency-cryptography)).
347
347
 
348
348
  ```bash
349
349
  # Run the unit test suite (compact failure report; full: --traceback / -v)
package/bin/tokensafe CHANGED
@@ -11,6 +11,16 @@ PROJECT_ROOT = os.path.dirname(SCRIPT_DIR)
11
11
  if PROJECT_ROOT not in sys.path:
12
12
  sys.path.insert(0, PROJECT_ROOT)
13
13
 
14
+ # If launched via system python3 without cryptography (PEP 668), re-exec in ~/.tokensafe/venv if present.
15
+ _venv_py = os.path.expanduser(
16
+ "~/.tokensafe/venv/Scripts/python.exe" if sys.platform == "win32" else "~/.tokensafe/venv/bin/python3"
17
+ )
18
+ if os.path.exists(_venv_py) and os.path.realpath(sys.executable) != os.path.realpath(_venv_py):
19
+ try:
20
+ import cryptography # noqa: F401
21
+ except ImportError:
22
+ os.execv(_venv_py, [_venv_py, __file__, *sys.argv[1:]])
23
+
14
24
  from src.cli import main
15
25
 
16
26
  if __name__ == "__main__":
package/bin/tokensafe.js CHANGED
@@ -8,25 +8,78 @@
8
8
  const { spawn, spawnSync } = require('child_process');
9
9
  const path = require('path');
10
10
  const fs = require('fs');
11
+ const os = require('os');
11
12
 
12
13
  const ROOT_DIR = path.resolve(__dirname, '..');
13
14
  const args = process.argv.slice(2);
15
+ const VENV_DIR = path.join(os.homedir(), '.tokensafe', 'venv');
14
16
 
15
- // Locate system Python 3 interpreter
17
+ function checkPython(cmd, requireCrypto) {
18
+ const probe = requireCrypto
19
+ ? 'import sys, cryptography; assert sys.version_info >= (3, 10)'
20
+ : 'import sys; assert sys.version_info >= (3, 10)';
21
+ try {
22
+ const res = spawnSync(cmd, ['-c', probe], { encoding: 'utf-8', stdio: 'pipe' });
23
+ return res.status === 0;
24
+ } catch (_) {
25
+ return false;
26
+ }
27
+ }
28
+
29
+ function bootstrapCryptography(basePython) {
30
+ console.error('⚡ Installing required dependency: cryptography>=42.0 ...');
31
+ // 1. Try user-site pip first (respects normal user environments)
32
+ const userPip = spawnSync(
33
+ basePython,
34
+ ['-m', 'pip', 'install', '--user', '--quiet', '--disable-pip-version-check', 'cryptography>=42.0'],
35
+ { encoding: 'utf-8', stdio: 'pipe' }
36
+ );
37
+ if (userPip.status === 0 && checkPython(basePython, true)) {
38
+ return basePython;
39
+ }
40
+
41
+ // 2. Fallback to isolated ~/.tokensafe/venv (handles PEP 668 externally-managed Python on macOS/Ubuntu)
42
+ fs.mkdirSync(path.dirname(VENV_DIR), { recursive: true });
43
+ const venvPy = process.platform === 'win32'
44
+ ? path.join(VENV_DIR, 'Scripts', 'python.exe')
45
+ : path.join(VENV_DIR, 'bin', 'python3');
46
+
47
+ if (!fs.existsSync(venvPy)) {
48
+ const mk = spawnSync(basePython, ['-m', 'venv', VENV_DIR], { encoding: 'utf-8', stdio: 'pipe' });
49
+ if (mk.status !== 0) return null;
50
+ }
51
+ const venvPip = spawnSync(
52
+ venvPy,
53
+ ['-m', 'pip', 'install', '--quiet', '--disable-pip-version-check', 'cryptography>=42.0'],
54
+ { encoding: 'utf-8', stdio: 'pipe' }
55
+ );
56
+ if (venvPip.status === 0 && checkPython(venvPy, true)) {
57
+ return venvPy;
58
+ }
59
+ return null;
60
+ }
61
+
62
+ // Locate Python 3.10+ interpreter with required `cryptography` package
16
63
  function findPython() {
17
- const candidates = ['python3', 'python'];
64
+ const venvPy = process.platform === 'win32'
65
+ ? path.join(VENV_DIR, 'Scripts', 'python.exe')
66
+ : path.join(VENV_DIR, 'bin', 'python3');
67
+ const candidates = [venvPy, 'python3', 'python'];
68
+
69
+ for (const cmd of candidates) {
70
+ if (cmd === venvPy && !fs.existsSync(venvPy)) continue;
71
+ if (checkPython(cmd, true)) return cmd;
72
+ }
73
+
18
74
  for (const cmd of candidates) {
19
- try {
20
- const res = spawnSync(cmd, ['-c', 'import sys; assert sys.version_info >= (3, 10)'], {
21
- encoding: 'utf-8',
22
- stdio: 'pipe'
23
- });
24
- if (res.status === 0) return cmd;
25
- if (res.error && res.error.code !== 'ENOENT') {
26
- console.error(`TokenSafe: python probe for '${cmd}' failed: ${res.error.message}`);
27
- }
28
- } catch (err) {
29
- console.error(`TokenSafe: python probe for '${cmd}' threw: ${err.message}`);
75
+ if (cmd === venvPy && !fs.existsSync(venvPy)) continue;
76
+ if (checkPython(cmd, false)) {
77
+ const bootstrapped = bootstrapCryptography(cmd);
78
+ if (bootstrapped) return bootstrapped;
79
+ console.error("\n❌ TokenSafe requires the Python 'cryptography>=42.0' package.");
80
+ console.error("Install it manually cleanly via:");
81
+ console.error(" pip install 'cryptography>=42.0'\n");
82
+ process.exit(1);
30
83
  }
31
84
  }
32
85
  return null;
@@ -184,6 +184,12 @@ def main():
184
184
  response = handle(event, payload if isinstance(payload, dict) else {})
185
185
  except Exception:
186
186
  response = {}
187
+ if event in ("UserPromptSubmit", "PreToolUse", "PostToolUse", "Stop"):
188
+ try:
189
+ from src.telemetry_sync import TelemetrySync
190
+ TelemetrySync.sync_background(throttle_seconds=0.0 if event == "Stop" else 20.0)
191
+ except Exception:
192
+ pass
187
193
  print(json.dumps(response))
188
194
 
189
195
 
@@ -78,6 +78,12 @@ def main():
78
78
  response = _allow(event)
79
79
  if not isinstance(response, dict) or not response:
80
80
  response = _allow(event)
81
+ if event in ("beforeShellExecution", "beforeReadFile", "beforeSubmitPrompt", "stop"):
82
+ try:
83
+ from src.telemetry_sync import TelemetrySync
84
+ TelemetrySync.sync_background(throttle_seconds=0.0 if event == "stop" else 20.0)
85
+ except Exception:
86
+ pass
81
87
  print(json.dumps(response))
82
88
 
83
89
 
@@ -25,7 +25,7 @@ def main():
25
25
  # Non-blocking telemetry sync trigger (detached background process)
26
26
  try:
27
27
  from src.telemetry_sync import TelemetrySync
28
- TelemetrySync.sync_background(throttle_seconds=60.0)
28
+ TelemetrySync.sync_background(throttle_seconds=20.0)
29
29
  except Exception:
30
30
  pass
31
31
 
@@ -74,10 +74,10 @@ def main():
74
74
  tracker = MetricsTracker()
75
75
  inject_steps = []
76
76
 
77
- # 0. Asynchronous telemetry sync (detached & throttled to 60s)
77
+ # 0. Asynchronous telemetry sync (detached & throttled to 20s)
78
78
  try:
79
79
  from src.telemetry_sync import TelemetrySync
80
- TelemetrySync.sync_background(throttle_seconds=60.0)
80
+ TelemetrySync.sync_background(throttle_seconds=20.0)
81
81
  except Exception:
82
82
  pass
83
83
 
@@ -28,6 +28,15 @@ from src.license_manager import LicenseManager
28
28
  from src.secret_redactor import SecretRedactor
29
29
  from src.guard import TokenSafeGuard
30
30
 
31
+
32
+ def _trigger_bg_sync():
33
+ try:
34
+ from src.telemetry_sync import TelemetrySync
35
+ TelemetrySync.sync_background(throttle_seconds=20.0)
36
+ except Exception:
37
+ pass
38
+
39
+
31
40
  def main():
32
41
  try:
33
42
  raw_input = sys.stdin.read()
@@ -67,6 +76,7 @@ def main():
67
76
  "decision": "force_ask",
68
77
  "reason": loop_msg
69
78
  }))
79
+ _trigger_bg_sync()
70
80
  return
71
81
 
72
82
  response = {"decision": "allow"}
@@ -92,6 +102,7 @@ def main():
92
102
  "decision": "deny",
93
103
  "reason": f"🛡️ TokenSafe Guard: {guard_res.reason}"
94
104
  }))
105
+ _trigger_bg_sync()
95
106
  return
96
107
 
97
108
  # 3. Output Guard: Block write_file on large existing files to enforce edit_file
@@ -130,6 +141,7 @@ def main():
130
141
  f"Please use 'edit_file' with surgical Target and Replacement blocks instead."
131
142
  )
132
143
  }))
144
+ _trigger_bg_sync()
133
145
  return
134
146
 
135
147
  # 3. read_file Optimization (AST Windowing & Skeletonization).
@@ -256,6 +268,7 @@ def main():
256
268
  "decision": "deny",
257
269
  "reason": f"🛡️ TokenSafe Guard: {guard_res.reason}"
258
270
  }))
271
+ _trigger_bg_sync()
259
272
  return
260
273
  elif guard_res.warning_only:
261
274
  response["reason"] = f"⚠️ TokenSafe Guard Warning: {guard_res.reason}"
@@ -52,13 +52,13 @@ def main():
52
52
  from src.metrics import MetricsTracker
53
53
  tracker = MetricsTracker()
54
54
 
55
- # 1. Idle epilogue: final cloud sync + retention prune.
55
+ # 1. Turn-end / idle epilogue: cloud sync + idle retention prune.
56
+ try:
57
+ from src.telemetry_sync import TelemetrySync
58
+ TelemetrySync.sync_background(throttle_seconds=0.0 if fully_idle else 15.0)
59
+ except Exception:
60
+ pass
56
61
  if fully_idle:
57
- try:
58
- from src.telemetry_sync import TelemetrySync
59
- TelemetrySync.sync_background(throttle_seconds=0.0)
60
- except Exception:
61
- pass
62
62
  try:
63
63
  tracker.prune()
64
64
  except Exception:
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "2.5.2",
4
+ "version": "2.6.1",
5
5
  "description": "Reduce your AI bills by up to 99% locally. Your agents read only needed code, keep prompt caches intact across turns, and keep secrets out of git.",
6
6
  "main": "bin/tokensafe.js",
7
7
  "bin": {
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "displayName": "TokenSafe",
4
- "version": "2.5.2",
4
+ "version": "2.6.1",
5
5
  "description": "Reduce your AI bills by up to 99% locally. Your agents read only needed code, keep prompt caches intact across turns, and keep secrets out of git.",
6
6
  "logo": "assets/logo.svg",
7
7
  "author": {
package/server.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "dev.tokensafe/tokensafe",
4
4
  "title": "TokenSafe",
5
5
  "description": "Reduce your AI bills by up to 99% locally: focused code, warm prompt caches & zero secret leaks.",
6
- "version": "2.5.2",
6
+ "version": "2.6.1",
7
7
  "websiteUrl": "https://tokensafe.dev",
8
8
  "repository": {
9
9
  "url": "https://github.com/tokensafe-dev/tokensafe",
@@ -30,7 +30,7 @@
30
30
  "registryType": "npm",
31
31
  "registryBaseUrl": "https://registry.npmjs.org",
32
32
  "identifier": "tokensafe",
33
- "version": "2.5.2",
33
+ "version": "2.6.1",
34
34
  "runtimeHint": "npx",
35
35
  "transport": {
36
36
  "type": "stdio"
@@ -46,7 +46,7 @@
46
46
  "registryType": "pypi",
47
47
  "registryBaseUrl": "https://pypi.org",
48
48
  "identifier": "tokensafe",
49
- "version": "2.5.2",
49
+ "version": "2.6.1",
50
50
  "runtimeHint": "uvx",
51
51
  "transport": {
52
52
  "type": "stdio"
@@ -1,6 +1,6 @@
1
1
  """
2
- Cryptographically secure, zero-dependency License Engine for TokenSafe.
3
- Supports offline-verifiable HMAC-SHA256 signed licenses and 7-day trials.
2
+ Cryptographically secure License Engine for TokenSafe.
3
+ Supports offline-verifiable Ed25519 (TS2) licenses, 7-day trials, and quota checks.
4
4
  Compatible with Stripe webhook lifecycle and B2B on-premise proxy deployments.
5
5
  """
6
6
 
@@ -39,103 +39,32 @@ ROTATED_HMAC_SALT = os.environ.get("TOKENSAFE_HMAC_SALT", "")
39
39
  DEFAULT_SIGNING_SALT = ROTATED_HMAC_SALT
40
40
 
41
41
  # ---------------------------------------------------------------------------
42
- # Zero-dependency RFC 8032 Ed25519 Implementation with Cryptography Fast-Path
42
+ # Required Cryptography-Backed RFC 8032 Ed25519 Verification & Signing
43
43
  # ---------------------------------------------------------------------------
44
- _ED25519_Q = 2**255 - 19
45
- _ED25519_L = 2**252 + 27742317777372353535851937790883648493
46
-
47
- def _ed_inv(x: int) -> int:
48
- return pow(x, _ED25519_Q - 2, _ED25519_Q)
49
-
50
- _ED_D = -121665 * _ed_inv(121666)
51
- _ED_I = pow(2, (_ED25519_Q - 1) // 4, _ED25519_Q)
52
-
53
- def _ed_xrecover(y: int) -> int:
54
- xx = (y * y - 1) * _ed_inv(_ED_D * y * y + 1)
55
- x = pow(xx, (_ED25519_Q + 3) // 8, _ED25519_Q)
56
- if (x * x - xx) % _ED25519_Q != 0:
57
- x = (x * _ED_I) % _ED25519_Q
58
- if x % 2 != 0:
59
- x = _ED25519_Q - x
60
- return x
61
-
62
- _ED_BY = 4 * _ed_inv(5)
63
- _ED_BX = _ed_xrecover(_ED_BY)
64
- _ED_B = [_ED_BX % _ED25519_Q, _ED_BY % _ED25519_Q]
65
-
66
- def _ed_add(p1: list, p2: list) -> list:
67
- x1, y1 = p1[0], p1[1]
68
- x2, y2 = p2[0], p2[1]
69
- x3 = (x1 * y2 + x2 * y1) * _ed_inv(1 + _ED_D * x1 * x2 * y1 * y2)
70
- y3 = (y1 * y2 + x1 * x2) * _ed_inv(1 - _ED_D * x1 * x2 * y1 * y2)
71
- return [x3 % _ED25519_Q, y3 % _ED25519_Q]
72
-
73
- def _ed_scalarmult(pt: list, e: int) -> list:
74
- if e == 0:
75
- return [0, 1]
76
- q = _ed_scalarmult(pt, e // 2)
77
- q = _ed_add(q, q)
78
- if e & 1:
79
- q = _ed_add(q, pt)
80
- return q
81
-
82
- def _ed_encodepoint(pt: list) -> bytes:
83
- x, y = pt[0], pt[1]
84
- bits = [(y >> i) & 1 for i in range(255)] + [x & 1]
85
- return bytes([sum([bits[i * 8 + j] << j for j in range(8)]) for i in range(32)])
86
-
87
- def _ed_bit(h: bytes, i: int) -> int:
88
- return (h[i // 8] >> (i % 8)) & 1
89
-
90
- def _ed_decodepoint(s: bytes) -> Optional[list]:
91
- y = sum(2**i * _ed_bit(s, i) for i in range(0, 255))
92
- x = _ed_xrecover(y)
93
- if x & 1 != _ed_bit(s, 255):
94
- x = _ED25519_Q - x
95
- pt = [x, y]
96
- if (-x * x + y * y - 1 - _ED_D * x * x * y * y) % _ED25519_Q != 0:
97
- return None
98
- return pt
99
-
100
- def _ed25519_sign_bytes(msg: bytes, priv_bytes: bytes, pub_bytes: bytes = b"") -> bytes:
44
+ def _load_ed25519_module():
101
45
  try:
102
46
  from cryptography.hazmat.primitives.asymmetric import ed25519
103
- priv_obj = ed25519.Ed25519PrivateKey.from_private_bytes(priv_bytes)
104
- return priv_obj.sign(msg)
105
- except Exception:
106
- h = hashlib.sha512(priv_bytes).digest()
107
- a = 2**254 + sum(2**i * _ed_bit(h, i) for i in range(3, 254))
108
- # Always derive the RFC 8032 public point from priv_bytes so env/global overrides cannot desync H(R||A||M).
109
- derived_pub = _ed_encodepoint(_ed_scalarmult(_ED_B, a))
110
- r = int.from_bytes(hashlib.sha512(h[32:] + msg).digest(), "little")
111
- r_pt = _ed_scalarmult(_ED_B, r)
112
- r_bytes = _ed_encodepoint(r_pt)
113
- k = int.from_bytes(hashlib.sha512(r_bytes + derived_pub + msg).digest(), "little")
114
- s = (r + k * a) % _ED25519_L
115
- return r_bytes + int.to_bytes(s, 32, "little")
47
+ return ed25519
48
+ except ImportError as exc:
49
+ raise RuntimeError(
50
+ "TokenSafe requires 'cryptography>=42.0'. Install it via: pip install 'cryptography>=42.0'"
51
+ ) from exc
52
+
53
+
54
+ def _ed25519_sign_bytes(msg: bytes, priv_bytes: bytes, pub_bytes: bytes = b"") -> bytes:
55
+ ed25519 = _load_ed25519_module()
56
+ priv_obj = ed25519.Ed25519PrivateKey.from_private_bytes(priv_bytes)
57
+ return priv_obj.sign(msg)
58
+
116
59
 
117
60
  def _ed25519_verify_bytes(sig: bytes, msg: bytes, pub_bytes: bytes) -> bool:
118
61
  if len(sig) != 64 or len(pub_bytes) != 32:
119
62
  return False
63
+ ed25519 = _load_ed25519_module()
120
64
  try:
121
- from cryptography.hazmat.primitives.asymmetric import ed25519
122
65
  pub_obj = ed25519.Ed25519PublicKey.from_public_bytes(pub_bytes)
123
66
  pub_obj.verify(sig, msg)
124
67
  return True
125
- except Exception:
126
- pass
127
- try:
128
- r_pt = _ed_decodepoint(sig[:32])
129
- a_pt = _ed_decodepoint(pub_bytes)
130
- if r_pt is None or a_pt is None:
131
- return False
132
- s = int.from_bytes(sig[32:], "little")
133
- if s >= _ED25519_L:
134
- return False
135
- h = int.from_bytes(hashlib.sha512(sig[:32] + pub_bytes + msg).digest(), "little")
136
- v1 = _ed_scalarmult(_ED_B, s)
137
- v2 = _ed_add(r_pt, _ed_scalarmult(a_pt, h))
138
- return v1 == v2
139
68
  except Exception:
140
69
  return False
141
70
 
@@ -271,18 +200,22 @@ class LicenseManager:
271
200
  except Exception:
272
201
  return False, {}, "Invalid signature encoding"
273
202
 
274
- if not _ed25519_verify_bytes(sig_bytes, payload_bytes, pub_bytes):
275
- verified = False
276
- if not public_key:
203
+ try:
204
+ verified = _ed25519_verify_bytes(sig_bytes, payload_bytes, pub_bytes)
205
+ if not verified and not public_key:
277
206
  for leg_hex in LEGACY_ED25519_PUBLIC_KEYS:
278
207
  try:
279
208
  if _ed25519_verify_bytes(sig_bytes, payload_bytes, bytes.fromhex(leg_hex)):
280
209
  verified = True
281
210
  break
211
+ except RuntimeError:
212
+ raise
282
213
  except Exception:
283
214
  pass
284
- if not verified:
285
- return False, {}, "Invalid digital signature: license key has been tampered with or is counterfeit"
215
+ except RuntimeError as crypto_err:
216
+ return False, {}, str(crypto_err)
217
+ if not verified:
218
+ return False, {}, "Invalid digital signature: license key has been tampered with or is counterfeit"
286
219
 
287
220
  # 2. Legacy TS1 Verification (disabled offline to eliminate public-salt forgery)
288
221
  else:
package/src/mcp_server.py CHANGED
@@ -40,7 +40,7 @@ from src.license_manager import LicenseManager
40
40
 
41
41
  SERVER_INFO = {
42
42
  "name": "tokensafe-mcp",
43
- "version": "2.5.2"
43
+ "version": "2.6.1"
44
44
  }
45
45
 
46
46
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -1250,7 +1250,7 @@ def run_mcp_server():
1250
1250
  finally:
1251
1251
  try:
1252
1252
  from src.telemetry_sync import TelemetrySync
1253
- TelemetrySync.sync_background(throttle_seconds=60.0)
1253
+ TelemetrySync.sync_background(throttle_seconds=20.0)
1254
1254
  except Exception:
1255
1255
  pass
1256
1256
  else:
package/src/proxy.py CHANGED
@@ -219,6 +219,8 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
219
219
  },
220
220
  measurement="measured", # bytes literally swapped
221
221
  )
222
+ from src.telemetry_sync import TelemetrySync
223
+ TelemetrySync.sync_background(throttle_seconds=20.0)
222
224
  except Exception:
223
225
  pass
224
226
  target_symbol = compaction.get("symbol")
@@ -15,6 +15,7 @@ import os
15
15
  import sys
16
16
  import json
17
17
  import time
18
+ import secrets
18
19
  import sqlite3
19
20
  import threading
20
21
  import subprocess
@@ -165,53 +166,6 @@ class TelemetrySync:
165
166
  state = cls.get_state()
166
167
  last_id = 0 if force else state.get("last_synced_event_id", 0)
167
168
 
168
- try:
169
- conn = sqlite3.connect(METRICS_DB_PATH)
170
- conn.row_factory = sqlite3.Row
171
- cur = conn.cursor()
172
-
173
- synthetic_events: List[Dict[str, Any]] = []
174
- if not state.get("lifetime_rollup_synced", False):
175
- try:
176
- life_row = cur.execute("SELECT * FROM lifetime_aggregates WHERE id = 1").fetchone()
177
- if life_row and life_row["total_saved_tokens"] > 0:
178
- synthetic_events.append({
179
- "event_type": "ROLLUP_LIFETIME",
180
- "original_tokens": int(life_row["total_original_tokens"]),
181
- "saved_tokens": int(life_row["total_saved_tokens"]),
182
- "usd_saved": float(life_row["total_usd_saved"]),
183
- "model": "aggregate",
184
- "timestamp": int(time.time()),
185
- # Rolled-up historical mass of mixed provenance: conservatively estimated.
186
- "measurement": "estimated"
187
- })
188
- except Exception:
189
- pass
190
-
191
- # The measurement column may be absent on legacy databases that have
192
- # not yet been migrated by MetricsTracker._init_db; fall back to the
193
- # event-type map so sync never blocks on schema drift.
194
- try:
195
- rows = cur.execute(
196
- "SELECT id, timestamp, event_type, original_tokens, saved_tokens, est_usd_saved, details, measurement "
197
- "FROM events WHERE id > ? ORDER BY id ASC LIMIT 2000",
198
- (last_id,)
199
- ).fetchall()
200
- except sqlite3.OperationalError:
201
- rows = cur.execute(
202
- "SELECT id, timestamp, event_type, original_tokens, saved_tokens, est_usd_saved, details, "
203
- "NULL as measurement "
204
- "FROM events WHERE id > ? ORDER BY id ASC LIMIT 2000",
205
- (last_id,)
206
- ).fetchall()
207
- conn.close()
208
- except Exception as e:
209
- return {
210
- "success": False,
211
- "synced_events": 0,
212
- "error": f"Failed to read local metrics database: {str(e)}"
213
- }
214
-
215
169
  try:
216
170
  from src.metrics import MetricsTracker
217
171
  local_monthly_measured = MetricsTracker(db_path=METRICS_DB_PATH).get_monthly_saved_tokens(measured_only=True)
@@ -219,64 +173,13 @@ class TelemetrySync:
219
173
  local_monthly_measured = 0
220
174
  machine_fp = "" if os.environ.get("TOKENSAFE_TELEMETRY_DISABLED") in ("1", "true", "yes") else LicenseManager.get_machine_fingerprint()
221
175
 
222
- if not rows and not synthetic_events:
223
- last_q_sync = float(state.get("last_quota_sync_at", 0) or 0)
224
- if not (machine_fp and active_key == "community" and (time.time() - last_q_sync > 3600)):
225
- return {
226
- "success": True,
227
- "synced_events": 0,
228
- "total_synced": state.get("total_synced_events", 0),
229
- "message": "All metrics are already up to date."
230
- }
231
- formatted_items = [(None, None)] # quota-only probe for community tier
232
- else:
233
- formatted_items = [
234
- (None, ev) for ev in synthetic_events
235
- ]
236
- current_last_id = last_id
237
-
238
- for r in rows:
239
- ev_id = int(r["id"])
240
- raw_ts = r["timestamp"]
241
- ts_int = int(time.time())
242
- if isinstance(raw_ts, (int, float)):
243
- ts_int = int(raw_ts)
244
- elif isinstance(raw_ts, str) and raw_ts.strip():
245
- try:
246
- ts_int = int(float(raw_ts.strip()))
247
- except ValueError:
248
- try:
249
- clean_iso = raw_ts.strip().replace("Z", "+00:00")
250
- dt = datetime.fromisoformat(clean_iso)
251
- ts_int = int(dt.timestamp())
252
- except Exception:
253
- ts_int = int(time.time())
254
-
255
- model_name = os.environ.get("AGY_MODEL") or os.environ.get("MODEL") or "gemini-3.8-flash"
256
- if r["details"]:
257
- try:
258
- det = json.loads(r["details"]) if isinstance(r["details"], str) else r["details"]
259
- if isinstance(det, dict) and det.get("model"):
260
- model_name = str(det["model"])
261
- except Exception:
262
- pass
263
-
264
- formatted_items.append((ev_id, {
265
- "event_type": str(r["event_type"] or "PROMPT"),
266
- "original_tokens": int(r["original_tokens"] or 0),
267
- "saved_tokens": int(r["saved_tokens"] or 0),
268
- "usd_saved": float(r["est_usd_saved"] or 0.0),
269
- "model": model_name,
270
- "timestamp": ts_int,
271
- "measurement": resolve_measurement(str(r["event_type"] or "PROMPT"), r["measurement"])
272
- }))
273
-
274
176
  total_sent = 0
275
177
  cumulative_synced = state.get("total_synced_events", 0)
276
178
  rollup_synced = bool(state.get("lifetime_rollup_synced", False))
179
+ current_last_id = last_id
277
180
  headers = {
278
181
  "Content-Type": "application/json",
279
- "User-Agent": "TokenSafe-Sync/2.5.2"
182
+ "User-Agent": "TokenSafe-Sync/2.6.1"
280
183
  }
281
184
  if active_key:
282
185
  headers["Authorization"] = f"Bearer {active_key}"
@@ -296,54 +199,163 @@ class TelemetrySync:
296
199
  "error": err_msg
297
200
  }
298
201
 
299
- for i in range(0, len(formatted_items), batch_size):
300
- batch_items = formatted_items[i:i + batch_size]
301
- chunk = [item[1] for item in batch_items if item[1] is not None]
302
- body_dict = {
303
- "email": target_email,
304
- "license_key": active_key,
305
- "events": chunk,
306
- }
307
- if machine_fp and active_key == "community":
308
- body_dict["machine_id"] = machine_fp
309
- body_dict["monthly_measured_saved"] = local_monthly_measured
310
- body_bytes = json.dumps(body_dict).encode("utf-8")
311
-
312
- req = urllib.request.Request(target_url, data=body_bytes, headers=headers, method="POST")
202
+ page_limit = 2000
203
+ max_pages = 25
204
+ for page_idx in range(max_pages):
313
205
  try:
314
- with urllib.request.urlopen(req, timeout=timeout) as resp:
315
- if resp.status == 200:
206
+ conn = sqlite3.connect(METRICS_DB_PATH)
207
+ conn.row_factory = sqlite3.Row
208
+ cur = conn.cursor()
209
+
210
+ synthetic_events: List[Dict[str, Any]] = []
211
+ if page_idx == 0 and not rollup_synced:
212
+ try:
213
+ life_row = cur.execute("SELECT * FROM lifetime_aggregates WHERE id = 1").fetchone()
214
+ if life_row and life_row["total_saved_tokens"] > 0:
215
+ synthetic_events.append({
216
+ "event_type": "ROLLUP_LIFETIME",
217
+ "original_tokens": int(life_row["total_original_tokens"]),
218
+ "saved_tokens": int(life_row["total_saved_tokens"]),
219
+ "usd_saved": float(life_row["total_usd_saved"]),
220
+ "model": "aggregate",
221
+ "timestamp": int(time.time()),
222
+ # Rolled-up historical mass of mixed provenance: conservatively estimated.
223
+ "measurement": "estimated"
224
+ })
225
+ except Exception:
226
+ pass
227
+
228
+ # The measurement column may be absent on legacy databases that have
229
+ # not yet been migrated by MetricsTracker._init_db; fall back to the
230
+ # event-type map so sync never blocks on schema drift.
231
+ try:
232
+ rows = cur.execute(
233
+ "SELECT id, timestamp, event_type, original_tokens, saved_tokens, est_usd_saved, details, measurement "
234
+ "FROM events WHERE id > ? ORDER BY id ASC LIMIT ?",
235
+ (current_last_id, page_limit)
236
+ ).fetchall()
237
+ except sqlite3.OperationalError:
238
+ rows = cur.execute(
239
+ "SELECT id, timestamp, event_type, original_tokens, saved_tokens, est_usd_saved, details, "
240
+ "NULL as measurement "
241
+ "FROM events WHERE id > ? ORDER BY id ASC LIMIT ?",
242
+ (current_last_id, page_limit)
243
+ ).fetchall()
244
+ conn.close()
245
+ except Exception as e:
246
+ if total_sent > 0:
247
+ return _record_failure(f"Failed to read local metrics database: {str(e)}")
248
+ return {
249
+ "success": False,
250
+ "synced_events": 0,
251
+ "error": f"Failed to read local metrics database: {str(e)}"
252
+ }
253
+
254
+ if not rows and not synthetic_events:
255
+ if page_idx == 0:
256
+ last_q_sync = float(state.get("last_quota_sync_at", 0) or 0)
257
+ if not (machine_fp and active_key == "community" and (time.time() - last_q_sync > 3600)):
258
+ return {
259
+ "success": True,
260
+ "synced_events": 0,
261
+ "total_synced": cumulative_synced,
262
+ "message": "All metrics are already up to date."
263
+ }
264
+ formatted_items = [(None, None)] # quota-only probe for community tier
265
+ else:
266
+ break
267
+ else:
268
+ formatted_items = [
269
+ (None, ev) for ev in synthetic_events
270
+ ]
271
+
272
+ for r in rows:
273
+ ev_id = int(r["id"])
274
+ raw_ts = r["timestamp"]
275
+ ts_int = int(time.time())
276
+ if isinstance(raw_ts, (int, float)):
277
+ ts_int = int(raw_ts)
278
+ elif isinstance(raw_ts, str) and raw_ts.strip():
279
+ try:
280
+ ts_int = int(float(raw_ts.strip()))
281
+ except ValueError:
316
282
  try:
317
- resp_body = json.loads(resp.read().decode("utf-8") or "{}")
318
- srv_measured = int(resp_body.get("server_monthly_measured_saved") or 0)
319
- if srv_measured > 0:
320
- from src.metrics import MetricsTracker
321
- MetricsTracker(db_path=METRICS_DB_PATH).record_server_quota_floor(srv_measured)
283
+ clean_iso = raw_ts.strip().replace("Z", "+00:00")
284
+ dt = datetime.fromisoformat(clean_iso)
285
+ ts_int = int(dt.timestamp())
322
286
  except Exception:
323
- pass
324
- total_sent += len(chunk)
325
- cumulative_synced += len(chunk)
326
- for ev_id, ev_payload in batch_items:
327
- if ev_id is not None and ev_id > current_last_id:
328
- current_last_id = ev_id
329
- if ev_payload and ev_payload.get("event_type") == "ROLLUP_LIFETIME":
287
+ ts_int = int(time.time())
288
+
289
+ model_name = os.environ.get("AGY_MODEL") or os.environ.get("MODEL") or "gemini-3.8-flash"
290
+ if r["details"]:
291
+ try:
292
+ det = json.loads(r["details"]) if isinstance(r["details"], str) else r["details"]
293
+ if isinstance(det, dict) and det.get("model"):
294
+ model_name = str(det["model"])
295
+ except Exception:
296
+ pass
297
+
298
+ formatted_items.append((ev_id, {
299
+ "event_type": str(r["event_type"] or "PROMPT"),
300
+ "original_tokens": int(r["original_tokens"] or 0),
301
+ "saved_tokens": int(r["saved_tokens"] or 0),
302
+ "usd_saved": float(r["est_usd_saved"] or 0.0),
303
+ "model": model_name,
304
+ "timestamp": ts_int,
305
+ "measurement": resolve_measurement(str(r["event_type"] or "PROMPT"), r["measurement"])
306
+ }))
307
+
308
+ for i in range(0, len(formatted_items), batch_size):
309
+ batch_items = formatted_items[i:i + batch_size]
310
+ chunk = [item[1] for item in batch_items if item[1] is not None]
311
+ body_dict = {
312
+ "email": target_email,
313
+ "license_key": active_key,
314
+ "events": chunk,
315
+ }
316
+ if machine_fp and active_key == "community":
317
+ body_dict["machine_id"] = machine_fp
318
+ body_dict["monthly_measured_saved"] = local_monthly_measured
319
+ body_bytes = json.dumps(body_dict).encode("utf-8")
320
+
321
+ req = urllib.request.Request(target_url, data=body_bytes, headers=headers, method="POST")
322
+ try:
323
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
324
+ if resp.status == 200:
325
+ try:
326
+ resp_body = json.loads(resp.read().decode("utf-8") or "{}")
327
+ srv_measured = int(resp_body.get("server_monthly_measured_saved") or 0)
328
+ if srv_measured > 0:
329
+ from src.metrics import MetricsTracker
330
+ MetricsTracker(db_path=METRICS_DB_PATH).record_server_quota_floor(srv_measured)
331
+ except Exception:
332
+ pass
333
+ total_sent += len(chunk)
334
+ cumulative_synced += len(chunk)
335
+ for ev_id, ev_payload in batch_items:
336
+ if ev_id is not None and ev_id > current_last_id:
337
+ current_last_id = ev_id
338
+ if ev_payload and ev_payload.get("event_type") == "ROLLUP_LIFETIME":
339
+ rollup_synced = True
340
+ if not synthetic_events:
330
341
  rollup_synced = True
331
- if not synthetic_events:
332
- rollup_synced = True
333
- cls.save_state({
334
- "last_synced_event_id": current_last_id,
335
- "last_synced_at": int(time.time()),
336
- "last_attempt_at": int(time.time()),
337
- "last_quota_sync_at": int(time.time()),
338
- "total_synced_events": cumulative_synced,
339
- "lifetime_rollup_synced": rollup_synced
340
- })
341
- else:
342
- return _record_failure(f"Server returned HTTP {resp.status}")
343
- except urllib.error.HTTPError as he:
344
- return _record_failure(f"Cloud API error: {he.code} {he.reason}")
345
- except Exception as ex:
346
- return _record_failure(f"Network error during sync: {str(ex)}")
342
+ cls.save_state({
343
+ "last_synced_event_id": current_last_id,
344
+ "last_synced_at": int(time.time()),
345
+ "last_attempt_at": int(time.time()),
346
+ "last_quota_sync_at": int(time.time()),
347
+ "total_synced_events": cumulative_synced,
348
+ "lifetime_rollup_synced": rollup_synced
349
+ })
350
+ else:
351
+ return _record_failure(f"Server returned HTTP {resp.status}")
352
+ except urllib.error.HTTPError as he:
353
+ return _record_failure(f"Cloud API error: {he.code} {he.reason}")
354
+ except Exception as ex:
355
+ return _record_failure(f"Network error during sync: {str(ex)}")
356
+
357
+ if len(rows) < page_limit:
358
+ break
347
359
 
348
360
  return {
349
361
  "success": True,
@@ -352,11 +364,48 @@ class TelemetrySync:
352
364
  "message": f"Successfully synchronized {total_sent:,} events to TokenSafe Cloud."
353
365
  }
354
366
 
367
+ @staticmethod
368
+ def _is_pid_alive(pid: int) -> bool:
369
+ if pid <= 0:
370
+ return False
371
+ try:
372
+ os.kill(pid, 0)
373
+ return True
374
+ except (OSError, ProcessLookupError):
375
+ return False
376
+
355
377
  @classmethod
356
- def sync_background(cls, throttle_seconds: float = 60.0, force: bool = False):
378
+ def _lock_is_active(cls, raw_content: str, allow_legacy_self: bool = False) -> bool:
379
+ """Interprets .sync.lock contents (`spawn:<token>:<ts>`, `worker:<pid>`, or legacy `<pid>`)."""
380
+ text = (raw_content or "").strip()
381
+ if not text:
382
+ return False
383
+ if text.startswith("spawn:"):
384
+ parts = text.split(":")
385
+ try:
386
+ claimed_at = float(parts[2])
387
+ except (IndexError, ValueError):
388
+ return False
389
+ return (time.time() - claimed_at) < 15.0
390
+ if text.startswith("worker:"):
391
+ try:
392
+ pid = int(text.split(":", 1)[1])
393
+ except ValueError:
394
+ return False
395
+ return cls._is_pid_alive(pid)
396
+ try:
397
+ pid = int(text)
398
+ except ValueError:
399
+ return False
400
+ if not allow_legacy_self and pid == os.getpid():
401
+ return False
402
+ return cls._is_pid_alive(pid)
403
+
404
+ @classmethod
405
+ def sync_background(cls, throttle_seconds: float = 20.0, force: bool = False):
357
406
  """
358
407
  Spawns a detached, non-blocking background OS process to sync metrics.
359
- Throttled to run at most once every `throttle_seconds` (default: 60s)
408
+ Throttled to run at most once every `throttle_seconds` (default: 20s)
360
409
  using persistent state from sync_state.json.
361
410
  Detached from parent process group so it survives the termination of short-lived CLI lifecycle hooks.
362
411
  """
@@ -372,30 +421,35 @@ class TelemetrySync:
372
421
  if status.get("pending_events", 0) == 0:
373
422
  return
374
423
 
375
- # Prevent overlapping sync runs via PID lock file.
376
- # Atomic O_EXCL claim closes the check-then-write race where two hook
377
- # processes could both pass the liveness check and spawn duplicate syncs.
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.
428
+ claim_token = secrets.token_hex(8)
429
+ spawn_marker = f"spawn:{claim_token}:{now:.3f}"
378
430
  lock_claimed = False
379
431
  for _ in range(2):
380
432
  try:
381
433
  fd = os.open(SYNC_LOCK_PATH, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
382
- os.write(fd, str(os.getpid()).encode("utf-8"))
383
- os.close(fd)
434
+ try:
435
+ os.write(fd, spawn_marker.encode("utf-8"))
436
+ finally:
437
+ os.close(fd)
384
438
  lock_claimed = True
385
439
  break
386
440
  except FileExistsError:
387
441
  try:
388
442
  with open(SYNC_LOCK_PATH, "r", encoding="utf-8") as f:
389
- pid = int(f.read().strip())
390
- # Check if PID is still alive
391
- os.kill(pid, 0)
392
- return # an active sync owns the lock
393
- except (ValueError, OSError, ProcessLookupError):
394
- # Stale lock from a dead process: reclaim it once
395
- try:
396
- os.unlink(SYNC_LOCK_PATH)
397
- except OSError:
443
+ existing = f.read()
444
+ if cls._lock_is_active(existing, allow_legacy_self=False):
398
445
  return
446
+ except OSError:
447
+ return
448
+ # Stale spawn/dead-worker/legacy-self lock: reclaim it once
449
+ try:
450
+ os.unlink(SYNC_LOCK_PATH)
451
+ except OSError:
452
+ return
399
453
  if not lock_claimed:
400
454
  return
401
455
 
@@ -405,7 +459,7 @@ class TelemetrySync:
405
459
  flags = subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.DETACHED_PROCESS
406
460
  script_path = os.path.abspath(__file__)
407
461
  subprocess.Popen(
408
- [sys.executable, script_path, "--background"],
462
+ [sys.executable, script_path, "--background", f"--claim-token={claim_token}"],
409
463
  cwd=PROJECT_ROOT,
410
464
  stdout=subprocess.DEVNULL,
411
465
  stderr=subprocess.DEVNULL,
@@ -414,41 +468,80 @@ class TelemetrySync:
414
468
  creationflags=flags
415
469
  )
416
470
  except Exception:
417
- pass
471
+ try:
472
+ with open(SYNC_LOCK_PATH, "r", encoding="utf-8") as f:
473
+ if f.read().strip() == spawn_marker:
474
+ os.unlink(SYNC_LOCK_PATH)
475
+ except OSError:
476
+ pass
418
477
 
419
478
 
420
- if __name__ == "__main__":
421
- is_bg = "--background" in sys.argv
422
- os.makedirs(DATA_DIR, exist_ok=True)
423
- # Claim the lock atomically; if another live process owns it, exit without syncing.
424
- try:
425
- fd = os.open(SYNC_LOCK_PATH, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
426
- os.write(fd, str(os.getpid()).encode("utf-8"))
427
- os.close(fd)
428
- except FileExistsError:
479
+ def _claim_worker_lock(claim_token: str) -> bool:
480
+ """Claims or takes over .sync.lock for the current sync worker process."""
481
+ worker_marker = f"worker:{os.getpid()}"
482
+ for _ in range(2):
429
483
  try:
430
- with open(SYNC_LOCK_PATH, "r", encoding="utf-8") as f:
431
- pid = int(f.read().strip())
432
- os.kill(pid, 0)
433
- sys.exit(0) # live owner is syncing already
434
- except (ValueError, OSError, ProcessLookupError):
484
+ fd = os.open(SYNC_LOCK_PATH, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
435
485
  try:
436
- os.unlink(SYNC_LOCK_PATH)
486
+ os.write(fd, worker_marker.encode("utf-8"))
487
+ finally:
488
+ os.close(fd)
489
+ return True
490
+ except FileExistsError:
491
+ try:
492
+ with open(SYNC_LOCK_PATH, "r", encoding="utf-8") as f:
493
+ existing = f.read().strip()
437
494
  except OSError:
438
- sys.exit(0)
495
+ return False
496
+
497
+ if claim_token and existing.startswith(f"spawn:{claim_token}:"):
498
+ tmp_path = f"{SYNC_LOCK_PATH}.{os.getpid()}.tmp"
499
+ try:
500
+ fd = os.open(tmp_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
501
+ try:
502
+ os.write(fd, worker_marker.encode("utf-8"))
503
+ finally:
504
+ os.close(fd)
505
+ os.replace(tmp_path, SYNC_LOCK_PATH)
506
+ return True
507
+ except OSError:
508
+ try:
509
+ if os.path.exists(tmp_path):
510
+ os.unlink(tmp_path)
511
+ except OSError:
512
+ pass
513
+ return False
514
+
515
+ if TelemetrySync._lock_is_active(existing, allow_legacy_self=True):
516
+ return False
517
+
439
518
  try:
440
- fd = os.open(SYNC_LOCK_PATH, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
441
- os.write(fd, str(os.getpid()).encode("utf-8"))
442
- os.close(fd)
443
- except FileExistsError:
444
- sys.exit(0)
519
+ os.unlink(SYNC_LOCK_PATH)
520
+ except OSError:
521
+ return False
522
+ return False
523
+
524
+
525
+ if __name__ == "__main__":
526
+ is_bg = "--background" in sys.argv
527
+ claim_token = ""
528
+ for arg in sys.argv[1:]:
529
+ if arg.startswith("--claim-token="):
530
+ claim_token = arg.split("=", 1)[1].strip()
531
+
532
+ os.makedirs(DATA_DIR, exist_ok=True)
533
+ if not _claim_worker_lock(claim_token):
534
+ sys.exit(0)
535
+
536
+ worker_marker = f"worker:{os.getpid()}"
445
537
  try:
446
538
  res = TelemetrySync.sync(timeout=10.0, verbose=not is_bg)
447
539
  if not is_bg:
448
540
  print(json.dumps(res, indent=2))
449
541
  finally:
450
542
  try:
451
- if os.path.exists(SYNC_LOCK_PATH):
452
- os.remove(SYNC_LOCK_PATH)
543
+ with open(SYNC_LOCK_PATH, "r", encoding="utf-8") as f:
544
+ if f.read().strip() == worker_marker:
545
+ os.remove(SYNC_LOCK_PATH)
453
546
  except Exception:
454
547
  pass
@@ -16,7 +16,7 @@ import urllib.request
16
16
  import urllib.error
17
17
  from typing import Dict, Any, Optional, Tuple
18
18
 
19
- CURRENT_VERSION = "2.5.2"
19
+ CURRENT_VERSION = "2.6.1"
20
20
  CACHE_TTL = 86400 # 24 hours
21
21
  # When the cloud is unreachable we must NOT cache the synthesized "up to date"
22
22
  # answer for a full day — otherwise an update released right after an outage