tokensafe 1.2.0 → 1.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +200 -16
- package/bin/agy-tokens +156 -4
- package/bin/tokensafe.js +7 -0
- package/hooks/pre_invocation.py +40 -11
- package/hooks/pre_tool_use.py +23 -3
- package/package.json +7 -3
- package/plugin.json +1 -1
- package/rules/AGENTS.md +6 -0
- package/skills/token-optimizer/SKILL.md +1 -0
- package/src/__init__.py +1 -1
- package/src/agent_firewall.py +146 -0
- package/src/benchmark.py +68 -9
- package/src/cache_normalizer.py +105 -0
- package/src/command_sanitizer.py +21 -12
- package/src/dashboard.py +54 -7
- package/src/diff_slicer.py +120 -0
- package/src/environment_auditor.py +259 -0
- package/src/governor.py +166 -0
- package/src/graph_engine.py +4 -0
- package/src/installer.py +192 -34
- package/src/license_manager.py +157 -23
- package/src/mcp_server.py +59 -7
- package/src/metrics.py +261 -21
- package/src/proxy.py +160 -18
- package/src/version_checker.py +156 -0
- package/src/weekly_digest.py +305 -0
- package/src/mailer.py +0 -327
package/src/installer.py
CHANGED
|
@@ -15,13 +15,33 @@ 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")
|
|
23
31
|
PYTHON_BIN = sys.executable
|
|
24
32
|
|
|
33
|
+
UNIFIED_TOKENSAFE_RULE = (
|
|
34
|
+
"## TOKENSAFE GRAPH-FIRST OPTIMIZATION PROTOCOL\n"
|
|
35
|
+
"Always prioritize `tokensafe` MCP tools over default raw file reads or high-output terminal executions to prevent context window exhaustion.\n\n"
|
|
36
|
+
"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"
|
|
37
|
+
"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"
|
|
38
|
+
"3. **No Unconstrained Shell Grep/Find**: Strictly avoid running raw recursive grep/find across projects. Use `get_architecture_graph` or `get_api_surface`.\n"
|
|
39
|
+
"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"
|
|
40
|
+
"5. **Proof-of-Savings Turn Footer (English default)**:\n"
|
|
41
|
+
"At the end of your response for any turn where tools were executed, files were inspected, commands were sanitized, or prompts were compacted, append a compact 1-line footer in English:\n"
|
|
42
|
+
"`⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown>) | Cumulative Total: <total> tokens ($<usd>)`\n"
|
|
43
|
+
)
|
|
44
|
+
|
|
25
45
|
AGENTS_REGISTRY = {
|
|
26
46
|
"antigravity": {
|
|
27
47
|
"name": "Google Antigravity",
|
|
@@ -49,12 +69,14 @@ AGENTS_REGISTRY = {
|
|
|
49
69
|
"name": "Windsurf",
|
|
50
70
|
"type": "mcp_json",
|
|
51
71
|
"config_path": os.path.join(HOME, ".codeium", "windsurf", "mcp_config.json"),
|
|
72
|
+
"rules_path": os.path.join(HOME, ".codeium", "windsurf", "memories", "global_rules.md"),
|
|
52
73
|
"detect_path": os.path.join(HOME, ".codeium", "windsurf")
|
|
53
74
|
},
|
|
54
75
|
"cline": {
|
|
55
76
|
"name": "Cline / Roo Code (VS Code)",
|
|
56
77
|
"type": "mcp_json",
|
|
57
78
|
"config_path": os.path.join(HOME, "Library", "Application Support", "Code", "User", "globalStorage", "saoudrizwan.claude-dev", "settings", "cline_mcp_settings.json"),
|
|
79
|
+
"rules_path": os.path.join(HOME, "Library", "Application Support", "Code", "User", "globalStorage", "saoudrizwan.claude-dev", "settings", "Rule_TokenSafe.md"),
|
|
58
80
|
"detect_path": os.path.join(HOME, "Library", "Application Support", "Code")
|
|
59
81
|
},
|
|
60
82
|
"claude_code": {
|
|
@@ -163,14 +185,11 @@ class AgentInstaller:
|
|
|
163
185
|
"globs: *\n"
|
|
164
186
|
"alwaysApply: true\n"
|
|
165
187
|
"---\n\n"
|
|
166
|
-
|
|
167
|
-
"Always prioritize `tokensafe` MCP tools over default raw file reads or high-output terminal executions to prevent context window exhaustion.\n\n"
|
|
168
|
-
"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"
|
|
169
|
-
"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"
|
|
170
|
-
"3. **No Unconstrained Shell Grep/Find**: Strictly avoid running raw recursive grep/find across projects. Use `get_architecture_graph` or `get_api_surface`.\n"
|
|
171
|
-
"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"
|
|
188
|
+
+ UNIFIED_TOKENSAFE_RULE
|
|
172
189
|
)
|
|
173
190
|
cls._write_file_safely(info["rules_path"], rule_text)
|
|
191
|
+
cursorrules = os.path.join(HOME, ".cursorrules")
|
|
192
|
+
cls._inject_global_rule(cursorrules, UNIFIED_TOKENSAFE_RULE)
|
|
174
193
|
|
|
175
194
|
return True, f"Configured MCP, Extension & Rule for Cursor"
|
|
176
195
|
|
|
@@ -207,6 +226,9 @@ class AgentInstaller:
|
|
|
207
226
|
if "skills_path" in info:
|
|
208
227
|
cls._symlink_skill(info["skills_path"])
|
|
209
228
|
|
|
229
|
+
if "rules_path" in info:
|
|
230
|
+
cls._inject_global_rule(info["rules_path"], UNIFIED_TOKENSAFE_RULE)
|
|
231
|
+
|
|
210
232
|
return True, f"Updated MCP configuration at {config_file}"
|
|
211
233
|
|
|
212
234
|
elif info["type"] == "codex_toml":
|
|
@@ -244,15 +266,7 @@ class AgentInstaller:
|
|
|
244
266
|
cls._symlink_dir(PROJECT_ROOT, info["plugin_path"])
|
|
245
267
|
|
|
246
268
|
if "agents_md_path" in info:
|
|
247
|
-
|
|
248
|
-
"## TOKENSAFE GRAPH-FIRST OPTIMIZATION PROTOCOL\n"
|
|
249
|
-
"Always prioritize `tokensafe` MCP tools over default raw file reads or high-output terminal executions to prevent context window exhaustion.\n"
|
|
250
|
-
"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"
|
|
251
|
-
"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"
|
|
252
|
-
"3. **No Unconstrained Shell Grep/Find**: Strictly avoid running raw recursive grep/find across projects. Use `get_architecture_graph` or `get_api_surface`.\n"
|
|
253
|
-
"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"
|
|
254
|
-
)
|
|
255
|
-
cls._inject_global_rule(info["agents_md_path"], codex_rule)
|
|
269
|
+
cls._inject_global_rule(info["agents_md_path"], UNIFIED_TOKENSAFE_RULE)
|
|
256
270
|
|
|
257
271
|
return True, f"Configured MCP, Plugin, Skill & AGENTS.md in {config_file}"
|
|
258
272
|
|
|
@@ -276,15 +290,7 @@ class AgentInstaller:
|
|
|
276
290
|
json.dump(data, f, indent=2)
|
|
277
291
|
|
|
278
292
|
if "agents_md_path" in info:
|
|
279
|
-
|
|
280
|
-
"## TOKENSAFE GRAPH-FIRST OPTIMIZATION PROTOCOL\n"
|
|
281
|
-
"Always prioritize `tokensafe` MCP tools over default raw file reads or recursive grep/find.\n"
|
|
282
|
-
"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"
|
|
283
|
-
"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"
|
|
284
|
-
"3. **No Unconstrained Shell Grep/Find**: Strictly avoid running raw recursive grep/find across projects. Use `get_architecture_graph` or `get_api_surface`.\n"
|
|
285
|
-
"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"
|
|
286
|
-
)
|
|
287
|
-
cls._inject_global_rule(info["agents_md_path"], claude_rule)
|
|
293
|
+
cls._inject_global_rule(info["agents_md_path"], UNIFIED_TOKENSAFE_RULE)
|
|
288
294
|
|
|
289
295
|
if "skills_path" in info:
|
|
290
296
|
cls._symlink_skill(info["skills_path"])
|
|
@@ -346,15 +352,7 @@ class AgentInstaller:
|
|
|
346
352
|
cls._symlink_dir(PROJECT_ROOT, info["plugin_path"])
|
|
347
353
|
|
|
348
354
|
if "agents_md_path" in info:
|
|
349
|
-
|
|
350
|
-
"## TOKENSAFE GRAPH-FIRST OPTIMIZATION PROTOCOL\n"
|
|
351
|
-
"Always prioritize `tokensafe` MCP tools over default raw file reads or high-output terminal executions to prevent context window exhaustion.\n"
|
|
352
|
-
"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"
|
|
353
|
-
"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"
|
|
354
|
-
"3. **No Unconstrained Shell Grep/Find**: Strictly avoid running raw recursive grep/find across projects. Use `get_architecture_graph` or `get_api_surface`.\n"
|
|
355
|
-
"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"
|
|
356
|
-
)
|
|
357
|
-
cls._inject_global_rule(info["agents_md_path"], zcode_rule)
|
|
355
|
+
cls._inject_global_rule(info["agents_md_path"], UNIFIED_TOKENSAFE_RULE)
|
|
358
356
|
|
|
359
357
|
return True, f"Configured MCP, Plugin, Skill & AGENTS.md in {config_file}"
|
|
360
358
|
|
|
@@ -414,6 +412,87 @@ class AgentInstaller:
|
|
|
414
412
|
skill_src = os.path.join(PROJECT_ROOT, "skills", "token-optimizer")
|
|
415
413
|
cls._symlink_dir(skill_src, target_path)
|
|
416
414
|
|
|
415
|
+
@classmethod
|
|
416
|
+
def install_project(cls, project_dir: Optional[str] = None) -> Dict[str, Any]:
|
|
417
|
+
"""Injects TokenSafe rules and MCP configs directly into a target project workspace."""
|
|
418
|
+
if not project_dir:
|
|
419
|
+
project_dir = os.getcwd()
|
|
420
|
+
project_dir = os.path.abspath(project_dir)
|
|
421
|
+
|
|
422
|
+
rule_files = [
|
|
423
|
+
os.path.join(project_dir, "AGENTS.md"),
|
|
424
|
+
os.path.join(project_dir, "CLAUDE.md"),
|
|
425
|
+
os.path.join(project_dir, ".cursorrules"),
|
|
426
|
+
os.path.join(project_dir, ".windsurfrules"),
|
|
427
|
+
os.path.join(project_dir, ".clinerules"),
|
|
428
|
+
os.path.join(project_dir, ".github", "copilot-instructions.md"),
|
|
429
|
+
os.path.join(project_dir, ".cursor", "rules", "tokensafe.mdc"),
|
|
430
|
+
]
|
|
431
|
+
|
|
432
|
+
cursor_mdc_header = (
|
|
433
|
+
"---\n"
|
|
434
|
+
"description: TokenSafe token economy, graph-first navigation and context optimization protocol\n"
|
|
435
|
+
"globs: *\n"
|
|
436
|
+
"alwaysApply: true\n"
|
|
437
|
+
"---\n\n"
|
|
438
|
+
)
|
|
439
|
+
|
|
440
|
+
created = []
|
|
441
|
+
for rf in rule_files:
|
|
442
|
+
try:
|
|
443
|
+
if rf.endswith(".mdc"):
|
|
444
|
+
cls._write_file_safely(rf, cursor_mdc_header + UNIFIED_TOKENSAFE_RULE)
|
|
445
|
+
else:
|
|
446
|
+
cls._inject_global_rule(rf, UNIFIED_TOKENSAFE_RULE)
|
|
447
|
+
created.append(os.path.relpath(rf, project_dir))
|
|
448
|
+
except Exception:
|
|
449
|
+
pass
|
|
450
|
+
|
|
451
|
+
# Also inject project-local .cursor/mcp.json
|
|
452
|
+
cursor_mcp = os.path.join(project_dir, ".cursor", "mcp.json")
|
|
453
|
+
try:
|
|
454
|
+
os.makedirs(os.path.dirname(cursor_mcp), exist_ok=True)
|
|
455
|
+
data = {}
|
|
456
|
+
if os.path.exists(cursor_mcp):
|
|
457
|
+
try:
|
|
458
|
+
with open(cursor_mcp, "r", encoding="utf-8") as f:
|
|
459
|
+
data = json.load(f)
|
|
460
|
+
except Exception:
|
|
461
|
+
data = {}
|
|
462
|
+
if "mcpServers" not in data or not isinstance(data["mcpServers"], dict):
|
|
463
|
+
data["mcpServers"] = {}
|
|
464
|
+
data["mcpServers"]["tokensafe"] = {
|
|
465
|
+
"command": PYTHON_BIN,
|
|
466
|
+
"args": [MCP_SERVER_PATH]
|
|
467
|
+
}
|
|
468
|
+
with open(cursor_mcp, "w", encoding="utf-8") as f:
|
|
469
|
+
json.dump(data, f, indent=2)
|
|
470
|
+
created.append(".cursor/mcp.json")
|
|
471
|
+
except Exception:
|
|
472
|
+
pass
|
|
473
|
+
|
|
474
|
+
return {
|
|
475
|
+
"success": True,
|
|
476
|
+
"project_dir": project_dir,
|
|
477
|
+
"created_rules": created
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
@classmethod
|
|
481
|
+
def install_all(cls, force: bool = False) -> Dict[str, Any]:
|
|
482
|
+
"""Automatically installs TokenSafe to all detected (or all registered) AI agents."""
|
|
483
|
+
agents = cls.detect_available_agents()
|
|
484
|
+
results = {}
|
|
485
|
+
for key, info in agents.items():
|
|
486
|
+
if info["installed"] or force:
|
|
487
|
+
ok, msg = cls.install_mcp_config(key)
|
|
488
|
+
results[key] = {"name": info["name"], "success": ok, "message": msg}
|
|
489
|
+
# Also configure project rules
|
|
490
|
+
proj_res = cls.install_project(os.getcwd())
|
|
491
|
+
return {
|
|
492
|
+
"agents": results,
|
|
493
|
+
"project_rules": proj_res.get("created_rules", [])
|
|
494
|
+
}
|
|
495
|
+
|
|
417
496
|
@classmethod
|
|
418
497
|
def run_interactive(cls):
|
|
419
498
|
"""Interactive terminal UI asking developer which agents to connect."""
|
|
@@ -462,8 +541,87 @@ class AgentInstaller:
|
|
|
462
541
|
print(f"\n\033[32m\033[1m✅ TokenSafe successfully connected to {installed_count} agent(s)!\033[0m")
|
|
463
542
|
print(" Restart your IDE / Agent to start saving tokens automatically.\n")
|
|
464
543
|
|
|
544
|
+
@classmethod
|
|
545
|
+
def self_update(cls):
|
|
546
|
+
"""
|
|
547
|
+
One-click self update for TokenSafe:
|
|
548
|
+
1. Detects package installation source (git, npm, pip).
|
|
549
|
+
2. Upgrades TokenSafe engine to latest release.
|
|
550
|
+
3. Re-synchronizes MCP configs and rules for all active agents.
|
|
551
|
+
4. Refreshes local version cache.
|
|
552
|
+
"""
|
|
553
|
+
print(f"\n{BOLD}{CYAN}╔════════════════════════════════════════════════════════════════════╗{RESET}")
|
|
554
|
+
print(f"{BOLD}{CYAN}║ ⚡ TOKENSAFE ONE-CLICK SELF-UPDATE ⚡ ║{RESET}")
|
|
555
|
+
print(f"{BOLD}{CYAN}╚════════════════════════════════════════════════════════════════════╝{RESET}\n")
|
|
556
|
+
|
|
557
|
+
# 1. Check if git clone installation (e.g. ~/.tokensafe)
|
|
558
|
+
is_git_clone = os.path.isdir(os.path.join(PROJECT_ROOT, ".git"))
|
|
559
|
+
if is_git_clone and PROJECT_ROOT.endswith((".tokensafe", "agy-token-optimizer")):
|
|
560
|
+
print(f" {CYAN}→{RESET} Detected local repository at {PROJECT_ROOT}. Pulling latest changes...")
|
|
561
|
+
try:
|
|
562
|
+
res = subprocess.run(["git", "pull", "--quiet"], cwd=PROJECT_ROOT, capture_output=True, text=True, timeout=10)
|
|
563
|
+
if res.returncode == 0:
|
|
564
|
+
print(f" {GREEN}✔{RESET} Git repository updated to latest commit.")
|
|
565
|
+
except Exception as e:
|
|
566
|
+
print(f" {YELLOW}⚠{RESET} Git pull skipped: {e}")
|
|
567
|
+
|
|
568
|
+
# 2. Check npm global
|
|
569
|
+
if shutil.which("npm"):
|
|
570
|
+
try:
|
|
571
|
+
res = subprocess.run(["npm", "list", "-g", "--depth=0", "tokensafe"], capture_output=True, text=True, timeout=5)
|
|
572
|
+
if "tokensafe@" in res.stdout:
|
|
573
|
+
print(f" {CYAN}→{RESET} Updating global npm package (npm install -g tokensafe@latest)...")
|
|
574
|
+
up_res = subprocess.run(["npm", "install", "-g", "tokensafe@latest"], capture_output=True, text=True, timeout=30)
|
|
575
|
+
if up_res.returncode == 0:
|
|
576
|
+
print(f" {GREEN}✔{RESET} npm package upgraded successfully.")
|
|
577
|
+
except Exception:
|
|
578
|
+
pass
|
|
579
|
+
|
|
580
|
+
# 3. Check pip
|
|
581
|
+
pip_cmd = "pip3" if shutil.which("pip3") else ("pip" if shutil.which("pip") else None)
|
|
582
|
+
if pip_cmd:
|
|
583
|
+
try:
|
|
584
|
+
res = subprocess.run([pip_cmd, "list"], capture_output=True, text=True, timeout=5)
|
|
585
|
+
if "tokensafe" in res.stdout:
|
|
586
|
+
print(f" {CYAN}→{RESET} Updating Python package ({pip_cmd} install --upgrade tokensafe)...")
|
|
587
|
+
up_res = subprocess.run([pip_cmd, "install", "--upgrade", "tokensafe"], capture_output=True, text=True, timeout=30)
|
|
588
|
+
if up_res.returncode == 0:
|
|
589
|
+
print(f" {GREEN}✔{RESET} Python package upgraded successfully.")
|
|
590
|
+
except Exception:
|
|
591
|
+
pass
|
|
592
|
+
|
|
593
|
+
# 4. Re-synchronize all detected agents
|
|
594
|
+
print(f"\n {CYAN}→{RESET} Re-synchronizing AI Agent MCP configs & rules...")
|
|
595
|
+
agents = cls.detect_available_agents()
|
|
596
|
+
synced_count = 0
|
|
597
|
+
for key, info in agents.items():
|
|
598
|
+
if info["installed"]:
|
|
599
|
+
ok, msg = cls.install_mcp_config(key)
|
|
600
|
+
if ok:
|
|
601
|
+
print(f" {GREEN}✔{RESET} {info['name']}: {msg}")
|
|
602
|
+
synced_count += 1
|
|
603
|
+
else:
|
|
604
|
+
print(f" {YELLOW}⚠{RESET} {info['name']}: {msg}")
|
|
605
|
+
|
|
606
|
+
# 5. Refresh local version cache
|
|
607
|
+
try:
|
|
608
|
+
data_dir = os.path.join(PROJECT_ROOT, "data")
|
|
609
|
+
cache_file = os.path.join(data_dir, "version_cache.json")
|
|
610
|
+
if os.path.exists(cache_file):
|
|
611
|
+
os.remove(cache_file)
|
|
612
|
+
except Exception:
|
|
613
|
+
pass
|
|
614
|
+
|
|
615
|
+
print(f"\n{BOLD}{GREEN}✅ Self-update complete!{RESET}")
|
|
616
|
+
print(f" Synchronized {synced_count} agent environments with zero-loss AST & God Nodes rules.")
|
|
617
|
+
print(f" Run {BOLD}tokensafe stats{RESET} to view token savings.\n")
|
|
618
|
+
|
|
465
619
|
def main():
|
|
466
|
-
|
|
620
|
+
args = sys.argv[1:]
|
|
621
|
+
if args and args[0] in ("update", "--update", "upgrade", "--upgrade"):
|
|
622
|
+
AgentInstaller.self_update()
|
|
623
|
+
else:
|
|
624
|
+
AgentInstaller.run_interactive()
|
|
467
625
|
|
|
468
626
|
if __name__ == "__main__":
|
|
469
627
|
main()
|
package/src/license_manager.py
CHANGED
|
@@ -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
|
|
21
|
-
|
|
22
|
-
|
|
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 =
|
|
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:
|
|
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":
|
|
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
|
-
|
|
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
|
-
|
|
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]
|
|
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,
|
|
87
|
-
|
|
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(
|
|
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
|
-
#
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
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
|
@@ -23,10 +23,12 @@ from src.metrics import MetricsTracker
|
|
|
23
23
|
from src.dashboard import Dashboard
|
|
24
24
|
from src.graph_engine import GraphEngine
|
|
25
25
|
from src.tokenizer import count_tokens
|
|
26
|
+
from src.agent_firewall import AgentFirewall
|
|
27
|
+
from src.diff_slicer import DiffSlicer
|
|
26
28
|
|
|
27
29
|
SERVER_INFO = {
|
|
28
30
|
"name": "tokensafe-mcp",
|
|
29
|
-
"version": "1.
|
|
31
|
+
"version": "1.3.1"
|
|
30
32
|
}
|
|
31
33
|
|
|
32
34
|
TOOLS = [
|
|
@@ -86,6 +88,18 @@ TOOLS = [
|
|
|
86
88
|
"required": ["command"]
|
|
87
89
|
}
|
|
88
90
|
},
|
|
91
|
+
{
|
|
92
|
+
"name": "slice_diff",
|
|
93
|
+
"description": "Slices unified diffs, omitting lockfiles and minimizing context lines to reduce tokens by up to 80%.",
|
|
94
|
+
"inputSchema": {
|
|
95
|
+
"type": "object",
|
|
96
|
+
"properties": {
|
|
97
|
+
"diff": {"type": "string", "description": "Raw git diff text"},
|
|
98
|
+
"max_context": {"type": "integer", "description": "Maximum surrounding context lines (default: 2)"}
|
|
99
|
+
},
|
|
100
|
+
"required": ["diff"]
|
|
101
|
+
}
|
|
102
|
+
},
|
|
89
103
|
{
|
|
90
104
|
"name": "get_token_savings_metrics",
|
|
91
105
|
"description": "Returns cumulative token and cost savings analytics.",
|
|
@@ -108,6 +122,11 @@ def handle_tool_call(name: str, args: dict) -> dict:
|
|
|
108
122
|
if not path or not os.path.exists(path):
|
|
109
123
|
return {"isError": True, "content": [{"type": "text", "text": f"File not found: {path}"}]}
|
|
110
124
|
|
|
125
|
+
# Check Subagent Firewall dedup cache
|
|
126
|
+
is_hit, cached_text, saved_dedup = AgentFirewall.check_cache("mcp_session", path, symbol=symbol or "", tracker=tracker)
|
|
127
|
+
if is_hit and cached_text:
|
|
128
|
+
return {"content": [{"type": "text", "text": cached_text}]}
|
|
129
|
+
|
|
111
130
|
# Check loop detector
|
|
112
131
|
is_loop, repeats, msg = LoopDetector.check_loop("mcp_session", "smart_read_file", args)
|
|
113
132
|
if is_loop:
|
|
@@ -183,13 +202,35 @@ def handle_tool_call(name: str, args: dict) -> dict:
|
|
|
183
202
|
}
|
|
184
203
|
return {"content": [{"type": "text", "text": json.dumps(result, indent=2)}]}
|
|
185
204
|
|
|
205
|
+
elif name == "slice_diff":
|
|
206
|
+
raw_diff = args.get("diff", "")
|
|
207
|
+
max_ctx = int(args.get("max_context", 2))
|
|
208
|
+
sliced, orig_t, opt_t = DiffSlicer.slice_diff(raw_diff, max_context_lines=max_ctx)
|
|
209
|
+
saved = max(0, orig_t - opt_t)
|
|
210
|
+
if saved > 0:
|
|
211
|
+
tracker.record_event(
|
|
212
|
+
session_id="mcp_session",
|
|
213
|
+
event_type="DIFF_SLICER",
|
|
214
|
+
original_tokens=orig_t,
|
|
215
|
+
optimized_tokens=opt_t,
|
|
216
|
+
details={"saved_tokens": saved, "max_context": max_ctx}
|
|
217
|
+
)
|
|
218
|
+
return {"content": [{"type": "text", "text": sliced}]}
|
|
219
|
+
|
|
186
220
|
elif name == "get_token_savings_metrics":
|
|
187
221
|
dashboard = Dashboard(tracker)
|
|
188
222
|
return {"content": [{"type": "text", "text": dashboard.render_markdown()}]}
|
|
189
223
|
|
|
190
224
|
elif name == "get_architecture_graph":
|
|
191
|
-
target = args.get("project_path") or os.getcwd()
|
|
192
|
-
|
|
225
|
+
target = args.get("project_path") or args.get("root_dir") or args.get("path") or args.get("directory") or os.getcwd()
|
|
226
|
+
target_abs = os.path.abspath(target)
|
|
227
|
+
system_roots = {"/", "/Users", "/home", "/root", os.path.expanduser("~")}
|
|
228
|
+
if target_abs in system_roots:
|
|
229
|
+
return {
|
|
230
|
+
"isError": True,
|
|
231
|
+
"content": [{"type": "text", "text": "Error: Invalid or root project_path. Please specify an explicit 'project_path' pointing to your project directory."}]
|
|
232
|
+
}
|
|
233
|
+
graph = GraphEngine.get_instance(target_abs)
|
|
193
234
|
god_nodes = graph.get_god_nodes(7)
|
|
194
235
|
banner = graph.format_topology_banner()
|
|
195
236
|
payload = {
|
|
@@ -199,7 +240,9 @@ def handle_tool_call(name: str, args: dict) -> dict:
|
|
|
199
240
|
"total_symbols": len(graph.symbols),
|
|
200
241
|
"god_nodes": god_nodes
|
|
201
242
|
}
|
|
202
|
-
|
|
243
|
+
# Cap estimated crawl tokens to max 50,000 to prevent runaway spikes on large/root dirs
|
|
244
|
+
capped_files = min(80, len(graph.file_symbols))
|
|
245
|
+
est_crawl_tokens = min(50000, max(5000, capped_files * 600))
|
|
203
246
|
topo_tokens = 250
|
|
204
247
|
tracker.record_event(
|
|
205
248
|
session_id="mcp_session",
|
|
@@ -211,11 +254,20 @@ def handle_tool_call(name: str, args: dict) -> dict:
|
|
|
211
254
|
return {"content": [{"type": "text", "text": json.dumps(payload, indent=2, ensure_ascii=False)}]}
|
|
212
255
|
|
|
213
256
|
elif name == "get_api_surface":
|
|
214
|
-
target = args.get("project_path") or os.getcwd()
|
|
215
|
-
|
|
257
|
+
target = args.get("project_path") or args.get("root_dir") or args.get("path") or args.get("directory") or os.getcwd()
|
|
258
|
+
target_abs = os.path.abspath(target)
|
|
259
|
+
system_roots = {"/", "/Users", "/home", "/root", os.path.expanduser("~")}
|
|
260
|
+
if target_abs in system_roots:
|
|
261
|
+
return {
|
|
262
|
+
"isError": True,
|
|
263
|
+
"content": [{"type": "text", "text": "Error: Invalid or root project_path. Please specify an explicit 'project_path' pointing to your project directory."}]
|
|
264
|
+
}
|
|
265
|
+
graph = GraphEngine.get_instance(target_abs)
|
|
216
266
|
surface_md = graph.generate_api_surface()
|
|
217
267
|
surface_tokens = count_tokens(surface_md)
|
|
218
|
-
|
|
268
|
+
# Cap estimated crawl tokens to max 60,000
|
|
269
|
+
capped_files = min(100, len(graph.file_symbols))
|
|
270
|
+
est_orig_tokens = min(60000, max(10000, capped_files * 600))
|
|
219
271
|
tracker.record_event(
|
|
220
272
|
session_id="mcp_session",
|
|
221
273
|
event_type="GRAPH_TOPOLOGY",
|