- typed_manifest: harness.workerSetup {tool, order, guestAllowed, update,
enablesHarness, installerEnv, recipe}; in the capability fingerprint.
- worker/tools.sh keeps gh, ask-form and the helpers; the claude / pi recipes
are the plugins' (sourced from WORKER_TOOL_RECIPES), opencode / agy go
through WORKER_INSTALLER_TOOLS.
- sidecar tools_check / tools_install read the rows off the loaded harness
drivers (setup_check hook); backend workers/tools.py off the registry.
- A guest's computer: gh + guestAllowed harness tools (claude) — pi's plugin
never reaches it, so pi left its checklist.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
458 lines
17 KiB
Python
458 lines
17 KiB
Python
"""
|
|
Install / update a worker's tools for the hub — the worker page's *Setup*
|
|
checklist: tools_check.py says what is there, this puts what is missing there.
|
|
|
|
``POST /tools/install {tools: [...], action: "install"|"update"}`` starts
|
|
``worker/tools.sh <action> <tool>...`` detached — its own session, because a
|
|
harness install (opencode, agy, ask-form: ``install.sh update`` with
|
|
``WORKER_<TOOL>=1``) restarts this service and the batch must outlive it — and
|
|
answers once the script has marked its tools ``queued``. The script writes
|
|
``<state dir>/tools/<tool>.json`` as it goes; ``public()`` reads them back for
|
|
``/health``'s ``toolJobs`` (a short tail of the tool's log while it runs and
|
|
once it failed), and reads a job still ``queued`` / ``running`` whose batch is
|
|
gone as ``interrupted``.
|
|
|
|
What may be installed is a list — the hub sends a tool *name*, never a
|
|
command. Core's own tools are ``gh`` and ``ask-form`` (their recipes in
|
|
``worker/tools.sh``); every other row is a **harness plugin's**, declared by
|
|
its ``harness.workerSetup`` (2026-11-26 — the claude / opencode / agy / pi
|
|
recipes left this checkout): a bash ``recipe`` in the plugin's sidecar dir
|
|
(harness-claude, harness-pi), sourced by tools.sh, or ``enablesHarness``
|
|
(harness-opencode, harness-agy: ``install.sh update`` with its
|
|
``installerEnv=1``). :func:`harness_tools` reads them off the live harness
|
|
drivers, so a harness this machine doesn't have offers nothing.
|
|
|
|
the owner's workers gh, ask-form + every loaded harness's tool
|
|
a guest's computer gh + the tools whose ``workerSetup.guestAllowed`` is
|
|
set (claude — only guestAllowed harnesses reach it at
|
|
all) — never ask-form (the installer leaves a guest's
|
|
forms to its owner's)
|
|
|
|
``update`` is for the tools that don't update themselves: gh and the
|
|
``workerSetup.update`` ones (pi — only a copy the worker installed; tools.sh
|
|
refuses one a package manager owns). The host sidecar answers 409: the
|
|
Homelab is set up by hand.
|
|
|
|
``/gh/login`` (POST start · GET state · DELETE cancel) is GitHub's device-code
|
|
sign-in for ``gh``: ``gh auth login --web`` prints a one-time code and
|
|
``github.com/login/device`` and polls GitHub until someone enters it — the
|
|
pumping is opencode's ``_Login`` with GitHub's patterns.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import threading
|
|
import time
|
|
from typing import Callable
|
|
|
|
from fastapi import APIRouter, Header, HTTPException
|
|
from pydantic import BaseModel
|
|
|
|
import link
|
|
import pairing
|
|
|
|
ROOT = pathlib.Path(__file__).resolve().parent.parent
|
|
SCRIPT = ROOT / "worker" / "tools.sh"
|
|
# Core's own rows (order, guest computers too, updatable, via the installer).
|
|
CORE_TOOLS = {"gh": {"order": 15, "guestAllowed": True, "update": True, "installerEnv": None},
|
|
"ask-form": {"order": 90, "guestAllowed": False, "update": False,
|
|
"installerEnv": "WORKER_ASKFORM"}}
|
|
TAIL_LINES = 8
|
|
_ANSI = re.compile(r"\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b\[[0-9;?]*[A-Za-z]|\r")
|
|
|
|
|
|
def _dir() -> pathlib.Path:
|
|
return pairing.state_dir() / "tools"
|
|
|
|
|
|
def _is_worker() -> bool:
|
|
from config import IS_WORKER
|
|
return IS_WORKER
|
|
|
|
|
|
def guest_computer() -> bool:
|
|
"""A guest's own computer: it dials out, and not as one of the owner's."""
|
|
cfg = link.config()
|
|
return bool(cfg) and not cfg.get("owner")
|
|
|
|
|
|
def harness_tools() -> list[dict]:
|
|
"""``[{tool, harness, order, guestAllowed, update, installerEnv, recipe,
|
|
driver}]`` — every loaded harness plugin's ``workerSetup``, ``recipe`` the
|
|
absolute path of its bash recipe (None for an ``enablesHarness`` one),
|
|
in checklist order."""
|
|
try:
|
|
import harness_loader
|
|
entries = harness_loader.LOADER.entries()
|
|
except Exception: # noqa: BLE001 — no drivers: core's tools only
|
|
return []
|
|
out = []
|
|
for e in entries:
|
|
hv = (e.meta or {}).get("manifest") or {}
|
|
ws = hv.get("workerSetup") if isinstance(hv, dict) else None
|
|
if not isinstance(ws, dict):
|
|
continue
|
|
tool = ws.get("tool") or e.id
|
|
if not isinstance(tool, str) or tool in CORE_TOOLS:
|
|
continue
|
|
enables = bool(ws.get("enablesHarness"))
|
|
recipe = None
|
|
if not enables and isinstance(ws.get("recipe"), str) and e.dir:
|
|
r = pathlib.Path(e.dir) / ws["recipe"]
|
|
if "/" in ws["recipe"] or not r.is_file():
|
|
continue # a recipe that isn't there installs nothing
|
|
recipe = str(r)
|
|
out.append({"tool": tool, "harness": e.id,
|
|
"order": ws.get("order") if isinstance(ws.get("order"), int) else e.order,
|
|
"guestAllowed": bool(ws.get("guestAllowed"))
|
|
and bool((e.meta or {}).get("guestAllowed")),
|
|
"update": bool(ws.get("update")),
|
|
"installerEnv": ws.get("installerEnv") if enables else None,
|
|
"recipe": recipe, "driver": e.obj})
|
|
return sorted(out, key=lambda t: (t["order"], t["tool"]))
|
|
|
|
|
|
def _rows() -> list[dict]:
|
|
"""Every installable row of this machine, core's and the harnesses', in
|
|
checklist order (claude, gh, opencode, agy, pi, ask-form)."""
|
|
guest = guest_computer()
|
|
rows = [{"tool": k, **v} for k, v in CORE_TOOLS.items()] + harness_tools()
|
|
rows = [r for r in rows if r["guestAllowed"] or not guest]
|
|
return sorted(rows, key=lambda r: (r["order"], r["tool"]))
|
|
|
|
|
|
def allowed() -> tuple[str, ...]:
|
|
return tuple(r["tool"] for r in _rows())
|
|
|
|
|
|
def updatable() -> tuple[str, ...]:
|
|
return tuple(r["tool"] for r in _rows() if r["update"])
|
|
|
|
|
|
def _env_tables(names: list[str]) -> dict:
|
|
"""tools.sh's WORKER_TOOL_RECIPES / WORKER_INSTALLER_TOOLS for this batch."""
|
|
recipes, installers = [], []
|
|
for r in _rows():
|
|
if r["tool"] not in names or r["tool"] in CORE_TOOLS:
|
|
continue
|
|
if r.get("recipe"):
|
|
recipes.append(f"{r['tool']}\t{r['recipe']}")
|
|
elif r.get("installerEnv"):
|
|
installers.append(f"{r['tool']}\t{r['installerEnv']}")
|
|
return {"WORKER_TOOL_RECIPES": "\n".join(recipes),
|
|
"WORKER_INSTALLER_TOOLS": "\n".join(installers)}
|
|
|
|
|
|
def _alive(pid) -> bool:
|
|
try:
|
|
os.kill(int(pid), 0)
|
|
return True
|
|
except (OSError, ValueError, TypeError):
|
|
return False
|
|
|
|
|
|
def running_pid() -> int | None:
|
|
"""The batch in progress (tools.sh's lock), None when idle."""
|
|
try:
|
|
pid = int((_dir() / "lock" / "pid").read_text())
|
|
except (OSError, ValueError):
|
|
return None
|
|
return pid if _alive(pid) else None
|
|
|
|
|
|
def _tail(tool: str) -> list[str]:
|
|
try:
|
|
text = (_dir() / f"{tool}.log").read_text(errors="replace")
|
|
except OSError:
|
|
return []
|
|
lines = [_ANSI.sub("", ln).strip() for ln in text.splitlines()]
|
|
return [ln[:200] for ln in lines if ln][-TAIL_LINES:]
|
|
|
|
|
|
def _read(tool: str) -> dict | None:
|
|
try:
|
|
j = json.loads((_dir() / f"{tool}.json").read_text())
|
|
except (OSError, ValueError):
|
|
return None
|
|
return j if isinstance(j, dict) else None
|
|
|
|
|
|
def public() -> dict:
|
|
"""``/health``'s ``toolJobs``: ``{tool: {action, state, startedAt,
|
|
finishedAt, error, tail?}}`` — the last install / update of each tool."""
|
|
out: dict = {}
|
|
for tool in _known():
|
|
j = _read(tool)
|
|
if not j:
|
|
continue
|
|
st = j.get("state")
|
|
if st in ("queued", "running") and not _alive(j.get("pid")):
|
|
st = "interrupted"
|
|
job = {"action": j.get("action"), "state": st,
|
|
"startedAt": j.get("startedAt"), "finishedAt": j.get("finishedAt"),
|
|
"error": j.get("error")}
|
|
if st in ("running", "failed", "interrupted"):
|
|
job["tail"] = _tail(tool)
|
|
out[tool] = job
|
|
return out
|
|
|
|
|
|
def last_finished() -> float:
|
|
"""When the last job ended (its progress file's mtime) — tools_check
|
|
re-checks once something was installed after its last look."""
|
|
newest = 0.0
|
|
for tool in _known():
|
|
j = _read(tool)
|
|
if j and j.get("state") in ("done", "failed"):
|
|
try:
|
|
newest = max(newest, (_dir() / f"{tool}.json").stat().st_mtime)
|
|
except OSError:
|
|
pass
|
|
return newest
|
|
|
|
|
|
def _known() -> list[str]:
|
|
"""The tools whose progress files are read back: this machine's rows
|
|
(never a file some other name left there)."""
|
|
return [r["tool"] for r in _rows()]
|
|
|
|
|
|
def _err(status: int, message: str, kind: str) -> HTTPException:
|
|
return HTTPException(status, {"message": message, "kind": kind})
|
|
|
|
|
|
def _wait_queued(tools: list[str], pid: int, timeout: float) -> None:
|
|
"""Until tools.sh has marked every tool queued (its pid in each file), so
|
|
the /health right after the answer shows the new batch, not the last one."""
|
|
deadline = time.monotonic() + timeout
|
|
while time.monotonic() < deadline:
|
|
if all((_read(t) or {}).get("pid") == pid for t in tools):
|
|
return
|
|
time.sleep(0.05)
|
|
|
|
|
|
def start(tools: list[str], action: str = "install") -> dict:
|
|
if not _is_worker():
|
|
raise _err(409, "the Homelab's tools are set up by hand, not from here", "host")
|
|
if action not in ("install", "update"):
|
|
raise _err(400, "action must be install or update", "bad_action")
|
|
names = list(dict.fromkeys(t.strip() for t in tools or [] if t and t.strip()))
|
|
if not names:
|
|
raise _err(400, "no tool named", "no_tool")
|
|
ok = allowed()
|
|
bad = [t for t in names if t not in ok]
|
|
if bad:
|
|
raise _err(400, f"can't install {', '.join(bad)} on this machine "
|
|
f"(only {', '.join(ok)})", "tool_unknown")
|
|
if action == "update":
|
|
up = updatable()
|
|
bad = [t for t in names if t not in up]
|
|
if bad:
|
|
raise _err(400, f"{', '.join(bad)} update{'s' if len(bad) == 1 else ''} "
|
|
f"itself — only {', '.join(up)} are updated from here",
|
|
"not_updatable")
|
|
if not SCRIPT.is_file():
|
|
raise _err(409, "this worker's version can't install tools — update it first", "no_script")
|
|
pid = running_pid()
|
|
if pid:
|
|
raise _err(409, "tools are already being installed here — wait for that to end",
|
|
"tools_busy")
|
|
tables = _env_tables(names)
|
|
if any(r["tool"] in names and r.get("installerEnv") for r in _rows()):
|
|
import selfupdate
|
|
if selfupdate.running_pid():
|
|
raise _err(409, "the worker is updating itself — try again in a minute", "updating")
|
|
d = _dir()
|
|
d.mkdir(parents=True, exist_ok=True)
|
|
env = {**os.environ, "WORKER_STATE_DIR": str(pairing.state_dir()), **tables}
|
|
with open(d / "batch.log", "ab") as log:
|
|
log.write(f"\n[{time.strftime('%F %T')}] {action} {' '.join(names)}\n".encode())
|
|
log.flush()
|
|
try:
|
|
p = subprocess.Popen(["bash", str(SCRIPT), action, *names],
|
|
stdin=subprocess.DEVNULL, stdout=log,
|
|
stderr=subprocess.STDOUT, start_new_session=True,
|
|
cwd=str(pathlib.Path.home()), env=env)
|
|
except OSError as e:
|
|
raise _err(500, f"couldn't start tools.sh: {e}", "spawn")
|
|
_wait_queued(names, p.pid, 3.0)
|
|
return {"ok": True, "started": True, "pid": p.pid, "tools": names, "action": action}
|
|
|
|
|
|
# ── gh's device-code sign-in ─────────────────────────────────────────────────
|
|
_GH_CODE = re.compile(r"one-time code:\s*([A-Z0-9]{4}-[A-Z0-9]{4})")
|
|
_GH_URL = re.compile(r"https://github\.com/login/device\S*")
|
|
# How long a started sign-in waits for its code before the CLI is killed.
|
|
GH_LOGIN_TTL_S = float(os.environ.get("SIDECAR_OPENCODE_LOGIN_TTL_S", "900"))
|
|
_LOGIN_ANSI = re.compile(r"\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b\[[0-9;?]*[A-Za-z]")
|
|
|
|
|
|
class _Login:
|
|
"""A device-code sign-in in flight: pumps the CLI's output, finds the code
|
|
and the address to enter it at (``code_re`` / ``url_re``)."""
|
|
def __init__(self, account: str, proc: subprocess.Popen,
|
|
code_re: re.Pattern, url_re: re.Pattern):
|
|
self.account = account
|
|
self.proc = proc
|
|
self._code_re = code_re
|
|
self._url_re = url_re
|
|
self.started = time.time()
|
|
self.code: str | None = None
|
|
self.url: str | None = None
|
|
self._buf: list[str] = []
|
|
self._lock = threading.Lock()
|
|
threading.Thread(target=self._pump, daemon=True).start()
|
|
self._timer = threading.Timer(GH_LOGIN_TTL_S, self.kill)
|
|
self._timer.daemon = True
|
|
self._timer.start()
|
|
|
|
def _pump(self) -> None:
|
|
fd = self.proc.stdout.fileno()
|
|
while True:
|
|
try:
|
|
chunk = os.read(fd, 4096)
|
|
except OSError:
|
|
break
|
|
if not chunk:
|
|
break
|
|
with self._lock:
|
|
self._buf.append(chunk.decode(errors="replace"))
|
|
|
|
def output(self) -> str:
|
|
with self._lock:
|
|
return _LOGIN_ANSI.sub("", "".join(self._buf))
|
|
|
|
def wait_code(self, timeout: float) -> bool:
|
|
deadline = time.monotonic() + timeout
|
|
while time.monotonic() < deadline:
|
|
out = self.output()
|
|
c, u = self._code_re.search(out), self._url_re.search(out)
|
|
if c and u:
|
|
self.code, self.url = c.group(1), u.group(0).rstrip(".")
|
|
return True
|
|
if self.proc.poll() is not None:
|
|
return False
|
|
time.sleep(0.1)
|
|
return False
|
|
|
|
def kill(self) -> None:
|
|
self._timer.cancel()
|
|
if self.proc.poll() is None:
|
|
try:
|
|
self.proc.kill()
|
|
self.proc.wait(timeout=5)
|
|
except (OSError, subprocess.TimeoutExpired):
|
|
pass
|
|
|
|
def public(self) -> dict:
|
|
return {"account": self.account, "url": self.url, "userCode": self.code,
|
|
"flow": "device", "startedAt": int(self.started),
|
|
"expiresAt": int(self.started + GH_LOGIN_TTL_S)}
|
|
|
|
|
|
_gh: list = [None] # the sign-in in flight (a _Login)
|
|
_gh_lock = threading.Lock()
|
|
|
|
|
|
def gh_bin() -> str | None:
|
|
p = shutil.which("gh")
|
|
if p:
|
|
return p
|
|
own = pathlib.Path.home() / ".local" / "bin" / "gh"
|
|
return str(own) if os.access(own, os.X_OK) else None
|
|
|
|
|
|
def gh_login_start() -> dict:
|
|
if not _is_worker():
|
|
raise _err(409, "the Homelab's gh is signed in by hand", "host")
|
|
gh = gh_bin()
|
|
if not gh:
|
|
raise _err(409, "gh isn't installed here — install it first", "not_installed")
|
|
gh_login_cancel()
|
|
# BROWSER=true: "opening" the page is a no-op, gh goes straight to polling.
|
|
env = {**os.environ, "BROWSER": "true", "GH_BROWSER": "true", "NO_COLOR": "1"}
|
|
try:
|
|
proc = subprocess.Popen(
|
|
[gh, "auth", "login", "--hostname", "github.com", "--web",
|
|
"--git-protocol", "https"],
|
|
stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
|
env=env, cwd=str(pathlib.Path.home()))
|
|
except OSError as e:
|
|
raise _err(500, f"couldn't start `gh auth login`: {e}", "login")
|
|
login = _Login("gh", proc, code_re=_GH_CODE, url_re=_GH_URL)
|
|
if not login.wait_code(30):
|
|
tail = [ln for ln in login.output().strip().splitlines() if ln.strip()]
|
|
login.kill()
|
|
raise _err(502, "gh printed no device code: " + (tail[-1][:300] if tail else "(no output)"),
|
|
"login")
|
|
with _gh_lock:
|
|
_gh[0] = login
|
|
return login.public()
|
|
|
|
|
|
def gh_login_state() -> dict:
|
|
"""``{state: pending|complete|failed|none, …}`` of the last sign-in."""
|
|
with _gh_lock:
|
|
login = _gh[0]
|
|
if login is None:
|
|
return {"state": "none"}
|
|
rc = login.proc.poll()
|
|
if rc is None:
|
|
return {"state": "pending", **login.public()}
|
|
with _gh_lock:
|
|
_gh[0] = None
|
|
if rc == 0:
|
|
import tools_check
|
|
tools_check.invalidate()
|
|
return {"state": "complete"}
|
|
tail = [ln.strip(" !✓") for ln in login.output().splitlines() if ln.strip(" !✓")]
|
|
return {"state": "failed", "message": (tail[-1] if tail else f"exit {rc}")[:300]}
|
|
|
|
|
|
def gh_login_cancel() -> bool:
|
|
with _gh_lock:
|
|
login, _gh[0] = _gh[0], None
|
|
if not login:
|
|
return False
|
|
login.kill()
|
|
return True
|
|
|
|
|
|
class InstallBody(BaseModel):
|
|
tools: list[str]
|
|
action: str = "install"
|
|
|
|
|
|
def make_router(auth: Callable[[str | None], None]) -> APIRouter:
|
|
router = APIRouter()
|
|
|
|
@router.post("/tools/install")
|
|
def install(body: InstallBody, authorization: str | None = Header(default=None)):
|
|
"""Install (or update) these tools — asynchronous: /health's
|
|
``toolJobs`` follows the batch, ``tools`` re-checks once it ends."""
|
|
auth(authorization)
|
|
return start(body.tools, body.action)
|
|
|
|
@router.post("/gh/login")
|
|
def gh_login(authorization: str | None = Header(default=None)):
|
|
auth(authorization)
|
|
return gh_login_start()
|
|
|
|
@router.get("/gh/login")
|
|
def gh_login_get(authorization: str | None = Header(default=None)):
|
|
auth(authorization)
|
|
return gh_login_state()
|
|
|
|
@router.delete("/gh/login")
|
|
def gh_login_delete(authorization: str | None = Header(default=None)):
|
|
auth(authorization)
|
|
return {"ok": True, "cancelled": gh_login_cancel()}
|
|
|
|
return router
|