- 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>
259 lines
8.8 KiB
Python
259 lines
8.8 KiB
Python
"""
|
|
``/health``'s ``tools`` (workers only): the worker page's *Setup* checklist —
|
|
is each tool installed here (path, version) and signed in / set up. What's
|
|
missing is installed from that same checklist (tools_install.py).
|
|
|
|
Core checks its own two tools; every other row is a **harness plugin's**
|
|
(its ``harness.workerSetup``, read through ``tools_install.harness_tools``):
|
|
the driver's ``setup_check(tc)`` answers its row, ``tc`` being this module
|
|
(the helpers below — ``_run``, ``_which``, ``_first_line``, ``_own``,
|
|
``_status``, ``harness_row`` — are the API a driver may use). A driver with no
|
|
``setup_check`` gets a bare "is ``<tool>`` on PATH" row. harness-claude
|
|
answers ``claude`` (its ``auth status``, or the hub's Claude proxy),
|
|
harness-opencode / harness-agy their CLI + the declared account's login,
|
|
harness-pi ``pi`` (its wrapper marks a managed copy). A guest's computer
|
|
checks only what it may install (tools_install.allowed).
|
|
|
|
The checks run CLIs (``gh auth status``, ``claude --version``…), so they never
|
|
run inside a ``/health`` request: ``public()`` answers the last result (None
|
|
until the first one is in) and starts a background refresh when it is older
|
|
than ``TTL_S`` — or than the last install tools_install.py finished, or an
|
|
``invalidate()`` (a gh sign-in). Nothing a check returns is a secret — ``gh``'s login name, the
|
|
Claude login's email, never a token or a CLI's raw output.
|
|
|
|
gh signedIn: ``gh auth status`` exits 0; ``login`` read off its output;
|
|
``managed``: the worker (or brew) installed it — *Update* moves it
|
|
ask-form installed: a real ``ask-form`` on PATH (not this repo's
|
|
``cli/ask-form`` install hint); signedIn: set up (its admin token)
|
|
and its serve answers ``/v1/health`` (askform.health)
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import platform
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import threading
|
|
import time
|
|
|
|
TTL_S = 10 * 60
|
|
TIMEOUT_S = 15
|
|
SHIM_MARK = "the ask-form tool isn't installed"
|
|
|
|
_lock = threading.Lock()
|
|
_state: dict = {"at": 0.0, "tools": None, "running": False}
|
|
|
|
|
|
def _run(args: list[str], timeout: float = TIMEOUT_S) -> tuple[int, str]:
|
|
"""(exit code, stdout + stderr); (-1, "") when it couldn't run."""
|
|
try:
|
|
r = subprocess.run(args, capture_output=True, text=True, timeout=timeout,
|
|
stdin=subprocess.DEVNULL)
|
|
return r.returncode, (r.stdout or "") + (r.stderr or "")
|
|
except (OSError, subprocess.SubprocessError):
|
|
return -1, ""
|
|
|
|
|
|
def _first_line(text: str) -> str | None:
|
|
line = (text or "").strip().splitlines()[0:1]
|
|
return line[0].strip()[:80] if line else None
|
|
|
|
|
|
def _which(name: str) -> str | None:
|
|
"""On PATH, else in ~/.local/bin — where tools.sh installs, which an
|
|
older service's PATH may lack."""
|
|
p = shutil.which(name)
|
|
if p:
|
|
return p
|
|
own = pathlib.Path.home() / ".local" / "bin" / name
|
|
return str(own) if os.access(own, os.X_OK) else None
|
|
|
|
|
|
def _own(path: str | None) -> bool:
|
|
"""Installed by the worker (tools.sh → ~/.local/bin) or by Homebrew —
|
|
something *Update* may move."""
|
|
if not path:
|
|
return False
|
|
if path == str(pathlib.Path.home() / ".local" / "bin" / os.path.basename(path)):
|
|
return True
|
|
real = os.path.realpath(path)
|
|
return platform.system() == "Darwin" and "/Cellar/" in real
|
|
|
|
|
|
def _status(harness: str, account: str) -> dict:
|
|
"""An account's login as its harness plugin's driver reads it — {} when
|
|
that harness isn't installed here, or its driver can't say."""
|
|
import harness_loader
|
|
from harness_base import NOT_HANDLED
|
|
d = harness_loader.get(harness)
|
|
if d is None:
|
|
return {}
|
|
try:
|
|
st = d.account_status(account)
|
|
except Exception: # noqa: BLE001 — a checklist read never fails
|
|
return {}
|
|
return st if isinstance(st, dict) and st is not NOT_HANDLED else {}
|
|
|
|
|
|
_GH_LOGIN = re.compile(r"(?:account|as)\s+([A-Za-z0-9-]{1,39})\b")
|
|
|
|
|
|
def check_gh() -> dict:
|
|
path = _which("gh")
|
|
out: dict = {"installed": bool(path), "path": path}
|
|
if not path:
|
|
return {**out, "signedIn": False}
|
|
rc, text = _run([path, "--version"])
|
|
out["version"] = _first_line(text) if rc == 0 else None
|
|
rc, text = _run([path, "auth", "status", "--hostname", "github.com"])
|
|
out["signedIn"] = rc == 0
|
|
m = _GH_LOGIN.search(text) if rc == 0 else None
|
|
out["login"] = m.group(1) if m else None
|
|
out["managed"] = _own(path)
|
|
return out
|
|
|
|
|
|
def harness_row(name: str, bin_path: str | None, accounts, status_fn) -> dict:
|
|
"""A harness CLI's row (opencode / agy): the binary, whether this service
|
|
runs it (an account declared) and that account's login — a helper for
|
|
the harness drivers' ``setup_check``."""
|
|
out: dict = {"installed": bool(bin_path), "path": bin_path,
|
|
"harness": bool(accounts)}
|
|
if bin_path:
|
|
rc, text = _run([bin_path, "--version"])
|
|
out["version"] = _first_line(text) if rc == 0 else None
|
|
account = next(iter(accounts), None)
|
|
out["account"] = account
|
|
if not (bin_path and account):
|
|
return {**out, "signedIn": False}
|
|
st = status_fn(account) or {}
|
|
out["signedIn"] = bool(st.get("loggedIn"))
|
|
out["login"] = st.get("email") or None
|
|
return out
|
|
|
|
|
|
_harness = harness_row # the old name
|
|
|
|
|
|
def check_plain(tool: str) -> dict:
|
|
"""A harness row whose driver has no ``setup_check``: on PATH or not."""
|
|
path = _which(tool)
|
|
out: dict = {"installed": bool(path), "path": path, "signedIn": None}
|
|
if path:
|
|
rc, text = _run([path, "--version"])
|
|
out["version"] = _first_line(text) if rc == 0 else None
|
|
return out
|
|
|
|
|
|
def _askform_bin() -> str | None:
|
|
p = _which("ask-form")
|
|
if not p:
|
|
return None
|
|
try:
|
|
with open(p, "rb") as f:
|
|
if SHIM_MARK.encode() in f.read(4096):
|
|
return None
|
|
except OSError:
|
|
return None
|
|
return p
|
|
|
|
|
|
def check_askform() -> dict:
|
|
import askform
|
|
path = _askform_bin()
|
|
out: dict = {"installed": bool(path), "path": path}
|
|
if path:
|
|
rc, text = _run([path, "--version"])
|
|
v = None
|
|
if rc == 0:
|
|
try:
|
|
v = json.loads(text).get("version")
|
|
except (ValueError, AttributeError):
|
|
v = _first_line(text)
|
|
out["version"] = v
|
|
h = askform.health()
|
|
out["configured"] = bool(h.get("installed"))
|
|
out["running"] = bool(h.get("ok"))
|
|
out["signedIn"] = out["configured"] and out["running"]
|
|
return out
|
|
|
|
|
|
# Core's own checks; the harness rows come from their plugins (checks()).
|
|
CHECKS = {"gh": check_gh, "ask-form": check_askform}
|
|
|
|
|
|
def checks() -> dict:
|
|
"""``{tool: check()}`` of this machine, in checklist order: core's and
|
|
every loaded harness plugin's (its driver's ``setup_check``)."""
|
|
import sys
|
|
import tools_install
|
|
me = sys.modules[__name__]
|
|
harness = {}
|
|
for r in tools_install.harness_tools():
|
|
fn = getattr(r["driver"], "setup_check", None)
|
|
harness[r["tool"]] = ((lambda fn=fn: fn(me)) if callable(fn)
|
|
else (lambda t=r["tool"]: check_plain(t)))
|
|
out = {}
|
|
for name in tools_install.allowed():
|
|
fn = CHECKS.get(name) or harness.get(name)
|
|
if fn is not None:
|
|
out[name] = fn
|
|
return out
|
|
|
|
|
|
def collect() -> dict:
|
|
tools = {}
|
|
for name, fn in checks().items():
|
|
try:
|
|
tools[name] = fn()
|
|
except Exception as e: # a broken check reads as unknown, never a 500
|
|
tools[name] = {"installed": None, "signedIn": None, "error": str(e)[:200]}
|
|
return tools
|
|
|
|
|
|
def _refresh() -> None:
|
|
try:
|
|
tools = collect()
|
|
with _lock:
|
|
_state.update(tools=tools, at=time.time())
|
|
finally:
|
|
with _lock:
|
|
_state["running"] = False
|
|
|
|
|
|
def invalidate() -> None:
|
|
"""Re-check on the next /health (something was just signed in)."""
|
|
with _lock:
|
|
_state["at"] = 0.0
|
|
|
|
|
|
def _installed_since(at: float) -> bool:
|
|
try:
|
|
import tools_install
|
|
return tools_install.last_finished() > at
|
|
except Exception:
|
|
return False
|
|
|
|
|
|
def public(now: float | None = None) -> dict | None:
|
|
"""The last checklist (``{checkedAt, tools: {name: {...}}}``) or None
|
|
before the first one; refreshes in the background when stale."""
|
|
now = time.time() if now is None else now
|
|
with _lock:
|
|
stale = now - _state["at"] >= TTL_S or _installed_since(_state["at"])
|
|
if stale and not _state["running"]:
|
|
_state["running"] = True
|
|
threading.Thread(target=_refresh, daemon=True, name="tools-check").start()
|
|
if _state["tools"] is None:
|
|
return None
|
|
return {"checkedAt": int(_state["at"]), "tools": _state["tools"]}
|
|
|
|
|
|
def start() -> None:
|
|
"""Warm it up at sidecar start, so the first /health after has it."""
|
|
public()
|