tokensafe 1.4.10 → 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/skills/token-optimizer/SKILL.md +17 -2
- package/src/graph_engine.py +4 -0
- package/src/mcp_server.py +144 -21
- package/src/metrics.py +63 -48
- package/src/scoped_search.py +39 -4
- 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": {
|
|
@@ -49,7 +49,8 @@ All tools are exposed via Model Context Protocol (stdio JSON-RPC 2.0).
|
|
|
49
49
|
| MCP Tool | Description | Efficiency Impact |
|
|
50
50
|
|---|---|---|
|
|
51
51
|
| `tokensafe:smart_read_file` | Graph-guided AST reader with target `symbol` body retention and 1-hop dependency inlining. | **-85% to -92%** token reduction |
|
|
52
|
-
| `tokensafe:scoped_search` | Safe, token-bounded keyword, symbol, or config search across the codebase. | **-90% to -95%** vs raw grep/find |
|
|
52
|
+
| `tokensafe:scoped_search` | Safe, token-bounded keyword, symbol, or config search across the codebase (supports `path`, 4s safety timeout, system root protection). | **-90% to -95%** vs raw grep/find |
|
|
53
|
+
| `tokensafe:list_dir` | Token-efficient directory tree without lockfiles, timestamps, or ignored folders (node_modules, .git, dist, .env). Replaces `ls -la`. | **-90%** vs verbose `ls` |
|
|
53
54
|
| `tokensafe:get_architecture_graph` | Computes dependency topology, hub centrality, and identifies top God Nodes for `project_path`. | **~200 tokens** (replaces 50k crawl) |
|
|
54
55
|
| `tokensafe:get_api_surface` | Generates a compact markdown map of all exported types, interfaces, and classes. | **~500 tokens** for entire project |
|
|
55
56
|
| `tokensafe:sanitize_command` | Intercepts shell commands to strip lockfiles, cap unbounded git logs, and quiet test tracebacks. | Saves **10k-50k tokens** per run |
|
|
@@ -81,11 +82,25 @@ All tools are exposed via Model Context Protocol (stdio JSON-RPC 2.0).
|
|
|
81
82
|
"ToolName": "scoped_search",
|
|
82
83
|
"Arguments": {
|
|
83
84
|
"query": "HARDCODED_VERSION",
|
|
85
|
+
"path": "/Users/.../projects/my-app/src",
|
|
84
86
|
"scope": "code"
|
|
85
87
|
}
|
|
86
88
|
}
|
|
87
89
|
```
|
|
88
|
-
*Locates exact occurrences with file and line references in < 100 tokens
|
|
90
|
+
*Locates exact occurrences with file and line references in < 100 tokens. Always pass explicit `path` or `project_path` (auto-guarded against system roots with 4s safety timeout).*
|
|
91
|
+
|
|
92
|
+
### 2b. Directory Navigation Workflow (`list_dir`)
|
|
93
|
+
```json
|
|
94
|
+
{
|
|
95
|
+
"ServerName": "tokensafe",
|
|
96
|
+
"ToolName": "list_dir",
|
|
97
|
+
"Arguments": {
|
|
98
|
+
"path": "/Users/.../projects/my-app/src",
|
|
99
|
+
"depth": 2
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
```
|
|
103
|
+
*Renders a clean directory tree without permissions, timestamps, lockfiles, or heavy directories (`node_modules`, `.git`, `dist`).*
|
|
89
104
|
|
|
90
105
|
### 3. Targeted Symbol Inspection Workflow
|
|
91
106
|
```json
|
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,7 +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
|
|
10
|
+
import time
|
|
9
11
|
import json
|
|
12
|
+
import threading
|
|
10
13
|
import traceback
|
|
11
14
|
import fnmatch
|
|
12
15
|
from typing import Tuple, Optional
|
|
@@ -32,7 +35,7 @@ from src.scoped_search import ScopedSearch
|
|
|
32
35
|
|
|
33
36
|
SERVER_INFO = {
|
|
34
37
|
"name": "tokensafe-mcp",
|
|
35
|
-
"version": "1.4.
|
|
38
|
+
"version": "1.4.13"
|
|
36
39
|
}
|
|
37
40
|
|
|
38
41
|
TOOLS = [
|
|
@@ -153,6 +156,10 @@ TOOLS = [
|
|
|
153
156
|
"enum": ["code", "config", "all"],
|
|
154
157
|
"description": "Scope of search: 'code' (source files only), 'config' (json, toml, yaml), or 'all' (default: 'all')"
|
|
155
158
|
},
|
|
159
|
+
"path": {
|
|
160
|
+
"type": "string",
|
|
161
|
+
"description": "Directory or project path to search (alias for project_path)"
|
|
162
|
+
},
|
|
156
163
|
"project_path": {
|
|
157
164
|
"type": "string",
|
|
158
165
|
"description": "Optional root directory path (defaults to current project)"
|
|
@@ -191,7 +198,8 @@ def build_dir_tree(dir_path: str, max_depth: int = 2, max_entries: int = 80) ->
|
|
|
191
198
|
IGNORE_DIRS = {
|
|
192
199
|
'node_modules', '.git', 'dist', 'build', '.next', 'coverage',
|
|
193
200
|
'__pycache__', '.turbo', '.vite', '.output', '.bunny', 'data',
|
|
194
|
-
'.venv', 'venv', '.cache', '.idea', '.vscode'
|
|
201
|
+
'.venv', 'venv', '.cache', '.idea', '.vscode',
|
|
202
|
+
'Library', 'Applications', 'Movies', 'Music', 'Pictures'
|
|
195
203
|
}
|
|
196
204
|
IGNORE_FILES = {
|
|
197
205
|
'*.lock', '*.lockb', '*.map', '.DS_Store', 'Thumbs.db', 'package-lock.json',
|
|
@@ -209,11 +217,14 @@ def build_dir_tree(dir_path: str, max_depth: int = 2, max_entries: int = 80) ->
|
|
|
209
217
|
base_name = os.path.basename(os.path.abspath(dir_path)) or dir_path
|
|
210
218
|
lines = [f"📁 **{base_name}/** (max depth: {max_depth})"]
|
|
211
219
|
entries_count = 0
|
|
220
|
+
start_time = time.monotonic()
|
|
212
221
|
|
|
213
222
|
def _traverse(curr_dir: str, prefix: str, current_depth: int):
|
|
214
223
|
nonlocal entries_count
|
|
215
224
|
if current_depth > max_depth or entries_count >= max_entries:
|
|
216
225
|
return
|
|
226
|
+
if time.monotonic() - start_time > 3.0:
|
|
227
|
+
return
|
|
217
228
|
|
|
218
229
|
try:
|
|
219
230
|
items = sorted(os.listdir(curr_dir))
|
|
@@ -313,8 +324,71 @@ def _resolve_project_root(args: dict) -> Tuple[Optional[str], Optional[str]]:
|
|
|
313
324
|
|
|
314
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')."
|
|
315
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
|
+
|
|
316
381
|
def handle_tool_call(name: str, args: dict) -> dict:
|
|
317
|
-
|
|
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()
|
|
318
392
|
|
|
319
393
|
if name == "smart_read_file":
|
|
320
394
|
path = args.get("path", "")
|
|
@@ -324,6 +398,11 @@ def handle_tool_call(name: str, args: dict) -> dict:
|
|
|
324
398
|
|
|
325
399
|
if not path or not os.path.exists(path):
|
|
326
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}")
|
|
327
406
|
|
|
328
407
|
# Check Subagent Firewall dedup cache
|
|
329
408
|
is_hit, cached_text, saved_dedup = AgentFirewall.check_cache("mcp_session", path, symbol=symbol or "", tracker=tracker)
|
|
@@ -563,13 +642,17 @@ def handle_tool_call(name: str, args: dict) -> dict:
|
|
|
563
642
|
return {"content": [{"type": "text", "text": surface_md}]}
|
|
564
643
|
|
|
565
644
|
elif name == "list_dir":
|
|
566
|
-
path = args.get("path"
|
|
645
|
+
path = args.get("path") or args.get("project_path") or args.get("directory") or args.get("root_dir") or ""
|
|
567
646
|
if not path:
|
|
568
|
-
return
|
|
647
|
+
return _fallback_error("list_dir", "missing required 'path' argument")
|
|
569
648
|
|
|
570
649
|
# Resolve path relative to current working directory or absolute
|
|
571
650
|
abs_path = os.path.abspath(path)
|
|
651
|
+
system_roots = {"/", "/Users", "/home", "/root", os.path.expanduser("~")}
|
|
572
652
|
depth = min(4, max(1, int(args.get("depth", 2))))
|
|
653
|
+
if abs_path in system_roots:
|
|
654
|
+
# Do not walk entire home dir or filesystem root deeply
|
|
655
|
+
depth = 1
|
|
573
656
|
max_entries = min(150, max(10, int(args.get("max_entries", 80))))
|
|
574
657
|
|
|
575
658
|
tree_output = build_dir_tree(abs_path, max_depth=depth, max_entries=max_entries)
|
|
@@ -588,11 +671,20 @@ def handle_tool_call(name: str, args: dict) -> dict:
|
|
|
588
671
|
elif name == "scoped_search":
|
|
589
672
|
query = args.get("query", "")
|
|
590
673
|
if not query:
|
|
591
|
-
return
|
|
674
|
+
return _fallback_error("scoped_search", "missing required 'query' argument")
|
|
592
675
|
|
|
593
676
|
scope = args.get("scope", "all")
|
|
594
|
-
|
|
595
|
-
|
|
677
|
+
raw_path = args.get("project_path") or args.get("path") or args.get("root_dir") or args.get("directory")
|
|
678
|
+
if raw_path:
|
|
679
|
+
target_path = os.path.abspath(raw_path)
|
|
680
|
+
if os.path.isfile(target_path):
|
|
681
|
+
target_path = os.path.dirname(target_path)
|
|
682
|
+
else:
|
|
683
|
+
resolved_path, err = _resolve_project_root(args)
|
|
684
|
+
if err or not resolved_path:
|
|
685
|
+
return _fallback_error("scoped_search", err or "unspecified project_path")
|
|
686
|
+
target_path = resolved_path
|
|
687
|
+
|
|
596
688
|
max_res = args.get("max_results", 25)
|
|
597
689
|
c_sens = bool(args.get("case_sensitive", False))
|
|
598
690
|
u_regex = bool(args.get("use_regex", False))
|
|
@@ -606,6 +698,9 @@ def handle_tool_call(name: str, args: dict) -> dict:
|
|
|
606
698
|
use_regex=u_regex
|
|
607
699
|
)
|
|
608
700
|
md_text = res["markdown"]
|
|
701
|
+
if not res.get("success", True):
|
|
702
|
+
return _fallback_error("scoped_search", md_text)
|
|
703
|
+
|
|
609
704
|
res_tokens = count_tokens(md_text)
|
|
610
705
|
est_orig = max(1500, res_tokens * 8)
|
|
611
706
|
tracker.record_event(
|
|
@@ -617,12 +712,39 @@ def handle_tool_call(name: str, args: dict) -> dict:
|
|
|
617
712
|
)
|
|
618
713
|
return {"content": [{"type": "text", "text": md_text}]}
|
|
619
714
|
|
|
620
|
-
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
|
+
|
|
621
740
|
|
|
622
741
|
def run_mcp_server():
|
|
623
|
-
"""Runs stdio JSON-RPC 2.0 loop."""
|
|
742
|
+
"""Runs stdio JSON-RPC 2.0 loop with per-call timeout & resilient error recovery."""
|
|
624
743
|
while True:
|
|
625
|
-
|
|
744
|
+
try:
|
|
745
|
+
line = sys.stdin.readline()
|
|
746
|
+
except Exception:
|
|
747
|
+
break
|
|
626
748
|
if not line:
|
|
627
749
|
break
|
|
628
750
|
line = line.strip()
|
|
@@ -638,6 +760,10 @@ def run_mcp_server():
|
|
|
638
760
|
method = req.get("method")
|
|
639
761
|
params = req.get("params", {})
|
|
640
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
|
+
|
|
641
767
|
response = {"jsonrpc": "2.0", "id": msg_id}
|
|
642
768
|
|
|
643
769
|
if method == "initialize":
|
|
@@ -651,21 +777,15 @@ def run_mcp_server():
|
|
|
651
777
|
"capabilities": {"tools": {}},
|
|
652
778
|
"serverInfo": SERVER_INFO
|
|
653
779
|
}
|
|
654
|
-
elif method == "notifications/initialized":
|
|
655
|
-
continue
|
|
656
780
|
elif method == "tools/list":
|
|
657
781
|
response["result"] = {"tools": TOOLS}
|
|
658
782
|
elif method == "tools/call":
|
|
659
783
|
tool_name = params.get("name", "")
|
|
660
784
|
tool_args = params.get("arguments", {})
|
|
661
785
|
try:
|
|
662
|
-
result =
|
|
663
|
-
response["result"] = result
|
|
786
|
+
response["result"] = _execute_with_timeout(tool_name, tool_args)
|
|
664
787
|
except Exception as e:
|
|
665
|
-
response["result"] = {
|
|
666
|
-
"isError": True,
|
|
667
|
-
"content": [{"type": "text", "text": f"Error: {str(e)}\n{traceback.format_exc()}"}]
|
|
668
|
-
}
|
|
788
|
+
response["result"] = _fallback_error(tool_name, f"{type(e).__name__}: {str(e)}")
|
|
669
789
|
finally:
|
|
670
790
|
try:
|
|
671
791
|
from src.telemetry_sync import TelemetrySync
|
|
@@ -675,8 +795,11 @@ def run_mcp_server():
|
|
|
675
795
|
else:
|
|
676
796
|
response["error"] = {"code": -32601, "message": f"Method not found: {method}"}
|
|
677
797
|
|
|
678
|
-
|
|
679
|
-
|
|
798
|
+
try:
|
|
799
|
+
sys.stdout.write(json.dumps(response) + "\n")
|
|
800
|
+
sys.stdout.flush()
|
|
801
|
+
except Exception:
|
|
802
|
+
break
|
|
680
803
|
|
|
681
804
|
def main():
|
|
682
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,13 +5,17 @@ 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
|
|
10
|
+
import time
|
|
9
11
|
from typing import Dict, List, Optional, Any, Tuple
|
|
10
12
|
|
|
11
13
|
IGNORED_DIRS = {
|
|
12
|
-
".git", "node_modules", ".venv", "venv", "__pycache__", "dist", "build",
|
|
14
|
+
".git", ".hg", ".svn", "node_modules", ".venv", "venv", "__pycache__", "dist", "build",
|
|
13
15
|
".next", ".turbo", ".idea", ".vscode", "coverage", ".pytest_cache",
|
|
14
|
-
".mypy_cache", ".gemini", ".system_generated", "data", "tokensafe.egg-info"
|
|
16
|
+
".mypy_cache", ".gemini", ".system_generated", "data", "tokensafe.egg-info",
|
|
17
|
+
"Library", "Applications", "Pictures", "Movies", "Music", "Downloads",
|
|
18
|
+
".cache", ".npm", ".bun", ".rustup", ".cargo", ".local", ".output", ".vite"
|
|
15
19
|
}
|
|
16
20
|
|
|
17
21
|
IGNORED_EXTENSIONS = {
|
|
@@ -90,6 +94,16 @@ class ScopedSearch:
|
|
|
90
94
|
}
|
|
91
95
|
|
|
92
96
|
root_dir = os.path.abspath(project_path or os.getcwd())
|
|
97
|
+
system_roots = {"/", "/Users", "/home", "/root", os.path.expanduser("~")}
|
|
98
|
+
if root_dir in system_roots:
|
|
99
|
+
return {
|
|
100
|
+
"success": False,
|
|
101
|
+
"error": f"Refusing to search system root or home directory ({root_dir}). Please provide an explicit project directory.",
|
|
102
|
+
"matches": [],
|
|
103
|
+
"total_matches": 0,
|
|
104
|
+
"markdown": f"Search aborted: '{root_dir}' is a system root. Please specify an explicit project directory path."
|
|
105
|
+
}
|
|
106
|
+
|
|
93
107
|
if not os.path.isdir(root_dir):
|
|
94
108
|
return {
|
|
95
109
|
"success": False,
|
|
@@ -122,8 +136,18 @@ class ScopedSearch:
|
|
|
122
136
|
matches: List[Dict[str, Any]] = []
|
|
123
137
|
total_scanned_files = 0
|
|
124
138
|
hit_files = set()
|
|
139
|
+
start_time = time.monotonic()
|
|
140
|
+
timeout_seconds = 4.0
|
|
141
|
+
max_scanned_files = 2500
|
|
142
|
+
timed_out = False
|
|
125
143
|
|
|
126
144
|
for dirpath, dirnames, filenames in os.walk(root_dir):
|
|
145
|
+
if time.monotonic() - start_time > timeout_seconds:
|
|
146
|
+
timed_out = True
|
|
147
|
+
break
|
|
148
|
+
if total_scanned_files >= max_scanned_files:
|
|
149
|
+
break
|
|
150
|
+
|
|
127
151
|
# Prune ignored directories in-place
|
|
128
152
|
dirnames[:] = [
|
|
129
153
|
d for d in dirnames
|
|
@@ -131,15 +155,21 @@ class ScopedSearch:
|
|
|
131
155
|
]
|
|
132
156
|
|
|
133
157
|
for fname in filenames:
|
|
158
|
+
if time.monotonic() - start_time > timeout_seconds:
|
|
159
|
+
timed_out = True
|
|
160
|
+
break
|
|
161
|
+
if total_scanned_files >= max_scanned_files:
|
|
162
|
+
break
|
|
134
163
|
full_path = os.path.join(dirpath, fname)
|
|
135
164
|
rel_path = os.path.relpath(full_path, root_dir).replace("\\", "/")
|
|
136
165
|
|
|
137
166
|
if not cls.is_match_file(fname, rel_path, scope):
|
|
138
167
|
continue
|
|
139
168
|
|
|
140
|
-
# Skip files larger than 1MB
|
|
169
|
+
# Skip non-regular files (FIFOs/pipes/devices) and files larger than 1MB
|
|
141
170
|
try:
|
|
142
|
-
|
|
171
|
+
st = os.stat(full_path)
|
|
172
|
+
if not stat.S_ISREG(st.st_mode) or st.st_size > 1024 * 1024:
|
|
143
173
|
continue
|
|
144
174
|
except OSError:
|
|
145
175
|
continue
|
|
@@ -184,6 +214,10 @@ class ScopedSearch:
|
|
|
184
214
|
|
|
185
215
|
if len(matches) >= max_results:
|
|
186
216
|
lines.append(f"_Results capped at {max_results} matches._")
|
|
217
|
+
elif timed_out:
|
|
218
|
+
lines.append(f"_Search bounded at {timeout_seconds}s safety limit ({total_scanned_files} files scanned). Narrow 'project_path' for exhaustive scan._")
|
|
219
|
+
elif total_scanned_files >= max_scanned_files:
|
|
220
|
+
lines.append(f"_Scan bounded at {max_scanned_files} files limit. Narrow 'project_path' if needed._")
|
|
187
221
|
|
|
188
222
|
return {
|
|
189
223
|
"success": True,
|
|
@@ -192,6 +226,7 @@ class ScopedSearch:
|
|
|
192
226
|
"total_matches": len(matches),
|
|
193
227
|
"files_matched": len(hit_files),
|
|
194
228
|
"scanned_files": total_scanned_files,
|
|
229
|
+
"timed_out": timed_out,
|
|
195
230
|
"matches": matches,
|
|
196
231
|
"markdown": "\n".join(lines)
|
|
197
232
|
}
|
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__)))
|