Files
gabrielvidalandClaude Opus 5.5 2cc8aee58e feat(workers): repo plugins — account picks + per-worker overrides, applied on probe
workers/repoplugins.py: /data/repo-plugins.json holds each account's picks
(seeded work: [work-context@orus]), repoPluginOverrides on a worker record
its ticks/unticks. Desired = override, else on when the account picks it,
else left alone (a hand-enabled plugin stays). After each probe the hub
POSTs /repo-plugins {enable, disable} when that differs from the worker's
/health repoPlugins (10 min between attempts at one change); never a
guest's computer. GET /api/repo-plugins, PUT
/api/repo-plugins/accounts/{account}, PUT /api/workers/{id}/repo-plugins;
the worker carries repoPlugins / repoPluginsStatus / repoPluginsError.

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

255 lines
11 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
Repo plugins — Claude Code plugins a repo ships through its own marketplace
(``<repo>/.claude-plugin/marketplace.json``), enabled on a worker by the hub.
orus-monorepo ships opt-in plugins that way (marketplace ``orus``, plugin
``work-context``). A worker's ``/health`` says what its default cwd's repo
offers and which ``<plugin>@<marketplace>`` are on for its default account
(``repoPlugins``, sidecar ``repo_plugins.py``); the hub keeps:
- **account picks** — ``/data/repo-plugins.json``, ``{"accounts": {account:
[id, …]}}``: every worker of that account gets them on, a worker paired
later included (seeded ``work: [work-context@orus]``);
- **per-worker overrides** — ``repoPluginOverrides`` on the record, ``{id:
bool}``: a tick or an untick on that worker, whatever its account picks.
The desired state is tri-state: an override, else on when the account picks
it, else **left alone** — the hub never turns off a plugin it was not told to
(a hand-enabled one stays). Unticking is ``disable``, never an uninstall.
After each probe ``maybe_push`` compares the desired state with the worker's
report and POSTs ``/repo-plugins {enable, disable}`` when they differ (10 min
between attempts at one change). A guest's computer is never touched; a
sidecar from before has no ``repoPlugins`` ⇒ ``unsupported``.
"""
from __future__ import annotations
import hashlib
import json
import os
import pathlib
import re
import threading
import time
from fastapi import HTTPException
DEFAULT_PICKS: dict[str, list[str]] = {"work": ["work-context@orus"]}
RETRY_S = 10 * 60
_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}@[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
_ACCOUNT_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,31}$")
CURRENT, OUTDATED, FAILED = "current", "outdated", "failed"
UNSUPPORTED, UNKNOWN, NONE = "unsupported", "unknown", "none"
# worker id → (hash of the change last sent, when)
_attempts: dict[str, tuple[str, float]] = {}
def valid_id(pid) -> bool:
return isinstance(pid, str) and bool(_ID_RE.match(pid))
# ── the account picks ─────────────────────────────────────────────────────────
def _clean_picks(raw) -> dict[str, list[str]]:
out: dict[str, list[str]] = {}
if not isinstance(raw, dict):
return out
for acct, ids in raw.items():
if not isinstance(acct, str) or not _ACCOUNT_RE.match(acct) \
or not isinstance(ids, list):
continue
keep = sorted({i for i in ids if valid_id(i)})
if keep:
out[acct] = keep
return out
class RepoPluginSettings:
"""``/data/repo-plugins.json`` — one small file, rewritten atomically.
Missing ⇒ the seed (``DEFAULT_PICKS``)."""
def __init__(self, path: str | os.PathLike):
self.path = pathlib.Path(path)
self._lock = threading.Lock()
try:
raw = json.loads(self.path.read_text(encoding="utf-8"))
self._picks = _clean_picks(raw.get("accounts"))
except (OSError, ValueError, AttributeError):
self._picks = {k: list(v) for k, v in DEFAULT_PICKS.items()}
def picks(self) -> dict[str, list[str]]:
with self._lock:
return {k: list(v) for k, v in self._picks.items()}
def set_account(self, account: str, ids: list[str]) -> dict[str, list[str]]:
if not isinstance(account, str) or not _ACCOUNT_RE.match(account):
raise HTTPException(400, "bad account")
with self._lock:
picks = _clean_picks({**self._picks, account: ids})
if account not in picks:
picks.pop(account, None)
self.path.parent.mkdir(parents=True, exist_ok=True)
tmp = self.path.with_suffix(".tmp")
tmp.write_text(json.dumps({"accounts": picks}, indent=2), encoding="utf-8")
os.replace(tmp, self.path)
self._picks = picks
return {k: list(v) for k, v in picks.items()}
# ── one worker ────────────────────────────────────────────────────────────────
def eligible(w: dict) -> bool:
"""The owner's own workers only — never a guest's computer."""
return not w.get("owner")
def held(st: dict) -> dict | None:
"""The worker's report (its /health ``repoPlugins``), None from a sidecar
from before."""
v = st.get("repoPlugins")
return v if isinstance(v, dict) else None
def desired(w: dict, picks: dict[str, list[str]], report: dict | None) -> dict[str, bool]:
"""``{id: on}`` for the plugins of the worker's marketplace the hub has a
say on — an id missing is left as it is."""
if not report:
return {}
ov = w.get("repoPluginOverrides") or {}
mine = set(picks.get(w.get("account") or "", []))
out: dict[str, bool] = {}
for pid in (report.get("plugins") or {}):
if isinstance(ov.get(pid), bool):
out[pid] = ov[pid]
elif pid in mine:
out[pid] = True
return out
def diff(w: dict, picks: dict[str, list[str]], report: dict | None) -> tuple[list[str], list[str]]:
"""(to enable, to disable) on that worker."""
have = (report or {}).get("plugins") or {}
want = desired(w, picks, report)
enable = sorted(p for p, on in want.items() if on and not (have.get(p) or {}).get("enabled"))
disable = sorted(p for p, on in want.items() if not on and (have.get(p) or {}).get("enabled"))
return enable, disable
def status(st: dict, w: dict, picks: dict[str, list[str]]) -> str:
if st.get("status") != "online":
return UNKNOWN
report = held(st)
if report is None:
return UNSUPPORTED
if not report.get("marketplace"):
return NONE
enable, disable = diff(w, picks, report)
if not enable and not disable:
return CURRENT
return FAILED if st.get("repoPluginsError") else OUTDATED
def _change_hash(enable: list[str], disable: list[str]) -> str:
return hashlib.sha256(json.dumps([enable, disable]).encode()).hexdigest()[:16]
def _picks(store) -> dict[str, list[str]]:
s = getattr(store, "repo_plugins", None)
return s.picks() if s else {k: list(v) for k, v in DEFAULT_PICKS.items()}
def push(store, w: dict, enable: list[str], disable: list[str]) -> dict:
"""POST the change to the worker's ``/repo-plugins``; keeps a failure as
``repoPluginsError`` (and raises the sidecar's HTTPException)."""
from .store import sidecar_request
_attempts[w["id"]] = (_change_hash(enable, disable), time.time())
try:
out = sidecar_request(w["url"], w["token"], "/repo-plugins",
{"enable": enable, "disable": disable},
timeout=300, 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"], repoPluginsError=d.get("message") or "apply failed")
raise
errors = [f"{p}: {r.get('error')}" for p, r in (out.get("results") or {}).items()
if isinstance(r, dict) and not r.get("ok")]
store.set_status(w["id"], repoPluginsError="; ".join(errors)[:300] or None,
**({"repoPlugins": out["repoPlugins"]}
if isinstance(out.get("repoPlugins"), dict) else {}))
return out
def maybe_push(store, w: dict, force: bool = False) -> bool:
"""The probe's half: True when a change was sent. One change is retried
after ``RETRY_S`` (``force``: now — a Settings tick)."""
if not eligible(w) or not store.online(w["id"]):
return False
st = store.status(w["id"])
report = held(st)
if not report or not report.get("marketplace"):
return False
enable, disable = diff(w, _picks(store), report)
if not enable and not disable:
if st.get("repoPluginsError"):
store.set_status(w["id"], repoPluginsError=None)
return False
last = _attempts.get(w["id"])
if not force and last and last[0] == _change_hash(enable, disable) \
and time.time() - last[1] < RETRY_S:
return False
try:
push(store, w, enable, disable)
except HTTPException:
return False
return True
def clean_overrides(raw: dict | None, account: str | None,
picks: dict[str, list[str]]) -> dict[str, bool]:
"""Keep valid ids; a tick on a plugin the account already picks is no
override (an untick always is — it turns the plugin off)."""
mine = set(picks.get(account or "", []))
return {k: v for k, v in (raw or {}).items()
if valid_id(k) and isinstance(v, bool) and not (v and k in mine)}
# ── the Settings matrix ───────────────────────────────────────────────────────
def view(store) -> dict:
"""Every plugin any worker's repo offers × every owner worker, plus the
account picks."""
picks = _picks(store)
plugins: dict[str, dict] = {}
workers: list[dict] = []
for w in store.list():
if not eligible(w) or w.get("pending"):
continue
st = store.status(w["id"])
report = held(st)
mk = (report or {}).get("marketplace") or None
if mk:
for p in mk.get("plugins") or []:
pid = f"{p.get('name')}@{mk.get('name')}"
if valid_id(pid):
plugins.setdefault(pid, {
"id": pid, "name": p.get("name"), "marketplace": mk.get("name"),
"description": p.get("description"), "repo": mk.get("repo")})
want = desired(w, picks, report)
ov = w.get("repoPluginOverrides") or {}
have = (report or {}).get("plugins") or {}
workers.append({
"id": w["id"], "name": w.get("name"), "account": w.get("account"),
"status": status(st, w, picks),
"error": st.get("repoPluginsError"),
"repo": (mk or {}).get("repo"), "marketplace": (mk or {}).get("name"),
"checkedAt": (report or {}).get("checkedAt"),
"cells": {pid: {"installed": bool(v.get("installed")),
"enabled": bool(v.get("enabled")),
"desired": want.get(pid),
"override": ov.get(pid) if isinstance(ov.get(pid), bool) else None}
for pid, v in have.items() if isinstance(v, dict)},
})
accounts = sorted({w["account"] for w in workers if w.get("account")} | set(picks))
return {"plugins": sorted(plugins.values(), key=lambda p: p["id"]),
"workers": workers, "accounts": accounts, "picks": picks}