Files
gabrielvidalandClaude Opus 5.5 1f48faaffe refactor(workers): drop the hub's Claude-only MCP servers setup
The MCP servers the owner sets up for his harnesses become the
mcp-servers live plugin (homelab spec 2026-11-26 §4.1). Gone from the
core: workers/mcpservers.py and its test, the /api/mcp-servers* routes,
the McpServer*/McpLogin*/McpMachine*/McpSetup schemas and Worker.mcpSetup,
the LabMcp poller, worker_store.mcp_servers and MCP_SERVERS_PATH, and the
MCP push / change detection in a worker's probe. A worker record keeps
its mcpServerOverrides only for the carry-over into the plugin.

The hub's own MCP server (mcpserver/, mcp.connect) is untouched.

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

639 lines
31 KiB
Python

"""
Workers — runners on other machines the hub drives like its own sidecar.
The homelab's host sidecar is the default runner: the backend POSTs to
``SIDECAR_URL`` and reads the transcripts through a mount. A **worker** is the
very same ``sidecar/sidecar.py`` running somewhere else (the Orus MacBook, as a
launchd agent — see ``worker/``), reached over the tailnet with its own bearer.
Every run is still "a POST to a sidecar URL"; a worker is just a second
``(url, token)`` pair chosen per run.
The hub pulls: spawn/resume/fork/interrupt are POSTs to the worker, liveness
is a poll of its ``/health`` + ``/sessions``, and its transcripts come over
its ``/feed`` (``remotefeed.py`` mirrors them into a dir the indexer already
watches). The one call a worker makes is its runs' model calls, to the hub's
Claude proxy, with a token that can do nothing else.
Pairing (``pair``): the worker's installer prints ``host:port/code[/login]``.
The hub trades the one-time code for the worker's bearer at ``POST /pair``
and stores the worker in ``/data/workers.json``, with the Claude accounts it
may bill (``claudeAccounts``) — through the hub's Claude proxy
(``claudeproxy/``), so the machine needs no Claude login of its own; a login
it does have only pre-selects its account. Only persisted fields go to disk;
the live status (online / offline / unauthorized, last seen, running count)
lives in memory and is re-learnt by the poller within a tick of a restart.
"""
from __future__ import annotations
import datetime
import json
import os
import pathlib
import re
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
from fastapi import HTTPException
DEFAULT_PORT = 8790
# The fields a worker record keeps on disk. Everything else is runtime status.
# ``opencodeAccounts``: the opencode accounts (ChatGPT logins) the worker hosts
# besides its Claude login — what its /health declares; an opencode run, its
# login and its usage go to the worker that hosts the account.
# ``agyAccounts``: the same for the agy (Antigravity CLI) Google logins — one
# account may be declared by several machines (each has its own login).
# ``claudeMode``: ``proxy`` (it bills the hub's Claude logins through the
# Claude proxy) or ``own`` (its machine's login); ``claudeAccounts``: the hub
# accounts a proxied worker may bill, ``proxyToken`` its bearer there
# (claudeproxy/ — never served); ``opencodeProxyAccounts``: the Homelab's
# opencode (ChatGPT) accounts it bills through the opencode proxy.
# ``owner``: the guest whose machine it is (guests.py) — unset for the
# owner's own workers.
_PERSISTED = ("id", "name", "host", "port", "url", "token", "account", "email",
"orgName", "hostname", "platform", "machine", "version", "cwd",
"permissionMode", "pairedAt", "autoRoute", "opencodeAccounts",
"agyAccounts", "commit", "updatable", "autoUpdate", "labSyncOverrides",
"claudeMode", "claudeAccounts", "proxyToken", "opencodeProxyAccounts",
"owner", "link", "pending", "linkToken", "pairCode", "enrolledAt",
"paused", "tokensRotatedAt", "proxyTokenPrev", "linkTokenPrev",
"prevTokensUntil", "enrollProfile", "enrollDefault",
"repoPluginOverrides", "mcpServerOverrides")
# ``mcpServerOverrides``: ``{name: bool}`` — this worker's ticks / unticks of
# the hub's MCP servers from before the ``mcp-servers`` plugin; kept only so
# ``plugins/carryover.mcp_servers`` can carry them over (nothing writes it).
# ``repoPluginOverrides``: ``{"<plugin>@<marketplace>": bool}`` — this
# worker's ticks / unticks of its repo's plugins (workers/repoplugins.py).
# ``link``: it dials out to the hub (link.py) — its ``url`` is this backend's
# own ``/_tunnel/<id>``, its ``linkToken`` what it polls with, ``pending`` +
# ``pairCode`` until the pairing through the link has run.
# ``paused``: its guest paused it. ``tokensRotatedAt``: when its proxy and
# link tokens were last replaced (guests.maybe_rotate) — the previous ones
# still work until ``prevTokensUntil``, the time it takes to hand the new ones
# over. ``enrollProfile`` / ``enrollDefault``: an owner's machine that dials
# out joins that profile (as its default runner) once paired (link.on_paired).
# Not served either (``_SECRET``): only the hub reads them.
_SECRET = ("token", "proxyToken", "labSyncOverrides", "linkToken", "pairCode",
"proxyTokenPrev", "linkTokenPrev", "enrollProfile", "enrollDefault",
"repoPluginOverrides", "mcpServerOverrides")
_CODE_RE = re.compile(r"^[A-Za-z0-9]{6,32}$")
_HOST_RE = re.compile(r"^[A-Za-z0-9.-]{1,253}$")
def _now_iso() -> str:
return datetime.datetime.now(datetime.timezone.utc) \
.strftime("%Y-%m-%dT%H:%M:%SZ")
# ── the sidecar HTTP call (shared with main's local-sidecar path) ─────────────
def error_detail(body: str) -> dict:
"""A sidecar error body → the structured detail. An older sidecar (or a
FastAPI validation error) answers a plain string / list — wrap it."""
try:
detail = json.loads(body).get("detail")
except (ValueError, AttributeError):
detail = body[:500]
if isinstance(detail, dict) and detail.get("message"):
return detail
return {"message": str(detail)[:500] or "sidecar error", "kind": "unknown"}
def sidecar_request(base: str, token: str, path: str,
payload: dict | None = None, *, method: str = "POST",
timeout: float = 15, label: str = "sidecar") -> dict:
"""Call a runner (bearer auth) and return its JSON reply.
502 when it's unreachable, and a runner error passes through with its own
status — except 401/403 (its bearer check), which become 502: the viewer
reads any 401 as an expired Authelia session and reloads into the login
page. The detail is always ``{message, kind, hint?, account?}``."""
data = json.dumps(payload).encode() if payload is not None else None
req = urllib.request.Request(
f"{base}{path}", data=data, method=method,
headers={"Content-Type": "application/json",
"Authorization": f"Bearer {token}"})
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.loads(r.read().decode())
except urllib.error.HTTPError as e:
body = e.read().decode(errors="replace")
if e.code in (401, 403):
if label == "sidecar":
raise HTTPException(502, error_detail(body))
raise HTTPException(502, {
"message": f"{label} refused the hub's token — re-pair it",
"kind": "worker_auth"})
status = e.code if 400 <= e.code < 600 else 502
raise HTTPException(status, error_detail(body))
except (urllib.error.URLError, OSError, ValueError) as e:
kind = "worker_offline" if label != "sidecar" else "sidecar"
raise HTTPException(502, {"message": f"{label} unreachable: {e}",
"kind": kind})
def _get_json(url: str, token: str | None = None, timeout: float = 4) -> dict:
headers = {"Authorization": f"Bearer {token}"} if token else {}
with urllib.request.urlopen(urllib.request.Request(url, headers=headers),
timeout=timeout) as r:
return json.loads(r.read().decode())
# ── pairing string ────────────────────────────────────────────────────────────
def parse_pairing(raw: str) -> dict:
"""``100.80.162.92:8790/K7QMX4PJ2R/gabriel@orus.insure`` → its parts.
The login segment is optional (an older installer, a Mac with no login
yet); a leading ``http://`` is tolerated because people paste URLs. 400
with ``kind: "pairing"`` on anything else."""
s = (raw or "").strip()
s = re.sub(r"^https?://", "", s)
head, _, rest = s.partition("/")
code, _, login = rest.partition("/")
host, _, port = head.rpartition(":") if ":" in head else (head, "", "")
try:
port_n = int(port) if port else DEFAULT_PORT
except ValueError:
port_n = -1
if not (host and _HOST_RE.match(host) and 0 < port_n < 65536
and _CODE_RE.match(code or "")):
raise HTTPException(400, {
"message": "not a pairing string — expected host:port/code "
"(the line install-macos.sh prints)",
"kind": "pairing"})
return {"host": host, "port": port_n, "code": code.upper(),
"login": urllib.parse.unquote(login).strip() or None}
# ── the store ─────────────────────────────────────────────────────────────────
class WorkerStore:
"""``/data/workers.json`` — MetaStore/CronStore discipline: one lock,
atomic saves, mtime reload (the deploy-cutover twin shares the file)."""
def __init__(self, path: str):
self.path = pathlib.Path(path)
self._lock = threading.Lock()
self._mtime: float | None = None
self._checked = 0.0
self._data: dict[str, dict] = {}
self._by_link_token: dict[str, dict] = {}
self._by_link_token_prev: dict[str, dict] = {}
self._status: dict[str, dict] = {}
self.version = 0
# (worker id, its Claude logins) → its ★ among them — the profiles'
# business, wired in by core/state (the Claude proxy's machine default).
self.star_of = None
# () → days between a guest computer's token rotations (core/state).
self.rotate_days = lambda: 7
# (worker, its /health ``terminal``) → pushed? — a guest computer's
# picker and mod figures (workers/terminal.py, wired by core/state).
self.terminal_push = None
# The account picks of repo plugins (workers/repoplugins.py
# RepoPluginSettings, wired by core/state; None ⇒ the seed).
self.repo_plugins = None
self._load()
def _rebuild_link_index(self) -> None:
by_tok: dict[str, dict] = {}
by_prev: dict[str, dict] = {}
for rec in self._data.values():
tok = rec.get("linkToken")
if tok:
by_tok[tok] = rec
prev = rec.get("linkTokenPrev")
if prev:
by_prev[prev] = rec
self._by_link_token = by_tok
self._by_link_token_prev = by_prev
def _load(self) -> None:
try:
self._data = json.loads(self.path.read_text(encoding="utf-8")) or {}
self._mtime = self.path.stat().st_mtime
except (OSError, ValueError):
self._data, self._mtime = {}, None
# Records paired before the flag existed auto-routed by construction
# (that was the only behaviour) — keep them doing so. Legacy: the flag
# only seeds a profile's default runner now (profiles/store.py).
for rec in self._data.values():
rec.setdefault("autoRoute", True)
self._rebuild_link_index()
self._checked = time.monotonic()
def _save(self) -> None:
self.path.parent.mkdir(parents=True, exist_ok=True)
tmp = self.path.with_suffix(".json.tmp")
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w", encoding="utf-8") as f:
json.dump(self._data, f, indent=2, sort_keys=True)
os.replace(tmp, self.path)
try:
self._mtime = self.path.stat().st_mtime
except OSError:
pass
self._rebuild_link_index()
self._checked = time.monotonic()
self.version += 1
def _reload_if_changed(self, force: bool = False) -> None:
now = time.monotonic()
if not force and now - self._checked < 1.0:
return
self._checked = now
try:
m = self.path.stat().st_mtime
except OSError:
if self._mtime is not None:
self._data, self._mtime = {}, None
self._rebuild_link_index()
return
if m != self._mtime:
self._load()
self.version += 1
def list(self) -> list[dict]:
with self._lock:
self._reload_if_changed()
return [dict(w) for w in self._data.values()]
def get(self, wid: str | None) -> dict | None:
if not wid:
return None
with self._lock:
self._reload_if_changed()
w = self._data.get(wid)
return dict(w) if w else None
def by_link_token(self, token: str) -> dict | None:
"""O(1) lookup of a linked worker by its current or grace-period linkToken."""
if not token:
return None
from . import guests
with self._lock:
self._reload_if_changed()
w = self._by_link_token.get(token)
if w is not None and guests.token_matches(w, "linkToken", token):
return dict(w)
w = self._by_link_token_prev.get(token)
if w is not None and guests.token_matches(w, "linkToken", token):
return dict(w)
return None
def put(self, w: dict) -> dict:
rec = {k: w.get(k) for k in _PERSISTED}
with self._lock:
self._reload_if_changed(force=True)
self._data[rec["id"]] = rec
self._save()
return dict(rec)
def patch(self, wid: str, changes: dict) -> dict | None:
with self._lock:
self._reload_if_changed(force=True)
cur = self._data.get(wid)
if not cur:
return None
cur.update({k: v for k, v in changes.items() if k in _PERSISTED})
self._save()
return dict(cur)
def delete(self, wid: str) -> bool:
with self._lock:
self._reload_if_changed(force=True)
gone = self._data.pop(wid, None) is not None
if gone:
self._save()
self._status.pop(wid, None)
return gone
# runtime status (memory only)
def status(self, wid: str) -> dict:
with self._lock:
return dict(self._status.get(wid) or {"status": "unknown"})
def set_status(self, wid: str, **st) -> bool:
"""Merge status fields; True when ``status`` itself changed."""
with self._lock:
cur = self._status.setdefault(wid, {"status": "unknown"})
changed = "status" in st and st["status"] != cur.get("status")
cur.update(st)
return changed
def online(self, wid: str | None) -> bool:
return bool(wid) and self.status(wid).get("status") == "online"
def hosting(self, account: str | None) -> list[dict]:
"""The workers whose sidecar declares this hosted login — an opencode
seat (``opencodeAccounts``) or an agy Google login (``agyAccounts``)."""
return [w for w in self.list()
if account and account in [*(w.get("opencodeAccounts") or []),
*(w.get("agyAccounts") or [])]]
def public(self, w: dict) -> dict:
"""What the API serves: no token, plus the live status."""
from claudeproxy import opencode as oc_proxy, service as proxy
from . import labsync, repoplugins, updates
out = {k: w.get(k) for k in _PERSISTED if k not in _SECRET}
st = self.status(w["id"])
hub = updates.hub_commit()
out.update({"autoUpdate": w.get("autoUpdate") is not False,
"updatable": bool(w.get("updatable")),
"hubCommit": hub,
"updateStatus": updates.update_status(w, st, hub),
"update": st.get("update"),
"updateError": st.get("updateError"),
"status": st.get("status", "unknown"),
"lastSeen": st.get("lastSeen"),
"lastError": st.get("lastError"),
"running": st.get("running", 0),
"mirrored": st.get("mirrored", 0),
"syncing": bool(st.get("syncing")),
"labSyncStatus": labsync.status(st, labsync.for_worker(w)),
"labSync": st.get("labSync"),
"labSyncError": st.get("labSyncError"),
"claudeMode": proxy.mode(w),
"claudeAccounts": proxy.claude_accounts(w),
"claudeProxy": proxy.public(self, w, st),
"opencodeProxyAccounts": oc_proxy.proxied_accounts(w),
"opencodeProxy": oc_proxy.public(w, st),
"tools": st.get("tools") if isinstance(st.get("tools"), dict) else None,
"toolsCheckedAt": st.get("toolsCheckedAt"),
"toolInstall": st.get("toolInstall") if isinstance(st.get("toolInstall"), dict) else None,
"toolJobs": st.get("toolJobs") if isinstance(st.get("toolJobs"), dict) else None,
"repoPlugins": repoplugins.held(st),
"repoPluginsStatus": repoplugins.status(
st, w, repoplugins._picks(self)) if repoplugins.eligible(w)
else repoplugins.NONE,
"repoPluginsError": st.get("repoPluginsError")})
return out
# ── pairing ───────────────────────────────────────────────────────────────────
def pair(store: WorkerStore, raw: str, *, account: str | None,
name: str | None, hub_name: str,
resolve_login, valid_account, auto_route: bool = False,
claude_accounts: list[str] | None = None, claude_mode: str = "proxy") -> dict:
"""Pair with a worker from its pairing string. A worker needs no Claude
login of its own: by default (``claude_mode`` ``proxy``) it bills the
hub's accounts through the Claude proxy — ``claude_accounts`` (the
dialog's ticks), else the login its string names when it is one of the
hub's, else the default account. ``own`` runs it on its own login, which
must then match one of the hub's accounts (checked before the code is
spent, so a mismatch asks for a pick instead of burning it)."""
import accounts as accounts_mod
from claudeproxy.service import clean_accounts
p = parse_pairing(raw)
acct = valid_account(account) if account else None
if account and not acct:
raise HTTPException(400, {"message": f"unknown account: {account!r}",
"kind": "account"})
if not acct and p["login"]:
acct = resolve_login(p["login"]) or valid_account(p["login"])
claude_mode = "own" if claude_mode == "own" else "proxy"
if claude_mode == "own" and not acct:
raise HTTPException(400, {
"message": (f"no account on this hub is signed in as "
f"{p['login']} — pick the account" if p["login"] else
"the pairing string names no Claude login — pick the "
"account this worker's own login is, or bill the hub's"),
"kind": "account", "login": p["login"]})
proxied = clean_accounts(claude_accounts) if claude_accounts is not None else []
if not proxied:
proxied = clean_accounts([acct]) or [accounts_mod.DEFAULT]
url = f"http://{p['host']}:{p['port']}"
try:
req = urllib.request.Request(
f"{url}/pair", method="POST",
data=json.dumps({"code": p["code"], "hubName": hub_name}).encode(),
headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=10) as r:
out = json.loads(r.read().decode())
except urllib.error.HTTPError as e:
d = error_detail(e.read().decode(errors="replace"))
hint = {"bad_code": "check the code, or run `install-macos.sh --pair` "
"on the worker for a new one",
"no_code": "run `install-macos.sh --pair` on the worker"}
raise HTTPException(409 if e.code in (403, 409) else 502,
{**d, "kind": d.get("kind") or "pairing",
"hint": hint.get(d.get("kind"))})
except (urllib.error.URLError, OSError, ValueError) as e:
raise HTTPException(502, {
"message": f"worker unreachable at {url}: {e}",
"kind": "worker_offline",
"hint": "is the worker running (install-macos.sh --status) and "
"is this box on the same tailnet?"})
if not out.get("token") or not out.get("workerId"):
raise HTTPException(502, {"message": "worker answered /pair without a "
"token", "kind": "pairing"})
login = out.get("account") or {}
w = store.put({
"id": out["workerId"],
"name": (name or "").strip()[:60] or out.get("name")
or out.get("hostname") or p["host"],
"host": p["host"], "port": p["port"], "url": url,
"token": out["token"], "account": acct, "claudeMode": claude_mode,
"claudeAccounts": proxied,
"email": login.get("email") or p["login"],
"orgName": login.get("orgName"),
"hostname": out.get("hostname"), "platform": out.get("platform"),
"machine": out.get("machine"), "version": out.get("version"),
"cwd": out.get("cwd"), "permissionMode": out.get("permissionMode"),
"pairedAt": _now_iso(), "autoRoute": bool(auto_route),
})
store.set_status(w["id"], status="online", lastSeen=_now_iso(),
lastError=None)
return w
def unpair(store: WorkerStore, wid: str) -> bool:
"""Forget a worker; tell it to drop the bearer too (best-effort — an
offline worker keeps a token nobody holds any more)."""
w = store.get(wid)
if not w:
return False
try:
sidecar_request(w["url"], w["token"], "/unpair", {}, timeout=5,
label="worker")
except HTTPException:
pass
return store.delete(wid)
# ── liveness ──────────────────────────────────────────────────────────────────
def probe(store: WorkerStore, w: dict) -> bool:
"""One health check: ``/health`` (is it up) + ``/sessions`` (does our token
still work — a re-pair elsewhere rotates it). Updates the status, then
lets ``updates.maybe_update`` move a worker that is behind the hub and
``labsync.maybe_push`` send it the lab's portable skills and agents, and
``claudeproxy.maybe_push`` its Claude proxy config, ``repoplugins`` its
repo plugins; True when the status,
the worker's version standing, its lab sync or its proxy changed."""
from claudeproxy import opencode as oc_proxy, service as proxy
from . import labsync, repoplugins, updates
if w.get("pending"):
# Enrolled, not paired yet: the link's first poll pairs it (link.py).
return store.set_status(w["id"], status="pairing")
try:
h = _get_json(f"{w['url']}/health")
s = _get_json(f"{w['url']}/sessions", w["token"])
before = updates.update_status(w, store.status(w["id"]))
changes = {k: h.get(k) for k in ("version", "permissionMode", "cwd",
"opencodeAccounts", "agyAccounts", "commit")
if h.get(k) is not None and h.get(k) != w.get(k)}
if bool(h.get("updatable")) != bool(w.get("updatable")):
changes["updatable"] = bool(h.get("updatable"))
if changes:
w = store.patch(w["id"], changes) or w
held = store.status(w["id"]).get("labSync")
held_plugins = store.status(w["id"]).get("repoPlugins")
held_proxy = (proxy.status(store, w, store.status(w["id"])),
oc_proxy.status(w, store.status(w["id"])))
changed = store.set_status(w["id"], status="online", lastSeen=_now_iso(),
lastError=None, running=s.get("count", 0),
update=h.get("update"), labSync=h.get("labSync"),
# the harness / provider maps it holds and
# runs (sidecar labsync.plugin_sync) —
# labsync.status re-sends what it lacks
pluginSync=h.get("pluginSync"),
liveHarnesses=h.get("harnesses"),
liveProviders=h.get("providers"),
claudeProxy=h.get("claudeProxy"),
opencodeProxy=h.get("opencodeProxy"),
terminal=h.get("terminal"),
# a guest computer's own Claude login
# (sidecar claude_accounts.machine_login)
ownLogin=h.get("ownLogin"),
agentKeys=h.get("agentKeys"),
# the Setup checklist (sidecar tools_check.py)
tools=h.get("tools"),
toolsCheckedAt=h.get("toolsCheckedAt"),
# what it can install from there, and how
# each install went (sidecar tools_install.py)
toolInstall=h.get("toolInstall"),
toolJobs=h.get("toolJobs"),
# the cwd repo's plugins (sidecar repo_plugins.py)
repoPlugins=h.get("repoPlugins"),
# can it run Code Mode (runs/codemode.py)
codeMode=h.get("codeMode"))
updating = updates.maybe_update(store, w) or \
updates.update_status(w, store.status(w["id"])) == updates.UPDATING
pushed = False
# A worker about to restart onto other code gets its bundle on the
# probe after: an older sidecar takes the bundle's hash and drops
# what it doesn't know (the harness plugin maps, 2026-11-26).
if not updating:
try:
pushed = labsync.maybe_push(store, w)
except Exception as e: # a lab-side read error must not read as offline
store.set_status(w["id"], labSyncError=str(e)[:200])
try:
pushed |= repoplugins.maybe_push(store, w)
except Exception as e:
store.set_status(w["id"], repoPluginsError=str(e)[:200])
try:
from . import guests
if guests.maybe_rotate(store, w, store.rotate_days()):
w = store.get(w["id"]) or w
except Exception as e:
store.set_status(w["id"], lastError=f"rotation: {e}"[:200])
try:
pushed |= proxy.maybe_push(store, w)
except Exception as e:
store.set_status(w["id"], claudeProxyError=str(e)[:200])
try:
pushed |= oc_proxy.maybe_push(store, w)
except Exception as e:
store.set_status(w["id"], opencodeProxyError=str(e)[:200])
push_status = store.terminal_push
if push_status:
# A guest computer's picker and mod: budget left, paused… (terminal.py)
try:
pushed |= bool(push_status(w, h.get("terminal")))
except Exception as e:
store.set_status(w["id"], lastError=f"terminal status: {e}"[:200])
w = store.get(w["id"]) or w
return (changed or pushed or held != store.status(w["id"]).get("labSync")
or _plugins_state(held_plugins) != _plugins_state(
store.status(w["id"]).get("repoPlugins"))
or held_proxy != (proxy.status(store, w, store.status(w["id"])),
oc_proxy.status(w, store.status(w["id"])))
or updates.update_status(w, store.status(w["id"])) != before)
except urllib.error.HTTPError as e:
st = "unauthorized" if e.code in (401, 403) else "offline"
return store.set_status(w["id"], status=st, lastError=f"HTTP {e.code}")
except (urllib.error.URLError, OSError, ValueError) as e:
return store.set_status(w["id"], status="offline",
lastError=str(getattr(e, "reason", e))[:200])
def _plugins_state(v) -> object:
"""A repoPlugins report minus its ``checkedAt`` (which moves every read)."""
return {k: x for k, x in v.items() if k != "checkedAt"} if isinstance(v, dict) else v
class WorkerMonitor(threading.Thread):
"""Polls every paired worker's health; publishes a ``workers`` SSE event
when one goes online/offline (the Settings cards, the composer chip and
the home banner all key off it)."""
def __init__(self, store: WorkerStore, publish, interval: float = 15.0):
super().__init__(daemon=True, name="worker-monitor")
self.store, self.publish, self.interval = store, publish, interval
def check(self, wid: str | None = None) -> None:
changed = False
for w in self.store.list():
if wid and w["id"] != wid:
continue
changed |= probe(self.store, w)
if changed or wid:
self.publish({"type": "workers"})
def run(self) -> None:
while True:
try:
self.check()
except Exception:
pass
# Between rounds, a worker installing tools is probed every few
# seconds: its Setup checklist follows the batch live.
end = time.monotonic() + self.interval
while (left := end - time.monotonic()) > 0:
time.sleep(min(HOT_S, left))
try:
self.check_hot()
except Exception:
pass
def check_hot(self) -> None:
for w in self.store.list():
if installing(self.store.status(w["id"])):
self.check(w["id"])
HOT_S = 3.0
HOT_MAX_S = 30 * 60 # a batch that never reports back stops being watched
def installing(st: dict, now: float | None = None) -> bool:
"""A tool install queued or running on this worker, started in the last
half hour (workers/tools.py) — what makes it a hot probe."""
import calendar
jobs = st.get("toolJobs")
if not isinstance(jobs, dict):
return False
now = time.time() if now is None else now
for j in jobs.values():
if not isinstance(j, dict) or j.get("state") not in ("queued", "running"):
continue
try:
at = calendar.timegm(time.strptime(j.get("startedAt") or "", "%Y-%m-%dT%H:%M:%SZ"))
except ValueError:
continue
if now - at < HOT_MAX_S:
return True
return False