integrity-killswitch 0.3.0__py3-none-any.whl
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.
- agent_killswitch/__init__.py +63 -0
- agent_killswitch/__main__.py +10 -0
- agent_killswitch/ancestry.py +767 -0
- agent_killswitch/cloud.py +477 -0
- agent_killswitch/core.py +1214 -0
- agent_killswitch/hooks.py +748 -0
- agent_killswitch/mcp_server.py +551 -0
- agent_killswitch/network.py +1442 -0
- agent_killswitch/web.py +426 -0
- integrity_killswitch-0.3.0.dist-info/METADATA +356 -0
- integrity_killswitch-0.3.0.dist-info/RECORD +15 -0
- integrity_killswitch-0.3.0.dist-info/WHEEL +5 -0
- integrity_killswitch-0.3.0.dist-info/entry_points.txt +2 -0
- integrity_killswitch-0.3.0.dist-info/licenses/LICENSE +21 -0
- integrity_killswitch-0.3.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,748 @@
|
|
|
1
|
+
"""1-command hook auto-installer and uninstaller for AI coding agents.
|
|
2
|
+
|
|
3
|
+
Supports Claude Code, Codex CLI, Cursor, Gemini CLI, and Antigravity using
|
|
4
|
+
Python 3.10+ stdlib only. Reads UTF-8/UTF-8-BOM JSON cleanly, resolves the
|
|
5
|
+
executable dynamically, embeds `--hook-format <vendor>` (exit 2 + JSON stdout)
|
|
6
|
+
and explicit `--state` when provided or hardened, creates timestamped `.bak`
|
|
7
|
+
backups before modifying existing configuration, preserves unrelated user
|
|
8
|
+
settings and hooks, and is idempotent on re-run.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import copy
|
|
14
|
+
import json
|
|
15
|
+
import os
|
|
16
|
+
import re
|
|
17
|
+
import shutil
|
|
18
|
+
import sys
|
|
19
|
+
import uuid
|
|
20
|
+
from dataclasses import asdict, dataclass
|
|
21
|
+
from datetime import datetime, timezone
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import Any
|
|
24
|
+
|
|
25
|
+
SUPPORTED_TARGETS: tuple[str, ...] = ("claude", "codex", "cursor", "gemini", "antigravity")
|
|
26
|
+
|
|
27
|
+
_KILLSWITCH_CMD_RE = re.compile(
|
|
28
|
+
r"(?:(?:^|[\s\"'/\\])agent-killswitch(?:\.exe)?|(?:-m\s+agent_killswitch))(?:\s|$).*\bcheck\b",
|
|
29
|
+
re.IGNORECASE,
|
|
30
|
+
)
|
|
31
|
+
_SAFE_ACTION_RE = re.compile(r"[a-z0-9][a-z0-9_-]{0,31}")
|
|
32
|
+
|
|
33
|
+
_TARGET_SPECS: dict[str, dict[str, str]] = {
|
|
34
|
+
"claude": {
|
|
35
|
+
"title": "Claude Code",
|
|
36
|
+
"rel_path": ".claude/settings.json",
|
|
37
|
+
"event_key": "PreToolUse",
|
|
38
|
+
"matcher": ".*",
|
|
39
|
+
"mode": "event_group",
|
|
40
|
+
},
|
|
41
|
+
"codex": {
|
|
42
|
+
"title": "Codex CLI",
|
|
43
|
+
"rel_path": ".codex/hooks.json",
|
|
44
|
+
"event_key": "PreToolUse",
|
|
45
|
+
"matcher": ".*",
|
|
46
|
+
"mode": "event_group",
|
|
47
|
+
},
|
|
48
|
+
"gemini": {
|
|
49
|
+
"title": "Gemini CLI",
|
|
50
|
+
"rel_path": ".gemini/settings.json",
|
|
51
|
+
"event_key": "BeforeTool",
|
|
52
|
+
"matcher": ".*",
|
|
53
|
+
"mode": "event_group",
|
|
54
|
+
},
|
|
55
|
+
"antigravity": {
|
|
56
|
+
"title": "Antigravity",
|
|
57
|
+
"rel_path": ".gemini/config/hooks.json",
|
|
58
|
+
"event_key": "PreToolUse",
|
|
59
|
+
"matcher": ".*",
|
|
60
|
+
"mode": "antigravity",
|
|
61
|
+
},
|
|
62
|
+
"cursor": {
|
|
63
|
+
"title": "Cursor",
|
|
64
|
+
"rel_path": ".cursor/hooks.json",
|
|
65
|
+
"matcher": ".*",
|
|
66
|
+
"mode": "cursor",
|
|
67
|
+
},
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass(frozen=True)
|
|
72
|
+
class HookResult:
|
|
73
|
+
"""Structured outcome for installing or uninstalling hooks for one client."""
|
|
74
|
+
|
|
75
|
+
target: str
|
|
76
|
+
title: str
|
|
77
|
+
path: str
|
|
78
|
+
status: str
|
|
79
|
+
changed: bool
|
|
80
|
+
backup: str | None = None
|
|
81
|
+
command: str | None = None
|
|
82
|
+
error: str | None = None
|
|
83
|
+
|
|
84
|
+
def to_dict(self) -> dict[str, Any]:
|
|
85
|
+
return asdict(self)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def resolve_home(home_override: str | Path | None = None) -> Path:
|
|
89
|
+
"""Resolves user home directory, honoring `--home` and `HOME` cross-platform."""
|
|
90
|
+
if home_override is not None and str(home_override).strip():
|
|
91
|
+
return Path(home_override).expanduser().resolve()
|
|
92
|
+
env_home = os.environ.get("HOME", "").strip()
|
|
93
|
+
if env_home:
|
|
94
|
+
return Path(env_home).expanduser().resolve()
|
|
95
|
+
return Path.home().resolve()
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def target_config_path(target: str, home_override: str | Path | None = None) -> Path:
|
|
99
|
+
"""Returns the resolved configuration file path for a given agent target."""
|
|
100
|
+
key = target.lower().strip()
|
|
101
|
+
if key not in _TARGET_SPECS:
|
|
102
|
+
raise ValueError(f"Unsupported hook target {target!r}; expected one of {', '.join(SUPPORTED_TARGETS)}")
|
|
103
|
+
return resolve_home(home_override) / _TARGET_SPECS[key]["rel_path"]
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def default_hardened_state_file() -> Path:
|
|
107
|
+
"""Returns the default OS system-owned hardened state path."""
|
|
108
|
+
if os.name == "nt":
|
|
109
|
+
return Path(r"C:\ProgramData\agent-killswitch\state.json")
|
|
110
|
+
return Path("/etc/agent-killswitch/state.json")
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def resolve_executable() -> str:
|
|
114
|
+
"""Uses `agent-killswitch` only when on PATH; otherwise falls back to `sys.executable -m agent_killswitch`."""
|
|
115
|
+
if shutil.which("agent-killswitch"):
|
|
116
|
+
return "agent-killswitch"
|
|
117
|
+
return f'"{sys.executable}" -m agent_killswitch'
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def build_hook_command(
|
|
121
|
+
vendor: str = "none",
|
|
122
|
+
state_path: str | Path | None = None,
|
|
123
|
+
*,
|
|
124
|
+
state_override: str | Path | None = None,
|
|
125
|
+
action: str | None = None,
|
|
126
|
+
executable: str | None = None,
|
|
127
|
+
) -> str:
|
|
128
|
+
"""Builds the cross-platform shell command invoked by AI client hooks.
|
|
129
|
+
|
|
130
|
+
Always passes `--hook-format <vendor>` for supported vendors so refusals exit
|
|
131
|
+
with code `2` and emit vendor-compatible JSON on stdout. Explicitly embeds
|
|
132
|
+
`--state "<path>"` whenever `state_path` is provided or a system hardened
|
|
133
|
+
state file exists so `AGENT_KILLSWITCH_STATE` cannot bypass enforcement.
|
|
134
|
+
"""
|
|
135
|
+
clean_vendor = vendor.strip().lower() if vendor else "none"
|
|
136
|
+
if clean_vendor != "none" and clean_vendor not in _TARGET_SPECS:
|
|
137
|
+
raise ValueError(f"Unsupported hook vendor {vendor!r}; expected one of {', '.join(SUPPORTED_TARGETS)}")
|
|
138
|
+
|
|
139
|
+
effective_state = state_override if state_override is not None else state_path
|
|
140
|
+
if effective_state is None:
|
|
141
|
+
hardened = default_hardened_state_file()
|
|
142
|
+
if hardened.is_file():
|
|
143
|
+
effective_state = hardened
|
|
144
|
+
|
|
145
|
+
exe = executable if executable is not None else resolve_executable()
|
|
146
|
+
parts = [exe]
|
|
147
|
+
if effective_state is not None and str(effective_state).strip():
|
|
148
|
+
raw_state = str(effective_state).strip()
|
|
149
|
+
if any(ch in raw_state for ch in ("\r", "\n", '"')):
|
|
150
|
+
raise ValueError("State path cannot contain newlines or double quotes")
|
|
151
|
+
parts.extend(["--state", f'"{raw_state}"'])
|
|
152
|
+
|
|
153
|
+
parts.append("check")
|
|
154
|
+
if clean_vendor != "none":
|
|
155
|
+
parts.extend(["--hook-format", clean_vendor])
|
|
156
|
+
if action is not None and action.strip() and action.strip().lower() != "any":
|
|
157
|
+
clean_action = action.strip().lower()
|
|
158
|
+
if not _SAFE_ACTION_RE.fullmatch(clean_action):
|
|
159
|
+
raise ValueError(f"Invalid action scope {action!r}")
|
|
160
|
+
parts.extend(["--action", clean_action])
|
|
161
|
+
return " ".join(parts)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def is_killswitch_command(cmd: Any) -> bool:
|
|
165
|
+
"""Returns True if a hook command string invokes `agent-killswitch ... check`."""
|
|
166
|
+
return isinstance(cmd, str) and bool(_KILLSWITCH_CMD_RE.search(cmd))
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _create_backup(path: Path) -> Path:
|
|
170
|
+
ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
|
171
|
+
candidate = path.with_name(f"{path.name}.{ts}.bak")
|
|
172
|
+
counter = 1
|
|
173
|
+
while candidate.exists():
|
|
174
|
+
candidate = path.with_name(f"{path.name}.{ts}.{counter}.bak")
|
|
175
|
+
counter += 1
|
|
176
|
+
shutil.copy2(path, candidate)
|
|
177
|
+
return candidate
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _atomic_write_json(path: Path, data: dict[str, Any]) -> None:
|
|
181
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
182
|
+
tmp = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")
|
|
183
|
+
tmp.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
|
184
|
+
os.replace(tmp, path)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _load_json_dict(path: Path) -> dict[str, Any]:
|
|
188
|
+
raw = path.read_text(encoding="utf-8-sig")
|
|
189
|
+
if not raw.strip():
|
|
190
|
+
return {}
|
|
191
|
+
parsed = json.loads(raw)
|
|
192
|
+
if not isinstance(parsed, dict):
|
|
193
|
+
raise ValueError("Configuration root must be a JSON object")
|
|
194
|
+
return parsed
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _patch_event_group_install(
|
|
198
|
+
data: dict[str, Any],
|
|
199
|
+
*,
|
|
200
|
+
event_key: str,
|
|
201
|
+
matcher: str,
|
|
202
|
+
command: str,
|
|
203
|
+
) -> tuple[dict[str, Any], str]:
|
|
204
|
+
"""Idempotently installs or updates a `hooks.<event_key>` entry (e.g. PreToolUse / BeforeTool)."""
|
|
205
|
+
updated = copy.deepcopy(data)
|
|
206
|
+
hooks = updated.get("hooks")
|
|
207
|
+
if hooks is None:
|
|
208
|
+
hooks = {}
|
|
209
|
+
updated["hooks"] = hooks
|
|
210
|
+
if not isinstance(hooks, dict):
|
|
211
|
+
raise ValueError("'hooks' field must be a JSON object")
|
|
212
|
+
|
|
213
|
+
entries = hooks.get(event_key)
|
|
214
|
+
if entries is None:
|
|
215
|
+
entries = []
|
|
216
|
+
hooks[event_key] = entries
|
|
217
|
+
if not isinstance(entries, list):
|
|
218
|
+
raise ValueError(f"'hooks.{event_key}' field must be a JSON array")
|
|
219
|
+
|
|
220
|
+
found_any = False
|
|
221
|
+
changed = False
|
|
222
|
+
for group in entries:
|
|
223
|
+
if not isinstance(group, dict):
|
|
224
|
+
continue
|
|
225
|
+
inner = group.get("hooks")
|
|
226
|
+
if not isinstance(inner, list):
|
|
227
|
+
continue
|
|
228
|
+
for item in inner:
|
|
229
|
+
if isinstance(item, dict) and is_killswitch_command(item.get("command")):
|
|
230
|
+
found_any = True
|
|
231
|
+
if item.get("command") != command:
|
|
232
|
+
item["command"] = command
|
|
233
|
+
changed = True
|
|
234
|
+
if len(inner) == 1 and group.get("matcher") != matcher:
|
|
235
|
+
group["matcher"] = matcher
|
|
236
|
+
changed = True
|
|
237
|
+
|
|
238
|
+
if found_any:
|
|
239
|
+
return updated, ("updated" if changed else "unchanged")
|
|
240
|
+
|
|
241
|
+
entries.append(
|
|
242
|
+
{
|
|
243
|
+
"matcher": matcher,
|
|
244
|
+
"hooks": [
|
|
245
|
+
{
|
|
246
|
+
"type": "command",
|
|
247
|
+
"command": command,
|
|
248
|
+
}
|
|
249
|
+
],
|
|
250
|
+
}
|
|
251
|
+
)
|
|
252
|
+
return updated, "installed"
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _patch_event_group_uninstall(
|
|
256
|
+
data: dict[str, Any],
|
|
257
|
+
*,
|
|
258
|
+
event_key: str,
|
|
259
|
+
) -> tuple[dict[str, Any], bool]:
|
|
260
|
+
"""Removes only agent-killswitch entries from `hooks.<event_key>`."""
|
|
261
|
+
updated = copy.deepcopy(data)
|
|
262
|
+
hooks = updated.get("hooks")
|
|
263
|
+
if not isinstance(hooks, dict):
|
|
264
|
+
return updated, False
|
|
265
|
+
|
|
266
|
+
entries = hooks.get(event_key)
|
|
267
|
+
if not isinstance(entries, list):
|
|
268
|
+
return updated, False
|
|
269
|
+
|
|
270
|
+
removed = False
|
|
271
|
+
new_entries: list[Any] = []
|
|
272
|
+
for group in entries:
|
|
273
|
+
if not isinstance(group, dict) or not isinstance(group.get("hooks"), list):
|
|
274
|
+
new_entries.append(group)
|
|
275
|
+
continue
|
|
276
|
+
inner = group["hooks"]
|
|
277
|
+
kept = [
|
|
278
|
+
item
|
|
279
|
+
for item in inner
|
|
280
|
+
if not (isinstance(item, dict) and is_killswitch_command(item.get("command")))
|
|
281
|
+
]
|
|
282
|
+
if len(kept) != len(inner):
|
|
283
|
+
removed = True
|
|
284
|
+
if kept:
|
|
285
|
+
group["hooks"] = kept
|
|
286
|
+
new_entries.append(group)
|
|
287
|
+
else:
|
|
288
|
+
new_entries.append(group)
|
|
289
|
+
|
|
290
|
+
if not removed:
|
|
291
|
+
return updated, False
|
|
292
|
+
|
|
293
|
+
if new_entries:
|
|
294
|
+
hooks[event_key] = new_entries
|
|
295
|
+
else:
|
|
296
|
+
hooks.pop(event_key, None)
|
|
297
|
+
if not hooks:
|
|
298
|
+
updated.pop("hooks", None)
|
|
299
|
+
return updated, True
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _patch_antigravity_install(
|
|
303
|
+
data: dict[str, Any],
|
|
304
|
+
*,
|
|
305
|
+
matcher: str,
|
|
306
|
+
command: str,
|
|
307
|
+
) -> tuple[dict[str, Any], str]:
|
|
308
|
+
"""Idempotently installs top-level `"agent-killswitch": {"PreToolUse": [...]}` in Antigravity hooks.json."""
|
|
309
|
+
updated = copy.deepcopy(data)
|
|
310
|
+
desired_pack = {
|
|
311
|
+
"PreToolUse": [
|
|
312
|
+
{
|
|
313
|
+
"matcher": matcher,
|
|
314
|
+
"hooks": [
|
|
315
|
+
{
|
|
316
|
+
"type": "command",
|
|
317
|
+
"command": command,
|
|
318
|
+
}
|
|
319
|
+
],
|
|
320
|
+
}
|
|
321
|
+
]
|
|
322
|
+
}
|
|
323
|
+
existing = updated.get("agent-killswitch")
|
|
324
|
+
if existing is None:
|
|
325
|
+
updated["agent-killswitch"] = desired_pack
|
|
326
|
+
return updated, "installed"
|
|
327
|
+
if not isinstance(existing, dict):
|
|
328
|
+
raise ValueError("'agent-killswitch' entry in Antigravity hooks.json must be a JSON object")
|
|
329
|
+
if existing == desired_pack:
|
|
330
|
+
return updated, "unchanged"
|
|
331
|
+
# Preserve unrelated events under agent-killswitch if any, updating PreToolUse in place.
|
|
332
|
+
pretool = existing.get("PreToolUse")
|
|
333
|
+
if pretool is None:
|
|
334
|
+
existing["PreToolUse"] = desired_pack["PreToolUse"]
|
|
335
|
+
return updated, "updated"
|
|
336
|
+
if not isinstance(pretool, list):
|
|
337
|
+
raise ValueError("'agent-killswitch.PreToolUse' must be a JSON array")
|
|
338
|
+
|
|
339
|
+
found_any = False
|
|
340
|
+
changed = False
|
|
341
|
+
for group in pretool:
|
|
342
|
+
if not isinstance(group, dict) or not isinstance(group.get("hooks"), list):
|
|
343
|
+
continue
|
|
344
|
+
inner = group["hooks"]
|
|
345
|
+
for item in inner:
|
|
346
|
+
if isinstance(item, dict) and is_killswitch_command(item.get("command")):
|
|
347
|
+
found_any = True
|
|
348
|
+
if item.get("command") != command:
|
|
349
|
+
item["command"] = command
|
|
350
|
+
changed = True
|
|
351
|
+
if len(inner) == 1 and group.get("matcher") != matcher:
|
|
352
|
+
group["matcher"] = matcher
|
|
353
|
+
changed = True
|
|
354
|
+
if not found_any:
|
|
355
|
+
pretool.append(desired_pack["PreToolUse"][0])
|
|
356
|
+
changed = True
|
|
357
|
+
return updated, ("updated" if changed else "unchanged")
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def _patch_antigravity_uninstall(data: dict[str, Any]) -> tuple[dict[str, Any], bool]:
|
|
361
|
+
"""Removes only the `"agent-killswitch"` top-level hook pack from Antigravity hooks.json."""
|
|
362
|
+
updated = copy.deepcopy(data)
|
|
363
|
+
pack = updated.get("agent-killswitch")
|
|
364
|
+
if not isinstance(pack, dict):
|
|
365
|
+
return updated, False
|
|
366
|
+
pretool = pack.get("PreToolUse")
|
|
367
|
+
if not isinstance(pretool, list):
|
|
368
|
+
return updated, False
|
|
369
|
+
|
|
370
|
+
removed = False
|
|
371
|
+
new_pretool: list[Any] = []
|
|
372
|
+
for group in pretool:
|
|
373
|
+
if not isinstance(group, dict) or not isinstance(group.get("hooks"), list):
|
|
374
|
+
new_pretool.append(group)
|
|
375
|
+
continue
|
|
376
|
+
inner = group["hooks"]
|
|
377
|
+
kept = [
|
|
378
|
+
item
|
|
379
|
+
for item in inner
|
|
380
|
+
if not (isinstance(item, dict) and is_killswitch_command(item.get("command")))
|
|
381
|
+
]
|
|
382
|
+
if len(kept) != len(inner):
|
|
383
|
+
removed = True
|
|
384
|
+
if kept:
|
|
385
|
+
group["hooks"] = kept
|
|
386
|
+
new_pretool.append(group)
|
|
387
|
+
else:
|
|
388
|
+
new_pretool.append(group)
|
|
389
|
+
|
|
390
|
+
if not removed:
|
|
391
|
+
return updated, False
|
|
392
|
+
if new_pretool:
|
|
393
|
+
pack["PreToolUse"] = new_pretool
|
|
394
|
+
else:
|
|
395
|
+
pack.pop("PreToolUse", None)
|
|
396
|
+
if not pack:
|
|
397
|
+
updated.pop("agent-killswitch", None)
|
|
398
|
+
return updated, True
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def _upsert_cursor_hook_list(
|
|
402
|
+
hooks: dict[str, Any],
|
|
403
|
+
key: str,
|
|
404
|
+
*,
|
|
405
|
+
command: str,
|
|
406
|
+
matcher: str | None = None,
|
|
407
|
+
) -> tuple[bool, bool]:
|
|
408
|
+
"""Upserts a Cursor hook item with `failClosed: true` into `hooks[key]`.
|
|
409
|
+
|
|
410
|
+
Returns `(found_existing, changed)`.
|
|
411
|
+
"""
|
|
412
|
+
entries = hooks.get(key)
|
|
413
|
+
if entries is None:
|
|
414
|
+
entries = []
|
|
415
|
+
hooks[key] = entries
|
|
416
|
+
if not isinstance(entries, list):
|
|
417
|
+
raise ValueError(f"'hooks.{key}' field must be a JSON array")
|
|
418
|
+
|
|
419
|
+
found = False
|
|
420
|
+
changed = False
|
|
421
|
+
for item in entries:
|
|
422
|
+
if isinstance(item, dict) and is_killswitch_command(item.get("command")):
|
|
423
|
+
found = True
|
|
424
|
+
if item.get("command") != command:
|
|
425
|
+
item["command"] = command
|
|
426
|
+
changed = True
|
|
427
|
+
if item.get("failClosed") is not True:
|
|
428
|
+
item["failClosed"] = True
|
|
429
|
+
changed = True
|
|
430
|
+
if matcher is not None and item.get("matcher") != matcher:
|
|
431
|
+
item["matcher"] = matcher
|
|
432
|
+
changed = True
|
|
433
|
+
if not found:
|
|
434
|
+
new_entry: dict[str, Any] = {"command": command, "failClosed": True}
|
|
435
|
+
if matcher is not None:
|
|
436
|
+
new_entry = {"matcher": matcher, "command": command, "failClosed": True}
|
|
437
|
+
entries.append(new_entry)
|
|
438
|
+
changed = True
|
|
439
|
+
return found, changed
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def _patch_cursor_install(
|
|
443
|
+
data: dict[str, Any],
|
|
444
|
+
*,
|
|
445
|
+
matcher: str,
|
|
446
|
+
command: str,
|
|
447
|
+
) -> tuple[dict[str, Any], str]:
|
|
448
|
+
"""Idempotently installs Cursor camelCase hooks with `failClosed: true`.
|
|
449
|
+
|
|
450
|
+
Configures `hooks.preToolUse`, `hooks.beforeShellExecution`, and
|
|
451
|
+
`hooks.beforeMCPExecution` (and cleans up legacy v0.2 PascalCase `PreToolUse`).
|
|
452
|
+
"""
|
|
453
|
+
updated = copy.deepcopy(data)
|
|
454
|
+
if "version" not in updated:
|
|
455
|
+
updated["version"] = 1
|
|
456
|
+
|
|
457
|
+
hooks = updated.get("hooks")
|
|
458
|
+
if hooks is None:
|
|
459
|
+
hooks = {}
|
|
460
|
+
updated["hooks"] = hooks
|
|
461
|
+
if not isinstance(hooks, dict):
|
|
462
|
+
raise ValueError("'hooks' field must be a JSON object")
|
|
463
|
+
|
|
464
|
+
# Migrate away from legacy v0.2 PascalCase PreToolUse if present
|
|
465
|
+
updated, legacy_removed = _patch_event_group_uninstall(updated, event_key="PreToolUse")
|
|
466
|
+
if "hooks" not in updated:
|
|
467
|
+
updated["hooks"] = {}
|
|
468
|
+
hooks = updated["hooks"]
|
|
469
|
+
|
|
470
|
+
f1, c1 = _upsert_cursor_hook_list(hooks, "preToolUse", command=command, matcher=matcher)
|
|
471
|
+
f2, c2 = _upsert_cursor_hook_list(hooks, "beforeShellExecution", command=command)
|
|
472
|
+
f3, c3 = _upsert_cursor_hook_list(hooks, "beforeMCPExecution", command=command)
|
|
473
|
+
|
|
474
|
+
any_changed = c1 or c2 or c3 or legacy_removed
|
|
475
|
+
if not any_changed:
|
|
476
|
+
return updated, "unchanged"
|
|
477
|
+
if not (f1 and f2 and f3) and not (f1 or f2 or f3):
|
|
478
|
+
return updated, "installed"
|
|
479
|
+
return updated, "updated"
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
def _patch_cursor_uninstall(data: dict[str, Any]) -> tuple[dict[str, Any], bool]:
|
|
483
|
+
"""Removes only agent-killswitch entries from Cursor `hooks.json`."""
|
|
484
|
+
updated = copy.deepcopy(data)
|
|
485
|
+
removed = False
|
|
486
|
+
|
|
487
|
+
hooks = updated.get("hooks")
|
|
488
|
+
if isinstance(hooks, dict):
|
|
489
|
+
for key in ("preToolUse", "beforeShellExecution", "beforeMCPExecution"):
|
|
490
|
+
orig = hooks.get(key)
|
|
491
|
+
if not isinstance(orig, list):
|
|
492
|
+
continue
|
|
493
|
+
kept = [
|
|
494
|
+
item
|
|
495
|
+
for item in orig
|
|
496
|
+
if not (isinstance(item, dict) and is_killswitch_command(item.get("command")))
|
|
497
|
+
]
|
|
498
|
+
if len(kept) != len(orig):
|
|
499
|
+
removed = True
|
|
500
|
+
if kept:
|
|
501
|
+
hooks[key] = kept
|
|
502
|
+
else:
|
|
503
|
+
hooks.pop(key, None)
|
|
504
|
+
|
|
505
|
+
updated, legacy_removed = _patch_event_group_uninstall(updated, event_key="PreToolUse")
|
|
506
|
+
removed = removed or legacy_removed
|
|
507
|
+
if removed and isinstance(updated.get("hooks"), dict) and not updated["hooks"]:
|
|
508
|
+
updated.pop("hooks", None)
|
|
509
|
+
return updated, removed
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
def install_target_hook(
|
|
513
|
+
target: str,
|
|
514
|
+
*,
|
|
515
|
+
home_override: str | Path | None = None,
|
|
516
|
+
state_override: str | Path | None = None,
|
|
517
|
+
action: str | None = None,
|
|
518
|
+
dry_run: bool = False,
|
|
519
|
+
) -> HookResult:
|
|
520
|
+
"""Installs or updates the agent-killswitch hook for a single client target."""
|
|
521
|
+
key = target.lower().strip()
|
|
522
|
+
if key not in _TARGET_SPECS:
|
|
523
|
+
raise ValueError(f"Unsupported hook target {target!r}; expected one of {', '.join(SUPPORTED_TARGETS)}")
|
|
524
|
+
spec = _TARGET_SPECS[key]
|
|
525
|
+
cfg_path = target_config_path(key, home_override)
|
|
526
|
+
command = build_hook_command(vendor=key, state_path=state_override, action=action)
|
|
527
|
+
|
|
528
|
+
existed = cfg_path.exists()
|
|
529
|
+
try:
|
|
530
|
+
current = _load_json_dict(cfg_path) if existed else {}
|
|
531
|
+
mode = spec["mode"]
|
|
532
|
+
if mode == "cursor":
|
|
533
|
+
patched, status = _patch_cursor_install(current, matcher=spec["matcher"], command=command)
|
|
534
|
+
elif mode == "antigravity":
|
|
535
|
+
patched, status = _patch_antigravity_install(current, matcher=spec["matcher"], command=command)
|
|
536
|
+
else:
|
|
537
|
+
patched, status = _patch_event_group_install(
|
|
538
|
+
current,
|
|
539
|
+
event_key=spec["event_key"],
|
|
540
|
+
matcher=spec["matcher"],
|
|
541
|
+
command=command,
|
|
542
|
+
)
|
|
543
|
+
except (OSError, ValueError) as exc:
|
|
544
|
+
return HookResult(
|
|
545
|
+
target=key,
|
|
546
|
+
title=spec["title"],
|
|
547
|
+
path=str(cfg_path),
|
|
548
|
+
status="error",
|
|
549
|
+
changed=False,
|
|
550
|
+
command=command,
|
|
551
|
+
error=str(exc),
|
|
552
|
+
)
|
|
553
|
+
|
|
554
|
+
if status == "unchanged":
|
|
555
|
+
return HookResult(
|
|
556
|
+
target=key,
|
|
557
|
+
title=spec["title"],
|
|
558
|
+
path=str(cfg_path),
|
|
559
|
+
status="unchanged",
|
|
560
|
+
changed=False,
|
|
561
|
+
command=command,
|
|
562
|
+
)
|
|
563
|
+
|
|
564
|
+
if dry_run:
|
|
565
|
+
dry_status = {"installed": "would_install", "updated": "would_update"}.get(status, f"would_{status}")
|
|
566
|
+
return HookResult(
|
|
567
|
+
target=key,
|
|
568
|
+
title=spec["title"],
|
|
569
|
+
path=str(cfg_path),
|
|
570
|
+
status=dry_status,
|
|
571
|
+
changed=True,
|
|
572
|
+
command=command,
|
|
573
|
+
)
|
|
574
|
+
|
|
575
|
+
backup_str: str | None = None
|
|
576
|
+
try:
|
|
577
|
+
if existed:
|
|
578
|
+
backup_str = str(_create_backup(cfg_path))
|
|
579
|
+
_atomic_write_json(cfg_path, patched)
|
|
580
|
+
except OSError as exc:
|
|
581
|
+
return HookResult(
|
|
582
|
+
target=key,
|
|
583
|
+
title=spec["title"],
|
|
584
|
+
path=str(cfg_path),
|
|
585
|
+
status="error",
|
|
586
|
+
changed=False,
|
|
587
|
+
backup=backup_str,
|
|
588
|
+
command=command,
|
|
589
|
+
error=str(exc),
|
|
590
|
+
)
|
|
591
|
+
|
|
592
|
+
return HookResult(
|
|
593
|
+
target=key,
|
|
594
|
+
title=spec["title"],
|
|
595
|
+
path=str(cfg_path),
|
|
596
|
+
status=status,
|
|
597
|
+
changed=True,
|
|
598
|
+
backup=backup_str,
|
|
599
|
+
command=command,
|
|
600
|
+
)
|
|
601
|
+
|
|
602
|
+
|
|
603
|
+
def uninstall_target_hook(
|
|
604
|
+
target: str,
|
|
605
|
+
*,
|
|
606
|
+
home_override: str | Path | None = None,
|
|
607
|
+
dry_run: bool = False,
|
|
608
|
+
) -> HookResult:
|
|
609
|
+
"""Cleanly removes only agent-killswitch hook entries for a single client target."""
|
|
610
|
+
key = target.lower().strip()
|
|
611
|
+
if key not in _TARGET_SPECS:
|
|
612
|
+
raise ValueError(f"Unsupported hook target {target!r}; expected one of {', '.join(SUPPORTED_TARGETS)}")
|
|
613
|
+
spec = _TARGET_SPECS[key]
|
|
614
|
+
cfg_path = target_config_path(key, home_override)
|
|
615
|
+
|
|
616
|
+
if not cfg_path.exists():
|
|
617
|
+
return HookResult(
|
|
618
|
+
target=key,
|
|
619
|
+
title=spec["title"],
|
|
620
|
+
path=str(cfg_path),
|
|
621
|
+
status="missing",
|
|
622
|
+
changed=False,
|
|
623
|
+
)
|
|
624
|
+
|
|
625
|
+
try:
|
|
626
|
+
current = _load_json_dict(cfg_path)
|
|
627
|
+
mode = spec["mode"]
|
|
628
|
+
if mode == "cursor":
|
|
629
|
+
patched, removed = _patch_cursor_uninstall(current)
|
|
630
|
+
elif mode == "antigravity":
|
|
631
|
+
patched, removed = _patch_antigravity_uninstall(current)
|
|
632
|
+
else:
|
|
633
|
+
patched, removed = _patch_event_group_uninstall(current, event_key=spec["event_key"])
|
|
634
|
+
except (OSError, ValueError) as exc:
|
|
635
|
+
return HookResult(
|
|
636
|
+
target=key,
|
|
637
|
+
title=spec["title"],
|
|
638
|
+
path=str(cfg_path),
|
|
639
|
+
status="error",
|
|
640
|
+
changed=False,
|
|
641
|
+
error=str(exc),
|
|
642
|
+
)
|
|
643
|
+
|
|
644
|
+
if not removed:
|
|
645
|
+
return HookResult(
|
|
646
|
+
target=key,
|
|
647
|
+
title=spec["title"],
|
|
648
|
+
path=str(cfg_path),
|
|
649
|
+
status="unchanged",
|
|
650
|
+
changed=False,
|
|
651
|
+
)
|
|
652
|
+
|
|
653
|
+
if dry_run:
|
|
654
|
+
return HookResult(
|
|
655
|
+
target=key,
|
|
656
|
+
title=spec["title"],
|
|
657
|
+
path=str(cfg_path),
|
|
658
|
+
status="would_uninstall",
|
|
659
|
+
changed=True,
|
|
660
|
+
)
|
|
661
|
+
|
|
662
|
+
backup_str: str | None = None
|
|
663
|
+
try:
|
|
664
|
+
backup_str = str(_create_backup(cfg_path))
|
|
665
|
+
_atomic_write_json(cfg_path, patched)
|
|
666
|
+
except OSError as exc:
|
|
667
|
+
return HookResult(
|
|
668
|
+
target=key,
|
|
669
|
+
title=spec["title"],
|
|
670
|
+
path=str(cfg_path),
|
|
671
|
+
status="error",
|
|
672
|
+
changed=False,
|
|
673
|
+
backup=backup_str,
|
|
674
|
+
error=str(exc),
|
|
675
|
+
)
|
|
676
|
+
|
|
677
|
+
return HookResult(
|
|
678
|
+
target=key,
|
|
679
|
+
title=spec["title"],
|
|
680
|
+
path=str(cfg_path),
|
|
681
|
+
status="uninstalled",
|
|
682
|
+
changed=True,
|
|
683
|
+
backup=backup_str,
|
|
684
|
+
)
|
|
685
|
+
|
|
686
|
+
|
|
687
|
+
def select_targets(
|
|
688
|
+
*,
|
|
689
|
+
claude: bool = False,
|
|
690
|
+
codex: bool = False,
|
|
691
|
+
cursor: bool = False,
|
|
692
|
+
gemini: bool = False,
|
|
693
|
+
antigravity: bool = False,
|
|
694
|
+
all_targets: bool = False,
|
|
695
|
+
) -> list[str]:
|
|
696
|
+
"""Resolves selected client targets from CLI flags."""
|
|
697
|
+
if all_targets:
|
|
698
|
+
return list(SUPPORTED_TARGETS)
|
|
699
|
+
selected: list[str] = []
|
|
700
|
+
if claude:
|
|
701
|
+
selected.append("claude")
|
|
702
|
+
if codex:
|
|
703
|
+
selected.append("codex")
|
|
704
|
+
if cursor:
|
|
705
|
+
selected.append("cursor")
|
|
706
|
+
if gemini:
|
|
707
|
+
selected.append("gemini")
|
|
708
|
+
if antigravity:
|
|
709
|
+
selected.append("antigravity")
|
|
710
|
+
return selected
|
|
711
|
+
|
|
712
|
+
|
|
713
|
+
def install_hooks(
|
|
714
|
+
targets: list[str],
|
|
715
|
+
*,
|
|
716
|
+
home_override: str | Path | None = None,
|
|
717
|
+
state_override: str | Path | None = None,
|
|
718
|
+
action: str | None = None,
|
|
719
|
+
dry_run: bool = False,
|
|
720
|
+
) -> list[HookResult]:
|
|
721
|
+
"""Installs hooks across all selected client targets."""
|
|
722
|
+
return [
|
|
723
|
+
install_target_hook(
|
|
724
|
+
target,
|
|
725
|
+
home_override=home_override,
|
|
726
|
+
state_override=state_override,
|
|
727
|
+
action=action,
|
|
728
|
+
dry_run=dry_run,
|
|
729
|
+
)
|
|
730
|
+
for target in targets
|
|
731
|
+
]
|
|
732
|
+
|
|
733
|
+
|
|
734
|
+
def uninstall_hooks(
|
|
735
|
+
targets: list[str],
|
|
736
|
+
*,
|
|
737
|
+
home_override: str | Path | None = None,
|
|
738
|
+
dry_run: bool = False,
|
|
739
|
+
) -> list[HookResult]:
|
|
740
|
+
"""Uninstalls hooks across all selected client targets."""
|
|
741
|
+
return [
|
|
742
|
+
uninstall_target_hook(
|
|
743
|
+
target,
|
|
744
|
+
home_override=home_override,
|
|
745
|
+
dry_run=dry_run,
|
|
746
|
+
)
|
|
747
|
+
for target in targets
|
|
748
|
+
]
|