Files
ai-agent/backend/plugins/harness_hooks.py
gabrielvidalandClaude Opus 5.5 94c07968d3 feat(plugins): harnessHooks[] — plugins hook into the agent harness; gcloud_reauth leaves the core
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>
2026-11-26 19:12:32 +01:00

318 lines
14 KiB
Python

"""``harnessHooks[]``: hooks a live plugin adds to the agent harness (Claude
Code's ``--settings`` hooks) on the lab and on paired workers.
Two shapes:
* **declarative** — a rule the sidecar's stdlib runner (``sidecar/
plugin_hooks.py``) evaluates: a tool call whose command / output matches
gets ``message`` as ``additionalContext``. No plugin code runs, anywhere;
the owner may approve it.
* **script** — a ``.py`` file of the plugin the harness runs as the hook
itself (``python -I``). Code on every machine it reaches: operator approval.
Only the owner's enabled, approved plugins count. Where a hook goes is the
plugin's settings — ``where`` (``workers`` | ``lab`` | ``all``), ``profiles``
(profile ids; empty = any) and ``workers`` (runner ids, ``local`` = the lab;
non-empty overrides the other two). A guest's computer — and a guest's scoped
run on the lab — gets a hook only when it says ``guestAllowed: true``.
The host sidecar reads ``live-hooks/index.json`` (already filtered for
``local``); a worker gets its own filtered copy in its ``/sync`` bundle
(``hooks``: ``{hash, rules, files}``), written to ``~/.ai-agent-worker/hooks``.
"""
from __future__ import annotations
import base64
import hashlib
import json
import os
import pathlib
import shutil
import secrets
from typing import Any, Callable
HARNESSES = frozenset({"claude"})
DECL_EVENTS = frozenset({"PreToolUse", "PostToolUse"})
SCRIPT_EVENTS = frozenset({"PreToolUse", "PostToolUse", "UserPromptSubmit", "Stop", "SessionStart"})
TOOL_EVENTS = frozenset({"PreToolUse", "PostToolUse"})
WHERE = ("workers", "lab", "all")
MAX_HOOKS = 16
MAX_MESSAGE = 1000
MAX_SCRIPT_BYTES = 256 * 1024
LOCAL = "local"
_HOOK_KEYS = frozenset({"id", "harness", "event", "matcher", "commandRegex",
"excludeCommandRegex", "outputRegex", "ignoreCase", "message",
"script", "timeoutSec", "guestAllowed", "description"})
# runner id → its profile id (None: a guest's computer / unknown) — bound by
# core/state to the ProfileStore.
profile_of: Callable[[str], str | None] = lambda rid: None # noqa: E731
# ── manifest validation ──────────────────────────────────────────────────────
def parse(root: pathlib.Path, raw: Any, errors: list[str]) -> list[dict[str, Any]]:
"""Validate ``harnessHooks[]`` into normalized dicts (errors appended)."""
from plugins.manifest import _KEY_RE, _check_safe_regex, _safe_rel
if raw is None:
return []
if not isinstance(raw, list) or len(raw) > MAX_HOOKS:
errors.append(f"harnessHooks must be a list ({MAX_HOOKS} max)")
return []
out: list[dict[str, Any]] = []
seen: set[str] = set()
for i, h in enumerate(raw):
lb = f"harnessHooks[{i}]"
if not isinstance(h, dict):
errors.append(f"{lb} must be an object")
continue
bad = sorted(set(h) - _HOOK_KEYS)
if bad:
errors.append(f"{lb}: unknown keys {', '.join(bad)}")
hid = str(h.get("id") or "").strip()
if not _KEY_RE.match(hid) or hid in seen:
errors.append(f"{lb}.id invalid or duplicate")
continue
seen.add(hid)
lb = f"harnessHooks.{hid}"
harness = str(h.get("harness") or "claude")
if harness not in HARNESSES:
errors.append(f"{lb}.harness must be one of {sorted(HARNESSES)}")
event = str(h.get("event") or "")
script = h.get("script")
is_script = script is not None
events = SCRIPT_EVENTS if is_script else DECL_EVENTS
if event not in events:
errors.append(f"{lb}.event must be one of {sorted(events)}")
continue
item: dict[str, Any] = {"id": hid, "harness": harness, "event": event,
"guestAllowed": h.get("guestAllowed") is True,
"description": str(h.get("description") or "")[:200]}
matcher = h.get("matcher")
if event in TOOL_EVENTS:
if not isinstance(matcher, str) or len(matcher) > 200:
errors.append(f"{lb}.matcher (a tool-name regex) is required for {event}")
continue
if _check_safe_regex(matcher, f"{lb}.matcher", errors) is None:
continue
item["matcher"] = matcher
elif matcher is not None:
errors.append(f"{lb}.matcher: only for PreToolUse / PostToolUse")
if is_script:
for k in ("message", "commandRegex", "excludeCommandRegex", "outputRegex"):
if h.get(k) is not None:
errors.append(f"{lb}: a script hook takes no {k}")
if not isinstance(script, str) or not script.endswith(".py"):
errors.append(f"{lb}.script must be a .py file of the plugin")
continue
p = _safe_rel(root, script, f"{lb}.script", errors)
if p is None:
continue
if p.stat().st_size > MAX_SCRIPT_BYTES:
errors.append(f"{lb}.script is over {MAX_SCRIPT_BYTES // 1024} KB")
continue
try:
t = int(h.get("timeoutSec") or 10)
except (TypeError, ValueError):
t = 10
item.update(script=script, timeoutSec=max(1, min(60, t)))
else:
msg = h.get("message")
if not isinstance(msg, str) or not msg.strip() or len(msg) > MAX_MESSAGE:
errors.append(f"{lb}.message is required (<= {MAX_MESSAGE} chars)")
continue
if event == "PreToolUse" and h.get("outputRegex") is not None:
errors.append(f"{lb}.outputRegex: a PreToolUse call has no output yet")
continue
rx: dict[str, str] = {}
ok = True
for k in ("commandRegex", "excludeCommandRegex", "outputRegex"):
v = h.get(k)
if v is None:
continue
pat = _check_safe_regex(v, f"{lb}.{k}", errors)
if pat is None:
ok = False
else:
rx[k] = pat
if not ok:
continue
if not rx.get("commandRegex") and not rx.get("outputRegex"):
errors.append(f"{lb}: needs commandRegex or outputRegex")
continue
item.update(rx, message=msg.strip(), ignoreCase=h.get("ignoreCase", True) is not False)
out.append(item)
return out
def has_script(manifest: dict[str, Any]) -> bool:
return any(h.get("script") for h in manifest.get("harnessHooks") or [])
def summary(manifest: dict[str, Any]) -> list[dict[str, Any]]:
items = []
for h in manifest.get("harnessHooks") or []:
where = f"{h['event']}" + (f" · {h['matcher']}" if h.get("matcher") else "")
guests = ", guests' computers included" if h.get("guestAllowed") else ""
if h.get("script"):
items.append({"kind": "harnessHook", "privileged": True,
"label": f"Runs hook script `{h['script']}` in agent runs ({where}) "
f"on the machines its settings pick{guests} (operator only)"})
else:
items.append({"kind": "harnessHook",
"label": f"Adds a hint to agent runs when a tool call matches "
f"`{h['id']}` ({where}){guests} — no code runs"})
return items
def fingerprint_sig(manifest: dict[str, Any]) -> list | None:
hooks = manifest.get("harnessHooks") or []
if not hooks:
return None
return [[h["id"], h["harness"], h["event"], h.get("matcher"), h.get("commandRegex"),
h.get("excludeCommandRegex"), h.get("outputRegex"), h.get("message"),
h.get("script"), bool(h.get("guestAllowed"))] for h in hooks]
# ── scope ────────────────────────────────────────────────────────────────────
def _as_list(v) -> list[str]:
if isinstance(v, str):
v = [x for part in v.splitlines() for x in part.split(",")]
if not isinstance(v, list):
return []
return [x.strip() for x in v if isinstance(x, str) and x.strip()]
def scope_of(manifest: dict[str, Any], config: dict[str, Any] | None) -> dict[str, Any]:
"""The plugin's settings that place its hooks: a value never saved reads
as its field's ``default``."""
defaults = {f["key"]: f.get("default")
for f in (manifest.get("settings") or {}).get("fields") or []}
cfg = config or {}
def get(k):
return cfg[k] if k in cfg and cfg[k] not in (None, "") else defaults.get(k)
where = str(get("where") or "all").strip().lower()
return {"where": where if where in WHERE else "all",
"profiles": _as_list(get("profiles")), "workers": _as_list(get("workers"))}
def applies(scope: dict[str, Any], runner: str, profile: str | None,
guest_computer: bool, guest_allowed: bool) -> bool:
if guest_computer and not guest_allowed:
return False
if scope.get("workers"):
return runner in scope["workers"]
where = scope.get("where") or "all"
if where == "lab" and runner != LOCAL:
return False
if where == "workers" and runner == LOCAL:
return False
if scope.get("profiles") and profile not in scope["profiles"]:
return False
return True
def all_rules(store) -> list[dict[str, Any]]:
"""Every active hook of the owner's plugins, with its plugin's scope."""
out = []
for kind in ("app", "provider", "harness"):
for rec in store.active_by_kind(kind):
mf = rec["manifest"]
hooks = mf.get("harnessHooks") or []
if not hooks:
continue
scope = scope_of(mf, rec.get("config"))
for h in hooks:
r = {k: v for k, v in h.items() if k != "description"}
r["plugin"] = rec["id"]
r["scope"] = scope
if h.get("script"):
r["script"] = f"{rec['id']}/{h['script']}"
r["_src"] = str(pathlib.Path(rec["dir"] or "") / h["script"])
out.append(r)
out.sort(key=lambda r: (r["plugin"], r["id"]))
return out
def for_runner(rules: list[dict[str, Any]], runner: str, profile: str | None,
guest_computer: bool = False) -> list[dict[str, Any]]:
return [r for r in rules if applies(r["scope"], runner, profile, guest_computer,
bool(r.get("guestAllowed")))]
def _public(rules: list[dict[str, Any]]) -> list[dict[str, Any]]:
return [{k: v for k, v in r.items() if not k.startswith("_")} for r in rules]
def _hash(rules: list[dict[str, Any]], files: dict[str, str]) -> str:
h = hashlib.sha256(json.dumps(_public(rules), sort_keys=True).encode())
for k in sorted(files):
h.update(f"\0{k}\0".encode() + files[k].encode())
return h.hexdigest()[:16]
# ── the host's copy: live-hooks/ ─────────────────────────────────────────────
def materialize(store) -> bool:
"""Write ``live-hooks/`` (index.json + script copies) with the hooks that
apply to the lab. True when it changed."""
base: pathlib.Path = store.live_hooks_dir
rules = for_runner(all_rules(store), LOCAL, _profile(LOCAL))
base.mkdir(parents=True, exist_ok=True)
tmp = base.parent / f".live-hooks-{secrets.token_hex(4)}"
tmp.mkdir()
files: dict[str, str] = {}
kept = []
for r in rules:
if r.get("script"):
src = pathlib.Path(r["_src"])
if not src.is_file():
continue
dest = tmp / r["script"]
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(src, dest)
files[r["script"]] = hashlib.sha256(src.read_bytes()).hexdigest()
kept.append(r)
try:
prev = json.loads((base / "index.json").read_text(encoding="utf-8"))
except (OSError, ValueError):
prev = {}
digest = _hash(kept, files)
index = {"version": int(prev.get("version") or 0) + (digest != prev.get("hash")),
"hash": digest, "hooks": _public(kept)}
(tmp / "index.json").write_text(json.dumps(index, indent=2, sort_keys=True), encoding="utf-8")
old = base.parent / f".live-hooks-old-{secrets.token_hex(4)}"
os.replace(base, old)
os.replace(tmp, base)
shutil.rmtree(old, ignore_errors=True)
return digest != prev.get("hash")
def _profile(runner: str) -> str | None:
try:
return profile_of(runner)
except Exception: # noqa: BLE001 — no profile store: no profile filter match
return None
# ── a worker's copy: the /sync bundle's ``hooks`` map ───────────────────────
def bundle_for_worker(store, w: dict) -> dict[str, Any]:
"""``{hash, rules, files: {rel: base64}}`` for worker ``w`` — empty rules
when none apply (an empty map tells the worker to clear its copy)."""
guest = bool(w.get("owner"))
rid = str(w.get("id") or "")
rules = for_runner(all_rules(store), rid, None if guest else _profile(rid), guest)
files: dict[str, str] = {}
kept = []
for r in rules:
if r.get("script"):
try:
data = pathlib.Path(r["_src"]).read_bytes()
except OSError:
continue
if len(data) > MAX_SCRIPT_BYTES:
continue
files[r["script"]] = base64.b64encode(data).decode()
kept.append(r)
return {"hash": _hash(kept, files), "rules": _public(kept), "files": files}