A live plugin declares harnessHooks[]: declarative rules (command/output regex → additionalContext, evaluated by the stdlib sidecar/plugin_hooks.py, no plugin code — owner-approvable) or .py script hooks (operator approval). Regexes compiled + ReDoS-checked at install, paths kept inside the plugin, the declaration in the approval fingerprint (unchanged for plugins without it). Placed by the plugin's where/profiles/workers settings; guests' computers and scoped runs only get guestAllowed hooks. The lab reads /data/plugins/live-hooks (PluginStore.sync_hooks on every owner plugin change and at start); a worker gets its filtered copy in the /sync bundle's hooks map (~/.ai-agent-worker/hooks). _claude_settings wires them in place of the hard-coded gcloud hook; sidecar/gcloud_reauth.py and its test are gone — the gcloud-reauth plugin (ai-agent-plugins) carries it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
185 lines
7.2 KiB
Python
185 lines
7.2 KiB
Python
#!/usr/bin/env python3
|
|
"""Live plugins' ``harnessHooks`` (backend plugins/harness_hooks.py) on this
|
|
machine: where their index lives, the ``--settings`` hook entries a claude run
|
|
gets for them (launch.py ``_claude_settings``), and — run as a hook — the
|
|
evaluator of the declarative rules.
|
|
|
|
The index (``index.json``: ``{hash, hooks: [rule…]}`` + the script hooks'
|
|
files beside it, ``<plugin>/<path>``) is already filtered for this machine by
|
|
the hub: the lab's is ``live-hooks/`` (the hub's data dir), a worker's is what
|
|
``/sync`` wrote under ``~/.ai-agent-worker/hooks``. A scoped (guest) run only
|
|
gets the rules marked ``guestAllowed``.
|
|
|
|
As a hook (``plugin_hooks.py --index P --event E --matcher M [--guest]``) it
|
|
reads the hook's JSON on stdin, applies every declarative rule of that event
|
|
and matcher, and prints one ``additionalContext`` with each matching rule's
|
|
message. Stdlib only, fast, and it always exits 0: a broken index, a bad
|
|
regex or bad input prints nothing. Tool output is scanned on its last 200 KB.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import re
|
|
import shlex
|
|
import sys
|
|
|
|
MAX_SCAN = 200_000
|
|
_DECL_TIMEOUT_S = 5
|
|
_REL_RE = re.compile(r"^[A-Za-z0-9._-]+(?:/[A-Za-z0-9._-]+)*$")
|
|
|
|
|
|
# ── where the index lives ────────────────────────────────────────────────────
|
|
def root(is_worker: bool) -> pathlib.Path:
|
|
v = os.environ.get("SIDECAR_LIVE_HOOKS_DIR")
|
|
if v:
|
|
return pathlib.Path(os.path.expanduser(v))
|
|
if is_worker:
|
|
return pathlib.Path(os.path.expanduser("~/.ai-agent-worker/hooks"))
|
|
if os.path.isdir("/data/plugins"):
|
|
return pathlib.Path("/data/plugins/live-hooks")
|
|
return pathlib.Path(os.path.expanduser("~/homelab/services/ai-agent/data/plugins/live-hooks"))
|
|
|
|
|
|
def load(index: pathlib.Path) -> list[dict]:
|
|
try:
|
|
idx = json.loads(index.read_text(encoding="utf-8"))
|
|
except (OSError, ValueError):
|
|
return []
|
|
hooks = idx.get("hooks") if isinstance(idx, dict) else None
|
|
return [h for h in hooks or [] if isinstance(h, dict)] if isinstance(hooks, list) else []
|
|
|
|
|
|
def _safe_script(base: pathlib.Path, rel) -> pathlib.Path | None:
|
|
if not isinstance(rel, str) or not _REL_RE.match(rel) or ".." in rel.split("/"):
|
|
return None
|
|
p = (base / rel).resolve()
|
|
try:
|
|
p.relative_to(base.resolve())
|
|
except ValueError:
|
|
return None
|
|
return p if p.is_file() and p.suffix == ".py" else None
|
|
|
|
|
|
def settings_hooks(base: pathlib.Path, python: str, scoped: bool = False,
|
|
code_mode: bool = False) -> dict[str, list[dict]]:
|
|
"""``{event: [settings hook entry]}`` for the index under ``base``: one
|
|
entry per (event, matcher) of declarative rules (this script), one per
|
|
script hook (the plugin's file)."""
|
|
index = base / "index.json"
|
|
out: dict[str, list[dict]] = {}
|
|
groups: dict[tuple[str, str | None], bool] = {}
|
|
me = pathlib.Path(__file__).resolve()
|
|
|
|
def add(event, matcher, cmd, timeout):
|
|
hook = {"type": "command", "command": cmd, "timeout": timeout}
|
|
if code_mode:
|
|
hook["onFailure"] = "continue"
|
|
entry: dict = {"hooks": [hook]}
|
|
if matcher is not None:
|
|
entry["matcher"] = matcher
|
|
out.setdefault(event, []).append(entry)
|
|
|
|
for h in load(index):
|
|
if h.get("harness", "claude") != "claude" or (scoped and h.get("guestAllowed") is not True):
|
|
continue
|
|
event, matcher = h.get("event"), h.get("matcher")
|
|
if not isinstance(event, str) or (matcher is not None and not isinstance(matcher, str)):
|
|
continue
|
|
if h.get("script"):
|
|
p = _safe_script(base, h["script"])
|
|
if p is None:
|
|
continue
|
|
try:
|
|
t = max(1, min(60, int(h.get("timeoutSec") or 10)))
|
|
except (TypeError, ValueError):
|
|
t = 10
|
|
add(event, matcher, f"{shlex.quote(python)} -I {shlex.quote(str(p))}", t)
|
|
elif h.get("message"):
|
|
groups[(event, matcher)] = True
|
|
for event, matcher in groups:
|
|
cmd = (f"{shlex.quote(python)} -I {shlex.quote(str(me))} --index {shlex.quote(str(index))}"
|
|
f" --event {shlex.quote(event)}")
|
|
if matcher is not None:
|
|
cmd += f" --matcher {shlex.quote(matcher)}"
|
|
if scoped:
|
|
cmd += " --guest"
|
|
add(event, matcher, cmd, _DECL_TIMEOUT_S)
|
|
return out
|
|
|
|
|
|
# ── the evaluator ────────────────────────────────────────────────────────────
|
|
def _text(v) -> str:
|
|
if isinstance(v, str):
|
|
return v
|
|
if isinstance(v, dict):
|
|
return "\n".join(_text(x) for x in v.values())
|
|
if isinstance(v, list):
|
|
return "\n".join(_text(x) for x in v)
|
|
return ""
|
|
|
|
|
|
def _search(pat, text: str, flags: int) -> bool:
|
|
try:
|
|
return re.search(pat, text, flags) is not None
|
|
except (re.error, TypeError):
|
|
return False
|
|
|
|
|
|
def matches(rule: dict, payload: dict) -> bool:
|
|
flags = re.IGNORECASE if rule.get("ignoreCase", True) is not False else 0
|
|
cmd = _text((payload.get("tool_input") or {}).get("command"))
|
|
if rule.get("excludeCommandRegex") and _search(rule["excludeCommandRegex"], cmd, flags):
|
|
return False
|
|
if rule.get("commandRegex") and not _search(rule["commandRegex"], cmd, flags):
|
|
return False
|
|
if rule.get("outputRegex"):
|
|
out = _text(payload.get("tool_response"))[-MAX_SCAN:]
|
|
if not _search(rule["outputRegex"], out, flags):
|
|
return False
|
|
return bool(rule.get("commandRegex") or rule.get("outputRegex"))
|
|
|
|
|
|
def check(rules: list[dict], payload: dict, event: str, matcher: str | None,
|
|
guest: bool = False) -> str | None:
|
|
"""The hook's stdout for ``payload``, or None."""
|
|
msgs: list[str] = []
|
|
for r in rules:
|
|
if r.get("script") or r.get("event") != event or r.get("matcher") != matcher:
|
|
continue
|
|
if guest and r.get("guestAllowed") is not True:
|
|
continue
|
|
msg = r.get("message")
|
|
if isinstance(msg, str) and msg and msg not in msgs and matches(r, payload):
|
|
msgs.append(msg)
|
|
if not msgs:
|
|
return None
|
|
return json.dumps({"hookSpecificOutput": {
|
|
"hookEventName": event, "additionalContext": "\n\n".join(msgs)}})
|
|
|
|
|
|
def main(argv: list[str]) -> int:
|
|
try:
|
|
args = {"--matcher": None, "--guest": False}
|
|
it = iter(argv)
|
|
for a in it:
|
|
if a == "--guest":
|
|
args[a] = True
|
|
elif a in ("--index", "--event", "--matcher"):
|
|
args[a] = next(it, None)
|
|
payload = json.loads(sys.stdin.read() or "{}")
|
|
if isinstance(payload, dict) and args.get("--index") and args.get("--event"):
|
|
out = check(load(pathlib.Path(args["--index"])), payload, args["--event"],
|
|
args["--matcher"], bool(args["--guest"]))
|
|
if out:
|
|
print(out)
|
|
except Exception: # noqa: BLE001 — a hint hook never breaks a run
|
|
pass
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main(sys.argv[1:]))
|