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

910 lines
42 KiB
Python

"""
Profiles — where a new conversation runs, and which conversations a view
shows.
A **profile** (Personal, Work) is an ordered list of **runners** — the
machines its conversations run on — plus what goes with them:
* ``workers`` — the runners, in order: ``"local"`` (the Homelab's own
sidecar) or a paired worker's id. Each runner sits in **exactly one**
profile, and a conversation belongs to the profile of the runner it ran on
(``resolve``) — whatever account it billed: a personal task run on the
Homelab on the Claude work seat is a Personal conversation. A new prompt of
the profile goes to the **first runner online** (``runs/service.py``).
An entry also carries its runner's settings within the profile:
``accounts`` — a per-machine *override* of the profile's ★ login, per
vendor (``{"anthropic": "work"}``; the runner's other logins stay a pin
away in the composer) — and ``cwd``, where a run there starts
(``None`` = the runner's own default: the lab sidecar's, a Mac's install
dir). Which logins a runner *has* is the machine's business
(``profiles/runners.py``): the lab's config dirs, a Mac's Keychain login and
opencode database.
* ``accounts`` — the profile's ★ login **per provider vendor**
(``{"anthropic": "personal", "google": "google-personal", "openrouter":
"openrouter"}``): what a new prompt of the profile bills for a model of
that vendor, on whichever of its runners holds it (``default_login``:
the runner's override → this → the runner's first login of the vendor).
Until 2026-11-26 the ★ sat on each runner, keyed by *harness*
(``{"claude": …, "opencode": …, "agy": …}``); such a file is migrated on
load (``_lift_accounts``): each harness key becomes its account's vendor,
the default runner's ★ becomes the profile's, and a runner keeps an
override only where it differs.
* ``retired`` — the ids of workers that were unpaired while in the profile,
so their mirrored conversations keep their profile.
* its **projects** (``~/projects`` slugs): preselected in the composer, kept
off its cards, and the home of a conversation that touched no project (its
costs land there, not on the lab root). A project sits in one profile.
``meta.profile`` on a conversation, when set, overrides the runner rule —
the history migration pins the Orus tasks that ran on the lab (before the
Orus MacBook was paired) to Work.
The **Guests** profile (``id`` / ``kind`` ``"guests"``, built in, always
listed last) is the other exception: it holds no runner or project —
its conversations are the ones a **guest started**
(``meta.owner`` names a guest, or the run billed a guest's own login), on
whatever machine they ran (the Homelab, a guest's own computer). Only its
name, icon, colour and ``enabled`` switch are edited; switched off, guests'
conversations fall back to the runner rule (Personal, for the lab).
This replaced (2026-10-19) the account-first model, where a profile owned
**accounts** and its workers were derived from their login: a conversation's
profile followed the account it billed, so a personal task on the work seat
listed under Work. A file in that shape (``accounts`` / ``defaultWorker`` /
``cwd``) is migrated on load (``_migrate``).
Stored in ``/data/profiles.json`` (one list, atomic saves, mtime reload — the
blue-green deploy's standby shares the file), seeded on first load from the
paired workers' logins and their old ``autoRoute`` flags.
"""
from __future__ import annotations
import copy
import json
import os
import pathlib
import re
import threading
import time
import accounts as accounts_mod
# The colours a profile can paint the app in — keep in sync with
# ``ACCOUNT_THEME_COLORS`` (frontend/src/lib/accountTheme.ts).
COLORS = ("orange", "amber", "rose", "fuchsia", "violet", "blue", "sky",
"cyan", "teal", "emerald", "lime")
ICONS = ("user", "briefcase", "home", "rocket", "flask", "heart", "star", "users")
DEFAULT = "personal"
# The built-in Guests profile: the conversations guests started.
GUESTS = "guests"
GUESTS_SEED = {"id": GUESTS, "kind": GUESTS, "label": "Guests", "icon": "users",
"color": "emerald", "enabled": True}
# The one write the Guests profile takes beyond these is none: no runners or
# projects.
_GUESTS_KEYS = ("label", "color", "icon", "enabled")
# ``meta.owner`` of a conversation the owner started (users/caller.OWNER_ID).
_OWNER_ID = "owner"
# The Homelab's own sidecar as a runner (runs/service.py's LOCAL_RUNNER).
LOCAL = "local"
def _reg():
from plugins import providers
return providers.current()
def login_harnesses() -> tuple[str, ...]:
"""The harnesses a runner holds logins for (``loginMode`` other than
``none`` — pi isn't a login)."""
reg = _reg()
return tuple(h for h, spec in reg.harnesses.items()
if (spec.spec.get("loginMode") or "none") != "none")
def vendor_key(key: str | None, account: str | None = None) -> str | None:
"""A ★ map's key as a vendor: a vendor id as is; a legacy harness key
(``claude`` / ``opencode`` / ``agy``) → the vendor of the account it
names (``opencode: opencode-lab`` → ``evox2``), else the harness's first
vendor."""
reg = _reg()
k = (key or "").strip().lower()
if k in reg.providers:
return k
if k in reg.harnesses:
return accounts_mod.vendor_of_account(account) or next(iter(reg.vendors_of_harness(k)), None)
return None
def __getattr__(name: str):
if name == "LOGIN_HARNESSES": # the old constant (PEP 562)
return login_harnesses()
raise AttributeError(name)
# The account-first seed (pre-2026-10-19 shape), migrated like any old file.
SEED: list[dict] = [
{"id": "personal", "label": "Personal", "icon": "user", "color": "orange",
"accounts": ["personal"], "defaultWorker": None, "projects": [],
"cwd": None},
{"id": "work", "label": "Work", "icon": "briefcase", "color": "blue",
"accounts": ["work", "chatgpt-work"], "defaultWorker": None,
"projects": ["orus-monorepo"], "cwd": "~/projects/orus-monorepo"},
]
_SLUG_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$")
_ID_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,39}$")
# A profile once carried a ``resources`` block (which conversations get
# issue / PR / Slack pills). Since 2026-11-26 each resource plugin's own
# settings scope its kinds (plugins/resources.py): a stored block is dropped
# on load. (``contextAgent`` / ``pastConversations`` went the same way on
# 2026-11-05.)
class ProfileError(ValueError):
"""A rejected edit — the route turns it into a 400."""
def is_guests(p: dict | None) -> bool:
"""Whether a profile is the built-in Guests one."""
return bool(p) and (p.get("id") == GUESTS or p.get("kind") == GUESTS)
def guest_owner(meta: dict | None, account: str | None = None) -> str | None:
"""The guest who started a conversation (``meta.owner``), else the guest
whose own login it billed (``guest-<uid>``), else None (the owner's)."""
o = (meta or {}).get("owner")
if isinstance(o, str) and o and o != _OWNER_ID:
return o
return accounts_mod.guest_of(account)
def _clean_cwd(raw) -> str | None:
s = (raw or "").strip() if isinstance(raw, str) else ""
if not s:
return None
if not (s.startswith("~") or s.startswith("/")) or "\n" in s or len(s) > 300:
raise ProfileError("cwd must be an absolute or ~/ path")
return s
def _slugs(raw, what: str) -> list[str]:
if not isinstance(raw, list):
raise ProfileError(f"{what} must be a list")
out: list[str] = []
for v in raw:
s = (v or "").strip() if isinstance(v, str) else ""
if not s or not _SLUG_RE.match(s):
raise ProfileError(f"not a valid {what[:-1]}: {v!r}")
if s not in out:
out.append(s)
return out
# ── runners ──────────────────────────────────────────────────────────────────
def worker_logins_by_harness(w: dict | None) -> dict[str, list[str]]:
"""The logins a paired worker can run on, per *harness*: the hub's Claude
accounts ticked for it (billed through the Claude proxy — claudeproxy/),
the opencode accounts its ``/health`` declares, and the Homelab's opencode
accounts it bills through the opencode proxy; the agy (Google) logins its
``/health`` declares (``agyAccounts`` — each machine holds its own)."""
from claudeproxy.opencode import proxied_accounts as oc_proxied
from claudeproxy.service import claude_accounts
out: dict[str, list[str]] = {h: [] for h in login_harnesses()}
w = w or {}
declared = {"claude": claude_accounts(w),
"opencode": [*(w.get("opencodeAccounts") or []), *oc_proxied(w)],
"agy": list(w.get("agyAccounts") or [])}
for h, raw in declared.items():
if h not in out:
continue
for x in raw:
v = accounts_mod.valid_for(x, h)
if v and v not in out[h]:
out[h].append(v)
return out
def by_vendor(harness_logins: dict[str, list[str]]) -> dict[str, list[str]]:
"""``{harness: [accounts]}`` → ``{vendor: [accounts]}``."""
out: dict[str, list[str]] = {}
for accts in harness_logins.values():
for a in accts:
v = accounts_mod.vendor_of_account(a)
if v and a not in out.setdefault(v, []):
out[v].append(a)
return out
def worker_logins(w: dict | None) -> dict[str, list[str]]:
"""The logins a paired worker holds, per **vendor** (``{anthropic: […],
openai: […], google: […]}``) — :func:`worker_logins_by_harness` grouped
by each account's provider."""
return by_vendor(worker_logins_by_harness(w))
def lab_logins_static() -> dict[str, list[str]]:
"""What the lab holds before its sidecar has answered, per vendor: every
account of a vendor whose logins live on the hub (a Claude config dir,
the OpenRouter key) and every keyless one — no hosted (opencode / agy)
login."""
reg = _reg()
hosted = set(reg.hosted_harnesses())
out: dict[str, list[str]] = {}
for a in reg.accounts():
lh = reg.login_harness(a["vendor"])
if a.get("keyless") or lh not in hosted:
out.setdefault(a["vendor"], []).append(a["id"])
return out
def _star_from(logins: dict[str, list[str]], prefer: list[str]) -> dict[str, str]:
"""The ★ logins of a new entry, per vendor: the first ``prefer`` account
the runner holds, else its first login of that vendor."""
out: dict[str, str] = {}
for v, held in logins.items():
held = held or []
pick = next((a for a in prefer if a in held), None) or (held[0] if held else None)
if pick:
out[v] = pick
return out
def _entry_accounts(raw, strict: bool) -> dict[str, str]:
"""A ★ map: ``{vendor: account}``, each an account of that vendor. A
legacy harness key (``{"claude": "personal"}``) is read as its account's
vendor. Whether a runner *holds* it is checked where it is used
(``default_login``) — a login can come and go without an edit here."""
if not isinstance(raw, dict):
if strict:
raise ProfileError("accounts map a provider (or a harness) to an account")
return {}
out: dict[str, str] = {}
for k, a in raw.items():
if a in (None, ""):
continue
acct = accounts_mod.valid(a) if isinstance(a, str) else None
v = vendor_key(k, acct)
if v is None:
if strict:
raise ProfileError(f"unknown provider: {k!r}")
continue
if not acct or accounts_mod.vendor_of_account(acct) != v:
if strict:
raise ProfileError(f"{a!r} is not a {k} account")
continue
out[v] = acct
return out
def _lift_accounts(p: dict, migrate: bool = False) -> None:
"""Profile-level ★ per vendor. Always: the profile's own map cleaned, and
a runner's override equal to it dropped (it *is* the profile's).
``migrate`` (a file from before profile-level ★ — idempotent, since the
result has the map): every vendor a runner's ★ names takes the first
runner's (the default runner's) value at the profile level; then a vendor
still unset takes the account whose ``homeProfile`` is this profile (the
default profile: also a vendor's account that names none — OpenRouter's
key)."""
raw = p.get("accounts")
accts = _entry_accounts(raw if isinstance(raw, dict) else {}, strict=False)
reg = _reg()
if migrate:
for e in p.get("workers") or []:
for v, a in (e.get("accounts") or {}).items():
accts.setdefault(v, a)
for a in reg.accounts():
home = a.get("homeProfile")
if a["vendor"] in accts:
continue
if home == p["id"] or (not home and p.get("default")):
accts[a["vendor"]] = a["id"]
for e in p.get("workers") or []:
e["accounts"] = {v: a for v, a in (e.get("accounts") or {}).items() if accts.get(v) != a}
p["accounts"] = {v: accts[v] for v in reg.providers if v in accts}
def _clean_entry(raw, strict: bool = False) -> dict | None:
"""``"local"`` / a worker id / ``{id, accounts, cwd}`` → a full entry."""
if isinstance(raw, str):
raw = {"id": raw}
if not isinstance(raw, dict):
if strict:
raise ProfileError("a runner is an id or {id, accounts, cwd}")
return None
rid = raw.get("id").strip() if isinstance(raw.get("id"), str) else ""
if not rid or not _SLUG_RE.match(rid):
if strict:
raise ProfileError(f"not a runner id: {raw.get('id')!r}")
return None
try:
cwd = _clean_cwd(raw.get("cwd"))
except ProfileError:
if strict:
raise
cwd = None
return {"id": rid, "accounts": _entry_accounts(raw.get("accounts") or {}, strict),
"cwd": cwd}
def _migrate(profiles: list[dict], workers: list[dict]) -> list[dict]:
"""An account-first profile (``accounts`` / ``defaultWorker`` / ``cwd``)
→ its runner list: the paired workers logged in on its accounts, its old
default runner first. The lab goes to the default profile, starting where
that profile's lab runs started — first, unless the profile defaulted to
a worker (that worker stays the default runner). A profile that defaulted
to the lab without holding it (Work) loses that fallback: the lab is
Personal's now."""
if all("workers" in p for p in profiles):
return profiles
ids = [p.get("id") for p in profiles]
dflt = DEFAULT if DEFAULT in ids else (ids[0] if ids else None)
claimed: set[str] = {e.get("id") if isinstance(e, dict) else e
for p in profiles for e in p.get("workers") or []}
out = []
for p in profiles:
if "workers" in p:
out.append(p)
continue
accts = [a for a in (accounts_mod.valid(x) for x in p.get("accounts") or []) if a]
dw = p.get("defaultWorker")
mine = [w for w in workers if w.get("id") and w.get("account") in accts
and w["id"] not in claimed]
mine.sort(key=lambda w: w["id"] != dw)
entries = []
for w in mine:
claimed.add(w["id"])
entries.append({"id": w["id"], "accounts": _star_from(worker_logins(w), accts),
"cwd": None})
if p.get("id") == dflt and LOCAL not in claimed:
claimed.add(LOCAL)
lab = {"id": LOCAL, "accounts": _star_from(lab_logins_static(), accts),
"cwd": p.get("cwd")}
entries.insert(1 if dw and entries and entries[0]["id"] == dw else 0, lab)
q = {k: v for k, v in p.items() if k not in ("accounts", "defaultWorker", "cwd")}
q["workers"] = entries
out.append(q)
return out
class ProfileStore:
def __init__(self, path: str, seed_workers: list[dict] | None = None,
workers_fn=None):
"""``workers_fn()`` lists the paired workers (``WorkerStore.list``):
one in no profile lands in the default one."""
self.path = pathlib.Path(path)
self._lock = threading.Lock()
self._mtime: float | None = None
self._data: list[dict] = []
self.version = 0
self._checked = 0.0
self._workers_fn = workers_fn or (lambda: list(seed_workers or []))
self._load()
def _workers(self) -> list[dict]:
try:
return [w for w in self._workers_fn() or [] if isinstance(w, dict)]
except Exception:
return []
# ── persistence ──────────────────────────────────────────────────────────
def _load(self) -> None:
try:
raw = json.loads(self.path.read_text(encoding="utf-8"))
self._mtime = self.path.stat().st_mtime
self._data = [p for p in (raw.get("profiles") or [])
if isinstance(p, dict) and p.get("id")]
except (OSError, ValueError, AttributeError):
self._data, self._mtime = [], None
if not self._data:
self._data = copy.deepcopy(SEED)
# The worker that used to auto-route an account was its
# profile's default runner (the Orus MacBook → Work).
for p in self._data:
for w in self._workers():
if w.get("autoRoute") and w.get("account") in p["accounts"]:
p["defaultWorker"] = w.get("id")
break
self._normalize()
def _normalize(self) -> None:
"""Every profile complete; each runner and project in one profile
(the first claim wins); the lab and every paired worker in some
profile (the default one, unless one retired it); exactly one
default profile, listed first."""
workers = self._workers()
guests = next((p for p in self._data if is_guests(p)), None)
self._data = _migrate([p for p in self._data if not is_guests(p)], workers)
if not self._data:
self._data = _migrate(copy.deepcopy(SEED)[:1], workers)
seen_run: set[str] = set()
seen_proj: set[str] = set()
legacy: set[str] = set()
for p in self._data:
p.setdefault("label", p["id"].title())
if p.get("icon") not in ICONS:
p["icon"] = "user" if p["id"] == DEFAULT else "briefcase"
if p.get("color") not in COLORS:
p["color"] = "orange"
entries = []
for raw in p.get("workers") or []:
e = _clean_entry(raw)
if e and e["id"] not in seen_run:
seen_run.add(e["id"])
entries.append(e)
p["workers"] = entries
projs = [s for s in p.get("projects") or [] if isinstance(s, str)
and s not in seen_proj]
seen_proj.update(projs)
p["projects"] = projs
p["retired"] = [r for r in dict.fromkeys(p.get("retired") or [])
if isinstance(r, str) and _SLUG_RE.match(r)]
for k in ("defaultWorker", "cwd"):
p.pop(k, None)
if not isinstance(p.get("accounts"), dict):
# a file from before profile-level ★ (or the account-first
# shape's list): lift the runners' ★ below
p["accounts"] = {}
legacy.add(p["id"])
ids = [p["id"] for p in self._data]
dflt = DEFAULT if DEFAULT in ids else ids[0]
for p in self._data:
p["default"] = p["id"] == dflt
self._data.sort(key=lambda p: not p["default"])
home = self._data[0]
if LOCAL not in seen_run:
home["workers"].insert(0, {"id": LOCAL, "accounts": {}, "cwd": None})
seen_run.add(LOCAL)
for w in workers:
wid = w.get("id")
if wid and wid not in seen_run:
back = next((p for p in self._data if wid in p["retired"]), home)
back["workers"].append({"id": wid, "accounts": {}, "cwd": None})
seen_run.add(wid)
for p in self._data:
p["retired"] = [r for r in p["retired"] if r not in seen_run]
p.pop("resources", None) # moved to the resource plugins' settings
_lift_accounts(p, migrate=p["id"] in legacy)
self._data.append(self._clean_guests(guests))
@staticmethod
def _clean_guests(raw: dict | None) -> dict:
"""The Guests profile, complete: its own fields over the seed, never
a runner, project or resources rule of its own."""
g = {**GUESTS_SEED, **{k: v for k, v in (raw or {}).items() if k in _GUESTS_KEYS}}
if not isinstance(g.get("label"), str) or not g["label"].strip():
g["label"] = GUESTS_SEED["label"]
if g.get("icon") not in ICONS:
g["icon"] = GUESTS_SEED["icon"]
if g.get("color") not in COLORS:
g["color"] = GUESTS_SEED["color"]
g["enabled"] = bool(g.get("enabled", True))
g.update({"id": GUESTS, "kind": GUESTS, "workers": [], "retired": [],
"projects": [], "accounts": {}, "default": False})
return g
def _reload_if_changed(self, force: bool = False) -> None:
# A card build asks once per conversation: one stat a second is
# plenty for an out-of-band edit (the deploy standby's).
now = time.monotonic()
if not force and now - self._checked < 1.0:
return
self._checked = now
try:
m = self.path.stat().st_mtime
except OSError:
return
if self._mtime is None or m != self._mtime:
self._load()
self.version += 1
def _save(self) -> None:
self.path.parent.mkdir(parents=True, exist_ok=True)
tmp = self.path.with_suffix(".json.tmp")
body = {"version": 3,
"profiles": [{k: v for k, v in p.items() if k != "default"}
for p in self._data]}
tmp.write_text(json.dumps(body, indent=2), encoding="utf-8")
os.replace(tmp, self.path)
try:
self._mtime = self.path.stat().st_mtime
except OSError:
pass
self.version += 1
# ── reads ────────────────────────────────────────────────────────────────
def _ref(self) -> list[dict]:
"""The live list without a copy, for the per-card reads (a card build
asks ~2 000 times). Callers must not mutate it."""
with self._lock:
self._reload_if_changed()
return self._data
def list(self) -> list[dict]:
return copy.deepcopy(self._ref())
def get(self, profile_id: str | None) -> dict | None:
pid = (profile_id or "").strip().lower()
return next((p for p in self.list() if p["id"] == pid), None)
def default(self) -> dict:
return self.list()[0]
def _runner_ref(self, runner: str | None) -> dict | None:
rid = runner or LOCAL
data = self._ref()
return (next((p for p in data if any(e["id"] == rid for e in p["workers"])), None)
or next((p for p in data if rid in p["retired"]), None))
def resolve_ref(self, runner: str | None, account: str | None = None,
explicit: str | None = None, owner: str | None = None) -> dict:
"""A conversation's profile (no copy): ``explicit`` (``meta.profile``)
→ Guests when a guest started it (``owner``, see :func:`guest_owner`)
and that profile is on → the profile holding its runner (``None`` =
the lab) → for a runner no profile knows, the one where its account is
a runner's ★ login → the default profile."""
data = self._ref()
if explicit:
hit = next((p for p in data if p["id"] == explicit), None)
if hit and (not is_guests(hit) or hit.get("enabled")):
return hit
if owner or accounts_mod.guest_of(account):
g = self._guests_ref()
if g.get("enabled"):
return g
p = self._runner_ref(runner)
if p:
return p
return self._star_ref(account) or data[0]
def _star_ref(self, account: str | None) -> dict | None:
a = accounts_mod.valid(account)
if not a:
return None
return next((p for p in self._ref() if a in self.stars(p)), None)
def for_account_star(self, account: str | None) -> dict | None:
"""The profile where ``account`` is a runner's ★ login (a copy), None
when it is nobody's — where a run naming only an account belongs."""
p = self._star_ref(account)
return copy.deepcopy(p) if p else None
def resolve(self, runner: str | None, account: str | None = None,
explicit: str | None = None, owner: str | None = None) -> str:
""":meth:`resolve_ref`'s id."""
return self.resolve_ref(runner, account, explicit, owner)["id"]
def of_meta(self, meta: dict | None, account: str | None = None) -> str:
"""A conversation's profile id from its metadata sidecar (runner,
stamp, guest owner) and the account it billed."""
m = meta or {}
return self.resolve(m.get("worker") or m.get("workerSource"), account,
m.get("profile"), guest_owner(m, account))
def _guests_ref(self) -> dict:
return next(p for p in self._ref() if is_guests(p))
def guests_enabled(self) -> bool:
"""Whether guests' conversations get their own profile."""
return bool(self._guests_ref().get("enabled"))
def for_runner(self, runner: str | None) -> dict:
"""The profile a runner sits in (a copy; the default one when none)."""
return copy.deepcopy(self._runner_ref(runner) or self._ref()[0])
def entry(self, runner: str | None) -> dict | None:
"""A runner's entry (``{id, accounts, cwd}``), a copy."""
rid = runner or LOCAL
for p in self._ref():
for e in p["workers"]:
if e["id"] == rid:
return copy.deepcopy(e)
return None
def default_runner(self, profile: dict) -> str | None:
"""Where a new prompt of the profile runs unless the composer pins a
runner: its first runner (None = none at all)."""
ws = profile.get("workers") or []
return ws[0]["id"] if ws else None
def effective_accounts(self, runner: str | None) -> dict[str, str]:
"""A runner's ★ per vendor: its profile's map, its own overrides on
top (a copy)."""
rid = runner or LOCAL
p = self._runner_ref(rid) or {}
e = next((x for x in p.get("workers") or [] if x["id"] == rid), None) or {}
return {**(p.get("accounts") or {}), **(e.get("accounts") or {})}
def default_login(self, runner: str | None, key: str,
held: list[str]) -> str | None:
"""What a new run on ``runner`` bills for ``key`` — a **vendor**
(``anthropic``), or a harness (``claude``: its vendors, in order):
the runner's override when the runner still holds it, else its
profile's ★, else the first login it holds."""
reg = _reg()
k = (key or "").lower()
vendors = [k] if k in reg.providers else reg.vendors_of_harness(k)
rid = runner or LOCAL
p = self._runner_ref(rid) or {}
e = next((x for x in p.get("workers") or [] if x["id"] == rid), None) or {}
for src in (e.get("accounts") or {}, p.get("accounts") or {}):
for v in vendors:
star = src.get(v)
if star in held:
return star
return held[0] if held else None
def stars(self, profile: dict) -> set[str]:
"""The ★ logins of a profile — its own per vendor and its runners'
overrides: the seats native to it (their spend counts in its own view
even when out of the totals)."""
return {*(profile.get("accounts") or {}).values(),
*(a for e in profile.get("workers") or [] for a in (e.get("accounts") or {}).values())}
def selector(self, param: str | None):
"""A predicate over ``(account, profile id[, guest])`` for an
``?account=`` query param — ``accounts.selector``'s grammar
(``totals``, ``all``, account ids, ``guests``) plus ``profile:<id>``
(comma-listable): the conversations of that profile (by runner) that
billed one of its runners' ★ seats or a seat counted in the totals — a
personal task on the lab on the work seat lists under Personal, but its
spend stays out of Personal's figures (not the owner's money).
Guests' conversations are the Guests profile's, and their spend on a
profile's own seat (a guest run bills the lab's ★ by default) stays
counted in that profile's figures too — it is that seat's money.
``profile:guests`` counts them on any seat, their own logins included;
``guest:<uid>`` items narrow it to those guests (the predicate's third
argument, the conversation's guest — :func:`guest_owner`). The
predicate's ``by_profile`` says whether it reads the profile at all."""
p = (param or "").strip().lower()
items = [x.strip() for x in p.split(",") if x.strip()]
wants = [x.split(":", 1)[1] for x in items if x.startswith("profile:")]
only = {x.split(":", 1)[1] for x in items if x.startswith("guest:")}
if not wants:
sel = accounts_mod.selector(param)
def by_account(a, _profile=None, _guest=None):
return sel(a)
by_account.by_profile = False
return by_account
native = {pid: self.stars(prof) for pid in wants
for prof in [next((x for x in self._ref() if x["id"] == pid), None)] if prof}
def by_profile(a, profile, guest=None):
if profile == GUESTS and only and guest not in only:
return False
seats = native.get(profile)
if seats is not None:
# Guests: the seats counted in the totals (the owner's, which
# a guest run bills by default) and every guest's own login.
if profile == GUESTS and accounts_mod.guest_of(a):
return True
return accounts_mod.counts_in_totals(a) or (a or accounts_mod.DEFAULT) in seats
if profile == GUESTS and not only:
acct = a or accounts_mod.DEFAULT
return any(acct in s for pid, s in native.items() if pid != GUESTS)
return False
by_profile.by_profile = True
return by_profile
def runner_cwd(self, runner: str | None) -> str | None:
"""Where a run on ``runner`` starts unless the caller says (None ⇒ the
runner's own default)."""
return (self.entry(runner) or {}).get("cwd")
def account_for_project(self, slug: str | None) -> str | None:
"""The account owning a project's costs: the ★ login of the first
runner of the profile listing it; None when no profile does (it then
counts as the default account's — the caller decides)."""
s = (slug or "").strip().split(":")[-1]
if not s:
return None
for p in self._ref():
if s in p["projects"]:
first = (p["workers"] or [{}])[0].get("id")
eff = self.effective_accounts(first) if first else dict(p.get("accounts") or {})
claude = next(iter(_reg().vendors_of_harness("claude")), None)
return eff.get(claude) or next(iter(eff.values()), None) or accounts_mod.DEFAULT
return None
def home_project(self, profile_id: str | None) -> str | None:
"""Where a conversation of the profile that touched no project is
filed: its first project (None ⇒ the lab root)."""
p = next((x for x in self._ref() if x["id"] == profile_id), None)
return ((p or {}).get("projects") or [None])[0]
# ── writes ───────────────────────────────────────────────────────────────
@staticmethod
def _name(rid: str, workers: list[dict] | None) -> str:
if rid == LOCAL:
return "the Homelab"
w = next((x for x in workers or [] if x.get("id") == rid), None)
return (w or {}).get("name") or rid
def patch(self, profile_id: str, changes: dict,
workers: list[dict] | None = None) -> dict:
"""Apply an edit. ``projects`` claimed here leave the profile that had
them. ``workers`` is the profile's whole runner list, default first:
a runner claimed here leaves the profile that had it, and one this
profile drops must be claimed by another one — a runner always sits
in a profile (``workers`` = the paired ones, to check the ids)."""
with self._lock:
self._reload_if_changed(force=True)
p = next((x for x in self._data if x["id"] == profile_id), None)
if p is None:
raise KeyError(profile_id)
if is_guests(p):
bad = [k for k in changes if k not in _GUESTS_KEYS]
if bad:
raise ProfileError(f"the Guests profile has no {bad[0]} — its "
"conversations are the ones guests started")
if "enabled" in changes:
p["enabled"] = bool(changes["enabled"])
elif "enabled" in changes:
raise ProfileError("only the Guests profile can be switched off")
if "label" in changes:
label = (changes["label"] or "").strip()
if not label or len(label) > 40:
raise ProfileError("a profile needs a name (40 chars max)")
p["label"] = label
if "color" in changes:
if changes["color"] not in COLORS:
raise ProfileError(f"unknown colour: {changes['color']!r}")
p["color"] = changes["color"]
if "icon" in changes:
if changes["icon"] not in ICONS:
raise ProfileError(f"unknown icon: {changes['icon']!r}")
p["icon"] = changes["icon"]
if "accounts" in changes:
if is_guests(p):
raise ProfileError("the Guests profile bills no account of its own")
raw = changes["accounts"]
if not isinstance(raw, dict):
raise ProfileError("accounts maps a provider to an account")
cur = dict(p.get("accounts") or {})
for k, a in raw.items():
v = vendor_key(k, accounts_mod.valid(a) if isinstance(a, str) else None)
if v is None:
raise ProfileError(f"unknown provider: {k!r}")
if not a:
cur.pop(v, None)
else:
cur.update(_entry_accounts({k: a}, strict=True))
p["accounts"] = cur
# an explicit profile ★ wins over the runners' equal overrides
# (cleared ones fall back to the runner's first login)
if "projects" in changes:
projs = _slugs(changes["projects"], "projects")
for other in self._data:
if other is not p:
other["projects"] = [s for s in other["projects"]
if s not in projs]
p["projects"] = projs
if "workers" in changes:
raw = changes["workers"]
if not isinstance(raw, list):
raise ProfileError("workers must be a list")
entries: list[dict] = []
for r in raw:
e = _clean_entry(r, strict=True)
if any(x["id"] == e["id"] for x in entries):
continue
if workers is not None and e["id"] != LOCAL \
and not any(w.get("id") == e["id"] for w in workers):
raise ProfileError(f"unknown worker: {e['id']!r}")
entries.append(e)
ids = {e["id"] for e in entries}
dropped = [e["id"] for e in p["workers"] if e["id"] not in ids]
if dropped:
raise ProfileError(
f"{self._name(dropped[0], workers)} has to sit in a profile "
"— move it to another one instead")
for other in self._data:
if other is not p:
other["workers"] = [e for e in other["workers"]
if e["id"] not in ids]
other["retired"] = [r for r in other.get("retired") or []
if r not in ids]
p["workers"] = entries
self._normalize()
self._save()
return copy.deepcopy(next(x for x in self._data if x["id"] == profile_id))
def patch_runner(self, runner: str, changes: dict,
workers: list[dict] | None = None) -> dict:
"""Edit one runner's entry: ``accounts`` (merged per harness — an
empty value clears that ★), ``cwd``, ``default`` (true = make it its
profile's default runner) and ``profile`` (move it there, last — or
first when ``default`` says so). Answers the runner's profile."""
with self._lock:
self._reload_if_changed(force=True)
rid = (runner or "").strip()
src = next((p for p in self._data if any(e["id"] == rid for e in p["workers"])), None)
if src is None:
raise KeyError(rid)
e = next(x for x in src["workers"] if x["id"] == rid)
if "accounts" in changes:
raw = changes["accounts"]
if not isinstance(raw, dict):
raise ProfileError("accounts maps a harness to an account")
merged = dict(e["accounts"])
for k, a in raw.items():
v = vendor_key(k, accounts_mod.valid(a) if isinstance(a, str) else None)
if v is None:
raise ProfileError(f"unknown provider: {k!r}")
if a:
merged.update(_entry_accounts({k: a}, strict=True))
else:
merged.pop(v, None)
# an override equal to the profile's ★ is the profile's
e["accounts"] = {v: a for v, a in merged.items()
if (src.get("accounts") or {}).get(v) != a}
if "cwd" in changes:
e["cwd"] = _clean_cwd(changes["cwd"])
dst = src
if changes.get("profile") and changes["profile"] != src["id"]:
dst = next((p for p in self._data if p["id"] == changes["profile"]), None)
if dst is None:
raise ProfileError(f"unknown profile: {changes['profile']!r}")
if is_guests(dst):
raise ProfileError("the Guests profile has no runners of its own")
src["workers"] = [x for x in src["workers"] if x["id"] != rid]
dst["workers"].append(e)
if changes.get("default"):
dst["workers"] = [e, *[x for x in dst["workers"] if x["id"] != rid]]
self._normalize()
self._save()
return copy.deepcopy(next(x for x in self._data if x["id"] == dst["id"]))
def assign_worker(self, w: dict, profile_id: str | None = None) -> None:
"""A newly (re-)paired worker: into ``profile_id`` when given, else it
stays where it is, else back to the profile that retired it, else the
default profile — ★ on the logins it holds. A guest's own computer
joins none (workers/guests.py)."""
wid = w.get("id")
if not wid or w.get("owner"):
return
with self._lock:
self._reload_if_changed(force=True)
cur = next((p for p in self._data if any(e["id"] == wid for e in p["workers"])), None)
dst = next((p for p in self._data if p["id"] == profile_id
and not is_guests(p)), None) if profile_id else None
entry = {"id": wid, "accounts": {}, "cwd": None}
if cur is not None:
old = next(e for e in cur["workers"] if e["id"] == wid)
held = worker_logins(w)
entry["accounts"] = {v: a for v, a in old["accounts"].items()
if a in held.get(v, [])}
entry["cwd"] = old.get("cwd")
if dst is None or dst is cur:
cur["workers"] = [entry if e["id"] == wid else e for e in cur["workers"]]
dst = cur
else:
cur["workers"] = [e for e in cur["workers"] if e["id"] != wid]
dst["workers"].append(entry)
else:
dst = dst or next((p for p in self._data if wid in p["retired"]), self._data[0])
dst["workers"].append(entry)
self._normalize()
self._save()
def forget_worker(self, worker_id: str) -> None:
"""An unpaired worker leaves its profile's runners — but stays in its
``retired`` list, so its mirrored conversations keep their profile."""
with self._lock:
self._reload_if_changed(force=True)
hit = False
for p in self._data:
if any(e["id"] == worker_id for e in p["workers"]):
p["workers"] = [e for e in p["workers"] if e["id"] != worker_id]
if worker_id not in p["retired"]:
p["retired"].append(worker_id)
hit = True
if hit:
# _normalize would put a still-listed worker back: the caller
# deletes it from the worker store first.
self._normalize()
self._save()