Files
paulandClaude Opus 5.5 61dca2c3ca Run on the workstation, on pydantic-ai with cloud and local models
The daemon moves from the Lightsail host to WSL on the workstation (EVAI),
where the RTX 4090 can run local models and the data platform and home
cluster live. It reaches the core host over one multiplexed SSH connection:
each health check pipes probe.py to the host's python3 and gets Kuma, disk,
memory, OOM kills, restarts and reboots back in one snapshot. The agent edits
and commits core's live checkout there, as semprini-core's rules expect, and
the service desk still runs on the host. Off the host, it now notices when
the host itself stops answering.

The agent runs in-process with pydantic-ai instead of Claude Code headless.
Model profiles (anthropic, ollama, any OpenAI-compatible server) are routed
per kind of task: an unreachable model hands over at once (FallbackModel), a
run that fails as a run restarts on the next profile. The result is a typed
envelope; conversations persist as message histories; cancel stops the
command in flight; each reply names the model and its cost. `model` in Matrix
pins a room to a profile; --try-model checks a model calls tools and uses
what they return (qwen3-coder does not; GLM-4.7-Flash, the local default, does).

Cloud runs now need an API key (--set-api-key) and are billed per token; the
subscription token was for Claude Code only. Back-off is per kind of task, so
a cloud-only upgrade waiting on a key does not stall work the local model
can do. A queued task held back by a hold no longer spins the main loop.

--hold and --resume stay stdlib-only, so sync-to-host.sh can still hold the
daemon from the host's checkout; the daemon reads the host's hold each minute.
install.sh sets up WSL and retires the host's service: one Matrix bot, one
daemon.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 01:46:03 +12:00

156 lines
5.5 KiB
Python

#!/usr/bin/env python3
"""
One health snapshot of the core stack host, as JSON on stdout.
The daemon does not run on the host it watches, so each health cycle pipes
this script to `ssh core python3 - '<args>'` and reads everything back in one
round trip: Uptime Kuma's monitors and up/down transitions, disk, memory,
kernel OOM kills, container restart counts, boot time and a pending reboot.
Judging the snapshot stays in maintainer.py; this only reads.
Args (one JSON object in argv[1]):
kuma_volume, sqlite_image where kuma.db lives and what reads it
event_since Kuma heartbeat id already seen; null = watermark only
oom_since unix time to read the kernel log from
Stdlib only: it runs on the host's system python3.
"""
import json
import os
import re
import shutil
import subprocess
import sys
import time
KUMA_QUERY = (
"select json_object('latest', (select max(time) from heartbeat), "
"'monitors', (select json_group_array(json_object("
"'id', m.id, 'name', m.name, 'type', m.type, 'url', m.url, "
"'hostname', m.hostname, 'port', m.port, "
"'status', (select h.status from heartbeat h where h.monitor_id=m.id "
"order by h.time desc limit 1), "
"'msg', (select h.msg from heartbeat h where h.monitor_id=m.id "
"order by h.time desc limit 1))) "
"from monitor m where m.active=1));"
)
# Kuma flags every up/down transition with important=1. This reads those since
# a heartbeat id, plus the current max id (watermark), in one shot.
KUMA_EVENTS_QUERY = (
"select json_object("
"'watermark', (select max(id) from heartbeat), "
"'events', (select json_group_array(json_object("
"'monitor_id', h.monitor_id, 'name', m.name, 'status', h.status, "
"'time', h.time, 'msg', h.msg)) "
"from heartbeat h join monitor m on m.id = h.monitor_id "
"where h.important = 1 {clause} order by h.id));"
)
SPLIT = "--8<--"
def run(argv, timeout=60):
return subprocess.run(argv, capture_output=True, text=True, timeout=timeout)
def unnest(data):
# A json_group_array inside a subquery can come back as text.
return {k: (json.loads(v) if isinstance(v, str) and v[:1] in "[{" else v)
for k, v in data.items()}
def kuma(args):
"""Both Kuma queries against one copy of kuma.db, read out of its named
volume by a throwaway sqlite container (the file is root-owned)."""
since = args.get("event_since")
clause = "and 1=0" if since is None else f"and h.id > {int(since)}"
script = (f"cp /src/kuma.db /tmp/k.db && sqlite3 /tmp/k.db \"{KUMA_QUERY}\" && "
f"echo '{SPLIT}' && sqlite3 /tmp/k.db \"{KUMA_EVENTS_QUERY.format(clause=clause)}\"")
out = run(["docker", "run", "--rm", "-v", f"{args['kuma_volume']}:/src:ro",
args["sqlite_image"], "sh", "-c", script], timeout=120)
if out.returncode != 0:
raise RuntimeError(f"kuma read failed: {out.stderr.strip()[:300]}")
status, _, events = out.stdout.partition(SPLIT)
return unnest(json.loads(status.strip() or "{}")), unnest(json.loads(events.strip() or "{}"))
def meminfo_mb():
info = {}
with open("/proc/meminfo") as fh:
for line in fh:
key, _, rest = line.partition(":")
info[key] = int(rest.split()[0]) // 1024
return info
def boot_time():
with open("/proc/stat") as fh:
for line in fh:
if line.startswith("btime "):
return int(line.split()[1])
return None
def reboot_required():
"""Packages waiting on a reboot, or None when none is pending."""
if not os.path.exists("/var/run/reboot-required"):
return None
try:
with open("/var/run/reboot-required.pkgs") as fh:
return sorted({p.strip() for p in fh if p.strip()})
except OSError:
return []
def oom_kills_since(ts):
"""Kernel OOM-kill lines since ts (needs the adm or systemd-journal group)."""
out = run(["journalctl", "-k", "-q", "--no-pager", "-o", "short-iso",
"--since", f"@{int(ts)}"]).stdout
return [l for l in out.splitlines()
if re.search(r"out of memory|oom-kill|killed process", l, re.I)][:10]
def container_restarts():
"""{container id: [name, restart count, status]} for every container."""
ids = run(["docker", "ps", "-aq", "--no-trunc"]).stdout.split()
if not ids:
return {}
out = run(["docker", "inspect", "-f",
"{{.Id}}\t{{.Name}}\t{{.RestartCount}}\t{{.State.Status}}", *ids]).stdout
result = {}
for line in out.splitlines():
parts = line.split("\t")
if len(parts) == 4:
result[parts[0]] = [parts[1].lstrip("/"), int(parts[2]), parts[3]]
return result
def main():
args = json.loads(sys.argv[1]) if len(sys.argv) > 1 else {}
snap = {"at": time.time()}
def attempt(key, fn):
try:
snap[key] = fn()
except Exception as e: # one blind spot must not blind the rest
snap[key + "_error"] = f"{type(e).__name__}: {e}"[:400]
if args.get("kuma_volume"):
attempt("kuma", lambda: kuma(args))
if "kuma" in snap:
snap["kuma"], snap["events"] = snap["kuma"]
du = shutil.disk_usage("/")
snap["disk"] = {"pct": round(100 * du.used / du.total, 1), "free_gb": du.free // 2**30}
attempt("mem", meminfo_mb)
attempt("btime", boot_time)
attempt("reboot", reboot_required)
attempt("ooms", lambda: oom_kills_since(args.get("oom_since") or time.time()))
attempt("containers", container_restarts)
print(json.dumps(snap))
if __name__ == "__main__":
main()