tokensafe 2.6.1 → 2.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/bin/tokensafe +1 -1
  2. package/extensions/cursor-tokensafe/extension.js +21 -8
  3. package/hooks/claude_code_hook.py +13 -5
  4. package/hooks/cursor_hook.py +7 -4
  5. package/hooks/post_tool_use.py +24 -6
  6. package/hooks/pre_invocation.py +40 -27
  7. package/hooks/pre_tool_use.py +85 -83
  8. package/hooks/session_start.py +8 -4
  9. package/hooks/stop_hook.py +7 -4
  10. package/package.json +1 -1
  11. package/plugin.json +1 -1
  12. package/server.json +3 -3
  13. package/src/agent_firewall.py +38 -21
  14. package/src/cache_normalizer.py +39 -10
  15. package/src/cli.py +144 -91
  16. package/src/command_sanitizer.py +248 -136
  17. package/src/compactor.py +55 -25
  18. package/src/dashboard.py +17 -10
  19. package/src/deepseek_distiller.py +26 -17
  20. package/src/dependency_prefetcher.py +66 -41
  21. package/src/diff_slicer.py +23 -17
  22. package/src/distiller.py +45 -17
  23. package/src/distiller_cache.py +74 -47
  24. package/src/environment_auditor.py +34 -12
  25. package/src/governor.py +83 -26
  26. package/src/graph_engine.py +653 -140
  27. package/src/guard.py +316 -132
  28. package/src/history_compactor.py +57 -26
  29. package/src/installer.py +174 -131
  30. package/src/license_manager.py +12 -9
  31. package/src/loop_detector.py +68 -29
  32. package/src/mcp_server.py +200 -60
  33. package/src/metrics.py +141 -54
  34. package/src/paths.py +32 -6
  35. package/src/proxy.py +121 -52
  36. package/src/scoped_search.py +18 -6
  37. package/src/secret_redactor.py +78 -59
  38. package/src/skeletonizer.py +68 -13
  39. package/src/slicer.py +25 -7
  40. package/src/team_cache.py +10 -3
  41. package/src/telemetry_sync.py +110 -39
  42. package/src/tokenizer.py +24 -13
  43. package/src/treesitter_backend.py +539 -0
  44. package/src/version_checker.py +67 -32
  45. package/src/weekly_digest.py +6 -3
@@ -11,14 +11,18 @@ from src.tokenizer import count_tokens
11
11
 
12
12
 
13
13
  def _extract_step_text(step: dict) -> str:
14
- """Step text in any supported transcript format. Antigravity writes a
15
- top-level `content` string; Claude Code writes `message.content` as a
16
- string or a list of typed blocks (text / thinking)."""
14
+ """Step text in any supported transcript format (Antigravity string/list, Claude Code text/thinking/tool_result)."""
17
15
  if not isinstance(step, dict):
18
16
  return ""
19
17
  content = step.get("content")
20
18
  if isinstance(content, str) and content:
21
19
  return content
20
+ if isinstance(content, list):
21
+ return " ".join(
22
+ str(b.get("text") or b.get("thinking") or "")
23
+ for b in content
24
+ if isinstance(b, dict)
25
+ ).strip()
22
26
  message = step.get("message")
23
27
  if not isinstance(message, dict):
24
28
  return ""
@@ -26,20 +30,38 @@ def _extract_step_text(step: dict) -> str:
26
30
  if isinstance(mc, str) and mc:
27
31
  return mc
28
32
  if isinstance(mc, list):
29
- parts = []
33
+ parts: List[str] = []
30
34
  for block in mc:
31
- if isinstance(block, dict) and block.get("type") in ("text", "thinking"):
32
- text = block.get("text")
33
- if isinstance(text, str) and text:
34
- parts.append(text)
35
+ if not isinstance(block, dict):
36
+ continue
37
+ btype = block.get("type")
38
+ if btype == "text":
39
+ t = block.get("text")
40
+ if isinstance(t, str) and t:
41
+ parts.append(t)
42
+ elif btype == "thinking":
43
+ t = block.get("thinking") or block.get("text")
44
+ if isinstance(t, str) and t:
45
+ parts.append(t)
46
+ elif btype == "tool_result":
47
+ tc = block.get("content")
48
+ if isinstance(tc, str) and tc:
49
+ parts.append(tc)
50
+ elif isinstance(tc, list):
51
+ for sub in tc:
52
+ if isinstance(sub, dict) and isinstance(sub.get("text"), str):
53
+ parts.append(sub["text"])
35
54
  return " ".join(parts)
36
55
  return ""
37
56
 
38
57
 
39
- _READ_TOOLS = {"read_file", "view_file", "Read"}
40
- _EDIT_TOOLS = {"edit_file", "write_file", "Edit", "Write", "NotebookEdit"}
41
- _COMMAND_TOOLS = {"run_command", "Bash"}
42
- _PATH_KEYS = ("Path", "path", "FilePath", "file_path", "notebook_path")
58
+ _READ_TOOLS = {
59
+ "read_file", "view_file", "Read", "smart_read_file",
60
+ "scoped_search", "list_dir", "get_architecture_graph", "get_api_surface",
61
+ }
62
+ _EDIT_TOOLS = {"edit_file", "write_file", "Edit", "Write", "MultiEdit", "NotebookEdit", "replace_file_content"}
63
+ _COMMAND_TOOLS = {"run_command", "Bash", "sanitize_command"}
64
+ _PATH_KEYS = ("Path", "path", "FilePath", "file_path", "notebook_path", "project_path")
43
65
  _COMMAND_KEYS = ("CommandLine", "command")
44
66
 
45
67
 
@@ -54,22 +76,24 @@ def _arg_value(args: dict, keys) -> str:
54
76
 
55
77
 
56
78
  def _extract_step_tool_calls(step: dict) -> List[Tuple[str, dict]]:
57
- """Tool calls in any supported transcript format: Antigravity
58
- `tool_calls: [{name, args}]` or Claude Code `message.content` blocks of
59
- type `tool_use` with `name` / `input`. Returns (name, args) pairs."""
79
+ """Tool calls in any supported transcript format."""
60
80
  calls: List[Tuple[str, dict]] = []
61
81
  if not isinstance(step, dict):
62
82
  return calls
63
- for tc in step.get("tool_calls") or []:
64
- if isinstance(tc, dict):
65
- calls.append((str(tc.get("name", "")), tc.get("args") or {}))
83
+ tc_list = step.get("tool_calls")
84
+ if isinstance(tc_list, list):
85
+ for tc in tc_list:
86
+ if isinstance(tc, dict):
87
+ args = tc.get("args")
88
+ calls.append((str(tc.get("name", "")), args if isinstance(args, dict) else {}))
66
89
  message = step.get("message")
67
90
  if isinstance(message, dict):
68
91
  mc = message.get("content")
69
92
  if isinstance(mc, list):
70
93
  for block in mc:
71
94
  if isinstance(block, dict) and block.get("type") == "tool_use":
72
- calls.append((str(block.get("name", "")), block.get("input") or {}))
95
+ inp = block.get("input")
96
+ calls.append((str(block.get("name", "")), inp if isinstance(inp, dict) else {}))
73
97
  return calls
74
98
 
75
99
  class HistoryCompactor:
@@ -129,13 +153,19 @@ class HistoryCompactor:
129
153
  read_files = set()
130
154
  edited_files = set()
131
155
  executed_commands = []
132
- raw_text_accum = []
156
+ key_turns: List[str] = []
157
+ orig_tokens = 0
133
158
 
134
159
  for step in steps:
135
- # Accumulate content for token counting (any supported format)
160
+ if not isinstance(step, dict):
161
+ continue
136
162
  text = _extract_step_text(step)
137
163
  if text:
138
- raw_text_accum.append(text)
164
+ orig_tokens += count_tokens(text)
165
+ if len(key_turns) < 5:
166
+ first_ln = text.splitlines()[0].strip()
167
+ if len(first_ln) > 8:
168
+ key_turns.append(first_ln[:100])
139
169
 
140
170
  # Inspect tool calls (Antigravity tool_calls / Claude Code tool_use)
141
171
  for name, args in _extract_step_tool_calls(step):
@@ -150,14 +180,10 @@ class HistoryCompactor:
150
180
  elif name in _COMMAND_TOOLS:
151
181
  cmd = _arg_value(args, _COMMAND_KEYS)
152
182
  if cmd:
153
- # Keep short representation
154
183
  clean_cmd = cmd.split()[0] if cmd.split() else cmd
155
184
  if clean_cmd not in executed_commands:
156
185
  executed_commands.append(clean_cmd)
157
186
 
158
- raw_history_str = " ".join(raw_text_accum)
159
- orig_tokens = count_tokens(raw_history_str)
160
-
161
187
  # Only fold if history has accumulated significant mass (> 1,000 tokens)
162
188
  if orig_tokens < 1000:
163
189
  return None, 0, 0, {}
@@ -170,6 +196,11 @@ class HistoryCompactor:
170
196
  ledger_lines.append(f"• Modified: {', '.join(sorted(edited_files))}")
171
197
  if executed_commands:
172
198
  ledger_lines.append(f"• Executed: {', '.join(executed_commands[:5])}")
199
+ if not (read_files or edited_files or executed_commands):
200
+ if not key_turns:
201
+ return None, 0, 0, {}
202
+ for snippet in key_turns[:3]:
203
+ ledger_lines.append(f"• Context: {snippet}")
173
204
 
174
205
  consolidated_text = "\n".join(ledger_lines)
175
206
  folded_tokens = count_tokens(consolidated_text)
package/src/installer.py CHANGED
@@ -29,10 +29,19 @@ YELLOW = "\033[33m"
29
29
  RED = "\033[31m"
30
30
 
31
31
  HOME = os.path.expanduser("~")
32
- PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
32
+ PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
33
33
  MCP_SERVER_PATH = os.path.join(PROJECT_ROOT, "src", "mcp_server.py")
34
34
  PYTHON_BIN = sys.executable
35
35
 
36
+ def _app_data_dir(*parts: str) -> str:
37
+ if sys.platform == "darwin":
38
+ base = os.path.join(HOME, "Library", "Application Support")
39
+ elif sys.platform == "win32":
40
+ base = os.environ.get("APPDATA") or os.path.join(HOME, "AppData", "Roaming")
41
+ else:
42
+ base = os.environ.get("XDG_CONFIG_HOME") or os.path.join(HOME, ".config")
43
+ return os.path.join(base, *parts)
44
+
36
45
  UNIFIED_TOKENSAFE_RULE = (
37
46
  "## TOKENSAFE GRAPH-FIRST OPTIMIZATION PROTOCOL\n"
38
47
  "Always use `tokensafe` MCP tools over default raw file reads or high-output terminal executions to prevent context window exhaustion.\n\n"
@@ -58,8 +67,8 @@ AGENTS_REGISTRY = {
58
67
  "claude_desktop": {
59
68
  "name": "Claude Desktop",
60
69
  "type": "mcp_json",
61
- "config_path": os.path.join(HOME, "Library", "Application Support", "Claude", "claude_desktop_config.json"),
62
- "detect_path": os.path.join(HOME, "Library", "Application Support", "Claude")
70
+ "config_path": _app_data_dir("Claude", "claude_desktop_config.json"),
71
+ "detect_path": _app_data_dir("Claude")
63
72
  },
64
73
  "cursor": {
65
74
  "name": "Cursor",
@@ -80,9 +89,9 @@ AGENTS_REGISTRY = {
80
89
  "cline": {
81
90
  "name": "Cline / Roo Code (VS Code)",
82
91
  "type": "mcp_json",
83
- "config_path": os.path.join(HOME, "Library", "Application Support", "Code", "User", "globalStorage", "saoudrizwan.claude-dev", "settings", "cline_mcp_settings.json"),
84
- "rules_path": os.path.join(HOME, "Library", "Application Support", "Code", "User", "globalStorage", "saoudrizwan.claude-dev", "settings", "Rule_TokenSafe.md"),
85
- "detect_path": os.path.join(HOME, "Library", "Application Support", "Code")
92
+ "config_path": _app_data_dir("Code", "User", "globalStorage", "saoudrizwan.claude-dev", "settings", "cline_mcp_settings.json"),
93
+ "rules_path": _app_data_dir("Code", "User", "globalStorage", "saoudrizwan.claude-dev", "settings", "Rule_TokenSafe.md"),
94
+ "detect_path": _app_data_dir("Code")
86
95
  },
87
96
  "claude_code": {
88
97
  "name": "Claude Code CLI",
@@ -142,6 +151,35 @@ class AgentInstaller:
142
151
  script = os.path.join(PROJECT_ROOT, "hooks", script_name)
143
152
  return f"{shlex.quote(PYTHON_BIN)} {shlex.quote(script)}"
144
153
 
154
+ @staticmethod
155
+ def _load_json_with_backup(config_file: str) -> Tuple[Optional[Dict[str, Any]], Optional[str]]:
156
+ """Reads a JSON config file after creating a .backup copy.
157
+ If parsing fails or root is non-dict, refuses to overwrite existing data."""
158
+ if not os.path.exists(config_file):
159
+ return {}, None
160
+ try:
161
+ shutil.copy2(config_file, f"{config_file}.backup")
162
+ except Exception:
163
+ pass
164
+ try:
165
+ with open(config_file, "r", encoding="utf-8") as f:
166
+ data = json.load(f)
167
+ if not isinstance(data, dict):
168
+ return None, f"Existing JSON config '{config_file}' is not an object; left untouched (.backup saved)."
169
+ return data, None
170
+ except Exception as e:
171
+ return None, f"Could not parse existing JSON config '{config_file}' ({e}); left untouched (.backup saved)."
172
+
173
+ @staticmethod
174
+ def _atomic_write_json(config_file: str, data: Dict[str, Any]) -> None:
175
+ parent = os.path.dirname(config_file)
176
+ if parent:
177
+ os.makedirs(parent, exist_ok=True)
178
+ tmp = f"{config_file}.tmp.{os.getpid()}"
179
+ with open(tmp, "w", encoding="utf-8") as f:
180
+ json.dump(data, f, indent=2)
181
+ os.replace(tmp, config_file)
182
+
145
183
  @classmethod
146
184
  def install_hooks_config(cls, agent_key: str) -> Tuple[bool, str]:
147
185
  """Registers TokenSafe lifecycle-hook adapters with agents that support them.
@@ -158,52 +196,83 @@ class AgentInstaller:
158
196
  cursor_cmd = cls._tokensafe_hook_command("cursor_hook.py")
159
197
 
160
198
  if agent_key == "claude_code":
161
- info = AGENTS_REGISTRY["claude_code"]
162
- config_file = info.get("agents_md_path", "").replace("CLAUDE.md", "settings.json")
163
199
  config_file = os.path.join(HOME, ".claude", "settings.json")
164
200
  os.makedirs(os.path.dirname(config_file), exist_ok=True)
165
- data: Dict[str, Any] = {}
166
- if os.path.exists(config_file):
167
- try:
168
- with open(config_file, "r", encoding="utf-8") as f:
169
- data = json.load(f)
170
- except Exception:
171
- data = {}
201
+ data, err = cls._load_json_with_backup(config_file)
202
+ if err or data is None:
203
+ return False, err or f"Failed to parse {config_file}"
172
204
  hooks = data.get("hooks") if isinstance(data.get("hooks"), dict) else {}
173
- blob = json.dumps(hooks)
174
- if "claude_code_hook.py" in blob:
175
- return True, "TokenSafe Claude Code hooks already registered"
176
205
  prompt_entry = {"hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
177
206
  bash_entry = {"matcher": "Bash", "hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
178
- # SessionStart: no matcher = all sources (startup/resume/clear/compact).
179
207
  session_entry = {"hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
180
- hooks.setdefault("SessionStart", []).append(session_entry)
181
- hooks.setdefault("UserPromptSubmit", []).append(prompt_entry)
182
- hooks.setdefault("PreToolUse", []).append(bash_entry)
208
+
209
+ def _sync_claude_event(event_name: str, default_entry: dict) -> bool:
210
+ entries = hooks.get(event_name)
211
+ if not isinstance(entries, list):
212
+ hooks[event_name] = [default_entry]
213
+ return True
214
+ seen = False
215
+ dirty = False
216
+ for entry in entries:
217
+ if isinstance(entry, dict) and isinstance(entry.get("hooks"), list):
218
+ for h in entry["hooks"]:
219
+ if isinstance(h, dict) and "claude_code_hook.py" in str(h.get("command", "")):
220
+ seen = True
221
+ if h.get("command") != claude_cmd:
222
+ h["command"] = claude_cmd
223
+ dirty = True
224
+ if not seen:
225
+ entries.append(default_entry)
226
+ dirty = True
227
+ return dirty
228
+
229
+ changed = any([
230
+ _sync_claude_event("SessionStart", session_entry),
231
+ _sync_claude_event("UserPromptSubmit", prompt_entry),
232
+ _sync_claude_event("PreToolUse", bash_entry),
233
+ ])
234
+ if not changed:
235
+ return True, "TokenSafe Claude Code hooks already registered"
183
236
  data["hooks"] = hooks
184
- cls._write_file_safely(config_file, json.dumps(data, indent=2))
237
+ cls._atomic_write_json(config_file, data)
185
238
  return True, "hooks registered (SessionStart + UserPromptSubmit + PreToolUse guard)"
186
239
 
187
240
  # cursor
188
241
  config_file = os.path.join(HOME, ".cursor", "hooks.json")
189
242
  os.makedirs(os.path.dirname(config_file), exist_ok=True)
190
- data = {}
191
- if os.path.exists(config_file):
192
- try:
193
- with open(config_file, "r", encoding="utf-8") as f:
194
- data = json.load(f)
195
- except Exception:
196
- data = {}
243
+ data, err = cls._load_json_with_backup(config_file)
244
+ if err or data is None:
245
+ return False, err or f"Failed to parse {config_file}"
197
246
  hooks = data.get("hooks") if isinstance(data.get("hooks"), dict) else {}
198
- blob = json.dumps(hooks)
199
- if "cursor_hook.py" in blob:
200
- return True, "TokenSafe Cursor hooks already registered"
201
247
  shell_entry = {"command": cursor_cmd, "timeout": 10}
202
- hooks.setdefault("beforeShellExecution", []).append(dict(shell_entry))
203
- hooks.setdefault("beforeReadFile", []).append(dict(shell_entry))
204
- hooks.setdefault("beforeSubmitPrompt", []).append(dict(shell_entry))
248
+
249
+ def _sync_cursor_event(event_name: str) -> bool:
250
+ entries = hooks.get(event_name)
251
+ if not isinstance(entries, list):
252
+ hooks[event_name] = [dict(shell_entry)]
253
+ return True
254
+ seen = False
255
+ dirty = False
256
+ for entry in entries:
257
+ if isinstance(entry, dict) and "cursor_hook.py" in str(entry.get("command", "")):
258
+ seen = True
259
+ if entry.get("command") != cursor_cmd:
260
+ entry["command"] = cursor_cmd
261
+ dirty = True
262
+ if not seen:
263
+ entries.append(dict(shell_entry))
264
+ dirty = True
265
+ return dirty
266
+
267
+ changed = any([
268
+ _sync_cursor_event("beforeShellExecution"),
269
+ _sync_cursor_event("beforeReadFile"),
270
+ _sync_cursor_event("beforeSubmitPrompt"),
271
+ ])
272
+ if not changed:
273
+ return True, "TokenSafe Cursor hooks already registered"
205
274
  data["hooks"] = hooks
206
- cls._write_file_safely(config_file, json.dumps(data, indent=2))
275
+ cls._atomic_write_json(config_file, data)
207
276
  return True, "guards registered (shell + junk-read + prompt pipeline)"
208
277
 
209
278
  @classmethod
@@ -244,14 +313,9 @@ class AgentInstaller:
244
313
  config_file = info["config_path"]
245
314
  os.makedirs(os.path.dirname(config_file), exist_ok=True)
246
315
 
247
- data = {}
248
- if os.path.exists(config_file):
249
- try:
250
- with open(config_file, "r", encoding="utf-8") as f:
251
- data = json.load(f)
252
- shutil.copy2(config_file, f"{config_file}.backup")
253
- except Exception:
254
- data = {}
316
+ data, err = cls._load_json_with_backup(config_file)
317
+ if err or data is None:
318
+ return False, err or f"Failed to parse {config_file}"
255
319
 
256
320
  if "mcpServers" not in data or not isinstance(data["mcpServers"], dict):
257
321
  data["mcpServers"] = {}
@@ -261,8 +325,7 @@ class AgentInstaller:
261
325
  "args": [MCP_SERVER_PATH]
262
326
  }
263
327
 
264
- with open(config_file, "w", encoding="utf-8") as f:
265
- json.dump(data, f, indent=2)
328
+ cls._atomic_write_json(config_file, data)
266
329
 
267
330
  if "skills_path" in info:
268
331
  cls._symlink_skill(info["skills_path"])
@@ -291,15 +354,11 @@ class AgentInstaller:
291
354
  config_file = info["config_path"]
292
355
  os.makedirs(os.path.dirname(config_file), exist_ok=True)
293
356
 
294
- data = {}
295
- if os.path.exists(config_file):
296
- try:
297
- with open(config_file, "r", encoding="utf-8") as f:
298
- data = json.load(f)
299
- except Exception:
300
- data = {}
357
+ data, err = cls._load_json_with_backup(config_file)
358
+ if err or data is None:
359
+ return False, err or f"Failed to parse {config_file}"
301
360
 
302
- if "mcpServers" not in data:
361
+ if "mcpServers" not in data or not isinstance(data["mcpServers"], dict):
303
362
  data["mcpServers"] = {}
304
363
 
305
364
  data["mcpServers"]["tokensafe"] = {
@@ -307,15 +366,7 @@ class AgentInstaller:
307
366
  "args": [MCP_SERVER_PATH]
308
367
  }
309
368
 
310
- # Backup existing
311
- if os.path.exists(config_file):
312
- try:
313
- shutil.copy2(config_file, f"{config_file}.backup")
314
- except Exception:
315
- pass
316
-
317
- with open(config_file, "w", encoding="utf-8") as f:
318
- json.dump(data, f, indent=2)
369
+ cls._atomic_write_json(config_file, data)
319
370
 
320
371
  if "skills_path" in info:
321
372
  cls._symlink_skill(info["skills_path"])
@@ -331,24 +382,30 @@ class AgentInstaller:
331
382
 
332
383
  content = ""
333
384
  if os.path.exists(config_file):
385
+ try:
386
+ shutil.copy2(config_file, f"{config_file}.backup")
387
+ except Exception:
388
+ pass
334
389
  try:
335
390
  with open(config_file, "r", encoding="utf-8") as f:
336
391
  content = f.read()
337
- shutil.copy2(config_file, f"{config_file}.backup")
338
392
  except Exception:
339
393
  pass
340
394
 
341
- server_snippet = (
342
- f'\n[mcp_servers.tokensafe]\n'
343
- f'command = "{PYTHON_BIN}"\n'
344
- f'args = ["{MCP_SERVER_PATH}"]\n'
395
+ toml_cmd = json.dumps(PYTHON_BIN)
396
+ toml_srv = json.dumps(MCP_SERVER_PATH)
397
+ server_section = (
398
+ f'[mcp_servers.tokensafe]\n'
399
+ f'command = {toml_cmd}\n'
400
+ f'args = [{toml_srv}]\n'
345
401
  )
346
402
 
347
- if '[mcp_servers.tokensafe]' in content:
348
- pattern = r'\[mcp_servers\.tokensafe\][^\[]*'
349
- content = re.sub(pattern, f'[mcp_servers.tokensafe]\ncommand = "{PYTHON_BIN}"\nargs = ["{MCP_SERVER_PATH}"]\n\n', content)
403
+ if re.search(r'(?m)^\[mcp_servers\.tokensafe\]\s*$', content):
404
+ # Replace the entire section up to the next TOML table header or EOF (keeps args=[...] intact)
405
+ pattern = re.compile(r'(?ms)^\[mcp_servers\.tokensafe\]\s*\n(?:(?!^\[).)*')
406
+ content = pattern.sub(lambda _: server_section + "\n", content)
350
407
  else:
351
- content = content.rstrip() + "\n" + server_snippet
408
+ content = (content.rstrip() + "\n\n" + server_section) if content.strip() else server_section
352
409
 
353
410
  with open(config_file, "w", encoding="utf-8") as f:
354
411
  f.write(content)
@@ -367,21 +424,16 @@ class AgentInstaller:
367
424
  elif info["type"] == "claude_md":
368
425
  if "config_path" in info:
369
426
  config_file = info["config_path"]
370
- data = {}
371
- if os.path.exists(config_file):
372
- try:
373
- with open(config_file, "r", encoding="utf-8") as f:
374
- data = json.load(f)
375
- except Exception:
376
- data = {}
427
+ data, err = cls._load_json_with_backup(config_file)
428
+ if err or data is None:
429
+ return False, err or f"Failed to parse {config_file}"
377
430
  if "mcpServers" not in data or not isinstance(data["mcpServers"], dict):
378
431
  data["mcpServers"] = {}
379
432
  data["mcpServers"]["tokensafe"] = {
380
433
  "command": PYTHON_BIN,
381
434
  "args": [MCP_SERVER_PATH]
382
435
  }
383
- with open(config_file, "w", encoding="utf-8") as f:
384
- json.dump(data, f, indent=2)
436
+ cls._atomic_write_json(config_file, data)
385
437
 
386
438
  if "agents_md_path" in info:
387
439
  cls._inject_global_rule(info["agents_md_path"], UNIFIED_TOKENSAFE_RULE)
@@ -394,13 +446,9 @@ class AgentInstaller:
394
446
  elif info["type"] == "copilot_json":
395
447
  config_file = info["config_path"]
396
448
  os.makedirs(os.path.dirname(config_file), exist_ok=True)
397
- data = {}
398
- if os.path.exists(config_file):
399
- try:
400
- with open(config_file, "r", encoding="utf-8") as f:
401
- data = json.load(f)
402
- except Exception:
403
- data = {}
449
+ data, err = cls._load_json_with_backup(config_file)
450
+ if err or data is None:
451
+ return False, err or f"Failed to parse {config_file}"
404
452
  if "mcpServers" not in data or not isinstance(data["mcpServers"], dict):
405
453
  data["mcpServers"] = {}
406
454
  data["mcpServers"]["tokensafe"] = {
@@ -409,22 +457,16 @@ class AgentInstaller:
409
457
  "args": [MCP_SERVER_PATH],
410
458
  "tools": ["*"]
411
459
  }
412
- with open(config_file, "w", encoding="utf-8") as f:
413
- json.dump(data, f, indent=2)
460
+ cls._atomic_write_json(config_file, data)
414
461
  return True, f"Configured MCP for GitHub Copilot in {config_file}"
415
462
 
416
463
  elif info["type"] == "zcode_json":
417
464
  config_file = info["config_path"]
418
465
  os.makedirs(os.path.dirname(config_file), exist_ok=True)
419
466
 
420
- data = {}
421
- if os.path.exists(config_file):
422
- try:
423
- with open(config_file, "r", encoding="utf-8") as f:
424
- data = json.load(f)
425
- shutil.copy2(config_file, f"{config_file}.backup")
426
- except Exception:
427
- data = {}
467
+ data, err = cls._load_json_with_backup(config_file)
468
+ if err or data is None:
469
+ return False, err or f"Failed to parse {config_file}"
428
470
 
429
471
  if "mcp" not in data or not isinstance(data["mcp"], dict):
430
472
  data["mcp"] = {}
@@ -436,8 +478,7 @@ class AgentInstaller:
436
478
  "args": [MCP_SERVER_PATH]
437
479
  }
438
480
 
439
- with open(config_file, "w", encoding="utf-8") as f:
440
- json.dump(data, f, indent=2)
481
+ cls._atomic_write_json(config_file, data)
441
482
 
442
483
  if "skills_path" in info:
443
484
  cls._symlink_skill(info["skills_path"])
@@ -481,10 +522,13 @@ class AgentInstaller:
481
522
 
482
523
  @classmethod
483
524
  def _symlink_dir(cls, source_path: str, target_path: str):
484
- """Safely creates or replaces a symlink to a directory."""
525
+ """Safely creates or replaces a symlink to a directory (falls back to copytree if symlinks fail)."""
485
526
  if not os.path.exists(source_path):
486
527
  return
487
- os.makedirs(os.path.dirname(target_path), exist_ok=True)
528
+ parent = os.path.dirname(target_path)
529
+ if parent:
530
+ os.makedirs(parent, exist_ok=True)
531
+ # Remove previous link or directory cleanly
488
532
  if os.path.islink(target_path) or os.path.exists(target_path):
489
533
  try:
490
534
  if os.path.islink(target_path) or os.path.isfile(target_path):
@@ -496,19 +540,26 @@ class AgentInstaller:
496
540
  try:
497
541
  os.symlink(source_path, target_path)
498
542
  except Exception:
499
- pass
543
+ try:
544
+ shutil.copytree(source_path, target_path, dirs_exist_ok=True, ignore=shutil.ignore_patterns(".git", "__pycache__", "node_modules", "*.pyc"))
545
+ except Exception:
546
+ pass
500
547
 
501
548
  @classmethod
502
549
  def _write_file_safely(cls, file_path: str, content: str):
503
550
  """Safely writes content creating parent directories."""
504
- os.makedirs(os.path.dirname(file_path), exist_ok=True)
551
+ parent = os.path.dirname(file_path)
552
+ if parent:
553
+ os.makedirs(parent, exist_ok=True)
505
554
  with open(file_path, "w", encoding="utf-8") as f:
506
555
  f.write(content)
507
556
 
508
557
  @classmethod
509
558
  def _inject_global_rule(cls, file_path: str, rule_snippet: str, tag: str = "tokensafe"):
510
559
  """Injects or updates a delimited rule block in a markdown instruction file."""
511
- os.makedirs(os.path.dirname(file_path), exist_ok=True)
560
+ parent = os.path.dirname(file_path)
561
+ if parent:
562
+ os.makedirs(parent, exist_ok=True)
512
563
  content = ""
513
564
  if os.path.exists(file_path):
514
565
  try:
@@ -520,8 +571,10 @@ class AgentInstaller:
520
571
  end_tag = f"<!-- /{tag} -->"
521
572
  pattern = re.compile(rf"{re.escape(start_tag)}.*?{re.escape(end_tag)}", re.DOTALL)
522
573
  wrapped = f"{start_tag}\n{rule_snippet.strip()}\n{end_tag}"
523
- if start_tag in content:
524
- new_content = pattern.sub(wrapped, content)
574
+ if start_tag in content and end_tag in content:
575
+ new_content = pattern.sub(lambda _: wrapped, content)
576
+ elif start_tag in content:
577
+ new_content = content.replace(start_tag, wrapped, 1)
525
578
  else:
526
579
  new_content = (content.rstrip() + "\n\n" + wrapped).lstrip()
527
580
  with open(file_path, "w", encoding="utf-8") as f:
@@ -582,22 +635,16 @@ class AgentInstaller:
582
635
  cursor_mcp = os.path.join(project_dir, ".cursor", "mcp.json")
583
636
  try:
584
637
  os.makedirs(os.path.dirname(cursor_mcp), exist_ok=True)
585
- data = {}
586
- if os.path.exists(cursor_mcp):
587
- try:
588
- with open(cursor_mcp, "r", encoding="utf-8") as f:
589
- data = json.load(f)
590
- except Exception:
591
- data = {}
592
- if "mcpServers" not in data or not isinstance(data["mcpServers"], dict):
593
- data["mcpServers"] = {}
594
- data["mcpServers"]["tokensafe"] = {
595
- "command": PYTHON_BIN,
596
- "args": [MCP_SERVER_PATH]
597
- }
598
- with open(cursor_mcp, "w", encoding="utf-8") as f:
599
- json.dump(data, f, indent=2)
600
- created.append(".cursor/mcp.json")
638
+ data, err = cls._load_json_with_backup(cursor_mcp)
639
+ if not err and data is not None:
640
+ if "mcpServers" not in data or not isinstance(data["mcpServers"], dict):
641
+ data["mcpServers"] = {}
642
+ data["mcpServers"]["tokensafe"] = {
643
+ "command": PYTHON_BIN,
644
+ "args": [MCP_SERVER_PATH]
645
+ }
646
+ cls._atomic_write_json(cursor_mcp, data)
647
+ created.append(".cursor/mcp.json")
601
648
  except Exception:
602
649
  pass
603
650
 
@@ -617,13 +664,9 @@ class AgentInstaller:
617
664
  directory. Stored relative to the project root when the plugin lives
618
665
  inside it (team-shareable), otherwise as an absolute path."""
619
666
  config_path = os.path.join(project_dir, ".agents", "plugins.json")
620
- config: Dict[str, Any] = {}
621
- if os.path.isfile(config_path):
622
- try:
623
- with open(config_path, "r", encoding="utf-8") as f:
624
- config = json.load(f)
625
- except Exception:
626
- config = {}
667
+ config, err = cls._load_json_with_backup(config_path)
668
+ if err or config is None:
669
+ return
627
670
 
628
671
  abs_path = os.path.abspath(plugin_path if os.path.isabs(plugin_path) else os.path.join(os.getcwd(), plugin_path))
629
672
  if abs_path == project_dir or abs_path.startswith(project_dir + os.sep):