tokensafe 4.5.0 → 4.5.2

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 (62) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/bin/agy-tokens +10 -1
  3. package/bin/tokensafe.js +2 -1
  4. package/hooks/claude_code_hook.py +38 -126
  5. package/hooks/cursor_hook.py +45 -1
  6. package/hooks/kimi_hook.py +46 -90
  7. package/hooks/pre_invocation.py +23 -4
  8. package/hooks/pre_tool_use.py +40 -22
  9. package/hooks/session_start.py +28 -10
  10. package/hooks/zcode_hook.py +95 -0
  11. package/hooks.json +1 -1
  12. package/kimi.plugin.json +17 -1
  13. package/mcp_config.json +10 -4
  14. package/package.json +1 -1
  15. package/plugin.json +1 -1
  16. package/rules/AGENTS.md +24 -24
  17. package/server.json +3 -3
  18. package/skills/token-optimizer/SKILL.md +61 -86
  19. package/skills/token-optimizer/references/mcp-tools.md +32 -132
  20. package/src/adapter_core.py +231 -7
  21. package/src/batch_editor.py +73 -22
  22. package/src/batch_search.py +31 -11
  23. package/src/burn_monitor.py +581 -0
  24. package/src/cache_normalizer.py +2 -0
  25. package/src/cli.py +34 -4
  26. package/src/compactor.py +1 -1
  27. package/src/dashboard.py +17 -9
  28. package/src/diff_slicer.py +1 -1
  29. package/src/distiller.py +11 -1
  30. package/src/environment_auditor.py +30 -6
  31. package/src/format_parsers/ansi.py +1 -1
  32. package/src/format_parsers/lockfiles.py +22 -17
  33. package/src/format_parsers/tabular.py +6 -3
  34. package/src/fts_index.py +26 -20
  35. package/src/governor.py +2 -2
  36. package/src/graph_engine.py +31 -9
  37. package/src/guard.py +3 -3
  38. package/src/image_downscale.py +26 -0
  39. package/src/installer.py +61 -48
  40. package/src/license_manager.py +49 -16
  41. package/src/live_relay.py +9 -8
  42. package/src/mcp_server.py +487 -48
  43. package/src/metrics.py +78 -13
  44. package/src/mistakes.py +4 -2
  45. package/src/paths.py +4 -1
  46. package/src/proxy.py +302 -123
  47. package/src/result_ledger.py +39 -1
  48. package/src/schema_slicer.py +40 -18
  49. package/src/scoped_search.py +66 -23
  50. package/src/skeletonizer.py +22 -11
  51. package/src/slicer.py +6 -4
  52. package/src/stash.py +37 -7
  53. package/src/superseded.py +42 -23
  54. package/src/syntax_guard.py +2 -0
  55. package/src/team_cache.py +3 -0
  56. package/src/telemetry_sync.py +96 -54
  57. package/src/thinking_fold.py +50 -12
  58. package/src/transcript_analyzer.py +270 -68
  59. package/src/treesitter_backend.py +2 -0
  60. package/src/type_slicer.py +60 -18
  61. package/src/version_checker.py +1 -1
  62. package/src/web_reader.py +55 -22
@@ -41,6 +41,13 @@ def _resolve_hook_path(raw_path: str, hook_cwd: str) -> str:
41
41
 
42
42
 
43
43
  def _handle(payload: dict) -> dict:
44
+ # If invoked by ZCode / Claude Code (tool_name + tool_input without Antigravity toolCall),
45
+ # route through the CC/ZCode PreToolUse evaluator so we return {} / hookSpecificOutput
46
+ # instead of {"decision": "allow"} (which causes hook.run.failed in ZCode).
47
+ if not isinstance(payload.get("toolCall"), dict) and payload.get("tool_name"):
48
+ from src.adapter_core import evaluate_cc_pre_tool_use
49
+ return evaluate_cc_pre_tool_use(payload, agent=str(payload.get("agent") or "zcode"))
50
+
44
51
  tool_call = payload.get("toolCall")
45
52
  if not isinstance(tool_call, dict):
46
53
  tool_call = {}
@@ -48,18 +55,24 @@ def _handle(payload: dict) -> dict:
48
55
  args = tool_call.get("args")
49
56
  if not isinstance(args, dict):
50
57
  args = {}
58
+ from src.adapter_core import canonical_tool_name
59
+ canon_tool = canonical_tool_name(tool_name)
51
60
  conversation_id = str(payload.get("conversationId") or "default_session")
52
61
  last_user_input = str(payload.get("lastUserInput") or "")
53
62
  # Working directory of the tool call: lets CommandSanitizer peek at
54
63
  # package.json and Guard audit git staging in the user's repo (never plugin CWD).
55
- workspace_paths = payload.get("workspacePaths") if isinstance(payload.get("workspacePaths"), list) else []
56
- hook_cwd = str(payload.get("cwd") or (workspace_paths[0] if workspace_paths else "") or os.getcwd())
64
+ workspace_paths = [str(w) for w in payload["workspacePaths"] if str(w).strip()] if isinstance(payload.get("workspacePaths"), list) else []
65
+ explicit_cwd = str(payload.get("cwd") or "").strip()
66
+ hook_cwd = explicit_cwd or (workspace_paths[0] if workspace_paths else "") or os.getcwd()
57
67
  try:
58
68
  from src.paths import save_active_workspace
59
- if workspace_paths and workspace_paths[0]:
60
- save_active_workspace(str(workspace_paths[0]))
61
- elif hook_cwd:
62
- save_active_workspace(hook_cwd)
69
+ if workspace_paths:
70
+ save_active_workspace(workspace_paths[0])
71
+ elif explicit_cwd and any(
72
+ os.path.exists(os.path.join(explicit_cwd, m))
73
+ for m in (".git", "package.json", "pyproject.toml", "go.mod", "Cargo.toml", "requirements.txt")
74
+ ):
75
+ save_active_workspace(explicit_cwd)
63
76
  except Exception:
64
77
  pass
65
78
 
@@ -92,11 +105,11 @@ def _handle(payload: dict) -> dict:
92
105
  # either corrupts content or fails and forces a costly full re-read.
93
106
  # Surface it BEFORE the edit lands — force_ask, never deny.
94
107
  # Kill switch: TOKENSAFE_STALE_GUARD=0.
95
- if tool_name in ("edit_file", "replace_file_content"):
108
+ if canon_tool == "edit":
96
109
  try:
97
110
  from src.file_state import FileState
98
111
  if FileState.guard_enabled():
99
- raw_path = str(args.get("Path") or args.get("TargetFile") or args.get("path") or "")
112
+ raw_path = str(args.get("Path") or args.get("TargetFile") or args.get("path") or args.get("file_path") or "")
100
113
  stale = FileState.check_stale(_resolve_hook_path(raw_path, hook_cwd)) if raw_path else None
101
114
  if stale:
102
115
  tracker.record_event(
@@ -124,11 +137,16 @@ def _handle(payload: dict) -> dict:
124
137
  pass
125
138
 
126
139
  # 2. TokenSafe Guard: Inspect file writes and edits for security violations
127
- if tool_name in ("write_file", "edit_file"):
140
+ if canon_tool in ("write", "edit"):
128
141
  from src.guard import TokenSafeGuard
129
- raw_path = str(args.get("Path") or args.get("TargetFile") or args.get("path") or "")
142
+ from src.adapter_core import extract_write_content
143
+ raw_path = str(args.get("Path") or args.get("TargetFile") or args.get("path") or args.get("file_path") or "")
130
144
  path = _resolve_hook_path(raw_path, hook_cwd)
131
- code_to_check = args.get("Content", "") if tool_name == "write_file" else args.get("Replacement", "")
145
+ code_to_check = (
146
+ (args.get("Content") or args.get("content") or "")
147
+ if canon_tool == "write"
148
+ else (extract_write_content(tool_name, args) or "")
149
+ )
132
150
  guard_res = TokenSafeGuard.inspect_file_write(path, code_to_check)
133
151
  if guard_res.blocked:
134
152
  tracker.record_event(
@@ -158,23 +176,22 @@ def _handle(payload: dict) -> dict:
158
176
 
159
177
  # 3. Output Guard (shared guard_write, v3.0.0): deny wholesale overwrite of
160
178
  # large existing files to enforce edit_file; ask on small-delta writes.
161
- if tool_name == "write_file":
162
- raw_path = str(args.get("Path") or args.get("path") or "")
179
+ if canon_tool == "write":
180
+ raw_path = str(args.get("Path") or args.get("path") or args.get("file_path") or "")
163
181
  path = _resolve_hook_path(raw_path, hook_cwd)
164
- content = args.get("Content", "")
165
- is_append = args.get("Append", False)
182
+ content = args.get("Content") or args.get("content") or ""
183
+ is_append = args.get("Append", args.get("append", False))
166
184
  verdict = guard_write(path, str(content or ""), bool(is_append), "antigravity", conversation_id)
167
185
  if verdict["decision"] in ("deny", "ask"):
168
186
  _trigger_bg_sync()
169
187
  return {"decision": verdict["decision"], "reason": verdict["reason"]}
170
188
 
171
189
  # 3. read_file Optimization (AST Windowing & Skeletonization).
172
- # 'view_file' is the IDE-surface name for the same tool (hooks.md) —
173
- # route it through the same optimization pipeline.
174
- elif tool_name in ("read_file", "view_file"):
190
+ # 'view_file' and 'Read' route through the same optimization pipeline.
191
+ elif canon_tool == "read":
175
192
  from src.slicer import ToolSlicer
176
193
  from src.skeletonizer import Skeletonizer
177
- raw_path = str(args.get("Path") or args.get("path") or args.get("FilePath") or "")
194
+ raw_path = str(args.get("Path") or args.get("path") or args.get("FilePath") or args.get("file_path") or "")
178
195
  path = _resolve_hook_path(raw_path, hook_cwd)
179
196
  start_line = args.get("StartLine")
180
197
  if start_line is None:
@@ -325,11 +342,11 @@ def _handle(payload: dict) -> dict:
325
342
  return response
326
343
 
327
344
  # 4. run_command Optimization & TokenSafe Guard
328
- elif tool_name == "run_command":
345
+ elif canon_tool == "bash":
329
346
  from src.guard import TokenSafeGuard
330
347
  from src.diff_slicer import DiffSlicer
331
348
  from src.command_sanitizer import CommandSanitizer
332
- cmd = str(args.get("CommandLine") or "")
349
+ cmd = str(args.get("CommandLine") or args.get("command") or "")
333
350
  guard_res = TokenSafeGuard.inspect_command(cmd, cwd=hook_cwd)
334
351
  if guard_res.blocked:
335
352
  tracker.record_event(
@@ -376,7 +393,8 @@ def _handle(payload: dict) -> dict:
376
393
  new_cmd, est_saved, reason = diff_cmd, diff_saved, diff_reason
377
394
 
378
395
  if new_cmd and est_saved > 0:
379
- response["overwrite"] = {"CommandLine": new_cmd}
396
+ cmd_key = "command" if "command" in args and "CommandLine" not in args else "CommandLine"
397
+ response["overwrite"] = {cmd_key: new_cmd}
380
398
  response["reason"] = f"Token Optimizer: {reason} (Saved ~{est_saved} tokens)"
381
399
 
382
400
  tracker.record_event(
@@ -85,12 +85,13 @@ def main():
85
85
  # hooks.md: hook CWD is the plugin directory, not the workspace — use the
86
86
  # workspacePaths from the payload for project-scoped audits.
87
87
  raw_ws = payload.get("workspacePaths")
88
- workspace_paths = raw_ws if isinstance(raw_ws, list) else []
89
- workspace_root = str(workspace_paths[0]) if workspace_paths else os.getcwd()
88
+ workspace_paths = [str(w) for w in raw_ws if str(w).strip()] if isinstance(raw_ws, list) else []
89
+ workspace_root = workspace_paths[0] if workspace_paths else os.getcwd()
90
90
  try:
91
91
  from src.paths import save_active_workspace, ensure_tokensafe_gitignore
92
- save_active_workspace(workspace_root)
93
- ensure_tokensafe_gitignore(workspace_root)
92
+ if workspace_paths:
93
+ save_active_workspace(workspace_root)
94
+ ensure_tokensafe_gitignore(workspace_root)
94
95
  except Exception:
95
96
  pass
96
97
 
@@ -111,7 +112,7 @@ def main():
111
112
  f"{directives}\n\n"
112
113
  f"{banner}\n"
113
114
  "⚡ Core God Nodes and dependency hubs mapped above. "
114
- "Call 'tokensafe:get_architecture_graph(project_path)' for full dependency trees."
115
+ "Call 'tokensafe:repo_map(view=\"graph\", project_path=...)' for full dependency trees."
115
116
  )
116
117
  except Exception:
117
118
  pass
@@ -135,6 +136,14 @@ def main():
135
136
  except Exception:
136
137
  pass
137
138
 
139
+ try:
140
+ from src.adapter_core import format_cumulative_banner
141
+ cum_banner = format_cumulative_banner()
142
+ if cum_banner:
143
+ system_sections.append(cum_banner)
144
+ except Exception:
145
+ pass
146
+
138
147
  inject_steps = [
139
148
  {"systemMessage": {"systemMessage": "\n\n".join(system_sections), "metadata": {}}}
140
149
  ]
@@ -156,11 +165,8 @@ def main():
156
165
  except Exception:
157
166
  pass
158
167
 
159
- try:
160
- import threading
161
- threading.Thread(target=LicenseManager.ensure_community_license, daemon=True).start()
162
- except Exception:
163
- pass
168
+ # Variant A: Anonymous installs stay on 50k Guest mode until `tokensafe login`
169
+ # unlocks the 500k Community license (never auto-issue 500k in SessionStart).
164
170
 
165
171
  try:
166
172
  bloat_warning = EnvironmentAuditor.get_bloat_warning(workspace_root=workspace_root)
@@ -169,6 +175,18 @@ def main():
169
175
  except Exception:
170
176
  pass
171
177
 
178
+ try:
179
+ from src.burn_monitor import get_burn_warnings
180
+ burn_warn = get_burn_warnings(
181
+ agent="antigravity",
182
+ session_id=str(payload.get("conversationId") or ""),
183
+ transcript_path=str(payload.get("transcriptPath") or ""),
184
+ )
185
+ if burn_warn:
186
+ inject_steps.append(_user_markdown(burn_warn))
187
+ except Exception:
188
+ pass
189
+
172
190
  print(json.dumps({"injectSteps": inject_steps}))
173
191
 
174
192
 
@@ -0,0 +1,95 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ TokenSafe adapter for ZCode (Z.ai Code) lifecycle hooks (~/.zcode/cli/config.json).
4
+
5
+ Speaks the ZCode / Claude Code JSON hook contract:
6
+ SessionStart -> injects TokenSafe directives, God Nodes banner, and burn alerts.
7
+ UserPromptSubmit -> compacts prompt (TOCP) + emits live burn warnings from model-io-*.jsonl.
8
+ PreToolUse -> LoopDetector, MistakesLedger, Bash/Write/Edit/Read guards, stale-edit check.
9
+ PostToolUse -> compacts verbose shell output, records FileState + command failures.
10
+ Stop -> flushes telemetry and runs optional fold-at-rest.
11
+
12
+ Contract: stdin = one JSON payload, stdout = one JSON response ({} on clean allow).
13
+ """
14
+
15
+ import json
16
+ import os
17
+ import sys
18
+
19
+ HOOK_DIR = os.path.dirname(os.path.realpath(__file__))
20
+ PROJECT_ROOT = os.path.dirname(HOOK_DIR)
21
+ if PROJECT_ROOT not in sys.path:
22
+ sys.path.insert(0, PROJECT_ROOT)
23
+
24
+ from hooks.claude_code_hook import handle as _cc_handle # noqa: E402
25
+
26
+ AGENT = "zcode"
27
+
28
+
29
+ def handle(event: str, payload: dict) -> dict:
30
+ # Normalize ZCode-specific camelCase aliases onto CC fields while preserving existing keys.
31
+ norm = dict(payload)
32
+ if not norm.get("session_id") and norm.get("conversationId"):
33
+ norm["session_id"] = norm["conversationId"]
34
+ if not norm.get("prompt") and norm.get("lastUserInput"):
35
+ norm["prompt"] = norm["lastUserInput"]
36
+ if not norm.get("transcript_path") and norm.get("transcriptPath"):
37
+ norm["transcript_path"] = norm["transcriptPath"]
38
+ if not norm.get("tool_name") and isinstance(norm.get("toolCall"), dict):
39
+ tc = norm["toolCall"]
40
+ norm["tool_name"] = tc.get("name") or ""
41
+ if not norm.get("tool_input"):
42
+ raw_in = tc.get("args") if tc.get("args") is not None else (tc.get("input") if tc.get("input") is not None else tc.get("arguments"))
43
+ if isinstance(raw_in, dict):
44
+ norm["tool_input"] = raw_in
45
+ elif isinstance(raw_in, str) and raw_in.strip():
46
+ try:
47
+ parsed_in = json.loads(raw_in)
48
+ if isinstance(parsed_in, dict):
49
+ norm["tool_input"] = parsed_in
50
+ except Exception:
51
+ pass
52
+ if "tool_response" not in norm and "toolResponse" in norm:
53
+ norm["tool_response"] = norm["toolResponse"]
54
+ if not norm.get("cwd") and isinstance(norm.get("workspacePaths"), list) and norm["workspacePaths"]:
55
+ norm["cwd"] = str(norm["workspacePaths"][0])
56
+ return _cc_handle(event, norm, agent=AGENT)
57
+
58
+
59
+ def main():
60
+ try:
61
+ raw = sys.stdin.read()
62
+ payload = json.loads(raw) if raw.strip() else {}
63
+ if not isinstance(payload, dict):
64
+ payload = {}
65
+ except Exception:
66
+ print(json.dumps({}))
67
+ return
68
+ event = ""
69
+ try:
70
+ event = str(payload.get("hook_event_name") or payload.get("hookEventName") or "")
71
+ if not event:
72
+ if "tool_name" in payload or "toolCall" in payload:
73
+ event = "PostToolUse" if ("tool_response" in payload or "toolResponse" in payload) else "PreToolUse"
74
+ elif "prompt" in payload or "lastUserInput" in payload:
75
+ event = "UserPromptSubmit"
76
+ elif "terminationReason" in payload or "fullyIdle" in payload:
77
+ event = "Stop"
78
+ else:
79
+ event = "SessionStart"
80
+ response = handle(event, payload)
81
+ if not isinstance(response, dict):
82
+ response = {}
83
+ except Exception:
84
+ response = {}
85
+ if event in ("UserPromptSubmit", "PreToolUse", "PostToolUse", "Stop"):
86
+ try:
87
+ from src.telemetry_sync import TelemetrySync
88
+ TelemetrySync.sync_background(throttle_seconds=0.0 if event == "Stop" else 20.0)
89
+ except Exception:
90
+ pass
91
+ print(json.dumps(response))
92
+
93
+
94
+ if __name__ == "__main__":
95
+ main()
package/hooks.json CHANGED
@@ -24,7 +24,7 @@
24
24
  ],
25
25
  "PreToolUse": [
26
26
  {
27
- "matcher": "read_file|view_file|run_command|write_file|edit_file",
27
+ "matcher": "read_file|view_file|run_command|write_file|edit_file|replace_file_content|multi_replace_file_content|find_by_name|grep_search|list_dir",
28
28
  "hooks": [
29
29
  {
30
30
  "type": "command",
package/kimi.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokensafe",
3
- "version": "4.5.0",
3
+ "version": "4.5.2",
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",
@@ -52,11 +52,27 @@
52
52
  "command": "python3 hooks/kimi_hook.py",
53
53
  "timeout": 10
54
54
  },
55
+ {
56
+ "event": "PreToolUse",
57
+ "matcher": "Edit",
58
+ "command": "python3 hooks/kimi_hook.py",
59
+ "timeout": 10
60
+ },
55
61
  {
56
62
  "event": "PreToolUse",
57
63
  "matcher": "Read",
58
64
  "command": "python3 hooks/kimi_hook.py",
59
65
  "timeout": 10
66
+ },
67
+ {
68
+ "event": "PostToolUse",
69
+ "command": "python3 hooks/kimi_hook.py",
70
+ "timeout": 10
71
+ },
72
+ {
73
+ "event": "Stop",
74
+ "command": "python3 hooks/kimi_hook.py",
75
+ "timeout": 15
60
76
  }
61
77
  ]
62
78
  }
package/mcp_config.json CHANGED
@@ -7,19 +7,25 @@
7
7
  "exec \"${TOKENSAFE_PYTHON:-python3}\" \"$PLUGIN_ROOT/src/mcp_server.py\""
8
8
  ],
9
9
  "tools": {
10
+ "smart_read_file": {
11
+ "eager": true
12
+ },
13
+ "scoped_search": {
14
+ "eager": true
15
+ },
10
16
  "apply_edits": {
11
17
  "eager": true
12
18
  },
13
- "batch_search": {
19
+ "repo_map": {
14
20
  "eager": true
15
21
  },
16
- "scoped_search": {
22
+ "session_context": {
17
23
  "eager": true
18
24
  },
19
- "smart_read_file": {
25
+ "oumv": {
20
26
  "eager": true
21
27
  },
22
- "get_architecture_graph": {
28
+ "run_helper": {
23
29
  "eager": true
24
30
  }
25
31
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "4.5.0",
4
+ "version": "4.5.2",
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.0",
4
+ "version": "4.5.2",
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/rules/AGENTS.md CHANGED
@@ -21,32 +21,32 @@ Execute the specified action directly based on these extracted parameters.
21
21
 
22
22
  ### 2. Zero-Fluff Output Directives (Egress Optimization)
23
23
  1. **No Conversational Filler**: Never include courtesy greetings or sign-offs (e.g., "Certainly!", "Sure, I can help", "Let me know if you need anything else").
24
- 2. **Surgical Code Edits, Batching & Zero In-Place Stream Editing**: Prefer `apply_edits` for >=2 hunks/files or edit + verify loops (`tokensafe:apply_edits(edits=[...], verify="npm test")`) to replace serial edit turns. For single surgical tweaks, prefer `edit_file` with concise `Target` and `Replacement`. NEVER run terminal stream editors (`sed -i`, `perl -i`, `awk -i`) to edit or delete source code — blind numeric ranges cause line-drift and silent code loss (hard-blocked by TokenSafe Guard). NEVER suppress errors (`2>/dev/null`) on file modifications.
24
+ 2. **Surgical Code Edits, Batching & Zero In-Place Stream Editing**: Prefer `tokensafe:apply_edits(edits=[...], verify="npm test")` for >=2 hunks/files or edit + verify loops. For single tweaks, use `edit_file` with exact `Target` and `Replacement`. NEVER run terminal stream editors (`sed -i`, `perl -i`, `awk -i`) on source code (hard-blocked by TokenSafe Guard), and never suppress errors (`2>/dev/null`).
25
25
  3. **Diff-Centric Responses**: Never reprint entire unmodified files or long boilerplate blocks. Reference file lines instead (e.g., `wallet.ts#L42-L50`).
26
26
  4. **Dense Formatting**: Use compact bullet points and direct technical prose.
27
- 5. **Repeat Read Deduplication**: Never re-read unchanged files or symbols in the same session. Reuse the skeleton or pointer reference (`// [TokenSafe: Pointer Hit ...]`) returned earlier; only pass `force_full=true` if your context was compacted or you are a fresh subagent.
28
- 6. **Compact Test Output Execution**: Run unit tests with concise flags or via `tokensafe tests [cmd]` so passing test runs return a 1-line summary (`PASS: ...`) rather than flooding `Messages` history with hundreds of verbose log lines. Full output is preserved only on failure.
29
- 7. **Multimodal Image Isolation (Prompt Cache Protection)**: Loading `.png`/`.jpg`/`.webp` images or screenshots into a long (>150k-token) coding conversation triggers KV-cache invalidation and a 3-7x TTFT cliff (40-97s/turn). ALWAYS delegate visual inspection of any screenshot or image to a subagent that returns a concise text-only list of findings (selectors, coordinates, values, error text); NEVER load raw images into the main coding session.
30
- 8. **Startup Snapshot Utilization**: On turn 1 of any session, check the injected `[TokenSafe Workspace Snapshot]` (git branch, modified tree, last 3 commits, 2-level layout, detected scripts) before running exploratory `ls`, `git status`, or reading project scripts.
31
- 9. **Zero-Spill 8.8 KB Cap & Reversible Stash**: All TokenSafe MCP outputs are hard-capped at <= 8.8 KB (UTF-8) with `[TokenSafe folded: #hash ...]` anchors to prevent Antigravity `output.txt` disk spills. Call `tokensafe:expand_ref(hash)` if full raw content is needed.
32
-
33
- ### 3. Architecture & Code Navigation Directives (Graph-Guided)
34
- 1. **Zero Raw Terminal Grep/Find (Blocked & Replaced by `scoped_search` / `batch_search`)**: Strictly NEVER execute terminal `grep`, `egrep`, `ripgrep`, or `find` on source code files or directories (`src/`, `views/`, `components/`, `.ts`, `.tsx`, `.py`, `.js`). These commands are hard-blocked by TokenSafe Guard. To search for text, symbols, or functions across unknown files, call `tokensafe:scoped_search(query, path=".", scope="code")`. When running >=2 queries (or combining code search with git checks), ALWAYS call `tokensafe:batch_search(queries=[...])` to execute up to 20 queries concurrently in 1 call (<70ms local) without paying per-command remote safety check overhead.
35
- 2. **Mandatory Symbol & Component Inspection**: Whenever locating or reading a function, class, component, or method, ALWAYS call `tokensafe:smart_read_file` with `path` (relative e.g. `"src/service.ts"` or absolute) and `symbol`. By default (`dep_mode="signature"`), it preserves the full executable target and compact 1-line 1-hop dependency signatures while folding inert code (-95%+ tokens). Pass `dep_mode="full"` only when dependency bodies are needed, or `force_full=true` if a cache pointer references content missing from your context. When you need 3+ related symbols across several files, call `tokensafe:smart_bundle(targets=[{path, symbol}])` ONCE instead of repeated `smart_read_file` calls — it merges the skeletons and deduplicates shared imports/types in a single roundtrip. For OpenAPI/Prisma/GraphQL/SQL schema files `smart_read_file` auto-slices: pass the spec path/model/type/table as `symbol` (empty `symbol` returns a compact overview). Lockfiles (`package-lock.json`, `Cargo.lock`) and tabular data (`.csv`, `.tsv`, `.sql`, `.har`) auto-reduce to compact schemas with reversible hash anchors.
36
- 3. **Reversible Hash Stashing (`expand_ref`)**: Whenever TokenSafe folds a long command output, test log, file, or MCP payload, it tags it with an 8-character hash `[TokenSafe folded: #a1b2c3d4 ...]`. If full raw content is ever needed, ALWAYS call `tokensafe:expand_ref(hash="a1b2c3d4")` or run `tokensafe expand-ref a1b2c3d4` to retrieve the exact original bytes without re-running.
37
- 4. **Web & Documentation Reading (`read_web_page`)**: To read web pages, documentation, or API references, ALWAYS call `tokensafe:read_web_page(url)` or run `tokensafe web <url>` instead of raw HTML fetches — it strips scripts, styles, navbars, and cookie banners (-80-95% tokens).
38
- 5. **Mandatory Architecture Graph & God Nodes First**: For ANY codebase inquiry, feature design, refactoring, or multi-component investigation, your FIRST tool call MUST be `tokensafe:get_architecture_graph(project_path)` to locate God Nodes and dependency topology in < 250 tokens before reading individual files or searching (pass the target project's absolute path when working across multiple workspaces or outside CWD).
39
- 6. **API Surface Map**: Use `tokensafe:get_api_surface(project_path)` to get all exported classes, types, and interfaces in a single markdown map without crawling files (pass the target project's absolute path when working across multiple workspaces or outside CWD).
40
- 7. **Bounded Reads**: Never call `read_file` without `StartLine`/`EndLine` on files > 100 lines unless inspecting a skeleton.
41
- 8. **Directory Navigation**: Never run verbose `ls -la` or `ls -l`; use `tokensafe:list_dir(path=".", depth=2)` to inspect directory trees without permissions, timestamps, or lockfiles (-90% tokens). Supports relative subfolders (`path="src"`).
42
- 9. **Style & Design Tokens**: When inspecting CSS/SCSS/LESS/Tailwind, `tokensafe:smart_read_file` automatically preserves all design tokens (`:root`, `@theme`, CSS variables) in full while folding component selectors.
43
- 10. **Command Output Wrapping & Test Execution**: Run noisy commands, builds, and test suites (`bun test`, `pytest`, `python -m unittest`, `vitest`, `jest`, `cargo test`, `go test`) via `tokensafe wrap '<command>'` or `tokensafe tests [cmd]`. Sanitization automatically strips `git push` progress animation frames (`--no-progress`), wraps `git commit` when pre-commit/husky hooks exist, and forces test runners into run-once mode. Passing tests return a 1-line summary (`✓ PASS: ...`), and failures return focused failure blocks with full tracebacks preserved in stash.
44
- 11. **Context Budget & Smart Compaction**: Before large multi-step tasks, call `tokensafe:context_budget(model=...)` to check window usage and Context Quality Score (Grade S-F). When it reports `warning`, `critical`, or Grade C/F, call `tokensafe:compact_conversation(transcript_path=...)` to fold past turns into a Consolidated State Ledger with a 3-line Post-Compaction Orientation Digest (Active Goal, Last State, Next Focus) before continuing.
45
- 12. **Vision Image Optimization (`optimize_image`)**: When handling screenshots or visual diagrams, call `tokensafe:optimize_image` or run `tokensafe optimize-image <file>` to downscale images exceeding 1024px (-50-75% vision tokens) while preserving original disk files.
46
- 13. **Superseded Output Pruning (`prune_superseded`)**: In long multi-turn sessions, prune obsolete intermediate file reads via `tokensafe:prune_superseded(transcript_path)` to free up context without losing history.
47
- 14. **Anti-Stuck Revert Memory (`get_mistakes`) & Hybrid Escalation**: Consult `tokensafe:get_mistakes` to retrieve persistent records of prior dead-ends, loop guard trips, and git reverts to avoid attempting previously failed solutions. The 2-tier hybrid escalation policy issues a soft advisory warning for 1-2 failures and triggers `force_ask` if an identical action or command fails >2 times within 30 minutes, automatically broadcasting scrubbed failure summaries to the team.
48
- 15. **External Types & Lockfile Point Queries**: Use `tokensafe:slice_external_type(package_name, type_name)` to extract 3rd-party TypeScript interfaces from `node_modules` without crawling directories (-95% tokens, L1/L2/L3 cached). Use `tokensafe:query_dependency(lockfile_path, package_name)` for instant lockfile point lookups in <50 tokens; raw `read_file` on lockfiles without bounds is redirected to an index summary.
49
- 16. **Universal OUMV Protocol (Runtime Introspection & Verification Directives)**: For live Frontend (ports 5173/3000 across `tokensafe-ui`, React 18/19 with Zustand/Redux/Context/useReducer, and Vue 3) and Backend (ports 8080/8000) services, inspect connectivity via `tokensafe:oumv_status()`. Observe state progressively: `tokensafe:oumv_observe(level="L0")` for pulse (~20 tokens), `L1` for endpoints/models/interactive surface (~150 tokens), `L2` for target contracts or DTO schemas. Never guess state flows or bugs — query runtime causality via `tokensafe:oumv_understand(query="causality")` or `why_state`. Verify actions in-memory (UI synthetic actions, store updates, or backend transactional sandbox with automatic DB rollback) via `tokensafe:oumv_verify(target=..., action=..., payload={...})` instead of heavy browser runs or blind shell curls. Apply OCC edits with `tokensafe:oumv_mutate(path=..., expectedVersion=...).`
27
+ 5. **Repeat Read Deduplication**: Never re-read unchanged files or symbols in the same session. Reuse the skeleton or pointer reference (`// [TokenSafe: Pointer Hit ...]`) returned earlier; pass `force_full=true` only after compaction or as a fresh subagent.
28
+ 6. **Compact Test Output Execution**: Run unit tests via `tokensafe tests [cmd]` or `tokensafe wrap '<cmd>'` so passing suites return a 1-line summary (`PASS: ...`), preserving full output only on failure.
29
+ 7. **Multimodal Image Isolation (Prompt Cache Protection)**: Never load raw `.png`/`.jpg`/`.webp` screenshots into a long (>150k-token) coding session (triggers KV-cache invalidation). Delegate visual inspection to a subagent returning text-only findings.
30
+ 8. **Startup Snapshot Utilization**: Check `[TokenSafe Workspace Snapshot]` on turn 1 before running exploratory `ls` or `git status`.
31
+ 9. **Zero-Spill 8.8 KB Cap & Reversible Stash**: All TokenSafe MCP outputs are capped at <= 8.8 KB with `[TokenSafe folded: #hash ...]` anchors. Call `tokensafe:run_helper(action="expand", hash="...")` if full raw content is needed.
32
+
33
+ ### 3. Architecture & Code Navigation Directives (7 Consolidated MCP Tools)
34
+ 1. **Search (`scoped_search`)**: Terminal `grep`/`egrep`/`rg`/`find` on source files are BLOCKED. Call `tokensafe:scoped_search(query, path=".", scope="code")` (supports `mode="auto|text|regex|glob|fuzzy|git"`) or pass `queries=[...]` for up to 20 concurrent queries in 1 call (<70ms local).
35
+ 2. **Symbol, Bundle & External Type Reads (`smart_read_file`)**: Call `tokensafe:smart_read_file(path, symbol)` (`dep_mode="signature"` default, `"full"` when needed, `force_full=true` on pointer miss; OpenAPI/Prisma/GraphQL/SQL auto-slice via `symbol`). Pass `targets=[{path, symbol}]` (2–8 targets) to bundle files with deduplicated imports, or `package_name` + `symbol` for 3rd-party `.d.ts` interfaces.
36
+ 3. **Architecture, API Surface & Directory Trees (`repo_map`)**: First inspect God Nodes via `tokensafe:repo_map(view="graph", project_path=...)` before crawling files. Use `view="api"` for exported types/interfaces and `view="tree"` (never `ls -la`).
37
+ 4. **Multi-File Edits (`apply_edits`)**: Batch >=2 hunks/files and optional `verify` commands in a single turn.
38
+ 5. **Session & Context Hygiene (`session_context`)**: Call `tokensafe:session_context(action="budget", model=...)` before large tasks; when `warning`/`critical` or Grade C/F, call `action="compact"` with `transcript_path`. Use `action="prune"` for superseded reads, `action="mistakes"` for anti-stuck dead-end memory, and `action="metrics"` for savings analytics.
39
+ 6. **Utilities (`run_helper`)**: Call `tokensafe:run_helper(action=...)` for:
40
+ - `"expand"` (`hash`): restore stashed `#hash` content
41
+ - `"web"` (`url`): fetch clean Markdown docs (-80-95% tokens, L1/L2/L3 cached)
42
+ - `"deps"` (`package_name`, `lockfile_path`): point lockfile lookup in <50 tokens
43
+ - `"sanitize"` (`command`, `cwd`): rewrite noisy shell/test commands
44
+ - `"guard"` (`command`/`code`, `file_path`): pre-flight security/hygiene audit
45
+ - `"diff"` (`diff`): slice unified git diffs
46
+ - `"image"` (`image_path`, `max_edge=1024`): downscale screenshots (-50-75% vision tokens)
47
+ - `"compress"` (`prompt`): TOCP S-expression compression
48
+ 7. **Universal OUMV Protocol (`oumv`)**: For live Frontend (ports 5173/3000) and Backend (ports 8080/8000) runtimes, call `tokensafe:oumv(action="status"|"observe"|"understand"|"verify"|"mutate"|"graph", ...)` instead of headless browsers or blind shell curls.
49
+ 8. **Bounded Reads & Styles**: Never call raw `read_file` without `StartLine`/`EndLine` on files > 100 lines. `smart_read_file` preserves CSS/SCSS/Tailwind design tokens (`:root`, `@theme`) in full.
50
50
 
51
51
  ### 4. Turn Token Savings Footer (Proof-of-Savings — always in English)
52
52
  At the end of your response for any turn where tools were executed, files were inspected, commands were sanitized, or prompts were compacted, append a compact 1-line footer:
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.0",
6
+ "version": "4.5.2",
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.0",
26
+ "version": "4.5.2",
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.0",
42
+ "version": "4.5.2",
43
43
  "runtimeHint": "uvx",
44
44
  "transport": {
45
45
  "type": "stdio"