Files

439 lines
17 KiB
Python

"""Many plugin reads in one request — what the conversation's Details drawer
asks when it opens (since 2026-11-28, the details-panel load work).
Each ``conversation.details`` slot used to load its document, then post its
own ``readOnly`` action from inside its frame: a dozen frames, a dozen HTML
fetches and a dozen action requests queued behind the thread's read on a busy
hub. Two endpoints make that two requests:
* ``POST|GET /api/plugins/batch-read`` (:func:`batch_read`) — up to
:data:`MAX_ITEMS` ``readOnly`` actions of any active plugins, run at once
(at most :data:`BATCH_CONCURRENCY` per batch, so one batch never takes every
``REQUEST_SCRIPT_SLOTS``), each through :mod:`plugins.singleflight` (a
header chip and the drawer asking the same thing share one handler run),
each answered on its own — one failing item never fails the batch. A
success is kept a few seconds (:class:`ReadCache`, shared with single
``readOnly`` action calls via :func:`run_read_cached`): 30 s for a finished
conversation's read, 3 s for a running one's, 5 s for a read naming no
conversation — and keyed on a stamp of the conversation's summary + meta,
so a new turn misses at once. ``fresh`` skips it; any write to the plugin
(install, reload, config, secret, grant, ``hub/changed``) drops it
(:func:`invalidate`).
* ``GET /api/plugins/ui-bundle?where=&kinds=`` (:func:`ui_bundle`) — every
active slot document for one or more ``where`` places and/or UI kind documents
(``toolCard``, ``fence``, ``preview``, ``overlay``), in one body, ``ETag``'d
on its files.
Authorization is :func:`resolve_call`, the one ``_invoke_action`` uses.
"""
from __future__ import annotations
import asyncio
import hashlib
import json
import pathlib
import stat
import threading
import time
from collections import OrderedDict
from collections.abc import Sequence
from dataclasses import dataclass
from typing import Any
from fastapi import HTTPException
from starlette.concurrency import run_in_threadpool
from plugins import singleflight
from plugins.runner import ActionError, requester_context, run_script
from plugins.store import OWNER_UID
MAX_ITEMS = 32
BODY_MAX = 32 * 1024
GET_ITEMS_MAX = 16 * 1024
PAYLOAD_MAX = 8 * 1024
KEY_MAX = 128
BATCH_CONCURRENCY = 8
UI_DOC_MAX = 512 * 1024
BUNDLE_KINDS: dict[str, str] = {
"toolCard": "toolCards",
"fence": "fences",
"preview": "filePreviews",
"overlay": "overlays",
}
TTL_FINISHED = 30.0
TTL_RUNNING = 3.0
TTL_NO_CONVERSATION = 5.0
_CONV_KEYS = ("conversationId", "sessionId", "sid")
def _uid(caller) -> str:
return OWNER_UID if caller.is_owner else caller.id
# ── one action call, resolved as the caller ───────────────────────────────────
@dataclass
class Call:
uid: str
run_uid: str
pid: str
action: str
rec: dict[str, Any]
act: dict[str, Any]
grant: dict[str, Any] | None
using_own: bool
requester: dict[str, Any] | None
context: dict[str, Any] | None
def run(self, deps, payload: dict[str, Any]):
return run_in_threadpool(
run_script, deps, deps.plugin_store, self.run_uid, self.rec, self.act["script"],
payload=payload,
timeout_sec=int(self.act.get("timeoutSec") or 30),
grant=self.grant,
using_own_secret=self.using_own,
requester=self.requester,
context=self.context,
)
def flight_key(self, payload: dict[str, Any]) -> tuple:
# The same key ``_invoke_action`` shares a read under.
return singleflight.key_of(self.uid, self.run_uid, self.pid, self.action, payload=payload)
def resolve_call(deps, caller, pid: str, action: str, *, read: bool) -> Call:
"""Who runs ``pid``'s ``action`` for ``caller`` and with what — or the
HTTPException ``/api/plugins/{pid}/actions/{action}`` answers."""
uid = _uid(caller)
rec, grant, is_managed = deps.plugin_store.resolve_active_for_caller(uid, pid)
if not rec:
raise HTTPException(404, f"plugin '{pid}' not active")
act = (rec["manifest"].get("actions") or {}).get(action)
if not act:
raise HTTPException(404, f"action '{action}' not declared")
from plugins.endpoints import endpoint_actions
if action in endpoint_actions(rec["manifest"]):
# An endpoint's action answers HTTP only (plugins/endpoints.py): its
# payload is the host's word on who is asking — never a caller's.
raise HTTPException(403, {"message": f"action '{action}' answers HTTP only",
"kind": "endpoint_only"})
if read and not act.get("readOnly"):
raise HTTPException(405, f"action '{action}' is not read-only: POST it")
if act.get("ownerOnly") and not caller.is_owner:
raise HTTPException(403, f"action '{action}' is owner-only")
using_own = deps.plugin_store.has_user_override_secret(uid, pid, rec["manifest"]) if is_managed else False
run_uid = uid
requester = None
if act.get("runAs") == "owner" and is_managed and not caller.is_owner:
requester = requester_context(deps, uid, grant)
run_uid = OWNER_UID
# The owner looking through a guest's eyes: the plugin can keep a preview
# from counting as the guest's own visit (What's new's seen marks).
context = {"impersonatedBy": caller.impersonator} if caller.impersonator else None
return Call(uid, run_uid, pid, action, rec, act, grant, using_own, requester, context)
# ── the short read cache ──────────────────────────────────────────────────────
class ReadCache:
"""A bounded LRU of read results, each with its expiry. A per-plugin
generation makes :meth:`invalidate` win over a read still in flight: a
result whose plugin changed while it ran is not kept."""
def __init__(self, max_entries: int = 512):
self.max = max_entries
self._lock = threading.Lock()
self._data: OrderedDict[tuple, tuple[float, str, Any]] = OrderedDict()
self._gen: dict[str, int] = {}
self._all = 0
def generation(self, pid: str) -> tuple[int, int]:
with self._lock:
return self._all, self._gen.get(pid, 0)
def get(self, key: tuple) -> tuple[bool, Any]:
now = time.monotonic()
with self._lock:
hit = self._data.get(key)
if not hit:
return False, None
if hit[0] <= now:
self._data.pop(key, None)
return False, None
self._data.move_to_end(key)
return True, hit[2]
def put(self, key: tuple, pid: str, value: Any, ttl: float, gen: tuple[int, int]) -> None:
with self._lock:
if (self._all, self._gen.get(pid, 0)) != gen:
return
self._data[key] = (time.monotonic() + ttl, pid, value)
self._data.move_to_end(key)
while len(self._data) > self.max:
self._data.popitem(last=False)
def invalidate(self, pid: str | None = None) -> None:
with self._lock:
if pid is None:
self._all += 1
self._data.clear()
return
self._gen[pid] = self._gen.get(pid, 0) + 1
for k in [k for k, v in self._data.items() if v[1] == pid]:
self._data.pop(k, None)
def __len__(self) -> int:
return len(self._data)
CACHE = ReadCache()
def invalidate(pid: str | None = None) -> None:
"""Drop the cached reads of ``pid`` (every plugin's when None)."""
CACHE.invalidate(pid)
def conversation_stamp(deps, payload: dict[str, Any]) -> tuple[tuple, float]:
"""``(stamp, ttl)`` of the conversation a read names: a stamp of its
summary + meta (a new turn, a new stamp), the TTL its state allows."""
raw = next((payload[k] for k in _CONV_KEYS if isinstance(payload.get(k), str) and payload[k]), None)
if raw is None:
return (), TTL_NO_CONVERSATION
try:
from plugins.hubchecks import locate
hit = locate(deps, raw)
except Exception: # noqa: BLE001 — a cache key never fails a read
hit = None
if not hit:
return ("?", raw), TTL_RUNNING
_cid, _path, s = hit
sid = s.get("sessionId") or raw
try:
meta = deps.meta_store.peek(sid) or {}
except Exception: # noqa: BLE001
meta = {}
try:
from core import liveruns
live = liveruns.alive(sid)
except Exception: # noqa: BLE001
live = False
running = bool(live or meta.get("state") == "running")
stamp = (s.get("endedAt"), s.get("turns", s.get("userTurns")), s.get("cost"), id(meta), running)
return stamp, (TTL_RUNNING if running else TTL_FINISHED)
def _canon(payload: Any) -> str:
return json.dumps(payload, sort_keys=True, separators=(",", ":"), default=str)
# ── the batch ─────────────────────────────────────────────────────────────────
def parse_items(raw: Any) -> list[dict[str, Any]]:
"""The validated items of a batch body (400 on a malformed one)."""
if not isinstance(raw, list):
raise HTTPException(400, "items must be a list")
if len(raw) > MAX_ITEMS:
raise HTTPException(400, f"at most {MAX_ITEMS} items")
out: list[dict[str, Any]] = []
keys: set[str] = set()
for i, it in enumerate(raw):
if not isinstance(it, dict):
raise HTTPException(400, f"items[{i}] must be an object")
key, pid, action = it.get("key"), it.get("pluginId"), it.get("action")
if not isinstance(key, str) or not 1 <= len(key) <= KEY_MAX:
raise HTTPException(400, f"items[{i}].key must be 1..{KEY_MAX} characters")
if key in keys:
raise HTTPException(400, f"items[{i}].key repeats {key!r}")
if not isinstance(pid, str) or not pid or not isinstance(action, str) or not action:
raise HTTPException(400, f"items[{i}] needs pluginId and action")
payload = it.get("payload")
if payload is None:
payload = {}
if not isinstance(payload, dict):
raise HTTPException(400, f"items[{i}].payload must be a JSON object")
if len(_canon(payload).encode("utf-8")) > PAYLOAD_MAX:
raise HTTPException(413, f"items[{i}].payload too large")
keys.add(key)
out.append({"key": key, "pluginId": pid, "action": action, "payload": payload,
"fresh": bool(it.get("fresh"))})
return out
def _error(status: int, err: Any) -> dict[str, Any]:
if isinstance(err, dict):
err = err.get("message") or json.dumps(err)
return {"ok": False, "status": status, "error": str(err)}
async def run_read_cached(
deps,
call: Call,
payload: dict[str, Any],
*,
fresh: bool = False,
gate: asyncio.Semaphore | None = None,
) -> tuple[Any, bool, int]:
"""Run a ``readOnly`` action through :data:`CACHE` and :mod:`plugins.singleflight`,
returning ``(data, cached, elapsed_ms)``. Shared by ``batch-read`` and
single ``/api/plugins/{pid}/actions/{action}`` reads."""
t0 = time.monotonic()
fp = call.rec.get("fingerprint") or ""
try:
stamp, ttl = await run_in_threadpool(conversation_stamp, deps, payload)
except Exception: # noqa: BLE001
stamp, ttl = ("!",), 0.0
ckey = (call.uid, call.run_uid, call.pid, fp, call.action, _canon(payload), stamp,
(call.context or {}).get("impersonatedBy"))
if not fresh:
hit, value = CACHE.get(ckey)
if hit:
return value, True, max(0, round((time.monotonic() - t0) * 1000))
gen = CACHE.generation(call.pid)
async def _run():
return await singleflight.shared(call.flight_key(payload), lambda: call.run(deps, payload))
if gate is not None:
async with gate:
data = await _run()
else:
data = await _run()
if ttl > 0:
CACHE.put(ckey, call.pid, data, ttl, gen)
return data, False, max(0, round((time.monotonic() - t0) * 1000))
async def _one(deps, caller, item: dict[str, Any], fresh: bool, gate: asyncio.Semaphore) -> dict[str, Any]:
payload = item["payload"]
try:
call = resolve_call(deps, caller, item["pluginId"], item["action"], read=True)
except HTTPException as e:
if e.status_code == 405:
return _error(405, "action is not read-only")
return _error(e.status_code, e.detail)
try:
data, cached, elapsed_ms = await run_read_cached(
deps, call, payload, fresh=fresh or item["fresh"], gate=gate,
)
except ActionError as e:
return _error(e.status, e.message)
except HTTPException as e:
return _error(e.status_code, e.detail)
except Exception as e: # noqa: BLE001 — one item never fails the batch
return _error(500, f"{type(e).__name__}: {e}")
return {"ok": True, "data": data, "cached": cached, "ms": elapsed_ms}
async def batch_read(deps, caller, items: list[dict[str, Any]], *, fresh: bool = False) -> dict[str, Any]:
"""``{"results": {key: {ok, data, cached, ms} | {ok: false, status, error}}}``."""
gate = asyncio.Semaphore(BATCH_CONCURRENCY)
answers = await asyncio.gather(*(_one(deps, caller, it, fresh, gate) for it in items))
return {"results": {it["key"]: a for it, a in zip(items, answers)}}
# ── every slot / UI document of one or more places / kinds ───────────────────
def etag_matches(if_none_match: str | None, tag: str) -> bool:
"""True when an ``If-None-Match`` header names ``tag`` (strong, weak, list, or ``*``)."""
if not if_none_match:
return False
for part in if_none_match.split(","):
t = part.strip()
if t.startswith(("W/", "w/")):
t = t[2:].strip()
t = t.strip('"')
if t == tag or t == "*":
return True
return False
def _active_pids(deps, caller) -> list[str]:
"""The caller's active plugins in ``GET /api/plugins/ui``'s order: their
own, then (a guest) the managed ones granted to them."""
uid = _uid(caller)
store = deps.plugin_store
pids = [pid for pid, _mf, _cfg in store.active_manifests(uid)]
if not caller.is_owner:
seen = set(pids)
for rec in store.managed_plugins():
if rec["id"] not in seen and store.effective_grant(caller.id, rec["id"], rec["manifest"]).get("enabled"):
pids.append(rec["id"])
return pids
def _parse_tokens(raw: str | Sequence[str]) -> list[str]:
items = raw.split(",") if isinstance(raw, str) else raw
return list(dict.fromkeys(str(x).strip() for x in items if str(x).strip()))
def ui_bundle(
deps,
caller,
where: str | Sequence[str] = "",
if_none_match: str | None = None,
*,
kinds: str | Sequence[str] = "",
) -> tuple[str, dict[str, Any] | None]:
"""``(version, {where, version, docs, ...})`` — every active UI document
for the requested slot places (keyed ``"<pid>:<slot>"``) and/or UI kinds
(keyed ``"<kind>:<pid>:<subId>"``). ``version`` hashes the file identities
(the ETag); the body is None when ``if_none_match`` matches (nothing is read)."""
uid = _uid(caller)
places = _parse_tokens(where)
kind_list = _parse_tokens(kinds)
place_set = set(places)
files: list[tuple[str, pathlib.Path]] = []
ident: list[tuple[str, str, str, str, int, int]] = []
def _collect(root: pathlib.Path, pid: str, fp: str, kind: str, sub_id: str,
rel: Any, doc_key: str) -> None:
if not rel:
return
target = (root / str(rel)).resolve()
try:
target.relative_to(root)
st = target.stat()
except (ValueError, OSError):
return
if not stat.S_ISREG(st.st_mode):
return
files.append((doc_key, target))
ident.append((kind, pid, fp, sub_id, st.st_mtime_ns, st.st_size))
for pid in _active_pids(deps, caller):
rec, _grant, _managed = deps.plugin_store.resolve_active_for_caller(uid, pid)
if not rec:
continue
ui = rec["manifest"].get("ui") or {}
root = pathlib.Path(rec["dir"]).resolve()
fp = rec.get("fingerprint") or ""
if place_set:
for sl in ui.get("slots") or []:
if sl.get("where") not in place_set:
continue
if not caller.is_owner and sl.get("where") == "composer.send" and not sl.get("guestAllowed"):
continue
_collect(root, pid, fp, "slot", sl["id"], sl.get("html"), f"{pid}:{sl['id']}")
for kind in kind_list:
arr_key = BUNDLE_KINDS.get(kind)
if not arr_key:
continue
for item in ui.get(arr_key) or []:
_collect(root, pid, fp, kind, item["id"], item.get("html"), f"{kind}:{pid}:{item['id']}")
spec = {"places": sorted(places), "kinds": sorted(kind_list), "files": sorted(ident)}
version = hashlib.sha256(repr(spec).encode()).hexdigest()[:16]
if etag_matches(if_none_match, version):
return version, None
docs: dict[str, str] = {}
for key, target in files:
try:
docs[key] = target.read_text(encoding="utf-8", errors="replace")[:UI_DOC_MAX]
except OSError:
continue
body: dict[str, Any] = {"where": ",".join(places), "version": version, "docs": docs}
if kind_list:
body["kinds"] = ",".join(kind_list)
return version, body