Files
ai-agent/sidecar/harness_base.py
Gabriel VidalandClaude Opus 5.5 1574ccd388 sidecar: strict plugin-only cutover (Wave 3C)
Delete the built-in bridges and the legacy harness / usage modules now owned
by ai-agent-plugins (harness_builtin, claude_cli, claude_accounts,
claude_usage, pi_runs, opencode_{cli,mirror,tools,usage},
agy_{cli,mirror,tools,usage}). routes_runs / fork keep only the routes; the
harness-* plugins' drivers launch.

- harness_loader: no builtins; the first read boots the registry; a live dir
  never materialized falls back to .lkg, then (host only) the seed plugins
  (SIDECAR_SEED_PLUGINS_DIR, default ~/projects/ai-agent-plugins/plugins);
  codeless provider entries keep their manifest + config.json; module() and
  forget_status() accessors; hub-written absolute dirs resolved by name.
- usage_loader: provider_configs() covers every provider plugin, evox2()
  reads servers + Wake-on-LAN from provider-evox2 (local_ready, gen_progress
  use it — no duplicated EVOX2 constants).
- core helpers kept self-contained: claude_env.py (run env, account env,
  machine login), run_errors.py (typed errors); launch._stop_run calls the
  driver's stop_extra; /accounts?fresh=1 and guest listing go through drivers;
  gen_progress reads the opencode db via harness_loader.module; tools_check
  via driver status; tools_install has its own gh device-login pump.
- /sync accepts a provider bundle without a usage reader.
- backend workers/labsync: always send harnesses + providers maps ({} clears
  a worker); guests only get harnesses whose own plugin.json says
  guestAllowed.
- tests + A/B scripts run the real plugins (conftest live index + legacy-name
  import hook; launch-dump / _mirror_worker load the plugins for a tree with
  no bridges). install.sh points the host unit at the hub's live dirs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 16:53:17 +01:00

230 lines
8.0 KiB
Python

"""
The sidecar's harness and usage-reader contracts (typed-plugins spec §3.2 /
§3.3, ``~/homelab/data/log/2026-11-26-ai-agent-typed-plugins-spec.md``).
A **harness driver** is what turns a ``/spawn`` / ``/resume`` / ``/fork`` body
into a launched process for one harness (``claude``, ``pi``, ``opencode``,
``agy``…), and what answers the account routes for the logins it owns. A
**usage reader** keeps one vendor's plan-usage snapshots (the
``rate-limits.json`` files the hub reads as Plan %).
Both come only from a harness / provider plugin's ``sidecar/`` dir, loaded by
``harness_loader`` / ``usage_loader`` out of ``SIDECAR_LIVE_HARNESSES_DIR`` /
``SIDECAR_LIVE_PROVIDERS_DIR`` (their ``.lkg`` copy, or on the host the seed
plugins) — the sidecar has no built-in driver (strict plugin-only).
A plugin driver module (``<plugin>/sidecar/driver.py`` by default) exposes one
of: ``create(ctx) -> SidecarHarness``, a module-level ``harness`` instance, or
a ``Harness`` class (instantiated with no argument). A usage reader module the
same with ``create`` / ``reader`` / ``Reader``. The loaders check what they get
against :func:`check_harness` / :func:`check_reader` before anything is
swapped in.
Optional methods: every account method may be left to the base class, which
answers :data:`NOT_HANDLED` — the route then tries the next driver that owns
the account (the catch-all, ``claude``) or answers 404, exactly as the
hard-coded dispatch did.
"""
from __future__ import annotations
import dataclasses
import pathlib
from types import ModuleType
from typing import Any
class _NotHandled:
"""The base class's answer for a method a driver doesn't implement."""
_inst = None
def __new__(cls):
if cls._inst is None:
cls._inst = super().__new__(cls)
return cls._inst
def __bool__(self) -> bool:
return False
def __repr__(self) -> str:
return "NOT_HANDLED"
NOT_HANDLED: Any = _NotHandled()
@dataclasses.dataclass
class SidecarContext:
"""What a driver gets from the sidecar it runs in. Modules, not copies, so
a driver reads the live value (tests patch ``config`` / ``launch``)."""
config: ModuleType
LOG_DIR: pathlib.Path
IS_WORKER: bool
pids: ModuleType
launch: ModuleType # _launch, _claude_args, _stop_run, valid_scope…
validate: ModuleType # _valid_model, _thinking_args, _effort_args…
transcript_v1: ModuleType
mirror_base: ModuleType
# {vendorId: {pluginId, dir, config}} from SIDECAR_LIVE_PROVIDERS_DIR — the
# non-secret config each provider plugin materialized (usage_loader).
providers: dict = dataclasses.field(default_factory=dict)
def take_over(self, sid: str, force: bool) -> dict | None:
"""A resume's idempotency check (routes_runs.resume): a run that is
really still going answers ``reused`` unless ``force``, which stops it
first. None = go ahead and launch."""
rec = self.pids._live_record(sid)
if rec:
if not force:
return {"sessionId": sid, "pid": rec.get("pid"),
"log": str(self.LOG_DIR / f"{sid}.log"), "reused": True}
self.launch._stop_run(sid, rec)
return None
def make_context(providers: dict | None = None) -> SidecarContext:
import config
import launch
import mirror_base
import pids
import transcript_v1
import validate
return SidecarContext(config=config, LOG_DIR=config.LOG_DIR, IS_WORKER=config.IS_WORKER,
pids=pids, launch=launch, validate=validate,
transcript_v1=transcript_v1, mirror_base=mirror_base,
providers=dict(providers or {}))
class SidecarHarness:
"""One harness's sidecar runtime. Subclass it (or duck-type it: the loader
checks the required methods, not the class)."""
harness_id: str = ""
# The driver that answers for an account no other driver claims (claude:
# its login ids are config dirs, anything else is a 404 there).
catch_all_accounts: bool = False
# ── life ──
def startup(self, ctx: SidecarContext) -> None:
"""Start the driver's threads (mirrors…). Called once it is active."""
def shutdown(self) -> None:
"""Stop them. Called when a reload drops or replaces the driver."""
# ── runs ──
def valid_model(self, model: str | None) -> str | None:
raise NotImplementedError
def spawn(self, body, sid: str, cwd: str, ctx: SidecarContext) -> dict:
raise NotImplementedError
def resume(self, body, sid: str, cwd: str, ctx: SidecarContext) -> dict:
raise NotImplementedError
def fork(self, body, sid: str, new_sid: str, cwd: str, ctx: SidecarContext) -> dict:
raise NotImplementedError
def stop_extra(self, pid: int, sid: str, rec: dict | None = None) -> Any:
"""What an interrupt must do beyond the SIGINT to the run's group —
called before the signal; may return a callable run after it."""
return None
def health_meta(self) -> dict:
return {}
# ── accounts (all optional) ──
def owns_account(self, account: str) -> bool:
return False
def accounts_list(self) -> list[dict]:
return []
def account_status(self, account: str, fresh: bool = False):
return NOT_HANDLED
def account_probe(self, account: str):
return NOT_HANDLED
def account_login_start(self, account: str, body) -> Any:
return NOT_HANDLED
def account_login_status(self, account: str) -> Any:
return NOT_HANDLED
def account_login_code(self, account: str, code: str) -> Any:
return NOT_HANDLED
def account_login_cancel(self, account: str) -> Any:
return NOT_HANDLED
def account_logout(self, account: str) -> Any:
return NOT_HANDLED
def access_token(self, account: str, refresh: bool = False) -> Any:
return NOT_HANDLED
def extra_routers(self) -> list:
return []
class SidecarUsageReader:
"""One vendor's plan-usage snapshots."""
vendor_id: str = ""
# Legacy route names kept forwarding here (``/claude/usage`` → anthropic).
aliases: tuple[str, ...] = ()
def startup(self, ctx: SidecarContext) -> None:
pass
def shutdown(self) -> None:
pass
def snapshots(self) -> dict[str, dict]:
raise NotImplementedError
def poll_once(self, account: str | None = None) -> dict:
return {}
def refresh_soon(self, account: str | None = None) -> None:
pass
HARNESS_REQUIRED = ("startup", "shutdown", "valid_model", "spawn", "resume", "fork")
READER_REQUIRED = ("startup", "shutdown", "snapshots")
def check_harness(obj, expect_id: str | None = None) -> str:
"""The driver's harness id, or ValueError saying what's wrong with it."""
hid = getattr(obj, "harness_id", None)
if not isinstance(hid, str) or not hid.strip():
raise ValueError("driver has no harness_id")
if expect_id and hid != expect_id:
raise ValueError(f"driver says harness_id {hid!r}, its plugin says {expect_id!r}")
for m in HARNESS_REQUIRED:
if not callable(getattr(obj, m, None)):
raise ValueError(f"harness {hid!r}: {m}() missing")
return hid
def check_reader(obj, expect_id: str | None = None) -> str:
vid = getattr(obj, "vendor_id", None)
if not isinstance(vid, str) or not vid.strip():
raise ValueError("usage reader has no vendor_id")
if expect_id and vid != expect_id:
raise ValueError(f"reader says vendor_id {vid!r}, its plugin says {expect_id!r}")
for m in READER_REQUIRED:
if not callable(getattr(obj, m, None)):
raise ValueError(f"usage reader {vid!r}: {m}() missing")
return vid
def implements(obj, method: str) -> bool:
"""Whether ``obj`` has its own ``method`` (not the base class's no-op)."""
fn = getattr(type(obj), method, None)
if fn is None:
return callable(getattr(obj, method, None))
return fn is not getattr(SidecarHarness, method, None)