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

258 lines
9.1 KiB
Python

"""Plugin reports — what a plugin's path shim (``pathShims``,
plugins/path_shims.py) filed about a run, out of band (since 2026-11-27, the
``commits`` plugin's git shim).
A shim calls core's ``sidecar/aia_report.py`` ``report(event, summary,
blob)``. It reaches the hub on the transport ``conv add`` uses — on the lab
``POST /api/plugin-reports`` (plugins/hubreports.py, the run's HMAC token), on
a worker a one-shot ``report`` outbox item (``rpt_``) the ``OutboxMirror``
collects — and lands here:
<REPORTS_DIR>/<sessionId>/<pluginId>.jsonl one row per report
<REPORTS_DIR>/<sessionId>/<pluginId>.blobs/<rid>.json its blob, if any
Caps per conversation and plugin: :data:`MAX_REPORTS` rows, :data:`MAX_BYTES`
on disk (rows + blobs) — past them a report is refused. A report id seen
before is a no-op (an outbox item collected twice).
Reads: the plugin's own (``conversations.reports`` — hub/conversations/{cid}/
reports), and the thread's join (:func:`join_thread`): each shell call gets
the summaries filed while it ran — ``[start ts, result ts]`` (now while it
runs) — as ``reports: {<pluginId>: [summary row…]}``, which a tool card's
``match.hasReport`` and its init / update read.
"""
from __future__ import annotations
import datetime as dt
import json
import os
import pathlib
import re
import threading
import time
from typing import Any
REPORTS_DIR = pathlib.Path(os.environ.get("PLUGIN_REPORTS_DIR", "/data/plugin-reports"))
MAX_REPORTS = 2000
MAX_BYTES = 16 * 1024 * 1024
MAX_SUMMARY = 8 * 1024
MAX_BLOB = 160 * 1024
# A report stamped this long before its call's start (clock skew between the
# shim and the transcript writer) or after its result still joins it.
JOIN_SLACK_BEFORE_MS = 1500
JOIN_SLACK_AFTER_MS = 3000
_ID_RE = re.compile(r"^rpt_[0-9a-f]{12}$")
_SID_RE = re.compile(r"^[A-Za-z0-9_-]{8,64}$")
_PLUGIN_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,47}$")
_EVENT_RE = re.compile(r"^[a-z][a-z0-9._-]{0,31}$")
_lock = threading.Lock()
# (sid, plugin) → (mtime_ns, size, rows) — the parsed jsonl, re-read on change.
_cache: dict[tuple[str, str], tuple[int, int, list[dict]]] = {}
_CACHE_MAX = 256
def _dump(v) -> str:
return json.dumps(v, separators=(",", ":"), ensure_ascii=False)
def _dir(sid: str) -> pathlib.Path:
return REPORTS_DIR / sid
def _rows_path(sid: str, plugin: str) -> pathlib.Path:
return _dir(sid) / f"{plugin}.jsonl"
def _blobs_dir(sid: str, plugin: str) -> pathlib.Path:
return _dir(sid) / f"{plugin}.blobs"
def valid(sid: str, plugin: str) -> bool:
return bool(_SID_RE.match(sid or "")) and bool(_PLUGIN_RE.match(plugin or ""))
def _read(sid: str, plugin: str) -> list[dict]:
p = _rows_path(sid, plugin)
try:
st = p.stat()
except OSError:
return []
key = (sid, plugin)
hit = _cache.get(key)
if hit and hit[0] == st.st_mtime_ns and hit[1] == st.st_size:
return hit[2]
rows = []
try:
with p.open(encoding="utf-8") as f:
for line in f:
try:
r = json.loads(line)
except ValueError:
continue
if isinstance(r, dict) and r.get("id"):
rows.append(r)
except OSError:
return []
_cache[key] = (st.st_mtime_ns, st.st_size, rows)
while len(_cache) > _CACHE_MAX:
_cache.pop(next(iter(_cache)))
return rows
def _usage(sid: str, plugin: str) -> int:
n = 0
try:
n += _rows_path(sid, plugin).stat().st_size
except OSError:
pass
try:
for f in _blobs_dir(sid, plugin).iterdir():
n += f.stat().st_size
except OSError:
pass
return n
def clean(rep: Any) -> dict | None:
"""A report as filed (``aia_report.build``'s ``report``) → the row we keep
(+ ``blob``), or None when it is not one."""
if not isinstance(rep, dict):
return None
event, summary, blob = rep.get("event"), rep.get("summary"), rep.get("blob")
if not isinstance(event, str) or not _EVENT_RE.match(event) or not isinstance(summary, dict):
return None
if len(_dump(summary).encode()) > MAX_SUMMARY:
return None
if blob is not None and (not isinstance(blob, dict) or len(_dump(blob).encode()) > MAX_BLOB):
blob, summary = None, {**summary, "blobDropped": True}
try:
ts = int(rep.get("ts") or 0)
except (TypeError, ValueError):
ts = 0
if ts <= 0:
ts = int(time.time() * 1000)
out = {"ts": ts, "event": event, "cwd": str(rep.get("cwd") or "")[:1000],
"pid": rep.get("pid") if isinstance(rep.get("pid"), int) else None,
"summary": summary}
if blob is not None:
out["blob"] = blob
return out
def add(sid: str, plugin: str, rid: str, rep: Any, *, worker: str | None = None) -> str:
"""Store one report: ``"added"``, ``"exists"``, or a refusal
(``"invalid"`` / ``"full"``)."""
if not valid(sid, plugin) or not _ID_RE.match(rid or ""):
return "invalid"
row = clean(rep)
if row is None:
return "invalid"
blob = row.pop("blob", None)
row = {"id": rid, **row, "hasBlob": blob is not None, "worker": worker or None,
"receivedAt": int(time.time() * 1000)}
line = _dump(row) + "\n"
blob_text = _dump(blob) if blob is not None else ""
with _lock:
rows = _read(sid, plugin)
if any(r.get("id") == rid for r in rows):
return "exists"
if len(rows) >= MAX_REPORTS or _usage(sid, plugin) + len(line) + len(blob_text) > MAX_BYTES:
return "full"
d = _dir(sid)
d.mkdir(parents=True, exist_ok=True)
if blob is not None:
bd = _blobs_dir(sid, plugin)
bd.mkdir(exist_ok=True)
tmp = bd / f".{rid}.tmp"
tmp.write_text(blob_text, encoding="utf-8")
os.replace(tmp, bd / f"{rid}.json")
with _rows_path(sid, plugin).open("a", encoding="utf-8") as f:
f.write(line)
return "added"
def public(row: dict) -> dict:
return {k: row.get(k) for k in ("id", "ts", "event", "cwd", "summary", "hasBlob")}
def list_reports(sid: str, plugin: str, since: int = 0) -> list[dict]:
if not valid(sid, plugin):
return []
with _lock:
rows = list(_read(sid, plugin))
return [public(r) for r in sorted(rows, key=lambda r: (r.get("ts") or 0, r["id"]))
if (r.get("ts") or 0) > since]
def blob(sid: str, plugin: str, rid: str) -> dict | None:
if not valid(sid, plugin) or not _ID_RE.match(rid or ""):
return None
try:
return json.loads((_blobs_dir(sid, plugin) / f"{rid}.json").read_text(encoding="utf-8"))
except (OSError, ValueError):
return None
def plugins_of(sid: str) -> list[str]:
"""The plugins that filed reports on this conversation."""
if not _SID_RE.match(sid or ""):
return []
try:
return sorted(p.stem for p in _dir(sid).glob("*.jsonl") if _PLUGIN_RE.match(p.stem))
except OSError:
return []
# ── the thread's join ────────────────────────────────────────────────────────
def _ms(iso: str | None) -> int | None:
if not iso:
return None
try:
t = dt.datetime.fromisoformat(str(iso).replace("Z", "+00:00"))
except ValueError:
return None
if t.tzinfo is None:
t = t.replace(tzinfo=dt.timezone.utc)
return int(t.timestamp() * 1000)
def join_thread(sid: str | None, thread: list[dict], *, active: set[str] | None = None,
now_ms: int | None = None) -> dict[int, dict]:
"""``{index: item + reports}`` for the shell calls of ``thread`` that
reports were filed during — new dicts, the parsed (cached) items are never
touched. ``active``: the plugins whose reports count (None = any).
A report goes to the call whose window holds its ``ts`` — the latest one
to start when calls overlap (parallel shells)."""
if not sid:
return {}
plugins = [p for p in plugins_of(sid) if active is None or p in active]
if not plugins:
return {}
now_ms = now_ms if now_ms is not None else int(time.time() * 1000)
calls: list[tuple[int, int, int]] = [] # (start, end, index)
for i, it in enumerate(thread):
if it.get("kind") != "tool_use" or it.get("name") != "shell":
continue
start = _ms(it.get("ts"))
if start is None:
continue
dur = it.get("durationMs")
end = start + int(dur) if isinstance(dur, (int, float)) and dur >= 0 else now_ms
calls.append((start - JOIN_SLACK_BEFORE_MS, end + JOIN_SLACK_AFTER_MS, i))
if not calls:
return {}
got: dict[int, dict[str, list[dict]]] = {}
for plugin in plugins:
for r in list_reports(sid, plugin):
ts = r.get("ts") or 0
hit = None
for start, end, i in calls:
if start <= ts <= end and (hit is None or start > hit[0]):
hit = (start, i)
if hit is not None:
got.setdefault(hit[1], {}).setdefault(plugin, []).append(r)
return {i: {**thread[i], "reports": reps} for i, reps in got.items()}