tokensafe 2.7.0 → 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 (44) 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 +139 -83
  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 +65 -40
  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 +1 -1
  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/slicer.py +15 -3
  39. package/src/team_cache.py +10 -3
  40. package/src/telemetry_sync.py +110 -39
  41. package/src/tokenizer.py +24 -13
  42. package/src/treesitter_backend.py +1 -0
  43. package/src/version_checker.py +67 -32
  44. package/src/weekly_digest.py +6 -3
package/bin/tokensafe CHANGED
@@ -6,7 +6,7 @@ TokenSafe standalone CLI launcher.
6
6
  import sys
7
7
  import os
8
8
 
9
- SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
9
+ SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
10
10
  PROJECT_ROOT = os.path.dirname(SCRIPT_DIR)
11
11
  if PROJECT_ROOT not in sys.path:
12
12
  sys.path.insert(0, PROJECT_ROOT)
@@ -1,7 +1,19 @@
1
1
  const vscode = require('vscode');
2
- const { exec } = require('child_process');
2
+ const { execFile } = require('child_process');
3
3
  const path = require('path');
4
4
  const fs = require('fs');
5
+ const os = require('os');
6
+
7
+ function resolveDashboardHtml(projectRoot) {
8
+ const candidates = [
9
+ path.join(os.homedir(), ".tokensafe", "data", "dashboard.html"),
10
+ path.join(projectRoot, "data", "dashboard.html"),
11
+ ];
12
+ for (const p of candidates) {
13
+ if (fs.existsSync(p)) return p;
14
+ }
15
+ return candidates[0];
16
+ }
5
17
 
6
18
  function activate(context) {
7
19
  const statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 100);
@@ -14,11 +26,10 @@ function activate(context) {
14
26
  const projectRoot = path.dirname(path.dirname(__dirname));
15
27
  const candidateTokensafe = path.join(projectRoot, "bin", "tokensafe");
16
28
  const cliPath = fs.existsSync(candidateTokensafe) ? candidateTokensafe : path.join(projectRoot, "bin", "agy-tokens");
17
- const dashboardHtml = path.join(projectRoot, "data", "dashboard.html");
18
29
 
19
30
  const disposableStats = vscode.commands.registerCommand('tokensafe.showStats', () => {
20
31
  if (fs.existsSync(cliPath)) {
21
- exec(`python3 "${cliPath}" stats`, (error, stdout) => {
32
+ execFile('python3', [cliPath, 'stats'], (error, stdout) => {
22
33
  if (stdout) {
23
34
  vscode.window.showInformationMessage(`TokenSafe Savings:\n${stdout.split('\n').slice(0, 5).join('\n')}`);
24
35
  } else {
@@ -31,14 +42,16 @@ function activate(context) {
31
42
  });
32
43
 
33
44
  const disposableDash = vscode.commands.registerCommand('tokensafe.openDashboard', () => {
34
- if (fs.existsSync(dashboardHtml)) {
35
- vscode.env.openExternal(vscode.Uri.file(dashboardHtml));
45
+ const existingHtml = resolveDashboardHtml(projectRoot);
46
+ if (fs.existsSync(existingHtml)) {
47
+ vscode.env.openExternal(vscode.Uri.file(existingHtml));
36
48
  } else {
37
49
  vscode.window.showInformationMessage("Generating TokenSafe dashboard...");
38
50
  if (fs.existsSync(cliPath)) {
39
- exec(`python3 "${cliPath}" html`, () => {
40
- if (fs.existsSync(dashboardHtml)) {
41
- vscode.env.openExternal(vscode.Uri.file(dashboardHtml));
51
+ execFile('python3', [cliPath, 'html'], () => {
52
+ const generatedHtml = resolveDashboardHtml(projectRoot);
53
+ if (fs.existsSync(generatedHtml)) {
54
+ vscode.env.openExternal(vscode.Uri.file(generatedHtml));
42
55
  }
43
56
  });
44
57
  }
@@ -17,7 +17,7 @@ import sys
17
17
  import json
18
18
  import os
19
19
 
20
- HOOK_DIR = os.path.dirname(os.path.abspath(__file__))
20
+ HOOK_DIR = os.path.dirname(os.path.realpath(__file__))
21
21
  PROJECT_ROOT = os.path.dirname(HOOK_DIR)
22
22
  if PROJECT_ROOT not in sys.path:
23
23
  sys.path.insert(0, PROJECT_ROOT)
@@ -111,7 +111,8 @@ def handle(event: str, payload: dict) -> dict:
111
111
  transcript_path, turn
112
112
  )
113
113
  if folded and stats.get("saved_tokens", 0) > 0:
114
- tracker = MetricsTracker()
114
+ if tracker is None:
115
+ tracker = MetricsTracker()
115
116
  prev_event = tracker.get_last_event(session_id, "HISTORY_FOLD")
116
117
  prev_orig = 0
117
118
  if prev_event and isinstance(prev_event.get("details"), dict):
@@ -147,7 +148,9 @@ def handle(event: str, payload: dict) -> dict:
147
148
 
148
149
  if event == "PreToolUse":
149
150
  tool = str(payload.get("tool_name") or "")
150
- tool_input = payload.get("tool_input") or {}
151
+ tool_input = payload.get("tool_input")
152
+ if not isinstance(tool_input, dict):
153
+ tool_input = {}
151
154
  if tool in ("Bash", "Shell", "bash"):
152
155
  command = str(tool_input.get("command") or "")
153
156
  verdict = guard_command(command, AGENT, session_id)
@@ -176,12 +179,17 @@ def main():
176
179
  try:
177
180
  raw = sys.stdin.read()
178
181
  payload = json.loads(raw) if raw.strip() else {}
182
+ if not isinstance(payload, dict):
183
+ payload = {}
179
184
  except Exception:
180
185
  print(json.dumps({}))
181
186
  return
182
- event = str(payload.get("hook_event_name") or "")
187
+ event = ""
183
188
  try:
184
- response = handle(event, payload if isinstance(payload, dict) else {})
189
+ event = str(payload.get("hook_event_name") or "")
190
+ response = handle(event, payload)
191
+ if not isinstance(response, dict):
192
+ response = {}
185
193
  except Exception:
186
194
  response = {}
187
195
  if event in ("UserPromptSubmit", "PreToolUse", "PostToolUse", "Stop"):
@@ -21,7 +21,7 @@ import sys
21
21
  import json
22
22
  import os
23
23
 
24
- HOOK_DIR = os.path.dirname(os.path.abspath(__file__))
24
+ HOOK_DIR = os.path.dirname(os.path.realpath(__file__))
25
25
  PROJECT_ROOT = os.path.dirname(HOOK_DIR)
26
26
  if PROJECT_ROOT not in sys.path:
27
27
  sys.path.insert(0, PROJECT_ROOT)
@@ -68,12 +68,15 @@ def main():
68
68
  try:
69
69
  raw = sys.stdin.read()
70
70
  payload = json.loads(raw) if raw.strip() else {}
71
+ if not isinstance(payload, dict):
72
+ payload = {}
71
73
  except Exception:
72
- print(json.dumps({}))
74
+ print(json.dumps(_allow("")))
73
75
  return
74
- event = str(payload.get("hook_event_name") or "")
76
+ event = ""
75
77
  try:
76
- response = handle(event, payload if isinstance(payload, dict) else {})
78
+ event = str(payload.get("hook_event_name") or "")
79
+ response = handle(event, payload)
77
80
  except Exception:
78
81
  response = _allow(event)
79
82
  if not isinstance(response, dict) or not response:
@@ -10,11 +10,28 @@ import os
10
10
  import sys
11
11
  import json
12
12
 
13
- HOOK_DIR = os.path.dirname(os.path.abspath(__file__))
13
+ import time
14
+
15
+ HOOK_DIR = os.path.dirname(os.path.realpath(__file__))
14
16
  PROJECT_ROOT = os.path.dirname(HOOK_DIR)
15
17
  if PROJECT_ROOT not in sys.path:
16
18
  sys.path.insert(0, PROJECT_ROOT)
17
19
 
20
+ def _should_skip_fast() -> bool:
21
+ if os.environ.get("TOKENSAFE_TELEMETRY_DISABLED", "").strip().lower() in ("1", "true", "yes"):
22
+ return True
23
+ try:
24
+ data_dir = os.environ.get("TOKENSAFE_DATA_DIR") or os.path.join(os.path.expanduser("~"), ".tokensafe", "data")
25
+ state_file = os.path.join(data_dir, "sync_state.json")
26
+ if os.path.isfile(state_file):
27
+ with open(state_file, "r", encoding="utf-8") as f:
28
+ st = json.load(f)
29
+ if isinstance(st, dict) and (time.time() - float(st.get("last_attempt_at", 0) or 0)) < 20.0:
30
+ return True
31
+ except Exception:
32
+ pass
33
+ return False
34
+
18
35
  def main():
19
36
  try:
20
37
  # Drain stdin to keep pipes clean
@@ -23,11 +40,12 @@ def main():
23
40
  pass
24
41
 
25
42
  # Non-blocking telemetry sync trigger (detached background process)
26
- try:
27
- from src.telemetry_sync import TelemetrySync
28
- TelemetrySync.sync_background(throttle_seconds=20.0)
29
- except Exception:
30
- pass
43
+ if not _should_skip_fast():
44
+ try:
45
+ from src.telemetry_sync import TelemetrySync
46
+ TelemetrySync.sync_background(throttle_seconds=20.0)
47
+ except Exception:
48
+ pass
31
49
 
32
50
  # PostToolUse contract expects an empty JSON object {}
33
51
  print(json.dumps({}))
@@ -16,9 +16,10 @@ import sys
16
16
  import os
17
17
  import json
18
18
 
19
- HOOK_DIR = os.path.dirname(os.path.abspath(__file__))
19
+ HOOK_DIR = os.path.dirname(os.path.realpath(__file__))
20
20
  PROJECT_ROOT = os.path.dirname(HOOK_DIR)
21
- sys.path.insert(0, PROJECT_ROOT)
21
+ if PROJECT_ROOT not in sys.path:
22
+ sys.path.insert(0, PROJECT_ROOT)
22
23
 
23
24
  from src.compactor import PromptCompactor
24
25
  from src.history_compactor import HistoryCompactor
@@ -54,22 +55,14 @@ def _proxy_is_active() -> bool:
54
55
  pass
55
56
  return False
56
57
 
57
- def main():
58
+ def _handle(payload: dict) -> dict:
59
+ last_user_input = str(payload.get("lastUserInput") or "")
60
+ conversation_id = str(payload.get("conversationId") or "default_session")
58
61
  try:
59
- raw_input = sys.stdin.read()
60
- if not raw_input.strip():
61
- print(json.dumps({}))
62
- return
63
-
64
- payload = json.loads(raw_input)
65
- except Exception:
66
- print(json.dumps({}))
67
- return
68
-
69
- last_user_input = payload.get("lastUserInput", "")
70
- conversation_id = payload.get("conversationId", "default_session")
71
- invocation_num = payload.get("invocationNum", 1)
72
- transcript_path = payload.get("transcriptPath", "")
62
+ invocation_num = int(payload.get("invocationNum", 1) or 1)
63
+ except (TypeError, ValueError):
64
+ invocation_num = 1
65
+ transcript_path = str(payload.get("transcriptPath") or "")
73
66
 
74
67
  tracker = MetricsTracker()
75
68
  inject_steps = []
@@ -140,7 +133,7 @@ def main():
140
133
  folded_text = None
141
134
  fresh_fold = False
142
135
  orig_hist_tokens = 0
143
- if not quota.get("is_quota_exceeded", False) and invocation_num >= 3 and transcript_path:
136
+ if not is_quota_exceeded and invocation_num >= 3 and transcript_path:
144
137
  folded_text, orig_hist_tokens, folded_tokens, stats = HistoryCompactor.fold_transcript(
145
138
  transcript_path, invocation_num
146
139
  )
@@ -202,8 +195,15 @@ def main():
202
195
  if not is_valid_remind:
203
196
  guard_unreminded = True
204
197
  else:
205
- reminded_id = int((last_remind.get("details") or {}).get("guard_id", 0))
206
- guard_unreminded = int(recent_guard.get("id", 0)) > reminded_id
198
+ rem_details = last_remind.get("details")
199
+ rem_dict = rem_details if isinstance(rem_details, dict) else {}
200
+ try:
201
+ reminded_id = int(rem_dict.get("guard_id", 0) or 0)
202
+ recent_id = int(recent_guard.get("id", 0) or 0)
203
+ except (TypeError, ValueError):
204
+ reminded_id = 0
205
+ recent_id = 0
206
+ guard_unreminded = recent_id > reminded_id
207
207
  if fresh_fold or guard_unreminded:
208
208
  inject_steps.append({
209
209
  "systemMessage": {
@@ -223,10 +223,7 @@ def main():
223
223
  except Exception:
224
224
  pass
225
225
 
226
- # 5. Context Budget HUD warning: inject once per session when the
227
- # context crosses 80% of the estimated window. history_mass upgrades
228
- # the instrumented floor to a semi-real estimate, so the threshold is
229
- # actually reachable; the warning carries a ready-to-run compact command.
226
+ # 5. Context Budget HUD warning
230
227
  try:
231
228
  budget = ContextBudget.estimate(
232
229
  tracker, session_id=conversation_id,
@@ -262,9 +259,25 @@ def main():
262
259
  except Exception:
263
260
  pass
264
261
 
265
- response = {}
266
- if inject_steps:
267
- response["injectSteps"] = inject_steps
262
+ return {"injectSteps": inject_steps} if inject_steps else {}
263
+
264
+
265
+ def main():
266
+ try:
267
+ raw_input = sys.stdin.read()
268
+ if not raw_input.strip():
269
+ print(json.dumps({}))
270
+ return
271
+ payload = json.loads(raw_input)
272
+ if not isinstance(payload, dict):
273
+ print(json.dumps({}))
274
+ return
275
+ response = _handle(payload)
276
+ if not isinstance(response, dict):
277
+ response = {}
278
+ except Exception:
279
+ # Fail-open: never block user prompt submission on internal/SQLite errors
280
+ response = {}
268
281
 
269
282
  print(json.dumps(response))
270
283
 
@@ -12,21 +12,15 @@ import sys
12
12
  import os
13
13
  import json
14
14
 
15
- HOOK_DIR = os.path.dirname(os.path.abspath(__file__))
15
+ HOOK_DIR = os.path.dirname(os.path.realpath(__file__))
16
16
  PROJECT_ROOT = os.path.dirname(HOOK_DIR)
17
- sys.path.insert(0, PROJECT_ROOT)
17
+ if PROJECT_ROOT not in sys.path:
18
+ sys.path.insert(0, PROJECT_ROOT)
18
19
 
19
- from src.slicer import ToolSlicer
20
- from src.skeletonizer import Skeletonizer
21
- from src.command_sanitizer import CommandSanitizer
22
20
  from src.loop_detector import LoopDetector
23
21
  from src.metrics import MetricsTracker
24
22
  from src.tokenizer import count_tokens
25
- from src.agent_firewall import AgentFirewall
26
- from src.diff_slicer import DiffSlicer
27
23
  from src.license_manager import LicenseManager
28
- from src.secret_redactor import SecretRedactor
29
- from src.guard import TokenSafeGuard
30
24
 
31
25
 
32
26
  def _trigger_bg_sync():
@@ -37,30 +31,32 @@ def _trigger_bg_sync():
37
31
  pass
38
32
 
39
33
 
40
- def main():
41
- try:
42
- raw_input = sys.stdin.read()
43
- if not raw_input.strip():
44
- print(json.dumps({"decision": "allow"}))
45
- return
46
-
47
- payload = json.loads(raw_input)
48
- except Exception:
49
- print(json.dumps({"decision": "allow"}))
50
- return
51
-
52
- tool_call = payload.get("toolCall", {})
53
- tool_name = tool_call.get("name", "")
54
- args = tool_call.get("args", {})
55
- conversation_id = payload.get("conversationId", "default_session")
56
- last_user_input = payload.get("lastUserInput", "")
57
- # Working directory of the tool call: lets the Command Sanitizer peek at
58
- # package.json to identify the runner behind opaque `yarn/npm test` scripts
59
- hook_cwd = payload.get("cwd") or os.getcwd()
34
+ def _resolve_hook_path(raw_path: str, hook_cwd: str) -> str:
35
+ if not raw_path:
36
+ return ""
37
+ if os.path.isabs(raw_path):
38
+ return raw_path
39
+ return os.path.abspath(os.path.join(hook_cwd, raw_path))
40
+
41
+
42
+ def _handle(payload: dict) -> dict:
43
+ tool_call = payload.get("toolCall")
44
+ if not isinstance(tool_call, dict):
45
+ tool_call = {}
46
+ tool_name = str(tool_call.get("name") or "")
47
+ args = tool_call.get("args")
48
+ if not isinstance(args, dict):
49
+ args = {}
50
+ conversation_id = str(payload.get("conversationId") or "default_session")
51
+ last_user_input = str(payload.get("lastUserInput") or "")
52
+ # Working directory of the tool call: lets CommandSanitizer peek at
53
+ # package.json and Guard audit git staging in the user's repo (never plugin CWD).
54
+ workspace_paths = payload.get("workspacePaths") if isinstance(payload.get("workspacePaths"), list) else []
55
+ hook_cwd = str(payload.get("cwd") or (workspace_paths[0] if workspace_paths else "") or os.getcwd())
60
56
 
61
57
  tracker = MetricsTracker()
62
58
  quota = LicenseManager.check_quota(tracker)
63
- is_quota_exceeded = quota.get("is_quota_exceeded", False)
59
+ is_quota_exceeded = bool(quota.get("is_quota_exceeded", False))
64
60
 
65
61
  # 1. Loop Detector Guard (Applies to all tools)
66
62
  is_loop, repeat_count, loop_msg = LoopDetector.check_loop(conversation_id, tool_name, args)
@@ -72,18 +68,16 @@ def main():
72
68
  optimized_tokens=100,
73
69
  details={"tool": tool_name, "repeats": repeat_count}
74
70
  )
75
- print(json.dumps({
76
- "decision": "force_ask",
77
- "reason": loop_msg
78
- }))
79
71
  _trigger_bg_sync()
80
- return
72
+ return {"decision": "force_ask", "reason": loop_msg}
81
73
 
82
- response = {"decision": "allow"}
74
+ response: dict = {"decision": "allow"}
83
75
 
84
76
  # 2. TokenSafe Guard: Inspect file writes and edits for security violations
85
77
  if tool_name in ("write_file", "edit_file"):
86
- path = args.get("Path", "")
78
+ from src.guard import TokenSafeGuard
79
+ raw_path = str(args.get("Path") or args.get("TargetFile") or args.get("path") or "")
80
+ path = _resolve_hook_path(raw_path, hook_cwd)
87
81
  code_to_check = args.get("Content", "") if tool_name == "write_file" else args.get("Replacement", "")
88
82
  guard_res = TokenSafeGuard.inspect_file_write(path, code_to_check)
89
83
  if guard_res.blocked:
@@ -98,23 +92,20 @@ def main():
98
92
  "reason": guard_res.reason
99
93
  }
100
94
  )
101
- print(json.dumps({
102
- "decision": "deny",
103
- "reason": f"🛡️ TokenSafe Guard: {guard_res.reason}"
104
- }))
105
95
  _trigger_bg_sync()
106
- return
96
+ return {"decision": "deny", "reason": f"🛡️ TokenSafe Guard: {guard_res.reason}"}
107
97
 
108
98
  # 3. Output Guard: Block write_file on large existing files to enforce edit_file
109
99
  if tool_name == "write_file":
110
- path = args.get("Path", "")
100
+ raw_path = str(args.get("Path") or args.get("path") or "")
101
+ path = _resolve_hook_path(raw_path, hook_cwd)
111
102
  content = args.get("Content", "")
112
103
  is_append = args.get("Append", False)
113
104
 
114
105
  if not is_append and path and os.path.exists(path):
115
106
  try:
116
107
  with open(path, "r", encoding="utf-8", errors="replace") as f:
117
- existing_lines = len(f.readlines())
108
+ existing_lines = sum(1 for _ in f)
118
109
  except Exception:
119
110
  existing_lines = 0
120
111
 
@@ -132,25 +123,30 @@ def main():
132
123
  "saved_output_tokens": max(0, content_tokens - 80)
133
124
  }
134
125
  )
135
-
136
- print(json.dumps({
126
+ _trigger_bg_sync()
127
+ return {
137
128
  "decision": "deny",
138
129
  "reason": (
139
130
  f"Token Optimizer Output Guard: '{os.path.basename(path)}' already exists with {existing_lines} lines. "
140
131
  f"Wholesale rewriting via write_file burns expensive output tokens. "
141
132
  f"Please use 'edit_file' with surgical Target and Replacement blocks instead."
142
133
  )
143
- }))
144
- _trigger_bg_sync()
145
- return
134
+ }
146
135
 
147
136
  # 3. read_file Optimization (AST Windowing & Skeletonization).
148
137
  # 'view_file' is the IDE-surface name for the same tool (hooks.md) —
149
138
  # route it through the same optimization pipeline.
150
139
  elif tool_name in ("read_file", "view_file"):
151
- path = args.get("Path") or args.get("path") or args.get("FilePath") or ""
152
- start_line = args.get("StartLine") or args.get("startLine")
153
- end_line = args.get("EndLine") or args.get("endLine")
140
+ from src.slicer import ToolSlicer
141
+ from src.skeletonizer import Skeletonizer
142
+ raw_path = str(args.get("Path") or args.get("path") or args.get("FilePath") or "")
143
+ path = _resolve_hook_path(raw_path, hook_cwd)
144
+ start_line = args.get("StartLine")
145
+ if start_line is None:
146
+ start_line = args.get("startLine")
147
+ end_line = args.get("EndLine")
148
+ if end_line is None:
149
+ end_line = args.get("endLine")
154
150
  # The overwrite merge is shallow top-level key replacement — we must
155
151
  # rewrite the SAME keys the agent actually sent, or a "path"/"FilePath"
156
152
  # read would get the optimized content under a brand-new "Path" key
@@ -163,26 +159,17 @@ def main():
163
159
  # Free tier quota reached: pass through raw read_file without AST skeletonization
164
160
  if LicenseManager.should_emit_quota_banner(tracker, conversation_id, every_n_turns=5) and quota.get("warning"):
165
161
  response["reason"] = quota["warning"]
166
- print(json.dumps(response))
167
- return
168
-
169
- # Step 3A: Subagent Firewall — Check if file was already read in active session
170
- is_hit, cached_text, saved_dedup = AgentFirewall.check_cache(
171
- session_id=conversation_id,
172
- file_path=path,
173
- tracker=tracker
174
- )
175
- if is_hit and saved_dedup > 0:
176
- # Point to cached skeleton view or let tool proceed with cached metadata
177
- response["reason"] = f"Token Optimizer: Subagent Firewall dedup hit (Saved ~{saved_dedup} tokens)"
162
+ return response
178
163
 
179
- # Step 3B: If model explicitly specified line range, respect it
164
+ # Step 3A: If model explicitly specified line range, respect it
180
165
  if start_line is not None and end_line is not None:
181
- print(json.dumps(response))
182
- return
166
+ return response
183
167
 
184
168
  # Step 3B: If a specific symbol/function is targeted in user prompt, check graph-guided skeleton first
185
- overwrite_args, metrics = ToolSlicer.optimize_read_file(args, context_hint=last_user_input)
169
+ slicer_args = dict(args)
170
+ if path:
171
+ slicer_args[path_key] = path
172
+ overwrite_args, metrics = ToolSlicer.optimize_read_file(slicer_args, context_hint=last_user_input)
186
173
  target_sym = metrics.get("target_symbol")
187
174
  if target_sym and path and os.path.exists(path):
188
175
  skel_path, orig_t, skel_t = Skeletonizer.get_skeleton_file(path, target_symbol=target_sym)
@@ -201,8 +188,7 @@ def main():
201
188
  "saved_tokens": saved
202
189
  }
203
190
  )
204
- print(json.dumps(response))
205
- return
191
+ return response
206
192
 
207
193
  if overwrite_args and metrics.get("saved_tokens", 0) > 0:
208
194
  response["overwrite"] = {
@@ -225,8 +211,7 @@ def main():
225
211
  "lines_sliced": metrics.get("lines_sliced", 0)
226
212
  }
227
213
  )
228
- print(json.dumps(response))
229
- return
214
+ return response
230
215
 
231
216
  # Step 3C: If entire file requested with no symbol target, provide AST Skeleton (mtime-cached)
232
217
  if path and os.path.exists(path):
@@ -249,13 +234,15 @@ def main():
249
234
  "saved_tokens": saved
250
235
  }
251
236
  )
252
- print(json.dumps(response))
253
- return
237
+ return response
254
238
 
255
239
  # 4. run_command Optimization & TokenSafe Guard
256
240
  elif tool_name == "run_command":
257
- cmd = args.get("CommandLine", "")
258
- guard_res = TokenSafeGuard.inspect_command(cmd)
241
+ from src.guard import TokenSafeGuard
242
+ from src.diff_slicer import DiffSlicer
243
+ from src.command_sanitizer import CommandSanitizer
244
+ cmd = str(args.get("CommandLine") or "")
245
+ guard_res = TokenSafeGuard.inspect_command(cmd, cwd=hook_cwd)
259
246
  if guard_res.blocked:
260
247
  tracker.record_event(
261
248
  session_id=conversation_id,
@@ -264,12 +251,8 @@ def main():
264
251
  optimized_tokens=0,
265
252
  details={"cmd": cmd[:100], "reason": guard_res.reason}
266
253
  )
267
- print(json.dumps({
268
- "decision": "deny",
269
- "reason": f"🛡️ TokenSafe Guard: {guard_res.reason}"
270
- }))
271
254
  _trigger_bg_sync()
272
- return
255
+ return {"decision": "deny", "reason": f"🛡️ TokenSafe Guard: {guard_res.reason}"}
273
256
  elif guard_res.warning_only:
274
257
  response["reason"] = f"⚠️ TokenSafe Guard Warning: {guard_res.reason}"
275
258
 
@@ -277,8 +260,7 @@ def main():
277
260
  # Free tier quota reached: skip Pro diff/command optimization while Security Guards remain active
278
261
  if LicenseManager.should_emit_quota_banner(tracker, conversation_id, every_n_turns=5) and quota.get("warning"):
279
262
  response["reason"] = response.get("reason") or quota["warning"]
280
- print(json.dumps(response))
281
- return
263
+ return response
282
264
 
283
265
  # Check AST Diff Slicer first (per-stage rewrite of git diff stages),
284
266
  # then run the Command Sanitizer on the result so other stages
@@ -310,6 +292,26 @@ def main():
310
292
  }
311
293
  )
312
294
 
295
+ return response
296
+
297
+
298
+ def main():
299
+ try:
300
+ raw_input = sys.stdin.read()
301
+ if not raw_input.strip():
302
+ print(json.dumps({"decision": "allow"}))
303
+ return
304
+ payload = json.loads(raw_input)
305
+ if not isinstance(payload, dict):
306
+ print(json.dumps({"decision": "allow"}))
307
+ return
308
+ response = _handle(payload)
309
+ if not isinstance(response, dict):
310
+ response = {"decision": "allow"}
311
+ except Exception:
312
+ # Hooks must always fail open so an internal error never blocks the IDE/agent.
313
+ response = {"decision": "allow"}
314
+
313
315
  print(json.dumps(response))
314
316
 
315
317
  if __name__ == "__main__":
@@ -19,9 +19,10 @@ import sys
19
19
  import os
20
20
  import json
21
21
 
22
- HOOK_DIR = os.path.dirname(os.path.abspath(__file__))
22
+ HOOK_DIR = os.path.dirname(os.path.realpath(__file__))
23
23
  PROJECT_ROOT = os.path.dirname(HOOK_DIR)
24
- sys.path.insert(0, PROJECT_ROOT)
24
+ if PROJECT_ROOT not in sys.path:
25
+ sys.path.insert(0, PROJECT_ROOT)
25
26
 
26
27
  from src.metrics import MetricsTracker
27
28
  from src.license_manager import LicenseManager
@@ -47,14 +48,17 @@ def main():
47
48
  print(json.dumps({}))
48
49
  return
49
50
  payload = json.loads(raw_input)
51
+ if not isinstance(payload, dict):
52
+ payload = {}
50
53
  except Exception:
51
54
  print(json.dumps({}))
52
55
  return
53
56
 
54
57
  # hooks.md: hook CWD is the plugin directory, not the workspace — use the
55
58
  # workspacePaths from the payload for project-scoped audits.
56
- workspace_paths = payload.get("workspacePaths") or []
57
- workspace_root = workspace_paths[0] if workspace_paths else os.getcwd()
59
+ raw_ws = payload.get("workspacePaths")
60
+ workspace_paths = raw_ws if isinstance(raw_ws, list) else []
61
+ workspace_root = str(workspace_paths[0]) if workspace_paths else os.getcwd()
58
62
 
59
63
  inject_steps = [
60
64
  {"systemMessage": {"systemMessage": PROTOCOL_DIRECTIVES, "metadata": {}}}
@@ -18,9 +18,10 @@ import sys
18
18
  import os
19
19
  import json
20
20
 
21
- HOOK_DIR = os.path.dirname(os.path.abspath(__file__))
21
+ HOOK_DIR = os.path.dirname(os.path.realpath(__file__))
22
22
  PROJECT_ROOT = os.path.dirname(HOOK_DIR)
23
- sys.path.insert(0, PROJECT_ROOT)
23
+ if PROJECT_ROOT not in sys.path:
24
+ sys.path.insert(0, PROJECT_ROOT)
24
25
 
25
26
  BUDGET_NUDGE_EVENT = "STOP_BUDGET_NUDGE"
26
27
 
@@ -38,12 +39,14 @@ def main():
38
39
  print(json.dumps({}))
39
40
  return
40
41
  payload = json.loads(raw_input)
42
+ if not isinstance(payload, dict):
43
+ payload = {}
41
44
  except Exception:
42
45
  print(json.dumps({}))
43
46
  return
44
47
 
45
- conversation_id = payload.get("conversationId", "default_session")
46
- termination_reason = payload.get("terminationReason", "")
48
+ conversation_id = str(payload.get("conversationId") or "default_session")
49
+ termination_reason = str(payload.get("terminationReason") or "")
47
50
  fully_idle = bool(payload.get("fullyIdle", False))
48
51
 
49
52
  response = {}