- 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>
108 lines
4.1 KiB
Python
108 lines
4.1 KiB
Python
"""``models.serve`` — the host's model servers for a plugin's handlers (the
|
|
``model-catalog`` plugin, 2026-12-02; ``sidecar/routes_model_serve.py`` is the
|
|
other half).
|
|
|
|
Owner only, operator approval, the plugin's own handlers only. One route,
|
|
served at ``…/hub/model-serve`` (the bridges' convention) and
|
|
``…/bridge/model-serve``:
|
|
|
|
* ``POST …/plugins/{pid}/hub/model-serve`` — ``{"op", …}`` → the host
|
|
sidecar's ``POST /model-serve`` (Colab / Vast.ai serve scripts, SSH to the
|
|
EVOX2, ``~/.pi/agent/models.json`` — none of which the hub's container
|
|
reaches). ``op`` is one of :data:`OPS`; the body is passed on as it is
|
|
(≤ :data:`BODY_MAX` bytes) and the sidecar validates every field. Its JSON
|
|
reply is passed back.
|
|
|
|
Refusals carry ``{"error": {message, kind}, "detail": {message, kind}}`` like
|
|
``machines.wake``'s: a bad body 400 ``bad_request``, the sidecar's own errors
|
|
passed through.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import logging
|
|
from typing import Any
|
|
|
|
from fastapi import APIRouter, HTTPException, Request
|
|
from fastapi.responses import JSONResponse
|
|
from starlette.concurrency import run_in_threadpool
|
|
|
|
from plugins.hubmachines import _refuse
|
|
from plugins.proxyroutes import _active_plugin, _who
|
|
|
|
log = logging.getLogger(__name__)
|
|
router = APIRouter(include_in_schema=False)
|
|
|
|
CAP = "models.serve"
|
|
BASE = "/proxy/tools/plugins/{pid}"
|
|
BODY_MAX = 64 * 1024
|
|
OPS = frozenset({
|
|
"status", "start", "stop", "evox2_scan", "evox2_load", "evox2_unload",
|
|
"evox2_install", "evox2_download_status", "sync_pi_models",
|
|
})
|
|
# How long the sidecar may take per op (its own subprocess timeouts + slack).
|
|
TIMEOUTS = {"start": 150, "stop": 120, "evox2_scan": 90, "evox2_load": 240,
|
|
"evox2_unload": 90, "evox2_install": 60, "evox2_download_status": 30,
|
|
"status": 20, "sync_pi_models": 20}
|
|
|
|
|
|
def _bridge(request: Request, pid: str):
|
|
"""(rec, error): the plugin's own handler, run for the owner, holding
|
|
``models.serve``."""
|
|
who, err = _who(request, pid)
|
|
if err:
|
|
return None, err
|
|
if who.handler != pid:
|
|
return None, _refuse(403, f"{CAP} is only available to the plugin's own handlers",
|
|
"handler_only")
|
|
if not who.is_owner:
|
|
return None, _refuse(403, f"{CAP} is owner-only", "capability")
|
|
_, rec, _, _, err = _active_plugin(request.app.state.ai, who, pid)
|
|
if err:
|
|
return None, err
|
|
if CAP not in (rec["manifest"].get("capabilities") or []):
|
|
return None, _refuse(403, f"plugin lacks {CAP} capability", "capability")
|
|
return rec, None
|
|
|
|
|
|
def serve_payload(body: Any) -> tuple[dict | None, str | None]:
|
|
"""The body → ``(payload, None)`` or ``(None, why)``."""
|
|
if not isinstance(body, dict):
|
|
return None, "body must be a JSON object"
|
|
op = body.get("op")
|
|
if not isinstance(op, str) or op not in OPS:
|
|
return None, f"op must be one of {sorted(OPS)}"
|
|
return dict(body), None
|
|
|
|
|
|
def call_sidecar(deps, payload: dict) -> tuple[int, dict]:
|
|
from runs.sidecar_client import _sidecar_call
|
|
try:
|
|
return 200, _sidecar_call(deps, "/model-serve", payload,
|
|
timeout=TIMEOUTS.get(payload["op"], 60))
|
|
except HTTPException as e:
|
|
d = e.detail if isinstance(e.detail, dict) else {"message": str(e.detail)}
|
|
d = {"message": str(d.get("message") or d)[:500], "kind": str(d.get("kind") or "model_serve")}
|
|
return e.status_code, {"error": d, "detail": d}
|
|
|
|
|
|
@router.post(BASE + "/hub/model-serve")
|
|
@router.post(BASE + "/bridge/model-serve")
|
|
async def hub_model_serve(pid: str, request: Request):
|
|
_rec, err = _bridge(request, pid)
|
|
if err:
|
|
return err
|
|
raw = await request.body()
|
|
if len(raw) > BODY_MAX:
|
|
return _refuse(413, "body too large", "bad_request")
|
|
try:
|
|
body = json.loads(raw or b"null")
|
|
except ValueError:
|
|
body = None
|
|
payload, why = serve_payload(body)
|
|
if why:
|
|
return _refuse(400, why, "bad_request")
|
|
status, out = await run_in_threadpool(call_sidecar, request.app.state.ai, payload)
|
|
return JSONResponse(out, status_code=status)
|