Files
ai-agent/backend/plugins/models_catalog_bridge.py
gabrielvidalandClaude Opus 5.5 7bbb93b1c9 feat(models): core support for the model-catalog plugin
- provides "models.catalog" (plugins/models_catalog_bridge.py): the owner's
  provider's {providers, disabled, families} overlay, validated, served from a
  background-refreshed cache; catalog_version() is part of the provider
  registry's key, so a change rebuilds /api/models and /api/providers.
- ProviderRegistry merges it on read (merge_models in _models_of, the
  pricers' ids + watts — new EVOX2 models price local —, families_of for
  entries / api_payload / context_window); no ProviderSpec.spec is mutated.
- A POSTed non-readOnly action of the provider reloads it and publishes SSE
  models + providers; install/toggle/uninstall re-look the provider up.
- "models.serve" capability (operator): POST …/hub/model-serve
  (plugins/hubmodelserve.py) → host sidecar POST /model-serve
  (sidecar/routes_model_serve.py, host only): status, start/stop (colab,
  vast), evox2_scan/load/unload/install/download_status, sync_pi_models.
- Settings → Models: a Model catalog shortcut while a provider is on; the
  app invalidates ["models"] / ["providers"] on the new SSE events.
- Tests: backend/test_models_catalog_bridge.py, sidecar/test_routes_model_serve.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 21:40:18 +01:00

299 lines
11 KiB
Python

"""The dynamic model catalog: models a live plugin adds to (or hides from) the
provider plugins' static ``provider.models`` lists.
The ``model-catalog`` plugin (2026-12-02) lets the owner add a Hugging Face or
local model to the EVOX2 / Colab / Vast.ai providers, hide one they ship, and
give a family its icon, colour and default context window — without editing a
provider plugin. It declares ``provides: {"models.catalog": "<action>"}``; the
host runs that action as the owner and reads::
{"providers": {"evox2": [{"id", "displayName", "family", "version", "label",
"alias", "latest", "contextWindow", "server",
"efforts", "watts", "key"}], "colab": […], …},
"disabled": {"evox2": ["id-to-hide"], …},
"families": {"deepseek": {"icon", "color", "defaultContextWindow"}}}
:mod:`plugins.providers` merges it into the registry (``_models_of``, the
pricers' model ids and watts, the families) without touching any
``ProviderSpec.spec``.
The registry asks on every build, so :func:`overlay` never runs the plugin on
the caller's thread: it serves the last answer and refreshes it in the
background once it is :data:`TTL_SECS` old (or the provider changed).
:func:`catalog_version` moves only when the answer really changed — it is part
of the registry's cache key, so a change rebuilds ``/api/models`` and
``/api/providers`` at once. A POSTed action of the provider (its page saved)
reloads it straight away and publishes SSE ``models`` + ``providers``
(:func:`touched`). With no provider (no plugin store bound — unit tests —,
none installed, disabled or failing) the overlay is :data:`EMPTY`.
"""
from __future__ import annotations
import json
import logging
import re
import threading
import time
from typing import Any
from plugins.store import OWNER_UID
log = logging.getLogger(__name__)
PROVIDES = "models.catalog"
TTL_SECS = 30.0
MAX_MODELS = 500
_VENDOR_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,47}$")
_ID_RE = re.compile(r"^[A-Za-z0-9._:/@+-]{1,160}$")
_FAMILY_RE = re.compile(r"^[a-z0-9][a-z0-9._-]{0,47}$")
_STR = ("displayName", "family", "version", "label", "alias", "server", "key")
_FAMILY_STR = ("icon", "color", "label")
EMPTY: dict[str, Any] = {"providers": {}, "disabled": {}, "families": {}}
_lock = threading.Lock()
# (provider key, fetched at, overlay)
_state: dict[str, Any] = {"key": None, "at": 0.0, "data": EMPTY}
_version = 0
_refreshing = False
# (store, store version) → (rec, action) | None — the lookup is on the hot path
_prov_memo: tuple[Any, Any, Any] | None = None
def catalog_version() -> int:
return _version
def _bump() -> None:
global _version
_version += 1
# ── validation ───────────────────────────────────────────────────────────────
def _clean_model(raw: Any) -> dict[str, Any] | None:
if not isinstance(raw, dict):
return None
mid = raw.get("id")
if not isinstance(mid, str) or not _ID_RE.fullmatch(mid):
return None
out: dict[str, Any] = {"id": mid}
for k in _STR:
v = raw.get(k)
if isinstance(v, str) and v:
out[k] = v[:200]
if "alias" in raw and raw["alias"] is None:
out["alias"] = None
if isinstance(raw.get("latest"), bool):
out["latest"] = raw["latest"]
cw = raw.get("contextWindow")
if isinstance(cw, int) and not isinstance(cw, bool) and 0 < cw <= 100_000_000:
out["contextWindow"] = cw
w = raw.get("watts")
if isinstance(w, (int, float)) and not isinstance(w, bool) and 0 <= w <= 100_000:
out["watts"] = float(w)
ef = raw.get("efforts")
if isinstance(ef, list):
out["efforts"] = [str(x)[:32] for x in ef if isinstance(x, str) and x][:12]
return out
def clean(res: Any) -> dict[str, Any]:
"""A plugin's answer → the overlay; anything malformed is dropped."""
if not isinstance(res, dict):
return {"providers": {}, "disabled": {}, "families": {}}
providers: dict[str, list[dict]] = {}
for vid, rows in (res.get("providers") or {}).items() if isinstance(res.get("providers"), dict) else ():
if not isinstance(vid, str) or not _VENDOR_RE.fullmatch(vid) or not isinstance(rows, list):
continue
seen: set[str] = set()
out = []
for raw in rows[:MAX_MODELS]:
m = _clean_model(raw)
if m is None or m["id"] in seen:
continue
seen.add(m["id"])
out.append(m)
providers[vid] = out
disabled: dict[str, list[str]] = {}
for vid, ids in (res.get("disabled") or {}).items() if isinstance(res.get("disabled"), dict) else ():
if not isinstance(vid, str) or not _VENDOR_RE.fullmatch(vid) or not isinstance(ids, list):
continue
disabled[vid] = sorted({i for i in ids[:MAX_MODELS] if isinstance(i, str) and _ID_RE.fullmatch(i)})
families: dict[str, dict] = {}
for fam, spec in (res.get("families") or {}).items() if isinstance(res.get("families"), dict) else ():
if not isinstance(fam, str) or not _FAMILY_RE.fullmatch(fam) or not isinstance(spec, dict):
continue
f: dict[str, Any] = {}
for k in _FAMILY_STR:
if isinstance(spec.get(k), str) and spec[k]:
f[k] = spec[k][:64]
cw = spec.get("defaultContextWindow")
if isinstance(cw, int) and not isinstance(cw, bool) and 0 < cw <= 100_000_000:
f["defaultContextWindow"] = cw
families[fam] = f
return {"providers": providers, "disabled": disabled, "families": families}
# ── the provider ─────────────────────────────────────────────────────────────
def _provider(deps) -> tuple[dict[str, Any], str] | None:
"""The owner's active plugin providing ``models.catalog`` → (rec, action)."""
global _prov_memo
store = getattr(deps, "plugin_store", None)
if store is None:
return None
v = getattr(store, "version", None)
memo = _prov_memo
if memo is not None and memo[0] is store and memo[1] == v:
return memo[2]
from plugins.waiting import _providers_for
hit = None
try:
found = _providers_for(deps, OWNER_UID, PROVIDES)
except Exception: # noqa: BLE001 — no plugin store (tests, early boot)
found = []
for rec, _grant in found:
mf = rec.get("manifest") or {}
act = (mf.get("provides") or {}).get(PROVIDES)
if act in (mf.get("actions") or {}):
hit = (rec, act)
break
_prov_memo = (store, v, hit)
return hit
def has_provider(deps) -> bool:
return _provider(deps) is not None
def provides(rec: dict[str, Any] | None) -> bool:
mf = (rec or {}).get("manifest") or {}
act = (mf.get("provides") or {}).get(PROVIDES)
return bool(act and act in (mf.get("actions") or {}))
def _key(rec: dict[str, Any]) -> str:
return f"{rec.get('id')}@{rec.get('fingerprint') or ''}:{rec.get('dir') or ''}"
def _run(deps, rec: dict[str, Any], action: str) -> dict[str, Any] | None:
from plugins.runner import run_script
act = (rec.get("manifest") or {}).get("actions", {}).get(action) or {}
try:
res = run_script(deps, deps.plugin_store, OWNER_UID, rec, act["script"],
payload={"trigger": PROVIDES},
timeout_sec=int(act.get("timeoutSec") or 30))
except Exception as e: # noqa: BLE001 — a broken plugin never breaks the hub
log.warning("models.catalog via %s failed: %s", rec.get("id"), e)
return None
return clean(res)
def _store(key: str | None, data: dict[str, Any]) -> bool:
"""Keep ``data`` as the overlay; True when it changed (version bumped)."""
with _lock:
same = json.dumps(_state["data"], sort_keys=True) == json.dumps(data, sort_keys=True)
_state.update(key=key, at=time.monotonic(), data=data)
if not same:
_bump()
return not same
def reload(deps) -> bool:
"""Ask the provider now (synchronously); True when the overlay changed."""
hit = _provider(deps)
if hit is None:
return _store(None, EMPTY)
rec, action = hit
data = _run(deps, rec, action)
if data is None: # a failing plugin keeps its last good answer
with _lock:
_state["at"] = time.monotonic()
return False
return _store(_key(rec), data)
def _refresh_bg(deps, publish: bool) -> None:
global _refreshing
try:
changed = reload(deps)
if changed or publish:
_publish(deps)
except Exception: # noqa: BLE001
log.warning("models.catalog refresh failed", exc_info=True)
finally:
with _lock:
_refreshing = False
def _start_refresh(deps, *, publish: bool = False) -> None:
global _refreshing
with _lock:
if _refreshing:
return
_refreshing = True
threading.Thread(target=_refresh_bg, args=(deps, publish), daemon=True,
name="models-catalog-refresh").start()
def _publish(deps) -> None:
hub = getattr(deps, "hub", None)
if hub is None:
return
try:
hub.publish({"type": "models"})
hub.publish({"type": "providers"})
except Exception: # noqa: BLE001 — no hub (tests)
pass
def overlay(deps) -> dict[str, Any]:
"""The current overlay, never waiting on the plugin (a stale or missing
answer is refreshed in the background). Treat it as read-only."""
hit = _provider(deps)
if hit is None:
if _state["key"] is not None or _state["data"] is not EMPTY:
_store(None, EMPTY)
return EMPTY
rec, _action = hit
with _lock:
key, at, data = _state["key"], _state["at"], _state["data"]
if key != _key(rec) or time.monotonic() - at >= TTL_SECS:
_start_refresh(deps, publish=False)
return data
def touched(deps, rec: dict[str, Any] | None, *, action: str | None = None) -> None:
"""The plugin ``rec`` ran a POSTed action: when it provides
``models.catalog`` (and the action isn't read-only), read the catalog
again and tell every app to refetch its models (SSE ``models`` +
``providers``, sent once the new answer is in)."""
if not provides(rec):
return
if action:
act = (((rec or {}).get("manifest") or {}).get("actions") or {}).get(action) or {}
if act.get("readOnly"):
return
with _lock:
_state["at"] = 0.0
_start_refresh(deps, publish=True)
def changed() -> None:
"""A plugin came or went (install, toggle, uninstall): look it up again."""
global _prov_memo
_prov_memo = None
with _lock:
_state["at"] = 0.0
def invalidate() -> None:
"""Drop the cached answer and move :func:`catalog_version` (tests, a
provider that went away)."""
global _prov_memo
_prov_memo = None
with _lock:
_state.update(key=None, at=0.0, data=EMPTY)
_bump()