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
agent_killswitch/core.py
ADDED
|
@@ -0,0 +1,1214 @@
|
|
|
1
|
+
"""State management, audit log, evaluation gate, and CLI for agent-killswitch."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import sys
|
|
10
|
+
import threading
|
|
11
|
+
import time
|
|
12
|
+
import uuid
|
|
13
|
+
from collections.abc import Callable, Iterator
|
|
14
|
+
from contextlib import contextmanager
|
|
15
|
+
from datetime import datetime, timezone
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
if os.name == "nt":
|
|
20
|
+
import msvcrt
|
|
21
|
+
else:
|
|
22
|
+
import fcntl
|
|
23
|
+
|
|
24
|
+
from . import ancestry, cloud, hooks, network
|
|
25
|
+
|
|
26
|
+
SCHEMA = "agent-killswitch/v1"
|
|
27
|
+
EXIT_ALLOWED = 0
|
|
28
|
+
EXIT_HOOK_BLOCK = 2
|
|
29
|
+
EXIT_REFUSED = 3
|
|
30
|
+
HOOK_FORMATS: tuple[str, ...] = ("none", "claude", "cursor", "codex", "gemini", "antigravity")
|
|
31
|
+
LOG_ROTATE_BYTES = 5 * 1024 * 1024
|
|
32
|
+
VENDOR_NAME_RE = re.compile(r"[a-z0-9][a-z0-9_-]{0,31}")
|
|
33
|
+
|
|
34
|
+
DEFAULT_HOME = Path.home() / ".agent-killswitch"
|
|
35
|
+
DEFAULT_STATE_FILE = DEFAULT_HOME / "state.json"
|
|
36
|
+
DEFAULT_LOG_FILE = DEFAULT_HOME / "audit.jsonl"
|
|
37
|
+
|
|
38
|
+
DEFAULT_VENDORS: dict[str, dict[str, Any]] = {
|
|
39
|
+
"claude": {"enabled": True, "title": "Anthropic Claude Code", "reason": "Initial default"},
|
|
40
|
+
"codex": {"enabled": True, "title": "OpenAI Codex CLI", "reason": "Initial default"},
|
|
41
|
+
"cursor": {"enabled": True, "title": "Cursor Agent", "reason": "Initial default"},
|
|
42
|
+
"antigravity": {"enabled": True, "title": "Google Antigravity", "reason": "Initial default"},
|
|
43
|
+
"copilot": {"enabled": True, "title": "GitHub Copilot", "reason": "Initial default"},
|
|
44
|
+
"aider": {"enabled": True, "title": "Aider", "reason": "Initial default"},
|
|
45
|
+
"cline": {"enabled": True, "title": "Cline", "reason": "Initial default"},
|
|
46
|
+
"windsurf": {"enabled": True, "title": "Windsurf", "reason": "Initial default"},
|
|
47
|
+
"grok": {"enabled": True, "title": "xAI Grok", "reason": "Initial default"},
|
|
48
|
+
"gemini": {"enabled": True, "title": "Google Gemini CLI", "reason": "Initial default"},
|
|
49
|
+
"service": {"enabled": True, "title": "Background Services", "reason": "Initial default"},
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
DEFAULT_SCOPES: dict[str, bool] = {
|
|
53
|
+
"secrets": True,
|
|
54
|
+
"ssh": True,
|
|
55
|
+
"deploy": True,
|
|
56
|
+
"git_push": True,
|
|
57
|
+
"db_write": True,
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class KillswitchRefusedError(RuntimeError):
|
|
62
|
+
"""Raised by check_or_refuse() when the killswitch denies an action."""
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def utc_now() -> str:
|
|
66
|
+
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def state_path(custom: str | None = None) -> Path:
|
|
70
|
+
if custom:
|
|
71
|
+
return Path(custom)
|
|
72
|
+
env = os.environ.get("AGENT_KILLSWITCH_STATE")
|
|
73
|
+
return Path(env) if env else DEFAULT_STATE_FILE
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def log_path(custom: str | None = None) -> Path:
|
|
77
|
+
if custom:
|
|
78
|
+
return Path(custom)
|
|
79
|
+
env = os.environ.get("AGENT_KILLSWITCH_LOG")
|
|
80
|
+
return Path(env) if env else DEFAULT_LOG_FILE
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def log_audit_event(action: str, details: dict[str, Any], path: Path | None = None) -> None:
|
|
84
|
+
target_log = path or log_path()
|
|
85
|
+
try:
|
|
86
|
+
target_log.parent.mkdir(parents=True, exist_ok=True)
|
|
87
|
+
try:
|
|
88
|
+
if target_log.exists() and target_log.stat().st_size > LOG_ROTATE_BYTES:
|
|
89
|
+
os.replace(target_log, target_log.with_name(target_log.name + ".1"))
|
|
90
|
+
except OSError:
|
|
91
|
+
return
|
|
92
|
+
entry = {"ts": utc_now(), "action": action, **details}
|
|
93
|
+
with target_log.open("a", encoding="utf-8") as handle:
|
|
94
|
+
handle.write(json.dumps(entry, ensure_ascii=False) + "\n")
|
|
95
|
+
except OSError as exc:
|
|
96
|
+
print(f"agent-killswitch: warning: failed to write audit log: {exc}", file=sys.stderr)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def init_state() -> dict[str, Any]:
|
|
100
|
+
return {
|
|
101
|
+
"schema": SCHEMA,
|
|
102
|
+
"master_panic": False,
|
|
103
|
+
"updated_at": utc_now(),
|
|
104
|
+
"updated_by": "system-init",
|
|
105
|
+
"note": "Initial baseline killswitch configuration",
|
|
106
|
+
"vendors": json.loads(json.dumps(DEFAULT_VENDORS)),
|
|
107
|
+
"scopes": json.loads(json.dumps(DEFAULT_SCOPES)),
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
STATE_LOCK_TIMEOUT = 5.0
|
|
112
|
+
_THREAD_LOCKS_GUARD = threading.Lock()
|
|
113
|
+
_THREAD_LOCKS: dict[str, threading.Lock] = {}
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _thread_lock_for(path: Path) -> threading.Lock:
|
|
117
|
+
key = str(path.resolve())
|
|
118
|
+
with _THREAD_LOCKS_GUARD:
|
|
119
|
+
lock = _THREAD_LOCKS.get(key)
|
|
120
|
+
if lock is None:
|
|
121
|
+
lock = threading.Lock()
|
|
122
|
+
_THREAD_LOCKS[key] = lock
|
|
123
|
+
return lock
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
@contextmanager
|
|
127
|
+
def state_lock(path: Path, timeout: float = STATE_LOCK_TIMEOUT) -> Iterator[None]:
|
|
128
|
+
"""Cross-platform exclusive file lock using a sibling `.lock` file with bounded retry."""
|
|
129
|
+
lock_path = path.with_name(f"{path.name}.lock")
|
|
130
|
+
lock_path.parent.mkdir(parents=True, exist_ok=True)
|
|
131
|
+
deadline = time.monotonic() + max(0.05, float(timeout))
|
|
132
|
+
tlock = _thread_lock_for(lock_path)
|
|
133
|
+
if not tlock.acquire(timeout=max(0.05, float(timeout))):
|
|
134
|
+
raise TimeoutError(f"Timed out waiting for in-process lock on {path}")
|
|
135
|
+
try:
|
|
136
|
+
with lock_path.open("a+b") as handle:
|
|
137
|
+
delay = 0.005
|
|
138
|
+
locked = False
|
|
139
|
+
while True:
|
|
140
|
+
try:
|
|
141
|
+
if os.name == "nt":
|
|
142
|
+
handle.seek(0)
|
|
143
|
+
msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
|
|
144
|
+
else:
|
|
145
|
+
fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
146
|
+
locked = True
|
|
147
|
+
break
|
|
148
|
+
except OSError:
|
|
149
|
+
if time.monotonic() >= deadline:
|
|
150
|
+
raise TimeoutError(f"Timed out waiting for file lock on {path}") from None
|
|
151
|
+
time.sleep(delay)
|
|
152
|
+
delay = min(delay * 1.5, 0.025)
|
|
153
|
+
try:
|
|
154
|
+
yield
|
|
155
|
+
finally:
|
|
156
|
+
if locked:
|
|
157
|
+
try:
|
|
158
|
+
if os.name == "nt":
|
|
159
|
+
handle.seek(0)
|
|
160
|
+
msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
|
|
161
|
+
else:
|
|
162
|
+
fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
|
|
163
|
+
except OSError:
|
|
164
|
+
pass
|
|
165
|
+
finally:
|
|
166
|
+
tlock.release()
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _atomic_replace(tmp: Path, path: Path, *, attempts: int = 12) -> None:
|
|
170
|
+
"""Replaces `path` with `tmp`, retrying transient Windows PermissionError with backoff."""
|
|
171
|
+
for attempt in range(attempts):
|
|
172
|
+
try:
|
|
173
|
+
os.replace(tmp, path)
|
|
174
|
+
return
|
|
175
|
+
except PermissionError:
|
|
176
|
+
if attempt == attempts - 1:
|
|
177
|
+
raise
|
|
178
|
+
time.sleep(min(0.005 * (2**attempt), 0.1))
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _write_json_atomic(path: Path, data: dict[str, Any]) -> None:
|
|
182
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
183
|
+
tmp = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")
|
|
184
|
+
try:
|
|
185
|
+
tmp.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
|
186
|
+
_atomic_replace(tmp, path)
|
|
187
|
+
except BaseException:
|
|
188
|
+
tmp.unlink(missing_ok=True)
|
|
189
|
+
raise
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _read_text_retry(path: Path, attempts: int = 10) -> str:
|
|
193
|
+
for attempt in range(attempts):
|
|
194
|
+
try:
|
|
195
|
+
return path.read_text(encoding="utf-8-sig")
|
|
196
|
+
except OSError:
|
|
197
|
+
if attempt == attempts - 1:
|
|
198
|
+
raise
|
|
199
|
+
time.sleep(min(0.01 * (attempt + 1), 0.05))
|
|
200
|
+
return ""
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _save_state_unlocked(path: Path, state: dict[str, Any], actor: str = "owner") -> None:
|
|
204
|
+
state["updated_at"] = utc_now()
|
|
205
|
+
state["updated_by"] = actor
|
|
206
|
+
_write_json_atomic(path, state)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def save_state(path: Path, state: dict[str, Any], actor: str = "owner") -> None:
|
|
210
|
+
with state_lock(path):
|
|
211
|
+
_save_state_unlocked(path, state, actor=actor)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _load_state_unlocked(path: Path, *, create_if_missing: bool = True) -> dict[str, Any]:
|
|
215
|
+
if not path.exists():
|
|
216
|
+
state = init_state()
|
|
217
|
+
if create_if_missing:
|
|
218
|
+
_save_state_unlocked(path, state, "init")
|
|
219
|
+
return state
|
|
220
|
+
try:
|
|
221
|
+
data = json.loads(_read_text_retry(path))
|
|
222
|
+
if not isinstance(data, dict):
|
|
223
|
+
raise ValueError("state root must be a JSON object")
|
|
224
|
+
data.setdefault("schema", SCHEMA)
|
|
225
|
+
data.setdefault("master_panic", False)
|
|
226
|
+
data.setdefault("vendors", {})
|
|
227
|
+
for vendor, meta in DEFAULT_VENDORS.items():
|
|
228
|
+
data["vendors"].setdefault(vendor, dict(meta))
|
|
229
|
+
data.setdefault("scopes", dict(DEFAULT_SCOPES))
|
|
230
|
+
return data
|
|
231
|
+
except (OSError, ValueError, TypeError) as exc:
|
|
232
|
+
print(f"agent-killswitch: error reading state from {path}: {exc}; failing CLOSED", file=sys.stderr)
|
|
233
|
+
state = init_state()
|
|
234
|
+
state["master_panic"] = True
|
|
235
|
+
state["updated_by"] = "state-error"
|
|
236
|
+
state["note"] = (
|
|
237
|
+
f"State file unreadable ({type(exc).__name__}); failing closed. "
|
|
238
|
+
"Owner: run 'agent-killswitch resume' to rewrite it."
|
|
239
|
+
)
|
|
240
|
+
return state
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def load_state(path: Path, *, create_if_missing: bool = True) -> dict[str, Any]:
|
|
244
|
+
if not path.exists():
|
|
245
|
+
if create_if_missing:
|
|
246
|
+
with state_lock(path):
|
|
247
|
+
return _load_state_unlocked(path, create_if_missing=True)
|
|
248
|
+
return init_state()
|
|
249
|
+
return _load_state_unlocked(path, create_if_missing=False)
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def mutate_state(
|
|
253
|
+
path: Path,
|
|
254
|
+
fn: Callable[[dict[str, Any]], Any],
|
|
255
|
+
*,
|
|
256
|
+
actor: str = "owner",
|
|
257
|
+
timeout: float = STATE_LOCK_TIMEOUT,
|
|
258
|
+
) -> dict[str, Any]:
|
|
259
|
+
"""Atomically performs a locked read-modify-write mutation on `state.json`.
|
|
260
|
+
|
|
261
|
+
If `fn(state)` returns `False` explicitly, the write is skipped.
|
|
262
|
+
"""
|
|
263
|
+
with state_lock(path, timeout=timeout):
|
|
264
|
+
state = _load_state_unlocked(path, create_if_missing=False)
|
|
265
|
+
res = fn(state)
|
|
266
|
+
if res is not False:
|
|
267
|
+
_save_state_unlocked(path, state, actor=actor)
|
|
268
|
+
return state
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def format_hook_refusal(hook_format: str, reason: str) -> str:
|
|
272
|
+
"""Builds exact vendor-compatible blocking JSON payload for stdout."""
|
|
273
|
+
fmt = hook_format.strip().lower()
|
|
274
|
+
if fmt == "antigravity":
|
|
275
|
+
payload: dict[str, Any] = {"decision": "deny", "reason": reason}
|
|
276
|
+
elif fmt == "cursor":
|
|
277
|
+
payload = {"continue": False, "permission": "deny", "userMessage": reason}
|
|
278
|
+
else:
|
|
279
|
+
# claude, codex, gemini
|
|
280
|
+
payload = {"decision": "block", "reason": reason}
|
|
281
|
+
return json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def resolve_effective_vendor(claimed: str | None = None) -> str:
|
|
285
|
+
"""Resolves effective caller vendor without allowing `--vendor` to spoof OS ancestry.
|
|
286
|
+
|
|
287
|
+
Always calls `ancestry.detect_vendor()` first:
|
|
288
|
+
- If OS ancestry detects a concrete LLM/service vendor, `--vendor` can NEVER override it.
|
|
289
|
+
- If OS ancestry is `unknown_llm`, `--vendor` can specify a non-owner vendor (never `owner`).
|
|
290
|
+
- If OS ancestry is `owner`, `--vendor` may be used for owner policy testing.
|
|
291
|
+
"""
|
|
292
|
+
os_detected = ancestry.detect_vendor()
|
|
293
|
+
clean_claimed = claimed.strip().lower() if claimed and claimed.strip() else None
|
|
294
|
+
if os_detected not in ("owner", "unknown_llm"):
|
|
295
|
+
return os_detected
|
|
296
|
+
if clean_claimed and (clean_claimed != "owner" or os_detected == "owner"):
|
|
297
|
+
return clean_claimed
|
|
298
|
+
return os_detected
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def is_allowed(
|
|
302
|
+
vendor: str | None = None,
|
|
303
|
+
action: str = "any",
|
|
304
|
+
target: str = "",
|
|
305
|
+
state_file: Path | None = None,
|
|
306
|
+
*,
|
|
307
|
+
cloud_url: str | None = None,
|
|
308
|
+
license_key: str | None = None,
|
|
309
|
+
cloud_fail_closed: bool = False,
|
|
310
|
+
cloud_fetcher: cloud.CloudFetcher | None = None,
|
|
311
|
+
) -> tuple[bool, str]:
|
|
312
|
+
"""Evaluates whether an action is allowed under local + optional cloud killswitch state."""
|
|
313
|
+
path = state_file or state_path()
|
|
314
|
+
detected = resolve_effective_vendor(vendor)
|
|
315
|
+
|
|
316
|
+
if detected == "owner":
|
|
317
|
+
return True, "owner: interactive human execution unrestricted"
|
|
318
|
+
|
|
319
|
+
# Optional Cloud Control Plane sync (TTL-cached) or previously cached remote policy
|
|
320
|
+
resolved_key = cloud.resolve_license_key(license_key)
|
|
321
|
+
resolved_url = cloud.resolve_cloud_url(cloud_url, default_if_empty=bool(resolved_key))
|
|
322
|
+
cloud_state: dict[str, Any] | None = None
|
|
323
|
+
if resolved_url and resolved_key:
|
|
324
|
+
sync_kwargs: dict[str, Any] = {
|
|
325
|
+
"state_file": path,
|
|
326
|
+
"cloud_url": resolved_url,
|
|
327
|
+
"license_key": resolved_key,
|
|
328
|
+
}
|
|
329
|
+
if cloud_fetcher is not None:
|
|
330
|
+
sync_kwargs["fetcher"] = cloud_fetcher
|
|
331
|
+
sync_res = cloud.sync_cloud_state(**sync_kwargs)
|
|
332
|
+
if not sync_res["ok"] and cloud_fail_closed:
|
|
333
|
+
reason = f"CLOUD UNREACHABLE (fail-closed): {sync_res.get('error') or 'sync failed'}"
|
|
334
|
+
log_audit_event("block", {"vendor": detected, "action": action, "target": target, "reason": reason})
|
|
335
|
+
return False, reason
|
|
336
|
+
cloud_state = sync_res.get("state")
|
|
337
|
+
elif cloud_fail_closed and (resolved_url or cloud_url):
|
|
338
|
+
reason = "CLOUD UNREACHABLE (fail-closed): missing INTEGRITY_LICENSE_KEY / --license-key"
|
|
339
|
+
log_audit_event("block", {"vendor": detected, "action": action, "target": target, "reason": reason})
|
|
340
|
+
return False, reason
|
|
341
|
+
else:
|
|
342
|
+
try:
|
|
343
|
+
cached = cloud.load_cloud_cache(path, raise_on_corrupt=cloud_fail_closed)
|
|
344
|
+
except cloud.CorruptCloudCacheError as exc:
|
|
345
|
+
reason = f"CLOUD CACHE CORRUPT (fail-closed): {exc}"
|
|
346
|
+
log_audit_event("block", {"vendor": detected, "action": action, "target": target, "reason": reason})
|
|
347
|
+
return False, reason
|
|
348
|
+
if cached:
|
|
349
|
+
cloud_state = cached.get("state")
|
|
350
|
+
|
|
351
|
+
state = load_state(path)
|
|
352
|
+
|
|
353
|
+
if state.get("master_panic", False):
|
|
354
|
+
reason = f"MASTER PANIC ACTIVE: all AI agent access is blocked ({state.get('note', '')})"
|
|
355
|
+
log_audit_event("block", {"vendor": detected, "action": action, "target": target, "reason": reason})
|
|
356
|
+
return False, reason
|
|
357
|
+
|
|
358
|
+
if detected == "unknown_llm":
|
|
359
|
+
reason = "UNKNOWN_LLM: caller has an unrecognized or orphaned process ancestry"
|
|
360
|
+
log_audit_event(
|
|
361
|
+
"block",
|
|
362
|
+
{
|
|
363
|
+
"vendor": detected,
|
|
364
|
+
"action": action,
|
|
365
|
+
"target": target,
|
|
366
|
+
"reason": reason,
|
|
367
|
+
"ancestors": ancestry.get_process_ancestor_names(),
|
|
368
|
+
},
|
|
369
|
+
)
|
|
370
|
+
return False, reason
|
|
371
|
+
|
|
372
|
+
cloud_ok, cloud_reason = cloud.evaluate_cloud_state(
|
|
373
|
+
detected_vendor=detected,
|
|
374
|
+
action=action,
|
|
375
|
+
cloud_state=cloud_state,
|
|
376
|
+
)
|
|
377
|
+
if not cloud_ok and cloud_reason:
|
|
378
|
+
log_audit_event("block", {"vendor": detected, "action": action, "target": target, "reason": cloud_reason})
|
|
379
|
+
return False, cloud_reason
|
|
380
|
+
|
|
381
|
+
vendors = state.get("vendors", {})
|
|
382
|
+
vendor_info = vendors.get(detected)
|
|
383
|
+
if not vendor_info or not vendor_info.get("enabled", True):
|
|
384
|
+
v_reason = vendor_info.get("reason", "Vendor switch turned off") if vendor_info else "Vendor not registered"
|
|
385
|
+
reason = f"KILLSWITCH OFF: access for vendor '{detected}' is disabled ({v_reason})"
|
|
386
|
+
log_audit_event("block", {"vendor": detected, "action": action, "target": target, "reason": reason})
|
|
387
|
+
return False, reason
|
|
388
|
+
|
|
389
|
+
scopes = state.get("scopes", {})
|
|
390
|
+
if action in scopes and not scopes[action]:
|
|
391
|
+
reason = f"SCOPE DISABLED: scope '{action}' is currently disabled for all agents"
|
|
392
|
+
log_audit_event("block", {"vendor": detected, "action": action, "target": target, "reason": reason})
|
|
393
|
+
return False, reason
|
|
394
|
+
|
|
395
|
+
return True, f"allowed for {detected}"
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def check_or_refuse(
|
|
399
|
+
action: str = "any",
|
|
400
|
+
target: str = "",
|
|
401
|
+
state_file: Path | None = None,
|
|
402
|
+
) -> None:
|
|
403
|
+
"""Raises KillswitchRefusedError when the caller is blocked."""
|
|
404
|
+
allowed, reason = is_allowed(action=action, target=target, state_file=state_file)
|
|
405
|
+
if not allowed:
|
|
406
|
+
raise KillswitchRefusedError(reason)
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
# --------------------------------------------------------------------------- CLI commands
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def admin_actor(action: str, owner_only: bool) -> str | None:
|
|
413
|
+
actor = ancestry.detect_vendor()
|
|
414
|
+
if owner_only and actor != "owner":
|
|
415
|
+
log_audit_event(
|
|
416
|
+
"admin_denied",
|
|
417
|
+
{
|
|
418
|
+
"actor": actor,
|
|
419
|
+
"admin_action": action,
|
|
420
|
+
"ancestors": ancestry.get_process_ancestor_names(),
|
|
421
|
+
},
|
|
422
|
+
)
|
|
423
|
+
print(
|
|
424
|
+
f"agent-killswitch: REFUSED: '{action}' restores access and is owner-only "
|
|
425
|
+
f"(caller detected as {actor}). Use an interactive owner shell or the web dashboard.",
|
|
426
|
+
file=sys.stderr,
|
|
427
|
+
)
|
|
428
|
+
return None
|
|
429
|
+
return actor
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def cmd_status(args: argparse.Namespace) -> int:
|
|
433
|
+
path = state_path(args.state)
|
|
434
|
+
state = load_state(path, create_if_missing=False)
|
|
435
|
+
detected = ancestry.detect_vendor()
|
|
436
|
+
master = bool(state.get("master_panic", False))
|
|
437
|
+
|
|
438
|
+
if getattr(args, "json", False):
|
|
439
|
+
print(
|
|
440
|
+
json.dumps(
|
|
441
|
+
{
|
|
442
|
+
"caller": detected,
|
|
443
|
+
"ancestors": ancestry.get_process_ancestor_names(),
|
|
444
|
+
"state_file": str(path),
|
|
445
|
+
"state": state,
|
|
446
|
+
},
|
|
447
|
+
indent=2,
|
|
448
|
+
)
|
|
449
|
+
)
|
|
450
|
+
return 0
|
|
451
|
+
|
|
452
|
+
label = "[MASTER PANIC: ALL AGENTS BLOCKED]" if master else "[NORMAL: PER-VENDOR POLICY]"
|
|
453
|
+
print("=" * 68)
|
|
454
|
+
print(" agent-killswitch — Local AI Coding Agent Killswitch")
|
|
455
|
+
print(f" Status: {label}")
|
|
456
|
+
print(f" State: {path}")
|
|
457
|
+
print(f" Updated: {state.get('updated_at')} by {state.get('updated_by')}")
|
|
458
|
+
if state.get("note"):
|
|
459
|
+
print(f" Note: {state.get('note')}")
|
|
460
|
+
print("=" * 68)
|
|
461
|
+
print(f" Caller detected as: [{detected.upper()}]")
|
|
462
|
+
print(f" Process chain: {' <- '.join(ancestry.get_process_ancestor_names()) or 'n/a'}")
|
|
463
|
+
print("-" * 68)
|
|
464
|
+
print(f" {'VENDOR':<14} {'TITLE':<24} {'STATE':<15} {'REASON'}")
|
|
465
|
+
print("-" * 68)
|
|
466
|
+
for vendor, info in state.get("vendors", {}).items():
|
|
467
|
+
raw_enabled = bool(info.get("enabled", True))
|
|
468
|
+
if master and raw_enabled:
|
|
469
|
+
state_str = "BLOCKED(PANIC)"
|
|
470
|
+
elif raw_enabled:
|
|
471
|
+
state_str = "ENABLED"
|
|
472
|
+
else:
|
|
473
|
+
state_str = "DISABLED"
|
|
474
|
+
print(f" {vendor:<14} {info.get('title', vendor):<24} {state_str:<15} {info.get('reason', '')}")
|
|
475
|
+
print("-" * 68)
|
|
476
|
+
print(" Scopes:")
|
|
477
|
+
for scope, sc_enabled in state.get("scopes", {}).items():
|
|
478
|
+
sc_str = "ACTIVE" if sc_enabled and not master else "DISABLED"
|
|
479
|
+
print(f" - {scope:<14}: {sc_str}")
|
|
480
|
+
print("=" * 68)
|
|
481
|
+
return 0
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
def cmd_set_vendor(args: argparse.Namespace, enabled: bool) -> int:
|
|
485
|
+
vendor = args.vendor.lower().strip()
|
|
486
|
+
if not VENDOR_NAME_RE.fullmatch(vendor):
|
|
487
|
+
print(f"agent-killswitch: invalid vendor name {vendor!r}", file=sys.stderr)
|
|
488
|
+
return 2
|
|
489
|
+
actor = admin_actor(("on " if enabled else "off ") + vendor, owner_only=enabled)
|
|
490
|
+
if actor is None:
|
|
491
|
+
return EXIT_REFUSED
|
|
492
|
+
|
|
493
|
+
path = state_path(args.state)
|
|
494
|
+
reason = args.reason or f"Turned {'ON' if enabled else 'OFF'} by {actor}"
|
|
495
|
+
|
|
496
|
+
def _apply_vendor(state: dict[str, Any]) -> None:
|
|
497
|
+
if vendor not in state.get("vendors", {}):
|
|
498
|
+
state.setdefault("vendors", {})[vendor] = {
|
|
499
|
+
"title": vendor.capitalize(),
|
|
500
|
+
"enabled": enabled,
|
|
501
|
+
"reason": reason,
|
|
502
|
+
"updated_at": utc_now(),
|
|
503
|
+
}
|
|
504
|
+
else:
|
|
505
|
+
state["vendors"][vendor]["enabled"] = enabled
|
|
506
|
+
state["vendors"][vendor]["reason"] = reason
|
|
507
|
+
state["vendors"][vendor]["updated_at"] = utc_now()
|
|
508
|
+
|
|
509
|
+
mutate_state(path, _apply_vendor, actor=f"{actor}-cli")
|
|
510
|
+
log_audit_event(
|
|
511
|
+
"vendor_enable" if enabled else "vendor_disable",
|
|
512
|
+
{"vendor": vendor, "reason": reason, "actor": actor},
|
|
513
|
+
)
|
|
514
|
+
status_str = "ENABLED (ON)" if enabled else "DISABLED (OFF - KILLSWITCH ACTIVE)"
|
|
515
|
+
print(f"agent-killswitch: vendor '{vendor}' is now {status_str}")
|
|
516
|
+
return 0
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
def cmd_set_scope(args: argparse.Namespace, enabled: bool) -> int:
|
|
520
|
+
scope = args.scope.lower().strip()
|
|
521
|
+
if not VENDOR_NAME_RE.fullmatch(scope):
|
|
522
|
+
print(f"agent-killswitch: invalid scope name {scope!r}", file=sys.stderr)
|
|
523
|
+
return 2
|
|
524
|
+
actor = admin_actor(("scope-on " if enabled else "scope-off ") + scope, owner_only=enabled)
|
|
525
|
+
if actor is None:
|
|
526
|
+
return EXIT_REFUSED
|
|
527
|
+
|
|
528
|
+
path = state_path(args.state)
|
|
529
|
+
|
|
530
|
+
def _apply_scope(state: dict[str, Any]) -> None:
|
|
531
|
+
state.setdefault("scopes", {})[scope] = enabled
|
|
532
|
+
|
|
533
|
+
mutate_state(path, _apply_scope, actor=f"{actor}-cli")
|
|
534
|
+
log_audit_event("scope_toggle", {"scope": scope, "enabled": enabled, "actor": actor})
|
|
535
|
+
print(f"agent-killswitch: scope '{scope}' is now {'ACTIVE' if enabled else 'DISABLED'}")
|
|
536
|
+
return 0
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
def _effective_state(args: argparse.Namespace) -> str | None:
|
|
540
|
+
return getattr(args, "sub_state", None) or getattr(args, "state", None)
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
def cmd_panic(args: argparse.Namespace) -> int:
|
|
544
|
+
path = state_path(_effective_state(args))
|
|
545
|
+
actor = ancestry.detect_vendor()
|
|
546
|
+
dry_run = bool(getattr(args, "dry_run", False))
|
|
547
|
+
want_network = bool(getattr(args, "network", False))
|
|
548
|
+
want_freeze = bool(getattr(args, "freeze", False))
|
|
549
|
+
note = args.reason or f"EMERGENCY PANIC TRIGGERED BY {actor.upper()}"
|
|
550
|
+
|
|
551
|
+
if not dry_run:
|
|
552
|
+
def _apply_panic(state: dict[str, Any]) -> None:
|
|
553
|
+
state["master_panic"] = True
|
|
554
|
+
state["note"] = note
|
|
555
|
+
|
|
556
|
+
mutate_state(path, _apply_panic, actor=f"{actor}-panic")
|
|
557
|
+
log_audit_event(
|
|
558
|
+
"panic_triggered",
|
|
559
|
+
{"reason": note, "actor": actor, "network": want_network, "freeze": want_freeze},
|
|
560
|
+
)
|
|
561
|
+
print("!" * 68)
|
|
562
|
+
print(" MASTER KILLSWITCH ACTIVATED: ALL AI AGENT ACCESS IS CUT OFF")
|
|
563
|
+
print(f" Reason: {note}")
|
|
564
|
+
print("!" * 68)
|
|
565
|
+
else:
|
|
566
|
+
print(f"[DRY-RUN] Would activate Master Panic in {path} (reason: {note})")
|
|
567
|
+
|
|
568
|
+
rc = 0
|
|
569
|
+
if want_network:
|
|
570
|
+
try:
|
|
571
|
+
plan = network.net_cut(
|
|
572
|
+
endpoints_file=getattr(args, "endpoints_file", None),
|
|
573
|
+
allow_hosts=getattr(args, "allow_host", None),
|
|
574
|
+
block_binaries=getattr(args, "block_binaries", None),
|
|
575
|
+
dry_run=dry_run,
|
|
576
|
+
)
|
|
577
|
+
except (OSError, ValueError) as exc:
|
|
578
|
+
print(f"agent-killswitch: net-cut error: {exc}", file=sys.stderr)
|
|
579
|
+
return 2
|
|
580
|
+
_print_network_plan(plan, as_json=False)
|
|
581
|
+
if not plan.ok:
|
|
582
|
+
rc = 1
|
|
583
|
+
elif not dry_run:
|
|
584
|
+
log_audit_event("net_cut", {"actor": actor, "backend": plan.backend, "via": "panic"})
|
|
585
|
+
|
|
586
|
+
if want_freeze:
|
|
587
|
+
try:
|
|
588
|
+
res = network.freeze_or_thaw_agents(
|
|
589
|
+
thaw=False,
|
|
590
|
+
vendor_filter=getattr(args, "vendor", None),
|
|
591
|
+
dry_run=dry_run,
|
|
592
|
+
)
|
|
593
|
+
except ValueError as exc:
|
|
594
|
+
print(f"agent-killswitch: freeze error: {exc}", file=sys.stderr)
|
|
595
|
+
return 2
|
|
596
|
+
_print_freeze_result(res, as_json=False)
|
|
597
|
+
if not res.get("ok", True):
|
|
598
|
+
rc = 1
|
|
599
|
+
elif not dry_run:
|
|
600
|
+
log_audit_event("freeze", {"actor": actor, "count": len(res.get("affected", [])), "via": "panic"})
|
|
601
|
+
|
|
602
|
+
return rc
|
|
603
|
+
|
|
604
|
+
|
|
605
|
+
def cmd_resume(args: argparse.Namespace) -> int:
|
|
606
|
+
if admin_actor("resume", owner_only=True) is None:
|
|
607
|
+
return EXIT_REFUSED
|
|
608
|
+
path = state_path(_effective_state(args))
|
|
609
|
+
dry_run = bool(getattr(args, "dry_run", False))
|
|
610
|
+
want_network = bool(getattr(args, "network", False))
|
|
611
|
+
want_thaw = bool(getattr(args, "thaw", False))
|
|
612
|
+
note = args.reason or "Normal operations resumed by owner"
|
|
613
|
+
|
|
614
|
+
if not dry_run:
|
|
615
|
+
def _apply_resume(state: dict[str, Any]) -> None:
|
|
616
|
+
state["master_panic"] = False
|
|
617
|
+
state["note"] = note
|
|
618
|
+
|
|
619
|
+
mutate_state(path, _apply_resume, actor="owner-resume")
|
|
620
|
+
log_audit_event("panic_cleared", {"reason": note, "network": want_network, "thaw": want_thaw})
|
|
621
|
+
print("=" * 68)
|
|
622
|
+
print(" Master Panic CLEARED. Returned to per-vendor policy.")
|
|
623
|
+
print("=" * 68)
|
|
624
|
+
else:
|
|
625
|
+
print(f"[DRY-RUN] Would clear Master Panic in {path} (reason: {note})")
|
|
626
|
+
|
|
627
|
+
rc = 0
|
|
628
|
+
if want_network:
|
|
629
|
+
plan = network.net_restore(dry_run=dry_run)
|
|
630
|
+
_print_network_plan(plan, as_json=False)
|
|
631
|
+
if not plan.ok:
|
|
632
|
+
rc = 1
|
|
633
|
+
elif not dry_run:
|
|
634
|
+
log_audit_event("net_restore", {"actor": "owner", "backend": plan.backend, "via": "resume"})
|
|
635
|
+
|
|
636
|
+
if want_thaw:
|
|
637
|
+
try:
|
|
638
|
+
res = network.freeze_or_thaw_agents(
|
|
639
|
+
thaw=True,
|
|
640
|
+
vendor_filter=getattr(args, "vendor", None),
|
|
641
|
+
dry_run=dry_run,
|
|
642
|
+
)
|
|
643
|
+
except ValueError as exc:
|
|
644
|
+
print(f"agent-killswitch: thaw error: {exc}", file=sys.stderr)
|
|
645
|
+
return 2
|
|
646
|
+
_print_freeze_result(res, as_json=False)
|
|
647
|
+
if not res.get("ok", True):
|
|
648
|
+
rc = 1
|
|
649
|
+
elif not dry_run:
|
|
650
|
+
log_audit_event("thaw", {"actor": "owner", "count": len(res.get("affected", [])), "via": "resume"})
|
|
651
|
+
|
|
652
|
+
return rc
|
|
653
|
+
|
|
654
|
+
|
|
655
|
+
def _print_hook_results(
|
|
656
|
+
action: str,
|
|
657
|
+
results: list[hooks.HookResult],
|
|
658
|
+
*,
|
|
659
|
+
dry_run: bool,
|
|
660
|
+
as_json: bool,
|
|
661
|
+
home: Path,
|
|
662
|
+
) -> int:
|
|
663
|
+
had_error = any(r.status == "error" for r in results)
|
|
664
|
+
if as_json:
|
|
665
|
+
print(
|
|
666
|
+
json.dumps(
|
|
667
|
+
{
|
|
668
|
+
"action": action,
|
|
669
|
+
"dry_run": dry_run,
|
|
670
|
+
"home": str(home),
|
|
671
|
+
"ok": not had_error,
|
|
672
|
+
"results": [r.to_dict() for r in results],
|
|
673
|
+
},
|
|
674
|
+
indent=2,
|
|
675
|
+
)
|
|
676
|
+
)
|
|
677
|
+
return 1 if had_error else 0
|
|
678
|
+
|
|
679
|
+
prefix = "[DRY-RUN] " if dry_run else ""
|
|
680
|
+
for item in results:
|
|
681
|
+
suffix = f" (backup: {item.backup})" if item.backup else ""
|
|
682
|
+
if item.error:
|
|
683
|
+
print(f"{prefix}{item.target:<12} ERROR: {item.path} — {item.error}", file=sys.stderr)
|
|
684
|
+
else:
|
|
685
|
+
print(f"{prefix}{item.target:<12} {item.status:<16} {item.path}{suffix}")
|
|
686
|
+
return 1 if had_error else 0
|
|
687
|
+
|
|
688
|
+
|
|
689
|
+
def cmd_install_hooks(args: argparse.Namespace) -> int:
|
|
690
|
+
if getattr(args, "uninstall", False):
|
|
691
|
+
return cmd_uninstall_hooks(args)
|
|
692
|
+
targets = hooks.select_targets(
|
|
693
|
+
claude=bool(args.claude),
|
|
694
|
+
codex=bool(args.codex),
|
|
695
|
+
cursor=bool(args.cursor),
|
|
696
|
+
gemini=bool(getattr(args, "gemini", False)),
|
|
697
|
+
antigravity=bool(args.antigravity),
|
|
698
|
+
all_targets=bool(args.all),
|
|
699
|
+
)
|
|
700
|
+
if not targets:
|
|
701
|
+
print(
|
|
702
|
+
"agent-killswitch: specify at least one target "
|
|
703
|
+
"(--claude, --codex, --cursor, --gemini, --antigravity) or --all",
|
|
704
|
+
file=sys.stderr,
|
|
705
|
+
)
|
|
706
|
+
return 2
|
|
707
|
+
home = hooks.resolve_home(args.home)
|
|
708
|
+
try:
|
|
709
|
+
results = hooks.install_hooks(
|
|
710
|
+
targets,
|
|
711
|
+
home_override=home,
|
|
712
|
+
state_override=_effective_state(args),
|
|
713
|
+
action=getattr(args, "action", None),
|
|
714
|
+
dry_run=bool(args.dry_run),
|
|
715
|
+
)
|
|
716
|
+
except ValueError as exc:
|
|
717
|
+
print(f"agent-killswitch: {exc}", file=sys.stderr)
|
|
718
|
+
return 2
|
|
719
|
+
|
|
720
|
+
if not args.dry_run and any(r.changed for r in results):
|
|
721
|
+
log_audit_event(
|
|
722
|
+
"hooks_install",
|
|
723
|
+
{
|
|
724
|
+
"actor": ancestry.detect_vendor(),
|
|
725
|
+
"targets": [r.target for r in results if r.changed],
|
|
726
|
+
"home": str(home),
|
|
727
|
+
},
|
|
728
|
+
)
|
|
729
|
+
return _print_hook_results("install-hooks", results, dry_run=bool(args.dry_run), as_json=bool(args.json), home=home)
|
|
730
|
+
|
|
731
|
+
|
|
732
|
+
def cmd_uninstall_hooks(args: argparse.Namespace) -> int:
|
|
733
|
+
if admin_actor("uninstall-hooks", owner_only=True) is None:
|
|
734
|
+
return EXIT_REFUSED
|
|
735
|
+
targets = hooks.select_targets(
|
|
736
|
+
claude=bool(args.claude),
|
|
737
|
+
codex=bool(args.codex),
|
|
738
|
+
cursor=bool(args.cursor),
|
|
739
|
+
gemini=bool(getattr(args, "gemini", False)),
|
|
740
|
+
antigravity=bool(args.antigravity),
|
|
741
|
+
all_targets=bool(args.all),
|
|
742
|
+
)
|
|
743
|
+
if not targets:
|
|
744
|
+
print(
|
|
745
|
+
"agent-killswitch: specify at least one target "
|
|
746
|
+
"(--claude, --codex, --cursor, --gemini, --antigravity) or --all",
|
|
747
|
+
file=sys.stderr,
|
|
748
|
+
)
|
|
749
|
+
return 2
|
|
750
|
+
home = hooks.resolve_home(args.home)
|
|
751
|
+
results = hooks.uninstall_hooks(targets, home_override=home, dry_run=bool(args.dry_run))
|
|
752
|
+
if not args.dry_run and any(r.changed for r in results):
|
|
753
|
+
log_audit_event(
|
|
754
|
+
"hooks_uninstall",
|
|
755
|
+
{
|
|
756
|
+
"actor": "owner",
|
|
757
|
+
"targets": [r.target for r in results if r.changed],
|
|
758
|
+
"home": str(home),
|
|
759
|
+
},
|
|
760
|
+
)
|
|
761
|
+
return _print_hook_results(
|
|
762
|
+
"uninstall-hooks",
|
|
763
|
+
results,
|
|
764
|
+
dry_run=bool(args.dry_run),
|
|
765
|
+
as_json=bool(args.json),
|
|
766
|
+
home=home,
|
|
767
|
+
)
|
|
768
|
+
|
|
769
|
+
|
|
770
|
+
def _print_network_plan(plan: network.NetworkPlan, *, as_json: bool) -> None:
|
|
771
|
+
if as_json:
|
|
772
|
+
print(json.dumps(plan.to_dict(), indent=2))
|
|
773
|
+
return
|
|
774
|
+
prefix = "[DRY-RUN] " if plan.dry_run and plan.action != "net-status" else ""
|
|
775
|
+
if plan.action == "net-status":
|
|
776
|
+
status_str = "ACTIVE (LLM API CUTOFF ENGAGED)" if plan.active else "INACTIVE"
|
|
777
|
+
print(f"agent-killswitch net-status [{plan.platform}/{plan.backend}]: {status_str}")
|
|
778
|
+
if plan.active_rules:
|
|
779
|
+
print(f" Active rules ({len(plan.active_rules)}): {', '.join(plan.active_rules[:8])}")
|
|
780
|
+
return
|
|
781
|
+
if not plan.ok:
|
|
782
|
+
print(f"agent-killswitch {plan.action}: ERROR: {plan.error}", file=sys.stderr)
|
|
783
|
+
return
|
|
784
|
+
print(f"{prefix}agent-killswitch {plan.action} [{plan.platform}/{plan.backend}]: OK")
|
|
785
|
+
if plan.action == "net-cut":
|
|
786
|
+
print(
|
|
787
|
+
f" Blocked IPs: {len(plan.blocked_ipv4)} IPv4, {len(plan.blocked_ipv6)} IPv6 "
|
|
788
|
+
f"across {len(plan.blocked_hosts)} host(s)"
|
|
789
|
+
)
|
|
790
|
+
print(f" Anti-lockout preserved: loopback, SSH:22, DNS:53, {', '.join(plan.allowed_hosts)}")
|
|
791
|
+
if plan.unresolved_hosts:
|
|
792
|
+
print(f" Unresolved hosts: {', '.join(plan.unresolved_hosts)}")
|
|
793
|
+
for warning in plan.warnings:
|
|
794
|
+
print(f" Warning: {warning}")
|
|
795
|
+
if plan.dry_run:
|
|
796
|
+
if plan.ruleset:
|
|
797
|
+
print("--- Planned Ruleset ---")
|
|
798
|
+
print(plan.ruleset.rstrip())
|
|
799
|
+
if plan.commands:
|
|
800
|
+
print("--- Planned Commands ---")
|
|
801
|
+
for cmd in plan.commands:
|
|
802
|
+
print(f" {' '.join(cmd)}")
|
|
803
|
+
|
|
804
|
+
|
|
805
|
+
def cmd_net_cut(args: argparse.Namespace) -> int:
|
|
806
|
+
try:
|
|
807
|
+
plan = network.net_cut(
|
|
808
|
+
endpoints_file=args.endpoints_file,
|
|
809
|
+
allow_hosts=args.allow_host,
|
|
810
|
+
block_binaries=args.block_binaries,
|
|
811
|
+
dry_run=bool(args.dry_run),
|
|
812
|
+
)
|
|
813
|
+
except (OSError, ValueError) as exc:
|
|
814
|
+
print(f"agent-killswitch: net-cut invalid input: {exc}", file=sys.stderr)
|
|
815
|
+
return 2
|
|
816
|
+
_print_network_plan(plan, as_json=bool(args.json))
|
|
817
|
+
if not plan.ok:
|
|
818
|
+
return 1
|
|
819
|
+
if not args.dry_run:
|
|
820
|
+
log_audit_event(
|
|
821
|
+
"net_cut",
|
|
822
|
+
{
|
|
823
|
+
"actor": ancestry.detect_vendor(),
|
|
824
|
+
"platform": plan.platform,
|
|
825
|
+
"backend": plan.backend,
|
|
826
|
+
"blocked_ipv4": len(plan.blocked_ipv4),
|
|
827
|
+
"blocked_ipv6": len(plan.blocked_ipv6),
|
|
828
|
+
},
|
|
829
|
+
)
|
|
830
|
+
return 0
|
|
831
|
+
|
|
832
|
+
|
|
833
|
+
def cmd_net_restore(args: argparse.Namespace) -> int:
|
|
834
|
+
if admin_actor("net-restore", owner_only=True) is None:
|
|
835
|
+
return EXIT_REFUSED
|
|
836
|
+
plan = network.net_restore(dry_run=bool(args.dry_run))
|
|
837
|
+
_print_network_plan(plan, as_json=bool(args.json))
|
|
838
|
+
if not plan.ok:
|
|
839
|
+
return 1
|
|
840
|
+
if not args.dry_run:
|
|
841
|
+
log_audit_event("net_restore", {"actor": "owner", "platform": plan.platform, "backend": plan.backend})
|
|
842
|
+
return 0
|
|
843
|
+
|
|
844
|
+
|
|
845
|
+
def cmd_net_status(args: argparse.Namespace) -> int:
|
|
846
|
+
plan = network.net_status()
|
|
847
|
+
_print_network_plan(plan, as_json=bool(args.json))
|
|
848
|
+
return 0
|
|
849
|
+
|
|
850
|
+
|
|
851
|
+
def _print_freeze_result(res: dict[str, Any], *, as_json: bool) -> None:
|
|
852
|
+
if as_json:
|
|
853
|
+
print(json.dumps(res, indent=2))
|
|
854
|
+
return
|
|
855
|
+
prefix = "[DRY-RUN] " if res.get("dry_run") else ""
|
|
856
|
+
action = res["action"]
|
|
857
|
+
matched = res.get("matched", [])
|
|
858
|
+
if not res.get("supported", True):
|
|
859
|
+
print(f"{prefix}agent-killswitch {action} [{res['platform']}]: {len(matched)} agent process(es) matched")
|
|
860
|
+
print(f" Note: {res.get('note', '')}")
|
|
861
|
+
for cmd in res.get("safe_plan_commands", []):
|
|
862
|
+
print(f" {cmd}")
|
|
863
|
+
return
|
|
864
|
+
affected = res.get("affected", [])
|
|
865
|
+
failed = res.get("failed", [])
|
|
866
|
+
print(
|
|
867
|
+
f"{prefix}agent-killswitch {action} [{res['platform']}/{res['signal']}]: "
|
|
868
|
+
f"{len(affected)} process(es) handled, {len(failed)} failed"
|
|
869
|
+
)
|
|
870
|
+
for item in affected:
|
|
871
|
+
print(f" PID {item['pid']:<7} [{item['vendor']}] {item['name']} ({item['status']})")
|
|
872
|
+
for item in failed:
|
|
873
|
+
print(f" PID {item['pid']:<7} [{item['vendor']}] FAILED: {item['error']}", file=sys.stderr)
|
|
874
|
+
|
|
875
|
+
|
|
876
|
+
def cmd_freeze(args: argparse.Namespace) -> int:
|
|
877
|
+
try:
|
|
878
|
+
res = network.freeze_or_thaw_agents(
|
|
879
|
+
thaw=False,
|
|
880
|
+
vendor_filter=args.vendor,
|
|
881
|
+
dry_run=bool(args.dry_run),
|
|
882
|
+
)
|
|
883
|
+
except ValueError as exc:
|
|
884
|
+
print(f"agent-killswitch: freeze invalid input: {exc}", file=sys.stderr)
|
|
885
|
+
return 2
|
|
886
|
+
_print_freeze_result(res, as_json=bool(args.json))
|
|
887
|
+
if not args.dry_run and res.get("supported"):
|
|
888
|
+
log_audit_event(
|
|
889
|
+
"freeze",
|
|
890
|
+
{
|
|
891
|
+
"actor": ancestry.detect_vendor(),
|
|
892
|
+
"vendor_filter": args.vendor,
|
|
893
|
+
"count": len(res.get("affected", [])),
|
|
894
|
+
},
|
|
895
|
+
)
|
|
896
|
+
return 0 if res.get("ok", True) else 1
|
|
897
|
+
|
|
898
|
+
|
|
899
|
+
def cmd_thaw(args: argparse.Namespace) -> int:
|
|
900
|
+
if admin_actor("thaw", owner_only=True) is None:
|
|
901
|
+
return EXIT_REFUSED
|
|
902
|
+
try:
|
|
903
|
+
res = network.freeze_or_thaw_agents(
|
|
904
|
+
thaw=True,
|
|
905
|
+
vendor_filter=args.vendor,
|
|
906
|
+
dry_run=bool(args.dry_run),
|
|
907
|
+
)
|
|
908
|
+
except ValueError as exc:
|
|
909
|
+
print(f"agent-killswitch: thaw invalid input: {exc}", file=sys.stderr)
|
|
910
|
+
return 2
|
|
911
|
+
_print_freeze_result(res, as_json=bool(args.json))
|
|
912
|
+
if not args.dry_run and res.get("supported"):
|
|
913
|
+
log_audit_event(
|
|
914
|
+
"thaw",
|
|
915
|
+
{
|
|
916
|
+
"actor": "owner",
|
|
917
|
+
"vendor_filter": args.vendor,
|
|
918
|
+
"count": len(res.get("affected", [])),
|
|
919
|
+
},
|
|
920
|
+
)
|
|
921
|
+
return 0 if res.get("ok", True) else 1
|
|
922
|
+
|
|
923
|
+
|
|
924
|
+
def cmd_harden(args: argparse.Namespace) -> int:
|
|
925
|
+
explicit = _effective_state(args)
|
|
926
|
+
target_path = Path(explicit) if explicit else Path(network.default_hardened_state_path())
|
|
927
|
+
res = network.harden_state(target_path, dry_run=bool(args.dry_run))
|
|
928
|
+
if args.json:
|
|
929
|
+
print(json.dumps(res, indent=2))
|
|
930
|
+
elif not res["ok"]:
|
|
931
|
+
print(f"agent-killswitch harden: ERROR: {res['error']}", file=sys.stderr)
|
|
932
|
+
else:
|
|
933
|
+
prefix = "[DRY-RUN] " if args.dry_run else ""
|
|
934
|
+
print(f"{prefix}agent-killswitch harden [{res['platform']}]: {res['state_file']}")
|
|
935
|
+
for warning in res.get("warnings", []):
|
|
936
|
+
print(f" Warning: {warning}")
|
|
937
|
+
for cmd in res["commands"]:
|
|
938
|
+
print(f" {' '.join(cmd)}")
|
|
939
|
+
if args.dry_run and res.get("rollback_commands"):
|
|
940
|
+
print("--- Rollback Commands ---")
|
|
941
|
+
for cmd in res["rollback_commands"]:
|
|
942
|
+
print(f" {' '.join(cmd)}")
|
|
943
|
+
if not res["ok"]:
|
|
944
|
+
return 1
|
|
945
|
+
if not args.dry_run:
|
|
946
|
+
log_audit_event("harden", {"actor": ancestry.detect_vendor(), "state_file": str(target_path)})
|
|
947
|
+
return 0
|
|
948
|
+
|
|
949
|
+
|
|
950
|
+
def cmd_cloud_sync(args: argparse.Namespace) -> int:
|
|
951
|
+
path = state_path(_effective_state(args))
|
|
952
|
+
try:
|
|
953
|
+
res = cloud.sync_cloud_state(
|
|
954
|
+
state_file=path,
|
|
955
|
+
cloud_url=getattr(args, "cloud_url", None),
|
|
956
|
+
license_key=getattr(args, "license_key", None),
|
|
957
|
+
force=True,
|
|
958
|
+
)
|
|
959
|
+
except ValueError as exc:
|
|
960
|
+
print(f"agent-killswitch cloud-sync: ERROR: {exc}", file=sys.stderr)
|
|
961
|
+
return 2
|
|
962
|
+
|
|
963
|
+
if getattr(args, "json", False):
|
|
964
|
+
print(json.dumps(res, indent=2))
|
|
965
|
+
elif not res["configured"]:
|
|
966
|
+
print(f"agent-killswitch cloud-sync: ERROR: {res['error']}", file=sys.stderr)
|
|
967
|
+
elif not res["ok"]:
|
|
968
|
+
cached_note = " (falling back to cached remote state)" if res.get("from_cache") else ""
|
|
969
|
+
print(
|
|
970
|
+
f"agent-killswitch cloud-sync: OFFLINE/ERROR: {res['error']}{cached_note}",
|
|
971
|
+
file=sys.stderr,
|
|
972
|
+
)
|
|
973
|
+
else:
|
|
974
|
+
st = res.get("state") or {}
|
|
975
|
+
panic_label = "ACTIVE (LATCHED LOCALLY)" if st.get("master_panic") else "CLEAR"
|
|
976
|
+
print(f"agent-killswitch cloud-sync: OK ({res['cloud_url']})")
|
|
977
|
+
print(f" Master Panic: {panic_label}")
|
|
978
|
+
print(f" Disabled Vendors: {', '.join(st.get('disabled_vendors') or []) or 'none'}")
|
|
979
|
+
print(f" Disabled Scopes: {', '.join(st.get('disabled_scopes') or []) or 'none'}")
|
|
980
|
+
|
|
981
|
+
if not res["configured"]:
|
|
982
|
+
return 2
|
|
983
|
+
if not res["ok"]:
|
|
984
|
+
return 1
|
|
985
|
+
return 0
|
|
986
|
+
|
|
987
|
+
|
|
988
|
+
def cmd_check(args: argparse.Namespace) -> int:
|
|
989
|
+
claimed = args.vendor if args.vendor and args.vendor.strip().lower() != "owner" else None
|
|
990
|
+
hook_format = str(getattr(args, "hook_format", "none") or "none").strip().lower()
|
|
991
|
+
cloud_url = getattr(args, "cloud_url", None)
|
|
992
|
+
license_key = getattr(args, "license_key", None)
|
|
993
|
+
cloud_fail_closed = bool(getattr(args, "cloud_fail_closed", False))
|
|
994
|
+
try:
|
|
995
|
+
allowed, reason = is_allowed(
|
|
996
|
+
vendor=claimed,
|
|
997
|
+
action=args.action or "any",
|
|
998
|
+
target=args.target or "",
|
|
999
|
+
state_file=state_path(args.state),
|
|
1000
|
+
cloud_url=cloud_url,
|
|
1001
|
+
license_key=license_key,
|
|
1002
|
+
cloud_fail_closed=cloud_fail_closed,
|
|
1003
|
+
)
|
|
1004
|
+
for extra in args.also_state or []:
|
|
1005
|
+
if allowed and Path(extra).is_file():
|
|
1006
|
+
allowed, reason = is_allowed(
|
|
1007
|
+
vendor=claimed,
|
|
1008
|
+
action=args.action or "any",
|
|
1009
|
+
target=args.target or "",
|
|
1010
|
+
state_file=Path(extra),
|
|
1011
|
+
)
|
|
1012
|
+
except (OSError, ValueError, RuntimeError) as exc:
|
|
1013
|
+
allowed, reason = False, f"KILLSWITCH ERROR: {type(exc).__name__}: {exc}"
|
|
1014
|
+
log_audit_event(
|
|
1015
|
+
"check_error",
|
|
1016
|
+
{"action": args.action or "any", "target": args.target or "", "reason": reason},
|
|
1017
|
+
)
|
|
1018
|
+
|
|
1019
|
+
if args.match_blocked:
|
|
1020
|
+
if not allowed:
|
|
1021
|
+
print(f"KILLSWITCH BLOCKED: {reason}", file=sys.stderr)
|
|
1022
|
+
return 0
|
|
1023
|
+
return 1
|
|
1024
|
+
|
|
1025
|
+
if allowed:
|
|
1026
|
+
if args.verbose:
|
|
1027
|
+
print(f"ALLOWED: {reason}")
|
|
1028
|
+
return EXIT_ALLOWED
|
|
1029
|
+
|
|
1030
|
+
if hook_format != "none":
|
|
1031
|
+
print(format_hook_refusal(hook_format, reason))
|
|
1032
|
+
print(f"REFUSED BY KILLSWITCH: {reason}", file=sys.stderr)
|
|
1033
|
+
return EXIT_HOOK_BLOCK
|
|
1034
|
+
|
|
1035
|
+
print(f"REFUSED BY KILLSWITCH: {reason}", file=sys.stderr)
|
|
1036
|
+
return EXIT_REFUSED
|
|
1037
|
+
|
|
1038
|
+
|
|
1039
|
+
def cmd_serve(args: argparse.Namespace) -> int:
|
|
1040
|
+
from .web import serve_dashboard
|
|
1041
|
+
|
|
1042
|
+
return serve_dashboard(host=args.host, port=args.port, state_override=args.state)
|
|
1043
|
+
|
|
1044
|
+
|
|
1045
|
+
def cmd_mcp_serve(args: argparse.Namespace) -> int:
|
|
1046
|
+
from .mcp_server import serve_stdio
|
|
1047
|
+
|
|
1048
|
+
return serve_stdio(state_override=_effective_state(args))
|
|
1049
|
+
|
|
1050
|
+
|
|
1051
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
1052
|
+
parser = argparse.ArgumentParser(
|
|
1053
|
+
prog="agent-killswitch",
|
|
1054
|
+
description="OS process-tree killswitch for autonomous AI coding agents.",
|
|
1055
|
+
)
|
|
1056
|
+
parser.add_argument("--state", help="Override state JSON path (default: ~/.agent-killswitch/state.json)")
|
|
1057
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
1058
|
+
|
|
1059
|
+
p_status = sub.add_parser("status", help="Show current killswitch state and detected caller")
|
|
1060
|
+
p_status.add_argument("--json", action="store_true", help="Emit machine-readable JSON")
|
|
1061
|
+
p_status.set_defaults(func=cmd_status)
|
|
1062
|
+
|
|
1063
|
+
p_on = sub.add_parser("on", help="Enable access for a vendor (owner-only)")
|
|
1064
|
+
p_on.add_argument("vendor", help="Vendor ID (e.g. claude, codex, cursor, antigravity)")
|
|
1065
|
+
p_on.add_argument("--reason", help="Audit log reason")
|
|
1066
|
+
p_on.set_defaults(func=lambda a: cmd_set_vendor(a, True))
|
|
1067
|
+
|
|
1068
|
+
p_off = sub.add_parser("off", help="Disable access for a vendor immediately")
|
|
1069
|
+
p_off.add_argument("vendor", help="Vendor ID")
|
|
1070
|
+
p_off.add_argument("--reason", help="Audit log reason")
|
|
1071
|
+
p_off.set_defaults(func=lambda a: cmd_set_vendor(a, False))
|
|
1072
|
+
|
|
1073
|
+
p_s_on = sub.add_parser("scope-on", help="Enable an action scope (owner-only)")
|
|
1074
|
+
p_s_on.add_argument("scope", help="Scope name (e.g. secrets, ssh, deploy, git_push)")
|
|
1075
|
+
p_s_on.set_defaults(func=lambda a: cmd_set_scope(a, True))
|
|
1076
|
+
|
|
1077
|
+
p_s_off = sub.add_parser("scope-off", help="Disable an action scope for all agents")
|
|
1078
|
+
p_s_off.add_argument("scope", help="Scope name")
|
|
1079
|
+
p_s_off.set_defaults(func=lambda a: cmd_set_scope(a, False))
|
|
1080
|
+
|
|
1081
|
+
p_panic = sub.add_parser("panic", help="MASTER RED BUTTON: block all AI agents immediately")
|
|
1082
|
+
p_panic.add_argument("--reason", help="Audit log reason")
|
|
1083
|
+
p_panic.add_argument("--network", action="store_true", help="Also apply OS-level LLM API network cutoff")
|
|
1084
|
+
p_panic.add_argument("--freeze", action="store_true", help="Also freeze running AI agent processes (SIGSTOP)")
|
|
1085
|
+
p_panic.add_argument("--endpoints-file", help="Optional custom endpoints file for --network")
|
|
1086
|
+
p_panic.add_argument("--allow-host", action="append", help="Extra host to keep allowed with --network")
|
|
1087
|
+
p_panic.add_argument("--block-binaries", action="append", help="Windows executable path(s) to block with --network")
|
|
1088
|
+
p_panic.add_argument("--vendor", help="Optional vendor filter when using --freeze")
|
|
1089
|
+
p_panic.add_argument("--dry-run", action="store_true", help="Preview panic/network/freeze actions without mutating")
|
|
1090
|
+
p_panic.set_defaults(func=cmd_panic)
|
|
1091
|
+
|
|
1092
|
+
p_resume = sub.add_parser("resume", help="Clear master panic (owner-only)")
|
|
1093
|
+
p_resume.add_argument("--reason", help="Audit log reason")
|
|
1094
|
+
p_resume.add_argument("--network", action="store_true", help="Also remove OS-level LLM API network cutoff")
|
|
1095
|
+
p_resume.add_argument("--thaw", action="store_true", help="Also resume frozen AI agent processes (SIGCONT)")
|
|
1096
|
+
p_resume.add_argument("--vendor", help="Optional vendor filter when using --thaw")
|
|
1097
|
+
p_resume.add_argument("--dry-run", action="store_true", help="Preview resume/restore/thaw actions without mutating")
|
|
1098
|
+
p_resume.set_defaults(func=cmd_resume)
|
|
1099
|
+
|
|
1100
|
+
p_check = sub.add_parser("check", help="Gate check for hooks/scripts (exit 0 allowed, 3 refused; 2 in hook mode)")
|
|
1101
|
+
p_check.add_argument("--vendor", help="Vendor hint when ancestry is unknown/owner (never overrides detected LLM)")
|
|
1102
|
+
p_check.add_argument("--action", default="any", help="Action scope to check (e.g. ssh, deploy)")
|
|
1103
|
+
p_check.add_argument("--target", default="", help="Optional target label for audit log")
|
|
1104
|
+
p_check.add_argument("--also-state", action="append", help="Additional state file(s) to enforce")
|
|
1105
|
+
p_check.add_argument(
|
|
1106
|
+
"--hook-format",
|
|
1107
|
+
choices=HOOK_FORMATS,
|
|
1108
|
+
default="none",
|
|
1109
|
+
help="Emit vendor-compatible blocking JSON on stdout and exit 2 on refusal",
|
|
1110
|
+
)
|
|
1111
|
+
p_check.add_argument("--cloud-url", help="Optional Integrity Cloud Control Plane URL (or INTEGRITY_CLOUD_URL)")
|
|
1112
|
+
p_check.add_argument("--license-key", help="Optional Integrity license/agent key (or INTEGRITY_LICENSE_KEY)")
|
|
1113
|
+
p_check.add_argument(
|
|
1114
|
+
"--cloud-fail-closed",
|
|
1115
|
+
action="store_true",
|
|
1116
|
+
help="Refuse actions if Cloud Control Plane cannot be reached",
|
|
1117
|
+
)
|
|
1118
|
+
p_check.add_argument(
|
|
1119
|
+
"--match-blocked",
|
|
1120
|
+
action="store_true",
|
|
1121
|
+
help="Invert exit code for OpenSSH `Match exec` (exit 0 when BLOCKED)",
|
|
1122
|
+
)
|
|
1123
|
+
p_check.add_argument("-v", "--verbose", action="store_true", help="Print ALLOWED line on pass")
|
|
1124
|
+
p_check.set_defaults(func=cmd_check)
|
|
1125
|
+
|
|
1126
|
+
p_cs = sub.add_parser("cloud-sync", help="Sync killswitch policy & Master Panic from Integrity Cloud Control Plane")
|
|
1127
|
+
p_cs.add_argument("--cloud-url", help="Cloud Control Plane base URL (default: INTEGRITY_CLOUD_URL or official URL)")
|
|
1128
|
+
p_cs.add_argument("--license-key", help="License or agent sub-key (default: INTEGRITY_LICENSE_KEY)")
|
|
1129
|
+
p_cs.add_argument("--state", dest="sub_state", help="Override local state JSON path")
|
|
1130
|
+
p_cs.add_argument("--json", action="store_true", help="Emit machine-readable JSON")
|
|
1131
|
+
p_cs.set_defaults(func=cmd_cloud_sync)
|
|
1132
|
+
|
|
1133
|
+
p_serve = sub.add_parser("serve", help="Run localhost web UI dashboard")
|
|
1134
|
+
p_serve.add_argument("--host", default="127.0.0.1", help="Bind host (default: 127.0.0.1)")
|
|
1135
|
+
p_serve.add_argument("--port", type=int, default=8787, help="Bind port (default: 8787)")
|
|
1136
|
+
p_serve.set_defaults(func=cmd_serve)
|
|
1137
|
+
|
|
1138
|
+
p_mcp = sub.add_parser("mcp-serve", help="Run zero-dependency tighten-only MCP server over stdio")
|
|
1139
|
+
p_mcp.add_argument("--state", dest="sub_state", help="Override state JSON path")
|
|
1140
|
+
p_mcp.set_defaults(func=cmd_mcp_serve)
|
|
1141
|
+
|
|
1142
|
+
p_ih = sub.add_parser("install-hooks", help="Auto-install PreToolUse hooks for AI coding agents")
|
|
1143
|
+
p_ih.add_argument("--claude", action="store_true", help="Install hook into ~/.claude/settings.json")
|
|
1144
|
+
p_ih.add_argument("--codex", action="store_true", help="Install hook into ~/.codex/hooks.json")
|
|
1145
|
+
p_ih.add_argument("--cursor", action="store_true", help="Install hook into ~/.cursor/hooks.json")
|
|
1146
|
+
p_ih.add_argument("--gemini", action="store_true", help="Install hook into ~/.gemini/settings.json")
|
|
1147
|
+
p_ih.add_argument("--antigravity", action="store_true", help="Install hook into ~/.gemini/config/hooks.json")
|
|
1148
|
+
p_ih.add_argument("--all", action="store_true", help="Install hooks for all supported agents")
|
|
1149
|
+
p_ih.add_argument("--state", dest="sub_state", help="Embed custom state JSON path in hook command")
|
|
1150
|
+
p_ih.add_argument("--action", help="Optional action scope passed to `agent-killswitch check --action`")
|
|
1151
|
+
p_ih.add_argument("--home", help="Override home directory (for hermetic/testing installs)")
|
|
1152
|
+
p_ih.add_argument("--uninstall", action="store_true", help="Alias for `uninstall-hooks` (owner-only)")
|
|
1153
|
+
p_ih.add_argument("--dry-run", action="store_true", help="Preview changes without modifying config files")
|
|
1154
|
+
p_ih.add_argument("--json", action="store_true", help="Emit machine-readable JSON")
|
|
1155
|
+
p_ih.set_defaults(func=cmd_install_hooks)
|
|
1156
|
+
|
|
1157
|
+
p_uh = sub.add_parser("uninstall-hooks", help="Cleanly remove agent-killswitch hooks (owner-only)")
|
|
1158
|
+
p_uh.add_argument("--claude", action="store_true", help="Remove hook from ~/.claude/settings.json")
|
|
1159
|
+
p_uh.add_argument("--codex", action="store_true", help="Remove hook from ~/.codex/hooks.json")
|
|
1160
|
+
p_uh.add_argument("--cursor", action="store_true", help="Remove hook from ~/.cursor/hooks.json")
|
|
1161
|
+
p_uh.add_argument("--gemini", action="store_true", help="Remove hook from ~/.gemini/settings.json")
|
|
1162
|
+
p_uh.add_argument("--antigravity", action="store_true", help="Remove hook from ~/.gemini/config/hooks.json")
|
|
1163
|
+
p_uh.add_argument("--all", action="store_true", help="Remove hooks from all supported agents")
|
|
1164
|
+
p_uh.add_argument("--home", help="Override home directory (for hermetic/testing uninstalls)")
|
|
1165
|
+
p_uh.add_argument("--dry-run", action="store_true", help="Preview removals without modifying config files")
|
|
1166
|
+
p_uh.add_argument("--json", action="store_true", help="Emit machine-readable JSON")
|
|
1167
|
+
p_uh.set_defaults(func=cmd_uninstall_hooks)
|
|
1168
|
+
|
|
1169
|
+
p_nc = sub.add_parser("net-cut", help="OS-level outbound firewall cutoff for LLM API endpoints")
|
|
1170
|
+
p_nc.add_argument("--endpoints-file", help="Path to newline-delimited extra LLM hostnames/IPs to block")
|
|
1171
|
+
p_nc.add_argument("--allow-host", action="append", help="Hostname/IP to explicitly keep allowed (repeatable)")
|
|
1172
|
+
p_nc.add_argument(
|
|
1173
|
+
"--block-binaries",
|
|
1174
|
+
action="append",
|
|
1175
|
+
help="Windows executable path to block outbound (repeatable)",
|
|
1176
|
+
)
|
|
1177
|
+
p_nc.add_argument("--dry-run", action="store_true", help="Generate and print ruleset/commands without applying")
|
|
1178
|
+
p_nc.add_argument("--json", action="store_true", help="Emit machine-readable JSON")
|
|
1179
|
+
p_nc.set_defaults(func=cmd_net_cut)
|
|
1180
|
+
|
|
1181
|
+
p_nr = sub.add_parser("net-restore", help="Remove OS-level LLM API firewall cutoff (owner-only)")
|
|
1182
|
+
p_nr.add_argument("--dry-run", action="store_true", help="Preview restore commands without executing")
|
|
1183
|
+
p_nr.add_argument("--json", action="store_true", help="Emit machine-readable JSON")
|
|
1184
|
+
p_nr.set_defaults(func=cmd_net_restore)
|
|
1185
|
+
|
|
1186
|
+
p_ns = sub.add_parser("net-status", help="Read-only inspection of OS network cutoff rules (zero-write)")
|
|
1187
|
+
p_ns.add_argument("--json", action="store_true", help="Emit machine-readable JSON")
|
|
1188
|
+
p_ns.set_defaults(func=cmd_net_status)
|
|
1189
|
+
|
|
1190
|
+
p_fr = sub.add_parser("freeze", help="Freeze running AI agent processes (SIGSTOP on POSIX)")
|
|
1191
|
+
p_fr.add_argument("--vendor", help="Only freeze processes matching this vendor (e.g. claude, codex)")
|
|
1192
|
+
p_fr.add_argument("--dry-run", action="store_true", help="List matched agent processes without sending signals")
|
|
1193
|
+
p_fr.add_argument("--json", action="store_true", help="Emit machine-readable JSON")
|
|
1194
|
+
p_fr.set_defaults(func=cmd_freeze)
|
|
1195
|
+
|
|
1196
|
+
p_th = sub.add_parser("thaw", help="Resume frozen AI agent processes (SIGCONT on POSIX, owner-only)")
|
|
1197
|
+
p_th.add_argument("--vendor", help="Only resume processes matching this vendor")
|
|
1198
|
+
p_th.add_argument("--dry-run", action="store_true", help="List matched agent processes without sending signals")
|
|
1199
|
+
p_th.add_argument("--json", action="store_true", help="Emit machine-readable JSON")
|
|
1200
|
+
p_th.set_defaults(func=cmd_thaw)
|
|
1201
|
+
|
|
1202
|
+
p_hd = sub.add_parser("harden", help="Harden OS-level ACLs on state directory & state.json (read-only for agents)")
|
|
1203
|
+
p_hd.add_argument("--state", dest="sub_state", help="Override state JSON path to harden")
|
|
1204
|
+
p_hd.add_argument("--dry-run", action="store_true", help="Print hardening and rollback commands without executing")
|
|
1205
|
+
p_hd.add_argument("--json", action="store_true", help="Emit machine-readable JSON")
|
|
1206
|
+
p_hd.set_defaults(func=cmd_harden)
|
|
1207
|
+
|
|
1208
|
+
return parser
|
|
1209
|
+
|
|
1210
|
+
|
|
1211
|
+
def main(argv: list[str] | None = None) -> int:
|
|
1212
|
+
parser = build_parser()
|
|
1213
|
+
args = parser.parse_args(argv)
|
|
1214
|
+
return int(args.func(args))
|