- 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>
198 lines
8.9 KiB
Python
198 lines
8.9 KiB
Python
"""
|
|
A worker's tools, installed from the hub — the *Setup* checklist's Install /
|
|
Update / *Install all missing* and gh's *Sign in* (the worker page, and a
|
|
guest's *My computers* for their own computer).
|
|
|
|
The hub only **names** tools; the recipes live in the worker's own checkout
|
|
(``worker/tools.sh``, started by ``sidecar/tools_install.py``), so nothing the
|
|
hub sends is ever run as a command. The worker answers at once and reports
|
|
the batch through its ``/health`` (``toolJobs``: queued → running → done /
|
|
failed, a log tail while it runs), which the page follows by probing every
|
|
few seconds; ``tools`` re-checks once a job ends.
|
|
|
|
Core's own tools are ``gh`` and ``ask-form``; every other row is an active
|
|
**harness plugin's** ``harness.workerSetup`` (2026-11-26 — read off the
|
|
``ProviderRegistry``, never a list in core): its tool, whether a guest's
|
|
computer may install it, whether the hub may ask for an update.
|
|
|
|
the owner's workers gh, ask-form + every harness plugin's tool (claude,
|
|
opencode, agy, pi) — an ``enablesHarness`` one switches
|
|
its harness on (``install.sh update`` with its
|
|
``installerEnv=1``: the worker restarts, its runs survive)
|
|
a guest's computer gh + the ``workerSetup.guestAllowed`` ones of a
|
|
``guestAllowed`` harness (claude) — from their portal
|
|
only: the owner's routes leave a guest's machine alone
|
|
|
|
``update`` is gh and the ``workerSetup.update`` ones (pi — claude, agy,
|
|
opencode and ask-form keep themselves current). pi is the CLI for a
|
|
terminal: pi *runs* stay on the Homelab (``runs/service.py``). A sidecar from
|
|
before has no ``toolInstall`` in its ``/health``: 409 ``tools_unsupported``
|
|
until it updates itself.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import time
|
|
from typing import Literal
|
|
|
|
from fastapi import APIRouter, HTTPException
|
|
from pydantic import BaseModel
|
|
|
|
import schemas
|
|
from core.http import _r
|
|
from core.state import AppState, State
|
|
|
|
from . import guests
|
|
|
|
# Core's own rows: (checklist order, a guest's computer too, updatable).
|
|
CORE_TOOLS = {"gh": (15, True, True), "ask-form": (90, False, False)}
|
|
|
|
|
|
def _rows(reg=None) -> list[tuple[str, int, bool, bool]]:
|
|
"""``[(tool, order, guest, update)]`` — core's and every active harness
|
|
plugin's ``workerSetup``, in checklist order."""
|
|
if reg is None:
|
|
from plugins import providers
|
|
reg = providers.current()
|
|
rows = [(t, o, g, u) for t, (o, g, u) in CORE_TOOLS.items()]
|
|
for hs in getattr(reg, "harnesses", {}).values():
|
|
ws = hs.spec.get("workerSetup")
|
|
if not isinstance(ws, dict):
|
|
continue
|
|
tool = ws.get("tool") or hs.harness_id
|
|
if tool in CORE_TOOLS:
|
|
continue
|
|
guest = bool(ws.get("guestAllowed")) and bool(hs.spec.get("guestAllowed"))
|
|
order = ws.get("order") if isinstance(ws.get("order"), int) else hs.order
|
|
rows.append((tool, order, guest, bool(ws.get("update"))))
|
|
return sorted(rows, key=lambda r: (r[1], r[0]))
|
|
|
|
|
|
def allowed(w: dict, reg=None) -> tuple[str, ...]:
|
|
guest = guests.is_guest(w)
|
|
return tuple(t for t, _o, g, _u in _rows(reg) if g or not guest)
|
|
|
|
|
|
def updatable(w: dict, reg=None) -> tuple[str, ...]:
|
|
ok = set(allowed(w, reg))
|
|
return tuple(t for t, _o, _g, u in _rows(reg) if u and t in ok)
|
|
|
|
|
|
def _now() -> str:
|
|
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
|
|
|
|
|
def check(store, w: dict, tools: list[str], action: str, *, msg=lambda s, **kw: s.format(**kw)) -> list[str]:
|
|
"""The tools this call may ask for, deduplicated — or the 4xx to answer.
|
|
``msg`` translates (a guest's portal is in French)."""
|
|
if action not in ("install", "update"):
|
|
raise HTTPException(400, {"message": msg("action must be install or update"),
|
|
"kind": "bad_action"})
|
|
names = list(dict.fromkeys(t.strip() for t in tools or [] if isinstance(t, str) and t.strip()))
|
|
if not names:
|
|
raise HTTPException(400, {"message": msg("no tool named"), "kind": "no_tool"})
|
|
ok = allowed(w)
|
|
bad = [t for t in names if t not in ok]
|
|
if bad:
|
|
raise HTTPException(400, {"message": msg("{tools} can't be installed on this machine",
|
|
tools=", ".join(bad)),
|
|
"kind": "tool_unknown"})
|
|
up = updatable(w)
|
|
if action == "update" and any(t not in up for t in names):
|
|
raise HTTPException(400, {"message": msg("only {tools} are updated from here — "
|
|
"the others keep themselves current",
|
|
tools=", ".join(up)),
|
|
"kind": "not_updatable"})
|
|
if not store.online(w["id"]):
|
|
raise HTTPException(409, {"message": msg("{name} is offline", name=w.get("name") or w["id"]),
|
|
"kind": "worker_offline", "worker": w["id"]})
|
|
caps = store.status(w["id"]).get("toolInstall")
|
|
if not isinstance(caps, dict):
|
|
raise HTTPException(409, {"message": msg("{name} can't install tools from here until it "
|
|
"updates itself", name=w.get("name") or w["id"]),
|
|
"kind": "tools_unsupported"})
|
|
return names
|
|
|
|
|
|
def install(store, w: dict, names: list[str], action: str) -> dict:
|
|
"""Start the batch on the worker; its jobs read ``queued`` until the next
|
|
probe brings the worker's own word."""
|
|
from .store import sidecar_request
|
|
out = sidecar_request(w["url"], w["token"], "/tools/install",
|
|
{"tools": names, "action": action}, timeout=20,
|
|
label=f"worker {w.get('name') or w['id']}")
|
|
jobs = dict(store.status(w["id"]).get("toolJobs") or {})
|
|
for t in out.get("tools") or names:
|
|
jobs[t] = {"action": action, "state": "queued", "startedAt": _now(),
|
|
"finishedAt": None, "error": None}
|
|
store.set_status(w["id"], toolJobs=jobs)
|
|
return out
|
|
|
|
|
|
def gh_login(w: dict, method: str) -> dict:
|
|
"""gh's device-code sign-in on the worker: POST starts it (the code and
|
|
github.com/login/device), GET follows it, DELETE cancels it."""
|
|
from .store import sidecar_request
|
|
return sidecar_request(w["url"], w["token"], "/gh/login", None, method=method,
|
|
timeout=45, label=f"worker {w.get('name') or w['id']}")
|
|
|
|
|
|
# ── the owner's routes ───────────────────────────────────────────────────────
|
|
router = APIRouter()
|
|
|
|
|
|
class ToolsBody(BaseModel):
|
|
tools: list[str]
|
|
action: Literal["install", "update"] = "install"
|
|
|
|
|
|
def _owner_worker(deps: AppState, worker_id: str) -> dict:
|
|
w = deps.worker_store.get(worker_id)
|
|
if not w:
|
|
raise HTTPException(404, {"message": f"unknown worker: {worker_id!r}",
|
|
"kind": "worker_unknown"})
|
|
if guests.is_guest(w):
|
|
raise HTTPException(409, {"message": "a guest's own computer — they install "
|
|
"its tools from their portal",
|
|
"kind": "guest_computer"})
|
|
return w
|
|
|
|
|
|
@router.post("/api/workers/{worker_id}/tools", responses=_r(schemas.Worker))
|
|
def install_tools(deps: State, worker_id: str, body: ToolsBody):
|
|
"""*Install* / *Update* / *Install all missing* on the worker page —
|
|
asynchronous: ``toolJobs`` follows the batch on the next probes."""
|
|
w = _owner_worker(deps, worker_id)
|
|
names = check(deps.worker_store, w, body.tools, body.action)
|
|
install(deps.worker_store, w, names, body.action)
|
|
deps.hub.publish({"type": "workers"})
|
|
return deps.worker_store.public(deps.worker_store.get(worker_id))
|
|
|
|
|
|
def _gh(deps: AppState, worker_id: str, method: str) -> dict:
|
|
w = _owner_worker(deps, worker_id)
|
|
if not deps.worker_store.online(worker_id):
|
|
raise HTTPException(409, {"message": f"{w.get('name')} is offline",
|
|
"kind": "worker_offline", "worker": worker_id})
|
|
out = gh_login(w, method)
|
|
if method == "GET" and out.get("state") == "complete":
|
|
deps.worker_monitor.check(worker_id) # the checklist shows it at once
|
|
return out
|
|
|
|
|
|
@router.post("/api/workers/{worker_id}/gh-login", responses=_r(schemas.GhLogin))
|
|
def gh_login_start(deps: State, worker_id: str):
|
|
"""Start gh's sign-in on the worker: a code to enter at github.com/login/device."""
|
|
return _gh(deps, worker_id, "POST")
|
|
|
|
|
|
@router.get("/api/workers/{worker_id}/gh-login", responses=_r(schemas.GhLogin))
|
|
def gh_login_state(deps: State, worker_id: str):
|
|
"""``state``: pending (the code is still waiting) | complete | failed | none."""
|
|
return _gh(deps, worker_id, "GET")
|
|
|
|
|
|
@router.delete("/api/workers/{worker_id}/gh-login")
|
|
def gh_login_cancel(deps: State, worker_id: str):
|
|
return _gh(deps, worker_id, "DELETE")
|