Files
gabrielvidalandClaude Opus 5.5 16aabb9922 feat(plugins): move commits + diff viewer out of core into plugins
Generic platform points for the `diff-viewer` and `commits` plugins
(ai-agent-plugins): a `conversation.tab` slot (Thread | Changes N) with
setTab/openTab/closeTab/reply bridges; stackable + pullOut tool cards and
match.hasReport; `pathShims` (a git PATH shim for every harness) with
out-of-band reports (lab: /api/plugin-reports, worker: outbox `report`);
`conversations.reports` and `diff.read` hub bridges; ui.pages[].opens for
Project/Service "Recent commits". The core commit card, Changes view, diff
page and review store are gone; bash_diff.py keeps bashDiff only. Legacy
gitCommits / commit-line parsing stays for past transcripts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 20:17:04 +01:00

259 lines
10 KiB
Python

"""Live plugins' ``pathShims`` (backend plugins/path_shims.py) on this machine:
the POSIX-sh wrappers every agent run gets first on its ``PATH``, whatever its
harness (``launch._launch`` calls :func:`apply`), and the report spool's drain.
The shims come with the ``harnessHooks`` index (plugin_hooks.root(): the lab's
``live-hooks/``, a worker's ``~/.ai-agent-worker/hooks``) — ``shims: [{plugin,
id, command, script, triggers, guestAllowed}]``, already filtered for this
machine by the hub; a scoped (guest) run only gets the ``guestAllowed`` ones.
``SIDECAR_PLUGIN_HOOKS=0`` turns them off.
A wrapper ``<SHIMS_DIR>/bin[-guest]/<command>`` scans its arguments. One equal
to a trigger word → ``exec <python> -I <script> "$@"`` with ``AIA_SHIM_REAL``
(the command the run would have run without the shim, resolved on the run's
PATH minus the shim dir), ``AIA_SHIM_PLUGIN``, ``AIA_REPORT_PY`` (core's
``aia_report.py``, copied next to the wrappers) and ``AIA_SHIM_ACTIVE=1``
(nested calls — a git hook's own ``git`` — take the fast path). Anything else
→ ``exec "$AIA_SHIM_REAL" "$@"``: read-only git never starts a python, and
``exec`` keeps the exit code, stdio and signals the real command's.
Every run gets ``AIA_SESSION_ID`` and the report transport: on a worker the
outbox env it already has (claude_env._run_env), on the lab ``AIA_REPORT_URL``
(the hub) + ``AIA_REPORT_TOKEN`` (HMAC of the session id under the sidecar's
bearer, which the hub checks), and ``AIA_REPORT_SPOOL`` — where a report that
couldn't be sent waits for :func:`drain_spool`.
"""
from __future__ import annotations
import hashlib
import hmac
import json
import os
import pathlib
import re
import shlex
import shutil
import sys
import threading
_CMD_RE = re.compile(r"^[a-z][a-z0-9_-]{0,31}$")
_TRIGGER_RE = re.compile(r"^[a-z][a-z0-9-]{0,31}$")
_PLUGIN_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,47}$")
REPORT_PY = pathlib.Path(__file__).resolve().parent / "aia_report.py"
_lock = threading.Lock()
def shims_dir() -> pathlib.Path:
return pathlib.Path(os.path.expanduser(
os.environ.get("SIDECAR_SHIMS_DIR", "~/.cache/ai-agent/shims")))
def load(base: pathlib.Path, scoped: bool = False) -> list[dict]:
"""The index's shims that a run (a scoped one: ``guestAllowed`` only) gets."""
try:
idx = json.loads((base / "index.json").read_text(encoding="utf-8"))
except (OSError, ValueError):
return []
out, seen = [], set()
for s in (idx.get("shims") if isinstance(idx, dict) else None) or []:
if not isinstance(s, dict) or (scoped and s.get("guestAllowed") is not True):
continue
cmd, plugin = s.get("command"), s.get("plugin")
trig = [t for t in s.get("triggers") or [] if isinstance(t, str) and _TRIGGER_RE.match(t)]
if (not isinstance(cmd, str) or not _CMD_RE.match(cmd) or cmd in seen or not trig
or not isinstance(plugin, str) or not _PLUGIN_RE.match(plugin)):
continue
import plugin_hooks
script = plugin_hooks._safe_script(base, s.get("script"))
if script is None:
continue
seen.add(cmd)
out.append({"command": cmd, "plugin": plugin, "script": str(script), "triggers": trig})
return out
def _q(s: str) -> str:
return shlex.quote(s)
def wrapper(shim: dict, *, real: str, bindir: str, python: str, report_py: str) -> str:
"""The wrapper script of one shim (POSIX sh)."""
cmd = shim["command"]
pattern = "|".join(shim["triggers"])
return f"""#!/bin/sh
# ai-agent path shim for `{cmd}` (plugin {shim['plugin']}) — generated by the
# sidecar (path_shims.py) at each launch; edits are overwritten.
AIA_SHIM_REAL={_q(real)}
if [ ! -x "$AIA_SHIM_REAL" ] || [ -d "$AIA_SHIM_REAL" ]; then
AIA_SHIM_REAL=
_aia_ifs=$IFS; IFS=:; set -f
for _aia_p in $PATH; do
[ "$_aia_p" = {_q(bindir)} ] && continue
[ -n "$_aia_p" ] || _aia_p=.
if [ -x "$_aia_p/{cmd}" ] && [ ! -d "$_aia_p/{cmd}" ]; then AIA_SHIM_REAL="$_aia_p/{cmd}"; break; fi
done
IFS=$_aia_ifs; set +f
if [ -z "$AIA_SHIM_REAL" ]; then echo "{cmd}: command not found" >&2; exit 127; fi
fi
if [ -z "$AIA_SHIM_ACTIVE" ] && [ -r {_q(shim['script'])} ]; then
for _aia_a in "$@"; do
case "$_aia_a" in
{pattern})
AIA_SHIM_PLUGIN={_q(shim['plugin'])}; AIA_REPORT_PY={_q(report_py)}; AIA_SHIM_ACTIVE=1
export AIA_SHIM_REAL AIA_SHIM_PLUGIN AIA_REPORT_PY AIA_SHIM_ACTIVE
exec {_q(python)} -I {_q(shim['script'])} "$@"
;;
esac
done
fi
exec "$AIA_SHIM_REAL" "$@"
"""
def _write_if_changed(p: pathlib.Path, text: str, mode: int) -> None:
try:
if p.read_text(encoding="utf-8") == text and (p.stat().st_mode & 0o777) == mode:
return
except OSError:
pass
tmp = p.with_name(f".{p.name}.{os.getpid()}.tmp")
tmp.write_text(text, encoding="utf-8")
os.chmod(tmp, mode)
os.replace(tmp, p)
def _python() -> str:
exe = sys.executable
return exe if exe and os.access(exe, os.X_OK) else "python3"
def report_token(sid: str, key: str) -> str:
"""The run's report credential on the lab: what the hub recomputes
(backend plugins/hubreports.py ``token_ok``)."""
return hmac.new(key.encode(), f"aia-report:{sid}".encode(), hashlib.sha256).hexdigest()[:40]
def apply(env: dict[str, str], sid: str, *, scoped: bool, is_worker: bool,
base: pathlib.Path | None = None, enabled: bool = True,
root: pathlib.Path | None = None) -> dict[str, str]:
"""``env`` with the run's report env and, when shims apply here, their
wrappers' dir first on ``PATH``. Best effort: any failure leaves PATH
as it was (never a broken run)."""
env = dict(env)
root = root or shims_dir()
env["AIA_SESSION_ID"] = sid
env["AIA_REPORT_SPOOL"] = str(root / "spool.jsonl")
if not is_worker:
from config import TOKEN
if TOKEN:
env["AIA_REPORT_URL"] = (os.environ.get("AI_AGENT_URL")
or "http://127.0.0.1:8096").rstrip("/")
env["AIA_REPORT_TOKEN"] = report_token(sid, TOKEN)
if not enabled:
return env
try:
if base is None:
import plugin_hooks
base = plugin_hooks.root(is_worker)
shims = load(base, scoped)
if not shims:
return env
bindir = root / ("bin-guest" if scoped else "bin")
path = env.get("PATH") or os.defpath
rest = os.pathsep.join(p for p in path.split(os.pathsep)
if p and os.path.abspath(p) != str(bindir)
and os.path.abspath(p) != str(root / "bin")
and os.path.abspath(p) != str(root / "bin-guest"))
with _lock:
bindir.mkdir(parents=True, exist_ok=True)
report_py = root / "aia_report.py"
_write_if_changed(report_py, REPORT_PY.read_text(encoding="utf-8"), 0o644)
wanted = set()
for s in shims:
real = shutil.which(s["command"], path=rest) or ""
_write_if_changed(bindir / s["command"],
wrapper(s, real=real, bindir=str(bindir), python=_python(),
report_py=str(report_py)), 0o755)
wanted.add(s["command"])
for f in bindir.iterdir(): # a shim no longer delivered
if f.name not in wanted and not f.name.startswith("."):
f.unlink(missing_ok=True)
env["PATH"] = f"{bindir}{os.pathsep}{rest}" if rest else str(bindir)
except Exception as e: # noqa: BLE001 — a shim never stops a launch
print(f"[sidecar] path shims skipped: {e!r}", flush=True)
return env
# ── the spool ────────────────────────────────────────────────────────────────
def drain_spool(deliver, root: pathlib.Path | None = None, max_items: int = 200) -> int:
"""Hand each spooled report to ``deliver(payload) -> bool``; what it
refuses stays. The number delivered."""
p = (root or shims_dir()) / "spool.jsonl"
with _lock:
try:
lines = p.read_text(encoding="utf-8").splitlines()
except OSError:
return 0
if not lines:
return 0
keep, sent = [], 0
for i, line in enumerate(lines):
if i >= max_items:
keep.append(line)
continue
try:
payload = json.loads(line)
except ValueError:
continue
if not isinstance(payload, dict):
continue
try:
ok = bool(deliver(payload))
except Exception: # noqa: BLE001
ok = False
if ok:
sent += 1
else:
keep.append(line)
tmp = p.with_name(f".spool.{os.getpid()}.tmp")
tmp.write_text("".join(ln + "\n" for ln in keep), encoding="utf-8")
os.chmod(tmp, 0o600)
os.replace(tmp, p)
return sent
def lab_deliver(payload: dict) -> bool:
"""The lab sidecar's own delivery of a spooled report: to the hub, with
the run's token recomputed."""
from config import TOKEN
import aia_report
sid = str(payload.get("sessionId") or "")
if not TOKEN or not sid:
return False
url = (os.environ.get("AI_AGENT_URL") or "http://127.0.0.1:8096").rstrip("/")
return aia_report._post(f"{url}/api/plugin-reports",
{**payload, "token": report_token(sid, TOKEN)}, {}, 5.0)
def start_drain(outbox_put, is_worker: bool, every_s: float = 20.0) -> None:
"""A daemon thread draining the spool: into the outbox on a worker, to the
hub on the lab."""
def deliver(payload: dict) -> bool:
if not is_worker:
return lab_deliver(payload)
try:
outbox_put("report", payload)
except ValueError as e:
return "duplicate" in str(e) # already queued: drop the copy
return True
def loop():
ev = threading.Event()
while not ev.wait(every_s):
try:
drain_spool(deliver)
except Exception: # noqa: BLE001
pass
threading.Thread(target=loop, daemon=True, name="report-spool").start()