Files
ai-agent/backend/plugins/providers.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

1427 lines
60 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""The provider & harness registry — every model, price, account and agent
harness the hub knows, read from the owner's enabled ``kind: "provider"`` and
``kind: "harness"`` plugins (homelab spec
``data/log/2026-11-26-ai-agent-typed-plugins-spec.md`` §2).
Built in process and cached on ``PluginStore.version`` (the same pattern as
``plugins/resources.py``): a parse prices thousands of calls, so nothing here
spawns a process or waits on the network — live model discovery (Anthropic's
``/v1/models``, APPE's OpenRouter catalogue) refreshes in a background thread,
with a disk copy so a cold start still answers.
**Pricing is a port, not a rewrite**: ``price_call`` / ``rates_for`` /
``plan_units`` / ``local_call`` give the exact floats
``conversations/pricing.py`` gives for the same tables (the operations run in
the same order — ``test_typed_plugins`` checks it bit for bit). The vendor a
model id belongs to is decided by each provider's ``pricing`` matcher, tried by
``matchOrder``; the provider whose pricing says ``catchAll`` prices whatever no
one claimed (Anthropic's newest Opus, as ``pricing.rates_for`` does).
A provider disabled later must not break the pricing of the transcripts it
already priced: the last pricing tables seen are kept (in memory and in
``<PLUGINS_DIR>/pricing-snapshot.json``) and price an id no active provider
claims.
Wave 1A only *adds* this: ``conversations/pricing.py``, ``models/catalog.py``
and ``accounts/profiles.py`` still answer every caller until the Wave 3
cutover.
"""
from __future__ import annotations
import copy
import dataclasses
import json
import logging
import os
import pathlib
import re
import threading
import time
import urllib.error
import urllib.request
from typing import Any
log = logging.getLogger(__name__)
DISCOVERY_TTL_S = 6 * 3600
DEFAULT_CONTEXT_WINDOW = 200_000
_GUEST_RE = re.compile(r"guest-([a-z0-9][a-z0-9-]{0,39})")
# ── small helpers ────────────────────────────────────────────────────────────
def norm_usage(u: dict) -> dict:
"""``conversations.pricing.norm_usage`` (an already-normalized block is
returned as is)."""
if "cacheWriteUnits" in u:
return u
cc = u.get("cache_creation") or {}
c5 = cc.get("ephemeral_5m_input_tokens", 0) or 0
c1 = cc.get("ephemeral_1h_input_tokens", 0) or 0
flat = u.get("cache_creation_input_tokens", 0) or 0
split = c5 + c1
return {
"input": u.get("input_tokens", 0) or 0,
"output": u.get("output_tokens", 0) or 0,
"cacheRead": u.get("cache_read_input_tokens", 0) or 0,
"cacheWriteTokens": split if split else flat,
"cacheWriteUnits": (c5 * 1.25 + c1 * 2.0) if split else flat * 1.25,
}
def _cost(u: dict, rates) -> float:
pi, po, pc = (r / 1e6 for r in rates[:3])
return (u["input"] * pi + u["cacheWriteUnits"] * pi
+ u["cacheRead"] * pc + u["output"] * po)
def _prompt(u: dict) -> int:
return int(u["input"] + u["cacheRead"] + u["cacheWriteTokens"])
def _find_close(s: str, i: int) -> int:
depth = 0
for j in range(i, len(s)):
if s[j] == "{":
depth += 1
elif s[j] == "}":
depth -= 1
if depth == 0:
return j
return -1
def render_template(tpl: str, vars: dict[str, Any]) -> str:
"""A harness ``argTemplate``: ``{name}``, ``{name|default}`` and
``{name?then:else}`` (the branches may hold placeholders themselves)."""
out: list[str] = []
i = 0
while i < len(tpl):
c = tpl[i]
if c != "{":
out.append(c)
i += 1
continue
j = _find_close(tpl, i)
if j < 0:
out.append(tpl[i:])
break
body = tpl[i + 1:j]
i = j + 1
q = body.find("?")
if q > 0 and "{" not in body[:q]:
name, rest = body[:q], body[q + 1:]
# the ':' at depth 0 splits then / else
depth, cut = 0, -1
for k, ch in enumerate(rest):
if ch == "{":
depth += 1
elif ch == "}":
depth -= 1
elif ch == ":" and depth == 0:
cut = k
break
then, other = (rest, "") if cut < 0 else (rest[:cut], rest[cut + 1:])
out.append(render_template(then if vars.get(name) else other, vars))
continue
name, _, default = body.partition("|")
v = vars.get(name)
out.append(str(v) if v not in (None, "") else default)
return "".join(out)
# ── specs ────────────────────────────────────────────────────────────────────
@dataclasses.dataclass
class ProviderSpec:
vendor_id: str
plugin_id: str
spec: dict
config: dict
active: bool = True
@property
def order(self) -> int:
return int(self.spec.get("order") or 100)
@property
def pricing(self) -> dict | None:
return self.spec.get("pricing")
@dataclasses.dataclass
class HarnessSpec:
harness_id: str
plugin_id: str
spec: dict
config: dict
@property
def order(self) -> int:
return int(self.spec.get("order") or 100)
@dataclasses.dataclass
class CallCost:
"""One API call's money: list ``cost`` (the record's own ``costUSD`` when
the harness reported one, the box's time on the EVOX2), the replayed
cache's share of it, the plan units it weighs, and the local breakdown."""
cost: float
cache_cost: float
plan_units: float
vendor: str | None
source: str # "table" | "record" | "local"
local: dict | None = None
def as_dict(self) -> dict:
return dataclasses.asdict(self)
# ── a compiled pricing table ─────────────────────────────────────────────────
class _Pricer:
"""One provider's ``pricing`` block, compiled."""
def __init__(self, vendor: str, pricing: dict, models: list[dict], twin_regexes: list[str]):
self.vendor = vendor
self.p = pricing
self.kind = pricing["kind"]
self.order = int(pricing.get("matchOrder") or 100)
self.catch_all = bool(pricing.get("catchAll"))
self.fast = pricing.get("fastMult")
self.id_re = re.compile(pricing["idRegex"]) if pricing.get("idRegex") else None
self.bare_re = re.compile(pricing["bareIdRegex"]) if pricing.get("bareIdRegex") else None
self.table: dict[str, list[float]] = pricing.get("models") or {}
norm = pricing.get("normalize") or {}
self.suffix_re = re.compile(norm["stripSuffixRegex"]) if norm.get("stripSuffixRegex") else None
self.level_re = re.compile(norm["stripLevelRegex"]) if norm.get("stripLevelRegex") else None
self.split_prefixes = list(norm.get("splitPrefixes") or [])
self.model_ids = {m["id"] for m in models}
self.watts = {m["id"]: m["watts"] for m in models if m.get("watts") is not None}
self.twin_res = [re.compile(r) for r in twin_regexes]
# openrouter_catalogue: id → APPE row, read lazily (the background
# discovery may land after the registry was built)
self.catalogue_fn = lambda: {}
self._key_memo: dict[str, tuple[str, str | None] | None] = {}
# matching ---------------------------------------------------------------
def _token_key(self, model: str) -> tuple[str, str | None] | None:
"""(book key, mode) for a token_table id, or None (memoized: the
table is fixed for the pricer's life)."""
raw = model or ""
memo = self._key_memo
if raw in memo:
return memo[raw]
hit = self._token_key_uncached(raw)
if len(memo) < 4096:
memo[raw] = hit
return hit
def _token_key_uncached(self, raw: str) -> tuple[str, str | None] | None:
m = raw.lower().strip()
if self.suffix_re is not None:
m = self.suffix_re.sub("", m)
for pre in self.split_prefixes:
if m.startswith(pre):
m = m[len(pre):]
break
if "/" in raw:
return None
mode = None
if self.id_re is not None:
hit = self.id_re.match(m)
if not hit:
return None
gd = hit.groupdict()
if gd.get("base"):
m = gd["base"]
mode = gd.get("mode")
if self.level_re is not None:
m = self.level_re.sub("", m.strip())
if m in self.table:
return m, mode
if self.id_re is not None:
for line, key in (self.p.get("lineFallback") or {}).items():
if m.endswith(f"-{line}") or f"-{line}-" in m:
return key, mode
if self.p.get("prefixFallback"):
for key in self.table:
if m.startswith(key):
return key, mode
excl = self.p.get("familyExclude") or []
for fam, key in (self.p.get("familyFallback") or {}).items():
if fam in m and not any(x in m for x in excl):
return key, mode
if self.id_re is not None and self.p.get("defaultModel"):
return self.p["defaultModel"], mode
return None
def local_base(self, model: str | None) -> str | None:
"""The model a twin id runs (``evox2-inkling/inkling-2-mini`` →
``inkling-2-mini``), else None."""
for rx in self.twin_res:
hit = rx.match(model or "")
if hit and (model or "")[hit.end():]:
return (model or "")[hit.end():]
return None
def is_local(self, model: str | None) -> bool:
if self.kind != "local_energy":
return False
return (model or "") in self.model_ids or bool(self.local_base(model))
def claims(self, model: str) -> bool:
if self.kind == "token_table":
return self._token_key(model) is not None
if self.kind == "local_energy":
if self.is_local(model):
return True
m = (model or "").lower()
return bool(self.bare_re and self.bare_re.search(m) and "/" not in m)
if self.kind == "openrouter_catalogue":
return bool(self.id_re.search(model or "")) if self.id_re else "/" in (model or "")
return False
# rates ------------------------------------------------------------------
def rates(self, model: str, prompt: int = 0) -> tuple[list[float], str | None]:
"""(rates [in, out, cache(, write)], book key) at a prompt size."""
if self.kind == "local_energy":
return [0.0, 0.0, 0.0], None
if self.kind == "openrouter_catalogue":
hit = self.catalogue_fn().get((model or "").strip())
if hit:
cache = hit["cacheCost"] if hit["cacheCost"] is not None else hit["inputCost"]
return [hit["inputCost"], hit["outputCost"], cache], None
return list(self.p.get("fallbackRates") or [0.0, 0.0, 0.0]), None
tk = self._token_key(model)
if tk is None:
return list(self.p.get("fallbackRates") or [0.0, 0.0, 0.0]), None
key, mode = tk
r = list(self.table[key])
modes = self.p.get("modes") or {}
if modes:
mult = (self.p.get("modeExceptions") or {}).get(f"{key}:{mode}",
modes.get(mode or "", 1.0))
r = [x * mult for x in r]
for t in self.p.get("longPromptTiers") or []:
if "rates" not in t or not self._tier_applies(t, key):
continue
if prompt > t["threshold"]:
ri, ro, rc = t["rates"]
pi, po, pc = r[0], r[1], r[2]
r = [pi * ri, po * ro, pc * rc] + ([r[3] * ri] if len(r) > 3 else [])
return r, key
def _tier_applies(self, t: dict, key: str | None) -> bool:
if t.get("model") is not None:
return key == t["model"]
if t.get("models") is not None:
return key in t["models"]
if t.get("prefix") is not None:
return bool(key) and key.startswith(t["prefix"])
return True
def mult(self, u: dict, key: str | None, speed: str | None) -> float:
"""The per-call multiplier ``pricing._tier_mult`` applies (fast mode,
a scalar long-prompt tier). 1.0 for a table without either."""
if self.fast is None and not any("mult" in t for t in self.p.get("longPromptTiers") or []):
return 1.0
mult = self.fast if (speed == "fast" and self.fast is not None) else 1.0
for t in self.p.get("longPromptTiers") or []:
if "mult" in t and key is not None and self._tier_applies(t, key) \
and (u["input"] + u["cacheRead"] + u["cacheWriteTokens"]) > t["threshold"]:
mult *= t["mult"]
return mult
# local ------------------------------------------------------------------
def local_call(self, model: str | None, ms: float | None, ts: str | None) -> dict:
p = self.p
s = min(max((ms or 0) / 1000, 0.0), p["callCapSeconds"])
base = self.local_base(model) or model or ""
watts = self.watts.get(base, p["defaultWatts"])
wh = watts * s / 3600
day = (ts or "9999")[:10]
tariffs = p["electricityTariffs"]
price = tariffs[0][1]
for since, eur in tariffs:
if day >= since:
price = eur
hw_per_hour = p["hardwarePriceEur"] / (p["lifetimeYears"] * p["busyHoursPerYear"])
return {
"seconds": s,
"wh": wh,
"electricity": wh / 1000 * price * p["usdPerEur"],
"hardware": s / 3600 * hw_per_hour * p["usdPerEur"],
}
# ── the registry ─────────────────────────────────────────────────────────────
class ProviderRegistry:
def __init__(self, providers: list[ProviderSpec], harnesses: list[HarnessSpec], *,
version: int = 0, sig: str = "", snapshot: dict | None = None,
discovery_dir: pathlib.Path | None = None):
self.version = version
self.sig = sig
self.providers: dict[str, ProviderSpec] = {
p.vendor_id: p for p in sorted(providers, key=lambda p: (p.order, p.vendor_id))}
self.harnesses: dict[str, HarnessSpec] = {
h.harness_id: h for h in sorted(harnesses, key=lambda h: (h.order, h.harness_id))}
self._discovery_dir = discovery_dir
twin_by_vendor: dict[str, list[str]] = {}
for h in self.harnesses.values():
for s in h.spec.get("supports") or []:
if s.get("stripPrefixRegex"):
twin_by_vendor.setdefault(s["vendor"], []).append(s["stripPrefixRegex"])
self._pricers: list[_Pricer] = []
for p in self.providers.values():
if p.pricing:
twin = list(twin_by_vendor.get(p.vendor_id) or [])
if p.pricing.get("kind") == "local_energy" and p.pricing.get("idRegex"):
twin.append(p.pricing["idRegex"])
self._pricers.append(_Pricer(p.vendor_id, p.pricing, p.spec.get("models") or [], twin))
# A vendor no longer active still prices its historical ids.
active = {pr.vendor for pr in self._pricers}
self._stale_pricers: list[_Pricer] = []
for vid, snap in (snapshot or {}).items():
if vid in active or not isinstance(snap, dict) or not snap.get("pricing"):
continue
try:
self._stale_pricers.append(_Pricer(vid, snap["pricing"], snap.get("models") or [],
snap.get("twin") or []))
except Exception: # noqa: BLE001 — a damaged snapshot prices nothing
continue
self._pricers.sort(key=lambda p: p.order)
self._stale_pricers.sort(key=lambda p: p.order)
for pr in self._pricers + self._stale_pricers:
if pr.kind == "openrouter_catalogue":
pr.catalogue_fn = (lambda v=pr.vendor: _discovery_index(self, v))
self._entries_memo: tuple[Any, list[dict]] | None = None
# model id → the pricer that claims it (the tables are fixed per
# registry; the parser asks for every call)
self._pricer_memo: dict[str, _Pricer | None] = {}
self._accounts = self._build_accounts()
self._alias = {al: a["id"] for a in self._accounts for al in a.get("aliases") or []}
self._acct_by_id = {a["id"]: a for a in self._accounts}
# ids ---------------------------------------------------------------------
def harness_ids(self) -> tuple[str, ...]:
return tuple(self.harnesses)
def vendor_ids(self) -> tuple[str, ...]:
return tuple(self.providers)
def login_vendors(self) -> tuple[str, ...]:
out = []
for vid, p in self.providers.items():
if p.spec.get("keyless"):
continue
if any(not a.get("keyless") for a in self.accounts_for_vendor(vid)):
out.append(vid)
return tuple(out)
def snapshot(self) -> dict:
"""What :func:`_save_snapshot` keeps: each active vendor's pricing."""
out = {}
for pr in self._pricers:
prov = self.providers.get(pr.vendor)
out[pr.vendor] = {"pricing": pr.p,
"models": [{"id": m["id"], "watts": m.get("watts")}
for m in (prov.spec.get("models") if prov else []) or []],
"twin": [r.pattern for r in pr.twin_res]}
return out
# accounts ------------------------------------------------------------------
def _build_accounts(self) -> list[dict]:
out: list[dict] = []
for vid, p in self.providers.items():
base = [copy.deepcopy(a) for a in p.spec.get("accounts") or []]
edits = p.config.get("accounts") if isinstance(p.config.get("accounts"), list) else []
by_id = {a["id"]: a for a in base}
order = [a["id"] for a in base]
for e in edits:
if not isinstance(e, dict) or not e.get("id"):
continue
if e.get("removed"):
by_id.pop(e["id"], None)
continue
if e["id"] in by_id:
by_id[e["id"]].update({k: v for k, v in e.items() if k not in ("id", "removed")})
else:
by_id[e["id"]] = dict(e)
order.append(e["id"])
for aid in order:
if aid not in by_id:
continue
a = by_id[aid]
a.setdefault("aliases", [])
a["vendor"] = vid
a["pluginId"] = p.plugin_id
if p.spec.get("keyless"):
a["keyless"] = True
out.append(a)
return out
def accounts(self) -> list[dict]:
return [dict(a) for a in self._accounts]
def resolve_alias(self, aid: str | None) -> str:
a = (aid or "").strip().lower()
return self._alias.get(a, a)
def account(self, aid: str | None) -> dict | None:
a = self.resolve_alias(aid)
hit = self._acct_by_id.get(a)
if hit:
return dict(hit)
m = _GUEST_RE.fullmatch(a)
if m:
uid = m.group(1)
vendor = next((v for v in self.providers
if (self.providers[v].spec.get("discovery") or {}).get("kind") == "anthropic_models"),
next(iter(self.providers), None))
return {"id": a, "label": f"{uid} (own Claude)",
"description": f"Guest {uid}'s own Claude subscription.",
"color": "violet", "configDir": None, "excludeFromTotals": True,
"default": False, "guest": uid, "vendor": vendor, "aliases": []}
return None
def accounts_for_vendor(self, vid: str) -> list[dict]:
return [dict(a) for a in self._accounts if a["vendor"] == vid]
def vendor_of_account(self, aid: str | None) -> str | None:
a = self.account(aid)
return a.get("vendor") if a else None
def default_account(self) -> str | None:
"""The account flagged ``default`` (the first one, else none)."""
hit = next((a for a in self._accounts if a.get("default")), None) \
or next(iter(self._accounts), None)
return hit["id"] if hit else None
# harness ↔ vendor ------------------------------------------------------------
def vendors_of_harness(self, hid: str | None) -> list[str]:
"""The vendors a harness runs (its ``supports[]``, active ones only)."""
h = self.harnesses.get((hid or "").lower())
if h is None:
return []
return [s["vendor"] for s in h.spec.get("supports") or []
if s.get("vendor") in self.providers]
def harnesses_of_vendor(self, vid: str | None) -> list[str]:
"""The harnesses that run a vendor's models, in harness order."""
return [hid for hid in self.harnesses if vid in self.vendors_of_harness(hid)]
def login_harness(self, vid: str | None) -> str | None:
"""The harness an account of ``vid`` is a login *of* — the first that
runs it and signs in (``loginMode`` other than ``none``), else the
first that runs it (anthropic → claude, openai → opencode, google →
agy, evox2 → opencode, openrouter → pi)."""
hs = self.harnesses_of_vendor(vid)
signs = [h for h in hs if (self.harnesses[h].spec.get("loginMode") or "none") != "none"]
return (signs or hs or [None])[0]
def hosted_harnesses(self) -> tuple[str, ...]:
"""The harnesses whose logins a machine hosts and declares in its
``/health`` (``loginMode`` ``worker`` / ``machine``: opencode, agy)."""
return tuple(h for h, spec in self.harnesses.items()
if spec.spec.get("loginMode") in ("worker", "machine"))
def accounts_for_harness(self, hid: str | None) -> list[dict]:
"""The accounts a run on ``hid`` can bill: those of every vendor it
runs, in vendor order."""
vs = self.vendors_of_harness(hid)
return [dict(a) for v in self.providers if v in vs for a in self._accounts
if a["vendor"] == v]
def provider_config(self, vid: str) -> dict:
p = self.providers.get(vid)
return dict(p.config) if p else {}
def provider_secret(self, vid: str, key: str) -> str | None:
"""A provider plugin's hub secret (``None`` when unbound or unset)."""
p = self.providers.get(vid)
if p is None or _SECRET_GETTER is None:
return None
try:
return _SECRET_GETTER(p.plugin_id, key)
except Exception: # noqa: BLE001
return None
# models --------------------------------------------------------------------
def canonical_models(self) -> list[dict]:
"""Every active provider's models (``vendor`` stamped), live discovery
merged in where the provider declares one."""
out: list[dict] = []
for vid, p in self.providers.items():
for m in _models_of(self, p):
out.append({**m, "vendor": vid})
return out
def _model_vars(self, m: dict, vendor: str) -> dict:
return {"id": m["id"], "server": m.get("server"), "family": m.get("family"),
"key": m.get("key"), "vendor": vendor}
def catalog_entries(self, *, annotated: bool = False) -> list[dict]:
"""The ``/api/models`` list: one entry per (model, harness, fast mode),
from active ``provider.models`` × active ``harness.supports[]``."""
stamp = tuple(id(v[1]) for v in _disc_cache.values())
memo = self._entries_memo
if memo is not None and memo[0] == stamp:
rows = [dict(e) for e in memo[1]]
return [self._annotate(e) for e in rows] if annotated else rows
rows = self._build_entries()
self._entries_memo = (stamp, rows)
rows = [dict(e) for e in rows]
return [self._annotate(e) for e in rows] if annotated else rows
def _build_entries(self) -> list[dict]:
by_vendor: dict[str, list[dict]] = {}
for m in self.canonical_models():
by_vendor.setdefault(m["vendor"], []).append(m)
out: list[dict] = []
for hid, h in self.harnesses.items():
hs = h.spec
rows: list[dict] = []
for sup in hs.get("supports") or []:
vendor = sup["vendor"]
prov = self.providers.get(vendor)
if prov is None:
continue
local = bool(prov.spec.get("local"))
for m in by_vendor.get(vendor, []):
rows.extend(self._entries_for(m, vendor, hid, hs, sup, local, prov))
dm = hs.get("defaultModel")
if dm:
rows.sort(key=lambda e: e["id"] != dm)
out.extend(rows)
return out
def _entries_for(self, m: dict, vendor: str, hid: str, hs: dict, sup: dict,
local: bool, prov: ProviderSpec) -> list[dict]:
tpl = sup.get("argTemplate") or "{id}"
fams = prov.spec.get("families") or {}
ctx = m.get("contextWindow") or (fams.get(m.get("family") or "") or {}).get("defaultContextWindow") \
or DEFAULT_CONTEXT_WINDOW
base: dict[str, Any] = {
"id": render_template(tpl, {**self._model_vars(m, vendor), "fast": ""}),
"displayName": m.get("displayName") or m["id"],
"family": m.get("family"),
"version": m.get("version") or "",
"alias": m.get("alias"),
"latest": bool(m.get("latest", True)),
"harness": hid,
"provider": vendor,
"contextWindow": ctx,
}
if m.get("label"):
base["label"] = m["label"]
if m.get("server"):
base["server"] = m["server"]
if local and m.get("efforts"):
base["twinEfforts"] = list(m["efforts"])
if hs.get("modelEfforts"):
base["efforts"] = list(m.get("efforts") or sup.get("defaultEfforts") or [])
rows = [base]
if sup.get("expandFastModes"):
base["fast"] = False
for mode in m.get("fastModes") or []:
v = {**base,
"id": render_template(tpl, {**self._model_vars(m, vendor), "fast": mode}),
"displayName": f"{base['displayName']} ({mode})",
"latest": False, "fast": True}
if base.get("label"):
v["label"] = f"{base['label']} {mode}"
if "efforts" in base:
v["efforts"] = list(base["efforts"])
rows.append(v)
return rows
def _annotate(self, e: dict) -> dict:
"""``models.presets.annotate`` for one synthesized entry."""
key = self.key_of(e)
out = {**e, "key": key, "vendor": e.get("provider")}
if e.get("fast"):
hit = re.search(r"-(fast|ultrafast)$", e["id"])
out["fastMode"] = hit.group(1) if hit else ""
return out
def key_of(self, e: dict) -> str:
"""The preset key of a catalogue entry: the provider model's ``key``
(a Claude family, a twin's pi id, a GPT tier's base id)."""
vendor = e.get("provider")
prov = self.providers.get(vendor or "")
mid = e.get("id") or ""
if prov is None:
return mid
h = self.harnesses.get(e.get("harness") or "")
sup = next((s for s in (h.spec.get("supports") or []) if s["vendor"] == vendor), None) if h else None
base_id = mid
if sup and sup.get("stripPrefixRegex"):
base_id = re.sub(sup["stripPrefixRegex"], "", mid, count=1)
for m in _models_of(self, prov):
if m["id"] == base_id or (e.get("fast") and base_id.startswith(m["id"] + "-")):
return m.get("key") or m["id"]
return base_id
def _pricer_for(self, model: str | None) -> _Pricer | None:
m = model or ""
memo = self._pricer_memo
if m in memo:
return memo[m]
hit = next((pr for pr in self._pricers if pr.claims(m)), None) \
or next((pr for pr in self._stale_pricers if pr.claims(m)), None)
if len(memo) < 4096: # every claim is by id shape alone: fixed per registry
memo[m] = hit
return hit
def _catch_all(self) -> _Pricer | None:
return next((p for p in self._pricers + self._stale_pricers if p.catch_all), None)
def vendor_of_model(self, model_id: str | None) -> str | None:
pr = self._pricer_for(model_id)
if pr is not None:
return pr.vendor
for m in self.canonical_models():
if m["id"] == model_id:
return m["vendor"]
return None
def is_local(self, model_id: str | None) -> bool:
return any(pr.is_local(model_id) for pr in self._pricers + self._stale_pricers)
def context_window(self, model_id: str | None) -> int:
mid = model_id or ""
entries = self.catalog_entries()
# an anthropic id goes by its family (the API's window isn't kept per id)
for e in entries:
if e["id"] == mid and e.get("contextWindow") and not self._family_priced(e):
return e["contextWindow"]
for pr in self._pricers:
if pr.level_re is not None:
base = pr.level_re.sub("", mid.strip())
for e in entries:
if e["id"] == base and e.get("provider") == pr.vendor and e.get("contextWindow"):
return e["contextWindow"]
low = mid.lower()
for p in self.providers.values():
for fam, spec in (p.spec.get("families") or {}).items():
if fam in low and spec.get("defaultContextWindow"):
return spec["defaultContextWindow"]
return DEFAULT_CONTEXT_WINDOW
def _family_priced(self, e: dict) -> bool:
prov = self.providers.get(e.get("provider") or "")
return bool(prov and (prov.spec.get("discovery") or {}).get("kind") == "anthropic_models")
def default_guest_keys(self) -> tuple[str, ...]:
out: list[str] = []
for m in self.canonical_models():
if m.get("defaultGuest"):
k = m.get("key") or m["id"]
if k not in out:
out.append(k)
return tuple(out)
# pricing -------------------------------------------------------------------
def _rates_mult(self, model: str, u: dict | None, speed: str | None):
claimed = self._pricer_for(model)
pr = claimed or self._catch_all()
if pr is None:
return None, [0.0, 0.0, 0.0], 1.0, None
if claimed is None: # nobody claims it: the catch-all's fallback
rates, key = list(pr.p.get("fallbackRates") or [0.0, 0.0, 0.0]), None
else:
rates, key = pr.rates(model, _prompt(u) if u is not None else 0)
mult = pr.mult(u, key, speed) if u is not None else 1.0
return pr, rates, mult, key
def rates_for(self, model_id: str, speed: str | None = None) -> tuple[float, float, float]:
"""(input, output, cache-read) $/Mtok — ``pricing.rates_for``."""
_pr, rates, _m, _k = self._rates_mult(model_id, None, speed)
return rates[0], rates[1], rates[2]
def usage_cost(self, model_id: str, usage: dict, speed: str | None = None) -> float:
u = norm_usage(usage)
_pr, rates, mult, _k = self._rates_mult(model_id, u, speed)
return _cost(u, rates) * mult
def usage_cache_cost(self, model_id: str, usage: dict, speed: str | None = None) -> float:
u = norm_usage(usage)
_pr, rates, mult, _k = self._rates_mult(model_id, u, speed)
return u["cacheRead"] * (rates[2] / 1e6) * mult
def plan_units(self, model_id: str, usage: dict, *, speed: str | None = None) -> float:
"""What a usage block weighs on the subscription's limits — the
provider's ``planMeter`` (``pricing.plan_units``)."""
u = norm_usage(usage)
pr = self._pricer_for(model_id)
if pr is None:
return 0.0
prov = self.providers.get(pr.vendor)
meter = (prov.spec.get("planMeter") if prov else None) or {"kind": "none"}
kind = meter.get("kind") or "none"
if kind == "list_price":
return self.usage_cost(model_id, u, speed)
if kind != "claude_units" or pr.kind != "token_table":
return 0.0
tk = pr._token_key(model_id)
if tk is None:
return 0.0
key = tk[0]
as_key = (meter.get("meterAs") or {}).get(key, key)
units = _cost(u, pr.table[as_key]) * pr.mult(u, key, speed)
for fam, w in (meter.get("familyWeights") or {}).items():
if fam in key:
units *= w
break
return units
def local_call(self, model_id: str | None, ms: float | None, ts: str | None) -> dict:
"""One local call's energy and cost (USD) — ``pricing.local_call``."""
pr = next((p for p in self._pricers + self._stale_pricers
if p.kind == "local_energy" and p.is_local(model_id)), None)
if pr is None:
pr = next((p for p in self._pricers + self._stale_pricers if p.kind == "local_energy"), None)
if pr is None:
return {"seconds": 0.0, "wh": 0.0, "electricity": 0.0, "hardware": 0.0}
return pr.local_call(model_id, ms, ts)
def price_call(self, model_id: str, usage: dict, *, speed: str | None = None,
record: dict | None = None, elapsed_ms: float | None = None,
at: str | None = None) -> CallCost:
"""One API call, priced the way the parser does it
(``conversations/parse/state.py``): the table, then the record's own
``cost.usd`` (pi's runner), then the box's time for a local model."""
u = norm_usage(usage)
cost = self.usage_cost(model_id, u, speed)
source = "table"
real = (record or {}).get("cost")
if isinstance(real, dict) and real.get("usd") is not None:
cost, source = float(real["usd"]), "record"
local = None
if self.is_local(model_id):
local = self.local_call(model_id, elapsed_ms, at)
cost, source = local["electricity"] + local["hardware"], "local"
return CallCost(cost=cost, cache_cost=self.usage_cache_cost(model_id, u, speed),
plan_units=self.plan_units(model_id, u, speed=speed),
vendor=self.vendor_of_model(model_id), source=source, local=local)
# the API -------------------------------------------------------------------
def api_payload(self, *, guest: bool = False) -> dict:
"""``GET /api/providers``: harnesses, vendors, families, price books,
accounts (the owner's; a guest gets no accounts and no config dirs)."""
harnesses = []
for hid, h in self.harnesses.items():
s = h.spec
if guest and not s.get("guestAllowed"):
continue
harnesses.append({
"id": hid, "pluginId": h.plugin_id,
**{k: s.get(k) for k in ("label", "hint", "icon", "color", "order", "knob", "efforts",
"modelEfforts", "caps", "switchTo", "loginMode", "loginFlow",
"runsOn", "guestAllowed", "defaultModel", "defaultEffort")},
"vendors": [x["vendor"] for x in s.get("supports") or []],
})
vendors, families, books = [], {}, {}
for vid, p in self.providers.items():
s = p.spec
vendors.append({
"id": vid, "pluginId": p.plugin_id, "label": s.get("label") or vid,
"order": p.order, "local": bool(s.get("local")), "keyless": bool(s.get("keyless")),
"discovery": (s.get("discovery") or {}).get("kind") or "static",
"families": sorted(s.get("families") or {}),
"planMeter": (s.get("planMeter") or {}).get("kind") or "none",
"login": vid in self.login_vendors(),
})
for fam, f in (s.get("families") or {}).items():
families.setdefault(fam, {**f, "vendor": vid})
pr = s.get("pricing")
if pr:
books[vid] = {k: pr.get(k) for k in (
"kind", "bookDate", "models", "fastMult", "modes",
"modeExceptions", "longPromptTiers", "fallbackRates",
"cacheWrite5mMult", "cacheWrite1hMult",
"idRegex", "bareIdRegex", "familyFallback", "familyExclude",
"lineFallback", "prefixFallback", "defaultModel",
"normalize", "matchOrder", "catchAll",
"defaultWatts", "callCapSeconds", "outputWeight",
"electricityTariffs", "hardwarePriceEur",
"lifetimeYears", "busyHoursPerYear", "usdPerEur",
) if pr.get(k) is not None}
accounts = [] if guest else [
{k: a.get(k) for k in ("id", "label", "description", "color", "vendor", "pluginId",
"planWindows", "weekTarget", "limitAlerts", "excludeFromTotals",
"default", "homeProfile", "keyless", "aliases", "configDir")}
for a in self._accounts]
return {"version": self.version, "harnesses": harnesses, "vendors": vendors,
"families": families, "priceBooks": books, "accounts": accounts,
"defaultGuestKeys": list(self.default_guest_keys())}
# ── live discovery (background, cached 6 h, disk copy) ───────────────────────
_disc_lock = threading.Lock()
# (discovery dir, vendor) → (fetched at, payload); payload is the shaped list
# (anthropic_models) or the APPE index (openrouter_appe).
_disc_cache: dict[tuple[str, str], tuple[float, Any]] = {}
_disc_busy: set[tuple[str, str]] = set()
# vendor → callable(spec, secret) -> payload, for tests and future kinds.
_FETCHERS: dict[str, Any] = {}
def _disc_path(reg: ProviderRegistry, vendor: str) -> pathlib.Path | None:
return (reg._discovery_dir / f"{vendor}.json") if reg._discovery_dir else None
def _disc_get(reg: ProviderRegistry, vendor: str, kind: str, spec: dict, secret: str | None):
"""The cached discovery payload (None when there is none yet); starts a
background refresh when stale. Never blocks on the network."""
key = (str(reg._discovery_dir or ""), vendor)
now = time.time()
with _disc_lock:
hit = _disc_cache.get(key)
if hit is None:
path = _disc_path(reg, vendor)
try:
payload = json.loads(path.read_text(encoding="utf-8")) if path else None
except (OSError, ValueError):
payload = None
hit = (0.0, payload)
_disc_cache[key] = hit
stale = now - hit[0] >= DISCOVERY_TTL_S
start = stale and key not in _disc_busy and (spec.get("url") or kind in _FETCHERS)
if start:
_disc_busy.add(key)
if start and os.environ.get("PROVIDERS_DISCOVERY", "1") != "0":
threading.Thread(target=_disc_refresh, args=(key, reg, vendor, kind, spec, secret),
daemon=True, name=f"discovery-{vendor}").start()
elif start:
with _disc_lock:
_disc_busy.discard(key)
return hit[1]
def _disc_refresh(key, reg, vendor, kind, spec, secret) -> None:
try:
payload = None
fetch = _FETCHERS.get(kind)
if fetch is not None:
payload = fetch(spec, secret)
elif kind == "anthropic_models":
payload = _fetch_anthropic(spec, secret)
elif kind == "openrouter_appe":
payload = _fetch_appe(spec)
if payload:
with _disc_lock:
_disc_cache[key] = (time.time(), payload)
path = _disc_path(reg, vendor)
if path is not None:
try:
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(".tmp")
tmp.write_text(json.dumps(payload), encoding="utf-8")
os.replace(tmp, path)
except OSError:
pass
else:
with _disc_lock: # failed: try again in an hour, keep what we had
old = _disc_cache.get(key) or (0.0, None)
_disc_cache[key] = (time.time() - DISCOVERY_TTL_S + 3600, old[1])
except Exception: # noqa: BLE001
log.exception("provider discovery failed (%s)", vendor)
finally:
with _disc_lock:
_disc_busy.discard(key)
def _fetch_anthropic(spec: dict, secret: str | None) -> list[dict] | None:
key = secret or os.environ.get(spec.get("envFallback") or "", "")
if not key:
return None
req = urllib.request.Request(spec["url"], headers={"x-api-key": key,
"anthropic-version": "2023-06-01"})
try:
with urllib.request.urlopen(req, timeout=10) as r:
data = json.loads(r.read().decode())
except (urllib.error.URLError, OSError, ValueError):
return None
return [{"id": m.get("id"), "displayName": m.get("display_name") or m.get("displayName"),
"max_input_tokens": m.get("max_input_tokens")}
for m in data.get("data") or [] if m.get("id")]
def _fetch_appe(spec: dict) -> dict | None:
req = urllib.request.Request(spec["url"], headers={"accept": "application/json",
"user-agent": "ai-agent/openrouter-catalogue"})
try:
with urllib.request.urlopen(req, timeout=15) as r:
payload = json.loads(r.read().decode())
except (urllib.error.URLError, OSError, ValueError):
return None
return payload if (payload or {}).get("models") else None
def _version(model_id: str, family: str) -> str:
rest = model_id.split(f"{family}-", 1)[-1] if f"{family}-" in model_id else ""
parts = [p for p in rest.split("-") if p.isdigit()]
if parts and len(parts[-1]) == 8:
parts = parts[:-1]
return ".".join(parts)
def _shape_anthropic(raw: list[dict], prov: ProviderSpec) -> list[dict]:
"""``models.catalog._shape``: the newest model of each family."""
disc = prov.spec.get("discovery") or {}
fams = disc.get("families") or list(prov.spec.get("families") or {})
aliases = set(disc.get("cliAliases") or [])
windows = prov.spec.get("families") or {}
static = {m.get("family"): m for m in prov.spec.get("models") or []}
out, seen = [], set()
for m in raw:
mid = m.get("id") or ""
family = next((f for f in fams if re.search(rf"\b{f}\b", mid)), None)
if not family or family in seen:
continue
seen.add(family)
st = static.get(family) or {}
out.append({
"id": mid, "key": family,
"displayName": m.get("displayName") or mid,
"family": family, "version": _version(mid, family),
"alias": family if family in aliases else None, "latest": True,
"contextWindow": m.get("max_input_tokens")
or (windows.get(family) or {}).get("defaultContextWindow") or DEFAULT_CONTEXT_WINDOW,
"efforts": [], "fastModes": [], "server": None, "watts": None,
"defaultGuest": bool(st.get("defaultGuest")),
})
out.sort(key=lambda e: fams.index(e["family"]))
return out
def _secret_for(reg: ProviderRegistry, prov: ProviderSpec) -> str | None:
sk = (prov.spec.get("discovery") or {}).get("secretKey")
getter = _SECRET_GETTER
if not sk or getter is None:
return None
try:
return getter(prov.plugin_id, sk)
except Exception: # noqa: BLE001
return None
def _models_of(reg: ProviderRegistry, prov: ProviderSpec) -> list[dict]:
disc = prov.spec.get("discovery") or {}
kind = disc.get("kind") or "static"
static = [dict(m) for m in prov.spec.get("models") or []]
if kind != "anthropic_models":
return static
raw = _disc_get(reg, prov.vendor_id, kind, disc, _secret_for(reg, prov))
if not raw:
return static
shaped = _shape_anthropic(raw, prov)
return shaped or static
# ── the APPE catalogue (``openrouter_appe`` discovery) ─────────────────────
# What was ``models/openrouter.py`` before 2026-11-26: the provider-openrouter
# plugin declares the catalogue (its discovery ``kind`` + ``url``, its
# ``catalogueUrl`` setting) and the registry fetches it in the background like
# any discovery (6 h, a disk copy under ``PLUGINS_DIR/discovery/``). **The
# prices are APPE's** (https://appe.dev.gabvdl.xyz — models.dev synced daily),
# never a second table here. ``APPE_OPENROUTER_URL`` overrides the URL when no
# plugin says one; the pre-plugin disk copy (``OPENROUTER_CACHE_PATH``) is read
# once while nothing was fetched yet.
APPE_DEFAULT_URL = "https://appe.dev.gabvdl.xyz/api/models/openrouter.json"
def appe_shape(entry: dict) -> dict | None:
"""One APPE catalogue row → one pickable model. ``api_id`` is the id
**without** the ``openrouter/`` prefix — exactly the ``--model`` argument
the pi runner passes to OpenRouter. Prices stay USD per million tokens,
``modelSize`` is billions of parameters (None when unpublished),
``speedTps`` the median output tokens/sec."""
mid = entry.get("api_id") or ""
if not mid:
return None
return {
"id": mid,
"name": entry.get("name") or mid,
"vendor": mid.split("/")[0],
"description": entry.get("description") or "",
"inputCost": float(entry.get("input_cost") or 0.0),
"outputCost": float(entry.get("output_cost") or 0.0),
# None (not 0) when the model has no prompt cache: a missing cache
# price and a free cache are different facts.
"cacheCost": (float(entry["cache_cost"]) if entry.get("cache_cost") is not None else None),
"contextWindow": entry.get("max_token") or None,
"modelSize": entry.get("model_size") or None,
"tags": entry.get("tags") or [],
"tier": entry.get("tier") or "",
"license": entry.get("license") or "",
"speedTps": entry.get("speed_tps") or None,
}
def appe_parse(payload: dict) -> tuple[list[dict], str]:
"""``(models, generatedAt)`` of an APPE payload — cheapest first (blended
3:1 in:out, the usual agent mix), so the browser opens on what a run
costs least to try."""
rows = (payload or {}).get("models") or []
models = [m for m in (appe_shape(r) for r in rows if isinstance(r, dict)) if m]
models.sort(key=lambda m: (m["inputCost"] * 0.75 + m["outputCost"] * 0.25, m["id"]))
return models, str((payload or {}).get("generatedAt") or "")
def legacy_appe_payload() -> dict | None:
"""The pre-plugin catalogue's disk copy (``OPENROUTER_CACHE_PATH``), read
once per path — never the network."""
legacy = os.environ.get("OPENROUTER_CACHE_PATH", "/data/openrouter-models.json")
if legacy not in _legacy_or:
try:
_legacy_or[legacy] = json.loads(pathlib.Path(legacy).read_text(encoding="utf-8"))
except (OSError, ValueError):
_legacy_or[legacy] = None
return _legacy_or[legacy]
def _index_of(key: str, payload) -> dict[str, dict]:
if not payload:
return {}
memo = _index_memo.get(key)
if memo is not None and memo[0] is payload:
return memo[1]
models, _gen = appe_parse(payload)
index = {m["id"]: m for m in models}
_index_memo[key] = (payload, index)
return index
def legacy_appe_index() -> dict[str, dict]:
"""``id → row`` of the legacy disk copy (a seed registry's pricer: no
store, no network)."""
return _index_of("legacy", legacy_appe_payload())
def _appe_disc(reg: ProviderRegistry, vendor: str) -> dict:
"""The vendor's discovery block with its effective URL: the plugin's
``catalogueUrl`` setting, else its discovery ``url``, else
``APPE_OPENROUTER_URL`` / the APPE default."""
prov = reg.providers.get(vendor)
disc = dict((prov.spec.get("discovery") if prov else None) or {})
try:
cfg = reg.provider_config(vendor) or {}
except Exception: # noqa: BLE001
cfg = {}
url = cfg.get("catalogueUrl").strip() if isinstance(cfg.get("catalogueUrl"), str) else ""
disc["url"] = url or disc.get("url") or os.environ.get("APPE_OPENROUTER_URL", APPE_DEFAULT_URL)
return disc
def _appe_payload(reg: ProviderRegistry, vendor: str):
prov = reg.providers.get(vendor)
disc = (prov.spec.get("discovery") if prov else None) or {}
if disc.get("kind") != "openrouter_appe":
return None
return _disc_get(reg, vendor, "openrouter_appe", _appe_disc(reg, vendor), None) \
or legacy_appe_payload()
def _discovery_index(reg: ProviderRegistry, vendor: str) -> dict[str, dict]:
"""An ``openrouter_appe`` provider's catalogue (id → row). Read from the
cache, never fetched inline."""
return _index_of(f"{reg._discovery_dir}:{vendor}", _appe_payload(reg, vendor))
def appe_vendor(reg: ProviderRegistry) -> str | None:
"""The active provider whose discovery is the APPE catalogue."""
return next((vid for vid, p in reg.providers.items()
if (p.spec.get("discovery") or {}).get("kind") == "openrouter_appe"), None)
def appe_catalogue(reg: ProviderRegistry, *, wait_s: float = 15.0) -> dict:
"""``GET /api/models/openrouter``: ``{models, source, generatedAt}`` —
every OpenRouter model, cheapest first, from the plugin's catalogue.
Never empty-handed when it can help it: with nothing cached yet (a fresh
install) the fetch runs inline, up to ``wait_s``. No provider-openrouter
active ⇒ no models."""
vid = appe_vendor(reg)
if vid is None:
return {"models": [], "source": "", "generatedAt": ""}
disc = _appe_disc(reg, vid)
payload = _appe_payload(reg, vid)
if not payload and wait_s > 0 and os.environ.get("PROVIDERS_DISCOVERY", "1") != "0":
key = (str(reg._discovery_dir or ""), vid)
done = threading.Event()
def run():
try:
_disc_refresh(key, reg, vid, "openrouter_appe", disc, None)
finally:
done.set()
threading.Thread(target=run, daemon=True, name=f"discovery-{vid}-now").start()
done.wait(wait_s)
payload = _appe_payload(reg, vid)
models, generated = appe_parse(payload) if payload else ([], "")
return {"models": models, "source": disc["url"], "generatedAt": generated}
def warm_discovery(reg: ProviderRegistry) -> None:
"""Start every active provider's stale discovery in the background (the
hub's startup: the first model-browser open and the first priced
transcript already have the catalogue)."""
for vid, prov in reg.providers.items():
disc = prov.spec.get("discovery") or {}
kind = disc.get("kind") or "static"
if kind == "openrouter_appe":
_appe_payload(reg, vid)
elif kind == "anthropic_models":
_disc_get(reg, vid, kind, disc, _secret_for(reg, prov))
_index_memo: dict[str, tuple[Any, dict]] = {}
_legacy_or: dict[str, Any] = {}
# ── building + caching ───────────────────────────────────────────────────────
_lock = threading.Lock()
_cache: dict[int, tuple[Any, int, ProviderRegistry]] = {}
_bound = None
_SECRET_GETTER = None
_snapshot_mem: dict[str, dict] = {}
def _store_of(deps_or_store):
if deps_or_store is None:
return None
if hasattr(deps_or_store, "active_manifests"):
return deps_or_store
return getattr(deps_or_store, "plugin_store", None)
def _entries(store) -> tuple[list[ProviderSpec], list[HarnessSpec]]:
from plugins.store import OWNER_UID
try:
rows = store.active_manifests(OWNER_UID)
except Exception: # noqa: BLE001 — no store (tests, early boot)
return [], []
provs, hars = _specs_of(rows)
if not provs and not hars and not _ever_seeded(store):
# Before the first boot's seeding (main._startup) — or a store a test
# never seeded — the seed dir's plugins are what the hub *will* run.
return _seed_entries()
return provs, hars
def _ever_seeded(store) -> bool:
try:
return bool(store.seeded())
except Exception: # noqa: BLE001 — a fake store
return False
# ── the seed dir (strict plugin-only bootstrap) ─────────────────────────────
# There is no built-in model / account table in core: what an unseeded hub (a
# unit test with no PluginStore bound, a fresh standalone before its first
# boot's seeding) reads is the seed dir's plugin manifests themselves — the
# very plugins carryover.seed_typed_plugins installs. ``PLUGINS_SEED_DIR``
# (set but empty: none), else the plugins checkout, else the reference
# fixtures shipped with the backend (tests, a bare image).
FIXTURES_DIR = pathlib.Path(__file__).resolve().parent.parent / "fixtures" / "typed_plugins"
_seed_lock = threading.Lock()
_seed_memo: dict[str, tuple[list[ProviderSpec], list[HarnessSpec]]] = {}
_root_memo: dict[str | None, pathlib.Path | None] = {}
def seed_root() -> pathlib.Path | None:
"""The seed dir (memoized per ``PLUGINS_SEED_DIR`` value: the hot
accounts / pricing helpers read the registry thousands of times a
request)."""
env = os.environ.get("PLUGINS_SEED_DIR")
if env in _root_memo:
return _root_memo[env]
out = _find_seed_root(env)
_root_memo[env] = out
return out
def _find_seed_root(env: str | None) -> pathlib.Path | None:
if env is not None:
d = pathlib.Path(env) if env else None
return d if d is not None and d.is_dir() else None
for d in (pathlib.Path("/workspace/projects/ai-agent-plugins/plugins"),
pathlib.Path.home() / "projects" / "ai-agent-plugins" / "plugins",
FIXTURES_DIR):
if d.is_dir() and any(d.glob("provider-*/plugin.json")):
return d
return None
def _seed_entries() -> tuple[list[ProviderSpec], list[HarnessSpec]]:
root = seed_root()
if root is None:
return [], []
key = str(root)
with _seed_lock:
hit = _seed_memo.get(key)
if hit is not None:
return hit
from plugins.manifest import ManifestError, validate_manifest
rows = []
for child in sorted(root.iterdir()):
if not child.is_dir() or not child.name.startswith(("provider-", "harness-")) \
or not (child / "plugin.json").is_file():
continue
try:
mf = validate_manifest(child)
except (ManifestError, OSError, ValueError) as e:
log.warning("seed plugin %s is invalid: %s", child.name, e)
continue
rows.append((mf["id"], mf, {}))
out = _specs_of(rows)
with _seed_lock:
_seed_memo[key] = out
return out
def _specs_of(rows) -> tuple[list[ProviderSpec], list[HarnessSpec]]:
provs, hars = [], []
seen_v, seen_h = set(), set()
for pid, mf, cfg in rows:
kind = mf.get("kind") or "app"
defaults = {f["key"]: f.get("default") for f in (mf.get("settings") or {}).get("fields") or ()
if f.get("default") not in (None, "")}
conf = {**defaults, **(cfg or {})}
if kind == "provider" and mf.get("provider"):
vid = mf["provider"]["vendorId"]
if vid in seen_v:
log.warning("provider %s declared twice (plugin %s ignored)", vid, pid)
continue
seen_v.add(vid)
provs.append(ProviderSpec(vid, pid, mf["provider"], conf))
elif kind == "harness" and mf.get("harness"):
hid = mf["harness"]["harnessId"]
if hid in seen_h:
log.warning("harness %s declared twice (plugin %s ignored)", hid, pid)
continue
seen_h.add(hid)
hars.append(HarnessSpec(hid, pid, mf["harness"], conf))
return provs, hars
def _snapshot_path(store) -> pathlib.Path | None:
root = getattr(store, "root", None)
return pathlib.Path(root) / "pricing-snapshot.json" if root else None
def _load_snapshot(store) -> dict:
snap = dict(_snapshot_mem)
path = _snapshot_path(store)
if path is not None:
try:
disk = json.loads(path.read_text(encoding="utf-8"))
if isinstance(disk, dict):
for k, v in disk.items():
snap.setdefault(k, v)
except (OSError, ValueError):
pass
return snap
def _save_snapshot(store, reg: ProviderRegistry) -> None:
fresh = reg.snapshot()
if not fresh:
return
_snapshot_mem.update(fresh)
path = _snapshot_path(store)
if path is None:
return
merged = _load_snapshot(store)
merged.update(fresh)
try:
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(".tmp")
tmp.write_text(json.dumps(merged, sort_keys=True), encoding="utf-8")
os.replace(tmp, path)
except OSError:
pass
def build(providers: list[ProviderSpec], harnesses: list[HarnessSpec], *, version: int = 1,
sig: str = "", snapshot: dict | None = None,
discovery_dir: pathlib.Path | None = None) -> ProviderRegistry:
return ProviderRegistry(providers, harnesses, version=version, sig=sig,
snapshot=snapshot, discovery_dir=discovery_dir)
def registry(deps_or_store=None) -> ProviderRegistry:
"""The owner's active providers and harnesses — rebuilt when the plugin
store changes, the same object while what it is built from holds.
``None`` reads the deps :func:`bind` was given."""
if deps_or_store is None:
deps_or_store = _bound
store = _store_of(deps_or_store)
if store is None:
return _boot_registry()
v = getattr(store, "version", 0)
hit = _cache.get(id(store))
if hit and hit[0] is store and hit[1] == v:
return hit[2]
with _lock:
hit = _cache.get(id(store))
if hit and hit[0] is not store:
hit = None
if hit and hit[1] == v:
return hit[2]
provs, hars = _entries(store)
sig = json.dumps([[dataclasses.asdict(p) for p in provs],
[dataclasses.asdict(h) for h in hars]], sort_keys=True, default=str)
if hit and hit[2].sig == sig:
reg = hit[2]
else:
reg = build(provs, hars, version=(hit[2].version + 1) if hit else 1, sig=sig,
snapshot=_load_snapshot(store),
discovery_dir=pathlib.Path(store.root) / "discovery"
if getattr(store, "root", None) else None)
_save_snapshot(store, reg)
if len(_cache) > 32:
_cache.clear()
_cache[id(store)] = (store, v, reg)
return reg
_boot: tuple[Any, ProviderRegistry] | None = None
def _boot_registry() -> ProviderRegistry:
"""No store bound (a unit test, a helper imported outside the app): the
seed dir's plugins (:func:`seed_root`) — empty when there is none."""
global _boot
entries = _seed_entries() # memoized per seed dir: the same object
hit = _boot
if hit is not None and hit[0] is entries:
return hit[1]
provs, hars = entries
sig = json.dumps([[dataclasses.asdict(p) for p in provs],
[dataclasses.asdict(h) for h in hars]], sort_keys=True, default=str)
reg = build(provs, hars, version=1 if provs or hars else 0, sig=sig,
snapshot=dict(_snapshot_mem))
_boot = (entries, reg)
return reg
def bind(deps) -> None:
"""The app's deps — what :func:`registry` reads when called with none
(pricing / catalogue helpers that have no deps of their own)."""
global _bound, _SECRET_GETTER
_bound = deps
store = _store_of(deps)
if store is not None and hasattr(store, "get_secret"):
from plugins.store import HUB_SECRET_UID
def _get(pid: str, key: str) -> str | None:
return store.get_secret(HUB_SECRET_UID, pid, key) or store.get_secret("owner", pid, key)
_SECRET_GETTER = _get
def current() -> ProviderRegistry:
return registry(None)