tokensafe 4.5.2 → 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.2",
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.2",
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.2",
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.2",
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.2",
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.2",
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.2",
42
+ "version": "4.5.4",
43
43
  "runtimeHint": "uvx",
44
44
  "transport": {
45
45
  "type": "stdio"
@@ -16,16 +16,183 @@ Key capabilities:
16
16
  import os
17
17
  import re
18
18
  import difflib
19
+ import shlex
19
20
  import subprocess
20
21
  import time
21
22
  from typing import Dict, Any, List, Optional, Tuple
22
23
 
24
+ from src.guard import TokenSafeGuard
25
+ from src.paths import is_plugin_or_system_dir
23
26
  from src.secret_redactor import SecretRedactor
24
27
  from src.format_parsers.ansi import strip_ansi
25
28
 
26
29
  MAX_BATCH_FILES = 50
27
30
  MAX_VERIFY_OUTPUT_CHARS = 4000
28
31
 
32
+ _VERIFY_SIMPLE_RUNNERS = frozenset({
33
+ "pytest", "py.test", "ruff", "mypy", "pyright", "flake8", "tox", "nox",
34
+ "vitest", "jest", "mocha", "ava", "tsc", "eslint", "prettier", "biome",
35
+ "oxlint", "rspec", "phpunit", "ctest",
36
+ })
37
+ _VERIFY_PYTHON_RUNNERS = frozenset({
38
+ "python", "python3", "python3.10", "python3.11", "python3.12", "python3.13",
39
+ })
40
+ _VERIFY_PYTHON_MODULES = frozenset({
41
+ "unittest", "pytest", "py_compile", "compileall", "mypy", "ruff", "flake8", "doctest",
42
+ })
43
+ _VERIFY_JS_PKG_MANAGERS = frozenset({"npm", "pnpm", "yarn"})
44
+ _VERIFY_SAFE_SCRIPT_PREFIXES = ("test", "lint", "check", "typecheck", "build")
45
+ _VERIFY_SUBCOMMAND_ALLOWLIST = {
46
+ "go": frozenset({"test", "vet", "build"}),
47
+ "cargo": frozenset({"test", "check", "clippy", "build"}),
48
+ "dotnet": frozenset({"test", "build"}),
49
+ "zig": frozenset({"test", "build"}),
50
+ "swift": frozenset({"test", "build"}),
51
+ "tokensafe": frozenset({"tests"}),
52
+ }
53
+ _VERIFY_FORBIDDEN_FLAGS = frozenset({
54
+ "-c", "-e", "--eval", "-p", "--print", "-r", "--require",
55
+ "--import", "--loader", "-exec", "--exec", "-toolexec",
56
+ })
57
+ _DISALLOWED_SYSTEM_DIRS = frozenset({"/etc", "/usr", "/bin", "/sbin", "/System", "/private/etc"})
58
+
59
+
60
+ def _has_unquoted_shell_operators(cmd_str: str) -> bool:
61
+ """Detects shell chaining, redirection, or command substitution operators."""
62
+ in_single = False
63
+ in_double = False
64
+ escaped = False
65
+ n = len(cmd_str)
66
+ for i, ch in enumerate(cmd_str):
67
+ if ch in ("\n", "\r", "\x00"):
68
+ return True
69
+ if escaped:
70
+ escaped = False
71
+ continue
72
+ if ch == "\\" and not in_single:
73
+ escaped = True
74
+ continue
75
+ if ch == "'" and not in_double:
76
+ in_single = not in_single
77
+ continue
78
+ if ch == '"' and not in_single:
79
+ in_double = not in_double
80
+ continue
81
+ if not in_single:
82
+ if ch == "`":
83
+ return True
84
+ if ch == "$" and i + 1 < n and cmd_str[i + 1] in ("(", "{"):
85
+ return True
86
+ if not in_single and not in_double and ch in (";", "|", "&", ">", "<"):
87
+ return True
88
+ return False
89
+
90
+
91
+ def validate_verify_command(
92
+ verify_cmd: str, base_dir: str = ""
93
+ ) -> Tuple[Optional[List[str]], Optional[str], Optional[str]]:
94
+ """
95
+ Validates an inline verify command through TokenSafeGuard, shell-operator
96
+ rejection, shlex tokenization, and a strict verification-runner allowlist.
97
+ Returns (argv, error_reason, guard_check_name).
98
+ """
99
+ cmd_str = str(verify_cmd or "").strip()
100
+ if not cmd_str:
101
+ return None, "Verification command cannot be empty.", "VERIFY_COMMAND_BLOCKED"
102
+
103
+ guard_res = TokenSafeGuard.inspect_command(cmd_str, cwd=base_dir)
104
+ if guard_res.blocked:
105
+ return (
106
+ None,
107
+ f"TokenSafe Security Guard ({guard_res.check_name}) blocked verify command: {guard_res.reason}",
108
+ guard_res.check_name,
109
+ )
110
+
111
+ if _has_unquoted_shell_operators(cmd_str):
112
+ return (
113
+ None,
114
+ "Shell chaining, redirection, and command substitution operators are disallowed in apply_edits.verify.",
115
+ "VERIFY_COMMAND_BLOCKED",
116
+ )
117
+
118
+ try:
119
+ argv = shlex.split(cmd_str)
120
+ except ValueError as exc:
121
+ return None, f"Malformed verify command syntax: {exc}", "VERIFY_COMMAND_BLOCKED"
122
+
123
+ if not argv:
124
+ return None, "Verification command cannot be empty.", "VERIFY_COMMAND_BLOCKED"
125
+
126
+ raw_exe = argv[0]
127
+ if "/" in raw_exe or "\\" in raw_exe:
128
+ return (
129
+ None,
130
+ f"Path-qualified executables ('{raw_exe}') are disallowed in apply_edits.verify.",
131
+ "VERIFY_COMMAND_BLOCKED",
132
+ )
133
+
134
+ exe = raw_exe.lower()
135
+ if exe.endswith(".exe"):
136
+ exe = exe[:-4]
137
+
138
+ args_rest = argv[1:]
139
+ if any(a in _VERIFY_FORBIDDEN_FLAGS or a.startswith("--eval=") or a.startswith("-exec=") for a in args_rest):
140
+ return (
141
+ None,
142
+ f"Flag '{next(a for a in args_rest if a in _VERIFY_FORBIDDEN_FLAGS or a.startswith(('--eval=', '-exec=')))}' is disallowed in apply_edits.verify.",
143
+ "VERIFY_COMMAND_BLOCKED",
144
+ )
145
+
146
+ if exe in _VERIFY_PYTHON_RUNNERS:
147
+ if len(argv) >= 3 and argv[1] == "-m" and argv[2] in _VERIFY_PYTHON_MODULES:
148
+ return argv, None, None
149
+ return (
150
+ None,
151
+ f"Python verify commands must use '-m <allowed_module>' (one of {sorted(_VERIFY_PYTHON_MODULES)}).",
152
+ "VERIFY_COMMAND_BLOCKED",
153
+ )
154
+
155
+ if exe in _VERIFY_JS_PKG_MANAGERS:
156
+ if args_rest and args_rest[0] in ("test", "t", "lint", "check", "typecheck", "build"):
157
+ return argv, None, None
158
+ if len(args_rest) >= 2 and args_rest[0] == "run" and args_rest[1].startswith(_VERIFY_SAFE_SCRIPT_PREFIXES):
159
+ return argv, None, None
160
+ return (
161
+ None,
162
+ f"'{exe}' verify command only allows test/lint/check/typecheck/build subcommands.",
163
+ "VERIFY_COMMAND_BLOCKED",
164
+ )
165
+
166
+ if exe == "bun":
167
+ if args_rest and args_rest[0] == "test":
168
+ return argv, None, None
169
+ if len(args_rest) >= 2 and args_rest[0] == "run" and args_rest[1].startswith(_VERIFY_SAFE_SCRIPT_PREFIXES):
170
+ return argv, None, None
171
+ return (
172
+ None,
173
+ "'bun' verify command only allows 'bun test' or 'bun run <test|lint|check|typecheck|build>*'.",
174
+ "VERIFY_COMMAND_BLOCKED",
175
+ )
176
+
177
+ if exe in _VERIFY_SUBCOMMAND_ALLOWLIST:
178
+ allowed_subs = _VERIFY_SUBCOMMAND_ALLOWLIST[exe]
179
+ if args_rest and args_rest[0] in allowed_subs:
180
+ return argv, None, None
181
+ return (
182
+ None,
183
+ f"'{exe}' verify command only allows subcommands: {sorted(allowed_subs)}.",
184
+ "VERIFY_COMMAND_BLOCKED",
185
+ )
186
+
187
+ if exe in _VERIFY_SIMPLE_RUNNERS:
188
+ return argv, None, None
189
+
190
+ return (
191
+ None,
192
+ f"Executable '{raw_exe}' is not in the allowlisted verification runners for apply_edits.verify.",
193
+ "VERIFY_COMMAND_BLOCKED",
194
+ )
195
+
29
196
 
30
197
  def _find_closest_line_hint(target: str, content: str, max_lines_preview: int = 5) -> str:
31
198
  """Finds closest matching snippet in content to provide actionable line-drift retry guidance."""
@@ -140,6 +307,29 @@ def execute_batch_edits(
140
307
 
141
308
  base_dir = os.path.abspath(cwd or os.getcwd())
142
309
  real_base = os.path.realpath(base_dir)
310
+ if is_plugin_or_system_dir(base_dir) or real_base in _DISALLOWED_SYSTEM_DIRS or not os.path.isdir(real_base):
311
+ return {
312
+ "success": False,
313
+ "error": f"Refusing batch edits in system, plugin, or non-existent directory '{cwd or base_dir}'.",
314
+ "applied_files": [],
315
+ "failed_files": []
316
+ }
317
+
318
+ verified_argv: Optional[List[str]] = None
319
+ if verify:
320
+ verified_argv, verify_err, verify_check = validate_verify_command(str(verify), base_dir=real_base)
321
+ if verify_err or not verified_argv:
322
+ return {
323
+ "success": False,
324
+ "blocked": True,
325
+ "check_name": verify_check or "VERIFY_COMMAND_BLOCKED",
326
+ "error": verify_err or "Verification command blocked.",
327
+ "applied_count": 0,
328
+ "applied_files": [],
329
+ "failed_count": 0,
330
+ "failed_files": [],
331
+ "dry_run": dry_run,
332
+ }
143
333
 
144
334
  # Pre-validation & secret check
145
335
  prepared_files: Dict[str, Dict[str, Any]] = {}
@@ -345,15 +535,15 @@ def execute_batch_edits(
345
535
  "dry_run": dry_run
346
536
  }
347
537
 
348
- # Execute inline verify command if requested and files were modified
349
- if verify and applied_files_info and not dry_run:
538
+ # Execute inline verify command if requested and files were modified (shell=False, allowlisted argv)
539
+ if verified_argv and applied_files_info and not dry_run:
350
540
  cmd_str = str(verify).strip()
351
541
  t0 = time.time()
352
542
  try:
353
543
  proc = subprocess.run(
354
- cmd_str,
355
- shell=True,
356
- cwd=base_dir,
544
+ verified_argv,
545
+ shell=False,
546
+ cwd=real_base,
357
547
  stdout=subprocess.PIPE,
358
548
  stderr=subprocess.STDOUT,
359
549
  text=True,
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.2"
45
+ "version": "4.5.4"
46
46
  }
47
47
 
48
48
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -552,9 +552,10 @@ FULL_TOOLS = [ { 'annotations': {'readOnlyHint': True},
552
552
  'type': 'object'},
553
553
  'maxItems': 50,
554
554
  'type': 'array'},
555
- 'verify': { 'description': 'Optional shell command to execute immediately '
555
+ 'verify': { 'description': 'Optional allowlisted verification command '
556
556
  'after applying edits (e.g. npm test, pytest, '
557
- 'cargo test)',
557
+ 'cargo test, go test, python3 -m unittest) '
558
+ 'validated via TokenSafeGuard without a shell',
558
559
  'type': 'string'},
559
560
  'verify_timeout_sec': { 'description': 'Verification timeout in seconds '
560
561
  '(default 30)',
@@ -2653,7 +2654,19 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2653
2654
  dry_run = bool(args.get("dry_run", False))
2654
2655
  verify = args.get("verify")
2655
2656
  verify_timeout = int(args.get("verify_timeout_sec") or 30)
2656
- cwd = args.get("cwd") or get_active_workspace()
2657
+ raw_cwd = args.get("cwd")
2658
+ active_ws = get_active_workspace()
2659
+ if raw_cwd:
2660
+ if not os.path.isabs(str(raw_cwd)) and active_ws and os.path.isdir(os.path.join(active_ws, str(raw_cwd))):
2661
+ cwd = os.path.abspath(os.path.join(active_ws, str(raw_cwd)))
2662
+ else:
2663
+ cwd = os.path.abspath(str(raw_cwd))
2664
+ else:
2665
+ cwd, err = _resolve_project_root(args)
2666
+ if err or not cwd:
2667
+ return _fallback_error("apply_edits", err or "unspecified project workspace cwd")
2668
+ if is_plugin_or_system_dir(cwd):
2669
+ return _fallback_error("apply_edits", f"refusing to run apply_edits in system root or plugin dir '{cwd}'")
2657
2670
 
2658
2671
  res = execute_batch_edits(
2659
2672
  edits=edits,
@@ -2663,6 +2676,15 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2663
2676
  verify_timeout_sec=verify_timeout,
2664
2677
  cwd=cwd
2665
2678
  )
2679
+ if res.get("blocked"):
2680
+ tracker.record_event(
2681
+ session_id=_mcp_session_id(),
2682
+ event_type=f"GUARD_{res.get('check_name') or 'VERIFY_COMMAND_BLOCKED'}",
2683
+ original_tokens=count_tokens(str(verify or "")),
2684
+ optimized_tokens=0,
2685
+ details={"cmd": str(verify or "")[:100], "reason": str(res.get("error") or "")}
2686
+ )
2687
+ return _fallback_error("apply_edits", str(res.get("error") or "verify command blocked"))
2666
2688
  lines = []
2667
2689
  if res.get("success"):
2668
2690
  action_desc = "Validated" if dry_run else "Applied"
@@ -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.2"
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.2"
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