tokensafe 1.4.3 → 1.4.5
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 +1 -0
- package/bin/tokensafe.js +1 -0
- package/hooks/post_tool_use.py +15 -1
- package/hooks/pre_invocation.py +8 -1
- package/package.json +3 -1
- package/plugin.json +1 -1
- package/src/cli.py +37 -2
- package/src/license_manager.py +26 -1
- package/src/mcp_server.py +12 -1
- package/src/metrics.py +6 -0
- package/src/telemetry_sync.py +361 -0
- package/src/version_checker.py +11 -2
- package/hooks/__pycache__/pre_tool_use.cpython-313.pyc +0 -0
package/README.md
CHANGED
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
<p align="center">
|
|
14
14
|
<a href="https://github.com/NekoSin4eG/tokensafe/actions/workflows/test.yml"><img src="https://img.shields.io/github/actions/workflow/status/NekoSin4eG/tokensafe/test.yml?branch=main&label=tests&style=flat-square" alt="Tests"></a>
|
|
15
15
|
<a href="https://www.npmjs.com/package/tokensafe"><img src="https://img.shields.io/npm/v/tokensafe.svg?color=CB3837&style=flat-square" alt="npm"></a>
|
|
16
|
+
<a href="https://www.npmjs.com/package/tokensafe"><img src="https://img.shields.io/npm/dw/tokensafe.svg?color=10B981&label=npm%20downloads&style=flat-square" alt="npm downloads"></a>
|
|
16
17
|
<a href="https://pypi.org/project/tokensafe/"><img src="https://img.shields.io/pypi/v/tokensafe.svg?color=3775A9&style=flat-square" alt="PyPI"></a>
|
|
17
18
|
<a href="https://github.com/NekoSin4eG/tokensafe/stargazers"><img src="https://img.shields.io/github/stars/NekoSin4eG/tokensafe?style=flat-square&color=yellow" alt="Stars"></a>
|
|
18
19
|
<a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-emerald.svg?style=flat-square" alt="License"></a>
|
package/bin/tokensafe.js
CHANGED
|
@@ -39,6 +39,7 @@ Usage:
|
|
|
39
39
|
|
|
40
40
|
Commands:
|
|
41
41
|
tokensafe stats Show token economy savings & performance metrics
|
|
42
|
+
tokensafe sync Synchronize local token metrics with Cloud Dashboard
|
|
42
43
|
tokensafe html Generate and open interactive browser dashboard
|
|
43
44
|
tokensafe test "<prompt>" Test prompt compression on custom input
|
|
44
45
|
tokensafe doctor Audit MCP servers & skills context token tax
|
package/hooks/post_tool_use.py
CHANGED
|
@@ -2,12 +2,19 @@
|
|
|
2
2
|
"""
|
|
3
3
|
Antigravity Lifecycle Hook: PostToolUse
|
|
4
4
|
Fires after tool execution.
|
|
5
|
-
Fulfills Antigravity PostToolUse contract by returning `{}`.
|
|
5
|
+
1. Fulfills Antigravity PostToolUse contract by returning `{}`.
|
|
6
|
+
2. Triggers detached background telemetry sync if pending events exist.
|
|
6
7
|
"""
|
|
7
8
|
|
|
9
|
+
import os
|
|
8
10
|
import sys
|
|
9
11
|
import json
|
|
10
12
|
|
|
13
|
+
HOOK_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
14
|
+
PROJECT_ROOT = os.path.dirname(HOOK_DIR)
|
|
15
|
+
if PROJECT_ROOT not in sys.path:
|
|
16
|
+
sys.path.insert(0, PROJECT_ROOT)
|
|
17
|
+
|
|
11
18
|
def main():
|
|
12
19
|
try:
|
|
13
20
|
# Drain stdin to keep pipes clean
|
|
@@ -15,6 +22,13 @@ def main():
|
|
|
15
22
|
except Exception:
|
|
16
23
|
pass
|
|
17
24
|
|
|
25
|
+
# Non-blocking telemetry sync trigger (detached background process)
|
|
26
|
+
try:
|
|
27
|
+
from src.telemetry_sync import TelemetrySync
|
|
28
|
+
TelemetrySync.sync_background(throttle_seconds=60.0)
|
|
29
|
+
except Exception:
|
|
30
|
+
pass
|
|
31
|
+
|
|
18
32
|
# PostToolUse contract expects an empty JSON object {}
|
|
19
33
|
print(json.dumps({}))
|
|
20
34
|
|
package/hooks/pre_invocation.py
CHANGED
|
@@ -42,7 +42,14 @@ def main():
|
|
|
42
42
|
tracker = MetricsTracker()
|
|
43
43
|
inject_steps = []
|
|
44
44
|
|
|
45
|
-
# 0.
|
|
45
|
+
# 0. Asynchronous telemetry sync (detached & throttled to 60s)
|
|
46
|
+
try:
|
|
47
|
+
from src.telemetry_sync import TelemetrySync
|
|
48
|
+
TelemetrySync.sync_background(throttle_seconds=60.0)
|
|
49
|
+
except Exception:
|
|
50
|
+
pass
|
|
51
|
+
|
|
52
|
+
# 1. Quota and Environment Audits (Fires on first invocation)
|
|
46
53
|
quota = LicenseManager.check_quota(tracker)
|
|
47
54
|
if invocation_num <= 1:
|
|
48
55
|
if quota.get("warning"):
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
|
-
"version": "1.4.
|
|
3
|
+
"version": "1.4.5",
|
|
4
4
|
"description": "Autonomous Zero-Loss Token Economy & Context Optimizer for AI Coding Agents",
|
|
5
5
|
"main": "bin/tokensafe.js",
|
|
6
6
|
"bin": {
|
|
@@ -13,6 +13,8 @@
|
|
|
13
13
|
"src/*.py",
|
|
14
14
|
"!src/cloud_backend.py",
|
|
15
15
|
"!src/mailer.py",
|
|
16
|
+
"!**/__pycache__/**",
|
|
17
|
+
"!**/*.pyc",
|
|
16
18
|
"rules/",
|
|
17
19
|
"skills/",
|
|
18
20
|
"hooks/",
|
package/plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agy-token-optimizer",
|
|
3
3
|
"displayName": "TokenSafe",
|
|
4
|
-
"version": "1.4.
|
|
4
|
+
"version": "1.4.5",
|
|
5
5
|
"description": "Zero-Loss Token Economy & Context Optimizer for AI Agents. Compresses prompts, slices AST/tool outputs, and prevents stuck loops.",
|
|
6
6
|
"logo": "assets/logo.svg",
|
|
7
7
|
"author": {
|
package/src/cli.py
CHANGED
|
@@ -29,6 +29,11 @@ def main():
|
|
|
29
29
|
command = args[0] if args else "stats"
|
|
30
30
|
|
|
31
31
|
if command in ("stats", "dashboard"):
|
|
32
|
+
try:
|
|
33
|
+
from src.telemetry_sync import TelemetrySync
|
|
34
|
+
TelemetrySync.sync_background()
|
|
35
|
+
except Exception:
|
|
36
|
+
pass
|
|
32
37
|
print(dashboard.render_terminal())
|
|
33
38
|
|
|
34
39
|
elif command in ("html", "web"):
|
|
@@ -207,11 +212,41 @@ def main():
|
|
|
207
212
|
key = args[1].strip()
|
|
208
213
|
ok, msg = LicenseManager.save_license(key)
|
|
209
214
|
if ok:
|
|
210
|
-
print(f"\n\033[32m\033[1m✔ {msg}\033[0m
|
|
215
|
+
print(f"\n\033[32m\033[1m✔ {msg}\033[0m")
|
|
216
|
+
# Automatically report version and seat activation to cloud
|
|
217
|
+
try:
|
|
218
|
+
from src.version_checker import VersionChecker
|
|
219
|
+
VersionChecker.check_version(license_key=key, force_fetch=True)
|
|
220
|
+
except Exception:
|
|
221
|
+
pass
|
|
222
|
+
# Automatically sync existing local token metrics to newly activated license
|
|
223
|
+
try:
|
|
224
|
+
from src.telemetry_sync import TelemetrySync
|
|
225
|
+
sync_res = TelemetrySync.sync(license_key=key, timeout=3.0)
|
|
226
|
+
if sync_res.get("success") and sync_res.get("synced_events", 0) > 0:
|
|
227
|
+
print(f" \033[36m✔ Synced {sync_res['synced_events']:,} past optimization events to cloud dashboard.\033[0m")
|
|
228
|
+
except Exception:
|
|
229
|
+
pass
|
|
230
|
+
print()
|
|
211
231
|
else:
|
|
212
232
|
print(f"\n\033[31m\033[1m✖ {msg}\033[0m\n")
|
|
213
233
|
sys.exit(1)
|
|
214
234
|
|
|
235
|
+
elif command in ("sync", "push"):
|
|
236
|
+
from src.telemetry_sync import TelemetrySync
|
|
237
|
+
print("\n\033[1m\033[36m⚡ SYNCHRONIZING TOKEN METRICS WITH DASHBOARD ⚡\033[0m\n")
|
|
238
|
+
force_sync = "--force" in args or "-f" in args
|
|
239
|
+
status_before = TelemetrySync.get_sync_status()
|
|
240
|
+
print(f" Local recorded events: {status_before['total_local_events']:,}")
|
|
241
|
+
print(f" Pending sync: {status_before['pending_events']:,}\n")
|
|
242
|
+
res = TelemetrySync.sync(force=force_sync, verbose=True)
|
|
243
|
+
if res.get("success"):
|
|
244
|
+
print(f" \033[32m✔ {res.get('message', 'Synchronized successfully.')}\033[0m")
|
|
245
|
+
status_after = TelemetrySync.get_sync_status()
|
|
246
|
+
print(f" Total synced events: {status_after['total_synced_events']:,}\n")
|
|
247
|
+
else:
|
|
248
|
+
print(f" \033[31m✖ Sync failed: {res.get('error', 'Unknown error')}\033[0m\n")
|
|
249
|
+
|
|
215
250
|
elif command in ("license", "tier"):
|
|
216
251
|
from src.license_manager import LicenseManager
|
|
217
252
|
tier, payload = LicenseManager.get_active_license()
|
|
@@ -391,7 +426,7 @@ def main():
|
|
|
391
426
|
|
|
392
427
|
else:
|
|
393
428
|
print(f"Unknown command: {command}")
|
|
394
|
-
print("Available commands: stats, html, test, doctor, providers, mcp, benchmark, proxy, graph, map, vacuum, prune, digest, activate, license, markdown, setup, reset")
|
|
429
|
+
print("Available commands: stats, sync, html, test, doctor, providers, mcp, benchmark, proxy, graph, map, vacuum, prune, digest, activate, license, markdown, setup, reset")
|
|
395
430
|
sys.exit(1)
|
|
396
431
|
|
|
397
432
|
if __name__ == "__main__":
|
package/src/license_manager.py
CHANGED
|
@@ -19,6 +19,8 @@ LICENSE_FILE = os.path.join(DATA_DIR, "license.json")
|
|
|
19
19
|
|
|
20
20
|
# Master Public Key for client-side offline verification (RFC 8032 Ed25519)
|
|
21
21
|
DEFAULT_ED25519_PUBLIC_KEY = os.environ.get("TOKENSAFE_PUBLIC_KEY", "3911e2ffe5ad07ee23be392b88f238af302f9d3a0bf51881de8b5e0e6af71430")
|
|
22
|
+
# Pre-rotation public keys accepted for backwards compatibility
|
|
23
|
+
LEGACY_ED25519_PUBLIC_KEYS = ("8a2c9d550180ab5b00a06174cb6aecfd712740c59d0bdcff66a56515348c855e",)
|
|
22
24
|
# Private key for cloud server signing (never distributed to client, loaded strictly from environment)
|
|
23
25
|
DEFAULT_ED25519_PRIVATE_KEY = os.environ.get("TOKENSAFE_PRIVATE_KEY", "")
|
|
24
26
|
# Rotated HMAC salt for backward compatibility with TS1 legacy licenses
|
|
@@ -221,7 +223,17 @@ class LicenseManager:
|
|
|
221
223
|
return False, {}, "Invalid signature encoding"
|
|
222
224
|
|
|
223
225
|
if not _ed25519_verify_bytes(sig_bytes, payload_bytes, pub_bytes):
|
|
224
|
-
|
|
226
|
+
verified = False
|
|
227
|
+
if not public_key:
|
|
228
|
+
for leg_hex in LEGACY_ED25519_PUBLIC_KEYS:
|
|
229
|
+
try:
|
|
230
|
+
if _ed25519_verify_bytes(sig_bytes, payload_bytes, bytes.fromhex(leg_hex)):
|
|
231
|
+
verified = True
|
|
232
|
+
break
|
|
233
|
+
except Exception:
|
|
234
|
+
pass
|
|
235
|
+
if not verified:
|
|
236
|
+
return False, {}, "Invalid digital signature: license key has been tampered with or is counterfeit"
|
|
225
237
|
|
|
226
238
|
# 2. Legacy TS1 Verification
|
|
227
239
|
else:
|
|
@@ -262,6 +274,19 @@ class LicenseManager:
|
|
|
262
274
|
|
|
263
275
|
return "free", {"tier": "free", "max_tokens_monthly": 500_000}
|
|
264
276
|
|
|
277
|
+
@classmethod
|
|
278
|
+
def get_active_license_key(cls) -> str:
|
|
279
|
+
"""Retrieves active raw license key string from env or data/license.json, or empty string."""
|
|
280
|
+
key = os.environ.get("TOKENSAFE_LICENSE_KEY", "").strip()
|
|
281
|
+
if not key and os.path.exists(LICENSE_FILE):
|
|
282
|
+
try:
|
|
283
|
+
with open(LICENSE_FILE, "r", encoding="utf-8") as f:
|
|
284
|
+
data = json.load(f)
|
|
285
|
+
key = data.get("license_key", "").strip()
|
|
286
|
+
except Exception:
|
|
287
|
+
pass
|
|
288
|
+
return key
|
|
289
|
+
|
|
265
290
|
@classmethod
|
|
266
291
|
def save_license(cls, license_key: str) -> Tuple[bool, str]:
|
|
267
292
|
"""Saves a verified license key to local persistent storage."""
|
package/src/mcp_server.py
CHANGED
|
@@ -31,7 +31,7 @@ from src.guard import TokenSafeGuard
|
|
|
31
31
|
|
|
32
32
|
SERVER_INFO = {
|
|
33
33
|
"name": "tokensafe-mcp",
|
|
34
|
-
"version": "1.4.
|
|
34
|
+
"version": "1.4.5"
|
|
35
35
|
}
|
|
36
36
|
|
|
37
37
|
TOOLS = [
|
|
@@ -570,6 +570,11 @@ def run_mcp_server():
|
|
|
570
570
|
response = {"jsonrpc": "2.0", "id": msg_id}
|
|
571
571
|
|
|
572
572
|
if method == "initialize":
|
|
573
|
+
try:
|
|
574
|
+
from src.telemetry_sync import TelemetrySync
|
|
575
|
+
TelemetrySync.sync_background()
|
|
576
|
+
except Exception:
|
|
577
|
+
pass
|
|
573
578
|
response["result"] = {
|
|
574
579
|
"protocolVersion": "2024-11-05",
|
|
575
580
|
"capabilities": {"tools": {}},
|
|
@@ -590,6 +595,12 @@ def run_mcp_server():
|
|
|
590
595
|
"isError": True,
|
|
591
596
|
"content": [{"type": "text", "text": f"Error: {str(e)}\n{traceback.format_exc()}"}]
|
|
592
597
|
}
|
|
598
|
+
finally:
|
|
599
|
+
try:
|
|
600
|
+
from src.telemetry_sync import TelemetrySync
|
|
601
|
+
TelemetrySync.sync_background(throttle_seconds=60.0)
|
|
602
|
+
except Exception:
|
|
603
|
+
pass
|
|
593
604
|
else:
|
|
594
605
|
response["error"] = {"code": -32601, "message": f"Method not found: {method}"}
|
|
595
606
|
|
package/src/metrics.py
CHANGED
|
@@ -133,6 +133,12 @@ class MetricsTracker:
|
|
|
133
133
|
|
|
134
134
|
# Periodic amortized auto-retention check (every 100 events)
|
|
135
135
|
self._event_counter += 1
|
|
136
|
+
if self._event_counter % 20 == 0:
|
|
137
|
+
try:
|
|
138
|
+
from src.telemetry_sync import TelemetrySync
|
|
139
|
+
TelemetrySync.sync_background()
|
|
140
|
+
except Exception:
|
|
141
|
+
pass
|
|
136
142
|
if self._event_counter >= 100:
|
|
137
143
|
self._event_counter = 0
|
|
138
144
|
try:
|
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
"""
|
|
2
|
+
TokenSafe Telemetry Sync Engine.
|
|
3
|
+
Synchronizes local token optimization metrics from SQLite (data/metrics.db)
|
|
4
|
+
with TokenSafe Cloud Dashboard API.
|
|
5
|
+
|
|
6
|
+
Features:
|
|
7
|
+
- Zero external runtime dependencies (Python standard library only).
|
|
8
|
+
- Offline-safe with fast connection timeout (< 2.5s).
|
|
9
|
+
- Non-blocking asynchronous background sync support.
|
|
10
|
+
- Idempotent tracking of synced event IDs to prevent duplicate counting.
|
|
11
|
+
- Lifetime aggregate preservation for pruned historical events.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import os
|
|
15
|
+
import sys
|
|
16
|
+
import json
|
|
17
|
+
import time
|
|
18
|
+
import sqlite3
|
|
19
|
+
import threading
|
|
20
|
+
import subprocess
|
|
21
|
+
import urllib.request
|
|
22
|
+
import urllib.parse
|
|
23
|
+
import urllib.error
|
|
24
|
+
from datetime import datetime
|
|
25
|
+
from typing import Dict, Any, List, Optional, Tuple
|
|
26
|
+
|
|
27
|
+
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
28
|
+
if PROJECT_ROOT not in sys.path:
|
|
29
|
+
sys.path.insert(0, PROJECT_ROOT)
|
|
30
|
+
|
|
31
|
+
from src.license_manager import LicenseManager
|
|
32
|
+
|
|
33
|
+
DATA_DIR = os.path.join(PROJECT_ROOT, "data")
|
|
34
|
+
METRICS_DB_PATH = os.path.join(DATA_DIR, "metrics.db")
|
|
35
|
+
SYNC_STATE_PATH = os.path.join(DATA_DIR, "sync_state.json")
|
|
36
|
+
SYNC_LOCK_PATH = os.path.join(DATA_DIR, ".sync.lock")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _get_cloud_url() -> str:
|
|
40
|
+
base = os.environ.get("TOKENSAFE_CLOUD_URL")
|
|
41
|
+
if not base:
|
|
42
|
+
base = "https://api.tokensafe.dev"
|
|
43
|
+
return base.rstrip("/")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class TelemetrySync:
|
|
47
|
+
"""Manages secure telemetry synchronization between local metrics and cloud dashboard."""
|
|
48
|
+
|
|
49
|
+
_sync_lock = threading.Lock()
|
|
50
|
+
_last_bg_sync_time = 0.0
|
|
51
|
+
|
|
52
|
+
@classmethod
|
|
53
|
+
def get_state(cls) -> Dict[str, Any]:
|
|
54
|
+
"""Loads sync cursor state from persistent JSON."""
|
|
55
|
+
if not os.path.exists(SYNC_STATE_PATH):
|
|
56
|
+
return {
|
|
57
|
+
"last_synced_event_id": 0,
|
|
58
|
+
"last_synced_at": 0,
|
|
59
|
+
"total_synced_events": 0,
|
|
60
|
+
"lifetime_rollup_synced": False
|
|
61
|
+
}
|
|
62
|
+
try:
|
|
63
|
+
with open(SYNC_STATE_PATH, "r", encoding="utf-8") as f:
|
|
64
|
+
return json.load(f)
|
|
65
|
+
except Exception:
|
|
66
|
+
return {
|
|
67
|
+
"last_synced_event_id": 0,
|
|
68
|
+
"last_synced_at": 0,
|
|
69
|
+
"total_synced_events": 0,
|
|
70
|
+
"lifetime_rollup_synced": False
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
@classmethod
|
|
74
|
+
def save_state(cls, state: Dict[str, Any]):
|
|
75
|
+
"""Persists sync cursor state."""
|
|
76
|
+
os.makedirs(DATA_DIR, exist_ok=True)
|
|
77
|
+
try:
|
|
78
|
+
with open(SYNC_STATE_PATH, "w", encoding="utf-8") as f:
|
|
79
|
+
json.dump(state, f, indent=2)
|
|
80
|
+
except Exception:
|
|
81
|
+
pass
|
|
82
|
+
|
|
83
|
+
@classmethod
|
|
84
|
+
def get_sync_status(cls) -> Dict[str, Any]:
|
|
85
|
+
"""Returns statistics on local events, synced events, and pending sync count."""
|
|
86
|
+
state = cls.get_state()
|
|
87
|
+
last_id = state.get("last_synced_event_id", 0)
|
|
88
|
+
|
|
89
|
+
total_local = 0
|
|
90
|
+
pending = 0
|
|
91
|
+
if os.path.exists(METRICS_DB_PATH):
|
|
92
|
+
try:
|
|
93
|
+
conn = sqlite3.connect(METRICS_DB_PATH)
|
|
94
|
+
c = conn.cursor()
|
|
95
|
+
row = c.execute("SELECT COUNT(*) FROM events").fetchone()
|
|
96
|
+
total_local = row[0] if row else 0
|
|
97
|
+
row_pending = c.execute("SELECT COUNT(*) FROM events WHERE id > ?", (last_id,)).fetchone()
|
|
98
|
+
pending = row_pending[0] if row_pending else 0
|
|
99
|
+
conn.close()
|
|
100
|
+
except Exception:
|
|
101
|
+
pass
|
|
102
|
+
|
|
103
|
+
return {
|
|
104
|
+
"total_local_events": total_local,
|
|
105
|
+
"last_synced_event_id": last_id,
|
|
106
|
+
"pending_events": pending,
|
|
107
|
+
"last_synced_at": state.get("last_synced_at", 0),
|
|
108
|
+
"total_synced_events": state.get("total_synced_events", 0)
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
@classmethod
|
|
112
|
+
def sync(
|
|
113
|
+
cls,
|
|
114
|
+
cloud_url: Optional[str] = None,
|
|
115
|
+
license_key: Optional[str] = None,
|
|
116
|
+
email: Optional[str] = None,
|
|
117
|
+
force: bool = False,
|
|
118
|
+
batch_size: int = 500,
|
|
119
|
+
timeout: float = 2.5,
|
|
120
|
+
verbose: bool = False
|
|
121
|
+
) -> Dict[str, Any]:
|
|
122
|
+
"""
|
|
123
|
+
Synchronizes all un-synced events from data/metrics.db to the TokenSafe cloud server.
|
|
124
|
+
Returns a dict with sync results and totals.
|
|
125
|
+
"""
|
|
126
|
+
with cls._sync_lock:
|
|
127
|
+
base_url = (cloud_url or _get_cloud_url()).rstrip("/")
|
|
128
|
+
target_url = f"{base_url}/api/telemetry/sync"
|
|
129
|
+
active_key = license_key or LicenseManager.get_active_license_key()
|
|
130
|
+
|
|
131
|
+
target_email = (email or "").strip().lower()
|
|
132
|
+
if not target_email and active_key:
|
|
133
|
+
_, payload, _ = LicenseManager.validate_license(active_key)
|
|
134
|
+
target_email = payload.get("email", "").strip().lower()
|
|
135
|
+
|
|
136
|
+
# Community fallback: unauthenticated users participate in global token savings
|
|
137
|
+
if not target_email:
|
|
138
|
+
target_email = "community@tokensafe.dev"
|
|
139
|
+
if not active_key:
|
|
140
|
+
active_key = "community"
|
|
141
|
+
|
|
142
|
+
if not os.path.exists(METRICS_DB_PATH):
|
|
143
|
+
return {
|
|
144
|
+
"success": True,
|
|
145
|
+
"synced_events": 0,
|
|
146
|
+
"total_synced": 0,
|
|
147
|
+
"message": "No local metrics database found."
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
state = cls.get_state()
|
|
151
|
+
last_id = 0 if force else state.get("last_synced_event_id", 0)
|
|
152
|
+
|
|
153
|
+
try:
|
|
154
|
+
conn = sqlite3.connect(METRICS_DB_PATH)
|
|
155
|
+
conn.row_factory = sqlite3.Row
|
|
156
|
+
cur = conn.cursor()
|
|
157
|
+
|
|
158
|
+
synthetic_events: List[Dict[str, Any]] = []
|
|
159
|
+
if not state.get("lifetime_rollup_synced", False):
|
|
160
|
+
try:
|
|
161
|
+
life_row = cur.execute("SELECT * FROM lifetime_aggregates WHERE id = 1").fetchone()
|
|
162
|
+
if life_row and life_row["total_saved_tokens"] > 0:
|
|
163
|
+
synthetic_events.append({
|
|
164
|
+
"event_type": "ROLLUP_LIFETIME",
|
|
165
|
+
"original_tokens": int(life_row["total_original_tokens"]),
|
|
166
|
+
"saved_tokens": int(life_row["total_saved_tokens"]),
|
|
167
|
+
"usd_saved": float(life_row["total_usd_saved"]),
|
|
168
|
+
"model": "aggregate",
|
|
169
|
+
"timestamp": int(time.time())
|
|
170
|
+
})
|
|
171
|
+
except Exception:
|
|
172
|
+
pass
|
|
173
|
+
|
|
174
|
+
rows = cur.execute(
|
|
175
|
+
"SELECT id, timestamp, event_type, original_tokens, saved_tokens, est_usd_saved, details "
|
|
176
|
+
"FROM events WHERE id > ? ORDER BY id ASC LIMIT 2000",
|
|
177
|
+
(last_id,)
|
|
178
|
+
).fetchall()
|
|
179
|
+
conn.close()
|
|
180
|
+
except Exception as e:
|
|
181
|
+
return {
|
|
182
|
+
"success": False,
|
|
183
|
+
"synced_events": 0,
|
|
184
|
+
"error": f"Failed to read local metrics database: {str(e)}"
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
if not rows and not synthetic_events:
|
|
188
|
+
return {
|
|
189
|
+
"success": True,
|
|
190
|
+
"synced_events": 0,
|
|
191
|
+
"total_synced": state.get("total_synced_events", 0),
|
|
192
|
+
"message": "All metrics are already up to date."
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
formatted_events: List[Dict[str, Any]] = list(synthetic_events)
|
|
196
|
+
max_id = last_id
|
|
197
|
+
|
|
198
|
+
for r in rows:
|
|
199
|
+
ev_id = r["id"]
|
|
200
|
+
if ev_id > max_id:
|
|
201
|
+
max_id = ev_id
|
|
202
|
+
|
|
203
|
+
raw_ts = r["timestamp"]
|
|
204
|
+
ts_int = int(time.time())
|
|
205
|
+
if isinstance(raw_ts, (int, float)):
|
|
206
|
+
ts_int = int(raw_ts)
|
|
207
|
+
elif isinstance(raw_ts, str) and raw_ts.strip():
|
|
208
|
+
try:
|
|
209
|
+
ts_int = int(float(raw_ts.strip()))
|
|
210
|
+
except ValueError:
|
|
211
|
+
try:
|
|
212
|
+
clean_iso = raw_ts.strip().replace("Z", "+00:00")
|
|
213
|
+
dt = datetime.fromisoformat(clean_iso)
|
|
214
|
+
ts_int = int(dt.timestamp())
|
|
215
|
+
except Exception:
|
|
216
|
+
ts_int = int(time.time())
|
|
217
|
+
|
|
218
|
+
model_name = "default"
|
|
219
|
+
if r["details"]:
|
|
220
|
+
try:
|
|
221
|
+
det = json.loads(r["details"]) if isinstance(r["details"], str) else r["details"]
|
|
222
|
+
if isinstance(det, dict) and det.get("model"):
|
|
223
|
+
model_name = str(det["model"])
|
|
224
|
+
except Exception:
|
|
225
|
+
pass
|
|
226
|
+
|
|
227
|
+
formatted_events.append({
|
|
228
|
+
"event_type": str(r["event_type"] or "PROMPT"),
|
|
229
|
+
"original_tokens": int(r["original_tokens"] or 0),
|
|
230
|
+
"saved_tokens": int(r["saved_tokens"] or 0),
|
|
231
|
+
"usd_saved": float(r["est_usd_saved"] or 0.0),
|
|
232
|
+
"model": model_name,
|
|
233
|
+
"timestamp": ts_int
|
|
234
|
+
})
|
|
235
|
+
|
|
236
|
+
total_sent = 0
|
|
237
|
+
headers = {
|
|
238
|
+
"Content-Type": "application/json",
|
|
239
|
+
"User-Agent": "TokenSafe-Sync/1.4.5"
|
|
240
|
+
}
|
|
241
|
+
if active_key:
|
|
242
|
+
headers["Authorization"] = f"Bearer {active_key}"
|
|
243
|
+
|
|
244
|
+
for i in range(0, len(formatted_events), batch_size):
|
|
245
|
+
chunk = formatted_events[i:i + batch_size]
|
|
246
|
+
body_dict = {
|
|
247
|
+
"email": target_email,
|
|
248
|
+
"license_key": active_key,
|
|
249
|
+
"events": chunk
|
|
250
|
+
}
|
|
251
|
+
body_bytes = json.dumps(body_dict).encode("utf-8")
|
|
252
|
+
|
|
253
|
+
req = urllib.request.Request(target_url, data=body_bytes, headers=headers, method="POST")
|
|
254
|
+
try:
|
|
255
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
256
|
+
if resp.status == 200:
|
|
257
|
+
total_sent += len(chunk)
|
|
258
|
+
else:
|
|
259
|
+
return {
|
|
260
|
+
"success": False,
|
|
261
|
+
"synced_events": total_sent,
|
|
262
|
+
"error": f"Server returned HTTP {resp.status}"
|
|
263
|
+
}
|
|
264
|
+
except urllib.error.HTTPError as he:
|
|
265
|
+
return {
|
|
266
|
+
"success": False,
|
|
267
|
+
"synced_events": total_sent,
|
|
268
|
+
"error": f"Cloud API error: {he.code} {he.reason}"
|
|
269
|
+
}
|
|
270
|
+
except Exception as ex:
|
|
271
|
+
return {
|
|
272
|
+
"success": False,
|
|
273
|
+
"synced_events": total_sent,
|
|
274
|
+
"error": f"Network error during sync: {str(ex)}"
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
new_state = {
|
|
278
|
+
"last_synced_event_id": max_id,
|
|
279
|
+
"last_synced_at": int(time.time()),
|
|
280
|
+
"total_synced_events": state.get("total_synced_events", 0) + total_sent,
|
|
281
|
+
"lifetime_rollup_synced": True
|
|
282
|
+
}
|
|
283
|
+
cls.save_state(new_state)
|
|
284
|
+
|
|
285
|
+
return {
|
|
286
|
+
"success": True,
|
|
287
|
+
"synced_events": total_sent,
|
|
288
|
+
"total_synced": new_state["total_synced_events"],
|
|
289
|
+
"message": f"Successfully synchronized {total_sent:,} events to TokenSafe Cloud."
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
@classmethod
|
|
293
|
+
def sync_background(cls, throttle_seconds: float = 60.0, force: bool = False):
|
|
294
|
+
"""
|
|
295
|
+
Spawns a detached, non-blocking background OS process to sync metrics.
|
|
296
|
+
Throttled to run at most once every `throttle_seconds` (default: 60s)
|
|
297
|
+
using persistent state from sync_state.json.
|
|
298
|
+
Detached from parent process group so it survives the termination of short-lived CLI lifecycle hooks.
|
|
299
|
+
"""
|
|
300
|
+
now = time.time()
|
|
301
|
+
state = cls.get_state()
|
|
302
|
+
last_synced = state.get("last_synced_at", 0)
|
|
303
|
+
if not force and (now - last_synced) < throttle_seconds:
|
|
304
|
+
return
|
|
305
|
+
|
|
306
|
+
status = cls.get_sync_status()
|
|
307
|
+
if status.get("pending_events", 0) == 0:
|
|
308
|
+
return
|
|
309
|
+
|
|
310
|
+
# Prevent overlapping sync runs via PID lock file
|
|
311
|
+
if os.path.exists(SYNC_LOCK_PATH):
|
|
312
|
+
try:
|
|
313
|
+
with open(SYNC_LOCK_PATH, "r", encoding="utf-8") as f:
|
|
314
|
+
pid = int(f.read().strip())
|
|
315
|
+
# Check if PID is still alive
|
|
316
|
+
os.kill(pid, 0)
|
|
317
|
+
return
|
|
318
|
+
except (ValueError, OSError, ProcessLookupError):
|
|
319
|
+
pass
|
|
320
|
+
|
|
321
|
+
try:
|
|
322
|
+
flags = 0
|
|
323
|
+
if os.name == "nt":
|
|
324
|
+
flags = subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.DETACHED_PROCESS
|
|
325
|
+
script_path = os.path.abspath(__file__)
|
|
326
|
+
subprocess.Popen(
|
|
327
|
+
[sys.executable, script_path, "--background"],
|
|
328
|
+
cwd=PROJECT_ROOT,
|
|
329
|
+
stdout=subprocess.DEVNULL,
|
|
330
|
+
stderr=subprocess.DEVNULL,
|
|
331
|
+
stdin=subprocess.DEVNULL,
|
|
332
|
+
start_new_session=(os.name != "nt"),
|
|
333
|
+
creationflags=flags
|
|
334
|
+
)
|
|
335
|
+
except Exception:
|
|
336
|
+
# Fallback to daemon thread if process spawn fails
|
|
337
|
+
def _worker():
|
|
338
|
+
try:
|
|
339
|
+
cls.sync(timeout=2.0)
|
|
340
|
+
except Exception:
|
|
341
|
+
pass
|
|
342
|
+
|
|
343
|
+
t = threading.Thread(target=_worker, daemon=True)
|
|
344
|
+
t.start()
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
if __name__ == "__main__":
|
|
348
|
+
is_bg = "--background" in sys.argv
|
|
349
|
+
os.makedirs(DATA_DIR, exist_ok=True)
|
|
350
|
+
try:
|
|
351
|
+
with open(SYNC_LOCK_PATH, "w", encoding="utf-8") as f:
|
|
352
|
+
f.write(str(os.getpid()))
|
|
353
|
+
res = TelemetrySync.sync(timeout=5.0 if is_bg else 10.0, verbose=not is_bg)
|
|
354
|
+
if not is_bg:
|
|
355
|
+
print(json.dumps(res, indent=2))
|
|
356
|
+
finally:
|
|
357
|
+
try:
|
|
358
|
+
if os.path.exists(SYNC_LOCK_PATH):
|
|
359
|
+
os.remove(SYNC_LOCK_PATH)
|
|
360
|
+
except Exception:
|
|
361
|
+
pass
|
package/src/version_checker.py
CHANGED
|
@@ -14,7 +14,7 @@ import urllib.request
|
|
|
14
14
|
import urllib.error
|
|
15
15
|
from typing import Dict, Any, Optional, Tuple
|
|
16
16
|
|
|
17
|
-
CURRENT_VERSION = "1.
|
|
17
|
+
CURRENT_VERSION = "1.4.5"
|
|
18
18
|
CACHE_TTL = 86400 # 24 hours
|
|
19
19
|
|
|
20
20
|
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
@@ -87,6 +87,13 @@ class VersionChecker:
|
|
|
87
87
|
Falls back gracefully on network or offline scenarios.
|
|
88
88
|
"""
|
|
89
89
|
now = int(time.time())
|
|
90
|
+
if not license_key:
|
|
91
|
+
try:
|
|
92
|
+
from src.license_manager import LicenseManager
|
|
93
|
+
license_key = LicenseManager.get_active_license_key()
|
|
94
|
+
except Exception:
|
|
95
|
+
license_key = ""
|
|
96
|
+
|
|
90
97
|
cached = cls.load_cache()
|
|
91
98
|
|
|
92
99
|
if not force_fetch and cached:
|
|
@@ -107,7 +114,9 @@ class VersionChecker:
|
|
|
107
114
|
}
|
|
108
115
|
|
|
109
116
|
try:
|
|
110
|
-
|
|
117
|
+
import platform as _plat
|
|
118
|
+
plat_str = f"{_plat.system().lower()}-{_plat.machine().lower()}"
|
|
119
|
+
params = f"?version={urllib.parse.quote(current_version)}&license={urllib.parse.quote(license_key)}&platform={urllib.parse.quote(plat_str)}&client_type=cli"
|
|
111
120
|
url = f"{CLOUD_CHECK_URL}{params}"
|
|
112
121
|
req = urllib.request.Request(
|
|
113
122
|
url,
|
|
Binary file
|