Files
ai-agent/sidecar/labsync.py
gabrielvidalandClaude Opus 5.5 16aabb9922 feat(plugins): move commits + diff viewer out of core into plugins
Generic platform points for the `diff-viewer` and `commits` plugins
(ai-agent-plugins): a `conversation.tab` slot (Thread | Changes N) with
setTab/openTab/closeTab/reply bridges; stackable + pullOut tool cards and
match.hasReport; `pathShims` (a git PATH shim for every harness) with
out-of-band reports (lab: /api/plugin-reports, worker: outbox `report`);
`conversations.reports` and `diff.read` hub bridges; ui.pages[].opens for
Project/Service "Recent commits". The core commit card, Changes view, diff
page and review store are gone; bash_diff.py keeps bashDiff only. Legacy
gitCommits / commit-line parsing stays for past transcripts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 20:17:04 +01:00

596 lines
24 KiB
Python

"""
Lab sync, the worker's half — the homelab skills and agents the hub ships here.
The homelab's ``.claude/skills`` and ``.claude/agents`` live in a private repo
this machine can't pull. The hub bundles the ones flagged ``workers: true``
(``backend/workers/labsync.py``) and, when this worker's ``/health`` reports a
different ``labSync.hash``, POSTs the bundle to ``/sync``:
POST /sync {hash, skills: {name: {rel: base64}}, agents: {name: text},
executables: ["<skill>/<rel>", …]}
The bundle is written to ``<LABSYNC_DIR>/v-<hash>/`` and ``current`` is swapped
to it in one rename, so a run never sees half a sync. Each Claude config dir
this runner knows (the default ``~/.claude`` and every declared account) gets a
symlink per item — ``skills/<name>`` → ``current/skills/<name>``,
``agents/<name>.md`` → ``current/agents/<name>.md`` — so the names stay plain,
terminal sessions on this machine see them too, and the composer's skill list
(``skills_list.py``) picks them up.
Only links the sync owns are ever touched: a skill or agent of this machine's
own under the same name wins (listed as a ``conflict``), and an item dropped
from the bundle loses its link only when that link still points into
``LABSYNC_DIR``. Refused on the host sidecar — the lab has the originals.
"""
from __future__ import annotations
import base64
import datetime
import json
import os
import pathlib
import re
import shutil
import time
from typing import Callable
from fastapi import APIRouter, Header, HTTPException
from pydantic import BaseModel
from config import ACCOUNTS, IS_WORKER
LABSYNC_DIR = pathlib.Path(os.path.expanduser(os.environ.get(
"WORKER_LABSYNC_DIR", "~/.local/share/ai-agent-worker/lab-sync")))
_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
_HASH_RE = re.compile(r"^[0-9a-f]{8,64}$")
_PART_RE = re.compile(r"^[A-Za-z0-9_@+-][A-Za-z0-9._@+-]{0,127}$")
MAX_TOTAL = 8 * 1024 * 1024
KEEP = 2 # versions kept on disk: current + the one before
def _now_iso() -> str:
return datetime.datetime.now(datetime.timezone.utc) \
.strftime("%Y-%m-%dT%H:%M:%SZ")
def _valid_rel(rel: str) -> pathlib.PurePosixPath:
p = pathlib.PurePosixPath(rel)
if p.is_absolute() or not p.parts or len(p.parts) > 8 \
or not all(_PART_RE.match(x) and x not in (".", "..") for x in p.parts):
raise HTTPException(400, f"bad file path in bundle: {rel!r}")
return p
def _config_dirs() -> list[pathlib.Path]:
"""Every Claude config dir of this runner, the default first."""
out: list[pathlib.Path] = []
for d in ACCOUNTS.values():
p = d or pathlib.Path(os.path.expanduser("~/.claude"))
if p not in out:
out.append(p)
return out
def _state_file(root: pathlib.Path) -> pathlib.Path:
return root / "state.json"
def state(root: pathlib.Path | None = None) -> dict:
"""What ``/health`` reports as ``labSync`` — ``{"hash": None}`` before the
first sync (the hub reads a missing key as a sidecar without /sync)."""
try:
return json.loads(_state_file(root or LABSYNC_DIR).read_text())
except (OSError, ValueError):
return {"hash": None}
def _owned(link: pathlib.Path, root: pathlib.Path) -> bool:
"""A symlink this sync made (its target lives under ``root``)."""
if not link.is_symlink():
return False
target = os.path.normpath(os.path.join(link.parent, os.readlink(link)))
return any(target.startswith(r + os.sep)
for r in (os.path.normpath(root), os.path.realpath(root)))
def _link(link: pathlib.Path, target: pathlib.Path, root: pathlib.Path) -> bool:
"""Point ``link`` at ``target`` unless the machine has its own there.
True when the link is (now) ours."""
if link.is_symlink() or link.exists():
if not _owned(link, root):
return False
if os.readlink(link) == str(target):
return True
link.parent.mkdir(parents=True, exist_ok=True)
tmp = link.with_name(f".{link.name}.labsync")
try:
tmp.unlink()
except FileNotFoundError:
pass
os.symlink(target, tmp)
os.replace(tmp, link)
return True
def _write_version(root: pathlib.Path, body: "SyncBody") -> pathlib.Path:
total = 0
execs = set(body.executables or [])
stage = root / f".stage-{body.hash}-{os.getpid()}"
shutil.rmtree(stage, ignore_errors=True)
# Made up front: an empty bundle (everything unticked) is a version too.
stage.mkdir(parents=True)
try:
for name, files in body.skills.items():
if not _NAME_RE.match(name) or "SKILL.md" not in files:
raise HTTPException(400, f"bad skill in bundle: {name!r}")
for rel, b64 in files.items():
p = _valid_rel(rel)
try:
data = base64.b64decode(b64, validate=True)
except ValueError:
raise HTTPException(400, f"bad base64 for {name}/{rel}")
total += len(data)
if total > MAX_TOTAL:
raise HTTPException(413, "bundle too large")
dest = stage / "skills" / name / p
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_bytes(data)
# hub.json (a plugin skill with a proxy): this machine's
# tool-proxy token — readable by its user only.
os.chmod(dest, 0o600 if rel == "hub.json"
else 0o755 if f"{name}/{rel}" in execs else 0o644)
for name, text in body.agents.items():
if not _NAME_RE.match(name):
raise HTTPException(400, f"bad agent in bundle: {name!r}")
total += len(text.encode())
if total > MAX_TOTAL:
raise HTTPException(413, "bundle too large")
dest = stage / "agents" / f"{name}.md"
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_text(text, encoding="utf-8")
final = root / f"v-{body.hash}"
shutil.rmtree(final, ignore_errors=True)
os.replace(stage, final)
return final
except BaseException:
shutil.rmtree(stage, ignore_errors=True)
raise
def apply(body: "SyncBody", root: pathlib.Path | None = None,
config_dirs: list[pathlib.Path] | None = None) -> dict:
"""Write the bundle, swap ``current`` to it, (un)link every config dir.
Returns the new state."""
root = root or LABSYNC_DIR
root.mkdir(parents=True, exist_ok=True)
version = _write_version(root, body)
cur = root / "current"
tmp = root / ".current.tmp"
try:
tmp.unlink()
except FileNotFoundError:
pass
os.symlink(version.name, tmp)
os.replace(tmp, cur)
prev = state(root)
linked: dict[str, dict[str, list[str]]] = {}
conflicts: list[str] = []
for cfg in (config_dirs if config_dirs is not None else _config_dirs()):
mine = {"skills": [], "agents": []}
for name in sorted(body.skills):
if _link(cfg / "skills" / name, cur / "skills" / name, root):
mine["skills"].append(name)
else:
conflicts.append(str(cfg / "skills" / name))
for name in sorted(body.agents):
if _link(cfg / "agents" / f"{name}.md", cur / "agents" / f"{name}.md", root):
mine["agents"].append(name)
else:
conflicts.append(str(cfg / "agents" / f"{name}.md"))
# Items the previous bundle had and this one doesn't: drop our links.
before = (prev.get("linked") or {}).get(str(cfg)) or {}
for name in set(before.get("skills") or []) - set(body.skills):
link = cfg / "skills" / name
if _owned(link, root):
link.unlink()
for name in set(before.get("agents") or []) - set(body.agents):
link = cfg / "agents" / f"{name}.md"
if _owned(link, root):
link.unlink()
linked[str(cfg)] = mine
for old in sorted((p for p in root.glob("v-*") if p != version),
key=lambda p: p.stat().st_mtime, reverse=True)[KEEP - 1:]:
shutil.rmtree(old, ignore_errors=True)
st = {"hash": body.hash, "syncedAt": _now_iso(),
"skills": sorted(body.skills), "agents": sorted(body.agents),
"conflicts": conflicts, "linked": linked}
sf = _state_file(root)
sf.with_suffix(".tmp").write_text(json.dumps(st, indent=2))
os.replace(sf.with_suffix(".tmp"), sf)
return st
def needs_apply(st: dict, h: str) -> bool:
"""Whether ``/sync`` with bundle ``h`` has work to do: a new hash, or the
same one whose last apply left ``conflicts`` — the machine's own skill may
be gone since (removed by hand), so *Sync now* links ours in its place."""
return st.get("hash") != h or bool(st.get("conflicts"))
def public(st: dict) -> dict:
"""``labSync`` as /health and /sync serve it (no per-dir link table)."""
return {k: st.get(k) for k in ("hash", "syncedAt", "skills", "agents",
"conflicts")}
# ── harness drivers + provider usage readers (typed-plugins spec §3.1) ───────
# A bundle may carry two more maps — ``harnesses`` / ``providers``:
# ``{pluginId: {hash, files: {rel: base64}}}``, each a harness / provider
# plugin's dir (its plugin.json + sidecar/ code). They are written as one
# version under the loader's root (``~/.ai-agent-worker/harnesses`` /
# ``…/providers``: ``v-<hash>/`` + an index.json built from each plugin.json,
# then ``current`` swapped to it) and the drivers reloaded
# (routes_harnesses.reload_all). A reload that fails swaps ``current`` back,
# reloads what was there, and the whole /sync answers 409 — the hub keeps
# its error and tries again later; nothing of the bundle is half-applied.
# A map left out (None) leaves that kind as it is; ``{}`` clears it.
# A guest's computer takes only harnesses whose plugin.json says
# ``guestAllowed`` and no provider readers at all (they read the owner's plans).
def _guest_computer() -> bool:
"""A link worker that isn't the owner's (mirrors mcp_base.enabled)."""
if not IS_WORKER:
return False
try:
import link
cfg = link.config()
except Exception:
cfg = None
return bool(cfg) and not cfg.get("owner")
def _plugins_hash(m: dict) -> str:
import hashlib
h = hashlib.sha256()
for pid in sorted(m):
h.update(f"{pid}\0{m[pid].get('hash')}\0".encode())
return h.hexdigest()[:16]
def _index_entry(kind: str, pid: str, man: dict, hash_: str, pdir: pathlib.Path):
"""(id, index entry) of one plugin, from its plugin.json — None when it
isn't a plugin of that kind."""
if kind == "harnesses":
obj = man.get("harness")
code = obj.get("sidecar") if isinstance(obj, dict) else None
cid = obj.get("harnessId") if isinstance(obj, dict) else None
default_entry = "driver.py"
else:
obj = man.get("provider")
code = obj.get("usageReader") if isinstance(obj, dict) else None
cid = obj.get("vendorId") if isinstance(obj, dict) else None
default_entry = "usage.py"
if not isinstance(cid, str):
return None
if not isinstance(code, dict):
if kind == "harnesses":
return None # a harness plugin always has its driver
code = None # a provider with no usage reader: config only
e = {"pluginId": pid, "dir": pid,
"entry": str(code.get("entry") or default_entry) if code is not None else None,
"hash": hash_}
if kind == "harnesses":
e["guestAllowed"] = bool(obj.get("guestAllowed"))
else:
try:
cfg = json.loads((pdir / "config.json").read_text())
if isinstance(cfg, dict):
e["config"] = cfg
except (OSError, ValueError):
pass
return cid, e
def write_plugins(kind: str, root: pathlib.Path, bundles: dict,
guest: bool = False) -> tuple[str | None, str]:
"""Write one kind's bundles as a version under ``root`` and swap
``current`` to it. Returns (the previous ``current`` target or None,
the new hash). Raises HTTPException on a bad bundle (nothing swapped)."""
if guest and kind == "providers":
bundles = {}
h = _plugins_hash(bundles)
root.mkdir(parents=True, exist_ok=True)
cur = root / "current"
prev = os.readlink(cur) if cur.is_symlink() else None
if prev == f"v-{h}" and (root / prev / "index.json").is_file():
return prev, h
stage = root / f".stage-{h}-{os.getpid()}"
shutil.rmtree(stage, ignore_errors=True)
stage.mkdir(parents=True)
total = 0
index: dict[str, dict] = {}
try:
for pid, b in bundles.items():
if not _NAME_RE.match(pid) or not isinstance(b, dict) \
or not isinstance(b.get("files"), dict):
raise HTTPException(400, f"bad {kind} bundle: {pid!r}")
pdir = stage / pid
for rel, val in b["files"].items():
rp = _valid_rel(rel)
if not isinstance(val, str):
raise HTTPException(400, f"bad file in {pid}: {rel!r}")
try:
data = base64.b64decode(val, validate=True)
except ValueError:
raise HTTPException(400, f"bad base64 for {pid}/{rel}")
total += len(data)
if total > MAX_TOTAL:
raise HTTPException(413, "bundle too large")
dest = pdir / rp
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_bytes(data)
os.chmod(dest, 0o600 if rel == "config.json" else 0o644)
try:
man = json.loads((pdir / "plugin.json").read_text())
except (OSError, ValueError):
raise HTTPException(400, f"{kind} bundle {pid!r} has no readable plugin.json")
got = _index_entry(kind, pid, man if isinstance(man, dict) else {},
str(b.get("hash") or ""), pdir)
if got is None:
raise HTTPException(400, f"{pid!r} is not a {kind[:-2] if kind == 'harnesses' else 'provider'} plugin")
cid, entry = got
if guest and kind == "harnesses" and not entry.get("guestAllowed"):
shutil.rmtree(pdir, ignore_errors=True) # not for a guest's computer
continue
if cid in index:
raise HTTPException(400, f"two {kind} bundles provide {cid!r}")
index[cid] = entry
(stage / "index.json").write_text(json.dumps(
{"version": 1, "hash": h, kind: index}, indent=2))
final = root / f"v-{h}"
shutil.rmtree(final, ignore_errors=True)
os.replace(stage, final)
except BaseException:
shutil.rmtree(stage, ignore_errors=True)
raise
_swap(root, final.name)
return prev, h
def _swap(root: pathlib.Path, target: str | None) -> None:
cur = root / "current"
if target is None:
try:
cur.unlink()
except FileNotFoundError:
pass
return
tmp = root / ".current.tmp"
try:
tmp.unlink()
except FileNotFoundError:
pass
os.symlink(target, tmp)
os.replace(tmp, cur)
def _prune(root: pathlib.Path) -> None:
cur = os.readlink(root / "current") if (root / "current").is_symlink() else None
for old in sorted((p for p in root.glob("v-*") if p.name != cur),
key=lambda p: p.stat().st_mtime, reverse=True)[KEEP - 1:]:
shutil.rmtree(old, ignore_errors=True)
def _plugin_roots() -> dict:
import harness_loader
import usage_loader
return {"harnesses": harness_loader.LOADER.root(),
"providers": usage_loader.LOADER.root()}
def _plugin_loaders() -> dict:
import harness_loader
import usage_loader
return {"harnesses": harness_loader.LOADER, "providers": usage_loader.LOADER}
def _version_of(root: pathlib.Path) -> str | None:
"""The plugins hash of the version ``root/current`` points at (``v-<hash>``
with its index.json), None when no /sync ever wrote one."""
cur = root / "current"
try:
t = os.readlink(cur) if cur.is_symlink() else None
except OSError:
return None
if not t or not t.startswith("v-") or not (root / t / "index.json").is_file():
return None
return t[2:]
def _loaded_matches(kind: str, root: pathlib.Path, loader) -> bool:
"""Do the drivers ``loader`` runs match the current version's index —
every entry with code (a provider without a usage reader has none),
by id and hash? False on an unreadable index."""
try:
idx = json.loads((root / "current" / "index.json").read_text())
items = idx.get(kind) if isinstance(idx, dict) else None
want = {cid: spec.get("hash") for cid, spec in (items or {}).items()
if isinstance(spec, dict) and spec.get("entry", "driver.py") is not None}
except (OSError, ValueError, AttributeError):
return False
have = {e.id: e.hash for e in loader.entries()}
return have == want
def plugin_sync(roots: dict | None = None, loaders: dict | None = None) -> dict:
"""``{kind: {"version": hash | None, "loaded": bool | None}}`` — which
version of the hub's harness / provider maps this worker holds
(``_plugins_hash`` of what the last /sync wrote) and whether the live
drivers are that version's. /health reports it; the hub re-sends a
bundle whose maps a worker doesn't hold or run, even under the bundle's
own hash (workers/labsync.status) — a sidecar from before the plugin
maps once took a bundle's hash and dropped its maps."""
roots = roots if roots is not None else _plugin_roots()
loaders = loaders if loaders is not None else _plugin_loaders()
out: dict[str, dict] = {}
for kind, root in roots.items():
v = _version_of(root)
out[kind] = {"version": v,
"loaded": _loaded_matches(kind, root, loaders[kind]) if v else None}
return out
def plugins_stale(body: "SyncBody", roots: dict | None = None,
loaders: dict | None = None) -> bool:
"""Does the bundle carry a harness / provider map this worker doesn't
hold — another version, or the right one with other drivers running?
Checked even when the bundle's hash is the one already applied."""
kinds = {k: v for k, v in (("harnesses", body.harnesses), ("providers", body.providers))
if v is not None}
if not kinds:
return False
held = plugin_sync(roots, loaders)
guest = _guest_computer()
for kind, bundles in kinds.items():
want = _plugins_hash({} if guest and kind == "providers" else bundles)
got = held.get(kind) or {}
if got.get("version") != want or got.get("loaded") is False:
return True
return False
def apply_plugins(body: "SyncBody", roots: dict | None = None,
reload: Callable[[], dict] | None = None) -> dict | None:
"""Write the bundle's harness / provider maps and reload the drivers —
or put everything back and raise 409. None when the bundle has neither."""
kinds = {k: v for k, v in (("harnesses", body.harnesses), ("providers", body.providers))
if v is not None}
if not kinds:
return None
if roots is None:
roots = _plugin_roots()
if reload is None:
import routes_harnesses
reload = routes_harnesses.reload_all
guest = _guest_computer()
prevs: dict[str, str | None] = {}
try:
for kind, bundles in kinds.items():
prevs[kind], _ = write_plugins(kind, roots[kind], bundles, guest=guest)
except BaseException:
for kind, prev in prevs.items():
_swap(roots[kind], prev)
raise
out = reload()
if not out.get("ok"):
for kind, prev in prevs.items():
_swap(roots[kind], prev)
reload() # the drivers that half-loaded go back to what was there
raise HTTPException(409, {"message": f"harness reload failed: {out.get('error')}",
"kind": "harness_reload", "rolledBack": True})
for kind in prevs:
_prune(roots[kind])
return {k: {"hash": _plugins_hash(v), "plugins": sorted(v)} for k, v in kinds.items()}
# ── harnessHooks (backend plugins/harness_hooks.py) ───────────────────────────
# A bundle's ``hooks`` map — ``{hash, rules, files: {<plugin>/<path>: b64}}``,
# already filtered for this machine by the hub — is written whole to
# plugin_hooks.root() (``~/.ai-agent-worker/hooks``): index.json + the script
# hooks' files. ``{}`` clears it; absent (an older hub) leaves it alone. A
# guest's computer keeps only rules marked ``guestAllowed`` whatever it is sent.
HOOK_FILE_MAX = 256 * 1024
def write_hooks(hooks: dict, root: pathlib.Path | None = None) -> dict:
import plugin_hooks
root = root or plugin_hooks.root(True)
guest = _guest_computer()
rules = [r for r in (hooks.get("rules") or []) if isinstance(r, dict)
and (not guest or r.get("guestAllowed") is True)]
# Plugins' path shims (path_shims.py) ride the same map: the same rule.
shims = [s for s in (hooks.get("shims") or []) if isinstance(s, dict)
and (not guest or s.get("guestAllowed") is True)]
files: dict[str, bytes] = {}
for rel, b64 in (hooks.get("files") or {}).items():
try:
_valid_rel(rel)
data = base64.b64decode(b64, validate=True)
except Exception:
raise HTTPException(400, f"bad hook file {rel!r}") from None
if len(data) > HOOK_FILE_MAX:
raise HTTPException(400, f"hook file {rel!r} is too big")
files[rel] = data
rules = [r for r in rules if not r.get("script") or r["script"] in files]
shims = [s for s in shims if s.get("script") in files]
used = {r.get("script") for r in rules} | {s.get("script") for s in shims}
root.parent.mkdir(parents=True, exist_ok=True)
tmp = root.with_name(f".{root.name}-{os.getpid()}-{int(time.time() * 1000)}")
tmp.mkdir()
for rel, data in files.items():
if rel in used:
f = tmp / rel
f.parent.mkdir(parents=True, exist_ok=True)
f.write_bytes(data)
index = {"hash": str(hooks.get("hash") or ""), "hooks": rules}
if shims:
index["shims"] = shims
(tmp / "index.json").write_text(json.dumps(index, indent=2), encoding="utf-8")
old = root.with_name(f".{root.name}-old-{os.getpid()}-{int(time.time() * 1000)}")
if root.exists():
os.replace(root, old)
os.replace(tmp, root)
shutil.rmtree(old, ignore_errors=True)
out = {"hash": str(hooks.get("hash") or ""), "rules": len(rules)}
if shims:
out["shims"] = len(shims)
return out
class SyncBody(BaseModel):
hash: str
skills: dict[str, dict[str, str]] = {}
agents: dict[str, str] = {}
executables: list[str] = []
harnesses: dict[str, dict] | None = None
providers: dict[str, dict] | None = None
hooks: dict | None = None
def make_router(auth: Callable[[str | None], None]) -> APIRouter:
router = APIRouter()
@router.post("/sync")
def sync(body: SyncBody,
authorization: str | None = Header(default=None)) -> dict:
auth(authorization)
if not IS_WORKER:
raise HTTPException(409, "the host sidecar has the lab's skills already")
if not _HASH_RE.match(body.hash):
raise HTTPException(400, "bad bundle hash")
st = state()
skills = needs_apply(st, body.hash)
# The plugin maps are checked on their own: a worker can hold the
# bundle's hash without its drivers (an older sidecar took the hash
# and dropped the maps, or its plugin dir went away since).
if not skills and not plugins_stale(body):
return {"changed": False, "labSync": public(st)}
# The drivers first: a reload that fails is a 409 with nothing applied.
plugins = apply_plugins(body)
if body.hooks is not None:
hooks_out = write_hooks(body.hooks)
else:
hooks_out = None
out = {"changed": True, "labSync": public(apply(body) if skills else st)}
if plugins is not None:
out["plugins"] = plugins
if hooks_out is not None:
out["hooks"] = hooks_out
return out
return router