Files

204 lines
8.0 KiB
Python

"""Two generic composer hooks a plugin can provide — the core knows nothing of
what they are for (the fresh-context plugin is the first to use both).
``provides: {"composer.beforeSend": "<action>"}`` — asked by
``POST /api/plugins/composer/before-send`` before a composer sends (the reply
box, on an idle turn it would launch). Each enabled, approved plugin active for
the caller (their own installs; for a guest, the owner's managed plugins
granted to them — the same lookup as ``plugins/launch.py``) runs that action
**as the caller** with ``{"trigger": "composer.beforeSend", **payload}``, in
plugin id order. The first answer that isn't ``proceed`` wins:
* ``{"verdict": "proceed"}`` — send as it is;
* ``{"verdict": "modify", "resume": {"compact": {"model", "instructions"}}}`` —
send, with that patch on the resume (a compaction first);
* ``{"verdict": "modal", "slot": "<one of its app.modal slots>", "init": {…}}``
— the app opens that modal and acts on its result (``cancel`` / ``proceed``
with an optional ``resume``).
Anything malformed, a failed or slow action, or no provider: ``proceed``. A
send is never held up by a broken plugin.
``provides: {"runs.compact": "<action>"}`` — :func:`compact_spec`: what a
compaction before a reply runs on and keeps, when a send asks for one without
naming it (``/api/resume`` ``fresh: true`` — ``ai-agent send --fresh``, a
guest continuing a terminal session). Answers ``{"model", "instructions"}``.
"""
from __future__ import annotations
import json
import logging
import re
from typing import Any
from plugins.store import OWNER_UID
log = logging.getLogger(__name__)
BEFORE_SEND = "composer.beforeSend"
COMPACT = "runs.compact"
MAX_INIT = 16 * 1024
MAX_MODEL = 120
MAX_INSTRUCTIONS = 8000
TIMEOUT_S = 8
VERDICTS = ("proceed", "modify", "modal")
_SLOT_RE = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_-]{0,47}$")
_MODEL_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:/@+\[\]-]{0,119}$")
PROCEED: dict[str, Any] = {"verdict": "proceed"}
def _uid_of(caller: Any) -> str:
"""The plugin-store user a caller (a ``Caller``, a guest id, or None for
the owner) runs plugins as."""
if caller is None:
return OWNER_UID
if isinstance(caller, str):
return caller or OWNER_UID
return OWNER_UID if getattr(caller, "is_owner", False) else str(getattr(caller, "id", "") or OWNER_UID)
def _context(caller: Any) -> dict | None:
imp = getattr(caller, "impersonator", None)
return {"impersonatedBy": imp} if imp else None
def clean_compact(raw: Any) -> dict[str, str] | None:
"""``{"model", "instructions"}`` as the sidecar may take it, or None."""
if not isinstance(raw, dict):
return None
model, text = raw.get("model"), raw.get("instructions")
if not isinstance(model, str) or not _MODEL_RE.match(model.strip()) or len(model) > MAX_MODEL:
return None
if not isinstance(text, str) or not text.strip() or len(text) > MAX_INSTRUCTIONS:
return None
return {"model": model.strip(), "instructions": text}
def clean_resume(raw: Any) -> dict[str, Any] | None:
"""A ``resume`` patch: only a valid ``compact`` survives."""
if not isinstance(raw, dict):
return None
c = clean_compact(raw.get("compact"))
return {"compact": c} if c else None
def _modal_slots(rec: dict[str, Any]) -> set[str]:
mf = rec.get("manifest") or {}
return {s.get("id") for s in ((mf.get("ui") or {}).get("slots") or [])
if isinstance(s, dict) and s.get("where") == "app.modal"}
def clean_verdict(rec: dict[str, Any], raw: Any) -> dict[str, Any]:
"""A provider's answer as the app may act on it; ``proceed`` for anything
it may not (an unknown verdict, a slot that isn't one of its modals, an
init over 16 KB, a ``modify`` with nothing valid in it)."""
if not isinstance(raw, dict):
return dict(PROCEED)
verdict = raw.get("verdict")
pid = rec.get("id")
if verdict == "modify":
resume = clean_resume(raw.get("resume"))
if not resume:
log.warning("composer.beforeSend: %s's modify carries no valid resume", pid)
return dict(PROCEED)
return {"verdict": "modify", "resume": resume, "pluginId": pid}
if verdict == "modal":
slot = raw.get("slot")
if not isinstance(slot, str) or not _SLOT_RE.match(slot) or slot not in _modal_slots(rec):
log.warning("composer.beforeSend: %s answered slot %r, not one of its app.modal slots",
pid, slot)
return dict(PROCEED)
init = raw.get("init") if raw.get("init") is not None else {}
if not isinstance(init, dict):
return dict(PROCEED)
try:
if len(json.dumps(init)) > MAX_INIT:
log.warning("composer.beforeSend: %s's init is over 16 KB", pid)
return dict(PROCEED)
except (TypeError, ValueError):
return dict(PROCEED)
return {"verdict": "modal", "pluginId": pid, "slot": slot, "init": init}
return dict(PROCEED)
def _clean_payload(payload: Any) -> dict[str, Any]:
"""What the composer sent, kept small and JSON (never the prompt text —
the composers don't send it, and it would be dropped here)."""
if not isinstance(payload, dict):
return {}
out: dict[str, Any] = {}
for k, v in payload.items():
if k in ("prompt", "text") or not isinstance(k, str) or len(k) > 48:
continue
out[k] = v
try:
if len(json.dumps(out)) > 32 * 1024:
out.pop("lastMessages", None)
except (TypeError, ValueError):
return {}
return out
def _run(deps, caller: Any, key: str, payload: dict[str, Any]):
"""Yield ``(rec, answer)`` for each active provider of ``key``, run as the
caller; a failed one is skipped."""
from plugins.runner import run_script
from plugins.waiting import _providers_for
uid = _uid_of(caller)
context = _context(caller)
found = sorted(_providers_for(deps, uid, key), key=lambda p: p[0].get("id") or "")
for rec, grant in found:
mf = rec.get("manifest") or {}
act = (mf.get("actions") or {}).get((mf.get("provides") or {}).get(key) or "")
if not act:
continue
try:
raw = run_script(deps, deps.plugin_store, uid, rec, act["script"], payload=payload,
timeout_sec=min(TIMEOUT_S, int(act.get("timeoutSec") or TIMEOUT_S)),
grant=grant, context=context)
except Exception as e: # noqa: BLE001 — a broken plugin never blocks a send
log.warning("%s plugin %s failed: %s", key, rec.get("id"), e)
continue
yield rec, raw
def before_send(deps, caller: Any, payload: dict) -> dict[str, Any]:
"""The first non-``proceed`` verdict of the caller's ``composer.beforeSend``
providers, else ``{"verdict": "proceed"}``."""
body = {"trigger": BEFORE_SEND, **_clean_payload(payload)}
try:
for rec, raw in _run(deps, caller, BEFORE_SEND, body):
v = clean_verdict(rec, raw)
if v["verdict"] != "proceed":
return v
except Exception as e: # noqa: BLE001
log.warning("composer.beforeSend failed: %s", e)
return dict(PROCEED)
def has_provider(deps, caller: Any, key: str) -> bool:
from plugins.waiting import _providers_for
try:
return bool(_providers_for(deps, _uid_of(caller), key))
except Exception: # noqa: BLE001
return False
def compact_spec(deps, caller: Any, sid: str, own_model: str | None) -> dict[str, str] | None:
"""The ``runs.compact`` provider's compaction for session ``sid`` (run as
the caller), or None when no provider answers a valid one."""
body = {"trigger": COMPACT, "sessionId": sid, "ownModel": own_model}
try:
for _rec, raw in _run(deps, caller, COMPACT, body):
c = clean_compact(raw if not (isinstance(raw, dict) and "compact" in raw)
else raw.get("compact"))
if c:
return c
except Exception as e: # noqa: BLE001
log.warning("runs.compact failed: %s", e)
return None