tokensafe 1.4.11 → 1.4.13
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/package.json +1 -1
- package/plugin.json +1 -1
- package/src/graph_engine.py +4 -0
- package/src/mcp_server.py +118 -23
- package/src/metrics.py +63 -48
- package/src/scoped_search.py +4 -2
- package/src/telemetry_sync.py +51 -39
- package/src/version_checker.py +1 -1
package/package.json
CHANGED
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.13",
|
|
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/graph_engine.py
CHANGED
|
@@ -12,6 +12,7 @@ import os
|
|
|
12
12
|
import ast
|
|
13
13
|
import re
|
|
14
14
|
import json
|
|
15
|
+
import stat
|
|
15
16
|
import time
|
|
16
17
|
from typing import Dict, Set, List, Optional, Tuple, Any
|
|
17
18
|
|
|
@@ -146,6 +147,9 @@ class CodeGraph:
|
|
|
146
147
|
"""Indexes a single code file using standard AST or regex tokenizers."""
|
|
147
148
|
self._purge_file(rel_path)
|
|
148
149
|
try:
|
|
150
|
+
st = os.stat(full_path)
|
|
151
|
+
if not stat.S_ISREG(st.st_mode) or st.st_size > 2 * 1024 * 1024:
|
|
152
|
+
return
|
|
149
153
|
with open(full_path, "r", encoding="utf-8", errors="replace") as f:
|
|
150
154
|
content = f.read()
|
|
151
155
|
except OSError:
|
package/src/mcp_server.py
CHANGED
|
@@ -6,8 +6,10 @@ Exposes tools for smart file reading, dependency prefetching, prompt compression
|
|
|
6
6
|
|
|
7
7
|
import sys
|
|
8
8
|
import os
|
|
9
|
+
import stat
|
|
9
10
|
import time
|
|
10
11
|
import json
|
|
12
|
+
import threading
|
|
11
13
|
import traceback
|
|
12
14
|
import fnmatch
|
|
13
15
|
from typing import Tuple, Optional
|
|
@@ -33,7 +35,7 @@ from src.scoped_search import ScopedSearch
|
|
|
33
35
|
|
|
34
36
|
SERVER_INFO = {
|
|
35
37
|
"name": "tokensafe-mcp",
|
|
36
|
-
"version": "1.4.
|
|
38
|
+
"version": "1.4.13"
|
|
37
39
|
}
|
|
38
40
|
|
|
39
41
|
TOOLS = [
|
|
@@ -322,8 +324,71 @@ def _resolve_project_root(args: dict) -> Tuple[Optional[str], Optional[str]]:
|
|
|
322
324
|
|
|
323
325
|
return None, "Error: Invalid or root project_path. Please specify an explicit 'project_path' pointing to your project directory (e.g. project_path='/path/to/project')."
|
|
324
326
|
|
|
327
|
+
MCP_TOOL_TIMEOUT = float(os.environ.get("TOKENSAFE_MCP_TIMEOUT", "8.0"))
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _fallback_error(tool_name: str, reason: str) -> dict:
|
|
331
|
+
"""Returns a non-blocking, actionable error telling the AI model to try another approach."""
|
|
332
|
+
clean_reason = (reason or "unknown error").strip()
|
|
333
|
+
return {
|
|
334
|
+
"isError": True,
|
|
335
|
+
"content": [{
|
|
336
|
+
"type": "text",
|
|
337
|
+
"text": (
|
|
338
|
+
f"⚠️ TokenSafe MCP tool '{tool_name}' could not complete ({clean_reason}). "
|
|
339
|
+
"Try an alternative approach instead of repeating this exact call: "
|
|
340
|
+
"narrow the target 'path'/'project_path' or 'depth', inspect a specific file with 'smart_read_file', "
|
|
341
|
+
"or fall back to standard 'read_file' / bounded 'run_command'."
|
|
342
|
+
)
|
|
343
|
+
}]
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
class _NoOpTracker:
|
|
348
|
+
"""Fallback metrics tracker if SQLite DB is temporarily unavailable or locked."""
|
|
349
|
+
db_path = ""
|
|
350
|
+
def record_event(self, *args, **kwargs):
|
|
351
|
+
return 0
|
|
352
|
+
def get_summary(self, *args, **kwargs):
|
|
353
|
+
return {}
|
|
354
|
+
def get_last_event(self, *args, **kwargs):
|
|
355
|
+
return None
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
class _SafeTrackerProxy:
|
|
359
|
+
"""Wraps MetricsTracker so transient SQLite errors never interrupt MCP tool output."""
|
|
360
|
+
def __init__(self, inner):
|
|
361
|
+
self._inner = inner
|
|
362
|
+
self.db_path = getattr(inner, "db_path", "")
|
|
363
|
+
|
|
364
|
+
def record_event(self, *args, **kwargs):
|
|
365
|
+
try:
|
|
366
|
+
return self._inner.record_event(*args, **kwargs)
|
|
367
|
+
except Exception:
|
|
368
|
+
return 0
|
|
369
|
+
|
|
370
|
+
def __getattr__(self, name):
|
|
371
|
+
return getattr(self._inner, name)
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def _get_safe_tracker():
|
|
375
|
+
try:
|
|
376
|
+
return _SafeTrackerProxy(MetricsTracker())
|
|
377
|
+
except Exception:
|
|
378
|
+
return _NoOpTracker()
|
|
379
|
+
|
|
380
|
+
|
|
325
381
|
def handle_tool_call(name: str, args: dict) -> dict:
|
|
326
|
-
|
|
382
|
+
if args is None or not isinstance(args, dict):
|
|
383
|
+
args = {}
|
|
384
|
+
try:
|
|
385
|
+
return _dispatch_tool_call(name, args)
|
|
386
|
+
except Exception as e:
|
|
387
|
+
return _fallback_error(name, f"{type(e).__name__}: {str(e)}")
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
391
|
+
tracker = _get_safe_tracker()
|
|
327
392
|
|
|
328
393
|
if name == "smart_read_file":
|
|
329
394
|
path = args.get("path", "")
|
|
@@ -333,6 +398,11 @@ def handle_tool_call(name: str, args: dict) -> dict:
|
|
|
333
398
|
|
|
334
399
|
if not path or not os.path.exists(path):
|
|
335
400
|
return {"isError": True, "content": [{"type": "text", "text": f"File not found: {path}"}]}
|
|
401
|
+
try:
|
|
402
|
+
if not stat.S_ISREG(os.stat(path).st_mode):
|
|
403
|
+
return _fallback_error("smart_read_file", f"path is not a regular file: {path}")
|
|
404
|
+
except OSError as e:
|
|
405
|
+
return _fallback_error("smart_read_file", f"cannot stat path: {e}")
|
|
336
406
|
|
|
337
407
|
# Check Subagent Firewall dedup cache
|
|
338
408
|
is_hit, cached_text, saved_dedup = AgentFirewall.check_cache("mcp_session", path, symbol=symbol or "", tracker=tracker)
|
|
@@ -572,9 +642,9 @@ def handle_tool_call(name: str, args: dict) -> dict:
|
|
|
572
642
|
return {"content": [{"type": "text", "text": surface_md}]}
|
|
573
643
|
|
|
574
644
|
elif name == "list_dir":
|
|
575
|
-
path = args.get("path"
|
|
645
|
+
path = args.get("path") or args.get("project_path") or args.get("directory") or args.get("root_dir") or ""
|
|
576
646
|
if not path:
|
|
577
|
-
return
|
|
647
|
+
return _fallback_error("list_dir", "missing required 'path' argument")
|
|
578
648
|
|
|
579
649
|
# Resolve path relative to current working directory or absolute
|
|
580
650
|
abs_path = os.path.abspath(path)
|
|
@@ -601,7 +671,7 @@ def handle_tool_call(name: str, args: dict) -> dict:
|
|
|
601
671
|
elif name == "scoped_search":
|
|
602
672
|
query = args.get("query", "")
|
|
603
673
|
if not query:
|
|
604
|
-
return
|
|
674
|
+
return _fallback_error("scoped_search", "missing required 'query' argument")
|
|
605
675
|
|
|
606
676
|
scope = args.get("scope", "all")
|
|
607
677
|
raw_path = args.get("project_path") or args.get("path") or args.get("root_dir") or args.get("directory")
|
|
@@ -612,10 +682,7 @@ def handle_tool_call(name: str, args: dict) -> dict:
|
|
|
612
682
|
else:
|
|
613
683
|
resolved_path, err = _resolve_project_root(args)
|
|
614
684
|
if err or not resolved_path:
|
|
615
|
-
return
|
|
616
|
-
"isError": True,
|
|
617
|
-
"content": [{"type": "text", "text": err or "Error: Invalid or unspecified project_path."}]
|
|
618
|
-
}
|
|
685
|
+
return _fallback_error("scoped_search", err or "unspecified project_path")
|
|
619
686
|
target_path = resolved_path
|
|
620
687
|
|
|
621
688
|
max_res = args.get("max_results", 25)
|
|
@@ -632,7 +699,7 @@ def handle_tool_call(name: str, args: dict) -> dict:
|
|
|
632
699
|
)
|
|
633
700
|
md_text = res["markdown"]
|
|
634
701
|
if not res.get("success", True):
|
|
635
|
-
return
|
|
702
|
+
return _fallback_error("scoped_search", md_text)
|
|
636
703
|
|
|
637
704
|
res_tokens = count_tokens(md_text)
|
|
638
705
|
est_orig = max(1500, res_tokens * 8)
|
|
@@ -645,12 +712,39 @@ def handle_tool_call(name: str, args: dict) -> dict:
|
|
|
645
712
|
)
|
|
646
713
|
return {"content": [{"type": "text", "text": md_text}]}
|
|
647
714
|
|
|
648
|
-
return
|
|
715
|
+
return _fallback_error(name, f"unknown tool '{name}'")
|
|
716
|
+
|
|
717
|
+
|
|
718
|
+
def _execute_with_timeout(tool_name: str, tool_args: dict, timeout: float = MCP_TOOL_TIMEOUT) -> dict:
|
|
719
|
+
"""Runs handle_tool_call inside a daemon thread with hard timeout so stdio MCP never freezes."""
|
|
720
|
+
box = {"result": None, "error": None}
|
|
721
|
+
|
|
722
|
+
def _runner():
|
|
723
|
+
try:
|
|
724
|
+
box["result"] = handle_tool_call(tool_name, tool_args)
|
|
725
|
+
except Exception as exc:
|
|
726
|
+
box["error"] = f"{type(exc).__name__}: {str(exc)}"
|
|
727
|
+
|
|
728
|
+
worker = threading.Thread(target=_runner, daemon=True)
|
|
729
|
+
worker.start()
|
|
730
|
+
worker.join(timeout=timeout)
|
|
731
|
+
|
|
732
|
+
if worker.is_alive():
|
|
733
|
+
return _fallback_error(tool_name, f"execution exceeded {timeout:.1f}s timeout")
|
|
734
|
+
if box["error"] is not None:
|
|
735
|
+
return _fallback_error(tool_name, box["error"])
|
|
736
|
+
if box["result"] is None:
|
|
737
|
+
return _fallback_error(tool_name, "empty result returned")
|
|
738
|
+
return box["result"]
|
|
739
|
+
|
|
649
740
|
|
|
650
741
|
def run_mcp_server():
|
|
651
|
-
"""Runs stdio JSON-RPC 2.0 loop."""
|
|
742
|
+
"""Runs stdio JSON-RPC 2.0 loop with per-call timeout & resilient error recovery."""
|
|
652
743
|
while True:
|
|
653
|
-
|
|
744
|
+
try:
|
|
745
|
+
line = sys.stdin.readline()
|
|
746
|
+
except Exception:
|
|
747
|
+
break
|
|
654
748
|
if not line:
|
|
655
749
|
break
|
|
656
750
|
line = line.strip()
|
|
@@ -666,6 +760,10 @@ def run_mcp_server():
|
|
|
666
760
|
method = req.get("method")
|
|
667
761
|
params = req.get("params", {})
|
|
668
762
|
|
|
763
|
+
# Notifications (no id, or notifications/*) must never receive JSON-RPC responses
|
|
764
|
+
if msg_id is None or (isinstance(method, str) and method.startswith("notifications/")):
|
|
765
|
+
continue
|
|
766
|
+
|
|
669
767
|
response = {"jsonrpc": "2.0", "id": msg_id}
|
|
670
768
|
|
|
671
769
|
if method == "initialize":
|
|
@@ -679,21 +777,15 @@ def run_mcp_server():
|
|
|
679
777
|
"capabilities": {"tools": {}},
|
|
680
778
|
"serverInfo": SERVER_INFO
|
|
681
779
|
}
|
|
682
|
-
elif method == "notifications/initialized":
|
|
683
|
-
continue
|
|
684
780
|
elif method == "tools/list":
|
|
685
781
|
response["result"] = {"tools": TOOLS}
|
|
686
782
|
elif method == "tools/call":
|
|
687
783
|
tool_name = params.get("name", "")
|
|
688
784
|
tool_args = params.get("arguments", {})
|
|
689
785
|
try:
|
|
690
|
-
result =
|
|
691
|
-
response["result"] = result
|
|
786
|
+
response["result"] = _execute_with_timeout(tool_name, tool_args)
|
|
692
787
|
except Exception as e:
|
|
693
|
-
response["result"] = {
|
|
694
|
-
"isError": True,
|
|
695
|
-
"content": [{"type": "text", "text": f"Error: {str(e)}\n{traceback.format_exc()}"}]
|
|
696
|
-
}
|
|
788
|
+
response["result"] = _fallback_error(tool_name, f"{type(e).__name__}: {str(e)}")
|
|
697
789
|
finally:
|
|
698
790
|
try:
|
|
699
791
|
from src.telemetry_sync import TelemetrySync
|
|
@@ -703,8 +795,11 @@ def run_mcp_server():
|
|
|
703
795
|
else:
|
|
704
796
|
response["error"] = {"code": -32601, "message": f"Method not found: {method}"}
|
|
705
797
|
|
|
706
|
-
|
|
707
|
-
|
|
798
|
+
try:
|
|
799
|
+
sys.stdout.write(json.dumps(response) + "\n")
|
|
800
|
+
sys.stdout.flush()
|
|
801
|
+
except Exception:
|
|
802
|
+
break
|
|
708
803
|
|
|
709
804
|
def main():
|
|
710
805
|
run_mcp_server()
|
package/src/metrics.py
CHANGED
|
@@ -7,11 +7,14 @@ Uses SQLite for persistent, fast, zero-dependency storage.
|
|
|
7
7
|
import os
|
|
8
8
|
import json
|
|
9
9
|
import sqlite3
|
|
10
|
+
import threading
|
|
10
11
|
from contextlib import contextmanager
|
|
11
12
|
from datetime import datetime, timedelta
|
|
12
13
|
from typing import Dict, List, Optional, Any, Generator
|
|
13
14
|
|
|
14
15
|
USD_PER_TOKEN = 1.50 / 1_000_000.0
|
|
16
|
+
_METRICS_INIT_LOCK = threading.Lock()
|
|
17
|
+
_INITIALIZED_METRICS_DBS: set = set()
|
|
15
18
|
|
|
16
19
|
|
|
17
20
|
class MetricsTracker:
|
|
@@ -26,7 +29,7 @@ class MetricsTracker:
|
|
|
26
29
|
os.makedirs(data_dir, exist_ok=True)
|
|
27
30
|
db_path = os.environ.get("TOKENSAFE_DB_PATH", os.path.join(data_dir, "metrics.db"))
|
|
28
31
|
|
|
29
|
-
self.db_path = db_path
|
|
32
|
+
self.db_path = os.path.abspath(db_path)
|
|
30
33
|
self.retention_days = int(os.environ.get("TOKENSAFE_RETENTION_DAYS", "30"))
|
|
31
34
|
self.max_events = int(os.environ.get("TOKENSAFE_MAX_EVENTS", "5000"))
|
|
32
35
|
self._event_counter = 0
|
|
@@ -34,8 +37,12 @@ class MetricsTracker:
|
|
|
34
37
|
|
|
35
38
|
@contextmanager
|
|
36
39
|
def _get_connection(self) -> Generator[sqlite3.Connection, None, None]:
|
|
37
|
-
conn = sqlite3.connect(self.db_path)
|
|
40
|
+
conn = sqlite3.connect(self.db_path, timeout=5.0)
|
|
38
41
|
conn.row_factory = sqlite3.Row
|
|
42
|
+
try:
|
|
43
|
+
conn.execute("PRAGMA busy_timeout=3000;")
|
|
44
|
+
except sqlite3.Error:
|
|
45
|
+
pass
|
|
39
46
|
try:
|
|
40
47
|
yield conn
|
|
41
48
|
conn.commit()
|
|
@@ -43,52 +50,60 @@ class MetricsTracker:
|
|
|
43
50
|
conn.close()
|
|
44
51
|
|
|
45
52
|
def _init_db(self):
|
|
46
|
-
with
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
53
|
+
with _METRICS_INIT_LOCK:
|
|
54
|
+
if self.db_path in _INITIALIZED_METRICS_DBS and os.path.exists(self.db_path) and os.path.getsize(self.db_path) > 0:
|
|
55
|
+
return
|
|
56
|
+
with self._get_connection() as conn:
|
|
57
|
+
cursor = conn.cursor()
|
|
58
|
+
try:
|
|
59
|
+
cursor.execute("PRAGMA journal_mode=WAL;")
|
|
60
|
+
except sqlite3.Error:
|
|
61
|
+
pass
|
|
62
|
+
cursor.execute("""
|
|
63
|
+
CREATE TABLE IF NOT EXISTS sessions (
|
|
64
|
+
session_id TEXT PRIMARY KEY,
|
|
65
|
+
created_at TEXT NOT NULL,
|
|
66
|
+
last_updated TEXT NOT NULL,
|
|
67
|
+
total_original_tokens INTEGER DEFAULT 0,
|
|
68
|
+
total_optimized_tokens INTEGER DEFAULT 0,
|
|
69
|
+
total_saved_tokens INTEGER DEFAULT 0,
|
|
70
|
+
total_usd_saved REAL DEFAULT 0.0
|
|
71
|
+
)
|
|
72
|
+
""")
|
|
73
|
+
cursor.execute("""
|
|
74
|
+
CREATE TABLE IF NOT EXISTS events (
|
|
75
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
76
|
+
session_id TEXT NOT NULL,
|
|
77
|
+
timestamp TEXT NOT NULL,
|
|
78
|
+
event_type TEXT NOT NULL,
|
|
79
|
+
original_tokens INTEGER NOT NULL,
|
|
80
|
+
optimized_tokens INTEGER NOT NULL,
|
|
81
|
+
saved_tokens INTEGER NOT NULL,
|
|
82
|
+
reduction_pct REAL NOT NULL,
|
|
83
|
+
est_usd_saved REAL NOT NULL,
|
|
84
|
+
details TEXT
|
|
85
|
+
)
|
|
86
|
+
""")
|
|
87
|
+
cursor.execute("""
|
|
88
|
+
CREATE TABLE IF NOT EXISTS lifetime_aggregates (
|
|
89
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
90
|
+
total_events INTEGER DEFAULT 0,
|
|
91
|
+
total_original_tokens INTEGER DEFAULT 0,
|
|
92
|
+
total_optimized_tokens INTEGER DEFAULT 0,
|
|
93
|
+
total_saved_tokens INTEGER DEFAULT 0,
|
|
94
|
+
total_usd_saved REAL DEFAULT 0.0,
|
|
95
|
+
breakdown TEXT DEFAULT '{}'
|
|
96
|
+
)
|
|
97
|
+
""")
|
|
98
|
+
cursor.execute("""
|
|
99
|
+
INSERT OR IGNORE INTO lifetime_aggregates (
|
|
100
|
+
id, total_events, total_original_tokens, total_optimized_tokens,
|
|
101
|
+
total_saved_tokens, total_usd_saved, breakdown
|
|
102
|
+
) VALUES (1, 0, 0, 0, 0, 0.0, '{}')
|
|
103
|
+
""")
|
|
104
|
+
cursor.execute("CREATE INDEX IF NOT EXISTS idx_events_timestamp ON events(timestamp)")
|
|
105
|
+
cursor.execute("CREATE INDEX IF NOT EXISTS idx_events_session_id ON events(session_id)")
|
|
106
|
+
_INITIALIZED_METRICS_DBS.add(self.db_path)
|
|
92
107
|
|
|
93
108
|
def record_event(
|
|
94
109
|
self,
|
package/src/scoped_search.py
CHANGED
|
@@ -5,6 +5,7 @@ Replaces uncontrolled grep/find commands with bounded, clean, token-efficient re
|
|
|
5
5
|
"""
|
|
6
6
|
import os
|
|
7
7
|
import re
|
|
8
|
+
import stat
|
|
8
9
|
import fnmatch
|
|
9
10
|
import time
|
|
10
11
|
from typing import Dict, List, Optional, Any, Tuple
|
|
@@ -165,9 +166,10 @@ class ScopedSearch:
|
|
|
165
166
|
if not cls.is_match_file(fname, rel_path, scope):
|
|
166
167
|
continue
|
|
167
168
|
|
|
168
|
-
# Skip files larger than 1MB
|
|
169
|
+
# Skip non-regular files (FIFOs/pipes/devices) and files larger than 1MB
|
|
169
170
|
try:
|
|
170
|
-
|
|
171
|
+
st = os.stat(full_path)
|
|
172
|
+
if not stat.S_ISREG(st.st_mode) or st.st_size > 1024 * 1024:
|
|
171
173
|
continue
|
|
172
174
|
except OSError:
|
|
173
175
|
continue
|
package/src/telemetry_sync.py
CHANGED
|
@@ -115,8 +115,8 @@ class TelemetrySync:
|
|
|
115
115
|
license_key: Optional[str] = None,
|
|
116
116
|
email: Optional[str] = None,
|
|
117
117
|
force: bool = False,
|
|
118
|
-
batch_size: int =
|
|
119
|
-
timeout: float =
|
|
118
|
+
batch_size: int = 200,
|
|
119
|
+
timeout: float = 10.0,
|
|
120
120
|
verbose: bool = False
|
|
121
121
|
) -> Dict[str, Any]:
|
|
122
122
|
"""
|
|
@@ -192,14 +192,13 @@ class TelemetrySync:
|
|
|
192
192
|
"message": "All metrics are already up to date."
|
|
193
193
|
}
|
|
194
194
|
|
|
195
|
-
|
|
196
|
-
|
|
195
|
+
formatted_items: List[Tuple[Optional[int], Dict[str, Any]]] = [
|
|
196
|
+
(None, ev) for ev in synthetic_events
|
|
197
|
+
]
|
|
198
|
+
current_last_id = last_id
|
|
197
199
|
|
|
198
200
|
for r in rows:
|
|
199
|
-
ev_id = r["id"]
|
|
200
|
-
if ev_id > max_id:
|
|
201
|
-
max_id = ev_id
|
|
202
|
-
|
|
201
|
+
ev_id = int(r["id"])
|
|
203
202
|
raw_ts = r["timestamp"]
|
|
204
203
|
ts_int = int(time.time())
|
|
205
204
|
if isinstance(raw_ts, (int, float)):
|
|
@@ -224,25 +223,43 @@ class TelemetrySync:
|
|
|
224
223
|
except Exception:
|
|
225
224
|
pass
|
|
226
225
|
|
|
227
|
-
|
|
226
|
+
formatted_items.append((ev_id, {
|
|
228
227
|
"event_type": str(r["event_type"] or "PROMPT"),
|
|
229
228
|
"original_tokens": int(r["original_tokens"] or 0),
|
|
230
229
|
"saved_tokens": int(r["saved_tokens"] or 0),
|
|
231
230
|
"usd_saved": float(r["est_usd_saved"] or 0.0),
|
|
232
231
|
"model": model_name,
|
|
233
232
|
"timestamp": ts_int
|
|
234
|
-
})
|
|
233
|
+
}))
|
|
235
234
|
|
|
236
235
|
total_sent = 0
|
|
236
|
+
cumulative_synced = state.get("total_synced_events", 0)
|
|
237
|
+
rollup_synced = bool(state.get("lifetime_rollup_synced", False))
|
|
237
238
|
headers = {
|
|
238
239
|
"Content-Type": "application/json",
|
|
239
|
-
"User-Agent": "TokenSafe-Sync/1.4.
|
|
240
|
+
"User-Agent": "TokenSafe-Sync/1.4.13"
|
|
240
241
|
}
|
|
241
242
|
if active_key:
|
|
242
243
|
headers["Authorization"] = f"Bearer {active_key}"
|
|
243
244
|
|
|
244
|
-
|
|
245
|
-
|
|
245
|
+
def _record_failure(err_msg: str) -> Dict[str, Any]:
|
|
246
|
+
fail_state = {
|
|
247
|
+
"last_synced_event_id": current_last_id,
|
|
248
|
+
"last_synced_at": state.get("last_synced_at", 0) if total_sent == 0 else int(time.time()),
|
|
249
|
+
"last_attempt_at": int(time.time()),
|
|
250
|
+
"total_synced_events": cumulative_synced,
|
|
251
|
+
"lifetime_rollup_synced": rollup_synced
|
|
252
|
+
}
|
|
253
|
+
cls.save_state(fail_state)
|
|
254
|
+
return {
|
|
255
|
+
"success": False,
|
|
256
|
+
"synced_events": total_sent,
|
|
257
|
+
"error": err_msg
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
for i in range(0, len(formatted_items), batch_size):
|
|
261
|
+
batch_items = formatted_items[i:i + batch_size]
|
|
262
|
+
chunk = [item[1] for item in batch_items]
|
|
246
263
|
body_dict = {
|
|
247
264
|
"email": target_email,
|
|
248
265
|
"license_key": active_key,
|
|
@@ -255,37 +272,32 @@ class TelemetrySync:
|
|
|
255
272
|
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
256
273
|
if resp.status == 200:
|
|
257
274
|
total_sent += len(chunk)
|
|
275
|
+
cumulative_synced += len(chunk)
|
|
276
|
+
for ev_id, ev_payload in batch_items:
|
|
277
|
+
if ev_id is not None and ev_id > current_last_id:
|
|
278
|
+
current_last_id = ev_id
|
|
279
|
+
if ev_payload.get("event_type") == "ROLLUP_LIFETIME":
|
|
280
|
+
rollup_synced = True
|
|
281
|
+
if not synthetic_events:
|
|
282
|
+
rollup_synced = True
|
|
283
|
+
cls.save_state({
|
|
284
|
+
"last_synced_event_id": current_last_id,
|
|
285
|
+
"last_synced_at": int(time.time()),
|
|
286
|
+
"last_attempt_at": int(time.time()),
|
|
287
|
+
"total_synced_events": cumulative_synced,
|
|
288
|
+
"lifetime_rollup_synced": rollup_synced
|
|
289
|
+
})
|
|
258
290
|
else:
|
|
259
|
-
return {
|
|
260
|
-
"success": False,
|
|
261
|
-
"synced_events": total_sent,
|
|
262
|
-
"error": f"Server returned HTTP {resp.status}"
|
|
263
|
-
}
|
|
291
|
+
return _record_failure(f"Server returned HTTP {resp.status}")
|
|
264
292
|
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
|
-
}
|
|
293
|
+
return _record_failure(f"Cloud API error: {he.code} {he.reason}")
|
|
270
294
|
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)
|
|
295
|
+
return _record_failure(f"Network error during sync: {str(ex)}")
|
|
284
296
|
|
|
285
297
|
return {
|
|
286
298
|
"success": True,
|
|
287
299
|
"synced_events": total_sent,
|
|
288
|
-
"total_synced":
|
|
300
|
+
"total_synced": cumulative_synced,
|
|
289
301
|
"message": f"Successfully synchronized {total_sent:,} events to TokenSafe Cloud."
|
|
290
302
|
}
|
|
291
303
|
|
|
@@ -299,7 +311,7 @@ class TelemetrySync:
|
|
|
299
311
|
"""
|
|
300
312
|
now = time.time()
|
|
301
313
|
state = cls.get_state()
|
|
302
|
-
last_synced = state.get("last_synced_at", 0)
|
|
314
|
+
last_synced = max(state.get("last_synced_at", 0), state.get("last_attempt_at", 0))
|
|
303
315
|
if not force and (now - last_synced) < throttle_seconds:
|
|
304
316
|
return
|
|
305
317
|
|
|
@@ -342,7 +354,7 @@ if __name__ == "__main__":
|
|
|
342
354
|
try:
|
|
343
355
|
with open(SYNC_LOCK_PATH, "w", encoding="utf-8") as f:
|
|
344
356
|
f.write(str(os.getpid()))
|
|
345
|
-
res = TelemetrySync.sync(timeout=
|
|
357
|
+
res = TelemetrySync.sync(timeout=10.0, verbose=not is_bg)
|
|
346
358
|
if not is_bg:
|
|
347
359
|
print(json.dumps(res, indent=2))
|
|
348
360
|
finally:
|
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 = "1.4.
|
|
19
|
+
CURRENT_VERSION = "1.4.13"
|
|
20
20
|
CACHE_TTL = 86400 # 24 hours
|
|
21
21
|
|
|
22
22
|
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|