tokensafe 1.1.1 → 1.3.0

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.
@@ -88,6 +88,10 @@ class CodeGraph:
88
88
  Fast incremental scan of the workspace.
89
89
  Parses modified files only; returns number of files re-indexed.
90
90
  """
91
+ system_roots = {"/", "/Users", "/home", "/root", os.path.expanduser("~")}
92
+ if self.root_dir in system_roots:
93
+ return 0
94
+
91
95
  reindexed = 0
92
96
  current_files = set()
93
97
 
package/src/installer.py CHANGED
@@ -15,8 +15,16 @@ import sys
15
15
  import json
16
16
  import shutil
17
17
  import re
18
+ import subprocess
18
19
  from typing import Dict, List, Any, Optional, Tuple
19
20
 
21
+ RESET = "\033[0m"
22
+ BOLD = "\033[1m"
23
+ GREEN = "\033[32m"
24
+ CYAN = "\033[36m"
25
+ YELLOW = "\033[33m"
26
+ RED = "\033[31m"
27
+
20
28
  HOME = os.path.expanduser("~")
21
29
  PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
22
30
  MCP_SERVER_PATH = os.path.join(PROJECT_ROOT, "src", "mcp_server.py")
@@ -57,6 +65,14 @@ AGENTS_REGISTRY = {
57
65
  "config_path": os.path.join(HOME, "Library", "Application Support", "Code", "User", "globalStorage", "saoudrizwan.claude-dev", "settings", "cline_mcp_settings.json"),
58
66
  "detect_path": os.path.join(HOME, "Library", "Application Support", "Code")
59
67
  },
68
+ "claude_code": {
69
+ "name": "Claude Code CLI",
70
+ "type": "claude_md",
71
+ "config_path": os.path.join(HOME, ".claude.json"),
72
+ "agents_md_path": os.path.join(HOME, ".claude", "CLAUDE.md"),
73
+ "skills_path": os.path.join(HOME, ".claude", "skills", "token-optimizer"),
74
+ "detect_path": os.path.join(HOME, ".claude")
75
+ },
60
76
  "codex": {
61
77
  "name": "OpenAI Codex",
62
78
  "type": "codex_toml",
@@ -66,12 +82,19 @@ AGENTS_REGISTRY = {
66
82
  "plugin_path": os.path.join(HOME, ".codex", "plugins", "tokensafe"),
67
83
  "detect_path": os.path.join(HOME, ".codex")
68
84
  },
85
+ "copilot": {
86
+ "name": "GitHub Copilot",
87
+ "type": "copilot_json",
88
+ "config_path": os.path.join(HOME, ".copilot", "mcp-config.json"),
89
+ "detect_path": os.path.join(HOME, ".copilot")
90
+ },
69
91
  "zcode": {
70
92
  "name": "Z.ai Code",
71
93
  "type": "zcode_json",
72
94
  "config_path": os.path.join(HOME, ".zcode", "cli", "config.json"),
73
95
  "skills_path": os.path.join(HOME, ".zcode", "skills", "token-optimizer"),
74
96
  "plugin_path": os.path.join(HOME, ".zcode", "cli", "plugins", "tokensafe"),
97
+ "agents_md_path": os.path.join(HOME, ".zcode", "AGENTS.md"),
75
98
  "detect_path": os.path.join(HOME, ".zcode")
76
99
  }
77
100
  }
@@ -144,15 +167,16 @@ class AgentInstaller:
144
167
  if "rules_path" in info:
145
168
  rule_text = (
146
169
  "---\n"
147
- "description: TokenSafe token economy and context optimization protocol\n"
170
+ "description: TokenSafe token economy, graph-first navigation and context optimization protocol\n"
148
171
  "globs: *\n"
149
172
  "alwaysApply: true\n"
150
173
  "---\n\n"
151
- "# TokenSafe Optimization Protocol\n"
152
- "Always prioritize `tokensafe` MCP tools (`smart_read_file`, `compress_prompt`, `sanitize_command`) "
153
- "over default raw file reads or high-output terminal executions to preserve context tokens and prevent context overflow.\n"
154
- "- When inspecting code files, use `smart_read_file` with `symbol` or line range.\n"
155
- "- Sanitize verbose commands (`git diff`, `pytest`, `find`, `grep`) via `sanitize_command`.\n"
174
+ "# TokenSafe Graph-First Optimization Protocol\n"
175
+ "Always prioritize `tokensafe` MCP tools over default raw file reads or high-output terminal executions to prevent context window exhaustion.\n\n"
176
+ "1. **Architecture Discovery**: Always call `tokensafe:get_architecture_graph` before grep or multi-file reading. Returns project God Nodes and key dependency hubs in < 250 tokens without file crawling.\n"
177
+ "2. **Graph-Guided Symbol Inspection**: When inspecting code implementations, prioritize `tokensafe:smart_read_file` with the targeted `symbol`. Returns full executable bodies for the symbol and 1-hop dependencies while folding inert code into signatures (-85% to -92% tokens).\n"
178
+ "3. **No Unconstrained Shell Grep/Find**: Strictly avoid running raw recursive grep/find across projects. Use `get_architecture_graph` or `get_api_surface`.\n"
179
+ "4. **Command Sanitization**: Use `sanitize_command` on high-output terminal commands (`git diff`, `pytest`, `find`, `grep`) to prevent lockfile or test log context contamination.\n"
156
180
  )
157
181
  cls._write_file_safely(info["rules_path"], rule_text)
158
182
 
@@ -229,16 +253,74 @@ class AgentInstaller:
229
253
 
230
254
  if "agents_md_path" in info:
231
255
  codex_rule = (
232
- "## TOKENSAFE TOKEN OPTIMIZATION PROTOCOL\n"
233
- "Always prioritize `tokensafe` MCP tools (`smart_read_file`, `compress_prompt`, `sanitize_command`) "
234
- "over default raw file reads or high-token shell executions to preserve context tokens and prevent context overflow.\n"
235
- "- When inspecting code files, use `smart_read_file` with `symbol` or line range.\n"
236
- "- When running verbose commands (`git diff`, `pytest`, `find`, `grep`), sanitize them with `sanitize_command`.\n"
256
+ "## TOKENSAFE GRAPH-FIRST OPTIMIZATION PROTOCOL\n"
257
+ "Always prioritize `tokensafe` MCP tools over default raw file reads or high-output terminal executions to prevent context window exhaustion.\n"
258
+ "1. **Architecture Discovery**: Always call `tokensafe:get_architecture_graph` before grep or multi-file reading. Returns project God Nodes and key dependency hubs in < 250 tokens without file crawling.\n"
259
+ "2. **Graph-Guided Symbol Inspection**: When inspecting code implementations, prioritize `tokensafe:smart_read_file` with the targeted `symbol`. Returns full executable bodies for the symbol and 1-hop dependencies while folding inert code into signatures (-85% to -92% tokens).\n"
260
+ "3. **No Unconstrained Shell Grep/Find**: Strictly avoid running raw recursive grep/find across projects. Use `get_architecture_graph` or `get_api_surface`.\n"
261
+ "4. **Command Sanitization**: Use `sanitize_command` on high-output terminal commands (`git diff`, `pytest`, `find`, `grep`) to prevent lockfile or test log context contamination.\n"
237
262
  )
238
263
  cls._inject_global_rule(info["agents_md_path"], codex_rule)
239
264
 
240
265
  return True, f"Configured MCP, Plugin, Skill & AGENTS.md in {config_file}"
241
266
 
267
+ elif info["type"] == "claude_md":
268
+ if "config_path" in info:
269
+ config_file = info["config_path"]
270
+ data = {}
271
+ if os.path.exists(config_file):
272
+ try:
273
+ with open(config_file, "r", encoding="utf-8") as f:
274
+ data = json.load(f)
275
+ except Exception:
276
+ data = {}
277
+ if "mcpServers" not in data or not isinstance(data["mcpServers"], dict):
278
+ data["mcpServers"] = {}
279
+ data["mcpServers"]["tokensafe"] = {
280
+ "command": PYTHON_BIN,
281
+ "args": [MCP_SERVER_PATH]
282
+ }
283
+ with open(config_file, "w", encoding="utf-8") as f:
284
+ json.dump(data, f, indent=2)
285
+
286
+ if "agents_md_path" in info:
287
+ claude_rule = (
288
+ "## TOKENSAFE GRAPH-FIRST OPTIMIZATION PROTOCOL\n"
289
+ "Always prioritize `tokensafe` MCP tools over default raw file reads or recursive grep/find.\n"
290
+ "1. **Architecture Discovery**: Always call `tokensafe:get_architecture_graph` before grep or multi-file reading. Returns project God Nodes and key dependency hubs in < 250 tokens without file crawling.\n"
291
+ "2. **Graph-Guided Symbol Inspection**: When inspecting code implementations, prioritize `tokensafe:smart_read_file` with the targeted `symbol`. Returns full executable bodies for the symbol and 1-hop dependencies while folding inert code into signatures (-85% to -92% tokens).\n"
292
+ "3. **No Unconstrained Shell Grep/Find**: Strictly avoid running raw recursive grep/find across projects. Use `get_architecture_graph` or `get_api_surface`.\n"
293
+ "4. **Command Sanitization**: Use `sanitize_command` on high-output terminal commands (`git diff`, `pytest`, `find`, `grep`) to prevent lockfile or test log context contamination.\n"
294
+ )
295
+ cls._inject_global_rule(info["agents_md_path"], claude_rule)
296
+
297
+ if "skills_path" in info:
298
+ cls._symlink_skill(info["skills_path"])
299
+
300
+ return True, f"Configured MCP, Rule & Skill in {info.get('agents_md_path')}"
301
+
302
+ elif info["type"] == "copilot_json":
303
+ config_file = info["config_path"]
304
+ os.makedirs(os.path.dirname(config_file), exist_ok=True)
305
+ data = {}
306
+ if os.path.exists(config_file):
307
+ try:
308
+ with open(config_file, "r", encoding="utf-8") as f:
309
+ data = json.load(f)
310
+ except Exception:
311
+ data = {}
312
+ if "mcpServers" not in data or not isinstance(data["mcpServers"], dict):
313
+ data["mcpServers"] = {}
314
+ data["mcpServers"]["tokensafe"] = {
315
+ "type": "stdio",
316
+ "command": PYTHON_BIN,
317
+ "args": [MCP_SERVER_PATH],
318
+ "tools": ["*"]
319
+ }
320
+ with open(config_file, "w", encoding="utf-8") as f:
321
+ json.dump(data, f, indent=2)
322
+ return True, f"Configured MCP for GitHub Copilot in {config_file}"
323
+
242
324
  elif info["type"] == "zcode_json":
243
325
  config_file = info["config_path"]
244
326
  os.makedirs(os.path.dirname(config_file), exist_ok=True)
@@ -271,7 +353,18 @@ class AgentInstaller:
271
353
  if "plugin_path" in info:
272
354
  cls._symlink_dir(PROJECT_ROOT, info["plugin_path"])
273
355
 
274
- return True, f"Configured MCP, Plugin & Skill in {config_file}"
356
+ if "agents_md_path" in info:
357
+ zcode_rule = (
358
+ "## TOKENSAFE GRAPH-FIRST OPTIMIZATION PROTOCOL\n"
359
+ "Always prioritize `tokensafe` MCP tools over default raw file reads or high-output terminal executions to prevent context window exhaustion.\n"
360
+ "1. **Architecture Discovery**: Always call `tokensafe:get_architecture_graph` before grep or multi-file reading. Returns project God Nodes and key dependency hubs in < 250 tokens without file crawling.\n"
361
+ "2. **Graph-Guided Symbol Inspection**: When inspecting code implementations, prioritize `tokensafe:smart_read_file` with the targeted `symbol`. Returns full executable bodies for the symbol and 1-hop dependencies while folding inert code into signatures (-85% to -92% tokens).\n"
362
+ "3. **No Unconstrained Shell Grep/Find**: Strictly avoid running raw recursive grep/find across projects. Use `get_architecture_graph` or `get_api_surface`.\n"
363
+ "4. **Command Sanitization**: Use `sanitize_command` on high-output terminal commands (`git diff`, `pytest`, `find`, `grep`) to prevent lockfile or test log context contamination.\n"
364
+ )
365
+ cls._inject_global_rule(info["agents_md_path"], zcode_rule)
366
+
367
+ return True, f"Configured MCP, Plugin, Skill & AGENTS.md in {config_file}"
275
368
 
276
369
  return False, "Unsupported type"
277
370
 
@@ -377,8 +470,87 @@ class AgentInstaller:
377
470
  print(f"\n\033[32m\033[1m✅ TokenSafe successfully connected to {installed_count} agent(s)!\033[0m")
378
471
  print(" Restart your IDE / Agent to start saving tokens automatically.\n")
379
472
 
473
+ @classmethod
474
+ def self_update(cls):
475
+ """
476
+ One-click self update for TokenSafe:
477
+ 1. Detects package installation source (git, npm, pip).
478
+ 2. Upgrades TokenSafe engine to latest release.
479
+ 3. Re-synchronizes MCP configs and rules for all active agents.
480
+ 4. Refreshes local version cache.
481
+ """
482
+ print(f"\n{BOLD}{CYAN}╔════════════════════════════════════════════════════════════════════╗{RESET}")
483
+ print(f"{BOLD}{CYAN}║ ⚡ TOKENSAFE ONE-CLICK SELF-UPDATE ⚡ ║{RESET}")
484
+ print(f"{BOLD}{CYAN}╚════════════════════════════════════════════════════════════════════╝{RESET}\n")
485
+
486
+ # 1. Check if git clone installation (e.g. ~/.tokensafe)
487
+ is_git_clone = os.path.isdir(os.path.join(PROJECT_ROOT, ".git"))
488
+ if is_git_clone and PROJECT_ROOT.endswith((".tokensafe", "agy-token-optimizer")):
489
+ print(f" {CYAN}→{RESET} Detected local repository at {PROJECT_ROOT}. Pulling latest changes...")
490
+ try:
491
+ res = subprocess.run(["git", "pull", "--quiet"], cwd=PROJECT_ROOT, capture_output=True, text=True, timeout=10)
492
+ if res.returncode == 0:
493
+ print(f" {GREEN}✔{RESET} Git repository updated to latest commit.")
494
+ except Exception as e:
495
+ print(f" {YELLOW}⚠{RESET} Git pull skipped: {e}")
496
+
497
+ # 2. Check npm global
498
+ if shutil.which("npm"):
499
+ try:
500
+ res = subprocess.run(["npm", "list", "-g", "--depth=0", "tokensafe"], capture_output=True, text=True, timeout=5)
501
+ if "tokensafe@" in res.stdout:
502
+ print(f" {CYAN}→{RESET} Updating global npm package (npm install -g tokensafe@latest)...")
503
+ up_res = subprocess.run(["npm", "install", "-g", "tokensafe@latest"], capture_output=True, text=True, timeout=30)
504
+ if up_res.returncode == 0:
505
+ print(f" {GREEN}✔{RESET} npm package upgraded successfully.")
506
+ except Exception:
507
+ pass
508
+
509
+ # 3. Check pip
510
+ pip_cmd = "pip3" if shutil.which("pip3") else ("pip" if shutil.which("pip") else None)
511
+ if pip_cmd:
512
+ try:
513
+ res = subprocess.run([pip_cmd, "list"], capture_output=True, text=True, timeout=5)
514
+ if "tokensafe" in res.stdout:
515
+ print(f" {CYAN}→{RESET} Updating Python package ({pip_cmd} install --upgrade tokensafe)...")
516
+ up_res = subprocess.run([pip_cmd, "install", "--upgrade", "tokensafe"], capture_output=True, text=True, timeout=30)
517
+ if up_res.returncode == 0:
518
+ print(f" {GREEN}✔{RESET} Python package upgraded successfully.")
519
+ except Exception:
520
+ pass
521
+
522
+ # 4. Re-synchronize all detected agents
523
+ print(f"\n {CYAN}→{RESET} Re-synchronizing AI Agent MCP configs & rules...")
524
+ agents = cls.detect_available_agents()
525
+ synced_count = 0
526
+ for key, info in agents.items():
527
+ if info["installed"]:
528
+ ok, msg = cls.install_mcp_config(key)
529
+ if ok:
530
+ print(f" {GREEN}✔{RESET} {info['name']}: {msg}")
531
+ synced_count += 1
532
+ else:
533
+ print(f" {YELLOW}⚠{RESET} {info['name']}: {msg}")
534
+
535
+ # 5. Refresh local version cache
536
+ try:
537
+ data_dir = os.path.join(PROJECT_ROOT, "data")
538
+ cache_file = os.path.join(data_dir, "version_cache.json")
539
+ if os.path.exists(cache_file):
540
+ os.remove(cache_file)
541
+ except Exception:
542
+ pass
543
+
544
+ print(f"\n{BOLD}{GREEN}✅ Self-update complete!{RESET}")
545
+ print(f" Synchronized {synced_count} agent environments with zero-loss AST & God Nodes rules.")
546
+ print(f" Run {BOLD}tokensafe stats{RESET} to view token savings.\n")
547
+
380
548
  def main():
381
- AgentInstaller.run_interactive()
549
+ args = sys.argv[1:]
550
+ if args and args[0] in ("update", "--update", "upgrade", "--upgrade"):
551
+ AgentInstaller.self_update()
552
+ else:
553
+ AgentInstaller.run_interactive()
382
554
 
383
555
  if __name__ == "__main__":
384
556
  main()
@@ -17,9 +17,113 @@ PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
17
17
  DATA_DIR = os.path.join(PROJECT_ROOT, "data")
18
18
  LICENSE_FILE = os.path.join(DATA_DIR, "license.json")
19
19
 
20
- # Master signing seed - used for validation and verification
21
- # In production, signature verification uses a public verification hash
22
- DEFAULT_SIGNING_SALT = "ts-core-sec-9a4f8b2c1e7d3a506198fbcde40231aa"
20
+ # Master Public Key for client-side offline verification (RFC 8032 Ed25519)
21
+ DEFAULT_ED25519_PUBLIC_KEY = "244ea9d4a20e697578b7b7b31db71613c659678d221300dea1c5a03083bc90e9"
22
+ # Private key for cloud server signing (never distributed to untrusted clients)
23
+ DEFAULT_ED25519_PRIVATE_KEY = os.environ.get("TOKENSAFE_PRIVATE_KEY", "6785d298e2df4c2c305bd4956f124f038d2da5cbda7f4146513645f1733064c0")
24
+ # Rotated HMAC salt for backward compatibility with TS1 legacy licenses
25
+ ROTATED_HMAC_SALT = os.environ.get("TOKENSAFE_HMAC_SALT", "ts-sec-rotated-7b3f9c2d1e0a4f5b6829e1c3a70428e5")
26
+ DEFAULT_SIGNING_SALT = ROTATED_HMAC_SALT
27
+
28
+ # ---------------------------------------------------------------------------
29
+ # Zero-dependency RFC 8032 Ed25519 Implementation with Cryptography Fast-Path
30
+ # ---------------------------------------------------------------------------
31
+ _ED25519_Q = 2**255 - 19
32
+ _ED25519_L = 2**252 + 27742317777372353535851937790883648493
33
+
34
+ def _ed_inv(x: int) -> int:
35
+ return pow(x, _ED25519_Q - 2, _ED25519_Q)
36
+
37
+ _ED_D = -121665 * _ed_inv(121666)
38
+ _ED_I = pow(2, (_ED25519_Q - 1) // 4, _ED25519_Q)
39
+
40
+ def _ed_xrecover(y: int) -> int:
41
+ xx = (y * y - 1) * _ed_inv(_ED_D * y * y + 1)
42
+ x = pow(xx, (_ED25519_Q + 3) // 8, _ED25519_Q)
43
+ if (x * x - xx) % _ED25519_Q != 0:
44
+ x = (x * _ED_I) % _ED25519_Q
45
+ if x % 2 != 0:
46
+ x = _ED25519_Q - x
47
+ return x
48
+
49
+ _ED_BY = 4 * _ed_inv(5)
50
+ _ED_BX = _ed_xrecover(_ED_BY)
51
+ _ED_B = [_ED_BX % _ED25519_Q, _ED_BY % _ED25519_Q]
52
+
53
+ def _ed_add(p1: list, p2: list) -> list:
54
+ x1, y1 = p1[0], p1[1]
55
+ x2, y2 = p2[0], p2[1]
56
+ x3 = (x1 * y2 + x2 * y1) * _ed_inv(1 + _ED_D * x1 * x2 * y1 * y2)
57
+ y3 = (y1 * y2 + x1 * x2) * _ed_inv(1 - _ED_D * x1 * x2 * y1 * y2)
58
+ return [x3 % _ED25519_Q, y3 % _ED25519_Q]
59
+
60
+ def _ed_scalarmult(pt: list, e: int) -> list:
61
+ if e == 0:
62
+ return [0, 1]
63
+ q = _ed_scalarmult(pt, e // 2)
64
+ q = _ed_add(q, q)
65
+ if e & 1:
66
+ q = _ed_add(q, pt)
67
+ return q
68
+
69
+ def _ed_encodepoint(pt: list) -> bytes:
70
+ x, y = pt[0], pt[1]
71
+ bits = [(y >> i) & 1 for i in range(255)] + [x & 1]
72
+ return bytes([sum([bits[i * 8 + j] << j for j in range(8)]) for i in range(32)])
73
+
74
+ def _ed_bit(h: bytes, i: int) -> int:
75
+ return (h[i // 8] >> (i % 8)) & 1
76
+
77
+ def _ed_decodepoint(s: bytes) -> Optional[list]:
78
+ y = sum(2**i * _ed_bit(s, i) for i in range(0, 255))
79
+ x = _ed_xrecover(y)
80
+ if x & 1 != _ed_bit(s, 255):
81
+ x = _ED25519_Q - x
82
+ pt = [x, y]
83
+ if (-x * x + y * y - 1 - _ED_D * x * x * y * y) % _ED25519_Q != 0:
84
+ return None
85
+ return pt
86
+
87
+ def _ed25519_sign_bytes(msg: bytes, priv_bytes: bytes, pub_bytes: bytes) -> bytes:
88
+ try:
89
+ from cryptography.hazmat.primitives.asymmetric import ed25519
90
+ priv_obj = ed25519.Ed25519PrivateKey.from_private_bytes(priv_bytes)
91
+ return priv_obj.sign(msg)
92
+ except Exception:
93
+ h = hashlib.sha512(priv_bytes).digest()
94
+ a = 2**254 + sum(2**i * _ed_bit(h, i) for i in range(3, 254))
95
+ r = int.from_bytes(hashlib.sha512(h[32:] + msg).digest(), "little")
96
+ r_pt = _ed_scalarmult(_ED_B, r)
97
+ r_bytes = _ed_encodepoint(r_pt)
98
+ k = int.from_bytes(hashlib.sha512(r_bytes + pub_bytes + msg).digest(), "little")
99
+ s = (r + k * a) % _ED25519_L
100
+ return r_bytes + int.to_bytes(s, 32, "little")
101
+
102
+ def _ed25519_verify_bytes(sig: bytes, msg: bytes, pub_bytes: bytes) -> bool:
103
+ if len(sig) != 64 or len(pub_bytes) != 32:
104
+ return False
105
+ try:
106
+ from cryptography.hazmat.primitives.asymmetric import ed25519
107
+ pub_obj = ed25519.Ed25519PublicKey.from_public_bytes(pub_bytes)
108
+ pub_obj.verify(sig, msg)
109
+ return True
110
+ except Exception:
111
+ pass
112
+ try:
113
+ r_pt = _ed_decodepoint(sig[:32])
114
+ a_pt = _ed_decodepoint(pub_bytes)
115
+ if r_pt is None or a_pt is None:
116
+ return False
117
+ s = int.from_bytes(sig[32:], "little")
118
+ if s >= _ED25519_L:
119
+ return False
120
+ h = int.from_bytes(hashlib.sha512(sig[:32] + pub_bytes + msg).digest(), "little")
121
+ v1 = _ed_scalarmult(_ED_B, s)
122
+ v2 = _ed_add(r_pt, _ed_scalarmult(a_pt, h))
123
+ return v1 == v2
124
+ except Exception:
125
+ return False
126
+
23
127
 
24
128
  class LicenseManager:
25
129
  """Manages TokenSafe subscription tiers, offline signature verification, and 7-day trials."""
@@ -37,18 +141,17 @@ class LicenseManager:
37
141
  tier: str,
38
142
  email: str,
39
143
  duration_days: int = 30,
40
- signing_key: str = DEFAULT_SIGNING_SALT,
41
- is_trial: bool = False
144
+ signing_key: Optional[str] = None,
145
+ is_trial: bool = False,
146
+ version: int = 2
42
147
  ) -> str:
43
148
  """
44
149
  Generates a tamper-proof cryptographically signed license key.
45
- Format: TS1.<b64_payload>.<signature_hex>
150
+ - Version 2 (Default): Asymmetric Ed25519 signed (Format: TS2.<b64_payload>.<b64_sig>)
151
+ - Version 1: Legacy HMAC-SHA256 signed (Format: TS1.<b64_payload>.<sig_hex>)
46
152
  """
47
153
  now = int(time.time())
48
- if duration_days == 0:
49
- expires_at = 0 # Lifetime
50
- else:
51
- expires_at = now + (duration_days * 86400)
154
+ expires_at = 0 if duration_days == 0 else now + (duration_days * 86400)
52
155
 
53
156
  payload = {
54
157
  "tier": tier.lower(),
@@ -56,23 +159,36 @@ class LicenseManager:
56
159
  "issued_at": now,
57
160
  "expires_at": expires_at,
58
161
  "trial": is_trial,
59
- "v": 1
162
+ "v": version
60
163
  }
61
164
 
62
165
  payload_bytes = json.dumps(payload, sort_keys=True, separators=(',', ':')).encode("utf-8")
63
166
  payload_b64 = base64.urlsafe_b64encode(payload_bytes).decode("ascii").rstrip("=")
64
167
 
65
- sig = hmac.new(signing_key.encode("utf-8"), payload_bytes, hashlib.sha256).hexdigest()[:32]
168
+ if version == 2:
169
+ priv_hex = signing_key or DEFAULT_ED25519_PRIVATE_KEY
170
+ priv_bytes = bytes.fromhex(priv_hex)
171
+ pub_bytes = bytes.fromhex(DEFAULT_ED25519_PUBLIC_KEY)
172
+ sig_raw = _ed25519_sign_bytes(payload_bytes, priv_bytes, pub_bytes)
173
+ sig_b64 = base64.urlsafe_b64encode(sig_raw).decode("ascii").rstrip("=")
174
+ return f"TS2.{payload_b64}.{sig_b64}"
175
+
176
+ # Fallback to TS1 HMAC format
177
+ hmac_key = signing_key or ROTATED_HMAC_SALT
178
+ sig = hmac.new(hmac_key.encode("utf-8"), payload_bytes, hashlib.sha256).hexdigest()[:32]
66
179
  return f"TS1.{payload_b64}.{sig}"
67
180
 
68
181
  @classmethod
69
182
  def validate_license(
70
183
  cls,
71
184
  license_key: str,
72
- signing_key: str = DEFAULT_SIGNING_SALT
185
+ public_key: Optional[str] = None
73
186
  ) -> Tuple[bool, Dict[str, Any], str]:
74
187
  """
75
188
  Validates the license key signature and expiration.
189
+ Supports:
190
+ - TS2: Asymmetric Ed25519 verification using public key (Offline-safe, impossible to forge)
191
+ - TS1: Legacy HMAC-SHA256 verification with rotated salt
76
192
  Returns (is_valid, payload_dict, reason_str).
77
193
  """
78
194
  if not license_key or not isinstance(license_key, str):
@@ -80,22 +196,40 @@ class LicenseManager:
80
196
 
81
197
  license_key = license_key.strip()
82
198
  parts = license_key.split(".")
83
- if len(parts) != 3 or parts[0] != "TS1":
84
- return False, {}, "Invalid license key format (must start with TS1.)"
199
+ if len(parts) != 3 or parts[0] not in ("TS1", "TS2"):
200
+ return False, {}, "Invalid license key format (must start with TS2. or TS1.)"
85
201
 
86
- payload_b64, sig = parts[1], parts[2]
87
- # Pad base64
88
- padded = payload_b64 + "=" * (-len(payload_b64) % 4)
202
+ schema_ver, payload_b64, sig_part = parts[0], parts[1], parts[2]
203
+ padded_payload = payload_b64 + "=" * (-len(payload_b64) % 4)
89
204
  try:
90
- payload_bytes = base64.urlsafe_b64decode(padded.encode("ascii"))
205
+ payload_bytes = base64.urlsafe_b64decode(padded_payload.encode("ascii"))
91
206
  payload = json.loads(payload_bytes.decode("utf-8"))
92
207
  except Exception as e:
93
208
  return False, {}, f"Corrupted license payload: {str(e)}"
94
209
 
95
- # Verify signature
96
- expected_sig = hmac.new(signing_key.encode("utf-8"), payload_bytes, hashlib.sha256).hexdigest()[:32]
97
- if not hmac.compare_digest(sig, expected_sig):
98
- return False, {}, "Invalid signature: license key has been tampered with"
210
+ # 1. Asymmetric Ed25519 Verification (TS2)
211
+ if schema_ver == "TS2":
212
+ pub_hex = public_key or DEFAULT_ED25519_PUBLIC_KEY
213
+ try:
214
+ pub_bytes = bytes.fromhex(pub_hex)
215
+ padded_sig = sig_part + "=" * (-len(sig_part) % 4)
216
+ sig_bytes = base64.urlsafe_b64decode(padded_sig.encode("ascii"))
217
+ except Exception:
218
+ return False, {}, "Invalid signature encoding"
219
+
220
+ if not _ed25519_verify_bytes(sig_bytes, payload_bytes, pub_bytes):
221
+ return False, {}, "Invalid digital signature: license key has been tampered with or is counterfeit"
222
+
223
+ # 2. Legacy TS1 Verification
224
+ else:
225
+ hmac_key = public_key or ROTATED_HMAC_SALT
226
+ expected_sig = hmac.new(hmac_key.encode("utf-8"), payload_bytes, hashlib.sha256).hexdigest()[:32]
227
+ if not hmac.compare_digest(sig_part, expected_sig):
228
+ # Try fallback default salt if user had old key
229
+ old_salt = "ts-core-sec-9a4f8b2c1e7d3a506198fbcde40231aa"
230
+ fallback_sig = hmac.new(old_salt.encode("utf-8"), payload_bytes, hashlib.sha256).hexdigest()[:32]
231
+ if not hmac.compare_digest(sig_part, fallback_sig):
232
+ return False, {}, "Invalid signature: legacy license key has been tampered with"
99
233
 
100
234
  # Check expiration
101
235
  now = int(time.time())
package/src/mcp_server.py CHANGED
@@ -22,10 +22,11 @@ from src.loop_detector import LoopDetector
22
22
  from src.metrics import MetricsTracker
23
23
  from src.dashboard import Dashboard
24
24
  from src.graph_engine import GraphEngine
25
+ from src.tokenizer import count_tokens
25
26
 
26
27
  SERVER_INFO = {
27
28
  "name": "tokensafe-mcp",
28
- "version": "1.1.1"
29
+ "version": "1.2.0"
29
30
  }
30
31
 
31
32
  TOOLS = [
@@ -127,6 +128,18 @@ def handle_tool_call(name: str, args: dict) -> dict:
127
128
  graph, rel_path = GraphEngine.for_file(path)
128
129
  graph_skel = graph.graph_guided_skeletonize(path, target_symbol=symbol)
129
130
  if graph_skel:
131
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
132
+ raw_code = f.read()
133
+ orig_t = count_tokens(raw_code)
134
+ skel_t = count_tokens(graph_skel)
135
+ saved = max(0, orig_t - skel_t)
136
+ tracker.record_event(
137
+ session_id="mcp_session",
138
+ event_type="GRAPH_SKELETON",
139
+ original_tokens=orig_t,
140
+ optimized_tokens=skel_t,
141
+ details={"file": os.path.basename(path), "symbol": symbol, "saved_tokens": saved}
142
+ )
130
143
  header = f"// [TokenSafe Graph-Guided Skeleton for '{symbol}' | Full body + 1-hop dependencies]\n"
131
144
  return {"content": [{"type": "text", "text": (prefetch_block or "") + header + graph_skel}]}
132
145
  except Exception:
@@ -175,8 +188,15 @@ def handle_tool_call(name: str, args: dict) -> dict:
175
188
  return {"content": [{"type": "text", "text": dashboard.render_markdown()}]}
176
189
 
177
190
  elif name == "get_architecture_graph":
178
- target = args.get("project_path") or os.getcwd()
179
- graph = GraphEngine.get_instance(target)
191
+ target = args.get("project_path") or args.get("root_dir") or args.get("path") or args.get("directory") or os.getcwd()
192
+ target_abs = os.path.abspath(target)
193
+ system_roots = {"/", "/Users", "/home", "/root", os.path.expanduser("~")}
194
+ if target_abs in system_roots:
195
+ return {
196
+ "isError": True,
197
+ "content": [{"type": "text", "text": "Error: Invalid or root project_path. Please specify an explicit 'project_path' pointing to your project directory."}]
198
+ }
199
+ graph = GraphEngine.get_instance(target_abs)
180
200
  god_nodes = graph.get_god_nodes(7)
181
201
  banner = graph.format_topology_banner()
182
202
  payload = {
@@ -186,12 +206,41 @@ def handle_tool_call(name: str, args: dict) -> dict:
186
206
  "total_symbols": len(graph.symbols),
187
207
  "god_nodes": god_nodes
188
208
  }
209
+ # Cap estimated crawl tokens to max 50,000 to prevent runaway spikes on large/root dirs
210
+ capped_files = min(80, len(graph.file_symbols))
211
+ est_crawl_tokens = min(50000, max(5000, capped_files * 600))
212
+ topo_tokens = 250
213
+ tracker.record_event(
214
+ session_id="mcp_session",
215
+ event_type="GRAPH_TOPOLOGY",
216
+ original_tokens=est_crawl_tokens,
217
+ optimized_tokens=topo_tokens,
218
+ details={"hubs_count": len(god_nodes), "indexed_files": len(graph.file_symbols)}
219
+ )
189
220
  return {"content": [{"type": "text", "text": json.dumps(payload, indent=2, ensure_ascii=False)}]}
190
221
 
191
222
  elif name == "get_api_surface":
192
- target = args.get("project_path") or os.getcwd()
193
- graph = GraphEngine.get_instance(target)
223
+ target = args.get("project_path") or args.get("root_dir") or args.get("path") or args.get("directory") or os.getcwd()
224
+ target_abs = os.path.abspath(target)
225
+ system_roots = {"/", "/Users", "/home", "/root", os.path.expanduser("~")}
226
+ if target_abs in system_roots:
227
+ return {
228
+ "isError": True,
229
+ "content": [{"type": "text", "text": "Error: Invalid or root project_path. Please specify an explicit 'project_path' pointing to your project directory."}]
230
+ }
231
+ graph = GraphEngine.get_instance(target_abs)
194
232
  surface_md = graph.generate_api_surface()
233
+ surface_tokens = count_tokens(surface_md)
234
+ # Cap estimated crawl tokens to max 60,000
235
+ capped_files = min(100, len(graph.file_symbols))
236
+ est_orig_tokens = min(60000, max(10000, capped_files * 600))
237
+ tracker.record_event(
238
+ session_id="mcp_session",
239
+ event_type="GRAPH_TOPOLOGY",
240
+ original_tokens=est_orig_tokens,
241
+ optimized_tokens=surface_tokens,
242
+ details={"type": "API_SURFACE", "symbols_count": len(graph.symbols)}
243
+ )
195
244
  return {"content": [{"type": "text", "text": surface_md}]}
196
245
 
197
246
  return {"isError": True, "content": [{"type": "text", "text": f"Unknown tool: {name}"}]}
package/src/metrics.py CHANGED
@@ -174,6 +174,51 @@ class MetricsTracker:
174
174
  events.append(ev)
175
175
  return events
176
176
 
177
+ def get_last_event(self, session_id: str, event_type: str) -> Optional[Dict[str, Any]]:
178
+ """Returns the most recent event of a given type for a session."""
179
+ with self._get_connection() as conn:
180
+ cursor = conn.cursor()
181
+ cursor.execute("""
182
+ SELECT id, session_id, timestamp, event_type, original_tokens,
183
+ optimized_tokens, saved_tokens, reduction_pct, est_usd_saved, details
184
+ FROM events
185
+ WHERE session_id = ? AND event_type = ?
186
+ ORDER BY id DESC
187
+ LIMIT 1
188
+ """, (session_id, event_type))
189
+ row = cursor.fetchone()
190
+ if not row:
191
+ return None
192
+ res = dict(row)
193
+ try:
194
+ res["details"] = json.loads(res["details"])
195
+ except Exception:
196
+ pass
197
+ return res
198
+
199
+ def recalculate_sessions(self):
200
+ """Recalculates sessions table aggregates directly from events table."""
201
+ with self._get_connection() as conn:
202
+ cursor = conn.cursor()
203
+ cursor.execute("DELETE FROM sessions")
204
+ cursor.execute("""
205
+ INSERT INTO sessions (
206
+ session_id, created_at, last_updated,
207
+ total_original_tokens, total_optimized_tokens,
208
+ total_saved_tokens, total_usd_saved
209
+ )
210
+ SELECT
211
+ session_id,
212
+ MIN(timestamp) as created_at,
213
+ MAX(timestamp) as last_updated,
214
+ COALESCE(SUM(original_tokens), 0) as total_original_tokens,
215
+ COALESCE(SUM(optimized_tokens), 0) as total_optimized_tokens,
216
+ COALESCE(SUM(saved_tokens), 0) as total_saved_tokens,
217
+ COALESCE(SUM(est_usd_saved), 0.0) as total_usd_saved
218
+ FROM events
219
+ GROUP BY session_id
220
+ """)
221
+
177
222
  def reset(self):
178
223
  """Resets all metrics data."""
179
224
  with self._get_connection() as conn: