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
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "4.5.0",
2
+ "version": "4.5.2",
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/bin/agy-tokens CHANGED
@@ -6,11 +6,20 @@ Legacy alias for TokenSafe 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)
13
13
 
14
+ _venv_py = os.path.expanduser(
15
+ "~/.tokensafe/venv/Scripts/python.exe" if sys.platform == "win32" else "~/.tokensafe/venv/bin/python3"
16
+ )
17
+ if os.path.exists(_venv_py) and os.path.realpath(sys.executable) != os.path.realpath(_venv_py):
18
+ try:
19
+ import cryptography # noqa: F401
20
+ except ImportError:
21
+ os.execv(_venv_py, [_venv_py, __file__, *sys.argv[1:]])
22
+
14
23
  from src.cli import main
15
24
 
16
25
  if __name__ == "__main__":
package/bin/tokensafe.js CHANGED
@@ -114,8 +114,9 @@ Usage:
114
114
  tokensafe [command] [options]
115
115
 
116
116
  Commands:
117
- tokensafe create <name> Greenfield project scaffolder (tokensafe-ui + tokensafe-python)
118
117
  tokensafe init Initialize TokenSafe ecosystem in current directory
118
+ tokensafe login Sign in to unlock 500k free monthly tokens
119
+ tokensafe logout Sign out and revert to Guest 50k mode
119
120
  tokensafe stats Show token economy savings & performance metrics
120
121
  tokensafe sync Synchronize local token metrics with Cloud Dashboard
121
122
  tokensafe html Generate and open interactive browser dashboard
@@ -22,13 +22,13 @@ PROJECT_ROOT = os.path.dirname(HOOK_DIR)
22
22
  if PROJECT_ROOT not in sys.path:
23
23
  sys.path.insert(0, PROJECT_ROOT)
24
24
 
25
- from src.adapter_core import TOKENSAFE_DIRECTIVES, compact_for_injection, extract_write_content, guard_command, guard_file_content, guard_write
25
+ from src.adapter_core import TOKENSAFE_DIRECTIVES, compact_for_injection, evaluate_cc_pre_tool_use
26
26
 
27
27
  AGENT = "claude_code"
28
28
 
29
29
 
30
- def handle(event: str, payload: dict) -> dict:
31
- session_id = str(payload.get("session_id") or "") or f"hook_{AGENT}"
30
+ def handle(event: str, payload: dict, agent: str = AGENT) -> dict:
31
+ session_id = str(payload.get("session_id") or "") or f"hook_{agent}"
32
32
 
33
33
  if event == "SessionStart":
34
34
  # One-shot session injection (mirrors the Antigravity SessionStart
@@ -69,10 +69,28 @@ def handle(event: str, payload: dict) -> dict:
69
69
  extra = (
70
70
  f"{extra}\n\n{banner}\n"
71
71
  "⚡ Core God Nodes and dependency hubs mapped above. "
72
- "Call 'tokensafe:get_architecture_graph(project_path)' for full dependency trees."
72
+ "Call 'tokensafe:repo_map(view=\"graph\", project_path=...)' for full dependency trees."
73
73
  )
74
74
  except Exception:
75
75
  pass
76
+ try:
77
+ from src.burn_monitor import get_burn_warnings
78
+ burn_warn = get_burn_warnings(
79
+ agent=agent,
80
+ session_id=session_id,
81
+ transcript_path=str(payload.get("transcript_path") or ""),
82
+ )
83
+ if burn_warn:
84
+ extra = f"{extra}\n\n{burn_warn}"
85
+ except Exception:
86
+ pass
87
+ try:
88
+ from src.adapter_core import format_cumulative_banner
89
+ cum_banner = format_cumulative_banner()
90
+ if cum_banner:
91
+ extra = f"{extra}\n\n{cum_banner}"
92
+ except Exception:
93
+ pass
76
94
  return {
77
95
  "hookSpecificOutput": {
78
96
  "hookEventName": "SessionStart",
@@ -109,7 +127,7 @@ def handle(event: str, payload: dict) -> dict:
109
127
  }
110
128
  return {}
111
129
 
112
- context, meta = compact_for_injection(prompt, AGENT, session_id, transcript_path=str(payload.get("transcript_path") or ""))
130
+ context, meta = compact_for_injection(prompt, agent, session_id, transcript_path=str(payload.get("transcript_path") or ""))
113
131
  if context and meta.get("compacted"):
114
132
  parts.append(
115
133
  f"{context}\n"
@@ -117,12 +135,18 @@ def handle(event: str, payload: dict) -> dict:
117
135
  f"-{meta.get('reduction_pct', 0)}% — original intent preserved.)"
118
136
  )
119
137
 
120
- # History auto-fold (parity with the Antigravity PreInvocation hook):
121
- # Claude Code ships transcript_path in every hook payload. Once the
122
- # transcript holds enough turns, past turns are folded into a State
123
- # Ledger and injected; savings are recorded incrementally to avoid
124
- # double-counting the same history mass on every submit.
125
138
  transcript_path = str(payload.get("transcript_path") or "")
139
+ try:
140
+ from src.burn_monitor import get_burn_warnings
141
+ burn_warn = get_burn_warnings(
142
+ agent=agent,
143
+ session_id=session_id,
144
+ transcript_path=transcript_path,
145
+ )
146
+ if burn_warn:
147
+ parts.append(burn_warn)
148
+ except Exception:
149
+ pass
126
150
  if transcript_path:
127
151
  try:
128
152
  from src.history_compactor import HistoryCompactor
@@ -150,7 +174,7 @@ def handle(event: str, payload: dict) -> dict:
150
174
  event_type="HISTORY_FOLD",
151
175
  original_tokens=inc_orig,
152
176
  optimized_tokens=folded_tok,
153
- details={"turns": turn, "total_accum_orig": orig_hist, "agent": AGENT},
177
+ details={"turns": turn, "total_accum_orig": orig_hist, "agent": agent},
154
178
  )
155
179
  parts.append(
156
180
  f"{folded}\n"
@@ -171,119 +195,7 @@ def handle(event: str, payload: dict) -> dict:
171
195
  return {}
172
196
 
173
197
  if event == "PreToolUse":
174
- tool = str(payload.get("tool_name") or "")
175
- tool_input = payload.get("tool_input")
176
- if not isinstance(tool_input, dict):
177
- tool_input = {}
178
- if tool in ("Bash", "Shell", "bash"):
179
- command = str(tool_input.get("command") or "")
180
- verdict = guard_command(command, AGENT, session_id, cwd=str(payload.get("cwd") or ""), transcript_path=str(payload.get("transcript_path") or ""))
181
- if verdict["decision"] == "deny":
182
- return {
183
- "hookSpecificOutput": {
184
- "hookEventName": "PreToolUse",
185
- "permissionDecision": "deny",
186
- "permissionDecisionReason": verdict["reason"],
187
- }
188
- }
189
- if verdict["decision"] == "ask":
190
- return {
191
- "hookSpecificOutput": {
192
- "hookEventName": "PreToolUse",
193
- "permissionDecision": "ask",
194
- "permissionDecisionReason": verdict["reason"],
195
- }
196
- }
197
- elif tool in ("Write", "write_file", "replace_file_content"):
198
- # Egress economy (v3.0.0): full-file writes over existing files
199
- # burn expensive output tokens — steer to surgical Edit instead.
200
- file_path = str(tool_input.get("file_path") or tool_input.get("Path") or tool_input.get("path") or "")
201
- content = tool_input.get("content") or tool_input.get("Content") or tool_input.get("file_text") or ""
202
- append = bool(tool_input.get("append") or tool_input.get("Append") or False)
203
- # Security first (parity with the Antigravity path): hardcoded
204
- # secrets / TLS bypass / SQLi / CORS never reach disk, before any
205
- # egress-economy steering.
206
- sec_verdict = guard_file_content(file_path, str(content or ""), AGENT, session_id, transcript_path=str(payload.get("transcript_path") or ""))
207
- if sec_verdict["decision"] == "deny":
208
- return {
209
- "hookSpecificOutput": {
210
- "hookEventName": "PreToolUse",
211
- "permissionDecision": "deny",
212
- "permissionDecisionReason": sec_verdict["reason"],
213
- }
214
- }
215
- verdict = guard_write(file_path, str(content or ""), append, AGENT, session_id, transcript_path=str(payload.get("transcript_path") or ""))
216
- if verdict["decision"] == "deny":
217
- return {
218
- "hookSpecificOutput": {
219
- "hookEventName": "PreToolUse",
220
- "permissionDecision": "deny",
221
- "permissionDecisionReason": verdict["reason"],
222
- }
223
- }
224
- if verdict["decision"] == "ask":
225
- return {
226
- "hookSpecificOutput": {
227
- "hookEventName": "PreToolUse",
228
- "permissionDecision": "ask",
229
- "permissionDecisionReason": verdict["reason"],
230
- }
231
- }
232
- elif tool in ("Edit", "MultiEdit", "edit_file", "replace_file_content"):
233
- # Security first (parity with the Antigravity path): deny hardcoded
234
- # secrets / TLS bypass / SQLi / CORS in the replacement text before
235
- # the stale-file check (deny outranks ask).
236
- sec_file = str(tool_input.get("file_path") or tool_input.get("Path") or tool_input.get("path") or "")
237
- sec_verdict = guard_file_content(sec_file, extract_write_content(tool, tool_input), AGENT, session_id, transcript_path=str(payload.get("transcript_path") or ""))
238
- if sec_verdict["decision"] == "deny":
239
- return {
240
- "hookSpecificOutput": {
241
- "hookEventName": "PreToolUse",
242
- "permissionDecision": "deny",
243
- "permissionDecisionReason": sec_verdict["reason"],
244
- }
245
- }
246
- # Stale-file edit guard: when the target changed on disk since the
247
- # model last saw it (build output, linters, another session), the
248
- # edit either corrupts content or fails and forces a costly full
249
- # re-read. Surface it BEFORE the edit lands — ask, never deny.
250
- # Kill switch: TOKENSAFE_STALE_GUARD=0.
251
- try:
252
- from src.file_state import FileState
253
- stale_fp = str(tool_input.get("file_path") or tool_input.get("Path") or tool_input.get("path") or "")
254
- if stale_fp and FileState.guard_enabled():
255
- stale = FileState.check_stale(stale_fp)
256
- if stale:
257
- try:
258
- from src.metrics import MetricsTracker
259
- MetricsTracker().record_event(
260
- session_id=session_id,
261
- event_type="STALE_EDIT_ASK",
262
- original_tokens=FileState.estimate_reread_tokens(stale_fp),
263
- optimized_tokens=0,
264
- details={
265
- "agent": AGENT,
266
- "target_file": os.path.basename(stale_fp),
267
- "age_s": stale.get("age_s", 0),
268
- },
269
- measurement="estimated",
270
- )
271
- except Exception:
272
- pass
273
- return {
274
- "hookSpecificOutput": {
275
- "hookEventName": "PreToolUse",
276
- "permissionDecision": "ask",
277
- "permissionDecisionReason": (
278
- f"[TokenSafe] {os.path.basename(stale_fp)} changed on disk since it was last read "
279
- f"(external edit: build/linter/another session?). Your edit may target outdated content. "
280
- f"Approve if you have verified the current file state."
281
- ),
282
- }
283
- }
284
- except Exception:
285
- pass
286
- return {}
198
+ return evaluate_cc_pre_tool_use(payload, agent=agent)
287
199
 
288
200
  if event == "PostToolUse":
289
201
  # Auto-mute noisy stdout of successful shell commands (tests/linters/builds):
@@ -307,7 +219,7 @@ def handle(event: str, payload: dict) -> dict:
307
219
  event_type="TOOL_OUTPUT_COMPACT",
308
220
  original_tokens=count_tokens(str(payload.get("tool_response") or "")),
309
221
  optimized_tokens=count_tokens(compacted),
310
- details={"agent": AGENT, "tool": tool, "chars": f"{orig}->{new}"},
222
+ details={"agent": agent, "tool": tool, "chars": f"{orig}->{new}"},
311
223
  )
312
224
  except Exception:
313
225
  pass
@@ -353,7 +265,7 @@ def handle(event: str, payload: dict) -> dict:
353
265
  original_tokens=res.get("orig_tokens", 0),
354
266
  optimized_tokens=res.get("pruned_tokens", 0),
355
267
  details={
356
- "agent": AGENT,
268
+ "agent": agent,
357
269
  "pruned": res.get("pruned_count", 0),
358
270
  "transcript": os.path.basename(rest_tp),
359
271
  },
@@ -42,14 +42,34 @@ def _allow(event: str) -> dict:
42
42
 
43
43
  def handle(event: str, payload: dict) -> dict:
44
44
  session_id = str(payload.get("conversation_id") or payload.get("session_id") or "") or f"hook_{AGENT}"
45
+ cwd = str(payload.get("cwd") or "")
46
+
47
+ # Loop guard across Cursor pre-tool hooks
48
+ if event in ("beforeShellExecution", "beforeReadFile", "beforeEditFile"):
49
+ try:
50
+ from src.loop_detector import LoopDetector
51
+ is_loop, _cnt, loop_msg = LoopDetector.check_loop(session_id, event, payload)
52
+ if is_loop:
53
+ if event == "beforeShellExecution":
54
+ return {"permission": "ask", "agent_message": loop_msg}
55
+ return {"permission": "deny", "user_message": loop_msg}
56
+ except Exception:
57
+ pass
45
58
 
46
59
  if event == "beforeShellExecution":
47
60
  command = str(payload.get("command") or "")
48
- verdict = guard_command(command, AGENT, session_id, cwd=str(payload.get("cwd") or ""), transcript_path=str(payload.get("transcript_path") or ""))
61
+ verdict = guard_command(command, AGENT, session_id, cwd=cwd, transcript_path=str(payload.get("transcript_path") or ""))
49
62
  if verdict["decision"] == "deny":
50
63
  return {"permission": "deny", "user_message": verdict["reason"]}
51
64
  if verdict["decision"] == "ask":
52
65
  return {"permission": "ask", "agent_message": verdict["reason"]}
66
+ try:
67
+ from src.mistakes import MistakesLedger
68
+ is_blocked, m_reason = MistakesLedger.should_force_ask(command, action_type="command", project_root=cwd or os.getcwd())
69
+ if is_blocked:
70
+ return {"permission": "ask", "agent_message": f"[TokenSafe Anti-Stuck Guard] {m_reason}"}
71
+ except Exception:
72
+ pass
53
73
  return {"permission": "allow"}
54
74
 
55
75
  if event == "beforeReadFile":
@@ -70,6 +90,13 @@ def handle(event: str, payload: dict) -> dict:
70
90
  verdict = guard_file_content(edit_path, edit_content, AGENT, session_id, transcript_path=str(payload.get("transcript_path") or ""))
71
91
  if verdict["decision"] == "deny":
72
92
  return {"permission": "deny", "user_message": verdict["reason"]}
93
+ try:
94
+ from src.mistakes import MistakesLedger
95
+ is_blocked, m_reason = MistakesLedger.should_force_ask(edit_path, action_type="edit_file", project_root=cwd or os.getcwd())
96
+ if is_blocked:
97
+ return {"permission": "deny", "user_message": f"[TokenSafe Anti-Stuck Guard] {m_reason}"}
98
+ except Exception:
99
+ pass
73
100
  return {"permission": "allow"}
74
101
 
75
102
  if event == "beforeSubmitPrompt":
@@ -77,6 +104,23 @@ def handle(event: str, payload: dict) -> dict:
77
104
  # record: the model still sees the full prompt. Always allow.
78
105
  return {"continue": True}
79
106
 
107
+ if event in ("afterFileEdit", "postToolUse"):
108
+ try:
109
+ fp = str(payload.get("file_path") or payload.get("path") or "")
110
+ if fp:
111
+ from src.file_state import FileState
112
+ FileState.record_seen(fp)
113
+ err_txt = str(payload.get("error") or payload.get("stderr") or "").strip()
114
+ if err_txt and fp:
115
+ from src.mistakes import MistakesLedger
116
+ MistakesLedger.record_failure(summary=err_txt[:140], file_path=fp, source="cursor_hook", project_root=cwd or os.getcwd())
117
+ except Exception:
118
+ pass
119
+ return _allow(event)
120
+
121
+ if event == "stop":
122
+ return {}
123
+
80
124
  return _allow(event)
81
125
 
82
126
 
@@ -24,11 +24,7 @@ if PROJECT_ROOT not in sys.path:
24
24
  from src.adapter_core import (
25
25
  TOKENSAFE_DIRECTIVES,
26
26
  compact_for_injection,
27
- extract_write_content,
28
- guard_command,
29
- guard_file_content,
30
- guard_read,
31
- guard_write,
27
+ evaluate_cc_pre_tool_use,
32
28
  )
33
29
 
34
30
  AGENT = "kimi_code"
@@ -59,6 +55,24 @@ def handle(event: str, payload: dict) -> dict:
59
55
  extra = f"{extra}\n\n{guard}"
60
56
  except Exception:
61
57
  pass
58
+ try:
59
+ from src.burn_monitor import get_burn_warnings
60
+ burn_warn = get_burn_warnings(
61
+ agent=AGENT,
62
+ session_id=session_id,
63
+ transcript_path=str(payload.get("transcript_path") or ""),
64
+ )
65
+ if burn_warn:
66
+ extra = f"{extra}\n\n{burn_warn}"
67
+ except Exception:
68
+ pass
69
+ try:
70
+ from src.adapter_core import format_cumulative_banner
71
+ cum_banner = format_cumulative_banner()
72
+ if cum_banner:
73
+ extra = f"{extra}\n\n{cum_banner}"
74
+ except Exception:
75
+ pass
62
76
  return {
63
77
  "hookSpecificOutput": {
64
78
  "hookEventName": "SessionStart",
@@ -102,6 +116,17 @@ def handle(event: str, payload: dict) -> dict:
102
116
  f"(TokenSafe: compacted ~{meta['saved_tokens']} prompt tokens, "
103
117
  f"-{meta.get('reduction_pct', 0)}% — original intent preserved.)"
104
118
  )
119
+ try:
120
+ from src.burn_monitor import get_burn_warnings
121
+ burn_warn = get_burn_warnings(
122
+ agent=AGENT,
123
+ session_id=session_id,
124
+ transcript_path=str(payload.get("transcript_path") or ""),
125
+ )
126
+ if burn_warn:
127
+ parts.append(burn_warn)
128
+ except Exception:
129
+ pass
105
130
 
106
131
  if parts:
107
132
  return {
@@ -113,91 +138,7 @@ def handle(event: str, payload: dict) -> dict:
113
138
  return {}
114
139
 
115
140
  if event == "PreToolUse":
116
- tool = str(payload.get("tool_name") or "")
117
- tool_input = payload.get("tool_input")
118
- if not isinstance(tool_input, dict):
119
- tool_input = {}
120
-
121
- if tool in ("Bash", "Shell", "bash"):
122
- command = str(tool_input.get("command") or "")
123
- verdict = guard_command(command, AGENT, session_id, cwd=str(payload.get("cwd") or ""), transcript_path=str(payload.get("transcript_path") or ""))
124
- if verdict["decision"] == "deny":
125
- return {
126
- "hookSpecificOutput": {
127
- "hookEventName": "PreToolUse",
128
- "permissionDecision": "deny",
129
- "permissionDecisionReason": verdict["reason"],
130
- }
131
- }
132
- if verdict["decision"] == "ask":
133
- return {
134
- "hookSpecificOutput": {
135
- "hookEventName": "PreToolUse",
136
- "permissionDecision": "ask",
137
- "permissionDecisionReason": verdict["reason"],
138
- }
139
- }
140
-
141
- elif tool in ("Write", "write_file", "replace_file_content"):
142
- file_path = str(tool_input.get("file_path") or tool_input.get("Path") or tool_input.get("path") or "")
143
- content = tool_input.get("content") or tool_input.get("Content") or tool_input.get("file_text") or ""
144
- append = bool(tool_input.get("append") or tool_input.get("Append") or False)
145
- # Security first (parity with the Antigravity path): hardcoded
146
- # secrets / TLS bypass / SQLi / CORS never reach disk.
147
- sec_verdict = guard_file_content(file_path, str(content or ""), AGENT, session_id, transcript_path=str(payload.get("transcript_path") or ""))
148
- if sec_verdict["decision"] == "deny":
149
- return {
150
- "hookSpecificOutput": {
151
- "hookEventName": "PreToolUse",
152
- "permissionDecision": "deny",
153
- "permissionDecisionReason": sec_verdict["reason"],
154
- }
155
- }
156
- verdict = guard_write(file_path, str(content or ""), append, AGENT, session_id, transcript_path=str(payload.get("transcript_path") or ""))
157
- if verdict["decision"] == "deny":
158
- return {
159
- "hookSpecificOutput": {
160
- "hookEventName": "PreToolUse",
161
- "permissionDecision": "deny",
162
- "permissionDecisionReason": verdict["reason"],
163
- }
164
- }
165
- if verdict["decision"] == "ask":
166
- return {
167
- "hookSpecificOutput": {
168
- "hookEventName": "PreToolUse",
169
- "permissionDecision": "ask",
170
- "permissionDecisionReason": verdict["reason"],
171
- }
172
- }
173
-
174
- elif tool in ("Edit", "MultiEdit", "edit_file"):
175
- # Security parity: deny hardcoded secrets / TLS bypass / SQLi /
176
- # CORS in the replacement text before the edit lands.
177
- edit_path = str(tool_input.get("file_path") or tool_input.get("Path") or tool_input.get("path") or "")
178
- sec_verdict = guard_file_content(edit_path, extract_write_content(tool, tool_input), AGENT, session_id, transcript_path=str(payload.get("transcript_path") or ""))
179
- if sec_verdict["decision"] == "deny":
180
- return {
181
- "hookSpecificOutput": {
182
- "hookEventName": "PreToolUse",
183
- "permissionDecision": "deny",
184
- "permissionDecisionReason": sec_verdict["reason"],
185
- }
186
- }
187
-
188
- elif tool in ("Read", "read_file", "view_file"):
189
- file_path = str(tool_input.get("file_path") or tool_input.get("path") or tool_input.get("Path") or "")
190
- verdict = guard_read(file_path, AGENT, session_id, transcript_path=str(payload.get("transcript_path") or ""))
191
- if verdict["decision"] == "deny":
192
- return {
193
- "hookSpecificOutput": {
194
- "hookEventName": "PreToolUse",
195
- "permissionDecision": "deny",
196
- "permissionDecisionReason": verdict["reason"],
197
- }
198
- }
199
-
200
- return {}
141
+ return evaluate_cc_pre_tool_use(payload, agent=AGENT)
201
142
 
202
143
  if event == "PostToolUse":
203
144
  tool = str(payload.get("tool_name") or "")
@@ -229,8 +170,23 @@ def handle(event: str, payload: dict) -> dict:
229
170
  f"({orig:,} → {new:,} chars). Output summary:\n{compacted}"
230
171
  ),
231
172
  }
173
+ try:
174
+ if tool in ("Read", "view_file", "read_file", "Write", "write_file",
175
+ "Edit", "MultiEdit", "edit_file", "replace_file_content"):
176
+ ti = payload.get("tool_input")
177
+ if isinstance(ti, dict):
178
+ track_fp = str(ti.get("file_path") or ti.get("Path") or ti.get("path") or ti.get("FilePath") or "")
179
+ if track_fp:
180
+ from src.file_state import FileState
181
+ FileState.record_seen(track_fp)
182
+ except Exception:
183
+ pass
232
184
  return {}
233
185
 
186
+ if event == "Stop":
187
+ from hooks.claude_code_hook import handle as _cc_handle
188
+ return _cc_handle("Stop", payload, agent=AGENT)
189
+
234
190
  return {}
235
191
 
236
192
 
@@ -26,7 +26,7 @@ from src.history_compactor import HistoryCompactor
26
26
  from src.metrics import MetricsTracker
27
27
  from src.governor import ContextBudget
28
28
  from src.license_manager import LicenseManager
29
- from src.adapter_core import TOKENSAFE_DIRECTIVES as PROTOCOL_DIRECTIVES
29
+ from src.adapter_core import TOKENSAFE_DIRECTIVES as PROTOCOL_DIRECTIVES, resolve_event_model
30
30
  from src.paths import resolve_data_dir
31
31
 
32
32
  def _model_name(payload: dict) -> str:
@@ -119,7 +119,7 @@ def _handle(payload: dict) -> dict:
119
119
  "symbol": compaction["symbol"],
120
120
  "traits": compaction["traits"],
121
121
  "tier": tier,
122
- "model": _model_name(payload) or "gemini-3.8-flash"
122
+ "model": _model_name(payload) or resolve_event_model(transcript_path, conversation_id)
123
123
  }
124
124
  )
125
125
 
@@ -184,7 +184,7 @@ def _handle(payload: dict) -> dict:
184
184
  "total_accum_orig": orig_hist_tokens,
185
185
  "read_files": stats.get("read_files_count", 0),
186
186
  "edited_files": stats.get("edited_files_count", 0),
187
- "model": _model_name(payload) or "gemini-3.8-flash"
187
+ "model": _model_name(payload) or resolve_event_model(transcript_path, conversation_id)
188
188
  }
189
189
  )
190
190
 
@@ -261,7 +261,7 @@ def _handle(payload: dict) -> dict:
261
261
  already = tracker.get_last_event(conversation_id, "BUDGET_WARNING")
262
262
  if not already:
263
263
  if transcript_path:
264
- action = (f"Call tokensafe:compact_conversation(transcript_path='{transcript_path}') "
264
+ action = (f"Call tokensafe:session_context(action='compact', transcript_path='{transcript_path}') "
265
265
  f"now to fold past turns before continuing.")
266
266
  else:
267
267
  action = budget["recommendation"]
@@ -285,6 +285,25 @@ def _handle(payload: dict) -> dict:
285
285
  except Exception:
286
286
  pass
287
287
 
288
+ # 6. Multi-Agent Live Burn Monitor (rate-limited, only fires on real burn spikes)
289
+ if invocation_num >= 2 or transcript_path:
290
+ try:
291
+ from src.burn_monitor import get_burn_warnings
292
+ burn_warn = get_burn_warnings(
293
+ agent="antigravity",
294
+ session_id=conversation_id,
295
+ transcript_path=transcript_path,
296
+ )
297
+ if burn_warn:
298
+ inject_steps.append({
299
+ "systemMessage": {
300
+ "systemMessage": "",
301
+ "metadata": {"user_markdown": burn_warn},
302
+ }
303
+ })
304
+ except Exception:
305
+ pass
306
+
288
307
  return {"injectSteps": inject_steps} if inject_steps else {}
289
308
 
290
309