tokensafe 4.5.3 → 4.5.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.codex-plugin/plugin.json +1 -1
- package/kimi.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/cli.py +48 -4
- package/src/environment_auditor.py +351 -20
- package/src/installer.py +253 -55
- package/src/mcp_server.py +1 -1
- package/src/syntax_guard.py +1 -1
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
package/kimi.plugin.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
|
-
"version": "4.5.
|
|
3
|
+
"version": "4.5.5",
|
|
4
4
|
"description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
|
|
5
5
|
"homepage": "https://tokensafe.dev",
|
|
6
6
|
"license": "MIT",
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"mcpName": "dev.tokensafe/tokensafe",
|
|
4
|
-
"version": "4.5.
|
|
4
|
+
"version": "4.5.5",
|
|
5
5
|
"description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
|
|
6
6
|
"main": "bin/tokensafe.js",
|
|
7
7
|
"bin": {
|
package/plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"displayName": "TokenSafe",
|
|
4
|
-
"version": "4.5.
|
|
4
|
+
"version": "4.5.5",
|
|
5
5
|
"description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
|
|
6
6
|
"logo": "assets/logo.png",
|
|
7
7
|
"developerName": "TokenSafe",
|
package/server.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "dev.tokensafe/tokensafe",
|
|
4
4
|
"title": "TokenSafe",
|
|
5
5
|
"description": "Your AI agent is smart enough to code all day. Local firewall & zero-loss runtime.",
|
|
6
|
-
"version": "4.5.
|
|
6
|
+
"version": "4.5.5",
|
|
7
7
|
"websiteUrl": "https://tokensafe.dev",
|
|
8
8
|
"repository": {
|
|
9
9
|
"url": "https://github.com/tokensafe-dev/tokensafe",
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
"registryType": "npm",
|
|
24
24
|
"registryBaseUrl": "https://registry.npmjs.org",
|
|
25
25
|
"identifier": "tokensafe",
|
|
26
|
-
"version": "4.5.
|
|
26
|
+
"version": "4.5.5",
|
|
27
27
|
"runtimeHint": "npx",
|
|
28
28
|
"transport": {
|
|
29
29
|
"type": "stdio"
|
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
"registryType": "pypi",
|
|
40
40
|
"registryBaseUrl": "https://pypi.org",
|
|
41
41
|
"identifier": "tokensafe",
|
|
42
|
-
"version": "4.5.
|
|
42
|
+
"version": "4.5.5",
|
|
43
43
|
"runtimeHint": "uvx",
|
|
44
44
|
"transport": {
|
|
45
45
|
"type": "stdio"
|
package/src/cli.py
CHANGED
|
@@ -116,7 +116,8 @@ def _print_help():
|
|
|
116
116
|
print(" expand-ref <hash> Restore folded tool/command/file result by its 8-char hash")
|
|
117
117
|
print(" wrap <command> Run command with compact output folding (e.g. tests/logs)")
|
|
118
118
|
print(" web <url> Fetch web page/docs and print clean compact Markdown")
|
|
119
|
-
print(" doctor [--cleanup]
|
|
119
|
+
print(" doctor [--fix | --cleanup] Audit MCP/skill overhead, repair configs & consolidate ghost rules")
|
|
120
|
+
print(" skills [list|disable|enable] Inspect and toggle active skills to cut turn context tax")
|
|
120
121
|
print(" tests [pytest] [--traceback] Run the unit test suite (compact failure report)")
|
|
121
122
|
print(" prune [--days N | --max N] Compact metrics database (roll old events)")
|
|
122
123
|
print(" vacuum Reclaim SQLite disk space")
|
|
@@ -422,6 +423,9 @@ def main(argv: Optional[List[str]] = None):
|
|
|
422
423
|
agents_plugin = args[idx + 1]
|
|
423
424
|
res = AgentInstaller.install_project(os.getcwd(), agents_plugin_path=agents_plugin)
|
|
424
425
|
print(f"\n\033[32m✔ TokenSafe rules injected into project: {', '.join(res['created_rules'])}\033[0m\n")
|
|
426
|
+
elif "--refresh" in args or "--sync-installed" in args:
|
|
427
|
+
res = AgentInstaller.refresh_installed_agents()
|
|
428
|
+
print(f"\n\033[32m✔ Synchronized {res['synced_count']} installed/configured agent environment(s).\033[0m\n")
|
|
425
429
|
else:
|
|
426
430
|
AgentInstaller.run_interactive()
|
|
427
431
|
|
|
@@ -927,9 +931,21 @@ def main(argv: Optional[List[str]] = None):
|
|
|
927
931
|
|
|
928
932
|
elif command in ("doctor", "audit", "tax"):
|
|
929
933
|
from src.environment_auditor import EnvironmentAuditor
|
|
934
|
+
from src.competitors import CompetitorAuditor
|
|
935
|
+
|
|
936
|
+
if "--fix" in args:
|
|
937
|
+
print("\n\033[1m\033[36m🔧 TOKENSAFE ENVIRONMENT AUTO-FIX 🔧\033[0m\n")
|
|
938
|
+
fix_res = EnvironmentAuditor.auto_fix()
|
|
939
|
+
for item in fix_res.get("fixed", []):
|
|
940
|
+
print(f" \033[32m✔\033[0m {item}")
|
|
941
|
+
for item in fix_res.get("skipped", []):
|
|
942
|
+
print(f" \033[33m⚠\033[0m {item}")
|
|
943
|
+
if not fix_res.get("fixed") and not fix_res.get("skipped"):
|
|
944
|
+
print(" \033[32m✔\033[0m No auto-fixable config or ghost-token issues found.")
|
|
945
|
+
print()
|
|
946
|
+
|
|
930
947
|
print(EnvironmentAuditor.format_cli_report())
|
|
931
948
|
|
|
932
|
-
from src.competitors import CompetitorAuditor
|
|
933
949
|
conflicts = CompetitorAuditor.audit()
|
|
934
950
|
if conflicts:
|
|
935
951
|
print("\n\033[1m\033[33m⚡ DETECTED CONFLICTING OR STALE TOOLS ⚡\033[0m")
|
|
@@ -938,13 +954,41 @@ def main(argv: Optional[List[str]] = None):
|
|
|
938
954
|
for tr in c['traces']:
|
|
939
955
|
loc = tr.get('path') or tr.get('file') or tr.get('config')
|
|
940
956
|
print(f" - {tr['kind']}: {loc}")
|
|
941
|
-
print("\n 💡 Tip: Run 'tokensafe doctor --cleanup' to remove conflicting orphan hooks/rules.\n")
|
|
957
|
+
print("\n 💡 Tip: Run 'tokensafe doctor --cleanup' (or '--fix') to remove conflicting orphan hooks/rules.\n")
|
|
942
958
|
|
|
943
959
|
if "--cleanup" in args:
|
|
944
960
|
for c in conflicts:
|
|
945
961
|
res = CompetitorAuditor.cleanup(c["id"])
|
|
946
962
|
print(f" \033[32m✔ Cleaned {c['name']}: {', '.join(res.get('removed', []))}\033[0m")
|
|
947
963
|
|
|
964
|
+
elif command in ("skills", "skill"):
|
|
965
|
+
from src.environment_auditor import EnvironmentAuditor
|
|
966
|
+
sub = args[1] if len(args) > 1 else "list"
|
|
967
|
+
if sub in ("disable", "off", "rm"):
|
|
968
|
+
if len(args) < 3:
|
|
969
|
+
print("Usage: tokensafe skills disable <skill_name>")
|
|
970
|
+
sys.exit(1)
|
|
971
|
+
target = args[2].strip()
|
|
972
|
+
res = EnvironmentAuditor.disable_skill(target)
|
|
973
|
+
if res.get("success"):
|
|
974
|
+
print(f"\n\033[32m✔ Skill '{res['skill']}' disabled ({res['path']}).\033[0m\n")
|
|
975
|
+
else:
|
|
976
|
+
print(f"\n\033[31m✖ {res.get('error', 'Failed to disable skill')}\033[0m\n")
|
|
977
|
+
sys.exit(1)
|
|
978
|
+
elif sub in ("enable", "on", "add"):
|
|
979
|
+
if len(args) < 3:
|
|
980
|
+
print("Usage: tokensafe skills enable <skill_name>")
|
|
981
|
+
sys.exit(1)
|
|
982
|
+
target = args[2].strip()
|
|
983
|
+
res = EnvironmentAuditor.enable_skill(target)
|
|
984
|
+
if res.get("success"):
|
|
985
|
+
print(f"\n\033[32m✔ Skill '{res['skill']}' re-enabled ({res['path']}).\033[0m\n")
|
|
986
|
+
else:
|
|
987
|
+
print(f"\n\033[31m✖ {res.get('error', 'Failed to enable skill')}\033[0m\n")
|
|
988
|
+
sys.exit(1)
|
|
989
|
+
else:
|
|
990
|
+
print(EnvironmentAuditor.format_skills_report())
|
|
991
|
+
|
|
948
992
|
elif command in ("web", "fetch", "url"):
|
|
949
993
|
if len(args) < 2:
|
|
950
994
|
print("Usage: tokensafe web <url>")
|
|
@@ -1644,7 +1688,7 @@ def main(argv: Optional[List[str]] = None):
|
|
|
1644
1688
|
|
|
1645
1689
|
else:
|
|
1646
1690
|
print(f"Unknown command: {command}")
|
|
1647
|
-
print("Available commands: init, login, logout, stats, status, sync, html, test, tests, expand-ref, wrap, web, doctor, providers, mcp, benchmark, proxy, graph, map, skeleton, guard, mistakes, vacuum, prune, digest, activate, license, markdown, install, uninstall, setup, update, check-update, reset. Run 'tokensafe help' for details.")
|
|
1691
|
+
print("Available commands: init, login, logout, stats, status, sync, html, test, tests, expand-ref, wrap, web, doctor, skills, providers, mcp, benchmark, proxy, graph, map, skeleton, guard, mistakes, vacuum, prune, digest, activate, license, markdown, install, uninstall, setup, update, check-update, reset. Run 'tokensafe help' for details.")
|
|
1648
1692
|
sys.exit(1)
|
|
1649
1693
|
|
|
1650
1694
|
if __name__ == "__main__":
|
|
@@ -9,7 +9,9 @@ Also audits always-on rule files against the Antigravity limits (rules.md):
|
|
|
9
9
|
import os
|
|
10
10
|
import re
|
|
11
11
|
import json
|
|
12
|
-
|
|
12
|
+
import hashlib
|
|
13
|
+
import shutil
|
|
14
|
+
from typing import Dict, List, Any, Optional, Tuple
|
|
13
15
|
|
|
14
16
|
from src.tokenizer import count_tokens
|
|
15
17
|
|
|
@@ -27,6 +29,34 @@ RULE_FILE_LIMIT_BYTES = 24000 # per rule file, after @[label](path) expansion
|
|
|
27
29
|
RULES_BUDGET_TOKENS = 20000 # shared always-on/global rules budget
|
|
28
30
|
|
|
29
31
|
_RULE_INCLUDE_RE = re.compile(r"@\[[^\]]*\]\(([^)]+)\)")
|
|
32
|
+
_SUBTABLE_RE = re.compile(r'^\s*\[mcp_servers\.(?:"([^"]+)"|\'([^\']+)\'|([A-Za-z0-9_-]+))(?:\.|\])')
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _parse_codex_toml_servers(raw_bytes: bytes) -> Tuple[Dict[str, Any], Optional[str]]:
|
|
36
|
+
"""Parses [mcp_servers.*] top-level server entries from Codex config.toml.
|
|
37
|
+
Returns (servers_dict, parse_error). Never treats nested subtables like
|
|
38
|
+
.env or .http_headers as separate MCP servers."""
|
|
39
|
+
text = raw_bytes.decode("utf-8", errors="replace")
|
|
40
|
+
parse_err: Optional[str] = None
|
|
41
|
+
try:
|
|
42
|
+
import tomllib
|
|
43
|
+
try:
|
|
44
|
+
loaded_toml = tomllib.loads(text)
|
|
45
|
+
mcp_tbl = loaded_toml.get("mcp_servers")
|
|
46
|
+
return (dict(mcp_tbl) if isinstance(mcp_tbl, dict) else {}), None
|
|
47
|
+
except Exception as exc:
|
|
48
|
+
parse_err = str(exc)
|
|
49
|
+
except ImportError:
|
|
50
|
+
pass
|
|
51
|
+
|
|
52
|
+
servers: Dict[str, Any] = {}
|
|
53
|
+
for line in text.splitlines():
|
|
54
|
+
m = _SUBTABLE_RE.match(line)
|
|
55
|
+
if m:
|
|
56
|
+
s_name = next((g for g in m.groups() if g), "").strip()
|
|
57
|
+
if s_name:
|
|
58
|
+
servers.setdefault(s_name, {})
|
|
59
|
+
return servers, parse_err
|
|
30
60
|
|
|
31
61
|
|
|
32
62
|
class EnvironmentAuditor:
|
|
@@ -113,17 +143,9 @@ class EnvironmentAuditor:
|
|
|
113
143
|
try:
|
|
114
144
|
with open(p, "rb") as f:
|
|
115
145
|
raw_bytes = f.read()
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
if isinstance(loaded_toml.get("mcp_servers"), dict):
|
|
120
|
-
configured.update(loaded_toml["mcp_servers"])
|
|
121
|
-
except Exception:
|
|
122
|
-
text = raw_bytes.decode("utf-8", errors="replace")
|
|
123
|
-
for m in re.finditer(r"^\s*\[mcp_servers\.([^\]]+)\]", text, re.MULTILINE):
|
|
124
|
-
s_name = m.group(1).strip().strip('"\'')
|
|
125
|
-
if s_name:
|
|
126
|
-
configured.setdefault(s_name, {})
|
|
146
|
+
parsed_toml, _ = _parse_codex_toml_servers(raw_bytes)
|
|
147
|
+
if parsed_toml:
|
|
148
|
+
configured.update(parsed_toml)
|
|
127
149
|
except Exception:
|
|
128
150
|
continue
|
|
129
151
|
continue
|
|
@@ -280,11 +302,13 @@ class EnvironmentAuditor:
|
|
|
280
302
|
|
|
281
303
|
# 2. Count skills (follow symlinked plugins/skills with cycle protection; skip disabled plugins)
|
|
282
304
|
skills_count = 0
|
|
305
|
+
skills_breakdown: Dict[str, int] = {}
|
|
283
306
|
disabled_plugins = cls._get_disabled_plugin_names()
|
|
284
307
|
plugins_dir = os.path.abspath(cls.get_plugins_dir())
|
|
285
308
|
seen_skill_dirs = set()
|
|
286
309
|
for sdir in cls.get_skills_dirs(workspace_root):
|
|
287
310
|
is_plugins_root = os.path.abspath(sdir) == plugins_dir
|
|
311
|
+
dir_skills = 0
|
|
288
312
|
for root, dirs, files in os.walk(sdir, followlinks=True):
|
|
289
313
|
real_root = os.path.realpath(root)
|
|
290
314
|
if real_root in seen_skill_dirs:
|
|
@@ -297,6 +321,32 @@ class EnvironmentAuditor:
|
|
|
297
321
|
dirs[:] = [d for d in dirs if d not in ("node_modules", ".git", "__pycache__", ".venv", "venv") and not d.endswith(".disabled")]
|
|
298
322
|
if "SKILL.md" in files:
|
|
299
323
|
skills_count += 1
|
|
324
|
+
dir_skills += 1
|
|
325
|
+
if dir_skills > 0:
|
|
326
|
+
skills_breakdown[sdir] = dir_skills
|
|
327
|
+
|
|
328
|
+
# Detect config & schema hygiene issues fixable via `tokensafe doctor --fix`
|
|
329
|
+
config_issues: List[Dict[str, str]] = []
|
|
330
|
+
for p in cls.get_config_paths():
|
|
331
|
+
if p.endswith(".toml") and os.path.isfile(p):
|
|
332
|
+
try:
|
|
333
|
+
with open(p, "rb") as f:
|
|
334
|
+
_, parse_err = _parse_codex_toml_servers(f.read())
|
|
335
|
+
if parse_err:
|
|
336
|
+
config_issues.append({
|
|
337
|
+
"type": "CORRUPTED_CODEX_TOML",
|
|
338
|
+
"path": p,
|
|
339
|
+
"description": f"Invalid TOML syntax in {os.path.basename(p)} ({parse_err[:80]})"
|
|
340
|
+
})
|
|
341
|
+
except Exception:
|
|
342
|
+
pass
|
|
343
|
+
if os.path.isdir(schemas_dir):
|
|
344
|
+
if os.path.isdir(os.path.join(schemas_dir, "tokensafe_tokensafe")) and os.path.isdir(os.path.join(schemas_dir, "tokensafe_tokensafe-mcp")):
|
|
345
|
+
config_issues.append({
|
|
346
|
+
"type": "STALE_MCP_SCHEMA",
|
|
347
|
+
"path": os.path.join(schemas_dir, "tokensafe_tokensafe-mcp"),
|
|
348
|
+
"description": "Legacy schema directory tokensafe_tokensafe-mcp duplicates tokensafe_tokensafe"
|
|
349
|
+
})
|
|
300
350
|
|
|
301
351
|
# 3. Rule files (rules.md limits)
|
|
302
352
|
rules = cls.audit_rules(workspace_root)
|
|
@@ -333,11 +383,13 @@ class EnvironmentAuditor:
|
|
|
333
383
|
"total_active_servers": len([s for s in servers.values() if s["active"]]),
|
|
334
384
|
"total_tools": total_mcp_tools,
|
|
335
385
|
"total_skills": skills_count,
|
|
386
|
+
"skills_breakdown": skills_breakdown,
|
|
336
387
|
"mcp_tokens_per_turn": total_mcp_tokens,
|
|
337
388
|
"skills_tokens_per_turn": total_skills_tokens,
|
|
338
389
|
"total_static_tokens_per_turn": total_static_tokens,
|
|
339
390
|
"bloated_servers": bloated_servers,
|
|
340
391
|
"has_critical_bloat": len(bloated_servers) > 0,
|
|
392
|
+
"config_issues": config_issues,
|
|
341
393
|
"rules": rules,
|
|
342
394
|
"ghost_tokens": ghost_tokens,
|
|
343
395
|
"treesitter": treesitter_info,
|
|
@@ -570,19 +622,279 @@ class EnvironmentAuditor:
|
|
|
570
622
|
"directory_renamed": renamed
|
|
571
623
|
}
|
|
572
624
|
|
|
625
|
+
@classmethod
|
|
626
|
+
def auto_fix(cls, workspace_root: Optional[str] = None) -> Dict[str, Any]:
|
|
627
|
+
"""Automatically fixes safe, recoverable context/config issues found by `doctor`:
|
|
628
|
+
1. Repairs corrupted [mcp_servers.tokensafe] / orphaned lines in Codex config.toml.
|
|
629
|
+
2. Removes stale duplicate tokensafe_tokensafe-mcp schema directory.
|
|
630
|
+
3. Backs up & consolidates redundant cross-IDE rule files into AGENTS.md pointer stubs
|
|
631
|
+
and strips large inactive comment blocks from rule files.
|
|
632
|
+
4. Cleans conflicting orphan competitor hooks/rules."""
|
|
633
|
+
root = workspace_root or os.getcwd()
|
|
634
|
+
fixed: List[str] = []
|
|
635
|
+
skipped: List[str] = []
|
|
636
|
+
|
|
637
|
+
try:
|
|
638
|
+
from src.paths import resolve_data_dir
|
|
639
|
+
backup_base = resolve_data_dir()
|
|
640
|
+
except Exception:
|
|
641
|
+
backup_base = os.path.join(os.path.expanduser("~"), ".tokensafe", "data")
|
|
642
|
+
ws_hash = hashlib.sha256(os.path.abspath(root).encode("utf-8")).hexdigest()[:12]
|
|
643
|
+
backup_dir = os.path.join(backup_base, "backups", ws_hash)
|
|
644
|
+
|
|
645
|
+
# 1. Repair Codex config.toml orphaned lines / corrupted [mcp_servers.tokensafe]
|
|
646
|
+
for p in cls.get_config_paths():
|
|
647
|
+
if not (p.endswith(".toml") and os.path.isfile(p)):
|
|
648
|
+
continue
|
|
649
|
+
try:
|
|
650
|
+
with open(p, "rb") as fb:
|
|
651
|
+
raw_bytes = fb.read()
|
|
652
|
+
_, parse_err = _parse_codex_toml_servers(raw_bytes)
|
|
653
|
+
orig_text = raw_bytes.decode("utf-8", errors="replace")
|
|
654
|
+
from src.installer import AgentInstaller
|
|
655
|
+
if parse_err or AgentInstaller._CODEX_ORPHAN_LINE_RE.search(orig_text):
|
|
656
|
+
shutil.copy2(p, f"{p}.backup")
|
|
657
|
+
cleaned = AgentInstaller._clean_codex_orphans(orig_text)
|
|
658
|
+
try:
|
|
659
|
+
try:
|
|
660
|
+
import tomllib
|
|
661
|
+
tomllib.loads(cleaned)
|
|
662
|
+
except ImportError:
|
|
663
|
+
pass
|
|
664
|
+
with open(p, "w", encoding="utf-8") as f:
|
|
665
|
+
f.write(cleaned)
|
|
666
|
+
fixed.append(f"Repaired TOML syntax/orphans in {p} (backup: {p}.backup)")
|
|
667
|
+
except Exception as e2:
|
|
668
|
+
skipped.append(f"Could not auto-repair {p} ({e2}); manual edit needed")
|
|
669
|
+
except Exception:
|
|
670
|
+
pass
|
|
671
|
+
|
|
672
|
+
# 2. Clean stale legacy tokensafe_tokensafe-mcp schema dir when tokensafe_tokensafe exists
|
|
673
|
+
schemas_dir = cls.get_mcp_schemas_dir()
|
|
674
|
+
if os.path.isdir(schemas_dir):
|
|
675
|
+
legacy_schema = os.path.join(schemas_dir, "tokensafe_tokensafe-mcp")
|
|
676
|
+
canonical_schema = os.path.join(schemas_dir, "tokensafe_tokensafe")
|
|
677
|
+
if os.path.isdir(legacy_schema) and os.path.isdir(canonical_schema):
|
|
678
|
+
try:
|
|
679
|
+
shutil.rmtree(legacy_schema)
|
|
680
|
+
fixed.append("Removed stale legacy MCP schema dir tokensafe_tokensafe-mcp")
|
|
681
|
+
except Exception as exc:
|
|
682
|
+
skipped.append(f"Could not remove {legacy_schema}: {exc}")
|
|
683
|
+
|
|
684
|
+
# 3. Consolidate cross-IDE ghost rule duplicates & strip large dead HTML comment blocks
|
|
685
|
+
ghost = cls.audit_ghost_tokens(root)
|
|
686
|
+
agents_md_path = os.path.join(root, "AGENTS.md")
|
|
687
|
+
has_agents_md = os.path.isfile(agents_md_path)
|
|
688
|
+
pointer_stub = (
|
|
689
|
+
"# TokenSafe Project Rules (Pointer)\n\n"
|
|
690
|
+
"The canonical project rules live in AGENTS.md in this repository — "
|
|
691
|
+
"read that file now and follow it for this repo.\n"
|
|
692
|
+
)
|
|
693
|
+
dead_comment_re = re.compile(r"<!--[\s\S]*?-->")
|
|
694
|
+
for gf in ghost.get("ghost_files", []):
|
|
695
|
+
rel = gf.get("file", "")
|
|
696
|
+
gtype = gf.get("type", "")
|
|
697
|
+
abs_p = os.path.join(root, rel)
|
|
698
|
+
if not rel or not os.path.isfile(abs_p):
|
|
699
|
+
continue
|
|
700
|
+
if gtype == "DUPLICATE_CROSS_IDE_RULE" and has_agents_md and rel != "AGENTS.md":
|
|
701
|
+
try:
|
|
702
|
+
os.makedirs(backup_dir, exist_ok=True)
|
|
703
|
+
bak_target = os.path.join(backup_dir, rel.replace(os.sep, "__") + ".bak")
|
|
704
|
+
shutil.copy2(abs_p, bak_target)
|
|
705
|
+
with open(abs_p, "w", encoding="utf-8") as f:
|
|
706
|
+
f.write(pointer_stub)
|
|
707
|
+
fixed.append(f"Consolidated {rel} -> AGENTS.md pointer (-{gf.get('tokens', 0):,} tok/turn, backup: {bak_target})")
|
|
708
|
+
except Exception as exc:
|
|
709
|
+
skipped.append(f"Failed to consolidate {rel}: {exc}")
|
|
710
|
+
elif gtype == "DEAD_COMMENT_BLOCKS":
|
|
711
|
+
try:
|
|
712
|
+
with open(abs_p, "r", encoding="utf-8", errors="replace") as f:
|
|
713
|
+
txt = f.read()
|
|
714
|
+
# Preserve <!-- tokensafe --> markers; strip large non-tokensafe HTML comment blocks (>300 chars)
|
|
715
|
+
def _strip_dead_comment(m: "re.Match[str]") -> str:
|
|
716
|
+
block = m.group(0)
|
|
717
|
+
if "<!-- tokensafe" in block or "<!-- /tokensafe" in block:
|
|
718
|
+
return block
|
|
719
|
+
return "" if len(block) > 300 else block
|
|
720
|
+
|
|
721
|
+
new_txt = dead_comment_re.sub(_strip_dead_comment, txt)
|
|
722
|
+
new_txt = re.sub(r"\n{3,}", "\n\n", new_txt).strip() + "\n"
|
|
723
|
+
if new_txt != txt:
|
|
724
|
+
os.makedirs(backup_dir, exist_ok=True)
|
|
725
|
+
bak_target = os.path.join(backup_dir, rel.replace(os.sep, "__") + ".bak")
|
|
726
|
+
shutil.copy2(abs_p, bak_target)
|
|
727
|
+
with open(abs_p, "w", encoding="utf-8") as f:
|
|
728
|
+
f.write(new_txt)
|
|
729
|
+
fixed.append(f"Stripped inactive comment blocks in {rel} (backup: {bak_target})")
|
|
730
|
+
except Exception as exc:
|
|
731
|
+
skipped.append(f"Failed to strip comments in {rel}: {exc}")
|
|
732
|
+
|
|
733
|
+
# 4. Cleanup conflicting competitor hooks/rules
|
|
734
|
+
try:
|
|
735
|
+
from src.competitors import CompetitorAuditor
|
|
736
|
+
for c in CompetitorAuditor.audit():
|
|
737
|
+
res = CompetitorAuditor.cleanup(c["id"])
|
|
738
|
+
if res.get("removed"):
|
|
739
|
+
fixed.append(f"Cleaned conflicting {c['name']}: {', '.join(res['removed'])}")
|
|
740
|
+
except Exception:
|
|
741
|
+
pass
|
|
742
|
+
|
|
743
|
+
return {
|
|
744
|
+
"fixed": fixed,
|
|
745
|
+
"skipped": skipped,
|
|
746
|
+
"backup_dir": backup_dir if fixed else None,
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
@classmethod
|
|
750
|
+
def list_skills(cls, workspace_root: Optional[str] = None) -> List[Dict[str, Any]]:
|
|
751
|
+
"""Lists active and disabled skills across all skill roots with source & token estimate."""
|
|
752
|
+
skills: List[Dict[str, Any]] = []
|
|
753
|
+
disabled_plugins = cls._get_disabled_plugin_names()
|
|
754
|
+
plugins_dir = os.path.abspath(cls.get_plugins_dir())
|
|
755
|
+
seen_real = set()
|
|
756
|
+
|
|
757
|
+
for sdir in cls.get_skills_dirs(workspace_root):
|
|
758
|
+
is_plugins_root = os.path.abspath(sdir) == plugins_dir
|
|
759
|
+
for root, dirs, files in os.walk(sdir, followlinks=True):
|
|
760
|
+
real_root = os.path.realpath(root)
|
|
761
|
+
if real_root in seen_real:
|
|
762
|
+
dirs[:] = []
|
|
763
|
+
continue
|
|
764
|
+
seen_real.add(real_root)
|
|
765
|
+
if is_plugins_root and os.path.abspath(root) == plugins_dir:
|
|
766
|
+
dirs[:] = [d for d in dirs if d not in disabled_plugins and not d.endswith(".disabled")]
|
|
767
|
+
else:
|
|
768
|
+
dirs[:] = [d for d in dirs if d not in ("node_modules", ".git", "__pycache__", ".venv", "venv")]
|
|
769
|
+
|
|
770
|
+
if "SKILL.md" in files:
|
|
771
|
+
folder_name = os.path.basename(root)
|
|
772
|
+
is_disabled = folder_name.endswith(".disabled") or ".disabled" + os.sep in root
|
|
773
|
+
clean_name = folder_name[:-9] if folder_name.endswith(".disabled") else folder_name
|
|
774
|
+
desc = ""
|
|
775
|
+
try:
|
|
776
|
+
with open(os.path.join(root, "SKILL.md"), "r", encoding="utf-8", errors="replace") as f:
|
|
777
|
+
head = f.read(1200)
|
|
778
|
+
m_name = re.search(r"(?m)^name:\s*(.+)$", head)
|
|
779
|
+
if m_name and m_name.group(1).strip():
|
|
780
|
+
clean_name = m_name.group(1).strip().strip("'\"")
|
|
781
|
+
m_desc = re.search(r"(?m)^description:\s*(.+)$", head)
|
|
782
|
+
if m_desc:
|
|
783
|
+
raw_desc = m_desc.group(1).strip().strip("'\"")
|
|
784
|
+
if raw_desc in (">", ">-", "|", "|-"):
|
|
785
|
+
after = head[m_desc.end():]
|
|
786
|
+
for next_l in after.splitlines():
|
|
787
|
+
stripped = next_l.strip()
|
|
788
|
+
if stripped and not re.match(r"^[A-Za-z0-9_-]+:\s*", stripped):
|
|
789
|
+
desc = stripped[:90]
|
|
790
|
+
break
|
|
791
|
+
else:
|
|
792
|
+
desc = raw_desc[:90]
|
|
793
|
+
except Exception:
|
|
794
|
+
pass
|
|
795
|
+
skills.append({
|
|
796
|
+
"name": clean_name,
|
|
797
|
+
"dir_name": folder_name[:-9] if folder_name.endswith(".disabled") else folder_name,
|
|
798
|
+
"path": root,
|
|
799
|
+
"root": sdir,
|
|
800
|
+
"disabled": is_disabled,
|
|
801
|
+
"est_tokens": EST_TOKENS_PER_SKILL,
|
|
802
|
+
"description": desc,
|
|
803
|
+
"builtin": "builtin" in root.split(os.sep),
|
|
804
|
+
})
|
|
805
|
+
dirs[:] = []
|
|
806
|
+
return sorted(skills, key=lambda x: (x["disabled"], x["name"].lower()))
|
|
807
|
+
|
|
808
|
+
@classmethod
|
|
809
|
+
def disable_skill(cls, skill_name: str, workspace_root: Optional[str] = None) -> Dict[str, Any]:
|
|
810
|
+
"""Disables a user/workspace skill by renaming its directory to `<name>.disabled`."""
|
|
811
|
+
target = skill_name.strip().lower()
|
|
812
|
+
for sk in cls.list_skills(workspace_root):
|
|
813
|
+
if sk["disabled"]:
|
|
814
|
+
continue
|
|
815
|
+
if sk["name"].lower() == target or sk["dir_name"].lower() == target:
|
|
816
|
+
if sk["builtin"]:
|
|
817
|
+
return {"success": False, "error": f"Skill '{sk['name']}' is a builtin Antigravity skill and cannot be renamed safely."}
|
|
818
|
+
src_path = sk["path"]
|
|
819
|
+
dst_path = f"{src_path}.disabled"
|
|
820
|
+
if os.path.exists(dst_path):
|
|
821
|
+
return {"success": False, "error": f"Target '{dst_path}' already exists."}
|
|
822
|
+
try:
|
|
823
|
+
os.rename(src_path, dst_path)
|
|
824
|
+
return {"success": True, "skill": sk["name"], "path": dst_path}
|
|
825
|
+
except Exception as exc:
|
|
826
|
+
return {"success": False, "error": str(exc)}
|
|
827
|
+
return {"success": False, "error": f"Active skill '{skill_name}' not found."}
|
|
828
|
+
|
|
829
|
+
@classmethod
|
|
830
|
+
def enable_skill(cls, skill_name: str, workspace_root: Optional[str] = None) -> Dict[str, Any]:
|
|
831
|
+
"""Re-enables a previously `.disabled` skill directory."""
|
|
832
|
+
target = skill_name.strip().lower()
|
|
833
|
+
for sk in cls.list_skills(workspace_root):
|
|
834
|
+
if not sk["disabled"]:
|
|
835
|
+
continue
|
|
836
|
+
if sk["name"].lower() == target or sk["dir_name"].lower() == target:
|
|
837
|
+
src_path = sk["path"]
|
|
838
|
+
if not src_path.endswith(".disabled"):
|
|
839
|
+
continue
|
|
840
|
+
dst_path = src_path[:-9]
|
|
841
|
+
if os.path.exists(dst_path):
|
|
842
|
+
return {"success": False, "error": f"Target '{dst_path}' already exists."}
|
|
843
|
+
try:
|
|
844
|
+
os.rename(src_path, dst_path)
|
|
845
|
+
return {"success": True, "skill": sk["name"], "path": dst_path}
|
|
846
|
+
except Exception as exc:
|
|
847
|
+
return {"success": False, "error": str(exc)}
|
|
848
|
+
return {"success": False, "error": f"Disabled skill '{skill_name}' not found."}
|
|
849
|
+
|
|
850
|
+
@classmethod
|
|
851
|
+
def format_skills_report(cls, workspace_root: Optional[str] = None) -> str:
|
|
852
|
+
"""Formats a clean CLI list of active & disabled skills grouped by token overhead."""
|
|
853
|
+
skills = cls.list_skills(workspace_root)
|
|
854
|
+
active = [s for s in skills if not s["disabled"]]
|
|
855
|
+
disabled = [s for s in skills if s["disabled"]]
|
|
856
|
+
lines = [
|
|
857
|
+
f"\n\033[1m\033[36m⚡ TOKENSAFE SKILLS INVENTORY ({len(active)} active, {len(disabled)} disabled) ⚡\033[0m\n",
|
|
858
|
+
f" \033[1mActive Context Overhead:\033[0m ~{len(active) * EST_TOKENS_PER_SKILL:,} tokens/turn (~{EST_TOKENS_PER_SKILL} tok/skill)\n",
|
|
859
|
+
]
|
|
860
|
+
for s in active:
|
|
861
|
+
tag = "\033[2m[builtin]\033[0m" if s["builtin"] else f"\033[2m[{os.path.basename(s['root'])}]\033[0m"
|
|
862
|
+
desc = f" — {s['description']}" if s["description"] else ""
|
|
863
|
+
lines.append(f" \033[32m✔\033[0m \033[1m{s['name']:<28}\033[0m {tag}{desc}")
|
|
864
|
+
if disabled:
|
|
865
|
+
lines.append("\n \033[2mDisabled Skills:\033[0m")
|
|
866
|
+
for s in disabled:
|
|
867
|
+
lines.append(f" \033[2m○ {s['name']:<28} [{os.path.basename(s['root'])}]\033[0m")
|
|
868
|
+
lines.append("\n 💡 Tip: Run \033[36mtokensafe skills disable <name>\033[0m (or \033[36mtokensafe skills enable <name>\033[0m) to manage overhead.\n")
|
|
869
|
+
return "\n".join(lines)
|
|
870
|
+
|
|
573
871
|
@classmethod
|
|
574
872
|
def format_cli_report(cls, workspace_root: Optional[str] = None) -> str:
|
|
575
|
-
"""Formats visual CLI report for tokensafe doctor."""
|
|
873
|
+
"""Formats visual CLI report for tokensafe doctor (pure static environment score)."""
|
|
576
874
|
report = cls.audit(workspace_root)
|
|
875
|
+
q_score: Dict[str, Any] = {}
|
|
577
876
|
score_line = ""
|
|
578
877
|
try:
|
|
579
878
|
from src.quality_score import ContextQualityScore
|
|
580
879
|
from src.governor import ContextBudget
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
880
|
+
window = ContextBudget.resolve_window()
|
|
881
|
+
static_overhead = (
|
|
882
|
+
int(report.get("total_static_tokens_per_turn", 0) or 0)
|
|
883
|
+
+ int((report.get("ghost_tokens") or {}).get("ghost_tokens_per_turn", 0) or 0)
|
|
884
|
+
+ int((report.get("rules") or {}).get("total_tokens", 0) or 0)
|
|
885
|
+
)
|
|
886
|
+
used_pct = round(min(100.0, (static_overhead / window) * 100.0), 1) if window > 0 else 0.0
|
|
887
|
+
static_budget = {
|
|
888
|
+
"used_estimated": static_overhead,
|
|
889
|
+
"window_tokens": window,
|
|
890
|
+
"used_pct": used_pct,
|
|
891
|
+
}
|
|
892
|
+
q_score = ContextQualityScore.calculate(budget=static_budget, audit=report)
|
|
584
893
|
color = "\033[32m" if q_score["grade"] in ("S", "A") else ("\033[33m" if q_score["grade"] == "B" else "\033[31m")
|
|
585
|
-
score_line =
|
|
894
|
+
score_line = (
|
|
895
|
+
f" \033[1mEnvironment Quality Score:\033[0m {color}\033[1mGrade {q_score['grade']} ({q_score['label']})\033[0m "
|
|
896
|
+
f"— {q_score['headroom_pct']:.1f}% fresh-turn headroom, {q_score['score']}/100 pts\n"
|
|
897
|
+
)
|
|
586
898
|
except Exception:
|
|
587
899
|
score_line = ""
|
|
588
900
|
|
|
@@ -607,6 +919,11 @@ class EnvironmentAuditor:
|
|
|
607
919
|
lines.append(f" {status}")
|
|
608
920
|
|
|
609
921
|
lines.append(f"\n \033[1mInstalled Skills:\033[0m {report['total_skills']} skills (~{report['skills_tokens_per_turn']:,} tokens/turn)")
|
|
922
|
+
if report["total_skills"] >= 15 and report.get("skills_breakdown"):
|
|
923
|
+
for sdir, cnt in sorted(report["skills_breakdown"].items(), key=lambda kv: -kv[1])[:4]:
|
|
924
|
+
lines.append(f" \033[2m• {sdir}: {cnt} skill(s)\033[0m")
|
|
925
|
+
if report["skills_tokens_per_turn"] >= 4000:
|
|
926
|
+
lines.append(" \033[36m💡 Tip: Run 'tokensafe skills list' and 'tokensafe skills disable <name>' to trim unused skills\033[0m")
|
|
610
927
|
|
|
611
928
|
rules = report.get("rules") or {}
|
|
612
929
|
if rules.get("files"):
|
|
@@ -623,6 +940,12 @@ class EnvironmentAuditor:
|
|
|
623
940
|
missing_str = ", ".join(ts.get("missing", []))
|
|
624
941
|
lines.append(f" \033[1mAST Engines (Tree-sitter):\033[0m \033[33m⚠ {ts['active']}/{ts['total']} active (missing: {missing_str})\033[0m")
|
|
625
942
|
|
|
943
|
+
config_issues = report.get("config_issues") or []
|
|
944
|
+
if config_issues:
|
|
945
|
+
lines.append("\n \033[33m\033[1m⚠ Config / Schema Issues Detected:\033[0m")
|
|
946
|
+
for ci in config_issues:
|
|
947
|
+
lines.append(f" • {ci['description']}")
|
|
948
|
+
|
|
626
949
|
ghost = report.get("ghost_tokens") or {}
|
|
627
950
|
if ghost.get("has_ghost_tokens"):
|
|
628
951
|
lines.append(f"\n \033[33m\033[1m👻 Ghost Tokens Detected:\033[0m ~{ghost['ghost_tokens_per_turn']:,} wasted tokens per turn")
|
|
@@ -632,12 +955,20 @@ class EnvironmentAuditor:
|
|
|
632
955
|
else:
|
|
633
956
|
lines.append("\n \033[32m✔ No Ghost Tokens detected: Rule files and configs are lean.\033[0m")
|
|
634
957
|
|
|
635
|
-
|
|
636
|
-
|
|
958
|
+
has_auto_fixable = bool(ghost.get("has_ghost_tokens") or config_issues)
|
|
959
|
+
low_grade = q_score.get("grade") in ("C", "F")
|
|
960
|
+
if report["has_critical_bloat"] or has_auto_fixable or rules.get("budget_exceeded") or low_grade:
|
|
961
|
+
lines.append("\n \033[33m\033[1mDiagnostic Recommendations:\033[0m")
|
|
637
962
|
for b in report["bloated_servers"]:
|
|
638
963
|
lines.append(f" ➜ Run: \033[36mtokensafe mcp disable {b['name']}\033[0m to save ~{b['est_tokens_per_turn']:,} tokens per turn!")
|
|
964
|
+
if has_auto_fixable:
|
|
965
|
+
lines.append(" ➜ Run: \033[36mtokensafe doctor --fix\033[0m to repair configs & consolidate ghost rule duplicates (with backups)")
|
|
966
|
+
if report["skills_tokens_per_turn"] >= 4000:
|
|
967
|
+
lines.append(f" ➜ Run: \033[36mtokensafe skills list\033[0m (currently {report['total_skills']} skills ≈ ~{report['skills_tokens_per_turn']:,} tok/turn; disable unused via \033[36mtokensafe skills disable <name>\033[0m)")
|
|
968
|
+
if q_score.get("headroom_pct", 100.0) < 35.0:
|
|
969
|
+
lines.append(" ➜ Run: \033[36mtokensafe budget\033[0m to inspect live session context usage")
|
|
639
970
|
else:
|
|
640
|
-
lines.append("\n \033[32m✔ Environment healthy: No critical
|
|
971
|
+
lines.append("\n \033[32m✔ Environment healthy: No critical context bloat detected.\033[0m")
|
|
641
972
|
|
|
642
973
|
lines.append("")
|
|
643
974
|
return "\n".join(lines)
|
package/src/installer.py
CHANGED
|
@@ -113,7 +113,7 @@ AGENTS_REGISTRY = {
|
|
|
113
113
|
"type": "mcp_json",
|
|
114
114
|
"config_path": _app_data_dir("Code", "User", "globalStorage", "saoudrizwan.claude-dev", "settings", "cline_mcp_settings.json"),
|
|
115
115
|
"rules_path": _app_data_dir("Code", "User", "globalStorage", "saoudrizwan.claude-dev", "settings", "Rule_TokenSafe.md"),
|
|
116
|
-
"detect_path": _app_data_dir("Code")
|
|
116
|
+
"detect_path": _app_data_dir("Code", "User", "globalStorage", "saoudrizwan.claude-dev")
|
|
117
117
|
},
|
|
118
118
|
"claude_code": {
|
|
119
119
|
"name": "Claude Code CLI",
|
|
@@ -159,27 +159,188 @@ AGENTS_REGISTRY = {
|
|
|
159
159
|
}
|
|
160
160
|
}
|
|
161
161
|
|
|
162
|
+
_DEFAULT_DETECT_PATHS = {k: v["detect_path"] for k, v in AGENTS_REGISTRY.items()}
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _has_vscode_extension(prefixes: Tuple[str, ...]) -> bool:
|
|
166
|
+
ext_root = os.path.join(HOME, ".vscode", "extensions")
|
|
167
|
+
if os.path.isdir(ext_root):
|
|
168
|
+
try:
|
|
169
|
+
for entry in os.listdir(ext_root):
|
|
170
|
+
low = entry.lower()
|
|
171
|
+
if any(low.startswith(p) for p in prefixes):
|
|
172
|
+
return True
|
|
173
|
+
except OSError:
|
|
174
|
+
pass
|
|
175
|
+
return False
|
|
176
|
+
|
|
177
|
+
|
|
162
178
|
class AgentInstaller:
|
|
163
179
|
"""Manages multi-agent detection and configuration injection."""
|
|
164
180
|
|
|
181
|
+
_CODEX_SECTION_RE = re.compile(
|
|
182
|
+
r'(?ms)^\[mcp_servers\.tokensafe\]\s*\n(?:(?!^\[{1,2}\s*(?!["\']?(?:/|[A-Za-z]:\\))[A-Za-z0-9_."\' -]+\]{1,2}\s*(?:#.*)?$).)*'
|
|
183
|
+
)
|
|
184
|
+
_CODEX_ORPHAN_LINE_RE = re.compile(r'(?m)^\s*\["[^"\n]*(?:mcp_server\.py|tokensafe[^"\n]*)"\]\s*\n?')
|
|
185
|
+
|
|
186
|
+
@classmethod
|
|
187
|
+
def _clean_codex_orphans(cls, content: str) -> str:
|
|
188
|
+
"""Removes orphaned array lines left by legacy Codex TOML regex bugs."""
|
|
189
|
+
return cls._CODEX_ORPHAN_LINE_RE.sub("", content)
|
|
190
|
+
|
|
191
|
+
@classmethod
|
|
192
|
+
def _is_real_agent_installed(cls, key: str, info: Dict[str, Any]) -> bool:
|
|
193
|
+
"""Checks genuine IDE/CLI installation artifacts rather than empty/installer-created dirs."""
|
|
194
|
+
detect_path = info.get("detect_path", "")
|
|
195
|
+
if detect_path != _DEFAULT_DETECT_PATHS.get(key):
|
|
196
|
+
return bool(detect_path and os.path.exists(detect_path))
|
|
197
|
+
|
|
198
|
+
if key == "antigravity":
|
|
199
|
+
return any((
|
|
200
|
+
os.path.exists("/Applications/Antigravity.app"),
|
|
201
|
+
os.path.exists("/Applications/Antigravity IDE.app"),
|
|
202
|
+
os.path.exists(os.path.join(HOME, "Applications", "Antigravity.app")),
|
|
203
|
+
os.path.exists(os.path.join(HOME, ".gemini", "antigravity")),
|
|
204
|
+
os.path.exists(os.path.join(HOME, ".gemini", "antigravity-ide")),
|
|
205
|
+
shutil.which("agy") is not None,
|
|
206
|
+
))
|
|
207
|
+
if key == "claude_desktop":
|
|
208
|
+
return any((
|
|
209
|
+
os.path.exists("/Applications/Claude.app"),
|
|
210
|
+
os.path.exists(os.path.join(HOME, "Applications", "Claude.app")),
|
|
211
|
+
os.path.exists(_app_data_dir("Claude", "claude_desktop_config.json")),
|
|
212
|
+
os.path.exists(_app_data_dir("Claude", "IndexedDB")),
|
|
213
|
+
os.path.exists(_app_data_dir("Claude", "Session Storage")),
|
|
214
|
+
))
|
|
215
|
+
if key == "cursor":
|
|
216
|
+
if sys.platform == "darwin":
|
|
217
|
+
return any((
|
|
218
|
+
os.path.exists("/Applications/Cursor.app"),
|
|
219
|
+
os.path.exists(os.path.join(HOME, "Applications", "Cursor.app")),
|
|
220
|
+
shutil.which("cursor") is not None,
|
|
221
|
+
))
|
|
222
|
+
return any((
|
|
223
|
+
os.path.exists(_app_data_dir("Cursor")),
|
|
224
|
+
os.path.exists(os.path.join(HOME, ".cursor", "projects")),
|
|
225
|
+
shutil.which("cursor") is not None,
|
|
226
|
+
))
|
|
227
|
+
if key == "windsurf":
|
|
228
|
+
if sys.platform == "darwin":
|
|
229
|
+
return any((
|
|
230
|
+
os.path.exists("/Applications/Windsurf.app"),
|
|
231
|
+
os.path.exists(os.path.join(HOME, "Applications", "Windsurf.app")),
|
|
232
|
+
shutil.which("windsurf") is not None,
|
|
233
|
+
))
|
|
234
|
+
return any((
|
|
235
|
+
os.path.exists(_app_data_dir("Windsurf")),
|
|
236
|
+
os.path.exists(os.path.join(HOME, ".codeium", "windsurf", "User")),
|
|
237
|
+
os.path.exists(os.path.join(HOME, ".codeium", "windsurf", "globalStorage")),
|
|
238
|
+
shutil.which("windsurf") is not None,
|
|
239
|
+
))
|
|
240
|
+
if key == "cline":
|
|
241
|
+
# Require the actual installed extension (not bare VS Code or deleted globalStorage).
|
|
242
|
+
return _has_vscode_extension(("saoudrizwan.claude-dev", "rooveterinaryinc.roo-cline"))
|
|
243
|
+
if key == "claude_code":
|
|
244
|
+
return any((
|
|
245
|
+
shutil.which("claude") is not None,
|
|
246
|
+
os.path.exists(os.path.join(HOME, ".claude", "projects")),
|
|
247
|
+
os.path.exists(os.path.join(HOME, ".claude", "statsig")),
|
|
248
|
+
os.path.exists(os.path.join(HOME, ".claude", ".credentials.json")),
|
|
249
|
+
))
|
|
250
|
+
if key == "codex":
|
|
251
|
+
codex_dir = os.path.join(HOME, ".codex")
|
|
252
|
+
has_logs = os.path.isdir(codex_dir) and any(
|
|
253
|
+
n.startswith("logs") or n in ("auth.json", "sessions", "history.jsonl")
|
|
254
|
+
for n in os.listdir(codex_dir)
|
|
255
|
+
)
|
|
256
|
+
return any((
|
|
257
|
+
os.path.exists("/Applications/Codex.app"),
|
|
258
|
+
os.path.exists(os.path.join(HOME, "Applications", "Codex.app")),
|
|
259
|
+
shutil.which("codex") is not None,
|
|
260
|
+
has_logs,
|
|
261
|
+
))
|
|
262
|
+
if key == "copilot":
|
|
263
|
+
return any((
|
|
264
|
+
shutil.which("github-copilot-cli") is not None,
|
|
265
|
+
shutil.which("copilot") is not None,
|
|
266
|
+
os.path.exists(os.path.join(HOME, ".local", "share", "gh", "extensions", "gh-copilot")),
|
|
267
|
+
_has_vscode_extension(("github.copilot",)),
|
|
268
|
+
))
|
|
269
|
+
if key == "zcode":
|
|
270
|
+
return any((
|
|
271
|
+
os.path.exists("/Applications/ZCode.app"),
|
|
272
|
+
os.path.exists(os.path.join(HOME, "Applications", "ZCode.app")),
|
|
273
|
+
os.path.exists(os.path.join(HOME, ".zcode", "v2")),
|
|
274
|
+
os.path.exists(os.path.join(HOME, ".zcode", "workspace")),
|
|
275
|
+
shutil.which("zcode") is not None,
|
|
276
|
+
))
|
|
277
|
+
if key == "kimi":
|
|
278
|
+
return any((
|
|
279
|
+
os.path.exists("/Applications/Kimi Code.app"),
|
|
280
|
+
os.path.exists(os.path.join(HOME, "Applications", "Kimi Code.app")),
|
|
281
|
+
os.path.exists(os.path.join(HOME, ".kimi-code", "sessions")),
|
|
282
|
+
os.path.exists(os.path.join(HOME, ".kimi-code", "oauth")),
|
|
283
|
+
shutil.which("kimi") is not None,
|
|
284
|
+
))
|
|
285
|
+
return bool(detect_path and os.path.exists(detect_path))
|
|
286
|
+
|
|
287
|
+
@classmethod
|
|
288
|
+
def _is_agent_configured(cls, key: str, info: Dict[str, Any]) -> bool:
|
|
289
|
+
"""True if TokenSafe MCP/plugin is currently wired into this agent."""
|
|
290
|
+
if info.get("type") == "plugin":
|
|
291
|
+
t = info.get("target_path", "")
|
|
292
|
+
return bool(t and os.path.exists(t))
|
|
293
|
+
if key == "codex":
|
|
294
|
+
p = info.get("config_path", "")
|
|
295
|
+
if os.path.isfile(p):
|
|
296
|
+
try:
|
|
297
|
+
return "[mcp_servers.tokensafe]" in open(p, "r", encoding="utf-8", errors="replace").read()
|
|
298
|
+
except Exception:
|
|
299
|
+
return False
|
|
300
|
+
return False
|
|
301
|
+
if key == "zcode":
|
|
302
|
+
p = info.get("config_path", "")
|
|
303
|
+
if os.path.isfile(p):
|
|
304
|
+
try:
|
|
305
|
+
d = json.load(open(p, "r", encoding="utf-8"))
|
|
306
|
+
return "tokensafe" in ((d.get("mcp") or {}).get("servers") or {})
|
|
307
|
+
except Exception:
|
|
308
|
+
return False
|
|
309
|
+
return False
|
|
310
|
+
p = info.get("config_path", "")
|
|
311
|
+
if os.path.isfile(p):
|
|
312
|
+
try:
|
|
313
|
+
d = json.load(open(p, "r", encoding="utf-8"))
|
|
314
|
+
return "tokensafe" in (d.get("mcpServers") or {})
|
|
315
|
+
except Exception:
|
|
316
|
+
return False
|
|
317
|
+
return False
|
|
318
|
+
|
|
319
|
+
@classmethod
|
|
320
|
+
def refresh_installed_agents(cls) -> Dict[str, Any]:
|
|
321
|
+
"""Re-synchronizes MCP, plugins, skills, rules, and hooks for genuinely installed or already-configured agents."""
|
|
322
|
+
agents = cls.detect_available_agents()
|
|
323
|
+
synced_count = 0
|
|
324
|
+
details: Dict[str, Any] = {}
|
|
325
|
+
for key, info in agents.items():
|
|
326
|
+
if info.get("installed") or cls._is_agent_configured(key, info):
|
|
327
|
+
ok, msg = cls.install_mcp_config(key)
|
|
328
|
+
if ok:
|
|
329
|
+
h_ok, h_msg = cls.install_hooks_config(key)
|
|
330
|
+
if h_ok:
|
|
331
|
+
msg = f"{msg}; {h_msg}"
|
|
332
|
+
synced_count += 1
|
|
333
|
+
details[key] = {"name": info["name"], "success": ok, "message": msg}
|
|
334
|
+
return {"synced_count": synced_count, "agents": details}
|
|
335
|
+
|
|
165
336
|
@classmethod
|
|
166
337
|
def detect_available_agents(cls) -> Dict[str, Dict[str, Any]]:
|
|
167
|
-
"""Scans filesystem to find which AI agent platforms are installed."""
|
|
338
|
+
"""Scans filesystem to find which AI agent platforms are genuinely installed."""
|
|
168
339
|
detected = {}
|
|
169
340
|
for key, info in AGENTS_REGISTRY.items():
|
|
170
|
-
is_present = os.path.exists(info["detect_path"])
|
|
171
|
-
# Fallback for cursor / windsurf on macOS
|
|
172
|
-
if not is_present and key == "cursor":
|
|
173
|
-
is_present = os.path.exists(os.path.join(HOME, "Library", "Application Support", "Cursor"))
|
|
174
|
-
if not is_present and key == "kimi":
|
|
175
|
-
is_present = (
|
|
176
|
-
os.path.exists("/Applications/Kimi Code.app")
|
|
177
|
-
or os.path.exists(os.path.join(HOME, "Applications", "Kimi Code.app"))
|
|
178
|
-
or shutil.which("kimi") is not None
|
|
179
|
-
)
|
|
180
341
|
detected[key] = {
|
|
181
342
|
**info,
|
|
182
|
-
"installed":
|
|
343
|
+
"installed": cls._is_real_agent_installed(key, info)
|
|
183
344
|
}
|
|
184
345
|
return detected
|
|
185
346
|
|
|
@@ -256,8 +417,16 @@ class AgentInstaller:
|
|
|
256
417
|
return f'[[hooks]]\nevent = "{event}"\n{m}command = {toml_hook_cmd}\ntimeout = 10\n'
|
|
257
418
|
|
|
258
419
|
if "kimi_hook.py" in content:
|
|
259
|
-
#
|
|
420
|
+
# Refresh command path/interpreter on upgrade + add missing events.
|
|
260
421
|
migrated = False
|
|
422
|
+
new_content, cmd_replacements = re.subn(
|
|
423
|
+
r'(?m)^command\s*=\s*".*kimi_hook\.py[^"\n]*"\s*$',
|
|
424
|
+
f'command = {toml_hook_cmd}',
|
|
425
|
+
content,
|
|
426
|
+
)
|
|
427
|
+
if new_content != content and cmd_replacements > 0:
|
|
428
|
+
content = new_content
|
|
429
|
+
migrated = True
|
|
261
430
|
if 'event = "PostToolUse"' not in content:
|
|
262
431
|
content = content.rstrip() + "\n\n# TokenSafe PostToolUse stdout compaction (migration)\n" + _kimi_section("PostToolUse")
|
|
263
432
|
migrated = True
|
|
@@ -271,7 +440,7 @@ class AgentInstaller:
|
|
|
271
440
|
return True, "TokenSafe Kimi Code hooks already registered in config.toml"
|
|
272
441
|
with open(config_file, "w", encoding="utf-8") as f:
|
|
273
442
|
f.write(content)
|
|
274
|
-
return True, "Kimi Code hooks
|
|
443
|
+
return True, "Kimi Code hooks updated in ~/.kimi-code/config.toml (Edit/PostToolUse/Stop)"
|
|
275
444
|
|
|
276
445
|
hook_sections = (
|
|
277
446
|
'\n# TokenSafe Lifecycle Hooks\n'
|
|
@@ -1334,10 +1503,10 @@ WantedBy=default.target
|
|
|
1334
1503
|
f'args = [{toml_srv}]\n'
|
|
1335
1504
|
)
|
|
1336
1505
|
|
|
1506
|
+
content = cls._clean_codex_orphans(content)
|
|
1337
1507
|
if re.search(r'(?m)^\[mcp_servers\.tokensafe\]\s*$', content):
|
|
1338
|
-
# Replace the entire section up to the next TOML table header or EOF (
|
|
1339
|
-
|
|
1340
|
-
content = pattern.sub(lambda _: server_section + "\n", content)
|
|
1508
|
+
# Replace the entire section up to the next valid TOML table header or EOF (never stop at array items like ["/path/..."]).
|
|
1509
|
+
content = cls._CODEX_SECTION_RE.sub(lambda _: server_section + "\n", content)
|
|
1341
1510
|
else:
|
|
1342
1511
|
content = (content.rstrip() + "\n\n" + server_section) if content.strip() else server_section
|
|
1343
1512
|
|
|
@@ -1587,10 +1756,10 @@ WantedBy=default.target
|
|
|
1587
1756
|
try:
|
|
1588
1757
|
with open(config_file, "r", encoding="utf-8") as f:
|
|
1589
1758
|
content = f.read()
|
|
1590
|
-
if re.search(r'(?m)^\[mcp_servers\.tokensafe\]\s*$', content):
|
|
1759
|
+
if re.search(r'(?m)^\[mcp_servers\.tokensafe\]\s*$', content) or cls._CODEX_ORPHAN_LINE_RE.search(content):
|
|
1591
1760
|
shutil.copy2(config_file, f"{config_file}.backup")
|
|
1592
|
-
|
|
1593
|
-
content =
|
|
1761
|
+
content = cls._clean_codex_orphans(content)
|
|
1762
|
+
content = cls._CODEX_SECTION_RE.sub("", content)
|
|
1594
1763
|
with open(config_file, "w", encoding="utf-8") as f:
|
|
1595
1764
|
f.write(content.strip() + "\n" if content.strip() else "")
|
|
1596
1765
|
except Exception:
|
|
@@ -2552,21 +2721,30 @@ WantedBy=default.target
|
|
|
2552
2721
|
else:
|
|
2553
2722
|
print(f" {YELLOW}⚠{RESET} npm not found — skipping npm channel.")
|
|
2554
2723
|
|
|
2555
|
-
# 3. Check pip
|
|
2556
|
-
|
|
2557
|
-
|
|
2724
|
+
# 3. Check pip (prefer current interpreter's pip, fallback to pip3/pip)
|
|
2725
|
+
pip_cmds: List[List[str]] = [[sys.executable, "-m", "pip"]]
|
|
2726
|
+
pip_bin = shutil.which("pip3") or shutil.which("pip")
|
|
2727
|
+
if pip_bin:
|
|
2728
|
+
pip_cmds.append([pip_bin])
|
|
2729
|
+
upgraded_pip = False
|
|
2730
|
+
seen_pip_bins = set()
|
|
2731
|
+
for pip_base in pip_cmds:
|
|
2732
|
+
if upgraded_pip:
|
|
2733
|
+
break
|
|
2558
2734
|
try:
|
|
2559
|
-
res = subprocess.run([
|
|
2560
|
-
if "tokensafe" in res.stdout:
|
|
2561
|
-
print(f" {CYAN}→{RESET} Updating Python package ({
|
|
2562
|
-
up_res = subprocess.run([
|
|
2735
|
+
res = subprocess.run([*pip_base, "list"], capture_output=True, text=True, timeout=15)
|
|
2736
|
+
if "tokensafe" in (res.stdout or ""):
|
|
2737
|
+
print(f" {CYAN}→{RESET} Updating Python package ({' '.join(pip_base)} install --upgrade tokensafe)...")
|
|
2738
|
+
up_res = subprocess.run([*pip_base, "install", "--upgrade", "tokensafe"], capture_output=True, text=True, timeout=120)
|
|
2563
2739
|
if up_res.returncode == 0:
|
|
2564
2740
|
print(f" {GREEN}✔{RESET} Python package upgraded successfully.")
|
|
2741
|
+
upgraded_pip = True
|
|
2565
2742
|
else:
|
|
2566
2743
|
detail = (up_res.stderr or up_res.stdout or "").strip()[:200]
|
|
2567
2744
|
print(f" {YELLOW}⚠{RESET} pip upgrade failed: {detail}")
|
|
2568
2745
|
except Exception as e:
|
|
2569
2746
|
print(f" {YELLOW}⚠{RESET} pip update skipped: {e}")
|
|
2747
|
+
pip_cmd = pip_bin
|
|
2570
2748
|
|
|
2571
2749
|
# 3b. Check and upgrade TokenSafe ecosystem packages (Frontend & Backend)
|
|
2572
2750
|
print(f"\n {CYAN}→{RESET} Checking TokenSafe Ecosystem packages (UI & Backend)...")
|
|
@@ -2625,22 +2803,54 @@ WantedBy=default.target
|
|
|
2625
2803
|
except Exception:
|
|
2626
2804
|
pass
|
|
2627
2805
|
|
|
2628
|
-
# 4. Re-synchronize
|
|
2629
|
-
|
|
2806
|
+
# 4. Re-synchronize active/configured agents using the FRESHLY upgraded binary when available
|
|
2807
|
+
# (so plugins, hooks, skills, and rules come from the new release instead of the old process).
|
|
2808
|
+
print(f"\n {CYAN}→{RESET} Re-synchronizing AI Agent plugins, hooks, MCP configs & rules...")
|
|
2809
|
+
fresh_bin = None
|
|
2810
|
+
for npm_bin in upgraded_npm_bins:
|
|
2811
|
+
cand_bin = os.path.join(os.path.dirname(npm_bin), "tokensafe.cmd" if os.name == "nt" else "tokensafe")
|
|
2812
|
+
if os.path.isfile(cand_bin) and os.access(cand_bin, os.X_OK):
|
|
2813
|
+
fresh_bin = cand_bin
|
|
2814
|
+
break
|
|
2815
|
+
if not fresh_bin:
|
|
2816
|
+
fresh_bin = shutil.which("tokensafe")
|
|
2817
|
+
|
|
2630
2818
|
agents = cls.detect_available_agents()
|
|
2631
2819
|
synced_count = 0
|
|
2632
|
-
|
|
2633
|
-
|
|
2634
|
-
|
|
2635
|
-
|
|
2636
|
-
|
|
2637
|
-
|
|
2638
|
-
|
|
2639
|
-
|
|
2640
|
-
|
|
2641
|
-
|
|
2820
|
+
if fresh_bin and (upgraded_npm_bins or upgraded_pip) and agents:
|
|
2821
|
+
try:
|
|
2822
|
+
sync_env = cls._npm_subprocess_env(fresh_bin)
|
|
2823
|
+
ref_res = subprocess.run(
|
|
2824
|
+
[fresh_bin, "install", "--refresh"],
|
|
2825
|
+
env=sync_env,
|
|
2826
|
+
capture_output=True,
|
|
2827
|
+
text=True,
|
|
2828
|
+
timeout=30,
|
|
2829
|
+
)
|
|
2830
|
+
if ref_res.returncode == 0:
|
|
2831
|
+
m_cnt = re.search(r"Synchronized\s+(\d+)", ref_res.stdout or "")
|
|
2832
|
+
synced_count = int(m_cnt.group(1)) if m_cnt else sum(1 for _, i in agents.items() if i.get("installed"))
|
|
2833
|
+
print(f" {GREEN}✔{RESET} Refreshed {synced_count} agent environment(s) via upgraded binary ({fresh_bin}).")
|
|
2642
2834
|
else:
|
|
2643
|
-
|
|
2835
|
+
ref_res = None
|
|
2836
|
+
except Exception:
|
|
2837
|
+
ref_res = None
|
|
2838
|
+
if ref_res is None:
|
|
2839
|
+
refresh_res = cls.refresh_installed_agents()
|
|
2840
|
+
synced_count = refresh_res["synced_count"]
|
|
2841
|
+
else:
|
|
2842
|
+
for key, info in agents.items():
|
|
2843
|
+
if info["installed"] or cls._is_agent_configured(key, info):
|
|
2844
|
+
ok, msg = cls.install_mcp_config(key)
|
|
2845
|
+
if ok:
|
|
2846
|
+
h_ok, h_msg = cls.install_hooks_config(key)
|
|
2847
|
+
if h_ok:
|
|
2848
|
+
msg = f"{msg}; {h_msg}"
|
|
2849
|
+
if ok:
|
|
2850
|
+
print(f" {GREEN}✔{RESET} {info['name']}: {msg}")
|
|
2851
|
+
synced_count += 1
|
|
2852
|
+
else:
|
|
2853
|
+
print(f" {YELLOW}⚠{RESET} {info['name']}: {msg}")
|
|
2644
2854
|
|
|
2645
2855
|
# 5. Refresh local version cache and report the newly installed version in a fresh process
|
|
2646
2856
|
try:
|
|
@@ -2651,14 +2861,7 @@ WantedBy=default.target
|
|
|
2651
2861
|
except Exception:
|
|
2652
2862
|
pass
|
|
2653
2863
|
try:
|
|
2654
|
-
tokensafe_bin =
|
|
2655
|
-
for npm_bin in upgraded_npm_bins:
|
|
2656
|
-
cand_bin = os.path.join(os.path.dirname(npm_bin), "tokensafe.cmd" if os.name == "nt" else "tokensafe")
|
|
2657
|
-
if os.path.isfile(cand_bin) and os.access(cand_bin, os.X_OK):
|
|
2658
|
-
tokensafe_bin = cand_bin
|
|
2659
|
-
break
|
|
2660
|
-
if not tokensafe_bin:
|
|
2661
|
-
tokensafe_bin = shutil.which("tokensafe")
|
|
2864
|
+
tokensafe_bin = fresh_bin or shutil.which("tokensafe")
|
|
2662
2865
|
sync_cmd = [tokensafe_bin, "version", "--check"] if tokensafe_bin else [sys.executable, os.path.join(PROJECT_ROOT, "src", "cli.py"), "version", "--check"]
|
|
2663
2866
|
sync_env = cls._npm_subprocess_env(tokensafe_bin) if tokensafe_bin else None
|
|
2664
2867
|
subprocess.run(sync_cmd, env=sync_env, capture_output=True, text=True, timeout=5)
|
|
@@ -2675,12 +2878,7 @@ WantedBy=default.target
|
|
|
2675
2878
|
# route for every wire-able agent. Agent/app updates are known to rewrite
|
|
2676
2879
|
# their own configs and drop third-party routing, so after every update we
|
|
2677
2880
|
# reinstall the daemon with the FRESH engine binary and re-claim the wiring.
|
|
2678
|
-
ensure_bin =
|
|
2679
|
-
for npm_bin in upgraded_npm_bins:
|
|
2680
|
-
cand_bin = os.path.join(os.path.dirname(npm_bin), "tokensafe.cmd" if os.name == "nt" else "tokensafe")
|
|
2681
|
-
if os.path.isfile(cand_bin) and os.access(cand_bin, os.X_OK):
|
|
2682
|
-
ensure_bin = cand_bin
|
|
2683
|
-
break
|
|
2881
|
+
ensure_bin = fresh_bin
|
|
2684
2882
|
cls._ensure_proxy_default("update", fresh_bin=ensure_bin)
|
|
2685
2883
|
|
|
2686
2884
|
print(f"\n{BOLD}{GREEN}✅ Self-update complete!{RESET}")
|
package/src/mcp_server.py
CHANGED
package/src/syntax_guard.py
CHANGED
package/src/telemetry_sync.py
CHANGED
|
@@ -249,7 +249,7 @@ class TelemetrySync:
|
|
|
249
249
|
current_last_id = last_id
|
|
250
250
|
headers = {
|
|
251
251
|
"Content-Type": "application/json",
|
|
252
|
-
"User-Agent": "TokenSafe-Sync/4.5.
|
|
252
|
+
"User-Agent": "TokenSafe-Sync/4.5.5"
|
|
253
253
|
}
|
|
254
254
|
if active_key:
|
|
255
255
|
headers["Authorization"] = f"Bearer {active_key}"
|
package/src/version_checker.py
CHANGED
|
@@ -17,7 +17,7 @@ import urllib.request
|
|
|
17
17
|
import urllib.error
|
|
18
18
|
from typing import Dict, Any, Optional, Tuple
|
|
19
19
|
|
|
20
|
-
CURRENT_VERSION = "4.5.
|
|
20
|
+
CURRENT_VERSION = "4.5.5"
|
|
21
21
|
CACHE_TTL = 86400 # 24 hours
|
|
22
22
|
# When the cloud is unreachable we must NOT cache the synthesized "up to date"
|
|
23
23
|
# answer for a full day — otherwise an update released right after an outage
|