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

167 lines
6.9 KiB
Python

"""Plugin reports on the hub (plugins/reports.py): where they come in, and the
``conversations.reports`` capability that reads them back (since 2026-11-27).
In:
* ``POST /api/plugin-reports`` — a lab run's ``aia_report.py`` (or the lab
sidecar draining its spool): ``{id, sessionId, plugin, report, token}``.
The route is public at the gate; the ``token`` is the run's own, an HMAC of
its session id under the host sidecar's bearer (``sidecar/path_shims.py``
``report_token``) — so a run files reports on its own conversation only,
and a guest's sandboxed run needs no host credential.
* a worker's ``report`` outbox item (``OutboxMirror`` → :func:`outbox_ingest`),
allowed like any other (a guest's computer: its own sessions only).
Either way the plugin must be one of the owner's active plugins that declares
``pathShims`` (the shims are its code). A stored report publishes SSE
``transcript`` for the conversation, so its cards and tabs refresh.
Out (capability ``conversations.reports`` — the caller's own conversations, a
guest's theirs; no operator approval: it only reads what the plugin wrote):
* ``GET …/plugins/{pid}/hub/conversations/{cid}/reports?since=<ts>`` →
``{sessionId, conversationId, worker, reports: [{id, ts, event, cwd,
summary, hasBlob}]}`` — the calling plugin's only, oldest first;
* ``GET …/plugins/{pid}/hub/conversations/{cid}/reports/{rid}/blob`` → the
blob (404 none).
"""
from __future__ import annotations
import hashlib
import hmac
from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse
from starlette.concurrency import run_in_threadpool
from plugins import reports
router = APIRouter(include_in_schema=False)
CAP = "conversations.reports"
MAX_BODY = 200 * 1024
def token_ok(sid: str, token: str) -> bool:
from core.config import SIDECAR_TOKEN
if not SIDECAR_TOKEN or not sid or not token:
return False
want = hmac.new(SIDECAR_TOKEN.encode(), f"aia-report:{sid}".encode(),
hashlib.sha256).hexdigest()[:40]
return hmac.compare_digest(want, str(token))
def _shim_plugin(deps, pid: str) -> bool:
"""Is ``pid`` one of the owner's active plugins with path shims?"""
from plugins.store import OWNER_UID
try:
rec, _g, _m = deps.plugin_store.resolve_active_for_caller(OWNER_UID, pid)
except Exception: # noqa: BLE001
return False
return bool(rec and (rec.get("manifest") or {}).get("pathShims"))
def _publish(deps, sid: str) -> None:
from conversations.catalog import _conv_ids_by_session
try:
cid = _conv_ids_by_session(deps).get(sid)
except Exception: # noqa: BLE001
cid = None
ids = [cid] if cid else []
deps.hub.publish({"type": "transcript", "ids": ids, "sessionId": sid,
"reports": True})
def ingest(deps, payload: dict, *, worker: str | None = None) -> dict:
"""Store one report payload (``aia_report.build``'s shape)."""
sid = str(payload.get("sessionId") or "")
pid = str(payload.get("plugin") or "")
rid = str(payload.get("id") or "")
if not reports.valid(sid, pid):
return {"failed": True, "error": "bad sessionId or plugin"}
if not _shim_plugin(deps, pid):
return {"failed": True, "error": f"plugin {pid!r} files no reports here"}
got = reports.add(sid, pid, rid, payload.get("report"), worker=worker)
if got == "added":
_publish(deps, sid)
if got in ("added", "exists"):
return {"id": rid, "ok": True, **({"existing": True} if got == "exists" else {})}
return {"failed": True, "error": f"report {got}"}
def outbox_ingest(deps, d: dict) -> dict:
"""A worker's ``report`` outbox item (``d`` = its payload + ``worker``)."""
return ingest(deps, d, worker=str(d.get("worker") or "") or None)
@router.post("/api/plugin-reports")
async def post_report(request: Request):
"""A lab run's report (see the module doc). Public at the gate: the body's
``token`` is the credential."""
try:
if int(request.headers.get("content-length") or 0) > MAX_BODY:
return JSONResponse({"detail": "report too big"}, status_code=413)
except ValueError:
return JSONResponse({"detail": "bad length"}, status_code=400)
try:
body = await request.json()
except ValueError:
return JSONResponse({"detail": "bad json"}, status_code=400)
if not isinstance(body, dict):
return JSONResponse({"detail": "bad body"}, status_code=400)
if not token_ok(str(body.get("sessionId") or ""), str(body.get("token") or "")):
return JSONResponse({"detail": "bad report token"}, status_code=403)
deps = request.app.state.ai
out = await run_in_threadpool(ingest, deps, body)
if out.get("failed"):
return JSONResponse({"detail": out.get("error")}, status_code=400)
return out
# ── conversations.reports ────────────────────────────────────────────────────
def _conversation(request: Request, pid: str, cid: str):
"""(deps, sessionId, conversation id, worker) of a conversation the caller
may read, or an error response."""
from plugins.hubbridge import _check_cap
from plugins.hubchecks import locate, visible_to
from plugins.proxyroutes import _error
deps, who, _rec, err = _check_cap(request, pid, CAP)
if err:
return None, err
hit = locate(deps, cid)
if hit is None:
# A run just spawned: the hub knows its session id from its meta only.
meta = deps.meta_store.peek(cid) if reports.valid(cid, pid) else None
if not meta or not visible_to(who, meta):
return None, _error(404, "conversation not found", "not_found")
return (deps, cid, None, meta.get("worker") or meta.get("workerSource")), None
real, _path, s = hit
meta = deps.meta_store.peek(s["sessionId"]) or {}
if not visible_to(who, meta):
return None, _error(404, "conversation not found", "not_found")
return (deps, s["sessionId"], real, meta.get("worker") or meta.get("workerSource")), None
@router.get("/proxy/tools/plugins/{pid}/hub/conversations/{cid}/reports")
async def hub_reports(pid: str, cid: str, request: Request, since: int = 0):
got, err = _conversation(request, pid, cid)
if err:
return err
_deps, sid, real, worker = got
rows = await run_in_threadpool(reports.list_reports, sid, pid, since)
return {"sessionId": sid, "conversationId": real, "worker": worker, "reports": rows}
@router.get("/proxy/tools/plugins/{pid}/hub/conversations/{cid}/reports/{rid}/blob")
async def hub_report_blob(pid: str, cid: str, rid: str, request: Request):
from plugins.proxyroutes import _error
got, err = _conversation(request, pid, cid)
if err:
return err
_deps, sid, _real, _worker = got
data = await run_in_threadpool(reports.blob, sid, pid, rid)
if data is None:
return _error(404, "no blob", "not_found")
return data