tokensafe 4.5.3 → 4.5.4

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.
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "4.5.3",
2
+ "version": "4.5.4",
3
3
  "name": "tokensafe",
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
  "author": {
package/kimi.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokensafe",
3
- "version": "4.5.3",
3
+ "version": "4.5.4",
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.3",
4
+ "version": "4.5.4",
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.3",
4
+ "version": "4.5.4",
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.3",
6
+ "version": "4.5.4",
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.3",
26
+ "version": "4.5.4",
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.3",
42
+ "version": "4.5.4",
43
43
  "runtimeHint": "uvx",
44
44
  "transport": {
45
45
  "type": "stdio"
package/src/cli.py CHANGED
@@ -422,6 +422,9 @@ def main(argv: Optional[List[str]] = None):
422
422
  agents_plugin = args[idx + 1]
423
423
  res = AgentInstaller.install_project(os.getcwd(), agents_plugin_path=agents_plugin)
424
424
  print(f"\n\033[32m✔ TokenSafe rules injected into project: {', '.join(res['created_rules'])}\033[0m\n")
425
+ elif "--refresh" in args or "--sync-installed" in args:
426
+ res = AgentInstaller.refresh_installed_agents()
427
+ print(f"\n\033[32m✔ Synchronized {res['synced_count']} installed/configured agent environment(s).\033[0m\n")
425
428
  else:
426
429
  AgentInstaller.run_interactive()
427
430
 
@@ -927,9 +930,21 @@ def main(argv: Optional[List[str]] = None):
927
930
 
928
931
  elif command in ("doctor", "audit", "tax"):
929
932
  from src.environment_auditor import EnvironmentAuditor
933
+ from src.competitors import CompetitorAuditor
934
+
935
+ if "--fix" in args:
936
+ print("\n\033[1m\033[36m🔧 TOKENSAFE ENVIRONMENT AUTO-FIX 🔧\033[0m\n")
937
+ fix_res = EnvironmentAuditor.auto_fix()
938
+ for item in fix_res.get("fixed", []):
939
+ print(f" \033[32m✔\033[0m {item}")
940
+ for item in fix_res.get("skipped", []):
941
+ print(f" \033[33m⚠\033[0m {item}")
942
+ if not fix_res.get("fixed") and not fix_res.get("skipped"):
943
+ print(" \033[32m✔\033[0m No auto-fixable config or ghost-token issues found.")
944
+ print()
945
+
930
946
  print(EnvironmentAuditor.format_cli_report())
931
947
 
932
- from src.competitors import CompetitorAuditor
933
948
  conflicts = CompetitorAuditor.audit()
934
949
  if conflicts:
935
950
  print("\n\033[1m\033[33m⚡ DETECTED CONFLICTING OR STALE TOOLS ⚡\033[0m")
@@ -938,7 +953,7 @@ def main(argv: Optional[List[str]] = None):
938
953
  for tr in c['traces']:
939
954
  loc = tr.get('path') or tr.get('file') or tr.get('config')
940
955
  print(f" - {tr['kind']}: {loc}")
941
- print("\n 💡 Tip: Run 'tokensafe doctor --cleanup' to remove conflicting orphan hooks/rules.\n")
956
+ print("\n 💡 Tip: Run 'tokensafe doctor --cleanup' (or '--fix') to remove conflicting orphan hooks/rules.\n")
942
957
 
943
958
  if "--cleanup" in args:
944
959
  for c in conflicts:
@@ -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
- from typing import Dict, List, Any, Optional
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
- try:
117
- import tomllib
118
- loaded_toml = tomllib.loads(raw_bytes.decode("utf-8", errors="replace"))
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,10 +622,132 @@ 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
+ import tomllib
660
+ tomllib.loads(cleaned)
661
+ with open(p, "w", encoding="utf-8") as f:
662
+ f.write(cleaned)
663
+ fixed.append(f"Repaired TOML syntax/orphans in {p} (backup: {p}.backup)")
664
+ except Exception as e2:
665
+ skipped.append(f"Could not auto-repair {p} ({e2}); manual edit needed")
666
+ except Exception:
667
+ pass
668
+
669
+ # 2. Clean stale legacy tokensafe_tokensafe-mcp schema dir when tokensafe_tokensafe exists
670
+ schemas_dir = cls.get_mcp_schemas_dir()
671
+ if os.path.isdir(schemas_dir):
672
+ legacy_schema = os.path.join(schemas_dir, "tokensafe_tokensafe-mcp")
673
+ canonical_schema = os.path.join(schemas_dir, "tokensafe_tokensafe")
674
+ if os.path.isdir(legacy_schema) and os.path.isdir(canonical_schema):
675
+ try:
676
+ shutil.rmtree(legacy_schema)
677
+ fixed.append("Removed stale legacy MCP schema dir tokensafe_tokensafe-mcp")
678
+ except Exception as exc:
679
+ skipped.append(f"Could not remove {legacy_schema}: {exc}")
680
+
681
+ # 3. Consolidate cross-IDE ghost rule duplicates & strip large dead HTML comment blocks
682
+ ghost = cls.audit_ghost_tokens(root)
683
+ agents_md_path = os.path.join(root, "AGENTS.md")
684
+ has_agents_md = os.path.isfile(agents_md_path)
685
+ pointer_stub = (
686
+ "# TokenSafe Project Rules (Pointer)\n\n"
687
+ "The canonical project rules live in AGENTS.md in this repository — "
688
+ "read that file now and follow it for this repo.\n"
689
+ )
690
+ dead_comment_re = re.compile(r"<!--[\s\S]*?-->")
691
+ for gf in ghost.get("ghost_files", []):
692
+ rel = gf.get("file", "")
693
+ gtype = gf.get("type", "")
694
+ abs_p = os.path.join(root, rel)
695
+ if not rel or not os.path.isfile(abs_p):
696
+ continue
697
+ if gtype == "DUPLICATE_CROSS_IDE_RULE" and has_agents_md and rel != "AGENTS.md":
698
+ try:
699
+ os.makedirs(backup_dir, exist_ok=True)
700
+ bak_target = os.path.join(backup_dir, rel.replace(os.sep, "__") + ".bak")
701
+ shutil.copy2(abs_p, bak_target)
702
+ with open(abs_p, "w", encoding="utf-8") as f:
703
+ f.write(pointer_stub)
704
+ fixed.append(f"Consolidated {rel} -> AGENTS.md pointer (-{gf.get('tokens', 0):,} tok/turn, backup: {bak_target})")
705
+ except Exception as exc:
706
+ skipped.append(f"Failed to consolidate {rel}: {exc}")
707
+ elif gtype == "DEAD_COMMENT_BLOCKS":
708
+ try:
709
+ with open(abs_p, "r", encoding="utf-8", errors="replace") as f:
710
+ txt = f.read()
711
+ # Preserve <!-- tokensafe --> markers; strip large non-tokensafe HTML comment blocks (>300 chars)
712
+ def _strip_dead_comment(m: "re.Match[str]") -> str:
713
+ block = m.group(0)
714
+ if "<!-- tokensafe" in block or "<!-- /tokensafe" in block:
715
+ return block
716
+ return "" if len(block) > 300 else block
717
+
718
+ new_txt = dead_comment_re.sub(_strip_dead_comment, txt)
719
+ new_txt = re.sub(r"\n{3,}", "\n\n", new_txt).strip() + "\n"
720
+ if new_txt != txt:
721
+ os.makedirs(backup_dir, exist_ok=True)
722
+ bak_target = os.path.join(backup_dir, rel.replace(os.sep, "__") + ".bak")
723
+ shutil.copy2(abs_p, bak_target)
724
+ with open(abs_p, "w", encoding="utf-8") as f:
725
+ f.write(new_txt)
726
+ fixed.append(f"Stripped inactive comment blocks in {rel} (backup: {bak_target})")
727
+ except Exception as exc:
728
+ skipped.append(f"Failed to strip comments in {rel}: {exc}")
729
+
730
+ # 4. Cleanup conflicting competitor hooks/rules
731
+ try:
732
+ from src.competitors import CompetitorAuditor
733
+ for c in CompetitorAuditor.audit():
734
+ res = CompetitorAuditor.cleanup(c["id"])
735
+ if res.get("removed"):
736
+ fixed.append(f"Cleaned conflicting {c['name']}: {', '.join(res['removed'])}")
737
+ except Exception:
738
+ pass
739
+
740
+ return {
741
+ "fixed": fixed,
742
+ "skipped": skipped,
743
+ "backup_dir": backup_dir if fixed else None,
744
+ }
745
+
573
746
  @classmethod
574
747
  def format_cli_report(cls, workspace_root: Optional[str] = None) -> str:
575
748
  """Formats visual CLI report for tokensafe doctor."""
576
749
  report = cls.audit(workspace_root)
750
+ q_score: Dict[str, Any] = {}
577
751
  score_line = ""
578
752
  try:
579
753
  from src.quality_score import ContextQualityScore
@@ -607,6 +781,9 @@ class EnvironmentAuditor:
607
781
  lines.append(f" {status}")
608
782
 
609
783
  lines.append(f"\n \033[1mInstalled Skills:\033[0m {report['total_skills']} skills (~{report['skills_tokens_per_turn']:,} tokens/turn)")
784
+ if report["total_skills"] >= 15 and report.get("skills_breakdown"):
785
+ for sdir, cnt in sorted(report["skills_breakdown"].items(), key=lambda kv: -kv[1])[:4]:
786
+ lines.append(f" \033[2m• {sdir}: {cnt} skill(s)\033[0m")
610
787
 
611
788
  rules = report.get("rules") or {}
612
789
  if rules.get("files"):
@@ -623,6 +800,12 @@ class EnvironmentAuditor:
623
800
  missing_str = ", ".join(ts.get("missing", []))
624
801
  lines.append(f" \033[1mAST Engines (Tree-sitter):\033[0m \033[33m⚠ {ts['active']}/{ts['total']} active (missing: {missing_str})\033[0m")
625
802
 
803
+ config_issues = report.get("config_issues") or []
804
+ if config_issues:
805
+ lines.append("\n \033[33m\033[1m⚠ Config / Schema Issues Detected:\033[0m")
806
+ for ci in config_issues:
807
+ lines.append(f" • {ci['description']}")
808
+
626
809
  ghost = report.get("ghost_tokens") or {}
627
810
  if ghost.get("has_ghost_tokens"):
628
811
  lines.append(f"\n \033[33m\033[1m👻 Ghost Tokens Detected:\033[0m ~{ghost['ghost_tokens_per_turn']:,} wasted tokens per turn")
@@ -632,12 +815,20 @@ class EnvironmentAuditor:
632
815
  else:
633
816
  lines.append("\n \033[32m✔ No Ghost Tokens detected: Rule files and configs are lean.\033[0m")
634
817
 
635
- if report["has_critical_bloat"]:
636
- lines.append("\n \033[33m\033[1mDiagnostic Recommendation:\033[0m")
818
+ has_auto_fixable = bool(ghost.get("has_ghost_tokens") or config_issues)
819
+ low_grade = q_score.get("grade") in ("C", "F")
820
+ if report["has_critical_bloat"] or has_auto_fixable or rules.get("budget_exceeded") or low_grade:
821
+ lines.append("\n \033[33m\033[1mDiagnostic Recommendations:\033[0m")
637
822
  for b in report["bloated_servers"]:
638
823
  lines.append(f" ➜ Run: \033[36mtokensafe mcp disable {b['name']}\033[0m to save ~{b['est_tokens_per_turn']:,} tokens per turn!")
824
+ if has_auto_fixable:
825
+ lines.append(" ➜ Run: \033[36mtokensafe doctor --fix\033[0m to repair configs & consolidate ghost rule duplicates (with backups)")
826
+ if report["skills_tokens_per_turn"] >= 4000:
827
+ lines.append(f" ➜ Disable unused skills/plugins (currently {report['total_skills']} skills ≈ ~{report['skills_tokens_per_turn']:,} tok/turn)")
828
+ if q_score.get("headroom_pct", 100.0) < 35.0:
829
+ lines.append(" ➜ Run: \033[36mtokensafe compact\033[0m or start a fresh session to restore context headroom")
639
830
  else:
640
- lines.append("\n \033[32m✔ Environment healthy: No critical MCP bloat detected.\033[0m")
831
+ lines.append("\n \033[32m✔ Environment healthy: No critical context bloat detected.\033[0m")
641
832
 
642
833
  lines.append("")
643
834
  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": is_present
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
- # Migration: older installs lack PostToolUse, PreToolUse Edit matcher, or Stop.
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 migrated in ~/.kimi-code/config.toml (Edit/PostToolUse/Stop)"
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 (keeps args=[...] intact)
1339
- pattern = re.compile(r'(?ms)^\[mcp_servers\.tokensafe\]\s*\n(?:(?!^\[).)*')
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
- pattern = re.compile(r'(?ms)^\[mcp_servers\.tokensafe\]\s*\n(?:(?!^\[).)*')
1593
- content = pattern.sub("", 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
- pip_cmd = "pip3" if shutil.which("pip3") else ("pip" if shutil.which("pip") else None)
2557
- if pip_cmd:
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([pip_cmd, "list"], capture_output=True, text=True, timeout=15)
2560
- if "tokensafe" in res.stdout:
2561
- print(f" {CYAN}→{RESET} Updating Python package ({pip_cmd} install --upgrade tokensafe)...")
2562
- up_res = subprocess.run([pip_cmd, "install", "--upgrade", "tokensafe"], capture_output=True, text=True, timeout=120)
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 all detected agents
2629
- print(f"\n {CYAN}→{RESET} Re-synchronizing AI Agent MCP configs & rules...")
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
- for key, info in agents.items():
2633
- if info["installed"]:
2634
- ok, msg = cls.install_mcp_config(key)
2635
- if ok:
2636
- h_ok, h_msg = cls.install_hooks_config(key)
2637
- if h_ok:
2638
- msg = f"{msg}; {h_msg}"
2639
- if ok:
2640
- print(f" {GREEN}✔{RESET} {info['name']}: {msg}")
2641
- synced_count += 1
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
- print(f" {YELLOW}⚠{RESET} {info['name']}: {msg}")
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 = None
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 = None
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
@@ -42,7 +42,7 @@ from src.paths import get_active_workspace, is_plugin_or_system_dir
42
42
 
43
43
  SERVER_INFO = {
44
44
  "name": "tokensafe-mcp",
45
- "version": "4.5.3"
45
+ "version": "4.5.4"
46
46
  }
47
47
 
48
48
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -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.3"
252
+ "User-Agent": "TokenSafe-Sync/4.5.4"
253
253
  }
254
254
  if active_key:
255
255
  headers["Authorization"] = f"Bearer {active_key}"
@@ -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.3"
20
+ CURRENT_VERSION = "4.5.4"
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