Strict plugin-only: no model / account / harness table left in core.
- plugins/providers: an unbound or never-seeded store reads the seed dir's
provider-*/harness-* manifests (PLUGINS_SEED_DIR, else the plugins
checkout, else backend/fixtures/typed_plugins) — once seeded, only what is
installed. Harness↔vendor helpers (vendors_of_harness, login_harness,
hosted_harnesses, accounts_for_harness, provider_config/secret).
- models/catalog + presets: list_models / is_local / context_window /
opencode_model / agy_model / pi_provider / key_of / vendor_of / guest pool
delegate to the registry; DEFAULT_MODEL, FAMILIES… computed (PEP 562).
openrouter.py reads the provider-openrouter plugin's catalogueUrl and its
api_key hub secret (OPENROUTER_API_KEY fallback).
- accounts: provider-owned; vendor-native helpers (accounts_for_vendor,
vendor_of_account, resolve_alias, wire_id) + compat for_harness /
valid_for / harness_of joined through harness.supports[]. Clean provider
accounts: keyless evox2 (alias opencode-lab, still sent to the sidecar as
opencode-lab), openrouter's own account — pi no longer bills `personal`.
- profiles: profile-level ★ per vendor (profile.accounts), per-machine
overrides on workers[i].accounts; idempotent migration of the harness-keyed
runner ★ on load (file version 3); default_login takes a vendor or a
harness; PUT|PATCH /api/profiles/{id} edits accounts. The API keeps
harness keys beside vendor keys in each runner's accounts/logins.
- runs/cron/scheduled: harness tuples → the registry (caps lean/fork,
runsOn lab, hosted harnesses); a new run routes model → vendor → the
profile's ★ for it.
- cli: --harness accepts any active harness (checked against
/api/providers); MCP drops its static enum.
- tests: golden-tables.json pins the old tables' answers; new
test_provider_accounts.py (migration, clean accounts, routing by vendor).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
279 lines
10 KiB
Python
279 lines
10 KiB
Python
"""
|
|
Settings → Models: one preset per model, owned by the hub (``/data/model-presets.json``).
|
|
|
|
The composer no longer has a harness select: **the model decides**. Every
|
|
catalogue entry (``catalog.list_models``) is one *(model, harness)* pair, and
|
|
the same model can appear under several harnesses — the EVOX2's Qwen runs on
|
|
pi and, as its ``evox2/…`` twin, on opencode; a GPT model is listed once per
|
|
priority tier (``-fast`` / ``-ultrafast``). :func:`key_of` folds those into one
|
|
**model key**:
|
|
|
|
* a Claude model → its family (``opus``): stable across releases, and the
|
|
same word a guest's allowed-models list has always held;
|
|
* an opencode EVOX2 twin → the pi id it twins (``ggml-org/qwen3.8-27b``);
|
|
* a GPT tier variant → its base id (``gpt-6-sol``), the tier being a preset
|
|
field (``fast``);
|
|
* anything else → its id.
|
|
|
|
A preset is what a run on that model starts with — ``harness`` (one of the
|
|
harnesses that list it), ``effort`` (claude / opencode / agy), ``thinking``
|
|
(pi), ``fast`` (GPT: ``""`` | ``fast`` | ``ultrafast``) — plus two flags:
|
|
``favorite`` (the picker's ★ section — the owner's, shared with guests) and
|
|
``guests`` (the **guest pool**: a guest may run it, if their own model list
|
|
on Settings → Users keeps it). Unset fields resolve to :func:`defaults`, so an
|
|
untouched hub behaves as before (Claude on claude, Qwen on pi, Gemini on agy,
|
|
GPT on opencode; guests: opus / sonnet / haiku).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import copy
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import re
|
|
import threading
|
|
import time
|
|
|
|
PATH = os.environ.get("MODEL_PRESETS_PATH", "/data/model-presets.json")
|
|
|
|
FAST_MODES = ("", "fast", "ultrafast")
|
|
FIELDS = ("harness", "effort", "thinking", "fast", "favorite", "guests")
|
|
_KEY = re.compile(r"^[A-Za-z0-9._:/@+-]{1,200}$")
|
|
_EFFORT = re.compile(r"^[a-z]{1,16}$")
|
|
_FAST_RE = re.compile(r"-(fast|ultrafast)$")
|
|
|
|
|
|
def _reg():
|
|
from plugins import providers
|
|
return providers.current()
|
|
|
|
|
|
def harness_order() -> tuple[str, ...]:
|
|
"""The harness a model runs on when its preset names none (or one that no
|
|
longer lists it): the first of the active harnesses, in their plugins'
|
|
``order``, that does."""
|
|
return _reg().harness_ids()
|
|
|
|
|
|
def default_guest_keys() -> tuple[str, ...]:
|
|
"""The guest pool before the owner touches it: the provider models flagged
|
|
``defaultGuest`` (opus / sonnet / haiku)."""
|
|
return _reg().default_guest_keys()
|
|
|
|
|
|
class PresetError(ValueError):
|
|
pass
|
|
|
|
|
|
# ── keys and vendors ─────────────────────────────────────────────────────────
|
|
def key_of(m: dict) -> str:
|
|
"""The model key of a catalogue entry (see the module docstring): the
|
|
provider model's ``key`` — a Claude family, a twin's base id, a GPT
|
|
tier's base id."""
|
|
if not m.get("provider") and (m.get("harness") or "claude") == "claude":
|
|
# an entry from before ``provider`` was stamped on Claude entries
|
|
m = {**m, "provider": next(iter(_reg().vendors_of_harness("claude")), None)}
|
|
key = _reg().key_of(m)
|
|
if key == (m.get("id") or "") and m.get("family") and \
|
|
(m.get("harness") or "claude") in _reg().harnesses_of_vendor("anthropic"):
|
|
return m["family"] # a Claude snapshot the provider no longer lists
|
|
return key
|
|
|
|
|
|
def fast_mode(m: dict) -> str:
|
|
"""A GPT entry's tier: ``""`` (standard), ``fast`` or ``ultrafast``."""
|
|
if not m.get("fast"):
|
|
return ""
|
|
hit = _FAST_RE.search(m.get("id") or "")
|
|
return hit.group(1) if hit else ""
|
|
|
|
|
|
def vendor_of(m: dict) -> str:
|
|
"""Who makes / serves it — the picker's and the settings page's groups:
|
|
the entry's ``provider``, else the registry's read of its id, else the
|
|
harness's first vendor."""
|
|
if m.get("provider"):
|
|
return m["provider"]
|
|
reg = _reg()
|
|
return (reg.vendor_of_model(m.get("id"))
|
|
or next(iter(reg.vendors_of_harness(m.get("harness") or "claude")), None)
|
|
or "")
|
|
|
|
|
|
def annotate(models: list[dict]) -> list[dict]:
|
|
"""The catalogue with ``key`` + ``vendor`` (+ ``fastMode``) on every entry."""
|
|
out = []
|
|
for m in models:
|
|
e = {**m, "key": key_of(m), "vendor": vendor_of(m)}
|
|
if m.get("fast"):
|
|
e["fastMode"] = fast_mode(m)
|
|
out.append(e)
|
|
return out
|
|
|
|
|
|
def harnesses_by_key(models: list[dict]) -> dict[str, list[str]]:
|
|
"""Which harnesses list each key, in :func:`harness_order`."""
|
|
order = harness_order()
|
|
seen: dict[str, set[str]] = {}
|
|
for m in models:
|
|
seen.setdefault(key_of(m), set()).add(m.get("harness") or "claude")
|
|
return {k: [h for h in order if h in hs] + sorted(hs - set(order))
|
|
for k, hs in seen.items()}
|
|
|
|
|
|
def defaults(key: str, harnesses: list[str]) -> dict:
|
|
"""A key's preset before anyone set it."""
|
|
return {"harness": harnesses[0] if harnesses else "claude", "effort": "",
|
|
"thinking": True, "fast": "", "favorite": False,
|
|
"guests": key in default_guest_keys()}
|
|
|
|
|
|
def resolve(stored: dict | None, key: str, harnesses: list[str]) -> dict:
|
|
"""The stored fields over :func:`defaults`; a harness that no longer lists
|
|
the model falls back to its first one."""
|
|
out = defaults(key, harnesses)
|
|
for k, v in (stored or {}).items():
|
|
if k in FIELDS:
|
|
out[k] = v
|
|
if harnesses and out["harness"] not in harnesses:
|
|
out["harness"] = harnesses[0]
|
|
return out
|
|
|
|
|
|
def entry_for(models: list[dict], key: str, preset: dict) -> dict | None:
|
|
"""The catalogue entry a run on ``key`` launches: its preset harness's
|
|
(the GPT tier the preset names, else the standard one)."""
|
|
cands = [m for m in models if key_of(m) == key
|
|
and (m.get("harness") or "claude") == preset.get("harness")]
|
|
if not cands:
|
|
cands = [m for m in models if key_of(m) == key]
|
|
want = preset.get("fast") or ""
|
|
return next((m for m in cands if fast_mode(m) == want), cands[0] if cands else None)
|
|
|
|
|
|
def find_key(models: list[dict], arg: str | None) -> str | None:
|
|
"""The key a ``--model`` argument (alias, id, a twin's or tier's id, a
|
|
pinned Claude snapshot) belongs to — None for an unlisted one (an
|
|
OpenRouter-browser pick)."""
|
|
if not arg:
|
|
return None
|
|
for m in models:
|
|
if arg in (m.get("id"), m.get("alias")) or arg == key_of(m):
|
|
return key_of(m)
|
|
a = arg.lower()
|
|
for m in models:
|
|
fam = m.get("family")
|
|
if (m.get("harness") or "claude") == "claude" and fam \
|
|
and re.search(rf"(^|-){re.escape(fam)}(-|$)", a):
|
|
return fam
|
|
return None
|
|
|
|
|
|
# ── the store ────────────────────────────────────────────────────────────────
|
|
def clean_patch(patch: dict) -> dict:
|
|
if not isinstance(patch, dict):
|
|
raise PresetError("patch must be an object")
|
|
unknown = set(patch) - set(FIELDS)
|
|
if unknown:
|
|
raise PresetError(f"unknown field(s): {', '.join(sorted(unknown))}")
|
|
out: dict = {}
|
|
for k, v in patch.items():
|
|
if v is None:
|
|
out[k] = None
|
|
elif k in ("thinking", "favorite", "guests"):
|
|
if not isinstance(v, bool):
|
|
raise PresetError(f"{k} must be true or false")
|
|
out[k] = v
|
|
elif k == "harness":
|
|
if v not in harness_order():
|
|
raise PresetError(f"unknown harness {v!r}")
|
|
out[k] = v
|
|
elif k == "fast":
|
|
if v not in FAST_MODES:
|
|
raise PresetError("fast is '', 'fast' or 'ultrafast'")
|
|
out[k] = v
|
|
else: # effort
|
|
if not isinstance(v, str) or (v and not _EFFORT.match(v)):
|
|
raise PresetError("bad effort level")
|
|
out[k] = v
|
|
return out
|
|
|
|
|
|
class PresetStore:
|
|
def __init__(self, path: str = PATH):
|
|
self.path = pathlib.Path(path)
|
|
self._lock = threading.Lock()
|
|
try:
|
|
data = json.loads(self.path.read_text(encoding="utf-8"))
|
|
except (OSError, ValueError):
|
|
data = {}
|
|
self._models = {k: v for k, v in (data.get("models") or {}).items()
|
|
if isinstance(v, dict) and _KEY.match(k)}
|
|
|
|
def _save(self) -> None:
|
|
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
tmp = self.path.with_suffix(".tmp")
|
|
tmp.write_text(json.dumps({"models": self._models}, ensure_ascii=False, indent=1),
|
|
encoding="utf-8")
|
|
os.replace(tmp, self.path)
|
|
|
|
def stored(self) -> dict[str, dict]:
|
|
with self._lock:
|
|
return copy.deepcopy(self._models)
|
|
|
|
def patch(self, key: str, patch: dict) -> dict:
|
|
"""Merge ``patch`` (None clears a field) into ``key``'s stored preset;
|
|
returns what is stored now."""
|
|
if not _KEY.match(key or ""):
|
|
raise PresetError(f"bad model key {key!r}")
|
|
p = clean_patch(patch)
|
|
with self._lock:
|
|
cur = {k: v for k, v in (self._models.get(key) or {}).items() if k != "updatedAt"}
|
|
for k, v in p.items():
|
|
if v is None:
|
|
cur.pop(k, None)
|
|
else:
|
|
cur[k] = v
|
|
if cur:
|
|
cur["updatedAt"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
|
self._models[key] = cur
|
|
else:
|
|
self._models.pop(key, None)
|
|
self._save()
|
|
return copy.deepcopy(cur)
|
|
|
|
|
|
_store: PresetStore | None = None
|
|
_store_lock = threading.Lock()
|
|
|
|
|
|
def store() -> PresetStore:
|
|
"""The hub's one store (a module singleton: ``users/runs.check_model``
|
|
reads the guest pool without the app state at hand)."""
|
|
global _store
|
|
with _store_lock:
|
|
if _store is None:
|
|
_store = PresetStore(PATH)
|
|
return _store
|
|
|
|
|
|
def set_store(s: PresetStore | None) -> None:
|
|
"""Tests: point the singleton at a temp file (None resets it)."""
|
|
global _store
|
|
with _store_lock:
|
|
_store = s
|
|
|
|
|
|
def presets(models: list[dict]) -> dict[str, dict]:
|
|
"""Every listed key's resolved preset."""
|
|
stored = store().stored()
|
|
return {k: resolve(stored.get(k), k, hs) for k, hs in harnesses_by_key(models).items()}
|
|
|
|
|
|
def guest_pool(models: list[dict] | None = None) -> set[str]:
|
|
"""The keys guests may run (each guest's own list narrows it)."""
|
|
from models import catalog
|
|
return {k for k, p in presets(models if models is not None else catalog.list_models()).items()
|
|
if p.get("guests")}
|