Files
Gabriel VidalandClaude Opus 5.5 0bbb086c07 feat(providers): cut catalog, presets, accounts, profiles & routing over to the ProviderRegistry (Wave 3A)
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>
2026-11-26 16:50:47 +01:00

274 lines
11 KiB
Python

"""
Accounts — which subscription a conversation runs (and is billed) on.
Since the typed-plugins cutover (Wave 3A, 2026-11-26) the accounts are the
**provider plugins'** (``kind: "provider"``, ``provider.accounts`` + the
owner's edits in the plugin's settings — ``plugins/providers.py``): there is
no account table in core any more. Each account belongs to one **vendor**
(``anthropic``: the Claude logins ``personal`` / ``work``; ``openai``: the
ChatGPT seat; ``google``: the AI Pro login; ``openrouter``: the hub's
OpenRouter key; ``evox2``: the EVOX2's local models — ``keyless``, its old
name ``opencode-lab`` an alias). Which harness runs a vendor's models is the
harness plugins' ``supports[]``.
A Claude account *is* a config dir: ``CLAUDE_CONFIG_DIR`` moves the login,
``.claude.json``, settings and ``projects/`` transcripts together, so the
sidecar picks one per run by exporting it (``configDir``, None = the CLI's
own ``~/.claude``). Settings only owns the presentation (plan, price, in the
totals or not); which runner and start dir go with an account is a
**profile**'s business (``profiles/``).
A conversation's account resolves in this order (``resolve``):
1. **explicit** — ``meta.account``, stamped by ``/api/spawn`` (and carried over
by resume/fork/cron), i.e. the account the run was actually launched on;
2. **source** — ``meta.accountSource``, stamped by the indexer when it imports
a transcript out of a non-default account's ``projects/`` dir, or by the
worker mirror (catches a work session started from a terminal);
3. the default account.
An alias (``opencode-lab``) resolves to its account (``evox2``) everywhere.
**Compat.** The vendor-native helpers are :func:`accounts_for_vendor`,
:func:`vendor_of_account`, :func:`resolve_alias`. The harness-keyed ones the
older callers use (:func:`for_harness`, :func:`valid_for`, :func:`harness_of`)
join ``harness.supports[].vendor`` to the provider accounts: a pi run bills
the vendor of its model (``evox2`` or ``openrouter``), no longer a fake
``personal``. ``DEFAULT``, ``ACCOUNTS``, ``HARNESSES`` and
``HOSTED_HARNESSES`` are computed from the registry on access.
"""
from __future__ import annotations
import os
import pathlib
import re
# A guest's **own** Claude login (Settings → Claude account, on their side):
# account ``guest-<uid>``, a config dir the host sidecar makes on their first
# sign-in. Not a provider account — any id of that shape is one. Their spend
# is an estimate on a plan the owner doesn't pay for, so like Work it stays
# out of the aggregated totals; ``?account=guests`` selects all of them.
GUEST_PREFIX = "guest-"
_GUEST_RE = re.compile(r"guest-([a-z0-9][a-z0-9-]{0,39})")
def _reg():
from plugins import providers
return providers.current()
def guest_of(account_id: str | None) -> str | None:
"""The guest id a ``guest-<uid>`` account belongs to, else None."""
m = _GUEST_RE.fullmatch((account_id or "").strip().lower())
return m.group(1) if m else None
def guest_account(uid: str) -> str:
return f"{GUEST_PREFIX}{uid}"
def default_id() -> str:
"""The account flagged ``default`` (Gabriel's ``personal``)."""
return _reg().default_account() or ""
def _compat(a: dict) -> dict:
"""A registry account with the harness-era fields older callers read:
``harness`` (the harness it is a login of) and ``provider`` (its vendor)."""
reg = _reg()
vendor = a.get("vendor")
a.setdefault("provider", vendor)
a["harness"] = (reg.login_harness(vendor) if vendor else None) or "claude"
return a
def all_accounts() -> list[dict]:
"""Every provider account, in vendor order (copies)."""
return [_compat(a) for a in _reg().accounts()]
def resolve_alias(account_id: str | None) -> str:
"""An old account name → its account (``opencode-lab`` → ``evox2``)."""
return _reg().resolve_alias(account_id)
def ids() -> list[str]:
return [a["id"] for a in _reg().accounts()]
def get(account_id: str | None) -> dict | None:
a = _reg().account(account_id)
return _compat(a) if a else None
def valid(account_id: str | None) -> str | None:
"""The canonical id for ``account_id`` (an alias resolved), or None when
it names no account."""
a = _reg().account(account_id)
return a["id"] if a else None
def accounts_for_vendor(vendor: str | None) -> list[str]:
return [a["id"] for a in _reg().accounts_for_vendor((vendor or "").lower())]
def vendor_of_account(account_id: str | None) -> str | None:
return _reg().vendor_of_account(account_id)
def default_for_vendor(vendor: str | None) -> str | None:
"""A vendor's first account (its ``default`` one first)."""
accts = _reg().accounts_for_vendor((vendor or "").lower())
hit = next((a for a in accts if a.get("default")), None) or next(iter(accts), None)
return hit["id"] if hit else None
def is_keyless(account_id: str | None) -> bool:
return bool((_reg().account(account_id) or {}).get("keyless"))
def harness_of(account_id: str | None) -> str:
"""The harness an account is a login of (a guest's own login: claude) —
``claude`` for anthropic, ``opencode`` for openai / evox2, ``agy`` for
google, ``pi`` for openrouter."""
a = _reg().account(account_id)
if not a:
return "claude"
return _reg().login_harness(a.get("vendor")) or "claude"
def for_harness(harness: str | None) -> list[str]:
"""The accounts a run on ``harness`` can bill, in vendor order: those of
every vendor its plugin ``supports``."""
return [a["id"] for a in _reg().accounts_for_harness((harness or "claude").lower())]
def valid_for(account_id: str | None, harness: str | None) -> str | None:
"""``account_id``'s canonical id when a ``harness`` run can bill it (its
vendor is one the harness runs; a guest's own login: claude)."""
a = _reg().account(account_id)
if a is None:
return None
h = (harness or "claude").lower()
if a.get("guest"):
return a["id"] if h in _reg().harnesses_of_vendor(a.get("vendor")) else None
return a["id"] if a.get("vendor") in _reg().vendors_of_harness(h) else None
def plan_windows(account_id: str | None) -> list[str]:
"""The usage windows an account's plan enforces (``week``, ``h5``); an
explicit ``[]`` (a keyless account) has none."""
pw = (_reg().account(account_id) or {}).get("planWindows")
return list(pw) if pw is not None else ["week", "h5"]
def counts_in_totals(account_id: str | None) -> bool:
a = _reg().account(account_id) or _reg().account(default_id()) or {}
return not a.get("excludeFromTotals")
def wire_id(account_id: str | None, harness: str | None = None) -> str | None:
"""The name a runner's sidecar knows an account by: its first alias for a
keyless account on a harness that hosts logins (the lab sidecar declares
the EVOX2's opencode account as ``opencode-lab``), else the id."""
a = _reg().account(account_id)
if not a:
return account_id
h = (harness or harness_of(a["id"])).lower()
if a.get("keyless") and a.get("aliases") and h in _reg().hosted_harnesses():
return a["aliases"][0]
return a["id"]
def transcripts_dirs() -> dict[str, pathlib.Path]:
"""account id → its live transcripts dir, for the non-default accounts whose
mount env is set (an unset/empty env ⇒ that account isn't ingested):
* a Claude config-dir account (``configDir`` set): its own mount,
``<ID>_TRANSCRIPTS_DIR`` (``WORK_TRANSCRIPTS_DIR``) or the account's
``transcriptsEnv``;
* an account of a harness that mirrors one subdir per account (opencode,
agy — ``loginMode`` worker / machine): ``<harness transcriptsEnv>/<id>``
(its alias's subdir when that is the one on disk: ``opencode-lab``)."""
reg = _reg()
out: dict[str, pathlib.Path] = {}
for a in reg.accounts():
if a.get("configDir") and not a.get("default"):
env = a.get("transcriptsEnv") or f"{re.sub(r'[^A-Z0-9]', '_', a['id'].upper())}_TRANSCRIPTS_DIR"
raw = os.environ.get(env, "")
if raw:
out[a["id"]] = pathlib.Path(raw).resolve()
for hid in reg.hosted_harnesses():
env = reg.harnesses[hid].spec.get("transcriptsEnv")
root = os.environ.get(env, "") if env else ""
if not root:
continue
for a in reg.accounts_for_harness(hid):
if a["id"] in out:
continue
names = [a["id"], *(a.get("aliases") or [])]
sub = next((n for n in names if (pathlib.Path(root) / n).is_dir()), a["id"])
out[a["id"]] = (pathlib.Path(root) / sub).resolve()
return out
def resolve(summary: dict | None, meta: dict | None) -> str:
"""A conversation's account: explicit stamp → import source → default.
(``summary`` is unused since the cwd rule went — kept for the callers.)"""
m = meta or {}
for key in ("account", "accountSource"):
v = valid(m.get(key))
if v:
return v
return default_id()
def selector(param: str | None):
"""A predicate over account ids for an ``?account=`` query param.
* unset / ``""`` / ``totals`` — the aggregated-totals view: every account
except the ones flagged ``excludeFromTotals`` (the default everywhere);
* ``all`` — every account;
* an account id — that account only; ``a,b`` — those accounts (a
profile's, when it holds several);
* ``guests`` — every guest's own login (also usable inside a list).
Unknown ids select nothing (an empty page beats silently widening)."""
p = (param or "").strip().lower()
if p in ("", "totals"):
return counts_in_totals
if p == "all":
return lambda _a: True
want = {x.strip() for x in p.split(",") if x.strip()}
guests = "guests" in want
want |= {resolve_alias(x) for x in want}
dflt = default_id()
return lambda a: resolve_alias(a or dflt) in want or (guests and bool(guest_of(a)))
def public() -> list[dict]:
"""The accounts as ``/api/accounts`` serves them (no host paths)."""
return [{"id": a["id"], "label": a.get("label") or a["id"],
"description": a.get("description") or "", "color": a.get("color") or "orange",
"harness": a["harness"],
"provider": a.get("vendor"),
"vendor": a.get("vendor"),
"keyless": bool(a.get("keyless")),
"aliases": list(a.get("aliases") or []),
"planWindows": plan_windows(a["id"]),
"excludeFromTotals": bool(a.get("excludeFromTotals")),
"default": bool(a.get("default"))} for a in all_accounts()]
# The old module constants, now read off the registry (PEP 562).
def __getattr__(name: str):
if name == "DEFAULT":
return default_id()
if name == "ACCOUNTS":
return all_accounts()
if name == "HARNESSES":
return _reg().harness_ids()
if name == "HOSTED_HARNESSES":
return _reg().hosted_harnesses()
raise AttributeError(name)