Files
ai-agent/sidecar/harness_loader.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

717 lines
30 KiB
Python

"""
The live harness drivers — which ``SidecarHarness`` answers for each harness id.
Typed-plugins spec §3.1. The hub materializes every enabled ``harness-*``
plugin's ``sidecar/`` dir + ``plugin.json`` under ``SIDECAR_LIVE_HARNESSES_DIR``
(the host: ``/data/plugins/live-harnesses``; a worker: the dir ``/sync`` writes,
``~/.ai-agent-worker/harnesses``), with an ``index.json``::
{"version": 1, "hash": "…",
"harnesses": {"opencode": {"pluginId": "harness-opencode", "dir": "harness-opencode",
"entry": "driver.py", "guestAllowed": false, "hash": "…"}}}
``reload()`` turns that into the active registry, **atomically**:
1. every candidate driver module is imported in a namespace of its own
(``sidecar_ext.harness.<plugin id>.<module>`` — its relative imports work,
nothing leaks into the sidecar's own module names), its object checked
against the contract (``harness_base.check_harness``);
2. only once *all* of them loaded, the new drivers are started, the registry
is swapped under the lock, and the drivers that left are shut down;
3. on any import / validation / startup error nothing is swapped: the
previous drivers stay live, the modules the attempt replaced in
``sys.modules`` are put back, and the answer is
``{"ok": false, "rolledBack": true, "error": …}``.
A good load is copied to ``<dir>.lkg/`` (last-known-good).
**Strict plugin-only** (typed-plugins spec §0.5): there are no built-in
drivers — a harness no plugin provides is simply not there (the run routes
answer 409 ``harness_unavailable``). So a sidecar must always find its
plugins, even cold, before the hub ever materialized them. Where a load
comes from, first that has something:
1. the live dir (``SIDECAR_LIVE_HARNESSES_DIR``);
2. its ``.lkg`` copy, when the live dir was never written (missing, or no
``index.json`` nor plugin dir in it) or fails to load while nothing is
loaded yet — a worker
boots on its last synced drivers while the hub is offline;
3. **the host only** (not a worker): the seed plugins,
``SIDECAR_SEED_PLUGINS_DIR`` (default ``~/projects/ai-agent-plugins/plugins``)
— every ``harness-*`` / ``provider-*`` dir there, the same dirs the hub
seeds its PluginStore from.
A live dir that *was* materialized with nothing in it (every harness plugin
disabled) is respected: no fallback. The first read of the registry boots it
(without starting the drivers); the sidecar's lifespan then starts them.
The same machinery, with another kind, loads the providers' usage readers
(``usage_loader.py``): :class:`DriverLoader` is shared. A provider's code is
its ``usageReader`` or a plain ``sidecar`` module (provider-evox2: live
progress, room-making, ``/local-ready``); one with neither
(provider-openrouter) loads no code, but its manifest + config are kept
(``configs()``).
"""
from __future__ import annotations
import hashlib
import importlib.util
import json
import logging
import os
import pathlib
import re
import shutil
import sys
import threading
import time
import types
from typing import Any, Callable
import harness_base
log = logging.getLogger("harness-loader")
_SAFE = re.compile(r"[^A-Za-z0-9_]")
_ID_RE = re.compile(r"^[a-z][a-z0-9_-]{0,63}$")
_HASH_SKIP = {"__pycache__", ".git", "node_modules"}
SEED_DEFAULT = "~/projects/ai-agent-plugins/plugins"
def seed_root() -> pathlib.Path | None:
"""The seed plugins dir a host sidecar falls back to (None on a worker,
or when ``SIDECAR_SEED_PLUGINS_DIR`` is set empty)."""
from config import IS_WORKER
if IS_WORKER:
return None
v = os.environ.get("SIDECAR_SEED_PLUGINS_DIR", SEED_DEFAULT)
return pathlib.Path(os.path.expanduser(v)) if v.strip() else None
def _ns_part(s: str) -> str:
return _SAFE.sub("_", s)
def dir_hash(d: pathlib.Path) -> str:
"""A content hash of a driver dir (relpath + bytes of every file)."""
h = hashlib.sha256()
for p in sorted(d.rglob("*")):
if not p.is_file() or any(part in _HASH_SKIP for part in p.relative_to(d).parts):
continue
h.update(p.relative_to(d).as_posix().encode() + b"\0")
try:
h.update(p.read_bytes())
except OSError:
continue
h.update(b"\0")
return h.hexdigest()[:16]
class Entry:
"""One active driver and where it came from."""
__slots__ = ("id", "obj", "source", "plugin_id", "hash", "dir", "order", "meta",
"started", "error")
def __init__(self, id: str, obj: Any, source: str, *, plugin_id: str | None = None,
hash: str | None = None, dir: str | None = None, order: int = 1000,
meta: dict | None = None):
self.id = id
self.obj = obj
self.source = source # "plugin" | "lkg" | "seed"
self.plugin_id = plugin_id
self.hash = hash
self.dir = dir
self.order = order
self.meta = meta or {}
self.started = False
self.error: str | None = None
def public(self) -> dict:
return {"id": self.id, "source": self.source, "pluginId": self.plugin_id,
"hash": self.hash, "dir": self.dir, "order": self.order,
"started": self.started, "version": self.meta.get("version"),
"guestAllowed": self.meta.get("guestAllowed"), "error": self.error}
class DriverLoader:
"""A registry of drivers of one kind, reloadable from a plugin dir.
``kind`` "harness" | "provider" (the namespace + index key)
``index_key`` the index.json map ("harnesses" | "providers")
``manifest_key`` plugin.json's object ("harness" | "provider")
``id_key`` its id field ("harnessId" | "vendorId")
``code_key`` where its sidecar code is ("sidecar" | ("usageReader", "sidecar")
— a tuple: the first block the manifest declares)
``check`` the contract check (``harness_base.check_harness``…)
``factories`` the module attributes tried, in order (create / instance / class)
"""
def __init__(self, *, kind: str, index_key: str, manifest_key: str, id_key: str,
code_key: str, default_entry: str, check: Callable, factories: tuple,
root_env: str, host_root: str, worker_root: str):
self.kind = kind
self.index_key = index_key
self.manifest_key = manifest_key
self.id_key = id_key
self.code_key = code_key
self.default_entry = default_entry
self.check = check
self.factories = factories
self.root_env = root_env
self.host_root = host_root
self.worker_root = worker_root
self._lock = threading.RLock()
self._active: dict[str, Entry] | None = None # None = not booted yet
# {id: {pluginId, dir, config, manifest, code}} of every plugin of the
# loaded base — the codeless ones too (a provider without a reader).
self._configs: dict[str, dict] = {}
self._ctx = None
self._last: dict = {"ok": None, "at": None, "error": None, "rolledBack": False,
"source": None}
self._started = False
# ── paths ──
def root(self) -> pathlib.Path:
v = os.environ.get(self.root_env)
if v:
return pathlib.Path(os.path.expanduser(v))
from config import IS_WORKER
return pathlib.Path(os.path.expanduser(self.worker_root if IS_WORKER else self.host_root))
def lkg_root(self) -> pathlib.Path:
r = self.root()
return r.with_name(r.name + ".lkg")
@staticmethod
def base_of(root: pathlib.Path) -> pathlib.Path:
"""The dir holding index.json: ``root/current`` when a sync swapped one in."""
cur = root / "current"
return cur if cur.is_dir() else root
# ── context ──
def set_context(self, ctx) -> None:
self._ctx = ctx
def context(self):
if self._ctx is None:
self._ctx = harness_base.make_context()
return self._ctx
# ── boot ──
def _fallbacks(self) -> list[tuple[pathlib.Path, str]]:
"""(base, source) to try when the live dir can't serve: its .lkg copy,
then — on the host — the seed plugins."""
out = [(self.base_of(self.lkg_root()), "lkg")]
seed = seed_root()
if seed is not None:
out.append((seed, "seed"))
return out
@staticmethod
def builtins_enabled() -> bool:
"""Always False: there are no built-in drivers (kept so a check that
they're off — the plugins' own tests — still reads)."""
return False
def _materialized(self) -> bool:
"""Has the live dir ever been written — an index.json in it, or (no
index: scanned) a plugin dir?"""
base = self.base_of(self.root())
if (base / "index.json").is_file():
return True
try:
return any((d / "plugin.json").is_file() for d in base.iterdir() if d.is_dir())
except OSError:
return False
def _ensure(self) -> dict[str, Entry]:
with self._lock:
if self._active is None:
# The first read boots the registry (nothing started: the
# lifespan's startup() does that) — a route asked before the
# lifespan ran, a test, an A/B dump.
self._active = {}
try:
self.reload(start=False)
except Exception: # noqa: BLE001 — reload never raises, but a boot never may
log.exception("%s boot", self.kind)
return self._active
# ── reads ──
def get(self, id: str | None):
e = self._ensure().get(id or "")
return e.obj if e else None
def entry(self, id: str) -> Entry | None:
return self._ensure().get(id)
def ids(self) -> tuple[str, ...]:
return tuple(e.id for e in self.entries())
def entries(self) -> list[Entry]:
return sorted(self._ensure().values(), key=lambda e: (e.order, e.id))
def drivers(self) -> list:
return [e.obj for e in self.entries()]
def public(self) -> dict:
root = self.root()
seed = seed_root()
return {"root": str(root), "lkg": self.lkg_root().is_dir(),
"seed": str(seed) if seed is not None else None,
self.index_key: [e.public() for e in self.entries()],
"last": dict(self._last)}
# ── discovery ──
def _candidates(self, base: pathlib.Path) -> list[dict]:
"""``[{id, pluginId, path, entry, hash, guestAllowed, order, config}]`` from
``base`` — its index.json, else a scan of its plugin dirs. Raises on
an unreadable index (a broken materialization is an error, not
"nothing installed"). A plugin with no code of this kind (a provider
without a usage reader) comes back with ``path`` None."""
if not base.is_dir():
return []
idx_path = base / "index.json"
if idx_path.is_file():
idx = json.loads(idx_path.read_text())
items = (idx.get(self.index_key) or {}) if isinstance(idx, dict) else None
if not isinstance(items, dict):
raise ValueError(f"{idx_path}: no {self.index_key!r} map")
out = []
for cid, spec in items.items():
if not isinstance(spec, dict):
raise ValueError(f"{idx_path}: {cid!r} is not an object")
out.append(self._resolve(base, cid, spec))
return out
out = []
for d in sorted(p for p in base.iterdir() if p.is_dir() and not p.name.startswith(".")):
man = self._manifest(d)
obj = man.get(self.manifest_key) if man else None
if not isinstance(obj, dict):
continue
cid = obj.get(self.id_key)
if not isinstance(cid, str):
continue
out.append(self._resolve(base, cid, {"pluginId": man.get("id") or d.name,
"dir": d.name}))
return out
@staticmethod
def _manifest(d: pathlib.Path) -> dict | None:
try:
m = json.loads((d / "plugin.json").read_text())
return m if isinstance(m, dict) else None
except (OSError, ValueError):
return None
def _plugin_dir(self, base: pathlib.Path, d: str) -> pathlib.Path:
"""A spec's ``dir``: relative to the base, or absolute — the hub writes
its own (container) path, which a host sidecar reading the same
files through another mount resolves by name under its base."""
if not os.path.isabs(d):
return base / d
p = pathlib.Path(d)
if p.is_dir() or not (base / p.name).is_dir():
return p
return base / p.name
def _resolve(self, base: pathlib.Path, cid: str, spec: dict) -> dict:
if not _ID_RE.match(str(cid)):
raise ValueError(f"bad {self.kind} id {cid!r}")
plugin_id = str(spec.get("pluginId") or cid)
pdir = self._plugin_dir(base, str(spec.get("dir") or plugin_id))
man = self._manifest(pdir) or self._manifest(pdir.parent) or {}
obj = man.get(self.manifest_key) if isinstance(man.get(self.manifest_key), dict) else {}
keys = self.code_key if isinstance(self.code_key, tuple) else (self.code_key,)
code = next((obj[k] for k in keys if isinstance(obj.get(k), dict)), None)
root = pdir if self._manifest(pdir) else pdir.parent
config = spec.get("config") if isinstance(spec.get("config"), dict) else None
if config is None:
# The hub writes a provider's non-secret config beside its manifest.
try:
c = json.loads((root / "config.json").read_text())
config = c if isinstance(c, dict) else {}
except (OSError, ValueError):
config = {}
order = obj.get("order", spec.get("order", 1000))
out = {"id": str(cid), "pluginId": plugin_id, "path": None, "root": root,
"hash": None,
"guestAllowed": bool(spec.get("guestAllowed", obj.get("guestAllowed", False))),
"order": order if isinstance(order, int) else 1000,
"version": man.get("version"), "config": config, "manifest": obj}
has_entry = "entry" in spec and spec["entry"] is None
if code is None and (has_entry or not spec.get("entry")):
return out # codeless: config only
code = code or {}
entry = str(spec.get("entry") or code.get("entry") or self.default_entry)
if ".." in pathlib.PurePath(entry).parts or "/" in entry:
raise ValueError(f"{self.kind} {cid!r}: bad entry {entry!r}")
# `dir` may name the plugin dir or its code dir itself.
tried = [pdir / entry, pdir / str(code.get("dir") or "sidecar") / entry]
path = next((p for p in tried if p.is_file()), None)
if path is None:
raise ValueError(f"{self.kind} {cid!r}: no {entry} under {pdir}")
out["path"] = path
out["hash"] = str(spec.get("hash") or dir_hash(path.parent))
return out
# ── loading one ──
def _load(self, cand: dict, stash: dict) -> Any:
"""Import a candidate's entry module in its own namespace and return
the driver object. ``stash`` collects the sys.modules entries it
replaced, so a failed reload can put them back."""
pkg = f"sidecar_ext.{self.kind}.{_ns_part(cand['pluginId'])}"
for name in ("sidecar_ext", f"sidecar_ext.{self.kind}"):
if name not in sys.modules:
m = types.ModuleType(name)
m.__path__ = [] # a namespace: nothing to import from it
sys.modules[name] = m
for name in [n for n in sys.modules if n == pkg or n.startswith(pkg + ".")]:
stash.setdefault(name, sys.modules.pop(name))
stash.setdefault(f"__new__:{pkg}", None)
code_dir = cand["path"].parent
p = types.ModuleType(pkg)
p.__path__ = [str(code_dir)]
p.__package__ = pkg
p.__file__ = str(code_dir / "__init__.py")
sys.modules[pkg] = p
modname = f"{pkg}.{_ns_part(cand['path'].stem)}"
spec = importlib.util.spec_from_file_location(modname, cand["path"])
if spec is None or spec.loader is None:
raise ImportError(f"cannot load {cand['path']}")
mod = importlib.util.module_from_spec(spec)
mod.__package__ = pkg
sys.modules[modname] = mod
spec.loader.exec_module(mod)
obj = None
ctx = self.context()
for attr in self.factories:
v = getattr(mod, attr, None)
if v is None:
continue
if isinstance(v, type):
obj = v()
elif attr == "create" and callable(v):
obj = v(ctx)
else:
obj = v
break
if obj is None:
raise ValueError(f"{cand['path']}: none of {', '.join(self.factories)} defined")
self.check(obj, cand["id"])
return obj
@staticmethod
def _restore(stash: dict) -> None:
for name in list(stash):
if name.startswith("__new__:"):
pkg = name[len("__new__:"):]
for n in [n for n in sys.modules if n == pkg or n.startswith(pkg + ".")]:
sys.modules.pop(n, None)
for name, mod in stash.items():
if not name.startswith("__new__:") and mod is not None:
sys.modules[name] = mod
# ── the swap ──
def reload(self, force: bool = False, *, start: bool = True) -> dict:
"""Load the live dir and swap it in — see the module docstring.
``start``: call ``startup`` on new drivers (and ``shutdown`` on the
ones that left) — the sidecar's lifespan and every reload do."""
with self._lock:
if self._active is None:
self._active = {}
cur = self._active
root = self.root()
booting = not cur
try:
if not self._materialized():
# Never written (a worker that never synced since a wipe, a
# host whose hub hasn't materialized yet): the last good
# copy, else the seed plugins.
return self._fall_back(force, start, None)
out = self._try(self.base_of(root), "plugin", cur, force, start)
if out["ok"] and out.get("plugins"):
self._snapshot(root)
return out
except Exception as e: # noqa: BLE001 — anything at all rolls back
err = f"{type(e).__name__}: {e}"
log.warning("%s reload failed, rolled back: %s", self.kind, err)
out = {"ok": False, "rolledBack": True, "error": err}
if booting:
# Nothing was running: boot on the last good copy (or the
# seed) — still answered as the failure it is.
alt = self._fall_back(force, start, err)
if alt.get("ok"):
out["fallback"] = alt.get("fallback")
elif alt.get("fallbackErrors"):
out["fallbackErrors"] = alt["fallbackErrors"]
self._last = {"ok": False, "at": time.time(), "error": err,
"rolledBack": True, "source": out.get("fallback")}
out[self.index_key] = [e.public() for e in self.entries()]
return out
def _fall_back(self, force: bool, start: bool, err: str | None) -> dict:
"""Boot on the first fallback base that loads something. ``err``: why
the live dir didn't (None = it was never written)."""
errors = []
for base, source in self._fallbacks():
if not base.is_dir():
continue
try:
out = self._try(base, source, self._active, force, start)
except Exception as e: # noqa: BLE001
errors.append(f"{source}: {type(e).__name__}: {e}")
continue
if out.get("plugins"):
out["fallback"] = source
if err:
out["liveError"] = err
return out
if err is None:
# Nothing anywhere: an empty registry is a clean answer.
self._active = {}
self._configs = {}
self._last = {"ok": True, "at": time.time(), "error": None, "rolledBack": False,
"source": None}
return {"ok": True, "rolledBack": False, "plugins": [], "loaded": [],
"removed": [], "fallbackErrors": errors, self.index_key: []}
return {"ok": False, "rolledBack": True, "error": err, "fallbackErrors": errors}
def _try(self, base: pathlib.Path, source: str, cur: dict[str, Entry], force: bool,
start: bool) -> dict:
cands = self._candidates(base)
seen: set[str] = set()
new: dict[str, Entry] = {}
stash: dict = {}
fresh: list[Entry] = []
configs: dict[str, dict] = {}
try:
for c in cands:
if c["id"] in seen:
raise ValueError(f"two plugins provide {self.kind} {c['id']!r}")
seen.add(c["id"])
configs[c["id"]] = {"pluginId": c["pluginId"], "dir": str(c["root"]),
"config": dict(c["config"]), "manifest": c["manifest"],
"code": c["path"] is not None}
if c["path"] is None:
continue # nothing to load: config only
old = cur.get(c["id"])
meta = {"guestAllowed": c["guestAllowed"], "version": c["version"],
"config": c["config"], "manifest": c["manifest"]}
if (old is not None and not force
and old.plugin_id == c["pluginId"] and old.hash == c["hash"]):
old.meta = meta
new[c["id"]] = old # unchanged: keep the live instance
continue
obj = self._load(c, stash)
e = Entry(c["id"], obj, source, plugin_id=c["pluginId"], hash=c["hash"],
dir=str(c["path"].parent), order=c["order"], meta=meta)
new[c["id"]] = e
fresh.append(e)
if start:
ctx = self.context()
for e in fresh: # a plugin driver that can't start rolls back
e.obj.startup(ctx)
e.started = True
except BaseException:
for e in fresh:
if e.started:
try:
e.obj.shutdown()
except Exception: # noqa: BLE001
log.exception("%s %s shutdown", self.kind, e.id)
self._restore(stash)
raise
# Commit: swap, then shut down what left (or was replaced).
gone = [e for k, e in cur.items() if new.get(k) is not e]
self._active = new
self._configs = configs
if start:
for e in gone:
if e.started:
try:
e.obj.shutdown()
except Exception: # noqa: BLE001 — a bad shutdown never undoes a swap
log.exception("%s %s shutdown", self.kind, e.id)
e.started = False
self._started = self._started or start
plugins = [e.id for e in new.values()]
self._last = {"ok": True, "at": time.time(), "error": None, "rolledBack": False,
"source": source}
return {"ok": True, "rolledBack": False, "plugins": plugins,
"loaded": [e.id for e in fresh],
"removed": [e.id for e in gone],
self.index_key: [e.public() for e in self.entries()]}
def _snapshot(self, root: pathlib.Path) -> None:
"""Copy the live dir that just loaded to ``<root>.lkg`` (once per content)."""
base = self.base_of(root)
lkg = self.lkg_root()
h = hashlib.sha256()
for e in sorted(self._active.values(), key=lambda e: e.id):
if e.source == "plugin":
h.update(f"{e.id}\0{e.plugin_id}\0{e.hash}\0".encode())
stamp = h.hexdigest()[:16]
try:
if (lkg / ".lkg-hash").read_text().strip() == stamp:
return
except OSError:
pass
tmp = lkg.with_name(f".{lkg.name}.tmp-{os.getpid()}")
try:
shutil.rmtree(tmp, ignore_errors=True)
shutil.copytree(base, tmp, symlinks=False,
ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
(tmp / ".lkg-hash").write_text(stamp)
old = lkg.with_name(f".{lkg.name}.old-{os.getpid()}")
if lkg.exists():
os.replace(lkg, old)
os.replace(tmp, lkg)
shutil.rmtree(old, ignore_errors=True)
except OSError as e:
log.warning("%s: could not snapshot %s: %s", self.kind, lkg, e)
shutil.rmtree(tmp, ignore_errors=True)
# ── life ──
def startup(self) -> dict:
"""The sidecar's lifespan: load the live dir and start everything."""
self._ensure()
out = self.reload(start=True)
with self._lock:
for e in self._active.values():
if not e.started:
self._start_entry(e)
return out
def _start_entry(self, e: Entry) -> None:
try:
e.obj.startup(self.context())
e.started = True
e.error = None
except Exception as ex: # noqa: BLE001
e.error = f"{type(ex).__name__}: {ex}"
log.exception("%s %s startup", self.kind, e.id)
def shutdown(self) -> None:
with self._lock:
for e in (self._active or {}).values():
if e.started:
try:
e.obj.shutdown()
except Exception: # noqa: BLE001
log.exception("%s %s shutdown", self.kind, e.id)
e.started = False
def configs(self) -> dict[str, dict]:
"""``{id: {pluginId, dir, config, manifest, code}}`` of every plugin of
the loaded base, with code or not."""
self._ensure()
return {k: dict(v) for k, v in self._configs.items()}
def module(self, id: str, name: str):
"""A loaded driver's own submodule (``module("opencode", "cli")`` →
the harness-opencode plugin's ``sidecar/cli.py``), or None — what a
core feature reads a harness's own helpers through (gen_progress's
opencode database lookup) without importing a plugin by path."""
e = self.entry(id)
if e is None or e.plugin_id is None:
return None
return sys.modules.get(f"sidecar_ext.{self.kind}.{_ns_part(e.plugin_id)}.{_ns_part(name)}")
def reset(self) -> None:
"""Forget everything (tests)."""
with self._lock:
self.shutdown()
self._active = None
self._configs = {}
self._ctx = None
self._last = {"ok": None, "at": None, "error": None, "rolledBack": False,
"source": None}
LOADER = DriverLoader(
kind="harness", index_key="harnesses", manifest_key="harness", id_key="harnessId",
code_key="sidecar", default_entry="driver.py", check=harness_base.check_harness,
factories=("create", "harness", "Harness"),
root_env="SIDECAR_LIVE_HARNESSES_DIR", host_root="/data/plugins/live-harnesses",
worker_root="~/.ai-agent-worker/harnesses")
# ── the module API the routes use ─────────────────────────────────────────────
def get(harness: str | None):
return LOADER.get(harness)
def ids() -> tuple[str, ...]:
return LOADER.ids()
def drivers() -> list:
return LOADER.drivers()
def context():
return LOADER.context()
def reload(force: bool = False) -> dict:
return LOADER.reload(force)
def startup() -> dict:
return LOADER.startup()
def public() -> dict:
return LOADER.public()
def module(harness: str, name: str):
"""The harness plugin's own submodule ``name`` (see DriverLoader.module)."""
return LOADER.module(harness, name)
def forget_status(account: str | None = None) -> None:
"""Drop every driver's cached login status (``GET /accounts?fresh=1``) —
the drivers that keep one say so with ``forget_status``."""
for d in drivers():
fn = getattr(d, "forget_status", None)
if callable(fn):
try:
fn(account)
except Exception: # noqa: BLE001 — a cache drop never fails a read
log.exception("forget_status on %r", d)
def account_drivers(account: str) -> list:
"""The drivers to ask about ``account``: the ones that claim it, in
order, then the catch-all ones (claude) — the old if/elif chain."""
ds = drivers()
owners = [d for d in ds if not getattr(d, "catch_all_accounts", False)
and _owns(d, account)]
return owners + [d for d in ds if getattr(d, "catch_all_accounts", False)]
def _owns(d, account: str) -> bool:
try:
return bool(d.owns_account(account))
except Exception: # noqa: BLE001
return False
def dispatch_account(account: str, method: str, *args, **kw):
"""``method`` of the first driver for ``account`` that handles it, or
``harness_base.NOT_HANDLED``."""
for d in account_drivers(account):
fn = getattr(d, method, None)
if not callable(fn):
continue
out = fn(account, *args, **kw)
if out is not harness_base.NOT_HANDLED:
return out
return harness_base.NOT_HANDLED