Files
ai-agent/backend/models/routes.py
gabrielvidalandClaude Opus 5.5 2c02deb109 refactor(plugins): EVOX2 sidecar helpers → provider-evox2, OpenRouter catalogue → registry discovery
- sidecar/gen_progress.py, local_ready.py, local_room.py moved into the
  provider-evox2 plugin's new provider.sidecar module; the core reaches them
  through usage_loader.live_progress / before_launch and the module's
  extra_routers() (/local-ready, host only). No plugin: no-ops.
- provider.sidecar: a provider sidecar module that is no usage reader
  (typed_manifest, store.sync_typed, DriverLoader code_key tuple).
- backend/models/openrouter.py deleted: the APPE catalogue is the
  openrouter_appe discovery of plugins/providers.py (appe_catalogue,
  warm_discovery, legacy_appe_index).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 18:43:37 +01:00

209 lines
8.2 KiB
Python

"""The models a session can run on, and the OpenRouter catalogue."""
import threading
import time
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
import accounts as accounts_mod
import models as models_mod
import schemas
from core.http import _json_in_worker, _r
from core.state import State
from models import presets as presets_mod
from runs.sidecar_client import _sidecar_get
from users.caller import CallerDep, OwnerDep
router = APIRouter()
# Whether OpenRouter takes pi runs: the key lives on the host, so the sidecar
# checks it (sidecar/pi_runs.py, cached there too). A refused key is re-asked
# every OR_TTL_S; a sidecar that didn't answer sooner — and says nothing
# against the key.
OR_TTL_S = 300
OR_UNKNOWN_TTL_S = 30
_or_down: tuple[float, float, str | None] | None = None # (at, ttl, reason)
_or_lock = threading.Lock()
_or_refreshing = False
def _probe_openrouter() -> tuple[float, float, str | None]:
now = time.time()
st = _sidecar_get("/pi/openrouter", timeout=4)
if st is None:
return (now, OR_UNKNOWN_TTL_S, None)
return (now, OR_TTL_S, (st.get("reason") or "OpenRouter refused the key")
if st.get("ok") is False else None)
def _refresh_openrouter_bg() -> None:
global _or_down, _or_refreshing
try:
val = _probe_openrouter()
with _or_lock:
_or_down = val
finally:
with _or_lock:
_or_refreshing = False
def openrouter_down() -> str | None:
"""Why OpenRouter can't take a pi run right now, or None (fine / unknown).
Stale-while-revalidate on TTL expiry so `/api/models` never blocks on the
4 s sidecar HTTP probe."""
global _or_down, _or_refreshing
now = time.time()
with _or_lock:
cur = _or_down
if cur is not None:
if now - cur[0] < cur[1]:
return cur[2]
if not _or_refreshing:
_or_refreshing = True
threading.Thread(target=_refresh_openrouter_bg, daemon=True,
name="openrouter-probe").start()
return cur[2]
val = _probe_openrouter()
with _or_lock:
_or_down = val
return val[2]
def with_availability(models: list[dict], or_reason: str | None) -> list[dict]:
"""The list with ``unavailable`` set on the pi chips that can't run now."""
if not or_reason:
return models
return [{**m, "unavailable": or_reason}
if m.get("harness") == "pi" and m.get("provider") == "openrouter" else m
for m in models]
AGY_UNHOSTED = ("No machine runs agy yet — install it on the lab (SIDECAR_AGY_ACCOUNTS) "
"or on a worker (its installer's --update with Antigravity on)")
def agy_down(deps) -> str | None:
"""Why no agy run can start now, or None: some machine — the lab's own
sidecar, or an online worker — declares an agy (Google) account."""
agy = set(accounts_mod.for_harness("agy"))
if not agy:
return AGY_UNHOSTED
health = getattr(deps, "account_health", None)
try:
if health and agy & health.host_accounts():
return None
except Exception:
pass
store = getattr(deps, "worker_store", None)
if store is not None:
for w in store.list():
if agy & set(w.get("agyAccounts") or []) and store.online(w["id"]) \
and not w.get("owner"):
return None
return AGY_UNHOSTED
def for_caller(models: list[dict], is_owner: bool, agy_reason: str | None,
presets: dict[str, dict] | None = None,
allowed: list[str] | None = None) -> list[dict]:
"""The owner gets every entry, the agy ones greyed with ``agy_reason``
while no machine hosts agy.
A guest gets every Claude entry (on their own Claude login any model is
theirs — the composer narrows it to ``allowed`` when the run bills the
host) and, of the other models, the ones in the guest pool *and* in
their own list (``allowed``, Settings → Users) — only the entry of each
one's preset harness: a guest never picks a harness."""
if agy_reason:
models = [{**m, "unavailable": agy_reason} if m.get("harness") == "agy" else m
for m in models]
if is_owner:
return models
presets = presets or {}
mine = set(allowed or ())
out = []
for m in models:
if (m.get("harness") or "claude") == "claude":
out.append(m)
continue
key = presets_mod.key_of(m)
p = presets.get(key) or {}
if not p.get("guests") or key not in mine:
continue
pick = presets_mod.entry_for(models, key, p) or {}
if m.get("id") == pick.get("id") and m.get("harness") == pick.get("harness"):
out.append(m)
return out
@router.get("/api/models", responses=_r(schemas.ModelsResponse))
@_json_in_worker
def list_models(deps: State, caller: CallerDep):
"""The models a session can be spawned/resumed on (a tag each in the composer).
Fetched from the Anthropic API and cached in-process (see models.py), so the
picker follows new releases without a redeploy. `default` is what a run uses
when no model tag is picked. An OpenRouter pi model carries `unavailable`
(the reason) while the host's OpenRouter key is refused; an agy (Gemini)
model while no machine hosts agy — and a guest gets no agy model at all."""
models = with_availability(models_mod.list_models(), openrouter_down())
presets = presets_mod.presets(models)
models = for_caller(models, caller.is_owner, agy_down(deps), presets,
list(caller.models or ()))
models = presets_mod.annotate(models)
keys = {m["key"] for m in models}
shown = {k: p for k, p in presets.items() if k in keys}
if not caller.is_owner: # the pool is the owner's business
shown = {k: {f: v for f, v in p.items() if f != "guests"} for k, p in shown.items()}
return {"models": models, "default": models_mod.DEFAULT_MODEL, "presets": shown}
class PresetPatchBody(BaseModel):
key: str
patch: dict
@router.patch("/api/model-presets", responses=_r(schemas.ModelPresetResponse))
def patch_model_preset(deps: State, _owner: OwnerDep, body: PresetPatchBody):
"""Settings → Models: change one model's preset (None clears a field back
to its default). Switching ``guests`` on adds the model to every guest's
own list — the pool is what they get; Settings → Users can untick it per
guest — and off leaves their lists alone (the pool alone gates it)."""
models = models_mod.list_models()
hs = presets_mod.harnesses_by_key(models).get(body.key)
if hs is None:
raise HTTPException(404, "no such model")
if body.patch.get("harness") and body.patch["harness"] not in hs:
raise HTTPException(400, f"{body.key} doesn't run on {body.patch['harness']}")
try:
before = presets_mod.presets(models).get(body.key) or {}
presets_mod.store().patch(body.key, body.patch)
except presets_mod.PresetError as exc:
raise HTTPException(400, str(exc)) from None
after = presets_mod.presets(models)[body.key]
if after.get("guests") and not before.get("guests"):
for u in deps.users.all():
have = list(u.get("models") or ())
if u.get("role") == "guest" and body.key not in have:
deps.users.update(u["id"], {"models": [*have, body.key]})
deps.hub.publish({"type": "model-presets"})
return {"key": body.key, "preset": after}
@router.get("/api/models/openrouter",
responses=_r(schemas.OpenRouterModelsResponse))
@_json_in_worker
def list_openrouter_models():
"""Every model a pi.dev session can run on OpenRouter, cheapest first.
Not part of `/api/models` on purpose: that endpoint is the composer's short
pickable list (one chip per Claude family + the curated pi entries), while
this is a few hundred models the model browser searches through. Prices
($/Mtok in / out / cache), context window and parameter size all come from
APPE's catalogue — the homelab's model-data source of truth, declared by
the provider-openrouter plugin (``plugins/providers.appe_catalogue``).
"""
from plugins import providers
return providers.appe_catalogue(providers.current())