Files
ai-agent/backend/plugins/path_shims.py
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

148 lines
6.3 KiB
Python

"""``pathShims[]``: commands a live plugin wraps on every agent run's ``PATH``
(since 2026-11-27 — the ``commits`` plugin's ``git`` shim).
```json
"pathShims": [ { "id": "git", "command": "git", "script": "shim/git_shim.py",
"triggers": ["commit", "merge", "push"], "guestAllowed": true } ]
```
The sidecar (``sidecar/path_shims.py``, called by ``launch._launch`` for every
harness) writes a POSIX-sh wrapper ``<state>/shims/bin/<command>`` and puts
its dir first on the run's ``PATH``. The wrapper scans its arguments: one equal
to a trigger word → ``exec python3 -I <script> "$@"`` (the script runs the real
command itself and files reports with core's ``aia_report.py``); else ``exec``
the real command — read-only git never starts a python.
Code on every machine a run goes through: **operator approval**, and the whole
declaration is in the approval fingerprint (only when declared — other
plugins' fingerprints don't move). Delivered exactly like ``harnessHooks``
scripts (plugins/harness_hooks.py): the lab's ``live-hooks/index.json``
(``shims``) and a worker's ``/sync`` bundle ``hooks`` map, with the same
``where`` / ``profiles`` / ``workers`` scope settings and ``guestAllowed``;
``SIDECAR_PLUGIN_HOOKS=0`` turns them off on a machine.
"""
from __future__ import annotations
import pathlib
import re
from typing import Any
MAX_SHIMS = 4
MAX_TRIGGERS = 32
MAX_SCRIPT_BYTES = 256 * 1024
COMMAND_RE = re.compile(r"^[a-z][a-z0-9_-]{0,31}$")
TRIGGER_RE = re.compile(r"^[a-z][a-z0-9-]{0,31}$")
_KEYS = frozenset({"id", "command", "script", "triggers", "guestAllowed", "description"})
def parse(root: pathlib.Path, raw: Any, errors: list[str]) -> list[dict[str, Any]]:
"""Validate ``pathShims[]`` into normalized dicts (errors appended)."""
from plugins.manifest import _KEY_RE, _safe_rel
if raw is None:
return []
if not isinstance(raw, list) or len(raw) > MAX_SHIMS:
errors.append(f"pathShims must be a list ({MAX_SHIMS} max)")
return []
out: list[dict[str, Any]] = []
seen: set[str] = set()
commands: set[str] = set()
for i, s in enumerate(raw):
lb = f"pathShims[{i}]"
if not isinstance(s, dict):
errors.append(f"{lb} must be an object")
continue
bad = sorted(set(s) - _KEYS)
if bad:
errors.append(f"{lb}: unknown keys {', '.join(bad)}")
sid = str(s.get("id") or "").strip()
if not _KEY_RE.match(sid) or sid in seen:
errors.append(f"{lb}.id invalid or duplicate")
continue
seen.add(sid)
lb = f"pathShims.{sid}"
cmd = s.get("command")
if not isinstance(cmd, str) or not COMMAND_RE.match(cmd):
errors.append(f"{lb}.command must match {COMMAND_RE.pattern}")
continue
if cmd in commands:
errors.append(f"{lb}.command {cmd!r} is wrapped twice")
continue
commands.add(cmd)
script = s.get("script")
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
trig = s.get("triggers")
if (not isinstance(trig, list) or not trig or len(trig) > MAX_TRIGGERS
or not all(isinstance(t, str) and TRIGGER_RE.match(t) for t in trig)):
errors.append(f"{lb}.triggers must be 1..{MAX_TRIGGERS} words matching {TRIGGER_RE.pattern}")
continue
if s.get("guestAllowed") is not None and not isinstance(s["guestAllowed"], bool):
errors.append(f"{lb}.guestAllowed must be true or false")
out.append({"id": sid, "command": cmd, "script": script,
"triggers": list(dict.fromkeys(trig)),
"guestAllowed": s.get("guestAllowed") is True,
"description": str(s.get("description") or "")[:200]})
return out
def summary(manifest: dict[str, Any]) -> list[dict[str, Any]]:
items = []
for s in manifest.get("pathShims") or []:
guests = ", guests' runs included" if s.get("guestAllowed") else ""
items.append({"kind": "pathShim", "privileged": True,
"label": f"Wraps `{s['command']}` in every agent run on the machines its "
f"settings pick{guests}: `{s['command']} "
f"{'|'.join(s['triggers'][:8])}{'|…' if len(s['triggers']) > 8 else ''}` "
f"runs its script `{s['script']}` (operator only)"})
return items
def fingerprint_sig(manifest: dict[str, Any]) -> list | None:
shims = manifest.get("pathShims") or []
if not shims:
return None
return [[s["id"], s["command"], s["script"], list(s["triggers"]), bool(s.get("guestAllowed"))]
for s in shims]
def all_shims(store) -> list[dict[str, Any]]:
"""Every active shim of the owner's plugins, with its plugin's scope (the
harnessHooks settings) — the same shape :mod:`harness_hooks` filters."""
from plugins.harness_hooks import scope_of
out = []
for kind in ("app", "provider", "harness"):
for rec in store.active_by_kind(kind):
mf = rec["manifest"]
shims = mf.get("pathShims") or []
if not shims:
continue
scope = scope_of(mf, rec.get("config"))
for s in shims:
r = {k: v for k, v in s.items() if k != "description"}
r["plugin"] = rec["id"]
r["scope"] = scope
r["script"] = f"{rec['id']}/{s['script']}"
r["_src"] = str(pathlib.Path(rec["dir"] or "") / s["script"])
out.append(r)
out.sort(key=lambda r: (r["plugin"], r["id"]))
return out
def one_per_command(rules: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""One wrapper per command on a machine: the first plugin (by id) of those
that apply there keeps it."""
kept, cmds = [], set()
for r in rules:
if r["command"] not in cmds:
cmds.add(r["command"])
kept.append(r)
return kept