176 lines
6.8 KiB
Python
176 lines
6.8 KiB
Python
"""
|
|
The live usage readers — which ``SidecarUsageReader`` keeps each vendor's
|
|
plan-usage snapshots (typed-plugins spec §3.3) — and the provider plugins'
|
|
non-secret config every harness driver and local-model helper reads.
|
|
|
|
The providers' twin of ``harness_loader``, on the same ``DriverLoader``: the
|
|
hub materializes every enabled ``provider-*`` plugin's ``usageReader`` code +
|
|
``plugin.json`` + non-secret ``config.json`` under ``SIDECAR_LIVE_PROVIDERS_DIR``
|
|
(the host: ``/data/plugins/live-providers``; a worker: ``~/.ai-agent-worker/providers``)
|
|
with an ``index.json`` (``{"providers": {vendorId: {pluginId, dir, entry,
|
|
hash}}}``); a reader module exposes ``create(ctx)`` / ``reader`` /
|
|
``Reader``. Same atomic swap, rollback, ``.lkg`` copy and — on the host — the
|
|
seed plugins (``SIDECAR_SEED_PLUGINS_DIR``) when nothing was materialized yet.
|
|
|
|
**Strict plugin-only**: a vendor no plugin reads has no Plan % here. A
|
|
provider with no reader (provider-openrouter) still counts: its manifest and
|
|
config are in :func:`provider_configs`, and :func:`evox2` is the EVOX2's
|
|
servers and Wake-on-LAN target out of provider-evox2's. A provider's module
|
|
may also be a plain ``sidecar`` one (``provider.sidecar``) with hooks the core
|
|
calls: :func:`live_progress`, :func:`before_launch`, and ``extra_routers()``
|
|
(mounted by routes_harnesses) — provider-evox2's ``/local-ready``.
|
|
|
|
The routes: ``GET /usage/{vendor_id}`` (a vendor id, or a legacy alias —
|
|
``claude`` / ``opencode`` / ``agy``), and the legacy ``/claude/usage``,
|
|
``/opencode/usage``, ``/agy/usage`` kept forwarding here so a worker on an
|
|
older hub and a hub on an older worker both keep reading Plan %.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import harness_base
|
|
from harness_loader import DriverLoader
|
|
|
|
LOADER = DriverLoader(
|
|
kind="provider", index_key="providers", manifest_key="provider", id_key="vendorId",
|
|
code_key=("usageReader", "sidecar"), default_entry="usage.py", check=harness_base.check_reader,
|
|
factories=("create", "reader", "Reader"),
|
|
root_env="SIDECAR_LIVE_PROVIDERS_DIR", host_root="/data/plugins/live-providers",
|
|
worker_root="~/.ai-agent-worker/providers")
|
|
|
|
# The legacy harness-named ids the routes still take, by vendor — a reader
|
|
# may add its own with an ``aliases`` attribute.
|
|
LEGACY_ALIASES = {"claude": "anthropic", "opencode": "openai", "agy": "google"}
|
|
|
|
|
|
def get(vendor: str | None):
|
|
"""The reader for a vendor id or one of its aliases (``claude`` → anthropic)."""
|
|
r = LOADER.get(vendor)
|
|
if r is not None:
|
|
return r
|
|
v = (vendor or "").strip().lower()
|
|
if v in LEGACY_ALIASES:
|
|
r = LOADER.get(LEGACY_ALIASES[v])
|
|
if r is not None:
|
|
return r
|
|
for d in LOADER.drivers():
|
|
if v in (getattr(d, "aliases", ()) or ()):
|
|
return d
|
|
return None
|
|
|
|
|
|
def vendor_ids() -> tuple[str, ...]:
|
|
return LOADER.ids()
|
|
|
|
|
|
def snapshots(vendor: str) -> dict[str, dict] | None:
|
|
"""``{accountId: rate-limits dict}`` of a vendor, or None when no reader
|
|
knows it."""
|
|
r = get(vendor)
|
|
if r is None:
|
|
return None
|
|
return r.snapshots() or {}
|
|
|
|
|
|
def refresh_soon(vendor: str, account: str | None = None) -> None:
|
|
r = get(vendor)
|
|
if r is not None:
|
|
r.refresh_soon(account)
|
|
|
|
|
|
def provider_configs() -> dict:
|
|
"""``{vendorId: {pluginId, dir, config, manifest}}`` of every live
|
|
provider plugin, reader or not — ``dir`` the plugin dir (its
|
|
``plugin.json``), ``config`` its non-secret config (``config.json``:
|
|
``{config, accounts}`` as the hub writes it), ``manifest`` its
|
|
``provider`` object. What the harness drivers get as
|
|
``SidecarContext.providers``."""
|
|
return {k: {"pluginId": v["pluginId"], "dir": v["dir"], "config": v["config"],
|
|
"manifest": v["manifest"]}
|
|
for k, v in LOADER.configs().items()}
|
|
|
|
|
|
def evox2() -> dict:
|
|
"""The EVOX2 out of provider-evox2's manifest: ``{servers: {name: {root,
|
|
url, port, api}}, wolMac, wolBroadcast, host}`` — ``root`` the server's
|
|
URL without ``/v1``. Empty maps / None when the plugin isn't here (then
|
|
nothing is local: no server to wake or to read)."""
|
|
spec = provider_configs().get("evox2") or {}
|
|
man = spec.get("manifest") or {}
|
|
servers = {}
|
|
for name, s in (man.get("servers") or {}).items():
|
|
if isinstance(s, dict) and isinstance(s.get("url"), str):
|
|
url = s["url"].rstrip("/")
|
|
servers[name] = {"url": url, "root": url.removesuffix("/v1"),
|
|
"port": s.get("port"), "api": s.get("api")}
|
|
infra = man.get("localInfra") if isinstance(man.get("localInfra"), dict) else {}
|
|
models = [m for m in man.get("models") or [] if isinstance(m, dict) and m.get("id")]
|
|
return {"servers": servers, "wolMac": infra.get("wolMac"),
|
|
"wolBroadcast": infra.get("wolBroadcast"), "host": infra.get("host"),
|
|
"models": models}
|
|
|
|
|
|
def live_progress(sid: str) -> dict | None:
|
|
"""A live run's generation progress (``GET /sessions`` → ``progress``),
|
|
from the first provider module that reads one (provider-evox2's
|
|
gen_progress); None without one."""
|
|
for d in LOADER.drivers():
|
|
fn = getattr(d, "live_progress", None)
|
|
if not callable(fn):
|
|
continue
|
|
try:
|
|
p = fn(sid)
|
|
except Exception: # noqa: BLE001 — a reading never fails /sessions
|
|
continue
|
|
if p:
|
|
return p
|
|
return None
|
|
|
|
|
|
def before_launch(harness: str | None, model: str | None) -> None:
|
|
"""Every provider module's pre-launch hook (provider-evox2: free the other
|
|
local servers' idle models). Never raises, never blocks."""
|
|
for d in LOADER.drivers():
|
|
fn = getattr(d, "before_launch", None)
|
|
if callable(fn):
|
|
try:
|
|
fn(harness, model)
|
|
except Exception: # noqa: BLE001
|
|
pass
|
|
|
|
|
|
def local_target(harness: str | None, model: str | None) -> dict | None:
|
|
"""``{root, key, model}`` of the local server for ``(harness, model)``, from
|
|
the first provider module that serves it (provider-evox2); None without one."""
|
|
for d in LOADER.drivers():
|
|
fn = getattr(d, "local_target", None)
|
|
if callable(fn):
|
|
try:
|
|
t = fn(harness, model)
|
|
except Exception: # noqa: BLE001
|
|
continue
|
|
if t:
|
|
return t
|
|
return None
|
|
|
|
|
|
def local_ready(harness: str | None, model: str | None, timeout: int = 30) -> dict:
|
|
"""Wake and load a local model via the first provider module that supports it."""
|
|
for d in LOADER.drivers():
|
|
fn = getattr(d, "local_ready", None)
|
|
if callable(fn):
|
|
return fn(harness, model, timeout)
|
|
return {"ready": False, "reason": "no local provider loaded"}
|
|
|
|
|
|
def reload(force: bool = False) -> dict:
|
|
return LOADER.reload(force)
|
|
|
|
|
|
def startup() -> dict:
|
|
return LOADER.startup()
|
|
|
|
|
|
def public() -> dict:
|
|
return LOADER.public()
|