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>
134 lines
4.8 KiB
Python
134 lines
4.8 KiB
Python
"""
|
|
What every harness mirror shares — the harness plugins' own ``sidecar/``
|
|
mirrors (harness-opencode's and harness-agy's ``mirror.py``).
|
|
|
|
A mirror reads a harness's native store and **appends** v1 events to a
|
|
transcript the hub imports (``transcript_v1.Out`` does the append + the dedup
|
|
on its key field). Around that, each one needs the same few things:
|
|
|
|
- :func:`cwd_slug` — Claude Code's project-dir spelling of a cwd;
|
|
- :func:`git_branch` — the branch a session's cwd is on (its header line);
|
|
- :func:`iso_from_ms` / :func:`iso_from_text` — a record's ``timestamp``;
|
|
- :func:`read_state` / :func:`write_state` — the mirror's own small JSON
|
|
state file, written atomically (a crash never leaves half of it);
|
|
- :class:`PollThread` — one daemon thread ticking every account's mirror.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import datetime
|
|
import json
|
|
import logging
|
|
import os
|
|
import pathlib
|
|
import re
|
|
import subprocess
|
|
import threading
|
|
from typing import Callable
|
|
|
|
|
|
def cwd_slug(cwd: str) -> str:
|
|
"""Claude Code's project-dir spelling of a cwd (every non-alphanumeric → ``-``)."""
|
|
return re.sub(r"[^A-Za-z0-9]", "-", cwd or "/")
|
|
|
|
|
|
def git_branch(cwd: str, timeout: float = 5) -> str | None:
|
|
try:
|
|
r = subprocess.run(["git", "-C", cwd, "rev-parse", "--abbrev-ref", "HEAD"],
|
|
capture_output=True, text=True, timeout=timeout)
|
|
return (r.stdout or "").strip() or None if r.returncode == 0 else None
|
|
except (OSError, subprocess.TimeoutExpired):
|
|
return None
|
|
|
|
|
|
def _now_iso() -> str:
|
|
return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z")
|
|
|
|
|
|
def iso_from_ms(ms) -> str:
|
|
"""Epoch milliseconds → ``2026-01-02T03:04:05.678Z`` (now, when unreadable)."""
|
|
try:
|
|
return datetime.datetime.fromtimestamp(float(ms) / 1000, datetime.timezone.utc) \
|
|
.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
|
|
except (TypeError, ValueError, OverflowError, OSError):
|
|
return _now_iso()
|
|
|
|
|
|
def iso_from_text(ts) -> str:
|
|
"""An ISO timestamp in any offset → the same instant in UTC, ms precision."""
|
|
try:
|
|
d = datetime.datetime.fromisoformat(str(ts).replace("Z", "+00:00"))
|
|
return d.astimezone(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
|
|
except (TypeError, ValueError):
|
|
return _now_iso()
|
|
|
|
|
|
def read_state(path: pathlib.Path, key: str) -> dict[str, int]:
|
|
"""``{name: int}`` under ``key`` of a mirror's state file ({} when unreadable)."""
|
|
try:
|
|
return {k: int(v) for k, v in (json.loads(path.read_text()).get(key) or {}).items()}
|
|
except (OSError, ValueError, AttributeError, TypeError):
|
|
return {}
|
|
|
|
|
|
def write_state(path: pathlib.Path, obj: dict) -> None:
|
|
"""Write a mirror's state file atomically (tmp + rename); errors are dropped
|
|
— the worst case is re-reading what was already mirrored, which dedups."""
|
|
try:
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
tmp = path.with_suffix(".tmp")
|
|
tmp.write_text(json.dumps(obj))
|
|
os.replace(tmp, path)
|
|
except OSError:
|
|
pass
|
|
|
|
|
|
class PollThread:
|
|
"""Ticks every mirror every ``poll_s()`` seconds on one daemon thread.
|
|
``kick()`` runs the next pass now, ``add()`` joins a mirror later (and
|
|
starts the thread), ``stop()`` ends it. A mirror whose ``tick`` raises is
|
|
logged (``on_error``) and the loop goes on."""
|
|
|
|
def __init__(self, mirrors: list, *, name: str, poll_s: Callable[[], float],
|
|
on_error: Callable[[object, BaseException], None] | None = None):
|
|
self.mirrors = mirrors
|
|
self._name = name
|
|
self._poll_s = poll_s
|
|
self._on_error = on_error or (lambda m, e: logging.getLogger(name).exception(
|
|
"%s %s", name, getattr(m, "account", m)))
|
|
self._stop = threading.Event()
|
|
self._kick = threading.Event()
|
|
self._thread: threading.Thread | None = None
|
|
|
|
@property
|
|
def _started(self) -> bool:
|
|
return self._thread is not None
|
|
|
|
def start(self) -> None:
|
|
if self._thread is None and self.mirrors:
|
|
self._thread = threading.Thread(target=self._loop, name=self._name, daemon=True)
|
|
self._thread.start()
|
|
|
|
def add(self, mirror) -> None:
|
|
if all(getattr(m, "account", None) != getattr(mirror, "account", None)
|
|
for m in self.mirrors):
|
|
self.mirrors = [*self.mirrors, mirror]
|
|
self.start()
|
|
|
|
def kick(self) -> None:
|
|
self._kick.set()
|
|
|
|
def _loop(self) -> None:
|
|
while not self._stop.is_set():
|
|
for m in list(self.mirrors):
|
|
try:
|
|
m.tick()
|
|
except Exception as e: # never let one bad row stop the mirror
|
|
self._on_error(m, e)
|
|
self._kick.wait(self._poll_s())
|
|
self._kick.clear()
|
|
|
|
def stop(self) -> None:
|
|
self._stop.set()
|
|
self._kick.set()
|