Speed - seed_registry.effective() cached the "any provider plugin active?" check on the plugin store's version: it deep-copied all 46 manifests on every price lookup (9.4 ms → 8 µs per rates_for) — half the hub's CPU, and what made Graph / Goals / Plan usage bridges take 17–180 s. - GET /api/plugins/ui: the slim list every page reads (UI descriptors, provides, each active plugin's glyph + config), a few KB instead of the 253 KB full list, which is now for Settings → Plugins only. - Identical readOnly actions in flight share one handler run (plugins/singleflight.py). - composer.shortcuts / composer.mode are stale-while-revalidate (plugins/swr.py); inbox.waiting stays fresh but concurrent calls share one run, auto-archive reuses a ≤ 30 s answer; provider lookups copy only the matching records (store.active_providing / active_ids). - aiAgentPlugin.query(): host-kept reads — the last answer at once (own IndexedDB store, not busted per deploy), then the fresh one; learned preload starts a page's reads as its route mounts; UI documents kept the same way. UI - The page's subtitle, buttons and a refresh that spins while its reads run live in the app's header (setHeader / onHeaderAction / onRefresh); the frame is borderless across the content area; a skeleton (after 150 ms) holds its place until the frame painted, then it fades in. - A UI kit (aia-* classes, the app's font and tokens) injected into every plugin frame. - Dashboards / Files nav: plugin pages in the same rearrangeable list, with the plugin's description as subtitle. - Mock: a demo plugin page (/plugins/demo/board?mock=1). Docs: docs/plugins.md → "Pages that feel native: reads, header, kit". Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
146 lines
5.5 KiB
Python
146 lines
5.5 KiB
Python
"""Composer prompt shortcuts contributed by live plugins
|
|
(``provides: {"composer.shortcuts": "<action>"}``).
|
|
|
|
Additive to core prompt shortcuts: each enabled, approved plugin active for the
|
|
caller that declares ``provides.composer.shortcuts`` runs its action (cached
|
|
per caller + plugin fingerprint + config, invalidated on plugin mutations) and
|
|
returns a list of declarative ``PromptShortcut`` objects rendered natively by
|
|
the core composer's ``RichInput`` with zero iframe latency.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import json
|
|
import logging
|
|
from typing import Any
|
|
|
|
from plugins.store import OWNER_UID
|
|
from plugins.swr import SWRCache
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
PROVIDES = "composer.shortcuts"
|
|
TTL_SECS = 60.0
|
|
# Past the TTL the last answer is still served (the plugin runs again behind
|
|
# it) for this long; only an older or missing one makes the composer wait.
|
|
MAX_STALE_SECS = 3600.0
|
|
|
|
_cache = SWRCache(TTL_SECS, MAX_STALE_SECS, name="composer-shortcuts")
|
|
|
|
|
|
def invalidate(pid: str | None = None) -> None:
|
|
"""Drop cached shortcuts (all, or for one plugin id)."""
|
|
if pid is None:
|
|
_cache.clear()
|
|
else:
|
|
prefix = f":{pid}@"
|
|
_cache.drop(lambda k: prefix in k)
|
|
|
|
|
|
def _providers_for(deps, uid: str) -> list[tuple[dict[str, Any], dict[str, Any] | None]]:
|
|
store = getattr(deps, "plugin_store", None)
|
|
if store is None:
|
|
return []
|
|
try:
|
|
out: list[tuple[dict[str, Any], dict[str, Any] | None]] = [
|
|
(rec, None) for rec in store.active_providing(uid, PROVIDES)]
|
|
except Exception:
|
|
out = []
|
|
seen = {rec["id"] for rec, _ in out}
|
|
if uid != OWNER_UID:
|
|
for rec in store.managed_plugins():
|
|
pid = rec["id"]
|
|
if pid in seen:
|
|
continue
|
|
mf = rec.get("manifest") or {}
|
|
act = (mf.get("provides") or {}).get(PROVIDES)
|
|
if not (act and act in (mf.get("actions") or {})):
|
|
continue
|
|
grant = store.effective_grant(uid, pid, mf)
|
|
if grant.get("enabled"):
|
|
seen.add(pid)
|
|
out.append((rec, grant))
|
|
return out
|
|
|
|
|
|
def _cache_key(uid: str, rec: dict[str, Any], grant: dict[str, Any] | None) -> str:
|
|
cfg = json.dumps({"c": rec.get("config") or {}, "g": (grant or {}).get("config") or {}}, sort_keys=True)
|
|
ch = hashlib.sha256(cfg.encode("utf-8")).hexdigest()[:12]
|
|
return f"{uid}:{rec['id']}@{rec.get('fingerprint') or ''}:{ch}"
|
|
|
|
|
|
def _clean_shortcuts(pid: str, raw: Any) -> list[dict[str, Any]]:
|
|
items = raw.get("shortcuts") if isinstance(raw, dict) else None
|
|
if not isinstance(items, list):
|
|
return []
|
|
out: list[dict[str, Any]] = []
|
|
for sc in items[:24]:
|
|
if not isinstance(sc, dict):
|
|
continue
|
|
sid = str(sc.get("id") or "").strip()[:64]
|
|
label = str(sc.get("label") or "").strip()[:60]
|
|
guideline = str(sc.get("guideline") or "").strip()[:2000]
|
|
if not sid or not label or not guideline:
|
|
continue
|
|
entry: dict[str, Any] = {
|
|
"id": sid,
|
|
"label": label,
|
|
"icon": str(sc.get("icon") or "Sparkles")[:48],
|
|
"guideline": guideline,
|
|
"defaultOn": bool(sc.get("defaultOn", False)),
|
|
"shared": bool(sc.get("shared", True)),
|
|
"guests": bool(sc.get("guests", True)),
|
|
"pluginId": pid,
|
|
}
|
|
if isinstance(sc.get("labelOff"), str) and sc["labelOff"].strip():
|
|
entry["labelOff"] = sc["labelOff"].strip()[:60]
|
|
if isinstance(sc.get("guidelineOff"), str) and sc["guidelineOff"].strip():
|
|
entry["guidelineOff"] = sc["guidelineOff"].strip()[:2000]
|
|
if isinstance(sc.get("triggers"), list):
|
|
tr = [str(x).strip()[:60] for x in sc["triggers"] if isinstance(x, str) and x.strip()][:20]
|
|
if tr:
|
|
entry["triggers"] = tr
|
|
if isinstance(sc.get("runners"), list):
|
|
rn = [str(x).strip()[:64] for x in sc["runners"] if isinstance(x, str) and x.strip()][:20]
|
|
if rn:
|
|
entry["runners"] = rn
|
|
if isinstance(sc.get("children"), list):
|
|
ch = [str(x).strip()[:64] for x in sc["children"] if isinstance(x, str) and x.strip()][:20]
|
|
if ch:
|
|
entry["children"] = ch
|
|
out.append(entry)
|
|
return out
|
|
|
|
|
|
def _run_one(deps, uid: str, rec: dict[str, Any], grant: dict[str, Any] | None) -> list[dict[str, Any]]:
|
|
from plugins.runner import run_script
|
|
mf = rec["manifest"]
|
|
act = mf["actions"][mf["provides"][PROVIDES]]
|
|
try:
|
|
raw = run_script(
|
|
deps, deps.plugin_store, uid, rec, act["script"],
|
|
payload={"trigger": PROVIDES},
|
|
timeout_sec=min(15, int(act.get("timeoutSec") or 15)),
|
|
grant=grant,
|
|
)
|
|
except Exception as e:
|
|
log.warning("composer.shortcuts plugin %s failed: %s", rec.get("id"), e)
|
|
return []
|
|
return _clean_shortcuts(rec["id"], raw)
|
|
|
|
|
|
def shortcuts_for(deps, caller) -> list[dict[str, Any]]:
|
|
"""Every plugin-contributed composer shortcut active for ``caller``."""
|
|
uid = OWNER_UID if caller.is_owner else caller.id
|
|
out: list[dict[str, Any]] = []
|
|
seen_ids: set[str] = set()
|
|
for rec, grant in _providers_for(deps, uid):
|
|
key = _cache_key(uid, rec, grant)
|
|
items = _cache.get(key, lambda rec=rec, grant=grant: _run_one(deps, uid, rec, grant))
|
|
for sc in items:
|
|
if sc["id"] not in seen_ids:
|
|
seen_ids.add(sc["id"])
|
|
out.append(sc)
|
|
return out
|