tokensafe 2.6.0 → 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/hooks/claude_code_hook.py +6 -0
- package/hooks/cursor_hook.py +6 -0
- package/hooks/post_tool_use.py +1 -1
- package/hooks/pre_invocation.py +2 -2
- package/hooks/pre_tool_use.py +13 -0
- package/hooks/stop_hook.py +6 -6
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/mcp_server.py +2 -2
- package/src/proxy.py +2 -0
- package/src/telemetry_sync.py +278 -185
- package/src/version_checker.py +1 -1
|
@@ -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
|
|
package/hooks/cursor_hook.py
CHANGED
|
@@ -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
|
|
package/hooks/post_tool_use.py
CHANGED
|
@@ -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=
|
|
28
|
+
TelemetrySync.sync_background(throttle_seconds=20.0)
|
|
29
29
|
except Exception:
|
|
30
30
|
pass
|
|
31
31
|
|
package/hooks/pre_invocation.py
CHANGED
|
@@ -74,10 +74,10 @@ def main():
|
|
|
74
74
|
tracker = MetricsTracker()
|
|
75
75
|
inject_steps = []
|
|
76
76
|
|
|
77
|
-
# 0. Asynchronous telemetry sync (detached & throttled to
|
|
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=
|
|
80
|
+
TelemetrySync.sync_background(throttle_seconds=20.0)
|
|
81
81
|
except Exception:
|
|
82
82
|
pass
|
|
83
83
|
|
package/hooks/pre_tool_use.py
CHANGED
|
@@ -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}"
|
package/hooks/stop_hook.py
CHANGED
|
@@ -52,13 +52,13 @@ def main():
|
|
|
52
52
|
from src.metrics import MetricsTracker
|
|
53
53
|
tracker = MetricsTracker()
|
|
54
54
|
|
|
55
|
-
# 1.
|
|
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.6.
|
|
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.6.
|
|
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.6.
|
|
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.6.
|
|
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.6.
|
|
49
|
+
"version": "2.6.1",
|
|
50
50
|
"runtimeHint": "uvx",
|
|
51
51
|
"transport": {
|
|
52
52
|
"type": "stdio"
|
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.6.
|
|
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=
|
|
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")
|
package/src/telemetry_sync.py
CHANGED
|
@@ -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.6.
|
|
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
|
-
|
|
300
|
-
|
|
301
|
-
|
|
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
|
-
|
|
315
|
-
|
|
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
|
-
|
|
318
|
-
|
|
319
|
-
|
|
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
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
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
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
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
|
|
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:
|
|
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
|
-
|
|
376
|
-
#
|
|
377
|
-
#
|
|
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
|
-
|
|
383
|
-
|
|
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
|
-
|
|
390
|
-
|
|
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
|
-
|
|
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
|
-
|
|
421
|
-
|
|
422
|
-
os.
|
|
423
|
-
|
|
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
|
-
|
|
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.
|
|
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
|
-
|
|
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
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
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
|
-
|
|
452
|
-
|
|
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
|
package/src/version_checker.py
CHANGED
|
@@ -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.6.
|
|
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
|