Files
ai-agent/backend/plugins/seed_registry.py
Gabriel VidalandClaude Opus 5.5 9ebc2de810 perf(plugins): plugin pages paint at once and look native
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>
2026-11-26 21:22:43 +01:00

192 lines
7.3 KiB
Python

"""The provider registry pricing reads, with or without a plugin store.
A running hub prices through the owner's enabled ``provider-*`` plugins
(``plugins.providers.current()``, bound by ``core/state.build_state``) — and
**only** through them: a provider disabled later still prices its history
from the registry's pricing snapshot, never from a table in core.
A process with no plugin store at all — a standalone parse
(``scripts/ab/_parse_worker.py``, ``scripts/*.py``), a unit test that never
built the app, or a store that has never held a single provider (a fresh test
store, the first-boot window before ``carryover.seed_typed_plugins``) — reads
the default plugins straight from the seed dir instead: ``PLUGINS_SEED_DIR``,
else the plugins repo checkout (``/workspace/projects/ai-agent-plugins/plugins``,
``~/projects/ai-agent-plugins/plugins``), else ``backend/fixtures/typed_plugins``.
The same tables either way, so a figure never depends on which side priced it.
The seed registry never touches the network: Anthropic's live ``/v1/models``
discovery is off (pricing doesn't read it), and the OpenRouter catalogue is
the APPE catalogue's legacy disk copy (``providers.legacy_appe_index``) — the disk copy a parse has always
priced pi sessions from.
"""
from __future__ import annotations
import copy
import json
import logging
import os
import pathlib
import threading
from . import providers
log = logging.getLogger(__name__)
FIXTURES = pathlib.Path(__file__).resolve().parent.parent / "fixtures" / "typed_plugins"
_lock = threading.Lock()
_seed: tuple[str, providers.ProviderRegistry] | None = None
def seed_dirs() -> list[pathlib.Path]:
"""Where the default provider / harness plugins are read from, in order."""
out: list[pathlib.Path] = []
env = os.environ.get("PLUGINS_SEED_DIR")
if env:
out.append(pathlib.Path(env))
out += [pathlib.Path("/workspace/projects/ai-agent-plugins/plugins"),
pathlib.Path.home() / "projects" / "ai-agent-plugins" / "plugins",
FIXTURES]
return out
def _seed_root() -> pathlib.Path | None:
for d in seed_dirs():
try:
if d.is_dir() and any(c.name.startswith("provider-") and (c / "plugin.json").is_file()
for c in d.iterdir()):
return d
except OSError:
continue
return None
def _defaults(mf: dict) -> dict:
"""A plugin's settings defaults — the config ``providers._entries`` gives
an installed plugin nobody configured."""
return {f["key"]: f.get("default") for f in (mf.get("settings") or {}).get("fields") or ()
if f.get("key") and f.get("default") not in (None, "")}
class _OpenRouterIndex:
"""The APPE catalogue's legacy disk copy as the ``id → row`` mapping an
``openrouter_catalogue`` pricer reads (a seed registry never fetches)."""
def get(self, model_id, default=None):
return providers.legacy_appe_index().get((model_id or "").strip()) or default
def build_from(root: pathlib.Path) -> providers.ProviderRegistry:
"""A registry of every ``provider-*`` / ``harness-*`` plugin under
``root``, each on its default settings."""
provs: list[providers.ProviderSpec] = []
hars: list[providers.HarnessSpec] = []
seen_v: set[str] = set()
seen_h: set[str] = set()
for child in sorted(root.iterdir()):
if not child.is_dir() or not child.name.startswith(("provider-", "harness-")):
continue
path = child / "plugin.json"
try:
mf = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError) as e:
log.warning("seed plugin %s unreadable: %s", child.name, e)
continue
kind = mf.get("kind") or "app"
pid = mf.get("id") or child.name
if kind == "provider" and isinstance(mf.get("provider"), dict):
spec = copy.deepcopy(mf["provider"])
vid = spec.get("vendorId")
if not vid or vid in seen_v:
continue
seen_v.add(vid)
disc = spec.get("discovery") or {}
if disc.get("kind") == "anthropic_models":
# no network from a seed registry: the static models stand
spec["discovery"] = {**disc, "kind": "static"}
provs.append(providers.ProviderSpec(vid, pid, spec, _defaults(mf)))
elif kind == "harness" and isinstance(mf.get("harness"), dict):
hid = mf["harness"].get("harnessId")
if not hid or hid in seen_h:
continue
seen_h.add(hid)
hars.append(providers.HarnessSpec(hid, pid, copy.deepcopy(mf["harness"]), _defaults(mf)))
reg = providers.build(provs, hars, version=1, sig=f"seed:{root}")
index = _OpenRouterIndex()
for pr in reg._pricers:
if pr.kind == "openrouter_catalogue":
pr.catalogue_fn = (lambda i=index: i)
return reg
def seed() -> providers.ProviderRegistry:
"""The seed dir's registry, built once per process (rebuilt only when
``PLUGINS_SEED_DIR`` changes)."""
global _seed
key = os.environ.get("PLUGINS_SEED_DIR") or ""
hit = _seed
if hit is not None and hit[0] == key:
return hit[1]
with _lock:
if _seed is not None and _seed[0] == key:
return _seed[1]
root = _seed_root()
if root is None:
log.warning("no provider plugins found in %s — every price is 0",
", ".join(map(str, seed_dirs())))
reg = providers.build([], [], version=0)
else:
reg = build_from(root)
_seed = (key, reg)
return reg
def reset() -> None:
"""Forget the seed registry (tests that point PLUGINS_SEED_DIR elsewhere)."""
global _seed
with _lock:
_seed = None
def _knows_pricing(reg: providers.ProviderRegistry) -> bool:
return bool(reg.providers or reg._stale_pricers)
# (store, its version, whether an active plugin is a provider / harness):
# ``effective()`` runs once per priced row (a project's cost rollup prices
# thousands), and ``active_manifests`` deep-copies every manifest — that copy
# was half the hub's CPU on 2026-11-26. The answer only moves with the store.
_typed_memo: tuple[object, int, bool] | None = None
def _has_typed(store) -> bool:
global _typed_memo
v = getattr(store, "version", None)
hit = _typed_memo
if v is not None and hit is not None and hit[0] is store and hit[1] == v:
return hit[2]
try:
from plugins.store import OWNER_UID
rows = store.active_manifests(OWNER_UID)
has_typed = any((mf.get("kind") or "app") in ("provider", "harness") for _, mf, _ in rows)
except Exception: # noqa: BLE001 — fake/partial store
has_typed = False
if isinstance(v, int):
_typed_memo = (store, v, has_typed)
return has_typed
def effective() -> providers.ProviderRegistry:
"""The registry pricing reads: the bound plugin store's when it has ever
known a provider (strict: the hub's own plugins and their pricing
snapshot), else the seed dir's."""
store = providers._store_of(providers._bound)
if store is None:
return seed()
has_typed = _has_typed(store)
if not has_typed and not providers._ever_seeded(store):
return seed()
reg = providers.current()
return reg if _knows_pricing(reg) else seed()