Files
gabrielvidalandClaude Opus 5.5 4d0dcfa3ff refactor(toolproxy): the tools are plugins — retire the core brokers, the guests' tool groups and the hub editions
Since 2026-11-25 nanobanana, video-extract, 3d-gen, 3d-render, matomo,
movies and meta are live plugins with their own proxies and managed grants,
but the core still served the old path next to them — and its hub editions
won over the plugin skills on workers. This finishes the move (form
ai-agent-moves-to-ai-agent-plugins_o2qxmd, move A). Rebased on 41665fa2,
which had already removed the core's Meta Business.

- gone: toolproxy/{matomo,media,webroutes,owned,catalog}.py, the nanobanana /
  3d-gen / 3d-render / video-extract / matomo / movies routes and the movies
  webhook, cli/skills/{nanobanana,3d-gen,3d-render,video-extract,matomo,
  movies}, the guests' `tools` groups (users store, Caller.tool_groups,
  Me/GuestUser.tools, tools.matomoSites), the User page's Paid tools and
  Tools budget panels
- kept: the /proxy/tools door (tokens, whoami — now the caller's plugins and
  spend — and the shared client), the tool ledger, the tools chip, a guest
  job's tool token (c6e15991: tool_scope still gives one with plugin skills)
- labsync: a plugin skill wins over a lab skill of the same name; plugin
  skills with a proxy keep their hub.json
- guest runs get their plugins' skills on spawn, resume, reply, fork and No
  project runs alike (deps passed to scope_for / scratch_scope everywhere)
- Movies brings Jellyfin when the movies grant comes on (new guest, or the
  owner's switch)
- plugins/carryover_tools.py: tool groups → grants / installs (never over an
  explicit grant), Meta keys + saved days (only where the plugin has none),
  Matomo viewers, Seerr users and pending requests, 3d-gen ownership → the
  plugins' data, once
- matomo_sites: users.json tools.matomoSites → the matomo grant's
  `extraSites` (list grantField, sibling ai-agent-plugins PR), and the grant
  on for an `analytics` guest — once per guest, so Cel (analytics + site 11
  after the groups moved) gets it; an explicit grant only gets extraSites
  when it has none; waits for a matomo manifest with the field
- Me → Budget's Tools card reads the guest's managed plugins

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

689 lines
28 KiB
Python

"""
Lab sync — the homelab's portable skills and agents, kept current on every worker.
A worker only sees the skills of its own machine: the user-level
``<config>/skills`` and its run's cwd. The homelab's ``.claude/skills`` and
``.claude/agents`` live in a private repo a Mac can't pull, so the hub ships
them, from the canonical checkout (mounted at ``/workspace/.claude``):
* **which** — a skill or agent whose frontmatter says ``portable: true`` (it
needs neither the homelab checkout nor lab-only infra) goes to every worker;
``portable: <account>`` (``work``, ``personal``…) only to the workers whose
record's ``account`` is that one (a work-only skill stays off a personal Mac);
Settings → *Skills & agents* ticks or unticks any
of them for that worker (``labSyncOverrides`` on its record, ``{name: bool}``
keyed ``skill:<name>`` / ``agent:<name>``);
* **how** — the worker's ``/health`` says which bundle it holds
(``labSync.hash``); each liveness probe compares it with the bundle the hub
would send that worker and, when they differ, POSTs it to ``/sync``. The
worker links it into its user-level skills/agents dirs
(``sidecar/labsync.py``). Same direction as auto-update (``updates.py``): the
hub calls in, the worker never calls the lab. A skill edit that lands on
homelab ``main`` reaches the Macs on the next probe (≤ 15 s).
Portable **agents** also reach every lab run, whatever its cwd, through
``claude --agents`` (``runs/extras.py``) — the way the clarifier does.
What a bundle never carries: ``.env*`` files (a skill's secrets stay on the
lab), vendor trees (``node_modules``, venvs, caches, tests), anything over
``MAX_FILE``, and past ``MAX_BUNDLE`` the rest of the files (listed in
``skipped``).
"""
from __future__ import annotations
import base64
import hashlib
import json
import os
import pathlib
import re
import time
from fastapi import HTTPException
from dashboards.skills import parse_frontmatter
SOURCE = pathlib.Path(os.environ.get(
"LABSYNC_SOURCE",
os.path.join(os.environ.get("WORKSPACE", "/workspace"), ".claude")))
FLAG = "portable"
IGNORE_DIRS = {"node_modules", ".git", "__pycache__", "dist", "build", ".venv",
"venv", ".pytest_cache", ".mypy_cache", ".ruff_cache", "tests"}
MAX_FILE = 512 * 1024
MAX_BUNDLE = 4 * 1024 * 1024
RETRY_S = 10 * 60
_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
# Statuses the Settings page shows.
CURRENT, OUTDATED, FAILED, UNSUPPORTED, UNKNOWN = (
"current", "outdated", "failed", "unsupported", "unknown")
CATALOG_TTL = 5.0
_catalogs: dict[str, tuple[float, list[dict]]] = {} # source → (when, items)
_bundles: dict[tuple, dict] = {} # fingerprint → bundle
_attempts: dict[str, tuple[str, float]] = {} # worker id → (hash, when)
def truthy(v) -> bool:
return isinstance(v, str) and v.strip().lower() in ("true", "yes", "1")
_ACCOUNT_RE = re.compile(r"^[a-z][a-z0-9_-]{0,31}$")
def scope_account(v) -> str | None:
"""``portable: <account>`` → that account name; ``true``/``false``/missing
→ None (``true`` is every worker, read by :func:`truthy`)."""
if not isinstance(v, str):
return None
a = v.strip().lower()
if a in ("", "true", "yes", "1", "false", "no", "0", "none") \
or not _ACCOUNT_RE.match(a):
return None
return a
def default_on(i: dict, account: str | None) -> bool:
"""Whether item ``i`` goes to a worker of ``account`` by default (no
override): ``portable: true`` everywhere, ``portable: <account>`` on
that account's workers only."""
return bool(i.get("portable")) or (
bool(i.get("account")) and i.get("account") == account)
def _read(f: pathlib.Path) -> str | None:
try:
return f.read_text(encoding="utf-8", errors="replace")
except OSError:
return None
def catalog(source: pathlib.Path | None = None) -> list[dict]:
"""Every lab skill and agent: ``{key, kind, name, description, portable,
path}`` — what the Settings checklist lists. Re-read at most every
``CATALOG_TTL`` s: the workers payload asks for it on every request."""
src = source or SOURCE
hit = _catalogs.get(str(src))
if hit and time.time() - hit[0] < CATALOG_TTL:
return hit[1]
out = _scan(src)
_catalogs[str(src)] = (time.time(), out)
return out
def _scan(src: pathlib.Path) -> list[dict]:
out: list[dict] = []
try:
dirs = sorted((src / "skills").iterdir())
except OSError:
dirs = []
for d in dirs:
text = _read(d / "SKILL.md") if _NAME_RE.match(d.name) else None
if text is None:
continue
fm = parse_frontmatter(text)
out.append({"key": f"skill:{d.name}", "kind": "skill", "name": d.name,
"description": str(fm.get("description") or "")[:300],
"portable": truthy(fm.get(FLAG)),
"account": scope_account(fm.get(FLAG)), "path": d})
try:
files = sorted((src / "agents").glob("*.md"))
except OSError:
files = []
for f in files:
text = _read(f) if _NAME_RE.match(f.stem) else None
if text is None:
continue
fm = parse_frontmatter(text)
out.append({"key": f"agent:{f.stem}", "kind": "agent", "name": f.stem,
"description": str(fm.get("description") or "")[:300],
"portable": truthy(fm.get(FLAG)),
"account": scope_account(fm.get(FLAG)), "path": f})
return out
def chosen(items: list[dict], overrides: dict | None,
account: str | None = None) -> list[dict]:
"""The items a worker of ``account`` gets: the portable ones (every
worker's, and its account's), then its overrides."""
ov = overrides or {}
return [i for i in items if ov.get(i["key"], default_on(i, account)) is True]
def _skill_files(d: pathlib.Path) -> list[pathlib.Path]:
out: list[pathlib.Path] = []
for dirpath, dirnames, filenames in os.walk(d):
dirnames[:] = sorted(x for x in dirnames
if x not in IGNORE_DIRS and not x.startswith("."))
for fn in sorted(filenames):
p = pathlib.Path(dirpath) / fn
# No dotfile at all (.env*, .gitignore, .DS_Store…): the worker
# refuses a path part that starts with a dot (sidecar labsync
# `_valid_rel`), and one such file failed a whole bundle — every
# guest computer's sync stopped on screenshot's
# scripts/evox2-runner/.gitignore (2026-11-04 → 11-06).
if fn.startswith(".") or fn.endswith((".pyc", ".pyo")) or not p.is_file():
continue
out.append(p)
return out
def _fingerprint(items: list[dict]) -> tuple:
"""Cheap change key: every bundled file's (path, size, mtime)."""
parts = []
for i in items:
files = _skill_files(i["path"]) if i["kind"] == "skill" else [i["path"]]
for p in files:
try:
st = p.stat()
except OSError:
continue
parts.append((i["key"], str(p), st.st_size, st.st_mtime_ns,
os.access(p, os.X_OK)))
return tuple(parts)
def build(items: list[dict]) -> dict:
"""The bundle of ``items``: ``{hash, skills: {name: {rel: base64}},
agents: {name: text}, executables, skipped}``. Cached on the files'
(size, mtime): the probe asks for it every 15 s per worker."""
key = _fingerprint(items)
if key in _bundles:
return _bundles[key]
h = hashlib.sha256()
total = 0
skills: dict[str, dict[str, str]] = {}
agents: dict[str, str] = {}
execs: list[str] = []
skipped: list[str] = []
for i in items:
name = i["name"]
if i["kind"] == "agent":
text = _read(i["path"])
if text is not None:
agents[name] = text
h.update(f"a\0{name}\0".encode() + text.encode())
continue
files: dict[str, str] = {}
x_here: list[str] = []
for p in _skill_files(i["path"]):
rel = p.relative_to(i["path"]).as_posix()
try:
data = p.read_bytes()
except OSError:
continue
if len(data) > MAX_FILE or total + len(data) > MAX_BUNDLE:
skipped.append(f"{name}/{rel}")
continue
total += len(data)
files[rel] = base64.b64encode(data).decode()
# The executable bit travels in the hash too: a chmod is a change.
x = os.access(p, os.X_OK)
if x:
x_here.append(f"{name}/{rel}")
h.update(f"s\0{name}\0{rel}\0{'x' if x else '-'}\0".encode() + data)
if "SKILL.md" in files:
skills[name] = files
execs += x_here
bundle = {"hash": h.hexdigest()[:16], "skills": skills, "agents": agents,
"executables": execs, "skipped": skipped}
if len(_bundles) > 32:
_bundles.clear()
_bundles[key] = bundle
return bundle
# () → the lab skills every guest gets (``guestDefaults.sharedSkills``, the
# repo's own — wired in by core/state): all a guest's computer is sent, with
# the skills of the live plugins they have (installed or granted).
guest_skills = lambda: [] # noqa: E731
# (uid) → enabled live plugins' skill descriptors (plugins/store.py).
user_plugins = lambda uid: [] # noqa: E731
# () → the hub's PluginStore, or None (core/state). Read duck-typed: before the
# typed-plugins store lands (Wave 1A) it has no ``sidecar_bundles`` and the
# materialized dirs on disk are read instead (:func:`plugin_bundles`).
plugin_store = lambda: None # noqa: E731
# (worker) → ``{url, token}``: where the plugin skills with a proxy on that
# machine call the tool proxy, with its proxy token (core/state).
tool_hub = lambda w: None # noqa: E731
def all_items(source: pathlib.Path | None = None) -> list[dict]:
"""What an owner's worker may get: the lab's skills and agents."""
return catalog(source)
def plugin_items(uid: str) -> list[dict]:
"""Catalog items for ``uid``'s enabled live plugins that provide a skill."""
out = []
for p in user_plugins(uid) or ():
d = pathlib.Path(p["dir"])
text = _read(d / "SKILL.md")
if text is None:
continue
fm = parse_frontmatter(text)
name = p["name"]
out.append({"key": f"skill:{name}", "kind": "skill", "name": name,
"description": str(fm.get("description") or "")[:300],
"portable": True, "path": d, "hub": bool(p.get("hasProxy"))})
return out
def items_for(w: dict, source: pathlib.Path | None = None) -> list[dict]:
"""The skills (and, for an owner's worker, agents) a worker is sent. A live
plugin's skill wins over a lab skill of the same name — the lab's own
``movies``, ``meta``, ``3d-gen``… are shims for its own sessions, the
plugin's edition reaches the hub from any machine (its ``hub.json``)."""
if w.get("owner"):
extra = plugin_items(w["owner"])
mine = {i["name"] for i in extra}
names = set(guest_skills()) - mine
base = [i for i in catalog(source) if i["kind"] == "skill" and i["name"] in names]
return base + extra
extra = plugin_items("owner")
mine = {i["name"] for i in extra}
base = chosen([i for i in all_items(source)
if not (i["kind"] == "skill" and i["name"] in mine)],
w.get("labSyncOverrides"), w.get("account"))
return base + extra
def with_hub(bundle: dict, names: list[str], hub: dict | None) -> dict:
"""The bundle with each proxied plugin skill's ``hub.json`` — the
machine's tool proxy URL and token (its own proxy token) — and a hash that
moves with them (a rotated token resyncs)."""
present = [n for n in names if n in bundle["skills"]]
if not hub or not present:
return bundle
data = base64.b64encode(json.dumps({"url": hub["url"], "token": hub["token"]})
.encode()).decode()
skills = dict(bundle["skills"])
for n in present:
skills[n] = {**skills[n], "hub.json": data}
h = hashlib.sha256(f"{bundle['hash']}\0{hub['url']}\0{hub['token']}".encode())
return {**bundle, "skills": skills, "hash": h.hexdigest()[:16]}
def for_worker(w: dict, source: pathlib.Path | None = None) -> dict:
items = items_for(w, source)
bundle = build(items)
hub = [i["name"] for i in items if i.get("hub")]
if hub:
try:
bundle = with_hub(bundle, hub, tool_hub(w))
except Exception:
pass
plugins = plugin_bundles(guest_only=bool(w.get("owner")))
plugins["hooks"] = hooks_bundle(w)
return with_plugins(bundle, plugins)
def hooks_bundle(w: dict) -> dict:
"""The owner's plugins' ``harnessHooks`` that apply to worker ``w`` (its
runner id, its profile; a guest's computer only ``guestAllowed`` ones) —
``{hash, rules, files}``, empty rules when none (plugins/harness_hooks.py)."""
try:
store = plugin_store()
except Exception:
store = None
if store is None or not hasattr(store, "active_by_kind"):
return {}
from plugins import harness_hooks
try:
return harness_hooks.bundle_for_worker(store, w)
except Exception:
return {}
# ── harness drivers + provider usage readers (typed-plugins spec §3.1) ───────
# The lab's PluginStore materializes every enabled ``harness-*`` plugin's
# sidecar code (and ``provider-*`` usage reader) under these dirs, each with
# an ``index.json``; a worker gets the same as two extra maps in its /sync
# bundle — ``harnesses`` / ``providers``: ``{pluginId: {hash, files: {rel:
# base64}}}`` — which its sidecar writes under ``~/.ai-agent-worker/`` and
# reloads (sidecar/labsync.py, harness_loader.py). A guest's computer gets
# only the harnesses marked ``guestAllowed`` and no provider usage reader
# (those read the owner's plans).
LIVE_HARNESSES_DIR = pathlib.Path(os.environ.get(
"PLUGINS_LIVE_HARNESSES_DIR", "/data/plugins/live-harnesses"))
LIVE_PROVIDERS_DIR = pathlib.Path(os.environ.get(
"PLUGINS_LIVE_PROVIDERS_DIR", "/data/plugins/live-providers"))
_plugin_bundles: dict[tuple, dict] = {} # fingerprint → bundles
# The worker's own rule for a bundle path (sidecar/labsync.py ``_valid_rel``):
# up to 8 parts, none hidden. A path it refuses fails the *whole* /sync, so
# it is never shipped — a plugin's ``runner/.gitignore`` kept every owner
# worker off its harness plugins (2026-11-26).
_PART_RE = re.compile(r"^[A-Za-z0-9_@+-][A-Za-z0-9._@+-]{0,127}$")
MAX_PARTS = 8
def _shippable(rel: tuple[str, ...]) -> bool:
return 0 < len(rel) <= MAX_PARTS and all(_PART_RE.match(x) for x in rel)
def _code_files(d: pathlib.Path) -> list[pathlib.Path]:
out = []
for p in sorted(d.rglob("*")):
rel = p.relative_to(d).parts
if p.is_file() and not any(x in IGNORE_DIRS for x in rel) and _shippable(rel) \
and p.suffix != ".pyc":
out.append(p)
return out
def _live_items(root: pathlib.Path, key: str, guest_only: bool) -> list[tuple[str, pathlib.Path]]:
"""``[(pluginId, dir)]`` of a materialized live dir's index.json. A guest
computer's view keeps only ``guestAllowed`` entries."""
try:
idx = json.loads((root / "index.json").read_text())
except (OSError, ValueError):
return []
items = idx.get(key) if isinstance(idx, dict) else None
out = []
for spec in (items or {}).values() if isinstance(items, dict) else ():
if not isinstance(spec, dict):
continue
if guest_only and spec.get("guestAllowed") is not True:
continue
pid = str(spec.get("pluginId") or "")
if not _NAME_RE.match(pid):
continue
d = spec.get("dir") or pid
pdir = pathlib.Path(d) if os.path.isabs(str(d)) else root / str(d)
# `dir` may name the code dir: ship the whole plugin dir (plugin.json with it)
if not (pdir / "plugin.json").is_file() and (pdir.parent / "plugin.json").is_file():
pdir = pdir.parent
if not pdir.is_dir():
continue
if guest_only and not _manifest_guest_allowed(pdir / "plugin.json"):
continue # the index said so, its own plugin.json doesn't
out.append((pid, pdir))
return out
def _manifest_guest_allowed(path: pathlib.Path) -> bool:
try:
man = json.loads(path.read_text())
except (OSError, ValueError):
return False
h = man.get("harness") if isinstance(man, dict) else None
return man.get("kind") == "harness" and isinstance(h, dict) and h.get("guestAllowed") is True
def _bundle_guest_allowed(b: dict) -> bool:
"""A {hash, files} bundle whose own plugin.json says guestAllowed."""
raw = (b.get("files") or {}).get("plugin.json")
if not isinstance(raw, str):
return False
try:
man = json.loads(base64.b64decode(raw))
except (ValueError, TypeError):
return False
h = man.get("harness") if isinstance(man, dict) else None
return man.get("kind") == "harness" and isinstance(h, dict) and h.get("guestAllowed") is True
def _bundle_dirs(items: list[tuple[str, pathlib.Path]]) -> dict:
out: dict[str, dict] = {}
total = 0
for pid, d in items:
h = hashlib.sha256()
files: dict[str, str] = {}
for p in _code_files(d):
rel = p.relative_to(d).as_posix()
try:
data = p.read_bytes()
except OSError:
continue
if len(data) > MAX_FILE or total + len(data) > MAX_BUNDLE:
continue
total += len(data)
files[rel] = base64.b64encode(data).decode()
h.update(rel.encode() + b"\0" + data + b"\0")
if "plugin.json" in files:
out[pid] = {"hash": h.hexdigest()[:16], "files": files}
return out
def _disk_bundles(guest_only: bool) -> dict:
hs = _live_items(LIVE_HARNESSES_DIR, "harnesses", guest_only)
ps = [] if guest_only else _live_items(LIVE_PROVIDERS_DIR, "providers", False)
key = (guest_only, tuple((pid, str(d), _fingerprint_dir(d)) for pid, d in hs + ps))
if key in _plugin_bundles:
return _plugin_bundles[key]
out = {"harnesses": _bundle_dirs(hs), "providers": _bundle_dirs(ps)}
if len(_plugin_bundles) > 16:
_plugin_bundles.clear()
_plugin_bundles[key] = out
return out
def _fingerprint_dir(d: pathlib.Path) -> tuple:
parts = []
for p in _code_files(d):
try:
st = p.stat()
except OSError:
continue
parts.append((str(p), st.st_size, st.st_mtime_ns))
return tuple(parts)
def plugin_bundles(guest_only: bool = False) -> dict:
"""``{"harnesses": {pluginId: {hash, files}}, "providers": {…}}`` for a
worker — ``guest_only``: a guest's computer (guestAllowed harnesses only,
no provider readers). From the PluginStore when it can say
(``sidecar_bundles(guest_only=…)``), else from the materialized dirs."""
store = None
try:
store = plugin_store()
except Exception:
store = None
fn = getattr(store, "sidecar_bundles", None)
if callable(fn):
try:
got = fn(guest_only=guest_only) or {}
out = {"harnesses": dict(got.get("harnesses") or {}),
"providers": {} if guest_only else dict(got.get("providers") or {})}
if guest_only:
# Only an explicit guestAllowed — never a harness that just
# doesn't say (its plugin.json is checked too).
out["harnesses"] = {k: v for k, v in out["harnesses"].items()
if isinstance(v, dict) and v.get("guestAllowed") is True
and _bundle_guest_allowed(v)}
return out
except Exception:
pass
try:
return _disk_bundles(guest_only)
except OSError:
return {"harnesses": {}, "providers": {}}
def with_plugins(bundle: dict, plugins: dict) -> dict:
"""The bundle with the harness / provider maps — **always both**, ``{}``
when there are none: the worker's ``/sync`` reads a map left out as
"leave that kind as it is" and ``{}`` as "clear it", so a harness plugin
disabled or removed on the hub leaves every worker too. The hash moves
with the maps; with none it is the bare bundle's (a worker that never
had a plugin isn't re-synced for nothing, one that had some is — its
hash differs)."""
hs, ps = plugins.get("harnesses") or {}, plugins.get("providers") or {}
# harnessHooks ride as a third map: ``{hash, rules, files}``; with no rule
# it is ``{}`` (clear) and leaves the hash alone.
hk = plugins.get("hooks") or {}
hk = hk if hk.get("rules") else {}
if not hs and not ps and not hk:
return {**bundle, "harnesses": {}, "providers": {}, "hooks": {}}
h = hashlib.sha256(bundle["hash"].encode())
for kind, m in (("h", hs), ("p", ps)):
for pid in sorted(m):
h.update(f"\0{kind}\0{pid}\0{m[pid].get('hash')}".encode())
if hk:
h.update(f"\0k\0{hk.get('hash')}".encode())
return {**bundle, "harnesses": hs, "providers": ps, "hooks": hk, "hash": h.hexdigest()[:16]}
# ── the probe's half ──────────────────────────────────────────────────────────
def plugins_hash(m: dict) -> str:
"""The worker's hash of one kind's map (sidecar/labsync.py
``_plugins_hash``): its version dir is ``v-<this>``."""
h = hashlib.sha256()
for pid in sorted(m):
h.update(f"{pid}\0{m[pid].get('hash')}\0".encode())
return h.hexdigest()[:16]
def plugins_drift(st: dict, bundle: dict) -> bool:
"""Does a worker that holds the bundle's hash lack its harness / provider
maps — another version on disk, or other drivers running? Read off its
/health: ``pluginSync`` (``{kind: {version, loaded}}``), else — a sidecar
from before that — its ``harnesses`` list (``liveHarnesses`` in the
status) against the bundle's harness plugins. A sidecar with neither (from before the plugin maps) can't take
them: never a drift. Both maps are compared as the worker hashes them,
so a guest's computer (no provider map) compares ``{}``."""
ps = st.get("pluginSync")
if isinstance(ps, dict):
for kind in ("harnesses", "providers"):
if kind not in bundle:
continue
got = ps.get(kind) if isinstance(ps.get(kind), dict) else {}
if got.get("version") != plugins_hash(bundle.get(kind) or {}) \
or got.get("loaded") is False:
return True
return False
live = st.get("liveHarnesses")
if isinstance(live, list) and "harnesses" in bundle:
want = sorted(str(b.get("hash")) for b in (bundle["harnesses"] or {}).values())
return sorted(str(e.get("hash")) for e in live if isinstance(e, dict)) != want
return False
def status(st: dict, bundle: dict) -> str:
"""Where a worker's copy stands against the bundle the hub would send it.
``unsupported``: its /health has no ``labSync`` (a sidecar from before).
The bundle's hash held but its plugin maps not (:func:`plugins_drift`) is
``outdated`` too: the worker re-applies the maps of a same-hash /sync."""
if st.get("status") != "online":
return UNKNOWN
held = st.get("labSync")
if not isinstance(held, dict):
return UNSUPPORTED
if held.get("hash") == bundle["hash"] and not plugins_drift(st, bundle):
return CURRENT
if st.get("labSyncError"):
return FAILED
return OUTDATED
def push(store, w: dict, bundle: dict | None = None) -> dict:
"""POST the bundle to the worker's ``/sync``; raises the sidecar's
HTTPException (and keeps its message as ``labSyncError``)."""
from .store import sidecar_request
bundle = bundle or for_worker(w)
_attempts[w["id"]] = (bundle["hash"], time.time())
try:
out = sidecar_request(
w["url"], w["token"], "/sync",
{k: bundle[k] for k in ("hash", "skills", "agents", "executables",
"harnesses", "providers", "hooks") if k in bundle},
timeout=30, label=f"worker {w.get('name') or w['id']}")
except HTTPException as e:
d = e.detail if isinstance(e.detail, dict) else {"message": str(e.detail)}
store.set_status(w["id"], labSyncError=d.get("message") or "sync failed")
raise
store.set_status(w["id"], labSyncError=None, labSync=out.get("labSync"))
return out
def maybe_push(store, w: dict) -> bool:
"""The automatic half, run after each probe: True when a bundle was sent.
A failed hash is retried after ``RETRY_S``."""
if not store.online(w["id"]):
return False
bundle = for_worker(w)
if status(store.status(w["id"]), bundle) not in (OUTDATED, FAILED):
return False
last = _attempts.get(w["id"])
if last and last[0] == bundle["hash"] and time.time() - last[1] < RETRY_S:
return False
try:
push(store, w, bundle)
except HTTPException:
return False
return True
def view(store, w: dict) -> dict:
"""The Settings section: the checklist, the bundle summary and the
worker's own report."""
items = all_items()
ov = w.get("labSyncOverrides") or {}
acct = w.get("account")
bundle = for_worker(w)
st = store.status(w["id"])
return {
"items": [{"key": i["key"], "kind": i["kind"], "name": i["name"],
"description": i["description"], "portable": i["portable"],
"account": i.get("account"),
"default": default_on(i, acct),
"override": ov.get(i["key"]),
"enabled": ov.get(i["key"], default_on(i, acct)) is True}
for i in items],
"hash": bundle["hash"], "skipped": bundle["skipped"],
"status": status(st, bundle),
"held": st.get("labSync"), "error": st.get("labSyncError"),
}
def clean_overrides(raw: dict | None, items: list[dict],
account: str | None = None) -> dict:
"""Keep only overrides that name a known item and differ from its
default for a worker of ``account`` (a tick that matches the frontmatter
is no override at all)."""
known = {i["key"]: default_on(i, account) for i in items}
return {k: bool(v) for k, v in (raw or {}).items()
if k in known and isinstance(v, bool) and v != known[k]}
# ── portable agents on every lab run ──────────────────────────────────────────
def _tools(v) -> list[str] | None:
if isinstance(v, list):
tools = [str(t).strip() for t in v if str(t).strip()]
elif isinstance(v, str) and v.strip():
tools = [t.strip() for t in v.split(",") if t.strip()]
else:
return None
# "All tools" / "*" mean no restriction: leave the key out.
return None if any(t in ("*", "All tools") for t in tools) else tools
def agent_definitions(source: pathlib.Path | None = None) -> dict:
"""``{name: {description, prompt, model?, tools?}}`` for every
``portable: true`` agent — the ``claude --agents`` shape (an
account-scoped one, ``portable: work``, stays on that account's workers).
Agent names the CLI rejects are skipped."""
out: dict[str, dict] = {}
for i in catalog(source):
if i["kind"] != "agent" or not i["portable"] \
or not re.match(r"^[a-z][a-z0-9-]{0,40}$", i["name"]):
continue
text = _read(i["path"]) or ""
fm = parse_frontmatter(text)
end = text.find("\n---", 3) if text.startswith("---") else -1
prompt = (text[end + 4:] if end != -1 else text).strip()
desc = str(fm.get("description") or "").strip()
if not desc or not prompt:
continue
d: dict = {"description": desc, "prompt": prompt}
if isinstance(fm.get("model"), str) and fm["model"].strip():
d["model"] = fm["model"].strip()
tools = _tools(fm.get("tools"))
if tools:
d["tools"] = tools
out[i["name"]] = d
return out