Files
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

205 lines
7.8 KiB
Python

"""
Repo plugins, the worker's half — Claude Code plugins a repo ships through its
own marketplace (``<cwd>/.claude-plugin/marketplace.json``), enabled for this
worker's default account when the hub says so (``backend/workers/repoplugins.py``).
``/health``'s ``repoPlugins`` (workers only) is what is here:
{checkedAt, configDir,
marketplace: {name, path, repo, plugins: [{name, description}]} | None,
known: bool, # the marketplace is in that config dir
plugins: {"<plugin>@<marketplace>": {installed, enabled}}}
It is read off files — the marketplace manifest, ``<config>/settings.json``
(``enabledPlugins``, ``extraKnownMarketplaces``) and
``<config>/plugins/{installed_plugins,known_marketplaces}.json`` — never the
CLI and never a token, and cached ``TTL_S`` (an apply drops the cache).
``POST /repo-plugins {enable: [id], disable: [id]}`` (the hub's bearer) makes
it so for the default account, with that account's ``CLAUDE_CONFIG_DIR``:
``claude plugin marketplace add <cwd>/`` when the marketplace isn't known yet
(``"."`` alone is refused, ``"./"`` works), then ``claude plugin install <id>
--scope user`` (or ``enable`` when it is installed but off) / ``claude plugin
disable <id> --scope user``. Only ids of the cwd's own marketplace are taken;
nothing is ever uninstalled. Refused on the host sidecar.
"""
from __future__ import annotations
import json
import os
import pathlib
import re
import subprocess
import threading
import time
from typing import Callable
from fastapi import APIRouter, Header, HTTPException
from pydantic import BaseModel
from config import ACCOUNTS, CLAUDE_BIN, DEFAULT_ACCOUNT, DEFAULT_CWD, IS_WORKER
TTL_S = 30
CLI_TIMEOUT_S = 120
MANIFEST = pathlib.Path(".claude-plugin") / "marketplace.json"
_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
_DESC_MAX = 300
_lock = threading.Lock()
_cache: dict = {"at": 0.0, "value": None}
_apply_lock = threading.Lock()
def config_dir() -> pathlib.Path:
"""The default account's Claude config dir (``~/.claude`` unless declared)."""
return ACCOUNTS.get(DEFAULT_ACCOUNT) or pathlib.Path(os.path.expanduser("~/.claude"))
def _json(p: pathlib.Path) -> dict:
try:
v = json.loads(p.read_text(encoding="utf-8"))
return v if isinstance(v, dict) else {}
except (OSError, ValueError):
return {}
def marketplace(cwd: str | os.PathLike) -> dict | None:
"""The cwd repo's marketplace: ``{name, path, repo, plugins}``, or None."""
root = pathlib.Path(cwd)
m = _json(root / MANIFEST)
name = m.get("name")
if not isinstance(name, str) or not _NAME_RE.match(name):
return None
plugins = []
for p in m.get("plugins") or []:
if not isinstance(p, dict) or not isinstance(p.get("name"), str) \
or not _NAME_RE.match(p["name"]):
continue
d = p.get("description")
plugins.append({"name": p["name"],
"description": d.strip()[:_DESC_MAX] if isinstance(d, str) else None})
return {"name": name, "path": str(root), "repo": root.name, "plugins": plugins}
def read(cwd: str | os.PathLike, cfg: pathlib.Path) -> dict:
"""What is here, read off files (see the module doc)."""
mk = marketplace(cwd)
out: dict = {"checkedAt": int(time.time()), "configDir": str(cfg),
"marketplace": mk, "known": False, "plugins": {}}
if not mk:
return out
settings = _json(cfg / "settings.json")
extra = settings.get("extraKnownMarketplaces") or {}
known = _json(cfg / "plugins" / "known_marketplaces.json")
out["known"] = mk["name"] in known or (isinstance(extra, dict) and mk["name"] in extra)
enabled = settings.get("enabledPlugins") or {}
installed = _json(cfg / "plugins" / "installed_plugins.json").get("plugins") or {}
for p in mk["plugins"]:
pid = f"{p['name']}@{mk['name']}"
out["plugins"][pid] = {
"installed": isinstance(installed, dict) and bool(installed.get(pid)),
"enabled": isinstance(enabled, dict) and enabled.get(pid) is True}
return out
def public(now: float | None = None) -> dict:
"""``/health``'s ``repoPlugins`` — cached ``TTL_S``."""
now = time.time() if now is None else now
with _lock:
if _cache["value"] is None or now - _cache["at"] >= TTL_S:
_cache["value"] = read(DEFAULT_CWD, config_dir())
_cache["at"] = now
return _cache["value"]
def invalidate() -> None:
with _lock:
_cache["value"] = None
def _env() -> dict:
import claude_env
return claude_env._account_env(DEFAULT_ACCOUNT)
def _cli(args: list[str], run: Callable | None = None) -> str | None:
"""Run ``claude <args>`` in the cwd for the default account; None when it
worked, else a short error."""
run = run or subprocess.run
try:
r = run([CLAUDE_BIN, *args], capture_output=True, text=True,
timeout=CLI_TIMEOUT_S, stdin=subprocess.DEVNULL,
cwd=DEFAULT_CWD, env=_env())
except (OSError, subprocess.SubprocessError) as e:
return str(e)[:300]
if r.returncode != 0:
msg = ((r.stderr or "") + (r.stdout or "")).strip().splitlines()
return (msg[-1] if msg else f"exit {r.returncode}")[:300]
return None
def apply(enable: list[str], disable: list[str], *, cwd: str | None = None,
cfg: pathlib.Path | None = None, cli: Callable[[list[str]], str | None] | None = None) -> dict:
"""Enable / disable the given ``<plugin>@<marketplace>`` ids; returns
``{results: {id: {ok, error?}}, repoPlugins}``."""
cwd = cwd or DEFAULT_CWD
cfg = cfg or config_dir()
cli = cli or _cli
with _apply_lock:
st = read(cwd, cfg)
mk = st["marketplace"]
if not mk:
raise HTTPException(409, {"message": f"no plugin marketplace in {cwd}",
"kind": "no_marketplace"})
ours = set(st["plugins"])
bad = [p for p in [*enable, *disable] if p not in ours]
if bad:
raise HTTPException(400, {"message": f"not a plugin of the {mk['name']} "
f"marketplace: {', '.join(bad)}",
"kind": "unknown_plugin"})
results: dict[str, dict] = {}
if enable and not st["known"]:
err = cli(["plugin", "marketplace", "add", str(cwd).rstrip("/") + "/"])
if err:
for p in enable:
results[p] = {"ok": False, "error": f"marketplace add: {err}"}
enable = []
for p in enable:
cur = st["plugins"][p]
if cur["enabled"]:
results[p] = {"ok": True}
continue
err = cli(["plugin", "enable", p, "--scope", "user"] if cur["installed"]
else ["plugin", "install", p, "--scope", "user"])
results[p] = {"ok": not err, **({"error": err} if err else {})}
for p in disable:
if p in results:
continue
if not st["plugins"][p]["enabled"]:
results[p] = {"ok": True}
continue
err = cli(["plugin", "disable", p, "--scope", "user"])
results[p] = {"ok": not err, **({"error": err} if err else {})}
invalidate()
return {"results": results, "repoPlugins": read(cwd, cfg)}
class ApplyBody(BaseModel):
enable: list[str] = []
disable: list[str] = []
def make_router(auth: Callable[[str | None], None]) -> APIRouter:
router = APIRouter()
@router.post("/repo-plugins")
def post_repo_plugins(body: ApplyBody,
authorization: str | None = Header(default=None)) -> dict:
auth(authorization)
if not IS_WORKER:
raise HTTPException(409, "the host sidecar's plugins are set up by hand")
return apply(body.enable, body.disable)
return router